diff --git a/.bca-baseline.toml b/.bca-baseline.toml index f29c2af4b..5f732e855 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" @@ -311,25 +299,25 @@ value = 43.0 path = "big-code-analysis-ast/src/node/ancestors.rs" qualified = "" metric = "loc.ploc" -value = 646.0 +value = 704.0 [[entry]] path = "big-code-analysis-ast/src/node/ancestors.rs" qualified = "" metric = "loc.sloc" -value = 1390.0 +value = 1519.0 [[entry]] path = "big-code-analysis-ast/src/node/ancestors.rs" qualified = "Ancestors<'tree, 'chain>" metric = "nom" -value = 41.0 +value = 44.0 [[entry]] path = "big-code-analysis-ast/src/node/ancestors.rs" qualified = "Ancestors<'tree, 'chain>" metric = "wmc" -value = 76.0 +value = 84.0 [[entry]] path = "big-code-analysis-ast/src/node/ancestors.rs" @@ -371,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 = 2268.0 +value = 2325.0 [[entry]] path = "big-code-analysis-ast/src/tools.rs" @@ -1273,6 +1261,12 @@ qualified = "Mi::compute" metric = "nargs" value = 5.0 +[[entry]] +path = "src/metrics/nargs.rs" +qualified = "" +metric = "loc.ploc" +value = 524.0 + [[entry]] path = "src/metrics/npa/php.rs" qualified = "PhpCode::compute" diff --git a/.claude/skills/add-lang/SKILL.md b/.claude/skills/add-lang/SKILL.md index b61a2ca23..e8baeae31 100644 --- a/.claude/skills/add-lang/SKILL.md +++ b/.claude/skills/add-lang/SKILL.md @@ -536,17 +536,21 @@ 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. 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 @@ -594,13 +598,14 @@ 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 - (`grammar-dispatch.md` §7). +- `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; 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 @@ -893,8 +898,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/CHANGELOG.md b/CHANGELOG.md index c17c89043..aca8f03a5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -70,6 +70,39 @@ 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, 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 + 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, 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 + `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 +335,20 @@ 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. 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. - **`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/checker.rs b/big-code-analysis-ast/src/checker.rs index 29450251b..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 overrides both spellings. 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` @@ -351,12 +350,21 @@ 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 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` / @@ -428,15 +436,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 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>( 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 +533,33 @@ 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. + /// Whether `node` opens a space by its kind alone: a function, + /// closure, or one of the containers (class, struct, trait, impl, + /// namespace, interface). /// - /// `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. + /// The byte-less spelling of + /// [`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. /// - /// 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). - #[inline] + /// 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<'a>(_: &Node<'a>, _ancestors: Ancestors<'a, '_>) -> bool { - false - } + fn is_func_space(node: &Node) -> bool; /// 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 { @@ -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. /// @@ -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..391d0aefd 100644 --- a/big-code-analysis-ast/src/checker/ccomment.rs +++ b/big-code-analysis-ast/src/checker/ccomment.rs @@ -7,9 +7,27 @@ 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. + impl_byte_less_func_space!(ccomment); + + 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()]) } + // 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/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..cf8fc98b9 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) { + if doc_body_residual_kind!(csharp, ancestor, code, 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..d6152d905 100644 --- a/big-code-analysis-ast/src/checker/groovy.rs +++ b/big-code-analysis-ast/src/checker/groovy.rs @@ -38,19 +38,20 @@ 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)) + || doc_body_residual_kind!(groovy, ancestor, code, ancestors)) } // Mirrors `impl Checker for JavaCode` exactly: `EnumDeclaration`, @@ -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..e1f942d1c 100644 --- a/big-code-analysis-ast/src/checker/java.rs +++ b/big-code-analysis-ast/src/checker/java.rs @@ -40,21 +40,20 @@ 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)) + || doc_body_residual_kind!(java, ancestor, code, ancestors)) } // The space tree is declared in `roles/java.rs` (#1696): the @@ -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..8eca6db7d 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,9 +79,9 @@ 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)) + || doc_body_residual_kind!(kotlin, ancestor, code, 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..5849e5656 100644 --- a/big-code-analysis-ast/src/checker/preproc.rs +++ b/big-code-analysis-ast/src/checker/preproc.rs @@ -7,5 +7,23 @@ 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. + impl_byte_less_func_space!(preproc); + + 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) + } + + // 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/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..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>, @@ -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..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 { @@ -254,19 +255,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) } @@ -387,32 +388,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), + /// 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 { - SpaceKind::Unknown - } + fn get_space_kind(node: &Node) -> SpaceKind; - /// 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 +2059,18 @@ 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], + _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..df89bdaa7 100644 --- a/big-code-analysis-ast/src/getter/ccomment.rs +++ b/big-code-analysis-ast/src/getter/ccomment.rs @@ -8,4 +8,15 @@ 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. + impl_byte_less_space_kind!(ccomment); + + 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/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..def7db545 100644 --- a/big-code-analysis-ast/src/getter/groovy.rs +++ b/big-code-analysis-ast/src/getter/groovy.rs @@ -58,11 +58,12 @@ 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::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 3b875a755..186eb3754 100644 --- a/big-code-analysis-ast/src/getter/java.rs +++ b/big-code-analysis-ast/src/getter/java.rs @@ -43,11 +43,12 @@ 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::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/getter/preproc.rs b/big-code-analysis-ast/src/getter/preproc.rs index bb17471d2..5b83e80fc 100644 --- a/big-code-analysis-ast/src/getter/preproc.rs +++ b/big-code-analysis-ast/src/getter/preproc.rs @@ -8,4 +8,15 @@ 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. + impl_byte_less_space_kind!(preproc); + + 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/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/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/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/lib.rs b/big-code-analysis-ast/src/lib.rs index 82ab70e2f..24d455f31 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 @@ -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, 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 833d17e17..dadac1604 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, LevelQuestion, NodeQuestion, WIDE_PARENT, child_chains_derived, + fold_slot_probes, fold_steps, sibling_cache_reads, sibling_seeks, }; use tree_sitter::Node as OtherNode; @@ -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 @@ -2354,4 +2354,104 @@ 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 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 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; `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() { + 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); }, 3); let e = 4; }\n\ + const K: u8 = 5;\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; + 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 memoised = Ancestors::known(chain) + .with_folds(&cache) + .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!( + (memoised, chained, climbed), + (expected, expected, expected), + "{kind} at byte {start}: (memoised, chained, climbed) must all be the climb's answer" + ); + if kind == "integer_literal" { + 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; + } else { + no += 1; + } + }); + let (answers, asked): (Vec<_>, Vec<_>) = literals.into_iter().unzip(); + assert_eq!( + answers, + [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` 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 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/node/ancestors.rs b/big-code-analysis-ast/src/node/ancestors.rs index 8f4e1ca58..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 @@ -269,14 +284,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( @@ -326,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. /// @@ -377,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 @@ -419,6 +443,90 @@ 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 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 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 is scanned + /// again for each child asked from. + /// + /// 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( + self, + node: &Node<'tree>, + question: LevelQuestion, + 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) + }; + 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; + } + 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!( + found, + climb(), + "the {question:?} memo disagrees with the climb on a {} node: a \ + question holds one answer fn per walk", + node.kind() + ); + found + } + /// 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]) @@ -624,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 @@ -1078,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 @@ -1121,14 +1236,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 @@ -1156,6 +1273,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 @@ -1229,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/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/bash.rs b/big-code-analysis-ast/src/roles/bash.rs index 3bf3fd10f..b9529c5a2 100644 --- a/big-code-analysis-ast/src/roles/bash.rs +++ b/big-code-analysis-ast/src/roles/bash.rs @@ -93,16 +93,18 @@ 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 - // `(( … ))`, which only the test's descent can tell (#1536); the - // ABC consumer counts it from the test, as its own extra. + // 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 +123,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 - // 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, - 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 1c9c3c778..23327e8c2 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 @@ -102,11 +103,67 @@ 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. 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: &[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`) 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,9 +188,80 @@ fn sources_for(lang: LANG) -> Vec { bytes: f.source.into_owned(), }), ); + let table = crate::roles::tables() + .iter() + .find(|t| t.lang == lang) + .map(|t| t.name); + out.extend( + BYTE_GATE_FIXTURES + .iter() + .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 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_their_gates() { + let tables = crate::roles::tables(); + 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!("`{label}` 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 = BTreeSet::new(); + with_code_tag!(table.lang, |C| { + for_each_node_with_sibling_cache::(source, |node, ancestors| { + let ancestors = ancestors.without_folds(); + let kind = node.kind_id(); + 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())); + } + } + }); + }); + 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:?}" + ); + } + } +} + // --------------------------------------------------------------------------- // The census // --------------------------------------------------------------------------- @@ -462,12 +590,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", @@ -943,20 +1065,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. + // 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, 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, ); @@ -1460,6 +1582,140 @@ 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], + 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. 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 { + 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_sibling_cache::(code, |node, ancestors| { + if node.start_byte() != node.end_byte() { + probe.probe(table, &rows, node, code, ancestors); + } + }); + }); + } + } + 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/doc_tests/mod.rs b/big-code-analysis-ast/src/roles/doc_tests/mod.rs index 1b876aa74..3137030cd 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 )); @@ -1172,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")] @@ -1283,8 +1321,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/groovy.rs b/big-code-analysis-ast/src/roles/groovy.rs index 474fb085c..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; @@ -97,11 +99,13 @@ 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 -/// 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 — +/// 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 — /// 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) @@ -122,7 +126,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,23 +139,44 @@ 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 +/// 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 `groovy_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 `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 `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,22 +187,30 @@ 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 !is_record_header(node, &record) { return false; } let Some(body) = record.child_by_field_name("body") else { return true; }; + 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 - && is_record_canonical_constructor(&member, &record, node, code) + && 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); + /// 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 f17b31f81..d9ffa95a0 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; @@ -105,10 +107,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 +128,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 +141,13 @@ fn is_record_canonical_constructor( if node_bytes(&ctor_name, code) != node_bytes(&record_name, code) { return false; } - let declared = params - .children() - .filter_map(|p| java_parameter_type(&p, code)); - let components = header + let mut declared = params .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 @@ -165,25 +168,59 @@ 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 !is_record_header(node, &record) { return false; } let Some(body) = record.child_by_field_name("body") else { return true; }; + 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 => { - is_record_canonical_constructor(&member, &record, node, code) + is_record_canonical_constructor(&member, &record, &components, code) } _ => false, }) } +/// 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 +/// `java_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() +} + +/// 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 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 /// `Switch` owner's child — a structural fact about the construct the /// row recognises, pinned by @@ -260,7 +297,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 +305,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 +697,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..f0d71cc4f 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,8 +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 -//! (Java's `static { … }` opens a `Function` space and is nobody's +//! 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 //! so, under a gate of its own beside the owner's — a JS @@ -354,7 +355,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 @@ -385,7 +390,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 @@ -400,8 +406,18 @@ //! //! - **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. +//! `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 @@ -410,20 +426,22 @@ //! 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). +//! 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 @@ -442,7 +460,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, +//! 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. //! - **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`, @@ -561,11 +587,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 @@ -852,6 +887,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] @@ -906,6 +950,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`. @@ -930,9 +976,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 @@ -1688,8 +1735,25 @@ 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` — under its gate. + /// named function, for `Checker::is_func_with_code` — under + /// its gate. #[inline] pub fn is_callable<'a>( node: &Node<'a>, @@ -1780,6 +1844,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, @@ -2463,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. @@ -3986,6 +4062,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/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..7c0f32443 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}; @@ -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,21 +180,17 @@ 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; } - // 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 @@ -233,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")] @@ -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), @@ -873,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, @@ -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,19 +1295,198 @@ 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)), ) } +/// 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 +/// `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(); + 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) + .is_some_and(|owner| is_record_header(node, &owner)); + 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, 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"]); + 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, 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"]); + 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), + ] + ); +} + +/// 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], + is_record_header: IsRecordHeader, + 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) + .is_some_and(|owner| is_record_header(node, &owner)); + 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, 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, + is_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, 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, + is_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 /// (`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-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/big-code-analysis-bench/src/shapes.rs b/big-code-analysis-bench/src/shapes.rs index d6cb667d0..95113b120 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 @@ -455,6 +455,67 @@ 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 +/// 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: 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 +/// 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 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 +/// 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 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)); + 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. /// @@ -505,7 +566,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. /// @@ -1013,6 +1074,38 @@ 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 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 +/// 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. @@ -1127,7 +1220,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 +2680,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 +3159,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 +3174,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 \ @@ -3408,6 +3501,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 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.", + }, + 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 the top rung with the \ + gate asked once per constructor.", + }, Probe { name: "loc/rust-attributed-docs", lang: LANG::Rust, @@ -3790,6 +3925,56 @@ 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; each \ + level's nearest answer is memoised on \ + `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", + 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.00 and 26 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, @@ -4581,7 +4766,9 @@ 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, PAREN_PREFIX_PAIRS, PROBES, Probe, RECORD_BASE_CTORS, Workload, exported_nodes, + }; /// How deep an export nests, counted on an explicit stack like /// [`exported_nodes`]. @@ -5060,6 +5247,129 @@ 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 + /// 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 + /// 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/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 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/docs/development/benchmarking.md b/docs/development/benchmarking.md index 8f7beaae4..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: @@ -152,7 +161,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 | @@ -177,6 +186,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 | @@ -191,6 +202,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; 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 | @@ -347,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 @@ -833,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 @@ -872,6 +886,115 @@ 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 + 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 | +|---|---|---|---|---| +| 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. 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 + +`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. 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.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 +`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: 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 +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 + ### Child scans, and where the allocation actually was {#child-scans} `Node::children` builds a `tree_sitter::TreeCursor`, which heap-allocates diff --git a/docs/development/grammar_dispatch.md b/docs/development/grammar_dispatch.md index fa73a857a..a4b71aa1e 100644 --- a/docs/development/grammar_dispatch.md +++ b/docs/development/grammar_dispatch.md @@ -116,11 +116,12 @@ 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 -node present for every spelling, verified with `bca dump` on valid and +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. Where neither choice strands a node, keep the node whose span is the @@ -141,16 +142,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/docs/development/lessons_learned.md b/docs/development/lessons_learned.md index 4915fb6cf..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. @@ -5345,7 +5347,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 @@ -5356,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) {…} }` @@ -5364,9 +5367,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. --- 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..8390d019e 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. + // 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/cyclomatic.rs b/src/metrics/cyclomatic.rs index e0f9605b7..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 @@ -463,8 +463,45 @@ mod tests { #[cfg(feature = "cpp")] mod constrained_probe { use super::*; + + // 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], + _: Ancestors<'a, '_>, + ) -> bool { + false + } + + 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 + } + } + }; + } + struct Probe; - impl Checker for Probe {} + probe_checker!(Probe); impl_cyclomatic_rows!( Probe, Cpp, @@ -476,7 +513,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/loc.rs b/src/metrics/loc.rs index 30a3cd998..79a552c3f 100644 --- a/src/metrics/loc.rs +++ b/src/metrics/loc.rs @@ -10384,6 +10384,78 @@ EOF } } + /// #1863: whether code precedes a parenthesis on its logical line is + /// 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: + /// + /// - `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 + 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 + /// 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_each_level_once() { + let n = 40; + let nested = format!( + "{}\"\"\"doc\"\"\"\n{}\nx = 1\n", + "(\n\\\n# c\n".repeat(n), + ")".repeat(n) + ); + 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 `)`; 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` + // 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 `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 /// 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/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 diff --git a/src/metrics/loc/python.rs b/src/metrics/loc/python.rs index 4c038dda5..76bee5d93 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 { @@ -431,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) }) } @@ -593,27 +594,58 @@ 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. -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) +// 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. +// +// 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_parent`'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_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). +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 @@ -637,12 +669,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 3131eaf84..8adf553e9 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; @@ -854,16 +851,18 @@ 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 -// 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'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. 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::is_record_header(node, record)), Java::CompactConstructorDeclaration => ancestors .iter(node) .nth(1) @@ -885,10 +884,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 -// reads the body's constructor types, so the callable test is the -// `_with_code` spelling, as the shared impl's. +// `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. impl NArgs for GroovyCode { fn compute<'a>(node: &Node<'a>, code: &[u8], ancestors: Ancestors<'a, '_>, stats: &mut Stats) { use crate::languages::language_groovy::Groovy; @@ -943,60 +944,6 @@ 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}; - 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), - ("elixir Closure", elixir::closure::TEXT_GATED), - ]; - 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" - ); - } - } - /// 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 @@ -2720,7 +2667,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")] @@ -4444,7 +4391,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")] @@ -4466,6 +4416,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| { @@ -4492,6 +4444,8 @@ class A(val x: Int)", ("G", 1), ("H", 1), ("V", 1), + ("P", 2), + ("S", 2), ("Nullable", 0), ] ); @@ -4510,7 +4464,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() { @@ -4522,7 +4478,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 @@ -4541,6 +4499,8 @@ class A(val x: Int)", ("G", 1), ("K", 1), ("H", 1), + ("P", 2), + ("S", 2), ] ); }, @@ -4634,13 +4594,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 +4625,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() { @@ -4927,6 +4888,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/nom.rs b/src/metrics/nom.rs index 0b75e8309..c0f33e881 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` @@ -302,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 @@ -339,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" ); } } @@ -1387,8 +1387,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 +1618,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 +2359,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..1e568c2b3 100644 --- a/src/metrics/npm.rs +++ b/src/metrics/npm.rs @@ -264,21 +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 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 +/// 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>, - field: &str, + header: Option>, code: &[u8], ancestors: Ancestors<'a, '_>, ) -> bool { - record.child_by_field_name(field).is_some_and(|header| { + header.is_some_and(|header| { C::is_func_with_code(&header, code, ancestors.of_children(record).get()) }) } @@ -331,7 +332,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 +346,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>, @@ -354,11 +357,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()) } @@ -383,7 +389,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(node), + code, + ancestors, + ) { stats.class_nm += 1; let interface_member = ancestors.parent(node).is_some_and(|body| { matches!(body.kind_id().into(), InterfaceBody | AnnotationTypeBody) @@ -1435,7 +1446,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 +1461,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 @@ -1883,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 93e67aa14..6b893ddfa 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(node), + 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); 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..68421e9a1 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`, - // which is why this moves even though the block is deliberately - // *not* in `is_func` (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 5bba378ea..82877ab68 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), @@ -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"))] @@ -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..181120f6e 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. @@ -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