Search in sources :

Example 11 with GrMethod

use of org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod in project intellij-community by JetBrains.

the class GrPullUpConflictsUtil method checkConflicts.

public static MultiMap<PsiElement, String> checkConflicts(final MemberInfoBase<? extends GrMember>[] infos, @NotNull final PsiClass subclass, @Nullable PsiClass superClass, @NotNull final PsiPackage targetPackage, @NotNull PsiDirectory targetDirectory, final InterfaceContainmentVerifier interfaceContainmentVerifier, boolean movedMembers2Super) {
    final PsiElement targetRepresentativeElement;
    final boolean isInterfaceTarget;
    if (superClass != null) {
        isInterfaceTarget = superClass.isInterface();
        targetRepresentativeElement = superClass;
    } else {
        isInterfaceTarget = false;
        targetRepresentativeElement = targetDirectory;
    }
    final Set<GrMember> movedMembers = ContainerUtil.newHashSet();
    final Set<GrMethod> abstractMethods = ContainerUtil.newHashSet();
    for (MemberInfoBase<? extends GrMember> info : infos) {
        GrMember member = info.getMember();
        if (member instanceof GrMethod) {
            if (!info.isToAbstract() && !isInterfaceTarget) {
                movedMembers.add(member);
            } else {
                abstractMethods.add((GrMethod) member);
            }
        } else {
            movedMembers.add(member);
        }
    }
    final Set<PsiMethod> allAbstractMethods = new HashSet<>(abstractMethods);
    if (superClass != null) {
        for (PsiMethod method : subclass.getMethods()) {
            if (!movedMembers.contains(method) && !method.hasModifierProperty(PsiModifier.PRIVATE)) {
                if (method.findSuperMethods(superClass).length > 0) {
                    allAbstractMethods.add(method);
                }
            }
        }
    }
    final MultiMap<PsiElement, String> conflicts = new MultiMap<>();
    GrRefactoringConflictsUtil.analyzeAccessibilityConflicts(movedMembers, superClass, conflicts, VisibilityUtil.ESCALATE_VISIBILITY, targetRepresentativeElement, allAbstractMethods);
    if (superClass != null) {
        if (movedMembers2Super) {
            checkSuperclassMembers(superClass, infos, conflicts);
            if (isInterfaceTarget) {
                checkInterfaceTarget(infos, conflicts);
            }
        } else {
            final String qualifiedName = superClass.getQualifiedName();
            assert qualifiedName != null;
            if (superClass.hasModifierProperty(PsiModifier.PACKAGE_LOCAL)) {
                if (!Comparing.strEqual(StringUtil.getPackageName(qualifiedName), targetPackage.getQualifiedName())) {
                    conflicts.putValue(superClass, RefactoringUIUtil.getDescription(superClass, true) + " won't be accessible from " + RefactoringUIUtil.getDescription(targetPackage, true));
                }
            }
        }
    }
    // check if moved methods use other members in the classes between Subclass and Superclass
    List<PsiElement> checkModuleConflictsList = new ArrayList<>();
    for (PsiMember member : movedMembers) {
        if (member instanceof PsiMethod || member instanceof PsiClass && !(member instanceof PsiCompiledElement)) {
            GrClassMemberReferenceVisitor visitor = movedMembers2Super ? new ConflictingUsagesOfSubClassMembers(member, movedMembers, abstractMethods, subclass, superClass, superClass != null ? null : targetPackage, conflicts, interfaceContainmentVerifier) : new ConflictingUsagesOfSuperClassMembers(member, subclass, targetPackage, movedMembers, conflicts);
            ((GroovyPsiElement) member).accept(visitor);
        }
        checkModuleConflictsList.add(member);
    }
    for (final PsiMethod method : abstractMethods) {
        ContainerUtil.addIfNotNull(checkModuleConflictsList, method.getParameterList());
        ContainerUtil.addIfNotNull(checkModuleConflictsList, method.getReturnTypeElement());
        ContainerUtil.addIfNotNull(checkModuleConflictsList, method.getTypeParameterList());
    }
    GrRefactoringConflictsUtil.analyzeModuleConflicts(subclass.getProject(), checkModuleConflictsList, UsageInfo.EMPTY_ARRAY, targetRepresentativeElement, conflicts);
    final String fqName = subclass.getQualifiedName();
    final String packageName;
    if (fqName != null) {
        packageName = StringUtil.getPackageName(fqName);
    } else {
        final PsiFile psiFile = PsiTreeUtil.getParentOfType(subclass, PsiFile.class);
        if (psiFile instanceof PsiClassOwner) {
            packageName = ((PsiClassOwner) psiFile).getPackageName();
        } else {
            packageName = null;
        }
    }
    final boolean toDifferentPackage = !Comparing.strEqual(targetPackage.getQualifiedName(), packageName);
    for (final GrMethod abstractMethod : abstractMethods) {
        abstractMethod.accept(new GrClassMemberReferenceVisitor(subclass) {

            @Override
            protected void visitClassMemberReferenceElement(GrMember classMember, GrReferenceElement classMemberReference) {
                if (classMember != null && willBeMoved(classMember, movedMembers)) {
                    boolean isAccessible = false;
                    if (classMember.hasModifierProperty(PsiModifier.PRIVATE)) {
                        isAccessible = true;
                    } else if (classMember.hasModifierProperty(PsiModifier.PACKAGE_LOCAL) && toDifferentPackage) {
                        isAccessible = true;
                    }
                    if (isAccessible) {
                        String message = RefactoringUIUtil.getDescription(abstractMethod, false) + " uses " + RefactoringUIUtil.getDescription(classMember, true) + " which won't be accessible from the subclass.";
                        message = CommonRefactoringUtil.capitalize(message);
                        conflicts.putValue(classMember, message);
                    }
                }
            }
        });
        if (abstractMethod.hasModifierProperty(PsiModifier.PACKAGE_LOCAL) && toDifferentPackage) {
            if (!isInterfaceTarget) {
                String message = "Can't make " + RefactoringUIUtil.getDescription(abstractMethod, false) + " abstract as it won't be accessible from the subclass.";
                message = CommonRefactoringUtil.capitalize(message);
                conflicts.putValue(abstractMethod, message);
            }
        }
    }
    return conflicts;
}
Also used : GrClassMemberReferenceVisitor(org.jetbrains.plugins.groovy.refactoring.classMembers.GrClassMemberReferenceVisitor) ArrayList(java.util.ArrayList) MultiMap(com.intellij.util.containers.MultiMap) GroovyPsiElement(org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElement) GrReferenceElement(org.jetbrains.plugins.groovy.lang.psi.GrReferenceElement) HashSet(java.util.HashSet) GroovyPsiElement(org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElement) GrMember(org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMember) GrMethod(org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod)

Example 12 with GrMethod

use of org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod in project intellij-community by JetBrains.

the class GrPullUpHandler method invoke.

@Override
public void invoke(@NotNull final Project project, @NotNull PsiElement[] elements, DataContext dataContext) {
    if (elements.length != 1)
        return;
    myProject = project;
    PsiElement element = elements[0];
    GrTypeDefinition aClass;
    PsiElement aMember = null;
    if (element instanceof GrTypeDefinition) {
        aClass = (GrTypeDefinition) element;
    } else if (element instanceof GrMethod) {
        aClass = DefaultGroovyMethods.asType(((GrMethod) element).getContainingClass(), GrTypeDefinition.class);
        aMember = element;
    } else if (element instanceof GrField) {
        aClass = DefaultGroovyMethods.asType(((GrField) element).getContainingClass(), GrTypeDefinition.class);
        aMember = element;
    } else {
        return;
    }
    invokeImpl(project, dataContext, aClass, aMember);
}
Also used : GrField(org.jetbrains.plugins.groovy.lang.psi.api.statements.GrField) GrTypeDefinition(org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrTypeDefinition) GrMethod(org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod)

Example 13 with GrMethod

use of org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod 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 14 with GrMethod

use of org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod in project intellij-community by JetBrains.

the class GrIntroduceParameterDialog method doOKAction.

@Override
public void doOKAction() {
    saveSettings();
    super.doOKAction();
    final GrParametersOwner toReplaceIn = myInfo.getToReplaceIn();
    final GrExpression expr = GroovyIntroduceParameterUtil.findExpr(myInfo);
    final GrVariable var = GroovyIntroduceParameterUtil.findVar(myInfo);
    final StringPartInfo stringPart = findStringPart();
    if (myTypeComboBox.isClosureSelected() || expr == null && var == null && stringPart == null) {
        GrIntroduceParameterSettings settings = new ExtractClosureHelperImpl(myInfo, getEnteredName(), myDeclareFinalCheckBox.isSelected(), getParametersToRemove(), myDelegateViaOverloadingMethodCheckBox.isSelected(), getReplaceFieldsWithGetter(), myForceReturnCheckBox.isSelected(), false, myTypeComboBox.getSelectedType() == null);
        if (toReplaceIn instanceof GrMethod) {
            invokeRefactoring(new ExtractClosureFromMethodProcessor(settings));
        } else {
            invokeRefactoring(new ExtractClosureFromClosureProcessor(settings));
        }
    } else {
        GrIntroduceParameterSettings settings = new GrIntroduceExpressionSettingsImpl(myInfo, getEnteredName(), myDeclareFinalCheckBox.isSelected(), getParametersToRemove(), myDelegateViaOverloadingMethodCheckBox.isSelected(), getReplaceFieldsWithGetter(), expr, var, myTypeComboBox.getSelectedType(), var != null, true, myForceReturnCheckBox.isSelected());
        if (toReplaceIn instanceof GrMethod) {
            invokeRefactoring(new GrIntroduceParameterProcessor(settings));
        } else {
            invokeRefactoring(new GrIntroduceClosureParameterProcessor(settings));
        }
    }
}
Also used : GrVariable(org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariable) ExtractClosureFromClosureProcessor(org.jetbrains.plugins.groovy.refactoring.extract.closure.ExtractClosureFromClosureProcessor) ExtractClosureFromMethodProcessor(org.jetbrains.plugins.groovy.refactoring.extract.closure.ExtractClosureFromMethodProcessor) GrParametersOwner(org.jetbrains.plugins.groovy.lang.psi.api.statements.GrParametersOwner) ExtractClosureHelperImpl(org.jetbrains.plugins.groovy.refactoring.extract.closure.ExtractClosureHelperImpl) GrMethod(org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod) GrExpression(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression) StringPartInfo(org.jetbrains.plugins.groovy.refactoring.introduce.StringPartInfo)

Example 15 with GrMethod

use of org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod in project intellij-community by JetBrains.

the class GrIntroduceParameterProcessor method createExpressionWrapper.

private static GrExpressionWrapper createExpressionWrapper(GrIntroduceParameterSettings settings) {
    LOG.assertTrue(settings.getToReplaceIn() instanceof GrMethod);
    LOG.assertTrue(settings.getToSearchFor() instanceof PsiMethod);
    final StringPartInfo stringPartInfo = settings.getStringPartInfo();
    GrVariable var = settings.getVar();
    final GrExpression expression = stringPartInfo != null ? stringPartInfo.createLiteralFromSelected() : var != null ? var.getInitializerGroovy() : settings.getExpression();
    return new GrExpressionWrapper(expression);
}
Also used : GrVariable(org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariable) GrMethod(org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod) GrExpression(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression) StringPartInfo(org.jetbrains.plugins.groovy.refactoring.introduce.StringPartInfo)

Aggregations

GrMethod (org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod)134 GrOpenBlock (org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrOpenBlock)24 PsiElement (com.intellij.psi.PsiElement)22 NotNull (org.jetbrains.annotations.NotNull)21 GroovyPsiElementFactory (org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory)19 GroovyPsiElement (org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElement)18 GrParameter (org.jetbrains.plugins.groovy.lang.psi.api.statements.params.GrParameter)17 GrField (org.jetbrains.plugins.groovy.lang.psi.api.statements.GrField)16 GrClosableBlock (org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock)16 ArrayList (java.util.ArrayList)15 GrTypeDefinition (org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrTypeDefinition)15 Nullable (org.jetbrains.annotations.Nullable)12 GrStatement (org.jetbrains.plugins.groovy.lang.psi.api.statements.GrStatement)12 GrExpression (org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression)12 GrReferenceExpression (org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression)12 IncorrectOperationException (com.intellij.util.IncorrectOperationException)10 GrCodeBlock (org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrCodeBlock)10 Project (com.intellij.openapi.project.Project)9 GrVariable (org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariable)8 GrReturnStatement (org.jetbrains.plugins.groovy.lang.psi.api.statements.branch.GrReturnStatement)8