Home | History | Annotate | Download | only in cindex
      1 # This file provides common utility functions for the test suite.
      2 
      3 from clang.cindex import Cursor
      4 from clang.cindex import Index
      5 
      6 def get_tu(source, lang='c', all_warnings=False):
      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     name = 't.c'
     18     if lang == 'cpp':
     19         name = 't.cpp'
     20     elif lang == 'objc':
     21         name = 't.m'
     22     elif lang != 'c':
     23         raise Exception('Unknown language: %s' % lang)
     24 
     25     args = []
     26     if all_warnings:
     27         args = ['-Wall', '-Wextra']
     28 
     29     index = Index.create()
     30     tu = index.parse(name, args=args, unsaved_files=[(name, source)])
     31     assert tu is not None
     32     return tu
     33 
     34 def get_cursor(source, spelling):
     35     """Obtain a cursor from a source object.
     36 
     37     This provides a convenient search mechanism to find a cursor with specific
     38     spelling within a source. The first argument can be either a
     39     TranslationUnit or Cursor instance.
     40 
     41     If the cursor is not found, None is returned.
     42     """
     43     children = []
     44     if isinstance(source, Cursor):
     45         children = source.get_children()
     46     else:
     47         # Assume TU
     48         children = source.cursor.get_children()
     49 
     50     for cursor in children:
     51         if cursor.spelling == spelling:
     52             return cursor
     53 
     54         # Recurse into children.
     55         result = get_cursor(cursor, spelling)
     56         if result is not None:
     57             return result
     58 
     59     return None
     60 
     61 
     62 __all__ = [
     63     'get_cursor',
     64     'get_tu',
     65 ]
     66