Search in sources :

Example 26 with SuggestedNameInfo

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

the class OptionalIsPresentInspection method generateOptionalLambda.

@NotNull
static String generateOptionalLambda(PsiElementFactory factory, CommentTracker ct, PsiVariable optionalVariable, PsiElement trueValue) {
    PsiType type = optionalVariable.getType();
    JavaCodeStyleManager javaCodeStyleManager = JavaCodeStyleManager.getInstance(trueValue.getProject());
    SuggestedNameInfo info = javaCodeStyleManager.suggestVariableName(VariableKind.PARAMETER, null, null, type);
    if (info.names.length == 0) {
        info = javaCodeStyleManager.suggestVariableName(VariableKind.PARAMETER, "value", null, type);
    }
    String paramName = javaCodeStyleManager.suggestUniqueVariableName(info, trueValue, true).names[0];
    if (trueValue instanceof PsiExpressionStatement) {
        trueValue = ((PsiExpressionStatement) trueValue).getExpression();
    }
    ct.markUnchanged(trueValue);
    PsiElement copy = trueValue.copy();
    for (PsiElement getCall : PsiTreeUtil.collectElements(copy, e -> isOptionalGetCall(e, optionalVariable))) {
        PsiElement result = getCall.replace(factory.createIdentifier(paramName));
        if (copy == getCall)
            copy = result;
    }
    if (copy instanceof PsiStatement && !(copy instanceof PsiBlockStatement)) {
        return paramName + "->{" + copy.getText() + "}";
    }
    return paramName + "->" + copy.getText();
}
Also used : JavaCodeStyleManager(com.intellij.psi.codeStyle.JavaCodeStyleManager) SuggestedNameInfo(com.intellij.psi.codeStyle.SuggestedNameInfo) NotNull(org.jetbrains.annotations.NotNull)

Example 27 with SuggestedNameInfo

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

the class JavaNameSuggestionProvider method getSuggestedNames.

@Nullable
public SuggestedNameInfo getSuggestedNames(final PsiElement element, final PsiElement nameSuggestionContext, Set<String> result) {
    if (!element.getLanguage().isKindOf(JavaLanguage.INSTANCE))
        return null;
    String initialName = UsageViewUtil.getShortName(element);
    SuggestedNameInfo info = suggestNamesForElement(element, nameSuggestionContext);
    if (info != null) {
        info = JavaCodeStyleManager.getInstance(element.getProject()).suggestUniqueVariableName(info, element, true, true);
    }
    String parameterName = null;
    String superMethodName = null;
    if (nameSuggestionContext instanceof PsiParameter) {
        final PsiElement nameSuggestionContextParent = nameSuggestionContext.getParent();
        if (nameSuggestionContextParent instanceof PsiParameterList) {
            final PsiElement parentOfParent = nameSuggestionContextParent.getParent();
            if (parentOfParent instanceof PsiMethod) {
                final String propName = PropertyUtil.getPropertyName((PsiMethod) parentOfParent);
                if (propName != null) {
                    parameterName = propName;
                }
                superMethodName = getSuperMethodName((PsiParameter) nameSuggestionContext, (PsiMethod) parentOfParent);
            }
        }
    }
    final String[] strings = info != null ? info.names : ArrayUtil.EMPTY_STRING_ARRAY;
    final ArrayList<String> list = new ArrayList<>(Arrays.asList(strings));
    final String[] properlyCased = suggestProperlyCasedName(element);
    if (properlyCased != null) {
        Collections.addAll(list, properlyCased);
    }
    if (parameterName != null && !list.contains(parameterName)) {
        list.add(parameterName);
    }
    if (superMethodName != null && !list.contains(superMethodName)) {
        list.add(0, superMethodName);
    }
    if (!list.contains(initialName)) {
        list.add(initialName);
    } else {
        int i = list.indexOf(initialName);
        list.remove(i);
        list.add(initialName);
    }
    ContainerUtil.removeDuplicates(list);
    result.addAll(list);
    return info;
}
Also used : SuggestedNameInfo(com.intellij.psi.codeStyle.SuggestedNameInfo) Nullable(org.jetbrains.annotations.Nullable)

Example 28 with SuggestedNameInfo

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

the class JavaNameSuggestionProvider method suggestNamesForElement.

@Nullable
private static SuggestedNameInfo suggestNamesForElement(final PsiElement element, PsiElement nameSuggestionContext) {
    PsiVariable var = null;
    if (element instanceof PsiVariable) {
        var = (PsiVariable) element;
    } else if (element instanceof PsiIdentifier) {
        PsiIdentifier identifier = (PsiIdentifier) element;
        if (identifier.getParent() instanceof PsiVariable) {
            var = (PsiVariable) identifier.getParent();
        }
    }
    if (var == null)
        return null;
    JavaCodeStyleManager codeStyleManager = JavaCodeStyleManager.getInstance(element.getProject());
    VariableKind variableKind = codeStyleManager.getVariableKind(var);
    final SuggestedNameInfo nameInfo = codeStyleManager.suggestVariableName(variableKind, null, var.getInitializer(), var.getType());
    final PsiExpression expression = PsiTreeUtil.getParentOfType(nameSuggestionContext, PsiExpression.class, false);
    if (expression != null) {
        return new SuggestedNameInfo.Delegate(codeStyleManager.suggestVariableName(variableKind, null, expression, var.getType()).names, nameInfo);
    }
    return nameInfo;
}
Also used : JavaCodeStyleManager(com.intellij.psi.codeStyle.JavaCodeStyleManager) SuggestedNameInfo(com.intellij.psi.codeStyle.SuggestedNameInfo) VariableKind(com.intellij.psi.codeStyle.VariableKind) Nullable(org.jetbrains.annotations.Nullable)

Example 29 with SuggestedNameInfo

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

the class GuavaFluentIterableConversionRule method getOneMethodDescriptor.

@Nullable
private static TypeConversionDescriptorBase getOneMethodDescriptor(@NotNull String methodName, @NotNull PsiMethod method, @NotNull PsiType from, @Nullable PsiType to, @Nullable PsiExpression context) {
    TypeConversionDescriptor descriptorBase = null;
    PsiType conversionType = null;
    boolean needSpecifyType = true;
    if (methodName.equals("of")) {
        descriptorBase = new TypeConversionDescriptor("'FluentIterable*.of($arr$)", "java.util.Arrays.stream($arr$)");
    } else if (methodName.equals("from")) {
        descriptorBase = new TypeConversionDescriptor("'FluentIterable*.from($it$)", null) {

            @Override
            public PsiExpression replace(PsiExpression expression, @NotNull TypeEvaluator evaluator) {
                final PsiMethodCallExpression methodCall = (PsiMethodCallExpression) expression;
                PsiExpression argument = PseudoLambdaReplaceTemplate.replaceTypeParameters(methodCall.getArgumentList().getExpressions()[0]);
                if (argument == null) {
                    return expression;
                }
                boolean isCollection = InheritanceUtil.isInheritor(PsiTypesUtil.getPsiClass(argument.getType()), CommonClassNames.JAVA_UTIL_COLLECTION);
                setReplaceByString(isCollection ? "($it$).stream()" : "java.util.stream.StreamSupport.stream(($it$).spliterator(), false)");
                final PsiExpression replaced = super.replace(expression, evaluator);
                ParenthesesUtils.removeParentheses(replaced, false);
                return replaced;
            }
        };
    } else if (methodName.equals("filter")) {
        descriptorBase = FluentIterableConversionUtil.getFilterDescriptor(method, context);
    } else if (methodName.equals("isEmpty")) {
        descriptorBase = new TypeConversionDescriptor("$q$.isEmpty()", null) {

            @Override
            public PsiExpression replace(PsiExpression expression, @NotNull TypeEvaluator evaluator) {
                final PsiElement parent = expression.getParent();
                boolean isDoubleNegation = false;
                if (parent instanceof PsiExpression && DoubleNegationInspection.isNegation((PsiExpression) parent)) {
                    isDoubleNegation = true;
                    expression = (PsiExpression) parent.replace(expression);
                }
                setReplaceByString((isDoubleNegation ? "" : "!") + "$q$.findAny().isPresent()");
                return super.replace(expression, evaluator);
            }
        };
        needSpecifyType = false;
    } else if (methodName.equals("transformAndConcat")) {
        descriptorBase = new FluentIterableConversionUtil.TransformAndConcatConversionRule();
    } else if (methodName.equals("toArray")) {
        descriptorBase = FluentIterableConversionUtil.getToArrayDescriptor(from, context);
        needSpecifyType = false;
    } else if (methodName.equals("copyInto")) {
        descriptorBase = new FluentIterableConversionUtil.CopyIntoConversionDescriptor();
        needSpecifyType = false;
    } else if (methodName.equals("append")) {
        descriptorBase = createDescriptorForAppend(method, context);
    } else if (methodName.equals("get")) {
        descriptorBase = new TypeConversionDescriptor("$it$.get($p$)", null) {

            @Override
            public PsiExpression replace(PsiExpression expression, @NotNull TypeEvaluator evaluator) {
                PsiMethodCallExpression methodCall = (PsiMethodCallExpression) expression;
                final PsiExpression[] arguments = methodCall.getArgumentList().getExpressions();
                setReplaceByString("$it$.skip($p$).findFirst().get()");
                if (arguments.length == 1 && arguments[0] instanceof PsiLiteralExpression) {
                    final Object value = ((PsiLiteralExpression) arguments[0]).getValue();
                    if (value != null && value.equals(0)) {
                        setReplaceByString("$it$.findFirst().get()");
                    }
                }
                return super.replace(expression, evaluator);
            }
        };
        needSpecifyType = false;
    } else if (methodName.equals("contains")) {
        descriptorBase = new TypeConversionDescriptor("$it$.contains($o$)", null) {

            @Override
            public PsiExpression replace(PsiExpression expression, @NotNull TypeEvaluator evaluator) {
                final PsiMethodCallExpression methodCallExpression = (PsiMethodCallExpression) expression;
                final PsiExpression qualifier = methodCallExpression.getMethodExpression().getQualifierExpression();
                LOG.assertTrue(qualifier != null);
                final PsiClassType qualifierType = (PsiClassType) qualifier.getType();
                LOG.assertTrue(qualifierType != null);
                final PsiType[] parameters = qualifierType.getParameters();
                final JavaCodeStyleManager codeStyleManager = JavaCodeStyleManager.getInstance(expression.getProject());
                final SuggestedNameInfo suggestedNameInfo = codeStyleManager.suggestVariableName(VariableKind.LOCAL_VARIABLE, null, null, parameters.length == 1 ? parameters[0] : null, false);
                final String suggestedName = codeStyleManager.suggestUniqueVariableName(suggestedNameInfo, expression, false).names[0];
                setReplaceByString("$it$.anyMatch(" + suggestedName + " -> java.util.Objects.equals(" + suggestedName + ", $o$))");
                return super.replace(expression, evaluator);
            }
        };
        needSpecifyType = false;
    } else if (methodName.equals("last")) {
        descriptorBase = new TypeConversionDescriptor("$it$.last()", null) {

            @Override
            public PsiExpression replace(PsiExpression expression, @NotNull TypeEvaluator evaluator) {
                final JavaCodeStyleManager codeStyleManager = JavaCodeStyleManager.getInstance(expression.getProject());
                String varA = suggestName("a", codeStyleManager, expression);
                String varB = suggestName("b", codeStyleManager, expression);
                setReplaceByString("$it$.reduce((" + varA + ", " + varB + ") -> " + varB + ")");
                return super.replace(expression, evaluator);
            }

            private String suggestName(String baseName, JavaCodeStyleManager codeStyleManager, PsiElement place) {
                final SuggestedNameInfo suggestedNameInfo = codeStyleManager.suggestVariableName(VariableKind.LOCAL_VARIABLE, baseName, null, null, false);
                return codeStyleManager.suggestUniqueVariableName(suggestedNameInfo, place, false).names[0];
            }
        };
    } else {
        final TypeConversionDescriptorFactory base = DESCRIPTORS_MAP.get(methodName);
        if (base != null) {
            final TypeConversionDescriptor descriptor = base.create();
            needSpecifyType = base.isChainedMethod();
            if (needSpecifyType && !base.isFluentIterableReturnType()) {
                conversionType = GuavaConversionUtil.addTypeParameters(GuavaOptionalConversionRule.JAVA_OPTIONAL, context.getType(), context);
            }
            descriptorBase = descriptor;
        }
    }
    if (descriptorBase == null) {
        return FluentIterableConversionUtil.createToCollectionDescriptor(methodName, context);
    }
    if (needSpecifyType) {
        if (conversionType == null) {
            PsiMethodCallExpression methodCall = (PsiMethodCallExpression) (context instanceof PsiMethodCallExpression ? context : context.getParent());
            conversionType = GuavaConversionUtil.addTypeParameters(GuavaTypeConversionDescriptor.isIterable(methodCall) ? CommonClassNames.JAVA_LANG_ITERABLE : StreamApiConstants.JAVA_UTIL_STREAM_STREAM, context.getType(), context);
        }
        descriptorBase.withConversionType(conversionType);
    }
    return descriptorBase;
}
Also used : NotNull(org.jetbrains.annotations.NotNull) TypeEvaluator(com.intellij.refactoring.typeMigration.TypeEvaluator) JavaCodeStyleManager(com.intellij.psi.codeStyle.JavaCodeStyleManager) TypeConversionDescriptor(com.intellij.refactoring.typeMigration.TypeConversionDescriptor) SuggestedNameInfo(com.intellij.psi.codeStyle.SuggestedNameInfo) Nullable(org.jetbrains.annotations.Nullable)

Example 30 with SuggestedNameInfo

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

the class CreateLocalVarFromInstanceofAction method generateTemplate.

private static Template generateTemplate(Project project, PsiExpression initializer, PsiType type) {
    final TemplateManager templateManager = TemplateManager.getInstance(project);
    final Template template = templateManager.createTemplate("", "");
    template.setToReformat(true);
    final SuggestedNameInfo suggestedNameInfo = IntroduceVariableBase.getSuggestedName(type, initializer, initializer);
    Set<LookupElement> itemSet = new LinkedHashSet<>();
    for (String name : suggestedNameInfo.names) {
        itemSet.add(LookupElementBuilder.create(name));
    }
    final LookupElement[] lookupItems = itemSet.toArray(new LookupElement[itemSet.size()]);
    final Result result = suggestedNameInfo.names.length == 0 ? null : new TextResult(suggestedNameInfo.names[0]);
    Expression expr = new Expression() {

        @Override
        public LookupElement[] calculateLookupItems(ExpressionContext context) {
            return lookupItems.length > 1 ? lookupItems : null;
        }

        @Override
        public Result calculateResult(ExpressionContext context) {
            return result;
        }

        @Override
        public Result calculateQuickResult(ExpressionContext context) {
            return result;
        }
    };
    template.addVariable("", expr, expr, true);
    return template;
}
Also used : LinkedHashSet(java.util.LinkedHashSet) SuggestedNameInfo(com.intellij.psi.codeStyle.SuggestedNameInfo) LookupElement(com.intellij.codeInsight.lookup.LookupElement)

Aggregations

SuggestedNameInfo (com.intellij.psi.codeStyle.SuggestedNameInfo)40 JavaCodeStyleManager (com.intellij.psi.codeStyle.JavaCodeStyleManager)22 VariableKind (com.intellij.psi.codeStyle.VariableKind)11 Nullable (org.jetbrains.annotations.Nullable)7 Project (com.intellij.openapi.project.Project)6 NotNull (org.jetbrains.annotations.NotNull)6 ArrayList (java.util.ArrayList)4 LinkedHashSet (java.util.LinkedHashSet)4 NonNls (org.jetbrains.annotations.NonNls)4 LookupElement (com.intellij.codeInsight.lookup.LookupElement)3 Editor (com.intellij.openapi.editor.Editor)3 PsiType (com.intellij.psi.PsiType)3 PreferrableNameSuggestionProvider (com.intellij.refactoring.rename.PreferrableNameSuggestionProvider)3 IncorrectOperationException (com.intellij.util.IncorrectOperationException)3 List (java.util.List)3 ApplicationManager (com.intellij.openapi.application.ApplicationManager)2 Logger (com.intellij.openapi.diagnostic.Logger)2 com.intellij.psi (com.intellij.psi)2 THashSet (gnu.trove.THashSet)2 JavaPsiEquivalenceUtil (com.intellij.codeInsight.JavaPsiEquivalenceUtil)1