util.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. # This file provides common utility functions for the test suite.
  2. from clang.cindex import Cursor
  3. from clang.cindex import TranslationUnit
  4. def get_tu(source, lang='c', all_warnings=False, flags=[]):
  5. """Obtain a translation unit from source and language.
  6. By default, the translation unit is created from source file "t.<ext>"
  7. where <ext> is the default file extension for the specified language. By
  8. default it is C, so "t.c" is the default file name.
  9. Supported languages are {c, cpp, objc}.
  10. all_warnings is a convenience argument to enable all compiler warnings.
  11. """
  12. args = list(flags)
  13. name = 't.c'
  14. if lang == 'cpp':
  15. name = 't.cpp'
  16. args.append('-std=c++11')
  17. elif lang == 'objc':
  18. name = 't.m'
  19. elif lang != 'c':
  20. raise Exception('Unknown language: %s' % lang)
  21. if all_warnings:
  22. args += ['-Wall', '-Wextra']
  23. return TranslationUnit.from_source(name, args, unsaved_files=[(name,
  24. source)])
  25. def get_cursor(source, spelling):
  26. """Obtain a cursor from a source object.
  27. This provides a convenient search mechanism to find a cursor with specific
  28. spelling within a source. The first argument can be either a
  29. TranslationUnit or Cursor instance.
  30. If the cursor is not found, None is returned.
  31. """
  32. # Convenience for calling on a TU.
  33. root_cursor = source if isinstance(source, Cursor) else source.cursor
  34. for cursor in root_cursor.walk_preorder():
  35. if cursor.spelling == spelling:
  36. return cursor
  37. return None
  38. def get_cursors(source, spelling):
  39. """Obtain all cursors from a source object with a specific spelling.
  40. This provides a convenient search mechanism to find all cursors with
  41. specific spelling within a source. The first argument can be either a
  42. TranslationUnit or Cursor instance.
  43. If no cursors are found, an empty list is returned.
  44. """
  45. # Convenience for calling on a TU.
  46. root_cursor = source if isinstance(source, Cursor) else source.cursor
  47. cursors = []
  48. for cursor in root_cursor.walk_preorder():
  49. if cursor.spelling == spelling:
  50. cursors.append(cursor)
  51. return cursors
  52. __all__ = [
  53. 'get_cursor',
  54. 'get_cursors',
  55. 'get_tu',
  56. ]