下面列出了com.intellij.psi.PsiReferenceBase#com.intellij.psi.PsiReference 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@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);
}
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());
}
@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());
}
@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;
}
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;
}
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;
}
@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)};
}
@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];
}
@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()]);
}
@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;
}
@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;
}
@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);
}
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);
}
public void testReference6()
{
myFixture.configureByFile("public/packages/filePackagesResolveTest.js");
PsiReference reference;
reference = getReferenceForHumanPosition(7, 35);
assertReference(reference, "'packageWithMainNotExists'", null);
}
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);
}
}
/**
* 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());
}
/**
* @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());
}
@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();
}
public void testReference2()
{
myFixture.configureByFile("public/blocks/fileForReferenceTestWithExclamationMark.js");
PsiReference reference;
// 1
reference = getReferenceForHumanPosition(3, 42);
assertReference(reference, "'moduleTwo!moduleOne'", "childBlock.js");
}
@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");
}
@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);
}
}
}
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());
});
}
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;
}
@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));
}
/**
* 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;
}
public static TranslationReference getTranslationReference(@NotNull PsiElement element) {
for (PsiReference reference : element.getReferences()) {
if (reference instanceof TranslationReference) {
return (TranslationReference) reference;
}
}
return null;
}
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);
}
@Nonnull
@Override
public Collection<PsiReference> findReferences(PsiElement element) {
if (!getSearchForReferences(element)) {
return Collections.emptyList();
}
return super.findReferences(element);
}
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());
}
/**
* 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;
}