From 4aed88bc57854290219e42cd1cfcc935ccc5d592 Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Wed, 11 Nov 2026 16:19:38 -0800 Subject: [PATCH 01/21] refactor(checker): require the with-code space predicates and drop byte-less is_func MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `Checker::is_func_with_code`, `Checker::is_func_space_with_code` and `Getter::get_space_kind_with_code` defaulted to their byte-less spellings, the reverse of what `roles/mod.rs` and `grammar_dispatch.md` §7 document. A language that wrote only the byte-less one handed a text-gated row no bytes without a word, which is how the Java record-header gate read every same-arity constructor as canonical on #1862. The three are now required. `is_func_space` and `get_space_kind` default to the with-code form asked with no bytes and a known-empty chain, so the forward runs one way only. Byte-less `is_func` is removed. It had three contracts: 20 languages passed the caller's chain with no bytes, Java and Groovy discarded the chain, Elixir answered `false`. Its production readers move to `is_func_with_code`: - the Go, Kotlin, Lua, Tcl, iRules and Perl `NArgs::compute` impls; - `holds_doc_comment_in_body`, which gains a `code` parameter, as do `held_in_body` and `outside_function_bodies`. The JS family and C# need the real chain there, so a derived kind-table `is_func` would have moved `dloc`. No metric value moves: 7287 workspace tests pass unchanged, corpus snapshots included. The baseline loses `Checker` `nom` and `Getter` `wmc`, which fell under their limits, and records `checker.rs` and `roles/mod.rs` `sloc`. It also picks up `node/ancestors.rs` `sloc` 1292 -> 1294, which was already stale on main at a62077d5. Refs #1863 --- .bca-baseline.toml | 16 +- .claude/skills/add-lang/SKILL.md | 33 +++-- big-code-analysis-ast/src/checker.rs | 139 +++++++++--------- big-code-analysis-ast/src/checker/bash.rs | 4 +- big-code-analysis-ast/src/checker/c.rs | 4 +- big-code-analysis-ast/src/checker/ccomment.rs | 14 ++ big-code-analysis-ast/src/checker/cpp.rs | 4 +- big-code-analysis-ast/src/checker/csharp.rs | 7 +- big-code-analysis-ast/src/checker/elixir.rs | 8 +- big-code-analysis-ast/src/checker/go.rs | 4 +- big-code-analysis-ast/src/checker/groovy.rs | 17 +-- big-code-analysis-ast/src/checker/irules.rs | 4 +- big-code-analysis-ast/src/checker/java.rs | 24 +-- .../src/checker/javascript.rs | 4 +- .../src/checker/js_doc_binding.rs | 7 +- big-code-analysis-ast/src/checker/kotlin.rs | 9 +- big-code-analysis-ast/src/checker/lua.rs | 4 +- big-code-analysis-ast/src/checker/mozcpp.rs | 4 +- big-code-analysis-ast/src/checker/mozjs.rs | 4 +- big-code-analysis-ast/src/checker/objc.rs | 6 +- big-code-analysis-ast/src/checker/perl.rs | 4 +- big-code-analysis-ast/src/checker/php.rs | 5 +- big-code-analysis-ast/src/checker/preproc.rs | 14 ++ big-code-analysis-ast/src/checker/python.rs | 4 +- big-code-analysis-ast/src/checker/ruby.rs | 4 +- big-code-analysis-ast/src/checker/rust.rs | 4 +- big-code-analysis-ast/src/checker/tcl.rs | 4 +- big-code-analysis-ast/src/checker/tsx.rs | 4 +- .../src/checker/typescript.rs | 4 +- big-code-analysis-ast/src/getter.rs | 46 +++--- big-code-analysis-ast/src/getter/ccomment.rs | 9 ++ big-code-analysis-ast/src/getter/preproc.rs | 9 ++ .../src/lang_helpers/doc_comment.rs | 10 +- .../src/lang_helpers/doxygen.rs | 2 +- big-code-analysis-ast/src/lib.rs | 2 +- big-code-analysis-ast/src/node.rs | 2 +- big-code-analysis-ast/src/parser.rs | 2 +- .../src/roles/derived_parity_tests.rs | 10 +- .../src/roles/doc_tests/mod.rs | 26 ++-- big-code-analysis-ast/src/roles/elixir.rs | 5 +- big-code-analysis-ast/src/roles/java.rs | 9 +- big-code-analysis-ast/src/roles/js_family.rs | 6 +- big-code-analysis-ast/src/roles/mod.rs | 67 +++++---- big-code-analysis-ast/src/roles/python.rs | 4 +- .../src/roles/space_tree_tests.rs | 49 +++--- big-code-analysis-bench/src/shapes.rs | 12 +- docs/development/benchmarking.md | 2 +- docs/development/grammar_dispatch.md | 30 ++-- src/function.rs | 3 +- src/metrics/cognitive.rs | 4 +- src/metrics/cyclomatic.rs | 25 +++- src/metrics/nargs.rs | 121 ++++++--------- src/metrics/nom.rs | 25 ++-- src/metrics/npm.rs | 4 +- src/metrics/npm/kotlin.rs | 2 +- src/metrics/npm/python.rs | 2 +- src/metrics/wmc.rs | 6 +- src/spaces_tests.rs | 10 +- src/suppression.rs | 21 ++- tests/api/ast_seam_test.rs | 2 +- tests/grammars/c_grammar_metrics.rs | 4 +- tests/parity/functions_metrics_parity.rs | 4 +- tests/parity/ops_metrics_space_parity.rs | 2 +- 63 files changed, 468 insertions(+), 432 deletions(-) diff --git a/.bca-baseline.toml b/.bca-baseline.toml index f29c2af4b..567c8f5ac 100644 --- a/.bca-baseline.toml +++ b/.bca-baseline.toml @@ -215,19 +215,7 @@ value = 5.0 path = "big-code-analysis-ast/src/checker.rs" qualified = "" metric = "loc.sloc" -value = 1285.0 - -[[entry]] -path = "big-code-analysis-ast/src/checker.rs" -qualified = "Checker" -metric = "nom" -value = 29.0 - -[[entry]] -path = "big-code-analysis-ast/src/getter.rs" -qualified = "Getter" -metric = "wmc" -value = 58.0 +value = 1288.0 [[entry]] path = "big-code-analysis-ast/src/getter.rs" @@ -377,7 +365,7 @@ value = 894.0 path = "big-code-analysis-ast/src/roles/mod.rs" qualified = "" metric = "loc.sloc" -value = 2268.0 +value = 2279.0 [[entry]] path = "big-code-analysis-ast/src/tools.rs" diff --git a/.claude/skills/add-lang/SKILL.md b/.claude/skills/add-lang/SKILL.md index b61a2ca23..582ec95fc 100644 --- a/.claude/skills/add-lang/SKILL.md +++ b/.claude/skills/add-lang/SKILL.md @@ -536,13 +536,15 @@ Create the file, add `mod ;` to `checker.rs`, and write answer `false`, which is right for a language with no doc convention. Where one exists, `lang_helpers/doc_text.rs` has the shared opener tests. -- `is_func_space` / `is_func_space_with_code`, `is_func`, - `is_closure` — forward to the table: `crate::roles::::opens_space` - (emitted once per table as the fold over every `opens K` annotation - on the `FuncOpener` and `Container` rows) for the space predicates, - `func_opener::is_callable` for `is_func`, `closure::owns` for - `is_closure` (#1696). Copy the Lua or Go shape, including the - byte-less `is_func_space` forwarding with `Ancestors::known(&[])`. +- `is_func_space_with_code`, `is_func_with_code`, `is_closure` — + forward to the table: `crate::roles::::opens_space` (emitted + once per table as the fold over every `opens K` annotation on the + `FuncOpener` and `Container` rows) for the space predicate, + `func_opener::is_callable` for `is_func_with_code`, `closure::owns` + for `is_closure` (#1696). The two `_with_code` predicates are + required: the trait gives them no default (#1863). Copy the Lua or + Go shape, including `impl_byte_less_func_space!`, which emits the + byte-less `is_func_space` with its build-time pin. - `is_call`, `is_call_with_code`, `is_string`, `is_string_with_code` — one `impl_row_predicates!(, call, …)` and one `impl_row_predicates!(, string_lit, …)` line each @@ -594,12 +596,13 @@ Create the file, add `mod ;` to `checker.rs`, and write Create the file, add `mod ;` to `getter.rs`, and write `impl Getter for Code`. Required methods: -- `get_space_kind` / `get_space_kind_with_code` — forward to - `crate::roles::::opens_space`, the fold over every `opens K` - annotation on the `FuncOpener` and `Container` rows (#1696). The - byte-less spelling forwards with `Ancestors::known(&[])`, as the - Lua and Go impls do; `is_func_space` and `get_space_kind` must read - the same predicate or the space tree disagrees with itself +- `get_space_kind_with_code` — **required** by the trait (no default, + #1863); forward to `crate::roles::::opens_space`, the fold + over every `opens K` annotation on the `FuncOpener` and `Container` + rows (#1696). `impl_byte_less_space_kind!();` emits the + byte-less `get_space_kind` with its build-time pin, as the Lua and + Go impls do; `is_func_space` and `get_space_kind` must read the same + predicate or the space tree disagrees with itself (`grammar-dispatch.md` §7). - `keyword_roles!();` — emits `get_keyword_role`, which is **required** by the trait (no default), from the `Modifier`, @@ -893,8 +896,8 @@ Add real impls for the remaining metrics where the grammar exposes the necessary nodes: - **Nom** (`src/metrics/nom.rs`): default trait body usually works if - `Checker::is_func` and `Checker::is_closure` are correct. Verify - with a unit test before assuming. + `Checker::is_func_with_code` and `Checker::is_closure` are correct. + Verify with a unit test before assuming. - **NArgs** (`src/metrics/nargs.rs`): default counts direct children of the parameter list. Some grammars group same-typed parameters into a single node (Go does this with `parameter_declaration`, diff --git a/big-code-analysis-ast/src/checker.rs b/big-code-analysis-ast/src/checker.rs index 29450251b..eb8a0f2b8 100644 --- a/big-code-analysis-ast/src/checker.rs +++ b/big-code-analysis-ast/src/checker.rs @@ -351,12 +351,17 @@ impl SubtreeSkip { /// recognize comments, function spaces, calls, strings, branches, and so /// on by node kind. /// -/// Every predicate defaults to `false` — "this node is never of that +/// Most predicates default to `false` — "this node is never of that /// category." A language implements only the predicates its grammar /// actually expresses; categories it lacks fall through to the default, /// so adding a language no longer requires copy-pasting `-> false` stubs. /// The flip side is that the compiler cannot flag a forgotten override, so /// each language's per-metric tests are the safety net for completeness. +/// The two the space tree is built from are the exception: +/// [`is_func_space_with_code`](Self::is_func_space_with_code) and +/// [`is_func_with_code`](Self::is_func_with_code) are required, so a +/// language cannot answer them by forwarding to a spelling that drops +/// the bytes or the chain (#1863). /// /// `#[doc(hidden)]` for the reason the crate root gives: this is /// plumbing, and the surface the README points a reader at is `LANG` / @@ -428,15 +433,19 @@ pub trait Checker { /// and the C# specification wants one before a member's attributes, /// so a doc comment after an annotation or on a parameter documents /// nothing there. A language whose tool reads doc comments in the - /// signature narrows this to the body proper (#1597). + /// signature narrows this to the body proper (#1597). `code` is + /// the source, for the callable test: a callable told by its bytes + /// or its chain (a record's header, a bound arrow) is asked as the + /// walk asks it (#1863). #[inline] #[must_use] fn holds_doc_comment_in_body<'a>( ancestor: &Node<'a>, + code: &[u8], ancestors: Ancestors<'a, '_>, _below: &Node<'a>, ) -> bool { - Self::is_func(ancestor, ancestors) || Self::is_closure(ancestor, ancestors) + Self::is_func_with_code(ancestor, code, ancestors) || Self::is_closure(ancestor, ancestors) } /// Whether `comment`, held in a body by `ancestor` (one of its two /// nearest ancestors, with `below` the node between them), is that @@ -521,38 +530,29 @@ pub trait Checker { fn is_doc_run_directive(_: &Node, _code: &[u8]) -> bool { false } - /// Whether `node` opens a space: a function, closure, or one of the - /// containers (class, struct, trait, impl, namespace, interface). - #[inline] - #[must_use] - fn is_func_space(_: &Node) -> bool { - false - } - /// Whether `node` is a *named* function definition. - /// - /// `ancestors` is the chain the caller descended through. The - /// JS-family grammars have no distinct production for a named - /// function: `const f = () => …` and `g(() => …)` share one - /// `arrow_function` node, and only what encloses it says which is - /// which. Those steps come off the chain, because `Node::parent` - /// costs `O(depth)` each however few of them a walk takes (#1088). - /// Every other grammar answers `is_func` from the node's own kind - /// and ignores the parameter. + /// Whether `node` opens a space by its kind alone: a function, + /// closure, or one of the containers (class, struct, trait, impl, + /// namespace, interface). /// - /// The suppression scan asks this through a chain that records no - /// siblings, so an impl must not ask `ancestors` for one: under a - /// wide parent that trips the walk assertion in a debug build - /// (#1601). + /// The byte-less spelling of + /// [`is_func_space_with_code`](Self::is_func_space_with_code), and + /// by default that predicate asked with no bytes and a known-empty + /// chain — the node read as if it were the root (#1863). It agrees + /// with the walk wherever no space-opening gate reads either, and + /// answers the gate's rootless, byte-less verdict where one does + /// (Ruby's lambda body, C#'s primary constructor, a Java or Groovy + /// record's header). The walk calls the `_with_code` one. #[inline] #[must_use] - fn is_func<'a>(_: &Node<'a>, _ancestors: Ancestors<'a, '_>) -> bool { - false + fn is_func_space(node: &Node) -> bool { + Self::is_func_space_with_code(node, &[], Ancestors::known(&[])) } /// Whether `node` is an anonymous function — the complement of - /// [`is_func`](Self::is_func) on the grammars that express both. Takes `ancestors` - /// for the same reason, plus one of its own: Ruby's `{ … }` block is - /// a closure only when its parent is not the `Lambda` that already - /// counted it. + /// [`is_func_with_code`](Self::is_func_with_code) on the grammars + /// that express both. `ancestors` is the chain the caller descended + /// through: the JS family tells a bound arrow from a positional one + /// by what encloses it, and Ruby's `{ … }` block is a closure only + /// when its parent is not the `Lambda` that already counted it. #[inline] #[must_use] fn is_closure<'a>(_: &Node<'a>, _ancestors: Ancestors<'a, '_>) -> bool { @@ -805,43 +805,46 @@ pub trait Checker { SubtreeSkip::RETAIN } - /// Source-aware variant of [`is_func_space`](Self::is_func_space). The default forwards - /// to the byte-less predicate so languages whose function-space - /// classification is encoded in distinct grammar productions (Java, - /// Rust, Python, …) need no override. Languages whose function - /// boundaries are macro-shaped — Elixir's `def` / `defp` / - /// `defmacro` / `defmacrop` / `defmodule` — override this to - /// disambiguate `Call` nodes by their target identifier text - /// (#275). + /// Whether `node` opens a space, as the walk asks it: with the + /// source bytes and the chain it descended through. Required: every + /// language answers from its role table's `opens_space` fold, and + /// the byte-less [`is_func_space`](Self::is_func_space) derives + /// from this, never the reverse — a default forwarding the other + /// way handed a text-gated row no bytes without a word (#1863). /// - /// `ancestors` is the chain the caller descended through, so a - /// language whose classification depends on an enclosing construct - /// (Elixir's `quote` template) can answer without paying - /// `Node::parent`'s `O(depth)` per step (#1084). - #[inline] + /// Elixir's `def` / `defmodule` are `Call`s told apart by their + /// target text (#275), and a `def` inside a `quote` template by the + /// chain, read here rather than through `Node::parent`'s `O(depth)` + /// per step (#1084). #[must_use] fn is_func_space_with_code<'a>( node: &Node<'a>, - _code: &[u8], - _ancestors: Ancestors<'a, '_>, - ) -> bool { - Self::is_func_space(node) - } - - /// Source-aware variant of [`is_func`](Self::is_func). Same rationale as - /// [`is_func_space_with_code`](Self::is_func_space_with_code) (#275). - #[inline] + code: &[u8], + ancestors: Ancestors<'a, '_>, + ) -> bool; + + /// Whether `node` is a *named* function definition: the `callable` + /// owners of the language's `FuncOpener` row under their gates. + /// Required, and the only spelling (#1863): a callable can be told + /// by its bytes (Elixir's `def`, #275), by its chain (the JS + /// family's bound arrow, #1088; C#'s primary constructor, #1828) or + /// by both (a Java or Groovy record's header, #1842), so a + /// byte-less form answered three different questions across the + /// languages and was right for none of the walks. + /// + /// The suppression scan asks this through a chain that records no + /// siblings, so an impl must not ask `ancestors` for one: under a + /// wide parent that trips the walk assertion in a debug build + /// (#1601). #[must_use] - fn is_func_with_code<'a>(node: &Node<'a>, _code: &[u8], ancestors: Ancestors<'a, '_>) -> bool { - Self::is_func(node, ancestors) - } + fn is_func_with_code<'a>(node: &Node<'a>, code: &[u8], ancestors: Ancestors<'a, '_>) -> bool; /// Combined predicate the walker uses to decide whether to promote /// `node` to a new function-space frame. Default forwards to - /// `is_func_with_code || is_func_space_with_code` so existing - /// languages need no override — each kept the freedom to expose - /// `is_func` and `is_func_space` as disjoint sets (Rust includes - /// closures in `is_func_space`, Java keeps lambdas out, …) and + /// `is_func_with_code || is_func_space_with_code` so most + /// languages need no override — each keeps the freedom to expose + /// the two as disjoint sets (Rust includes closures among its + /// spaces, Java keeps lambdas out, …) and /// this method preserves that flexibility while letting Elixir /// halve its per-`Call` source-text lookups: a single /// `elixir_call_keyword` call answers both halves at once @@ -981,7 +984,7 @@ fn csharp_accessors<'a>(node: &Node<'a>) -> impl Iterator> + use /// expression-bodied form (`this[int i] => _d[i];` / `int W => _w;`), which /// has no accessor list and defines a single implicit getter. /// -/// Shared by `CsharpCode::is_func` / `is_func_space` and +/// Shared by `CsharpCode`'s callable and space tests and /// `CsharpCode::get_space_kind` so all three agree on when an indexer or /// property opens its own Function space versus deferring to its accessor /// children. This mirrors the npm reference (`csharp_count_member`): the @@ -3434,7 +3437,7 @@ mod tests { ); } - /// Asserts `is_func` / `is_closure` answer the same off a known + /// Asserts `is_func_with_code` / `is_closure` answer the same off a known /// chain as off a `Node::parent` climb, for every node of `code`. /// Returns the `(functions, closures)` the chain path counted, so a /// caller can additionally pin what the predicates actually decided. @@ -3460,9 +3463,9 @@ mod tests { let known = Ancestors::known(chain); let climbing = Ancestors::unknown(); assert_eq!( - L::is_func(node, known), - L::is_func(node, climbing), - "{label}: is_func disagrees on {} at row {}", + L::is_func_with_code(node, code, known), + L::is_func_with_code(node, code, climbing), + "{label}: is_func_with_code disagrees on {} at row {}", node.kind(), node.start_row() ); @@ -3473,7 +3476,7 @@ mod tests { node.kind(), node.start_row() ); - funcs += usize::from(L::is_func(node, known)); + funcs += usize::from(L::is_func_with_code(node, code, known)); closures += usize::from(L::is_closure(node, known)); }); assert!(visited > 20, "{label}: fixture is too small to prove much"); @@ -3486,9 +3489,9 @@ mod tests { (funcs, closures) } - /// The JS-family `is_func` / `is_closure` must classify a node the - /// same whether they read the walker's ancestor chain or climb with - /// `Node::parent` (#1088). + /// The JS-family `is_func_with_code` / `is_closure` must classify a + /// node the same whether they read the walker's ancestor chain or + /// climb with `Node::parent` (#1088). /// /// These are the predicates with the longest ancestor lookup: an /// upward walk, its `is_else_if` filter, and a `has_sibling` diff --git a/big-code-analysis-ast/src/checker/bash.rs b/big-code-analysis-ast/src/checker/bash.rs index 77a3a901e..b6a515558 100644 --- a/big-code-analysis-ast/src/checker/bash.rs +++ b/big-code-analysis-ast/src/checker/bash.rs @@ -21,8 +21,8 @@ impl Checker for BashCode { crate::roles::bash::opens_space(node, code, ancestors) != SpaceKind::Unknown } - fn is_func<'a>(node: &Node<'a>, ancestors: Ancestors<'a, '_>) -> bool { - crate::roles::bash::func_opener::is_callable(node, &[], ancestors) + fn is_func_with_code<'a>(node: &Node<'a>, code: &[u8], ancestors: Ancestors<'a, '_>) -> bool { + crate::roles::bash::func_opener::is_callable(node, code, ancestors) } // `Call` and `StringLit` are the rows of `roles/bash.rs` (#1698); diff --git a/big-code-analysis-ast/src/checker/c.rs b/big-code-analysis-ast/src/checker/c.rs index c5fe257d2..baf36c0a0 100644 --- a/big-code-analysis-ast/src/checker/c.rs +++ b/big-code-analysis-ast/src/checker/c.rs @@ -40,8 +40,8 @@ impl Checker for CCode { crate::roles::c::opens_space(node, code, ancestors) != SpaceKind::Unknown } - fn is_func<'a>(node: &Node<'a>, ancestors: Ancestors<'a, '_>) -> bool { - crate::roles::c::func_opener::is_callable(node, &[], ancestors) + fn is_func_with_code<'a>(node: &Node<'a>, code: &[u8], ancestors: Ancestors<'a, '_>) -> bool { + crate::roles::c::func_opener::is_callable(node, code, ancestors) } // C has no closures/lambdas. diff --git a/big-code-analysis-ast/src/checker/ccomment.rs b/big-code-analysis-ast/src/checker/ccomment.rs index e02fe813c..0d7cc5fec 100644 --- a/big-code-analysis-ast/src/checker/ccomment.rs +++ b/big-code-analysis-ast/src/checker/ccomment.rs @@ -7,6 +7,20 @@ impl Checker for CcommentCode { // The one `Comment` row of `roles/ccomment.rs`; no `DocComment` row (#1699). impl_comment_from_rows!(ccomment); + // The `FuncOpener` and `Container` rows of `roles/ccomment.rs` are + // absent: the pass opens no space and names no function. + fn is_func_space_with_code<'a>( + node: &Node<'a>, + code: &[u8], + ancestors: Ancestors<'a, '_>, + ) -> bool { + crate::roles::ccomment::opens_space(node, code, ancestors) != SpaceKind::Unknown + } + + fn is_func_with_code<'a>(node: &Node<'a>, code: &[u8], ancestors: Ancestors<'a, '_>) -> bool { + crate::roles::ccomment::func_opener::is_callable(node, code, ancestors) + } + fn is_useful_comment<'a>(node: &Node<'a>, code: &[u8], _ancestors: Ancestors<'a, '_>) -> bool { get_aho_corasick_match(&code[node.start_byte()..node.end_byte()]) } diff --git a/big-code-analysis-ast/src/checker/cpp.rs b/big-code-analysis-ast/src/checker/cpp.rs index ac87be8df..f988fa780 100644 --- a/big-code-analysis-ast/src/checker/cpp.rs +++ b/big-code-analysis-ast/src/checker/cpp.rs @@ -40,8 +40,8 @@ impl Checker for CppCode { crate::roles::cpp::opens_space(node, code, ancestors) != SpaceKind::Unknown } - fn is_func<'a>(node: &Node<'a>, ancestors: Ancestors<'a, '_>) -> bool { - crate::roles::cpp::func_opener::is_callable(node, &[], ancestors) + fn is_func_with_code<'a>(node: &Node<'a>, code: &[u8], ancestors: Ancestors<'a, '_>) -> bool { + crate::roles::cpp::func_opener::is_callable(node, code, ancestors) } fn is_closure<'a>(node: &Node<'a>, ancestors: Ancestors<'a, '_>) -> bool { diff --git a/big-code-analysis-ast/src/checker/csharp.rs b/big-code-analysis-ast/src/checker/csharp.rs index d15f5c4d7..9936da322 100644 --- a/big-code-analysis-ast/src/checker/csharp.rs +++ b/big-code-analysis-ast/src/checker/csharp.rs @@ -55,13 +55,14 @@ impl Checker for CsharpCode { // each of them (#1612); then the callables and the closures (#1699). fn holds_doc_comment_in_body<'a>( ancestor: &Node<'a>, + code: &[u8], ancestors: Ancestors<'a, '_>, below: &Node<'a>, ) -> bool { if doc_body_residual_kind!(csharp, ancestor, ancestors) { return below.kind_id() != Csharp::AccessorList; } - Self::is_func(ancestor, ancestors) || Self::is_closure(ancestor, ancestors) + Self::is_func_with_code(ancestor, code, ancestors) || Self::is_closure(ancestor, ancestors) } // A bodied indexer (`this[int i] { get; set; }`) or property @@ -107,8 +108,8 @@ impl Checker for CsharpCode { crate::roles::csharp::opens_space(node, code, ancestors) != SpaceKind::Unknown } - fn is_func<'a>(node: &Node<'a>, ancestors: Ancestors<'a, '_>) -> bool { - crate::roles::csharp::func_opener::is_callable(node, &[], ancestors) + fn is_func_with_code<'a>(node: &Node<'a>, code: &[u8], ancestors: Ancestors<'a, '_>) -> bool { + crate::roles::csharp::func_opener::is_callable(node, code, ancestors) } fn is_closure<'a>(node: &Node<'a>, ancestors: Ancestors<'a, '_>) -> bool { diff --git a/big-code-analysis-ast/src/checker/elixir.rs b/big-code-analysis-ast/src/checker/elixir.rs index b2ae454cc..9d3102fa2 100644 --- a/big-code-analysis-ast/src/checker/elixir.rs +++ b/big-code-analysis-ast/src/checker/elixir.rs @@ -12,8 +12,8 @@ impl Checker for ElixirCode { // the macro identifier in the `target` field, so the rows that name // them (`roles/elixir.rs`) read source bytes and, for a `def` inside // a `quote` template (#310), the chain. The byte-less `is_func_space` - // and `is_func` cannot read either and so answer the kind table - // alone: the file root and an anonymous function. The `_with_code` + // cannot read either and so answers the kind table alone: the file + // root and an anonymous function. The `_with_code` // spellings read the rows, and the walk promotes through // `promotes_to_func_space_with_code` below, which reads the one // keyword lookup both rows share rather than each row in turn. @@ -32,10 +32,6 @@ impl Checker for ElixirCode { ) } - fn is_func<'a>(_: &Node<'a>, _ancestors: Ancestors<'a, '_>) -> bool { - false - } - fn is_func_space_with_code<'a>( node: &Node<'a>, code: &[u8], diff --git a/big-code-analysis-ast/src/checker/go.rs b/big-code-analysis-ast/src/checker/go.rs index 62a882987..4052ecc8d 100644 --- a/big-code-analysis-ast/src/checker/go.rs +++ b/big-code-analysis-ast/src/checker/go.rs @@ -28,8 +28,8 @@ impl Checker for GoCode { crate::roles::go::opens_space(node, code, ancestors) != SpaceKind::Unknown } - fn is_func<'a>(node: &Node<'a>, ancestors: Ancestors<'a, '_>) -> bool { - crate::roles::go::func_opener::is_callable(node, &[], ancestors) + fn is_func_with_code<'a>(node: &Node<'a>, code: &[u8], ancestors: Ancestors<'a, '_>) -> bool { + crate::roles::go::func_opener::is_callable(node, code, ancestors) } fn is_closure<'a>(node: &Node<'a>, ancestors: Ancestors<'a, '_>) -> bool { diff --git a/big-code-analysis-ast/src/checker/groovy.rs b/big-code-analysis-ast/src/checker/groovy.rs index 394fec615..bc205c5d3 100644 --- a/big-code-analysis-ast/src/checker/groovy.rs +++ b/big-code-analysis-ast/src/checker/groovy.rs @@ -38,17 +38,18 @@ impl Checker for GroovyCode { // `roles/groovy.rs` — `static { … }` (#1699). A record's header // (`record_components`) is a callable to the walk (#1842, below) // but never a doc comment's body, as Java's is not: a comment - // inside the parentheses sits in no body. Excluded by kind, not - // left to the byte-less `is_func`'s discarded chain. + // inside the parentheses sits in no body. Excluded by kind, before + // the callable test that would admit it. fn holds_doc_comment_in_body<'a>( ancestor: &Node<'a>, + code: &[u8], ancestors: Ancestors<'a, '_>, _below: &Node<'a>, ) -> bool { // role-bypass: allow(FuncOpener) — the record header's kind is subtracted from // the body test, a doc-binding policy over the row, not whether it opens a space ancestor.kind_id() != Groovy::RecordComponents as u16 - && (Self::is_func(ancestor, ancestors) + && (Self::is_func_with_code(ancestor, code, ancestors) || Self::is_closure(ancestor, ancestors) || doc_body_residual_kind!(groovy, ancestor, ancestors)) } @@ -76,14 +77,8 @@ impl Checker for GroovyCode { crate::roles::groovy::opens_space(node, code, ancestors) != SpaceKind::Unknown } - // As Java's pair (`checker/java.rs`): the `_with_code` spelling is - // the row, which the record header's text gate needs; the byte-less - // one forwards a known-empty chain so the header answers `false` - // rather than the degenerate gate. - fn is_func<'a>(node: &Node<'a>, _ancestors: Ancestors<'a, '_>) -> bool { - crate::roles::groovy::func_opener::is_callable(node, &[], Ancestors::known(&[])) - } - + // As Java's (`checker/java.rs`): the row, whose record-header gate + // reads the chain and the bytes. fn is_func_with_code<'a>(node: &Node<'a>, code: &[u8], ancestors: Ancestors<'a, '_>) -> bool { crate::roles::groovy::func_opener::is_callable(node, code, ancestors) } diff --git a/big-code-analysis-ast/src/checker/irules.rs b/big-code-analysis-ast/src/checker/irules.rs index fa14179ea..0340a98ad 100644 --- a/big-code-analysis-ast/src/checker/irules.rs +++ b/big-code-analysis-ast/src/checker/irules.rs @@ -39,8 +39,8 @@ impl Checker for IrulesCode { // Event handlers count as functions (not closures): `nom.functions` on // a typical iRules file is then the handler count, the intuitive // metric. `try` handlers are excluded — see `is_func_space`. - fn is_func<'a>(node: &Node<'a>, ancestors: Ancestors<'a, '_>) -> bool { - crate::roles::irules::func_opener::is_callable(node, &[], ancestors) + fn is_func_with_code<'a>(node: &Node<'a>, code: &[u8], ancestors: Ancestors<'a, '_>) -> bool { + crate::roles::irules::func_opener::is_callable(node, code, ancestors) } // iRules has no anonymous lambda node (`apply` is an ordinary command). diff --git a/big-code-analysis-ast/src/checker/java.rs b/big-code-analysis-ast/src/checker/java.rs index cd025edb9..38dbdf55e 100644 --- a/big-code-analysis-ast/src/checker/java.rs +++ b/big-code-analysis-ast/src/checker/java.rs @@ -40,19 +40,18 @@ impl Checker for JavaCode { // header is a callable to the walk (#1842, below) but never a doc // comment's body: a comment inside the parentheses sits in no body, // the pre-#1842 reading, and javac attaches it to nothing. The - // header kind is excluded here by name rather than left to the - // byte-less `is_func`, which omits the header only because its - // forward discards the chain; a chain-reading `is_func` would not - // move this answer. + // header kind is excluded here by name, before the callable test + // that would admit it. fn holds_doc_comment_in_body<'a>( ancestor: &Node<'a>, + code: &[u8], ancestors: Ancestors<'a, '_>, _below: &Node<'a>, ) -> bool { // role-bypass: allow(FuncOpener) — the record header's kind is subtracted from // the body test, a doc-binding policy over the row, not whether it opens a space ancestor.kind_id() != Java::FormalParameters as u16 - && (Self::is_func(ancestor, ancestors) + && (Self::is_func_with_code(ancestor, code, ancestors) || Self::is_closure(ancestor, ancestors) || doc_body_residual_kind!(java, ancestor, ancestors)) } @@ -90,17 +89,10 @@ impl Checker for JavaCode { // the body writes neither (#1842). Everything keyed on the callable // test follows from the row: `Nom`, `NArgs`, `Npm`'s // `direct_child_funcs`, and the space tree that `Wmc` and `NExits` - // are attributed through — each through the `_with_code` spelling, - // which the header's text gate needs. This byte-less one forwards a - // known-empty chain as `is_func_space` does, so the header answers - // `false` rather than the degenerate gate (under no bytes every - // same-arity constructor spells the empty type and reads as - // canonical, closing a header the walk opened); every other callable - // is kind-only and answers alike either way. - fn is_func<'a>(node: &Node<'a>, _ancestors: Ancestors<'a, '_>) -> bool { - crate::roles::java::func_opener::is_callable(node, &[], Ancestors::known(&[])) - } - + // are attributed through. The header's gate reads the chain and the + // bytes: under no bytes every same-arity constructor spells the + // empty type and reads as canonical, closing a header the walk + // opened, which is why the callable test has no byte-less spelling. fn is_func_with_code<'a>(node: &Node<'a>, code: &[u8], ancestors: Ancestors<'a, '_>) -> bool { crate::roles::java::func_opener::is_callable(node, code, ancestors) } diff --git a/big-code-analysis-ast/src/checker/javascript.rs b/big-code-analysis-ast/src/checker/javascript.rs index b67dbcacd..d9d42a85b 100644 --- a/big-code-analysis-ast/src/checker/javascript.rs +++ b/big-code-analysis-ast/src/checker/javascript.rs @@ -45,8 +45,8 @@ impl Checker for JavascriptCode { crate::roles::javascript::opens_space(node, code, ancestors) != SpaceKind::Unknown } - fn is_func<'a>(node: &Node<'a>, ancestors: Ancestors<'a, '_>) -> bool { - crate::roles::javascript::func_opener::is_callable(node, &[], ancestors) + fn is_func_with_code<'a>(node: &Node<'a>, code: &[u8], ancestors: Ancestors<'a, '_>) -> bool { + crate::roles::javascript::func_opener::is_callable(node, code, ancestors) } fn is_closure<'a>(node: &Node<'a>, ancestors: Ancestors<'a, '_>) -> bool { diff --git a/big-code-analysis-ast/src/checker/js_doc_binding.rs b/big-code-analysis-ast/src/checker/js_doc_binding.rs index da1a9d735..8ff94981f 100644 --- a/big-code-analysis-ast/src/checker/js_doc_binding.rs +++ b/big-code-analysis-ast/src/checker/js_doc_binding.rs @@ -20,7 +20,7 @@ macro_rules! impl_js_family_doc_binding { skips: |node, _| node.kind_id() == $lang::Decorator, forward: |comment, code, ancestors| { $crate::lang_helpers::doc_comment::outside_function_bodies::( - comment, ancestors, + comment, code, ancestors, ) && !$standalone($crate::lang_helpers::doc_comment::node_bytes(comment, code)) }, ..$crate::lang_helpers::DocBinding::new($crate::lang_helpers::KeptDocs::Leading { @@ -40,10 +40,13 @@ macro_rules! impl_js_family_doc_binding { // ends it without starting it. fn holds_doc_comment_in_body<'a>( ancestor: &Node<'a>, + code: &[u8], ancestors: Ancestors<'a, '_>, below: &Node<'a>, ) -> bool { - if !Self::is_func(ancestor, ancestors) && !Self::is_closure(ancestor, ancestors) { + if !Self::is_func_with_code(ancestor, code, ancestors) + && !Self::is_closure(ancestor, ancestors) + { return false; } // role-bypass: allow(FuncOpener, Closure) — where a comment diff --git a/big-code-analysis-ast/src/checker/kotlin.rs b/big-code-analysis-ast/src/checker/kotlin.rs index a9b82ca70..60553cd3c 100644 --- a/big-code-analysis-ast/src/checker/kotlin.rs +++ b/big-code-analysis-ast/src/checker/kotlin.rs @@ -65,10 +65,11 @@ impl Checker for KotlinCode { // body, decided by its kind so that a lambda holding thousands of // statements is not rescanned for every comment in it (#1597). // Accessors and `init` blocks open function spaces without being - // `is_func` (#1184), and Dokka reads a KDoc in them no more than one + // callables (#1184), and Dokka reads a KDoc in them no more than one // in a method. fn holds_doc_comment_in_body<'a>( ancestor: &Node<'a>, + code: &[u8], ancestors: Ancestors<'a, '_>, below: &Node<'a>, ) -> bool { @@ -78,7 +79,7 @@ impl Checker for KotlinCode { if ancestor.kind_id() == Kotlin::LambdaLiteral { return true; } - (Self::is_func(ancestor, ancestors) + (Self::is_func_with_code(ancestor, code, ancestors) || Self::is_closure(ancestor, ancestors) || doc_body_residual_kind!(kotlin, ancestor, ancestors)) && matches!(below.kind_id().into(), Kotlin::FunctionBody | Kotlin::Block) @@ -99,8 +100,8 @@ impl Checker for KotlinCode { crate::roles::kotlin::opens_space(node, code, ancestors) != SpaceKind::Unknown } - fn is_func<'a>(node: &Node<'a>, ancestors: Ancestors<'a, '_>) -> bool { - crate::roles::kotlin::func_opener::is_callable(node, &[], ancestors) + fn is_func_with_code<'a>(node: &Node<'a>, code: &[u8], ancestors: Ancestors<'a, '_>) -> bool { + crate::roles::kotlin::func_opener::is_callable(node, code, ancestors) } fn is_closure<'a>(node: &Node<'a>, ancestors: Ancestors<'a, '_>) -> bool { diff --git a/big-code-analysis-ast/src/checker/lua.rs b/big-code-analysis-ast/src/checker/lua.rs index a01841da2..ae6bea955 100644 --- a/big-code-analysis-ast/src/checker/lua.rs +++ b/big-code-analysis-ast/src/checker/lua.rs @@ -161,8 +161,8 @@ impl Checker for LuaCode { crate::roles::lua::opens_space(node, code, ancestors) != SpaceKind::Unknown } - fn is_func<'a>(node: &Node<'a>, ancestors: Ancestors<'a, '_>) -> bool { - crate::roles::lua::func_opener::is_callable(node, &[], ancestors) + fn is_func_with_code<'a>(node: &Node<'a>, code: &[u8], ancestors: Ancestors<'a, '_>) -> bool { + crate::roles::lua::func_opener::is_callable(node, code, ancestors) } fn is_closure<'a>(node: &Node<'a>, ancestors: Ancestors<'a, '_>) -> bool { diff --git a/big-code-analysis-ast/src/checker/mozcpp.rs b/big-code-analysis-ast/src/checker/mozcpp.rs index d4c2c9f3b..308cac81b 100644 --- a/big-code-analysis-ast/src/checker/mozcpp.rs +++ b/big-code-analysis-ast/src/checker/mozcpp.rs @@ -34,8 +34,8 @@ impl Checker for MozcppCode { crate::roles::mozcpp::opens_space(node, code, ancestors) != SpaceKind::Unknown } - fn is_func<'a>(node: &Node<'a>, ancestors: Ancestors<'a, '_>) -> bool { - crate::roles::mozcpp::func_opener::is_callable(node, &[], ancestors) + fn is_func_with_code<'a>(node: &Node<'a>, code: &[u8], ancestors: Ancestors<'a, '_>) -> bool { + crate::roles::mozcpp::func_opener::is_callable(node, code, ancestors) } fn is_closure<'a>(node: &Node<'a>, ancestors: Ancestors<'a, '_>) -> bool { diff --git a/big-code-analysis-ast/src/checker/mozjs.rs b/big-code-analysis-ast/src/checker/mozjs.rs index a7adcd15e..6c2246672 100644 --- a/big-code-analysis-ast/src/checker/mozjs.rs +++ b/big-code-analysis-ast/src/checker/mozjs.rs @@ -45,8 +45,8 @@ impl Checker for MozjsCode { crate::roles::mozjs::opens_space(node, code, ancestors) != SpaceKind::Unknown } - fn is_func<'a>(node: &Node<'a>, ancestors: Ancestors<'a, '_>) -> bool { - crate::roles::mozjs::func_opener::is_callable(node, &[], ancestors) + fn is_func_with_code<'a>(node: &Node<'a>, code: &[u8], ancestors: Ancestors<'a, '_>) -> bool { + crate::roles::mozjs::func_opener::is_callable(node, code, ancestors) } fn is_closure<'a>(node: &Node<'a>, ancestors: Ancestors<'a, '_>) -> bool { diff --git a/big-code-analysis-ast/src/checker/objc.rs b/big-code-analysis-ast/src/checker/objc.rs index a384ef0af..ad45a82f1 100644 --- a/big-code-analysis-ast/src/checker/objc.rs +++ b/big-code-analysis-ast/src/checker/objc.rs @@ -42,8 +42,8 @@ impl Checker for ObjcCode { // A `method_definition` is the `@implementation`-side method with a // body; the `@interface`-side `method_declaration` has no body and // is therefore not a function. - fn is_func<'a>(node: &Node<'a>, ancestors: Ancestors<'a, '_>) -> bool { - crate::roles::objc::func_opener::is_callable(node, &[], ancestors) + fn is_func_with_code<'a>(node: &Node<'a>, code: &[u8], ancestors: Ancestors<'a, '_>) -> bool { + crate::roles::objc::func_opener::is_callable(node, code, ancestors) } // A plain C function written inside `@implementation` / `@interface` @@ -69,7 +69,7 @@ impl Checker for ObjcCode { // `true` at file scope is deliberate and inert: `wmc::Stats::merge` // credits a `Function` child only to a `Class` or `Interface` // parent. Both aliases ride together per the #285 contract this file - // follows in `is_func` / `is_func_space`. + // follows in the callable and space tests. fn is_non_member_function<'a>( node: &Node<'a>, _code: &[u8], diff --git a/big-code-analysis-ast/src/checker/perl.rs b/big-code-analysis-ast/src/checker/perl.rs index aacc3b9a4..24502236f 100644 --- a/big-code-analysis-ast/src/checker/perl.rs +++ b/big-code-analysis-ast/src/checker/perl.rs @@ -24,8 +24,8 @@ impl Checker for PerlCode { crate::roles::perl::opens_space(node, code, ancestors) != SpaceKind::Unknown } - fn is_func<'a>(node: &Node<'a>, ancestors: Ancestors<'a, '_>) -> bool { - crate::roles::perl::func_opener::is_callable(node, &[], ancestors) + fn is_func_with_code<'a>(node: &Node<'a>, code: &[u8], ancestors: Ancestors<'a, '_>) -> bool { + crate::roles::perl::func_opener::is_callable(node, code, ancestors) } fn is_closure<'a>(node: &Node<'a>, ancestors: Ancestors<'a, '_>) -> bool { diff --git a/big-code-analysis-ast/src/checker/php.rs b/big-code-analysis-ast/src/checker/php.rs index 2d009fec9..39a0f20b3 100644 --- a/big-code-analysis-ast/src/checker/php.rs +++ b/big-code-analysis-ast/src/checker/php.rs @@ -125,6 +125,7 @@ impl Checker for PhpCode { // comment in the signature (#1612). fn holds_doc_comment_in_body<'a>( ancestor: &Node<'a>, + _code: &[u8], _ancestors: Ancestors<'a, '_>, below: &Node<'a>, ) -> bool { @@ -156,8 +157,8 @@ impl Checker for PhpCode { crate::roles::php::opens_space(node, code, ancestors) != SpaceKind::Unknown } - fn is_func<'a>(node: &Node<'a>, ancestors: Ancestors<'a, '_>) -> bool { - crate::roles::php::func_opener::is_callable(node, &[], ancestors) + fn is_func_with_code<'a>(node: &Node<'a>, code: &[u8], ancestors: Ancestors<'a, '_>) -> bool { + crate::roles::php::func_opener::is_callable(node, code, ancestors) } fn is_closure<'a>(node: &Node<'a>, ancestors: Ancestors<'a, '_>) -> bool { diff --git a/big-code-analysis-ast/src/checker/preproc.rs b/big-code-analysis-ast/src/checker/preproc.rs index 5ab180eab..b1db44904 100644 --- a/big-code-analysis-ast/src/checker/preproc.rs +++ b/big-code-analysis-ast/src/checker/preproc.rs @@ -7,5 +7,19 @@ impl Checker for PreprocCode { // The one `Comment` row of `roles/preproc.rs`; no `DocComment` row (#1699). impl_comment_from_rows!(preproc); + // The `FuncOpener` and `Container` rows of `roles/preproc.rs` are + // absent: the pass opens no space and names no function. + fn is_func_space_with_code<'a>( + node: &Node<'a>, + code: &[u8], + ancestors: Ancestors<'a, '_>, + ) -> bool { + crate::roles::preproc::opens_space(node, code, ancestors) != SpaceKind::Unknown + } + + fn is_func_with_code<'a>(node: &Node<'a>, code: &[u8], ancestors: Ancestors<'a, '_>) -> bool { + crate::roles::preproc::func_opener::is_callable(node, code, ancestors) + } + impl_row_predicates!(preproc, string_lit, is_string, is_string_with_code); } diff --git a/big-code-analysis-ast/src/checker/python.rs b/big-code-analysis-ast/src/checker/python.rs index b857c4a3e..246ec622a 100644 --- a/big-code-analysis-ast/src/checker/python.rs +++ b/big-code-analysis-ast/src/checker/python.rs @@ -35,8 +35,8 @@ impl Checker for PythonCode { crate::roles::python::opens_space(node, code, ancestors) != SpaceKind::Unknown } - fn is_func<'a>(node: &Node<'a>, ancestors: Ancestors<'a, '_>) -> bool { - crate::roles::python::func_opener::is_callable(node, &[], ancestors) + fn is_func_with_code<'a>(node: &Node<'a>, code: &[u8], ancestors: Ancestors<'a, '_>) -> bool { + crate::roles::python::func_opener::is_callable(node, code, ancestors) } // The `Closure` row lists `Lambda` (196, the concrete production diff --git a/big-code-analysis-ast/src/checker/ruby.rs b/big-code-analysis-ast/src/checker/ruby.rs index 4ffc5bc67..0d83e4027 100644 --- a/big-code-analysis-ast/src/checker/ruby.rs +++ b/big-code-analysis-ast/src/checker/ruby.rs @@ -133,8 +133,8 @@ impl Checker for RubyCode { crate::roles::ruby::opens_space(node, code, ancestors) != SpaceKind::Unknown } - fn is_func<'a>(node: &Node<'a>, ancestors: Ancestors<'a, '_>) -> bool { - crate::roles::ruby::func_opener::is_callable(node, &[], ancestors) + fn is_func_with_code<'a>(node: &Node<'a>, code: &[u8], ancestors: Ancestors<'a, '_>) -> bool { + crate::roles::ruby::func_opener::is_callable(node, code, ancestors) } // Ruby is the one non-JS grammar whose closure test is not diff --git a/big-code-analysis-ast/src/checker/rust.rs b/big-code-analysis-ast/src/checker/rust.rs index da403a51f..26cf739c6 100644 --- a/big-code-analysis-ast/src/checker/rust.rs +++ b/big-code-analysis-ast/src/checker/rust.rs @@ -121,8 +121,8 @@ impl Checker for RustCode { crate::roles::rust::opens_space(node, code, ancestors) != SpaceKind::Unknown } - fn is_func<'a>(node: &Node<'a>, ancestors: Ancestors<'a, '_>) -> bool { - crate::roles::rust::func_opener::is_callable(node, &[], ancestors) + fn is_func_with_code<'a>(node: &Node<'a>, code: &[u8], ancestors: Ancestors<'a, '_>) -> bool { + crate::roles::rust::func_opener::is_callable(node, code, ancestors) } fn is_closure<'a>(node: &Node<'a>, ancestors: Ancestors<'a, '_>) -> bool { diff --git a/big-code-analysis-ast/src/checker/tcl.rs b/big-code-analysis-ast/src/checker/tcl.rs index e6841246b..942bd9580 100644 --- a/big-code-analysis-ast/src/checker/tcl.rs +++ b/big-code-analysis-ast/src/checker/tcl.rs @@ -21,8 +21,8 @@ impl Checker for TclCode { crate::roles::tcl::opens_space(node, code, ancestors) != SpaceKind::Unknown } - fn is_func<'a>(node: &Node<'a>, ancestors: Ancestors<'a, '_>) -> bool { - crate::roles::tcl::func_opener::is_callable(node, &[], ancestors) + fn is_func_with_code<'a>(node: &Node<'a>, code: &[u8], ancestors: Ancestors<'a, '_>) -> bool { + crate::roles::tcl::func_opener::is_callable(node, code, ancestors) } // Tcl closures (`apply`) are ordinary commands; the grammar has no distinct closure node. diff --git a/big-code-analysis-ast/src/checker/tsx.rs b/big-code-analysis-ast/src/checker/tsx.rs index 452de450d..3a36d4bb1 100644 --- a/big-code-analysis-ast/src/checker/tsx.rs +++ b/big-code-analysis-ast/src/checker/tsx.rs @@ -57,8 +57,8 @@ impl Checker for TsxCode { crate::roles::tsx::opens_space(node, code, ancestors) != SpaceKind::Unknown } - fn is_func<'a>(node: &Node<'a>, ancestors: Ancestors<'a, '_>) -> bool { - crate::roles::tsx::func_opener::is_callable(node, &[], ancestors) + fn is_func_with_code<'a>(node: &Node<'a>, code: &[u8], ancestors: Ancestors<'a, '_>) -> bool { + crate::roles::tsx::func_opener::is_callable(node, code, ancestors) } fn is_closure<'a>(node: &Node<'a>, ancestors: Ancestors<'a, '_>) -> bool { diff --git a/big-code-analysis-ast/src/checker/typescript.rs b/big-code-analysis-ast/src/checker/typescript.rs index 0958bd7d3..b91cb26d6 100644 --- a/big-code-analysis-ast/src/checker/typescript.rs +++ b/big-code-analysis-ast/src/checker/typescript.rs @@ -57,8 +57,8 @@ impl Checker for TypescriptCode { crate::roles::typescript::opens_space(node, code, ancestors) != SpaceKind::Unknown } - fn is_func<'a>(node: &Node<'a>, ancestors: Ancestors<'a, '_>) -> bool { - crate::roles::typescript::func_opener::is_callable(node, &[], ancestors) + fn is_func_with_code<'a>(node: &Node<'a>, code: &[u8], ancestors: Ancestors<'a, '_>) -> bool { + crate::roles::typescript::func_opener::is_callable(node, code, ancestors) } fn is_closure<'a>(node: &Node<'a>, ancestors: Ancestors<'a, '_>) -> bool { diff --git a/big-code-analysis-ast/src/getter.rs b/big-code-analysis-ast/src/getter.rs index a12b03441..df745b3a3 100644 --- a/big-code-analysis-ast/src/getter.rs +++ b/big-code-analysis-ast/src/getter.rs @@ -387,32 +387,32 @@ pub trait Getter { default_func_space_name(node, code, ancestors) } - /// The kind of space `node` opens, or [`SpaceKind::Unknown`] when it - /// opens none. + /// The kind of space `node` opens by its kind alone, or + /// [`SpaceKind::Unknown`] when it opens none: the byte-less spelling + /// of [`get_space_kind_with_code`](Self::get_space_kind_with_code), + /// and by default that classifier asked with no bytes and a + /// known-empty chain, as `Checker::is_func_space` is of its own + /// (#1863). The walk calls the `_with_code` one. #[must_use] - fn get_space_kind(_node: &Node) -> SpaceKind { - SpaceKind::Unknown + fn get_space_kind(node: &Node) -> SpaceKind { + Self::get_space_kind_with_code(node, &[], Ancestors::known(&[])) } - /// Source-aware variant of [`get_space_kind`](Self::get_space_kind). The default - /// forwards to the byte-less classifier; languages whose space - /// kinds are encoded in macro identifier text (Elixir's - /// `defmodule` / `def` / `defp` / `defmacro` / `defmacrop` Calls) - /// override this so the walker can attribute the correct - /// `SpaceKind` to each promoted func space (#275). + /// The kind of space `node` opens, as the walk asks it: with the + /// source bytes and the chain it descended through. Required: every + /// language answers from its role table's `opens_space` fold, and + /// the byte-less [`get_space_kind`](Self::get_space_kind) derives + /// from this, never the reverse (#1863). /// - /// `ancestors` is the chain the caller descended through; Elixir - /// needs it to see whether the `Call` sits inside a `quote` - /// template without paying `Node::parent`'s `O(depth)` (#1084). - #[inline] + /// Elixir's `defmodule` / `def` are `Call`s told apart by their + /// target text (#275), and a `def` inside a `quote` template by the + /// chain rather than `Node::parent`'s `O(depth)` (#1084). #[must_use] fn get_space_kind_with_code<'a>( node: &Node<'a>, - _code: &[u8], - _ancestors: Ancestors<'a, '_>, - ) -> SpaceKind { - Self::get_space_kind(node) - } + code: &[u8], + ancestors: Ancestors<'a, '_>, + ) -> SpaceKind; /// Classifies `node` as a Halstead operator, operand, or neither. /// @@ -2058,6 +2058,14 @@ mod keyword_role_tests { macro_rules! conflicting_getter { ($name:ident, $row:ident, $arm:ident) => { impl Getter for $name { + fn get_space_kind_with_code<'a>( + _node: &Node<'a>, + _code: &[u8], + _ancestors: Ancestors<'a, '_>, + ) -> crate::SpaceKind { + crate::SpaceKind::Unknown + } + fn get_keyword_role<'a>( _node: &Node<'a>, _code: &[u8], diff --git a/big-code-analysis-ast/src/getter/ccomment.rs b/big-code-analysis-ast/src/getter/ccomment.rs index baf18edd4..43f0d924f 100644 --- a/big-code-analysis-ast/src/getter/ccomment.rs +++ b/big-code-analysis-ast/src/getter/ccomment.rs @@ -8,4 +8,13 @@ impl Getter for CcommentCode { // reading the rows rather than inheriting a default is what lets // the trait require the method of every language (#1693). keyword_roles!(ccomment); + + // No row of `roles/ccomment.rs` opens a space. + fn get_space_kind_with_code<'a>( + node: &Node<'a>, + code: &[u8], + ancestors: Ancestors<'a, '_>, + ) -> SpaceKind { + crate::roles::ccomment::opens_space(node, code, ancestors) + } } diff --git a/big-code-analysis-ast/src/getter/preproc.rs b/big-code-analysis-ast/src/getter/preproc.rs index bb17471d2..80d40e61c 100644 --- a/big-code-analysis-ast/src/getter/preproc.rs +++ b/big-code-analysis-ast/src/getter/preproc.rs @@ -8,4 +8,13 @@ impl Getter for PreprocCode { // reading the rows rather than inheriting a default is what lets // the trait require the method of every language (#1693). keyword_roles!(preproc); + + // No row of `roles/preproc.rs` opens a space. + fn get_space_kind_with_code<'a>( + node: &Node<'a>, + code: &[u8], + ancestors: Ancestors<'a, '_>, + ) -> SpaceKind { + crate::roles::preproc::opens_space(node, code, ancestors) + } } diff --git a/big-code-analysis-ast/src/lang_helpers/doc_comment.rs b/big-code-analysis-ast/src/lang_helpers/doc_comment.rs index bd5c92cf8..8225e9782 100644 --- a/big-code-analysis-ast/src/lang_helpers/doc_comment.rs +++ b/big-code-analysis-ast/src/lang_helpers/doc_comment.rs @@ -174,9 +174,10 @@ pub(crate) fn token_spelling(node: &Node, code: &[u8]) -> Vec { #[must_use] pub(crate) fn outside_function_bodies<'a, T: Checker>( comment: &Node<'a>, + code: &[u8], ancestors: Ancestors<'a, '_>, ) -> bool { - !held_in_body::(comment, 0, ancestors) + !held_in_body::(comment, code, 0, ancestors) } /// Whether an ancestor of `node`, past the `skip` nearest ones, holds it @@ -186,6 +187,7 @@ pub(crate) fn outside_function_bodies<'a, T: Checker>( /// everywhere. fn held_in_body<'a, T: Checker>( node: &Node<'a>, + code: &[u8], skip: usize, ancestors: Ancestors<'a, '_>, ) -> bool { @@ -195,7 +197,7 @@ fn held_in_body<'a, T: Checker>( FoldLane::DocInBody, 0, |held, ancestor, outer, below| { - u8::from(held != 0 || T::holds_doc_comment_in_body(ancestor, outer, below)) + u8::from(held != 0 || T::holds_doc_comment_in_body(ancestor, code, outer, below)) }, ) != 0 } @@ -236,14 +238,14 @@ pub fn documents_where_it_sits<'a, T: Checker>( // once per walk rather than climbed once per comment. let mut below = *node; for (ancestor, outer) in ancestors.iter(node).take(2) { - if T::holds_doc_comment_in_body(&ancestor, outer, &below) + if T::holds_doc_comment_in_body(&ancestor, code, outer, &below) && !T::doc_comment_opens_body(node, &ancestor, &below, code) { return false; } below = ancestor; } - !held_in_body::(node, 2, ancestors) + !held_in_body::(node, code, 2, ancestors) } /// Whether a doc comment documents without a following declaration, diff --git a/big-code-analysis-ast/src/lang_helpers/doxygen.rs b/big-code-analysis-ast/src/lang_helpers/doxygen.rs index bd7d6d226..1fdf332de 100644 --- a/big-code-analysis-ast/src/lang_helpers/doxygen.rs +++ b/big-code-analysis-ast/src/lang_helpers/doxygen.rs @@ -611,7 +611,7 @@ pub(crate) fn doxygen_binds_forward<'a, T: Checker + DoxygenRow>( && ancestors .parent(comment) .is_some_and(|parent| doxygen_container::(&parent)) - && outside_function_bodies::(comment, ancestors) + && outside_function_bodies::(comment, code, ancestors) } #[cfg(test)] diff --git a/big-code-analysis-ast/src/lib.rs b/big-code-analysis-ast/src/lib.rs index 82ab70e2f..986b65279 100644 --- a/big-code-analysis-ast/src/lib.rs +++ b/big-code-analysis-ast/src/lib.rs @@ -21,7 +21,7 @@ //! //! This crate turns source bytes into a [`tree_sitter`] tree and //! answers structural questions about it: which [`LANG`] a file is in, -//! what a [`Node`] is (`is_func`, `is_call`, `is_string`, … through +//! what a [`Node`] is (`is_func_with_code`, `is_call`, `is_string`, … through //! [`Checker`]), what it is called and which Halstead class or //! [`SpaceKind`] it opens ([`Getter`]), and how it should be rendered //! as an [`AstNode`] ([`Alterator`]). It also owns the C-family diff --git a/big-code-analysis-ast/src/node.rs b/big-code-analysis-ast/src/node.rs index 833d17e17..7aab75195 100644 --- a/big-code-analysis-ast/src/node.rs +++ b/big-code-analysis-ast/src/node.rs @@ -1570,7 +1570,7 @@ mod tests { ); // The shape #1088 added as a consumer: the JS-family - // `Checker::is_func` / `is_closure` walk upward from an + // callable and closure tests walk upward from an // `arrow_function` / `function_expression` looking for the // binding that names it, and end on `Ancestors::previous_sibling` // through `has_sibling`. None of the fixtures above contains diff --git a/big-code-analysis-ast/src/parser.rs b/big-code-analysis-ast/src/parser.rs index 7a936653b..c0cf5ace3 100644 --- a/big-code-analysis-ast/src/parser.rs +++ b/big-code-analysis-ast/src/parser.rs @@ -173,7 +173,7 @@ impl ParserTrait for P "string" => res.push(Box::new(move |node: &Node, ancestors| { T::is_string_with_code(node, code, ancestors) })), - // The JS-family `is_func` and Elixir's `is_func_with_code` + // The JS family's and Elixir's `is_func_with_code` // consult the chain to tell a named function from a // closure and a `def` `Call` from any other (#1088, // #1162). Both answer the same off an unknown chain — diff --git a/big-code-analysis-ast/src/roles/derived_parity_tests.rs b/big-code-analysis-ast/src/roles/derived_parity_tests.rs index 1c9c3c778..b43f418b3 100644 --- a/big-code-analysis-ast/src/roles/derived_parity_tests.rs +++ b/big-code-analysis-ast/src/roles/derived_parity_tests.rs @@ -943,20 +943,20 @@ fn forwards_on<'a, C: Checker + crate::Getter>( owns(&rows.closure), ); // The body-holding residual: every hand-written adapter composes - // `is_func ∨ is_closure ∨ doc_body_residual::owns` with a body-child - // test on `below` that no row spells, so the forward is compared + // `is_func_with_code ∨ is_closure ∨ doc_body_residual::owns` with a + // body-child test on `below` that no row spells, so the forward is compared // against the composition *without* the child test on the one // side it can be — a node the forward admits for some child is one // the composition admits. The row half is what the `&[]` forward // in `doc_body_residual_kind!` drops; the chain is the real one. let holds_for_any_child = node .children() - .any(|below| C::holds_doc_comment_in_body(node, ancestors, &below)); - let composition = C::is_func(node, ancestors) + .any(|below| C::holds_doc_comment_in_body(node, code, ancestors, &below)); + let composition = C::is_func_with_code(node, code, ancestors) || C::is_closure(node, ancestors) || owns(&rows.doc_body_residual); push( - "holds_doc_comment_in_body ⇒ is_func ∨ is_closure ∨ row", + "holds_doc_comment_in_body ⇒ is_func_with_code ∨ is_closure ∨ row", holds_for_any_child, holds_for_any_child && composition, ); diff --git a/big-code-analysis-ast/src/roles/doc_tests/mod.rs b/big-code-analysis-ast/src/roles/doc_tests/mod.rs index 1b876aa74..e6715b90c 100644 --- a/big-code-analysis-ast/src/roles/doc_tests/mod.rs +++ b/big-code-analysis-ast/src/roles/doc_tests/mod.rs @@ -705,7 +705,7 @@ mod java { for_each_node_with_chain::(source, |node, chain| { let ancestors = Ancestors::known(chain); let target = JavaCode::is_doc_target(node, source, ancestors); - let holds = JavaCode::holds_doc_comment_in_body(node, ancestors, node); + let holds = JavaCode::holds_doc_comment_in_body(node, source, ancestors, node); if target || holds { seen.push((node.kind(), target, holds)); } @@ -750,7 +750,7 @@ mod java { if node.kind() == "formal_parameters" { headers.push(( JavaCode::is_func_with_code(node, source, ancestors), - JavaCode::holds_doc_comment_in_body(node, ancestors, node), + JavaCode::holds_doc_comment_in_body(node, source, ancestors, node), )); } else if JavaCode::is_doc_comment(node, source) { comments.push(( @@ -876,7 +876,7 @@ mod groovy { if node.kind() == "record_components" { headers.push(( GroovyCode::is_func_with_code(node, source, ancestors), - GroovyCode::holds_doc_comment_in_body(node, ancestors, node), + GroovyCode::holds_doc_comment_in_body(node, source, ancestors, node), )); } else if GroovyCode::is_doc_comment(node, source) { comments.push(( @@ -991,8 +991,10 @@ mod kotlin { let not_body = node.child(0).expect("every listed node has a child"); seen.push(( node.kind(), - body.is_some_and(|b| KotlinCode::holds_doc_comment_in_body(node, ancestors, &b)), - KotlinCode::holds_doc_comment_in_body(node, ancestors, ¬_body), + body.is_some_and(|b| { + KotlinCode::holds_doc_comment_in_body(node, source, ancestors, &b) + }), + KotlinCode::holds_doc_comment_in_body(node, source, ancestors, ¬_body), )); }); assert_eq!( @@ -1122,9 +1124,10 @@ mod csharp { let first = node.child(0).expect("a member has children"); seen.push(( node.kind(), - accessors - .is_some_and(|a| CsharpCode::holds_doc_comment_in_body(node, ancestors, &a)), - CsharpCode::holds_doc_comment_in_body(node, ancestors, &first), + accessors.is_some_and(|a| { + CsharpCode::holds_doc_comment_in_body(node, source, ancestors, &a) + }), + CsharpCode::holds_doc_comment_in_body(node, source, ancestors, &first), )); }); assert_eq!( @@ -1140,7 +1143,7 @@ mod csharp { /// The cost pin for the order above: asking the body test of a /// property or indexer runs **no** accessor search, because the row - /// answers before `is_func` (whose `has_no_accessors` gate would + /// answers before the callable test (whose `has_no_accessors` gate would /// scan the accessor list) is reached. Swapping the branches makes /// the count one per member — a cost no verdict and no scaling probe /// reaches, which is why it is counted here. @@ -1159,6 +1162,7 @@ mod csharp { let first = node.child(0).expect("a member has children"); assert!(CsharpCode::holds_doc_comment_in_body( node, + source, Ancestors::known(chain), &first )); @@ -1283,8 +1287,8 @@ mod php { let last = node.children().last().expect("a body"); seen.push(( node.kind(), - PhpCode::holds_doc_comment_in_body(node, ancestors, ¶ms), - PhpCode::holds_doc_comment_in_body(node, ancestors, &last), + PhpCode::holds_doc_comment_in_body(node, source, ancestors, ¶ms), + PhpCode::holds_doc_comment_in_body(node, source, ancestors, &last), )); }); assert_eq!( diff --git a/big-code-analysis-ast/src/roles/elixir.rs b/big-code-analysis-ast/src/roles/elixir.rs index e3758316f..2063a9258 100644 --- a/big-code-analysis-ast/src/roles/elixir.rs +++ b/big-code-analysis-ast/src/roles/elixir.rs @@ -287,8 +287,9 @@ mod tests { // Until #1696 the rows restated `checker/elixir.rs` and // `getter/elixir.rs` and this compared the two; now the classifiers // read the rows, so the expected answer per node is pinned - // independently here — `(is_func, is_closure, promoted, SpaceKind, - // is_member)`, by the call's target text where the kind is `call`. + // independently here — `(is_func_with_code, is_closure, promoted, + // SpaceKind, is_member)`, by the call's target text where the kind + // is `call`. // The per-shape tests below do not cover membership: emptying // `Call` or dropping `Sigil` from `StringLit` failed none of them. #[cfg(feature = "elixir")] diff --git a/big-code-analysis-ast/src/roles/java.rs b/big-code-analysis-ast/src/roles/java.rs index f17b31f81..4f9277e00 100644 --- a/big-code-analysis-ast/src/roles/java.rs +++ b/big-code-analysis-ast/src/roles/java.rs @@ -260,7 +260,7 @@ role_table! { } // Mapping. Every function opener is a `Function` space. The four - // `callable` owners are what `is_func` answers — a method, a + // `callable` owners are what `is_func_with_code` answers — a method, a // constructor, a record's compact constructor (#1160) and a // record's header where it stands for the implicit canonical // constructor (#1842) — each a function someone names at a call @@ -268,8 +268,8 @@ role_table! { // it opens a space (#1184) and is nobody's callee, so it carries no // `callable` and `nom` / `nargs` / `npm` never see it as a method. // The lambda is *not* here: the walk promotes on - // `promotes_to_func_space_with_code`, and Java's `is_func` and - // `is_func_space` both leave `lambda_expression` out, so no lambda + // `promotes_to_func_space_with_code`, and Java's callable and + // space tests both leave `lambda_expression` out, so no lambda // opens a space today — even though the byte-less `get_space_kind` // labelled one `Function` before #1696. The row records the walk's // answer, and the parity test below pins it against the walk's @@ -660,11 +660,10 @@ mod tests { if kind != "formal_parameters" { assert_eq!( ( - JavaCode::is_func(node, ancestors), JavaCode::is_func_space(node), JavaCode::get_space_kind(node) ), - (got.0, promoted, got.3), + (promoted, got.3), "{kind}: the byte-less spellings are the kind table" ); } diff --git a/big-code-analysis-ast/src/roles/js_family.rs b/big-code-analysis-ast/src/roles/js_family.rs index 692fcf3bb..9c70addca 100644 --- a/big-code-analysis-ast/src/roles/js_family.rs +++ b/big-code-analysis-ast/src/roles/js_family.rs @@ -164,8 +164,8 @@ macro_rules! js_family_binding_gates { // `property_identifier` child at all, an `O(width)` scan. Asked // through the walk's memo it runs once per parent, so a wide // argument list or array literal of positional arrows is linear; - // `nom` and `nargs` each ask twice per arrow (`is_func` then - // `is_closure`), and off the walk it is computed each time. + // `nom` and `nargs` each ask twice per arrow (`is_func_with_code` + // then `is_closure`), and off the walk it is computed each time. // // At the pinned grammars no parent reaches this clause with a // `property_identifier` child: `node-types.json` places one only @@ -637,7 +637,7 @@ run(function* () {});\n"; let ancestors = Ancestors::known(chain); let kind = node.kind(); let got = ( - L::is_func(node, ancestors), + L::is_func_with_code(node, source, ancestors), L::is_closure(node, ancestors), L::promotes_to_func_space_with_code(node, source, ancestors), L::get_space_kind_with_code(node, source, ancestors), diff --git a/big-code-analysis-ast/src/roles/mod.rs b/big-code-analysis-ast/src/roles/mod.rs index 522eb3c78..c561ac9d9 100644 --- a/big-code-analysis-ast/src/roles/mod.rs +++ b/big-code-analysis-ast/src/roles/mod.rs @@ -116,8 +116,9 @@ //! kind that moves between `FuncOpener` or `Closure` and this row //! changes nothing the Checker answers; only a kind on none of the //! three does (#1797 named the residual; `holds_doc_comment_in_body -//! ⇒ is_func ∨ is_closure ∨ row` in `derived_parity_tests.rs` pins the -//! composition). A class body is never one. +//! ⇒ is_func_with_code ∨ is_closure ∨ row` in +//! `derived_parity_tests.rs` pins the composition). A class body is +//! never one. //! //! The seven documentation roles are what a language's doc-comment //! adapter (`checker/.rs`, the per-language half of the @@ -233,7 +234,8 @@ //! flags, so an opener on a third role would bypass them — the macro //! rejects it (#1793). //! - `callable` marks a `FuncOpener` owner that is a *named function* — -//! what `Checker::is_func` answers — beside openers that are not +//! what `Checker::is_func_with_code` answers — beside openers that are +//! not //! (Java's `static { … }` opens a `Function` space and is nobody's //! callee; Elixir's `fn … end` opens one and is a `Closure`), and //! `callable_when f` one that is a named function only where `f` says @@ -400,30 +402,38 @@ //! //! - **Reach for the `_with_code` spelling** — that is what the walk //! calls (`promotes_to_func_space_with_code`, -//! `get_space_kind_with_code`). The legacy `Checker` spellings come -//! in three shapes, and only one of them is the ungated kind set. -//! `is_call`, `is_string` and `is_comment` take neither bytes nor a -//! chain and read `lists_kind`. `is_func_space` and `get_space_kind` -//! take neither either, and forward to the `_with_code` form with -//! `&[]` and a *known-empty* chain, `Ancestors::known(&[])` — never -//! `Ancestors::unknown()`, which climbs through `Node::parent` and -//! answers the gated result, so the spelling would silently stop -//! being the kind set (lesson 114); a gate that reads only the node's -//! own children (Java's anonymous-class body) still applies there. -//! `is_func`, `is_closure` and `is_else_if` take the caller's chain -//! and hand it through with `&[]` bytes, so a chain gate (Ruby's -//! `block` under a stabby lambda) answers exactly and only a byte -//! gate is dropped — unless one gate reads both, as a Java or Groovy -//! record header's does (#1842): there `is_func` forwards the -//! known-empty chain too, so the header answers `false` as -//! `is_func_space` does, not the degenerate no-bytes comparison. The -//! chain-less pair disagrees with the walk wherever a gate reads -//! what it drops — Elixir's text-gated `call` openers, Ruby's -//! `block`, C#'s `parameter_list` under a type declaration (#1828), -//! the record header — and the derived parity suite pins each such -//! disagreement by name (`KNOWN_DISAGREEMENTS`). Every other -//! language's pair asserts `!TEXT_GATED && !CHAIN_GATED` on its -//! `FuncOpener` and `Container` rows at build time (#1793). +//! `get_space_kind_with_code`). The three the space tree is built +//! from — `Checker::is_func_with_code`, +//! `Checker::is_func_space_with_code` and +//! `Getter::get_space_kind_with_code` — are required of every +//! language, and a byte-less spelling derives from one, never the +//! reverse (#1863): a trait default forwarding with-code to byte-less +//! handed a text-gated row no bytes without a word. The callable test +//! has no byte-less spelling at all: a callable can be told by its +//! bytes, by its chain, or by one gate reading both (a Java or Groovy +//! record's header, #1842), so a byte-less `is_func` answered three +//! different questions across the languages. The legacy `Checker` +//! spellings that remain come in three shapes, and only one of them +//! is the ungated kind set. `is_call`, `is_string` and `is_comment` +//! take neither bytes nor a chain and read `lists_kind`. +//! `is_func_space` and `get_space_kind` take neither either, and +//! forward to the `_with_code` form with `&[]` and a *known-empty* +//! chain, `Ancestors::known(&[])` — never `Ancestors::unknown()`, +//! which climbs through `Node::parent` and answers the gated result, +//! so the spelling would silently stop being the kind set (lesson +//! 114); a gate that reads only the node's own children (Java's +//! anonymous-class body) still applies there. That forward is the +//! trait default, and a language's own spelling of it adds only the +//! build-time pin below. `is_closure` and `is_else_if` take the +//! caller's chain and hand it through with `&[]` bytes, so a chain +//! gate (Ruby's `block` under a stabby lambda) answers exactly and +//! only a byte gate is dropped. The chain-less pair disagrees with +//! the walk wherever a gate reads what it drops — Elixir's text-gated +//! `call` openers, Ruby's `block`, C#'s `parameter_list` under a type +//! declaration (#1828), the record header — and the derived parity +//! suite pins each such disagreement by name (`KNOWN_DISAGREEMENTS`). +//! Every other language's pair asserts `!TEXT_GATED && !CHAIN_GATED` +//! on its `FuncOpener` and `Container` rows at build time (#1793). //! - **Ask several rows of one node through the `_kind` projections**, //! reading `kind_id()` once. //! - **A consumer's policy over a row is the consumer's.** Which @@ -1689,7 +1699,8 @@ macro_rules! role_table { }; /// Whether `node` is a `callable` owner of the construct — a - /// named function, for `Checker::is_func` — under its gate. + /// named function, for `Checker::is_func_with_code` — under + /// its gate. #[inline] pub fn is_callable<'a>( node: &Node<'a>, diff --git a/big-code-analysis-ast/src/roles/python.rs b/big-code-analysis-ast/src/roles/python.rs index 094fe8515..699f3f56e 100644 --- a/big-code-analysis-ast/src/roles/python.rs +++ b/big-code-analysis-ast/src/roles/python.rs @@ -280,7 +280,7 @@ mod tests { // Until #1696 the space rows restated `checker/python.rs` and // `getter/python.rs` and this compared the two; now the classifiers - // read the rows, so the expected `(is_func, is_closure, promoted, + // read the rows, so the expected `(is_func_with_code, is_closure, promoted, // SpaceKind, is_member)` per node is pinned independently, as are // the `Call` and `StringLit` rows by kind string since R08 (#1698) // made the classifiers read those too. The per-shape tests below do @@ -297,7 +297,7 @@ mod tests { let kind = node.kind(); let promoted = PythonCode::promotes_to_func_space_with_code(node, source, ancestors); let got = ( - PythonCode::is_func(node, ancestors), + PythonCode::is_func_with_code(node, source, ancestors), PythonCode::is_closure(node, ancestors), promoted, PythonCode::get_space_kind_with_code(node, source, ancestors), diff --git a/big-code-analysis-ast/src/roles/space_tree_tests.rs b/big-code-analysis-ast/src/roles/space_tree_tests.rs index 798aae158..aede244d5 100644 --- a/big-code-analysis-ast/src/roles/space_tree_tests.rs +++ b/big-code-analysis-ast/src/roles/space_tree_tests.rs @@ -1,10 +1,10 @@ //! The space-tree rows of the kind-only languages, pinned independently //! (#1696): for each language, a fixture spelling every `FuncOpener`, //! `Closure`, `Container` and `Member` kind, and the expected -//! `(is_func, is_closure, promoted, SpaceKind, is_member)` per kind as -//! the classifiers answered before they read the rows. A kind absent -//! from a language's table answers all-false; every declared owner must -//! be met by the fixture. +//! `(is_func_with_code, is_closure, promoted, SpaceKind, is_member)` per +//! kind as the classifiers answered before they read the rows. A kind +//! absent from a language's table answers all-false; every declared +//! owner must be met by the fixture. use crate::test_support::{for_each_node_with_chain, owners_covered}; use crate::{Ancestors, Checker, Getter, LanguageInfo, Node, SpaceKind}; @@ -184,17 +184,13 @@ fn check_gated( rows.push((node.utf8_text(source).unwrap_or("?").to_owned(), got)); return; } - // The byte-less triple is the kind table, gates aside: on a row + // The byte-less pair is the kind table, gates aside: on a row // whose owners read no chain and no bytes it answers exactly - // what the `_with_code` triple answers (Ruby's chain-reading gate + // what the `_with_code` pair answers (Ruby's chain-reading gate // is pinned apart, in `ruby_byte_less_spellings_stay_the_kind_table`). assert_eq!( - ( - L::is_func(node, ancestors), - L::is_func_space(node), - L::get_space_kind(node) - ), - (got.0, promoted, got.3), + (L::is_func_space(node), L::get_space_kind(node)), + (promoted, got.3), "{kind}: the byte-less spellings are the kind table" ); let want = expected @@ -459,7 +455,7 @@ fn check_cpp( let kind = node.kind(); let promoted = L::promotes_to_func_space_with_code(node, source, ancestors); let got = ( - L::is_func(node, ancestors), + L::is_func_with_code(node, source, ancestors), L::is_closure(node, ancestors), promoted, L::get_space_kind_with_code(node, source, ancestors), @@ -629,7 +625,7 @@ fn csharp_space_tree_rows() { let kind = node.kind(); let promoted = CsharpCode::promotes_to_func_space_with_code(node, source, ancestors); let got = ( - CsharpCode::is_func(node, ancestors), + CsharpCode::is_func_with_code(node, source, ancestors), CsharpCode::is_closure(node, ancestors), promoted, CsharpCode::get_space_kind_with_code(node, source, ancestors), @@ -738,7 +734,7 @@ fn kotlin_space_tree_rows() { let kind = node.kind(); let promoted = KotlinCode::promotes_to_func_space_with_code(node, source, ancestors); let got = ( - KotlinCode::is_func(node, ancestors), + KotlinCode::is_func_with_code(node, source, ancestors), KotlinCode::is_closure(node, ancestors), promoted, KotlinCode::get_space_kind_with_code(node, source, ancestors), @@ -898,7 +894,7 @@ fn ruby_space_tree_rows() { let kind = node.kind(); let promoted = RubyCode::promotes_to_func_space_with_code(node, source, ancestors); let got = ( - RubyCode::is_func(node, ancestors), + RubyCode::is_func_with_code(node, source, ancestors), RubyCode::is_closure(node, ancestors), promoted, RubyCode::get_space_kind_with_code(node, source, ancestors), @@ -1246,13 +1242,13 @@ fn csharp_byte_less_spellings_omit_the_primary_constructor() { } /// One parameter list's answers for the two record-header tests below: -/// its text, the byte-less `(is_func, is_func_space, get_space_kind)` -/// and the with-code `(is_func_with_code, is_func_space_with_code, +/// its text, the byte-less `(is_func_space, get_space_kind)` and the +/// with-code `(is_func_with_code, is_func_space_with_code, /// get_space_kind_with_code, get_func_space_name)`. #[cfg(any(feature = "java", feature = "groovy"))] type ListAnswer = ( String, - (bool, bool, SpaceKind), + (bool, SpaceKind), (bool, bool, SpaceKind, Option<&'static str>), ); @@ -1271,11 +1267,7 @@ fn list_answers( let ancestors = Ancestors::known(chain); lists.push(( node.utf8_text(source).unwrap_or("?").to_owned(), - ( - L::is_func(node, ancestors), - L::is_func_space(node), - L::get_space_kind(node), - ), + (L::is_func_space(node), L::get_space_kind(node)), ( L::is_func_with_code(node, source, ancestors), L::is_func_space_with_code(node, source, ancestors), @@ -1293,7 +1285,7 @@ fn list_answers( fn header(text: &str, name: &'static str) -> ListAnswer { ( text.to_owned(), - (false, false, SpaceKind::Unknown), + (false, SpaceKind::Unknown), (true, true, SpaceKind::Function, Some(name)), ) } @@ -1303,7 +1295,7 @@ fn header(text: &str, name: &'static str) -> ListAnswer { fn plain(text: &str, name: &'static str) -> ListAnswer { ( text.to_owned(), - (false, false, SpaceKind::Unknown), + (false, SpaceKind::Unknown), (false, false, SpaceKind::Unknown, Some(name)), ) } @@ -1313,9 +1305,8 @@ fn plain(text: &str, name: &'static str) -> ListAnswer { /// which the byte-less spellings cannot see, as C#'s primary constructor /// (`csharp_byte_less_spellings_omit_the_primary_constructor`): the /// gate reads the record's body through the chain and its constructors' -/// types from the bytes, so the byte-less `is_func` forwards the -/// known-empty chain as `is_func_space` does, and the header is no -/// callable to it. Every other `formal_parameters` — a method's, a +/// types from the bytes, neither of which the byte-less pair hands it. +/// Every other `formal_parameters` — a method's, a /// constructor's, and the header of a record whose body writes a /// compact or a normal canonical constructor — answers alike on both. /// The normal canonical constructor is told from an alternative by its diff --git a/big-code-analysis-bench/src/shapes.rs b/big-code-analysis-bench/src/shapes.rs index d6cb667d0..d223858d6 100644 --- a/big-code-analysis-bench/src/shapes.rs +++ b/big-code-analysis-bench/src/shapes.rs @@ -251,7 +251,7 @@ pub fn nested_declarations(depth: usize) -> String { /// Elixir: a module of nested `quote` blocks, each wrapping a `def`. /// -/// Elixir's `is_func` asks `elixir_is_inside_quote_block` for every +/// Elixir's callable test asks `elixir_is_inside_quote_block` for every /// `def`-like call, because a `def` inside `quote` is quoted AST /// rather than a definition. That predicate walks the ancestor chain /// reading each ancestor's call keyword out of the source bytes. It @@ -505,7 +505,7 @@ pub fn c_unclosed_comment_rows(width: usize) -> String { /// The linear control for [`nested_arrows`]: one function per nesting /// level and one `FuncSpace` per level, as there, but *declared* rather /// than written as an expression. `function_declaration` is a distinct -/// grammar production, so `Checker::is_func` answers it from the node's +/// grammar production, so the callable test answers it from the node's /// own kind and never starts the ancestor walk. What is left is the /// space-nesting bookkeeping the two shapes share. /// @@ -1127,7 +1127,7 @@ pub fn nested_cfg_predicate(depth: usize) -> String { /// /// The JS grammars have no production for "named function": `const f = /// () => …` and `g(() => …)` are the same `arrow_function` node, and -/// `Checker::is_func` tells them apart by asking the ancestors for a +/// the callable test tells them apart by asking the ancestors for a /// name binding before a frame that proves positional use. Here the /// enclosing `statement_block` is that frame two steps up — which is /// the point; [`js_arrow_per_array_depth`] is the shape with no frame @@ -2587,7 +2587,7 @@ pub const PROBES: &[Probe] = &[ render: nested_quotes, sizes: LINEAR_DEPTHS, max_exponent: LINEAR_BOUND, - rationale: "#1084: Elixir's `is_func` asks \ + rationale: "#1084: Elixir's callable test asks \ `elixir_is_inside_quote_block` for every `def`. The \ predicate short-circuits on the first `quote` \ ancestor, and each step now indexes the walker's \ @@ -3066,7 +3066,7 @@ pub const PROBES: &[Probe] = &[ max_exponent: LINEAR_BOUND, rationale: "Shape control for `nom/nested-arrow`: one function and \ one `FuncSpace` per level as there, but declared with \ - `function`, which `Checker::is_func` answers from the \ + `function`, which the callable test answers from the \ node's own kind without an ancestor walk.", }, Probe { @@ -3081,7 +3081,7 @@ pub const PROBES: &[Probe] = &[ render: nested_arrows, sizes: LINEAR_DEPTHS, max_exponent: LINEAR_BOUND, - rationale: "#1088: the JS-family `Checker::is_func` / `is_closure` \ + rationale: "#1088: the JS-family callable test and `is_closure` \ decide whether an `arrow_function` is bound to a name by \ walking upward. The enclosing `statement_block` stops \ that walk after two steps, but `Node::parent` is \ diff --git a/docs/development/benchmarking.md b/docs/development/benchmarking.md index 8f7beaae4..2d747b790 100644 --- a/docs/development/benchmarking.md +++ b/docs/development/benchmarking.md @@ -152,7 +152,7 @@ Read it as follows. | `loc/nested-fn-rows` | Rust | depth | `Ploc::merge` / `Cloc::merge` row-set union (#1109) | linear | | `nom/nested-fn-rows` | Rust | depth | metric control for the row above | linear | | `nom/nested-declared-function` | JavaScript | depth | shape control for the row below | linear | -| `nom/nested-arrow` | JavaScript | depth | JS-family `is_func` / `is_closure` (#1088) | linear | +| `nom/nested-arrow` | JavaScript | depth | JS-family `is_func_with_code` / `is_closure` (#1088) | linear | | `nom/js-arrow-per-array-depth` | JavaScript | depth | the same binding question with no frame below the root, folded on `FoldLane::NamedBinding` (#1767) | linear | | `cognitive/python-and-per-list-depth` | Python | depth | a boolean operator's "inside another chain" and enclosing-`lambda` questions, with no stop in a list, folded on `GateLane::InsideBooleanChain` and `FoldLane::LambdaDepth` (#1767) | linear | | `nom/wide-arrow-array` | JavaScript | width | the arrow binding gate's parent sibling scan on `run(() => 1, …)`, memoised per parent under `MemoQuestion::NamesAnArrow` (#1696) | linear | diff --git a/docs/development/grammar_dispatch.md b/docs/development/grammar_dispatch.md index fa73a857a..ad6bef116 100644 --- a/docs/development/grammar_dispatch.md +++ b/docs/development/grammar_dispatch.md @@ -116,10 +116,10 @@ both reads `pays_at_wrapper` and `pays_at_leaf` explicitly. ## 6. Narrow a dispatch set with a gate, never by deletion -Deleting a kind from `is_func` / `is_func_space` to stop an over-count -regresses its childless variant to zero. Gate the arm on child presence -and keep `is_func`, `is_func_space` and `get_space_kind` on the same -predicate. When a wrapper/leaf pair double-counts, the keeper is the +Deleting a kind from the `FuncOpener` row to stop an over-count +regresses its childless variant to zero. Gate the owner on child +presence, which keeps `is_func_with_code`, `is_func_space_with_code` +and `get_space_kind_with_code` on the same predicate. When a wrapper/leaf pair double-counts, the keeper is the node present for every spelling, verified with `bca dump` on valid and on recovery input: `node-types.json` describes the well-formed grammar only, and an `ERROR` root routinely holds the leaf with no wrapper. @@ -141,16 +141,18 @@ differently. last pair fails quietly: a space the walker opens but the getter leaves `Unknown` is not a member scope, so it serialises no `npm` / `npa` block and nothing diffs. Cross-walk the `_with_code` spellings, which -are what the walk calls: the byte-less defaults forward to them and -agree everywhere except the languages that override (Elixir's -keyword-text containers, Ruby's lambda-body blocks, C#'s primary -constructor — a `parameter_list` gated `under` a type declaration -(#1828) — and a Java or Groovy record's header, gated on a record -parent whose body writes no canonical constructor, told by the -constructors' names and types as bytes (#1842); the known-empty chain sees -neither gate, and for the header the byte-less `is_func` forwards it -too), which is exactly where the answer matters. `tests/parity/ops_metrics_space_parity.rs` -keeps `bca ops` and `bca metrics` opening the same spaces. +are what the walk calls and what every language must write: the +byte-less `is_func_space` and `get_space_kind` derive from them (#1863) +and agree everywhere except where a gate reads what they drop +(Elixir's keyword-text containers, Ruby's lambda-body blocks, C#'s +primary constructor — a `parameter_list` gated `under` a type +declaration (#1828) — and a Java or Groovy record's header, gated on a +record parent whose body writes no canonical constructor, told by the +constructors' names and types as bytes (#1842); the known-empty chain +sees neither gate), which is exactly where the answer matters. The +callable test has no byte-less spelling: ask `is_func_with_code`. +`tests/parity/ops_metrics_space_parity.rs` keeps `bca ops` and +`bca metrics` opening the same spaces. ## 8. Anchor a default/fallback exclusion to the construct diff --git a/src/function.rs b/src/function.rs index e359991d1..68d0fe2aa 100644 --- a/src/function.rs +++ b/src/function.rs @@ -60,8 +60,7 @@ pub(crate) fn function(parser: &T) -> Vec { // `is_func_with_code`, not `promotes_to_func_space_with_code`: // this seam enumerates *functions*, so an Elixir `defmodule` // stays out for the same reason a Rust `impl` block and a Java - // class do. Every language but Elixir inherits the byte-less - // `is_func` through the default impl (#1162). + // class do (#1162). if T::Checker::is_func_with_code(n, code, ancestors) { let start_line = n.start_row() + 1; // `Node::end_line`, not a blanket `end_row() + 1`: a function diff --git a/src/metrics/cognitive.rs b/src/metrics/cognitive.rs index 6fedb56f7..451ccfcd3 100644 --- a/src/metrics/cognitive.rs +++ b/src/metrics/cognitive.rs @@ -4629,7 +4629,7 @@ fn ie(x: bool) -> i32 { /// Regression for #1160: a record's compact constructor is its own /// grammar kind (`compact_constructor_declaration`), which was absent - /// from `is_func`, `get_space_kind`, and the boundary arm in + /// from the callable test, `get_space_kind`, and the boundary arm in /// `cognitive/java.rs`. It therefore opened no function space and its /// control flow was charged to the enclosing class, so `bca check` /// could never flag one however complex it got. @@ -11030,7 +11030,7 @@ end", // expected: nesting.conditional 2 from `outer`'s two `if`s, so the // callback's own `if` costs +3. The `nom` assertion states the // premise — that this shape really is on the closure side of - // `is_func` / `is_closure` — rather than leaving it implied. + // function / closure split — rather than leaving it implied. check_func_space::( "function outer(a, b) { if (a) { if (b) { run(function (c) { if (c) { return 1; } }); } } diff --git a/src/metrics/cyclomatic.rs b/src/metrics/cyclomatic.rs index e0f9605b7..2007f1079 100644 --- a/src/metrics/cyclomatic.rs +++ b/src/metrics/cyclomatic.rs @@ -463,8 +463,29 @@ mod tests { #[cfg(feature = "cpp")] mod constrained_probe { use super::*; + + // A `Checker` that opens no space and names no function: the two + // predicates the trait requires, answered `false`. + macro_rules! probe_checker { + ($name:ident) => { + impl Checker for $name { + fn is_func_space_with_code<'a>( + _: &Node<'a>, + _: &[u8], + _: Ancestors<'a, '_>, + ) -> bool { + false + } + + fn is_func_with_code<'a>(_: &Node<'a>, _: &[u8], _: Ancestors<'a, '_>) -> bool { + false + } + } + }; + } + struct Probe; - impl Checker for Probe {} + probe_checker!(Probe); impl_cyclomatic_rows!( Probe, Cpp, @@ -476,7 +497,7 @@ mod tests { constraints = [RequiresClause, RequiresExpression], ); struct Empty; - impl Checker for Empty {} + probe_checker!(Empty); impl_cyclomatic_rows!( Empty, Cpp, diff --git a/src/metrics/nargs.rs b/src/metrics/nargs.rs index 3131eaf84..a9c8c13c3 100644 --- a/src/metrics/nargs.rs +++ b/src/metrics/nargs.rs @@ -29,10 +29,10 @@ use crate::*; /// This metric counts the number of arguments /// of functions/closures. /// -/// A callable is whatever opens a `Function` space and is `is_func`: -/// a Kotlin or C# primary constructor is one, its space being the -/// parameter list in the class header (#1828), so its parameters are -/// its own and never the class's. +/// A callable is whatever opens a `Function` space and is +/// `is_func_with_code`: a Kotlin or C# primary constructor is one, its +/// space being the parameter list in the class header (#1828), so its +/// parameters are its own and never the class's. /// /// Unlike the per-function fields of cyclomatic, cognitive and nexits /// (#1284), the extrema and the averages here read different @@ -316,13 +316,12 @@ where /// Walk `node` and update `stats` with this metric for the language /// implementing the trait. /// - /// Uses the source-aware [`Checker::is_func_with_code`] rather than the - /// byte-less `is_func`, exactly as [`crate::nom::Nom::compute`] does. - /// For every grammar with a syntactic function-definition node the two - /// are the same predicate, so no count moves; the point is that a - /// language whose declarations are only recognisable from the source - /// text — Elixir's `def` is an ordinary `Call` (#275) — does not - /// silently report 0 here (#1142). + /// Asks [`Checker::is_func_with_code`], the bytes and the chain in + /// hand, exactly as [`crate::nom::Nom::compute`] does: a callable + /// recognisable only from the source text — Elixir's `def` is an + /// ordinary `Call` (#275) — or from what encloses it must not + /// silently report 0 here (#1142). Every override below asks the + /// same predicate; there is no byte-less one to reach for (#1863). fn compute<'a>(node: &Node<'a>, code: &[u8], ancestors: Ancestors<'a, '_>, stats: &mut Stats) { if Self::is_func_with_code(node, code, ancestors) { compute_args::( @@ -348,7 +347,7 @@ where /// Exists so a language that spells its parameters somewhere other /// than on the function node can say *that* and inherit everything /// else. Overriding [`Self::compute`] to change this one expression - /// means re-stating the `is_func_with_code`-not-`is_func` rule and + /// means re-stating the callable test and /// the closure fallback, and a language that copied them does not /// pick up a later correction — which is the drift #1142 and #1162 /// were both filed about. @@ -487,8 +486,8 @@ fn compute_go_args(node: &Node, nargs: &mut usize) { } impl NArgs for GoCode { - fn compute<'a>(node: &Node<'a>, _code: &[u8], ancestors: Ancestors<'a, '_>, stats: &mut Stats) { - if Self::is_func(node, ancestors) { + fn compute<'a>(node: &Node<'a>, code: &[u8], ancestors: Ancestors<'a, '_>, stats: &mut Stats) { + if Self::is_func_with_code(node, code, ancestors) { compute_go_args(node, &mut stats.fn_nargs); return; } @@ -534,7 +533,7 @@ fn compute_kotlin_lambda_args(node: &Node, code: &[u8], nargs: &mut usize) { impl NArgs for KotlinCode { fn compute<'a>(node: &Node<'a>, code: &[u8], ancestors: Ancestors<'a, '_>, stats: &mut Stats) { - if Self::is_func(node, ancestors) { + if Self::is_func_with_code(node, code, ancestors) { compute_kotlin_func_args(node, &mut stats.fn_nargs); return; } @@ -560,8 +559,8 @@ fn compute_lua_args(node: &Node, nargs: &mut usize) { } impl NArgs for LuaCode { - fn compute<'a>(node: &Node<'a>, _code: &[u8], ancestors: Ancestors<'a, '_>, stats: &mut Stats) { - if Self::is_func(node, ancestors) { + fn compute<'a>(node: &Node<'a>, code: &[u8], ancestors: Ancestors<'a, '_>, stats: &mut Stats) { + if Self::is_func_with_code(node, code, ancestors) { compute_lua_args(node, &mut stats.fn_nargs); } else if Self::is_closure(node, ancestors) { compute_lua_args(node, &mut stats.closure_nargs); @@ -580,8 +579,8 @@ fn compute_tcl_args(node: &Node, nargs: &mut usize) { } impl NArgs for TclCode { - fn compute<'a>(node: &Node<'a>, _code: &[u8], ancestors: Ancestors<'a, '_>, stats: &mut Stats) { - if Self::is_func(node, ancestors) { + fn compute<'a>(node: &Node<'a>, code: &[u8], ancestors: Ancestors<'a, '_>, stats: &mut Stats) { + if Self::is_func_with_code(node, code, ancestors) { compute_tcl_args(node, &mut stats.fn_nargs); } } @@ -603,8 +602,8 @@ fn compute_irules_args(node: &Node, nargs: &mut usize) { } impl NArgs for IrulesCode { - fn compute<'a>(node: &Node<'a>, _code: &[u8], ancestors: Ancestors<'a, '_>, stats: &mut Stats) { - if Self::is_func(node, ancestors) { + fn compute<'a>(node: &Node<'a>, code: &[u8], ancestors: Ancestors<'a, '_>, stats: &mut Stats) { + if Self::is_func_with_code(node, code, ancestors) { compute_irules_args(node, &mut stats.fn_nargs); } } @@ -659,7 +658,7 @@ fn compute_perl_args(node: &Node, code: &[u8], nargs: &mut usize) { impl NArgs for PerlCode { fn compute<'a>(node: &Node<'a>, code: &[u8], ancestors: Ancestors<'a, '_>, stats: &mut Stats) { - if Self::is_func(node, ancestors) { + if Self::is_func_with_code(node, code, ancestors) { compute_perl_args(node, code, &mut stats.fn_nargs); return; } @@ -735,11 +734,9 @@ fn elixir_unwrap_guard<'a>(node: &Node<'a>, code: &[u8]) -> Node<'a> { impl NArgs for ElixirCode { fn compute<'a>(node: &Node<'a>, code: &[u8], ancestors: Ancestors<'a, '_>, stats: &mut Stats) { - // `is_func` is byte-less and constant `false` for Elixir, because a - // `def` is textually indistinguishable from any other `Call`. The - // code-aware predicate (#275) is the only one that identifies one, - // and it also excludes a `def` inside `quote do … end`, which - // declares nothing until the macro expands (#310). + // A `def` is a `Call` told from any other by its target text + // (#275), and one inside `quote do … end` declares nothing until + // the macro expands (#310): the predicate reads both. if Self::is_func_with_code(node, code, ancestors) { stats.fn_nargs += elixir_declared_args(node, code); return; @@ -943,36 +940,24 @@ mod tests { // count is only observable one space at a time. check_func_space_only_shim!(check_spaces, Nargs); - /// The `compute` impls above for Go, Kotlin, Lua, Tcl, iRules and - /// Perl read the byte-less `is_func` / `is_closure`, and Elixir's, - /// Groovy's and the shared impl read the byte-less `is_closure`: - /// each hands the walk's chain through and no bytes, which answers - /// the row's question only while no owner of that row is - /// `text_gated_by`. This pins that — a row that grows a text gate - /// fails here, naming the impl that must move to the `_with_code` - /// spelling rather than silently missing the gated owner (#1696 - /// AC 3). The text-gated `FuncOpener` rows are read through - /// `is_func_with_code`: Elixir's by its impl, and since #1842 - /// Java's by the shared impl and Groovy's by its own — a record's - /// header is gated on the body's constructor *types*, and the - /// byte-less spelling forwards a known-empty chain under which the - /// header is no callable at all - /// (`java_header_beside_a_same_arity_alternative_counts_its_components`). - /// The rows are declarations, built in every feature set, so this - /// needs no grammar. - #[test] - fn byte_less_spellings_read_only_rows_without_a_text_gate() { - use crate::roles::{elixir, go, groovy, irules, java, kotlin, lua, perl, tcl}; + /// Every `compute` impl above reads the byte-less `is_closure`: it + /// hands the walk's chain through and no bytes, which answers the + /// `Closure` row's question only while no owner of that row is + /// `text_gated_by`. This pins that for the impls that spell the + /// call themselves — a row that grows a text gate fails here, + /// naming the impl that must stop dropping the bytes rather than + /// silently missing the gated owner (#1696 AC 3). The callable half + /// needs no such pin since #1863: every impl asks + /// `is_func_with_code`, the only spelling. The rows are + /// declarations, built in every feature set, so this needs no + /// grammar. + #[test] + fn byte_less_is_closure_reads_only_rows_without_a_text_gate() { + use crate::roles::{elixir, go, groovy, java, kotlin, lua, perl}; let rows: &[(&str, bool)] = &[ - ("go FuncOpener", go::func_opener::TEXT_GATED), ("go Closure", go::closure::TEXT_GATED), - ("kotlin FuncOpener", kotlin::func_opener::TEXT_GATED), ("kotlin Closure", kotlin::closure::TEXT_GATED), - ("lua FuncOpener", lua::func_opener::TEXT_GATED), ("lua Closure", lua::closure::TEXT_GATED), - ("tcl FuncOpener", tcl::func_opener::TEXT_GATED), - ("irules FuncOpener", irules::func_opener::TEXT_GATED), - ("perl FuncOpener", perl::func_opener::TEXT_GATED), ("perl Closure", perl::closure::TEXT_GATED), ("java Closure", java::closure::TEXT_GATED), ("groovy Closure", groovy::closure::TEXT_GATED), @@ -981,18 +966,7 @@ mod tests { for (row, text_gated) in rows { assert!( !text_gated, - "{row} grew a text gate: its `NArgs::compute` must read the `_with_code` spelling" - ); - } - let read_with_code = [ - ("elixir FuncOpener", elixir::func_opener::TEXT_GATED), - ("java FuncOpener", java::func_opener::TEXT_GATED), - ("groovy FuncOpener", groovy::func_opener::TEXT_GATED), - ]; - for (row, text_gated) in read_with_code { - assert!( - text_gated, - "{row} is read through `is_func_with_code` above" + "{row} grew a text gate: its `NArgs::compute` must stop reading the byte-less `is_closure`" ); } } @@ -2720,7 +2694,7 @@ mod tests { ); } - /// Perl 5.38's `method` is a second `is_func` kind + /// Perl 5.38's `method` is a second callable kind /// (`function_definition_without_sub`) reaching the same helper, so it /// gets its own fixture rather than riding on the `sub` tests. #[cfg(feature = "perl")] @@ -4634,13 +4608,14 @@ class A(val x: Int)", } /// The header's row is gated on the *bytes* of the body's - /// constructor types, so a byte-less `is_func` asked of it reads + /// constructor types, so a callable test handed none reads /// every same-arity constructor as canonical — `A(long a)` beside /// component `int a` closes the header under no bytes and leaves it /// open under the real ones. The space walk opens the header with - /// the bytes; a `compute` whose callable test fell through to the - /// byte-less spelling counted nothing on that space, and the header - /// row read `nargs` 0 beside the alternative's 1. Both rows are 1: + /// the bytes; a `compute` whose callable test dropped them (the + /// byte-less `is_func` #1863 removed) counted nothing on that space, + /// and the header row read `nargs` 0 beside the alternative's 1. + /// Both rows are 1: /// the header's one component and the alternative's one parameter. #[cfg(feature = "java")] #[test] @@ -4664,9 +4639,9 @@ class A(val x: Int)", /// Groovy's twin of /// `java_header_beside_a_same_arity_alternative_counts_its_components`: - /// the `record_components` row's gate compares type bytes, so the - /// byte-less `is_func` closes the header beside any same-arity - /// constructor and the walk's space read 0. + /// the `record_components` row's gate compares type bytes, so a + /// callable test handed none closes the header beside any + /// same-arity constructor and the walk's space read 0. #[cfg(feature = "groovy")] #[test] fn groovy_header_beside_a_same_arity_alternative_counts_its_components() { diff --git a/src/metrics/nom.rs b/src/metrics/nom.rs index 0b75e8309..4710d1f43 100644 --- a/src/metrics/nom.rs +++ b/src/metrics/nom.rs @@ -225,14 +225,11 @@ where /// Walk `node` and update `stats` with this metric for the language /// implementing the trait. /// - /// Uses the source-aware [`Checker::is_func_with_code`] rather than the - /// byte-less `is_func`. For every grammar that exposes a syntactic - /// function-definition node, `is_func_with_code` forwards to `is_func`, - /// so the count is unchanged. Elixir is the exception: its `def`/`defp`/ - /// `defmacro`/`defmacrop` declarations are ordinary `Call` nodes that - /// only a source-text lookup can recognise, so its `is_func_with_code` - /// override now classifies them as functions instead of leaving - /// `functions_sum` permanently at 0 (#696). + /// Asks [`Checker::is_func_with_code`], the bytes and the chain in + /// hand. Elixir's `def`/`defp`/`defmacro`/`defmacrop` declarations are + /// ordinary `Call` nodes that only a source-text lookup can + /// recognise, so a callable test with no bytes left `functions_sum` + /// permanently at 0 (#696). /// /// `ancestors` is the chain the walker descended through; Elixir's /// `is_func_with_code` needs it to spot a `def` inside a `quote` @@ -1387,8 +1384,8 @@ mod tests { fn csharp_expression_bodied_indexer_nom() { // An expression-bodied indexer (`this[int i] => _d[i];`) has NO // `accessor_declaration` child — it defines a single implicit - // getter. Removing the IndexerDeclaration entry from is_func / - // is_func_space outright would drop this to 0; the #464 fix gates + // getter. Removing the IndexerDeclaration entry from the callable + // and space tests outright would drop this to 0; the #464 fix gates // the entry on the absence of accessors so this form still counts // as 1, matching the npm `.max(1)` fallback. check_nom_and_npm::( @@ -1618,7 +1615,7 @@ mod tests { } /// Regression for #1160: `compact_constructor_declaration` was absent - /// from `JavaCode::is_func`, so a record's compact constructor was + /// from Java's callables, so a record's compact constructor was /// invisible to every metric keyed on that predicate — `nom` included. /// /// The delegating `R(int a)` is the control: it is an ordinary @@ -2359,9 +2356,9 @@ outer() { } // Elixir's `def`/`defp`/`defmacro`/`defmacrop` declarations surface - // as `Call` nodes whose target is an `Identifier`, so the byte-less - // `is_func` cannot see them. Since #696, `Nom::compute` consults the - // source-aware `is_func_with_code`, so the three named declarations + // as `Call` nodes whose target is an `Identifier`, so a callable test + // with no bytes cannot see them. Since #696, `Nom::compute` consults + // `is_func_with_code`, so the three named declarations // (`public_fn`, `private_fn`, `with_anon`) now count as FUNCTIONS and // the two `fn x -> … end` literals count as CLOSURES — the same split // every other language already produced. `functions_sum` was pinned at diff --git a/src/metrics/npm.rs b/src/metrics/npm.rs index 9aa67b3e6..79a75ecdd 100644 --- a/src/metrics/npm.rs +++ b/src/metrics/npm.rs @@ -1435,7 +1435,7 @@ mod tests { }", "foo.java", |metric| { - // `JavaCode::is_func` accepts both `MethodDeclaration` + // The callable test accepts both `MethodDeclaration` // and `ConstructorDeclaration`, so the body contributes // one method (`sum`) plus one explicit constructor // (`Point()`), both annotated `public`; `Point()` is an @@ -1450,7 +1450,7 @@ mod tests { } /// The same for #1160, which added `CompactConstructorDeclaration` to - /// `JavaCode::is_func`: a record's compact constructor joins the body + /// Java's callables: a record's compact constructor joins the body /// walker's method count on the same footing as the canonical /// spelling. The `public` modifier check reads `child(0)`, and the /// compact form carries its optional `modifiers` node in that same diff --git a/src/metrics/npm/kotlin.rs b/src/metrics/npm/kotlin.rs index 778e71573..9cc7540fc 100644 --- a/src/metrics/npm/kotlin.rs +++ b/src/metrics/npm/kotlin.rs @@ -85,7 +85,7 @@ impl Npm for KotlinCode { // tree-sitter-kotlin elides the `class_member_declaration` and // `declaration` rule layers, so function declarations and // secondary constructors appear as direct children of - // `class_body`. `Self::is_func` recognises both kinds. + // `class_body`. The callable test recognises both kinds. let under = ancestors.of_children(node); for func in direct_child_funcs::(node, code, under.get()) { if is_interface { diff --git a/src/metrics/npm/python.rs b/src/metrics/npm/python.rs index 3f5001d74..15e6083e6 100644 --- a/src/metrics/npm/python.rs +++ b/src/metrics/npm/python.rs @@ -23,7 +23,7 @@ use super::*; // // Nested classes and async functions are handled naturally: // `async def m(self):` still parses as `FunctionDefinition`, so the -// `is_func` check covers it without special-casing. Nested +// callable test covers it without special-casing. Nested // `ClassDefinition` children of a class body are skipped here — they // open their own class space, where their methods will be counted. impl Npm for PythonCode { diff --git a/src/metrics/wmc.rs b/src/metrics/wmc.rs index 7fe9aba25..930383366 100644 --- a/src/metrics/wmc.rs +++ b/src/metrics/wmc.rs @@ -276,7 +276,7 @@ impl Wmc for PhpCode { // the enclosing class). // - `Unknown` (anything else — skipped). // -// Lambdas (`Lambda`) are not `is_func` and therefore do not open a +// Lambdas (`Lambda`) are not `is_func_with_code` and so do not open a // `Function` space, so they correctly do *not* contribute to WMC // — they are anonymous expressions, not methods. impl Wmc for PythonCode { @@ -2668,9 +2668,9 @@ mod tests { // charged to the enclosing class space without WMC ever seeing // it, and `bca check` could not flag one however complex it got. // - // WMC keys on `SpaceKind::Function` rather than on `is_func`, + // WMC keys on `SpaceKind::Function` rather than on the callable test, // which is why this moves even though the block is deliberately - // *not* in `is_func` (it is not a callable anyone names). + // *not* a callable (it is not a callable anyone names). check_metrics::( "class C(val n: Int) { // +1 since #1828 init { // +1 since #1184 diff --git a/src/spaces_tests.rs b/src/spaces_tests.rs index 5bba378ea..6e3ec25dd 100644 --- a/src/spaces_tests.rs +++ b/src/spaces_tests.rs @@ -72,8 +72,8 @@ fn cpp_function_definition_is_classified_as_function() { .expect("parse must produce a function_definition node"); assert!( - CppCode::is_func(&fn_node, Ancestors::unknown()), - "is_func must return true for a function_definition" + CppCode::is_func_with_code(&fn_node, source.as_bytes(), Ancestors::unknown()), + "is_func_with_code must return true for a function_definition" ); assert!( CppCode::is_func_space(&fn_node), @@ -2865,7 +2865,7 @@ mod nameless_construct_spaces { // `nom.functions` deliberately stays 0. The issue calls an // accessor-only file reporting `nom.functions == 0` the worst of // the set, and this fix does *not* change that number: `Nom` - // keys on `is_func`, and these constructs are `is_func_space` + // keys on the callable test, and these constructs open a space // only, because a Kotlin accessor is not a callable anyone names // at a call site (`p.foo`, not `p.getFoo()`) and counting it as // a method would have `npm` bill the same property once as an @@ -2875,11 +2875,11 @@ mod nameless_construct_spaces { // caused: each accessor now has its own metric scope, so its // complexity is no longer charged to the class and `bca check` // can flag it. WMC picks them up because it keys on the space - // kind rather than on `is_func`. + // kind rather than on the callable test. assert_eq!( root.metrics.nom.functions_sum(), 0, - "accessors are is_func_space, not is_func" + "accessors open a space and are no callable" ); assert_eq!( root.metrics.wmc.class_wmc_sum(), diff --git a/src/suppression.rs b/src/suppression.rs index 567ecfbcc..a70729bd1 100644 --- a/src/suppression.rs +++ b/src/suppression.rs @@ -757,13 +757,11 @@ pub(crate) fn suppression_markers(parser: &T) -> Vec(&node, code, enclosing) { markers.push(marker); } - // `is_func_with_code` rather than `is_func`: Java, Groovy and - // Elixir identify some functions only with the source bytes, - // and the default impl delegates to `is_func` for every other - // language. The predicates that consult an ancestor — Elixir's - // `quote` template check, the JS-family name-binding walk — read - // it off `chain` rather than climbing with `Node::parent` - // (#1088). `for_walk_without_siblings` is one of the two walk + // The callable test takes the bytes and the chain. The + // predicates that consult an ancestor — Elixir's `quote` + // template check, the JS-family name-binding walk — read it off + // `chain` rather than climbing with `Node::parent` (#1088). + // `for_walk_without_siblings` is one of the two walk // constructors, which lend the memo and record the visit in one // step (#1737), and the one that says this walk records no // siblings: none of these predicates asks for one, and one that @@ -1607,11 +1605,10 @@ mod tests { #[cfg(feature = "elixir")] #[test] fn collector_elixir_requires_code_aware_func_predicate() { - // Elixir is the language whose `Checker::is_func` returns `false` - // unconditionally — it identifies functions only through the - // code-aware `is_func_with_code`. This test fails if the walk - // reverts to plain `is_func` (the enclosing function would then - // resolve to `None`), so it pins the predicate choice in + // Elixir tells a function only by the bytes: a `def` is a `call` + // whose target text says so. This test fails if the walk's + // callable test is handed none (the enclosing function would + // then resolve to `None`), so it pins the predicate choice in // `suppression_markers`. let src = "defmodule M do\n def parse_long do\n # bca: suppress\n x = 1\n end\nend\n"; diff --git a/tests/api/ast_seam_test.rs b/tests/api/ast_seam_test.rs index 527b4f969..6de9df31c 100644 --- a/tests/api/ast_seam_test.rs +++ b/tests/api/ast_seam_test.rs @@ -598,7 +598,7 @@ fn count_matches_named_kinds() { let (matching, total) = ast.count(&["function_item".to_owned()]); assert_eq!(matching, 2); assert!(total > matching, "total must include non-matching nodes"); - // The `function` keyword filter resolves to the same `is_func` + // The `function` keyword filter resolves to the same callable // predicate, so it agrees with the exact-kind count here. let (by_keyword, _) = ast.count(&["function".to_owned()]); assert_eq!(by_keyword, 2); diff --git a/tests/grammars/c_grammar_metrics.rs b/tests/grammars/c_grammar_metrics.rs index b0349b346..779e3c57a 100644 --- a/tests/grammars/c_grammar_metrics.rs +++ b/tests/grammars/c_grammar_metrics.rs @@ -92,8 +92,8 @@ mod c_metrics { /// return type wraps the declarator therefore parses as a plain /// `declaration` that swallows the first parameter declaration, with /// the body orphaned as a bare `compound_statement` sibling — no - /// `ERROR` node, no `function_definition`, so `is_func` never sees a - /// node to match. `LANG::Objc` shares the defect and `Cpp` / `Mozcpp` + /// `ERROR` node, no `function_definition`, so the callable test never + /// sees a node to match. `LANG::Objc` shares the defect and `Cpp` / `Mozcpp` /// open no space for either form (no K&R rule at all); both are /// recorded in the book's Supported Languages page rather than here, /// since this suite drives `LANG::C` only. diff --git a/tests/parity/functions_metrics_parity.rs b/tests/parity/functions_metrics_parity.rs index a5734d4b4..448d1c500 100644 --- a/tests/parity/functions_metrics_parity.rs +++ b/tests/parity/functions_metrics_parity.rs @@ -40,7 +40,7 @@ use super::ops_metrics_space_parity::fixture; /// only some call it a *function*: Rust's `ClosureExpression`, Go's /// `FuncLiteral`, Perl's and PHP's anonymous `sub`/`function`, Ruby's /// `lambda` and Lua's `function` expression are `is_func_space` without -/// being `is_func`, while a JavaScript arrow function and an iRules +/// being callables, while a JavaScript arrow function and an iRules /// `when` block are both. `bca functions` therefore reports some such /// spaces and not others, which is a per-grammar judgement this test has /// no business pinning — so the coverage claim below is scoped to spaces @@ -56,7 +56,7 @@ use super::ops_metrics_space_parity::fixture; /// /// `` is the trait default; #1184 added the other four for /// constructs that carry executable code but no name token, each -/// `is_func_space` without being `is_func` for exactly the reason above. +/// `is_func_space` without being a callable for exactly the reason above. #[cfg(any( feature = "bash", feature = "c", diff --git a/tests/parity/ops_metrics_space_parity.rs b/tests/parity/ops_metrics_space_parity.rs index 6e1090092..bfc54cb2e 100644 --- a/tests/parity/ops_metrics_space_parity.rs +++ b/tests/parity/ops_metrics_space_parity.rs @@ -115,7 +115,7 @@ pub(super) fn fixture(lang: LANG) -> (&'static str, &'static str) { "m", ), // An expression-bodied property alongside an ordinary method: - // per `docs/development/grammar_dispatch.md` §6, `is_func`, + // per `docs/development/grammar_dispatch.md` §6, the callable test, // `is_func_space`, and `get_space_kind` must stay gated by the // same child-presence predicate for these, and a mismatch shows // up here as an ops/metrics divergence. From a359774b491aafec495f10b7d42c4ac3f393daf6 Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Wed, 11 Nov 2026 16:26:15 -0800 Subject: [PATCH 02/21] test(loc,roles): pin the chain the doc-body callable test reads Dropping the chain from the callable half of `holds_doc_comment_in_body` failed nothing in the workspace, for the JS family or for C# (two `utils/perturb.py` cases over `cargo test --workspace --all-features --no-fail-fast`, both UNCAUGHT). - JS family: a doc comment in a bound arrow's or bound function expression's body, above a call. Without the chain the function is neither a callable nor a closure, its body holds nothing, and the comment binds forward to the call: `dloc` 0 where it reads 1. - C#: no `dloc` reads the difference, since a `///` in a primary constructor's parameter list binds forward to a parameter. The pin is at the `Checker`: the list holds under its type declaration and a method's own list does not. Refs #1863 --- .../src/roles/doc_tests/mod.rs | 34 +++++++++++++++ src/metrics/loc/dloc.rs | 43 +++++++++++++++++++ 2 files changed, 77 insertions(+) diff --git a/big-code-analysis-ast/src/roles/doc_tests/mod.rs b/big-code-analysis-ast/src/roles/doc_tests/mod.rs index e6715b90c..3137030cd 100644 --- a/big-code-analysis-ast/src/roles/doc_tests/mod.rs +++ b/big-code-analysis-ast/src/roles/doc_tests/mod.rs @@ -1176,6 +1176,40 @@ mod csharp { "the row is read before the callable test" ); } + + /// A primary constructor's `parameter_list` is a callable only under + /// a type declaration (#1828), which the body test learns from the + /// chain the walk hands it: asked of that list it holds, as a method + /// holds what sits in it, and a method's own list does not. No + /// `dloc` reads the difference — a `///` in the list binds forward + /// to a parameter, which is no target — so this is the one pin that + /// the callable half of the body test is asked with the walk's chain + /// rather than a known-empty one, under which the list is no + /// callable at all (#1863). + #[test] + fn primary_constructor_list_holds_doc_by_the_chain() { + let source = b"class C(int a) { void M(int b) { } }\n"; + let mut lists = Vec::new(); + for_each_node_with_chain::(source, |node, chain| { + if node.kind_id() != Csharp::ParameterList as u16 { + return; + } + let first = node.child(0).expect("a list opens with `(`"); + lists.push(( + node.utf8_text(source).expect("UTF-8").to_owned(), + CsharpCode::holds_doc_comment_in_body( + node, + source, + Ancestors::known(chain), + &first, + ), + )); + }); + assert_eq!( + lists, + [("(int a)".to_owned(), true), ("(int b)".to_owned(), false)] + ); + } } #[cfg(feature = "php")] diff --git a/src/metrics/loc/dloc.rs b/src/metrics/loc/dloc.rs index 8305bc10e..15cbf59cd 100644 --- a/src/metrics/loc/dloc.rs +++ b/src/metrics/loc/dloc.rs @@ -2249,6 +2249,49 @@ mod tests { assert_doc_rows(LANG::Mozjs, cases); } + /// A JS-family doc comment in a function body keeps the unbound + /// reading (JSDoc's inner symbols, #1613) however the function is + /// spelled. The body test asks the callable test with the walk's + /// chain, which is what tells a *bound* arrow or function expression + /// from a closure (#1088): asked without it a bound one is neither, + /// its body holds nothing, and the comment binds forward to the call + /// below it, which is no declaration — `dloc` 0 where each of these + /// reads 1 (#1863). The positional rows are the closure half of the + /// same test. + #[cfg(all(feature = "javascript", feature = "mozjs", feature = "typescript"))] + #[test] + fn js_family_in_body_doc_comments_read_the_function_s_binding() { + let cases: &[(&str, &[u8], u64, u64)] = &[ + ( + "bound arrow", + b"const f = () => {\n /** d */\n foo();\n};\n", + 1, + 1, + ), + ( + "bound function expression", + b"const f = function () {\n /** d */\n foo();\n};\n", + 1, + 1, + ), + ( + "positional arrow", + b"run(() => {\n /** d */\n foo();\n});\n", + 1, + 1, + ), + ( + "positional function expression", + b"run(function () {\n /** d */\n foo();\n});\n", + 1, + 1, + ), + ]; + for lang in [LANG::Javascript, LANG::Mozjs, LANG::Typescript, LANG::Tsx] { + assert_doc_rows(lang, cases); + } + } + /// tsc's `getJSDocCommentsAndTags` gives a declaration the last `/**` /// before its first token, past every plain comment, and declares no /// symbol for an assignment statement; a comment after a decorator is From e93b37777c104a856110b13fb5be06bd0fc136f6 Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Wed, 11 Nov 2026 16:36:44 -0800 Subject: [PATCH 03/21] test(roles): add the byte-axis backstop and re-declare three gates it found MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `TEXT_GATED` is the author's word: a gate that reads source bytes under a plain `gated_by` builds, passes every `!TEXT_GATED` assertion a byte-less forward makes, and answers that forward from an empty slice. The chain axis has had a behavioural backstop since #1793; the byte axis had none. `unmarked_owners_answer_alike_without_the_bytes` asks every owner a row does not mark `text_gated_by`, and the table's `opens_space` fold, with the walk's bytes and with `&[]`, on every corpus candidate. It is per owner: `role_table!` now emits `TEXT_GATED_OWNERS` under `test-support` so a row one owner marks is still asked through its others. Both asks share one chain that lends no `FoldCache`, since a memo is keyed by node and would serve the byte-less ask the answer the real bytes stored. It found three owner gates declared `gated_by` that read bytes, now `text_gated_by`: - the Tcl family's `is_braced_literal` (Tcl and iRules `StringLit`), which tells a script body by the enclosing command's leading word; - Bash's `comparison_operator` and `short_circuit_operator`, which read a `test_operator`'s bytes to tell `-a` / `-o` from a comparison. The keyword changes no expansion and no metric value. No forward asserts `!TEXT_GATED` on those rows. A gate is seen only where its answer moves, so `BYTE_GATE_FIXTURES` adds the shapes no other source spells: a record with a same-arity alternative constructor for Java and Groovy, and a `[ … -a … ]` test for Bash. The Bash fixture gives `ShortCircuit` `binary_expression` its first positive, so that `NO_POSITIVE_IN_CORPUS` entry goes. The baseline records `roles/mod.rs` `ploc` and `sloc`. Refs #1863 --- .bca-baseline.toml | 4 +- big-code-analysis-ast/src/roles/bash.rs | 25 +- .../src/roles/derived_parity_tests.rs | 216 ++++++++++++++++-- big-code-analysis-ast/src/roles/mod.rs | 127 +++++++++- big-code-analysis-ast/src/roles/tcl_family.rs | 4 +- docs/development/lessons_learned.md | 3 +- 6 files changed, 335 insertions(+), 44 deletions(-) diff --git a/.bca-baseline.toml b/.bca-baseline.toml index 567c8f5ac..e67594ff4 100644 --- a/.bca-baseline.toml +++ b/.bca-baseline.toml @@ -359,13 +359,13 @@ value = 5.0 path = "big-code-analysis-ast/src/roles/mod.rs" qualified = "" metric = "loc.ploc" -value = 894.0 +value = 906.0 [[entry]] path = "big-code-analysis-ast/src/roles/mod.rs" qualified = "" metric = "loc.sloc" -value = 2279.0 +value = 2314.0 [[entry]] path = "big-code-analysis-ast/src/tools.rs" diff --git a/big-code-analysis-ast/src/roles/bash.rs b/big-code-analysis-ast/src/roles/bash.rs index 3bf3fd10f..ceb9ed05a 100644 --- a/big-code-analysis-ast/src/roles/bash.rs +++ b/big-code-analysis-ast/src/roles/bash.rs @@ -93,16 +93,17 @@ role_table! { // `-eq`, `-lt`, `-z`, `-n`, … — one kind the grammar shares with the // `-a` / `-o` connectives, so that payer is text-gated: a // `test_operator` pays as a comparison exactly when its bytes are - // not a connective. `=` compares inside a test and assigns inside + // not a connective — and so is the owner, whose gate reads the same + // bytes off its `operator` field (#1863). `=` compares inside a test and assigns inside // `(( … ))`, which only the test's descent can tell (#1536); the // ABC consumer counts it from the test, as its own extra. Comparison { owns [ - BinaryExpression(gated_by comparison_operator no_chain), - BinaryExpression2(gated_by comparison_operator no_chain), - BinaryExpression3(gated_by comparison_operator no_chain), - BinaryExpression4(gated_by comparison_operator no_chain), - BinaryExpression5(gated_by comparison_operator no_chain), + BinaryExpression(text_gated_by comparison_operator no_chain), + BinaryExpression2(text_gated_by comparison_operator no_chain), + BinaryExpression3(text_gated_by comparison_operator no_chain), + BinaryExpression4(text_gated_by comparison_operator no_chain), + BinaryExpression5(text_gated_by comparison_operator no_chain), ] pays [ EQEQ, BANGEQ, LTEQ, GTEQ, EQTILDE, @@ -121,18 +122,18 @@ role_table! { // `&&` / `||` join two commands in a `list` and two tests inside // `[[ … ]]` / `(( … ))` in a `binary_expression`; inside `[ … ]` the // same join is the `-a` / `-o` spelling of `test_operator`, read by - // text. Bash's `&&` / `||` are command-list separators, so the ABC + // text, at the payer and at the owner alike. Bash's `&&` / `||` are command-list separators, so the ABC // consumer reads this row for nothing (#1536 — Fitzpatrick Rule 9 // does not map onto its grammar) where cyclomatic and cognitive // read it. ShortCircuit { owns [ List, - BinaryExpression(gated_by short_circuit_operator no_chain), - BinaryExpression2(gated_by short_circuit_operator no_chain), - BinaryExpression3(gated_by short_circuit_operator no_chain), - BinaryExpression4(gated_by short_circuit_operator no_chain), - BinaryExpression5(gated_by short_circuit_operator no_chain), + BinaryExpression(text_gated_by short_circuit_operator no_chain), + BinaryExpression2(text_gated_by short_circuit_operator no_chain), + BinaryExpression3(text_gated_by short_circuit_operator no_chain), + BinaryExpression4(text_gated_by short_circuit_operator no_chain), + BinaryExpression5(text_gated_by short_circuit_operator no_chain), ] pays [AMPAMP, PIPEPIPE, TestOperator text_gated_by is_test_connective] project "operator" diff --git a/big-code-analysis-ast/src/roles/derived_parity_tests.rs b/big-code-analysis-ast/src/roles/derived_parity_tests.rs index b43f418b3..d5406cfc5 100644 --- a/big-code-analysis-ast/src/roles/derived_parity_tests.rs +++ b/big-code-analysis-ast/src/roles/derived_parity_tests.rs @@ -50,12 +50,13 @@ //! //! `control_flow//*` in the output submodule — the per-language //! fixtures #1744 preserved — plus the R09 documentation fixtures read -//! in place through `doc_tests::fixtures()`. Mozcpp and Mozjs own no -//! fixture of their own and read the C++ and JavaScript files under -//! their own grammars; Ccomment and Preproc own no extension and have -//! only inline fixtures. Every language must yield at least one -//! candidate, so a language the routing forgets fails rather than -//! passing empty. +//! in place through `doc_tests::fixtures()`, plus `BYTE_GATE_FIXTURES`, +//! the shapes a text gate's answer turns on that neither spells +//! (#1863). Mozcpp and Mozjs own no fixture of their own and read the +//! C++ and JavaScript files under their own grammars; Ccomment and +//! Preproc own no extension and have only inline fixtures. Every +//! language must yield at least one candidate, so a language the +//! routing forgets fails rather than passing empty. //! //! The CI `features` and `chain-audit` legs run the lib tests with no //! submodule checked out. The structural assertions — the macro @@ -73,8 +74,8 @@ use std::fmt::Write as _; use crate::roles::{DeclaredRow, LanguageTable, RowView}; use crate::test_support::{ - control_flow_corpus_present, control_flow_sources, for_each_node_with_sibling_cache, - for_each_node_with_sibling_cache_tolerating_errors, + control_flow_corpus_present, control_flow_sources, for_each_node_with_chain, + for_each_node_with_sibling_cache, for_each_node_with_sibling_cache_tolerating_errors, }; use crate::{Ancestors, Checker, LANG, Node, with_code_tag}; @@ -102,11 +103,46 @@ struct Source { bytes: Vec, } +/// Shapes a text gate's answer turns on that no other source spells, +/// kept in the tree so the byte backstop +/// (`unmarked_owners_answer_alike_without_the_bytes`) can see them on +/// the legs that check out no submodule: a gate re-declared under a +/// plain `gated_by` must *move* on some candidate to be caught, and +/// each of these is the one candidate that moves it (#1863). +/// +/// - A record whose body writes a same-arity constructor of another +/// type: the header gate compares type spellings, and with no bytes +/// every same-arity constructor spells the empty type and reads as +/// canonical. `B` writes the canonical one, the control. +/// - A `[ … ]` test joined by `-a` / `-o`: one `test_operator` kind +/// spells the connectives and the comparisons, told apart by text. +/// +/// Keyed by the table's name, as the exception tables below are: a +/// language is asked its fixture only when its table is enabled. +const BYTE_GATE_FIXTURES: &[(&str, &str, &[u8])] = &[ + ( + "Java", + "gate/java-records", + b"record A(int a) { A(long a) { this((int) a); } }\nrecord B(int b) { B(int b) { this.b = b; } }\n", + ), + ( + "Groovy", + "gate/groovy-records", + b"record A(int a) { A(long a) { this(1) } }\nrecord B(int b) { B(int b) { this.b = b } }\n", + ), + ( + "Bash", + "gate/bash-tests", + b"if [ \"$a\" -eq 1 -a \"$b\" -eq 2 ]; then :; fi\n[ -n \"$a\" -o -n \"$b\" ]\n", + ), +]; + /// Every source `lang` is asked on: its control-flow files (routed by -/// `test_support::control_flow_sources`) and its documentation -/// fixtures, read in place. Without the output submodule — the CI legs -/// that check out no submodules — the documentation fixtures alone, -/// which every language has, and the census says so once. +/// `test_support::control_flow_sources`), its documentation fixtures, +/// read in place, and its [`BYTE_GATE_FIXTURES`]. Without the output +/// submodule — the CI legs that check out no submodules — the in-tree +/// fixtures alone, which every language has, and the census says so +/// once. fn sources_for(lang: LANG) -> Vec { let mut out: Vec = if let Some(files) = control_flow_sources(lang) { files @@ -131,6 +167,23 @@ fn sources_for(lang: LANG) -> Vec { bytes: f.source.into_owned(), }), ); + let tables = crate::roles::tables(); + for (table, fixture, _) in BYTE_GATE_FIXTURES { + assert!( + tables.iter().any(|t| t.name == *table), + "`{fixture}` names `{table}`, which is no table: it would be asked of nothing" + ); + } + let name = tables.iter().find(|t| t.lang == lang).map(|t| t.name); + out.extend( + BYTE_GATE_FIXTURES + .iter() + .filter(|(table, _, _)| Some(*table) == name) + .map(|(_, fixture, bytes)| Source { + name: (*fixture).to_owned(), + bytes: bytes.to_vec(), + }), + ); out } @@ -462,12 +515,6 @@ fn macro_invariants_hold_on_every_candidate() { /// zero and fails. Per owner kind, not per row: a row with two owners /// can lose every positive of one while the other keeps it green. const NO_POSITIVE_IN_CORPUS: &[(&str, &str, &str, &str)] = &[ - ( - "Bash", - "ShortCircuit", - "binary_expression", - "a `binary_expression` owns a short circuit only when it holds `&&` / `||`; none in the fixtures", - ), ( "C", "ShortCircuit", @@ -1460,6 +1507,139 @@ fn no_chain_rows_answer_alike_under_the_empty_chain() { ); } +/// What the byte backstop found across every probed table: the +/// per-gate findings, deduplicated by `(role, kind)` since one +/// byte-reading gate answers on every candidate of its kind. +#[derive(Default)] +struct ByteProbe { + asked: usize, + disagreements: BTreeSet, +} + +impl ByteProbe { + /// Asks every row that owns `node`'s kind through an owner it does + /// not mark `text_gated_by`, with the bytes and with none, then the + /// `opens_space` fold where no marked opener owns the kind. + fn probe<'a>( + &mut self, + table: &LanguageTable, + rows: &[DeclaredRow], + node: &Node<'a>, + code: &[u8], + chain: &[Node<'a>], + ) { + // One chain for both asks, and no `FoldCache` on it: a memo is + // keyed by node, never by buffer, so through the walk's cache + // the byte-less ask would be served what the real bytes stored + // a moment before, and a memoised byte reader would agree with + // itself. + let ancestors = Ancestors::known(chain); + let kind = node.kind_id(); + let mut unmarked_owner = false; + for row in rows { + if !row.owners.contains(&kind) || row.text_gated_owners.contains(&kind) { + continue; + } + unmarked_owner = true; + self.asked += 1; + let real = (row.owns_kind)(kind, node, code, ancestors); + let byteless = (row.owns_kind)(kind, node, &[], ancestors); + if real != byteless { + self.disagreements.insert(format!( + "{} {} on `{}`: owns {real} with the bytes, {byteless} without", + table.name, + row.role, + node.kind() + )); + } + } + // The fold reads every row's `opens` / `opens_by`, so it is + // compared only where no space-opening row marks the node's + // kind: a marked opener reads the bytes by declaration. + let marked_opener = rows.iter().any(|r| { + matches!(r.role, "FuncOpener" | "Container") && r.text_gated_owners.contains(&kind) + }); + if unmarked_owner && !marked_opener { + let real = (table.opens_space)(node, code, ancestors); + let byteless = (table.opens_space)(node, &[], ancestors); + if real != byteless { + self.disagreements.insert(format!( + "{} opens_space on `{}`: {real:?} with the bytes, {byteless:?} without", + table.name, + node.kind() + )); + } + } + } +} + +/// The behavioural backstop for `TEXT_GATED` (#1863): every owner a row +/// does not mark `text_gated_by` answers `owns_kind` the same with the +/// walk's bytes and with `&[]`, on every candidate of the corpus, and +/// so does the table's `opens_space` fold, which `owns_kind` never +/// reaches for an `opens_by` owner. The flag is the author's word — the +/// keyword is the declaration, where `CHAIN_GATED` is held to the fn's +/// signature — so a gate that reads bytes under a plain `gated_by` +/// builds, passes every `!TEXT_GATED` assertion a byte-less forward +/// makes, and answers that forward from an empty slice. +/// `no_chain_rows_answer_alike_under_the_empty_chain` is the same +/// backstop on the chain axis. +/// +/// Per owner, not per row (`TEXT_GATED_OWNERS`): a row one owner marks +/// is still asked through its others. What it sees is an owner whose +/// answer *moves* without the bytes on some candidate the corpus +/// spells; a byte reader no fixture can move — a gate comparing two +/// spellings that happen to agree when both are empty — is not seen, +/// nor an owner kind with no occurrence (`make role-coverage-claimed`). +/// It asks ownership and the space fold, which is what `TEXT_GATED` +/// claims: a `callable_when`, a `pays_itself_when` and a payer's gate +/// are outside the flag and outside this. +/// +/// Verified to discriminate by re-keywording three gates to a plain +/// `gated_by` (recorded on #1863): Java's `opens_record_header`, whose +/// answer moves on the same-arity alternative constructor of +/// `gate/java-records`; Bash's `comparison_operator`, on the `-a` of +/// `gate/bash-tests`; and Elixir's `control_branch`, whose target read +/// the walk memoises per visited node. +#[test] +fn unmarked_owners_answer_alike_without_the_bytes() { + let mut probe = ByteProbe::default(); + for table in crate::roles::tables() { + if !table.lang.is_enabled() { + continue; + } + let rows: Vec = (table.rows)() + .iter() + .filter_map(RowView::declared) + .copied() + .collect(); + for source in sources_for(table.lang) { + let code = source.bytes.as_slice(); + with_code_tag!(table.lang, |C| { + for_each_node_with_chain::(code, |node, chain| { + if node.start_byte() != node.end_byte() { + probe.probe(table, &rows, node, code, chain); + } + }); + }); + } + } + assert!( + probe.asked > 0, + "no candidate of an owner without a text gate in the corpus" + ); + assert!( + probe.disagreements.is_empty(), + "an owner not marked `text_gated_by` answers differently without the bytes — \ + its gate reads them under the wrong keyword:\n{}", + probe + .disagreements + .into_iter() + .collect::>() + .join("\n") + ); +} + /// The `Closure` rows read no bytes in any language, which is what /// lets every `Checker::is_closure` forward `&[]` — the pin the 19 /// forwards lack at build time, held here for every table at once. diff --git a/big-code-analysis-ast/src/roles/mod.rs b/big-code-analysis-ast/src/roles/mod.rs index c561ac9d9..428960d45 100644 --- a/big-code-analysis-ast/src/roles/mod.rs +++ b/big-code-analysis-ast/src/roles/mod.rs @@ -356,7 +356,11 @@ //! `text_gated_by` is carried as `gated_by`, and a gate that reads //! bytes under a plain `gated_by`, `callable_when`, `pays_itself_when` //! or `opens_by` is not flagged — the keyword is the declaration, and -//! a gate named under the wrong keyword is the author's error. +//! a gate named under the wrong keyword is the author's error. The +//! derived suite's `unmarked_owners_answer_alike_without_the_bytes` +//! is the behavioural backstop for the owner and `opens_by` cases +//! (#1863): it asks every owner the row does not mark, with the bytes +//! and without. //! - `CHAIN_GATED`: whether any owner carries a `gated_by` / //! `text_gated_by` gate or an `opens_by` fn *without* `no_chain` //! (#1793), or an `under` / `not_under` list, so a forward that @@ -387,7 +391,8 @@ //! //! Every production predicate and constant a table emits is `pub` //! (the test-support enumeration, `canonical()` and the per-row -//! `MODE` / `HOLDS_PAYER` are not): the root crate's metric +//! `MODE` / `HOLDS_PAYER` / `TEXT_GATED_OWNERS` are not): the root +//! crate's metric //! dispatchers are consumers too (`abc`, `cyclomatic`, `cognitive` read //! the `Comparison` and `ShortCircuit` rows since #1694), and they reach //! a row as `big_code_analysis_ast::roles::::`. The AST @@ -571,11 +576,20 @@ //! compared nor counted, and `make role-coverage-claimed` lists the //! claimed kinds with no corpus occurrence), a `callable_when` or payer //! gate (no chain-less forward reads them), and a text gate under the -//! wrong keyword. So the derived suite still -//! compares every forward on every corpus candidate, and a known -//! disagreement is a named -//! `KNOWN_DISAGREEMENTS` entry that must still occur (a stale entry -//! fails too), never a tolerance. The check, when adding a chain- or +//! wrong keyword whose answer no corpus candidate moves. The byte axis +//! has the same kind of backstop as the chain axis since #1863: +//! `unmarked_owners_answer_alike_without_the_bytes` asks every owner a +//! row does not mark `text_gated_by`, and the `opens_space` fold, with +//! the walk's bytes and with `&[]`. It found the Tcl family's +//! `is_braced_literal` and Bash's two `test_operator` owner gates +//! declared `gated_by`. It sees a gate only where the answer *moves*: +//! a comparison of two spellings agrees with itself when both are +//! empty, so the shape that separates them has to be in the corpus +//! (`BYTE_GATE_FIXTURES` holds the ones no other source spells). So +//! the derived suite still compares every forward on every corpus +//! candidate, and a known disagreement is a named `KNOWN_DISAGREEMENTS` +//! entry that must still occur (a stale entry fails too), never a +//! tolerance. The check, when adding a chain- or //! byte-reading gate to a row: list every forward of that row //! (`rg 'Ancestors::known\(&\[\]\)'` and the `&[]` byte arguments), //! decide for each whether the dropped input changes the answer, and @@ -862,6 +876,15 @@ pub const fn some_kinds(marked: &[Option]) -> [u16; N] { kinds } +/// `Some(kind)` where `marked`, for a per-owner list built from a +/// detector that answers `true` or `false` (`TEXT_GATED_OWNERS`). +#[cfg(any(test, feature = "test-support"))] +#[doc(hidden)] +#[must_use] +pub const fn marked_kind(marked: bool, kind: u16) -> Option { + if marked { Some(kind) } else { None } +} + /// The kinds of an `EXCLUDED` list, for the same checks. #[doc(hidden)] #[must_use] @@ -916,6 +939,8 @@ pub struct DeclaredRow { pub excluded: &'static [(u16, &'static str)], /// `TEXT_GATED`. pub text_gated: bool, + /// `TEXT_GATED_OWNERS`. + pub text_gated_owners: &'static [u16], /// `CHAIN_GATED`. pub chain_gated: bool, /// `PAYS_NEVER`. @@ -940,9 +965,10 @@ pub struct DeclaredRow { // `cfg(test)`, not `test-support`: nothing the feature exports reaches // it — `pub(crate)`, and no `pub` item calls it — so under the feature -// alone it is dead. `rows()`, `view()`, `MODE` and `HOLDS_PAYER` are -// `pub(crate)` under the feature too, and live, because `tables()` -// reaches them; that reachability is the test, not the visibility. +// alone it is dead. `rows()`, `view()`, `MODE`, `HOLDS_PAYER` and +// `TEXT_GATED_OWNERS` are `pub(crate)` under the feature too, and live, +// because `tables()` reaches them; that reachability is the test, not +// the visibility. #[cfg(test)] impl DeclaredRow { /// Every kind the row names as owning, paying or paying at the @@ -1698,6 +1724,22 @@ macro_rules! role_table { $crate::roles::some_kinds::<{ $crate::roles::count_some(MARKED) }>(MARKED) }; + /// Every owner marked `text_gated_by`: [`TEXT_GATED`] per + /// owner. The derived byte backstop asks every *other* owner + /// with and without the bytes, so a gate that reads them + /// under a plain `gated_by` is seen on a row another owner + /// already marks (#1863). + #[cfg(any(test, feature = "test-support"))] + pub(crate) const TEXT_GATED_OWNERS: &[u16] = &{ + const MARKED: &[Option] = &[ $( $crate::roles::marked_kind( + $crate::role_table!( + @scan text_gated_kind [] [] $owner [] [] [] [] $($($owner_attr)*)? + ), + $lang::$owner as u16, + ), )* ]; + $crate::roles::some_kinds::<{ $crate::roles::count_some(MARKED) }>(MARKED) + }; + /// Whether `node` is a `callable` owner of the construct — a /// named function, for `Checker::is_func_with_code` — under /// its gate. @@ -1791,6 +1833,7 @@ macro_rules! role_table { wraps: WRAPS, excluded: EXCLUDED, text_gated: TEXT_GATED, + text_gated_owners: TEXT_GATED_OWNERS, chain_gated: CHAIN_GATED, pays_never: PAYS_NEVER, mode: MODE, @@ -3997,6 +4040,70 @@ mod tests { ); } + /// `TEXT_GATED_OWNERS` names every `text_gated_by` owner in each + /// position the attribute list can put the word — alone, after + /// `holds_payer`, after an `opens` and a `callable`, and marked + /// `no_chain` — and none whose gate is a plain `gated_by`, a + /// `callable_when` or absent. The derived byte backstop asks every + /// owner *not* listed here, so an owner wrongly listed is one it + /// stops asking, and a row wrongly empty is one it asks of a + /// declared byte reader (#1863). + #[test] + fn text_gated_owners_lists_the_marked_owners_in_every_spelling() { + assert_eq!( + dsl_gates::member::TEXT_GATED_OWNERS, + &[Java::FieldDeclaration as u16], + "alone" + ); + assert_eq!( + dsl_gates::call::TEXT_GATED_OWNERS, + &[Java::MethodInvocation as u16], + "after holds_payer" + ); + assert_eq!( + dsl_gates::func_opener::TEXT_GATED_OWNERS, + &[Java::RecordDeclaration as u16], + "one marked owner among kind-only, gated and callable_when ones" + ); + assert_eq!( + dsl_gates::short_circuit::TEXT_GATED_OWNERS, + &[] as &[u16], + "gated_by, not text" + ); + assert_eq!( + dsl_no_chain::catch::TEXT_GATED_OWNERS, + &[Java::CatchClause as u16], + "text_gated_by … no_chain" + ); + assert_eq!( + dsl_no_chain::exit::TEXT_GATED_OWNERS, + &[] as &[u16], + "gated_by … no_chain" + ); + // The flag is the list's emptiness, on every production row. + for table in super::tables() { + for row in (table.rows)() { + if let Some(row) = row.declared() { + assert_eq!( + row.text_gated, + !row.text_gated_owners.is_empty(), + "{} {}", + table.name, + row.role + ); + assert!( + row.text_gated_owners + .iter() + .all(|kind| row.owners.contains(kind)), + "{} {}: a listed kind is no owner", + table.name, + row.role + ); + } + } + } + } + // `opens_by f`: one kind, two space kinds, by what `f` reads. #[cfg(feature = "java")] #[test] diff --git a/big-code-analysis-ast/src/roles/tcl_family.rs b/big-code-analysis-ast/src/roles/tcl_family.rs index 321ffdf0b..a57c0b08e 100644 --- a/big-code-analysis-ast/src/roles/tcl_family.rs +++ b/big-code-analysis-ast/src/roles/tcl_family.rs @@ -40,11 +40,13 @@ macro_rules! tcl_family_short_circuit_payers { /// `is_braced_literal`, which each dialect emits over its own /// `BracedWordKinds` through `Getter::is_braced_script_word` — the one /// reader Halstead, `find string` and the dump flattening share (#1382). +/// The enclosing command is told by its leading word's bytes, so the +/// gate is `text_gated_by` (#1863). macro_rules! tcl_family_strings { (@splice $cont:tt [$($acc:tt)*] $($rest:tt)*) => { $crate::role_table!(@owners $cont [$($acc)* QuotedWord, - BracedWord(gated_by is_braced_literal), + BracedWord(text_gated_by is_braced_literal), BracedWordSimple, ] $($rest)*); }; diff --git a/docs/development/lessons_learned.md b/docs/development/lessons_learned.md index 4915fb6cf..0cf58f7b6 100644 --- a/docs/development/lessons_learned.md +++ b/docs/development/lessons_learned.md @@ -5345,7 +5345,8 @@ by a behavioural check. Before declaring a gate, list what it reads and declare each axis it uses; then confirm the derived suite has a backstop for that axis. The chain axis has `no_chain_rows_answer_alike_under_the_empty_chain`; the byte axis has -none (#1863). +`unmarked_owners_answer_alike_without_the_bytes` since #1863, which +sees a gate only on a fixture whose answer moves without the bytes. Handed no bytes, a gate that compares spellings sees every spelling as the empty string and answers *equal*: a confident wrong `true` that From 4bf33be81368c2335666aae261ed33ceafbe09a1 Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Wed, 11 Nov 2026 16:41:56 -0800 Subject: [PATCH 04/21] docs(lessons): bring lesson 120 up to the removal of byte-less is_func The example's last sentence described the #1862 state as current: both checkers overriding `is_func_with_code` and a byte-less `is_func` forwarding a known-empty chain. #1863 removed that method. The sentence now reads as history and names what replaced it. Found by the checkpoint review of steps 1 and 2. Refs #1863 --- docs/development/lessons_learned.md | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/docs/development/lessons_learned.md b/docs/development/lessons_learned.md index 0cf58f7b6..8148683d7 100644 --- a/docs/development/lessons_learned.md +++ b/docs/development/lessons_learned.md @@ -5365,9 +5365,12 @@ reported the header's `nargs` as 0. A fixture with that exact record existed and passed: it counted the record's function *spaces*, which the walk opened through the with-code path, not the header's `nargs`, which the byte-less path zeroed. A reviewer reading the gate found it. -The row is `text_gated_by` now, both checkers override -`is_func_with_code`, and this gate's byte-less `is_func` forwards a -known-empty chain so the header answers `false` there by design. +The #1862 fix made the row `text_gated_by`, had both checkers override +`is_func_with_code`, and had the byte-less `is_func` forward a +known-empty chain so the header answered `false` there by design. The +follow-up (#1863) removed `is_func` and made `is_func_with_code` a +required `Checker` method, so no language can answer the callable test +by forwarding to a spelling that drops the bytes. --- From ee68d23fe79194664c4d2cd8cc2d7e88d6976f70 Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Wed, 11 Nov 2026 16:51:07 -0800 Subject: [PATCH 05/21] refactor(roles): name a record's header once, beside the Java and Groovy tables "The header is the record's `parameters` / `components` field" was spelled four times: in the `FuncOpener` gate, in the getter's naming closure as a kind pair, in Java's `NArgs::params_owner`, and as a string argument to `record_header_is_a_method` in `npm`. `roles::java::record_header` and `roles::groovy::record_header` project the list from a record declaration and answer `None` for any other node, as `is_switch_body_kind` names the `Switch` owner's body. The gate, the naming helper, `nargs` and `npm` read them. `func_space_name_from_owner` takes the list and its parent as nodes, so a language can match by identity or, as C# does, by kind. C# is left as it is: a primary constructor's list sits in no field, the pinned grammar admits more than one `parameter_list` under a type declaration, and the row's `under` list already is the relation. An identity projection would rename the second list's space. No metric value, space or name moves. One row test per language pins the projection against the row. The baseline records `roles/mod.rs` `sloc` and adds `nargs.rs` `ploc` at 525, three lines over the soft limit. Refs #1863 --- .bca-baseline.toml | 8 +- big-code-analysis-ast/src/getter.rs | 10 +- big-code-analysis-ast/src/getter/csharp.rs | 4 +- big-code-analysis-ast/src/getter/groovy.rs | 5 +- big-code-analysis-ast/src/getter/java.rs | 4 +- big-code-analysis-ast/src/roles/groovy.rs | 28 +++-- big-code-analysis-ast/src/roles/java.rs | 24 +++- big-code-analysis-ast/src/roles/mod.rs | 10 +- .../src/roles/space_tree_tests.rs | 107 ++++++++++++++++++ src/metrics/nargs.rs | 9 +- src/metrics/npm.rs | 35 +++--- src/metrics/npm/groovy.rs | 7 +- src/metrics/npm/java.rs | 2 +- 13 files changed, 206 insertions(+), 47 deletions(-) diff --git a/.bca-baseline.toml b/.bca-baseline.toml index e67594ff4..aafb8af69 100644 --- a/.bca-baseline.toml +++ b/.bca-baseline.toml @@ -365,7 +365,7 @@ value = 906.0 path = "big-code-analysis-ast/src/roles/mod.rs" qualified = "" metric = "loc.sloc" -value = 2314.0 +value = 2322.0 [[entry]] path = "big-code-analysis-ast/src/tools.rs" @@ -1261,6 +1261,12 @@ qualified = "Mi::compute" metric = "nargs" value = 5.0 +[[entry]] +path = "src/metrics/nargs.rs" +qualified = "" +metric = "loc.ploc" +value = 525.0 + [[entry]] path = "src/metrics/npa/php.rs" qualified = "PhpCode::compute" diff --git a/big-code-analysis-ast/src/getter.rs b/big-code-analysis-ast/src/getter.rs index df745b3a3..e97bde63d 100644 --- a/big-code-analysis-ast/src/getter.rs +++ b/big-code-analysis-ast/src/getter.rs @@ -254,19 +254,19 @@ pub fn default_func_space_name<'a, 'tree>( /// the list carries no `name` field, so it takes its owner's, as a /// constructor's `name` already spells the type it constructs, where /// the default would read `` and `bca check` a closure. -/// `owned_list` reads the `(list kind, parent kind)` pair and says -/// whether the parent is such an owner; a method's list sits under a -/// method and keeps the default. +/// `owned_list` reads the list and its parent and says whether the +/// parent is such an owner; a method's list sits under a method and +/// keeps the default. #[must_use] pub(crate) fn func_space_name_from_owner<'a, 'tree>( node: &Node<'tree>, code: &'a [u8], ancestors: Ancestors<'tree, '_>, - owned_list: impl FnOnce(u16, u16) -> bool, + owned_list: impl FnOnce(&Node<'tree>, &Node<'tree>) -> bool, ) -> Option<&'a str> { let named = ancestors .parent(node) - .filter(|owner| owned_list(node.kind_id(), owner.kind_id())) + .filter(|owner| owned_list(node, owner)) .unwrap_or(*node); default_func_space_name(&named, code, ancestors) } diff --git a/big-code-analysis-ast/src/getter/csharp.rs b/big-code-analysis-ast/src/getter/csharp.rs index 2f541dea0..6e981829a 100644 --- a/big-code-analysis-ast/src/getter/csharp.rs +++ b/big-code-analysis-ast/src/getter/csharp.rs @@ -124,8 +124,8 @@ impl Getter for CsharpCode { // The `Container` row carries no gate, so its kind table is the // whole answer. crate::getter::func_space_name_from_owner(node, code, ancestors, |list, owner| { - list == Csharp::ParameterList as u16 - && crate::roles::csharp::container::lists_kind(owner) + list.kind_id() == Csharp::ParameterList as u16 + && crate::roles::csharp::container::lists_kind(owner.kind_id()) }) } diff --git a/big-code-analysis-ast/src/getter/groovy.rs b/big-code-analysis-ast/src/getter/groovy.rs index 1634aca02..e35c2cf6c 100644 --- a/big-code-analysis-ast/src/getter/groovy.rs +++ b/big-code-analysis-ast/src/getter/groovy.rs @@ -58,10 +58,9 @@ impl Getter for GroovyCode { return Some(""); } // A record's header takes the record's name (#1842). - // role-bypass: allow(FuncOpener, Container) — a naming rule over the - // list and the record it names, not whether either opens a space crate::getter::func_space_name_from_owner(node, code, ancestors, |list, owner| { - list == Groovy::RecordComponents as u16 && owner == Groovy::RecordDeclaration as u16 + crate::roles::groovy::record_header(owner) + .is_some_and(|header| header.id() == list.id()) }) } diff --git a/big-code-analysis-ast/src/getter/java.rs b/big-code-analysis-ast/src/getter/java.rs index 3b875a755..3d0fa8715 100644 --- a/big-code-analysis-ast/src/getter/java.rs +++ b/big-code-analysis-ast/src/getter/java.rs @@ -43,10 +43,8 @@ impl Getter for JavaCode { return Some(""); } // A record's header takes the record's name (#1842). - // role-bypass: allow(FuncOpener, Container) — a naming rule over the - // list and the record it names, not whether either opens a space crate::getter::func_space_name_from_owner(node, code, ancestors, |list, owner| { - list == Java::FormalParameters as u16 && owner == Java::RecordDeclaration as u16 + crate::roles::java::record_header(owner).is_some_and(|header| header.id() == list.id()) }) } diff --git a/big-code-analysis-ast/src/roles/groovy.rs b/big-code-analysis-ast/src/roles/groovy.rs index 474fb085c..fbfc96abe 100644 --- a/big-code-analysis-ast/src/roles/groovy.rs +++ b/big-code-analysis-ast/src/roles/groovy.rs @@ -146,12 +146,26 @@ fn is_record_canonical_constructor( declared.eq(components) } +/// A record's header: the component list in the `components` field of +/// a `record_declaration`, a sibling of its `class_body` — the node the +/// `FuncOpener` row opens the implicit canonical constructor's space on +/// (#1842), and Java's twin (`roles/java.rs`, the rationale there). +/// `None` for any other node. Held once for the row's gate and for the +/// consumers that step between a record and its header (#1863); pinned +/// by `record_header_is_the_records_own_list`. +#[inline] +#[must_use] +pub fn record_header<'a>(record: &Node<'a>) -> Option> { + (record.kind_id() == Groovy::RecordDeclaration as u16) + .then(|| record.child_by_field_name("components")) + .flatten() +} + /// Whether a `record_components` list is a record's header in a record /// that declares no canonical constructor, so the header stands for -/// the implicitly declared one (#1842): the `components` field of a -/// `record_declaration`, a sibling of its `class_body`, checked by -/// field as Java's is so a grammar bump that reuses the kind elsewhere -/// under the record opens nothing there. A written canonical +/// the implicitly declared one (#1842): the record's [`record_header`], +/// checked by field as Java's is so a grammar bump that reuses the kind +/// elsewhere under the record opens nothing there. A written canonical /// constructor ([`is_record_canonical_constructor`]) owns the /// components instead; a non-canonical one is a callable of its own /// and leaves the header open. The gate reads the record's body, so it @@ -162,11 +176,7 @@ fn opens_record_header<'a>(node: &Node<'a>, code: &[u8], ancestors: Ancestors<'a let Some(record) = ancestors.parent(node) else { return false; }; - if record.kind_id() != Groovy::RecordDeclaration as u16 - || record - .child_by_field_name("components") - .is_none_or(|p| p.id() != node.id()) - { + if record_header(&record).is_none_or(|header| header.id() != node.id()) { return false; } let Some(body) = record.child_by_field_name("body") else { diff --git a/big-code-analysis-ast/src/roles/java.rs b/big-code-analysis-ast/src/roles/java.rs index 4f9277e00..b86ddebae 100644 --- a/big-code-analysis-ast/src/roles/java.rs +++ b/big-code-analysis-ast/src/roles/java.rs @@ -165,11 +165,7 @@ fn opens_record_header<'a>(node: &Node<'a>, code: &[u8], ancestors: Ancestors<'a let Some(record) = ancestors.parent(node) else { return false; }; - if record.kind_id() != Java::RecordDeclaration as u16 - || record - .child_by_field_name("parameters") - .is_none_or(|p| p.id() != node.id()) - { + if record_header(&record).is_none_or(|header| header.id() != node.id()) { return false; } let Some(body) = record.child_by_field_name("body") else { @@ -184,6 +180,24 @@ fn opens_record_header<'a>(node: &Node<'a>, code: &[u8], ancestors: Ancestors<'a }) } +/// A record's header: the component list in the `parameters` field of +/// a `record_declaration`, a sibling of its `class_body` — the node the +/// `FuncOpener` row opens the implicit canonical constructor's space on +/// (#1842). `None` for any other node: every callable holds its own +/// list in a field of the same name, so the record's kind is part of +/// the relation. A structural fact about the construct the rows +/// recognise, held once for the row's gate and for the consumers that +/// step between a record and its header — the space's name, `nargs`' +/// parameter owner, `npm`'s method count (#1863); pinned by +/// `record_header_is_the_records_own_list`. +#[inline] +#[must_use] +pub fn record_header<'a>(record: &Node<'a>) -> Option> { + (record.kind_id() == Java::RecordDeclaration as u16) + .then(|| record.child_by_field_name("parameters")) + .flatten() +} + /// The container a `switch` nests its arms in: the `switch_block`, the /// `Switch` owner's child — a structural fact about the construct the /// row recognises, pinned by diff --git a/big-code-analysis-ast/src/roles/mod.rs b/big-code-analysis-ast/src/roles/mod.rs index 428960d45..1cd1efaae 100644 --- a/big-code-analysis-ast/src/roles/mod.rs +++ b/big-code-analysis-ast/src/roles/mod.rs @@ -457,7 +457,15 @@ //! form: `is_preproc_conditional_kind` (`roles/c_family.rs`) names the //! C-family `DocTarget` row's conditional owners, held to their names //! over every runtime id by `_old_names_are_the_conditional_kinds` -//! (`roles/doc_tests/doxygen.rs`, #1795). +//! (`roles/doc_tests/doxygen.rs`, #1795). So does the step from a +//! declaration to the child a row gates: `record_header` +//! (`roles/java.rs`, `roles/groovy.rs`) projects a record's component +//! list, read by the `FuncOpener` gate and by the getter's naming, +//! `nargs` and `npm`, where each had spelled the field name or the +//! kind pair itself (#1863). C#'s primary constructor has no such +//! projection: its list sits in no field, the grammar admits more +//! than one under a type declaration, and the row's `under` list is +//! the whole relation. //! - **A kind a row claims is not restated as classification inside the //! consumer boundary** — the per-language dispatch files, their //! dispatcher modules and macros (`utils/check-role-bypass.py`, diff --git a/big-code-analysis-ast/src/roles/space_tree_tests.rs b/big-code-analysis-ast/src/roles/space_tree_tests.rs index aede244d5..ba2dc273c 100644 --- a/big-code-analysis-ast/src/roles/space_tree_tests.rs +++ b/big-code-analysis-ast/src/roles/space_tree_tests.rs @@ -1300,6 +1300,113 @@ fn plain(text: &str, name: &'static str) -> ListAnswer { ) } +/// What a language's `record_header` projection and its `FuncOpener` +/// row say of every list of `source`: the declarations the projection +/// answers for, by kind, and per list its text, whether it is its +/// parent's projected header, and whether the row owns it there. +#[cfg(any(feature = "java", feature = "groovy"))] +type HeaderAnswers = (Vec, Vec<(String, bool, bool)>); + +#[cfg(any(feature = "java", feature = "groovy"))] +fn header_answers( + source: &'static [u8], + list_kinds: &[&str], + record_header: for<'a> fn(&Node<'a>) -> Option>, + opener_owns: crate::roles::RowPred, +) -> HeaderAnswers { + let mut projecting = Vec::new(); + let mut lists = Vec::new(); + for_each_node_with_chain::(source, |node, chain| { + if let Some(header) = record_header(node) { + assert!( + node.children().any(|child| child.id() == header.id()), + "the projection is the declaration's own child" + ); + projecting.push(node.kind().to_owned()); + } + if !list_kinds.contains(&node.kind()) { + return; + } + let ancestors = Ancestors::known(chain); + let is_header = ancestors + .parent(node) + .and_then(|owner| record_header(&owner)) + .is_some_and(|header| header.id() == node.id()); + let owned = opener_owns(node, source, ancestors); + assert!( + is_header || !owned, + "the row owns a `{}` that is no record's header", + node.kind() + ); + lists.push(( + node.utf8_text(source).unwrap_or("?").to_owned(), + is_header, + owned, + )); + }); + (projecting, lists) +} + +/// Java's `record_header` projects a record's own component list and +/// nothing else: a method's and a constructor's lists sit in a field of +/// the same name and are no header, which is the record-kind half of +/// the relation. The `FuncOpener` row owns a list only where it is that +/// projection — `Q`'s, whose body writes no constructor; `R`'s compact +/// constructor closes its header — so the gate, the space's name, +/// `nargs` and `npm` read one definition of "the header" (#1863). +#[cfg(feature = "java")] +#[test] +fn java_record_header_is_the_records_own_list() { + use crate::roles::java::{func_opener, record_header}; + let source = + b"record R(int x) { R { } void m(int y) { } }\nrecord Q(int q) { }\nclass C { C(int z) { } }\n"; + let (projecting, lists) = header_answers::( + source, + &["formal_parameters"], + record_header, + func_opener::owns, + ); + assert_eq!(projecting, ["record_declaration", "record_declaration"]); + assert_eq!( + lists, + [ + ("(int x)".to_owned(), true, false), + ("(int y)".to_owned(), false, false), + ("(int q)".to_owned(), true, true), + ("(int z)".to_owned(), false, false), + ] + ); +} + +/// Groovy's twin: the header is the `components` field, a kind of its +/// own, so a method's `formal_parameters` could not be mistaken for one +/// and the record-kind check guards only a grammar that reuses the +/// field name. `R`'s header is open; `B` writes its canonical +/// constructor. +#[cfg(feature = "groovy")] +#[test] +fn groovy_record_header_is_the_records_own_list() { + use crate::roles::groovy::{func_opener, record_header}; + let source = b"record R(int x) { void m(int y) { } }\nrecord B(int b) { B(int b) { this.b = b } }\nclass C { C(int z) { } }\n"; + let (projecting, lists) = header_answers::( + source, + &["record_components", "formal_parameters"], + record_header, + func_opener::owns, + ); + assert_eq!(projecting, ["record_declaration", "record_declaration"]); + assert_eq!( + lists, + [ + ("(int x)".to_owned(), true, true), + ("(int y)".to_owned(), false, false), + ("(int b)".to_owned(), true, false), + ("(int b)".to_owned(), false, false), + ("(int z)".to_owned(), false, false), + ] + ); +} + /// A Java record's header opens the implicit canonical constructor's /// space, named after the record, where the body writes none (#1842) — /// which the byte-less spellings cannot see, as C#'s primary constructor diff --git a/src/metrics/nargs.rs b/src/metrics/nargs.rs index a9c8c13c3..c5e23aace 100644 --- a/src/metrics/nargs.rs +++ b/src/metrics/nargs.rs @@ -851,8 +851,8 @@ impl NArgs for CsharpCode { // itself where the body writes neither a compact nor a normal canonical // constructor (#1842, revisiting #1160's "declared code rather than // generated code": the component list *is* declared, as a C# positional -// record's is — #1828), so the list's owner is its parent, the record. -// The row's gate keeps the count to one owner: with a compact +// record's is — #1828), so the list's owner is the record whose +// `record_header` it is (`roles/java.rs`). The row's gate keeps the count to one owner: with a compact // constructor the header opens nothing and the redirect counts the // components there; with neither the header is the callable. A // non-canonical constructor is a callable of its own, owns its own @@ -860,7 +860,10 @@ impl NArgs for CsharpCode { impl NArgs for JavaCode { fn params_owner<'tree>(node: &Node<'tree>, ancestors: Ancestors<'tree, '_>) -> Node<'tree> { let record = match node.kind_id().into() { - Java::FormalParameters => ancestors.parent(node), + Java::FormalParameters => ancestors.parent(node).filter(|record| { + crate::roles::java::record_header(record) + .is_some_and(|header| header.id() == node.id()) + }), Java::CompactConstructorDeclaration => ancestors .iter(node) .nth(1) diff --git a/src/metrics/npm.rs b/src/metrics/npm.rs index 79a75ecdd..ea2ecbaec 100644 --- a/src/metrics/npm.rs +++ b/src/metrics/npm.rs @@ -264,21 +264,23 @@ fn direct_child_funcs<'a, 'c, C: Checker>( .filter(move |child| C::is_func_with_code(child, code, members)) } -/// Whether a record declaration's header — the component list held in -/// its `field`, a sibling of the body and so never a body member — is -/// the record's implicit canonical constructor, a method the body scan -/// cannot see (#1842; Java and Groovy). The question is the `FuncOpener` -/// row's, asked of the list under the record's own child chain so the -/// row's gate reads the body, and the answer is read here while the walk -/// is still on the class space: the list's own function space opens one -/// node later. +/// Whether a record declaration's header — the component list +/// `record_header` projects, a sibling of the body and so never a body +/// member — is the record's implicit canonical constructor, a method +/// the body scan cannot see (#1842; Java and Groovy). `record_header` +/// is the language's projection beside its role table +/// (`roles::java::record_header`, `roles::groovy::record_header`). The +/// question is the `FuncOpener` row's, asked of the list under the +/// record's own child chain so the row's gate reads the body, and the +/// answer is read here while the walk is still on the class space: the +/// list's own function space opens one node later. fn record_header_is_a_method<'a, C: Checker>( record: &Node<'a>, - field: &str, + record_header: impl FnOnce(&Node<'a>) -> Option>, code: &[u8], ancestors: Ancestors<'a, '_>, ) -> bool { - record.child_by_field_name(field).is_some_and(|header| { + record_header(record).is_some_and(|header| { C::is_func_with_code(&header, code, ancestors.of_children(record).get()) }) } @@ -331,7 +333,9 @@ where // `impl_npa_java_like!` in `npa.rs`; issue #280). Groovy has since moved // to a hand-written impl — the dekobon grammar flattens modifiers, see // `npm/groovy.rs` — so this expands against Java alone. It is kept in -// macro form because the next Java-shaped grammar can reuse it. +// macro form because the next Java-shaped grammar can reuse it. `$roles` +// is the language's module under `crate::roles`, whose `record_header` +// projects a record's component list. // // `ClassBody` covers class and record explicit bodies; // `EnumBodyDeclarations` is the optional declarations block inside @@ -343,7 +347,7 @@ where // `AnnotationTypeBody`: annotation type elements are abstract public // methods at the bytecode level and obey the same rule. macro_rules! impl_npm_java_like { - ($code:ty, $lang:ident) => { + ($code:ty, $lang:ident, $roles:ident) => { impl Npm for $code { fn compute<'a>( node: &Node<'a>, @@ -383,7 +387,12 @@ macro_rules! impl_npm_java_like { // the record to the list the `FuncOpener` row then judges, // not whether the record opens a space RecordDeclaration => { - if record_header_is_a_method::(node, "parameters", code, ancestors) { + if record_header_is_a_method::( + node, + crate::roles::$roles::record_header, + code, + ancestors, + ) { stats.class_nm += 1; let interface_member = ancestors.parent(node).is_some_and(|body| { matches!(body.kind_id().into(), InterfaceBody | AnnotationTypeBody) diff --git a/src/metrics/npm/groovy.rs b/src/metrics/npm/groovy.rs index 93e67aa14..ca6f3ce99 100644 --- a/src/metrics/npm/groovy.rs +++ b/src/metrics/npm/groovy.rs @@ -35,7 +35,12 @@ impl Npm for GroovyCode { // record to the list the `FuncOpener` row then judges, not // whether the record opens a space RecordDeclaration - if record_header_is_a_method::(node, "components", code, ancestors) => + if record_header_is_a_method::( + node, + crate::roles::groovy::record_header, + code, + ancestors, + ) => { stats.class_nm += 1; stats.class_npm += usize::from(groovy_record_is_public(node, ancestors)); diff --git a/src/metrics/npm/java.rs b/src/metrics/npm/java.rs index 98675f927..1be4d14bb 100644 --- a/src/metrics/npm/java.rs +++ b/src/metrics/npm/java.rs @@ -8,4 +8,4 @@ use super::*; -impl_npm_java_like!(JavaCode, Java); +impl_npm_java_like!(JavaCode, Java, java); From 4c1f571772888d9ddd45a9098bbf187af63e47d1 Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Wed, 11 Nov 2026 17:20:33 -0800 Subject: [PATCH 06/21] perf(roles): read a record header's types once per scan, and probe the gate The record-header gate (#1842) scans a record's body for a canonical constructor and tells one from an alternative by its parameter types. It re-spelled the header's component types for every constructor it compared. `opens_record_header` now builds them once, on the first constructor it meets, for Java and Groovy alike. The comparison is the same pairwise equality with the same arity rule; two rows pin a constructor that runs past the components and one that stops short. No probe rendered a record. `nargs/java-record-alternative-ctors` and its Groovy twin render one record of ten components with `width` alternative constructors whose first nine types match, the most a constructor can cost. Both fit 1.01. With the gate asked once per constructor instead, one walk of 2 000 constructors took 47 s (Java) and 49 s (Groovy) against 32 ms and 26 ms, and the gate abandons both probes over the per-walk budget. Reading the types once took the same top rung from 44 ms to 29 ms for Java and from 35 ms to 21 ms for Groovy on a warm tree. The issue's other two optional changes are not made: an arity pass would either change answers on recovery input or repeat the filter, and a per-record memo adds walk state for a constant factor on a gate that costs microseconds on a real record. Measured on a host that was not idle; the numbers and commands are on the issue. Refs #1863 --- big-code-analysis-ast/src/roles/groovy.rs | 31 +++--- big-code-analysis-ast/src/roles/java.rs | 29 +++--- big-code-analysis-bench/src/shapes.rs | 111 +++++++++++++++++++++- docs/development/benchmarking.md | 34 +++++++ src/metrics/nargs.rs | 19 +++- 5 files changed, 198 insertions(+), 26 deletions(-) diff --git a/big-code-analysis-ast/src/roles/groovy.rs b/big-code-analysis-ast/src/roles/groovy.rs index fbfc96abe..27ed9f9ac 100644 --- a/big-code-analysis-ast/src/roles/groovy.rs +++ b/big-code-analysis-ast/src/roles/groovy.rs @@ -97,8 +97,10 @@ fn groovy_parameter_type(param: &Node<'_>, code: &[u8]) -> Option> { /// Whether `ctor`, a `constructor_declaration` in `record`'s body, /// declares the record's canonical constructor: named after the record, -/// with as many formal parameters as the record `header` has -/// components, each spelling the same type as its component (Java's +/// with as many formal parameters as the record's header has +/// `components` — their types, read once per header by +/// [`opens_record_header`] — each spelling the same type as its +/// component (Java's /// rule, JLS 8.10.4.1 and 8.8, which Groovy records follow). Parameter /// names and annotations do not take part. The same spelling, not the /// same type — the tokens, so a comment inside the type is nothing — @@ -122,7 +124,7 @@ fn groovy_parameter_type(param: &Node<'_>, code: &[u8]) -> Option> { fn is_record_canonical_constructor( ctor: &Node<'_>, record: &Node<'_>, - header: &Node<'_>, + components: &[Option>], code: &[u8], ) -> bool { let (Some(ctor_name), Some(record_name), Some(params)) = ( @@ -135,15 +137,14 @@ fn is_record_canonical_constructor( if node_bytes(&ctor_name, code) != node_bytes(&record_name, code) { return false; } - let declared = params + let mut declared = params .children() .filter(|p| p.kind_id() == Groovy::FormalParameter as u16) .map(|p| groovy_parameter_type(&p, code)); - let components = header - .children() - .filter(|p| p.kind_id() == Groovy::RecordComponent as u16) - .map(|p| groovy_parameter_type(&p, code)); - declared.eq(components) + components + .iter() + .all(|component| declared.next().as_ref() == Some(component)) + && declared.next().is_none() } /// A record's header: the component list in the `components` field of @@ -182,9 +183,17 @@ fn opens_record_header<'a>(node: &Node<'a>, code: &[u8], ancestors: Ancestors<'a let Some(body) = record.child_by_field_name("body") else { return true; }; + let mut components = None; !body.children().any(|member| { - member.kind_id() == Groovy::ConstructorDeclaration as u16 - && is_record_canonical_constructor(&member, &record, node, code) + member.kind_id() == Groovy::ConstructorDeclaration as u16 && { + let components = components.get_or_insert_with(|| { + node.children() + .filter(|p| p.kind_id() == Groovy::RecordComponent as u16) + .map(|p| groovy_parameter_type(&p, code)) + .collect::>() + }); + is_record_canonical_constructor(&member, &record, components, code) + } }) } diff --git a/big-code-analysis-ast/src/roles/java.rs b/big-code-analysis-ast/src/roles/java.rs index b86ddebae..319b98644 100644 --- a/big-code-analysis-ast/src/roles/java.rs +++ b/big-code-analysis-ast/src/roles/java.rs @@ -105,10 +105,11 @@ fn java_parameter_type(param: &Node<'_>, code: &[u8]) -> Option { /// the check is for a body that holds a constructor named otherwise, /// which tree-sitter-java accepts for the invalid `record R(int a) { /// Q(int a) { } }` as tree-sitter-groovy does), and its formal -/// parameters and the record `header`'s -/// components have the same arity and, pairwise, the same declared type -/// and the same variable-arity-ness. Parameter names and annotations -/// may differ and do not take part. +/// parameters and the record header's `components` — their types, read +/// once per header by [`opens_record_header`] rather than once per +/// constructor — have the same arity and, pairwise, the same declared +/// type and the same variable-arity-ness. Parameter names and +/// annotations may differ and do not take part. /// /// "Same type" is read as the same spelling — the type's tokens, with /// comments and whitespace removed, so `List` and @@ -125,7 +126,7 @@ fn java_parameter_type(param: &Node<'_>, code: &[u8]) -> Option { fn is_record_canonical_constructor( ctor: &Node<'_>, record: &Node<'_>, - header: &Node<'_>, + components: &[ParameterType], code: &[u8], ) -> bool { let (Some(ctor_name), Some(record_name), Some(params)) = ( @@ -138,13 +139,13 @@ fn is_record_canonical_constructor( if node_bytes(&ctor_name, code) != node_bytes(&record_name, code) { return false; } - let declared = params + let mut declared = params .children() .filter_map(|p| java_parameter_type(&p, code)); - let components = header - .children() - .filter_map(|p| java_parameter_type(&p, code)); - declared.eq(components) + components + .iter() + .all(|component| declared.next().as_ref() == Some(component)) + && declared.next().is_none() } /// Whether a `formal_parameters` list is a record's header — the @@ -171,10 +172,16 @@ fn opens_record_header<'a>(node: &Node<'a>, code: &[u8], ancestors: Ancestors<'a let Some(body) = record.child_by_field_name("body") else { return true; }; + let mut components = None; !body.children().any(|member| match member.kind_id().into() { Java::CompactConstructorDeclaration => true, Java::ConstructorDeclaration => { - is_record_canonical_constructor(&member, &record, node, code) + let components = components.get_or_insert_with(|| { + node.children() + .filter_map(|p| java_parameter_type(&p, code)) + .collect::>() + }); + is_record_canonical_constructor(&member, &record, components, code) } _ => false, }) diff --git a/big-code-analysis-bench/src/shapes.rs b/big-code-analysis-bench/src/shapes.rs index d223858d6..716ccff13 100644 --- a/big-code-analysis-bench/src/shapes.rs +++ b/big-code-analysis-bench/src/shapes.rs @@ -1013,6 +1013,37 @@ pub fn nested_classes_with_method(depth: usize) -> String { ) } +/// How many alternative constructors [`record_alternative_ctors`] +/// renders beyond its `width`: the header's list is ten components and +/// their commas, 21 children, so the body needs more than that at the +/// smallest size `shapes_widen_without_deepening` parses (16) to be the +/// node that widens. +const RECORD_BASE_CTORS: usize = 4; + +/// Java and Groovy, which read it alike: one record of ten components +/// whose body holds `width` alternative constructors, each spelling the +/// first nine component types and a tenth that differs. +/// +/// The record's header stands for the implicit canonical constructor +/// only where the body writes none, and a written one is told from an +/// alternative by its parameter types against the components' (#1842). +/// So the header's gate scans the body, and for each constructor named +/// after the record spells its types until one differs — here the +/// last, the most a constructor can cost. Every consumer that asks the +/// gate pays one such scan; a consumer asking it once per *member* +/// would pay `width` of them. The constructors are identical, which no +/// compiler accepts and both grammars parse, so the bytes per unit of +/// `width` are constant. +#[must_use] +pub fn record_alternative_ctors(width: usize) -> String { + const COMPONENTS: &str = "int a, int b, int c, int d, int e, int f, int g, int h, int i"; + let ctor = format!("R({COMPONENTS}, long j) {{ }}\n"); + format!( + "record R({COMPONENTS}, int j) {{\n{}}}\n", + ctor.repeat(width + RECORD_BASE_CTORS) + ) +} + /// Lua: a module block, then `width` units of a tagless `---` block /// directly under a call — no item follows it, so the first-block test /// scans back — and a documented function, whose block is the reading. @@ -3408,6 +3439,48 @@ pub const PROBES: &[Probe] = &[ rows; the reading counts the comment rows, which do \ not depend on the scan.", }, + Probe { + name: "nargs/java-record-alternative-ctors", + lang: LANG::Java, + axis: Axis::Width, + workload: Workload::Metrics { + exclude_tests: false, + selection: &[Metric::Nargs], + reading: |m| m.nargs.function_args_sum(), + }, + render: record_alternative_ctors, + sizes: LINEAR_WIDTHS, + max_exponent: LINEAR_BOUND, + rationale: "#1863: a record's header gate scans the body for a \ + canonical constructor, spelling each same-named \ + constructor's parameter types until one differs from \ + the component's. One scan is linear in the body, and \ + each consumer of the gate pays one per record: 1.01. \ + With the gate asked once per constructor instead, one \ + walk of 2 000 constructors took 47 s against 32 ms and \ + the gate abandons the probe over its per-walk budget. \ + The reading is ten arguments per constructor and ten \ + for the header.", + }, + Probe { + name: "nargs/groovy-record-alternative-ctors", + lang: LANG::Groovy, + axis: Axis::Width, + workload: Workload::Metrics { + exclude_tests: false, + selection: &[Metric::Nargs], + reading: |m| m.nargs.function_args_sum(), + }, + render: record_alternative_ctors, + sizes: LINEAR_WIDTHS, + max_exponent: LINEAR_BOUND, + rationale: "#1863: the same gate on the same source as \ + `nargs/java-record-alternative-ctors`, under the \ + Groovy grammar, whose header is a `record_components` \ + list and whose gate is a twin in `roles/groovy.rs`: \ + 1.01, and 49 s against 26 ms at 2 000 constructors \ + with the gate asked once per constructor.", + }, Probe { name: "loc/rust-attributed-docs", lang: LANG::Rust, @@ -4581,7 +4654,7 @@ pub const PROBES: &[Probe] = &[ mod tests { use big_code_analysis::{Ast, AstCfg, AstNode, Source}; - use super::{Axis, PROBES, Probe, Workload, exported_nodes}; + use super::{Axis, PROBES, Probe, RECORD_BASE_CTORS, Workload, exported_nodes}; /// How deep an export nests, counted on an explicit stack like /// [`exported_nodes`]. @@ -5060,6 +5133,42 @@ mod tests { } } + /// The two `record-alternative-ctors` probes (#1863) read every + /// list: ten arguments for each of the `size` constructors and the + /// base ones, and ten for the header, which stays open because + /// every constructor is an alternative. A constructor read as + /// canonical closes the header and drops its ten; a header gate + /// that stopped scanning leaves the reading unchanged, which is why + /// the node count is pinned beside it: the scan is priced by the + /// constructors the body really holds. + #[test] + fn record_alternative_ctor_probes_read_every_list() { + for name in [ + "nargs/java-record-alternative-ctors", + "nargs/groovy-record-alternative-ctors", + ] { + let probe = PROBES + .iter() + .find(|p| p.name == name) + .unwrap_or_else(|| panic!("{name} is a probe")); + for size in [3, probe.sizes[0]] { + let ast = parse(probe, size); + let constructors = size + RECORD_BASE_CTORS; + assert_eq!( + count_kind(&ast, "constructor_declaration"), + constructors, + "{name}: one constructor per unit of width, and the base" + ); + let reading = probe + .workload + .walk(&ast, probe.workload.options()) + .expect("metrics walk"); + // expected: 10 per constructor, plus the header's 10. + assert_eq!(reading, 10 * (constructors as u64 + 1), "{name} at {size}"); + } + } + } + /// A probe of `size` one-`line_continuation` runs under one /// parenthesis reads `reading(size)`: the two tests below share /// the shape and differ in the formula. diff --git a/docs/development/benchmarking.md b/docs/development/benchmarking.md index 2d747b790..5a9ef1fd2 100644 --- a/docs/development/benchmarking.md +++ b/docs/development/benchmarking.md @@ -177,6 +177,8 @@ Read it as follows. | `loc/rust-inner-doc-run` | Rust | width | the inner-doc test of each `//!` opening a function body, with no prefix scan | linear | | `loc/java-dangling-docs` | Java | width | `bound_doc_run`'s once-per-stretch decision over dangling [Javadoc](https://docs.oracle.com/en/java/javase/21/javadoc/javadoc.html) (#1613) | linear | | `loc/java-package-docs` | Java | width | the package Javadoc's look-ahead for a type, stopped at the next package (#1613) | linear | +| `nargs/java-record-alternative-ctors` | Java | width | the record-header gate's scan of the body for a canonical constructor, told by its parameter types: one scan per consumer of the gate, never one per constructor (#1863) | linear | +| `nargs/groovy-record-alternative-ctors` | Groovy | width | the same gate on the same source under the Groovy grammar (#1863) | linear | | `loc/rust-attributed-docs` | Rust | width | the same decision through the attributes between `///` comments (#1613) | linear | | `loc/csharp-dangling-docs` | C# | width | [Roslyn](https://github.com/dotnet/roslyn)'s reverse trivia scan over doc comments split by plain ones (#1613) | linear | | `loc/php-file-docblock` | PHP | width | [phpDocumentor](https://www.phpdoc.org/)'s file-DocBlock test, a forward scan from the first DocBlock only (#1613) | linear | @@ -872,6 +874,38 @@ first count cannot see. Under `--cfg chain_audit` every folded answer is also checked against the scan, which is what would catch a second kind list asked on the same lane. +`nargs/java-record-alternative-ctors` and +`nargs/groovy-record-alternative-ctors` guard the record-header gate +[#1842][record-header] added. A record's header opens a function space +only where the body writes no canonical constructor, and a written one +is told from an alternative by its parameter types, so the gate scans +the body and spells the types of every constructor named after the +record until one differs. The walk promotion, the space's kind, +`nargs`, `nom`, `npm` and cognitive each ask the gate, so a record +costs a handful of scans, each linear in its body. No probe rendered a +record before [#1863][roles-followups]. + +Both probes render one record of ten components whose body holds +`width` alternative constructors, each spelling nine component types +and a tenth that differs, which is the most a constructor can cost. + +| Walk put back | Probe that fails | Clean | Regressed | Top rung | +|---|---|---|---|---| +| the gate asked once per constructor | `nargs/java-record-alternative-ctors` | 1.01 | abandoned | 32 ms → 47 s | +| (same patch) | `nargs/groovy-record-alternative-ctors` | 1.01 | abandoned | 26 ms → 49 s | + +One run each, on a host that was not idle. The regressed walk runs past +`MAX_CELL_WALK` at the top rung, so the gate reports an abandoned walk +in place of an exponent. `loc/java-package-docs`, +`loc/rust-attributed-docs` and `cognitive/wide-if-siblings` read 0.84, +1.00 and 0.86 in the same run. The same change reads the header's +component types once per scan rather than once per constructor, which +took the top rung from 44 ms to 29 ms for Java and from 35 ms to 21 ms +for Groovy on a warm tree; the exponent does not move. + +[record-header]: https://github.com/dekobon/big-code-analysis/issues/1842 +[roles-followups]: https://github.com/dekobon/big-code-analysis/issues/1863 + ### Child scans, and where the allocation actually was {#child-scans} `Node::children` builds a `tree_sitter::TreeCursor`, which heap-allocates diff --git a/src/metrics/nargs.rs b/src/metrics/nargs.rs index c5e23aace..ebbcd8869 100644 --- a/src/metrics/nargs.rs +++ b/src/metrics/nargs.rs @@ -4421,7 +4421,10 @@ class A(val x: Int)", /// still reads as canonical. C-style trailing dimensions are part /// of the spelling: `int a[]` is `int` plus `[]`, the same type /// `int[] a` spells (`D`, canonical, JLS 8.4.1), and `int a[][]` - /// one dimension more (`Z`, an alternative). `Nullable` is declared + /// one dimension more (`Z`, an alternative). Arity is part of the + /// rule wherever the lists part ways: a constructor whose parameters + /// run past the components (`P`) or stop short of them (`S`) is an + /// alternative however far the types agree. `Nullable` is declared /// at the end so `N` is the valid Java javac accepts (`@Deprecated` /// is not a type-use annotation); its row is the annotation type's. #[cfg(feature = "java")] @@ -4443,6 +4446,8 @@ class A(val x: Int)", record G(java.util.List l) { G(java.util.List l) { this.l = l; } } record H(int[] a) { H(int a[/* c */]) { this.a = a; } } record V(int... xs) { V(final /* c */ int... xs) { this.xs = xs; } } + record P(int a) { P(int a, int b) { this(a); } } + record S(int a, int b) { S(int a) { this(a, 0); } } @java.lang.annotation.Target(java.lang.annotation.ElementType.TYPE_USE) @interface Nullable { }", "types.java", |space| { @@ -4469,6 +4474,8 @@ class A(val x: Int)", ("G", 1), ("H", 1), ("V", 1), + ("P", 2), + ("S", 2), ("Nullable", 0), ] ); @@ -4487,7 +4494,9 @@ class A(val x: Int)", /// (`Q`) is an alternative, the spelling limit `roles/groovy.rs` /// documents. A comment is no token: inside the generic arguments /// (`G`), inside a qualified name (`K`) or inside an array type's - /// brackets (`H`) the constructor still reads as canonical. + /// brackets (`H`) the constructor still reads as canonical. A + /// constructor whose parameters run past the components (`P`) or + /// stop short of them (`S`) is an alternative. #[cfg(feature = "groovy")] #[test] fn groovy_canonical_constructor_is_told_by_its_types() { @@ -4499,7 +4508,9 @@ class A(val x: Int)", record Q(java.util.List l) { Q(List l) { this.l = l } } record G(List l) { G(List l) { this.l = l } } record K(java.util.List l) { K(java.util./* c */List l) { this.l = l } } - record H(int[] a) { H(int[/* c */] a) { this.a = a } }", + record H(int[] a) { H(int[/* c */] a) { this.a = a } } + record P(int a) { P(int a, int b) { this(a) } } + record S(int a, int b) { S(int a) { this(a, 0) } }", "types.groovy", |space| { let functions_per_record: Vec<(&str, usize)> = space @@ -4518,6 +4529,8 @@ class A(val x: Int)", ("G", 1), ("K", 1), ("H", 1), + ("P", 2), + ("S", 2), ] ); }, From 545895943716a7b2143904a00fe605326f38344c Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Wed, 11 Nov 2026 17:53:55 -0800 Subject: [PATCH 07/21] perf(loc/python): fold the code-before-a-parenthesis question down the chain MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A bare `\` run inside a parenthesised docstring asks whether its parenthesis sits on the string's line with no code before it. The answer is read at the nearest level, from the node's own upward, that holds a token before its node; a level holding only comments and splices defers to the one above. Where no level answers, each of `depth` nested parentheses climbed to the root: `depth² / 2` levels, bounded only by CPython's 200-level cap. Every existing Python parenthesis probe grows the nesting or one level's prefix, never both. `Ancestors::nearest_level_answer` folds such a question down the walk's chain on a new `LevelLane`, each ancestor's own answer once per walk, and climbs where no cache is lent. `python_code_before_node` reads its own level and then the fold, so a parenthesis reads three levels. `loc/python-deep-paren-extra-prefix` renders a docstring `depth` parentheses deep with 30 run-and-comment pairs per level, the most that keeps a parenthesis under `WIDE_PARENT`, so a level's read is a seek and the number of levels read shows in the timing. It fits 1.00. With the climb put back it reads 1.95 and fails the gate, 92 ms at the top rung against 5.3 ms. The measurement decided this. Probe-only was the plan if a bound separated the memoised climb from an unmemoised one; on the issue's shape they read 1.56 and 1.98, with no bound that clears both on a shared host. `python_code_before_a_parenthesis_reads_three_levels_each` pins the count: 120 levels over 40 parentheses, 900 with the climb. `make chain-audit` checks every folded answer against the climb and passes. No `loc` value moves. The baseline records `node/ancestors.rs`, which gained the method. Refs #1863 --- .bca-baseline.toml | 8 +- big-code-analysis-ast/src/lib.rs | 2 +- big-code-analysis-ast/src/node.rs | 72 ++++++++++++- big-code-analysis-ast/src/node/ancestors.rs | 84 ++++++++++++++- big-code-analysis-bench/src/shapes.rs | 112 +++++++++++++++++++- docs/development/benchmarking.md | 43 ++++++++ src/metrics/loc.rs | 42 ++++++++ src/metrics/loc/python.rs | 38 +++++-- 8 files changed, 385 insertions(+), 16 deletions(-) diff --git a/.bca-baseline.toml b/.bca-baseline.toml index aafb8af69..97c426025 100644 --- a/.bca-baseline.toml +++ b/.bca-baseline.toml @@ -299,25 +299,25 @@ value = 43.0 path = "big-code-analysis-ast/src/node/ancestors.rs" qualified = "" metric = "loc.ploc" -value = 646.0 +value = 690.0 [[entry]] path = "big-code-analysis-ast/src/node/ancestors.rs" qualified = "" metric = "loc.sloc" -value = 1390.0 +value = 1470.0 [[entry]] path = "big-code-analysis-ast/src/node/ancestors.rs" qualified = "Ancestors<'tree, 'chain>" metric = "nom" -value = 41.0 +value = 45.0 [[entry]] path = "big-code-analysis-ast/src/node/ancestors.rs" qualified = "Ancestors<'tree, 'chain>" metric = "wmc" -value = 76.0 +value = 81.0 [[entry]] path = "big-code-analysis-ast/src/node/ancestors.rs" diff --git a/big-code-analysis-ast/src/lib.rs b/big-code-analysis-ast/src/lib.rs index 986b65279..9a9d4ac4a 100644 --- a/big-code-analysis-ast/src/lib.rs +++ b/big-code-analysis-ast/src/lib.rs @@ -141,7 +141,7 @@ pub use crate::macros::ParseLangError; pub(crate) use crate::node::FoldLane; pub use crate::node::{Ancestors, ChildAncestors, FoldCache, Node, SiblingCache}; #[doc(hidden)] -pub use crate::node::{GateLane, KindLane, NodeQuestion}; +pub use crate::node::{GateLane, KindLane, LevelLane, NodeQuestion}; pub use crate::parser::Parser; pub use crate::preproc::{ PreprocDiagnostic, PreprocFile, PreprocResults, fix_includes, get_macros, preprocess, diff --git a/big-code-analysis-ast/src/node.rs b/big-code-analysis-ast/src/node.rs index 7aab75195..468d0565d 100644 --- a/big-code-analysis-ast/src/node.rs +++ b/big-code-analysis-ast/src/node.rs @@ -19,8 +19,8 @@ pub use ancestors::{AncestorIter, Ancestors, ChildAncestors, FoldCache, SiblingC pub(crate) use ancestors::{FoldLane, MemoQuestion, NodeMemo, WordSlot}; #[doc(hidden)] pub use ancestors::{ - GateLane, KindLane, NodeQuestion, WIDE_PARENT, child_chains_derived, fold_slot_probes, - fold_steps, sibling_cache_reads, sibling_seeks, + GateLane, KindLane, LevelLane, NodeQuestion, WIDE_PARENT, child_chains_derived, + fold_slot_probes, fold_steps, sibling_cache_reads, sibling_seeks, }; use tree_sitter::Node as OtherNode; @@ -2354,4 +2354,72 @@ mod tests { ); assert!(yes > 0 && no > 0, "both answers must occur ({yes} / {no})"); } + + /// `nearest_level_answer` answers what the climb answers through + /// all three of its paths — the walk's memoised fold, a known chain + /// with no cache, the chainless climb — for every node of the + /// fixture (#1863). + /// + /// The answer fn says "yes" at a function and "no" at a closure, so + /// a node inside a closure inside a function reads the closure's + /// "no": the nearer answer replaces the outer one, where a fold + /// that only ever set its state would read "yes". A node under + /// neither reads `false`, and the answering node itself is not + /// asked: a function's own answer is its ancestors'. The second + /// cache is asked only at integer literals, so each ask meets the + /// slots the previous literal's chain left under other parents. + #[cfg(feature = "rust")] + #[test] + fn nearest_level_answer_answers_the_climb_on_every_path() { + use crate::node::{FoldCache, LevelLane}; + fn level(_code: &[u8], node: &Node, _chain: Ancestors) -> Option { + match node.kind() { + "function_item" => Some(true), + "closure_expression" => Some(false), + _ => None, + } + } + let code = b"fn f() { let c = || { let d = (1 + 2); }; let e = 3; }\n\ + const K: u8 = 4;\n\ + mod m { fn g() { let h = || 5; } fn i() { 6; } }\n"; + let cache = FoldCache::default(); + let asked_at_literals = FoldCache::default(); + let lane = LevelLane::CodeBeforeOnLine; + let mut literals = Vec::new(); + let (mut yes, mut no) = (0_usize, 0_usize); + for_each_node_with_chain::(code, |node, chain| { + let expected = std::iter::successors(node.parent(), Node::parent) + .find_map(|ancestor| level(code, &ancestor, Ancestors::unknown())) + .unwrap_or(false); + let folded = Ancestors::known(chain) + .with_folds(&cache) + .nearest_level_answer(node, lane, code, level); + let chained = Ancestors::known(chain).nearest_level_answer(node, lane, code, level); + let climbed = Ancestors::unknown().nearest_level_answer(node, lane, code, level); + let (kind, start) = (node.kind(), node.start_byte()); + assert_eq!( + (folded, chained, climbed), + (expected, expected, expected), + "{kind} at byte {start}: (folded, chained, climbed) must all be the climb's answer" + ); + if kind == "integer_literal" { + literals.push( + Ancestors::known(chain) + .with_folds(&asked_at_literals) + .nearest_level_answer(node, lane, code, level), + ); + } + if expected { + yes += 1; + } else { + no += 1; + } + }); + assert_eq!( + literals, + [false, false, true, false, false, true], + "1 and 2 in f's closure, 3 in f, 4 under neither, 5 in g's closure, 6 in i" + ); + assert!(yes > 0 && no > 0, "both answers must occur ({yes} / {no})"); + } } diff --git a/big-code-analysis-ast/src/node/ancestors.rs b/big-code-analysis-ast/src/node/ancestors.rs index 8f4e1ca58..f17083583 100644 --- a/big-code-analysis-ast/src/node/ancestors.rs +++ b/big-code-analysis-ast/src/node/ancestors.rs @@ -419,6 +419,62 @@ impl<'tree, 'chain> Ancestors<'tree, 'chain> { folded } + /// The answer of the nearest ancestor of `node` that has one, or + /// `false` where none does: what + /// `self.iter(node).find_map(|(level, chain)| answer(code, &level, + /// chain)).unwrap_or(false)` answers. `node` itself is not asked. + /// + /// That climb stops at the first ancestor that answers, which bounds + /// it only where one is near. A node asked from each level of a nest + /// whose levels answer nothing — a parenthesis in each of `n` + /// parentheses around a Python docstring, each asking whether code + /// precedes it on its logical line — climbs the nest from every + /// level and is quadratic in its depth (#1863). Under a walk that + /// lent a [`FoldCache`] the answer is folded down the chain on + /// `lane` instead, each ancestor's own answer once per walk: a + /// `Some` replaces what the ancestors above it said, a `None` keeps + /// it. Elsewhere the climb is what runs, since an unmemoised fold + /// would start at the root for every ask. + /// + /// A lane memoises whatever its first asker folded, so each + /// [`LevelLane`] belongs to one `answer` per walk, and `answer` is a + /// plain `fn` of the source, the ancestor and the ancestor's own + /// chain: a closure that captured the asking node would hand every + /// later node the first one's answer. `make chain-audit` checks + /// every folded answer against the climb. + #[doc(hidden)] + #[must_use] + pub fn nearest_level_answer( + self, + node: &Node<'tree>, + lane: LevelLane, + code: &[u8], + answer: fn(&[u8], &Node<'tree>, Ancestors<'tree, 'chain>) -> Option, + ) -> bool { + let climb = || { + self.iter(node) + .find_map(|(level, chain)| answer(code, &level, chain)) + .unwrap_or(false) + }; + if !self.memoises_folds() { + return climb(); + } + let folded = self.fold_down(node, 0, lane.fold_lane(), 0, |held, ancestor, outer, _| { + answer(code, ancestor, outer).map_or(held, u8::from) + }) == 1; + // Opt-in only: the climb is the `O(depth)` per ask the fold + // exists to remove. + #[cfg(chain_audit)] + assert_eq!( + folded, + climb(), + "the {lane:?} fold disagrees with the climb on a {} node: a lane \ + holds one answer fn per walk", + node.kind() + ); + folded + } + /// The walk's memo for `question`, when it lent a [`FoldCache`]. pub(crate) fn node_memo(self, question: MemoQuestion) -> Option<&'chain NodeMemo> { self.folds.map(|cache| &cache.nodes[question as usize]) @@ -1031,6 +1087,28 @@ impl KindLane { } } +/// The "nearest ancestor that answers" questions the metric crate asks +/// through [`Ancestors::nearest_level_answer`], one per lane of the +/// walk's [`FoldCache`]. Its own enum for the reason [`KindLane`] is: +/// this entry point stores an answer, not a "seen one" flag, so a lane +/// passed to the wrong one would hand each question the other's memo. +#[doc(hidden)] +#[non_exhaustive] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum LevelLane { + /// Python: whether code precedes a node on its logical line, read + /// at the nearest level above it that has a token before its node. + CodeBeforeOnLine, +} + +impl LevelLane { + const fn fold_lane(self) -> FoldLane { + match self { + Self::CodeBeforeOnLine => FoldLane::CodeBeforeOnLine, + } + } +} + /// Which memoised fold a [`FoldCache`] slot holds. A language may run /// more than one fold over the same walk, and two folds' states must not /// share a slot. @@ -1064,17 +1142,19 @@ pub(crate) enum FoldLane { LambdaDepth, /// [`KindLane::InsideFunction`]. InsideFunction, + /// [`LevelLane::CodeBeforeOnLine`]. + CodeBeforeOnLine, } impl FoldLane { /// How many lanes a [`FoldCache`] holds; one per variant above. - const COUNT: usize = 11; + const COUNT: usize = 12; } // A lane past `COUNT` would index out of the array at run time, on the // first walk that folds on it; this makes a variant added without the // bump a build error instead. -const _: () = assert!(FoldLane::InsideFunction as usize + 1 == FoldLane::COUNT); +const _: () = assert!(FoldLane::CodeBeforeOnLine as usize + 1 == FoldLane::COUNT); /// Which memoised per-node question a [`FoldCache`] [`NodeMemo`] holds. /// Two questions asked of the same node must not share a slot, so each diff --git a/big-code-analysis-bench/src/shapes.rs b/big-code-analysis-bench/src/shapes.rs index 716ccff13..6349a1c18 100644 --- a/big-code-analysis-bench/src/shapes.rs +++ b/big-code-analysis-bench/src/shapes.rs @@ -455,6 +455,41 @@ pub fn python_bare_runs_before_string(width: usize) -> String { ) } +/// How many `\` + `# c` pairs [`python_deep_paren_extra_prefix`] puts +/// ahead of the next parenthesis at every level: 63 children with the +/// two parentheses and the next level, the most a node holds before the +/// walk records it for sibling lookups (`WIDE_PARENT`). A level's read +/// is then a seek over the parenthesis's children rather than a slice +/// of the walk's sibling cache, which is what makes the number of +/// levels read show in the timing: timed alone on a warm tree, the +/// climb read 1.56 with 31 pairs and 2.05 with these 30. +const PAREN_PREFIX_PAIRS: usize = 30; + +/// Python: a bare string `depth` parentheses deep, each parenthesis +/// opening with [`PAREN_PREFIX_PAIRS`] one-row bare `\` runs, each +/// joining a comment row, before the next parenthesis; then a retained +/// `x = 1`. +/// +/// [`python_bare_runs_before_string`] grows the prefix of one +/// parenthesis and [`python_paren_bare_strings`] the nesting with no +/// prefix; this grows both. A run asks whether its parenthesis is on +/// the string's line with no code before it, and that question looks at +/// each level above the parenthesis for a token before the level's +/// node, past that level's extras. None of these levels has one, so the +/// question defers to the root from every parenthesis: read by +/// climbing, `depth` parentheses read `depth² / 2` levels, under the +/// 200 levels Python's tokenizer lets parentheses nest. Folded down the +/// walk's chain, each reads three (#1863). +#[must_use] +pub fn python_deep_paren_extra_prefix(depth: usize) -> String { + let level = format!("(\n{}", "\\\n# c\n".repeat(PAREN_PREFIX_PAIRS)); + format!( + "{}\"\"\"doc\"\"\"\n{}\nx = 1\n", + level.repeat(depth), + ")".repeat(depth) + ) +} + /// C: `width` units of a `{` that never closes, each followed by a row /// holding only `\` and a row holding two block comments. /// @@ -3863,6 +3898,32 @@ pub const PROBES: &[Probe] = &[ depth under the cap, and the metric probe cannot see \ a walk it does not run.", }, + Probe { + name: "loc/python-deep-paren-extra-prefix", + lang: LANG::Python, + axis: Axis::Depth, + workload: Workload::Metrics { + exclude_tests: false, + selection: &[Metric::Loc], + reading: |m| m.loc.cloc(), + }, + render: python_deep_paren_extra_prefix, + sizes: PAREN_CAP_DEPTHS, + max_exponent: LINEAR_BOUND, + rationale: "#1863: every parenthesis of a parenthesised bare string \ + that opens with bare `\\` runs asks whether code precedes \ + it on its logical line, which defers level by level to \ + the root where the levels hold only comments and \ + splices. Climbed from each parenthesis that is \ + `depth² / 2` levels under CPython's 200-level cap; the \ + answer is folded down the walk's chain on \ + `LevelLane::CodeBeforeOnLine`, three levels per \ + parenthesis. With the climb put back this reads 1.95, \ + 92 ms at the top rung against 5.3 ms, and 1.00 \ + without. The reading is the comment rows: each level's \ + `(` row, bare rows and comments, the string's and the \ + `)` row.", + }, Probe { name: "loc/go-nested-doc-fields", lang: LANG::Go, @@ -4654,7 +4715,9 @@ pub const PROBES: &[Probe] = &[ mod tests { use big_code_analysis::{Ast, AstCfg, AstNode, Source}; - use super::{Axis, PROBES, Probe, RECORD_BASE_CTORS, Workload, exported_nodes}; + use super::{ + Axis, PAREN_PREFIX_PAIRS, PROBES, Probe, RECORD_BASE_CTORS, Workload, exported_nodes, + }; /// How deep an export nests, counted on an explicit stack like /// [`exported_nodes`]. @@ -5133,6 +5196,53 @@ mod tests { } } + /// `loc/python-deep-paren-extra-prefix` (#1863) keeps every + /// parenthesis as wide as a node can be before the walk records its + /// children for sibling lookups, so each level's read is a seek and + /// the count of levels read shows in the timing. One pair more and + /// the levels are served from the sibling cache: the probe would + /// still fit, and would read about 1.6 with the climb put back + /// where it reads about 2. The threshold is the walk's `WIDE_PARENT`, read from + /// the AST crate so a raised or lowered threshold fails here rather + /// than weakening the probe unseen. The reading is every row but + /// the retained `x = 1`. + #[test] + fn python_deep_paren_probe_levels_stay_under_the_sibling_cache() { + use big_code_analysis_ast::node::WIDE_PARENT; + let name = "loc/python-deep-paren-extra-prefix"; + let probe = PROBES + .iter() + .find(|p| p.name == name) + .unwrap_or_else(|| panic!("{name} is a probe")); + for size in [3, probe.sizes[0]] { + let ast = parse(probe, size); + assert_eq!( + count_kind(&ast, "parenthesized_expression"), + size, + "one parenthesis per level" + ); + // expected: `(`, two nodes per pair, the next level, `)`. + let widest = 2 * PAREN_PREFIX_PAIRS + 3; + assert_eq!(max_child_count(&ast), widest, "{name} at {size}"); + assert!( + widest <= WIDE_PARENT && widest + 2 > WIDE_PARENT, + "{widest} children per parenthesis must be the most that stays \ + under WIDE_PARENT ({WIDE_PARENT})" + ); + let reading = probe + .workload + .walk(&ast, probe.workload.options()) + .expect("metrics walk"); + // expected: per level the `(` row and a bare row and a + // comment row per pair; then the string's row and the `)` row. + assert_eq!( + reading, + ((2 * PAREN_PREFIX_PAIRS + 1) * size + 2) as u64, + "{name} at {size}" + ); + } + } + /// The two `record-alternative-ctors` probes (#1863) read every /// list: ten arguments for each of the `size` constructors and the /// base ones, and ten for the header, which stays open because diff --git a/docs/development/benchmarking.md b/docs/development/benchmarking.md index 5a9ef1fd2..9fdaff8b3 100644 --- a/docs/development/benchmarking.md +++ b/docs/development/benchmarking.md @@ -193,6 +193,7 @@ Read it as follows. | `halstead/python-nested-paren` | Python | depth | the climb from each parenthesis to its statement, capped at CPython's nesting limit (#1610) | linear | | `loc/python-paren-bare-strings` | Python | depth | each parenthesis of a bare string statement asking whether it wraps the string, memoised per statement under the cap (#1610) | linear | | `ops/python-paren-bare-strings` | Python | depth | the same test in the `bca ops` walk, which keeps its own fold cache (#1610) | linear | +| `loc/python-deep-paren-extra-prefix` | Python | depth | each parenthesis of a parenthesised docstring asking whether code precedes it on its logical line, where every level defers to the one above, folded on `LevelLane::CodeBeforeOnLine` (#1863) | linear | | `loc/go-nested-doc-fields` | Go | depth | Go's package-level scope test over nested struct fields (#1597) | linear | | `loc/ruby-nested-doc-constants` | Ruby | depth | YARD's namespace scope test through nested `if`s (#1597) | linear | | `loc/lua-tagless-blocks` | Lua | width | LDoc's first-block test, scanning back to the previous block (#1597) | linear | @@ -906,6 +907,48 @@ for Groovy on a warm tree; the exponent does not move. [record-header]: https://github.com/dekobon/big-code-analysis/issues/1842 [roles-followups]: https://github.com/dekobon/big-code-analysis/issues/1863 +`loc/python-deep-paren-extra-prefix` guards the Python `loc` question +"does code precede this node on its logical line". A bare `\` run +inside a parenthesised docstring asks it of its parenthesis, once per +parenthesis. The answer is read at the nearest level, from the node's +own upward, that holds a token before its node; a level holding only +comments and splices defers to the one above. Every existing Python +parenthesis probe grows either the nesting or one level's prefix. With +both, no level answers, so each of `depth` parentheses climbed to the +root: `depth² / 2` levels under [CPython](https://www.python.org/)'s +200-level cap. The answer is now folded down the walk's chain +(`Ancestors::nearest_level_answer`), so a parenthesis reads three +levels: its own, the one ancestor state not yet stored, and its +parent's. + +The probe renders a docstring `depth` parentheses deep, each opening +with 30 one-row `\` runs that each join a comment row. Thirty is the +most that keeps a parenthesis under `WIDE_PARENT`, so a level's read is +a seek over the parenthesis's children rather than a slice of the +walk's sibling cache, and the number of levels read shows in the +timing. + +| Walk put back | Probe that fails | Clean | Regressed | Top rung | +|---|---|---|---|---| +| the climb per parenthesis | `loc/python-deep-paren-extra-prefix` | 1.00 | 1.95 | 5.3 ms → 92 ms | + +One run each, on a host that was not idle. In the regressed run +`loc/python-paren-bare-strings`, `ops/python-paren-bare-strings`, +`halstead/python-nested-paren` and `loc/python-bare-runs-before-string` +read 0.95, 1.05, 0.87 and 1.02. The per-change guard is +`python_code_before_a_parenthesis_reads_three_levels_each` in +`src/metrics/loc.rs`, which pins the exact number of levels read over +40 parentheses: 120 folded, 900 climbed. Under `--cfg chain_audit` +every folded answer is also checked against the climb. + +The climb sweep above was re-run for this fold and each match re-read, +not re-timed. Every other match stops within a fixed distance of all +but one asker per subtree, is capped, or already folds where a walk +lends a cache. The one exception was filed before this change: +`python_is_bound_self_attribute` ([#1867][python-npa]). + +[python-npa]: https://github.com/dekobon/big-code-analysis/issues/1867 + ### Child scans, and where the allocation actually was {#child-scans} `Node::children` builds a `tree_sitter::TreeCursor`, which heap-allocates diff --git a/src/metrics/loc.rs b/src/metrics/loc.rs index 30a3cd998..9610a8ae7 100644 --- a/src/metrics/loc.rs +++ b/src/metrics/loc.rs @@ -10384,6 +10384,48 @@ EOF } } + /// #1863: whether code precedes a parenthesis on its logical line is + /// folded down the walk's chain, so a docstring `depth` parentheses + /// deep, each opening with a bare `\` run, reads three levels per + /// parenthesis rather than every level above each. + /// + /// The rows cannot see it: the fold and the climb answer the same, + /// so every row but the last is a comment row either way, and only + /// the count of levels read tells the two apart. No level here has a + /// token before its node, so the question defers from each + /// parenthesis to the root, the shape the climb was quadratic on. + #[cfg(feature = "python")] + #[test] + fn python_code_before_a_parenthesis_reads_three_levels_each() { + let depth = 40; + let source = format!( + "{}\"\"\"doc\"\"\"\n{}\nx = 1\n", + "(\n\\\n# c\n".repeat(depth), + ")".repeat(depth) + ); + let before = python::python_line_levels_read::observed(); + let loc = metrics_verbatim( + crate::LANG::Python, + source.as_bytes(), + MetricsOptions::default().with_only(&[crate::Metric::Loc]), + ) + .loc; + let read = python::python_line_levels_read::observed() - before; + // expected: per level the `(` row, the bare row and the comment + // row; then the string's row and the row of `)`. + assert_eq!(loc.cloc(), 3 * depth as u64 + 2); + // expected: each parenthesis is asked once, by its run, and reads + // its own level, the one ancestor state the fold has not stored + // yet, and its parent's level, which a fold never stores. The + // climb read `j + 2` levels from the parenthesis `j` deep, + // `depth * (depth + 5) / 2` in all: 900 here. `make chain-audit` + // checks every folded answer against that climb, which reads + // the levels this counts, so the count is asserted without it. + if cfg!(not(chain_audit)) { + assert_eq!(read, 3 * depth); + } + } + /// #1818: the C-family bare-row index is built exactly once per /// walk, and only where the walk can use it. The output cannot tell /// one build from one per node — each build answers the same — so diff --git a/src/metrics/loc/python.rs b/src/metrics/loc/python.rs index 4c038dda5..49c120d72 100644 --- a/src/metrics/loc/python.rs +++ b/src/metrics/loc/python.rs @@ -605,15 +605,41 @@ fn python_code_before_string<'a>( // run's parent once the run's own level is read, and every level a // parenthesis's memoised answer reads — the parenthesis's inside, where // nothing before the string can be code, is never one of them. +// +// The levels above `node` are folded down the walk's chain rather than +// climbed. A parenthesis whose own level holds only comments and `\` +// splices before it defers to the level above, and so does that one: +// asked from each of `n` nested parentheses, the climb read every level +// above each, `Σ` of their extras, quadratic in `n` under CPython's +// 200-level cap (#1863; `loc/python-deep-paren-extra-prefix` prices it). fn python_code_before_node<'a>(code: &[u8], node: &Node<'a>, ancestors: Ancestors<'a, '_>) -> bool { - std::iter::once((*node, ancestors)) - .chain(ancestors.iter(node)) - .find_map(|(level, chain)| { - python_code_among(code, chain.siblings_before(&level), &level, Some(chain)) - }) - .unwrap_or(false) + python_code_at_level(code, node, ancestors).unwrap_or_else(|| { + ancestors.nearest_level_answer( + node, + LevelLane::CodeBeforeOnLine, + code, + python_code_at_level, + ) + }) +} + +// `python_code_among` for `level` among its own siblings: one level of +// `python_code_before_node`'s reading, a function of the level alone. +fn python_code_at_level<'a>( + code: &[u8], + level: &Node<'a>, + chain: Ancestors<'a, '_>, +) -> Option { + python_line_levels_read::record(); + python_code_among(code, chain.siblings_before(level), level, Some(chain)) } +// Levels `python_code_before_node` reads for a token before their node. +// The fold and the climb answer the same, so only this tells a walk that +// reads each level once from one that reads every level above every +// parenthesis (#1863). +crate::observation::counter!(python_line_levels_read); + // Whether the nearest of `siblings` (nearest first) that is neither a // `\` splice nor the bare string's own parenthesis ends on `next`'s // logical line — only padding and splices between the two, a splice the From bacf760c10b1c2fe660da0d889eb6573bfa9c5d1 Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Wed, 11 Nov 2026 18:00:16 -0800 Subject: [PATCH 08/21] test(roles): count the record-header type reads the hoist saves The header gate spells a record's component types once per evaluation since 582b5331. No answer can see that: three alternative constructors leave the header open whether its types are spelled once or three times, and the scaling probes fit the same exponent either way. A counter beside each gate and one exact-count test per language pin it: one read for a record with three alternatives, none for a record with no constructor. Also corrects the Python probe's shape doc, which said it grows the prefix; the prefix is fixed at 30 pairs per level and only the nesting grows. Both found by the checkpoint review of steps 3 to 5. Refs #1863 --- big-code-analysis-ast/src/roles/groovy.rs | 9 +++ big-code-analysis-ast/src/roles/java.rs | 10 +++ .../src/roles/space_tree_tests.rs | 67 +++++++++++++++++++ big-code-analysis-bench/src/shapes.rs | 3 +- 4 files changed, 88 insertions(+), 1 deletion(-) diff --git a/big-code-analysis-ast/src/roles/groovy.rs b/big-code-analysis-ast/src/roles/groovy.rs index 27ed9f9ac..0aeeadbd2 100644 --- a/big-code-analysis-ast/src/roles/groovy.rs +++ b/big-code-analysis-ast/src/roles/groovy.rs @@ -187,6 +187,7 @@ fn opens_record_header<'a>(node: &Node<'a>, code: &[u8], ancestors: Ancestors<'a !body.children().any(|member| { member.kind_id() == Groovy::ConstructorDeclaration as u16 && { let components = components.get_or_insert_with(|| { + record_header_types_read::record(); node.children() .filter(|p| p.kind_id() == Groovy::RecordComponent as u16) .map(|p| groovy_parameter_type(&p, code)) @@ -197,6 +198,14 @@ fn opens_record_header<'a>(node: &Node<'a>, code: &[u8], ancestors: Ancestors<'a }) } +// Times `opens_record_header` spelled a header's component types: once +// per evaluation that meets a constructor, as Java's twin counts +// (`roles/java.rs`, #1863). +crate::observation::counter!( + record_header_types_read, + cfg(any(test, feature = "test-support")) +); + /// Java's eight primitive type keywords and `void`, which Groovy /// reserves as Java does. const PRIMITIVE_TYPES: &[&str] = &[ diff --git a/big-code-analysis-ast/src/roles/java.rs b/big-code-analysis-ast/src/roles/java.rs index 319b98644..70c2f63ce 100644 --- a/big-code-analysis-ast/src/roles/java.rs +++ b/big-code-analysis-ast/src/roles/java.rs @@ -177,6 +177,7 @@ fn opens_record_header<'a>(node: &Node<'a>, code: &[u8], ancestors: Ancestors<'a Java::CompactConstructorDeclaration => true, Java::ConstructorDeclaration => { let components = components.get_or_insert_with(|| { + record_header_types_read::record(); node.children() .filter_map(|p| java_parameter_type(&p, code)) .collect::>() @@ -205,6 +206,15 @@ pub fn record_header<'a>(record: &Node<'a>) -> Option> { .flatten() } +// Times `opens_record_header` spelled a header's component types. Once +// per evaluation that meets a constructor, however many it compares: +// re-spelled per constructor the gate answers the same, a third slower +// on a record of alternatives (#1863). +crate::observation::counter!( + record_header_types_read, + cfg(any(test, feature = "test-support")) +); + /// The container a `switch` nests its arms in: the `switch_block`, the /// `Switch` owner's child — a structural fact about the construct the /// row recognises, pinned by diff --git a/big-code-analysis-ast/src/roles/space_tree_tests.rs b/big-code-analysis-ast/src/roles/space_tree_tests.rs index ba2dc273c..a63f0d87e 100644 --- a/big-code-analysis-ast/src/roles/space_tree_tests.rs +++ b/big-code-analysis-ast/src/roles/space_tree_tests.rs @@ -1407,6 +1407,73 @@ fn groovy_record_header_is_the_records_own_list() { ); } +/// How many times the header gate of each record of `source` spelled +/// its component types, one entry per record in source order, with the +/// gate's answer. +#[cfg(any(feature = "java", feature = "groovy"))] +fn header_type_reads( + source: &'static [u8], + record_header: for<'a> fn(&Node<'a>) -> Option>, + opener_owns: crate::roles::RowPred, + observed: fn() -> usize, +) -> Vec<(bool, usize)> { + let mut reads = Vec::new(); + for_each_node_with_chain::(source, |node, chain| { + let ancestors = Ancestors::known(chain); + let is_header = ancestors + .parent(node) + .and_then(|owner| record_header(&owner)) + .is_some_and(|header| header.id() == node.id()); + if is_header { + let before = observed(); + let owned = opener_owns(node, source, ancestors); + reads.push((owned, observed() - before)); + } + }); + reads +} + +/// The header gate spells the record's component types once per +/// evaluation, on the first constructor it meets, and not at all where +/// the body holds none (#1863). Nothing in the answer can see it: three +/// alternative constructors, each agreeing with the components up to +/// the last parameter, leave the header open whether its types are +/// spelled once or three times, so the count is what pins the hoist. +#[cfg(feature = "java")] +#[test] +fn java_header_types_are_read_once_per_gate_evaluation() { + use crate::roles::java::{func_opener, record_header, record_header_types_read}; + let source = b"record R(int a, int b) { R(int a, long b) { this(a, 0); } R(int a, short b) { this(a, 0); } R(int a, byte b) { this(a, 0); } }\nrecord Q(int q) { int m() { return q; } }\n"; + assert_eq!( + header_type_reads::( + source, + record_header, + func_opener::owns, + record_header_types_read::observed, + ), + // expected: `R` open after three comparisons on one read; `Q` + // open with no constructor to compare, so nothing read. + [(true, 1), (true, 0)] + ); +} + +/// Groovy's twin of `java_header_types_are_read_once_per_gate_evaluation`. +#[cfg(feature = "groovy")] +#[test] +fn groovy_header_types_are_read_once_per_gate_evaluation() { + use crate::roles::groovy::{func_opener, record_header, record_header_types_read}; + let source = b"record R(int a, int b) { R(int a, long b) { this(a, 0) } R(int a, short b) { this(a, 0) } R(int a, byte b) { this(a, 0) } }\nrecord Q(int q) { int m() { return q } }\n"; + assert_eq!( + header_type_reads::( + source, + record_header, + func_opener::owns, + record_header_types_read::observed, + ), + [(true, 1), (true, 0)] + ); +} + /// A Java record's header opens the implicit canonical constructor's /// space, named after the record, where the body writes none (#1842) — /// which the byte-less spellings cannot see, as C#'s primary constructor diff --git a/big-code-analysis-bench/src/shapes.rs b/big-code-analysis-bench/src/shapes.rs index 6349a1c18..43278c483 100644 --- a/big-code-analysis-bench/src/shapes.rs +++ b/big-code-analysis-bench/src/shapes.rs @@ -472,7 +472,8 @@ const PAREN_PREFIX_PAIRS: usize = 30; /// /// [`python_bare_runs_before_string`] grows the prefix of one /// parenthesis and [`python_paren_bare_strings`] the nesting with no -/// prefix; this grows both. A run asks whether its parenthesis is on +/// prefix; this grows the nesting and keeps a prefix at every level. +/// A run asks whether its parenthesis is on /// the string's line with no code before it, and that question looks at /// each level above the parenthesis for a token before the level's /// node, past that level's extras. None of these levels has one, so the From 678be3030cce79283008d786899ca11a9180cd36 Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Wed, 11 Nov 2026 18:11:26 -0800 Subject: [PATCH 09/21] refactor(tests,npm,loc): close the smaller follow-ups of the #1862 review - `ops_and_metrics_agree_on_the_space_tree` asserts the Java and Groovy record's header space is in the rendered tree. Dropped by both walks it left the two trees equal, and the fixture's other members kept the non-empty check true. - `check_gated` takes `Option<&str>` for the gated kind instead of `""` as the no-kind sentinel. - `has_public_modifier` reads `modifiers` as `child(0)` again rather than searching for it with a cursor per declaration. `bca dump` confirms it is the first child of a documented, annotated record and method; comments and annotations sit beside or inside it. - `python_is_extra` states tree-sitter-python's two extras once. `not_extra` and `python_code_among` read it. The Groovy `nargs` header arm keeps its kind filter. The issue proposed `count_args::` as giving the same answer; it does on a clean parse only. `count_args` takes every child that is no parenthesis, comma or comment, so the `ERROR` recovery leaves in the list reads as an argument: `record R(int a,) { }` would move from 1 to 2. A test pins both readings and the comment says why the arm is not shared. The Java row test in `roles/java.rs` keeps its own gated-kind loop: it gates two kinds and asserts three more rows, so `check_gated` is no drop-in. No metric value moves. Refs #1863 --- .../src/lang_helpers/python.rs | 18 ++++-- .../src/roles/space_tree_tests.rs | 10 +-- src/metrics/loc/python.rs | 13 ++-- src/metrics/nargs.rs | 62 ++++++++++++++++++- src/metrics/npm.rs | 7 ++- tests/parity/ops_metrics_space_parity.rs | 11 ++++ 6 files changed, 100 insertions(+), 21 deletions(-) diff --git a/big-code-analysis-ast/src/lang_helpers/python.rs b/big-code-analysis-ast/src/lang_helpers/python.rs index 96f979b45..2ddfb7f88 100644 --- a/big-code-analysis-ast/src/lang_helpers/python.rs +++ b/big-code-analysis-ast/src/lang_helpers/python.rs @@ -228,6 +228,18 @@ fn unparenthesized_once<'a>(node: &Node<'a>, cursor: &mut Cursor<'a>) -> Option< node.children_with(cursor).find(not_extra) } +/// Whether `node` is one of the grammar's two extras, a `#` comment or +/// a `\` line continuation: the nodes tree-sitter-python admits between +/// any two tokens, which spell no part of the construct they sit in. +#[inline] +#[must_use] +pub fn python_is_extra(node: &Node) -> bool { + matches!( + node.kind_id().into(), + Python::Comment | Python::LineContinuation + ) +} + /// Whether `node` is a named child that spells an expression or a /// statement rather than one of the grammar's two extras. Both extras /// are *named* nodes, so `is_named` alone takes the first `\` of @@ -235,11 +247,7 @@ fn unparenthesized_once<'a>(node: &Node<'a>, cursor: &mut Cursor<'a>) -> Option< /// string as none (#1830); every selector of "the first real child" /// skips both. fn not_extra(node: &Node) -> bool { - node.is_named() - && !matches!( - node.kind_id().into(), - Python::Comment | Python::LineContinuation - ) + node.is_named() && !python_is_extra(node) } /// Whether `statement` is a bare string statement: an diff --git a/big-code-analysis-ast/src/roles/space_tree_tests.rs b/big-code-analysis-ast/src/roles/space_tree_tests.rs index a63f0d87e..c673eb392 100644 --- a/big-code-analysis-ast/src/roles/space_tree_tests.rs +++ b/big-code-analysis-ast/src/roles/space_tree_tests.rs @@ -154,7 +154,7 @@ fn check_gated( member_owns: OpensSpace, owners: &[&[u16]], defensive: &[u16], - gated: &str, + gated: Option<&str>, ) -> Vec<(String, Answers)> { let mut rows = Vec::new(); let mut seen_kinds = std::collections::BTreeSet::new(); @@ -180,7 +180,7 @@ fn check_gated( promoted, "{kind}: is_func_space is what the walk promotes" ); - if kind == gated { + if gated == Some(kind) { rows.push((node.utf8_text(source).unwrap_or("?").to_owned(), got)); return; } @@ -229,8 +229,8 @@ fn check( owners: &[&[u16]], defensive: &[u16], ) { - let rows = check_gated::(source, expected, member_owns, owners, defensive, ""); - assert!(rows.is_empty(), "no node has the empty kind: {rows:?}"); + let rows = check_gated::(source, expected, member_owns, owners, defensive, None); + assert!(rows.is_empty(), "no kind is gated: {rows:?}"); } #[cfg(feature = "rust")] @@ -869,7 +869,7 @@ fn groovy_space_tree_rows() { member::owns, &[func_opener::OWNERS, closure::OWNERS, container::OWNERS, member::OWNERS], &[], - "record_components", + Some("record_components"), ); assert_eq!( headers, diff --git a/src/metrics/loc/python.rs b/src/metrics/loc/python.rs index 49c120d72..8a08c120f 100644 --- a/src/metrics/loc/python.rs +++ b/src/metrics/loc/python.rs @@ -18,7 +18,8 @@ use super::shared::{ use super::*; use crate::lang_helpers::python::{ python_documentation_string_run, python_is_bare_statement_value, python_is_bare_string, - python_is_bare_string_parenthesis, python_is_bare_string_statement, python_sphinx_doc_comment, + python_is_bare_string_parenthesis, python_is_bare_string_statement, python_is_extra, + python_sphinx_doc_comment, }; impl Loc for PythonCode { @@ -663,12 +664,10 @@ fn python_code_among<'a>( next: &Node<'a>, parens: Option>, ) -> Option { - let mut tokens = siblings.skip_while(|sibling| match sibling.kind_id().into() { - Python::LineContinuation | Python::Comment => true, - Python::LPAREN | Python::RPAREN => { - parens.is_some_and(|chain| python_is_bare_string_parenthesis(sibling, chain)) - } - _ => false, + let mut tokens = siblings.skip_while(|sibling| { + python_is_extra(sibling) + || matches!(sibling.kind_id().into(), Python::LPAREN | Python::RPAREN) + && parens.is_some_and(|chain| python_is_bare_string_parenthesis(sibling, chain)) }); tokens .next() diff --git a/src/metrics/nargs.rs b/src/metrics/nargs.rs index ebbcd8869..03b41bd2f 100644 --- a/src/metrics/nargs.rs +++ b/src/metrics/nargs.rs @@ -885,8 +885,12 @@ impl NArgs for JavaCode { // writes no canonical constructor (#1842) — so the list is the node // itself and its `record_component` children are the arguments, one // wrapper each (a variable-arity component's stray `...` lands in an -// `ERROR` beside its type, inside the one wrapper). Every other -// callable holds its list in the `parameters` field. The header's gate +// `ERROR` beside its type, inside the one wrapper). They are counted by +// kind and not through `count_args`: the two agree on a clean parse, +// but `count_args` takes every child that is no parenthesis, comma or +// comment, so the `ERROR` recovery leaves beside a component +// (`record R(int a,)`) would read as a second argument (#1863). Every +// other callable holds its list in the `parameters` field. The header's gate // reads the body's constructor types, so the callable test is the // `_with_code` spelling, as the shared impl's. impl NArgs for GroovyCode { @@ -4918,6 +4922,60 @@ record A(int x) {}", }); } + /// A header's arguments are its `record_component` children, counted + /// by kind: the `ERROR` recovery leaves in the list beside a + /// component — here for a trailing comma — is none, so the header + /// reads 1. `count_args`, which counts every other callable's list, + /// takes each child that is no parenthesis, comma or comment and + /// reads 2 on this list. The two agree on every clean parse, which + /// is why #1863 proposed swapping one for the other; the swap would + /// move this row. The second assertion keeps that claim honest: a + /// `count_args` that learns to skip an `ERROR` fails it, and the + /// header arm can then share the one definition. + #[cfg(feature = "groovy")] + #[test] + fn groovy_header_counts_components_and_no_recovery_error() { + use crate::languages::language_groovy::Groovy; + let source = "record R(int a,) { }"; + let parser = GroovyParser::new( + source.as_bytes().to_vec(), + std::path::Path::new("trailing.groovy"), + None, + ); + let headers: Vec<_> = parser + .root() + .preorder() + .filter(|node| node.kind_id() == Groovy::RecordComponents) + .map(|header| { + ( + header + .children() + .map(|child| child.kind().to_owned()) + .collect::>(), + count_args::(&header, source.as_bytes()), + ) + }) + .collect(); + assert_eq!( + headers, + [( + ["(", "record_component", "ERROR", ")"] + .map(str::to_owned) + .to_vec(), + 2 + )] + ); + check_spaces::(source, "trailing.groovy", |space| { + assert_eq!( + space_rows(&space), + [ + row("R", SpaceKind::Class, 0), + row("R", SpaceKind::Function, 1), + ] + ); + }); + } + #[cfg(feature = "php")] #[test] fn php_no_functions_and_closures() { diff --git a/src/metrics/npm.rs b/src/metrics/npm.rs index ea2ecbaec..dd14cbcc9 100644 --- a/src/metrics/npm.rs +++ b/src/metrics/npm.rs @@ -358,11 +358,14 @@ macro_rules! impl_npm_java_like { use $lang::*; // Whether a declaration spells `public` in its `modifiers` - // child, the first child when present. Source: + // child, the first child when present, so it is read by + // index: a search for it builds a cursor per declaration. + // Source: // https://docs.oracle.com/javase/tutorial/reflect/member/methodModifiers.html fn has_public_modifier(declaration: &Node) -> bool { declaration - .first_child(|id| id == Modifiers) + .child(0) + .filter(|first| first.kind_id() == Modifiers) .is_some_and(|modifiers| modifiers.first_child(|id| id == Public).is_some()) } diff --git a/tests/parity/ops_metrics_space_parity.rs b/tests/parity/ops_metrics_space_parity.rs index bfc54cb2e..181120f6e 100644 --- a/tests/parity/ops_metrics_space_parity.rs +++ b/tests/parity/ops_metrics_space_parity.rs @@ -382,6 +382,17 @@ fn ops_and_metrics_agree_on_the_space_tree() { first_divergence(&from_metrics, &from_ops), ); + // The record's header space must be there to compare. Dropped by + // both walks it leaves the trees equal, and the fixture's other + // members keep `space.spaces` non-empty, so neither assertion + // around this one would see it go. + if matches!(lang, LANG::Java | LANG::Groovy) { + assert!( + from_metrics.contains("Function Some(\"R\")"), + "{lang:?}: the record's header opened no space:\n{from_metrics}" + ); + } + // A fixture whose only space is the file root would satisfy the // assertion above no matter how badly the two walks disagreed // about nested spaces — which is precisely the #1130 shape. The From 1642a96300e9e658c56e555c19fad9ada7c05c6d Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Wed, 11 Nov 2026 18:14:41 -0800 Subject: [PATCH 10/21] docs(changelog): record the #1863 follow-ups One entry under Changed for the AST-crate trait change and what came with it (the byte-axis backstop and the three re-declared gates, the record-header projection, the header-type hoist and its probes), and one under Fixed for the Python `loc` fold. Neither moves a metric value. Refs #1863 --- CHANGELOG.md | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index c17c89043..67808c539 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -70,6 +70,35 @@ for historical reference. a survey of every production read found no consumer asking a projection outside its role's profile, and which projection a consumer reads remains the manual check the module doc names. +- **`big-code-analysis-ast`: every language writes the space-tree + predicates, and the byte-less `Checker::is_func` is removed** (#1863). + `Checker::is_func_with_code`, `Checker::is_func_space_with_code` and + `Getter::get_space_kind_with_code` defaulted to their byte-less + spellings, so a language that wrote only the byte-less one handed a + text-gated role row no bytes, silently. The three are now required + methods, and `is_func_space` and `get_space_kind` default to the + with-code form asked with no bytes and a known-empty chain. + `Checker::is_func` answered three different questions across the + languages and is gone; its readers ask `is_func_with_code`. + `Checker::holds_doc_comment_in_body` gains a `code` parameter for the + same test. The crate is outside `STABILITY.md`, and no item this + crate re-exports changes. Metric values are unchanged. With it: + - The derived role suite gains a byte-axis backstop, + `unmarked_owners_answer_alike_without_the_bytes`: every owner a row + does not mark `text_gated_by` must answer alike with the source + bytes and without. It found three gates that read bytes under a + plain `gated_by`, now re-declared: the Tcl family's + `is_braced_literal` and Bash's `comparison_operator` and + `short_circuit_operator`. The keyword changes no answer. + - `roles::java::record_header` and `roles::groovy::record_header` + name a record's component list once; the header gate, the space's + name, `nargs` and `npm` read them where each spelled the field or + the kind pair itself. + - The record-header gate reads the header's component types once per + evaluation rather than once per constructor it compares. New + scaling probes `nargs/java-record-alternative-ctors` and + `nargs/groovy-record-alternative-ctors` price the gate's scan of a + record's body. - **Release packaging tools are upgraded**: cargo-about 0.9.3, cargo-deb 3.8.0, cargo-generate-rpm 0.21.1 and cargo-cyclonedx 0.5.10. Three outputs change: @@ -302,6 +331,19 @@ for historical reference. `ChildAncestors` and `Ancestors` keep their signatures. New scaling probes `npa/ruby-nested-classes`, `npm/ruby-nested-classes` and their `loc` control price it. +- **Python `loc` stays linear over a docstring nested in parentheses + that each open with bare `\` rows** (#1863). A bare `\` row inside a + parenthesised docstring asks whether code precedes its parenthesis on + the logical line, and the answer is read at the nearest enclosing + level that holds a token before its node. Where every level holds + only comments and `\` rows, each of `n` nested parentheses read every + level above it, quadratic in `n` up to the 200 levels Python's + tokenizer allows. The answer is now folded down the walk's ancestor + chain, so a parenthesis reads three levels: at 200 levels with 30 + such rows each, a 37 KB file, the `loc` walk took 92 ms and takes + 5.3 ms (one run each, on a host that was not idle). Metric values are + unchanged. New scaling probe `loc/python-deep-paren-extra-prefix` + prices it. - **`cognitive` stays linear over functions in nested containers** (#1864). The walk asks every function definition whether another function encloses it, to charge a nested function its depth, and From 6e9ab71484c6dd74ccf187c9bb2c0e7f8b050b13 Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Wed, 11 Nov 2026 18:18:45 -0800 Subject: [PATCH 11/21] docs(bench): unlink a private const from a public shape's doc `python_deep_paren_extra_prefix` is `pub` and its doc linked the private `PAREN_PREFIX_PAIRS`, which `make doc-check` rejects (`rustdoc::private_intra_doc_links`). `make pre-commit` named the stage. Refs #1863 --- big-code-analysis-bench/src/shapes.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/big-code-analysis-bench/src/shapes.rs b/big-code-analysis-bench/src/shapes.rs index 43278c483..d60500280 100644 --- a/big-code-analysis-bench/src/shapes.rs +++ b/big-code-analysis-bench/src/shapes.rs @@ -466,7 +466,7 @@ pub fn python_bare_runs_before_string(width: usize) -> String { const PAREN_PREFIX_PAIRS: usize = 30; /// Python: a bare string `depth` parentheses deep, each parenthesis -/// opening with [`PAREN_PREFIX_PAIRS`] one-row bare `\` runs, each +/// opening with `PAREN_PREFIX_PAIRS` one-row bare `\` runs, each /// joining a comment row, before the next parenthesis; then a retained /// `x = 1`. /// From 9e09880737f84d369e4b9dd6faa62d3ceae393d0 Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Wed, 11 Nov 2026 18:56:59 -0800 Subject: [PATCH 12/21] refactor(roles,nargs): apply the simplify-rust pass over the #1863 batch - `is_record_header(list, record)` beside each `record_header` states "this list is that record's header" once. The gate, the two getters and Java's `params_owner` each spelled the id comparison. - `opens_record_header` holds the header's component types in a `LazyCell` rather than an `Option` filled through `get_or_insert_with`, which drops a `mut`, a shadowing rebind and, in Groovy, a block used as an `&&` operand. Still one read per evaluation, on the first constructor; the count tests are unchanged. - `record_header_types_read` is read by this crate's tests only, so its accessor takes the default `cfg(test)` gate. - `byte_less_is_closure_reads_only_rows_without_a_text_gate` in `nargs.rs` is removed. With its `FuncOpener` half gone (#1863) its seven rows were a subset of the same-named test in `nom.rs`, which pins every language's `Closure` row, and its doc named the wrong set of impls. The `nom.rs` test now says it stands for `NArgs` too. - Comments: two stale sentences about the callable test's spelling (`nargs.rs`, `spaces_tests.rs`), Elixir's byte-less spelling (`checker.rs`), exact test names in the `record_header` docs, two rename slips, and five paragraphs re-wrapped. No behaviour changes. Findings of three read-only review agents (reuse, clarity, efficiency). Declined: a macro for the 75 identical space-tree forwards (50 files of churn for code this change did not add), and keying `BYTE_GATE_FIXTURES` by `LANG` (the per-language test gate check rejects it without a hand-written marker; the file's other exception tables are keyed by table name). Refs #1863 --- .bca-baseline.toml | 4 +- big-code-analysis-ast/src/checker.rs | 2 +- big-code-analysis-ast/src/getter/groovy.rs | 10 +++-- big-code-analysis-ast/src/getter/java.rs | 9 ++-- big-code-analysis-ast/src/roles/bash.rs | 15 ++++--- big-code-analysis-ast/src/roles/groovy.rs | 47 ++++++++++--------- big-code-analysis-ast/src/roles/java.rs | 34 ++++++++------ big-code-analysis-ast/src/roles/mod.rs | 3 +- src/metrics/cognitive.rs | 2 +- src/metrics/nargs.rs | 52 ++++------------------ src/metrics/nom.rs | 7 ++- src/metrics/wmc.rs | 6 +-- src/spaces_tests.rs | 4 +- 13 files changed, 90 insertions(+), 105 deletions(-) diff --git a/.bca-baseline.toml b/.bca-baseline.toml index 97c426025..6476bd9c8 100644 --- a/.bca-baseline.toml +++ b/.bca-baseline.toml @@ -365,7 +365,7 @@ value = 906.0 path = "big-code-analysis-ast/src/roles/mod.rs" qualified = "" metric = "loc.sloc" -value = 2322.0 +value = 2321.0 [[entry]] path = "big-code-analysis-ast/src/tools.rs" @@ -1265,7 +1265,7 @@ value = 5.0 path = "src/metrics/nargs.rs" qualified = "" metric = "loc.ploc" -value = 525.0 +value = 524.0 [[entry]] path = "src/metrics/npa/php.rs" diff --git a/big-code-analysis-ast/src/checker.rs b/big-code-analysis-ast/src/checker.rs index eb8a0f2b8..60535004d 100644 --- a/big-code-analysis-ast/src/checker.rs +++ b/big-code-analysis-ast/src/checker.rs @@ -130,7 +130,7 @@ macro_rules! impl_byte_gated_row_predicate { // design and keeps a hand-written forward pinned at runtime instead // (`ruby_byte_less_spellings_stay_the_kind_table`), as C#'s is since // #1828 (`csharp_byte_less_spellings_omit_the_primary_constructor`); -// Elixir overrides both spellings. Per-language rationale — which +// Elixir hand-writes the byte-less one. Per-language rationale — which // rows, what the gated one reads — sits above the invocation. macro_rules! impl_byte_less_func_space { ($roles:ident) => { diff --git a/big-code-analysis-ast/src/getter/groovy.rs b/big-code-analysis-ast/src/getter/groovy.rs index e35c2cf6c..def7db545 100644 --- a/big-code-analysis-ast/src/getter/groovy.rs +++ b/big-code-analysis-ast/src/getter/groovy.rs @@ -58,10 +58,12 @@ impl Getter for GroovyCode { return Some(""); } // A record's header takes the record's name (#1842). - crate::getter::func_space_name_from_owner(node, code, ancestors, |list, owner| { - crate::roles::groovy::record_header(owner) - .is_some_and(|header| header.id() == list.id()) - }) + crate::getter::func_space_name_from_owner( + node, + code, + ancestors, + crate::roles::groovy::is_record_header, + ) } // The mapping is the `opens` annotations of `roles/groovy.rs` diff --git a/big-code-analysis-ast/src/getter/java.rs b/big-code-analysis-ast/src/getter/java.rs index 3d0fa8715..186eb3754 100644 --- a/big-code-analysis-ast/src/getter/java.rs +++ b/big-code-analysis-ast/src/getter/java.rs @@ -43,9 +43,12 @@ impl Getter for JavaCode { return Some(""); } // A record's header takes the record's name (#1842). - crate::getter::func_space_name_from_owner(node, code, ancestors, |list, owner| { - crate::roles::java::record_header(owner).is_some_and(|header| header.id() == list.id()) - }) + crate::getter::func_space_name_from_owner( + node, + code, + ancestors, + crate::roles::java::is_record_header, + ) } // The mapping is the `opens` annotations of `roles/java.rs` (#1696): diff --git a/big-code-analysis-ast/src/roles/bash.rs b/big-code-analysis-ast/src/roles/bash.rs index ceb9ed05a..b9529c5a2 100644 --- a/big-code-analysis-ast/src/roles/bash.rs +++ b/big-code-analysis-ast/src/roles/bash.rs @@ -94,9 +94,10 @@ role_table! { // `-a` / `-o` connectives, so that payer is text-gated: a // `test_operator` pays as a comparison exactly when its bytes are // not a connective — and so is the owner, whose gate reads the same - // bytes off its `operator` field (#1863). `=` compares inside a test and assigns inside - // `(( … ))`, which only the test's descent can tell (#1536); the - // ABC consumer counts it from the test, as its own extra. + // bytes off its `operator` field (#1863). `=` compares inside a test + // and assigns inside `(( … ))`, which only the test's descent can + // tell (#1536); the ABC consumer counts it from the test, as its own + // extra. Comparison { owns [ BinaryExpression(text_gated_by comparison_operator no_chain), @@ -122,10 +123,10 @@ role_table! { // `&&` / `||` join two commands in a `list` and two tests inside // `[[ … ]]` / `(( … ))` in a `binary_expression`; inside `[ … ]` the // same join is the `-a` / `-o` spelling of `test_operator`, read by - // text, at the payer and at the owner alike. Bash's `&&` / `||` are command-list separators, so the ABC - // consumer reads this row for nothing (#1536 — Fitzpatrick Rule 9 - // does not map onto its grammar) where cyclomatic and cognitive - // read it. + // text, at the payer and at the owner alike. Bash's `&&` / `||` are + // command-list separators, so the ABC consumer reads this row for + // nothing (#1536 — Fitzpatrick Rule 9 does not map onto its grammar) + // where cyclomatic and cognitive read it. ShortCircuit { owns [ List, diff --git a/big-code-analysis-ast/src/roles/groovy.rs b/big-code-analysis-ast/src/roles/groovy.rs index 0aeeadbd2..048c5763f 100644 --- a/big-code-analysis-ast/src/roles/groovy.rs +++ b/big-code-analysis-ast/src/roles/groovy.rs @@ -5,6 +5,8 @@ //! `Catch`, `ElseIf`, `Exit` (#1697) — and //! the documentation rows (#1699) are declared. +use std::cell::LazyCell; + use crate::getter::node_text; use crate::lang_helpers::doc_comment::{java_doc, node_bytes, token_spelling}; use crate::role_table; @@ -100,10 +102,10 @@ fn groovy_parameter_type(param: &Node<'_>, code: &[u8]) -> Option> { /// with as many formal parameters as the record's header has /// `components` — their types, read once per header by /// [`opens_record_header`] — each spelling the same type as its -/// component (Java's -/// rule, JLS 8.10.4.1 and 8.8, which Groovy records follow). Parameter -/// names and annotations do not take part. The same spelling, not the -/// same type — the tokens, so a comment inside the type is nothing — +/// component (Java's rule, JLS 8.10.4.1 and 8.8, which Groovy records +/// follow). Parameter names and annotations do not take part. The same +/// spelling, not the same type — the tokens, so a comment inside the +/// type is nothing — /// so `java.util.List` and `List` are two spellings here, as in /// `roles/java.rs`. The name test is for the grammar, not the language: /// the grammar does not check a constructor's name, so `record R(int a) @@ -153,7 +155,7 @@ fn is_record_canonical_constructor( /// (#1842), and Java's twin (`roles/java.rs`, the rationale there). /// `None` for any other node. Held once for the row's gate and for the /// consumers that step between a record and its header (#1863); pinned -/// by `record_header_is_the_records_own_list`. +/// by `groovy_record_header_is_the_records_own_list`. #[inline] #[must_use] pub fn record_header<'a>(record: &Node<'a>) -> Option> { @@ -162,6 +164,14 @@ pub fn record_header<'a>(record: &Node<'a>) -> Option> { .flatten() } +/// Whether `list` is `record`'s [`record_header`]: the same node, not +/// one of its kind. +#[inline] +#[must_use] +pub fn is_record_header(list: &Node<'_>, record: &Node<'_>) -> bool { + record_header(record).is_some_and(|header| header.id() == list.id()) +} + /// Whether a `record_components` list is a record's header in a record /// that declares no canonical constructor, so the header stands for /// the implicitly declared one (#1842): the record's [`record_header`], @@ -177,34 +187,29 @@ fn opens_record_header<'a>(node: &Node<'a>, code: &[u8], ancestors: Ancestors<'a let Some(record) = ancestors.parent(node) else { return false; }; - if record_header(&record).is_none_or(|header| header.id() != node.id()) { + if !is_record_header(node, &record) { return false; } let Some(body) = record.child_by_field_name("body") else { return true; }; - let mut components = None; + let components = LazyCell::new(|| { + record_header_types_read::record(); + node.children() + .filter(|p| p.kind_id() == Groovy::RecordComponent as u16) + .map(|p| groovy_parameter_type(&p, code)) + .collect::>() + }); !body.children().any(|member| { - member.kind_id() == Groovy::ConstructorDeclaration as u16 && { - let components = components.get_or_insert_with(|| { - record_header_types_read::record(); - node.children() - .filter(|p| p.kind_id() == Groovy::RecordComponent as u16) - .map(|p| groovy_parameter_type(&p, code)) - .collect::>() - }); - is_record_canonical_constructor(&member, &record, components, code) - } + member.kind_id() == Groovy::ConstructorDeclaration as u16 + && is_record_canonical_constructor(&member, &record, &components, code) }) } // Times `opens_record_header` spelled a header's component types: once // per evaluation that meets a constructor, as Java's twin counts // (`roles/java.rs`, #1863). -crate::observation::counter!( - record_header_types_read, - cfg(any(test, feature = "test-support")) -); +crate::observation::counter!(record_header_types_read); /// Java's eight primitive type keywords and `void`, which Groovy /// reserves as Java does. diff --git a/big-code-analysis-ast/src/roles/java.rs b/big-code-analysis-ast/src/roles/java.rs index 70c2f63ce..9c1684863 100644 --- a/big-code-analysis-ast/src/roles/java.rs +++ b/big-code-analysis-ast/src/roles/java.rs @@ -7,6 +7,8 @@ //! `Catch`, `ElseIf`, `Exit` (#1697) — and //! the documentation rows (#1699) are declared. +use std::cell::LazyCell; + use crate::checker::java_anonymous_class_body; use crate::lang_helpers::doc_comment::{java_doc, node_bytes, token_spelling}; use crate::role_table; @@ -166,23 +168,22 @@ fn opens_record_header<'a>(node: &Node<'a>, code: &[u8], ancestors: Ancestors<'a let Some(record) = ancestors.parent(node) else { return false; }; - if record_header(&record).is_none_or(|header| header.id() != node.id()) { + if !is_record_header(node, &record) { return false; } let Some(body) = record.child_by_field_name("body") else { return true; }; - let mut components = None; + let components = LazyCell::new(|| { + record_header_types_read::record(); + node.children() + .filter_map(|p| java_parameter_type(&p, code)) + .collect::>() + }); !body.children().any(|member| match member.kind_id().into() { Java::CompactConstructorDeclaration => true, Java::ConstructorDeclaration => { - let components = components.get_or_insert_with(|| { - record_header_types_read::record(); - node.children() - .filter_map(|p| java_parameter_type(&p, code)) - .collect::>() - }); - is_record_canonical_constructor(&member, &record, components, code) + is_record_canonical_constructor(&member, &record, &components, code) } _ => false, }) @@ -197,7 +198,7 @@ fn opens_record_header<'a>(node: &Node<'a>, code: &[u8], ancestors: Ancestors<'a /// recognise, held once for the row's gate and for the consumers that /// step between a record and its header — the space's name, `nargs`' /// parameter owner, `npm`'s method count (#1863); pinned by -/// `record_header_is_the_records_own_list`. +/// `java_record_header_is_the_records_own_list`. #[inline] #[must_use] pub fn record_header<'a>(record: &Node<'a>) -> Option> { @@ -206,14 +207,19 @@ pub fn record_header<'a>(record: &Node<'a>) -> Option> { .flatten() } +/// Whether `list` is `record`'s [`record_header`]: the same node, not +/// one of its kind. +#[inline] +#[must_use] +pub fn is_record_header(list: &Node<'_>, record: &Node<'_>) -> bool { + record_header(record).is_some_and(|header| header.id() == list.id()) +} + // Times `opens_record_header` spelled a header's component types. Once // per evaluation that meets a constructor, however many it compares: // re-spelled per constructor the gate answers the same, a third slower // on a record of alternatives (#1863). -crate::observation::counter!( - record_header_types_read, - cfg(any(test, feature = "test-support")) -); +crate::observation::counter!(record_header_types_read); /// The container a `switch` nests its arms in: the `switch_block`, the /// `Switch` owner's child — a structural fact about the construct the diff --git a/big-code-analysis-ast/src/roles/mod.rs b/big-code-analysis-ast/src/roles/mod.rs index 1cd1efaae..1e9eb9c02 100644 --- a/big-code-analysis-ast/src/roles/mod.rs +++ b/big-code-analysis-ast/src/roles/mod.rs @@ -235,8 +235,7 @@ //! rejects it (#1793). //! - `callable` marks a `FuncOpener` owner that is a *named function* — //! what `Checker::is_func_with_code` answers — beside openers that are -//! not -//! (Java's `static { … }` opens a `Function` space and is nobody's +//! not (Java's `static { … }` opens a `Function` space and is nobody's //! callee; Elixir's `fn … end` opens one and is a `Closure`), and //! `callable_when f` one that is a named function only where `f` says //! so, under a gate of its own beside the owner's — a JS diff --git a/src/metrics/cognitive.rs b/src/metrics/cognitive.rs index 451ccfcd3..8390d019e 100644 --- a/src/metrics/cognitive.rs +++ b/src/metrics/cognitive.rs @@ -11030,7 +11030,7 @@ end", // expected: nesting.conditional 2 from `outer`'s two `if`s, so the // callback's own `if` costs +3. The `nom` assertion states the // premise — that this shape really is on the closure side of - // function / closure split — rather than leaving it implied. + // the function / closure split — rather than leaving it implied. check_func_space::( "function outer(a, b) { if (a) { if (b) { run(function (c) { if (c) { return 1; } }); } } diff --git a/src/metrics/nargs.rs b/src/metrics/nargs.rs index 03b41bd2f..8adf553e9 100644 --- a/src/metrics/nargs.rs +++ b/src/metrics/nargs.rs @@ -852,18 +852,17 @@ impl NArgs for CsharpCode { // constructor (#1842, revisiting #1160's "declared code rather than // generated code": the component list *is* declared, as a C# positional // record's is — #1828), so the list's owner is the record whose -// `record_header` it is (`roles/java.rs`). The row's gate keeps the count to one owner: with a compact -// constructor the header opens nothing and the redirect counts the -// components there; with neither the header is the callable. A -// non-canonical constructor is a callable of its own, owns its own -// list, and suppresses nothing. +// `record_header` it is (`roles/java.rs`). The row's gate keeps the +// count to one owner: with a compact constructor the header opens +// nothing and the redirect counts the components there; with neither +// the header is the callable. A non-canonical constructor is a callable +// of its own, owns its own list, and suppresses nothing. impl NArgs for JavaCode { fn params_owner<'tree>(node: &Node<'tree>, ancestors: Ancestors<'tree, '_>) -> Node<'tree> { let record = match node.kind_id().into() { - Java::FormalParameters => ancestors.parent(node).filter(|record| { - crate::roles::java::record_header(record) - .is_some_and(|header| header.id() == node.id()) - }), + Java::FormalParameters => ancestors + .parent(node) + .filter(|record| crate::roles::java::is_record_header(node, record)), Java::CompactConstructorDeclaration => ancestors .iter(node) .nth(1) @@ -890,9 +889,7 @@ impl NArgs for JavaCode { // but `count_args` takes every child that is no parenthesis, comma or // comment, so the `ERROR` recovery leaves beside a component // (`record R(int a,)`) would read as a second argument (#1863). Every -// other callable holds its list in the `parameters` field. The header's gate -// reads the body's constructor types, so the callable test is the -// `_with_code` spelling, as the shared impl's. +// other callable holds its list in the `parameters` field. impl NArgs for GroovyCode { fn compute<'a>(node: &Node<'a>, code: &[u8], ancestors: Ancestors<'a, '_>, stats: &mut Stats) { use crate::languages::language_groovy::Groovy; @@ -947,37 +944,6 @@ mod tests { // count is only observable one space at a time. check_func_space_only_shim!(check_spaces, Nargs); - /// Every `compute` impl above reads the byte-less `is_closure`: it - /// hands the walk's chain through and no bytes, which answers the - /// `Closure` row's question only while no owner of that row is - /// `text_gated_by`. This pins that for the impls that spell the - /// call themselves — a row that grows a text gate fails here, - /// naming the impl that must stop dropping the bytes rather than - /// silently missing the gated owner (#1696 AC 3). The callable half - /// needs no such pin since #1863: every impl asks - /// `is_func_with_code`, the only spelling. The rows are - /// declarations, built in every feature set, so this needs no - /// grammar. - #[test] - fn byte_less_is_closure_reads_only_rows_without_a_text_gate() { - use crate::roles::{elixir, go, groovy, java, kotlin, lua, perl}; - let rows: &[(&str, bool)] = &[ - ("go Closure", go::closure::TEXT_GATED), - ("kotlin Closure", kotlin::closure::TEXT_GATED), - ("lua Closure", lua::closure::TEXT_GATED), - ("perl Closure", perl::closure::TEXT_GATED), - ("java Closure", java::closure::TEXT_GATED), - ("groovy Closure", groovy::closure::TEXT_GATED), - ("elixir Closure", elixir::closure::TEXT_GATED), - ]; - for (row, text_gated) in rows { - assert!( - !text_gated, - "{row} grew a text gate: its `NArgs::compute` must stop reading the byte-less `is_closure`" - ); - } - } - /// Regression for #227: a `Stats::default()` that never sees an /// observation must not leak the `usize::MAX` sentinel for /// `fn_args_min` or `closure_args_min`. Both getters collapse diff --git a/src/metrics/nom.rs b/src/metrics/nom.rs index 4710d1f43..c0f33e881 100644 --- a/src/metrics/nom.rs +++ b/src/metrics/nom.rs @@ -299,7 +299,10 @@ mod tests { /// `Nom::compute` reads the byte-less `is_closure` for every /// language, which hands the walk's chain through and no bytes to /// the `Closure` row — the row's answer only while no owner is - /// `text_gated_by`. Every row is pinned here, so one that grows a + /// `text_gated_by`. `NArgs::compute` reads the same spelling of + /// the same rows, in the shared impl and in each override that + /// tests for a closure, and has no pin of its own since #1863. + /// Every row is pinned here, so one that grows a /// text gate names the impl that must move to a `_with_code` /// spelling (#1696 AC 3); Ruby's chain-reading gate is answered /// with the chain and is not what this pins. The rows are @@ -336,7 +339,7 @@ mod tests { for (lang, text_gated) in rows { assert!( !text_gated, - "{lang}'s Closure row grew a text gate: `Nom::compute` must read a `_with_code` spelling" + "{lang}'s Closure row grew a text gate: `Nom::compute` and `NArgs::compute` must read a `_with_code` spelling" ); } } diff --git a/src/metrics/wmc.rs b/src/metrics/wmc.rs index 930383366..68421e9a1 100644 --- a/src/metrics/wmc.rs +++ b/src/metrics/wmc.rs @@ -2668,9 +2668,9 @@ mod tests { // charged to the enclosing class space without WMC ever seeing // it, and `bca check` could not flag one however complex it got. // - // WMC keys on `SpaceKind::Function` rather than on the callable test, - // which is why this moves even though the block is deliberately - // *not* a callable (it is not a callable anyone names). + // WMC keys on `SpaceKind::Function` rather than on the callable + // test, which is why this moves even though the block is + // deliberately *not* a callable (nobody names it at a call site). check_metrics::( "class C(val n: Int) { // +1 since #1828 init { // +1 since #1184 diff --git a/src/spaces_tests.rs b/src/spaces_tests.rs index 6e3ec25dd..82877ab68 100644 --- a/src/spaces_tests.rs +++ b/src/spaces_tests.rs @@ -152,8 +152,8 @@ fn mozcpp_bodiless_specifiers_open_no_space_1555() { /// `get_space_kind_with_code` — the spellings the walker calls — agree on /// every struct / class specifier node, checked node by node because the /// space tree alone cannot see the getter half: it only labels spaces the -/// checker already opened. Today both forward to `is_func_space` / -/// `get_space_kind`, so only a `_with_code` override could split them +/// checker already opened. Both read the role table's `opens_space` +/// fold, so only a hand-written spelling could split them /// (grammar-dispatch §7). The oracle is independent of the `body` field: /// a specifier defines a type exactly when its text has a `{`. #[cfg(any(feature = "cpp", feature = "mozcpp"))] From 8061e967b9e21116127060faaafa4ac1257fceac Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Wed, 11 Nov 2026 18:57:14 -0800 Subject: [PATCH 13/21] perf(loc/python): memoise the code-before climb per level, not on a fold lane MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 798ee09c folded "does code precede this parenthesis on its logical line" down the walk's chain. That fixed the nest it was written for and made another shape quadratic that `main` reads in linear time. A fold evaluates every ancestor, the ones above the nearest answer included, and stores an ancestor's state under the child on the path. That is free where the step is a kind test. Here a level's answer is a scan of the comments and `\` splices before it. In an `if` block that opens with `k` comment rows and holds `n` parenthesised strings, each string's own statement answers, yet the fold read the block's level, the scan of the `k` comments, once per statement: `n × k` where the climb costs `n + k`. Unlike the nest, this shape has no 200-level cap. `Ancestors::nearest_level_answer` now memoises the climb itself. It stops at the first level that answers or already holds an answer, and hands what it found to the levels it passed (`LevelQuestion`, a `NodeMemo` keyed by level). A level is read at most once per walk and never above the nearest answer. `FoldLane::CodeBeforeOnLine` is gone. `fold_down`'s doc states what a step costs. Scaling (`cargo bench -p big-code-analysis-bench --bench scaling -- --no-gate`, one run each, host not idle): probe climb fold memo loc/python-deep-paren-extra-prefix 1.96 1.06 0.93 loc/python-block-comments-paren-strings 1.08 2.02 1.04 Top rungs: 100 ms climbed against 4.7 ms on the first; 763 ms folded against 28 ms on the second, which is new. Each defect passes the other probe, so both stay. `python_code_before_a_parenthesis_reads_each_level_once` pins the levels read on both shapes at size 40: 81 and 81; 900 and 81 climbed; 120 and 122 folded. `nearest_level_answer_answers_the_climb_on_every_path` counts the answer fn's calls per ask, which is what tells a memo from a climb. `make chain-audit` passes. No `loc` value moves. Also parenthesises the `||` / `&&` in `python_code_among`. Found by the efficiency agent of the simplify-rust pass. Refs #1863 --- .bca-baseline.toml | 8 +- CHANGELOG.md | 13 +- big-code-analysis-ast/src/lib.rs | 2 +- big-code-analysis-ast/src/node.rs | 80 +++++++---- big-code-analysis-ast/src/node/ancestors.rs | 145 ++++++++++++-------- big-code-analysis-bench/src/shapes.rs | 102 +++++++++++++- docs/development/benchmarking.md | 101 +++++++++----- src/metrics/loc.rs | 83 ++++++----- src/metrics/loc/python.rs | 27 ++-- 9 files changed, 378 insertions(+), 183 deletions(-) diff --git a/.bca-baseline.toml b/.bca-baseline.toml index 6476bd9c8..564b66546 100644 --- a/.bca-baseline.toml +++ b/.bca-baseline.toml @@ -299,25 +299,25 @@ value = 43.0 path = "big-code-analysis-ast/src/node/ancestors.rs" qualified = "" metric = "loc.ploc" -value = 690.0 +value = 704.0 [[entry]] path = "big-code-analysis-ast/src/node/ancestors.rs" qualified = "" metric = "loc.sloc" -value = 1470.0 +value = 1501.0 [[entry]] path = "big-code-analysis-ast/src/node/ancestors.rs" qualified = "Ancestors<'tree, 'chain>" metric = "nom" -value = 45.0 +value = 44.0 [[entry]] path = "big-code-analysis-ast/src/node/ancestors.rs" qualified = "Ancestors<'tree, 'chain>" metric = "wmc" -value = 81.0 +value = 84.0 [[entry]] path = "big-code-analysis-ast/src/node/ancestors.rs" diff --git a/CHANGELOG.md b/CHANGELOG.md index 67808c539..d2825f620 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -338,12 +338,13 @@ for historical reference. level that holds a token before its node. Where every level holds only comments and `\` rows, each of `n` nested parentheses read every level above it, quadratic in `n` up to the 200 levels Python's - tokenizer allows. The answer is now folded down the walk's ancestor - chain, so a parenthesis reads three levels: at 200 levels with 30 - such rows each, a 37 KB file, the `loc` walk took 92 ms and takes - 5.3 ms (one run each, on a host that was not idle). Metric values are - unchanged. New scaling probe `loc/python-deep-paren-extra-prefix` - prices it. + tokenizer allows. Each level's answer is now memoised for the walk, + so a parenthesis reads two levels: at 200 levels with 30 such rows + each, a 37 KB file, the `loc` walk took 100 ms and takes 4.7 ms (one + run each, on a host that was not idle). Metric values are unchanged. + New scaling probes `loc/python-deep-paren-extra-prefix` and + `loc/python-block-comments-paren-strings` price it, the second for + the levels above the nearest answer, which are never read. - **`cognitive` stays linear over functions in nested containers** (#1864). The walk asks every function definition whether another function encloses it, to charge a nested function its depth, and diff --git a/big-code-analysis-ast/src/lib.rs b/big-code-analysis-ast/src/lib.rs index 9a9d4ac4a..24d455f31 100644 --- a/big-code-analysis-ast/src/lib.rs +++ b/big-code-analysis-ast/src/lib.rs @@ -141,7 +141,7 @@ pub use crate::macros::ParseLangError; pub(crate) use crate::node::FoldLane; pub use crate::node::{Ancestors, ChildAncestors, FoldCache, Node, SiblingCache}; #[doc(hidden)] -pub use crate::node::{GateLane, KindLane, LevelLane, NodeQuestion}; +pub use crate::node::{GateLane, KindLane, LevelQuestion, NodeQuestion}; pub use crate::parser::Parser; pub use crate::preproc::{ PreprocDiagnostic, PreprocFile, PreprocResults, fix_includes, get_macros, preprocess, diff --git a/big-code-analysis-ast/src/node.rs b/big-code-analysis-ast/src/node.rs index 468d0565d..783d879be 100644 --- a/big-code-analysis-ast/src/node.rs +++ b/big-code-analysis-ast/src/node.rs @@ -19,7 +19,7 @@ pub use ancestors::{AncestorIter, Ancestors, ChildAncestors, FoldCache, SiblingC pub(crate) use ancestors::{FoldLane, MemoQuestion, NodeMemo, WordSlot}; #[doc(hidden)] pub use ancestors::{ - GateLane, KindLane, LevelLane, NodeQuestion, WIDE_PARENT, child_chains_derived, + GateLane, KindLane, LevelQuestion, NodeQuestion, WIDE_PARENT, child_chains_derived, fold_slot_probes, fold_steps, sibling_cache_reads, sibling_seeks, }; @@ -2356,58 +2356,69 @@ mod tests { } /// `nearest_level_answer` answers what the climb answers through - /// all three of its paths — the walk's memoised fold, a known chain - /// with no cache, the chainless climb — for every node of the - /// fixture (#1863). + /// all three of its paths — the walk's memo, a known chain with no + /// cache, the chainless climb — for every node of the fixture + /// (#1863). /// /// The answer fn says "yes" at a function and "no" at a closure, so /// a node inside a closure inside a function reads the closure's - /// "no": the nearer answer replaces the outer one, where a fold - /// that only ever set its state would read "yes". A node under - /// neither reads `false`, and the answering node itself is not - /// asked: a function's own answer is its ancestors'. The second - /// cache is asked only at integer literals, so each ask meets the - /// slots the previous literal's chain left under other parents. + /// "no": the nearer answer wins. A node under neither reads `false`, + /// and the answering node itself is not asked: a function's own + /// answer is its ancestors'. + /// + /// The second cache is asked only at integer literals, and the + /// answer fn's calls are counted per ask, which is the memo's whole + /// effect: the answers cannot tell it from the climb. `2` meets the + /// answer `1` left on their shared `binary_expression`; `4` reads + /// its own `let` and meets the one `3` left on the block they + /// share, a level `3` passed without an answer. `3` sits in the + /// tuple after the closure: a memo that handed `1`'s "no" to a + /// level above the closure would answer "no" for it. #[cfg(feature = "rust")] #[test] fn nearest_level_answer_answers_the_climb_on_every_path() { - use crate::node::{FoldCache, LevelLane}; + use crate::node::{FoldCache, LevelQuestion}; + use std::cell::Cell; + thread_local! { + static LEVELS_ASKED: Cell = const { Cell::new(0) }; + } fn level(_code: &[u8], node: &Node, _chain: Ancestors) -> Option { + LEVELS_ASKED.set(LEVELS_ASKED.get() + 1); match node.kind() { "function_item" => Some(true), "closure_expression" => Some(false), _ => None, } } - let code = b"fn f() { let c = || { let d = (1 + 2); }; let e = 3; }\n\ - const K: u8 = 4;\n\ - mod m { fn g() { let h = || 5; } fn i() { 6; } }\n"; + let code = b"fn f() { let c = (|| { let d = (1 + 2); }, 3); let e = 4; }\n\ + const K: u8 = 5;\n\ + mod m { fn g() { let h = || 6; } fn i() { 7; } }\n"; let cache = FoldCache::default(); let asked_at_literals = FoldCache::default(); - let lane = LevelLane::CodeBeforeOnLine; + let question = LevelQuestion::CodeBeforeOnLine; let mut literals = Vec::new(); let (mut yes, mut no) = (0_usize, 0_usize); for_each_node_with_chain::(code, |node, chain| { let expected = std::iter::successors(node.parent(), Node::parent) .find_map(|ancestor| level(code, &ancestor, Ancestors::unknown())) .unwrap_or(false); - let folded = Ancestors::known(chain) + let memoised = Ancestors::known(chain) .with_folds(&cache) - .nearest_level_answer(node, lane, code, level); - let chained = Ancestors::known(chain).nearest_level_answer(node, lane, code, level); - let climbed = Ancestors::unknown().nearest_level_answer(node, lane, code, level); + .nearest_level_answer(node, question, code, level); + let chained = Ancestors::known(chain).nearest_level_answer(node, question, code, level); + let climbed = Ancestors::unknown().nearest_level_answer(node, question, code, level); let (kind, start) = (node.kind(), node.start_byte()); assert_eq!( - (folded, chained, climbed), + (memoised, chained, climbed), (expected, expected, expected), - "{kind} at byte {start}: (folded, chained, climbed) must all be the climb's answer" + "{kind} at byte {start}: (memoised, chained, climbed) must all be the climb's answer" ); if kind == "integer_literal" { - literals.push( - Ancestors::known(chain) - .with_folds(&asked_at_literals) - .nearest_level_answer(node, lane, code, level), - ); + let before = LEVELS_ASKED.get(); + let answer = Ancestors::known(chain) + .with_folds(&asked_at_literals) + .nearest_level_answer(node, question, code, level); + literals.push((answer, LEVELS_ASKED.get() - before)); } if expected { yes += 1; @@ -2415,11 +2426,22 @@ mod tests { no += 1; } }); + let (answers, asked): (Vec<_>, Vec<_>) = literals.into_iter().unzip(); assert_eq!( - literals, - [false, false, true, false, false, true], - "1 and 2 in f's closure, 3 in f, 4 under neither, 5 in g's closure, 6 in i" + answers, + [false, false, true, true, false, false, true], + "1 and 2 in f's closure, 3 and 4 in f, 5 under neither, 6 in g's closure, 7 in i" ); + // expected: `1` climbs binary, parenthesis, `let`, block and the + // closure; `2` meets the memo on the binary; `3` climbs tuple, + // `let`, block and `f`; `4` its `let`, then the memo on the + // block; `5` the const and the file; `6` its closure; `7` the + // statement, the block and `i`. The unmemoised climb asks 5 for + // `2` and 3 for `4`. `make chain-audit` runs that climb beside + // every ask, so the count is asserted without it. + if cfg!(not(chain_audit)) { + assert_eq!(asked, [5, 0, 4, 1, 2, 1, 3]); + } assert!(yes > 0 && no > 0, "both answers must occur ({yes} / {no})"); } } diff --git a/big-code-analysis-ast/src/node/ancestors.rs b/big-code-analysis-ast/src/node/ancestors.rs index f17083583..36bec27fb 100644 --- a/big-code-analysis-ast/src/node/ancestors.rs +++ b/big-code-analysis-ast/src/node/ancestors.rs @@ -269,14 +269,21 @@ impl<'tree, 'chain> Ancestors<'tree, 'chain> { /// /// Under a walk that lent a [`FoldCache`], the state at each ancestor /// is stored per depth, keyed by the ancestor's id, so each one is - /// folded once per walk and a query costs amortised `O(1)`. A node - /// fixes its own ancestry, so a stored state whose id matches the - /// chain is exact; a slot left by a node the walk has moved past holds - /// another id and is refolded. `step` must answer the same for every - /// call on one `lane` within a walk. It may fold on another lane, - /// memoised; a fold on its own lane is answered unmemoised. The - /// state at `node` (`skip == 0`) depends on `node`, so it is folded - /// fresh. Without a known chain the ancestry is climbed with + /// folded once per walk and a query costs amortised `O(1)` steps. A + /// state is the fold over the ancestors *above* its key, so `step` + /// runs for an ancestor once per child of it the walk asks from, and + /// for every ancestor on the chain whatever it answers. A step that + /// scans is therefore rescanned per child; a question the nearest + /// ancestor settles belongs on + /// [`nearest_level_answer`](Self::nearest_level_answer) (#1863). + /// + /// A node fixes its own ancestry, so a stored state whose id matches + /// the chain is exact; a slot left by a node the walk has moved past + /// holds another id and is refolded. `step` must answer the same for + /// every call on one `lane` within a walk. It may fold on another + /// lane, memoised; a fold on its own lane is answered unmemoised. + /// The state at `node` (`skip == 0`) depends on `node`, so it is + /// folded fresh. Without a known chain the ancestry is climbed with /// [`Node::parent`] first, which is `O(depth²)` per query; only tests /// and chainless callers reach that path, never the metrics walk. pub(crate) fn fold_down( @@ -430,24 +437,31 @@ impl<'tree, 'chain> Ancestors<'tree, 'chain> { /// parentheses around a Python docstring, each asking whether code /// precedes it on its logical line — climbs the nest from every /// level and is quadratic in its depth (#1863). Under a walk that - /// lent a [`FoldCache`] the answer is folded down the chain on - /// `lane` instead, each ancestor's own answer once per walk: a - /// `Some` replaces what the ancestors above it said, a `None` keeps - /// it. Elsewhere the climb is what runs, since an unmemoised fold - /// would start at the root for every ask. + /// lent a [`FoldCache`] the climb is memoised per level on + /// `question`: it stops at the first level that answers or already + /// holds an answer, and hands what it found to every level it + /// passed. So `answer` runs at most once per level per walk, and + /// never on a level above the nearest one that answers. /// - /// A lane memoises whatever its first asker folded, so each - /// [`LevelLane`] belongs to one `answer` per walk, and `answer` is a - /// plain `fn` of the source, the ancestor and the ancestor's own - /// chain: a closure that captured the asking node would hand every - /// later node the first one's answer. `make chain-audit` checks - /// every folded answer against the climb. + /// Not [`fold_down`](Self::fold_down), which this was first written + /// on: a fold evaluates every ancestor, the ones above the nearest + /// answer included, and stores an ancestor's state under the child + /// on the path, so a level whose answer is a long scan was scanned + /// again for each child asked from. `n` statements in a block behind + /// `k` comments cost `n × k` where the plain climb costs `n + k`. + /// + /// The memo hands every later asker the first one's answer, so each + /// [`LevelQuestion`] belongs to one `answer` per walk, and `answer` + /// is a plain `fn` of the source, the ancestor and the ancestor's + /// own chain: a closure that captured the asking node would answer + /// for it at every level. `make chain-audit` checks every memoised + /// answer against the climb. #[doc(hidden)] #[must_use] pub fn nearest_level_answer( self, node: &Node<'tree>, - lane: LevelLane, + question: LevelQuestion, code: &[u8], answer: fn(&[u8], &Node<'tree>, Ancestors<'tree, 'chain>) -> Option, ) -> bool { @@ -456,23 +470,39 @@ impl<'tree, 'chain> Ancestors<'tree, 'chain> { .find_map(|(level, chain)| answer(code, &level, chain)) .unwrap_or(false) }; - if !self.memoises_folds() { + let Some(memo) = self.node_memo(question.memo_question()) else { return climb(); + }; + // The levels passed without an answer are counted, not listed: + // they are the first `deferred` of the same iteration. + let mut deferred = 0; + let mut found = false; + for (level, chain) in self.iter(node) { + if let Some(known) = memo.get(&level) { + found = known; + break; + } + if let Some(own) = answer(code, &level, chain) { + memo.set(&level, own); + found = own; + break; + } + deferred += 1; } - let folded = self.fold_down(node, 0, lane.fold_lane(), 0, |held, ancestor, outer, _| { - answer(code, ancestor, outer).map_or(held, u8::from) - }) == 1; - // Opt-in only: the climb is the `O(depth)` per ask the fold + for (level, _) in self.iter(node).take(deferred) { + memo.set(&level, found); + } + // Opt-in only: the climb is the `O(depth)` per ask the memo // exists to remove. #[cfg(chain_audit)] assert_eq!( - folded, + found, climb(), - "the {lane:?} fold disagrees with the climb on a {} node: a lane \ - holds one answer fn per walk", + "the {question:?} memo disagrees with the climb on a {} node: a \ + question holds one answer fn per walk", node.kind() ); - folded + found } /// The walk's memo for `question`, when it lent a [`FoldCache`]. @@ -1087,28 +1117,6 @@ impl KindLane { } } -/// The "nearest ancestor that answers" questions the metric crate asks -/// through [`Ancestors::nearest_level_answer`], one per lane of the -/// walk's [`FoldCache`]. Its own enum for the reason [`KindLane`] is: -/// this entry point stores an answer, not a "seen one" flag, so a lane -/// passed to the wrong one would hand each question the other's memo. -#[doc(hidden)] -#[non_exhaustive] -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum LevelLane { - /// Python: whether code precedes a node on its logical line, read - /// at the nearest level above it that has a token before its node. - CodeBeforeOnLine, -} - -impl LevelLane { - const fn fold_lane(self) -> FoldLane { - match self { - Self::CodeBeforeOnLine => FoldLane::CodeBeforeOnLine, - } - } -} - /// Which memoised fold a [`FoldCache`] slot holds. A language may run /// more than one fold over the same walk, and two folds' states must not /// share a slot. @@ -1142,19 +1150,17 @@ pub(crate) enum FoldLane { LambdaDepth, /// [`KindLane::InsideFunction`]. InsideFunction, - /// [`LevelLane::CodeBeforeOnLine`]. - CodeBeforeOnLine, } impl FoldLane { /// How many lanes a [`FoldCache`] holds; one per variant above. - const COUNT: usize = 12; + const COUNT: usize = 11; } // A lane past `COUNT` would index out of the array at run time, on the // first walk that folds on it; this makes a variant added without the // bump a build error instead. -const _: () = assert!(FoldLane::CodeBeforeOnLine as usize + 1 == FoldLane::COUNT); +const _: () = assert!(FoldLane::InsideFunction as usize + 1 == FoldLane::COUNT); /// Which memoised per-node question a [`FoldCache`] [`NodeMemo`] holds. /// Two questions asked of the same node must not share a slot, so each @@ -1201,14 +1207,16 @@ pub(crate) enum MemoQuestion { KeywordsLeadTheirList, /// [`NodeQuestion::BareStringParenthesisLine`]. BareStringParenthesisLine, + /// [`LevelQuestion::CodeBeforeOnLine`]. + CodeBeforeOnLine, } impl MemoQuestion { /// How many memos a [`FoldCache`] holds; one per variant above. - const COUNT: usize = 9; + const COUNT: usize = 10; } -const _: () = assert!(MemoQuestion::BareStringParenthesisLine as usize + 1 == MemoQuestion::COUNT); +const _: () = assert!(MemoQuestion::CodeBeforeOnLine as usize + 1 == MemoQuestion::COUNT); /// The per-node questions the metric crate memoises through /// [`Ancestors::memoised_answer`], one per [`MemoQuestion`] memo of the @@ -1236,6 +1244,29 @@ impl NodeQuestion { } } +/// The "nearest ancestor that answers" questions the metric crate asks +/// through [`Ancestors::nearest_level_answer`], one per [`MemoQuestion`] +/// memo of the walk's [`FoldCache`]. Its own enum, apart from +/// [`NodeQuestion`]: that entry point stores a node's own answer and +/// this one the nearest answer at or above it, so a question passed to +/// the wrong one would hand each the other's memo. +#[doc(hidden)] +#[non_exhaustive] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum LevelQuestion { + /// Python: whether code precedes a node on its logical line, read + /// at the nearest level above it that has a token before its node. + CodeBeforeOnLine, +} + +impl LevelQuestion { + const fn memo_question(self) -> MemoQuestion { + match self { + Self::CodeBeforeOnLine => MemoQuestion::CodeBeforeOnLine, + } + } +} + /// The per-depth states of the walk's memoised folds, for /// `Ancestors::fold_down` (#1597), the per-node memos for /// `Ancestors::node_memo`, and the word slots keyed on the node the diff --git a/big-code-analysis-bench/src/shapes.rs b/big-code-analysis-bench/src/shapes.rs index d60500280..a04dc5a9a 100644 --- a/big-code-analysis-bench/src/shapes.rs +++ b/big-code-analysis-bench/src/shapes.rs @@ -455,6 +455,29 @@ pub fn python_bare_runs_before_string(width: usize) -> String { ) } +/// Python: an `if` whose block opens with `width` comment rows and then +/// holds `width` parenthesised bare strings, each with a bare `\` row +/// inside its parentheses. +/// +/// Each string's parenthesis asks whether code precedes it on its +/// logical line, and the nearest level that answers is its statement's: +/// the statement before it ends on another row. The comments ahead of a +/// block's first statement are children of the `if`, before the `block`, +/// so the block's own level is a scan of `width` comments back to the +/// `:`. Only the first statement needs it. A walk that reads the levels +/// above the nearest answering one for every asker — a fold of the +/// answer down the chain evaluates each ancestor, and keys the block's +/// state by the statement under it — scans the comments once per +/// statement, quadratic in `width` (#1863). +#[must_use] +pub fn python_block_comments_paren_strings(width: usize) -> String { + format!( + "if x:\n{}{}", + " # c\n".repeat(width), + " (\"s\"\n\\\n)\n".repeat(width) + ) +} + /// How many `\` + `# c` pairs [`python_deep_paren_extra_prefix`] puts /// ahead of the next parenthesis at every level: 63 children with the /// two parentheses and the next level, the most a node holds before the @@ -479,8 +502,8 @@ const PAREN_PREFIX_PAIRS: usize = 30; /// node, past that level's extras. None of these levels has one, so the /// question defers to the root from every parenthesis: read by /// climbing, `depth` parentheses read `depth² / 2` levels, under the -/// 200 levels Python's tokenizer lets parentheses nest. Folded down the -/// walk's chain, each reads three (#1863). +/// 200 levels Python's tokenizer lets parentheses nest. Read through the +/// walk's memo of each level's nearest answer, each reads two (#1863). #[must_use] pub fn python_deep_paren_extra_prefix(depth: usize) -> String { let level = format!("(\n{}", "\\\n# c\n".repeat(PAREN_PREFIX_PAIRS)); @@ -3916,15 +3939,40 @@ pub const PROBES: &[Probe] = &[ it on its logical line, which defers level by level to \ the root where the levels hold only comments and \ splices. Climbed from each parenthesis that is \ - `depth² / 2` levels under CPython's 200-level cap; the \ - answer is folded down the walk's chain on \ - `LevelLane::CodeBeforeOnLine`, three levels per \ - parenthesis. With the climb put back this reads 1.95, \ - 92 ms at the top rung against 5.3 ms, and 1.00 \ + `depth² / 2` levels under CPython's 200-level cap; each \ + level's nearest answer is memoised on \ + `LevelQuestion::CodeBeforeOnLine`, two levels per \ + parenthesis. With the climb put back this reads 1.96, \ + 100 ms at the top rung against 4.7 ms, and 0.93 \ without. The reading is the comment rows: each level's \ `(` row, bare rows and comments, the string's and the \ `)` row.", }, + Probe { + name: "loc/python-block-comments-paren-strings", + lang: LANG::Python, + axis: Axis::Width, + workload: Workload::Metrics { + exclude_tests: false, + selection: &[Metric::Loc], + reading: |m| m.loc.cloc(), + }, + render: python_block_comments_paren_strings, + sizes: SLOT_SCAN_WIDTHS, + max_exponent: LINEAR_BOUND, + rationale: "#1863: `width` parenthesised bare strings, each holding \ + a bare `\\` row, in an `if` block that opens with \ + `width` comment rows. Each parenthesis asks whether code \ + precedes it on its logical line, and its own statement's \ + level answers. The block's level above it is a scan of \ + the `width` comments back to the `:`, which only the \ + first statement needs. Read for every statement, as a \ + fold of the answer down the chain reads it, the walk is \ + quadratic in `width`: 2.02 and 763 ms at the top rung \ + with that fold, 1.04 and 28 ms with the memoised climb. \ + The reading is the comment rows: the `width` comments \ + and three rows per string.", + }, Probe { name: "loc/go-nested-doc-fields", lang: LANG::Go, @@ -5197,6 +5245,46 @@ mod tests { } } + /// `loc/python-block-comments-paren-strings` (#1863) puts its + /// comments where the block's level must scan them: tree-sitter + /// hangs a comment ahead of a block's first statement on the + /// compound statement, before the `block`, so the `if` holds all + /// `size` of them and the block one statement per string. A grammar + /// that moved them into the block would leave the probe measuring + /// nothing. The reading is every row but the `if`. + #[test] + fn python_block_comments_probe_hangs_its_comments_on_the_if() { + let name = "loc/python-block-comments-paren-strings"; + let probe = PROBES + .iter() + .find(|p| p.name == name) + .unwrap_or_else(|| panic!("{name} is a probe")); + for size in [3, probe.sizes[0]] { + let ast = parse(probe, size); + let root = ast.as_tree_sitter().root_node(); + assert!(!root.has_error(), "{name} at {size}"); + let compound = root.child(0).expect("the `if`"); + assert_eq!(compound.kind(), "if_statement"); + let mut cursor = compound.walk(); + let kinds: Vec<_> = compound.children(&mut cursor).map(|c| c.kind()).collect(); + assert_eq!( + kinds.iter().filter(|kind| **kind == "comment").count(), + size, + "every comment is the `if`'s child" + ); + assert_eq!(kinds.last(), Some(&"block"), "and sits before the block"); + assert_eq!(count_kind(&ast, "parenthesized_expression"), size); + assert_eq!(count_kind(&ast, "line_continuation"), size); + let reading = probe + .workload + .walk(&ast, probe.workload.options()) + .expect("metrics walk"); + // expected: a row per comment, and the string's, the bare + // row and the `)` row per statement. + assert_eq!(reading, 4 * size as u64, "{name} at {size}"); + } + } + /// `loc/python-deep-paren-extra-prefix` (#1863) keeps every /// parenthesis as wide as a node can be before the walk records its /// children for sibling lookups, so each level's read is a seek and diff --git a/docs/development/benchmarking.md b/docs/development/benchmarking.md index 9fdaff8b3..4a99d9f5f 100644 --- a/docs/development/benchmarking.md +++ b/docs/development/benchmarking.md @@ -193,7 +193,8 @@ Read it as follows. | `halstead/python-nested-paren` | Python | depth | the climb from each parenthesis to its statement, capped at CPython's nesting limit (#1610) | linear | | `loc/python-paren-bare-strings` | Python | depth | each parenthesis of a bare string statement asking whether it wraps the string, memoised per statement under the cap (#1610) | linear | | `ops/python-paren-bare-strings` | Python | depth | the same test in the `bca ops` walk, which keeps its own fold cache (#1610) | linear | -| `loc/python-deep-paren-extra-prefix` | Python | depth | each parenthesis of a parenthesised docstring asking whether code precedes it on its logical line, where every level defers to the one above, folded on `LevelLane::CodeBeforeOnLine` (#1863) | linear | +| `loc/python-deep-paren-extra-prefix` | Python | depth | each parenthesis of a parenthesised docstring asking whether code precedes it on its logical line, where every level defers to the one above; each level's nearest answer is memoised on `LevelQuestion::CodeBeforeOnLine` (#1863) | linear | +| `loc/python-block-comments-paren-strings` | Python | width | the same question where each asker's own statement answers and the block above it is a long scan: the levels above the nearest answer are never read (#1863) | linear | | `loc/go-nested-doc-fields` | Go | depth | Go's package-level scope test over nested struct fields (#1597) | linear | | `loc/ruby-nested-doc-constants` | Ruby | depth | YARD's namespace scope test through nested `if`s (#1597) | linear | | `loc/lua-tagless-blocks` | Lua | width | LDoc's first-block test, scanning back to the previous block (#1597) | linear | @@ -907,44 +908,72 @@ for Groovy on a warm tree; the exponent does not move. [record-header]: https://github.com/dekobon/big-code-analysis/issues/1842 [roles-followups]: https://github.com/dekobon/big-code-analysis/issues/1863 -`loc/python-deep-paren-extra-prefix` guards the Python `loc` question -"does code precede this node on its logical line". A bare `\` run -inside a parenthesised docstring asks it of its parenthesis, once per -parenthesis. The answer is read at the nearest level, from the node's -own upward, that holds a token before its node; a level holding only -comments and splices defers to the one above. Every existing Python -parenthesis probe grows either the nesting or one level's prefix. With -both, no level answers, so each of `depth` parentheses climbed to the -root: `depth² / 2` levels under [CPython](https://www.python.org/)'s -200-level cap. The answer is now folded down the walk's chain -(`Ancestors::nearest_level_answer`), so a parenthesis reads three -levels: its own, the one ancestor state not yet stored, and its -parent's. - -The probe renders a docstring `depth` parentheses deep, each opening -with 30 one-row `\` runs that each join a comment row. Thirty is the -most that keeps a parenthesis under `WIDE_PARENT`, so a level's read is -a seek over the parenthesis's children rather than a slice of the -walk's sibling cache, and the number of levels read shows in the -timing. +`loc/python-deep-paren-extra-prefix` and +`loc/python-block-comments-paren-strings` guard the Python `loc` +question "does code precede this node on its logical line". A bare `\` +run inside a parenthesised docstring asks it of its parenthesis, once +per parenthesis. The answer is read at the nearest level, from the +node's own upward, that holds a token before its node; a level holding +only comments and splices defers to the one above. + +The two probes exist because each of the two ways to answer it wrongly +is linear on the other's shape: + +- **A climb per asker.** Every earlier Python parenthesis probe grows + either the nesting or one level's prefix. With both, no level + answers, so each of `depth` parentheses climbed to the root: + `depth² / 2` levels under [CPython](https://www.python.org/)'s + 200-level cap. `loc/python-deep-paren-extra-prefix` renders a + docstring `depth` parentheses deep, each opening with 30 one-row `\` + runs that each join a comment row. Thirty is the most that keeps a + parenthesis under `WIDE_PARENT`, so a level's read is a seek over the + parenthesis's children rather than a slice of the walk's sibling + cache, and the number of levels read shows in the timing. +- **A fold down the chain.** The first fix folded the answer on a + `FoldCache` lane, as `has_ancestor_of_kind` does. A fold evaluates + every ancestor, the ones above the nearest answer included, and + stores an ancestor's state under the child on the path. That is free + where the step is a kind test. Here a level's answer is a scan of the + extras before it, so a level above the answering one was scanned + again for every child asked from. + `loc/python-block-comments-paren-strings` renders an `if` block that + opens with `width` comment rows and then holds `width` parenthesised + strings. Each parenthesis's own statement answers; the block's level + above it is the scan of the `width` comments, which only the first + statement needs. + +`Ancestors::nearest_level_answer` now memoises the climb per level +(`LevelQuestion`): it stops at the first level that answers or already +holds an answer, and hands what it found to the levels it passed. A +level is read at most once per walk, and never above the nearest +answer. | Walk put back | Probe that fails | Clean | Regressed | Top rung | |---|---|---|---|---| -| the climb per parenthesis | `loc/python-deep-paren-extra-prefix` | 1.00 | 1.95 | 5.3 ms → 92 ms | - -One run each, on a host that was not idle. In the regressed run -`loc/python-paren-bare-strings`, `ops/python-paren-bare-strings`, -`halstead/python-nested-paren` and `loc/python-bare-runs-before-string` -read 0.95, 1.05, 0.87 and 1.02. The per-change guard is -`python_code_before_a_parenthesis_reads_three_levels_each` in -`src/metrics/loc.rs`, which pins the exact number of levels read over -40 parentheses: 120 folded, 900 climbed. Under `--cfg chain_audit` -every folded answer is also checked against the climb. - -The climb sweep above was re-run for this fold and each match re-read, -not re-timed. Every other match stops within a fixed distance of all -but one asker per subtree, is capped, or already folds where a walk -lends a cache. The one exception was filed before this change: +| the climb per parenthesis | `loc/python-deep-paren-extra-prefix` | 0.93 | 1.96 | 4.7 ms → 100 ms | +| the fold down the chain | `loc/python-block-comments-paren-strings` | 1.04 | 2.02 | 28 ms → 763 ms | + +One run each, on a host that was not idle. With the climb put back +`loc/python-block-comments-paren-strings` reads 1.08, and with the fold +`loc/python-deep-paren-extra-prefix` reads 1.06: each passes the +other's defect. In the climb run `loc/python-paren-bare-strings`, +`ops/python-paren-bare-strings`, `halstead/python-nested-paren` and +`loc/python-bare-runs-before-string` read 0.93, 0.86, 1.12 and 1.06. +The per-change guard is +`python_code_before_a_parenthesis_reads_each_level_once` in +`src/metrics/loc.rs`, which pins the exact number of levels read on +both shapes at size 40: 81 and 81 memoised, 900 and 81 climbed, 120 +and 122 folded. Under `--cfg chain_audit` every memoised answer is also +checked against the climb. + +Before putting a question on `fold_down`, check what its step costs: +the step runs for every ancestor on an asker's chain, once per child +the walk asks from. A step that scans is a fold's quadratic. + +The climb sweep above was re-run for this change and each match +re-read, not re-timed. Every other match stops within a fixed distance +of all but one asker per subtree, is capped, or already folds where a +walk lends a cache. The one exception was filed before this change: `python_is_bound_self_attribute` ([#1867][python-npa]). [python-npa]: https://github.com/dekobon/big-code-analysis/issues/1867 diff --git a/src/metrics/loc.rs b/src/metrics/loc.rs index 9610a8ae7..39e5e491c 100644 --- a/src/metrics/loc.rs +++ b/src/metrics/loc.rs @@ -10385,44 +10385,65 @@ EOF } /// #1863: whether code precedes a parenthesis on its logical line is - /// folded down the walk's chain, so a docstring `depth` parentheses - /// deep, each opening with a bare `\` run, reads three levels per - /// parenthesis rather than every level above each. + /// read at the nearest level that answers, and each level is read + /// once per walk. Two shapes, because each of the two ways to get it + /// wrong is linear on one of them: /// - /// The rows cannot see it: the fold and the climb answer the same, - /// so every row but the last is a comment row either way, and only - /// the count of levels read tells the two apart. No level here has a - /// token before its node, so the question defers from each - /// parenthesis to the root, the shape the climb was quadratic on. + /// - `nested`: a docstring `n` parentheses deep, each opening with a + /// bare `\` run. No level has a token before its node, so the + /// question defers from every parenthesis to the root. A climb per + /// parenthesis reads `j + 2` levels from the one `j` deep. + /// - `block`: `n` parenthesised strings in an `if` block behind `n` + /// comments. Each statement's own level answers. A fold of the + /// answer down the chain reads the block's level too, for every + /// statement, and that level is a scan of the `n` comments. + /// + /// The rows cannot see either: every reading answers the same, so + /// the comment rows are the same rows, and only the count of levels + /// read tells the three apart. #[cfg(feature = "python")] #[test] - fn python_code_before_a_parenthesis_reads_three_levels_each() { - let depth = 40; - let source = format!( + fn python_code_before_a_parenthesis_reads_each_level_once() { + let n = 40; + let nested = format!( "{}\"\"\"doc\"\"\"\n{}\nx = 1\n", - "(\n\\\n# c\n".repeat(depth), - ")".repeat(depth) + "(\n\\\n# c\n".repeat(n), + ")".repeat(n) ); - let before = python::python_line_levels_read::observed(); - let loc = metrics_verbatim( - crate::LANG::Python, - source.as_bytes(), - MetricsOptions::default().with_only(&[crate::Metric::Loc]), - ) - .loc; - let read = python::python_line_levels_read::observed() - before; + let block = format!( + "if x:\n{}{}", + " # c\n".repeat(n), + " (\"s\"\n\\\n)\n".repeat(n) + ); + let read = |source: &str| { + let before = python::python_line_levels_read::observed(); + let loc = metrics_verbatim( + crate::LANG::Python, + source.as_bytes(), + MetricsOptions::default().with_only(&[crate::Metric::Loc]), + ) + .loc; + ( + loc.cloc(), + python::python_line_levels_read::observed() - before, + ) + }; + let (nested_cloc, nested_read) = read(&nested); + let (block_cloc, block_read) = read(&block); // expected: per level the `(` row, the bare row and the comment - // row; then the string's row and the row of `)`. - assert_eq!(loc.cloc(), 3 * depth as u64 + 2); - // expected: each parenthesis is asked once, by its run, and reads - // its own level, the one ancestor state the fold has not stored - // yet, and its parent's level, which a fold never stores. The - // climb read `j + 2` levels from the parenthesis `j` deep, - // `depth * (depth + 5) / 2` in all: 900 here. `make chain-audit` - // checks every folded answer against that climb, which reads - // the levels this counts, so the count is asserted without it. + // row, then the string's row and the row of `)`; and a row per + // comment plus three per string. + assert_eq!((nested_cloc, block_cloc), (3 * n as u64 + 2, 4 * n as u64)); + // expected: each parenthesis is asked once, by its run. `nested`: + // its own level and its parent's, where it meets the answer the + // parent's ask left on the levels above; the outermost reads its + // statement and the module instead. `block`: its own level and + // its statement's, which answers; the first statement has no + // statement before it and reads the block. The climb reads 900 + // and 81, the fold 120 and 122. `make chain-audit` runs the + // climb beside every ask, so the count is asserted without it. if cfg!(not(chain_audit)) { - assert_eq!(read, 3 * depth); + assert_eq!((nested_read, block_read), (2 * n + 1, 2 * n + 1)); } } diff --git a/src/metrics/loc/python.rs b/src/metrics/loc/python.rs index 8a08c120f..1e56326ab 100644 --- a/src/metrics/loc/python.rs +++ b/src/metrics/loc/python.rs @@ -607,17 +607,20 @@ fn python_code_before_string<'a>( // parenthesis's memoised answer reads — the parenthesis's inside, where // nothing before the string can be code, is never one of them. // -// The levels above `node` are folded down the walk's chain rather than -// climbed. A parenthesis whose own level holds only comments and `\` -// splices before it defers to the level above, and so does that one: -// asked from each of `n` nested parentheses, the climb read every level -// above each, `Σ` of their extras, quadratic in `n` under CPython's -// 200-level cap (#1863; `loc/python-deep-paren-extra-prefix` prices it). +// The levels above `node` are read through the walk's memo of each +// level's nearest answer rather than climbed afresh. A parenthesis whose +// own level holds only comments and `\` splices before it defers to the +// level above, and so does that one: asked from each of `n` nested +// parentheses, the climb read every level above each, `Σ` of their +// extras, quadratic in `n` under CPython's 200-level cap (#1863; +// `loc/python-deep-paren-extra-prefix` prices it). The memo keeps the +// climb's stop at the first level that answers, so a level above it is +// never read (`loc/python-block-comments-paren-strings`). fn python_code_before_node<'a>(code: &[u8], node: &Node<'a>, ancestors: Ancestors<'a, '_>) -> bool { python_code_at_level(code, node, ancestors).unwrap_or_else(|| { ancestors.nearest_level_answer( node, - LevelLane::CodeBeforeOnLine, + LevelQuestion::CodeBeforeOnLine, code, python_code_at_level, ) @@ -636,9 +639,9 @@ fn python_code_at_level<'a>( } // Levels `python_code_before_node` reads for a token before their node. -// The fold and the climb answer the same, so only this tells a walk that -// reads each level once from one that reads every level above every -// parenthesis (#1863). +// Every way of reading them answers the same, so only this tells a walk +// that reads each level once from one that reads every level above +// every parenthesis, or a level above the one that answers (#1863). crate::observation::counter!(python_line_levels_read); // Whether the nearest of `siblings` (nearest first) that is neither a @@ -666,8 +669,8 @@ fn python_code_among<'a>( ) -> Option { let mut tokens = siblings.skip_while(|sibling| { python_is_extra(sibling) - || matches!(sibling.kind_id().into(), Python::LPAREN | Python::RPAREN) - && parens.is_some_and(|chain| python_is_bare_string_parenthesis(sibling, chain)) + || (matches!(sibling.kind_id().into(), Python::LPAREN | Python::RPAREN) + && parens.is_some_and(|chain| python_is_bare_string_parenthesis(sibling, chain))) }); tokens .next() From c799efd938d1fed3c6c145402ef7b15d3a67d1cd Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Wed, 11 Nov 2026 18:58:22 -0800 Subject: [PATCH 14/21] test(node): make the answering level's memo observable The per-ask call counts in `nearest_level_answer_answers_the_climb_on_every_path` could not see whether the level that answered was stored: every later asker met a passed level first. A closure with a typed parameter gives one asker that climbs to the closure through its parameter list and a second that is its direct child, which meets the stored answer or asks again. Refs #1863 --- big-code-analysis-ast/src/node.rs | 25 ++++++++++++++----------- 1 file changed, 14 insertions(+), 11 deletions(-) diff --git a/big-code-analysis-ast/src/node.rs b/big-code-analysis-ast/src/node.rs index 783d879be..ae51a9f7b 100644 --- a/big-code-analysis-ast/src/node.rs +++ b/big-code-analysis-ast/src/node.rs @@ -2371,9 +2371,10 @@ mod tests { /// effect: the answers cannot tell it from the climb. `2` meets the /// answer `1` left on their shared `binary_expression`; `4` reads /// its own `let` and meets the one `3` left on the block they - /// share, a level `3` passed without an answer. `3` sits in the - /// tuple after the closure: a memo that handed `1`'s "no" to a - /// level above the closure would answer "no" for it. + /// share, a level `3` passed without an answer; `7` meets the one + /// `6` left on the closure itself, the level that answered. `3` + /// sits in the tuple after the closure: a memo that handed `1`'s + /// "no" to a level above the closure would answer "no" for it. #[cfg(feature = "rust")] #[test] fn nearest_level_answer_answers_the_climb_on_every_path() { @@ -2392,7 +2393,7 @@ mod tests { } let code = b"fn f() { let c = (|| { let d = (1 + 2); }, 3); let e = 4; }\n\ const K: u8 = 5;\n\ - mod m { fn g() { let h = || 6; } fn i() { 7; } }\n"; + mod m { fn g() { let h = |_: [u8; 6]| 7; } fn i() { 8; } }\n"; let cache = FoldCache::default(); let asked_at_literals = FoldCache::default(); let question = LevelQuestion::CodeBeforeOnLine; @@ -2429,18 +2430,20 @@ mod tests { let (answers, asked): (Vec<_>, Vec<_>) = literals.into_iter().unzip(); assert_eq!( answers, - [false, false, true, true, false, false, true], - "1 and 2 in f's closure, 3 and 4 in f, 5 under neither, 6 in g's closure, 7 in i" + [false, false, true, true, false, false, false, true], + "1 and 2 in f's closure, 3 and 4 in f, 5 under neither, 6 and 7 in g's closure, 8 in i" ); // expected: `1` climbs binary, parenthesis, `let`, block and the // closure; `2` meets the memo on the binary; `3` climbs tuple, // `let`, block and `f`; `4` its `let`, then the memo on the - // block; `5` the const and the file; `6` its closure; `7` the - // statement, the block and `i`. The unmemoised climb asks 5 for - // `2` and 3 for `4`. `make chain-audit` runs that climb beside - // every ask, so the count is asserted without it. + // block; `5` the const and the file; `6` the array type, the + // parameter, the parameter list and the closure; `7` meets the + // memo on the closure; `8` the statement, the block and `i`. + // The unmemoised climb asks 5 for `2`, 3 for `4` and 1 for `7`. + // `make chain-audit` runs that climb beside every ask, so the + // count is asserted without it. if cfg!(not(chain_audit)) { - assert_eq!(asked, [5, 0, 4, 1, 2, 1, 3]); + assert_eq!(asked, [5, 0, 4, 1, 2, 4, 0, 3]); } assert!(yes > 0 && no > 0, "both answers must occur ({yes} / {no})"); } From 601a0742e398e236fbc45874f89cf7c9a03a7d6f Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Wed, 11 Nov 2026 19:02:13 -0800 Subject: [PATCH 15/21] test(roles): check the byte-gate fixtures' table names in a test of their own `sources_for` asserted that every `BYTE_GATE_FIXTURES` row names a table on each of its calls, once per language per test. The check is a property of the table, not of loading one language's sources. The rust-optimize pass over the branch found nothing else: the workspace already gates `clippy::pedantic` at `-D warnings`, and the catalog's remaining candidates in the changed code are established idioms of the surrounding files. Refs #1863 --- .../src/roles/derived_parity_tests.rs | 28 +++++++++++++------ 1 file changed, 19 insertions(+), 9 deletions(-) diff --git a/big-code-analysis-ast/src/roles/derived_parity_tests.rs b/big-code-analysis-ast/src/roles/derived_parity_tests.rs index d5406cfc5..9ff222228 100644 --- a/big-code-analysis-ast/src/roles/derived_parity_tests.rs +++ b/big-code-analysis-ast/src/roles/derived_parity_tests.rs @@ -167,18 +167,14 @@ fn sources_for(lang: LANG) -> Vec { bytes: f.source.into_owned(), }), ); - let tables = crate::roles::tables(); - for (table, fixture, _) in BYTE_GATE_FIXTURES { - assert!( - tables.iter().any(|t| t.name == *table), - "`{fixture}` names `{table}`, which is no table: it would be asked of nothing" - ); - } - let name = tables.iter().find(|t| t.lang == lang).map(|t| t.name); + let table = crate::roles::tables() + .iter() + .find(|t| t.lang == lang) + .map(|t| t.name); out.extend( BYTE_GATE_FIXTURES .iter() - .filter(|(table, _, _)| Some(*table) == name) + .filter(|(name, _, _)| Some(*name) == table) .map(|(_, fixture, bytes)| Source { name: (*fixture).to_owned(), bytes: bytes.to_vec(), @@ -187,6 +183,20 @@ fn sources_for(lang: LANG) -> Vec { out } +/// A fixture keyed by a name no table carries is asked of nothing, and +/// the byte backstop loses the one candidate that moves its gate +/// without a failure anywhere. +#[test] +fn byte_gate_fixtures_each_name_a_table() { + let tables = crate::roles::tables(); + for (table, fixture, _) in BYTE_GATE_FIXTURES { + assert!( + tables.iter().any(|t| t.name == *table), + "`{fixture}` names `{table}`, which is no table" + ); + } +} + // --------------------------------------------------------------------------- // The census // --------------------------------------------------------------------------- From 6198f3fe519cbc97ca105b8fedb4fec37a42601a Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Wed, 11 Nov 2026 20:25:34 -0800 Subject: [PATCH 16/21] perf(loc/python): ask the level question from the run, so each level is read once `python_code_before_node` read the asked parenthesis's own level directly and handed only the levels above it to `Ancestors::nearest_level_answer`. The parenthesis was therefore never looked up or stored in the memo: the next parenthesis in read it again as its parent, and a second asker of the same parenthesis (a `\`-continuing run through `python_code_before_string`, which is not behind the per-parenthesis memo) rescanned its prefix. The docs said "a level is read at most once per walk"; the count test pinned `2n + 1` reads for `n + 2` levels. Both callers now ask from the run itself, whose first ancestor is the parenthesis, so the parenthesis is a level like the rest. `python_code_before_node` is replaced by `python_code_before_parent`. The answer is the same `find_map` over the same levels. `python_code_before_a_parenthesis_reads_each_level_once`: 42 and 81 levels read at size 40 (was 81 and 81), one per level on both shapes. Scaling, one `--no-gate` run on a busy host: `loc/python-deep-paren-extra-prefix` 0.99 and 3.5 ms at the top rung (was 0.93 and 4.7 ms; 1.96 and 100 ms with a climb per parenthesis), `loc/python-block-comments-paren-strings` 1.00 and 26 ms. `benchmarking.md` also gains what the reviews of the batch asked for: `nearest_level_answer` in the climb sweep's pattern, a note that the timer starts after the parse (tree-sitter-python's scanner is itself quadratic on two of these shapes, which no probe prices), and the record-header passage's two timings told apart. Found by four of the seven reviewers of the batch. Refs #1863 --- CHANGELOG.md | 8 ++-- big-code-analysis-bench/src/shapes.rs | 34 +++++++------- docs/development/benchmarking.md | 47 +++++++++++++------- src/metrics/loc.rs | 23 +++++----- src/metrics/loc/python.rs | 64 ++++++++++++++------------- 5 files changed, 100 insertions(+), 76 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d2825f620..d046c6f0a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -338,10 +338,10 @@ for historical reference. level that holds a token before its node. Where every level holds only comments and `\` rows, each of `n` nested parentheses read every level above it, quadratic in `n` up to the 200 levels Python's - tokenizer allows. Each level's answer is now memoised for the walk, - so a parenthesis reads two levels: at 200 levels with 30 such rows - each, a 37 KB file, the `loc` walk took 100 ms and takes 4.7 ms (one - run each, on a host that was not idle). Metric values are unchanged. + tokenizer allows. Each level's answer is now memoised for the walk + and read once: at 200 levels with 30 such rows each, a 37 KB file, + the `loc` walk took 100 ms and takes 3.5 ms (one run each, on a host + that was not idle). Metric values are unchanged. New scaling probes `loc/python-deep-paren-extra-prefix` and `loc/python-block-comments-paren-strings` price it, the second for the levels above the nearest answer, which are never read. diff --git a/big-code-analysis-bench/src/shapes.rs b/big-code-analysis-bench/src/shapes.rs index a04dc5a9a..95113b120 100644 --- a/big-code-analysis-bench/src/shapes.rs +++ b/big-code-analysis-bench/src/shapes.rs @@ -484,8 +484,9 @@ pub fn python_block_comments_paren_strings(width: usize) -> String { /// walk records it for sibling lookups (`WIDE_PARENT`). A level's read /// is then a seek over the parenthesis's children rather than a slice /// of the walk's sibling cache, which is what makes the number of -/// levels read show in the timing: timed alone on a warm tree, the -/// climb read 1.56 with 31 pairs and 2.05 with these 30. +/// levels read show in the timing: with 31 pairs a climb per +/// parenthesis fits about 1.6, under no bound that would also pass the +/// memoised walk on a shared host, where these 30 fit about 2. const PAREN_PREFIX_PAIRS: usize = 30; /// Python: a bare string `depth` parentheses deep, each parenthesis @@ -503,7 +504,8 @@ const PAREN_PREFIX_PAIRS: usize = 30; /// question defers to the root from every parenthesis: read by /// climbing, `depth` parentheses read `depth² / 2` levels, under the /// 200 levels Python's tokenizer lets parentheses nest. Read through the -/// walk's memo of each level's nearest answer, each reads two (#1863). +/// walk's memo of each level's nearest answer, each level is read once +/// (#1863). #[must_use] pub fn python_deep_paren_extra_prefix(depth: usize) -> String { let level = format!("(\n{}", "\\\n# c\n".repeat(PAREN_PREFIX_PAIRS)); @@ -1080,8 +1082,9 @@ pub fn nested_classes_with_method(depth: usize) -> String { const RECORD_BASE_CTORS: usize = 4; /// Java and Groovy, which read it alike: one record of ten components -/// whose body holds `width` alternative constructors, each spelling the -/// first nine component types and a tenth that differs. +/// whose body holds `width` alternative constructors and +/// `RECORD_BASE_CTORS` more, each spelling the first nine component +/// types and a tenth that differs. /// /// The record's header stands for the implicit canonical constructor /// only where the body writes none, and a written one is told from an @@ -3516,8 +3519,8 @@ pub const PROBES: &[Probe] = &[ the component's. One scan is linear in the body, and \ each consumer of the gate pays one per record: 1.01. \ With the gate asked once per constructor instead, one \ - walk of 2 000 constructors took 47 s against 32 ms and \ - the gate abandons the probe over its per-walk budget. \ + walk at the top rung took 47 s against 32 ms and the \ + gate abandons the probe over its per-walk budget. \ The reading is ten arguments per constructor and ten \ for the header.", }, @@ -3537,8 +3540,8 @@ pub const PROBES: &[Probe] = &[ `nargs/java-record-alternative-ctors`, under the \ Groovy grammar, whose header is a `record_components` \ list and whose gate is a twin in `roles/groovy.rs`: \ - 1.01, and 49 s against 26 ms at 2 000 constructors \ - with the gate asked once per constructor.", + 1.01, and 49 s against 26 ms at the top rung with the \ + gate asked once per constructor.", }, Probe { name: "loc/rust-attributed-docs", @@ -3941,12 +3944,11 @@ pub const PROBES: &[Probe] = &[ splices. Climbed from each parenthesis that is \ `depth² / 2` levels under CPython's 200-level cap; each \ level's nearest answer is memoised on \ - `LevelQuestion::CodeBeforeOnLine`, two levels per \ - parenthesis. With the climb put back this reads 1.96, \ - 100 ms at the top rung against 4.7 ms, and 0.93 \ - without. The reading is the comment rows: each level's \ - `(` row, bare rows and comments, the string's and the \ - `)` row.", + `LevelQuestion::CodeBeforeOnLine` and read once. With \ + the climb put back this reads 1.96, 100 ms at the top \ + rung against 3.5 ms, and 0.99 without. The reading is \ + the comment rows: each level's `(` row, bare rows and \ + comments, the string's and the `)` row.", }, Probe { name: "loc/python-block-comments-paren-strings", @@ -3969,7 +3971,7 @@ pub const PROBES: &[Probe] = &[ first statement needs. Read for every statement, as a \ fold of the answer down the chain reads it, the walk is \ quadratic in `width`: 2.02 and 763 ms at the top rung \ - with that fold, 1.04 and 28 ms with the memoised climb. \ + with that fold, 1.00 and 26 ms with the memoised climb. \ The reading is the comment rows: the `width` comments \ and three rows per string.", }, diff --git a/docs/development/benchmarking.md b/docs/development/benchmarking.md index 4a99d9f5f..e9eb546d3 100644 --- a/docs/development/benchmarking.md +++ b/docs/development/benchmarking.md @@ -71,6 +71,15 @@ visit order rotated between rounds, and the reported figure is the slope of `ln(time)` against `ln(size)`. A linear walk sits near 1.0; a quadratic one sits near 2.0. +The timer starts after the parse, so a probe prices the walk and +never the grammar. A scanner that is itself super-linear on a shape +shows in no exponent here: tree-sitter-python's external scanner is +quadratic in a run of comment rows inside a block and in a run of bare +`\` rows, so `bca metrics` on the shape +`loc/python-block-comments-paren-strings` renders is dominated by the +parse at the top rung while the probe fits 1.00. Time `bca count -t +error` on the same file to see the parse alone. + A probe declares which **axis** its size parameter grows along, because a walk can be linear in one and quadratic in the other: @@ -351,7 +360,7 @@ sites by hand. rg -U '\.iter\([^)]+\)\)?\s*(\.(map|skip|by_ref|take|filter)\([^\n]*\)\s*)*\.(any|all|find|find_map|position|take_while|skip_while|map_while|last|count|fold|try_fold)\(' src big-code-analysis-ast/src rg 'for .* in .*\.iter\([^)]+\)' src big-code-analysis-ast/src rg 'successors\(.*parent' src big-code-analysis-ast/src -rg 'count_specific_ancestors|has_ancestor_before_stop|has_ancestor_of_kind' src big-code-analysis-ast/src +rg 'count_specific_ancestors|has_ancestor_before_stop|has_ancestor_of_kind|nearest_level_answer' src big-code-analysis-ast/src ``` For each match, name what stops the loop, then render a shape where @@ -837,8 +846,9 @@ up. A method in a class has none, so its scan read the whole chain, and a method in each of `n` nested classes read `Σ depth` entries. The answer is now folded down the chain on `KindLane::InsideFunction` -(`Ancestors::has_ancestor_of_kind`), each ancestor once per walk, the -way #1767 folded the other ancestor questions that have no stop nearby. +(`Ancestors::has_ancestor_of_kind`), each ancestor's kind once per +child the walk asks under, the way #1767 folded the other ancestor +questions that have no stop nearby. Both probes render the same source, `depth` nested classes each holding one method with one `if`, on 4 000 / 8 000 / 16 000. The Groovy row is @@ -888,8 +898,9 @@ costs a handful of scans, each linear in its body. No probe rendered a record before [#1863][roles-followups]. Both probes render one record of ten components whose body holds -`width` alternative constructors, each spelling nine component types -and a tenth that differs, which is the most a constructor can cost. +`width + 4` alternative constructors, each spelling nine component +types and a tenth that differs, which is the most a constructor can +cost. | Walk put back | Probe that fails | Clean | Regressed | Top rung | |---|---|---|---|---| @@ -900,10 +911,15 @@ One run each, on a host that was not idle. The regressed walk runs past `MAX_CELL_WALK` at the top rung, so the gate reports an abandoned walk in place of an exponent. `loc/java-package-docs`, `loc/rust-attributed-docs` and `cognitive/wide-if-siblings` read 0.84, -1.00 and 0.86 in the same run. The same change reads the header's -component types once per scan rather than once per constructor, which -took the top rung from 44 ms to 29 ms for Java and from 35 ms to 21 ms -for Groovy on a warm tree; the exponent does not move. +1.00 and 0.86 in the same run. + +The same change reads the header's component types once per scan +rather than once per constructor. A separate timing of the `nargs` +walk alone on the top rung's shape, the minimum of 31 walks, read +44 ms before and 29 ms after for Java, and 35 ms and 21 ms for Groovy. +The exponent does not move, so no probe sees it; +`java_header_types_are_read_once_per_gate_evaluation` and its Groovy +twin count the reads. [record-header]: https://github.com/dekobon/big-code-analysis/issues/1842 [roles-followups]: https://github.com/dekobon/big-code-analysis/issues/1863 @@ -946,12 +962,13 @@ is linear on the other's shape: (`LevelQuestion`): it stops at the first level that answers or already holds an answer, and hands what it found to the levels it passed. A level is read at most once per walk, and never above the nearest -answer. +answer. The run asks from itself, so its parenthesis is a level like +the rest. | Walk put back | Probe that fails | Clean | Regressed | Top rung | |---|---|---|---|---| -| the climb per parenthesis | `loc/python-deep-paren-extra-prefix` | 0.93 | 1.96 | 4.7 ms → 100 ms | -| the fold down the chain | `loc/python-block-comments-paren-strings` | 1.04 | 2.02 | 28 ms → 763 ms | +| the climb per parenthesis | `loc/python-deep-paren-extra-prefix` | 0.99 | 1.96 | 3.5 ms → 100 ms | +| the fold down the chain | `loc/python-block-comments-paren-strings` | 1.00 | 2.02 | 26 ms → 763 ms | One run each, on a host that was not idle. With the climb put back `loc/python-block-comments-paren-strings` reads 1.08, and with the fold @@ -962,9 +979,9 @@ other's defect. In the climb run `loc/python-paren-bare-strings`, The per-change guard is `python_code_before_a_parenthesis_reads_each_level_once` in `src/metrics/loc.rs`, which pins the exact number of levels read on -both shapes at size 40: 81 and 81 memoised, 900 and 81 climbed, 120 -and 122 folded. Under `--cfg chain_audit` every memoised answer is also -checked against the climb. +both shapes at size 40: 42 and 81 memoised, one per level; 900 and 81 +climbed; 120 and 122 folded. Under `--cfg chain_audit` every memoised +answer is also checked against the climb. Before putting a question on `fold_down`, check what its step costs: the step runs for every ancestor on an asker's chain, once per child diff --git a/src/metrics/loc.rs b/src/metrics/loc.rs index 39e5e491c..baca637a3 100644 --- a/src/metrics/loc.rs +++ b/src/metrics/loc.rs @@ -10392,7 +10392,7 @@ EOF /// - `nested`: a docstring `n` parentheses deep, each opening with a /// bare `\` run. No level has a token before its node, so the /// question defers from every parenthesis to the root. A climb per - /// parenthesis reads `j + 2` levels from the one `j` deep. + /// parenthesis reads `j + 3` levels from the one `j` deep. /// - `block`: `n` parenthesised strings in an `if` block behind `n` /// comments. Each statement's own level answers. A fold of the /// answer down the chain reads the block's level too, for every @@ -10434,16 +10434,19 @@ EOF // row, then the string's row and the row of `)`; and a row per // comment plus three per string. assert_eq!((nested_cloc, block_cloc), (3 * n as u64 + 2, 4 * n as u64)); - // expected: each parenthesis is asked once, by its run. `nested`: - // its own level and its parent's, where it meets the answer the - // parent's ask left on the levels above; the outermost reads its - // statement and the module instead. `block`: its own level and - // its statement's, which answers; the first statement has no - // statement before it and reads the block. The climb reads 900 - // and 81, the fold 120 and 122. `make chain-audit` runs the - // climb beside every ask, so the count is asserted without it. + // expected: each parenthesis is asked once, by its run. `nested` + // has `n + 2` levels, the parentheses, the statement and the + // module: a run reads its parenthesis and meets the answer the + // run outside it left on the levels above, and the outermost + // reads all three of its own. `block` has `2n + 1`, the + // parentheses, their statements and the block: a run reads its + // parenthesis and its statement, which answers, and the first + // statement has none before it and reads the block. The climb + // reads 900 and 81, the fold 120 and 122. `make chain-audit` + // runs the climb beside every ask, so the count is asserted + // without it. if cfg!(not(chain_audit)) { - assert_eq!((nested_read, block_read), (2 * n + 1, 2 * n + 1)); + assert_eq!((nested_read, block_read), (n + 2, 2 * n + 1)); } } diff --git a/src/metrics/loc/python.rs b/src/metrics/loc/python.rs index 1e56326ab..76bee5d93 100644 --- a/src/metrics/loc/python.rs +++ b/src/metrics/loc/python.rs @@ -432,7 +432,7 @@ fn python_run_inside_bare_string_parentheses<'a>( }; ancestors.memoised_answer(NodeQuestion::BareStringParenthesisLine, &parent, || { python_is_bare_string_parenthesis(&parent, chain) - && !python_code_before_node(code, &parent, chain) + && !python_code_before_parent(code, node, ancestors) }) } @@ -594,41 +594,43 @@ fn python_code_before_string<'a>( if let Some(answer) = python_code_among(code, before_holder, &line.holder, Some(ancestors)) { return answer; } - ancestors - .iter(node) - .next() - .is_some_and(|(parent, chain)| python_code_before_node(code, &parent, chain)) + python_code_before_parent(code, node, ancestors) } -// Whether code precedes `node` on its logical line: among its own -// siblings, or at the deepest level above it that has a token before -// its node. The levels `python_code_before_string` climbs from the -// run's parent once the run's own level is read, and every level a -// parenthesis's memoised answer reads — the parenthesis's inside, where -// nothing before the string can be code, is never one of them. +// Whether code precedes `node`'s parent on its logical line: among the +// parent's own siblings, or at the nearest level above it that has a +// token before its node. The levels `python_code_before_string` climbs +// from the run's parent once the run's own level is read, and every +// level a parenthesis's memoised answer reads — the parenthesis's +// inside, where nothing before the string can be code, is never one of +// them. // -// The levels above `node` are read through the walk's memo of each -// level's nearest answer rather than climbed afresh. A parenthesis whose -// own level holds only comments and `\` splices before it defers to the -// level above, and so does that one: asked from each of `n` nested -// parentheses, the climb read every level above each, `Σ` of their -// extras, quadratic in `n` under CPython's 200-level cap (#1863; -// `loc/python-deep-paren-extra-prefix` prices it). The memo keeps the -// climb's stop at the first level that answers, so a level above it is -// never read (`loc/python-block-comments-paren-strings`). -fn python_code_before_node<'a>(code: &[u8], node: &Node<'a>, ancestors: Ancestors<'a, '_>) -> bool { - python_code_at_level(code, node, ancestors).unwrap_or_else(|| { - ancestors.nearest_level_answer( - node, - LevelQuestion::CodeBeforeOnLine, - code, - python_code_at_level, - ) - }) +// Asked of the run rather than of its parent, so the parent is a level +// like any other: read once per walk through the memo of each level's +// nearest answer, however many runs and nested parentheses reach it. A +// parenthesis whose own level holds only comments and `\` splices +// before it defers to the level above, and so does that one: climbed +// afresh from each of `n` nested parentheses, that read every level +// above each, `Σ` of their extras, quadratic in `n` under CPython's +// 200-level cap (#1863; `loc/python-deep-paren-extra-prefix` prices +// it). The memo keeps the climb's stop at the first level that answers, +// so a level above it is never read +// (`loc/python-block-comments-paren-strings`). +fn python_code_before_parent<'a>( + code: &[u8], + node: &Node<'a>, + ancestors: Ancestors<'a, '_>, +) -> bool { + ancestors.nearest_level_answer( + node, + LevelQuestion::CodeBeforeOnLine, + code, + python_code_at_level, + ) } // `python_code_among` for `level` among its own siblings: one level of -// `python_code_before_node`'s reading, a function of the level alone. +// `python_code_before_parent`'s reading, a function of the level alone. fn python_code_at_level<'a>( code: &[u8], level: &Node<'a>, @@ -638,7 +640,7 @@ fn python_code_at_level<'a>( python_code_among(code, chain.siblings_before(level), level, Some(chain)) } -// Levels `python_code_before_node` reads for a token before their node. +// Levels `python_code_before_parent` reads for a token before their node. // Every way of reading them answers the same, so only this tells a walk // that reads each level once from one that reads every level above // every parenthesis, or a level above the one that answers (#1863). From f0774c3905e45eb30f72133155d53fac0a784ce4 Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Wed, 11 Nov 2026 20:25:55 -0800 Subject: [PATCH 17/21] refactor(checker): leave no default on the with-code predicates or the byte-less pair c935311d made three with-code predicates required and gave the byte-less `is_func_space` / `get_space_kind` a provided forward. Two gaps were left, both the silent default this work removes: - The provided forward carried no build-time pin. `Ccomment` and `Preproc` took it, and a new language that left out `impl_byte_less_func_space!` would have compiled and forwarded a gated opener under `&[]` with no assertion. The pair is required again: the two helper grammars invoke the macros (their rows are absent, so the assertions hold), and Ruby takes the `opener_gated` form in place of an identical hand-written forward, which pins its `Container` row. C# keeps its hand-written forward with its own assertion and Elixir its kind table. - `Checker::is_call_with_code` and `is_string_with_code` still defaulted to their byte-less spellings. Both are required. Every language already emitted them through `impl_row_predicates!` except the two helper grammars' `Call` rows, which are absent. `doc_body_residual_kind!` passes the bytes `holds_doc_comment_in_body` now has, in place of `&[]` behind an assertion that the row reads none. No answer changes: every body a language now writes is the one the default gave it. The module doc of `roles/mod.rs`, the add-lang skill, the book's new-language page and the CHANGELOG say what is required. The rustdoc on `holds_doc_comment_in_body` named a record's header as a callable its `code` serves; Java and Groovy exclude that kind first, so the examples are C#'s primary constructor and a bound arrow. The baseline records `roles/mod.rs` `sloc`. Found by the review, code-review, under-reviewed-areas, Argon and architecture reviewers. Refs #1863 --- .bca-baseline.toml | 2 +- .claude/skills/add-lang/SKILL.md | 12 +- CHANGELOG.md | 12 +- big-code-analysis-ast/src/checker.rs | 126 +++++++++--------- big-code-analysis-ast/src/checker/ccomment.rs | 4 + big-code-analysis-ast/src/checker/csharp.rs | 2 +- big-code-analysis-ast/src/checker/groovy.rs | 2 +- big-code-analysis-ast/src/checker/java.rs | 2 +- big-code-analysis-ast/src/checker/kotlin.rs | 2 +- big-code-analysis-ast/src/checker/preproc.rs | 4 + big-code-analysis-ast/src/checker/ruby.rs | 12 +- big-code-analysis-ast/src/getter.rs | 21 +-- big-code-analysis-ast/src/getter/ccomment.rs | 2 + big-code-analysis-ast/src/getter/preproc.rs | 2 + big-code-analysis-ast/src/getter/ruby.rs | 14 +- big-code-analysis-ast/src/roles/mod.rs | 72 +++++----- .../src/developers/new-language.md | 5 +- src/metrics/cyclomatic.rs | 20 ++- 18 files changed, 180 insertions(+), 136 deletions(-) diff --git a/.bca-baseline.toml b/.bca-baseline.toml index 564b66546..3ce445e08 100644 --- a/.bca-baseline.toml +++ b/.bca-baseline.toml @@ -365,7 +365,7 @@ value = 906.0 path = "big-code-analysis-ast/src/roles/mod.rs" qualified = "" metric = "loc.sloc" -value = 2321.0 +value = 2325.0 [[entry]] path = "big-code-analysis-ast/src/tools.rs" diff --git a/.claude/skills/add-lang/SKILL.md b/.claude/skills/add-lang/SKILL.md index 582ec95fc..e8baeae31 100644 --- a/.claude/skills/add-lang/SKILL.md +++ b/.claude/skills/add-lang/SKILL.md @@ -544,11 +544,13 @@ Create the file, add `mod ;` to `checker.rs`, and write for `is_closure` (#1696). The two `_with_code` predicates are required: the trait gives them no default (#1863). Copy the Lua or Go shape, including `impl_byte_less_func_space!`, which emits the - byte-less `is_func_space` with its build-time pin. + byte-less `is_func_space` with its build-time pin. That one is + required too, so the build fails without the macro. - `is_call`, `is_call_with_code`, `is_string`, `is_string_with_code` — one `impl_row_predicates!(, call, …)` and one `impl_row_predicates!(, string_lit, …)` line each - (#1698). + (#1698). The two `_with_code` predicates are required (#1863), so + both lines are needed even where a row is `absent`. - `is_non_arg` — punctuation kinds inside argument lists (`LPAREN`, `COMMA`, `RPAREN`, etc.). Not a role; written by kind. - `is_else_if` — `#[inline]`. **Do not blind-copy the Go @@ -601,9 +603,9 @@ Create the file, add `mod ;` to `getter.rs`, and write over every `opens K` annotation on the `FuncOpener` and `Container` rows (#1696). `impl_byte_less_space_kind!();` emits the byte-less `get_space_kind` with its build-time pin, as the Lua and - Go impls do; `is_func_space` and `get_space_kind` must read the same - predicate or the space tree disagrees with itself - (`grammar-dispatch.md` §7). + Go impls do; it is required too. `is_func_space` and + `get_space_kind` must read the same predicate or the space tree + disagrees with itself (`grammar-dispatch.md` §7). - `keyword_roles!();` — emits `get_keyword_role`, which is **required** by the trait (no default), from the `Modifier`, `DeclKeyword` and `Primitive` rows. Pass `primitive: Operand` if the diff --git a/CHANGELOG.md b/CHANGELOG.md index d046c6f0a..aca8f03a5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -76,8 +76,12 @@ for historical reference. `Getter::get_space_kind_with_code` defaulted to their byte-less spellings, so a language that wrote only the byte-less one handed a text-gated role row no bytes, silently. The three are now required - methods, and `is_func_space` and `get_space_kind` default to the - with-code form asked with no bytes and a known-empty chain. + methods, as are `Checker::is_call_with_code` and + `is_string_with_code`, whose defaults forwarded the same way. The + byte-less `is_func_space` and `get_space_kind` are required too: + every language's spelling asks the with-code form with no bytes and + a known-empty chain, through a macro that pins at build time that + the rows read neither, or by hand beside the reason. `Checker::is_func` answered three different questions across the languages and is gone; its readers ask `is_func_with_code`. `Checker::holds_doc_comment_in_body` gains a `code` parameter for the @@ -92,8 +96,8 @@ for historical reference. `short_circuit_operator`. The keyword changes no answer. - `roles::java::record_header` and `roles::groovy::record_header` name a record's component list once; the header gate, the space's - name, `nargs` and `npm` read them where each spelled the field or - the kind pair itself. + name, Java's `nargs` and `npm` read them where each spelled the + field or the kind pair itself. - The record-header gate reads the header's component types once per evaluation rather than once per constructor it compares. New scaling probes `nargs/java-record-alternative-ctors` and diff --git a/big-code-analysis-ast/src/checker.rs b/big-code-analysis-ast/src/checker.rs index 60535004d..243b930b4 100644 --- a/big-code-analysis-ast/src/checker.rs +++ b/big-code-analysis-ast/src/checker.rs @@ -124,14 +124,17 @@ macro_rules! impl_byte_gated_row_predicate { // chain or the bytes by design, so that only the `Container` row is // asserted — and that the opener *is* gated, so the form cannot be // taken by a language whose rows the plain form would check: the -// gated opener answers `false` under the known-empty chain, a -// disagreement the language pins at runtime by value (a Java or -// Groovy record's header, #1842). Ruby's opener is chain-gated by -// design and keeps a hand-written forward pinned at runtime instead -// (`ruby_byte_less_spellings_stay_the_kind_table`), as C#'s is since -// #1828 (`csharp_byte_less_spellings_omit_the_primary_constructor`); -// Elixir hand-writes the byte-less one. Per-language rationale — which -// rows, what the gated one reads — sits above the invocation. +// gated opener answers its rootless verdict under the known-empty +// chain, a disagreement the language pins at runtime by value — +// `false` for a Java or Groovy record's header (#1842), `true` for a +// Ruby lambda's body block (`ruby_byte_less_spellings_stay_the_kind_table`). +// C#'s opener is chain-gated too and keeps a hand-written forward with +// a stricter pin since #1828 +// (`csharp_byte_less_spellings_omit_the_primary_constructor`); Elixir +// hand-writes the byte-less one as its kind table. The trait gives the +// spelling no default, so no language takes the forward without one of +// these (#1863). Per-language rationale — which rows, what the gated +// one reads — sits above the invocation. macro_rules! impl_byte_less_func_space { ($roles:ident) => { fn is_func_space(node: &Node) -> bool { @@ -176,19 +179,15 @@ macro_rules! impl_doc_run_directive_from_row { // The `DocBodyResidual` row of a language, read inside its hand-written // `holds_doc_comment_in_body` for the kinds it names beyond the -// callables and closures (#1699): asked with `ancestors`, the chain the -// trait hands in (the ancestor's own), and no bytes — exact while no -// such row reads bytes, which the build asserts. An expression rather -// than an emitted method, so the per-language branch order and the -// body-child test stay visible in `checker/.rs`. +// callables and closures (#1699): asked with the bytes and `ancestors`, +// the chain the trait hands in (the ancestor's own), as the callable +// test beside it is (#1863). An expression rather than an emitted +// method, so the per-language branch order and the body-child test stay +// visible in `checker/.rs`. macro_rules! doc_body_residual_kind { - ($roles:ident, $ancestor:expr, $ancestors:expr) => {{ - const _: () = assert!( - !$crate::roles::$roles::doc_body_residual::TEXT_GATED, - "the `DocBodyResidual` row reads bytes; the body test cannot forward with `&[]`" - ); - $crate::roles::$roles::doc_body_residual::owns($ancestor, &[], $ancestors) - }}; + ($roles:ident, $ancestor:expr, $code:expr, $ancestors:expr) => { + $crate::roles::$roles::doc_body_residual::owns($ancestor, $code, $ancestors) + }; } // Emits a `Checker::is_doc_target` that reads the language's `DocTarget` @@ -357,11 +356,15 @@ impl SubtreeSkip { /// so adding a language no longer requires copy-pasting `-> false` stubs. /// The flip side is that the compiler cannot flag a forgotten override, so /// each language's per-metric tests are the safety net for completeness. -/// The two the space tree is built from are the exception: -/// [`is_func_space_with_code`](Self::is_func_space_with_code) and -/// [`is_func_with_code`](Self::is_func_with_code) are required, so a -/// language cannot answer them by forwarding to a spelling that drops -/// the bytes or the chain (#1863). +/// The predicates a walk asks with the bytes and the chain in hand are +/// the exception: [`is_func_space_with_code`](Self::is_func_space_with_code), +/// [`is_func_with_code`](Self::is_func_with_code), +/// [`is_call_with_code`](Self::is_call_with_code) and +/// [`is_string_with_code`](Self::is_string_with_code) are required, so +/// a language cannot answer one by inheriting a forward to a spelling +/// that drops the bytes or the chain; and so is the byte-less +/// [`is_func_space`](Self::is_func_space), whose forward the other way +/// carries a build-time pin a default could not (#1863). /// /// `#[doc(hidden)]` for the reason the crate root gives: this is /// plumbing, and the surface the README points a reader at is `LANG` / @@ -434,9 +437,9 @@ pub trait Checker { /// so a doc comment after an annotation or on a parameter documents /// nothing there. A language whose tool reads doc comments in the /// signature narrows this to the body proper (#1597). `code` is - /// the source, for the callable test: a callable told by its bytes - /// or its chain (a record's header, a bound arrow) is asked as the - /// walk asks it (#1863). + /// the source, for the callable test and the residual row: a + /// callable told by its chain or its bytes (C#'s primary + /// constructor, a bound arrow) is asked as the walk asks it (#1863). #[inline] #[must_use] fn holds_doc_comment_in_body<'a>( @@ -535,18 +538,22 @@ pub trait Checker { /// namespace, interface). /// /// The byte-less spelling of - /// [`is_func_space_with_code`](Self::is_func_space_with_code), and - /// by default that predicate asked with no bytes and a known-empty - /// chain — the node read as if it were the root (#1863). It agrees - /// with the walk wherever no space-opening gate reads either, and - /// answers the gate's rootless, byte-less verdict where one does - /// (Ruby's lambda body, C#'s primary constructor, a Java or Groovy - /// record's header). The walk calls the `_with_code` one. - #[inline] + /// [`is_func_space_with_code`](Self::is_func_space_with_code): that + /// predicate asked with no bytes and a known-empty chain, the node + /// read as if it were the root. It agrees with the walk wherever no + /// space-opening gate reads either, and answers the gate's + /// rootless, byte-less verdict where one does (Elixir's `def` and + /// `defmodule` calls, Ruby's lambda body, C#'s primary constructor, + /// a Java or Groovy record's header). The walk calls the + /// `_with_code` one. + /// + /// Required, with no default (#1863): a language emits it through + /// `impl_byte_less_func_space!`, which pins at build time that the + /// rows it forwards to read neither, or writes it by hand beside + /// the reason it cannot. A provided forward would hand a new + /// language the spelling without the pin. #[must_use] - fn is_func_space(node: &Node) -> bool { - Self::is_func_space_with_code(node, &[], Ancestors::known(&[])) - } + fn is_func_space(node: &Node) -> bool; /// Whether `node` is an anonymous function — the complement of /// [`is_func_with_code`](Self::is_func_with_code) on the grammars /// that express both. `ancestors` is the chain the caller descended @@ -612,21 +619,20 @@ pub trait Checker { } /// [`is_call`](Self::is_call), given the source bytes and the /// chain the caller descended through, which the `call` filter - /// hands it. The default forwards to [`is_call`](Self::is_call). + /// hands it: the language's `Call` row under its gates. Required + /// (#1863): a default forwarding to the byte-less [`is_call`](Self::is_call) + /// answered a gated row from its kind table without a word. /// - /// Perl overrides it: the grammar nests a call's name inside the + /// Perl's row is gated: the grammar nests a call's name inside the /// call as a bareword call of its own, and parses an auto-quoted /// hash key as one, so only the position says which words are /// calls (#1580). As with [`is_string_with_code`](Self::is_string_with_code), /// a call site reaching for the byte-less spelling reads as correct - /// against every language without an override; + /// against every language with an ungated row; /// `perl_bareword_is_a_call_only_to_the_byteless_spelling` pins that /// the two really do disagree. - #[inline] #[must_use] - fn is_call_with_code<'a>(node: &Node<'a>, _code: &[u8], _ancestors: Ancestors<'a, '_>) -> bool { - Self::is_call(node) - } + fn is_call_with_code<'a>(node: &Node<'a>, code: &[u8], ancestors: Ancestors<'a, '_>) -> bool; /// Whether `node`, met among a parameter list's children, is /// punctuation or a keyword rather than a parameter (`nargs` skips it). #[inline] @@ -687,20 +693,21 @@ pub trait Checker { false } /// Source-aware variant of [`is_string`](Self::is_string), and the - /// spelling every walk calls. + /// spelling every walk calls: the language's `StringLit` row under + /// its gates. Required (#1863): a default forwarding to the + /// byte-less predicate answered a gated row from its kind table + /// without a word. /// - /// The default forwards to the byte-less predicate, so a language - /// whose string literals are a closed set of kinds needs no - /// override. The Tcl family is the case that does: `braced_word` is - /// both the literal of `lappend x {a b}` and the *script* of a - /// `proc` body or an iRules `when` handler, and only the enclosing - /// command's leading word tells the two apart (#1318, #1381). So + /// The Tcl family's row is gated: `braced_word` is both the literal + /// of `lappend x {a b}` and the *script* of a `proc` body or an + /// iRules `when` handler, and only the enclosing command's leading + /// word tells the two apart (#1318, #1381). Read by kind, /// `bca find --type string` reported every script body in the file /// as a string literal. /// /// **A call site reaching for the byte-less spelling reads as - /// correct against every language without an override, and is wrong - /// only on the one that has one** — + /// correct against every language with an ungated row, and is wrong + /// only on the one whose row is gated** — /// `docs/development/grammar_dispatch.md` §7. There is one call site, /// the `"string"` arm of [`ParserTrait::filters`], and it takes this /// spelling; `tcl_script_body_is_a_string_only_to_the_byteless_spelling` @@ -708,15 +715,8 @@ pub trait Checker { /// picks the wrong one is not silently right. /// /// [`ParserTrait::filters`]: crate::traits::ParserTrait::filters - #[inline] #[must_use] - fn is_string_with_code<'a>( - node: &Node<'a>, - _code: &[u8], - _ancestors: Ancestors<'a, '_>, - ) -> bool { - Self::is_string(node) - } + fn is_string_with_code<'a>(node: &Node<'a>, code: &[u8], ancestors: Ancestors<'a, '_>) -> bool; /// Whether `node` is the `if` that continues an `else if` chain, /// rather than a freshly nested branch. /// diff --git a/big-code-analysis-ast/src/checker/ccomment.rs b/big-code-analysis-ast/src/checker/ccomment.rs index 0d7cc5fec..391d0aefd 100644 --- a/big-code-analysis-ast/src/checker/ccomment.rs +++ b/big-code-analysis-ast/src/checker/ccomment.rs @@ -9,6 +9,8 @@ impl Checker for CcommentCode { // The `FuncOpener` and `Container` rows of `roles/ccomment.rs` are // absent: the pass opens no space and names no function. + impl_byte_less_func_space!(ccomment); + fn is_func_space_with_code<'a>( node: &Node<'a>, code: &[u8], @@ -25,5 +27,7 @@ impl Checker for CcommentCode { get_aho_corasick_match(&code[node.start_byte()..node.end_byte()]) } + // The `Call` row is absent: the pass names no call. + impl_row_predicates!(ccomment, call, is_call, is_call_with_code); impl_row_predicates!(ccomment, string_lit, is_string, is_string_with_code); } diff --git a/big-code-analysis-ast/src/checker/csharp.rs b/big-code-analysis-ast/src/checker/csharp.rs index 9936da322..cf8fc98b9 100644 --- a/big-code-analysis-ast/src/checker/csharp.rs +++ b/big-code-analysis-ast/src/checker/csharp.rs @@ -59,7 +59,7 @@ impl Checker for CsharpCode { ancestors: Ancestors<'a, '_>, below: &Node<'a>, ) -> bool { - if doc_body_residual_kind!(csharp, ancestor, ancestors) { + if doc_body_residual_kind!(csharp, ancestor, code, ancestors) { return below.kind_id() != Csharp::AccessorList; } Self::is_func_with_code(ancestor, code, ancestors) || Self::is_closure(ancestor, ancestors) diff --git a/big-code-analysis-ast/src/checker/groovy.rs b/big-code-analysis-ast/src/checker/groovy.rs index bc205c5d3..d6152d905 100644 --- a/big-code-analysis-ast/src/checker/groovy.rs +++ b/big-code-analysis-ast/src/checker/groovy.rs @@ -51,7 +51,7 @@ impl Checker for GroovyCode { ancestor.kind_id() != Groovy::RecordComponents as u16 && (Self::is_func_with_code(ancestor, code, ancestors) || Self::is_closure(ancestor, ancestors) - || doc_body_residual_kind!(groovy, ancestor, ancestors)) + || doc_body_residual_kind!(groovy, ancestor, code, ancestors)) } // Mirrors `impl Checker for JavaCode` exactly: `EnumDeclaration`, diff --git a/big-code-analysis-ast/src/checker/java.rs b/big-code-analysis-ast/src/checker/java.rs index 38dbdf55e..e1f942d1c 100644 --- a/big-code-analysis-ast/src/checker/java.rs +++ b/big-code-analysis-ast/src/checker/java.rs @@ -53,7 +53,7 @@ impl Checker for JavaCode { ancestor.kind_id() != Java::FormalParameters as u16 && (Self::is_func_with_code(ancestor, code, ancestors) || Self::is_closure(ancestor, ancestors) - || doc_body_residual_kind!(java, ancestor, ancestors)) + || doc_body_residual_kind!(java, ancestor, code, ancestors)) } // The space tree is declared in `roles/java.rs` (#1696): the diff --git a/big-code-analysis-ast/src/checker/kotlin.rs b/big-code-analysis-ast/src/checker/kotlin.rs index 60553cd3c..8eca6db7d 100644 --- a/big-code-analysis-ast/src/checker/kotlin.rs +++ b/big-code-analysis-ast/src/checker/kotlin.rs @@ -81,7 +81,7 @@ impl Checker for KotlinCode { } (Self::is_func_with_code(ancestor, code, ancestors) || Self::is_closure(ancestor, ancestors) - || doc_body_residual_kind!(kotlin, ancestor, ancestors)) + || doc_body_residual_kind!(kotlin, ancestor, code, ancestors)) && matches!(below.kind_id().into(), Kotlin::FunctionBody | Kotlin::Block) } diff --git a/big-code-analysis-ast/src/checker/preproc.rs b/big-code-analysis-ast/src/checker/preproc.rs index b1db44904..5849e5656 100644 --- a/big-code-analysis-ast/src/checker/preproc.rs +++ b/big-code-analysis-ast/src/checker/preproc.rs @@ -9,6 +9,8 @@ impl Checker for PreprocCode { // The `FuncOpener` and `Container` rows of `roles/preproc.rs` are // absent: the pass opens no space and names no function. + impl_byte_less_func_space!(preproc); + fn is_func_space_with_code<'a>( node: &Node<'a>, code: &[u8], @@ -21,5 +23,7 @@ impl Checker for PreprocCode { crate::roles::preproc::func_opener::is_callable(node, code, ancestors) } + // The `Call` row is absent: the pass names no call. + impl_row_predicates!(preproc, call, is_call, is_call_with_code); impl_row_predicates!(preproc, string_lit, is_string, is_string_with_code); } diff --git a/big-code-analysis-ast/src/checker/ruby.rs b/big-code-analysis-ast/src/checker/ruby.rs index 0d83e4027..459dd89bd 100644 --- a/big-code-analysis-ast/src/checker/ruby.rs +++ b/big-code-analysis-ast/src/checker/ruby.rs @@ -117,13 +117,13 @@ impl Checker for RubyCode { // `Ancestors::unknown()`, which climbs through `Node::parent` and // would answer the gated result here — a change in this spelling's // answer no output could see. The walk calls the `_with_code` one. - // No `!CHAIN_GATED` assertion, unlike every other language's forward - // (#1793): the row *is* chain-gated by design, and + // The `opener_gated` form: no `!CHAIN_GATED` assertion on the opener + // row, unlike most languages' forward (#1793), since the row *is* + // chain-gated by design and // `ruby_byte_less_spellings_stay_the_kind_table` - // (`roles/space_tree_tests.rs`) pins the disagreement by value. - fn is_func_space(node: &Node) -> bool { - Self::is_func_space_with_code(node, &[], Ancestors::known(&[])) - } + // (`roles/space_tree_tests.rs`) pins the disagreement by value; the + // `Container` row is pinned at build time (#1863). + impl_byte_less_func_space!(ruby, opener_gated); fn is_func_space_with_code<'a>( node: &Node<'a>, diff --git a/big-code-analysis-ast/src/getter.rs b/big-code-analysis-ast/src/getter.rs index e97bde63d..daf59a33a 100644 --- a/big-code-analysis-ast/src/getter.rs +++ b/big-code-analysis-ast/src/getter.rs @@ -78,8 +78,9 @@ macro_rules! get_operator { // (#1793). The `opener_gated` form asserts the `Container` row alone, // and that the opener row is gated at all, for a language whose opener // row reads the chain or the bytes by design and labels the gated -// owner `Unknown` here, as the Checker half answers `false`. Ruby, C# -// and Elixir keep hand-written spellings for the reasons given there. +// owner by its rootless verdict here, as the Checker half answers it. +// C# and Elixir keep hand-written spellings for the reasons given +// there. macro_rules! impl_byte_less_space_kind { ($roles:ident) => { fn get_space_kind(node: &Node) -> SpaceKind { @@ -390,13 +391,13 @@ pub trait Getter { /// The kind of space `node` opens by its kind alone, or /// [`SpaceKind::Unknown`] when it opens none: the byte-less spelling /// of [`get_space_kind_with_code`](Self::get_space_kind_with_code), - /// and by default that classifier asked with no bytes and a - /// known-empty chain, as `Checker::is_func_space` is of its own - /// (#1863). The walk calls the `_with_code` one. + /// that classifier asked with no bytes and a known-empty chain. The + /// walk calls the `_with_code` one. Required, as + /// `Checker::is_func_space` is and for its reason (#1863): a + /// language emits it through `impl_byte_less_space_kind!`, which + /// carries the build-time pin, or writes it by hand. #[must_use] - fn get_space_kind(node: &Node) -> SpaceKind { - Self::get_space_kind_with_code(node, &[], Ancestors::known(&[])) - } + fn get_space_kind(node: &Node) -> SpaceKind; /// The kind of space `node` opens, as the walk asks it: with the /// source bytes and the chain it descended through. Required: every @@ -2058,6 +2059,10 @@ mod keyword_role_tests { macro_rules! conflicting_getter { ($name:ident, $row:ident, $arm:ident) => { impl Getter for $name { + fn get_space_kind(_node: &Node) -> crate::SpaceKind { + crate::SpaceKind::Unknown + } + fn get_space_kind_with_code<'a>( _node: &Node<'a>, _code: &[u8], diff --git a/big-code-analysis-ast/src/getter/ccomment.rs b/big-code-analysis-ast/src/getter/ccomment.rs index 43f0d924f..df89bdaa7 100644 --- a/big-code-analysis-ast/src/getter/ccomment.rs +++ b/big-code-analysis-ast/src/getter/ccomment.rs @@ -10,6 +10,8 @@ impl Getter for CcommentCode { keyword_roles!(ccomment); // No row of `roles/ccomment.rs` opens a space. + impl_byte_less_space_kind!(ccomment); + fn get_space_kind_with_code<'a>( node: &Node<'a>, code: &[u8], diff --git a/big-code-analysis-ast/src/getter/preproc.rs b/big-code-analysis-ast/src/getter/preproc.rs index 80d40e61c..5b83e80fc 100644 --- a/big-code-analysis-ast/src/getter/preproc.rs +++ b/big-code-analysis-ast/src/getter/preproc.rs @@ -10,6 +10,8 @@ impl Getter for PreprocCode { keyword_roles!(preproc); // No row of `roles/preproc.rs` opens a space. + impl_byte_less_space_kind!(preproc); + fn get_space_kind_with_code<'a>( node: &Node<'a>, code: &[u8], diff --git a/big-code-analysis-ast/src/getter/ruby.rs b/big-code-analysis-ast/src/getter/ruby.rs index c0504600e..ad66e13b9 100644 --- a/big-code-analysis-ast/src/getter/ruby.rs +++ b/big-code-analysis-ast/src/getter/ruby.rs @@ -11,14 +11,14 @@ impl Getter for RubyCode { // declines it (#1257). It forwards with a *known-empty* chain — the // node read as if it were the root, so the parent gate sees no // lambda — and not `Ancestors::unknown()`, which climbs through - // `Node::parent` and would answer the gated result. No `!CHAIN_GATED` - // assertion, unlike every other language's forward (#1793): the row - // is chain-gated by design, and + // `Node::parent` and would answer the gated result. The + // `opener_gated` form: no `!CHAIN_GATED` assertion on the opener + // row, unlike most languages' forward (#1793), since the row is + // chain-gated by design and // `ruby_byte_less_spellings_stay_the_kind_table` pins the - // disagreement by value. - fn get_space_kind(node: &Node) -> SpaceKind { - Self::get_space_kind_with_code(node, &[], Ancestors::known(&[])) - } + // disagreement by value; the `Container` row is pinned at build + // time (#1863). + impl_byte_less_space_kind!(ruby, opener_gated); fn get_space_kind_with_code<'a>( node: &Node<'a>, diff --git a/big-code-analysis-ast/src/roles/mod.rs b/big-code-analysis-ast/src/roles/mod.rs index 1e9eb9c02..4b661ba8a 100644 --- a/big-code-analysis-ast/src/roles/mod.rs +++ b/big-code-analysis-ast/src/roles/mod.rs @@ -406,38 +406,42 @@ //! //! - **Reach for the `_with_code` spelling** — that is what the walk //! calls (`promotes_to_func_space_with_code`, -//! `get_space_kind_with_code`). The three the space tree is built -//! from — `Checker::is_func_with_code`, -//! `Checker::is_func_space_with_code` and -//! `Getter::get_space_kind_with_code` — are required of every -//! language, and a byte-less spelling derives from one, never the -//! reverse (#1863): a trait default forwarding with-code to byte-less -//! handed a text-gated row no bytes without a word. The callable test -//! has no byte-less spelling at all: a callable can be told by its -//! bytes, by its chain, or by one gate reading both (a Java or Groovy -//! record's header, #1842), so a byte-less `is_func` answered three -//! different questions across the languages. The legacy `Checker` -//! spellings that remain come in three shapes, and only one of them -//! is the ungated kind set. `is_call`, `is_string` and `is_comment` -//! take neither bytes nor a chain and read `lists_kind`. -//! `is_func_space` and `get_space_kind` take neither either, and -//! forward to the `_with_code` form with `&[]` and a *known-empty* -//! chain, `Ancestors::known(&[])` — never `Ancestors::unknown()`, -//! which climbs through `Node::parent` and answers the gated result, -//! so the spelling would silently stop being the kind set (lesson -//! 114); a gate that reads only the node's own children (Java's -//! anonymous-class body) still applies there. That forward is the -//! trait default, and a language's own spelling of it adds only the -//! build-time pin below. `is_closure` and `is_else_if` take the -//! caller's chain and hand it through with `&[]` bytes, so a chain -//! gate (Ruby's `block` under a stabby lambda) answers exactly and -//! only a byte gate is dropped. The chain-less pair disagrees with -//! the walk wherever a gate reads what it drops — Elixir's text-gated -//! `call` openers, Ruby's `block`, C#'s `parameter_list` under a type -//! declaration (#1828), the record header — and the derived parity -//! suite pins each such disagreement by name (`KNOWN_DISAGREEMENTS`). -//! Every other language's pair asserts `!TEXT_GATED && !CHAIN_GATED` -//! on its `FuncOpener` and `Container` rows at build time (#1793). +//! `get_space_kind_with_code`). The predicates a walk asks with the +//! bytes and the chain in hand — `Checker::is_func_with_code`, +//! `is_func_space_with_code`, `is_call_with_code`, +//! `is_string_with_code` and `Getter::get_space_kind_with_code` — are +//! required of every language, with no default (#1863): a trait +//! default forwarding with-code to byte-less handed a gated row no +//! bytes without a word. The callable test has no byte-less spelling +//! at all: a callable can be told by its bytes, by its chain, or by +//! one gate reading both (a Java or Groovy record's header, #1842), +//! so a byte-less `is_func` answered three different questions across +//! the languages. The legacy `Checker` spellings that remain come in +//! three shapes, and only one of them is the ungated kind set. +//! `is_call`, `is_string` and `is_comment` take neither bytes nor a +//! chain and read `lists_kind`. `is_func_space` and `get_space_kind` +//! take neither either, and forward to the `_with_code` form with +//! `&[]` and a *known-empty* chain, `Ancestors::known(&[])` — never +//! `Ancestors::unknown()`, which climbs through `Node::parent` and +//! answers the gated result, so the spelling would silently stop +//! being the kind set (lesson 114); a gate that reads only the node's +//! own children (Java's anonymous-class body) still applies there. +//! Both are required too, so that no language takes that forward +//! without its pin. `impl_byte_less_func_space!` and +//! `impl_byte_less_space_kind!` emit it and assert +//! `!TEXT_GATED && !CHAIN_GATED` on the `FuncOpener` and `Container` +//! rows at build time (#1793), or on the `Container` row alone where +//! the opener is gated by design (the `opener_gated` form: Ruby, +//! Java, Groovy); C# writes it by hand with an assertion of its own, +//! and Elixir as its kind table. `is_closure` and `is_else_if` take +//! the caller's chain and hand it through with `&[]` bytes, so a +//! chain gate (Ruby's `block` under a stabby lambda) answers exactly +//! and only a byte gate is dropped. The chain-less pair disagrees +//! with the walk wherever a gate reads what it drops — Elixir's +//! text-gated `call` openers, Ruby's `block`, C#'s `parameter_list` +//! under a type declaration (#1828), the record header — and the +//! derived parity suite pins each such disagreement by name +//! (`KNOWN_DISAGREEMENTS`). //! - **Ask several rows of one node through the `_kind` projections**, //! reading `kind_id()` once. //! - **A consumer's policy over a row is the consumer's.** Which @@ -460,8 +464,8 @@ //! declaration to the child a row gates: `record_header` //! (`roles/java.rs`, `roles/groovy.rs`) projects a record's component //! list, read by the `FuncOpener` gate and by the getter's naming, -//! `nargs` and `npm`, where each had spelled the field name or the -//! kind pair itself (#1863). C#'s primary constructor has no such +//! Java's `nargs` and `npm`, where each had spelled the field name or +//! the kind pair itself (#1863). C#'s primary constructor has no such //! projection: its list sits in no field, the grammar admits more //! than one under a type declaration, and the row's `under` list is //! the whole relation. diff --git a/big-code-analysis-book/src/developers/new-language.md b/big-code-analysis-book/src/developers/new-language.md index d9b8251ce..b52becd57 100644 --- a/big-code-analysis-book/src/developers/new-language.md +++ b/big-code-analysis-book/src/developers/new-language.md @@ -118,8 +118,9 @@ workspace defines: which forward to the language's role table (below). - **`Getter`** in a new per-language file under [/big-code-analysis-ast/src/getter/](https://github.com/dekobon/big-code-analysis/tree/main/big-code-analysis-ast/src/getter) - (`getter/.rs`, registered in `getter.rs`): `get_space_kind` - plus the Halstead operator/operand classification table. + (`getter/.rs`, registered in `getter.rs`): + `get_space_kind_with_code`, its byte-less `get_space_kind`, and the + Halstead operator/operand classification table. - **`Alterator`** in [/big-code-analysis-ast/src/alterator.rs](https://github.com/dekobon/big-code-analysis/blob/main/big-code-analysis-ast/src/alterator.rs): an `alterate` body that flattens the kinds the language's `StringLit` diff --git a/src/metrics/cyclomatic.rs b/src/metrics/cyclomatic.rs index 2007f1079..3c6c2a8c0 100644 --- a/src/metrics/cyclomatic.rs +++ b/src/metrics/cyclomatic.rs @@ -464,11 +464,15 @@ mod tests { mod constrained_probe { use super::*; - // A `Checker` that opens no space and names no function: the two - // predicates the trait requires, answered `false`. + // A `Checker` that opens no space and names no function, call + // or string: the predicates the trait requires, answered `false`. macro_rules! probe_checker { ($name:ident) => { impl Checker for $name { + fn is_func_space(_: &Node) -> bool { + false + } + fn is_func_space_with_code<'a>( _: &Node<'a>, _: &[u8], @@ -480,6 +484,18 @@ mod tests { fn is_func_with_code<'a>(_: &Node<'a>, _: &[u8], _: Ancestors<'a, '_>) -> bool { false } + + fn is_call_with_code<'a>(_: &Node<'a>, _: &[u8], _: Ancestors<'a, '_>) -> bool { + false + } + + fn is_string_with_code<'a>( + _: &Node<'a>, + _: &[u8], + _: Ancestors<'a, '_>, + ) -> bool { + false + } } }; } From e3d0cca89124c5b809d67d78964fea069ea2c3c2 Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Wed, 11 Nov 2026 20:26:13 -0800 Subject: [PATCH 18/21] test(roles,npm): close the test gaps the reviews of the batch found - The byte backstop walked a bare chain. A gate that reads a sibling under a parent wider than `WIDE_PARENT` (the `ElseIf` rows of Java, Groovy, C# and Kotlin) would have tripped the walk-must-lend assertion on the first such fixture, as a panic rather than a byte finding. It now walks with the sibling cache and withholds only the `FoldCache` (`Ancestors::without_folds`, test-only). - Nothing checked that a `BYTE_GATE_FIXTURES` row still moves the gate it was written for. The backstop skips a marked owner, so a fixture a grammar bump left answering alike both ways would leave that gate unguarded with every test green. `byte_gate_fixtures_each_move_a_marked_gate` asserts it, and still checks the table names. - `has_public_modifier` reads `modifiers` as child 0 and no test wrote anything ahead of `public`. `java_public_is_read_past_what_precedes_it` pins a doc comment, annotations, a comment among them, a comment after the keyword and type parameters. - `header_answers` and `header_type_reads` rebuilt "is this list its parent's header" from `record_header`; they read `is_record_header`, which had no direct row. - `record_header_is_a_method` took the projection as an `impl FnOnce` it called once on its own argument; it takes the header. Docs: `nearest_level_answer` states that it needs the node's whole ancestry, and `below` that a level question must not be asked from a re-rooted chain; `NodeMemo` and `MemoQuestion` describe the ancestry answer they now hold; "each ancestor once per walk" is "once per child the walk asks under" on the two fold entry points; lessons 65 and 120 name the current predicates; `BYTE_GATE_FIXTURES` says why it is keyed by table name. The baseline records `node/ancestors.rs` `sloc`. Refs #1863 --- .bca-baseline.toml | 2 +- big-code-analysis-ast/src/node/ancestors.rs | 80 +++++++++++++------ .../src/roles/derived_parity_tests.rs | 70 ++++++++++++---- big-code-analysis-ast/src/roles/java.rs | 4 +- .../src/roles/space_tree_tests.rs | 32 +++++--- docs/development/grammar_dispatch.md | 5 +- docs/development/lessons_learned.md | 10 ++- src/metrics/npm.rs | 62 +++++++++++--- src/metrics/npm/groovy.rs | 2 +- 9 files changed, 190 insertions(+), 77 deletions(-) diff --git a/.bca-baseline.toml b/.bca-baseline.toml index 3ce445e08..5f732e855 100644 --- a/.bca-baseline.toml +++ b/.bca-baseline.toml @@ -305,7 +305,7 @@ value = 704.0 path = "big-code-analysis-ast/src/node/ancestors.rs" qualified = "" metric = "loc.sloc" -value = 1501.0 +value = 1519.0 [[entry]] path = "big-code-analysis-ast/src/node/ancestors.rs" diff --git a/big-code-analysis-ast/src/node/ancestors.rs b/big-code-analysis-ast/src/node/ancestors.rs index 36bec27fb..0fcdd427a 100644 --- a/big-code-analysis-ast/src/node/ancestors.rs +++ b/big-code-analysis-ast/src/node/ancestors.rs @@ -198,6 +198,21 @@ impl<'tree, 'chain> Ancestors<'tree, 'chain> { } } + /// This chain with the walk's [`FoldCache`] withheld and its + /// [`SiblingCache`] kept. Test-only, for a test that asks one + /// question twice with different inputs: a memo is keyed by node, + /// so through the cache the second ask would be served the first + /// one's answer. + #[cfg(test)] + #[inline] + #[must_use] + pub(crate) const fn without_folds(self) -> Self { + Self { + folds: None, + ..self + } + } + /// The chain a walk hands its predicates for `node`, the node it is /// visiting: [`checked`](Self::checked) on `chain`, lending `folds` /// with the visit recorded on it (#1737) and answering sibling @@ -333,7 +348,8 @@ impl<'tree, 'chain> Ancestors<'tree, 'chain> { /// ambient — climbs to the root from every node and is quadratic in /// depth (#1767). Under a walk that lent a [`FoldCache`] this folds /// the answer down the chain on `lane` instead, each ancestor once - /// per walk: a `stop` resets it, a `check` sets it. Elsewhere the + /// per child the walk asks under: a `stop` resets it, a `check` sets + /// it, and both are kind tests. Elsewhere the /// climb is the cheaper of the two and is what runs, so a caller /// with no cache keeps the climb's cost. /// @@ -384,8 +400,9 @@ impl<'tree, 'chain> Ancestors<'tree, 'chain> { /// chain where there is none: a function in each of `n` nested /// containers scanned `n²` entries (#1864). Under a walk that lent a /// [`FoldCache`] the answer is folded down the chain on `lane`, each - /// ancestor once per walk; elsewhere the scan is what runs, since an - /// unmemoised fold would start at the root for every ask. + /// ancestor's kind once per child the walk asks under; elsewhere the + /// scan is what runs, since an unmemoised fold would start at the + /// root for every ask. /// /// A lane memoises whatever its first asker folded, so every ask on /// `lane` within one walk must pass the same `kinds`: each @@ -443,19 +460,24 @@ impl<'tree, 'chain> Ancestors<'tree, 'chain> { /// passed. So `answer` runs at most once per level per walk, and /// never on a level above the nearest one that answers. /// - /// Not [`fold_down`](Self::fold_down), which this was first written - /// on: a fold evaluates every ancestor, the ones above the nearest + /// A fold ([`fold_down`](Self::fold_down)) does not fit this + /// question: it evaluates every ancestor, the ones above the nearest /// answer included, and stores an ancestor's state under the child - /// on the path, so a level whose answer is a long scan was scanned - /// again for each child asked from. `n` statements in a block behind - /// `k` comments cost `n × k` where the plain climb costs `n + k`. + /// on the path, so a level whose answer is a long scan is scanned + /// again for each child asked from. /// - /// The memo hands every later asker the first one's answer, so each - /// [`LevelQuestion`] belongs to one `answer` per walk, and `answer` - /// is a plain `fn` of the source, the ancestor and the ancestor's - /// own chain: a closure that captured the asking node would answer - /// for it at every level. `make chain-audit` checks every memoised - /// answer against the climb. + /// The memo is keyed by the level alone and hands every later asker + /// the first one's answer. Three things follow. Each + /// [`LevelQuestion`] belongs to one `answer` per walk. `answer` is a + /// plain `fn` of the source, the ancestor and the ancestor's own + /// chain: a closure that captured the asking node would answer for + /// it at every level. And `self` must be `node`'s whole ancestry: a + /// chain re-rooted part-way (`below`) runs off its top early, and + /// "no level answers" would be stored on levels whose real ancestors + /// do answer. Nothing checks that last one, since the audit's climb + /// reads the same chain; no caller asks from a re-rooted chain. + /// `make chain-audit` checks every memoised answer against the + /// climb. #[doc(hidden)] #[must_use] pub fn nearest_level_answer( @@ -710,7 +732,12 @@ impl<'tree, 'chain> Ancestors<'tree, 'chain> { /// reads and stores through the same one. Rebuilding with /// [`Ancestors::known`] instead dropped it silently — the shape /// lesson 101 is about — and left Doxygen's conditionals inside an - /// `ERROR` child unmemoised (#1686 review). + /// `ERROR` child unmemoised (#1686 review). Sharing it is sound for + /// a fold lane, whose slots are keyed by depth and id, and for a + /// memo of a node's own subtree. It is not for + /// [`nearest_level_answer`](Self::nearest_level_answer), whose memo + /// holds an answer about the ancestry this chain cuts short: do not + /// ask one from a re-rooted chain. /// /// The sibling cache is keyed by depth and holds only the nodes the /// walk has pushed; the node this chain descends into is one the walk @@ -1164,7 +1191,9 @@ const _: () = assert!(FoldLane::InsideFunction as usize + 1 == FoldLane::COUNT); /// Which memoised per-node question a [`FoldCache`] [`NodeMemo`] holds. /// Two questions asked of the same node must not share a slot, so each -/// has a memo of its own. +/// has a memo of its own. A [`NodeQuestion`] or one of this crate's own +/// stores the node's answer; a [`LevelQuestion`] the nearest answer at +/// or above it. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(crate) enum MemoQuestion { /// Doxygen: whether a preprocessor conditional holds an entry, in @@ -1340,14 +1369,17 @@ impl WordSlot { const _: () = assert!(WordSlot::TclCommandWord as usize + 1 == WordSlot::COUNT); -/// Answers about a node's own subtree, memoised for one walk and keyed -/// by node id, which is unique within a tree: Doxygen's "does this -/// preprocessor conditional hold an entry", asked of every conditional -/// a doc comment's stretch meets; the Tcl family's "can this argument -/// list be read by position", asked by every braced word in it. Unlike -/// a [`FoldLane`] it is not tied to the chain, so an answer stored for -/// one sibling subtree serves every later question about it (#1613). -/// Each holds one [`MemoQuestion`]. +/// Answers that are a fact of one node, memoised for one walk and keyed +/// by node id, which is unique within a tree. Most are about the node's +/// own subtree: Doxygen's "does this preprocessor conditional hold an +/// entry", asked of every conditional a doc comment's stretch meets; +/// the Tcl family's "can this argument list be read by position", asked +/// by every braced word in it. A [`LevelQuestion`]'s is about the +/// node's ancestry instead: the nearest answer at or above it, which +/// [`Ancestors::nearest_level_answer`] stores only from a whole chain. +/// Unlike a [`FoldLane`] slot the entry is not keyed by depth, so an +/// answer stored for one sibling subtree serves every later question +/// about it (#1613). Each holds one [`MemoQuestion`]. #[derive(Debug, Default)] pub(crate) struct NodeMemo(RefCell>); diff --git a/big-code-analysis-ast/src/roles/derived_parity_tests.rs b/big-code-analysis-ast/src/roles/derived_parity_tests.rs index 9ff222228..c48301c23 100644 --- a/big-code-analysis-ast/src/roles/derived_parity_tests.rs +++ b/big-code-analysis-ast/src/roles/derived_parity_tests.rs @@ -74,8 +74,8 @@ use std::fmt::Write as _; use crate::roles::{DeclaredRow, LanguageTable, RowView}; use crate::test_support::{ - control_flow_corpus_present, control_flow_sources, for_each_node_with_chain, - for_each_node_with_sibling_cache, for_each_node_with_sibling_cache_tolerating_errors, + control_flow_corpus_present, control_flow_sources, for_each_node_with_sibling_cache, + for_each_node_with_sibling_cache_tolerating_errors, }; use crate::{Ancestors, Checker, LANG, Node, with_code_tag}; @@ -118,7 +118,11 @@ struct Source { /// spells the connectives and the comparisons, told apart by text. /// /// Keyed by the table's name, as the exception tables below are: a -/// language is asked its fixture only when its table is enabled. +/// language is asked its fixture only when its table is enabled. Not +/// by `LANG`, as the documentation fixtures are: a `LANG` literal here +/// makes `utils/check-test-lang-gates.py` derive a gate on these three +/// languages for every test that loads a source, all of which run +/// under any one language. const BYTE_GATE_FIXTURES: &[(&str, &str, &[u8])] = &[ ( "Java", @@ -183,16 +187,47 @@ fn sources_for(lang: LANG) -> Vec { out } -/// A fixture keyed by a name no table carries is asked of nothing, and -/// the byte backstop loses the one candidate that moves its gate -/// without a failure anywhere. +/// Each fixture names a table and still moves a gate that table marks +/// `text_gated_by`: some node of a marked owner kind answers `owns` +/// differently under the fixture's bytes and under none. That is the +/// fixture's whole use — it is the candidate that would move the gate +/// were it re-declared `gated_by` — and nothing else would notice it +/// gone. The backstop skips a marked owner, so a fixture keyed by a +/// name no table carries, or one a grammar bump or a gate edit left +/// answering alike both ways, leaves the backstop passing with that +/// gate unguarded. #[test] -fn byte_gate_fixtures_each_name_a_table() { +fn byte_gate_fixtures_each_move_a_marked_gate() { let tables = crate::roles::tables(); - for (table, fixture, _) in BYTE_GATE_FIXTURES { + for (name, fixture, code) in BYTE_GATE_FIXTURES { + let table = tables + .iter() + .find(|t| t.name == *name) + .unwrap_or_else(|| panic!("`{fixture}` names `{name}`, which is no table")); + if !table.lang.is_enabled() { + continue; + } + let rows: Vec = (table.rows)() + .iter() + .filter_map(RowView::declared) + .copied() + .collect(); + let mut moved = false; + with_code_tag!(table.lang, |C| { + for_each_node_with_sibling_cache::(code, |node, ancestors| { + let ancestors = ancestors.without_folds(); + let kind = node.kind_id(); + moved |= rows.iter().any(|row| { + row.text_gated_owners.contains(&kind) + && (row.owns_kind)(kind, node, code, ancestors) + != (row.owns_kind)(kind, node, &[], ancestors) + }); + }); + }); assert!( - tables.iter().any(|t| t.name == *table), - "`{fixture}` names `{table}`, which is no table" + moved, + "`{fixture}` moves no `text_gated_by` owner of {name}: the gate it was written \ + for answers alike with and without its bytes" ); } } @@ -1004,8 +1039,8 @@ fn forwards_on<'a, C: Checker + crate::Getter>( // body-child test on `below` that no row spells, so the forward is compared // against the composition *without* the child test on the one // side it can be — a node the forward admits for some child is one - // the composition admits. The row half is what the `&[]` forward - // in `doc_body_residual_kind!` drops; the chain is the real one. + // the composition admits. Every term reads the real bytes and the + // real chain, as the adapters do since #1863. let holds_for_any_child = node .children() .any(|below| C::holds_doc_comment_in_body(node, code, ancestors, &below)); @@ -1536,14 +1571,15 @@ impl ByteProbe { rows: &[DeclaredRow], node: &Node<'a>, code: &[u8], - chain: &[Node<'a>], + ancestors: Ancestors<'a, '_>, ) { // One chain for both asks, and no `FoldCache` on it: a memo is // keyed by node, never by buffer, so through the walk's cache // the byte-less ask would be served what the real bytes stored // a moment before, and a memoised byte reader would agree with - // itself. - let ancestors = Ancestors::known(chain); + // itself. The `SiblingCache` stays: a gate that reads a sibling + // under a wide parent needs it, as on the walk. + let ancestors = ancestors.without_folds(); let kind = node.kind_id(); let mut unmarked_owner = false; for row in rows { @@ -1626,9 +1662,9 @@ fn unmarked_owners_answer_alike_without_the_bytes() { for source in sources_for(table.lang) { let code = source.bytes.as_slice(); with_code_tag!(table.lang, |C| { - for_each_node_with_chain::(code, |node, chain| { + for_each_node_with_sibling_cache::(code, |node, ancestors| { if node.start_byte() != node.end_byte() { - probe.probe(table, &rows, node, code, chain); + probe.probe(table, &rows, node, code, ancestors); } }); }); diff --git a/big-code-analysis-ast/src/roles/java.rs b/big-code-analysis-ast/src/roles/java.rs index 9c1684863..d9ffa95a0 100644 --- a/big-code-analysis-ast/src/roles/java.rs +++ b/big-code-analysis-ast/src/roles/java.rs @@ -217,8 +217,8 @@ pub fn is_record_header(list: &Node<'_>, record: &Node<'_>) -> bool { // Times `opens_record_header` spelled a header's component types. Once // per evaluation that meets a constructor, however many it compares: -// re-spelled per constructor the gate answers the same, a third slower -// on a record of alternatives (#1863). +// re-spelled per constructor the gate answers the same and costs about +// half as much again on a record of alternatives (#1863). crate::observation::counter!(record_header_types_read); /// The container a `switch` nests its arms in: the `switch_block`, the diff --git a/big-code-analysis-ast/src/roles/space_tree_tests.rs b/big-code-analysis-ast/src/roles/space_tree_tests.rs index c673eb392..7c0f32443 100644 --- a/big-code-analysis-ast/src/roles/space_tree_tests.rs +++ b/big-code-analysis-ast/src/roles/space_tree_tests.rs @@ -1302,16 +1302,22 @@ fn plain(text: &str, name: &'static str) -> ListAnswer { /// What a language's `record_header` projection and its `FuncOpener` /// row say of every list of `source`: the declarations the projection -/// answers for, by kind, and per list its text, whether it is its -/// parent's projected header, and whether the row owns it there. +/// answers for, by kind, and per list its text, whether +/// `is_record_header` reads it as its parent's header, and whether the +/// row owns it there. #[cfg(any(feature = "java", feature = "groovy"))] type HeaderAnswers = (Vec, Vec<(String, bool, bool)>); +/// A language's `is_record_header`, by value. +#[cfg(any(feature = "java", feature = "groovy"))] +type IsRecordHeader = for<'a, 'b> fn(&Node<'a>, &Node<'b>) -> bool; + #[cfg(any(feature = "java", feature = "groovy"))] fn header_answers( source: &'static [u8], list_kinds: &[&str], record_header: for<'a> fn(&Node<'a>) -> Option>, + is_record_header: IsRecordHeader, opener_owns: crate::roles::RowPred, ) -> HeaderAnswers { let mut projecting = Vec::new(); @@ -1330,8 +1336,7 @@ fn header_answers( let ancestors = Ancestors::known(chain); let is_header = ancestors .parent(node) - .and_then(|owner| record_header(&owner)) - .is_some_and(|header| header.id() == node.id()); + .is_some_and(|owner| is_record_header(node, &owner)); let owned = opener_owns(node, source, ancestors); assert!( is_header || !owned, @@ -1357,13 +1362,14 @@ fn header_answers( #[cfg(feature = "java")] #[test] fn java_record_header_is_the_records_own_list() { - use crate::roles::java::{func_opener, record_header}; + use crate::roles::java::{func_opener, is_record_header, record_header}; let source = b"record R(int x) { R { } void m(int y) { } }\nrecord Q(int q) { }\nclass C { C(int z) { } }\n"; let (projecting, lists) = header_answers::( source, &["formal_parameters"], record_header, + is_record_header, func_opener::owns, ); assert_eq!(projecting, ["record_declaration", "record_declaration"]); @@ -1386,12 +1392,13 @@ fn java_record_header_is_the_records_own_list() { #[cfg(feature = "groovy")] #[test] fn groovy_record_header_is_the_records_own_list() { - use crate::roles::groovy::{func_opener, record_header}; + use crate::roles::groovy::{func_opener, is_record_header, record_header}; let source = b"record R(int x) { void m(int y) { } }\nrecord B(int b) { B(int b) { this.b = b } }\nclass C { C(int z) { } }\n"; let (projecting, lists) = header_answers::( source, &["record_components", "formal_parameters"], record_header, + is_record_header, func_opener::owns, ); assert_eq!(projecting, ["record_declaration", "record_declaration"]); @@ -1413,7 +1420,7 @@ fn groovy_record_header_is_the_records_own_list() { #[cfg(any(feature = "java", feature = "groovy"))] fn header_type_reads( source: &'static [u8], - record_header: for<'a> fn(&Node<'a>) -> Option>, + is_record_header: IsRecordHeader, opener_owns: crate::roles::RowPred, observed: fn() -> usize, ) -> Vec<(bool, usize)> { @@ -1422,8 +1429,7 @@ fn header_type_reads( let ancestors = Ancestors::known(chain); let is_header = ancestors .parent(node) - .and_then(|owner| record_header(&owner)) - .is_some_and(|header| header.id() == node.id()); + .is_some_and(|owner| is_record_header(node, &owner)); if is_header { let before = observed(); let owned = opener_owns(node, source, ancestors); @@ -1442,12 +1448,12 @@ fn header_type_reads( #[cfg(feature = "java")] #[test] fn java_header_types_are_read_once_per_gate_evaluation() { - use crate::roles::java::{func_opener, record_header, record_header_types_read}; + use crate::roles::java::{func_opener, is_record_header, record_header_types_read}; let source = b"record R(int a, int b) { R(int a, long b) { this(a, 0); } R(int a, short b) { this(a, 0); } R(int a, byte b) { this(a, 0); } }\nrecord Q(int q) { int m() { return q; } }\n"; assert_eq!( header_type_reads::( source, - record_header, + is_record_header, func_opener::owns, record_header_types_read::observed, ), @@ -1461,12 +1467,12 @@ fn java_header_types_are_read_once_per_gate_evaluation() { #[cfg(feature = "groovy")] #[test] fn groovy_header_types_are_read_once_per_gate_evaluation() { - use crate::roles::groovy::{func_opener, record_header, record_header_types_read}; + use crate::roles::groovy::{func_opener, is_record_header, record_header_types_read}; let source = b"record R(int a, int b) { R(int a, long b) { this(a, 0) } R(int a, short b) { this(a, 0) } R(int a, byte b) { this(a, 0) } }\nrecord Q(int q) { int m() { return q } }\n"; assert_eq!( header_type_reads::( source, - record_header, + is_record_header, func_opener::owns, record_header_types_read::observed, ), diff --git a/docs/development/grammar_dispatch.md b/docs/development/grammar_dispatch.md index ad6bef116..a4b71aa1e 100644 --- a/docs/development/grammar_dispatch.md +++ b/docs/development/grammar_dispatch.md @@ -119,8 +119,9 @@ both reads `pays_at_wrapper` and `pays_at_leaf` explicitly. Deleting a kind from the `FuncOpener` row to stop an over-count regresses its childless variant to zero. Gate the owner on child presence, which keeps `is_func_with_code`, `is_func_space_with_code` -and `get_space_kind_with_code` on the same predicate. When a wrapper/leaf pair double-counts, the keeper is the -node present for every spelling, verified with `bca dump` on valid and +and `get_space_kind_with_code` on the same predicate. When a +wrapper/leaf pair double-counts, the keeper is the node present for +every spelling, verified with `bca dump` on valid and on recovery input: `node-types.json` describes the well-formed grammar only, and an `ERROR` root routinely holds the leaf with no wrapper. Where neither choice strands a node, keep the node whose span is the diff --git a/docs/development/lessons_learned.md b/docs/development/lessons_learned.md index 8148683d7..d5c569785 100644 --- a/docs/development/lessons_learned.md +++ b/docs/development/lessons_learned.md @@ -2675,9 +2675,11 @@ if the `do` section has one, otherwise `after`. set to fix an over-count, enumerate the construct's variants and find the one with **no qualifying children** — it is relying on the membership you are about to delete. Gate the arm on child-presence -rather than removing it, and keep `is_func`, `is_func_space`, and -`get_space_kind` gated by the *same* predicate so the space tree stays -self-consistent. The same holds for any classification arm, not only the +rather than removing it, and keep the callable test, the space test and +the space kind (`is_func_with_code`, `is_func_space_with_code` and +`get_space_kind_with_code` since #1863; `is_func`, `is_func_space` and +`get_space_kind` when this was written) gated by the *same* predicate +so the space tree stays self-consistent. The same holds for any classification arm, not only the space dispatch: a kind that fills several grammatical roles must be fixtured in each role before an arm naming it is deleted — the reported fixtures show one role. @@ -5357,7 +5359,7 @@ assertion reads the value the collapse moves, not just the shape. **A same-arity alternative constructor closed a record's header** (#1842, PR #1862). `opens_record_header` reads the body's constructor parameter types to tell the canonical constructor from an alternative, -and was declared `gated_by`. `JavaCode::is_func` forwards the row with +and was declared `gated_by`. `JavaCode::is_func` forwarded the row with `&[]`; `is_func_with_code` defaulted to it. Under no bytes `A(long a)` and component `int a` both spelled `""`, the constructor read as canonical, the header closed, and `record A(int a) { A(long a) {…} }` diff --git a/src/metrics/npm.rs b/src/metrics/npm.rs index dd14cbcc9..1e568c2b3 100644 --- a/src/metrics/npm.rs +++ b/src/metrics/npm.rs @@ -264,23 +264,22 @@ fn direct_child_funcs<'a, 'c, C: Checker>( .filter(move |child| C::is_func_with_code(child, code, members)) } -/// Whether a record declaration's header — the component list -/// `record_header` projects, a sibling of the body and so never a body -/// member — is the record's implicit canonical constructor, a method -/// the body scan cannot see (#1842; Java and Groovy). `record_header` -/// is the language's projection beside its role table -/// (`roles::java::record_header`, `roles::groovy::record_header`). The -/// question is the `FuncOpener` row's, asked of the list under the -/// record's own child chain so the row's gate reads the body, and the -/// answer is read here while the walk is still on the class space: the -/// list's own function space opens one node later. +/// Whether a record declaration's `header` — the component list the +/// language's `record_header` projects (`roles::java`, `roles::groovy`), +/// a sibling of the body and so never a body member — is the record's +/// implicit canonical constructor, a method the body scan cannot see +/// (#1842; Java and Groovy). The question is the `FuncOpener` row's, +/// asked of the list under the record's own child chain so the row's +/// gate reads the body, and the answer is read here while the walk is +/// still on the class space: the list's own function space opens one +/// node later. fn record_header_is_a_method<'a, C: Checker>( record: &Node<'a>, - record_header: impl FnOnce(&Node<'a>) -> Option>, + header: Option>, code: &[u8], ancestors: Ancestors<'a, '_>, ) -> bool { - record_header(record).is_some_and(|header| { + header.is_some_and(|header| { C::is_func_with_code(&header, code, ancestors.of_children(record).get()) }) } @@ -392,7 +391,7 @@ macro_rules! impl_npm_java_like { RecordDeclaration => { if record_header_is_a_method::( node, - crate::roles::$roles::record_header, + crate::roles::$roles::record_header(node), code, ancestors, ) { @@ -1895,6 +1894,43 @@ mod tests { ); } + /// `public` is read off `modifiers` as the declaration's first child + /// (#1863), which holds for whatever is written ahead of the + /// keyword: a doc comment before the declaration is its sibling, + /// annotations and a comment among them sit inside `modifiers`, a + /// comment after `public` follows it, and type parameters come + /// after. Were any of these the declaration's first child, the + /// record or its method would read as package-private. + #[cfg(feature = "java")] + #[test] + fn java_public_is_read_past_what_precedes_it() { + check_func_space::( + "/** d */ + @Deprecated + // among the modifiers + public /* after */ record P(int a) { + /** m */ + @Override + public String toString() { return \"\"; } + /* lead */ public static void s() { } + @Deprecated void p() { } + }", + "trivia.java", + |space| { + let record = child_space(&space, "P"); + // expected: the header, `toString`, `s` and `p`; all but + // `p` public. + assert_eq!( + ( + record.metrics.npm.class_nm(), + record.metrics.npm.class_npm() + ), + (4, 3) + ); + }, + ); + } + /// A record that is a member of an interface is implicitly public /// (JLS 9.5), so its implicit canonical constructor is too — `javap` /// prints `public I$R(int)` — and `R` reads as `P`, which spells the diff --git a/src/metrics/npm/groovy.rs b/src/metrics/npm/groovy.rs index ca6f3ce99..6b893ddfa 100644 --- a/src/metrics/npm/groovy.rs +++ b/src/metrics/npm/groovy.rs @@ -37,7 +37,7 @@ impl Npm for GroovyCode { RecordDeclaration if record_header_is_a_method::( node, - crate::roles::groovy::record_header, + crate::roles::groovy::record_header(node), code, ancestors, ) => From 6dd823a9547343cfef9c3ff2069f180416e6dcc7 Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Wed, 11 Nov 2026 20:29:21 -0800 Subject: [PATCH 19/21] test(roles): name the gates each byte-gate fixture must move `byte_gate_fixtures_each_move_a_marked_gate` asked for *some* marked owner to move. Rewriting the Groovy fixture's alternative constructor into a canonical one, which stops the header gate moving, still passed: another text gate of the Groovy table moves on the same source. Each fixture now lists the `(role, owner kind)` gates it was written for, and the test, `byte_gate_fixtures_each_move_their_gates`, requires each. Found by reverting the fixture the first form of the test was meant to guard. Refs #1863 --- .../src/roles/derived_parity_tests.rs | 118 +++++++++++------- 1 file changed, 74 insertions(+), 44 deletions(-) diff --git a/big-code-analysis-ast/src/roles/derived_parity_tests.rs b/big-code-analysis-ast/src/roles/derived_parity_tests.rs index c48301c23..23327e8c2 100644 --- a/big-code-analysis-ast/src/roles/derived_parity_tests.rs +++ b/big-code-analysis-ast/src/roles/derived_parity_tests.rs @@ -123,24 +123,41 @@ struct Source { /// makes `utils/check-test-lang-gates.py` derive a gate on these three /// languages for every test that loads a source, all of which run /// under any one language. -const BYTE_GATE_FIXTURES: &[(&str, &str, &[u8])] = &[ - ( - "Java", - "gate/java-records", - b"record A(int a) { A(long a) { this((int) a); } }\nrecord B(int b) { B(int b) { this.b = b; } }\n", - ), - ( - "Groovy", - "gate/groovy-records", - b"record A(int a) { A(long a) { this(1) } }\nrecord B(int b) { B(int b) { this.b = b } }\n", - ), - ( - "Bash", - "gate/bash-tests", - b"if [ \"$a\" -eq 1 -a \"$b\" -eq 2 ]; then :; fi\n[ -n \"$a\" -o -n \"$b\" ]\n", - ), +const BYTE_GATE_FIXTURES: &[ByteGateFixture] = &[ + ByteGateFixture { + table: "Java", + name: "gate/java-records", + source: b"record A(int a) { A(long a) { this((int) a); } }\nrecord B(int b) { B(int b) { this.b = b; } }\n", + moves: &[("FuncOpener", "formal_parameters")], + }, + ByteGateFixture { + table: "Groovy", + name: "gate/groovy-records", + source: b"record A(int a) { A(long a) { this(1) } }\nrecord B(int b) { B(int b) { this.b = b } }\n", + moves: &[("FuncOpener", "record_components")], + }, + ByteGateFixture { + table: "Bash", + name: "gate/bash-tests", + source: b"if [ \"$a\" -eq 1 -a \"$b\" -eq 2 ]; then :; fi\n[ -n \"$a\" -o -n \"$b\" ]\n", + moves: &[ + ("Comparison", "binary_expression"), + ("ShortCircuit", "binary_expression"), + ], + }, ]; +/// One [`BYTE_GATE_FIXTURES`] row. +struct ByteGateFixture { + /// The `LanguageTable::name` the source is asked under. + table: &'static str, + name: &'static str, + source: &'static [u8], + /// The `(role, owner kind)` gates this source was written to move: + /// each answers differently with its bytes and with none. + moves: &'static [(&'static str, &'static str)], +} + /// Every source `lang` is asked on: its control-flow files (routed by /// `test_support::control_flow_sources`), its documentation fixtures, /// read in place, and its [`BYTE_GATE_FIXTURES`]. Without the output @@ -178,32 +195,40 @@ fn sources_for(lang: LANG) -> Vec { out.extend( BYTE_GATE_FIXTURES .iter() - .filter(|(name, _, _)| Some(*name) == table) - .map(|(_, fixture, bytes)| Source { - name: (*fixture).to_owned(), - bytes: bytes.to_vec(), + .filter(|fixture| Some(fixture.table) == table) + .map(|fixture| Source { + name: fixture.name.to_owned(), + bytes: fixture.source.to_vec(), }), ); out } -/// Each fixture names a table and still moves a gate that table marks -/// `text_gated_by`: some node of a marked owner kind answers `owns` -/// differently under the fixture's bytes and under none. That is the -/// fixture's whole use — it is the candidate that would move the gate -/// were it re-declared `gated_by` — and nothing else would notice it -/// gone. The backstop skips a marked owner, so a fixture keyed by a -/// name no table carries, or one a grammar bump or a gate edit left -/// answering alike both ways, leaves the backstop passing with that -/// gate unguarded. +/// Each fixture names a table and still moves every gate it was written +/// for: some node of the owner kind answers that row's `owns` +/// differently under the fixture's bytes and under none, and the row +/// marks the kind `text_gated_by`. That is the fixture's whole use — it +/// is the candidate that would move the gate were it re-declared +/// `gated_by` — and nothing else would notice it gone. The backstop +/// skips a marked owner, so a fixture keyed by a name no table carries, +/// or one a grammar bump or a gate edit left answering alike both ways, +/// leaves the backstop passing with that gate unguarded. Named gates, +/// not "some marked owner": another text gate of the table moving on +/// the same source would hide the one the fixture is for. #[test] -fn byte_gate_fixtures_each_move_a_marked_gate() { +fn byte_gate_fixtures_each_move_their_gates() { let tables = crate::roles::tables(); - for (name, fixture, code) in BYTE_GATE_FIXTURES { + for fixture in BYTE_GATE_FIXTURES { + let ByteGateFixture { + table: name, + name: label, + source, + moves, + } = *fixture; let table = tables .iter() - .find(|t| t.name == *name) - .unwrap_or_else(|| panic!("`{fixture}` names `{name}`, which is no table")); + .find(|t| t.name == name) + .unwrap_or_else(|| panic!("`{label}` names `{name}`, which is no table")); if !table.lang.is_enabled() { continue; } @@ -212,23 +237,28 @@ fn byte_gate_fixtures_each_move_a_marked_gate() { .filter_map(RowView::declared) .copied() .collect(); - let mut moved = false; + let mut moved = BTreeSet::new(); with_code_tag!(table.lang, |C| { - for_each_node_with_sibling_cache::(code, |node, ancestors| { + for_each_node_with_sibling_cache::(source, |node, ancestors| { let ancestors = ancestors.without_folds(); let kind = node.kind_id(); - moved |= rows.iter().any(|row| { - row.text_gated_owners.contains(&kind) - && (row.owns_kind)(kind, node, code, ancestors) + for row in &rows { + if row.text_gated_owners.contains(&kind) + && (row.owns_kind)(kind, node, source, ancestors) != (row.owns_kind)(kind, node, &[], ancestors) - }); + { + moved.insert((row.role, node.kind())); + } + } }); }); - assert!( - moved, - "`{fixture}` moves no `text_gated_by` owner of {name}: the gate it was written \ - for answers alike with and without its bytes" - ); + for gate in moves { + assert!( + moved.contains(gate), + "`{label}` no longer moves {name}'s {gate:?}: that gate answers alike with \ + and without the fixture's bytes; moved: {moved:?}" + ); + } } } From 8f7bbe660024ac835a86cb546ad009b411d6fd90 Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Wed, 11 Nov 2026 21:57:58 -0800 Subject: [PATCH 20/21] docs(book): translate the new-language page's Getter bullet into Japanese 19b637fc changed the bullet to name `get_space_kind_with_code` and its byte-less `get_space_kind`. The `ja.po` entry for it was already fuzzy against an older English sentence (`getter.rs` as one file), so the item rendered in English on the `/ja/` page. The entry now carries the current `msgid`, taken from a freshly generated `messages.pot`, and a new translation, with the fuzzy flag dropped. Only this entry changes: `msgcat` is a no-op on the rest of the catalog, and a full `make book-po-update` would have rewritten 4,727 lines of unrelated stale entries. Fuzzy entries: 991 -> 990. Checked with mdbook 0.5.2 and mdbook-i18n-helpers 0.4.0 built with `syntect/regex-onig`: `msgfmt --check` passes, a scratch `msgmerge` against the new pot leaves the entry non-fuzzy, and `make book && make book-ja` renders the Japanese sentence on `ja/developers/new-language.html` with the link target intact. Refs #1863 --- big-code-analysis-book/po/ja.po | 23 +++++++++++++---------- 1 file changed, 13 insertions(+), 10 deletions(-) diff --git a/big-code-analysis-book/po/ja.po b/big-code-analysis-book/po/ja.po index fc4bb32e3..116c6ccc2 100644 --- a/big-code-analysis-book/po/ja.po +++ b/big-code-analysis-book/po/ja.po @@ -31896,16 +31896,19 @@ msgstr "" "checker.rs) の **`Checker`** — 文法の `kind_id` に対する、コメント、関数、ク" "ロージャ、呼び出し、文字列リテラル、`else-if` の各述語。" -#: src/developers/new-language.md:117 -#, fuzzy -msgid "" -"**`Getter`** in [/big-code-analysis-ast/src/getter.rs](https://github.com/" -"dekobon/big-code-analysis/blob/main/big-code-analysis-ast/src/getter.rs): " -"`get_space_kind` plus the Halstead operator/operand classification table." -msgstr "" -"[/src/getter.rs](https://github.com/dekobon/big-code-analysis/blob/main/src/" -"getter.rs) の **`Getter`** — `get_space_kind` に加え、Halstead の演算子/オペ" -"ランド分類テーブル。" +#: src/developers/new-language.md:119 +msgid "" +"**`Getter`** in a new per-language file under [/big-code-analysis-ast/src/" +"getter/](https://github.com/dekobon/big-code-analysis/tree/main/big-code-" +"analysis-ast/src/getter) (`getter/.rs`, registered in `getter.rs`): " +"`get_space_kind_with_code`, its byte-less `get_space_kind`, and the Halstead " +"operator/operand classification table." +msgstr "" +"[/big-code-analysis-ast/src/getter/](https://github.com/dekobon/big-code-" +"analysis/tree/main/big-code-analysis-ast/src/getter) 配下に言語ごとに新しく作" +"るファイル(`getter/.rs`、`getter.rs` に登録)の **`Getter`** — " +"`get_space_kind_with_code`、そのソースバイト列を受け取らない版である " +"`get_space_kind`、および Halstead の演算子 / オペランド分類テーブル。" #: src/developers/new-language.md:121 #, fuzzy From 68b70b083763e3f22e79d9905d6f79d65d64f098 Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Wed, 11 Nov 2026 22:21:50 -0800 Subject: [PATCH 21/21] test(node,loc,roles): cover the five patch lines that have a reason to be covered Codecov on #1877 reports patch coverage 92.79% (489 of 527 lines), with 38 lines missed. Five of them are fixed here: - `marked_kind` (`roles/mod.rs`, 3 lines) is a `const fn` that only runs at compile time, in `TEXT_GATED_OWNERS`, so instrumentation sees none of it. Its siblings `count_some` and `some_kinds` have a run-time test for that reason; `marked_kind` gets one beside it. - The two exact-count tests guarded their assertion with `if cfg!(not(chain_audit))`, whose implicit else is a region no build of the coverage job enters (`node.rs`, `loc.rs`, 1 line each). The guard also meant the chain-audit leg asserted no count at all. Both now assert exactly in either configuration, without a branch: under `--cfg chain_audit` the audit's unmemoised climb runs beside every ask, so each count is the memoised one plus the climb's. The other 33 lines are left: 23 in `cyclomatic.rs` and 10 in `getter.rs` are the bodies of the methods `Checker` and `Getter` now require, on three test doubles (`Probe` and `Empty`, `Conflict`) whose tests never call them. They can only be covered by a test of the doubles themselves, which exercises no production code. Measured at this commit with the coverage job's commands and `utils/patch-coverage.py coverage-llvm.json a62077d5`, an LLVM line approximation of Codecov's figure: patch 508 of 541 lines, 93.90%, the 33 missed lines being exactly those stubs. Also corrects the probe's doc in `cyclomatic.rs`, which still said it carries "the default `Checker`". Refs #1863 --- big-code-analysis-ast/src/node.rs | 19 +++++++++++++------ big-code-analysis-ast/src/roles/mod.rs | 11 +++++++++++ src/metrics/cyclomatic.rs | 4 ++-- src/metrics/loc.rs | 18 ++++++++++++------ 4 files changed, 38 insertions(+), 14 deletions(-) diff --git a/big-code-analysis-ast/src/node.rs b/big-code-analysis-ast/src/node.rs index ae51a9f7b..dadac1604 100644 --- a/big-code-analysis-ast/src/node.rs +++ b/big-code-analysis-ast/src/node.rs @@ -2439,12 +2439,19 @@ mod tests { // block; `5` the const and the file; `6` the array type, the // parameter, the parameter list and the closure; `7` meets the // memo on the closure; `8` the statement, the block and `i`. - // The unmemoised climb asks 5 for `2`, 3 for `4` and 1 for `7`. - // `make chain-audit` runs that climb beside every ask, so the - // count is asserted without it. - if cfg!(not(chain_audit)) { - assert_eq!(asked, [5, 0, 4, 1, 2, 4, 0, 3]); - } + // The unmemoised climb asks every level up to the one that + // answers: 5 for `2`, 3 for `4` and 1 for `7`, the rest as + // memoised. `make chain-audit` runs that climb beside every ask, + // so there each count is the two together. + let memoised = [5, 0, 4, 1, 2, 4, 0, 3]; + let climbed = [5, 5, 4, 3, 2, 4, 1, 3]; + let audited = usize::from(cfg!(chain_audit)); + let expected: Vec = memoised + .iter() + .zip(climbed) + .map(|(memo, climb)| memo + audited * climb) + .collect(); + assert_eq!(asked, expected); assert!(yes > 0 && no > 0, "both answers must occur ({yes} / {no})"); } } diff --git a/big-code-analysis-ast/src/roles/mod.rs b/big-code-analysis-ast/src/roles/mod.rs index 4b661ba8a..f0d71cc4f 100644 --- a/big-code-analysis-ast/src/roles/mod.rs +++ b/big-code-analysis-ast/src/roles/mod.rs @@ -2528,6 +2528,17 @@ mod tests { assert_eq!(some_kinds::<0>(EMPTY), [0u16; 0]); } + /// `marked_kind` runs at compile time as well, once per owner of + /// every `TEXT_GATED_OWNERS`: it keeps the kind of an owner the + /// detector marks and nothing of one it does not, which is the + /// `Option` list `some_kinds` compacts. + #[test] + fn marked_kind_keeps_the_kind_of_a_marked_owner_only() { + use super::marked_kind; + assert_eq!(marked_kind(true, 7), Some(7)); + assert_eq!(marked_kind(false, 7), None); + } + /// An absent row's `lists_kind` is false for every kind, as its /// `OWNERS` is empty; the one a declared row emits reads the table. /// The rows are declarations, built in every feature set. diff --git a/src/metrics/cyclomatic.rs b/src/metrics/cyclomatic.rs index 3c6c2a8c0..0640d0e7d 100644 --- a/src/metrics/cyclomatic.rs +++ b/src/metrics/cyclomatic.rs @@ -453,8 +453,8 @@ mod tests { /// The two `impl_cyclomatic_rows!` shapes no pilot language spells /// (#1697): a non-empty `constraints` list, and every list empty. - /// `Probe` carries the default `Checker` so the macro's `impl` has - /// a type to hang on; its body is driven on C++ nodes with the walk's + /// `Probe` carries an inert `Checker` so the macro's `impl` has a + /// type to hang on; its body is driven on C++ nodes with the walk's /// own chain. A `requires` clause opens a reach under which a later /// `&&` scores nothing, and the first node past the reach scores /// again — the C++ invocation (`cyclomatic/cpp.rs`) relies on exactly this, and diff --git a/src/metrics/loc.rs b/src/metrics/loc.rs index baca637a3..79a552c3f 100644 --- a/src/metrics/loc.rs +++ b/src/metrics/loc.rs @@ -10442,12 +10442,18 @@ EOF // parentheses, their statements and the block: a run reads its // parenthesis and its statement, which answers, and the first // statement has none before it and reads the block. The climb - // reads 900 and 81, the fold 120 and 122. `make chain-audit` - // runs the climb beside every ask, so the count is asserted - // without it. - if cfg!(not(chain_audit)) { - assert_eq!((nested_read, block_read), (n + 2, 2 * n + 1)); - } + // reads `j + 3` levels from the parenthesis `j` deep on + // `nested`, 900 in all, and the same 81 on `block`; the fold + // read 120 and 122. `make chain-audit` runs the climb beside + // every ask, so there each count is the two together. + let audited = usize::from(cfg!(chain_audit)); + assert_eq!( + (nested_read, block_read), + ( + n + 2 + audited * (n * (n + 5) / 2), + (1 + audited) * (2 * n + 1) + ) + ); } /// #1818: the C-family bare-row index is built exactly once per