Debian Codegraph @

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

raw
1 import os
2
3 from clang.cindex import (
4 Cursor,
5 CursorKind,
6 File,
7 Index,
8 SourceLocation,
9 SourceRange,
10 TranslationUnit,
11 TranslationUnitLoadError,
12 TranslationUnitSaveError,
13 )
14
15
16 import gc
17 import tempfile
18 import unittest
19 from contextlib import contextmanager
20 from pathlib import Path
21
22 from .util import get_cursor, get_tu
23
24 INPUTS_DIR = os.path.join(os.path.dirname(__file__), "INPUTS")
25
26
27 @contextmanager
28 def save_tu(tu):
29 """Convenience API to save a TranslationUnit to a file.
30
31 Returns the filename it was saved to.
32 """
33 with tempfile.NamedTemporaryFile() as t:
34 tu.save(t.name)
35 yield t.name
36
37
38 @contextmanager
39 def save_tu_pathlike(tu):
40 """Convenience API to save a TranslationUnit to a file.
41
42 Returns the filename it was saved to.
43 """
44 with tempfile.NamedTemporaryFile() as t:
45 tu.save(Path(t.name))
46 yield t.name
47
48
49 class TestTranslationUnit(unittest.TestCase):
50 def test_spelling(self):
51 path = os.path.join(INPUTS_DIR, "hello.cpp")
52 tu = TranslationUnit.from_source(path)
53 self.assertEqual(tu.spelling, path)
54
55 def test_cursor(self):
56 path = os.path.join(INPUTS_DIR, "hello.cpp")
57 tu = get_tu(path)
58 c = tu.cursor
59 self.assertIsInstance(c, Cursor)
60 self.assertIs(c.kind, CursorKind.TRANSLATION_UNIT)
61
62 def test_parse_arguments(self):
63 path = os.path.join(INPUTS_DIR, "parse_arguments.c")
64 tu = TranslationUnit.from_source(path, ["-DDECL_ONE=hello", "-DDECL_TWO=hi"])
65 spellings = [c.spelling for c in tu.cursor.get_children()]
66 self.assertEqual(spellings[-2], "hello")
67 self.assertEqual(spellings[-1], "hi")
68
69 def test_reparse_arguments(self):
70 path = os.path.join(INPUTS_DIR, "parse_arguments.c")
71 tu = TranslationUnit.from_source(path, ["-DDECL_ONE=hello", "-DDECL_TWO=hi"])
72 tu.reparse()
73 spellings = [c.spelling for c in tu.cursor.get_children()]
74 self.assertEqual(spellings[-2], "hello")
75 self.assertEqual(spellings[-1], "hi")
76
77 def test_unsaved_files(self):
78 tu = TranslationUnit.from_source(
79 "fake.c",
80 ["-I./"],
81 unsaved_files=[
82 (
83 "fake.c",
84 """
85 #include "fake.h"
86 int x;
87 int SOME_DEFINE;
88 """,
89 ),
90 (
91 "./fake.h",
92 """
93 #define SOME_DEFINE y
94 """,
95 ),
96 ],
97 )
98 spellings = [c.spelling for c in tu.cursor.get_children()]
99 self.assertEqual(spellings[-2], "x")
100 self.assertEqual(spellings[-1], "y")
101
102 def test_unsaved_files_2(self):
103 from io import StringIO
104
105 tu = TranslationUnit.from_source(
106 "fake.c", unsaved_files=[("fake.c", StringIO("int x;"))]
107 )
108 spellings = [c.spelling for c in tu.cursor.get_children()]
109 self.assertEqual(spellings[-1], "x")
110
111 def test_from_source_accepts_pathlike(self):
112 tu = TranslationUnit.from_source(
113 Path("fake.c"),
114 ["-Iincludes"],
115 unsaved_files=[
116 (
117 Path("fake.c"),
118 """
119 #include "fake.h"
120 int x;
121 int SOME_DEFINE;
122 """,
123 ),
124 (
125 Path("includes/fake.h"),
126 """
127 #define SOME_DEFINE y
128 """,
129 ),
130 ],
131 )
132 spellings = [c.spelling for c in tu.cursor.get_children()]
133 self.assertEqual(spellings[-2], "x")
134 self.assertEqual(spellings[-1], "y")
135
136 def assert_normpaths_equal(self, path1, path2):
137 """Compares two paths for equality after normalizing them with
138 os.path.normpath
139 """
140 self.assertEqual(os.path.normpath(path1), os.path.normpath(path2))
141
142 def test_includes(self):
143 def eq(expected, actual):
144 if not actual.is_input_file:
145 self.assert_normpaths_equal(expected[0], actual.source.name)
146 self.assert_normpaths_equal(expected[1], actual.include.name)
147 else:
148 self.assert_normpaths_equal(expected[1], actual.include.name)
149
150 src = os.path.join(INPUTS_DIR, "include.cpp")
151 h1 = os.path.join(INPUTS_DIR, "header1.h")
152 h2 = os.path.join(INPUTS_DIR, "header2.h")
153 h3 = os.path.join(INPUTS_DIR, "header3.h")
154 inc = [(src, h1), (h1, h3), (src, h2), (h2, h3)]
155
156 tu = TranslationUnit.from_source(src)
157 for i in zip(inc, tu.get_includes()):
158 eq(i[0], i[1])
159
160 def test_inclusion_directive(self):
161 src = os.path.join(INPUTS_DIR, "include.cpp")
162 h1 = os.path.join(INPUTS_DIR, "header1.h")
163 h2 = os.path.join(INPUTS_DIR, "header2.h")
164 h3 = os.path.join(INPUTS_DIR, "header3.h")
165 inc = [h1, h3, h2, h3, h1]
166
167 tu = TranslationUnit.from_source(
168 src, options=TranslationUnit.PARSE_DETAILED_PROCESSING_RECORD
169 )
170 inclusion_directive_files = [
171 c.get_included_file().name
172 for c in tu.cursor.get_children()
173 if c.kind == CursorKind.INCLUSION_DIRECTIVE
174 ]
175 for i in zip(inc, inclusion_directive_files):
176 self.assert_normpaths_equal(i[0], i[1])
177
178 def test_save(self):
179 """Ensure TranslationUnit.save() works."""
180
181 tu = get_tu("int foo();")
182
183 with save_tu(tu) as path:
184 self.assertTrue(os.path.exists(path))
185 self.assertGreater(os.path.getsize(path), 0)
186
187 def test_save_pathlike(self):
188 """Ensure TranslationUnit.save() works with PathLike filename."""
189
190 tu = get_tu("int foo();")
191
192 with save_tu_pathlike(tu) as path:
193 self.assertTrue(os.path.exists(path))
194 self.assertGreater(os.path.getsize(path), 0)
195
196 def test_save_translation_errors(self):
197 """Ensure that saving to an invalid directory raises."""
198
199 tu = get_tu("int foo();")
200
201 path = "/does/not/exist/llvm-test.ast"
202 self.assertFalse(os.path.exists(os.path.dirname(path)))
203
204 with self.assertRaises(TranslationUnitSaveError) as cm:
205 tu.save(path)
206 ex = cm.exception
207 expected = TranslationUnitSaveError.ERROR_UNKNOWN
208 self.assertEqual(ex.save_error, expected)
209
210 def test_load(self):
211 """Ensure TranslationUnits can be constructed from saved files."""
212
213 tu = get_tu("int foo();")
214 self.assertEqual(len(tu.diagnostics), 0)
215 with save_tu(tu) as path:
216 self.assertTrue(os.path.exists(path))
217 self.assertGreater(os.path.getsize(path), 0)
218
219 tu2 = TranslationUnit.from_ast_file(filename=path)
220 self.assertEqual(len(tu2.diagnostics), 0)
221
222 foo = get_cursor(tu2, "foo")
223 self.assertIsNotNone(foo)
224
225 # Just in case there is an open file descriptor somewhere.
226 del tu2
227
228 def test_load_pathlike(self):
229 """Ensure TranslationUnits can be constructed from saved files -
230 PathLike variant."""
231 tu = get_tu("int foo();")
232 self.assertEqual(len(tu.diagnostics), 0)
233 with save_tu(tu) as path:
234 tu2 = TranslationUnit.from_ast_file(filename=Path(path))
235 self.assertEqual(len(tu2.diagnostics), 0)
236
237 foo = get_cursor(tu2, "foo")
238 self.assertIsNotNone(foo)
239
240 # Just in case there is an open file descriptor somewhere.
241 del tu2
242
243 def test_index_parse(self):
244 path = os.path.join(INPUTS_DIR, "hello.cpp")
245 index = Index.create()
246 tu = index.parse(path)
247 self.assertIsInstance(tu, TranslationUnit)
248
249 def test_get_file(self):
250 """Ensure tu.get_file() works appropriately."""
251
252 tu = get_tu("int foo();")
253
254 f = tu.get_file("t.c")
255 self.assertIsInstance(f, File)
256 self.assertEqual(f.name, "t.c")
257
258 with self.assertRaises(Exception):
259 f = tu.get_file("foobar.cpp")
260
261 def test_get_file_pathlike(self):
262 """Ensure tu.get_file() works appropriately with PathLike filenames."""
263
264 tu = get_tu("int foo();")
265
266 f = tu.get_file(Path("t.c"))
267 self.assertIsInstance(f, File)
268 self.assertEqual(f.name, "t.c")
269
270 with self.assertRaises(Exception):
271 f = tu.get_file(Path("foobar.cpp"))
272
273 def test_get_source_location(self):
274 """Ensure tu.get_source_location() works."""
275
276 tu = get_tu("int foo();")
277
278 location = tu.get_location("t.c", 2)
279 self.assertIsInstance(location, SourceLocation)
280 self.assertEqual(location.offset, 2)
281 self.assertEqual(location.file.name, "t.c")
282
283 location = tu.get_location("t.c", (1, 3))
284 self.assertIsInstance(location, SourceLocation)
285 self.assertEqual(location.line, 1)
286 self.assertEqual(location.column, 3)
287 self.assertEqual(location.file.name, "t.c")
288
289 def test_get_source_range(self):
290 """Ensure tu.get_source_range() works."""
291
292 tu = get_tu("int foo();")
293
294 r = tu.get_extent("t.c", (1, 4))
295 self.assertIsInstance(r, SourceRange)
296 self.assertEqual(r.start.offset, 1)
297 self.assertEqual(r.end.offset, 4)
298 self.assertEqual(r.start.file.name, "t.c")
299 self.assertEqual(r.end.file.name, "t.c")
300
301 r = tu.get_extent("t.c", ((1, 2), (1, 3)))
302 self.assertIsInstance(r, SourceRange)
303 self.assertEqual(r.start.line, 1)
304 self.assertEqual(r.start.column, 2)
305 self.assertEqual(r.end.line, 1)
306 self.assertEqual(r.end.column, 3)
307 self.assertEqual(r.start.file.name, "t.c")
308 self.assertEqual(r.end.file.name, "t.c")
309
310 start = tu.get_location("t.c", 0)
311 end = tu.get_location("t.c", 5)
312
313 r = tu.get_extent("t.c", (start, end))
314 self.assertIsInstance(r, SourceRange)
315 self.assertEqual(r.start.offset, 0)
316 self.assertEqual(r.end.offset, 5)
317 self.assertEqual(r.start.file.name, "t.c")
318 self.assertEqual(r.end.file.name, "t.c")
319
320 def test_get_tokens_gc(self):
321 """Ensures get_tokens() works properly with garbage collection."""
322
323 tu = get_tu("int foo();")
324 r = tu.get_extent("t.c", (0, 10))
325 tokens = list(tu.get_tokens(extent=r))
326
327 self.assertEqual(tokens[0].spelling, "int")
328 gc.collect()
329 self.assertEqual(tokens[0].spelling, "int")
330
331 del tokens[1]
332 gc.collect()
333 self.assertEqual(tokens[0].spelling, "int")
334
335 # May trigger segfault if we don't do our job properly.
336 del tokens
337 gc.collect()
338 gc.collect() # Just in case.
339
340 def test_fail_from_source(self):
341 path = os.path.join(INPUTS_DIR, "non-existent.cpp")
342 try:
343 tu = TranslationUnit.from_source(path)
344 except TranslationUnitLoadError:
345 tu = None
346 self.assertEqual(tu, None)
347
348 def test_fail_from_ast_file(self):
349 path = os.path.join(INPUTS_DIR, "non-existent.ast")
350 try:
351 tu = TranslationUnit.from_ast_file(path)
352 except TranslationUnitLoadError:
353 tu = None
354 self.assertEqual(tu, None)