forked from VirtusLab/scala-cli
/
BspClient.scala
275 lines (251 loc) · 9.92 KB
/
BspClient.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
package scala.build.bsp
import ch.epfl.scala.bsp4j.{ScalaAction, ScalaDiagnostic, ScalaTextEdit, ScalaWorkspaceEdit}
import ch.epfl.scala.bsp4j as b
import com.google.gson.{Gson, JsonElement}
import java.lang.Boolean as JBoolean
import java.net.URI
import java.nio.file.Paths
import java.util.concurrent.{ConcurrentHashMap, ExecutorService}
import scala.build.Position.File
import scala.build.bsp.protocol.TextEdit
import scala.build.errors.{BuildException, CompositeBuildException, Diagnostic, Severity}
import scala.build.internal.util.WarningMessages
import scala.build.postprocessing.LineConversion.scalaLineToScLine
import scala.build.{BloopBuildClient, GeneratedSource, Logger}
import scala.jdk.CollectionConverters.*
class BspClient(
readFilesEs: ExecutorService,
@volatile var logger: Logger,
var forwardToOpt: Option[b.BuildClient] = None
) extends b.BuildClient with BuildClientForwardStubs with BloopBuildClient
with HasGeneratedSourcesImpl {
private def updatedPublishDiagnosticsParams(
params: b.PublishDiagnosticsParams,
genSource: GeneratedSource
): Either[() => b.PublishDiagnosticsParams, b.PublishDiagnosticsParams] = {
val updatedUri = genSource.reportingPath.fold(
_ => params.getTextDocument.getUri,
_.toNIO.toUri.toASCIIString
)
val updatedDiagnostics =
if (genSource.wrapperParamsOpt.isEmpty)
Right(params.getDiagnostics)
else
Left { () =>
val updateLine = scalaLine => scalaLineToScLine(scalaLine, genSource.wrapperParamsOpt)
params.getDiagnostics.asScala.toSeq
.map { diag =>
val updatedDiagOpt = for {
startLine <- updateLine(diag.getRange.getStart.getLine)
endLine <- updateLine(diag.getRange.getEnd.getLine)
} yield {
val diag0 = diag.duplicate()
diag0.getRange.getStart.setLine(startLine)
diag0.getRange.getEnd.setLine(endLine)
val scalaDiagnostic = new Gson().fromJson[b.ScalaDiagnostic](
diag0.getData().asInstanceOf[JsonElement],
classOf[b.ScalaDiagnostic]
)
scalaDiagnostic.getActions().asScala.foreach { action =>
for {
change <- action.getEdit().getChanges().asScala
startLine <- updateLine(change.getRange.getStart.getLine)
endLine <- updateLine(change.getRange.getEnd.getLine)
} yield {
change.getRange().getStart.setLine(startLine)
change.getRange().getEnd.setLine(endLine)
}
}
diag0.setData(scalaDiagnostic)
if (
diag0.getMessage.contains(
"cannot be a main method since it cannot be accessed statically"
)
)
diag0.setMessage(
WarningMessages.mainAnnotationNotSupported( /* annotationIgnored */ false)
)
diag0
}
updatedDiagOpt.getOrElse(diag)
}
.asJava
}
def updatedParamsFor(
updatedDiagnostics: java.util.List[b.Diagnostic]
): b.PublishDiagnosticsParams = {
val updatedTextDoc = new b.TextDocumentIdentifier(updatedUri)
val updatedParams = new b.PublishDiagnosticsParams(
updatedTextDoc,
params.getBuildTarget,
updatedDiagnostics,
params.getReset
)
updatedParams.setOriginId(params.getOriginId)
updatedParams
}
updatedDiagnostics
.left.map(f => () => updatedParamsFor(f()))
.map(updatedParamsFor(_))
}
override def onBuildPublishDiagnostics(params: b.PublishDiagnosticsParams): Unit = {
val path = os.Path(Paths.get(new URI(params.getTextDocument.getUri)))
buildExceptionDiagnosticsDocs.remove((path, params.getBuildTarget))
actualBuildPublishDiagnostics(params)
}
private def actualBuildPublishDiagnostics(params: b.PublishDiagnosticsParams): Unit = {
val updatedParamsOpt = targetScopeOpt(params.getBuildTarget).flatMap { scope =>
generatedSources.getOrElse(scope, HasGeneratedSources.GeneratedSources(Nil))
.uriMap
.get(params.getTextDocument.getUri)
.map { genSource =>
updatedPublishDiagnosticsParams(params, genSource)
}
}
def call(updatedParams0: b.PublishDiagnosticsParams): Unit =
super.onBuildPublishDiagnostics(updatedParams0)
updatedParamsOpt match {
case None =>
call(params)
case Some(Right(updatedParams0)) =>
call(updatedParams0)
case Some(Left(updateParamsFunc)) =>
val runnable =
new Runnable {
def run(): Unit =
try call(updateParamsFunc())
catch {
case t: Throwable =>
logger.debug(s"Caught $t while publishing updated diagnostics")
}
}
readFilesEs.submit(runnable)
}
}
def setProjectParams(newParams: Seq[String]): Unit = {}
def diagnostics: Option[Seq[(Either[String, os.Path], b.Diagnostic)]] = None
def clear(): Unit = {}
private val buildExceptionDiagnosticsDocs =
new ConcurrentHashMap[(os.Path, b.BuildTargetIdentifier), JBoolean]
def resetDiagnostics(path: os.Path, targetId: b.BuildTargetIdentifier): Unit = {
val id = new b.TextDocumentIdentifier(path.toNIO.toUri.toASCIIString)
val params = new b.PublishDiagnosticsParams(
id,
targetId,
List.empty[b.Diagnostic].asJava,
true
)
actualBuildPublishDiagnostics(params)
}
def resetBuildExceptionDiagnostics(targetId: b.BuildTargetIdentifier): Unit =
for {
(key @ (path, elemTargetId), _) <- buildExceptionDiagnosticsDocs.asScala.toVector
if elemTargetId == targetId
} {
val removedValue = buildExceptionDiagnosticsDocs.remove(key)
if (removedValue != null) {
val id = new b.TextDocumentIdentifier(path.toNIO.toUri.toASCIIString)
val params = new b.PublishDiagnosticsParams(
id,
targetId,
List.empty[b.Diagnostic].asJava,
true
)
actualBuildPublishDiagnostics(params)
}
}
def reportBuildException(
targetIdOpt: Option[b.BuildTargetIdentifier],
ex: BuildException,
reset: Boolean = true
): Unit =
targetIdOpt match {
case None =>
logger.debug(s"Not reporting $ex to users (no build target id)")
case Some(targetId) =>
val touchedFiles = (ex match {
case c: CompositeBuildException =>
reportDiagnosticsForFiles(targetId, c.exceptions, reset = reset)
case _ => reportDiagnosticsForFiles(targetId, Seq(ex), reset = reset)
}).toSet
// Small chance of us wiping some Bloop diagnostics, if these happen
// between the call to remove and the call to actualBuildPublishDiagnostics.
for {
(key @ (path, elemTargetId), _) <- buildExceptionDiagnosticsDocs.asScala.toVector
if elemTargetId == targetId && !touchedFiles(path)
} {
val removedValue = buildExceptionDiagnosticsDocs.remove(key)
if (removedValue != null) {
val id = new b.TextDocumentIdentifier(path.toNIO.toUri.toASCIIString)
val params = new b.PublishDiagnosticsParams(
id,
targetId,
List.empty[b.Diagnostic].asJava,
true
)
actualBuildPublishDiagnostics(params)
}
}
}
def reportDiagnosticsForFiles(
targetId: b.BuildTargetIdentifier,
diags: Seq[Diagnostic],
reset: Boolean = true
): Seq[os.Path] =
if reset then // send diagnostic with reset only once for every file path
diags.flatMap { diag =>
diag.positions.map { position =>
Diagnostic(diag.message, diag.severity, Seq(position), diag.textEdit)
}
}
.groupBy(_.positions.headOption match
case Some(File(Right(path), _, _, _)) => Some(path)
case _ => None
)
.filter(_._1.isDefined)
.values
.toSeq
.flatMap {
case head :: tail =>
reportDiagnosticForFiles(targetId, reset = reset)(head)
++ tail.flatMap(reportDiagnosticForFiles(targetId))
case _ => Nil
}
else
diags.flatMap(reportDiagnosticForFiles(targetId))
private def reportDiagnosticForFiles(
targetId: b.BuildTargetIdentifier,
reset: Boolean = false
)(diag: Diagnostic): Seq[os.Path] =
diag.positions.flatMap {
case File(Right(path), (startLine, startC), (endL, endC), _) =>
val id = new b.TextDocumentIdentifier(path.toNIO.toUri.toASCIIString)
val startPos = new b.Position(startLine, startC)
val endPos = new b.Position(endL, endC)
val range = new b.Range(startPos, endPos)
val bDiag =
new b.Diagnostic(range, diag.message)
diag.textEdit.foreach { textEdit =>
val bScalaTextEdit = new ScalaTextEdit(range, textEdit.newText)
val bScalaWorkspaceEdit = new ScalaWorkspaceEdit(List(bScalaTextEdit).asJava)
val bAction = new ScalaAction(textEdit.title)
bAction.setEdit(bScalaWorkspaceEdit)
val bScalaDiagnostic = new ScalaDiagnostic
bScalaDiagnostic.setActions(List(bAction).asJava)
bDiag.setDataKind("scala")
bDiag.setData(new Gson().toJsonTree(bScalaDiagnostic))
}
bDiag.setSeverity(diag.severity.toBsp4j)
bDiag.setSource("scala-cli")
val params = new b.PublishDiagnosticsParams(
id,
targetId,
List(bDiag).asJava,
reset
)
buildExceptionDiagnosticsDocs.put((path, targetId), JBoolean.TRUE)
actualBuildPublishDiagnostics(params)
Seq(path)
case _ => Nil
}
}