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