public void testReferenceCanResolveDefinition() { PsiFile file = myFixture.configureByText(PhpFileType.INSTANCE, "<?php \n" + "class ActionController {" + "public function action() {" + " $this->forward('<caret>baz');" + "}" + "}" ); PsiElement elementAtCaret = file.findElementAt(myFixture.getCaretOffset()).getParent(); PsiReference[] references = elementAtCaret.getReferences(); for (PsiReference reference : references) { if (reference instanceof ControllerActionReference) { ResolveResult[] resolveResults = ((ControllerActionReference) reference).multiResolve(false); for (ResolveResult resolveResult : resolveResults) { assertInstanceOf(resolveResult.getElement(), Method.class); return; } } } fail("No TranslationReference found"); }
public void testReferenceCanResolveDefinition() { PsiFile file = myFixture.configureByText(PhpFileType.INSTANCE, "<?php \n" + "\"LLL:EXT:foo/sample.xlf:sys_<caret>language.language_isocode.ab\";"); PsiElement elementAtCaret = file.findElementAt(myFixture.getCaretOffset()).getParent(); PsiReference[] references = elementAtCaret.getReferences(); for (PsiReference reference : references) { if (reference instanceof TranslationReference) { ResolveResult[] resolveResults = ((TranslationReference) reference).multiResolve(false); for (ResolveResult resolveResult : resolveResults) { assertInstanceOf(resolveResult.getElement(), XmlTag.class); return; } } } fail("No TranslationReference found"); }
@Nullable private static IProperty getResolvedProperty(@NotNull final XmlAttributeValue codeValue) { return CachedValuesManager.getCachedValue(codeValue, KEY, () -> { List<IProperty> allProperties = new SmartList<>(); for (PsiReference nextRef : codeValue.getReferences()) { if (nextRef instanceof PsiPolyVariantReference) { Arrays.stream(((PsiPolyVariantReference) nextRef).multiResolve(false)) .filter(ResolveResult::isValidResult) .map(ResolveResult::getElement) .map(o -> ObjectUtils.tryCast(o, IProperty.class)) .filter(Objects::nonNull) .forEach(allProperties::add); } else { Optional.ofNullable(nextRef.resolve()) .map(o -> ObjectUtils.tryCast(o, IProperty.class)) .ifPresent(allProperties::add); } } IProperty theChosenOne = chooseForLocale(allProperties); return new CachedValueProvider.Result<>(theChosenOne, PsiModificationTracker.MODIFICATION_COUNT); }); }
@NotNull @Override public ResolveResult[] multiResolve(final boolean incompleteCode) { Project project = myElement.getProject(); final String enumLiteralJavaModelName = myElement.getText().replaceAll("\"", "").toUpperCase(); final PsiShortNamesCache psiShortNamesCache = PsiShortNamesCache.getInstance(project); final PsiField[] javaEnumLiteralFields = psiShortNamesCache.getFieldsByName( enumLiteralJavaModelName, GlobalSearchScope.allScope(project) ); final Set<PsiField> enumFields = stream(javaEnumLiteralFields) .filter(literal -> literal.getParent() != null) .filter(literal -> literal.getParent() instanceof ClsClassImpl) .filter(literal -> ((ClsClassImpl) literal.getParent()).isEnum()) .collect(Collectors.toSet()); return PsiElementResolveResult.createResults(enumFields); }
@NotNull @Override public ResolveResult[] multiResolve(final boolean incompleteCode) { final Project project = myElement.getProject(); final String modelName = PATTERN.matcher(myElement.getText()).replaceAll(""); final String javaModelName = modelName + JAVA_MODEL_SUFFIX; final String jaloModelName = modelName; final PsiClass[] javaModelClasses = PsiShortNamesCache.getInstance(project).getClassesByName( javaModelName, GlobalSearchScope.allScope(project) ); final PsiClass[] jaloModelClasses = PsiShortNamesCache.getInstance(project).getClassesByName( jaloModelName, GlobalSearchScope.projectScope(project) ); final PsiClass[] psiClasses = ArrayUtil.mergeArrays(javaModelClasses, jaloModelClasses); return PsiElementResolveResult.createResults(psiClasses); }
@NotNull @Override public ResolveResult[] multiResolve(final boolean incompleteCode) { final PsiFile originalFile = getElement().getContainingFile(); final Collection<ImpexMacroDeclaration> macroDeclarations = PsiTreeUtil.findChildrenOfType( originalFile, ImpexMacroDeclaration.class ); if (!macroDeclarations.isEmpty()) { final ArrayList<PsiElement> references = ContainerUtil.newArrayList(); for (final ImpexMacroDeclaration declaration : macroDeclarations) { if (getElement().textMatches(declaration.getFirstChild())) { references.add(declaration.getFirstChild()); } } return PsiElementResolveResult.createResults(references); } return ResolveResult.EMPTY_ARRAY; }
@NotNull public ResolveResult[] multiResolve(boolean incompleteCode) { final String name = getName(); if (name == null) return ResolveResult.EMPTY_ARRAY; ArrayList<LuaResolveResult> candidates = new ArrayList<LuaResolveResult>(); final PsiElement owner = LuaDocCommentUtil.findDocOwner(this); if (owner instanceof LuaFunctionDefinition) { final LuaFunctionDefinition method = (LuaFunctionDefinition)owner; final LuaParameter[] parameters = method.getParameters().getLuaParameters(); for (LuaParameter parameter : parameters) { if (name.equals(parameter.getName())) { candidates.add(new LuaResolveResultImpl(parameter, true)); } } return candidates.toArray(new ResolveResult[candidates.size()]); } return ResolveResult.EMPTY_ARRAY; }
@NotNull @Override public ResolveResult[] multiResolve(boolean incompleteCode) { String nodeTypeNameToFindReferenceFor = yamlElement.getKeyText(); // files which contain the NodeType definition Collection<VirtualFile> files = FileBasedIndex.getInstance().getContainingFiles(NodeTypesYamlFileIndex.KEY, nodeTypeNameToFindReferenceFor, GlobalSearchScope.allScope(yamlElement.getProject())); return files .stream() // get the PSI for each file .map(file -> PsiManager.getInstance(yamlElement.getProject()).findFile(file)) // ensure we only have YAML files .filter(psiFile -> psiFile instanceof YAMLFile) .map(psiFile -> (YAMLFile) psiFile) // get all YAML keys in these files .flatMap(yamlFile -> YAMLUtil.getTopLevelKeys(yamlFile).stream()) // get the correct YAML key .filter(yamlKeyValue -> yamlKeyValue.getKeyText().equals(nodeTypeNameToFindReferenceFor)) // remove "current" element if it exists .filter(yamlKeyValue -> yamlElement != yamlKeyValue) // build up the result object .map(yamlKeyValue -> new PsiElementResolveResult(yamlKeyValue, true)) .toArray(PsiElementResolveResult[]::new); }
@Nullable public PsiElement getPsiElement() { Object o = getObject(); if (o instanceof PsiElement) { return (PsiElement)o; } if (o instanceof ResolveResult) { return ((ResolveResult)o).getElement(); } if (o instanceof PsiElementNavigationItem) { return ((PsiElementNavigationItem)o).getTargetElement(); } if (o instanceof SmartPsiElementPointer) { return ((SmartPsiElementPointer)o).getElement(); } return null; }
@NotNull @Override public ResolveResult[] multiResolve(boolean incompleteCode) { final ResolveResult[] results = super.multiResolve(incompleteCode); boolean shadowed = false; for (ResolveResult result : results) { final PsiElement element = result.getElement(); if (element != null && (element.getContainingFile() != myElement.getContainingFile() || element instanceof PyFunction || element instanceof PyClass)) { shadowed = true; break; } } if (results.length > 0 && !shadowed) { return results; } // resolve to self if no other target found return new ResolveResult[] { new PsiElementResolveResult(myElement) }; }
public void testToConstructorInherited() { ResolveResult[] targets = multiResolve(); assertEquals(2, targets.length); // to class, to init PsiElement elt; // class elt = targets[0].getElement(); assertTrue(elt instanceof PyClass); assertEquals("Bar", ((PyClass)elt).getName()); // init elt = targets[1].getElement(); assertTrue(elt instanceof PyFunction); PyFunction fun = (PyFunction)elt; assertEquals(PyNames.INIT, fun.getName()); PyClass cls = fun.getContainingClass(); assertNotNull(cls); assertEquals("Foo", cls.getName()); }
public void testResolveIncludedRef2() throws Throwable { myTestFixture.copyFileToProject("include.rng"); final PsiReference ref = myTestFixture.getReferenceAtCaretPositionWithAssertion("resolve-include-ref-2.rng"); assertTrue("PolyVariantRef", ref instanceof PsiPolyVariantReference); final PsiElement element = ref.resolve(); assertNull(element); final ResolveResult[] results = ((PsiPolyVariantReference)ref).multiResolve(false); assertEquals(2, results.length); for (ResolveResult result : results) { PsiElement e = result.getElement(); assertTrue(e instanceof XmlTag); final int contentLength = ((XmlTag)e).getSubTags().length; if (e.getContainingFile() == ref.getElement().getContainingFile()) { assertEquals(1, contentLength); } else { assertEquals(0, contentLength); } } }
@NotNull public ResolveResult createResolveResult() { return new ResolveResult() { @Nullable @Override public PsiElement getElement() { // TODO: Try to find the item in the Gradle files return null; } @Override public boolean isValidResult() { return false; } }; }
@NotNull public ResolveResult[] resolve(@NotNull AntDomPropertyReference antDomPropertyReference, boolean incompleteCode) { final List<ResolveResult> result = new ArrayList<ResolveResult>(); final AntDomProject project = antDomPropertyReference.myInvocationContextElement.getParentOfType(AntDomProject.class, true); if (project != null) { final AntDomProject contextAntProject = project.getContextAntProject(); final String propertyName = antDomPropertyReference.getCanonicalText(); final Trinity<PsiElement,Collection<String>,PropertiesProvider> resolved = PropertyResolver.resolve(contextAntProject, propertyName, antDomPropertyReference.myInvocationContextElement); final PsiElement mainDeclaration = resolved.getFirst(); if (mainDeclaration != null) { result.add(new MyResolveResult(mainDeclaration, resolved.getThird())); } final List<PsiElement> antCallParams = AntCallParamsFinder.resolve(project, propertyName); for (PsiElement param : antCallParams) { result.add(new MyResolveResult(param, null)); } } return ContainerUtil.toArray(result, new ResolveResult[result.size()]); }
@Override public Integer weigh(@NotNull LookupElement element, @NotNull CompletionLocation location) { if (!(location.getCompletionParameters().getPosition().getContainingFile() instanceof GroovyFileBase)) { return null; } Object o = element.getObject(); if (o instanceof ResolveResult) { o = ((ResolveResult)o).getElement(); } if (o instanceof PsiMethod && (GroovyPropertyUtils.isSimplePropertyAccessor((PsiMethod)o) || "setProperty".equals(((PsiMethod)o).getName()))) { return 1; } return 0; }
@Nullable private static PsiElement resolveXsltReference(PsiReference reference) { final PsiElement element = reference.resolve(); if (element != null) { return element; } if (reference instanceof PsiPolyVariantReference) { final ResolveResult[] results = ((PsiPolyVariantReference)reference).multiResolve(false); for (ResolveResult result : results) { if (result.isValidResult() && result.getElement() instanceof XsltElement) { return result.getElement(); } } } return null; }
@NotNull public ResolveResult[] multiResolve(@NotNull Project project) { List<ResolveResult> typeDefs = SchemaIndexUtil.findTypeDefs(project, prefixes, suffix, searchScope).stream() .filter(Objects::nonNull) .map(PsiElementResolveResult::new) .collect(Collectors.toList()); // see comment in `resolve` above re. namespace declaration reference Qn prefix = input; int prefixLength = prefix.size(); List<SchemaNamespaceDecl> namespaceDecls = resolveNamespaces(project, prefix); ResolveResult[] namespaces = namespaceDecls.stream() .map(ns -> new PsiElementResolveResult(getTargetSegment(ns, prefixLength))) .toArray(ResolveResult[]::new); return ArrayUtil.mergeArrays(typeDefs.toArray(new ResolveResult[typeDefs.size()]), namespaces); }
@Override public void fillResolveResults(PsiElement psiElement, List<ResolveResult> results, String typeName) { Collection<VirtualFile> containingFiles = FileBasedIndex .getInstance() .getContainingFiles( EventsDeclarationsFileBasedIndex.NAME, typeName, GlobalSearchScope.allScope(psiElement.getProject()) ); PsiManager psiManager = PsiManager.getInstance(psiElement.getProject()); for (VirtualFile virtualFile: containingFiles) { PhpFile phpFile = (PhpFile)psiManager.findFile(virtualFile); if (phpFile != null) { recursiveFill(results, phpFile, typeName); } } }
@Override public void fillResolveResults(PsiElement psiElement, List<ResolveResult> results, String typeName) { Collection<VirtualFile> containingFiles = FileBasedIndex .getInstance() .getContainingFiles( EventObserverFileBasedIndex.NAME, typeName, GlobalSearchScope.allScope(psiElement.getProject()) ); PsiManager psiManager = PsiManager.getInstance(psiElement.getProject()); for (VirtualFile virtualFile: containingFiles) { XmlFile xmlFile = (XmlFile)psiManager.findFile(virtualFile); if (xmlFile != null) { results.add(new PhpResolveResult(xmlFile)); } } }
private void doTest(@NotNull String beforeText, String... expectedResolve) { myFixture.configureByText(GitFileType.INSTANCE, beforeText); PsiPolyVariantReference reference = ((PsiPolyVariantReference) myFixture.getReferenceAtCaretPosition()); assertNotNull(reference); final VirtualFile rootFile = myFixture.getFile().getContainingDirectory().getVirtualFile(); ResolveResult[] resolveResults = reference.multiResolve(true); List<String> actualResolve = ContainerUtil.map(resolveResults, new Function<ResolveResult, String>() { @Override public String fun(ResolveResult resolveResult) { PsiElement resolveResultElement = resolveResult.getElement(); assertNotNull(resolveResultElement); assertInstanceOf(resolveResultElement, PsiFileSystemItem.class); PsiFileSystemItem fileSystemItem = (PsiFileSystemItem) resolveResultElement; return VfsUtilCore.getRelativePath(fileSystemItem.getVirtualFile(), rootFile, '/'); } }); assertContainsElements(actualResolve, expectedResolve); }
@NotNull public static MethodResolveResult createResult(@NotNull MethodCalcResult calcResult, @Nullable PsiElement element, @Nullable ResolveResult resolveResult) { PsiElement providerElement = element == null ? null : element.getUserData(FORCE_PROVIDER_ELEMENT); if(providerElement == null && resolveResult instanceof CSharpResolveResult) { providerElement = ((CSharpResolveResult) resolveResult).getProviderElement(); } MethodResolveResult methodResolveResult = new MethodResolveResult(element, calcResult); methodResolveResult.setProvider(providerElement); if(resolveResult instanceof CSharpUndefinedResolveResult) { methodResolveResult.myUnknown = true; } return methodResolveResult; }
public void consumeAll() { ResolveResult[] resolveResults = ((CommonProcessors.CollectProcessor<ResolveResult>) myResultProcessor).toArray(ResolveResult.ARRAY_FACTORY); ContainerUtil.sort(resolveResults, myComparator); for(ResolveResult result : resolveResults) { ProgressManager.checkCanceled(); if(!myOriginalProcessor.process(result)) { return; } } }
@RequiredReadAction public CompletionResolveScopeProcessor(@NotNull CSharpResolveOptions options, @NotNull Processor<ResolveResult> processor, @NotNull ExecuteTarget[] targets) { myProcessor = processor; myPlace = options.getElement(); myScope = myPlace.getResolveScope(); CSharpContextUtil.ContextType completionContextType = options.getCompletionContextType(); if(completionContextType != null) { myContextType = completionContextType; } else { myContextType = myPlace instanceof CSharpReferenceExpression ? CSharpContextUtil.getParentContextTypeForReference((CSharpReferenceExpression) myPlace) : CSharpContextUtil.ContextType.ANY; } putUserData(ExecuteTargetUtil.EXECUTE_TARGETS, ExecuteTargetUtil.of(targets)); }
@RequiredReadAction @Override public void process(@NotNull CSharpResolveOptions options, @NotNull DotNetGenericExtractor defaultExtractor, @Nullable PsiElement forceQualifierElement, @NotNull 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)); } }
@RequiredReadAction @Override public void process(@NotNull CSharpResolveOptions options, @NotNull DotNetGenericExtractor defaultExtractor, @Nullable PsiElement forceQualifierElement, @NotNull Processor<ResolveResult> processor) { PsiElement element = options.getElement(); PsiElement nativeElement = ((CSharpReferenceExpression) element).getReferenceElement(); assert nativeElement != null; String nativeRuntimeType = CSharpNativeTypeImplUtil.ourElementToQTypes.get(nativeElement.getNode().getElementType()); if(nativeRuntimeType == null) { return; } PsiElement psiElement = DotNetPsiSearcher.getInstance(element.getProject()).findType(nativeRuntimeType, element.getResolveScope(), CSharpTransform.INSTANCE); if(psiElement == null) { return; } processor.process(new CSharpResolveResult(psiElement, true)); }
@Nullable private static CSharpTypeDeclaration hasElementWithName(ResolveResult[] resolveResults, String ref) { for(ResolveResult resolveResult : resolveResults) { if(!resolveResult.isValidResult()) { continue; } PsiElement resolveResultElement = resolveResult.getElement(); if(resolveResultElement instanceof CSharpTypeDeclaration && Comparing.equal(((CSharpTypeDeclaration) resolveResultElement).getName(), ref)) { return (CSharpTypeDeclaration) resolveResultElement; } } return null; }
private void putState(@NotNull ResolveResult firstValidResult, @Nullable PsiElement element) { if(element == null) { return; } if(firstValidResult instanceof CSharpResolveResult) { PsiElement providerElement = ((CSharpResolveResult) firstValidResult).getProviderElement(); if(providerElement instanceof CSharpUsingListChild) { CSharpUsingListChild child = (CSharpUsingListChild) providerElement; putElement(child, element); } } }
@RequiredReadAction @Override public void process(@NotNull CSharpResolveOptions options, @NotNull DotNetGenericExtractor defaultExtractor, @Nullable PsiElement forceQualifierElement, @NotNull Processor<ResolveResult> processor) { PsiElement element = options.getElement(); DotNetParameterListOwner parameterListOwner = CSharpReferenceExpressionImplUtil.findParentOrNextIfDoc(element, DotNetParameterListOwner .class); if(parameterListOwner == null) { return; } SimpleNamedScopeProcessor scopeProcessor = new SimpleNamedScopeProcessor(processor, options.isCompletion(), ExecuteTarget.LOCAL_VARIABLE_OR_PARAMETER); ResolveState state = ResolveState.initial(); state = state.put(CSharpResolveUtil.SELECTOR, options.getSelector()); parameterListOwner.processDeclarations(scopeProcessor, state, null, element); }
@RequiredReadAction @Override public void process(@NotNull CSharpResolveOptions options, @NotNull DotNetGenericExtractor defaultExtractor, @Nullable PsiElement forceQualifierElement, @NotNull Processor<ResolveResult> processor) { PsiElement element = options.getElement(); DotNetGenericParameterListOwner genericParameterListOwner = CSharpReferenceExpressionImplUtil.findParentOrNextIfDoc(element, DotNetGenericParameterListOwner.class); if(genericParameterListOwner == null) { return; } SimpleNamedScopeProcessor scopeProcessor = new SimpleNamedScopeProcessor(processor, options.isCompletion(), ExecuteTarget.GENERIC_PARAMETER); ResolveState state = ResolveState.initial(); state = state.put(CSharpResolveUtil.SELECTOR, options.getSelector()); genericParameterListOwner.processDeclarations(scopeProcessor, state, null, element); }
@RequiredReadAction private void processDefaultCompletion(@NotNull Processor<ResolveResult> processor, PsiElement element, PsiElement qualifier) { DotNetNamespaceAsElement namespace; String qualifiedText = ""; if(qualifier != null) { qualifiedText = StringUtil.strip(qualifier.getText(), CSharpReferenceExpression.DEFAULT_REF_FILTER); } namespace = DotNetPsiSearcher.getInstance(element.getProject()).findNamespace(qualifiedText, element.getResolveScope()); if(namespace == null) { return; } processNamespaceChildren(processor, element, namespace); }
@RequiredReadAction @Override public void process(@NotNull CSharpResolveOptions options, @NotNull DotNetGenericExtractor defaultExtractor, @Nullable PsiElement forceQualifierElement, @NotNull Processor<ResolveResult> processor) { PsiElement element = options.getElement(); DotNetTypeDeclaration thisTypeDeclaration = PsiTreeUtil.getParentOfType(element, DotNetTypeDeclaration.class); if(thisTypeDeclaration != null) { Pair<DotNetTypeDeclaration, DotNetGenericExtractor> pair = CSharpTypeDeclarationImplUtil.resolveBaseType(thisTypeDeclaration, element); if(pair != null) { processor.process(new CSharpResolveResultWithExtractor(pair.getFirst(), pair.getSecond())); } } }
@Nullable public static ResolveResult findFirstValidResult(ResolveResult[] resolveResults) { if(resolveResults.length == 0) { return null; } for(ResolveResult resolveResult : resolveResults) { if(resolveResult.isValidResult() && isAssignable(resolveResult)) { return resolveResult; } } return null; }
@RequiredReadAction public static void sortAndProcess(@NotNull List<MethodResolveResult> list, @NotNull Processor<ResolveResult> processor, @NotNull PsiElement place) { if(list.isEmpty()) { return; } ContainerUtil.sort(list, ourComparator); for(MethodResolveResult methodResolveResult : list) { ProgressManager.checkCanceled(); methodResolveResult.setAssignable(place); if(!processor.process(methodResolveResult)) { return; } } }
@RequiredReadAction private static boolean isReferenceTo(@NotNull ResolveResult resolveResult, PsiElement element) { PsiElement psiElement = resolveResult.getElement(); if(element instanceof DotNetNamespaceAsElement && psiElement instanceof DotNetNamespaceAsElement) { if(Comparing.equal(((DotNetNamespaceAsElement) psiElement).getPresentableQName(), ((DotNetNamespaceAsElement) element).getPresentableQName())) { return true; } } if(element.getManager().areElementsEquivalent(element, psiElement)) { return true; } return false; }
@NotNull @RequiredReadAction public static DotNetTypeRef toTypeRefWithoutCaching(@NotNull CSharpReferenceExpressionEx referenceExpressionEx, @NotNull ResolveToKind kind, boolean resolveFromParent) { ResolveResult[] resolveResults = referenceExpressionEx.multiResolveImpl(kind, resolveFromParent); if(resolveResults.length == 0) { return DotNetTypeRef.ERROR_TYPE; } ResolveResult firstValidResult = CSharpResolveUtil.findFirstValidResult(resolveResults); if(firstValidResult == null) { return DotNetTypeRef.ERROR_TYPE; } return CSharpReferenceExpressionImplUtil.toTypeRef(firstValidResult); }
@Override public ResolveResult[] doResolve() { if (myReferencedName == null) return ResolveResult.EMPTY_ARRAY; if (EmberJSAsExpression.isAsControllerRef(myRef, myRef.getParent())) { final JSNamedElementProxy resolve = EmberIndexUtil.resolve(myParent.getProject(), EmberControllerIndex.INDEX_ID, myReferencedName); if (resolve != null) { return new JSResolveResult[]{new JSResolveResult(resolve)}; } } else { final Collection<JSNamedElement> localVariables = getItemsByName(myReferencedName, myRef); if (!localVariables.isEmpty()) { return ContainerUtil.map2Array(localVariables, JSResolveResult.class, new Function<JSNamedElement, JSResolveResult>() { @Override public JSResolveResult fun(JSNamedElement item) { return new JSResolveResult(item); } }); } } return super.doResolve(); }