Java Code Examples for com.intellij.psi.util.PsiTreeUtil#getContextOfType()

The following examples show how to use com.intellij.psi.util.PsiTreeUtil#getContextOfType() . 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: CSharpVisibilityUtil.java    From consulo-csharp with Apache License 2.0 6 votes vote down vote up
@Nonnull
@RequiredReadAction
private static List<DotNetTypeDeclaration> collectAllTypes(@Nonnull PsiElement place)
{
	List<DotNetTypeDeclaration> typeDeclarations = new SmartList<>();
	if(place instanceof CSharpTypeDeclaration)
	{
		typeDeclarations.add((DotNetTypeDeclaration) place);
	}
	PsiElement type = place;
	while((type = PsiTreeUtil.getContextOfType(type, DotNetTypeDeclaration.class)) != null)
	{
		typeDeclarations.add((DotNetTypeDeclaration) type);
	}
	return typeDeclarations;
}
 
Example 2
Source File: ThisKindProcessor.java    From consulo-csharp with Apache License 2.0 6 votes vote down vote up
@RequiredReadAction
@Override
public void process(@Nonnull CSharpResolveOptions options,
		@Nonnull DotNetGenericExtractor defaultExtractor,
		@Nullable PsiElement forceQualifierElement,
		@Nonnull Processor<ResolveResult> processor)
{
	DotNetTypeDeclaration thisTypeDeclaration = PsiTreeUtil.getContextOfType(options.getElement(), DotNetTypeDeclaration.class);
	if(thisTypeDeclaration != null)
	{
		thisTypeDeclaration = CSharpCompositeTypeDeclaration.selectCompositeOrSelfType(thisTypeDeclaration);

		DotNetGenericExtractor genericExtractor = DotNetGenericExtractor.EMPTY;
		int genericParametersCount = thisTypeDeclaration.getGenericParametersCount();
		if(genericParametersCount > 0)
		{
			Map<DotNetGenericParameter, DotNetTypeRef> map = new THashMap<>(genericParametersCount);
			for(DotNetGenericParameter genericParameter : thisTypeDeclaration.getGenericParameters())
			{
				map.put(genericParameter, new CSharpTypeRefFromGenericParameter(genericParameter));
			}
			genericExtractor = CSharpGenericExtractor.create(map);
		}
		processor.process(new CSharpResolveResultWithExtractor(thisTypeDeclaration, genericExtractor));
	}
}
 
Example 3
Source File: XQueryDocElement.java    From intellij-xquery with Apache License 2.0 6 votes vote down vote up
@Nullable
public PsiFile getContainingFile() {
    if (!isValid()) {
        return null;
    }

    PsiFile file = originalElement.getContainingFile();
    final PsiElement context = originalElement.getContext();
    if (file == null && context != null) {
        file = context.getContainingFile();
    }
    PsiFile f;
    if ((f = PsiTreeUtil.getContextOfType(file, PsiFile.class, true)) instanceof XQueryFile) {
        return f;
    }
    return file;
}
 
Example 4
Source File: CSharpCompletionSorting.java    From consulo-csharp with Apache License 2.0 5 votes vote down vote up
@Nullable
@RequiredReadAction
private static LookupElementWeigher recursiveSorter(CompletionParameters completionParameters, CompletionResultSet result)
{
	PsiElement position = completionParameters.getPosition();


	Set<PsiElement> elements = new THashSet<>();

	PsiElement argumentListOwner = PsiTreeUtil.getContextOfType(position, CSharpCallArgumentListOwner.class, DotNetVariable.class);
	if(argumentListOwner instanceof CSharpMethodCallExpressionImpl)
	{
		ContainerUtil.addIfNotNull(elements, ((CSharpMethodCallExpressionImpl) argumentListOwner).resolveToCallable());
	}
	else if(argumentListOwner instanceof DotNetVariable)
	{
		elements.add(argumentListOwner);
	}

	List<CSharpForeachStatementImpl> foreachStatements = SyntaxTraverser.psiApi().parents(position).filter(CSharpForeachStatementImpl.class).addAllTo(new ArrayList<>());
	for(CSharpForeachStatementImpl foreachStatement : foreachStatements)
	{
		DotNetExpression iterableExpression = foreachStatement.getIterableExpression();
		if(iterableExpression instanceof CSharpReferenceExpression)
		{
			ContainerUtil.addIfNotNull(elements, ((CSharpReferenceExpression) iterableExpression).resolve());
		}
	}

	if(!elements.isEmpty())
	{
		return new CSharpRecursiveGuardWeigher(elements);
	}
	return null;
}
 
Example 5
Source File: CS0026.java    From consulo-csharp with Apache License 2.0 5 votes vote down vote up
@RequiredReadAction
@Nullable
@Override
public HighlightInfoFactory checkImpl(@Nonnull CSharpLanguageVersion languageVersion, @Nonnull CSharpHighlightContext highlightContext, @Nonnull CSharpReferenceExpression element)
{
	if(element.kind() == CSharpReferenceExpression.ResolveToKind.THIS)
	{
		DotNetModifierListOwner modifierListOwner = (DotNetModifierListOwner) PsiTreeUtil.getContextOfType(element, DotNetQualifiedElement.class);
		if(modifierListOwner == null || modifierListOwner.hasModifier(DotNetModifier.STATIC))
		{
			return newBuilder(element, "this");
		}
	}
	return null;
}
 
Example 6
Source File: RenameClassActionTest.java    From lombok-intellij-plugin with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
protected void doTest(String newName) throws Exception {
  myFixture.configureByFile(getBasePath() + "/before" + getTestName(false) + ".java");

  PsiElement psiElement = myFixture.getFile().findElementAt(myFixture.getEditor().getCaretModel().getOffset());
  PsiElement psiClass = PsiTreeUtil.getContextOfType(psiElement, PsiClass.class, true);
  myFixture.renameElement(psiClass, newName);

  checkResultByFile(getBasePath() + "/after" + getTestName(false) + ".java");
}
 
Example 7
Source File: GrammarElementRef.java    From intellij-plugin-v4 with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/** Called upon jump to def for this rule ref */
@Nullable
@Override
public PsiElement resolve() {
	PsiFile tokenVocabFile = TokenVocabResolver.resolveTokenVocabFile(getElement());

	if (tokenVocabFile != null) {
		return tokenVocabFile;
	}

	PsiFile importedFile = ImportResolver.resolveImportedFile(getElement());
	if ( importedFile!=null ) {
		return importedFile;
	}

	GrammarSpecNode grammar = PsiTreeUtil.getContextOfType(getElement(), GrammarSpecNode.class);
	PsiElement specNode = MyPsiUtils.findSpecNode(grammar, ruleName);

	if (specNode != null) {
		return specNode;
	}

	// Look for a rule defined in an imported grammar
	specNode = ImportResolver.resolveInImportedFiles(getElement().getContainingFile(), ruleName);

	if (specNode != null) {
		return specNode;
	}

	// Look for a lexer rule in the tokenVocab file if it exists
	if (getElement() instanceof LexerRuleRefNode) {
		return TokenVocabResolver.resolveInTokenVocab(getElement(), ruleName);
	}

	return null;
}
 
Example 8
Source File: JSGraphQLEndpointDocCompletionContributor.java    From js-graphql-intellij-plugin with MIT License 4 votes vote down vote up
public JSGraphQLEndpointDocCompletionContributor() {

		CompletionProvider<CompletionParameters> provider = new CompletionProvider<CompletionParameters>() {
			@SuppressWarnings("unchecked")
			@Override
			protected void addCompletions(@NotNull final CompletionParameters parameters, ProcessingContext context, @NotNull CompletionResultSet result) {

				final PsiFile file = parameters.getOriginalFile();

				if (!(file instanceof JSGraphQLEndpointDocFile)) {
					return;
				}

				final PsiElement completionElement = Optional.ofNullable(parameters.getOriginalPosition()).orElse(parameters.getPosition());
				if (completionElement != null) {
					final PsiComment comment = PsiTreeUtil.getContextOfType(completionElement, PsiComment.class);
					if (comment != null && JSGraphQLEndpointDocPsiUtil.isDocumentationComment(comment)) {

						if (completionElement.getNode().getElementType() == JSGraphQLEndpointDocTokenTypes.DOCVALUE) {
							final JSGraphQLEndpointFieldDefinition fieldDefinition = PsiTreeUtil.getNextSiblingOfType(comment, JSGraphQLEndpointFieldDefinition.class);
							if (fieldDefinition != null && fieldDefinition.getArgumentsDefinition() != null) {
								final List<String> otherDocTagValues = JSGraphQLEndpointDocPsiUtil.getOtherDocTagValues(comment);
								for (JSGraphQLEndpointInputValueDefinition arg : PsiTreeUtil.findChildrenOfType(fieldDefinition.getArgumentsDefinition(), JSGraphQLEndpointInputValueDefinition.class)) {
									final String argName = arg.getInputValueDefinitionIdentifier().getText();
									if (!otherDocTagValues.contains(argName)) {
										result.addElement(LookupElementBuilder.create(argName).withInsertHandler(AddSpaceInsertHandler.INSTANCE));
									}
								}
							}
							return;
						}

						final JSGraphQLEndpointDocTag tagBefore = PsiTreeUtil.getPrevSiblingOfType(completionElement, JSGraphQLEndpointDocTag.class);
						final JSGraphQLEndpointDocTag tagParent = PsiTreeUtil.getParentOfType(completionElement, JSGraphQLEndpointDocTag.class);
						if (tagBefore == null || tagParent != null) {
							String completion = "param";
							final boolean includeAt = completionElement.getNode().getElementType() != JSGraphQLEndpointDocTokenTypes.DOCNAME;
							if (includeAt) {
								completion = "@" + completion;
							}
							result.addElement(LookupElementBuilder.create(completion).withInsertHandler(AddSpaceInsertHandler.INSTANCE_WITH_AUTO_POPUP));
						}
					}
				}
			}
		};

		extend(CompletionType.BASIC, PlatformPatterns.psiElement(), provider);

	}
 
Example 9
Source File: JSGraphQLEndpointDocHighlightAnnotator.java    From js-graphql-intellij-plugin with MIT License 4 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public void annotate(@NotNull PsiElement element, @NotNull AnnotationHolder holder) {

	final IElementType elementType = element.getNode().getElementType();

       // highlight TO-DO items
       if(elementType == JSGraphQLEndpointDocTokenTypes.DOCTEXT) {
		final String elementText = element.getText().toLowerCase();
		if(isTodoToken(elementText)) {
			setTextAttributes(element, holder, CodeInsightColors.TODO_DEFAULT_ATTRIBUTES);
               holder.getCurrentAnnotationSession().putUserData(TODO_ELEMENT, element);
			return;
		} else {
               PsiElement prevSibling = element.getPrevSibling();
               while (prevSibling != null) {
                   if(prevSibling == holder.getCurrentAnnotationSession().getUserData(TODO_ELEMENT)) {
                       setTextAttributes(element, holder, CodeInsightColors.TODO_DEFAULT_ATTRIBUTES);
                       return;
                   }
                   prevSibling = prevSibling.getPrevSibling();
               }
           }
	}

	final PsiComment comment = PsiTreeUtil.getContextOfType(element, PsiComment.class);
	if (comment != null && JSGraphQLEndpointDocPsiUtil.isDocumentationComment(comment)) {
		final TextAttributesKey textAttributesKey = ATTRIBUTES.get(elementType);
		if (textAttributesKey != null) {
			setTextAttributes(element, holder, textAttributesKey);
		}
		// highlight invalid argument names after @param
		if(elementType == JSGraphQLEndpointDocTokenTypes.DOCVALUE) {
			final JSGraphQLEndpointFieldDefinition field = PsiTreeUtil.getNextSiblingOfType(comment, JSGraphQLEndpointFieldDefinition.class);
			if(field != null) {
				final JSGraphQLEndpointDocTag tag = PsiTreeUtil.getParentOfType(element, JSGraphQLEndpointDocTag.class);
				if(tag != null && tag.getDocName().getText().equals("@param")) {
					final String paramName = element.getText();
					final JSGraphQLEndpointInputValueDefinitions arguments = PsiTreeUtil.findChildOfType(field, JSGraphQLEndpointInputValueDefinitions.class);
					if(arguments == null) {
						// no arguments so invalid use of @param
						holder.createErrorAnnotation(element, "Invalid use of @param. The property has no arguments");
					} else {
						final JSGraphQLEndpointInputValueDefinition[] inputValues = PsiTreeUtil.getChildrenOfType(arguments, JSGraphQLEndpointInputValueDefinition.class);
						boolean found = false;
						if(inputValues != null) {
							for (JSGraphQLEndpointInputValueDefinition inputValue: inputValues) {
								if(inputValue.getInputValueDefinitionIdentifier().getText().equals(paramName)) {
									found = true;
									break;
								}
							}
						}
						if(!found) {
							holder.createErrorAnnotation(element, "@param name '" + element.getText() + "' doesn't match any of the field arguments");
						}

					}
				}
			}
		}
	}
}
 
Example 10
Source File: VariableNameCompletionProvider.java    From BashSupport with Apache License 2.0 4 votes vote down vote up
@Override
protected void addBashCompletions(String currentText, CompletionParameters parameters, ProcessingContext context, CompletionResultSet result) {
    PsiElement element = parameters.getPosition();

    BashVar varElement = PsiTreeUtil.getContextOfType(element, BashVar.class, false);
    boolean dollarPrefix = currentText != null && currentText.startsWith("$");
    boolean insideExpansion = element.getParent() != null && element.getParent().getParent() instanceof BashParameterExpansion;
    if (varElement == null && !dollarPrefix && !insideExpansion) {
        return;
    }

    int invocationCount = parameters.getInvocationCount();
    int resultLength = 0;

    PsiElement original = parameters.getOriginalPosition();
    BashVar varElementOriginal = original != null ? PsiTreeUtil.getContextOfType(original, BashVar.class, false) : null;

    if (varElement != null) {
        // only keep vars of included files when starting in the original file
        PsiElement originalRef = varElementOriginal != null ? varElementOriginal : original;
        if (originalRef != null) {
            resultLength += addCollectedVariables(original, result, new BashVarVariantsProcessor(originalRef, false, true));
        }

        // only keep vars of the dummy file when starting in the dummy file
        resultLength += addCollectedVariables(element, result, new BashVarVariantsProcessor(varElement, true, false));
    } else {
        // not in a variable element, but collect all known variable names at this offset in the current file
        if (original != null) {
            resultLength += addCollectedVariables(original, result, new BashVarVariantsProcessor(original, false, true));
        }
        resultLength += addCollectedVariables(element, result, new BashVarVariantsProcessor(element, false, true));
    }

    if (currentText != null && (dollarPrefix || insideExpansion) && (invocationCount >= 2 || resultLength == 0)) {
        Project project = element.getProject();
        addBuiltInVariables(result, project);
        addGlobalVariables(result, project);
    } else {
        result.addLookupAdvertisement("Press twice for global variables");
    }
}
 
Example 11
Source File: GrammarElementRef.java    From intellij-plugin-v4 with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
/** Using for completion. Returns list of rules and tokens; the prefix
	 *  of current element is used as filter by IDEA later.
	 */
	@NotNull
	@Override
	public Object[] getVariants() {
		String prefix = myElement.getText();
		RulesNode rules = PsiTreeUtil.getContextOfType(myElement, RulesNode.class);
		// find all rule defs (token, parser)
		Collection<? extends RuleSpecNode> ruleSpecNodes =
			PsiTreeUtil.findChildrenOfAnyType(rules,
											  new Class[] {
												ParserRuleSpecNode.class,
											  	LexerRuleSpecNode.class}
											 );

		return ruleSpecNodes.toArray();
//
//		final ArrayList<LookupElement> list = new ArrayList<LookupElement>();
//		PsiFile containingFile = myElement.getContainingFile();
//		List<BnfRule> rules = containingFile instanceof BnfFile ? ((BnfFile)containingFile).getRules() : Collections.<BnfRule>emptyList();
//		for (BnfRule rule : rules) {
//			boolean fakeRule = ParserGeneratorUtil.Rule.isFake(rule);
//			boolean privateRule = ParserGeneratorUtil.Rule.isPrivate(rule);
//			list.add(LookupElementBuilder.createWithIcon(rule).withBoldness(!privateRule).withStrikeoutness(fakeRule));
//		}
//		if (GrammarUtil.isExternalReference(myElement)) {
//			BnfRule rule = PsiTreeUtil.getParentOfType(myElement, BnfRule.class);
//			String parserClass = ParserGeneratorUtil.getAttribute(rule, KnownAttribute.PARSER_UTIL_CLASS);
//			if (StringUtil.isNotEmpty(parserClass)) {
//				JavaHelper javaHelper = JavaHelper.getJavaHelper(myElement.getProject());
//				for (NavigatablePsiElement element : javaHelper.getClassMethods(parserClass, true)) {
//					List<String> methodTypes = javaHelper.getMethodTypes(element);
//					if (methodTypes.size() > 3 &&
//						methodTypes.get(0).equals("boolean") &&
//						methodTypes.get(1).equals("com.intellij.lang.PsiBuilder") &&
//						methodTypes.get(3).equals("int")) {
//						list.add(LookupElementBuilder.createWithIcon((PsiNamedElement)element));
//					}
//				}
//			}
//		}
//		return ArrayUtil.toObjectArray(list);
	}