xref: /llvm-project/clang/bindings/python/tests/cindex/util.py (revision 71cfa381ef8c4fe659c67e8b2901d767e10f2aff)
1# This file provides common utility functions for the test suite.
2
3from clang.cindex import Cursor, TranslationUnit
4
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, source)])
31
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
51
52def get_cursors(source, spelling):
53    """Obtain all cursors from a source object with a specific spelling.
54
55    This provides a convenient search mechanism to find all cursors with
56    specific spelling within a source. The first argument can be either a
57    TranslationUnit or Cursor instance.
58
59    If no cursors are found, an empty list is returned.
60    """
61    # Convenience for calling on a TU.
62    root_cursor = source if isinstance(source, Cursor) else source.cursor
63
64    cursors = []
65    for cursor in root_cursor.walk_preorder():
66        if cursor.spelling == spelling:
67            cursors.append(cursor)
68
69    return cursors
70
71
72__all__ = [
73    "get_cursor",
74    "get_cursors",
75    "get_tu",
76]
77