Search in sources :

Example 26 with JavaCodeStyleManager

use of com.intellij.psi.codeStyle.JavaCodeStyleManager in project intellij-community by JetBrains.

the class JavaIntroduceVariableTest method doTest.

protected static void doTest(String expression, VariableKind kind, PsiType type, String... results) throws Exception {
    final PsiElementFactory factory = JavaPsiFacade.getElementFactory(getProject());
    final PsiExpression expr = factory.createExpressionFromText(expression, null);
    final JavaCodeStyleManager codeStyleManager = JavaCodeStyleManager.getInstance(getProject());
    final SuggestedNameInfo info = codeStyleManager.suggestVariableName(kind, null, expr, type);
    assert info.names.length >= results.length : msg("Can't find some variants", info.names, results);
    for (int i = 0; i < results.length; i++) {
        if (!results[i].equals(info.names[i])) {
            throw new Exception(msg("", info.names, results));
        }
    }
}
Also used : PsiExpression(com.intellij.psi.PsiExpression) JavaCodeStyleManager(com.intellij.psi.codeStyle.JavaCodeStyleManager) PsiElementFactory(com.intellij.psi.PsiElementFactory) SuggestedNameInfo(com.intellij.psi.codeStyle.SuggestedNameInfo)

Example 27 with JavaCodeStyleManager

use of com.intellij.psi.codeStyle.JavaCodeStyleManager in project intellij-community by JetBrains.

the class GenerateConstructorHandler method generateConstructorPrototype.

public static PsiMethod generateConstructorPrototype(PsiClass aClass, PsiMethod baseConstructor, boolean copyJavaDoc, PsiField[] fields) throws IncorrectOperationException {
    PsiManager manager = aClass.getManager();
    Project project = aClass.getProject();
    JVMElementFactory factory = JVMElementFactories.requireFactory(aClass.getLanguage(), project);
    CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(manager.getProject());
    String className = aClass.getName();
    assert className != null : aClass;
    PsiMethod constructor = factory.createConstructor(className, aClass);
    GenerateMembersUtil.setVisibility(aClass, constructor);
    if (baseConstructor != null) {
        PsiJavaCodeReferenceElement[] throwRefs = baseConstructor.getThrowsList().getReferenceElements();
        for (PsiJavaCodeReferenceElement ref : throwRefs) {
            constructor.getThrowsList().add(ref);
        }
        if (copyJavaDoc) {
            final PsiDocComment docComment = ((PsiMethod) baseConstructor.getNavigationElement()).getDocComment();
            if (docComment != null) {
                constructor.addAfter(docComment, null);
            }
        }
    }
    boolean isNotEnum = false;
    if (baseConstructor != null) {
        PsiClass superClass = aClass.getSuperClass();
        LOG.assertTrue(superClass != null);
        if (!CommonClassNames.JAVA_LANG_ENUM.equals(superClass.getQualifiedName())) {
            isNotEnum = true;
            if (baseConstructor instanceof PsiCompiledElement) {
                // to get some parameter names
                PsiClass dummyClass = JVMElementFactories.requireFactory(baseConstructor.getLanguage(), project).createClass("Dummy");
                baseConstructor = (PsiMethod) dummyClass.add(baseConstructor);
            }
            PsiParameter[] params = baseConstructor.getParameterList().getParameters();
            for (PsiParameter param : params) {
                String name = param.getName();
                assert name != null : param;
                PsiParameter newParam = factory.createParameter(name, param.getType(), aClass);
                GenerateMembersUtil.copyOrReplaceModifierList(param, aClass, newParam);
                constructor.getParameterList().add(newParam);
            }
        }
    }
    JavaCodeStyleManager javaStyle = JavaCodeStyleManager.getInstance(project);
    final PsiMethod dummyConstructor = factory.createConstructor(className);
    dummyConstructor.getParameterList().replace(constructor.getParameterList().copy());
    List<PsiParameter> fieldParams = new ArrayList<>();
    for (PsiField field : fields) {
        String fieldName = field.getName();
        assert fieldName != null : field;
        String name = javaStyle.variableNameToPropertyName(fieldName, VariableKind.FIELD);
        String parmName = javaStyle.propertyNameToVariableName(name, VariableKind.PARAMETER);
        parmName = javaStyle.suggestUniqueVariableName(parmName, dummyConstructor, true);
        PsiParameter parm = factory.createParameter(parmName, field.getType(), aClass);
        NullableNotNullManager.getInstance(project).copyNotNullAnnotation(field, parm);
        if (constructor.isVarArgs()) {
            final PsiParameterList parameterList = constructor.getParameterList();
            parameterList.addBefore(parm, parameterList.getParameters()[parameterList.getParametersCount() - 1]);
            final PsiParameterList dummyParameterList = dummyConstructor.getParameterList();
            dummyParameterList.addBefore(parm.copy(), dummyParameterList.getParameters()[dummyParameterList.getParametersCount() - 1]);
        } else {
            constructor.getParameterList().add(parm);
            dummyConstructor.getParameterList().add(parm.copy());
        }
        fieldParams.add(parm);
    }
    ConstructorBodyGenerator generator = ConstructorBodyGenerator.INSTANCE.forLanguage(aClass.getLanguage());
    if (generator != null) {
        StringBuilder buffer = new StringBuilder();
        generator.start(buffer, constructor.getName(), PsiParameter.EMPTY_ARRAY);
        if (isNotEnum) {
            generator.generateSuperCallIfNeeded(buffer, baseConstructor.getParameterList().getParameters());
        }
        final PsiParameter[] parameters = fieldParams.toArray(new PsiParameter[fieldParams.size()]);
        final List<String> existingNames = ContainerUtil.map(dummyConstructor.getParameterList().getParameters(), parameter -> parameter.getName());
        if (generator instanceof ConstructorBodyGeneratorEx) {
            ((ConstructorBodyGeneratorEx) generator).generateFieldInitialization(buffer, fields, parameters, existingNames);
        } else {
            generator.generateFieldInitialization(buffer, fields, parameters);
        }
        generator.finish(buffer);
        PsiMethod stub = factory.createMethodFromText(buffer.toString(), aClass);
        PsiCodeBlock original = constructor.getBody(), replacement = stub.getBody();
        assert original != null : constructor;
        assert replacement != null : stub;
        original.replace(replacement);
    }
    constructor = (PsiMethod) codeStyleManager.reformat(constructor);
    return constructor;
}
Also used : PsiDocComment(com.intellij.psi.javadoc.PsiDocComment) JavaCodeStyleManager(com.intellij.psi.codeStyle.JavaCodeStyleManager) CodeStyleManager(com.intellij.psi.codeStyle.CodeStyleManager) ArrayList(java.util.ArrayList) Project(com.intellij.openapi.project.Project) JavaCodeStyleManager(com.intellij.psi.codeStyle.JavaCodeStyleManager)

Example 28 with JavaCodeStyleManager

use of com.intellij.psi.codeStyle.JavaCodeStyleManager in project intellij-community by JetBrains.

the class ExtractMethodObjectProcessor method createField.

private PsiField createField(PsiParameter parameter, PsiMethod constructor, boolean isFinal) {
    final String parameterName = parameter.getName();
    PsiType type = parameter.getType();
    if (type instanceof PsiEllipsisType)
        type = ((PsiEllipsisType) type).toArrayType();
    try {
        final JavaCodeStyleManager styleManager = JavaCodeStyleManager.getInstance(getMethod().getProject());
        final String fieldName = styleManager.suggestVariableName(VariableKind.FIELD, styleManager.variableNameToPropertyName(parameterName, VariableKind.PARAMETER), null, type).names[0];
        PsiField field = myElementFactory.createField(fieldName, type);
        final PsiModifierList modifierList = field.getModifierList();
        LOG.assertTrue(modifierList != null);
        final NullableNotNullManager manager = NullableNotNullManager.getInstance(myProject);
        if (manager.isNullable(parameter, false)) {
            modifierList.addAfter(myElementFactory.createAnnotationFromText("@" + manager.getDefaultNullable(), field), null);
        }
        modifierList.setModifierProperty(PsiModifier.FINAL, isFinal);
        final PsiCodeBlock methodBody = constructor.getBody();
        LOG.assertTrue(methodBody != null);
        @NonNls final String stmtText;
        if (Comparing.strEqual(parameterName, fieldName)) {
            stmtText = "this." + fieldName + " = " + parameterName + ";";
        } else {
            stmtText = fieldName + " = " + parameterName + ";";
        }
        PsiStatement assignmentStmt = myElementFactory.createStatementFromText(stmtText, methodBody);
        assignmentStmt = (PsiStatement) CodeStyleManager.getInstance(constructor.getProject()).reformat(assignmentStmt);
        methodBody.add(assignmentStmt);
        field = (PsiField) myInnerClass.add(field);
        return field;
    } catch (IncorrectOperationException e) {
        LOG.error(e);
    }
    return null;
}
Also used : NonNls(org.jetbrains.annotations.NonNls) NullableNotNullManager(com.intellij.codeInsight.NullableNotNullManager) JavaCodeStyleManager(com.intellij.psi.codeStyle.JavaCodeStyleManager) IncorrectOperationException(com.intellij.util.IncorrectOperationException)

Example 29 with JavaCodeStyleManager

use of com.intellij.psi.codeStyle.JavaCodeStyleManager in project intellij-community by JetBrains.

the class DefaultQuickFixProvider method registerPriorityActions.

private static void registerPriorityActions(@NotNull QuickFixActionRegistrar registrar, @NotNull TextRange fixRange, @NotNull PsiReferenceExpression refExpr) {
    final JavaCodeStyleManager styleManager = JavaCodeStyleManager.getInstance(refExpr.getProject());
    final Map<VariableKind, IntentionAction> map = new EnumMap<>(VariableKind.class);
    map.put(VariableKind.FIELD, new CreateFieldFromUsageFix(refExpr));
    map.put(VariableKind.STATIC_FINAL_FIELD, new CreateConstantFieldFromUsageFix(refExpr));
    if (!refExpr.isQualified()) {
        map.put(VariableKind.LOCAL_VARIABLE, new CreateLocalFromUsageFix(refExpr));
        map.put(VariableKind.PARAMETER, new CreateParameterFromUsageFix(refExpr));
    }
    final VariableKind kind = getKind(styleManager, refExpr);
    if (map.containsKey(kind)) {
        map.put(kind, PriorityIntentionActionWrapper.highPriority(map.get(kind)));
    }
    for (IntentionAction action : map.values()) {
        registrar.register(fixRange, action, null);
    }
}
Also used : JavaCodeStyleManager(com.intellij.psi.codeStyle.JavaCodeStyleManager) IntentionAction(com.intellij.codeInsight.intention.IntentionAction) EnumMap(java.util.EnumMap) VariableKind(com.intellij.psi.codeStyle.VariableKind)

Example 30 with JavaCodeStyleManager

use of com.intellij.psi.codeStyle.JavaCodeStyleManager in project intellij-community by JetBrains.

the class AddExceptionToCatchFix method addCatchStatement.

private static PsiCodeBlock addCatchStatement(PsiTryStatement tryStatement, PsiClassType exceptionType, PsiFile file) throws IncorrectOperationException {
    PsiElementFactory factory = JavaPsiFacade.getInstance(tryStatement.getProject()).getElementFactory();
    if (tryStatement.getTryBlock() == null) {
        addTryBlock(tryStatement, factory);
    }
    JavaCodeStyleManager styleManager = JavaCodeStyleManager.getInstance(tryStatement.getProject());
    String name = styleManager.suggestVariableName(VariableKind.PARAMETER, null, null, exceptionType).names[0];
    name = styleManager.suggestUniqueVariableName(name, tryStatement, false);
    PsiCatchSection catchSection = factory.createCatchSection(exceptionType, name, file);
    PsiCodeBlock finallyBlock = tryStatement.getFinallyBlock();
    if (finallyBlock == null) {
        tryStatement.add(catchSection);
    } else {
        tryStatement.addBefore(catchSection, getFinallySectionStart(finallyBlock));
    }
    PsiParameter[] parameters = tryStatement.getCatchBlockParameters();
    PsiTypeElement typeElement = parameters[parameters.length - 1].getTypeElement();
    if (typeElement != null) {
        JavaCodeStyleManager.getInstance(file.getProject()).shortenClassReferences(typeElement);
    }
    PsiCodeBlock[] catchBlocks = tryStatement.getCatchBlocks();
    return catchBlocks[catchBlocks.length - 1];
}
Also used : JavaCodeStyleManager(com.intellij.psi.codeStyle.JavaCodeStyleManager)

Aggregations

JavaCodeStyleManager (com.intellij.psi.codeStyle.JavaCodeStyleManager)96 Project (com.intellij.openapi.project.Project)27 SuggestedNameInfo (com.intellij.psi.codeStyle.SuggestedNameInfo)21 VariableKind (com.intellij.psi.codeStyle.VariableKind)19 IncorrectOperationException (com.intellij.util.IncorrectOperationException)15 NotNull (org.jetbrains.annotations.NotNull)13 CodeStyleManager (com.intellij.psi.codeStyle.CodeStyleManager)12 Nullable (org.jetbrains.annotations.Nullable)12 ArrayList (java.util.ArrayList)10 NonNls (org.jetbrains.annotations.NonNls)8 StringUtil (com.intellij.openapi.util.text.StringUtil)3 UniqueNameGenerator (com.intellij.util.text.UniqueNameGenerator)3 HashSet (java.util.HashSet)3 JavaLanguage (com.intellij.lang.java.JavaLanguage)2 Logger (com.intellij.openapi.diagnostic.Logger)2 Editor (com.intellij.openapi.editor.Editor)2 Comparing (com.intellij.openapi.util.Comparing)2 com.intellij.psi (com.intellij.psi)2 CodeStyleSettings (com.intellij.psi.codeStyle.CodeStyleSettings)2 FunctionalInterfaceParameterizationUtil (com.intellij.psi.impl.source.resolve.graphInference.FunctionalInterfaceParameterizationUtil)2