Java 类org.eclipse.jdt.core.dom.ASTVisitor 实例源码

项目:gw4e.project    文件:ClassExtension.java   
/**
 * @param methodname
 * @return
 */
public FieldDeclaration getField(   ) {
    ASTParser parser = ASTParser.newParser(AST.JLS8);
    String s = getStaticVariable ( );
    if (s==null) return null;
    parser.setSource(s.toCharArray());
    parser.setKind(ASTParser.K_COMPILATION_UNIT);
    final  CompilationUnit cu = (CompilationUnit) parser.createAST(null);
    cu.accept(new ASTVisitor() {
        public boolean visit(FieldDeclaration node) {
            field = node;
            return true;
        }
    });      
    return field;
}
项目:gw4e.project    文件:ClassExtension.java   
/**
 * @return
 */
public NormalAnnotation getGraphWalkerClassAnnotation() {
    String source = getSource ();
    if(source==null) return null;
    ASTParser parser = ASTParser.newParser(AST.JLS8);
    parser.setSource(source.toCharArray());
    parser.setKind(ASTParser.K_COMPILATION_UNIT);
    final CompilationUnit cu = (CompilationUnit) parser.createAST(null);
    cu.accept(new ASTVisitor() {
        public boolean visit(NormalAnnotation node) {
            annotation = node;
            return true;
        }
    });
    if (this.generateAnnotation) return annotation;
    return null;
}
项目:eclipse.jdt.ls    文件:ASTNodes.java   
public static SimpleName getLeftMostSimpleName(Name name) {
    if (name instanceof SimpleName) {
        return (SimpleName)name;
    } else {
        final SimpleName[] result= new SimpleName[1];
        ASTVisitor visitor= new ASTVisitor() {
            @Override
            public boolean visit(QualifiedName qualifiedName) {
                Name left= qualifiedName.getQualifier();
                if (left instanceof SimpleName) {
                    result[0]= (SimpleName)left;
                } else {
                    left.accept(this);
                }
                return false;
            }
        };
        name.accept(visitor);
        return result[0];
    }
}
项目:code    文件:GenerateDefaultMap.java   
private void analyzeCompilationUnit(CompilationUnit unit, ICompilationUnit compilationUnit) {
    Set<String> filters = loadFilters();
    ASTVisitor importsVisitor = new ImportsVisitor(filters);
    unit.accept(importsVisitor);

    List types = unit.types();
    for (Iterator iter = types.iterator(); iter.hasNext();) {
        Object next = iter.next();
        if (next instanceof TypeDeclaration) {
            // declaration: Contains one file content at a time.
            TypeDeclaration declaration = (TypeDeclaration) next;
            // traverseType(declaration,true);

        }
    }
}
项目:gw4e.project    文件:ClassExtension.java   
public NormalAnnotation getGeneratedClassAnnotation() {
    String source = getGeneratedAnnotationSource ();
    if(source==null) return null;
    ASTParser parser = ASTParser.newParser(AST.JLS8);
    parser.setSource(source.toCharArray());
    parser.setKind(ASTParser.K_COMPILATION_UNIT);
    final CompilationUnit cu = (CompilationUnit) parser.createAST(null);
    cu.accept(new ASTVisitor() {
        public boolean visit(NormalAnnotation node) {
            annotation = node;
            return true;
        }
    });
    return annotation;

}
项目:gw4e.project    文件:JDTManager.java   
/**
 * @param cu
 * @return
 */
public static String findPathGeneratorInGraphWalkerAnnotation(ICompilationUnit cu) {
    CompilationUnit ast = parse(cu);
    Map<String, String> ret = new HashMap<String, String>();
    ast.accept(new ASTVisitor() {
        public boolean visit(MemberValuePair node) {
            String name = node.getName().getFullyQualifiedName();
            if ("value".equals(name) && node.getParent() != null && node.getParent() instanceof NormalAnnotation) {
                IAnnotationBinding annoBinding = ((NormalAnnotation) node.getParent()).resolveAnnotationBinding();
                String qname = annoBinding.getAnnotationType().getQualifiedName();
                if (GraphWalker.class.getName().equals(qname)) {
                    StringLiteral sl = (StringLiteral) node.getValue();
                    ret.put("ret", sl.getLiteralValue());
                }
            }
            return true;
        }
    });
    return ret.get("ret");
}
项目:junit2spock    文件:GroovyClosure.java   
@Override
public Object intercept(Object o, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
    switch (method.getName()) {
        case "appendDebugString":
            return ((StringBuffer) args[0]).append(groovyClosure.toString());
        case "getNodeType0":
            return NODE_TYPE;
        case "accept0":
            ASTVisitor visitor = ((ASTVisitor) args[0]);
            if (visitor instanceof NaiveASTFlattener) {
                Field field = findField(NaiveASTFlattener.class, "buffer");
                makeAccessible(field);
                ((StringBuffer) field.get(visitor)).append(groovyClosure.toString());
            } else {
                throw new UnsupportedOperationException();
            }
            return null;
        default:
            makeAccessible(method);
            return methodProxy.invokeSuper(o, args);
    }
}
项目:gwt-eclipse-plugin    文件:EquivalentNodeFinder.java   
/**
 * Finds the equivalent AST node, or null if one could not be found.
 */
public ASTNode find() {
  final ASTNode foundNode[] = new ASTNode[1];
  newAncestorNode.accept(new ASTVisitor(true) {
    @Override
    public void preVisit(ASTNode visitedNode) {
      if (foundNode[0] != null) {
        // Already found a result, do not search further
        return;
      }

      if (!treesMatch(originalNode, visitedNode, ancestorNode,
          newAncestorNode, matcher)) {
        // Keep searching
        return;
      }

      foundNode[0] = visitedNode;

      // We are done
    }
  });

  return foundNode[0];
}
项目:Convert-For-Each-Loop-to-Lambda-Expression-Eclipse-Plugin    文件:ForeachLoopToLambdaRefactoring.java   
private static Set<EnhancedForStatement> getEnhancedForStatements(IMethod method, IProgressMonitor pm)
        throws JavaModelException {
    ICompilationUnit iCompilationUnit = method.getCompilationUnit();

    // get the ASTParser of the method
    CompilationUnit compilationUnit = RefactoringASTParser.parseWithASTProvider(iCompilationUnit, true,
            new SubProgressMonitor(pm, 1));

    // get the method declaration ASTNode.
    MethodDeclaration methodDeclarationNode = ASTNodeSearchUtil.getMethodDeclarationNode(method, compilationUnit);

    final Set<EnhancedForStatement> statements = new LinkedHashSet<EnhancedForStatement>();
    // extract all enhanced for loop statements in the method.
    methodDeclarationNode.accept(new ASTVisitor() {

        @Override
        public boolean visit(EnhancedForStatement node) {
            statements.add(node);
            return super.visit(node);
        }
    });

    return statements;
}
项目:naturalize    文件:JunkVariableRenamer.java   
/**
 * @param vars
 * @param entry
 * @return
 */
private Set<Integer> getCurrentlyUsedNames(
        final Multimap<ASTNode, Variable> vars,
        final Entry<ASTNode, Variable> entry) {
    // Create a list of all the names that are used in that scope
    final Set<Variable> scopeUsedNames = Sets.newHashSet();
    // Check all the parents & self
    ASTNode currentNode = entry.getKey();
    while (currentNode != null) {
        scopeUsedNames.addAll(vars.get(currentNode));
        currentNode = currentNode.getParent();
    }
    // and now add all children
    final ASTVisitor v = new ASTVisitor() {
        @Override
        public void preVisit(final ASTNode node) {
            scopeUsedNames.addAll(vars.get(node));
        }
    };
    entry.getKey().accept(v);
    // and we're done
    return getUsedIds(scopeUsedNames);
}
项目:Eclipse-Postfix-Code-Completion    文件:ExtractClassRefactoring.java   
private boolean replaceMarker(final ASTRewrite rewrite, final Expression qualifier, Expression assignedValue, final NullLiteral marker) {
    class MarkerReplacer extends ASTVisitor {

        private boolean fReplaced= false;

        @Override
        public boolean visit(NullLiteral node) {
            if (node == marker) {
                rewrite.replace(node, rewrite.createCopyTarget(qualifier), null);
                fReplaced= true;
                return false;
            }
            return true;
        }
    }
    if (assignedValue != null && qualifier != null) {
        MarkerReplacer visitor= new MarkerReplacer();
        assignedValue.accept(visitor);
        return visitor.fReplaced;
    }
    return false;
}
项目:Eclipse-Postfix-Code-Completion    文件:AccessorClassModifier.java   
private ASTNode findField(ASTNode astRoot, final String name) {

        class STOP_VISITING extends RuntimeException {
            private static final long serialVersionUID= 1L;
        }

        final ASTNode[] result= new ASTNode[1];

        try {
            astRoot.accept(new ASTVisitor() {

                @Override
                public boolean visit(VariableDeclarationFragment node) {
                    if (name.equals(node.getName().getFullyQualifiedName())) {
                        result[0]= node.getParent();
                        throw new STOP_VISITING();
                    }
                    return true;
                }
            });
        } catch (STOP_VISITING ex) {
            // stop visiting AST
        }

        return result[0];
    }
项目:Eclipse-Postfix-Code-Completion    文件:ASTNodes.java   
public static SimpleName getLeftMostSimpleName(Name name) {
    if (name instanceof SimpleName) {
        return (SimpleName)name;
    } else {
        final SimpleName[] result= new SimpleName[1];
        ASTVisitor visitor= new ASTVisitor() {
            @Override
            public boolean visit(QualifiedName qualifiedName) {
                Name left= qualifiedName.getQualifier();
                if (left instanceof SimpleName)
                    result[0]= (SimpleName)left;
                else
                    left.accept(this);
                return false;
            }
        };
        name.accept(visitor);
        return result[0];
    }
}
项目:EASyProducer    文件:JavaMethod.java   
/**
 * Returns all statements within a method.
 * 
 * @return Set of all statements
 */
private ArraySet<AbstractJavaStatement> statements() {
    final List<AbstractJavaStatement> list = new ArrayList<AbstractJavaStatement>();
    methodDeclaration.accept(new ASTVisitor() {
        @Override
        public boolean visit(ExpressionStatement node) {
            if (node.getExpression() instanceof MethodInvocation) {
                MethodInvocation methodInvocation = (MethodInvocation) node.getExpression();
                String methodName = methodInvocation.getName().toString();
                if (null != methodInvocation.getExpression()) {
                    ITypeBinding typeBinding = methodInvocation.getExpression().resolveTypeBinding();
                    if (null != typeBinding) {
                        JavaCall javaCall = new JavaCall(node, methodName, typeBinding, JavaMethod.this);
                        list.add(javaCall);
                    }
                }
            }
            return false;
        }
    });
    return new ArraySet<AbstractJavaStatement>(list.toArray(new JavaCall[list.size()]), JavaCall.class);
}
项目:EASyProducer    文件:JavaMethod.java   
/**
 * Returns all statements within a method.
 * 
 * @return Set of all statements
 */
private ArraySet<AbstractJavaStatement> assignments() {
    final List<AbstractJavaStatement> list = new ArrayList<AbstractJavaStatement>();
    methodDeclaration.accept(new ASTVisitor() {
        @Override
        public boolean visit(Assignment node) {
            Expression lhs = node.getLeftHandSide();
            ITypeBinding typeBinding = lhs.resolveTypeBinding();
            Expression rhs = node.getRightHandSide();
            if (rhs instanceof ClassInstanceCreation && node.getParent() instanceof ExpressionStatement) {
                ExpressionStatement parent = (ExpressionStatement) node.getParent();
                JavaAssignment assignment = new JavaAssignment(JavaMethod.this, parent, lhs.toString(), typeBinding,
                        (ClassInstanceCreation) rhs);
                list.add(assignment);
            }
            // TODO SE: (Static) method invocations, e.g. call of another
            // factory are not supported.

            return false;
        }
    });
    return new ArraySet<AbstractJavaStatement>(list.toArray(new JavaAssignment[list.size()]), JavaAssignment.class);
}
项目:EASyProducer    文件:JavaClass.java   
/**
 * Returns the attributes of this class.
 * 
 * @return the attributes
 */
@OperationMeta(returnGenerics = JavaAttribute.class)
public Set<JavaAttribute> attributes() {
    final List<JavaAttribute> list = new ArrayList<JavaAttribute>();
    typeDeclaration.accept(new ASTVisitor() {
        @Override
        public boolean visit(FieldDeclaration node) {
            String attributeName = "";
            Object object = node.fragments().get(0);
            if (object instanceof VariableDeclarationFragment) {
                attributeName = ((VariableDeclarationFragment) object).getName().toString();
            }
            JavaAttribute attribute = new JavaAttribute(node, attributeName, JavaClass.this);
            list.add(attribute);
            return false;
        }
    });
    return new ArraySet<JavaAttribute>(list.toArray(new JavaAttribute[list.size()]), JavaAttribute.class);
}
项目:EASyProducer    文件:JavaClass.java   
/**
 * Returns the specified Java attribute.
 * 
 * @param name
 *            the name of the attribute
 * @return the attribute or <b>null</b> if there is no such attribute
 */
public JavaAttribute getAttributeByName(final String name) {
    final JavaAttribute[] tmp = new JavaAttribute[1];
    typeDeclaration.accept(new ASTVisitor() {
        @Override
        public boolean visit(FieldDeclaration node) {
            String attributeName = "";
            Object object = node.fragments().get(0);
            if (object instanceof VariableDeclarationFragment) {
                attributeName = ((VariableDeclarationFragment) object).getName().toString();
            }
            if (null == tmp[0] && attributeName.equals(name)) {
                tmp[0] = new JavaAttribute(node, attributeName, JavaClass.this);
            }
            return false;
        }
    });
    return tmp[0];
}
项目:ChangeScribe    文件:MethodAnalyzer.java   
public MethodAnalyzer(final MethodDeclaration method) {
    super();
    this.isConstructor = false;
    this.isAnonymous = false;
    this.hasBody = false;
    this.hasStatements = false;
    this.usesNonStaticFinalFields = false;
    this.overridesClone = false;
    this.overridesFinalize = false;
    this.overridesToString = false;
    this.overridesHashCode = false;
    this.overridesEquals = false;
    this.getFields = new HashSet<IVariableBinding>();
    this.propertyFields = new HashSet<IVariableBinding>();
    this.voidAccessorFields = new HashSet<IVariableBinding>();
    this.setFields = new HashSet<IVariableBinding>();
    this.parameters = new LinkedList<VariableInfo>();
    this.variables = new LinkedList<VariableInfo>();
    this.instantiatedReturn = false;
    this.invokedLocalMethods = new HashSet<IMethodBinding>();
    this.invokedExternalMethods = new HashSet<IMethodBinding>();
    this.usedTypes = new LinkedList<TypeInfo>();
    method.accept((ASTVisitor)new MethodVisitor(method));
}
项目:ChangeScribe    文件:MethodAnalyzer.java   
public boolean visit(final Assignment node) {
    final IVariableBinding field = this.getLocalField(node.getLeftHandSide());
    if (field != null) {
        MethodAnalyzer.this.setFields.add(field);
    }
    this.assignedVariableIndex = this.getVariableIndex(node.getLeftHandSide());
    if (this.assignedVariableIndex != -1) {
        MethodAnalyzer.this.variables.get(this.assignedVariableIndex).setModified(true);
    }
    this.assignedParameterIndex = this.getParameterIndex(node.getLeftHandSide());
    if (this.assignedParameterIndex != -1) {
        MethodAnalyzer.this.parameters.get(this.assignedParameterIndex).setModified(true);
    }
    node.getLeftHandSide().accept((ASTVisitor)this);
    ++this.inAssignmentRightSide;
    node.getRightHandSide().accept((ASTVisitor)this);
    --this.inAssignmentRightSide;
    return false;
}
项目:dominoes    文件:FileNode.java   
private void extractPackage(Repository _repo) throws MissingObjectException, IOException{
    ObjectLoader newFile = _repo.open(this.newObjId);
    String newData = readStream(newFile.openStream());


    ASTParser parser = ASTParser.newParser(AST.JLS3);
    parser.setSource(newData.toCharArray());
    parser.setKind(ASTParser.K_COMPILATION_UNIT);
    Hashtable<String, String> options = JavaCore.getOptions();
    options.put(JavaCore.COMPILER_DOC_COMMENT_SUPPORT, JavaCore.DISABLED);
    parser.setCompilerOptions(options);

    final CompilationUnit cu = (CompilationUnit) parser.createAST(null);

    cu.accept(new ASTVisitor() {

        public boolean visit(PackageDeclaration _package){
            packageName = _package.getName().getFullyQualifiedName();
            return false;
        }
    });
}
项目:dominoes    文件:FileNode.java   
private void extractPackage(Repository _repo) throws MissingObjectException, IOException{
    ObjectLoader newFile = _repo.open(this.newObjId);
    String newData = readStream(newFile.openStream());


    ASTParser parser = ASTParser.newParser(AST.JLS3);
    parser.setSource(newData.toCharArray());
    parser.setKind(ASTParser.K_COMPILATION_UNIT);
    Hashtable<String, String> options = JavaCore.getOptions();
    options.put(JavaCore.COMPILER_DOC_COMMENT_SUPPORT, JavaCore.DISABLED);
    parser.setCompilerOptions(options);

    final CompilationUnit cu = (CompilationUnit) parser.createAST(null);

    cu.accept(new ASTVisitor() {

        public boolean visit(PackageDeclaration _package){
            packageName = _package.getName().getFullyQualifiedName();
            return false;
        }
    });
}
项目:Eclipse-Postfix-Code-Completion-Juno38    文件:ExtractClassRefactoring.java   
private boolean replaceMarker(final ASTRewrite rewrite, final Expression qualifier, Expression assignedValue, final NullLiteral marker) {
    class MarkerReplacer extends ASTVisitor {

        private boolean fReplaced= false;

        @Override
        public boolean visit(NullLiteral node) {
            if (node == marker) {
                rewrite.replace(node, rewrite.createCopyTarget(qualifier), null);
                fReplaced= true;
                return false;
            }
            return true;
        }
    }
    if (assignedValue != null && qualifier != null) {
        MarkerReplacer visitor= new MarkerReplacer();
        assignedValue.accept(visitor);
        return visitor.fReplaced;
    }
    return false;
}
项目:Eclipse-Postfix-Code-Completion-Juno38    文件:AccessorClassModifier.java   
private ASTNode findField(ASTNode astRoot, final String name) {

        class STOP_VISITING extends RuntimeException {
            private static final long serialVersionUID= 1L;
        }

        final ASTNode[] result= new ASTNode[1];

        try {
            astRoot.accept(new ASTVisitor() {

                @Override
                public boolean visit(VariableDeclarationFragment node) {
                    if (name.equals(node.getName().getFullyQualifiedName())) {
                        result[0]= node.getParent();
                        throw new STOP_VISITING();
                    }
                    return true;
                }
            });
        } catch (STOP_VISITING ex) {
            // stop visiting AST
        }

        return result[0];
    }
项目:Eclipse-Postfix-Code-Completion-Juno38    文件:ASTNodes.java   
public static SimpleName getLeftMostSimpleName(Name name) {
    if (name instanceof SimpleName) {
        return (SimpleName)name;
    } else {
        final SimpleName[] result= new SimpleName[1];
        ASTVisitor visitor= new ASTVisitor() {
            @Override
            public boolean visit(QualifiedName qualifiedName) {
                Name left= qualifiedName.getQualifier();
                if (left instanceof SimpleName)
                    result[0]= (SimpleName)left;
                else
                    left.accept(this);
                return false;
            }
        };
        name.accept(visitor);
        return result[0];
    }
}
项目:Eclipse-Postfix-Code-Completion-Juno38    文件:ASTNodes.java   
public static SimpleType getLeftMostSimpleType(QualifiedType type) {
    final SimpleType[] result= new SimpleType[1];
    ASTVisitor visitor= new ASTVisitor() {
        @Override
        public boolean visit(QualifiedType qualifiedType) {
            Type left= qualifiedType.getQualifier();
            if (left instanceof SimpleType)
                result[0]= (SimpleType)left;
            else
                left.accept(this);
            return false;
        }
    };
    type.accept(visitor);
    return result[0];
}
项目:FindBug-for-Domino-Designer    文件:CreateDoPrivilegedBlockResolution.java   
protected void updateLocalVariableDeclarations(final ASTRewrite rewrite, final Set<String> variables, Block block) {
    Assert.isNotNull(rewrite);
    Assert.isNotNull(block);
    Assert.isNotNull(variables);

    final AST ast = rewrite.getAST();
    block.accept(new ASTVisitor() {

        @Override
        public boolean visit(VariableDeclarationFragment fragment) {
            if (variables.contains(fragment.getName().getFullyQualifiedName())) {
                ASTNode parent = fragment.getParent();
                if (parent instanceof VariableDeclarationStatement) {
                    ListRewrite listRewrite = rewrite
                            .getListRewrite(parent, VariableDeclarationStatement.MODIFIERS2_PROPERTY);
                    listRewrite.insertLast(ast.newModifier(ModifierKeyword.FINAL_KEYWORD), null);
                }
            }
            return true;
        }

    });

}
项目:FindBug-for-Domino-Designer    文件:CreateDoPrivilegedBlockResolution.java   
private Set<String> findVariableReferences(List<?> arguments) {
    final Set<String> refs = new HashSet<String>();
    for (Object argumentObj : arguments) {
        Expression argument = (Expression) argumentObj;
        argument.accept(new ASTVisitor() {

            @Override
            public boolean visit(SimpleName node) {
                if (!(node.getParent() instanceof Type)) {
                    refs.add(node.getFullyQualifiedName());
                }
                return true;
            }

        });
    }
    return refs;
}
项目:querybuilder_plugin    文件:MapperHelper.java   
private Map<IType, String> getGetter(IType type, IProgressMonitor pm) {
    final Map<IType, String> childTypes = new HashMap<IType, String>();
    ASTVisitor visitor = new ASTVisitor() {
        @Override
        public boolean visit(MethodDeclaration methodDeclaration) {
            Type returnType = methodDeclaration.getReturnType2();
            String methodName = methodDeclaration.getName().toString();

            if (GetterHelper.isValid(methodName))
                if (!returnType.isPrimitiveType()) //avoiding NullPointerException when some entity attribute is primitive
                    childTypes.put((IType) returnType.resolveBinding().getJavaElement(), GetterHelper.getField(methodName));

            return super.visit(methodDeclaration);
        }
    };
    parse(type.getCompilationUnit(), pm).accept(visitor);
    return childTypes;
}
项目:reflectify    文件:MethodInvocationTest.java   
/** 
 * @return selection (offset,length) of first method invocation node within statement given by <code>statementIndex</code>
 */
private int[] getMethodInvocationSelection(int statementIndex, IMethod target) {
    MethodDeclaration targetNode = compileTargetMethod(target);
    Statement stmt = (Statement) targetNode.getBody().statements().get(statementIndex );
    final int[] selection = new int[2];
    stmt.accept( new ASTVisitor() {
        @Override
        public boolean visit(MethodInvocation node) {
            if (selection[1] == 0) {
                selection[0] = node.getStartPosition();
                selection[1] = node.getLength();
            }
            return false;
        }
    });
    return selection;
}
项目:reflectify    文件:TestBase.java   
@SuppressWarnings("deprecation")
protected MethodDeclaration compileTargetMethod(final IMethod target) {
    ASTParser p = ASTParser.newParser(AST.JLS3);
    p.setSource(target.getCompilationUnit());
    p.setResolveBindings(true);
    CompilationUnit unit = (CompilationUnit) p.createAST(PROGRESS_MONITOR);
    final MethodDeclaration[] result = new MethodDeclaration[1];
    unit.accept( new ASTVisitor() {
        @Override
        public boolean visit(MethodDeclaration node) {
            if (target.getElementName().equals(node.getName().toString())) {
                result[0] = node;
            }
            return false;
        }
    });
    return result[0];
}
项目:reflectify    文件:ClassAccessTest.java   
/** 
 * @return selection (offset,length) of first simple type node within statement given by <code>statementIndex</code>
 */
private int[] getTypeLiteralSelection(int statementIndex, IMethod target) {
    MethodDeclaration targetNode = compileTargetMethod(target);
    Statement stmt = (Statement) targetNode.getBody().statements().get(statementIndex );
    final int[] selection = new int[2];
    stmt.accept( new ASTVisitor() {
        @Override
        public boolean visit(TypeLiteral node) {
            if (selection[1] == 0) {
                selection[0] = node.getStartPosition();
                selection[1] = node.getLength();
            }
            return false;
        }
    });
    return selection;
}
项目:reflectify    文件:ClassInstanceCreationTest.java   
/** 
 * @return selection (offset,length) of first class instance creation node within statement given by <code>statementIndex</code>
 */
private int[] getClassInstanceCreationSelection(int statementIndex, IMethod target) {
    MethodDeclaration targetNode = compileTargetMethod(target);
    Statement stmt = (Statement) targetNode.getBody().statements().get(statementIndex );
    final int[] selection = new int[2];
    stmt.accept( new ASTVisitor() {
        @Override
        public boolean visit(ClassInstanceCreation node) {
            if (selection[1] == 0) {
                selection[0] = node.getStartPosition();
                selection[1] = node.getLength();
            }
            return false;
        }
    });
    return selection;
}
项目:reflectify    文件:FieldAccessTest.java   
/** @return selection (offset,length) of expression node of first return statement **/
private int[] getReturnStatementExpressionSelection(IMethod target) {
    MethodDeclaration targetNode = compileTargetMethod(target);
    final int[] selection = new int[2];
    targetNode.getBody().accept( new ASTVisitor() {
        @Override
        public boolean visit(ReturnStatement node) {
            if (selection[1] == 0) {
                Expression sel = node.getExpression();
                selection[0] = sel.getStartPosition();
                selection[1] = sel.getLength();
            }
            return false;
        }
    });
    return selection;
}
项目:gw4e.project    文件:ClassExtension.java   
/**
 * @param methodname
 * @return
 */
public ExpressionStatement getBodyMethod(String methodname) {
    ASTParser parser = ASTParser.newParser(AST.JLS8);
    parser.setSource(getBodyMethodSource (methodname).toCharArray());
    parser.setKind(ASTParser.K_COMPILATION_UNIT);
    final  CompilationUnit cu = (CompilationUnit) parser.createAST(null);
    cu.accept(new ASTVisitor() {
        public boolean visit(ExpressionStatement node) {
            expression = node;
            return true;
        }
    });      
    return expression;
}
项目:gw4e.project    文件:JDTManager.java   
public static IPath guessPackageRootFragment(IProject project, boolean main)
        throws CoreException, FileNotFoundException {
    IPath folder = project.getFullPath()
            .append(GraphWalkerContextManager.getTargetFolderForTestInterface(project.getName(), main));

    IResource interfaceFolder = ResourceManager.toResource(folder);
    List<IPath> paths = new ArrayList<IPath>();
    if (interfaceFolder != null) {
        interfaceFolder.accept(new IResourceVisitor() {
            @Override
            public boolean visit(IResource resource) throws CoreException {
                IJavaElement element = JavaCore.create(resource);
                if (element != null && element instanceof ICompilationUnit) {
                    try {
                        ICompilationUnit cu = (ICompilationUnit) element;
                        CompilationUnit ast = parse(cu);
                        ast.accept(new ASTVisitor() {
                            public boolean visit(PackageDeclaration node) {
                                PackageDeclaration decl = (PackageDeclaration) node;
                                String pkgname = decl.getName().getFullyQualifiedName();
                                int sizePath = pkgname.split("\\.").length;
                                paths.add(resource.getParent().getFullPath().removeLastSegments(sizePath));
                                return false;
                            }
                        });
                    } catch (Exception e) {
                        ResourceManager.logException(e);
                    }
                }
                return true;
            }
        });
    }
    if (paths.size() == 0)
        return null;
    return paths.get(0);
}
项目:gw4e.project    文件:JDTManager.java   
/**
 * @param project
 * @param itype
 * @return
 * @throws JavaModelException
 */
private static IPath findPathInStaticField(IProject project, IType itype) throws JavaModelException {
    List<IPath> wrapper = new ArrayList<IPath>();
    ICompilationUnit cu = itype.getCompilationUnit();
    CompilationUnit ast = parse(cu);
    ast.accept(new ASTVisitor() {
        public boolean visit(VariableDeclarationFragment node) {
            SimpleName simpleName = node.getName();
            IBinding bding = simpleName.resolveBinding();
            if (bding instanceof IVariableBinding) {
                IVariableBinding binding = (IVariableBinding) bding;
                String type = binding.getType().getBinaryName(); //
                String name = simpleName.getFullyQualifiedName();
                if ("MODEL_PATH".equals(name) && "java.nio.file.Path".equals(type)) {
                    Expression expression = node.getInitializer();
                    if (expression instanceof MethodInvocation) {
                        MethodInvocation mi = (MethodInvocation) expression;
                        if ("get".equals(mi.resolveMethodBinding().getName())
                                && "java.nio.file.Path".equals(mi.resolveTypeBinding().getBinaryName())) {
                            StringLiteral sl = (StringLiteral) mi.arguments().get(0);
                            String argument = sl.getLiteralValue();
                            try {
                                IPath p = ResourceManager.find(project, argument);
                                wrapper.add(p);
                            } catch (CoreException e) {
                                ResourceManager.logException(e);
                            }
                        }
                    }
                }
            }
            return true;
        }
    });
    if (wrapper.size() > 0)
        return wrapper.get(0);
    return null;
}
项目:gw4e.project    文件:JDTManager.java   
/**
 * Rename a class name into another name
 * 
 * @param file
 * @param oldClassname
 * @param newName
 * @param monitor
 * @return
 * @throws MalformedTreeException
 * @throws BadLocationException
 * @throws CoreException
 */
public static IFile renameClass(IFile file, String oldClassname, String newName, IProgressMonitor monitor)
        throws MalformedTreeException, BadLocationException, CoreException {
    Display.getDefault().syncExec(new Runnable() {

        @Override
        public void run() {
            try {

                ICompilationUnit unit = JavaCore.createCompilationUnitFrom(file);
                CompilationUnit cu = parse(unit);
                AST ast = cu.getAST();
                ASTRewrite rewrite = ASTRewrite.create(ast);

                String classname = file.getName();
                classname = classname.substring(0, classname.indexOf("."));
                final String clazz = classname;
                ASTVisitor visitor = new ASTVisitor() {
                    public boolean visit(SimpleName node) {
                        String s = node.getIdentifier();
                        if (oldClassname.equalsIgnoreCase(s)) {
                            rewrite.replace(node, ast.newSimpleName(newName), null);
                        }
                        return true;
                    }
                };
                cu.accept(visitor);

                addPackageDeclarationIfNeeded(file, cu, rewrite, ast);
                file.refreshLocal(IResource.DEPTH_ZERO, monitor);
                cu = parse(JavaCore.createCompilationUnitFrom(file));
                save(cu, rewrite);
            } catch (Exception e) {
                ResourceManager.logException(e);
            }
        }
    });
    return file;
}
项目:pandionj    文件:JavaSourceParser.java   
public void parse(ASTVisitor visitor) {
        parser.setSource(this.source);
        CompilationUnit unit = (CompilationUnit) parser.createAST(null);

//      if(unit.getProblems().length > 0)
//          throw new RuntimeException("code has compilation errors");

        unit.accept(visitor);
        hasErrors = unit.getProblems().length > 0;
    }
项目:Constants-to-Enum-Eclipse-Plugin    文件:Util.java   
public static ASTNode getExactASTNode(CompilationUnit root,
        final SearchMatch match) {
    final ArrayList ret = new ArrayList(1);
    final ASTVisitor visitor = new ASTVisitor() {
        public void preVisit(ASTNode node) {
            if (node.getStartPosition() == match.getOffset()) {
                ret.clear();
                ret.add(node);
            }
        }
    };
    root.accept(visitor);
    return (ASTNode) ret.get(0);
}
项目:che    文件:ConvertAnonymousToNestedRefactoring.java   
private void collectRefrencedVariables(ASTNode root, final Set<IBinding> result) {
  root.accept(
      new ASTVisitor() {
        @Override
        public boolean visit(SimpleName node) {
          IBinding binding = node.resolveBinding();
          if (binding instanceof IVariableBinding) result.add(binding);
          return true;
        }
      });
}