Search in sources :

Example 76 with GrVariable

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

the class GrSetStrongTypeIntention method processIntention.

@Override
protected void processIntention(@NotNull PsiElement element, @NotNull Project project, final Editor editor) throws IncorrectOperationException {
    PsiElement parent = element.getParent();
    PsiElement elementToBuildTemplate;
    GrVariable[] variables;
    if (parent instanceof GrVariable && parent.getParent() instanceof GrVariableDeclaration) {
        variables = ((GrVariableDeclaration) parent.getParent()).getVariables();
        elementToBuildTemplate = parent.getParent();
    } else if (parent instanceof GrVariable && parent.getParent() instanceof GrForInClause) {
        variables = new GrVariable[] { (GrVariable) parent };
        elementToBuildTemplate = parent.getParent().getParent();
    } else if (parent instanceof GrVariableDeclaration) {
        variables = ((GrVariableDeclaration) parent).getVariables();
        elementToBuildTemplate = parent;
    } else if (parent instanceof GrParameter && parent.getParent() instanceof GrParameterList) {
        variables = new GrVariable[] { (GrVariable) parent };
        elementToBuildTemplate = parent.getParent().getParent();
    } else if (parent instanceof GrVariable) {
        variables = new GrVariable[] { ((GrVariable) parent) };
        elementToBuildTemplate = parent;
    } else {
        return;
    }
    ArrayList<TypeConstraint> types = new ArrayList<>();
    if (parent.getParent() instanceof GrForInClause) {
        types.add(SupertypeConstraint.create(PsiUtil.extractIteratedType((GrForInClause) parent.getParent())));
    } else {
        for (GrVariable variable : variables) {
            GrExpression initializer = variable.getInitializerGroovy();
            if (initializer != null) {
                PsiType type = initializer.getType();
                if (type != null) {
                    types.add(SupertypeConstraint.create(type));
                }
            }
            if (variable instanceof GrParameter) {
                final PsiParameter parameter = (PsiParameter) variable;
                final PsiType type = getClosureParameterType(parameter);
                if (type != null) {
                    types.add(SupertypeConstraint.create(type));
                }
            }
        }
    }
    final String originalText = elementToBuildTemplate.getText();
    final TypeInfo typeInfo = getOrCreateTypeElement(parent, elementToBuildTemplate);
    final PsiElement replaceElement = typeInfo.elementToReplace;
    TypeConstraint[] constraints = types.toArray(new TypeConstraint[types.size()]);
    ChooseTypeExpression chooseTypeExpression = new ChooseTypeExpression(constraints, element.getManager(), replaceElement.getResolveScope());
    TemplateBuilderImpl builder = new TemplateBuilderImpl(elementToBuildTemplate);
    builder.replaceElement(replaceElement, chooseTypeExpression);
    final Document document = editor.getDocument();
    final RangeMarker rangeMarker = document.createRangeMarker(elementToBuildTemplate.getTextRange());
    rangeMarker.setGreedyToRight(true);
    rangeMarker.setGreedyToLeft(true);
    final PsiElement afterPostprocess = CodeInsightUtilCore.forcePsiPostprocessAndRestoreElement(elementToBuildTemplate);
    final Template template = builder.buildTemplate();
    TextRange range = afterPostprocess.getTextRange();
    document.deleteString(range.getStartOffset(), range.getEndOffset());
    TemplateManager templateManager = TemplateManager.getInstance(project);
    templateManager.startTemplate(editor, template, new TemplateEditingAdapter() {

        @Override
        public void templateFinished(Template template, boolean brokenOff) {
            if (brokenOff) {
                ApplicationManager.getApplication().runWriteAction(() -> {
                    if (rangeMarker.isValid()) {
                        document.replaceString(rangeMarker.getStartOffset(), rangeMarker.getEndOffset(), originalText);
                        editor.getCaretModel().moveToOffset(rangeMarker.getStartOffset() + typeInfo.originalOffset);
                    }
                });
            }
        }
    });
}
Also used : GrParameterList(org.jetbrains.plugins.groovy.lang.psi.api.statements.params.GrParameterList) ArrayList(java.util.ArrayList) GrParameter(org.jetbrains.plugins.groovy.lang.psi.api.statements.params.GrParameter) Document(com.intellij.openapi.editor.Document) ChooseTypeExpression(org.jetbrains.plugins.groovy.template.expressions.ChooseTypeExpression) Template(com.intellij.codeInsight.template.Template) GrVariable(org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariable) TemplateBuilderImpl(com.intellij.codeInsight.template.TemplateBuilderImpl) TemplateManager(com.intellij.codeInsight.template.TemplateManager) PsiElement(com.intellij.psi.PsiElement) PsiType(com.intellij.psi.PsiType) TemplateEditingAdapter(com.intellij.codeInsight.template.TemplateEditingAdapter) GrExpression(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression) TextRange(com.intellij.openapi.util.TextRange) RangeMarker(com.intellij.openapi.editor.RangeMarker) GrVariableDeclaration(org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariableDeclaration) PsiParameter(com.intellij.psi.PsiParameter) GrForInClause(org.jetbrains.plugins.groovy.lang.psi.api.statements.clauses.GrForInClause) TypeConstraint(org.jetbrains.plugins.groovy.lang.psi.expectedTypes.TypeConstraint)

Example 77 with GrVariable

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

the class GrSplitDeclarationIntention method processTuple.

private static void processTuple(Project project, GrVariableDeclaration declaration) {
    GrExpression initializer = declaration.getTupleInitializer();
    assert initializer != null;
    GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(project);
    GrVariable[] variables = declaration.getVariables();
    StringBuilder assignmentBuilder = new StringBuilder();
    assignmentBuilder.append('(');
    for (GrVariable variable : variables) {
        assignmentBuilder.append(variable.getName()).append(',');
    }
    assignmentBuilder.replace(assignmentBuilder.length() - 1, assignmentBuilder.length(), ")=");
    assignmentBuilder.append(initializer.getText());
    GrStatement assignment = factory.createStatementFromText(assignmentBuilder.toString());
    declaration = GroovyRefactoringUtil.addBlockIntoParent(declaration);
    declaration.getParent().addAfter(assignment, declaration);
    initializer.delete();
}
Also used : GroovyPsiElementFactory(org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory) GrVariable(org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariable) GrExpression(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression) GrStatement(org.jetbrains.plugins.groovy.lang.psi.api.statements.GrStatement)

Example 78 with GrVariable

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

the class GrSplitDeclarationIntention method processIntention.

@Override
protected void processIntention(@NotNull PsiElement element, @NotNull Project project, Editor editor) throws IncorrectOperationException {
    if (!(element instanceof GrVariableDeclaration))
        return;
    GrVariableDeclaration declaration = (GrVariableDeclaration) element;
    GrVariable[] variables = declaration.getVariables();
    if (variables.length == 1) {
        processSingleVar(project, declaration, variables[0]);
    } else if (variables.length > 1) {
        if (!declaration.isTuple() || declaration.getTupleInitializer() instanceof GrListOrMap) {
            processMultipleVars(project, declaration);
        } else {
            processTuple(project, declaration);
        }
    }
}
Also used : GrVariable(org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariable) GrVariableDeclaration(org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariableDeclaration) GrListOrMap(org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.GrListOrMap)

Example 79 with GrVariable

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

the class MyPredicate method replaceMapWithClass.

public static void replaceMapWithClass(Project project, final GrListOrMap map, PsiClass generatedClass, boolean replaceReturnType, boolean variableDeclaration, GrParameter parameter) {
    JavaCodeStyleManager.getInstance(project).shortenClassReferences(generatedClass);
    final String text = map.getText();
    int begin = 0;
    int end = text.length();
    if (text.startsWith("["))
        begin++;
    if (text.endsWith("]"))
        end--;
    final GrExpression newExpression = GroovyPsiElementFactory.getInstance(project).createExpressionFromText("new " + generatedClass.getQualifiedName() + "(" + text.substring(begin, end) + ")");
    final GrExpression replacedNewExpression = ((GrExpression) map.replace(newExpression));
    if (replaceReturnType) {
        final PsiType type = replacedNewExpression.getType();
        final GrMethod method = PsiTreeUtil.getParentOfType(replacedNewExpression, GrMethod.class, true, GrClosableBlock.class);
        LOG.assertTrue(method != null);
        GrReferenceAdjuster.shortenAllReferencesIn(method.setReturnType(type));
    }
    if (variableDeclaration) {
        final PsiElement parent = PsiUtil.skipParentheses(replacedNewExpression.getParent(), true);
        ((GrVariable) parent).setType(replacedNewExpression.getType());
    }
    if (parameter != null) {
        parameter.setType(newExpression.getType());
    }
    JavaCodeStyleManager.getInstance(project).shortenClassReferences(replacedNewExpression);
    IntentionUtils.positionCursor(project, generatedClass.getContainingFile(), generatedClass);
}
Also used : GrVariable(org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariable) GrMethod(org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod) GrExpression(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression)

Example 80 with GrVariable

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

the class CompletionTestBase method doTest.

protected void doTest(String directory) {
    CamelHumpMatcher.forceStartMatching(myFixture.getTestRootDisposable());
    final List<String> stringList = TestUtils.readInput(getTestDataPath() + "/" + getTestName(true) + ".test");
    if (directory.length() != 0)
        directory += "/";
    final String fileName = directory + getTestName(true) + "." + getExtension();
    myFixture.addFileToProject(fileName, stringList.get(0));
    myFixture.configureByFile(fileName);
    boolean old = CodeInsightSettings.getInstance().AUTOCOMPLETE_COMMON_PREFIX;
    CodeInsightSettings.getInstance().AUTOCOMPLETE_COMMON_PREFIX = false;
    CodeInsightSettings.getInstance().AUTOCOMPLETE_ON_CODE_COMPLETION = false;
    String result = "";
    try {
        myFixture.completeBasic();
        final LookupImpl lookup = (LookupImpl) LookupManager.getActiveLookup(myFixture.getEditor());
        if (lookup != null) {
            List<LookupElement> items = lookup.getItems();
            if (!addReferenceVariants()) {
                items = ContainerUtil.findAll(items, lookupElement -> {
                    final Object o = lookupElement.getObject();
                    return !(o instanceof PsiMember) && !(o instanceof GrVariable) && !(o instanceof GroovyResolveResult) && !(o instanceof PsiPackage);
                });
            }
            Collections.sort(items, (o1, o2) -> o1.getLookupString().compareTo(o2.getLookupString()));
            result = "";
            for (LookupElement item : items) {
                result = result + "\n" + item.getLookupString();
            }
            result = result.trim();
            LookupManager.getInstance(myFixture.getProject()).hideActiveLookup();
        }
    } finally {
        CodeInsightSettings.getInstance().AUTOCOMPLETE_ON_CODE_COMPLETION = true;
        CodeInsightSettings.getInstance().AUTOCOMPLETE_COMMON_PREFIX = old;
    }
    assertEquals(StringUtil.trimEnd(stringList.get(1), "\n"), result);
}
Also used : PsiPackage(com.intellij.psi.PsiPackage) LookupImpl(com.intellij.codeInsight.lookup.impl.LookupImpl) PsiMember(com.intellij.psi.PsiMember) JavaCodeInsightFixtureTestCase(com.intellij.testFramework.fixtures.JavaCodeInsightFixtureTestCase) LookupElement(com.intellij.codeInsight.lookup.LookupElement) StringUtil(com.intellij.openapi.util.text.StringUtil) LookupManager(com.intellij.codeInsight.lookup.LookupManager) CodeInsightSettings(com.intellij.codeInsight.CodeInsightSettings) TestUtils(org.jetbrains.plugins.groovy.util.TestUtils) ContainerUtil(com.intellij.util.containers.ContainerUtil) GroovyResolveResult(org.jetbrains.plugins.groovy.lang.psi.api.GroovyResolveResult) List(java.util.List) GrVariable(org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariable) CamelHumpMatcher(com.intellij.codeInsight.completion.impl.CamelHumpMatcher) Collections(java.util.Collections) GrVariable(org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariable) LookupImpl(com.intellij.codeInsight.lookup.impl.LookupImpl) GroovyResolveResult(org.jetbrains.plugins.groovy.lang.psi.api.GroovyResolveResult) PsiPackage(com.intellij.psi.PsiPackage) LookupElement(com.intellij.codeInsight.lookup.LookupElement) PsiMember(com.intellij.psi.PsiMember)

Aggregations

GrVariable (org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariable)88 GrExpression (org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression)34 PsiElement (com.intellij.psi.PsiElement)24 Nullable (org.jetbrains.annotations.Nullable)20 GrVariableDeclaration (org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariableDeclaration)19 GroovyPsiElement (org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElement)16 NotNull (org.jetbrains.annotations.NotNull)14 GrReferenceExpression (org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression)14 GrField (org.jetbrains.plugins.groovy.lang.psi.api.statements.GrField)12 StringPartInfo (org.jetbrains.plugins.groovy.refactoring.introduce.StringPartInfo)11 GrStatement (org.jetbrains.plugins.groovy.lang.psi.api.statements.GrStatement)10 GrParameter (org.jetbrains.plugins.groovy.lang.psi.api.statements.params.GrParameter)10 GrClosableBlock (org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock)8 GrMethod (org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod)8 PsiType (com.intellij.psi.PsiType)7 GroovyResolveResult (org.jetbrains.plugins.groovy.lang.psi.api.GroovyResolveResult)7 GrAssignmentExpression (org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrAssignmentExpression)7 TextRange (com.intellij.openapi.util.TextRange)6 GroovyRecursiveElementVisitor (org.jetbrains.plugins.groovy.lang.psi.GroovyRecursiveElementVisitor)6 ASTNode (com.intellij.lang.ASTNode)5