Repository navigation
Description
TL;DR: Coverage through source maps is wrong. c8 reports Shapes.res at 100% although 10 of its 14 switch arms never run (repro). Arms that return a constant or a variable, and the tests that pick an arm, get no mapping, because Lambda has no locations on Lconst/Lvar/switch nodes. Proposed fix: per-arm locations on the switch/if nodes. Details below.
Summary
Source maps are accurate for calls, operators, functions, throw and debugger(). Pattern matching and if expressions are a different story:
- Arms that return a constant or a variable get no mapping at all. Examples are
| Empty => "empty",| None => -1and| _ => x. - The tests that pick an arm (
typeof s !== "object",s === "Empty",o === undefined,switch (s.TAG)) get either no mapping or the location of a different arm.
Breakpoints and stack traces mostly still work, because they land on calls. Coverage reports through the source map, however, are wrong, not just imprecise. With c8, unexecuted arms are reported as covered:
| Target | % Lines | % Branch |
|---|---|---|
Probe.mjs with the map removed |
62.3 | 34.8 |
Probe.res through the source map |
100 | 0 (one branch detected) |
The behavior is the same as at the commit that introduced source maps (#8393). Built at that commit and at current master, the compiler produces identical mappings for the probe below. It is not a regression.
Reproduction
Standalone repo: https://github.com/fhammerschmidt/rescript-sourcemap-coverage, using rescript@13.0.0-alpha.7 and c8 12.0.0.
- The setup:
src/Shapes.reshas 4 switches with 14 arms in total, and the exercise script runs one arm of each. npm run coverage: c8 reportsShapes.resat 100% for statements, branches, functions and lines, although 10 of the 14 arms never run.npm test: a control run on the JS with the map removed reports exactly those 10 arms as uncovered. Through the source map, all 10 are reported with 1 hit, so 10 of the 28 tests fail.
Probe with decoded mappings (guards, lists, tuples, curried calls)
The probe below covers more constructs (guards, lists, tuples, curried calls) and shows the decoded mappings.
rescript.json:
{
"name": "sm_probe",
"sources": ["src"],
"package-specs": [{ "module": "esmodule", "in-source": true, "suffix": ".mjs" }],
"sourceMap": { "enabled": "always", "mode": "linked", "sourcesContent": true }
}src/Probe.res (excerpt; the full file is below):
let area = s =>
switch s {
| Circle(r) => 3.14 * r * r
| Rect(w, h) => w * h
| Square(x) => x * x
| Empty => 0.0
| Unknown => -1.0
}
let opt = o =>
switch o {
| Some(Some(x)) => x + 1
| Some(None) => 0
| None => -1
}Decoded mappings (generated line, then generated column → original line:column and the source text there):
function area(s) { @0 → 8:11 «s =>»
if (typeof s !== "object") { (none)
if (s === "Empty") { (none)
return 0.0; (none) ← `Empty => 0.0`
} else {
return -1.0; (none) ← `Unknown => -1.0`
}
}
switch (s.TAG) { (none)
case "Circle" : @9 → 10:4 «Circle(r) => …» ✓
let r = s._0; @6 → 10:4 ✓
return 3.14 * r * r; @13 → 10:17 «3.14 * r * r» ✓
function opt(o) { @0 → 33:10 «o =>»
if (o === undefined) { @6 → 35:4 «Some(Some(x)) => …» ✗ this is the `None` test
return -1; (none) ← `None => -1`
}
let x = Primitive_option.valFromOption(o);
@10 → 36:4 «Some(None) => 0» ✗ shared by both `Some` arms
if (x !== undefined) { @6 → 35:9 «Some(x)) => x + 1»
return x + 1 | 0; @11 → 35:21 «x + 1» ✓
} else {
return 0; (none) ← `Some(None) => 0`
Coverage: c8 --reporter=text node run.mjs, where run.mjs calls each function once with input that takes only one arm, for example area(Circle(1.)), opt(Some(Some(5))), str("a") and tup(true, true).
Most likely, v8-to-istanbul (c8's remapper) drops a range whose start or end can't be mapped on the same generated line. The unexecuted constant arms have no mappings, so nothing marks them uncovered, and the enclosing function's hit count shows through.
Curried and partial application map correctly: add3(1, ...), x => y => x + y, applyF(f, x).
Full probe
type shape =
| Circle(float)
| Rect(float, float)
| Square(float)
| Empty
| Unknown
let area = s =>
switch s {
| Circle(r) => 3.14 * r * r
| Rect(w, h) => w * h
| Square(x) => x * x
| Empty => 0.0
| Unknown => -1.0
}
let label = s =>
switch s {
| Empty => "empty"
| Unknown => "unknown"
| Circle(_) => "circle"
| _ => "polygon"
}
let classify = n =>
switch n {
| 0 => "zero"
| n if n < 0 => "negative"
| n if n > 100 => "big"
| _ => "small"
}
let opt = o =>
switch o {
| Some(Some(x)) => x + 1
| Some(None) => 0
| None => -1
}
let lst = l =>
switch l {
| list{} => "nil"
| list{_} => "one"
| list{a, b, ..._} if a == b => "pair-eq"
| _ => "many"
}
let str = s =>
switch s {
| "a" => 1
| "b" => 2
| _ => 3
}
let tup = (a, b) =>
switch (a, b) {
| (true, true) => "tt"
| (true, false) => "tf"
| (false, _) => "f_"
}
let add3 = (a, b, c) => a + b + c
let partial = add3(1, ...)
let curried = x => y => x + y
let useCurried = curried(1)(2)
let usePartial = partial(2, 3)
let applyF = (f, x) => f(x)
let usesHigher = applyF(x => x * 2, 21)In this probe, label, str and tup have no mappings inside their bodies. classify has mappings only for its two guards.
Root cause
Lambda.t carries a Location.t only on Lprim, Lapply and Lfunction (compiler/ml/lambda.mli). Lconst, Lvar, Lswitch, Lstringswitch, Lifthenelse, Lstaticcatch and Lstaticraise carry none.
source_loc_of_lam in compiler/core/lam_compile.ml therefore borrows a location from the first nested call or primitive, and returns None for constants and variables. This gives the two symptoms above:
- an arm whose body is a constant or a variable has nothing to map to;
- dispatch code borrows the location of whichever arm comes first in the Lambda, which can belong to a sibling pattern.
What accuracy we should aim for
A mapping for every generated token isn't achievable, and we don't need one. A dispatch test like switch (s.TAG) belongs to the whole switch. One return can serve several patterns. Folded code has no expression left to point at. Three properties are realistic, and each can be tested:
- Completeness: every generated line with executable code has at least one mapping. This is what coverage tools depend on.
- Containment: every mapping points inside the construct that produced the code. An arm's statements point into that arm. Tests and dispatch point to the
switch/ifor to the arm's pattern, never into a sibling arm. - Precision for calls and expressions, which already holds.
Fix options
-
A. A no-op location wrapper node in Lambda (like OCaml's
Levent). Not recommended. Every pass that matches onLconstorLvarwould stop seeing through it, which hurts constant folding, switch tables and boolean simplification. JS output would also differ depending on whether source maps are enabled. -
B. Locations on the branch structure (recommended):
LswitchandLstringswitcharms,Lifthenelsebranches andLstaticcatchhandlers get the location of the arm they came from. The matcher has this from the typed tree (c_lhs/c_rhs).- The node itself gets the location of the
switchorif. lam_compilemaps the first statement of each arm (case,returnorletbinding) to the arm's location, and the tests to the node's location.
The leaves stay untouched, so optimizations and JS output don't change. Because
Lambda.tisprivatewith smart constructors, the change is contained. A pass that fails to carry the locations through only loses mappings and never produces wrong code. -
C. End mappings for mapped nodes (complementary to B). These give coverage tools proper range boundaries.
How other compilers check accuracy
-
esbuild (
scripts/verify-source-map.js) runs a round-trip test. Fixtures contain unique string markers. For each marker, the test checks two things:originalPositionForat the marker's position in the output resolves to the marker's exact line and column insourcesContent;allGeneratedPositionsForon that original position includes the output position.
It runs this across bundling, minification, code splitting, CRLF and Unicode inputs.
-
TypeScript writes a
.sourcemap.txtbaseline for each compiler test that enables source maps. The baseline lists every emitted span next to the source span it maps to, so any mapping change shows up as a baseline diff in review. -
js_of_ocaml (
compiler/tests-sourcemap) decodes the map and prints every mapping as a marker in the generated line, e.g.b.ml:1:10 -> function f(x){<>return x - 1 | 0;}, then diffs the result against an expected file. It also emits end-of-function mappings (return x - 1 | 0;<>}). -
Gleam (
compiler-core/src/javascript/tests/sourcemaps.rs) uses snapshot tests that render each mapping's source segment next to its JS segment. Theircasesnapshots show every arm mapped, including arms that return a constant (return 1;maps to the1inOk(1), Error(_) -> 1). That is the case this issue is about.
Tests
The current test (tests/build_tests/source_map/input.js) only checks that some mapping exists on a branch's original line. That is why this gap went unnoticed. Proposed tests:
- Round-trip markers, as in esbuild: each arm in a fixture returns a unique literal (
| Empty => "arm_empty"). For every occurrence in the JS:- the mapping must resolve inside that arm's span in the
.res; - the reverse lookup must include that JS position.
- the mapping must resolve inside that arm's span in the
- Completeness baseline: compile a corpus (for example
tests/tests/src) with source maps. Record per file the share of executable generated lines that have a mapping, and fail if any file's share drops. This catches regressions in passes nobody thought to test. - End-to-end coverage: run c8 on a fixture with a driver that takes known arms, and assert that exactly the arms that weren't taken are reported uncovered.
- Mapping snapshots, as in TypeScript, js_of_ocaml and Gleam: print each mapping as a marker in the generated line next to its source text, so every change to the mappings shows up in review.
- Output invariance: JS is byte-identical with source maps on and off, apart from the
sourceMappingURLcomment.
Plan:
- Land the tests first. Where today's behavior falls short, record it as the baseline, so CI stays green and the gap is documented.
- Implement B in steps, stacked on the tests:
LifthenelseandLswitch, thenLstringswitch, then static exits. Tighten the baseline with each step.
Activity
Emit source map mappings for pattern-match arms, branch tests, and bl…