Search in sources :

Example 1 with GroovyScriptClass

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

the class CreateFieldFix method doFix.

protected void doFix(@NotNull Project project, @NotNull @GrModifier.ModifierConstant String[] modifiers, @NotNull @NonNls String fieldName, @NotNull TypeConstraint[] typeConstraints, @NotNull PsiElement context) throws IncorrectOperationException {
    JVMElementFactory factory = JVMElementFactories.getFactory(myTargetClass.getLanguage(), project);
    if (factory == null)
        return;
    PsiField field = factory.createField(fieldName, PsiType.INT);
    if (myTargetClass instanceof GroovyScriptClass) {
        field.getModifierList().addAnnotation(GroovyCommonClassNames.GROOVY_TRANSFORM_FIELD);
    }
    for (@GrModifier.ModifierConstant String modifier : modifiers) {
        PsiUtil.setModifierProperty(field, modifier, true);
    }
    field = CreateFieldFromUsageHelper.insertField(myTargetClass, field, context);
    JavaCodeStyleManager.getInstance(project).shortenClassReferences(field.getParent());
    Editor newEditor = IntentionUtils.positionCursor(project, myTargetClass.getContainingFile(), field);
    Template template = CreateFieldFromUsageHelper.setupTemplate(field, typeConstraints, myTargetClass, newEditor, context, false);
    TemplateManager manager = TemplateManager.getInstance(project);
    manager.startTemplate(newEditor, template);
}
Also used : GroovyScriptClass(org.jetbrains.plugins.groovy.lang.psi.impl.synthetic.GroovyScriptClass) TemplateManager(com.intellij.codeInsight.template.TemplateManager) Editor(com.intellij.openapi.editor.Editor) Template(com.intellij.codeInsight.template.Template)

Example 2 with GroovyScriptClass

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

the class MavenGroovyPolyglotPomMemberContributor method processDynamicElements.

@Override
public void processDynamicElements(@NotNull PsiType qualifierType, PsiClass aClass, @NotNull PsiScopeProcessor processor, @NotNull PsiElement place, @NotNull ResolveState state) {
    if (!(aClass instanceof GroovyScriptClass)) {
        return;
    }
    PsiFile file = aClass.getContainingFile();
    if (file == null || !"pom.groovy".equals(file.getName()))
        return;
    List<String> methodCallInfo = MavenGroovyPomUtil.getGroovyMethodCalls(place);
    MultiMap<String, String> multiMap = MultiMap.createLinked();
    MultiMap<String, String> leafMap = MultiMap.createLinked();
    String key = StringUtil.join(methodCallInfo, "->");
    for (Contributor contributor : contributors.getValue()) {
        contributor.populate(place.getProject(), multiMap, leafMap);
    }
    for (String classSource : multiMap.get(key)) {
        DynamicMemberUtils.process(processor, false, place, classSource);
    }
    for (String classSource : leafMap.get(key)) {
        if (!(place.getParent() instanceof GrClosableBlock)) {
            DynamicMemberUtils.process(processor, false, place, classSource);
        }
    }
    if (!methodCallInfo.isEmpty() && StringUtil.endsWithIgnoreCase(ContainerUtil.getLastItem(methodCallInfo), CompletionUtilCore.DUMMY_IDENTIFIER_TRIMMED)) {
        key = StringUtil.join(ContainerUtil.dropTail(methodCallInfo), "->");
        for (String classSource : multiMap.get(key)) {
            DynamicMemberUtils.process(processor, false, place, classSource);
        }
    }
}
Also used : GroovyScriptClass(org.jetbrains.plugins.groovy.lang.psi.impl.synthetic.GroovyScriptClass) NonCodeMembersContributor(org.jetbrains.plugins.groovy.lang.resolve.NonCodeMembersContributor) GrClosableBlock(org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock)

Example 3 with GroovyScriptClass

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

the class ClassItemGeneratorImpl method writeMethod.

@Override
public void writeMethod(StringBuilder builder, PsiMethod method) {
    if (method == null)
        return;
    GenerationUtil.writeDocComment(builder, method, true);
    String name = method.getName();
    boolean isAbstract = method.hasModifierProperty(PsiModifier.ABSTRACT);
    PsiModifierList modifierList = method.getModifierList();
    final PsiClass containingClass = method.getContainingClass();
    if (method.isConstructor() && containingClass != null && containingClass.isEnum()) {
        ModifierListGenerator.writeModifiers(builder, modifierList, ModifierListGenerator.ENUM_CONSTRUCTOR_MODIFIERS);
    } else {
        ModifierListGenerator.writeModifiers(builder, modifierList);
    }
    if (method.hasTypeParameters()) {
        GenerationUtil.writeTypeParameters(builder, method, classNameProvider);
        builder.append(' ');
    }
    //append return type
    if (!method.isConstructor()) {
        PsiType retType = context.typeProvider.getReturnType(method);
        TypeWriter.writeType(builder, retType, method, classNameProvider);
        builder.append(' ');
    }
    builder.append(name);
    if (method instanceof GroovyPsiElement) {
        context.searchForLocalVarsToWrap((GroovyPsiElement) method);
    }
    GenerationUtil.writeParameterList(builder, method.getParameterList().getParameters(), classNameProvider, context);
    if (method instanceof GrAnnotationMethod) {
        GrAnnotationMemberValue defaultValue = ((GrAnnotationMethod) method).getDefaultValue();
        if (defaultValue != null) {
            builder.append("default ");
            defaultValue.accept(new AnnotationGenerator(builder, context));
        }
    }
    GenerationUtil.writeThrowsList(builder, method.getThrowsList(), getMethodExceptions(method), classNameProvider);
    if (!isAbstract) {
        /* ************ body ********* */
        if (method instanceof GrMethod) {
            if (method instanceof GrReflectedMethod && ((GrReflectedMethod) method).getSkippedParameters().length > 0) {
                builder.append("{\n").append(generateDelegateCall((GrReflectedMethod) method)).append("\n}\n");
            } else {
                new CodeBlockGenerator(builder, context.extend()).generateMethodBody((GrMethod) method);
            }
        } else if (method instanceof GrAccessorMethod) {
            writeAccessorBody(builder, method);
        } else if (method instanceof LightMethodBuilder && containingClass instanceof GroovyScriptClass) {
            if ("main".equals(method.getName())) {
                writeMainScriptMethodBody(builder, method);
            } else if ("run".equals(method.getName())) {
                writeRunScriptMethodBody(builder, method);
            }
        } else {
            builder.append("{//todo\n}");
        }
    } else {
        builder.append(';');
    }
}
Also used : GroovyPsiElement(org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElement) LightMethodBuilder(com.intellij.psi.impl.light.LightMethodBuilder) GrAnnotationMemberValue(org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.annotation.GrAnnotationMemberValue) GroovyScriptClass(org.jetbrains.plugins.groovy.lang.psi.impl.synthetic.GroovyScriptClass)

Example 4 with GroovyScriptClass

use of org.jetbrains.plugins.groovy.lang.psi.impl.synthetic.GroovyScriptClass 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 5 with GroovyScriptClass

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

the class ExpressionGenerator method visitReferenceExpression.

@Override
public void visitReferenceExpression(@NotNull GrReferenceExpression referenceExpression) {
    final GrExpression qualifier = referenceExpression.getQualifier();
    final GroovyResolveResult resolveResult = referenceExpression.advancedResolve();
    final PsiElement resolved = resolveResult.getElement();
    final String referenceName = referenceExpression.getReferenceName();
    if (PsiUtil.isThisOrSuperRef(referenceExpression)) {
        writeThisOrSuperRef(referenceExpression, qualifier, referenceName);
        return;
    }
    if (ResolveUtil.isClassReference(referenceExpression)) {
        // just delegate to qualifier
        LOG.assertTrue(qualifier != null);
        qualifier.accept(this);
        return;
    }
    if (resolved instanceof PsiClass) {
        builder.append(((PsiClass) resolved).getQualifiedName());
        if (PsiUtil.isExpressionUsed(referenceExpression)) {
            builder.append(".class");
        }
        return;
    }
    //don't try to resolve local vars that are provided my this generator (they are listed in myUsedVarNames)
    if (resolved == null && qualifier == null && context.myUsedVarNames.contains(referenceName)) {
        builder.append(referenceName);
        return;
    }
    //all refs in script that are not resolved are saved in 'binding' of the script
    if (qualifier == null && (resolved == null || resolved instanceof GrBindingVariable || resolved instanceof LightElement && !(resolved instanceof ClosureSyntheticParameter)) && (referenceExpression.getParent() instanceof GrIndexProperty || !(referenceExpression.getParent() instanceof GrCall)) && PsiUtil.getContextClass(referenceExpression) instanceof GroovyScriptClass) {
        final GrExpression thisExpr = factory.createExpressionFromText("this", referenceExpression);
        thisExpr.accept(this);
        builder.append(".getBinding().getProperty(\"").append(referenceExpression.getReferenceName()).append("\")");
        return;
    }
    final IElementType type = referenceExpression.getDotTokenType();
    GrExpression qualifierToUse = qualifier;
    if (type == GroovyTokenTypes.mMEMBER_POINTER) {
        LOG.assertTrue(qualifier != null);
        builder.append("new ").append(GroovyCommonClassNames.ORG_CODEHAUS_GROOVY_RUNTIME_METHOD_CLOSURE).append('(');
        qualifier.accept(this);
        builder.append(", \"").append(referenceName).append("\")");
        return;
    }
    if (type == GroovyTokenTypes.mOPTIONAL_DOT) {
        LOG.assertTrue(qualifier != null);
        String qualifierName = createVarByInitializer(qualifier);
        builder.append('(').append(qualifierName).append(" == null ? null : ");
        qualifierToUse = factory.createReferenceExpressionFromText(qualifierName, referenceExpression);
    }
    if (resolveResult.isInvokedOnProperty()) {
        //property-style access to accessor (e.g. qual.prop should be translated to qual.getProp())
        LOG.assertTrue(resolved instanceof PsiMethod);
        LOG.assertTrue(GroovyPropertyUtils.isSimplePropertyGetter((PsiMethod) resolved));
        invokeMethodOn(((PsiMethod) resolved), qualifierToUse, GrExpression.EMPTY_ARRAY, GrNamedArgument.EMPTY_ARRAY, GrClosableBlock.EMPTY_ARRAY, resolveResult.getSubstitutor(), referenceExpression);
    } else {
        if (qualifierToUse != null) {
            qualifierToUse.accept(this);
            builder.append('.');
        }
        if (resolved instanceof PsiNamedElement && !(resolved instanceof GrBindingVariable)) {
            final String refName = ((PsiNamedElement) resolved).getName();
            if (resolved instanceof GrVariable && context.analyzedVars.toWrap((GrVariable) resolved)) {
                //this var should be wrapped by groovy.lang.Reference. so we add .get() tail.
                builder.append(context.analyzedVars.toVarName((GrVariable) resolved));
                if (!PsiUtil.isAccessedForWriting(referenceExpression)) {
                    builder.append(".get()");
                }
            } else {
                builder.append(refName);
            }
        } else {
            //unresolved reference
            if (referenceName != null) {
                if (PsiUtil.isAccessedForWriting(referenceExpression)) {
                    builder.append(referenceName);
                } else {
                    PsiType stringType = PsiType.getJavaLangString(referenceExpression.getManager(), referenceExpression.getResolveScope());
                    PsiType qualifierType = PsiImplUtil.getQualifierType(referenceExpression);
                    GroovyResolveResult[] candidates = qualifierType != null ? ResolveUtil.getMethodCandidates(qualifierType, "getProperty", referenceExpression, stringType) : GroovyResolveResult.EMPTY_ARRAY;
                    final PsiElement method = PsiImplUtil.extractUniqueElement(candidates);
                    if (method != null) {
                        builder.append("getProperty(\"").append(referenceName).append("\")");
                    } else {
                        builder.append(referenceName);
                    }
                }
            } else {
                final PsiElement nameElement = referenceExpression.getReferenceNameElement();
                if (nameElement instanceof GrExpression) {
                    ((GrExpression) nameElement).accept(this);
                } else if (nameElement != null) {
                    builder.append(nameElement.toString());
                }
            }
        }
    }
    if (type == GroovyTokenTypes.mOPTIONAL_DOT) {
        builder.append(')');
    }
}
Also used : GrIndexProperty(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.path.GrIndexProperty) GrString(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.literals.GrString) LightElement(com.intellij.psi.impl.light.LightElement) ClosureSyntheticParameter(org.jetbrains.plugins.groovy.lang.psi.impl.synthetic.ClosureSyntheticParameter) IElementType(com.intellij.psi.tree.IElementType) GrVariable(org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariable) GroovyResolveResult(org.jetbrains.plugins.groovy.lang.psi.api.GroovyResolveResult) GroovyScriptClass(org.jetbrains.plugins.groovy.lang.psi.impl.synthetic.GroovyScriptClass) GrBindingVariable(org.jetbrains.plugins.groovy.lang.psi.impl.synthetic.GrBindingVariable) GroovyPsiElement(org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElement)

Aggregations

GroovyScriptClass (org.jetbrains.plugins.groovy.lang.psi.impl.synthetic.GroovyScriptClass)26 GroovyFile (org.jetbrains.plugins.groovy.lang.psi.GroovyFile)8 GroovyPsiElement (org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElement)6 PsiElement (com.intellij.psi.PsiElement)4 NotNull (org.jetbrains.annotations.NotNull)4 GroovyPsiElementFactory (org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory)3 GrClosableBlock (org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock)3 GrReferenceExpression (org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression)3 GrTypeDefinition (org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrTypeDefinition)3 GrMember (org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMember)3 GrMethod (org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod)3 GrImportStatement (org.jetbrains.plugins.groovy.lang.psi.api.toplevel.imports.GrImportStatement)3 PsiClass (com.intellij.psi.PsiClass)2 LightMethodBuilder (com.intellij.psi.impl.light.LightMethodBuilder)2 GrDocComment (org.jetbrains.plugins.groovy.lang.groovydoc.psi.api.GrDocComment)2 GrVariable (org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariable)2 GrExpression (org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression)2 GrPackageDefinition (org.jetbrains.plugins.groovy.lang.psi.api.toplevel.packaging.GrPackageDefinition)2 Template (com.intellij.codeInsight.template.Template)1 TemplateManager (com.intellij.codeInsight.template.TemplateManager)1