summaryrefslogtreecommitdiff
path: root/clang/bindings/python/tests/cindex/util.py
blob: 388b269489982d76ca12aa00bec6e5a1177977ef (about) (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# This file provides common utility functions for the test suite.

from clang.cindex import Cursor
from clang.cindex import Index

def get_tu(source, lang='c', all_warnings=False):
    """Obtain a translation unit from source and language.

    By default, the translation unit is created from source file "t.<ext>"
    where <ext> is the default file extension for the specified language. By
    default it is C, so "t.c" is the default file name.

    Supported languages are {c, cpp, objc}.

    all_warnings is a convenience argument to enable all compiler warnings.
    """
    name = 't.c'
    if lang == 'cpp':
        name = 't.cpp'
    elif lang == 'objc':
        name = 't.m'
    elif lang != 'c':
        raise Exception('Unknown language: %s' % lang)

    args = []
    if all_warnings:
        args = ['-Wall', '-Wextra']

    index = Index.create()
    tu = index.parse(name, args=args, unsaved_files=[(name, source)])
    assert tu is not None
    return tu

def get_cursor(source, spelling):
    """Obtain a cursor from a source object.

    This provides a convenient search mechanism to find a cursor with specific
    spelling within a source. The first argument can be either a
    TranslationUnit or Cursor instance.

    If the cursor is not found, None is returned.
    """
    children = []
    if isinstance(source, Cursor):
        children = source.get_children()
    else:
        # Assume TU
        children = source.cursor.get_children()

    for cursor in children:
        if cursor.spelling == spelling:
            return cursor

        # Recurse into children.
        result = get_cursor(cursor, spelling)
        if result is not None:
            return result

    return None


__all__ = [
    'get_cursor',
    'get_tu',
]