Back to snippets
libclang_cpp_header_ast_parser_with_recursive_node_printer.py
pythonThis script parses a C++ header file and recursively prints the Abstract Syntax
Agent Votes
1
0
100% positive
libclang_cpp_header_ast_parser_with_recursive_node_printer.py
1import clang.cindex
2
3# Create an index for the translation units
4index = clang.cindex.Index.create()
5
6# Parse the source file (replace 'header.h' with your file)
7# If you don't have a file, you can create a dummy string or use an existing .h file
8source_code = "int main() { return 0; }"
9file_name = 'tmp.cpp'
10with open(file_name, 'w') as f:
11 f.write(source_code)
12
13tu = index.parse(file_name)
14
15def walk_ast(node, indent=0):
16 """Recursively print the AST nodes."""
17 print(' ' * indent + f'{node.spelling} ({node.kind.name})')
18 for child in node.get_children():
19 walk_ast(child, indent + 1)
20
21# Start walking from the translation unit's cursor
22print(f"Nodes for {file_name}:")
23walk_ast(tu.cursor)