Skip to content

Instantly share code, notes, and snippets.

@novakboskov
Created October 3, 2017 14:57
Show Gist options
  • Save novakboskov/1f110a3a587a74cf9ac8d3346266ea42 to your computer and use it in GitHub Desktop.
Save novakboskov/1f110a3a587a74cf9ac8d3346266ea42 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
""" Usage: <filename> <typename>
Example of C AST introspection using libclang.
Clang version: 5.0.0
Python version: 3.6.2
"""
import sys
import clang.cindex as cc
def errors(tu):
e = any(True for _ in tu.diagnostics)
if e:
print("Errors:")
for diag in tu.diagnostics:
print("{} at {}:{}".format(diag.spelling,
diag.location.line,
diag.location.column))
return e
def introspect(c, typename=None):
if typename and c.type.kind.spelling.lower() == typename or \
not typename:
print('Found {} {} of type {} at {}, {}' \
.format(c.kind, c.spelling, c.type.kind.spelling,
c.location.line, c.location.column))
# Recurse for children of this cursor
for child in c.get_children():
introspect(child, typename)
if __name__ == '__main__':
index = cc.Index.create()
tu = index.parse(sys.argv[1])
if not errors(tu):
introspect(tu.cursor, sys.argv[2])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment