diff --git a/.bca-baseline.toml b/.bca-baseline.toml index ac8118ed8..ab0959a82 100644 --- a/.bca-baseline.toml +++ b/.bca-baseline.toml @@ -845,13 +845,7 @@ value = 7.0 path = "big-code-analysis-py/src/node.rs" qualified = "PyNode" metric = "nom" -value = 52.0 - -[[entry]] -path = "big-code-analysis-py/src/node.rs" -qualified = "PyNode" -metric = "wmc" -value = 59.0 +value = 47.0 [[entry]] path = "big-code-analysis-py/src/node.rs" @@ -923,7 +917,7 @@ value = 48620.735506493904 path = "big-code-analysis-web/src/web/server.rs" qualified = "run_parse" metric = "halstead.effort" -value = 84151.62410156948 +value = 87801.57184376812 [[entry]] path = "big-code-analysis-web/src/web/server.rs" diff --git a/.role-coverage-baseline.txt b/.role-coverage-baseline.txt index bbb23f949..e4868f7d9 100644 --- a/.role-coverage-baseline.txt +++ b/.role-coverage-baseline.txt @@ -517,7 +517,7 @@ 361 named visible 'statement_identifier' 362 named visible 'type_identifier' -[Ccomment tree-sitter-ccomment 2.5.2] +[Ccomment tree-sitter-ccomment 2.6.0] 1 named visible 'nothing' 2 named visible 'preproc_continuation_line' 3 named visible 'preproc_line' @@ -2823,7 +2823,7 @@ 141 anon hidden '_expression_list_repeat1' 142 anon hidden '_field_list_repeat1' -[Mozcpp tree-sitter-mozcpp 2.5.2] +[Mozcpp tree-sitter-mozcpp 2.6.0] 1 named visible 'identifier' 2 anon visible '#include' 3 anon hidden 'preproc_include_token2' @@ -3325,7 +3325,7 @@ 636 named visible 'statement_identifier' 637 named visible 'type_identifier' -[Mozjs tree-sitter-mozjs 2.5.2] +[Mozjs tree-sitter-mozjs 2.6.0] 1 named visible 'identifier' 2 named visible 'hash_bang_line' 3 anon visible 'export' @@ -4628,7 +4628,7 @@ 432 anon hidden 'nowdoc_body_repeat1' 433 named visible 'operation' -[Preproc tree-sitter-preproc 2.5.2] +[Preproc tree-sitter-preproc 2.6.0] 1 named visible 'identifier' 2 named visible 'nothing' 3 named visible 'preproc_continuation_line' @@ -5414,7 +5414,7 @@ 353 named visible 'shorthand_field_identifier' 354 named visible 'type_identifier' -[Tcl tree-sitter-tcl 2.5.2] +[Tcl tree-sitter-tcl 2.6.0] 1 named visible 'simple_word' 2 anon visible '\n' 3 anon visible ';' diff --git a/.role-coverage-observed.txt b/.role-coverage-observed.txt index c90963453..ecf4e7827 100644 --- a/.role-coverage-observed.txt +++ b/.role-coverage-observed.txt @@ -2,7 +2,7 @@ # emitted, with provenance (#1692). Written by # `check-role-coverage.py --observe`; informational for the ratchet. # A kind absent here is "unobserved", never "unreachable". -observer bca 2.5.2 +observer bca 2.6.0 corpus DeepSpeech aa1d28530d531d0d92289bf5f11a49fe516fdc86 corpus pdf.js 65c4a4b3fe81b20cd262193c55a6f4519362184c corpus serde d6de911855d1cc0ad13f87503a79d40dc4490442 @@ -205,7 +205,7 @@ corpus big-code-analysis-output 5fbe03bf005b9b03a1928273faa477a9c1be5ed7 263 264 -[Mozjs tree-sitter-mozjs 2.5.2 sampled attempted=388 parsed=388 failed=0] +[Mozjs tree-sitter-mozjs 2.6.0 sampled attempted=388 parsed=388 failed=0] 1 3 4 @@ -1005,7 +1005,7 @@ corpus big-code-analysis-output 5fbe03bf005b9b03a1928273faa477a9c1be5ed7 354 65535 -[Tcl tree-sitter-tcl 2.5.2 sampled attempted=2 parsed=2 failed=0] +[Tcl tree-sitter-tcl 2.6.0 sampled attempted=2 parsed=2 failed=0] 1 3 6 @@ -1459,7 +1459,7 @@ corpus big-code-analysis-output 5fbe03bf005b9b03a1928273faa477a9c1be5ed7 542 65535 -[Mozcpp tree-sitter-mozcpp 2.5.2 sampled attempted=1048 parsed=1048 failed=0] +[Mozcpp tree-sitter-mozcpp 2.6.0 sampled attempted=1048 parsed=1048 failed=0] 1 2 4 @@ -2645,9 +2645,9 @@ corpus big-code-analysis-output 5fbe03bf005b9b03a1928273faa477a9c1be5ed7 253 65535 -[Ccomment tree-sitter-ccomment 2.5.2 not-sampled attempted=0 parsed=0 failed=0] +[Ccomment tree-sitter-ccomment 2.6.0 not-sampled attempted=0 parsed=0 failed=0] -[Preproc tree-sitter-preproc 2.5.2 not-sampled attempted=0 parsed=0 failed=0] +[Preproc tree-sitter-preproc 2.6.0 not-sampled attempted=0 parsed=0 failed=0] [Perl tree-sitter-perl 1.1.2 sampled attempted=1 parsed=1 failed=0] 1 diff --git a/CHANGELOG.md b/CHANGELOG.md index 4b249e150..9d0745346 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -24,6 +24,18 @@ for historical reference. ## [Unreleased] +### Changed + +- **(breaking), deferred to the next major (3.0):** the MI of a space + with no code will serialize as `null` (an omitted key in TOML) + instead of `0.0`. Throughout `2.x` the serialized value stays `0.0`; + use `mi::Stats::is_empty()` to tell it apart. The change retires the + dict-side copy of that predicate in the Python bindings + (`big-code-analysis-py/src/sarif.rs`, `mi_is_empty`), which exists + only because the wire cannot yet say "empty". (#1621) + +## [2.6.0] - 2026-11-17 + ### Added - **`Node::is_extra()`** (#1871): whether tree-sitter marks a node as @@ -223,13 +235,6 @@ for historical reference. The `.deb` control fields and file lists and the RPM file lists and file flags are unchanged. -- **(breaking), deferred to the next major (3.0):** the MI of a space - with no code will serialize as `null` (an omitted key in TOML) - instead of `0.0`. Throughout `2.x` the serialized value stays `0.0`; - use `mi::Stats::is_empty()` to tell it apart. The change retires the - dict-side copy of that predicate in the Python bindings - (`big-code-analysis-py/src/sarif.rs`, `mi_is_empty`), which exists - only because the wire cannot yet say "empty". (#1621) - **Bumped the `dekobon-tree-sitter-groovy` grammar pin to `=0.5.0`.** Releases 0.4.0 and 0.5.0 close a set of parse gaps ([tree-sitter-groovy#49](https://github.com/dekobon/tree-sitter-groovy/issues/49), @@ -551,6 +556,27 @@ for historical reference. reached the same recursion and aborted where the 0.5.0 pin answered. The three checks step through the assignments in a loop. +- **CSV output no longer overflows the stack on deeply nested + functions** (#1936). The writer called itself once per nested space, + so `bca metrics -O csv` on a few tens of thousands of nested closures, + such as JavaScript's `x = ()=>()=>…1;`, aborted the process (from + about 43,000 levels on an x86_64 release build, 32,000 on aarch64). + The public `write_csv` and `write_csv_aggregate` aborted the same way. + `bca-web` never emits CSV. The rows now come from an explicit stack, + in the same depth-first order. + +- **The Python `Node.parent`, sibling and `field_name` getters no + longer kill the interpreter on a deep zero-width node** (#1937). A + `MISSING` node is zero-width, and tree-sitter's parent lookup calls + itself once per tree level above one, so asking for the parent, a + sibling or the field name of one some 15,000 levels deep was a + segmentation fault, in 2.5.1 too. The + bindings now find a zero-width node's parent by walking down from the + root with a cursor, entering only the nodes that hold its position, + and read its siblings off that parent; a node with width keeps + tree-sitter's own lookup. The Rust `Node::parent` cannot reach the + root that way and still makes the call (#1941). + - **`npm` and `npa` read the visibility of interface members** (#1880). An interface member used to count as public whatever it declared; only a C# interface field already read `private` and `protected`. @@ -583,6 +609,22 @@ for historical reference. climb checked, so it is no longer asked. At 16,000 levels a release build goes from 0.92 s to 0.10 s. Values are unchanged. +- **The AST export is linear in a Tcl `expr`'s nested parentheses** + (#1938). `Ast::dump`, `POST /v1/ast` and the Python `Ast.dump` read + each child's grammar field through a cursor, which climbs every hidden + grammar level between the child and its visible parent. Tcl and + iRules fold each parenthesis of `expr {((…(1)…))}` into one more + hidden level under a single flat node, so the export took time + quadratic in the nesting: 0.6 s at 16,000 levels, and about 40 s for a + 200 KB request. A node 32 or more children wide is now first asked + whether any child has a field, which its grammar answers without + visiting the children. At 16,000 levels the export goes from 623 ms + to 10 ms. The exported tree is unchanged, which a comparison of 46,215 + exports over the test corpora confirms. An `ERROR` node has no + production to answer from, so every child's field is still read + there, and the same `expr` with its closing brace missing still + exports in quadratic time (#1942). + - **`cognitive::Stats` and `nexits::Stats` print a well-formed `Display` line** (#1736). The cognitive line printed the space's own score under `sum`, where the JSON `sum` field and every sibling @@ -948,6 +990,68 @@ for historical reference. deliberate #709 accessor split); and `Comments` said "lines that are entirely comment" while `cloc()` counts trailing comments too. +### Security + +- Closed two remotely-triggerable process aborts in `npa` (#1934). + A Python class-level chained assignment `a = a = … = 1` a few + thousand links long, or an Elixir `defstruct` list nested about ten + thousand brackets deep, overflowed the thread stack: the Python reader + recursed once per link, and the Elixir field count once per bracket. + The depth that aborts varies with the build and with the stack of the + thread running the analysis. Release builds of the code just before + the fix aborted from about 5,600 links and 9,900 levels on x86_64 + Linux, and from about 6,400 and 9,200 on aarch64 Linux. + + Every interface that computes `npa` was affected: the Rust API + (`analyze`, or `Ast::metrics` with `npa` selected), the Python + bindings, `bca metrics`, `bca check` with an `npa` threshold, + `bca report`, and `POST /v1/metrics`. A stack overflow is not a + catchable panic: the Rust binaries abort with `SIGABRT`, and the + Python interpreter dies of a segmentation fault. So one + `POST /v1/metrics` under 30 KB, far inside the 4 MiB body cap, took + `bca-web` down with every request in flight. The Elixir count has + recursed since 1.0.0, the Python reader since 2.0.0. The Python reader + now steps along the chain in a loop and the Elixir count keeps its + own stack; a test runs each at 20,000 levels on a 512 KiB stack. + +- **A timed-out `bca-web` request no longer holds a server thread + until its parse finishes** (#1939). A request past its deadline got + `504`, but its analysis ran on in the background, and once + `max(threads × 2, 4)` of those were running, every new request got + `503`. A grammar that parses some input in superlinear time made that + a denial of service: the pinned Perl grammar takes minutes over a few + tens of KB of `-and =>` pairs (#1940), so a handful of small requests + kept the server out of service for that long. A flag is now set at + the deadline, or earlier if actix drops the request's handler, as it + does when the connection is reset before the client has closed its + sending side; the parse checks it every hundred parse operations and + stops. An ordinary close (FIN) does not drop the handler: HTTP/1 lets + a client half-close and still read its response, so actix reads + nothing more from the connection, not even a reset that follows, and + that request's work runs on until it answers or its deadline, if any. + A release server with one orphan slot and a 2 s deadline, sent 8,000 + such pairs, answered `503` to every later request for as long as it + was asked (14 s); it now answers `200` half a second after the `504`. + The AST export checks the flag once per node: an unclosed nested Tcl + `expr` parses at once but exports in quadratic time (#1942), and a + debug build's export of 100,000 parentheses ran for 24 s past a 0.5 s + deadline. It now stops at the deadline. The other walks after the + parse are not interrupted: they are linear, which `make bench-scaling` + gates. + +- Cleared RUSTSEC-2026-0552, -0553 and -0554 (`actix-http` 3.21.0: a + bare LF in chunked trailers could consume pipelined requests or stall + body decoding; malformed quoted chunk extensions could end an HTTP/1.1 + request body early; partial requests on a keep-alive connection could + bypass the request header timeout) by moving `actix-http` 3.21.0 → + 3.22.0. All three reach `bca-web` only. No other package version or + checksum moved; five entries (`errno`, `rustix`, + `rustls-platform-verifier`, `tempfile`, `winapi-util`) had a + dependency edge re-pointed between + two `windows-sys` / `getrandom` versions the lockfile already + carried. `utils/check-deny-manifests.sh` passes all four checks on all + eight lockfiles. + ## [2.5.1] - 2026-11-06 2.5.0 reached PyPI only: its release run failed a Windows smoke test @@ -13842,7 +13946,8 @@ Halstead scores, and MI stay `f64`. No value changes — only the type. [Unreleased] link to `vX.Y.Z...HEAD` and add a `[X.Y.Z]:` line pointing at `...vX.Y.Z`. --> -[Unreleased]: https://github.com/dekobon/big-code-analysis/compare/v2.5.1...HEAD +[Unreleased]: https://github.com/dekobon/big-code-analysis/compare/v2.6.0...HEAD +[2.6.0]: https://github.com/dekobon/big-code-analysis/compare/v2.5.1...v2.6.0 [2.5.1]: https://github.com/dekobon/big-code-analysis/compare/v2.5.0...v2.5.1 [2.5.0]: https://github.com/dekobon/big-code-analysis/compare/v2.4.0...v2.5.0 [2.4.0]: https://github.com/dekobon/big-code-analysis/compare/v2.3.1...v2.4.0 diff --git a/Cargo.lock b/Cargo.lock index 0982f4657..675028811 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -21,9 +21,9 @@ dependencies = [ [[package]] name = "actix-http" -version = "3.21.0" +version = "3.22.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3422032be73eeb15bafdb64086386385875b653eb418a80241d1f98473e86ea6" +checksum = "50f98f47b03911915aa3f0b856749aa3d3915033afabb295ab6ac5ff3b8bd5c1" dependencies = [ "actix-codec", "actix-service", @@ -400,7 +400,7 @@ checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" [[package]] name = "bca-tree-sitter-ccomment" -version = "2.5.2" +version = "2.6.0" dependencies = [ "cc", "tree-sitter-language", @@ -408,7 +408,7 @@ dependencies = [ [[package]] name = "bca-tree-sitter-mozcpp" -version = "2.5.2" +version = "2.6.0" dependencies = [ "cc", "tree-sitter-cpp", @@ -417,7 +417,7 @@ dependencies = [ [[package]] name = "bca-tree-sitter-mozjs" -version = "2.5.2" +version = "2.6.0" dependencies = [ "cc", "tree-sitter-javascript", @@ -426,7 +426,7 @@ dependencies = [ [[package]] name = "bca-tree-sitter-preproc" -version = "2.5.2" +version = "2.6.0" dependencies = [ "cc", "tree-sitter-language", @@ -434,7 +434,7 @@ dependencies = [ [[package]] name = "bca-tree-sitter-tcl" -version = "2.5.2" +version = "2.6.0" dependencies = [ "cc", "tree-sitter-language", @@ -442,7 +442,7 @@ dependencies = [ [[package]] name = "big-code-analysis" -version = "2.5.2" +version = "2.6.0" dependencies = [ "big-code-analysis-ast", "bstr", @@ -469,7 +469,7 @@ dependencies = [ [[package]] name = "big-code-analysis-ast" -version = "2.5.2" +version = "2.6.0" dependencies = [ "aho-corasick", "bca-tree-sitter-ccomment", @@ -510,7 +510,7 @@ dependencies = [ [[package]] name = "big-code-analysis-bench" -version = "2.5.2" +version = "2.6.0" dependencies = [ "big-code-analysis", "big-code-analysis-ast", @@ -521,7 +521,7 @@ dependencies = [ [[package]] name = "big-code-analysis-cli" -version = "2.5.2" +version = "2.6.0" dependencies = [ "assert_cmd", "big-code-analysis", @@ -545,7 +545,7 @@ dependencies = [ [[package]] name = "big-code-analysis-py" -version = "2.5.2" +version = "2.6.0" dependencies = [ "big-code-analysis", "globset", @@ -559,7 +559,7 @@ dependencies = [ [[package]] name = "big-code-analysis-web" -version = "2.5.2" +version = "2.6.0" dependencies = [ "actix-rt", "actix-web", @@ -1250,7 +1250,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -3744,7 +3744,7 @@ dependencies = [ "errno", "libc", "linux-raw-sys", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -3800,7 +3800,7 @@ dependencies = [ "security-framework", "security-framework-sys", "webpki-root-certs", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -4185,10 +4185,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" dependencies = [ "fastrand", - "getrandom 0.4.3", + "getrandom 0.3.4", "once_cell", "rustix", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -5013,7 +5013,7 @@ version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" dependencies = [ - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -5130,7 +5130,7 @@ checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" [[package]] name = "xtask" -version = "2.5.2" +version = "2.6.0" dependencies = [ "big-code-analysis-cli", "big-code-analysis-web", diff --git a/Cargo.toml b/Cargo.toml index 12e463f3b..e813068c9 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -47,7 +47,7 @@ exclude = [ ] [workspace.package] -version = "2.5.2" +version = "2.6.0" edition = "2024" rust-version = "1.94" license = "MPL-2.0" @@ -108,11 +108,11 @@ tree-sitter-c = "=0.24.2" # Rationale and the rejected alternatives live on the umbrella # issue (dekobon/big-code-analysis#149); the operational details # (publish order, first-bootstrap workflow) live in `RELEASING.md`. -tree-sitter-ccomment = { package = "bca-tree-sitter-ccomment", path = "./tree-sitter-ccomment", version = "=2.5.2" } -tree-sitter-mozcpp = { package = "bca-tree-sitter-mozcpp", path = "./tree-sitter-mozcpp", version = "=2.5.2" } -tree-sitter-mozjs = { package = "bca-tree-sitter-mozjs", path = "./tree-sitter-mozjs", version = "=2.5.2" } -tree-sitter-preproc = { package = "bca-tree-sitter-preproc", path = "./tree-sitter-preproc", version = "=2.5.2" } -tree-sitter-tcl = { package = "bca-tree-sitter-tcl", path = "./tree-sitter-tcl", version = "=2.5.2" } +tree-sitter-ccomment = { package = "bca-tree-sitter-ccomment", path = "./tree-sitter-ccomment", version = "=2.6.0" } +tree-sitter-mozcpp = { package = "bca-tree-sitter-mozcpp", path = "./tree-sitter-mozcpp", version = "=2.6.0" } +tree-sitter-mozjs = { package = "bca-tree-sitter-mozjs", path = "./tree-sitter-mozjs", version = "=2.6.0" } +tree-sitter-preproc = { package = "bca-tree-sitter-preproc", path = "./tree-sitter-preproc", version = "=2.6.0" } +tree-sitter-tcl = { package = "bca-tree-sitter-tcl", path = "./tree-sitter-tcl", version = "=2.6.0" } # PyO3 powers the `big-code-analysis-py` cdylib. Pinned to a major # series; bumping is a deliberate, separate change because the Bound @@ -262,7 +262,7 @@ tree-sitter.workspace = true # the C preprocessor pass. Version-locked like the vendored grammar leaves; # the per-language features below forward to it, so a `--features rust` # build of this crate still links exactly one grammar. -big-code-analysis-ast = { path = "big-code-analysis-ast", version = "=2.5.2", default-features = false } +big-code-analysis-ast = { path = "big-code-analysis-ast", version = "=2.6.0", default-features = false } # Per-language Cargo features. `default = ["all-languages"]` keeps the # library's historical "every grammar compiled in" behaviour for @@ -373,7 +373,7 @@ workspace = true # `javascript` was off while the parse layer's was on. The language # features come from the normal dependency above; this entry adds only # `test-support`. -big-code-analysis-ast = { path = "big-code-analysis-ast", version = "=2.5.2", default-features = false, features = [ +big-code-analysis-ast = { path = "big-code-analysis-ast", version = "=2.6.0", default-features = false, features = [ "test-support", ] } insta = { version = "1.49.0", features = ["yaml", "json", "redactions"] } diff --git a/RELEASING.md b/RELEASING.md index 3bb882b89..110292e8f 100644 --- a/RELEASING.md +++ b/RELEASING.md @@ -216,6 +216,51 @@ category of to the new version, with the `BCA_SHA256` values taken from the release's `SHA256SUMS` asset. +### Advisories for a security release {#security-advisories} + +A release whose `CHANGELOG.md` section has a `### Security` entry for +a vulnerability in this project's own code also owes the advisories +that [`SECURITY.md`](SECURITY.md) promises. File them only after +crates.io and PyPI both carry the release: an advisory tells its +readers which version to install, so that version must resolve. + +Each vulnerability gets its own advisories, and the packages they name +depend on where the vulnerable code lives: + +- In the library (a metric, the parser, an output writer): the + `big-code-analysis` crate and both PyPI packages, `big-code-analysis` + and `big-code-analysis-cli`, which ship it. +- In `bca-web` alone (request handling, timeouts): the + `big-code-analysis-web` crate. Neither wheel ships the server. + +Give each package the first version that shipped the defect. The +release archives also carry `bca` and `bca-web` binaries, which no +advisory ecosystem covers; name them in the advisory text. + +1. **Draft a GitHub advisory.** Under **Security → Advisories → New + draft security advisory**, list the affected packages, `Rust` for a + crate and `pip` for a PyPI package. RustSec reaches only Rust + dependants; Dependabot reads the + [GitHub Advisory Database](https://github.com/advisories) for the + Python ones. A draft can request a CVE from GitHub; do that where + `SECURITY.md`'s "where appropriate" applies. +2. **File the RustSec advisory.** For each affected crate, open a pull + request against + [rustsec/advisory-db](https://github.com/rustsec/advisory-db) that + adds `crates//RUSTSEC-0000-0000.md`, filled in from the TOML + template in that repository's README; the RustSec maintainers assign + the number. Set `patched` to the release (`[">= X.Y.Z"]`), + `unaffected` to the versions before the defect shipped, and + `aliases` to the GHSA (and CVE) id from step 1. A crash or a stall + that crafted input triggers takes the `denial-of-service` category. + This is the advisory `cargo audit` and `cargo deny check advisories` + report to dependants. +3. **Publish the GitHub advisory**, which adds it to the database. + +A dependency advisory that a lockfile bump clears, such as the +`RUSTSEC-…` entries in earlier `### Security` sections, needs neither +step: the upstream advisory already exists. + ## Bumping the version The release pipeline is strict about version parity: the preflight job diff --git a/SECURITY.md b/SECURITY.md index 9bd213675..f60316380 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -37,7 +37,9 @@ We follow **coordinated disclosure**. Once a fix is available: crates.io publication gate described in [`RELEASING.md`](RELEASING.md)). 2. We will publish a [RustSec advisory](https://rustsec.org/) with a - CVE identifier where appropriate. + CVE identifier where appropriate, and a GitHub advisory that names + every affected package, PyPI ones included (see + [`RELEASING.md`](RELEASING.md#security-advisories)). 3. We will credit the reporter in the advisory unless they prefer to remain anonymous. diff --git a/STABILITY.md b/STABILITY.md index ae40e6913..9b661f465 100644 --- a/STABILITY.md +++ b/STABILITY.md @@ -1,6 +1,6 @@ # Stability policy -`big-code-analysis` is on the `2.x` line (currently `2.5.1`). This +`big-code-analysis` is on the `2.x` line (currently `2.6.0`). This document is the public-API stability contract for library consumers, CLI integrators, and the Python and REST users: what is stable, what counts as an additive change, what is reserved for a major bump, and @@ -32,7 +32,7 @@ pin bump (any [tree-sitter](https://tree-sitter.github.io/tree-sitter/) regression fix in a metric definition is by definition a value change but does not break the API surface. Callers who need bit-for-bit reproducibility should pin to an exact version -(`big-code-analysis = "= 2.5.1"`) and store that version alongside +(`big-code-analysis = "= 2.6.0"`) and store that version alongside their results; see [What is stable in value](#what-is-stable-in-value) below. @@ -582,7 +582,7 @@ versions, even within `2.x`.** Concretely: This is the one deliberate carve-out in the `2.x` contract. The *shape* of the data is stable; the *numbers in the cells* are not. If you need to compare metric runs across time, pin to an exact -version (`big-code-analysis = "= 2.5.1"`) and store the version +version (`big-code-analysis = "= 2.6.0"`) and store the version alongside the results. ### Float precision and non-finite values diff --git a/big-code-analysis-ast/src/ast.rs b/big-code-analysis-ast/src/ast.rs index f6bfa0271..b2fe25125 100644 --- a/big-code-analysis-ast/src/ast.rs +++ b/big-code-analysis-ast/src/ast.rs @@ -278,15 +278,54 @@ struct Frame<'a> { field: Option<&'static str>, children: Vec, next_child: usize, + /// Whether a child of `node` may carry a field, so that reading + /// each child's is worth its cost. + fields: bool, +} + +/// Child count from which a frame asks [`has_field_child`] before its +/// children's fields are read one by one. +/// +/// A child's field read climbs the hidden grammar levels between it and +/// its visible parent, and every hidden level consumes input that lands +/// among that parent's children, so a narrow node bounds the climb. A +/// wide one need not: each parenthesis of a Tcl `expr` adds a hidden +/// level under one flat node, which made reading every child's field +/// quadratic in the count (#1938). Below this width the probe's scan of +/// the grammar's field ids would cost more than it saves. +const FIELD_PROBE_WIDTH: usize = 32; + +/// Whether some child of `node` carries a field name, through any hidden +/// grammar levels between them. +/// +/// `ts_node_child_by_field_id` reads the node's own production field +/// map, which lists a hidden child's fields as inherited entries, and +/// returns as soon as the sorted map shows it lacks the id. So this costs +/// one scan of that small map per field the grammar names, however wide +/// the node is. +/// +/// An `ERROR` node has no production of its own, so its map is empty even +/// where a hidden subtree recovery parked under it hands its visible +/// children a field (a cursor reads `operators` on a Python `==` there). +/// It always answers `true`. +fn has_field_child(node: &crate::Node<'_>) -> bool { + if node.is_error() { + return true; + } + (1..=node.as_tree_sitter().language().field_count()) + .filter_map(|id| u16::try_from(id).ok()) + .any(|id| node.child_by_field_id(id).is_some()) } impl<'a> Frame<'a> { fn new(node: crate::Node<'a>, field: Option<&'static str>) -> Self { + let width = node.child_count(); Self { node, field, - children: Vec::with_capacity(node.child_count()), + children: Vec::with_capacity(width), next_child: 0, + fields: width < FIELD_PROBE_WIDTH || has_field_child(&node), } } } @@ -355,10 +394,35 @@ impl<'a, 'code> Export<'a, 'code> { self.chain.push(child); } + /// Whether the node on top of the stack may have a child with a + /// field, so that a child's field is worth reading. + fn children_may_have_fields(&self) -> bool { + self.stack.last().is_some_and(|parent| parent.fields) + } + + /// Descends into the node `cursor` sits on, reading its field only + /// where its parent's children may carry one. + fn enter_at(&mut self, cursor: &crate::node::Cursor<'a>) { + let field = if self.children_may_have_fields() { + cursor.field_name() + } else { + None + }; + self.enter(cursor.node(), field); + } + /// Exports the node on top of the stack — every child of it has /// been exported by now — and attaches it to its parent's frame. - /// Breaks with the export once the node finished was the root. + /// Breaks with the export once the node finished was the root, and + /// with no tree once the [`ParseCancel`](crate::cancel::ParseCancel) + /// installed on this thread is cancelled: a wide `ERROR` node still + /// has every child's field read, which is quadratic over deep hidden + /// nesting (#1942), and a `bca-web` request past its deadline must + /// not keep its thread for that long. fn finish(&mut self) -> ControlFlow> { + if crate::cancel::requested() { + return ControlFlow::Break(None); + } let frame = self .stack .pop() @@ -392,7 +456,12 @@ impl<'a, 'code> Export<'a, 'code> { /// node and its visible parent: `O(log n)` under a balanced `repeat()`, /// `O(1)` under a flat node. The enumeration is therefore `O(n log n)` /// over a wide balanced list and `O(n)` over a flat one, never -/// quadratic. Indexing the children instead is quadratic on a flat node +/// quadratic. The field read is not that cheap everywhere: under a flat +/// node whose children sit in *nested* hidden rules, such as a Tcl +/// `expr`'s parentheses, it climbs one more level per child, so a wide +/// node is first asked whether any child has a field at all +/// ([`FIELD_PROBE_WIDTH`], #1938; `dump/tcl-expr-parens` prices it). +/// Indexing the children instead is quadratic on a flat node /// — see [`build_indexed`] — and that difference is the whole reason /// there are two builders (#1684). What the alterator does per node is /// priced separately: `keeps_children` reads the ancestor chain, which @@ -414,14 +483,14 @@ fn build_cursor(parser: &T, span: bool, comment: bool) -> Option let mut cursor = root.cursor(); loop { while cursor.goto_first_child() { - export.enter(cursor.node(), cursor.field_name()); + export.enter_at(&cursor); } loop { if let ControlFlow::Break(root) = export.finish::() { return root; } if cursor.goto_next_sibling() { - export.enter(cursor.node(), cursor.field_name()); + export.enter_at(&cursor); break; } // The root frame is finished above before this can fail, @@ -463,9 +532,14 @@ fn build_indexed(parser: &T, span: bool, comment: bool) -> Optio .node .child(idx) .expect("stack invariant: idx < child_count so the child exists"); - let field = frame.node.field_name_for_child( - u32::try_from(idx).expect("invariant: tree-sitter caps child indices at u32::MAX"), - ); + let field = if frame.fields { + frame.node.field_name_for_child( + u32::try_from(idx) + .expect("invariant: tree-sitter caps child indices at u32::MAX"), + ) + } else { + None + }; export.enter(child, field); } else if let ControlFlow::Break(root) = export.finish::() { return root; @@ -630,6 +704,112 @@ mod tests { parent.children.iter().find(|c| c.field_name == Some(field)) } + /// A node `FIELD_PROBE_WIDTH` children wide or more is asked whether + /// any child has a field before its children's fields are read, and + /// one whose children do must still report each (#1938). A tuple + /// struct's `ordered_field_declaration_list` names every element type + /// `type`. expected: 40 `primitive_type` children with field `type`, + /// and none of the 41 punctuation children with a field. + #[cfg(feature = "rust")] + #[test] + fn a_wide_node_with_fields_keeps_them() { + const ELEMENTS: usize = 40; + const { + assert!( + 2 * ELEMENTS + 1 >= FIELD_PROBE_WIDTH, + "the list must be wide enough to probe" + ); + } + let code = format!("struct T({});\n", vec!["i32"; ELEMENTS].join(", ")); + for_each_strategy::(code.as_bytes(), "test.rs", false, |name, root| { + let list = + find_first(root, "ordered_field_declaration_list").expect("a tuple struct body"); + let typed = list + .children + .iter() + .filter(|c| c.field_name == Some("type")) + .count(); + assert_eq!(typed, ELEMENTS, "{name}"); + assert!( + list.children + .iter() + .all(|c| (c.r#type == "primitive_type") == (c.field_name == Some("type"))), + "{name}" + ); + }); + } + + /// An `ERROR` node has no production of its own, so the field probe + /// finds nothing on it, yet the hidden subtrees recovery leaves under + /// it still give its children fields (#1938). An unfinished tuple + /// struct recovers into one `ERROR` node whose element types keep + /// their `type` field; the export must keep every one whichever side + /// of the probe width the node falls. expected: the counts + /// `field_name_for_child` reads off the raw node, one per element but + /// the first, which recovery leaves without a field. + #[cfg(feature = "rust")] + #[test] + fn a_wide_error_node_keeps_its_childrens_fields() { + for (elements, typed) in [(10, 9), (20, 19)] { + let code = format!("struct T({}", "i32, ".repeat(elements)); + let path = PathBuf::from("test.rs"); + let parser = crate::RustParser::new(code.as_bytes().to_vec(), &path, None); + let error = parser + .root() + .preorder() + .find(crate::Node::is_error) + .expect("an unfinished tuple struct recovers into an ERROR"); + let raw = (0..error.child_count()) + .filter_map(|i| u32::try_from(i).ok()) + .filter(|&i| error.field_name_for_child(i) == Some("type")) + .count(); + assert_eq!(raw, typed, "raw at {elements}"); + assert_eq!( + error.child_count() >= FIELD_PROBE_WIDTH, + elements == 20, + "the two inputs must straddle the probe width" + ); + for_each_strategy::( + code.as_bytes(), + "test.rs", + false, + |name, root| { + let error = find_first(root, "ERROR").expect("the exported ERROR"); + let exported = error + .children + .iter() + .filter(|c| c.field_name == Some("type")) + .count(); + assert_eq!(exported, typed, "{name} at {elements}"); + }, + ); + } + } + + /// A cancelled flag stops the export as it stops the parse: a wide + /// `ERROR` node can make the export quadratic (#1942), and a + /// `bca-web` request past its deadline must not keep its thread for + /// that. The parse runs before the flag is installed, so only the + /// export sees it. expected: the full tree under a live flag, no tree + /// once it is cancelled, from both strategies. + #[cfg(feature = "rust")] + #[test] + fn a_cancelled_export_yields_no_tree() { + let path = PathBuf::from("test.rs"); + let parser = crate::RustParser::new(b"fn f() {}\n".to_vec(), &path, None); + let cancel = crate::cancel::ParseCancel::new(); + let export = |dump: Dump| { + cancel.run(|| dump(&parser, cfg_with(false, false)).root) + }; + for (name, dump) in strategies::() { + assert!(export(dump).is_some(), "{name} under a live flag"); + } + cancel.cancel(); + for (name, dump) in strategies::() { + assert!(export(dump).is_none(), "{name} under a cancelled flag"); + } + } + #[cfg(feature = "rust")] #[test] fn root_has_no_field_name() { diff --git a/big-code-analysis-ast/src/cancel.rs b/big-code-analysis-ast/src/cancel.rs new file mode 100644 index 000000000..82090243b --- /dev/null +++ b/big-code-analysis-ast/src/cancel.rs @@ -0,0 +1,136 @@ +//! Asking the parses and AST exports one thread runs to stop (#1939). +//! +//! `bca-web` gives each request a deadline, but the analysis runs on a +//! blocking thread that nothing outside it can interrupt. A request past +//! its deadline used to run to completion as an orphan, holding a worker +//! for as long as its parse took: minutes for some grammar shapes, which +//! a handful of small requests turned into a server answering 503. +//! +//! A [`ParseCancel`] installed with [`ParseCancel::run`] is read by every +//! parse the closure runs on this thread, through tree-sitter's progress +//! callback, which the runtime calls every hundred parse operations. +//! Once it is cancelled the parse stops and yields an empty tree, so the +//! walks after it finish at once. An AST export already under way reads +//! it once per node and yields no tree, since its walk over a wide +//! `ERROR` node can be quadratic (#1942). The answer is wrong by design: +//! the one party that asks to stop is the one that has stopped waiting +//! for it. + +use std::cell::Cell; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; + +/// A flag that asks the parses and AST exports of the closure it is +/// installed for to stop. Clones share the flag, so the thread that +/// cancels holds one clone and the thread that parses another. +#[derive(Clone, Debug, Default)] +pub struct ParseCancel(Arc); + +thread_local! { + /// The flag the closure running on this thread was given, if any. + static INSTALLED: Cell> = const { Cell::new(None) }; +} + +impl ParseCancel { + /// A flag that has not been cancelled. + #[must_use] + pub fn new() -> Self { + Self::default() + } + + /// Asks every parse and AST export running under this flag, or + /// started under it later, to stop. + pub fn cancel(&self) { + // The flag publishes no data, only that the parse should stop, so + // no ordering with other memory is needed. + self.0.store(true, Ordering::Relaxed); + } + + /// Whether [`cancel`](Self::cancel) has been called on any clone. + #[must_use] + pub fn is_cancelled(&self) -> bool { + self.0.load(Ordering::Relaxed) + } + + /// Runs `f` with this flag installed for the parses `f` runs on the + /// current thread, and restores whatever was installed before. + pub fn run(&self, f: impl FnOnce() -> T) -> T { + let previous = INSTALLED.try_with(|slot| slot.replace(Some(self.clone()))); + let _restore = Restore(previous.ok().flatten()); + f() + } +} + +/// Puts the previously installed flag back when the closure returns or +/// unwinds. +struct Restore(Option); + +impl Drop for Restore { + fn drop(&mut self) { + let previous = self.0.take(); + // `try_with`: a closure run from another thread-local's destructor + // may outlive this slot, and `with` would panic there. + let _ = INSTALLED.try_with(|slot| slot.set(previous)); + } +} + +/// Whether the flag installed on this thread, if any, has been +/// cancelled. Read by the parser's progress callback and by the AST +/// export walk. +pub(crate) fn requested() -> bool { + INSTALLED + .try_with(|slot| { + let flag = slot.take(); + let cancelled = flag.as_ref().is_some_and(ParseCancel::is_cancelled); + slot.set(flag); + cancelled + }) + .unwrap_or(false) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Only the flag installed on this thread counts, only while its + /// closure runs, and an inner `run` restores the outer flag. + #[test] + fn a_flag_counts_only_inside_its_run() { + let outer = ParseCancel::new(); + let inner = ParseCancel::new(); + inner.cancel(); + assert!(!requested(), "nothing is installed yet"); + outer.run(|| { + assert!(!requested(), "the outer flag is not cancelled"); + inner.run(|| assert!(requested(), "the inner flag is")); + assert!(!requested(), "the outer flag is back"); + outer.cancel(); + assert!(requested(), "a cancel reaches the running closure"); + }); + assert!(!requested(), "nothing is installed after the run"); + } + + /// A clone shares the flag, which is how the thread that cancels + /// reaches the thread that parses. The parsing thread reads the flag + /// only after the test has cancelled it and said so over a channel, + /// so the order is fixed rather than raced. + #[test] + fn a_cancel_reaches_a_clone_on_another_thread() { + let flag = ParseCancel::new(); + let parsing = flag.clone(); + let (cancelled, wait_for_cancel) = std::sync::mpsc::channel::<()>(); + let seen = std::thread::spawn(move || { + parsing.run(|| { + wait_for_cancel + .recv() + .expect("the test thread reports the cancel"); + requested() + }) + }); + flag.cancel(); + cancelled + .send(()) + .expect("the parsing thread waits for the report"); + assert!(seen.join().expect("the parsing thread must not panic")); + } +} diff --git a/big-code-analysis-ast/src/langs.rs b/big-code-analysis-ast/src/langs.rs index 0ad2cbbcb..0ec438930 100644 --- a/big-code-analysis-ast/src/langs.rs +++ b/big-code-analysis-ast/src/langs.rs @@ -79,7 +79,7 @@ mk_langs!( tree_sitter_mozjs, [jsm], [], - "2.5.2" + "2.6.0" ), ( "java", @@ -151,7 +151,7 @@ mk_langs!( tree_sitter_tcl, [tcl, tk, tm], ["tcl"], - "2.5.2" + "2.6.0" ), ( "irules", @@ -213,7 +213,7 @@ mk_langs!( tree_sitter_mozcpp, [], [], - "2.5.2" + "2.6.0" ), ( "objc", @@ -314,7 +314,7 @@ mk_langs!( tree_sitter_ccomment, [], [], - "2.5.2" + "2.6.0" ), ( "c-family-helpers", @@ -326,7 +326,7 @@ mk_langs!( tree_sitter_preproc, [], [], - "2.5.2" + "2.6.0" ), ( "perl", diff --git a/big-code-analysis-ast/src/lib.rs b/big-code-analysis-ast/src/lib.rs index 24d455f31..cf73abbd2 100644 --- a/big-code-analysis-ast/src/lib.rs +++ b/big-code-analysis-ast/src/lib.rs @@ -92,6 +92,7 @@ pub mod ast; pub mod c_declarator; pub(crate) mod c_langs_macros; pub(crate) mod c_macro; +pub mod cancel; pub(crate) mod cfg_predicate; pub mod checker; pub(crate) mod comment_rm; diff --git a/big-code-analysis-ast/src/node.rs b/big-code-analysis-ast/src/node.rs index a1e53f3fb..b2b3dd5bf 100644 --- a/big-code-analysis-ast/src/node.rs +++ b/big-code-analysis-ast/src/node.rs @@ -349,6 +349,12 @@ impl<'a> Node<'a> { /// comment-removal walks reach calls this; the remaining callers are /// `Ancestors` itself (the no-chain fallback), the one-off start node /// of a `dump`, and tests. `rg '\.parent\(\)' src/` re-checks that. + /// + /// **Not on a deep zero-width node.** On a zero-width node, such as a + /// `MISSING` one, tree-sitter's lookup calls itself once per tree + /// level, so far enough down it overflows the stack (#1941). The + /// Python bindings answer that case by walking down from the root + /// (#1937); this type cannot reach the root without this lookup. #[inline] pub fn parent(&self) -> Option> { node_resolved_parent_lookups::record(); diff --git a/big-code-analysis-ast/src/node/parser_cache.rs b/big-code-analysis-ast/src/node/parser_cache.rs index 3382a17c0..35c5c99ac 100644 --- a/big-code-analysis-ast/src/node/parser_cache.rs +++ b/big-code-analysis-ast/src/node/parser_cache.rs @@ -23,8 +23,9 @@ //! misparse a file buys nothing. use std::cell::Cell; +use std::ops::ControlFlow; -use tree_sitter::{Language, Parser, Tree}; +use tree_sitter::{Language, ParseOptions, ParseState, Parser, Tree}; thread_local! { /// The parser this thread reuses across the files it analyzes. @@ -54,10 +55,14 @@ crate::observation::counter!(parsers_built); /// them through a pool of its own (`ts_tree_delete`). It outlives both /// the cached parser and the thread that built it. /// -/// The `parse` invariant below holds only because nothing in this crate -/// sets a timeout, a cancellation flag, or included ranges: unlike the -/// parse state, `set_language` does not clear those, so anything that -/// starts setting one must clear it before the parser goes back. +/// Under a cancelled [`crate::cancel::ParseCancel`] the parse stops and +/// this returns the tree of an empty input instead (#1939). The stop is a +/// per-call progress callback, not parser state; the parser is reset +/// after it, because a stopped parser resumes where it left off on the +/// next call. Nothing in this crate sets a timeout, a cancellation flag, +/// or included ranges, which *are* parser state: `set_language` does not +/// clear those, so anything that starts setting one must clear it before +/// the parser goes back. pub fn parse_on_scratch_parser(language: &Language, code: &[u8]) -> Tree { let mut parser = SCRATCH_PARSER .try_with(Cell::take) @@ -69,14 +74,36 @@ pub fn parse_on_scratch_parser(language: &Language, code: &[u8]) -> Tree { parser .set_language(language) .expect("invariant: grammar version is pinned and compatible with bundled tree-sitter"); - let tree = parser - .parse(code, None) - .expect("invariant: parser has a language set and no cancellation flag"); + let tree = parse_unless_cancelled(&mut parser, code).unwrap_or_else(|| { + parser.reset(); + parser + .parse(b"", None) + .expect("invariant: parser has a language set and nothing stops this parse") + }); // Dropped rather than cached when the slot is already gone. let _ = SCRATCH_PARSER.try_with(|slot| slot.set(Some(parser))); tree } +/// Parses `code`, or answers `None` once the [`crate::cancel`] flag +/// installed on this thread is cancelled. The runtime reads the callback +/// every hundred parse operations. +fn parse_unless_cancelled(parser: &mut Parser, code: &[u8]) -> Option { + let mut stop_if_cancelled = |_: &ParseState| { + if crate::cancel::requested() { + ControlFlow::Break(()) + } else { + ControlFlow::Continue(()) + } + }; + let options = ParseOptions::new().progress_callback(&mut stop_if_cancelled); + parser.parse_with_options( + &mut |offset, _| code.get(offset..).unwrap_or_default(), + None, + Some(options), + ) +} + fn build_parser() -> Parser { parsers_built::record(); Parser::new() @@ -137,6 +164,49 @@ mod tests { .expect("parsing thread must not panic"); } + /// A cancelled flag stops the parse, which then yields the tree of an + /// empty input, and the next parse on the thread reads its own input + /// in full (#1939). The input is long enough that the runtime asks its + /// progress callback — every hundred parse operations — before the + /// parse could finish, so the stop lands mid-parse. That is what makes + /// the reset observable: without it the empty-input parse resumes the + /// abandoned one and does not answer `0..0`. + #[test] + fn a_cancelled_parse_yields_an_empty_tree_and_a_clean_parser() { + std::thread::spawn(|| { + let language = rust_language(); + let long = "fn f() { let x = 1; }\n".repeat(200); + let cancel = crate::cancel::ParseCancel::new(); + cancel.cancel(); + let stopped = cancel.run(|| parse_on_scratch_parser(&language, long.as_bytes())); + assert_eq!(stopped.root_node().byte_range(), 0..0); + assert_eq!(stopped.root_node().child_count(), 0); + + let code = b"fn g() { let y = 2; }"; + let next = parse_on_scratch_parser(&language, code); + let mut fresh = Parser::new(); + fresh + .set_language(&language) + .expect("the pinned grammar loads"); + let expected = fresh.parse(code, None).expect("an uncancelled parse"); + assert_eq!(next.root_node().byte_range(), 0..code.len()); + assert_eq!(next.root_node().to_sexp(), expected.root_node().to_sexp()); + }) + .join() + .expect("parsing thread must not panic"); + } + + /// An installed flag nobody cancels changes nothing. + #[test] + fn an_uncancelled_flag_parses_in_full() { + let language = rust_language(); + let code = "fn f() { let x = 1; }\n".repeat(200); + let tree = crate::cancel::ParseCancel::new() + .run(|| parse_on_scratch_parser(&language, code.as_bytes())); + assert_eq!(tree.root_node().byte_range(), 0..code.len()); + assert!(!tree.root_node().has_error()); + } + /// Each thread carries its own parser: one thread's cache must not /// satisfy another's first parse. /// diff --git a/big-code-analysis-bench/src/shapes.rs b/big-code-analysis-bench/src/shapes.rs index 8e00aeec9..4d0073527 100644 --- a/big-code-analysis-bench/src/shapes.rs +++ b/big-code-analysis-bench/src/shapes.rs @@ -1736,6 +1736,18 @@ pub fn tcl_nested_eval(depth: usize) -> String { format!("{}puts hi{}\n", "eval {".repeat(depth), "}".repeat(depth)) } +/// Tcl: `expr {((…(1)…))}`, `width` parentheses deep inside one `expr`. +/// +/// The grammar folds each parenthesised level into a hidden rule, so the +/// visible tree is flat: one `expr` node with `2 * width + 3` children, +/// nested `width` hidden levels deep, and no field on any of them. That +/// is the shape whose field lookup climbed the hidden levels per child +/// (#1938). +#[must_use] +pub fn tcl_expr_parens(width: usize) -> String { + format!("expr {{{}1{}}}\n", "(".repeat(width), ")".repeat(width)) +} + /// Tcl: `x {{…{a b}…}}`, `depth` braces deep on one row. /// /// #1416's fixture: one `braced_word` per level, two AST levels apart @@ -2078,6 +2090,17 @@ const SPACE_MERGE_WIDTHS: [usize; 3] = [4_000, 8_000, 16_000]; /// a `--gate` run the space-merge probes pay. const SLOT_SCAN_WIDTHS: [usize; 3] = SPACE_MERGE_WIDTHS; +/// Parenthesis counts for `dump/tcl-expr-parens`. +/// +/// Set by measurement. On [`LINEAR_WIDTHS`] the climb is still small +/// beside the export's own cost per node: the export that climbed for +/// every child fitted 0.82 there, its 500-wide cell reading slower than +/// its 1 000-wide one. On this ladder it fits 1.95 (41, 150 and 623 ms) +/// and the export that asks first 0.50 (4.9, 4.5 and 9.9 ms, the same +/// inversion again at the bottom). A climbing 16 000-wide cell stays far +/// inside `scaling::MAX_CELL_WALK`. +const FIELD_CLIMB_WIDTHS: [usize; 3] = SPACE_MERGE_WIDTHS; + /// Sibling counts for the two `perl-commented-*-list` probes, the ladder /// of [`SPACE_MERGE_WIDTHS`]. With its sibling read put back on a pass /// from the list's first child the plain list read 2.08 here, 0.9 s at @@ -2345,6 +2368,24 @@ pub const PROBES: &[Probe] = &[ cache from `Export::finish` scans the list once per \ word, quadratic in the line's width (#1686).", }, + Probe { + name: "dump/tcl-expr-parens", + lang: LANG::Tcl, + axis: Axis::Width, + workload: Workload::Dump { + span: true, + comment: false, + }, + render: tcl_expr_parens, + sizes: FIELD_CLIMB_WIDTHS, + max_exponent: LINEAR_BOUND, + rationale: "A cursor reads a child's field by climbing every hidden \ + level between it and the visible parent, and each \ + parenthesis of a Tcl `expr` adds one, so asking it of \ + every child of the flat `expr` is quadratic. The export \ + asks only under a wide parent whose production maps a \ + field (#1938).", + }, Probe { name: "halstead/tcl-wide-erroring-eval", lang: LANG::Tcl, diff --git a/big-code-analysis-book/po/ja.po b/big-code-analysis-book/po/ja.po index 116c6ccc2..987553c19 100644 --- a/big-code-analysis-book/po/ja.po +++ b/big-code-analysis-book/po/ja.po @@ -16111,29 +16111,46 @@ msgstr "" "値で過大なボディを拒否します。" #: src/commands/web-server.md:116 -#, fuzzy msgid "" -"**Orphaned-task admission control.** When a parse exceeds `--parse-timeout-" -"secs`, the request returns `504`, but the blocking thread keeps running on " -"the pool until the parse finishes on its own, because tree-sitter cannot be " -"interrupted mid-parse. To stop sustained pathological input from piling up " -"unbounded background work, new requests are rejected with `503 Service " -"Unavailable` once the count of orphaned tasks reaches a soft cap. The cap " -"defaults to `max(num_jobs * 2, 4)`; `BCA_MAX_ORPHANED_TASKS` overrides it " -"(parsed as an unsigned integer; an invalid or zero value falls back to the " -"default). Setting `--parse-timeout-secs 0` disables this mechanism entirely, " -"since with no deadline no task is ever orphaned." -msgstr "" -"**孤児タスクの流入制御。** パースが `--parse-timeout-secs` を超えるとリクエス" -"トは `504` を返しますが、tree-sitter はパース途中で中断できないため、ブロッキ" -"ングスレッドはパースが自然に終わるまでプール上で動き続けます。持続的な病的入" -"力によってバックグラウンド作業が際限なく積み上がるのを止めるため、孤児タスク" -"数がソフト上限に達すると、新しいリクエストは `503 Service Unavailable` で拒否" -"されます。上限のデフォルトは `max(num_jobs * 2, 4)` で、" -"`BCA_MAX_ORPHANED_TASKS` で上書きできます(符号なし整数としてパースされ、不正" -"な値やゼロはデフォルトにフォールバックします)。`--parse-timeout-secs 0` を設" -"定すると、この仕組み全体が無効になります。期限がなければタスクが孤児化するこ" -"とはないためです。" +"**Orphaned-task admission control.** When a request exceeds `--parse-timeout-secs`, " +"it returns `504` and its blocking task is asked to stop. The parse and the AST " +"export check for that as they run, so they end soon after the deadline; other " +"analysis already under way, such as a `/vcs` history walk, runs to completion. " +"Until the task ends it counts as orphaned. To stop sustained pathological input " +"from piling up unbounded background work, new requests are rejected with `503 " +"Service Unavailable` once the count of orphaned tasks reaches a soft cap. The " +"cap defaults to `max(num_jobs * 2, 4)`; `BCA_MAX_ORPHANED_TASKS` overrides it " +"(parsed as an unsigned integer; an invalid or zero value falls back to the default). " +"Setting `--parse-timeout-secs 0` disables this mechanism entirely, since with " +"no deadline no task is ever orphaned." +msgstr "" +"**孤児タスクの流入制御。** リクエストが `--parse-timeout-secs` を超えると `504` " +"を返し、そのブロッキングタスクには停止が要求されます。パースと AST エクスポー" +"トは実行中にこの要求を確認するため、期限の直後に終了します。一方、すでに進行" +"中のその他の解析(`/vcs` の履歴ウォークなど)は最後まで実行されます。タスクは" +"終了するまで孤児として数えられます。持続的な病的入力によってバックグラウンド" +"作業が際限なく積み上がるのを止めるため、孤児タスク数がソフト上限に達すると、" +"新しいリクエストは `503 Service Unavailable` で拒否されます。上限のデフォルト" +"は `max(num_jobs * 2, 4)` で、`BCA_MAX_ORPHANED_TASKS` で上書きできます(符号" +"なし整数としてパースされ、不正な値やゼロはデフォルトにフォールバックします)" +"。`--parse-timeout-secs 0` を設定すると、この仕組み全体が無効になります。期限" +"がなければタスクが孤児化することはないためです。" + +#: src/commands/web-server.md:130 +msgid "" +"A request's work is also asked to stop when its connection is reset before the " +"client has closed its sending side. An ordinary close is different: HTTP/1 lets " +"a client close its sending side and still read the response, so the server reads " +"nothing more from that connection, not even a reset that follows, and keeps " +"working on the request until it answers or the deadline passes. With `--parse-timeout-secs " +"0` there is no deadline, so that work runs to completion." +msgstr "" +"クライアントが送信側を閉じる前に接続がリセットされた場合も、そのリクエストの" +"処理には停止が要求されます。通常のクローズは事情が異なります。HTTP/1 ではクラ" +"イアントが送信側を閉じたあとも応答を読み取れるため、サーバーはその接続からそ" +"れ以上何も読み取らず(後に続くリセットも読み取りません)、応答を返すか期限が" +"過ぎるまでリクエストの処理を続けます。`--parse-timeout-secs 0` では期限がない" +"ため、その処理は最後まで実行されます。" #: src/commands/web-server.md:128 msgid "Security and trust boundaries" diff --git a/big-code-analysis-book/src/commands/rest.md b/big-code-analysis-book/src/commands/rest.md index 14c7ca4ca..5e0b160d1 100644 --- a/big-code-analysis-book/src/commands/rest.md +++ b/big-code-analysis-book/src/commands/rest.md @@ -546,8 +546,8 @@ GET http://127.0.0.1:8080/v1/version ```json { - "server": "2.5.1", - "library": "2.5.1" + "server": "2.6.0", + "library": "2.6.0" } ``` @@ -597,7 +597,7 @@ GET http://127.0.0.1:8080/v1 ```json { "service": "bca-web", - "version": "2.5.1", + "version": "2.6.0", "routes": [ { "path": "/v1", "methods": ["GET", "HEAD"], "description": "This route index." }, { "path": "/v1/metrics", "methods": ["POST"], "description": "Compute maintainability metrics for the source." } diff --git a/big-code-analysis-book/src/commands/web-server.md b/big-code-analysis-book/src/commands/web-server.md index 476539d30..617528710 100644 --- a/big-code-analysis-book/src/commands/web-server.md +++ b/big-code-analysis-book/src/commands/web-server.md @@ -113,18 +113,28 @@ than 4 MiB with `413 Payload Too Large`. The limit applies uniformly to the JSON and raw-octet-stream content types, so both reject oversized bodies at the same threshold. -**Orphaned-task admission control.** When a parse exceeds -`--parse-timeout-secs`, the request returns `504`, but the blocking -thread keeps running on the pool until the parse finishes on its own, -because tree-sitter cannot be interrupted mid-parse. To stop sustained -pathological input from piling up unbounded background work, new -requests are rejected with `503 Service Unavailable` once the count of -orphaned tasks reaches a soft cap. The cap defaults to +**Orphaned-task admission control.** When a request exceeds +`--parse-timeout-secs`, it returns `504` and its blocking task is asked +to stop. The parse and the AST export check for that as they run, so +they end soon after the deadline; other analysis already under way, +such as a `/vcs` history walk, runs to completion. Until the task ends +it counts as orphaned. To stop +sustained pathological input from piling up unbounded background work, +new requests are rejected with `503 Service Unavailable` once the count +of orphaned tasks reaches a soft cap. The cap defaults to `max(num_jobs * 2, 4)`; `BCA_MAX_ORPHANED_TASKS` overrides it (parsed as an unsigned integer; an invalid or zero value falls back to the default). Setting `--parse-timeout-secs 0` disables this mechanism entirely, since with no deadline no task is ever orphaned. +A request's work is also asked to stop when its connection is reset +before the client has closed its sending side. An ordinary close is +different: HTTP/1 lets a client close its sending side and still read +the response, so the server reads nothing more from that connection, +not even a reset that follows, and keeps working on the request until +it answers or the deadline passes. With `--parse-timeout-secs 0` there +is no deadline, so that work runs to completion. + ## Security and trust boundaries `bca-web` has no authentication, authorization, or rate limiting of diff --git a/big-code-analysis-book/src/library/cargo-features.md b/big-code-analysis-book/src/library/cargo-features.md index cece63a69..c405b589f 100644 --- a/big-code-analysis-book/src/library/cargo-features.md +++ b/big-code-analysis-book/src/library/cargo-features.md @@ -7,7 +7,7 @@ The default feature set is `all-languages`, so the default ```toml [dependencies] -big-code-analysis = "2.5.1" +big-code-analysis = "2.6.0" ``` pulls every grammar in, matching the library's historical behaviour @@ -24,7 +24,7 @@ A downstream service that only analyses Rust and TypeScript: ```toml [dependencies] -big-code-analysis = { version = "2.5.1", default-features = false, features = ["rust", "typescript"] } +big-code-analysis = { version = "2.6.0", default-features = false, features = ["rust", "typescript"] } ``` The library still compiles, the `LANG` enum still has every diff --git a/big-code-analysis-book/src/library/quick-start.md b/big-code-analysis-book/src/library/quick-start.md index 76e35c4ee..8bd4a377d 100644 --- a/big-code-analysis-book/src/library/quick-start.md +++ b/big-code-analysis-book/src/library/quick-start.md @@ -9,7 +9,7 @@ crate to add the dependency to. ```toml # Cargo.toml [dependencies] -big-code-analysis = "2.5.1" +big-code-analysis = "2.6.0" ``` The crate uses Rust edition 2024 and pins `rust-version = "1.94"`. diff --git a/big-code-analysis-book/src/library/stability.md b/big-code-analysis-book/src/library/stability.md index 39bebf185..8f5e69660 100644 --- a/big-code-analysis-book/src/library/stability.md +++ b/big-code-analysis-book/src/library/stability.md @@ -1,6 +1,6 @@ # Stability and versioning -`big-code-analysis` is on the `2.x` line (currently `2.5.1`). The +`big-code-analysis` is on the `2.x` line (currently `2.6.0`). The full stability contract lives in [`STABILITY.md`][stability] at the root of the repository. That file is the source of truth and is updated alongside the changelog at every release; this page is the @@ -22,7 +22,7 @@ The headlines: or a bug fix in a metric definition can shift any metric value on any file in any direction, even across a patch bump. Each such drift is flagged in the changelog. Pin to an exact version - (`big-code-analysis = "= 2.5.1"`) if you need bit-for-bit + (`big-code-analysis = "= 2.6.0"`) if you need bit-for-bit reproducibility across runs. - **The minimum supported Rust version (MSRV) is `1.94`.** Bumping the MSRV is treated as a minor-bump diff --git a/big-code-analysis-cli/Cargo.toml b/big-code-analysis-cli/Cargo.toml index ddada312e..e325700c0 100644 --- a/big-code-analysis-cli/Cargo.toml +++ b/big-code-analysis-cli/Cargo.toml @@ -23,7 +23,7 @@ ignore = "^0.4" # The CLI exposes every language `bca` advertises, so it pins the # library's full feature set explicitly. Disabling default features # here would silently drop grammars from the CLI build. See #252. -big-code-analysis = { path = "..", version = "=2.5.2", default-features = false, features = [ +big-code-analysis = { path = "..", version = "=2.6.0", default-features = false, features = [ "all-languages", # End-user binary ships every backend that exists; `vcs` is the # umbrella turning on `vcs-git` (issue #328). diff --git a/big-code-analysis-py/src/node.rs b/big-code-analysis-py/src/node.rs index 674341452..b00919950 100644 --- a/big-code-analysis-py/src/node.rs +++ b/big-code-analysis-py/src/node.rs @@ -137,6 +137,83 @@ fn push_children_for_preorder( stack[first_child..].reverse(); } +/// Which relative of a node a getter asks for. +#[derive(Clone, Copy)] +enum Relative { + Parent, + Next { named: bool }, + Prev { named: bool }, +} + +/// The visible parent of the zero-width `node`, found by walking down +/// from `root` rather than through `ts_node_parent`. +/// +/// In the pinned runtime, `ts_node_parent` asks +/// `ts_node_child_with_descendant`, which calls itself once per tree +/// level when the node it looks for is zero-width. Asking for the parent +/// of a `MISSING` node some 15,000 levels deep overflowed the +/// interpreter's stack and killed it (#1937). This walk keeps its place +/// in a cursor and enters only nodes whose span holds the node's +/// position, so it costs the siblings along that one path. +fn zero_width_parent<'t>(root: TsNode<'t>, node: TsNode<'_>) -> Option> { + let at = node.start_byte(); + let holds = |here: &TsNode<'_>| here.start_byte() <= at && at <= here.end_byte(); + let mut cursor = root.walk(); + while cursor.node().id() != node.id() { + let entered = holds(&cursor.node()) && cursor.goto_first_child(); + if !entered && !skip_subtree(&mut cursor) { + return None; + } + } + cursor.goto_parent().then(|| cursor.node()) +} + +/// The visible parent of `node` in the tree rooted at `root`: tree-sitter's +/// own lookup for a node with width, [`zero_width_parent`] for a +/// zero-width one, on which `ts_node_parent` recurses once per level (#1937). +fn parent_within<'t>(root: TsNode<'t>, node: TsNode<'t>) -> Option> { + if node.start_byte() == node.end_byte() { + zero_width_parent(root, node) + } else { + node.parent() + } +} + +/// Moves `cursor` past the subtree it sits on, to the next node in +/// pre-order: its next sibling, or the next sibling of the nearest +/// ancestor that has one. `false` once the walk has left the tree. +fn skip_subtree(cursor: &mut TreeCursor<'_>) -> bool { + while !cursor.goto_next_sibling() { + if !cursor.goto_parent() { + return false; + } + } + true +} + +/// The child of `parent` before `node` and the one after it, counting only +/// named children when `named`, read off `parent` rather than through +/// tree-sitter's sibling lookups, which ask `ts_node_parent` first. +fn neighbours<'t>( + parent: TsNode<'t>, + node: TsNode<'_>, + named: bool, +) -> (Option>, Option>) { + let counts = |child: &TsNode<'_>| !named || child.is_named(); + let mut cursor = parent.walk(); + let mut children = parent.children(&mut cursor); + let mut before = None; + while let Some(child) = children.next() { + if child.id() == node.id() { + return (before, children.find(counts)); + } + if counts(&child) { + before = Some(child); + } + } + (None, None) +} + /// Ownership boundary for the erased-lifetime pair (#1057). /// /// Both pyclasses pair an erased `Node<'static>` / `TreeCursor<'static>` @@ -180,9 +257,11 @@ mod owned { /// `Ast` alive through `ast`. /// /// The one place the pairing is a *caller* obligation: `node` must - /// have come from the tree held by `ast`. Both callers are + /// have come from the tree held by `ast`. The callers are /// [`PyAst::root_node`] / [`PyAst::find`], which pass a node from - /// the very `Ast` they are wrapping. Every other handle in this + /// the very `Ast` they are wrapping, and `PyNode::relative`, which + /// passes a node it found by walking down from that `Ast`'s root + /// for a zero-width node's relatives. Every other handle in this /// module is derived from an existing one by [`rewrap`](Self::rewrap) /// or [`PyNodeWalk::next_node`], which carry the pairing over /// instead of restating it. @@ -285,6 +364,34 @@ mod owned { pub(crate) use owned::{PyNode, PyNodeWalk}; +impl PyNode { + /// `relative` of this node. A node with width keeps tree-sitter's own + /// lookup, which is iterative; a zero-width one, such as a `MISSING` + /// node, finds its parent from the root instead ([`zero_width_parent`], + /// #1937) and reads its siblings off that parent. + fn relative(&self, py: Python<'_>, relative: Relative) -> Option { + let node = self.node(); + if node.start_byte() != node.end_byte() { + let found = match relative { + Relative::Parent => node.parent(), + Relative::Next { named: false } => node.next_sibling(), + Relative::Next { named: true } => node.next_named_sibling(), + Relative::Prev { named: false } => node.prev_sibling(), + Relative::Prev { named: true } => node.prev_named_sibling(), + }; + return found.map(|n| self.rewrap(py, n)); + } + let ast = self.ast().bind(py).get(); + let parent = zero_width_parent(ast.ast_ref().root_node().as_tree_sitter(), node)?; + let found = match relative { + Relative::Parent => Some(parent), + Relative::Next { named } => neighbours(parent, node, named).1, + Relative::Prev { named } => neighbours(parent, node, named).0, + }; + found.map(|n| PyNode::wrap(self.ast().clone_ref(py), n)) + } +} + #[pymethods] impl PyNode { /// The raw grammar kind of this node (e.g. `"function_item"`). @@ -405,9 +512,11 @@ impl PyNode { /// (e.g. `"declarator"`), or `None` for the root and for nodes their /// parent reaches without a field. #[getter] - fn field_name(&self) -> Option<&'static str> { - let parent = self.node().parent()?; - let id = self.node().id(); + fn field_name(&self, py: Python<'_>) -> Option<&'static str> { + let node = self.node(); + let ast = self.ast().bind(py).get(); + let parent = parent_within(ast.ast_ref().root_node().as_tree_sitter(), node)?; + let id = node.id(); let mut cursor = parent.walk(); if !cursor.goto_first_child() { return None; @@ -457,31 +566,31 @@ impl PyNode { /// This node's parent, or `None` at the root. #[getter] fn parent(&self, py: Python<'_>) -> Option { - self.node().parent().map(|p| self.rewrap(py, p)) + self.relative(py, Relative::Parent) } /// The next sibling (named or anonymous), or `None`. #[getter] fn next_sibling(&self, py: Python<'_>) -> Option { - self.node().next_sibling().map(|n| self.rewrap(py, n)) + self.relative(py, Relative::Next { named: false }) } /// The previous sibling (named or anonymous), or `None`. #[getter] fn prev_sibling(&self, py: Python<'_>) -> Option { - self.node().prev_sibling().map(|n| self.rewrap(py, n)) + self.relative(py, Relative::Prev { named: false }) } /// The next *named* sibling, or `None`. #[getter] fn next_named_sibling(&self, py: Python<'_>) -> Option { - self.node().next_named_sibling().map(|n| self.rewrap(py, n)) + self.relative(py, Relative::Next { named: true }) } /// The previous *named* sibling, or `None`. #[getter] fn prev_named_sibling(&self, py: Python<'_>) -> Option { - self.node().prev_named_sibling().map(|n| self.rewrap(py, n)) + self.relative(py, Relative::Prev { named: true }) } /// The child at `index` (named and anonymous children counted), or @@ -632,3 +741,89 @@ impl PyNodeWalk { self.next_node(py) } } + +#[cfg(test)] +mod tests { + use big_code_analysis::{Ast, LANG, Source}; + + use super::{TsNode, neighbours, zero_width_parent}; + + /// `void f(){x = ((…()…));}`, `depth` parentheses deep: the innermost + /// pair holds a zero-width `MISSING` identifier. + fn nested_missing(depth: usize) -> Ast { + let code = format!( + "void f(){{x = {}{};}}\n", + "(".repeat(depth), + ")".repeat(depth) + ); + Ast::parse(Source::new(LANG::C, code.as_bytes())).expect("C is a default feature") + } + + /// Every zero-width node of `root`'s tree, found on an explicit stack. + fn zero_width_nodes(root: TsNode<'_>) -> Vec> { + let mut found = Vec::new(); + let mut pending = vec![root]; + let mut cursor = root.walk(); + while let Some(node) = pending.pop() { + if node.start_byte() == node.end_byte() { + found.push(node); + } + pending.extend(node.children(&mut cursor)); + } + found + } + + /// Where tree-sitter's own lookups are safe, at a shallow depth, the + /// walk from the root answers what they answer, for every zero-width + /// node (#1937). + #[test] + fn the_root_walk_agrees_with_tree_sitter_where_it_is_safe() { + let ast = nested_missing(6); + let root = ast.root_node().as_tree_sitter(); + let nodes = zero_width_nodes(root); + assert!(!nodes.is_empty(), "the input must hold a zero-width node"); + for node in nodes { + let parent = zero_width_parent(root, node); + assert_eq!(parent, node.parent(), "{}", node.kind()); + let parent = parent.expect("a zero-width node below the root has a parent"); + assert_eq!( + neighbours(parent, node, false), + (node.prev_sibling(), node.next_sibling()) + ); + assert_eq!( + neighbours(parent, node, true), + (node.prev_named_sibling(), node.next_named_sibling()) + ); + } + } + + /// 20,000 levels above the `MISSING` node, far past the depth at which + /// `ts_node_parent` overflowed the interpreter's main-thread stack, on + /// a 512 KiB one. expected: the innermost `parenthesized_expression`, + /// whose `(` and `)` flank the node. + #[test] + fn a_deep_zero_width_node_finds_its_parent_on_a_small_stack() { + // Parentheses around the `MISSING` node. + const DEPTH: usize = 20_000; + // A deliberately small test-thread stack. + const SMALL_STACK: usize = 512 * 1024; + std::thread::Builder::new() + .stack_size(SMALL_STACK) + .spawn(|| { + let ast = nested_missing(DEPTH); + let root = ast.root_node().as_tree_sitter(); + let missing = zero_width_nodes(root) + .into_iter() + .find(TsNode::is_missing) + .expect("the innermost pair holds a MISSING node"); + let parent = zero_width_parent(root, missing).expect("a parent"); + assert_eq!(parent.kind(), "parenthesized_expression"); + let (before, after) = neighbours(parent, missing, false); + assert_eq!(before.map(|n| n.kind()), Some("(")); + assert_eq!(after.map(|n| n.kind()), Some(")")); + }) + .expect("spawn bounded-stack thread") + .join() + .expect("the root walk must not overflow a 512 KiB stack"); + } +} diff --git a/big-code-analysis-py/tests/test_node.py b/big-code-analysis-py/tests/test_node.py index 7c53c5d52..2785a7939 100644 --- a/big-code-analysis-py/tests/test_node.py +++ b/big-code-analysis-py/tests/test_node.py @@ -158,6 +158,39 @@ def test_parent_and_sibling_links() -> None: assert stmts[0].prev_sibling is not None # the opening `{` +def _innermost_missing(depth: int) -> Node: + """The zero-width ``MISSING`` identifier in ``void f(){x = ((…()…));}``, + ``depth`` parentheses deep.""" + src = "void f(){x = " + "(" * depth + ")" * depth + ";}\n" + root = bca.Ast.parse(src, "c").root_node + return next(node for node in root.walk() if node.is_missing) + + +@pytest.mark.parametrize("depth", [3, 20_000]) +def test_parent_and_siblings_of_a_deep_zero_width_node(depth: int) -> None: + """#1937: a ``MISSING`` node is zero-width, and tree-sitter's parent + lookup recursed once per tree level above one, so at 20,000 levels the + interpreter died of a segmentation fault. ``parent`` and the sibling + getters now answer at any depth what they answer at a shallow one: the + innermost ``parenthesized_expression``, whose ``(`` and ``)`` flank the + node, with no named sibling.""" + missing = _innermost_missing(depth) + parent = missing.parent + assert parent is not None + assert parent.kind == "parenthesized_expression" + assert missing in parent.children + prev, following = missing.prev_sibling, missing.next_sibling + assert prev is not None + assert prev.kind == "(" + assert following is not None + assert following.kind == ")" + assert missing.prev_named_sibling is None + assert missing.next_named_sibling is None + # `field_name` asks for the parent too; the identifier sits in the + # parenthesized expression without a field. + assert missing.field_name is None + + def test_field_name_and_child_by_field_name() -> None: fn = bca.Ast.parse(RUST_SRC, "rust").root_node.children[0] name = fn.child_by_field_name("name") diff --git a/big-code-analysis-web/Cargo.toml b/big-code-analysis-web/Cargo.toml index 875025e25..8a21dc490 100644 --- a/big-code-analysis-web/Cargo.toml +++ b/big-code-analysis-web/Cargo.toml @@ -11,9 +11,10 @@ description = "Run a web service to compute and export code metrics" [dependencies] actix-rt = "^2.6" -# The daemon binds plaintext only (no TLS), and actix negotiates HTTP/2 -# solely through TLS ALPN, so the `http2` default feature buys nothing -# and only pulls in `h2 0.3`, which carries the unfixable +# The daemon binds plaintext only (no TLS) and serves HTTP/1. The `http2` +# default feature would add cleartext HTTP/2 by prior knowledge (h2c) on +# that socket, which no client of this API needs, and it pulls in +# `h2 0.3`, which carries the unfixable # RUSTSEC-2026-0258 (actix-http 3 stays on http 0.2, hence h2 0.3; the # fix exists only in h2 0.4.16). The rest is actix-web 4.19's default # set as of that pin; re-derive it on a minor bump, since the list is a @@ -34,7 +35,7 @@ futures = "^0.3" # pins the library's full feature set explicitly. Disabling default # features here would silently drop grammars from the daemon build. # See #252. -big-code-analysis = { path = "..", version = "=2.5.2", default-features = false, features = [ +big-code-analysis = { path = "..", version = "=2.6.0", default-features = false, features = [ "all-languages", # `POST /vcs` change-history endpoint (issue #328). "vcs", @@ -64,6 +65,9 @@ pretty_assertions = "^1.3" # `POST /vcs` route tests build a throwaway git working tree on disk # (issue #328); the history walk has no in-request representation. tempfile.workspace = true +# The live-server tests drive raw HTTP/1 connections; `set_zero_linger` +# (1.50) makes a close a reset. +tokio = { version = "^1.50", features = ["io-util", "net"] } tracing-test = "^0.2" # Debian/Ubuntu packaging — consumed by `cargo deb` in release CI. diff --git a/big-code-analysis-web/src/lib.rs b/big-code-analysis-web/src/lib.rs index e2fc734ae..e61560eea 100644 --- a/big-code-analysis-web/src/lib.rs +++ b/big-code-analysis-web/src/lib.rs @@ -53,7 +53,8 @@ pub mod cli { /// timeout a parse never times out, so no task is ever orphaned and /// the `503` back-pressure that sheds load under sustained /// pathological input never engages. Use `0` only when an unbounded - /// parse is acceptable (issue #707). + /// parse is acceptable. + // The deadline / admission-gate coupling is issue #707. #[clap(long, default_value_t = DEFAULT_PARSE_TIMEOUT_SECS)] pub parse_timeout_secs: u64, /// Enable CORS for the given origins (off by default). diff --git a/big-code-analysis-web/src/web/server.rs b/big-code-analysis-web/src/web/server.rs index 1a792e01b..4453fde23 100644 --- a/big-code-analysis-web/src/web/server.rs +++ b/big-code-analysis-web/src/web/server.rs @@ -92,6 +92,24 @@ async fn run_parse_fallible( .map_err(|err| ParseError::from_metrics(payload_id, err)) } +/// Cancels the parse it holds when dropped: by then nobody awaits the +/// task's result, whether `run_parse` returned or its future was dropped. +/// +/// actix drops a handler's future when a read from its connection fails, +/// as one does once the connection is reset (RST). A client that closes +/// its sending side (FIN) does not end it: HTTP/1 lets a client half-close +/// and still read the response, so actix reads nothing more from that +/// connection (`read_available` in actix-http's h1 dispatcher), not even +/// a reset that follows, and the handler runs on until it answers or its +/// deadline, if any. +struct CancelOnDrop(big_code_analysis::ParseCancel); + +impl Drop for CancelOnDrop { + fn drop(&mut self) { + self.0.cancel(); + } +} + /// Runs `f` on the blocking pool under the timeout / orphan-pool policy. /// /// `payload_id` is the client-supplied request id from the JSON payload @@ -140,7 +158,16 @@ async fn run_parse( }); } - let mut handle = tokio::task::spawn_blocking(f); + // A blocking task nobody waits for any more cannot be interrupted, so + // it is asked to stop instead: the parse and the AST export read this + // flag and give up, which ends the orphan soon after the deadline + // rather than after however long they would have taken (#1939). The + // flag is set on drop, so a handler actix drops before the deadline, + // as it does when the connection is reset before the client closes its + // sending side, stops its work too. + let cancel = CancelOnDrop(big_code_analysis::ParseCancel::new()); + let task_cancel = cancel.0.clone(); + let mut handle = tokio::task::spawn_blocking(move || task_cancel.run(f)); let result = if let Some(deadline) = config.timeout { match tokio::time::timeout(deadline, &mut handle).await { @@ -154,10 +181,12 @@ async fn run_parse( }) } Err(_) => { - // A timeout orphans the blocking task until it finishes on - // its own. Log it (`warn`, not `error`: it is a deadline / - // load condition, not an internal fault) so ops can correlate - // which request timed out and track orphan-pool pressure. + // A timeout orphans the blocking task until it finishes, + // which `cancel` makes prompt for the parse once this + // returns. Log it (`warn`, not `error`: it is a deadline / + // load condition, not an internal fault) so ops can + // correlate which request timed out and track orphan-pool + // pressure. tracing::warn!( payload_id = %payload_id, timeout_secs = deadline.as_secs(), @@ -241,10 +270,12 @@ pub async fn run(host: &str, port: u16, n_threads: usize) -> std::io::Result<()> /// /// ## Orphaned-task admission control /// -/// When a parse times out, its blocking thread keeps running on tokio's -/// blocking pool until the work itself completes. To prevent unbounded -/// growth from sustained pathological inputs, new requests are rejected -/// with `503` once the orphan count reaches a soft cap. The cap defaults +/// When a request times out, its blocking task on tokio's pool is asked +/// to stop: the parse and the AST export check for that as they run, +/// while other work already under way, such as a `/vcs` history walk, +/// runs to completion. Until it ends the task counts as orphaned. To prevent unbounded growth from sustained +/// pathological inputs, new requests are rejected with `503` once the +/// orphan count reaches a soft cap. The cap defaults /// to `max(n_threads * 2, 4)` and can be overridden by the /// `BCA_MAX_ORPHANED_TASKS` environment variable (parsed as `usize`; /// invalid or zero values fall back to the default). A `parse_timeout_secs` @@ -277,7 +308,37 @@ pub async fn run_with_timeout( max_orphaned_tasks, max_body_size: MAX_BODY_SIZE, }); + serve(Listen::Addr(host, port), n_threads, config, cors)?.await +} + +/// Where [`serve`] accepts connections. +enum Listen<'a> { + /// Bind `host:port`, as `bca-web` does. + Addr(&'a str, u16), + /// A socket the caller bound, so a test can serve on an ephemeral port + /// with production's middleware, routes and HTTP settings. OS signal + /// handling is left off: actix would install process-wide SIGINT / + /// SIGTERM handlers that outlive the test. + #[cfg(test)] + Socket(std::net::TcpListener), +} +/// Builds the HTTP server `run_with_timeout` runs: its middleware, routes +/// and connection settings, one place for production and the transport +/// tests to share. +#[cfg_attr( + not(test), + expect( + clippy::needless_pass_by_value, + reason = "only the test-only `Listen::Socket` is consumed" + ) +)] +fn serve( + listen: Listen<'_>, + n_threads: usize, + config: web::Data, + cors: CorsPolicy, +) -> std::io::Result { // CORS is off by default (#694): the `from_fn` layer is wrapped only // when `--cors` is enabled (`Condition::new`), so the default request // path carries no extra middleware. The policy is registered as app @@ -285,7 +346,7 @@ pub async fn run_with_timeout( let cors_enabled = cors != CorsPolicy::Disabled; let cors = web::Data::new(cors); - HttpServer::new(move || { + let server = HttpServer::new(move || { App::new() .wrap(Condition::new( cors_enabled, @@ -299,10 +360,13 @@ pub async fn run_with_timeout( // integration tests share them (#639). .configure(configure_routes) }) - .workers(n_threads) - .bind((host, port))? - .run() - .await + .workers(n_threads); + let server = match listen { + Listen::Addr(host, port) => server.bind((host, port))?, + #[cfg(test)] + Listen::Socket(listener) => server.listen(listener)?.disable_signals(), + }; + Ok(server.run()) } // curl --header "Content-Type: application/json" --request POST --data '{"id": "1234", "file_name": "prova.cpp", "code": "int x = 1;", "comment": true, "span": true}' http://127.0.0.1:8081/ast diff --git a/big-code-analysis-web/src/web/server_tests.rs b/big-code-analysis-web/src/web/server_tests.rs index 2d09e28dc..bed620b87 100644 --- a/big-code-analysis-web/src/web/server_tests.rs +++ b/big-code-analysis-web/src/web/server_tests.rs @@ -1231,6 +1231,309 @@ async fn test_run_parse_timeout_increments_orphan_counter_and_decrements_on_comp assert_eq!(orphaned.load(Ordering::Acquire), 0); } +/// `-and => ` pairs in [`slow_perl`]. +const SLOW_PAIRS: usize = 8_000; + +/// `$x = ` and [`SLOW_PAIRS`] `-and => ` pairs, which the pinned Perl +/// grammar parses in quadratic time (#1940): about 80 s in a release +/// build, where 4,000 pairs take 19 s, so far past every bound in these +/// tests. Each test cancels its parse, so a passing run pays nothing for +/// the size. +fn slow_perl() -> String { + format!("$x = {}1;\n", "-and => ".repeat(SLOW_PAIRS)) +} + +/// A timed-out request's parse is asked to stop, so its orphan ends soon +/// after the deadline rather than whenever the parse would have finished +/// (#1939). The parse of [`slow_perl`] runs far past the bound below, so +/// an orphan that outlived it still had its parse running. +#[actix_rt::test] +async fn test_run_parse_timeout_stops_the_orphaned_parse() { + // How long the orphan may outlive the deadline. A cancelled parse + // checks the flag every hundred parse operations and ends far sooner. + const ORPHAN_BOUND: Duration = Duration::from_secs(10); + + let orphaned = Arc::new(AtomicUsize::new(0)); + let config = web::Data::new(ParseConfig { + timeout: Some(Duration::from_millis(200)), + semaphore: Arc::new(Semaphore::new(4)), + orphaned_tasks: Arc::clone(&orphaned), + max_orphaned_tasks: 64, + max_body_size: TEST_MAX_BODY_SIZE, + }); + let code = slow_perl(); + let err = run_parse(&config, "req-stop", move || { + big_code_analysis::Ast::parse(big_code_analysis::Source::new( + big_code_analysis::LANG::Perl, + code.as_bytes(), + )) + .is_ok() + }) + .await + .unwrap_err(); + assert_eq!(err.error_response().status(), StatusCode::GATEWAY_TIMEOUT); + + let started = std::time::Instant::now(); + while orphaned.load(Ordering::Acquire) != 0 && started.elapsed() < ORPHAN_BOUND { + tokio::time::sleep(Duration::from_millis(20)).await; + } + assert_eq!( + orphaned.load(Ordering::Acquire), + 0, + "the orphaned parse must stop within {ORPHAN_BOUND:?} of the deadline" + ); +} + +/// A `run_parse` future dropped before its deadline cancels its parse, as +/// a timed-out one does (#1939). This drops the future by hand and says +/// nothing about sockets: which disconnects make actix drop a handler is +/// what `test_live_server_reset_drops_the_handler` and +/// `test_live_server_half_closed_client_gets_its_response` show. No +/// timeout is configured, so only the drop can stop the parse. expected: +/// the parse yields the empty tree, whose root ends at byte 0, inside the +/// bound; without the guard it is still running there. +#[actix_rt::test] +async fn test_run_parse_dropped_future_stops_its_parse() { + // How long the future is polled before it is dropped. + const POLLED_FOR: Duration = Duration::from_millis(200); + // How long the parse may outlive its dropped future. + const PARSE_BOUND: Duration = Duration::from_secs(10); + + let config = web::Data::new(ParseConfig { + timeout: None, + semaphore: Arc::new(Semaphore::new(4)), + orphaned_tasks: Arc::new(AtomicUsize::new(0)), + max_orphaned_tasks: 64, + max_body_size: TEST_MAX_BODY_SIZE, + }); + let code = slow_perl(); + let (parsed, parsed_end) = std::sync::mpsc::channel::(); + let request = run_parse(&config, "req-dropped", move || { + let ast = big_code_analysis::Ast::parse(big_code_analysis::Source::new( + big_code_analysis::LANG::Perl, + code.as_bytes(), + )); + let end = ast.map_or(usize::MAX, |ast| ast.root_node().end_byte()); + let _ = parsed.send(end); + }); + assert!( + tokio::time::timeout(POLLED_FOR, request).await.is_err(), + "the parse must still be running when its future is dropped" + ); + let end = tokio::task::spawn_blocking(move || parsed_end.recv_timeout(PARSE_BOUND)) + .await + .expect("the waiting task must not panic") + .expect("the parse must stop within the bound once its future is dropped"); + assert_eq!( + end, 0, + "the dropped future's parse must have been cancelled" + ); +} + +/// How long a sent request may take to be admitted, or a dropped handler +/// to return its permit. +const LIVE_BOUND: Duration = Duration::from_secs(10); + +/// A `bca-web` server on an ephemeral loopback port, built by the +/// production [`serve`]: its middleware, routes and HTTP settings, HTTP/1 +/// half-close included, on a socket the test binds itself and without OS +/// signal handling. It has one parse permit the test watches: a request's +/// handler holds it from admission until the handler returns or is +/// dropped. Dropping this asks the server to stop. +struct LiveServer { + addr: std::net::SocketAddr, + permits: Arc, + handle: actix_web::dev::ServerHandle, +} + +impl LiveServer { + fn start(deadline: Duration) -> Self { + let listener = + std::net::TcpListener::bind("127.0.0.1:0").expect("bind an ephemeral loopback port"); + let addr = listener + .local_addr() + .expect("a bound listener has an address"); + let permits = Arc::new(Semaphore::new(1)); + let config = web::Data::new(ParseConfig { + timeout: Some(deadline), + semaphore: Arc::clone(&permits), + orphaned_tasks: Arc::new(AtomicUsize::new(0)), + max_orphaned_tasks: 64, + max_body_size: TEST_MAX_BODY_SIZE, + }); + let server = serve(Listen::Socket(listener), 1, config, CorsPolicy::Disabled) + .expect("the test server starts"); + let handle = server.handle(); + actix_rt::spawn(server); + Self { + addr, + permits, + handle, + } + } + + /// Sends [`slow_perl`] as a whole `POST /v1/metrics` and returns once + /// its handler holds the permit, so the request was admitted and its + /// parse spawned before the caller disconnects. + async fn send_slow_request(&self) -> tokio::net::TcpStream { + use tokio::io::AsyncWriteExt as _; + + let code = slow_perl(); + let body = json!({ "file_name": "slow.pl", "code": code }).to_string(); + let request = format!( + "POST /v1/metrics HTTP/1.1\r\nHost: {}\r\nContent-Type: application/json\r\n\ + Content-Length: {}\r\n\r\n{body}", + self.addr, + body.len() + ); + let mut stream = tokio::net::TcpStream::connect(self.addr) + .await + .expect("connect to the test server"); + stream + .write_all(request.as_bytes()) + .await + .expect("send the request"); + assert!( + self.permits_reach(0).await, + "the request must be admitted within {LIVE_BOUND:?}" + ); + stream + } + + /// Whether the free permits reach `count` within [`LIVE_BOUND`]. + async fn permits_reach(&self, count: usize) -> bool { + let started = std::time::Instant::now(); + while self.permits.available_permits() != count { + if started.elapsed() > LIVE_BOUND { + return false; + } + tokio::time::sleep(Duration::from_millis(5)).await; + } + true + } + + async fn stop(self) { + self.handle.stop(false).await; + } +} + +impl Drop for LiveServer { + fn drop(&mut self) { + // `stop` sends its command before it returns the future, so a test + // that panics before its own `stop` still asks the server to end. + drop(self.handle.stop(false)); + } +} + +/// A connection reset before the client closes its sending side drops +/// its handler, which returns the parse permit. This reads only the +/// permit: that a dropped handler also cancels its parse, through +/// `CancelOnDrop`, is what `test_run_parse_dropped_future_stops_its_parse` +/// pins, since the server shows no trace of a parse left running on its +/// blocking pool. The parse and the deadline both run far past the bound, +/// so only the reset can end the handler in time. expected: the permit is +/// back within the bound. An ordinary close in place of the reset keeps +/// the handler until its deadline and fails. +#[actix_rt::test] +async fn test_live_server_reset_drops_the_handler() { + // Far past `LIVE_BOUND`, so the deadline cannot be what ends it. + const DEADLINE: Duration = Duration::from_secs(60); + + let server = LiveServer::start(DEADLINE); + let stream = server.send_slow_request().await; + stream + .set_zero_linger() + .expect("SO_LINGER 0 makes the close a reset"); + drop(stream); + assert!( + server.permits_reach(1).await, + "a reset connection must drop its handler within {LIVE_BOUND:?}" + ); + server.stop().await; +} + +/// HTTP/1 lets a client close its sending side (FIN) once its request is +/// out and still read the response, so a FIN does not end the handler: +/// it runs to its deadline, whose `504` the half-closed client receives, +/// and only then does `CancelOnDrop` stop the parse. A client that closes +/// both sides sends the same FIN, so its request also runs to the +/// deadline. expected: a `504` response, read after the FIN. +#[actix_rt::test] +async fn test_live_server_half_closed_client_gets_its_response() { + use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _}; + + // Short, since the handler runs until it. + const DEADLINE: Duration = Duration::from_secs(2); + + let server = LiveServer::start(DEADLINE); + let mut stream = server.send_slow_request().await; + stream.shutdown().await.expect("half-close the connection"); + let mut response = Vec::new(); + tokio::time::timeout(LIVE_BOUND, stream.read_to_end(&mut response)) + .await + .expect("the response must arrive within the bound") + .expect("read the response"); + let response = String::from_utf8_lossy(&response); + assert!( + response.starts_with("HTTP/1.1 504"), + "a half-closed client must get the deadline's 504, got: {response}" + ); + server.stop().await; +} + +/// A timed-out request's AST export stops as its parse does. An unclosed +/// nested Tcl `expr` parses at once but recovers into one `ERROR` node +/// whose every child's field is read, which is quadratic in the nesting +/// (#1942), so the export, not the parse, outlives the deadline. +/// expected: the parse finished whole, and the export, cancelled at the +/// deadline, yields no tree well inside the bound; the uncancelled export +/// ran for 24 s in a debug build. +#[actix_rt::test] +async fn test_run_parse_timeout_stops_the_orphaned_export() { + // Parentheses of the unclosed `expr`, far more than export inside the + // bound below. + const DEPTH: usize = 100_000; + // How long the orphaned export may outlive the deadline. + const ORPHAN_BOUND: Duration = Duration::from_secs(10); + + let config = web::Data::new(ParseConfig { + timeout: Some(Duration::from_millis(500)), + semaphore: Arc::new(Semaphore::new(4)), + orphaned_tasks: Arc::new(AtomicUsize::new(0)), + max_orphaned_tasks: 64, + max_body_size: TEST_MAX_BODY_SIZE, + }); + let code = format!("expr {{{}1{}\n", "(".repeat(DEPTH), ")".repeat(DEPTH)); + let (exported, export_end) = std::sync::mpsc::channel::<(bool, bool)>(); + let err = run_parse(&config, "req-export", move || { + let ast = big_code_analysis::Ast::parse(big_code_analysis::Source::new( + big_code_analysis::LANG::Tcl, + code.as_bytes(), + )) + .expect("the tcl feature is enabled"); + // A cancelled parse yields the empty tree, which ends at byte 0. + let parsed = ast.root_node().end_byte() != 0; + let tree = ast.dump(AstCfg { + id: String::new(), + language: String::new(), + comment: false, + span: false, + }); + let _ = exported.send((parsed, tree.root.is_none())); + }) + .await + .unwrap_err(); + assert_eq!(err.error_response().status(), StatusCode::GATEWAY_TIMEOUT); + + let (parsed, cancelled) = + tokio::task::spawn_blocking(move || export_end.recv_timeout(ORPHAN_BOUND)) + .await + .expect("the waiting task must not panic") + .expect("the orphaned export must stop within the bound"); + assert!(parsed, "the parse must finish inside the deadline"); + assert!(cancelled, "the orphaned export must have been cancelled"); +} + #[actix_rt::test] async fn test_run_parse_rejects_with_503_when_orphan_threshold_exceeded() { // Pre-fill the counter to the threshold. diff --git a/big-code-analysis-web/tests/cli_smoke.rs b/big-code-analysis-web/tests/cli_smoke.rs index 834413196..33dc8d765 100644 --- a/big-code-analysis-web/tests/cli_smoke.rs +++ b/big-code-analysis-web/tests/cli_smoke.rs @@ -17,6 +17,26 @@ fn help_prints_usage_with_renamed_binary() { .stdout(predicate::str::contains("--port")); } +/// No issue-tracker reference (`#707`) may reach `bca-web --help`, or the +/// man page generated from it: provenance belongs in `//` comments, as +/// `bca`'s own help test holds for that binary. +#[test] +fn help_carries_no_issue_references() { + let output = bin().arg("--help").output().unwrap(); + let help = String::from_utf8(output.stdout).unwrap(); + let reference = help.match_indices('#').find(|(at, _)| { + let digits = help[at + 1..] + .bytes() + .take_while(u8::is_ascii_digit) + .count(); + (2..=4).contains(&digits) + }); + assert!( + reference.is_none(), + "`bca-web --help` leaks an issue reference:\n{help}" + ); +} + #[test] fn version_prints() { bin() diff --git a/docs/development/benchmarking.md b/docs/development/benchmarking.md index 29a071a5d..dbbaa512b 100644 --- a/docs/development/benchmarking.md +++ b/docs/development/benchmarking.md @@ -251,6 +251,7 @@ 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 | +| `dump/tcl-expr-parens` | Tcl | width | the export's field read under a flat `expr` whose children sit in nested hidden rules, asked only where a wide node maps a field (#1938) | 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 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 | @@ -837,6 +838,7 @@ larger share everywhere, 20-30 %: | `ops_inner` lends no `FoldCache` | `ops/tcl-wide-erroring-eval` | 0.99-1.01 | 2.01-2.22 | 10.3-10.4 ms clean against 7.8-16.2 s | | `AncestorIter` drops the cache | `halstead/tcl-wide-erroring-eval` | (same) | 2.03-2.05 | 7.6-8.9 s; the dump and count rows stay at 1.0, since neither reaches the question through an ancestor | | `act_on_node` lends no `FoldCache` | `count/tcl-wide-erroring-eval` | 0.98-1.03 | 2.01-2.05 | 6.9-7.7 ms clean against 8.1-8.8 s | +| the export reads every child's field (#1938) | `dump/tcl-expr-parens` | 0.50 | 1.95 | 16 000 parentheses; 9.9 ms against 623 ms, one run | Each band is three runs at the top rung; the regressed spreads are wide because a 9 s cell shares the host with whatever else is running. diff --git a/enums/Cargo.lock b/enums/Cargo.lock index 7e47489cd..4c572984b 100644 --- a/enums/Cargo.lock +++ b/enums/Cargo.lock @@ -110,7 +110,7 @@ dependencies = [ [[package]] name = "bca-tree-sitter-ccomment" -version = "2.5.2" +version = "2.6.0" dependencies = [ "cc", "tree-sitter-language", @@ -118,7 +118,7 @@ dependencies = [ [[package]] name = "bca-tree-sitter-mozcpp" -version = "2.5.2" +version = "2.6.0" dependencies = [ "cc", "tree-sitter-cpp", @@ -127,7 +127,7 @@ dependencies = [ [[package]] name = "bca-tree-sitter-mozjs" -version = "2.5.2" +version = "2.6.0" dependencies = [ "cc", "tree-sitter-javascript", @@ -136,7 +136,7 @@ dependencies = [ [[package]] name = "bca-tree-sitter-preproc" -version = "2.5.2" +version = "2.6.0" dependencies = [ "cc", "tree-sitter-language", @@ -144,7 +144,7 @@ dependencies = [ [[package]] name = "bca-tree-sitter-tcl" -version = "2.5.2" +version = "2.6.0" dependencies = [ "cc", "tree-sitter-language", @@ -218,7 +218,7 @@ dependencies = [ [[package]] name = "enums" -version = "2.5.2" +version = "2.6.0" dependencies = [ "askama", "bca-tree-sitter-ccomment", diff --git a/enums/Cargo.toml b/enums/Cargo.toml index 4e8876b1c..dcdd02e08 100644 --- a/enums/Cargo.toml +++ b/enums/Cargo.toml @@ -12,7 +12,7 @@ [package] name = "enums" -version = "2.5.2" +version = "2.6.0" publish = false authors = ["Calixte Denizet "] edition = "2024" @@ -59,11 +59,11 @@ tree-sitter-c = "=0.24.2" # Vendored grammar forks — see ../Cargo.toml for rationale on the # `package = ...` alias trick that preserves the `tree_sitter_` # import path while the published crate name is `bca-tree-sitter-`. -tree-sitter-tcl = { package = "bca-tree-sitter-tcl", path = "../tree-sitter-tcl", version = "=2.5.2" } -tree-sitter-preproc = { package = "bca-tree-sitter-preproc", path = "../tree-sitter-preproc", version = "=2.5.2" } -tree-sitter-ccomment = { package = "bca-tree-sitter-ccomment", path = "../tree-sitter-ccomment", version = "=2.5.2" } -tree-sitter-mozcpp = { package = "bca-tree-sitter-mozcpp", path = "../tree-sitter-mozcpp", version = "=2.5.2" } -tree-sitter-mozjs = { package = "bca-tree-sitter-mozjs", path = "../tree-sitter-mozjs", version = "=2.5.2" } +tree-sitter-tcl = { package = "bca-tree-sitter-tcl", path = "../tree-sitter-tcl", version = "=2.6.0" } +tree-sitter-preproc = { package = "bca-tree-sitter-preproc", path = "../tree-sitter-preproc", version = "=2.6.0" } +tree-sitter-ccomment = { package = "bca-tree-sitter-ccomment", path = "../tree-sitter-ccomment", version = "=2.6.0" } +tree-sitter-mozcpp = { package = "bca-tree-sitter-mozcpp", path = "../tree-sitter-mozcpp", version = "=2.6.0" } +tree-sitter-mozjs = { package = "bca-tree-sitter-mozjs", path = "../tree-sitter-mozjs", version = "=2.6.0" } # Mirrors [workspace.lints] in ../Cargo.toml. `enums` is excluded from # that workspace (see [workspace].exclude there), so it cannot inherit diff --git a/fuzz/Cargo.lock b/fuzz/Cargo.lock index 6b9293e61..3fdb49d59 100644 --- a/fuzz/Cargo.lock +++ b/fuzz/Cargo.lock @@ -34,7 +34,7 @@ checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" [[package]] name = "bca-tree-sitter-ccomment" -version = "2.5.2" +version = "2.6.0" dependencies = [ "cc", "tree-sitter-language", @@ -42,7 +42,7 @@ dependencies = [ [[package]] name = "bca-tree-sitter-mozcpp" -version = "2.5.2" +version = "2.6.0" dependencies = [ "cc", "tree-sitter-cpp", @@ -51,7 +51,7 @@ dependencies = [ [[package]] name = "bca-tree-sitter-mozjs" -version = "2.5.2" +version = "2.6.0" dependencies = [ "cc", "tree-sitter-javascript", @@ -60,7 +60,7 @@ dependencies = [ [[package]] name = "bca-tree-sitter-preproc" -version = "2.5.2" +version = "2.6.0" dependencies = [ "cc", "tree-sitter-language", @@ -68,7 +68,7 @@ dependencies = [ [[package]] name = "bca-tree-sitter-tcl" -version = "2.5.2" +version = "2.6.0" dependencies = [ "cc", "tree-sitter-language", @@ -76,7 +76,7 @@ dependencies = [ [[package]] name = "big-code-analysis" -version = "2.5.2" +version = "2.6.0" dependencies = [ "big-code-analysis-ast", "crossbeam", @@ -92,7 +92,7 @@ dependencies = [ [[package]] name = "big-code-analysis-ast" -version = "2.5.2" +version = "2.6.0" dependencies = [ "aho-corasick", "bca-tree-sitter-ccomment", diff --git a/man/bca-check.1 b/man/bca-check.1 index 193ca0494..7a2d1c20c 100644 --- a/man/bca-check.1 +++ b/man/bca-check.1 @@ -1,6 +1,6 @@ .ie \n(.g .ds Aq \(aq .el .ds Aq ' -.TH BCA-CHECK 1 "big-code-analysis 2.5.2" "big-code-analysis Manual" +.TH BCA-CHECK 1 "big-code-analysis 2.6.0" "big-code-analysis Manual" .SH NAME bca\-check \- Check per\-function metrics against thresholds. Exits 2 when any threshold is exceeded; reserve exit 1 for tool errors so CI can distinguish "metric regression" from "tool crashed". `\-\-exit\-codes=tiered` opts into tiered codes (2\-5) that split the violation case by severity: 2 new offenders, 3 regressions, 4 both, 5 a hard breach at the soft tier .SH SYNOPSIS diff --git a/man/bca-count.1 b/man/bca-count.1 index 181b90579..17bda138b 100644 --- a/man/bca-count.1 +++ b/man/bca-count.1 @@ -1,6 +1,6 @@ .ie \n(.g .ds Aq \(aq .el .ds Aq ' -.TH BCA-COUNT 1 "big-code-analysis 2.5.2" "big-code-analysis Manual" +.TH BCA-COUNT 1 "big-code-analysis 2.6.0" "big-code-analysis Manual" .SH NAME bca\-count \- Count nodes of one or more types .SH SYNOPSIS diff --git a/man/bca-diff-baseline.1 b/man/bca-diff-baseline.1 index d60bbd829..90707d355 100644 --- a/man/bca-diff-baseline.1 +++ b/man/bca-diff-baseline.1 @@ -1,6 +1,6 @@ .ie \n(.g .ds Aq \(aq .el .ds Aq ' -.TH BCA-DIFF-BASELINE 1 "big-code-analysis 2.5.2" "big-code-analysis Manual" +.TH BCA-DIFF-BASELINE 1 "big-code-analysis 2.6.0" "big-code-analysis Manual" .SH NAME bca\-diff\-baseline \- Diff two `.bca\-baseline.toml` files and report what was added, removed, worsened, or improved. Replaces the in\-the\-head TOML diff parsing the book\*(Aqs PR\-review recipe used to walk through. Exits 0 on success by default — the diff is informational, not a gate. With `\-\-exit\-code`, exits 2 when the filtered diff is non\-empty .SH SYNOPSIS diff --git a/man/bca-diff.1 b/man/bca-diff.1 index 90eed1a6f..a94dfe651 100644 --- a/man/bca-diff.1 +++ b/man/bca-diff.1 @@ -1,6 +1,6 @@ .ie \n(.g .ds Aq \(aq .el .ds Aq ' -.TH BCA-DIFF 1 "big-code-analysis 2.5.2" "big-code-analysis Manual" +.TH BCA-DIFF 1 "big-code-analysis 2.6.0" "big-code-analysis Manual" .SH NAME bca\-diff \- Compare two metric\-output runs and report, per metric, which files changed (old to new), plus files added/removed between the two sets and metric fields present on one side only, which are listed rather than compared against `0`. Each side is a per\-file JSON file, the aggregate file `bca metrics \-O json \-\-output FILE` writes, or a directory tree of either (the form `bca metrics \-O json \-\-output\-dir DIR` writes). Replaces the grammar\-bump glue chain — the external `json\-minimal\-tests` binary plus `split\-minimal\-tests.py` — with one native command. Exits 0 on success by default; the diff is informational, not a gate. With `\-\-exit\-code`, exits 2 when the filtered diff is non\-empty .SH SYNOPSIS diff --git a/man/bca-dump.1 b/man/bca-dump.1 index 835d0ae61..6502210a9 100644 --- a/man/bca-dump.1 +++ b/man/bca-dump.1 @@ -1,6 +1,6 @@ .ie \n(.g .ds Aq \(aq .el .ds Aq ' -.TH BCA-DUMP 1 "big-code-analysis 2.5.2" "big-code-analysis Manual" +.TH BCA-DUMP 1 "big-code-analysis 2.6.0" "big-code-analysis Manual" .SH NAME bca\-dump \- Dump the AST to stdout. Each file\*(Aqs tree is prefixed with a `== ==` banner so a multi\-file dump is attributable. Requires an explicit path — unlike the other walking subcommands, bare `bca dump` errors instead of dumping the whole current directory (a whole\-tree AST dump has no plausible use) .SH SYNOPSIS diff --git a/man/bca-exemptions.1 b/man/bca-exemptions.1 index 017a0de00..2fb651d80 100644 --- a/man/bca-exemptions.1 +++ b/man/bca-exemptions.1 @@ -1,6 +1,6 @@ .ie \n(.g .ds Aq \(aq .el .ds Aq ' -.TH BCA-EXEMPTIONS 1 "big-code-analysis 2.5.2" "big-code-analysis Manual" +.TH BCA-EXEMPTIONS 1 "big-code-analysis 2.6.0" "big-code-analysis Manual" .SH NAME bca\-exemptions \- Audit everything the `bca check` gate skips in one view: in\-source suppression markers (`bca: suppress`, `#lizard forgives`, …), `[check.exclude]` globs, and `.bca\-baseline.toml` entries. Read\-only; always exits 0 on success .SH SYNOPSIS diff --git a/man/bca-find.1 b/man/bca-find.1 index 9b01cdc7b..3008b4eb0 100644 --- a/man/bca-find.1 +++ b/man/bca-find.1 @@ -1,6 +1,6 @@ .ie \n(.g .ds Aq \(aq .el .ds Aq ' -.TH BCA-FIND 1 "big-code-analysis 2.5.2" "big-code-analysis Manual" +.TH BCA-FIND 1 "big-code-analysis 2.6.0" "big-code-analysis Manual" .SH NAME bca\-find \- Find nodes of one or more types .SH SYNOPSIS diff --git a/man/bca-functions.1 b/man/bca-functions.1 index c8ca9288c..2e5dcaaa8 100644 --- a/man/bca-functions.1 +++ b/man/bca-functions.1 @@ -1,6 +1,6 @@ .ie \n(.g .ds Aq \(aq .el .ds Aq ' -.TH BCA-FUNCTIONS 1 "big-code-analysis 2.5.2" "big-code-analysis Manual" +.TH BCA-FUNCTIONS 1 "big-code-analysis 2.6.0" "big-code-analysis Manual" .SH NAME bca\-functions \- List functions/methods and their spans .SH SYNOPSIS diff --git a/man/bca-init.1 b/man/bca-init.1 index acf05d53c..91bc42929 100644 --- a/man/bca-init.1 +++ b/man/bca-init.1 @@ -1,6 +1,6 @@ .ie \n(.g .ds Aq \(aq .el .ds Aq ' -.TH BCA-INIT 1 "big-code-analysis 2.5.2" "big-code-analysis Manual" +.TH BCA-INIT 1 "big-code-analysis 2.6.0" "big-code-analysis Manual" .SH NAME bca\-init \- Scaffold the canonical adoption files (`bca.toml` manifest, `.bcaignore`, `.bca\-baseline.toml`) in the current directory. Replaces the six\-step copy\-paste flow from the book\*(Aqs adoption recipe. Refuses to overwrite existing files without `\-\-force` .SH SYNOPSIS diff --git a/man/bca-list-metrics.1 b/man/bca-list-metrics.1 index 5ec06e03f..f8553b4a2 100644 --- a/man/bca-list-metrics.1 +++ b/man/bca-list-metrics.1 @@ -1,6 +1,6 @@ .ie \n(.g .ds Aq \(aq .el .ds Aq ' -.TH BCA-LIST-METRICS 1 "big-code-analysis 2.5.2" "big-code-analysis Manual" +.TH BCA-LIST-METRICS 1 "big-code-analysis 2.6.0" "big-code-analysis Manual" .SH NAME bca\-list\-metrics \- List the metrics this tool can compute and exit .SH SYNOPSIS diff --git a/man/bca-metrics.1 b/man/bca-metrics.1 index f2a72ad0e..d0a4281ee 100644 --- a/man/bca-metrics.1 +++ b/man/bca-metrics.1 @@ -1,6 +1,6 @@ .ie \n(.g .ds Aq \(aq .el .ds Aq ' -.TH BCA-METRICS 1 "big-code-analysis 2.5.2" "big-code-analysis Manual" +.TH BCA-METRICS 1 "big-code-analysis 2.6.0" "big-code-analysis Manual" .SH NAME bca\-metrics \- Compute per\-file metrics and emit them in a structured format .SH SYNOPSIS diff --git a/man/bca-ops.1 b/man/bca-ops.1 index 9e9c7b4b0..8f73a066b 100644 --- a/man/bca-ops.1 +++ b/man/bca-ops.1 @@ -1,6 +1,6 @@ .ie \n(.g .ds Aq \(aq .el .ds Aq ' -.TH BCA-OPS 1 "big-code-analysis 2.5.2" "big-code-analysis Manual" +.TH BCA-OPS 1 "big-code-analysis 2.6.0" "big-code-analysis Manual" .SH NAME bca\-ops \- Extract per\-file operands and operators .SH SYNOPSIS diff --git a/man/bca-preproc.1 b/man/bca-preproc.1 index 465aaf83a..58fcc366b 100644 --- a/man/bca-preproc.1 +++ b/man/bca-preproc.1 @@ -1,6 +1,6 @@ .ie \n(.g .ds Aq \(aq .el .ds Aq ' -.TH BCA-PREPROC 1 "big-code-analysis 2.5.2" "big-code-analysis Manual" +.TH BCA-PREPROC 1 "big-code-analysis 2.6.0" "big-code-analysis Manual" .SH NAME bca\-preproc \- Generate preprocessor\-data JSON for C/C++ analysis .SH SYNOPSIS diff --git a/man/bca-report.1 b/man/bca-report.1 index 3c33ea4a5..06d9af875 100644 --- a/man/bca-report.1 +++ b/man/bca-report.1 @@ -1,6 +1,6 @@ .ie \n(.g .ds Aq \(aq .el .ds Aq ' -.TH BCA-REPORT 1 "big-code-analysis 2.5.2" "big-code-analysis Manual" +.TH BCA-REPORT 1 "big-code-analysis 2.6.0" "big-code-analysis Manual" .SH NAME bca\-report \- Generate an aggregated report across the analyzed source .SH SYNOPSIS diff --git a/man/bca-strip-comments.1 b/man/bca-strip-comments.1 index 2d6808172..8d27609c2 100644 --- a/man/bca-strip-comments.1 +++ b/man/bca-strip-comments.1 @@ -1,6 +1,6 @@ .ie \n(.g .ds Aq \(aq .el .ds Aq ' -.TH BCA-STRIP-COMMENTS 1 "big-code-analysis 2.5.2" "big-code-analysis Manual" +.TH BCA-STRIP-COMMENTS 1 "big-code-analysis 2.6.0" "big-code-analysis Manual" .SH NAME bca\-strip\-comments \- Remove comments from source files .SH SYNOPSIS diff --git a/man/bca-vcs-commit.1 b/man/bca-vcs-commit.1 index 0fc8d6c2f..25b947c07 100644 --- a/man/bca-vcs-commit.1 +++ b/man/bca-vcs-commit.1 @@ -1,6 +1,6 @@ .ie \n(.g .ds Aq \(aq .el .ds Aq ' -.TH BCA-VCS-COMMIT 1 "big-code-analysis 2.5.2" "big-code-analysis Manual" +.TH BCA-VCS-COMMIT 1 "big-code-analysis 2.6.0" "big-code-analysis Manual" .SH NAME bca\-vcs\-commit \- Score a single commit for defect\-induction risk — the just\-in\-time (JIT) defect\-prediction unit a CI gate reviews at check\-in. Emits a JSON breakdown of size / diffusion / history / experience / purpose features, their contributions, and an ordinal composite score. Window / `\-\-ref` / bot / merge / rename behaviour comes from the parent `vcs` flags. The old `jit` spelling stays a hidden alias for one release cycle .SH SYNOPSIS diff --git a/man/bca-vcs-trend.1 b/man/bca-vcs-trend.1 index 179699c64..2e931902a 100644 --- a/man/bca-vcs-trend.1 +++ b/man/bca-vcs-trend.1 @@ -1,6 +1,6 @@ .ie \n(.g .ds Aq \(aq .el .ds Aq ' -.TH BCA-VCS-TREND 1 "big-code-analysis 2.5.2" "big-code-analysis Manual" +.TH BCA-VCS-TREND 1 "big-code-analysis 2.6.0" "big-code-analysis Manual" .SH NAME bca\-vcs\-trend \- Sample the change\-history metrics at several points in time and emit a per\-file time series, surfacing whether code is improving or degrading over the project\*(Aqs life. Each point re\-anchors at the mainline tip of that moment, so it is a faithful historical snapshot. Window / `\-\-ref` / bot / merge / rename / as\-of (the most\-recent anchor) and `\-\-top` (files kept) come from the parent `vcs` flags .SH SYNOPSIS diff --git a/man/bca-vcs.1 b/man/bca-vcs.1 index e7e0c202a..27db910e5 100644 --- a/man/bca-vcs.1 +++ b/man/bca-vcs.1 @@ -1,6 +1,6 @@ .ie \n(.g .ds Aq \(aq .el .ds Aq ' -.TH BCA-VCS 1 "big-code-analysis 2.5.2" "big-code-analysis Manual" +.TH BCA-VCS 1 "big-code-analysis 2.6.0" "big-code-analysis Manual" .SH NAME bca\-vcs \- Rank files by change\-history (VCS) risk: churn, commit and author counts, ownership dilution, and bug\- / security\-fix history over a git working tree. Errors clearly outside a repo .SH SYNOPSIS diff --git a/man/bca-web.1 b/man/bca-web.1 index 720b58616..1930774e2 100644 --- a/man/bca-web.1 +++ b/man/bca-web.1 @@ -1,6 +1,6 @@ .ie \n(.g .ds Aq \(aq .el .ds Aq ' -.TH BCA-WEB 1 "big-code-analysis 2.5.2" "big-code-analysis Manual" +.TH BCA-WEB 1 "big-code-analysis 2.6.0" "big-code-analysis Manual" .SH NAME bca\-web \- Run a web server. .SH SYNOPSIS @@ -21,7 +21,7 @@ Host for the web server Port for the web server .TP \fB\-\-parse\-timeout\-secs\fR \fI\fR [default: 30] -Timeout in seconds for each parse operation. `0` disables the deadline *and* the orphaned\-task admission gate it feeds: with no timeout a parse never times out, so no task is ever orphaned and the `503` back\-pressure that sheds load under sustained pathological input never engages. Use `0` only when an unbounded parse is acceptable (issue #707) +Timeout in seconds for each parse operation. `0` disables the deadline *and* the orphaned\-task admission gate it feeds: with no timeout a parse never times out, so no task is ever orphaned and the `503` back\-pressure that sheds load under sustained pathological input never engages. Use `0` only when an unbounded parse is acceptable .TP \fB\-\-cors\fR \fI\fR Enable CORS for the given origins (off by default). @@ -34,6 +34,6 @@ Print help (see a summary with \*(Aq\-h\*(Aq) \fB\-V\fR, \fB\-\-version\fR Print version .SH VERSION -v2.5.2 +v2.6.0 .SH AUTHORS Calixte Denizet , Elijah Zupancic diff --git a/man/bca.1 b/man/bca.1 index 8c8d0b434..3f58edfc5 100644 --- a/man/bca.1 +++ b/man/bca.1 @@ -1,6 +1,6 @@ .ie \n(.g .ds Aq \(aq .el .ds Aq ' -.TH BCA 1 "big-code-analysis 2.5.2" "big-code-analysis Manual" +.TH BCA 1 "big-code-analysis 2.6.0" "big-code-analysis Manual" .SH NAME bca \- Analyze source code. .SH SYNOPSIS @@ -85,6 +85,6 @@ Every other subcommand exits 0 on success and 1 on error. Migrating from the flag\-style CLI? See the migration guide: https://dekobon.github.io/big\-code\-analysis/migration.html .SH VERSION -v2.5.2 +v2.6.0 .SH AUTHORS Calixte Denizet , Elijah Zupancic diff --git a/src/lib.rs b/src/lib.rs index e9304c163..46223caa4 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -302,6 +302,10 @@ pub use crate::output::{ // for the CLI and the scaling bench (#1416). #[doc(hidden)] pub use crate::output::{dump_found_with_color, write_found}; +// The flag `bca-web` stops a timed-out request's parse and AST export +// with; hidden because it exists for that crate (#1939). +#[doc(hidden)] +pub use big_code_analysis_ast::cancel::ParseCancel; // --- AST plumbing (Node) --- pub use big_code_analysis_ast::Node; diff --git a/src/metrics/npa.rs b/src/metrics/npa.rs index 9e43809f9..045137e15 100644 --- a/src/metrics/npa.rs +++ b/src/metrics/npa.rs @@ -4779,6 +4779,44 @@ mod tests { .expect("the target walk must not overflow a 512 KiB stack"); } + // A class-level chain `a0 = a1 = … = 1` nests one `Assignment` per + // link, and the reader took one frame per link until it was made a + // loop: a few thousand links aborted a release `bca` (the depth varies + // with the build). Run on a small stack so a reintroduced recursion + // aborts here. Measured with the recursion restored, in the dev + // profile the tests build: it overflows at about 2,220 links on this + // 512 KiB stack, so `DEPTH` is ~9x past it. Each link names a + // distinct attribute so `seen` cannot absorb one a walk stopped short + // of. + // + // expected: one attribute per link — na = npa = DEPTH. + #[cfg(feature = "python")] + #[test] + fn python_long_chained_class_assignment_does_not_overflow_the_stack() { + use std::fmt::Write as _; + // Links in the chain, far past what the stack below holds at one + // frame per link. + const DEPTH: u64 = 20_000; + // A deliberately small test-thread stack. + const SMALL_STACK: usize = 512 * 1024; + let mut source = String::from("class C:\n "); + for i in 0..DEPTH { + write!(source, "a{i} = ").expect("a String takes any write"); + } + source.push_str("1\n"); + std::thread::Builder::new() + .stack_size(SMALL_STACK) + .spawn(move || { + check_metrics::(&source, "foo.py", |metric| { + assert_eq!(metric.npa.class_na_sum(), DEPTH); + assert_eq!(metric.npa.class_npa_sum(), DEPTH); + }); + }) + .expect("spawn bounded-stack thread") + .join() + .expect("the chained-assignment walk must not overflow a 512 KiB stack"); + } + /// A nested target binding a distinct attribute at every level /// counts each one (#1867). The name differs per level so `seen` /// cannot absorb a level: one name repeated would read 1 whatever @@ -5412,6 +5450,42 @@ mod tests { ); } + // `defstruct [[[ … :a … ]]]` nests one `List` per bracket, and the + // field count took one frame per level until it was given an explicit + // stack: about ten thousand levels aborted a release `bca` (the depth + // varies with the build). Run on a small stack so a reintroduced + // recursion aborts here. Measured with the recursion restored, in the + // dev profile the tests build: it overflows at about 940 levels on + // this 512 KiB stack, so `DEPTH` is ~21x past it. The one atom sits + // innermost, so a walk that stopped short of it reads 0. + // + // expected: the innermost atom is the one field — na = npa = 1. + #[cfg(feature = "elixir")] + #[test] + fn elixir_deeply_nested_defstruct_list_does_not_overflow_the_stack() { + // Bracket levels around the atom, far past what the stack below + // holds at one frame per level. + const DEPTH: usize = 20_000; + // A deliberately small test-thread stack. + const SMALL_STACK: usize = 512 * 1024; + let source = format!( + "defmodule M do\n defstruct {}:a{}\nend\n", + "[".repeat(DEPTH), + "]".repeat(DEPTH) + ); + std::thread::Builder::new() + .stack_size(SMALL_STACK) + .spawn(move || { + check_metrics::(&source, "foo.ex", |metric| { + assert_eq!(metric.npa.class_na_sum(), 1); + assert_eq!(metric.npa.class_npa_sum(), 1); + }); + }) + .expect("spawn bounded-stack thread") + .join() + .expect("the defstruct field walk must not overflow a 512 KiB stack"); + } + /// The `Npa` half of the #1088 simplification: a `defmodule` inside /// a `quote` template still opens a class, so its `defstruct` fields /// are still counted. diff --git a/src/metrics/npa/elixir.rs b/src/metrics/npa/elixir.rs index 3a18a97e0..06f1991fe 100644 --- a/src/metrics/npa/elixir.rs +++ b/src/metrics/npa/elixir.rs @@ -105,19 +105,26 @@ fn count_defstruct_fields(call: &Node) -> usize { fn count_field_entries(node: &Node) -> usize { use Elixir as E; - node.children() - .map(|child| match child.kind_id().into() { + // The wrappers nest as deep as the source brackets them, so they are + // opened from an explicit stack: a recursion per level overflowed the + // stack on deeply nested lists. Only the total is kept, so the order + // the stack visits them in does not matter. + let mut fields = 0; + let mut pending: Vec = node.children().collect(); + while let Some(child) = pending.pop() { + match child.kind_id().into() { // Bare-list form (`defstruct [:a, :b]`): each atom is a // field. Keyword form (`defstruct a: 1, b: 2`): each // `Pair` is a field. // role-bypass: allow(StringLit) — the field *name* a quoted atom spells, // as a bare one does, not whether it is a literal - E::Atom | E::QuotedAtom | E::Atom2 | E::Pair => 1, + E::Atom | E::QuotedAtom | E::Atom2 | E::Pair => fields += 1, // A `List` or `Keywords` may wrap the entries one level // deeper (`defstruct [a: 1, b: 2]` puts a `List` inside // `Arguments`, which then contains a `Keywords`). - E::List | E::Keywords => count_field_entries(&child), - _ => 0, - }) - .sum() + E::List | E::Keywords => pending.extend(child.children()), + _ => {} + } + } + fields } diff --git a/src/metrics/npa/python.rs b/src/metrics/npa/python.rs index 9656eeb66..2822fae53 100644 --- a/src/metrics/npa/python.rs +++ b/src/metrics/npa/python.rs @@ -165,27 +165,27 @@ fn python_collect_bound_names_from_target<'a>( code: &'a [u8], seen: &mut std::collections::HashSet<&'a [u8]>, ) { - let Some(target) = assignment.child(0) else { - return; - }; - // Every simple-name binding contributes one attribute, including names - // nested inside an unpacking pattern. An attribute target (`obj.x = …`) - // at class level is not a simple name binding and is ignored (the - // self/cls instance-attribute pass handles those). - python_walk_target_elements(&target, &mut |element| { - if element.kind_id() == Python::Identifier - && let Some(name) = code.get(element.start_byte()..element.end_byte()) - { - seen.insert(name); - } - }); // Chained `a = b = 3`: the right operand is itself a nested - // `Assignment`, whose own target binds another name. Recurse so - // every link in the chain is counted. - if let Some(value) = assignment.child(assignment.child_count().saturating_sub(1)) - && value.kind_id() == Python::Assignment - { - python_collect_bound_names_from_target(&value, code, seen); + // `Assignment`, whose own target binds another name. The chain is as + // long as the source makes it, so its links are iterated, not recursed + // into: one frame per link overflowed a worker's stack within a few + // thousand links. + let chain = std::iter::successors(Some(*assignment), |link| { + link.child(link.child_count().saturating_sub(1)) + .filter(|value| value.kind_id() == Python::Assignment) + }); + for target in chain.filter_map(|link| link.child(0)) { + // Every simple-name binding contributes one attribute, including + // names nested inside an unpacking pattern. An attribute target + // (`obj.x = …`) at class level is not a simple name binding and is + // ignored (the self/cls instance-attribute pass handles those). + python_walk_target_elements(&target, &mut |element| { + if element.kind_id() == Python::Identifier + && let Some(name) = code.get(element.start_byte()..element.end_byte()) + { + seen.insert(name); + } + }); } } diff --git a/src/output/csv.rs b/src/output/csv.rs index 1322daaa2..76dbbe5a7 100644 --- a/src/output/csv.rs +++ b/src/output/csv.rs @@ -242,9 +242,14 @@ fn write_space_rows( path_str: &str, space: &FuncSpace, ) -> io::Result<()> { - write_one_row(wtr, path_str, space)?; - for child in &space.spaces { - write_space_rows(wtr, path_str, child)?; + // Spaces nest as deep as the source's functions, so the rows are + // written from an explicit stack: one frame per level aborted the + // process on a few tens of thousands of nested closures. Children are + // pushed in reverse so `pop()` keeps the depth-first source order. + let mut pending = vec![space]; + while let Some(space) = pending.pop() { + write_one_row(wtr, path_str, space)?; + pending.extend(space.spaces.iter().rev()); } Ok(()) } @@ -580,6 +585,78 @@ mod tests { assert_eq!(names, vec!["root", "outer", "inner", "sibling"]); } + /// A sink that fails partway through stops the row walk and reports + /// the failure rather than writing on. The rows outgrow the CSV + /// writer's buffer long before the walk ends, so the failure surfaces + /// from a row in the middle of the walk, not from the final flush. + #[test] + fn a_failing_sink_stops_the_row_walk() { + // Nesting levels, enough rows to overflow the writer's buffer + // many times over. + const DEPTH: usize = 2_000; + let mut space = empty_space("leaf", SpaceKind::Function, 1, 1); + for level in 0..DEPTH { + let mut outer = empty_space(&format!("l{level}"), SpaceKind::Function, 1, 1); + outer.spaces.push(space); + space = outer; + } + let mut full = crate::output::test_support::FailAfter::new(usize::MAX); + write_csv(&space, Path::new("a.js"), &mut full).expect("an unlimited sink takes every row"); + let mut failing = crate::output::test_support::FailAfter::new(0); + let err = write_csv(&space, Path::new("a.js"), &mut failing) + .expect_err("a sink that refuses every write fails the render"); + assert_eq!(err.kind(), std::io::ErrorKind::BrokenPipe); + assert!( + failing.attempts() < full.attempts(), + "the walk must stop at the first failure: {} attempts against {}", + failing.attempts(), + full.attempts() + ); + } + + // A space nested DEPTH levels deep, as `x = ()=>()=>…1;` produces in + // JavaScript, writes one row per level. The rows came from one frame + // per level until the walk kept its own stack, and some 32,000 nested + // arrow functions aborted a release `bca metrics -O csv` (the depth + // varies with the build). Run on a small stack so a reintroduced + // recursion aborts here. Measured with the recursion restored, in the + // dev profile the tests build: it overflows at about 5,150 levels on + // this 512 KiB stack, so `DEPTH` is ~10x past it. Each level carries + // its own name, so a walk that left the nesting order fails too. + // + // expected: one row per level, `l0` … `l49999` in nesting order. + #[test] + fn deeply_nested_spaces_do_not_overflow_the_stack() { + // Nesting levels, far past what the stack below holds at one + // frame per level. + const DEPTH: usize = 50_000; + // A deliberately small test-thread stack. + const SMALL_STACK: usize = 512 * 1024; + let mut space = empty_space(&format!("l{}", DEPTH - 1), SpaceKind::Function, 1, 1); + for level in (0..DEPTH - 1).rev() { + let mut outer = empty_space(&format!("l{level}"), SpaceKind::Function, 1, 1); + outer.spaces.push(space); + space = outer; + } + std::thread::Builder::new() + .stack_size(SMALL_STACK) + .spawn(move || { + let out = render(&space, Path::new("a.js")); + let names: Vec<&str> = out + .lines() + .skip(1) // header + .map(|line| line.split(',').nth(1).unwrap_or("")) + .collect(); + assert_eq!(names.len(), DEPTH); + for (level, name) in names.iter().enumerate() { + assert_eq!(*name, format!("l{level}")); + } + }) + .expect("spawn bounded-stack thread") + .join() + .expect("the CSV row walk must not overflow a 512 KiB stack"); + } + #[test] fn rfc_4180_quoting_handled_by_csv_crate() { // Names with commas, double-quotes and newlines must round-trip diff --git a/src/output/snapshots/big_code_analysis__output__sarif__tests__sarif_empty.snap b/src/output/snapshots/big_code_analysis__output__sarif__tests__sarif_empty.snap index a124318c3..0701bc837 100644 --- a/src/output/snapshots/big_code_analysis__output__sarif__tests__sarif_empty.snap +++ b/src/output/snapshots/big_code_analysis__output__sarif__tests__sarif_empty.snap @@ -10,7 +10,7 @@ expression: "render(&[])" "tool": { "driver": { "name": "big-code-analysis", - "version": "2.5.2", + "version": "2.6.0", "rules": [] } }, diff --git a/src/output/snapshots/big_code_analysis__output__sarif__tests__sarif_multi.snap b/src/output/snapshots/big_code_analysis__output__sarif__tests__sarif_multi.snap index 2562f83a7..88e8b1ee0 100644 --- a/src/output/snapshots/big_code_analysis__output__sarif__tests__sarif_multi.snap +++ b/src/output/snapshots/big_code_analysis__output__sarif__tests__sarif_multi.snap @@ -10,7 +10,7 @@ expression: render(&offenders) "tool": { "driver": { "name": "big-code-analysis", - "version": "2.5.2", + "version": "2.6.0", "rules": [ { "id": "cognitive", diff --git a/tests/output_formats/snapshots/output_formats__sarif_test__sarif_multi_offender.snap b/tests/output_formats/snapshots/output_formats__sarif_test__sarif_multi_offender.snap index abb8fc1a4..30339411d 100644 --- a/tests/output_formats/snapshots/output_formats__sarif_test__sarif_multi_offender.snap +++ b/tests/output_formats/snapshots/output_formats__sarif_test__sarif_multi_offender.snap @@ -10,7 +10,7 @@ expression: out "tool": { "driver": { "name": "big-code-analysis", - "version": "2.5.2", + "version": "2.6.0", "rules": [ { "id": "cyclomatic", diff --git a/tests/output_formats/snapshots/output_formats__sarif_test__sarif_zero_offenders.snap b/tests/output_formats/snapshots/output_formats__sarif_test__sarif_zero_offenders.snap index 821a5386e..cfd5db0c0 100644 --- a/tests/output_formats/snapshots/output_formats__sarif_test__sarif_zero_offenders.snap +++ b/tests/output_formats/snapshots/output_formats__sarif_test__sarif_zero_offenders.snap @@ -10,7 +10,7 @@ expression: out "tool": { "driver": { "name": "big-code-analysis", - "version": "2.5.2", + "version": "2.6.0", "rules": [] } }, diff --git a/tree-sitter-ccomment/Cargo.lock b/tree-sitter-ccomment/Cargo.lock index 22a1f12ff..740666506 100644 --- a/tree-sitter-ccomment/Cargo.lock +++ b/tree-sitter-ccomment/Cargo.lock @@ -13,7 +13,7 @@ dependencies = [ [[package]] name = "bca-tree-sitter-ccomment" -version = "2.5.2" +version = "2.6.0" dependencies = [ "cc", "tree-sitter", diff --git a/tree-sitter-ccomment/Cargo.toml b/tree-sitter-ccomment/Cargo.toml index df1be852e..225f1a679 100644 --- a/tree-sitter-ccomment/Cargo.toml +++ b/tree-sitter-ccomment/Cargo.toml @@ -13,7 +13,7 @@ [package] name = "bca-tree-sitter-ccomment" description = "Ccomment grammar for the tree-sitter parsing library (big-code-analysis fork)" -version = "2.5.2" +version = "2.6.0" authors = [ "Calixte Denizet ", "Elijah Zupancic ", diff --git a/tree-sitter-ccomment/bindings/rust/README.md b/tree-sitter-ccomment/bindings/rust/README.md index 7b2e7e898..83552ec97 100644 --- a/tree-sitter-ccomment/bindings/rust/README.md +++ b/tree-sitter-ccomment/bindings/rust/README.md @@ -13,7 +13,7 @@ To use this crate, add it to the `[dependencies]` section of your ``` toml [dependencies] tree-sitter = "0.26" -bca-tree-sitter-ccomment = "2.5" +bca-tree-sitter-ccomment = "2.6" ``` Typically, you will use the [LANGUAGE][] function to add this diff --git a/tree-sitter-mozcpp/Cargo.lock b/tree-sitter-mozcpp/Cargo.lock index b374a3379..76dab7ea9 100644 --- a/tree-sitter-mozcpp/Cargo.lock +++ b/tree-sitter-mozcpp/Cargo.lock @@ -13,7 +13,7 @@ dependencies = [ [[package]] name = "bca-tree-sitter-mozcpp" -version = "2.5.2" +version = "2.6.0" dependencies = [ "cc", "tree-sitter", diff --git a/tree-sitter-mozcpp/Cargo.toml b/tree-sitter-mozcpp/Cargo.toml index 9ae6ec45b..1cfec7fb3 100644 --- a/tree-sitter-mozcpp/Cargo.toml +++ b/tree-sitter-mozcpp/Cargo.toml @@ -13,7 +13,7 @@ [package] name = "bca-tree-sitter-mozcpp" description = "Mozcpp grammar for the tree-sitter parsing library (big-code-analysis fork)" -version = "2.5.2" +version = "2.6.0" authors = [ "Calixte Denizet ", "Elijah Zupancic ", diff --git a/tree-sitter-mozcpp/bindings/rust/README.md b/tree-sitter-mozcpp/bindings/rust/README.md index ec147c3a2..41bb70028 100644 --- a/tree-sitter-mozcpp/bindings/rust/README.md +++ b/tree-sitter-mozcpp/bindings/rust/README.md @@ -13,7 +13,7 @@ To use this crate, add it to the `[dependencies]` section of your ``` toml [dependencies] tree-sitter = "0.26" -bca-tree-sitter-mozcpp = "2.5" +bca-tree-sitter-mozcpp = "2.6" ``` Typically, you will use the [LANGUAGE][] function to add this diff --git a/tree-sitter-mozjs/Cargo.lock b/tree-sitter-mozjs/Cargo.lock index ff9e38cd6..6b1819fba 100644 --- a/tree-sitter-mozjs/Cargo.lock +++ b/tree-sitter-mozjs/Cargo.lock @@ -13,7 +13,7 @@ dependencies = [ [[package]] name = "bca-tree-sitter-mozjs" -version = "2.5.2" +version = "2.6.0" dependencies = [ "cc", "tree-sitter", diff --git a/tree-sitter-mozjs/Cargo.toml b/tree-sitter-mozjs/Cargo.toml index dc328a6a6..e2a84a09f 100644 --- a/tree-sitter-mozjs/Cargo.toml +++ b/tree-sitter-mozjs/Cargo.toml @@ -13,7 +13,7 @@ [package] name = "bca-tree-sitter-mozjs" description = "Mozjs grammar for the tree-sitter parsing library (big-code-analysis fork)" -version = "2.5.2" +version = "2.6.0" authors = [ "Calixte Denizet ", "Elijah Zupancic ", diff --git a/tree-sitter-mozjs/bindings/rust/README.md b/tree-sitter-mozjs/bindings/rust/README.md index 3d65b7980..3434934e9 100644 --- a/tree-sitter-mozjs/bindings/rust/README.md +++ b/tree-sitter-mozjs/bindings/rust/README.md @@ -13,7 +13,7 @@ To use this crate, add it to the `[dependencies]` section of your ``` toml [dependencies] tree-sitter = "0.26" -bca-tree-sitter-mozjs = "2.5" +bca-tree-sitter-mozjs = "2.6" ``` Typically, you will use the [language][language func] function to add this diff --git a/tree-sitter-preproc/Cargo.lock b/tree-sitter-preproc/Cargo.lock index 74af55c0f..c64d6ccc2 100644 --- a/tree-sitter-preproc/Cargo.lock +++ b/tree-sitter-preproc/Cargo.lock @@ -13,7 +13,7 @@ dependencies = [ [[package]] name = "bca-tree-sitter-preproc" -version = "2.5.2" +version = "2.6.0" dependencies = [ "cc", "tree-sitter", diff --git a/tree-sitter-preproc/Cargo.toml b/tree-sitter-preproc/Cargo.toml index d65e85e1e..f02bd11de 100644 --- a/tree-sitter-preproc/Cargo.toml +++ b/tree-sitter-preproc/Cargo.toml @@ -13,7 +13,7 @@ [package] name = "bca-tree-sitter-preproc" description = "Preproc grammar for the tree-sitter parsing library (big-code-analysis fork)" -version = "2.5.2" +version = "2.6.0" authors = [ "Calixte Denizet ", "Elijah Zupancic ", diff --git a/tree-sitter-preproc/bindings/rust/README.md b/tree-sitter-preproc/bindings/rust/README.md index fee798b26..4ce8b3ecf 100644 --- a/tree-sitter-preproc/bindings/rust/README.md +++ b/tree-sitter-preproc/bindings/rust/README.md @@ -13,7 +13,7 @@ To use this crate, add it to the `[dependencies]` section of your ``` toml [dependencies] tree-sitter = "0.26" -bca-tree-sitter-preproc = "2.5" +bca-tree-sitter-preproc = "2.6" ``` Typically, you will use the [LANGUAGE][] function to add this diff --git a/tree-sitter-tcl/Cargo.lock b/tree-sitter-tcl/Cargo.lock index cb48e70be..7eeaac4f7 100644 --- a/tree-sitter-tcl/Cargo.lock +++ b/tree-sitter-tcl/Cargo.lock @@ -13,7 +13,7 @@ dependencies = [ [[package]] name = "bca-tree-sitter-tcl" -version = "2.5.2" +version = "2.6.0" dependencies = [ "cc", "tree-sitter", diff --git a/tree-sitter-tcl/Cargo.toml b/tree-sitter-tcl/Cargo.toml index 9a12209ff..27d75ed17 100644 --- a/tree-sitter-tcl/Cargo.toml +++ b/tree-sitter-tcl/Cargo.toml @@ -13,7 +13,7 @@ [package] name = "bca-tree-sitter-tcl" description = "Tcl grammar for the tree-sitter parsing library (big-code-analysis fork)" -version = "2.5.2" +version = "2.6.0" authors = [ "Lewis Russell", "Elijah Zupancic ", diff --git a/tree-sitter-tcl/bindings/rust/README.md b/tree-sitter-tcl/bindings/rust/README.md index fcec47b4e..485837155 100644 --- a/tree-sitter-tcl/bindings/rust/README.md +++ b/tree-sitter-tcl/bindings/rust/README.md @@ -14,7 +14,7 @@ To use this crate, add it to the `[dependencies]` section of your ``` toml [dependencies] tree-sitter = "0.26" -bca-tree-sitter-tcl = "2.5" +bca-tree-sitter-tcl = "2.6" ``` Typically, you will use the [LANGUAGE][] constant to add this grammar