├── .gitignore
├── .run
└── Run IDE with Plugin.run.xml
├── README.md
├── build.gradle.kts
├── gradle.properties
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
├── images
└── example.png
├── settings.gradle.kts
└── src
└── main
├── kotlin
└── com
│ └── serranofp
│ └── kotlin
│ └── mismatch
│ └── hints
│ ├── MismatchInlayHintProvider.kt
│ ├── Problem.kt
│ └── TypeUtils.kt
└── resources
├── META-INF
└── plugin.xml
└── messages
└── kotlin-mismatch-hints.properties
/.gitignore:
--------------------------------------------------------------------------------
1 | .gradle
2 | build/
3 | !gradle/wrapper/gradle-wrapper.jar
4 | !**/src/main/**/build/
5 | !**/src/test/**/build/
6 | .kotlin/
7 |
8 | ### IntelliJ IDEA ###
9 | .idea/
10 | .idea/modules.xml
11 | .idea/jarRepositories.xml
12 | .idea/compiler.xml
13 | .idea/libraries/
14 | *.iws
15 | *.iml
16 | *.ipr
17 | out/
18 | !**/src/main/**/out/
19 | !**/src/test/**/out/
20 | .intellijPlatform
21 |
22 | ### Eclipse ###
23 | .apt_generated
24 | .classpath
25 | .factorypath
26 | .project
27 | .settings
28 | .springBeans
29 | .sts4-cache
30 | bin/
31 | !**/src/main/**/bin/
32 | !**/src/test/**/bin/
33 |
34 | ### NetBeans ###
35 | /nbproject/private/
36 | /nbbuild/
37 | /dist/
38 | /nbdist/
39 | /.nb-gradle/
40 |
41 | ### VS Code ###
42 | .vscode/
43 |
44 | ### Mac OS ###
45 | .DS_Store
--------------------------------------------------------------------------------
/.run/Run IDE with Plugin.run.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
12 |
17 |
18 |
19 | true
20 | true
21 | false
22 |
23 |
24 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Kotlin Mistmatch Hints
2 |
3 | > Inlay hints succinctly describing mismatches in Kotlin code
4 |
5 | ### Available at [JetBrains Marketplace](https://plugins.jetbrains.com/plugin/26892-kotlin-mismatch-hints)
6 |
7 | This plugin inlays information about mismatches in Kotlin code,
8 | allowing you to know at a glance what the problem is.
9 | At this moment, type, nullability, and variance mismatches
10 | are recognized by this plugin.
11 |
12 | In case of type mismatches, the type of the erroneous expression
13 | is shown as `: Type`, and the type expected by the surrounding
14 | context is shown afterward. If more than one potential overload
15 | is applicable, the expected types are shown after different symbols;
16 | the same symbol in different arguments corresponds to the same
17 | overload.
18 |
19 | 
--------------------------------------------------------------------------------
/build.gradle.kts:
--------------------------------------------------------------------------------
1 | import org.jetbrains.intellij.platform.gradle.IntelliJPlatformType
2 | import org.jetbrains.intellij.platform.gradle.models.ProductRelease
3 | import org.jetbrains.intellij.platform.gradle.tasks.RunIdeTask
4 | import org.jetbrains.kotlin.gradle.dsl.JvmTarget
5 | import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
6 |
7 | plugins {
8 | id("java")
9 | id("org.jetbrains.kotlin.jvm") version "2.1.20"
10 | id("org.jetbrains.intellij.platform") version "2.5.0"
11 | }
12 |
13 | group = "com.serranofp"
14 | version = "0.2.0"
15 |
16 | repositories {
17 | mavenCentral()
18 | intellijPlatform {
19 | defaultRepositories()
20 | }
21 | }
22 |
23 | dependencies {
24 | intellijPlatform {
25 | intellijIdeaCommunity("2024.3.2")
26 | pluginVerifier()
27 | bundledPlugin("com.intellij.java")
28 | bundledPlugin("org.jetbrains.kotlin")
29 | }
30 | }
31 |
32 | intellijPlatform {
33 | pluginConfiguration {
34 | ideaVersion {
35 | sinceBuild = "243"
36 | untilBuild = "251.*"
37 | }
38 | }
39 | pluginVerification {
40 | ides {
41 | select {
42 | types = listOf(
43 | IntelliJPlatformType.IntellijIdeaUltimate,
44 | IntelliJPlatformType.IntellijIdeaCommunity,
45 | IntelliJPlatformType.AndroidStudio
46 | )
47 | channels = listOf(
48 | ProductRelease.Channel.RELEASE,
49 | ProductRelease.Channel.BETA,
50 | ProductRelease.Channel.EAP
51 | )
52 | sinceBuild = "243"
53 | untilBuild = "251.*"
54 | }
55 | }
56 | }
57 | }
58 |
59 | tasks {
60 | withType {
61 | sourceCompatibility = "21"
62 | targetCompatibility = "21"
63 | }
64 | withType {
65 | compilerOptions.jvmTarget.set(JvmTarget.JVM_21)
66 | compilerOptions.freeCompilerArgs.addAll("-Xcontext-parameters", "-Xwhen-guards")
67 | }
68 | }
69 |
70 | val runIde: RunIdeTask by tasks
71 | runIde.jvmArgs("-Didea.kotlin.plugin.use.k2=true")
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Opt-out flag for bundling Kotlin standard library -> https://jb.gg/intellij-platform-kotlin-stdlib
2 | kotlin.stdlib.default.dependency=false
3 | # Enable Gradle Configuration Cache -> https://docs.gradle.org/current/userguide/configuration_cache.html
4 | org.gradle.configuration-cache=true
5 | # Enable Gradle Build Cache -> https://docs.gradle.org/current/userguide/build_cache.html
6 | org.gradle.caching=true
7 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/serras/kotlin-mismatch-hints/3d0bc7c5f81f0ebb08edf0eaa28c4dd2f9bc0e06/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | distributionBase=GRADLE_USER_HOME
2 | distributionPath=wrapper/dists
3 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.13-bin.zip
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/bin/sh
2 |
3 | #
4 | # Copyright © 2015-2021 the original authors.
5 | #
6 | # Licensed under the Apache License, Version 2.0 (the "License");
7 | # you may not use this file except in compliance with the License.
8 | # You may obtain a copy of the License at
9 | #
10 | # https://www.apache.org/licenses/LICENSE-2.0
11 | #
12 | # Unless required by applicable law or agreed to in writing, software
13 | # distributed under the License is distributed on an "AS IS" BASIS,
14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | # See the License for the specific language governing permissions and
16 | # limitations under the License.
17 | #
18 |
19 | ##############################################################################
20 | #
21 | # Gradle start up script for POSIX generated by Gradle.
22 | #
23 | # Important for running:
24 | #
25 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
26 | # noncompliant, but you have some other compliant shell such as ksh or
27 | # bash, then to run this script, type that shell name before the whole
28 | # command line, like:
29 | #
30 | # ksh Gradle
31 | #
32 | # Busybox and similar reduced shells will NOT work, because this script
33 | # requires all of these POSIX shell features:
34 | # * functions;
35 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
36 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»;
37 | # * compound commands having a testable exit status, especially «case»;
38 | # * various built-in commands including «command», «set», and «ulimit».
39 | #
40 | # Important for patching:
41 | #
42 | # (2) This script targets any POSIX shell, so it avoids extensions provided
43 | # by Bash, Ksh, etc; in particular arrays are avoided.
44 | #
45 | # The "traditional" practice of packing multiple parameters into a
46 | # space-separated string is a well documented source of bugs and security
47 | # problems, so this is (mostly) avoided, by progressively accumulating
48 | # options in "$@", and eventually passing that to Java.
49 | #
50 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
51 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
52 | # see the in-line comments for details.
53 | #
54 | # There are tweaks for specific operating systems such as AIX, CygWin,
55 | # Darwin, MinGW, and NonStop.
56 | #
57 | # (3) This script is generated from the Groovy template
58 | # https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
59 | # within the Gradle project.
60 | #
61 | # You can find Gradle at https://github.com/gradle/gradle/.
62 | #
63 | ##############################################################################
64 |
65 | # Attempt to set APP_HOME
66 |
67 | # Resolve links: $0 may be a link
68 | app_path=$0
69 |
70 | # Need this for daisy-chained symlinks.
71 | while
72 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
73 | [ -h "$app_path" ]
74 | do
75 | ls=$( ls -ld "$app_path" )
76 | link=${ls#*' -> '}
77 | case $link in #(
78 | /*) app_path=$link ;; #(
79 | *) app_path=$APP_HOME$link ;;
80 | esac
81 | done
82 |
83 | APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
84 |
85 | APP_NAME="Gradle"
86 | APP_BASE_NAME=${0##*/}
87 |
88 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
89 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
90 |
91 | # Use the maximum available, or set MAX_FD != -1 to use that value.
92 | MAX_FD=maximum
93 |
94 | warn () {
95 | echo "$*"
96 | } >&2
97 |
98 | die () {
99 | echo
100 | echo "$*"
101 | echo
102 | exit 1
103 | } >&2
104 |
105 | # OS specific support (must be 'true' or 'false').
106 | cygwin=false
107 | msys=false
108 | darwin=false
109 | nonstop=false
110 | case "$( uname )" in #(
111 | CYGWIN* ) cygwin=true ;; #(
112 | Darwin* ) darwin=true ;; #(
113 | MSYS* | MINGW* ) msys=true ;; #(
114 | NONSTOP* ) nonstop=true ;;
115 | esac
116 |
117 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
118 |
119 |
120 | # Determine the Java command to use to start the JVM.
121 | if [ -n "$JAVA_HOME" ] ; then
122 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
123 | # IBM's JDK on AIX uses strange locations for the executables
124 | JAVACMD=$JAVA_HOME/jre/sh/java
125 | else
126 | JAVACMD=$JAVA_HOME/bin/java
127 | fi
128 | if [ ! -x "$JAVACMD" ] ; then
129 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
130 |
131 | Please set the JAVA_HOME variable in your environment to match the
132 | location of your Java installation."
133 | fi
134 | else
135 | JAVACMD=java
136 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
137 |
138 | Please set the JAVA_HOME variable in your environment to match the
139 | location of your Java installation."
140 | fi
141 |
142 | # Increase the maximum file descriptors if we can.
143 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
144 | case $MAX_FD in #(
145 | max*)
146 | MAX_FD=$( ulimit -H -n ) ||
147 | warn "Could not query maximum file descriptor limit"
148 | esac
149 | case $MAX_FD in #(
150 | '' | soft) :;; #(
151 | *)
152 | ulimit -n "$MAX_FD" ||
153 | warn "Could not set maximum file descriptor limit to $MAX_FD"
154 | esac
155 | fi
156 |
157 | # Collect all arguments for the java command, stacking in reverse order:
158 | # * args from the command line
159 | # * the main class name
160 | # * -classpath
161 | # * -D...appname settings
162 | # * --module-path (only if needed)
163 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
164 |
165 | # For Cygwin or MSYS, switch paths to Windows format before running java
166 | if "$cygwin" || "$msys" ; then
167 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
168 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
169 |
170 | JAVACMD=$( cygpath --unix "$JAVACMD" )
171 |
172 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
173 | for arg do
174 | if
175 | case $arg in #(
176 | -*) false ;; # don't mess with options #(
177 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
178 | [ -e "$t" ] ;; #(
179 | *) false ;;
180 | esac
181 | then
182 | arg=$( cygpath --path --ignore --mixed "$arg" )
183 | fi
184 | # Roll the args list around exactly as many times as the number of
185 | # args, so each arg winds up back in the position where it started, but
186 | # possibly modified.
187 | #
188 | # NB: a `for` loop captures its iteration list before it begins, so
189 | # changing the positional parameters here affects neither the number of
190 | # iterations, nor the values presented in `arg`.
191 | shift # remove old arg
192 | set -- "$@" "$arg" # push replacement arg
193 | done
194 | fi
195 |
196 | # Collect all arguments for the java command;
197 | # * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
198 | # shell script including quotes and variable substitutions, so put them in
199 | # double quotes to make sure that they get re-expanded; and
200 | # * put everything else in single quotes, so that it's not re-expanded.
201 |
202 | set -- \
203 | "-Dorg.gradle.appname=$APP_BASE_NAME" \
204 | -classpath "$CLASSPATH" \
205 | org.gradle.wrapper.GradleWrapperMain \
206 | "$@"
207 |
208 | # Use "xargs" to parse quoted args.
209 | #
210 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed.
211 | #
212 | # In Bash we could simply go:
213 | #
214 | # readarray ARGS < <( xargs -n1 <<<"$var" ) &&
215 | # set -- "${ARGS[@]}" "$@"
216 | #
217 | # but POSIX shell has neither arrays nor command substitution, so instead we
218 | # post-process each arg (as a line of input to sed) to backslash-escape any
219 | # character that might be a shell metacharacter, then use eval to reverse
220 | # that process (while maintaining the separation between arguments), and wrap
221 | # the whole thing up as a single "set" statement.
222 | #
223 | # This will of course break if any of these variables contains a newline or
224 | # an unmatched quote.
225 | #
226 |
227 | eval "set -- $(
228 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
229 | xargs -n1 |
230 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
231 | tr '\n' ' '
232 | )" '"$@"'
233 |
234 | exec "$JAVACMD" "$@"
235 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @rem
2 | @rem Copyright 2015 the original author or authors.
3 | @rem
4 | @rem Licensed under the Apache License, Version 2.0 (the "License");
5 | @rem you may not use this file except in compliance with the License.
6 | @rem You may obtain a copy of the License at
7 | @rem
8 | @rem https://www.apache.org/licenses/LICENSE-2.0
9 | @rem
10 | @rem Unless required by applicable law or agreed to in writing, software
11 | @rem distributed under the License is distributed on an "AS IS" BASIS,
12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | @rem See the License for the specific language governing permissions and
14 | @rem limitations under the License.
15 | @rem
16 |
17 | @if "%DEBUG%" == "" @echo off
18 | @rem ##########################################################################
19 | @rem
20 | @rem Gradle startup script for Windows
21 | @rem
22 | @rem ##########################################################################
23 |
24 | @rem Set local scope for the variables with windows NT shell
25 | if "%OS%"=="Windows_NT" setlocal
26 |
27 | set DIRNAME=%~dp0
28 | if "%DIRNAME%" == "" set DIRNAME=.
29 | set APP_BASE_NAME=%~n0
30 | set APP_HOME=%DIRNAME%
31 |
32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter.
33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
34 |
35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
37 |
38 | @rem Find java.exe
39 | if defined JAVA_HOME goto findJavaFromJavaHome
40 |
41 | set JAVA_EXE=java.exe
42 | %JAVA_EXE% -version >NUL 2>&1
43 | if "%ERRORLEVEL%" == "0" goto execute
44 |
45 | echo.
46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
47 | echo.
48 | echo Please set the JAVA_HOME variable in your environment to match the
49 | echo location of your Java installation.
50 |
51 | goto fail
52 |
53 | :findJavaFromJavaHome
54 | set JAVA_HOME=%JAVA_HOME:"=%
55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
56 |
57 | if exist "%JAVA_EXE%" goto execute
58 |
59 | echo.
60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
61 | echo.
62 | echo Please set the JAVA_HOME variable in your environment to match the
63 | echo location of your Java installation.
64 |
65 | goto fail
66 |
67 | :execute
68 | @rem Setup the command line
69 |
70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
71 |
72 |
73 | @rem Execute Gradle
74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
75 |
76 | :end
77 | @rem End local scope for the variables with windows NT shell
78 | if "%ERRORLEVEL%"=="0" goto mainEnd
79 |
80 | :fail
81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
82 | rem the _cmd.exe /c_ return code!
83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
84 | exit /b 1
85 |
86 | :mainEnd
87 | if "%OS%"=="Windows_NT" endlocal
88 |
89 | :omega
90 |
--------------------------------------------------------------------------------
/images/example.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/serras/kotlin-mismatch-hints/3d0bc7c5f81f0ebb08edf0eaa28c4dd2f9bc0e06/images/example.png
--------------------------------------------------------------------------------
/settings.gradle.kts:
--------------------------------------------------------------------------------
1 | rootProject.name = "kotlin-mismatch-hints"
--------------------------------------------------------------------------------
/src/main/kotlin/com/serranofp/kotlin/mismatch/hints/MismatchInlayHintProvider.kt:
--------------------------------------------------------------------------------
1 | package com.serranofp.kotlin.mismatch.hints
2 |
3 | import com.intellij.codeInsight.hints.declarative.HintFormat
4 | import com.intellij.codeInsight.hints.declarative.InlayActionData
5 | import com.intellij.codeInsight.hints.declarative.InlayHintsCollector
6 | import com.intellij.codeInsight.hints.declarative.InlayHintsProvider
7 | import com.intellij.codeInsight.hints.declarative.InlayTreeSink
8 | import com.intellij.codeInsight.hints.declarative.InlineInlayPosition
9 | import com.intellij.codeInsight.hints.declarative.PresentationTreeBuilder
10 | import com.intellij.codeInsight.hints.declarative.SharedBypassCollector
11 | import com.intellij.codeInsight.hints.declarative.StringInlayActionPayload
12 | import com.intellij.openapi.editor.Editor
13 | import com.intellij.openapi.util.TextRange
14 | import com.intellij.psi.PsiElement
15 | import com.intellij.psi.PsiFile
16 | import org.jetbrains.kotlin.analysis.api.KaExperimentalApi
17 | import org.jetbrains.kotlin.analysis.api.KaSession
18 | import org.jetbrains.kotlin.analysis.api.analyze
19 | import org.jetbrains.kotlin.analysis.api.components.KaDiagnosticCheckerFilter
20 | import org.jetbrains.kotlin.analysis.api.resolution.KaFunctionCall
21 | import org.jetbrains.kotlin.analysis.api.types.KaCapturedType
22 | import org.jetbrains.kotlin.analysis.api.types.KaClassType
23 | import org.jetbrains.kotlin.analysis.api.types.KaDefinitelyNotNullType
24 | import org.jetbrains.kotlin.analysis.api.types.KaFlexibleType
25 | import org.jetbrains.kotlin.analysis.api.types.KaFunctionType
26 | import org.jetbrains.kotlin.analysis.api.types.KaIntersectionType
27 | import org.jetbrains.kotlin.analysis.api.types.KaStarTypeProjection
28 | import org.jetbrains.kotlin.analysis.api.types.KaType
29 | import org.jetbrains.kotlin.analysis.api.types.KaTypeArgumentWithVariance
30 | import org.jetbrains.kotlin.analysis.api.types.KaTypeProjection
31 | import org.jetbrains.kotlin.idea.codeInsight.hints.KotlinFqnDeclarativeInlayActionHandler
32 | import org.jetbrains.kotlin.psi.KtElement
33 | import org.jetbrains.kotlin.psi.psiUtil.endOffset
34 | import org.jetbrains.kotlin.types.Variance
35 |
36 | @OptIn(KaExperimentalApi::class)
37 | class MismatchInlayHintProvider : InlayHintsProvider {
38 | companion object {
39 | const val PROVIDER_ID : String = "kotlin.mismatch"
40 | }
41 |
42 | override fun createCollector(file: PsiFile, editor: Editor): InlayHintsCollector? = Collector()
43 |
44 | private class Collector : SharedBypassCollector {
45 | override fun collectFromElement(element: PsiElement, sink: InlayTreeSink) {
46 | if (element !is KtElement) return
47 | analyze(element) {
48 | for (diagnostic in element.diagnostics(KaDiagnosticCheckerFilter.ONLY_COMMON_CHECKERS)) {
49 | if (diagnostic.textRanges.isEmpty()) continue
50 | val problem = asProblem(diagnostic) ?: continue
51 | problemHint(problem, element, diagnostic.textRanges, sink)
52 | }
53 | }
54 | }
55 |
56 | fun KaSession.problemHint(problem: Problem, element: KtElement, ranges: Collection, sink: InlayTreeSink) = when (problem) {
57 | is NoneApplicable -> noneApplicableHint(element, sink)
58 |
59 | is ExpectedActualTypeMismatch if problem.dueToNullability -> sink.hintAfter(ranges) {
60 | text(": ")
61 | text(renderNullability(problem.actualType))
62 | text(" ⇏ ")
63 | text(renderNullability(problem.expectedType))
64 | }
65 |
66 | is ExpectedActualTypeMismatch -> sink.hintAfter(ranges) {
67 | text(": ")
68 | val actualType = chooseBetterActualType(element, problem.actualType)
69 | val expectedType = problem.expectedType
70 | val renderQualified = actualType.renderShort() == expectedType.renderShort()
71 | type(actualType, renderQualified)
72 | text(" ⇏ ")
73 | type(expectedType, renderQualified)
74 | }
75 |
76 | is TypeMismatch -> sink.hintAfter(ranges) {
77 | text(": ")
78 | val renderQualified = problem.typeA.renderShort() == problem.typeB.renderShort()
79 | type(problem.typeA, renderQualified)
80 | text(" ≠ ")
81 | type(problem.typeB, renderQualified)
82 | }
83 |
84 | is TypeVarianceMismatch -> sink.hintBefore(ranges) {
85 | text(problem.expectedVariance.label)
86 | text(" ≠ ")
87 | text(problem.actualVariance.label)
88 | }
89 |
90 | is AmbiguousType -> sink.hintAfter(ranges) {
91 | text("<")
92 | val shortCandidateNames = problem.candidates.map { it.renderShort() }
93 | problem.candidates.withSeparator(
94 | separator = { text(" or ") }
95 | ) { candidate ->
96 | val candidateShortName = candidate.renderShort()
97 | val renderQualified = shortCandidateNames.filter { it == candidateShortName }.size > 1
98 | type(candidate, renderQualified)
99 | }
100 | text(">")
101 | }
102 |
103 | else -> {}
104 | }
105 |
106 | private val NONE_APPLICABLE_MAX_OVERLOADS = 4
107 | private val BOLDFACE_NUMBERS = listOf(
108 | "\uD835\uDFD9", "\uD835\uDFDA", "\uD835\uDFDB", "\uD835\uDFDC"
109 | )
110 |
111 | fun KaSession.noneApplicableHint(element: KtElement, sink: InlayTreeSink) {
112 | val bestCandidates =
113 | element.resolveToCallCandidates().filter { it.isInBestCandidates }.map { it.candidate }
114 | val evenBetterCandidates =
115 | bestCandidates.filterIsInstance>()
116 | .filter { !it.hasOptionalArguments() }
117 | // if we have nothing to show, or it is too complicated, bail out
118 | val evenBetterCandidatesCount = evenBetterCandidates.size
119 | if (evenBetterCandidatesCount == 0 || evenBetterCandidatesCount > NONE_APPLICABLE_MAX_OVERLOADS || evenBetterCandidates.size < bestCandidates.size) {
120 | return
121 | }
122 |
123 | for (expression in evenBetterCandidates.first().argumentMapping.keys) {
124 | val expressionType = expression.expressionType
125 | val expressionTypeStringShort = expressionType?.renderShort() ?: "??"
126 | val expressionTypeStringQualified = expressionType?.renderQualified() ?: "??"
127 |
128 | var somethingWrong = false
129 | var needsQualification = false
130 | val actualTypeStrings = mutableListOf Unit>()
131 | for ((index, call) in evenBetterCandidates.withIndex()) {
132 | val signature = call.argumentMapping[expression] ?: continue
133 | val actualTypeStringShort = signature.returnType.renderShort()
134 | val actualTypeStringQualified = signature.returnType.renderQualified()
135 |
136 | when {
137 | expressionTypeStringQualified == actualTypeStringQualified -> {
138 | actualTypeStrings.add {
139 | text("⟦${BOLDFACE_NUMBERS[index]}⟧ ✓")
140 | }
141 | }
142 | else -> {
143 | val thisOneNeedsQualification = expressionTypeStringShort == actualTypeStringShort
144 | actualTypeStrings.add {
145 | text("⟦${BOLDFACE_NUMBERS[index]}⟧ ⇏ ")
146 | type(signature.returnType, thisOneNeedsQualification)
147 | }
148 | somethingWrong = true
149 | needsQualification = needsQualification || thisOneNeedsQualification
150 | }
151 | }
152 | }
153 |
154 | // no problem => do not show hint
155 | if (!somethingWrong) continue
156 |
157 | sink.hintAfter(expression.endOffset) {
158 | text(": ")
159 | if (expressionType == null) { text("??") }
160 | else { type(expressionType, needsQualification) }
161 | }
162 |
163 | for (actualTypeString in actualTypeStrings) {
164 | sink.hintAfter(expression.endOffset, actualTypeString)
165 | }
166 | }
167 | }
168 |
169 | fun InlayTreeSink.hintBefore(ranges: Collection, builder: PresentationTreeBuilder.() -> Unit) =
170 | addPresentation(
171 | InlineInlayPosition(ranges.before, relatedToPrevious = false),
172 | hintFormat = HintFormat.default,
173 | builder = builder
174 | )
175 |
176 | fun InlayTreeSink.hintAfter(ranges: Collection, builder: PresentationTreeBuilder.() -> Unit) =
177 | this.hintAfter(ranges.after, builder)
178 |
179 | fun InlayTreeSink.hintAfter(offset: Int, builder: PresentationTreeBuilder.() -> Unit) =
180 | addPresentation(
181 | InlineInlayPosition(offset, relatedToPrevious = true),
182 | hintFormat = HintFormat.default,
183 | builder = builder
184 | )
185 |
186 | context(session: KaSession)
187 | fun PresentationTreeBuilder.type(type: KaType, renderQualified: Boolean) {
188 | when (type) {
189 | is KaFunctionType -> {
190 | type.receiverType?.let {
191 | type(it, renderQualified)
192 | text(".")
193 | }
194 | text("(")
195 | type.parameterTypes.withSeparator(
196 | separator = { text(", ") }
197 | ) { type(it, renderQualified) }
198 | text(" -> ")
199 | type(type.returnType, renderQualified)
200 | }
201 | is KaClassType -> {
202 | type.symbol.classId?.let { classId ->
203 | val action = InlayActionData(
204 | StringInlayActionPayload(classId.asFqNameString()),
205 | handlerId = KotlinFqnDeclarativeInlayActionHandler.HANDLER_NAME
206 | )
207 | text(classId.render(renderQualified), action)
208 | } ?: text("??")
209 |
210 | if (type.typeArguments.isNotEmpty()) {
211 | text("<")
212 | type.typeArguments.withSeparator(
213 | separator = { text(", ") }
214 | ) { projection(it, renderQualified) }
215 | text(">")
216 | }
217 | }
218 | is KaDefinitelyNotNullType -> {
219 | type(type.original, renderQualified)
220 | text(" & Any")
221 | }
222 | is KaIntersectionType -> {
223 | type.conjuncts.withSeparator(
224 | separator = { text(" & ") }
225 | ) { type(it, renderQualified) }
226 | }
227 | is KaFlexibleType -> {
228 | type(type.lowerBound, renderQualified)
229 | text(" .. ")
230 | type(type.upperBound, renderQualified)
231 | }
232 | is KaCapturedType -> {
233 | projection(type.projection, renderQualified)
234 | }
235 | else -> text(type.renderShort())
236 | }
237 | if (type.nullability.isNullable) {
238 | text("?")
239 | }
240 | }
241 |
242 | context(session: KaSession)
243 | fun PresentationTreeBuilder.projection(projection: KaTypeProjection, renderQualified: Boolean) {
244 | when (projection) {
245 | is KaStarTypeProjection -> {
246 | text("*")
247 | text(" : ")
248 | }
249 | is KaTypeArgumentWithVariance if projection.variance != Variance.INVARIANT -> {
250 | text(projection.variance.label)
251 | text(" ")
252 | }
253 | else -> { }
254 | }
255 | projection.type?.let { type(it, renderQualified) }
256 | }
257 |
258 | fun Iterable.withSeparator(
259 | separator: () -> Unit,
260 | block: (A) -> Unit
261 | ) {
262 | firstOrNull()?.let { block(it) }
263 | drop(1).forEach {
264 | separator()
265 | block(it)
266 | }
267 | }
268 | }
269 | }
--------------------------------------------------------------------------------
/src/main/kotlin/com/serranofp/kotlin/mismatch/hints/Problem.kt:
--------------------------------------------------------------------------------
1 | package com.serranofp.kotlin.mismatch.hints
2 |
3 | import org.jetbrains.kotlin.analysis.api.KaSession
4 | import org.jetbrains.kotlin.analysis.api.diagnostics.KaDiagnosticWithPsi
5 | import org.jetbrains.kotlin.analysis.api.fir.diagnostics.KaFirDiagnostic
6 | import org.jetbrains.kotlin.analysis.api.symbols.KaSymbol
7 | import org.jetbrains.kotlin.analysis.api.types.KaType
8 | import org.jetbrains.kotlin.types.Variance
9 |
10 | sealed interface Problem
11 | data class ExpectedActualTypeMismatch(val expectedType: KaType, val actualType: KaType, val dueToNullability: Boolean) : Problem
12 | data class TypeMismatch(val typeA: KaType, val typeB: KaType) : Problem
13 | data class TypeVarianceMismatch(val expectedVariance: Variance, val actualVariance: Variance) : Problem
14 | data class NoneApplicable(val candidates: List) : Problem
15 | data class AmbiguousType(val candidates: List) : Problem
16 | data class AmbiguousCandidate(val candidates: List) : Problem
17 |
18 | @Suppress("UNCHECKED_CAST")
19 | fun KaSession.asProblem(element: KaDiagnosticWithPsi<*>): Problem? = when (element) {
20 | is KaFirDiagnostic.TypeMismatch -> ExpectedActualTypeMismatch(element.expectedType, element.actualType, element.isMismatchDueToNullability)
21 | is KaFirDiagnostic.TypeMismatchWhenFlexibilityChanges -> ExpectedActualTypeMismatch(element.expectedType, element.actualType, false)
22 | is KaFirDiagnostic.JavaTypeMismatch -> ExpectedActualTypeMismatch(element.expectedType, element.actualType, false)
23 | is KaFirDiagnostic.ArgumentTypeMismatch -> ExpectedActualTypeMismatch(element.expectedType, element.actualType, element.isMismatchDueToNullability)
24 | is KaFirDiagnostic.InitializerTypeMismatch -> ExpectedActualTypeMismatch(element.expectedType, element.actualType, element.isMismatchDueToNullability)
25 | is KaFirDiagnostic.AssignmentTypeMismatch -> ExpectedActualTypeMismatch(element.expectedType, element.actualType, element.isMismatchDueToNullability)
26 | is KaFirDiagnostic.ResultTypeMismatch -> ExpectedActualTypeMismatch(element.expectedType, element.actualType, false)
27 | is KaFirDiagnostic.ReturnTypeMismatch -> ExpectedActualTypeMismatch(element.expectedType, element.actualType, element.isMismatchDueToNullability)
28 | is KaFirDiagnostic.ConditionTypeMismatch -> ExpectedActualTypeMismatch(builtinTypes.boolean, element.actualType, element.isMismatchDueToNullability)
29 | is KaFirDiagnostic.ThrowableTypeMismatch -> ExpectedActualTypeMismatch(builtinTypes.throwable, element.actualType, element.isMismatchDueToNullability)
30 | is KaFirDiagnostic.NullForNonnullType -> ExpectedActualTypeMismatch(element.expectedType, builtinTypes.nullableNothing, false)
31 | is KaFirDiagnostic.UpperBoundViolated -> ExpectedActualTypeMismatch(element.expectedUpperBound, element.actualUpperBound, false)
32 | is KaFirDiagnostic.IncompatibleTypes -> TypeMismatch(element.typeA, element.typeB)
33 | is KaFirDiagnostic.IncompatibleTypesWarning -> TypeMismatch(element.typeA, element.typeB)
34 | is KaFirDiagnostic.TypeVarianceConflictError -> TypeVarianceMismatch(element.typeParameterVariance, element.variance)
35 | is KaFirDiagnostic.TypeVarianceConflictInExpandedType -> TypeVarianceMismatch(element.typeParameterVariance, element.variance)
36 | is KaFirDiagnostic.NoneApplicable -> NoneApplicable(element.candidates)
37 | is KaFirDiagnostic.InapplicableCandidate -> NoneApplicable(listOf(element.candidate))
38 | is KaFirDiagnostic.AmbiguousSuper -> AmbiguousType(element.candidates)
39 | is KaFirDiagnostic.OverloadResolutionAmbiguity -> AmbiguousCandidate(element.candidates)
40 | else -> null
41 | }
--------------------------------------------------------------------------------
/src/main/kotlin/com/serranofp/kotlin/mismatch/hints/TypeUtils.kt:
--------------------------------------------------------------------------------
1 | package com.serranofp.kotlin.mismatch.hints
2 |
3 | import com.intellij.openapi.util.TextRange
4 | import org.jetbrains.kotlin.analysis.api.KaExperimentalApi
5 | import org.jetbrains.kotlin.analysis.api.KaSession
6 | import org.jetbrains.kotlin.analysis.api.renderer.types.impl.KaTypeRendererForSource
7 | import org.jetbrains.kotlin.analysis.api.resolution.KaCallableMemberCall
8 | import org.jetbrains.kotlin.analysis.api.signatures.KaCallableSignature
9 | import org.jetbrains.kotlin.analysis.api.symbols.KaCallableSymbol
10 | import org.jetbrains.kotlin.analysis.api.symbols.KaFunctionSymbol
11 | import org.jetbrains.kotlin.analysis.api.symbols.KaVariableSymbol
12 | import org.jetbrains.kotlin.analysis.api.types.KaClassType
13 | import org.jetbrains.kotlin.analysis.api.types.KaType
14 | import org.jetbrains.kotlin.analysis.api.types.KaTypeParameterType
15 | import org.jetbrains.kotlin.name.ClassId
16 | import org.jetbrains.kotlin.psi.KtElement
17 | import org.jetbrains.kotlin.psi.KtExpression
18 | import org.jetbrains.kotlin.types.Variance
19 |
20 | context(session: KaSession)
21 | @OptIn(KaExperimentalApi::class)
22 | fun KaType.renderShort(): String = with(session) {
23 | this@renderShort.render(renderer = KaTypeRendererForSource.WITH_SHORT_NAMES, position = Variance.INVARIANT)
24 | }
25 |
26 | context(session: KaSession)
27 | @OptIn(KaExperimentalApi::class)
28 | fun KaType.renderQualified(): String = with(session) {
29 | this@renderQualified.render(renderer = KaTypeRendererForSource.WITH_QUALIFIED_NAMES, position = Variance.INVARIANT)
30 | }
31 |
32 | fun renderNullability(type: KaType): String = if (type.nullability.isNullable) "nullable" else "non-nullable"
33 |
34 | fun ClassId.render(renderQualified: Boolean): String = when {
35 | outerClassId != null -> "${outerClassId!!.render(renderQualified)}.$shortClassName"
36 | renderQualified -> "${this.packageFqName.pathSegments().joinToString(".")}.$shortClassName"
37 | else -> "$shortClassName"
38 | }
39 |
40 | context(session: KaSession)
41 | fun chooseBetterActualType(element: KtElement, problem: KaType): KaType = with(session) {
42 | val expression = (element as? KtExpression)?.expressionType ?: return problem
43 | if (expression.approximatedIsGenericInstantiationOf(problem)) return expression
44 | return problem
45 | }
46 |
47 | fun > KaCallableMemberCall.hasOptionalArguments(): Boolean =
48 | when (val symbol = partiallyAppliedSymbol.signature.symbol) {
49 | is KaVariableSymbol -> false
50 | is KaFunctionSymbol -> symbol.valueParameters.any { it.hasDefaultValue }
51 | }
52 |
53 | fun KaType.approximatedIsGenericInstantiationOf(other: KaType): Boolean {
54 | when (other) {
55 | is KaTypeParameterType -> return true
56 | else -> when {
57 | this is KaClassType && other is KaClassType -> {
58 | if (this.classId != other.classId) return false
59 | if (this.typeArguments.size != other.typeArguments.size) return false
60 | return this.typeArguments.zip(other.typeArguments).all { (a, b) ->
61 | val aType = a.type ?: return false
62 | val bType = b.type ?: return false
63 | aType.approximatedIsGenericInstantiationOf(bType)
64 | }
65 | }
66 |
67 | else -> return false
68 | }
69 | }
70 | }
71 |
72 | val Collection.before : Int get() = this.first().startOffset
73 | val Collection.after : Int get() = this.last().endOffset
--------------------------------------------------------------------------------
/src/main/resources/META-INF/plugin.xml:
--------------------------------------------------------------------------------
1 |
2 | com.serranofp.kotlin-mismatch-hints
3 | Kotlin Mismatch Hints
4 | Serrano FP
5 | Inlay hints succinctly describing mismatches in Kotlin code
6 |
7 | com.intellij.modules.platform
8 | org.jetbrains.kotlin
9 |
10 |
11 |
12 |
13 |
14 |
15 |
23 |
24 |
25 |
--------------------------------------------------------------------------------
/src/main/resources/messages/kotlin-mismatch-hints.properties:
--------------------------------------------------------------------------------
1 | mismatch=Mismatch Hints
--------------------------------------------------------------------------------