├── .gitattributes ├── .github └── workflows │ └── build.yml ├── .gitignore ├── LICENSE ├── README.md ├── build.gradle.kts ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── settings.gradle.kts └── src ├── main └── kotlin │ └── dev │ └── fwcd │ └── kas │ ├── KotlinLanguageServer.kt │ ├── KotlinTextDocumentService.kt │ ├── KotlinWorkspaceService.kt │ └── Main.kt └── test └── kotlin └── dev └── fwcd └── kas └── AppTest.kt /.gitattributes: -------------------------------------------------------------------------------- 1 | # 2 | # https://help.github.com/articles/dealing-with-line-endings/ 3 | # 4 | # These are explicitly windows files and should use crlf 5 | *.bat text eol=crlf 6 | 7 | -------------------------------------------------------------------------------- /.github/workflows/build.yml: -------------------------------------------------------------------------------- 1 | name: Build 2 | 3 | on: 4 | push: 5 | branches: 6 | - main 7 | pull_request: 8 | 9 | jobs: 10 | build: 11 | runs-on: ubuntu-latest 12 | strategy: 13 | matrix: 14 | java: ['17'] 15 | steps: 16 | - uses: actions/checkout@v3 17 | - name: Setup JDK 18 | uses: actions/setup-java@v3 19 | with: 20 | distribution: 'temurin' 21 | java-version: ${{ matrix.java }} 22 | - uses: gradle/gradle-build-action@v2 23 | - name: Build 24 | run: ./gradlew build 25 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | .vscode 3 | .idea 4 | .settings 5 | .project 6 | .gradle 7 | build 8 | bin 9 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2022 fwcd 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Kotlin Analysis Server 2 | 3 | [![Build](https://github.com/fwcd/kotlin-analysis-server/actions/workflows/build.yml/badge.svg)](https://github.com/fwcd/kotlin-analysis-server/actions/workflows/build.yml) 4 | 5 | An experimental [language server](https://microsoft.github.io/language-server-protocol/) for [Kotlin](https://kotlinlang.org/) using the new analysis APIs, aiming to provide high-fidelity code completion, etc. 6 | -------------------------------------------------------------------------------- /build.gradle.kts: -------------------------------------------------------------------------------- 1 | val analysisApiKotlinVersion: String by project 2 | val intellijVersion: String by project 3 | 4 | plugins { 5 | // Apply the Kotlin JVM Plugin to add support for Kotlin. 6 | kotlin("jvm") 7 | 8 | // Apply the application plugin to add support for building a CLI application in Java. 9 | application 10 | } 11 | 12 | repositories { 13 | // Use Maven Central for resolving dependencies. 14 | mavenCentral() 15 | 16 | // Add Maven repos for Kotlin compiler etc. 17 | maven(url = "https://maven.pkg.jetbrains.space/kotlin/p/kotlin/bootstrap") 18 | maven(url = "https://maven.pkg.jetbrains.space/kotlin/p/kotlin/kotlin-ide-plugin-dependencies") 19 | maven(url = "https://www.jetbrains.com/intellij-repository/releases") 20 | maven(url = "https://cache-redirector.jetbrains.com/intellij-third-party-dependencies") 21 | } 22 | 23 | dependencies { 24 | // Align versions of all Kotlin components 25 | implementation(platform("org.jetbrains.kotlin:kotlin-bom")) 26 | // Kotlin standard library 27 | implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8") 28 | implementation("org.jetbrains.kotlinx:kotlinx-collections-immutable-jvm:0.3.4") 29 | // LSP library 30 | implementation("org.eclipse.lsp4j:org.eclipse.lsp4j:0.14.0") 31 | // IntelliJ IDEA APIs distributed as a library (required by the analysis API and Kotlin compiler) 32 | implementation("com.jetbrains.intellij.platform:core:$intellijVersion") 33 | implementation("com.jetbrains.intellij.platform:core-impl:$intellijVersion") 34 | implementation("com.jetbrains.intellij.platform:util:$intellijVersion") 35 | // Kotlin compiler and analysis API 36 | // See https://github.com/google/ksp/blob/319ddf/kotlin-analysis-api/build.gradle.kts 37 | implementation("org.jetbrains.kotlin:kotlin-compiler:$analysisApiKotlinVersion") 38 | implementation("org.jetbrains.kotlin:high-level-api-fir-for-ide:$analysisApiKotlinVersion") { 39 | isTransitive = false 40 | } 41 | implementation("org.jetbrains.kotlin:high-level-api-for-ide:$analysisApiKotlinVersion") { 42 | isTransitive = false 43 | } 44 | implementation("org.jetbrains.kotlin:low-level-api-fir-for-ide:$analysisApiKotlinVersion") { 45 | isTransitive = false 46 | } 47 | implementation("org.jetbrains.kotlin:analysis-api-providers-for-ide:$analysisApiKotlinVersion") { 48 | isTransitive = false 49 | } 50 | implementation("org.jetbrains.kotlin:analysis-project-structure-for-ide:$analysisApiKotlinVersion") { 51 | isTransitive = false 52 | } 53 | implementation("org.jetbrains.kotlin:symbol-light-classes-for-ide:$analysisApiKotlinVersion") { 54 | isTransitive = false 55 | } 56 | implementation("org.jetbrains.kotlin:analysis-api-standalone-for-ide:$analysisApiKotlinVersion") { 57 | isTransitive = false 58 | } 59 | implementation("org.jetbrains.kotlin:high-level-api-impl-base-for-ide:$analysisApiKotlinVersion") { 60 | isTransitive = false 61 | } 62 | } 63 | 64 | tasks.withType { 65 | kotlinOptions { 66 | jvmTarget = "11" 67 | } 68 | } 69 | 70 | java { 71 | toolchain.languageVersion.set(JavaLanguageVersion.of(11)) 72 | } 73 | 74 | testing { 75 | suites { 76 | // Configure the built-in test suite 77 | val test by getting(JvmTestSuite::class) { 78 | // Use Kotlin Test test framework 79 | useKotlinTest() 80 | } 81 | } 82 | } 83 | 84 | application { 85 | // Define the main class for the application. 86 | mainClass.set("dev.fwcd.kas.MainKt") 87 | } 88 | -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | buildKotlinVersion=1.9.23 2 | analysisApiKotlinVersion=2.0.20-dev-3728 3 | intellijVersion=213.7172.25 4 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fwcd/kotlin-analysis-server/3bfbc1866b08a2cb77f76676cad2ee590276489c/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.8-bin.zip 4 | networkTimeout=10000 5 | validateDistributionUrl=true 6 | zipStoreBase=GRADLE_USER_HOME 7 | zipStorePath=wrapper/dists 8 | -------------------------------------------------------------------------------- /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/HEAD/platforms/jvm/plugins-application/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 | # This is normally unused 84 | # shellcheck disable=SC2034 85 | APP_BASE_NAME=${0##*/} 86 | # Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) 87 | APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit 88 | 89 | # Use the maximum available, or set MAX_FD != -1 to use that value. 90 | MAX_FD=maximum 91 | 92 | warn () { 93 | echo "$*" 94 | } >&2 95 | 96 | die () { 97 | echo 98 | echo "$*" 99 | echo 100 | exit 1 101 | } >&2 102 | 103 | # OS specific support (must be 'true' or 'false'). 104 | cygwin=false 105 | msys=false 106 | darwin=false 107 | nonstop=false 108 | case "$( uname )" in #( 109 | CYGWIN* ) cygwin=true ;; #( 110 | Darwin* ) darwin=true ;; #( 111 | MSYS* | MINGW* ) msys=true ;; #( 112 | NONSTOP* ) nonstop=true ;; 113 | esac 114 | 115 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 116 | 117 | 118 | # Determine the Java command to use to start the JVM. 119 | if [ -n "$JAVA_HOME" ] ; then 120 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 121 | # IBM's JDK on AIX uses strange locations for the executables 122 | JAVACMD=$JAVA_HOME/jre/sh/java 123 | else 124 | JAVACMD=$JAVA_HOME/bin/java 125 | fi 126 | if [ ! -x "$JAVACMD" ] ; then 127 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 128 | 129 | Please set the JAVA_HOME variable in your environment to match the 130 | location of your Java installation." 131 | fi 132 | else 133 | JAVACMD=java 134 | if ! command -v java >/dev/null 2>&1 135 | then 136 | 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 | fi 142 | 143 | # Increase the maximum file descriptors if we can. 144 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then 145 | case $MAX_FD in #( 146 | max*) 147 | # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. 148 | # shellcheck disable=SC2039,SC3045 149 | MAX_FD=$( ulimit -H -n ) || 150 | warn "Could not query maximum file descriptor limit" 151 | esac 152 | case $MAX_FD in #( 153 | '' | soft) :;; #( 154 | *) 155 | # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. 156 | # shellcheck disable=SC2039,SC3045 157 | ulimit -n "$MAX_FD" || 158 | warn "Could not set maximum file descriptor limit to $MAX_FD" 159 | esac 160 | fi 161 | 162 | # Collect all arguments for the java command, stacking in reverse order: 163 | # * args from the command line 164 | # * the main class name 165 | # * -classpath 166 | # * -D...appname settings 167 | # * --module-path (only if needed) 168 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. 169 | 170 | # For Cygwin or MSYS, switch paths to Windows format before running java 171 | if "$cygwin" || "$msys" ; then 172 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) 173 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) 174 | 175 | JAVACMD=$( cygpath --unix "$JAVACMD" ) 176 | 177 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 178 | for arg do 179 | if 180 | case $arg in #( 181 | -*) false ;; # don't mess with options #( 182 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath 183 | [ -e "$t" ] ;; #( 184 | *) false ;; 185 | esac 186 | then 187 | arg=$( cygpath --path --ignore --mixed "$arg" ) 188 | fi 189 | # Roll the args list around exactly as many times as the number of 190 | # args, so each arg winds up back in the position where it started, but 191 | # possibly modified. 192 | # 193 | # NB: a `for` loop captures its iteration list before it begins, so 194 | # changing the positional parameters here affects neither the number of 195 | # iterations, nor the values presented in `arg`. 196 | shift # remove old arg 197 | set -- "$@" "$arg" # push replacement arg 198 | done 199 | fi 200 | 201 | 202 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 203 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 204 | 205 | # Collect all arguments for the java command: 206 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, 207 | # and any embedded shellness will be escaped. 208 | # * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be 209 | # treated as '${Hostname}' itself on the command line. 210 | 211 | set -- \ 212 | "-Dorg.gradle.appname=$APP_BASE_NAME" \ 213 | -classpath "$CLASSPATH" \ 214 | org.gradle.wrapper.GradleWrapperMain \ 215 | "$@" 216 | 217 | # Stop when "xargs" is not available. 218 | if ! command -v xargs >/dev/null 2>&1 219 | then 220 | die "xargs is not available" 221 | fi 222 | 223 | # Use "xargs" to parse quoted args. 224 | # 225 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 226 | # 227 | # In Bash we could simply go: 228 | # 229 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 230 | # set -- "${ARGS[@]}" "$@" 231 | # 232 | # but POSIX shell has neither arrays nor command substitution, so instead we 233 | # post-process each arg (as a line of input to sed) to backslash-escape any 234 | # character that might be a shell metacharacter, then use eval to reverse 235 | # that process (while maintaining the separation between arguments), and wrap 236 | # the whole thing up as a single "set" statement. 237 | # 238 | # This will of course break if any of these variables contains a newline or 239 | # an unmatched quote. 240 | # 241 | 242 | eval "set -- $( 243 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 244 | xargs -n1 | 245 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 246 | tr '\n' ' ' 247 | )" '"$@"' 248 | 249 | exec "$JAVACMD" "$@" 250 | -------------------------------------------------------------------------------- /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 | @rem This is normally unused 30 | set APP_BASE_NAME=%~n0 31 | set APP_HOME=%DIRNAME% 32 | 33 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 34 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 35 | 36 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 37 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 38 | 39 | @rem Find java.exe 40 | if defined JAVA_HOME goto findJavaFromJavaHome 41 | 42 | set JAVA_EXE=java.exe 43 | %JAVA_EXE% -version >NUL 2>&1 44 | if %ERRORLEVEL% equ 0 goto execute 45 | 46 | echo. 1>&2 47 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 48 | echo. 1>&2 49 | echo Please set the JAVA_HOME variable in your environment to match the 1>&2 50 | echo location of your Java installation. 1>&2 51 | 52 | goto fail 53 | 54 | :findJavaFromJavaHome 55 | set JAVA_HOME=%JAVA_HOME:"=% 56 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 57 | 58 | if exist "%JAVA_EXE%" goto execute 59 | 60 | echo. 1>&2 61 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 62 | echo. 1>&2 63 | echo Please set the JAVA_HOME variable in your environment to match the 1>&2 64 | echo location of your Java installation. 1>&2 65 | 66 | goto fail 67 | 68 | :execute 69 | @rem Setup the command line 70 | 71 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 72 | 73 | 74 | @rem Execute Gradle 75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 76 | 77 | :end 78 | @rem End local scope for the variables with windows NT shell 79 | if %ERRORLEVEL% equ 0 goto mainEnd 80 | 81 | :fail 82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 83 | rem the _cmd.exe /c_ return code! 84 | set EXIT_CODE=%ERRORLEVEL% 85 | if %EXIT_CODE% equ 0 set EXIT_CODE=1 86 | if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% 87 | exit /b %EXIT_CODE% 88 | 89 | :mainEnd 90 | if "%OS%"=="Windows_NT" endlocal 91 | 92 | :omega 93 | -------------------------------------------------------------------------------- /settings.gradle.kts: -------------------------------------------------------------------------------- 1 | rootProject.name = "kotlin-analysis-server" 2 | 3 | pluginManagement { 4 | val buildKotlinVersion: String by settings 5 | 6 | plugins { 7 | kotlin("jvm") version buildKotlinVersion apply false 8 | } 9 | 10 | repositories { 11 | gradlePluginPortal() 12 | maven("https://maven.pkg.jetbrains.space/kotlin/p/kotlin/bootstrap/") 13 | maven("https://www.jetbrains.com/intellij-repository/snapshots") 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/main/kotlin/dev/fwcd/kas/KotlinLanguageServer.kt: -------------------------------------------------------------------------------- 1 | package dev.fwcd.kas 2 | 3 | import com.intellij.mock.MockProject 4 | import org.eclipse.lsp4j.* 5 | import org.eclipse.lsp4j.services.* 6 | import org.jetbrains.kotlin.analysis.api.KtAnalysisApiInternals 7 | import org.jetbrains.kotlin.analysis.api.lifetime.KtLifetimeTokenProvider 8 | import org.jetbrains.kotlin.analysis.api.standalone.KtAlwaysAccessibleLifetimeTokenProvider 9 | import org.jetbrains.kotlin.analysis.api.standalone.buildStandaloneAnalysisAPISession 10 | import org.jetbrains.kotlin.analysis.project.structure.builder.buildKtSourceModule 11 | import org.jetbrains.kotlin.platform.jvm.JvmPlatforms 12 | import java.net.URI 13 | import java.nio.file.Path 14 | import java.util.concurrent.CompletableFuture 15 | import java.util.logging.Logger 16 | 17 | private val LOG = Logger.getLogger(KotlinLanguageServer::class.java.name) 18 | 19 | /** 20 | * The language server implementation, responsible for basic lifecycle management, i.e. 21 | * initialization and shutdown. The request implementations are handled by 22 | * `KotlinTextDocumentService` and `KotlinWorkspaceService`. 23 | */ 24 | class KotlinLanguageServer: LanguageServer, LanguageClientAware { 25 | /** The text document service responsible for handling code completion requests, etc. */ 26 | private val textDocuments = KotlinTextDocumentService() 27 | /** The text document service responsible for handling workspace updates, etc. */ 28 | private val workspaces = KotlinWorkspaceService() 29 | 30 | /** A proxy object for sending messages to the client. */ 31 | private var client: LanguageClient? = null 32 | 33 | @OptIn(KtAnalysisApiInternals::class) 34 | override fun initialize(params: InitializeParams?): CompletableFuture { 35 | // TODO: Investigate proper lifecycle management with disposables (should we store a Disposable in the class?) 36 | // TODO: Add a proper logging abstraction that uses LSP's logMessage underneath 37 | 38 | client?.logMessage(MessageParams(MessageType.Info, "Locating sources...")) 39 | // TODO: Make source-resolution more flexible (currently only Gradle-style src/main/kotlin folders are considered) 40 | val workspaceFolders = params?.workspaceFolders ?: listOf() 41 | val sourceRoots = workspaceFolders 42 | .map { Path.of(URI(it.uri)).resolve("src").resolve("main").resolve("kotlin") } 43 | 44 | // Configure headless IDEA to not spawn an app in the Dock 45 | // https://stackoverflow.com/questions/17460777/stop-java-coffee-cup-icon-from-appearing-in-the-dock-on-mac-osx 46 | System.setProperty("apple.awt.UIElement", "true") 47 | 48 | client?.logMessage(MessageParams(MessageType.Info, "Setting up standalone analysis API session...")) 49 | val session = buildStandaloneAnalysisAPISession { 50 | // FIXME: This workaround fixing a 'getService(...) must not be null' crash should be replaced (and the @OptIn removed) 51 | // See also https://youtrack.jetbrains.com/issue/KT-65215/Analysis-API-Distinguish-APIs-for-Analysis-API-users-and-platforms 52 | (project as MockProject).registerService( 53 | KtLifetimeTokenProvider::class.java, 54 | KtAlwaysAccessibleLifetimeTokenProvider::class.java 55 | ) 56 | 57 | buildKtModuleProvider { 58 | platform = JvmPlatforms.defaultJvmPlatform 59 | 60 | addModule(buildKtSourceModule { 61 | moduleName = "Language server project sources" // TODO 62 | platform = JvmPlatforms.defaultJvmPlatform 63 | 64 | // TODO: We should handle (virtual) file changes announced via LSP with the VFS 65 | addSourceRoots(sourceRoots) 66 | }) 67 | } 68 | } 69 | textDocuments.session = session 70 | 71 | // Assemble LSP initialization response 72 | val result = InitializeResult( 73 | ServerCapabilities().apply { 74 | completionProvider = CompletionOptions() 75 | diagnosticProvider = DiagnosticRegistrationOptions() 76 | }, 77 | ServerInfo("Kotlin Analysis Server") 78 | ) 79 | 80 | return CompletableFuture.completedFuture(result) 81 | } 82 | 83 | override fun connect(client: LanguageClient?) { 84 | this.client = client 85 | } 86 | 87 | override fun shutdown(): CompletableFuture { 88 | return CompletableFuture.completedFuture(Unit) 89 | } 90 | 91 | override fun exit() {} 92 | 93 | override fun getTextDocumentService(): TextDocumentService = textDocuments 94 | 95 | override fun getWorkspaceService(): WorkspaceService = workspaces 96 | } 97 | -------------------------------------------------------------------------------- /src/main/kotlin/dev/fwcd/kas/KotlinTextDocumentService.kt: -------------------------------------------------------------------------------- 1 | package dev.fwcd.kas 2 | 3 | import com.intellij.openapi.util.TextRange 4 | import com.intellij.openapi.util.text.StringUtil 5 | import com.intellij.openapi.vfs.StandardFileSystems 6 | import com.intellij.psi.PsiElement 7 | import com.intellij.psi.PsiManager 8 | import org.eclipse.lsp4j.* 9 | import org.eclipse.lsp4j.jsonrpc.messages.Either 10 | import org.eclipse.lsp4j.services.TextDocumentService 11 | import org.jetbrains.kotlin.analysis.api.analyze 12 | import org.jetbrains.kotlin.analysis.api.components.KtDiagnosticCheckerFilter 13 | import org.jetbrains.kotlin.analysis.api.diagnostics.KtDiagnosticWithPsi 14 | import org.jetbrains.kotlin.analysis.api.standalone.StandaloneAnalysisAPISession 15 | import org.jetbrains.kotlin.diagnostics.Severity 16 | import org.jetbrains.kotlin.psi.KtFile 17 | import org.jetbrains.kotlin.psi.psiUtil.getFileOrScriptDeclarations 18 | import java.net.URI 19 | import java.nio.file.Path 20 | import java.util.concurrent.CompletableFuture 21 | 22 | /** 23 | * The implementation of text document-related requests, e.g. code completion etc. 24 | */ 25 | class KotlinTextDocumentService: TextDocumentService { 26 | /** The Kotlin analysis API session. */ 27 | lateinit var session: StandaloneAnalysisAPISession 28 | 29 | /** Looks up a KtFile (the AST) for a URI via PsiManager. */ 30 | private fun URI.findKtFile(): KtFile? { 31 | val fs = StandardFileSystems.local() 32 | val psiManager = PsiManager.getInstance(session.project) 33 | val path = Path.of(this) 34 | val vFile = fs.findFileByPath(path.toString()) 35 | val psiFile = vFile?.let(psiManager::findFile) 36 | return psiFile as? KtFile 37 | } 38 | 39 | /** Fetch code completions. */ 40 | override fun completion(params: CompletionParams?): CompletableFuture, CompletionList>> { 41 | val items = params 42 | ?.let { URI(it.textDocument.uri).findKtFile() } 43 | ?.let { ktFile -> 44 | // TODO: Proper completions, also figure out how the analysis API might be useful here (analyze { ... }) 45 | ktFile.getFileOrScriptDeclarations() 46 | .map { CompletionItem(it.name) } 47 | } ?: listOf() 48 | 49 | val list = CompletionList(items) 50 | return CompletableFuture.completedFuture(Either.forRight(list)) 51 | } 52 | 53 | private fun Severity.toLspSeverity(): DiagnosticSeverity = when (this) { 54 | Severity.INFO -> DiagnosticSeverity.Information 55 | Severity.WARNING -> DiagnosticSeverity.Warning 56 | Severity.ERROR -> DiagnosticSeverity.Error 57 | } 58 | 59 | private fun PsiElement.toLspPosition(offset: Int): Position { 60 | val text = containingFile.text 61 | val lc = StringUtil.offsetToLineColumn(text, offset) 62 | return Position(lc.line, lc.column) 63 | } 64 | 65 | private fun PsiElement.toLspRange(textRange: TextRange): Range = Range( 66 | toLspPosition(textRange.startOffset), 67 | toLspPosition(textRange.endOffset) 68 | ) 69 | 70 | private fun KtDiagnosticWithPsi<*>.toLspDiagnostic(): Diagnostic = Diagnostic().also { 71 | it.range = psi.toLspRange(textRanges.first()) 72 | it.message = defaultMessage 73 | it.severity = severity.toLspSeverity() 74 | } 75 | 76 | /** Fetch diagnostics using the LSP 3.17 pull model. Uses the new analysis session. */ 77 | override fun diagnostic(params: DocumentDiagnosticParams?): CompletableFuture { 78 | val items = params 79 | ?.let { URI(it.textDocument.uri).findKtFile() } 80 | ?.let { ktFile -> 81 | analyze(ktFile) { 82 | ktFile.collectDiagnosticsForFile(KtDiagnosticCheckerFilter.EXTENDED_AND_COMMON_CHECKERS) 83 | .map { it.toLspDiagnostic() } 84 | } 85 | } 86 | ?: listOf() 87 | val fullReport = RelatedFullDocumentDiagnosticReport(items) 88 | val report = DocumentDiagnosticReport(fullReport) 89 | return CompletableFuture.completedFuture(report) 90 | } 91 | 92 | override fun didOpen(params: DidOpenTextDocumentParams?) { 93 | // TODO 94 | } 95 | 96 | override fun didChange(params: DidChangeTextDocumentParams?) { 97 | // TODO 98 | } 99 | 100 | override fun didClose(params: DidCloseTextDocumentParams?) { 101 | // TODO 102 | } 103 | 104 | override fun didSave(params: DidSaveTextDocumentParams?) { 105 | // TODO 106 | } 107 | } 108 | -------------------------------------------------------------------------------- /src/main/kotlin/dev/fwcd/kas/KotlinWorkspaceService.kt: -------------------------------------------------------------------------------- 1 | package dev.fwcd.kas 2 | 3 | import org.eclipse.lsp4j.DidChangeConfigurationParams 4 | import org.eclipse.lsp4j.DidChangeWatchedFilesParams 5 | import org.eclipse.lsp4j.services.WorkspaceService 6 | 7 | /** 8 | * The implementation of workspace-related requests. 9 | */ 10 | class KotlinWorkspaceService: WorkspaceService { 11 | override fun didChangeConfiguration(params: DidChangeConfigurationParams?) { 12 | // TODO 13 | } 14 | 15 | override fun didChangeWatchedFiles(params: DidChangeWatchedFilesParams?) { 16 | // TODO 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/main/kotlin/dev/fwcd/kas/Main.kt: -------------------------------------------------------------------------------- 1 | package dev.fwcd.kas 2 | 3 | import org.eclipse.lsp4j.jsonrpc.Launcher 4 | import org.eclipse.lsp4j.launch.LSPLauncher 5 | import org.eclipse.lsp4j.services.LanguageClient 6 | 7 | fun main() { 8 | // Bootstrap the language server 9 | val server = KotlinLanguageServer() 10 | val launcher: Launcher = LSPLauncher.createServerLauncher(server, System.`in`, System.out) 11 | 12 | // Inject the client proxy and start the language server 13 | server.connect(launcher.remoteProxy) 14 | launcher.startListening() 15 | } 16 | -------------------------------------------------------------------------------- /src/test/kotlin/dev/fwcd/kas/AppTest.kt: -------------------------------------------------------------------------------- 1 | package dev.fwcd.kas 2 | 3 | class AppTest { 4 | // TODO 5 | } 6 | --------------------------------------------------------------------------------