从C code构建AST [英] Build AST from C code

查看:181
本文介绍了从C code构建AST的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何建立从GCC C code。将AST(抽象语法树)为了进行一些修改,比如将一些诠释变量浮动,并再次重现(生成)的code到C语法之后。

How can I build an AST (Abstract Syntax Tree) from gcc C code in order to make some modifications, like converting some int variables to float, and reproduce(generate) the code to C syntax again after that.

事实上,就目前而言,我真正需要的唯一功能是从由几行C程序中提取的变量及其类型的表...我认为这是一个简单的解析器这样做。

Actually, for the moment, the only functionality I truly need is to extract a table of variables and their types from a c program consisting of few lines... I think there is a simple parser doing so.

我有一些变量,如:

int  var_bss ;           
float var_f_bss;            
int var_data = 4;        
float var_f_data = 5;  

和一个功能:

int Foo(){          
   some local variables;            
}    

在code是在一个单一的C文件。

The code is in a single c file.

我要介绍的所有变量给最终用户,让他选择在一个特定的内存段源类型如诠释在.data变量。然后,用户可以将这些变量转换成浮动。最后,我产生相同的code为用户但随着新的变量类型的他选择。

I want to introduce all the variables to the end user to let him choose a source type in a specific memory segment e.g. int variables in the .data. Then the user can convert those variables into floats. Finally, I generate the same code for the user but with the new variable types those he has chosen.

推荐答案

首先,这是一项艰巨的任务,因为C的抽象语法树比复杂得多你认为它是。

First, it is a difficult task, because the abstract syntax tree of C is much more complex than what you believe it is.

然后,如果你使用的是最近的海湾合作​​委员会(如4.7或4.8),我强烈建议定制GCC 例如与 MELT 扩展程序(或某些GCC插件)。

Then if you are using a recent GCC (e.g. 4.7 or 4.8), I strongly suggest customizing GCC e.g. with a MELT extension (or some GCC plugin).

我不主张这是一个简单的任务,因为很有可能你需要理解GCC内部重新presentations的细节。

I don't claim it is a simple task, because very probably you need to understand the details of GCC internal representations.

BTW,的 MELT 的是一个领域特定语言扩展GCC,并且也正是专为那种你梦想着任务。你将能够熔体改造内部GCC重新presentations(GIMPLE和树-S)。

BTW, MELT is a domain specific language to extend GCC, and is designed exactly for the kind of tasks you are dreaming about. You would be able with MELT to transform the internal GCC representations (Gimple and Tree-s).

里面GCC工作的好处(或其他编译器一样锵/ LLVM内部)是,你不必回吐一些C code(实际上是你所想的要困难得多);你刚才改造内部编译器重新presentation,也许最重要的是,您利用的很多事情编译器总是做免费各种优化喜欢不断的折叠,内联,共SUBEX pression消除,等,等,等......

The advantage of working inside GCC (or inside some other compiler like Clang/LLVM) is that you don't have to spit back some C code (which is actually much more difficult than what you think); you just transform the internal compiler representation and, perhaps most importantly, you take advantage "gratis" of the many things a compiler always do: all kind of optimizations like constant folding, inlining, common-subexpression elimination, etc, etc, etc, ....

这篇关于从C code构建AST的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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