Search in sources :

Example 86 with AST

use of org.eclipse.jdt.core.dom.AST in project AutoRefactor by JnRouvignac.

the class ReduceVariableScopeRefactoring method replace.

private void replace(VariableAccess varDecl, VariableAccess varAccess) {
    final ASTBuilder b = this.ctx.getASTBuilder();
    final AST ast = b.getAST();
    final ASTNode scope = varAccess.getScope();
    final Name varName = varAccess.getVariableName();
    final Type varType = getType(varDecl.getVariableName().getParent());
    if (scope instanceof Block) {
        final List<Statement> stmts = statements((Block) scope);
        for (int i = 0; i < stmts.size(); i++) {
            final Statement stmt = stmts.get(i);
            // FIXME i=0
            final Expression parentExpr = getAncestor(varName, Expression.class);
            // FIXME i=0
            final Statement parentStmt = getAncestor(parentExpr, Statement.class);
            if (stmt.equals(parentStmt)) {
                final VariableDeclarationFragment vdf = getVariableDeclarationFragment(parentExpr, varName);
                final VariableDeclarationStatement vds = ast.newVariableDeclarationStatement(vdf);
                vds.setType(varType);
                this.ctx.getRefactorings().replace(stmt, vds);
                break;
            }
        }
    } else if (scope instanceof EnhancedForStatement) {
        final EnhancedForStatement efs = (EnhancedForStatement) scope;
        final EnhancedForStatement newEfs = b.copy(efs);
        newEfs.setParameter(b.copy(efs.getParameter()));
        newEfs.setExpression(b.copy(efs.getExpression()));
        final Statement parentStmt = getAncestor(varName, Statement.class);
        if (equalNotNull(efs.getBody(), parentStmt)) {
            newEfs.setBody(copy(efs.getBody(), varName));
        }
        this.ctx.getRefactorings().replace(efs, newEfs);
    } else if (scope instanceof ForStatement) {
        final ForStatement fs = (ForStatement) scope;
        final ForStatement newFs = b.copy(fs);
        final List<Expression> initializers = initializers(newFs);
        if (initializers.size() == 1) {
            final Expression init = initializers.remove(0);
            final VariableDeclarationFragment vdf = getVariableDeclarationFragment(init, varName);
            final VariableDeclarationExpression vde = ast.newVariableDeclarationExpression(vdf);
            vde.setType(varType);
            initializers.add(vde);
            this.ctx.getRefactorings().replace(fs, newFs);
        // TODO JNR
        // if (equalNotNull(fs.getBody(), parentStmt)) {
        // newFs.setBody(copy(fs.getBody()));
        // }
        } else {
            throw new NotImplementedException(scope, "for more than one initializer in for loop.");
        }
    } else if (scope instanceof WhileStatement) {
        final WhileStatement ws = (WhileStatement) scope;
        final WhileStatement newWs = ast.newWhileStatement();
        newWs.setExpression(b.copy(ws.getExpression()));
        final Statement parentStmt = getAncestor(varName, Statement.class);
        if (equalNotNull(ws.getBody(), parentStmt)) {
            newWs.setBody(copy(ws.getBody(), varName));
        }
        this.ctx.getRefactorings().replace(ws, newWs);
    } else if (scope instanceof IfStatement) {
        final IfStatement is = (IfStatement) scope;
        final IfStatement newIs = ast.newIfStatement();
        newIs.setExpression(b.copy(is.getExpression()));
        final Statement parentStmt = getAncestor(varName, Statement.class);
        if (equalNotNull(is.getThenStatement(), parentStmt)) {
            newIs.setThenStatement(copy(is.getThenStatement(), varName));
            if (is.getElseStatement() != null) {
                newIs.setElseStatement(b.copy(is.getElseStatement()));
            }
            this.ctx.getRefactorings().replace(is, newIs);
        } else if (equalNotNull(is.getElseStatement(), parentStmt)) {
            if (is.getThenStatement() != null) {
                newIs.setThenStatement(b.copy(is.getThenStatement()));
            }
            newIs.setElseStatement(copy(is.getElseStatement(), varName));
            this.ctx.getRefactorings().replace(is, newIs);
        } else {
            throw new IllegalStateException(is, "Parent statement should be inside the then or else statement of this if statement: " + is);
        }
    } else {
        throw new NotImplementedException(scope);
    }
}
Also used : IllegalStateException(org.autorefactor.util.IllegalStateException) AST(org.eclipse.jdt.core.dom.AST) ExpressionStatement(org.eclipse.jdt.core.dom.ExpressionStatement) Statement(org.eclipse.jdt.core.dom.Statement) IfStatement(org.eclipse.jdt.core.dom.IfStatement) WhileStatement(org.eclipse.jdt.core.dom.WhileStatement) ForStatement(org.eclipse.jdt.core.dom.ForStatement) EnhancedForStatement(org.eclipse.jdt.core.dom.EnhancedForStatement) VariableDeclarationStatement(org.eclipse.jdt.core.dom.VariableDeclarationStatement) VariableDeclarationExpression(org.eclipse.jdt.core.dom.VariableDeclarationExpression) NotImplementedException(org.autorefactor.util.NotImplementedException) WhileStatement(org.eclipse.jdt.core.dom.WhileStatement) ASTBuilder(org.autorefactor.refactoring.ASTBuilder) SimpleName(org.eclipse.jdt.core.dom.SimpleName) Name(org.eclipse.jdt.core.dom.Name) QualifiedName(org.eclipse.jdt.core.dom.QualifiedName) IfStatement(org.eclipse.jdt.core.dom.IfStatement) Type(org.eclipse.jdt.core.dom.Type) PostfixExpression(org.eclipse.jdt.core.dom.PostfixExpression) Expression(org.eclipse.jdt.core.dom.Expression) InfixExpression(org.eclipse.jdt.core.dom.InfixExpression) VariableDeclarationExpression(org.eclipse.jdt.core.dom.VariableDeclarationExpression) VariableDeclarationFragment(org.eclipse.jdt.core.dom.VariableDeclarationFragment) ASTNode(org.eclipse.jdt.core.dom.ASTNode) Block(org.eclipse.jdt.core.dom.Block) VariableDeclarationStatement(org.eclipse.jdt.core.dom.VariableDeclarationStatement) EnhancedForStatement(org.eclipse.jdt.core.dom.EnhancedForStatement) ForStatement(org.eclipse.jdt.core.dom.ForStatement) EnhancedForStatement(org.eclipse.jdt.core.dom.EnhancedForStatement)

Example 87 with AST

use of org.eclipse.jdt.core.dom.AST in project AutoRefactor by JnRouvignac.

the class OperatorEnumTest method simpleTestCompareExpressions.

@Test
public void simpleTestCompareExpressions() {
    final AST ast = AST.newAST(AST.JLS8);
    final Assignment op1 = ast.newAssignment();
    op1.setOperator(Assignment.Operator.ASSIGN);
    final InfixExpression op2 = ast.newInfixExpression();
    op2.setOperator(InfixExpression.Operator.CONDITIONAL_AND);
    assertTrue(OperatorEnum.compareTo(op1, op2) < 0);
    assertEquals("Comparing unknown objects result in no decision", 0, OperatorEnum.compareTo(op1, null));
}
Also used : Assignment(org.eclipse.jdt.core.dom.Assignment) AST(org.eclipse.jdt.core.dom.AST) InfixExpression(org.eclipse.jdt.core.dom.InfixExpression) Test(org.junit.Test)

Example 88 with AST

use of org.eclipse.jdt.core.dom.AST in project eclipse-pmd by acanda.

the class JavaQuickFix method fixMarkersInFile.

/**
 * Fixes all provided markers in a file.
 *
 * @param markers The markers to fix. There is at least one marker in this collection and all markers can be fixed
 *            by this quick fix.
 */
protected void fixMarkersInFile(final IFile file, final List<IMarker> markers, final IProgressMonitor monitor) {
    monitor.subTask(file.getFullPath().toOSString());
    final Optional<ICompilationUnit> optionalCompilationUnit = getCompilationUnit(file);
    if (!optionalCompilationUnit.isPresent()) {
        return;
    }
    final ICompilationUnit compilationUnit = optionalCompilationUnit.get();
    ITextFileBufferManager bufferManager = null;
    final IPath path = compilationUnit.getPath();
    try {
        bufferManager = FileBuffers.getTextFileBufferManager();
        bufferManager.connect(path, LocationKind.IFILE, null);
        final ITextFileBuffer textFileBuffer = bufferManager.getTextFileBuffer(path, LocationKind.IFILE);
        final IDocument document = textFileBuffer.getDocument();
        final IAnnotationModel annotationModel = textFileBuffer.getAnnotationModel();
        final ASTParser astParser = ASTParser.newParser(AST.JLS4);
        astParser.setKind(ASTParser.K_COMPILATION_UNIT);
        astParser.setResolveBindings(needsTypeResolution());
        astParser.setSource(compilationUnit);
        final SubProgressMonitor parserMonitor = new SubProgressMonitor(monitor, 100);
        final CompilationUnit ast = (CompilationUnit) astParser.createAST(parserMonitor);
        parserMonitor.done();
        startFixingMarkers(ast);
        final Map<?, ?> options = compilationUnit.getJavaProject().getOptions(true);
        for (final IMarker marker : markers) {
            try {
                final MarkerAnnotation annotation = getMarkerAnnotation(annotationModel, marker);
                // if the annotation is null it means that is was deleted by a previous quick fix
                if (annotation != null) {
                    final Optional<T> node = getNodeFinder(annotationModel.getPosition(annotation)).findNode(ast);
                    if (node.isPresent()) {
                        final boolean isSuccessful = fixMarker(node.get(), document, options);
                        if (isSuccessful) {
                            marker.delete();
                        }
                    }
                }
            } finally {
                monitor.worked(100);
            }
        }
        finishFixingMarkers(ast, document, options);
        // commit changes to underlying file if it is not opened in an editor
        if (!isEditorOpen(file)) {
            final SubProgressMonitor commitMonitor = new SubProgressMonitor(monitor, 100);
            textFileBuffer.commit(commitMonitor, false);
            commitMonitor.done();
        } else {
            monitor.worked(100);
        }
    } catch (CoreException | MalformedTreeException | BadLocationException e) {
    // TODO: log error
    // PMDPlugin.getDefault().error("Error processing quickfix", e);
    } finally {
        if (bufferManager != null) {
            try {
                bufferManager.disconnect(path, LocationKind.IFILE, null);
            } catch (final CoreException e) {
            // TODO: log error
            // PMDPlugin.getDefault().error("Error processing quickfix", e);
            }
        }
    }
}
Also used : ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) IPath(org.eclipse.core.runtime.IPath) ITextFileBufferManager(org.eclipse.core.filebuffers.ITextFileBufferManager) MalformedTreeException(org.eclipse.text.edits.MalformedTreeException) IAnnotationModel(org.eclipse.jface.text.source.IAnnotationModel) SubProgressMonitor(org.eclipse.core.runtime.SubProgressMonitor) MarkerAnnotation(org.eclipse.ui.texteditor.MarkerAnnotation) AST(org.eclipse.jdt.core.dom.AST) CoreException(org.eclipse.core.runtime.CoreException) ITextFileBuffer(org.eclipse.core.filebuffers.ITextFileBuffer) IMarker(org.eclipse.core.resources.IMarker) ASTParser(org.eclipse.jdt.core.dom.ASTParser) IDocument(org.eclipse.jface.text.IDocument) BadLocationException(org.eclipse.jface.text.BadLocationException)

Example 89 with AST

use of org.eclipse.jdt.core.dom.AST in project eclipse-pmd by acanda.

the class UseUtilityClassQuickFix method addPrivateConstructor.

@SuppressWarnings("unchecked")
private void addPrivateConstructor(final TypeDeclaration typeDeclaration, final ASTRewrite rewrite) {
    final AST ast = typeDeclaration.getAST();
    final MethodDeclaration constructor = (MethodDeclaration) ast.createInstance(MethodDeclaration.class);
    constructor.setConstructor(true);
    final Modifier modifier = (Modifier) ast.createInstance(Modifier.class);
    modifier.setKeyword(ModifierKeyword.PRIVATE_KEYWORD);
    constructor.modifiers().add(modifier);
    constructor.setName(ASTUtil.copy(typeDeclaration.getName()));
    final Block body = (Block) ast.createInstance(Block.class);
    constructor.setBody(body);
    final ListRewrite statementRewrite = rewrite.getListRewrite(body, Block.STATEMENTS_PROPERTY);
    final ASTNode comment = rewrite.createStringPlaceholder("// hide constructor of utility class", ASTNode.EMPTY_STATEMENT);
    statementRewrite.insertFirst(comment, null);
    final int position = findConstructorPosition(typeDeclaration);
    final ListRewrite bodyDeclarationRewrite = rewrite.getListRewrite(typeDeclaration, TypeDeclaration.BODY_DECLARATIONS_PROPERTY);
    bodyDeclarationRewrite.insertAt(constructor, position, null);
}
Also used : AST(org.eclipse.jdt.core.dom.AST) MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) ASTNode(org.eclipse.jdt.core.dom.ASTNode) Block(org.eclipse.jdt.core.dom.Block) ListRewrite(org.eclipse.jdt.core.dom.rewrite.ListRewrite) Modifier(org.eclipse.jdt.core.dom.Modifier) IExtendedModifier(org.eclipse.jdt.core.dom.IExtendedModifier)

Example 90 with AST

use of org.eclipse.jdt.core.dom.AST in project eclipse-pmd by acanda.

the class EqualsNullQuickFix method apply.

/**
 * Replaces {@code x.equals(null)} with {@code x == null}.
 */
@Override
protected boolean apply(final MethodInvocation node) {
    final AST ast = node.getAST();
    final InfixExpression infix = (InfixExpression) ast.createInstance(InfixExpression.class);
    infix.setOperator(Operator.EQUALS);
    infix.setLeftOperand(ASTUtil.copy(node.getExpression()));
    infix.setRightOperand((NullLiteral) ast.createInstance(NullLiteral.class));
    ASTUtil.replace(node, infix);
    return true;
}
Also used : AST(org.eclipse.jdt.core.dom.AST) InfixExpression(org.eclipse.jdt.core.dom.InfixExpression)

Aggregations

AST (org.eclipse.jdt.core.dom.AST)169 ASTRewrite (org.eclipse.jdt.core.dom.rewrite.ASTRewrite)78 Expression (org.eclipse.jdt.core.dom.Expression)77 ASTNode (org.eclipse.jdt.core.dom.ASTNode)70 Type (org.eclipse.jdt.core.dom.Type)52 SimpleName (org.eclipse.jdt.core.dom.SimpleName)51 Block (org.eclipse.jdt.core.dom.Block)44 ITypeBinding (org.eclipse.jdt.core.dom.ITypeBinding)43 InfixExpression (org.eclipse.jdt.core.dom.InfixExpression)42 CastExpression (org.eclipse.jdt.core.dom.CastExpression)40 ParenthesizedExpression (org.eclipse.jdt.core.dom.ParenthesizedExpression)40 MethodDeclaration (org.eclipse.jdt.core.dom.MethodDeclaration)39 VariableDeclarationFragment (org.eclipse.jdt.core.dom.VariableDeclarationFragment)38 ASTRewriteCorrectionProposal (org.eclipse.jdt.ui.text.java.correction.ASTRewriteCorrectionProposal)38 ReturnStatement (org.eclipse.jdt.core.dom.ReturnStatement)34 PrefixExpression (org.eclipse.jdt.core.dom.PrefixExpression)33 VariableDeclarationStatement (org.eclipse.jdt.core.dom.VariableDeclarationStatement)33 ContextSensitiveImportRewriteContext (org.eclipse.jdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext)33 ConditionalExpression (org.eclipse.jdt.core.dom.ConditionalExpression)30 ListRewrite (org.eclipse.jdt.core.dom.rewrite.ListRewrite)30