Search in sources :

Example 71 with SingleVariableDeclaration

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

the class ObsoleteRedundantComparatorCleanUp method maybeRefactorTypedCode.

private boolean maybeRefactorTypedCode(final MethodInvocation visitedIfRefactoringNeeded, final Expression list, final Expression comparatorToRemove, final Expression comparatorToAnalyze, final ITypeBinding[] typeArguments, final boolean isForward, final Set<String> classesToUseWithImport, final Set<String> importsToAdd) {
    NullLiteral nullLiteral = ASTNodes.as(comparatorToAnalyze, NullLiteral.class);
    if (nullLiteral != null) {
        return maybeRemoveComparator(visitedIfRefactoringNeeded, list, comparatorToRemove, isForward, classesToUseWithImport, importsToAdd);
    }
    ClassInstanceCreation classInstanceCreation = ASTNodes.as(comparatorToAnalyze, ClassInstanceCreation.class);
    if (classInstanceCreation != null && isClassToRemove(classInstanceCreation, isForward)) {
        return maybeRemoveComparator(visitedIfRefactoringNeeded, list, comparatorToRemove, true, classesToUseWithImport, importsToAdd);
    }
    MethodReference methodReference = ASTNodes.as(comparatorToAnalyze, MethodReference.class);
    LambdaExpression lambdaExpression = ASTNodes.as(comparatorToAnalyze, LambdaExpression.class);
    MethodInvocation methodInvocation = ASTNodes.as(comparatorToAnalyze, MethodInvocation.class);
    if (methodReference != null) {
        String elementClass = typeArguments[0].isWildcardType() ? Comparable.class.getCanonicalName() : typeArguments[0].getQualifiedName();
        if (// $NON-NLS-1$
        ASTNodes.usesGivenSignature(// $NON-NLS-1$
        methodReference.resolveMethodBinding(), // $NON-NLS-1$
        elementClass, // $NON-NLS-1$
        "compareTo", Object.class.getCanonicalName())) {
            return maybeRemoveComparator(visitedIfRefactoringNeeded, list, comparatorToRemove, isForward, classesToUseWithImport, importsToAdd);
        }
    } else if (methodInvocation != null) {
        if (// $NON-NLS-1$
        ASTNodes.usesGivenSignature(methodInvocation, Comparator.class.getCanonicalName(), "reversed") && methodInvocation.getExpression() != null) {
            return maybeRefactorTypedCode(visitedIfRefactoringNeeded, list, comparatorToRemove, methodInvocation.getExpression(), typeArguments, !isForward, classesToUseWithImport, importsToAdd);
        }
        if (ASTNodes.usesGivenSignature(methodInvocation, Comparator.class.getCanonicalName(), "naturalOrder")) {
            // $NON-NLS-1$
            return maybeRemoveComparator(visitedIfRefactoringNeeded, list, comparatorToRemove, isForward, classesToUseWithImport, importsToAdd);
        }
        if (// $NON-NLS-1$
        "comparing".equals(methodInvocation.getName().getIdentifier()) && methodInvocation.resolveMethodBinding() != null && methodInvocation.resolveMethodBinding().getParameterTypes().length == 1 && ASTNodes.hasType(methodInvocation.resolveMethodBinding().getDeclaringClass(), Comparator.class.getCanonicalName()) && ASTNodes.hasType(methodInvocation.resolveMethodBinding().getParameterTypes()[0], Function.class.getCanonicalName())) {
            List<Expression> comparingMethodArgs = methodInvocation.arguments();
            Expression criteria = comparingMethodArgs.get(0);
            LambdaExpression comparingMethodLambdaExpression = ASTNodes.as(criteria, LambdaExpression.class);
            MethodInvocation identityMethod = ASTNodes.as(criteria, MethodInvocation.class);
            if (comparingMethodLambdaExpression != null) {
                if (comparingMethodLambdaExpression.parameters().size() == 1) {
                    List<VariableDeclaration> parameters = comparingMethodLambdaExpression.parameters();
                    SimpleName variable = parameters.get(0).getName();
                    Expression bodyExpression = null;
                    if (comparingMethodLambdaExpression.getBody() instanceof Block) {
                        ReturnStatement returnStatement = ASTNodes.as((Block) comparingMethodLambdaExpression.getBody(), ReturnStatement.class);
                        if (returnStatement == null) {
                            return true;
                        }
                        bodyExpression = returnStatement.getExpression();
                    } else if (comparingMethodLambdaExpression.getBody() instanceof Expression) {
                        bodyExpression = (Expression) comparingMethodLambdaExpression.getBody();
                    } else {
                        return true;
                    }
                    if (ASTNodes.areSameVariables(variable, bodyExpression)) {
                        return maybeRemoveComparator(visitedIfRefactoringNeeded, list, comparatorToRemove, isForward, classesToUseWithImport, importsToAdd);
                    }
                }
            } else if (identityMethod != null && // $NON-NLS-1$
            "identity".equals(identityMethod.getName().getIdentifier()) && identityMethod.resolveMethodBinding() != null && identityMethod.resolveMethodBinding().getParameterTypes().length == 0 && ASTNodes.hasType(identityMethod.resolveMethodBinding().getDeclaringClass(), Function.class.getCanonicalName())) {
                return maybeRemoveComparator(visitedIfRefactoringNeeded, list, comparatorToRemove, isForward, classesToUseWithImport, importsToAdd);
            }
        }
    } else if (lambdaExpression != null) {
        if (lambdaExpression.parameters().size() == 2) {
            List<ASTNode> parameters = lambdaExpression.parameters();
            ASTNode parameter1 = parameters.get(0);
            ASTNode parameter2 = parameters.get(1);
            SimpleName variable1;
            if (parameter1 instanceof SingleVariableDeclaration) {
                variable1 = ((SingleVariableDeclaration) parameter1).getName();
            } else if (parameter1 instanceof VariableDeclarationFragment) {
                variable1 = ((VariableDeclarationFragment) parameter1).getName();
            } else {
                return true;
            }
            SimpleName variable2;
            if (parameter2 instanceof SingleVariableDeclaration) {
                variable2 = ((SingleVariableDeclaration) parameter2).getName();
            } else if (parameter2 instanceof VariableDeclarationFragment) {
                variable2 = ((VariableDeclarationFragment) parameter2).getName();
            } else {
                return true;
            }
            Expression bodyExpression = null;
            if (lambdaExpression.getBody() instanceof Block) {
                ReturnStatement returnStatement = ASTNodes.as((Block) lambdaExpression.getBody(), ReturnStatement.class);
                if (returnStatement == null) {
                    return true;
                }
                bodyExpression = returnStatement.getExpression();
            } else if (lambdaExpression.getBody() instanceof Expression) {
                bodyExpression = (Expression) lambdaExpression.getBody();
            } else {
                return true;
            }
            if (isReturnedExpressionToRemove(variable1, variable2, bodyExpression, isForward)) {
                return maybeRemoveComparator(visitedIfRefactoringNeeded, list, comparatorToRemove, true, classesToUseWithImport, importsToAdd);
            }
        }
    }
    return true;
}
Also used : ClassInstanceCreation(org.eclipse.jdt.core.dom.ClassInstanceCreation) SingleVariableDeclaration(org.eclipse.jdt.core.dom.SingleVariableDeclaration) SimpleName(org.eclipse.jdt.core.dom.SimpleName) MethodInvocation(org.eclipse.jdt.core.dom.MethodInvocation) Comparator(java.util.Comparator) Function(java.util.function.Function) Expression(org.eclipse.jdt.core.dom.Expression) LambdaExpression(org.eclipse.jdt.core.dom.LambdaExpression) PrefixExpression(org.eclipse.jdt.core.dom.PrefixExpression) VariableDeclarationFragment(org.eclipse.jdt.core.dom.VariableDeclarationFragment) ReturnStatement(org.eclipse.jdt.core.dom.ReturnStatement) ASTNode(org.eclipse.jdt.core.dom.ASTNode) Block(org.eclipse.jdt.core.dom.Block) MethodReference(org.eclipse.jdt.core.dom.MethodReference) List(java.util.List) NullLiteral(org.eclipse.jdt.core.dom.NullLiteral) LambdaExpression(org.eclipse.jdt.core.dom.LambdaExpression)

Example 72 with SingleVariableDeclaration

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

the class ObsoleteSimpleNameRatherThanQualifiedNameCleanUp method visit.

@Override
public boolean visit(final MethodDeclaration visited) {
    // Method parameters
    for (SingleVariableDeclaration parameter : (List<SingleVariableDeclaration>) visited.parameters()) {
        if (!maybeReplaceFqnsWithSimpleNames(parameter)) {
            return false;
        }
    }
    // Method return value
    if (!maybeReplaceFqnsWithSimpleNames(visited.getReturnType2())) {
        return false;
    }
    // Method body
    Set<SimpleName> localIdentifiers = new HashSet<>();
    for (SingleVariableDeclaration localParameter : (List<SingleVariableDeclaration>) visited.parameters()) {
        localIdentifiers.add(localParameter.getName());
    }
    localIdentifiers.addAll(ASTNodes.getLocalVariableIdentifiers(visited.getBody(), true));
    return maybeReplaceFqnsWithSimpleNames(visited.getBody(), localIdentifiers);
}
Also used : SingleVariableDeclaration(org.eclipse.jdt.core.dom.SingleVariableDeclaration) SimpleName(org.eclipse.jdt.core.dom.SimpleName) ArrayList(java.util.ArrayList) List(java.util.List) HashSet(java.util.HashSet)

Example 73 with SingleVariableDeclaration

use of org.eclipse.jdt.core.dom.SingleVariableDeclaration in project eap-additional-testsuite by jboss-set.

the class SourceParser method parse.

public static void parse(String str) throws IOException {
    fields.clear();
    methods.clear();
    imports.clear();
    types.clear();
    ASTParser parser = ASTParser.newParser(AST.JLS3);
    parser.setSource(readFileToString(str).toCharArray());
    parser.setKind(ASTParser.K_COMPILATION_UNIT);
    final CompilationUnit cu = (CompilationUnit) parser.createAST(null);
    cu.accept(new ASTVisitor() {

        Set names = new HashSet();

        int blockCount = 0;

        public boolean visit(FieldDeclaration node) {
            String name = node.fragments().get(0).toString().split("=")[0].trim();
            String type = node.getType().toString();
            if (!node.modifiers().toString().contains("private")) {
                fields.put(name, type);
            }
            ArrayList<String> types0 = new ArrayList<>();
            String type2 = null;
            do {
                if (type.contains("[")) {
                    type = type.replaceAll("\\[\\]", "");
                    if (type.contains("[")) {
                        type = type.substring(0, type.indexOf("["));
                    }
                }
                if (type.contains("<")) {
                    String type3 = type;
                    type = type.substring(0, type.indexOf("<"));
                    if (type3.substring(type3.indexOf("<") + 1).startsWith("<>") || type3.substring(type.indexOf("<") + 1).startsWith("<T>")) {
                        type2 = null;
                    } else if (type3.indexOf("<") >= 0 && type3.indexOf(">") >= 0 && type3.indexOf("<") < type3.indexOf(">")) {
                        type2 = type3.substring(type3.indexOf("<") + 1, type3.lastIndexOf(">"));
                        if (type2.contains(",")) {
                            if (type2.substring(0, type2.indexOf(",")).contains("<")) {
                                types0.add(type2);
                            } else {
                                types0.add(type2.substring(0, type2.indexOf(",")));
                                types0.add(type2.substring(type2.indexOf(",") + 1));
                            }
                        } else {
                            types0.add(type2);
                        }
                    }
                }
                types.addAll(Arrays.asList(type.split(" extends ")));
                if (types0.size() != 0) {
                    type = types0.remove(0);
                } else {
                    type = null;
                }
            } while (type != null);
            return true;
        }

        public boolean visit(MethodDeclaration node) {
            if (node.getName().getIdentifier() != null) {
                MethodInfo2 mf = new MethodInfo2();
                mf.name = node.getName().toString();
                if (node.getReturnType2() != null) {
                    mf.returnType = node.getReturnType2().toString();
                } else {
                    mf.returnType = null;
                }
                List params = node.parameters();
                ArrayList<String> types = new ArrayList<>();
                // System.out.println("params : " + params.toString());
                for (Object s : params) {
                    String type = ((SingleVariableDeclaration) s).getType().toString();
                    if (type.startsWith("class "))
                        type = type.replaceFirst("class ", "");
                    types.add(type);
                }
                // System.out.println("sourceTypes : " + types.toString());
                mf.paramTypes = types;
                methods.put(mf.name, mf);
            }
            return true;
        }

        public boolean visit(ImportDeclaration node) {
            imports.add(node.getName().toString());
            return true;
        }

        public boolean visit(PackageDeclaration node) {
            packageName = node.getName().toString();
            return true;
        }
    });
}
Also used : CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) Set(java.util.Set) HashSet(java.util.HashSet) MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) SingleVariableDeclaration(org.eclipse.jdt.core.dom.SingleVariableDeclaration) ArrayList(java.util.ArrayList) FieldDeclaration(org.eclipse.jdt.core.dom.FieldDeclaration) ASTVisitor(org.eclipse.jdt.core.dom.ASTVisitor) ImportDeclaration(org.eclipse.jdt.core.dom.ImportDeclaration) ArrayList(java.util.ArrayList) List(java.util.List) ASTParser(org.eclipse.jdt.core.dom.ASTParser) PackageDeclaration(org.eclipse.jdt.core.dom.PackageDeclaration) HashSet(java.util.HashSet)

Example 74 with SingleVariableDeclaration

use of org.eclipse.jdt.core.dom.SingleVariableDeclaration in project che by eclipse.

the class VariableDeclarationFix method createAddFinalOperation.

private static ModifierChangeOperation createAddFinalOperation(SimpleName name, ASTNode decl) {
    if (decl == null)
        return null;
    IBinding binding = name.resolveBinding();
    if (!canAddFinal(binding, decl))
        return null;
    if (decl instanceof SingleVariableDeclaration) {
        return new ModifierChangeOperation(decl, new ArrayList<VariableDeclarationFragment>(), Modifier.FINAL, Modifier.NONE);
    } else if (decl instanceof VariableDeclarationExpression) {
        return new ModifierChangeOperation(decl, new ArrayList<VariableDeclarationFragment>(), Modifier.FINAL, Modifier.NONE);
    } else if (decl instanceof VariableDeclarationFragment) {
        VariableDeclarationFragment frag = (VariableDeclarationFragment) decl;
        decl = decl.getParent();
        if (decl instanceof FieldDeclaration || decl instanceof VariableDeclarationStatement) {
            List<VariableDeclarationFragment> list = new ArrayList<VariableDeclarationFragment>();
            list.add(frag);
            return new ModifierChangeOperation(decl, list, Modifier.FINAL, Modifier.NONE);
        } else if (decl instanceof VariableDeclarationExpression) {
            return new ModifierChangeOperation(decl, new ArrayList<VariableDeclarationFragment>(), Modifier.FINAL, Modifier.NONE);
        }
    }
    return null;
}
Also used : SingleVariableDeclaration(org.eclipse.jdt.core.dom.SingleVariableDeclaration) VariableDeclarationFragment(org.eclipse.jdt.core.dom.VariableDeclarationFragment) IBinding(org.eclipse.jdt.core.dom.IBinding) VariableDeclarationExpression(org.eclipse.jdt.core.dom.VariableDeclarationExpression) ArrayList(java.util.ArrayList) VariableDeclarationStatement(org.eclipse.jdt.core.dom.VariableDeclarationStatement) FieldDeclaration(org.eclipse.jdt.core.dom.FieldDeclaration)

Example 75 with SingleVariableDeclaration

use of org.eclipse.jdt.core.dom.SingleVariableDeclaration in project che by eclipse.

the class ExtractMethodRefactoring method createNewMethodDeclaration.

private MethodDeclaration createNewMethodDeclaration() {
    MethodDeclaration result = fAST.newMethodDeclaration();
    int modifiers = fVisibility;
    BodyDeclaration enclosingBodyDeclaration = fAnalyzer.getEnclosingBodyDeclaration();
    boolean isDestinationInterface = isDestinationInterface();
    if (isDestinationInterface && !(enclosingBodyDeclaration instanceof MethodDeclaration && enclosingBodyDeclaration.getParent() == fDestination && Modifier.isPublic(enclosingBodyDeclaration.getModifiers()))) {
        modifiers = Modifier.NONE;
    }
    boolean shouldBeStatic = false;
    ASTNode currentParent = enclosingBodyDeclaration;
    do {
        if (currentParent instanceof BodyDeclaration) {
            shouldBeStatic = shouldBeStatic || JdtFlags.isStatic((BodyDeclaration) currentParent);
        }
        currentParent = currentParent.getParent();
    } while (!shouldBeStatic && currentParent != null && currentParent != fDestination);
    if (shouldBeStatic || fAnalyzer.getForceStatic() || forceStatic()) {
        modifiers |= Modifier.STATIC;
    } else if (isDestinationInterface) {
        modifiers |= Modifier.DEFAULT;
    }
    ITypeBinding[] typeVariables = computeLocalTypeVariables(modifiers);
    List<TypeParameter> typeParameters = result.typeParameters();
    for (int i = 0; i < typeVariables.length; i++) {
        TypeParameter parameter = fAST.newTypeParameter();
        parameter.setName(fAST.newSimpleName(typeVariables[i].getName()));
        ITypeBinding[] bounds = typeVariables[i].getTypeBounds();
        for (int j = 0; j < bounds.length; j++) if (//$NON-NLS-1$
        !"java.lang.Object".equals(bounds[j].getQualifiedName()))
            parameter.typeBounds().add(fImportRewriter.addImport(bounds[j], fAST));
        typeParameters.add(parameter);
    }
    result.modifiers().addAll(ASTNodeFactory.newModifiers(fAST, modifiers));
    result.setReturnType2((Type) ASTNode.copySubtree(fAST, fAnalyzer.getReturnType()));
    result.setName(fAST.newSimpleName(fMethodName));
    ImportRewriteContext context = new ContextSensitiveImportRewriteContext(enclosingBodyDeclaration, fImportRewriter);
    List<SingleVariableDeclaration> parameters = result.parameters();
    for (int i = 0; i < fParameterInfos.size(); i++) {
        ParameterInfo info = fParameterInfos.get(i);
        VariableDeclaration infoDecl = getVariableDeclaration(info);
        SingleVariableDeclaration parameter = fAST.newSingleVariableDeclaration();
        parameter.modifiers().addAll(ASTNodeFactory.newModifiers(fAST, ASTNodes.getModifiers(infoDecl)));
        parameter.setType(ASTNodeFactory.newType(fAST, infoDecl, fImportRewriter, context));
        parameter.setName(fAST.newSimpleName(info.getNewName()));
        parameter.setVarargs(info.isNewVarargs());
        parameters.add(parameter);
    }
    List<Type> exceptions = result.thrownExceptionTypes();
    ITypeBinding[] exceptionTypes = fAnalyzer.getExceptions(fThrowRuntimeExceptions);
    for (int i = 0; i < exceptionTypes.length; i++) {
        ITypeBinding exceptionType = exceptionTypes[i];
        exceptions.add(fImportRewriter.addImport(exceptionType, fAST, context));
    }
    return result;
}
Also used : TypeParameter(org.eclipse.jdt.core.dom.TypeParameter) MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) SingleVariableDeclaration(org.eclipse.jdt.core.dom.SingleVariableDeclaration) ParameterInfo(org.eclipse.jdt.internal.corext.refactoring.ParameterInfo) ContextSensitiveImportRewriteContext(org.eclipse.jdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext) Type(org.eclipse.jdt.core.dom.Type) ImportRewriteContext(org.eclipse.jdt.core.dom.rewrite.ImportRewrite.ImportRewriteContext) ContextSensitiveImportRewriteContext(org.eclipse.jdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding) ASTNode(org.eclipse.jdt.core.dom.ASTNode) BodyDeclaration(org.eclipse.jdt.core.dom.BodyDeclaration) VariableDeclaration(org.eclipse.jdt.core.dom.VariableDeclaration) SingleVariableDeclaration(org.eclipse.jdt.core.dom.SingleVariableDeclaration)

Aggregations

SingleVariableDeclaration (org.eclipse.jdt.core.dom.SingleVariableDeclaration)124 ITypeBinding (org.eclipse.jdt.core.dom.ITypeBinding)41 MethodDeclaration (org.eclipse.jdt.core.dom.MethodDeclaration)39 Type (org.eclipse.jdt.core.dom.Type)37 Block (org.eclipse.jdt.core.dom.Block)35 ASTNode (org.eclipse.jdt.core.dom.ASTNode)33 AST (org.eclipse.jdt.core.dom.AST)32 ArrayList (java.util.ArrayList)29 List (java.util.List)27 SimpleName (org.eclipse.jdt.core.dom.SimpleName)27 VariableDeclarationFragment (org.eclipse.jdt.core.dom.VariableDeclarationFragment)27 VariableDeclarationStatement (org.eclipse.jdt.core.dom.VariableDeclarationStatement)26 Expression (org.eclipse.jdt.core.dom.Expression)22 CompilationUnit (org.eclipse.jdt.core.dom.CompilationUnit)20 MethodInvocation (org.eclipse.jdt.core.dom.MethodInvocation)18 ImportRewriteContext (org.eclipse.jdt.core.dom.rewrite.ImportRewrite.ImportRewriteContext)18 PrimitiveType (org.eclipse.jdt.core.dom.PrimitiveType)17 ICompilationUnit (org.eclipse.jdt.core.ICompilationUnit)16 ReturnStatement (org.eclipse.jdt.core.dom.ReturnStatement)16 ASTRewrite (org.eclipse.jdt.core.dom.rewrite.ASTRewrite)16