Skip to content

Commit fe0c080

Browse files
committed
bugfix: scoverage does not instrument pat-mat assignment properly
1 parent 3db2c6f commit fe0c080

File tree

2 files changed

+42
-0
lines changed

2 files changed

+42
-0
lines changed

plugin/src/main/scala/scoverage/ScoveragePlugin.scala

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -842,6 +842,20 @@ class ScoverageInstrumentationComponent(
842842
*/
843843
case v: ValDef if v.symbol.isLazy => tree
844844

845+
/** Pattern matching assignment instrumentation (see https://github.com/scoverage/scalac-scoverage-plugin/issues/123)
846+
*
847+
* User code: val (a, b) = { if (c) 1 -> 1 else 2 -> 2 }
848+
*
849+
* After typer, this desugars to:
850+
* <synthetic> val x$1 = (if (c) 1 -> 1 else 2 -> 2) match { case (a, b) => Tuple2(a, b) }
851+
* val a = x$1._1
852+
* val b = x$1._2
853+
*
854+
* This will instrument the user expression (if-else with arrow calls).
855+
*/
856+
case v: ValDef if v.symbol.isSynthetic && v.rhs.pos.isDefined && containsNonSynthetic(v.rhs) =>
857+
treeCopy.ValDef(tree, v.mods, v.name, v.tpt, process(v.rhs))
858+
845859
/** <synthetic> val default: A1 => B1 =
846860
* <synthetic> val x1: Any = _
847861
*/

plugin/src/test/scala/scoverage/PluginCoverageTest.scala

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -380,4 +380,32 @@ class PluginCoverageTest extends FunSuite with MacroSupport {
380380
assert(!compiler.reporter.hasWarnings)
381381
compiler.assertNMeasuredStatements(11)
382382
}
383+
384+
test("plugin should handle return pattern matching assignment https://github.com/scoverage/scalac-scoverage-plugin/issues/123") {
385+
val compiler = ScoverageCompiler.default
386+
compiler.compileCodeSnippet(
387+
"""
388+
|object TestObject {
389+
| def test(c: Boolean): Unit = {
390+
| val (a, b) = {
391+
| if (c) 1 -> 1 else 2 -> 2
392+
| }
393+
| }
394+
|}
395+
""".stripMargin
396+
)
397+
assert(!compiler.reporter.hasErrors)
398+
assert(!compiler.reporter.hasWarnings)
399+
/**
400+
* WITHOUT the bugfix:
401+
* 2 when assigning value to "a" and "b"
402+
* 1 at the end of the function
403+
* WITH the bugfix, it will additionally include
404+
* 2 from then branch
405+
* 2 from else branch
406+
* 2 from synthetic code generated for pattern matching assignment
407+
*/
408+
compiler.assertNMeasuredStatements(9)
409+
}
410+
383411
}

0 commit comments

Comments
 (0)