From db11b540b1b4c60926c175cb5cd043c7555b99f3 Mon Sep 17 00:00:00 2001 From: dev Date: Sat, 21 Nov 2026 19:24:13 +0000 Subject: tools,tests: count the pub(crate) items nothing outside their own file reaches MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `pub(crate)` was the good state in the census by decree: `priv` was reported and deliberately left out of the budget, on the grounds that a rising count of crate-internal items is progress. That is true of `pub` -> `pub(crate)` and false of the next step. A `pub(crate)` item that no file except the one that declares it ever names is offering the whole crate a thing nothing reaches, and nothing in the suite said so. `overwide` counts them. Same shape as `deadonly`, on purpose: a per-module number that may only shrink, an item allowed to stay only by name in `over_visibility.allowlist`, and the compiler fact that forces it written beside the name. `--list-overwide` names every one with its file:line, and `tests/architecture.rs` mirrors the definition so the two implementations are cross-checked against each other, the way the census already is. Baseline, before any item is narrowed: 35 of 170 `pub(crate)` declarations are over-wide. Eight of them are already argued — a `pub(crate)` field cannot carry a private type, privacy does not reach up to a parent module or across to a sibling one, and `pub(super)` is not a form this crate admits — which leaves 27 unargued, and 27 is what the budget now holds. The count is a grep and a grep is a lead, not a verdict: the verdict is the compiler's, and it has to be asked under both profiles, because the `cfg(not(feature = "test-support"))` half of a feature-conditional declaration is never compiled by `cargo check --all-targets`. --- tests/architecture-budget.json | 137 ++++++++++++++++++++------- tests/architecture.rs | 172 +++++++++++++++++++++++++++++++++- tools/arch-census.py | 206 ++++++++++++++++++++++++++++++++++++++--- 3 files changed, 465 insertions(+), 50 deletions(-) diff --git a/tests/architecture-budget.json b/tests/architecture-budget.json index 7a95341..4ac33de 100644 --- a/tests/architecture-budget.json +++ b/tests/architecture-budget.json @@ -1,24 +1,24 @@ { "dead_code": { "allowlist": { - "db.Migration": "the row type of `MIGRATIONS`, which is `pub` only under `test-support`; production walks the table through `db::migrate` without naming it", - "db.PackageRow": "what `index_packages` hands back to `http`, the publish step and the `aur-build` binary, which bind it without naming it", - "db.Subscription": "what `get_subscription` and `list_subscriptions` hand back to `watch`, `usecase`, the binary and tests/detect.rs", - "db.Unbuilt": "the attention row `approved_but_unbuilt` returns to the web UI and to tests/crash.rs", - "pkginfo.Installed": "what `parse_installed` answers with, read line by line by `pipeline` and tests/world.rs", - "pkginfo.PkgInfo": "what `parse_pkginfo` answers with; `pipeline`, `shims` and tests/world.rs read its fields, never its name", - "review.BulkItem": "one outcome of `approve::bulk`, which tests/approve.rs drives directly", - "sandbox.ProvisionRequest": "the argument of `Provisioner::provision`, the trait the public `LocalAgentProvisioner` implements", - "sandbox.Provisioner": "implemented by the test-gated public `LocalAgentProvisioner`; a private trait on a public impl is E0445", - "shims.FakeInstalled": "the whole `shims` module is `test-support`-gated, so a release build never compiles it", - "shims.FakePackage": "the whole `shims` module is `test-support`-gated, so a release build never compiles it", - "shims.Manifest": "returned by `manifest()`, which the shim tests read; the module is `test-support`-gated", - "time.VirtualClock": "lives in the `test-support`-gated clock module, behind the gated `virtualize()` that returns it", - "usecase.Checked": "what `usecase::detect` returns to the `aur-build` binary, which is a separate crate", - "usecase.GcPlan": "what `usecase::plan_gc` returns to the `aur-build` binary, which is a separate crate", - "usecase.Prepared": "what `prepare_review` and `view_review` return to the `aur-build` binary, which is a separate crate", - "watch.CheckReport": "what `detect::check_pkgbase` returns; the test tier drives it and binds the value without naming it", - "watch.StageA": "what `upstream::probe` returns; tests/ops.rs and tests/vcs.rs call `probe` directly" + "db.Migration": "the element type of `MIGRATIONS`, which is `pub` under `test-support`; narrowing it is `private_interfaces` - type `Migration` is more private than the item `MIGRATIONS`. Production walks the table through `db::migrate` without naming it", + "db.PackageRow": "what `index_packages` answers with, and `index_packages` is `pub`; narrowing the row is `private_interfaces` - type `PackageRow` is more private than the item `index_packages`. http, the publish step and the `aur-build` binary bind it without naming it", + "db.Subscription": "what `get_subscription` and `list_subscriptions` answer with, both `pub`; narrowing it is `private_interfaces` on `list_subscriptions`. `watch`, `usecase`, the binary and tests/detect.rs bind the value without naming the type", + "db.Unbuilt": "the attention row `approved_but_unbuilt` returns, and that fn is `pub`; narrowing it is `private_interfaces` on `approved_but_unbuilt`. The web UI and tests/crash.rs bind it without naming it", + "pkginfo.Installed": "what `parse_installed` answers with, and `parse_installed` is `pub`; narrowing it is `private_interfaces` on `parse_installed`. `pipeline`, `shims` and tests/world.rs read it line by line", + "pkginfo.PkgInfo": "what `parse_pkginfo` answers with, and `parse_pkginfo` is `pub`; narrowing it is `private_interfaces` on `parse_pkginfo`. `pipeline`, `shims` and tests/world.rs read its fields, never its name", + "review.BulkItem": "one outcome of `approve::bulk`, which is `pub` and which tests/approve.rs drives directly; narrowing the row is `private_interfaces` on `approve::bulk`", + "sandbox.ProvisionRequest": "the parameter of `Provisioner::provision`, a `pub` trait method - a `pub` trait method cannot take a `pub(crate)` parameter, so the compiler answers `type kata::ProvisionRequest is more private than the item kata::Provisioner::provision`", + "sandbox.Provisioner": "implemented by the test-gated `pub` `LocalAgentProvisioner` and returned by `KataBackend::bind`; a private trait on a public impl is E0445, and the compiler says `trait kata::Provisioner is more private than the item KataBackend::bind`", + "shims.FakeInstalled": "the element type of the `pub` field `Manifest::installed`, so narrowing it is `private_interfaces` on that field; the whole `shims` module is `test-support`-gated, so a release build never compiles it", + "shims.FakePackage": "the element type of the `pub` field `Manifest::packages`, so narrowing it is `private_interfaces` on that field; the whole `shims` module is `test-support`-gated, so a release build never compiles it", + "shims.Manifest": "returned by `manifest()`, which is `pub` and which seven test files read to assert what a build did; narrowing the type is `private_interfaces` on `manifest`. The module is `test-support`-gated", + "time.VirtualClock": "re-exported by the gated `pub use` that is the only public path to it; narrowing it is E0365 - `VirtualClock` is only public within the crate, and cannot be re-exported outside", + "usecase.Checked": "re-exported by `usecase`'s `pub use`, which is how the `aur-build` binary - a separate crate - names it; narrowing it is E0365, cannot be re-exported outside the crate", + "usecase.GcPlan": "re-exported by `usecase`'s `pub use` for the `aur-build` binary, a separate crate; narrowing it is E0365, cannot be re-exported outside the crate", + "usecase.Prepared": "re-exported by `usecase`'s `pub use` for the `aur-build` binary, a separate crate; narrowing it is E0365, cannot be re-exported outside the crate", + "watch.CheckReport": "what `detect::check_pkgbase` answers with, and that fn is `pub`; narrowing it is `private_interfaces` on `check_pkgbase`. The test tier drives it and binds the value without naming it", + "watch.StageA": "what `upstream::probe` answers with, and `probe` is `pub`; narrowing it is `private_interfaces` on `probe`. tests/ops.rs and tests/vcs.rs call `probe` directly" }, "deadonly": { "bin/gpg": 0, @@ -59,6 +59,7 @@ "largest": 4, "largest_file": "src/bin/gpg.rs", "lines": 4, + "overwide": 0, "priv": 0, "pub": 0, "test": 0 @@ -70,6 +71,7 @@ "largest": 4, "largest_file": "src/bin/makechrootpkg.rs", "lines": 4, + "overwide": 0, "priv": 0, "pub": 0, "test": 0 @@ -81,6 +83,7 @@ "largest": 4, "largest_file": "src/bin/makepkg.rs", "lines": 4, + "overwide": 0, "priv": 0, "pub": 0, "test": 0 @@ -92,6 +95,7 @@ "largest": 4, "largest_file": "src/bin/mkarchroot.rs", "lines": 4, + "overwide": 0, "priv": 0, "pub": 0, "test": 0 @@ -103,6 +107,7 @@ "largest": 4, "largest_file": "src/bin/pacman.rs", "lines": 4, + "overwide": 0, "priv": 0, "pub": 0, "test": 0 @@ -114,6 +119,7 @@ "largest": 4, "largest_file": "src/bin/repo-add.rs", "lines": 4, + "overwide": 0, "priv": 0, "pub": 0, "test": 0 @@ -125,6 +131,7 @@ "largest": 50, "largest_file": "src/bin/sandbox-agent.rs", "lines": 50, + "overwide": 0, "priv": 0, "pub": 0, "test": 0 @@ -133,9 +140,10 @@ "dead": 2, "deadonly": 0, "glob": 0, - "largest": 701, + "largest": 699, "largest_file": "src/config.rs", - "lines": 701, + "lines": 699, + "overwide": 1, "priv": 2, "pub": 29, "test": 2 @@ -146,7 +154,8 @@ "glob": 0, "largest": 368, "largest_file": "src/db/mod.rs", - "lines": 3897, + "lines": 3890, + "overwide": 0, "priv": 19, "pub": 189, "test": 11 @@ -155,9 +164,10 @@ "dead": 0, "deadonly": 0, "glob": 0, - "largest": 430, + "largest": 428, "largest_file": "src/error.rs", - "lines": 430, + "lines": 428, + "overwide": 0, "priv": 0, "pub": 21, "test": 0 @@ -169,6 +179,7 @@ "largest": 57, "largest_file": "src/fetch.rs", "lines": 57, + "overwide": 1, "priv": 2, "pub": 1, "test": 0 @@ -180,6 +191,7 @@ "largest": 240, "largest_file": "src/git.rs", "lines": 240, + "overwide": 0, "priv": 0, "pub": 14, "test": 0 @@ -188,9 +200,10 @@ "dead": 0, "deadonly": 0, "glob": 0, - "largest": 111, + "largest": 112, "largest_file": "src/hash.rs", - "lines": 111, + "lines": 112, + "overwide": 0, "priv": 0, "pub": 7, "test": 0 @@ -201,7 +214,8 @@ "glob": 0, "largest": 565, "largest_file": "src/http/routes/pages.rs", - "lines": 2034, + "lines": 2035, + "overwide": 1, "priv": 81, "pub": 17, "test": 5 @@ -213,6 +227,7 @@ "largest": 23, "largest_file": "src/lib.rs", "lines": 23, + "overwide": 0, "priv": 0, "pub": 0, "test": 0 @@ -224,6 +239,7 @@ "largest": 314, "largest_file": "src/main.rs", "lines": 314, + "overwide": 0, "priv": 0, "pub": 0, "test": 0 @@ -235,6 +251,7 @@ "largest": 455, "largest_file": "src/ops.rs", "lines": 455, + "overwide": 3, "priv": 5, "pub": 11, "test": 3 @@ -245,7 +262,8 @@ "glob": 0, "largest": 472, "largest_file": "src/pipeline/steps.rs", - "lines": 1411, + "lines": 1410, + "overwide": 8, "priv": 16, "pub": 21, "test": 6 @@ -257,6 +275,7 @@ "largest": 117, "largest_file": "src/pkginfo.rs", "lines": 117, + "overwide": 0, "priv": 0, "pub": 6, "test": 0 @@ -268,6 +287,7 @@ "largest": 559, "largest_file": "src/pkgver/mod.rs", "lines": 559, + "overwide": 0, "priv": 0, "pub": 7, "test": 0 @@ -279,6 +299,7 @@ "largest": 459, "largest_file": "src/recipe.rs", "lines": 459, + "overwide": 0, "priv": 0, "pub": 7, "test": 0 @@ -290,6 +311,7 @@ "largest": 301, "largest_file": "src/review/diff.rs", "lines": 915, + "overwide": 0, "priv": 4, "pub": 24, "test": 4 @@ -298,9 +320,10 @@ "dead": 7, "deadonly": 0, "glob": 0, - "largest": 508, + "largest": 507, "largest_file": "src/sandbox/kata.rs", - "lines": 1413, + "lines": 1408, + "overwide": 6, "priv": 16, "pub": 21, "test": 7 @@ -312,6 +335,7 @@ "largest": 655, "largest_file": "src/shims/mod.rs", "lines": 655, + "overwide": 7, "priv": 13, "pub": 8, "test": 4 @@ -320,9 +344,10 @@ "dead": 3, "deadonly": 0, "glob": 0, - "largest": 243, + "largest": 245, "largest_file": "src/time.rs", - "lines": 243, + "lines": 245, + "overwide": 0, "priv": 0, "pub": 13, "test": 3 @@ -334,6 +359,7 @@ "largest": 56, "largest_file": "src/urlutil.rs", "lines": 56, + "overwide": 0, "priv": 0, "pub": 1, "test": 0 @@ -345,6 +371,7 @@ "largest": 124, "largest_file": "src/usecase/reviews.rs", "lines": 405, + "overwide": 0, "priv": 0, "pub": 30, "test": 0 @@ -356,11 +383,54 @@ "largest": 296, "largest_file": "src/watch/upstream.rs", "lines": 1115, + "overwide": 0, "priv": 12, "pub": 21, "test": 4 } }, + "over_visibility": { + "allowlist": { + "db.OpenReview": "returned by `open_in` and taken by `collapse_in`, both `pub(crate)` in this file; a private type behind a `pub(crate)` signature is the `private_interfaces` warning, so the type has to be as visible as the functions that carry it", + "db.Readers": "`Db` is `pub` and its `readers` field is `pub(crate)`, and a field cannot out-reach its own type; making `Readers` private is the `private_interfaces` warning on `db::Db::readers`", + "db.ReviewSubject": "`review_subject_in` is `pub(crate)` and answers with it, and another file binds the value: with the type private that call site is `error: type ReviewSubject is private`", + "ops.EvictPlan": "`plan_retention` is `pub(crate)` and returns `Vec`; with the type private, the caller that binds that Vec in another file is `error: type EvictPlan is private`", + "pipeline.SourceIdentity": "the `pub(crate)` field `Ctx::src` has this type, and a field may not be more reachable than its type; private `SourceIdentity` is the `private_interfaces` warning on `Ctx::src`", + "review.Assessment": "`assess` is `pub(crate)` and answers with it, so a private `Assessment` is `error: type Assessment is private` at every site in another file that binds the result", + "review.LOW": "declared inside the `pub mod level` nested in risk.rs and read as `level::LOW` by the scorer in the parent module; privacy does not reach upward to a parent, and `pub(super)` is not a form this crate admits, so `pub(crate)` is the narrowest that works", + "sandbox.provision_request": "declared inside the private `kata_backend` module (kata.rs:184) and called from the sibling `#[cfg(test)] mod tests` (kata.rs:421); privacy does not cross to a sibling - E0624 - and `pub(super)` is not a form this crate admits" + }, + "overwide": { + "bin/gpg": 0, + "bin/makechrootpkg": 0, + "bin/makepkg": 0, + "bin/mkarchroot": 0, + "bin/pacman": 0, + "bin/repo-add": 0, + "bin/sandbox-agent": 0, + "config": 1, + "db": 0, + "error": 0, + "fetch": 1, + "git": 0, + "hash": 0, + "http": 1, + "lib": 0, + "main": 0, + "ops": 3, + "pipeline": 8, + "pkginfo": 0, + "pkgver": 0, + "recipe": 0, + "review": 0, + "sandbox": 6, + "shims": 7, + "time": 0, + "urlutil": 0, + "usecase": 0, + "watch": 0 + } + }, "test_surface": { "already-gated": 16, "interface": 1, @@ -372,9 +442,10 @@ "deadonly": 0, "edges": 87, "glob": 0, - "largest": 701, + "largest": 699, "largest_file": "src/config.rs", - "lines": 15684, + "lines": 15671, + "overwide": 27, "priv": 170, "pub": 448, "test": 49 diff --git a/tests/architecture.rs b/tests/architecture.rs index 3eafcdc..b32ea54 100644 --- a/tests/architecture.rs +++ b/tests/architecture.rs @@ -224,6 +224,7 @@ struct Module { test_only: usize, dead_only: usize, pub_crate: usize, + over_wide: usize, globs: usize, lines: usize, } @@ -301,6 +302,40 @@ impl Census { } } + // A `pub(crate)` item is over-wide when no file except the one that + // declares it writes its name: it offers the crate a thing nothing + // outside its own file reaches, and plain private is what it should be. + // `tests/` is not consulted — a separate crate cannot name a `pub(crate)` + // item, so a mention there says nothing. As with `dead`, a name declared + // in several files is flagged only when no file outside all of them says + // it, and the compiler, not this count, gives the verdict. + let mut pc_declared: BTreeMap> = BTreeMap::new(); + for (path, text) in &texts { + for line in text.lines() { + if let Some(name) = pub_crate_decl(line) { + pc_declared.entry(name).or_default().insert(path.clone()); + } + } + } + let over_allow = allowed_overwide_items(); + for (name, files) in &pc_declared { + let read_outside = texts + .iter() + .any(|(path, text)| !files.contains(path) && mentions(text, name)); + if read_outside { + continue; + } + for path in files { + let module = module_of(path); + // Argued, so not counted: the reason it stays `pub(crate)` is in + // the budget file next to its name, exactly as on the `pub` side. + if over_allow.contains(&format!("{module}.{name}")) { + continue; + } + modules.get_mut(&module).unwrap().over_wide += 1; + } + } + let mut edges: BTreeMap> = BTreeMap::new(); for (path, text) in &texts { let source = module_of(path); @@ -374,6 +409,27 @@ fn allowed_pub_items() -> BTreeSet { .unwrap_or_default() } +/// The `over_visibility.allowlist` keys — `module.item` for every `pub(crate)` +/// item that stays `pub(crate)` by decision, with the compiler fact beside it. +fn allowed_overwide_items() -> BTreeSet { + let path = root().join("tests/architecture-budget.json"); + let text = std::fs::read_to_string(&path).unwrap_or_else(|e| panic!("read {}: {}", path.display(), e)); + let value: serde_json::Value = serde_json::from_str(&text).expect("budget file is json"); + value + .get("over_visibility") + .and_then(|d| d.get("allowlist")) + .and_then(|a| a.as_object()) + .map(|a| { + a.keys() + .map(|k| { + assert!(!k.trim().is_empty(), "an over-wide permission key cannot be blank"); + k.clone() + }) + .collect() + }) + .unwrap_or_default() +} + /// A top-level section of the budget file, as `key -> allowed`. fn budget_section(section: &str) -> BTreeMap { let path = root().join("tests/architecture-budget.json"); @@ -513,11 +569,12 @@ fn glob_reexports_stay_on_the_allowlist() { } /// The four comparisons the ratchet makes, as `(key, actual)` pairs. -fn budgeted(row: &Module) -> [(&'static str, usize); 4] { +fn budgeted(row: &Module) -> [(&'static str, usize); 5] { [ ("pub", row.pub_items), ("dead", row.dead), ("deadonly", row.dead_only), + ("overwide", row.over_wide), ("glob", row.globs), ] } @@ -616,6 +673,7 @@ fn the_census_tool_and_this_test_agree() { ("test", mine.test_only), ("deadonly", mine.dead_only), ("priv", mine.pub_crate), + ("overwide", mine.over_wide), ("glob", mine.globs), ] { let got = row.get(key).and_then(|v| v.as_u64()).unwrap_or(u64::MAX) as usize; @@ -873,6 +931,69 @@ fn the_dead_code_allowlist_names_real_items() { ); } +/// The `over_visibility.allowlist` is a set of decisions too, and it is checked +/// the same two ways: an entry must name something that is still `pub(crate)` in +/// the module it names, and it must carry a reason worth reading. +/// +/// The first direction matters more here than on the `pub` side. A `pub(crate)` +/// item that has since gone private still matches a `module.item` key written +/// against the module's declared names, so the check has to look at the +/// `pub(crate)` declarations specifically — otherwise the permission quietly +/// re-widens the item it was left behind by. +#[test] +fn the_over_visibility_allowlist_names_real_items() { + let path = root().join("tests/architecture-budget.json"); + let text = std::fs::read_to_string(&path).unwrap_or_else(|e| panic!("read {}: {}", path.display(), e)); + let value: serde_json::Value = serde_json::from_str(&text).expect("budget file is json"); + let allow = value + .get("over_visibility") + .and_then(|d| d.get("allowlist")) + .and_then(|a| a.as_object()) + .expect("budget file has an over_visibility.allowlist object"); + + let mut pub_crate_declared: BTreeMap> = BTreeMap::new(); + for path in src_files() { + let module = module_of(&path); + for line in std::fs::read_to_string(&path).expect("read source").lines() { + if let Some(name) = pub_crate_decl(line) { + pub_crate_declared.entry(module.clone()).or_default().insert(name); + } + } + } + + let mut stale = Vec::new(); + let mut blank = Vec::new(); + for (key, reason) in allow { + let Some((module, name)) = key.split_once('.') else { + stale.push(format!("{key}: a key is `module.item`")); + continue; + }; + if reason.as_str().map(|r| r.trim().len() < 20).unwrap_or(true) { + blank.push(key.clone()); + } + if !pub_crate_declared + .get(module) + .is_some_and(|names| names.contains(name)) + { + stale.push(format!("{key} at {reason}")); + } + } + stale.sort(); + blank.sort(); + assert!( + stale.is_empty(), + "these over-wide permissions name something that is no longer a `pub(crate)`\n\ + item in that module — it went private, or it was never one:\n{}", + stale.join("\n") + ); + assert!( + blank.is_empty(), + "these over-wide permissions have no reason (or one too short to be one):\n{}\n\ + say what the compiler refuses to let go private, not that it felt safer.", + blank.join("\n") + ); +} + /// `tests/common/mod.rs` is compiled into every test binary, so the suite keeps /// a crate-level `allow(dead_code)` there — a helper used by one binary is dead /// code in the other twenty, and the lint would fire everywhere and mean @@ -1037,6 +1158,53 @@ fn the_dead_code_budget_matches_the_code() { ); } +#[test] +fn the_over_visibility_budget_matches_the_code() { + // The same self-consistency the dead-code budget is held to: the accepted + // count, the number in the `modules` section, and the number the census + // actually measures have to be one number, or the ratchet is checking a + // figure nothing reads. + let path = root().join("tests/architecture-budget.json"); + let value: serde_json::Value = + serde_json::from_str(&std::fs::read_to_string(&path).expect("read budget")).expect("budget is json"); + let modules = value.get("modules").and_then(|m| m.as_object()).expect("modules"); + let over = value + .get("over_visibility") + .and_then(|d| d.get("overwide")) + .and_then(|d| d.as_object()) + .expect("over_visibility.overwide"); + let census = Census::take(); + + let mut mismatch = Vec::new(); + for (module, row) in modules { + let stated = row.get("overwide").and_then(|v| v.as_u64()).unwrap_or(u64::MAX); + let accepted = over.get(module).and_then(|v| v.as_u64()); + let actual = census + .modules + .get(module) + .map(|m| m.over_wide as u64) + .unwrap_or(u64::MAX); + if accepted != Some(stated) || stated != actual { + mismatch.push(format!( + "{module}: over_visibility.overwide {:?}, modules.overwide {stated}, actual {actual}", + accepted + )); + } + } + for module in over.keys() { + if !modules.contains_key(module) { + mismatch.push(format!("{module}: in over_visibility.overwide, absent from modules")); + } + } + mismatch.sort(); + assert!( + mismatch.is_empty(), + "the budget contradicts itself about how many over-wide `pub(crate)` items a\n\ + module has:\n{}", + mismatch.join("\n") + ); +} + /// Two tools write one file, so neither may erase what the other owns. /// /// `tools/arch-census.py` writes the module numbers and the accepted dead-code @@ -1063,7 +1231,7 @@ fn the_budget_writers_preserve_each_other() { let after: serde_json::Value = serde_json::from_str(&std::fs::read_to_string(&tmp).expect("read temp budget")) .expect("written budget is json"); - for section in ["test_surface", "dead_code"] { + for section in ["test_surface", "dead_code", "over_visibility"] { assert!( after.get(section).is_some(), "{tool} erased the `{section}` section it does not own" diff --git a/tools/arch-census.py b/tools/arch-census.py index b734061..231073c 100755 --- a/tools/arch-census.py +++ b/tools/arch-census.py @@ -30,6 +30,17 @@ as used: `watch::upstream::resolve` looked live for as long as some unrelated db message happened to end "... to resolve". A flagged item is a question; a clean item is not always an answer. +`pub(crate)` is not automatically the narrow state. A `pub(crate)` item whose +name is never written outside the one file that declares it is *over-wide*: it +says "the whole crate may reach this" about something only its own file reaches, +and it is one keystroke away from being a hole in the module's real interface. +`overwide` counts those. The search space is `src/` only, because `tests/` is a +separate crate and cannot name a `pub(crate)` item at all, so a test mentioning +the word says nothing about crate-internal visibility. Like every other column +here the flag is a lead, not a verdict — a `pub(crate)` type that appears in a +`pub` signature in its own file cannot go private without a private-in-public +error — and the compiler, not this file, decides. + The census counts; it does not remember. What is *accepted* lives in exactly one machine-parsable file, `tests/architecture-budget.json`, which holds a `dead_code` section: the accepted `deadonly` count per module, and an `allowlist` @@ -44,12 +55,21 @@ Reported per module: test of the dead ones, the ones a test does name: pub for the test tier deadonly dead minus test: exported, and named by nobody at all priv items declared `pub(crate)`: crate-internal on purpose + overwide of those, ones no file outside the declaring file names: wider than + anything reaches, and a candidate for plain private glob `use … ::*` re-exports, which flatten a namespace and hide width lines total lines of the module, and its largest single file Reported for the crate: the `crate::x` edge set between modules, which is the dependency graph the layer map in tests/architecture.rs is allowed to be. +The over-wide count is held down the same way `deadonly` is: an item that stays +`pub(crate)` despite nothing outside its file reading it is allowed only by name, +in `over_visibility.allowlist`, with the compiler fact that forces it written +beside it. `over_visibility.overwide` is the accepted count per module, and +`--budget` fails on an excess, on an unargued item, and on a permission whose +item is gone. + `tests/architecture.rs` enforces the same two definitions against a committed budget and fails when a number grows; this tool is the human-facing report of where the numbers are and where they moved. @@ -61,6 +81,7 @@ Usage: tools/arch-census.py --budget FILE compare against a budget, exit 1 if over tools/arch-census.py --write-budget FILE write the current numbers as budget tools/arch-census.py --list-dead name every dead item, with file:line + tools/arch-census.py --list-overwide name every over-wide pub(crate) item """ import argparse @@ -81,6 +102,9 @@ PUB_CRATE_RE = re.compile(r"^\s*pub\(crate\)\s+(?:fn|struct|enum|trait|const|sta PUB_CRATE_NAME_RE = re.compile( r"^\s*pub\(crate\)\s+(?:fn|struct|enum|trait|const|static|type)\s+([A-Za-z0-9_]+)" ) +# `pub(crate) use` is a re-export, not a declaration; the same rule the `pub` +# side follows, so a re-export cannot be counted as an item that could be private. +PUB_CRATE_USE_RE = re.compile(r"^\s*pub\(crate\)\s+use\s+") GLOB_RE = re.compile(r"^\s*pub(?:\(crate\))?\s+use\s+[^\n]*::\*") EDGE_RE = re.compile(r"\bcrate::([a-z_][a-z0-9_]*)") # The binaries are separate crates, so they name the library through its own @@ -101,6 +125,17 @@ def load_allowlist(path=None): return allow if isinstance(allow, dict) else {} +def load_over_visibility(path=None): + """The `module.item` names that stay `pub(crate)` by decision, with reasons.""" + try: + with open(path or BUDGET) as handle: + section = json.load(handle).get("over_visibility", {}) + except (ValueError, OSError): + return {} + allow = section.get("allowlist", {}) + return allow if isinstance(allow, dict) else {} + + def rust_files(*dirs): out = [] for d in dirs: @@ -154,19 +189,43 @@ def declarations(texts): return names -def census(allow=None): +def pub_crate_declarations(texts): + """Every `pub(crate)` item name, with every place that declares it. + + The twin of `declarations`, and it exists for the same reason: a count of + over-wide items is only useful if the tool can say which file and line. + `pub(crate) use` is a re-export and is not an item, so it is not a candidate + for going private on its own. + """ + names = collections.defaultdict(list) + for path, text in texts.items(): + for lineno, line in enumerate(text.splitlines(), 1): + if COMMENT.match(line) or PUB_CRATE_USE_RE.match(line): + continue + m = PUB_CRATE_NAME_RE.match(line) + if m: + names[m.group(1)].append((path, lineno)) + return names + + +def census(allow=None, over_allow=None): allow = set(load_allowlist() if allow is None else allow) + over_allow = set(load_over_visibility() if over_allow is None else over_allow) src_files = rust_files(SRC) test_files = rust_files(TESTS) src_texts = read_all(src_files) test_texts = read_all(test_files) names = declarations(src_texts) + pc_names = pub_crate_declarations(src_texts) mods = sorted({module_of(p) for p in src_files}) rows = {} # Every name a module declares, `pub` or `pub(crate)`. The allowlist is # checked against this, so a permission cannot outlive the item it names. declared = collections.defaultdict(set) + # Only the `pub(crate)` half, because an over-wide permission has to name a + # `pub(crate)` item: a key pointing at a `pub` one excuses nothing. + pc_declared = collections.defaultdict(set) for mod in mods: rows[mod] = { "pub": 0, @@ -174,6 +233,7 @@ def census(allow=None): "test": 0, "deadonly": 0, "priv": 0, + "overwide": 0, "glob": 0, "lines": 0, "largest": 0, @@ -191,6 +251,7 @@ def census(allow=None): m = PUB_CRATE_NAME_RE.match(line) if m: declared[module_of(path)].add(m.group(1)) + pc_declared[module_of(path)].add(m.group(1)) if GLOB_RE.match(line): row["glob"] += 1 size = text.count("\n") + 1 @@ -240,6 +301,41 @@ def census(allow=None): "line": line, }) + overwide_items = [] + # A `pub(crate)` name is over-wide when no file except the one that declares + # it says the word. `tests/` is not consulted: it is a separate crate and + # cannot name a `pub(crate)` item, so a mention there is noise. As with + # `dead`, a name declared in several files is only flagged when none of them + # is read from outside any of them — the flag is a lead, and a false one is + # cheaper than a missed one. + for name, places in sorted(pc_names.items()): + declaring = {p for p, _ in places} + outside = any( + p not in declaring and re.search(r"\b%s\b" % re.escape(name), t) + for p, t in src_texts.items() + ) + if outside: + continue + for path, line in places: + mod = module_of(path) + if f"{mod}.{name}" in over_allow: + overwide_items.append({ + "module": mod, + "name": name, + "kind": "allowlisted", + "file": os.path.relpath(path, ROOT), + "line": line, + }) + continue + rows[mod]["overwide"] += 1 + overwide_items.append({ + "module": mod, + "name": name, + "kind": "overwide", + "file": os.path.relpath(path, ROOT), + "line": line, + }) + edges = collections.defaultdict(set) for path, text in src_texts.items(): src_mod = module_of(path) @@ -252,10 +348,13 @@ def census(allow=None): edges[src_mod].add(target) dead_items.sort(key=lambda d: (d["module"], d["name"])) + overwide_items.sort(key=lambda d: (d["module"], d["name"], d["file"], d["line"])) return { "modules": rows, "dead_items": dead_items, + "overwide_items": overwide_items, "declared": {mod: sorted(v) for mod, v in sorted(declared.items())}, + "pc_declared": {mod: sorted(v) for mod, v in sorted(pc_declared.items())}, "edges": {k: sorted(v) for k, v in sorted(edges.items())}, "totals": { "pub": sum(r["pub"] for r in rows.values()), @@ -263,6 +362,7 @@ def census(allow=None): "test": sum(r["test"] for r in rows.values()), "deadonly": sum(r["deadonly"] for r in rows.values()), "priv": sum(r["priv"] for r in rows.values()), + "overwide": sum(r["overwide"] for r in rows.values()), "glob": sum(r["glob"] for r in rows.values()), "edges": sum(len(v) for v in edges.values()), "lines": sum(r["lines"] for r in rows.values()), @@ -275,9 +375,11 @@ def census(allow=None): # `priv` is deliberately absent: a `pub(crate)` item is the good state, so a -# rising count is progress and must never be a ceiling. The same list is +# rising count is progress and must never be a ceiling. `overwide` is the +# opposite: it counts the `pub(crate)` items nothing outside their own file +# reaches, and the only direction that number may move is down. The same list is # mirrored by `budgeted` in tests/architecture.rs. -BUDGET_KEYS = ("pub", "dead", "test", "deadonly", "glob") +BUDGET_KEYS = ("pub", "dead", "test", "deadonly", "overwide", "glob") def check_budget(data, budget): @@ -338,6 +440,48 @@ def check_dead_code(data, budget): return problems +def over_visibility_section(budget): + """The `over_visibility` section as `(accepted overwide per module, allowlist)`.""" + section = budget.get("over_visibility", {}) + return section.get("overwide", {}), section.get("allowlist", {}) + + +def check_over_visibility(data, budget): + """Every surviving over-wide item is counted, named and argued — or it fails. + + The mirror of `check_dead_code` for the `pub(crate)` side, with the same + three failures: a module past its accepted count, an item nobody argued for, + and a permission whose item is gone. A reason has to say why the compiler + will not let the item go private — a `pub(crate)` type in a `pub` signature + in its own file, a trait impl that has to stay visible — because "it seemed + safer" is not a reason and does not stop the next widening. + """ + accepted, allowlist = over_visibility_section(budget) + problems = [] + actual = {mod: row["overwide"] for mod, row in data["modules"].items()} + for mod in sorted(set(actual) | set(accepted)): + have, allowed = actual.get(mod, 0), accepted.get(mod, 0) + if have > allowed: + problems.append(f"{mod}.overwide: {have} > {allowed} accepted") + for item in data["overwide_items"]: + if item["kind"] != "overwide": + continue + key = f"{item['module']}.{item['name']}" + if key not in allowlist: + problems.append(f"{key} at {item['file']}:{item['line']} is over-wide and unargued") + elif not str(allowlist[key]).strip(): + problems.append(f"{key} is allowlisted with no reason") + pc_declared = data["pc_declared"] + for key in sorted(allowlist): + mod, _, name = key.partition(".") + if name not in pc_declared.get(mod, []): + problems.append( + f"over_visibility allowlist names {key}, which is no longer a " + "`pub(crate)` item here; it is private, or it was never one" + ) + return problems + + def list_dead(data): """Name every dead item. A count tells a module is wide; this says which items.""" width = max(len(d["module"]) for d in data["dead_items"]) if data["dead_items"] else 0 @@ -352,20 +496,34 @@ def list_dead(data): f"{totals['deadonly']} of them unargued") +def list_overwide(data): + """Name every over-wide `pub(crate)` item, with the file that declares it.""" + items = data["overwide_items"] + width = max((len(d["module"]) for d in items), default=0) + for kind, label in (("overwide", "wider than anything reaches; a candidate for plain private"), + ("allowlisted", "kept `pub(crate)` by decision, reason in the budget file")): + rows = [d for d in items if d["kind"] == kind] + print(f"\n{label} — {len(rows)} items") + for d in rows: + print(f" {d['module'].ljust(width)} {d['name'].ljust(34)} {d['file']}:{d['line']}") + totals = data["totals"] + print(f"\n{totals['overwide']} over-wide of {totals['priv']} pub(crate)") + + def print_census(data): totals = data["totals"] width = max(len(m) for m in data["modules"]) print(f"{'module'.ljust(width)} {'pub':>4} {'dead':>5} {'test':>5} {'deadon':>7} " - f"{'priv':>5} {'glob':>5} {'lines':>6} largest file") - print("-" * (width + 49)) + f"{'priv':>5} {'overwd':>7} {'glob':>5} {'lines':>6} largest file") + print("-" * (width + 57)) for mod, row in sorted(data["modules"].items()): print(f"{mod.ljust(width)} {row['pub']:>4} {row['dead']:>5} {row['test']:>5} " - f"{row['deadonly']:>7} {row['priv']:>5} {row['glob']:>5} {row['lines']:>6} " - f"{row['largest']:>4} {row['largest_file']}") - print("-" * (width + 49)) + f"{row['deadonly']:>7} {row['priv']:>5} {row['overwide']:>7} {row['glob']:>5} " + f"{row['lines']:>6} {row['largest']:>4} {row['largest_file']}") + print("-" * (width + 57)) print(f"{'total'.ljust(width)} {totals['pub']:>4} {totals['dead']:>5} {totals['test']:>5} " - f"{totals['deadonly']:>7} {totals['priv']:>5} {totals['glob']:>5} {totals['lines']:>6} " - f"{totals['largest']:>4} {totals['largest_file']}") + f"{totals['deadonly']:>7} {totals['priv']:>5} {totals['overwide']:>7} {totals['glob']:>5} " + f"{totals['lines']:>6} {totals['largest']:>4} {totals['largest_file']}") print(f"\ncrate:: edges between modules: {totals['edges']}") for src_mod, targets in sorted(data["edges"].items()): print(f" {src_mod.ljust(width)} -> {' '.join(targets)}") @@ -382,14 +540,15 @@ def record(data, path): handle.write(f"totals: {totals['pub']} pub, {totals['dead']} dead " f"({totals['test']} test-only, {totals['deadonly']} named by nobody), " f"{totals['priv']} pub(crate), " + f"{totals['overwide']} over-wide, " f"{totals['glob']} glob re-exports, {totals['edges']} edges, " f"largest file {totals['largest']} ({totals['largest_file']})\n\n") - handle.write("| module | pub | dead | test-only | dead-only | pub(crate) | glob | lines | largest file |\n") - handle.write("|---|---|---|---|---|---|---|---|---|\n") + handle.write("| module | pub | dead | test-only | dead-only | pub(crate) | over-wide | glob | lines | largest file |\n") + handle.write("|---|---|---|---|---|---|---|---|---|---|\n") for mod, row in sorted(data["modules"].items()): handle.write(f"| {mod} | {row['pub']} | {row['dead']} | {row['test']} | " f"{row['deadonly']} | " - f"{row['priv']} | {row['glob']} | {row['lines']} | " + f"{row['priv']} | {row['overwide']} | {row['glob']} | {row['lines']} | " f"{row['largest']} {row['largest_file']} |\n") handle.write("\n```\n") for src_mod, targets in sorted(data["edges"].items()): @@ -405,10 +564,15 @@ def main(): ap.add_argument("--budget", metavar="FILE", help="fail if a number is over the committed budget") ap.add_argument("--write-budget", metavar="FILE", help="write the current numbers as the budget") ap.add_argument("--list-dead", action="store_true", help="name every dead item with its file:line") + ap.add_argument("--list-overwide", action="store_true", + help="name every over-wide pub(crate) item with its file:line") ap.add_argument("--allowlist", metavar="FILE", help="read the kept-item allowlist from FILE") args = ap.parse_args() - data = census(allow=load_allowlist(args.allowlist) if args.allowlist else None) + data = census( + allow=load_allowlist(args.allowlist) if args.allowlist else None, + over_allow=load_over_visibility(args.allowlist) if args.allowlist else None, + ) if args.write_budget: # Preserve any section another tool owns (for example `test_surface`, @@ -430,6 +594,14 @@ def main(): mod: row["deadonly"] for mod, row in sorted(data["modules"].items()) } out["dead_code"] = dead_code + # Same split as `dead_code`: the accepted count is the tool's to write, + # the allowlist of kept `pub(crate)` items is a human's to argue. + over = dict(out.get("over_visibility") or {}) + over.setdefault("allowlist", {}) + over["overwide"] = { + mod: row["overwide"] for mod, row in sorted(data["modules"].items()) + } + out["over_visibility"] = over with open(args.write_budget, "w") as handle: json.dump(out, handle, indent=2, sort_keys=True) @@ -445,13 +617,17 @@ def main(): list_dead(data) return 0 + if args.list_overwide: + list_overwide(data) + return 0 + print_census(data) if args.budget: with open(args.budget) as handle: budget = json.load(handle) over = check_budget(data, budget) - problems = check_dead_code(data, budget) + problems = check_dead_code(data, budget) + check_over_visibility(data, budget) if over or problems: if over: print("\nOVER BUDGET — these numbers grew:") -- cgit v1.2.3