Dan Grahn
Dan Grahn

Reputation: 9414

Get Clang AST from C/C++ Code with Undeclared Identifiers

I would like to generate an AST from a set of C/C++ code in which I know that there will be missing includes. Here is a sample.

int main() {
    printf("Hello, World!");
}

I've tried doing this with clang -Xclang -ast-dump -fsyntax-only test.cpp. But it stops exporting the AST when it encounters printf.

With Import

#include <stdio.h>
int main() {
    printf("Hello, World!");
}
-FunctionDecl 0x1902628 <test.cpp:3:1, line:5:1> line:3:5 main 'int ()'
 `-CompoundStmt 0x20d6880 <col:12, line:5:1>
    `-CallExpr 0x20d6840 <line:4:2, col:24> 'int'
      |-ImplicitCastExpr 0x20d6828 <col:2> 'int (*)(const char *__restrict, ...)' <FunctionToPointerDecay>
      | `-DeclRefExpr 0x20d67b0 <col:2> 'int (const char *__restrict, ...)' lvalue Function 0x20c2808 'printf' 'int (const char *__restrict, ...)'
      `-ImplicitCastExpr 0x20d6868 <col:9> 'const char *' <ArrayToPointerDecay>
        `-StringLiteral 0x20d6788 <col:9> 'const char [14]' lvalue "Hello, World!"

Without Import

`-FunctionDecl 0xc71350 <test.cpp:3:1, line:5:1> line:3:5 main 'int ()'
  `-CompoundStmt 0xc71588 <col:12, line:5:1>

Upvotes: 1

Views: 600

Answers (1)

user4442671
user4442671

Reputation:

I could reproduce your issue with clang-10, but as of clang-11.0, the output is much more informative and spits out an UnresolvedLookupExpr node as I'd expect:

FunctionDecl 0x5641ea7ce5d8 <<source>:9:1, line:11:1> line:9:5 main 'int ()'
  `-CompoundStmt 0x5641ea7ce860 <col:12, line:11:1>
    `-RecoveryExpr 0x5641ea7ce830 <line:10:5, col:27> '<dependent type>' contains-errors lvalue
      |-UnresolvedLookupExpr 0x5641ea7ce6f8 <col:5> '<overloaded function type>' lvalue (ADL) = 'printf' empty
      `-StringLiteral 0x5641ea7ce7c0 <col:12> 'const char [14]' lvalue "Hello, World!"

See on godbolt: https://gcc.godbolt.org/z/1v6h7rarc

So the fix is simply to use a more recent version of clang.

Upvotes: 3

Related Questions