Search in sources :

Example 76 with ListRewrite

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;
}
Also used : ListRewrite(org.eclipse.jdt.core.dom.rewrite.ListRewrite) Document(org.eclipse.jface.text.Document) IDocument(org.eclipse.jface.text.IDocument) FieldDeclaration(org.eclipse.jdt.core.dom.FieldDeclaration) Name(org.eclipse.jdt.core.dom.Name) Iterator(java.util.Iterator) ASTNode(org.eclipse.jdt.core.dom.ASTNode) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite) CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) AST(org.eclipse.jdt.core.dom.AST) MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) ShellException(org.mybatis.generator.exception.ShellException) Type(org.eclipse.jdt.core.dom.Type) TextEdit(org.eclipse.text.edits.TextEdit) ImportDeclaration(org.eclipse.jdt.core.dom.ImportDeclaration) BodyDeclaration(org.eclipse.jdt.core.dom.BodyDeclaration) TypeDeclaration(org.eclipse.jdt.core.dom.TypeDeclaration) IDocument(org.eclipse.jface.text.IDocument) BadLocationException(org.eclipse.jface.text.BadLocationException)

Example 77 with ListRewrite

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;
}
Also used : ASTNode(org.eclipse.jdt.core.dom.ASTNode) ListRewrite(org.eclipse.jdt.core.dom.rewrite.ListRewrite) ChildListPropertyDescriptor(org.eclipse.jdt.core.dom.ChildListPropertyDescriptor)

Example 78 with 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();
}
Also used : TextEdit(org.eclipse.text.edits.TextEdit) ListRewrite(org.eclipse.jdt.core.dom.rewrite.ListRewrite) Document(org.eclipse.jface.text.Document) IDocument(org.eclipse.jface.text.IDocument) IDocument(org.eclipse.jface.text.IDocument) BadLocationException(org.eclipse.jface.text.BadLocationException)

Example 79 with ListRewrite

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;
}
Also used : Bayou(edu.rice.cs.caper.bayou.annotations.Bayou) Document(org.eclipse.jface.text.Document) java.util(java.util) org.eclipse.jdt.core.dom(org.eclipse.jdt.core.dom) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite) BadLocationException(org.eclipse.jface.text.BadLocationException) DSubTree(edu.rice.cs.caper.bayou.core.dsl.DSubTree) ListRewrite(org.eclipse.jdt.core.dom.rewrite.ListRewrite) org.eclipse.jdt.core.dom(org.eclipse.jdt.core.dom) ListRewrite(org.eclipse.jdt.core.dom.rewrite.ListRewrite)

Aggregations

ListRewrite (org.eclipse.jdt.core.dom.rewrite.ListRewrite)79 ASTRewrite (org.eclipse.jdt.core.dom.rewrite.ASTRewrite)45 ASTNode (org.eclipse.jdt.core.dom.ASTNode)37 AST (org.eclipse.jdt.core.dom.AST)30 ICompilationUnit (org.eclipse.jdt.core.ICompilationUnit)19 ASTRewriteCorrectionProposal (org.eclipse.jdt.ui.text.java.correction.ASTRewriteCorrectionProposal)19 Block (org.eclipse.jdt.core.dom.Block)18 Type (org.eclipse.jdt.core.dom.Type)18 Image (org.eclipse.swt.graphics.Image)17 VariableDeclarationStatement (org.eclipse.jdt.core.dom.VariableDeclarationStatement)15 ImportRewriteContext (org.eclipse.jdt.core.dom.rewrite.ImportRewrite.ImportRewriteContext)15 ContextSensitiveImportRewriteContext (org.eclipse.jdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext)15 ArrayList (java.util.ArrayList)13 IType (org.eclipse.jdt.core.IType)13 MethodDeclaration (org.eclipse.jdt.core.dom.MethodDeclaration)13 Statement (org.eclipse.jdt.core.dom.Statement)13 VariableDeclarationFragment (org.eclipse.jdt.core.dom.VariableDeclarationFragment)13 Expression (org.eclipse.jdt.core.dom.Expression)12 ExpressionStatement (org.eclipse.jdt.core.dom.ExpressionStatement)12 ITypeBinding (org.eclipse.jdt.core.dom.ITypeBinding)12