1# This file provides common utility functions for the test suite. 2 3from clang.cindex import Cursor 4from clang.cindex import TranslationUnit 5 6def get_tu(source, lang='c', all_warnings=False, flags=[]): 7 """Obtain a translation unit from source and language. 8 9 By default, the translation unit is created from source file "t.<ext>" 10 where <ext> is the default file extension for the specified language. By 11 default it is C, so "t.c" is the default file name. 12 13 Supported languages are {c, cpp, objc}. 14 15 all_warnings is a convenience argument to enable all compiler warnings. 16 """ 17 args = list(flags) 18 name = 't.c' 19 if lang == 'cpp': 20 name = 't.cpp' 21 args.append('-std=c++11') 22 elif lang == 'objc': 23 name = 't.m' 24 elif lang != 'c': 25 raise Exception('Unknown language: %s' % lang) 26 27 if all_warnings: 28 args += ['-Wall', '-Wextra'] 29 30 return TranslationUnit.from_source(name, args, unsaved_files=[(name, 31 source)]) 32 33def get_cursor(source, spelling): 34 """Obtain a cursor from a source object. 35 36 This provides a convenient search mechanism to find a cursor with specific 37 spelling within a source. The first argument can be either a 38 TranslationUnit or Cursor instance. 39 40 If the cursor is not found, None is returned. 41 """ 42 # Convenience for calling on a TU. 43 root_cursor = source if isinstance(source, Cursor) else source.cursor 44 45 for cursor in root_cursor.walk_preorder(): 46 if cursor.spelling == spelling: 47 return cursor 48 49 return None 50 51def get_cursors(source, spelling): 52 """Obtain all cursors from a source object with a specific spelling. 53 54 This provides a convenient search mechanism to find all cursors with 55 specific spelling within a source. The first argument can be either a 56 TranslationUnit or Cursor instance. 57 58 If no cursors are found, an empty list is returned. 59 """ 60 # Convenience for calling on a TU. 61 root_cursor = source if isinstance(source, Cursor) else source.cursor 62 63 cursors = [] 64 for cursor in root_cursor.walk_preorder(): 65 if cursor.spelling == spelling: 66 cursors.append(cursor) 67 68 return cursors 69 70 71__all__ = [ 72 'get_cursor', 73 'get_cursors', 74 'get_tu', 75] 76