• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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):
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    args = []
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    children = []
43    if isinstance(source, Cursor):
44        children = source.get_children()
45    else:
46        # Assume TU
47        children = source.cursor.get_children()
48
49    for cursor in children:
50        if cursor.spelling == spelling:
51            return cursor
52
53        # Recurse into children.
54        result = get_cursor(cursor, spelling)
55        if result is not None:
56            return result
57
58    return None
59
60def get_cursors(source, spelling):
61    """Obtain all cursors from a source object with a specific spelling.
62
63    This provides a convenient search mechanism to find all cursors with specific
64    spelling within a source. The first argument can be either a
65    TranslationUnit or Cursor instance.
66
67    If no cursors are found, an empty list is returned.
68    """
69    cursors = []
70    children = []
71    if isinstance(source, Cursor):
72        children = source.get_children()
73    else:
74        # Assume TU
75        children = source.cursor.get_children()
76
77    for cursor in children:
78        if cursor.spelling == spelling:
79            cursors.append(cursor)
80
81        # Recurse into children.
82        cursors.extend(get_cursors(cursor, spelling))
83
84    return cursors
85
86
87
88
89__all__ = [
90    'get_cursor',
91    'get_cursors',
92    'get_tu',
93]
94