cindex-dump.py 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. #!/usr/bin/env python
  2. #===- cindex-dump.py - cindex/Python Source Dump -------------*- python -*--===#
  3. #
  4. # Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  5. # See https://llvm.org/LICENSE.txt for license information.
  6. # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  7. #
  8. #===------------------------------------------------------------------------===#
  9. """
  10. A simple command line tool for dumping a source file using the Clang Index
  11. Library.
  12. """
  13. def get_diag_info(diag):
  14. return { 'severity' : diag.severity,
  15. 'location' : diag.location,
  16. 'spelling' : diag.spelling,
  17. 'ranges' : diag.ranges,
  18. 'fixits' : diag.fixits }
  19. def get_cursor_id(cursor, cursor_list = []):
  20. if not opts.showIDs:
  21. return None
  22. if cursor is None:
  23. return None
  24. # FIXME: This is really slow. It would be nice if the index API exposed
  25. # something that let us hash cursors.
  26. for i,c in enumerate(cursor_list):
  27. if cursor == c:
  28. return i
  29. cursor_list.append(cursor)
  30. return len(cursor_list) - 1
  31. def get_info(node, depth=0):
  32. if opts.maxDepth is not None and depth >= opts.maxDepth:
  33. children = None
  34. else:
  35. children = [get_info(c, depth+1)
  36. for c in node.get_children()]
  37. return { 'id' : get_cursor_id(node),
  38. 'kind' : node.kind,
  39. 'usr' : node.get_usr(),
  40. 'spelling' : node.spelling,
  41. 'location' : node.location,
  42. 'extent.start' : node.extent.start,
  43. 'extent.end' : node.extent.end,
  44. 'is_definition' : node.is_definition(),
  45. 'definition id' : get_cursor_id(node.get_definition()),
  46. 'children' : children }
  47. def main():
  48. from clang.cindex import Index
  49. from pprint import pprint
  50. from optparse import OptionParser, OptionGroup
  51. global opts
  52. parser = OptionParser("usage: %prog [options] {filename} [clang-args*]")
  53. parser.add_option("", "--show-ids", dest="showIDs",
  54. help="Compute cursor IDs (very slow)",
  55. action="store_true", default=False)
  56. parser.add_option("", "--max-depth", dest="maxDepth",
  57. help="Limit cursor expansion to depth N",
  58. metavar="N", type=int, default=None)
  59. parser.disable_interspersed_args()
  60. (opts, args) = parser.parse_args()
  61. if len(args) == 0:
  62. parser.error('invalid number arguments')
  63. index = Index.create()
  64. tu = index.parse(None, args)
  65. if not tu:
  66. parser.error("unable to load input")
  67. pprint(('diags', [get_diag_info(d) for d in tu.diagnostics]))
  68. pprint(('nodes', get_info(tu.cursor)))
  69. if __name__ == '__main__':
  70. main()