Search in sources :

Example 1 with GroovyPsiElementFactory

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

the class GroovyCodeFragmentFactory method externalParameters.

public static Pair<Map<String, String>, GroovyFile> externalParameters(String text, @NotNull final PsiElement context) {
    final GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(context.getProject());
    final GroovyFile toEval = factory.createGroovyFile(text, false, context);
    final GrClosableBlock closure = PsiTreeUtil.getParentOfType(context, GrClosableBlock.class);
    final Map<String, String> parameters = new THashMap<>();
    final Map<GrExpression, String> replacements = new HashMap<>();
    toEval.accept(new GroovyRecursiveElementVisitor() {

        @Override
        public void visitReferenceExpression(@NotNull GrReferenceExpression referenceExpression) {
            super.visitReferenceExpression(referenceExpression);
            if (PsiUtil.isThisReference(referenceExpression) || PsiUtil.isSuperReference(referenceExpression)) {
                replaceWithReference(referenceExpression, "delegate");
                return;
            }
            PsiElement resolved = referenceExpression.resolve();
            if (resolved instanceof PsiMember && (resolved instanceof PsiClass || ((PsiMember) resolved).hasModifierProperty(PsiModifier.STATIC))) {
                String qName = com.intellij.psi.util.PsiUtil.getMemberQualifiedName((PsiMember) resolved);
                if (qName != null && qName.contains(".") && !referenceExpression.isQualified()) {
                    replaceWithReference(referenceExpression, qName);
                    return;
                }
            }
            if (shouldDelegate(referenceExpression, resolved)) {
                replaceWithReference(referenceExpression, "delegate." + referenceExpression.getReferenceName());
                return;
            }
            if (resolved instanceof GrVariable && !(resolved instanceof GrField) && !PsiTreeUtil.isAncestor(toEval, resolved, false)) {
                final String name = ((GrVariable) resolved).getName();
                if (resolved instanceof ClosureSyntheticParameter && PsiTreeUtil.isAncestor(toEval, ((ClosureSyntheticParameter) resolved).getClosure(), false)) {
                    return;
                }
                if (resolved instanceof GrBindingVariable && !PsiTreeUtil.isAncestor(resolved.getContainingFile(), toEval, false)) {
                    return;
                }
                String value;
                if (closure != null && PsiTreeUtil.findCommonParent(resolved, closure) != closure && !(resolved instanceof ClosureSyntheticParameter)) {
                    // Evaluating inside closure for outer variable definitions
                    // All non-local variables are accessed by references
                    value = "this." + name;
                } else {
                    value = name;
                }
                parameters.put(name, value);
                return;
            }
            if (resolved instanceof PsiLocalVariable || resolved instanceof PsiParameter && !(resolved instanceof GrParameter)) {
                String name = referenceExpression.getReferenceName();
                parameters.put(name, name);
            }
        }

        private boolean shouldDelegate(GrReferenceExpression referenceExpression, @Nullable PsiElement resolved) {
            if (referenceExpression.isQualified()) {
                return false;
            }
            if (resolved instanceof GrField) {
                return true;
            }
            if (resolved instanceof PsiMethod) {
                String methodName = ((PsiMethod) resolved).getName();
                if (closure != null && "getDelegate".equals(methodName) || "call".equals(methodName)) {
                    return true;
                }
            }
            return closure != null && resolved instanceof GrLightVariable && "owner".equals(((GrLightVariable) resolved).getName());
        }

        private void replaceWithReference(GrExpression expr, final String exprText) {
            replacements.put(expr, exprText);
        }

        @Override
        public void visitCodeReferenceElement(@NotNull GrCodeReferenceElement refElement) {
            super.visitCodeReferenceElement(refElement);
            if (refElement.getQualifier() == null) {
                PsiElement resolved = refElement.resolve();
                if (resolved instanceof PsiClass) {
                    String qName = ((PsiClass) resolved).getQualifiedName();
                    if (qName != null) {
                        int dotIndex = qName.lastIndexOf(".");
                        if (dotIndex < 0)
                            return;
                        String packageName = qName.substring(0, dotIndex);
                        refElement.setQualifier(factory.createReferenceElementFromText(packageName));
                    }
                }
            }
        }
    });
    for (GrExpression expression : replacements.keySet()) {
        expression.replaceWithExpression(factory.createExpressionFromText(replacements.get(expression)), false);
    }
    return Pair.create(parameters, toEval);
}
Also used : GrField(org.jetbrains.plugins.groovy.lang.psi.api.statements.GrField) THashMap(gnu.trove.THashMap) GrParameter(org.jetbrains.plugins.groovy.lang.psi.api.statements.params.GrParameter) GrVariable(org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariable) THashMap(gnu.trove.THashMap) GrBindingVariable(org.jetbrains.plugins.groovy.lang.psi.impl.synthetic.GrBindingVariable) GrClosableBlock(org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock) GrExpression(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression) GroovyRecursiveElementVisitor(org.jetbrains.plugins.groovy.lang.psi.GroovyRecursiveElementVisitor) ClosureSyntheticParameter(org.jetbrains.plugins.groovy.lang.psi.impl.synthetic.ClosureSyntheticParameter) GrReferenceExpression(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression) GroovyPsiElementFactory(org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory) GrCodeReferenceElement(org.jetbrains.plugins.groovy.lang.psi.api.types.GrCodeReferenceElement) GrLightVariable(org.jetbrains.plugins.groovy.lang.psi.impl.synthetic.GrLightVariable) GroovyFile(org.jetbrains.plugins.groovy.lang.psi.GroovyFile)

Example 2 with GroovyPsiElementFactory

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

the class ForToEachIntention method processIntention.

@Override
public void processIntention(@NotNull PsiElement element, @NotNull Project project, Editor editor) throws IncorrectOperationException {
    final GrForStatement parentStatement = (GrForStatement) element;
    final GrForInClause clause = (GrForInClause) parentStatement.getClause();
    final GrVariable var = clause.getDeclaredVariable();
    final GrStatement body = parentStatement.getBody();
    final String bodyText;
    if (body instanceof GrBlockStatement) {
        final String text = body.getText();
        bodyText = text.substring(1, text.length() - 1);
    } else {
        bodyText = body.getText();
    }
    GrExpression collection = clause.getIteratedExpression();
    assert collection != null;
    @NonNls final String statement = "x.each{" + var.getText() + " -> " + bodyText + " }";
    final GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(parentStatement.getProject());
    final GrMethodCallExpression eachExpression = (GrMethodCallExpression) factory.createTopElementFromText(statement);
    ((GrReferenceExpression) eachExpression.getInvokedExpression()).getQualifierExpression().replaceWithExpression(collection, true);
    parentStatement.replaceWithStatement(eachExpression);
}
Also used : GrVariable(org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariable) GroovyPsiElementFactory(org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory) NonNls(org.jetbrains.annotations.NonNls) GrMethodCallExpression(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.path.GrMethodCallExpression) GrForInClause(org.jetbrains.plugins.groovy.lang.psi.api.statements.clauses.GrForInClause) GrForStatement(org.jetbrains.plugins.groovy.lang.psi.api.statements.GrForStatement) GrExpression(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression) GrBlockStatement(org.jetbrains.plugins.groovy.lang.psi.api.statements.GrBlockStatement) GrStatement(org.jetbrains.plugins.groovy.lang.psi.api.statements.GrStatement)

Example 3 with GroovyPsiElementFactory

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

the class GrChangeSignatureUsageProcessor method createDefaultValue.

@Nullable
private static GrExpression createDefaultValue(GroovyPsiElementFactory factory, JavaChangeInfo changeInfo, JavaParameterInfo info, final GrArgumentList list, PsiSubstitutor substitutor) {
    if (info.isUseAnySingleVariable()) {
        final PsiResolveHelper resolveHelper = JavaPsiFacade.getInstance(list.getProject()).getResolveHelper();
        final PsiType type = info.getTypeWrapper().getType(changeInfo.getMethod(), list.getManager());
        final VariablesProcessor processor = new VariablesProcessor(false) {

            @Override
            protected boolean check(PsiVariable var, ResolveState state) {
                if (var instanceof PsiField && !resolveHelper.isAccessible((PsiField) var, list, null))
                    return false;
                if (var instanceof GrVariable && PsiUtil.isLocalVariable(var) && list.getTextRange().getStartOffset() <= var.getTextRange().getStartOffset()) {
                    return false;
                }
                if (PsiTreeUtil.isAncestor(var, list, false))
                    return false;
                final PsiType _type = var instanceof GrVariable ? ((GrVariable) var).getTypeGroovy() : var.getType();
                final PsiType varType = state.get(PsiSubstitutor.KEY).substitute(_type);
                return type.isAssignableFrom(varType);
            }

            @Override
            public boolean execute(@NotNull PsiElement pe, @NotNull ResolveState state) {
                super.execute(pe, state);
                return size() < 2;
            }
        };
        treeWalkUp(list, processor);
        if (processor.size() == 1) {
            final PsiVariable result = processor.getResult(0);
            return factory.createExpressionFromText(result.getName(), list);
        }
        if (processor.size() == 0) {
            final PsiClass parentClass = PsiTreeUtil.getParentOfType(list, PsiClass.class);
            if (parentClass != null) {
                PsiClass containingClass = parentClass;
                final Set<PsiClass> containingClasses = new HashSet<>();
                final PsiElementFactory jfactory = JavaPsiFacade.getElementFactory(list.getProject());
                while (containingClass != null) {
                    if (type.isAssignableFrom(jfactory.createType(containingClass, PsiSubstitutor.EMPTY))) {
                        containingClasses.add(containingClass);
                    }
                    containingClass = PsiTreeUtil.getParentOfType(containingClass, PsiClass.class);
                }
                if (containingClasses.size() == 1) {
                    return factory.createThisExpression(containingClasses.contains(parentClass) ? null : containingClasses.iterator().next());
                }
            }
        }
    }
    final PsiElement element = info.getActualValue(list.getParent(), substitutor);
    if (element instanceof GrExpression) {
        return (GrExpression) element;
    }
    final String value = info.getDefaultValue();
    return !StringUtil.isEmpty(value) ? factory.createExpressionFromText(value, list) : null;
}
Also used : VariablesProcessor(com.intellij.psi.scope.processor.VariablesProcessor) GrExpression(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression) NotNull(org.jetbrains.annotations.NotNull) GroovyPsiElementFactory(org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory) GroovyPsiElement(org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElement) HashSet(com.intellij.util.containers.HashSet) Nullable(org.jetbrains.annotations.Nullable)

Example 4 with GroovyPsiElementFactory

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

the class GrChangeSignatureUsageProcessor method fixCatchBlock.

private static PsiElement fixCatchBlock(GrTryCatchStatement tryCatch, PsiClassType[] exceptions) {
    if (exceptions.length == 0)
        return tryCatch;
    final GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(tryCatch.getProject());
    final GrCatchClause[] clauses = tryCatch.getCatchClauses();
    List<String> restricted = ContainerUtil.map(clauses, grCatchClause -> {
        final GrParameter grParameter = grCatchClause.getParameter();
        return grParameter != null ? grParameter.getName() : null;
    });
    restricted = ContainerUtil.skipNulls(restricted);
    final DefaultGroovyVariableNameValidator nameValidator = new DefaultGroovyVariableNameValidator(tryCatch, restricted);
    GrCatchClause anchor = clauses.length == 0 ? null : clauses[clauses.length - 1];
    for (PsiClassType type : exceptions) {
        final String[] names = GroovyNameSuggestionUtil.suggestVariableNameByType(type, nameValidator);
        final GrCatchClause catchClause = factory.createCatchClause(type, names[0]);
        final GrStatement printStackTrace = factory.createStatementFromText(names[0] + ".printStackTrace()");
        catchClause.getBody().addStatementBefore(printStackTrace, null);
        anchor = tryCatch.addCatchClause(catchClause, anchor);
        JavaCodeStyleManager.getInstance(anchor.getProject()).shortenClassReferences(anchor);
    }
    return tryCatch;
}
Also used : GroovyPsiElementFactory(org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory) DefaultGroovyVariableNameValidator(org.jetbrains.plugins.groovy.refactoring.DefaultGroovyVariableNameValidator) GrParameter(org.jetbrains.plugins.groovy.lang.psi.api.statements.params.GrParameter)

Example 5 with GroovyPsiElementFactory

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

the class GrChangeSignatureUsageProcessor method createNewParameter.

private static GrParameter createNewParameter(@NotNull PsiSubstitutor substitutor, @NotNull PsiMethod context, @NotNull GrParameterList parameterList, @NotNull JavaParameterInfo newParameter, @NotNull String newName) {
    GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(parameterList.getProject());
    String typeText = newParameter.getTypeText();
    if (newParameter instanceof GrParameterInfo && (typeText.isEmpty() || "def".equals(typeText))) {
        return factory.createParameter(newName, null, getInitializer(newParameter), parameterList);
    }
    PsiType type = substitutor.substitute(newParameter.createType(context, parameterList.getManager()));
    return factory.createParameter(newName, type == null ? null : type.getCanonicalText(), getInitializer(newParameter), parameterList);
}
Also used : GroovyPsiElementFactory(org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory)

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