Search in sources :

Example 6 with GroovyPsiElementFactory

use of org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory 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 7 with GroovyPsiElementFactory

use of org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory in project intellij-community by JetBrains.

the class ClassItemGeneratorImpl method collectMethods.

@Override
public Collection<PsiMethod> collectMethods(PsiClass typeDefinition) {
    List<PsiMethod> result = ContainerUtil.filter(typeDefinition.getMethods(), m -> !GroovyObjectTransformationSupport.isGroovyObjectSupportMethod(m));
    if (typeDefinition instanceof GroovyScriptClass) {
        final GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(context.project);
        final String name = typeDefinition.getName();
        GrTypeDefinition tempClass = factory.createTypeDefinition("class " + name + " extends groovy.lang.Script {\n" + "  def " + name + "(groovy.lang.Binding binding){\n" + "    super(binding);\n" + "  }\n" + "  def " + name + "(){\n" + "    super();\n" + "  }\n" + "}");
        ContainerUtil.addAll(result, tempClass.getCodeConstructors());
    }
    return result;
}
Also used : GroovyPsiElementFactory(org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory) GroovyScriptClass(org.jetbrains.plugins.groovy.lang.psi.impl.synthetic.GroovyScriptClass) GrTypeDefinition(org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrTypeDefinition)

Example 8 with GroovyPsiElementFactory

use of org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory in project intellij-community by JetBrains.

the class SetterWriter method write.

public void write() {
    final boolean isStatic = mySetter.hasModifierProperty(PsiModifier.STATIC);
    final GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(myContext.project);
    PsiParameter[] parameters = mySetter.getParameterList().getParameters();
    PsiParameter parameter = parameters[parameters.length - 1];
    final PsiType parameterType = myContext.typeProvider.getParameterType(parameter);
    myBuffer.append("private static ");
    processTypeParameters(parameterType);
    myBuffer.append(myName);
    if (!(parameterType instanceof PsiPrimitiveType)) {
        parameter = factory.createParameter(parameter.getName(), "Value", null);
    }
    PsiParameter[] actual = inferActualParameters(isStatic, parameters, parameter);
    final GroovyPsiElement place = createStubMethod(actual);
    GenerationUtil.writeParameterList(myBuffer, actual, myClassNameProvider, myContext);
    writeBody(isStatic, parameters, parameter, place);
}
Also used : GroovyPsiElementFactory(org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory) GroovyPsiElement(org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElement)

Example 9 with GroovyPsiElementFactory

use of org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory in project intellij-community by JetBrains.

the class ClosureGenerator method generateClosureMethod.

@NotNull
private GrMethod generateClosureMethod(@NotNull GrClosableBlock block) {
    final GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(context.project);
    final GrMethod method = factory.createMethodFromText("def doCall(){}", block);
    GrReferenceAdjuster.shortenAllReferencesIn(method.setReturnType(context.typeProvider.getReturnType(block)));
    if (block.hasParametersSection()) {
        method.getParameterList().replace(block.getParameterList());
    } else {
        final GrParameter[] allParameters = block.getAllParameters();
        LOG.assertTrue(allParameters.length == 1);
        final GrParameter itParameter = allParameters[0];
        final GrParameter parameter = factory.createParameter("it", itParameter.getType().getCanonicalText(), "null", block);
        method.getParameterList().add(parameter);
    }
    ((GroovyFileImpl) method.getContainingFile()).setContextNullable(null);
    return method;
}
Also used : GroovyPsiElementFactory(org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory) GroovyFileImpl(org.jetbrains.plugins.groovy.lang.psi.impl.GroovyFileImpl) GrMethod(org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod) GrParameter(org.jetbrains.plugins.groovy.lang.psi.api.statements.params.GrParameter) NotNull(org.jetbrains.annotations.NotNull)

Example 10 with GroovyPsiElementFactory

use of org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory 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

GroovyPsiElementFactory (org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory)159 GrExpression (org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression)42 PsiElement (com.intellij.psi.PsiElement)30 GroovyPsiElement (org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElement)23 GrStatement (org.jetbrains.plugins.groovy.lang.psi.api.statements.GrStatement)22 GrReferenceExpression (org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression)21 IncorrectOperationException (com.intellij.util.IncorrectOperationException)20 Nullable (org.jetbrains.annotations.Nullable)20 GrParameter (org.jetbrains.plugins.groovy.lang.psi.api.statements.params.GrParameter)18 GrMethod (org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod)18 GrMethodCallExpression (org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.path.GrMethodCallExpression)17 NotNull (org.jetbrains.annotations.NotNull)16 GrClosableBlock (org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock)15 GrArgumentList (org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrArgumentList)14 Project (com.intellij.openapi.project.Project)8 GrOpenBlock (org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrOpenBlock)8 ASTNode (com.intellij.lang.ASTNode)7 ArrayList (java.util.ArrayList)7 GrCodeReferenceElement (org.jetbrains.plugins.groovy.lang.psi.api.types.GrCodeReferenceElement)7 GroovyResolveResult (org.jetbrains.plugins.groovy.lang.psi.api.GroovyResolveResult)6