How to automatically insert pragmas in your program

我与影子孤独终老i 提交于 2019-12-18 08:39:15

问题


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.


回答1:


If you want to do this reliably, you need a full C front end, and the ability to modify parsed code.

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.

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.

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 \b " ->
          " \fh 
            #pragma  my_pragma 
            \b "
         if some_condiiton(fh);

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.

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.




回答2:


Take a look at lex/flex or yacc/bison.

great article: http://www.ibm.com/developerworks/aix/tutorials/au-lexyacc/index.html




回答3:


You can use regular expressions to search for the function definition.

http://en.wikipedia.org/wiki/Regular_expression



来源:https://stackoverflow.com/questions/10960974/how-to-automatically-insert-pragmas-in-your-program

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!