I’m trying to use libclang from python to traverse the AST for the following snippet of C:
//simple.c
bool LED0 = 0; /* state0 */
bool LED1 = 0; /* state1 */
bool LED2 = 1; /* state2 */
/* inputs */
bool a0,a1,a2;
I’m using the following Python code to parse this C code:
import sys
import clang.cindex
var_decls = []
function_decls = []
def printnode(node):
print(f"Found : {node.displayname} type: {node.kind} [line={node.location.line}]")
def traverse(node):
for child in node.get_children():
traverse(child)
if node.kind == clang.cindex.CursorKind.DECL_STMT:
print("DECL_STMT")
printnode(node)
if node.kind == clang.cindex.CursorKind.VAR_DECL:
var_decls.append(node)
printnode(node)
if node.kind == clang.cindex.CursorKind.FUNCTION_DECL:
function_decls.append(node)
index = clang.cindex.Index.create()
translation_unit = index.parse("simple.c")
traverse(translation_unit.cursor)
When I run this python script I get this output:
Found : LED0 type: CursorKind.VAR_DECL [line=3]
Found : LED1 type: CursorKind.VAR_DECL [line=4]
Found : LED2 type: CursorKind.VAR_DECL [line=5]
Found : a0 type: CursorKind.VAR_DECL [line=9]
The problem here is that only a0 from the declaration bool a0,a1,a2;
was found. No a1 or a2 declarations. How does one get the a1 and a2 declarations from the AST?
(NOTE: there was an older post entitled: “clang ast visitor for single line multiple variable declaration” which suggested that you needed to check for a CursorKind DECL_STMT, but as you can see from the output above, that kind of node was never observed)