Search in sources :

Example 1 with TypeExpression

use of com.intellij.codeInsight.intention.impl.TypeExpression in project intellij-community by JetBrains.

the class ConstructorInsertHandler method startTemplate.

private static void startTemplate(final PsiAnonymousClass aClass, final Editor editor, final Runnable runnable, @NotNull final PsiTypeElement[] parameters) {
    final Project project = aClass.getProject();
    new WriteCommandAction(project, getCommandName(), getCommandName()) {

        @Override
        protected void run(@NotNull Result result) throws Throwable {
            PsiDocumentManager.getInstance(project).doPostponedOperationsAndUnblockDocument(editor.getDocument());
            editor.getCaretModel().moveToOffset(aClass.getTextOffset());
            final TemplateBuilderImpl templateBuilder = (TemplateBuilderImpl) TemplateBuilderFactory.getInstance().createTemplateBuilder(aClass);
            for (int i = 0; i < parameters.length; i++) {
                PsiTypeElement parameter = parameters[i];
                templateBuilder.replaceElement(parameter, "param" + i, new TypeExpression(project, new PsiType[] { parameter.getType() }), true);
            }
            Template template = templateBuilder.buildInlineTemplate();
            TemplateManager.getInstance(project).startTemplate(editor, template, false, null, new TemplateEditingAdapter() {

                @Override
                public void templateFinished(Template template, boolean brokenOff) {
                    if (!brokenOff) {
                        runnable.run();
                    }
                }
            });
        }
    }.execute();
}
Also used : WriteCommandAction(com.intellij.openapi.command.WriteCommandAction) Project(com.intellij.openapi.project.Project) TypeExpression(com.intellij.codeInsight.intention.impl.TypeExpression) Result(com.intellij.openapi.application.Result)

Example 2 with TypeExpression

use of com.intellij.codeInsight.intention.impl.TypeExpression in project intellij-community by JetBrains.

the class CreatePropertyFromUsageFix method invokeImpl.

@Override
protected void invokeImpl(PsiClass targetClass) {
    PsiManager manager = myMethodCall.getManager();
    final Project project = manager.getProject();
    PsiElementFactory factory = JavaPsiFacade.getInstance(manager.getProject()).getElementFactory();
    boolean isStatic = false;
    PsiExpression qualifierExpression = myMethodCall.getMethodExpression().getQualifierExpression();
    if (qualifierExpression != null) {
        PsiReference reference = qualifierExpression.getReference();
        if (reference != null) {
            isStatic = reference.resolve() instanceof PsiClass;
        }
    } else {
        PsiMethod method = PsiTreeUtil.getParentOfType(myMethodCall, PsiMethod.class);
        if (method != null) {
            isStatic = method.hasModifierProperty(PsiModifier.STATIC);
        }
    }
    String fieldName = getVariableName(myMethodCall, isStatic);
    LOG.assertTrue(fieldName != null);
    String callText = myMethodCall.getMethodExpression().getReferenceName();
    LOG.assertTrue(callText != null, myMethodCall.getMethodExpression());
    PsiType[] expectedTypes;
    PsiType type;
    PsiField field = targetClass.findFieldByName(fieldName, true);
    if (callText.startsWith(GET_PREFIX)) {
        expectedTypes = field != null ? new PsiType[] { field.getType() } : CreateFromUsageUtils.guessType(myMethodCall, false);
        type = expectedTypes[0];
    } else if (callText.startsWith(IS_PREFIX)) {
        type = PsiType.BOOLEAN;
        expectedTypes = new PsiType[] { type };
    } else {
        type = RefactoringUtil.getTypeByExpression(myMethodCall.getArgumentList().getExpressions()[0]);
        if (type == null || PsiType.NULL.equals(type))
            type = PsiType.getJavaLangObject(manager, myMethodCall.getResolveScope());
        expectedTypes = new PsiType[] { type };
    }
    positionCursor(project, targetClass.getContainingFile(), targetClass);
    IdeDocumentHistory.getInstance(project).includeCurrentPlaceAsChangePlace();
    if (field == null) {
        field = factory.createField(fieldName, type);
        PsiUtil.setModifierProperty(field, PsiModifier.STATIC, isStatic);
    }
    PsiMethod accessor;
    PsiElement fieldReference;
    PsiElement typeReference;
    PsiCodeBlock body;
    if (callText.startsWith(GET_PREFIX) || callText.startsWith(IS_PREFIX)) {
        accessor = (PsiMethod) targetClass.add(GenerateMembersUtil.generateSimpleGetterPrototype(field));
        body = accessor.getBody();
        LOG.assertTrue(body != null, accessor.getText());
        fieldReference = ((PsiReturnStatement) body.getStatements()[0]).getReturnValue();
        typeReference = accessor.getReturnTypeElement();
    } else {
        accessor = (PsiMethod) targetClass.add(GenerateMembersUtil.generateSimpleSetterPrototype(field, targetClass));
        body = accessor.getBody();
        LOG.assertTrue(body != null, accessor.getText());
        PsiAssignmentExpression expr = (PsiAssignmentExpression) ((PsiExpressionStatement) body.getStatements()[0]).getExpression();
        fieldReference = ((PsiReferenceExpression) expr.getLExpression()).getReferenceNameElement();
        typeReference = accessor.getParameterList().getParameters()[0].getTypeElement();
    }
    accessor.setName(callText);
    PsiUtil.setModifierProperty(accessor, PsiModifier.STATIC, isStatic);
    TemplateBuilderImpl builder = new TemplateBuilderImpl(accessor);
    builder.replaceElement(typeReference, TYPE_VARIABLE, new TypeExpression(project, expectedTypes), true);
    builder.replaceElement(fieldReference, FIELD_VARIABLE, new FieldExpression(field, targetClass, expectedTypes), true);
    builder.setEndVariableAfter(body.getLBrace());
    accessor = CodeInsightUtilCore.forcePsiPostprocessAndRestoreElement(accessor);
    LOG.assertTrue(accessor != null);
    targetClass = accessor.getContainingClass();
    LOG.assertTrue(targetClass != null);
    Template template = builder.buildTemplate();
    TextRange textRange = accessor.getTextRange();
    final PsiFile file = targetClass.getContainingFile();
    final Editor editor = positionCursor(project, targetClass.getContainingFile(), accessor);
    if (editor == null)
        return;
    editor.getDocument().deleteString(textRange.getStartOffset(), textRange.getEndOffset());
    editor.getCaretModel().moveToOffset(textRange.getStartOffset());
    final boolean isStatic1 = isStatic;
    startTemplate(editor, template, project, new TemplateEditingAdapter() {

        @Override
        public void beforeTemplateFinished(final TemplateState state, Template template) {
            ApplicationManager.getApplication().runWriteAction(() -> {
                String fieldName1 = state.getVariableValue(FIELD_VARIABLE).getText();
                if (!PsiNameHelper.getInstance(project).isIdentifier(fieldName1))
                    return;
                String fieldType = state.getVariableValue(TYPE_VARIABLE).getText();
                PsiElement element = file.findElementAt(editor.getCaretModel().getOffset());
                PsiClass aClass = PsiTreeUtil.getParentOfType(element, PsiClass.class);
                if (aClass == null)
                    return;
                PsiField field1 = aClass.findFieldByName(fieldName1, true);
                if (field1 != null) {
                    CreatePropertyFromUsageFix.this.beforeTemplateFinished(aClass, field1);
                    return;
                }
                PsiElementFactory factory1 = JavaPsiFacade.getInstance(aClass.getProject()).getElementFactory();
                try {
                    PsiType type1 = factory1.createTypeFromText(fieldType, aClass);
                    try {
                        field1 = factory1.createField(fieldName1, type1);
                        field1 = (PsiField) aClass.add(field1);
                        PsiUtil.setModifierProperty(field1, PsiModifier.STATIC, isStatic1);
                        CreatePropertyFromUsageFix.this.beforeTemplateFinished(aClass, field1);
                    } catch (IncorrectOperationException e) {
                        LOG.error(e);
                    }
                } catch (IncorrectOperationException e) {
                }
            });
        }

        @Override
        public void templateFinished(Template template, boolean brokenOff) {
            PsiDocumentManager.getInstance(project).commitDocument(editor.getDocument());
            final int offset = editor.getCaretModel().getOffset();
            final PsiMethod generatedMethod = PsiTreeUtil.findElementOfClassAtOffset(file, offset, PsiMethod.class, false);
            if (generatedMethod != null) {
                ApplicationManager.getApplication().runWriteAction(() -> {
                    CodeStyleManager.getInstance(project).reformat(generatedMethod);
                });
            }
        }
    });
}
Also used : TypeExpression(com.intellij.codeInsight.intention.impl.TypeExpression) TextRange(com.intellij.openapi.util.TextRange) TemplateState(com.intellij.codeInsight.template.impl.TemplateState) Project(com.intellij.openapi.project.Project) IncorrectOperationException(com.intellij.util.IncorrectOperationException) Editor(com.intellij.openapi.editor.Editor)

Example 3 with TypeExpression

use of com.intellij.codeInsight.intention.impl.TypeExpression in project intellij-community by JetBrains.

the class GuessTypeParameters method setupTypeElement.

public void setupTypeElement(PsiTypeElement typeElement, ExpectedTypeInfo[] infos, PsiSubstitutor substitutor, TemplateBuilder builder, @Nullable PsiElement context, PsiClass targetClass) {
    LOG.assertTrue(typeElement.isValid());
    ApplicationManager.getApplication().assertWriteAccessAllowed();
    PsiManager manager = typeElement.getManager();
    GlobalSearchScope scope = typeElement.getResolveScope();
    Project project = manager.getProject();
    if (infos.length == 1 && substitutor != null && substitutor != PsiSubstitutor.EMPTY) {
        ExpectedTypeInfo info = infos[0];
        Map<PsiTypeParameter, PsiType> map = substitutor.getSubstitutionMap();
        PsiType[] vals = map.values().toArray(PsiType.createArray(map.size()));
        PsiTypeParameter[] params = map.keySet().toArray(new PsiTypeParameter[map.size()]);
        List<PsiType> types = matchingTypeParameters(vals, params, info);
        if (!types.isEmpty()) {
            ContainerUtil.addAll(types, ExpectedTypesProvider.processExpectedTypes(infos, new MyTypeVisitor(manager, scope), project));
            builder.replaceElement(typeElement, new TypeExpression(project, types.toArray(PsiType.createArray(types.size()))));
            return;
        } else {
            PsiElementFactory factory = JavaPsiFacade.getInstance(manager.getProject()).getElementFactory();
            PsiType type = info.getType();
            PsiType defaultType = info.getDefaultType();
            try {
                PsiTypeElement inplaceTypeElement = ((PsiVariable) factory.createVariableDeclarationStatement("foo", type, null).getDeclaredElements()[0]).getTypeElement();
                PsiSubstitutor rawingSubstitutor = getRawingSubstitutor(context, targetClass);
                int substitionResult = substituteToTypeParameters(typeElement, inplaceTypeElement, vals, params, builder, rawingSubstitutor, true);
                if (substitionResult != SUBSTITUTED_NONE) {
                    if (substitionResult == SUBSTITUTED_IN_PARAMETERS) {
                        PsiJavaCodeReferenceElement refElement = typeElement.getInnermostComponentReferenceElement();
                        LOG.assertTrue(refElement != null && refElement.getReferenceNameElement() != null);
                        type = getComponentType(type);
                        LOG.assertTrue(type != null);
                        defaultType = getComponentType(defaultType);
                        LOG.assertTrue(defaultType != null);
                        ExpectedTypeInfo info1 = ExpectedTypesProvider.createInfo(((PsiClassType) defaultType).rawType(), ExpectedTypeInfo.TYPE_STRICTLY, ((PsiClassType) defaultType).rawType(), info.getTailType());
                        MyTypeVisitor visitor = new MyTypeVisitor(manager, scope);
                        builder.replaceElement(refElement.getReferenceNameElement(), new TypeExpression(project, ExpectedTypesProvider.processExpectedTypes(new ExpectedTypeInfo[] { info1 }, visitor, project)));
                    }
                    return;
                }
            } catch (IncorrectOperationException e) {
                LOG.error(e);
            }
        }
    }
    PsiType[] types = infos.length == 0 ? new PsiType[] { typeElement.getType() } : ExpectedTypesProvider.processExpectedTypes(infos, new MyTypeVisitor(manager, scope), project);
    builder.replaceElement(typeElement, new TypeExpression(project, types));
}
Also used : TypeExpression(com.intellij.codeInsight.intention.impl.TypeExpression) Project(com.intellij.openapi.project.Project) ExpectedTypeInfo(com.intellij.codeInsight.ExpectedTypeInfo) GlobalSearchScope(com.intellij.psi.search.GlobalSearchScope) IncorrectOperationException(com.intellij.util.IncorrectOperationException)

Example 4 with TypeExpression

use of com.intellij.codeInsight.intention.impl.TypeExpression in project intellij-community by JetBrains.

the class TryWithResourcesPostfixTemplate method expand.

@Override
public void expand(@NotNull PsiElement context, @NotNull Editor editor) {
    PsiExpression expression = JavaPostfixTemplatesUtils.getTopmostExpression(context);
    assert expression != null;
    Project project = context.getProject();
    editor.getDocument().deleteString(expression.getTextRange().getStartOffset(), expression.getTextRange().getEndOffset());
    TemplateManager manager = TemplateManager.getInstance(project);
    Template template = manager.createTemplate("", "");
    template.setToReformat(true);
    template.addTextSegment("try (");
    MacroCallNode name = new MacroCallNode(new SuggestVariableNameMacro());
    template.addVariable("type", new TypeExpression(project, new PsiType[] { expression.getType() }), false);
    template.addTextSegment(" ");
    template.addVariable("name", name, name, true);
    template.addTextSegment(" = ");
    template.addVariable("variable", new TextExpression(expression.getText()), false);
    template.addTextSegment(") {\n");
    template.addEndVariable();
    template.addTextSegment("\n}");
    Collection<PsiClassType> unhandled = getUnhandled(expression);
    for (PsiClassType exception : unhandled) {
        MacroCallNode variable = new MacroCallNode(new SuggestVariableNameMacro());
        template.addTextSegment("catch(");
        template.addVariable("type " + exception.getClassName(), new TypeExpression(project, new PsiType[] { exception }), false);
        template.addTextSegment(" ");
        template.addVariable("name " + exception.getClassName(), variable, variable, false);
        template.addTextSegment(") {}");
    }
    manager.startTemplate(editor, template);
}
Also used : Project(com.intellij.openapi.project.Project) TypeExpression(com.intellij.codeInsight.intention.impl.TypeExpression) TemplateManager(com.intellij.codeInsight.template.TemplateManager) SuggestVariableNameMacro(com.intellij.codeInsight.template.macro.SuggestVariableNameMacro) MacroCallNode(com.intellij.codeInsight.template.impl.MacroCallNode) TextExpression(com.intellij.codeInsight.template.impl.TextExpression) Template(com.intellij.codeInsight.template.Template)

Example 5 with TypeExpression

use of com.intellij.codeInsight.intention.impl.TypeExpression in project intellij-community by JetBrains.

the class ChangeClassParametersIntention method invoke.

@Override
public void invoke(@NotNull final Project project, final Editor editor, @NotNull final PsiElement element) throws IncorrectOperationException {
    final PsiTypeElement typeElement = PsiTreeUtil.getTopmostParentOfType(element, PsiTypeElement.class);
    final PsiReferenceParameterList parameterList = PsiTreeUtil.getParentOfType(typeElement, PsiReferenceParameterList.class);
    if (parameterList != null) {
        final PsiClass aClass = PsiTreeUtil.getParentOfType(element, PsiClass.class);
        if (aClass instanceof PsiAnonymousClass) {
            editor.getCaretModel().moveToOffset(aClass.getTextOffset());
            final PsiTypeElement[] typeElements = parameterList.getTypeParameterElements();
            final int changeIdx = ArrayUtil.find(typeElements, typeElement);
            final PsiClassType.ClassResolveResult result = ((PsiAnonymousClass) aClass).getBaseClassType().resolveGenerics();
            final PsiClass baseClass = result.getElement();
            LOG.assertTrue(baseClass != null);
            final PsiTypeParameter typeParameter = baseClass.getTypeParameters()[changeIdx];
            final TemplateBuilderImpl templateBuilder = (TemplateBuilderImpl) TemplateBuilderFactory.getInstance().createTemplateBuilder(aClass);
            final String oldTypeText = typeElement.getText();
            final String varName = "param";
            templateBuilder.replaceElement(typeElement, varName, new TypeExpression(project, new PsiType[] { typeElement.getType() }), true);
            final Template template = templateBuilder.buildInlineTemplate();
            TemplateManager.getInstance(project).startTemplate(editor, template, false, null, new TemplateEditingAdapter() {

                private String myNewType;

                @Override
                public void beforeTemplateFinished(TemplateState state, Template template) {
                    final TextResult value = state.getVariableValue(varName);
                    myNewType = value != null ? value.getText() : "";
                    final int segmentsCount = state.getSegmentsCount();
                    final Document document = state.getEditor().getDocument();
                    ApplicationManager.getApplication().runWriteAction(() -> {
                        for (int i = 0; i < segmentsCount; i++) {
                            final TextRange segmentRange = state.getSegmentRange(i);
                            document.replaceString(segmentRange.getStartOffset(), segmentRange.getEndOffset(), oldTypeText);
                        }
                    });
                }

                @Override
                public void templateFinished(Template template, boolean brokenOff) {
                    if (!brokenOff) {
                        final PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(project);
                        try {
                            final PsiType targetParam = elementFactory.createTypeFromText(myNewType, aClass);
                            if (!(targetParam instanceof PsiClassType)) {
                                HintManager.getInstance().showErrorHint(editor, JavaErrorMessages.message("generics.type.argument.cannot.be.of.primitive.type"));
                                return;
                            }
                            final PsiClassType classType = (PsiClassType) targetParam;
                            final PsiClass target = classType.resolve();
                            if (target == null) {
                                HintManager.getInstance().showErrorHint(editor, JavaErrorMessages.message("cannot.resolve.symbol", classType.getPresentableText()));
                                return;
                            }
                            final TypeMigrationRules myRules = new TypeMigrationRules();
                            final PsiSubstitutor substitutor = result.getSubstitutor().put(typeParameter, targetParam);
                            final PsiType targetClassType = elementFactory.createType(baseClass, substitutor);
                            myRules.setBoundScope(new LocalSearchScope(aClass));
                            TypeMigrationProcessor.runHighlightingTypeMigration(project, editor, myRules, ((PsiAnonymousClass) aClass).getBaseClassReference().getParameterList(), targetClassType);
                        } catch (IncorrectOperationException e) {
                            HintManager.getInstance().showErrorHint(editor, "Incorrect type");
                        }
                    }
                }
            });
        }
    }
}
Also used : TypeMigrationRules(com.intellij.refactoring.typeMigration.TypeMigrationRules) Document(com.intellij.openapi.editor.Document) LocalSearchScope(com.intellij.psi.search.LocalSearchScope) TypeExpression(com.intellij.codeInsight.intention.impl.TypeExpression) TextRange(com.intellij.openapi.util.TextRange) TemplateState(com.intellij.codeInsight.template.impl.TemplateState) IncorrectOperationException(com.intellij.util.IncorrectOperationException)

Aggregations

TypeExpression (com.intellij.codeInsight.intention.impl.TypeExpression)7 Project (com.intellij.openapi.project.Project)6 TextRange (com.intellij.openapi.util.TextRange)3 IncorrectOperationException (com.intellij.util.IncorrectOperationException)3 Template (com.intellij.codeInsight.template.Template)2 TemplateState (com.intellij.codeInsight.template.impl.TemplateState)2 Editor (com.intellij.openapi.editor.Editor)2 ExpectedTypeInfo (com.intellij.codeInsight.ExpectedTypeInfo)1 TemplateBuilderImpl (com.intellij.codeInsight.template.TemplateBuilderImpl)1 TemplateEditingAdapter (com.intellij.codeInsight.template.TemplateEditingAdapter)1 TemplateManager (com.intellij.codeInsight.template.TemplateManager)1 MacroCallNode (com.intellij.codeInsight.template.impl.MacroCallNode)1 TextExpression (com.intellij.codeInsight.template.impl.TextExpression)1 SuggestVariableNameMacro (com.intellij.codeInsight.template.macro.SuggestVariableNameMacro)1 Result (com.intellij.openapi.application.Result)1 WriteCommandAction (com.intellij.openapi.command.WriteCommandAction)1 Document (com.intellij.openapi.editor.Document)1 GlobalSearchScope (com.intellij.psi.search.GlobalSearchScope)1 LocalSearchScope (com.intellij.psi.search.LocalSearchScope)1 TypeMigrationRules (com.intellij.refactoring.typeMigration.TypeMigrationRules)1