Using the CDT Abstract Syntax Tree API to generate / write C code?

I was able to use the AST CDT API to successfully parse the source code. My question involves the opposite: how can I create a C AST programmatically and then say that it writes itself to a file? I have seen the ASTWriter class (but this is internal) and cannot find any tutorials or documentation on creating a real AST.

I found an article that describes what I want to do: Generating rewritable abstract syntax trees , which makes it look like generating code would be easy if I could build a tree and say "write yourself." Is this possible in CDT and how can I get started (preferably without outdated / internal methods?)

+7
source share
2 answers

I would advise you to start by exploring CRefactoring and its subclasses (e.g. ExtractFunctionRefactoring ).

There are many problems that the CDT refactoring system faces:

  • Allow the user to review the changes before they are submitted to the source code.
  • Use an unsaved file error (for example, restructure the code in an unsaved source editor)
  • Read the user code formatting settings in the newly generated code.
  • Impossible transactions spanning multiple source files.

I am sure that even if you do not need all these functions, these two classes should be a good starting point.

+1
source

You need to use ASTWriter:

ASTWriter writer = new ASTWriter() String code = writer.write(myAST); 

You can then output the line to a file that is in the context of the eclipse resource plugin.

+2
source

All Articles