7
votes

I have been able to use CDT's AST API for parsing source code successfully. My question involves the reverse: How can I build an C AST programmatically, and then tell it to write itself to a file? I have seen the class ASTWriter (but that is internal) and can't find any tutorials or documentation on building the actual AST.

I have found a paper that goes over the idea of what I want to do: Generating Rewritable Abstract Syntax Trees which makes it seem like generating code would be easy if I could construct the tree and say 'write yourself'. Is this possible in CDT and how might I get started (preferably without deprecated/internal methods?)

2
Are you more interested in a CDT based solution, or any solution that will let you build/transform arbitrary ASTs for C, and then prettyprint the result?Ira Baxter
Due to focus change on the project of which spawned this question, this is no longer a majour need. If we do revisit it though, I would prefer a CDT based solution (like the refactoring solution mentioned by Eugene) since the project is an Eclipse based plugin.Erika Redmark

2 Answers

2
votes

What you need is using an ASTWriter:

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

Then you can dump the string to a file which is in the context of eclipse resources plugin.

1
votes

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

There are many problems that CDT refactoring framework tries to address:

  1. Let the user preview the changes before actually committing them to the source code.
  2. Operate on unsaved file bug (e.g. restructure the code in the unsaved source editor)
  3. Honour the user code formatting settings in a newly generated code.
  4. Undoable transactions spanning several source files.

I am pretty sure that even if you don't need all those features, these two classes should be a good starting point.