libClang cannot get the string data of many types of AST nodes

Hi, I am using libclang to parse C source code into AST nodes. When I try get the string of the nodes, it doesn’t work for many types of nodes, like statements, expressions, it only works for function declarations and variable declarations.

Below are my sample code:
enum CXCursorKind kind = clang_getCursorKind(cursor);
switch (kind) {
case CXCursor_FunctionDecl:
CXString funcDeclStr = clang_getCursorSpelling(cursor);
const char* funcStr = clang_getCString(funcDeclStr);
printf(“%s\n”, funcStr);
case CXCursor_WhileStmt:
CXString whileStmtStr = clang_getCursorSpelling(cursor);
const char* whileStr = clang_getCString(whileStmtStr);
printf(“%s\n”, whileStr);

When it comes to function declaration, the string of the function name can be successfully printed. But for while statements, it couldn’t print out anything. I wonder if I used libclang incorrectly or if libclang doesn’t support getting the string of statements or expressions.

libclang only supports getting a string form of some kinds of statements and expressions. For example, we will give you a spelling for a label statement or a string literal expression, but not many other kinds of AST nodes. is the implementation of that function, so you can see what kinds of cursors we currently can get spellings for. This would be the area of code you’d need to modify if you wanted to propose adding support for additional cursors.

Thank you Aaron for clearing my confusion.

1 Like