【问题标题】:Get Clang AST from C/C++ Code with Undeclared Identifiers使用未声明的标识符从 C/C++ 代码中获取 Clang AST
【发布时间】:2021-08-03 17:53:42
【问题描述】:

我想从一组 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>

【问题讨论】:

  • @Frank 我已经包含了示例,clang 确实 停止在printf 上导出 AST。即使理论上它应该能够继续。
  • 感谢您的澄清。您能否也请添加“带导入”版本代码的完整列表。
  • @Frank 已更新。看来CompoundStatement 是clang 处理这个问题的方式。但这是非常无信息的。它可能只是因为错误而存在。
  • 作为一个简短的旁注,import 在这里有点误导,因为在语言中引入了一个名为 import 的实际功能,这意味着其他东西。这里的正确术语应该是“包含标头”或“前向声明函数”。
  • @Frank python ;)

标签: c++ clang abstract-syntax-tree


【解决方案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!"

查看godbolt:https://gcc.godbolt.org/z/1v6h7rarc

所以解决方法就是使用更新版本的 clang。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多