diff --git a/.cargo/mutants.toml b/.cargo/mutants.toml index e91c73ebe..ce21b23e5 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 @@ -44,21 +52,107 @@ 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$', + # 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 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 + # 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. `<=` 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$', + # 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)$', + # 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$', + # 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$''', + # 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 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/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() { 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 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()); + } +} diff --git a/big-code-analysis-ast/src/getter.rs b/big-code-analysis-ast/src/getter.rs index daf59a33a..e9c6743f7 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,113 @@ 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 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. + #[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 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), + ] + ); +} 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"]); + } +} diff --git a/docs/development/mutation_testing.md b/docs/development/mutation_testing.md index 4f6f43d4b..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 @@ -168,9 +167,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 @@ -311,13 +314,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. diff --git a/src/metrics/abc.rs b/src/metrics/abc.rs index 6a551699e..1e1e3c32f 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 @@ -6053,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 @@ -11079,6 +11202,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() { @@ -13150,6 +13297,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() { @@ -16133,6 +16305,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() { @@ -16597,6 +16808,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 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 diff --git a/src/metrics/cognitive.rs b/src/metrics/cognitive.rs index e89c7a95f..20caf51fb 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() { @@ -6554,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() { @@ -7693,6 +7763,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 +8003,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 +10554,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 diff --git a/src/metrics/halstead.rs b/src/metrics/halstead.rs index 8aa35ae64..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() { @@ -5864,6 +5914,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 +9300,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 @@ -10089,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() { @@ -12541,6 +12683,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: + // ( + "( + "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() { @@ -4890,6 +4917,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() { @@ -6362,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() { @@ -9448,6 +9546,54 @@ 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 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. @@ -10109,6 +10255,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. @@ -10124,6 +10317,114 @@ 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() { + 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( + 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)); + } + + /// 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. /// @@ -10228,6 +10529,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 +10904,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. /// @@ -11307,6 +11683,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() { @@ -11621,6 +12018,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() { @@ -12493,6 +12910,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() { @@ -13366,6 +13817,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() { @@ -13642,6 +14119,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() { 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"( + "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() { @@ -4453,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 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. 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() { 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::*; 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() { 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 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