1 # This file provides common utility functions for the test suite.
5 HAS_FSPATH
= hasattr(os
, "fspath")
8 from pathlib
import Path
as str_to_path
14 from clang
.cindex
import Cursor
15 from clang
.cindex
import TranslationUnit
18 def get_tu(source
, lang
="c", all_warnings
=False, flags
=[]):
19 """Obtain a translation unit from source and language.
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.
25 Supported languages are {c, cpp, objc}.
27 all_warnings is a convenience argument to enable all compiler warnings.
33 args
.append("-std=c++11")
37 raise Exception("Unknown language: %s" % lang
)
40 args
+= ["-Wall", "-Wextra"]
42 return TranslationUnit
.from_source(name
, args
, unsaved_files
=[(name
, source
)])
45 def get_cursor(source
, spelling
):
46 """Obtain a cursor from a source object.
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.
52 If the cursor is not found, None is returned.
54 # Convenience for calling on a TU.
55 root_cursor
= source
if isinstance(source
, Cursor
) else source
.cursor
57 for cursor
in root_cursor
.walk_preorder():
58 if cursor
.spelling
== spelling
:
64 def get_cursors(source
, spelling
):
65 """Obtain all cursors from a source object with a specific spelling.
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.
71 If no cursors are found, an empty list is returned.
73 # Convenience for calling on a TU.
74 root_cursor
= source
if isinstance(source
, Cursor
) else source
.cursor
77 for cursor
in root_cursor
.walk_preorder():
78 if cursor
.spelling
== spelling
:
79 cursors
.append(cursor
)
84 skip_if_no_fspath
= unittest
.skipUnless(
85 HAS_FSPATH
, "Requires file system path protocol / Python 3.6+"