Search in sources :

Example 41 with ASTVisitor

use of org.eclipse.jdt.core.dom.ASTVisitor 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 42 with ASTVisitor

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

the class ConvertIterableLoopOperation method satisfiesPreconditions.

/**
	 * Is this proposal applicable?
	 *
	 * @return A status with severity <code>IStatus.Error</code> if not
	 *         applicable
	 */
@Override
public final IStatus satisfiesPreconditions() {
    IStatus resultStatus = StatusInfo.OK_STATUS;
    if (JavaModelUtil.is50OrHigher(getJavaProject())) {
        resultStatus = checkExpressionCondition();
        if (resultStatus.getSeverity() == IStatus.ERROR)
            return resultStatus;
        List<Expression> updateExpressions = getForStatement().updaters();
        if (updateExpressions.size() == 1) {
            resultStatus = new StatusInfo(IStatus.WARNING, Messages.format(FixMessages.ConvertIterableLoopOperation_RemoveUpdateExpression_Warning, BasicElementLabels.getJavaCodeString(updateExpressions.get(0).toString())));
        } else if (updateExpressions.size() > 1) {
            resultStatus = new StatusInfo(IStatus.WARNING, FixMessages.ConvertIterableLoopOperation_RemoveUpdateExpressions_Warning);
        }
        for (final Iterator<Expression> outer = getForStatement().initializers().iterator(); outer.hasNext(); ) {
            final Expression initializer = outer.next();
            if (initializer instanceof VariableDeclarationExpression) {
                final VariableDeclarationExpression declaration = (VariableDeclarationExpression) initializer;
                List<VariableDeclarationFragment> fragments = declaration.fragments();
                if (fragments.size() != 1) {
                    //$NON-NLS-1$
                    return new StatusInfo(IStatus.ERROR, "");
                } else {
                    final VariableDeclarationFragment fragment = fragments.get(0);
                    fragment.accept(new ASTVisitor() {

                        @Override
                        public final boolean visit(final MethodInvocation node) {
                            final IMethodBinding binding = node.resolveMethodBinding();
                            if (binding != null) {
                                final ITypeBinding type = binding.getReturnType();
                                if (type != null) {
                                    final String qualified = type.getQualifiedName();
                                    if (qualified.startsWith("java.util.Enumeration<") || qualified.startsWith("java.util.Iterator<")) {
                                        //$NON-NLS-1$ //$NON-NLS-2$
                                        final Expression qualifier = node.getExpression();
                                        if (qualifier != null) {
                                            final ITypeBinding resolved = qualifier.resolveTypeBinding();
                                            if (resolved != null) {
                                                //$NON-NLS-1$
                                                final ITypeBinding iterable = getSuperType(resolved, "java.lang.Iterable");
                                                if (iterable != null) {
                                                    fExpression = qualifier;
                                                    fIterable = resolved;
                                                }
                                            }
                                        } else {
                                            final ITypeBinding declaring = binding.getDeclaringClass();
                                            if (declaring != null) {
                                                //$NON-NLS-1$
                                                final ITypeBinding superBinding = getSuperType(declaring, "java.lang.Iterable");
                                                if (superBinding != null) {
                                                    fIterable = superBinding;
                                                    fThis = true;
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                            return true;
                        }

                        @Override
                        public final boolean visit(final VariableDeclarationFragment node) {
                            final IVariableBinding binding = node.resolveBinding();
                            if (binding != null) {
                                final ITypeBinding type = binding.getType();
                                if (type != null) {
                                    //$NON-NLS-1$
                                    ITypeBinding iterator = getSuperType(type, "java.util.Iterator");
                                    if (iterator != null)
                                        fIteratorVariable = binding;
                                    else {
                                        //$NON-NLS-1$
                                        iterator = getSuperType(type, "java.util.Enumeration");
                                        if (iterator != null)
                                            fIteratorVariable = binding;
                                    }
                                }
                            }
                            return true;
                        }
                    });
                }
            }
        }
        final Statement statement = getForStatement().getBody();
        final boolean[] otherInvocationThenNext = new boolean[] { false };
        final int[] nextInvocationCount = new int[] { 0 };
        if (statement != null && fIteratorVariable != null) {
            final ITypeBinding elementType = getElementType(fIteratorVariable.getType());
            statement.accept(new ASTVisitor() {

                @Override
                public boolean visit(SimpleName node) {
                    IBinding nodeBinding = node.resolveBinding();
                    if (fElementVariable != null && fElementVariable.equals(nodeBinding)) {
                        fMakeFinal = false;
                    }
                    if (nodeBinding == fIteratorVariable) {
                        if (node.getLocationInParent() == MethodInvocation.EXPRESSION_PROPERTY) {
                            MethodInvocation invocation = (MethodInvocation) node.getParent();
                            String name = invocation.getName().getIdentifier();
                            if (name.equals("next") || name.equals("nextElement")) {
                                //$NON-NLS-1$ //$NON-NLS-2$
                                nextInvocationCount[0]++;
                                Expression left = null;
                                if (invocation.getLocationInParent() == Assignment.RIGHT_HAND_SIDE_PROPERTY) {
                                    left = ((Assignment) invocation.getParent()).getLeftHandSide();
                                } else if (invocation.getLocationInParent() == VariableDeclarationFragment.INITIALIZER_PROPERTY) {
                                    left = ((VariableDeclarationFragment) invocation.getParent()).getName();
                                }
                                return visitElementVariable(left);
                            }
                        }
                        otherInvocationThenNext[0] = true;
                    }
                    return true;
                }

                private boolean visitElementVariable(final Expression node) {
                    if (node != null) {
                        final ITypeBinding binding = node.resolveTypeBinding();
                        if (binding != null && elementType.equals(binding)) {
                            if (node instanceof Name) {
                                final Name name = (Name) node;
                                final IBinding result = name.resolveBinding();
                                if (result != null) {
                                    fOccurrences.add(node);
                                    fElementVariable = result;
                                    return false;
                                }
                            } else if (node instanceof FieldAccess) {
                                final FieldAccess access = (FieldAccess) node;
                                final IBinding result = access.resolveFieldBinding();
                                if (result != null) {
                                    fOccurrences.add(node);
                                    fElementVariable = result;
                                    return false;
                                }
                            }
                        }
                    }
                    return true;
                }
            });
            if (otherInvocationThenNext[0])
                return ERROR_STATUS;
            if (nextInvocationCount[0] > 1)
                return ERROR_STATUS;
            if (fElementVariable != null) {
                statement.accept(new ASTVisitor() {

                    @Override
                    public final boolean visit(final VariableDeclarationFragment node) {
                        if (node.getInitializer() instanceof NullLiteral) {
                            SimpleName name = node.getName();
                            if (elementType.equals(name.resolveTypeBinding()) && fElementVariable.equals(name.resolveBinding())) {
                                fOccurrences.add(name);
                            }
                        }
                        return true;
                    }
                });
            }
        }
        final ASTNode root = getForStatement().getRoot();
        if (root != null) {
            root.accept(new ASTVisitor() {

                @Override
                public final boolean visit(final ForStatement node) {
                    return false;
                }

                @Override
                public final boolean visit(final SimpleName node) {
                    final IBinding binding = node.resolveBinding();
                    if (binding != null && binding.equals(fElementVariable))
                        fAssigned = true;
                    return false;
                }
            });
        }
    }
    if ((fExpression != null || fThis) && fIterable != null && fIteratorVariable != null && !fAssigned) {
        return resultStatus;
    } else {
        return ERROR_STATUS;
    }
}
Also used : IMethodBinding(org.eclipse.jdt.core.dom.IMethodBinding) IStatus(org.eclipse.core.runtime.IStatus) SimpleName(org.eclipse.jdt.core.dom.SimpleName) IBinding(org.eclipse.jdt.core.dom.IBinding) MethodInvocation(org.eclipse.jdt.core.dom.MethodInvocation) SimpleName(org.eclipse.jdt.core.dom.SimpleName) Name(org.eclipse.jdt.core.dom.Name) Assignment(org.eclipse.jdt.core.dom.Assignment) VariableDeclarationFragment(org.eclipse.jdt.core.dom.VariableDeclarationFragment) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding) ASTNode(org.eclipse.jdt.core.dom.ASTNode) ForStatement(org.eclipse.jdt.core.dom.ForStatement) EnhancedForStatement(org.eclipse.jdt.core.dom.EnhancedForStatement) Statement(org.eclipse.jdt.core.dom.Statement) ForStatement(org.eclipse.jdt.core.dom.ForStatement) EnhancedForStatement(org.eclipse.jdt.core.dom.EnhancedForStatement) VariableDeclarationExpression(org.eclipse.jdt.core.dom.VariableDeclarationExpression) IVariableBinding(org.eclipse.jdt.core.dom.IVariableBinding) ASTVisitor(org.eclipse.jdt.core.dom.ASTVisitor) Expression(org.eclipse.jdt.core.dom.Expression) VariableDeclarationExpression(org.eclipse.jdt.core.dom.VariableDeclarationExpression) StatusInfo(org.eclipse.jdt.internal.ui.dialogs.StatusInfo) FieldAccess(org.eclipse.jdt.core.dom.FieldAccess) NullLiteral(org.eclipse.jdt.core.dom.NullLiteral)

Example 43 with ASTVisitor

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

the class ImportRemover method divideTypeRefs.

private void divideTypeRefs(List<SimpleName> importNames, List<SimpleName> staticNames, List<SimpleName> removedRefs, List<SimpleName> unremovedRefs) {
    final List<int[]> removedStartsEnds = new ArrayList<int[]>();
    fRoot.accept(new ASTVisitor(true) {

        int fRemovingStart = -1;

        @Override
        public void preVisit(ASTNode node) {
            Object property = node.getProperty(PROPERTY_KEY);
            if (property == REMOVED) {
                if (fRemovingStart == -1) {
                    fRemovingStart = node.getStartPosition();
                } else {
                    /*
						 * Bug in client code: REMOVED node should not be nested inside another REMOVED node without
						 * an intermediate RETAINED node.
						 * Drop REMOVED property to prevent problems later (premature end of REMOVED section).
						 */
                    node.setProperty(PROPERTY_KEY, null);
                }
            } else if (property == RETAINED) {
                if (fRemovingStart != -1) {
                    removedStartsEnds.add(new int[] { fRemovingStart, node.getStartPosition() });
                    fRemovingStart = -1;
                } else {
                    /*
						 * Bug in client code: RETAINED node should not be nested inside another RETAINED node without
						 * an intermediate REMOVED node and must have an enclosing REMOVED node.
						 * Drop RETAINED property to prevent problems later (premature restart of REMOVED section).
						 */
                    node.setProperty(PROPERTY_KEY, null);
                }
            }
            super.preVisit(node);
        }

        @Override
        public void postVisit(ASTNode node) {
            Object property = node.getProperty(PROPERTY_KEY);
            if (property == RETAINED) {
                int end = node.getStartPosition() + node.getLength();
                fRemovingStart = end;
            } else if (property == REMOVED) {
                if (fRemovingStart != -1) {
                    int end = node.getStartPosition() + node.getLength();
                    removedStartsEnds.add(new int[] { fRemovingStart, end });
                    fRemovingStart = -1;
                }
            }
            super.postVisit(node);
        }
    });
    for (Iterator<SimpleName> iterator = importNames.iterator(); iterator.hasNext(); ) {
        SimpleName name = iterator.next();
        if (isInRemoved(name, removedStartsEnds))
            removedRefs.add(name);
        else
            unremovedRefs.add(name);
    }
    for (Iterator<SimpleName> iterator = staticNames.iterator(); iterator.hasNext(); ) {
        SimpleName name = iterator.next();
        if (isInRemoved(name, removedStartsEnds))
            removedRefs.add(name);
        else
            unremovedRefs.add(name);
    }
    for (Iterator<ImportDeclaration> iterator = fInlinedStaticImports.iterator(); iterator.hasNext(); ) {
        ImportDeclaration importDecl = iterator.next();
        Name name = importDecl.getName();
        if (name instanceof QualifiedName)
            name = ((QualifiedName) name).getName();
        removedRefs.add((SimpleName) name);
    }
}
Also used : SimpleName(org.eclipse.jdt.core.dom.SimpleName) QualifiedName(org.eclipse.jdt.core.dom.QualifiedName) ArrayList(java.util.ArrayList) ASTVisitor(org.eclipse.jdt.core.dom.ASTVisitor) SimpleName(org.eclipse.jdt.core.dom.SimpleName) Name(org.eclipse.jdt.core.dom.Name) QualifiedName(org.eclipse.jdt.core.dom.QualifiedName) ASTNode(org.eclipse.jdt.core.dom.ASTNode) ImportDeclaration(org.eclipse.jdt.core.dom.ImportDeclaration)

Example 44 with ASTVisitor

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

the class ASTUtils method findAllOccurrences.

protected static List<SimpleName> findAllOccurrences(ASTNode root, String bindingKey) {
    List<SimpleName> occurences = new ArrayList<>();
    root.getRoot().accept(new ASTVisitor() {

        @Override
        public boolean visit(SimpleName name) {
            IBinding binding = resolveBinding(name);
            if (binding != null && bindingKey.equals(binding.getKey())) {
                occurences.add(name);
            }
            return super.visit(name);
        }
    });
    return occurences;
}
Also used : SimpleName(org.eclipse.jdt.core.dom.SimpleName) IBinding(org.eclipse.jdt.core.dom.IBinding) ArrayList(java.util.ArrayList) ASTVisitor(org.eclipse.jdt.core.dom.ASTVisitor)

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

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