Java 类com.intellij.psi.search.LocalSearchScope 实例源码

项目:intellij-ce-playground    文件:AnnotatedElementsSearcher.java   
private static Collection<PsiAnnotation> getAnnotationCandidates(final PsiClass annClass, final SearchScope useScope) {
  return ApplicationManager.getApplication().runReadAction(new Computable<Collection<PsiAnnotation>>() {
    @Override
    public Collection<PsiAnnotation> compute() {
      if (useScope instanceof GlobalSearchScope) {
        return JavaAnnotationIndex.getInstance().get(annClass.getName(), annClass.getProject(), (GlobalSearchScope)useScope);
      }

      final List<PsiAnnotation> result = ContainerUtil.newArrayList();
      for (PsiElement element : ((LocalSearchScope)useScope).getScope()) {
        result.addAll(PsiTreeUtil.findChildrenOfType(element, PsiAnnotation.class));
      }
      return result;
    }
  });
}
项目:intellij-ce-playground    文件:ParametersFolder.java   
private static boolean isConditional(PsiElement expr, LocalSearchScope scope) {
  while (expr != null) {
    final PsiElement parent = expr.getParent();
    if (parent != null && scope.containsRange(parent.getContainingFile(), parent.getTextRange())) {
      if (parent instanceof PsiIfStatement) {
        if (((PsiIfStatement)parent).getCondition() != expr) return true;
      } else if (parent instanceof PsiConditionalExpression) {
        if (((PsiConditionalExpression)parent).getCondition() != expr) return true;
      } else if (parent instanceof PsiSwitchStatement) {
        if (((PsiSwitchStatement)parent).getExpression() != expr) return true;
      }
    } else {
      return false;
    }
    expr = parent;
  }
  return false;
}
项目:intellij-ce-playground    文件:XsltParameterImpl.java   
@NotNull
@Override
public SearchScope getLocalUseScope() {
    final XmlTag tag = getTag();
    if (!tag.isValid()) {
        return getDefaultUseScope();
    }
    final XsltTemplate template = getTemplate();
    if (template == null) {
        return getDefaultUseScope();
    }
    if (template.getName() == null) {
        return getDefaultUseScope();
    }
    final XmlFile file = (XmlFile)tag.getContainingFile();
    if (!XsltIncludeIndex.processBackwardDependencies(file, new CommonProcessors.FindFirstProcessor<XmlFile>())) {
        // processor found something
        return getDefaultUseScope();
    }
    return new LocalSearchScope(file);
}
项目:intellij-ce-playground    文件:InputVariables.java   
public void removeParametersUsedInExitsOnly(PsiElement codeFragment,
                                            Collection<PsiStatement> exitStatements,
                                            ControlFlow controlFlow,
                                            int startOffset,
                                            int endOffset) {
  final LocalSearchScope scope = new LocalSearchScope(codeFragment);
  Variables:
  for (Iterator<VariableData> iterator = myInputVariables.iterator(); iterator.hasNext();) {
    final VariableData data = iterator.next();
    for (PsiReference ref : ReferencesSearch.search(data.variable, scope)) {
      PsiElement element = ref.getElement();
      int elementOffset = controlFlow.getStartOffset(element);
      if (elementOffset >= startOffset && elementOffset <= endOffset) {
        if (!isInExitStatements(element, exitStatements)) continue Variables;
      }
    }
    iterator.remove();
  }
}
项目:intellij-ce-playground    文件:JoinDeclarationAndAssignmentAction.java   
private static Pair<PsiLocalVariable, PsiAssignmentExpression> getPair(PsiElement element) {
  PsiAssignmentExpression assignmentExpression = PsiTreeUtil.getParentOfType(element, PsiAssignmentExpression.class);
  PsiDeclarationStatement declarationStatement = PsiTreeUtil.getParentOfType(element, PsiDeclarationStatement.class);
  if (declarationStatement != null) {
    assignmentExpression = getAssignmentStatement(declarationStatement);
  } else if (assignmentExpression != null) {
    declarationStatement = getDeclarationStatement(assignmentExpression);
  }

  if (declarationStatement != null && assignmentExpression != null) {
    final PsiExpression lExpression = assignmentExpression.getLExpression();
    final PsiExpression rExpression = assignmentExpression.getRExpression();
    if (lExpression instanceof PsiReferenceExpression && rExpression != null) {
      final PsiElement resolve = ((PsiReferenceExpression)lExpression).resolve();
      if (resolve instanceof PsiLocalVariable && resolve.getParent() == declarationStatement) {
        final PsiLocalVariable variable = (PsiLocalVariable)resolve;
        if (ReferencesSearch.search(variable, new LocalSearchScope(rExpression), false).findFirst() != null) {
          return null;
        }
        return Pair.create(variable, assignmentExpression);
      }
    }
  }
  return null;
}
项目:intellij-ce-playground    文件:JavaRefactoringSupportProvider.java   
public static boolean mayRenameInplace(PsiElement elementToRename, final PsiElement nameSuggestionContext) {
  if (nameSuggestionContext != null && nameSuggestionContext.getContainingFile() != elementToRename.getContainingFile()) return false;
  if (!(elementToRename instanceof PsiLocalVariable) &&
      !(elementToRename instanceof PsiParameter) &&
      !(elementToRename instanceof PsiLabeledStatement)) {
    return false;
  }
  SearchScope useScope = PsiSearchHelper.SERVICE.getInstance(elementToRename.getProject()).getUseScope(elementToRename);
  if (!(useScope instanceof LocalSearchScope)) return false;
  PsiElement[] scopeElements = ((LocalSearchScope)useScope).getScope();
  if (scopeElements.length > 1 &&                          // assume there are no elements with use scopes with holes in them
      !isElementWithComment(scopeElements) &&              // ... except a case of element and it's doc comment
      !isResourceVariable(scopeElements)) {
    return false;    // ... and badly scoped resource variables
  }
  PsiFile containingFile = elementToRename.getContainingFile();
  return PsiTreeUtil.isAncestor(containingFile, scopeElements[0], false);
}
项目:intellij-ce-playground    文件:ControlFlowWrapper.java   
private void removeParametersUsedInExitsOnly(PsiElement codeFragment, List<PsiVariable> inputVariables) {
  LocalSearchScope scope = new LocalSearchScope(codeFragment);
  Variables:
  for (Iterator<PsiVariable> iterator = inputVariables.iterator(); iterator.hasNext();) {
    PsiVariable variable = iterator.next();
    for (PsiReference ref : ReferencesSearch.search(variable, scope)) {
      PsiElement element = ref.getElement();
      int elementOffset = myControlFlow.getStartOffset(element);
      if (elementOffset >= myFlowStart && elementOffset <= myFlowEnd) {
        if (!isInExitStatements(element, myExitStatements)) continue Variables;
      }
      if (elementOffset == -1) { //references in local/anonymous classes should not be skipped
        final PsiClass psiClass = PsiTreeUtil.getParentOfType(element, PsiClass.class);
        if (psiClass != null) {
          final TextRange textRange = psiClass.getTextRange();
          if (myControlFlow.getElement(myFlowStart).getTextOffset() <= textRange.getStartOffset() &&
              textRange.getEndOffset() <= myControlFlow.getElement(myFlowEnd).getTextRange().getEndOffset()) {
            continue Variables;
          }
        }
      }
    }
    iterator.remove();
  }
}
项目:intellij-ce-playground    文件:IntroduceFieldCentralPanel.java   
private boolean initializedInSetUp(Set<PsiField> fields) {
  if (hasSetUpChoice()) {
    for (PsiField field : fields) {
      final PsiMethod setUpMethod = TestFrameworks.getInstance().findSetUpMethod((field).getContainingClass());
      if (setUpMethod != null) {
        final Processor<PsiReference> initializerSearcher = new Processor<PsiReference>() {
          @Override
          public boolean process(PsiReference reference) {
            final PsiElement referenceElement = reference.getElement();
            if (referenceElement instanceof PsiExpression) {
              return !PsiUtil.isAccessedForWriting((PsiExpression)referenceElement);
            }
            return true;
          }
        };
        if (ReferencesSearch.search(field, new LocalSearchScope(setUpMethod)).forEach(initializerSearcher)) {
          return false;
        }
      }
    }
    return true;
  }
  return false;
}
项目:intellij-ce-playground    文件:SafeDeleteJavaCallerChooser.java   
private PsiParameter getParameter(PsiMethod caller) {

      //do not change hierarchy
      if (caller.findDeepestSuperMethods().length > 0) {
        return null;
      }

      //find first method call
      final Ref<PsiParameter> ref = new Ref<PsiParameter>();
      ReferencesSearch.search(myMethod, new LocalSearchScope(caller)).forEach(new Processor<PsiReference>() {
        @Override
        public boolean process(PsiReference reference) {
          final PsiElement element = reference.getElement();
          if (element instanceof PsiReferenceExpression) {
            final PsiElement elementParent = element.getParent();
            if (elementParent instanceof PsiCallExpression) {
              ref.set(isTheOnlyOneParameterUsage(elementParent, myParameterIdx, myMethod));
              return false;
            }
          }
          return true;
        }
      });
      return ref.get();
    }
项目:intellij-ce-playground    文件:FindParameterTest.java   
public void testMethod() throws Exception {
  String text =
          "void method(final int i) {" +
          "  Runnable runnable = new Runnable() {" +
          "    public void run() {" +
          "      System.out.println(i);" +
          "    }" +
          "  };" +
          "  System.out.println(i);" +
          "}";
  final PsiManager psiManager = PsiManager.getInstance(myProject);
  final PsiElementFactory elementFactory = JavaPsiFacade.getInstance(psiManager.getProject()).getElementFactory();
  final PsiMethod methodFromText = elementFactory.createMethodFromText(text, null);
  final PsiParameter[] parameters = methodFromText.getParameterList().getParameters();
  final PsiReference[] references =
    ReferencesSearch.search(parameters[0], new LocalSearchScope(methodFromText), false).toArray(new PsiReference[0]);
  Assert.assertEquals(references.length, 2);
}
项目:intellij-ce-playground    文件:FindManagerTest.java   
public void testFindInClassHierarchy() {
  initProject("findInClassHierarchy", "src");

  FindModel findModel = new FindModel();
  findModel.setStringToFind("instanceof");
  findModel.setWholeWordsOnly(true);
  findModel.setFromCursor(false);
  findModel.setGlobal(true);
  findModel.setMultipleFiles(true);
  final JavaPsiFacade facade = JavaPsiFacade.getInstance(getProject());
  final PsiClass baseClass = facade.findClass("A", GlobalSearchScope.allScope(getProject()));
  final PsiClass implClass = facade.findClass("AImpl", GlobalSearchScope.allScope(getProject()));
  findModel.setCustomScope(new LocalSearchScope(new PsiElement[]{baseClass, implClass}));

  List<UsageInfo> usages = findUsages(findModel);
  assertEquals(2, usages.size());
}
项目:intellij-ce-playground    文件:GroovyRefactoringSupportProvider.java   
@Override
public boolean isInplaceRenameAvailable(@NotNull PsiElement elementToRename, PsiElement nameSuggestionContext) {
  //local vars & params renames GrVariableInplaceRenameHandler

  if (nameSuggestionContext != null && nameSuggestionContext.getContainingFile() != elementToRename.getContainingFile()) return false;
  if (!(elementToRename instanceof GrLabeledStatement)) {
    return false;
  }
  SearchScope useScope = PsiSearchHelper.SERVICE.getInstance(elementToRename.getProject()).getUseScope(elementToRename);
  if (!(useScope instanceof LocalSearchScope)) return false;
  PsiElement[] scopeElements = ((LocalSearchScope)useScope).getScope();
  if (scopeElements.length > 1) {
    return false;
  }

  PsiFile containingFile = elementToRename.getContainingFile();
  return PsiTreeUtil.isAncestor(containingFile, scopeElements[0], false);

}
项目:intellij-ce-playground    文件:AnalysisScope.java   
public boolean contains(@NotNull VirtualFile file) {
  if (myFilesSet == null) {
    if (myType == CUSTOM) {
      // optimization
      if (myScope instanceof GlobalSearchScope) return ((GlobalSearchScope)myScope).contains(file);
      if (myScope instanceof LocalSearchScope) return ((LocalSearchScope)myScope).isInScope(file);
    }
    if (myType == PROJECT) {  //optimization
      final ProjectFileIndex index = ProjectRootManager.getInstance(myProject).getFileIndex();
      return index.isInContent(file) && (myIncludeTestSource || !index.isInTestSourceContent(file));
    }
    initFilesSet();
  }

  return myFilesSet.contains(file);
}
项目:intellij-ce-playground    文件:PsiElement2UsageTargetAdapter.java   
@Override
public void highlightUsages(@NotNull PsiFile file, @NotNull Editor editor, boolean clearHighlights) {
  PsiElement target = getElement();

  if (file instanceof PsiCompiledFile) file = ((PsiCompiledFile)file).getDecompiledPsiFile();

  Project project = target.getProject();
  final FindUsagesManager findUsagesManager = ((FindManagerImpl)FindManager.getInstance(project)).getFindUsagesManager();
  final FindUsagesHandler handler = findUsagesManager.getFindUsagesHandler(target, true);

  // in case of injected file, use host file to highlight all occurrences of the target in each injected file
  PsiFile context = InjectedLanguageManager.getInstance(project).getTopLevelFile(file);
  SearchScope searchScope = new LocalSearchScope(context);
  Collection<PsiReference> refs = handler == null
                                  ? ReferencesSearch.search(target, searchScope, false).findAll()
                                  : handler.findReferencesToHighlight(target, searchScope);

  new HighlightUsagesHandler.DoHighlightRunnable(new ArrayList<PsiReference>(refs), project, target,
                                                 editor, context, clearHighlights).run();
}
项目:intellij-ce-playground    文件:PyIntroduceFieldHandler.java   
@Override
protected List<PsiElement> getOccurrences(PsiElement element, @NotNull PyExpression expression) {
  if (isAssignedLocalVariable(element)) {
    PyFunction function = PsiTreeUtil.getParentOfType(element, PyFunction.class);
    Collection<PsiReference> references = ReferencesSearch.search(element, new LocalSearchScope(function)).findAll();
    ArrayList<PsiElement> result = new ArrayList<PsiElement>();
    for (PsiReference reference : references) {
      PsiElement refElement = reference.getElement();
      if (refElement != element) {
        result.add(refElement);
      }
    }
    return result;
  }
  return super.getOccurrences(element, expression);
}
项目:intellij-ce-playground    文件:RenameXmlAttributeProcessor.java   
private static void renameAll(PsiElement originalElement, UsageInfo[] infos, String newName,
                              String originalName) throws IncorrectOperationException {
  if (newName.equals(originalName)) return;
  Queue<PsiReference> queue = new Queue<PsiReference>(infos.length);
  for (UsageInfo info : infos) {
    if (info.getElement() == null) continue;
    PsiReference ref = info.getReference();
    if (ref == null) continue;
    queue.addLast(ref);
  }

  while(!queue.isEmpty()) {
    final PsiReference reference = queue.pullFirst();
    final PsiElement oldElement = reference.getElement();
    if (!oldElement.isValid() || oldElement == originalElement) continue;
    final PsiElement newElement = reference.handleElementRename(newName);
    if (!oldElement.isValid()) {
      for (PsiReference psiReference : ReferencesSearch.search(originalElement, new LocalSearchScope(newElement), false)) {
        queue.addLast(psiReference);
      }
    }
  }
}
项目:intellij-ce-playground    文件:UnusedDefineInspection.java   
@Override
public void visitDefine(RncDefine pattern) {
  final RncGrammar grammar = PsiTreeUtil.getParentOfType(pattern, RncGrammar.class);
  final PsiFile file = pattern.getContainingFile();
  if (grammar != null) {
    if (processRncUsages(pattern, new LocalSearchScope(grammar))) return;
  } else {
    if (processRncUsages(pattern, new LocalSearchScope(file))) return;
  }

  final PsiElementProcessor.CollectElements<XmlFile> collector = new PsiElementProcessor.CollectElements<XmlFile>();
  RelaxIncludeIndex.processBackwardDependencies((XmlFile)file, collector);

  if (processRncUsages(pattern, new LocalSearchScope(collector.toArray()))) return;

  final ASTNode astNode = ((RncDefineImpl)pattern).getNameNode();
  myHolder.registerProblem(astNode.getPsi(), "Unreferenced define", ProblemHighlightType.LIKE_UNUSED_SYMBOL, new MyFix<RncDefine>(pattern));
}
项目:intellij-ce-playground    文件:GrParameterImpl.java   
@Override
@NotNull
public SearchScope getUseScope() {
  if (!isPhysical()) {
    final PsiFile file = getContainingFile();
    final PsiElement context = file.getContext();
    if (context != null) return new LocalSearchScope(context);
    return super.getUseScope();
  }

  final PsiElement scope = getDeclarationScope();
  if (scope instanceof GrDocCommentOwner) {
    GrDocCommentOwner owner = (GrDocCommentOwner)scope;
    final GrDocComment comment = owner.getDocComment();
    if (comment != null) {
      return new LocalSearchScope(new PsiElement[]{scope, comment});
    }
  }

  return new LocalSearchScope(scope);
}
项目:intellij-ce-playground    文件:ImportOnDemandIntention.java   
@Override
protected void processIntention(@NotNull PsiElement element, Project project, Editor editor) throws IncorrectOperationException {
  if (!(element instanceof GrReferenceElement)) return;
  final GrReferenceElement ref = (GrReferenceElement)element;
  final PsiElement resolved = ref.resolve();
  if (!(resolved instanceof PsiClass)) return;

  final String qname = ((PsiClass)resolved).getQualifiedName();

  final GrImportStatement importStatement =
    GroovyPsiElementFactory.getInstance(project).createImportStatementFromText(qname, true, true, null);

  final PsiFile containingFile = element.getContainingFile();
  if (!(containingFile instanceof GroovyFile)) return;
  ((GroovyFile)containingFile).addImport(importStatement);

  for (PsiReference reference : ReferencesSearch.search(resolved, new LocalSearchScope(containingFile))) {
    final PsiElement refElement = reference.getElement();
    if (refElement == null) continue;
    final PsiElement parent = refElement.getParent();
    if (parent instanceof GrQualifiedReference<?>) {
      org.jetbrains.plugins.groovy.codeStyle.GrReferenceAdjuster.shortenReference((GrQualifiedReference<?>)parent);
    }
  }
}
项目:jgiven-intellij-plugin    文件:ReferenceProviderTest.java   
@Test
public void should_not_process_reference_if_search_scope_is_not_global() throws Exception {
    // given
    PsiField field = mock(PsiField.class);
    ReferencesSearch.SearchParameters searchParameters = mock(ReferencesSearch.SearchParameters.class);
    when(searchParameters.getElementToSearch()).thenReturn(field);
    when(searchParameters.getEffectiveSearchScope()).thenReturn(mock(LocalSearchScope.class));
    when(scenarioStateProvider.isJGivenScenarioState(field)).thenReturn(true);

    // when
    referenceProvider.processQuery(searchParameters, processor);

    // then
    verifyZeroInteractions(processor);
}
项目:intellij-ce-playground    文件:AllClassesSearchExecutor.java   
@Override
public boolean execute(@NotNull final AllClassesSearch.SearchParameters queryParameters, @NotNull final Processor<PsiClass> consumer) {
  SearchScope scope = queryParameters.getScope();

  if (scope instanceof GlobalSearchScope) {
    return processAllClassesInGlobalScope((GlobalSearchScope)scope, queryParameters, consumer);
  }

  PsiElement[] scopeRoots = ((LocalSearchScope)scope).getScope();
  for (final PsiElement scopeRoot : scopeRoots) {
    if (!processScopeRootForAllClasses(scopeRoot, consumer)) return false;
  }
  return true;
}
项目:intellij-ce-playground    文件:PsiLocalVariableImpl.java   
@Override
@NotNull
public SearchScope getUseScope() {
  final PsiElement parentElement = getParent();
  if (parentElement instanceof PsiDeclarationStatement) {
    return new LocalSearchScope(parentElement.getParent());
  }
  else {
    return ResolveScopeManager.getElementUseScope(this);
  }
}
项目:intellij-ce-playground    文件:PsiImplUtil.java   
@NotNull
public static SearchScope getMemberUseScope(@NotNull PsiMember member) {
  PsiFile file = member.getContainingFile();
  PsiElement topElement = file == null ? member : file;
  Project project = topElement.getProject();
  final GlobalSearchScope maximalUseScope = ResolveScopeManager.getInstance(project).getUseScope(topElement);
  if (isInServerPage(file)) return maximalUseScope;

  PsiClass aClass = member.getContainingClass();
  if (aClass instanceof PsiAnonymousClass) {
    //member from anonymous class can be called from outside the class
    PsiElement methodCallExpr = PsiUtil.isLanguageLevel8OrHigher(aClass) ? PsiTreeUtil.getTopmostParentOfType(aClass, PsiStatement.class) 
                                                                         : PsiTreeUtil.getParentOfType(aClass, PsiMethodCallExpression.class);
    return new LocalSearchScope(methodCallExpr != null ? methodCallExpr : aClass);
  }

  PsiModifierList modifierList = member.getModifierList();
  int accessLevel = modifierList == null ? PsiUtil.ACCESS_LEVEL_PUBLIC : PsiUtil.getAccessLevel(modifierList);
  if (accessLevel == PsiUtil.ACCESS_LEVEL_PUBLIC || accessLevel == PsiUtil.ACCESS_LEVEL_PROTECTED) {
    return maximalUseScope; // class use scope doesn't matter, since another very visible class can inherit from aClass
  }
  if (accessLevel == PsiUtil.ACCESS_LEVEL_PRIVATE) {
    PsiClass topClass = PsiUtil.getTopLevelClass(member);
    return topClass != null ? new LocalSearchScope(topClass) : file == null ? maximalUseScope : new LocalSearchScope(file);
  }
  if (file instanceof PsiJavaFile) {
    PsiPackage aPackage = JavaPsiFacade.getInstance(project).findPackage(((PsiJavaFile)file).getPackageName());
    if (aPackage != null) {
      SearchScope scope = PackageScope.packageScope(aPackage, false);
      return scope.intersectWith(maximalUseScope);
    }
  }
  return maximalUseScope;
}
项目:intellij-ce-playground    文件:InferenceFromSourceUtil.java   
private static boolean isUnusedInAnonymousClass(@NotNull PsiMethod method) {
  PsiClass containingClass = method.getContainingClass();
  if (!(containingClass instanceof PsiAnonymousClass)) {
    return false;
  }

  if (containingClass.getParent() instanceof PsiNewExpression && 
      containingClass.getParent().getParent() instanceof PsiVariable && 
      !method.getHierarchicalMethodSignature().getSuperSignatures().isEmpty()) {
    // references outside anonymous class can still resolve to this method, see com.intellij.psi.scope.util.PsiScopesUtil.setupAndRunProcessor()
    return false;
  }

  return MethodReferencesSearch.search(method, new LocalSearchScope(containingClass), false).findFirst() == null;
}
项目:intellij-ce-playground    文件:HighlightControlFlowUtil.java   
@Nullable
static HighlightInfo checkVariableMustBeFinal(@NotNull PsiVariable variable,
                                              @NotNull PsiJavaCodeReferenceElement context,
                                              @NotNull LanguageLevel languageLevel) {
  if (variable.hasModifierProperty(PsiModifier.FINAL)) return null;
  final PsiElement innerClass = getInnerClassVariableReferencedFrom(variable, context);
  if (innerClass instanceof PsiClass) {
    if (variable instanceof PsiParameter) {
      final PsiElement parent = variable.getParent();
      if (parent instanceof PsiParameterList && parent.getParent() instanceof PsiLambdaExpression &&
          notAccessedForWriting(variable, new LocalSearchScope(((PsiParameter)variable).getDeclarationScope()))) {
        return null;
      }
    }
    final boolean isToBeEffectivelyFinal = languageLevel.isAtLeast(LanguageLevel.JDK_1_8);
    if (isToBeEffectivelyFinal && isEffectivelyFinal(variable, innerClass, context)) {
      return null;
    }
    final String description = JavaErrorMessages.message(isToBeEffectivelyFinal ? "variable.must.be.final.or.effectively.final" : "variable.must.be.final", context.getText());

    final HighlightInfo highlightInfo =
      HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(context).descriptionAndTooltip(description).create();
    QuickFixAction.registerQuickFixAction(highlightInfo, QUICK_FIX_FACTORY.createVariableAccessFromInnerClassFix(variable, innerClass));
    return highlightInfo;
  }
  return checkWriteToFinalInsideLambda(variable, context);
}
项目:intellij-ce-playground    文件:HighlightControlFlowUtil.java   
public static boolean isEffectivelyFinal(@NotNull PsiVariable variable, @NotNull PsiElement scope, @Nullable PsiJavaCodeReferenceElement context) {
  boolean effectivelyFinal;
  if (variable instanceof PsiParameter) {
    effectivelyFinal = notAccessedForWriting(variable, new LocalSearchScope(((PsiParameter)variable).getDeclarationScope()));
  }
  else {
    final ControlFlow controlFlow;
    try {
      PsiElement codeBlock = PsiUtil.getVariableCodeBlock(variable, context);
      if (codeBlock == null) return true;
      controlFlow = getControlFlow(codeBlock);
    }
    catch (AnalysisCanceledException e) {
      return true;
    }

    final List<PsiReferenceExpression> readBeforeWriteLocals = ControlFlowUtil.getReadBeforeWriteLocals(controlFlow);
    for (PsiReferenceExpression expression : readBeforeWriteLocals) {
      if (expression.resolve() == variable) {
        return PsiUtil.isAccessedForReading(expression);
      }
    }

    final Collection<ControlFlowUtil.VariableInfo> initializedTwice = ControlFlowUtil.getInitializedTwice(controlFlow);
    effectivelyFinal = !initializedTwice.contains(new ControlFlowUtil.VariableInfo(variable, null));
    if (effectivelyFinal) {
      effectivelyFinal = notAccessedForWriting(variable, new LocalSearchScope(scope));
    }
  }
  return effectivelyFinal;
}
项目:intellij-ce-playground    文件:HighlightControlFlowUtil.java   
private static boolean notAccessedForWriting(@NotNull PsiVariable variable, @NotNull LocalSearchScope searchScope) {
  for (PsiReference reference : ReferencesSearch.search(variable, searchScope)) {
    final PsiElement element = reference.getElement();
    if (element instanceof PsiExpression && PsiUtil.isAccessedForWriting((PsiExpression)element)) {
      return false;
    }
  }
  return true;
}
项目:intellij-ce-playground    文件:ParametersFolder.java   
public boolean isParameterFoldable(@NotNull VariableData data,
                                   @NotNull LocalSearchScope scope,
                                   @NotNull final List<? extends PsiVariable> inputVariables) {
  final List<PsiExpression> mentionedInExpressions = getMentionedExpressions(data.variable, scope, inputVariables);
  if (mentionedInExpressions == null) return false;

  int currentRank = 0;
  PsiExpression mostRanked = null;
  for (int i = mentionedInExpressions.size() - 1; i >= 0; i--) {
    PsiExpression expression = mentionedInExpressions.get(i);
    if (expression instanceof PsiArrayAccessExpression) {
      mostRanked = expression;
      if (!isConditional(expression, scope)) {
        myFoldingSelectedByDefault = true;
        break;
      }
    }
    final int r = findUsedVariables(data, inputVariables, expression).size();
    if (currentRank < r) {
      currentRank = r;
      mostRanked = expression;
    }
  }

  if (mostRanked != null) {
    myExpressions.put(data.variable, mostRanked);
    data.type = mostRanked.getType();
    final JavaCodeStyleManager codeStyleManager = JavaCodeStyleManager.getInstance(mostRanked.getProject());
    final SuggestedNameInfo nameInfo = codeStyleManager.suggestVariableName(VariableKind.PARAMETER, null, mostRanked, data.type);
    if (nameInfo.names.length > 0) {
      data.name = nameInfo.names[0];
    }
    setUniqueName(data, scope, mostRanked);
  }

  return mostRanked != null;
}
项目:intellij-ce-playground    文件:ParametersFolder.java   
private void setUniqueName(VariableData data, LocalSearchScope scope, PsiExpression expr) {
  String name = data.name;
  int idx = 1;
  while (true) {
    if (myUsedNames.add(name)) {
      final PsiVariable definedVariable = PsiResolveHelper.SERVICE.getInstance(expr.getProject()).resolveReferencedVariable(name, expr);
      if (definedVariable == null || !scope.containsRange(expr.getContainingFile(), definedVariable.getTextRange())) {
        data.name = name;
        break;
      }
    }
    name = data.name + idx++;
  }
}
项目:intellij-ce-playground    文件:XsltImplicitUsagesProvider.java   
public boolean isImplicitUsage(PsiElement element) {
    if (!(element instanceof XmlAttribute)) {
        return false;
    }
    final XmlAttribute attr = (XmlAttribute)element;
    if (!attr.isNamespaceDeclaration()) {
        return false;
    }
    final PsiFile file = attr.getContainingFile();
    if (!(file instanceof XmlFile)) {
      return false;
    }

    // also catch namespace declarations in "normal" XML files that have XPath injected into some attributes
    // ContextProvider.hasXPathInjections() is an optimization that avoids to run the references search on totally XPath-free XML files
    if (!ContextProvider.hasXPathInjections((XmlFile)file) && !XsltSupport.isXsltFile(file)) {
        return false;
    }

    // This need to catch both prefix references from injected XPathFiles and prefixes from mode declarations/references:
    // <xsl:template match="*" mode="prefix:name" />

    // BTW: Almost the same logic applies to other XML dialects (RELAX-NG).
    // Pull this class into the platform?
    final String prefix = attr.getLocalName();
    final SchemaPrefix target = new SchemaPrefix(attr, TextRange.from("xmlns:".length(), prefix.length()), prefix);
    final Query<PsiReference> q = ReferencesSearch.search(target, new LocalSearchScope(attr.getParent()));
    return !q.forEach(new Processor<PsiReference>() {
        public boolean process(PsiReference psiReference) {
            if (psiReference.getElement() == attr) {
                return true;
            }
            return false;
        }
    });
}
项目:intellij-ce-playground    文件:InputVariables.java   
/**
 * copy use only
 */
public InputVariables(List<VariableData> inputVariables,
                      Project project,
                      LocalSearchScope scope) {
  myProject = project;
  myScope = scope;
  myInputVariables = new ArrayList<VariableData>(inputVariables);
}
项目:intellij-ce-playground    文件:GroovyIntroduceParameterUtil.java   
static PsiElement[] getOccurrences(GrIntroduceParameterSettings settings) {
  final GrParametersOwner scope = settings.getToReplaceIn();

  final GrExpression expression = settings.getExpression();
  if (expression != null) {
    final PsiElement expr = PsiUtil.skipParentheses(expression, false);
    if (expr == null) return PsiElement.EMPTY_ARRAY;

    final PsiElement[] occurrences = GroovyRefactoringUtil.getExpressionOccurrences(expr, scope);
    if (occurrences == null || occurrences.length == 0) {
      throw new GrRefactoringError(GroovyRefactoringBundle.message("no.occurrences.found"));
    }
    return occurrences;
  }
  else {
    final GrVariable var = settings.getVar();
    LOG.assertTrue(var != null);
    final List<PsiElement> list = Collections.synchronizedList(new ArrayList<PsiElement>());
    ReferencesSearch.search(var, new LocalSearchScope(scope)).forEach(new Processor<PsiReference>() {
      @Override
      public boolean process(PsiReference psiReference) {
        final PsiElement element = psiReference.getElement();
        if (element != null) {
          list.add(element);
        }
        return true;
      }
    });
    return list.toArray(new PsiElement[list.size()]);
  }
}
项目:intellij-ce-playground    文件:FieldConflictsResolver.java   
public FieldConflictsResolver(String name, GrCodeBlock scope) {
  myScope = scope;
  if (myScope == null) {
    myField = null;
    myReferenceExpressions = null;
    return;
  }
  JavaPsiFacade facade = JavaPsiFacade.getInstance(myScope.getProject());
  final PsiVariable oldVariable = facade.getResolveHelper().resolveAccessibleReferencedVariable(name, myScope);
  myField = oldVariable instanceof PsiField ? (PsiField)oldVariable : null;

  if (!(oldVariable instanceof PsiField)) {
    myReferenceExpressions = null;
    return;
  }
  myReferenceExpressions = new ArrayList<GrReferenceExpression>();
  for (PsiReference reference : ReferencesSearch.search(myField, new LocalSearchScope(myScope), false)) {
    final PsiElement element = reference.getElement();
    if (element instanceof GrReferenceExpression) {
      final GrReferenceExpression referenceExpression = (GrReferenceExpression)element;
      if (referenceExpression.getQualifierExpression() == null) {
        myReferenceExpressions.add(referenceExpression);
      }
    }
  }
  if (myField.hasModifierProperty(PsiModifier.STATIC)) {
    myQualifyingClass = myField.getContainingClass();
  }
}
项目:intellij-ce-playground    文件:InitializeFinalFieldInConstructorFix.java   
private static PsiMethod[] filterIfFieldAlreadyAssigned(@NotNull PsiField field, @NotNull PsiMethod[] ctors) {
  final List<PsiMethod> result = new ArrayList<PsiMethod>(Arrays.asList(ctors));
  for (PsiReference reference : ReferencesSearch.search(field, new LocalSearchScope(ctors))) {
    final PsiElement element = reference.getElement();
    if (element instanceof PsiReferenceExpression && PsiUtil.isOnAssignmentLeftHand((PsiExpression)element)) {
      result.remove(PsiTreeUtil.getParentOfType(element, PsiMethod.class));
    }
  }
  return result.toArray(new PsiMethod[result.size()]);
}
项目:intellij-ce-playground    文件:ConvertSwitchToIfIntention.java   
private static void dumpBody(List<PsiElement> bodyStatements,
                             Set<PsiLocalVariable> variables,
                             @NonNls StringBuilder ifStatementString) {
  ifStatementString.append('{');
  for (PsiLocalVariable variable : variables) {
    if (ReferencesSearch.search(variable, new LocalSearchScope(bodyStatements.toArray(new PsiElement[bodyStatements.size()]))).findFirst() != null) {
      final PsiType varType = variable.getType();
      ifStatementString.append(varType.getPresentableText());
      ifStatementString.append(' ');
      ifStatementString.append(variable.getName());
      ifStatementString.append(';');
    }
  }
  for (PsiElement bodyStatement : bodyStatements) {
    if (bodyStatement instanceof PsiBlockStatement) {
      final PsiBlockStatement blockStatement =
        (PsiBlockStatement)bodyStatement;
      final PsiCodeBlock codeBlock = blockStatement.getCodeBlock();
      final PsiStatement[] statements = codeBlock.getStatements();
      for (PsiStatement statement : statements) {
        appendElement(statement, ifStatementString);
      }
    }
    else {
      appendElement(bodyStatement, ifStatementString);
    }
  }
  ifStatementString.append("\n}");
}
项目:intellij-ce-playground    文件:CreateConstructorParameterFromFieldFix.java   
private static ArrayList<PsiMethod> filterConstructorsIfFieldAlreadyAssigned(PsiMethod[] constructors, PsiField field) {
  final ArrayList<PsiMethod> result = new ArrayList<PsiMethod>(Arrays.asList(constructors));
  for (PsiReference reference : ReferencesSearch.search(field, new LocalSearchScope(constructors))) {
    final PsiElement element = reference.getElement();
    if (element instanceof PsiReferenceExpression && PsiUtil.isOnAssignmentLeftHand((PsiExpression)element)) {
      result.remove(PsiTreeUtil.getParentOfType(element, PsiMethod.class));
    }
  }
  return result;
}
项目:intellij-ce-playground    文件:JavaTargetElementEvaluator.java   
@Override
@Nullable
public SearchScope getSearchScope(Editor editor, @NotNull PsiElement element) {
  final PsiReferenceExpression referenceExpression = editor != null ? findReferenceExpression(editor) : null;
  if (referenceExpression != null && element instanceof PsiMethod) {
    final PsiClass[] memberClass = getMemberClass(referenceExpression, element);
    if (memberClass != null && memberClass.length == 1) {
      return CachedValuesManager.getCachedValue(memberClass[0], new CachedValueProvider<SearchScope>() {
        @Nullable
        @Override
        public Result<SearchScope> compute() {
          final List<PsiClass> classesToSearch = ContainerUtil.newArrayList(memberClass);
          classesToSearch.addAll(ClassInheritorsSearch.search(memberClass[0], true).findAll());

          final Set<PsiClass> supers = new HashSet<PsiClass>();
          for (PsiClass psiClass : classesToSearch) {
            supers.addAll(InheritanceUtil.getSuperClasses(psiClass));
          }
          classesToSearch.addAll(supers);

          return new Result<SearchScope>(new LocalSearchScope(PsiUtilCore.toPsiElementArray(classesToSearch)), PsiModificationTracker.JAVA_STRUCTURE_MODIFICATION_COUNT);
        }
      });
    }
  }
  return super.getSearchScope(editor, element);
}
项目:intellij-ce-playground    文件:FieldFromParameterUtils.java   
@Nullable
public static PsiField getParameterAssignedToField(final PsiParameter parameter) {
  for (PsiReference reference : ReferencesSearch.search(parameter, new LocalSearchScope(parameter.getDeclarationScope()), false)) {
    if (!(reference instanceof PsiReferenceExpression)) continue;
    final PsiReferenceExpression expression = (PsiReferenceExpression)reference;
    if (!(expression.getParent() instanceof PsiAssignmentExpression)) continue;
    final PsiAssignmentExpression assignmentExpression = (PsiAssignmentExpression)expression.getParent();
    if (assignmentExpression.getRExpression() != expression) continue;
    final PsiExpression lExpression = assignmentExpression.getLExpression();
    if (!(lExpression instanceof PsiReferenceExpression)) continue;
    final PsiElement element = ((PsiReferenceExpression)lExpression).resolve();
    if (element instanceof PsiField) return (PsiField)element;
  }
  return null;
}
项目:intellij-ce-playground    文件:ImportHelper.java   
private static void calcClassesToReimport(PsiJavaFile file, JavaPsiFacade facade, PsiResolveHelper helper, String packageName, List<PsiClass> classesToReimport,
                                   Collection<String> onDemandRefs) {
  if (onDemandRefs.isEmpty()) {
    return;
  }
  PsiPackage aPackage = facade.findPackage(packageName);
  if (aPackage != null) {
    PsiDirectory[] dirs = aPackage.getDirectories();
    GlobalSearchScope resolveScope = file.getResolveScope();
    for (PsiDirectory dir : dirs) {
      PsiFile[] files = dir.getFiles(); // do not iterate classes - too slow when not loaded
      for (PsiFile aFile : files) {
        if (!(aFile instanceof PsiJavaFile)) continue;
        String name = aFile.getVirtualFile().getNameWithoutExtension();
        for (String refName : onDemandRefs) {
          String conflictClassName = refName + "." + name;
          PsiClass conflictClass = facade.findClass(conflictClassName, resolveScope);
          if (conflictClass == null || !helper.isAccessible(conflictClass, file, null)) continue;
          String conflictClassName2 = packageName + "." + name;
          PsiClass conflictClass2 = facade.findClass(conflictClassName2, resolveScope);
          if (conflictClass2 != null &&
              helper.isAccessible(conflictClass2, file, null) &&
              ReferencesSearch.search(conflictClass, new LocalSearchScope(file), false).findFirst() != null) {
            classesToReimport.add(conflictClass);
          }
        }
      }
    }
  }
}
项目:intellij-ce-playground    文件:ConvertToInstanceMethodProcessor.java   
private void prepareTypeParameterReplacement() throws IncorrectOperationException {
  if (myTypeParameterReplacements == null) return;
  final Collection<PsiTypeParameter> typeParameters = myTypeParameterReplacements.keySet();
  for (final PsiTypeParameter parameter : typeParameters) {
    for (final PsiReference reference : ReferencesSearch.search(parameter, new LocalSearchScope(myMethod), false)) {
      if (reference.getElement() instanceof PsiJavaCodeReferenceElement) {
        reference.getElement().putCopyableUserData(BIND_TO_TYPE_PARAMETER, myTypeParameterReplacements.get(parameter));
      }
    }
  }
  final Set<PsiTypeParameter> methodTypeParameters = myTypeParameterReplacements.keySet();
  for (final PsiTypeParameter methodTypeParameter : methodTypeParameters) {
    methodTypeParameter.delete();
  }
}