@Override public void prepareRenaming(PsiElement psiElement, String s, Map<PsiElement, String> map) { renders.clear(); for (PsiReference reference : findReferences(psiElement)) { final PsiElement element = reference.getElement(); if (element instanceof StringLiteralExpression) { String fileName = ((StringLiteralExpression) element).getContents(); if (fileName.contains("/")) { element.getParent().putUserData(RELATIVE_PATH, fileName.substring(0, fileName.lastIndexOf('/') + 1)); fileName = fileName.substring(fileName.lastIndexOf('/') + 1); } element.getParent().putUserData(WITH_EXT, fileName.contains(".")); String realFile = ((PsiFile) psiElement).getName(); if (realFile.contains(".")) { element.getParent().putUserData(OLD_EXT, realFile.substring(realFile.lastIndexOf('.'))); } renders.add(element.getParent()); } } }
@Override public boolean execute(@NotNull PsiElement element, int offsetInElement) { String selector; if (element instanceof AppleScriptHandlerCall) { AppleScriptHandlerCall handlerCall = (AppleScriptHandlerCall) element; selector = handlerCall.getHandlerSelector(); if (myHandlerSelector.equals(selector)) { for (PsiReference ref : element.getReferences()) { if (ref.isReferenceTo(myHandler)) { return myConsumer.process(ref); } } } } return true; }
private Boolean doExecute(ReferencesSearch.SearchParameters queryParameters, final Processor<PsiReference> consumer) { final PsiElement element = queryParameters.getElementToSearch(); //was selector_identifier->redefined in DictionaryComponent dictionaryComponent = null; if (element instanceof DictionaryComponent) { dictionaryComponent = (DictionaryComponent) element; } if (dictionaryComponent == null) return true; final List<String> parts = dictionaryComponent.getNameIdentifiers(); if (parts.isEmpty()) return true; final String componentName = dictionaryComponent.getName(); //or just getName()... final PsiSearchHelper helper = PsiSearchHelper.SERVICE.getInstance(element.getProject()); String searchWord = parts.get(0); return searchWord.isEmpty() || helper.processElementsWithWord(new MyOccurrenceProcessor(dictionaryComponent, componentName, consumer), queryParameters.getScopeDeterminedByUser(), searchWord, UsageSearchContext.IN_CODE, true); }
@Override public boolean execute(@NotNull PsiElement element, int offsetInElement) { String selector = null; if (element instanceof AppleScriptCommandHandlerCall) { AppleScriptCommandHandlerCall handlerCall = (AppleScriptCommandHandlerCall) element; selector = handlerCall.getCommandName(); }//todo: handle other component types else if (element instanceof DictionaryCompositeElement) { DictionaryCompositeElement dictionaryCompositeElement = (DictionaryCompositeElement) element; selector = dictionaryCompositeElement.getCompositeNameElement().getCompositeName(); } if (selector != null) { boolean selectorMatches; selectorMatches = myComponentName.equals(selector); if (selectorMatches) { for (PsiReference ref : element.getReferences()) { if (ref.isReferenceTo(myDictionaryComponent)) { return myConsumer.process(ref); } } } } return true; }
@Test public void should_process_reference() throws Exception { // given PsiReference reference1 = mock(PsiReference.class); PsiReference reference2 = mock(PsiReference.class); PsiField field = mock(PsiField.class); ReferencesSearch.SearchParameters searchParameters = mock(ReferencesSearch.SearchParameters.class); when(searchParameters.getElementToSearch()).thenReturn(field); when(searchParameters.getEffectiveSearchScope()).thenReturn(mock(GlobalSearchScope.class)); when(scenarioStateReferenceProvider.findReferences(field)).thenReturn(Arrays.asList(reference1, reference2)); when(scenarioStateProvider.isJGivenScenarioState(field)).thenReturn(true); // when referenceProvider.processQuery(searchParameters, processor); // then verify(processor).process(reference1); verify(processor).process(reference2); }
@Override public void annotate(@NotNull PsiElement psiElement, @NotNull AnnotationHolder annotationHolder) { 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); } } }
@NotNull @Override public FoldingDescriptor[] buildFoldRegions(@NotNull PsiElement root, @NotNull Document document, boolean quick) { FoldingGroup group = FoldingGroup.newGroup("TYPO3Route"); List<FoldingDescriptor> descriptors = new ArrayList<>(); Collection<StringLiteralExpression> literalExpressions = PsiTreeUtil.findChildrenOfType(root, StringLiteralExpression.class); for (final StringLiteralExpression literalExpression : literalExpressions) { for (PsiReference reference : literalExpression.getReferences()) { if (reference instanceof RouteReference) { String value = literalExpression.getContents(); FoldingDescriptor descriptor = foldRouteReferenceString(reference, value, group); if (descriptor != null) { descriptors.add(descriptor); } } } } return descriptors.toArray(new FoldingDescriptor[descriptors.size()]); }
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 testCanCreateTranslationReferencesOnPhpStrings() { 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) { return; } } fail("No ControllerActionReference found"); }
public void testResourceReferencesAreCreated() { myFixture.addFileToProject("foo/ext_emconf.php", ""); myFixture.configureByText(PhpFileType.INSTANCE, "<?php \n" + "'EXT:foo/ext_emconf.php<caret>';"); PsiElement elementAtCaret = myFixture.getFile().findElementAt(myFixture.getCaretOffset()).getParent(); PsiReference[] references = elementAtCaret.getReferences(); for (PsiReference ref : references) { if (ref instanceof ResourceReference) { return; } } fail("No resource reference."); }
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"); }
public void testReferenceCanResolveVariants() { 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) { Object[] variants = reference.getVariants(); for (Object variant : variants) { if (variant instanceof LookupElement) { String lookupString = ((LookupElement) variant).getLookupString(); assertEquals("LLL:EXT:foo/sample.xlf:sys_language.language_isocode.ab", lookupString); return; } } } } fail("No TranslationReference found"); }
public void testIconReferenceIsCreatedOnGetIcon() { myFixture.addFileToProject("foo/ext_emconf.php", ""); myFixture.configureByFile("IconRegistry9.php"); myFixture.configureByFile("icon_provider_test.php"); PsiElement elementAtCaret = myFixture.getFile().findElementAt(myFixture.getCaretOffset()).getParent(); PsiReference[] references = elementAtCaret.getReferences(); for (PsiReference ref : references) { if (ref instanceof IconReference) { return; } } fail("No icon reference found"); }
public void testIconReferenceIsCreatedOnGetIconFromGeneralUtility() { myFixture.addFileToProject("foo/ext_emconf.php", ""); myFixture.configureByFile("IconRegistry9.php"); myFixture.configureByFile("general_utility_icon_provider_test.php"); PsiElement elementAtCaret = myFixture.getFile().findElementAt(myFixture.getCaretOffset()).getParent(); PsiReference[] references = elementAtCaret.getReferences(); for (PsiReference ref : references) { if (ref instanceof IconReference) { return; } } fail("No icon reference found"); }
@NotNull @Override public PsiReference[] getReferencesByElement(@NotNull PsiElement element, @NotNull ProcessingContext context) { if (!(element instanceof XmlElement)) { return PsiReference.EMPTY_ARRAY; } List<PsiReference> psiReferences = new ArrayList<>(); String methodName = StringUtil.unquoteString(element.getText()); PhpClass phpClass = DiIndex.getPhpClassOfServiceMethod((XmlElement) element); if (phpClass != null) { Collection<Method> methods = phpClass.getMethods(); methods.removeIf(m -> !m.getName().equalsIgnoreCase(methodName)); psiReferences.add(new PolyVariantReferenceBase(element, methods)); } return psiReferences.toArray(new PsiReference[psiReferences.size()]); }
@NotNull @Override public PsiReference[] getReferencesByElement(@NotNull PsiElement element, @NotNull ProcessingContext context) { String value = StringUtil.unquoteString(element.getText()); DiIndex index = DiIndex.getInstance(element.getProject()); Collection<PsiElement> targets = index.getVirtualTypeElements(value, element.getResolveScope()); if (!(targets.size() > 0)) { return PsiReference.EMPTY_ARRAY; } return new PsiReference[] { new PolyVariantReferenceBase(element, targets) }; }
@NotNull @Override public PsiReference[] getReferencesByElement(@NotNull PsiElement element, @NotNull ProcessingContext context) { String value = StringUtil.unquoteString(element.getText()); Collection<PsiElement> targets = EventIndex.getInstance(element.getProject()) .getEventElements( value, GlobalSearchScope.getScopeRestrictedByFileTypes( GlobalSearchScope.allScope(element.getProject()), XmlFileType.INSTANCE ) ); if (targets.size() > 0) { return new PsiReference[] {new PolyVariantReferenceBase(element, targets)}; } return PsiReference.EMPTY_ARRAY; }
@NotNull @Override public PsiReference[] getReferencesByElement(@NotNull PsiElement element, @NotNull ProcessingContext context) { String parameterName = StringUtil.unquoteString(element.getText()); if (parameterName.isEmpty() || !(element instanceof XmlElement)) { return PsiReference.EMPTY_ARRAY; } DiIndex diIndex = DiIndex.getInstance(element.getProject()); PhpClass phpClass = diIndex.getPhpClassOfArgument((XmlElement) element); if (phpClass != null) { Method constructor = phpClass.getConstructor(); if (constructor != null) { Collection<Parameter> parameterList = new THashSet<>(Arrays.asList(constructor.getParameters())); parameterList.removeIf(p -> !p.getName().contains(parameterName)); if (parameterList.size() > 0) { return new PsiReference[] {new PolyVariantReferenceBase(element, parameterList)}; } } } return PsiReference.EMPTY_ARRAY; }
@NotNull @Override public PsiReference[] getReferencesByElement(@NotNull PsiElement element, @NotNull ProcessingContext context) { String value = StringUtil.unquoteString(element.getText()); Collection<VirtualFile> containingFiles = FileBasedIndex.getInstance() .getContainingFiles(EventNameIndex.KEY, value, GlobalSearchScope.getScopeRestrictedByFileTypes( GlobalSearchScope.allScope(element.getProject()), PhpFileType.INSTANCE ) ); PsiManager psiManager = PsiManager.getInstance(element.getProject()); for (VirtualFile virtualFile: containingFiles) { PhpFile phpFile = (PhpFile) psiManager.findFile(virtualFile); if (phpFile != null) { List<PsiElement> psiElements = new ArrayList<>(); recursiveFill(psiElements, phpFile, value); if (psiElements.size() > 0) { return new PsiReference[] {new PolyVariantReferenceBase(element, psiElements)}; } } } return PsiReference.EMPTY_ARRAY; }
@Override public PsiReference[] getReferences() { PsiElement element = getNode().getPsi(); String maybeEmbeddedExpression = this.getText(); if (!maybeEmbeddedExpression.startsWith("\"")) { PsiReference singleReference = getReference(); return singleReference == null ? new PsiReference[] {} : new PsiReference[] {singleReference}; } Matcher identifierMatcher = identifierPattern.matcher(maybeEmbeddedExpression); List<PsiReference> variableReferenceList = new ArrayList<>(); while (identifierMatcher.find()) { variableReferenceList.add( new VariableReference( 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()]); }
@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 final PsiReference[] getReferences() { final IElementType leafType = Optional.ofNullable(getFirstChild()) .map(PsiElement::getNode) .map(ASTNode::getElementType) .orElse(null); if (ImpexTypes.MACRO_USAGE.equals(leafType)) { return new PsiReference[]{new ImpexMacrosReferenceBase(this)}; } //optimisation: dont even try for macro's and documents if (!ImpexTypes.HEADER_PARAMETER_NAME.equals(leafType)) { return PsiReference.EMPTY_ARRAY; } if (myReference == null) { myReference = new TypeSystemAttributeReference(this); } return new PsiReference[]{myReference}; }
@Override public boolean ignoreUnresolvedReference(@NotNull PyElement element, @NotNull PsiReference reference) { final PsiFile file = element.getContainingFile(); final Project project = file.getProject(); if (StudyTaskManager.getInstance(project).getCourse() == null) { return false; } TaskFile taskFile = StudyUtils.getTaskFile(project, file.getVirtualFile()); if (taskFile == null || taskFile.isUserCreated() || taskFile.isHighlightErrors()) { return false; } if (PsiTreeUtil.getParentOfType(element, PyImportStatementBase.class) != null) { return false; } return true; }
@Override public void registerReferenceProviders(@NotNull PsiReferenceRegistrar registrar) { registrar.registerReferenceProvider(PlatformPatterns.psiElement(YAMLScalar.class), new PsiReferenceProvider() { @NotNull @Override public PsiReference[] getReferencesByElement(@NotNull PsiElement element, @NotNull ProcessingContext context) { if (isConfigFile(element)) { String valueText = ((YAMLScalar) element).getTextValue(); List<MacroResolver.Match> matches = new MacroResolver().resolve(valueText); List<PsiReference> references = new ArrayList<>(); matches.stream() .filter(match -> !match.isEscaped()) .map(match -> resolvePsiReferences(element, match.getReference(), (element instanceof YAMLQuotedText ? 1 : 0) + match.getStartPos())) .forEach(references::addAll); return references.toArray(new PsiReference[references.size()]); } return PsiReference.EMPTY_ARRAY; } }); }
@NotNull protected List<PsiReference> resolvePsiReferences(@NotNull PsiElement element, String value, int rangeOffset) { if (value != null) { String[] split = value.split("\\."); List<PsiReference> psiReferences = new ArrayList<>(); StringBuilder sb = new StringBuilder(); int startIndex = 0; for (int i = 0; i < split.length; i++) { if (i > 0) { sb.append("."); startIndex = sb.length(); } sb.append(split[i]); psiReferences.add(new CoffigReference(element, new TextRange(rangeOffset + startIndex, rangeOffset + sb.length()), sb.toString())); } return psiReferences; } else { return new ArrayList<>(); } }
@Override public void registerReferenceProviders(@NotNull PsiReferenceRegistrar registrar) { registrar.registerReferenceProvider(PlatformPatterns.psiElement(PsiLiteralExpression.class), new PsiReferenceProvider() { @NotNull @Override public PsiReference[] getReferencesByElement(@NotNull PsiElement element, @NotNull ProcessingContext context) { if (isLiteralOfConfigurationAnnotation(element) || isCoffigMethod(element)) { PsiLiteralExpression literalExpression = (PsiLiteralExpression) element; String value = literalExpression.getValue() instanceof String ? (String) literalExpression.getValue() : null; List<PsiReference> psiReferences = resolvePsiReferences(element, value, 1); return psiReferences.toArray(new PsiReference[psiReferences.size()]); } return PsiReference.EMPTY_ARRAY; } }); }
@Nullable @Override public List<UsageInfo> findUsages( PsiFile psiFile, PsiDirectory newParent, boolean searchInComments, boolean searchInNonJavaFiles ) { Module mod = ModuleUtilCore.findModuleForPsiElement( psiFile ); ManModule module = ManProject.getModule( mod ); PsiClass psiClass = findPsiClass( psiFile ); if( psiClass == null ) { return Collections.emptyList(); } Query<PsiReference> search = ReferencesSearch.search( psiClass, GlobalSearchScope.moduleWithDependenciesAndLibrariesScope( module.getIjModule() ) ); List<UsageInfo> usages = new ArrayList<>(); for( PsiReference ref: search.findAll() ) { usages.add( new MoveRenameUsageInfo( ref.getElement(), ref, ref.getRangeInElement().getStartOffset(), ref.getRangeInElement().getEndOffset(), psiClass, ref.resolve() == null && !(ref instanceof PsiPolyVariantReference && ((PsiPolyVariantReference)ref).multiResolve( true ).length > 0) ) ); } return usages; }
@NotNull @Override public Collection<PsiReference> findReferences( PsiElement element ) { Collection<PsiReference> references = super.findReferences( element ); if( element instanceof JsonProperty ) { //## hack: IJ's json parser considers all properties having the same name as the same reference, which is total crap references.clear(); } // Store refs to manifold types storeTypeManifoldReferences( element ); return references; }
public static PsiReference getReference(TSCallExpr call) { PsiElement nameNode = getNameNode(call); if (nameNode == null) { return null; } return new TSFunctionCallReference(call, nameNode); }
@Nullable @Override public PsiElement getElementByReference(@NotNull PsiReference ref, int flags) { // final PsiElement elem = ref.getElement(); // return ref.getElement(); return null; }
@Override public boolean execute(@NotNull final ReferencesSearch.SearchParameters queryParameters, @NotNull final Processor<PsiReference> consumer) { return new ReadAction<Boolean>() { protected void run(@NotNull final Result<Boolean> result) { result.setResult(doExecute(queryParameters, consumer)); } }.execute().getResultObject(); }
@Nullable @Override public PsiElement getOriginalDeclaration() { //todo (re)move this to targetReference PsiReference myReference = getReference(); if (myReference != null) { return myReference.resolve(); } return null; }
@Override public PsiReference getReference() { if (this instanceof AppleScriptTargetVariable) { return new AppleScriptTargetReferenceImpl(this); } return null; }
public List<PsiReference> findReferences(PsiField field, int maxNumberOfResults) { PsiClass fieldClass = PsiTypesUtil.getPsiClass(field.getType()); if (fieldClass == null) { return Collections.emptyList(); } Project project = field.getProject(); PsiManager manager = PsiManager.getInstance(project); JGivenUsageProvider usageProvider = new JGivenUsageProvider(scenarioStateProvider, resolutionHandler, new ReferenceFactory(manager)); StateReferenceProcessor processor = new StateReferenceProcessor(field, maxNumberOfResults, usageProvider); SearchScope scope = GlobalSearchScope.everythingScope(project).intersectWith(javaFilesScope(project)); findPsiFields(project, (GlobalSearchScope) scope, processor); return processor.getResults(); }
@Override public boolean process(PsiField field) { PsiReference reference = usageProvider.createReferenceIfJGivenUsage(fieldToSearch, field); if (reference != null) { results.add(reference); } return results.size() < maxNumberOfResults || maxNumberOfResults == ScenarioStateReferenceProvider.ANY_NUMBER_OF_RESULTS; }
@Nullable PsiReference createReferenceIfJGivenUsage(PsiField fieldToSearch, PsiField field) { if (scenarioStateProvider.isJGivenScenarioState(field) && !fieldToSearch.equals(field) && resolutionHandler.resolutionMatches(field, fieldToSearch)) { return referenceFactory.referenceFor(field); } return null; }
@Override public void processQuery(@NotNull ReferencesSearch.SearchParameters queryParameters, @NotNull Processor<PsiReference> consumer) { final PsiElement element = queryParameters.getElementToSearch(); ApplicationManager.getApplication().runReadAction(() -> { SearchScope scope = queryParameters.getEffectiveSearchScope(); if (!scenarioStateProvider.isJGivenScenarioState(element) || !(scope instanceof GlobalSearchScope)) { return; } PsiField field = (PsiField) element; scenarioStateReferenceProvider.findReferences(field).forEach(consumer::process); }); }
@Test public void should_add_reference() throws Exception { PsiField field = mock(PsiField.class); StateReferenceProcessor processor = referenceProcessorFor(2); PsiReference reference = mock(PsiReference.class); when(usageProvider.createReferenceIfJGivenUsage(fieldToSearch, field)).thenReturn(reference); boolean result = processor.process(field); assertThat(processor.getResults()).containsOnly(reference); assertThat(result).isTrue(); }
@Test public void should_return_false_if_enough_results_have_been_read() throws Exception { PsiField field1 = mock(PsiField.class); PsiReference reference1 = mock(PsiReference.class); when(usageProvider.createReferenceIfJGivenUsage(fieldToSearch, field1)).thenReturn(reference1); StateReferenceProcessor processor = referenceProcessorFor(1); boolean result = processor.process(field1); assertThat(result).isFalse(); }