Search in sources :

Example 51 with ASTVisitor

use of org.eclipse.jdt.core.dom.ASTVisitor in project flux by eclipse.

the class ASTNodes method getQualifiedTypeName.

/**
 * Returns the (potentially qualified) name of a type, followed by array dimensions.
 * Skips type arguments and type annotations.
 *
 * @param type a type that has a name
 * @return the name, followed by array dimensions
 * @since 3.10
 */
public static String getQualifiedTypeName(Type type) {
    final StringBuffer buffer = new StringBuffer();
    ASTVisitor visitor = new ASTVisitor() {

        @Override
        public boolean visit(SimpleType node) {
            buffer.append(node.getName().getFullyQualifiedName());
            return false;
        }

        @Override
        public boolean visit(QualifiedType node) {
            node.getQualifier().accept(this);
            buffer.append('.');
            buffer.append(node.getName().getIdentifier());
            return false;
        }

        @Override
        public boolean visit(NameQualifiedType node) {
            buffer.append(node.getQualifier().getFullyQualifiedName());
            buffer.append('.');
            buffer.append(node.getName().getIdentifier());
            return false;
        }

        @Override
        public boolean visit(ParameterizedType node) {
            node.getType().accept(this);
            return false;
        }

        @Override
        public void endVisit(ArrayType node) {
            for (int i = 0; i < node.dimensions().size(); i++) {
                // $NON-NLS-1$
                buffer.append("[]");
            }
        }
    };
    type.accept(visitor);
    return buffer.toString();
}
Also used : ParameterizedType(org.eclipse.jdt.core.dom.ParameterizedType) ArrayType(org.eclipse.jdt.core.dom.ArrayType) SimpleType(org.eclipse.jdt.core.dom.SimpleType) NameQualifiedType(org.eclipse.jdt.core.dom.NameQualifiedType) QualifiedType(org.eclipse.jdt.core.dom.QualifiedType) NameQualifiedType(org.eclipse.jdt.core.dom.NameQualifiedType) ASTVisitor(org.eclipse.jdt.core.dom.ASTVisitor)

Example 52 with ASTVisitor

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

the class SuppressWarningsQuickFix method findBodyDeclaration.

private BodyDeclaration findBodyDeclaration(final ASTNode node) {
    final BodyDeclaration[] bodyDeclaration = new BodyDeclaration[1];
    node.accept(new ASTVisitor() {

        @Override
        public boolean visit(final EnumDeclaration node) {
            bodyDeclaration[0] = node;
            return false;
        }

        @Override
        public boolean visit(final TypeDeclaration node) {
            bodyDeclaration[0] = node;
            return false;
        }

        @Override
        public boolean visit(final AnnotationTypeDeclaration node) {
            bodyDeclaration[0] = node;
            return false;
        }
    });
    return bodyDeclaration[0];
}
Also used : AnnotationTypeDeclaration(org.eclipse.jdt.core.dom.AnnotationTypeDeclaration) BodyDeclaration(org.eclipse.jdt.core.dom.BodyDeclaration) AnnotationTypeDeclaration(org.eclipse.jdt.core.dom.AnnotationTypeDeclaration) AbstractTypeDeclaration(org.eclipse.jdt.core.dom.AbstractTypeDeclaration) TypeDeclaration(org.eclipse.jdt.core.dom.TypeDeclaration) ASTVisitor(org.eclipse.jdt.core.dom.ASTVisitor) EnumDeclaration(org.eclipse.jdt.core.dom.EnumDeclaration)

Example 53 with ASTVisitor

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

the class ApplyRefactoringsJob method applyRefactoring.

/**
 * Applies the cleanups provided inside the {@link AggregateASTVisitor} to
 * the provided {@link ICompilationUnit}.
 *
 * @param document        the document where the compilation unit comes from
 * @param compilationUnit the compilation unit to refactor
 * @param refactoring     the {@link AggregateASTVisitor} to apply to the
 *                        compilation unit
 * @param options         the Java project options used to compile the project
 * @param monitor         the progress monitor of the current job
 * @param hasToSave       hasToSave
 * @return TextEdit
 * @throws Exception if any problem occurs
 *
 * @see <a href=
 *      "http://help.eclipse.org/indigo/index.jsp?topic=%2Forg.eclipse.jdt.doc.isv%2Fguide%2Fjdt_api_manip.htm"
 *      >Eclipse JDT core - Manipulating Java code</a>
 * @see <a href=
 *      "http://help.eclipse.org/indigo/index.jsp?topic=/org.eclipse.platform.doc.isv/guide/workbench_cmd_menus.htm"
 *      > Eclipse Platform Plug-in Developer Guide > Plugging into the workbench
 *      > Basic workbench extension points using commands >
 *      org.eclipse.ui.menus</a>
 * @see <a href=
 *      "http://www.eclipse.org/articles/article.php?file=Article-JavaCodeManipulation_AST/index.html"
 *      >Abstract Syntax Tree > Write it down</a>
 */
public List<TextEdit> applyRefactoring(final IDocument document, final ICompilationUnit compilationUnit, final AggregateASTVisitor refactoring, final JavaProjectOptions options, final SubMonitor monitor, final boolean hasToSave) throws Exception {
    // Creation of DOM/AST from a ICompilationUnit
    @SuppressWarnings("deprecation") ASTParser parser = ASTParser.newParser(AST.JLS8);
    int maxIterations = 100;
    int iterationCount = 0;
    Set<ASTVisitor> lastLoopVisitors = Collections.emptySet();
    int nbLoopsWithSameVisitors = 0;
    List<TextEdit> textEdits = new ArrayList<>();
    monitor.setWorkRemaining(maxIterations);
    CompilationUnit astRoot;
    do {
        // I did not find any other way to directly modify the AST
        // while still keeping the resolved type bindings working.
        // Using astRoot.recordModifications() did not work:
        // type bindings were lost. Is there a way to recover them?
        // FIXME we should find a way to apply all the changes at
        // the AST level and refresh the bindings
        resetParser(compilationUnit, parser, options);
        astRoot = (CompilationUnit) parser.createAST(null);
        if (iterationCount > maxIterations) {
            // Oops! Something went wrong.
            String errorMsg = // $NON-NLS-1$ //$NON-NLS-2$
            "An infinite loop has been detected for file " + ASTNodes.getFileName(astRoot) + "." + // $NON-NLS-1$
            " A possible cause is that code is being incorrectly" + " refactored one way then refactored back to what it was." + // $NON-NLS-1$ //$NON-NLS-2$
            " Fix the code before pursuing." + getPossibleCulprits(nbLoopsWithSameVisitors, lastLoopVisitors);
            environment.getLogger().error(errorMsg, new IllegalStateException(astRoot, errorMsg));
            break;
        }
        CompilationUnitRewrite cuRewrite = new CompilationUnitRewrite(compilationUnit, astRoot, options, monitor, environment);
        refactoring.setRefactoringContext(cuRewrite);
        ASTRewrite refactorings = refactoring.getRefactorings(astRoot);
        if (!refactorings.hasRefactorings()) {
            // We are done with applying the cleanups.
            break;
        }
        // Apply the cleanups and save the compilation unit
        refactorings.applyTo(document, hasToSave);
        textEdits.add(refactorings.getEdits());
        if (!hasToSave) {
            return textEdits;
        }
        boolean hadUnsavedChanges = compilationUnit.hasUnsavedChanges();
        compilationUnit.getBuffer().setContents(document.get());
        // , null, null);
        if (!hadUnsavedChanges && hasToSave) {
            compilationUnit.save(null, true);
        }
        iterationCount++;
        Set<ASTVisitor> thisLoopVisitors = refactoring.getVisitorsContributingRefactoring();
        if (thisLoopVisitors.equals(lastLoopVisitors)) {
            nbLoopsWithSameVisitors++;
        } else {
            lastLoopVisitors = new HashSet<>(thisLoopVisitors);
            nbLoopsWithSameVisitors = 0;
        }
    } while (true);
    return textEdits;
}
Also used : ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) CompilationUnitRewrite(org.autorefactor.jdt.internal.corext.refactoring.structure.CompilationUnitRewrite) IllegalStateException(org.autorefactor.util.IllegalStateException) ArrayList(java.util.ArrayList) ASTVisitor(org.eclipse.jdt.core.dom.ASTVisitor) AggregateASTVisitor(org.autorefactor.jdt.internal.ui.fix.AggregateASTVisitor) TextEdit(org.eclipse.text.edits.TextEdit) ASTRewrite(org.autorefactor.jdt.core.dom.ASTRewrite) ASTParser(org.eclipse.jdt.core.dom.ASTParser)

Example 54 with ASTVisitor

use of org.eclipse.jdt.core.dom.ASTVisitor in project xtext-xtend by eclipse.

the class ASTFlattenerUtils method findDeclaredType.

private Type findDeclaredType(final ASTNode scope, final SimpleName simpleName) {
    final ArrayList<Type> matchesFound = CollectionLiterals.<Type>newArrayList();
    scope.accept(new ASTVisitor() {

        @Override
        public boolean visit(final VariableDeclarationFragment node) {
            boolean _equals = node.getName().getIdentifier().equals(simpleName.getIdentifier());
            if (_equals) {
                final ASTNode parentNode = node.getParent();
                boolean _matched = false;
                if (parentNode instanceof VariableDeclarationStatement) {
                    _matched = true;
                    matchesFound.add(((VariableDeclarationStatement) parentNode).getType());
                }
                if (!_matched) {
                    if (parentNode instanceof FieldDeclaration) {
                        _matched = true;
                        matchesFound.add(((FieldDeclaration) parentNode).getType());
                    }
                }
                if (!_matched) {
                    if (parentNode instanceof VariableDeclarationExpression) {
                        _matched = true;
                        matchesFound.add(((VariableDeclarationExpression) parentNode).getType());
                    }
                }
            }
            return false;
        }

        @Override
        public boolean preVisit2(final ASTNode node) {
            return matchesFound.isEmpty();
        }

        @Override
        public boolean visit(final SingleVariableDeclaration node) {
            boolean _equals = node.getName().getIdentifier().equals(simpleName.getIdentifier());
            if (_equals) {
                matchesFound.add(node.getType());
            }
            return false;
        }
    });
    return IterableExtensions.<Type>head(matchesFound);
}
Also used : Type(org.eclipse.jdt.core.dom.Type) PrimitiveType(org.eclipse.jdt.core.dom.PrimitiveType) VariableDeclarationFragment(org.eclipse.jdt.core.dom.VariableDeclarationFragment) SingleVariableDeclaration(org.eclipse.jdt.core.dom.SingleVariableDeclaration) VariableDeclarationExpression(org.eclipse.jdt.core.dom.VariableDeclarationExpression) ASTNode(org.eclipse.jdt.core.dom.ASTNode) VariableDeclarationStatement(org.eclipse.jdt.core.dom.VariableDeclarationStatement) FieldDeclaration(org.eclipse.jdt.core.dom.FieldDeclaration) ASTVisitor(org.eclipse.jdt.core.dom.ASTVisitor)

Example 55 with ASTVisitor

use of org.eclipse.jdt.core.dom.ASTVisitor in project flow by vaadin.

the class CodeTest method gwtGenerics.

private static void gwtGenerics(File file) throws IOException {
    ASTParser parser = ASTParser.newParser(AST.JLS8);
    String value = FileUtils.readFileToString(file, UTF_8);
    parser.setSource(value.toCharArray());
    parser.setKind(ASTParser.K_COMPILATION_UNIT);
    final CompilationUnit cu = (CompilationUnit) parser.createAST(null);
    cu.accept(new ASTVisitor() {

        Set<String> imports = new HashSet<>();

        String packageName;

        @Override
        public boolean visit(PackageDeclaration node) {
            packageName = node.getName().toString();
            return false;
        }

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

        @Override
        public boolean visit(VariableDeclarationStatement node) {
            for (Object frament : node.fragments()) {
                if (frament instanceof VariableDeclarationFragment) {
                    VariableDeclarationFragment variableDeclaration = (VariableDeclarationFragment) frament;
                    Expression expression = variableDeclaration.getInitializer();
                    if (expression instanceof ClassInstanceCreation) {
                        ClassInstanceCreation classInstanceCreation = (ClassInstanceCreation) expression;
                        Class<?> typeClass = getClass(node.getType());
                        Class<?> instanceClass = getClass(classInstanceCreation.getType());
                        if (typeClass != instanceClass && typeClass.isAssignableFrom(instanceClass)) {
                            fail("Variable type must be the specific implementation in " + node + " in " + file.getName());
                        }
                    }
                }
            }
            return false;
        }

        private Class<?> getClass(Type type) {
            if (type instanceof ArrayType) {
                type = ((ArrayType) type).getElementType();
            }
            if (type instanceof ParameterizedType) {
                type = ((ParameterizedType) type).getType();
            }
            String className = type.toString();
            if (className.indexOf('.') == -1) {
                String dotPrefix = '.' + className;
                for (String i : imports) {
                    if (i.endsWith(dotPrefix)) {
                        className = i;
                        break;
                    }
                }
            }
            Class<?> clas = getClass(className);
            if (clas != null) {
                return clas;
            }
            clas = getClass("java.lang." + className);
            if (clas != null) {
                return clas;
            }
            try {
                String fileName = file.getName();
                fileName = fileName.substring(0, fileName.lastIndexOf('.'));
                if (fileName.equals(className)) {
                    return Class.forName(packageName + '.' + fileName);
                }
                clas = getClass(packageName + '.' + className);
                if (clas != null) {
                    return clas;
                }
                return Class.forName(packageName + '.' + fileName + '$' + className);
            } catch (ClassNotFoundException e) {
                fail("Could not load class " + e);
                return null;
            }
        }

        private Class<?> getClass(String className) {
            try {
                return ClassUtils.getClass(className);
            } catch (ClassNotFoundException e) {
                return null;
            }
        }
    });
}
Also used : CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) ClassInstanceCreation(org.eclipse.jdt.core.dom.ClassInstanceCreation) ASTVisitor(org.eclipse.jdt.core.dom.ASTVisitor) ArrayType(org.eclipse.jdt.core.dom.ArrayType) ParameterizedType(org.eclipse.jdt.core.dom.ParameterizedType) Type(org.eclipse.jdt.core.dom.Type) ArrayType(org.eclipse.jdt.core.dom.ArrayType) ParameterizedType(org.eclipse.jdt.core.dom.ParameterizedType) Expression(org.eclipse.jdt.core.dom.Expression) VariableDeclarationFragment(org.eclipse.jdt.core.dom.VariableDeclarationFragment) ImportDeclaration(org.eclipse.jdt.core.dom.ImportDeclaration) VariableDeclarationStatement(org.eclipse.jdt.core.dom.VariableDeclarationStatement) ASTParser(org.eclipse.jdt.core.dom.ASTParser) PackageDeclaration(org.eclipse.jdt.core.dom.PackageDeclaration) HashSet(java.util.HashSet)

Aggregations

ASTVisitor (org.eclipse.jdt.core.dom.ASTVisitor)66 ArrayList (java.util.ArrayList)27 ASTNode (org.eclipse.jdt.core.dom.ASTNode)20 SimpleName (org.eclipse.jdt.core.dom.SimpleName)20 CompilationUnit (org.eclipse.jdt.core.dom.CompilationUnit)18 ICompilationUnit (org.eclipse.jdt.core.ICompilationUnit)15 List (java.util.List)14 MethodDeclaration (org.eclipse.jdt.core.dom.MethodDeclaration)14 SingleVariableDeclaration (org.eclipse.jdt.core.dom.SingleVariableDeclaration)12 TypeDeclaration (org.eclipse.jdt.core.dom.TypeDeclaration)12 VariableDeclarationStatement (org.eclipse.jdt.core.dom.VariableDeclarationStatement)12 ASTParser (org.eclipse.jdt.core.dom.ASTParser)11 Block (org.eclipse.jdt.core.dom.Block)10 Expression (org.eclipse.jdt.core.dom.Expression)10 ImportDeclaration (org.eclipse.jdt.core.dom.ImportDeclaration)10 Name (org.eclipse.jdt.core.dom.Name)10 Statement (org.eclipse.jdt.core.dom.Statement)10 MethodInvocation (org.eclipse.jdt.core.dom.MethodInvocation)9 SearchResult (com.liferay.blade.api.SearchResult)8 FieldDeclaration (org.eclipse.jdt.core.dom.FieldDeclaration)8