Search in sources :

Example 41 with PsiReference

use of com.intellij.psi.PsiReference in project intellij-community by JetBrains.

the class ImportToggleAliasIntention method doInvoke.

@Override
public void doInvoke(@NotNull final Project project, Editor editor, PsiFile file) throws IncorrectOperationException {
    // sanity check: isAvailable must have set it.
    final IntentionState state = IntentionState.fromContext(editor, file);
    //
    // we set in in the source
    final String target_name;
    // we replace it in the source
    final String remove_name;
    PyReferenceExpression reference = sure(state.myImportElement.getImportReferenceExpression());
    // search for references to us with the right name
    try {
        String imported_name = PyPsiUtils.toPath(reference);
        if (state.myAlias != null) {
            // have to remove alias, rename everything to original
            target_name = imported_name;
            remove_name = state.myAlias;
        } else {
            // ask for and add alias
            Application application = ApplicationManager.getApplication();
            if (application != null && !application.isUnitTestMode()) {
                String alias = Messages.showInputDialog(project, PyBundle.message("INTN.alias.for.$0.dialog.title", imported_name), "Add Alias", Messages.getQuestionIcon(), "", new InputValidator() {

                    @Override
                    public boolean checkInput(String inputString) {
                        return PyNames.isIdentifier(inputString);
                    }

                    @Override
                    public boolean canClose(String inputString) {
                        return PyNames.isIdentifier(inputString);
                    }
                });
                if (alias == null) {
                    return;
                }
                target_name = alias;
            } else {
                // test mode
                target_name = "alias";
            }
            remove_name = imported_name;
        }
        final PsiElement referee = reference.getReference().resolve();
        if (referee != null && imported_name != null) {
            final Collection<PsiReference> references = new ArrayList<>();
            final ScopeOwner scope = PsiTreeUtil.getParentOfType(state.myImportElement, ScopeOwner.class);
            PsiTreeUtil.processElements(scope, new PsiElementProcessor() {

                public boolean execute(@NotNull PsiElement element) {
                    getReferences(element);
                    if (element instanceof PyStringLiteralExpression) {
                        final PsiLanguageInjectionHost host = (PsiLanguageInjectionHost) element;
                        final List<Pair<PsiElement, TextRange>> files = InjectedLanguageManager.getInstance(project).getInjectedPsiFiles(host);
                        if (files != null) {
                            for (Pair<PsiElement, TextRange> pair : files) {
                                final PsiElement first = pair.getFirst();
                                if (first instanceof ScopeOwner) {
                                    final ScopeOwner scopeOwner = (ScopeOwner) first;
                                    PsiTreeUtil.processElements(scopeOwner, new PsiElementProcessor() {

                                        public boolean execute(@NotNull PsiElement element) {
                                            getReferences(element);
                                            return true;
                                        }
                                    });
                                }
                            }
                        }
                    }
                    return true;
                }

                private void getReferences(PsiElement element) {
                    if (element instanceof PyReferenceExpression && PsiTreeUtil.getParentOfType(element, PyImportElement.class) == null) {
                        PyReferenceExpression ref = (PyReferenceExpression) element;
                        if (remove_name.equals(PyPsiUtils.toPath(ref))) {
                            // filter out other names that might resolve to our target
                            PsiElement resolved = ref.getReference().resolve();
                            if (resolved == referee)
                                references.add(ref.getReference());
                        }
                    }
                }
            });
            // no references here is OK by us.
            if (showConflicts(project, findDefinitions(target_name, references, Collections.<PsiElement>emptySet()), target_name, null)) {
                // got conflicts
                return;
            }
            // alter the import element
            PyElementGenerator generator = PyElementGenerator.getInstance(project);
            final LanguageLevel languageLevel = LanguageLevel.forElement(state.myImportElement);
            if (state.myAlias != null) {
                // remove alias
                ASTNode node = sure(state.myImportElement.getNode());
                ASTNode parent = sure(node.getTreeParent());
                // this is the reference
                node = sure(node.getFirstChildNode());
                // things past the reference: space, 'as', and alias
                node = sure(node.getTreeNext());
                parent.removeRange(node, null);
            } else {
                // add alias
                ASTNode my_ielt_node = sure(state.myImportElement.getNode());
                PyImportElement fountain = generator.createFromText(languageLevel, PyImportElement.class, "import foo as " + target_name, new int[] { 0, 2 });
                // at import elt
                ASTNode graft_node = sure(fountain.getNode());
                // at ref
                graft_node = sure(graft_node.getFirstChildNode());
                // space
                graft_node = sure(graft_node.getTreeNext());
                my_ielt_node.addChild((ASTNode) graft_node.clone());
                // 'as'
                graft_node = sure(graft_node.getTreeNext());
                my_ielt_node.addChild((ASTNode) graft_node.clone());
                // space
                graft_node = sure(graft_node.getTreeNext());
                my_ielt_node.addChild((ASTNode) graft_node.clone());
                // alias
                graft_node = sure(graft_node.getTreeNext());
                my_ielt_node.addChild((ASTNode) graft_node.clone());
            }
            // alter references
            for (PsiReference ref : references) {
                ASTNode ref_name_node = sure(sure(ref.getElement()).getNode());
                ASTNode parent = sure(ref_name_node.getTreeParent());
                ASTNode new_name_node = generator.createExpressionFromText(languageLevel, target_name).getNode();
                assert new_name_node != null;
                parent.replaceChild(ref_name_node, new_name_node);
            }
        }
    } catch (IncorrectOperationException ignored) {
        PyUtil.showBalloon(project, PyBundle.message("QFIX.action.failed"), MessageType.WARNING);
    }
}
Also used : ArrayList(java.util.ArrayList) PsiReference(com.intellij.psi.PsiReference) TextRange(com.intellij.openapi.util.TextRange) NotNull(org.jetbrains.annotations.NotNull) PsiElementProcessor(com.intellij.psi.search.PsiElementProcessor) ScopeOwner(com.jetbrains.python.codeInsight.controlflow.ScopeOwner) InputValidator(com.intellij.openapi.ui.InputValidator) PsiLanguageInjectionHost(com.intellij.psi.PsiLanguageInjectionHost) ASTNode(com.intellij.lang.ASTNode) ArrayList(java.util.ArrayList) List(java.util.List) IncorrectOperationException(com.intellij.util.IncorrectOperationException) Application(com.intellij.openapi.application.Application) PsiElement(com.intellij.psi.PsiElement) Pair(com.intellij.openapi.util.Pair)

Example 42 with PsiReference

use of com.intellij.psi.PsiReference in project intellij-community by JetBrains.

the class GrIntroduceLocalVariableProcessor method resolveLocalConflicts.

private static void resolveLocalConflicts(@NotNull PsiElement tempContainer, @NotNull String varName) {
    for (PsiElement child : tempContainer.getChildren()) {
        if (child instanceof GrReferenceExpression && !child.getText().contains(".")) {
            PsiReference psiReference = child.getReference();
            if (psiReference != null) {
                final PsiElement resolved = psiReference.resolve();
                if (resolved != null) {
                    String fieldName = getFieldName(resolved);
                    if (fieldName != null && varName.equals(fieldName)) {
                        GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(tempContainer.getProject());
                        ((GrReferenceExpression) child).replaceWithExpression(factory.createExpressionFromText("this." + child.getText()), true);
                    }
                }
            }
        } else {
            resolveLocalConflicts(child, varName);
        }
    }
}
Also used : GroovyPsiElementFactory(org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory) PsiReference(com.intellij.psi.PsiReference) PsiElement(com.intellij.psi.PsiElement) GrReferenceExpression(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression)

Example 43 with PsiReference

use of com.intellij.psi.PsiReference in project intellij-community by JetBrains.

the class XmlLocationCompletionContributor method fillCompletionVariants.

@Override
public void fillCompletionVariants(@NotNull CompletionParameters parameters, @NotNull CompletionResultSet result) {
    PsiReference reference = parameters.getPosition().getContainingFile().findReferenceAt(parameters.getOffset());
    if (reference instanceof URLReference) {
        if (((URLReference) reference).isSchemaLocation()) {
            Object[] objects = completeSchemaLocation(reference.getElement());
            result.addAllElements(ContainerUtil.map(objects, MAPPING));
            return;
        }
        Object[] objects = completeNamespace(reference.getElement());
        result.addAllElements(ContainerUtil.map(objects, MAPPING));
        return;
    }
    if (reference instanceof PsiMultiReference)
        reference = ((PsiMultiReference) reference).getReferences()[0];
    if (reference instanceof DependentNSReference) {
        MultiMap<String, String> map = ExternalResourceManagerEx.getInstanceEx().getUrlsByNamespace(parameters.getOriginalFile().getProject());
        String namespace = ((DependentNSReference) reference).getNamespaceReference().getCanonicalText();
        Collection<String> strings = map.get(namespace);
        for (String string : strings) {
            if (!namespace.equals(string)) {
                // exclude namespaces from location urls
                result.consume(PrioritizedLookupElement.withPriority(LookupElementBuilder.create(string), 100));
            }
        }
        if (!strings.isEmpty())
            result.stopHere();
    }
}
Also used : DependentNSReference(com.intellij.psi.impl.source.resolve.reference.impl.providers.DependentNSReference) URLReference(com.intellij.psi.impl.source.resolve.reference.impl.providers.URLReference) PsiReference(com.intellij.psi.PsiReference) PsiMultiReference(com.intellij.psi.impl.source.resolve.reference.impl.PsiMultiReference)

Example 44 with PsiReference

use of com.intellij.psi.PsiReference in project intellij-community by JetBrains.

the class SchemaReferencesProvider method getReferencesByElement.

@Override
@NotNull
public PsiReference[] getReferencesByElement(@NotNull PsiElement element, @NotNull final ProcessingContext context) {
    final PsiElement parent = element.getParent();
    if (!(parent instanceof XmlAttribute))
        return PsiReference.EMPTY_ARRAY;
    final String attrName = ((XmlAttribute) parent).getName();
    if (VALUE_ATTR_NAME.equals(attrName)) {
        return PsiReference.EMPTY_ARRAY;
    } else if (NAME_ATTR_NAME.equals(attrName)) {
        return new PsiReference[] { new NameReference(element) };
    } else if (MEMBER_TYPES_ATTR_NAME.equals(attrName)) {
        final List<PsiReference> result = new ArrayList<>(1);
        final String text = element.getText();
        int lastIndex = 1;
        final int testLength = text.length();
        for (int i = 1; i < testLength; ++i) {
            if (Character.isWhitespace(text.charAt(i))) {
                if (lastIndex != i)
                    result.add(new TypeOrElementOrAttributeReference(element, new TextRange(lastIndex, i)));
                lastIndex = i + 1;
            }
        }
        if (lastIndex != testLength - 1)
            result.add(new TypeOrElementOrAttributeReference(element, new TextRange(lastIndex, testLength - 1)));
        return result.toArray(new PsiReference[result.size()]);
    } else {
        final PsiReference prefix = createSchemaPrefixReference(element);
        final PsiReference ref = createTypeOrElementOrAttributeReference(element, prefix == null ? null : prefix.getCanonicalText());
        return prefix == null ? new PsiReference[] { ref } : new PsiReference[] { ref, prefix };
    }
}
Also used : XmlAttribute(com.intellij.psi.xml.XmlAttribute) ArrayList(java.util.ArrayList) PsiReference(com.intellij.psi.PsiReference) TextRange(com.intellij.openapi.util.TextRange) PsiElement(com.intellij.psi.PsiElement) NotNull(org.jetbrains.annotations.NotNull)

Example 45 with PsiReference

use of com.intellij.psi.PsiReference in project intellij-community by JetBrains.

the class MicrodataUtil method getReferencesForAttributeValue.

public static PsiReference[] getReferencesForAttributeValue(@Nullable XmlAttributeValue element, PairFunction<String, Integer, PsiReference> refFun) {
    if (element == null) {
        return PsiReference.EMPTY_ARRAY;
    }
    String text = element.getText();
    String urls = StringUtil.unquoteString(text);
    StringTokenizer tokenizer = new StringTokenizer(urls);
    List<PsiReference> result = new ArrayList<>();
    while (tokenizer.hasMoreTokens()) {
        String token = tokenizer.nextToken();
        int index = text.indexOf(token);
        PsiReference ref = refFun.fun(token, index);
        if (ref != null) {
            result.add(ref);
        }
    }
    return result.toArray(new PsiReference[result.size()]);
}
Also used : StringTokenizer(com.intellij.util.text.StringTokenizer) PsiReference(com.intellij.psi.PsiReference)

Aggregations

PsiReference (com.intellij.psi.PsiReference)564 PsiElement (com.intellij.psi.PsiElement)327 NotNull (org.jetbrains.annotations.NotNull)97 Nullable (org.jetbrains.annotations.Nullable)55 TextRange (com.intellij.openapi.util.TextRange)54 PsiFile (com.intellij.psi.PsiFile)52 ArrayList (java.util.ArrayList)46 Test (org.junit.Test)40 WorkspacePath (com.google.idea.blaze.base.model.primitives.WorkspacePath)36 BuildFile (com.google.idea.blaze.base.lang.buildfile.psi.BuildFile)32 IdentifierPSINode (org.ballerinalang.plugins.idea.psi.IdentifierPSINode)25 LeafPsiElement (com.intellij.psi.impl.source.tree.LeafPsiElement)23 XmlTag (com.intellij.psi.xml.XmlTag)22 VirtualFile (com.intellij.openapi.vfs.VirtualFile)21 XmlAttributeValue (com.intellij.psi.xml.XmlAttributeValue)20 PsiClass (com.intellij.psi.PsiClass)17 XmlAttribute (com.intellij.psi.xml.XmlAttribute)17 LinkedList (java.util.LinkedList)17 LookupElement (com.intellij.codeInsight.lookup.LookupElement)16 Project (com.intellij.openapi.project.Project)16