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

项目:eclipse.jdt.ls    文件:RenameNodeCorrectionProposal.java   
@Override
protected void addEdits(IDocument doc, TextEdit root) throws CoreException {
    super.addEdits(doc, root);

    // build a full AST
    CompilationUnit unit = SharedASTProvider.getInstance().getAST(getCompilationUnit(), null);

    ASTNode name= NodeFinder.perform(unit, fOffset, fLength);
    if (name instanceof SimpleName) {

        SimpleName[] names= LinkedNodeFinder.findByProblems(unit, (SimpleName) name);
        if (names != null) {
            for (int i= 0; i < names.length; i++) {
                SimpleName curr= names[i];
                root.addChild(new ReplaceEdit(curr.getStartPosition(), curr.getLength(), fNewName));
            }
            return;
        }
    }
    root.addChild(new ReplaceEdit(fOffset, fLength, fNewName));
}
项目:che    文件:ConvertAnonymousToNestedRefactoring.java   
private void initAST(IProgressMonitor pm) {
  if (fCompilationUnitNode == null) {
    fCompilationUnitNode = RefactoringASTParser.parseWithASTProvider(fCu, true, pm);
  }
  if (fAnonymousInnerClassNode == null) {
    fAnonymousInnerClassNode =
        getAnonymousInnerClass(
            NodeFinder.perform(fCompilationUnitNode, fSelectionStart, fSelectionLength));
  }
  if (fAnonymousInnerClassNode != null) {
    final AbstractTypeDeclaration declaration =
        (AbstractTypeDeclaration)
            ASTNodes.getParent(fAnonymousInnerClassNode, AbstractTypeDeclaration.class);
    if (declaration instanceof TypeDeclaration) {
      final AbstractTypeDeclaration[] nested = ((TypeDeclaration) declaration).getTypes();
      fClassNamesUsed = new HashSet<String>(nested.length);
      for (int index = 0; index < nested.length; index++)
        fClassNamesUsed.add(nested[index].getName().getIdentifier());
    } else fClassNamesUsed = Collections.emptySet();
  }
}
项目:che    文件:InlineConstantRefactoring.java   
private Name findConstantNameNode() {
  ASTNode node =
      NodeFinder.perform(fSelectionCuRewrite.getRoot(), fSelectionStart, fSelectionLength);
  if (node == null) return null;
  if (node instanceof FieldAccess) node = ((FieldAccess) node).getName();
  if (!(node instanceof Name)) return null;
  Name name = (Name) node;
  IBinding binding = name.resolveBinding();
  if (!(binding instanceof IVariableBinding)) return null;
  IVariableBinding variableBinding = (IVariableBinding) binding;
  if (!variableBinding.isField() || variableBinding.isEnumConstant()) return null;
  int modifiers = binding.getModifiers();
  if (!(Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers))) return null;

  return name;
}
项目:che    文件:IntroduceFactoryRefactoring.java   
/**
 * Finds and returns the <code>ASTNode</code> for the given source text selection, if it is an
 * entire constructor call or the class name portion of a constructor call or constructor
 * declaration, or null otherwise.
 *
 * @param unit The compilation unit in which the selection was made
 * @param offset The textual offset of the start of the selection
 * @param length The length of the selection in characters
 * @return ClassInstanceCreation or MethodDeclaration
 */
private ASTNode getTargetNode(ICompilationUnit unit, int offset, int length) {
  ASTNode node = ASTNodes.getNormalizedNode(NodeFinder.perform(fCU, offset, length));
  if (node.getNodeType() == ASTNode.CLASS_INSTANCE_CREATION) return node;
  if (node.getNodeType() == ASTNode.METHOD_DECLARATION
      && ((MethodDeclaration) node).isConstructor()) return node;
  // we have some sub node. Make sure its the right child of the parent
  StructuralPropertyDescriptor location = node.getLocationInParent();
  ASTNode parent = node.getParent();
  if (location == ClassInstanceCreation.TYPE_PROPERTY) {
    return parent;
  } else if (location == MethodDeclaration.NAME_PROPERTY
      && ((MethodDeclaration) parent).isConstructor()) {
    return parent;
  }
  return null;
}
项目:che    文件:SelfEncapsulateFieldRefactoring.java   
@Override
public RefactoringStatus checkInitialConditions(IProgressMonitor pm) throws CoreException {
  if (fVisibility < 0)
    fVisibility = (fField.getFlags() & (Flags.AccPublic | Flags.AccProtected | Flags.AccPrivate));
  RefactoringStatus result = new RefactoringStatus();
  result.merge(Checks.checkAvailability(fField));
  if (result.hasFatalError()) return result;
  fRoot =
      new RefactoringASTParser(ASTProvider.SHARED_AST_LEVEL)
          .parse(fField.getCompilationUnit(), true, pm);
  ISourceRange sourceRange = fField.getNameRange();
  ASTNode node = NodeFinder.perform(fRoot, sourceRange.getOffset(), sourceRange.getLength());
  if (node == null) {
    return mappingErrorFound(result, node);
  }
  fFieldDeclaration =
      (VariableDeclarationFragment) ASTNodes.getParent(node, VariableDeclarationFragment.class);
  if (fFieldDeclaration == null) {
    return mappingErrorFound(result, node);
  }
  if (fFieldDeclaration.resolveBinding() == null) {
    if (!processCompilerError(result, node))
      result.addFatalError(RefactoringCoreMessages.SelfEncapsulateField_type_not_resolveable);
    return result;
  }
  computeUsedNames();
  return result;
}
项目:che    文件:RenameNodeCorrectionProposal.java   
@Override
protected void addEdits(IDocument doc, TextEdit root) throws CoreException {
  super.addEdits(doc, root);

  // build a full AST
  CompilationUnit unit =
      SharedASTProvider.getAST(getCompilationUnit(), SharedASTProvider.WAIT_YES, null);

  ASTNode name = NodeFinder.perform(unit, fOffset, fLength);
  if (name instanceof SimpleName) {

    SimpleName[] names = LinkedNodeFinder.findByProblems(unit, (SimpleName) name);
    if (names != null) {
      for (int i = 0; i < names.length; i++) {
        SimpleName curr = names[i];
        root.addChild(new ReplaceEdit(curr.getStartPosition(), curr.getLength(), fNewName));
      }
      return;
    }
  }
  root.addChild(new ReplaceEdit(fOffset, fLength, fNewName));
}
项目:Eclipse-Postfix-Code-Completion    文件:MoveStaticMembersProcessor.java   
@Override
public RefactoringStatus checkInitialConditions(IProgressMonitor pm) throws CoreException {
    try {
        pm.beginTask(RefactoringCoreMessages.MoveMembersRefactoring_checking, 1);
        RefactoringStatus result= new RefactoringStatus();
        result.merge(checkDeclaringType());
        pm.worked(1);
        if (result.hasFatalError())
            return result;

        fSource= new CompilationUnitRewrite(fMembersToMove[0].getCompilationUnit());
        fSourceBinding= (ITypeBinding)((SimpleName)NodeFinder.perform(fSource.getRoot(), fMembersToMove[0].getDeclaringType().getNameRange())).resolveBinding();
        fMemberBindings= getMemberBindings();
        if (fSourceBinding == null || hasUnresolvedMemberBinding()) {
            result.addFatalError(Messages.format(
                RefactoringCoreMessages.MoveMembersRefactoring_compile_errors,
                BasicElementLabels.getFileName(fSource.getCu())));
        }
        fMemberDeclarations= getASTMembers(result);
        return result;
    } finally {
        pm.done();
    }
}
项目:Eclipse-Postfix-Code-Completion    文件:MoveStaticMembersProcessor.java   
private BodyDeclaration[] getASTMembers(RefactoringStatus status) throws JavaModelException {
    BodyDeclaration[] result= new BodyDeclaration[fMembersToMove.length];
    for (int i= 0; i < fMembersToMove.length; i++) {
        IMember member= fMembersToMove[i];
        ASTNode node= NodeFinder.perform(fSource.getRoot(), member.getNameRange());
        result[i]= (BodyDeclaration)ASTNodes.getParent(node, BodyDeclaration.class);

        //Fix for bug 42383: exclude multiple VariableDeclarationFragments ("int a=1, b=2")
        //ReferenceAnalyzer#visit(FieldDeclaration node) depends on fragments().size() != 1 !
        if (result[i] instanceof FieldDeclaration
                && ((FieldDeclaration) result[i]).fragments().size() != 1) {
            status.addFatalError(RefactoringCoreMessages.MoveMembersRefactoring_multi_var_fields);
            return result;
        }

    }

    //Sorting members is important for field declarations referring to previous fields.
    Arrays.sort(result, new Comparator<BodyDeclaration>() {
        public int compare(BodyDeclaration o1, BodyDeclaration o2) {
            return o1.getStartPosition() - o2.getStartPosition();
        }
    });
    return result;
}
项目:Eclipse-Postfix-Code-Completion    文件:ChangeSignatureProcessor.java   
private RefactoringStatus createExceptionInfoList() {
    if (fExceptionInfos == null || fExceptionInfos.isEmpty()) {
        fExceptionInfos= new ArrayList<ExceptionInfo>(0);
        try {
            ASTNode nameNode= NodeFinder.perform(fBaseCuRewrite.getRoot(), fMethod.getNameRange());
            if (nameNode == null || !(nameNode instanceof Name) || !(nameNode.getParent() instanceof MethodDeclaration))
                return null;
            MethodDeclaration methodDeclaration= (MethodDeclaration) nameNode.getParent();
            List<Type> exceptions= methodDeclaration.thrownExceptionTypes();
            List<ExceptionInfo> result= new ArrayList<ExceptionInfo>(exceptions.size());
            for (int i= 0; i < exceptions.size(); i++) {
                Type type= exceptions.get(i);
                ITypeBinding typeBinding= type.resolveBinding();
                if (typeBinding == null)
                    return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ChangeSignatureRefactoring_no_exception_binding);
                IJavaElement element= typeBinding.getJavaElement();
                result.add(ExceptionInfo.createInfoForOldException(element, typeBinding));
            }
            fExceptionInfos= result;
        } catch (JavaModelException e) {
            JavaPlugin.log(e);
        }
    }
    return null;
}
项目:Eclipse-Postfix-Code-Completion-Juno38    文件:NLSStringHover.java   
@Override
public IRegion getHoverRegion(ITextViewer textViewer, int offset) {
    if (!(getEditor() instanceof JavaEditor))
        return null;

    ITypeRoot je= getEditorInputJavaElement();
    if (je == null)
        return null;

    // Never wait for an AST in UI thread.
    CompilationUnit ast= SharedASTProvider.getAST(je, SharedASTProvider.WAIT_NO, null);
    if (ast == null)
        return null;

    ASTNode node= NodeFinder.perform(ast, offset, 1);
    if (node instanceof StringLiteral) {
        StringLiteral stringLiteral= (StringLiteral)node;
        return new Region(stringLiteral.getStartPosition(), stringLiteral.getLength());
    } else if (node instanceof SimpleName) {
        SimpleName simpleName= (SimpleName)node;
        return new Region(simpleName.getStartPosition(), simpleName.getLength());
    }

    return null;
}
项目:Eclipse-Postfix-Code-Completion-Juno38    文件:RenameNodeCorrectionProposal.java   
@Override
protected void addEdits(IDocument doc, TextEdit root) throws CoreException {
    super.addEdits(doc, root);

    // build a full AST
    CompilationUnit unit= SharedASTProvider.getAST(getCompilationUnit(), SharedASTProvider.WAIT_YES, null);

    ASTNode name= NodeFinder.perform(unit, fOffset, fLength);
    if (name instanceof SimpleName) {

        SimpleName[] names= LinkedNodeFinder.findByProblems(unit, (SimpleName) name);
        if (names != null) {
            for (int i= 0; i < names.length; i++) {
                SimpleName curr= names[i];
                root.addChild(new ReplaceEdit(curr.getStartPosition(), curr.getLength(), fNewName));
            }
            return;
        }
    }
    root.addChild(new ReplaceEdit(fOffset, fLength, fNewName));
}
项目:Eclipse-Postfix-Code-Completion    文件:IntroduceFactoryRefactoring.java   
/**
 * Finds and returns the <code>ASTNode</code> for the given source text
 * selection, if it is an entire constructor call or the class name portion
 * of a constructor call or constructor declaration, or null otherwise.
 * @param unit The compilation unit in which the selection was made
 * @param offset The textual offset of the start of the selection
 * @param length The length of the selection in characters
 * @return ClassInstanceCreation or MethodDeclaration
 */
private ASTNode getTargetNode(ICompilationUnit unit, int offset, int length) {
    ASTNode node= ASTNodes.getNormalizedNode(NodeFinder.perform(fCU, offset, length));
    if (node.getNodeType() == ASTNode.CLASS_INSTANCE_CREATION)
        return node;
    if (node.getNodeType() == ASTNode.METHOD_DECLARATION && ((MethodDeclaration)node).isConstructor())
        return node;
    // we have some sub node. Make sure its the right child of the parent
    StructuralPropertyDescriptor location= node.getLocationInParent();
    ASTNode parent= node.getParent();
    if (location == ClassInstanceCreation.TYPE_PROPERTY) {
        return parent;
    } else if (location == MethodDeclaration.NAME_PROPERTY && ((MethodDeclaration)parent).isConstructor()) {
        return parent;
    }
    return null;
}
项目:Eclipse-Postfix-Code-Completion-Juno38    文件:JavaStatementPostfixContext.java   
private void initDomAST() {
        if (isReadOnly())
            return;

        ASTParser parser= ASTParser.newParser(AST.JLS4);
        parser.setSource(getCompilationUnit());
        parser.setResolveBindings(true);
        org.eclipse.jdt.core.dom.ASTNode domAst = parser.createAST(new NullProgressMonitor());

//      org.eclipse.jdt.core.dom.AST ast = domAst.getAST();

        NodeFinder nf = new NodeFinder(domAst, getCompletionOffset(), 1);
        org.eclipse.jdt.core.dom.ASTNode cv = nf.getCoveringNode();

        bodyDeclaration = ASTResolving.findParentBodyDeclaration(cv);
        parentDeclaration = ASTResolving.findParentType(cv);
        domInitialized = true;
    }
项目:Eclipse-Postfix-Code-Completion-Juno38    文件:JavadocView.java   
/**
 * Returns the constant value for a field that is referenced by the currently active type.
 * This method does may not run in the main UI thread.
 * <p>
 * XXX: This method was part of the JavadocHover#getConstantValue(IField field, IRegion hoverRegion)
 *      method (lines 299-314).
 * </p>
 * @param activeType the type that is currently active
 * @param field the field that is being referenced (usually not declared in <code>activeType</code>)
 * @param selection the region in <code>activeType</code> that contains the field reference
 * @param monitor a progress monitor
 *
 * @return the constant value for the given field or <code>null</code> if none
 * @since 3.4
 */
private static Object getConstantValueFromActiveEditor(ITypeRoot activeType, IField field, ITextSelection selection, IProgressMonitor monitor) {
    Object constantValue= null;

    CompilationUnit unit= SharedASTProvider.getAST(activeType, SharedASTProvider.WAIT_ACTIVE_ONLY, monitor);
    if (unit == null)
        return null;

    ASTNode node= NodeFinder.perform(unit, selection.getOffset(), selection.getLength());
    if (node != null && node.getNodeType() == ASTNode.SIMPLE_NAME) {
        IBinding binding= ((SimpleName)node).resolveBinding();
        if (binding != null && binding.getKind() == IBinding.VARIABLE) {
            IVariableBinding variableBinding= (IVariableBinding)binding;
            if (field.equals(variableBinding.getJavaElement())) {
                constantValue= variableBinding.getConstantValue();
            }
        }
    }
    return constantValue;
}
项目:Eclipse-Postfix-Code-Completion    文件:AddGetterSetterOperation.java   
/**
 * Generates a new setter method for the specified field
 * 
 * @param field the field
 * @param astRewrite the AST rewrite to use
 * @param rewrite the list rewrite to use
 * @throws CoreException if an error occurs
 * @throws OperationCanceledException if the operation has been cancelled
 */
private void generateSetterMethod(final IField field, ASTRewrite astRewrite, final ListRewrite rewrite) throws CoreException, OperationCanceledException {
    final IType type= field.getDeclaringType();
    final String name= GetterSetterUtil.getSetterName(field, null);
    final IMethod existing= JavaModelUtil.findMethod(name, new String[] { field.getTypeSignature()}, false, type);
    if (existing == null || !querySkipExistingMethods(existing)) {
        IJavaElement sibling= null;
        if (existing != null) {
            sibling= StubUtility.findNextSibling(existing);
            removeExistingAccessor(existing, rewrite);
        } else
            sibling= fInsert;
        ASTNode insertion= StubUtility2.getNodeToInsertBefore(rewrite, sibling);
        addNewAccessor(type, field, GetterSetterUtil.getSetterStub(field, name, fSettings.createComments, fVisibility | (field.getFlags() & Flags.AccStatic)), rewrite, insertion);
        if (Flags.isFinal(field.getFlags())) {
            ASTNode fieldDecl= ASTNodes.getParent(NodeFinder.perform(fASTRoot, field.getNameRange()), FieldDeclaration.class);
            if (fieldDecl != null) {
                ModifierRewrite.create(astRewrite, fieldDecl).setModifiers(0, Modifier.FINAL, null);
            }
        }

    }
}
项目:Eclipse-Postfix-Code-Completion    文件:OverrideIndicatorLabelDecorator.java   
private int findInHierarchyWithAST(CompilationUnit astRoot, IMethod method) throws JavaModelException {
    ASTNode node= NodeFinder.perform(astRoot, method.getNameRange());
    if (node instanceof SimpleName && node.getParent() instanceof MethodDeclaration) {
        IMethodBinding binding= ((MethodDeclaration) node.getParent()).resolveBinding();
        if (binding != null) {
            IMethodBinding defining= Bindings.findOverriddenMethod(binding, true);
            if (defining != null) {
                if (JdtFlags.isAbstract(defining)) {
                    return JavaElementImageDescriptor.IMPLEMENTS;
                } else {
                    return JavaElementImageDescriptor.OVERRIDES;
                }
            }
            return 0;
        }
    }
    return -1;
}
项目:Eclipse-Postfix-Code-Completion    文件:NLSStringHover.java   
@Override
public IRegion getHoverRegion(ITextViewer textViewer, int offset) {
    if (!(getEditor() instanceof JavaEditor))
        return null;

    ITypeRoot je= getEditorInputJavaElement();
    if (je == null)
        return null;

    // Never wait for an AST in UI thread.
    CompilationUnit ast= SharedASTProvider.getAST(je, SharedASTProvider.WAIT_NO, null);
    if (ast == null)
        return null;

    ASTNode node= NodeFinder.perform(ast, offset, 1);
    if (node instanceof StringLiteral) {
        StringLiteral stringLiteral= (StringLiteral)node;
        return new Region(stringLiteral.getStartPosition(), stringLiteral.getLength());
    } else if (node instanceof SimpleName) {
        SimpleName simpleName= (SimpleName)node;
        return new Region(simpleName.getStartPosition(), simpleName.getLength());
    }

    return null;
}
项目:Eclipse-Postfix-Code-Completion    文件:RenameNodeCorrectionProposal.java   
@Override
protected void addEdits(IDocument doc, TextEdit root) throws CoreException {
    super.addEdits(doc, root);

    // build a full AST
    CompilationUnit unit= SharedASTProvider.getAST(getCompilationUnit(), SharedASTProvider.WAIT_YES, null);

    ASTNode name= NodeFinder.perform(unit, fOffset, fLength);
    if (name instanceof SimpleName) {

        SimpleName[] names= LinkedNodeFinder.findByProblems(unit, (SimpleName) name);
        if (names != null) {
            for (int i= 0; i < names.length; i++) {
                SimpleName curr= names[i];
                root.addChild(new ReplaceEdit(curr.getStartPosition(), curr.getLength(), fNewName));
            }
            return;
        }
    }
    root.addChild(new ReplaceEdit(fOffset, fLength, fNewName));
}
项目:Eclipse-Postfix-Code-Completion-Juno38    文件:OverrideIndicatorLabelDecorator.java   
private int findInHierarchyWithAST(CompilationUnit astRoot, IMethod method) throws JavaModelException {
    ASTNode node= NodeFinder.perform(astRoot, method.getNameRange());
    if (node instanceof SimpleName && node.getParent() instanceof MethodDeclaration) {
        IMethodBinding binding= ((MethodDeclaration) node.getParent()).resolveBinding();
        if (binding != null) {
            IMethodBinding defining= Bindings.findOverriddenMethod(binding, true);
            if (defining != null) {
                if (JdtFlags.isAbstract(defining)) {
                    return JavaElementImageDescriptor.IMPLEMENTS;
                } else {
                    return JavaElementImageDescriptor.OVERRIDES;
                }
            }
            return 0;
        }
    }
    return -1;
}
项目:Eclipse-Postfix-Code-Completion    文件:JavaStatementPostfixContext.java   
private void initDomAST() {
        if (isReadOnly())
            return;

        ASTParser parser= ASTParser.newParser(AST.JLS8);
        parser.setSource(getCompilationUnit());
        parser.setResolveBindings(true);
        org.eclipse.jdt.core.dom.ASTNode domAst = parser.createAST(new NullProgressMonitor());

//      org.eclipse.jdt.core.dom.AST ast = domAst.getAST();

        NodeFinder nf = new NodeFinder(domAst, getCompletionOffset(), 1);
        org.eclipse.jdt.core.dom.ASTNode cv = nf.getCoveringNode();

        bodyDeclaration = ASTResolving.findParentBodyDeclaration(cv);
        parentDeclaration = ASTResolving.findParentType(cv);
        domInitialized = true;
    }
项目:Eclipse-Postfix-Code-Completion-Juno38    文件:ExtractClassRefactoring.java   
private List<ResourceChange> createParameterObject(ParameterObjectFactory pof, IPackageFragmentRoot packageRoot) throws CoreException {
    FieldUpdate fieldUpdate= new FieldUpdate();
    if (fDescriptor.isCreateTopLevel())
        return pof.createTopLevelParameterObject(packageRoot, fieldUpdate);
    else {
        CompilationUnit root= fBaseCURewrite.getRoot();
        TypeDeclaration typeDecl= (TypeDeclaration) NodeFinder.perform(root, fDescriptor.getType().getSourceRange());
        ASTRewrite rewrite= fBaseCURewrite.getASTRewrite();
        ListRewrite listRewrite= rewrite.getListRewrite(typeDecl, TypeDeclaration.BODY_DECLARATIONS_PROPERTY);
        TypeDeclaration paramClass= pof.createClassDeclaration(typeDecl.getName().getFullyQualifiedName(), fBaseCURewrite, fieldUpdate);
        paramClass.modifiers().add(rewrite.getAST().newModifier(ModifierKeyword.PUBLIC_KEYWORD));
        paramClass.modifiers().add(rewrite.getAST().newModifier(ModifierKeyword.STATIC_KEYWORD));
        listRewrite.insertFirst(paramClass, fBaseCURewrite.createGroupDescription(RefactoringCoreMessages.ExtractClassRefactoring_group_insert_parameter));
        return new ArrayList<ResourceChange>(); //Change will be generated later for fBaseCURewrite
    }

}
项目:Eclipse-Postfix-Code-Completion-Juno38    文件:MoveStaticMembersProcessor.java   
@Override
public RefactoringStatus checkInitialConditions(IProgressMonitor pm) throws CoreException {
    try {
        pm.beginTask(RefactoringCoreMessages.MoveMembersRefactoring_checking, 1);
        RefactoringStatus result= new RefactoringStatus();
        result.merge(checkDeclaringType());
        pm.worked(1);
        if (result.hasFatalError())
            return result;

        fSource= new CompilationUnitRewrite(fMembersToMove[0].getCompilationUnit());
        fSourceBinding= (ITypeBinding)((SimpleName)NodeFinder.perform(fSource.getRoot(), fMembersToMove[0].getDeclaringType().getNameRange())).resolveBinding();
        fMemberBindings= getMemberBindings();
        if (fSourceBinding == null || hasUnresolvedMemberBinding()) {
            result.addFatalError(Messages.format(
                RefactoringCoreMessages.MoveMembersRefactoring_compile_errors,
                BasicElementLabels.getFileName(fSource.getCu())));
        }
        fMemberDeclarations= getASTMembers(result);
        return result;
    } finally {
        pm.done();
    }
}
项目:Eclipse-Postfix-Code-Completion-Juno38    文件:ChangeSignatureProcessor.java   
private RefactoringStatus createExceptionInfoList() {
    if (fExceptionInfos == null || fExceptionInfos.isEmpty()) {
        fExceptionInfos= new ArrayList<ExceptionInfo>(0);
        try {
            ASTNode nameNode= NodeFinder.perform(fBaseCuRewrite.getRoot(), fMethod.getNameRange());
            if (nameNode == null || !(nameNode instanceof Name) || !(nameNode.getParent() instanceof MethodDeclaration))
                return null;
            MethodDeclaration methodDeclaration= (MethodDeclaration) nameNode.getParent();
            List<Name> exceptions= methodDeclaration.thrownExceptions();
            List<ExceptionInfo> result= new ArrayList<ExceptionInfo>(exceptions.size());
            for (int i= 0; i < exceptions.size(); i++) {
                Name name= exceptions.get(i);
                ITypeBinding typeBinding= name.resolveTypeBinding();
                if (typeBinding == null)
                    return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ChangeSignatureRefactoring_no_exception_binding);
                IJavaElement element= typeBinding.getJavaElement();
                result.add(ExceptionInfo.createInfoForOldException(element, typeBinding));
            }
            fExceptionInfos= result;
        } catch (JavaModelException e) {
            JavaPlugin.log(e);
        }
    }
    return null;
}
项目:Eclipse-Postfix-Code-Completion-Juno38    文件:ConvertAnonymousToNestedRefactoring.java   
private void initAST(IProgressMonitor pm) {
    if (fCompilationUnitNode == null) {
        fCompilationUnitNode= RefactoringASTParser.parseWithASTProvider(fCu, true, pm);
    }
    if (fAnonymousInnerClassNode == null) {
        fAnonymousInnerClassNode= getAnonymousInnerClass(NodeFinder.perform(fCompilationUnitNode, fSelectionStart, fSelectionLength));
    }
    if (fAnonymousInnerClassNode != null) {
        final AbstractTypeDeclaration declaration= (AbstractTypeDeclaration) ASTNodes.getParent(fAnonymousInnerClassNode, AbstractTypeDeclaration.class);
        if (declaration instanceof TypeDeclaration) {
            final AbstractTypeDeclaration[] nested= ((TypeDeclaration) declaration).getTypes();
            fClassNamesUsed= new HashSet<String>(nested.length);
            for (int index= 0; index < nested.length; index++)
                fClassNamesUsed.add(nested[index].getName().getIdentifier());
        } else
            fClassNamesUsed= Collections.emptySet();
    }
}
项目:Eclipse-Postfix-Code-Completion-Juno38    文件:InlineConstantRefactoring.java   
private Name findConstantNameNode() {
    ASTNode node= NodeFinder.perform(fSelectionCuRewrite.getRoot(), fSelectionStart, fSelectionLength);
    if (node == null)
        return null;
    if (node instanceof FieldAccess)
        node= ((FieldAccess) node).getName();
    if (node.getParent() instanceof EnumConstantDeclaration)
        return null;
    if (!(node instanceof Name))
        return null;
    Name name= (Name) node;
    IBinding binding= name.resolveBinding();
    if (!(binding instanceof IVariableBinding))
        return null;
    IVariableBinding variableBinding= (IVariableBinding) binding;
    if (!variableBinding.isField() || variableBinding.isEnumConstant())
        return null;
    int modifiers= binding.getModifiers();
    if (! (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)))
        return null;

    return name;
}
项目:Eclipse-Postfix-Code-Completion-Juno38    文件:IntroduceFactoryRefactoring.java   
/**
 * Finds and returns the <code>ASTNode</code> for the given source text
 * selection, if it is an entire constructor call or the class name portion
 * of a constructor call or constructor declaration, or null otherwise.
 * @param unit The compilation unit in which the selection was made
 * @param offset The textual offset of the start of the selection
 * @param length The length of the selection in characters
 * @return ClassInstanceCreation or MethodDeclaration
 */
private ASTNode getTargetNode(ICompilationUnit unit, int offset, int length) {
    ASTNode node= ASTNodes.getNormalizedNode(NodeFinder.perform(fCU, offset, length));
    if (node.getNodeType() == ASTNode.CLASS_INSTANCE_CREATION)
        return node;
    if (node.getNodeType() == ASTNode.METHOD_DECLARATION && ((MethodDeclaration)node).isConstructor())
        return node;
    // we have some sub node. Make sure its the right child of the parent
    StructuralPropertyDescriptor location= node.getLocationInParent();
    ASTNode parent= node.getParent();
    if (location == ClassInstanceCreation.TYPE_PROPERTY) {
        return parent;
    } else if (location == MethodDeclaration.NAME_PROPERTY && ((MethodDeclaration)parent).isConstructor()) {
        return parent;
    }
    return null;
}
项目:eclipse.jdt.ls    文件:ASTNodeFactory.java   
public static ASTNode newStatement(AST ast, String content) {
    StringBuffer buffer= new StringBuffer(STATEMENT_HEADER);
    buffer.append(content);
    buffer.append(STATEMENT_FOOTER);
    ASTParser p= ASTParser.newParser(ast.apiLevel());
    p.setSource(buffer.toString().toCharArray());
    CompilationUnit root= (CompilationUnit) p.createAST(null);
    ASTNode result= ASTNode.copySubtree(ast, NodeFinder.perform(root, STATEMENT_HEADER.length(), content.length()));
    result.accept(new PositionClearer());
    return result;
}
项目:eclipse.jdt.ls    文件:LinkedNodeFinder.java   
public static SimpleName[] findByProblems(ASTNode parent, SimpleName nameNode) {
    ArrayList<SimpleName> res= new ArrayList<>();

    ASTNode astRoot = parent.getRoot();
    if (!(astRoot instanceof CompilationUnit)) {
        return null;
    }

    IProblem[] problems= ((CompilationUnit) astRoot).getProblems();
    int nameNodeKind= getNameNodeProblemKind(problems, nameNode);
    if (nameNodeKind == 0) { // no problem on node
        return null;
    }

    int bodyStart= parent.getStartPosition();
    int bodyEnd= bodyStart + parent.getLength();

    String name= nameNode.getIdentifier();

    for (int i= 0; i < problems.length; i++) {
        IProblem curr= problems[i];
        int probStart= curr.getSourceStart();
        int probEnd= curr.getSourceEnd() + 1;

        if (probStart > bodyStart && probEnd < bodyEnd) {
            int currKind= getProblemKind(curr);
            if ((nameNodeKind & currKind) != 0) {
                ASTNode node= NodeFinder.perform(parent, probStart, (probEnd - probStart));
                if (node instanceof SimpleName && name.equals(((SimpleName) node).getIdentifier())) {
                    res.add((SimpleName) node);
                }
            }
        }
    }
    return res.toArray(new SimpleName[res.size()]);
}
项目:eclipse.jdt.ls    文件:OrganizeImportsOperation.java   
private static ImportDeclaration getProblematicImport(IProblem problem, CompilationUnit astRoot) {
    ASTNode coveringNode = new NodeFinder(astRoot, problem.getSourceStart(),
            problem.getSourceEnd() - problem.getSourceStart()).getCoveringNode();
    if (coveringNode != null) {
        ASTNode importNode= ASTNodes.getParent(coveringNode, ASTNode.IMPORT_DECLARATION);
        if (importNode instanceof ImportDeclaration) {
            return (ImportDeclaration) importNode;
        }
    }
    return null;
}
项目:eclipse.jdt.ls    文件:UnusedCodeFix.java   
private static boolean isSideEffectFree(SimpleName simpleName, CompilationUnit completeRoot) {
    SimpleName nameNode= (SimpleName) NodeFinder.perform(completeRoot, simpleName.getStartPosition(), simpleName.getLength());
    SimpleName[] references= LinkedNodeFinder.findByBinding(completeRoot, nameNode.resolveBinding());
    for (int i= 0; i < references.length; i++) {
        if (hasSideEffect(references[i])) {
            return false;
        }
    }
    return true;
}
项目:eclipse.jdt.ls    文件:ExtractMethodAnalyzer.java   
@Override
public boolean visit(Assignment node) {
    boolean result = super.visit(node);
    Selection selection = getSelection();
    ASTNode selectedNode = NodeFinder.perform(node, selection.getOffset(), selection.getLength());
    if ((selectedNode != null && SnippetFinder.isLeftHandSideOfAssignment(selectedNode)) || (selection.covers(node.getLeftHandSide()) && !selection.covers(node.getRightHandSide()))) {
        invalidSelection(RefactoringCoreMessages.ExtractMethodAnalyzer_leftHandSideOfAssignment, JavaStatusContext.create(fCUnit, node));
        return false;
    }
    return result;
}
项目:code    文件:ASTUtils.java   
public static ASTNode getASTNode(int offset, int length, IEditorPart part) {
    IJavaElement activeEditorJavaInput = null;
    if (part != null) {
        IEditorInput editorInput = part.getEditorInput();
        if (editorInput != null) {
            activeEditorJavaInput = JavaUI
                    .getEditorInputJavaElement(editorInput);
        }
    } else {
        activeEditorJavaInput = EditorUtility.getActiveEditorJavaInput();
        part = getActivePart();
    }

    if (activeEditorJavaInput != null
            && activeEditorJavaInput.getElementType() == IJavaElement.COMPILATION_UNIT) {

        ICompilationUnit compilationUnit = (ICompilationUnit) activeEditorJavaInput;
        ASTParser parser = ASTParser.newParser(AST.JLS3);
        parser.setKind(ASTParser.K_COMPILATION_UNIT);
        parser.setSource(compilationUnit);
        parser.setResolveBindings(true);
        ASTNode root = parser.createAST(null);

        ASTNode node = NodeFinder.perform(root, offset, length);
        return node;
    }
    return null;
}
项目:junit-tools    文件:JDTUtils.java   
public static IMethod getSelectedMethod(IFileEditorInput fileEditorInput)
        throws JavaModelException {
    ITextEditor editor = (ITextEditor) EclipseUIUtils.getActiveEditor();
    ITextSelection sel = (ITextSelection) editor.getSelectionProvider()
            .getSelection();
    ITypeRoot typeRoot = JavaUI.getEditorInputTypeRoot(editor
            .getEditorInput());
    ICompilationUnit icu = (ICompilationUnit) typeRoot
            .getAdapter(ICompilationUnit.class);
    CompilationUnit cu = createASTRoot(icu);
    NodeFinder finder = new NodeFinder(cu, sel.getOffset(), sel.getLength());

    ASTNode node = finder.getCoveringNode();

    MethodDeclaration methodDeclaration = getASTMethod(node);
    if (methodDeclaration == null) {
        return null;
    }

    IMethodBinding methodBinding = methodDeclaration.resolveBinding();

    IMethod selectedMethod = null;
    if (methodBinding != null) {
        selectedMethod = (IMethod) methodBinding.getJavaElement();
    }

    return selectedMethod;
}
项目:Constants-to-Enum-Eclipse-Plugin    文件:ConvertConstantsToEnumRefactoring.java   
private void rewriteExpressions(CompilationUnit node, SearchMatch match,
        RefactoringStatus status, ASTRewrite astRewrite,
        ImportRewrite importRewrite) {
    final ASTNode result = NodeFinder.perform(node, match.getOffset(),
            match.getLength());
    final InfixExpression ie = Util.getInfixExpression(result);
    if (ie == null) // there is none.
        return;
    else if (Util.inNeedOfTransformation(ie.getOperator())) {
        // Get the fully qualified type name.
        final String fqn = this.getFullyQualifiedName(((Name) result)
                .resolveBinding().getJavaElement());
        this.rewriteInfixExpression(astRewrite, importRewrite, ie, fqn);
    }
}
项目:che    文件:ASTNodeFactory.java   
public static ASTNode newStatement(AST ast, String content) {
  StringBuffer buffer = new StringBuffer(STATEMENT_HEADER);
  buffer.append(content);
  buffer.append(STATEMENT_FOOTER);
  CheASTParser p = CheASTParser.newParser(ast.apiLevel());
  p.setSource(buffer.toString().toCharArray());
  CompilationUnit root = (CompilationUnit) p.createAST(null);
  ASTNode result =
      ASTNode.copySubtree(
          ast, NodeFinder.perform(root, STATEMENT_HEADER.length(), content.length()));
  result.accept(new PositionClearer());
  return result;
}
项目:che    文件:LinkedNodeFinder.java   
public static SimpleName[] findByProblems(ASTNode parent, SimpleName nameNode) {
  ArrayList<SimpleName> res = new ArrayList<SimpleName>();

  ASTNode astRoot = parent.getRoot();
  if (!(astRoot instanceof CompilationUnit)) {
    return null;
  }

  IProblem[] problems = ((CompilationUnit) astRoot).getProblems();
  int nameNodeKind = getNameNodeProblemKind(problems, nameNode);
  if (nameNodeKind == 0) { // no problem on node
    return null;
  }

  int bodyStart = parent.getStartPosition();
  int bodyEnd = bodyStart + parent.getLength();

  String name = nameNode.getIdentifier();

  for (int i = 0; i < problems.length; i++) {
    IProblem curr = problems[i];
    int probStart = curr.getSourceStart();
    int probEnd = curr.getSourceEnd() + 1;

    if (probStart > bodyStart && probEnd < bodyEnd) {
      int currKind = getProblemKind(curr);
      if ((nameNodeKind & currKind) != 0) {
        ASTNode node = NodeFinder.perform(parent, probStart, (probEnd - probStart));
        if (node instanceof SimpleName && name.equals(((SimpleName) node).getIdentifier())) {
          res.add((SimpleName) node);
        }
      }
    }
  }
  return res.toArray(new SimpleName[res.size()]);
}
项目:che    文件:UnusedCodeFix.java   
private static boolean isSideEffectFree(SimpleName simpleName, CompilationUnit completeRoot) {
  SimpleName nameNode =
      (SimpleName)
          NodeFinder.perform(completeRoot, simpleName.getStartPosition(), simpleName.getLength());
  SimpleName[] references =
      LinkedNodeFinder.findByBinding(completeRoot, nameNode.resolveBinding());
  for (int i = 0; i < references.length; i++) {
    if (hasSideEffect(references[i])) return false;
  }
  return true;
}
项目:che    文件:ChangeSignatureProcessor.java   
private RefactoringStatus createExceptionInfoList() {
  if (fExceptionInfos == null || fExceptionInfos.isEmpty()) {
    fExceptionInfos = new ArrayList<ExceptionInfo>(0);
    try {
      ASTNode nameNode = NodeFinder.perform(fBaseCuRewrite.getRoot(), fMethod.getNameRange());
      if (nameNode == null
          || !(nameNode instanceof Name)
          || !(nameNode.getParent() instanceof MethodDeclaration)) return null;
      MethodDeclaration methodDeclaration = (MethodDeclaration) nameNode.getParent();
      List<Type> exceptions = methodDeclaration.thrownExceptionTypes();
      List<ExceptionInfo> result = new ArrayList<ExceptionInfo>(exceptions.size());
      for (int i = 0; i < exceptions.size(); i++) {
        Type type = exceptions.get(i);
        ITypeBinding typeBinding = type.resolveBinding();
        if (typeBinding == null)
          return RefactoringStatus.createFatalErrorStatus(
              RefactoringCoreMessages.ChangeSignatureRefactoring_no_exception_binding);
        IJavaElement element = typeBinding.getJavaElement();
        result.add(ExceptionInfo.createInfoForOldException(element, typeBinding));
      }
      fExceptionInfos = result;
    } catch (JavaModelException e) {
      JavaPlugin.log(e);
    }
  }
  return null;
}
项目:che    文件:ASTNodeSearchUtil.java   
public static ASTNode findNode(SearchMatch searchResult, CompilationUnit cuNode) {
  ASTNode selectedNode =
      NodeFinder.perform(cuNode, searchResult.getOffset(), searchResult.getLength());
  if (selectedNode == null) return null;
  if (selectedNode.getParent() == null) return null;
  return selectedNode;
}
项目:che    文件:RenameLocalVariableProcessor.java   
private void initAST() {
  if (!fIsComposite)
    fCompilationUnitNode = RefactoringASTParser.parseWithASTProvider(fCu, true, null);
  ISourceRange sourceRange = fLocalVariable.getNameRange();
  ASTNode name = NodeFinder.perform(fCompilationUnitNode, sourceRange);
  if (name == null) return;
  if (name.getParent() instanceof VariableDeclaration)
    fTempDeclarationNode = (VariableDeclaration) name.getParent();
}