test_translation_unit.py 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  1. import gc
  2. import os
  3. import tempfile
  4. from clang.cindex import CursorKind
  5. from clang.cindex import Cursor
  6. from clang.cindex import File
  7. from clang.cindex import Index
  8. from clang.cindex import SourceLocation
  9. from clang.cindex import SourceRange
  10. from clang.cindex import TranslationUnitSaveError
  11. from clang.cindex import TranslationUnitLoadError
  12. from clang.cindex import TranslationUnit
  13. from .util import get_cursor
  14. from .util import get_tu
  15. kInputsDir = os.path.join(os.path.dirname(__file__), 'INPUTS')
  16. def test_spelling():
  17. path = os.path.join(kInputsDir, 'hello.cpp')
  18. tu = TranslationUnit.from_source(path)
  19. assert tu.spelling == path
  20. def test_cursor():
  21. path = os.path.join(kInputsDir, 'hello.cpp')
  22. tu = get_tu(path)
  23. c = tu.cursor
  24. assert isinstance(c, Cursor)
  25. assert c.kind is CursorKind.TRANSLATION_UNIT
  26. def test_parse_arguments():
  27. path = os.path.join(kInputsDir, 'parse_arguments.c')
  28. tu = TranslationUnit.from_source(path, ['-DDECL_ONE=hello', '-DDECL_TWO=hi'])
  29. spellings = [c.spelling for c in tu.cursor.get_children()]
  30. assert spellings[-2] == 'hello'
  31. assert spellings[-1] == 'hi'
  32. def test_reparse_arguments():
  33. path = os.path.join(kInputsDir, 'parse_arguments.c')
  34. tu = TranslationUnit.from_source(path, ['-DDECL_ONE=hello', '-DDECL_TWO=hi'])
  35. tu.reparse()
  36. spellings = [c.spelling for c in tu.cursor.get_children()]
  37. assert spellings[-2] == 'hello'
  38. assert spellings[-1] == 'hi'
  39. def test_unsaved_files():
  40. tu = TranslationUnit.from_source('fake.c', ['-I./'], unsaved_files = [
  41. ('fake.c', """
  42. #include "fake.h"
  43. int x;
  44. int SOME_DEFINE;
  45. """),
  46. ('./fake.h', """
  47. #define SOME_DEFINE y
  48. """)
  49. ])
  50. spellings = [c.spelling for c in tu.cursor.get_children()]
  51. assert spellings[-2] == 'x'
  52. assert spellings[-1] == 'y'
  53. def test_unsaved_files_2():
  54. import StringIO
  55. tu = TranslationUnit.from_source('fake.c', unsaved_files = [
  56. ('fake.c', StringIO.StringIO('int x;'))])
  57. spellings = [c.spelling for c in tu.cursor.get_children()]
  58. assert spellings[-1] == 'x'
  59. def normpaths_equal(path1, path2):
  60. """ Compares two paths for equality after normalizing them with
  61. os.path.normpath
  62. """
  63. return os.path.normpath(path1) == os.path.normpath(path2)
  64. def test_includes():
  65. def eq(expected, actual):
  66. if not actual.is_input_file:
  67. return normpaths_equal(expected[0], actual.source.name) and \
  68. normpaths_equal(expected[1], actual.include.name)
  69. else:
  70. return normpaths_equal(expected[1], actual.include.name)
  71. src = os.path.join(kInputsDir, 'include.cpp')
  72. h1 = os.path.join(kInputsDir, "header1.h")
  73. h2 = os.path.join(kInputsDir, "header2.h")
  74. h3 = os.path.join(kInputsDir, "header3.h")
  75. inc = [(src, h1), (h1, h3), (src, h2), (h2, h3)]
  76. tu = TranslationUnit.from_source(src)
  77. for i in zip(inc, tu.get_includes()):
  78. assert eq(i[0], i[1])
  79. def save_tu(tu):
  80. """Convenience API to save a TranslationUnit to a file.
  81. Returns the filename it was saved to.
  82. """
  83. _, path = tempfile.mkstemp()
  84. tu.save(path)
  85. return path
  86. def test_save():
  87. """Ensure TranslationUnit.save() works."""
  88. tu = get_tu('int foo();')
  89. path = save_tu(tu)
  90. assert os.path.exists(path)
  91. assert os.path.getsize(path) > 0
  92. os.unlink(path)
  93. def test_save_translation_errors():
  94. """Ensure that saving to an invalid directory raises."""
  95. tu = get_tu('int foo();')
  96. path = '/does/not/exist/llvm-test.ast'
  97. assert not os.path.exists(os.path.dirname(path))
  98. try:
  99. tu.save(path)
  100. assert False
  101. except TranslationUnitSaveError as ex:
  102. expected = TranslationUnitSaveError.ERROR_UNKNOWN
  103. assert ex.save_error == expected
  104. def test_load():
  105. """Ensure TranslationUnits can be constructed from saved files."""
  106. tu = get_tu('int foo();')
  107. assert len(tu.diagnostics) == 0
  108. path = save_tu(tu)
  109. assert os.path.exists(path)
  110. assert os.path.getsize(path) > 0
  111. tu2 = TranslationUnit.from_ast_file(filename=path)
  112. assert len(tu2.diagnostics) == 0
  113. foo = get_cursor(tu2, 'foo')
  114. assert foo is not None
  115. # Just in case there is an open file descriptor somewhere.
  116. del tu2
  117. os.unlink(path)
  118. def test_index_parse():
  119. path = os.path.join(kInputsDir, 'hello.cpp')
  120. index = Index.create()
  121. tu = index.parse(path)
  122. assert isinstance(tu, TranslationUnit)
  123. def test_get_file():
  124. """Ensure tu.get_file() works appropriately."""
  125. tu = get_tu('int foo();')
  126. f = tu.get_file('t.c')
  127. assert isinstance(f, File)
  128. assert f.name == 't.c'
  129. try:
  130. f = tu.get_file('foobar.cpp')
  131. except:
  132. pass
  133. else:
  134. assert False
  135. def test_get_source_location():
  136. """Ensure tu.get_source_location() works."""
  137. tu = get_tu('int foo();')
  138. location = tu.get_location('t.c', 2)
  139. assert isinstance(location, SourceLocation)
  140. assert location.offset == 2
  141. assert location.file.name == 't.c'
  142. location = tu.get_location('t.c', (1, 3))
  143. assert isinstance(location, SourceLocation)
  144. assert location.line == 1
  145. assert location.column == 3
  146. assert location.file.name == 't.c'
  147. def test_get_source_range():
  148. """Ensure tu.get_source_range() works."""
  149. tu = get_tu('int foo();')
  150. r = tu.get_extent('t.c', (1,4))
  151. assert isinstance(r, SourceRange)
  152. assert r.start.offset == 1
  153. assert r.end.offset == 4
  154. assert r.start.file.name == 't.c'
  155. assert r.end.file.name == 't.c'
  156. r = tu.get_extent('t.c', ((1,2), (1,3)))
  157. assert isinstance(r, SourceRange)
  158. assert r.start.line == 1
  159. assert r.start.column == 2
  160. assert r.end.line == 1
  161. assert r.end.column == 3
  162. assert r.start.file.name == 't.c'
  163. assert r.end.file.name == 't.c'
  164. start = tu.get_location('t.c', 0)
  165. end = tu.get_location('t.c', 5)
  166. r = tu.get_extent('t.c', (start, end))
  167. assert isinstance(r, SourceRange)
  168. assert r.start.offset == 0
  169. assert r.end.offset == 5
  170. assert r.start.file.name == 't.c'
  171. assert r.end.file.name == 't.c'
  172. def test_get_tokens_gc():
  173. """Ensures get_tokens() works properly with garbage collection."""
  174. tu = get_tu('int foo();')
  175. r = tu.get_extent('t.c', (0, 10))
  176. tokens = list(tu.get_tokens(extent=r))
  177. assert tokens[0].spelling == 'int'
  178. gc.collect()
  179. assert tokens[0].spelling == 'int'
  180. del tokens[1]
  181. gc.collect()
  182. assert tokens[0].spelling == 'int'
  183. # May trigger segfault if we don't do our job properly.
  184. del tokens
  185. gc.collect()
  186. gc.collect() # Just in case.
  187. def test_fail_from_source():
  188. path = os.path.join(kInputsDir, 'non-existent.cpp')
  189. try:
  190. tu = TranslationUnit.from_source(path)
  191. except TranslationUnitLoadError:
  192. tu = None
  193. assert tu == None
  194. def test_fail_from_ast_file():
  195. path = os.path.join(kInputsDir, 'non-existent.ast')
  196. try:
  197. tu = TranslationUnit.from_ast_file(path)
  198. except TranslationUnitLoadError:
  199. tu = None
  200. assert tu == None