cindex-dump.py 2.7 KB

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