Search in sources :

Example 66 with JavaCodeStyleManager

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

the class ForEachMigration method migrate.

@Override
PsiElement migrate(@NotNull Project project, @NotNull PsiStatement body, @NotNull TerminalBlock tb) {
    PsiLoopStatement loopStatement = tb.getMainLoop();
    restoreComments(loopStatement, body);
    PsiElementFactory factory = JavaPsiFacade.getElementFactory(project);
    PsiExpression mapExpression = tryExtractMapExpression(tb);
    if (mapExpression != null) {
        PsiMethodCallExpression call = tb.getSingleMethodCall();
        LOG.assertTrue(call != null);
        PsiType addedType = getAddedElementType(call);
        if (addedType == null)
            addedType = call.getType();
        JavaCodeStyleManager codeStyleManager = JavaCodeStyleManager.getInstance(project);
        SuggestedNameInfo suggestedNameInfo = codeStyleManager.suggestVariableName(VariableKind.LOCAL_VARIABLE, null, null, addedType, false);
        if (suggestedNameInfo.names.length == 0) {
            suggestedNameInfo = codeStyleManager.suggestVariableName(VariableKind.LOCAL_VARIABLE, "item", null, null, false);
        }
        String varName = codeStyleManager.suggestUniqueVariableName(suggestedNameInfo, call, false).names[0];
        String streamText = tb.add(new StreamApiMigrationInspection.MapOp(mapExpression, tb.getVariable(), addedType)).generate();
        String forEachBody = varName + "->" + call.getMethodExpression().getText() + "(" + varName + ")";
        String callText = streamText + "." + getReplacement() + "(" + forEachBody + ");";
        return loopStatement.replace(factory.createStatementFromText(callText, loopStatement));
    }
    String stream = tb.generate(true) + "." + getReplacement() + "(";
    PsiElement block = tb.convertToElement(factory);
    final String functionalExpressionText = tb.getVariable().getName() + " -> " + wrapInBlock(block);
    PsiExpressionStatement callStatement = (PsiExpressionStatement) factory.createStatementFromText(stream + functionalExpressionText + ");", loopStatement);
    callStatement = (PsiExpressionStatement) loopStatement.replace(callStatement);
    final PsiExpressionList argumentList = ((PsiCallExpression) callStatement.getExpression()).getArgumentList();
    LOG.assertTrue(argumentList != null, callStatement.getText());
    final PsiExpression[] expressions = argumentList.getExpressions();
    LOG.assertTrue(expressions.length == 1);
    if (expressions[0] instanceof PsiFunctionalExpression && ((PsiFunctionalExpression) expressions[0]).getFunctionalInterfaceType() == null) {
        callStatement = (PsiExpressionStatement) callStatement.replace(factory.createStatementFromText(stream + "(" + tb.getVariable().getText() + ") -> " + wrapInBlock(block) + ");", callStatement));
    }
    return callStatement;
}
Also used : JavaCodeStyleManager(com.intellij.psi.codeStyle.JavaCodeStyleManager) SuggestedNameInfo(com.intellij.psi.codeStyle.SuggestedNameInfo)

Example 67 with JavaCodeStyleManager

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

the class ChangeMethodSignatureFromUsageReverseOrderFix method findNewParamsPlace.

@Override
protected boolean findNewParamsPlace(PsiExpression[] expressions, PsiMethod targetMethod, PsiSubstitutor substitutor, StringBuilder buf, HashSet<ParameterInfoImpl> newParams, PsiParameter[] parameters, List<ParameterInfoImpl> result) {
    // find which parameters to introduce and where
    Set<String> existingNames = new HashSet<>();
    for (PsiParameter parameter : parameters) {
        existingNames.add(parameter.getName());
    }
    int ei = expressions.length - 1;
    int pi = parameters.length - 1;
    final PsiParameter varargParam = targetMethod.isVarArgs() ? parameters[parameters.length - 1] : null;
    final List<String> params = new ArrayList<>();
    while (ei >= 0 || pi >= 0) {
        PsiExpression expression = ei >= 0 ? expressions[ei] : null;
        PsiParameter parameter = pi >= 0 ? parameters[pi] : null;
        PsiType paramType = parameter == null ? null : substitutor.substitute(parameter.getType());
        boolean parameterAssignable = paramType != null && (expression == null || TypeConversionUtil.areTypesAssignmentCompatible(paramType, expression));
        if (parameterAssignable) {
            final PsiType type = parameter.getType();
            result.add(0, new ParameterInfoImpl(pi, parameter.getName(), type));
            params.add(0, escapePresentableType(type));
            pi--;
            ei--;
        } else if (isArgumentInVarargPosition(expressions, ei, varargParam, substitutor)) {
            if (pi == parameters.length - 1) {
                assert varargParam != null;
                final PsiType type = varargParam.getType();
                result.add(0, new ParameterInfoImpl(pi, varargParam.getName(), type));
                params.add(0, escapePresentableType(type));
            }
            pi--;
            ei--;
        } else if (expression != null) {
            if (varargParam != null && pi >= parameters.length)
                return false;
            PsiType exprType = RefactoringUtil.getTypeByExpression(expression);
            if (exprType == null)
                return false;
            JavaCodeStyleManager codeStyleManager = JavaCodeStyleManager.getInstance(expression.getProject());
            String name = suggestUniqueParameterName(codeStyleManager, expression, exprType, existingNames);
            final ParameterInfoImpl newParameterInfo = new ParameterInfoImpl(-1, name, exprType, expression.getText().replace('\n', ' '));
            result.add(0, newParameterInfo);
            newParams.add(newParameterInfo);
            params.add(0, "<b>" + escapePresentableType(exprType) + "</b>");
            ei--;
        }
    }
    if (result.size() != expressions.length && varargParam == null)
        return false;
    buf.append(StringUtil.join(params, ", "));
    return true;
}
Also used : JavaCodeStyleManager(com.intellij.psi.codeStyle.JavaCodeStyleManager) ArrayList(java.util.ArrayList) ParameterInfoImpl(com.intellij.refactoring.changeSignature.ParameterInfoImpl) HashSet(java.util.HashSet)

Example 68 with JavaCodeStyleManager

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

the class ReplaceIteratorForEachLoopWithIteratorForLoopFix method invoke.

@Override
public void invoke(@NotNull Project project, Editor editor, PsiFile file) throws IncorrectOperationException {
    final PsiExpression iteratedValue = myStatement.getIteratedValue();
    if (iteratedValue == null) {
        return;
    }
    final PsiType iteratedValueType = iteratedValue.getType();
    if (iteratedValueType == null) {
        return;
    }
    final PsiParameter iterationParameter = myStatement.getIterationParameter();
    final String iterationParameterName = iterationParameter.getName();
    if (iterationParameterName == null) {
        return;
    }
    final PsiStatement forEachBody = myStatement.getBody();
    final PsiElementFactory elementFactory = JavaPsiFacade.getInstance(project).getElementFactory();
    final JavaCodeStyleManager javaStyleManager = JavaCodeStyleManager.getInstance(project);
    final String name = javaStyleManager.suggestUniqueVariableName("it", myStatement, true);
    PsiForStatement newForLoop = (PsiForStatement) elementFactory.createStatementFromText("for (Iterator " + name + " = initializer; " + name + ".hasNext();) { Object next = " + name + ".next(); }", myStatement);
    final PsiDeclarationStatement newDeclaration = (PsiDeclarationStatement) newForLoop.getInitialization();
    if (newDeclaration == null)
        return;
    final PsiLocalVariable newIteratorVariable = (PsiLocalVariable) newDeclaration.getDeclaredElements()[0];
    final PsiTypeElement newIteratorTypeElement = elementFactory.createTypeElement(iteratedValueType);
    newIteratorVariable.getTypeElement().replace(newIteratorTypeElement);
    newIteratorVariable.setInitializer(iteratedValue);
    final PsiBlockStatement newBody = (PsiBlockStatement) newForLoop.getBody();
    if (newBody == null)
        return;
    final PsiCodeBlock newBodyBlock = newBody.getCodeBlock();
    final PsiDeclarationStatement newFirstStatement = (PsiDeclarationStatement) newBodyBlock.getStatements()[0];
    final PsiLocalVariable newItemVariable = (PsiLocalVariable) newFirstStatement.getDeclaredElements()[0];
    final PsiTypeElement newItemTypeElement = elementFactory.createTypeElement(iterationParameter.getType());
    newItemVariable.getTypeElement().replace(newItemTypeElement);
    newItemVariable.setName(iterationParameterName);
    final CodeStyleSettings codeStyleSettings = CodeStyleSettingsManager.getSettings(project);
    if (codeStyleSettings.GENERATE_FINAL_LOCALS) {
        final PsiModifierList modifierList = newItemVariable.getModifierList();
        if (modifierList != null)
            modifierList.setModifierProperty(PsiModifier.FINAL, true);
    }
    final CodeStyleManager styleManager = CodeStyleManager.getInstance(project);
    newForLoop = (PsiForStatement) javaStyleManager.shortenClassReferences(newForLoop);
    newForLoop = (PsiForStatement) styleManager.reformat(newForLoop);
    if (forEachBody instanceof PsiBlockStatement) {
        final PsiCodeBlock bodyCodeBlock = ((PsiBlockStatement) forEachBody).getCodeBlock();
        final PsiElement firstBodyElement = bodyCodeBlock.getFirstBodyElement();
        final PsiElement lastBodyElement = bodyCodeBlock.getLastBodyElement();
        if (firstBodyElement != null && lastBodyElement != null) {
            newBodyBlock.addRangeAfter(firstBodyElement, lastBodyElement, newFirstStatement);
        }
    } else if (forEachBody != null && !(forEachBody instanceof PsiEmptyStatement)) {
        newBodyBlock.addAfter(forEachBody, newFirstStatement);
    }
    myStatement.replace(newForLoop);
}
Also used : CodeStyleManager(com.intellij.psi.codeStyle.CodeStyleManager) JavaCodeStyleManager(com.intellij.psi.codeStyle.JavaCodeStyleManager) CodeStyleSettings(com.intellij.psi.codeStyle.CodeStyleSettings) JavaCodeStyleManager(com.intellij.psi.codeStyle.JavaCodeStyleManager)

Example 69 with JavaCodeStyleManager

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

the class CreatePropertyFromUsageFix method getVariableName.

private static String getVariableName(PsiMethodCallExpression methodCall, boolean isStatic) {
    JavaCodeStyleManager codeStyleManager = JavaCodeStyleManager.getInstance(methodCall.getProject());
    String methodName = methodCall.getMethodExpression().getReferenceName();
    String propertyName = PropertyUtil.getPropertyName(methodName);
    if (propertyName != null && !propertyName.isEmpty()) {
        VariableKind kind = isStatic ? VariableKind.STATIC_FIELD : VariableKind.FIELD;
        return codeStyleManager.propertyNameToVariableName(propertyName, kind);
    }
    return null;
}
Also used : JavaCodeStyleManager(com.intellij.psi.codeStyle.JavaCodeStyleManager) VariableKind(com.intellij.psi.codeStyle.VariableKind)

Example 70 with JavaCodeStyleManager

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

the class IntroduceFieldDialog method createGenerator.

static NameSuggestionsGenerator createGenerator(final boolean willBeDeclaredStatic, final PsiLocalVariable localVariable, final PsiExpression initializerExpression, final boolean isInvokedOnDeclaration, @Nullable final String enteredName, final PsiClass parentClass, final Project project) {
    return new NameSuggestionsGenerator() {

        private final JavaCodeStyleManager myCodeStyleManager = JavaCodeStyleManager.getInstance(project);

        public SuggestedNameInfo getSuggestedNameInfo(PsiType type) {
            VariableKind variableKind = willBeDeclaredStatic ? VariableKind.STATIC_FIELD : VariableKind.FIELD;
            String propertyName = null;
            if (isInvokedOnDeclaration) {
                propertyName = myCodeStyleManager.variableNameToPropertyName(localVariable.getName(), VariableKind.LOCAL_VARIABLE);
            }
            final SuggestedNameInfo nameInfo = myCodeStyleManager.suggestVariableName(variableKind, propertyName, initializerExpression, type);
            if (initializerExpression != null) {
                String[] names = nameInfo.names;
                for (int i = 0, namesLength = names.length; i < namesLength; i++) {
                    String name = names[i];
                    if (parentClass.findFieldByName(name, false) != null) {
                        names[i] = myCodeStyleManager.suggestUniqueVariableName(name, initializerExpression, true);
                    }
                }
            }
            final String[] strings = AbstractJavaInplaceIntroducer.appendUnresolvedExprName(JavaCompletionUtil.completeVariableNameForRefactoring(myCodeStyleManager, type, VariableKind.LOCAL_VARIABLE, nameInfo), initializerExpression);
            return new SuggestedNameInfo.Delegate(enteredName != null ? ArrayUtil.mergeArrays(new String[] { enteredName }, strings) : strings, nameInfo);
        }
    };
}
Also used : JavaCodeStyleManager(com.intellij.psi.codeStyle.JavaCodeStyleManager) SuggestedNameInfo(com.intellij.psi.codeStyle.SuggestedNameInfo) VariableKind(com.intellij.psi.codeStyle.VariableKind)

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