Search code examples
javaeclipseabstract-syntax-treeeclipse-jdt

Eclipse JDT AST: How to write generated AST to java file?


I am currently working with eclipse AST to generate source code. Other than in most examples, I am generating the source code from scratch and in a stand-alone application, as opposed to an eclipse plug-in.

When read in from an ASTParser, you can activate modifications by calling recordModifications(), but this doesn't work when the AST is created from scratch, e.g. by calling newCompilationUnit().

Consequently, writing the source to file via a Document and TextEdit is not possible - there is an exception saying that modification recording hasn't been enabled.
Any experiences in generating AST from scratch and writing to file? Thanks!


Solution

  • Why not create the file first, then generate an AST from it, like this:

    ICompilationUnit unit = JavaCore.createCompilationUnitFrom(file);
    ASTParser parser = ASTParser.newParser(AST.JLS3);
    parser.setKind(ASTParser.K_COMPILATION_UNIT);
    parser.setResolveBindings(true);
    parser.setSource(unit);
    // Parse the source code and generate an AST.
    CompilationUnit ast = (CompilationUnit) parser.createAST(null);
    

    If the file is newly created and blank, then presumably the AST will be empty, You can then replace the root of the ast object and write it to the file. Also, if you are not tied to Eclipse, you could just do the same thing using the JSR199 standard and write that AST to a file in the normal way. See here for an introduction.