Search in sources :

Example 26 with Pair

use of com.intellij.openapi.util.Pair in project intellij-community by JetBrains.

the class DeclarationConflictChecker method findDefinitions.

/**
   * For each reference in the collection, finds a definition of name visible from the point of the reference. Returns a list of
   * such definitions.
   * @param name what to look for.
   * @param references references to check.
   * @param ignored if an element defining the name is also listed here, ignore it.
   * @return a list of pairs (referring element, element that defines name).
   */
@NotNull
public static List<Pair<PsiElement, PsiElement>> findDefinitions(@NotNull String name, @NotNull Collection<PsiReference> references, @NotNull Set<PsiElement> ignored) {
    final List<Pair<PsiElement, PsiElement>> conflicts = new ArrayList<>();
    for (PsiReference ref : references) {
        final PsiElement refElement = ref.getElement();
        final ScopeOwner owner = ScopeUtil.getScopeOwner(refElement);
        if (owner != null) {
            for (PsiElement element : PyResolveUtil.resolveLocally(owner, name)) {
                if (!ignored.contains(element)) {
                    conflicts.add(Pair.create(refElement, element));
                }
            }
        }
    }
    return conflicts;
}
Also used : ScopeOwner(com.jetbrains.python.codeInsight.controlflow.ScopeOwner) ArrayList(java.util.ArrayList) PsiReference(com.intellij.psi.PsiReference) PsiElement(com.intellij.psi.PsiElement) Pair(com.intellij.openapi.util.Pair) NotNull(org.jetbrains.annotations.NotNull)

Example 27 with Pair

use of com.intellij.openapi.util.Pair 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 28 with Pair

use of com.intellij.openapi.util.Pair in project intellij-community by JetBrains.

the class XmlUnwrapDescriptor method collectUnwrappers.

@Override
public List<Pair<PsiElement, Unwrapper>> collectUnwrappers(Project project, Editor editor, PsiFile file) {
    int offset = editor.getCaretModel().getOffset();
    PsiElement e1 = file.findElementAt(offset);
    if (e1 != null) {
        Language language = e1.getParent().getLanguage();
        if (language != file.getLanguage()) {
            UnwrapDescriptor unwrapDescriptor = LanguageUnwrappers.INSTANCE.forLanguage(language);
            if (unwrapDescriptor != null && !(unwrapDescriptor instanceof XmlUnwrapDescriptor)) {
                return unwrapDescriptor.collectUnwrappers(project, editor, file);
            }
        }
    }
    List<Pair<PsiElement, Unwrapper>> result = new ArrayList<>();
    FileViewProvider viewProvider = file.getViewProvider();
    for (Language language : viewProvider.getLanguages()) {
        UnwrapDescriptor unwrapDescriptor = LanguageUnwrappers.INSTANCE.forLanguage(language);
        if (unwrapDescriptor instanceof XmlUnwrapDescriptor) {
            PsiElement e = viewProvider.findElementAt(offset, language);
            PsiElement tag = PsiTreeUtil.getParentOfType(e, XmlTag.class);
            while (tag != null) {
                if (XmlChildRole.START_TAG_NAME_FINDER.findChild(tag.getNode()) != null) {
                    // Exclude implicit tags suck as 'jsp:root'
                    result.add(new Pair<>(tag, new XmlEnclosingTagUnwrapper()));
                }
                tag = PsiTreeUtil.getParentOfType(tag, XmlTag.class);
            }
        }
    }
    Collections.sort(result, (o1, o2) -> o2.first.getTextOffset() - o1.first.getTextOffset());
    return result;
}
Also used : Language(com.intellij.lang.Language) FileViewProvider(com.intellij.psi.FileViewProvider) ArrayList(java.util.ArrayList) PsiElement(com.intellij.psi.PsiElement) UnwrapDescriptor(com.intellij.codeInsight.unwrap.UnwrapDescriptor) Pair(com.intellij.openapi.util.Pair) XmlTag(com.intellij.psi.xml.XmlTag)

Example 29 with Pair

use of com.intellij.openapi.util.Pair in project intellij-community by JetBrains.

the class MethodOrClosureScopeChooser method create.

/**
   * @param callback is invoked if any scope was chosen. The first arg is this scope and the second arg is a psielement to search for (super method of chosen method or
   *                 variable if the scope is a closure)
   */
public static JBPopup create(List<? extends GrParametersOwner> scopes, final Editor editor, final JBPopupOwner popupRef, final PairFunction<GrParametersOwner, PsiElement, Object> callback) {
    final JPanel panel = new JPanel(new BorderLayout());
    final JCheckBox superMethod = new JCheckBox(USE_SUPER_METHOD_OF, true);
    superMethod.setMnemonic('U');
    panel.add(superMethod, BorderLayout.SOUTH);
    final JBList list = new JBList(scopes.toArray());
    list.setVisibleRowCount(5);
    list.setCellRenderer(new DefaultListCellRenderer() {

        @Override
        public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
            super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
            final String text;
            if (value instanceof PsiMethod) {
                final PsiMethod method = (PsiMethod) value;
                text = PsiFormatUtil.formatMethod(method, PsiSubstitutor.EMPTY, PsiFormatUtilBase.SHOW_CONTAINING_CLASS | PsiFormatUtilBase.SHOW_NAME | PsiFormatUtilBase.SHOW_PARAMETERS, PsiFormatUtilBase.SHOW_TYPE);
                final int flags = Iconable.ICON_FLAG_VISIBILITY;
                final Icon icon = method.getIcon(flags);
                if (icon != null)
                    setIcon(icon);
            } else {
                LOG.assertTrue(value instanceof GrClosableBlock);
                setIcon(JetgroovyIcons.Groovy.Groovy_16x16);
                text = "{...}";
            }
            setText(text);
            return this;
        }
    });
    list.getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    list.setSelectedIndex(0);
    final List<RangeHighlighter> highlighters = new ArrayList<>();
    final TextAttributes attributes = EditorColorsManager.getInstance().getGlobalScheme().getAttributes(EditorColors.SEARCH_RESULT_ATTRIBUTES);
    list.addListSelectionListener(new ListSelectionListener() {

        @Override
        public void valueChanged(final ListSelectionEvent e) {
            final GrParametersOwner selectedMethod = (GrParametersOwner) list.getSelectedValue();
            if (selectedMethod == null)
                return;
            dropHighlighters(highlighters);
            updateView(selectedMethod, editor, attributes, highlighters, superMethod);
        }
    });
    updateView(scopes.get(0), editor, attributes, highlighters, superMethod);
    final JScrollPane scrollPane = ScrollPaneFactory.createScrollPane(list);
    scrollPane.setBorder(null);
    panel.add(scrollPane, BorderLayout.CENTER);
    final List<Pair<ActionListener, KeyStroke>> keyboardActions = Collections.singletonList(Pair.<ActionListener, KeyStroke>create(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            final GrParametersOwner ToSearchIn = (GrParametersOwner) list.getSelectedValue();
            final JBPopup popup = popupRef.get();
            if (popup != null && popup.isVisible()) {
                popup.cancel();
            }
            final PsiElement toSearchFor;
            if (ToSearchIn instanceof GrMethod) {
                final GrMethod method = (GrMethod) ToSearchIn;
                toSearchFor = superMethod.isEnabled() && superMethod.isSelected() ? method.findDeepestSuperMethod() : method;
            } else {
                toSearchFor = superMethod.isEnabled() && superMethod.isSelected() ? ToSearchIn.getParent() : null;
            }
            IdeFocusManager.findInstance().doWhenFocusSettlesDown(() -> callback.fun(ToSearchIn, toSearchFor), ModalityState.current());
        }
    }, KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0)));
    return JBPopupFactory.getInstance().createComponentPopupBuilder(panel, list).setTitle("Introduce parameter to").setMovable(false).setResizable(false).setRequestFocus(true).setKeyboardActions(keyboardActions).addListener(new JBPopupAdapter() {

        @Override
        public void onClosed(LightweightWindowEvent event) {
            dropHighlighters(highlighters);
        }
    }).createPopup();
}
Also used : PsiMethod(com.intellij.psi.PsiMethod) GrParametersOwner(org.jetbrains.plugins.groovy.lang.psi.api.statements.GrParametersOwner) ActionEvent(java.awt.event.ActionEvent) ArrayList(java.util.ArrayList) ListSelectionEvent(javax.swing.event.ListSelectionEvent) LightweightWindowEvent(com.intellij.openapi.ui.popup.LightweightWindowEvent) JBPopup(com.intellij.openapi.ui.popup.JBPopup) PsiElement(com.intellij.psi.PsiElement) Pair(com.intellij.openapi.util.Pair) GrMethod(org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod) GrClosableBlock(org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock) ListSelectionListener(javax.swing.event.ListSelectionListener) ActionListener(java.awt.event.ActionListener) JBPopupAdapter(com.intellij.openapi.ui.popup.JBPopupAdapter) JBList(com.intellij.ui.components.JBList)

Example 30 with Pair

use of com.intellij.openapi.util.Pair in project intellij-community by JetBrains.

the class PyUnusedLocalInspectionVisitor method visitPyStringLiteralExpression.

@Override
public void visitPyStringLiteralExpression(PyStringLiteralExpression pyString) {
    final ScopeOwner owner = ScopeUtil.getScopeOwner(pyString);
    if (owner != null && !(owner instanceof PsiFile)) {
        final PyStatement instrAnchor = PsiTreeUtil.getParentOfType(pyString, PyStatement.class);
        if (instrAnchor == null)
            return;
        final Instruction[] instructions = ControlFlowCache.getControlFlow(owner).getInstructions();
        final int startInstruction = ControlFlowUtil.findInstructionNumberByElement(instructions, instrAnchor);
        if (startInstruction < 0)
            return;
        final Project project = pyString.getProject();
        final List<Pair<PsiElement, TextRange>> pairs = InjectedLanguageManager.getInstance(project).getInjectedPsiFiles(pyString);
        if (pairs != null) {
            for (Pair<PsiElement, TextRange> pair : pairs) {
                pair.getFirst().accept(new PyRecursiveElementVisitor() {

                    @Override
                    public void visitPyReferenceExpression(PyReferenceExpression expr) {
                        final PyExpression qualifier = expr.getQualifier();
                        if (qualifier != null) {
                            qualifier.accept(this);
                            return;
                        }
                        final String name = expr.getName();
                        if (name != null) {
                            analyzeReadsInScope(name, owner, instructions, startInstruction, pyString);
                        }
                    }
                });
            }
        }
    }
}
Also used : TextRange(com.intellij.openapi.util.TextRange) ReadWriteInstruction(com.jetbrains.python.codeInsight.controlflow.ReadWriteInstruction) Instruction(com.intellij.codeInsight.controlflow.Instruction) Project(com.intellij.openapi.project.Project) ScopeOwner(com.jetbrains.python.codeInsight.controlflow.ScopeOwner) PsiFile(com.intellij.psi.PsiFile) PsiElement(com.intellij.psi.PsiElement) Pair(com.intellij.openapi.util.Pair)

Aggregations

Pair (com.intellij.openapi.util.Pair)391 NotNull (org.jetbrains.annotations.NotNull)131 ArrayList (java.util.ArrayList)83 VirtualFile (com.intellij.openapi.vfs.VirtualFile)68 Project (com.intellij.openapi.project.Project)60 Nullable (org.jetbrains.annotations.Nullable)59 PsiElement (com.intellij.psi.PsiElement)47 TextRange (com.intellij.openapi.util.TextRange)43 File (java.io.File)42 List (java.util.List)37 Module (com.intellij.openapi.module.Module)34 ContainerUtil (com.intellij.util.containers.ContainerUtil)26 PsiFile (com.intellij.psi.PsiFile)25 StringUtil (com.intellij.openapi.util.text.StringUtil)20 IOException (java.io.IOException)19 java.util (java.util)19 ApplicationManager (com.intellij.openapi.application.ApplicationManager)18 THashSet (gnu.trove.THashSet)17 Map (java.util.Map)17 Document (com.intellij.openapi.editor.Document)15