-
Notifications
You must be signed in to change notification settings - Fork 228
/
Copy pathKotlinTextDocumentService.kt
378 lines (310 loc) · 14.2 KB
/
KotlinTextDocumentService.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
package org.javacs.kt
import org.eclipse.lsp4j.*
import org.eclipse.lsp4j.jsonrpc.messages.Either
import org.eclipse.lsp4j.services.LanguageClient
import org.eclipse.lsp4j.services.TextDocumentService
import org.javacs.kt.codeaction.codeActions
import org.javacs.kt.completion.completions
import org.javacs.kt.definition.goToDefinition
import org.javacs.kt.diagnostic.convertDiagnostic
import org.javacs.kt.formatting.FormattingService
import org.javacs.kt.hover.hoverAt
import org.javacs.kt.position.offset
import org.javacs.kt.position.extractRange
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.rename.renameSymbol
import org.javacs.kt.highlight.documentHighlightsAt
import org.javacs.kt.inlayhints.provideHints
import org.javacs.kt.symbols.documentSymbols
import org.javacs.kt.util.AsyncExecutor
import org.javacs.kt.util.Debouncer
import org.javacs.kt.util.TemporaryDirectory
import org.javacs.kt.util.describeURI
import org.javacs.kt.util.describeURIs
import org.javacs.kt.util.filePath
import org.javacs.kt.util.noResult
import org.javacs.kt.util.parseURI
import org.jetbrains.kotlin.resolve.diagnostics.Diagnostics
import java.net.URI
import java.io.Closeable
import java.nio.file.Path
import java.time.Duration
import java.util.concurrent.CompletableFuture
class KotlinTextDocumentService(
private val sf: SourceFiles,
private val sp: SourcePath,
private val config: Configuration,
private val tempDirectory: TemporaryDirectory,
private val uriContentProvider: URIContentProvider,
private val cp: CompilerClassPath
) : TextDocumentService, Closeable {
private lateinit var client: LanguageClient
private val async = AsyncExecutor()
private val formattingService = FormattingService(config.formatting)
var debounceLint = Debouncer(Duration.ofMillis(config.diagnostics.debounceTime))
val lintTodo = mutableSetOf<URI>()
var lintCount = 0
var lintRecompilationCallback: () -> Unit
get() = sp.beforeCompileCallback
set(callback) { sp.beforeCompileCallback = callback }
private val TextDocumentItem.filePath: Path?
get() = parseURI(uri).filePath
private val TextDocumentIdentifier.filePath: Path?
get() = parseURI(uri).filePath
private val TextDocumentIdentifier.isKotlinScript: Boolean
get() = uri.endsWith(".kts")
private val TextDocumentIdentifier.content: String
get() = sp.content(parseURI(uri))
fun connect(client: LanguageClient) {
this.client = client
}
private enum class Recompile {
ALWAYS, AFTER_DOT, NEVER
}
private fun recover(position: TextDocumentPositionParams, recompile: Recompile): Pair<CompiledFile, Int>? {
return recover(position.textDocument.uri, position.position, recompile)
}
private fun recover(uriString: String, position: Position, recompile: Recompile): Pair<CompiledFile, Int>? {
val uri = parseURI(uriString)
if (!sf.isIncluded(uri)) {
LOG.warn("URI is excluded, therefore cannot be recovered: $uri")
return null
}
val content = sp.content(uri)
val offset = offset(content, position.line, position.character)
val shouldRecompile = when (recompile) {
Recompile.ALWAYS -> true
Recompile.AFTER_DOT -> offset > 0 && content[offset - 1] == '.'
Recompile.NEVER -> false
}
val compiled = if (shouldRecompile) sp.currentVersion(uri) else sp.latestCompiledVersion(uri)
return Pair(compiled, offset)
}
override fun codeAction(params: CodeActionParams): CompletableFuture<List<Either<Command, CodeAction>>> = async.compute {
val (file, _) = recover(params.textDocument.uri, params.range.start, Recompile.NEVER) ?: return@compute emptyList()
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) ?: return@compute emptyList()
provideHints(file, config.inlayHints)
}
override fun hover(position: HoverParams): CompletableFuture<Hover?> = async.compute {
reportTime {
LOG.info("Hovering at {}", describePosition(position))
val (file, cursor) = recover(position, Recompile.NEVER) ?: return@compute null
hoverAt(file, cursor) ?: noResult("No hover found at ${describePosition(position)}", null)
}
}
override fun documentHighlight(position: DocumentHighlightParams): CompletableFuture<List<DocumentHighlight>> = async.compute {
val (file, cursor) = recover(position.textDocument.uri, position.position, Recompile.NEVER) ?: return@compute emptyList()
documentHighlightsAt(file, cursor)
}
override fun onTypeFormatting(params: DocumentOnTypeFormattingParams): CompletableFuture<List<TextEdit>> = async.compute {
val code = params.textDocument.content
val position = params.position
val offset = offset(code, position.line, position.character)
// Get the line up to the cursor position
val lineStart = code.lastIndexOf('\n', offset - 1) + 1
val lineEnd = code.indexOf('\n', offset)
val line = if (lineEnd == -1) code.substring(lineStart) else code.substring(lineStart, lineEnd)
// Format the line
val formattedLine = formattingService.formatKotlinCode(line, params.options)
// Create a range for the line
val range = Range(
Position(position.line, 0),
Position(position.line, line.length)
)
// Return the edit
listOf(TextEdit(range, formattedLine))
}
override fun definition(position: DefinitionParams): CompletableFuture<Either<List<Location>, List<LocationLink>>> = async.compute {
reportTime {
LOG.info("Go-to-definition at {}", describePosition(position))
val (file, cursor) = recover(position, Recompile.NEVER) ?: return@compute Either.forLeft(emptyList())
goToDefinition(file, cursor, uriContentProvider.classContentProvider, tempDirectory, config.externalSources, cp)
?.let(::listOf)
?.let { Either.forLeft<List<Location>, List<LocationLink>>(it) }
?: noResult("Couldn't find definition at ${describePosition(position)}", Either.forLeft(emptyList()))
}
}
override fun rangeFormatting(params: DocumentRangeFormattingParams): CompletableFuture<List<TextEdit>> = async.compute {
val code = extractRange(params.textDocument.content, params.range)
listOf(TextEdit(
params.range,
formattingService.formatKotlinCode(code, params.options)
))
}
override fun codeLens(params: CodeLensParams): CompletableFuture<List<CodeLens>> {
TODO("not implemented")
}
override fun rename(params: RenameParams) = async.compute {
val (file, cursor) = recover(params, Recompile.NEVER) ?: return@compute null
renameSymbol(file, cursor, sp, params.newName)
}
override fun completion(position: CompletionParams): CompletableFuture<Either<List<CompletionItem>, CompletionList>> = async.compute {
reportTime {
LOG.info("Completing at {}", describePosition(position))
val (file, cursor) = recover(position, Recompile.NEVER) ?: return@compute Either.forRight(CompletionList()) // TODO: Investigate when to recompile
val completions = completions(file, cursor, sp.index, config.completion)
LOG.info("Found {} items", completions.items.size)
Either.forRight(completions)
}
}
override fun resolveCompletionItem(unresolved: CompletionItem): CompletableFuture<CompletionItem> {
TODO("not implemented")
}
@Suppress("DEPRECATION")
override fun documentSymbol(params: DocumentSymbolParams): CompletableFuture<List<Either<SymbolInformation, DocumentSymbol>>> = async.compute {
LOG.info("Find symbols in {}", describeURI(params.textDocument.uri))
reportTime {
val uri = parseURI(params.textDocument.uri)
val parsed = sp.parsedFile(uri)
documentSymbols(parsed)
}
}
override fun didOpen(params: DidOpenTextDocumentParams) {
val uri = parseURI(params.textDocument.uri)
sf.open(uri, params.textDocument.text, params.textDocument.version)
lintNow(uri)
}
override fun didSave(params: DidSaveTextDocumentParams) {
// Lint after saving to prevent inconsistent diagnostics
val uri = parseURI(params.textDocument.uri)
lintNow(uri)
debounceLint.schedule {
sp.save(uri)
}
}
override fun signatureHelp(position: SignatureHelpParams): CompletableFuture<SignatureHelp?> = async.compute {
reportTime {
LOG.info("Signature help at {}", describePosition(position))
val (file, cursor) = recover(position, Recompile.NEVER) ?: return@compute null
fetchSignatureHelpAt(file, cursor) ?: noResult("No function call around ${describePosition(position)}", null)
}
}
override fun didClose(params: DidCloseTextDocumentParams) {
val uri = parseURI(params.textDocument.uri)
sf.close(uri)
clearDiagnostics(uri)
}
override fun formatting(params: DocumentFormattingParams): CompletableFuture<List<TextEdit>> = async.compute {
val code = params.textDocument.content
LOG.info("Formatting {}", describeURI(params.textDocument.uri))
listOf(TextEdit(
Range(Position(0, 0), position(code, code.length)),
formattingService.formatKotlinCode(code, params.options)
))
}
override fun didChange(params: DidChangeTextDocumentParams) {
val uri = parseURI(params.textDocument.uri)
sf.edit(uri, params.textDocument.version, params.contentChanges)
lintLater(uri)
}
override fun references(position: ReferenceParams) = async.compute {
position.textDocument.filePath
?.let { file ->
val content = sp.content(parseURI(position.textDocument.uri))
val offset = offset(content, position.position.line, position.position.character)
findReferences(file, offset, sp)
}
}
override fun semanticTokensFull(params: SemanticTokensParams) = async.compute {
LOG.info("Full semantic tokens in {}", describeURI(params.textDocument.uri))
reportTime {
val uri = parseURI(params.textDocument.uri)
val file = sp.currentVersion(uri)
val tokens = encodedSemanticTokens(file)
LOG.info("Found {} tokens", tokens.size)
SemanticTokens(tokens)
}
}
override fun semanticTokensRange(params: SemanticTokensRangeParams) = async.compute {
LOG.info("Ranged semantic tokens in {}", describeURI(params.textDocument.uri))
reportTime {
val uri = parseURI(params.textDocument.uri)
val file = sp.currentVersion(uri)
val tokens = encodedSemanticTokens(file, params.range)
LOG.info("Found {} tokens", tokens.size)
SemanticTokens(tokens)
}
}
override fun resolveCodeLens(unresolved: CodeLens): CompletableFuture<CodeLens> {
TODO("not implemented")
}
private fun describePosition(position: TextDocumentPositionParams): String {
return "${describeURI(position.textDocument.uri)} ${position.position.line + 1}:${position.position.character + 1}"
}
public fun updateDebouncer() {
debounceLint = Debouncer(Duration.ofMillis(config.diagnostics.debounceTime))
}
fun lintAll() {
debounceLint.submitImmediately {
sp.compileAllFiles()
sp.saveAllFiles()
sp.refreshDependencyIndexes()
}
}
private fun clearLint(): List<URI> {
val result = lintTodo.toList()
lintTodo.clear()
return result
}
private fun lintLater(uri: URI) {
lintTodo.add(uri)
debounceLint.schedule(::doLint)
}
private fun lintNow(file: URI) {
lintTodo.add(file)
debounceLint.submitImmediately(::doLint)
}
private fun doLint(cancelCallback: () -> Boolean) {
LOG.info("Linting {}", describeURIs(lintTodo))
val files = clearLint()
val context = sp.compileFiles(files)
if (!cancelCallback.invoke()) {
reportDiagnostics(files, context.diagnostics)
}
lintCount++
}
private fun reportDiagnostics(compiled: Collection<URI>, kotlinDiagnostics: Diagnostics) {
val langServerDiagnostics = kotlinDiagnostics
.flatMap(::convertDiagnostic)
.filter { config.diagnostics.enabled && it.second.severity <= config.diagnostics.level }
val byFile = langServerDiagnostics.groupBy({ it.first }, { it.second })
for ((uri, diagnostics) in byFile) {
if (sf.isOpen(uri)) {
client.publishDiagnostics(PublishDiagnosticsParams(uri.toString(), diagnostics))
LOG.info("Reported {} diagnostics in {}", diagnostics.size, describeURI(uri))
}
else LOG.info("Ignore {} diagnostics in {} because it's not open", diagnostics.size, describeURI(uri))
}
val noErrors = compiled - byFile.keys
for (file in noErrors) {
clearDiagnostics(file)
LOG.info("No diagnostics in {}", file)
}
lintCount++
}
private fun clearDiagnostics(uri: URI) {
client.publishDiagnostics(PublishDiagnosticsParams(uri.toString(), listOf()))
}
private fun shutdownExecutors(awaitTermination: Boolean) {
async.shutdown(awaitTermination)
debounceLint.shutdown(awaitTermination)
}
override fun close() {
shutdownExecutors(awaitTermination = true)
}
}
private inline fun<T> reportTime(block: () -> T): T {
val started = System.currentTimeMillis()
try {
return block()
} finally {
val finished = System.currentTimeMillis()
LOG.info("Finished in {} ms", finished - started)
}
}