[name hints] java parameter hints provider refactored and converted to kt

This commit is contained in:
Yaroslav Lepenkin
2016-12-01 19:31:43 +03:00
parent 764d236694
commit 00b4845ce7
4 changed files with 186 additions and 249 deletions
@@ -0,0 +1,175 @@
/*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.codeInsight.hints
import com.intellij.codeInsight.hints.settings.ParameterNameHintsSettings
import com.intellij.psi.*
import com.intellij.psi.util.TypeConversionUtil
object JavaInlayHintsProvider {
fun createHints(callExpression: PsiCallExpression): Set<InlayInfo> {
val (element, substitutor) = callExpression.resolveMethodGenerics().let { it.element to it.substitutor }
if (element is PsiMethod && isMethodToShow(element, callExpression)) {
val info = getCallInfo(callExpression, element)
return createHintSet(info, substitutor)
}
return emptySet()
}
private fun createHintSet(info: CallInfo, substitutor: PsiSubstitutor): Set<InlayInfo> {
val args = info.regularArgs.filter { it.isAssignable(substitutor) }
val resultSet = mutableSetOf<InlayInfo>()
with(resultSet) {
getVarArgInlay(info)?.let { add(it) }
if (ParameterNameHintsSettings.getInstance().isShowForParamsWithSameType) {
addAll(createSameTypeInlays(args))
}
addAll(createUnclearInlays(args))
}
return resultSet
}
private fun isMethodToShow(method: PsiMethod, callExpression: PsiCallExpression): Boolean {
val params = method.parameterList.parameters
if (params.isEmpty()) return false
if (params.size == 1) {
if (isBuilderLike(callExpression, method) || isSetterNamed(method)) return false
if (!ParameterNameHintsSettings.getInstance().isShowParamNameContainedInMethodName
&& isParamNameContainedInMethodName(params[0], method)) return false
}
return true
}
private fun createUnclearInlays(args: List<CallArgumentInfo>): List<InlayInfo> {
return args
.filter { isUnclearExpression(it.argument) }
.mapNotNull { createInlayInfo(it.argument, it.parameter) }
}
private fun getVarArgInlay(info: CallInfo): InlayInfo? {
if (info.varArg == null || info.varArgExpressions.isEmpty()) return null
val hasUnclearExpressions = info.varArgExpressions.find { isUnclearExpression(it) } != null
if (hasUnclearExpressions) {
return createInlayInfo(info.varArgExpressions.first(), info.varArg)
}
return null
}
private fun isBuilderLike(expression: PsiCallExpression, method: PsiMethod): Boolean {
if (expression is PsiNewExpression) return false
val returnType = TypeConversionUtil.erasure(method.returnType) ?: return false
val calledMethodClassFqn = method.containingClass?.qualifiedName ?: return false
return returnType.equalsToText(calledMethodClassFqn)
}
private fun isSetterNamed(method: PsiMethod): Boolean {
val methodName = method.name
if (methodName.startsWith("set")
&& (methodName.length == 3 || methodName.length > 3 && methodName[3].isUpperCase())) {
return true
}
return false
}
private fun isParamNameContainedInMethodName(parameter: PsiParameter, method: PsiMethod): Boolean {
val parameterName = parameter.name ?: return false
if (parameterName.length > 1) {
return method.name.contains(parameterName, ignoreCase = true)
}
return false
}
private fun createSameTypeInlays(args: List<CallArgumentInfo>): List<InlayInfo> {
val all = args.map { it.parameter.typeText() }
val duplicated = all.toMutableList()
all.distinct().forEach {
duplicated.remove(it)
}
return args
.filter { duplicated.contains(it.parameter.typeText()) }
.mapNotNull { createInlayInfo(it.argument, it.parameter) }
}
private fun createInlayInfo(callArgument: PsiExpression, methodParam: PsiParameter): InlayInfo? {
val paramName = methodParam.name ?: return null
val paramToShow = (if (methodParam.type is PsiEllipsisType) "..." else "") + paramName
return InlayInfo(paramToShow, callArgument.textRange.startOffset)
}
private fun getCallInfo(callExpression: PsiCallExpression, method: PsiMethod): CallInfo {
val params = method.parameterList.parameters
val hasVarArg = params.lastOrNull()?.isVarArgs ?: false
val regularParamsCount = if (hasVarArg) params.size - 1 else params.size
val arguments = callExpression.argumentList?.expressions ?: emptyArray()
val regularArgInfos = params
.take(regularParamsCount)
.zip(arguments)
.map { CallArgumentInfo(it.first, it.second) }
val varargParam = if (hasVarArg) params.last() else null
val varargExpressions = arguments.drop(regularParamsCount)
return CallInfo(regularArgInfos, varargParam, varargExpressions)
}
private fun isUnclearExpression(callArgument: PsiElement): Boolean {
return when (callArgument) {
is PsiLiteralExpression -> true
is PsiThisExpression -> true
is PsiBinaryExpression -> true
is PsiPolyadicExpression -> true
is PsiPrefixExpression -> {
val tokenType = callArgument.operationTokenType
val isLiteral = callArgument.operand is PsiLiteralExpression
isLiteral && (JavaTokenType.MINUS == tokenType || JavaTokenType.PLUS == tokenType)
}
else -> false
}
}
}
private class CallInfo(val regularArgs: List<CallArgumentInfo>,
val varArg: PsiParameter?,
val varArgExpressions: List<PsiExpression>)
private class CallArgumentInfo(val parameter: PsiParameter, val argument: PsiExpression)
private fun CallArgumentInfo.isAssignable(substitutor: PsiSubstitutor): Boolean {
val substitutedType = substitutor.substitute(parameter.type)
return argument.type?.isAssignableTo(substitutedType) ?: false
}
private fun PsiType.isAssignableTo(parameterType: PsiType): Boolean {
return TypeConversionUtil.isAssignable(parameterType, this)
}
private fun PsiParameter.typeText() = type.canonicalText
@@ -34,7 +34,7 @@ class JavaInlayParameterHintsProvider : InlayParameterHintsProvider {
override fun getParameterHints(element: PsiElement): List<InlayInfo> {
if (element is PsiCallExpression) {
return JavaParameterHintManager(element).descriptors.toList()
return JavaInlayHintsProvider.createHints(element).toList()
}
return emptyList()
}
@@ -1,244 +0,0 @@
/*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.codeInsight.hints;
import com.intellij.codeInsight.hints.settings.ParameterNameHintsSettings;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.*;
import com.intellij.psi.tree.IElementType;
import com.intellij.psi.util.TypeConversionUtil;
import com.intellij.util.containers.ContainerUtil;
import one.util.streamex.StreamEx;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
public class JavaParameterHintManager {
@NotNull
private final Set<InlayInfo> myDescriptors;
public JavaParameterHintManager(@NotNull PsiCallExpression callExpression) {
PsiExpression[] callArguments = getArguments(callExpression);
JavaResolveResult resolveResult = callExpression.resolveMethodGenerics();
if (!(resolveResult.getElement() instanceof PsiMethod)) {
myDescriptors = Collections.emptySet();
return;
}
final PsiMethod method = (PsiMethod)resolveResult.getElement();
Set<InlayInfo> descriptors = Collections.emptySet();
if (isMethodToShowParams(callExpression, method)) {
PsiParameter[] parameters = method.getParameterList().getParameters();
descriptors = buildDescriptorsForLiteralArguments(callArguments, parameters, resolveResult);
}
myDescriptors = descriptors;
}
private static boolean isMethodToShowParams(@NotNull PsiCallExpression callExpression, @NotNull PsiMethod method) {
if (isSetter(method)) return false;
PsiParameter[] parameters = method.getParameterList().getParameters();
if (parameters.length == 1) {
if (isBuilder(callExpression, method)) return false;
ParameterNameHintsSettings settings = ParameterNameHintsSettings.getInstance();
if (!settings.isShowParamNameContainedInMethodName()
&& isParamNameContainedInMethodName(parameters[0], method)) {
return false;
}
}
return true;
}
private static Set<String> getDuplicatedParamTypes(PsiParameter[] parameters) {
List<String> duplicatedTypes = Arrays
.stream(parameters)
.map((p) -> p.getType().getCanonicalText())
.collect(Collectors.toList());
ContainerUtil.newHashSet(duplicatedTypes).forEach((e) -> duplicatedTypes.remove(e));
return ContainerUtil.newHashSet(duplicatedTypes);
}
private static boolean isParamNameContainedInMethodName(@NotNull PsiParameter parameter, @NotNull PsiMethod method) {
String parameterName = parameter.getName();
if (parameterName != null && parameterName.length() > 1) {
String methodName = method.getName();
return StringUtil.containsIgnoreCase(methodName, parameterName);
}
return false;
}
private static boolean isBuilder(PsiCallExpression expression, PsiMethod method) {
if (expression instanceof PsiNewExpression || !hasSingleParameter(method)) {
return false;
}
PsiType returnType = TypeConversionUtil.erasure(method.getReturnType());
final PsiClass aClass = method.getContainingClass();
final String calledMethodFqn = aClass != null ? aClass.getQualifiedName() : null;
if (calledMethodFqn != null && returnType != null) {
return returnType.equalsToText(calledMethodFqn);
}
return false;
}
private static boolean hasSingleParameter(PsiMethod method) {
return method.getParameterList().getParametersCount() == 1;
}
private static boolean isSetter(PsiMethod method) {
String methodName = method.getName();
if (hasSingleParameter(method) && methodName.startsWith("set")
&& (methodName.length() == 3
|| methodName.length() > 3 && Character.isUpperCase(methodName.charAt(3)))) {
return true;
}
return false;
}
static boolean isUnclearExpression(@Nullable PsiElement callArgument) {
if (callArgument instanceof PsiLiteralExpression) {
return true;
}
if (callArgument instanceof PsiPrefixExpression) {
PsiPrefixExpression expr = (PsiPrefixExpression)callArgument;
IElementType tokenType = expr.getOperationTokenType();
return (JavaTokenType.MINUS.equals(tokenType)
|| JavaTokenType.PLUS.equals(tokenType)) && expr.getOperand() instanceof PsiLiteralExpression;
}
if (callArgument instanceof PsiThisExpression
|| callArgument instanceof PsiBinaryExpression
|| callArgument instanceof PsiPolyadicExpression) {
return true;
}
return false;
}
@NotNull
private static PsiExpression[] getArguments(@NotNull PsiCallExpression call) {
PsiExpressionList callArgumentsList = call.getArgumentList();
return callArgumentsList == null ? PsiExpression.EMPTY_ARRAY : callArgumentsList.getExpressions();
}
@NotNull
public Set<InlayInfo> getDescriptors() {
return myDescriptors;
}
@NotNull
private static Set<InlayInfo> buildDescriptorsForLiteralArguments(@NotNull PsiExpression[] callArguments,
@NotNull PsiParameter[] parameters,
@NotNull JavaResolveResult resolveResult) {
final Set<InlayInfo> descriptors = ContainerUtil.newHashSet();
final PsiSubstitutor substitutor = resolveResult.getSubstitutor();
if (ParameterNameHintsSettings.getInstance().isShowForParamsWithSameType()) {
final List<InlayInfo> hintsForNonLiterals = getHintsForParamsWithSameType(callArguments, parameters, substitutor);
descriptors.addAll(hintsForNonLiterals);
}
for (int i = 0; i < Math.min(callArguments.length, parameters.length); i++) {
PsiExpression arg = callArguments[i];
PsiParameter param = parameters[i];
if (isVarargParam(param.getType(), arg.getType()) && hasUnclearExpressionStartingFrom(i, callArguments)
|| isUnclearExpression(arg) && isAssignable(arg, param, substitutor)) {
descriptors.add(createInlayInfo(arg, param));
}
}
return descriptors;
}
private static List<InlayInfo> getHintsForParamsWithSameType(@NotNull PsiExpression[] callArguments,
@NotNull PsiParameter[] parameters,
@NotNull PsiSubstitutor substitutor)
{
final Set<String> duplicatedTypes = getDuplicatedParamTypes(parameters);
final int minArraySize = Math.min(callArguments.length, parameters.length);
List<PsiExpression> args = ContainerUtil.list(callArguments).subList(0, minArraySize);
List<PsiParameter> params = ContainerUtil.list(parameters).subList(0, minArraySize);
return StreamEx
.zip(args, params, (a, b) -> Pair.create(a, b))
.filter((pair) -> {
PsiParameter param = pair.getSecond();
return duplicatedTypes.contains(param.getType().getCanonicalText());
})
.filter((pair) -> isAssignable(pair.first, pair.second, substitutor))
.map((pair) -> createInlayInfo(pair.first, pair.second))
.collect(Collectors.toList());
}
@NotNull
private static InlayInfo createInlayInfo(@NotNull PsiExpression callArgument, @NotNull PsiParameter methodParam) {
String paramName = ((methodParam.getType() instanceof PsiEllipsisType) ? "..." : "") + methodParam.getName();
return new InlayInfo(paramName, callArgument.getTextRange().getStartOffset());
}
private static boolean isAssignable(@NotNull PsiExpression argument,
@NotNull PsiParameter parameter,
@NotNull PsiSubstitutor substitutor) {
PsiType argType = argument.getType();
PsiType paramType = parameter.getType();
if (argType != null) {
PsiType parameterType = substitutor.substitute(paramType);
return TypeConversionUtil.isAssignable(parameterType, argType);
}
return false;
}
private static boolean hasUnclearExpressionStartingFrom(int index, PsiExpression[] callArguments) {
for (int i = index; i < callArguments.length; i++) {
PsiExpression arg = callArguments[i];
if (isUnclearExpression(arg)) return true;
}
return false;
}
private static boolean isVarargParam(@Nullable PsiType paramType, @Nullable PsiType argType) {
if (paramType == null || argType == null) return false;
PsiType deepType = paramType.getDeepComponentType();
return paramType instanceof PsiEllipsisType && TypeConversionUtil.isAssignable(deepType, argType);
}
private static boolean hasUnclearExpressions(@NotNull PsiExpression[] arguments) {
for (PsiExpression argument : arguments) {
if (isUnclearExpression(argument)) return true;
}
return false;
}
}