@NotNull
 private static Collection<VirtualFile> gatherIncludeRoots(
     Collection<VirtualFile> goPathSourcesRoots, Set<VirtualFile> excludeRoots) {
   Collection<VirtualFile> includeRoots = ContainerUtil.newHashSet();
   for (VirtualFile goPathSourcesDirectory : goPathSourcesRoots) {
     ProgressIndicatorProvider.checkCanceled();
     boolean excludedRootIsAncestor = false;
     for (VirtualFile excludeRoot : excludeRoots) {
       ProgressIndicatorProvider.checkCanceled();
       if (VfsUtilCore.isAncestor(excludeRoot, goPathSourcesDirectory, false)) {
         excludedRootIsAncestor = true;
         break;
       }
     }
     if (excludedRootIsAncestor) {
       continue;
     }
     for (VirtualFile file : goPathSourcesDirectory.getChildren()) {
       ProgressIndicatorProvider.checkCanceled();
       if (file.isDirectory() && !excludeRoots.contains(file)) {
         includeRoots.add(file);
       }
     }
   }
   return includeRoots;
 }
Пример #2
0
 @Override
 public PsiElement resolve() {
   PsiElement _xblockexpression = null;
   {
     ProgressIndicatorProvider.checkCanceled();
     ICrossReferenceDescription crossReferenceDescription = this.getCrossReferenceDescription();
     boolean _equals = Objects.equal(crossReferenceDescription, null);
     if (_equals) {
       return null;
     }
     EObject object = crossReferenceDescription.resolve();
     ProgressIndicatorProvider.checkCanceled();
     _xblockexpression = this.psiModelAssociations.getPsiElement(object);
   }
   return _xblockexpression;
 }
 public static void checkCanceled() throws ProcessCanceledException {
   // smart optimization! There's a thread started in ProgressManagerImpl, that set's this flag up
   // once in 10 milliseconds
   if (ourNeedToCheckCancel && ourInstance != null) {
     ourInstance.doCheckCanceled();
     ourNeedToCheckCancel = false;
   }
 }
Пример #4
0
 @Override
 public Object[] getVariants() {
   ArrayList<LookupElementBuilder> _xblockexpression = null;
   {
     ProgressIndicatorProvider.checkCanceled();
     ICrossReferenceDescription crossReferenceDescription = this.getCrossReferenceDescription();
     boolean _equals = Objects.equal(crossReferenceDescription, null);
     if (_equals) {
       return ((Object[])
           Conversions.unwrapArray(CollectionLiterals.<Object>emptyList(), Object.class));
     }
     ArrayList<LookupElementBuilder> variants =
         CollectionLiterals.<LookupElementBuilder>newArrayList();
     Iterable<IEObjectDescription> _variants = crossReferenceDescription.getVariants();
     for (final IEObjectDescription objectDescription : _variants) {
       {
         ProgressIndicatorProvider.checkCanceled();
         QualifiedName _name = objectDescription.getName();
         String name = this.qualifiedNameConverter.toString(_name);
         BaseXtextFile _xtextFile = this.myElement.getXtextFile();
         XtextResource _resource = _xtextFile.getResource();
         PsiElement element =
             this.psiModelAssociations.getPsiElement(objectDescription, _resource);
         boolean _notEquals = (!Objects.equal(element, null));
         if (_notEquals) {
           LookupElementBuilder _create = LookupElementBuilder.create(name);
           PsiElement _navigationElement = element.getNavigationElement();
           PsiFile _containingFile = _navigationElement.getContainingFile();
           String _name_1 = _containingFile.getName();
           LookupElementBuilder _withTypeText = _create.withTypeText(_name_1);
           variants.add(_withTypeText);
         }
       }
     }
     _xblockexpression = variants;
   }
   return ((Object[]) Conversions.unwrapArray(_xblockexpression, Object.class));
 }
    @Override
    public void run() {
      Project project = myModule.getProject();
      if (GoSdkService.getInstance(project).isGoModule(myModule)) {
        synchronized (myLastHandledGoPathSourcesRoots) {
          Collection<VirtualFile> goPathSourcesRoots =
              GoSdkUtil.getGoPathSources(project, myModule);
          Set<VirtualFile> excludeRoots =
              ContainerUtil.newHashSet(ProjectRootManager.getInstance(project).getContentRoots());
          ProgressIndicatorProvider.checkCanceled();
          if (!myLastHandledGoPathSourcesRoots.equals(goPathSourcesRoots)
              || !myLastHandledExclusions.equals(excludeRoots)) {
            Collection<VirtualFile> includeRoots =
                gatherIncludeRoots(goPathSourcesRoots, excludeRoots);
            ApplicationManager.getApplication()
                .invokeLater(
                    () -> {
                      if (!myModule.isDisposed()
                          && GoSdkService.getInstance(project).isGoModule(myModule)) {
                        attachLibraries(includeRoots, excludeRoots);
                      }
                    });

            myLastHandledGoPathSourcesRoots.clear();
            myLastHandledGoPathSourcesRoots.addAll(goPathSourcesRoots);

            myLastHandledExclusions.clear();
            myLastHandledExclusions.addAll(excludeRoots);

            List<String> paths = ContainerUtil.map(goPathSourcesRoots, VirtualFile::getPath);
            myWatchedRequests.clear();
            myWatchedRequests.addAll(LocalFileSystem.getInstance().addRootsToWatch(paths, true));
          }
        }
      } else {
        synchronized (myLastHandledGoPathSourcesRoots) {
          LocalFileSystem.getInstance().removeWatchedRoots(myWatchedRequests);
          myLastHandledGoPathSourcesRoots.clear();
          myLastHandledExclusions.clear();
          ApplicationManager.getApplication()
              .invokeLater(
                  () -> {
                    if (!myModule.isDisposed()
                        && GoSdkService.getInstance(project).isGoModule(myModule)) {
                      removeLibraryIfNeeded();
                    }
                  });
        }
      }
    }
Пример #6
0
  @Override
  public boolean areElementsEquivalent(PsiElement element1, PsiElement element2) {
    ProgressIndicatorProvider
        .checkCanceled(); // We hope this method is being called often enough to cancel daemon
                          // processes smoothly

    if (element1 == element2) return true;
    if (element1 == null || element2 == null) {
      return false;
    }

    return element1.equals(element2)
        || element1.isEquivalentTo(element2)
        || element2.isEquivalentTo(element1);
  }
  @Override
  @NotNull
  public ASTNode getNode() {
    ASTNode node = myNode;
    if (node == null) {
      ApplicationManager.getApplication().assertReadAccessAllowed();
      PsiFileImpl file = (PsiFileImpl) getContainingFile();
      synchronized (file.getStubLock()) {
        node = myNode;
        if (node == null) {
          NonCancelableSection criticalSection =
              ProgressIndicatorProvider.startNonCancelableSectionIfSupported();
          try {
            if (!file.isValid()) throw new PsiInvalidElementAccessException(this);
            FileElement treeElement = file.getTreeElement();
            StubTree stubTree = file.getStubTree();
            if (treeElement != null) {
              return notBoundInExistingAst(file, treeElement, stubTree);
            }
            final FileElement fileElement = file.loadTreeElement();
            node = myNode;
            if (node == null) {
              @NonNls
              String message =
                  "Failed to bind stub to AST for element "
                      + getClass()
                      + " in "
                      + (file.getVirtualFile() == null
                          ? "<unknown file>"
                          : file.getVirtualFile().getPath())
                      + "\nFile stub tree:\n"
                      + (stubTree != null
                          ? StringUtil.trimLog(
                              ((PsiFileStubImpl) stubTree.getRoot()).printTree(), 1024)
                          : " is null")
                      + "\nLoaded file AST:\n"
                      + StringUtil.trimLog(DebugUtil.treeToString(fileElement, true), 1024);
              throw new IllegalArgumentException(message);
            }
          } finally {
            criticalSection.done();
          }
        }
      }
    }

    return node;
  }
  @Override
  public boolean processFilesWithWord(
      @NotNull final Processor<PsiFile> psiFileProcessor,
      @NotNull final String word,
      final short occurrenceMask,
      @NotNull final GlobalSearchScope scope,
      final boolean caseSensitively) {
    final List<VirtualFile> vFiles = new ArrayList<VirtualFile>(5);
    collectVirtualFilesWithWord(
        new CommonProcessors.CollectProcessor<VirtualFile>(vFiles),
        word,
        occurrenceMask,
        scope,
        caseSensitively);
    if (vFiles.isEmpty()) return true;

    final Processor<VirtualFile> virtualFileProcessor =
        new ReadActionProcessor<VirtualFile>() {
          @Override
          public boolean processInReadAction(VirtualFile virtualFile) {
            if (virtualFile.isValid()) {
              final PsiFile psiFile = myPsiManager.findFile(virtualFile);
              return psiFile == null || psiFileProcessor.process(psiFile);
            }
            return true;
          }
        };

    // IMPORTANT!!!
    // Since implementation of virtualFileProcessor.process() may call indices directly or
    // indirectly,
    // we cannot call it inside FileBasedIndex.processValues() method
    // If we do, deadlocks are possible (IDEADEV-42137). So first we obtain files with the word
    // specified,
    // and then process them not holding indices' read lock.
    for (VirtualFile vFile : vFiles) {
      ProgressIndicatorProvider.checkCanceled();
      if (!virtualFileProcessor.process(vFile)) {
        return false;
      }
    }
    return true;
  }
Пример #9
0
  public PsiClass findClass(@NotNull final String qualifiedName, @NotNull GlobalSearchScope scope) {
    ProgressIndicatorProvider
        .checkCanceled(); // We hope this method is being called often enough to cancel daemon
                          // processes smoothly

    PsiClass aClass = javaFileManager.findClass(qualifiedName, scope);
    if (aClass != null) {
      return aClass;
    }

    for (PsiElementFinder finder : extensionPsiElementFinders) {
      aClass = finder.findClass(qualifiedName, scope);
      if (aClass != null) {
        return aClass;
      }
    }

    return null;
  }
  @Nullable
  private <TRef extends PsiReference, TResult> TResult resolve(
      @NotNull final TRef ref,
      @NotNull final AbstractResolver<TRef, TResult> resolver,
      boolean needToPreventRecursion,
      final boolean incompleteCode,
      boolean isPoly,
      boolean isPhysical) {
    ProgressIndicatorProvider.checkCanceled();
    if (isPhysical) {
      ApplicationManager.getApplication().assertReadAccessAllowed();
    }

    int index = getIndex(isPhysical, incompleteCode, isPoly);
    ConcurrentMap<TRef, TResult> map = getMap(index);
    TResult result = map.get(ref);
    if (result != null) {
      return result;
    }

    RecursionGuard.StackStamp stamp = myGuard.markStack();
    result =
        needToPreventRecursion
            ? myGuard.doPreventingRecursion(
                Trinity.create(ref, incompleteCode, isPoly),
                true,
                new Computable<TResult>() {
                  @Override
                  public TResult compute() {
                    return resolver.resolve(ref, incompleteCode);
                  }
                })
            : resolver.resolve(ref, incompleteCode);
    PsiElement element =
        result instanceof ResolveResult ? ((ResolveResult) result).getElement() : null;
    LOG.assertTrue(element == null || element.isValid(), result);

    if (stamp.mayCacheNow()) {
      cache(ref, map, result);
    }
    return result;
  }
  @NotNull
  public <T extends PsiPolyVariantReference> ResolveResult[] resolveWithCaching(
      @NotNull final T ref,
      @NotNull final PolyVariantContextResolver<T> resolver,
      boolean needToPreventRecursion,
      final boolean incompleteCode,
      @NotNull final PsiFile containingFile) {
    ProgressIndicatorProvider.checkCanceled();
    ApplicationManager.getApplication().assertReadAccessAllowed();

    int index = getIndex(containingFile.isPhysical(), incompleteCode, true);
    ConcurrentMap<T, ResolveResult[]> map = getMap(index);
    ResolveResult[] result = map.get(ref);
    if (result != null) {
      return result;
    }

    RecursionGuard.StackStamp stamp = myGuard.markStack();
    result =
        needToPreventRecursion
            ? myGuard.doPreventingRecursion(
                Pair.create(ref, incompleteCode),
                true,
                new Computable<ResolveResult[]>() {
                  @Override
                  public ResolveResult[] compute() {
                    return resolver.resolve(ref, containingFile, incompleteCode);
                  }
                })
            : resolver.resolve(ref, containingFile, incompleteCode);

    if (stamp.mayCacheNow()) {
      cache(ref, map, result);
    }
    return result == null ? ResolveResult.EMPTY_ARRAY : result;
  }
  @RequiredReadAction
  private static boolean processInheritors(
      @NotNull final Processor<DotNetTypeDeclaration> consumer,
      @NotNull final String baseVmQName,
      @NotNull final SearchScope searchScope,
      @NotNull final SearchParameters parameters) {

    if (DotNetTypes.System.Object.equals(baseVmQName)) {
      return AllTypesSearch.search(
              searchScope, parameters.getProject(), parameters.getNameCondition())
          .forEach(
              new Processor<DotNetTypeDeclaration>() {
                @Override
                public boolean process(final DotNetTypeDeclaration aClass) {
                  ProgressIndicatorProvider.checkCanceled();
                  final String qname1 =
                      ApplicationManager.getApplication()
                          .runReadAction(
                              new Computable<String>() {
                                @Override
                                @Nullable
                                public String compute() {
                                  return aClass.getVmQName();
                                }
                              });
                  return DotNetTypes.System.Object.equals(qname1)
                      || consumer.process(parameters.myTransformer.fun(aClass));
                }
              });
    }

    final Ref<String> currentBase = Ref.create(null);
    final Stack<String> stack = new Stack<String>();
    // there are two sets for memory optimization: it's cheaper to hold FQN than PsiClass
    final Set<String> processedFqns =
        new THashSet<String>(); // FQN of processed classes if the class has one

    final Processor<DotNetTypeDeclaration> processor =
        new Processor<DotNetTypeDeclaration>() {
          @Override
          public boolean process(final DotNetTypeDeclaration candidate) {
            ProgressIndicatorProvider.checkCanceled();

            final Ref<Boolean> result = new Ref<Boolean>();
            final Ref<String> vmQNameRef = new Ref<String>();
            ApplicationManager.getApplication()
                .runReadAction(
                    new Runnable() {
                      @Override
                      public void run() {
                        vmQNameRef.set(candidate.getVmQName());
                        if (parameters.isCheckInheritance() || parameters.isCheckDeep()) {
                          if (!candidate.isInheritor(currentBase.get(), false)) {
                            result.set(true);
                            return;
                          }
                        }

                        if (PsiSearchScopeUtil.isInScope(searchScope, candidate)) {
                          final String name = candidate.getName();
                          if (name != null
                              && parameters.getNameCondition().value(name)
                              && !consumer.process(parameters.myTransformer.fun(candidate))) {
                            result.set(false);
                          }
                        }
                      }
                    });
            if (!result.isNull()) {
              return result.get();
            }

            if (parameters.isCheckDeep() && !isSealed(candidate)) {
              stack.push(vmQNameRef.get());
            }

            return true;
          }
        };
    stack.push(baseVmQName);

    final GlobalSearchScope projectScope = GlobalSearchScope.allScope(parameters.getProject());
    while (!stack.isEmpty()) {
      ProgressIndicatorProvider.checkCanceled();

      String vmQName = stack.pop();

      if (!processedFqns.add(vmQName)) {
        continue;
      }

      currentBase.set(vmQName);
      if (!DirectTypeInheritorsSearch.search(parameters.getProject(), vmQName, projectScope, false)
          .forEach(processor)) {
        return false;
      }
    }
    return true;
  }
Пример #13
0
  @Override
  public PsiDirectory findDirectory(@NotNull VirtualFile file) {
    ProgressIndicatorProvider.checkCanceled();

    return myFileManager.findDirectory(file);
  }
 public static ResolveCache getInstance(Project project) {
   ProgressIndicatorProvider
       .checkCanceled(); // We hope this method is being called often enough to cancel daemon
                         // processes smoothly
   return ServiceManager.getService(project, ResolveCache.class);
 }
Пример #15
0
 @Override
 public void cancel() {
   myCanceled = true;
   ProgressIndicatorProvider.canceled();
 }
Пример #16
0
  @NotNull
  /*package*/ OverloadResolutionResultsImpl<FunctionDescriptor> resolveFunctionCall(
      @NotNull BasicCallResolutionContext context) {

    ProgressIndicatorProvider.checkCanceled();

    List<ResolutionTask<CallableDescriptor, FunctionDescriptor>> prioritizedTasks;

    JetExpression calleeExpression = context.call.getCalleeExpression();
    JetReferenceExpression functionReference;
    if (calleeExpression instanceof JetSimpleNameExpression) {
      JetSimpleNameExpression expression = (JetSimpleNameExpression) calleeExpression;
      functionReference = expression;

      ExpressionTypingUtils.checkCapturingInClosure(expression, context.trace, context.scope);

      Name name = expression.getReferencedNameAsName();

      prioritizedTasks =
          TaskPrioritizer.<CallableDescriptor, FunctionDescriptor>computePrioritizedTasks(
              context,
              name,
              functionReference,
              CallableDescriptorCollectors.FUNCTIONS_AND_VARIABLES);
      ResolutionTask.DescriptorCheckStrategy abstractConstructorCheck =
          new ResolutionTask.DescriptorCheckStrategy() {
            @Override
            public <D extends CallableDescriptor> boolean performAdvancedChecks(
                D descriptor, BindingTrace trace, TracingStrategy tracing) {
              if (descriptor instanceof ConstructorDescriptor) {
                Modality modality =
                    ((ConstructorDescriptor) descriptor).getContainingDeclaration().getModality();
                if (modality == Modality.ABSTRACT) {
                  tracing.instantiationOfAbstractClass(trace);
                  return false;
                }
              }
              return true;
            }
          };
      for (ResolutionTask task : prioritizedTasks) {
        task.setCheckingStrategy(abstractConstructorCheck);
      }
    } else {
      JetValueArgumentList valueArgumentList = context.call.getValueArgumentList();
      PsiElement reportAbsenceOn =
          valueArgumentList == null ? context.call.getCallElement() : valueArgumentList;
      if (calleeExpression instanceof JetConstructorCalleeExpression) {
        assert !context.call.getExplicitReceiver().exists();

        JetConstructorCalleeExpression expression =
            (JetConstructorCalleeExpression) calleeExpression;
        functionReference = expression.getConstructorReferenceExpression();
        if (functionReference == null) {
          return checkArgumentTypesAndFail(context); // No type there
        }
        JetTypeReference typeReference = expression.getTypeReference();
        assert typeReference != null;
        JetType constructedType =
            typeResolver.resolveType(context.scope, typeReference, context.trace, true);

        if (constructedType.isError()) {
          return checkArgumentTypesAndFail(context);
        }

        DeclarationDescriptor declarationDescriptor =
            constructedType.getConstructor().getDeclarationDescriptor();
        if (declarationDescriptor instanceof ClassDescriptor) {
          ClassDescriptor classDescriptor = (ClassDescriptor) declarationDescriptor;
          Collection<ConstructorDescriptor> constructors = classDescriptor.getConstructors();
          if (constructors.isEmpty()) {
            context.trace.report(NO_CONSTRUCTOR.on(reportAbsenceOn));
            return checkArgumentTypesAndFail(context);
          }
          Collection<ResolutionCandidate<CallableDescriptor>> candidates =
              TaskPrioritizer.<CallableDescriptor>convertWithImpliedThis(
                  context.scope,
                  Collections.<ReceiverValue>singletonList(NO_RECEIVER),
                  constructors);
          prioritizedTasks =
              TaskPrioritizer
                  .<CallableDescriptor, FunctionDescriptor>computePrioritizedTasksFromCandidates(
                      context, functionReference, candidates, null);
        } else {
          context.trace.report(NOT_A_CLASS.on(calleeExpression));
          return checkArgumentTypesAndFail(context);
        }
      } else if (calleeExpression instanceof JetThisReferenceExpression) {
        functionReference = (JetThisReferenceExpression) calleeExpression;
        DeclarationDescriptor containingDeclaration = context.scope.getContainingDeclaration();
        if (containingDeclaration instanceof ConstructorDescriptor) {
          containingDeclaration = containingDeclaration.getContainingDeclaration();
        }
        assert containingDeclaration instanceof ClassDescriptor;
        ClassDescriptor classDescriptor = (ClassDescriptor) containingDeclaration;

        Collection<ConstructorDescriptor> constructors = classDescriptor.getConstructors();
        if (constructors.isEmpty()) {
          context.trace.report(NO_CONSTRUCTOR.on(reportAbsenceOn));
          return checkArgumentTypesAndFail(context);
        }
        List<ResolutionCandidate<CallableDescriptor>> candidates =
            ResolutionCandidate.<CallableDescriptor>convertCollection(
                constructors, JetPsiUtil.isSafeCall(context.call));
        prioritizedTasks =
            Collections.singletonList(
                new ResolutionTask<CallableDescriptor, FunctionDescriptor>(
                    candidates, functionReference, context)); // !! DataFlowInfo.EMPTY
      } else if (calleeExpression != null) {
        // Here we handle the case where the callee expression must be something of type function,
        // e.g. (foo.bar())(1, 2)
        JetType calleeType =
            expressionTypingServices.safeGetType(
                context.scope,
                calleeExpression,
                NO_EXPECTED_TYPE,
                context.dataFlowInfo,
                context
                    .trace); // We are actually expecting a function, but there seems to be no easy
                             // way of expressing this

        if (!KotlinBuiltIns.getInstance().isFunctionOrExtensionFunctionType(calleeType)) {
          //                    checkTypesWithNoCallee(trace, scope, call);
          if (!calleeType.isError()) {
            context.trace.report(CALLEE_NOT_A_FUNCTION.on(calleeExpression, calleeType));
          }
          return checkArgumentTypesAndFail(context);
        }

        FunctionDescriptorImpl functionDescriptor =
            new ExpressionAsFunctionDescriptor(
                context.scope.getContainingDeclaration(),
                Name.special("<for expression " + calleeExpression.getText() + ">"),
                calleeExpression);
        FunctionDescriptorUtil.initializeFromFunctionType(
            functionDescriptor,
            calleeType,
            NO_RECEIVER_PARAMETER,
            Modality.FINAL,
            Visibilities.LOCAL);
        ResolutionCandidate<CallableDescriptor> resolutionCandidate =
            ResolutionCandidate.<CallableDescriptor>create(
                functionDescriptor, JetPsiUtil.isSafeCall(context.call));
        resolutionCandidate.setReceiverArgument(context.call.getExplicitReceiver());
        resolutionCandidate.setExplicitReceiverKind(ExplicitReceiverKind.RECEIVER_ARGUMENT);

        // strictly speaking, this is a hack:
        // we need to pass a reference, but there's no reference in the PSI,
        // so we wrap what we have into a fake reference and pass it on (unwrap on the other end)
        functionReference = new JetFakeReference(calleeExpression);

        prioritizedTasks =
            Collections.singletonList(
                new ResolutionTask<CallableDescriptor, FunctionDescriptor>(
                    Collections.singleton(resolutionCandidate), functionReference, context));
      } else {
        //                checkTypesWithNoCallee(trace, scope, call);
        return checkArgumentTypesAndFail(context);
      }
    }

    return doResolveCallOrGetCachedResults(
        ResolutionResultsCache.FUNCTION_MEMBER_TYPE,
        context,
        prioritizedTasks,
        CallTransformer.FUNCTION_CALL_TRANSFORMER,
        functionReference);
  }
 @NotNull
 public static NonCancelableSection startNonCancelableSectionIfSupported() {
   return ourInstance != null
       ? ourInstance.startNonCancelableSection()
       : NonCancelableSection.EMPTY;
 }
 @Nullable
 public static ProgressIndicator getGlobalProgressIndicator() {
   return ourInstance != null ? ourInstance.getProgressIndicator() : null;
 }
  private static boolean processCachedMembersByName(
      @NotNull PsiClass aClass,
      @NotNull PsiScopeProcessor processor,
      @NotNull ResolveState state,
      @Nullable Set<PsiClass> visited,
      PsiElement last,
      @NotNull PsiElement place,
      boolean isRaw,
      @NotNull PsiSubstitutor substitutor,
      @NotNull MembersMap value,
      String name,
      @NotNull LanguageLevel languageLevel) {
    final ElementClassHint classHint = processor.getHint(ElementClassHint.KEY);

    PsiElementFactory factory = JavaPsiFacade.getInstance(aClass.getProject()).getElementFactory();

    if (classHint == null || classHint.shouldProcess(ElementClassHint.DeclarationKind.FIELD)) {
      final PsiField fieldByName = aClass.findFieldByName(name, false);
      if (fieldByName != null) {
        processor.handleEvent(PsiScopeProcessor.Event.SET_DECLARATION_HOLDER, aClass);
        if (!processor.execute(fieldByName, state)) return false;
      } else {
        final Map<String, List<Pair<PsiMember, PsiSubstitutor>>> allFieldsMap =
            value.get(MemberType.FIELD);

        final List<Pair<PsiMember, PsiSubstitutor>> list = allFieldsMap.get(name);
        if (list != null) {
          for (final Pair<PsiMember, PsiSubstitutor> candidate : list) {
            PsiMember candidateField = candidate.getFirst();
            PsiSubstitutor finalSubstitutor =
                obtainFinalSubstitutor(
                    candidateField.getContainingClass(),
                    candidate.getSecond(),
                    aClass,
                    substitutor,
                    factory,
                    languageLevel);

            processor.handleEvent(
                PsiScopeProcessor.Event.SET_DECLARATION_HOLDER,
                candidateField.getContainingClass());
            if (!processor.execute(candidateField, state.put(PsiSubstitutor.KEY, finalSubstitutor)))
              return false;
          }
        }
      }
    }
    if (classHint == null || classHint.shouldProcess(ElementClassHint.DeclarationKind.CLASS)) {
      if (last != null && last.getParent() == aClass) {
        if (last instanceof PsiClass) {
          if (!processor.execute(last, state)) return false;
        }
        // Parameters
        final PsiTypeParameterList list = aClass.getTypeParameterList();
        if (list != null && !list.processDeclarations(processor, state, last, place)) return false;
      }
      if (!(last instanceof PsiReferenceList)) {
        final PsiClass classByName = aClass.findInnerClassByName(name, false);
        if (classByName != null) {
          processor.handleEvent(PsiScopeProcessor.Event.SET_DECLARATION_HOLDER, aClass);
          if (!processor.execute(classByName, state)) return false;
        } else {
          Map<String, List<Pair<PsiMember, PsiSubstitutor>>> allClassesMap =
              value.get(MemberType.CLASS);

          List<Pair<PsiMember, PsiSubstitutor>> list = allClassesMap.get(name);
          if (list != null) {
            for (final Pair<PsiMember, PsiSubstitutor> candidate : list) {
              PsiMember inner = candidate.getFirst();
              PsiClass containingClass = inner.getContainingClass();
              if (containingClass != null) {
                PsiSubstitutor finalSubstitutor =
                    obtainFinalSubstitutor(
                        containingClass,
                        candidate.getSecond(),
                        aClass,
                        substitutor,
                        factory,
                        languageLevel);
                processor.handleEvent(
                    PsiScopeProcessor.Event.SET_DECLARATION_HOLDER, containingClass);
                if (!processor.execute(inner, state.put(PsiSubstitutor.KEY, finalSubstitutor)))
                  return false;
              }
            }
          }
        }
      }
    }
    if (classHint == null || classHint.shouldProcess(ElementClassHint.DeclarationKind.METHOD)) {
      if (processor instanceof MethodResolverProcessor) {
        final MethodResolverProcessor methodResolverProcessor = (MethodResolverProcessor) processor;
        if (methodResolverProcessor.isConstructor()) {
          final PsiMethod[] constructors = aClass.getConstructors();
          methodResolverProcessor.handleEvent(
              PsiScopeProcessor.Event.SET_DECLARATION_HOLDER, aClass);
          for (PsiMethod constructor : constructors) {
            if (!methodResolverProcessor.execute(constructor, state)) return false;
          }
          return true;
        }
      }
      Map<String, List<Pair<PsiMember, PsiSubstitutor>>> allMethodsMap =
          value.get(MemberType.METHOD);
      List<Pair<PsiMember, PsiSubstitutor>> list = allMethodsMap.get(name);
      if (list != null) {
        for (final Pair<PsiMember, PsiSubstitutor> candidate : list) {
          ProgressIndicatorProvider.checkCanceled();
          PsiMethod candidateMethod = (PsiMethod) candidate.getFirst();
          if (processor instanceof MethodResolverProcessor) {
            if (candidateMethod.isConstructor()
                != ((MethodResolverProcessor) processor).isConstructor()) continue;
          }
          final PsiClass containingClass = candidateMethod.getContainingClass();
          if (visited != null && visited.contains(candidateMethod.getContainingClass())) {
            continue;
          }

          PsiSubstitutor finalSubstitutor =
              obtainFinalSubstitutor(
                  containingClass,
                  candidate.getSecond(),
                  aClass,
                  substitutor,
                  factory,
                  languageLevel);
          finalSubstitutor = checkRaw(isRaw, factory, candidateMethod, finalSubstitutor);
          processor.handleEvent(PsiScopeProcessor.Event.SET_DECLARATION_HOLDER, containingClass);
          if (!processor.execute(candidateMethod, state.put(PsiSubstitutor.KEY, finalSubstitutor)))
            return false;
        }

        if (visited != null) {
          for (Pair<PsiMember, PsiSubstitutor> aList : list) {
            visited.add(aList.getFirst().getContainingClass());
          }
        }
      }
    }
    return true;
  }
Пример #20
0
  private static <D extends CallableDescriptor, F extends D> void doComputeTasks(
      @NotNull JetScope scope,
      @NotNull ReceiverDescriptor receiver,
      @NotNull Name name,
      @NotNull ResolutionTaskHolder<D, F> result,
      @NotNull BasicResolutionContext context,
      @NotNull CallableDescriptorCollector<? extends D> callableDescriptorCollector) {

    ProgressIndicatorProvider.checkCanceled();

    AutoCastServiceImpl autoCastService =
        new AutoCastServiceImpl(context.dataFlowInfo, context.trace.getBindingContext());
    List<ReceiverDescriptor> implicitReceivers = Lists.newArrayList();
    scope.getImplicitReceiversHierarchy(implicitReceivers);
    boolean hasExplicitThisObject = context.call.getThisObject().exists();
    if (hasExplicitThisObject) {
      implicitReceivers.add(context.call.getThisObject());
    }
    if (receiver.exists()) {
      List<ReceiverDescriptor> variantsForExplicitReceiver =
          autoCastService.getVariantsForReceiver(receiver);

      Collection<ResolutionCandidate<D>> extensionFunctions =
          convertWithImpliedThis(
              scope,
              variantsForExplicitReceiver,
              callableDescriptorCollector.getNonMembersByName(scope, name));
      List<ResolutionCandidate<D>> nonlocals = Lists.newArrayList();
      List<ResolutionCandidate<D>> locals = Lists.newArrayList();
      //noinspection unchecked,RedundantTypeArguments
      TaskPrioritizer.<D>splitLexicallyLocalDescriptors(
          extensionFunctions, scope.getContainingDeclaration(), locals, nonlocals);

      Collection<ResolutionCandidate<D>> members = Lists.newArrayList();
      for (ReceiverDescriptor variant : variantsForExplicitReceiver) {
        Collection<? extends D> membersForThisVariant =
            callableDescriptorCollector.getMembersByName(variant.getType(), name);
        convertWithReceivers(
            membersForThisVariant,
            Collections.singletonList(variant),
            Collections.singletonList(NO_RECEIVER),
            members,
            hasExplicitThisObject);
      }

      result.addLocalExtensions(locals);
      result.addMembers(members);

      for (ReceiverDescriptor implicitReceiver : implicitReceivers) {
        Collection<? extends D> memberExtensions =
            callableDescriptorCollector.getNonMembersByName(
                implicitReceiver.getType().getMemberScope(), name);
        List<ReceiverDescriptor> variantsForImplicitReceiver =
            autoCastService.getVariantsForReceiver(implicitReceiver);
        result.addNonLocalExtensions(
            convertWithReceivers(
                memberExtensions,
                variantsForImplicitReceiver,
                variantsForExplicitReceiver,
                hasExplicitThisObject));
      }

      result.addNonLocalExtensions(nonlocals);
    } else {
      Collection<ResolutionCandidate<D>> functions =
          convertWithImpliedThis(
              scope,
              Collections.singletonList(receiver),
              callableDescriptorCollector.getNonExtensionsByName(scope, name));

      List<ResolutionCandidate<D>> nonlocals = Lists.newArrayList();
      List<ResolutionCandidate<D>> locals = Lists.newArrayList();
      //noinspection unchecked,RedundantTypeArguments
      TaskPrioritizer.<D>splitLexicallyLocalDescriptors(
          functions, scope.getContainingDeclaration(), locals, nonlocals);

      result.addLocalExtensions(locals);
      result.addNonLocalExtensions(nonlocals);

      for (ReceiverDescriptor implicitReceiver : implicitReceivers) {
        doComputeTasks(scope, implicitReceiver, name, result, context, callableDescriptorCollector);
      }
    }
  }
 public T getStub() {
   ProgressIndicatorProvider.checkCanceled(); // Hope, this is called often
   return myStub;
 }