/
Compilers.scala
1418 lines (1310 loc) Β· 44.5 KB
/
Compilers.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.nio.file.Path
import java.nio.file.Paths
import java.util.Collections
import java.util.concurrent.ScheduledExecutorService
import java.{util => ju}
import scala.annotation.nowarn
import scala.annotation.tailrec
import scala.collection.concurrent.TrieMap
import scala.concurrent.ExecutionContextExecutorService
import scala.concurrent.Future
import scala.util.Try
import scala.util.control.NonFatal
import scala.meta.inputs.Input
import scala.meta.inputs.Position
import scala.meta.internal.decorations.DecorationOptions
import scala.meta.internal.metals.CompilerOffsetParamsUtils
import scala.meta.internal.metals.CompilerRangeParamsUtils
import scala.meta.internal.metals.Compilers.PresentationCompilerKey
import scala.meta.internal.metals.MetalsEnrichments._
import scala.meta.internal.parsing.Trees
import scala.meta.internal.pc.EmptySymbolSearch
import scala.meta.internal.pc.JavaPresentationCompiler
import scala.meta.internal.pc.LogMessages
import scala.meta.internal.pc.ScalaPresentationCompiler
import scala.meta.internal.worksheets.WorksheetPcData
import scala.meta.internal.worksheets.WorksheetProvider
import scala.meta.io.AbsolutePath
import scala.meta.pc.AutoImportsResult
import scala.meta.pc.CancelToken
import scala.meta.pc.HoverSignature
import scala.meta.pc.OffsetParams
import scala.meta.pc.PresentationCompiler
import scala.meta.pc.SymbolSearch
import scala.meta.pc.SyntheticDecoration
import ch.epfl.scala.bsp4j.BuildTargetIdentifier
import ch.epfl.scala.bsp4j.CompileReport
import org.eclipse.lsp4j.CompletionItem
import org.eclipse.lsp4j.CompletionItemKind
import org.eclipse.lsp4j.CompletionList
import org.eclipse.lsp4j.CompletionParams
import org.eclipse.lsp4j.Diagnostic
import org.eclipse.lsp4j.DocumentHighlight
import org.eclipse.lsp4j.InitializeParams
import org.eclipse.lsp4j.RenameParams
import org.eclipse.lsp4j.SelectionRange
import org.eclipse.lsp4j.SelectionRangeParams
import org.eclipse.lsp4j.SemanticTokens
import org.eclipse.lsp4j.SemanticTokensParams
import org.eclipse.lsp4j.SignatureHelp
import org.eclipse.lsp4j.TextDocumentIdentifier
import org.eclipse.lsp4j.TextDocumentPositionParams
import org.eclipse.lsp4j.TextEdit
import org.eclipse.lsp4j.{Position => LspPosition}
import org.eclipse.lsp4j.{Range => LspRange}
import org.eclipse.lsp4j.{debug => d}
/**
* Manages lifecycle for presentation compilers in all build targets.
*
* We need a custom presentation compiler for each build target since
* build targets can have different classpaths and compiler settings.
*/
class Compilers(
workspace: AbsolutePath,
config: ClientConfiguration,
userConfig: () => UserConfiguration,
buildTargets: BuildTargets,
buffers: Buffers,
search: SymbolSearch,
embedded: Embedded,
statusBar: StatusBar,
sh: ScheduledExecutorService,
initializeParams: InitializeParams,
excludedPackages: () => ExcludedPackagesHandler,
scalaVersionSelector: ScalaVersionSelector,
trees: Trees,
mtagsResolver: MtagsResolver,
sourceMapper: SourceMapper,
worksheetProvider: WorksheetProvider,
)(implicit ec: ExecutionContextExecutorService, rc: ReportContext)
extends Cancelable {
val plugins = new CompilerPlugins()
val outlineFilesProvider = new OutlineFilesProvider(buildTargets, buffers)
// Not a TrieMap because we want to avoid loading duplicate compilers for the same build target.
// Not a `j.u.c.ConcurrentHashMap` because it can deadlock in `computeIfAbsent` when the absent
// function is expensive, which is the case here.
val jcache: ju.Map[PresentationCompilerKey, PresentationCompiler] =
Collections.synchronizedMap(
new java.util.HashMap[PresentationCompilerKey, PresentationCompiler]
)
private val jworksheetsCache: ju.Map[AbsolutePath, PresentationCompiler] =
Collections.synchronizedMap(
new java.util.HashMap[AbsolutePath, PresentationCompiler]
)
private val worksheetsDigests = new TrieMap[AbsolutePath, String]()
private val cache = jcache.asScala
private def buildTargetPCFromCache(
id: BuildTargetIdentifier
): Option[PresentationCompiler] =
cache.get(PresentationCompilerKey.BuildTarget(id)).filter(_ != null)
private val worksheetsCache = jworksheetsCache.asScala
private def createStandaloneCompiler(
scalaVersion: String,
classpath: Seq[Path],
standaloneSearch: SymbolSearch,
name: String,
path: AbsolutePath,
): PresentationCompiler = {
val mtags =
mtagsResolver.resolve(scalaVersion).getOrElse(MtagsBinaries.BuildIn)
val tmpDirectory = workspace.resolve(Directories.tmp)
if (!path.toNIO.startsWith(tmpDirectory.toNIO))
scribe.info(
s"no build target found for $path. Using presentation compiler with project's scala-library version: ${mtags.scalaVersion}"
)
newCompiler(
mtags,
List.empty,
classpath ++ Embedded.scalaLibrary(scalaVersion),
standaloneSearch,
name,
)
}
// The "fallback" compiler is used for source files that don't belong to a build target.
def fallbackCompiler(path: AbsolutePath): PresentationCompiler = {
jcache.compute(
PresentationCompilerKey.Default,
(_, value) => {
val scalaVersion =
scalaVersionSelector.fallbackScalaVersion(isAmmonite = false)
val existingPc = Option(value).flatMap { pc =>
if (pc.scalaVersion == scalaVersion) {
Some(pc)
} else {
pc.shutdown()
None
}
}
existingPc match {
case Some(pc) => pc
case None =>
createStandaloneCompiler(
scalaVersion,
List.empty,
Try(
StandaloneSymbolSearch(
scalaVersion,
workspace,
buffers,
excludedPackages,
userConfig,
trees,
buildTargets,
saveSymbolFileToDisk = !config.isVirtualDocumentSupported(),
sourceMapper,
)
).getOrElse(EmptySymbolSearch),
"default",
path,
)
}
},
)
}
def loadedPresentationCompilerCount(): Int = cache.values.count(_.isLoaded())
override def cancel(): Unit = {
Cancelable.cancelEach(cache.values)(_.shutdown())
Cancelable.cancelEach(worksheetsCache.values)(_.shutdown())
cache.clear()
worksheetsCache.clear()
worksheetsDigests.clear()
outlineFilesProvider.clear()
}
def restartAll(): Unit = {
val count = cache.size
cancel()
scribe.info(
s"restarted ${count} presentation compiler${LogMessages.plural(count)}"
)
}
def load(paths: Seq[AbsolutePath]): Future[Unit] =
if (Testing.isEnabled) Future.successful(())
else {
Future {
val targets = paths
.filter(_.isScalaFilename)
.flatMap(path => buildTargets.inverseSources(path).toList)
.distinct
targets.foreach { target =>
loadCompiler(target).foreach { pc =>
pc.hover(
CompilerOffsetParams(
Paths.get("Main.scala").toUri(),
"object Ma\n",
"object Ma".length(),
)
).thenApply(_.map(_.toLsp()))
}
}
}
}
def didClose(path: AbsolutePath): Unit = {
loadCompiler(path).foreach { case (pc, _) =>
pc.didClose(path.toNIO.toUri())
}
}
def didChange(path: AbsolutePath): Future[List[Diagnostic]] = {
def originInput =
path
.toInputFromBuffers(buffers)
loadCompiler(path)
.map { case (pc, id) =>
val inputAndAdjust =
if (
path.isWorksheet && ScalaVersions.isScala3Version(pc.scalaVersion())
) {
WorksheetProvider.worksheetScala3AdjustmentsForPC(originInput)
} else {
None
}
val (input, adjust) = inputAndAdjust.getOrElse(
originInput,
AdjustedLspData.default,
)
id.foreach(outlineFilesProvider.didChange(_, path))
for {
ds <-
pc
.didChange(
CompilerVirtualFileParams(path.toNIO.toUri(), input.value)
)
.asScala
} yield {
ds.asScala.map(adjust.adjustDiagnostic).toList
}
}
.getOrElse(Future.successful(Nil))
}
def didCompile(report: CompileReport): Unit = {
val isSuccessful = report.getErrors == 0
buildTargetPCFromCache(report.getTarget).foreach { pc =>
if (
outlineFilesProvider.shouldRestartPc(
report.getTarget,
DidCompile(isSuccessful),
)
) {
pc.restart()
}
}
outlineFilesProvider.onDidCompile(report.getTarget(), isSuccessful)
if (isSuccessful) {
// Restart PC for all build targets that depend on this target since the classfiles
// may have changed.
for {
target <- buildTargets.allInverseDependencies(report.getTarget)
if target != report.getTarget
if outlineFilesProvider.shouldRestartPc(target, InverseDependency)
compiler <- buildTargetPCFromCache(target)
} {
compiler.restart()
}
}
}
def completionItemResolve(
item: CompletionItem
): Future[CompletionItem] = {
for {
data <- item.data
compiler <- buildTargetPCFromCache(new BuildTargetIdentifier(data.target))
} yield compiler.completionItemResolve(item, data.symbol).asScala
}.getOrElse(Future.successful(item))
def log: List[String] =
if (config.initialConfig.compilers.debug) {
List(
"-Ypresentation-debug",
"-Ypresentation-verbose",
"-Ypresentation-log",
workspace.resolve(Directories.pc).toString(),
)
} else {
Nil
}
/**
* Calculates completions for a expression evaluator at breakpointPosition
*
* @param path path to file containing ht ebreakpoint
* @param breakpointPosition actual breakpoint position
* @param token cancel token for the compiler
* @param expression expression that is currently being types
* @param isZeroBased whether the client supports starting at 0 or 1 index
* @return
*/
def debugCompletions(
path: AbsolutePath,
breakpointPosition: LspPosition,
token: CancelToken,
expression: d.CompletionsArguments,
isZeroBased: Boolean,
): Future[Seq[d.CompletionItem]] = {
/**
* Find the offset of the cursor inside the modified expression.
* We need it to give the compiler the right offset.
*
* @param modified modified expression with indentation inserted
* @param indentation indentation of the current breakpoint
* @return offset where the compiler should insert completions
*/
def expressionOffset(modified: String, indentation: String) = {
val line = expression.getLine()
val column = expression.getColumn()
modified.split("\n").zipWithIndex.take(line).foldLeft(0) {
case (offset, (lineText, index)) =>
if (index + 1 == line) {
if (line > 1)
offset + column + indentation.size - 1
else
offset + column - 1
} else offset + lineText.size + 1
}
}
loadCompiler(path)
.map { case (compiler, buildTargetId) =>
val input = path.toInputFromBuffers(buffers)
breakpointPosition.toMeta(input) match {
case Some(metaPos) =>
val oldText = metaPos.input.text
val lineStart = oldText.indexWhere(
c => c != ' ' && c != '\t',
metaPos.start + 1,
)
val indentationSize = lineStart - metaPos.start
val indentationChar =
if (oldText.lift(lineStart - 1).exists(_ == '\t')) '\t' else ' '
val indentation = indentationChar.toString * indentationSize
val expressionText =
expression.getText().replace("\n", s"\n$indentation")
val prev = oldText.substring(0, lineStart)
val succ = oldText.substring(lineStart)
// insert expression at the start of breakpoint's line and move the lines one down
val modified = s"$prev;$expressionText\n$indentation$succ"
val rangeEnd =
lineStart + expressionOffset(expressionText, indentation) + 1
/**
* Calculate the start if insertText is used for item, which does not declare an exact start.
*/
def insertStart = {
var i = rangeEnd - 1
while (modified.charAt(i).isLetterOrDigit) i -= 1
if (isZeroBased) i else i + 1
}
val offsetParams =
CompilerOffsetParams(
path.toURI,
modified,
rangeEnd,
token,
outlineFilesProvider.getOutlineFiles(buildTargetId),
)
val previousLines = expression
.getText()
.split("\n")
// we need to adjust start to point at the start of the replacement in the expression
val adjustStart =
/* For multiple line we need to insert at the correct offset and
* then adjust column by indentation that was added to the expression
*/
if (previousLines.size > 1)
previousLines
.take(expression.getLine() - 1)
.map(_.size + 1)
.sum - indentationSize
// for one line we only need to adjust column with indentation + ; that was added to the expression
else -(1 + indentationSize)
compiler
.complete(offsetParams)
.asScala
.map(list =>
list.getItems.asScala.toSeq
.map(
toDebugCompletionItem(
_,
adjustStart,
Position.Range(
input.copy(value = modified),
insertStart,
rangeEnd,
),
)
)
)
case None =>
scribe.debug(s"$breakpointPosition was not found in $path ")
Future.successful(Nil)
}
}
.getOrElse(Future.successful(Nil))
}
def semanticTokens(
params: SemanticTokensParams,
token: CancelToken,
): Future[SemanticTokens] = {
val emptyTokens = Collections.emptyList[Integer]();
if (!userConfig().enableSemanticHighlighting) {
Future { new SemanticTokens(emptyTokens) }
} else {
val path = params.getTextDocument.getUri.toAbsolutePath
loadCompiler(path)
.map { case (compiler, buildTargetId) =>
val (input, _, adjust) =
sourceAdjustments(
params.getTextDocument().getUri(),
compiler.scalaVersion(),
)
/**
* Find the start that is actually contained in the file and not
* in the added parts such as imports in sbt.
*
* @param line line within the adjusted source
* @param character line within the adjusted source
* @param remaining the rest of the tokens to analyze
* @return the first found that should be contained with the rest
*/
@tailrec
def findCorrectStart(
line: Integer,
character: Integer,
remaining: List[Integer],
): List[Integer] = {
remaining match {
case lineDelta :: charDelta :: next =>
val newCharacter: Integer =
// only increase character delta if the same line
if (lineDelta == 0) character + charDelta
else charDelta
val adjustedTokenPos = adjust.adjustPos(
new LspPosition(line + lineDelta, newCharacter),
adjustToZero = false,
)
if (
adjustedTokenPos.getLine() >= 0 &&
adjustedTokenPos.getCharacter() >= 0
)
(adjustedTokenPos.getLine(): Integer) ::
(adjustedTokenPos.getCharacter(): Integer) :: next
else
findCorrectStart(
line + lineDelta,
newCharacter,
next.drop(3),
)
case _ => Nil
}
}
def adjustForScala3Worksheet(tokens: List[Integer]): List[Integer] = {
@tailrec
@nowarn
def loop(
remaining: List[Integer],
acc: List[List[Integer]],
adjustColumnDelta: Int =
0, // after multiline string we need to adjust column delta of the next token in line
): List[Integer] = {
remaining match {
case Nil => acc.reverse.flatten
// we need to remove additional indent
case deltaLine :: deltaColumn :: len :: next
if deltaLine != 0 =>
if (deltaColumn - 2 >= 0) {
val adjustedColumn: Integer = deltaColumn - 2
val adjusted: List[Integer] =
List(deltaLine, adjustedColumn, len) ++ next.take(2)
loop(
next.drop(2),
adjusted :: acc,
)
}
// for multiline strings, we highlight the entire line inluding leading whitespace
// so we need to adjust the length after removing additional indent
else {
val deltaLen = deltaColumn - 2
val adjustedLen: Integer = Math.max(0, len + deltaLen)
val adjusted: List[Integer] =
List(deltaLine, deltaColumn, adjustedLen) ++ next.take(2)
loop(
next.drop(2),
adjusted :: acc,
deltaLen,
)
}
case deltaLine :: deltaColumn :: next =>
val adjustedColumn: Integer = deltaColumn + adjustColumnDelta
val adjusted: List[Integer] =
List(deltaLine, adjustedColumn) ++ next.take(3)
loop(
next.drop(3),
adjusted :: acc,
)
}
}
// Delta for first token was already adjusted in `findCorrectStart`
loop(tokens.drop(5), List(tokens.take(5)))
}
val vFile =
CompilerVirtualFileParams(
path.toNIO.toUri(),
input.text,
token,
outlineFilesProvider.getOutlineFiles(buildTargetId),
)
val isScala3 = ScalaVersions.isScala3Version(compiler.scalaVersion())
compiler
.semanticTokens(vFile)
.asScala
.map { nodes =>
val plist =
try {
SemanticTokensProvider.provide(
nodes.asScala.toList,
vFile,
isScala3,
)
} catch {
case NonFatal(e) =>
scribe.error(
s"Failed to tokenize input for semantic tokens for $path",
e,
)
Nil
}
val tokens =
findCorrectStart(0, 0, plist.toList)
if (isScala3 && path.isWorksheet) {
new SemanticTokens(adjustForScala3Worksheet(tokens).asJava)
} else {
new SemanticTokens(tokens.asJava)
}
}
}
.getOrElse(Future.successful(new SemanticTokens(emptyTokens)))
}
}
def syntheticDecorations(
path: AbsolutePath,
token: CancelToken,
): Future[ju.List[DecorationOptions]] = {
loadCompiler(path)
.map { case (compiler, buildTargetId) =>
val (input, _, adjust) =
sourceAdjustments(
path.toNIO.toUri().toString(),
compiler.scalaVersion(),
)
def adjustDecorations(
decorations: ju.List[SyntheticDecoration]
): ju.List[DecorationOptions] = {
val withCorrectStart = decorations.asScala.dropWhile { d =>
val adjusted = adjust
.adjustPos(d.range().getStart(), adjustToZero = false)
adjusted.getLine() < 0 || adjusted.getCharacter() < 0
}
withCorrectStart.map { decoration =>
DecorationOptions(
decoration.label(),
adjust.adjustRange(decoration.range()),
)
}.asJava
}
val vFile =
CompilerVirtualFileParams(
path.toNIO.toUri(),
input.text,
token,
outlineFilesProvider.getOutlineFiles(buildTargetId),
)
val pcParams = CompilerSyntheticDecorationsParams(
vFile,
typeParameters = userConfig().showInferredType.contains("true"),
inferredTypes = userConfig().showInferredType.contains("minimal") ||
userConfig().showInferredType.contains("true"),
implicitParameters = userConfig().showImplicitArguments,
implicitConversions = userConfig().showImplicitConversionsAndClasses,
)
compiler
.syntheticDecorations(pcParams)
.asScala
.map { decorations =>
adjustDecorations(decorations)
}
}
.getOrElse(Future.successful(Nil.asJava))
}
def completions(
params: CompletionParams,
token: CancelToken,
): Future[CompletionList] =
withPCAndAdjustLsp(params) { (pc, pos, adjust, buildTargetId) =>
val outlineFiles = outlineFilesProvider.getOutlineFiles(buildTargetId)
val offsetParams =
CompilerOffsetParamsUtils.fromPos(pos, token, outlineFiles)
pc.complete(offsetParams)
.asScala
.map { list =>
adjust.adjustCompletionListInPlace(list)
list
}
}.getOrElse(Future.successful(new CompletionList(Nil.asJava)))
def autoImports(
params: TextDocumentPositionParams,
name: String,
findExtensionMethods: Boolean,
token: CancelToken,
): Future[ju.List[AutoImportsResult]] = {
withPCAndAdjustLsp(params) { (pc, pos, adjust, buildTargetId) =>
pc.autoImports(
name,
CompilerOffsetParamsUtils.fromPos(
pos,
token,
outlineFilesProvider.getOutlineFiles(buildTargetId),
),
findExtensionMethods,
).asScala
.map { list =>
list.map(adjust.adjustImportResult)
list
}
}
}.getOrElse(Future.successful(Nil.asJava))
def insertInferredType(
params: TextDocumentPositionParams,
token: CancelToken,
): Future[ju.List[TextEdit]] = {
withPCAndAdjustLsp(params) { (pc, pos, adjust, buildTargetId) =>
pc.insertInferredType(
CompilerOffsetParamsUtils.fromPos(
pos,
token,
outlineFilesProvider.getOutlineFiles(buildTargetId),
)
).asScala
.map { edits =>
adjust.adjustTextEdits(edits)
}
}
}.getOrElse(Future.successful(Nil.asJava))
def inlineEdits(
params: TextDocumentPositionParams,
token: CancelToken,
): Future[ju.List[TextEdit]] =
withPCAndAdjustLsp(params) { (pc, pos, adjust, buildTargetId) =>
pc.inlineValue(
CompilerOffsetParamsUtils.fromPos(
pos,
token,
outlineFilesProvider.getOutlineFiles(buildTargetId),
)
).asScala
.map(adjust.adjustTextEdits)
}.getOrElse(Future.successful(Nil.asJava))
def documentHighlight(
params: TextDocumentPositionParams,
token: CancelToken,
): Future[ju.List[DocumentHighlight]] = {
withPCAndAdjustLsp(params) { (pc, pos, adjust, buildTargetId) =>
pc.documentHighlight(
CompilerOffsetParamsUtils.fromPos(
pos,
token,
outlineFilesProvider.getOutlineFiles(buildTargetId),
)
).asScala
.map { highlights =>
adjust.adjustDocumentHighlight(highlights)
}
}
}.getOrElse(Future.successful(Nil.asJava))
def extractMethod(
doc: TextDocumentIdentifier,
range: LspRange,
extractionPos: LspPosition,
token: CancelToken,
): Future[ju.List[TextEdit]] = {
withPCAndAdjustLsp(doc.getUri(), range, extractionPos) {
(pc, metaRange, metaExtractionPos, adjust, buildTargetId) =>
pc.extractMethod(
CompilerRangeParamsUtils.fromPos(
metaRange,
token,
outlineFilesProvider.getOutlineFiles(buildTargetId),
),
CompilerOffsetParamsUtils.fromPos(metaExtractionPos, token),
).asScala
.map { edits =>
adjust.adjustTextEdits(edits)
}
}
}.getOrElse(Future.successful(Nil.asJava))
def convertToNamedArguments(
position: TextDocumentPositionParams,
argIndices: ju.List[Integer],
token: CancelToken,
): Future[ju.List[TextEdit]] = {
withPCAndAdjustLsp(position) { (pc, pos, adjust, buildTargetId) =>
pc.convertToNamedArguments(
CompilerOffsetParamsUtils.fromPos(
pos,
token,
outlineFilesProvider.getOutlineFiles(buildTargetId),
),
argIndices,
).asScala
.map { edits =>
adjust.adjustTextEdits(edits)
}
}
}.getOrElse(Future.successful(Nil.asJava))
def implementAbstractMembers(
params: TextDocumentPositionParams,
token: CancelToken,
): Future[ju.List[TextEdit]] = {
withPCAndAdjustLsp(params) { (pc, pos, adjust, buildTargetId) =>
pc.implementAbstractMembers(
CompilerOffsetParamsUtils.fromPos(
pos,
token,
outlineFilesProvider.getOutlineFiles(buildTargetId),
)
).asScala
.map { edits =>
adjust.adjustTextEdits(edits)
}
}
}.getOrElse(Future.successful(Nil.asJava))
def hover(
params: HoverExtParams,
token: CancelToken,
): Future[Option[HoverSignature]] = {
withPCAndAdjustLsp(params) { (pc, pos, adjust, buildTargetId) =>
pc.hover(
CompilerRangeParamsUtils.offsetOrRange(
pos,
token,
outlineFilesProvider.getOutlineFiles(buildTargetId),
)
).asScala
.map(_.asScala.map { hover => adjust.adjustHoverResp(hover) })
}
}.getOrElse(Future.successful(None))
def prepareRename(
params: TextDocumentPositionParams,
token: CancelToken,
): Future[ju.Optional[LspRange]] = {
withPCAndAdjustLsp(params) { (pc, pos, adjust, buildTargetId) =>
pc.prepareRename(
CompilerRangeParamsUtils.offsetOrRange(
pos,
token,
outlineFilesProvider.getOutlineFiles(buildTargetId),
)
).asScala
.map { range =>
range.map(adjust.adjustRange(_))
}
}
}.getOrElse(Future.successful(None.asJava))
def rename(
params: RenameParams,
token: CancelToken,
): Future[ju.List[TextEdit]] = {
withPCAndAdjustLsp(params) { (pc, pos, adjust, buildTargetId) =>
pc.rename(
CompilerRangeParamsUtils.offsetOrRange(
pos,
token,
outlineFilesProvider.getOutlineFiles(buildTargetId),
),
params.getNewName(),
).asScala
.map { edits =>
adjust.adjustTextEdits(edits)
}
}
}.getOrElse(Future.successful(Nil.asJava))
def definition(
params: TextDocumentPositionParams,
token: CancelToken,
): Future[DefinitionResult] = {
definition(params = params, token = token, findTypeDef = false)
}
def typeDefinition(
params: TextDocumentPositionParams,
token: CancelToken,
): Future[DefinitionResult] = {
definition(params = params, token = token, findTypeDef = true)
}
private def definition(
params: TextDocumentPositionParams,
token: CancelToken,
findTypeDef: Boolean,
): Future[DefinitionResult] =
withPCAndAdjustLsp(params) { (pc, pos, adjust, buildTargetId) =>
val params = CompilerOffsetParamsUtils.fromPos(
pos,
token,
outlineFilesProvider.getOutlineFiles(buildTargetId),
)
val defResult =
if (findTypeDef) pc.typeDefinition(params)
else
pc.definition(CompilerOffsetParamsUtils.fromPos(pos, token))
defResult.asScala
.map { c =>
adjust.adjustLocations(c.locations())
val definitionPaths = c
.locations()
.map { loc =>
loc.getUri().toAbsolutePath
}
.asScala
.toSet
val definitionPath = if (definitionPaths.size == 1) {
Some(definitionPaths.head)
} else {
None
}
DefinitionResult(
c.locations(),
c.symbol(),
definitionPath,
None,
)
}
}.getOrElse(Future.successful(DefinitionResult.empty))
def signatureHelp(
params: TextDocumentPositionParams,
token: CancelToken,
): Future[SignatureHelp] =
withPCAndAdjustLsp(params) { (pc, pos, _, buildTargetId) =>
pc.signatureHelp(
CompilerOffsetParamsUtils.fromPos(
pos,
token,
outlineFilesProvider.getOutlineFiles(buildTargetId),
)
).asScala
}.getOrElse(Future.successful(new SignatureHelp()))
def selectionRange(
params: SelectionRangeParams,
token: CancelToken,
): Future[ju.List[SelectionRange]] = {
withPCAndAdjustLsp(params) { (pc, positions, buildTargetId) =>
val offsetPositions: ju.List[OffsetParams] =
positions.map(
CompilerOffsetParamsUtils.fromPos(
_,
token,
outlineFilesProvider.getOutlineFiles(buildTargetId),
)
)
pc.selectionRange(offsetPositions).asScala
}.getOrElse(Future.successful(Nil.asJava))
}
def loadCompiler(
path: AbsolutePath
): Option[(PresentationCompiler, Option[BuildTargetIdentifier])] = {
def fromBuildTarget
: Option[(PresentationCompiler, Option[BuildTargetIdentifier])] = {
val target = buildTargets
.inverseSources(path)
target match {
case None => Some((fallbackCompiler(path), None))
case Some(value) =>
if (path.isScalaFilename) loadCompiler(value).map((_, Some(value)))
else if (path.isJavaFilename)
loadJavaCompiler(value).map((_, Some(value)))
else None
}
}
if (!path.isScalaFilename && !path.isJavaFilename) None
else if (path.isWorksheet)
loadWorksheetCompiler(path).map((_, None)).orElse(fromBuildTarget)
else fromBuildTarget
}
def loadWorksheetCompiler(
path: AbsolutePath
): Option[PresentationCompiler] = {
worksheetProvider.getWorksheetPCData(path).flatMap { data =>
maybeRestartWorksheetPresentationCompiler(path, data)
worksheetsCache.get(path)
}
}
private def maybeRestartWorksheetPresentationCompiler(
path: AbsolutePath,
data: WorksheetPcData,
): Unit = {
val previousDigest = worksheetsDigests.getOrElse(path, "")
if (data.digest != previousDigest) {
worksheetsDigests.put(path, data.digest)
restartWorksheetPresentationCompiler(
path,
data.classpath,
data.dependencies,
)
}
}
private def restartWorksheetPresentationCompiler(
path: AbsolutePath,
classpath: List[Path],
sources: List[Path],
): Unit = {
val created: Option[Unit] = for {
targetId <- buildTargets.inverseSources(path)
scalaTarget <- buildTargets.scalaTarget(targetId)
scalaVersion = scalaTarget.scalaVersion
mtags <- {
val result = mtagsResolver.resolve(scalaVersion)
if (result.isEmpty) {
scribe.warn(s"unsupported Scala ${scalaVersion}")
}
result
}
} yield {