Debian Codegraph @

clang/bindings/python/tests/cindex/util.py

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