/
MetalsLanguageServer.scala
1799 lines (1717 loc) Β· 55.7 KB
/
MetalsLanguageServer.scala
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
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package scala.meta.internal.metals
import java.net.URI
import java.nio.charset.Charset
import java.nio.charset.StandardCharsets
import java.nio.file._
import java.util
import java.util.concurrent.CompletableFuture
import java.util.concurrent.Executors
import java.util.concurrent.ScheduledExecutorService
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.atomic.AtomicReference
import ch.epfl.scala.{bsp4j => b}
import com.google.gson.JsonElement
import io.methvin.watcher.DirectoryChangeEvent
import io.methvin.watcher.DirectoryChangeEvent.EventType
import io.undertow.server.HttpServerExchange
import org.eclipse.lsp4j._
import org.eclipse.{lsp4j => l}
import org.eclipse.lsp4j.jsonrpc.messages.{Either => JEither}
import org.eclipse.lsp4j.jsonrpc.services.JsonNotification
import org.eclipse.lsp4j.jsonrpc.services.JsonRequest
import scala.collection.mutable.ArrayBuffer
import scala.collection.mutable
import scala.concurrent.Await
import scala.concurrent.ExecutionContextExecutorService
import scala.concurrent.Future
import scala.concurrent.Promise
import scala.concurrent.TimeoutException
import scala.concurrent.duration.Duration
import scala.meta.internal.builds.BuildTool
import scala.meta.internal.builds.BuildTools
import scala.meta.internal.implementation.ImplementationProvider
import scala.meta.internal.io.FileIO
import scala.meta.internal.metals.MetalsEnrichments._
import scala.meta.internal.metals.debug.DebugServer
import scala.meta.internal.tvp._
import scala.meta.internal.mtags._
import scala.meta.internal.semanticdb.Scala._
import scala.meta.io.AbsolutePath
import scala.meta.parsers.ParseException
import scala.meta.pc.CancelToken
import scala.meta.tokenizers.TokenizeException
import scala.util.control.NonFatal
import scala.util.Success
import com.google.gson.JsonPrimitive
import scala.meta.internal.worksheets.WorksheetProvider
import scala.meta.internal.worksheets.WorksheetProvider
import scala.meta.internal.decorations.PublishDecorationsParams
import scala.meta.internal.rename.RenameProvider
class MetalsLanguageServer(
ec: ExecutionContextExecutorService,
buffers: Buffers = Buffers(),
redirectSystemOut: Boolean = true,
charset: Charset = StandardCharsets.UTF_8,
time: Time = Time.system,
config: MetalsServerConfig = MetalsServerConfig.default,
progressTicks: ProgressTicks = ProgressTicks.braille,
bspGlobalDirectories: List[AbsolutePath] =
BspServers.globalInstallDirectories,
sh: ScheduledExecutorService = Executors.newSingleThreadScheduledExecutor()
) extends Cancelable {
ThreadPools.discardRejectedRunnables("MetalsLanguageServer.sh", sh)
ThreadPools.discardRejectedRunnables("MetalsLanguageServer.ec", ec)
private val cancelables = new MutableCancelable()
val isCancelled = new AtomicBoolean(false)
override def cancel(): Unit = {
if (isCancelled.compareAndSet(false, true)) {
val buildShutdown = buildServer match {
case Some(build) => build.shutdown()
case None => Future.successful(())
}
try cancelables.cancel()
catch {
case NonFatal(_) =>
}
try buildShutdown.asJava.get(100, TimeUnit.MILLISECONDS)
catch {
case _: TimeoutException =>
}
}
}
def cancelAll(): Unit = {
cancel()
Cancelable.cancelAll(
List(
Cancelable(() => ec.shutdown()),
Cancelable(() => sh.shutdown())
)
)
}
private implicit val executionContext: ExecutionContextExecutorService = ec
private val fingerprints = new MutableMd5Fingerprints
private val mtags = new Mtags
var workspace: AbsolutePath = _
var focusedDocument: Option[AbsolutePath] = None
private val focusedDocumentBuildTarget =
new AtomicReference[b.BuildTargetIdentifier]()
private val definitionIndex = newSymbolIndex()
private val symbolDocs = new Docstrings(definitionIndex)
var buildServer: Option[BuildServerConnection] =
Option.empty[BuildServerConnection]
private val buildTargetClasses = new BuildTargetClasses(() => buildServer)
private val openTextDocument = new AtomicReference[AbsolutePath]()
private val savedFiles = new ActiveFiles(time)
private val openedFiles = new ActiveFiles(time)
private val messages = new Messages(config.icons)
private val languageClient = new DelegatingLanguageClient(NoopLanguageClient)
var userConfig: UserConfiguration = UserConfiguration()
val buildTargets: BuildTargets = new BuildTargets()
val compilations: Compilations = new Compilations(
buildTargets,
buildTargetClasses,
() => workspace,
() => buildServer,
languageClient,
buildTarget => focusedDocumentBuildTarget.get() == buildTarget,
worksheets => onWorksheetChanged(worksheets)
)
private val fileWatcher = register(
new FileWatcher(
buildTargets,
params => didChangeWatchedFiles(params)
)
)
private val indexingPromise = Promise[Unit]()
val parseTrees = new BatchedFunction[AbsolutePath, Unit](
paths => CancelableFuture(paths.distinct.foreach(trees.didChange))
)
private val onBuildChanged =
BatchedFunction.fromFuture[AbsolutePath, BuildChange](
onBuildChangedUnbatched
)
val pauseables: Pauseable = Pauseable.fromPausables(
onBuildChanged ::
parseTrees ::
compilations.pauseables
)
// These can't be instantiated until we know the workspace root directory.
private var bloopInstall: BloopInstall = _
private var diagnostics: Diagnostics = _
private var warnings: Warnings = _
private var trees: Trees = _
private var documentSymbolProvider: DocumentSymbolProvider = _
private var fileSystemSemanticdbs: FileSystemSemanticdbs = _
private var interactiveSemanticdbs: InteractiveSemanticdbs = _
private var buildTools: BuildTools = _
private var semanticdbs: Semanticdbs = _
private var buildClient: ForwardingMetalsBuildClient = _
private var bloopServers: BloopServers = _
private var bspServers: BspServers = _
private var codeLensProvider: CodeLensProvider = _
private var definitionProvider: DefinitionProvider = _
private var semanticDBIndexer: SemanticdbIndexer = _
private var implementationProvider: ImplementationProvider = _
private var renameProvider: RenameProvider = _
private var documentHighlightProvider: DocumentHighlightProvider = _
private var formattingProvider: FormattingProvider = _
private var multilineStringFormattingProvider
: MultilineStringFormattingProvider = _
private var initializeParams: Option[InitializeParams] = None
private var referencesProvider: ReferenceProvider = _
private var workspaceSymbols: WorkspaceSymbolProvider = _
private var foldingRangeProvider: FoldingRangeProvider = _
private val packageProvider: PackageProvider =
new PackageProvider(buildTargets)
private var compilers: Compilers = _
var tables: Tables = _
var statusBar: StatusBar = _
private var embedded: Embedded = _
private var doctor: Doctor = _
var httpServer: Option[MetalsHttpServer] = None
var treeView: TreeViewProvider = NoopTreeViewProvider
var worksheetProvider: Option[WorksheetProvider] = None
def connectToLanguageClient(client: MetalsLanguageClient): Unit = {
languageClient.underlying = new ConfiguredLanguageClient(client, config)(ec)
statusBar = new StatusBar(
() => languageClient,
time,
progressTicks,
config.icons,
config.statusBar
)
embedded = register(
new Embedded(
config.icons,
statusBar,
() => userConfig
)
)
LanguageClientLogger.languageClient = Some(languageClient)
cancelables.add(() => languageClient.shutdown())
}
def register[T <: Cancelable](cancelable: T): T = {
cancelables.add(cancelable)
cancelable
}
private def updateWorkspaceDirectory(params: InitializeParams): Unit = {
workspace = AbsolutePath(Paths.get(URI.create(params.getRootUri))).dealias
MetalsLogger.setupLspLogger(workspace, redirectSystemOut)
val clientExperimentalCapabilities =
ClientExperimentalCapabilities.from(params.getCapabilities)
languageClient.configure(clientExperimentalCapabilities)
buildTargets.setWorkspaceDirectory(workspace)
tables = register(new Tables(workspace, time, config))
buildTargets.setTables(tables)
buildTools = new BuildTools(workspace, bspGlobalDirectories)
fileSystemSemanticdbs = new FileSystemSemanticdbs(
buildTargets,
charset,
workspace,
fingerprints
)
interactiveSemanticdbs = register(
new InteractiveSemanticdbs(
workspace,
buildTargets,
charset,
languageClient,
tables,
messages,
statusBar,
() => compilers,
config
)
)
warnings = new Warnings(
workspace,
buildTargets,
statusBar,
config.icons,
buildTools,
compilations.isCurrentlyCompiling
)
diagnostics = new Diagnostics(
buildTargets,
buffers,
languageClient,
config.statistics,
() => userConfig
)
buildClient = new ForwardingMetalsBuildClient(
languageClient,
diagnostics,
buildTargets,
buildTargetClasses,
config,
statusBar,
time,
report => compilers.didCompile(report),
() => treeView,
() => worksheetProvider
)
trees = new Trees(buffers, diagnostics)
documentSymbolProvider = new DocumentSymbolProvider(trees)
bloopInstall = register(
new BloopInstall(
workspace,
languageClient,
sh,
buildTools,
time,
tables,
messages,
config,
embedded,
statusBar,
() => userConfig
)
)
bloopServers = new BloopServers(
sh,
workspace,
buildClient
)
bspServers = new BspServers(
workspace,
charset,
languageClient,
buildClient,
tables,
bspGlobalDirectories
)
semanticdbs = AggregateSemanticdbs(
List(
fileSystemSemanticdbs,
interactiveSemanticdbs
)
)
codeLensProvider = CodeLensProvider(
buildTargetClasses,
buffers,
buildTargets,
compilations,
semanticdbs,
clientExperimentalCapabilities
)
definitionProvider = new DefinitionProvider(
workspace,
mtags,
buffers,
definitionIndex,
semanticdbs,
config.icons,
statusBar,
warnings,
() => compilers
)
formattingProvider = new FormattingProvider(
workspace,
buffers,
embedded,
config,
() => userConfig,
languageClient,
statusBar,
config.icons,
Option(params.getWorkspaceFolders) match {
case Some(folders) =>
folders.asScala.map(_.getUri.toAbsolutePath).toList
case _ =>
Nil
}
)
multilineStringFormattingProvider = new MultilineStringFormattingProvider(
semanticdbs,
buffers
)
referencesProvider = new ReferenceProvider(
workspace,
semanticdbs,
buffers,
definitionProvider
)
implementationProvider = new ImplementationProvider(
semanticdbs,
workspace,
definitionIndex,
buildTargets,
buffers,
definitionProvider
)
renameProvider = new RenameProvider(
referencesProvider,
implementationProvider,
definitionProvider,
semanticdbs,
definitionIndex,
workspace,
languageClient,
buffers,
compilations
)
semanticDBIndexer =
new SemanticdbIndexer(referencesProvider, implementationProvider)
documentHighlightProvider = new DocumentHighlightProvider(
definitionProvider,
semanticdbs
)
workspaceSymbols = new WorkspaceSymbolProvider(
workspace,
config.statistics,
buildTargets,
definitionIndex,
pkg => {
val mightContain =
referencesProvider.referencedPackages.mightContain(pkg)
if (mightContain) 0 else 1
},
interactiveSemanticdbs.toFileOnDisk
)
foldingRangeProvider = FoldingRangeProvider(trees, buffers, params)
compilers = register(
new Compilers(
workspace,
config,
() => userConfig,
buildTargets,
buffers,
new MetalsSymbolSearch(
symbolDocs,
workspaceSymbols,
definitionProvider
),
embedded,
statusBar,
sh,
Option(params)
)
)
doctor = new Doctor(
workspace,
buildTargets,
config,
languageClient,
() => httpServer,
tables,
messages
)
if (clientExperimentalCapabilities.decorationProvider) {
worksheetProvider = Some(
register(
new WorksheetProvider(
workspace,
buffers,
buildTargets,
languageClient,
() => userConfig,
statusBar,
diagnostics
)
)
)
}
if (clientExperimentalCapabilities.treeViewProvider) {
treeView = new MetalsTreeViewProvider(
() => workspace,
languageClient,
buildTargets,
() => buildClient.ongoingCompilations(),
definitionIndex,
config.statistics,
id => compilations.compileTargets(List(id)),
sh
)
}
}
def setupJna(): Unit = {
// This is required to avoid the following error:
// java.lang.NoClassDefFoundError: Could not initialize class com.sun.jna.platform.win32.Kernel32
// at sbt.internal.io.WinMilli$.getHandle(Milli.scala:277)
// There is an incompatible JNA native library installed on this system
// Expected: 5.2.2
// Found: 3.2.1
System.setProperty("jna.nosys", "true")
}
@JsonRequest("initialize")
def initialize(
params: InitializeParams
): CompletableFuture[InitializeResult] = {
timed("initialize")(Future {
setupJna()
initializeParams = Option(params)
updateWorkspaceDirectory(params)
val capabilities = new ServerCapabilities()
capabilities.setExecuteCommandProvider(
new ExecuteCommandOptions(
ServerCommands.all.map(_.id).asJava
)
)
capabilities.setFoldingRangeProvider(true)
capabilities.setCodeLensProvider(new CodeLensOptions(false))
capabilities.setDefinitionProvider(true)
capabilities.setImplementationProvider(true)
capabilities.setHoverProvider(true)
capabilities.setReferencesProvider(true)
val renameOptions = new RenameOptions()
renameOptions.setPrepareProvider(true)
capabilities.setRenameProvider(renameOptions)
capabilities.setDocumentHighlightProvider(true)
capabilities.setDocumentOnTypeFormattingProvider(
new DocumentOnTypeFormattingOptions("\n")
)
capabilities.setDocumentRangeFormattingProvider(true)
capabilities.setSignatureHelpProvider(
new SignatureHelpOptions(List("(", "[").asJava)
)
capabilities.setCompletionProvider(
new CompletionOptions(
config.compilers.isCompletionItemResolve,
List(".").asJava
)
)
capabilities.setWorkspaceSymbolProvider(true)
capabilities.setDocumentSymbolProvider(true)
capabilities.setDocumentFormattingProvider(true)
capabilities.setTextDocumentSync(TextDocumentSyncKind.Full)
if (config.isNoInitialized) {
sh.schedule(
() => initialized(new InitializedParams),
1,
TimeUnit.SECONDS
)
}
capabilities.setExperimental(MetalsExperimental())
new InitializeResult(capabilities)
}).asJava
}
private def registerNiceToHaveFilePatterns(): Unit = {
for {
params <- initializeParams
capabilities <- Option(params.getCapabilities)
workspace <- Option(capabilities.getWorkspace)
didChangeWatchedFiles <- Option(workspace.getDidChangeWatchedFiles)
if didChangeWatchedFiles.getDynamicRegistration
} yield {
languageClient.registerCapability(
new RegistrationParams(
List(
new Registration(
"1",
"workspace/didChangeWatchedFiles",
config.globSyntax.registrationOptions(this.workspace)
)
).asJava
)
)
}
}
private def startHttpServer(): Unit = {
if (config.isHttpEnabled) {
val host = "localhost"
val port = 5031
var url = s"http://$host:$port"
var render: () => String = () => ""
var completeCommand: HttpServerExchange => Unit = e => ()
val server = register(
MetalsHttpServer(
host,
port,
this,
() => render(),
e => completeCommand(e),
() => doctor.problemsHtmlPage(url)
)
)
httpServer = Some(server)
val newClient = new MetalsHttpClient(
workspace,
() => url,
languageClient.underlying,
() => server.reload(),
charset,
config.icons,
time,
sh,
config
)
render = () => newClient.renderHtml
completeCommand = e => newClient.completeCommand(e)
languageClient.underlying = newClient
server.start()
url = server.address
}
}
val isInitialized = new AtomicBoolean(false)
@JsonNotification("initialized")
def initialized(params: InitializedParams): CompletableFuture[Unit] = {
// Avoid duplicate `initialized` notifications. During the transition
// for https://github.com/natebosch/vim-lsc/issues/113 to get fixed,
// we may have users on a fixed vim-lsc version but with -Dmetals.no-initialized=true
// enabled.
if (isInitialized.compareAndSet(false, true)) {
statusBar.start(sh, 0, 1, TimeUnit.SECONDS)
tables.connect()
registerNiceToHaveFilePatterns()
val result = Future
.sequence(
List[Future[Unit]](
quickConnectToBuildServer().ignoreValue,
slowConnectToBuildServer(forceImport = false).ignoreValue,
Future(workspaceSymbols.indexClasspath()),
Future(startHttpServer()),
Future(formattingProvider.load())
)
)
.ignoreValue
result
} else {
scribe.warn("Ignoring duplicate 'initialized' notification.")
Future.successful(())
}
}.recover {
case NonFatal(e) =>
scribe.error("Unexpected error initializing server", e)
}.asJava
lazy val shutdownPromise = new AtomicReference[Promise[Unit]](null)
@JsonRequest("shutdown")
def shutdown(): CompletableFuture[Unit] = {
val promise = Promise[Unit]()
// Ensure we only run `shutdown` at most once and that `exit` waits for the
// `shutdown` promise to complete.
if (shutdownPromise.compareAndSet(null, promise)) {
scribe.info("shutting down Metals")
try {
cancel()
} catch {
case NonFatal(e) =>
scribe.error("cancellation error", e)
} finally {
promise.success(())
}
if (config.isExitOnShutdown) {
System.exit(0)
}
promise.future.asJava
} else {
shutdownPromise.get().future.asJava
}
}
@JsonNotification("exit")
def exit(): Unit = {
// `shutdown` is idempotent, we can trigger it as often as we like.
shutdown()
// Ensure that `shutdown` has completed before killing the process.
// Some clients may send `exit` immediately after `shutdown` causing
// the build server to get killed before it can clean up resources.
try {
Await.result(
shutdownPromise.get().future,
Duration(3, TimeUnit.SECONDS)
)
} catch {
case NonFatal(e) =>
scribe.error("shutdown error", e)
} finally {
System.exit(0)
}
}
@JsonNotification("textDocument/didOpen")
def didOpen(params: DidOpenTextDocumentParams): CompletableFuture[Unit] = {
val path = params.getTextDocument.getUri.toAbsolutePath
focusedDocument = Some(path)
openedFiles.add(path)
openTextDocument.set(path)
// Update md5 fingerprint from file contents on disk
fingerprints.add(path, FileIO.slurp(path, charset))
// Update in-memory buffer contents from LSP client
buffers.put(path, params.getTextDocument.getText)
trees.didChange(path)
packageProvider
.workspaceEdit(path)
.map(new ApplyWorkspaceEditParams(_))
.foreach(languageClient.applyEdit)
if (path.isDependencySource(workspace)) {
CancelTokens { _ =>
// trigger compilation in preparation for definition requests
interactiveSemanticdbs.textDocument(path)
// publish diagnostics
interactiveSemanticdbs.didFocus(path)
()
}
} else {
compilers.load(List(path))
compilations.compileFiles(List(path)).ignoreValue.asJava
}
}
@JsonNotification("metals/didFocusTextDocument")
def didFocus(uri: String): CompletableFuture[DidFocusResult.Value] = {
val path = uri.toAbsolutePath
focusedDocument = Some(path)
buildTargets
.inverseSources(path)
.foreach(focusedDocumentBuildTarget.set)
// unpublish diagnostic for dependencies
interactiveSemanticdbs.didFocus(path)
Future(treeView.didFocusTextDocument(path))
// Don't trigger compilation on didFocus events under cascade compilation
// because save events already trigger compile in inverse dependencies.
if (path.isDependencySource(workspace)) {
CompletableFuture.completedFuture(DidFocusResult.NoBuildTarget)
} else if (openedFiles.isRecentlyActive(path)) {
CompletableFuture.completedFuture(DidFocusResult.RecentlyActive)
} else {
buildTargets.inverseSources(path) match {
case Some(target) =>
val isAffectedByCurrentCompilation =
path.isWorksheet ||
buildTargets.isInverseDependency(
target,
compilations.currentlyCompiling.toList
)
def isAffectedByLastCompilation: Boolean =
!compilations.wasPreviouslyCompiled(target) &&
buildTargets.isInverseDependency(
target,
compilations.previouslyCompiled.toList
)
val needsCompile = isAffectedByCurrentCompilation || isAffectedByLastCompilation
if (needsCompile) {
compilations
.compileFiles(List(path))
.map(_ => DidFocusResult.Compiled)
.asJava
} else {
CompletableFuture.completedFuture(DidFocusResult.AlreadyCompiled)
}
case None =>
CompletableFuture.completedFuture(DidFocusResult.NoBuildTarget)
}
}
}
@JsonNotification("metals/windowStateDidChange")
def windowStateDidChange(params: WindowStateDidChangeParams): Unit = {
if (params.focused) {
pauseables.unpause()
} else {
pauseables.pause()
}
}
@JsonNotification("textDocument/didChange")
def didChange(
params: DidChangeTextDocumentParams
): CompletableFuture[Unit] =
params.getContentChanges.asScala.headOption match {
case None => CompletableFuture.completedFuture(())
case Some(change) =>
val path = params.getTextDocument.getUri.toAbsolutePath
buffers.put(path, change.getText)
diagnostics.didChange(path)
parseTrees(path).asJava
}
@JsonNotification("textDocument/didClose")
def didClose(params: DidCloseTextDocumentParams): Unit = {
val path = params.getTextDocument.getUri.toAbsolutePath
buffers.remove(path)
trees.didClose(path)
}
@JsonNotification("textDocument/didSave")
def didSave(params: DidSaveTextDocumentParams): CompletableFuture[Unit] = {
val path = params.getTextDocument.getUri.toAbsolutePath
savedFiles.add(path)
// read file from disk, we only remove files from buffers on didClose.
buffers.put(path, path.toInput.text)
Future
.sequence(List(parseTrees(path), onChange(List(path))))
.ignoreValue
.asJava
}
@JsonNotification("workspace/didChangeConfiguration")
def didChangeConfiguration(
params: DidChangeConfigurationParams
): CompletableFuture[Unit] =
Future {
val json = params.getSettings.asInstanceOf[JsonElement].getAsJsonObject
UserConfiguration.fromJson(json) match {
case Left(errors) =>
errors.foreach { error =>
scribe.error(s"config error: $error")
}
case Right(value) =>
val old = userConfig
userConfig = value
if (userConfig.symbolPrefixes != old.symbolPrefixes) {
compilers.restartAll()
}
}
}.asJava
@JsonNotification("workspace/didChangeWatchedFiles")
def didChangeWatchedFiles(
params: DidChangeWatchedFilesParams
): CompletableFuture[Unit] = {
val paths = params.getChanges.asScala.iterator
.map(_.getUri.toAbsolutePath)
.filterNot(savedFiles.isRecentlyActive) // de-duplicate didSave events.
.toSeq
onChange(paths).asJava
}
def didChangeWatchedFiles(
event: DirectoryChangeEvent
): CompletableFuture[Unit] = {
val path = AbsolutePath(event.path())
val isScalaOrJava = path.isScalaOrJava
if (isScalaOrJava && event.eventType() == EventType.DELETE) {
diagnostics.didDelete(path)
CompletableFuture.completedFuture(())
} else if (isScalaOrJava && !savedFiles.isRecentlyActive(path)) {
event.eventType() match {
case EventType.CREATE =>
buildTargets.onCreate(path)
case _ =>
}
onChange(List(path)).asJava
} else if (path.isSemanticdb) {
CompletableFuture.completedFuture {
event.eventType() match {
case EventType.DELETE =>
semanticDBIndexer.onDelete(event.path())
case EventType.CREATE | EventType.MODIFY =>
semanticDBIndexer.onChange(event.path())
case EventType.OVERFLOW =>
semanticDBIndexer.onOverflow(event.path())
}
}
} else {
CompletableFuture.completedFuture(())
}
}
private def onChange(paths: Seq[AbsolutePath]): Future[Unit] = {
paths.foreach { path =>
fingerprints.add(path, FileIO.slurp(path, charset))
}
Future
.sequence(
List(
Future(reindexWorkspaceSources(paths)),
compilations.compileFiles(paths).ignoreValue,
onBuildChanged(paths).ignoreValue
)
)
.ignoreValue
}
@JsonRequest("textDocument/definition")
def definition(
position: TextDocumentPositionParams
): CompletableFuture[util.List[Location]] =
CancelTokens.future { token =>
definitionOrReferences(position, token).map(_.locations)
}
@JsonRequest("textDocument/typeDefinition")
def typeDefinition(
position: TextDocumentPositionParams
): CompletableFuture[util.List[Location]] =
CancelTokens { _ =>
scribe.warn("textDocument/typeDefinition is not supported.")
null
}
@JsonRequest("textDocument/implementation")
def implementation(
position: TextDocumentPositionParams
): CompletableFuture[util.List[Location]] =
CancelTokens { _ =>
implementationProvider.implementations(position).asJava
}
@JsonRequest("textDocument/hover")
def hover(params: TextDocumentPositionParams): CompletableFuture[Hover] =
CancelTokens.future { token =>
compilers
.hover(params, token, interactiveSemanticdbs)
.map(_.orNull)
}
@JsonRequest("textDocument/documentHighlight")
def documentHighlights(
params: TextDocumentPositionParams
): CompletableFuture[util.List[DocumentHighlight]] =
CancelTokens { _ =>
documentHighlightProvider.documentHighlight(params)
}
@JsonRequest("textDocument/documentSymbol")
def documentSymbol(
params: DocumentSymbolParams
): CompletableFuture[
JEither[util.List[DocumentSymbol], util.List[SymbolInformation]]
] =
CancelTokens { _ =>
val result = documentSymbolResult(params)
if (initializeParams.supportsHierarchicalDocumentSymbols) {
JEither.forLeft(result)
} else {
val infos = result.asScala
.toSymbolInformation(params.getTextDocument.getUri)
.asJava
JEither.forRight(infos)
}
}
@JsonRequest("textDocument/formatting")
def formatting(
params: DocumentFormattingParams
): CompletableFuture[util.List[TextEdit]] =
CancelTokens.future { token =>
formattingProvider.format(
params.getTextDocument.getUri.toAbsolutePath,
token
)
}
@JsonRequest("textDocument/onTypeFormatting")
def onTypeFormatting(
params: DocumentOnTypeFormattingParams
): CompletableFuture[util.List[TextEdit]] =
CancelTokens.future { _ =>
multilineStringFormattingProvider
.format(params)
.map(_.asJava)
}
@JsonRequest("textDocument/rangeFormatting")
def rangeFormatting(
params: DocumentRangeFormattingParams
): CompletableFuture[util.List[TextEdit]] =
CancelTokens.future { _ =>
multilineStringFormattingProvider
.format(params)
.map(_.asJava)
}
@JsonRequest("textDocument/prepareRename")
def prepareRename(
params: TextDocumentPositionParams
): CompletableFuture[l.Range] =
CancelTokens { _ =>
renameProvider.prepareRename(params).getOrElse(null)
}
@JsonRequest("textDocument/rename")
def rename(
params: RenameParams
): CompletableFuture[WorkspaceEdit] =
CancelTokens { _ =>
renameProvider.rename(params)
}
@JsonRequest("textDocument/references")
def references(
params: ReferenceParams
): CompletableFuture[util.List[Location]] =
CancelTokens { _ =>
referencesResult(params).locations.asJava
}
// Triggers a cascade compilation and tries to find new references to a given symbol.
// It's not possible to stream reference results so if we find new symbols we notify the
// user to run references again to see updated results.
private def compileAndLookForNewReferences(
params: ReferenceParams,
result: ReferencesResult
): Unit = {
val path = params.getTextDocument.getUri.toAbsolutePath
val old = path.toInputFromBuffers(buffers)
compilations.cascadeCompileFiles(Seq(path)).foreach { _ =>
val newBuffer = path.toInputFromBuffers(buffers)
val newParams: Option[ReferenceParams] =
if (newBuffer.text == old.text) Some(params)
else {
val edit = TokenEditDistance(old, newBuffer)
edit
.toRevised(
params.getPosition.getLine,
params.getPosition.getCharacter
)
.foldResult(
pos => {
params.getPosition.setLine(pos.startLine)
params.getPosition.setCharacter(pos.startColumn)
Some(params)
},
() => Some(params),
() => None
)
}
newParams match {
case None =>
case Some(p) =>
val newResult = referencesProvider.references(p)
val diff = newResult.locations.length - result.locations.length
val isSameSymbol = newResult.symbol == result.symbol
if (isSameSymbol && diff > 0) {
import scala.meta.internal.semanticdb.Scala._
val name = newResult.symbol.desc.name.value
val message =
s"Found new symbol references for '$name', try running again."
scribe.info(message)
statusBar.addMessage(config.icons.info + message)
}
}
}
}
def referencesResult(params: ReferenceParams): ReferencesResult = {
val timer = new Timer(time)
val result = referencesProvider.references(params)
if (config.statistics.isReferences) {
if (result.symbol.isEmpty) {
scribe.info(s"time: found 0 references in $timer")