Clang:AST(抽象语法树)是什么样的? [英] Clang : What does AST (abstract syntax tree) look like?

查看:31
本文介绍了Clang:AST(抽象语法树)是什么样的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是编译器开发的新手,想知道 AST 是什么样的.我有一小段代码,我使用 Clang 来生成 AST.我没有从中得到太多信息.从它的外观来看,语法树与源代码完全相同,除了一个结构体被添加到我测试的几乎所有样本中.

Hi I am new in Compiler development, and am wondering how AST look like. I have a small section of code, and I use Clang for generating the AST. I don't get much information out of it. From the looks of it, the Syntax tree is exactly the same as the source, except for one struct that is added to almost any sample I test with.

来源:

class A {
public:
  int *a, *b, *c;
  int i;
  void sum() {
    a = new int[5];
    b = new int[5];
    c = new int[5];
    for (i = 0; i < 5; i++) {
      a[i] = i;
      b[i] = i;
    }
    for (i = 0; i < 5; i++) {
      c[i] = a[i] + b[i];
    }
    delete[] a;   delete[] b;   delete[] c;
  }
};

class B : public A {
};

int main() {
  B bclass; 
  bclass.sum();
  return 0;
} 

生成 AST 的命令:

Command to generate AST:

clang++ -cc1 -ast-print ~/sum.cpp

AST 输出:

struct __va_list_tag {
    unsigned int gp_offset;
    unsigned int fp_offset;
    void *overflow_arg_area;
    void *reg_save_area;
};
typedef struct __va_list_tag __va_list_tag;
class A {
public:
    int *a;
    int *b;
    int *c;
    int i;
    void sum()     {
        this->a = new int [5];
        this->b = new int [5];
        this->c = new int [5];
        for (this->i = 0; this->i < 5; this->i++) {
            this->a[this->i] = this->i;
            this->b[this->i] = this->i;
        }
        for (this->i = 0; this->i < 5; this->i++) {
            this->c[this->i] = this->a[this->i] + this->b[this->i];
        }
        delete [] this->a;
        delete [] this->b;
        delete [] this->c;
    }


};
class B : public A {
};
int main() {
    B bclass;
    bclass.sum();
    return 0;
}

谢谢

推荐答案

在各种可用选项之间存在一个小小的混淆:

There is a small confusion between the various options available:

  • -ast-print 将漂亮地打印当前的 AST,也就是说,它将尽可能将它理解的代码呈现为它解析的内容(但使某些事情变得明确,例如幻影this)
  • -ast-dump 将生成当前 AST 的类似 lisp 的表示
  • -ast-print will pretty-print the current AST, that is, it will render the code it understood as closely as possible to what it parsed (but making some things explicit, like the apparition of the this)
  • -ast-dump will generate a lisp-like representation of the current AST

漂亮的打印机可用于检查 AST 是否无损(即,保留了此类表达式的 const-ness 等...),但实际上与开发无关.

The pretty printer can be useful to check that the AST is lossless (ie, preserved the const-ness of such expression, etc...) but is not really about development.

如果你想破解编译器,你需要 -ast-dump,它会生成一个输出,直接映射已解析代码的内存表示.

If you want to hack on the compiler, you need -ast-dump, which will generate an output that maps directly the in-memory representation of the code that was parsed.

这篇关于Clang:AST(抽象语法树)是什么样的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆