/
RunTestCodeLens.scala
384 lines (355 loc) Β· 12.1 KB
/
RunTestCodeLens.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
package scala.meta.internal.metals.codelenses
import java.util.Collections.singletonList
import scala.concurrent.ExecutionContext
import scala.concurrent.Future
import scala.meta.internal.implementation.TextDocumentWithPath
import scala.meta.internal.metals.BaseCommand
import scala.meta.internal.metals.Buffers
import scala.meta.internal.metals.BuildTargets
import scala.meta.internal.metals.ClientCommands.StartDebugSession
import scala.meta.internal.metals.ClientCommands.StartRunSession
import scala.meta.internal.metals.ClientConfiguration
import scala.meta.internal.metals.JavaBinary
import scala.meta.internal.metals.JsonParser._
import scala.meta.internal.metals.MetalsEnrichments._
import scala.meta.internal.metals.TestUserInterfaceKind
import scala.meta.internal.metals.UserConfiguration
import scala.meta.internal.metals.debug.BuildTargetClasses
import scala.meta.internal.metals.debug.DebugProvider
import scala.meta.internal.metals.debug.ExtendedScalaMainClass
import scala.meta.internal.parsing.TokenEditDistance
import scala.meta.internal.parsing.Trees
import scala.meta.internal.semanticdb.MethodSignature
import scala.meta.internal.semanticdb.Scope
import scala.meta.internal.semanticdb.Signature
import scala.meta.internal.semanticdb.SymbolOccurrence
import scala.meta.internal.semanticdb.TextDocument
import scala.meta.internal.semanticdb.TypeRef
import scala.meta.internal.semanticdb.ValueSignature
import scala.meta.io.AbsolutePath
import ch.epfl.scala.bsp4j.BuildTargetIdentifier
import ch.epfl.scala.{bsp4j => b}
import com.google.gson.JsonElement
import org.eclipse.{lsp4j => l}
/**
* Class to generate the Run and Test code lenses to trigger debugging.
*
* NOTE: (ckipp01) the isBloopOrSbt param is really only checking to
* see if the build server connection is bloop or sbt, which support debugging.
* Despite the fact, that canDebug capability is already a part of the BSP spec,
* bloop and sbt doesn't support this option, so we have to add additional if
* in order to generate lenses for them.
*/
final class RunTestCodeLens(
buildTargetClasses: BuildTargetClasses,
buffers: Buffers,
buildTargets: BuildTargets,
clientConfig: ClientConfiguration,
userConfig: () => UserConfiguration,
trees: Trees,
workspace: AbsolutePath,
)(implicit val ec: ExecutionContext)
extends CodeLens {
override def isEnabled: Boolean =
clientConfig.isDebuggingProvider() || clientConfig.isRunProvider()
override def codeLenses(
textDocumentWithPath: TextDocumentWithPath
): Future[Seq[l.CodeLens]] = {
/**
* Jvm environment needs to be requested lazily.
* This requests and caches it for later use, otherwise we
* would need to forward Future across different methods
* which would make things way too complex.
*/
def requestJvmEnvironment(
buildTargetId: BuildTargetIdentifier,
isJvm: Boolean,
): Future[Unit] = {
if (isJvm)
buildTargetClasses.jvmRunEnvironment(buildTargetId).map(_ => ())
else
Future.unit
}
val textDocument = textDocumentWithPath.textDocument
val path = textDocumentWithPath.filePath
val distance = buffers.tokenEditDistance(path, textDocument.text, trees)
val lenses = for {
buildTargetId <- buildTargets.inverseSources(path)
buildTarget <- buildTargets.info(buildTargetId)
isJVM = buildTarget.asScalaBuildTarget.forall(
_.getPlatform == b.ScalaPlatform.JVM
)
connection <- buildTargets.buildServerOf(buildTargetId)
// although hasDebug is already available in BSP capabilities
// see https://github.com/build-server-protocol/build-server-protocol/pull/161
// most of the bsp servers such as bloop and sbt might not support it.
} yield requestJvmEnvironment(buildTargetId, isJVM).map { _ =>
val classes = buildTargetClasses.classesOf(buildTargetId)
// sbt doesn't declare debugging provider
def buildServerCanDebug =
connection.isDebuggingProvider || connection.isSbt
if (connection.isScalaCLI && path.isAmmoniteScript) {
scalaCliCodeLenses(
textDocument,
buildTargetId,
classes,
distance,
buildServerCanDebug,
isJVM,
)
} else if (buildServerCanDebug || clientConfig.isRunProvider()) {
codeLenses(
textDocument,
buildTargetId,
classes,
distance,
path,
buildServerCanDebug,
isJVM,
)
} else { Nil }
}
lenses.getOrElse(Future.successful(Nil))
}
/**
* Java main method: public static void main(String[] args)
*/
private def isMainMethod(signature: Signature, textDocument: TextDocument) = {
signature match {
case MethodSignature(_, Seq(Scope(Seq(param), _)), returnType) =>
def isVoid = returnType match {
case TypeRef(_, symbol, _) => symbol == "scala/Unit#"
case _ => false
}
def isStringArray(sym: String) = {
textDocument.symbols.find(
_.symbol == sym
) match {
case Some(info) =>
info.signature match {
case ValueSignature(
TypeRef(
_,
"scala/Array#",
Vector(TypeRef(_, "java/lang/String#", _)),
)
) =>
true
case _ => false
}
case None => false
}
}
isVoid && isStringArray(param)
case _ => false
}
}
private def javaLenses(
occurence: SymbolOccurrence,
textDocument: TextDocument,
target: BuildTargetIdentifier,
buildServerCanDebug: Boolean,
): Seq[l.Command] = {
if (occurence.symbol.endsWith("#main().")) {
textDocument.symbols
.find(_.symbol == occurence.symbol)
.toSeq
.flatMap { a =>
val isMain =
a.isPublic && a.isStatic && isMainMethod(a.signature, textDocument)
if (isMain)
mainCommand(
target,
new b.ScalaMainClass(
occurence.symbol.stripSuffix("#main().").replace("/", "."),
Nil.asJava,
Nil.asJava,
),
buildServerCanDebug,
isJVM = true,
)
else
Nil
}
} else {
Nil
}
}
private def codeLenses(
textDocument: TextDocument,
target: BuildTargetIdentifier,
classes: BuildTargetClasses.Classes,
distance: TokenEditDistance,
path: AbsolutePath,
buildServerCanDebug: Boolean,
isJVM: Boolean,
): Seq[l.CodeLens] = {
for {
occurrence <- textDocument.occurrences
if occurrence.role.isDefinition || occurrence.symbol == "scala/main#"
symbol = occurrence.symbol
commands = {
val main = classes.mainClasses
.get(symbol)
.map(mainCommand(target, _, buildServerCanDebug, isJVM))
.getOrElse(Nil)
val tests =
// Currently tests can only be run via DAP
if (clientConfig.isDebuggingProvider() && buildServerCanDebug)
testClasses(target, classes, symbol, isJVM)
else Nil
val fromAnnot = DebugProvider
.mainFromAnnotation(occurrence, textDocument)
.flatMap { symbol =>
classes.mainClasses
.get(symbol)
.map(mainCommand(target, _, buildServerCanDebug, isJVM))
}
.getOrElse(Nil)
val javaMains =
if (path.isJava)
javaLenses(occurrence, textDocument, target, buildServerCanDebug)
else Nil
main ++ tests ++ fromAnnot ++ javaMains
}
if commands.nonEmpty
range <- occurrenceRange(occurrence, distance).toList
command <- commands
} yield new l.CodeLens(range, command, null)
}
private def occurrenceRange(
occurrence: SymbolOccurrence,
distance: TokenEditDistance,
): Option[l.Range] =
occurrence.range
.flatMap(r => distance.toRevisedStrict(r).map(_.toLsp))
private def scalaCliCodeLenses(
textDocument: TextDocument,
target: BuildTargetIdentifier,
classes: BuildTargetClasses.Classes,
distance: TokenEditDistance,
buildServerCanDebug: Boolean,
isJVM: Boolean,
): Seq[l.CodeLens] = {
val scriptFileName = textDocument.uri.stripSuffix(".sc")
val expectedMainClass =
if (scriptFileName.contains('/')) s"${scriptFileName}_sc."
else s"_empty_/${scriptFileName}_sc."
val main =
classes.mainClasses
.get(expectedMainClass)
.map(mainCommand(target, _, buildServerCanDebug, isJVM))
.getOrElse(Nil)
val fromAnnotations = textDocument.occurrences.flatMap { occ =>
for {
sym <- DebugProvider.mainFromAnnotation(occ, textDocument)
cls <- classes.mainClasses.get(sym)
range <- occurrenceRange(occ, distance)
} yield mainCommand(target, cls, buildServerCanDebug, isJVM).map { cmd =>
new l.CodeLens(range, cmd, null)
}
}.flatten
fromAnnotations ++ main.map(command =>
new l.CodeLens(
new l.Range(new l.Position(0, 0), new l.Position(0, 2)),
command,
null,
)
)
}
/**
* Do not return test code lenses if user declared test explorer as a test interface.
*/
private def testClasses(
target: BuildTargetIdentifier,
classes: BuildTargetClasses.Classes,
symbol: String,
isJVM: Boolean,
): List[l.Command] =
if (userConfig().testUserInterface == TestUserInterfaceKind.CodeLenses)
classes.testClasses
.get(symbol)
.toList
.flatMap(symbolInfo =>
testCommand(target, symbolInfo.fullyQualifiedName, isJVM)
)
else
Nil
private def testCommand(
target: b.BuildTargetIdentifier,
className: String,
isJVM: Boolean,
): List[l.Command] = {
val params = {
val dataKind = b.TestParamsDataKind.SCALA_TEST_SUITES
val data = singletonList(className).toJson
sessionParams(target, dataKind, data)
}
if (isJVM)
List(
command("test", StartRunSession, params),
command("debug test", StartDebugSession, params),
)
else
List(
command("test", StartRunSession, params)
)
}
private def mainCommand(
target: b.BuildTargetIdentifier,
main: b.ScalaMainClass,
buildServerCanDebug: Boolean,
isJVM: Boolean,
): List[l.Command] = {
val javaBinary = buildTargets
.scalaTarget(target)
.flatMap(scalaTarget =>
JavaBinary.javaBinaryFromPath(scalaTarget.jvmHome)
)
.orElse(userConfig().usedJavaBinary)
val (data, shellCommandAdded) =
if (!isJVM) (main.toJson, false)
else
buildTargetClasses
.jvmRunEnvironmentSync(target)
.zip(javaBinary) match {
case None =>
(main.toJson, false)
case Some((env, javaBinary)) =>
(
ExtendedScalaMainClass(main, env, javaBinary, workspace).toJson,
true,
)
}
val params = {
val dataKind = b.DebugSessionParamsDataKind.SCALA_MAIN_CLASS
sessionParams(target, dataKind, data)
}
if (clientConfig.isDebuggingProvider() && buildServerCanDebug && isJVM)
List(
command("run", StartRunSession, params),
command("debug", StartDebugSession, params),
)
// run provider needs shell command to run currently, we don't support pure run inside metals for JVM
else if (shellCommandAdded && clientConfig.isRunProvider() || !isJVM)
List(command("run", StartRunSession, params))
else Nil
}
private def sessionParams(
target: b.BuildTargetIdentifier,
dataKind: String,
data: JsonElement,
): b.DebugSessionParams = {
val params = new b.DebugSessionParams(List(target).asJava)
params.setDataKind(dataKind)
params.setData(data)
params
}
private def command(
name: String,
command: BaseCommand,
params: b.DebugSessionParams,
): l.Command = {
new l.Command(name, command.id, singletonList(params))
}
}