Search in sources :

Example 21 with ASTVisitor

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

the class ASTUtils method getSimpleNameChildren.

public static List<SimpleName> getSimpleNameChildren(ASTNode node) {
    List<SimpleName> simpleNames = new ArrayList<>();
    node.accept(new ASTVisitor() {

        @Override
        public boolean visit(SimpleName simpleName) {
            simpleNames.add(simpleName);
            return super.visit(simpleName);
        }
    });
    return simpleNames;
}
Also used : SimpleName(org.eclipse.jdt.core.dom.SimpleName) ArrayList(java.util.ArrayList) ASTVisitor(org.eclipse.jdt.core.dom.ASTVisitor)

Example 22 with ASTVisitor

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

the class ApplyRefactoringsJob method applyRefactoring.

/**
     * Applies the refactorings 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
     * @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 void applyRefactoring(IDocument document, ICompilationUnit compilationUnit, AggregateASTVisitor refactoring, JavaProjectOptions options, IProgressMonitor monitor) throws Exception {
    // creation of DOM/AST from a ICompilationUnit
    final ASTParser parser = ASTParser.newParser(AST.JLS4);
    resetParser(compilationUnit, parser, options);
    CompilationUnit astRoot = (CompilationUnit) parser.createAST(null);
    int totalNbLoops = 0;
    Set<ASTVisitor> lastLoopVisitors = Collections.emptySet();
    int nbLoopsWithSameVisitors = 0;
    while (true) {
        if (totalNbLoops > 100) {
            // Oops! Something went wrong.
            final String errorMsg = "An infinite loop has been detected for file " + getFileName(astRoot) + "." + " A possible cause is that code is being incorrectly" + " refactored one way then refactored back to what it was." + " Fix the code before pursuing." + getPossibleCulprits(nbLoopsWithSameVisitors, lastLoopVisitors);
            environment.getLogger().error(errorMsg, new IllegalStateException(astRoot, errorMsg));
            break;
        }
        final RefactoringContext ctx = new RefactoringContext(compilationUnit, astRoot, options, monitor, environment);
        refactoring.setRefactoringContext(ctx);
        final Refactorings refactorings = refactoring.getRefactorings(astRoot);
        if (!refactorings.hasRefactorings()) {
            // we are done with applying the refactorings.
            return;
        }
        // apply the refactorings and save the compilation unit
        refactorings.applyTo(document);
        final boolean hadUnsavedChanges = compilationUnit.hasUnsavedChanges();
        compilationUnit.getBuffer().setContents(document.get());
        // , null, null);
        if (!hadUnsavedChanges) {
            compilationUnit.save(null, true);
        }
        // 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);
        ++totalNbLoops;
        final Set<ASTVisitor> thisLoopVisitors = refactoring.getVisitorsContributingRefactoring();
        if (!thisLoopVisitors.equals(lastLoopVisitors)) {
            lastLoopVisitors = new HashSet<ASTVisitor>(thisLoopVisitors);
            nbLoopsWithSameVisitors = 0;
        } else {
            ++nbLoopsWithSameVisitors;
        }
    }
}
Also used : ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) IllegalStateException(org.autorefactor.util.IllegalStateException) ASTParser(org.eclipse.jdt.core.dom.ASTParser) RefactoringContext(org.autorefactor.refactoring.rules.RefactoringContext) AggregateASTVisitor(org.autorefactor.refactoring.rules.AggregateASTVisitor) ASTVisitor(org.eclipse.jdt.core.dom.ASTVisitor)

Example 23 with ASTVisitor

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

the class AbstractBuildErrorDetailsHandler method createFieldMarkerData.

/**
     * Create a marker on a Java Method
     *
     * @param javaProject
     * @param className
     *            - the fully qualified class name (e.g java.lang.String)
     * @param methodName
     * @param methodSignature
     *            - signatures are in "internal form" e.g. (Ljava.lang.Integer;[Ljava/lang/String;Z)V
     * @param markerAttributes
     *            - attributes that should be included in the marker, typically a message. The start and end points for
     *            the marker are added by this method.
     * @param hasResolutions
     *            - true if the marker will have resolutions
     * @return Marker Data that can be used to create an {@link IMarker}, or null if no location can be found
     * @throws JavaModelException
     */
public static final MarkerData createFieldMarkerData(IJavaProject javaProject, final String className, final String fieldName, final Map<String, Object> markerAttributes, boolean hasResolutions) throws JavaModelException {
    final CompilationUnit ast = createAST(javaProject, className);
    if (ast == null)
        return null;
    ast.accept(new ASTVisitor() {

        @Override
        public boolean visit(FieldDeclaration fieldDecl) {
            if (matches(ast, fieldDecl, fieldName)) {
                // Create the marker attribs here
                markerAttributes.put(IMarker.CHAR_START, fieldDecl.getStartPosition());
                markerAttributes.put(IMarker.CHAR_END, fieldDecl.getStartPosition() + fieldDecl.getLength());
            }
            return false;
        }

        private boolean matches(@SuppressWarnings("unused") CompilationUnit ast, FieldDeclaration fieldDecl, String fieldName) {
            @SuppressWarnings("unchecked") List<VariableDeclarationFragment> list = (List<VariableDeclarationFragment>) fieldDecl.getStructuralProperty(FieldDeclaration.FRAGMENTS_PROPERTY);
            for (VariableDeclarationFragment vdf : list) {
                if (fieldName.equals(vdf.getName().toString())) {
                    return true;
                }
            }
            return false;
        }
    });
    if (!markerAttributes.containsKey(IMarker.CHAR_START))
        return null;
    return new MarkerData(ast.getJavaElement().getResource(), markerAttributes, hasResolutions);
}
Also used : ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) VariableDeclarationFragment(org.eclipse.jdt.core.dom.VariableDeclarationFragment) List(java.util.List) FieldDeclaration(org.eclipse.jdt.core.dom.FieldDeclaration) ASTVisitor(org.eclipse.jdt.core.dom.ASTVisitor)

Example 24 with ASTVisitor

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

the class BaselineErrorHandler method generateAddedMethodMarker.

/*
    List<MarkerData> generateAddedTypeMarker(IJavaProject javaProject, String name, Delta ifAdded) {
        // TODO Auto-generated method stub
        return null;
    }
    */
List<MarkerData> generateAddedMethodMarker(IJavaProject javaProject, String className, final String methodName, final Delta requiresDelta) throws JavaModelException {
    final List<MarkerData> markers = new LinkedList<MarkerData>();
    final CompilationUnit ast = createAST(javaProject, className);
    if (ast != null) {
        ast.accept(new ASTVisitor() {

            @Override
            public boolean visit(MethodDeclaration methodDecl) {
                String signature = ASTUtil.buildMethodSignature(methodDecl);
                if (signature.equals(methodName)) {
                    // Create the marker attribs here
                    Map<String, Object> attribs = new HashMap<String, Object>();
                    attribs.put(IMarker.CHAR_START, methodDecl.getStartPosition());
                    attribs.put(IMarker.CHAR_END, methodDecl.getStartPosition() + methodDecl.getLength());
                    String message = String.format("This method was added, which requires a %s change to the package.", requiresDelta);
                    attribs.put(IMarker.MESSAGE, message);
                    markers.add(new MarkerData(ast.getJavaElement().getResource(), attribs, false));
                }
                return false;
            }
        });
    }
    return markers;
}
Also used : ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) MarkerData(org.bndtools.build.api.MarkerData) MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) Map(java.util.Map) HashMap(java.util.HashMap) LinkedList(java.util.LinkedList) ASTVisitor(org.eclipse.jdt.core.dom.ASTVisitor)

Example 25 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)

Aggregations

ASTVisitor (org.eclipse.jdt.core.dom.ASTVisitor)26 SimpleName (org.eclipse.jdt.core.dom.SimpleName)14 ICompilationUnit (org.eclipse.jdt.core.ICompilationUnit)10 ASTNode (org.eclipse.jdt.core.dom.ASTNode)9 CompilationUnit (org.eclipse.jdt.core.dom.CompilationUnit)9 ArrayList (java.util.ArrayList)8 Name (org.eclipse.jdt.core.dom.Name)7 EnhancedForStatement (org.eclipse.jdt.core.dom.EnhancedForStatement)5 ForStatement (org.eclipse.jdt.core.dom.ForStatement)5 IBinding (org.eclipse.jdt.core.dom.IBinding)5 LinkedList (java.util.LinkedList)4 ArrayType (org.eclipse.jdt.core.dom.ArrayType)4 Expression (org.eclipse.jdt.core.dom.Expression)4 ITypeBinding (org.eclipse.jdt.core.dom.ITypeBinding)4 IVariableBinding (org.eclipse.jdt.core.dom.IVariableBinding)4 MethodDeclaration (org.eclipse.jdt.core.dom.MethodDeclaration)4 ParameterizedType (org.eclipse.jdt.core.dom.ParameterizedType)4 SimpleType (org.eclipse.jdt.core.dom.SimpleType)4 Statement (org.eclipse.jdt.core.dom.Statement)4 TypeDeclaration (org.eclipse.jdt.core.dom.TypeDeclaration)4