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

查看:329
本文介绍了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:

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


$ b b

AST输出:

AST output:

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 将生成一个类似lisp的表示当前AST

  • -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

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天全站免登陆