-
Notifications
You must be signed in to change notification settings - Fork 217
Expand file tree
/
Copy pathBloopBspServices.scala
More file actions
1731 lines (1583 loc) · 66.4 KB
/
BloopBspServices.scala
File metadata and controls
1731 lines (1583 loc) · 66.4 KB
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 bloop.bsp
import java.net.URI
import java.nio.file.FileSystems
import java.nio.file.Path
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicInteger
import scala.collection.concurrent.TrieMap
import scala.collection.mutable
import scala.concurrent.Promise
import scala.concurrent.duration.Duration
import scala.concurrent.duration.FiniteDuration
import scala.util.Failure
import scala.util.Success
import scala.util.Try
import ch.epfl.scala.bsp
import ch.epfl.scala.bsp.BuildTargetIdentifier
import ch.epfl.scala.bsp.CompileResult
import ch.epfl.scala.bsp.MessageType
import ch.epfl.scala.bsp.ShowMessageParams
import ch.epfl.scala.bsp.StatusCode
import ch.epfl.scala.bsp.Uri
import ch.epfl.scala.bsp.endpoints
import ch.epfl.scala.debugadapter.DebugServer
import ch.epfl.scala.debugadapter.Debuggee
import bloop.Compiler
import bloop.ScalaInstance
import bloop.bsp.BloopBspDefinitions.BloopExtraBuildParams
import bloop.cli.Commands
import bloop.cli.ExitStatus
import bloop.cli.Validate
import bloop.config.Config
import bloop.dap.BloopDebugToolsResolver
import bloop.dap.BloopDebuggeeRunner
import bloop.dap.DebugServerLogger
import bloop.data.ClientInfo
import bloop.data.ClientInfo.BspClientInfo
import bloop.data.JdkConfig
import bloop.data.Platform
import bloop.data.Platform.Js
import bloop.data.Platform.Jvm
import bloop.data.Platform.Native
import bloop.data.Project
import bloop.data.WorkspaceSettings
import bloop.engine.Aggregate
import bloop.engine.Dag
import bloop.engine.Feedback
import bloop.engine.Interpreter
import bloop.engine.State
import bloop.engine.tasks.CompileTask
import bloop.engine.tasks.RunMode
import bloop.engine.tasks.Tasks
import bloop.engine.tasks.TestTask
import bloop.engine.tasks.compilation.CompileClientStore
import bloop.engine.tasks.toolchains.ScalaJsToolchain
import bloop.engine.tasks.toolchains.ScalaNativeToolchain
import bloop.exec.Forker
import bloop.internal.build.BuildInfo
import bloop.io.AbsolutePath
import bloop.io.ByteHasher
import bloop.io.Environment.lineSeparator
import bloop.io.RelativePath
import bloop.logging.BspServerLogger
import bloop.logging.DebugFilter
import bloop.logging.Logger
import bloop.reporter.BspProjectReporter
import bloop.reporter.ProblemPerPhase
import bloop.reporter.ReporterConfig
import bloop.reporter.ReporterInputs
import bloop.task.Task
import bloop.testing.LoggingEventHandler
import bloop.testing.TestInternals
import bloop.util.JavaCompat._
import bloop.util.JavaRuntime
import com.github.plokhotnyuk.jsoniter_scala.core.JsonValueCodec
import com.github.plokhotnyuk.jsoniter_scala.core._
import com.github.plokhotnyuk.jsoniter_scala.core.readFromArray
import com.github.plokhotnyuk.jsoniter_scala.macros.JsonCodecMaker
import jsonrpc4s._
import monix.execution.Cancelable
import monix.execution.CancelablePromise
import monix.execution.Scheduler
import monix.execution.atomic.AtomicBoolean
import monix.execution.atomic.AtomicInt
import monix.reactive.subjects.BehaviorSubject
import sbt.internal.inc.PlainVirtualFileConverter
final class BloopBspServices(
callSiteState: State,
client: BloopLanguageClient,
relativeConfigPath: RelativePath,
stopBspServer: CancelablePromise[Unit],
observer: Option[BehaviorSubject[State]],
isClientConnected: AtomicBoolean,
connectedBspClients: ConcurrentHashMap[ClientInfo.BspClientInfo, AbsolutePath],
computationScheduler: Scheduler,
ioScheduler: Scheduler
) {
private implicit val debugFilter: DebugFilter = DebugFilter.Bsp
private type BspResponse[T] = Either[Response.Error, T]
/** The return type of every endpoint implementation */
private type BspEndpointResponse[T] = Task[BspResponse[T]]
/** The return type of intermediate BSP computations */
private type BspResult[T] = Task[(State, BspResponse[T])]
/** The return type of a bsp computation wrapped by `ifInitialized` */
private type BspComputation[T] = (State, BspServerLogger) => BspResult[T]
/**
* Schedule the async response handlers to run on the default computation
* thread pool and leave the serialization/deserialization work (bsp4s
* library work) to the IO thread pool. This is critical for performance.
*/
def schedule[T](t: BspEndpointResponse[T]): BspEndpointResponse[T] = {
t.executeOn(computationScheduler).asyncBoundary(ioScheduler)
}
private val backgroundDebugServers = TrieMap.empty[URI, Cancelable]
// Disable ansi codes for now so that the BSP clients don't get unescaped color codes
private val taskIdCounter: AtomicInt = AtomicInt(0)
private val baseBspLogger = BspServerLogger(callSiteState, client, taskIdCounter, false)
final val services: BloopRpcServices = BloopRpcServices
.empty(baseBspLogger)
.requestAsync(endpoints.Build.initialize)(p => schedule(initialize(p)))
.notification(endpoints.Build.initialized)(_ => initialized())
.request(endpoints.Build.shutdown)(_ => shutdown())
.notificationAsync(endpoints.Build.exit)(_ => exit())
.requestAsync(endpoints.Workspace.buildTargets)(_ => schedule(buildTargets()))
.requestAsync(endpoints.BuildTarget.sources)(p => schedule(sources(p)))
.requestAsync(endpoints.BuildTarget.inverseSources)(p => schedule(inverseSources(p)))
.requestAsync(endpoints.BuildTarget.resources)(p => schedule(resources(p)))
.requestAsync(endpoints.BuildTarget.outputPaths)(p => schedule(outputPaths(p)))
.requestAsync(endpoints.BuildTarget.scalacOptions)(p => schedule(scalacOptions(p)))
.requestAsync(endpoints.BuildTarget.javacOptions)(p => schedule(javacOptions(p)))
.requestAsync(endpoints.BuildTarget.compile)(p => schedule(compile(p)))
.requestAsync(endpoints.BuildTarget.test)(p => schedule(test(p)))
.requestAsync(endpoints.BuildTarget.run)(p => schedule(run(p)))
.requestAsync(endpoints.BuildTarget.cleanCache)(p => schedule(clean(p)))
.requestAsync(endpoints.BuildTarget.scalaMainClasses)(p => schedule(scalaMainClasses(p)))
.requestAsync(endpoints.BuildTarget.scalaTestClasses)(p => schedule(scalaTestClasses(p)))
.requestAsync(endpoints.BuildTarget.dependencySources)(p => schedule(dependencySources(p)))
.requestAsync(endpoints.BuildTarget.dependencyModules)(p => schedule(dependencyModules(p)))
.requestAsync(endpoints.DebugSession.start)(p => schedule(startDebugSession(p)))
.requestAsync(endpoints.BuildTarget.jvmTestEnvironment)(p => schedule(jvmTestEnvironment(p)))
.requestAsync(endpoints.BuildTarget.jvmRunEnvironment)(p => schedule(jvmRunEnvironment(p)))
.notificationAsync(BloopBspDefinitions.stopClientCaching)(p => stopClientCaching(p))
.requestAsync(BloopBspDefinitions.debugIncrementalCompilation)(p =>
schedule(debugIncrementalCompilation(p))
)
// Internal state, initial value defaults to
@volatile private var currentState: State = callSiteState
/** Returns the final state after BSP commands that can be cached by bloop. */
def stateAfterExecution: State = {
// Use logger of the initial state instead of the bsp forwarder logger
val nextState0 = currentState.copy(logger = callSiteState.logger)
clientInfo.future.value match {
case Some(scala.util.Success(clientInfo)) => nextState0.copy(client = clientInfo)
case _ => nextState0
}
}
private val previouslyFailedCompilations = new TrieMap[Project, Compiler.Result.Failed]()
private def reloadState(
config: AbsolutePath,
clientInfo: ClientInfo,
clientSettings: Option[WorkspaceSettings],
bspLogger: BspServerLogger
): Task[State] = {
val pool = currentState.pool
val defaultOpts = currentState.commonOptions
bspLogger.debug(s"Reloading bsp state for ${config.syntax}")
State
.loadActiveStateFor(config, clientInfo, pool, defaultOpts, bspLogger, clientSettings)
.map { state0 =>
/* Create a new state that has the previously compiled results in this BSP
* client as the last compiled result available for a project. This is required
* because in diagnostics reporting in BSP is stateful. When compilations
* happen in other clients, the previous result does not contain the list of
* previous problems (that tracks where we reported diagnostics) that this client
* had and therefore we can fail to reset diagnostics. */
val newState = {
val previous = previouslyFailedCompilations.toMap
state0.copy(
results = state0.results.replacePreviousResults(previous),
client = clientInfo
)
}
currentState = newState
newState
}
}
private def saveState(state: State, bspLogger: BspServerLogger): Task[Unit] = {
Task {
val configDir = state.build.origin
bspLogger.debug(s"Saving bsp state for ${configDir.syntax}")
// Save the state globally so that it can be accessed by other clients
State.stateCache.updateBuild(state)
publishStateInObserver(state)
}.flatten
}
// Completed whenever the initialization happens, used in `initialized`
val clientInfo: Promise[BspClientInfo] = Promise[ClientInfo.BspClientInfo]()
val clientInfoTask: Task[BspClientInfo] = Task.fromFuture(clientInfo.future).memoize
/**
* Unregisters this client if the BSP services registered one.
*
* This method is typically called from `BspServer` when a client is
* disconnected for any reason.
*/
def unregisterClient: Option[ClientInfo.BspClientInfo] = {
Cancelable.cancelAll(backgroundDebugServers.values)
clientInfo.future.value match {
case None => None
case Some(client) =>
client match {
case Success(client) =>
val configDir = currentState.build.origin
connectedBspClients.remove(client, configDir)
Some(client)
case Failure(_) => None
}
}
}
/**
* Implements the initialize method that is the first pass of the Client-Server handshake.
*
* @param params The params request that we get from the client.
* @return An async computation that returns the response to the client.
*/
def initialize(
params: bsp.InitializeBuildParams
): BspEndpointResponse[bsp.InitializeBuildResult] = {
val bspLogger = baseBspLogger
val uri = new URI(params.rootUri.value)
val configDir = AbsolutePath(uri).resolve(relativeConfigPath)
val extraBuildParams = parseBloopExtraParams(params.data)
val ownsBuildFiles = extraBuildParams.flatMap(_.ownsBuildFiles).getOrElse(false)
val clientClassesRootDir = extraBuildParams.flatMap(extra =>
extra.clientClassesRootDir.map(dir => AbsolutePath(dir.toPath))
)
val currentWorkspaceSettings = WorkspaceSettings.readFromFile(configDir, callSiteState.logger)
val currentRefreshProjectsCommand: Option[List[String]] =
currentWorkspaceSettings.flatMap(_.refreshProjectsCommand)
val currentTraceSettings = currentWorkspaceSettings.flatMap(_.traceSettings)
val isMetals = params.displayName.contains("Metals")
val isIntelliJ = params.displayName.contains("IntelliJ")
val refreshProjectsCommand = if (isIntelliJ) currentRefreshProjectsCommand else None
val client = ClientInfo.BspClientInfo(
params.displayName,
params.version,
params.bspVersion,
ownsBuildFiles,
clientClassesRootDir,
refreshProjectsCommand,
() => isClientConnected.get
)
/**
* A Metals BSP client enables a special transformation of a build via the
* workspace settings. These workspace settings contains all of the
* information required by bloop to enable Metals-specific settings in
* every project of a build so that users from different build tools don't
* need to manually enable these in their build.
*/
val metalsSettings: Option[WorkspaceSettings] = {
if (!isMetals) {
currentWorkspaceSettings
} else {
val javaSemanticDBVersion = extraBuildParams.flatMap(_.javaSemanticdbVersion)
val scalaSemanticDBVersion = extraBuildParams.flatMap(_.semanticdbVersion)
val enableBestEffortMode = extraBuildParams.flatMap(_.enableBestEffortMode)
val supportedScalaVersions =
if (scalaSemanticDBVersion.nonEmpty)
extraBuildParams.map(_.supportedScalaVersions.toList.flatten)
else None
if (javaSemanticDBVersion.nonEmpty || scalaSemanticDBVersion.nonEmpty)
Some(
WorkspaceSettings(
javaSemanticDBVersion,
scalaSemanticDBVersion,
supportedScalaVersions,
currentRefreshProjectsCommand,
currentTraceSettings,
enableBestEffortMode
)
)
else None
}
}
reloadState(configDir, client, metalsSettings, bspLogger).flatMap { state =>
callSiteState.logger.info(s"request received: build/initialize")
clientInfo.success(client)
connectedBspClients.put(client, configDir)
publishStateInObserver(state.copy(client = client)).map { _ =>
Right(
bsp.InitializeBuildResult(
BuildInfo.bloopName,
BuildInfo.version,
BuildInfo.bspVersion,
bsp.BuildServerCapabilities(
compileProvider = Some(BloopBspServices.DefaultCompileProvider),
testProvider = Some(BloopBspServices.DefaultTestProvider),
runProvider = Some(BloopBspServices.DefaultRunProvider),
debugProvider = Some(BloopBspServices.DefaultDebugProvider),
inverseSourcesProvider = Some(true),
dependencySourcesProvider = Some(true),
dependencyModulesProvider = Some(true),
resourcesProvider = Some(true),
outputPathsProvider = Some(true),
buildTargetChangedProvider = Some(false),
jvmTestEnvironmentProvider = Some(true),
jvmRunEnvironmentProvider = Some(true),
canReload = Some(false)
),
None,
None
)
)
}
}
}
private def publishStateInObserver(state: State): Task[Unit] = {
observer match {
case None => Task.unit
case Some(observer) => Task.fromFuture(observer.onNext(state)).map(_ => ())
}
}
private def parseBloopExtraParams(data: Option[RawJson]): Option[BloopExtraBuildParams] = {
data.flatMap { json =>
try Some(readFromArray[BloopExtraBuildParams](json.value))
catch {
case e: Exception =>
callSiteState.logger.warn(
s"Unexpected error decoding bloop-specific initialize params: ${e.getMessage()}"
)
None
}
}
}
val isInitialized: Promise[BspResponse[Unit]] = scala.concurrent.Promise[BspResponse[Unit]]()
val isInitializedTask: Task[BspResponse[Unit]] = Task.fromFuture(isInitialized.future).memoize
def initialized(): Unit = {
isInitialized.success(Right(()))
callSiteState.logger.info("BSP initialization handshake complete.")
}
def ifInitialized[T](
originId: Option[String]
)(compute: BspComputation[T]): Task[BspResponse[T]] = {
val bspLogger = baseBspLogger.withOriginId(originId)
// Give a time window for `isInitialized` to complete, otherwise assume it didn't happen
isInitializedTask
.flatMap(_ => clientInfoTask.map(Right(_)))
.timeoutTo(
FiniteDuration(1, TimeUnit.SECONDS),
Task.now(Left(Response.invalidRequest("The session has not been initialized.")))
)
.flatMap {
case Left(e) => Task.now(Left(e))
case Right(clientInfo) =>
reloadState(currentState.build.origin, clientInfo, None, bspLogger).flatMap { state =>
compute(state, bspLogger).flatMap {
case (state, e) => saveState(state, bspLogger).map(_ => e)
}
}
}
}
def mapToProject(
target: bsp.BuildTargetIdentifier,
state: State
): Either[String, ProjectMapping] = {
val uri = target.uri
ProjectUris.getProjectDagFromUri(uri.value, state) match {
case Left(errorMsg) => Left(errorMsg)
case Right(Some(project)) => Right((target, project))
case Right(None) => Left(s"No project associated with $uri")
}
}
type ProjectMapping = (bsp.BuildTargetIdentifier, Project)
private def mapToProjects(
targets: Seq[bsp.BuildTargetIdentifier],
state: State
): Either[String, Seq[ProjectMapping]] = {
if (targets.isEmpty) {
Left("Empty build targets. Expected at least one build target identifier.")
} else {
val zero: Either[String, List[ProjectMapping]] = Right(Nil)
targets.foldLeft(zero) { (acc, t) =>
acc.flatMap(ms => mapToProject(t, state).map(m => m :: ms))
}
}
}
/**
* Keep track of those projects that were compiled at least once so that we can
* decide to enable fresh reporting for projects that are compiled for the first time.
*
* Required by https://github.com/scalacenter/bloop/issues/726
*/
private val compiledTargetsAtLeastOnce = new TrieMap[bsp.BuildTargetIdentifier, Boolean]()
private val originToCompileStores = new TrieMap[String, CompileClientStore.ConcurrentStore]()
def stopClientCaching(params: BloopBspDefinitions.StopClientCachingParams): Task[Unit] = {
Task.eval { originToCompileStores.remove(params.originId); () }.executeAsync
}
def debugIncrementalCompilation(
params: BloopBspDefinitions.DebugIncrementalCompilationParams
): BspEndpointResponse[BloopBspDefinitions.DebugIncrementalCompilationResult] = {
def debugInfo(
projects: Seq[ProjectMapping],
state: State
): BspResult[BloopBspDefinitions.DebugIncrementalCompilationResult] = {
val debugInfos = projects.map {
case (target, project) =>
collectDebugInfo(target, project, state)
}
Task.sequence(debugInfos).map { debugInfos =>
(state, Right(BloopBspDefinitions.DebugIncrementalCompilationResult(debugInfos.toList)))
}
}
ifInitialized(None) { (state: State, _: BspServerLogger) =>
mapToProjects(params.targets, state) match {
case Left(error) => Task.now((state, Left(Response.invalidRequest(error))))
case Right(mappings) => debugInfo(mappings, state)
}
}
}
private def collectDebugInfo(
target: bsp.BuildTargetIdentifier,
project: Project,
state: State
): Task[BloopBspDefinitions.IncrementalCompilationDebugInfo] = {
val allSources = bloop.io.SourceHasher
.findAndHashSourcesInProject(
project,
_ => Task.now(Nil),
20,
Promise[Unit](),
ioScheduler,
state.logger
)
.map(res => res.map(_.sortBy(_.source.id())))
.executeOn(ioScheduler)
allSources.map { allSources =>
import bloop.bsp.BloopBspDefinitions._
import java.nio.file.Files
val projectAnalysisFile = state.client
.getUniqueClassesDirFor(project, forceGeneration = false)
.resolve(s"../../${project.name}-analysis.bin")
val converter = PlainVirtualFileConverter.converter
// Extract analysis info from successful compilation results
val analysisInfo = state.results.lastSuccessfulResult(project) match {
case Some(success) =>
val maybeAnalysis = success.previous.analysis()
val analysis = maybeAnalysis.toOption match {
case Some(analysis: sbt.internal.inc.Analysis) => analysis
case _ => sbt.internal.inc.Analysis.empty
}
val compilationInfo = analysis
.readCompilations()
.getAllCompilations
.toList
.map { compilation =>
s" ${compilation.getStartTime} -> ${compilation.getOutput()}"
}
.mkString("\n")
val relations = analysis.relations
val lastModifiedA =
if (Files.exists(projectAnalysisFile.underlying))
Files.getLastModifiedTime(projectAnalysisFile.underlying).toMillis()
else 0L
val changedSource = allSources match {
case Left(_) => Nil
case Right(value) =>
value.filterNot { sourceHash =>
success.sources.exists(_.source.id() == sourceHash.source.id())
}
}
val hashes = success.sources.map { sourceHash =>
val sourcePath = converter.toPath(sourceHash.source)
val exists = Files.exists(sourcePath)
val lastModified = if (exists) sourcePath.toFile.lastModified() else 0L
val currentHash =
if (exists) ByteHasher.hashFileContents(sourcePath.toFile)
else 0
FileHashInfo(
uri = bsp.Uri(sourcePath.toUri()),
currentHash = currentHash,
analysisHash = Some(sourceHash.hash),
lastModified = lastModified,
exists = exists
)
}
val currentFailedResult = state.results.latestResult(project) match {
case _: Compiler.Result.Success => ""
case otherwise => otherwise.toString()
}
val analysisInfo =
AnalysisDebugInfo(
lastModified = lastModifiedA,
sourceFiles = analysis.readStamps.getAllSourceStamps.size(),
classFiles = analysis.readStamps.getAllProductStamps.size(),
internalDependencies = relations.allProducts.size,
externalDependencies = relations.allLibraryDeps.size,
location = bsp.Uri(projectAnalysisFile.toBspUri),
excludedFiles = changedSource.map(_.source.toString())
)
Some(
IncrementalCompilationDebugInfo(
target = target,
analysisInfo = Some(analysisInfo),
allFileHashes = hashes.toList,
lastCompilationInfo = compilationInfo,
maybeFailedCompilation = currentFailedResult
)
)
case _ => None
}
analysisInfo.getOrElse(
IncrementalCompilationDebugInfo(
target = target,
analysisInfo = None,
allFileHashes = Nil,
lastCompilationInfo = "",
maybeFailedCompilation = ""
)
)
}
}
def linkProjects(
userProjects: Seq[ProjectMapping],
state: State,
compileArgs: List[String],
originId: Option[String],
logger: BspServerLogger
): BspResult[bsp.CompileResult] = {
import bloop.engine.tasks.LinkTask.{linkJS, linkNative}
val isRelease = compileArgs.exists(_ == "--release")
val isDebug = compileArgs.exists(_ == "--debug")
val overrideLinkerMode = if (isRelease && isDebug) {
logger.warn(
"both --release and --debug passed as additional arguments for linking. Ignoring arguments"
)
None
} else if (isRelease) {
Some(Config.LinkerMode.Release)
} else {
Some(Config.LinkerMode.Debug)
}
def doLink(
project: Project,
newState: State
): Task[(State, Right[Nothing, CompileResult])] =
project.platform match {
case platform @ Js(config, _, _) =>
val cmd = Commands.Link(List(project.name))
val targetDir = ScalaJsToolchain.linkTargetFrom(project, config)
linkJS(cmd, project, newState, false, None, targetDir, platform, overrideLinkerMode).map {
linkState =>
val result = if (linkState.status == ExitStatus.LinkingError) {
Right(bsp.CompileResult(originId, bsp.StatusCode.Error, None, None))
} else {
Right(bsp.CompileResult(originId, bsp.StatusCode.Ok, None, None))
}
(linkState, result)
}
case Jvm(_, _, _, _, _, _) =>
// We can just NoOp here as we have already run the compile step before doLink
Task.now((newState, Right(bsp.CompileResult(originId, bsp.StatusCode.Ok, None, None))))
case platform @ Native(config, _, userMainClass) =>
val cmd = Commands.Link(List(project.name))
val target = ScalaNativeToolchain.linkTargetFrom(project, config)
linkNative(cmd, project, newState, userMainClass, target, platform, overrideLinkerMode)
.map { linkState =>
val result = if (linkState.status == ExitStatus.LinkingError) {
Right(bsp.CompileResult(originId, bsp.StatusCode.Error, None, None))
} else {
Right(bsp.CompileResult(originId, bsp.StatusCode.Ok, None, None))
}
(linkState, result)
}
}
compileProjects(userProjects, state, compileArgs, originId, logger).flatMap {
case (newState, Right(CompileResult(_, StatusCode.Ok, _, _))) =>
val linkExecution: Task[Seq[(State, Either[Response.Error, CompileResult])]] =
Task.sequence(userProjects.map { case (_, p) => doLink(p, newState) })
linkExecution.materialize.map {
case Success(linkRunsSeq) =>
val errors = linkRunsSeq.collect { case (_, Left(err)) => err }
if (errors.nonEmpty) {
logger.error(
s"Encountered errors when liking\n${errors.map(_.getMessage()).mkString("\n")}"
)
(newState, Right(bsp.CompileResult(originId, bsp.StatusCode.Error, None, None)))
} else {
linkRunsSeq.last
}
case Failure(e) =>
val errorMessage =
Response.internalError(s"Failed linking: ${e.getMessage}")
(newState, Left(errorMessage))
}
case (newState, Right(CompileResult(_, errorCode, _, _))) =>
Task.now((newState, Right(bsp.CompileResult(originId, errorCode, None, None))))
case (newState, Left(error)) =>
Task.now((newState, Left(error)))
}
}
def compileProjects(
userProjects: Seq[ProjectMapping],
state: State,
compileArgs: List[String],
originId: Option[String],
logger: BspServerLogger
): BspResult[bsp.CompileResult] = {
val cancelCompilation = Promise[Unit]()
def reportError(p: Project, problems: List[ProblemPerPhase], elapsedMs: Long): String = {
// Don't show warnings in this "final report", we're handling them in the reporter
val count = bloop.reporter.Problem.count(problems)
s"${p.name} [${elapsedMs}ms] (errors ${count.errors})"
}
val isPipeline = compileArgs.exists(_ == "--pipeline")
val bestEffortAllowed = compileArgs.exists(_ == "--best-effort")
def compile(projects: List[Project]): Task[State] = {
val config = ReporterConfig.defaultFormat.copy(reverseOrder = false)
val isSbtClient = state.client match {
case info: BspClientInfo if info.name == "sbt" => true
case _ => false
}
val createReporter = (inputs: ReporterInputs[BspServerLogger]) => {
val btid = bsp.BuildTargetIdentifier(inputs.project.bspUri)
val reportAllPreviousProblems = {
val report = compiledTargetsAtLeastOnce.putIfAbsent(btid, true) match {
case Some(_) => false
case None => true
}
if (isSbtClient) false
else report
}
new BspProjectReporter(
inputs.project,
inputs.logger,
inputs.cwd,
config,
reportAllPreviousProblems
)
}
val dag = Aggregate(projects.map(p => state.build.getDagFor(p)))
val store = {
if (!isSbtClient) CompileClientStore.NoStore
else {
originId match {
case None => CompileClientStore.NoStore
case Some(originId) =>
val newStore = new CompileClientStore.ConcurrentStore()
originToCompileStores.putIfAbsent(originId, newStore) match {
case Some(store) => store
case None => newStore
}
}
}
}
CompileTask.compile(
state,
dag,
createReporter,
isPipeline,
bestEffortAllowed,
cancelCompilation,
store,
logger
)
}
val projects: List[Project] = {
val projects0 = Dag.reduce(state.build.dags, userProjects.map(_._2).toSet).toList
if (!compileArgs.exists(_ == "--cascade")) projects0
else Dag.inverseDependencies(state.build.dags, projects0).reduced
}
compile(projects).map { newState =>
val compiledResults = state.results.diffLatest(newState.results)
val errorMsgs = compiledResults.flatMap {
case (p, result) =>
result match {
case Compiler.Result.Empty => Nil
case Compiler.Result.Blocked(_) => Nil
case Compiler.Result.Success(_, _, _, _, _, _, _) =>
previouslyFailedCompilations.remove(p)
Nil
case Compiler.Result.GlobalError(problem, _) => List(problem)
case Compiler.Result.Cancelled(problems, elapsed, _) =>
List(reportError(p, problems, elapsed))
case f @ Compiler.Result.Failed(problems, t, elapsed, _, _) =>
previouslyFailedCompilations.put(p, f)
val acc = List(reportError(p, problems, elapsed))
t match {
case Some(t) => s"Bloop error when compiling ${p.name}: '${t.getMessage}'" :: acc
case None => acc
}
}
}
val response: Either[Response.Error, bsp.CompileResult] = {
if (cancelCompilation.isCompleted)
Right(bsp.CompileResult(originId, bsp.StatusCode.Cancelled, None, None))
else {
errorMsgs match {
case Nil => Right(bsp.CompileResult(originId, bsp.StatusCode.Ok, None, None))
case _ => Right(bsp.CompileResult(originId, bsp.StatusCode.Error, None, None))
}
}
}
(newState, response)
}
}
def compile(params: bsp.CompileParams): BspEndpointResponse[bsp.CompileResult] = {
ifInitialized(params.originId) { (state: State, logger0: BspServerLogger) =>
mapToProjects(params.targets, state) match {
case Left(error) =>
// Log the mapping error to the user via a log event + an error status code
logger0.error(error)
Task.now((state, Right(bsp.CompileResult(None, bsp.StatusCode.Error, None, None))))
case Right(mappings) =>
val compileArgs = params.arguments.getOrElse(Nil)
val isVerbose = compileArgs.exists(_ == "--verbose")
val isLink = compileArgs.exists(_ == "--link")
val logger = if (isVerbose) logger0.asBspServerVerbose else logger0
if (isLink) linkProjects(mappings, state, compileArgs, params.originId, logger)
else compileProjects(mappings, state, compileArgs, params.originId, logger)
}
}
}
def clean(params: bsp.CleanCacheParams): BspEndpointResponse[bsp.CleanCacheResult] = {
ifInitialized(None) { (state: State, logger: BspServerLogger) =>
mapToProjects(params.targets, state) match {
case Left(error) =>
// Log the mapping error to the user via a log event + an error status code
logger.error(error)
val msg = s"Couldn't map all targets to clean to projects in the build: $error"
Task.now((state, Right(bsp.CleanCacheResult(Some(msg), cleaned = false))))
case Right(mappings) =>
val projectsToClean = mappings.map(_._2).toList
Tasks.clean(state, projectsToClean, includeDeps = false).materialize.map {
case Success(state) => (state, Right(bsp.CleanCacheResult(None, cleaned = true)))
case Failure(exception) =>
val t = Logger.prettyPrintException(exception)
val msg = s"Unexpected error when cleaning build targets!${lineSeparator}$t"
state -> Right(bsp.CleanCacheResult(Some(msg), cleaned = false))
}
}
}
}
def scalaTestClasses(
params: bsp.ScalaTestClassesParams
): BspEndpointResponse[bsp.ScalaTestClassesResult] =
ifInitialized(params.originId) { (state: State, logger: BspServerLogger) =>
mapToProjects(params.targets, state) match {
case Left(error) =>
logger.error(error)
Task.now((state, Right(bsp.ScalaTestClassesResult(Nil))))
case Right(projects) =>
val subTasks = projects.toList.filter(p => TestTask.isTestProject(p._2)).map {
case (id, project) =>
val task = TestTask.findTestNamesWithFramework(project, state)
val item = task.map { classes =>
classes
.groupBy(_.framework)
.map {
case (framework, classes) =>
bsp.ScalaTestClassesItem(id, Some(framework), classes.flatMap(_.classes))
}
.toList
}
item
}
Task.sequence(subTasks).map { items =>
val result = bsp.ScalaTestClassesResult(items.flatten)
(state, Right(result))
}
}
}
def startDebugSession(
params: bsp.DebugSessionParams
): BspEndpointResponse[bsp.DebugSessionAddress] = {
def inferDebuggee(projects: Seq[Project], state: State): BspResponse[Debuggee] = {
def convert[A: JsonValueCodec](
f: A => Either[String, Debuggee]
): Either[Response.Error, Debuggee] = {
params.data match {
case Some(data) =>
Try(readFromArray[A](data.value)) match {
case Failure(error) =>
Left(Response.invalidRequest(error.getMessage()))
case Success(params) =>
f(params) match {
case Right(adapter) => Right(adapter)
case Left(error) => Left(Response.invalidRequest(error))
}
}
case None =>
Left(Response.invalidRequest("No debug data available"))
}
}
params.dataKind match {
case Some(bsp.DebugSessionParamsDataKind.ScalaMainClass) =>
convert[bsp.ScalaMainClass](main =>
BloopDebuggeeRunner.forMainClass(projects, main, state, ioScheduler)
)
case Some(bsp.TestParamsDataKind.ScalaTestSuites) =>
implicit val codec = JsonCodecMaker.make[List[String]]
convert[List[String]](classNames => {
val testClasses = bsp.ScalaTestSuites(
classNames.map(className => bsp.ScalaTestSuiteSelection(className, Nil)),
Nil,
Nil
)
BloopDebuggeeRunner.forTestSuite(projects, testClasses, state, ioScheduler)
})
case Some(bsp.TestParamsDataKind.ScalaTestSuitesSelection) =>
convert[bsp.ScalaTestSuites](testClasses => {
BloopDebuggeeRunner.forTestSuite(projects, testClasses, state, ioScheduler)
})
case Some(bsp.DebugSessionParamsDataKind.ScalaAttachRemote) =>
Right(BloopDebuggeeRunner.forAttachRemote(projects, state, ioScheduler))
case dataKind => Left(Response.invalidRequest(s"Unsupported data kind: $dataKind"))
}
}
ifInitialized(None) { (state, logger) =>
JavaRuntime.loadJavaDebugInterface match {
case Failure(exception) =>
val message = JavaRuntime.current match {
case JavaRuntime.JDK => Feedback.detectedJdkWithoutJDI(exception)
case JavaRuntime.JRE => Feedback.detectedUnsupportedJreForDebugging(exception)
}
Task.now((state, Left(Response.internalError(message))))
case Success(_) =>
mapToProjects(params.targets, state) match {
case Left(error) =>
// Log the mapping error to the user via a log event + an error status code
logger.error(error)
Task.now((state, Left(Response.invalidRequest(error))))
case Right(mappings) =>
// FIXME: Add origin id to DAP request
compileProjects(mappings, state, Nil, None, logger).flatMap {
case (state, Left(error)) =>
Task.now((state, Left(error)))
case (state, Right(result)) if result.statusCode != bsp.StatusCode.Ok =>
Task.now(
(state, Left(Response.internalError("Compilation not successful")))
)
case (state, Right(_)) =>
val projects = mappings.map(_._2)
inferDebuggee(projects, state) match {
case Right(debuggee) =>
val dapLogger = new DebugServerLogger(logger)
val resolver = new BloopDebugToolsResolver(logger)
val handler =
DebugServer.run(
debuggee,
resolver,
dapLogger,
gracePeriod = Duration(5, TimeUnit.SECONDS)
)(ioScheduler)
val listenAndUnsubscribe = Task
.fromFuture(handler.running)
.map(_ => backgroundDebugServers -= handler.uri)
.runAsync(ioScheduler)
backgroundDebugServers += handler.uri -> listenAndUnsubscribe
Task.now(
(state, Right(new bsp.DebugSessionAddress(bsp.Uri(handler.uri.toString()))))
)
case Left(error) =>
Task.now((state, Left(error)))
}
}
}
}
}
}
def test(params: bsp.TestParams): BspEndpointResponse[bsp.TestResult] = {
def scalaTestSuitesByKind(kind: String): bsp.ScalaTestSuites =
kind match {
case bsp.TestParamsDataKind.ScalaTest =>
val scalaTestParams: Option[bsp.ScalaTestParams] =
params.data.map(raw => readFromArray[bsp.ScalaTestParams](raw.value))
val suites: List[bsp.ScalaTestSuiteSelection] =
scalaTestParams
.flatMap(
_.testClasses
.map(_.flatMap(item => item.classes))
.map(_.map(cls => bsp.ScalaTestSuiteSelection.apply(cls, Nil)))
)
.getOrElse(Nil)
bsp.ScalaTestSuites(suites, Nil, Nil)
case bsp.TestParamsDataKind.ScalaTestSuites =>
val scalaTestSuites: Option[List[bsp.ScalaTestSuiteSelection]] = params.data
.map { raw =>
readFromArray[List[String]](raw.value)(JsonCodecMaker.make[List[String]])
}
.map(_.map(className => bsp.ScalaTestSuiteSelection(className, Nil)))
bsp.ScalaTestSuites(scalaTestSuites.getOrElse(Nil), Nil, Nil)
case bsp.TestParamsDataKind.ScalaTestSuitesSelection =>
params.data
.map(raw => readFromArray[bsp.ScalaTestSuites](raw.value))
.getOrElse(bsp.ScalaTestSuites(Nil, Nil, Nil))
case _ => bsp.ScalaTestSuites(Nil, Nil, Nil)
}
def test(project: Project, state: State): Task[Tasks.TestRuns] = {
val scalaTestSuites: bsp.ScalaTestSuites = params.dataKind match {
case None => bsp.ScalaTestSuites(Nil, Nil, Nil)
case Some(kind) => scalaTestSuitesByKind(kind)
}
val testFilter =
TestInternals.parseFilters(Nil) // Does not handle filtering of tests, yet
val handler = new LoggingEventHandler(state.logger)
Tasks.test(
state,
List(project),
Nil,
testFilter,
scalaTestSuites,
handler,
mode = RunMode.Normal
)
}
val originId = params.originId
ifInitialized(originId) { (state: State, logger0: BspServerLogger) =>