Search in sources :

Example 6 with GrClosableBlock

use of org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock 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 7 with GrClosableBlock

use of org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock in project intellij-community by JetBrains.

the class GrIntroduceClosureParameterProcessor method findUsagesForLocal.

private static Collection<PsiReference> findUsagesForLocal(GrClosableBlock initializer, final GrVariable var) {
    final Instruction[] flow = ControlFlowUtils.findControlFlowOwner(initializer).getControlFlow();
    final List<BitSet> writes = ControlFlowUtils.inferWriteAccessMap(flow, var);
    Instruction writeInstr = null;
    final PsiElement parent = initializer.getParent();
    if (parent instanceof GrVariable) {
        writeInstr = ContainerUtil.find(flow, instruction -> instruction.getElement() == var);
    } else if (parent instanceof GrAssignmentExpression) {
        final GrReferenceExpression refExpr = (GrReferenceExpression) ((GrAssignmentExpression) parent).getLValue();
        final Instruction instruction = ContainerUtil.find(flow, instruction1 -> instruction1.getElement() == refExpr);
        LOG.assertTrue(instruction != null);
        final BitSet prev = writes.get(instruction.num());
        if (prev.cardinality() == 1) {
            writeInstr = flow[prev.nextSetBit(0)];
        }
    }
    LOG.assertTrue(writeInstr != null);
    Collection<PsiReference> result = new ArrayList<>();
    for (Instruction instruction : flow) {
        if (!(instruction instanceof ReadWriteVariableInstruction))
            continue;
        if (((ReadWriteVariableInstruction) instruction).isWrite())
            continue;
        final PsiElement element = instruction.getElement();
        if (element instanceof GrVariable && element != var)
            continue;
        if (!(element instanceof GrReferenceExpression))
            continue;
        final GrReferenceExpression ref = (GrReferenceExpression) element;
        if (ref.isQualified() || ref.resolve() != var)
            continue;
        final BitSet prev = writes.get(instruction.num());
        if (prev.cardinality() == 1 && prev.get(writeInstr.num())) {
            result.add(ref);
        }
    }
    return result;
}
Also used : IntroduceParameterRefactoring(com.intellij.refactoring.IntroduceParameterRefactoring) PsiImplUtil(org.jetbrains.plugins.groovy.lang.psi.impl.PsiImplUtil) GrClosableBlock(org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock) ExternalUsageInfo(com.intellij.refactoring.introduceParameter.ExternalUsageInfo) StringPartInfo(org.jetbrains.plugins.groovy.refactoring.introduce.StringPartInfo) GrArgumentList(org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrArgumentList) RefactoringBundle(com.intellij.refactoring.RefactoringBundle) BaseRefactoringProcessor(com.intellij.refactoring.BaseRefactoringProcessor) ControlFlowUtils(org.jetbrains.plugins.groovy.codeInspection.utils.ControlFlowUtils) PsiTreeUtil(com.intellij.psi.util.PsiTreeUtil) MethodReferencesSearch(com.intellij.psi.search.searches.MethodReferencesSearch) GrAccessorMethod(org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrAccessorMethod) Logger(com.intellij.openapi.diagnostic.Logger) MultiMap(com.intellij.util.containers.MultiMap) GrMethodCallExpression(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.path.GrMethodCallExpression) ReferencesSearch(com.intellij.psi.search.searches.ReferencesSearch) GrParameter(org.jetbrains.plugins.groovy.lang.psi.api.statements.params.GrParameter) IncorrectOperationException(com.intellij.util.IncorrectOperationException) GrClosureSignatureUtil(org.jetbrains.plugins.groovy.lang.psi.impl.signatures.GrClosureSignatureUtil) Collection(java.util.Collection) Nullable(org.jetbrains.annotations.Nullable) org.jetbrains.plugins.groovy.lang.psi.api.statements(org.jetbrains.plugins.groovy.lang.psi.api.statements) ReadWriteVariableInstruction(org.jetbrains.plugins.groovy.lang.psi.controlFlow.ReadWriteVariableInstruction) List(java.util.List) FieldConflictsResolver(org.jetbrains.plugins.groovy.refactoring.introduce.parameter.java2groovy.FieldConflictsResolver) GrMethod(org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod) com.intellij.psi(com.intellij.psi) NotNull(org.jetbrains.annotations.NotNull) Ref(com.intellij.openapi.util.Ref) PsiUtil(org.jetbrains.plugins.groovy.lang.psi.util.PsiUtil) GroovyRefactoringBundle(org.jetbrains.plugins.groovy.refactoring.GroovyRefactoringBundle) DescriptiveNameUtil(com.intellij.lang.findUsages.DescriptiveNameUtil) ChangedMethodCallInfo(com.intellij.refactoring.introduceParameter.ChangedMethodCallInfo) GrClosureSignature(org.jetbrains.plugins.groovy.lang.psi.api.signatures.GrClosureSignature) Instruction(org.jetbrains.plugins.groovy.lang.psi.controlFlow.Instruction) ArrayUtil(com.intellij.util.ArrayUtil) PsiUtilBase(com.intellij.psi.util.PsiUtilBase) GroovyLanguage(org.jetbrains.plugins.groovy.GroovyLanguage) ChangeContextUtil(com.intellij.codeInsight.ChangeContextUtil) UsageViewDescriptorAdapter(com.intellij.refactoring.ui.UsageViewDescriptorAdapter) UsageInfo(com.intellij.usageView.UsageInfo) GrStatementOwner(org.jetbrains.plugins.groovy.lang.psi.api.util.GrStatementOwner) ContainerUtil(com.intellij.util.containers.ContainerUtil) GrCodeBlock(org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrCodeBlock) AnySupers(org.jetbrains.plugins.groovy.refactoring.util.AnySupers) JavaCodeStyleManager(com.intellij.psi.codeStyle.JavaCodeStyleManager) ArrayList(java.util.ArrayList) OldReferencesResolver(org.jetbrains.plugins.groovy.refactoring.introduce.parameter.java2groovy.OldReferencesResolver) GroovyRefactoringUtil(org.jetbrains.plugins.groovy.refactoring.GroovyRefactoringUtil) GroovyPsiElementFactory(org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory) GrParameterList(org.jetbrains.plugins.groovy.lang.psi.api.statements.params.GrParameterList) InternalUsageInfo(com.intellij.refactoring.introduceParameter.InternalUsageInfo) Editor(com.intellij.openapi.editor.Editor) UsageViewUtil(com.intellij.usageView.UsageViewUtil) GroovyResolveResult(org.jetbrains.plugins.groovy.lang.psi.api.GroovyResolveResult) UsageViewDescriptor(com.intellij.usageView.UsageViewDescriptor) CommonRefactoringUtil(com.intellij.refactoring.util.CommonRefactoringUtil) CodeStyleManager(com.intellij.psi.codeStyle.CodeStyleManager) ExpressionConverter(com.intellij.psi.impl.ExpressionConverter) TIntProcedure(gnu.trove.TIntProcedure) org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions) BitSet(java.util.BitSet) ReadWriteVariableInstruction(org.jetbrains.plugins.groovy.lang.psi.controlFlow.ReadWriteVariableInstruction) BitSet(java.util.BitSet) ArrayList(java.util.ArrayList) ReadWriteVariableInstruction(org.jetbrains.plugins.groovy.lang.psi.controlFlow.ReadWriteVariableInstruction) Instruction(org.jetbrains.plugins.groovy.lang.psi.controlFlow.Instruction)

Example 8 with GrClosableBlock

use of org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock in project intellij-community by JetBrains.

the class GrIntroduceClosureParameterProcessor method insertDeclaration.

private GrVariableDeclaration insertDeclaration(GrVariable original, GrVariableDeclaration declaration) {
    if (original instanceof GrField) {
        final PsiClass containingClass = ((GrField) original).getContainingClass();
        LOG.assertTrue(containingClass != null);
        return (GrVariableDeclaration) containingClass.addBefore(declaration, original.getParent());
    }
    final GrStatementOwner block;
    if (original instanceof PsiParameter) {
        final PsiElement container = original.getParent().getParent();
        if (container instanceof GrMethod) {
            block = ((GrMethod) container).getBlock();
        } else if (container instanceof GrClosableBlock) {
            block = (GrCodeBlock) container;
        } else if (container instanceof GrForStatement) {
            final GrStatement body = ((GrForStatement) container).getBody();
            if (body instanceof GrBlockStatement) {
                block = ((GrBlockStatement) body).getBlock();
            } else {
                GrBlockStatement blockStatement = myFactory.createBlockStatement();
                LOG.assertTrue(blockStatement != null);
                if (body != null) {
                    blockStatement.getBlock().addStatementBefore((GrStatement) body.copy(), null);
                    blockStatement = (GrBlockStatement) body.replace(blockStatement);
                } else {
                    blockStatement = (GrBlockStatement) container.add(blockStatement);
                }
                block = blockStatement.getBlock();
            }
        } else {
            throw new IncorrectOperationException();
        }
        LOG.assertTrue(block != null);
        return (GrVariableDeclaration) block.addStatementBefore(declaration, null);
    }
    PsiElement parent = original.getParent();
    LOG.assertTrue(parent instanceof GrVariableDeclaration);
    final PsiElement pparent = parent.getParent();
    if (pparent instanceof GrIfStatement) {
        if (((GrIfStatement) pparent).getThenBranch() == parent) {
            block = ((GrIfStatement) pparent).replaceThenBranch(myFactory.createBlockStatement()).getBlock();
        } else {
            block = ((GrIfStatement) pparent).replaceElseBranch(myFactory.createBlockStatement()).getBlock();
        }
        parent = block.addStatementBefore(((GrVariableDeclaration) parent), null);
    } else if (pparent instanceof GrLoopStatement) {
        block = ((GrLoopStatement) pparent).replaceBody(myFactory.createBlockStatement()).getBlock();
        parent = block.addStatementBefore(((GrVariableDeclaration) parent), null);
    } else {
        LOG.assertTrue(pparent instanceof GrStatementOwner);
        block = (GrStatementOwner) pparent;
    }
    return (GrVariableDeclaration) block.addStatementBefore(declaration, (GrStatement) parent);
}
Also used : GrMethod(org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod) GrStatementOwner(org.jetbrains.plugins.groovy.lang.psi.api.util.GrStatementOwner) GrClosableBlock(org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock) IncorrectOperationException(com.intellij.util.IncorrectOperationException) GrCodeBlock(org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrCodeBlock)

Example 9 with GrClosableBlock

use of org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock in project intellij-community by JetBrains.

the class GrIntroduceClosureParameterProcessor method generateDelegateClosure.

private GrClosableBlock generateDelegateClosure(GrClosableBlock originalClosure, GrVariable anchor, String newName) {
    GrClosableBlock result;
    if (originalClosure.hasParametersSection()) {
        result = myFactory.createClosureFromText("{->}", anchor);
        final GrParameterList parameterList = (GrParameterList) originalClosure.getParameterList().copy();
        result.getParameterList().replace(parameterList);
    } else {
        result = myFactory.createClosureFromText("{}", anchor);
    }
    StringBuilder call = new StringBuilder();
    call.append(newName).append('(');
    final GrParameter[] parameters = result.getParameters();
    for (int i = 0; i < parameters.length; i++) {
        if (!mySettings.parametersToRemove().contains(i)) {
            call.append(parameters[i].getName()).append(", ");
        }
    }
    call.append(myParameterInitializer.getText());
    call.append(")");
    final GrStatement statement = myFactory.createStatementFromText(call.toString());
    result.addStatementBefore(statement, null);
    return result;
}
Also used : GrParameterList(org.jetbrains.plugins.groovy.lang.psi.api.statements.params.GrParameterList) GrClosableBlock(org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock) GrParameter(org.jetbrains.plugins.groovy.lang.psi.api.statements.params.GrParameter)

Example 10 with GrClosableBlock

use of org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock in project intellij-community by JetBrains.

the class GrVariableInplaceRenamer method renameSynthetic.

@Override
protected void renameSynthetic(String newName) {
    PsiNamedElement elementToRename = getVariable();
    if (elementToRename instanceof ClosureSyntheticParameter && !"it".equals(newName)) {
        final GrClosableBlock closure = ((ClosureSyntheticParameter) elementToRename).getClosure();
        final GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(myProject);
        final PsiType type = ((ClosureSyntheticParameter) elementToRename).getTypeGroovy();
        final GrParameter newParam = factory.createParameter(newName, TypesUtil.unboxPrimitiveTypeWrapper(type));
        final GrParameter added = closure.addParameter(newParam);
        JavaCodeStyleManager.getInstance(added.getProject()).shortenClassReferences(added);
    }
}
Also used : GroovyPsiElementFactory(org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory) PsiNamedElement(com.intellij.psi.PsiNamedElement) GrClosableBlock(org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock) GrParameter(org.jetbrains.plugins.groovy.lang.psi.api.statements.params.GrParameter) ClosureSyntheticParameter(org.jetbrains.plugins.groovy.lang.psi.impl.synthetic.ClosureSyntheticParameter) PsiType(com.intellij.psi.PsiType)

Aggregations

GrClosableBlock (org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock)116 PsiElement (com.intellij.psi.PsiElement)32 GrExpression (org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression)31 GroovyPsiElement (org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElement)26 GrReferenceExpression (org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression)26 Nullable (org.jetbrains.annotations.Nullable)23 GrParameter (org.jetbrains.plugins.groovy.lang.psi.api.statements.params.GrParameter)23 GrMethod (org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod)18 GroovyPsiElementFactory (org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory)17 GrArgumentList (org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrArgumentList)15 GrMethodCallExpression (org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.path.GrMethodCallExpression)15 GrNamedArgument (org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrNamedArgument)14 GrMethodCall (org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrMethodCall)13 GrField (org.jetbrains.plugins.groovy.lang.psi.api.statements.GrField)12 ArrayList (java.util.ArrayList)11 NotNull (org.jetbrains.annotations.NotNull)10 GroovyRecursiveElementVisitor (org.jetbrains.plugins.groovy.lang.psi.GroovyRecursiveElementVisitor)10 GroovyResolveResult (org.jetbrains.plugins.groovy.lang.psi.api.GroovyResolveResult)10 GrOpenBlock (org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrOpenBlock)10 GroovyFile (org.jetbrains.plugins.groovy.lang.psi.GroovyFile)9