从具有未声明标识符的 C/C++ 代码中获取 Clang AST
Get Clang AST from C/C++ Code with Undeclared Identifiers
我想从一组 C/C++ 代码中生成一个 AST,我知道其中会缺少包含。这是一个示例。
int main() {
printf("Hello, World!");
}
我试过 clang -Xclang -ast-dump -fsyntax-only test.cpp
这样做。但是当它遇到 printf
.
时它停止导出 AST
带导入
#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!"
不导入
`-FunctionDecl 0xc71350 <test.cpp:3:1, line:5:1> line:3:5 main 'int ()'
`-CompoundStmt 0xc71588 <col:12, line:5:1>
我可以用 clang-10 重现您的问题,但从 clang-11.0 开始,输出的信息量更大,并且如我所料吐出一个 UnresolvedLookupExpr
节点:
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!"
见神箭:https://gcc.godbolt.org/z/1v6h7rarc
所以解决方法就是使用更新版本的 clang。
我想从一组 C/C++ 代码中生成一个 AST,我知道其中会缺少包含。这是一个示例。
int main() {
printf("Hello, World!");
}
我试过 clang -Xclang -ast-dump -fsyntax-only test.cpp
这样做。但是当它遇到 printf
.
带导入
#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!"
不导入
`-FunctionDecl 0xc71350 <test.cpp:3:1, line:5:1> line:3:5 main 'int ()'
`-CompoundStmt 0xc71588 <col:12, line:5:1>
我可以用 clang-10 重现您的问题,但从 clang-11.0 开始,输出的信息量更大,并且如我所料吐出一个 UnresolvedLookupExpr
节点:
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!"
见神箭:https://gcc.godbolt.org/z/1v6h7rarc
所以解决方法就是使用更新版本的 clang。