Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support for inlay hints #498

Merged
merged 21 commits into from
Oct 20, 2023
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@ class KotlinLanguageServer : LanguageServer, LanguageClientAware, Closeable {
serverCapabilities.workspace.workspaceFolders = WorkspaceFoldersOptions()
serverCapabilities.workspace.workspaceFolders.supported = true
serverCapabilities.workspace.workspaceFolders.changeNotifications = Either.forRight(true)
serverCapabilities.inlayHintProvider = Either.forLeft(true)
serverCapabilities.hoverProvider = Either.forLeft(true)
serverCapabilities.renameProvider = Either.forLeft(true)
serverCapabilities.completionProvider = CompletionOptions(false, listOf("."))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,17 +16,11 @@ import org.javacs.kt.position.position
import org.javacs.kt.references.findReferences
import org.javacs.kt.semantictokens.encodedSemanticTokens
import org.javacs.kt.signaturehelp.fetchSignatureHelpAt
import org.javacs.kt.symbols.documentSymbols
import org.javacs.kt.util.noResult
import org.javacs.kt.util.AsyncExecutor
import org.javacs.kt.util.Debouncer
import org.javacs.kt.util.filePath
import org.javacs.kt.util.TemporaryDirectory
import org.javacs.kt.util.parseURI
import org.javacs.kt.util.describeURI
import org.javacs.kt.util.describeURIs
import org.javacs.kt.rename.renameSymbol
import org.javacs.kt.highlight.documentHighlightsAt
import org.javacs.kt.inlayhints.provideHints
import org.javacs.kt.symbols.*
elamc-2 marked this conversation as resolved.
Show resolved Hide resolved
import org.javacs.kt.util.*
import org.jetbrains.kotlin.resolve.diagnostics.Diagnostics
import java.net.URI
import java.io.Closeable
Expand Down Expand Up @@ -95,6 +89,11 @@ class KotlinTextDocumentService(
codeActions(file, sp.index, params.range, params.context)
}

override fun inlayHint(params: InlayHintParams): CompletableFuture<List<InlayHint>> = async.compute {
val (file, _) = recover(params.textDocument.uri, params.range.start, Recompile.ALWAYS)
provideHints(file)
}

override fun hover(position: HoverParams): CompletableFuture<Hover?> = async.compute {
reportTime {
LOG.info("Hovering at {}", describePosition(position))
Expand Down
112 changes: 112 additions & 0 deletions server/src/main/kotlin/org/javacs/kt/inlayhints/InlayHint.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
package org.javacs.kt.inlayhints

import com.intellij.psi.PsiElement
import com.intellij.psi.PsiNameIdentifierOwner
import org.eclipse.lsp4j.InlayHint
import org.eclipse.lsp4j.InlayHintKind
import org.eclipse.lsp4j.jsonrpc.messages.Either
import org.javacs.kt.CompiledFile
import org.javacs.kt.completion.DECL_RENDERER
import org.javacs.kt.position.range
import org.javacs.kt.util.preOrderTraversal
import org.jetbrains.kotlin.descriptors.CallableDescriptor
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getChildOfType
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.calls.model.VarargValueArgument
import org.jetbrains.kotlin.resolve.calls.smartcasts.getKotlinTypeForComparison
import org.jetbrains.kotlin.resolve.calls.util.*
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.error.ErrorType

private fun PsiElement.determineType(ctx: BindingContext): KotlinType? =
when (this) {
is KtParameter -> {
if (this.isLambdaParameter and (this.typeReference == null)) {
val descriptor = ctx[BindingContext.DECLARATION_TO_DESCRIPTOR, this] as CallableDescriptor
descriptor.returnType
} else null
}
is KtDestructuringDeclarationEntry -> {
val resolvedCall = ctx[BindingContext.COMPONENT_RESOLVED_CALL, this]
resolvedCall?.resultingDescriptor?.returnType
}
is KtProperty -> {
//TODO: better handling for unresolved-type error
elamc-2 marked this conversation as resolved.
Show resolved Hide resolved
val type = this.getKotlinTypeForComparison(ctx)
if (type is ErrorType) null else type
}
else -> null
}

private fun PsiElement.hintBuilder(kind: InlayHintKind, file: CompiledFile, label: String? = null): InlayHint? {
val namedElement = ((this as? PsiNameIdentifierOwner)?.nameIdentifier ?: this)
val range = range(file.parse.text, namedElement.textRange)
val hint = when(kind) {
InlayHintKind.Type ->
this.determineType(file.compile) ?.let {
InlayHint(range.end, Either.forLeft(": ${DECL_RENDERER.renderType(it)}"))
} ?: return null
InlayHintKind.Parameter -> InlayHint(range.start, Either.forLeft("$label:"))
}
hint.kind = kind
hint.paddingRight = true
hint.paddingLeft = true
return hint
}

private fun callableArgsToHints(
callExpression: KtCallExpression,
file: CompiledFile,
): List<InlayHint> {
val resolvedCall = callExpression.getResolvedCall(file.compile)

val hints = mutableListOf<InlayHint>()
resolvedCall?.valueArguments?.forEach { (t, u) ->
elamc-2 marked this conversation as resolved.
Show resolved Hide resolved
val valueArg = u.arguments.first()

if (!valueArg.isNamed()) {
val label = (t.name).let { name ->
when (u) {
is VarargValueArgument -> "...$name"
else -> name.asString()
}
}
valueArg.asElement().hintBuilder(InlayHintKind.Parameter, file, label)?.let { hints.add(it) }
}
}
return hints
}

private fun lambdaValueParamsToHints(node: KtLambdaArgument, file: CompiledFile): List<InlayHint> {
return node.getLambdaExpression()!!.valueParameters.mapNotNull {
it.hintBuilder(InlayHintKind.Type, file)
}
}

fun provideHints(file: CompiledFile): List<InlayHint> {
val hints = mutableListOf<InlayHint>()
for (node in file.parse.preOrderTraversal().asIterable()) {
when (node) {
is KtLambdaArgument -> {
hints.addAll(lambdaValueParamsToHints(node, file))
}
is KtCallExpression -> {
//hints are not rendered for argument of type lambda expression i.e. list.map { it }
if (node.getChildOfType<KtLambdaArgument>() == null) {
hints.addAll(callableArgsToHints(node, file))
}
}
is KtDestructuringDeclaration -> {
hints.addAll(node.entries.mapNotNull { it.hintBuilder(InlayHintKind.Type, file) })
}
is KtProperty -> {
//check decleration does not include type i.e. var t1: String
if (node.typeReference == null) {
node.hintBuilder(InlayHintKind.Type, file)?.let { hints.add(it) }
}
}
}
}
return hints
}