Search in sources :

Example 1 with GrNamedArgument

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

the class GroovyParameterInfoHandler method getCurrentParameterIndex.

private static int getCurrentParameterIndex(GroovyPsiElement place, int offset) {
    if (place instanceof GrArgumentList) {
        GrArgumentList list = (GrArgumentList) place;
        int idx = (list.getNamedArguments().length > 0) ? 1 : 0;
        for (PsiElement child = list.getFirstChild(); child != null; child = child.getNextSibling()) {
            if (child.getTextRange().contains(offset)) {
                if (child instanceof GrNamedArgument)
                    return 0;
                return idx;
            }
            if (child.getNode().getElementType() == GroovyTokenTypes.mCOMMA)
                idx++;
            if (isNamedArgWithPriorComma(child))
                idx--;
        }
    }
    return -1;
}
Also used : GrNamedArgument(org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrNamedArgument) GrArgumentList(org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrArgumentList) GroovyPsiElement(org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElement)

Example 2 with GrNamedArgument

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

the class AnonymousFromMapGenerator method writeAnonymousMap.

static void writeAnonymousMap(GrListOrMap operand, GrTypeElement typeElement, final StringBuilder builder, ExpressionContext context) {
    final PsiType type = typeElement.getType();
    final PsiClass psiClass;
    final PsiSubstitutor substitutor;
    if (type instanceof PsiClassType) {
        final PsiClassType.ClassResolveResult resolveResult = ((PsiClassType) type).resolveGenerics();
        psiClass = resolveResult.getElement();
        substitutor = resolveResult.getSubstitutor();
    } else {
        psiClass = null;
        substitutor = PsiSubstitutor.EMPTY;
    }
    builder.append("new ");
    TypeWriter.writeTypeForNew(builder, type, operand);
    builder.append("() {\n");
    final GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(operand.getProject());
    final GrExpression caller = factory.createExpressionFromText("this");
    for (GrNamedArgument arg : operand.getNamedArguments()) {
        final String name = arg.getLabelName();
        final GrExpression expression = arg.getExpression();
        if (name == null || expression == null || !(expression instanceof GrClosableBlock))
            continue;
        final GrClosableBlock closure = (GrClosableBlock) expression;
        final GrParameter[] allParameters = closure.getAllParameters();
        List<GrParameter> actual = new ArrayList<>(Arrays.asList(allParameters));
        final PsiType clReturnType = context.typeProvider.getReturnType(closure);
        GrExpression[] args = new GrExpression[allParameters.length];
        for (int i = 0; i < allParameters.length; i++) {
            args[i] = factory.createExpressionFromText(allParameters[i].getName());
        }
        for (int param = allParameters.length; param >= 0; param--) {
            if (param < allParameters.length && !actual.get(param).isOptional())
                continue;
            if (param < allParameters.length) {
                final GrParameter opt = actual.remove(param);
                args[param] = opt.getInitializerGroovy();
            }
            final GrParameter[] parameters = actual.toArray(new GrParameter[actual.size()]);
            final GrClosureSignature signature = GrClosureSignatureUtil.createSignature(parameters, clReturnType);
            final GrMethod pattern = factory.createMethodFromSignature(name, signature);
            PsiMethod found = null;
            if (psiClass != null) {
                found = psiClass.findMethodBySignature(pattern, true);
            }
            if (found != null) {
                ModifierListGenerator.writeModifiers(builder, found.getModifierList(), ModifierListGenerator.JAVA_MODIFIERS_WITHOUT_ABSTRACT);
            } else {
                builder.append("public ");
            }
            PsiType returnType;
            if (found != null) {
                returnType = substitutor.substitute(context.typeProvider.getReturnType(found));
            } else {
                returnType = signature.getReturnType();
            }
            TypeWriter.writeType(builder, returnType, operand);
            builder.append(' ').append(name);
            GenerationUtil.writeParameterList(builder, parameters, new GeneratorClassNameProvider(), context);
            final ExpressionContext extended = context.extend();
            extended.setInAnonymousContext(true);
            if (param == allParameters.length) {
                new CodeBlockGenerator(builder, extended).generateCodeBlock(allParameters, closure, false);
            } else {
                builder.append("{\n");
                final ExpressionGenerator expressionGenerator = new ExpressionGenerator(builder, extended);
                GenerationUtil.invokeMethodByName(caller, name, args, GrNamedArgument.EMPTY_ARRAY, GrClosableBlock.EMPTY_ARRAY, expressionGenerator, arg);
                builder.append(";\n}\n");
            }
        }
    }
    builder.append("}");
}
Also used : GrNamedArgument(org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrNamedArgument) ArrayList(java.util.ArrayList) GrMethod(org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod) GrClosableBlock(org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock) GrExpression(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression) GrParameter(org.jetbrains.plugins.groovy.lang.psi.api.statements.params.GrParameter) GroovyPsiElementFactory(org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory) GrClosureSignature(org.jetbrains.plugins.groovy.lang.psi.api.signatures.GrClosureSignature)

Example 3 with GrNamedArgument

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

the class ExpressionGenerator method generateMapElementInsertions.

private void generateMapElementInsertions(GrListOrMap listOrMap, String varName) {
    for (GrNamedArgument arg : listOrMap.getNamedArguments()) {
        StringBuilder insertion = new StringBuilder();
        insertion.append(varName).append(".put(");
        final String stringKey = arg.getLabelName();
        if (stringKey != null) {
            insertion.append('"').append(stringKey).append('"');
        } else {
            final GrArgumentLabel label = arg.getLabel();
            final GrExpression expression = label == null ? null : label.getExpression();
            if (expression != null) {
                expression.accept(new ExpressionGenerator(insertion, context));
            } else {
            //todo should we generate an exception?
            }
        }
        insertion.append(", ");
        final GrExpression expression = arg.getExpression();
        if (expression != null) {
            expression.accept(new ExpressionGenerator(insertion, context));
        } else {
        //todo should we generate an exception?
        }
        insertion.append(");");
        context.myStatements.add(insertion.toString());
    }
}
Also used : GrNamedArgument(org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrNamedArgument) GrArgumentLabel(org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrArgumentLabel) GrString(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.literals.GrString)

Example 4 with GrNamedArgument

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

the class ExpressionGenerator method generateMethodCall.

private void generateMethodCall(GrMethodCall methodCallExpression) {
    final GrExpression invoked = methodCallExpression.getInvokedExpression();
    final GrExpression[] exprs = methodCallExpression.getExpressionArguments();
    final GrNamedArgument[] namedArgs = methodCallExpression.getNamedArguments();
    final GrClosableBlock[] clArgs = methodCallExpression.getClosureArguments();
    if (invoked instanceof GrReferenceExpression) {
        final GroovyResolveResult resolveResult = ((GrReferenceExpression) invoked).advancedResolve();
        final PsiElement resolved = resolveResult.getElement();
        if (resolved instanceof PsiMethod) {
            //todo replace null-qualifier with this-reference
            final GrExpression qualifier = ((GrReferenceExpression) invoked).getQualifier();
            invokeMethodOn(((PsiMethod) resolved), qualifier, exprs, namedArgs, clArgs, resolveResult.getSubstitutor(), methodCallExpression);
            return;
        } else if (resolved == null) {
            final GrExpression qualifier = ((GrReferenceExpression) invoked).getQualifier();
            final GrExpression[] args = generateArgsForInvokeMethod(((GrReferenceExpression) invoked).getReferenceName(), exprs, namedArgs, clArgs, methodCallExpression);
            GenerationUtil.invokeMethodByName(qualifier, "invokeMethod", args, GrNamedArgument.EMPTY_ARRAY, GrClosableBlock.EMPTY_ARRAY, this, methodCallExpression);
            return;
        }
    }
    GenerationUtil.invokeMethodByName(invoked, "call", exprs, namedArgs, clArgs, this, methodCallExpression);
}
Also used : GroovyResolveResult(org.jetbrains.plugins.groovy.lang.psi.api.GroovyResolveResult) GrNamedArgument(org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrNamedArgument) GrClosableBlock(org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock) GroovyPsiElement(org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElement)

Example 5 with GrNamedArgument

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

the class ConvertParameterToMapEntryIntention method performRefactoring.

private static void performRefactoring(final PsiElement element, final GrParametersOwner owner, final Collection<PsiElement> occurrences, final boolean createNewFirstParam, @Nullable final String mapParamName, final boolean specifyMapType) {
    final GrParameter param = getAppropriateParameter(element);
    assert param != null;
    final String paramName = param.getName();
    final String mapName = createNewFirstParam ? mapParamName : getFirstParameter(owner).getName();
    final Project project = element.getProject();
    final Runnable runnable = () -> {
        final GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(project);
        final GrParameterList list = owner.getParameterList();
        assert list != null;
        final int index = list.getParameterNumber(param);
        if (!createNewFirstParam && index <= 0) {
            // bad undo
            return;
        }
        //final List<GrCall> calls = getCallOccurrences(occurrences);
        try {
            for (PsiElement occurrence : occurrences) {
                GrReferenceExpression refExpr = null;
                GroovyResolveResult resolveResult = null;
                boolean isExplicitGetterCall = false;
                if (occurrence instanceof GrReferenceExpression) {
                    final PsiElement parent = occurrence.getParent();
                    if (parent instanceof GrCall) {
                        refExpr = (GrReferenceExpression) occurrence;
                        resolveResult = refExpr.advancedResolve();
                        final PsiElement resolved = resolveResult.getElement();
                        if (resolved instanceof PsiMethod && GroovyPropertyUtils.isSimplePropertyGetter(((PsiMethod) resolved)) && //check for explicit getter call
                        ((PsiMethod) resolved).getName().equals(refExpr.getReferenceName())) {
                            isExplicitGetterCall = true;
                        }
                    } else if (parent instanceof GrReferenceExpression) {
                        resolveResult = ((GrReferenceExpression) parent).advancedResolve();
                        final PsiElement resolved = resolveResult.getElement();
                        if (resolved instanceof PsiMethod && "call".equals(((PsiMethod) resolved).getName())) {
                            refExpr = (GrReferenceExpression) parent;
                        }
                    }
                }
                if (refExpr == null)
                    continue;
                final GrClosureSignature signature = generateSignature(owner, refExpr);
                if (signature == null)
                    continue;
                GrCall call;
                if (isExplicitGetterCall) {
                    PsiElement parent = refExpr.getParent();
                    LOG.assertTrue(parent instanceof GrCall);
                    parent = parent.getParent();
                    if (parent instanceof GrReferenceExpression && "call".equals(((GrReferenceExpression) parent).getReferenceName())) {
                        parent = parent.getParent();
                    }
                    if (parent instanceof GrCall) {
                        call = (GrCall) parent;
                    } else {
                        continue;
                    }
                } else {
                    call = (GrCall) refExpr.getParent();
                }
                if (resolveResult.isInvokedOnProperty()) {
                    final PsiElement parent = call.getParent();
                    if (parent instanceof GrCall) {
                        call = (GrCall) parent;
                    } else if (parent instanceof GrReferenceExpression && parent.getParent() instanceof GrCall) {
                        final PsiElement resolved = ((GrReferenceExpression) parent).resolve();
                        if (resolved instanceof PsiMethod && "call".equals(((PsiMethod) resolved).getName())) {
                            call = (GrCall) parent.getParent();
                        } else {
                            continue;
                        }
                    }
                }
                final GrClosureSignatureUtil.ArgInfo<PsiElement>[] argInfos = GrClosureSignatureUtil.mapParametersToArguments(signature, call);
                if (argInfos == null)
                    continue;
                final GrClosureSignatureUtil.ArgInfo<PsiElement> argInfo = argInfos[index];
                final GrNamedArgument namedArg;
                if (argInfo.isMultiArg) {
                    if (argInfo.args.isEmpty())
                        continue;
                    String arg = "[" + StringUtil.join(ContainerUtil.map(argInfo.args, element1 -> element1.getText()), ", ") + "]";
                    for (PsiElement psiElement : argInfo.args) {
                        psiElement.delete();
                    }
                    namedArg = factory.createNamedArgument(paramName, factory.createExpressionFromText(arg));
                } else {
                    if (argInfo.args.isEmpty())
                        continue;
                    final PsiElement argument = argInfo.args.iterator().next();
                    assert argument instanceof GrExpression;
                    namedArg = factory.createNamedArgument(paramName, (GrExpression) argument);
                    argument.delete();
                }
                call.addNamedArgument(namedArg);
            }
        } catch (IncorrectOperationException e) {
            LOG.error(e);
        }
        //Replace of occurrences of old parameter in closure/method
        final Collection<PsiReference> references = ReferencesSearch.search(param).findAll();
        for (PsiReference ref : references) {
            final PsiElement elt = ref.getElement();
            if (elt instanceof GrReferenceExpression) {
                GrReferenceExpression expr = (GrReferenceExpression) elt;
                final GrExpression newExpr = factory.createExpressionFromText(mapName + "." + paramName);
                expr.replaceWithExpression(newExpr, true);
            }
        }
        //Add new map parameter to closure/method if it's necessary
        if (createNewFirstParam) {
            try {
                final GrParameter newParam = factory.createParameter(mapName, specifyMapType ? MAP_TYPE_TEXT : "", null);
                list.addAfter(newParam, null);
            } catch (IncorrectOperationException e) {
                LOG.error(e);
            }
        }
        //Eliminate obsolete parameter from parameter list
        param.delete();
    };
    CommandProcessor.getInstance().executeCommand(project, () -> ApplicationManager.getApplication().runWriteAction(runnable), REFACTORING_NAME, null);
}
Also used : GrParameterList(org.jetbrains.plugins.groovy.lang.psi.api.statements.params.GrParameterList) GrNamedArgument(org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrNamedArgument) GrCall(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrCall) GrExpression(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression) GrParameter(org.jetbrains.plugins.groovy.lang.psi.api.statements.params.GrParameter) GrReferenceExpression(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression) GroovyPsiElementFactory(org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory) GrClosureSignatureUtil(org.jetbrains.plugins.groovy.lang.psi.impl.signatures.GrClosureSignatureUtil) Project(com.intellij.openapi.project.Project) GroovyResolveResult(org.jetbrains.plugins.groovy.lang.psi.api.GroovyResolveResult) GrClosureSignature(org.jetbrains.plugins.groovy.lang.psi.api.signatures.GrClosureSignature) Collection(java.util.Collection) IncorrectOperationException(com.intellij.util.IncorrectOperationException)

Aggregations

GrNamedArgument (org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrNamedArgument)48 GroovyPsiElement (org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElement)17 GrExpression (org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression)16 GrClosableBlock (org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock)13 GrListOrMap (org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.GrListOrMap)12 PsiElement (com.intellij.psi.PsiElement)11 GrArgumentList (org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrArgumentList)11 Nullable (org.jetbrains.annotations.Nullable)10 GrArgumentLabel (org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrArgumentLabel)8 NotNull (org.jetbrains.annotations.NotNull)5 GroovyPsiElementFactory (org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory)5 GroovyResolveResult (org.jetbrains.plugins.groovy.lang.psi.api.GroovyResolveResult)5 GrString (org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.literals.GrString)5 IncorrectOperationException (com.intellij.util.IncorrectOperationException)4 NamedArgumentDescriptor (org.jetbrains.plugins.groovy.extensions.NamedArgumentDescriptor)4 GrClosureSignature (org.jetbrains.plugins.groovy.lang.psi.api.signatures.GrClosureSignature)4 GrCall (org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrCall)4 ASTNode (com.intellij.lang.ASTNode)3 LeafPsiElement (com.intellij.psi.impl.source.tree.LeafPsiElement)3 ArrayList (java.util.ArrayList)3