use of org.eclipse.jdt.core.dom.rewrite.ListRewrite in project generator by mybatis.
the class JavaFileMerger method getMergedSource.
@SuppressWarnings({ "unchecked", "rawtypes" })
public String getMergedSource() throws ShellException, InvalidExistingFileException {
NewJavaFileVisitor newJavaFileVisitor = visitNewJavaFile();
IDocument document = new Document(existingJavaSource);
// delete generated stuff, and collect imports
ExistingJavaFileVisitor visitor = new ExistingJavaFileVisitor(javaDocTags);
CompilationUnit cu = getCompilationUnitFromSource(existingJavaSource);
AST ast = cu.getAST();
cu.recordModifications();
cu.accept(visitor);
TypeDeclaration typeDeclaration = visitor.getTypeDeclaration();
if (typeDeclaration == null) {
throw new InvalidExistingFileException(ErrorCode.NO_TYPES_DEFINED_IN_FILE);
}
// reconcile the superinterfaces
List<Type> newSuperInterfaces = getNewSuperInterfaces(typeDeclaration.superInterfaceTypes(), newJavaFileVisitor);
for (Type newSuperInterface : newSuperInterfaces) {
typeDeclaration.superInterfaceTypes().add(ASTNode.copySubtree(ast, newSuperInterface));
}
// set the superclass
if (newJavaFileVisitor.getSuperclass() != null) {
typeDeclaration.setSuperclassType((Type) ASTNode.copySubtree(ast, newJavaFileVisitor.getSuperclass()));
} else {
typeDeclaration.setSuperclassType(null);
}
// interface or class?
if (newJavaFileVisitor.isInterface()) {
typeDeclaration.setInterface(true);
} else {
typeDeclaration.setInterface(false);
}
// reconcile the imports
List<ImportDeclaration> newImports = getNewImports(cu.imports(), newJavaFileVisitor);
for (ImportDeclaration newImport : newImports) {
Name name = ast.newName(newImport.getName().getFullyQualifiedName());
ImportDeclaration newId = ast.newImportDeclaration();
newId.setName(name);
cu.imports().add(newId);
}
TextEdit textEdit = cu.rewrite(document, null);
try {
textEdit.apply(document);
} catch (BadLocationException e) {
throw new ShellException("BadLocationException removing prior fields and methods");
}
// regenerate the CompilationUnit to reflect all the deletes and changes
CompilationUnit strippedCu = getCompilationUnitFromSource(document.get());
// find the top level public type declaration
TypeDeclaration topLevelType = null;
Iterator iter = strippedCu.types().iterator();
while (iter.hasNext()) {
TypeDeclaration td = (TypeDeclaration) iter.next();
if (td.getParent().equals(strippedCu) && (td.getModifiers() & Modifier.PUBLIC) > 0) {
topLevelType = td;
break;
}
}
// now add all the new methods and fields to the existing
// CompilationUnit with a ListRewrite
ASTRewrite rewrite = ASTRewrite.create(topLevelType.getRoot().getAST());
ListRewrite listRewrite = rewrite.getListRewrite(topLevelType, TypeDeclaration.BODY_DECLARATIONS_PROPERTY);
Iterator<ASTNode> astIter = newJavaFileVisitor.getNewNodes().iterator();
int i = 0;
while (astIter.hasNext()) {
ASTNode node = astIter.next();
if (node.getNodeType() == ASTNode.TYPE_DECLARATION) {
String name = ((TypeDeclaration) node).getName().getFullyQualifiedName();
if (visitor.containsInnerClass(name)) {
continue;
}
} else if (node instanceof FieldDeclaration) {
addExistsAnnotations((BodyDeclaration) node, visitor.getFieldAnnotations((FieldDeclaration) node));
} else if (node instanceof MethodDeclaration) {
addExistsAnnotations((BodyDeclaration) node, visitor.getMethodAnnotations((MethodDeclaration) node));
}
listRewrite.insertAt(node, i++, null);
}
textEdit = rewrite.rewriteAST(document, JavaCore.getOptions());
try {
textEdit.apply(document);
} catch (BadLocationException e) {
throw new ShellException("BadLocationException adding new fields and methods");
}
String newSource = document.get();
return newSource;
}
use of org.eclipse.jdt.core.dom.rewrite.ListRewrite in project AutoRefactor by JnRouvignac.
the class Refactorings method getListRewrite.
private ListRewrite getListRewrite(ASTNode node, ChildListPropertyDescriptor listProperty) {
final Pair<ASTNode, ChildListPropertyDescriptor> key = Pair.of(node, listProperty);
ListRewrite listRewrite = listRewriteCache.get(key);
if (listRewrite == null) {
listRewrite = rewrite.getListRewrite(node, listProperty);
listRewriteCache.put(key, listRewrite);
}
return listRewrite;
}
use of org.eclipse.jdt.core.dom.rewrite.ListRewrite in project Main by SpartanRefactoring.
the class ASTTestClassGenerator method addStaticImports.
public static String addStaticImports(ASTNode root, String importName, String simpleName) {
if (!iz.compilationUnit(root)) {
return root.toString();
}
ListRewrite lr = ASTRewrite.create(root.getAST()).getListRewrite(root, CompilationUnit.IMPORTS_PROPERTY);
ImportDeclaration id = root.getAST().newImportDeclaration();
id.setStatic(true);
id.setName(root.getAST().newName(importName.split("\\.")));
lr.insertLast(id, null);
//irw.addStaticImport(importName, simpleName, false);
try {
IDocument doc = new Document(root.toString());
TextEdit te = lr.getASTRewrite().rewriteAST(doc, null);
// TextEdit te = irw.rewriteImports(new NullProgressMonitor()); //FIXME: @orenafek: Change null to something else...
te.apply(doc);
return doc.get();
} catch (BadLocationException e) {
note.bug(e);
}
//lr.insertLast(ImportDeclaration.
return root.toString();
}
use of org.eclipse.jdt.core.dom.rewrite.ListRewrite in project bayou by capergroup.
the class Visitor method postprocessLocal.
/**
* Performs local post-processing of synthesized code:
* - Adds try-catch for uncaught exceptions
* - Adds local variable declarations
* - Adds return statement
*
* @param ast the owner of the block
* @param env environment that was used for synthesis
* @param body block containing synthesized code
* @param eliminatedVars variables eliminiated by DCE
* @return updated block containing synthesized code
*/
private Block postprocessLocal(AST ast, Environment env, Block body, Set<String> eliminatedVars) {
/* add uncaught exeptions */
Set<Class> exceptions = sketch.exceptionsThrown(eliminatedVars);
env.imports.addAll(exceptions);
if (!exceptions.isEmpty()) {
TryStatement statement = ast.newTryStatement();
statement.setBody(body);
List<Class> exceptions_ = new ArrayList<>(exceptions);
exceptions_.sort((Class e1, Class e2) -> e1.isAssignableFrom(e2) ? 1 : -1);
for (Class except : exceptions_) {
CatchClause catchClause = ast.newCatchClause();
SingleVariableDeclaration ex = ast.newSingleVariableDeclaration();
ex.setType(ast.newSimpleType(ast.newName(except.getSimpleName())));
ex.setName(ast.newSimpleName("_e"));
catchClause.setException(ex);
catchClause.setBody(ast.newBlock());
statement.catchClauses().add(catchClause);
}
body = ast.newBlock();
body.statements().add(statement);
}
/* add variable declarations */
Set<Variable> toDeclare = env.getScope().getVariables();
toDeclare.addAll(env.getScope().getPhantomVariables());
ListRewrite paramsRewriter = rewriter.getListRewrite(method, MethodDeclaration.PARAMETERS_PROPERTY);
for (Variable var : toDeclare) {
if (eliminatedVars.contains(var.getName()) || var.isUserVar())
continue;
// add the variable declaration to either the method's formal params or the body
org.eclipse.jdt.core.dom.Type varDeclType = var.getType().simpleT(ast, env);
if (var.isDefaultInit()) {
SingleVariableDeclaration varDecl = ast.newSingleVariableDeclaration();
varDecl.setType(varDeclType);
varDecl.setName(var.createASTNode(ast));
var.refactor("$" + var.getName());
paramsRewriter.insertLast(varDecl, null);
} else {
VariableDeclarationFragment varDeclFrag = ast.newVariableDeclarationFragment();
varDeclFrag.setName(var.createASTNode(ast));
VariableDeclarationStatement varDeclStmt = ast.newVariableDeclarationStatement(varDeclFrag);
varDeclStmt.setType(varDeclType);
body.statements().add(0, varDeclStmt);
}
}
/* add return statement */
org.eclipse.jdt.core.dom.Type ret = returnType.T();
List<Variable> toReturn = new ArrayList<>();
for (Variable var : env.getScope().getVariables()) if (returnType.isAssignableFrom(var.getType()))
toReturn.add(var);
toReturn.sort(Comparator.comparingInt(v -> v.getRefCount()));
ReturnStatement returnStmt = ast.newReturnStatement();
if (toReturn.isEmpty()) {
// add "return null" (or primitive) in order to make the code compile
if (ret.isPrimitiveType()) {
PrimitiveType primitiveType = (PrimitiveType) ret;
if (primitiveType.getPrimitiveTypeCode() == PrimitiveType.BOOLEAN)
returnStmt.setExpression(ast.newBooleanLiteral(false));
else if (primitiveType.getPrimitiveTypeCode() != PrimitiveType.VOID)
returnStmt.setExpression(ast.newNumberLiteral("0"));
} else
returnStmt.setExpression(ast.newNullLiteral());
} else {
returnStmt.setExpression(toReturn.get(0).createASTNode(ast));
}
body.statements().add(returnStmt);
return body;
}
Aggregations