Java Code Examples for com.intellij.openapi.util.RecursionManager#doPreventingRecursion()

The following examples show how to use com.intellij.openapi.util.RecursionManager#doPreventingRecursion() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: CSharpTypeResolveContext.java    From consulo-csharp with Apache License 2.0 6 votes vote down vote up
@RequiredReadAction
@Nonnull
@Override
protected List<DotNetTypeRef> getExtendTypeRefs()
{
	DotNetTypeRef[] typeRefs = myElement.getExtendTypeRefs();
	List<DotNetTypeRef> extendTypeRefs = new ArrayList<>(typeRefs.length);

	for(DotNetTypeRef typeRef : typeRefs)
	{
		DotNetTypeRef ref = RecursionManager.doPreventingRecursion(this, false, () -> GenericUnwrapTool.exchangeTypeRef(typeRef, myExtractor, myElement));
		if(ref == null)
		{
			continue;
		}
		extendTypeRefs.add(ref);
	}
	return extendTypeRefs;
}
 
Example 2
Source File: StubBasedPsiElementBase.java    From consulo with Apache License 2.0 6 votes vote down vote up
private ASTNode failedToBindStubToAst(@Nonnull PsiFileImpl file, @Nonnull final FileElement fileElement) {
  VirtualFile vFile = file.getVirtualFile();
  StubTree stubTree = file.getStubTree();
  final String stubString = stubTree != null ? ((PsiFileStubImpl)stubTree.getRoot()).printTree() : null;
  final String astString = RecursionManager.doPreventingRecursion("failedToBindStubToAst", true, () -> DebugUtil.treeToString(fileElement, true));

  @NonNls final String message =
          "Failed to bind stub to AST for element " + getClass() + " in " + (vFile == null ? "<unknown file>" : vFile.getPath()) + "\nFile:\n" + file + "@" + System.identityHashCode(file);

  final String creationTraces = ourTraceStubAstBinding ? dumpCreationTraces(fileElement) : null;

  List<Attachment> attachments = new ArrayList<>();
  if (stubString != null) {
    attachments.add(new Attachment("stubTree.txt", stubString));
  }
  if (astString != null) {
    attachments.add(new Attachment("ast.txt", astString));
  }
  if (creationTraces != null) {
    attachments.add(new Attachment("creationTraces.txt", creationTraces));
  }

  throw new RuntimeExceptionWithAttachments(message, attachments.toArray(Attachment.EMPTY_ARRAY));
}
 
Example 3
Source File: FileElement.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nonnull
public final AstSpine getStubbedSpine() {
  AstSpine result = myStubbedSpine;
  if (result == null) {
    PsiFileImpl file = (PsiFileImpl)getPsi();
    IStubFileElementType type = file.getElementTypeForStubBuilder();
    if (type == null) return AstSpine.EMPTY_SPINE;

    result = RecursionManager.doPreventingRecursion(file, false, () -> new AstSpine(calcStubbedDescendants(type.getBuilder())));
    if (result == null) {
      throw new StackOverflowPreventedException("Endless recursion prevented");
    }
    myStubbedSpine = result;
  }
  return result;
}
 
Example 4
Source File: CSharpLambdaExpressionImpl.java    From consulo-csharp with Apache License 2.0 5 votes vote down vote up
@Nonnull
@RequiredReadAction
public DotNetTypeRef toTypeRefForInference()
{
	// recursion when child lambda reference to parameter from parent lambda
	DotNetTypeRef returnType = RecursionManager.doPreventingRecursion("C# lambda return type", false, this::findPossibleReturnTypeRef);
	if(returnType == null)
	{
		returnType = DotNetTypeRef.ERROR_TYPE;
	}
	return new CSharpLambdaTypeRef(this, null, getParameterInfos(true), returnType);
}
 
Example 5
Source File: ResolveCache.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nullable
private <TRef extends PsiReference, TResult> TResult resolve(@Nonnull final TRef ref,
                                                             @Nonnull final AbstractResolver<? super TRef, TResult> resolver,
                                                             boolean needToPreventRecursion,
                                                             final boolean incompleteCode,
                                                             boolean isPoly,
                                                             boolean isPhysical) {
  ProgressIndicatorProvider.checkCanceled();
  if (isPhysical) {
    ApplicationManager.getApplication().assertReadAccessAllowed();
  }
  int index = getIndex(incompleteCode, isPoly);
  Map<TRef, TResult> map = getMap(isPhysical, index);
  TResult result = map.get(ref);
  if (result != null) {
    return result;
  }

  RecursionGuard.StackStamp stamp = RecursionManager.markStack();
  result = needToPreventRecursion
           ? RecursionManager.doPreventingRecursion(Trinity.create(ref, incompleteCode, isPoly), true, () -> resolver.resolve(ref, incompleteCode))
           : resolver.resolve(ref, incompleteCode);
  if (result instanceof ResolveResult) {
    ensureValidPsi((ResolveResult)result);
  }
  else if (result instanceof ResolveResult[]) {
    ensureValidResults((ResolveResult[])result);
  }
  else if (result instanceof PsiElement) {
    PsiUtilCore.ensureValid((PsiElement)result);
  }

  if (stamp.mayCacheNow()) {
    cache(ref, map, result);
  }
  return result;
}
 
Example 6
Source File: ResolveCache.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
public <T extends PsiPolyVariantReference> ResolveResult[] resolveWithCaching(@Nonnull final T ref,
                                                                              @Nonnull final PolyVariantContextResolver<T> resolver,
                                                                              boolean needToPreventRecursion,
                                                                              final boolean incompleteCode,
                                                                              @Nonnull final PsiFile containingFile) {
  ProgressIndicatorProvider.checkCanceled();
  ApplicationManager.getApplication().assertReadAccessAllowed();

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

  RecursionGuard.StackStamp stamp = RecursionManager.markStack();
  result = needToPreventRecursion
           ? RecursionManager.doPreventingRecursion(Pair.create(ref, incompleteCode), true, () -> resolver.resolve(ref, containingFile, incompleteCode))
           : resolver.resolve(ref, containingFile, incompleteCode);
  if (result != null) {
    ensureValidResults(result);
  }

  if (stamp.mayCacheNow()) {
    cache(ref, map, result);
  }
  return result == null ? ResolveResult.EMPTY_ARRAY : result;
}
 
Example 7
Source File: StaticVsInstanceComparator.java    From consulo-csharp with Apache License 2.0 4 votes vote down vote up
@RequiredReadAction
private int getWeightByContext(ResolveResult resolveResult)
{
	final PsiElement element = resolveResult.getElement();
	if(element == null)
	{
		return -100;
	}

	// type alias have max priority
	if(element instanceof CSharpTypeDefStatement)
	{
		return Integer.MAX_VALUE;
	}

	if(myParent != null)
	{
		CSharpContextUtil.ContextType parentContext = CSharpContextUtil.ContextType.ANY;
		if(element instanceof CSharpTypeDeclaration)
		{
			parentContext = CSharpContextUtil.ContextType.STATIC;
		}
		else if(element instanceof DotNetVariable)
		{
			parentContext = CSharpContextUtil.ContextType.INSTANCE;
		}

		DotNetTypeDeclaration forceTarget = resolveTargetElement(element, myParent);
		if(forceTarget == null)
		{
			return parentContext == CSharpContextUtil.ContextType.INSTANCE ? 10 : 5;
		}

		ResolveResult[] resolveResults = RecursionManager.doPreventingRecursion(myParent, false, () -> myParent.tryResolveFromQualifier(forceTarget));
		if(resolveResults == null || resolveResults.length == 0)
		{
			return parentContext == CSharpContextUtil.ContextType.INSTANCE ? 10 : 5;
		}

		for(ResolveResult result : resolveResults)
		{
			PsiElement element1 = result.getElement();
			if(element1 == null)
			{
				continue;
			}

			CSharpContextUtil.ContextType contextForResolved = CSharpContextUtil.getContextForResolved(element1);

			if(parentContext != CSharpContextUtil.ContextType.ANY)
			{
				switch(parentContext)
				{
					case INSTANCE:
						if(contextForResolved.isAllowInstance())
						{
							return 5000;
						}
						break;
					case STATIC:
						if(contextForResolved == CSharpContextUtil.ContextType.STATIC)
						{
							return 5000;
						}
						break;
				}
			}
		}
	}
	else
	{
		// if expression is single - types and namespaces are in the end of queue
		if(element instanceof CSharpTypeDeclaration || element instanceof DotNetNamespaceAsElement)
		{
			return -1;
		}
	}
	return 0;
}
 
Example 8
Source File: GenericInferenceUtil.java    From consulo-csharp with Apache License 2.0 4 votes vote down vote up
@Nonnull
@RequiredReadAction
public static GenericInferenceResult inferenceGenericExtractor(@Nonnull CSharpCallArgument[] callArguments,
		@Nonnull DotNetTypeRef[] typeArgumentListRefs,
		@Nonnull PsiElement scope,
		@Nonnull DotNetLikeMethodDeclaration methodDeclaration)
{
	DotNetGenericParameter[] genericParameters = methodDeclaration.getGenericParameters();
	if(genericParameters.length == 0 || typeArgumentListRefs.length > 0)
	{
		DotNetGenericExtractor extractor = genericParameters.length != typeArgumentListRefs.length ? DotNetGenericExtractor.EMPTY : CSharpGenericExtractor.create(genericParameters,
				typeArgumentListRefs);
		return new GenericInferenceResult(genericParameters.length == typeArgumentListRefs.length, extractor);
	}

	List<NCallArgument> methodCallArguments = RecursionManager.doPreventingRecursion(methodDeclaration, false, () -> NCallArgumentBuilder.buildCallArguments(callArguments, methodDeclaration, scope));

	if(ContainerUtil.isEmpty(methodCallArguments))
	{
		return new GenericInferenceResult(true, DotNetGenericExtractor.EMPTY);
	}

	final Map<DotNetGenericParameter, DotNetTypeRef> map = new THashMap<>();

	for(NCallArgument nCallArgument : methodCallArguments)
	{
		ProgressManager.checkCanceled();

		DotNetTypeRef parameterTypeRef = nCallArgument.getParameterTypeRef();
		if(parameterTypeRef == null)
		{
			continue;
		}

		DotNetTypeRef expressionTypeRef = unwrapPossibleGenericTypeRefs(nCallArgument, parameterTypeRef, map, scope);
		if(expressionTypeRef instanceof CSharpFastImplicitTypeRef)
		{
			DotNetTypeRef mirror = ((CSharpFastImplicitTypeRef) expressionTypeRef).doMirror(parameterTypeRef, scope);
			if(mirror != null)
			{
				expressionTypeRef = mirror;
			}
		}

		DotNetTypeResolveResult parameterTypeResolveResult = parameterTypeRef.resolve();
		DotNetTypeResolveResult expressionTypeResolveResult = expressionTypeRef.resolve();

		if(parameterTypeResolveResult instanceof CSharpLambdaResolveResult && expressionTypeResolveResult instanceof CSharpLambdaResolveResult)
		{
			CSharpLambdaResolveResult pLambdaResolveResult = (CSharpLambdaResolveResult) parameterTypeResolveResult;
			CSharpLambdaResolveResult eLambdaResolveResult = (CSharpLambdaResolveResult) expressionTypeResolveResult;

			DotNetTypeRef[] pParameterTypeRefs = pLambdaResolveResult.getParameterTypeRefs();
			DotNetTypeRef[] eParameterTypeRefs = eLambdaResolveResult.getParameterTypeRefs();

			if(pParameterTypeRefs.length == eParameterTypeRefs.length)
			{
				for(int i = 0; i < eParameterTypeRefs.length; i++)
				{
					DotNetTypeRef pParameterTypeRef = pParameterTypeRefs[i];
					DotNetTypeRef eParameterTypeRef = eParameterTypeRefs[i];

					inferenceGenericFromExpressionTypeRefAndParameterTypeRef(genericParameters, map, pParameterTypeRef, eParameterTypeRef, scope);
				}
			}

			inferenceGenericFromExpressionTypeRefAndParameterTypeRef(genericParameters, map, pLambdaResolveResult.getReturnTypeRef(), eLambdaResolveResult.getReturnTypeRef(), scope);
		}

		if(parameterTypeResolveResult instanceof CSharpArrayTypeRef.ArrayResolveResult && expressionTypeResolveResult instanceof CSharpArrayTypeRef.ArrayResolveResult)
		{
			DotNetTypeRef pTypeRef = ((CSharpArrayTypeRef.ArrayResolveResult) parameterTypeResolveResult).getInnerTypeRef();
			DotNetTypeRef eTypeRef = ((CSharpArrayTypeRef.ArrayResolveResult) expressionTypeResolveResult).getInnerTypeRef();
			inferenceGenericFromExpressionTypeRefAndParameterTypeRef(genericParameters, map, pTypeRef, eTypeRef, scope);
		}

		inferenceGenericFromExpressionTypeRefAndParameterTypeRef(genericParameters, map, parameterTypeRef, expressionTypeRef, scope);
	}

	return new GenericInferenceResult(genericParameters.length == map.size(), CSharpGenericExtractor.create(map));
}
 
Example 9
Source File: ValProcessor.java    From lombok-intellij-plugin with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
private PsiType processLocalVariableInitializer(final PsiExpression psiExpression) {
  PsiType result = null;
  if (null != psiExpression && !(psiExpression instanceof PsiArrayInitializerExpression)) {

    if (psiExpression instanceof PsiConditionalExpression) {
      result = RecursionManager.doPreventingRecursion(psiExpression, true, new Computable<PsiType>() {
        @Override
        public PsiType compute() {
          final PsiExpression thenExpression = ((PsiConditionalExpression) psiExpression).getThenExpression();
          final PsiExpression elseExpression = ((PsiConditionalExpression) psiExpression).getElseExpression();

          final PsiType thenType = null != thenExpression ? thenExpression.getType() : null;
          final PsiType elseType = null != elseExpression ? elseExpression.getType() : null;

          if (thenType == null) {
            return elseType;
          }
          if (elseType == null) {
            return thenType;
          }

          if (TypeConversionUtil.isAssignable(thenType, elseType, false)) {
            return thenType;
          }
          if (TypeConversionUtil.isAssignable(elseType, thenType, false)) {
            return elseType;
          }
          return thenType;
        }
      });
    } else {
      result = RecursionManager.doPreventingRecursion(psiExpression, true, new Computable<PsiType>() {
        @Override
        public PsiType compute() {
          return psiExpression.getType();
        }
      });
    }
  }

  return result;
}
 
Example 10
Source File: StubTreeLoaderImpl.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Override
@Nullable
public ObjectStubTree readOrBuild(Project project, final VirtualFile vFile, @Nullable PsiFile psiFile) {
  final ObjectStubTree fromIndices = readFromVFile(project, vFile);
  if (fromIndices != null) {
    return fromIndices;
  }

  try {
    byte[] content = vFile.contentsToByteArray();
    vFile.setPreloadedContentHint(content);
    try {
      final FileContent fc = new FileContentImpl(vFile, content);
      fc.putUserData(IndexingDataKeys.PROJECT, project);
      if (psiFile != null && !vFile.getFileType().isBinary()) {
        fc.putUserData(IndexingDataKeys.FILE_TEXT_CONTENT_KEY, psiFile.getViewProvider().getContents());
        // but don't reuse psiFile itself to avoid loading its contents. If we load AST, the stub will be thrown out anyway.
      }

      Stub element = RecursionManager.doPreventingRecursion(vFile, false, () -> StubTreeBuilder.buildStubTree(fc));
      ObjectStubTree tree = element instanceof PsiFileStub ? new StubTree((PsiFileStub)element) : element instanceof ObjectStubBase ? new ObjectStubTree((ObjectStubBase)element, true) : null;
      if (tree != null) {
        tree.setDebugInfo("created from file content");
        return tree;
      }
    }
    finally {
      vFile.setPreloadedContentHint(null);
    }
  }
  catch (IOException e) {
    if (LOG.isDebugEnabled()) {
      LOG.debug(e);
    }
    else {
      // content can be not cached yet, and the file can be deleted on disk already, without refresh
      LOG.info("Can't load file content for stub building: " + e.getMessage());
    }
  }

  return null;
}