Question

Using Eclipse JDT I would like to copy code from multiple source CompilationUnits to a central CompilationUnit.

I am using ASTRewrite to collect all the changes. In order to copy the code, I use ASTRewrite.createCopyTarget(ASTNode) to create a virtual copy which I would then like to add to my central CompilationUnit. My problem is that ASTRewrite.createCopyTarget(ASTNode) throws an IllegalArgumentException:

java.lang.IllegalArgumentException: Node is not inside the AST
    at org.eclipse.jdt.core.dom.rewrite.ASTRewrite.validateIsCorrectAST(ASTRewrite.java:582) ~[na:na]
    at org.eclipse.jdt.core.dom.rewrite.ASTRewrite.createTargetNode(ASTRewrite.java:698) ~[na:na]
    at org.eclipse.jdt.core.dom.rewrite.ASTRewrite.createCopyTarget(ASTRewrite.java:723) ~[na:na]

The ASTRewrite is setup using the AST for the central target CompilationUnit. So the question is: Is it possible to parse multiple Units, so they belong to the same AST? Or ist it passible to set the parent AST of a CompilationUnit in some way?

My parsing code looks like this:

private static ASTParser parser = ASTParser.newParser(AST.JLS4);
public static CompilationUnit parseAst(IType type, SubMonitor progress) {
    parser.setSource(type.getCompilationUnit());
    parser.setResolveBindings(true);
    return (CompilationUnit)parser.createAST(progress);
}

I assume, that this must be possible in some way, otherwise ASTRewrite.createCopyTarget(ASTNode) would be restricted to creating copies in the scope of a CompilationUnit only.

Any pointers are greatly appriciated!

Était-ce utile?

La solution

ASTRewrite can only be used to transform a single AST but not to copy nodes or subtrees from one AST to another. If you want to copy a node or subtree from one AST to another you have to use ASTNode.copySubtree(AST target, ASTNode node) which allows you to specify the target AST.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top