Skip to content

Commit 1ff5508

Browse files
authored
bugfix: scoverage does not instrument pat-mat assignment properly (#731)
* bugfix: scoverage does not instrument pat-mat assignment properly * style: fix scalafmt error
1 parent 2767956 commit 1ff5508

File tree

2 files changed

+47
-0
lines changed

2 files changed

+47
-0
lines changed

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

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -842,6 +842,23 @@ 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
857+
if v.symbol.isSynthetic && v.rhs.pos.isDefined && containsNonSynthetic(
858+
v.rhs
859+
) =>
860+
treeCopy.ValDef(tree, v.mods, v.name, v.tpt, process(v.rhs))
861+
845862
/** <synthetic> val default: A1 => B1 =
846863
* <synthetic> val x1: Any = _
847864
*/

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

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

0 commit comments

Comments
 (0)