From 5d6d3bd6601e435dc9f5599688b1888bf04bd3da Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Thu, 12 Nov 2026 12:24:11 -0800 Subject: [PATCH 01/42] refactor(abc): drop the init_declarator guard in the C and Objective-C impls Both impls counted an `init_declarator` only when `node.first_child(|id| id == EQ as u16)` found an `=`. tree-sitter-c 0.24.2 defines the rule as `declarator = value` and tree-sitter-objc 3.0.2 as `declarator [attribute] = value`, with no alias onto the kind, so the guard was true for every such node and cost one heap-allocating child scan each. The C++ grammar also spells `int x(5);` and `int x{5};` as an `init_declarator`; its guard is live and stays. The mutation run is what showed it: replacing the guard with `true`, or its `==` with `!=`, passed the suite, and neither can be killed by a metric value. Excluding the first would not be honest, since it skips the scan `child_scan_cursors` counts. With the guard gone the two `==` exclusions go too, and the config excludes two mutants. No output moves: the root and ast suites pass, the corpus snapshots included, and the merged arm's three mutants in each impl are caught. Refs #1736 --- .cargo/mutants.toml | 15 --------------- src/metrics/abc/c.rs | 22 +++++++++++----------- src/metrics/abc/objc.rs | 11 +++++++---- 3 files changed, 18 insertions(+), 30 deletions(-) diff --git a/.cargo/mutants.toml b/.cargo/mutants.toml index e91c73ebe..c3871bcaf 100644 --- a/.cargo/mutants.toml +++ b/.cargo/mutants.toml @@ -44,21 +44,6 @@ exclude_re = [ # the upward one, which does nothing there either, since `words` is # non-empty and `word - first_word >= words.len()` reads `0 >= len`. '^src/metrics/loc/line_set\.rs:\d+:\d+: replace < with <= in LineSet::reserve$', - # Equivalent while tree-sitter-c is pinned at 0.24.2, whose one - # `init_declarator` production is `declarator = value`. Every such node - # holds an `=` child (one the parser inserted in recovery is still that - # kind) and a child that is not `=`, so the guard's one child scan - # finds a match whether it looks for the `=` or for anything else. - # Re-derive on a grammar bump: the C++ grammar also has `int x(5);` and - # `int x{5};`, which keep this mutant live there. - '^src/metrics/abc/c\.rs:\d+:\d+: replace == with != in ::compute$', - # The same mutant in the Objective-C impl, equivalent for the same - # reason while tree-sitter-objc is pinned at 3.0.2: its one - # `init_declarator` production is `declarator [attribute] = value`. - # `compute` has a second `==`, in `kind == MessageExpression`, whose - # mutant is live and caught; the column (56 against 25) is what tells - # this one from it. - '^src/metrics/abc/objc\.rs:\d+:56: replace == with != in ::compute$', # Non-terminating under mutation. The loop then breaks when # `goto_next_sibling` succeeds and repeats when it fails, so a list # with one child is visited forever. Its one caller walks the values diff --git a/src/metrics/abc/c.rs b/src/metrics/abc/c.rs index 1dfae214d..a3d2f16a8 100644 --- a/src/metrics/abc/c.rs +++ b/src/metrics/abc/c.rs @@ -49,18 +49,18 @@ impl Abc for CCode { // single named node so we count once per // `assignment_expression`. `update_expression` covers both // prefix and postfix `++` / `--`. - AssignmentExpression | UpdateExpression => { - stats.assignments += 1.; - } + // // `int x = expr;` parses as a `declaration` carrying an - // `init_declarator` of the form `declarator = value`. Per - // Fitzpatrick (1997), every `=` operator increments A, so we - // count every `init_declarator` whose body contains an - // explicit `=` token (`const int x = 5;` counts like - // `int x = 5;`). `int x;` parses as a plain declarator inside - // the `declaration`, not an `init_declarator`, so this arm - // never fires for un-initialised declarations. - InitDeclarator if node.first_child(|id| id == EQ as u16).is_some() => { + // `init_declarator`. Per Fitzpatrick (1997), every `=` + // operator increments A, and tree-sitter-c 0.24.2 spells an + // `init_declarator` as `declarator = value` and nothing + // else, so each one counts (`const int x = 5;` like + // `int x = 5;`) with no look at its children. `int x;` + // parses as a plain declarator inside the `declaration`, so + // it never reaches this arm. The C++ grammar also spells + // `int x(5);` and `int x{5};` as an `init_declarator`, which + // is why its arm reads the `=` and this one does not. + AssignmentExpression | UpdateExpression | InitDeclarator => { stats.assignments += 1.; } // Every call — the `Call` row — counts. C has no `new` diff --git a/src/metrics/abc/objc.rs b/src/metrics/abc/objc.rs index 500c3aed1..a95732291 100644 --- a/src/metrics/abc/objc.rs +++ b/src/metrics/abc/objc.rs @@ -58,10 +58,13 @@ impl Abc for ObjcCode { let scores: ScoresItself = &|expr| objc_condition_scores_itself(expr, code); let kind = node.kind_id(); match kind.into() { - AssignmentExpression | UpdateExpression => { - stats.assignments += 1.; - } - InitDeclarator if node.first_child(|id| id == EQ as u16).is_some() => { + // An `init_declarator` counts with no look at its children: + // tree-sitter-objc 3.0.2 spells it `declarator [attribute] = + // value` and nothing else, so each one holds an `=`. The C + // sibling says the same of its grammar; the C++ grammar's + // `int x(5);` and `int x{5};` are why that arm reads the + // token. + AssignmentExpression | UpdateExpression | InitDeclarator => { stats.assignments += 1.; } // Every call — the `Call` row: a C `call_expression` (two From 074e72676b3ffd1bc806ae046c1ad74541a35ab4 Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Thu, 12 Nov 2026 13:08:01 -0800 Subject: [PATCH 02/42] ci(mutation): stop mutating the derived-parity test modules MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The selection's `roles/**/*.rs` and `src/metrics/**/*.rs` globs reach two `derived_parity_tests.rs` files. cargo-mutants skips a module under a bare `#[cfg(test)]`, and both are declared under `#[cfg(all(test, any(feature = …)))]`, which it reads as ordinary code. Run 43278927651 therefore mutated their helpers (`Census::record`, `ChainProbe::probe`, `owner_positives`) and reported the survivors as escapes in the classifier code: 20 of the 112 missed mutants in the first eight shards to finish. `exclude_globs = ["**/*_tests.rs"]` takes the 161 mutants of the two files out of the list and nothing else: `--list` reads 5280 with the config and 5443 without, the other two being the `exclude_re` entries. Refs #1736 --- .cargo/mutants.toml | 8 ++++++++ docs/development/mutation_testing.md | 10 +++++++--- 2 files changed, 15 insertions(+), 3 deletions(-) diff --git a/.cargo/mutants.toml b/.cargo/mutants.toml index c3871bcaf..8067b6797 100644 --- a/.cargo/mutants.toml +++ b/.cargo/mutants.toml @@ -26,6 +26,14 @@ output = "target/mutants" # runs both suites. test_package = ["big-code-analysis", "big-code-analysis-ast"] +# Test modules are not the subject. cargo-mutants skips a module +# declared under a bare `#[cfg(test)]`, and reads +# `#[cfg(all(test, any(feature = …)))]` as ordinary code: the two +# `derived_parity_tests.rs` suites are gated that way, and their helpers +# were being mutated as if they were classifiers. An exclusion, unlike +# `examine_globs`, cannot widen a single-file local run. +exclude_globs = ["**/*_tests.rs"] + # Mutants no run tests. Each entry is one mutant shown to behave # identically on every reachable input, panics and side effects # included, or one that never terminates; the reason sits above it. A diff --git a/docs/development/mutation_testing.md b/docs/development/mutation_testing.md index 4f6f43d4b..98212d0ff 100644 --- a/docs/development/mutation_testing.md +++ b/docs/development/mutation_testing.md @@ -168,9 +168,13 @@ cargo install cargo-mutants --locked the test-timeout floor, the output directory, and the test-package set (every mutant runs both the root crate's and `big-code-analysis-ast`'s tests, because the checker and getter are -pinned almost entirely by the root crate's metric tests). cargo-mutants -reads it from the workspace root, so a plain `cargo mutants` picks it -up. Which packages to mutate and `--in-place` have no config-file key +pinned almost entirely by the root crate's metric tests). It also +excludes the `*_tests.rs` modules, and the mutants listed under +`exclude_re`. cargo-mutants skips a module under a bare `#[cfg(test)]` +and treats `#[cfg(all(test, …))]` as ordinary code, so without the +glob it mutates the two `derived_parity_tests.rs` suites. cargo-mutants +reads the file from the workspace root, so a plain `cargo mutants` +picks it up. Which packages to mutate and `--in-place` have no config-file key and stay on the command line; which files could be configured (`examine_globs`) but is not, because cargo-mutants 27 unions that key with `-f` and a single-file local run would silently widen to the From db1b7bba9f806f2ef992c18138a92ad404495904 Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Thu, 12 Nov 2026 16:01:11 -0800 Subject: [PATCH 03/42] test(npm): read a Ruby class body where a keyword's name is not the keyword MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `is_statement_of` decides which child of a wrapper the class-body walk reads as a statement, and the walk reads a bare `public` / `private` statement as the visibility marker. No fixture put a word spelled like a marker anywhere a statement is not, so deleting the `if`, `case`, `when` / `in`, loop or modifier arm, returning `true` outright, or dropping the assignment guard all passed: eight of the function's mutants, and one more on the frame test in `read_body`. Three tests put the word in such a place: the target of a setter call and of a `for`, a `case … in` pattern that binds a local, and a local read in an `if` condition, a `case` value and a modifier's condition. `public_class_method` gets a fixture where it moves a singleton back to public; where it only restated the default, a walk that did not know the word counted the same. Every expected count was measured on ruby 3.0.2 and is derived beside its fixture. Refs #1736 --- src/metrics/npm.rs | 120 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 120 insertions(+) diff --git a/src/metrics/npm.rs b/src/metrics/npm.rs index c00f5e838..9361deea2 100644 --- a/src/metrics/npm.rs +++ b/src/metrics/npm.rs @@ -3539,6 +3539,27 @@ class C { ); } + #[cfg(feature = "ruby")] + #[test] + fn ruby_public_class_method_republishes_a_private_singleton() { + // `public_class_method` must be able to move a singleton *back* + // to public: `a` and `b` are demoted first, then `a` is named + // again (measured on ruby 3.0.2: `Cm.singleton_methods(false)` + // is `[a, c]`, with `b` private). Where the keyword only + // restates a default, as in the fixture above, a walk that does + // not know the word reports the same count. + // + // expected: nm = 3 (a, b, c), npm = 2 (a, c). + check_metrics::( + "class Cm\n def self.a\n end\n def self.b\n end\n def self.c\n end\n private_class_method :a, :b\n public_class_method :a\nend\n", + "foo.rb", + |metric| { + assert_eq!(metric.npm.class_nm_sum(), 3); + assert_eq!(metric.npm.class_npm_sum(), 2); + }, + ); + } + #[cfg(feature = "ruby")] #[test] fn ruby_private_in_a_singleton_class_body_demotes() { @@ -4328,6 +4349,105 @@ class C { ); } + #[cfg(feature = "ruby")] + #[test] + fn ruby_setter_target_named_like_a_keyword_is_not_the_marker() { + // `self.public = true` calls the setter `public=`, and the loop + // target of `for self.public in [true]` does too: neither runs + // `public`, so the `private` above each stays in force + // (measured on ruby 3.0.2: `after` is private in `A`, `in_for` + // and `after` in `F`, and the one public method of each is the + // singleton `public=`). The target is a `call` with a `self` + // receiver and no argument list, which as a statement is the + // bare keyword — `self.public` on a line of its own republishes + // what follows — so a walk that read an assignment's `left` or + // a `for`'s `pattern` as a statement would do the same here. + // + // expected: A nm = 2 (self.public=, after), npm = 1; F nm = 3 + // (self.public=, in_for, after), npm = 1. + check_metrics::( + "class A\n def self.public=(flag)\n end\n private\n self.public = true\n def after\n end\nend\n", + "foo.rb", + |metric| { + assert_eq!(metric.npm.class_nm_sum(), 2); + assert_eq!(metric.npm.class_npm_sum(), 1); + }, + ); + check_metrics::( + "class F\n def self.public=(flag)\n end\n private\n for self.public in [true] do\n def in_for\n end\n end\n def after\n end\nend\n", + "foo.rb", + |metric| { + assert_eq!(metric.npm.class_nm_sum(), 3); + assert_eq!(metric.npm.class_npm_sum(), 1); + }, + ); + } + + #[cfg(feature = "ruby")] + #[test] + fn ruby_pattern_binding_named_like_a_keyword_is_not_the_marker() { + // A bare identifier as a `case … in` pattern binds a local: `in + // public` matches anything and names it `public`, calling + // nothing, so the `private` above stays in force (measured on + // ruby 3.0.2: `P` has `[a]` public and `[b, c]` private). The + // pattern is a direct `identifier` child of the `in_clause` — + // a `when` pattern and a `rescue` class list are wrapped — so a + // walk that read every child of the clause as a statement would + // take it for the marker and publish `b` and `c`. + // + // expected: nm = 3 (a, b, c), npm = 1 (a). + check_metrics::( + "class P\n def a\n end\n private\n case 1\n in public\n def b\n end\n end\n def c\n end\nend\n", + "foo.rb", + |metric| { + assert_eq!(metric.npm.class_nm_sum(), 3); + assert_eq!(metric.npm.class_npm_sum(), 1); + }, + ); + } + + #[cfg(feature = "ruby")] + #[test] + fn ruby_keyword_named_local_in_a_wrapper_header_is_not_the_marker() { + // A local bound where the walk does not look — inside an array + // literal here, `x = [public = true]`, the gap + // `shadow_statement_bindings` records — is a local to Ruby all + // the same, so the bare `public` in an `if` condition, a `case` + // value and a modifier's condition reads it and the `private` + // above stays in force (measured on ruby 3.0.2: each class has + // `[a]` public and `[b, c]` private). The walk agrees because + // it reads none of the three as a statement. Read as one, the + // word is the marker call, no shadow having been recorded, and + // `b` and `c` come out public — `c` alone under the modifier, + // whose body is read before its condition. + // + // expected, for each: nm = 3 (a, b, c), npm = 1 (a). + check_metrics::( + "class I\n def a\n end\n private\n x = [public = true]\n if public\n def b\n end\n end\n def c\n end\nend\n", + "foo.rb", + |metric| { + assert_eq!(metric.npm.class_nm_sum(), 3, "if condition"); + assert_eq!(metric.npm.class_npm_sum(), 1, "if condition"); + }, + ); + check_metrics::( + "class C\n def a\n end\n private\n x = [public = 1]\n case public\n when 1\n def b\n end\n end\n def c\n end\nend\n", + "foo.rb", + |metric| { + assert_eq!(metric.npm.class_nm_sum(), 3, "case value"); + assert_eq!(metric.npm.class_npm_sum(), 1, "case value"); + }, + ); + check_metrics::( + "class M\n def a\n end\n private\n x = [public = true]\n def b\n end if public\n def c\n end\nend\n", + "foo.rb", + |metric| { + assert_eq!(metric.npm.class_nm_sum(), 3, "modifier condition"); + assert_eq!(metric.npm.class_npm_sum(), 1, "modifier condition"); + }, + ); + } + #[cfg(feature = "ruby")] #[test] fn ruby_def_inside_another_space_is_not_the_class_s() { From f6a76fe41bb7795c23628f6fea3bd5a3ef7bd562 Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Thu, 12 Nov 2026 16:01:11 -0800 Subject: [PATCH 04/42] test(npa): pin three attribute paths no fixture could tell from a constant - Ruby: an attribute whose name the walk cannot resolve takes the visibility of the keyword that wraps its declaration, not the flag in force. With resolvable names the keyword re-files the attribute afterwards and hides which one was read, so `governs` returning false and the inverted comparison in `ruby_wrapped_is_public` passed. - Rust: `type Opaque;` in an `extern` block is the same node under the same `declaration_list` kind as a trait's associated type, and is not one. `rust_count_assoc_type` with `||` counted it. - Kotlin: a destructuring `property_declaration` counts one attribute per binding. kotlinc rejects the form at class scope; the grammar accepts it and `kotlin_count_property_attrs` has an arm for it, which is what the test pins, and its comment says so. Refs #1736 --- src/metrics/npa.rs | 75 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 75 insertions(+) diff --git a/src/metrics/npa.rs b/src/metrics/npa.rs index 61adef639..9310fbd0e 100644 --- a/src/metrics/npa.rs +++ b/src/metrics/npa.rs @@ -2672,6 +2672,32 @@ mod tests { ); } + #[cfg(feature = "kotlin")] + #[test] + fn kotlin_destructuring_property_counts_each_binding() { + // A destructuring declaration is one `property_declaration` + // holding a `multi_variable_declaration`, counted by binding: + // two public, three private, and the plain `z`. kotlinc rejects + // the form at class scope ("Destructuring declarations are only + // allowed for local variables/values"); the grammar accepts it + // there, and this pins what the consumer makes of it. One + // attribute per declaration reads 3 / 2. + // + // expected: na = 6 (x, y, a, b, c, z), npa = 3 (x, y, z). + check_metrics::( + "class Pt(p: Pair, t: Triple) { + val (x, y) = p + private val (a, b, c) = t + val z = 0 + }", + "foo.kt", + |metric| { + assert_eq!(metric.npa.class_na_sum(), 6); + assert_eq!(metric.npa.class_npa_sum(), 3); + }, + ); + } + // --- TypeScript / TSX NPA tests -------------------------------------- // // TypeScript class fields are `public_field_definition` direct children @@ -4177,6 +4203,32 @@ mod tests { ); } + #[cfg(feature = "ruby")] + #[test] + fn ruby_keyword_wrapping_an_unresolvable_attr_name_decides_its_visibility() { + // An attribute whose name the walk cannot resolve (`:"a_#{S}"`, + // an interpolated symbol) is counted and can be re-filed by + // nothing, so the bit it is declared with is final: the + // wrapping keyword's, not the flag's. `a` is declared by + // `private attr_reader` under a public flag, `b` and `c` by + // `public attr_reader` under a private one (measured on ruby + // 3.0.2 with `S = "x"`: public `[b_x, c_x]`, private `[a_x]`). + // A resolvable name cannot show this: the keyword re-files it + // by name when the call is left, over whatever bit the + // declaration took. + // + // expected: na = 3, npa = 2 (b, c); the flag in place of the + // keyword, or the keyword inverted, reads 1. + check_metrics::( + "class At\n private attr_reader :\"a_#{S}\"\n private\n public attr_reader :\"b_#{S}\", :\"c_#{S}\"\nend\n", + "foo.rb", + |metric| { + assert_eq!(metric.npa.class_na_sum(), 3); + assert_eq!(metric.npa.class_npa_sum(), 2); + }, + ); + } + #[cfg(feature = "ruby")] #[test] fn ruby_string_argument_names_an_accessor() { @@ -4971,6 +5023,29 @@ mod tests { ); } + #[cfg(feature = "rust")] + #[test] + fn rust_extern_type_is_not_an_interface_attribute() { + // `type Opaque;` in an `extern` block — an extern type, the + // unstable `extern_types` feature — is the same + // `associated_type` node under the same `declaration_list` kind + // as a trait's `type Output;`. Only the trait's two count: the + // body's kind alone does not make its member an associated + // type. + // + // expected: interface_na = 2 (Output, Error), interface_npa = 2; + // every `associated_type` in a `declaration_list` reads 3. + check_metrics::( + "extern \"C\" {\n type Opaque;\n}\ntrait Shape {\n type Output;\n type Error;\n}\n", + "foo.rs", + |metric| { + assert_eq!(metric.npa.interface_na_sum(), 2); + assert_eq!(metric.npa.interface_npa_sum(), 2); + assert_eq!(metric.npa.class_na_sum(), 0); + }, + ); + } + #[cfg(feature = "rust")] #[test] fn rust_multiple_impls_aggregate() { From 04c8cb1abe7deb47f94725c873db3cb8385aba10 Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Thu, 12 Nov 2026 16:01:11 -0800 Subject: [PATCH 05/42] ci(mutation): exclude seven equivalent npa mutants MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Each entry carries its proof. Two rest on the code alone: the `RescueModifier` arm of `is_statement_of` answers what the fallthrough answers, and `read_body`'s frame test with `&&` reaches the same `child.is_named()` through `is_statement_of`. Five rest on a pinned grammar: Kotlin's `property_declaration` holds exactly one declaration node, PHP's `Member` row admits only kinds that hold no element of the other bucket, and a Rust `const_item` or `static_item` under an `impl` or `trait` can only sit in its `declaration_list`. `cargo mutants --list --no-config -e '**/*_tests.rs'` against `cargo mutants --list` over the workflow's selection differs by exactly these seven and the two earlier entries. The guide gains two notes from writing them: a name holding a `'` needs a `'''…'''` string, and a config that does not parse prints an empty list, which reads as everything excluded. Refs #1736 --- .cargo/mutants.toml | 26 ++++++++++++++++++++++++++ docs/development/mutation_testing.md | 8 ++++++-- 2 files changed, 32 insertions(+), 2 deletions(-) diff --git a/.cargo/mutants.toml b/.cargo/mutants.toml index 8067b6797..b0c401e6e 100644 --- a/.cargo/mutants.toml +++ b/.cargo/mutants.toml @@ -52,6 +52,32 @@ exclude_re = [ # the upward one, which does nothing there either, since `words` is # non-empty and `word - first_word >= words.len()` reads `0 >= len`. '^src/metrics/loc/line_set\.rs:\d+:\d+: replace < with <= in LineSet::reserve$', + # Equivalent. The deleted arm answers `true`, and so does the `_` + # arm the three kinds then fall to: `is_assignment` is false for a + # rescue modifier, so the guarded arm between them does not take them. + '^src/metrics/npa/ruby_body\.rs:\d+:\d+: delete match arm RescueModifier \| RescueModifier2 \| RescueModifier3 in is_statement_of$', + # Equivalent. With `&&` the class body's frame and an argument frame + # are read through `is_statement_of`, whose answer for a parent that + # is a class body or a `call` is `child.is_named()`, the test the + # original applies to those two frames itself. No frame is both. + '''^src/metrics/npa/ruby_body\.rs:\d+:\d+: replace \|\| with && in RubyBodyState<'a, 'chain>::read_body$''', + # Equivalent while tree-sitter-kotlin's `property_declaration` holds + # exactly one of `variable_declaration` and + # `multi_variable_declaration`: without the arm a single binding sums + # to 0, and the `.max(1)` on the sum makes it 1 again. + '^src/metrics/npa/kotlin\.rs:\d+:\d+: delete match arm VariableDeclaration in kotlin_count_property_attrs$', + # Equivalent, both `&&` of the function. PHP's `Member` row owns + # `property_declaration` and the two `const_declaration` ids with no + # gate, so `||` only admits members of the other kind into each + # filter, and those hold no `property_element` (the class arm) and no + # `const_element` (the interface arm) to count. + '^src/metrics/npa/php\.rs:\d+:\d+: replace && with \|\| in ::compute$', + # Equivalent while tree-sitter-rust places a `const_item` or + # `static_item` only in a `block`, a `declaration_list` or the + # `source_file`: of those, only a `declaration_list` is a direct child + # of an `impl_item` or a `trait_item`, so once the grandparent matches + # the guard on the parent is true. Both arms of the function. + '^src/metrics/npa/rust\.rs:\d+:\d+: replace match guard matches!\(parent\.kind_id\(\)\.into\(\), DeclarationList\) with true in rust_count_assoc_const$', # Non-terminating under mutation. The loop then breaks when # `goto_next_sibling` succeeds and repeats when it fails, so a list # with one child is visited forever. Its one caller walks the values diff --git a/docs/development/mutation_testing.md b/docs/development/mutation_testing.md index 98212d0ff..c35380aa6 100644 --- a/docs/development/mutation_testing.md +++ b/docs/development/mutation_testing.md @@ -315,13 +315,17 @@ survive edits elsewhere in the file and to match one mutant: the site, and a pattern pinned to them stops matching after the next one. - Anchor the pattern with `^` and `$`, and escape the mutant's text: the - names are full of `(`, `|`, `+` and `*`. + names are full of `(`, `|`, `+` and `*`. A name that holds a `'`, as + a lifetime does, needs a `'''…'''` string; TOML has no escape for it + inside `'…'`. - Keep the column where another site in the same function carries the same description. A column moves only when its own line is edited. Say in the comment what it distinguishes. - Compare `cargo mutants --list --no-config` with `cargo mutants --list` over the CI selection. The difference must be exactly the mutants the - entries name. + entries name. Check the second command's exit status as well: a file + that does not parse prints an error and an empty list, which reads as + every mutant excluded. - Put the proof above the entry: why no reachable input, panic or side effect tells the mutant from the original, and what would change that. An entry that rests on a grammar's productions names the pin. From 3d7542ff602ed1cf5ecd5733ec048f2decb9a0d4 Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Thu, 12 Nov 2026 16:57:23 -0800 Subject: [PATCH 06/42] test(loc): pin three bare-row helpers no fixture could tell from a mutant MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Four mutants in the bare-row code survived the suite: - `credit_bare_continuation_rows` skips a node with no children or too few rows. With `&&` for the `||` it scans a childless node that spans three rows, reading the node's own bytes as one gap. No fixture held a `\` row inside such a node that an arm did not already make code. A Ruby `=begin` … `=end` block does: the `\` row is comment text, and the mutant reports it as code. - `RowShape::step` reads a byte before the `\` as padding only when it is horizontal space. With the guard `true`, a row holding code before its `\` reads as bare. Through `loc` this shows only on a lone CR before the `\` and on text an error recovery leaves in no node, both of which read blank today, so the test steps the shape directly on rows whose reading is not in doubt. - `BareRowIndex::build` closes a last row that has no newline. With `==` or `>` for the `<` the row is never closed and `class` answers `None` for a bare `\` ending the file. No `loc` value shows it: the C-family grammars hold that `\` in an `ERROR` token, and for `\` + CR, which they leave in padding, the scan's fallback answers code as the index does. The test reads the index itself. Refs #1736 --- src/metrics/loc.rs | 97 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 97 insertions(+) diff --git a/src/metrics/loc.rs b/src/metrics/loc.rs index c5f92b9cf..376d42ec2 100644 --- a/src/metrics/loc.rs +++ b/src/metrics/loc.rs @@ -9448,6 +9448,28 @@ EOF } } + /// A row holding only `\` inside an `=begin` … `=end` block is the + /// comment's own text. The comment is one childless node spanning the + /// row, so it has no gap for the bare-row scan to read, and its bytes + /// are not padding. `ruby -c` accepts the fixture, and Ripper lexes + /// row 1 as `on_embdoc`. + /// + /// expected: rows 0–2 are the block comment and row 3 is code: + /// `(4, 1, 3, 0)`. A scan that reads a childless node's bytes as one + /// gap finds row 1 bare, joins it to `=end` as code, and reports + /// `(4, 2, 3, 0)`. + #[cfg(feature = "ruby")] + #[test] + fn ruby_backslash_row_inside_a_block_comment_is_comment_text() { + let loc = metrics_verbatim( + crate::LANG::Ruby, + b"=begin\n\\\n=end\nx = 1\n", + MetricsOptions::default().with_only(&[crate::Metric::Loc]), + ) + .loc; + assert_eq!(loc_rows(&loc), (4, 1, 3, 0)); + } + /// A bare row continuing the last statement of a method's body is the /// method's code: the `body_statement` runs on past its last child to /// a hidden line break, so the row sits in its trailing padding. @@ -10228,6 +10250,43 @@ EOF } } + /// The row test the gap scan and the C-family index share + /// (`RowShape`): a row is bare when it holds optional padding, one `\` + /// and an optional CR, the `[ \t\v\f]* \ \r?` whose spellings + /// `may_hold_bare_rows` admits. Each row is given without its newline. + /// + /// Stepped directly. Through `loc` the padding test shows only where + /// a gap holds bytes that are no padding: a lone CR before the `\`, or + /// text an error recovery leaves in no node. Both rows read blank + /// today, which no fixture here endorses. Reading any byte before the + /// `\` as padding fails the three rows that hold code before it. + #[test] + fn row_shape_is_bare_for_padding_and_one_backslash_alone() { + for (row, bare) in [ + (&b"\\"[..], true), + (b" \\", true), + (b"\t\x0b\x0c\\", true), + (b"\\\r", true), + (b" \\\r", true), + // Code before the `\`: a continued row, not a bare one. + (b"x \\", false), + (b"int x = 1 + \\", false), + (b"x \\\r", false), + // No `\`, more than one, or one that does not end the row. + (b"", false), + (b" ", false), + (b"\\\\", false), + (b"\\ ", false), + (b"\\x", false), + (b"\\\r\r", false), + ] { + let shape = row + .iter() + .fold(RowShape::default(), |shape, &byte| shape.step(byte)); + assert_eq!(shape.is_bare(), bare, "{:?}", String::from_utf8_lossy(row)); + } + } + /// A no-`\` fixture and its twin holding one bare row, per grammar /// with a `Loc::bare_rows` policy: the first skips the /// scan (no `bare_row_scans` recorded) and the second runs it, and @@ -10566,6 +10625,44 @@ EOF ); } + /// The index closes the file's last row when no newline does: a bare + /// `\` ending the file is a row of it, and one the scan credits where + /// the root's trailing padding holds it. + /// + /// Read from the index itself, since no `loc` value shows the row + /// missing: the grammars hold a `\` ending the file in an `ERROR` + /// token, which the scan never asks about, and for the `\` + CR + /// spelling, which they leave in padding, the scan's own reading + /// answers code as the index does. + /// + /// expected: `int x;` / `\` — row 0 is not bare; row 1 is, and its `\` + /// splices nothing, a stray token, so its line holds code. The same + /// with a CR after it. With the newline, the control, the `\` is + /// spliced and the line it starts holds nothing: blank, and the file + /// has no row 2. + #[cfg(feature = "c")] + #[test] + fn c_family_bare_row_index_closes_a_last_row_with_no_newline() { + let classes = |source: &[u8]| { + let ast = crate::Ast::parse(crate::Source::new(crate::LANG::C, source)) + .expect("the c feature is enabled"); + let index = continuation::BareRowIndex::build( + &ast.root_node(), + source, + crate::roles::c::comment::lists_kind, + ); + [0, 1, 2].map(|row| match index.class(row) { + None => "not bare", + Some(BareRow::Code) => "code", + Some(BareRow::Comment) => "comment", + Some(BareRow::Blank) => "blank", + }) + }; + assert_eq!(classes(b"int x;\n\\"), ["not bare", "code", "not bare"]); + assert_eq!(classes(b"int x;\n\\\r"), ["not bare", "code", "not bare"]); + assert_eq!(classes(b"int x;\n\\\n"), ["not bare", "blank", "not bare"]); + } + /// The orphan `heredoc_body` — the shape that makes routing the /// wrapper an *addition* rather than a replacement. /// From 8d46621deb8cbc98622bf10e57971aa368c2718e Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Thu, 12 Nov 2026 16:58:02 -0800 Subject: [PATCH 07/42] test(loc): pin the bare row that joins a comment a NUL cuts short `only_comments_after` decides whether the row a bare `\` row joins is comment text to its end. Six of its mutants survived: returning `true` outright, the three comparisons of the comment's end row against its start row, and the sibling guard read as `true` or with `||`. Every comment in the grammars that reach it runs to its row's end, so the answer was `true` for every fixture. The one input on which it is not is a comment token the lexer ends at a NUL byte, which the tree follows with an `ERROR`. Two fixtures use it, and four of the six no longer survive: - Python, `\` / `# c` NUL: the joined row holds a token that is no comment, so the bare row is code. Returning `true`, and the end row read as `>=` or `==` the start row, read it as a comment. CPython rejects a NUL byte, so this pins the recovery reading only, as the table's `\` + NUL row does. - Ruby, `\` / `=begin` / `=end` NUL: the comment runs past the row the bare row joins, so the bare row is a comment whatever follows `=end`. The end row read as `<` or `==` the start row goes on to the `ERROR` and reads code. Only `sloc` and `cloc` are asserted: `ruby` agrees with both, and reads the NUL as comment text where `ploc` counts its row as code. The two guard mutants are left alive. Only a sibling after a NUL-cut `#` comment tells them from the original, which the Bash, Ruby and Elixir trees hold. bash 5.1 and ruby 3.0 read the NUL as comment text (no Elixir was at hand), so the fixture would pin a value the interpreter contradicts. Refs #1736 --- src/metrics/loc.rs | 56 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) diff --git a/src/metrics/loc.rs b/src/metrics/loc.rs index 376d42ec2..3fb175f3e 100644 --- a/src/metrics/loc.rs +++ b/src/metrics/loc.rs @@ -9470,6 +9470,32 @@ EOF assert_eq!(loc_rows(&loc), (4, 1, 3, 0)); } + /// A block comment runs past the row a bare row above it joins, so + /// that row is comment text to its end and the bare row is a comment, + /// whatever follows `=end`. Something can follow it only where a NUL + /// byte ends the comment token: the grammar's `=end.*` stops there, and + /// the tree recovers with an `ERROR` token after the comment. + /// `ruby -c` accepts the fixture, and Ripper lexes row 0 as space and + /// rows 1 and 2, the NUL included, as the comment. + /// + /// expected: row 0 (`\`) joins row 1 (`=begin`), a comment row, as + /// row 2 (`=end` + NUL) is, and row 3 is code: sloc 4, cloc 3. + /// Reading on from the comment's end to the `ERROR` makes the bare row + /// code, cloc 2. ploc is not asserted: the row holding the NUL reads + /// as code too, 2 where `ruby` has 1. + #[cfg(feature = "ruby")] + #[test] + fn ruby_bare_row_joining_a_block_comment_is_a_comment_whatever_follows_its_end() { + let loc = metrics_verbatim( + crate::LANG::Ruby, + b"\\\n=begin\n=end\0\nx = 1\n", + MetricsOptions::default().with_only(&[crate::Metric::Loc]), + ) + .loc; + assert_eq!(loc.sloc(), 4); + assert_eq!(loc.cloc(), 3, "the bare row joins the comment's first row"); + } + /// A bare row continuing the last statement of a method's body is the /// method's code: the `body_statement` runs on past its last child to /// a hidden line break, so the row sits in its trailing padding. @@ -10146,6 +10172,36 @@ EOF ); } + /// The one shape in which the `#` comment a bare row joins is not the + /// rest of its row: the comment token stops at a NUL byte, and the + /// tree recovers with an `ERROR` token after it. CPython rejects a NUL + /// byte outright ("source code string cannot contain null bytes"), so + /// no tokenizer stream derives the value: like the `\` + NUL row of + /// `python_bare_continuation_rows_are_the_line_they_join`, it pins the + /// recovery reading only. + /// + /// expected: the comment's row also holds the `ERROR`, a token that is + /// no comment, so it is code carrying a comment, as it reads with no + /// bare row above it: `(2, 2, 1, 0)`. The bare row that starts its + /// line is code too: `(3, 3, 1, 0)`. Reading the line as its comment + /// alone moves the bare row from ploc to cloc, `(3, 2, 2, 0)`. + #[cfg(feature = "python")] + #[test] + fn python_bare_row_joining_a_comment_a_nul_cuts_short_is_code() { + let rows = |source: &[u8]| { + loc_rows( + &metrics_verbatim( + crate::LANG::Python, + source, + MetricsOptions::default().with_only(&[crate::Metric::Loc]), + ) + .loc, + ) + }; + assert_eq!(rows(b"# c\0\nx = 1\n"), (2, 2, 1, 0)); + assert_eq!(rows(b"\\\n# c\0\nx = 1\n"), (3, 3, 1, 0)); + } + /// Two bare rows under two parents, `class_definition` and /// `function_definition`, each credited to the space it sits in. /// From d38d32f02048ed5cf68912d45814dfe44feec10b Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Thu, 12 Nov 2026 17:18:35 -0800 Subject: [PATCH 08/42] ci(mutation): exclude ten loc row-scan mutants no test can kill Eight are equivalent and two never terminate; each entry carries its reason. Two of the equivalents rest on the code alone: `BareRowIndex::build` with `<=` differs only for an empty last row, and the `>=` in `add_cloc_lines` sits behind a test that already makes `diff` positive. The other six rest on one fact about the grammars whose bare rows reach the gap scan: a `comment` is a childless terminal that ends only before a newline, a NUL or the end of the file. It was read from each pinned lexer and backed by a differential run over generated sources, malformed ones included. The two timeouts from run 43278927651 are loops that stop making progress: `comment_spans` re-reads the same node, and `past_line_padding` is sent back to the start of the source. `opens_comment_only_line` has a live `==` beside the equivalent one, so that entry keeps the column. The list differs from the unconfigured one by exactly these ten and the nine earlier entries. Refs #1736 --- .cargo/mutants.toml | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/.cargo/mutants.toml b/.cargo/mutants.toml index b0c401e6e..23f0aa9ad 100644 --- a/.cargo/mutants.toml +++ b/.cargo/mutants.toml @@ -78,6 +78,45 @@ exclude_re = [ # of an `impl_item` or a `trait_item`, so once the grandparent matches # the guard on the parent is true. Both arms of the function. '^src/metrics/npa/rust\.rs:\d+:\d+: replace match guard matches!\(parent\.kind_id\(\)\.into\(\), DeclarationList\) with true in rust_count_assoc_const$', + # Equivalent. `<=` differs only when the last row starts at the end + # of the file, where the row is empty: its shape is blank, it pushes + # one `None` and leaves nothing pending, as the original does. + '^src/metrics/loc/continuation\.rs:\d+:\d+: replace < with <= in BareRowIndex::build$', + # Equivalent. The branch is reached only when `after && diff == 0` is + # false, so with `after` true `diff` is positive and both spellings + # read `after`. + '^src/metrics/loc/shared\.rs:\d+:\d+: replace > with >= in add_cloc_lines$', + # The next five rest on one fact about the grammars whose bare rows + # reach the gap scan (Bash, Tcl, iRules, Ruby, Elixir, Python; the C + # family answers every row from its index): `comment` is a childless + # terminal that ends only before a newline, a NUL or the end of the + # file. Read from each pinned grammar's lexer, and re-derived on a + # bump. A differential run over close to a million generated sources, + # malformed ones included, showed no output difference for any of them. + # + # `holder_of`: where the mutant answers a node and the original none, + # that node has children, or is one no comment can end against, so + # `in_comment` reads false either way. `<=` is both boundary tests. + '''^src/metrics/loc/shared\.rs:\d+:\d+: replace && with \|\| in GapScan<'_, 'a>::holder_of$''', + '''^src/metrics/loc/shared\.rs:\d+:\d+: replace < with <= in GapScan<'_, 'a>::holder_of$''', + # The sibling step of `only_comments_after` runs only for a comment a + # NUL cuts short. No comment starts at a NUL, so its guard is never + # true and the sibling list feeding it is never read; the NUL is a + # leaf of its own, so a next sibling starts exactly at `after`. + # `opens_comment_only_line` has a second, live `==` at column 33; the + # column is what tells this one from it. + '^src/metrics/loc/shared\.rs:\d+:37: replace == with != in opens_comment_only_line$', + '^src/metrics/loc/shared\.rs:\d+:\d+: replace match guard sibling\.start_byte\(\) == after && comments\.lists\(sibling\) with false in only_comments_after$', + '^src/metrics/loc/shared\.rs:\d+:\d+: replace == with != in only_comments_after$', + # Non-terminating under mutation. With `||` a node that is not a + # comment short-circuits past `goto_first_child`, and the `continue` + # reads the same node again; the root is never a comment, so every + # `BareRowIndex::build` spins on its first step. + '^src/metrics/loc/continuation\.rs:\d+:\d+: replace && with \|\| in comment_spans$', + # Non-terminating under mutation. `past_line_padding` re-reads its + # position through this function; answering 0 for a source that opens + # with a backslash and a newline sends it back to the start for ever. + '^src/metrics/loc/shared\.rs:\d+:\d+: replace past_horizontal_space -> usize with 0$', # Non-terminating under mutation. The loop then breaks when # `goto_next_sibling` succeeds and repeats when it fails, so a list # with one child is visited forever. Its one caller walks the values From 739fd3bafc16cf571b3938abc001eed951ed9e40 Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Thu, 12 Nov 2026 18:18:34 -0800 Subject: [PATCH 09/42] test(loc): cover the descent level of a Python bare run after a docstring `python_backslash_after_bare_string` records the deepest level, on the descent from the run's previous sibling to the bare string statement, that has a token before its node, and `python_code_before_string` reads that token. Three mutants of its `child_count() > 1` test survived the full mutation run at 68b70b08: `>` replaced by `<`, by `==` and by `>=` (src/metrics/loc/python.rs:561:34). No fixture put code on a level of that descent. Each one had the code beside the statement or the run (`x=1; """doc""" \`), or left the compound statement's header on a row of its own, where the answer is "no code" whether or not the level is read. The new fixtures put the docstring on its header's row (`if x: """doc""" \`) and after `pass;` inside the block. The first has a one-child `block`, so it sits exactly on the `>` / `>=` boundary. Refs #1736 --- src/metrics/loc.rs | 47 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) diff --git a/src/metrics/loc.rs b/src/metrics/loc.rs index 3fb175f3e..f2132129c 100644 --- a/src/metrics/loc.rs +++ b/src/metrics/loc.rs @@ -10157,6 +10157,53 @@ EOF } } + /// A bare run continuing a docstring's `\` where the docstring shares + /// its row with the header of the compound statement it ends: the + /// sibling before the run is the `if_statement`, and the code before + /// the string is a token of a level the descent to the statement + /// passes — the `if`'s `:` before its `block`, or the `;` before the + /// statement inside the `block`. Every other fixture either puts that + /// code beside the statement or the run (`x=1; """doc""" \`), or + /// leaves the header on a row of its own, where the answer is "no + /// code" whether or not the descent's level is read. + /// + /// expected: `NAME NAME OP STRING NEWLINE NAME OP NUMBER NEWLINE` — + /// the run is on the logical line `if x: """doc"""`, which holds + /// code, so it is that code's: rows `if x: """doc""" \` (code + /// carrying the string's comment row, #415), the bare row (code), + /// the empty row (blank) and `y = 2` (code), `(4, 3, 1, 1)`. The + /// `block` here has exactly one child, so the level recorded for + /// the descent must be the `if_statement`'s, the deepest one with a + /// token before its node; reading the run as the string's line + /// instead gives `(4, 2, 2, 1)`. `NAME NAME OP NEWLINE INDENT NAME OP + /// STRING NEWLINE DEDENT NAME OP NUMBER NEWLINE` — `pass;` precedes + /// the string inside a three-child `block`, the deepest level: + /// `if x:` (code), `pass; """doc""" \` (code carrying a comment), the + /// bare row (code), the empty row (blank), `y = 2` (code), + /// `(5, 4, 1, 1)`; as the string's line, `(5, 3, 2, 1)`. + #[cfg(feature = "python")] + #[test] + fn python_bare_run_after_a_docstring_on_its_headers_row_is_code() { + let rows = |source: &[u8]| { + loc_rows( + &metrics_verbatim( + crate::LANG::Python, + source, + MetricsOptions::default().with_only(&[crate::Metric::Loc]), + ) + .loc, + ) + }; + assert_eq!( + rows(b"if x: \"\"\"doc\"\"\" \\\n\\\n\ny = 2\n"), + (4, 3, 1, 1) + ); + assert_eq!( + rows(b"if x:\n pass; \"\"\"doc\"\"\" \\\n\\\n\ny = 2\n"), + (5, 4, 1, 1) + ); + } + /// A bare row under an `if_statement`, joining a comment before an /// empty row: the comment is the line's whole text, and the empty row /// stays blank. From bd90da64fcdcdebb76555f95e486b0e9d96d06d4 Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Thu, 12 Nov 2026 18:18:34 -0800 Subject: [PATCH 10/42] test(loc): cover the multi-row string arms of five languages Deleting the string arm survived the full mutation run at 68b70b08 in five `Loc` impls: Java and Groovy (`string_literal`), Rust (`string_literal | raw_string_literal`), TypeScript and TSX (`template_string`). `multiline_string_ploc_consistent_across_languages` has no row for any of them, and their other fixtures hold literals of one or two rows, which the opening and closing tokens credit without the arm. Each new test mirrors that table's shape: a three-row literal whose interior row is empty, so only the arm credits it. A Java text block opens with a line terminator and is one row longer. Rust and Groovy assert both spellings their arm routes. Refs #1736 --- src/metrics/loc.rs | 134 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 134 insertions(+) diff --git a/src/metrics/loc.rs b/src/metrics/loc.rs index f2132129c..2d60c3901 100644 --- a/src/metrics/loc.rs +++ b/src/metrics/loc.rs @@ -4890,6 +4890,32 @@ line two ); } + /// Java's row of `multiline_string_ploc_consistent_across_languages` + /// (#778): a text block's interior rows are code. Its + /// `multiline_string_fragment` is one node from the opening `"""` to + /// the closing one, so no node starts on an interior row and only the + /// `string_literal` arm credits it. A text block opens with a line + /// terminator, so the shape is one row longer than the quoted form's; + /// one interior row holds text and one is empty. + #[cfg(feature = "java")] + #[test] + fn java_text_block_interior_rows_are_ploc() { + check_metrics::( + "class A { String s = \"\"\"\nline1\n\nline3\"\"\"; }", + "foo.java", + |metric| { + // expected: four rows — the opening `"""` row, `line1`, + // the empty row and the closing row — all code. Left to + // the catch-all, the literal credits its opening row + // alone and both interior rows read blank: ploc 2. + assert_eq!(metric.loc.sloc(), 4); + assert_eq!(metric.loc.ploc(), 4); + assert_eq!(metric.loc.cloc(), 0); + assert_eq!(metric.loc.blank(), 0); + }, + ); + } + #[cfg(feature = "go")] #[test] fn go_general_loc() { @@ -11507,6 +11533,27 @@ EOF ); } + /// TypeScript's row of + /// `multiline_string_ploc_consistent_across_languages` (#778): a + /// template string's interior row is code. Its `string_fragment` is + /// one node from the opening backtick to the closing one, so no node + /// starts on the interior row and only the `template_string` arm + /// credits it. The middle row is empty, as in that table. + #[cfg(feature = "typescript")] + #[test] + fn typescript_template_string_interior_rows_are_ploc() { + check_metrics::("const s = `line1\n\nline3`;", "foo.ts", |metric| { + // expected: three rows — the opening backtick's, the empty + // interior one and the closing backtick's — all code. Left + // to the catch-all, the literal credits its opening row + // alone and the interior row reads blank: ploc 2, blank 1. + assert_eq!(metric.loc.sloc(), 3); + assert_eq!(metric.loc.ploc(), 3); + assert_eq!(metric.loc.cloc(), 0); + assert_eq!(metric.loc.blank(), 0); + }); + } + #[cfg(feature = "typescript")] #[test] fn tsx_blank() { @@ -11821,6 +11868,26 @@ EOF ); } + /// TSX's row of `multiline_string_ploc_consistent_across_languages` + /// (#778), the twin of + /// `typescript_template_string_interior_rows_are_ploc`: TSX carries + /// its own copy of the `template_string` arm, which only a `.tsx` + /// source routes to. + #[cfg(feature = "typescript")] + #[test] + fn tsx_template_string_interior_rows_are_ploc() { + check_metrics::("const s = `line1\n\nline3`;", "foo.tsx", |metric| { + // expected: three rows — the opening backtick's, the empty + // interior one and the closing backtick's — all code. Left + // to the catch-all, the literal credits its opening row + // alone and the interior row reads blank: ploc 2, blank 1. + assert_eq!(metric.loc.sloc(), 3); + assert_eq!(metric.loc.ploc(), 3); + assert_eq!(metric.loc.cloc(), 0); + assert_eq!(metric.loc.blank(), 0); + }); + } + #[cfg(feature = "php")] #[test] fn php_blank() { @@ -12693,6 +12760,40 @@ $y = 10 + match ($x) { 1 => 2, default => 0 };", ); } + /// Rust's row of `multiline_string_ploc_consistent_across_languages` + /// (#778), for both kinds its arm routes: the interior row of a + /// `string_literal` and of a `raw_string_literal` is code. Each + /// literal's `string_content` is one node from the opening quote to + /// the closing one, so no node starts on the interior row and only + /// the arm credits it. The middle row is empty, as in that table. + /// The two-row literals of `multiline_string_gate_fixture` have no + /// such row: their closing row holds the closing quote. + #[cfg(feature = "rust")] + #[test] + fn rust_multiline_string_interior_rows_are_ploc() { + // expected: three rows — the opening quote's, the empty interior + // one and the closing quote's — all code. Left to the catch-all, + // a literal credits its opening row alone and the interior row + // reads blank: ploc 2, blank 1. + #[allow(clippy::needless_pass_by_value)] + fn assert_three_code_rows(metric: crate::CodeMetrics) { + assert_eq!(metric.loc.sloc(), 3); + assert_eq!(metric.loc.ploc(), 3); + assert_eq!(metric.loc.cloc(), 0); + assert_eq!(metric.loc.blank(), 0); + } + check_metrics::( + "const S: &str = \"line1\n\nline3\";", + "foo.rs", + assert_three_code_rows, + ); + check_metrics::( + "const S: &str = r#\"line1\n\nline3\"#;", + "foo.rs", + assert_three_code_rows, + ); + } + #[cfg(feature = "elixir")] #[test] fn elixir_blank() { @@ -13842,6 +13943,39 @@ class A { ); } + /// Groovy's row of `multiline_string_ploc_consistent_across_languages` + /// (#778), for both triple-quoted spellings: the interior row of a + /// `"""…"""` and of a `'''…'''` literal is code. Each literal's + /// `string_fragment` is one node from the opening quotes to the + /// closing ones, so no node starts on the interior row and only the + /// `string_literal` arm credits it. The middle row is empty, as in + /// that table. + #[cfg(feature = "groovy")] + #[test] + fn groovy_multiline_string_interior_rows_are_ploc() { + // expected: three rows — the opening quotes', the empty interior + // one and the closing quotes' — all code. Left to the catch-all, + // a literal credits its opening row alone and the interior row + // reads blank: ploc 2, blank 1. + #[allow(clippy::needless_pass_by_value)] + fn assert_three_code_rows(metric: crate::CodeMetrics) { + assert_eq!(metric.loc.sloc(), 3); + assert_eq!(metric.loc.ploc(), 3); + assert_eq!(metric.loc.cloc(), 0); + assert_eq!(metric.loc.blank(), 0); + } + check_metrics::( + "def s = \"\"\"line1\n\nline3\"\"\"", + "foo.groovy", + assert_three_code_rows, + ); + check_metrics::( + "def s = '''line1\n\nline3'''", + "foo.groovy", + assert_three_code_rows, + ); + } + #[cfg(feature = "csharp")] #[test] fn csharp_local_function_in_method_lloc() { From 683160df6bd139f40c043e501991ddf108534faf Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Thu, 12 Nov 2026 18:18:34 -0800 Subject: [PATCH 11/42] test(loc): cover Mozcpp's for-header gate and Groovy's closure carve-out MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Two mutants survived the full mutation run at 68b70b08. src/metrics/loc/mozcpp.rs:58:43 replaces `==` with `!=` in the stop predicate of the for-header gate. Mozcpp owns no file extension, so no C++ fixture routes to its copy of the gate, and no test named `MozcppParser` with a declaration in a `for` header. src/metrics/loc/groovy.rs:61:36 replaces the bare-`Closure` guard with `false`. The grammar now parses an `else { … }` branch as a `block`, so `groovy_general_loc`, which was written for that shape, no longer reaches the carve-out. A labelled block still parses as `expression_statement (closure)` and is the new fixture. Refs #1736 --- src/metrics/loc.rs | 53 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) diff --git a/src/metrics/loc.rs b/src/metrics/loc.rs index 2d60c3901..c8fc61650 100644 --- a/src/metrics/loc.rs +++ b/src/metrics/loc.rs @@ -2538,6 +2538,33 @@ mod tests { ); } + /// Mozcpp's copy of the C-family for-header gate, which no fixture + /// reached: Mozcpp owns no file extension, so the C++ tests never + /// route to it (mirrors `objc_no_declaration_in_for_header_lloc`). + /// The `int i = 0` declaration in the header is part of the `for` + /// statement's logical line; `int x = i;` in the body is a line of + /// its own, because the `compound_statement` between it and the + /// `for` ends the header. + #[cfg(feature = "mozcpp")] + #[test] + fn mozcpp_no_declaration_in_for_header_lloc() { + check_metrics::( + "void f() { + for (int i = 0; i < 10; ++i) { + int x = i; + } + }", + "foo.cpp", + |metric| { + // expected: for-statement (1) + body declaration + // `int x = i;` (1) = 2. Without the gate the header + // declaration counts too, 3; a gate that stopped at no + // `compound_statement` would drop the body's, 1. + assert_eq!(metric.loc.lloc(), 2); + }, + ); + } + #[cfg(feature = "cpp")] #[test] fn cpp_while_lloc() { @@ -13667,6 +13694,32 @@ class A { ); } + /// A labelled block, Groovy's spelling of an anonymous code block, + /// parses as `labeled_statement (expression_statement (closure))`: + /// the braces are a grouping, as Java's `block` is, and the wrapper + /// is no statement of its own. The bare-`Closure` carve-out still + /// meets this shape; the grammar now parses an `else { … }` branch + /// as a `block`, so `groovy_general_loc` no longer reaches the + /// carve-out. + #[cfg(feature = "groovy")] + #[test] + fn groovy_labelled_block_wrapper_is_not_a_logical_line() { + check_metrics::( + "void f() { + scope: { + a() + } + }", + "foo.groovy", + |metric| { + // expected: the call `a()` (1) = 1. Neither the label nor + // the `expression_statement` wrapping the braces counts; + // counting the wrapper gives 2. + assert_eq!(metric.loc.lloc(), 1); + }, + ); + } + #[cfg(feature = "groovy")] #[test] fn groovy_try_lloc() { From 5cb2a9ef8606fbaf6ee8ffd5fc3115049b016542 Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Thu, 12 Nov 2026 18:18:35 -0800 Subject: [PATCH 12/42] test(nargs): tell a Go parameter's names from its other children `compute_go_args` counts the `identifier` children of each `parameter_declaration`. Replacing `==` with `!=` in that filter (src/metrics/nargs.rs:479:41) survived the full mutation run at 68b70b08. No fixture told the two counts apart: a declaration holds as many names as other children (`a, b int` is two names, one comma and one type), and an unnamed parameter reads 1 through `.max(1)` either way. A comment inside the declaration is a child that is neither a name nor a parameter, so the new fixture holds two. Refs #1736 --- src/metrics/nargs.rs | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/src/metrics/nargs.rs b/src/metrics/nargs.rs index 8adf553e9..33555fc4c 100644 --- a/src/metrics/nargs.rs +++ b/src/metrics/nargs.rs @@ -2194,6 +2194,27 @@ mod tests { ); } + /// A comment between a parameter's names, or between a name and its + /// type, is a child of the `parameter_declaration` and no parameter. + /// In the other Go fixtures here a declaration holds as many names as + /// other children — `a, b int` is two names, one comma and one type — + /// so counting the children that are not names reads the same. + #[cfg(feature = "go")] + #[test] + fn go_comment_in_parameter_declaration_is_no_parameter() { + check_metrics::( + "package main + func f(a /* width */ int, b, /* height */ c int) {}", + "foo.go", + |metric| { + // expected: `a` (1) + `b, c` (2) = 3. The children that + // are not names — a comment and a type, then a comma, a + // comment and a type — are 2 + 3 = 5. + assert_eq!(metric.nargs.function_args_sum(), 3); + }, + ); + } + #[cfg(feature = "go")] #[test] fn go_func_literal_args() { From c0b57d288e8588e83c44fc046abd79a843338824 Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Thu, 12 Nov 2026 18:18:35 -0800 Subject: [PATCH 13/42] test(loc): pin three guards that only recovery input separates Three mutants survived the full mutation run at 68b70b08. src/metrics/loc/lua.rs:46:20 replaces the comment-parent guard of the `[[` / `]]` arm with `true`. No valid Lua shows that guard: in a well-formed `string` both bracket rows are credited by the string's arm or its parent, whatever the bracket arm does. src/metrics/loc/python.rs:475:17 replaces `&&` with `||` in `python_past_string_parentheses`, and python.rs:675:17 does the same in `python_code_among`. Both tell a bare string's own parenthesis from any other, and in source that parses cleanly every parenthesis around a bare string is its own. The fixtures are recovery shapes: a stray `]]` that tree-sitter-lua leaves as a child of an `ERROR`, and Python parentheses that hold an `ERROR` before the string and so are not the string's. Each test asserts the recovered shape first, so a grammar bump that recovers differently fails as "fixture drift" rather than as a wrong number. The expected rows follow the documented reading (a token outside a comment is code; a parenthesis that is not the string's is code), not a language rule. Not pinned: python.rs:475:17 also differs where a lone CR sits between the bare run and the string's `)`. CPython reads that CR as a line break and the source as one docstring statement, and there the mutant gives the comment rows and the original one code row. Refs #1736 --- src/metrics/loc.rs | 106 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 106 insertions(+) diff --git a/src/metrics/loc.rs b/src/metrics/loc.rs index c8fc61650..afa6a5bbc 100644 --- a/src/metrics/loc.rs +++ b/src/metrics/loc.rs @@ -6415,6 +6415,51 @@ end", ); } + /// A `]]` that closes no comment is code. The `[[` / `]]` arm skips + /// the brackets only under a `comment`. In a well-formed `string` + /// both of their rows are credited whatever that arm does — the + /// opening one by the string's arm or its parent, the closing one as + /// the literal's last row — so no valid source shows the guard. + /// Recovery does: where no token fits before a `]]`, the scanner + /// hands back the padding as `string_content` and the `]]` as a + /// block-string end, both direct children of the `ERROR`, with no + /// `string` around them. The source does not compile, so this pins + /// the recovery reading only + /// (`docs/development/grammar_dispatch.md` §6). + /// + /// expected: three rows, each holding a token outside any comment — + /// `x = (`, the stray `]]`, and `)` — so every row is code. Reading + /// the `]]` as a comment's bracket credits its row to nothing, and + /// the row falls to `blank`: ploc 2, blank 1. + #[cfg(feature = "lua")] + #[test] + fn lua_closing_bracket_outside_a_comment_is_code() { + const SOURCE: &str = "x = (\n]]\n)\n"; + let ast = crate::test_support::parse_named(crate::LANG::Lua, "foo.lua", SOURCE); + let root = ast.root_node(); + let brackets = root.descendants_by_kind(&["]]"]); + assert_eq!(brackets.len(), 1, "fixture drift: expected one `]]`"); + assert_eq!( + ( + brackets[0].start_row(), + brackets[0].parent().map(|parent| parent.kind()) + ), + (1, Some("ERROR")), + "fixture drift: the `]]` must open row 1 as a child of the `ERROR`" + ); + + let loc = metrics_verbatim( + crate::LANG::Lua, + SOURCE.as_bytes(), + MetricsOptions::default().with_only(&[crate::Metric::Loc]), + ) + .loc; + assert_eq!(loc.sloc(), 3); + assert_eq!(loc.ploc(), 3); + assert_eq!(loc.cloc(), 0); + assert_eq!(loc.blank(), 0); + } + #[cfg(feature = "lua")] #[test] fn lua_no_functiondefinition_lloc() { @@ -10302,6 +10347,67 @@ EOF assert_eq!(rows(b"\\\n# c\0\nx = 1\n"), (3, 3, 1, 0)); } + /// Parentheses that hold a token before the string are not the + /// string's own: a parenthesis's value is read as its first named + /// child that is no comment or `\`, and here that is the `ERROR` + /// recovery leaves for a stray `:`. The `string` is still a bare + /// string statement's — its statement holds one value — so its row + /// is a comment row (#415), while the walk bills each parenthesis + /// as code, and a bare run beside one is that code's. In source + /// that parses cleanly every parenthesis around a bare string is + /// the string's, so only this shape tells "the string's + /// parenthesis" from "a parenthesis". CPython rejects both sources, + /// so no tokenizer stream derives the values: they pin the recovery + /// reading only (`docs/development/grammar_dispatch.md` §6). + /// + /// expected: `( :` (code), `"""doc""" \` (the string's comment row), + /// the bare row, `)` (code). The run is on the string's line and + /// joins a `)` that is not the string's, a token like any other, so + /// it is code: `(4, 3, 1, 0)`. Stepping over that `)` as the + /// string's own reads the run as the string's line, `(4, 2, 2, 0)`. + /// + /// expected: `( :` (code), `("""doc""" \` (code carrying the string's + /// comment row), the bare row, `# c` (comment), `))` (code). The + /// inner `(` is code before the string on its row, so the run is + /// that code's whatever it joins: `(5, 4, 2, 0)`. Skipping the `(` + /// as the string's own finds no code before the string — the `:` is + /// on the row above — and the run joins the comment, `(5, 3, 3, 0)`. + #[cfg(feature = "python")] + #[test] + fn python_bare_run_beside_a_parenthesis_that_is_not_the_strings_is_code() { + for (source, expected) in [ + ("( :\n\"\"\"doc\"\"\" \\\n\\\n)\n", (4, 3, 1, 0)), + ("( :\n(\"\"\"doc\"\"\" \\\n\\\n# c\n))\n", (5, 4, 2, 0)), + ] { + let ast = crate::test_support::parse_named(crate::LANG::Python, "foo.py", source); + let root = ast.root_node(); + let errors = root.descendants_by_kind(&["ERROR"]); + let strings = root.descendants_by_kind(&["string"]); + assert_eq!( + (errors.len(), strings.len()), + (1, 1), + "fixture drift: {source:?} must hold one `ERROR` and one `string`" + ); + assert_eq!( + errors[0].parent().map(|parent| parent.kind()), + Some("parenthesized_expression"), + "fixture drift: {source:?} must keep the `ERROR` inside the parentheses" + ); + assert!( + errors[0].end_byte() <= strings[0].start_byte(), + "fixture drift: {source:?} must keep the `ERROR` before the string" + ); + + let loc = metrics_verbatim( + crate::LANG::Python, + source.as_bytes(), + MetricsOptions::default().with_only(&[crate::Metric::Loc]), + ) + .loc; + assert_eq!(loc_rows(&loc), expected, "{source:?}"); + } + } + /// Two bare rows under two parents, `class_definition` and /// `function_definition`, each credited to the space it sits in. /// From cefb8f175e6cea1f464952eded8830dc2e03d3bf Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Thu, 12 Nov 2026 18:22:05 -0800 Subject: [PATCH 14/42] ci(mutation): exclude five mutants that select between equal values `FunctionPopulation::fold` and `merge` each compare a candidate with the running minimum and maximum; `<=` and `>=` differ from `<` and `>` only when the two are equal, and then pick the other of two equal values. No population can hold the one distinguishable pair, a negative and a positive zero. `classify_python_run`'s guard reads a constant that is false, so replacing it with `false` changes nothing. The configured list differs from the unconfigured one by exactly these five and the nineteen earlier entries. Refs #1736 --- .cargo/mutants.toml | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/.cargo/mutants.toml b/.cargo/mutants.toml index 23f0aa9ad..415be65a7 100644 --- a/.cargo/mutants.toml +++ b/.cargo/mutants.toml @@ -117,6 +117,17 @@ exclude_re = [ # position through this function; answering 0 for a source that opens # with a backslash and a newline sends it back to the start for ever. '^src/metrics/loc/shared\.rs:\d+:\d+: replace past_horizontal_space -> usize with 0$', + # Equivalent. `PYTHON_COMMENTS` is a constant whose `continued` is + # false, so the guard reads false for every input before the mutant + # says so. + '^src/metrics/loc/python\.rs:\d+:\d+: replace match guard in_comment && PYTHON_COMMENTS\.continued with false in classify_python_run$', + # Equivalent. Each differs only when the two values compared are + # equal, and then keeps or assigns the other of two equal values. The + # one pair that is equal and distinguishable is `+0.0` and `-0.0`, + # and no population folds a negative zero: a `usize` has none, and + # every `f64` folded starts at 1 and only grows. + '^src/metrics/mod\.rs:\d+:\d+: replace < with <= in FunctionPopulation::(fold|merge)$', + '^src/metrics/mod\.rs:\d+:\d+: replace > with >= in FunctionPopulation::(fold|merge)$', # Non-terminating under mutation. The loop then breaks when # `goto_next_sibling` succeeds and repeats when it fails, so a list # with one child is visited forever. Its one caller walks the values From baa82d646a6ef19955528fc1a0f435c24e388a91 Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Thu, 12 Nov 2026 19:05:27 -0800 Subject: [PATCH 15/42] test(abc): pin that a C-family compound assignment is not peeled One mutant survived the full mutation run at 68b70b08. src/metrics/abc/cpp.rs:69:36 replaces the `operator_is(&["="])` guard of `cpp_wrapper_operand` with `true`, so a compound assignment is peeled to its right-hand side as a plain `=` is. No fixture put a compound assignment whose right-hand side scores itself in a condition slot: `if (y += 1)` pays one condition peeled or not, and the rows of `slot_pays_tests.rs` hold `y += 1` and `y = b > 1` but not their cross. `if (y += x > 1)` is that cross. The slot tests the updated `y`, so it pays beside the `>`; under the mutant only the `>` pays. Refs #1736 --- src/metrics/abc.rs | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/src/metrics/abc.rs b/src/metrics/abc.rs index 6a551699e..77d13050c 100644 --- a/src/metrics/abc.rs +++ b/src/metrics/abc.rs @@ -13150,6 +13150,31 @@ end ); } + #[cfg(feature = "cpp")] + #[test] + fn cpp_compound_assignment_in_a_slot_is_not_peeled_to_its_value() { + // A plain `=` evaluates to its right-hand side, so the slot + // holding `y = x > 2` tests the comparison the `>` arm already + // counted. A compound assignment yields the updated `y`, a + // value of its own: the slot pays beside the `>`. Only a + // right-hand side that scores itself tells the two apart; + // `if (y += 1)` reads 1 either way. + // expected: `y += x > 1` is the `>` (+1) and the slot (+1); + // `y = x > 2` is the `>` (+1) alone: 3 conditions. Two + // assignment expressions: 2 assignments. + check_metrics::( + "void f(int x, int y) {\n\ + \x20 if (y += x > 1) {} // +1a +2c\n\ + \x20 if (y = x > 2) {} // +1a +1c\n\ + }\n", + "foo.cpp", + |metric| { + assert_eq!(metric.abc.assignments_sum(), 2); + assert_eq!(metric.abc.conditions_sum(), 3); + }, + ); + } + #[cfg(feature = "cpp")] #[test] fn cpp_if_constexpr_condition_counts() { From 09a5e846773fe3c5137d1c015c3bbf35783fa8db Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Thu, 12 Nov 2026 19:05:27 -0800 Subject: [PATCH 16/42] test(abc): pin the C# null-forgiving peel and the preprocessor's fields Two mutants survived the full mutation run at 68b70b08. src/metrics/abc/csharp.rs:101:35 replaces the `is_child(BANG)` guard of the `postfix_unary_expression` arm with `false`, so `x!` is no longer peeled. The existing null-forgiving fixtures wrap an operand that does not score itself, which pays one condition whether the slot sees the operand or the node around it. `(p ? a : b)!` and `(a == b)!` wrap operands that score themselves, and the slot holding them must not pay again. csharp.rs:656:14 replaces the `ternary::owns_kind` guard of `csharp_walk_for_conditions` with `true`, so every node that reaches the arm has its `condition`, `consequence` and `alternative` fields read as ternary slots. The only other kinds that declare those fields and reach the arm are the preprocessor directives, and no fixture held a directive whose condition does not score itself: `#if DEBUG` and `#elif TRACE` gain a condition each under the mutant. The C# fixtures were not compiled. Refs #1736 --- src/metrics/abc.rs | 74 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 74 insertions(+) diff --git a/src/metrics/abc.rs b/src/metrics/abc.rs index 77d13050c..1f626dc44 100644 --- a/src/metrics/abc.rs +++ b/src/metrics/abc.rs @@ -5125,6 +5125,42 @@ mod tests { }); } + // A `#if` / `#elif` directive names its symbol test `condition` and + // its `#elif` / `#else` `alternative`, the field names a + // `conditional_expression` uses, and is no ternary: the operand + // slots are walked for the `Ternary` row's owner alone. A bare + // symbol is the discriminating operand, since an operator in the + // directive scores itself and the slot would stay quiet either way. + // The directive selects text at compile time and is no decision to + // cyclomatic either. + #[cfg(feature = "csharp")] + #[test] + fn csharp_preprocessor_symbol_test_is_not_a_ternary_slot() { + let src = "class A { + int d(int a, int b) { + #if DEBUG + if (a == b) { return 1; } + #elif TRACE + if (a != b) { return 2; } + #endif + return 0; + } + }"; + assert_csharp_fixture_spells( + src, + &[ + (Csharp::PreprocIf as u16, 1, "the `#if DEBUG`"), + (Csharp::PreprocElif as u16, 1, "the `#elif TRACE`"), + ], + ); + // expected: the `==` and the `!=`, 2 conditions; `DEBUG` and + // `TRACE` add none (4 if the directives were walked as ternaries). + // Cyclomatic: 1 + the two `if` statements = 3. + check_func_space::(src, "foo.cs", |space| { + assert_members_score(&space.spaces[0], &[("d", 2, 3)]); + }); + } + // #1448, the C++ / Mozcpp instance of #1420. C++ overloads seven // comparison operators; before the fix only `<` / `>` were gated on a // `binary_expression` parent, so `operator<=` `>=` `==` `!=` and the @@ -5916,6 +5952,44 @@ mod tests { }); } + // The null-forgiving suffix is peeled, not merely tolerated: what it + // wraps decides whether the slot pays. The fixtures above wrap a + // bare `b`, which pays one condition whether the slot sees `b` or + // the `postfix_unary_expression` around it, so they cannot tell a + // peel from a wrapper the slot stops at. An operand that scores + // itself can: a ternary pays through its `?` and its own condition + // slot, a comparison through its token, and the `if` slot holding + // either must not pay again. + #[cfg(feature = "csharp")] + #[test] + fn csharp_null_forgiving_operand_that_scores_itself_pays_once() { + let src = "class A { + int t(bool p, bool a, bool b) { if (p ? a : b) { return 1; } return 0; } + int tn(bool p, bool a, bool b) { if ((p ? a : b)!) { return 1; } return 0; } + int e(int a, int b) { if (a == b) { return 1; } return 0; } + int en(int a, int b) { if ((a == b)!) { return 1; } return 0; } + }"; + assert_csharp_fixture_spells( + src, + &[( + Csharp::PostfixUnaryExpression as u16, + 2, + "the null-forgiving suffixes of `tn` and `en`", + )], + ); + // expected: `t` / `tn` are the `?` (+1) and the ternary's + // condition `p` (+1), 2; `e` / `en` are the `==`, 1. The `if` + // slot adds nothing to any of them, so each suffixed member + // equals its control. Cyclomatic: 1 + `if` + `?` = 3, and + // 1 + `if` = 2. + check_func_space::(src, "foo.cs", |space| { + assert_members_score( + &space.spaces[0], + &[("t", 2, 3), ("tn", 2, 3), ("e", 1, 2), ("en", 1, 2)], + ); + }); + } + // The statement `switch` reaches the same `when_clause` kind through // a different parent — `switch_section` rather than // `switch_expression_arm` — which makes it an independent path in From fdf52329d91b2919b1edc33bb52a62203d3934af Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Thu, 12 Nov 2026 19:05:27 -0800 Subject: [PATCH 17/42] test(abc): pin the parenthesised ternary slots of Tcl and iRules Two mutants survived the full mutation run at 68b70b08. src/metrics/abc/tcl.rs:153:18 and src/metrics/abc/irules.rs:48:18 replace the `!child.is_named()` guard of the two `*_ternary_slots` functions with `false`, so the anonymous `(` and `)` the grammars inline under `ternary_expr` are read as operands. The existing fixtures parenthesise a bare `$a` condition, and a `)` in the condition slot pays one condition exactly as `$a` does. The new rows put an operand that scores differently from a token in one slot at a time: a parenthesised comparison in the condition, and a parenthesised negation in each branch. Both grammars were dumped. Refs #1736 --- src/metrics/abc.rs | 69 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 69 insertions(+) diff --git a/src/metrics/abc.rs b/src/metrics/abc.rs index 1f626dc44..880c56230 100644 --- a/src/metrics/abc.rs +++ b/src/metrics/abc.rs @@ -16232,6 +16232,45 @@ end } } + /// A ternary slot is the operand inside its parentheses, never the + /// parenthesis token. + /// + /// `_expr` inlines `( … )` as anonymous children of `ternary_expr`, + /// so a slot located by position alone lands on `)` for a + /// parenthesised condition and on `(` for a parenthesised branch. + /// `($a) ? …` cannot show it: a token pays the condition slot as + /// `$a` does. Each row below holds an operand whose score differs + /// from a token's — a comparison, which pays through its `>` and + /// leaves the slot quiet, and a negation, which makes a branch a + /// condition — in one slot at a time. + #[cfg(feature = "tcl")] + #[test] + fn tcl_parenthesised_ternary_slots_hold_the_operand_inside() { + let conditions = |source: &str| { + crate::test_support::metrics_verbatim( + crate::LANG::Tcl, + source.as_bytes(), + crate::MetricsOptions::default().with_only(&[crate::Metric::Abc]), + ) + .abc + .conditions_sum() + }; + let rows = ["($a > 1) ? $b : $c", "$a ? (!$b) : $c", "$a ? $b : (!$c)"]; + let scored: Vec = rows + .iter() + .map(|expr| { + conditions(&format!( + "proc f {{a b c}} {{\n set r [expr {{{expr}}}]\n}}" + )) + }) + .collect(); + // expected: row 1 is the ternary (+1) and the `>` (+1), its + // condition slot holding the comparison and adding nothing; + // rows 2 and 3 are the ternary (+1), its condition `$a` (+1) + // and the negated branch (+1). + assert_eq!(scored, [2, 3, 3], "{rows:?}"); + } + #[cfg(feature = "irules")] #[test] fn irules_abc_parenthesised_negated_operands_match_the_bare_form() { @@ -16696,6 +16735,36 @@ end ); } + /// The iRules half of + /// `tcl_parenthesised_ternary_slots_hold_the_operand_inside`: the + /// grammar inlines the parentheses the same way (dumped, not + /// assumed), and `($a) ? …` hides a slot that lands on the `)` + /// because the token pays as `$a` does. One slot per row holds an + /// operand that scores differently from a token. + #[cfg(feature = "irules")] + #[test] + fn irules_abc_parenthesised_ternary_slots_hold_the_operand_inside() { + let conditions = |source: &str| { + crate::test_support::metrics_verbatim( + crate::LANG::Irules, + source.as_bytes(), + crate::MetricsOptions::default().with_only(&[crate::Metric::Abc]), + ) + .abc + .conditions_sum() + }; + let rows = ["($a > 1) ? $b : $c", "$a ? (!$b) : $c", "$a ? $b : (!$c)"]; + let scored: Vec = rows + .iter() + .map(|expr| conditions(&format!("when X {{\n set y [expr {{ {expr} }}]\n}}\n"))) + .collect(); + // expected: row 1 is the ternary (+1) and the `>` (+1), its + // condition slot holding the comparison and adding nothing; + // rows 2 and 3 are the ternary (+1), its condition `$a` (+1) + // and the negated branch (+1). + assert_eq!(scored, [2, 3, 3], "{rows:?}"); + } + // #1454's five-language sweep of #1422's C# rule: a pattern-match // guard is a condition *slot*, so every spelling of one contributes // exactly one condition, and the guard is a cyclomatic decision the From 99b202e3edc345b525047efd4b2926da4709dab5 Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Thu, 12 Nov 2026 19:05:27 -0800 Subject: [PATCH 18/42] test(abc): pin that a Rust block ending in `;` yields no operand One mutant survived the full mutation run at 68b70b08. src/metrics/abc/rust.rs:62:32 replaces the `!node.is_child(SEMI)` guard of `rust_transparent_operand` with `true`, so an expression statement that ends in `;` is peeled to its expression. No fixture ended a block in a statement: `m({ !a; })` passes `()`, and the mutant scores the discarded negation as the argument. Refs #1736 --- src/metrics/abc.rs | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/src/metrics/abc.rs b/src/metrics/abc.rs index 880c56230..ff95b81fe 100644 --- a/src/metrics/abc.rs +++ b/src/metrics/abc.rs @@ -11153,6 +11153,30 @@ end ); } + #[cfg(feature = "rust")] + #[test] + fn rust_block_ending_in_a_semicolon_yields_no_operand() { + // A block evaluates to its tail expression. `{ !b }` is the + // negation; `{ !a; }` discards it and is `()`, so the argument + // holding it is no negated operand. The fixture compiles as + // written (`rustc --crate-type lib`, warnings only). + // expected: `m({ !a; })` 0, `m({ !b })` 1 and `return { !a }` 1: + // 2 conditions. The two calls are 2 branches. + check_metrics::( + "fn m(_: T) {}\n\ + fn f(a: bool, b: bool) -> bool {\n\ + \x20 m({ !a; }); // +1b\n\ + \x20 m({ !b }); // +1b +1c\n\ + \x20 return { !a }; // +1c\n\ + }\n", + "foo.rs", + |metric| { + assert_eq!(metric.abc.branches_sum(), 2); + assert_eq!(metric.abc.conditions_sum(), 2); + }, + ); + } + #[cfg(feature = "rust")] #[test] fn rust_short_circuit_with_boolean_literal_operand() { From 0c655c4e22e7aca2d99ff963e24ab8cc604e80a6 Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Thu, 12 Nov 2026 19:05:33 -0800 Subject: [PATCH 19/42] test(cognitive): pin closure nesting, a def boundary, a sequence reset Seven mutants survived the full mutation run at 68b70b08. src/metrics/cognitive/lua.rs:75:18 and perl.rs:146:18 replace the `closure::owns_kind` guard with `false`, and lua.rs:76:32 and perl.rs:147:32 turn the `nesting.lambda += 1` beside it into `*=`. No Lua or Perl fixture held control flow inside an anonymous function. Each new fixture nests a closure in a closure, so the level is added to a non-zero one. elixir.rs:186:27 replaces the `target.is_method_macro()` guard with `false` and with `true`. No fixture showed the reset a `def` applies, which needs a `def` under a construct that raises the nesting, and none put control flow in an ordinary call's arguments. A `def` under a compile-time `if` shows the reset; an `if` in a call's argument shows that a call is no boundary. python.rs:227:13 deletes the arm that resets the boolean sequence at an expression list, an expression statement or a tuple. The reset shows only where a like operator encloses the container, which no fixture wrote: `a and (b and c, d)` and `a and (yield b and c, d)`. An expression statement cannot sit inside a boolean operator, so that third of the arm stays without a fixture. Refs #1736 --- src/metrics/cognitive.rs | 127 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 127 insertions(+) diff --git a/src/metrics/cognitive.rs b/src/metrics/cognitive.rs index e89c7a95f..1ff6900c1 100644 --- a/src/metrics/cognitive.rs +++ b/src/metrics/cognitive.rs @@ -5580,6 +5580,32 @@ fn ie(x: bool) -> i32 { ); } + /// The lambda channel: an anonymous `sub { … }` is the `Closure` + /// row's owner and charges its level to the control flow inside it, + /// and a closure inside a closure charges two. No Perl test read + /// the arm before: the suite passed with it severed. + #[cfg(feature = "perl")] + #[test] + fn perl_anonymous_sub_contributes_lambda_nesting() { + // expected: the outer `if` is 1 + one closure level = 2; the + // inner `if` is 1 + two closure levels = 3; 5 in all. With no + // lambda level each `if` is 1, 2 in all. + check_metrics::( + "my $f = sub { + my ($a) = @_; + if ($a) { return 1; } # +2 + return sub { + my ($b) = @_; + if ($b) { return 2; } # +3 + }; + };", + "foo.pl", + |metric| { + assert_eq!(metric.cognitive.cognitive_sum(), 5); + }, + ); + } + #[cfg(feature = "perl")] #[test] fn perl_goto_single_increment() { @@ -7693,6 +7719,34 @@ end", ); } + /// The lambda channel: an anonymous `function … end` is the + /// `Closure` row's owner and charges its level to the control flow + /// inside it, and a closure inside a closure charges two. No Lua + /// test read the arm before: the suite passed with it severed. + #[cfg(feature = "lua")] + #[test] + fn lua_cognitive_anonymous_function_contributes_lambda_nesting() { + // expected: the outer `if` is 1 + one closure level = 2; the + // inner `if` is 1 + two closure levels = 3; 5 in all. With no + // lambda level each `if` is 1, 2 in all. + check_metrics::( + "local f = function(a) + if a then + return 1 + end + return function(b) + if b then + return 2 + end + end +end", + "foo.lua", + |metric| { + assert_eq!(metric.cognitive.cognitive_sum(), 5); + }, + ); + } + #[cfg(feature = "typescript")] #[test] fn typescript_switch_statement() { @@ -7905,6 +7959,41 @@ end", ); } + /// An element of a tuple or of an expression list is an expression + /// of its own, so an `and` inside one opens a new sequence even + /// while a like operator around the container is still open. With + /// no like operator around the container the reset cannot show — a + /// sibling sequence ends where its operator does — which is why + /// `python_tuple` reads the same without it. A parenthesised + /// operand is the control: it continues the enclosing sequence. + #[cfg(feature = "python")] + #[test] + fn python_tuple_and_expression_list_open_a_new_bool_sequence() { + use crate::test_support::metrics_verbatim; + + let rows = [ + // a tuple, an expression list, a parenthesised operand + "return a and (b and c, d)", + "x = a and (yield b and c, d)", + "return a and (b and c)", + ]; + let scored: Vec = rows + .iter() + .map(|body| { + metrics_verbatim( + crate::LANG::Python, + format!("def f(a, b, c, d):\n {body}\n").as_bytes(), + MetricsOptions::default().with_only(&[crate::Metric::Cognitive]), + ) + .cognitive + .cognitive_sum() + }) + .collect(); + // expected: rows 1 and 2 are the outer `and` (+1), then the + // element's (+1); row 3 is one sequence of `and` (+1). + assert_eq!(scored, [2, 2, 1], "{rows:?}"); + } + #[cfg(feature = "perl")] #[test] fn perl_sibling_bool_sequences() { @@ -10421,6 +10510,44 @@ end", ); } + // A `def` is a function boundary wherever it sits: one written + // inside a compile-time `if` — conditional definition, a common + // module idiom — scores its body against its own depth. A `def` + // directly under `defmodule` cannot show it: the nesting it resets + // is already zero there. + #[cfg(feature = "elixir")] + #[test] + fn elixir_def_inside_a_conditional_restarts_the_nesting() { + check_func_space::( + "defmodule Foo do\n if Mix.env() == :test do\n def f(x) do\n if x do\n :hit\n end\n end\n end\nend\n", + "foo.ex", + |space| { + // expected: the module-level `if` (+1) and the `if` in + // `f` (+1, not +2: the `def` restarts the nesting) = 2. + assert_eq!(space.metrics.cognitive.cognitive_sum(), 2); + assert_eq!(function_space(&space, "f").metrics.cognitive.cognitive(), 1); + }, + ); + } + + // Only the method-defining macros are boundaries. An ordinary call + // is a `call` node like `def` and `if` are, and control flow in its + // arguments keeps the nesting of what encloses the call. + #[cfg(feature = "elixir")] + #[test] + fn elixir_ordinary_call_keeps_the_enclosing_nesting() { + check_metrics::( + "defmodule Foo do\n def f(x, y) do\n if x do\n g(if y do\n :hit\n end)\n end\n end\nend\n", + "foo.ex", + |metric| { + // expected: outer if (+1) + the if in `g`'s argument (+2 + // because nesting=1) = 3; 2 if the call reset the nesting + // as a `def` does. + assert_eq!(metric.cognitive.cognitive_sum(), 3); + }, + ); + } + // `try` with `rescue` and `catch`: the `try` wrapper itself does // NOT bump nesting (matches Java / C#'s "try is a wrapper" rule); // each `rescue` / `catch` block bumps +1 nesting at depth 0. The From 394fba51e72c95f0ed89a26ce09f0ff61380a200 Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Thu, 12 Nov 2026 19:05:34 -0800 Subject: [PATCH 20/42] test(cognitive): pin that a Bash jump level is a named argument One mutant survived the full mutation run at 68b70b08. src/metrics/cognitive/bash.rs:57:38 replaces `&&` with `||` in the filter of `bash_jump_with_level`, which then admits every child after the word. A trailing comment is no child of the command, so the two differ only for an argument the grammar spells as an anonymous token: a bare `$`. The builtin rejects `break $` at run time; with `break` defined as a function, as the neighbouring test does, the line is a call Bash 5.1 runs. It writes no level and scores nothing. Refs #1736 --- src/metrics/cognitive.rs | 44 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/src/metrics/cognitive.rs b/src/metrics/cognitive.rs index 1ff6900c1..20caf51fb 100644 --- a/src/metrics/cognitive.rs +++ b/src/metrics/cognitive.rs @@ -6580,6 +6580,50 @@ fn ie(x: bool) -> i32 { ); } + #[cfg(feature = "bash")] + #[test] + fn bash_jump_level_is_a_named_argument_1765() { + // A level is a named child after the word. The grammar spells a + // bare `$` argument as an anonymous token, the alias of + // `_bare_dollar`, and it is no level: B1 pays for a NUMBER. The + // builtin rejects `break $` when it runs ("numeric argument + // required"), so the fixture defines `break` as a function, + // which makes the line a call Bash accepts (run under 5.1) and + // one that costs nothing. `break 2` is the levelled control, + // read as the builtin as the test above pins. + let src = "break() { :; } + f() { + for i in 1 2; do # +1 + break $ # +0 + done + for i in 1 2; do # +1 + for j in 1 2; do # +2 + break 2 # +1 + done + done + }\n"; + // The shape the reading rests on: the `$` is a direct child of + // the command and anonymous. A grammar that names it fails here. + let mut bare_dollars = 0; + crate::test_support::for_each_node_with_chain::(src.as_bytes(), |node, chain| { + if node.kind_id() == Bash::DOLLAR as u16 { + bare_dollars += 1; + assert!(!node.is_named(), "the bare `$` argument is a token"); + assert_eq!( + chain.last().map(Node::kind_id), + Some(Bash::Command as u16), + "and sits directly under the `break` command" + ); + } + }); + assert_eq!(bare_dollars, 1, "the fixture spells one bare `$`"); + // expected: for(+1) + `break $`(+0) + for(+1) + for(+2 nested) + // + `break 2`(+1) = 5; 6 if the `$` read as a level. + check_metrics::(src, "foo.sh", |metric| { + assert_eq!(metric.cognitive.cognitive_sum(), 5); + }); + } + #[cfg(feature = "bash")] #[test] fn bash_case() { From 76771230951b3b7ead8b56a8f3809e61399b9d11 Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Thu, 12 Nov 2026 19:05:34 -0800 Subject: [PATCH 21/42] test(abc): pin the stranded C# `?` that only recovery input reaches Three mutants survived the full mutation run at 68b70b08. src/metrics/abc/csharp.rs:530:16 replaces the parent guard of the bare `?` arm with `false`, and csharp.rs:540:30 turns the arm's `stats.conditions += 1.` into `*=` and into `-=`. tree-sitter-c-sharp 0.23.5 spells `?` in four productions, all on the arm's deny list, so no valid C# reaches it. The fixture is a recovery shape: `int z = a ? ;` leaves the `?` as the only child of an `ERROR`. The test asserts that shape first, so a grammar bump that recovers differently fails as fixture drift rather than as a wrong number. Two comparisons precede the `?`, so the arm fires on a running count of 2. The expected value is what the arm has always paid, not a language rule. Refs #1736 --- src/metrics/abc.rs | 49 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) diff --git a/src/metrics/abc.rs b/src/metrics/abc.rs index ff95b81fe..1e1e3c32f 100644 --- a/src/metrics/abc.rs +++ b/src/metrics/abc.rs @@ -6127,6 +6127,55 @@ mod tests { assert_eq!(m.abc.conditions_sum(), 3); } + /// The bare `?` arm pays for the one spelling no production owns: a + /// `?` error recovery strands under an `ERROR`. The grammar spells + /// the token in four productions (`nullable_type`, + /// `type_parameter_constraint`, `conditional_expression`, + /// `conditional_access_expression`), all on the arm's deny list, so + /// no valid C# reaches the arm: only a recovery tree shows that it + /// pays, and how much. The compiler rejects `int z = a ? ;`. + /// + /// This pins what the arm has always done, not a language contract + /// (grammar-dispatch §6). The recovered shape is asserted first: a + /// grammar bump that recovers differently fails there, as fixture + /// drift, and should delete this test rather than relax it. + #[cfg(feature = "csharp")] + #[test] + fn csharp_stranded_question_mark_under_recovery_scores_a_condition() { + let src = "class C {\n void F(int a, int b) {\n bool x = a == b;\n bool y = a != b;\n int z = a ? ;\n }\n}\n"; + let parser = CsharpParser::new( + src.as_bytes().to_vec(), + std::path::Path::new("foo.cs"), + None, + ); + let question_marks: Vec<_> = parser + .root() + .preorder() + .filter(|node| node.kind_id() == Csharp::QMARK as u16) + .collect(); + assert_eq!(question_marks.len(), 1, "the fixture spells one `?`"); + assert!( + question_marks[0] + .parent() + .is_some_and(|parent| parent.is_error()), + "the `?` must be stranded directly under an `ERROR`" + ); + assert!( + !ast_has_kind_id(&parser, Csharp::ConditionalExpression as u16), + "recovery must not have built a ternary around it" + ); + let m = metrics_verbatim( + LANG::Csharp, + src.as_bytes(), + MetricsOptions::default().with_only(&[crate::Metric::Abc]), + ); + // expected: the `==` and the `!=`, which the walk reaches first, + // then the stranded `?`: 2 + 1 = 3. The three `=` are + // assignments. + assert_eq!(m.abc.conditions_sum(), 3); + assert_eq!(m.abc.assignments_sum(), 3); + } + // A guarded discard is where the two rules meet. `_ when g =>` is // already exempt from the `default:` exclusion — // `csharp_switch_expression_arm_is_bare_discard` looks for a From 82f93e38544ac8ca1940e8a24c11adb7ac65f08c Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Thu, 12 Nov 2026 19:11:58 -0800 Subject: [PATCH 22/42] ci(mutation): exclude the Groovy and Ruby ternary-walk guard mutants MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Replacing `ternary::owns_kind(…)` with `true` in the last arm of the two ABC condition walks hands every remaining node to the ternary walk, which reads three grammar fields and does nothing when none is present. In both pinned grammars every other kind that carries those fields is a branch, guard or loop kind an earlier arm of the same match takes, so no node reaches the walk with a field to read. The configured list differs from the unconfigured one by exactly these two and the twenty-four earlier entries. Refs #1736 --- .cargo/mutants.toml | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/.cargo/mutants.toml b/.cargo/mutants.toml index 415be65a7..701a2c368 100644 --- a/.cargo/mutants.toml +++ b/.cargo/mutants.toml @@ -128,6 +128,16 @@ exclude_re = [ # every `f64` folded starts at 1 and only grows. '^src/metrics/mod\.rs:\d+:\d+: replace < with <= in FunctionPopulation::(fold|merge)$', '^src/metrics/mod\.rs:\d+:\d+: replace > with >= in FunctionPopulation::(fold|merge)$', + # Equivalent while the pinned Groovy and Ruby grammars give the + # `condition`, `consequence` and `alternative` fields to no kind but + # the ternary and the branch, guard and loop kinds an earlier arm of + # the same match has already taken. The mutant hands every node that + # reaches this arm to the ternary walk, which reads those three fields + # and does nothing when all are absent; an `ERROR` node has no fields. + # Re-derive on a grammar bump, and if a `Branch` or `Guard` row there + # gains a gate. + '^src/metrics/abc/groovy\.rs:\d+:\d+: replace match guard ternary::owns_kind\(kind, node, code, ancestors\) with true in groovy_walk_for_conditions$', + '^src/metrics/abc/ruby\.rs:\d+:\d+: replace match guard ternary::owns_kind\(kind, node, code, ancestors\) with true in ::compute$', # Non-terminating under mutation. The loop then breaks when # `goto_next_sibling` succeeds and repeats when it fails, so a list # with one child is visited forever. Its one caller walks the values From 63da44a774758fecc40abc8f2376f93ef7997824 Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Thu, 12 Nov 2026 19:51:45 -0800 Subject: [PATCH 23/42] test(nexits): pin the text half of the Go and Ruby exit gates Two mutants survived the full mutation run at 68b70b08. big-code-analysis-ast/src/roles/go.rs:75:63 turns the `&&` of `calls_panic` into `||`, so any call of a bare identifier is an exit. Every Go fixture called `panic`, a selector, or nothing. big-code-analysis-ast/src/roles/ruby.rs:67:53 turns the `&&` of `kernel_raise_or_exit`'s receiver test into `||`, so any constant receiver is read as `Kernel`. The fixtures spelled only lowercase receivers and `self`. Each new fixture holds two calls the gate must decline beside one it admits, so the expected sum is 1 and the mutant's is 3. Refs #1736 --- src/metrics/nexits.rs | 41 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) diff --git a/src/metrics/nexits.rs b/src/metrics/nexits.rs index eec23f06c..a5f87d63e 100644 --- a/src/metrics/nexits.rs +++ b/src/metrics/nexits.rs @@ -1089,6 +1089,29 @@ mod tests { ); } + /// An ordinary call is no exit. The `Exit` row admits a call whose + /// callee is a bare identifier *and* spells `panic`; every other Go + /// fixture here calls `panic`, a selector, or nothing, so a gate + /// that admitted any bare callee scored them all the same. + #[cfg(feature = "go")] + #[test] + fn go_ordinary_call_is_not_exit() { + check_metrics::( + "package main + func f() { + g() + h(1) + panic(\"boom\") + }", + "foo.go", + |metric| { + // expected: `g()` and `h(1)` call bare identifiers that + // are not `panic` → 0; `panic("boom")` → 1. + assert_eq!(metric.nexits.nexits_sum(), 1); + }, + ); + } + #[cfg(feature = "java")] #[test] fn java_split_function() { @@ -2412,6 +2435,24 @@ end", ); } + /// The receiver gate reads the receiver's kind *and* its text: a + /// constant other than `Kernel` names a user method, as any other + /// receiver does. The fixture above spells only lowercase receivers + /// and `self`, which a gate admitting every constant rejects too. + #[cfg(feature = "ruby")] + #[test] + fn ruby_constant_receiver_other_than_kernel_is_not_exit() { + check_metrics::( + "def f(x)\n Salary.raise(x)\n Menu.exit\n Kernel.raise \"boom\"\nend\n", + "foo.rb", + |metric| { + // expected: `Salary.raise` and `Menu.exit` → 0; + // `Kernel.raise` → 1. + assert_eq!(metric.nexits.nexits_sum(), 1); + }, + ); + } + /// A *bare* `raise` / `exit` — the argument-less re-raise idiom — /// parses as a plain `identifier`, indistinguishable from reading a /// local variable of that name, so it is deliberately not counted. From c6f6b8c7a11536198cf11134bfd7b88382f40cac Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Thu, 12 Nov 2026 19:51:52 -0800 Subject: [PATCH 24/42] test(nargs): pin a variable-arity parameter in Java's canonical rule One mutant survived the full mutation run at 68b70b08 (there at roles/java.rs:86:9): deleting the `Java::SpreadParameter` arm of `java_parameter_type`, which makes a variable-arity parameter no parameter at all. Every variable-arity record of `java_canonical_constructor_is_told_by_its_types` has it as its only component, so the mutant compared an empty component list there and gave the same verdicts. The new records differ from their constructors by the variable-arity parameter alone: one constructor stops short of it, one runs past the components with it, one spells another element type. Each is an alternative, so the header opens beside it; under the mutant each reads as canonical. javac 25 accepts the fixture. Refs #1736 --- src/metrics/nargs.rs | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/src/metrics/nargs.rs b/src/metrics/nargs.rs index 33555fc4c..4719864ea 100644 --- a/src/metrics/nargs.rs +++ b/src/metrics/nargs.rs @@ -4474,6 +4474,42 @@ class A(val x: Int)", ); } + /// A variable-arity parameter is a parameter of the list it sits + /// in, compared like any other. Every variable-arity record of + /// `java_canonical_constructor_is_told_by_its_types` has it as the + /// *only* component, so a reading that dropped such a parameter + /// compared an empty list there and answered the same. Here the + /// lists differ by it alone: a constructor that stops short of the + /// variable-arity component (`S`), one that runs past the components + /// with a variable-arity parameter (`P`), and one whose only + /// parameter is variable-arity of another type (`K`) are + /// alternatives, so the header opens beside each. `X` writes the + /// canonical constructor, and its header closes. + #[cfg(feature = "java")] + #[test] + fn java_variable_arity_parameter_takes_part_in_the_canonical_rule() { + check_spaces::( + "record S(int a, int... xs) { S(int a) { this(a, 0); } } + record P(int a) { P(int a, int... more) { this(a); } } + record K(int... xs) { K(String... ss) { this(ss.length); } } + record X(int a, int... xs) { X(int a, int... xs) { this.a = a; this.xs = xs; } }", + "variadic.java", + |space| { + let functions_per_record: Vec<(&str, usize)> = space + .spaces + .iter() + .map(|r| (r.name.as_deref().unwrap_or("?"), r.spaces.len())) + .collect(); + // expected: the header and the written constructor for + // `S`, `P` and `K`; the written constructor alone for `X`. + assert_eq!( + functions_per_record, + [("S", 2), ("P", 2), ("K", 2), ("X", 1)] + ); + }, + ); + } + /// Groovy's twin of `java_canonical_constructor_is_told_by_its_types`, /// without the shapes the pinned grammar cannot parse (an annotated /// component, a variable-arity component, C-style dimensions): a From eb77bd94d5628298ddd6b8cf554996023e4cdd9f Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Thu, 12 Nov 2026 19:52:00 -0800 Subject: [PATCH 25/42] test(halstead): pin how Perl spells a dash key and the "[]" pair Four mutants in big-code-analysis-ast/src/getter/perl.rs survived the full mutation run at 68b70b08. 315:39 (`+` to `*`, and to `-`) and 317:69 (`||` to `&&`) are in `get_operand_id`'s file-test arm. Each makes the word after the sign empty, so a `-bareword` key that parses as a file test is keyed as `-` alone. `DASH_KEY_ROWS` pairs such a key only with itself or with a plain word, and one distinct entry is one entry under any spelling. The new rows hold two different keys: two word forms in one list, two exact file tests in two lists. 348:13 deletes the `Perl::LBRACK` arm of `get_operator_id_as_str`, so `[` lists as `[` and not as the `[]` pair. No `check_ops` fixture held a square bracket, and the counts key the operator by kind. Refs #1736 --- src/metrics/perl_keyword_key_tests.rs | 40 +++++++++++++++++++++++++++ src/ops.rs | 15 ++++++++++ 2 files changed, 55 insertions(+) diff --git a/src/metrics/perl_keyword_key_tests.rs b/src/metrics/perl_keyword_key_tests.rs index fa2b5df0a..6a721f1e5 100644 --- a/src/metrics/perl_keyword_key_tests.rs +++ b/src/metrics/perl_keyword_key_tests.rs @@ -529,6 +529,46 @@ fn perl_dash_key_scores_like_its_quoted_twin() { } } +/// Two different `-bareword` keys are two operands, as their quoted +/// twins are (#1545). `DASH_KEY_ROWS` pairs a file-test key only with +/// itself or with a plain word, which pins that the key is not spelled +/// as the word after it, nor as the pair it swallowed; spelled as the +/// sign alone, every key there still makes one entry. Here the keys +/// differ after the sign: two word forms in one list (`-text` and +/// `-foo`, each a file test on the rest of its word), and two exact +/// file tests in two lists (`-x` and `-e`, each swallowing its `=>` +/// and value). +#[cfg(feature = "perl")] +#[test] +fn perl_distinct_dash_keys_are_distinct_operands() { + for (twin, key, halstead) in [ + // expected: operators `sub`, `{}`, `()`, `=>` x2, `,`, `;`; + // operands `f` x2, the two keys, `1`, `2`. + ( + "f('-text' => 1, '-foo' => 2);", + "f(-text => 1, -foo => 2);", + [6, 7, 5, 6], + ), + // expected: operators `sub`, `{}`, `my` x2, `=` x2, `()` x2, + // `=>` x2, `;` x2; operands `f`, `%h`, `%g`, the two keys, `1`, + // `2`. + ( + "my %h = ('-x' => 1); my %g = ('-e' => 2);", + "my %h = (-x => 1); my %g = (-e => 2);", + [7, 12, 7, 7], + ), + ] { + assert_eq!(twin.replace('\'', ""), key, "`{key}` drifted from its twin"); + let want = measure_with_branches(twin); + assert_eq!(want.1, halstead, "`{twin}` moved; re-derive the row"); + assert_eq!( + measure_with_branches(key), + want, + "`{key}` must score like `{twin}`" + ); + } +} + /// A `-and` / `-not` key keeps its sign when whitespace separates the /// two: Perl keys `(- not => 1)` as `"-not"`, so it must not share a /// vocabulary entry with the plain `not` key beside it. The twins' diff --git a/src/ops.rs b/src/ops.rs index 68f81fec8..10606f3bf 100644 --- a/src/ops.rs +++ b/src/ops.rs @@ -517,6 +517,21 @@ mod tests { ); } + /// A `[` lists as the `[]` pair it opens, in an array reference and + /// in an element access, as `(` and `{` list as theirs. The counts + /// key the operator by kind and cannot see how it is spelled. + #[cfg(feature = "perl")] + #[test] + fn perl_square_bracket_renders_as_its_pair() { + check_ops( + LANG::Perl, + "my $r = [1, 2];\nmy $v = $a[0];", + "foo.pl", + &mut ["$", ",", ";", "=", "[]", "my"], + &mut ["$a", "$r", "$v", "0", "1", "2"], + ); + } + /// A bareword key bills as the string it is (#1572): `-name` as one /// operand with its sign, no `-` operator, and apart from the plain /// `name` key. The expected vocabularies are the quoted twin's From 8255475b96ddeb9b1f8ebd75c0103af3c68299e6 Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Thu, 12 Nov 2026 19:52:08 -0800 Subject: [PATCH 26/42] test(halstead): pin that a plain PHP heredoc is one operand One mutant survived the full mutation run at 68b70b08: big-code-analysis-ast/src/getter/php.rs:316:56 turns `kind == HeredocBody && c.wraps_any(..)` into `||`, so a heredoc is skipped as interpolating for merely having a body. The suite held an interpolating heredoc and a nowdoc, and no heredoc whose body is plain text. That one has a `heredoc_body` child too, and is one operand. Refs #1736 --- src/metrics/halstead.rs | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/src/metrics/halstead.rs b/src/metrics/halstead.rs index 8aa35ae64..6f08374d7 100644 --- a/src/metrics/halstead.rs +++ b/src/metrics/halstead.rs @@ -12541,6 +12541,35 @@ f() { ); } + #[cfg(feature = "php")] + #[test] + fn php_plain_heredoc_counts_as_one_operand() { + // The other side of #184's wrapper skip. A heredoc whose body + // interpolates nothing is one operand, like the double-quoted + // string it is shaped as. It still has a `heredoc_body` child, + // holding one `string_content`, so the skip must ask whether + // that body wraps an interpolation and not merely whether the + // heredoc has a body. The interpolating fixture above cannot + // tell the two apart, and a nowdoc is another kind. + // + // Source: + // ( + " Date: Thu, 12 Nov 2026 19:52:22 -0800 Subject: [PATCH 27/42] test(halstead): pin two Kotlin boundaries valid source reaches Two mutants survive, one from the full mutation run at 68b70b08 and one that replaced a listed mutant when its function was rewritten. big-code-analysis-ast/src/roles/kotlin.rs:42:71 turns the second `||` of `modifier_was_written_as_one` into `&&`, so the climb to the host stops at a `type_modifiers` list. The rows of `kotlin_modifiers_are_operators_1558` strand the bare leaf or a `*_modifier` wrapper under an `ERROR`, never that list. A function named `suspend`, called or declared, does: both are valid Kotlin that kotlin-ng fails to parse, and the mutant bills the name as a modifier. big-code-analysis-ast/src/getter/kotlin.rs:82:60 turns the `&&` of `kotlin_is_short_interp_name`'s previous-sibling test into `||`. The run listed it at 73:56 as `||` to `&&`, before eeb69b78 rewrote the early returns as one conjunction; it is the same change to the same test. kotlin-ng splits `"\uCAFE"` into the `string_content` tokens `\u` and `CAFE`, so the mutant reads the hex digits as a `$name`. Refs #1736 --- src/metrics/halstead.rs | 44 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/src/metrics/halstead.rs b/src/metrics/halstead.rs index 6f08374d7..136ef0ea9 100644 --- a/src/metrics/halstead.rs +++ b/src/metrics/halstead.rs @@ -5864,6 +5864,28 @@ end", assert_ops_operands::(src, "foo.kt", 3, vec!["f", "a", "\"price: $5\""]); } + #[cfg(feature = "kotlin")] + #[test] + fn kotlin_unicode_escape_is_not_a_short_template() { + // Issue #454 boundary: the name token must follow a token that + // spells exactly `$`. kotlin-ng splits a `\uXXXX` escape into two + // `string_content` tokens, `\u` and the hex digits, so + // `"\uCAFE\uBABE"` is `\u`, `CAFE`, `\u`, `BABE`: each digit + // run starts like an identifier and follows a `string_content`, + // which is every condition of a short template but the `$`. + // + // `fun f() { val a = "\uCAFE\uBABE" }\n` + // expected: operands `f`, `a` and the literal → u_operands = + // 3, N2 = 3. Read as `$CAFE$BABE`, the literal is suppressed + // and both digit runs recovered: 4 / 4. + let src = "fun f() { val a = \"\\uCAFE\\uBABE\" }\n"; + check_metrics::(src, "foo.kt", |metric| { + assert_eq!(metric.halstead.unique_operands(), 3); + assert_eq!(metric.halstead.total_operands(), 3); + }); + assert_ops_operands::(src, "foo.kt", 3, vec!["f", "a", "\"\\uCAFE\\uBABE\""]); + } + #[cfg(feature = "kotlin")] #[test] fn kotlin_string_template_long_form_no_double_count() { @@ -9228,6 +9250,28 @@ int helper(int a, char b) { return a; } assert_operator_rows::("foo.kt", ROWS); } + /// #1558, a stranding the rows above do not spell: a function + /// *named* `suspend`, called and declared. Both are valid Kotlin, + /// since `suspend` is a soft keyword and the standard library + /// declares such a function, and kotlin-ng parses neither. The name + /// recovers into an `ERROR` that holds a `type_modifiers` list, + /// where the rows above strand the bare leaf or a `*_modifier` + /// wrapper. The leaf is a name here too and bills nothing, so each + /// row scores what its twin scores with a name the grammar parses. + #[cfg(feature = "kotlin")] + #[test] + fn kotlin_function_named_suspend_bills_no_modifier_1558() { + const ROWS: &[(&str, &str, [u64; 2])] = &[ + // `val`, `=`, `()` + ("call", "val c = suspend(1)\n", [3, 3]), + ("call, twin", "val c = suspended(1)\n", [3, 3]), + // `fun`, `()`, `:`, `=` + ("declaration", "fun suspend(x: Int) = x\n", [4, 4]), + ("declaration, twin", "fun suspended(x: Int) = x\n", [4, 4]), + ]; + assert_operator_rows::("foo.kt", ROWS); + } + /// #1558: `reified` is the one Kotlin modifier spelled as an aliased /// named kind. `KotlinCode::is_primitive` keys it by its text, so /// `bca ops` lists the word written, not the grammar's From 293db69f1ca32914ca903f84cf0b548efab2f3dd Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Thu, 12 Nov 2026 19:52:52 -0800 Subject: [PATCH 28/42] test(getter): ask four readings directly that no walk can show Five mutants survived the full mutation run at 68b70b08, each in a reading whose answer the walk composes with another that masks it. No metric fixture can separate them, so each is asked directly, as the control-keyword tests in this module already ask `get_paying_role` and the byte-less `get_op_type`. getter/elixir.rs:147:13 and 148:13 turn a `||` of `get_paying_role` into `&&`, so the `Comparison` or the `ShortCircuit` row stops billing its applied tokens. The byte-less arm lists the same tokens for the spellings the rows' gate leaves out, and bills them when the rows decline. getter/java.rs:152:22 makes the byte-less arm call every `class` token an operand, and getter/perl.rs:377:16 makes it call every `and` token one. On the walk the `DeclKeyword` row and the `ShortCircuit` row answer first for the declaration's `class` and the applied `and`, so the arm only sees the tokens its guard admits. getter.rs:1185:9 makes the trait's default `get_operator_id_as_str` return "xyzzy". Only `ccomment` and `preproc` inherit it, and their Halstead `compute` records no operator for `ops` to name. Refs #1736 --- big-code-analysis-ast/src/getter.rs | 107 ++++++++++++++++++++++++++++ 1 file changed, 107 insertions(+) diff --git a/big-code-analysis-ast/src/getter.rs b/big-code-analysis-ast/src/getter.rs index daf59a33a..750f74d88 100644 --- a/big-code-analysis-ast/src/getter.rs +++ b/big-code-analysis-ast/src/getter.rs @@ -1730,6 +1730,7 @@ mod keyword_role_tests { feature = "python", feature = "rust", feature = "kotlin", + feature = "elixir", ))] fn roles_of( source: &[u8], @@ -1981,6 +1982,112 @@ mod keyword_role_tests { assert_eq!((via_walk, via_rows, via_byte_less), (5, 1, 5)); } + /// Elixir's hand-written `get_paying_role` bills the applied tokens + /// of the `Comparison` row and of the `ShortCircuit` row, each row + /// on its own. The walk cannot show which reading billed one: the + /// byte-less arm lists the same tokens, for the spellings the rows' + /// `applied` gate leaves out, so it answers `Operator` for an + /// applied `==` the rows declined. Asked directly, as the + /// control-keyword tests above ask the macro-built readings. + #[cfg(feature = "elixir")] + #[test] + fn elixir_paying_role_bills_each_rows_applied_tokens() { + use crate::ElixirCode; + // `==` and `<` are the `Comparison` row's, `&&` and `or` the + // `ShortCircuit` row's. `=`, `+` and `/` are no row's, and the + // capture `&==/2` names its `==` without applying it. + let source = b"x = a == b && c < d or e + f\ng = &==/2\n"; + let via_rows = roles_of::(source, ElixirCode::get_paying_role); + assert_eq!( + via_rows, + [ + ("==", TokenRole::Operator), + ("&&", TokenRole::Operator), + ("<", TokenRole::Operator), + ("or", TokenRole::Operator), + ] + ); + } + + /// Java's byte-less arm bills a `class` token only as the tail of a + /// class literal, the spelling the `DeclKeyword` row's gate leaves + /// to it (#1566). A declaration's `class` is the row's: on the walk + /// the row answers first and the arm never sees that token, so only + /// the arm asked directly shows that its parent guard holds. + #[cfg(feature = "java")] + #[test] + fn java_byte_less_arm_bills_class_only_in_a_class_literal() { + use crate::JavaCode; + let source = b"class A { Object o = A.class; }\n"; + let class_tokens = |roles: Vec<(&'static str, TokenRole)>| { + roles + .into_iter() + .filter(|&(kind, _)| kind == "class") + .map(|(_, role)| role) + .collect::>() + }; + let via_walk = class_tokens(roles_of::( + source, + JavaCode::get_op_type_with_code, + )); + let via_rows = class_tokens(roles_of::(source, JavaCode::get_keyword_role)); + let via_byte_less = class_tokens(roles_of::(source, |n, _, a| { + JavaCode::get_op_type(n, a) + })); + // The declaration's `class` first, then the literal's. + assert_eq!(via_walk, [TokenRole::Operator, TokenRole::Operand]); + assert_eq!(via_rows, [TokenRole::Operator]); + assert_eq!(via_byte_less, [TokenRole::Operand]); + } + + /// Perl's byte-less arm tells an `and` operator from an auto-quoted + /// `and` key (#1539) by its own test of the token's position. On the + /// walk the `ShortCircuit` row's `applied_and` gate, the same test, + /// pays the operator first, so the arm sees only the key there; the + /// operator half of its test shows only when the arm is asked + /// directly. + #[cfg(feature = "perl")] + #[test] + fn perl_byte_less_arm_tells_an_and_operator_from_an_and_key() { + use crate::PerlCode; + use crate::test_support::for_each_node_with_chain_tolerating_errors; + // The key's `=>` recovers into an `ERROR` (#1539), so the walk + // cannot require a clean parse. + let source = b"my $c = $a and $b;\nmy %h = (and => 1);\n"; + let and_tokens = |classify: fn(&Node<'_>, &[u8], Ancestors<'_, '_>) -> TokenRole| { + let mut out = Vec::new(); + for_each_node_with_chain_tolerating_errors::(source, |node, chain| { + if node.kind() == "and" { + out.push(classify(node, source, Ancestors::known(chain))); + } + }); + out + }; + // The operator first, then the key. + let via_walk = and_tokens(PerlCode::get_op_type_with_code); + let via_rows = and_tokens(PerlCode::get_paying_role); + let via_byte_less = and_tokens(|n, _, a| PerlCode::get_op_type(n, a)); + assert_eq!(via_walk, [TokenRole::Operator, TokenRole::Operand]); + assert_eq!(via_rows, [TokenRole::Operator, TokenRole::Unknown]); + assert_eq!(via_byte_less, [TokenRole::Operator, TokenRole::Operand]); + } + + /// The trait's default operator name is the empty string, which the + /// two pseudo-languages whose rows are all `absent` inherit: + /// `ccomment` and `preproc` bill no operator, so no kind of theirs + /// has a name to render. No walk shows it, since their Halstead + /// `compute` records no operator for `ops` to name, hence the direct + /// reading. + #[cfg(feature = "c-family-helpers")] + #[test] + fn row_less_languages_render_no_operator_name() { + use crate::{CcommentCode, PreprocCode}; + for id in [0, 1, u16::MAX] { + assert_eq!(CcommentCode::get_operator_id_as_str(id), ""); + assert_eq!(PreprocCode::get_operator_id_as_str(id), ""); + } + } + /// A C-family modifier, declaration keyword and primitive reach /// `Operator` through `get_op_type_with_code` and through /// `get_keyword_role` alone, and the byte-less `get_op_type` no From 050f7c5e5d39838dcdccb98a2c5cdd6853b4ea80 Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Thu, 12 Nov 2026 19:52:52 -0800 Subject: [PATCH 29/42] test(roles): pin the gate on the Rust Guard row's owner One mutant survived the full mutation run at 68b70b08: big-code-analysis-ast/src/roles/rust.rs:57:5 makes `has_guard` answer `true`, so every `match_pattern` owns a guard. The one consumer that reads the owner, ABC's `rust_count_match_arm`, reads the pattern's `condition` field again beside it and scores nothing where the field is absent, so no metric fixture can separate the two. The row is asked directly: of three patterns it owns the one that carries a condition. Refs #1736 --- big-code-analysis-ast/src/roles/rust.rs | 36 +++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/big-code-analysis-ast/src/roles/rust.rs b/big-code-analysis-ast/src/roles/rust.rs index 61dd1519f..103467ef1 100644 --- a/big-code-analysis-ast/src/roles/rust.rs +++ b/big-code-analysis-ast/src/roles/rust.rs @@ -267,3 +267,39 @@ role_table! { // function's own doc — is `Checker::doc_comment_opens_body`. DocBodyResidual { absent "only the callables and closures hold a doc comment in a body; the trait default" } } + +#[cfg(test)] +mod tests { + use super::*; + use crate::RustCode; + use crate::test_support::for_each_node_with_chain; + + // The `Guard` row owns a `match_pattern` exactly where it carries + // a `condition`, and the guard's `if` pays under it. The one + // consumer that reads the owner, ABC's arm walk, reads the + // `condition` field again beside it, so an owner that admitted + // every pattern scores the same there; the row is asked here. + #[cfg(feature = "rust")] + #[test] + fn guard_owns_a_pattern_only_where_it_carries_a_condition() { + let source = b"fn f(x: i32) -> i32 { match x { a if a > 0 => 1, b => b, _ => 0 } }\n"; + let (mut patterns, mut owned, mut paid) = (0, Vec::new(), Vec::new()); + for_each_node_with_chain::(source, |node, chain| { + let ancestors = Ancestors::known(chain); + let text = || node.utf8_text(source).expect("fixture is UTF-8").to_owned(); + if node.kind_id() == Rust::MatchPattern as u16 { + patterns += 1; + } + if guard::owns(node, source, ancestors) { + owned.push(text()); + } + if guard::pays_at_leaf(node, source, ancestors) { + paid.push(text()); + } + }); + // Three arms, three patterns; only the first is guarded. + assert_eq!(patterns, 3); + assert_eq!(owned, ["a if a > 0"]); + assert_eq!(paid, ["if"]); + } +} From e2bbeb7ae5cc55fb19056567204642e26af45c96 Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Thu, 12 Nov 2026 19:53:02 -0800 Subject: [PATCH 30/42] test(halstead): pin two getter arms only recovery input reaches Two mutants survived the full mutation run at 68b70b08, each on the branch of a parent guard that the pinned grammar reaches only through error recovery. getter/elixir.rs:214:25 makes every `:` leaf a quoted atom's. tree-sitter-elixir 0.3.5 emits a standalone `:` only inside a `quoted_atom`; `b = [:"q]` strands one under an `ERROR`. getter/perl.rs:50:20 makes every `/` a bare pattern's delimiter. tree-sitter-perl 1.1.2 spells `/` only in `pattern_matcher`; `$s =~ /abc` strands the opening one under an `ERROR`. Each language rejects its fixture. The tests pin what the arms have always done there, not a language contract, and assert the recovered shape first, so a grammar bump that recovers differently fails as fixture drift rather than as a wrong number. Kept apart from the other tests of this issue so the commit can be dropped if these arms are excluded instead. The Groovy `super` arm has the same shape and is left alone: the getter's comment and `groovy_wildcard_super_bound_stays_an_operator` say it is deliberately untested. Refs #1736 --- src/metrics/halstead.rs | 98 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 98 insertions(+) diff --git a/src/metrics/halstead.rs b/src/metrics/halstead.rs index 136ef0ea9..b4d38476b 100644 --- a/src/metrics/halstead.rs +++ b/src/metrics/halstead.rs @@ -4821,6 +4821,56 @@ mod tests { ); } + /// The other branch of the delimiter guard (#1312): a `/` whose + /// parent is no `pattern_matcher` falls through to the operator arm + /// and bills. tree-sitter-perl 1.1.2 spells `/` only as the bare + /// pattern's two delimiters (division emits no token, as the test + /// above pins), so no valid Perl reaches that branch and only a + /// recovery tree shows it. `$s =~ /abc` never closes its pattern, + /// and Perl rejects it. + /// + /// This pins what the arm has always done, not a language contract + /// (grammar-dispatch §6). The recovered shape is asserted first: a + /// grammar bump that recovers differently fails there, as fixture + /// drift, and should delete this test rather than relax it. + #[cfg(feature = "perl")] + #[test] + fn perl_slash_stranded_under_recovery_bills_an_operator() { + let src = "my $t = 1;\n$s =~ /abc\n"; + let parser = PerlParser::new( + src.as_bytes().to_vec(), + std::path::Path::new("foo.pl"), + None, + ); + let slashes: Vec<_> = parser + .root() + .preorder() + .filter(|node| node.kind_id() == Perl::SLASH as u16) + .collect(); + assert_eq!(slashes.len(), 1, "recovery keeps the opening `/` alone"); + assert!( + slashes[0].parent().is_some_and(|parent| parent.is_error()), + "the `/` must be stranded directly under an `ERROR`" + ); + assert!( + !ast_has_kind_id(&parser, Perl::PatternMatcher as u16), + "recovery must not have built a pattern around it" + ); + let h = crate::test_support::metrics_verbatim( + crate::LANG::Perl, + src.as_bytes(), + crate::MetricsOptions::default().with_only(&[crate::Metric::Halstead]), + ) + .halstead; + // expected: operators `my`, `$` x2, `=`, `;`, `=~` and the + // stranded `/` → n1 = 6, N1 = 7. Operands `$t`, `1`, `$s` → + // n2 = N2 = 3. + assert_eq!(h.unique_operators(), 6); + assert_eq!(h.total_operators(), 7); + assert_eq!(h.unique_operands(), 3); + assert_eq!(h.total_operands(), 3); + } + #[cfg(feature = "perl")] #[test] fn perl_readline_closer_alias_never_reaches_kind_id() { @@ -10133,6 +10183,54 @@ f() { ); } + /// The other branch of the quoted-atom guard (#1858): a `:` leaf + /// whose parent is no `quoted_atom` falls through to the operator + /// arm and bills. tree-sitter-elixir 0.3.5 emits a standalone `:` + /// only inside a `quoted_atom`, so no valid Elixir reaches that + /// branch and only a recovery tree shows it. `b = [:"q]` never + /// closes its quote, and the compiler rejects it. + /// + /// This pins what the arm has always done, not a language contract + /// (grammar-dispatch §6). The recovered shape is asserted first: a + /// grammar bump that recovers differently fails there, as fixture + /// drift, and should delete this test rather than relax it. + #[cfg(feature = "elixir")] + #[test] + fn elixir_colon_stranded_under_recovery_bills_an_operator() { + let src = "a = 1\nb = [:\"q]\n"; + let parser = ElixirParser::new( + src.as_bytes().to_vec(), + std::path::Path::new("foo.ex"), + None, + ); + let colons: Vec<_> = parser + .root() + .preorder() + .filter(|node| node.kind_id() == Elixir::COLON as u16) + .collect(); + assert_eq!(colons.len(), 1, "the fixture spells one `:`"); + assert!( + colons[0].parent().is_some_and(|parent| parent.is_error()), + "the `:` must be stranded directly under an `ERROR`" + ); + assert!( + !ast_has_kind_id(&parser, Elixir::QuotedAtom as u16), + "recovery must not have built a quoted atom around it" + ); + let h = crate::test_support::metrics_verbatim( + crate::LANG::Elixir, + src.as_bytes(), + crate::MetricsOptions::default().with_only(&[crate::Metric::Halstead]), + ) + .halstead; + // expected: operators `=` x2, `[]` and the stranded `:` → n1 = 3, + // N1 = 4. Operands `a`, `1`, `b` → n2 = N2 = 3. + assert_eq!(h.unique_operators(), 3); + assert_eq!(h.total_operators(), 4); + assert_eq!(h.unique_operands(), 3); + assert_eq!(h.total_operands(), 3); + } + #[cfg(feature = "elixir")] #[test] fn elixir_sigil_delimiters_are_not_operators() { From 63ee0b932dbfd614543ad2e1219e85badb1cea4c Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Thu, 12 Nov 2026 19:59:10 -0800 Subject: [PATCH 31/42] ci(mutation): exclude four ast mutants on code that cannot answer otherwise - `get_space_kind_with_code` for Ccomment and Preproc forwards to a role table with no opener, so it answers `Unknown`, the default. - `kinds_repeat`'s outer loop with `<=` makes one more pass that indexes nothing. Its inner loop has a live `<` too, so the entry keeps the column. - `kotlin_short_interp_operand_bytes` is reached only where its caller has already found a leading identifier, so the length it compares with 0 is never 0. The configured list differs from the unconfigured one by exactly these four and the twenty-six earlier entries. Refs #1736 --- .cargo/mutants.toml | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/.cargo/mutants.toml b/.cargo/mutants.toml index 701a2c368..17cdf4093 100644 --- a/.cargo/mutants.toml +++ b/.cargo/mutants.toml @@ -138,6 +138,21 @@ exclude_re = [ # gains a gate. '^src/metrics/abc/groovy\.rs:\d+:\d+: replace match guard ternary::owns_kind\(kind, node, code, ancestors\) with true in groovy_walk_for_conditions$', '^src/metrics/abc/ruby\.rs:\d+:\d+: replace match guard ternary::owns_kind\(kind, node, code, ancestors\) with true in ::compute$', + # Equivalent. The body forwards to the language's `opens_space`, + # which answers `SpaceKind::Unknown` unless a row's owner carries + # `opens` or `opens_by`. Neither the Ccomment nor the Preproc table has + # one, and `SpaceKind::default()` is `Unknown`. + '^big-code-analysis-ast/src/getter/(ccomment|preproc)\.rs:\d+:\d+: replace ::get_space_kind_with_code -> SpaceKind with Default::default\(\)$', + # Equivalent. The outer loop's extra pass has `i == a.len()`, so the + # inner loop, the only place that indexes, starts past the end and + # does not run. The inner loop's own `<` is at column 17 and is live: + # the column tells the two apart. + '^big-code-analysis-ast/src/roles/mod\.rs:\d+:13: replace < with <= in kinds_repeat$', + # Unreachable. The helper's one caller reaches it only where + # `kotlin_is_short_interp_name` holds for the same bytes, which needs + # a leading identifier of at least one byte, so `prefix_len` is never + # 0 here and `>` and `>=` agree. + '''^big-code-analysis-ast/src/getter/kotlin\.rs:\d+:\d+: replace > with >= in kotlin_short_interp_operand_bytes$''', # Non-terminating under mutation. The loop then breaks when # `goto_next_sibling` succeeds and repeats when it fails, so a list # with one child is visited forever. Its one caller walks the values From 8c7bfe075f04e6cff6480aebb9861018abe97e22 Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Thu, 12 Nov 2026 21:46:38 -0800 Subject: [PATCH 32/42] test(find): pin the error filter on a clean and a broken source Two mutants survived the full mutation run at 68b70b08. checker.rs:773:9 makes `Checker::is_error` answer `true`, and its twin makes it answer `false`. No language overrides the method, and its one caller is the `error` arm of `ParserTrait::filters`, which no test in either crate asked. The test asks `find` and `count` for `error` on a source that parses cleanly, where nothing matches, and on one that does not, where the matches are the `ERROR` and each of its ancestors, root first. The second source is one rustc rejects, by necessity: a tree with no parse error gives the filter nothing to match. The test asserts the recovered shape first, so a grammar bump that recovers differently fails as fixture drift rather than as a wrong count. Refs #1736 --- big-code-analysis-ast/src/find.rs | 65 +++++++++++++++++++++++++++++++ 1 file changed, 65 insertions(+) diff --git a/big-code-analysis-ast/src/find.rs b/big-code-analysis-ast/src/find.rs index 75f71abbd..cd486d90d 100644 --- a/big-code-analysis-ast/src/find.rs +++ b/big-code-analysis-ast/src/find.rs @@ -53,3 +53,68 @@ pub fn find<'a, T: ParserTrait>( }); Ok(good) } + +#[cfg(test)] +mod tests { + use std::path::PathBuf; + + use super::find; + use crate::count::count; + use crate::langs::RustParser; + use crate::node::Node; + use crate::traits::ParserTrait; + + // The `error` filter is `Checker::is_error`: a node that is a parse + // error or holds one. A clean source matches nothing, which an + // `is_error` answering `true` for every node fails. A broken one + // matches the path from the root down to its `ERROR` and nothing + // beside that path, which an `is_error` answering `false` fails. The + // second source is one rustc rejects, by necessity: a tree with no + // parse error gives the filter nothing to match. + #[cfg(feature = "rust")] + #[test] + fn the_error_filter_matches_the_path_to_a_parse_error_and_nothing_else() { + let error = ["error".to_owned()]; + let parse = |source: &str| { + RustParser::new(source.as_bytes().to_vec(), &PathBuf::from("t.rs"), None) + }; + let kind_and_row = |node: &Node| (node.kind(), node.start_row()); + + let clean = parse("fn ok() {}\nfn also() {}\n"); + // expected: no node of a clean parse is or holds an error, so + // `find` returns nothing and `count` tallies none of the nodes. + let found = find(&clean, &error).expect("`find` is infallible"); + assert_eq!(found.iter().map(kind_and_row).collect::>(), []); + let (good, total) = count(&clean, &error); + assert_eq!(good, 0); + assert!(total > 1, "the clean fixture parsed to {total} nodes"); + + let broken = parse("fn ok() {}\nfn broken() { let = ; }\n"); + // The recovered shape: `let =` is the tree's one `ERROR`, in + // the body of the second function, and no token is invented. + let errors: Vec<_> = broken.root().preorder().filter(Node::is_error).collect(); + let [error_node] = errors[..] else { + panic!("the fixture must recover into one `ERROR`, got {errors:?}"); + }; + assert!(broken.root().preorder().all(|node| !node.is_missing())); + // expected: the `ERROR` and each of its ancestors, root first, + // which is the order `find` visits them in. `fn ok` on row 0 + // holds no error and is on no such path. + let mut path: Vec<_> = std::iter::successors(Some(error_node), Node::parent) + .map(|node| kind_and_row(&node)) + .collect(); + path.reverse(); + assert_eq!( + path, + [ + ("source_file", 0), + ("function_item", 1), + ("block", 1), + ("ERROR", 1) + ] + ); + let found = find(&broken, &error).expect("`find` is infallible"); + assert_eq!(found.iter().map(kind_and_row).collect::>(), path); + assert_eq!(count(&broken, &error).0, path.len()); + } +} From 2957ead1c0fe0397e843a6a1eb9f097a5471ba21 Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Thu, 12 Nov 2026 21:46:38 -0800 Subject: [PATCH 33/42] test(checker): pin the byte a run verdict's reach ends on checker.rs:345:58 turns the `<` of `SubtreeSkip::answers_for` into `<=` and survived the full mutation run at 68b70b08. A verdict then also answers for every node that starts on the byte it names, where `covering_through_node` means to add one node only, the run's item. No walk over a clean parse shows the difference. The other nodes on that byte are the item's own leading descendants. The pinned grammar puts no prunable item there, and an attribute only at the head of a match arm or a field initializer, where it decorates nothing the prune removes. The hook retains each of them whether it is asked or not. So the reach is asked directly, on `#[inline]` above a `fn`: the verdict answers for the attribute's descendants and for the `function_item`, and not for the `fn` keyword on the same byte. Refs #1736 --- big-code-analysis-ast/src/checker.rs | 57 ++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) diff --git a/big-code-analysis-ast/src/checker.rs b/big-code-analysis-ast/src/checker.rs index 230cb1849..af5d1f3f6 100644 --- a/big-code-analysis-ast/src/checker.rs +++ b/big-code-analysis-ast/src/checker.rs @@ -2186,6 +2186,63 @@ mod tests { ); } + /// A run's verdict answers for the run and for the item it + /// decorates, and stops there: the item's first child starts at the + /// byte the reach ends on, and is asked about on its own (#1783). + /// + /// A direct test of the reach, because no walk over a clean parse + /// shows where it ends: the only other nodes starting on that byte + /// are the item's own leading descendants, which the hook retains + /// whether it is asked or not, and a pruned item's are never + /// visited. Only a recovery tree puts a prunable node there. + #[cfg(feature = "rust")] + #[test] + fn a_run_verdict_answers_for_its_item_and_not_for_the_items_first_child() { + let code = b"#[inline]\nfn f() {}\n"; + let mut verdict: Option = None; + let mut after_the_attribute = Vec::new(); + for_each_node_with_chain::(code, |node, chain| { + if let Some(verdict) = verdict { + after_the_attribute.push(( + node.kind(), + node.start_byte(), + verdict.answers_for(node), + )); + } else if node.kind_id() == Rust::AttributeItem { + verdict = Some(RustCode::should_skip_subtree( + node, + code, + Ancestors::known(chain), + )); + } + }); + // expected: `#[inline]` is bytes 0..9 and `fn f() {}` starts at + // byte 10. The verdict answers for the attribute's five + // descendants, which start before byte 10, and for the + // `function_item`, which it names. The `fn` keyword starts at + // byte 10 as well and is not the named node, so it is not + // answered for, and nothing after it is. + assert_eq!( + after_the_attribute, + [ + ("#", 0, true), + ("[", 1, true), + ("attribute", 2, true), + ("identifier", 2, true), + ("]", 8, true), + ("function_item", 10, true), + ("fn", 10, false), + ("identifier", 13, false), + ("parameters", 14, false), + ("(", 14, false), + (")", 15, false), + ("block", 17, false), + ("{", 17, false), + ("}", 18, false), + ] + ); + } + #[cfg(feature = "groovy")] #[test] fn groovy_is_else_if_recognises_else_followed_by_if() { From 08d51811ab216c9286b2e2d1495a016887d03695 Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Thu, 12 Nov 2026 21:46:39 -0800 Subject: [PATCH 34/42] test(spaces): prune a test module that starts where a reach ends The `exclude_tests` walk is the consumer of `SubtreeSkip::answers_for`, and it shows the `<` that checker.rs:345:58 mutates only on a recovery tree. `struct S` with no `;` above a `///` row and a module holding `#![cfg(test)]` recovers as a `struct_item` that keeps the doc comment and ends in an invented zero-width `;`. The doc comment's run ends at that `;`, on the byte where the module starts. With `<=` the run's `RETAIN` answered for the module as well, and its test code stayed. rustc rejects the fixture. The test pins what the prune does there and asserts the recovered shape first, so a grammar bump that recovers differently fails as fixture drift rather than as a wrong count. Kept apart from the direct test of the reach so this commit can be dropped if recovery input is not to be pinned. Refs #1736 --- src/spaces_tests.rs | 53 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) diff --git a/src/spaces_tests.rs b/src/spaces_tests.rs index 82877ab68..16759786c 100644 --- a/src/spaces_tests.rs +++ b/src/spaces_tests.rs @@ -1663,6 +1663,59 @@ impl Foo { ); } } + + // A run's verdict reaches the nodes that start before the byte it + // names, and a node that starts on that byte is asked about on its + // own. No clean parse puts a prunable node there: the byte is where + // the run's item starts, and only the item's own first child shares + // it. So this source is one rustc rejects, a `struct` with no `;` + // above a documented test module. The grammar keeps the `///` row + // inside the unfinished `struct_item` and closes it with an invented + // zero-width `;`, which is the item the doc comment's run ends at, + // on the byte where `mod t` starts. A reach that took that byte in + // answered `RETAIN` for `mod t` and kept the test code in it. + #[test] + fn a_reach_ending_where_a_test_module_starts_does_not_keep_the_module() { + let source = + "fn keep() {}\nstruct S\n/// doc\nmod t {\n #![cfg(test)]\n fn u() {}\n}\n"; + // The recovered shape. `fn keep() {}` and its line break are + // bytes 0..13, `struct S` 13..21, and the `///` row with its + // line break 22..30, so `mod` starts at byte 30; the module's + // three rows are 8, 18 and 14 bytes and its `}` is byte 70. + let parser = RustParser::new(source.as_bytes().to_vec(), &PathBuf::from("lib.rs"), None); + let spans = |node: crate::Node| -> Vec<(&str, usize, usize)> { + node.children() + .map(|child| (child.kind(), child.start_byte(), child.end_byte())) + .collect() + }; + assert_eq!( + spans(parser.root()), + [ + ("function_item", 0, 12), + ("struct_item", 13, 30), + ("mod_item", 30, 71), + ] + ); + let unfinished = parser.root().child(1).expect("the `struct_item`"); + assert_eq!( + spans(unfinished), + [ + ("struct", 13, 19), + ("type_identifier", 20, 21), + ("line_comment", 22, 30), + (";", 30, 30), + ] + ); + + // expected: `keep` and `u` are the functions. `mod t` is + // test-only by its inner attribute, so the prune takes it and + // `u` with it. + let baseline = analyse(source, false); + let pruned = analyse(source, true); + assert_eq!(baseline.metrics.nom.functions_sum() as usize, 2); + assert_eq!(pruned.metrics.nom.functions_sum() as usize, 1); + assert_eq!(pruned_shape(source).1, ["keep"]); + } } // Non-Rust languages must ignore `exclude_tests = true` because From 749913033d03cc88e32023760708b14840a8b8a1 Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Thu, 12 Nov 2026 21:46:39 -0800 Subject: [PATCH 35/42] test(roles): pin Groovy's byte-less is_primitive on the other nodes checker/groovy.rs:93:9 makes `GroovyCode::is_primitive` answer `true` for every node and survived the full mutation run at 68b70b08. The one test that asked it, `groovy_text_keyed_operators_are_the_primitives_1599`, asks it of the names `list` and `String`, where `true` is the answer. The method has no caller outside tests: Halstead reads Groovy's `Primitive` row through `keys_operator_by_text`, which `GroovyCode` overrides, and the trait's default of that method is the only caller of `is_primitive`. So it is asked directly on every node of a small class, as `byte_less_is_primitive_is_the_rows_kind_table` asks the eight other languages that override it: `true` for the three names, `false` for the ten other nodes. Refs #1736 --- .../src/roles/call_string_tests.rs | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/big-code-analysis-ast/src/roles/call_string_tests.rs b/big-code-analysis-ast/src/roles/call_string_tests.rs index 16d5cbb43..b8e212207 100644 --- a/big-code-analysis-ast/src/roles/call_string_tests.rs +++ b/big-code-analysis-ast/src/roles/call_string_tests.rs @@ -1080,3 +1080,41 @@ fn byte_less_is_primitive_is_the_rows_kind_table() { probe::("rust", rs, primitive::OWNERS, primitive::lists_kind, &unmet); } } + +/// Groovy's byte-less `Checker::is_primitive` is the `Primitive` row's +/// kind table as well, and that table is the two name kinds: a +/// primitive there is a name told by its text, which this spelling +/// cannot read (#1599). So it answers `true` for every name, `int` and +/// `a` alike, and `false` for every other node. +/// +/// Asked directly, because no walk asks it: Halstead reads the row +/// through `keys_operator_by_text`, which `GroovyCode` overrides. +#[cfg(feature = "groovy")] +#[test] +fn groovy_byte_less_is_primitive_is_the_name_kinds_and_nothing_else() { + let source = b"class C {\n int a = 1\n}\n"; + let mut answers = Vec::new(); + for_each_node_with_chain::(source, |node, _| { + answers.push((node.kind(), crate::GroovyCode::is_primitive(node))); + }); + // expected: in document order, the class name, the `int` and the + // field name are the tree's three names. + assert_eq!( + answers, + [ + ("source_file", false), + ("class_declaration", false), + ("class", false), + ("identifier", true), + ("class_body", false), + ("{", false), + ("field_declaration", false), + ("type_identifier", true), + ("variable_declarator", false), + ("identifier", true), + ("=", false), + ("number_literal", false), + ("}", false), + ] + ); +} From bb1df43d953c40460bd06697364562d54f21bd9c Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Thu, 12 Nov 2026 21:46:39 -0800 Subject: [PATCH 36/42] test(comment_rm): keep a Python encoding declaration when stripping Two mutants survived the full mutation run at 68b70b08, both in `PythonCode::is_useful_comment`: checker/python.rs:14:9 makes it answer `false`, and 14:26 turns `start_row() <= 1` into `> 1`. No test asserted that a `coding` comment on the first or second line survives `rm_comments`. The test strips two sources and compares the whole output. The declaration stays on the first line of one and on the second line of the other. A trailing comment, a shebang and the same `coding` words on the third line go. Refs #1736 --- big-code-analysis-ast/src/comment_rm.rs | 39 ++++++++++++++++++++++++- 1 file changed, 38 insertions(+), 1 deletion(-) diff --git a/big-code-analysis-ast/src/comment_rm.rs b/big-code-analysis-ast/src/comment_rm.rs index 1bf8aeb37..9e58504d5 100644 --- a/big-code-analysis-ast/src/comment_rm.rs +++ b/big-code-analysis-ast/src/comment_rm.rs @@ -184,7 +184,8 @@ mod tests { use std::path::PathBuf; use crate::{ - CParser, CcommentParser, CppParser, MozcppParser, ObjcParser, ParserTrait, RustParser, + CParser, CcommentParser, CppParser, MozcppParser, ObjcParser, ParserTrait, PythonParser, + RustParser, }; use super::rm_comments; @@ -322,6 +323,42 @@ mod tests { ); } + /// Python's `Checker::is_useful_comment` keeps an encoding + /// declaration: a comment on the first or second line that names a + /// `coding`, the two lines PEP 263 reads one from. Stripping it + /// changes how the file decodes. + /// + /// Each kept row sits beside rows that must go, so neither an + /// `is_useful_comment` that keeps nothing nor one that keeps every + /// comment passes: a trailing comment, a shebang on the first line, + /// and a `coding` comment on the third line, where it declares + /// nothing. + #[cfg(feature = "python")] + #[test] + fn python_keeps_an_encoding_declaration_on_the_first_two_lines_only() { + let strip = |source: &str| { + let path = PathBuf::from("foo.py"); + let parser = PythonParser::new(source.as_bytes().to_vec(), &path, None); + let stripped = rm_comments(&parser).expect("each fixture has a removable comment"); + String::from_utf8(stripped).expect("stripping preserves UTF-8") + }; + + // expected: the declaration on the first line stays; the + // trailing comment goes and leaves the two spaces before it. + assert_eq!( + strip("# coding: utf-8\nx = 1 # drop\n"), + "# coding: utf-8\nx = 1 \n" + ); + // expected: the shebang names no `coding` and goes; the + // declaration on the second line stays; the same words on the + // third line are an ordinary comment and go. A removed + // one-line comment leaves its line break behind. + assert_eq!( + strip("#!/usr/bin/env python\n# -*- coding: latin-1 -*-\n# coding: utf-8\nx = 1\n"), + "\n# -*- coding: latin-1 -*-\n\nx = 1\n" + ); + } + /// The C-family `Checker::is_useful_comment` impls (C, C++, Mozilla /// C++, Objective-C, and the comment-only `Ccomment` grammar) all /// delegate to one Aho-Corasick automaton whose single needle is From 5730698ec4673f5447eb68e5ded944cb1c287869 Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Thu, 12 Nov 2026 21:46:39 -0800 Subject: [PATCH 37/42] test(dloc): pin three doc-comment readings no fixture exercised Four mutants survived the full mutation run at 68b70b08, in three readings the `dloc` tables did not reach. checker/groovy.rs:53:17 turns `is_func_with_code || is_closure` into `&&` in `holds_doc_comment_in_body`, so neither a callable nor a closure holds a doc comment. Every in-body fixture sat in a `block`, which the `DocBodyResidual` row holds by itself. The new rows put the comment in a closure's body and in a parameter's default value, where no `block` encloses it. checker/lua.rs:30:60 and 30:63 change what `lua_block_text` counts as text: any byte at all, or a whitespace byte. Every empty block in the fixtures was a row of dashes, whose body is empty either way. The new rows are a `---` row holding one space and a `---F.` row with no whitespace. checker/php.rs:38:47 makes `php_file_docblock` stop at the first node after the DocBlock, a `declare` or a plain comment included. The fixtures put a non-element or a second DocBlock after such a node, where stopping there answers the same. The new rows put the file's first class and its first function after one. Refs #1736 --- src/metrics/loc/dloc.rs | 115 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 115 insertions(+) diff --git a/src/metrics/loc/dloc.rs b/src/metrics/loc/dloc.rs index 15cbf59cd..b412f797d 100644 --- a/src/metrics/loc/dloc.rs +++ b/src/metrics/loc/dloc.rs @@ -1827,6 +1827,48 @@ mod tests { ); } + /// A Groovy callable or closure holds a doc comment anywhere inside + /// it, as Java's does: the whole node counts, not only a braced + /// body. The in-body rows of the tables below sit in a method's + /// `block`, which the `DocBodyResidual` row holds whatever the + /// callable and the closure answer. Here no `block` encloses the + /// comment: a closure's statements are its direct children, and a + /// parameter's default value sits in the signature. The comment is + /// above a method of an anonymous class, a documentation target, so + /// only the enclosing closure or method keeps it out of `dloc`. The + /// last row is the same class with neither around it. + #[cfg(feature = "groovy")] + #[test] + fn groovy_closures_and_signatures_hold_their_doc_comments() { + // expected: each source holds one comment row, so `cloc` 1. A + // doc comment inside a closure or a callable is a working note, + // `dloc` 0; directly above a method outside both it binds to + // the method, `dloc` 1. + assert_doc_rows( + LANG::Groovy, + &[ + ( + "in a closure", + b"class C {\n def c = {\n new Object() {\n /** Doc. */\n void m() { }\n }\n }\n}\n", + 0, + 1, + ), + ( + "in a parameter's default value", + b"class C {\n def f(a = new Object() {\n /** Doc. */\n void m() { }\n }) { }\n}\n", + 0, + 1, + ), + ( + "in a field initializer, outside both", + b"class C {\n def c = new Object() {\n /** Doc. */\n void m() { }\n }\n}\n", + 1, + 1, + ), + ], + ); + } + /// Roslyn's `GetDocumentationCommentTriviaFromSyntaxNode` reads a /// member's leading trivia back past plain comments and directives to /// the nearest doc comment, then keeps every doc comment before it @@ -2105,6 +2147,48 @@ mod tests { ); } + /// `createFileDocBlock` decides at the file's first element, not at + /// the first node after the DocBlock: it reads past a `declare` and + /// past a plain comment, counting the DocBlocks on the way (#1613). + /// The rows above put a non-element or a second DocBlock after the + /// preamble, where stopping at the preamble answers the same. + #[cfg(feature = "php")] + #[test] + fn php_file_docblock_is_decided_at_the_first_element_past_the_preamble() { + assert_doc_rows( + LANG::Php, + &[ + // expected: the first element is the class and one + // DocBlock precedes it, not two, so the file has none. + // PHP-Parser hands the DocBlock to the `declare`, which + // is no element, so it documents nothing. + ( + "one DocBlock, a declare, the first class", + b" Date: Thu, 12 Nov 2026 21:50:47 -0800 Subject: [PATCH 38/42] ci(mutation): exclude seven checker mutants on bodies no language reaches The trait defaults of `is_comment`, `is_call` and `is_string` run for no language: all twenty-five impls define them through the row macros, and the only inheritors are two test probes that call no `Checker` method. The Ccomment and Preproc `is_func_space_with_code` and `is_func_with_code` read tables with no opener and no callable, so they answer `false` before the mutant does. The configured list differs from the unconfigured one by exactly these seven and the thirty earlier entries. The nine `is_non_arg` mutants (the trait default and the Bash, Go, iRules, Lua and Tcl overrides) are unreachable too and are left out here: C# removed its unused override rather than keep it, and whether these follow is a decision for the code, not for this file. So is `rust_attribute_run_member`'s second `||`, which is equivalent while the two Rust comment rows list the same kinds but shares its line-free name and its column with a live mutant one line above. Refs #1736 --- .cargo/mutants.toml | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/.cargo/mutants.toml b/.cargo/mutants.toml index 17cdf4093..360dfd84e 100644 --- a/.cargo/mutants.toml +++ b/.cargo/mutants.toml @@ -153,6 +153,18 @@ exclude_re = [ # a leading identifier of at least one byte, so `prefix_len` is never # 0 here and `>` and `>=` agree. '''^big-code-analysis-ast/src/getter/kotlin\.rs:\d+:\d+: replace > with >= in kotlin_short_interp_operand_bytes$''', + # Unreachable. Every `impl Checker for` in `checker/` defines these + # three itself, through `impl_comment_from_rows!` or + # `impl_doc_comment_rows_in_bodies!` and through + # `impl_row_predicates!`, so the trait's default bodies run for no + # language. The only types that inherit them are two test probes in + # `cyclomatic.rs`, which call no `Checker` method. A language added + # without the macros would make them live. + '^big-code-analysis-ast/src/checker\.rs:\d+:\d+: replace Checker::(is_comment|is_call|is_string) -> bool with true$', + # Equivalent. Both bodies read a role table in which `FuncOpener` and + # `Container` are `absent`, so each already answers `false` for every + # node of a Ccomment or Preproc tree. + '^big-code-analysis-ast/src/checker/(ccomment|preproc)\.rs:\d+:\d+: replace ::(is_func_space_with_code|is_func_with_code) -> bool with false$', # Non-terminating under mutation. The loop then breaks when # `goto_next_sibling` succeeds and repeats when it fails, so a list # with one child is visited forever. Its one caller walks the values From 6651984cf6ed30108d240c59676368b21df1f700 Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Thu, 12 Nov 2026 21:52:00 -0800 Subject: [PATCH 39/42] ci(mutation): split the run across eighteen shards Run 43278927651 put sixteen shards of 341 mutants through in 125 to 222 minutes, two of them past the 200 minutes the guide gives as the point to raise the count; the step timeout is 270. Eighteen holds about 292 of the 5249 mutants the list has once the test modules and the excluded mutants are out, roughly 190 minutes at that run's slowest rate of 39 seconds per mutant. The guide's sizing paragraph now states the current count and what it rests on. The derivation of the earlier sixteen (5048 mutants at 7008fdb3, 316 per shard, 165 minutes, against 190 for fourteen) leaves the page with it and stays in the history of this file. `make actionlint`, `make mutation-workflow-test` and `make mutation-report-test` pass. Refs #1736 --- .github/workflows/mutation-test.yml | 11 ++++++++--- docs/development/mutation_testing.md | 17 ++++++++--------- 2 files changed, 16 insertions(+), 12 deletions(-) diff --git a/.github/workflows/mutation-test.yml b/.github/workflows/mutation-test.yml index 30adfcb56..6191029a3 100644 --- a/.github/workflows/mutation-test.yml +++ b/.github/workflows/mutation-test.yml @@ -42,9 +42,14 @@ jobs: # twice either. Widening the selection to the per-language checker/, # getter/ and roles/ modules (#1728) took the census from 3673 to # 5048 mutants (`cargo mutants --list`, 27.1.0, at 7008fdb3) - # and the ast share from 5 % to 31 %. Sixteen gives ~316 per shard, + # and the ast share from 5 % to 31 %. Sixteen gave ~316 per shard, # about 165 min at those slow-runner rates; the margin to 270 is for - # the runner variance that made identical shards differ 1.6x. + # the runner variance that made identical shards differ 1.6x. The + # second complete run (43278927651, sixteen shards of 341 at + # 68b70b08) took 125 to 222 min, two shards past 200, so the count is + # eighteen: ~292 per shard of the 5249 the list holds once the test + # modules and the excluded mutants are out, about 190 min at that + # run's slowest rate of 39 s per mutant. prepare: name: shard list runs-on: ubuntu-latest @@ -56,7 +61,7 @@ jobs: - id: define run: | set -euo pipefail - shards='[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]' + shards='[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17]' echo "shards=${shards}" >> "$GITHUB_OUTPUT" echo "count=$(jq -n "${shards} | length")" >> "$GITHUB_OUTPUT" diff --git a/docs/development/mutation_testing.md b/docs/development/mutation_testing.md index c35380aa6..cb18346f3 100644 --- a/docs/development/mutation_testing.md +++ b/docs/development/mutation_testing.md @@ -127,15 +127,14 @@ slowest shard's `mutants.out/outcomes.json` — the file in each report artifact that records per-mutant `duration` — prices a root-crate mutant at ~28 seconds and an ast-crate one, which rebuilds both crates, at ~39, with a missed mutant about twice either since both -suites then run to completion. The current sixteen rests on those -per-crate rates and the census after #1728 widened the selection: -`cargo mutants --list` (27.1.0, at 7008fdb3) reports 5048 -mutants, up from 3673, and the ast share rose from 5 % to 31 % since -every added mutant is in that crate. Sixteen shards hold about 316 -each, roughly 165 minutes at the slow-runner rates; fourteen would -have been ~361 and ~190 minutes, inside the timeout but with the -margin eaten by the 1.6x host variance the first run showed between -two shards of identical composition. The laptop figure the count was first sized from, +suites then run to completion. The ast crate holds about 31 % of the +list since #1728 widened the selection. The current eighteen rests on +the second complete run (43278927651, 2026-11-12, at 68b70b08): its +sixteen shards of 341 mutants run for 125 to 222 minutes, two of them +past 200, and the slowest prices a mutant at 39 seconds. The list holds +5249 mutants with the test modules and the excluded mutants out, so +eighteen shards hold about 292 each, roughly 190 minutes at that rate. +The laptop figure the count was first sized from, about ten seconds per mutant, is roughly half the hosted cost. Both halves of `utils/mutation-report.py` are covered by `make mutation-report-test`, and the workflow's four `run:` bodies by `make From 5ca41cb186abc60ff64cf3a9d3084f4202463ceb Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Thu, 12 Nov 2026 22:14:32 -0800 Subject: [PATCH 40/42] ci(mutation): withdraw four exclusions the review could not accept - The two `&&` to `||` mutants in PHP's `Npa::compute` change no count, but each admits more members into its filter and scans their children, which `child_scan_cursors` observes. That is not the identical behaviour this file asks for. - The two guard mutants in `rust_count_assoc_const` were proved for the grammar's productions only. A `const_item` under an `ERROR` that is itself a direct child of an `impl_item` would separate them, and no one has shown recovery cannot build that. All four are open again on the issue. The `read_body` entry's comment named a `call` where the frame holds an argument list. The configured list now differs from the unconfigured one by exactly thirty-three mutants. Refs #1736 --- .cargo/mutants.toml | 14 +------------- 1 file changed, 1 insertion(+), 13 deletions(-) diff --git a/.cargo/mutants.toml b/.cargo/mutants.toml index 360dfd84e..ce21b23e5 100644 --- a/.cargo/mutants.toml +++ b/.cargo/mutants.toml @@ -58,7 +58,7 @@ exclude_re = [ '^src/metrics/npa/ruby_body\.rs:\d+:\d+: delete match arm RescueModifier \| RescueModifier2 \| RescueModifier3 in is_statement_of$', # Equivalent. With `&&` the class body's frame and an argument frame # are read through `is_statement_of`, whose answer for a parent that - # is a class body or a `call` is `child.is_named()`, the test the + # is a class body or an argument list is `child.is_named()`, the test the # original applies to those two frames itself. No frame is both. '''^src/metrics/npa/ruby_body\.rs:\d+:\d+: replace \|\| with && in RubyBodyState<'a, 'chain>::read_body$''', # Equivalent while tree-sitter-kotlin's `property_declaration` holds @@ -66,18 +66,6 @@ exclude_re = [ # `multi_variable_declaration`: without the arm a single binding sums # to 0, and the `.max(1)` on the sum makes it 1 again. '^src/metrics/npa/kotlin\.rs:\d+:\d+: delete match arm VariableDeclaration in kotlin_count_property_attrs$', - # Equivalent, both `&&` of the function. PHP's `Member` row owns - # `property_declaration` and the two `const_declaration` ids with no - # gate, so `||` only admits members of the other kind into each - # filter, and those hold no `property_element` (the class arm) and no - # `const_element` (the interface arm) to count. - '^src/metrics/npa/php\.rs:\d+:\d+: replace && with \|\| in ::compute$', - # Equivalent while tree-sitter-rust places a `const_item` or - # `static_item` only in a `block`, a `declaration_list` or the - # `source_file`: of those, only a `declaration_list` is a direct child - # of an `impl_item` or a `trait_item`, so once the grandparent matches - # the guard on the parent is true. Both arms of the function. - '^src/metrics/npa/rust\.rs:\d+:\d+: replace match guard matches!\(parent\.kind_id\(\)\.into\(\), DeclarationList\) with true in rust_count_assoc_const$', # Equivalent. `<=` differs only when the last row starts at the end # of the file, where the row is empty: its shape is blank, it pushes # one `None` and leaves nothing pending, as the original does. From 8458283cad304bdb217e2bfca47fad1f27dbae8f Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Thu, 12 Nov 2026 22:14:32 -0800 Subject: [PATCH 41/42] test(loc): assert the recovered shape before the NUL fixture's rows `python_bare_row_joining_a_comment_a_nul_cuts_short_is_code` pins a reading of a source CPython rejects. Like the other recovery fixtures it now checks the tree first: the comment ends at the NUL and an `ERROR` follows, so a grammar bump that recovers differently fails as fixture drift and not as a wrong row count. Refs #1736 --- src/metrics/loc.rs | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/src/metrics/loc.rs b/src/metrics/loc.rs index afa6a5bbc..972dc6139 100644 --- a/src/metrics/loc.rs +++ b/src/metrics/loc.rs @@ -10333,6 +10333,23 @@ EOF #[cfg(feature = "python")] #[test] fn python_bare_row_joining_a_comment_a_nul_cuts_short_is_code() { + use crate::traits::ParserTrait; + + // The fixture is this case only while the grammar ends the + // comment at the NUL and recovers past it. + let parser = PythonParser::new( + b"# c\0\nx = 1\n".to_vec(), + std::path::Path::new("foo.py"), + None, + ); + let root = parser.root(); + assert!(root.has_error(), "the NUL must leave an `ERROR`"); + let comment = root + .preorder() + .find(|node| node.kind_id() == crate::Python::Comment as u16) + .expect("the fixture holds one comment"); + assert_eq!(comment.end_byte(), 3, "the comment must stop at the NUL"); + let rows = |source: &[u8]| { loc_rows( &metrics_verbatim( From ab731b0a7c0eaa2b2267416c9248763253873504 Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Thu, 12 Nov 2026 22:14:32 -0800 Subject: [PATCH 42/42] docs(npa,getter): correct two comments the new tests made wrong `is_statement_of`'s comment said no fixture pins its exclusions, since any that told the arms apart would be one the walk reads wrongly. Three shapes do tell them apart with Ruby's own answer, and `npm.rs` now pins them; the comment names them and keeps the gap it describes for the rest. The test for the default `get_operator_id_as_str` called Ccomment and Preproc languages whose rows are all `absent`. Each declares a `Comment` and a `StringLit` row; what they lack is an operator row. Refs #1736 --- big-code-analysis-ast/src/getter.rs | 5 +++-- src/metrics/npa/ruby_body.rs | 26 ++++++++++++++------------ 2 files changed, 17 insertions(+), 14 deletions(-) diff --git a/big-code-analysis-ast/src/getter.rs b/big-code-analysis-ast/src/getter.rs index 750f74d88..e9c6743f7 100644 --- a/big-code-analysis-ast/src/getter.rs +++ b/big-code-analysis-ast/src/getter.rs @@ -2073,8 +2073,9 @@ mod keyword_role_tests { } /// The trait's default operator name is the empty string, which the - /// two pseudo-languages whose rows are all `absent` inherit: - /// `ccomment` and `preproc` bill no operator, so no kind of theirs + /// two pseudo-languages inherit. Their tables declare a `Comment` and + /// a `StringLit` row and no operator row: `ccomment` and `preproc` + /// bill no operator, so no kind of theirs /// has a name to render. No walk shows it, since their Halstead /// `compute` records no operator for `ops` to name, hence the direct /// reading. diff --git a/src/metrics/npa/ruby_body.rs b/src/metrics/npa/ruby_body.rs index f46743091..78616ec96 100644 --- a/src/metrics/npa/ruby_body.rs +++ b/src/metrics/npa/ruby_body.rs @@ -115,18 +115,20 @@ fn is_assignment(kind: u16) -> bool { // that no spelling produced; listed defensively per rule 2, and // pinned unreachable by `ruby_rescue_modifier_aliases_are_not_emitted`. // -// The exclusions are chosen by role, and no fixture pins them (the -// perturbation sweep recorded on #1401): a widened arm that read a -// condition, a loop header, a `case` value or a `when` pattern as a -// statement would find, in every valid fixture, either a local that -// shadows the keyword — which the walk already ignores — or a -// bare keyword that Ruby evaluates as the marker call, which the -// widened arm would then read *correctly* where this arm does not. -// A `when` pattern and a `rescue` class list are wrapped (`pattern`, -// `exceptions`) besides. The arms stay as the statement inventory -// they are; the fixture that would discriminate them is the one -// whose answer they get wrong, and the comment above records that -// gap rather than pinning it. +// The exclusions are chosen by role. A widened arm that read a +// condition, a loop header, a `case` value or a pattern as a +// statement would find, in most valid fixtures, either a local that +// shadows the keyword — which the walk already ignores — or a bare +// keyword that Ruby evaluates as the marker call, which the widened +// arm would then read *correctly* where this arm does not; the +// comment above records that gap rather than pinning it. Three +// shapes tell the arms apart with Ruby's own answer, and `npm.rs` +// pins them: a local the shadow ledger does not record (one bound +// inside an array literal) read in an `if` condition, a `case` value +// or a modifier's condition; a `case … in` pattern, which binds a +// local as a direct child of its clause; and a setter call's or a +// `for`'s target spelled `self.public`. A `when` pattern and a +// `rescue` class list are wrapped (`pattern`, `exceptions`) besides. fn is_statement_of(parent: &Node<'_>, parent_kind: u16, child: &Node<'_>) -> bool { use Ruby::*;