Run DCE after a LoopFlatten test to reduce spurious output [nfc]
[llvm-project.git] / clang / bindings / python / tests / cindex / util.py
blob8ba3114b35d1e1b0c3794249b5b373fc6886cbff
1 # This file provides common utility functions for the test suite.
3 import os
5 HAS_FSPATH = hasattr(os, "fspath")
7 if HAS_FSPATH:
8 from pathlib import Path as str_to_path
9 else:
10 str_to_path = None
12 import unittest
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.
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)
39 if all_warnings:
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.
53 """
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:
59 return cursor
61 return None
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.
72 """
73 # Convenience for calling on a TU.
74 root_cursor = source if isinstance(source, Cursor) else source.cursor
76 cursors = []
77 for cursor in root_cursor.walk_preorder():
78 if cursor.spelling == spelling:
79 cursors.append(cursor)
81 return cursors
84 skip_if_no_fspath = unittest.skipUnless(
85 HAS_FSPATH, "Requires file system path protocol / Python 3.6+"
88 __all__ = [
89 "get_cursor",
90 "get_cursors",
91 "get_tu",
92 "skip_if_no_fspath",
93 "str_to_path",