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;
}
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);
}
}
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;
}
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();
}
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);
}
}
});
}
}
}
}
Aggregations