xref: /openbsd-src/gnu/llvm/clang/bindings/python/examples/cindex/cindex-includes.py (revision e5dd70708596ae51455a0ffa086a00c5b29f8583)
1*e5dd7070Spatrick#!/usr/bin/env python
2*e5dd7070Spatrick
3*e5dd7070Spatrick#===- cindex-includes.py - cindex/Python Inclusion Graph -----*- python -*--===#
4*e5dd7070Spatrick#
5*e5dd7070Spatrick# Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
6*e5dd7070Spatrick# See https://llvm.org/LICENSE.txt for license information.
7*e5dd7070Spatrick# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
8*e5dd7070Spatrick#
9*e5dd7070Spatrick#===------------------------------------------------------------------------===#
10*e5dd7070Spatrick
11*e5dd7070Spatrick"""
12*e5dd7070SpatrickA simple command line tool for dumping a Graphviz description (dot) that
13*e5dd7070Spatrickdescribes include dependencies.
14*e5dd7070Spatrick"""
15*e5dd7070Spatrick
16*e5dd7070Spatrickdef main():
17*e5dd7070Spatrick    import sys
18*e5dd7070Spatrick    from clang.cindex import Index
19*e5dd7070Spatrick
20*e5dd7070Spatrick    from optparse import OptionParser, OptionGroup
21*e5dd7070Spatrick
22*e5dd7070Spatrick    parser = OptionParser("usage: %prog [options] {filename} [clang-args*]")
23*e5dd7070Spatrick    parser.disable_interspersed_args()
24*e5dd7070Spatrick    (opts, args) = parser.parse_args()
25*e5dd7070Spatrick    if len(args) == 0:
26*e5dd7070Spatrick        parser.error('invalid number arguments')
27*e5dd7070Spatrick
28*e5dd7070Spatrick    # FIXME: Add an output file option
29*e5dd7070Spatrick    out = sys.stdout
30*e5dd7070Spatrick
31*e5dd7070Spatrick    index = Index.create()
32*e5dd7070Spatrick    tu = index.parse(None, args)
33*e5dd7070Spatrick    if not tu:
34*e5dd7070Spatrick        parser.error("unable to load input")
35*e5dd7070Spatrick
36*e5dd7070Spatrick    # A helper function for generating the node name.
37*e5dd7070Spatrick    def name(f):
38*e5dd7070Spatrick        if f:
39*e5dd7070Spatrick            return "\"" + f.name + "\""
40*e5dd7070Spatrick
41*e5dd7070Spatrick    # Generate the include graph
42*e5dd7070Spatrick    out.write("digraph G {\n")
43*e5dd7070Spatrick    for i in tu.get_includes():
44*e5dd7070Spatrick        line = "  ";
45*e5dd7070Spatrick        if i.is_input_file:
46*e5dd7070Spatrick            # Always write the input file as a node just in case it doesn't
47*e5dd7070Spatrick            # actually include anything. This would generate a 1 node graph.
48*e5dd7070Spatrick            line += name(i.include)
49*e5dd7070Spatrick        else:
50*e5dd7070Spatrick            line += '%s->%s' % (name(i.source), name(i.include))
51*e5dd7070Spatrick        line += "\n";
52*e5dd7070Spatrick        out.write(line)
53*e5dd7070Spatrick    out.write("}\n")
54*e5dd7070Spatrick
55*e5dd7070Spatrickif __name__ == '__main__':
56*e5dd7070Spatrick    main()
57*e5dd7070Spatrick
58