From f80bcf1cc7c19b12f262c6670741645ae16c8f1d Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Thu, 5 Nov 2026 20:48:05 -0800 Subject: [PATCH 01/25] docs(ast): bound the attribute-value reach gap The comment on rust_attribute_run_verdict's reach said rustc accepts an item-nesting attribute `value` "only for a proc macro to consume". rustc 1.99.1 also compiles one on an item a false `cfg` strips, since the literal check (Reference `attributes.meta.literal-expr`) never runs there, and rejects one on a derive helper, which stays on its item. Name both routes, cite the rule, and record that neither occurs in this repository or the serde corpus, which is why the gap stays documented rather than closed. Reworded within the same 15 lines: checker.rs sits at its baselined loc.sloc. Fixes #1786 --- big-code-analysis-ast/src/checker.rs | 30 ++++++++++++++-------------- 1 file changed, 15 insertions(+), 15 deletions(-) diff --git a/big-code-analysis-ast/src/checker.rs b/big-code-analysis-ast/src/checker.rs index ac5624728..d04ec795e 100644 --- a/big-code-analysis-ast/src/checker.rs +++ b/big-code-analysis-ast/src/checker.rs @@ -1155,21 +1155,21 @@ fn rust_attribute_run_verdict<'a>( // so never a run start — and the run's verdict is the item's own by // construction rather than by a second spelling of it. let skipped = RustCode::should_skip_subtree(&item, code, ancestors).is_skipped(); - // Everything strictly between `node` and `item` is a run member — - // an `AttributeItem` or a comment, which is what - // `rust_attributed_item` searched past — so the reach holds for the - // run's remaining members: they all decorate `item`, and go or stay - // with it (#1647). It holds for *their* descendants too, which the - // walk visits whenever the run is retained: an attribute's children - // are the `#`, `[`, `]` tokens and the `attribute` body, whose path, - // argument token tree and literal or macro-call value nest no - // `rust_prunable_item` and no run member, and a comment's are its - // delimiter, marker and `doc_comment` tokens, so `RETAIN` is their - // answer as well. A `value` that nests an item, such as a block, is - // the exception: rustc accepts one only for a proc macro to consume, - // and a `#[cfg(test)]` item inside it is kept. The reach holds for - // `item` too, since `skipped` is its own verdict, so the walk need - // not ask about it again (#1783). + // Everything strictly between `node` and `item` is a run member — an + // `AttributeItem` or a comment, which `rust_attributed_item` searched + // past — so the reach holds for the run's remaining members: they all + // decorate `item`, and go or stay with it (#1647). It holds for *their* + // descendants, which a retained run's walk visits, because an + // attribute's `#`, `[`, `]`, path, token-tree argument and literal or + // macro-call value nest no run member and no `rust_prunable_item`, and + // neither do a comment's delimiter, marker and `doc_comment` tokens. A + // `value` that nests an item, such as a block, is the exception: a + // `#[cfg(test)]` item inside it is kept. rustc rejects such a value + // (Reference `attributes.meta.literal-expr`), so it compiles only in + // code a false `cfg` strips or where an attribute macro consumes the + // attribute, never as a derive helper; neither occurs in this + // repository or serde (#1786). The reach holds for `item` too, since + // `skipped` is its own verdict, so the walk does not ask again (#1783). SubtreeSkip::of(skipped).covering_through_node(&item) } From 472c35df1a6fc6efbdb5f24a29da0443ef585bdc Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Thu, 5 Nov 2026 20:48:27 -0800 Subject: [PATCH 02/25] fix(ci): audit all eight lockfiles with cargo-deny Both cargo-deny jobs ran from the repository root and so read only the root Cargo.lock. The seven [workspace].exclude crates (enums, fuzz and the five tree-sitter-* grammars) each resolve a graph of their own, and only Scorecard read those, on main, after merge: RUSTSEC-2026-0374 sat in enums/Cargo.lock that way until #1822. utils/check-deny-manifests.sh runs cargo-deny once per tracked Cargo.lock against the root deny.toml, with --locked, and fails when the tracked count is not eight, so a ninth excluded crate cannot enter unaudited. The ci.yml deny job and deny-advisories.yml both call it, installing cargo-deny 0.20.2 (what cargo-deny-action v2.1.1 shipped) through the SHA-pinned taiki-e/install-action, which checks the tarball's sha256. 0.20 moved --config to the top level and rejects `check --config`, so the script refuses an older cargo-deny. Running all four checks over the new graphs found three failures, each fixed at its narrowest point: - enums was unlicensed: its manifest now states the repository's MPL-2.0. licenses.private.ignore would also have stopped checking the licence of big-code-analysis-py, which ships to PyPI. - fuzz's libfuzzer-sys carries LLVM's NCSA: a crate-scoped exception. - fuzz's version-less path dependency read as a wildcard: allow-wildcard-paths, which exempts only publish = false crates. utils/check-deny-manifests-test.py, wired into make pre-commit, make ci, pre-commit and the lint job, drives the script against a stubbed cargo-deny in a scratch repository and against the live tree. Fixes #1823 --- .github/workflows/ci.yml | 24 ++- .github/workflows/deny-advisories.yml | 16 +- .pre-commit-config.yaml | 11 + AGENTS.md | 25 ++- Makefile | 25 ++- deny.toml | 20 ++ enums/Cargo.toml | 3 + utils/check-deny-manifests-test.py | 300 ++++++++++++++++++++++++++ utils/check-deny-manifests.sh | 123 +++++++++++ 9 files changed, 529 insertions(+), 18 deletions(-) create mode 100644 utils/check-deny-manifests-test.py create mode 100755 utils/check-deny-manifests.sh diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 37fcefada..396003ae1 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -675,9 +675,23 @@ jobs: with: fetch-depth: 1 submodules: false - - uses: EmbarkStudios/cargo-deny-action@3c6349835b2b7b196a839186cb8b78e02f7b5f25 # v2.1.1 + # cargo-deny resolves each graph with `cargo metadata`, so it needs a + # cargo; the action this replaced brought its own in a container. + - uses: dtolnay/rust-toolchain@683b588c487a69d01f6c6ddf40f036ff682cc2c8 # stable tip + with: + toolchain: stable + # 0.20.2 is what `cargo-deny-action` v2.1.1 shipped. install-action + # checks the release tarball against the sha256 in its own manifest, + # which the action's SHA pin fixes. Keep this pin equal to the one in + # deny-advisories.yml; `utils/check-deny-manifests-test.py` fails + # when they differ. + - uses: taiki-e/install-action@86f7a0ffb25f40114606501a311ebcfaf882ea32 # v2.88.0 with: - command: check advisories bans licenses sources + tool: cargo-deny@0.20.2 + # Every tracked Cargo.lock, not only the root's (#1823): the seven + # `[workspace].exclude` crates resolve graphs of their own, and until + # this ran per manifest only Scorecard read them, after merge. + - run: ./utils/check-deny-manifests.sh advisories bans licenses sources license-audit: name: license-audit @@ -944,6 +958,12 @@ jobs: run: python3 -B utils/check-grammar-build-watch.py - name: check-grammar-build-watch self-tests (explicit) run: python3 -B -m unittest -q utils/check-grammar-build-watch-test.py + # The `deny` job runs utils/check-deny-manifests.sh for real (#1823). + # Its self-tests pin what that job cannot show on a green run: every + # manifest and every check is invoked, a ninth lockfile fails, and + # both deny workflows still call the script on one cargo-deny pin. + - name: check-deny-manifests self-tests (explicit) + run: python3 -m unittest -q utils/check-deny-manifests-test.py # Defensive twin for the grammar-marker-sync gate (#400): bumping # the notification-only marker in tree-sitter-{mozjs,mozcpp}/ # Cargo.toml without re-running the matching generate-*.sh diff --git a/.github/workflows/deny-advisories.yml b/.github/workflows/deny-advisories.yml index b02ae0a33..962842a22 100644 --- a/.github/workflows/deny-advisories.yml +++ b/.github/workflows/deny-advisories.yml @@ -1,7 +1,8 @@ name: Advisories -# Weekly `cargo-deny check advisories` against the default branch's -# lockfile (#1815). +# Weekly `cargo-deny check advisories` against every lockfile the default +# branch tracks (#1815): the root's and the seven `[workspace].exclude` +# crates', through `utils/check-deny-manifests.sh` (#1823). # # The `deny` job in ci.yml runs on push and pull request only, so an # advisory published between pushes is seen only by Dependabot or the @@ -47,6 +48,13 @@ jobs: fetch-depth: 1 submodules: false persist-credentials: false - - uses: EmbarkStudios/cargo-deny-action@3c6349835b2b7b196a839186cb8b78e02f7b5f25 # v2.1.1 + # The same toolchain, cargo-deny pin and script as ci.yml's `deny` + # job, so the weekly run audits exactly the graphs a pull request + # does. See that job for why each step is there. + - uses: dtolnay/rust-toolchain@683b588c487a69d01f6c6ddf40f036ff682cc2c8 # stable tip with: - command: check advisories + toolchain: stable + - uses: taiki-e/install-action@86f7a0ffb25f40114606501a311ebcfaf882ea32 # v2.88.0 + with: + tool: cargo-deny@0.20.2 + - run: ./utils/check-deny-manifests.sh advisories diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index f60f31c1b..662c75299 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -636,6 +636,17 @@ repos: entry: python3 -B -m unittest -q utils/check-grammar-build-watch-test.py pass_filenames: false + # Self-tests for utils/check-deny-manifests.sh, which only the two + # `deny` workflow jobs run for real (#1823). Fires on a lockfile too, + # because a ninth tracked Cargo.lock is what the live-tree case + # exists to catch, and on both workflows, whose wiring it pins. + - id: check-deny-manifests-test + name: check-deny-manifests-test + language: system + files: '^(utils/check-deny-manifests(\.sh|-test\.py)|\.github/workflows/(ci|deny-advisories)\.yml|([^/]+/)?Cargo\.lock)$' + entry: python3 -m unittest -q utils/check-deny-manifests-test.py + pass_filenames: false + # The `enums/` crate is workspace-excluded, so the workspace # clippy/test hooks above never touch it. Add a dedicated check # so warnings here cannot drift (see #164). diff --git a/AGENTS.md b/AGENTS.md index 556112471..8e3d555e6 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -109,6 +109,10 @@ and `cargo run -p big-code-analysis-web --`. Each gate resolves the repository root from its own location (`Path(__file__).resolve().parents[1]`) rather than the cwd, so it runs correctly from anywhere; callers invoke them as `utils/`. + `check-deny-manifests.sh` (#1823) is a gate `make pre-commit` does + not run, because it needs the network: the two `deny` workflow jobs + call it to run cargo-deny once per tracked `Cargo.lock`, and `make + pre-commit` runs only its `*-test.py`, against a stubbed cargo-deny. `check-grammar-crate.py`, `check-grammars-crates.sh`, `patch-coverage.py` and `verify-name-only-churn.py` are not gates: they take their paths as arguments or run against the cwd. Nor are @@ -707,14 +711,19 @@ what keeps the job quiet. See **Advisories** is the fifth (`.github/workflows/deny-advisories.yml`, #1815): `cargo-deny check -advisories` against `main`'s lockfile every Monday. The `deny` job in -`ci.yml` runs the same check — plus bans, licences and sources, which -do not age — on push, pull request and dispatch, never on a schedule, -so between pushes an advisory is seen by Dependabot or Scorecard or not -at all; a RUSTSEC `unsound` / `unmaintained` entry has no Dependabot -path. A red run is the signal and no issue is filed. The fix is the -same as for a red `deny` job: move the lockfile past the advisory, or -add a documented `ignore` to `deny.toml`. +advisories` every Monday against all eight lockfiles `main` tracks — +the root's and the seven `[workspace].exclude` crates', each a graph of +its own — through `utils/check-deny-manifests.sh` (#1823). The `deny` +job in `ci.yml` runs the same script over the same eight, adding bans, +licences and sources, which do not age, on push, pull request and +dispatch, never on a schedule. So between pushes an advisory is seen by +Dependabot or Scorecard or not at all; a RUSTSEC `unsound` / +`unmaintained` entry has no Dependabot path. A red run is the signal +and no issue is filed. The fix is the same as for a red `deny` job: +move the lockfile past the advisory, or add a documented `ignore` to +`deny.toml`, which is keyed by advisory id and so covers all eight +graphs. A ninth lockfile fails the script until its +`EXPECTED_LOCKFILES` is raised. For snapshot test changes, run `cargo insta test --review` and accept or reject each snapshot rather than blindly updating files. diff --git a/Makefile b/Makefile index 5c9faaad9..e90403292 100644 --- a/Makefile +++ b/Makefile @@ -88,7 +88,7 @@ find-by-ext = $(if $(FD),$(FD) --extension $(1) $(FD_EXCLUDE) $(2),find . -name NEXTEST := $(shell command -v cargo-nextest 2>/dev/null) TEST_CMD = $(if $(NEXTEST),$(NEXTEST) nextest run --workspace --all-features,cargo test --workspace --all-features --lib --bins --tests) -.PHONY: role-census role-census-test role-coverage role-coverage-test role-coverage-observe role-coverage-claimed role-parity-corpus role-corpus-refresh role-bypass role-bypass-test mutation-report-test mutation-workflow-test drift-common-test drift-oracle-test drift-compare-test recovery-oracle-test perturb-test coverage-diff-test self-scan-bca-test _pc-role-census _pc-role-census-test _pc-role-coverage _pc-role-coverage-test _pc-role-bypass _pc-role-bypass-test _ci-role-census _ci-role-census-test _ci-role-coverage _ci-role-coverage-test _ci-role-bypass _ci-role-bypass-test help check-tools worktree-setup worktree-setup-test build build-release check test test-doc chain-audit fmt fmt-check markdown-fmt markdown-lint shellcheck sh-fmt sh-fmt-check toml-fmt toml-fmt-check toml-lint makefile-check actionlint snapshot-anchors snapshot-anchors-test rustfmt-bail rustfmt-bail-test grammar-marker-sync grammar-marker-sync-test check-versions check-excluded-manifests check-excluded-manifests-test check-ruff-lockstep check-ruff-lockstep-test check-rumdl-lockstep check-rumdl-lockstep-test check-publish-metadata check-publish-metadata-test check-manpage-assets check-manpage-drift-test check-diagnostic-prefix check-diagnostic-prefix-test check-feature-gates check-feature-gates-test check-test-lang-gates check-test-lang-gates-compare check-test-lang-gates-test check-safety-doc-pin check-safety-doc-pin-test check-grammar-build-watch check-grammar-build-watch-test gate-status-test check-tools-test enums-check enums-codegen-drift enums-codegen-drift-test self-scan self-scan-headroom self-scan-write-baseline self-scan-write-baseline-headroom self-scan-baseline-fresh self-scan-profile-parity vcs lint clippy udeps insta-review insta-accept clean distclean install install-cli install-web doc doc-open doc-check doc-check-docsrs book book-serve book-pot book-po-update book-ja book-deploy all pre-commit ci release-check verify-changelog pkg-deb-local pkg-rpm-local dev-env-build dev-env-run dev-env-shell dev-env-rm py-bootstrap py-sync py-relock py-clean py-fmt py-fmt-check py-lint py-typecheck py-test py-stubtest smoke smoke-cli smoke-lib bench bench-scaling bench-walk fuzz-check fuzz-smoke fuzz-replay fuzz-run fuzz-tmin _check-find _pc-all _pc-fmt _pc-clippy _pc-test _pc-doc-check _pc-udeps _pc-shellcheck _pc-markdown-lint _pc-toml-lint _pc-makefile-check _pc-actionlint _pc-snapshot-anchors _pc-snapshot-anchors-test _pc-rustfmt-bail _pc-rustfmt-bail-test _pc-role-census _pc-role-census-test _pc-role-coverage _pc-role-coverage-test _pc-role-bypass _pc-role-bypass-test _pc-mutation-report-test _pc-mutation-workflow-test _pc-drift-common-test _pc-drift-oracle-test _pc-drift-compare-test _pc-recovery-oracle-test _pc-perturb-test _pc-coverage-diff-test _pc-self-scan-bca-test _pc-grammar-marker-sync _pc-grammar-marker-sync-test _pc-check-versions _pc-check-versions-test _pc-check-grammar-crate-test _pc-check-excluded-manifests _pc-check-excluded-manifests-test _pc-check-ruff-lockstep _pc-check-ruff-lockstep-test _pc-check-rumdl-lockstep _pc-check-rumdl-lockstep-test _pc-check-publish-metadata _pc-check-publish-metadata-test _pc-check-manpage-assets _pc-check-manpage-drift-test _pc-check-diagnostic-prefix _pc-check-diagnostic-prefix-test _pc-check-feature-gates-test _pc-check-test-lang-gates _pc-check-test-lang-gates-test _pc-check-safety-doc-pin _pc-check-safety-doc-pin-test _pc-check-grammar-build-watch _pc-check-grammar-build-watch-test _pc-worktree-setup-test _pc-gate-status-test _pc-check-tools-test _pc-enums-check _pc-enums-codegen-drift _pc-enums-codegen-drift-test _pc-self-scan _pc-self-scan-headroom _pc-py-fmt _pc-py-typecheck _pc-py-test _pc-py-stubtest _ci-all _ci-fmt-check _ci-clippy _ci-test _ci-doc-check _ci-build _ci-udeps _ci-shellcheck _ci-markdown-lint _ci-toml-lint _ci-makefile-check _ci-actionlint _ci-snapshot-anchors _ci-snapshot-anchors-test _ci-rustfmt-bail _ci-rustfmt-bail-test _ci-role-census _ci-role-census-test _ci-role-coverage _ci-role-coverage-test _ci-role-bypass _ci-role-bypass-test _ci-mutation-report-test _ci-mutation-workflow-test _ci-drift-common-test _ci-drift-oracle-test _ci-drift-compare-test _ci-recovery-oracle-test _ci-perturb-test _ci-coverage-diff-test _ci-self-scan-bca-test _ci-grammar-marker-sync _ci-grammar-marker-sync-test _ci-check-versions _ci-check-versions-test _ci-check-grammar-crate-test _ci-check-excluded-manifests _ci-check-excluded-manifests-test _ci-check-ruff-lockstep _ci-check-ruff-lockstep-test _ci-check-rumdl-lockstep _ci-check-rumdl-lockstep-test _ci-check-publish-metadata _ci-check-publish-metadata-test _ci-check-manpage-assets _ci-check-manpage-drift-test _ci-check-diagnostic-prefix _ci-check-diagnostic-prefix-test _ci-check-feature-gates-test _ci-check-test-lang-gates _ci-check-test-lang-gates-test _ci-check-safety-doc-pin _ci-check-safety-doc-pin-test _ci-check-grammar-build-watch _ci-check-grammar-build-watch-test _ci-worktree-setup-test _ci-gate-status-test _ci-check-tools-test _ci-enums-check _ci-enums-codegen-drift _ci-enums-codegen-drift-test _ci-enums-codegen-drift-test _ci-self-scan _ci-self-scan-headroom _ci-cargo-pipeline _ci-py-fmt-check _ci-py-lint _ci-py-typecheck _ci-py-test _ci-py-stubtest +.PHONY: role-census role-census-test role-coverage role-coverage-test role-coverage-observe role-coverage-claimed role-parity-corpus role-corpus-refresh role-bypass role-bypass-test mutation-report-test mutation-workflow-test drift-common-test drift-oracle-test drift-compare-test recovery-oracle-test perturb-test coverage-diff-test self-scan-bca-test _pc-role-census _pc-role-census-test _pc-role-coverage _pc-role-coverage-test _pc-role-bypass _pc-role-bypass-test _ci-role-census _ci-role-census-test _ci-role-coverage _ci-role-coverage-test _ci-role-bypass _ci-role-bypass-test help check-tools worktree-setup worktree-setup-test build build-release check test test-doc chain-audit fmt fmt-check markdown-fmt markdown-lint shellcheck sh-fmt sh-fmt-check toml-fmt toml-fmt-check toml-lint makefile-check actionlint snapshot-anchors snapshot-anchors-test rustfmt-bail rustfmt-bail-test grammar-marker-sync grammar-marker-sync-test check-versions check-excluded-manifests check-excluded-manifests-test check-ruff-lockstep check-ruff-lockstep-test check-rumdl-lockstep check-rumdl-lockstep-test check-publish-metadata check-publish-metadata-test check-manpage-assets check-manpage-drift-test check-diagnostic-prefix check-diagnostic-prefix-test check-feature-gates check-feature-gates-test check-test-lang-gates check-test-lang-gates-compare check-test-lang-gates-test check-safety-doc-pin check-safety-doc-pin-test check-grammar-build-watch check-grammar-build-watch-test check-deny-manifests-test gate-status-test check-tools-test enums-check enums-codegen-drift enums-codegen-drift-test self-scan self-scan-headroom self-scan-write-baseline self-scan-write-baseline-headroom self-scan-baseline-fresh self-scan-profile-parity vcs lint clippy udeps insta-review insta-accept clean distclean install install-cli install-web doc doc-open doc-check doc-check-docsrs book book-serve book-pot book-po-update book-ja book-deploy all pre-commit ci release-check verify-changelog pkg-deb-local pkg-rpm-local dev-env-build dev-env-run dev-env-shell dev-env-rm py-bootstrap py-sync py-relock py-clean py-fmt py-fmt-check py-lint py-typecheck py-test py-stubtest smoke smoke-cli smoke-lib bench bench-scaling bench-walk fuzz-check fuzz-smoke fuzz-replay fuzz-run fuzz-tmin _check-find _pc-all _pc-fmt _pc-clippy _pc-test _pc-doc-check _pc-udeps _pc-shellcheck _pc-markdown-lint _pc-toml-lint _pc-makefile-check _pc-actionlint _pc-snapshot-anchors _pc-snapshot-anchors-test _pc-rustfmt-bail _pc-rustfmt-bail-test _pc-role-census _pc-role-census-test _pc-role-coverage _pc-role-coverage-test _pc-role-bypass _pc-role-bypass-test _pc-mutation-report-test _pc-mutation-workflow-test _pc-drift-common-test _pc-drift-oracle-test _pc-drift-compare-test _pc-recovery-oracle-test _pc-perturb-test _pc-coverage-diff-test _pc-self-scan-bca-test _pc-grammar-marker-sync _pc-grammar-marker-sync-test _pc-check-versions _pc-check-versions-test _pc-check-grammar-crate-test _pc-check-excluded-manifests _pc-check-excluded-manifests-test _pc-check-ruff-lockstep _pc-check-ruff-lockstep-test _pc-check-rumdl-lockstep _pc-check-rumdl-lockstep-test _pc-check-publish-metadata _pc-check-publish-metadata-test _pc-check-manpage-assets _pc-check-manpage-drift-test _pc-check-diagnostic-prefix _pc-check-diagnostic-prefix-test _pc-check-feature-gates-test _pc-check-test-lang-gates _pc-check-test-lang-gates-test _pc-check-safety-doc-pin _pc-check-safety-doc-pin-test _pc-check-grammar-build-watch _pc-check-grammar-build-watch-test _pc-check-deny-manifests-test _pc-worktree-setup-test _pc-gate-status-test _pc-check-tools-test _pc-enums-check _pc-enums-codegen-drift _pc-enums-codegen-drift-test _pc-self-scan _pc-self-scan-headroom _pc-py-fmt _pc-py-typecheck _pc-py-test _pc-py-stubtest _ci-all _ci-fmt-check _ci-clippy _ci-test _ci-doc-check _ci-build _ci-udeps _ci-shellcheck _ci-markdown-lint _ci-toml-lint _ci-makefile-check _ci-actionlint _ci-snapshot-anchors _ci-snapshot-anchors-test _ci-rustfmt-bail _ci-rustfmt-bail-test _ci-role-census _ci-role-census-test _ci-role-coverage _ci-role-coverage-test _ci-role-bypass _ci-role-bypass-test _ci-mutation-report-test _ci-mutation-workflow-test _ci-drift-common-test _ci-drift-oracle-test _ci-drift-compare-test _ci-recovery-oracle-test _ci-perturb-test _ci-coverage-diff-test _ci-self-scan-bca-test _ci-grammar-marker-sync _ci-grammar-marker-sync-test _ci-check-versions _ci-check-versions-test _ci-check-grammar-crate-test _ci-check-excluded-manifests _ci-check-excluded-manifests-test _ci-check-ruff-lockstep _ci-check-ruff-lockstep-test _ci-check-rumdl-lockstep _ci-check-rumdl-lockstep-test _ci-check-publish-metadata _ci-check-publish-metadata-test _ci-check-manpage-assets _ci-check-manpage-drift-test _ci-check-diagnostic-prefix _ci-check-diagnostic-prefix-test _ci-check-feature-gates-test _ci-check-test-lang-gates _ci-check-test-lang-gates-test _ci-check-safety-doc-pin _ci-check-safety-doc-pin-test _ci-check-grammar-build-watch _ci-check-grammar-build-watch-test _ci-check-deny-manifests-test _ci-worktree-setup-test _ci-gate-status-test _ci-check-tools-test _ci-enums-check _ci-enums-codegen-drift _ci-enums-codegen-drift-test _ci-enums-codegen-drift-test _ci-self-scan _ci-self-scan-headroom _ci-cargo-pipeline _ci-py-fmt-check _ci-py-lint _ci-py-typecheck _ci-py-test _ci-py-stubtest .PHONY: plugin-test _pc-plugin-test _ci-plugin-test @@ -179,6 +179,7 @@ help: @echo " check-safety-doc-pin-test Self-tests for the safety-doc-pin gate" @echo " check-grammar-build-watch Assert every vendored grammar build.rs watches src/tree_sitter/ headers" @echo " check-grammar-build-watch-test Self-tests for the grammar-build-watch gate" + @echo " check-deny-manifests-test Self-tests for the per-lockfile cargo-deny script CI runs" @echo " worktree-setup-test Self-tests for the worktree-setup submodule classifier" @echo " gate-status-test Self-tests for the pre-commit/ci BCA_GATE verdict line" @echo " check-tools-test Self-tests for the check-tools tool probes and hints" @@ -894,6 +895,15 @@ check-grammar-build-watch-test: @echo "Running check-grammar-build-watch self-tests..." @(cd $(BASE_DIR) && python3 -B -m unittest -q utils/check-grammar-build-watch-test.py) +# utils/check-deny-manifests.sh runs cargo-deny once per tracked Cargo.lock +# (#1823) and is called only by the two `deny` workflow jobs, because the +# real run needs the network and a pinned cargo-deny. These self-tests are +# therefore the only local check of it: they drive it against a stubbed +# cargo-deny, and fail on a ninth lockfile in the live tree. +check-deny-manifests-test: + @echo "Running check-deny-manifests self-tests..." + @(cd $(BASE_DIR) && python3 -m unittest -q utils/check-deny-manifests-test.py) + plugin-test: @if command -v node >/dev/null 2>&1 && node -e 'const [a,b] = process.versions.node.split(".").map(Number); process.exit(a > 22 || (a === 22 && b >= 7) ? 0 : 1)'; then \ node --test "$(BASE_DIR)utils/bca-check-plugin-test.mjs" "$(BASE_DIR)utils/bca-claude-hook-test.mjs"; \ @@ -1690,7 +1700,7 @@ lint: $(MAKE) -j --output-sync=target \ _ci-clippy _ci-plugin-test \ _ci-shellcheck _ci-markdown-lint _ci-toml-lint _ci-makefile-check \ - _ci-actionlint _ci-snapshot-anchors _ci-snapshot-anchors-test _ci-rustfmt-bail _ci-rustfmt-bail-test _ci-role-census _ci-role-census-test _ci-role-coverage _ci-role-coverage-test _ci-role-bypass _ci-role-bypass-test _ci-mutation-report-test _ci-mutation-workflow-test _ci-drift-common-test _ci-drift-oracle-test _ci-drift-compare-test _ci-recovery-oracle-test _ci-perturb-test _ci-coverage-diff-test _ci-self-scan-bca-test _ci-grammar-marker-sync _ci-grammar-marker-sync-test _ci-check-versions _ci-check-versions-test _ci-check-grammar-crate-test _ci-check-excluded-manifests _ci-check-excluded-manifests-test _ci-check-ruff-lockstep _ci-check-ruff-lockstep-test _ci-check-rumdl-lockstep _ci-check-rumdl-lockstep-test _ci-check-publish-metadata _ci-check-publish-metadata-test _ci-check-manpage-assets _ci-check-manpage-drift-test _ci-check-diagnostic-prefix _ci-check-diagnostic-prefix-test _ci-check-feature-gates-test _ci-check-test-lang-gates _ci-check-test-lang-gates-test _ci-check-safety-doc-pin _ci-check-safety-doc-pin-test _ci-check-grammar-build-watch _ci-check-grammar-build-watch-test _ci-worktree-setup-test _ci-gate-status-test _ci-check-tools-test _ci-enums-check _ci-enums-codegen-drift _ci-enums-codegen-drift-test + _ci-actionlint _ci-snapshot-anchors _ci-snapshot-anchors-test _ci-rustfmt-bail _ci-rustfmt-bail-test _ci-role-census _ci-role-census-test _ci-role-coverage _ci-role-coverage-test _ci-role-bypass _ci-role-bypass-test _ci-mutation-report-test _ci-mutation-workflow-test _ci-drift-common-test _ci-drift-oracle-test _ci-drift-compare-test _ci-recovery-oracle-test _ci-perturb-test _ci-coverage-diff-test _ci-self-scan-bca-test _ci-grammar-marker-sync _ci-grammar-marker-sync-test _ci-check-versions _ci-check-versions-test _ci-check-grammar-crate-test _ci-check-excluded-manifests _ci-check-excluded-manifests-test _ci-check-ruff-lockstep _ci-check-ruff-lockstep-test _ci-check-rumdl-lockstep _ci-check-rumdl-lockstep-test _ci-check-publish-metadata _ci-check-publish-metadata-test _ci-check-manpage-assets _ci-check-manpage-drift-test _ci-check-diagnostic-prefix _ci-check-diagnostic-prefix-test _ci-check-feature-gates-test _ci-check-test-lang-gates _ci-check-test-lang-gates-test _ci-check-safety-doc-pin _ci-check-safety-doc-pin-test _ci-check-grammar-build-watch _ci-check-grammar-build-watch-test _ci-check-deny-manifests-test _ci-worktree-setup-test _ci-gate-status-test _ci-check-tools-test _ci-enums-check _ci-enums-codegen-drift _ci-enums-codegen-drift-test # --------------------------------------------------------------------------- # Maintenance @@ -1877,7 +1887,7 @@ _pc-all: $(MAKE) -j --output-sync=target \ _pc-test _pc-plugin-test \ _pc-shellcheck _pc-markdown-lint _pc-toml-lint _pc-makefile-check \ - _pc-actionlint _pc-snapshot-anchors _pc-snapshot-anchors-test _pc-rustfmt-bail _pc-rustfmt-bail-test _pc-role-census _pc-role-census-test _pc-role-coverage _pc-role-coverage-test _pc-role-bypass _pc-role-bypass-test _pc-mutation-report-test _pc-mutation-workflow-test _pc-drift-common-test _pc-drift-oracle-test _pc-drift-compare-test _pc-recovery-oracle-test _pc-perturb-test _pc-coverage-diff-test _pc-self-scan-bca-test _pc-grammar-marker-sync _pc-grammar-marker-sync-test _pc-check-versions _pc-check-versions-test _pc-check-grammar-crate-test _pc-check-excluded-manifests _pc-check-excluded-manifests-test _pc-check-ruff-lockstep _pc-check-ruff-lockstep-test _pc-check-rumdl-lockstep _pc-check-rumdl-lockstep-test _pc-check-publish-metadata _pc-check-publish-metadata-test _pc-check-manpage-assets _pc-check-manpage-drift-test _pc-check-diagnostic-prefix _pc-check-diagnostic-prefix-test _pc-check-feature-gates-test _pc-check-test-lang-gates _pc-check-test-lang-gates-test _pc-check-safety-doc-pin _pc-check-safety-doc-pin-test _pc-check-grammar-build-watch _pc-check-grammar-build-watch-test _pc-worktree-setup-test _pc-gate-status-test _pc-check-tools-test _pc-enums-check _pc-enums-codegen-drift _pc-enums-codegen-drift-test \ + _pc-actionlint _pc-snapshot-anchors _pc-snapshot-anchors-test _pc-rustfmt-bail _pc-rustfmt-bail-test _pc-role-census _pc-role-census-test _pc-role-coverage _pc-role-coverage-test _pc-role-bypass _pc-role-bypass-test _pc-mutation-report-test _pc-mutation-workflow-test _pc-drift-common-test _pc-drift-oracle-test _pc-drift-compare-test _pc-recovery-oracle-test _pc-perturb-test _pc-coverage-diff-test _pc-self-scan-bca-test _pc-grammar-marker-sync _pc-grammar-marker-sync-test _pc-check-versions _pc-check-versions-test _pc-check-grammar-crate-test _pc-check-excluded-manifests _pc-check-excluded-manifests-test _pc-check-ruff-lockstep _pc-check-ruff-lockstep-test _pc-check-rumdl-lockstep _pc-check-rumdl-lockstep-test _pc-check-publish-metadata _pc-check-publish-metadata-test _pc-check-manpage-assets _pc-check-manpage-drift-test _pc-check-diagnostic-prefix _pc-check-diagnostic-prefix-test _pc-check-feature-gates-test _pc-check-test-lang-gates _pc-check-test-lang-gates-test _pc-check-safety-doc-pin _pc-check-safety-doc-pin-test _pc-check-grammar-build-watch _pc-check-grammar-build-watch-test _pc-check-deny-manifests-test _pc-worktree-setup-test _pc-gate-status-test _pc-check-tools-test _pc-enums-check _pc-enums-codegen-drift _pc-enums-codegen-drift-test \ _pc-manpages \ _pc-self-scan _pc-self-scan-headroom \ _pc-py-fmt _pc-py-typecheck _pc-py-test _pc-py-stubtest @@ -1887,7 +1897,7 @@ _ci-all: $(MAKE) -j --output-sync=target \ _ci-cargo-pipeline _ci-plugin-test \ _ci-shellcheck _ci-markdown-lint _ci-toml-lint _ci-makefile-check \ - _ci-actionlint _ci-snapshot-anchors _ci-snapshot-anchors-test _ci-rustfmt-bail _ci-rustfmt-bail-test _ci-role-census _ci-role-census-test _ci-role-coverage _ci-role-coverage-test _ci-role-bypass _ci-role-bypass-test _ci-mutation-report-test _ci-mutation-workflow-test _ci-drift-common-test _ci-drift-oracle-test _ci-drift-compare-test _ci-recovery-oracle-test _ci-perturb-test _ci-coverage-diff-test _ci-self-scan-bca-test _ci-grammar-marker-sync _ci-grammar-marker-sync-test _ci-check-versions _ci-check-versions-test _ci-check-grammar-crate-test _ci-check-excluded-manifests _ci-check-excluded-manifests-test _ci-check-ruff-lockstep _ci-check-ruff-lockstep-test _ci-check-rumdl-lockstep _ci-check-rumdl-lockstep-test _ci-check-publish-metadata _ci-check-publish-metadata-test _ci-check-manpage-assets _ci-check-manpage-drift-test _ci-check-diagnostic-prefix _ci-check-diagnostic-prefix-test _ci-check-feature-gates-test _ci-check-test-lang-gates _ci-check-test-lang-gates-test _ci-check-safety-doc-pin _ci-check-safety-doc-pin-test _ci-check-grammar-build-watch _ci-check-grammar-build-watch-test _ci-worktree-setup-test _ci-gate-status-test _ci-check-tools-test _ci-enums-check _ci-enums-codegen-drift _ci-enums-codegen-drift-test \ + _ci-actionlint _ci-snapshot-anchors _ci-snapshot-anchors-test _ci-rustfmt-bail _ci-rustfmt-bail-test _ci-role-census _ci-role-census-test _ci-role-coverage _ci-role-coverage-test _ci-role-bypass _ci-role-bypass-test _ci-mutation-report-test _ci-mutation-workflow-test _ci-drift-common-test _ci-drift-oracle-test _ci-drift-compare-test _ci-recovery-oracle-test _ci-perturb-test _ci-coverage-diff-test _ci-self-scan-bca-test _ci-grammar-marker-sync _ci-grammar-marker-sync-test _ci-check-versions _ci-check-versions-test _ci-check-grammar-crate-test _ci-check-excluded-manifests _ci-check-excluded-manifests-test _ci-check-ruff-lockstep _ci-check-ruff-lockstep-test _ci-check-rumdl-lockstep _ci-check-rumdl-lockstep-test _ci-check-publish-metadata _ci-check-publish-metadata-test _ci-check-manpage-assets _ci-check-manpage-drift-test _ci-check-diagnostic-prefix _ci-check-diagnostic-prefix-test _ci-check-feature-gates-test _ci-check-test-lang-gates _ci-check-test-lang-gates-test _ci-check-safety-doc-pin _ci-check-safety-doc-pin-test _ci-check-grammar-build-watch _ci-check-grammar-build-watch-test _ci-check-deny-manifests-test _ci-worktree-setup-test _ci-gate-status-test _ci-check-tools-test _ci-enums-check _ci-enums-codegen-drift _ci-enums-codegen-drift-test \ _ci-py-fmt-check _ci-py-lint _ci-py-typecheck _ci-py-test _ci-py-stubtest # --------------------------------------------------------------------------- @@ -1950,6 +1960,7 @@ _ci-all: # ├── _pc-check-safety-doc-pin-test # ├── _pc-check-grammar-build-watch # ├── _pc-check-grammar-build-watch-test +# ├── _pc-check-deny-manifests-test # ├── _pc-worktree-setup-test # ├── _pc-gate-status-test # ├── _pc-check-tools-test @@ -2155,6 +2166,9 @@ _pc-check-grammar-build-watch: _pc-fmt _pc-check-grammar-build-watch-test: _pc-fmt $(MAKE) check-grammar-build-watch-test +_pc-check-deny-manifests-test: _pc-fmt + $(MAKE) check-deny-manifests-test + _pc-worktree-setup-test: _pc-fmt $(MAKE) worktree-setup-test @@ -2429,6 +2443,9 @@ _ci-check-grammar-build-watch: _ci-check-grammar-build-watch-test: $(MAKE) check-grammar-build-watch-test +_ci-check-deny-manifests-test: + $(MAKE) check-deny-manifests-test + _ci-worktree-setup-test: $(MAKE) worktree-setup-test diff --git a/deny.toml b/deny.toml index 1c66be84f..258abde33 100644 --- a/deny.toml +++ b/deny.toml @@ -3,6 +3,12 @@ # `big-code-analysis` itself is licensed under MPL-2.0, and several of # its first-party crates re-license under MPL-2.0, so MPL-2.0 must be # accepted for the dependency graph to resolve. +# +# One config, eight graphs. `utils/check-deny-manifests.sh` runs cargo-deny +# against every tracked `Cargo.lock` — the root workspace plus the seven +# `[workspace].exclude` crates (`enums`, `fuzz`, the five `tree-sitter-*`), +# each of which resolves its own — and passes this file to each by +# `--config` (#1823). An entry below therefore applies to all eight. [graph] all-features = true @@ -10,6 +16,9 @@ all-features = true [advisories] version = 2 yanked = "deny" +# Keyed by advisory id, not by lockfile: one entry silences that advisory in +# all eight graphs, including ones it was never reported against. Say in its +# `reason` which graph needed it. ignore = [] # The default scope ("workspace") reports an unsound advisory only for a # direct dependency, so RUSTSEC-2026-0306 in `faster-hex` (reached through @@ -37,10 +46,21 @@ allow = [ "MPL-2.0", ] confidence-threshold = 0.93 +# `libfuzzer-sys` vendors LLVM's libFuzzer, whose NCSA licence is ANDed onto +# the crate's own `MIT OR Apache-2.0`. NCSA is permissive (BSD-style), and +# the crate sits only in the unpublished `fuzz` graph, so an exception scoped +# to it beats a global allow that any future crate could ride. The seven +# graphs without `fuzz` warn `license-exception-not-encountered`; expected. +exceptions = [{ crate = "libfuzzer-sys", allow = ["NCSA"] }] [bans] multiple-versions = "warn" wildcards = "deny" +# `fuzz` takes `big-code-analysis` by path with no version, deliberately (see +# `fuzz/Cargo.toml`), and cargo-deny reads that as a wildcard. This exempts a +# path dependency only in a `publish = false` crate, plus path dev-deps, which +# crates.io strips; a published crate's path dependency still needs a version. +allow-wildcard-paths = true # No `deny` entry for `h2 <0.4.16` (RUSTSEC-2026-0258): cargo-deny's graph # builder drops that crate before any check runs (`-L debug` logs # `filtered h2 0.3.27` with `actix-web/http2` enabled, on 0.19 and 0.20), diff --git a/enums/Cargo.toml b/enums/Cargo.toml index 55ceac187..fc8163a59 100644 --- a/enums/Cargo.toml +++ b/enums/Cargo.toml @@ -16,6 +16,9 @@ version = "2.4.0" publish = false authors = ["Calixte Denizet "] edition = "2024" +# The repository's licence, stated so cargo-deny's licence check has an +# expression to read (#1823); without one it rejects the crate as unlicensed. +license = "MPL-2.0" [dependencies] clap = { version = "^4.0", features = ["derive"] } diff --git a/utils/check-deny-manifests-test.py b/utils/check-deny-manifests-test.py new file mode 100644 index 000000000..8cc068b73 --- /dev/null +++ b/utils/check-deny-manifests-test.py @@ -0,0 +1,300 @@ +#!/usr/bin/env python3 +"""Tests for check-deny-manifests.sh (#1823). + +Each test stages a scratch git repository holding a copy of the script, +a `deny.toml`, and one fixture `Cargo.toml` / `Cargo.lock` pair per +crate directory the live tree tracks a lockfile for. A stub +`cargo-deny` first on PATH answers `--version` and records every other +invocation's argv, so nothing reaches the network or a real cargo-deny. +The script is run from an unrelated directory, so every test also pins +that its paths resolve from its own location rather than the cwd. + +This is the only verification `make pre-commit` runs: the real gate +needs the network and runs in the `deny` jobs of `ci.yml` and +`deny-advisories.yml`. + +Run with: + python3 -m unittest -q utils/check-deny-manifests-test.py +""" + +from __future__ import annotations + +import json +import os +import pathlib +import re +import shutil +import subprocess +import sys +import tempfile +import unittest + +UTILS_DIR = pathlib.Path(__file__).resolve().parent +REPO_ROOT = UTILS_DIR.parent +SCRIPT_SRC = UTILS_DIR / "check-deny-manifests.sh" + +# The directories whose `Cargo.lock` the live tree tracks; "" is the root. +# `test_live_tree_tracks_exactly_these_lockfiles` holds this list to the +# tree, so the fixture cannot drift from what the gate really audits. +CRATE_DIRS = ( + "", + "enums", + "fuzz", + "tree-sitter-ccomment", + "tree-sitter-mozcpp", + "tree-sitter-mozjs", + "tree-sitter-preproc", + "tree-sitter-tcl", +) +ALL_CHECKS = ("advisories", "bans", "licenses", "sources") + +# Exits 4 for the manifest `STUB_DENY_FAIL` names, the bit cargo-deny +# sets for a failed licences check; any non-zero status is a failure to +# the script, so the value only has to differ from 0. +STUB_SOURCE = """\ +#!{python} +import json, os, sys +args = sys.argv[1:] +if args == ["--version"]: + print("cargo-deny " + os.environ.get("STUB_DENY_VERSION", "0.20.2")) + sys.exit(0) +with open(os.environ["STUB_DENY_LOG"], "a", encoding="utf-8") as log: + log.write(json.dumps(args) + "\\n") +manifest = args[args.index("--manifest-path") + 1] +sys.exit(4 if manifest == os.environ.get("STUB_DENY_FAIL") else 0) +""" + + +def _git_env() -> dict[str, str]: + """The caller's environment with its git configuration shut out.""" + env = os.environ.copy() + env["GIT_CONFIG_GLOBAL"] = os.devnull + env["GIT_CONFIG_NOSYSTEM"] = "1" + return env + + +def _manifest_rel(crate_dir: str) -> str: + return f"{crate_dir}/Cargo.toml" if crate_dir else "Cargo.toml" + + +class DenyManifestsTest(unittest.TestCase): + def setUp(self) -> None: + self.tmp = pathlib.Path(tempfile.mkdtemp(prefix="bca-deny-manifests-")) + self.repo = self.tmp / "repo" + self.elsewhere = self.tmp / "elsewhere" + self.elsewhere.mkdir() + self.log = self.tmp / "invocations.jsonl" + + stub_dir = self.tmp / "stub-bin" + stub_dir.mkdir() + stub = stub_dir / "cargo-deny" + stub.write_text(STUB_SOURCE.format(python=sys.executable), encoding="utf-8") + stub.chmod(0o755) + self.env = _git_env() + self.env["PATH"] = f"{stub_dir}{os.pathsep}{self.env['PATH']}" + self.env["STUB_DENY_LOG"] = str(self.log) + + # The script derives its root as the parent of its own directory, + # so the copy sits in `repo/utils/` for `repo` to stand in for it. + (self.repo / "utils").mkdir(parents=True) + self.script = self.repo / "utils" / SCRIPT_SRC.name + shutil.copy(SCRIPT_SRC, self.script) + (self.repo / "deny.toml").write_text("[graph]\n", encoding="utf-8") + for crate_dir in CRATE_DIRS: + self._add_crate(crate_dir) + self._git("init", "-q") + self._git("add", "--", ".") + + def tearDown(self) -> None: + shutil.rmtree(self.tmp, ignore_errors=True) + + # --- helpers --- + + def _add_crate(self, crate_dir: str) -> None: + directory = self.repo / crate_dir + directory.mkdir(parents=True, exist_ok=True) + name = crate_dir or "root" + (directory / "Cargo.toml").write_text( + f'[package]\nname = "{name}"\n', encoding="utf-8" + ) + (directory / "Cargo.lock").write_text("version = 4\n", encoding="utf-8") + + def _git(self, *args: str) -> None: + subprocess.run( + ["git", "-C", str(self.repo), *args], + env=self.env, + check=True, + capture_output=True, + ) + + def _run( + self, *checks: str, script: pathlib.Path | None = None, **env: str + ) -> subprocess.CompletedProcess[str]: + return subprocess.run( + ["bash", str(script or self.script), *checks], + cwd=self.elsewhere, + env={**self.env, **env}, + capture_output=True, + text=True, + check=False, + ) + + def _invocations(self) -> list[list[str]]: + if not self.log.exists(): + return [] + lines = self.log.read_text(encoding="utf-8").splitlines() + return [json.loads(line) for line in lines] + + @staticmethod + def _manifest_of(argv: list[str]) -> str: + return argv[argv.index("--manifest-path") + 1] + + def _expected_manifests(self, root: pathlib.Path) -> list[str]: + return sorted(str(root / _manifest_rel(d)) for d in CRATE_DIRS) + + # --- coverage: every manifest, every check --- + + def test_runs_every_check_against_every_manifest(self) -> None: + result = self._run(*ALL_CHECKS) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn("OK (8 manifests", result.stdout) + calls = self._invocations() + self.assertEqual( + sorted(self._manifest_of(argv) for argv in calls), + self._expected_manifests(self.repo), + ) + deny_toml = str(self.repo / "deny.toml") + for argv in calls: + with self.subTest(manifest=self._manifest_of(argv)): + self.assertEqual(argv[-5:], ["check", *ALL_CHECKS]) + # One shared config, by absolute path, ahead of `check`: + # cargo-deny 0.20 rejects `check --config`. + config_at = argv.index("--config") + self.assertEqual(argv[config_at + 1], deny_toml) + self.assertLess(config_at, argv.index("check")) + self.assertIn("--locked", argv[: argv.index("check")]) + + def test_checks_are_forwarded_not_hard_coded(self) -> None: + # The weekly job asks for advisories alone. A script that ignored + # its arguments and always ran all four would pass the test above. + result = self._run("advisories") + self.assertEqual(result.returncode, 0, result.stderr) + calls = self._invocations() + self.assertEqual(len(calls), len(CRATE_DIRS)) + for argv in calls: + self.assertEqual(argv[-2:], ["check", "advisories"]) + + # --- the lockfile count --- + + def test_ninth_lockfile_fails_before_any_check_runs(self) -> None: + self._add_crate("tree-sitter-new") + self._git("add", "--", "tree-sitter-new") + result = self._run(*ALL_CHECKS) + self.assertEqual(result.returncode, 1, result.stderr) + self.assertIn("expected 8 tracked Cargo.lock files, found 9", result.stderr) + self.assertIn("tree-sitter-new/Cargo.lock", result.stderr) + self.assertIn("EXPECTED_LOCKFILES", result.stderr) + self.assertEqual(self._invocations(), []) + + def test_dropped_lockfile_fails(self) -> None: + self._git("rm", "-q", "--cached", "--", "tree-sitter-tcl/Cargo.lock") + result = self._run(*ALL_CHECKS) + self.assertEqual(result.returncode, 1, result.stderr) + self.assertIn("expected 8 tracked Cargo.lock files, found 7", result.stderr) + self.assertEqual(self._invocations(), []) + + def test_untracked_lockfile_is_not_counted(self) -> None: + # A build tree or a corpus checkout carries lockfiles nobody ships; + # the count is of what git tracks, not of what is on disk. + stray = self.repo / "target" / "package" / "Cargo.lock" + stray.parent.mkdir(parents=True) + stray.write_text("version = 4\n", encoding="utf-8") + result = self._run("advisories") + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(len(self._invocations()), len(CRATE_DIRS)) + + def test_lookalike_file_name_is_not_counted(self) -> None: + # `*Cargo.lock` as a pathspec would match this; the gate must not. + lookalike = self.repo / "docs" / "NotCargo.lock" + lookalike.parent.mkdir() + lookalike.write_text("", encoding="utf-8") + self._git("add", "--", "docs/NotCargo.lock") + result = self._run("advisories") + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(len(self._invocations()), len(CRATE_DIRS)) + + # --- failure propagation --- + + def test_one_failing_manifest_fails_the_gate_and_the_rest_still_run(self) -> None: + failing = str(self.repo / "fuzz" / "Cargo.toml") + result = self._run(*ALL_CHECKS, STUB_DENY_FAIL=failing) + self.assertEqual(result.returncode, 1, result.stderr) + self.assertIn("failed for 1 of 8 manifests", result.stderr) + self.assertIn(" fuzz/Cargo.toml", result.stderr) + self.assertNotIn("check-deny-manifests: OK", result.stdout) + # Every graph is still audited, so one red run reports them all. + self.assertEqual(len(self._invocations()), len(CRATE_DIRS)) + + # --- preconditions --- + + def test_no_checks_is_a_usage_error(self) -> None: + result = self._run() + self.assertEqual(result.returncode, 2, result.stderr) + self.assertIn("name the checks to run", result.stderr) + self.assertEqual(self._invocations(), []) + + def test_cargo_deny_older_than_0_20_is_refused(self) -> None: + result = self._run(*ALL_CHECKS, STUB_DENY_VERSION="0.19.4") + self.assertEqual(result.returncode, 2, result.stderr) + self.assertIn("cargo-deny 0.19.4 is older than 0.20", result.stderr) + self.assertEqual(self._invocations(), []) + + def test_cargo_deny_with_a_newer_major_is_accepted(self) -> None: + # Pins the comparison itself: a check on the minor alone would + # refuse 1.0. + result = self._run("advisories", STUB_DENY_VERSION="1.0.0") + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(len(self._invocations()), len(CRATE_DIRS)) + + # --- the live tree --- + + def test_live_tree_tracks_exactly_these_lockfiles(self) -> None: + # The live script against the live tree, stub still first on PATH. + # A ninth excluded crate fails here, under `make pre-commit`, and + # not first in CI's `deny` job. + result = self._run("advisories", script=SCRIPT_SRC) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual( + sorted(self._manifest_of(argv) for argv in self._invocations()), + self._expected_manifests(REPO_ROOT), + ) + + +class WorkflowWiringTest(unittest.TestCase): + """Both `deny` jobs go through the script, on one cargo-deny.""" + + WORKFLOWS = ("ci.yml", "deny-advisories.yml") + PIN = re.compile(r"cargo-deny@(\d+\.\d+\.\d+)") + + def test_both_workflows_call_the_script_on_one_pinned_cargo_deny(self) -> None: + # A workflow left on `cargo-deny-action`, or one that stops calling + # the script, audits the root lockfile alone again — the gap #1823 + # closed — and nothing else would notice. + pins: dict[str, set[str]] = {} + for name in self.WORKFLOWS: + text = (REPO_ROOT / ".github" / "workflows" / name).read_text( + encoding="utf-8" + ) + with self.subTest(workflow=name): + self.assertIn("./utils/check-deny-manifests.sh ", text) + self.assertNotIn("cargo-deny-action@", text) + pins[name] = set(self.PIN.findall(text)) + self.assertEqual(len(pins[name]), 1, pins[name]) + self.assertEqual(pins["ci.yml"], pins["deny-advisories.yml"]) + # The script's install hint names the same release. + hinted = set(self.PIN.findall(SCRIPT_SRC.read_text(encoding="utf-8"))) + self.assertEqual(hinted, pins["ci.yml"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/utils/check-deny-manifests.sh b/utils/check-deny-manifests.sh new file mode 100755 index 000000000..74dd122b2 --- /dev/null +++ b/utils/check-deny-manifests.sh @@ -0,0 +1,123 @@ +#!/bin/bash +# check-deny-manifests +# +# Runs `cargo-deny check ` once per tracked `Cargo.lock`, against +# the root `deny.toml`. Usage: +# +# utils/check-deny-manifests.sh advisories bans licenses sources +# +# The repository tracks eight lockfiles: the root workspace's and one per +# `[workspace].exclude` crate (`enums`, `fuzz`, the five `tree-sitter-*`), +# each of which roots its own workspace and resolves its own graph. A +# cargo-deny run from the root reads only the first. Until #1823 the other +# seven were read by the Scorecard job alone, on `main`, after merge: +# RUSTSEC-2026-0374 sat in `enums/Cargo.lock` that way and passed every +# PR's `deny` job (fixed by #1822). +# +# Both `deny` jobs call this script (`.github/workflows/ci.yml` and +# `.github/workflows/deny-advisories.yml`), so the per-PR and the weekly +# run cannot disagree on which graphs they cover. `make pre-commit` runs +# only its self-test, `utils/check-deny-manifests-test.py`, which drives +# it against a stubbed cargo-deny: the real run needs the network. + +set -euo pipefail + +# The parent of `utils/`, from this script's own location, so the gate +# reads the tree it was invoked from whatever the caller's cwd. +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" + +# The root lockfile plus the seven excluded crates'. A lockfile that +# appears or disappears fails the gate until this number is changed by +# hand, so a ninth excluded crate cannot enter the tree unaudited — the +# reasoning `utils/check-excluded-manifests.py` applies to the manifests +# themselves (#1151, #1228). +EXPECTED_LOCKFILES=8 + +# cargo-deny 0.20 moved `--config` from the `check` subcommand to the top +# level, and each side rejects the other's spelling. CI pins a 0.20 +# release through `taiki-e/install-action`; an older local copy fails +# here, with the remedy, rather than with clap's tip to move the flag +# back. The install hints below name CI's exact pin, and +# `utils/check-deny-manifests-test.py` holds them to it. +MIN_DENY_MAJOR=0 +MIN_DENY_MINOR=20 + +die() { + echo "check-deny-manifests: $*" >&2 + exit 2 +} + +if [ "$#" -eq 0 ]; then + die "name the checks to run, e.g. 'advisories bans licenses sources'" +fi + +# Called directly rather than as `cargo deny`: cargo resolves a +# subcommand from `$CARGO_HOME/bin` before PATH, which would put an +# installed copy ahead of the one PATH names (and of the self-test's stub). +if ! version_line=$(cargo-deny --version 2>/dev/null); then + die "cargo-deny not found; install the version CI pins:" \ + "cargo install --locked cargo-deny@0.20.2" +fi +version=${version_line##* } +major=${version%%.*} +minor=${version#*.} +minor=${minor%%.*} +if ! [[ "$major" =~ ^[0-9]+$ && "$minor" =~ ^[0-9]+$ ]]; then + die "cannot read a version from '$version_line'" +fi +if [ "$major" -eq "$MIN_DENY_MAJOR" ] && [ "$minor" -lt "$MIN_DENY_MINOR" ]; then + die "cargo-deny $version is older than $MIN_DENY_MAJOR.$MIN_DENY_MINOR," \ + "which this script's '--config' placement needs; install CI's pin:" \ + "cargo install --locked cargo-deny@0.20.2" +fi + +# The tracked set, not the filesystem: corpora, `target/` and scratch +# checkouts carry lockfiles nobody ships. `**/` also matches the root, +# and the glob pathspec keeps `NotCargo.lock` out, which `*Cargo.lock` +# would not. +if ! listing=$(git -C "$ROOT" ls-files -- ':(glob)**/Cargo.lock'); then + die "git ls-files failed in $ROOT; this gate reads the tracked lockfiles" +fi +locks=() +while IFS= read -r lock; do + if [ -n "$lock" ]; then + locks+=("$lock") + fi +done <<<"$listing" + +if [ "${#locks[@]}" -ne "$EXPECTED_LOCKFILES" ]; then + { + echo "check-deny-manifests: expected $EXPECTED_LOCKFILES tracked Cargo.lock files, found ${#locks[@]}:" + # The `+` form: an empty array is unbound under `set -u` before bash 4.4. + printf ' %s\n' ${locks[@]+"${locks[@]}"} + echo "An excluded crate was added or removed. Run this script with every" + echo "check against the new set, then change EXPECTED_LOCKFILES in" + echo "utils/check-deny-manifests.sh to match." + } >&2 + exit 1 +fi + +failed=() +for lock in "${locks[@]}"; do + manifest="${lock%Cargo.lock}Cargo.toml" + echo "==> cargo-deny check $*: $manifest" + # `--locked` audits the committed lockfile rather than a graph cargo + # re-resolved on the way, and refuses to rewrite a tracked lockfile + # when the script runs in a working tree. + if ! cargo-deny --locked \ + --manifest-path "$ROOT/$manifest" \ + --config "$ROOT/deny.toml" \ + check "$@"; then + failed+=("$manifest") + fi +done + +if [ "${#failed[@]}" -gt 0 ]; then + { + echo "check-deny-manifests: cargo-deny failed for ${#failed[@]} of ${#locks[@]} manifests:" + printf ' %s\n' "${failed[@]}" + } >&2 + exit 1 +fi + +echo "check-deny-manifests: OK (${#locks[@]} manifests: $*)" From 2f980ab96d8941edb5b69477620d0710fe82c2f3 Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Thu, 5 Nov 2026 21:00:17 -0800 Subject: [PATCH 03/25] docs(deny): name git deps in the wildcard exemption allow-wildcard-paths exempts path or git dependencies of a private crate, and path or git dev-dependencies of any crate, per the cargo-deny 0.20 book; the comment named path dependencies only. Note that a git source still has to pass the [sources] gate. Refs #1823 --- deny.toml | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/deny.toml b/deny.toml index 258abde33..c3ed93211 100644 --- a/deny.toml +++ b/deny.toml @@ -58,8 +58,9 @@ multiple-versions = "warn" wildcards = "deny" # `fuzz` takes `big-code-analysis` by path with no version, deliberately (see # `fuzz/Cargo.toml`), and cargo-deny reads that as a wildcard. This exempts a -# path dependency only in a `publish = false` crate, plus path dev-deps, which -# crates.io strips; a published crate's path dependency still needs a version. +# path or git dependency only in a `publish = false` crate, plus path or git +# dev-deps, which crates.io strips; a published crate's still needs a version. +# A git source must also pass `[sources]` below, which denies unknown ones. allow-wildcard-paths = true # No `deny` entry for `h2 <0.4.16` (RUSTSEC-2026-0258): cargo-deny's graph # builder drops that crate before any check runs (`-L debug` logs From f2cb74fbfc7bc2cf66a6aa38b26df70eb1503386 Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Thu, 5 Nov 2026 21:17:28 -0800 Subject: [PATCH 04/25] docs(nargs): name the average-below-min exception NArgs' extrema fold every space's own count on each channel, the file unit and containers included, while its averages divide by the functions and closures nom counts. A lambda that opens no space adds its parameters to the enclosing function's own closure_args (one extrema member) yet is one closure of the divisor, so closure_args_average can fall below closure_args_min; and file-level function_args_min is always 0. Document both in the Stats type docs, a new NArgs subsection in the book (#nargs-aggregates), the cyclomatic aggregate-population passage, and the Python Dependencies paragraph. The definition stays as it is; changing it moves integration snapshots. The loc sibling is #1827. Fixes #1809 --- big-code-analysis-book/src/metrics.md | 52 +++++++++++++++++--- big-code-analysis-book/src/python/metrics.md | 10 ++-- src/metrics/nargs.rs | 26 ++++++++++ 3 files changed, 77 insertions(+), 11 deletions(-) diff --git a/big-code-analysis-book/src/metrics.md b/big-code-analysis-book/src/metrics.md index 65cfaa9a4..3684fc2ab 100644 --- a/big-code-analysis-book/src/metrics.md +++ b/big-code-analysis-book/src/metrics.md @@ -586,14 +586,13 @@ Two things are deliberately *not* in that population: could report `average 7.0` against `min 14, max 14`. The same three fields on `cognitive` and `nexits` follow this rule; -`sum` on all three keeps its all-spaces meaning. [NArgs](#nargs) keeps -its own two channels — `function_args_average` and -`closure_args_average` divide each channel's argument total by the -number of functions or closures [NOM](#nom) counts, spaceless lambdas -included, and `average` divides the combined total by their sum — so -it does not follow the function-space population rule (#1809). The remaining metrics' -`*_average` / `*_min` / `*_max` fields are per-space averages over -every space in the subtree, as their sections say. +`sum` on all three keeps its all-spaces meaning. +[NArgs](#nargs-aggregates) does not follow it: its extrema fold every +space and its averages divide by the function and closure counts of +[NOM](#nom), so `closure_args_average` can fall below +`closure_args_min` (#1809). The remaining metrics' `*_average` / +`*_min` / `*_max` fields are per-space averages over every space in +the subtree, as their sections say. ### Modified cyclomatic @@ -1697,6 +1696,43 @@ second when none is (`closures_that_open_a_space_are_what_the_book_says` in `big-code-analysis-ast/src/roles/space_tree_tests.rs` pins the two against this paragraph; Bash, C, Tcl and iRules have no closure at all). +### Averages, minimums and maximums {#nargs-aggregates} + +NArgs does not follow the +[aggregate population](#aggregate-population) rule of cyclomatic, +cognitive and NExits. Its extrema and its averages count different +things: + +- `function_args_min` / `function_args_max` and `closure_args_min` / + `closure_args_max` fold each space's own count on that channel, over + every space in the subtree. A space that declares no parameters on a + channel folds a 0 into that channel's minimum. The file unit and + containers declare none, so their `function_args_min` is always 0. +- `function_args_average` and `closure_args_average` divide the + channel's argument total by the number of functions or closures + [NOM](#nom) counts. `average` divides the combined total by their + sum. + +Read the extrema per space and the averages per callable. The two +disagree in the languages whose lambdas open no space, the second list +under [What the threshold gate measures](#nargs-gate). There a +lambda's parameters add to the enclosing function's own +`closure_args`, one member of the extrema, while NOM counts the lambda +as one closure of the divisor. A function holding several such lambdas +can report a `closure_args_average` below its `closure_args_min`: + +```python +def pick(rows): + a = sorted(rows, key=lambda r: r[0]) + b = filter(lambda r: r[1], a) + c = map(lambda r: r[2], b) + return min(c, key=lambda r: r) +``` + +`pick` reports `closure_args_min 4`, `closure_args_max 4` and +`closure_args_average 1.0`: four parameters over four closures, all +held by one space. + ### Languages where it reads 0 {#nargs-language-gaps} A metric that silently reports 0 reads as "no offenders" rather than diff --git a/big-code-analysis-book/src/python/metrics.md b/big-code-analysis-book/src/python/metrics.md index 974c1e467..2c7446274 100644 --- a/big-code-analysis-book/src/python/metrics.md +++ b/big-code-analysis-book/src/python/metrics.md @@ -75,9 +75,13 @@ Duplicates are silently collapsed. Selecting a metric that reads another metric's result computes that one too. `nargs` divides its per-channel averages by the function and -closure counts `nom` supplies; `cognitive` and `nexits` count their -own function spaces but still pull `nom` in, so a selection naming -either returns the same blocks it always did. +closure counts `nom` supplies. A `lambda` is one of those closures +but opens no space, so its parameters fold into the enclosing +function's own `closure_args` and `closure_args_average` can fall +below `closure_args_min` (see [NArgs](../metrics.md#nargs-aggregates)). +`cognitive` and `nexits` count their own function spaces but still +pull `nom` in, so a selection naming either returns the same blocks it +always did. | Metric | JSON key | Dependencies pulled in | |--------|----------|------------------------| diff --git a/src/metrics/nargs.rs b/src/metrics/nargs.rs index 4499ff19f..3005d848a 100644 --- a/src/metrics/nargs.rs +++ b/src/metrics/nargs.rs @@ -28,6 +28,21 @@ use crate::*; /// /// This metric counts the number of arguments /// of functions/closures. +/// +/// Unlike the per-function fields of cyclomatic, cognitive and nexits +/// (#1284), the extrema and the averages here read different +/// populations (#1809): +/// +/// - `*_min` / `*_max` fold every space's own count on the channel, so a +/// space declaring none folds a 0. The file unit and containers +/// declare none, so their [`function_args_min`](Self::function_args_min) +/// is always 0. +/// - `*_average` divides the channel's subtree total by the functions or +/// closures `nom` counts. A lambda that opens no space (Python, Java, +/// C++, …) adds its parameters to the enclosing function's own +/// `closure_args` yet is one closure to `nom`, so a function holding +/// four one-parameter lambdas reports `closure_args_min` 4 and +/// [`closure_args_average`](Self::closure_args_average) 1.0. #[derive(Debug, Clone, PartialEq)] #[non_exhaustive] pub struct Stats { @@ -126,6 +141,9 @@ impl Stats { } /// Returns the average number of closures arguments in a space. + /// + /// Divides by the closures `nom` counts, so it can fall below + /// [`closure_args_min`](Self::closure_args_min); see [`Stats`]. #[inline] #[must_use] pub fn closure_args_average(&self) -> f64 { @@ -175,6 +193,9 @@ impl Stats { /// Collapses the `usize::MAX` sentinel that `Stats::default()` plants /// into `fn_nargs_min` to `0.0`, so a never-observed space /// serializes to a meaningful number rather than `1.8446744e19`. + /// + /// Folds every space in the subtree, so it is 0 on the file unit and + /// on every container; see [`Stats`]. #[inline] #[must_use] pub fn function_args_min(&self) -> u64 { @@ -213,6 +234,11 @@ impl Stats { self.closure_nargs_sum += self.closure_nargs; self.fn_nargs_sum += self.fn_nargs; } + /// Folds this space's own counts into both channels' extrema, + /// whatever its kind. Gating the function channel on + /// `SpaceKind::Function`, as cyclomatic does, would change file-level + /// `function_args_min`, now always 0: a definition change #1809 left + /// open. #[inline] pub(crate) fn compute_minmax(&mut self) { self.closure_nargs_min = self.closure_nargs_min.min(self.closure_nargs); From dbfdcbcbb73dd410d4a89f47e537ef1540c256b6 Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Thu, 5 Nov 2026 21:20:21 -0800 Subject: [PATCH 05/25] docs(book): drop a restating NArgs sentence Refs #1809 --- big-code-analysis-book/src/metrics.md | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/big-code-analysis-book/src/metrics.md b/big-code-analysis-book/src/metrics.md index 3684fc2ab..36112c990 100644 --- a/big-code-analysis-book/src/metrics.md +++ b/big-code-analysis-book/src/metrics.md @@ -1713,9 +1713,8 @@ things: [NOM](#nom) counts. `average` divides the combined total by their sum. -Read the extrema per space and the averages per callable. The two -disagree in the languages whose lambdas open no space, the second list -under [What the threshold gate measures](#nargs-gate). There a +The two disagree in the languages whose lambdas open no space, the +second list under [What the threshold gate measures](#nargs-gate). There a lambda's parameters add to the enclosing function's own `closure_args`, one member of the extrema, while NOM counts the lambda as one closure of the divisor. A function holding several such lambdas From 19dbf0e07dc09a8b018ce77d999c36d6208da72d Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Thu, 5 Nov 2026 21:22:05 -0800 Subject: [PATCH 06/25] perf(ast): read Doxygen conditionals by kind id `preproc_conditional` compared five `kind()` strings, and `conditional_declares` asked it up to three times of each non-conditional child: in the push filter, in the expansion and inside `doxygen_entry`. Each C-family dialect now has `is_preproc_conditional_kind` beside its table: the `DocTarget` row's conditional owners as a kind test, which `doc_target::lists_kind` cannot give, as the row also lists the entries. `DoxygenRow::conditional_kind` binds it per dialect, and `preproc_conditional`, `doxygen_container` and `doxygen_binds_forward` take the dialect. The two kind lists sit beside the two conditional fragments rather than being shared through a callback the `role_tables.py` fragment reader cannot follow, so the role-table gates read the rows exactly as before; a per-dialect test holds each list to the old conditional names over every runtime id. `conditional_declares` now classifies each child once, when its conditional is read: a nested conditional is queued or answered from the memo, any other child is asked the entry question there, and each nested answer is folded into its parent's. A new test pins the fold on shapes that tell it from an overwrite, which no existing test did. Fixes #1795 --- .../src/checker/doxygen_doc_binding.rs | 9 +- .../src/lang_helpers/doc_comment.rs | 2 +- .../src/lang_helpers/doxygen.rs | 217 +++++++++++++----- big-code-analysis-ast/src/roles/c.rs | 8 +- big-code-analysis-ast/src/roles/c_family.rs | 57 ++++- big-code-analysis-ast/src/roles/cpp.rs | 12 +- .../src/roles/doc_tests/doxygen.rs | 58 ++++- big-code-analysis-ast/src/roles/mozcpp.rs | 12 +- big-code-analysis-ast/src/roles/objc.rs | 4 +- 9 files changed, 302 insertions(+), 77 deletions(-) diff --git a/big-code-analysis-ast/src/checker/doxygen_doc_binding.rs b/big-code-analysis-ast/src/checker/doxygen_doc_binding.rs index 66d69e5c1..43e5bcee5 100644 --- a/big-code-analysis-ast/src/checker/doxygen_doc_binding.rs +++ b/big-code-analysis-ast/src/checker/doxygen_doc_binding.rs @@ -34,8 +34,9 @@ macro_rules! impl_doxygen_doc_binding { }; } -// The row each dialect's Doxygen helpers read targets through; one impl -// per dialect beside its `impl Checker`, which the macro above composes. +// The row each dialect's Doxygen helpers read targets through, and its +// conditional owners as a kind test; one impl per dialect beside its +// `impl Checker`, which the macro above composes. macro_rules! impl_doxygen_row { ($code:ident, $roles:ident) => { impl $crate::lang_helpers::doxygen::DoxygenRow for $code { @@ -48,6 +49,10 @@ macro_rules! impl_doxygen_row { ); $crate::roles::$roles::doc_target::owns(node, code, ancestors) } + + fn conditional_kind(kind: u16) -> bool { + $crate::roles::$roles::is_preproc_conditional_kind(kind) + } } }; } 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 957637a86..6dc093804 100644 --- a/big-code-analysis-ast/src/lang_helpers/doc_comment.rs +++ b/big-code-analysis-ast/src/lang_helpers/doc_comment.rs @@ -811,7 +811,7 @@ mod tests { .expect("recovery leaves an ERROR under the root"); let nested = error .children() - .filter(|child| crate::lang_helpers::doxygen::preproc_conditional(child)) + .filter(|child| crate::lang_helpers::doxygen::preproc_conditional::(child)) .count(); assert_eq!( nested, 1, diff --git a/big-code-analysis-ast/src/lang_helpers/doxygen.rs b/big-code-analysis-ast/src/lang_helpers/doxygen.rs index 05f6dc667..ee8f8a4ce 100644 --- a/big-code-analysis-ast/src/lang_helpers/doxygen.rs +++ b/big-code-analysis-ast/src/lang_helpers/doxygen.rs @@ -253,15 +253,14 @@ fn doxygen_command(s: &[u8], at: usize) -> Option<&[u8]> { (!mail).then(|| &rest[..len]) } -/// A preprocessor conditional or one of its branches, in every C-family -/// grammar and every alias of the rule: the nodes Doxygen's preprocessor -/// reads through to the declarations inside. +/// A preprocessor conditional or one of its branches, under any alias of +/// the rule: the nodes Doxygen's preprocessor reads through to the +/// declarations inside. Read by id from the dialect's `DocTarget` +/// conditional owners ([`DoxygenRow::conditional_kind`]), since the four +/// grammars number them differently (#1795). #[must_use] -pub(crate) fn preproc_conditional(node: &Node) -> bool { - matches!( - node.kind(), - "preproc_if" | "preproc_ifdef" | "preproc_else" | "preproc_elif" | "preproc_elifdef" - ) +pub(crate) fn preproc_conditional(node: &Node) -> bool { + T::conditional_kind(node.kind_id()) } // Each conditional `conditional_declares` reads the children of. The memo @@ -291,37 +290,73 @@ pub(crate) fn conditional_declares(node: &Node, ancestors: Ancest if let Some(answer) = memo.get(node) { return answer; } - // Post-order: a conditional is answered once its nested ones are. - let mut stack = vec![(*node, false)]; - while let Some((conditional, expanded)) = stack.pop() { - if memo.get(&conditional).is_some() { - continue; - } - if expanded { - conditionals_read::record(); - let parent = [conditional]; - let below = chain_below(ancestors, &parent); - let declares = conditional.children().any(|child| { - if preproc_conditional(&child) { - memo.get(&child) == Some(true) - } else { - doxygen_entry::(&child, below) + // Post-order: a conditional's answer is complete once each nested one + // has folded its own in. `answers[i]` holds the answer, so far, of the + // `i`th conditional read. + let mut answers = Vec::new(); + let mut stack = vec![Visit::Read(*node, None)]; + while let Some(visit) = stack.pop() { + match visit { + Visit::Read(conditional, outer) => { + conditionals_read::record(); + let own = answers.len(); + stack.push(Visit::Answer(conditional, outer, own)); + answers.push(children_declare::( + &conditional, + ancestors, + memo, + |nested| stack.push(Visit::Read(nested, Some(own))), + )); + } + Visit::Answer(conditional, outer, own) => { + memo.set(&conditional, answers[own]); + if let Some(outer) = outer { + answers[outer] |= answers[own]; } - }); - memo.set(&conditional, declares); - continue; + } } - stack.push((conditional, true)); - stack.extend( - conditional - .children() - .filter(|child| preproc_conditional(child) && memo.get(child).is_none()) - .map(|child| (child, false)), - ); } memo.get(node) == Some(true) } +/// A step of [`conditional_declares`]'s walk over a nest. The `Option` is +/// the enclosing conditional's index in the walk's `answers`, `None` for +/// the conditional asked about; an `Answer` carries its own index too. +enum Visit<'a> { + /// Read the conditional's children ([`children_declare`]). + Read(Node<'a>, Option), + /// Store the conditional's answer, every nested one folded in by now, + /// and fold it into the enclosing conditional's. + Answer(Node<'a>, Option, usize), +} + +/// Whether a child of `conditional` already answers +/// [`conditional_declares`] for it: an entry, or a nested conditional +/// the memo answers `true` for. Each nested conditional the memo has no +/// answer for is handed to `defer`, so the walk reads it and folds its +/// answer in later. Each child is classified once, here (#1795). +fn children_declare<'a, T: DoxygenRow>( + conditional: &Node<'a>, + ancestors: Ancestors<'a, '_>, + memo: &NodeMemo, + mut defer: impl FnMut(Node<'a>), +) -> bool { + let parent = [*conditional]; + let below = chain_below(ancestors, &parent); + let mut declares = false; + for child in conditional.children() { + if T::conditional_kind(child.kind_id()) { + match memo.get(&child) { + Some(answer) => declares |= answer, + None => defer(child), + } + } else if !declares { + declares = non_conditional_entry::(&child, below); + } + } + declares +} + /// The context a conditional's children are asked with: a chain of one /// entry, the conditional itself, so a gate reading `parent` takes the /// conditional and not the nest's parent — with the walk's fold cache @@ -361,8 +396,8 @@ fn chain_below<'a, 'c>( /// the grammars read Apple's `typedef NS_ENUM(…) { … }` as one, and there /// each doc comment documents an enumerator. #[must_use] -pub(crate) fn doxygen_container(node: &Node) -> bool { - preproc_conditional(node) +pub(crate) fn doxygen_container(node: &Node) -> bool { + preproc_conditional::(node) || matches!( node.kind(), "translation_unit" @@ -398,7 +433,7 @@ pub(crate) fn doxygen_skips(node: &Node, ancestors: Ancestors) -> | ";" => true, "expression_statement" => !statement_is_macro_call(node), "ERROR" => no_entry_inside::(node, ancestors), - _ => preproc_conditional(node) && !conditional_declares::(node, ancestors), + _ => preproc_conditional::(node) && !conditional_declares::(node, ancestors), } } @@ -470,14 +505,14 @@ pub(crate) fn doxygen_target<'a, T: DoxygenRow>( /// holding an entry. The conditional test comes *first*, so a /// conditional is no entry here whatever it holds and the row's /// `conditional_declares` gate is never reached through this fn — -/// [`conditional_declares`]'s own post-order walk asks this of a -/// conditional's non-conditional children only and reads its memo for -/// the rest, so the two defences are independent and either alone -/// keeps the walk from re-entering itself. Code the grammar could not parse, -/// often behind a macro Doxygen's preprocessor would expand, is given -/// the benefit of the doubt, as before #1613, rather than dropping the -/// block on a parse failure; an error holding no entry is read past -/// (`doxygen_skips`). +/// [`conditional_declares`]'s own post-order walk asks the entry question +/// ([`non_conditional_entry`]) of a conditional's non-conditional +/// children only and reads its memo for the rest, so the two defences are +/// independent and either alone keeps the walk from re-entering itself. +/// Code the grammar could not parse, often behind a macro Doxygen's +/// preprocessor would expand, is given the benefit of the doubt, as +/// before #1613, rather than dropping the block on a parse failure; an +/// error holding no entry is read past (`doxygen_skips`). /// /// The row is asked with no bytes, which is exact because no C-family /// `DocTarget` gate reads any — `impl_doxygen_row!` in @@ -489,21 +524,33 @@ pub(crate) fn doxygen_target<'a, T: DoxygenRow>( /// hand-writes a byte-reading `is_doc_target` would otherwise slip past /// the row's assertion. fn doxygen_entry(node: &Node, ancestors: Ancestors) -> bool { + !preproc_conditional::(node) && non_conditional_entry::(node, ancestors) +} + +/// [`doxygen_entry`] of a node its caller has already found is no +/// conditional: the row, or a parse error holding an entry (an `ERROR` +/// is never a conditional kind). +fn non_conditional_entry(node: &Node, ancestors: Ancestors) -> bool { if node.is_error() { return !no_entry_inside::(node, ancestors); } - !preproc_conditional(node) && T::doc_target_row(node, &[], ancestors) + T::doc_target_row(node, &[], ancestors) } -/// The `DocTarget` row of a C-family dialect, as the one function the -/// Doxygen helpers read targets through; implemented by -/// `impl_doxygen_row!` (`checker/doxygen_doc_binding.rs`) beside the -/// Checker that composes it. Only the row: no helper bounded on this -/// reads a `Checker` method, so a `Checker` supertrait would be a bound -/// nothing uses. +/// The `DocTarget` row of a C-family dialect, and its conditional owners +/// as a kind test, as the functions the Doxygen helpers read targets and +/// conditionals through; implemented by `impl_doxygen_row!` +/// (`checker/doxygen_doc_binding.rs`) beside the Checker that composes +/// it. Not a `Checker` supertrait: of the helpers bounded on this, only +/// [`doxygen_binds_forward`] reads a `Checker` method, and it names both +/// bounds. pub(crate) trait DoxygenRow { /// The dialect's `doc_target::owns`. fn doc_target_row<'a>(node: &Node<'a>, code: &[u8], ancestors: Ancestors<'a, '_>) -> bool; + /// The dialect's `is_preproc_conditional_kind`: the row's conditional + /// owners, gates aside, which `doc_target::lists_kind` cannot tell + /// from the entries it lists beside them. + fn conditional_kind(kind: u16) -> bool; } /// Whether a C-family doc comment binds to what follows it: one among a @@ -512,7 +559,7 @@ pub(crate) trait DoxygenRow { /// The others keep the reading of where they sit: in a body, Doxygen's /// in-body description (#1609); in a declaration, that declaration's. #[must_use] -pub(crate) fn doxygen_binds_forward<'a, T: Checker>( +pub(crate) fn doxygen_binds_forward<'a, T: Checker + DoxygenRow>( comment: &Node<'a>, code: &[u8], ancestors: Ancestors<'a, '_>, @@ -522,7 +569,7 @@ pub(crate) fn doxygen_binds_forward<'a, T: Checker>( && !doxygen_standalone(bytes) && ancestors .parent(comment) - .is_some_and(|parent| doxygen_container(&parent)) + .is_some_and(|parent| doxygen_container::(&parent)) && outside_function_bodies::(comment, ancestors) } @@ -682,7 +729,7 @@ mod tests { let nest: Vec<_> = tree .get_root() .preorder() - .filter(preproc_conditional) + .filter(|node| preproc_conditional::(node)) .collect(); assert_eq!(nest.len(), DEPTH, "{bottom}"); @@ -715,12 +762,66 @@ mod tests { } } + /// Every conditional of each nest answers as its children say — an + /// entry, or a nested conditional that declares — asked outermost + /// first (each nested answer folded in by the walk), innermost first + /// (each one the memo's) and unmemoised. The shapes that tell a fold + /// from an overwrite: an entry before and after a nested conditional + /// declaring nothing, and a declaring one before a child that is no + /// entry (#1795). The answers are in preorder, by hand: the `#elif` + /// branch nests in the `#if` and the `#else` in the `#elif`. + #[cfg(feature = "c")] + #[test] + fn conditional_declares_folds_in_every_child() { + use crate::langs::CCode; + use crate::node::{FoldCache, Tree}; + let shapes: &[(&str, &[bool])] = &[ + ( + "#ifdef A\nint x;\n#ifdef B\n#endif\n#endif\n", + &[true, false], + ), + ( + "#ifdef A\n#ifdef B\n#endif\nint x;\n#endif\n", + &[true, false], + ), + ( + "#ifdef A\n#ifdef B\nint x;\n#endif\n#include \n#endif\n", + &[true, true], + ), + ( + "#if A\n#ifdef B\n#endif\n#elif C\nint x;\n#else\n#ifdef D\n#endif\n#endif\n", + &[true, false, true, false, false], + ), + ]; + for &(shape, answers) in shapes { + let tree = Tree::new::(shape.as_bytes()); + let nest: Vec<_> = tree + .get_root() + .preorder() + .filter(|node| preproc_conditional::(node)) + .zip(answers.iter().copied()) + .collect(); + assert_eq!(nest.len(), answers.len(), "{shape}"); + for order in [nest.clone(), nest.iter().rev().copied().collect()] { + let cache = FoldCache::default(); + let walk = Ancestors::known(&[]).with_folds(&cache); + for (level, declares) in &order { + let row = level.start_row(); + let answer = conditional_declares::(level, walk); + assert_eq!(answer, *declares, "{shape}: row {row}"); + let answer = conditional_declares::(level, Ancestors::known(&[])); + assert_eq!(answer, *declares, "{shape}: row {row}, unmemoised"); + } + } + } + } + /// `doxygen_entry` must test `preproc_conditional` *before* reading /// the row: the row's conditional owners are gated by /// `conditional_declares`, so the other order would run that walk /// from inside an entry question about a conditional. Two defences /// keep the walk from re-entering itself — this order, and the - /// walk asking `doxygen_entry` of non-conditional children only — + /// walk asking the entry question of non-conditional children only — /// and when it had the first alone, reversing it cost `2^depth - 1` /// reads on the uncached path (4,095 at this depth) against `depth`. /// Pinned by count on the uncached path: asking the entry question @@ -742,7 +843,7 @@ mod tests { let outermost = tree .get_root() .preorder() - .find(preproc_conditional) + .find(|node| preproc_conditional::(node)) .expect("a nest"); // Both uncached contexts: a known chain, under which the walk // hands each child a one-entry chain, and no chain at all (a @@ -793,6 +894,10 @@ mod tests { ASKED.with(|asked| asked.set(asked.get() + 1)); false } + // The fixture is C, so C's conditionals. + fn conditional_kind(kind: u16) -> bool { + ::conditional_kind(kind) + } } let source = b"int ok;\nQ_OBJECT\nint after;\n"; let tree = Tree::new::(source); diff --git a/big-code-analysis-ast/src/roles/c.rs b/big-code-analysis-ast/src/roles/c.rs index 4cf667f9a..e42dab17d 100644 --- a/big-code-analysis-ast/src/roles/c.rs +++ b/big-code-analysis-ast/src/roles/c.rs @@ -9,14 +9,16 @@ use crate::C; use crate::role_table; use crate::roles::c_family::{ c_doc_declarations, c_family_binary_owners, c_family_calls, c_family_comparison_payers, - c_family_decl_keywords, c_family_doc_conditionals, c_family_doc_entries, c_family_doc_gates, - c_family_loops, c_family_modifiers, c_family_primitives, c_family_short_circuit_payers, - c_family_strings, + c_family_conditional_kinds, c_family_decl_keywords, c_family_doc_conditionals, + c_family_doc_entries, c_family_doc_gates, c_family_loops, c_family_modifiers, + c_family_primitives, c_family_short_circuit_payers, c_family_strings, }; use crate::roles::control_flow::else_if_parent_clause_gate; // The documentation gates, per dialect (#1699). c_family_doc_gates!(with_has_body CCode); +// The `DocTarget` row's conditional owners as a kind test (#1795). +c_family_conditional_kinds!(C); // The chained `if` sits directly inside an `else_clause`; a nested one // under `else { … }` sits inside the compound statement (#1697). diff --git a/big-code-analysis-ast/src/roles/c_family.rs b/big-code-analysis-ast/src/roles/c_family.rs index 84a130b18..76bf5cad9 100644 --- a/big-code-analysis-ast/src/roles/c_family.rs +++ b/big-code-analysis-ast/src/roles/c_family.rs @@ -504,6 +504,58 @@ macro_rules! objc_doc_conditionals { }; } +// The conditional owners again, as kind lists: `lang_helpers::doxygen` +// asks "is this a conditional" of a doc comment's parent and siblings +// and of every child of a conditional, which `doc_target::lists_kind` +// cannot answer, as the row lists the entries beside the conditionals. +// A fragment with a second arm sharing one list would need a callback +// the `role_tables.py` fragment reader cannot follow, so the lists are +// repeated here and `roles/doc_tests/doxygen.rs` holds each dialect's to +// the conditional names over every runtime id (#1795). + +/// `is_preproc_conditional_kind` for a dialect, from its conditional ids. +macro_rules! preproc_conditional_kind { + ($lang:ident [$($kind:ident),+ $(,)?]) => { + /// Whether `kind` is one of the dialect's preprocessor + /// conditionals or their branches — the conditional owners of the + /// `DocTarget` row, gates aside: the nodes Doxygen's preprocessor + /// reads through to the declarations inside. A projection of the + /// row's owners the row cannot hand out, as it lists the entries + /// beside them; read through `DoxygenRow::conditional_kind`. + #[inline] + #[must_use] + pub fn is_preproc_conditional_kind(kind: u16) -> bool { + $(kind == $crate::$lang::$kind as u16)||+ + } + }; +} + +/// The ids of `c_family_doc_conditionals!`, for the C and C++ grammars. +macro_rules! c_family_conditional_kinds { + ($lang:ident) => { + $crate::roles::c_family::preproc_conditional_kind!($lang [ + PreprocIf, PreprocIf2, PreprocIf3, PreprocIf4, + PreprocIfdef, PreprocIfdef2, PreprocIfdef3, PreprocIfdef4, + PreprocElse, PreprocElse2, PreprocElse3, PreprocElse4, + PreprocElif, PreprocElif2, PreprocElif3, PreprocElif4, + PreprocElifdef, PreprocElifdef2, PreprocElifdef3, PreprocElifdef4, + ]); + }; +} + +/// The ids of `objc_doc_conditionals!`, for the Objective-C grammar. +macro_rules! objc_conditional_kinds { + () => { + $crate::roles::c_family::preproc_conditional_kind!(Objc [ + PreprocIf, PreprocIf2, PreprocIf3, PreprocIf4, + PreprocIfdef, PreprocIfdef2, PreprocIfdef3, + PreprocElse, PreprocElse2, PreprocElse3, PreprocElse4, PreprocElse5, + PreprocElif, PreprocElif2, PreprocElif3, PreprocElif4, PreprocElif5, + PreprocElifdef, PreprocElifdef2, + ]); + }; +} + /// The gates the documentation rows read, per dialect because each /// table reads the dialect's kind ids and the gate fns resolve at the /// row; `$code` is the dialect's `Checker` tag the conditional memo is @@ -577,6 +629,7 @@ pub(crate) fn field_declaration_declares(node: &crate::Node<'_>) -> bool { } pub(crate) use { - c_doc_declarations, c_family_doc_conditionals, c_family_doc_entries, c_family_doc_gates, - cpp_doc_entries, objc_doc_conditionals, + c_doc_declarations, c_family_conditional_kinds, c_family_doc_conditionals, + c_family_doc_entries, c_family_doc_gates, cpp_doc_entries, objc_conditional_kinds, + objc_doc_conditionals, preproc_conditional_kind, }; diff --git a/big-code-analysis-ast/src/roles/cpp.rs b/big-code-analysis-ast/src/roles/cpp.rs index 73fcdcca8..e258f077b 100644 --- a/big-code-analysis-ast/src/roles/cpp.rs +++ b/big-code-analysis-ast/src/roles/cpp.rs @@ -8,16 +8,18 @@ use crate::Cpp; use crate::role_table; use crate::roles::c_family::{ - c_family_calls, c_family_decl_keywords, c_family_doc_conditionals, c_family_doc_entries, - c_family_doc_gates, c_family_modifiers, c_family_primitives, c_family_strings, cpp_doc_entries, - cpp_family_binary_owners, cpp_family_comparison_payers, cpp_family_containers, - cpp_family_exits, cpp_family_func_openers, cpp_family_gates, cpp_family_loops, - cpp_family_short_circuit_payers, + c_family_calls, c_family_conditional_kinds, c_family_decl_keywords, c_family_doc_conditionals, + c_family_doc_entries, c_family_doc_gates, c_family_modifiers, c_family_primitives, + c_family_strings, cpp_doc_entries, cpp_family_binary_owners, cpp_family_comparison_payers, + cpp_family_containers, cpp_family_exits, cpp_family_func_openers, cpp_family_gates, + cpp_family_loops, cpp_family_short_circuit_payers, }; use crate::roles::control_flow::else_if_parent_clause_gate; // The documentation gates, per dialect (#1699). c_family_doc_gates!(CppCode); +// The `DocTarget` row's conditional owners as a kind test (#1795). +c_family_conditional_kinds!(Cpp); cpp_family_gates!(Cpp); // The chained `if` sits directly inside an `else_clause`; a nested one diff --git a/big-code-analysis-ast/src/roles/doc_tests/doxygen.rs b/big-code-analysis-ast/src/roles/doc_tests/doxygen.rs index 82de99f55..1b711322d 100644 --- a/big-code-analysis-ast/src/roles/doc_tests/doxygen.rs +++ b/big-code-analysis-ast/src/roles/doc_tests/doxygen.rs @@ -15,8 +15,9 @@ use std::path::Path; /// The names `doxygen_entry` matched before #1699 (its `match /// node.kind()` arms, plus the specifier and field arms it gated), -/// and the five conditional names `preproc_conditional` matches. A -/// hand-pinned copy, not read from the rows, so this is an oracle. +/// and the five conditional names `preproc_conditional` matched until +/// #1795. A hand-pinned copy, not read from the rows, so this is an +/// oracle. const OLD_ENTRY_NAMES: &[&str] = &[ "declaration", "function_definition", @@ -141,6 +142,59 @@ old_names_are_the_row!( #[cfg(feature = "objc")] old_names_are_the_row!(objc_old_names_are_the_row, Objc, objc, OBJC_KIND_FLAGS); +macro_rules! old_names_are_the_conditional_kinds { + ($name:ident, $lang:ident, $code:ident, $flags:ident) => { + /// The conditional kind test `preproc_conditional` reads through + /// the dialect's `DoxygenRow` binding (#1795) answers, over every + /// runtime id, exactly the ids the old conditional names denote: + /// every alias of the five rules and nothing else — the runtime + /// `ERROR` id and the enum's sentinel included. + #[test] + fn $name() { + use crate::lang_helpers::doxygen::DoxygenRow; + let conditional = ::conditional_kind; + let old = ids_named::(OLD_CONDITIONAL_NAMES, crate::$flags); + let new: BTreeSet = crate::$flags + .iter() + .map(|(id, ..)| *id) + .filter(|&id| conditional(id)) + .collect(); + assert_eq!(new, old); + assert!(!old.is_empty()); + assert!(!conditional(u16::MAX) && !conditional(crate::$lang::Error as u16)); + } + }; +} + +#[cfg(feature = "c")] +old_names_are_the_conditional_kinds!( + c_old_names_are_the_conditional_kinds, + C, + CCode, + C_KIND_FLAGS +); +#[cfg(feature = "cpp")] +old_names_are_the_conditional_kinds!( + cpp_old_names_are_the_conditional_kinds, + Cpp, + CppCode, + CPP_KIND_FLAGS +); +#[cfg(feature = "mozcpp")] +old_names_are_the_conditional_kinds!( + mozcpp_old_names_are_the_conditional_kinds, + Mozcpp, + MozcppCode, + MOZCPP_KIND_FLAGS +); +#[cfg(feature = "objc")] +old_names_are_the_conditional_kinds!( + objc_old_names_are_the_conditional_kinds, + Objc, + ObjcCode, + OBJC_KIND_FLAGS +); + // Every C entry kind with its gate's two sides, the three conditional // forms with and without an entry, a nested conditional, a macro call // and an unterminated one, and a doc comment in a body (Doxygen's diff --git a/big-code-analysis-ast/src/roles/mozcpp.rs b/big-code-analysis-ast/src/roles/mozcpp.rs index 787750c91..806720577 100644 --- a/big-code-analysis-ast/src/roles/mozcpp.rs +++ b/big-code-analysis-ast/src/roles/mozcpp.rs @@ -12,16 +12,18 @@ use crate::Mozcpp; use crate::role_table; use crate::roles::c_family::{ - c_family_calls, c_family_decl_keywords, c_family_doc_conditionals, c_family_doc_entries, - c_family_doc_gates, c_family_modifiers, c_family_primitives, c_family_strings, cpp_doc_entries, - cpp_family_binary_owners, cpp_family_comparison_payers, cpp_family_containers, - cpp_family_exits, cpp_family_func_openers, cpp_family_gates, cpp_family_loops, - cpp_family_short_circuit_payers, + c_family_calls, c_family_conditional_kinds, c_family_decl_keywords, c_family_doc_conditionals, + c_family_doc_entries, c_family_doc_gates, c_family_modifiers, c_family_primitives, + c_family_strings, cpp_doc_entries, cpp_family_binary_owners, cpp_family_comparison_payers, + cpp_family_containers, cpp_family_exits, cpp_family_func_openers, cpp_family_gates, + cpp_family_loops, cpp_family_short_circuit_payers, }; use crate::roles::control_flow::else_if_parent_clause_gate; // The documentation gates, per dialect (#1699). c_family_doc_gates!(MozcppCode); +// The `DocTarget` row's conditional owners as a kind test (#1795). +c_family_conditional_kinds!(Mozcpp); cpp_family_gates!(Mozcpp); // The chained `if` sits directly inside an `else_clause`; a nested one diff --git a/big-code-analysis-ast/src/roles/objc.rs b/big-code-analysis-ast/src/roles/objc.rs index 4116e2e25..c0c42dec7 100644 --- a/big-code-analysis-ast/src/roles/objc.rs +++ b/big-code-analysis-ast/src/roles/objc.rs @@ -10,13 +10,15 @@ use crate::roles::c_family::{ c_doc_declarations, c_family_binary_owners, c_family_calls, c_family_comparison_payers, c_family_decl_keywords, c_family_doc_entries, c_family_doc_gates, c_family_loops, c_family_modifiers, c_family_primitives, c_family_short_circuit_payers, c_family_strings, - objc_doc_conditionals, + objc_conditional_kinds, objc_doc_conditionals, }; use crate::roles::control_flow::else_if_parent_clause_gate; use crate::{Ancestors, Node, Objc}; // The documentation gates, per dialect (#1699). c_family_doc_gates!(with_has_body ObjcCode); +// The `DocTarget` row's conditional owners as a kind test (#1795). +objc_conditional_kinds!(); /// Whether an `implementation_definition` is one Doxygen documents — /// not a `@synthesize` / `@dynamic` property implementation, which From d65786a1cf7855137b0102ee71e01c370de03fba Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Thu, 5 Nov 2026 21:53:16 -0800 Subject: [PATCH 07/25] docs(ast): tighten the #1795 comments Name Mozcpp among the grammars c_family_conditional_kinds! serves, state the kind lists' reason from the row's side rather than the consumer's call sites, and narrow the fold test's doc to the shape that tells a fold from an overwrite. Refs #1795 --- .../src/lang_helpers/doxygen.rs | 11 ++++++----- big-code-analysis-ast/src/roles/c_family.rs | 17 ++++++++--------- 2 files changed, 14 insertions(+), 14 deletions(-) diff --git a/big-code-analysis-ast/src/lang_helpers/doxygen.rs b/big-code-analysis-ast/src/lang_helpers/doxygen.rs index ee8f8a4ce..fab647e93 100644 --- a/big-code-analysis-ast/src/lang_helpers/doxygen.rs +++ b/big-code-analysis-ast/src/lang_helpers/doxygen.rs @@ -765,11 +765,12 @@ mod tests { /// Every conditional of each nest answers as its children say — an /// entry, or a nested conditional that declares — asked outermost /// first (each nested answer folded in by the walk), innermost first - /// (each one the memo's) and unmemoised. The shapes that tell a fold - /// from an overwrite: an entry before and after a nested conditional - /// declaring nothing, and a declaring one before a child that is no - /// entry (#1795). The answers are in preorder, by hand: the `#elif` - /// branch nests in the `#if` and the `#else` in the `#elif`. + /// (each one the memo's) and unmemoised. The first shape, an entry + /// before a nested conditional declaring nothing, is the one that + /// tells a fold from an overwrite at both fold sites (#1795); the + /// others pin the remaining orders. The answers are in preorder, by + /// hand: the `#elif` branch nests in the `#if` and the `#else` in the + /// `#elif`. #[cfg(feature = "c")] #[test] fn conditional_declares_folds_in_every_child() { diff --git a/big-code-analysis-ast/src/roles/c_family.rs b/big-code-analysis-ast/src/roles/c_family.rs index 76bf5cad9..2f5046354 100644 --- a/big-code-analysis-ast/src/roles/c_family.rs +++ b/big-code-analysis-ast/src/roles/c_family.rs @@ -504,14 +504,13 @@ macro_rules! objc_doc_conditionals { }; } -// The conditional owners again, as kind lists: `lang_helpers::doxygen` -// asks "is this a conditional" of a doc comment's parent and siblings -// and of every child of a conditional, which `doc_target::lists_kind` -// cannot answer, as the row lists the entries beside the conditionals. -// A fragment with a second arm sharing one list would need a callback -// the `role_tables.py` fragment reader cannot follow, so the lists are -// repeated here and `roles/doc_tests/doxygen.rs` holds each dialect's to -// the conditional names over every runtime id (#1795). +// The conditional owners again, as kind lists: the `DocTarget` row lists +// its entries beside them, so `doc_target::lists_kind` cannot tell a +// conditional from an entry. A fragment with a second arm sharing one +// list would need a callback the `role_tables.py` fragment reader cannot +// follow, so the lists are repeated here and `roles/doc_tests/doxygen.rs` +// holds each dialect's to the conditional names over every runtime id +// (#1795). /// `is_preproc_conditional_kind` for a dialect, from its conditional ids. macro_rules! preproc_conditional_kind { @@ -530,7 +529,7 @@ macro_rules! preproc_conditional_kind { }; } -/// The ids of `c_family_doc_conditionals!`, for the C and C++ grammars. +/// The ids of `c_family_doc_conditionals!`, for the C, C++ and Mozcpp grammars. macro_rules! c_family_conditional_kinds { ($lang:ident) => { $crate::roles::c_family::preproc_conditional_kind!($lang [ From 20775cd3d782f827513ea94b21ce4199fa7995ae Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Thu, 5 Nov 2026 22:17:09 -0800 Subject: [PATCH 08/25] refactor(roles): add owner under / not_under lists An owner whose membership is a test of its parent's kind spelled it as a named gate fn, which the role reader could not see. Owners now take the payer's parent test as an attribute, in both directions: `under [K, ..]` and `not_under [K, ..]`. A list fills the owner's one gate slot, so it is exclusive with gated_by, text_gated_by and holds_payer. It is bracketed and non-empty, reads the walk's chain (Ancestors::parent) and so sets CHAIN_GATED, and names kinds that are tests, not claims: OWNERS and the three role baselines are unchanged. The payer `under` clause now renders through the same @gate arm. Four gate fns move onto their rows: Python's under_case_clause, the TS family's under_enum_body (in the shared fragment and both dialects' String rows), Groovy's not_in_an_import and Java's not_a_class_literal. The other 11 pure parent gates (the ElseIf emitters, Go, PHP) stay named fns, and the TS/TSX export/ambient veto stays a Checker composition; the issue records why. role_tables.py reads both lists, tokenising a bracketed list as one attribute word, counts them in chain_gated, and parses owner and payer lists with one function. A proof table in roles/mod.rs reaches every terminal a list can reach, each list its row's only chain reader; the doctests pin exclusivity and the empty list. Zero drift, base 67d03ae1 against head: drift-oracle over the three corpora, the control-flow fixtures and two probe roots for python, javascript, typescript, tsx, groovy and java, 7,028 outputs in 14 views including verbatim, 0 differing. Mutation coverage: cargo-mutants never visits a macro token tree, so the three gates that were plain fns (python, groovy, java) are no longer mutated; under_enum_body already sat inside a macro. utils/perturb.py flipped and dropped each moved list over the ast and root lib tests, and every case failed a named test: - python: guard_owns_the_case_guard_and_not_a_comprehension_filter (both), and the three ABC case-guard tests on the flip; - java: java_class_literal_bills_its_parts_1566 and java_declaration_keywords_are_operators_1552 (both); - groovy: groovy_modifiers_are_operators_1565 (both); - ts/tsx: doc_tests' rows_answer_the_table for each of the four owners, and the dloc binding test on the flip. Each new macro arm, perturbed, fails the a_parent_list_gates_* test for its projection (owns, the leaf, callables and opens_space); the CHAIN_GATED arm and the reader's chain_gated term fail python_reader_agrees_with_the_compiled_tables. Fixes #1794 --- .bca-baseline.toml | 4 +- .claude/rules/macro-comments.md | 1 + big-code-analysis-ast/src/roles/groovy.rs | 15 +- big-code-analysis-ast/src/roles/java.rs | 16 +- big-code-analysis-ast/src/roles/js_family.rs | 20 +- big-code-analysis-ast/src/roles/mod.rs | 410 ++++++++++++++++-- big-code-analysis-ast/src/roles/python.rs | 19 +- big-code-analysis-ast/src/roles/tsx.rs | 2 +- big-code-analysis-ast/src/roles/typescript.rs | 2 +- utils/check-role-census-test.py | 64 +++ utils/role_tables.py | 60 ++- 11 files changed, 526 insertions(+), 87 deletions(-) diff --git a/.bca-baseline.toml b/.bca-baseline.toml index c88dbdadb..1a27456e7 100644 --- a/.bca-baseline.toml +++ b/.bca-baseline.toml @@ -365,13 +365,13 @@ value = 5.0 path = "big-code-analysis-ast/src/roles/mod.rs" qualified = "" metric = "loc.ploc" -value = 920.0 +value = 954.0 [[entry]] path = "big-code-analysis-ast/src/roles/mod.rs" qualified = "" metric = "loc.sloc" -value = 2226.0 +value = 2321.0 [[entry]] path = "big-code-analysis-ast/src/tools.rs" diff --git a/.claude/rules/macro-comments.md b/.claude/rules/macro-comments.md index 714a7a130..3df536e9a 100644 --- a/.claude/rules/macro-comments.md +++ b/.claude/rules/macro-comments.md @@ -69,6 +69,7 @@ it. Where each kind of rationale goes: | --- | --- | | the grammar fact a row encodes — what the construct's nodes are, how they nest, why an alias is listed or left off | a `//` comment on the line above the row, inside the invocation | | why a gate exists and what it reads (`gated_by f`, `text_gated_by f`) | the `///` doc on the gate `fn` beside the table | +| why an owner is gated `under [..]` / `not_under [..]` its parents — a gate with no `fn` to carry it | the `//` comment above the row, as the grammar fact it is | | why a kind the author considered is not on the row | the `excludes [K "why"]` string itself — it is read by the coverage gate and printed with the residue | | which consumer reads which projection, and why it counts there | at the consumer, in `big-code-analysis` | | the shape of the macro — what `owns`, `pays`, `opens` mean | `roles/mod.rs` only, never a row comment | diff --git a/big-code-analysis-ast/src/roles/groovy.rs b/big-code-analysis-ast/src/roles/groovy.rs index 7472888cc..2e40c63d7 100644 --- a/big-code-analysis-ast/src/roles/groovy.rs +++ b/big-code-analysis-ast/src/roles/groovy.rs @@ -139,14 +139,6 @@ fn spells_var<'a>(node: &Node<'a>, code: &[u8], ancestors: Ancestors<'a, '_>) -> }) } -/// Whether a `static` qualifies a declaration rather than `import -/// static`, whose `static` bills nothing as `import` does not; Java -/// makes the same call, and the reasoning (#1600) is on its -/// `not_in_a_directive`. -fn not_in_an_import<'a>(node: &Node<'a>, _code: &[u8], ancestors: Ancestors<'a, '_>) -> bool { - !ancestors.parent_has_kind(node, Groovy::ImportDeclaration as u16) -} - // `else if` is an `if_statement` whose previous sibling is the bare `else` // token — no clause wrapper — so a nested `if` under `else { … }` follows // `{` instead (#1697). @@ -325,10 +317,13 @@ role_table! { // as a name (`non-sealed` as a subtraction parses as `non`, `-` and // an identifier `sealed`). `default` is not here: it is one kind for // a `switch` label and an interface method's modifier, and bills - // with the control keywords. + // with the control keywords. The `static` of `import static` sits + // under the `import_declaration`, a directive that qualifies no + // declaration; Java's row reads the same parent, and the reasoning + // (#1600) is on its `not_in_a_directive`. Modifier { owns [ - Public, Private, Protected, Static(gated_by not_in_an_import), Abstract, Final, + Public, Private, Protected, Static(not_under [ImportDeclaration]), Abstract, Final, Native, Strictfp, Synchronized, Transient, Volatile, NonDASHsealed, Sealed(gated_by contextual_keyword_owns), Permits(gated_by contextual_keyword_owns), ] diff --git a/big-code-analysis-ast/src/roles/java.rs b/big-code-analysis-ast/src/roles/java.rs index e52025789..c245f8d3d 100644 --- a/big-code-analysis-ast/src/roles/java.rs +++ b/big-code-analysis-ast/src/roles/java.rs @@ -59,15 +59,6 @@ fn not_in_a_directive<'a>(node: &Node<'a>, _code: &[u8], ancestors: Ancestors<'a }) } -/// Whether a `class` keyword declares a class rather than ending a -/// class literal (`C.class`), where it is the operand the `.` acts on: -/// JLS §15.8.2 makes the literal a primary expression, not a literal -/// (§3.10), so its parts bill as they would anywhere else, as Kotlin's -/// and PHP's `Foo::class` and Groovy's `Foo.class` bill theirs (#1566). -fn not_a_class_literal<'a>(node: &Node<'a>, _code: &[u8], ancestors: Ancestors<'a, '_>) -> bool { - !ancestors.parent_has_kind(node, Java::ClassLiteral as u16) -} - // `else if` is an `if_statement` whose previous sibling is the bare `else` // token — no clause wrapper — so a nested `if` under `else { … }` follows // `{` instead (#1697). @@ -295,9 +286,12 @@ role_table! { } // The type-declaration keywords, billed as C# bills its own // (#1552). Only the leaves: no `*_declaration` wrapper is listed, so - // a declaration bills its keyword once. + // a declaration bills its keyword once. A `class` under a + // `class_literal` (`C.class`) ends the literal and declares nothing: + // JLS §15.8.2 makes the literal a primary expression, not a literal + // (§3.10), so its parts are what they are anywhere else (#1566). DeclKeyword { - owns [Class(gated_by not_a_class_literal), Interface, Enum, Record, ATinterface] + owns [Class(not_under [ClassLiteral]), Interface, Enum, Record, ATinterface] } // Each primitive is a kind of its own (`int`, `boolean_type`, …), so // none is keyed by text and `Checker::is_primitive` stays the diff --git a/big-code-analysis-ast/src/roles/js_family.rs b/big-code-analysis-ast/src/roles/js_family.rs index e88a51ea8..692fcf3bb 100644 --- a/big-code-analysis-ast/src/roles/js_family.rs +++ b/big-code-analysis-ast/src/roles/js_family.rs @@ -448,7 +448,8 @@ macro_rules! js_doc_gates { /// assignment statements are not here: tsc does not declare them. The /// `using` form is one, read by its own gate; an enum member without an /// initializer is a bare name under the `enum_body`, gated on that -/// parent. +/// parent, since anywhere else a `property_identifier` is a member name +/// after a modifier or a `.`, inside what it names. macro_rules! ts_family_doc_targets { (@splice $cont:tt [$($acc:tt)*] $($rest:tt)*) => { $crate::role_table!(@owners $cont [$($acc)* @@ -473,8 +474,8 @@ macro_rules! ts_family_doc_targets { OptionalParameter2, ExportStatement(gated_by export_declares_to_tsc), ExpressionStatement(gated_by using_declares no_chain), - PropertyIdentifier(gated_by under_enum_body), - ComputedPropertyName(gated_by under_enum_body), + PropertyIdentifier(under [EnumBody]), + ComputedPropertyName(under [EnumBody]), ] $($rest)*); }; } @@ -489,7 +490,7 @@ macro_rules! ts_family_doc_targets { /// asked through the row's `owns` with the *export's* chain: exact, /// because the `declaration` field holds a `declaration` supertype or /// an `internal_module` (`node-types.json`) and the row's chain-reading -/// owners — the enum-member kinds under `under_enum_body` — are never +/// owners — the enum-member kinds gated `under [EnumBody]` — are never /// among those, which `roles/doc_tests/mod.rs` pins; and the parent context /// tsc reads (a declaration under `export` documents nothing on its /// own) is the Checker's over the *export*, never applied to the child. @@ -543,17 +544,6 @@ macro_rules! ts_doc_gates { }) }) } - - /// An enum member without an initializer is a bare name in the - /// enum body; anywhere else a `property_identifier` is a member - /// name after a modifier or a `.`, inside what it names. - fn under_enum_body<'a>( - node: &$crate::Node<'a>, - _: &[u8], - ancestors: $crate::Ancestors<'a, '_>, - ) -> bool { - ancestors.parent_has_kind(node, $lang::EnumBody as u16) - } }; } diff --git a/big-code-analysis-ast/src/roles/mod.rs b/big-code-analysis-ast/src/roles/mod.rs index cc0680648..be0612c58 100644 --- a/big-code-analysis-ast/src/roles/mod.rs +++ b/big-code-analysis-ast/src/roles/mod.rs @@ -160,6 +160,9 @@ //! excludes [QMARK "a wildcard bound's `?` is type syntax"] } //! Container { owns [ClassDeclaration(opens Class), //! ObjectCreationExpression(opens Class gated_by has_class_body)] } +//! Modifier { owns [Static(not_under [ImportDeclaration, RequiresModifier]), +//! Final] } +//! DocTarget { owns [PropertyIdentifier(under [EnumBody])] } //! ElseIf { owns [IfStatement(gated_by follows_else)] pays [] } //! Guard { owns [Guard] pays never } //! NullSafe { absent "no `?.` or `??`" } @@ -195,6 +198,18 @@ //! bytes and no chain, Groovy's `spells_var` both — so //! `TEXT_GATED` comes from the keyword and `CHAIN_GATED` from the //! absence of the modifier. +//! - `under [P, Q]` makes the kind own the construct only where its +//! parent is one of the listed kinds, and `not_under [P, Q]` only +//! where it is none of them, a parentless node included (#1794): +//! Python's `if_clause` is a `case` guard under a `case_clause` and a +//! comprehension filter anywhere else; Java's `class` under a +//! `class_literal` ends `C.class`. The list is bracketed even for one +//! kind, and not empty. It is the owner's gate — exclusive with +//! `gated_by`, `text_gated_by` and `holds_payer` — and reads the +//! chain (`Ancestors::parent`), so it sets `CHAIN_GATED`. The parent +//! kinds are not claimed: they reach no kind list, and the coverage +//! ratchet does not count them. A test of anything beyond the +//! parent's kind stays a `fn`. //! - `pays_itself` marks a kind the grammar gives no token for, so the //! owner is also the payer; `pays_itself_when f` one the grammar gives //! a token in some spellings and none in others, so the owner pays @@ -225,16 +240,17 @@ //! `function_expression` opens a space wherever it sits and is a //! function only when bound to a name, a closure otherwise. //! -//! An owner takes at most one gate, one `pays_itself*` and one `opens*`; -//! a second of any is a compile error. An owner that needs two -//! conditions names one `fn` that tests both. +//! An owner takes at most one gate (a parent list is one), one +//! `pays_itself*` and one `opens*`; a second of any is a compile error. +//! An owner that needs two conditions names one `fn` that tests both. //! //! ## Payer attributes //! //! A payer takes `gated_by f` or `text_gated_by f` bare, after its kind, //! or `under P` / `under [P, Q]`, which gates it on its parent's kind — //! the one gate a token the grammar spells in several productions reads -//! (`?` under the ternary and not a wildcard). +//! (`?` under the ternary and not a wildcard), the same test as an +//! owner's `under`. //! //! ## Row attributes //! @@ -340,8 +356,9 @@ //! a gate named under the wrong keyword is the author's error. //! - `CHAIN_GATED`: whether any owner carries a `gated_by` / //! `text_gated_by` gate or an `opens_by` fn *without* `no_chain` -//! (#1793), so a forward that hands the row a known-empty chain -//! asserts at build time that no gate it reaches can take the chain. +//! (#1793), or an `under` / `not_under` list, so a forward that +//! hands the row a known-empty chain asserts at build time that no +//! gate it reaches can take the chain. //! It covers the `owns` / `pays_at_wrapper` projections and the //! `opens_space` fold — the ones a chain-less forward reads — and //! not `callable_when`, `pays_itself_when` or a payer's gate, which @@ -513,8 +530,9 @@ //! The check //! is the alias inventory of `grammar-dispatch.md` §1 — every //! numeric-suffix variant listed or excluded with a comment — for row -//! declarations as for consumers, and the §7 cross-walk of the sibling -//! predicates. +//! declarations as for consumers, an `under` / `not_under` list +//! included, since no gate reads one, and the §7 cross-walk of the +//! sibling predicates. //! //! **A forward whose dropped context no gate reads yet.** A byte-less or //! chain-less forward answers the same under any context until the day @@ -1065,6 +1083,30 @@ impl RowView { /// # fn main() {} /// ``` /// +/// A parent list is the owner's gate, so it sits beside no other, and +/// it names at least one kind (#1794): +/// +/// ```compile_fail +/// # #[macro_use] extern crate big_code_analysis_ast; +/// # use big_code_analysis_ast::{Ancestors, Java, Node}; +/// fn always(_: &Node<'_>, _: &[u8], _: Ancestors<'_, '_>) -> bool { true } +/// role_table! { +/// lang: Java; +/// Exit { owns [ReturnStatement(under [Block] gated_by always)] } +/// } +/// # fn main() {} +/// ``` +/// +/// ```compile_fail +/// # #[macro_use] extern crate big_code_analysis_ast; +/// # use big_code_analysis_ast::Java; +/// role_table! { +/// lang: Java; +/// Exit { owns [ReturnStatement(not_under [])] } +/// } +/// # fn main() {} +/// ``` +/// /// And a kind owned by two rows of the same role: /// /// ```compile_fail @@ -1153,6 +1195,8 @@ impl RowView { /// owns [MethodDeclaration(callable opens Function), StaticInitializer(opens Function)] /// } /// Guard { owns [Guard] pays never } +/// Modifier { owns [Static(not_under [ImportDeclaration, RequiresModifier]), Final] } +/// DeclKeyword { owns [Class(under [ClassDeclaration])] } /// NullSafe { absent "no `?.`" } /// Comment { pending R11 } /// } @@ -1162,6 +1206,9 @@ impl RowView { /// assert_eq!(comparison::PAYERS, &[Java::EQEQ as u16, Java::LT as u16]); /// assert_eq!((exit::PAYS_NEVER, guard::PAYS_NEVER), (false, true)); /// assert_eq!((comparison::CHAIN_GATED, container::CHAIN_GATED), (true, false)); +/// // A parent list reads the chain, and its kinds are not owners. +/// assert_eq!((modifier::CHAIN_GATED, decl_keyword::CHAIN_GATED), (true, true)); +/// assert_eq!(modifier::OWNERS, &[Java::Static as u16, Java::Final as u16]); /// # } /// ``` #[macro_export] @@ -1586,7 +1633,8 @@ macro_rules! role_table { ) )*; /// Whether any owner carries a `gated_by` / `text_gated_by` - /// gate or an `opens_by` fn that is *not* marked `no_chain` + /// gate or an `opens_by` fn that is *not* marked `no_chain`, + /// or an `under` / `not_under` parent list (#1794) /// — the row may read the chain it is handed through /// [`owns`], [`pays_at_wrapper`] or the table's `opens_space` /// fold. A forward that hands the row a known-empty chain @@ -1779,9 +1827,11 @@ macro_rules! role_table { // emitters below call the first with three arguments and the second // with two, so a `no_chain` gate cannot be given the chain by // construction. `opens_by f no_chain` is carried as `[by f no_chain]` - // the same way. `callable_when`, `pays_itself_when` and a payer's gate - // take no `no_chain`: nothing that drops the chain reads them, and a - // mark no consumer asserts would be a claim nothing checks. + // the same way, and an owner's parent list as `[under [P, ..]]` or + // `[not_under [P, ..]]` (#1794). `callable_when`, `pays_itself_when` + // and a payer's gate take no `no_chain`: nothing that drops the + // chain reads them, and a mark no consumer asserts would be a claim + // nothing checks. (@scan $d:ident $m:tt $ctx:tt $k:ident $g:tt $p:tt $s:tt $c:tt) => { $crate::role_table!(@$d $m $ctx $k $g $p $s $c) @@ -1855,6 +1905,15 @@ macro_rules! role_table { (@scan $d:ident $m:tt $ctx:tt $k:ident [] $p:tt $s:tt $c:tt text_gated_by $g:ident $($r:tt)*) => { $crate::role_table!(@scan $d $m $ctx $k [$g] $p $s $c $($r)*) }; + // An owner's parent list is its gate, so it needs the slot empty: + // beside `gated_by` or `holds_payer`, in either order, it matches + // no rule (#1794). + (@scan $d:ident $m:tt $ctx:tt $k:ident [] $p:tt $s:tt $c:tt under [$($u:ident),+ $(,)?] $($r:tt)*) => { + $crate::role_table!(@scan $d $m $ctx $k [under [$($u),+]] $p $s $c $($r)*) + }; + (@scan $d:ident $m:tt $ctx:tt $k:ident [] $p:tt $s:tt $c:tt not_under [$($u:ident),+ $(,)?] $($r:tt)*) => { + $crate::role_table!(@scan $d $m $ctx $k [not_under [$($u),+]] $p $s $c $($r)*) + }; (@scan $d:ident $m:tt $ctx:tt $k:ident $g:tt [] $s:tt $c:tt pays_itself $($r:tt)*) => { $crate::role_table!(@scan $d $m $ctx $k $g [pays_itself] $s $c $($r)*) }; @@ -1878,7 +1937,12 @@ macro_rules! role_table { // In `owns`: the owner's clause, gated or not. A gate slot is // `[g]` or `[g no_chain]`, carried into the clause as - // `gated_by g` / `gated_by g no_chain`. + // `gated_by g` / `gated_by g no_chain`. A parent list, + // `[under [..]]` or `[not_under [..]]`, is handed to `@gate` whole, + // here and in every terminal below that emits a clause. + (@owner_done [] $ctx:tt $k:ident [$rel:ident [$($q:ident),+]] $p:tt $s:tt $c:tt) => { + $crate::role_table!(@clause_gated $ctx $k [$rel [$($q),+]]); + }; (@owner_done [] $ctx:tt $k:ident [holds_payer $($g:ident $($nc:ident)?)?] $p:tt $s:tt $c:tt) => { $crate::role_table!(@clause_payer $ctx $k $(gated_by $g $($nc)?)?); }; @@ -1892,7 +1956,12 @@ macro_rules! role_table { false }; // In `CHAIN_GATED`: every gate and `opens_by` the owner carries was - // consumed with its `no_chain`, or the owner carries none. + // consumed with its `no_chain`, or the owner carries none — unless + // the gate is a parent list, which reads the chain by construction + // and takes no modifier, so the slot alone says so (#1794). + (@chain_gated_kind [] [] $k:ident [$rel:ident [$($q:ident),+]] $p:tt $s:tt $c:tt) => { + true + }; (@chain_gated_kind [] [] $k:ident $g:tt $p:tt $s:tt $c:tt) => { false }; @@ -1940,6 +2009,12 @@ macro_rules! role_table { // a `callable_when w` owner's under its gate *and* `w`; an owner // without either mark emits nothing. (@callable_done [] $ctx:tt $k:ident $g:tt $p:tt $s:tt []) => {}; + (@callable_done [] $ctx:tt $k:ident [$rel:ident [$($q:ident),+]] $p:tt $s:tt [callable]) => { + $crate::role_table!(@clause_gated $ctx $k [$rel [$($q),+]]); + }; + (@callable_done [] $ctx:tt $k:ident [$rel:ident [$($q:ident),+]] $p:tt $s:tt [callable $w:ident]) => { + $crate::role_table!(@clause_when_gated $ctx $k $w [$rel [$($q),+]]); + }; (@callable_done [] $ctx:tt $k:ident [$($g:ident $($nc:ident)?)?] $p:tt $s:tt [callable]) => { $crate::role_table!(@clause $ctx $k $(gated_by $g $($nc)?)?); }; @@ -1955,6 +2030,12 @@ macro_rules! role_table { // already pays, and under `pays never` it would contradict the row // — so the other two modes reject it. (@self_payer_done [$mode:ident] $ctx:tt $k:ident $g:tt [] $s:tt $c:tt) => {}; + (@self_payer_done [split] $ctx:tt $k:ident [$rel:ident [$($q:ident),+]] [pays_itself] $s:tt $c:tt) => { + $crate::role_table!(@clause_gated $ctx $k [$rel [$($q),+]]); + }; + (@self_payer_done [split] $ctx:tt $k:ident [$rel:ident [$($q:ident),+]] [pays_itself $w:ident] $s:tt $c:tt) => { + $crate::role_table!(@clause_when_gated $ctx $k $w [$rel [$($q),+]]); + }; (@self_payer_done [split] $ctx:tt $k:ident [$($g:ident $($nc:ident)?)?] [pays_itself] $s:tt $c:tt) => { $crate::role_table!(@clause $ctx $k $(gated_by $g $($nc)?)?); }; @@ -1971,6 +2052,12 @@ macro_rules! role_table { }; // In `opens_space`: an `opens K` owner returns its kind, under its gate. (@opens_done [] $ctx:tt $k:ident $g:tt $p:tt [] $c:tt) => {}; + (@opens_done [] $ctx:tt $k:ident [$rel:ident [$($q:ident),+]] $p:tt [by $f:ident $($fnc:ident)?] $c:tt) => { + $crate::role_table!(@space_clause_by_gated $ctx $k [$f $($fnc)?] [$rel [$($q),+]]); + }; + (@opens_done [] $ctx:tt $k:ident [$rel:ident [$($q:ident),+]] $p:tt [$s:ident] $c:tt) => { + $crate::role_table!(@space_clause_gated $ctx $k $s [$rel [$($q),+]]); + }; (@opens_done [] $ctx:tt $k:ident [$($g:ident $($nc:ident)?)?] $p:tt [by $f:ident $($fnc:ident)?] $c:tt) => { $crate::role_table!(@space_clause_by $ctx $k [$f $($fnc)?] $(gated_by $g $($nc)?)?); }; @@ -1998,7 +2085,8 @@ macro_rules! role_table { // A gate call is rendered by `@gate`: three arguments for a gate // with a chain parameter, two for one declared `no_chain` (#1793), // so the chain is unobtainable by a marked gate by construction — - // the proof is the signature, not the row. + // the proof is the signature, not the row. A parent list, an + // owner's or a payer's, is the parent-kind test itself (#1794). (@gate [$l:ident $kind:ident $n:ident $c:ident $a:ident] [$g:ident]) => { $g($n, $c, $a) @@ -2006,6 +2094,18 @@ macro_rules! role_table { (@gate [$l:ident $kind:ident $n:ident $c:ident $a:ident] [$g:ident no_chain]) => { $g($n, $c) }; + // Read off the walk's chain, `Ancestors::parent`: `Node::parent` + // resolves a parent by descending from the root (#1084, #1584). A + // node with no parent is under nothing, so `not_under` admits it. + (@gate [$l:ident $kind:ident $n:ident $c:ident $a:ident] [under [$($p:ident),*]]) => { + $a.parent($n).is_some_and(|parent| { + let parent = parent.kind_id(); + false $(|| parent == $l::$p as u16)* + }) + }; + (@gate [$l:ident $kind:ident $n:ident $c:ident $a:ident] [not_under [$($p:ident),*]]) => { + !$crate::role_table!(@gate [$l $kind $n $c $a] [under [$($p),*]]) + }; (@clause [$l:ident $kind:ident $n:ident $c:ident $a:ident] $k:ident) => { if $kind == $l::$k as u16 { @@ -2021,13 +2121,8 @@ macro_rules! role_table { } }; // A payer `under [P, Q]`: its parent is one of the listed kinds. - (@clause [$l:ident $kind:ident $n:ident $c:ident $a:ident] $k:ident under [$($p:ident),*]) => { - if $kind == $l::$k as u16 { - return $a.parent($n).is_some_and(|parent| { - let parent = parent.kind_id(); - false $(|| parent == $l::$p as u16)* - }); - } + (@clause $ctx:tt $k:ident under [$($p:ident),*]) => { + $crate::role_table!(@clause_gated $ctx $k [under [$($p),*]]); }; // A `holds_payer` owner: its projection lands on one of the row's // payers, under its gate if it has one. @@ -2445,9 +2540,10 @@ mod tests { // because `pays []` and a plain `owns [..]` row print the same // lists, so a reader that misread one as the other agreed with // every table until the mode was emitted. An owner's or payer's - // gate, `holds_payer`, `under`, - // `pays_itself` and `opens` are not in it, and the reader's handling - // of those is pinned by `utils/check-role-census-test.py` instead. + // gate, `holds_payer`, `under`, `not_under`, + // `pays_itself` and `opens` are not in it beyond the two flags, and + // the reader's handling of those is pinned by + // `utils/check-role-census-test.py` instead. // Every language's module is compiled unconditionally, so the // comparison needs no grammar and runs in every build. A missing // `python3` is a failure, not a skip: a pass that ran nothing would @@ -2763,6 +2859,45 @@ mod tests { } } + // An owner's parent list (#1794) in every terminal it reaches, each + // the only chain reader of its row — the `Container`'s `opens_by` is + // marked `no_chain` — so the row's `CHAIN_GATED` is the list's + // alone. Every list names the decisive parent *second*, so a clause + // that read only the first alternative would miss it, and the + // fixture spells each owner under its listed parent and away from + // it, so a terminal that dropped the list would answer both alike. + // The `never` `when` fns are the other half: a terminal that dropped + // the `when` would pay at the leaf, or be callable, where the list + // admits the node. + mod dsl_parent_gates { + use super::{always, class_or_interface_no_chain, never}; + use crate::Java; + + role_table! { + lang: Java; + Branch { owns [IfStatement(under [ClassBody, Block])] } + Loop { owns [WhileStatement(not_under [ClassBody, Block])] } + ElseIf { + owns [ + IfStatement(pays_itself not_under [ClassBody, Block]), + DoStatement(pays_itself_when always under [ClassBody, Block]), + WhileStatement(pays_itself_when never under [ClassBody, Block]), + ] + pays [] + } + FuncOpener { + owns [ + ConstructorDeclaration(opens Function callable_when never under [Program, ClassBody]), + MethodDeclaration(callable opens Function under [Program, ClassBody]), + LambdaExpression(opens Function callable_when always not_under [ClassBody, VariableDeclarator]), + ] + } + Container { + owns [ClassDeclaration(opens_by class_or_interface_no_chain no_chain under [InterfaceBody, Program])] + } + } + } + /// `opens_by`'s proof: a class named `I` is an `Interface`, any /// other a `Class`. pub(super) fn class_or_interface<'a>( @@ -3112,6 +3247,190 @@ mod tests { ); } + /// The `dsl_parent_gates` fixture: each owner of that table spelled + /// under the parent its list names and away from it. + #[cfg(feature = "java")] + const PARENT_LIST_FIXTURE: &[u8] = b"class A {\n\ + A() { }\n\ + void m(boolean a) {\n\ + if (a) { } else if (a) { }\n\ + while (a) while (a) { }\n\ + do { } while (a);\n\ + if (a) do { } while (a);\n\ + Runnable r = () -> { };\n\ + run(() -> { });\n\ + }\n\ + class B { }\n\ + }\n\ + interface I { void g(); }\n"; + + /// An owner's `under` / `not_under` list (#1794) in `owns`, each + /// owner asked under the parent its list names and away from it, the + /// parent recorded beside every answer. The parent kinds are tests, + /// not claims, so no kind list names them. + #[cfg(feature = "java")] + #[test] + fn a_parent_list_gates_an_owner_on_its_parents_kind() { + use crate::JavaCode; + use crate::test_support::for_each_node_with_chain; + use dsl_parent_gates::{branch, container, r#loop}; + let source = PARENT_LIST_FIXTURE; + let (mut branches, mut loops) = (Vec::new(), Vec::new()); + for_each_node_with_chain::(source, |node, chain| { + let a = Ancestors::known(chain); + let parent = chain.last().map_or("", |p| p.kind()); + if node.kind_id() == Java::IfStatement as u16 { + branches.push((parent, branch::owns(node, source, a))); + } + if node.kind_id() == Java::WhileStatement as u16 { + loops.push((parent, r#loop::owns(node, source, a))); + } + }); + // `under [ClassBody, Block]`: the two `if`s in the block, not + // the `else if` under its outer `if`. + assert_eq!( + branches, + [("block", true), ("if_statement", false), ("block", true)] + ); + // `not_under [ClassBody, Block]`: the inner `while` only. + assert_eq!(loops, [("block", false), ("while_statement", true)]); + assert_eq!(branch::OWNERS, &[Java::IfStatement as u16]); + assert_eq!(container::OWNERS, &[Java::ClassDeclaration as u16]); + } + + /// A list beside `pays_itself` and `pays_itself_when` (#1794): the + /// leaf pays where the list admits the owner and only there, and a + /// `pays_itself_when` still asks its `when`. + #[cfg(feature = "java")] + #[test] + fn a_parent_list_gates_a_self_paying_owner_at_the_leaf() { + use crate::JavaCode; + use crate::test_support::for_each_node_with_chain; + use dsl_parent_gates::else_if; + let source = PARENT_LIST_FIXTURE; + let mut chained = Vec::new(); + for_each_node_with_chain::(source, |node, chain| { + let a = Ancestors::known(chain); + if matches!( + node.kind_id().into(), + Java::IfStatement | Java::WhileStatement | Java::DoStatement + ) { + chained.push(( + node.kind(), + chain.last().map_or("", |p| p.kind()), + else_if::owns(node, source, a), + else_if::pays_at_leaf(node, source, a), + )); + } + }); + // `pays_itself` beside `not_under`: the `else if` pays; the `do` + // pays under `always` in the block, not under the `if`; the + // `while` is admitted by its list and owns, and pays nowhere + // under `never`. + assert_eq!( + chained, + [ + ("if_statement", "block", false, false), + ("if_statement", "if_statement", true, true), + ("while_statement", "block", true, false), + ("while_statement", "while_statement", false, false), + ("do_statement", "block", true, true), + ("if_statement", "block", false, false), + ("do_statement", "if_statement", false, false), + ] + ); + } + + /// A list in `is_callable`, beside `callable` and `callable_when`, + /// and in the `opens_space` fold, beside `opens` and `opens_by` + /// (#1794). + #[cfg(feature = "java")] + #[test] + fn a_parent_list_gates_callables_and_the_opens_space_fold() { + use crate::test_support::for_each_node_with_chain; + use crate::{JavaCode, SpaceKind}; + use dsl_parent_gates::{func_opener, opens_space}; + let source = PARENT_LIST_FIXTURE; + let mut openers = Vec::new(); + for_each_node_with_chain::(source, |node, chain| { + let a = Ancestors::known(chain); + if matches!( + node.kind_id().into(), + Java::ClassDeclaration + | Java::ConstructorDeclaration + | Java::MethodDeclaration + | Java::LambdaExpression + ) { + openers.push(( + node.kind(), + chain.last().map_or("", |p| p.kind()), + func_opener::owns(node, source, a), + func_opener::is_callable(node, source, a), + opens_space(node, source, a), + )); + } + }); + // The constructor is admitted and never callable; the method is + // callable in the class and nothing in the interface; the lambda + // is nothing in its declarator and callable as an argument. The + // top-level class opens through its `opens_by`, the nested one + // not at all. + assert_eq!( + openers, + [ + ( + "class_declaration", + "program", + false, + false, + SpaceKind::Class + ), + ( + "constructor_declaration", + "class_body", + true, + false, + SpaceKind::Function + ), + ( + "method_declaration", + "class_body", + true, + true, + SpaceKind::Function + ), + ( + "lambda_expression", + "variable_declarator", + false, + false, + SpaceKind::Unknown + ), + ( + "lambda_expression", + "argument_list", + true, + true, + SpaceKind::Function + ), + ( + "class_declaration", + "class_body", + false, + false, + SpaceKind::Unknown + ), + ( + "method_declaration", + "interface_body", + false, + false, + SpaceKind::Unknown + ), + ] + ); + } + /// `canonical()` names the row's mode as its own field, so the /// Python reader is held to the mode and not only to the lists it /// prints (#1745): a split row with payers and one without both @@ -3298,8 +3617,10 @@ mod tests { assert_eq!(*text_gated, *order != "gated_by, not text", "{order}"); } // `no_chain` leaves the byte axis alone: a marked text gate is - // still text-gated, a marked plain gate still is not. + // still text-gated, a marked plain gate still is not. A parent + // list reads no bytes (#1794). let marked: &[(&str, bool, bool)] = &[ + ("under, alone", dsl_parent_gates::branch::TEXT_GATED, false), ( "text_gated_by … no_chain", dsl_no_chain::catch::TEXT_GATED, @@ -3324,7 +3645,7 @@ mod tests { /// case: it reads the chain and is outside `CHAIN_GATED`. #[test] fn text_and_chain_flags_are_independent_on_the_production_rows() { - use crate::roles::{groovy, java, javascript, kotlin, ruby}; + use crate::roles::{groovy, java, javascript, kotlin, python, ruby}; type Flags = (bool, bool); let rows: &[(&str, Flags, Flags)] = &[ ( @@ -3377,6 +3698,19 @@ mod tests { (java::null_safe::TEXT_GATED, java::null_safe::CHAIN_GATED), (false, false), ), + ( + "python Guard `under [CaseClause]`, its only owner: chain, no bytes", + (python::guard::TEXT_GATED, python::guard::CHAIN_GATED), + (false, true), + ), + ( + "java DeclKeyword `not_under [ClassLiteral]`, its only gate: chain, no bytes", + ( + java::decl_keyword::TEXT_GATED, + java::decl_keyword::CHAIN_GATED, + ), + (false, true), + ), ( "java Exit, kind-only", (java::exit::TEXT_GATED, java::exit::CHAIN_GATED), @@ -3469,6 +3803,28 @@ mod tests { true, ), ("kind-only owners", dsl_gates::guard::CHAIN_GATED, false), + // A parent list, the row's only chain reader (#1794). + ("under alone", dsl_parent_gates::branch::CHAIN_GATED, true), + ( + "not_under alone", + dsl_parent_gates::r#loop::CHAIN_GATED, + true, + ), + ( + "a list beside pays_itself and pays_itself_when", + dsl_parent_gates::else_if::CHAIN_GATED, + true, + ), + ( + "a list beside callable and callable_when", + dsl_parent_gates::func_opener::CHAIN_GATED, + true, + ), + ( + "a list beside a no_chain opens_by", + dsl_parent_gates::container::CHAIN_GATED, + true, + ), ]; for (order, got, want) in synthetic { assert_eq!(got, want, "{order}"); diff --git a/big-code-analysis-ast/src/roles/python.rs b/big-code-analysis-ast/src/roles/python.rs index 9e173c0f4..344fc3f38 100644 --- a/big-code-analysis-ast/src/roles/python.rs +++ b/big-code-analysis-ast/src/roles/python.rs @@ -56,14 +56,6 @@ fn sole_statement_of_else_block<'a>( }) } -/// Whether an `if_clause` is a `case` guard rather than a comprehension's -/// filter (`[y for y in x if y]`), which the grammar spells with the same -/// kind. An owner's parent gate, which the DSL's `under` (a payer -/// attribute) does not spell. -fn under_case_clause<'a>(node: &Node<'a>, _code: &[u8], ancestors: Ancestors<'a, '_>) -> bool { - ancestors.parent_has_kind(node, Python::CaseClause as u16) -} - /// `python_is_bound_self_attribute`, under the row's gate signature. fn is_bound_self_attribute<'a>(node: &Node<'a>, code: &[u8], ancestors: Ancestors<'a, '_>) -> bool { python_is_bound_self_attribute(node, code, ancestors) @@ -151,12 +143,13 @@ role_table! { ] } // A `case X if g:` guard is an `if_clause` under the `case_clause` — - // the same kind a comprehension filter has, so the owner is gated to - // the clause — one decision paid at the node: ABC walks its - // expression as a boolean slot, and cyclomatic counts the `if` - // keyword wherever it is written, which Halstead bills likewise. + // the same kind a comprehension filter (`[y for y in x if y]`) has, + // so the owner is gated to that parent — one decision paid at the + // node: ABC walks its expression as a boolean slot, and cyclomatic + // counts the `if` keyword wherever it is written, which Halstead + // bills likewise. Guard { - owns [IfClause(gated_by under_case_clause)] + owns [IfClause(under [CaseClause])] excludes [If "the keyword the `if` statement's kind spells, counted and billed as such"] } // `a if c else b` is a `conditional_expression` with no field and diff --git a/big-code-analysis-ast/src/roles/tsx.rs b/big-code-analysis-ast/src/roles/tsx.rs index abfa02fc2..2b8a2fb20 100644 --- a/big-code-analysis-ast/src/roles/tsx.rs +++ b/big-code-analysis-ast/src/roles/tsx.rs @@ -179,7 +179,7 @@ role_table! { owns [ ..js_family_doc_targets!(), ..ts_family_doc_targets!(), - String2(gated_by under_enum_body), + String2(under [EnumBody]), ] } DocRunOpener { absent "TSDoc attaches every doc comment to a declaration or the module; none documents by its own content" } diff --git a/big-code-analysis-ast/src/roles/typescript.rs b/big-code-analysis-ast/src/roles/typescript.rs index 7ae4a6823..fc24a537f 100644 --- a/big-code-analysis-ast/src/roles/typescript.rs +++ b/big-code-analysis-ast/src/roles/typescript.rs @@ -212,7 +212,7 @@ role_table! { owns [ ..js_family_doc_targets!(), ..ts_family_doc_targets!(), - String(gated_by under_enum_body), + String(under [EnumBody]), ] } DocRunOpener { absent "TSDoc attaches every doc comment to a declaration or the module; none documents by its own content" } diff --git a/utils/check-role-census-test.py b/utils/check-role-census-test.py index 22ff86b54..f6f093caa 100644 --- a/utils/check-role-census-test.py +++ b/utils/check-role-census-test.py @@ -455,6 +455,70 @@ def test_holds_payer_and_under_are_read(self) -> None: [("EQEQ", None, ()), ("LT", None, ("BinaryExpression", "Fold")), ("GT", None, ("Fold",)), ("Instanceof", None, ("Call",))], ) + def test_owner_parent_lists_are_read_and_read_the_chain(self) -> None: + # An owner's `under [..]` / `not_under [..]` (#1794): bracketed + # and non-empty, inside a fragment as on the row, spaced or not. + # A list sets `chain_gated` on its own — `Static`'s `opens_by` is + # marked, and `Exit`'s second owner is kind-only — and its kinds + # are tests, not claims, so `raw_kinds()` leaves them out. + (self.t.roles / "ts.rs").write_text( + "macro_rules! enum_members {\n" + " (@splice $cont:tt [$($acc:tt)*] $($rest:tt)*) => {\n" + " $crate::role_table!(@owners $cont [$($acc)* PropertyIdentifier(under [EnumBody]), " + "Computed(under [EnumBody, Fold,]),] $($rest)*);\n" + " };\n" + "}\n" + ) + self.t.write( + "java", + " lang: Java;\n" + " DocTarget { owns [..enum_members!(), Class(not_under [ClassLiteral]), " + "Static(not_under[Import, Requires] opens_by h no_chain), Plain] }\n" + " Exit { owns [ReturnStatement(under [Block]), ThrowStatement] }\n" + " Modifier { owns [Public] }\n", + ) + rows = rt.parse_table(self.t.roles / "java.rs").rows + self.assertEqual( + [(o.kind, o.under, o.not_under, o.gate, o.chain_gated) for o in rows["DocTarget"].owners], + [ + ("PropertyIdentifier", ("EnumBody",), (), None, True), + ("Computed", ("EnumBody", "Fold"), (), None, True), + ("Class", (), ("ClassLiteral",), None, True), + ("Static", (), ("Import", "Requires"), None, True), + ("Plain", (), (), None, False), + ], + ) + self.assertEqual(rows["DocTarget"].raw_kinds(), ["PropertyIdentifier", "Computed", "Class", "Static", "Plain"]) + self.assertEqual( + [(role, rows[role].chain_gated) for role in ("DocTarget", "Exit", "Modifier")], + [("DocTarget", True), ("Exit", True), ("Modifier", False)], + ) + # What the macro rejects is an error here: a bare kind, an empty + # or unreadable list, a list beside a gate or `holds_payer` in + # either order, two lists, and a `no_chain` after one. + for bad in ( + "A(under Block)", + "A(under)", + "A(under [])", + "A(not_under [ ])", + "A(under [B C])", + "A(under [B,,C])", + "A(under [B] gated_by g)", + "A(gated_by g under [B])", + "A(holds_payer under [B])", + "A(under [B] holds_payer)", + "A(under [B] not_under [C])", + "A(under [B] no_chain)", + ): + self.t.write("java", f" lang: Java;\n Exit {{ owns [{bad}] }}\n") + with self.assertRaises(rt.RoleTableError, msg=bad): + rt.parse_table(self.t.roles / "java.rs") + # The payer's list shares the parser, so it is held to the same + # list shape. + self.t.write("java", " lang: Java;\n Call { owns [A] pays [EQEQ under [B,,C]] }\n") + with self.assertRaises(rt.RoleTableError, msg="payer"): + rt.parse_table(self.t.roles / "java.rs") + def test_self_paying_owners_are_read_in_both_spellings(self) -> None: # `pays_itself` and `pays_itself_when f` both mark a self-paying # owner (#1695); the differential test compares kinds only, so diff --git a/utils/role_tables.py b/utils/role_tables.py index c3927ee08..8e216e392 100755 --- a/utils/role_tables.py +++ b/utils/role_tables.py @@ -279,14 +279,22 @@ class Owner: # the gate under which it is one (#1696). callable: bool = False callable_when: str | None = None + # `under [P, Q]` / `not_under [P, Q]`: the parent kinds the owner is + # gated to, or away from (#1794). The owner's gate, so exclusive with + # `gate` and `holds_payer`; the kinds are not claimed by the row. + under: tuple[str, ...] = () + not_under: tuple[str, ...] = () @property def chain_gated(self) -> bool: """Whether this owner's gate or `opens_by` fn takes the chain — the macro's per-owner term of `CHAIN_GATED` (#1793), which - reads neither `callable_when` nor `pays_itself_when`.""" - return (self.gate is not None and not self.gate_no_chain) or ( - self.opens_by is not None and not self.opens_by_no_chain + reads neither `callable_when` nor `pays_itself_when`. A parent + list always reads it (#1794).""" + return ( + (self.gate is not None and not self.gate_no_chain) + or (self.opens_by is not None and not self.opens_by_no_chain) + or bool(self.under or self.not_under) ) @@ -396,6 +404,21 @@ def _string_at(source: str, spans: list[tuple[int, int]], start: int, end: int) rf"({IDENT})" rf"(?:\s+(?:text_)?gated_by\s+({IDENT})|\s+under\s+(?:({IDENT})|\[([^\]]*)\]))?\s*$" ) +# An owner's attribute words: a bracketed parent list is one token, and a +# stray bracket one of its own, so it reaches the attribute loop and is +# reported there rather than skipped. +ATTR_TOKEN_RE = re.compile(r"\[[^\[\]]*\]|[^\s\[\]]+|\S") +# A parent list's inside: one or more kinds, a trailing comma allowed — +# what `$($p:ident),+ $(,)?` accepts. +PARENT_LIST_RE = re.compile(rf"\s*{IDENT}(?:\s*,\s*{IDENT})*\s*,?\s*") + + +def _parent_list(inner: str) -> tuple[str, ...] | None: + """The kinds of an `under [..]` / `not_under [..]` list body, or + ``None`` where the macro would reject it (empty, or not kinds).""" + if not PARENT_LIST_RE.fullmatch(inner): + return None + return tuple(re.findall(IDENT, inner)) def _parse_owner(entry: str, line: int, path: pathlib.Path) -> Owner: @@ -413,7 +436,9 @@ def _parse_owner(entry: str, line: int, path: pathlib.Path) -> Owner: holds_payer = False callable_ = False callable_when = None - attrs = (m.group(3) or "").split() + under: tuple[str, ...] = () + not_under: tuple[str, ...] = () + attrs = ATTR_TOKEN_RE.findall(m.group(3) or "") def no_chain_after(i: int) -> bool: # `no_chain` is a trailing modifier on the fn it follows (#1793); @@ -427,10 +452,12 @@ def no_chain_after(i: int) -> bool: if a == "holds_payer": if holds_payer: raise RoleTableError(f"{path}:{line}: `{kind}` repeats `holds_payer`") + if under or not_under: + raise RoleTableError(f"{path}:{line}: `{kind}` has a malformed or repeated gate") holds_payer = True i += 1 elif a in ("gated_by", "text_gated_by"): - if gate is not None or i + 1 >= len(attrs): + if gate is not None or under or not_under or i + 1 >= len(attrs): raise RoleTableError(f"{path}:{line}: `{kind}` has a malformed or repeated gate") gate = attrs[i + 1] text_gated = a == "text_gated_by" @@ -438,6 +465,22 @@ def no_chain_after(i: int) -> bool: if no_chain_after(i): gate_no_chain = True i += 1 + elif a in ("under", "not_under"): + # The owner's parent list fills its one gate slot (#1794), + # and the macro takes it bracketed and non-empty only. + if gate is not None or holds_payer or under or not_under or i + 1 >= len(attrs): + raise RoleTableError(f"{path}:{line}: `{kind}` has a malformed or repeated gate") + token = attrs[i + 1] + parents = _parent_list(token[1:-1]) if token.startswith("[") and token.endswith("]") else None + if parents is None: + raise RoleTableError( + f"{path}:{line}: `{kind}`: `{a}` takes a bracketed, non-empty kind list, not `{token}`" + ) + if a == "under": + under = parents + else: + not_under = parents + i += 2 elif a == "pays_itself": if pays_itself: raise RoleTableError(f"{path}:{line}: `{kind}` repeats `pays_itself`") @@ -485,6 +528,8 @@ def no_chain_after(i: int) -> bool: holds_payer, callable_, callable_when, + under, + not_under, ) @@ -654,9 +699,10 @@ def expect_list(keyword: str) -> tuple[str, int, int] | None: if pm.group(3): under = (pm.group(3),) elif pm.group(4) is not None: - under = tuple(p.strip() for p in pm.group(4).split(",") if p.strip()) - if not under or any(not re.fullmatch(IDENT, p) for p in under): + parsed = _parent_list(pm.group(4)) + if parsed is None: raise RoleTableError(f"{path}:{line}: `{role}`: unreadable `under` list on `{pm.group(1)}`") + under = parsed row.payers.append(Payer(pm.group(1), pm.group(2), under)) pm = re.match(r"\s*project\s+", body[pos:]) if pm: From 8f5bee37aae155022707f56ebe4fcfabdb81fb6b Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Thu, 5 Nov 2026 22:53:29 -0800 Subject: [PATCH 09/25] test(roles): pin parent-list rejections in Rust The macro's owner parent-list rejections were pinned only on the Python reader's side, so a reordering of the @scan arms could accept one with no Rust test failing. roles/parent_list_doctests.rs, a cfg(doctest) module, now holds one compile_fail doctest per rejected shape beside a control that compiles: a list after or before gated_by, before text_gated_by, before or after holds_payer, two lists on one owner, and an empty list. The two parent-list doctests that sat on the macro move there, which keeps them out of roles/mod.rs; the module declaration costs that file two code lines (loc.ploc 954 -> 956, loc.sloc 2321 -> 2304, baseline refreshed). The Python Guard row comment drops the consumers' reading, which src/metrics/abc/python.rs and the row's excludes reason already carry, and keeps the grammar fact. Refs #1794 --- .bca-baseline.toml | 4 +- big-code-analysis-ast/src/roles/mod.rs | 29 +---- .../src/roles/parent_list_doctests.rs | 105 ++++++++++++++++++ big-code-analysis-ast/src/roles/python.rs | 10 +- 4 files changed, 117 insertions(+), 31 deletions(-) create mode 100644 big-code-analysis-ast/src/roles/parent_list_doctests.rs diff --git a/.bca-baseline.toml b/.bca-baseline.toml index 1a27456e7..6aaef12e9 100644 --- a/.bca-baseline.toml +++ b/.bca-baseline.toml @@ -365,13 +365,13 @@ value = 5.0 path = "big-code-analysis-ast/src/roles/mod.rs" qualified = "" metric = "loc.ploc" -value = 954.0 +value = 956.0 [[entry]] path = "big-code-analysis-ast/src/roles/mod.rs" qualified = "" metric = "loc.sloc" -value = 2321.0 +value = 2304.0 [[entry]] path = "big-code-analysis-ast/src/tools.rs" diff --git a/big-code-analysis-ast/src/roles/mod.rs b/big-code-analysis-ast/src/roles/mod.rs index be0612c58..f6b2b4443 100644 --- a/big-code-analysis-ast/src/roles/mod.rs +++ b/big-code-analysis-ast/src/roles/mod.rs @@ -717,6 +717,10 @@ mod control_flow_tests; #[cfg(test)] mod doc_tests; +// The owner parent-list rejections as `compile_fail` doctests (#1794). +#[cfg(doctest)] +mod parent_list_doctests; + // Cross-consumer parity derived from the rows themselves, on every // candidate node of the corpus (#1700). A full-enum sweep with an // `is_enabled()` filter and a non-vacuity assertion, so it is absent @@ -1083,29 +1087,8 @@ impl RowView { /// # fn main() {} /// ``` /// -/// A parent list is the owner's gate, so it sits beside no other, and -/// it names at least one kind (#1794): -/// -/// ```compile_fail -/// # #[macro_use] extern crate big_code_analysis_ast; -/// # use big_code_analysis_ast::{Ancestors, Java, Node}; -/// fn always(_: &Node<'_>, _: &[u8], _: Ancestors<'_, '_>) -> bool { true } -/// role_table! { -/// lang: Java; -/// Exit { owns [ReturnStatement(under [Block] gated_by always)] } -/// } -/// # fn main() {} -/// ``` -/// -/// ```compile_fail -/// # #[macro_use] extern crate big_code_analysis_ast; -/// # use big_code_analysis_ast::Java; -/// role_table! { -/// lang: Java; -/// Exit { owns [ReturnStatement(not_under [])] } -/// } -/// # fn main() {} -/// ``` +/// The owner parent-list rejections (#1794) are pinned in +/// `roles/parent_list_doctests.rs`, beside a control that compiles. /// /// And a kind owned by two rows of the same role: /// diff --git a/big-code-analysis-ast/src/roles/parent_list_doctests.rs b/big-code-analysis-ast/src/roles/parent_list_doctests.rs new file mode 100644 index 000000000..dc6608a96 --- /dev/null +++ b/big-code-analysis-ast/src/roles/parent_list_doctests.rs @@ -0,0 +1,105 @@ +//! The owner parent-list shapes `role_table!` rejects (#1794), each a +//! `compile_fail` doctest that differs from the control below in one +//! respect only. Kept off the macro's own doc so they do not count +//! against `roles/mod.rs`: this module exists only under `cfg(doctest)`, +//! where rustdoc collects a private module's doc comments too. +//! +//! The control: every attribute the rejections combine, one per owner. +//! +//! ``` +//! # #[macro_use] extern crate big_code_analysis_ast; +//! # use big_code_analysis_ast::{Ancestors, Java, Node}; +//! fn always(_: &Node<'_>, _: &[u8], _: Ancestors<'_, '_>) -> bool { true } +//! role_table! { +//! lang: Java; +//! Exit { +//! owns [ReturnStatement(gated_by always), ThrowStatement(under [Block]), +//! YieldStatement(not_under [ClassBody])] +//! } +//! Comparison { +//! owns [BinaryExpression(holds_payer), InstanceofExpression(text_gated_by always)] +//! pays [EQEQ] +//! } +//! } +//! # fn main() {} +//! ``` +//! +//! A parent list is the owner's gate, so it sits beside no other gate +//! and no `holds_payer`, in either order: +//! +//! ```compile_fail +//! # #[macro_use] extern crate big_code_analysis_ast; +//! # use big_code_analysis_ast::{Ancestors, Java, Node}; +//! fn always(_: &Node<'_>, _: &[u8], _: Ancestors<'_, '_>) -> bool { true } +//! role_table! { +//! lang: Java; +//! Exit { owns [ReturnStatement(under [Block] gated_by always)] } +//! } +//! # fn main() {} +//! ``` +//! +//! ```compile_fail +//! # #[macro_use] extern crate big_code_analysis_ast; +//! # use big_code_analysis_ast::{Ancestors, Java, Node}; +//! fn always(_: &Node<'_>, _: &[u8], _: Ancestors<'_, '_>) -> bool { true } +//! role_table! { +//! lang: Java; +//! Exit { owns [ReturnStatement(gated_by always under [Block])] } +//! } +//! # fn main() {} +//! ``` +//! +//! ```compile_fail +//! # #[macro_use] extern crate big_code_analysis_ast; +//! # use big_code_analysis_ast::{Ancestors, Java, Node}; +//! fn always(_: &Node<'_>, _: &[u8], _: Ancestors<'_, '_>) -> bool { true } +//! role_table! { +//! lang: Java; +//! Comparison { owns [InstanceofExpression(under [Block] text_gated_by always)] pays [EQEQ] } +//! } +//! # fn main() {} +//! ``` +//! +//! ```compile_fail +//! # #[macro_use] extern crate big_code_analysis_ast; +//! # use big_code_analysis_ast::Java; +//! role_table! { +//! lang: Java; +//! Comparison { owns [BinaryExpression(holds_payer under [Block])] pays [EQEQ] } +//! } +//! # fn main() {} +//! ``` +//! +//! ```compile_fail +//! # #[macro_use] extern crate big_code_analysis_ast; +//! # use big_code_analysis_ast::Java; +//! role_table! { +//! lang: Java; +//! Comparison { owns [BinaryExpression(under [Block] holds_payer)] pays [EQEQ] } +//! } +//! # fn main() {} +//! ``` +//! +//! An owner takes one list, so not one of each direction: +//! +//! ```compile_fail +//! # #[macro_use] extern crate big_code_analysis_ast; +//! # use big_code_analysis_ast::Java; +//! role_table! { +//! lang: Java; +//! Exit { owns [ThrowStatement(under [Block] not_under [ClassBody])] } +//! } +//! # fn main() {} +//! ``` +//! +//! And a list names at least one kind: +//! +//! ```compile_fail +//! # #[macro_use] extern crate big_code_analysis_ast; +//! # use big_code_analysis_ast::Java; +//! role_table! { +//! lang: Java; +//! Exit { owns [YieldStatement(not_under [])] } +//! } +//! # fn main() {} +//! ``` diff --git a/big-code-analysis-ast/src/roles/python.rs b/big-code-analysis-ast/src/roles/python.rs index 344fc3f38..094fe8515 100644 --- a/big-code-analysis-ast/src/roles/python.rs +++ b/big-code-analysis-ast/src/roles/python.rs @@ -142,12 +142,10 @@ role_table! { CARET "a boolean `^` is the integral `^`'s kind, which the grammar does not tell apart", ] } - // A `case X if g:` guard is an `if_clause` under the `case_clause` — - // the same kind a comprehension filter (`[y for y in x if y]`) has, - // so the owner is gated to that parent — one decision paid at the - // node: ABC walks its expression as a boolean slot, and cyclomatic - // counts the `if` keyword wherever it is written, which Halstead - // bills likewise. + // A `case X if g:` guard is an `if_clause` under the `case_clause`; + // a comprehension filter (`[y for y in x if y]`) is the same kind + // directly under the comprehension, so the owner is gated to that + // parent. Guard { owns [IfClause(under [CaseClause])] excludes [If "the keyword the `if` statement's kind spells, counted and billed as such"] From 62a45757e1ae57d5a6b7346a44afb2fdbc6f33a0 Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Thu, 5 Nov 2026 23:26:20 -0800 Subject: [PATCH 10/25] fix(find): render nested matches in linear time MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `bca find` rendered each match with its own `dump_node_with_color` call at depth 1. Each call chose the match's connector by asking `Node::parent`, which climbs from the root: O(depth) per match, 98% of the 397 ms it took on 4 000 nested Tcl braces. Each single-row match also printed its whole span, so a match nested k deep had its bytes printed k times: 16 MB of output for an 8 KB file. The CLI now renders a file's matches in one pass through the hidden `dump_found_with_color`. A match is flush-left iff it is the tree root, decided by node id, and a match nested in a single-row match is printed as `…` in the outer line, its own text following on its own line. Unnested matches print byte-identically to before, colour included. Depth 4 000 now takes 5.8 ms against `count`'s 4.9 ms, and prints 243 KB. `Workload::Find` and the `find/tcl-nested-braces` probe, with its `count` control, price the render on a 4 000 / 8 000 / 16 000 ladder. Reinstating the climb fits 2.00 and the whole-span text 1.84, against 0.99 clean. Fixes #1416 --- .bca-baseline.toml | 6 + big-code-analysis-bench/src/shapes.rs | 130 ++++- big-code-analysis-book/src/commands/nodes.md | 20 + .../src/recipes/ast-queries.md | 4 +- big-code-analysis-cli/src/dispatch.rs | 26 +- .../tests/output/dump_headers.rs | 67 ++- docs/development/benchmarking.md | 30 +- src/lib.rs | 4 + src/output/dump.rs | 548 +++++++++++++++++- 9 files changed, 787 insertions(+), 48 deletions(-) diff --git a/.bca-baseline.toml b/.bca-baseline.toml index 6aaef12e9..441464048 100644 --- a/.bca-baseline.toml +++ b/.bca-baseline.toml @@ -1315,6 +1315,12 @@ qualified = "dump_node" metric = "nargs" value = 5.0 +[[entry]] +path = "src/output/dump.rs" +qualified = "render_found" +metric = "nexits" +value = 5.0 + [[entry]] path = "src/output/dump.rs" qualified = "write_node_line" diff --git a/big-code-analysis-bench/src/shapes.rs b/big-code-analysis-bench/src/shapes.rs index c6c818e5f..bd27635d3 100644 --- a/big-code-analysis-bench/src/shapes.rs +++ b/big-code-analysis-bench/src/shapes.rs @@ -1462,6 +1462,16 @@ pub fn tcl_nested_eval(depth: usize) -> String { format!("{}puts hi{}\n", "eval {".repeat(depth), "}".repeat(depth)) } +/// Tcl: `x {{…{a b}…}}`, `depth` braces deep on one row. +/// +/// #1416's fixture: one `braced_word` per level, two AST levels apart +/// (`braced_word` → `command` → `braced_word`), each a single-row match +/// for `-t braced_word` whose span holds every level inside it. +#[must_use] +pub fn tcl_nested_braces(depth: usize) -> String { + format!("x {}a b{}\n", "{".repeat(depth), "}".repeat(depth)) +} + /// Tcl: one `eval` line of `width` `{a b} "x"` pairs with a stray `]` /// in the middle of its argument list. /// @@ -1505,7 +1515,8 @@ pub fn tcl_wide_switch(width: usize) -> String { /// `Ast::count` walk `bca find` shares, and the `Ast::dump` export — /// and they share no options type, so the selection a metric probe /// needs lives on the variant that uses it rather than on every probe -/// (#1110). +/// (#1110). `Find` is the count walk plus the renderer `bca find` prints +/// its matches through. #[derive(Clone, Copy)] pub enum Workload { /// `Ast::metrics` under `selection`. @@ -1537,6 +1548,15 @@ pub enum Workload { /// The filter, as `bca count --type` spells it. filter: &'static str, }, + /// `bca find`: `Ast::find` under one filter, then the CLI's + /// renderer (`write_found`, the sink form of what `bca find` prints + /// through) into a sink that reads every byte (#1416). Its reading + /// is the lines rendered, one per match, which equals the `Count` + /// reading on the same shape. + Find { + /// The filter, as `bca find --type` spells it. + filter: &'static str, + }, /// `Ast::dump`, the AST export (#1684). Its reading is the number /// of nodes exported, counted after the export and before its /// teardown, so the timing is construction + that count + drop. @@ -1566,7 +1586,9 @@ impl Workload { } => MetricsOptions::default() .with_only(selection) .with_exclude_tests(exclude_tests), - Self::Ops { .. } | Self::Count { .. } | Self::Dump { .. } => MetricsOptions::default(), + Self::Ops { .. } | Self::Count { .. } | Self::Find { .. } | Self::Dump { .. } => { + MetricsOptions::default() + } } } @@ -1587,6 +1609,11 @@ impl Workload { /// /// Whatever the underlying seam raises — in practice, a language /// feature disabled in the build. + /// + /// # Panics + /// + /// Never in practice: the only fallible step outside the seams is + /// [`Workload::Find`]'s render, whose sink accepts every write. pub fn walk(self, ast: &Ast, options: MetricsOptions) -> Result { Ok(match self { Self::Metrics { reading, .. } => reading(&black_box(ast.metrics(options)?).metrics), @@ -1595,6 +1622,13 @@ impl Workload { let (matching, _) = black_box(ast.count(&[filter.to_owned()])); u64::try_from(matching).unwrap_or(u64::MAX) } + Self::Find { filter } => { + let found = ast.find(&[filter.to_owned()])?; + let mut sink = RenderedLines(0); + big_code_analysis::write_found(&mut sink, ast, &found, ..) + .expect("RenderedLines never fails a write"); + sink.0 + } Self::Dump { span, comment } => { let cfg = AstCfg { id: String::new(), @@ -1609,6 +1643,29 @@ impl Workload { } } +/// The `Find` workload's sink: counts the lines written to it. +/// +/// It reads every byte rather than discarding them as `io::sink` does, +/// because the volume a render writes is half of what the probe prices: +/// a renderer that printed each nested match's text again would cost +/// nothing against a sink that never looks. +struct RenderedLines(u64); + +impl std::io::Write for RenderedLines { + // `bytecount` would be a dependency for one bench sink; this loop is + // what the probe means by reading every byte. + #[allow(clippy::naive_bytecount)] + fn write(&mut self, buf: &[u8]) -> std::io::Result { + let lines = buf.iter().filter(|byte| **byte == b'\n').count(); + self.0 += u64::try_from(lines).unwrap_or(u64::MAX); + Ok(buf.len()) + } + + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } +} + /// How many nodes an export holds, counted on an explicit stack: the /// depth shapes export thousands of levels, which a recursive count /// would overflow on. @@ -1772,6 +1829,13 @@ const PAREN_CAP_DEPTHS: [usize; 3] = [50, 100, 200]; /// the defect present is no probe; these sizes are where it goes red. const CONDITIONAL_PER_DEPTH_DEPTHS: [usize; 3] = [4_000, 8_000, 16_000]; +/// Depths for `find/tcl-nested-braces` and its control, the same two +/// rungs above [`LINEAR_DEPTHS`] and for the same reason. A renderer +/// that printed each match's whole span wrote `depth²` bytes against a +/// per-match cost the bytes take thousands of levels to overtake: on +/// [`LINEAR_DEPTHS`] it read 1.56, 0.06 past the bound (#1416). +const FIND_RENDER_DEPTHS: [usize; 3] = [4_000, 8_000, 16_000]; + /// Depths for the three #1767 probes, one rung above [`LINEAR_DEPTHS`]. /// Each prices an ancestor question with no stop near, folded down the /// walk's chain instead of climbed per node. On [`LINEAR_DEPTHS`] the @@ -1877,6 +1941,41 @@ pub const PROBES: &[Probe] = &[ walk must keep the chain in step with its own climbs \ (#1381, #1684).", }, + Probe { + name: "count/tcl-nested-braces", + lang: LANG::Tcl, + axis: Axis::Depth, + workload: Workload::Count { + filter: "braced_word", + }, + render: tcl_nested_braces, + sizes: FIND_RENDER_DEPTHS, + max_exponent: LINEAR_BOUND, + rationale: "The walk control for `find/tcl-nested-braces`: the same \ + shape and filter through the walk `bca find` shares, \ + with nothing rendered, so a regression that moves the \ + find probe and not this one is in the renderer (#1416). \ + The reading is one match per brace level.", + }, + Probe { + name: "find/tcl-nested-braces", + lang: LANG::Tcl, + axis: Axis::Depth, + workload: Workload::Find { + filter: "braced_word", + }, + render: tcl_nested_braces, + sizes: FIND_RENDER_DEPTHS, + max_exponent: LINEAR_BOUND, + rationale: "`bca find`'s render after the walk (#1416). Each match \ + once chose its connector through `Node::parent`, an \ + `O(depth)` climb per match: reinstating it fits \ + 2.00 against 0.99. Each single-row match also \ + printed its whole span, `depth²` bytes on this shape: \ + reinstating that fits 1.84, which is why the ladder \ + starts at 4 000. The reading is the lines rendered, one \ + per match.", + }, Probe { name: "dump/tcl-wide-erroring-eval", lang: LANG::Tcl, @@ -4970,6 +5069,33 @@ mod tests { ); } + /// `find/tcl-nested-braces` renders one line per match — the + /// `count` control's reading, which is one match per brace level — + /// at every rung. [`probe_workload_is_exercised`] would pass a + /// renderer that wrote one line in total, and the timing would then + /// price nothing but the walk the control already prices (#1416). + #[test] + fn the_find_probe_renders_one_line_per_match() { + let probe = |name: &str| { + PROBES + .iter() + .find(|probe| probe.name == name) + .unwrap_or_else(|| panic!("{name} is a probe")) + }; + let (find, count) = ( + probe("find/tcl-nested-braces"), + probe("count/tcl-nested-braces"), + ); + assert_eq!(find.sizes, count.sizes); + for size in find.sizes { + let ast = parse(find, size); + let read = |probe: &Probe| probe.workload.walk(&ast, probe.workload.options()); + let lines = read(find).expect("find walks"); + assert_eq!(lines, read(count).expect("count walks"), "at depth {size}"); + assert_eq!(lines, u64::try_from(size).expect("a small size")); + } + } + /// Probe names are unique — they key the report and the gate. #[test] fn probe_names_are_unique() { diff --git a/big-code-analysis-book/src/commands/nodes.md b/big-code-analysis-book/src/commands/nodes.md index 1d33f8832..c187421cf 100644 --- a/big-code-analysis-book/src/commands/nodes.md +++ b/big-code-analysis-book/src/commands/nodes.md @@ -39,6 +39,26 @@ bca find -t ERROR -I "*.ext" /path/to/your/file/or/directory `*.rs`). Each `-I` takes exactly one value, so a following positional path is never swallowed. +## Reading `find` output {#find-output} + +`find` prints a `== ==` banner for each file with a match, then +one line per match in source order: + +```text +== src/main.rs == +╰─ {call_expression:256} from (1, 13) to (1, 26) : f(…, …) +╰─ {call_expression:256} from (1, 15) to (1, 19) : g(1) +╰─ {call_expression:256} from (1, 21) to (1, 25) : h(2) +``` + +Each line gives the node type and its `kind_id`, then the 1-based +`(row, column)` where the node starts and ends. A node that fits on +one row ends with its source text; one that spans several rows prints +none. When one match sits inside another on the same row, the inner +match's text is printed on its own line and the outer match shows `…` +in its place. Each byte of source is therefore printed at most once, +however deeply the matches nest. + ## Semantic filters {#semantic-filters} Six `-t/--type` values are not node-type names but *semantic* filters, diff --git a/big-code-analysis-book/src/recipes/ast-queries.md b/big-code-analysis-book/src/recipes/ast-queries.md index 42e5e5566..4c2c209c0 100644 --- a/big-code-analysis-book/src/recipes/ast-queries.md +++ b/big-code-analysis-book/src/recipes/ast-queries.md @@ -57,7 +57,9 @@ bca find \ -t unsafe_block ``` -Each match prints the file path and the line range of the node. +Each match prints the file path and the line range of the node; see +[Reading `find` output](../commands/nodes.md#find-output) for the +format. ## Dump the AST of a file diff --git a/big-code-analysis-cli/src/dispatch.rs b/big-code-analysis-cli/src/dispatch.rs index bdaa3a454..2fe88b587 100644 --- a/big-code-analysis-cli/src/dispatch.rs +++ b/big-code-analysis-cli/src/dispatch.rs @@ -16,15 +16,16 @@ //! preprocessor lookup key. use std::io::Write; +use std::ops::Bound; use std::path::{Path, PathBuf}; use std::sync::Arc; use std::sync::atomic::Ordering; use big_code_analysis::{ Ast, FuncSpace, LANG, MetricsError, MetricsOptions, PreprocResults, Source, - dump_function_spans_with_color, dump_node_with_color, dump_ops_with_color, - dump_root_with_color, guess_language, is_generated, preprocess, read_file_with_eol_classified, - write_file, + dump_found_with_color, dump_function_spans_with_color, dump_node_with_color, + dump_ops_with_color, dump_root_with_color, guess_language, is_generated, preprocess, + read_file_with_eol_classified, write_file, }; use crate::exemptions::FileMarkers; @@ -532,16 +533,15 @@ fn dispatch_find( // for the reason given in `dispatch_dump`. let mut out = std::io::stdout().lock(); writeln!(out, "== {} ==", path.display())?; - for node in &found { - dump_node_with_color( - ast.source(), - node, - 1, - cfg.line_start, - cfg.line_end, - cfg.color, - )?; - } + // One render for every match rather than a `dump_node_with_color` + // per match: that asked each match for its parent, `O(depth)` + // apiece, and printed each nested match's text again inside the + // match around it (#1416). + let lines = ( + cfg.line_start.map_or(Bound::Unbounded, Bound::Included), + cfg.line_end.map_or(Bound::Unbounded, Bound::Included), + ); + dump_found_with_color(&ast, &found, lines, cfg.color)?; writeln!(out)?; } Ok(()) diff --git a/big-code-analysis-cli/tests/output/dump_headers.rs b/big-code-analysis-cli/tests/output/dump_headers.rs index 81e06fa00..4b87361ef 100644 --- a/big-code-analysis-cli/tests/output/dump_headers.rs +++ b/big-code-analysis-cli/tests/output/dump_headers.rs @@ -1,5 +1,6 @@ -//! Integration tests for `bca dump` per-file headers and the -//! explicit-path requirement (issue #690). +//! Integration tests for `bca dump` / `bca find` per-file headers and +//! the explicit-path requirement (issue #690), and for how `bca find` +//! prints nested matches and honours its line range (#1416). use std::fs; @@ -215,3 +216,65 @@ fn dump_holds_the_banner_and_tree_together_under_parallel_jobs() { assert_eq!(foreign, 0, "{path}'s block absorbed another file's tree"); } } + +/// `bca find` stdout for one Rust file, uncoloured, with its path +/// replaced by ``. +fn find_stdout(source: &str, args: &[&str]) -> String { + let dir = TempDir::new().unwrap(); + let path = dir.path().join("f.rs"); + fs::write(&path, source).unwrap(); + let path = path.to_str().unwrap(); + let out = common::bca_command() + .args(["find", "--color", "never"]) + .args(args) + .arg(path) + .assert() + .success() + .get_output() + .stdout + .clone(); + String::from_utf8(out) + .expect("utf8") + .replace(path, "") +} + +/// #1416: a match nested in a single-row match prints its text on its +/// own line, and the match around it prints `…` in its place. The outer +/// line used to read `f(g(1), h(2))`, so a match nested `N` deep had its +/// bytes printed `N` times: 16 MB for an 8 KB file of nested braces. +#[test] +fn find_prints_a_nested_match_once_and_elides_it_from_the_outer() { + assert_eq!( + find_stdout("fn main() { f(g(1), h(2)); }\n", &["-t", "call_expression"]), + concat!( + "== ==\n", + "╰─ {call_expression:256} from (1, 13) to (1, 26) : f(…, …) \n", + "╰─ {call_expression:256} from (1, 15) to (1, 19) : g(1) \n", + "╰─ {call_expression:256} from (1, 21) to (1, 25) : h(2) \n", + "\n", + ) + ); +} + +/// `--line-start` / `--line-end` keep the matches whose start row lies +/// in the inclusive range, either bound optional: the CLI hands the +/// renderer one range built from the two flags (#1416). +#[test] +fn find_line_range_keeps_matches_starting_inside_it() { + let source = "fn a() {}\nfn b() {}\nfn c() {}\n"; + let names = |range: &[&str]| { + let mut args = vec!["-t", "identifier"]; + args.extend_from_slice(range); + find_stdout(source, &args) + .lines() + .filter_map(|line| { + line.rsplit_once(" : ") + .map(|(_, name)| name.trim().to_owned()) + }) + .collect::>() + }; + assert_eq!(names(&[]), ["a", "b", "c"]); + assert_eq!(names(&["--line-start", "2", "--line-end", "2"]), ["b"]); + assert_eq!(names(&["--line-start", "2"]), ["b", "c"]); + assert_eq!(names(&["--line-end", "2"]), ["a", "b"]); +} diff --git a/docs/development/benchmarking.md b/docs/development/benchmarking.md index 94e692198..f5e6caaaa 100644 --- a/docs/development/benchmarking.md +++ b/docs/development/benchmarking.md @@ -230,6 +230,8 @@ Read it as follows. | `dump/wide-distinct-fns` | Rust | width | shape control for the row above: a balanced `repeat()` list | linear | | `dump/tcl-nested-eval` | Tcl | depth | the export's ancestor chain under `keeps_children` (#1381, #1684) | linear | | `dump/tcl-wide-erroring-eval` | Tcl | width | the argument-list readability scan under `keeps_children`, memoised through the cache the export lends (#1686) | linear | +| `count/tcl-nested-braces` | Tcl | depth | walk control for the row below: the same filter with nothing rendered | linear | +| `find/tcl-nested-braces` | Tcl | depth | the renderer `bca find` prints through: each match's connector decided without `Node::parent`, and a nested match's text printed once (#1416) | linear | | `halstead/tcl-wide-erroring-eval` | Tcl | width | the same scan under `braced_word_op_type`, reached through an iterated ancestor on the metric walk (#1686) | linear | | `ops/tcl-wide-erroring-eval` | Tcl | width | the same scan under `braced_word_op_type`, on the `ops` walk (#1686) | linear | | `count/tcl-wide-erroring-eval` | Tcl | width | the same scan under the `string` filter, on the `find` / `count` walk (#1686) | linear | @@ -257,7 +259,7 @@ See [The ranking pass](#ranking-pass). ### The control probes -The twelve control probes are what make the other readings mean +The thirteen control probes are what make the other readings mean something. - `nom/nested-while`, `nom/nested-fn` and `nom/nested-fn-rows` are @@ -268,6 +270,9 @@ something. `cognitive` reading alone. `nom/nested-fn-rows` plays the same part for `loc/nested-fn-rows`: `Nom`'s merge is a counter add, so the difference is the cost of `Loc`'s per-space row sets. + `count/tcl-nested-braces` is the same kind of control for + `find/tcl-nested-braces`: the walk `bca find` runs, without the + render that follows it. - `loc/nested-while`, `cognitive/nested-while`, `nom/nested-declared-function`, `halstead/nested-paren`, `abc/nested-block`, `cyclomatic/nested-and`, `cyclomatic/cpp-plus-chain`, @@ -615,6 +620,28 @@ one now, and `count/perl-error-tail-calls` prices it: |---|---|---|---|---| | `act_on_node` lends no cache | `count/perl-error-tail-calls` | 0.88 | 1.89 | 2.8 ms → 84.5 ms | +What `bca find` does after that walk went unpriced until +[#1416][find-render]. It printed each match through +`dump_node_with_color` at depth 1, which chose the match's connector by +asking `Node::parent`: one `O(depth)` climb per match, 98% of the +397 ms it took on 4 000 nested Tcl braces. It also printed each +single-row match's whole span, so a match nested `k` deep was printed +`k` times, 16 MB of output for 8 KB of input. The renderer the CLI +calls now, `render_found` in `src/output/dump.rs`, decides the +connector against the tree's root and prints `…` in place of each +nested match. `find/tcl-nested-braces` times the walk and that render +into a sink that reads every byte; `count/tcl-nested-braces` is the +walk alone. Both take `FIND_RENDER_DEPTHS`, 4 000 / 8 000 / 16 000, +because the output term needs those depths to overtake the per-match +cost: on `LINEAR_DEPTHS` the whole-span render fit only 1.56. + +| Render put back | Probe that fails | Clean | Regressed | Top rung | +|---|---|---|---|---| +| a `Node::parent` climb per match | `find/tcl-nested-braces` | 0.99 | 2.00 | 5.3 ms → 6.2 s | +| each match prints its whole span | `find/tcl-nested-braces` | 0.99 | 1.84 | 5.3 ms → 67.0 ms | + +`count/tcl-nested-braces` held at 0.92–0.94 under both. + The AST export reads the same flat `ERROR`, and until [#1684][dump-cursor] it did so by index: `Node::child` and `Node::field_name_for_child` both scan the parent's child array to the index, skipping hidden subtrees by @@ -1045,3 +1072,4 @@ treating it as a regression. [find-call]: https://github.com/dekobon/big-code-analysis/issues/1580 [dump-cursor]: https://github.com/dekobon/big-code-analysis/issues/1684 [tcl-slots]: https://github.com/dekobon/big-code-analysis/issues/1686 +[find-render]: https://github.com/dekobon/big-code-analysis/issues/1416 diff --git a/src/lib.rs b/src/lib.rs index af419742b..fbb3a47f0 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -298,6 +298,10 @@ pub use crate::output::{ write_csv_aggregate, write_msvc_warning, write_sarif, write_sarif_with_provenance, write_sarif_with_suppressed, }; +// The `bca find` renderer and its sink form; hidden because they exist +// for the CLI and the scaling bench (#1416). +#[doc(hidden)] +pub use crate::output::{dump_found_with_color, write_found}; // --- AST plumbing (Node) --- pub use big_code_analysis_ast::Node; diff --git a/src/output/dump.rs b/src/output/dump.rs index 17b62e5ca..6cc3cf1eb 100644 --- a/src/output/dump.rs +++ b/src/output/dump.rs @@ -6,8 +6,11 @@ // function so the per-language impl blocks stay readable. #![allow(clippy::enum_glob_use, clippy::ref_option, clippy::wildcard_imports)] -use termcolor::{Color, WriteColor}; +use std::ops::{Range, RangeBounds}; +use termcolor::{Color, NoColor, WriteColor}; + +use crate::Ast; use crate::node::Node; use crate::output::ColorMode; use crate::output::color::print_to_stdout; @@ -166,8 +169,10 @@ impl Connector { /// The connector for the node a walk starts from — the only node whose /// parent has to be looked up. A start node with a parent renders as a -/// last child (`bca find` dumps a matched node this way), matching the -/// `last = true` the recursive form passed for the root. +/// last child, matching the `last = true` the recursive form passed for +/// the root. One lookup per dump is `O(depth)`; one per match was what +/// made `bca find` quadratic, so [`render_found`] decides the same +/// question against the tree's root instead (#1416). fn start_connector(node: &Node) -> Connector { if node.parent().is_none() { Connector::Flush @@ -331,8 +336,6 @@ fn write_node_location(stdout: &mut dyn WriteColor, node: &Node) -> std::io::Res /// Source snippet for single-row nodes only. Multi-row nodes return /// without writing (the caller still emits the trailing newline). -/// Non-UTF-8 spans fall back to raw bytes — regression guard -/// `dump_node_non_utf8_source_emits_the_raw_snippet`. fn write_node_snippet( stdout: &mut dyn WriteColor, code: &[u8], @@ -341,14 +344,208 @@ fn write_node_snippet( if node.start_row() != node.end_row() { return Ok(()); } + write_snippet( + stdout, + code, + std::iter::once(node.start_byte()..node.end_byte()), + ) +} - paint(stdout, Color::White, format_args!(": "))?; - intense_color(stdout, Color::Red)?; - let snippet = &code[node.start_byte()..node.end_byte()]; - match str::from_utf8(snippet) { - Ok(text) => write!(stdout, "{text} "), - Err(_) => stdout.write_all(snippet), +/// What a `bca find` snippet prints in place of a match nested inside +/// it, whose text the nested match's own line prints (#1416). +const ELIDED: &str = "…"; + +/// The `: text` tail of a node line, for `pieces` of `code` with +/// [`ELIDED`] between consecutive ones. A dump passes the node's whole +/// span as one piece. +/// +/// The trailing space follows the text only when every piece is UTF-8; +/// non-UTF-8 bytes are written raw with none, as they always were — +/// regression guard `dump_node_non_utf8_source_emits_the_raw_snippet`. +/// Each piece is checked on its own, so the cost is the bytes printed +/// rather than the span they sit in. +fn write_snippet( + stdout: &mut dyn WriteColor, + code: &[u8], + pieces: impl IntoIterator>, +) -> std::io::Result<()> { + write_snippet_separator(stdout, ": ")?; + let mut utf8 = true; + for (nth, piece) in pieces.into_iter().enumerate() { + if nth > 0 { + write_snippet_separator(stdout, ELIDED)?; + } + let bytes = &code[piece]; + utf8 &= str::from_utf8(bytes).is_ok(); + stdout.write_all(bytes)?; } + if utf8 { stdout.write_all(b" ") } else { Ok(()) } +} + +/// The renderer's own punctuation inside a snippet (`: `, [`ELIDED`]), +/// in white, leaving the snippet colour set for the source that follows. +fn write_snippet_separator(stdout: &mut dyn WriteColor, text: &str) -> std::io::Result<()> { + paint(stdout, Color::White, format_args!("{text}"))?; + intense_color(stdout, Color::Red) +} + +/// Render every node `bca find` matched to stdout, one line per match. +/// +/// `found` is what [`Ast::find`] returned for `ast`, in its order, and +/// `lines` filters matches by their 1-based start row, as +/// `--line-start` / `--line-end` do. A line is what [`dump_node`] at +/// depth 1 renders for the match, so a match no other match is nested +/// in prints byte-identically to that, colour included. The two +/// differences are what keep the render linear in the depth the matches +/// nest to (#1416): +/// +/// - The connector is decided against `ast`'s root, where `dump_node` +/// asks [`Node::parent`], which climbs from the root and is `O(depth)`. +/// One climb per match was 98% of `bca find`'s time on 4 000 nested +/// matches. +/// - A match nested inside a single-row match prints its text on its +/// own line, so the outer match prints [`ELIDED`] in its place: +/// `f(g(1))` renders as `f(…)` followed by `g(1)`. Printing each +/// match's whole span instead made the output quadratic in the +/// nesting depth: 16 MB for an 8 KB file. +/// +/// Hidden because it exists for the CLI, like `format_suggestion`; it +/// is outside the stability contract. +/// +/// # Errors +/// +/// Propagates any [`std::io::Error`] from the stdout writer. +/// +/// # Panics +/// +/// Panics if a node in `found` was not parsed from `ast`, for the reason +/// given on [`dump_node`]. +#[doc(hidden)] +pub fn dump_found_with_color( + ast: &Ast, + found: &[Node], + lines: impl RangeBounds, + color_mode: ColorMode, +) -> std::io::Result<()> { + print_to_stdout(color_mode, |stdout| render_found(stdout, ast, found, lines)) +} + +/// [`dump_found_with_color`] into `out`, uncoloured. Exists so the +/// scaling bench can time the renderer the CLI runs; equally hidden. +/// +/// # Errors +/// +/// Propagates any [`std::io::Error`] from `out`. +/// +/// # Panics +/// +/// As [`dump_found_with_color`]. +#[doc(hidden)] +pub fn write_found( + out: &mut dyn std::io::Write, + ast: &Ast, + found: &[Node], + lines: impl RangeBounds, +) -> std::io::Result<()> { + render_found(&mut NoColor::new(out), ast, found, lines) +} + +fn render_found( + stdout: &mut dyn WriteColor, + ast: &Ast, + found: &[Node], + lines: impl RangeBounds, +) -> std::io::Result<()> { + let code = ast.source(); + let root = ast.root_node().id(); + let spans: Vec> = found + .iter() + .map(|node| node.start_byte()..node.end_byte()) + .collect(); + let next_outside = next_outside(&spans); + for (at, node) in found.iter().enumerate() { + if lines.contains(&(node.start_row() + 1)) { + let connector = if node.id() == root { + Connector::Flush + } else { + Connector::Last + }; + write_node_header(stdout, node, "", connector.glyphs().1)?; + write_node_location(stdout, node)?; + if node.start_row() == node.end_row() { + write_snippet(stdout, code, own_text(&spans, &next_outside, at))?; + } + writeln!(stdout)?; + } + // `dump_node_with_color` ends each call on white, filtered out + // or not; keeping it keeps the coloured bytes identical. + color(stdout, Color::White)?; + } + Ok(()) +} + +/// For each span, the index of the first later span that starts at or +/// after its end, so the matches nested in `spans[at]` are +/// `at + 1..next_outside[at]`. +/// +/// One pass over a stack of the spans still open. In [`Ast::find`]'s +/// pre-order the spans nest or follow one another, so the stack's ends +/// shrink towards the top and a span closes the moment a later one +/// starts past it. Spans in any other order get some answer, never a +/// panic; [`own_text`] does not trust it. +fn next_outside(spans: &[Range]) -> Vec { + let mut next = vec![spans.len(); spans.len()]; + let mut open: Vec = Vec::new(); + for (at, span) in spans.iter().enumerate() { + while let Some(&top) = open.last() + && spans[top].end <= span.start + { + next[top] = at; + open.pop(); + } + open.push(at); + } + next +} + +/// The parts of `spans[at]` that no match nested in it covers, in +/// source order: one piece more than the matches elided from it. +/// +/// Steps from one directly nested match to the next through +/// [`next_outside`], skipping what is nested deeper, so each match is +/// visited once as the child of the match it sits in and the render +/// stays linear. A zero-width match prints nothing and so elides +/// nothing. A span that is not inside what remains of `spans[at]` — +/// impossible in a tree, which nests or orders its nodes — ends the +/// elision, and the rest prints verbatim. +fn own_text<'s>( + spans: &'s [Range], + next_outside: &'s [usize], + at: usize, +) -> impl Iterator> + 's { + let outer = spans[at].clone(); + let mut cursor = outer.start; + let mut next = at + 1; + let mut done = false; + std::iter::from_fn(move || { + if done { + return None; + } + while let Some(inner) = spans.get(next).filter(|inner| inner.start < outer.end) { + if inner.start < cursor || inner.end > outer.end { + break; + } + next = next_outside[next]; + if inner.is_empty() { + continue; + } + let piece = cursor..inner.start; + cursor = inner.end; + return Some(piece); + } + done = true; + Some(cursor..outer.end) + }) } #[cfg(test)] @@ -360,12 +557,15 @@ fn write_node_snippet( clippy::similar_names, clippy::doc_markdown, clippy::needless_raw_string_hashes, - clippy::too_many_lines + clippy::too_many_lines, + // A snippet of one piece is a one-element list of ranges, not a + // range that wants collecting. + clippy::single_range_in_vec_init )] mod tests { use std::path::PathBuf; - use termcolor::NoColor; + use termcolor::{Ansi, NoColor}; use crate::output::test_support::assert_io_error_propagates_at_every_write; use crate::{CppParser, ParserTrait}; @@ -430,8 +630,8 @@ mod tests { // `start_connector` is the walk's only `Node::parent` call // (#1054), so it carries the whole "is this flush-left?" // decision. A parentless node renders flush left; a start node - // that *does* have a parent — how `bca find` dumps a matched - // node — renders as a last child. + // that *does* have a parent — one `dump_node` is handed from + // mid-tree — renders as a last child. let code = b"int a = 42;\n"; let parser = CppParser::new(code.to_vec(), &PathBuf::from("t.c"), None); let root = parser.root(); @@ -593,11 +793,11 @@ mod tests { #[cfg(feature = "cpp")] #[test] fn dump_output_from_a_parented_start_node_indents_as_a_last_child() { - // `bca find` dumps the matched node, not the file root, so the - // start node usually has a parent and renders `╰─` with its - // subtree indented under it. `start_connector` is the only place - // that distinction is made now that the walk carries connectors - // on the stack (#1054) — this pins it end to end. + // A start node handed from mid-tree has a parent, so it renders + // `╰─` with its subtree indented under it. `start_connector` is + // the only place that distinction is made now that the walk + // carries connectors on the stack (#1054) — this pins it end to + // end. let code = b"int a = (1) + 2;\n"; let parser = CppParser::new(code.to_vec(), &PathBuf::from("t.c"), None); let root = parser.root(); @@ -615,8 +815,8 @@ mod tests { ); assert_eq!(render(code, &paren, -1), expected); - // Depth 1 is what `bca find` actually passes: the matched node - // alone, still as a last child. + // Depth 1 renders the node alone, still as a last child: the + // line `render_found` gives a match nothing is nested in. assert_eq!( render(code, &paren, 1), "╰─ {parenthesized_expression:363} from (1, 9) to (1, 12) : (1) \n" @@ -695,13 +895,12 @@ mod tests { #[cfg(feature = "cpp")] #[test] fn dump_output_depth_limits_recursion() { - // `bca find` dumps with depth=1 - // (`big-code-analysis-ast/src/find.rs`) to show only the - // matched node, not its subtree. depth=1 renders the node and stops - // before its children; depth=0 renders nothing. This is the only - // positive-depth path in production, and it is what the `depth - 1` - // decrement in `dump_tree_helper`'s iterative walk guards — pin it - // explicitly. + // depth=1 renders the node and stops before its children; + // depth=0 renders nothing. `bca find` passed depth=1 per match + // until it moved to `render_found` (#1416), so no production + // caller passes a positive depth now, but `dump_node` still + // takes one, and it is what the `depth - 1` decrement in + // `dump_tree_helper`'s iterative walk guards — pin it explicitly. let code = b"int a = 42;\n"; let parser = CppParser::new(code.to_vec(), &PathBuf::from("t.c"), None); let root = parser.root(); @@ -761,4 +960,295 @@ mod tests { dump_tree_helper(&mut state, &root, -1) }); } + + /// `code` parsed as `lang`. + #[cfg(any(feature = "cpp", feature = "tcl"))] + fn parse_as(lang: crate::LANG, code: &[u8]) -> Ast { + Ast::parse(crate::Source::new(lang, code)).expect("language feature enabled") + } + + /// What `bca find -t ` matches in `ast`. + #[cfg(any(feature = "cpp", feature = "tcl"))] + fn found<'a>(ast: &'a Ast, filters: &[&str]) -> Vec> { + let filters: Vec = filters.iter().map(|f| (*f).to_owned()).collect(); + ast.find(&filters).expect("find is infallible") + } + + /// `bca find -t ` on `ast` as the CLI renders it, uncoloured. + #[cfg(any(feature = "cpp", feature = "tcl"))] + fn found_text(ast: &Ast, filters: &[&str]) -> String { + let mut out = Vec::new(); + write_found(&mut out, ast, &found(ast, filters), ..).expect("render to memory"); + String::from_utf8(out).expect("utf-8 fixture") + } + + /// What the CLI printed before #1416: one `dump_node_with_color` + /// call per match at depth 1, each a walk from the match ending on + /// white. Rebuilt from the same private pieces that call is made of, + /// into `sink`, as the oracle for the unnested case. + #[cfg(feature = "cpp")] + fn per_match_dump( + sink: &mut dyn WriteColor, + code: &[u8], + found: &[Node], + (line_start, line_end): (Option, Option), + ) { + for node in found { + let mut state = DumpState { + code, + line_start: &line_start, + line_end: &line_end, + stdout: &mut *sink, + }; + dump_tree_helper(&mut state, node, 1).expect("dump to memory"); + color(state.stdout, Color::White).expect("dump to memory"); + } + } + + /// A match no other single-row match nests in prints exactly what + /// the per-match dump printed, colour escapes included: the root + /// flush left, a multi-row match with matches inside it (it prints + /// no text, so nothing is elided), leaves, and a non-UTF-8 literal + /// written raw. Under the line filter too, which the two paths spell + /// differently. The old path is the specification here, so the test + /// asks it rather than restating its output. + #[cfg(feature = "cpp")] + #[test] + fn found_render_matches_the_per_match_dump_when_no_match_nests() { + use std::ops::Bound::{Included, Unbounded}; + + let code = b"int a = 1;\nint f(int b) {\n return g(b, 2);\n}\nchar c = '\xff';\n"; + let ast = parse_as(crate::LANG::Cpp, code); + let found = found( + &ast, + &[ + "translation_unit", + "compound_statement", + "identifier", + "number_literal", + "char_literal", + ], + ); + assert!(found.len() >= 9, "the fixture must match widely: {found:?}"); + assert_eq!(found[0].id(), ast.root_node().id(), "the root is a match"); + + for (lines, bounds) in [ + ((None, None), (Unbounded, Unbounded)), + ((Some(2), Some(3)), (Included(2), Included(3))), + ] { + let (mut new, mut old) = (NoColor::new(Vec::new()), NoColor::new(Vec::new())); + render_found(&mut new, &ast, &found, bounds).expect("render to memory"); + per_match_dump(&mut old, code, &found, lines); + assert_eq!(new.get_ref(), old.get_ref(), "plain output under {lines:?}"); + + let (mut new, mut old) = (Ansi::new(Vec::new()), Ansi::new(Vec::new())); + render_found(&mut new, &ast, &found, bounds).expect("render to memory"); + per_match_dump(&mut old, code, &found, lines); + assert!(new.get_ref().contains(&0x1b), "the colour sink colours"); + assert_eq!( + new.get_ref(), + old.get_ref(), + "coloured output under {lines:?}" + ); + } + + let mut out = Vec::new(); + write_found(&mut out, &ast, &found, ..).expect("render to memory"); + assert!(out.contains(&0xff), "the raw literal renders"); + let text = String::from_utf8_lossy(&out); + assert!( + text.starts_with("{translation_unit:"), + "the root renders flush:\n{text}" + ); + assert!( + text.contains("╰─ {identifier:1} from (3, 10) to (3, 11) : g \n"), + "{text}" + ); + } + + /// Each match nested in a single-row match prints on its own line, + /// and the match around it prints `…` in its place — once per + /// directly nested match, never for one nested deeper, which is + /// `h(1)` inside `g(…)` here: stepping to `k(2)` without skipping it + /// would read `h` as a sibling of `g` and stop eliding at it. + #[cfg(feature = "cpp")] + #[test] + fn found_render_elides_each_nested_match_from_the_one_around_it() { + let code = b"int a = f(g(h(1)), k(2));\n"; + let ast = parse_as(crate::LANG::Cpp, code); + assert_eq!(found(&ast, &["call_expression"]).len(), 4); + assert_eq!( + found_text(&ast, &["call_expression"]), + concat!( + "╰─ {call_expression:350} from (1, 9) to (1, 25) : f(…, …) \n", + "╰─ {call_expression:350} from (1, 11) to (1, 18) : g(…) \n", + "╰─ {call_expression:350} from (1, 13) to (1, 17) : h(1) \n", + "╰─ {call_expression:350} from (1, 20) to (1, 24) : k(2) \n", + ) + ); + } + + /// The shape #1416 measured: one `braced_word` per brace level, so + /// the per-match dump printed `depth²` bytes. Every level but the + /// innermost now prints its braces around one `…`. + #[cfg(feature = "tcl")] + #[test] + fn found_render_elides_nested_braced_words() { + let ast = parse_as(crate::LANG::Tcl, b"x {{{a b}}}\n"); + assert_eq!( + found_text(&ast, &["braced_word"]), + concat!( + "╰─ {braced_word:88} from (1, 3) to (1, 12) : {…} \n", + "╰─ {braced_word:88} from (1, 4) to (1, 11) : {…} \n", + "╰─ {braced_word:88} from (1, 5) to (1, 10) : {a b} \n", + ) + ); + } + + /// The non-UTF-8 rule — raw bytes, no trailing space — is decided on + /// the bytes a line prints, not on the span it elides: a line whose + /// own pieces are text keeps its space though a nested match is not, + /// and the other way round. + #[cfg(feature = "cpp")] + #[test] + fn found_render_decides_utf8_on_the_printed_pieces() { + let code = b"int a = f('\xff', g(1));\nint b = f(g('\xff'));\n"; + let ast = parse_as(crate::LANG::Cpp, code); + let found = found(&ast, &["call_expression"]); + let mut sink = NoColor::new(Vec::new()); + write_found(sink.get_mut(), &ast, &found, ..).expect("render to memory"); + let lines: Vec<&[u8]> = sink.get_ref().split_inclusive(|b| *b == b'\n').collect(); + let tail = |line: &[u8]| { + let at = line + .windows(3) + .position(|w| w == b" : ") + .expect("a snippet"); + line[at + 3..].to_vec() + }; + let elided = |before: &[u8], after: &[u8]| [before, ELIDED.as_bytes(), after].concat(); + assert_eq!(lines.len(), 4, "{lines:?}"); + assert_eq!(tail(lines[0]), elided(b"f('\xff', ", b")\n")); + assert_eq!(tail(lines[1]), b"g(1) \n"); + assert_eq!(tail(lines[2]), elided(b"f(", b") \n")); + assert_eq!(tail(lines[3]), b"g('\xff')\n"); + } + + /// Rendering every match asks no node for its parent. The per-match + /// dump asked each one, which climbs from the root: `O(depth)` per + /// match, 98% of `bca find`'s time on #1416's 4 000-deep input. The + /// second half shows the counter sees that path, so the zero above + /// it is not a counter that never moves. + #[cfg(feature = "cpp")] + #[test] + fn found_render_climbs_to_no_parent() { + let code = b"int a = f(g(h(1)), k(2));\n"; + let ast = parse_as(crate::LANG::Cpp, code); + let found = found(&ast, &["translation_unit", "call_expression"]); + assert_eq!(found.len(), 5); + let climbs = crate::node::node_resolved_parent_lookups::observed; + + let before = climbs(); + write_found(&mut std::io::sink(), &ast, &found, ..).expect("render to a sink"); + assert_eq!(climbs() - before, 0, "the find render climbed to a parent"); + + let before = climbs(); + per_match_dump( + &mut NoColor::new(std::io::sink()), + code, + &found, + (None, None), + ); + assert_eq!( + climbs() - before, + found.len(), + "the per-match dump asks each match" + ); + } + + /// Under `-t all` every byte of a one-row file is printed exactly + /// once: by the deepest match holding it, and by none around it. + /// The per-match dump printed each byte once per match above it. + #[cfg(feature = "cpp")] + #[test] + fn found_render_prints_each_byte_of_one_row_once() { + let code = b"int a = f(g(1), 2);"; + let ast = parse_as(crate::LANG::Cpp, code); + let found = found(&ast, &["all"]); + assert!(found.iter().all(|node| node.start_row() == node.end_row())); + let spans: Vec> = found + .iter() + .map(|node| node.start_byte()..node.end_byte()) + .collect(); + let next = next_outside(&spans); + let printed: usize = (0..spans.len()) + .flat_map(|at| own_text(&spans, &next, at)) + .map(|piece| piece.len()) + .sum(); + assert_eq!(printed, code.len()); + let spanned: usize = spans.iter().map(ExactSizeIterator::len).sum(); + assert!(spanned > 3 * code.len(), "the fixture must nest: {spanned}"); + } + + #[test] + fn next_outside_points_past_everything_nested() { + // 0..10 holds 0..4 (holding 1..2) and 5..9 (holding 6..7); + // 10..12 follows it. Pre-order, as `Ast::find` returns them. + let spans = [0..10, 0..4, 1..2, 5..9, 6..7, 10..12]; + assert_eq!(next_outside(&spans), [5, 3, 3, 5, 5, 6]); + } + + #[test] + fn own_text_elides_only_the_directly_nested_spans() { + let spans = [0..10, 0..4, 1..2, 5..9, 6..7, 10..12]; + let next = next_outside(&spans); + let own = |at| own_text(&spans, &next, at).collect::>(); + assert_eq!(own(0), [0..0, 4..5, 9..10]); + assert_eq!(own(1), [0..1, 2..4]); + assert_eq!(own(2), [1..2]); + assert_eq!(own(3), [5..6, 7..9]); + assert_eq!(own(5), [10..12]); + + // A child with its parent's whole span leaves the parent `…`; a + // zero-width child, a MISSING token, elides nothing. + let spans = [0..5, 0..5, 2..2]; + let next = next_outside(&spans); + assert_eq!(own_text(&spans, &next, 0).collect::>(), [0..0, 5..5]); + assert_eq!(own_text(&spans, &next, 1).collect::>(), [0..5]); + } + + /// `next_outside` and `own_text` are total: on spans in any order + /// and overlap, which no tree produces, the pieces still lie inside + /// the span in order, so slicing the source by them cannot panic. + /// Every sequence of up to four spans drawn from a small pool. + #[test] + fn own_text_stays_inside_its_span_on_any_input() { + const POOL: [Range; 6] = [0..4, 1..3, 2..2, 3..6, 0..6, 5..5]; + let mut checked = 0; + for len in 1..=4_u32 { + for code in 0..POOL.len().pow(len) { + let spans: Vec> = (0..len) + .scan(code, |rest, _| { + let pick = *rest % POOL.len(); + *rest /= POOL.len(); + Some(POOL[pick].clone()) + }) + .collect(); + let next = next_outside(&spans); + for (at, outer) in spans.iter().enumerate() { + let mut cursor = outer.start; + for piece in own_text(&spans, &next, at) { + assert!( + cursor <= piece.start + && piece.start <= piece.end + && piece.end <= outer.end, + "{piece:?} escapes {outer:?} after {cursor} in {spans:?}" + ); + cursor = piece.end; + } + checked += 1; + } + } + } + assert_eq!(checked, 6 + 2 * 36 + 3 * 216 + 4 * 1_296); + } } From 3e96eb760c5f5cc2348c88a06b3984295d2c38e0 Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Fri, 6 Nov 2026 00:14:24 -0800 Subject: [PATCH 11/25] refactor: simplify the batch's new code paths - role_table!: every owner gate slot goes to `@gate` whole, and an empty slot renders as `true`. That drops the seven parent-list terminal arms #1794 added beside their generic twins, and the six ungated clause forwarders left without callers. - dump: `render_found` writes each line through `write_node_line`, which now takes the snippet as byte pieces and owns the single-row rule, so `write_node_snippet` folds away. `own_text`'s two loop exits are one filter. - doxygen: `Visit` has named fields; `children_declare` calls `preproc_conditional`; the no-bytes paragraph moves onto `non_conditional_entry`, which makes the call, and the binding's assert names it. - Baseline: `render_found`'s nexits entry retires; roles/mod.rs loc drops. Refs #1794 Refs #1795 Refs #1416 --- .bca-baseline.toml | 10 +-- .../src/checker/doxygen_doc_binding.rs | 6 +- .../src/lang_helpers/doxygen.rs | 60 +++++++++---- .../src/roles/doc_tests/doxygen.rs | 8 +- big-code-analysis-ast/src/roles/mod.rs | 87 +++++-------------- src/output/dump.rs | 76 ++++++++-------- 6 files changed, 108 insertions(+), 139 deletions(-) diff --git a/.bca-baseline.toml b/.bca-baseline.toml index 441464048..7f6eb4518 100644 --- a/.bca-baseline.toml +++ b/.bca-baseline.toml @@ -365,13 +365,13 @@ value = 5.0 path = "big-code-analysis-ast/src/roles/mod.rs" qualified = "" metric = "loc.ploc" -value = 956.0 +value = 914.0 [[entry]] path = "big-code-analysis-ast/src/roles/mod.rs" qualified = "" metric = "loc.sloc" -value = 2304.0 +value = 2263.0 [[entry]] path = "big-code-analysis-ast/src/tools.rs" @@ -1315,12 +1315,6 @@ qualified = "dump_node" metric = "nargs" value = 5.0 -[[entry]] -path = "src/output/dump.rs" -qualified = "render_found" -metric = "nexits" -value = 5.0 - [[entry]] path = "src/output/dump.rs" qualified = "write_node_line" diff --git a/big-code-analysis-ast/src/checker/doxygen_doc_binding.rs b/big-code-analysis-ast/src/checker/doxygen_doc_binding.rs index 43e5bcee5..d0721fb03 100644 --- a/big-code-analysis-ast/src/checker/doxygen_doc_binding.rs +++ b/big-code-analysis-ast/src/checker/doxygen_doc_binding.rs @@ -41,11 +41,11 @@ macro_rules! impl_doxygen_row { ($code:ident, $roles:ident) => { impl $crate::lang_helpers::doxygen::DoxygenRow for $code { fn doc_target_row<'a>(node: &Node<'a>, code: &[u8], ancestors: Ancestors<'a, '_>) -> bool { - // `doxygen_entry` hands this row no bytes; the pin sits - // beside the forward it protects. + // `non_conditional_entry` hands this row no bytes; the + // pin sits beside the forward it protects. const _: () = assert!( !$crate::roles::$roles::doc_target::TEXT_GATED, - "a C-family `DocTarget` row reads bytes; `doxygen_entry` cannot forward with `&[]`" + "a C-family `DocTarget` row reads bytes; `non_conditional_entry` cannot forward with `&[]`" ); $crate::roles::$roles::doc_target::owns(node, code, ancestors) } diff --git a/big-code-analysis-ast/src/lang_helpers/doxygen.rs b/big-code-analysis-ast/src/lang_helpers/doxygen.rs index fab647e93..3dc17d238 100644 --- a/big-code-analysis-ast/src/lang_helpers/doxygen.rs +++ b/big-code-analysis-ast/src/lang_helpers/doxygen.rs @@ -294,21 +294,37 @@ pub(crate) fn conditional_declares(node: &Node, ancestors: Ancest // has folded its own in. `answers[i]` holds the answer, so far, of the // `i`th conditional read. let mut answers = Vec::new(); - let mut stack = vec![Visit::Read(*node, None)]; + let mut stack = vec![Visit::Read { + conditional: *node, + outer: None, + }]; while let Some(visit) = stack.pop() { match visit { - Visit::Read(conditional, outer) => { + Visit::Read { conditional, outer } => { conditionals_read::record(); let own = answers.len(); - stack.push(Visit::Answer(conditional, outer, own)); + stack.push(Visit::Answer { + conditional, + outer, + own, + }); answers.push(children_declare::( &conditional, ancestors, memo, - |nested| stack.push(Visit::Read(nested, Some(own))), + |nested| { + stack.push(Visit::Read { + conditional: nested, + outer: Some(own), + }); + }, )); } - Visit::Answer(conditional, outer, own) => { + Visit::Answer { + conditional, + outer, + own, + } => { memo.set(&conditional, answers[own]); if let Some(outer) = outer { answers[outer] |= answers[own]; @@ -319,15 +335,23 @@ pub(crate) fn conditional_declares(node: &Node, ancestors: Ancest memo.get(node) == Some(true) } -/// A step of [`conditional_declares`]'s walk over a nest. The `Option` is -/// the enclosing conditional's index in the walk's `answers`, `None` for -/// the conditional asked about; an `Answer` carries its own index too. +/// A step of [`conditional_declares`]'s walk over a nest. enum Visit<'a> { /// Read the conditional's children ([`children_declare`]). - Read(Node<'a>, Option), + Read { + conditional: Node<'a>, + /// The enclosing conditional's index in the walk's `answers`; + /// `None` for the conditional asked about. + outer: Option, + }, /// Store the conditional's answer, every nested one folded in by now, /// and fold it into the enclosing conditional's. - Answer(Node<'a>, Option, usize), + Answer { + conditional: Node<'a>, + outer: Option, + /// This conditional's own index in `answers`. + own: usize, + }, } /// Whether a child of `conditional` already answers @@ -345,7 +369,7 @@ fn children_declare<'a, T: DoxygenRow>( let below = chain_below(ancestors, &parent); let mut declares = false; for child in conditional.children() { - if T::conditional_kind(child.kind_id()) { + if preproc_conditional::(&child) { match memo.get(&child) { Some(answer) => declares |= answer, None => defer(child), @@ -513,6 +537,13 @@ pub(crate) fn doxygen_target<'a, T: DoxygenRow>( /// preprocessor would expand, is given the benefit of the doubt, as /// before #1613, rather than dropping the block on a parse failure; an /// error holding no entry is read past (`doxygen_skips`). +fn doxygen_entry(node: &Node, ancestors: Ancestors) -> bool { + !preproc_conditional::(node) && non_conditional_entry::(node, ancestors) +} + +/// [`doxygen_entry`] of a node its caller has already found is no +/// conditional: the row, or a parse error holding an entry (an `ERROR` +/// is never a conditional kind). /// /// The row is asked with no bytes, which is exact because no C-family /// `DocTarget` gate reads any — `impl_doxygen_row!` in @@ -523,13 +554,6 @@ pub(crate) fn doxygen_target<'a, T: DoxygenRow>( /// `ERROR` clause this fn already handles, and a dialect that someday /// hand-writes a byte-reading `is_doc_target` would otherwise slip past /// the row's assertion. -fn doxygen_entry(node: &Node, ancestors: Ancestors) -> bool { - !preproc_conditional::(node) && non_conditional_entry::(node, ancestors) -} - -/// [`doxygen_entry`] of a node its caller has already found is no -/// conditional: the row, or a parse error holding an entry (an `ERROR` -/// is never a conditional kind). fn non_conditional_entry(node: &Node, ancestors: Ancestors) -> bool { if node.is_error() { return !no_entry_inside::(node, ancestors); diff --git a/big-code-analysis-ast/src/roles/doc_tests/doxygen.rs b/big-code-analysis-ast/src/roles/doc_tests/doxygen.rs index 1b711322d..dc8b3b28a 100644 --- a/big-code-analysis-ast/src/roles/doc_tests/doxygen.rs +++ b/big-code-analysis-ast/src/roles/doc_tests/doxygen.rs @@ -14,10 +14,8 @@ use std::collections::BTreeSet; use std::path::Path; /// The names `doxygen_entry` matched before #1699 (its `match -/// node.kind()` arms, plus the specifier and field arms it gated), -/// and the five conditional names `preproc_conditional` matched until -/// #1795. A hand-pinned copy, not read from the rows, so this is an -/// oracle. +/// node.kind()` arms, plus the specifier and field arms it gated). A +/// hand-pinned copy, not read from the rows, so this is an oracle. const OLD_ENTRY_NAMES: &[&str] = &[ "declaration", "function_definition", @@ -47,6 +45,8 @@ const OLD_ENTRY_NAMES: &[&str] = &[ "expression_statement", "implementation_definition", ]; +/// The five conditional names `preproc_conditional` matched by name +/// until #1795, hand-pinned like [`OLD_ENTRY_NAMES`]. const OLD_CONDITIONAL_NAMES: &[&str] = &[ "preproc_if", "preproc_ifdef", diff --git a/big-code-analysis-ast/src/roles/mod.rs b/big-code-analysis-ast/src/roles/mod.rs index f6b2b4443..56bdc46d2 100644 --- a/big-code-analysis-ast/src/roles/mod.rs +++ b/big-code-analysis-ast/src/roles/mod.rs @@ -1918,19 +1918,17 @@ macro_rules! role_table { // ---- the scan's terminals ---------------------------------------------- - // In `owns`: the owner's clause, gated or not. A gate slot is - // `[g]` or `[g no_chain]`, carried into the clause as - // `gated_by g` / `gated_by g no_chain`. A parent list, - // `[under [..]]` or `[not_under [..]]`, is handed to `@gate` whole, - // here and in every terminal below that emits a clause. - (@owner_done [] $ctx:tt $k:ident [$rel:ident [$($q:ident),+]] $p:tt $s:tt $c:tt) => { - $crate::role_table!(@clause_gated $ctx $k [$rel [$($q),+]]); - }; + // In `owns`: the owner's clause, gated or not. The gate slot — `[]`, + // `[g]`, `[g no_chain]`, `[under [..]]` or `[not_under [..]]` — is + // handed to `@gate` whole, here and in every terminal below that + // emits a clause; an empty slot renders as `true`. Only + // `holds_payer` is read off the slot first, since it changes the + // clause rather than gating it. (@owner_done [] $ctx:tt $k:ident [holds_payer $($g:ident $($nc:ident)?)?] $p:tt $s:tt $c:tt) => { $crate::role_table!(@clause_payer $ctx $k $(gated_by $g $($nc)?)?); }; - (@owner_done [] $ctx:tt $k:ident [$($g:ident $($nc:ident)?)?] $p:tt $s:tt $c:tt) => { - $crate::role_table!(@clause $ctx $k $(gated_by $g $($nc)?)?); + (@owner_done [] $ctx:tt $k:ident $g:tt $p:tt $s:tt $c:tt) => { + $crate::role_table!(@clause_gated $ctx $k $g); }; // In `TEXT_GATED`: whether the owner's gate reads the bytes. The scan // folds `text_gated_by` and `gated_by` into one gate slot, so the @@ -1992,17 +1990,11 @@ macro_rules! role_table { // a `callable_when w` owner's under its gate *and* `w`; an owner // without either mark emits nothing. (@callable_done [] $ctx:tt $k:ident $g:tt $p:tt $s:tt []) => {}; - (@callable_done [] $ctx:tt $k:ident [$rel:ident [$($q:ident),+]] $p:tt $s:tt [callable]) => { - $crate::role_table!(@clause_gated $ctx $k [$rel [$($q),+]]); - }; - (@callable_done [] $ctx:tt $k:ident [$rel:ident [$($q:ident),+]] $p:tt $s:tt [callable $w:ident]) => { - $crate::role_table!(@clause_when_gated $ctx $k $w [$rel [$($q),+]]); - }; - (@callable_done [] $ctx:tt $k:ident [$($g:ident $($nc:ident)?)?] $p:tt $s:tt [callable]) => { - $crate::role_table!(@clause $ctx $k $(gated_by $g $($nc)?)?); + (@callable_done [] $ctx:tt $k:ident $g:tt $p:tt $s:tt [callable]) => { + $crate::role_table!(@clause_gated $ctx $k $g); }; - (@callable_done [] $ctx:tt $k:ident [$($g:ident $($nc:ident)?)?] $p:tt $s:tt [callable $w:ident]) => { - $crate::role_table!(@clause_when $ctx $k $w $(gated_by $g $($nc)?)?); + (@callable_done [] $ctx:tt $k:ident $g:tt $p:tt $s:tt [callable $w:ident]) => { + $crate::role_table!(@clause_when_gated $ctx $k $w $g); }; // In `pays_at_leaf`: a `pays_itself` owner pays under its own gate, // and a `pays_itself_when w` owner under its gate *and* `w` — the @@ -2013,17 +2005,11 @@ macro_rules! role_table { // already pays, and under `pays never` it would contradict the row // — so the other two modes reject it. (@self_payer_done [$mode:ident] $ctx:tt $k:ident $g:tt [] $s:tt $c:tt) => {}; - (@self_payer_done [split] $ctx:tt $k:ident [$rel:ident [$($q:ident),+]] [pays_itself] $s:tt $c:tt) => { - $crate::role_table!(@clause_gated $ctx $k [$rel [$($q),+]]); + (@self_payer_done [split] $ctx:tt $k:ident $g:tt [pays_itself] $s:tt $c:tt) => { + $crate::role_table!(@clause_gated $ctx $k $g); }; - (@self_payer_done [split] $ctx:tt $k:ident [$rel:ident [$($q:ident),+]] [pays_itself $w:ident] $s:tt $c:tt) => { - $crate::role_table!(@clause_when_gated $ctx $k $w [$rel [$($q),+]]); - }; - (@self_payer_done [split] $ctx:tt $k:ident [$($g:ident $($nc:ident)?)?] [pays_itself] $s:tt $c:tt) => { - $crate::role_table!(@clause $ctx $k $(gated_by $g $($nc)?)?); - }; - (@self_payer_done [split] $ctx:tt $k:ident [$($g:ident $($nc:ident)?)?] [pays_itself $w:ident] $s:tt $c:tt) => { - $crate::role_table!(@clause_when $ctx $k $w $(gated_by $g $($nc)?)?); + (@self_payer_done [split] $ctx:tt $k:ident $g:tt [pays_itself $w:ident] $s:tt $c:tt) => { + $crate::role_table!(@clause_when_gated $ctx $k $w $g); }; (@self_payer_done [never] $ctx:tt $k:ident $g:tt [pays_itself $($w:ident)?] $s:tt $c:tt) => { compile_error!("`pays_itself` contradicts `pays never`: the row says nothing pays"); @@ -2035,17 +2021,11 @@ macro_rules! role_table { }; // In `opens_space`: an `opens K` owner returns its kind, under its gate. (@opens_done [] $ctx:tt $k:ident $g:tt $p:tt [] $c:tt) => {}; - (@opens_done [] $ctx:tt $k:ident [$rel:ident [$($q:ident),+]] $p:tt [by $f:ident $($fnc:ident)?] $c:tt) => { - $crate::role_table!(@space_clause_by_gated $ctx $k [$f $($fnc)?] [$rel [$($q),+]]); - }; - (@opens_done [] $ctx:tt $k:ident [$rel:ident [$($q:ident),+]] $p:tt [$s:ident] $c:tt) => { - $crate::role_table!(@space_clause_gated $ctx $k $s [$rel [$($q),+]]); + (@opens_done [] $ctx:tt $k:ident $g:tt $p:tt [by $f:ident $($fnc:ident)?] $c:tt) => { + $crate::role_table!(@space_clause_by_gated $ctx $k [$f $($fnc)?] $g); }; - (@opens_done [] $ctx:tt $k:ident [$($g:ident $($nc:ident)?)?] $p:tt [by $f:ident $($fnc:ident)?] $c:tt) => { - $crate::role_table!(@space_clause_by $ctx $k [$f $($fnc)?] $(gated_by $g $($nc)?)?); - }; - (@opens_done [] $ctx:tt $k:ident [$($g:ident $($nc:ident)?)?] $p:tt [$s:ident] $c:tt) => { - $crate::role_table!(@space_clause $ctx $k $s $(gated_by $g $($nc)?)?); + (@opens_done [] $ctx:tt $k:ident $g:tt $p:tt [$s:ident] $c:tt) => { + $crate::role_table!(@space_clause_gated $ctx $k $s $g); }; // ---- the `opens_space` fold ------------------------------------------- @@ -2071,6 +2051,9 @@ macro_rules! role_table { // the proof is the signature, not the row. A parent list, an // owner's or a payer's, is the parent-kind test itself (#1794). + (@gate [$l:ident $kind:ident $n:ident $c:ident $a:ident] []) => { + true + }; (@gate [$l:ident $kind:ident $n:ident $c:ident $a:ident] [$g:ident]) => { $g($n, $c, $a) }; @@ -2123,27 +2106,11 @@ macro_rules! role_table { && project($n).is_some_and(|child| PAYERS.contains(&child.kind_id())); } }; - (@clause_when [$l:ident $kind:ident $n:ident $c:ident $a:ident] $k:ident $w:ident) => { - if $kind == $l::$k as u16 { - return $w($n, $c, $a); - } - }; - (@clause_when $ctx:tt $k:ident $w:ident gated_by $g:ident $($nc:ident)?) => { - $crate::role_table!(@clause_when_gated $ctx $k $w [$g $($nc)?]); - }; (@clause_when_gated [$l:ident $kind:ident $n:ident $c:ident $a:ident] $k:ident $w:ident $g:tt) => { if $kind == $l::$k as u16 { return $crate::role_table!(@gate [$l $kind $n $c $a] $g) && $w($n, $c, $a); } }; - (@space_clause [$l:ident $kind:ident $n:ident $c:ident $a:ident] $k:ident $s:ident) => { - if $kind == $l::$k as u16 { - return $crate::SpaceKind::$s; - } - }; - (@space_clause $ctx:tt $k:ident $s:ident gated_by $g:ident $($nc:ident)?) => { - $crate::role_table!(@space_clause_gated $ctx $k $s [$g $($nc)?]); - }; (@space_clause_gated [$l:ident $kind:ident $n:ident $c:ident $a:ident] $k:ident $s:ident $g:tt) => { if $kind == $l::$k as u16 && $crate::role_table!(@gate [$l $kind $n $c $a] $g) { return $crate::SpaceKind::$s; @@ -2151,14 +2118,6 @@ macro_rules! role_table { }; // An `opens_by f` owner: `f` answers the kind, `Unknown` for none; // `f` takes the `no_chain` mark like a gate. - (@space_clause_by [$l:ident $kind:ident $n:ident $c:ident $a:ident] $k:ident $f:tt) => { - if $kind == $l::$k as u16 { - return $crate::role_table!(@gate [$l $kind $n $c $a] $f); - } - }; - (@space_clause_by $ctx:tt $k:ident $f:tt gated_by $g:ident $($nc:ident)?) => { - $crate::role_table!(@space_clause_by_gated $ctx $k $f [$g $($nc)?]); - }; (@space_clause_by_gated [$l:ident $kind:ident $n:ident $c:ident $a:ident] $k:ident $f:tt $g:tt) => { if $kind == $l::$k as u16 && $crate::role_table!(@gate [$l $kind $n $c $a] $g) { return $crate::role_table!(@gate [$l $kind $n $c $a] $f); diff --git a/src/output/dump.rs b/src/output/dump.rs index 6cc3cf1eb..e11954635 100644 --- a/src/output/dump.rs +++ b/src/output/dump.rs @@ -221,7 +221,14 @@ fn dump_tree_helper<'a>(state: &mut DumpState, node: &Node<'a>, depth: i32) -> s let (pref_child, pref) = frame.connector.glyphs(); if line_in_range(frame.node.start_row() + 1, state.line_start, state.line_end) { - write_node_line(state.stdout, state.code, &frame.node, &prefix, pref)?; + let (code, node) = (state.code, frame.node); + write_node_line( + state.stdout, + &node, + &prefix, + pref, + std::iter::once_with(|| &code[node.start_byte()..node.end_byte()]), + )?; } // Leaves are roughly half the nodes and `child_count` is O(1), @@ -291,16 +298,19 @@ fn paint(stdout: &mut dyn WriteColor, c: Color, args: std::fmt::Arguments) -> st /// Emit the full colored description line for one node: header, position /// range, optional same-row snippet, then the trailing newline (always, /// even for multi-row nodes whose snippet is skipped). -fn write_node_line( +fn write_node_line<'c>( stdout: &mut dyn WriteColor, - code: &[u8], node: &Node, prefix: &str, pref: &str, + snippet: impl IntoIterator, ) -> std::io::Result<()> { write_node_header(stdout, node, prefix, pref)?; write_node_location(stdout, node)?; - write_node_snippet(stdout, code, node)?; + // Source snippet for single-row nodes only. + if node.start_row() == node.end_row() { + write_snippet(stdout, snippet)?; + } writeln!(stdout) } @@ -334,23 +344,6 @@ fn write_node_location(stdout: &mut dyn WriteColor, node: &Node) -> std::io::Res ) } -/// Source snippet for single-row nodes only. Multi-row nodes return -/// without writing (the caller still emits the trailing newline). -fn write_node_snippet( - stdout: &mut dyn WriteColor, - code: &[u8], - node: &Node, -) -> std::io::Result<()> { - if node.start_row() != node.end_row() { - return Ok(()); - } - write_snippet( - stdout, - code, - std::iter::once(node.start_byte()..node.end_byte()), - ) -} - /// What a `bca find` snippet prints in place of a match nested inside /// it, whose text the nested match's own line prints (#1416). const ELIDED: &str = "…"; @@ -364,18 +357,16 @@ const ELIDED: &str = "…"; /// regression guard `dump_node_non_utf8_source_emits_the_raw_snippet`. /// Each piece is checked on its own, so the cost is the bytes printed /// rather than the span they sit in. -fn write_snippet( +fn write_snippet<'c>( stdout: &mut dyn WriteColor, - code: &[u8], - pieces: impl IntoIterator>, + pieces: impl IntoIterator, ) -> std::io::Result<()> { write_snippet_separator(stdout, ": ")?; let mut utf8 = true; - for (nth, piece) in pieces.into_iter().enumerate() { + for (nth, bytes) in pieces.into_iter().enumerate() { if nth > 0 { write_snippet_separator(stdout, ELIDED)?; } - let bytes = &code[piece]; utf8 &= str::from_utf8(bytes).is_ok(); stdout.write_all(bytes)?; } @@ -470,12 +461,13 @@ fn render_found( } else { Connector::Last }; - write_node_header(stdout, node, "", connector.glyphs().1)?; - write_node_location(stdout, node)?; - if node.start_row() == node.end_row() { - write_snippet(stdout, code, own_text(&spans, &next_outside, at))?; - } - writeln!(stdout)?; + write_node_line( + stdout, + node, + "", + connector.glyphs().1, + own_text(&spans, &next_outside, at).map(|piece| &code[piece]), + )?; } // `dump_node_with_color` ends each call on white, filtered out // or not; keeping it keeps the coloured bytes identical. @@ -531,10 +523,9 @@ fn own_text<'s>( if done { return None; } - while let Some(inner) = spans.get(next).filter(|inner| inner.start < outer.end) { - if inner.start < cursor || inner.end > outer.end { - break; - } + while let Some(inner) = spans.get(next).filter(|inner| { + cursor <= inner.start && inner.start < outer.end && inner.end <= outer.end + }) { next = next_outside[next]; if inner.is_empty() { continue; @@ -669,7 +660,7 @@ mod tests { /// Render `node` to an in-memory sink under the given line filter and /// return the raw bytes. Not necessarily UTF-8: a non-UTF-8 source - /// snippet is written through verbatim by `write_node_snippet`. + /// snippet is written through verbatim by `write_snippet`. #[cfg(feature = "cpp")] fn render_raw( code: &[u8], @@ -933,7 +924,7 @@ mod tests { /// but every existing test writes into an infallible `Vec`, leaving /// the failure half of each `?` in `dump_tree_helper`, `paint`, /// `write_node_line`, `write_node_header`, `write_node_location`, and - /// `write_node_snippet` unexercised. + /// `write_snippet` unexercised. /// /// The fixture is deliberately the smallest tree that still nests: /// the sweep re-runs the whole dump once per write position, so cost @@ -1005,10 +996,11 @@ mod tests { } } - /// A match no other single-row match nests in prints exactly what - /// the per-match dump printed, colour escapes included: the root - /// flush left, a multi-row match with matches inside it (it prints - /// no text, so nothing is elided), leaves, and a non-UTF-8 literal + /// A match printed whole — multi-row, or single-row holding no other + /// match — prints exactly what the per-match dump printed, colour + /// escapes included: the root flush left, a multi-row match with + /// matches inside it (it prints no text, so nothing is elided), + /// leaves, and a non-UTF-8 literal /// written raw. Under the line filter too, which the two paths spell /// differently. The old path is the specification here, so the test /// asks it rather than restating its output. From d03276872c3a240acc7a38986e6fc1614407ed1c Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Fri, 6 Nov 2026 00:31:53 -0800 Subject: [PATCH 12/25] test(dump): pin find's colours and its UTF-8 rule MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Three #1416 tests passed with the renderer wrong, each shown by a utils/perturb.py run over the root lib, the CLI lib and its output/cli_ux/check/discovery targets, and the bench lib: - found_render_matches_the_per_match_dump_when_no_match_nests claims colour identity with the pre-fix path, but its oracle is rebuilt on the writers render_found shares. Painting the snippet separator cyan, or writing the elided `…` without its colour switch, failed nothing anywhere. found_render_colours_as_the_pre_fix_binary_did now holds the escapes to bytes captured from a pre-#1416 `bca find --color always` (02150268), plus the documented colour of `…`. - found_render_decides_utf8_on_the_printed_pieces only placed the non-UTF-8 piece first, so deciding the trailing space on the first piece alone passed. A line whose last piece is non-UTF-8 catches it. - found_render_prints_each_byte_of_one_row_once summed own_text's piece lengths and never rendered, so a render printing every whole span passed it. It now reads the rendered lines and compares the printed bytes, as a multiset, with the source. Refs #1416 --- src/output/dump.rs | 76 ++++++++++++++++++++++++++++++++++++++-------- 1 file changed, 63 insertions(+), 13 deletions(-) diff --git a/src/output/dump.rs b/src/output/dump.rs index e11954635..2ca3d1ed9 100644 --- a/src/output/dump.rs +++ b/src/output/dump.rs @@ -1003,7 +1003,11 @@ mod tests { /// leaves, and a non-UTF-8 literal /// written raw. Under the line filter too, which the two paths spell /// differently. The old path is the specification here, so the test - /// asks it rather than restating its output. + /// asks it rather than restating its output. It is rebuilt on the + /// writers `render_found` shares, though, so it pins what the two + /// paths decide differently (connector, filter, trailing white, the + /// pieces) and not the escapes themselves: those are + /// `found_render_colours_as_the_pre_fix_binary_did`'s. #[cfg(feature = "cpp")] #[test] fn found_render_matches_the_per_match_dump_when_no_match_nests() { @@ -1080,6 +1084,37 @@ mod tests { ); } + /// The escapes `bca find --color always` prints, held to the binary + /// from before #1416 (built from 02150268) instead of to the + /// per-match oracle, which goes through the same writers as + /// `render_found` and moves with them. The `g(1)` line is that + /// binary's output verbatim. The `f(…)` line is its `f(g(1))` line + /// with the nested `g(1)` replaced by `…`, painted like the `: ` + /// before it: white, then the snippet's intense red again for the + /// `)` after it. No other test renders a nested match in colour. + #[cfg(feature = "cpp")] + #[test] + fn found_render_colours_as_the_pre_fix_binary_did() { + let ast = parse_as(crate::LANG::Cpp, b"int a = f(g(1));\n"); + let mut sink = Ansi::new(Vec::new()); + render_found(&mut sink, &ast, &found(&ast, &["call_expression"]), ..) + .expect("render to memory"); + assert_eq!( + String::from_utf8(sink.into_inner()).expect("utf-8 fixture"), + concat!( + "\x1b[0m\x1b[34m╰─ \x1b[0m\x1b[38;5;11m{call_expression:350} ", + "\x1b[0m\x1b[37mfrom \x1b[0m\x1b[32m(1, 9) ", + "\x1b[0m\x1b[37mto \x1b[0m\x1b[32m(1, 16) ", + "\x1b[0m\x1b[37m: \x1b[0m\x1b[38;5;9mf(", + "\x1b[0m\x1b[37m…\x1b[0m\x1b[38;5;9m) \n\x1b[0m\x1b[37m", + "\x1b[0m\x1b[34m╰─ \x1b[0m\x1b[38;5;11m{call_expression:350} ", + "\x1b[0m\x1b[37mfrom \x1b[0m\x1b[32m(1, 11) ", + "\x1b[0m\x1b[37mto \x1b[0m\x1b[32m(1, 15) ", + "\x1b[0m\x1b[37m: \x1b[0m\x1b[38;5;9mg(1) \n\x1b[0m\x1b[37m", + ) + ); + } + /// The shape #1416 measured: one `braced_word` per brace level, so /// the per-match dump printed `depth²` bytes. Every level but the /// innermost now prints its braces around one `…`. @@ -1100,11 +1135,13 @@ mod tests { /// The non-UTF-8 rule — raw bytes, no trailing space — is decided on /// the bytes a line prints, not on the span it elides: a line whose /// own pieces are text keeps its space though a nested match is not, - /// and the other way round. + /// and the other way round. One non-UTF-8 piece drops the space + /// wherever it falls: first on line `a`, last on line `c`, so a rule + /// that read either end alone fails one of them. #[cfg(feature = "cpp")] #[test] fn found_render_decides_utf8_on_the_printed_pieces() { - let code = b"int a = f('\xff', g(1));\nint b = f(g('\xff'));\n"; + let code = b"int a = f('\xff', g(1));\nint b = f(g('\xff'));\nint c = f(g(1), '\xff');\n"; let ast = parse_as(crate::LANG::Cpp, code); let found = found(&ast, &["call_expression"]); let mut sink = NoColor::new(Vec::new()); @@ -1118,11 +1155,13 @@ mod tests { line[at + 3..].to_vec() }; let elided = |before: &[u8], after: &[u8]| [before, ELIDED.as_bytes(), after].concat(); - assert_eq!(lines.len(), 4, "{lines:?}"); + assert_eq!(lines.len(), 6, "{lines:?}"); assert_eq!(tail(lines[0]), elided(b"f('\xff', ", b")\n")); assert_eq!(tail(lines[1]), b"g(1) \n"); assert_eq!(tail(lines[2]), elided(b"f(", b") \n")); assert_eq!(tail(lines[3]), b"g('\xff')\n"); + assert_eq!(tail(lines[4]), elided(b"f(", b", '\xff')\n")); + assert_eq!(tail(lines[5]), b"g(1) \n"); } /// Rendering every match asks no node for its parent. The per-match @@ -1160,6 +1199,8 @@ mod tests { /// Under `-t all` every byte of a one-row file is printed exactly /// once: by the deepest match holding it, and by none around it. /// The per-match dump printed each byte once per match above it. + /// Read off the rendered lines, so the claim is about what the + /// render prints and not only about the pieces `own_text` offers it. #[cfg(feature = "cpp")] #[test] fn found_render_prints_each_byte_of_one_row_once() { @@ -1167,17 +1208,26 @@ mod tests { let ast = parse_as(crate::LANG::Cpp, code); let found = found(&ast, &["all"]); assert!(found.iter().all(|node| node.start_row() == node.end_row())); - let spans: Vec> = found - .iter() - .map(|node| node.start_byte()..node.end_byte()) + let rendered = found_text(&ast, &["all"]); + assert_eq!(rendered.lines().count(), found.len(), "{rendered}"); + let mut printed: Vec = rendered + .lines() + .flat_map(|line| { + let (_, text) = line.split_once(" : ").expect("a one-row snippet"); + let text = text.strip_suffix(' ').expect("a UTF-8 snippet's space"); + text.split(ELIDED).flat_map(str::bytes) + }) .collect(); - let next = next_outside(&spans); - let printed: usize = (0..spans.len()) - .flat_map(|at| own_text(&spans, &next, at)) - .map(|piece| piece.len()) + // The same bytes as the source, each once; sorted, since the + // render prints them in match order rather than source order. + printed.sort_unstable(); + let mut source = code.to_vec(); + source.sort_unstable(); + assert_eq!(printed, source, "{rendered}"); + let spanned: usize = found + .iter() + .map(|node| node.end_byte() - node.start_byte()) .sum(); - assert_eq!(printed, code.len()); - let spanned: usize = spans.iter().map(ExactSizeIterator::len).sum(); assert!(spanned > 3 * code.len(), "the fixture must nest: {spanned}"); } From f864093079324020a89e6ceec806aa3c9942904e Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Fri, 6 Nov 2026 00:49:32 -0800 Subject: [PATCH 13/25] test(deny): pin the version floor and run steps Three perturbations of check-deny-manifests.sh and its workflows passed the self-test: - `-lt` -> `-ne` in the minor comparison refuses every 0.x above 0.20, CI's next pin, but every test ran 0.20.2 (the floor's own minor) or 1.0.0. A 0.21.0 stub now has to be accepted. - Deleting the unreadable-version refusal lets `[ x -eq 0 ]` error inside the `if`, which bash reads as false, so the gate ran an unknown cargo-deny. No test gave it an unreadable version. - Commenting out either workflow's `run:` step still passed, because the wiring test was a substring match on the YAML. It now matches a step's `run:` line. Each case was run with the scratch driver before and after the fix: all three were uncaught before and are caught after. The other 22 cases (count, pathspec, --config order and path, --locked, failure collection, usage, pin drift) were caught before as well. Refs #1823 --- utils/check-deny-manifests-test.py | 23 ++++++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) diff --git a/utils/check-deny-manifests-test.py b/utils/check-deny-manifests-test.py index 8cc068b73..d42495ba7 100644 --- a/utils/check-deny-manifests-test.py +++ b/utils/check-deny-manifests-test.py @@ -256,6 +256,24 @@ def test_cargo_deny_with_a_newer_major_is_accepted(self) -> None: self.assertEqual(result.returncode, 0, result.stderr) self.assertEqual(len(self._invocations()), len(CRATE_DIRS)) + def test_cargo_deny_with_a_newer_minor_is_accepted(self) -> None: + # The floor is a floor: CI's next pin is a 0.x minor above 20. + # Every other test runs 0.20.2, the floor's own minor, so a + # comparison that admitted that minor alone (`-ne` for `-lt`) + # would pass them all and refuse the bump. + result = self._run("advisories", STUB_DENY_VERSION="0.21.0") + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(len(self._invocations()), len(CRATE_DIRS)) + + def test_unreadable_cargo_deny_version_is_refused(self) -> None: + # Without this refusal, `[ x -eq 0 ]` errors inside the version + # `if`, which bash reads as false, and the gate runs a cargo-deny + # whose version it never established. + result = self._run(*ALL_CHECKS, STUB_DENY_VERSION="unknown") + self.assertEqual(result.returncode, 2, result.stderr) + self.assertIn("cannot read a version from 'cargo-deny unknown'", result.stderr) + self.assertEqual(self._invocations(), []) + # --- the live tree --- def test_live_tree_tracks_exactly_these_lockfiles(self) -> None: @@ -275,6 +293,9 @@ class WorkflowWiringTest(unittest.TestCase): WORKFLOWS = ("ci.yml", "deny-advisories.yml") PIN = re.compile(r"cargo-deny@(\d+\.\d+\.\d+)") + # A step's `run:` line, so a commented-out step or a mention in a + # comment does not count as a call. + RUN = re.compile(r"^\s*(?:-\s+)?run:\s*\./utils/check-deny-manifests\.sh\s", re.M) def test_both_workflows_call_the_script_on_one_pinned_cargo_deny(self) -> None: # A workflow left on `cargo-deny-action`, or one that stops calling @@ -286,7 +307,7 @@ def test_both_workflows_call_the_script_on_one_pinned_cargo_deny(self) -> None: encoding="utf-8" ) with self.subTest(workflow=name): - self.assertIn("./utils/check-deny-manifests.sh ", text) + self.assertRegex(text, self.RUN) self.assertNotIn("cargo-deny-action@", text) pins[name] = set(self.PIN.findall(text)) self.assertEqual(len(pins[name]), 1, pins[name]) From 553334a47ffa122fb57a3fd94e3f3430ad21cbe9 Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Fri, 6 Nov 2026 00:50:09 -0800 Subject: [PATCH 14/25] test(roles): pin a parent list on a parentless node `role_table!`'s parent-list gate documents that a node with no parent is under nothing, so `under` rejects it and `not_under` admits it. No test asked a list with no parent: flipping `is_some_and` to `is_none_or` in the `@gate under` arm (which `not_under` negates) failed none of the 6,946 tests of the ast, root, cli, web and bench crates (`utils/perturb.py`, `--lib --tests --no-fail-fast`), because every owner of the `dsl_parent_gates` fixture has a parent. `a_parent_list_reads_a_parentless_node_as_under_nothing` asks the fixture's `under` and `not_under` owners under an empty known chain, the walk's record of the root, and counts the nodes it asked. Refs #1794 --- big-code-analysis-ast/src/roles/mod.rs | 32 ++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/big-code-analysis-ast/src/roles/mod.rs b/big-code-analysis-ast/src/roles/mod.rs index 56bdc46d2..421d5b1f0 100644 --- a/big-code-analysis-ast/src/roles/mod.rs +++ b/big-code-analysis-ast/src/roles/mod.rs @@ -3240,6 +3240,38 @@ mod tests { assert_eq!(container::OWNERS, &[Java::ClassDeclaration as u16]); } + /// A node with no parent is under nothing (#1794): `under` rejects + /// it and `not_under` admits it, whatever the list. Every owner in + /// the fixture has a parent, so the test above cannot see this + /// clause; an empty known chain is the walk's record of the root. + #[cfg(feature = "java")] + #[test] + fn a_parent_list_reads_a_parentless_node_as_under_nothing() { + use crate::JavaCode; + use crate::test_support::for_each_node_with_chain; + use dsl_parent_gates::{branch, r#loop}; + let source = PARENT_LIST_FIXTURE; + let none = Ancestors::known(&[]); + let (mut branches, mut loops) = (0, 0); + for_each_node_with_chain::(source, |node, _| { + if node.kind_id() == Java::IfStatement as u16 { + assert!( + !branch::owns(node, source, none), + "`under` admitted a parentless `if`" + ); + branches += 1; + } + if node.kind_id() == Java::WhileStatement as u16 { + assert!( + r#loop::owns(node, source, none), + "`not_under` rejected a parentless `while`" + ); + loops += 1; + } + }); + assert_eq!((branches, loops), (3, 2)); + } + /// A list beside `pays_itself` and `pays_itself_when` (#1794): the /// leaf pays where the list admits the owner and only there, and a /// `pays_itself_when` still asks its `when`. From 3ccbb4a41f6bd6230b1c09b8d6336deea45200d4 Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Fri, 6 Nov 2026 08:45:03 -0800 Subject: [PATCH 15/25] fix: address the batch's whole-branch review cargo-deny (#1823): read the root graph with --workspace (without it 155 of 374 crates went unread), refuse a lower major version as well as a lower minor, and list tracked lockfiles with --deduplicate. check-excluded-manifests.py now fails an excluded crate that tracks no Cargo.lock, the direction the count cannot see. The self-test drops every inherited GIT_* variable, which under a hook pointed its scratch git calls at the real repository's index, and pins each workflow's exact check set. The pre-commit hook matches any Cargo.lock, and AGENTS.md names both counts a ninth lockfile raises. role_table! (#1794): a payer's parent list names at least one kind, pinned by a compile_fail doctest, and the token-form @clause shims are gone. Java's directive `static` reads not_under [ImportDeclaration, RequiresModifier], as Groovy's does, in place of the not_in_a_directive gate fn. Doxygen (#1795): each path to the DocTarget row tests for a conditional on its own; the docs said either guard covered both. doxygen_entry_never_reenters_the_conditional_walk adds a nest that declares nothing, the only shape on which children_declare asking the row first shows (4,095 reads against 12). The C-family is_preproc_conditional_kind is pub(crate) and named in the roles module's consumer conventions. find (#1416): an I/O-error sweep over the renderer. The book's find output section, STABILITY.md on the hidden find renderers, and the mutation-testing note on parent lists are corrected. Refs #1823 #1794 #1795 #1416 --- .bca-baseline.toml | 4 +- .claude/rules/grammar-dispatch.md | 3 +- .pre-commit-config.yaml | 2 +- AGENTS.md | 8 +- STABILITY.md | 8 +- .../src/lang_helpers/doxygen.rs | 100 +++++++++--------- big-code-analysis-ast/src/roles/c_family.rs | 8 +- big-code-analysis-ast/src/roles/groovy.rs | 2 +- big-code-analysis-ast/src/roles/java.rs | 30 ++---- big-code-analysis-ast/src/roles/mod.rs | 47 +++----- .../src/roles/parent_list_doctests.rs | 17 ++- big-code-analysis-book/src/commands/nodes.md | 9 +- .../src/recipes/ast-queries.md | 3 +- docs/development/mutation_testing.md | 5 +- src/output/dump.rs | 17 +++ utils/check-deny-manifests-test.py | 65 +++++++++--- utils/check-deny-manifests.sh | 33 ++++-- utils/check-excluded-manifests-test.py | 45 +++++++- utils/check-excluded-manifests.py | 45 +++++++- 19 files changed, 307 insertions(+), 144 deletions(-) diff --git a/.bca-baseline.toml b/.bca-baseline.toml index 7f6eb4518..56bb12743 100644 --- a/.bca-baseline.toml +++ b/.bca-baseline.toml @@ -365,13 +365,13 @@ value = 5.0 path = "big-code-analysis-ast/src/roles/mod.rs" qualified = "" metric = "loc.ploc" -value = 914.0 +value = 895.0 [[entry]] path = "big-code-analysis-ast/src/roles/mod.rs" qualified = "" metric = "loc.sloc" -value = 2263.0 +value = 2250.0 [[entry]] path = "big-code-analysis-ast/src/tools.rs" diff --git a/.claude/rules/grammar-dispatch.md b/.claude/rules/grammar-dispatch.md index c876b1fa5..bc019a5ca 100644 --- a/.claude/rules/grammar-dispatch.md +++ b/.claude/rules/grammar-dispatch.md @@ -192,7 +192,8 @@ deliberate double count is a visible choice at the consumer, never an accident on the row. The compound-operator case above is still the consumer's: the row owns `not in` and pays its token, and returning `Unknown` for the inner `not` *under* the compound is a parent guard -in the classifier, which a row cannot spell. +in the classifier, which a payer cannot spell: a payer takes +`under [..]`, never `not_under` (#1794). ## 6. Narrow a dispatch set with a gate, never by deletion diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 662c75299..1ea2be915 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -643,7 +643,7 @@ repos: - id: check-deny-manifests-test name: check-deny-manifests-test language: system - files: '^(utils/check-deny-manifests(\.sh|-test\.py)|\.github/workflows/(ci|deny-advisories)\.yml|([^/]+/)?Cargo\.lock)$' + files: '^(utils/check-deny-manifests(\.sh|-test\.py)|\.github/workflows/(ci|deny-advisories)\.yml|(.+/)?Cargo\.lock)$' entry: python3 -m unittest -q utils/check-deny-manifests-test.py pass_filenames: false diff --git a/AGENTS.md b/AGENTS.md index 8e3d555e6..94c27b0ca 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -722,8 +722,12 @@ Dependabot or Scorecard or not at all; a RUSTSEC `unsound` / and no issue is filed. The fix is the same as for a red `deny` job: move the lockfile past the advisory, or add a documented `ignore` to `deny.toml`, which is keyed by advisory id and so covers all eight -graphs. A ninth lockfile fails the script until its -`EXPECTED_LOCKFILES` is raised. +graphs. The root's graph is rooted at every workspace member +(`--workspace`), not at the `big-code-analysis` package alone. A ninth +tracked lockfile fails the script until its `EXPECTED_LOCKFILES` and +the self-test's `CRATE_DIRS` are raised; an excluded crate that tracks +no lockfile fails `utils/check-excluded-manifests.py` instead, since +the script cannot see a graph with nothing to list. For snapshot test changes, run `cargo insta test --review` and accept or reject each snapshot rather than blindly updating files. diff --git a/STABILITY.md b/STABILITY.md index ecece2d7f..98c569619 100644 --- a/STABILITY.md +++ b/STABILITY.md @@ -530,7 +530,8 @@ re-finalizes under any key without a re-walk). The following are explicitly **not** part of the shape contract: - Anything marked `#[doc(hidden)]`. These exist for macro plumbing - and may move at any time, including in patch bumps. + or for this workspace's own crates (the CLI, the bench) and may + move at any time, including in patch bumps. - **The `big-code-analysis-ast` crate.** Since #1376 the parse and classification layer lives in a separate published crate that this one pins at an exact `=X.Y.Z` version: the generated kind enums, the @@ -968,7 +969,10 @@ consumes. Each terminal dump entry point also has a `dump_ops_with_color`, `dump_function_spans_with_color`) that takes a `ColorMode` (`Auto` / `Always` / `Never`); the bare forms retain their historical always-colored behavior. These were added in a minor bump -(issue #605) and are part of the stable surface going forward. +(issue #605) and are part of the stable surface going forward. The +`bca find` renderer and its sink form (`dump_found_with_color`, +`write_found`, #1416) are not: they are `#[doc(hidden)]`, re-exported +for the CLI and the scaling bench. #### CSV columns diff --git a/big-code-analysis-ast/src/lang_helpers/doxygen.rs b/big-code-analysis-ast/src/lang_helpers/doxygen.rs index 3dc17d238..0a0999241 100644 --- a/big-code-analysis-ast/src/lang_helpers/doxygen.rs +++ b/big-code-analysis-ast/src/lang_helpers/doxygen.rs @@ -528,11 +528,11 @@ pub(crate) fn doxygen_target<'a, T: DoxygenRow>( /// `roles/c_family.rs`) less the conditional owners, plus a parse error /// holding an entry. The conditional test comes *first*, so a /// conditional is no entry here whatever it holds and the row's -/// `conditional_declares` gate is never reached through this fn — -/// [`conditional_declares`]'s own post-order walk asks the entry question -/// ([`non_conditional_entry`]) of a conditional's non-conditional -/// children only and reads its memo for the rest, so the two defences are -/// independent and either alone keeps the walk from re-entering itself. +/// [`conditional_declares`] gate is never reached through this fn. Each +/// path to the row makes that test on its own, and neither covers the +/// other: this fn's, which the walk reaches through an error's sole +/// child ([`no_entry_inside`]), and [`children_declare`]'s, which asks +/// [`non_conditional_entry`] of a conditional's other children only. /// Code the grammar could not parse, often behind a macro Doxygen's /// preprocessor would expand, is given the benefit of the doubt, as /// before #1613, rather than dropping the block on a parse failure; an @@ -841,56 +841,60 @@ mod tests { } } - /// `doxygen_entry` must test `preproc_conditional` *before* reading - /// the row: the row's conditional owners are gated by + /// Each path to the row tests `preproc_conditional` *before* reading + /// it: the row's conditional owners are gated by /// `conditional_declares`, so the other order would run that walk - /// from inside an entry question about a conditional. Two defences - /// keep the walk from re-entering itself — this order, and the - /// walk asking the entry question of non-conditional children only — - /// and when it had the first alone, reversing it cost `2^depth - 1` - /// reads on the uncached path (4,095 at this depth) against `depth`. - /// Pinned by count on the uncached path: asking the entry question - /// of the outermost conditional must read **nothing** — it is no - /// entry whatever it holds, and the reversed order reads the nest - /// once — and asking `conditional_declares` of it reads each level - /// once (#1699). + /// from inside a question about a conditional. Pinned by count on the + /// uncached path, one assertion per path. The entry question + /// (`doxygen_entry`) of the outermost conditional reads **nothing** — + /// it is no entry whatever it holds, and the reversed order reads the + /// nest once. `conditional_declares` of it reads each level once, + /// where `children_declare` asking the row first costs `2^depth - 1` + /// (4,095 at this depth) on the nest declaring nothing; on the nest + /// with an entry each re-entered walk answers `true` and ends the + /// level, so that order reads `depth` there and only the other nest + /// tells (#1699, #1795). #[cfg(feature = "c")] #[test] fn doxygen_entry_never_reenters_the_conditional_walk() { use crate::node::Tree; const DEPTH: usize = 12; - let source = format!( - "{}int x;\n{}", - "#ifdef A\n".repeat(DEPTH), - "#endif\n".repeat(DEPTH) - ); - let tree = Tree::new::(source.as_bytes()); - let outermost = tree - .get_root() - .preorder() - .find(|node| preproc_conditional::(node)) - .expect("a nest"); - // Both uncached contexts: a known chain, under which the walk - // hands each child a one-entry chain, and no chain at all (a - // `find` / `count` consumer), under which the walk hands the - // climbing context through unchanged. - for uncached in [Ancestors::known(&[]), Ancestors::unknown()] { - let before = conditionals_read::observed(); - assert!(!doxygen_entry::(&outermost, uncached)); - assert_eq!( - conditionals_read::observed() - before, - 0, - "an entry question reads no nest" - ); - let before = conditionals_read::observed(); - assert!(conditional_declares::( - &outermost, uncached - )); - assert_eq!( - conditionals_read::observed() - before, - DEPTH, - "one walk, each level once" + for (bottom, declares) in [("int x;\n", true), ("#include \n", false)] { + let source = format!( + "{}{bottom}{}", + "#ifdef A\n".repeat(DEPTH), + "#endif\n".repeat(DEPTH) ); + let tree = Tree::new::(source.as_bytes()); + let outermost = tree + .get_root() + .preorder() + .find(|node| preproc_conditional::(node)) + .expect("a nest"); + // Both uncached contexts: a known chain, under which the walk + // hands each child a one-entry chain, and no chain at all (a + // `find` / `count` consumer), under which the walk hands the + // climbing context through unchanged. + for uncached in [Ancestors::known(&[]), Ancestors::unknown()] { + let before = conditionals_read::observed(); + assert!(!doxygen_entry::(&outermost, uncached)); + assert_eq!( + conditionals_read::observed() - before, + 0, + "{bottom}: an entry question reads no nest" + ); + let before = conditionals_read::observed(); + assert_eq!( + conditional_declares::(&outermost, uncached), + declares, + "{bottom}" + ); + assert_eq!( + conditionals_read::observed() - before, + DEPTH, + "{bottom}: one walk, each level once" + ); + } } } diff --git a/big-code-analysis-ast/src/roles/c_family.rs b/big-code-analysis-ast/src/roles/c_family.rs index 2f5046354..77f0882e1 100644 --- a/big-code-analysis-ast/src/roles/c_family.rs +++ b/big-code-analysis-ast/src/roles/c_family.rs @@ -374,9 +374,9 @@ pub(crate) use { // strings equals the row — exactly. A preprocessor conditional holding // an entry in any branch at any depth is a target too, through the // post-order memo in `lang_helpers::doxygen::conditional_declares`, -// which reads the rows back as "entry without conditionals" -// (`doxygen_entry`) and must never be asked of a conditional from -// inside its own walk. The `ERROR` node — an entry when it holds one +// which reads the rows back as "entry without conditionals" and so +// asks them of no conditional: each path to them there tests for one +// first, on its own. The `ERROR` node — an entry when it holds one // — is the sentinel no row may own, and stays the Checker's clause. // --------------------------------------------------------------------- @@ -523,7 +523,7 @@ macro_rules! preproc_conditional_kind { /// beside them; read through `DoxygenRow::conditional_kind`. #[inline] #[must_use] - pub fn is_preproc_conditional_kind(kind: u16) -> bool { + pub(crate) fn is_preproc_conditional_kind(kind: u16) -> bool { $(kind == $crate::$lang::$kind as u16)||+ } }; diff --git a/big-code-analysis-ast/src/roles/groovy.rs b/big-code-analysis-ast/src/roles/groovy.rs index 2e40c63d7..c7097e1cd 100644 --- a/big-code-analysis-ast/src/roles/groovy.rs +++ b/big-code-analysis-ast/src/roles/groovy.rs @@ -320,7 +320,7 @@ role_table! { // with the control keywords. The `static` of `import static` sits // under the `import_declaration`, a directive that qualifies no // declaration; Java's row reads the same parent, and the reasoning - // (#1600) is on its `not_in_a_directive`. + // (#1600) is in the comment above it. Modifier { owns [ Public, Private, Protected, Static(not_under [ImportDeclaration]), Abstract, Final, diff --git a/big-code-analysis-ast/src/roles/java.rs b/big-code-analysis-ast/src/roles/java.rs index c245f8d3d..7f65e9daf 100644 --- a/big-code-analysis-ast/src/roles/java.rs +++ b/big-code-analysis-ast/src/roles/java.rs @@ -41,24 +41,6 @@ fn has_class_body(node: &Node<'_>, _code: &[u8]) -> bool { java_anonymous_class_body(node).is_some() } -/// Whether a `static` qualifies a declaration rather than a directive: -/// the `static` of `import static` and `requires static` bills nothing, -/// because its own keyword — `import`, `requires` — bills nothing here. -/// Java and Groovy bill no directive keyword at all (`package`, -/// `import`, `module`, `requires`, `exports`, `transitive`), measured -/// on a fixture of each; C# bills `using` and so `using static` in -/// full. The two readings are each consistent and #1600 keeps both, -/// recording C# as the outlier in the book's Halstead rules: dropping -/// this guard would bill one directive word and no other. -fn not_in_a_directive<'a>(node: &Node<'a>, _code: &[u8], ancestors: Ancestors<'a, '_>) -> bool { - !ancestors.parent(node).is_some_and(|p| { - matches!( - p.kind_id().into(), - Java::ImportDeclaration | Java::RequiresModifier - ) - }) -} - // `else if` is an `if_statement` whose previous sibling is the bare `else` // token — no clause wrapper — so a nested `if` under `else { … }` follows // `{` instead (#1697). @@ -277,10 +259,18 @@ role_table! { // bills with the control keywords. `sealed` and `permits` // (`Permits2`; `Permits` is the clause) are contextual, and the // grammar parses each used as a name (`var sealed = 1`, - // `int permits`) as an `identifier`, so they need no gate. + // `int permits`) as an `identifier`, so they need no gate. The + // `static` of `import static` and `requires static` sits under an + // `import_declaration` / `requires_modifier`, a directive that + // qualifies no declaration. Java bills no directive word (`package`, + // `import`, `module`, `requires`, `exports`, `transitive`, measured + // on a fixture of each), so without the list this would be the one + // that bills; #1600 records C#, which bills `using static` in full, + // as the outlier in the book's Halstead rules. Modifier { owns [ - Public, Private, Protected, Static(gated_by not_in_a_directive), Abstract, Final, + Public, Private, Protected, Static(not_under [ImportDeclaration, RequiresModifier]), + Abstract, Final, Native, Strictfp, Synchronized, Transient, Volatile, Sealed, NonDASHsealed, Permits2, ] } diff --git a/big-code-analysis-ast/src/roles/mod.rs b/big-code-analysis-ast/src/roles/mod.rs index 421d5b1f0..37d9a9e0c 100644 --- a/big-code-analysis-ast/src/roles/mod.rs +++ b/big-code-analysis-ast/src/roles/mod.rs @@ -140,8 +140,9 @@ //! type-level cycle (`roles` → `checker` → `roles`) that is harmless //! exactly while the `Checker` methods it reaches read *other* rows, or //! read this one only through a projection that cannot re-enter the -//! gate (`doxygen_entry` tests `preproc_conditional` first; -//! `doxygen_entry_never_reenters_the_conditional_walk` pins it). +//! gate (`doxygen_entry` and the walk's `children_declare` each test +//! `preproc_conditional` first; `doxygen_entry_never_reenters_the_conditional_walk` +//! pins both). //! //! # The row grammar //! @@ -432,7 +433,11 @@ //! row holds it for its own reason (Java's `DocBodyResidual`) or //! recorded under `excludes` on the owner's row (Groovy). A DSL `body` //! attribute would be the declared form if a third grammar needs it -//! (#1701). +//! (#1701). A grammar-fact subset of a row's owners takes the same +//! 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). //! - **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`, @@ -1391,7 +1396,7 @@ macro_rules! role_table { }; // A payer's `under P` / `under [P, Q]` is carried as a bracketed // parent list, so the row body's payer pattern needs one shape. - (@owners $cont:tt [$($acc:tt)*] $k:ident under [ $($p:ident),* $(,)? ] $(, $($rest:tt)*)?) => { + (@owners $cont:tt [$($acc:tt)*] $k:ident under [ $($p:ident),+ $(,)? ] $(, $($rest:tt)*)?) => { $crate::role_table!(@owners $cont [$($acc)* $k under [$($p),*],] $($($rest)*)?); }; (@owners $cont:tt [$($acc:tt)*] $k:ident under $p:ident $(, $($rest:tt)*)?) => { @@ -1578,8 +1583,8 @@ macro_rules! role_table { ancestors: Ancestors<'a, '_>, ) -> bool { $( $crate::role_table!( - @clause [$lang kind node code ancestors] $payer - $(gated_by $payer_gate)? $(under [$($payer_parent),*])? + @clause_gated [$lang kind node code ancestors] $payer + [$($payer_gate)? $(under [$($payer_parent),*])?] ); )* $( $crate::role_table!( @scan self_payer_done [$mode] [$lang kind node code ancestors] $owner @@ -1921,11 +1926,13 @@ macro_rules! role_table { // In `owns`: the owner's clause, gated or not. The gate slot — `[]`, // `[g]`, `[g no_chain]`, `[under [..]]` or `[not_under [..]]` — is // handed to `@gate` whole, here and in every terminal below that - // emits a clause; an empty slot renders as `true`. Only - // `holds_payer` is read off the slot first, since it changes the - // clause rather than gating it. + // emits a clause; an empty slot renders as `true`. `holds_payer` is + // an `owns`-only mark, read off the slot first here since it changes + // the clause rather than gating it; any other terminal hands it to + // `@gate` as a gate name, so beside `callable`, `opens` or + // `pays_itself` it does not compile. (@owner_done [] $ctx:tt $k:ident [holds_payer $($g:ident $($nc:ident)?)?] $p:tt $s:tt $c:tt) => { - $crate::role_table!(@clause_payer $ctx $k $(gated_by $g $($nc)?)?); + $crate::role_table!(@clause_payer_gated $ctx $k [$($g $($nc)?)?]); }; (@owner_done [] $ctx:tt $k:ident $g:tt $p:tt $s:tt $c:tt) => { $crate::role_table!(@clause_gated $ctx $k $g); @@ -2073,33 +2080,13 @@ macro_rules! role_table { !$crate::role_table!(@gate [$l $kind $n $c $a] [under [$($p),*]]) }; - (@clause [$l:ident $kind:ident $n:ident $c:ident $a:ident] $k:ident) => { - if $kind == $l::$k as u16 { - return true; - } - }; - (@clause $ctx:tt $k:ident gated_by $g:ident $($nc:ident)?) => { - $crate::role_table!(@clause_gated $ctx $k [$g $($nc)?]); - }; (@clause_gated [$l:ident $kind:ident $n:ident $c:ident $a:ident] $k:ident $g:tt) => { if $kind == $l::$k as u16 { return $crate::role_table!(@gate [$l $kind $n $c $a] $g); } }; - // A payer `under [P, Q]`: its parent is one of the listed kinds. - (@clause $ctx:tt $k:ident under [$($p:ident),*]) => { - $crate::role_table!(@clause_gated $ctx $k [under [$($p),*]]); - }; // A `holds_payer` owner: its projection lands on one of the row's // payers, under its gate if it has one. - (@clause_payer [$l:ident $kind:ident $n:ident $c:ident $a:ident] $k:ident) => { - if $kind == $l::$k as u16 { - return project($n).is_some_and(|child| PAYERS.contains(&child.kind_id())); - } - }; - (@clause_payer $ctx:tt $k:ident gated_by $g:ident $($nc:ident)?) => { - $crate::role_table!(@clause_payer_gated $ctx $k [$g $($nc)?]); - }; (@clause_payer_gated [$l:ident $kind:ident $n:ident $c:ident $a:ident] $k:ident $g:tt) => { if $kind == $l::$k as u16 { return $crate::role_table!(@gate [$l $kind $n $c $a] $g) diff --git a/big-code-analysis-ast/src/roles/parent_list_doctests.rs b/big-code-analysis-ast/src/roles/parent_list_doctests.rs index dc6608a96..5cbaddc50 100644 --- a/big-code-analysis-ast/src/roles/parent_list_doctests.rs +++ b/big-code-analysis-ast/src/roles/parent_list_doctests.rs @@ -1,4 +1,4 @@ -//! The owner parent-list shapes `role_table!` rejects (#1794), each a +//! The parent-list shapes `role_table!` rejects (#1794), each a //! `compile_fail` doctest that differs from the control below in one //! respect only. Kept off the macro's own doc so they do not count //! against `roles/mod.rs`: this module exists only under `cfg(doctest)`, @@ -18,7 +18,7 @@ //! } //! Comparison { //! owns [BinaryExpression(holds_payer), InstanceofExpression(text_gated_by always)] -//! pays [EQEQ] +//! pays [EQEQ under [BinaryExpression]] //! } //! } //! # fn main() {} @@ -92,7 +92,8 @@ //! # fn main() {} //! ``` //! -//! And a list names at least one kind: +//! And a list names at least one kind, an owner's or a payer's — an +//! empty one would claim the kind and never admit it: //! //! ```compile_fail //! # #[macro_use] extern crate big_code_analysis_ast; @@ -103,3 +104,13 @@ //! } //! # fn main() {} //! ``` +//! +//! ```compile_fail +//! # #[macro_use] extern crate big_code_analysis_ast; +//! # use big_code_analysis_ast::Java; +//! role_table! { +//! lang: Java; +//! Comparison { owns [BinaryExpression] pays [EQEQ under []] } +//! } +//! # fn main() {} +//! ``` diff --git a/big-code-analysis-book/src/commands/nodes.md b/big-code-analysis-book/src/commands/nodes.md index c187421cf..c985d4570 100644 --- a/big-code-analysis-book/src/commands/nodes.md +++ b/big-code-analysis-book/src/commands/nodes.md @@ -42,7 +42,9 @@ bca find -t ERROR -I "*.ext" /path/to/your/file/or/directory ## Reading `find` output {#find-output} `find` prints a `== ==` banner for each file with a match, then -one line per match in source order: +one line per match in source order. The banner is printed even when +`--line-start` / `--line-end` leave none of the file's matches to +print: ```text == src/main.rs == @@ -51,8 +53,9 @@ one line per match in source order: ╰─ {call_expression:256} from (1, 21) to (1, 25) : h(2) ``` -Each line gives the node type and its `kind_id`, then the 1-based -`(row, column)` where the node starts and ends. A node that fits on +Each line gives the node type and its `kind_id`, then two 1-based +`(row, column)` pairs: the node's first column, and the column just +past its end. A node that fits on one row ends with its source text; one that spans several rows prints none. When one match sits inside another on the same row, the inner match's text is printed on its own line and the outer match shows `…` diff --git a/big-code-analysis-book/src/recipes/ast-queries.md b/big-code-analysis-book/src/recipes/ast-queries.md index 4c2c209c0..bb8829508 100644 --- a/big-code-analysis-book/src/recipes/ast-queries.md +++ b/big-code-analysis-book/src/recipes/ast-queries.md @@ -57,7 +57,8 @@ bca find \ -t unsafe_block ``` -Each match prints the file path and the line range of the node; see +Each match prints the line and column range of the node, under a +banner naming its file; see [Reading `find` output](../commands/nodes.md#find-output) for the format. diff --git a/docs/development/mutation_testing.md b/docs/development/mutation_testing.md index 16b929ab8..5cab34778 100644 --- a/docs/development/mutation_testing.md +++ b/docs/development/mutation_testing.md @@ -98,7 +98,10 @@ text gates, `is_switch_body_kind`, Java's `has_class_body`, PHP's `continues_else_clause`, and the like). cargo-mutants mutates `fn` items it can see in the source, and anything inside a macro is a token tree it never visits: the `owns [...]` / `pays [...]` membership -lists of a `role_table!` invocation, and equally every gate a macro +lists of a `role_table!` invocation and the `under [...]` / +`not_under [...]` parent lists on them — so a gate `fn` moved onto a +row as such a list leaves this selection, as the four #1794 moved +did — and equally every gate a macro *emits* — the thirteen `else_if_parent_clause_gate!` / `else_if_prev_sibling_gate!` invocations, and the gates the `js_family`, `c_family` and `tcl_family` fragments expand to. diff --git a/src/output/dump.rs b/src/output/dump.rs index 2ca3d1ed9..0b28752d1 100644 --- a/src/output/dump.rs +++ b/src/output/dump.rs @@ -1115,6 +1115,23 @@ mod tests { ); } + /// The find renderer surfaces the sink's error at every write and + /// stops there, the elided line's pieces included: `f(g(1))` prints + /// `f(`, `…` and `)`, each coloured on its own, as the test above + /// shows. + #[cfg(feature = "cpp")] + #[test] + fn found_render_propagates_an_io_error_at_every_write() { + let ast = parse_as(crate::LANG::Cpp, b"int a = f(g(1));\n"); + let matches = found(&ast, &["call_expression"]); + assert_eq!(matches.len(), 2); + // 20: two lines of several coloured pieces each; a floor under the + // real count, as in `every_write_position_propagates_an_io_error`. + assert_io_error_propagates_at_every_write(20, |sink| { + render_found(sink, &ast, &matches, ..) + }); + } + /// The shape #1416 measured: one `braced_word` per brace level, so /// the per-match dump printed `depth²` bytes. Every level but the /// innermost now prints its braces around one `…`. diff --git a/utils/check-deny-manifests-test.py b/utils/check-deny-manifests-test.py index d42495ba7..8c29dd305 100644 --- a/utils/check-deny-manifests-test.py +++ b/utils/check-deny-manifests-test.py @@ -65,11 +65,22 @@ """ -def _git_env() -> dict[str, str]: - """The caller's environment with its git configuration shut out.""" - env = os.environ.copy() +def _git_env(home: pathlib.Path) -> dict[str, str]: + """The caller's environment with its git state shut out. + + Every inherited `GIT_*` variable goes, not just the configuration: + git exports `GIT_DIR` and `GIT_INDEX_FILE` to hooks and to `git rebase + --exec` children, and both override `git -C`. Inherited, they sent + this suite's `git init` and `git add` into the real repository — a + `core.bare = true` in its config and an index holding only the + fixtures. `HOME` and `XDG_CONFIG_HOME` point into the scratch tree so + a user-level ignore file cannot hide a fixture lockfile either. + """ + env = {k: v for k, v in os.environ.items() if not k.startswith("GIT_")} env["GIT_CONFIG_GLOBAL"] = os.devnull env["GIT_CONFIG_NOSYSTEM"] = "1" + env["HOME"] = str(home) + env["XDG_CONFIG_HOME"] = str(home / ".config") return env @@ -80,6 +91,9 @@ def _manifest_rel(crate_dir: str) -> str: class DenyManifestsTest(unittest.TestCase): def setUp(self) -> None: self.tmp = pathlib.Path(tempfile.mkdtemp(prefix="bca-deny-manifests-")) + # Registered before anything else in `setUp` can fail, which + # `tearDown` would not be reached for. + self.addCleanup(shutil.rmtree, self.tmp, ignore_errors=True) self.repo = self.tmp / "repo" self.elsewhere = self.tmp / "elsewhere" self.elsewhere.mkdir() @@ -90,7 +104,9 @@ def setUp(self) -> None: stub = stub_dir / "cargo-deny" stub.write_text(STUB_SOURCE.format(python=sys.executable), encoding="utf-8") stub.chmod(0o755) - self.env = _git_env() + home = self.tmp / "home" + home.mkdir() + self.env = _git_env(home) self.env["PATH"] = f"{stub_dir}{os.pathsep}{self.env['PATH']}" self.env["STUB_DENY_LOG"] = str(self.log) @@ -105,9 +121,6 @@ def setUp(self) -> None: self._git("init", "-q") self._git("add", "--", ".") - def tearDown(self) -> None: - shutil.rmtree(self.tmp, ignore_errors=True) - # --- helpers --- def _add_crate(self, crate_dir: str) -> None: @@ -173,6 +186,9 @@ def test_runs_every_check_against_every_manifest(self) -> None: self.assertEqual(argv[config_at + 1], deny_toml) self.assertLess(config_at, argv.index("check")) self.assertIn("--locked", argv[: argv.index("check")]) + # The root manifest is a package too; without this the + # root graph is the library's alone (#1823 review). + self.assertIn("--workspace", argv[: argv.index("check")]) def test_checks_are_forwarded_not_hard_coded(self) -> None: # The weekly job asks for advisories alone. A script that ignored @@ -249,6 +265,20 @@ def test_cargo_deny_older_than_0_20_is_refused(self) -> None: self.assertIn("cargo-deny 0.19.4 is older than 0.20", result.stderr) self.assertEqual(self._invocations(), []) + def test_a_lower_major_than_the_floor_is_refused(self) -> None: + # The floor's major is 0 today, so no real version is below it; + # a copy with the floor raised to 1.20 asks the comparison what + # it will do the day it is, when a check that compared minors + # only within the floor's major would accept every 0.x. + text = self.script.read_text(encoding="utf-8") + raised = text.replace("MIN_DENY_MAJOR=0\n", "MIN_DENY_MAJOR=1\n") + self.assertNotEqual(raised, text, "the floor's major moved") + self.script.write_text(raised, encoding="utf-8") + result = self._run(*ALL_CHECKS, STUB_DENY_VERSION="0.25.0") + self.assertEqual(result.returncode, 2, result.stderr) + self.assertIn("cargo-deny 0.25.0 is older than 1.20", result.stderr) + self.assertEqual(self._invocations(), []) + def test_cargo_deny_with_a_newer_major_is_accepted(self) -> None: # Pins the comparison itself: a check on the minor alone would # refuse 1.0. @@ -291,23 +321,34 @@ def test_live_tree_tracks_exactly_these_lockfiles(self) -> None: class WorkflowWiringTest(unittest.TestCase): """Both `deny` jobs go through the script, on one cargo-deny.""" - WORKFLOWS = ("ci.yml", "deny-advisories.yml") + # Each workflow and the checks its step must pass: the per-PR job all + # four, the weekly one the only check that ages. + WORKFLOWS = { + "ci.yml": set(ALL_CHECKS), + "deny-advisories.yml": {"advisories"}, + } PIN = re.compile(r"cargo-deny@(\d+\.\d+\.\d+)") # A step's `run:` line, so a commented-out step or a mention in a - # comment does not count as a call. - RUN = re.compile(r"^\s*(?:-\s+)?run:\s*\./utils/check-deny-manifests\.sh\s", re.M) + # comment does not count as a call; the group is its arguments. + RUN = re.compile( + r"^\s*(?:-\s+)?run:\s*\./utils/check-deny-manifests\.sh\s+([^#\n]*)", re.M + ) def test_both_workflows_call_the_script_on_one_pinned_cargo_deny(self) -> None: # A workflow left on `cargo-deny-action`, or one that stops calling # the script, audits the root lockfile alone again — the gap #1823 # closed — and nothing else would notice. pins: dict[str, set[str]] = {} - for name in self.WORKFLOWS: + for name, checks in self.WORKFLOWS.items(): text = (REPO_ROOT / ".github" / "workflows" / name).read_text( encoding="utf-8" ) with self.subTest(workflow=name): - self.assertRegex(text, self.RUN) + calls = self.RUN.findall(text) + self.assertEqual(len(calls), 1, calls) + # A step trimmed to `advisories` would still call the + # script and drop three checks from every PR. + self.assertEqual(set(calls[0].split()), checks) self.assertNotIn("cargo-deny-action@", text) pins[name] = set(self.PIN.findall(text)) self.assertEqual(len(pins[name]), 1, pins[name]) diff --git a/utils/check-deny-manifests.sh b/utils/check-deny-manifests.sh index 74dd122b2..f6a9b62a0 100755 --- a/utils/check-deny-manifests.sh +++ b/utils/check-deny-manifests.sh @@ -9,7 +9,9 @@ # The repository tracks eight lockfiles: the root workspace's and one per # `[workspace].exclude` crate (`enums`, `fuzz`, the five `tree-sitter-*`), # each of which roots its own workspace and resolves its own graph. A -# cargo-deny run from the root reads only the first. Until #1823 the other +# cargo-deny run from the root reads only the first — and, without +# `--workspace`, only the part of it the root *package* reaches, since the +# root manifest is a package as well as the workspace. Until #1823 the other # seven were read by the Scorecard job alone, on `main`, after merge: # RUSTSEC-2026-0374 sat in `enums/Cargo.lock` that way and passed every # PR's `deny` job (fixed by #1822). @@ -26,11 +28,13 @@ set -euo pipefail # reads the tree it was invoked from whatever the caller's cwd. ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" -# The root lockfile plus the seven excluded crates'. A lockfile that -# appears or disappears fails the gate until this number is changed by -# hand, so a ninth excluded crate cannot enter the tree unaudited — the -# reasoning `utils/check-excluded-manifests.py` applies to the manifests -# themselves (#1151, #1228). +# The root lockfile plus the seven excluded crates'. A tracked lockfile +# that appears or disappears fails the gate until this number is changed by +# hand, so a new graph is a decision about `deny.toml` rather than a silent +# addition. The other direction — an excluded crate whose lockfile is not +# tracked, which this listing cannot see — is +# `utils/check-excluded-manifests.py`'s, which requires one per +# `[workspace].exclude` entry. EXPECTED_LOCKFILES=8 # cargo-deny 0.20 moved `--config` from the `check` subcommand to the top @@ -65,7 +69,7 @@ minor=${minor%%.*} if ! [[ "$major" =~ ^[0-9]+$ && "$minor" =~ ^[0-9]+$ ]]; then die "cannot read a version from '$version_line'" fi -if [ "$major" -eq "$MIN_DENY_MAJOR" ] && [ "$minor" -lt "$MIN_DENY_MINOR" ]; then +if ((major < MIN_DENY_MAJOR || (major == MIN_DENY_MAJOR && minor < MIN_DENY_MINOR))); then die "cargo-deny $version is older than $MIN_DENY_MAJOR.$MIN_DENY_MINOR," \ "which this script's '--config' placement needs; install CI's pin:" \ "cargo install --locked cargo-deny@0.20.2" @@ -74,8 +78,9 @@ fi # The tracked set, not the filesystem: corpora, `target/` and scratch # checkouts carry lockfiles nobody ships. `**/` also matches the root, # and the glob pathspec keeps `NotCargo.lock` out, which `*Cargo.lock` -# would not. -if ! listing=$(git -C "$ROOT" ls-files -- ':(glob)**/Cargo.lock'); then +# would not. `--deduplicate` lists a conflicted lockfile once, not once +# per merge stage. +if ! listing=$(git -C "$ROOT" ls-files --deduplicate -- ':(glob)**/Cargo.lock'); then die "git ls-files failed in $ROOT; this gate reads the tracked lockfiles" fi locks=() @@ -92,7 +97,8 @@ if [ "${#locks[@]}" -ne "$EXPECTED_LOCKFILES" ]; then printf ' %s\n' ${locks[@]+"${locks[@]}"} echo "An excluded crate was added or removed. Run this script with every" echo "check against the new set, then change EXPECTED_LOCKFILES in" - echo "utils/check-deny-manifests.sh to match." + echo "utils/check-deny-manifests.sh and CRATE_DIRS in" + echo "utils/check-deny-manifests-test.py to match." } >&2 exit 1 fi @@ -103,8 +109,13 @@ for lock in "${locks[@]}"; do echo "==> cargo-deny check $*: $manifest" # `--locked` audits the committed lockfile rather than a graph cargo # re-resolved on the way, and refuses to rewrite a tracked lockfile - # when the script runs in a working tree. + # when the script runs in a working tree. `--workspace` roots the graph + # at every member: the root manifest is also the `big-code-analysis` + # package, and handed a member cargo-deny roots the graph at it alone, + # which left the CLI, web, py, bench and xtask closures (155 of 374 + # crates) unread. On the seven single-package graphs it changes nothing. if ! cargo-deny --locked \ + --workspace \ --manifest-path "$ROOT/$manifest" \ --config "$ROOT/deny.toml" \ check "$@"; then diff --git a/utils/check-excluded-manifests-test.py b/utils/check-excluded-manifests-test.py index 59a8a15ab..288490a6d 100644 --- a/utils/check-excluded-manifests-test.py +++ b/utils/check-excluded-manifests-test.py @@ -551,7 +551,14 @@ class MainTest(unittest.TestCase): text were previously unexecuted by any test. """ - def _repo(self, root_manifest: str, crates: dict[str, str]) -> pathlib.Path: + def _repo( + self, + root_manifest: str, + crates: dict[str, str], + tracked: set[str] | None = None, + ) -> pathlib.Path: + """A synthetic root; `tracked` is what git would list as tracked + lockfiles, by default one per crate, since the root is no repo.""" root = pathlib.Path(self.enterContext(tempfile.TemporaryDirectory())) (root / "Cargo.toml").write_text(root_manifest, encoding="utf-8") for name, body in crates.items(): @@ -561,6 +568,11 @@ def _repo(self, root_manifest: str, crates: dict[str, str]) -> pathlib.Path: self.enterContext( mock.patch.object(GATE, "ROOT_MANIFEST", root / "Cargo.toml") ) + if tracked is None: + tracked = {f"{name}/Cargo.lock" for name in crates} + self.enterContext( + mock.patch.object(GATE, "tracked_lockfiles", lambda _root: tracked) + ) return root def _run(self) -> tuple[int, str]: @@ -578,6 +590,21 @@ def test_a_clean_tree_returns_zero(self) -> None: code, err = self._run() self.assertEqual(code, 0, err) + def test_an_excluded_crate_without_a_tracked_lockfile_is_reported(self) -> None: + # The deny script counts the tracked lockfiles, so a new excluded + # crate with none leaves its count unchanged and its graph + # unaudited; only this gate starts from `exclude` (#1823). + self._repo( + '[workspace]\nexclude = ["a", "b"]\n', + {"a": excluded_crate(), "b": excluded_crate(name="b")}, + tracked={"Cargo.lock", "a/Cargo.lock"}, + ) + code, err = self._run() + self.assertEqual(code, 1) + self.assertIn("without a tracked Cargo.lock:\n b/Cargo.lock\n", err) + self.assertNotIn("a/Cargo.lock", err) + self.assertIn("EXPECTED_LOCKFILES", err) + def test_an_excluded_crate_without_a_lints_table_is_reported(self) -> None: self._repo( '[workspace]\nexclude = ["a"]\n', @@ -660,6 +687,22 @@ def test_a_range_requirement_is_not_suggested_back_with_an_equals(self) -> None: class RealRepositoryTest(unittest.TestCase): + def test_every_excluded_crate_tracks_a_lockfile(self) -> None: + # Asked of the live tree rather than a scratch repository: an + # inherited `GIT_DIR` (a hook, `git rebase --exec`) overrides + # `git -C`, and only for the live tree is that the same repository. + crates = GATE.read_excluded_crates( + (REPO_ROOT / "Cargo.toml").read_text(encoding="utf-8") + ) + tracked = GATE.tracked_lockfiles(REPO_ROOT) + self.assertGreater(len(crates), 0) + self.assertIn("Cargo.lock", tracked) + self.assertEqual(GATE.untracked_lockfiles(crates, tracked), []) + self.assertEqual( + GATE.untracked_lockfiles(crates, tracked - {"fuzz/Cargo.lock"}), + ["fuzz"], + ) + def test_clean_tree_passes(self) -> None: result = subprocess.run( [sys.executable, str(SCRIPT_SRC)], diff --git a/utils/check-excluded-manifests.py b/utils/check-excluded-manifests.py index f69b54a11..fab454338 100644 --- a/utils/check-excluded-manifests.py +++ b/utils/check-excluded-manifests.py @@ -5,7 +5,7 @@ ``[workspace] exclude`` array — the five vendored ``tree-sitter-*`` grammars and the ``enums`` codegen helper. -Three invariants are checked. +Four invariants are checked. **Every excluded crate must root its own workspace.** ``exclude`` denies workspace membership but does **not** terminate cargo's upward @@ -38,6 +38,14 @@ *next* crate added to ``exclude`` forces the same decision instead of inheriting silence. +**Every excluded crate must track its own ``Cargo.lock``.** Each roots +its own workspace and resolves its own graph, and +``utils/check-deny-manifests.sh`` audits exactly the tracked lockfiles +(#1823). That script's count catches a tracked lockfile appearing or +disappearing; a new excluded crate committed without one — or with one +ignored — leaves the count unchanged and its graph unaudited, which +only a check that starts from ``exclude`` can see. + Manifests are parsed with ``tomllib`` rather than matched with regexes. The regex version of this gate silently skipped TOML literal strings (``tree-sitter-cpp = '0.23.4'`` read as no dependency at all), reported @@ -52,6 +60,7 @@ import pathlib import re +import subprocess import sys from typing import Any, Iterator @@ -220,6 +229,22 @@ def missing_workspace_table(crates: list[str], root: pathlib.Path) -> list[str]: return offenders +def tracked_lockfiles(root: pathlib.Path) -> set[str]: + """Return the repo-relative paths of every ``Cargo.lock`` git tracks.""" + listing = subprocess.run( + ["git", "-C", str(root), "ls-files", "--deduplicate", "--", ":(glob)**/Cargo.lock"], + check=True, + capture_output=True, + text=True, + ).stdout + return set(listing.splitlines()) + + +def untracked_lockfiles(crates: list[str], tracked: set[str]) -> list[str]: + """Return excluded crates whose ``Cargo.lock`` is not in ``tracked``.""" + return [crate for crate in crates if f"{crate}/Cargo.lock" not in tracked] + + def workspace_lints(manifest: dict[str, Any]) -> dict[str, Any] | None: """Return a manifest's own ``[workspace.lints]``, or ``None``. @@ -368,6 +393,19 @@ def _report_missing_workspace(offenders: list[str]) -> None: ) +def _report_untracked_lockfiles(offenders: list[str]) -> None: + print( + "error: excluded crates without a tracked Cargo.lock:\n" + + "\n".join(f" {crate}/Cargo.lock" for crate in offenders) + + "\n\nEach excluded crate resolves its own graph, and the cargo-deny\n" + "jobs audit only the lockfiles git tracks (#1823), so this graph is\n" + "never audited. Generate and commit the lockfile, then raise\n" + "EXPECTED_LOCKFILES in utils/check-deny-manifests.sh and CRATE_DIRS\n" + "in utils/check-deny-manifests-test.py to match.", + file=sys.stderr, + ) + + def _report_unlinted(offenders: list[tuple[str, str]]) -> None: print( "error: excluded crates not declaring their own lint set:\n" @@ -405,6 +443,11 @@ def main() -> int: _report_missing_workspace(offenders) return 1 + untracked = untracked_lockfiles(crates, tracked_lockfiles(REPO_ROOT)) + if untracked: + _report_untracked_lockfiles(untracked) + return 1 + # Ordered after the workspace-table check so a crate with no manifest # at all is reported by that one's explicit hard error rather than as # a read failure here. From 135fda7f97f841f56fe05a5d1d570bacc59e683c Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Fri, 6 Nov 2026 08:52:38 -0800 Subject: [PATCH 16/25] docs(mutation): name the gates #1794 moved --- docs/development/mutation_testing.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/docs/development/mutation_testing.md b/docs/development/mutation_testing.md index 5cab34778..7a82dea2f 100644 --- a/docs/development/mutation_testing.md +++ b/docs/development/mutation_testing.md @@ -100,8 +100,10 @@ items it can see in the source, and anything inside a macro is a token tree it never visits: the `owns [...]` / `pays [...]` membership lists of a `role_table!` invocation and the `under [...]` / `not_under [...]` parent lists on them — so a gate `fn` moved onto a -row as such a list leaves this selection, as the four #1794 moved -did — and equally every gate a macro +row as such a list leaves this selection, as Python's +`under_case_clause`, Groovy's `not_in_an_import` and Java's +`not_a_class_literal` and `not_in_a_directive` did under #1794 — and +equally every gate a macro *emits* — the thirteen `else_if_parent_clause_gate!` / `else_if_prev_sibling_gate!` invocations, and the gates the `js_family`, `c_family` and `tcl_family` fragments expand to. From 33d7233d492b0953ee604ed2f4017725ea99dc00 Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Fri, 6 Nov 2026 08:52:38 -0800 Subject: [PATCH 17/25] docs(changelog): add batch 2026-11-05 entries Fixed: the find renderer's linear time (#1416) and the deny jobs over all eight lockfiles (#1823), with the #1815 entry corrected to match. Changed: find's elided nested text and its hidden re-exports (#1416), owner parent lists (#1794) and the NArgs aggregate exception (#1809). Performance: Doxygen conditionals by kind id (#1795). Refs #1416 #1794 #1795 #1809 #1823 --- CHANGELOG.md | 85 ++++++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 83 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5c4e095e3..0d764fd7b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -26,8 +26,9 @@ for historical reference. ### Added -- **A weekly `cargo-deny check advisories` run** against `main`'s - lockfile (`.github/workflows/deny-advisories.yml`, #1815). The +- **A weekly `cargo-deny check advisories` run** against every + lockfile `main` tracks (`.github/workflows/deny-advisories.yml`, + #1815; all eight since #1823, under Fixed). The `deny` job in `ci.yml` runs on push and pull request only, so an advisory published between pushes was seen by Dependabot or the Scorecard job or not at all — and a RUSTSEC `unsound` or @@ -283,6 +284,44 @@ for historical reference. ### Changed +- **`bca find` prints a nested match's text once** (#1416). A match + inside a single-row match prints `…` in the outer match's line, and + its own text on a line of its own: `f(g(1))` lists `f(…)` and + `g(1)` where it listed `f(g(1))` and `g(1)`. A match with no match + nested in it prints byte-identically to before, colour included. + The renderer is reached through two new `#[doc(hidden)]` + re-exports, `dump_found_with_color` and `write_found`, which exist + for the CLI and the scaling bench and are outside the stability + contract (`STABILITY.md`). +- **A `role_table!` owner may carry a parent list** (#1794). + `K(under [P, ..])` admits the owner only under one of the listed + parent kinds and `K(not_under [P, ..])` only under none of them, + read from the walk's ancestor chain. A list fills the owner's one + gate slot, so it excludes `gated_by`, `text_gated_by` and + `holds_payer`; it must name a kind, as a payer's `under [..]` now + must too; it sets `CHAIN_GATED`; and it names kinds it tests rather + than claims, so the three role baselines are unchanged. + `utils/role_tables.py` reads both directions. Five gate fns move onto + their rows: Python's `under_case_clause`, the TypeScript family's + `under_enum_body`, Groovy's `not_in_an_import`, and Java's + `not_a_class_literal` and `not_in_a_directive`. cargo-mutants does + not visit a macro token tree, so the four that were plain fns are no + longer mutation-tested; each moved list was instead flipped and + dropped by `utils/perturb.py` and failed a named test. No output + changes: a drift-oracle sweep over the six languages, 7,028 outputs + in 14 views, found 0 differing for the first four, and the fifth + expands to the parent test its fn spelled. +- **NArgs documents where its aggregates disagree** (#1809). The + extrema fold every space's own count, the file unit and containers + included, while the averages divide by the functions and closures + `nom` counts. A lambda that opens no space adds its parameters to + the enclosing function's `closure_args` yet is one closure of the + divisor, so `closure_args_average` can fall below + `closure_args_min`, and file-level `function_args_min` is always 0. + The `Stats` docs, a new NArgs aggregates subsection in the book and + the Python bindings' metric page now say so. The definition is + unchanged, since changing it moves integration snapshots; #1827 + tracks the same shape in `loc`. - **The agent-feedback recipe documents the OpenCode V2 install** (#1811). The book had only the legacy V1 example and a pointer to the shipped V2 @@ -1078,6 +1117,36 @@ for historical reference. ### Fixed +- **`bca find` renders nested matches in linear time** (#1416). Each + match was rendered by its own `dump_node_with_color` call, which + chose its connector by climbing from the root with `Node::parent`: + `O(depth)` per match, 98% of the 397 ms that 4,000 nested Tcl braces + took. Each single-row match also printed its whole span, so a match + nested k deep had its bytes printed k times: 16 MB of output for an + 8 KB file. A file's matches now render in one pass, and that input + takes 5.8 ms against `count`'s 4.9 ms and prints 243 KB. `make + bench-scaling` prices it with the `find/tcl-nested-braces` probe + beside a `count` control. +- **The `deny` CI job and the weekly advisories run audit all eight + lockfiles** (#1823). Both ran cargo-deny from the repository root + and so read only the root `Cargo.lock`. The seven + `[workspace].exclude` crates (`enums`, `fuzz` and the five vendored + `tree-sitter-*` grammars) each resolve a graph of their own, which + only Scorecard read, on `main`, after merge: RUSTSEC-2026-0374 sat in + `enums/Cargo.lock` that way until #1822. + `utils/check-deny-manifests.sh` now runs cargo-deny once per tracked + `Cargo.lock` against the root `deny.toml`, with `--locked`, and roots + the root's graph at every workspace member (`--workspace`; the + library package alone left 155 of 374 crates unread). It fails when + the tracked count is not eight, and `check-excluded-manifests.py` + fails an excluded crate that tracks no lockfile, so no graph enters + unaudited. Both jobs install cargo-deny 0.20.2 through the SHA-pinned + `taiki-e/install-action`, and the script refuses an older one, since + 0.20 moved `--config` to the top level. The new graphs needed three + narrow fixes: `enums` states the repository's MPL-2.0, `fuzz`'s + `libfuzzer-sys` takes a crate-scoped NCSA exception, and + `allow-wildcard-paths` exempts `fuzz`'s version-less path + dependency, which it allows only in `publish = false` crates. - **`npa` / `npm` (C++, Mozcpp) read the two non-templated member-pointer spellings the grammars' error recovery misparses** (#1807). `int S::*getPd();` is a method returning a pointer to a data @@ -1642,6 +1711,18 @@ for historical reference. ### Performance +- The Doxygen documentation binding of C, C++, Mozcpp and + Objective-C reads preprocessor conditionals by kind id (#1795). + `preproc_conditional` compared five `kind()` strings, and + `conditional_declares` asked it up to three times of each + non-conditional child. Each dialect now tests its `DocTarget` row's + conditional owners with an `is_preproc_conditional_kind` beside its + table, held to the old names over every runtime id, and each child + is classified once. In `make bench-walk` the two nested-conditional + doc shapes run 24% and 12% faster in all 8 interleaved release + rounds; the real corpus slice is within noise (0.999). Output is + byte-identical: a drift-oracle sweep of 42,728 outputs over the four + dialects found 0 differing. - `loc`: a file with no `\`-continuation row skips the bare-row scan (`credit_bare_continuation_rows`) at every node, in every language that runs it (Bash, Tcl, iRules, C, C++, Mozcpp, Objective-C, Ruby, From 6a6a453c6581bb92b82d0d006d6eaa51acf532cb Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Fri, 6 Nov 2026 11:27:44 -0800 Subject: [PATCH 18/25] fix(find): print nested matches whole to 64 levels MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit #1416's renderer elided every match nested in a single-row match, so ordinary output changed: `Some(parse(s))` printed `Some(…)`, a method chain lost its receiver, and `-t all` printed a declaration as `… ……`, while the time cost it was fixing was the parent climb. A match now prints its whole span up to 64 levels of single-row matches nested in one another (`FULL_LEVELS`), and elides past that. The level counts single-row matches only — `prints_snippet` decides both whether a line ends with its text and which matches count, so the two cannot drift — read from the same stack pass as next_outside (`nesting`, folding the two walks the first cut had into one), so the render stays linear and climbs to no parent. Output on the serde, pdf.js and DeepSpeech corpora is byte-identical to main per file under `-t all` and `-t call_expression`; the deepest same-row nesting there is 42. 4,000 nested braces print 751 KB, and twice the depth prints twice the output. Probes: find/tcl-nested-braces fits 1.01, and 1.80 with the limit at usize::MAX. A new width probe, find/tcl-wide-braces-past-the-limit (4,000–16,000 sibling words inside 66 braces, so the level eliding them is past the limit), prices the step from one elided match to the next through next_outside: re-walking the siblings for each fits 1.81 against 1.01 while the depth probe, a chain with one match per level, stays at 1.02 under that mutant. The book, the CHANGELOG's Fixed and Changed entries, the renderer's rustdoc and dispatch_find's comment describe the 64-level rule; `…` is not escaped, which the docs say. Refs #1416 --- CHANGELOG.md | 25 +- big-code-analysis-bench/src/shapes.rs | 71 ++- big-code-analysis-book/src/commands/nodes.md | 23 +- big-code-analysis-cli/src/dispatch.rs | 4 +- .../tests/output/dump_headers.rs | 57 +- src/output/dump.rs | 492 +++++++++++++++--- 6 files changed, 567 insertions(+), 105 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0d764fd7b..ac842ec3f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -284,15 +284,16 @@ for historical reference. ### Changed -- **`bca find` prints a nested match's text once** (#1416). A match - inside a single-row match prints `…` in the outer match's line, and - its own text on a line of its own: `f(g(1))` lists `f(…)` and - `g(1)` where it listed `f(g(1))` and `g(1)`. A match with no match - nested in it prints byte-identically to before, colour included. - The renderer is reached through two new `#[doc(hidden)]` - re-exports, `dump_found_with_color` and `write_found`, which exist - for the CLI and the scaling bench and are outside the stability - contract (`STABILITY.md`). +- **`bca find` elides matches nested past 64 levels on one row** + (#1416). From the 65th level of single-row matches nested in one + another, a match prints `…` in place of each match nested in it, + whose own line prints that text. Above that depth nothing changes: + output is byte-identical to before, colour included, which held for + every file of the serde, pdf.js and DeepSpeech corpora under `-t all` + and `-t call_expression`; their deepest same-row nesting is 42. The renderer is reached through two new + `#[doc(hidden)]` re-exports, `dump_found_with_color` and + `write_found`, which exist for the CLI and the scaling bench and are + outside the stability contract (`STABILITY.md`). - **A `role_table!` owner may carry a parent list** (#1794). `K(under [P, ..])` admits the owner only under one of the listed parent kinds and `K(not_under [P, ..])` only under none of them, @@ -1123,8 +1124,10 @@ for historical reference. `O(depth)` per match, 98% of the 397 ms that 4,000 nested Tcl braces took. Each single-row match also printed its whole span, so a match nested k deep had its bytes printed k times: 16 MB of output for an - 8 KB file. A file's matches now render in one pass, and that input - takes 5.8 ms against `count`'s 4.9 ms and prints 243 KB. `make + 8 KB file. A file's matches now render in one pass, with no parent + climbs, and past 64 levels of nesting a match elides what is nested + in it (see Changed), so that input prints 751 KB and twice the depth + prints twice the output. `make bench-scaling` prices it with the `find/tcl-nested-braces` probe beside a `count` control. - **The `deny` CI job and the weekly advisories run audit all eight diff --git a/big-code-analysis-bench/src/shapes.rs b/big-code-analysis-bench/src/shapes.rs index bd27635d3..27b31699b 100644 --- a/big-code-analysis-bench/src/shapes.rs +++ b/big-code-analysis-bench/src/shapes.rs @@ -1472,6 +1472,20 @@ pub fn tcl_nested_braces(depth: usize) -> String { format!("x {}a b{}\n", "{".repeat(depth), "}".repeat(depth)) } +/// Tcl: `width` sibling `{{a}}` words inside 66 nested braces, all on one +/// row, so the innermost brace is past `bca find`'s 64 whole-printed +/// levels and elides each word, and each word elides the brace inside it. +#[must_use] +pub fn tcl_wide_braces_past_the_limit(width: usize) -> String { + let depth = 66; + format!( + "x {}{}{}\n", + "{".repeat(depth), + "{{a}} ".repeat(width), + "}".repeat(depth) + ) +} + /// Tcl: one `eval` line of `width` `{a b} "x"` pairs with a stray `]` /// in the middle of its argument list. /// @@ -1971,10 +1985,33 @@ pub const PROBES: &[Probe] = &[ once chose its connector through `Node::parent`, an \ `O(depth)` climb per match: reinstating it fits \ 2.00 against 0.99. Each single-row match also \ - printed its whole span, `depth²` bytes on this shape: \ - reinstating that fits 1.84, which is why the ladder \ - starts at 4 000. The reading is the lines rendered, one \ - per match.", + printed its whole span, `depth²` bytes on this shape; \ + now only the first 64 levels do, and the rest elide \ + what is nested in them. Printing every level whole \ + again (the limit at `usize::MAX`) fits 1.80 against \ + 1.01, which is why the ladder starts at 4 000. The \ + reading is the lines rendered, one per match.", + }, + Probe { + name: "find/tcl-wide-braces-past-the-limit", + lang: LANG::Tcl, + axis: Axis::Width, + workload: Workload::Find { + filter: "braced_word", + }, + render: tcl_wide_braces_past_the_limit, + sizes: SPACE_MERGE_WIDTHS, + max_exponent: LINEAR_BOUND, + rationale: "The width half of `find/tcl-nested-braces` (#1416): past \ + the 64 whole-printed levels a match elides each match \ + nested in it, stepping from one to the next through \ + `next_outside`, so the level holding `width` words \ + visits each word once. Finding each next word by walking \ + the siblings again from the first prints the same text \ + and passes every renderer test; it fits 1.81 here \ + against 1.01, while the depth probe, a chain with one \ + match per level, stays at 1.02. The reading is the lines \ + rendered, one per match.", }, Probe { name: "dump/tcl-wide-erroring-eval", @@ -5096,6 +5133,32 @@ mod tests { } } + /// The wide find probe renders one line per match, and its words sit + /// past the whole-printed levels: the innermost brace prints a `…` per + /// word. A shape that never reached the elision would time only the + /// whole-span path, which the depth probe already prices. + #[test] + fn the_wide_find_probe_elides_every_word() { + let probe = PROBES + .iter() + .find(|probe| probe.name == "find/tcl-wide-braces-past-the-limit") + .expect("the wide find probe exists"); + let width = 10; + let ast = parse(probe, width); + let lines = probe + .workload + .walk(&ast, probe.workload.options()) + .expect("find walks"); + // 66 braces around the words, and each word is two. + assert_eq!(lines, u64::try_from(66 + 2 * width).expect("small")); + let found = ast.find(&["braced_word".to_owned()]).expect("find walks"); + let mut out = Vec::new(); + big_code_analysis::write_found(&mut out, &ast, &found, ..).expect("render to memory"); + let text = String::from_utf8(out).expect("utf-8 fixture"); + let innermost = text.lines().nth(65).expect("the innermost brace's line"); + assert_eq!(innermost.matches('…').count(), width, "{innermost}"); + } + /// Probe names are unique — they key the report and the gate. #[test] fn probe_names_are_unique() { diff --git a/big-code-analysis-book/src/commands/nodes.md b/big-code-analysis-book/src/commands/nodes.md index c985d4570..51148de57 100644 --- a/big-code-analysis-book/src/commands/nodes.md +++ b/big-code-analysis-book/src/commands/nodes.md @@ -48,7 +48,7 @@ print: ```text == src/main.rs == -╰─ {call_expression:256} from (1, 13) to (1, 26) : f(…, …) +╰─ {call_expression:256} from (1, 13) to (1, 26) : f(g(1), h(2)) ╰─ {call_expression:256} from (1, 15) to (1, 19) : g(1) ╰─ {call_expression:256} from (1, 21) to (1, 25) : h(2) ``` @@ -57,10 +57,23 @@ Each line gives the node type and its `kind_id`, then two 1-based `(row, column)` pairs: the node's first column, and the column just past its end. A node that fits on one row ends with its source text; one that spans several rows prints -none. When one match sits inside another on the same row, the inner -match's text is printed on its own line and the outer match shows `…` -in its place. Each byte of source is therefore printed at most once, -however deeply the matches nest. +none. + +A match nested in another on the same row prints in full, as above, +until the nesting passes 64 levels. From the 65th level down, a match +prints `…` in place of each match nested in it, whose own line prints +that text: + +```text +╰─ {call_expression:256} from (1, 141) to (1, 148) : f(…) +╰─ {call_expression:256} from (1, 143) to (1, 147) : f(1) +``` + +This keeps the output linear in the size of the file: printing every +level in full made a file of 4,000 nested braces print 16 MB. The +`…` is not escaped, so a `…` that is in the source reads the same. +Real code rarely nests past 64 levels on one row: across the serde, +pdf.js and DeepSpeech corpora the deepest is 42, under `-t all`. ## Semantic filters {#semantic-filters} diff --git a/big-code-analysis-cli/src/dispatch.rs b/big-code-analysis-cli/src/dispatch.rs index 2fe88b587..d402fc282 100644 --- a/big-code-analysis-cli/src/dispatch.rs +++ b/big-code-analysis-cli/src/dispatch.rs @@ -535,8 +535,8 @@ fn dispatch_find( writeln!(out, "== {} ==", path.display())?; // One render for every match rather than a `dump_node_with_color` // per match: that asked each match for its parent, `O(depth)` - // apiece, and printed each nested match's text again inside the - // match around it (#1416). + // apiece, and printed each nested match's text again at every + // level around it. Past 64 levels the render elides it (#1416). let lines = ( cfg.line_start.map_or(Bound::Unbounded, Bound::Included), cfg.line_end.map_or(Bound::Unbounded, Bound::Included), diff --git a/big-code-analysis-cli/tests/output/dump_headers.rs b/big-code-analysis-cli/tests/output/dump_headers.rs index 4b87361ef..830e39199 100644 --- a/big-code-analysis-cli/tests/output/dump_headers.rs +++ b/big-code-analysis-cli/tests/output/dump_headers.rs @@ -238,24 +238,63 @@ fn find_stdout(source: &str, args: &[&str]) -> String { .replace(path, "") } -/// #1416: a match nested in a single-row match prints its text on its -/// own line, and the match around it prints `…` in its place. The outer -/// line used to read `f(g(1), h(2))`, so a match nested `N` deep had its -/// bytes printed `N` times: 16 MB for an 8 KB file of nested braces. +/// #1416: ordinary nesting prints each match's whole text, as `bca find` +/// always has, so a pipe through `rg` for a call's text finds it. Only +/// matches nested past 64 levels on one row elide (the test below). #[test] -fn find_prints_a_nested_match_once_and_elides_it_from_the_outer() { +fn find_prints_ordinary_nested_matches_whole() { assert_eq!( - find_stdout("fn main() { f(g(1), h(2)); }\n", &["-t", "call_expression"]), + find_stdout( + "fn main() { let x = Some(parse(s)); a.b().c(); }\n", + &["-t", "call_expression"] + ), concat!( "== ==\n", - "╰─ {call_expression:256} from (1, 13) to (1, 26) : f(…, …) \n", - "╰─ {call_expression:256} from (1, 15) to (1, 19) : g(1) \n", - "╰─ {call_expression:256} from (1, 21) to (1, 25) : h(2) \n", + "╰─ {call_expression:256} from (1, 21) to (1, 35) : Some(parse(s)) \n", + "╰─ {call_expression:256} from (1, 26) to (1, 34) : parse(s) \n", + "╰─ {call_expression:256} from (1, 37) to (1, 46) : a.b().c() \n", + "╰─ {call_expression:256} from (1, 37) to (1, 42) : a.b() \n", "\n", ) ); } +/// #1416: past 64 levels of single-row matches nested in one another, +/// a match prints `…` in place of each match nested in it, whose own +/// line prints that text, so a source byte is printed by at most 65 +/// lines. Printing every level whole made the output quadratic in the +/// depth: 16 MB for an 8 KB file of nested calls or braces. Level 65 is +/// the first that elides, and only visibly when it holds a match of its +/// own, so the fixture nests 66 calls. +#[test] +fn find_elides_nested_matches_past_sixty_four_levels() { + let depth = 66; + let source = format!( + "fn main() {{ {}1{}; }}\n", + "f(".repeat(depth), + ")".repeat(depth) + ); + let out = find_stdout(&source, &["-t", "call_expression"]); + let snippets: Vec<&str> = out + .lines() + .filter_map(|line| line.split_once(" : ").map(|(_, text)| text)) + .collect(); + assert_eq!(snippets.len(), depth, "{out}"); + let whole = |level: usize| { + let rest = depth - level + 1; + format!("{}1{} ", "f(".repeat(rest), ")".repeat(rest)) + }; + assert_eq!(snippets[0], whole(1)); + assert_eq!(snippets[63], whole(64)); + assert_eq!(snippets[64], "f(…) "); + assert_eq!(snippets[65], "f(1) "); + assert_eq!( + snippets.iter().filter(|text| text.contains('…')).count(), + 1, + "only level 65 elides: {out}" + ); +} + /// `--line-start` / `--line-end` keep the matches whose start row lies /// in the inclusive range, either bound optional: the CLI hands the /// renderer one range built from the two flags (#1416). diff --git a/src/output/dump.rs b/src/output/dump.rs index 0b28752d1..4a5408430 100644 --- a/src/output/dump.rs +++ b/src/output/dump.rs @@ -307,13 +307,19 @@ fn write_node_line<'c>( ) -> std::io::Result<()> { write_node_header(stdout, node, prefix, pref)?; write_node_location(stdout, node)?; - // Source snippet for single-row nodes only. - if node.start_row() == node.end_row() { + if prints_snippet(node) { write_snippet(stdout, snippet)?; } writeln!(stdout) } +/// Whether a node's line ends with its source text: single-row nodes +/// only. `bca find`'s nesting levels count these and nothing else, so the +/// two cannot drift apart. +fn prints_snippet(node: &Node) -> bool { + node.start_row() == node.end_row() +} + /// Prefix glyphs followed by the `{kind:kind_id}` tag. fn write_node_header( stdout: &mut dyn WriteColor, @@ -345,9 +351,24 @@ fn write_node_location(stdout: &mut dyn WriteColor, node: &Node) -> std::io::Res } /// What a `bca find` snippet prints in place of a match nested inside -/// it, whose text the nested match's own line prints (#1416). +/// it, whose text the nested match's own line prints (#1416). It is not +/// escaped, so a `…` in the source reads the same. const ELIDED: &str = "…"; +/// How many levels of single-row matches nested in one another `bca +/// find` prints whole before it starts eliding (#1416). +/// +/// Up to and including it a line is what the per-match dump printed, so +/// ordinary nesting — `Some(parse(s))`, a method chain, `-t all` on a +/// statement — reads in full. Past it each level prints [`ELIDED`] for +/// the matches nested in it, so a source byte is printed by at most this +/// many lines plus one and the output stays linear in the input, where +/// the whole span at every level printed `depth²` bytes. Across the +/// serde, pdf.js and DeepSpeech corpora under `-t all`, the deepest +/// same-row nesting is 42 (pdf.js), and every file renders +/// byte-identically to the per-match dump. +const FULL_LEVELS: usize = 64; + /// The `: text` tail of a node line, for `pieces` of `code` with /// [`ELIDED`] between consecutive ones. A dump passes the node's whole /// span as one piece. @@ -385,8 +406,8 @@ fn write_snippet_separator(stdout: &mut dyn WriteColor, text: &str) -> std::io:: /// `found` is what [`Ast::find`] returned for `ast`, in its order, and /// `lines` filters matches by their 1-based start row, as /// `--line-start` / `--line-end` do. A line is what [`dump_node`] at -/// depth 1 renders for the match, so a match no other match is nested -/// in prints byte-identically to that, colour included. The two +/// depth 1 renders for the match, so a match at most [`FULL_LEVELS`] +/// levels deep prints byte-identically to that, colour included. The two /// differences are what keep the render linear in the depth the matches /// nest to (#1416): /// @@ -394,11 +415,12 @@ fn write_snippet_separator(stdout: &mut dyn WriteColor, text: &str) -> std::io:: /// asks [`Node::parent`], which climbs from the root and is `O(depth)`. /// One climb per match was 98% of `bca find`'s time on 4 000 nested /// matches. -/// - A match nested inside a single-row match prints its text on its -/// own line, so the outer match prints [`ELIDED`] in its place: -/// `f(g(1))` renders as `f(…)` followed by `g(1)`. Printing each -/// match's whole span instead made the output quadratic in the -/// nesting depth: 16 MB for an 8 KB file. +/// - Past [`FULL_LEVELS`] levels of single-row matches nested in one +/// another, a match prints [`ELIDED`] in place of each match nested +/// in it, whose own line prints that text: `f(g(1))` at that depth +/// renders as `f(…)` followed by `g(1)`. Printing each match's whole +/// span at every level made the output quadratic in the nesting depth: +/// 16 MB for an 8 KB file. /// /// Hidden because it exists for the CLI, like `format_suggestion`; it /// is outside the stability contract. @@ -418,7 +440,9 @@ pub fn dump_found_with_color( lines: impl RangeBounds, color_mode: ColorMode, ) -> std::io::Result<()> { - print_to_stdout(color_mode, |stdout| render_found(stdout, ast, found, lines)) + print_to_stdout(color_mode, |stdout| { + render_found(stdout, ast, found, lines, FULL_LEVELS) + }) } /// [`dump_found_with_color`] into `out`, uncoloured. Exists so the @@ -438,22 +462,26 @@ pub fn write_found( found: &[Node], lines: impl RangeBounds, ) -> std::io::Result<()> { - render_found(&mut NoColor::new(out), ast, found, lines) + render_found(&mut NoColor::new(out), ast, found, lines, FULL_LEVELS) } +/// The two hidden entry points' renderer, with matches at a level up to +/// `full_levels` printed whole and the deeper ones elided (see +/// [`Nesting::levels`]). Only the tests pass anything but [`FULL_LEVELS`]: `0` +/// elides at every level, which keeps their fixtures small. fn render_found( stdout: &mut dyn WriteColor, ast: &Ast, found: &[Node], lines: impl RangeBounds, + full_levels: usize, ) -> std::io::Result<()> { + // bca: suppress(nargs) — the soft tier only; `full_levels` is the + // tests' seam for the level limit, which bundling with `lines` would + // hide rather than remove let code = ast.source(); let root = ast.root_node().id(); - let spans: Vec> = found - .iter() - .map(|node| node.start_byte()..node.end_byte()) - .collect(); - let next_outside = next_outside(&spans); + let layout = FoundLayout::new(found, full_levels); for (at, node) in found.iter().enumerate() { if lines.contains(&(node.start_row() + 1)) { let connector = if node.id() == root { @@ -466,7 +494,7 @@ fn render_found( node, "", connector.glyphs().1, - own_text(&spans, &next_outside, at).map(|piece| &code[piece]), + layout.pieces(at).map(|piece| &code[piece]), )?; } // `dump_node_with_color` ends each call on white, filtered out @@ -476,35 +504,94 @@ fn render_found( Ok(()) } -/// For each span, the index of the first later span that starts at or -/// after its end, so the matches nested in `spans[at]` are -/// `at + 1..next_outside[at]`. -/// -/// One pass over a stack of the spans still open. In [`Ast::find`]'s -/// pre-order the spans nest or follow one another, so the stack's ends -/// shrink towards the top and a span closes the moment a later one -/// starts past it. Spans in any other order get some answer, never a -/// panic; [`own_text`] does not trust it. -fn next_outside(spans: &[Range]) -> Vec { - let mut next = vec![spans.len(); spans.len()]; +/// Which bytes each of `bca find`'s matches prints: computed once for a +/// file's matches, in one linear pass, then asked per match. +struct FoundLayout { + spans: Vec>, + next_outside: Vec, + levels: Vec, + full_levels: usize, +} + +impl FoundLayout { + fn new(found: &[Node], full_levels: usize) -> Self { + let spans: Vec> = found + .iter() + .map(|node| node.start_byte()..node.end_byte()) + .collect(); + let counted: Vec = found.iter().map(prints_snippet).collect(); + let Nesting { + next_outside, + levels, + } = nesting(&spans, &counted); + Self { + spans, + next_outside, + levels, + full_levels, + } + } + + /// The source ranges match `at`'s line prints, with [`ELIDED`] + /// between consecutive ones: its whole span up to `full_levels`, + /// and past it the parts no match nested in it covers. + fn pieces(&self, at: usize) -> impl Iterator> + '_ { + let whole = (self.levels[at] <= self.full_levels).then(|| self.spans[at].clone()); + let elided = whole + .is_none() + .then(|| own_text(&self.spans, &self.next_outside, at)); + whole.into_iter().chain(elided.into_iter().flatten()) + } +} + +/// How a file's matches nest, per match: see [`nesting`]. +struct Nesting { + /// The index of the first later span that starts at or after this + /// one's end, so the matches nested in `spans[at]` are + /// `at + 1..next_outside[at]`. + next_outside: Vec, + /// How many `counted` spans hold this one, itself included: its level + /// among the single-row matches, which are the ones a line prints + /// text for. A multi-row match raises no level, so a function body + /// around a statement leaves the statement's matches at the levels + /// they have on their row. A zero-width match counts, but holds + /// nothing and prints nothing, so its count is never seen. + levels: Vec, +} + +/// [`Nesting`] for `spans`, in one pass over a stack of the spans still +/// open. In [`Ast::find`]'s pre-order the spans nest or follow one +/// another, so the stack's ends shrink towards the top and a span closes +/// the moment a later one starts past it. Spans in any other order get +/// some answer, never a panic; [`own_text`] does not trust it. +fn nesting(spans: &[Range], counted: &[bool]) -> Nesting { + let mut next_outside = vec![spans.len(); spans.len()]; + let mut levels = vec![0; spans.len()]; let mut open: Vec = Vec::new(); + let mut open_counted = 0; for (at, span) in spans.iter().enumerate() { while let Some(&top) = open.last() && spans[top].end <= span.start { - next[top] = at; + next_outside[top] = at; + open_counted -= usize::from(counted[top]); open.pop(); } + open_counted += usize::from(counted[at]); + levels[at] = open_counted; open.push(at); } - next + Nesting { + next_outside, + levels, + } } /// The parts of `spans[at]` that no match nested in it covers, in /// source order: one piece more than the matches elided from it. /// /// Steps from one directly nested match to the next through -/// [`next_outside`], skipping what is nested deeper, so each match is +/// [`Nesting::next_outside`], skipping what is nested deeper, so each match is /// visited once as the child of the match it sits in and the render /// stays linear. A zero-width match prints nothing and so elides /// nothing. A span that is not inside what remains of `spans[at]` — @@ -973,6 +1060,17 @@ mod tests { String::from_utf8(out).expect("utf-8 fixture") } + /// [`found_text`] with every level past `full_levels` elided, so a + /// fixture a few levels deep can show what the CLI does past + /// [`FULL_LEVELS`]. + #[cfg(any(feature = "cpp", feature = "tcl"))] + fn elided_text(ast: &Ast, filters: &[&str], full_levels: usize) -> String { + let mut sink = NoColor::new(Vec::new()); + render_found(&mut sink, ast, &found(ast, filters), .., full_levels) + .expect("render to memory"); + String::from_utf8(sink.into_inner()).expect("utf-8 fixture") + } + /// What the CLI printed before #1416: one `dump_node_with_color` /// call per match at depth 1, each a walk from the match ending on /// white. Rebuilt from the same private pieces that call is made of, @@ -996,49 +1094,62 @@ mod tests { } } - /// A match printed whole — multi-row, or single-row holding no other - /// match — prints exactly what the per-match dump printed, colour - /// escapes included: the root flush left, a multi-row match with - /// matches inside it (it prints no text, so nothing is elided), - /// leaves, and a non-UTF-8 literal - /// written raw. Under the line filter too, which the two paths spell - /// differently. The old path is the specification here, so the test - /// asks it rather than restating its output. It is rebuilt on the + /// Up to [`FULL_LEVELS`] the render prints exactly what the per-match + /// dump printed, colour escapes included, nested matches as well as + /// lone ones: the root flush left, a multi-row match with matches + /// inside it, calls nested in calls on one row (`f(g(h(1)))`, three + /// levels), the identifiers and literals inside them, and a non-UTF-8 + /// literal written raw. Under the line filter too, which the two paths + /// spell differently. The old path is the specification here, so the + /// test asks it rather than restating its output. It is rebuilt on the /// writers `render_found` shares, though, so it pins what the two /// paths decide differently (connector, filter, trailing white, the /// pieces) and not the escapes themselves: those are /// `found_render_colours_as_the_pre_fix_binary_did`'s. #[cfg(feature = "cpp")] #[test] - fn found_render_matches_the_per_match_dump_when_no_match_nests() { + fn found_render_matches_the_per_match_dump_below_the_level_limit() { use std::ops::Bound::{Included, Unbounded}; - let code = b"int a = 1;\nint f(int b) {\n return g(b, 2);\n}\nchar c = '\xff';\n"; + let code = b"int a = 1;\nint f(int b) {\n return f(g(h(b)), 2);\n}\nchar c = '\xff';\n"; let ast = parse_as(crate::LANG::Cpp, code); let found = found( &ast, &[ "translation_unit", "compound_statement", + "call_expression", "identifier", "number_literal", "char_literal", ], ); - assert!(found.len() >= 9, "the fixture must match widely: {found:?}"); + assert!( + found.len() >= 12, + "the fixture must match widely: {found:?}" + ); assert_eq!(found[0].id(), ast.root_node().id(), "the root is a match"); + let nested = found + .array_windows() + .filter(|[outer, inner]| { + prints_snippet(outer) + && outer.start_byte() <= inner.start_byte() + && inner.end_byte() <= outer.end_byte() + }) + .count(); + assert!(nested >= 3, "the fixture must nest on one row: {nested}"); for (lines, bounds) in [ ((None, None), (Unbounded, Unbounded)), ((Some(2), Some(3)), (Included(2), Included(3))), ] { let (mut new, mut old) = (NoColor::new(Vec::new()), NoColor::new(Vec::new())); - render_found(&mut new, &ast, &found, bounds).expect("render to memory"); + render_found(&mut new, &ast, &found, bounds, FULL_LEVELS).expect("render to memory"); per_match_dump(&mut old, code, &found, lines); assert_eq!(new.get_ref(), old.get_ref(), "plain output under {lines:?}"); let (mut new, mut old) = (Ansi::new(Vec::new()), Ansi::new(Vec::new())); - render_found(&mut new, &ast, &found, bounds).expect("render to memory"); + render_found(&mut new, &ast, &found, bounds, FULL_LEVELS).expect("render to memory"); per_match_dump(&mut old, code, &found, lines); assert!(new.get_ref().contains(&0x1b), "the colour sink colours"); assert_eq!( @@ -1057,16 +1168,35 @@ mod tests { "the root renders flush:\n{text}" ); assert!( - text.contains("╰─ {identifier:1} from (3, 10) to (3, 11) : g \n"), - "{text}" + text.contains(" : f(g(h(b)), 2) \n") && text.contains(" : g(h(b)) \n"), + "nested calls print whole:\n{text}" ); } - /// Each match nested in a single-row match prints on its own line, - /// and the match around it prints `…` in its place — once per - /// directly nested match, never for one nested deeper, which is - /// `h(1)` inside `g(…)` here: stepping to `k(2)` without skipping it - /// would read `h` as a sibling of `g` and stop eliding at it. + /// Ordinary nesting prints every match in full: the reason the level + /// limit exists. Before it, `Some(parse(s))` printed `Some(…)` and a + /// method chain lost its receiver to `….c()`, so a pipe through `rg` + /// for the call's text found nothing. + #[cfg(feature = "cpp")] + #[test] + fn found_render_prints_ordinary_nesting_whole() { + let ast = parse_as(crate::LANG::Cpp, b"int a = f(g(h(1)), k(2));\n"); + assert_eq!( + found_text(&ast, &["call_expression"]), + concat!( + "╰─ {call_expression:350} from (1, 9) to (1, 25) : f(g(h(1)), k(2)) \n", + "╰─ {call_expression:350} from (1, 11) to (1, 18) : g(h(1)) \n", + "╰─ {call_expression:350} from (1, 13) to (1, 17) : h(1) \n", + "╰─ {call_expression:350} from (1, 20) to (1, 24) : k(2) \n", + ) + ); + } + + /// Past the limit, each match nested in a single-row match prints on + /// its own line, and the match around it prints `…` in its place — + /// once per directly nested match, never for one nested deeper, which + /// is `h(1)` inside `g(…)` here: stepping to `k(2)` without skipping + /// it would read `h` as a sibling of `g` and stop eliding at it. #[cfg(feature = "cpp")] #[test] fn found_render_elides_each_nested_match_from_the_one_around_it() { @@ -1074,7 +1204,7 @@ mod tests { let ast = parse_as(crate::LANG::Cpp, code); assert_eq!(found(&ast, &["call_expression"]).len(), 4); assert_eq!( - found_text(&ast, &["call_expression"]), + elided_text(&ast, &["call_expression"], 0), concat!( "╰─ {call_expression:350} from (1, 9) to (1, 25) : f(…, …) \n", "╰─ {call_expression:350} from (1, 11) to (1, 18) : g(…) \n", @@ -1087,20 +1217,43 @@ mod tests { /// The escapes `bca find --color always` prints, held to the binary /// from before #1416 (built from 02150268) instead of to the /// per-match oracle, which goes through the same writers as - /// `render_found` and moves with them. The `g(1)` line is that - /// binary's output verbatim. The `f(…)` line is its `f(g(1))` line - /// with the nested `g(1)` replaced by `…`, painted like the `: ` - /// before it: white, then the snippet's intense red again for the - /// `)` after it. No other test renders a nested match in colour. + /// `render_found` and moves with them. Below the limit both lines are + /// that binary's output verbatim. Past it, the `f(…)` line is its + /// `f(g(1))` line with the nested `g(1)` replaced by `…`, painted + /// like the `: ` before it: white, then the snippet's intense red + /// again for the `)` after it. No other test renders a nested match + /// in colour. #[cfg(feature = "cpp")] #[test] fn found_render_colours_as_the_pre_fix_binary_did() { let ast = parse_as(crate::LANG::Cpp, b"int a = f(g(1));\n"); - let mut sink = Ansi::new(Vec::new()); - render_found(&mut sink, &ast, &found(&ast, &["call_expression"]), ..) + let coloured = |full_levels| { + let mut sink = Ansi::new(Vec::new()); + render_found( + &mut sink, + &ast, + &found(&ast, &["call_expression"]), + .., + full_levels, + ) .expect("render to memory"); + String::from_utf8(sink.into_inner()).expect("utf-8 fixture") + }; assert_eq!( - String::from_utf8(sink.into_inner()).expect("utf-8 fixture"), + coloured(FULL_LEVELS), + concat!( + "\x1b[0m\x1b[34m╰─ \x1b[0m\x1b[38;5;11m{call_expression:350} ", + "\x1b[0m\x1b[37mfrom \x1b[0m\x1b[32m(1, 9) ", + "\x1b[0m\x1b[37mto \x1b[0m\x1b[32m(1, 16) ", + "\x1b[0m\x1b[37m: \x1b[0m\x1b[38;5;9mf(g(1)) \n\x1b[0m\x1b[37m", + "\x1b[0m\x1b[34m╰─ \x1b[0m\x1b[38;5;11m{call_expression:350} ", + "\x1b[0m\x1b[37mfrom \x1b[0m\x1b[32m(1, 11) ", + "\x1b[0m\x1b[37mto \x1b[0m\x1b[32m(1, 15) ", + "\x1b[0m\x1b[37m: \x1b[0m\x1b[38;5;9mg(1) \n\x1b[0m\x1b[37m", + ) + ); + assert_eq!( + coloured(0), concat!( "\x1b[0m\x1b[34m╰─ \x1b[0m\x1b[38;5;11m{call_expression:350} ", "\x1b[0m\x1b[37mfrom \x1b[0m\x1b[32m(1, 9) ", @@ -1127,20 +1280,39 @@ mod tests { assert_eq!(matches.len(), 2); // 20: two lines of several coloured pieces each; a floor under the // real count, as in `every_write_position_propagates_an_io_error`. - assert_io_error_propagates_at_every_write(20, |sink| { - render_found(sink, &ast, &matches, ..) - }); + for full_levels in [FULL_LEVELS, 0] { + assert_io_error_propagates_at_every_write(20, |sink| { + render_found(sink, &ast, &matches, .., full_levels) + }); + } } /// The shape #1416 measured: one `braced_word` per brace level, so - /// the per-match dump printed `depth²` bytes. Every level but the - /// innermost now prints its braces around one `…`. + /// the per-match dump printed `depth²` bytes. Past the limit every + /// level but the innermost prints its braces around one `…`; below + /// it, each prints whole. #[cfg(feature = "tcl")] #[test] fn found_render_elides_nested_braced_words() { let ast = parse_as(crate::LANG::Tcl, b"x {{{a b}}}\n"); assert_eq!( found_text(&ast, &["braced_word"]), + concat!( + "╰─ {braced_word:88} from (1, 3) to (1, 12) : {{{a b}}} \n", + "╰─ {braced_word:88} from (1, 4) to (1, 11) : {{a b}} \n", + "╰─ {braced_word:88} from (1, 5) to (1, 10) : {a b} \n", + ) + ); + assert_eq!( + elided_text(&ast, &["braced_word"], 1), + concat!( + "╰─ {braced_word:88} from (1, 3) to (1, 12) : {{{a b}}} \n", + "╰─ {braced_word:88} from (1, 4) to (1, 11) : {…} \n", + "╰─ {braced_word:88} from (1, 5) to (1, 10) : {a b} \n", + ) + ); + assert_eq!( + elided_text(&ast, &["braced_word"], 0), concat!( "╰─ {braced_word:88} from (1, 3) to (1, 12) : {…} \n", "╰─ {braced_word:88} from (1, 4) to (1, 11) : {…} \n", @@ -1162,7 +1334,7 @@ mod tests { let ast = parse_as(crate::LANG::Cpp, code); let found = found(&ast, &["call_expression"]); let mut sink = NoColor::new(Vec::new()); - write_found(sink.get_mut(), &ast, &found, ..).expect("render to memory"); + render_found(&mut sink, &ast, &found, .., 0).expect("render to memory"); let lines: Vec<&[u8]> = sink.get_ref().split_inclusive(|b| *b == b'\n').collect(); let tail = |line: &[u8]| { let at = line @@ -1213,19 +1385,21 @@ mod tests { ); } - /// Under `-t all` every byte of a one-row file is printed exactly - /// once: by the deepest match holding it, and by none around it. - /// The per-match dump printed each byte once per match above it. - /// Read off the rendered lines, so the claim is about what the - /// render prints and not only about the pieces `own_text` offers it. + /// Eliding at every level, `-t all` prints every byte of a one-row + /// file exactly once: by the deepest match holding it, and by none + /// around it. The per-match dump printed each byte once per match + /// above it. Read off the rendered lines, so the claim is about what + /// the render prints and not only about the pieces `own_text` offers + /// it. [`found_render_prints_each_byte_at_most_limit_plus_one_times`] + /// is the same claim at a limit above zero. #[cfg(feature = "cpp")] #[test] fn found_render_prints_each_byte_of_one_row_once() { let code = b"int a = f(g(1), 2);"; let ast = parse_as(crate::LANG::Cpp, code); let found = found(&ast, &["all"]); - assert!(found.iter().all(|node| node.start_row() == node.end_row())); - let rendered = found_text(&ast, &["all"]); + assert!(found.iter().all(prints_snippet)); + let rendered = elided_text(&ast, &["all"], 0); assert_eq!(rendered.lines().count(), found.len(), "{rendered}"); let mut printed: Vec = rendered .lines() @@ -1248,6 +1422,176 @@ mod tests { assert!(spanned > 3 * code.len(), "the fixture must nest: {spanned}"); } + /// `x` and then `depth` nested Tcl braces around `a b`: one + /// `braced_word` match per level, all on one row. + #[cfg(feature = "tcl")] + fn nested_braces(depth: usize) -> Vec { + let mut code = b"x ".to_vec(); + code.extend(std::iter::repeat_n(b'{', depth)); + code.extend_from_slice(b"a b"); + code.extend(std::iter::repeat_n(b'}', depth)); + code.push(b'\n'); + code + } + + /// The snippets of a rendered `find`, one per line, in order. + #[cfg(any(feature = "cpp", feature = "tcl"))] + fn snippets(rendered: &str) -> Vec<&str> { + rendered + .lines() + .map(|line| line.split_once(" : ").expect("a one-row snippet").1) + .collect() + } + + /// The boundary, at the real limit: levels 1 to [`FULL_LEVELS`] + /// print whole and the first level past it elides. That level is + /// only visible when it holds a match of its own, so the fixture is + /// two levels deeper than the limit, and the levels either side of + /// it pin the comparison: `<` in place of `<=` would elide level 64 + /// as well, and a limit one higher would elide nothing. + #[cfg(feature = "tcl")] + #[test] + fn found_render_elides_from_the_first_level_past_the_limit() { + let depth = FULL_LEVELS + 2; + let code = nested_braces(depth); + let ast = parse_as(crate::LANG::Tcl, &code); + let rendered = found_text(&ast, &["braced_word"]); + let snippets = snippets(&rendered); + assert_eq!(snippets.len(), depth, "one line per level"); + let elided: Vec = snippets + .iter() + .enumerate() + .filter(|(_, s)| s.contains(ELIDED)) + .map(|(at, _)| at + 1) + .collect(); + assert_eq!(elided, [FULL_LEVELS + 1], "the levels printing `…`"); + let whole = |level: usize| { + let rest = depth - level + 1; + format!("{}a b{} ", "{".repeat(rest), "}".repeat(rest)) + }; + assert_eq!(snippets[FULL_LEVELS - 1], whole(FULL_LEVELS)); + assert_eq!(snippets[FULL_LEVELS], format!("{{{ELIDED}}} ")); + assert_eq!(snippets[FULL_LEVELS + 1], whole(FULL_LEVELS + 2)); + } + + /// The level counts single-row matches only. A multi-row match + /// around a row raises nothing, so the statement's call nests at + /// level 1 under a limit of 1 and prints whole; the call inside it, + /// level 2, elides from it. Counting the function body would put the + /// outer call at level 2 and elide it as well. + #[cfg(feature = "cpp")] + #[test] + fn found_render_levels_ignore_multi_row_matches() { + let code = b"int f() {\n return g(h(1));\n}\n"; + let ast = parse_as(crate::LANG::Cpp, code); + let filters = [ + "function_definition", + "compound_statement", + "call_expression", + ]; + let rendered = elided_text(&ast, &filters, 1); + assert!(rendered.contains(" : g(h(1)) \n"), "{rendered}"); + assert!(!rendered.contains(" : g(…)"), "{rendered}"); + let rendered = elided_text(&ast, &filters, 0); + assert!(rendered.contains(" : g(…) \n"), "{rendered}"); + } + + /// Siblings share a level: the second call of a row sits where the + /// first did, not one deeper. Under a limit of 2, `k`, level 2 like + /// `g`, prints whole, and `h` and `m`, level 3, elide the calls in + /// them. Leaving `g`'s level open across `k` would put `k` at 3 and + /// print `k(…)`. + #[cfg(feature = "cpp")] + #[test] + fn found_render_levels_reset_between_siblings() { + let ast = parse_as(crate::LANG::Cpp, b"int a = f(g(h(i(1))), k(m(n(2))));\n"); + assert_eq!( + snippets(&elided_text(&ast, &["call_expression"], 2)), + [ + "f(g(h(i(1))), k(m(n(2)))) ", + "g(h(i(1))) ", + "h(…) ", + "i(1) ", + "k(m(n(2))) ", + "m(…) ", + "n(2) ", + ] + ); + } + + /// Two matches with the same span are two levels, like any other + /// nesting. Tcl's `word_list` and the `braced_word` it holds share + /// one: under a limit of 1, the `word_list` prints whole, and the + /// `braced_word`, level 2, elides the `command` inside it. + #[cfg(feature = "tcl")] + #[test] + fn found_render_counts_a_match_with_its_parents_span_as_a_level() { + let ast = parse_as(crate::LANG::Tcl, b"x {{a}}\n"); + let filters = ["word_list", "braced_word"]; + let found = found(&ast, &filters); + assert_eq!( + (found[0].start_byte(), found[0].end_byte()), + (found[1].start_byte(), found[1].end_byte()), + "the fixture must open with two matches of one span: {found:?}" + ); + assert_eq!( + snippets(&elided_text(&ast, &filters, 1)), + ["{{a}} ", "{…} ", "{a} "] + ); + } + + /// The bound the limit exists for: at any depth, a source byte is + /// printed by at most `FULL_LEVELS + 1` lines, so the snippets of a + /// nest far past the limit total at most that many copies of the + /// file. Printing each match whole is `depth²`: at depth 1 000 that + /// is 7.7 times the bound, which the second assertion checks so the + /// first is not a bound any render would meet. + #[cfg(feature = "tcl")] + #[test] + fn found_render_prints_each_byte_at_most_limit_plus_one_times() { + let depth = 1_000; + let code = nested_braces(depth); + let ast = parse_as(crate::LANG::Tcl, &code); + let rendered = found_text(&ast, &["braced_word"]); + let printed: usize = snippets(&rendered) + .iter() + .map(|s| s.replace(ELIDED, "").trim_end().len()) + .sum(); + let bound = (FULL_LEVELS + 1) * code.len(); + assert!( + printed <= bound, + "{printed} source bytes printed, bound {bound}" + ); + let whole: usize = (1..=depth).map(|level| 2 * (depth - level + 1) + 3).sum(); + assert!( + whole > 4 * bound, + "the fixture must be past the bound when whole: {whole}" + ); + } + + /// [`Nesting::next_outside`] alone, every span counted. + fn next_outside(spans: &[Range]) -> Vec { + nesting(spans, &vec![true; spans.len()]).next_outside + } + + /// [`Nesting::levels`] alone. + fn levels(spans: &[Range], counted: &[bool]) -> Vec { + nesting(spans, counted).levels + } + + #[test] + fn levels_count_the_counted_spans_holding_each() { + // 0..10 holds 0..4 (holding 1..2) and 5..9 (holding 6..7); + // 10..12 follows it. With every span counted, the level is the + // nesting depth, and the siblings 0..4 and 5..9 share one. + let spans = [0..10, 0..4, 1..2, 5..9, 6..7, 10..12]; + assert_eq!(levels(&spans, &[true; 6]), [1, 2, 3, 2, 3, 1]); + // An uncounted span neither has a level of its own nor raises its + // children's: 0..10 multi-row, say. + let counted = [false, true, true, true, true, true]; + assert_eq!(levels(&spans, &counted), [0, 1, 2, 1, 2, 1]); + } + #[test] fn next_outside_points_past_everything_nested() { // 0..10 holds 0..4 (holding 1..2) and 5..9 (holding 6..7); From 3c35e9b02edb1284dcd5608ba5cd6ebef15d3bfb Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Fri, 6 Nov 2026 11:29:41 -0800 Subject: [PATCH 19/25] fix(perturb): read cargo failures from each target's list A doctest's name holds spaces (`src/lib.rs - one (line 7)`), and the failure patterns took the name as `\S+`, so every red `--doc` run parsed no failure and read as HARNESS-ERROR against its exit status. Failures are now read from each target's `failures:` list, the names `cargo test -- --list` and `--exact` use: the progress line adds ` - should panic` / ` - compile fail`, which no `expect` spells, and `-q` / `--format terse` print no progress lines at all. A test's captured section is bounded by whole `---- name stdout ----` headers on one line and by cargo's list up to its `test result:`, so a doctest's own compile error inside its section is a failing test, not a build that never reached the tests; a header pattern free to cross lines was quadratic (8 000 `---- ` lines took 4.7 s), joined a stray line to a later header and hid a real `error[` between them, and ended a section at a printed `---- ` line. A printed `test x ... FAILED` line no longer replaces the failure list. A test that prints a whole target report, list and `test result:` both, is cargo's shape exactly, and the docstring says no line parser can tell the two apart. The fixture is real `cargo test` output: a crate with one passing, one panicking, one uncompilable and one wrongly-compiling doctest, and a unit target with a `#[should_panic]` test and a test printing cargo-shaped lines. A perturbation sweep against that crate reports `caught`. Fixes #1831 --- utils/perturb-test.py | 76 +++++++++++++++++++++++++++++++++++++++++++ utils/perturb.py | 23 ++++++++----- 2 files changed, 91 insertions(+), 8 deletions(-) diff --git a/utils/perturb-test.py b/utils/perturb-test.py index 8172320cf..621675c9c 100644 --- a/utils/perturb-test.py +++ b/utils/perturb-test.py @@ -39,6 +39,53 @@ def _load(name: str, filename: str): ORIGINAL = b"fn f() -> u8 {\r\n 1\n}\n" RESULT = "test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out\\n" RED = "test result: FAILED. 2 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out\\n" +# `cargo test --doc` on a crate with four doctests (rustc 1.99.1): one +# passes, one panics, one fails to compile, and one is marked +# `compile_fail` and compiles. Verbatim but for the panicking thread's id. +DOCTEST_RUN = """\ + Doc-tests dt + +running 4 tests +test src/lib.rs - one (line 12) ... FAILED +test src/lib.rs - one (line 17) - compile fail ... FAILED +test src/lib.rs - one (line 2) ... ok +test src/lib.rs - one (line 7) ... FAILED + +failures: + +---- src/lib.rs - one (line 12) stdout ---- +error[E0425]: cannot find function `nope` in crate `dt` + --> src/lib.rs:14:17 + | +14 | let x: u8 = dt::nope(); + | ^^^^ not found in `dt` + +error: aborting due to 1 previous error + +For more information about this error, try `rustc --explain E0425`. +Couldn't compile the test. +---- src/lib.rs - one (line 17) stdout ---- +Test compiled successfully, but it's marked `compile_fail`. +---- src/lib.rs - one (line 7) stdout ---- +Test executable failed (exit status: 101). + +stderr: + +thread 'main' panicked at src/lib.rs:5:1: +assertion `left == right` failed + left: 1 + right: 2 + + +failures: + src/lib.rs - one (line 12) + src/lib.rs - one (line 17) + src/lib.rs - one (line 7) + +test result: FAILED. 1 passed; 3 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.10s + +error: doctest failed, to rerun pass `--doc` +""" class ScratchRepo: @@ -201,6 +248,35 @@ def test_build_error_is_classified_by_error_bracket_not_bare_error(self) -> None verdict, failed, _ = perturb.classify(101, "test a::b ... FAILED\n" + RED.replace("\\n", "\n") + "error: test failed\n") self.assertEqual((verdict, failed), ("caught", {"a::b"})) + def test_doctest_names_with_spaces_are_parsed(self) -> None: + # #1831: a doctest's name holds spaces, which `\S+` stopped at, so + # every red `--doc` run read as 0 parsed failures against exit 101. + verdict, failed, detail = perturb.classify(101, DOCTEST_RUN) + self.assertEqual((verdict, detail), ("caught", "")) + self.assertEqual( + failed, + { + "src/lib.rs - one (line 12)", + "src/lib.rs - one (line 17) - compile fail", + "src/lib.rs - one (line 7)", + }, + ) + + def test_a_doctest_that_fails_to_compile_is_a_failing_test_not_a_build_error(self) -> None: + # Its `error[E0425]` sits in its own captured stdout. Read as a + # build failure, every `compile_fail` perturbation is BUILD-ERROR. + self.assertEqual(perturb.classify(101, DOCTEST_RUN)[0], "caught") + # A real build failure outside any test's output still is one. + broken = "error: this file contains an unclosed delimiter\nerror: could not compile `dt` (lib) due to 1 previous error\n" + self.assertEqual(perturb.classify(101, broken)[0], "BUILD-ERROR") + self.assertEqual(perturb.classify(101, "error[E0425]: cannot find\n" + DOCTEST_RUN)[0], "BUILD-ERROR") + + def test_a_name_never_runs_past_its_own_line(self) -> None: + # A passing test's line before a failing one: a lazy group free + # to cross a newline reads `a ... ok\ntest b c` as one name. + out = "test a ... ok\ntest b c ... FAILED\n" + RED.replace("\\n", "\n") + self.assertEqual(perturb.classify(101, out)[1], {"b c"}) + def test_status_and_parsed_failures_disagreeing_is_a_harness_error(self) -> None: # Nonzero exit, no failure line: the parser missed (`cargo test # -q` dots, #1238) or the harness died. diff --git a/utils/perturb.py b/utils/perturb.py index ca0049cb0..ba0cdf4a8 100755 --- a/utils/perturb.py +++ b/utils/perturb.py @@ -86,10 +86,19 @@ import tempfile BUILD_ERROR_RE = re.compile(r"^error\[|could not compile", re.M) -FAILED_RES = ( - re.compile(r"^---- (\S+) stdout ----", re.M), - re.compile(r"^test (\S+) \.\.\. FAILED", re.M), -) +# A test name can hold spaces: a doctest's is `src/lib.rs - item (line 7)` +# (#1831). Each pattern is anchored at both ends of its line, so the lazy +# group cannot run past the line's own delimiter. The progress line is +# the name: a `compile_fail` doctest's carries ` - compile fail`, which +# its `----` header drops, so the headers are read only when no progress +# line is (a `--format terse` run, say), never merged with them. +FAILED_LINE_RE = re.compile(r"^test (.+?) \.\.\. FAILED$", re.M) +FAILED_HEADER_RE = re.compile(r"^---- (.+?) stdout ----$", re.M) +# A test's captured output runs from its `---- name stdout ----` header to +# the next header or the `failures:` list after the last one. A doctest +# that fails to compile prints its `error[E…]` there, which is a failing +# test, not a build that never reached the tests. +TEST_STDOUT_RE = re.compile(r"^---- .+? stdout ----$.*?(?=^---- |^failures:$|\Z)", re.M | re.S) TEST_RESULT_RE = re.compile(r"^test result: \w+\. (\d+) passed; (\d+) failed;", re.M) CARGO_PROGRAMS = frozenset({"cargo", "cargo.exe"}) @@ -249,10 +258,8 @@ def classify(returncode: int, output: str) -> tuple[str, set[str], str]: `HARNESS-ERROR` describe the harness: a disagreement between the parsed failure set and the exit status, or a run in which no test ran.""" - failed: set[str] = set() - for rx in FAILED_RES: - failed.update(rx.findall(output)) - if BUILD_ERROR_RE.search(output): + failed = set(FAILED_LINE_RE.findall(output)) or set(FAILED_HEADER_RE.findall(output)) + if BUILD_ERROR_RE.search(TEST_STDOUT_RE.sub("", output)): return "BUILD-ERROR", failed, "the build failed" if (returncode != 0) != bool(failed): return "HARNESS-ERROR", failed, f"exit {returncode} disagrees with {len(failed)} parsed failure(s)" From f6bed19e127cac9b1f8d79dcc1d5ca3473a7340e Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Fri, 6 Nov 2026 11:32:09 -0800 Subject: [PATCH 20/25] feat(perturb): add a unittest runner MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit perturb.py drove `cargo test` only, so the Python gates under utils/ had no sweep driver with its safety rules. A manifest may now name `"runner": "unittest"` with its argv under `"command"`; a `"cargo"` manifest means what it always did. Runners are a dataclass carrying their argv check, refusal text, preflight and `run`, so sweep() names none of them. The runner never reads unittest's printed report. A test can print anything — a ruled `FAIL:` header, a whole nested unittest report, a line shaped like a progress verdict — to either stream, `-b` copies it into the report, and no reading of the text can tell that from unittest's own: three attempts at a text parser each opened a new case, the last one certifying a passing test as the one that failed. Instead it runs `-m perturb_unittest_recorder` in place of `-m unittest`: the same unittest.main, with its own argument parsing, output and exit status, whose result class records each outcome by TestCase.id() — failures and errors with subtests under their test, unexpected successes, loader failures, class and module fixture failures — and writes the record as JSON after run() returns, so an exception escaping a test (a KeyboardInterrupt) leaves no record. Each run's record lives in its own temporary directory. classify_unittest reads that record and refuses, as HARNESS-ERROR: no record; one that is not JSON or not the recorder's shape (a run killed mid-write, a module shadowing the recorder); a loader failure; a run that was stopped early (`-c` and SIGINT, `result.stop()`) or killed by a signal, whose failures are a partial set; 0 tests run; and an exit status other than unittest's own 1-with-a-failure / 0-without, which an atexit hook or thread calling os._exit leaves. An unexpected success counts as a failure, since unittest exits 1 on one. The argv is parsed as unittest parses it, mirroring unittest/main.py's main and discovery parsers: fail-fast in any spelling (`-f`, `-vf`, `--failfast`, the abbreviation `--fail`) is refused, since it hides every guard after the first failure; so are `-E`, `-I` and `-X pycache_prefix`, each of which undoes the isolation below. Before 3.12 argparse exits on an unrecognized argument even with exit_on_error=False, which is a refusal, not a SystemExit. The suite is run once unperturbed and a red one refused. Each run gets an empty PYTHONPYCACHEPREFIX with writes off, so a `.pyc` left by a same-length mutant cannot be loaded for the next one (#1562): `-B` alone still loads a `.pyc` whose recorded size and mtime match. Every run recompiles what it imports, the interpreter's own start-up included — ~0.13 s against 0.05 s warm, the price of the guarantee. Colour is off (3.14 colours its report under FORCE_COLOR); the record's dedup is a set, where a list scan was quadratic past ~10 000 failures. Self-tests run real `python -m unittest` subprocesses on a scratch repository: the named test caught; a subtest failure under its test; skips and expected failures not counted; several unexpected successes; a failing test printing a header that names a passing test, under -b, -v and neither; a 2 000-prefix progress-shaped stderr line; a failing test followed by a KeyboardInterrupt, by SIGINT under -c, and by a tearDownClass that exits 7, with a test after each never run; a dying run after a recorded catch; a stale `.pyc` seeded with the committed source's stamp; a sweep without -B over two same-length mutants in one second; colour on a 3.14 interpreter when one is on PATH; argv refusals through sweep(); a corrupt or odd-shaped record. setUp clears the variables the runner sets, which an outer sweep of this file would otherwise hand every inner sweep. Each guard was swept with the unittest runner over this file; the one mutant that stops the record being written perturbs the sweep's own recorder too, so it was checked from a git archive copy. perturb-test.py passes on Python 3.10 through 3.14; the validator agrees with each interpreter's own unittest parsers on 20 argvs (`--durations`, a 3.12 option, is the one 3.10/3.11 then refuse at the preflight). testing.md points Python sweeps at the runner; the pre-commit hook triggers on the recorder. --- .claude/rules/testing.md | 4 +- .pre-commit-config.yaml | 2 +- utils/perturb-test.py | 652 ++++++++++++++++++++++++++++- utils/perturb.py | 376 +++++++++++++++-- utils/perturb_unittest_recorder.py | 123 ++++++ 5 files changed, 1107 insertions(+), 50 deletions(-) create mode 100644 utils/perturb_unittest_recorder.py diff --git a/.claude/rules/testing.md b/.claude/rules/testing.md index 04788b948..1352effa3 100644 --- a/.claude/rules/testing.md +++ b/.claude/rules/testing.md @@ -200,7 +200,9 @@ corrected under #1539. (to the second) and size both match. A same-length edit such as `min` → `max`, restored within the same second, therefore runs stale bytecode on the next import. In #1562 that produced "isolated test fails, full run -passes" results that described the cache, not the code. Delete the +passes" results that described the cache, not the code. For a `unittest` +subject, `utils/perturb.py`'s `"runner": "unittest"` handles this: every +run reads no existing `.pyc` and writes none. By hand, delete the module's `__pycache__` before the sweep, then run every step with `python3 -B` (or `PYTHONDONTWRITEBYTECODE=1`). `-B` stops new writes, but a `.pyc` written before the sweep is still read. diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 1ea2be915..01a607184 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -185,7 +185,7 @@ repos: - id: perturb-test name: perturb-test language: system - files: '^utils/perturb(-test)?\.py$' + files: '^utils/perturb(-test|_unittest_recorder)?\.py$' entry: python3 -B -m unittest -q utils/perturb-test.py pass_filenames: false - id: coverage-diff-test diff --git a/utils/perturb-test.py b/utils/perturb-test.py index 621675c9c..c501cb7e9 100644 --- a/utils/perturb-test.py +++ b/utils/perturb-test.py @@ -16,8 +16,11 @@ import pathlib import subprocess import sys +import shutil import tempfile +import time import unittest +from unittest import mock UTILS_DIR = pathlib.Path(__file__).resolve().parent @@ -39,6 +42,23 @@ def _load(name: str, filename: str): ORIGINAL = b"fn f() -> u8 {\r\n 1\n}\n" RESULT = "test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out\\n" RED = "test result: FAILED. 2 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out\\n" + + +def failing(*names: str, escaped: bool = True) -> str: + """One libtest target's report with `names` failing, in cargo's real + shape: progress lines, each failure's captured output, the + `failures:` list the parser reads, then `test result:`. Escaped (`\\n` + as two characters) for the stub's argv unless `escaped` is false.""" + out = ( + "running 2 tests\n" + + "".join(f"test {n} ... FAILED\n" for n in names) + + "test ok ... ok\n\nfailures:\n\n" + + "".join(f"---- {n} stdout ----\nboom\n\n" for n in names) + + "\nfailures:\n" + + "".join(f" {n}\n" for n in names) + + f"\ntest result: FAILED. 1 passed; {len(names)} failed; 0 ignored; 0 measured; 0 filtered out\n" + ) + return out.replace("\n", "\\n") if escaped else out # `cargo test --doc` on a crate with four doctests (rustc 1.99.1): one # passes, one panics, one fails to compile, and one is marked # `compile_fail` and compiles. Verbatim but for the panicking thread's id. @@ -87,6 +107,53 @@ def _load(name: str, filename: str): error: doctest failed, to rerun pass `--doc` """ +# `cargo test --no-fail-fast --lib` (rustc 1.99.1) on a unit target with a +# `#[should_panic]` test that does not panic and a test that prints +# cargo-shaped lines before failing. Verbatim but for thread ids; +# `{progress}` holds the progress lines, which `-q` drops. +NOISY_PROGRESS = """\ +test tests::ok ... ok +test tests::noisy ... FAILED +test tests::plain ... FAILED +test tests::sp - should panic ... FAILED +""" +NOISY_RUN = """\ +running 4 tests +{progress} +failures: + +---- tests::noisy stdout ---- +test fake::thing ... FAILED +---- fake::other stdout ---- +error[E0001]: fake +failures: + fake::listed +---- section 1 + +thread 'tests::noisy' panicked at src/lib.rs:25:9: +boom +note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace + +---- tests::plain stdout ---- + +thread 'tests::plain' panicked at src/lib.rs:17:26: +assertion `left == right` failed + left: 1 + right: 2 + +---- tests::sp stdout ---- +note: test did not panic as expected at src/lib.rs:16:32 + +failures: + tests::noisy + tests::plain + tests::sp + +test result: FAILED. 1 passed; 3 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s + +error: test failed, to rerun pass `--lib` +""" + class ScratchRepo: """A committed git repository holding `src/a.rs` and a stub `cargo` @@ -131,6 +198,16 @@ def _case(old: str = "1\n", new: str = "2\n", **extra: object) -> dict: class PerturbTests(unittest.TestCase): def setUp(self) -> None: + # The variables `unittest_env` sets, and the colour switches it + # overrides, cleared from this process: a sweep of this file by + # the unittest runner runs it with them set, and an inner sweep + # that inherited them would hide a mutant that drops one. + cleared = ("PYTHONPYCACHEPREFIX", "PYTHONDONTWRITEBYTECODE", "PYTHON_COLORS", "NO_COLOR", "FORCE_COLOR") + env = mock.patch.dict(os.environ, {}) + env.start() + self.addCleanup(env.stop) + for name in cleared: + os.environ.pop(name, None) self._tmp = tempfile.TemporaryDirectory() self.repo = ScratchRepo(pathlib.Path(self._tmp.name) / "repo") self.backup = pathlib.Path(self._tmp.name) / "backup" @@ -205,7 +282,7 @@ def test_rejects_an_anchor_that_does_not_occur_exactly_once(self) -> None: self.assertIn(f"occurs {n} times", out) def test_caught_when_a_test_fails_and_the_status_agrees(self) -> None: - stdout = "test a::b ... FAILED\\n---- a::b stdout ----\\n" + RED + "error: test failed\\n" + stdout = failing("a::b") + "error: test failed\\n" results, rc, _, _ = self._sweep(self.repo.manifest(stdout, 101, [_case(expect=["a::b"])])) self.assertEqual(rc, 0) self.assertEqual(results[0]["verdict"], "caught") @@ -213,7 +290,7 @@ def test_caught_when_a_test_fails_and_the_status_agrees(self) -> None: self.assertEqual(results[0]["missing_expected"], []) def test_caught_by_the_wrong_test_is_reported_as_missing(self) -> None: - stdout = "test a::other ... FAILED\\n" + RED + stdout = failing("a::other") results, rc, out, _ = self._sweep(self.repo.manifest(stdout, 101, [_case(expect=["a::b"])])) self.assertEqual(rc, 1) self.assertEqual(results[0]["missing_expected"], ["a::b"]) @@ -245,23 +322,61 @@ def test_build_error_is_classified_by_error_bracket_not_bare_error(self) -> None self.assertEqual(perturb.classify(101, "error[E0425]: cannot find\n")[0], "BUILD-ERROR") self.assertEqual(perturb.classify(101, "error: could not compile `x`\n")[0], "BUILD-ERROR") # An ordinary red run says `error: test failed` and is a catch. - verdict, failed, _ = perturb.classify(101, "test a::b ... FAILED\n" + RED.replace("\\n", "\n") + "error: test failed\n") + verdict, failed, _ = perturb.classify(101, failing("a::b", escaped=False) + "error: test failed\n") self.assertEqual((verdict, failed), ("caught", {"a::b"})) def test_doctest_names_with_spaces_are_parsed(self) -> None: # #1831: a doctest's name holds spaces, which `\S+` stopped at, so # every red `--doc` run read as 0 parsed failures against exit 101. + # The `compile_fail` one is named as `--list` names it, without the + # ` - compile fail` its progress line adds. verdict, failed, detail = perturb.classify(101, DOCTEST_RUN) self.assertEqual((verdict, detail), ("caught", "")) self.assertEqual( failed, { "src/lib.rs - one (line 12)", - "src/lib.rs - one (line 17) - compile fail", + "src/lib.rs - one (line 17)", "src/lib.rs - one (line 7)", }, ) + def test_failures_are_named_as_cargo_lists_them(self) -> None: + # `cargo test --no-fail-fast` (rustc 1.99.1) on a crate whose unit + # target has a `#[should_panic]` test that does not panic, and a + # test that prints cargo-shaped lines before failing. The progress + # line spells the first `tests::sp - should panic`, which no + # `--exact` or `expect` spells; the second prints a fake progress + # line, header, `error[`, `failures:` list and `---- ` line, none + # of which is cargo's report. Same names under `-q` and + # `--format terse`, which print no progress lines at all. + for label, progress in (("default", NOISY_PROGRESS), ("-q", "")): + out = NOISY_RUN.replace("{progress}", progress) + verdict, failed, detail = perturb.classify(101, out) + self.assertEqual((verdict, detail), ("caught", ""), label) + self.assertEqual(failed, {"tests::noisy", "tests::plain", "tests::sp"}, label) + + def test_a_printed_header_does_not_hide_a_real_build_error(self) -> None: + # A `---- ` line that is not a header, before an `error[`, then a + # real header: a header pattern free to cross lines joins the two + # and strips the error with them. + out = "---- not a header\nerror[E0308]: x\n---- t stdout ----\nboom\n\n" + failing("t", escaped=False) + self.assertEqual(perturb.classify(101, out)[0], "BUILD-ERROR") + + def test_section_stripping_is_linear(self) -> None: + # A header pattern free to cross lines rescans to the end of the + # input from every `---- ` line with no real header after it: + # 8 000 of them in one test's output took 4.7 s. + noise = "".join(f"---- section {i}\n" for i in range(8_000)) + out = ( + "running 1 test\ntest t ... FAILED\n\nfailures:\n\n---- t stdout ----\n" + + noise + + "\nfailures:\n t\n\ntest result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out\n" + ) + start = time.perf_counter() + self.assertEqual(perturb.classify(101, out)[:2], ("caught", {"t"})) + self.assertLess(time.perf_counter() - start, 0.5) + def test_a_doctest_that_fails_to_compile_is_a_failing_test_not_a_build_error(self) -> None: # Its `error[E0425]` sits in its own captured stdout. Read as a # build failure, every `compile_fail` perturbation is BUILD-ERROR. @@ -272,10 +387,9 @@ def test_a_doctest_that_fails_to_compile_is_a_failing_test_not_a_build_error(sel self.assertEqual(perturb.classify(101, "error[E0425]: cannot find\n" + DOCTEST_RUN)[0], "BUILD-ERROR") def test_a_name_never_runs_past_its_own_line(self) -> None: - # A passing test's line before a failing one: a lazy group free - # to cross a newline reads `a ... ok\ntest b c` as one name. - out = "test a ... ok\ntest b c ... FAILED\n" + RED.replace("\\n", "\n") - self.assertEqual(perturb.classify(101, out)[1], {"b c"}) + # Two names in one `failures:` list, one with spaces: each line + # is one name, whole. + self.assertEqual(perturb.classify(101, failing("a", "b c", escaped=False))[1], {"a", "b c"}) def test_status_and_parsed_failures_disagreeing_is_a_harness_error(self) -> None: # Nonzero exit, no failure line: the parser missed (`cargo test @@ -290,7 +404,7 @@ def test_restores_from_memory_and_keeps_an_on_disk_backup(self) -> None: seen = self.repo.root / "seen.txt" # The stub records the mutated file as it ran. self.repo.stub.write_text( - f"import pathlib, sys\npathlib.Path({str(seen)!r}).write_bytes(pathlib.Path({str(self.repo.target)!r}).read_bytes())\nsys.stdout.write('test a ... FAILED\\n{RED}')\nsys.exit(101)\n" + f"import pathlib, sys\npathlib.Path({str(seen)!r}).write_bytes(pathlib.Path({str(self.repo.target)!r}).read_bytes())\nsys.stdout.write({failing('a', escaped=False)!r})\nsys.exit(101)\n" ) results, rc, _, _ = self._sweep(self.repo.manifest("", 0, [_case()])) self.assertEqual(rc, 0) @@ -326,7 +440,7 @@ def _drop(self, backup: pathlib.Path) -> None: backup.rmdir() def test_main_uses_a_mktemp_backup_and_writes_the_record(self) -> None: - manifest = self.repo.manifest("test a::b ... FAILED\\n" + RED, 101, [_case(expect=["a::b"])]) + manifest = self.repo.manifest(failing("a::b"), 101, [_case(expect=["a::b"])]) manifest["record"] = "out/results.json" (self.repo.root / "out").mkdir() rc, backup, record = self._main(manifest) @@ -338,7 +452,7 @@ def test_main_uses_a_mktemp_backup_and_writes_the_record(self) -> None: self._drop(backup) def test_record_defaults_into_the_backup_directory_not_the_repo(self) -> None: - manifest = self.repo.manifest("test a::b ... FAILED\\n" + RED, 101, [_case(expect=["a::b"])]) + manifest = self.repo.manifest(failing("a::b"), 101, [_case(expect=["a::b"])]) rc, backup, record = self._main(manifest) self.assertEqual(rc, 0) self.assertEqual(record, backup / "perturb-results.json") @@ -356,7 +470,7 @@ def _cargo_stub(self) -> pathlib.Path: ran = pathlib.Path(self._tmp.name) / "cargo-ran" stub.write_text( f"#!{sys.executable}\nimport pathlib, sys\npathlib.Path({str(ran)!r}).write_text(' '.join(sys.argv[1:]))\n" - f"sys.stdout.write('test a::b ... FAILED\\n{RED}')\nsys.exit(101)\n" + f"sys.stdout.write({failing('a::b', escaped=False)!r})\nsys.exit(101)\n" ) stub.chmod(0o755) return stub @@ -509,6 +623,520 @@ def test_argv_rule_leaves_other_programs_and_subcommands_alone(self) -> None: ): self.assertIsNone(perturb.cargo_argv_problem(argv), argv) + # The unittest runner, against a real `python -m unittest -v` run on + # a module of the scratch repository: the parser is checked on the + # report this interpreter prints, not on a transcription of one. + + def _commit(self, message: str) -> None: + env = {**os.environ, "GIT_AUTHOR_NAME": "t", "GIT_AUTHOR_EMAIL": "t@t", "GIT_COMMITTER_NAME": "t", "GIT_COMMITTER_EMAIL": "t@t"} + for argv in (["git", "add", "-A"], ["git", "commit", "-q", "-m", message]): + subprocess.run(argv, cwd=self.repo.root, check=True, env=env) + + def _unittest_repo(self, body: str) -> dict: + """Commits `t_sub.py` (the subject) and `t_case.py` (its tests, + `body` being the class body) and returns a manifest skeleton.""" + (self.repo.root / "t_sub.py").write_text("def value():\n return 1\n") + (self.repo.root / "t_case.py").write_text( + "import unittest\nimport t_sub\n\n\nclass T(unittest.TestCase):\n" + body + ) + self._commit("unittest") + return { + "cwd": str(self.repo.root), + "runner": "unittest", + "command": [sys.executable, "-B", "-m", "unittest", "-v", "t_case"], + } + + @staticmethod + def _flip(expect: list[str]) -> dict: + return {"name": "flip", "file": "t_sub.py", "old": "return 1", "new": "return 2", "expect": expect} + + def test_unittest_caught_by_the_named_test(self) -> None: + manifest = self._unittest_repo( + " def test_value(self):\n self.assertEqual(t_sub.value(), 1)\n" + " def test_other(self):\n pass\n" + ) + results, rc, _, err = self._sweep({**manifest, "cases": [self._flip(["t_case.T.test_value"])]}) + self.assertEqual((rc, results[0]["verdict"]), (0, "caught"), err) + self.assertEqual(results[0]["failed"], ["t_case.T.test_value"]) + self.assertEqual((self.repo.root / "t_sub.py").read_text(), "def value():\n return 1\n") + + def test_unittest_uncaught_when_no_test_reads_the_line(self) -> None: + manifest = self._unittest_repo(" def test_other(self):\n pass\n") + results, rc, _, _ = self._sweep({**manifest, "cases": [self._flip([])]}) + self.assertEqual((rc, results[0]["verdict"]), (1, "UNCAUGHT")) + + def test_unittest_subtest_failure_counts_against_its_test(self) -> None: + # Two subtests fail; the test holding them is one failing test. + manifest = self._unittest_repo( + " def test_value(self):\n" + " for i in range(3):\n" + " with self.subTest(i=i):\n" + " self.assertEqual(t_sub.value(), 1)\n" + ) + results, rc, _, err = self._sweep({**manifest, "cases": [self._flip(["t_case.T.test_value"])]}) + self.assertEqual((rc, results[0]["verdict"], results[0]["failed"]), (0, "caught", ["t_case.T.test_value"]), err) + + def test_unittest_skips_and_expected_failures_are_not_failures(self) -> None: + # `expected failures=1` must not be read as `failures=1`, or the + # summary disagrees with the parsed set and every case is a + # harness error. + manifest = self._unittest_repo( + " @unittest.skip('s')\n def test_skip(self):\n pass\n" + " @unittest.expectedFailure\n def test_xf(self):\n self.fail()\n" + " def test_value(self):\n self.assertEqual(t_sub.value(), 1)\n" + ) + results, rc, _, err = self._sweep({**manifest, "cases": [self._flip(["t_case.T.test_value"])]}) + self.assertEqual((rc, results[0]["verdict"]), (0, "caught"), err) + + def test_unittest_unexpected_success_is_a_failure(self) -> None: + # unittest exits 1 on one, and the perturbation is what made it. + manifest = self._unittest_repo( + " @unittest.expectedFailure\n def test_value(self):\n self.assertEqual(t_sub.value(), 2)\n" + ) + results, rc, _, err = self._sweep({**manifest, "cases": [self._flip(["t_case.T.test_value"])]}) + self.assertEqual((rc, results[0]["verdict"]), (0, "caught"), err) + + def test_unittest_import_failure_is_a_harness_error(self) -> None: + # A syntax error in the subject kills the loader outright (no + # report); one in a discovered module is reported as an error of + # a synthetic loader test. Neither is an assertion catching it. + manifest = self._unittest_repo(" def test_value(self):\n self.assertEqual(t_sub.value(), 1)\n") + case = {"name": "break", "file": "t_sub.py", "old": "return 1", "new": "return (", "expect": ["t_case.T.test_value"]} + results, rc, out, _ = self._sweep({**manifest, "cases": [case]}) + self.assertEqual((rc, results[0]["verdict"]), (1, "HARNESS-ERROR")) + self.assertIn("no outcome recorded: the loader raised", out) + discovered = {**manifest, "command": [sys.executable, "-B", "-m", "unittest", "discover", "-v", "-p", "t_case.py"]} + results, rc, out, _ = self._sweep({**discovered, "cases": [case]}) + self.assertEqual((rc, results[0]["verdict"]), (1, "HARNESS-ERROR"), out) + self.assertIn("import or discovery failed (unittest.loader._FailedTest.", out) + + def test_unittest_refuses_a_red_suite_before_any_write(self) -> None: + manifest = self._unittest_repo(" def test_value(self):\n self.assertEqual(t_sub.value(), 2)\n") + results, rc, _, err = self._sweep({**manifest, "cases": [self._flip([])]}) + self.assertEqual((results, rc), ([], 2)) + self.assertIn("unperturbed suite is not green", err) + self.assertEqual(list(self.backup.iterdir()), [], "nothing was backed up, so nothing was written") + + def test_unittest_reads_no_stale_bytecode(self) -> None: + # A same-length edit restored within the second leaves the + # source's size and mtime as they were, so a `.pyc` written from + # the mutant is valid to the importer and `-B` alone reads it. + # Seed exactly that `.pyc` in the repository's `__pycache__`: a + # run that honours it sees `2` and fails although the file says 1. + manifest = self._unittest_repo(" def test_value(self):\n self.assertEqual(t_sub.value(), 1)\n") + self._seed_stale_pyc("def value():\n return 2\n") + stale = subprocess.run(manifest["command"], cwd=self.repo.root, capture_output=True, text=True) + self.assertNotEqual(stale.returncode, 0, "the seeded .pyc must be read without the private cache") + # Reading it, the preflight sees a red suite and refuses the sweep. + results, rc, _, err = self._sweep({**manifest, "cases": [self._flip(["t_case.T.test_value"])]}) + self.assertNotIn("not green", err, "the run read the stale .pyc") + self.assertEqual((rc, [r["verdict"] for r in results]), (0, ["caught"]), err) + + def _seed_stale_pyc(self, mutant: str) -> None: + """Writes `t_sub.py`'s `.pyc` for `mutant` into the repository's + `__pycache__`, stamped with the committed source's mtime, so the + importer takes it as current for the unchanged file. The mutant + carries the same stamp before it is compiled, so the seed holds + whichever second the writes land in.""" + sub = self.repo.root / "t_sub.py" + original, stat = sub.read_text(), sub.stat() + sub.write_text(mutant) + os.utime(sub, ns=(stat.st_atime_ns, stat.st_mtime_ns)) + subprocess.run([sys.executable, "-c", "import py_compile; py_compile.compile('t_sub.py')"], cwd=self.repo.root, check=True) + sub.write_text(original) + os.utime(sub, ns=(stat.st_atime_ns, stat.st_mtime_ns)) + + def test_unittest_writes_no_bytecode_for_a_later_case_to_read(self) -> None: + # Without `-B`, a run that may write bytecode leaves the first + # mutant's `.pyc` where the second same-length mutant, written in + # the same second, would load it. The private prefix is shared by + # every run of a sweep, so writes must be off as well. + manifest = self._unittest_repo(" def test_value(self):\n self.assertEqual(t_sub.value(), 1)\n") + manifest["command"] = [sys.executable, "-m", "unittest", "-v", "t_case"] + cases = [ + {"name": "two", "file": "t_sub.py", "old": "return 1", "new": "return 2", "expect": ["t_case.T.test_value"]}, + {"name": "three", "file": "t_sub.py", "old": "return 1", "new": "return 3", "expect": ["t_case.T.test_value"]}, + ] + stat = (self.repo.root / "t_sub.py").stat() + real_write = pathlib.Path.write_bytes + + def write_keeping_mtime(path: pathlib.Path, data: bytes) -> int: + # Every write in the same second, as a fast sweep's are. + n = real_write(path, data) + if path.name == "t_sub.py": + os.utime(path, ns=(stat.st_atime_ns, stat.st_mtime_ns)) + return n + + with mock.patch.object(pathlib.Path, "write_bytes", write_keeping_mtime): + results, rc, _, err = self._sweep({**manifest, "cases": cases}) + self.assertEqual([r["verdict"] for r in results], ["caught", "caught"], err) + self.assertEqual(list(self.backup.glob("**/*.pyc")), [], "the sweep wrote bytecode") + + def test_unittest_reads_its_report_not_what_a_test_printed(self) -> None: + # A test printing a progress line of its own: read with the + # report, it is one more unexpected success than the summary + # counts, and the green preflight reads as a harness error. + manifest = self._unittest_repo( + " def test_value(self):\n" + " print('test_fake (x.Y.test_fake) ... unexpected success')\n" + " self.assertEqual(t_sub.value(), 1)\n" + ) + results, rc, _, err = self._sweep({**manifest, "cases": [self._flip(["t_case.T.test_value"])]}) + self.assertEqual((rc, results[0]["verdict"], results[0]["failed"]), (0, "caught", ["t_case.T.test_value"]), err) + + def test_unittest_counts_several_unexpected_successes(self) -> None: + # From 3.11 the report lists consecutive unexpected successes + # under one `====` rule; before it, not at all. The progress lines + # name each on every version. + manifest = self._unittest_repo( + " @unittest.expectedFailure\n def test_a(self):\n self.assertEqual(t_sub.value(), 2)\n" + " @unittest.expectedFailure\n def test_b(self):\n self.assertEqual(t_sub.value(), 2)\n" + " def test_c(self):\n self.assertEqual(t_sub.value(), 1)\n" + ) + results, rc, _, err = self._sweep({**manifest, "cases": [self._flip(["t_case.T.test_a", "t_case.T.test_b"])]}) + self.assertEqual((rc, results[0]["verdict"]), (0, "caught"), err) + self.assertEqual(results[0]["failed"], ["t_case.T.test_a", "t_case.T.test_b", "t_case.T.test_c"]) + + def test_unittest_reads_no_header_from_a_traceback(self) -> None: + # A failure message holding a header-shaped line is not a second + # failure: headers sit directly under their `====` rule. + manifest = self._unittest_repo( + " def test_value(self):\n" + " self.assertEqual(t_sub.value(), 1, '\\nFAIL: fake (x.Y.fake)')\n" + ) + results, rc, _, err = self._sweep({**manifest, "cases": [self._flip(["t_case.T.test_value"])]}) + self.assertEqual((rc, results[0]["verdict"], results[0]["failed"]), (0, "caught", ["t_case.T.test_value"]), err) + + def test_unittest_reads_no_header_a_test_wrote_to_stderr(self) -> None: + # Before the outer report, a test's own stderr: a ruled header it + # printed, and the report of a failing unittest it ran inside + # itself. Each is followed by a passing test, so the outer report + # cannot simply start at the first rule after the last `... ok` + # of the test that wrote it. + manifest = self._unittest_repo( + " def test_a_printer(self):\n" + " import sys\n" + " sys.stderr.write('\\n' + '=' * 70 + '\\nFAIL: fake (x.Y.fake)\\n' + '-' * 70 + '\\n')\n" + " self.assertEqual(t_sub.value(), 1)\n" + " def test_b_nested(self):\n" + " class Inner(unittest.TestCase):\n" + " def test_inner(self):\n" + " self.fail()\n" + " suite = unittest.defaultTestLoader.loadTestsFromTestCase(Inner)\n" + " result = unittest.TextTestRunner(verbosity=2).run(suite)\n" + " self.assertEqual(len(result.failures), 1)\n" + " def test_c_clean(self):\n" + " pass\n" + ) + results, rc, _, err = self._sweep({**manifest, "cases": [self._flip(["t_case.T.test_a_printer"])]}) + self.assertEqual((rc, results[0]["verdict"], results[0]["failed"]), (0, "caught", ["t_case.T.test_a_printer"]), err) + + def test_unittest_counts_no_unexpected_success_from_a_traceback(self) -> None: + # A failure message, and `-b`'s captured stdout appended to the + # failure block, each holding a whole progress line ending + # `... unexpected success`: neither is a progress line, because + # both sit in the outer report after the last one. + line = "worker (a.B.worker) ... unexpected success" + manifest = self._unittest_repo( + " def test_value(self):\n" + f" print({line!r})\n" + f" self.assertEqual(t_sub.value(), 1, '\\n' + {line!r})\n" + " def test_clean(self):\n" + " pass\n" + ) + manifest["command"] = [sys.executable, "-B", "-m", "unittest", "-v", "-b", "t_case"] + results, rc, _, err = self._sweep({**manifest, "cases": [self._flip(["t_case.T.test_value"])]}) + self.assertEqual((rc, results[0]["verdict"], results[0]["failed"]), (0, "caught", ["t_case.T.test_value"]), err) + + def test_unittest_counts_no_unexpected_success_mid_line(self) -> None: + # Before the report, a test's own stderr holding a progress-shaped + # line after other text on the same line: a progress line starts + # its line, so this one is not counted. + manifest = self._unittest_repo( + " def test_value(self):\n" + " import sys\n" + " sys.stderr.write('prefix worker (a.B.worker) ... unexpected success\\n')\n" + " self.assertEqual(t_sub.value(), 1)\n" + " def test_clean(self):\n" + " pass\n" + ) + results, rc, _, err = self._sweep({**manifest, "cases": [self._flip(["t_case.T.test_value"])]}) + self.assertEqual((rc, results[0]["verdict"], results[0]["failed"]), (0, "caught", ["t_case.T.test_value"]), err) + + def test_unittest_names_the_test_that_failed_not_one_it_printed(self) -> None: + # Under `-b` a failing test's own output is copied into its block + # of the report, after its real header; a header it printed there + # names a test that passed. A reading of the text that took the + # last header named the passing one, and a sweep expecting it + # exited 0. + manifest = self._unittest_repo( + " def test_real(self):\n" + " print('\\n' + '=' * 70 + '\\nFAIL: test_bystander (t_case.T.test_bystander)\\n' + '-' * 70)\n" + " self.assertEqual(t_sub.value(), 1)\n" + " def test_bystander(self):\n" + " pass\n" + ) + for flags in (["-v", "-b"], ["-v"], []): + manifest["command"] = [sys.executable, "-B", "-m", "unittest", *flags, "t_case"] + results, rc, _, err = self._sweep({**manifest, "cases": [self._flip(["t_case.T.test_bystander"])]}) + self.assertEqual(results[0]["failed"], ["t_case.T.test_real"], (flags, err)) + self.assertEqual((rc, results[0]["missing_expected"]), (1, ["t_case.T.test_bystander"]), flags) + + def test_unittest_record_is_the_one_this_run_wrote(self) -> None: + # The record is the only thing read, so a run must find exactly + # its own: none left by an earlier run in the same sweep, and the + # recorder must be what ran. A case whose mutant kills the loader + # after a run that recorded a catch must not inherit that catch. + manifest = self._unittest_repo(" def test_value(self):\n self.assertEqual(t_sub.value(), 1)\n") + cases = [ + self._flip(["t_case.T.test_value"]), + {"name": "break", "file": "t_sub.py", "old": "return 1", "new": "return (", "expect": []}, + ] + results, _, _, err = self._sweep({**manifest, "cases": cases}) + self.assertEqual([r["verdict"] for r in results], ["caught", "HARNESS-ERROR"], err) + self.assertEqual(results[1]["failed"], [], err) + + def test_unittest_refuses_a_partial_run_as_a_catch(self) -> None: + # Under the mutant, a failing test and then a KeyboardInterrupt + # before the last test: unittest still calls stopTestRun on the + # way out, so a record written there held the first failure and + # the sweep certified it with the third test never run. With `-c` + # the interrupt stops the run gracefully instead; same partial set. + body = ( + " def test_a(self):\n self.assertEqual(t_sub.value(), 1)\n" + " def test_b(self):\n" + " if t_sub.value() != 1:\n" + " raise KeyboardInterrupt\n" + " def test_c(self):\n self.assertEqual(t_sub.value(), 1)\n" + ) + # A third shape no signal is involved in, so only the record's + # timing can refuse it: `tearDownClass` exits with status 7 after + # a failure, and the class after it never runs. Its own shape + # only: in the other two it would end those runs as well, and the + # `stopped` guard that the SIGINT shape exists for would go + # untested. + exiting = body.replace("raise KeyboardInterrupt", "pass") + ( + " @classmethod\n" + " def tearDownClass(cls):\n" + " if t_sub.value() != 1:\n" + " raise SystemExit(7)\n" + "\n\nclass U(unittest.TestCase):\n" + " def test_d(self):\n self.assertEqual(t_sub.value(), 1)\n" + ) + # `-c` catches SIGINT; a raised KeyboardInterrupt is not one, so + # that shape signals the process itself. + shapes = [ + ("SystemExit in tearDownClass", [], exiting, ["t_case.T.test_a", "t_case.U.test_d"]), + ("KeyboardInterrupt", [], body, ["t_case.T.test_a", "t_case.T.test_c"]), + ("SIGINT under -c", ["-c"], body.replace("raise KeyboardInterrupt", "import os, signal; os.kill(os.getpid(), signal.SIGINT)"), ["t_case.T.test_a", "t_case.T.test_c"]), + ] + manifest = self._unittest_repo(shapes[0][2]) + for label, flags, shape, expect in shapes: + if shape != shapes[0][2]: + (self.repo.root / "t_case.py").write_text("import unittest\nimport t_sub\n\n\nclass T(unittest.TestCase):\n" + shape) + self._commit(label) + manifest["command"] = [sys.executable, "-B", "-m", "unittest", *flags, "t_case"] + results, rc, _, err = self._sweep({**manifest, "cases": [self._flip(expect)]}) + # The verdict on its own: a partial run read as `caught` still + # exits 1 here, through the never-run test it leaves MISSING. + # The KeyboardInterrupt shape leaves no record, so only the + # record-reading test exercises the signal guard. + self.assertEqual(results[0]["verdict"], "HARNESS-ERROR", (label, err)) + self.assertEqual(rc, 1, label) + if label.startswith("SystemExit"): + self.assertIn("no outcome recorded", results[0]["detail"], label) + + def test_unittest_is_linear_in_a_progress_shaped_line(self) -> None: + # A run-on line of progress-shaped prefixes with no valid verdict + # backtracked exponentially in the text parser: 25 repetitions + # took over 2 s. + manifest = self._unittest_repo( + " def test_value(self):\n" + " import sys\n" + " sys.stderr.write('t (a.B) (i=1) ... ' * 2000 + 'bad verdict\\n')\n" + " self.assertEqual(t_sub.value(), 1)\n" + ) + start = time.perf_counter() + results, rc, _, err = self._sweep({**manifest, "cases": [self._flip(["t_case.T.test_value"])]}) + self.assertEqual((rc, results[0]["verdict"]), (0, "caught"), err) + self.assertLess(time.perf_counter() - start, 10) + + def test_unittest_reads_a_failure_whose_message_looks_like_progress(self) -> None: + # A traceback ends in the assertion's message, which can end in + # ` ... ok`; a parser that took the report to start after the last + # progress-shaped line skipped the real failure headers. + manifest = self._unittest_repo( + " def test_value(self):\n" + " self.assertEqual(t_sub.value(), 1, 'worker ... ok')\n" + " def test_other(self):\n" + " self.assertEqual(t_sub.value(), 1, 'second ... FAIL')\n" + ) + results, rc, _, err = self._sweep({**manifest, "cases": [self._flip(["t_case.T.test_value", "t_case.T.test_other"])]}) + self.assertEqual((rc, results[0]["verdict"]), (0, "caught"), err) + self.assertEqual(results[0]["failed"], ["t_case.T.test_other", "t_case.T.test_value"]) + + def test_unittest_fixture_failure_is_named_for_its_class(self) -> None: + manifest = self._unittest_repo( + " @classmethod\n def setUpClass(cls):\n assert t_sub.value() == 1\n" + " def test_value(self):\n pass\n" + ) + results, rc, out, _ = self._sweep({**manifest, "cases": [self._flip(["t_case.T"])]}) + self.assertEqual((rc, results[0]["verdict"]), (1, "HARNESS-ERROR")) + self.assertEqual(results[0]["failed"], ["t_case.T"]) + self.assertIn("fixture failed before any test ran", out) + + def test_unittest_ignores_colour_the_environment_asks_for(self) -> None: + # unittest colours its report from 3.14 on, so the test needs a + # 3.14 interpreter, whichever one runs this file. + python = next( + (p for p in (sys.executable, shutil.which("python3.14")) if p and self._python_version(p) >= (3, 14)), + None, + ) + if python is None: + self.skipTest("no Python 3.14+ interpreter on PATH: unittest only colours from 3.14") + manifest = self._unittest_repo(" def test_value(self):\n self.assertEqual(t_sub.value(), 1)\n") + manifest["command"] = [python, *manifest["command"][1:]] + with mock.patch.dict(os.environ, {"FORCE_COLOR": "1", "PYTHON_COLORS": "1"}): + results, rc, _, err = self._sweep({**manifest, "cases": [self._flip(["t_case.T.test_value"])]}) + self.assertEqual((rc, results[0]["verdict"]), (0, "caught"), err) + + @staticmethod + def _python_version(python: str) -> tuple[int, int]: + out = subprocess.run([python, "-c", "import sys; print(*sys.version_info[:2])"], capture_output=True, text=True, check=True) + major, minor = out.stdout.split() + return int(major), int(minor) + + def test_unittest_refuses_its_argv_before_any_write(self) -> None: + manifest = self._unittest_repo(" def test_value(self):\n self.assertEqual(t_sub.value(), 1)\n") + manifest["command"] = [sys.executable, "-BE", "-m", "unittest", "-v", "t_case"] + results, rc, _, err = self._sweep({**manifest, "cases": [self._flip([])]}) + self.assertEqual((results, rc), ([], 2)) + self.assertIn("refusing: the unittest argv: `-E` ignores the environment", err) + self.assertEqual(list(self.backup.iterdir()), []) + + def test_unittest_argv_rule(self) -> None: + base = [sys.executable, "-B", "-m", "unittest"] + for tail, needle in ( + (["-v", "-f", "t_case"], "fail-fast"), + (["-v", "--failfast", "t_case"], "fail-fast"), + (["-vf", "t_case"], "fail-fast"), + # argparse accepts any unambiguous prefix of a long option. + (["-v", "--fail", "t_case"], "fail-fast"), + (["discover", "-v", "--failf"], "fail-fast"), + ): + self.assertIn(needle, perturb.unittest_argv_problem([*base, *tail]) or "", tail) + self.assertIn("-m unittest", perturb.unittest_argv_problem([sys.executable, "t_case.py"]) or "") + for interpreter, needle in ( + (["-E"], "`-E` ignores the environment"), + (["-BE"], "`-E` ignores the environment"), + (["-I"], "`-I` ignores the environment"), + (["-X", "pycache_prefix=/tmp/x"], "`-X pycache_prefix`"), + (["-Xpycache_prefix=/tmp/x"], "`-X pycache_prefix`"), + ): + argv = [sys.executable, *interpreter, "-m", "unittest", "-v", "t_case"] + self.assertIn(needle, perturb.unittest_argv_problem(argv) or "", interpreter) + for tail in ( + ["-v", "t_case"], + ["-vb", "t_case"], + ["--verbose", "-k", "foo", "t_case"], + # A `-k` value is a pattern: `fast` holds an `f` and `v` is no + # `-v` of its own, so it is the trailing `-v` that counts. + ["-kfast", "-v", "t_case"], + ["discover", "-v", "-p", "t_*.py"], + # Discovery's start, pattern and top are three optional + # positionals. + ["discover", "-v", ".", "t_*.py", "."], + # Verbosity does not matter: the recorder reads outcomes, not + # the text, so quiet runs, `-vq` included, are fine. + ["t_case"], + ["-vq", "t_case"], + # `-fv`'s `f` is fail-fast however the cluster ends; `-kfv`'s + # is a pattern. + ["-kfv", "t_case"], + ): + self.assertIsNone(perturb.unittest_argv_problem([*base, *tail]), tail) + # Options between them: argparse reads that from 3.12, so the + # validator, built on this interpreter's argparse as unittest is, + # answers as this interpreter's unittest would. + interleaved = perturb.unittest_argv_problem([*base, "discover", ".", "-v", "t_*.py"]) + if sys.version_info >= (3, 12): + self.assertIsNone(interleaved) + else: + self.assertIn("unrecognized arguments: t_*.py", interleaved or "") + # An argv argparse rejects outright is refused, not raised: before + # 3.12 `exit_on_error=False` still exits on an unknown option, so + # only an older interpreter running this file exercises that arm. + with contextlib.redirect_stderr(io.StringIO()): + unknown = perturb.unittest_argv_problem([*base, "-v", "--no-such-option", "t_case"]) + self.assertIn("would reject", unknown or "") + # A fourth positional is one discovery has no slot for. + self.assertIn("would reject", perturb.unittest_argv_problem([*base, "discover", "-v", "a", "b", "c", "d"]) or "") + for interpreter in (["-X", "dev"], ["-W", "error"], ["-Werror"]): + self.assertIsNone(perturb.unittest_argv_problem([sys.executable, *interpreter, "-m", "unittest", "-v", "t"]), interpreter) + + def test_manifest_names_its_runner_unambiguously(self) -> None: + ok = {"cwd": ".", "cases": []} + self.assertEqual(perturb.manifest_command({**ok, "cargo": ["c"]}), ("cargo", ["c"])) + self.assertEqual(perturb.manifest_command({**ok, "runner": "unittest", "command": ["p"]}), ("unittest", ["p"])) + for manifest, needle in ( + ({**ok}, "exactly one"), + ({**ok, "cargo": ["c"], "command": ["c"]}, "exactly one"), + ({**ok, "runner": "unittest", "cargo": ["c"]}, "use `command`"), + ({**ok, "runner": "pytest", "command": ["p"]}, "unknown runner"), + ): + self.assertIn(needle, perturb.manifest_command(manifest), manifest) + + def test_classify_unittest_reads_the_record(self) -> None: + def record(**fields: object) -> dict: + return {"tests_run": 2, "stopped": False, "failed": [], "unexpected": [], "loader": [], "fixtures": [], **fields} + + self.assertEqual(perturb.classify_unittest(1, record(failed=["m.T.a"])), ("caught", {"m.T.a"}, "")) + self.assertEqual(perturb.classify_unittest(1, record(unexpected=["m.T.b"])), ("caught", {"m.T.b"}, "")) + self.assertEqual(perturb.classify_unittest(0, record()), ("UNCAUGHT", set(), "")) + for label, rc, rec, detail in ( + ("no record", 1, None, "no outcome recorded"), + ("loader", 1, record(loader=["unittest.loader._FailedTest.m"]), "import or discovery failed"), + ("no tests", 0, record(tests_run=0), "0 tests ran"), + ("fixture before any test", 1, record(tests_run=0, fixtures=["m.T"]), "fixture failed before any test ran"), + ("exit 0 with a failure", 0, record(failed=["m.T.a"]), "exit 0 where unittest exits 1"), + ("exit 1 with none", 1, record(), "exit 1 where unittest exits 0"), + # An atexit hook or a thread ending the process after the record. + ("exit 7 with a failure", 7, record(failed=["m.T.a"]), "exit 7 where unittest exits 1"), + ("stopped early", 1, record(failed=["m.T.a"], stopped=True), "stopped early"), + ("killed", -2, record(failed=["m.T.a"]), "killed by signal 2"), + # What `read_unittest_record` hands over for a file it could + # not read as a record. + ("unreadable", 1, "the record is not JSON", "not JSON"), + ): + verdict, _, got = perturb.classify_unittest(rc, rec) + self.assertEqual(verdict, "HARNESS-ERROR", label) + self.assertIn(detail, got, label) + + def test_read_unittest_record_refuses_what_the_recorder_did_not_write(self) -> None: + # A run killed mid-write leaves a truncated file; a module that + # shadows the recorder could write anything. Neither is a + # traceback out of the sweep, and neither is read as a result. + path = pathlib.Path(self._tmp.name) / "record.json" + self.assertIsNone(perturb.read_unittest_record(path)) + for label, text, needle in ( + ("truncated", '{"tests_run": 1, "fai', "not JSON"), + ("not utf-8", b"\xff\xfe", "not JSON"), + ("a list", "[1, 2]", "unexpected shape (list)"), + ("a key missing", '{"tests_run": 1}', "unexpected shape"), + ("a wrong type", '{"tests_run": "1", "stopped": false, "failed": [], "unexpected": [], "loader": [], "fixtures": []}', "unexpected shape"), + ): + if isinstance(text, bytes): + path.write_bytes(text) + else: + path.write_text(text) + got = perturb.read_unittest_record(path) + self.assertIsInstance(got, str, label) + self.assertIn(needle, got, label) + self.assertEqual(perturb.classify_unittest(1, got)[0], "HARNESS-ERROR", label) + good = '{"tests_run": 1, "stopped": false, "failed": ["m.T.a"], "unexpected": [], "loader": [], "fixtures": []}' + path.write_text(good) + self.assertEqual(perturb.read_unittest_record(path)["failed"], ["m.T.a"]) + def test_help_and_a_missing_manifest_are_usage_not_a_traceback(self) -> None: for argv in (["--help"], []): err, out = io.StringIO(), io.StringIO() diff --git a/utils/perturb.py b/utils/perturb.py index ba0cdf4a8..0299e8e61 100755 --- a/utils/perturb.py +++ b/utils/perturb.py @@ -2,15 +2,18 @@ """Perturbation sweep driver (`.claude/rules/testing.md`, "Verify defensive refactor tests by reverting the production code"). -Applies one exact substitution to one production file, runs a cargo -test command, records which tests fail, and restores the file from the +Applies one exact substitution to one production file, runs a test +command, records which tests fail, and restores the file from the in-memory copy in a `finally`. A perturbation that fails nothing is a finding; one whose anchor does not match is an error, never a silent no-op (lesson 94). manifest: { "cwd": , + "runner": "cargo" (the default) | "unittest", "cargo": ["cargo", "test", "-p", ..., "--", ...], + or, under any runner, + "command": [], "record": , "cases": [{"name": ..., "file": , "old": ..., "new": ..., @@ -21,12 +24,51 @@ test that should discriminate this did". Without it `caught` means "some test failed", which a bench-harness probe tripping on a zero reading satisfies; a run with any `expect`-less case prints a note, and -`failed` must be read for those. - -The failure parser reads `cargo test` output only: the `test -... FAILED` lines and the `test result:` summary of each target. A -`cargo nextest` argv prints neither, so every red run under it is -`HARNESS-ERROR` — loud, but not a result. +`failed` must be read for those. Names are spelled as each runner lists +them: `cargo test -- --list` (a `#[should_panic]` test without the +` - should panic` its progress line adds), and unittest's +`module.Class.test`. + +The cargo runner reads `cargo test` output only: each target's +`failures:` list and `test result:` summary, which `-q` and `--format +terse` print too. A `cargo nextest` argv prints neither, so every red +run under it is `HARNESS-ERROR` — loud, but not a result. Under +`--nocapture` a doctest's compile error is printed outside its captured +section and reads as `BUILD-ERROR`. + +The unittest runner, for a Python subject such as the `utils/*-test.py` +gates, takes `"command": ["python3", "-B", "-m", "unittest", ...]` (or +`... -m unittest discover ...`). It: + +- parses the argv as unittest does, and refuses fail-fast in any + spelling (`-f`, `-vf`, `--failfast`, `--fail`), which hides every + guard after the first failure, and an interpreter option that ignores + the environment (`-E`, `-I`) or moves the bytecode cache (`-X + pycache_prefix`); +- runs the suite once unperturbed and refuses one that is not green; +- runs `-m perturb_unittest_recorder` in place of `-m unittest`: the same + `unittest.main`, which writes each outcome by `TestCase.id()` to a + file. That record is what is classified; the printed report is never + read, because a test can print anything — a ruled `FAIL:` header, a + nested unittest's report — and `-b` copies it into the report, where + no reading of the text can tell it from unittest's own. A failing + subtest counts against the test that holds it; an unexpected success + as a failure; a failing `setUpClass` / `setUpModule` against its class + or module id. An import or discovery failure, a run stopped early or + killed, one whose exit status is not unittest's own for its record, + or one that wrote no record, is `HARNESS-ERROR`, never `caught`: no + assertion caught it; +- runs each test with no bytecode cache to read and writes none + (`PYTHONPYCACHEPREFIX` at an empty scratch directory, writes off), so + a `.pyc` left by a same-length mutant cannot be loaded for the next + one (#1562). Every run recompiles what it imports, the interpreter's + own start-up modules included: about 0.13 s per run against 0.05 s + with a warm cache, so a sweep costs roughly 0.15 s per case. That is + the price of the guarantee; `-B` alone is the cheap form #1562 + rejects. + +Runs on Python 3.10 and later; the self-test skips what an older +interpreter cannot show (unittest's 3.14 colour, 3.12's argparse). The refusals and classifications are the acceptance criteria of #1744 and #1787, each one a failure the rules file has already paid for: @@ -78,29 +120,48 @@ from __future__ import annotations import argparse +import contextlib +import io import json +import os import pathlib import re import subprocess import sys import tempfile +from collections.abc import Callable +from dataclasses import dataclass BUILD_ERROR_RE = re.compile(r"^error\[|could not compile", re.M) -# A test name can hold spaces: a doctest's is `src/lib.rs - item (line 7)` -# (#1831). Each pattern is anchored at both ends of its line, so the lazy -# group cannot run past the line's own delimiter. The progress line is -# the name: a `compile_fail` doctest's carries ` - compile fail`, which -# its `----` header drops, so the headers are read only when no progress -# line is (a `--format terse` run, say), never merged with them. -FAILED_LINE_RE = re.compile(r"^test (.+?) \.\.\. FAILED$", re.M) -FAILED_HEADER_RE = re.compile(r"^---- (.+?) stdout ----$", re.M) -# A test's captured output runs from its `---- name stdout ----` header to -# the next header or the `failures:` list after the last one. A doctest -# that fails to compile prints its `error[E…]` there, which is a failing -# test, not a build that never reached the tests. -TEST_STDOUT_RE = re.compile(r"^---- .+? stdout ----$.*?(?=^---- |^failures:$|\Z)", re.M | re.S) +# Each target's `failures:` list, which cargo ends with a blank line and +# that target's `test result:`: the names cargo would accept back +# (`--exact`, `--list`), one per indented line. The progress line is not +# that: `#[should_panic]` and `compile_fail` tests add ` - should panic` / +# ` - compile fail` there and nowhere else, and `-q` / `--format terse` +# print no progress lines at all. A name can hold spaces: a doctest's is +# `src/lib.rs - item (line 7)` (#1831). +_FAILURES_LIST = r"^failures:\n((?: {4}\S[^\n]*\n)+)\ntest result: " +FAILURES_LIST_RE = re.compile(_FAILURES_LIST, re.M) +# A test's captured output: from its `---- name stdout ----` header to the +# next such header, or to the `failures:` list after the last one. Both +# ends are matched whole, header on one line and list up to its `test +# result:`, because a test may print lines starting `---- `, a +# `failures:` line, or `test x ... FAILED` itself. What a test printed is +# not cargo's report: a doctest's own `error[E…]` is a failing test, not +# a build that never reached the tests. A test that prints a whole target +# report, list and `test result:` both, is cargo's shape exactly; no line +# parser can tell the two apart. +_HEADER = r"^---- [^\n]+ stdout ----$" +TEST_STDOUT_RE = re.compile(rf"{_HEADER}.*?(?={_HEADER}|{_FAILURES_LIST}|\Z)", re.M | re.S) TEST_RESULT_RE = re.compile(r"^test result: \w+\. (\d+) passed; (\d+) failed;", re.M) +# The module a unittest sweep runs in place of `unittest` (see +# `perturb_unittest_recorder.py`): unittest's own `main`, writing each +# outcome by `TestCase.id()` to the file named in RECORD_ENV. +UNITTEST_RECORDER = "perturb_unittest_recorder" +UTILS_DIR = pathlib.Path(__file__).resolve().parent +UNITTEST_RECORD_ENV = "PERTURB_UNITTEST_RECORD" + CARGO_PROGRAMS = frozenset({"cargo", "cargo.exe"}) # `t` is cargo's built-in alias for `test`. TEST_SUBCOMMANDS = frozenset({"test", "t"}) @@ -258,8 +319,9 @@ def classify(returncode: int, output: str) -> tuple[str, set[str], str]: `HARNESS-ERROR` describe the harness: a disagreement between the parsed failure set and the exit status, or a run in which no test ran.""" - failed = set(FAILED_LINE_RE.findall(output)) or set(FAILED_HEADER_RE.findall(output)) - if BUILD_ERROR_RE.search(TEST_STDOUT_RE.sub("", output)): + report = TEST_STDOUT_RE.sub("", output) + failed = {name.strip() for block in FAILURES_LIST_RE.findall(report) for name in block.splitlines()} + if BUILD_ERROR_RE.search(report): return "BUILD-ERROR", failed, "the build failed" if (returncode != 0) != bool(failed): return "HARNESS-ERROR", failed, f"exit {returncode} disagrees with {len(failed)} parsed failure(s)" @@ -271,9 +333,245 @@ def classify(returncode: int, output: str) -> tuple[str, set[str], str]: return ("caught" if failed else "UNCAUGHT"), failed, "" -def run_tests(cwd: pathlib.Path, cargo: list[str]) -> tuple[int, str]: - r = subprocess.run(cargo, cwd=cwd, capture_output=True, text=True, errors="replace") - return r.returncode, r.stdout + r.stderr +# Interpreter options that stop a run reading its environment (`-E`, `-I`) +# or that point its bytecode cache elsewhere (`-X pycache_prefix`): each +# undoes `unittest_env`'s isolation, so a mutant can run stale bytecode. +PYTHON_ENV_FLAGS = frozenset("EI") + + +def unittest_cli(discover: bool) -> argparse.ArgumentParser: + """unittest's own command line, as `python -m unittest [discover]` + parses it (`unittest/main.py`, `_getParentArgParser` and the main or + discovery parser on top): abbreviated long options (`--fail` for + `--failfast`), short-option clusters (`-vq`, `-kfoo`) and discovery's + three optional positionals between options are read as unittest + reads them. `--durations` is 3.12+; accepting it on an older host + only lets unittest refuse it, which the preflight reports.""" + ap = argparse.ArgumentParser(add_help=False, allow_abbrev=True, exit_on_error=False) + ap.add_argument("-v", "--verbose", dest="verbosity", action="store_const", const=2) + ap.add_argument("-q", "--quiet", dest="verbosity", action="store_const", const=0) + ap.add_argument("--locals", action="store_true") + ap.add_argument("--durations", type=int) + ap.add_argument("-f", "--failfast", action="store_true") + ap.add_argument("-c", "--catch", action="store_true") + ap.add_argument("-b", "--buffer", action="store_true") + ap.add_argument("-k", action="append") + if discover: + ap.add_argument("-s", "--start-directory") + ap.add_argument("-p", "--pattern") + ap.add_argument("-t", "--top-level-directory") + for positional in ("start", "pattern_", "top"): + ap.add_argument(positional, nargs="?") + else: + ap.add_argument("tests", nargs="*") + return ap + + +def python_argv_problem(interpreter: list[str]) -> str | None: + """Why the interpreter options before `-m` defeat the bytecode + isolation, or None.""" + for at, tok in enumerate(interpreter): + if tok.startswith("--") or not tok.startswith("-"): + continue + # `-X` and `-W` take a value, attached or as the next token. + flags = tok[1:] + for i, letter in enumerate(flags): + if letter in PYTHON_ENV_FLAGS: + return f"`-{letter}` ignores the environment, and with it the private bytecode cache" + if letter in "XW": + value = flags[i + 1 :] or (interpreter[at + 1] if at + 1 < len(interpreter) else "") + if letter == "X" and value.startswith("pycache_prefix"): + return "`-X pycache_prefix` overrides the private bytecode cache" + break + return None + + +def unittest_argv_problem(command: list[str]) -> str | None: + """Why `command` cannot be a unittest sweep, or None. + + It must run `python -m unittest`, which the runner swaps for its + recorder; must not stop at the first failure; and the interpreter must + read the environment `unittest_env` builds, which is how the recorder + is found and where its record goes.""" + try: + at = command.index("-m") + except ValueError: + return "no `-m unittest`: the runner runs unittest under its recorder" + if command[at + 1 : at + 2] != ["unittest"]: + return "no `-m unittest`: the runner runs unittest under its recorder" + if (problem := python_argv_problem(command[1:at])) is not None: + return problem + args = command[at + 2 :] + discover = args[:1] == ["discover"] + # Before 3.12 `exit_on_error=False` does not cover unrecognized + # arguments, which still print usage and exit. + err = io.StringIO() + try: + with contextlib.redirect_stderr(err): + parsed = unittest_cli(discover).parse_args(args[1:] if discover else args) + except argparse.ArgumentError as error: + return f"unittest would reject the argv: {error}" + except SystemExit: + return f"unittest would reject the argv: {err.getvalue().strip().splitlines()[-1]}" + if parsed.failfast: + return "fail-fast stops at the first failure, so later guards read as dead" + return None + + +# The record `perturb_unittest_recorder.py` writes, field by type. +UNITTEST_RECORD_SHAPE = {"tests_run": int, "stopped": bool, "failed": list, "unexpected": list, "loader": list, "fixtures": list} + + +def read_unittest_record(path: pathlib.Path) -> dict | str | None: + """The record at `path`: None when there is none, or why what is + there is not one. A run killed mid-write leaves a truncated file, and + a module shadowing the recorder (a subject's own + `perturb_unittest_recorder.py`, which `-m` finds on the cwd first) + could write anything to the path the environment names.""" + try: + record = json.loads(path.read_text(encoding="utf-8")) + except FileNotFoundError: + return None + except (json.JSONDecodeError, UnicodeDecodeError) as err: + return f"the record is not JSON ({err}): the run was killed mid-write, or something else wrote it" + if not isinstance(record, dict) or any( + not isinstance(record.get(key), kind) for key, kind in UNITTEST_RECORD_SHAPE.items() + ): + return f"the record has an unexpected shape ({sorted(record) if isinstance(record, dict) else type(record).__name__}): something else wrote it" + return record + + +def classify_unittest(returncode: int, record: dict | str | None) -> tuple[str, set[str], str]: + """`classify` for a unittest run, given the outcome its recorder wrote + (`perturb_unittest_recorder.py`), None when it wrote none, or + `read_unittest_record`'s reason it could not be read. A failing + subtest counts against the test that holds it, so `failed` is a set + of test ids, `module.Class.test`; an unexpected success counts as a + failure, since unittest exits 1 on one.""" + if record is None: + return "HARNESS-ERROR", set(), "no outcome recorded: the loader raised, or the run ended before its tests finished; no assertion caught it" + if isinstance(record, str): + return "HARNESS-ERROR", set(), record + failed = set(record["failed"]) | set(record["unexpected"]) | set(record["fixtures"]) + if returncode < 0: + return "HARNESS-ERROR", failed, f"the run was killed by signal {-returncode}: its failures are a partial set" + if record["stopped"]: + return "HARNESS-ERROR", failed, "the run was stopped early (an interrupt, or fail-fast): its failures are a partial set" + if record["loader"]: + return "HARNESS-ERROR", failed, f"import or discovery failed ({', '.join(record['loader'])}): no assertion caught it" + if record["tests_run"] == 0: + if record["fixtures"]: + return "HARNESS-ERROR", failed, "a class or module fixture failed before any test ran" + return "HARNESS-ERROR", failed, "0 tests ran: the selection matched nothing" + # unittest exits 1 with a failure and 0 without; any other status is + # the process ending some other way after the record was written (an + # atexit hook or a thread calling os._exit), which is not a result. + if returncode != (1 if failed else 0): + return "HARNESS-ERROR", failed, f"exit {returncode} where unittest exits {1 if failed else 0} with {len(failed)} recorded failure(s)" + return ("caught" if failed else "UNCAUGHT"), failed, "" + + +@dataclass(frozen=True) +class Runner: + """What a sweep needs from one test runner.""" + + #: Why an argv cannot be swept, or None. + argv_problem: Callable[[list[str]], str | None] + #: The refusal message's preamble, before the argv problem. + refusal: str + #: An extra refusal line saying what to do, or "". + refusal_hint: str + #: Whether to run the suite once unperturbed and refuse a red one. + preflight: bool + #: Runs the manifest's argv in `cwd`, with a private scratch + #: directory, and returns (verdict, failed tests, harness detail, rc). + run: Callable[[pathlib.Path, list[str], pathlib.Path], tuple[str, set[str], str, int]] + + +def run_cargo(cwd: pathlib.Path, argv: list[str], _scratch: pathlib.Path) -> tuple[str, set[str], str, int]: + r = subprocess.run(argv, cwd=cwd, capture_output=True, text=True, errors="replace") + return (*classify(r.returncode, r.stdout + r.stderr), r.returncode) + + +def unittest_env(scratch: pathlib.Path, record: pathlib.Path) -> dict[str, str]: + """A unittest run's environment: the recorder importable and told + where to write, no existing bytecode read and none written, no + colour. `-B` alone stops writes but still loads a `.pyc` whose + recorded size and mtime match, which a same-length edit restored + within the second leaves behind (#1562); an empty + `PYTHONPYCACHEPREFIX` hides every `.pyc`, the standard library's + included, so each run recompiles what it imports: about 0.13 s per + run against 0.05 s warm, the interpreter's own start-up being most + of it. The output is not read, so colour only keeps logs plain.""" + path = os.environ.get("PYTHONPATH") + return { + **os.environ, + "PYTHONPATH": str(UTILS_DIR) + (os.pathsep + path if path else ""), + UNITTEST_RECORD_ENV: str(record), + "PYTHONPYCACHEPREFIX": str(scratch / "pycache"), + "PYTHONDONTWRITEBYTECODE": "1", + "PYTHON_COLORS": "0", + "NO_COLOR": "1", + } + + +def run_unittest(cwd: pathlib.Path, argv: list[str], scratch: pathlib.Path) -> tuple[str, set[str], str, int]: + """Runs the manifest's `-m unittest` argv as `-m` the recorder, which + is unittest's own `main` writing its outcome to a file, and classifies + that record. The printed report is never read: a test can print + anything, `-b` copies it into the report, and no reading of the text + tells it from unittest's own.""" + # The first `-m` is the one `unittest_argv_problem` accepted; a `-m` + # earlier than it would have been refused as an interpreter option. + at = argv.index("-m") + recorded = [*argv[: at + 1], UNITTEST_RECORDER, *argv[at + 2 :]] + # Its own directory, not the scratch one: that holds the sweep's + # backups, and an interrupted run's record should not sit among them. + with tempfile.TemporaryDirectory(prefix="bca-perturb-unittest.") as run_dir: + record_path = pathlib.Path(run_dir) / "record.json" + env = unittest_env(scratch, record_path) + r = subprocess.run(recorded, cwd=cwd, capture_output=True, text=True, errors="replace", env=env) + record = read_unittest_record(record_path) + return (*classify_unittest(r.returncode, record), r.returncode) + + +RUNNERS = { + "cargo": Runner( + argv_problem=cargo_argv_problem, + refusal="the cargo argv can run several test targets without --no-fail-fast", + refusal_hint=( + "a failing target stops the run and every later target's guards read as dead; " + "add --no-fail-fast to the manifest's argv — perturb.py never adds it on your behalf" + ), + # Cargo sweeps have always skipped this run: a red suite already + # shows as every case failing the same tests. + preflight=False, + run=run_cargo, + ), + "unittest": Runner( + argv_problem=unittest_argv_problem, + refusal="the unittest argv", + refusal_hint="", + # A suite that is red before any perturbation would read every + # case as `caught`. + preflight=True, + run=run_unittest, + ), +} + + +def manifest_command(manifest: dict) -> tuple[str, list[str]] | str: + """The runner and argv a manifest names, or why it names none + unambiguously. `cargo` is the original key and implies the cargo + runner; `command` takes any runner.""" + runner = manifest.get("runner", "cargo") + if runner not in RUNNERS: + return f"unknown runner {runner!r}; expected one of {sorted(RUNNERS)}" + if ("cargo" in manifest) == ("command" in manifest): + return "name the argv under exactly one of `cargo` and `command`" + if "cargo" in manifest and runner != "cargo": + return f"the `cargo` key is the cargo runner's; use `command` for {runner!r}" + return runner, list(manifest.get("command", manifest.get("cargo"))) def anchor_problem(original: bytes, old: bytes, new: bytes) -> str | None: @@ -289,15 +587,17 @@ def sweep(manifest: dict, backup_dir: pathlib.Path) -> tuple[list[dict], int]: """Runs every case; returns the results and the exit status (1 when any case is not a clean `caught`, or a harness problem occurred).""" cwd = pathlib.Path(manifest["cwd"]).resolve() - cargo = list(manifest["cargo"]) - argv_problem = cargo_argv_problem(cargo) + chosen = manifest_command(manifest) + if isinstance(chosen, str): + print(f"refusing: {chosen}", file=sys.stderr) + return [], 2 + name, argv = chosen + runner = RUNNERS[name] + argv_problem = runner.argv_problem(argv) if argv_problem is not None: - print(f"refusing: the cargo argv can run several test targets without --no-fail-fast: {argv_problem}", file=sys.stderr) - print( - "a failing target stops the run and every later target's guards read as dead; " - "add --no-fail-fast to the manifest's argv — perturb.py never adds it on your behalf", - file=sys.stderr, - ) + print(f"refusing: {runner.refusal}: {argv_problem}", file=sys.stderr) + if runner.refusal_hint: + print(runner.refusal_hint, file=sys.stderr) return [], 2 cases = manifest["cases"] files = sorted({case["file"] for case in cases}) @@ -311,6 +611,11 @@ def sweep(manifest: dict, backup_dir: pathlib.Path) -> tuple[list[dict], int]: file=sys.stderr, ) return [], 2 + if runner.preflight: + verdict, failed, detail, _rc = runner.run(cwd, argv, backup_dir) + if verdict != "UNCAUGHT": + print(f"refusing: the unperturbed suite is not green ({verdict}: {detail or sorted(failed)})", file=sys.stderr) + return [], 2 backups: dict[pathlib.Path, bytes] = {} results: list[dict] = [] rc_all = 0 @@ -333,10 +638,9 @@ def sweep(manifest: dict, backup_dir: pathlib.Path) -> tuple[list[dict], int]: continue try: path.write_bytes(original.replace(old, new)) - rc, output = run_tests(cwd, cargo) + verdict, failed, detail, rc = runner.run(cwd, argv, backup_dir) finally: path.write_bytes(original) - verdict, failed, detail = classify(rc, output) expect = set(case.get("expect", [])) if not expect: no_expect += 1 diff --git a/utils/perturb_unittest_recorder.py b/utils/perturb_unittest_recorder.py new file mode 100644 index 000000000..ae6e68971 --- /dev/null +++ b/utils/perturb_unittest_recorder.py @@ -0,0 +1,123 @@ +"""`python -m unittest`, recording its outcome as data for `perturb.py`. + +`perturb.py`'s unittest runner replaces `-m unittest` in a sweep's +command with `-m perturb_unittest_recorder` (this module, on +`PYTHONPATH`), so the run is unittest's own `main` with its own +argument parsing, output and exit status, plus one thing: when it ends, +the outcome is written as JSON to the path in `PERTURB_UNITTEST_RECORD`. + +The record is what the sweep reads, never unittest's printed report. A +test can print anything — a ruled `FAIL:` header, a whole nested +unittest report, a line shaped like a progress verdict — to either +stream, and `-b` copies it into the report; no reading of the text can +tell that from unittest's own. The record holds `TestCase.id()` for +each failure, as the result object received it: + + {"tests_run": N, + "stopped": , the run was stopped early (`-c` and + SIGINT, or fail-fast) + "failed": [, ...], failures and errors, subtests under + the test that holds them + "unexpected": [, ...], unexpected successes + "loader": [, ...], import or discovery failures + "fixtures": [, ...]} setUpClass / setUpModule and their + teardowns, under the class or module + +No record means the run did not return normally — an import that killed +the loader, an exception escaping a test such as `KeyboardInterrupt`, a +crash — and `perturb.py` reports that as a harness error, as it does a +run that was stopped early. + +Self-tested through `utils/perturb-test.py`. A sweep of this file with +the unittest runner perturbs the runner's own recorder as well as the +subject, since both import it from here: sweep it from a `git archive` +copy, or read a mutant that stops the record being written as the +harness error it then is. +""" + +from __future__ import annotations + +import json +import os +import sys +import unittest +from unittest.suite import _ErrorHolder # type: ignore[attr-defined] + +RECORD_ENV = "PERTURB_UNITTEST_RECORD" +# An import or discovery failure is reported as a synthetic test named for +# the loader, never a test of the module. +LOADER_PREFIXES = ("unittest.loader._FailedTest", "unittest.loader.ModuleImportFailure") + + +class RecordingResult(unittest.TextTestResult): + """unittest's own text result, recording each outcome by id.""" + + def __init__(self, *args: object, **kwargs: object) -> None: + super().__init__(*args, **kwargs) # type: ignore[arg-type] + self.record: dict[str, list[str]] = {"failed": [], "unexpected": [], "loader": [], "fixtures": []} + self.seen: set[str] = set() + + def _failed(self, test: unittest.TestCase) -> None: + test_id = test.id() + if isinstance(test, _ErrorHolder): + # `setUpClass (m.T)`: a class or module fixture, no one test. + name = test.description.split(" ", 1) + bucket = "fixtures" + test_id = name[1].strip("()") if len(name) == 2 else test.description + elif test_id.startswith(LOADER_PREFIXES): + bucket = "loader" + else: + bucket = "failed" + # Once per id: a test's subtests each report the test. A set rather + # than a list scan, which was quadratic past ~10 000 failures. + if test_id not in self.seen: + self.seen.add(test_id) + self.record[bucket].append(test_id) + + def addFailure(self, test, err): # noqa: N802 — unittest's API + super().addFailure(test, err) + self._failed(test) + + def addError(self, test, err): # noqa: N802 + super().addError(test, err) + self._failed(test) + + def addSubTest(self, test, subtest, err): # noqa: N802 + super().addSubTest(test, subtest, err) + if err is not None: + self._failed(test) + + def addUnexpectedSuccess(self, test): # noqa: N802 + super().addUnexpectedSuccess(test) + self.record["unexpected"].append(test.id()) + + +class RecordingRunner(unittest.TextTestRunner): + resultclass = RecordingResult + + def run(self, test): + """unittest's run, then the record — only when the run returned. + + `TextTestRunner.run` calls `stopTestRun` in a `finally`, so a + `KeyboardInterrupt` or `SystemExit` escaping a test still reaches + it with the outcomes so far; writing there certified a partial + run. Written here, an exception leaves no record, which the sweep + reports as a harness error. `-c` turns SIGINT into a graceful + stop that does return: `shouldStop` marks it, and the record says + so for the sweep to refuse.""" + result = super().run(test) + path = os.environ.get(RECORD_ENV) + if path: + with open(path, "w", encoding="utf-8") as fh: + json.dump({"tests_run": result.testsRun, "stopped": bool(result.shouldStop), **result.record}, fh) + return result + + +def main() -> None: + # As `python -m unittest` names itself in usage and help. + sys.argv[0] = os.path.basename(sys.executable) + " -m unittest" + unittest.main(module=None, testRunner=RecordingRunner) + + +if __name__ == "__main__": + main() From b7e344f5e236c21e301edc122243db54dc665233 Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Fri, 6 Nov 2026 16:03:47 -0800 Subject: [PATCH 21/25] fix(deny): ban h2 below 0.4.16, which --workspace makes a live guard deny.toml said no `deny` entry for h2 <0.4.16 (RUSTSEC-2026-0258) could work because cargo-deny's graph builder filters the crate out before any check runs; lockfile_tests.rs and lessons_learned.md said the same. The observation was right and the diagnosis wrong: CI ran cargo-deny from the root with no --workspace, and the root manifest is also the big-code-analysis package, which does not depend on actix, so the web crate's closure was never visited and `filtered h2 0.3.27` meant unreachable from the roots, not invisible to cargo-deny. #1823's script passes --workspace, and on the pre-fix lockfile (3df3b2c3^) the same ban then fires: `error[banned]: crate 'h2 = 0.3.27'`, on 0.19.4 and 0.20.2 alike; without --workspace it stays silent. On today's lockfile the entry passes, and on a graph with no h2 at all (tree-sitter-ccomment) it adds no warning. Confirmed independently by two reviewers against both cargo-deny versions. The ban is added as a second guard beside the lockfile test, which holds whatever roots a future invocation selects, and the three texts say what the filter line means. The script fetches the advisory database once per lockfile, ~0.4 s each. --offline on the later runs was measured at 0.1 s each and rejected: it also stops the crate-index fetch, and on a cold cache a later manifest's crate the earlier runs did not pull fails resolution. The script's comment records the measurement. --- big-code-analysis-web/src/lockfile_tests.rs | 14 ++++++++----- deny.toml | 15 +++++++++----- docs/development/lessons_learned.md | 22 ++++++++++++++------- utils/check-deny-manifests.sh | 6 ++++++ 4 files changed, 40 insertions(+), 17 deletions(-) diff --git a/big-code-analysis-web/src/lockfile_tests.rs b/big-code-analysis-web/src/lockfile_tests.rs index 3f10d31fc..365561e64 100644 --- a/big-code-analysis-web/src/lockfile_tests.rs +++ b/big-code-analysis-web/src/lockfile_tests.rs @@ -7,11 +7,15 @@ //! negotiates HTTP/2 anyway — and the lockfile drops the crate once no //! workspace member can enable it. //! -//! cargo-deny cannot guard this: krates filters `h2 0.3.27` out of the -//! graph before the advisory and ban checks run, on 0.19 and 0.20 alike, -//! so `deny.toml` is silent whether or not the feature is on. Reading the -//! lockfile is the only observation that fails when `http2` comes back — -//! through a re-enabled default, or a new dependency that turns it on. +//! `deny.toml` bans `h2 <0.4.16` as well. That ban is live only while +//! cargo-deny roots its graph at every workspace member (`--workspace`, +//! which `utils/check-deny-manifests.sh` passes since #1823): rooted at +//! the root package alone, as CI once ran it, this crate's closure is +//! never visited and the ban cannot fire — which was misread as krates +//! filtering the crate out when the feature was dropped. This test reads +//! the lockfile directly, so it holds whatever roots a future cargo-deny +//! invocation selects, when `http2` comes back through a re-enabled +//! default or a new dependency that turns it on. use std::path::Path; diff --git a/deny.toml b/deny.toml index c3ed93211..ca99a314b 100644 --- a/deny.toml +++ b/deny.toml @@ -62,11 +62,16 @@ wildcards = "deny" # dev-deps, which crates.io strips; a published crate's still needs a version. # A git source must also pass `[sources]` below, which denies unknown ones. allow-wildcard-paths = true -# No `deny` entry for `h2 <0.4.16` (RUSTSEC-2026-0258): cargo-deny's graph -# builder drops that crate before any check runs (`-L debug` logs -# `filtered h2 0.3.27` with `actix-web/http2` enabled, on 0.19 and 0.20), -# so neither an advisory nor a ban can see it. The lockfile is pinned by -# `lockfile_tests` in big-code-analysis-web instead. +# `h2 0.3` (RUSTSEC-2026-0258) reached the tree through `actix-web`'s +# `http2` feature, which big-code-analysis-web no longer enables. This +# entry fires if it comes back; `lockfile_tests` in that crate reads the +# lockfile directly as a second guard. The entry is live only because the +# graph is rooted at every workspace member (`--workspace`, #1823): rooted +# at the root package alone, as CI's old `cargo-deny-action` ran it, the +# web crate's closure is never visited and `-L debug` logs `filtered h2 +# 0.3.27` — an unreachable crate, not one cargo-deny cannot see, which +# was misread as the latter when the feature was dropped (`3df3b2c3`). +deny = [{ crate = "h2:<0.4.16", reason = "RUSTSEC-2026-0258; see big-code-analysis-web/src/lockfile_tests.rs" }] [sources] unknown-registry = "deny" diff --git a/docs/development/lessons_learned.md b/docs/development/lessons_learned.md index d72394cac..6764772a0 100644 --- a/docs/development/lessons_learned.md +++ b/docs/development/lessons_learned.md @@ -3889,13 +3889,21 @@ call and not a property of actix — `bind_auto_h2c` speaks plaintext HTTP/2 without TLS, and is itself `#[cfg(feature = "http2")]`, so dropping the feature removes the H2C entry point along with the vulnerable crate. The obvious belt-and-braces guard, a `[bans] deny` on -`h2 <0.4.16`, turned out to be dead by construction — krates, cargo-deny's -graph builder, filters the crate out before the advisory and ban checks -run (`-L debug` logs `filtered h2 0.3.27`), on 0.19 and on the 0.20 that -CI's action bundles. Re-enabling `actix-web/http2` under both versions -left cargo-deny silent. The working guard reads `Cargo.lock` directly -from a test, and `deny.toml` carries a comment where the entry would -have been, naming the reproduction so the next reader does not add one. +`h2 <0.4.16`, was then found dead: re-enabling `actix-web/http2` left +cargo-deny silent on 0.19 and on the 0.20 CI's action bundled, with +`-L debug` logging `filtered h2 0.3.27`. That observation was right and +its diagnosis wrong. The filter was not krates dropping the crate; it +was the graph's roots. CI ran cargo-deny from the repository root with +no `--workspace`, and the root manifest is also the `big-code-analysis` +*package*, which does not depend on actix, so the web crate's whole +closure went unvisited. #1823 established that by measurement (155 of +374 crates unread) and `utils/check-deny-manifests.sh` now passes +`--workspace`; on the pre-fix lockfile the same ban then fires +(`error[banned]: crate 'h2 = 0.3.27'`), and it is in `deny.toml` as a +live guard beside the lockfile test. A `filtered ` debug line +means *unreachable from the chosen roots*, not *invisible to +cargo-deny*; check the roots before concluding a check cannot see a +crate. **A scaling probe that never reaches the scan it prices reads linear with or without the memo** (#1602, #1697 cost audit). The probe's diff --git a/utils/check-deny-manifests.sh b/utils/check-deny-manifests.sh index f6a9b62a0..6490c27a7 100755 --- a/utils/check-deny-manifests.sh +++ b/utils/check-deny-manifests.sh @@ -114,6 +114,12 @@ for lock in "${locks[@]}"; do # package, and handed a member cargo-deny roots the graph at it alone, # which left the CLI, web, py, bench and xtask closures (155 of 374 # crates) unread. On the seven single-package graphs it changes nothing. + # Each run fetches the advisory database again, ~0.4 s each and ~3.5 s + # for the eight on a warm cache. `--offline` on the later runs would + # cut that to ~0.1 s each, but it also stops the crate-index fetch, + # and on a cold cache a later manifest's crate the earlier runs did + # not pull fails resolution (`location searched: crates.io index`, + # measured with `tree-sitter-tcl` first and `enums` offline after it). if ! cargo-deny --locked \ --workspace \ --manifest-path "$ROOT/$manifest" \ From 9bd5f1de4411001928903cde9429c4f1a01df93b Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Fri, 6 Nov 2026 16:19:07 -0800 Subject: [PATCH 22/25] test(nargs): pin the aggregate exception the docs state The #1809 docs say closure_args_average can fall below closure_args_min, on the book's pick fixture, and nothing held them. A test asserts min 4, max 4, sum 4 and average 1.0 there, so the three docs are known to need an edit the day the definition changes. The #1809 CHANGELOG entry goes, being docs-only; the #1416 entry names pdf.js as the corpus with the deepest nesting. --- CHANGELOG.md | 18 ++++-------------- src/metrics/nargs.rs | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 37 insertions(+), 14 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ac842ec3f..f7ae1fec4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -290,9 +290,10 @@ for historical reference. whose own line prints that text. Above that depth nothing changes: output is byte-identical to before, colour included, which held for every file of the serde, pdf.js and DeepSpeech corpora under `-t all` - and `-t call_expression`; their deepest same-row nesting is 42. The renderer is reached through two new - `#[doc(hidden)]` re-exports, `dump_found_with_color` and - `write_found`, which exist for the CLI and the scaling bench and are + and `-t call_expression`; their deepest same-row nesting is 42, in + pdf.js. The renderer is reached through two new `#[doc(hidden)]` + re-exports, `dump_found_with_color` and `write_found`, which exist + for the CLI and the scaling bench and are outside the stability contract (`STABILITY.md`). - **A `role_table!` owner may carry a parent list** (#1794). `K(under [P, ..])` admits the owner only under one of the listed @@ -312,17 +313,6 @@ for historical reference. changes: a drift-oracle sweep over the six languages, 7,028 outputs in 14 views, found 0 differing for the first four, and the fifth expands to the parent test its fn spelled. -- **NArgs documents where its aggregates disagree** (#1809). The - extrema fold every space's own count, the file unit and containers - included, while the averages divide by the functions and closures - `nom` counts. A lambda that opens no space adds its parameters to - the enclosing function's `closure_args` yet is one closure of the - divisor, so `closure_args_average` can fall below - `closure_args_min`, and file-level `function_args_min` is always 0. - The `Stats` docs, a new NArgs aggregates subsection in the book and - the Python bindings' metric page now say so. The definition is - unchanged, since changing it moves integration snapshots; #1827 - tracks the same shape in `loc`. - **The agent-feedback recipe documents the OpenCode V2 install** (#1811). The book had only the legacy V1 example and a pointer to the shipped V2 diff --git a/src/metrics/nargs.rs b/src/metrics/nargs.rs index 3005d848a..583a4cc50 100644 --- a/src/metrics/nargs.rs +++ b/src/metrics/nargs.rs @@ -929,6 +929,39 @@ mod tests { /// The fixture is the #1236 reproducer, picked because no space in it /// has `own == total`: a fixture where the two agree passes whichever /// one the code reads. + /// The `Stats` doc's and the book's `#nargs-aggregates` example, held + /// here so the sentence "`closure_args_average` can fall below + /// `closure_args_min`" stops being true the day #1809 changes the + /// definition, and the three docs that state it are known to need + /// an edit. Four one-parameter lambdas open no space, so `pick` owns + /// all four parameters (min = max = 4) while `nom` counts four + /// closures (average 1.0). + #[cfg(feature = "python")] + #[test] + fn closure_args_average_falls_below_min_when_lambdas_open_no_space() { + check_spaces::( + "def pick(rows): + a = sorted(rows, key=lambda r: r[0]) + b = filter(lambda r: r[1], a) + c = map(lambda r: r[2], b) + return min(c, key=lambda r: r) +", + "pick.py", + |space| { + let pick = space.spaces.first().expect("pick is the first space"); + assert_eq!(pick.name.as_deref(), Some("pick")); + let nargs = &pick.metrics.nargs; + assert_eq!(nargs.closure_args_min(), 4); + assert_eq!(nargs.closure_args_max(), 4); + assert_eq!(nargs.closure_args_sum(), 4); + assert!((nargs.closure_args_average() - 1.0).abs() < 1e-9); + assert!(nargs.closure_args_average() < nargs.closure_args_min() as f64); + // The file unit declares no parameters, so its minimum is 0. + assert_eq!(space.metrics.nargs.function_args_min(), 0); + }, + ); + } + #[cfg(feature = "rust")] #[test] fn own_args_excludes_nested_closure_spaces() { From a237ddc857ea9d05cbb9201ac578d5adbf40a510 Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Fri, 6 Nov 2026 16:08:28 -0800 Subject: [PATCH 23/25] fix(roles): refuse an empty payer parent list from a fragment too MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The #1794 review of the role-table parent lists: - A row's own `pays [K under []]` was refused at the entry scan, but a `..fragment!()` splices straight into the row body, whose payer pattern took the list as `*`: `EQEQ under [],` from a fragment compiled and rendered a payer that never pays, the shape the new doctest says is rejected. The body now takes `+` as the scan does; the fragment form fails with `no rules expected ']'` and a named list still compiles. No production fragment spelled it. - Java's Modifier row comment carried the Halstead consumer's reading of directive words, which macro-comments.md puts at the consumer; it now states the grammar fact and points at the consumer's test. - grammar-dispatch.md §4 says a parent-only gate is a row list, not a fn, and why the ElseIf family keeps its emitters. - Objective-C's conditional list is 19 where the other three dialects have 20: its grammar mints one preproc_ifdef alias fewer and one more each of preproc_else and preproc_elif, so the count is the grammar's, not a slip; the per-dialect oracle holds each list to its enum, and the list's doc now says so. --- .claude/rules/grammar-dispatch.md | 8 ++++++++ big-code-analysis-ast/src/roles/c_family.rs | 7 ++++++- big-code-analysis-ast/src/roles/java.rs | 8 +++----- big-code-analysis-ast/src/roles/mod.rs | 2 +- big-code-analysis-ast/src/roles/parent_list_doctests.rs | 4 +++- 5 files changed, 21 insertions(+), 8 deletions(-) diff --git a/.claude/rules/grammar-dispatch.md b/.claude/rules/grammar-dispatch.md index bc019a5ca..5ee51b298 100644 --- a/.claude/rules/grammar-dispatch.md +++ b/.claude/rules/grammar-dispatch.md @@ -146,6 +146,14 @@ rg -n 'ElseIf \{ absent' big-code-analysis-ast/src/roles/*.rs # the co | the owner is the sole statement of the `else:` block (`else_clause → block → if_statement`, #276) | hand-written gate on the row; the Checker is `Branch ∧ ElseIf`, so the `elif_clause` the row also owns stays false | Python | | `absent` row — the trait default `false` | — | Elixir (`cond` and nested `if/else`, no chain to collapse) | +A gate that is only the owner's parent kind is not a `fn` at all +since #1794: spell it on the row as `K(under [P, ..])` or +`K(not_under [P, ..])`, which the Python reader and the derived suite +then see. The `ElseIf` family keeps its emitters because their gates +read more than the parent (the clause's previous sibling, the outer +`if`), and because a `fn` stays in cargo-mutants' reach where a row +list does not (`docs/development/mutation_testing.md`). + Two things that list is worth reading for. The dedicated-clause row exists because some grammars emit an `elif_clause` / `ElsifClause` / `Elseif` node with no nested `if` to inspect at all — a shape neither diff --git a/big-code-analysis-ast/src/roles/c_family.rs b/big-code-analysis-ast/src/roles/c_family.rs index 77f0882e1..5cdd0f01c 100644 --- a/big-code-analysis-ast/src/roles/c_family.rs +++ b/big-code-analysis-ast/src/roles/c_family.rs @@ -542,7 +542,12 @@ macro_rules! c_family_conditional_kinds { }; } -/// The ids of `objc_doc_conditionals!`, for the Objective-C grammar. +/// The ids of `objc_doc_conditionals!`, for the Objective-C grammar: +/// 19 where the other three have 20, since its grammar mints one +/// `preproc_ifdef` alias fewer and one more each of `preproc_else` and +/// `preproc_elif`, with two `preproc_elifdef`. The per-dialect +/// `old_names_are_the_conditional_kinds` test holds each list to its +/// enum, so a count that looks like a slip is the grammar's. macro_rules! objc_conditional_kinds { () => { $crate::roles::c_family::preproc_conditional_kind!(Objc [ diff --git a/big-code-analysis-ast/src/roles/java.rs b/big-code-analysis-ast/src/roles/java.rs index 7f65e9daf..f25bd1515 100644 --- a/big-code-analysis-ast/src/roles/java.rs +++ b/big-code-analysis-ast/src/roles/java.rs @@ -262,11 +262,9 @@ role_table! { // `int permits`) as an `identifier`, so they need no gate. The // `static` of `import static` and `requires static` sits under an // `import_declaration` / `requires_modifier`, a directive that - // qualifies no declaration. Java bills no directive word (`package`, - // `import`, `module`, `requires`, `exports`, `transitive`, measured - // on a fixture of each), so without the list this would be the one - // that bills; #1600 records C#, which bills `using static` in full, - // as the outlier in the book's Halstead rules. + // qualifies no declaration, and is not a modifier; what the + // Halstead consumer makes of directive words is its own + // (`java_modifiers_are_operators_1565`, #1600). Modifier { owns [ Public, Private, Protected, Static(not_under [ImportDeclaration, RequiresModifier]), diff --git a/big-code-analysis-ast/src/roles/mod.rs b/big-code-analysis-ast/src/roles/mod.rs index 37d9a9e0c..7f6b54ff5 100644 --- a/big-code-analysis-ast/src/roles/mod.rs +++ b/big-code-analysis-ast/src/roles/mod.rs @@ -1427,7 +1427,7 @@ macro_rules! role_table { }; (@row_body $lang:ident $role:ident [$mode:ident] { owns [ $($owner:ident $(( $($owner_attr:tt)* ))?),* $(,)? ] - pays [ $($payer:ident $(gated_by $payer_gate:ident)? $(under [$($payer_parent:ident),*])?),* $(,)? ] + pays [ $($payer:ident $(gated_by $payer_gate:ident)? $(under [$($payer_parent:ident),+ $(,)?])?),* $(,)? ] $(project $field:literal)? $(wraps [ $($wrapped:ident),* $(,)? ])? $(excludes [ $($excluded:ident $excluded_why:literal),* $(,)? ])? diff --git a/big-code-analysis-ast/src/roles/parent_list_doctests.rs b/big-code-analysis-ast/src/roles/parent_list_doctests.rs index 5cbaddc50..ab1fec52b 100644 --- a/big-code-analysis-ast/src/roles/parent_list_doctests.rs +++ b/big-code-analysis-ast/src/roles/parent_list_doctests.rs @@ -93,7 +93,9 @@ //! ``` //! //! And a list names at least one kind, an owner's or a payer's — an -//! empty one would claim the kind and never admit it: +//! empty one would claim the kind and never admit it. The row body +//! requires it as well as the entry scan, so a `..fragment!()` whose +//! splice spells `K under []` is refused where a row's own `pays` is: //! //! ```compile_fail //! # #[macro_use] extern crate big_code_analysis_ast; From c42a9bb20662a57bc1fee952479b465953a6f8bd Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Fri, 6 Nov 2026 16:19:07 -0800 Subject: [PATCH 24/25] docs: fixes from the batch's prose and performance reviews benchmarking.md gains the width probe added in 82c7d33f and the 1.80 and 1.81 readings; loc/c-nested-conditional-docs' rationale records that bypassing the memo fits 1.95 against 0.92, as testing.md asks of a probe; AGENTS.md's utils inventory names the unittest recorder; mutation_testing.md says why it lists four moved gates where the CHANGELOG counts five; nodes.md describes the position pairs and the trailing space and names pdf.js; a pronoun slip in grammar-dispatch.md. --- .claude/rules/grammar-dispatch.md | 2 +- AGENTS.md | 5 ++++- big-code-analysis-bench/src/shapes.rs | 3 ++- big-code-analysis-book/src/commands/nodes.md | 10 +++++----- docs/development/benchmarking.md | 20 +++++++++++++++----- docs/development/mutation_testing.md | 4 +++- 6 files changed, 30 insertions(+), 14 deletions(-) diff --git a/.claude/rules/grammar-dispatch.md b/.claude/rules/grammar-dispatch.md index 5ee51b298..3fd44c542 100644 --- a/.claude/rules/grammar-dispatch.md +++ b/.claude/rules/grammar-dispatch.md @@ -200,7 +200,7 @@ deliberate double count is a visible choice at the consumer, never an accident on the row. The compound-operator case above is still the consumer's: the row owns `not in` and pays its token, and returning `Unknown` for the inner `not` *under* the compound is a parent guard -in the classifier, which a payer cannot spell: a payer takes +in the classifier, which a row cannot spell: a payer takes `under [..]`, never `not_under` (#1794). ## 6. Narrow a dispatch set with a gate, never by deletion diff --git a/AGENTS.md b/AGENTS.md index 94c27b0ca..7464c33a9 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -125,7 +125,10 @@ and `cargo run -p big-code-analysis-web --`. the lesson-102 truncation sweep; `perturb.py` is the `.claude/rules/testing.md` perturbation driver, which refuses a target that is modified, untracked, ignored or absent and restores - from memory; `coverage-diff.py` compares two `llvm-cov` reports by + from memory, under a `cargo` or a `unittest` runner — the latter runs + `perturb_unittest_recorder.py` in place of `-m unittest`, unittest's + own `main` recording each outcome as data, since a test can print + anything the report prints; `coverage-diff.py` compares two `llvm-cov` reports by covered count. The extension tables, grammar-pin reader, byte-level subprocess capture and manifest shape the three drift drivers share live in `drift_common.py`, diff --git a/big-code-analysis-bench/src/shapes.rs b/big-code-analysis-bench/src/shapes.rs index 27b31699b..08ad1ef19 100644 --- a/big-code-analysis-bench/src/shapes.rs +++ b/big-code-analysis-bench/src/shapes.rs @@ -3477,7 +3477,8 @@ pub const PROBES: &[Probe] = &[ documents it when any branch, at any depth, holds an \ entry. Asked afresh at every level that is `O(depth)` \ each; the walk's `FoldCache` memoises the answer per \ - conditional. Every block binds, so the reading is the \ + conditional: bypassing the memo fits 1.95 against \ + 0.92 with it. Every block binds, so the reading is the \ doc rows, one per level.", }, Probe { diff --git a/big-code-analysis-book/src/commands/nodes.md b/big-code-analysis-book/src/commands/nodes.md index 51148de57..15d9a9152 100644 --- a/big-code-analysis-book/src/commands/nodes.md +++ b/big-code-analysis-book/src/commands/nodes.md @@ -54,10 +54,9 @@ print: ``` Each line gives the node type and its `kind_id`, then two 1-based -`(row, column)` pairs: the node's first column, and the column just -past its end. A node that fits on -one row ends with its source text; one that spans several rows prints -none. +`(row, column)` pairs: where the node starts, and the position just +past its end. A node that fits on one row ends with its source text and +one space; one that spans several rows prints none. A match nested in another on the same row prints in full, as above, until the nesting passes 64 levels. From the 65th level down, a match @@ -73,7 +72,8 @@ This keeps the output linear in the size of the file: printing every level in full made a file of 4,000 nested braces print 16 MB. The `…` is not escaped, so a `…` that is in the source reads the same. Real code rarely nests past 64 levels on one row: across the serde, -pdf.js and DeepSpeech corpora the deepest is 42, under `-t all`. +pdf.js and DeepSpeech corpora the deepest is 42, in pdf.js under +`-t all`. ## Semantic filters {#semantic-filters} diff --git a/docs/development/benchmarking.md b/docs/development/benchmarking.md index f5e6caaaa..84d051ab0 100644 --- a/docs/development/benchmarking.md +++ b/docs/development/benchmarking.md @@ -231,7 +231,8 @@ Read it as follows. | `dump/tcl-nested-eval` | Tcl | depth | the export's ancestor chain under `keeps_children` (#1381, #1684) | linear | | `dump/tcl-wide-erroring-eval` | Tcl | width | the argument-list readability scan under `keeps_children`, memoised through the cache the export lends (#1686) | linear | | `count/tcl-nested-braces` | Tcl | depth | walk control for the row below: the same filter with nothing rendered | linear | -| `find/tcl-nested-braces` | Tcl | depth | the renderer `bca find` prints through: each match's connector decided without `Node::parent`, and a nested match's text printed once (#1416) | linear | +| `find/tcl-nested-braces` | Tcl | depth | the renderer `bca find` prints through: each match's connector decided without `Node::parent`, and past 64 nested levels a match's text printed once (#1416) | linear | +| `find/tcl-wide-braces-past-the-limit` | Tcl | width | the same renderer's step from one elided match to the next through `next_outside`; re-walking the siblings for each is quadratic in a level's width (#1416) | linear | | `halstead/tcl-wide-erroring-eval` | Tcl | width | the same scan under `braced_word_op_type`, reached through an iterated ancestor on the metric walk (#1686) | linear | | `ops/tcl-wide-erroring-eval` | Tcl | width | the same scan under `braced_word_op_type`, on the `ops` walk (#1686) | linear | | `count/tcl-wide-erroring-eval` | Tcl | width | the same scan under the `string` filter, on the `find` / `count` walk (#1686) | linear | @@ -628,19 +629,28 @@ asking `Node::parent`: one `O(depth)` climb per match, 98% of the single-row match's whole span, so a match nested `k` deep was printed `k` times, 16 MB of output for 8 KB of input. The renderer the CLI calls now, `render_found` in `src/output/dump.rs`, decides the -connector against the tree's root and prints `…` in place of each -nested match. `find/tcl-nested-braces` times the walk and that render +connector against the tree's root, prints each match whole through 64 +levels of single-row matches nested in one another — so ordinary +output is what it always was — and past that prints `…` in place of +each nested match, stepping from one to the next through +`next_outside`. `find/tcl-nested-braces` times the walk and that render into a sink that reads every byte; `count/tcl-nested-braces` is the walk alone. Both take `FIND_RENDER_DEPTHS`, 4 000 / 8 000 / 16 000, because the output term needs those depths to overtake the per-match cost: on `LINEAR_DEPTHS` the whole-span render fit only 1.56. +`find/tcl-wide-braces-past-the-limit` is the width half: 4 000 to +16 000 sibling words inside 66 braces, so the level eliding them is +past the limit, where a chain of one match per level cannot show a +rescan of the siblings. | Render put back | Probe that fails | Clean | Regressed | Top rung | |---|---|---|---|---| | a `Node::parent` climb per match | `find/tcl-nested-braces` | 0.99 | 2.00 | 5.3 ms → 6.2 s | -| each match prints its whole span | `find/tcl-nested-braces` | 0.99 | 1.84 | 5.3 ms → 67.0 ms | +| each match prints its whole span (the limit at `usize::MAX`) | `find/tcl-nested-braces` | 1.01 | 1.80 | 5.3 ms → 67.0 ms | +| each next match found by re-walking the siblings | `find/tcl-wide-braces-past-the-limit` | 1.01 | 1.81 | — | -`count/tcl-nested-braces` held at 0.92–0.94 under both. +`count/tcl-nested-braces` held at 0.84–0.94 under all three, and the +depth probe at 1.02 under the third. The AST export reads the same flat `ERROR`, and until [#1684][dump-cursor] it did so by index: `Node::child` and `Node::field_name_for_child` both diff --git a/docs/development/mutation_testing.md b/docs/development/mutation_testing.md index 7a82dea2f..7355c1514 100644 --- a/docs/development/mutation_testing.md +++ b/docs/development/mutation_testing.md @@ -102,7 +102,9 @@ lists of a `role_table!` invocation and the `under [...]` / `not_under [...]` parent lists on them — so a gate `fn` moved onto a row as such a list leaves this selection, as Python's `under_case_clause`, Groovy's `not_in_an_import` and Java's -`not_a_class_literal` and `not_in_a_directive` did under #1794 — and +`not_a_class_literal` and `not_in_a_directive` did under #1794 (the +TypeScript family's `under_enum_body` moved too, but a fragment macro +emitted it, so it was never in the selection) — and equally every gate a macro *emits* — the thirteen `else_if_parent_clause_gate!` / `else_if_prev_sibling_gate!` invocations, and the gates the From f6e0ccf3624be645f478c18a461b886d3c6e5e2b Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Fri, 6 Nov 2026 16:45:12 -0800 Subject: [PATCH 25/25] fix(security): bump actix-http and actix-web past four RUSTSEC advisories MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit cargo-deny check advisories was red on main and on this branch alike: RUSTSEC-2026-0446, -0448 and -0455 against actix-http 3.19.0 (request smuggling through malformed chunked trailers; unbounded decompression exhausting memory and CPU; large-window Brotli bodies bypassing the decompression limits) and RUSTSEC-2026-0447 against actix-web 4.18.1 (compressed request bodies exhausting memory before extractor limits apply). `cargo update -p actix-http -p actix-web` moves them to 3.20.3 and 4.18.2; brotli 9.0.0 → 9.1.1 and brotli-decompressor 6.0.1 → 6.3.0 move with them and base64 0.22.1 leaves the lockfile. No other package version or checksum changes. utils/check-deny-manifests.sh advisories bans licenses sources, with cargo-deny 0.20.2: all eight manifests ok. The web crate's 184 tests and its lockfile test pass; check-excluded-manifests is OK. --- CHANGELOG.md | 12 ++++++++++++ Cargo.lock | 31 +++++++++++++------------------ 2 files changed, 25 insertions(+), 18 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f7ae1fec4..a41f15f59 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1746,6 +1746,18 @@ for historical reference. ### Security +- Cleared RUSTSEC-2026-0446, -0448 and -0455 (`actix-http` 3.19.0: + request smuggling through malformed chunked trailers, and two + unbounded-decompression memory exhaustions) and RUSTSEC-2026-0447 + (`actix-web` 4.18.1: compressed request bodies exhausting memory + before extractor limits apply) by moving `actix-http` 3.19.0 → + 3.20.3 and `actix-web` 4.18.1 → 4.18.2. `brotli` 9.0.0 → 9.1.1 and + `brotli-decompressor` 6.0.1 → 6.3.0 moved with them, and `base64` + 0.22.1 left the lockfile; no other package version or checksum did. + All four were red under `cargo-deny check advisories` on `main`, + where the `deny` job and the weekly run had reported them since + their publication; `utils/check-deny-manifests.sh` now passes all + four checks on all eight lockfiles. - Cleared GHSA-q54r-jf2p-rfr2 (Dependabot alert 90, high) by moving `gix` 0.89.0 → 0.90.0, with the rest of the gitoxide family advancing to its latest compatible release in step: 52 gitoxide diff --git a/Cargo.lock b/Cargo.lock index 7299c39e5..a5f59f6c9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -21,16 +21,17 @@ dependencies = [ [[package]] name = "actix-http" -version = "3.19.0" +version = "3.20.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b796ba3c974e5133f6ca1a2c4e97c5941ea1a46d202df83344afaa18219f1a62" +checksum = "cd4ef186188fed2d4f8177d712ad623c751c6e84f45b31da694cc53f483f320b" dependencies = [ "actix-codec", "actix-service", "actix-utils", - "base64 0.22.1", + "base64", "bitflags 2.13.2", "brotli", + "brotli-decompressor", "bytes", "bytestring", "derive_more", @@ -131,9 +132,9 @@ dependencies = [ [[package]] name = "actix-web" -version = "4.18.1" +version = "4.18.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "81f8da0d2ae4200dde8773d72ba47a65c220b251ba7b9248db5bd263c247e959" +checksum = "697d10a06f7a550791dcb963e3090aa5c65c4d94c029114814a4bd652f30f0b4" dependencies = [ "actix-codec", "actix-http", @@ -382,12 +383,6 @@ dependencies = [ "pkg-config", ] -[[package]] -name = "base64" -version = "0.22.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" - [[package]] name = "base64" version = "0.23.1" @@ -621,9 +616,9 @@ checksum = "dc0b364ead1874514c8c2855ab558056ebfeb775653e7ae45ff72f28f8f3166c" [[package]] name = "brotli" -version = "9.0.0" +version = "9.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f8b851b75c23ca7873623d612fe49bd1989aeb03d08fb9432187eb253d3d4c6b" +checksum = "627b7cfb0578f0eafce087a90fcd40add1231900b69e4d4de2d456260a4f5d81" dependencies = [ "alloc-no-stdlib", "alloc-stdlib", @@ -632,9 +627,9 @@ dependencies = [ [[package]] name = "brotli-decompressor" -version = "6.0.1" +version = "6.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "941cd9bd4ddab83cb46fa5a2d428f1c857b24ac78cb876cf7beb710840934bd7" +checksum = "97d9071e5b45944c5a9c06baf13a7a65ffa2c88c204015967852c90869692c05" dependencies = [ "alloc-no-stdlib", "alloc-stdlib", @@ -2537,7 +2532,7 @@ version = "0.1.21" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ddc03d96684f9226b8a787cdb71488417b53ab5ea8fdb1dac946cb9431cc8bff" dependencies = [ - "base64 0.23.1", + "base64", "bytes", "futures-channel", "futures-util", @@ -3650,7 +3645,7 @@ version = "0.13.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "16a1cfa75cc186dd73d5818e510e042e40927bccc9c236b061cea97e1eb08029" dependencies = [ - "base64 0.23.1", + "base64", "bytes", "futures-channel", "futures-core", @@ -3881,7 +3876,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a253edfdea34032da21af84e16fcc94f4c7a6ba237f9f3bc2dbf43cea8535c44" dependencies = [ "annotate-snippets", - "base64 0.23.1", + "base64", "encoding_rs_io", "granit-parser", "nohash-hasher",