com.intellij.psi.PsiReference Java Examples
The following examples show how to use
com.intellij.psi.PsiReference.
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: BlazePackageFindUsagesTest.java From intellij with Apache License 2.0 | 6 votes |
@Test public void testLabelFragmentReferenceFound() { BuildFile foo = createBuildFile( new WorkspacePath("java/com/google/foo/BUILD"), "java_library(name = \"lib\")"); BuildFile bar = createBuildFile( new WorkspacePath("java/com/google/bar/BUILD"), "java_library(name = \"lib2\", exports = [\"//java/com/google/foo:lib\"])"); PsiReference[] references = FindUsages.findAllReferences(foo); assertThat(references).hasLength(1); PsiElement ref = references[0].getElement(); assertThat(ref).isInstanceOf(StringLiteral.class); assertThat(ref.getContainingFile()).isEqualTo(bar); }
Example #2
Source File: HaskellGoToSymbolTest.java From intellij-haskforce with Apache License 2.0 | 6 votes |
public void testGoToSymbolFunction_QualifiedImportQualifierresolvesMultipleCons_Cons2() { PsiFile[] psiFiles = myFixture.configureByFiles( "QualifiedImport_QualifierResolvesMultipleCons_Cons2/Usage.hs", "QualifiedImport_QualifierResolvesMultipleCons_Cons2/Definition.hs" ); PsiFile usage = psiFiles[0]; String textOfFile = usage.getText(); int expectedStartOffset = textOfFile.indexOf("as Def.Lef") + 7; PsiElement psiElement = usage .findElementAt(myFixture.getCaretOffset()).getParent(); HaskellConid conId = (HaskellConid) psiElement; PsiReference reference = conId.getReference(); HaskellConid referencedElement = (HaskellConid) reference.resolve(); assertNotSame(psiElement, referencedElement); assertEquals(expectedStartOffset, referencedElement.getTextRange().getStartOffset()); }
Example #3
Source File: VarResolveTestCase.java From BashSupport with Apache License 2.0 | 6 votes |
@Test public void testBasicResolveUnknownGlobalVariable() throws Exception { final PsiReference psiReference = configure(); //must not resolve because the definition is local due to the previous definition PsiElement varDef = psiReference.resolve(); Assert.assertNull("The vardef should not be found, because it is undefined", varDef); //the variable must not be a valid reference to the following var def final AtomicInteger visited = new AtomicInteger(0); psiReference.getElement().getContainingFile().acceptChildren(new PsiRecursiveElementVisitor() { @Override public void visitElement(PsiElement element) { if (element instanceof BashVarDef) { visited.incrementAndGet(); Assert.assertFalse("A var def must not be a valid definition for the variable used.", psiReference.isReferenceTo(element)); } super.visitElement(element); } }); Assert.assertEquals(1, visited.get()); }
Example #4
Source File: ChangeSignatureAction.java From consulo with Apache License 2.0 | 6 votes |
@Nullable private static PsiElement findTargetMember(@Nullable PsiElement element) { if (element == null) return null; final ChangeSignatureHandler fileHandler = getChangeSignatureHandler(element.getLanguage()); if (fileHandler != null) { final PsiElement targetMember = fileHandler.findTargetMember(element); if (targetMember != null) return targetMember; } PsiReference reference = element.getReference(); if (reference == null && element instanceof PsiNameIdentifierOwner) { return element; } if (reference != null) { return reference.resolve(); } return null; }
Example #5
Source File: JSGraphQLEndpointErrorAnnotator.java From js-graphql-intellij-plugin with MIT License | 6 votes |
private JSGraphQLEndpointFieldDefinition getOverriddenField(JSGraphQLEndpointFieldDefinition override) { final String propertyName = override.getProperty().getIdentifier().getText(); final JSGraphQLEndpointObjectTypeDefinition typeDefinition = PsiTreeUtil.getParentOfType(override, JSGraphQLEndpointObjectTypeDefinition.class); if (typeDefinition != null) { final JSGraphQLEndpointImplementsInterfaces implementsInterfaces = PsiTreeUtil.findChildOfType(typeDefinition, JSGraphQLEndpointImplementsInterfaces.class); if (implementsInterfaces != null) { for (JSGraphQLEndpointNamedType namedType : implementsInterfaces.getNamedTypeList()) { final PsiReference reference = namedType.getReference(); if (reference != null) { final PsiElement interfaceTypeName = reference.resolve(); if (interfaceTypeName != null) { final JSGraphQLEndpointInterfaceTypeDefinition interfaceTypeDefinition = PsiTreeUtil.getParentOfType(interfaceTypeName, JSGraphQLEndpointInterfaceTypeDefinition.class); if (interfaceTypeDefinition != null) { for (JSGraphQLEndpointProperty property : PsiTreeUtil.findChildrenOfType(interfaceTypeDefinition, JSGraphQLEndpointProperty.class)) { if (property.getIdentifier().getText().equals(propertyName)) { return PsiTreeUtil.getParentOfType(property, JSGraphQLEndpointFieldDefinition.class); } } } } } } } } return null; }
Example #6
Source File: GenericInlineHandler.java From consulo with Apache License 2.0 | 6 votes |
public static Map<Language, InlineHandler.Inliner> initializeInliners(PsiElement element, InlineHandler.Settings settings, Collection<? extends PsiReference> allReferences) { final Map<Language, InlineHandler.Inliner> inliners = new HashMap<Language, InlineHandler.Inliner>(); for (PsiReference ref : allReferences) { if (ref == null) { LOG.error("element: " + element.getClass()+ ", allReferences contains null!"); continue; } PsiElement refElement = ref.getElement(); LOG.assertTrue(refElement != null, ref.getClass().getName()); final Language language = refElement.getLanguage(); if (inliners.containsKey(language)) continue; final List<InlineHandler> handlers = InlineHandlers.getInlineHandlers(language); for (InlineHandler handler : handlers) { InlineHandler.Inliner inliner = handler.createInliner(element, settings); if (inliner != null) { inliners.put(language, inliner); break; } } } return inliners; }
Example #7
Source File: SQFVariable.java From arma-intellij-plugin with MIT License | 6 votes |
@NotNull @Override public PsiReference[] getReferences() { SQFFile sqfFile = (SQFFile) getContainingFile(); if (sqfFile == null) { return PsiReference.EMPTY_ARRAY; } List<SQFVariable> vars = new ArrayList<>(); PsiUtil.traverseBreadthFirstSearch(sqfFile.getNode(), astNode -> { PsiElement nodeAsElement = astNode.getPsi(); if (nodeAsElement instanceof SQFVariable) { SQFVariable var = (SQFVariable) nodeAsElement; if (var.isLocal()) { return false; } if (SQFVariableName.nameEquals(var.getVarName(), getVarName())) { vars.add(var); } } return false; }); if (vars.isEmpty()) { return PsiReference.EMPTY_ARRAY; } return new PsiReference[]{new SQFVariableReference.IdentifierReference(this, vars)}; }
Example #8
Source File: ConfigEntityTypeAnnotation.java From idea-php-drupal-symfony2-bridge with MIT License | 6 votes |
@Nullable @Override public PsiReference[] getPropertyReferences(AnnotationPropertyParameter parameter, PhpAnnotationReferenceProviderParameter phpAnnotationReferenceProviderParameter) { if(!isSupported(parameter)) { return new PsiReference[0]; } String propertyName = parameter.getPropertyName(); if("admin_permission".equalsIgnoreCase(propertyName)) { String contents = getContents(parameter.getElement()); if(StringUtils.isBlank(contents)) { return new PsiReference[0]; } return new PsiReference[] {new ContentEntityTypeAnnotation.MyPermissionPsiPolyVariantReferenceBase(parameter.getElement(), contents)}; } return new PsiReference[0]; }
Example #9
Source File: IdentifierMixin.java From bamboo-soy with Apache License 2.0 | 6 votes |
@Override public PsiReference[] getReferences() { PsiElement element = getNode().getPsi(); String maybeEmbeddedExpression = this.getText(); if (!maybeEmbeddedExpression.startsWith("\"")) { PsiReference singleReference = getReference(); return singleReference == null ? PsiReference.EMPTY_ARRAY : new PsiReference[]{singleReference}; } Matcher identifierMatcher = IDENTIFIER_PATTERN.matcher(maybeEmbeddedExpression); List<PsiReference> variableReferenceList = new ArrayList<>(); while (identifierMatcher.find()) { variableReferenceList.add( new VariableDefinitionReference( element, maybeEmbeddedExpression.substring( identifierMatcher.start() + 1, identifierMatcher.end()), new TextRange( element.getTextRange().getStartOffset() + identifierMatcher.start(), element.getTextRange().getStartOffset() + identifierMatcher.end()), new TextRange(identifierMatcher.start(), identifierMatcher.end()))); } return variableReferenceList.toArray(new PsiReference[variableReferenceList.size()]); }
Example #10
Source File: SingleTargetRequestResultProcessor.java From consulo with Apache License 2.0 | 6 votes |
@Override public boolean processTextOccurrence(@Nonnull PsiElement element, int offsetInElement, @Nonnull final Processor<? super PsiReference> consumer) { if (!myTarget.isValid()) { return false; } final List<PsiReference> references = ourReferenceService.getReferences(element, new PsiReferenceService.Hints(myTarget, offsetInElement)); //noinspection ForLoopReplaceableByForEach for (int i = 0; i < references.size(); i++) { PsiReference ref = references.get(i); ProgressManager.checkCanceled(); if (ReferenceRange.containsOffsetInElement(ref, offsetInElement) && ref.isReferenceTo(myTarget) && !consumer.process(ref)) { return false; } } return true; }
Example #11
Source File: GrammarElementRefTest.java From intellij-plugin-v4 with BSD 3-Clause "New" or "Revised" License | 6 votes |
@Nullable private PsiElement resolveRefAtCaret() { PsiElement elementAtCaret = myFixture.getFile().findElementAt(myFixture.getCaretOffset()); if (elementAtCaret != null) { PsiReference ref = elementAtCaret.getReference(); if (ref != null) { return ref.resolve(); } else { fail("No reference at caret"); } } else { fail("No element at caret"); } return null; }
Example #12
Source File: CypherVariableElement.java From jetbrains-plugin-graph-database-support with Apache License 2.0 | 6 votes |
@Override default CypherType getType() { return Optional.ofNullable(getReferences()) .filter(reference -> reference.length > 0) .map(reference -> reference[0]) .map(PsiReference::resolve) .map(PsiElement::getParent) .map(node -> { if (node instanceof CypherNodePattern) { return NODE; } else if (node instanceof CypherPatternPart) { return PATH; } else if (node instanceof CypherRelationshipDetail) { return resolveRelationshipType((CypherRelationshipDetail) node); } return null; }) .orElse(ANY); }
Example #13
Source File: CppParsingTest.java From CppTools with Apache License 2.0 | 5 votes |
public void test() throws Throwable { doParseTest("SimpleParse"); String docContent = myFixture.getEditor().getDocument().getCharsSequence().toString(); String marker = "warn"; PsiReference psiReference = myFixture.getFile().findReferenceAt(docContent.indexOf(marker) + marker.length()); assertNotNull(psiReference); assertTrue(!(psiReference instanceof PsiMultiReference)); marker = "operator =="; int offset = docContent.indexOf(marker) + marker.length() - 1; psiReference = myFixture.getFile().findReferenceAt(offset); assertNotNull(psiReference); assertTrue(!(psiReference instanceof PsiMultiReference)); PsiElement psiElement = TargetElementUtil.getInstance().findTargetElement(myFixture.getEditor(), TargetElementUtil.REFERENCED_ELEMENT_ACCEPTED | TargetElementUtil.ELEMENT_NAME_ACCEPTED, offset); assertNotNull(psiElement); marker = "operator="; offset = docContent.indexOf(marker) + marker.length() - 1; psiReference = myFixture.getFile().findReferenceAt(offset); assertNotNull(psiReference); assertTrue(!(psiReference instanceof PsiMultiReference)); psiElement = TargetElementUtil.getInstance().findTargetElement(myFixture.getEditor(), TargetElementUtil.REFERENCED_ELEMENT_ACCEPTED | TargetElementUtil.ELEMENT_NAME_ACCEPTED, offset); assertNotNull(psiElement); }
Example #14
Source File: PackageTest.java From WebStormRequireJsPlugin with MIT License | 5 votes |
public void testReference6() { myFixture.configureByFile("public/packages/filePackagesResolveTest.js"); PsiReference reference; reference = getReferenceForHumanPosition(7, 35); assertReference(reference, "'packageWithMainNotExists'", null); }
Example #15
Source File: ProtoErrorsAnnotator.java From protobuf-jetbrains-plugin with Apache License 2.0 | 5 votes |
private void checkReference(PsiElement element) { PsiReference ref = element.getReference(); if (ref == null || ref.isSoft()) { return; } if (ref.resolve() == null) { String message = message("error.unresolved.reference"); markError(element.getNode(), null, message); } }
Example #16
Source File: HaskellGoToSymbolTest.java From intellij-haskforce with Apache License 2.0 | 5 votes |
/** * TODO * Can only make this test work if findDefinitionNode returns the type declaration as well */ public void ignoreTestGoToSymbolFunction_RecordsType(){ myFixture.configureByFile(getTestName(false)+".hs"); PsiFile file = myFixture.getFile(); String textOfFile = file.getText(); int expectedStartOffset= textOfFile.indexOf("data Pool") + 5; PsiElement psiElement = file .findElementAt(myFixture.getCaretOffset()).getParent(); HaskellConid conId = (HaskellConid) psiElement; PsiReference reference = conId.getReference(); HaskellConid referencedElement = (HaskellConid)reference.resolve(); assertNotSame(psiElement, referencedElement); assertEquals(expectedStartOffset,referencedElement.getTextRange().getStartOffset()); }
Example #17
Source File: BaseLithoComponentsDeclarationHandler.java From litho with Apache License 2.0 | 5 votes |
/** * @return Stream of resolved elements from the given element or an empty stream if nothing found. */ static Stream<PsiElement> resolve(PsiElement sourceElement) { return Optional.of(sourceElement) .filter(PsiIdentifier.class::isInstance) .map(element -> PsiTreeUtil.getParentOfType(element, PsiJavaCodeReferenceElement.class)) .map(PsiElement::getReferences) .map( psiReferences -> Stream.of(psiReferences).map(PsiReference::resolve).filter(Objects::nonNull)) .orElse(Stream.empty()); }
Example #18
Source File: GraphQLDirectiveLocationPsiElement.java From js-graphql-intellij-plugin with MIT License | 5 votes |
@Override public PsiReference getReference() { final Ref<PsiReference> reference = new Ref<>(); final GraphQLDirectiveLocationPsiElement psiElement = this; final String locationName = psiElement.getText(); GraphQLPsiSearchHelper.getService(getProject()).getBuiltInSchema().accept(new PsiRecursiveElementVisitor() { @Override public void visitElement(PsiElement element) { if(element instanceof GraphQLEnumValue && element.getText().equals(locationName)) { final GraphQLIdentifier referencedEnumValue = ((GraphQLEnumValue) element).getNameIdentifier(); reference.set(new PsiReferenceBase<PsiElement>(psiElement, new TextRange(0, psiElement.getTextLength())) { @Nullable @Override public PsiElement resolve() { return referencedEnumValue; } @NotNull @Override public Object[] getVariants() { return PsiReference.EMPTY_ARRAY; } }); return; // done visiting } super.visitElement(element); } }); return reference.get(); }
Example #19
Source File: ExclamationMarkTest.java From WebStormRequireJsPlugin with MIT License | 5 votes |
public void testReference2() { myFixture.configureByFile("public/blocks/fileForReferenceTestWithExclamationMark.js"); PsiReference reference; // 1 reference = getReferenceForHumanPosition(3, 42); assertReference(reference, "'moduleTwo!moduleOne'", "childBlock.js"); }
Example #20
Source File: RenameVariableTest.java From BashSupport with Apache License 2.0 | 5 votes |
@Test @Ignore //broken atm public void _testEvalRenameInlined() throws Exception { doRename(new Runnable() { @Override public void run() { PsiReference psiReference = myFixture.getFile().findReferenceAt(myFixture.getEditor().getCaretModel().getOffset()); Assert.assertTrue(psiReference.resolve() instanceof BashVarDef); myFixture.renameElementAtCaret("a_renamed"); } }, "source.bash"); }
Example #21
Source File: RouteAnnotator.java From idea-php-typo3-plugin with MIT License | 5 votes |
@Override public void annotate(@NotNull PsiElement psiElement, @NotNull AnnotationHolder annotationHolder) { if (!TYPO3CMSProjectSettings.getInstance(psiElement.getProject()).pluginEnabled) { return; } if (!TYPO3CMSProjectSettings.getInstance(psiElement.getProject()).routeAnnotatorEnabled) { return; } if (!(psiElement instanceof StringLiteralExpression)) { return; } StringLiteralExpression literalExpression = (StringLiteralExpression) psiElement; String value = literalExpression.getContents(); if (value.isEmpty()) { return; } for (PsiReference psiReference : literalExpression.getReferences()) { if (psiReference instanceof RouteReference) { annotateRoute(psiElement, annotationHolder, value); } } }
Example #22
Source File: ReferenceSearch.java From Intellij-Plugin with Apache License 2.0 | 5 votes |
private void processElements(final ReferencesSearch.SearchParameters searchParameters, final Processor<? super PsiReference> processor) { ApplicationManager.getApplication().runReadAction(() -> { StepCollector collector = helper.getStepCollector(searchParameters.getElementToSearch()); collector.collect(); final List<PsiElement> elements = helper.getPsiElements(collector, searchParameters.getElementToSearch()); for (PsiElement element : elements) processor.process(element.getReference()); }); }
Example #23
Source File: JavaClassUtils.java From camel-idea-plugin with Apache License 2.0 | 5 votes |
public PsiClass resolveClassReference(@NotNull PsiReference reference) { final PsiElement resolveElement = reference.resolve(); if (resolveElement instanceof PsiClass) { return (PsiClass) resolveElement; } else if (resolveElement instanceof PsiField) { final PsiType psiType = PsiUtil.getTypeByPsiElement(resolveElement); if (psiType != null) { return ((PsiClassReferenceType) psiType).resolve(); } } return null; }
Example #24
Source File: ReferencesTestCase.java From BashSupport with Apache License 2.0 | 5 votes |
@Test public void testValidScope() throws Exception { PsiReference variableReference = configure(); PsiFile included = addFile("included.bash"); PsiElement varDef = variableReference.resolve(); Assert.assertNotNull("The reference did not resolve", varDef); Assert.assertTrue("var def must resolve to the definition in included.bash", included.equals(varDef.getContainingFile())); Assert.assertTrue("The definition and usage scope must be valid", BashVarUtils.isInDefinedScope(variableReference.getElement(), (BashVarDef) varDef)); }
Example #25
Source File: YiiPsiReferenceProvider.java From yiistorm with MIT License | 5 votes |
/** * Return reference or empty array * * @param element PsiElement * @param context ProcessingContext * @return PsiReference[] */ @NotNull @Override public PsiReference[] getReferencesByElement(@NotNull PsiElement element, @NotNull final ProcessingContext context) { project = element.getProject(); String elname = element.getClass().getName(); //properties = PropertiesComponent.getInstance(project); /*boolean ProviderType2 = YiiRefsHelper.isYiiApplication(element); if (ProviderType2) { ProviderType2 = ProviderType2; } */ if (elname.endsWith("StringLiteralExpressionImpl")) { try { PsiFile file = element.getContainingFile(); VirtualFile vfile = file.getVirtualFile(); if (vfile != null) { String path = vfile.getPath(); String basePath = project.getBasePath(); if (basePath != null) { projectPath = basePath.replace("\\", "/"); int ProviderType = YiiRefsHelper.getYiiObjectType(path, element); switch (ProviderType) { case YiiRefsHelper.YII_TYPE_AR_RELATION: return ARRelationReferenceProvider.getReference(path, element); case YiiRefsHelper.YII_TYPE_CACTION_TO_VIEW_RENDER: return CActionRenderViewReferenceProvider.getReference(path, element); case YiiRefsHelper.YII_TYPE_WIDGET_VIEW_RENDER: return WidgetRenderViewReferenceProvider.getReference(path, element); case YiiRefsHelper.YII_TYPE_CONTROLLER_ACTIONS_CACTION: return ControlleActionsClassReferenceProvider.getReference(path, element); } } } } catch (Exception e) { //System.err.println("error" + e.getMessage()); } } return PsiReference.EMPTY_ARRAY; }
Example #26
Source File: TranslationUtil.java From idea-php-typo3-plugin with MIT License | 5 votes |
public static TranslationReference getTranslationReference(@NotNull PsiElement element) { for (PsiReference reference : element.getReferences()) { if (reference instanceof TranslationReference) { return (TranslationReference) reference; } } return null; }
Example #27
Source File: CustomOptionReferenceTest.java From protobuf-jetbrains-plugin with Apache License 2.0 | 5 votes |
public void testImportedImportedCustomOptionReference() { myFixture.configureByFiles( "reference/options/custom/SimpleExtensionField.proto", "reference/options/custom/ImportedExtension.proto" ); PsiReference reference = myFixture.getReferenceAtCaretPositionWithAssertion( "reference/options/custom/ImportedImportedExtension.proto" ); PsiElement target = reference.resolve(); Assert.assertNotNull(target); Assert.assertTrue(target instanceof FieldNode); FieldNode field = (FieldNode) target; Assert.assertEquals("bar", field.getFieldName()); Assert.assertTrue(field.getParent() instanceof ExtendEntryNode); }
Example #28
Source File: RenamePsiFileProcessor.java From consulo with Apache License 2.0 | 5 votes |
@Nonnull @Override public Collection<PsiReference> findReferences(PsiElement element) { if (!getSearchForReferences(element)) { return Collections.emptyList(); } return super.findReferences(element); }
Example #29
Source File: HaskellGoToSymbolTest.java From intellij-haskforce with Apache License 2.0 | 5 votes |
public void testGoToSymbolFunction_CanReferenceOtherFunction(){ myFixture.configureByFile(getTestName(false)+".hs"); PsiFile file = myFixture.getFile(); String textOfFile = file.getText(); int expectedStartOffset= textOfFile.indexOf("test2 ::"); PsiElement psiElement = file .findElementAt(myFixture.getCaretOffset()).getParent(); HaskellVarid varId = (HaskellVarid) psiElement; PsiReference reference = varId.getReference(); HaskellVarid referencedElement = (HaskellVarid)reference.resolve(); assertNotSame(psiElement, referencedElement); assertEquals(expectedStartOffset,referencedElement.getTextRange().getStartOffset()); }
Example #30
Source File: Symfony2InterfacesUtil.java From idea-php-toolbox with MIT License | 5 votes |
/** * Single resolve doesnt work if we have non unique class names in project context, * so try a multiResolve */ @Nullable public static Method[] getMultiResolvedMethod(PsiReference psiReference) { // class be unique in normal case, so try this first PsiElement resolvedReference = psiReference.resolve(); if (resolvedReference instanceof Method) { return new Method[] { (Method) resolvedReference }; } // try multiResolve if class exists twice in project if(psiReference instanceof PsiPolyVariantReference) { Collection<Method> methods = new HashSet<>(); for(ResolveResult resolveResult : ((PsiPolyVariantReference) psiReference).multiResolve(false)) { PsiElement element = resolveResult.getElement(); if(element instanceof Method) { methods.add((Method) element); } } if(methods.size() > 0) { return methods.toArray(new Method[methods.size()]); } } return null; }