Search in sources :

Example 6 with TypeExpression

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

the class GuessTypeParameters method substituteToTypeParameters.

private int substituteToTypeParameters(PsiTypeElement typeElement, PsiTypeElement inplaceTypeElement, PsiType[] paramVals, PsiTypeParameter[] params, TemplateBuilder builder, PsiSubstitutor rawingSubstitutor, boolean toplevel) {
    PsiType type = inplaceTypeElement.getType();
    List<PsiType> types = new ArrayList<>();
    for (int i = 0; i < paramVals.length; i++) {
        PsiType val = paramVals[i];
        if (val == null)
            return SUBSTITUTED_NONE;
        if (type.equals(val)) {
            types.add(myFactory.createType(params[i]));
        }
    }
    if (!types.isEmpty()) {
        Project project = typeElement.getProject();
        PsiType substituted = rawingSubstitutor.substitute(type);
        if (!CommonClassNames.JAVA_LANG_OBJECT.equals(substituted.getCanonicalText()) && (toplevel || substituted.equals(type))) {
            types.add(substituted);
        }
        builder.replaceElement(typeElement, new TypeExpression(project, types.toArray(PsiType.createArray(types.size()))));
        return toplevel ? SUBSTITUTED_IN_REF : SUBSTITUTED_IN_PARAMETERS;
    }
    boolean substituted = false;
    PsiJavaCodeReferenceElement ref = typeElement.getInnermostComponentReferenceElement();
    PsiJavaCodeReferenceElement inplaceRef = inplaceTypeElement.getInnermostComponentReferenceElement();
    if (ref != null) {
        LOG.assertTrue(inplaceRef != null);
        PsiTypeElement[] innerTypeElements = ref.getParameterList().getTypeParameterElements();
        PsiTypeElement[] inplaceInnerTypeElements = inplaceRef.getParameterList().getTypeParameterElements();
        for (int i = 0; i < innerTypeElements.length; i++) {
            substituted |= substituteToTypeParameters(innerTypeElements[i], inplaceInnerTypeElements[i], paramVals, params, builder, rawingSubstitutor, false) != SUBSTITUTED_NONE;
        }
    }
    return substituted ? SUBSTITUTED_IN_PARAMETERS : SUBSTITUTED_NONE;
}
Also used : Project(com.intellij.openapi.project.Project) TypeExpression(com.intellij.codeInsight.intention.impl.TypeExpression) ArrayList(java.util.ArrayList)

Example 7 with TypeExpression

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

the class CreateLocalFromUsageFix method invokeImpl.

@Override
protected void invokeImpl(final PsiClass targetClass) {
    if (CreateFromUsageUtils.isValidReference(myReferenceExpression, false)) {
        return;
    }
    final Project project = myReferenceExpression.getProject();
    PsiElementFactory factory = JavaPsiFacade.getInstance(project).getElementFactory();
    final PsiFile targetFile = targetClass.getContainingFile();
    PsiType[] expectedTypes = CreateFromUsageUtils.guessType(myReferenceExpression, false);
    final SmartTypePointer defaultType = SmartTypePointerManager.getInstance(project).createSmartTypePointer(expectedTypes[0]);
    final PsiType preferredType = TypeSelectorManagerImpl.getPreferredType(expectedTypes, expectedTypes[0]);
    PsiType type = preferredType != null ? preferredType : expectedTypes[0];
    if (LambdaUtil.notInferredType(type)) {
        type = PsiType.getJavaLangObject(myReferenceExpression.getManager(), targetClass.getResolveScope());
    }
    String varName = myReferenceExpression.getReferenceName();
    PsiExpression initializer = null;
    boolean isInline = false;
    PsiExpression[] expressions = CreateFromUsageUtils.collectExpressions(myReferenceExpression, PsiMember.class, PsiFile.class);
    PsiStatement anchor = getAnchor(expressions);
    if (anchor instanceof PsiExpressionStatement && ((PsiExpressionStatement) anchor).getExpression() instanceof PsiAssignmentExpression) {
        PsiAssignmentExpression assignment = (PsiAssignmentExpression) ((PsiExpressionStatement) anchor).getExpression();
        if (assignment.getLExpression().textMatches(myReferenceExpression)) {
            initializer = assignment.getRExpression();
            isInline = true;
        }
    }
    PsiDeclarationStatement decl = factory.createVariableDeclarationStatement(varName, type, initializer);
    TypeExpression expression = new TypeExpression(project, expectedTypes);
    if (isInline) {
        final PsiExpression expr = ((PsiExpressionStatement) anchor).getExpression();
        final PsiElement semicolon = expr.getNextSibling();
        if (semicolon != null) {
            final PsiElement nextSibling = semicolon.getNextSibling();
            if (nextSibling != null) {
                decl.addRange(nextSibling, anchor.getLastChild());
            }
        }
        decl = (PsiDeclarationStatement) anchor.replace(decl);
    } else {
        decl = (PsiDeclarationStatement) anchor.getParent().addBefore(decl, anchor);
    }
    PsiVariable var = (PsiVariable) decl.getDeclaredElements()[0];
    boolean isFinal = CodeStyleSettingsManager.getSettings(project).GENERATE_FINAL_LOCALS && !CreateFromUsageUtils.isAccessedForWriting(expressions);
    PsiUtil.setModifierProperty(var, PsiModifier.FINAL, isFinal);
    var = CodeInsightUtilCore.forcePsiPostprocessAndRestoreElement(var);
    if (var == null)
        return;
    TemplateBuilderImpl builder = new TemplateBuilderImpl(var);
    final PsiTypeElement typeElement = var.getTypeElement();
    LOG.assertTrue(typeElement != null);
    builder.replaceElement(typeElement, AbstractJavaInplaceIntroducer.createExpression(expression, typeElement.getText()));
    builder.setEndVariableAfter(var.getNameIdentifier());
    Template template = builder.buildTemplate();
    final Editor newEditor = positionCursor(project, targetFile, var);
    if (newEditor == null)
        return;
    TextRange range = var.getTextRange();
    newEditor.getDocument().deleteString(range.getStartOffset(), range.getEndOffset());
    startTemplate(newEditor, template, project, new TemplateEditingAdapter() {

        @Override
        public void templateFinished(Template template, boolean brokenOff) {
            PsiDocumentManager.getInstance(project).commitDocument(newEditor.getDocument());
            final int offset = newEditor.getCaretModel().getOffset();
            final PsiLocalVariable localVariable = PsiTreeUtil.findElementOfClassAtOffset(targetFile, offset, PsiLocalVariable.class, false);
            if (localVariable != null) {
                TypeSelectorManagerImpl.typeSelected(localVariable.getType(), defaultType.getType());
                ApplicationManager.getApplication().runWriteAction(() -> {
                    CodeStyleManager.getInstance(project).reformat(localVariable);
                });
            }
        }
    });
}
Also used : Template(com.intellij.codeInsight.template.Template) TemplateBuilderImpl(com.intellij.codeInsight.template.TemplateBuilderImpl) TypeExpression(com.intellij.codeInsight.intention.impl.TypeExpression) TemplateEditingAdapter(com.intellij.codeInsight.template.TemplateEditingAdapter) TextRange(com.intellij.openapi.util.TextRange) Project(com.intellij.openapi.project.Project) Editor(com.intellij.openapi.editor.Editor)

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