如何在程序中自动插入编译指示 [英] How to automatically insert pragmas in your program
问题描述
我需要编写一个工具,该工具可以使用 C 代码并将编译指示置于某些函数之上.哪个编译器框架最容易完成这样的任务.另外,如果您能提供一个示例,我将不胜感激.
I need to write a tool that can take a C code and put pragmas on top of some functions. Which compiler framework is the easiest to do such a task. Also if you can provide an example, I would really appreciate it.
推荐答案
如果您想可靠地做到这一点,您需要一个完整的 C 前端,以及修改解析代码的能力.
If you want to do this reliably, you need a full C front end, and the ability to modify parsed code.
我们的 DMS 软件再造工具包及其 C 前端 大概可以做你想做的.DMS 可以解析、构建 AST,并对源文本执行自定义转换,无论是程序性转换还是表面语法转换.
Our DMS Software Reengineering Toolkit with its C Front End can probably do what you want. DMS can parse, build ASTs, and carry out custom transformations on source text, either procedural or as a surface syntax transform.
宏和预处理器指令存在一些问题;如果您解析并保留这些,它可以在许多情况下这样做,但它会扩展此类指令,因为它们不是结构化"的.保留意味着您没有得到符号表.如果将所有指令展开,解析后可以获得与 C 编译器生成的内容相同的符号表.
There are some issues with macros and preprocessor directives; if you parse and retain these, it can do so in many cases but it expandis such directives where they are not "structured". Retention means you don't get a symbol table. If you expand all the directives, after parsing you can get a symbol table with the same content that a C compiler produces.
对于 OP 的特定任务,他想编写一个源代码到源代码的转换,如下所示:
For OP's specific task, he'd like write a source to source transform something like the following:
rule decorate_function_definition_with_pragma(fh:function_head, b: block): declaration -> declaration
= " fh " ->
" fh
#pragma my_pragma
"
if some_condiiton(fh);
其中my_pragma"基本上被他想要的pragma 文本替换,而some_condition 是自定义谓词,用于过滤匹配的function_headers,应为其插入pragma.
where "my_pragma" is replace essentially by the pragma text he wants, and some_condition is custom predicate that filters matched function_headers for which the pragma should be inserted.
模式与语法树匹配,因此它不会像 sed 或正则表达式那样不匹配.其秘诀在于模式变量引用了 C 前端中的语法规则;function_head 类型的模式变量只能匹配 function_head 语法规则可以满足的那些树.
The pattern matches against the syntax tree, so it cannot mismatch like sed or a regex might. The secret to this is that the pattern variables reference to grammar rules in the C Front End; a pattern variable of type function_head can only match those trees that the function_head grammar rule(s) can satisfy.
需要一些简单的控制逻辑来为每个遇到的函数定义运行一次这种转换.
One needs some trivial control logic to run this transformation just once for each encountered function definition.
这篇关于如何在程序中自动插入编译指示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!