-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathInstrumentCoverage.scala
More file actions
891 lines (777 loc) · 38.2 KB
/
InstrumentCoverage.scala
File metadata and controls
891 lines (777 loc) · 38.2 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
package dotty.tools.dotc
package transform
import java.io.File
import java.nio.file.{Files, Path}
import ast.tpd
import ast.tpd.*
import collection.mutable
import core.Comments.Comment
import core.Flags.*
import core.Contexts.{Context, ctx, inContext}
import core.DenotTransformers.IdentityDenotTransformer
import core.Symbols.{defn, Symbol}
import core.Constants.Constant
import core.NameKinds.DefaultGetterName
import core.NameOps.isContextFunction
import core.StdNames.nme
import core.Types.*
import core.Decorators.*
import coverage.*
import typer.LiftImpure
import util.{Property, SourcePosition, SourceFile}
import util.Spans.Span
import localopt.StringInterpolatorOpt
import inlines.Inlines
import scala.util.matching.Regex
import java.util.regex.Pattern
/** Lift impure + lift the prefixes for coverage instrumentation. */
object LiftCoverage extends LiftImpure:
// Property indicating whether we're currently lifting the arguments of an application
private val LiftingArgs = new Property.Key[Boolean]
val CoverageLiftedTemp = Property.StickyKey[Unit]()
private inline def liftingArgs(using Context): Boolean =
ctx.property(LiftingArgs).contains(true)
private def liftingArgsContext(using Context): Context =
ctx.fresh.setProperty(LiftingArgs, true)
/** Variant of `noLift` for the arguments of applications.
* To produce the right coverage information (especially in case of exceptions), we must lift:
* - all the applications, except the erased ones
*/
private def noLiftArg(arg: tpd.Tree)(using Context): Boolean =
arg match
case arg if isUnsafeAssumeSeparate(arg) => true
case a: tpd.Apply => a.symbol.is(Erased) // don't lift erased applications, but lift all others
case tpd.Block((meth: tpd.DefDef) :: Nil, closure: tpd.Closure)
if meth.symbol == closure.meth.symbol && closure.env.forall(noLiftArg) => true
case tpd.Block(stats, expr) => stats.forall(noLiftArg) && noLiftArg(expr)
case tpd.Inlined(_, bindings, expr) => noLiftArg(expr)
case tpd.Typed(expr, _) => noLiftArg(expr)
case _ => super.noLift(arg)
def isUnsafeAssumeSeparate(tree: tpd.Tree)(using Context): Boolean = tree match
case tree: tpd.Apply =>
tree.symbol == defn.Caps_unsafeAssumeSeparate
|| isUnsafeAssumeSeparate(tree.fun)
case tpd.Select(qual, _) => isUnsafeAssumeSeparate(qual)
case tpd.Block(_, expr) => isUnsafeAssumeSeparate(expr)
case tpd.Inlined(_, _, expr) => isUnsafeAssumeSeparate(expr)
case tpd.Typed(expr, _) => isUnsafeAssumeSeparate(expr)
case _ => false
def isCoverageLiftedTemp(sym: Symbol)(using Context): Boolean =
sym.defTree.hasAttachment(CoverageLiftedTemp)
override protected def onLiftedDef(tree: tpd.Tree)(using Context): Unit =
tree.putAttachment(CoverageLiftedTemp, ())
override def noLift(expr: tpd.Tree)(using Context) =
if liftingArgs then noLiftArg(expr)
else isUnsafeAssumeSeparate(expr) || super.noLift(expr)
/** Preserve precision for lifted coverage temps when widening would break later checks:
* compile-time constants and stable singleton types need their singleton precision,
* and capture-converted types need their local TypeBox#CAP references.
*/
override protected def liftedExprType(expr: tpd.Tree)(using Context): Type =
val dealiased = expr.tpe.dealias
val deskolemized = dealiased.deskolemized
val valueType = dealiased match
case ref: TermRef if ref.prefix.exists && ref.underlying.isInstanceOf[ExprType] =>
ref.prefix.memberInfo(ref.symbol).widenExpr
case _ =>
dealiased
valueType.widenTermRefExpr.normalized.simplified match
case _: ConstantType => deskolemized
case _ if dealiased.isInstanceOf[SingletonType] && dealiased.isStable => dealiased
case _ if valueType.existsPart(_.typeSymbol == defn.TypeBox_CAP) => valueType
case _ => super.liftedExprType(expr)
def liftForCoverage(defs: mutable.ListBuffer[tpd.Tree], tree: tpd.Apply)(using Context) =
val liftedFun = liftApp(defs, tree.fun)
val liftedArgs = liftArgs(defs, tree.fun.tpe, tree.args)(using liftingArgsContext)
tpd.cpy.Apply(tree)(liftedFun, liftedArgs)
/** Implements code coverage by inserting calls to scala.runtime.coverage.Invoker
* ("instruments" the source code).
* The result can then be consumed by the Scoverage tool.
*/
class InstrumentCoverage extends MacroTransform with IdentityDenotTransformer:
import InstrumentCoverage.{InstrumentedParts, ExcludeMethodFlags}
override def phaseName = InstrumentCoverage.name
override def description = InstrumentCoverage.description
// Enabled by argument "-coverage-out OUTPUT_DIR"
override def isEnabled(using ctx: Context) =
ctx.settings.coverageOutputDir.value.nonEmpty
private var coverageExcludeClasslikePatterns: List[Pattern] = Nil
private var coverageExcludeFilePatterns: List[Pattern] = Nil
private val coverageLocalExclusions: mutable.Map[String, List[Span]] = mutable.Map.empty
override def runOn(units: List[CompilationUnit])(using ctx: Context): List[CompilationUnit] =
val outputPath = ctx.settings.coverageOutputDir.value
// Ensure the dir exists (once per batch, not per unit)
val dataDir = File(outputPath)
val newlyCreated = dataDir.mkdirs()
if !newlyCreated then
// If the directory existed before, clean measurement files.
val files = dataDir.listFiles
if files != null then
files
.filter(_.getName.startsWith("scoverage.measurements."))
.foreach(_.delete())
end if
// Deserialize previous coverage once at the start
val coverageFilePath = Serializer.coverageFilePath(outputPath)
val previousCoverage =
if Files.exists(coverageFilePath) then
Serializer.deserialize(coverageFilePath, ctx.settings.sourceroot.value)
else Coverage()
// Initialize coverage patterns once
coverageExcludeClasslikePatterns = ctx.settings.coverageExcludeClasslikes.value.map(_.r.pattern)
coverageExcludeFilePatterns = ctx.settings.coverageExcludeFiles.value.map(_.r.pattern)
// Initialize coverage object
ctx.base.coverage = Coverage()
ctx.base.coverage.nn.setNextStatementId(previousCoverage.nextStatementId())
// Process each unit to extract local coverage exclusions from comments
units.foreach { unit =>
val excludedSpans = mutable.ListBuffer[Span]()
var currentStartingComment: Option[Comment] = None
unit.comments.foreach {
case comment if InstrumentCoverage.scoverageLocalOff.matches(comment.raw) && currentStartingComment.isEmpty =>
currentStartingComment = Some(comment)
case comment if InstrumentCoverage.scoverageLocalOn.matches(comment.raw) =>
currentStartingComment.foreach { start =>
currentStartingComment = None
excludedSpans += start.span.withEnd(comment.span.end)
}
case _ =>
}
currentStartingComment.headOption.foreach { start =>
excludedSpans += start.span.withEnd(unit.source.length - 1)
}
if excludedSpans.nonEmpty then
coverageLocalExclusions(unit.source.file.path) = excludedSpans.toList
}
// Run the transformation on all units
val result = super.runOn(units)
// Serialize once at the end with merged coverage
val mergedCoverage = Coverage()
val currentFiles = units.map(_.source.file.absolute.jpath)
// Add statements from previous coverage that aren't from recompiled files
// and whose source files still exist
previousCoverage.statements
.filterNot(stmt =>
val source = stmt.location.sourcePath
currentFiles.contains(source) || !Files.exists(source)
)
.foreach(mergedCoverage.addStatement)
// Add all new statements from this compilation
ctx.base.coverage.nn.statements.foreach(mergedCoverage.addStatement)
Serializer.serialize(mergedCoverage, outputPath, ctx.settings.sourceroot.value)
result
private def treeSize(tree: Tree)(using Context): Int =
var count = 0
tree.foreachSubTree(_ => count += 1)
count
private def isClassIncluded(sym: Symbol)(using Context): Boolean =
val fqn = sym.fullName.toText(ctx.printerFn(ctx)).show
coverageExcludeClasslikePatterns.isEmpty || !coverageExcludeClasslikePatterns.exists(
_.matcher(fqn).matches
)
private def isFileIncluded(file: SourceFile)(using Context): Boolean =
val normalizedPath = file.path.replace(".scala", "")
coverageExcludeFilePatterns.isEmpty || !coverageExcludeFilePatterns.exists(
_.matcher(normalizedPath).matches
)
private def isTreeExcluded(tree: Tree)(using Context): Boolean =
val sourceFile = ctx.source.file.path
coverageLocalExclusions.get(sourceFile).exists: excludedSpans =>
excludedSpans.exists(_.contains(tree.span))
override protected def newTransformer(using Context) =
CoverageTransformer(ctx.settings.coverageOutputDir.value)
/** Transforms trees to insert calls to Invoker.invoked to compute the coverage when the code is called */
private class CoverageTransformer(outputPath: String) extends Transformer:
private val ConstOutputPath = Constant(outputPath)
private def warnSkippedLargeTreeCoverage(tree: MemberDef, subject: String, nodeCount: Int)(using Context): Unit =
report.warning(
s"Skipping coverage instrumentation for large $subject ($nodeCount tree nodes exceeds threshold ${InstrumentCoverage.MaxInstrumentableTreeNodes}); compilation will continue but no coverage data will be recorded for it.",
tree.srcPos
)
/** Generates the tree for:
* ```
* Invoker.invoked(id, DIR)
* ```
* where DIR is the _outputPath_ defined by the coverage settings.
*/
private def invokeCall(id: Int, span: Span)(using Context): Apply =
ref(defn.InvokedMethodRef).withSpan(span)
.appliedToArgs(
Literal(Constant(id)) :: Literal(ConstOutputPath) :: Nil
).withSpan(span)
.asInstanceOf[Apply]
/**
* Records information about a new coverable statement. Generates a unique id for it.
*
* @param tree the tree to add to the coverage report
* @param pos the position to save in the report
* @param branch true if it's a branch (branches are considered differently by most coverage analysis tools)
* @param ctx the current context
* @return the statement's id
*/
private def recordStatement(tree: Tree, pos: SourcePosition, branch: Boolean)(using ctx: Context): Int =
val id = ctx.base.coverage.nn.nextStatementId()
val sourceFile = pos.source
val statement = Statement(
location = Location(tree, sourceFile),
id = id,
start = pos.start,
end = pos.end,
// +1 to account for the line number starting at 1
// the internal line number is 0-base https://github.com/scala/scala3/blob/18ada516a85532524a39a962b2ddecb243c65376/compiler/src/dotty/tools/dotc/util/SourceFile.scala#L173-L176
line = pos.line + 1,
desc = sourceFile.content.slice(pos.start, pos.end).mkString,
symbolName = tree.symbol.name.toSimpleName.show,
treeName = tree.getClass.getSimpleName,
branch,
ignored = isTreeExcluded(tree)
)
ctx.base.coverage.nn.addStatement(statement)
id
/**
* Adds a new statement to the current `Coverage` and creates a corresponding call
* to `Invoker.invoke` with its id, and the given position.
*
* Note that the entire tree won't be saved in the coverage analysis, only some
* data related to the tree is recorded (e.g. its type, its parent class, ...).
*
* @param tree the tree to add to the coverage report
* @param pos the position to save in the report
* @param branch true if it's a branch
* @return the tree corresponding to the call to `Invoker.invoke`
*/
private def createInvokeCall(tree: Tree, pos: SourcePosition, branch: Boolean = false)(using Context): Apply =
val statementId = recordStatement(tree, pos, branch)
val span = pos.span.toSynthetic
invokeCall(statementId, span)
private def erasedParamStatuses(app: Apply)(using Context): List[Boolean] =
app.fun.tpe.widen match
case mt: MethodType if mt.hasErasedParams => mt.paramErasureStatuses
case _ => Nil
private def transformApplyArgs(trees: List[Tree], erasedArgs: List[Boolean] = Nil)(using Context): List[Tree] =
if allConstArgs(trees) then trees
else if erasedArgs.isEmpty then transform(trees)
else trees.lazyZip(erasedArgs).map { (arg, isErased) =>
if isErased then arg else transform(arg)
}.toList
private def transformInnerApply(tree: Tree)(using Context): Tree = tree match
case a: Apply if a.fun.symbol == defn.StringContextModule_apply =>
a
case a: Apply =>
cpy.Apply(a)(
transformInnerApply(a.fun),
transformApplyArgs(a.args, erasedParamStatuses(a))
)
case a: TypeApply =>
cpy.TypeApply(a)(
transformInnerApply(a.fun),
transformApplyArgs(a.args)
)
case s: Select =>
cpy.Select(s)(transformInnerApply(s.qualifier), s.name)
case i: (Ident | This) => i
case t: Typed =>
cpy.Typed(t)(transformInnerApply(t.expr), t.tpt)
case other => transform(other)
private def allConstArgs(args: List[Tree]) =
args.forall(arg => arg.isInstanceOf[Literal] || arg.isInstanceOf[Ident])
/**
* Tries to instrument an `Apply`.
* These "tryInstrument" methods are useful to tweak the generation of coverage instrumentation,
* in particular in `case TypeApply` in the [[transform]] method.
*
* @param tree the tree to instrument
* @return instrumentation result, with the preparation statement, coverage call and tree separated
*/
private def tryInstrument(tree: Apply)(using Context): InstrumentedParts =
if LiftCoverage.isUnsafeAssumeSeparate(tree) then
val transformed = cpy.Apply(tree)(transformInnerApply(tree.fun), transformApplyArgs(tree.args, erasedParamStatuses(tree)))
InstrumentedParts.notCovered(transformed)
else if canInstrumentApply(tree) then
// Create a call to Invoker.invoked(coverageDirectory, newStatementId)
val coverageCall = createInvokeCall(tree, tree.sourcePos)
// Transform args and fun, i.e. instrument them if needed (and if possible)
val app =
if tree.fun.symbol eq defn.throwMethod then tree
else cpy.Apply(tree)(transformInnerApply(tree.fun), transformApplyArgs(tree.args, erasedParamStatuses(tree)))
if needsLift(tree) then
// Lifts the arguments. Note that if only one argument needs to be lifted, we lift them all.
// Also, tree.fun can be lifted too.
// See LiftCoverage for the internal working of this lifting.
val liftedDefs = mutable.ListBuffer[Tree]()
val liftedApp = LiftCoverage.liftForCoverage(liftedDefs, app)
InstrumentedParts(liftedDefs.toList, coverageCall, liftedApp)
else
// Instrument without lifting
InstrumentedParts.singleExpr(coverageCall, app)
else
// Transform recursively but don't instrument the tree itself
val transformed = cpy.Apply(tree)(transformInnerApply(tree.fun), transformApplyArgs(tree.args, erasedParamStatuses(tree)))
InstrumentedParts.notCovered(transformed)
private def tryInstrument(tree: Ident)(using Context): InstrumentedParts =
val sym = tree.symbol
if canInstrumentParameterless(sym) then
// call to a local parameterless method f
val coverageCall = createInvokeCall(tree, tree.sourcePos)
InstrumentedParts.singleExpr(coverageCall, tree)
else
InstrumentedParts.notCovered(tree)
private def tryInstrument(tree: Literal)(using Context): InstrumentedParts =
val coverageCall = createInvokeCall(tree, tree.sourcePos)
InstrumentedParts.singleExpr(coverageCall, tree)
private def tryInstrument(tree: Select)(using Context): InstrumentedParts =
val sym = tree.symbol
val transformedQual = transform(tree.qualifier)
val qual =
if tree.qualifier.symbol.exists && canInstrumentParameterless(tree.qualifier.symbol) then
transformedQual
else
transformedQual.ensureConforms(tree.qualifier.tpe)
val transformed = cpy.Select(tree)(qual, tree.name)
if canInstrumentParameterless(sym) then
// call to a parameterless method
val coverageCall = createInvokeCall(tree, tree.sourcePos)
InstrumentedParts.singleExpr(coverageCall, transformed)
else
InstrumentedParts.notCovered(transformed)
/** Generic tryInstrument */
private def tryInstrument(tree: Tree)(using Context): InstrumentedParts =
tree match
case t: Apply => tryInstrument(t)
case t: Ident => tryInstrument(t)
case t: Literal => tryInstrument(t)
case t: Select => tryInstrument(t)
case _ => InstrumentedParts.notCovered(transform(tree))
/**
* Transforms and instruments a branch if it's non-empty.
* If the tree is empty, return itself and don't instrument.
*/
private def transformBranch(tree: Tree)(using Context): Tree =
transformBranchWithInherited(tree, inheritedProbes = Nil)
/** Like [[transformBranch]], but runs `inheritedProbes` before the branch probe
* and the transformed body. Used for sub-cases: ancestor case-arm probes are
* emitted at the same successful leaves; see [[instrumentSubMatchWithProbes]].
*/
private def transformBranchWithInherited(tree: Tree, inheritedProbes: List[Apply])(using Context): Tree =
if tree.isEmpty then
// - If t.isEmpty then `transform(t) == t` always hold,
// so we can avoid calling transform in that case.
tree
else
val transformed = transform(tree)
val coverageCall = createInvokeCall(tree, tree.sourcePos, branch = true)
val allProbes = inheritedProbes :+ coverageCall
allProbes match
case single :: Nil => InstrumentedParts.singleExprTree(single, transformed)
case multiple => InstrumentCoverage.blockWithExprSpan(multiple, transformed)
private def transformCondition(tree: Tree)(using Context): Tree = tree match
case Literal(Constant(_: Boolean)) => tree
case _ => transform(tree)
override def transform(tree: Tree)(using Context): Tree =
inContext(transformCtx(tree)) { // necessary to position inlined code properly
tree match
// simple cases
case tree: (Import | Export | This | Super | New) => tree
case tree if tree.isEmpty || tree.isType => tree // empty Thicket, Ident (referring to a type), TypeTree, ...
case tree if !tree.span.exists || tree.span.isZeroExtent => tree // no meaningful position
case tree: ValDef if !tree.rhs.isEmpty && treeSize(tree.rhs) > InstrumentCoverage.MaxInstrumentableTreeNodes =>
warnSkippedLargeTreeCoverage(tree, s"value initializer `${tree.name.show}`", treeSize(tree.rhs))
tree
case tree: Literal =>
val rest = tryInstrument(tree).toTree
rest
// identifier
case tree: Ident =>
tryInstrument(tree).toTree
// branches
case tree: If =>
cpy.If(tree)(
cond = transformCondition(tree.cond),
thenp = transformBranch(tree.thenp),
elsep = transformBranch(tree.elsep)
)
case tree: Try =>
cpy.Try(tree)(
expr = transformBranch(tree.expr),
cases = tree.cases.map(transformCaseDef),
finalizer = transformBranch(tree.finalizer)
)
// f(args)
case tree: Apply =>
tryInstrument(tree).toTree
// (fun)[args]
case TypeApply(fun, args) =>
// Here is where `InstrumentedParts` becomes useful!
// We extract its components and act carefully.
val InstrumentedParts(pre, coverageCall, expr) = tryInstrument(fun)
if coverageCall.isEmpty then
// `fun` cannot be instrumented and `args` is a type, but `expr` may have been transformed
cpy.TypeApply(tree)(expr, args)
else
// expr[T] shouldn't be transformed to:
// {invoked(...), expr}[T]
//
// but to:
// {invoked(...), expr[T]}
//
// This is especially important for trees like (expr[T])(args),
// for which the wrong transformation crashes the compiler.
// See tests/coverage/pos/PolymorphicExtensions.scala
InstrumentCoverage.blockWithExprSpan(
pre :+ coverageCall,
cpy.TypeApply(tree)(expr, args)
)
// a.b
case tree: Select =>
tryInstrument(tree).toTree
case tree: CaseDef =>
transformCaseDef(tree)
case tree: ValDef if tree.symbol.is(Inline) =>
tree // transforming inline vals will result in `inline value must be pure` errors
case tree: ValDef =>
val rhs = if tree.symbol.isEffectivelyErased then tree.rhs else transform(tree.rhs)
cpy.ValDef(tree)(rhs = rhs)
case tree: DefDef =>
transformDefDef(tree)
case tree: PackageDef =>
if isFileIncluded(tree.srcPos.sourcePos.source) && isClassIncluded(tree.symbol) then
// Use transformStats (not transform) to process statements with updated context.
// This ensures language imports like `scala.language.unsafeNulls` are properly
// processed for subsequent statements in the package.
cpy.PackageDef(tree)(tree.pid, transformStats(tree.stats, tree.symbol))
else
tree
case tree: TypeDef =>
if isFileIncluded(tree.srcPos.sourcePos.source) && isClassIncluded(tree.symbol) then
super.transform(tree)
else
tree
case tree: Assign =>
if tree.lhs.symbol.is(Erased) then tree
else
// only transform the rhs
cpy.Assign(tree)(tree.lhs, transform(tree.rhs))
case tree: Return =>
// only transform the expr, because `from` is a "pointer"
// to the enclosing method, not a tree to instrument.
cpy.Return(tree)(expr = transform(tree.expr), from = tree.from)
case tree: Template =>
// only transform:
// - the arguments of the `Apply` trees in the parents
// - the template body
cpy.Template(tree)(
transformSub(tree.constr),
transformTemplateParents(tree.parents)(using ctx.superCallContext),
tree.derived,
tree.self,
transformStats(tree.body, tree.symbol)
)
case tree: Inlined =>
// Inlined code contents might come from another file (or project),
// which means that we cannot clearly designate which part of the inlined code
// was run using the API we are given.
// At best, we can show that the Inlined tree itself was reached.
// Additionally, Scala 2's coverage ignores macro calls entirely,
// so let's do that here too, also for regular inlined calls.
tree
// For everything else just recurse and transform
case _ =>
super.transform(tree)
}
/** Transforms a `def lhs = rhs` and instruments its body (rhs).
*
* The rhs is always transformed recursively.
*
* If possible, a coverage call is inserted at the beginning of the body
* (never outside of the DefDef tree). Therefore, this method always returns a `DefDef`.
* Thanks to this, it doesn't need to be wrapped in an`InstrumentedParts`.
*/
private def transformDefDef(tree: DefDef)(using Context): DefDef =
val sym = tree.symbol
if sym.isOneOf(Inline | Erased) then
// Inline and erased definitions will not be in the generated code and therefore do not need to be instrumented.
// (Note that a retained inline method will have a `$retained` variant that will be instrumented.)
tree
else if !tree.rhs.isEmpty && treeSize(tree.rhs) > InstrumentCoverage.MaxInstrumentableTreeNodes then
warnSkippedLargeTreeCoverage(tree, s"method body `${tree.name.show}`", treeSize(tree.rhs))
tree
else
// Only transform the params (for the default values) and the rhs, not the name and tpt.
val transformedParamss = transformParamss(tree.paramss)
val transformedRhs =
if tree.rhs.isEmpty then
tree.rhs
else if sym.isClassConstructor then
instrumentSecondaryCtor(tree)
else if !sym.isOneOf(Accessor | Artifact | Synthetic)
&& !LiftCoverage.isUnsafeAssumeSeparate(tree.rhs)
then
// If the body can be instrumented, do it (i.e. insert a "coverage call" at the beginning)
// This is useful because methods can be stored and called later, or called by reflection,
// and if the rhs is too simple to be instrumented (like `def f = this`),
// the method won't show up as covered if we don't insert a call at its beginning.
instrumentBody(tree, transform(tree.rhs))
else
transform(tree.rhs)
cpy.DefDef(tree)(tree.name, transformedParamss, tree.tpt, transformedRhs)
/** Span for coverage UI: end at the guard if present, else the pattern. */
private def caseDefUserEndPos(cdef: CaseDef)(using Context): SourcePosition =
val pat = cdef.pat
val guard = cdef.guard
val friendlyEnd = if guard.span.exists then guard.span.end else pat.span.end
cdef.sourcePos(using ctx).withSpan(cdef.span.withEnd(friendlyEnd))
/** Re-instrument a [[SubMatch]] while keeping it a direct sub-match tree.
* Downstream, [[dotty.tools.dotc.transform.PatternMatcher]] matches on
* `CaseDef.body: SubMatch` and [[CaseDef.maybePartial]] checks `isInstanceOf[SubMatch]`;
* wrapping the body in a [[Block]] (as in [[transformBranch]]) would break that.
*
* Branch coverage for each case arm is recorded by `inheritedProbes` plus, for each
* sub-case, a probe for that arm; we attach those probes to successful sub-match leaves
* so they do not run when a partial sub-match falls through to the next outer case.
*/
private def instrumentSubMatchWithProbes(sm: SubMatch, inheritedProbes: List[Apply])(using Context): SubMatch =
val newSelector = transform(sm.selector)
val newCases = sm.cases.map(cdef => transformSubMatchCaseDef(cdef, inheritedProbes))
cpy.Match(sm)(newSelector, newCases).asInstanceOf[SubMatch]
private def transformSubMatchCaseDef(cdef: CaseDef, inheritedProbes: List[Apply])(using Context): CaseDef =
val pos = caseDefUserEndPos(cdef)
val transformedGuard = transform(cdef.guard)
val newBody: Tree = cdef.body match
case sm: SubMatch =>
val p = createInvokeCall(sm, pos, branch = true)
instrumentSubMatchWithProbes(sm, p :: inheritedProbes)
case b =>
transformBranchWithInherited(b, inheritedProbes)
cpy.CaseDef(cdef)(cdef.pat, transformedGuard, newBody)
/** Transforms a `case ...` and instruments the parts that can be. */
private def transformCaseDef(tree: CaseDef)(using Context): CaseDef =
val pat = tree.pat
val guard = tree.guard
val pos = caseDefUserEndPos(tree)
// recursively transform the guard, but keep the pat
val transformedGuard = transform(guard)
// Sub-case bodies are [[SubMatch]]: keep that shape; see [[instrumentSubMatchWithProbes]].
val instrumentedBody: Tree = tree.body match
case sm: SubMatch =>
val p = createInvokeCall(sm, pos, branch = true)
instrumentSubMatchWithProbes(sm, p :: Nil)
case b =>
transformBranch(b)
cpy.CaseDef(tree)(pat, transformedGuard, instrumentedBody)
/** Transforms the parents of a Template. */
private def transformTemplateParents(parents: List[Tree])(using Context): List[Tree] =
def transformParent(parent: Tree): Tree = parent match
case tree: Apply =>
cpy.Apply(tree)(tree.fun, transformApplyArgs(tree.args, erasedParamStatuses(tree)))
case tree: TypeApply =>
// args are types, instrument the fun with transformParent
cpy.TypeApply(tree)(transformParent(tree.fun), tree.args)
case other =>
// should always be a TypeTree, nothing to instrument
other
parents.mapConserve(transformParent)
/** Instruments the body of a DefDef. Handles corner cases.
* Given a DefDef f like this:
* ```
* def f(params) = rhs
* ```
*
* It generally inserts a "coverage call" before rhs:
* ```
* def f(params) =
* Invoker.invoked(id, DIR)
* rhs
* ```
*
* But in some cases (e.g. closures), this would be invalid (see the comment below),
* and the call is inserted at another place.
*/
private def instrumentBody(parent: DefDef, body: Tree)(using Context): Tree =
/* recurse on closures, so that we insert the call at the leaf:
def g: (a: Ta) ?=> (b: Tb) = {
// nothing here <-- not here!
def $anonfun(using a: Ta) =
Invoked.invoked(id, DIR) <-- here
<userCode>
closure($anonfun)
}
*/
body match
case b @ Block((meth: DefDef) :: Nil, closure: Closure)
if meth.symbol == closure.meth.symbol && defn.isContextFunctionType(body.tpe) =>
val instr = cpy.DefDef(meth)(rhs = instrumentBody(parent, meth.rhs))
cpy.Block(b)(instr :: Nil, closure)
case _ =>
// compute user-friendly position to highlight more text in the coverage UI
val namePos = parent.namePos
val pos = namePos.withSpan(namePos.span.withStart(parent.span.start))
// record info and insert call to Invoker.invoked
val coverageCall = createInvokeCall(parent, pos)
InstrumentedParts.singleExprTree(coverageCall, body)
/** Instruments the body of a secondary constructor DefDef.
*
* We must preserve the delegate constructor call as the first statement of
* the rhs Block, otherwise `HoistSuperArgs` will not be happy (see #17042).
*/
private def instrumentSecondaryCtor(ctorDef: DefDef)(using Context): Tree =
// compute position like in instrumentBody
val namePos = ctorDef.namePos
val pos = namePos.withSpan(namePos.span.withStart(ctorDef.span.start))
val coverageCall = createInvokeCall(ctorDef, pos)
ctorDef.rhs match
case b @ Block(delegateCtorCall :: stats, expr: Literal) =>
cpy.Block(b)(transform(delegateCtorCall) :: coverageCall :: stats.mapConserve(transform), expr)
case rhs =>
cpy.Block(rhs)(transform(rhs) :: coverageCall :: Nil, unitLiteral)
end instrumentSecondaryCtor
/**
* Checks if the apply needs a lift in the coverage phase.
* In case of a nested application, we have to lift all arguments
* Example:
* ```
* def T(x:Int)(y:Int)
* T(f())(1)
* ```
* should not be changed to {val $x = f(); T($x)}(1) but to {val $x = f(); val $y = 1; T($x)($y)}
*/
private def needsLift(tree: Apply)(using Context): Boolean =
def isShortCircuitedOp(sym: Symbol) =
sym == defn.Boolean_&& || sym == defn.Boolean_||
def isUnliftableFun(fun: Tree) =
/*
* We don't want to lift a || getB(), to avoid calling getB if a is true.
* Same idea with a && getB(): if a is false, getB shouldn't be called.
*
* On top of that, the `s`, `f` and `raw` string interpolators are special-cased
* by the compiler and will disappear in phase StringInterpolatorOpt, therefore
* they shouldn't be lifted.
*/
val sym = fun.symbol
sym.exists && (
isShortCircuitedOp(sym)
|| StringInterpolatorOpt.isCompilerIntrinsic(sym)
|| sym == defn.Object_synchronized
|| isContextFunctionApply(fun)
)
end isUnliftableFun
val fun = tree.fun
val nestedApplyNeedsLift = fun match
case a: Apply => needsLift(a)
case _ => false
nestedApplyNeedsLift ||
!isUnliftableFun(fun) && !tree.args.isEmpty && !tree.args.forall(LiftCoverage.noLift)
private def isContextFunctionApply(fun: Tree)(using Context): Boolean =
fun match
case Select(prefix, nme.apply) =>
defn.isContextFunctionType(prefix.tpe.widen)
case _ => false
/** Check if an Apply can be instrumented. Prevents this phase from generating incorrect code. */
private def canInstrumentApply(tree: Apply)(using Context): Boolean =
def isSecondaryCtorDelegateCall(fun: Tree): Boolean = fun match
case Select(This(_), nme.CONSTRUCTOR) => true
case Apply(fn, _) => isSecondaryCtorDelegateCall(fn)
case TypeApply(fn, _) => isSecondaryCtorDelegateCall(fn)
case _ => false
val sym = tree.symbol
!sym.isOneOf(ExcludeMethodFlags)
&& !isCompilerIntrinsicMethod(sym)
&& !(sym.isClassConstructor && isSecondaryCtorDelegateCall(tree.fun))
&& !sym.name.is(DefaultGetterName) // https://github.com/scala/scala3/issues/20255
&& (tree.typeOpt match
case AppliedType(tycon: NamedType, _) =>
/* If the last expression in a block is a context function, we'll try to
summon its arguments at the current point, even if the expected type
is a function application. Therefore, this is not valid:
```
def f = (t: Exception) ?=> (c: String) ?=> result
({
invoked()
f(using e)
})(using s)
```
*/
!tycon.name.isContextFunction
case m: MethodType =>
/* def f(a: Ta)(b: Tb)
f(a)(b)
Here, f(a)(b) cannot be rewritten to {invoked();f(a)}(b)
*/
false
case _ =>
true
)
/** Is this the symbol of a parameterless method that we can instrument?
* Note: it is crucial that `asInstanceOf` and `isInstanceOf`, among others,
* do NOT get instrumented, because that would generate invalid code and crash
* in post-erasure checking.
*/
private def canInstrumentParameterless(sym: Symbol)(using Context): Boolean =
sym.is(Method, butNot = ExcludeMethodFlags)
&& sym.info.isParameterless
&& !isCompilerIntrinsicMethod(sym)
&& !sym.info.typeSymbol.name.isContextFunction // exclude context functions like in canInstrumentApply
&& !sym.name.is(DefaultGetterName) // https://github.com/scala/scala3/issues/20255
/** Does sym refer to a "compiler intrinsic" method, which only exist during compilation,
* like Any.isInstanceOf?
* If this returns true, the call souldn't be instrumented.
*/
private def isCompilerIntrinsicMethod(sym: Symbol)(using Context): Boolean =
val owner = sym.maybeOwner
owner.exists && (
(owner.eq(defn.AnyClass) && (sym == defn.Any_asInstanceOf || sym == defn.Any_isInstanceOf)) ||
owner.maybeOwner == defn.CompiletimePackageClass
)
object InstrumentCoverage:
val name: String = "instrumentCoverage"
val description: String = "instrument code for coverage checking"
val ExcludeMethodFlags: FlagSet = Artifact | Erased
/** Maximum number of tree nodes in a method body for coverage instrumentation.
* Beyond this threshold, the instrumented bytecode risks exceeding the JVM's 64KB
* method size limit. The per-statement overhead of `Invoker.invoked()` is ~15 bytes,
* so roughly half of the tree nodes in a large body would each add that overhead. */
val MaxInstrumentableTreeNodes: Int = 3000
val scoverageLocalOn: Regex = """^\s*//\s*\$COVERAGE-ON\$""".r
val scoverageLocalOff: Regex = """^\s*//\s*\$COVERAGE-OFF\$""".r
/** Coverage probes are synthetic bookkeeping calls that should be transparent to
* later warning logic and should not steal source positions from the user tree
* they wrap.
*/
def isCoverageProbe(tree: Tree)(using Context): Boolean = tree match
case Apply(fun, Literal(Constant(_: Int)) :: Literal(Constant(_: String)) :: Nil) =>
fun.symbol == defn.InvokedMethodRef.symbol
case _ =>
false
/** Remove leading synthetic coverage wrappers to recover the user-written tree. */
def stripLeadingCoverage(tree: Tree)(using Context): Tree = tree match
case Typed(expr, _) =>
stripLeadingCoverage(expr)
case Inlined(_, Nil, expr) =>
stripLeadingCoverage(expr)
case Block(stats, expr) if stats.forall(isCoverageProbe) =>
stripLeadingCoverage(expr)
case _ =>
tree
/** Keep wrapper blocks pointed at the wrapped expression span so later warnings
* still highlight user code instead of synthetic `Invoker.invoked` scaffolding.
*/
def blockWithExprSpan(stats: List[Tree], expr: Tree)(using Context): Tree =
Block(stats, expr).withSpan(expr.span)
/**
* An instrumented Tree, in 3 parts.
* @param pre preparation code, e.g. lifted arguments. May be empty.
* @param invokeCall call to Invoker.invoked(dir, id), or an empty tree.
* @param expr the instrumented expression, executed just after the invokeCall
*/
case class InstrumentedParts(pre: List[Tree], invokeCall: Apply | EmptyTree.type, expr: Tree):
require(pre.isEmpty || (pre.nonEmpty && !invokeCall.isEmpty), "if pre isn't empty then invokeCall shouldn't be empty")
/** Turns this into an actual Tree. */
def toTree(using Context): Tree =
if invokeCall.isEmpty then expr
else if pre.isEmpty then blockWithExprSpan(invokeCall :: Nil, expr)
else blockWithExprSpan(pre :+ invokeCall, expr)
object InstrumentedParts:
def notCovered(expr: Tree) = InstrumentedParts(Nil, EmptyTree, expr)
def singleExpr(invokeCall: Apply, expr: Tree) = InstrumentedParts(Nil, invokeCall, expr)
/** Shortcut for `singleExpr(call, expr).toTree` */
def singleExprTree(invokeCall: Apply, expr: Tree)(using Context): Tree =
blockWithExprSpan(invokeCall :: Nil, expr)