Search in sources :

Example 21 with SuggestedNameInfo

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

the class ClassMappingNameConverter method getVariants.

@NotNull
@Override
public Collection<String> getVariants(ConvertContext context) {
    DomElement parent = context.getInvocationElement().getParent();
    assert parent != null;
    List<DomElement> children = DomUtil.getDefinedChildren(parent, true, true);
    DomElement classElement = ContainerUtil.find(children, domElement -> domElement.getAnnotation(MappingClass.class) != null);
    if (classElement == null)
        return Collections.emptyList();
    Object value = ((GenericDomValue) classElement).getValue();
    if (value == null)
        return Collections.emptyList();
    PsiType type;
    if (value instanceof PsiType) {
        type = (PsiType) value;
    } else if (value instanceof PsiClass) {
        type = PsiTypesUtil.getClassType((PsiClass) value);
    } else {
        LOG.error("wrong type: " + value.getClass());
        return Collections.emptyList();
    }
    JavaCodeStyleManager codeStyleManager = JavaCodeStyleManager.getInstance(context.getProject());
    SuggestedNameInfo info = codeStyleManager.suggestVariableName(VariableKind.LOCAL_VARIABLE, null, null, type);
    return Arrays.asList(info.names);
}
Also used : JavaCodeStyleManager(com.intellij.psi.codeStyle.JavaCodeStyleManager) PsiClass(com.intellij.psi.PsiClass) SuggestedNameInfo(com.intellij.psi.codeStyle.SuggestedNameInfo) PsiType(com.intellij.psi.PsiType) NotNull(org.jetbrains.annotations.NotNull)

Example 22 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 23 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 24 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 25 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)

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