Community
Participate
Working Groups
I need to change existed AST by adding new statements, changing expression, etc. AFAIK JDT does not have support for parsing source and returning piece of AST, which can be added to another AST. So I have my own code in package org.eclipse.jdt.core.dom (see last two methods). I parse source and use old AST. But when I add this new Statement in Block, all type bindings become null. I know, that this is hack, but may be it is obvious for you, where is reason for such behaviour? try { Statement st = info.parseStatement(creation.getAST(), 0, "System.out.println();"); ASTNode blockNode = creation; while (!(blockNode instanceof Block)) blockNode = blockNode.getParent(); Block block = (Block) blockNode; block.statements().add(st); System.out.println("ce.resolveTypeBinding(): " + creation.resolveTypeBinding()); System.out.println("ce.resolveTypeBinding(): " + creation.resolveTypeBinding()); } catch (JavaModelException e1) { e1.printStackTrace(); } public static Statement parseStatement(AST ast, final int start, String src, IJavaProject project) throws JavaModelException { String source = "class Fake { public void foo() {"; final int baseLength = source.length(); source = source + src; source = source + ";}}"; final ArrayList resultList = new ArrayList(); CompilationUnit cu = parseCompilationUnit(ast, source, project); cu.accept(new ASTVisitor() { public void preVisit(ASTNode node) { if ((node instanceof Statement) && node.getStartPosition() == baseLength) resultList.add(node); int pos = node.getStartPosition(); int length = node.getLength(); if (pos >= baseLength) node.setSourceRange((start + pos) - baseLength, length); } }); Statement statement = (Statement) resultList.get(0); ((Block) statement.getParent()).statements().remove(statement); return statement; } public static CompilationUnit parseCompilationUnit(AST ast, String source, IJavaProject project) throws JavaModelException { if (source == null) throw new IllegalArgumentException(); if (project == null) { throw new IllegalArgumentException(); } else { CompilationUnitDeclaration compilationUnitDeclaration = CompilationUnitResolver.resolve( source.toCharArray(), "fakeUnit", project, new AbstractSyntaxTreeVisitorAdapter()); ASTConverter converter = new ASTConverter(project.getOptions(true), true); BindingResolver resolver = new DefaultBindingResolver(compilationUnitDeclaration.scope); ast.setBindingResolver(resolver); converter.setAST(ast); CompilationUnit cu = converter.convert(compilationUnitDeclaration, source.toCharArray()); cu.setLineEndTable(compilationUnitDeclaration.compilationResult.lineSeparatorPositions); resolver.storeModificationCount(ast.modificationCount()); return cu; } }
Sorry, I found, that this was my bug - I recreate resolver after each reuse of AST. After fixing this, bindings work fine, thanks!