Skip to main content

xtask/
module_lines.rs

1//! The module-size ratchet (#4085, slice 2.0 of the back-half paydown track, spine #3676).
2//!
3//! Q5 of the track: no source file may *newly* cross [`THRESHOLD`] production lines, and an
4//! existing one may not grow. This module measures production lines per `src/**/*.rs` file
5//! (comments and blank lines count; `#[cfg(test)]` modules, whole-test files and files
6//! declared away by `#[cfg(test)] mod name;` do not) and compares the back-half crates'
7//! files ([`BACK_HALF_CRATES`]) at or over the threshold against the committed ceilings in
8//! `xtask/module-line-ceilings.txt`. The `module_lines` trend probe reads the same
9//! measure, workspace-wide, so the trend and the gate share one definition.
10//!
11//! The rule is a ratchet in the way the function-length ratchet is ([`crate::fn_length`]):
12//!
13//! 1. a file may not grow past its ceiling;
14//! 2. a file not listed may not reach [`THRESHOLD`];
15//! 3. an entry whose file is under [`THRESHOLD`], or gone, or renamed, must be deleted;
16//! 4. a file that shrinks but stays over keeps its looser ceiling until
17//!    `cargo xtask module-lines --apply` rewrites the file from the tree.
18//!
19//! The track's exit cap is [`EXIT_CAP`] production lines: no entry may be at or over it. The
20//! files that were already over it when the ratchet landed were exempt until Phase 2's splits
21//! took each one under; the last went in 2.5b (#4090), and the exemption was then retired.
22//!
23//! Keys are `crate/src/path.rs` from the repository root with `/` separators on every
24//! platform ([`repo_rel_slash`]); Windows CI runs the gate.
25
26use std::collections::BTreeSet;
27use std::path::{Component, Path};
28
29use crate::greenfield_status::{
30    in_test_range, rust_files, strip_visibility, test_mod_ranges, top_level_crate_dirs,
31};
32
33/// Files of at least this many production lines are tracked.
34pub const THRESHOLD: usize = 2000;
35
36/// The track's exit target: no back-half file at or over this many production lines. It
37/// binds every ceiling.
38pub const EXIT_CAP: usize = 3000;
39
40/// The committed ceilings, relative to the repository root.
41pub const CEILINGS_FILE: &str = "xtask/module-line-ceilings.txt";
42
43/// One measured file.
44#[derive(Debug, Clone, PartialEq, Eq)]
45pub struct ModuleLines {
46    /// `crate/src/path.rs`, with forward slashes.
47    pub file: String,
48    pub lines: usize,
49}
50
51/// `path` relative to `root`, joined with `/` whatever the platform separator is. Built from
52/// `components()`, not by rewriting `\\` in a string, so a literal backslash in a Unix file
53/// name is left alone and `Path::display` on Windows cannot leak a `\\` into a key (#4026).
54pub fn repo_rel_slash(path: &Path, root: &Path) -> String {
55    let rel = path.strip_prefix(root).unwrap_or(path);
56    rel.components()
57        .filter_map(|c| match c {
58            Component::Normal(s) => Some(s.to_string_lossy().into_owned()),
59            _ => None,
60        })
61        .collect::<Vec<_>>()
62        .join("/")
63}
64
65/// The crates of the "back half" (track §8): the ratchet's scope and the probe's back-half reading.
66pub const BACK_HALF_CRATES: [&str; 6] = [
67    "bynk-model",
68    "bynk-emit",
69    "bynk-ts",
70    "bynk-driver",
71    "bynk-strip",
72    "bynk",
73];
74
75/// True for a file under a crate's `src/` that is wholly tests: `tests.rs`,
76/// `*_tests.rs`, or anything beneath a `tests/` directory. `rel` is the path
77/// relative to `src/`, with `/` separators.
78pub(crate) fn is_whole_test_file(rel: &str) -> bool {
79    let mut parts: Vec<&str> = rel.split('/').collect();
80    let file = parts.pop().unwrap_or("");
81    file == "tests.rs" || file.ends_with("_tests.rs") || parts.contains(&"tests")
82}
83
84/// Lines of `source` outside its `#[cfg(test)]` module ranges. Comments and blank
85/// lines count; only each test module's own range is removed, wherever it sits.
86pub(crate) fn production_lines(source: &str) -> usize {
87    let lines: Vec<&str> = source.lines().collect();
88    let ranges = test_mod_ranges(&lines);
89    (0..lines.len())
90        .filter(|&i| !in_test_range(i, &ranges))
91        .count()
92}
93
94/// Names declared by `#[cfg(test)] [vis] mod name;` — an external-file module
95/// *declaration* gated by its attribute, whose file is therefore wholly test code
96/// (`bynk-check/src/testkit.rs`). The attribute must be the line directly above
97/// (blank lines allowed), as [`test_mod_ranges`] reads it.
98fn cfg_test_declared_mods(source: &str) -> Vec<String> {
99    let lines: Vec<&str> = source.lines().collect();
100    let mut out = Vec::new();
101    for (i, line) in lines.iter().enumerate() {
102        if line.trim() != "#[cfg(test)]" {
103            continue;
104        }
105        let Some(next) = lines[i + 1..].iter().find(|l| !l.trim().is_empty()) else {
106            continue;
107        };
108        let t = next.trim();
109        let t = strip_visibility(t);
110        if let Some(name) = t
111            .trim_start()
112            .strip_prefix("mod ")
113            .and_then(|r| r.strip_suffix(';'))
114        {
115            out.push(name.trim().to_string());
116        }
117    }
118    out
119}
120
121/// The `src/`-relative stems (`testkit`, `emitter/testkit`) of files and
122/// directories declared away as test-only by a `#[cfg(test)] mod name;` in some
123/// other file. A module file `a/b.rs` owns directory `a/b/`, except `lib.rs`,
124/// `main.rs` and `mod.rs`, which own their own directory.
125fn declaration_gated_stems<'a>(
126    files: impl IntoIterator<Item = (&'a str, &'a str)>,
127) -> BTreeSet<String> {
128    let mut stems = BTreeSet::new();
129    for (rel, contents) in files {
130        let (dir, file) = rel.rsplit_once('/').unwrap_or(("", rel));
131        let stem = file.strip_suffix(".rs").unwrap_or(file);
132        let owned = match stem {
133            "lib" | "main" | "mod" => dir.to_string(),
134            _ if dir.is_empty() => stem.to_string(),
135            _ => format!("{dir}/{stem}"),
136        };
137        for name in cfg_test_declared_mods(contents) {
138            stems.insert(if owned.is_empty() {
139                name
140            } else {
141                format!("{owned}/{name}")
142            });
143        }
144    }
145    stems
146}
147
148/// True when `rel` is one of the declaration-gated stems' files (`stem.rs`,
149/// `stem/mod.rs`) or lies beneath such a module's directory.
150fn is_declaration_gated(rel: &str, stems: &BTreeSet<String>) -> bool {
151    let without_ext = rel.strip_suffix(".rs").unwrap_or(rel);
152    stems
153        .iter()
154        .any(|s| without_ext == s || rel.starts_with(&format!("{s}/")))
155}
156
157/// The stems of the modules that `files` declare away as test-only (`#[cfg(test)] mod x;`),
158/// for [`is_test_only_file`]. `files` are `(path, contents)` with one common base, in which
159/// the declaring file and the declared one both appear; paths may use either separator.
160pub(crate) fn gated_stems(files: &[(std::path::PathBuf, String)]) -> BTreeSet<String> {
161    let rels: Vec<String> = files
162        .iter()
163        .map(|(p, _)| p.to_string_lossy().replace('\\', "/"))
164        .collect();
165    declaration_gated_stems(
166        rels.iter()
167            .zip(files)
168            .map(|(rel, (_, contents))| (rel.as_str(), contents.as_str())),
169    )
170}
171
172/// Is `rel` test code throughout: a whole test file ([`is_whole_test_file`]), or a module
173/// declared `#[cfg(test)] mod x;` in `gated` ([`gated_stems`])? Every probe that skips
174/// test files uses this, so they agree with `module_lines` on what a test file is.
175pub(crate) fn is_test_only_file(rel: &str, gated: &BTreeSet<String>) -> bool {
176    is_whole_test_file(rel) || is_declaration_gated(rel, gated)
177}
178
179/// `(path from the repo root, production lines)` for one crate's `src/**/*.rs`
180/// files, given as `(src-relative path, contents)`. Whole-test files and files
181/// whose `mod` declaration is `#[cfg(test)]` are skipped; paths read
182/// `{crate}/src/{rel}`.
183pub(crate) fn module_lines_for_crate(
184    crate_name: &str,
185    files: &[(String, String)],
186) -> Vec<(String, usize)> {
187    let gated = declaration_gated_stems(files.iter().map(|(r, c)| (r.as_str(), c.as_str())));
188    files
189        .iter()
190        .filter(|(rel, _)| !is_test_only_file(rel, &gated))
191        .map(|(rel, contents)| {
192            (
193                format!("{crate_name}/src/{rel}"),
194                production_lines(contents),
195            )
196        })
197        .collect()
198}
199
200/// `(path from the repo root, production lines)` for every `src/**/*.rs` file of every
201/// top-level crate in the workspace (the trend probe's universe).
202pub fn measure_workspace(root: &Path) -> Vec<(String, usize)> {
203    let mut files = Vec::new();
204    for krate in top_level_crate_dirs(root) {
205        let crate_name = krate.file_name().unwrap().to_string_lossy().to_string();
206        let src = krate.join("src");
207        let rels: Vec<(String, String)> = rust_files(&src)
208            .into_iter()
209            .map(|(path, contents)| (repo_rel_slash(&path, &src), contents))
210            .collect();
211        files.extend(module_lines_for_crate(&crate_name, &rels));
212    }
213    files
214}
215
216/// The ratchet's universe: the back-half crates' files at or over [`THRESHOLD`], longest
217/// first, ties by path.
218pub fn measure(root: &Path) -> Vec<ModuleLines> {
219    let mut v: Vec<ModuleLines> = measure_workspace(root)
220        .into_iter()
221        .filter(|(file, lines)| {
222            *lines >= THRESHOLD
223                && file
224                    .split('/')
225                    .next()
226                    .is_some_and(|c| BACK_HALF_CRATES.contains(&c))
227        })
228        .map(|(file, lines)| ModuleLines { file, lines })
229        .collect();
230    v.sort_by(|a, b| b.lines.cmp(&a.lines).then_with(|| a.file.cmp(&b.file)));
231    v
232}
233
234/// The committed ceilings: `file = lines`, one per line; `#` starts a comment.
235pub fn read_ceilings(root: &Path) -> Vec<(String, usize)> {
236    let text = std::fs::read_to_string(root.join(CEILINGS_FILE)).unwrap_or_default();
237    parse_ceilings(&text)
238}
239
240/// Lines of the committed ceilings file that are neither blank, a comment nor `file = lines`
241/// (`foo.rs = 10,717`), which [`read_ceilings`] would otherwise drop silently.
242pub fn malformed_ceiling_lines(root: &Path) -> Vec<String> {
243    let text = std::fs::read_to_string(root.join(CEILINGS_FILE)).unwrap_or_default();
244    unparseable_lines(&text)
245}
246
247fn unparseable_lines(text: &str) -> Vec<String> {
248    text.lines()
249        .map(|l| l.split('#').next().unwrap_or("").trim())
250        .filter(|l| !l.is_empty())
251        .filter(|l| {
252            l.split_once('=')
253                .is_none_or(|(_, n)| n.trim().parse::<usize>().is_err())
254        })
255        .map(|l| format!("{CEILINGS_FILE}: unparseable line {l:?}: write `file = lines`"))
256        .collect()
257}
258
259fn parse_ceilings(text: &str) -> Vec<(String, usize)> {
260    text.lines()
261        .filter_map(|l| {
262            let l = l.split('#').next().unwrap_or("").trim();
263            let (key, n) = l.split_once('=')?;
264            Some((key.trim().to_string(), n.trim().parse().ok()?))
265        })
266        .collect()
267}
268
269/// The ceilings file's text for a measurement: every back-half file at or over the
270/// threshold, at its current length.
271pub fn render_ceilings(measured: &[ModuleLines]) -> String {
272    let mut s = format!(
273        "# Ratcheted maximum module size (#4085). `file = lines`, for every back-half source\n\
274         # file (bynk-model, bynk-emit, bynk-ts, bynk-driver, bynk-strip, bynk) of at least\n\
275         # {THRESHOLD} production lines: comments and blank lines count; `#[cfg(test)]` modules,\n\
276         # whole-test files and `#[cfg(test)] mod x;` files do not. A file may not grow past its\n\
277         # ceiling, none may newly reach {THRESHOLD}, and an entry whose file has dropped below\n\
278         # {THRESHOLD} (or gone, or been renamed) must be removed. No entry may be\n\
279         # {EXIT_CAP} or more: split along a seam first. Prefer splitting a file to raising its\n\
280         # ceiling; a raise needs its justification in review. `cargo xtask module-lines --apply`\n\
281         # rewrites this file from the tree (lowering ceilings after a file shrinks).\n"
282    );
283    for m in measured {
284        s.push_str(&format!("{} = {}\n", m.file, m.lines));
285    }
286    s
287}
288
289/// What is wrong, if anything: a file past its ceiling, one that newly crossed the
290/// threshold, an entry that no longer names a file over it, a new entry at or over
291/// [`EXIT_CAP`], and a key with a `\\`.
292pub fn violations(measured: &[ModuleLines], ceilings: &[(String, usize)]) -> Vec<String> {
293    let mut out = Vec::new();
294    for m in measured {
295        match ceilings.iter().find(|(k, _)| *k == m.file) {
296            None => out.push(format!(
297                "{} is {} production lines, over the {THRESHOLD}-line threshold, and has no ceiling: \
298                 split along a seam, or, if it must be this long, justify that in review and record \
299                 it with `cargo xtask module-lines --apply`",
300                m.file, m.lines
301            )),
302            Some((_, ceiling)) if m.lines > *ceiling => out.push(format!(
303                "{} grew to {} production lines, past its ceiling of {ceiling}: split the new code \
304                 into its own module, or, if the growth is warranted, justify it in review and \
305                 record it with `cargo xtask module-lines --apply`",
306                m.file, m.lines
307            )),
308            Some(_) => {}
309        }
310    }
311    for (key, ceiling) in ceilings {
312        if key.contains('\\') {
313            out.push(format!(
314                "{key} has a `\\` in its key: keys are `/`-separated on every platform"
315            ));
316        }
317        if !measured.iter().any(|m| m.file == *key) {
318            out.push(format!(
319                "{key} has a ceiling of {ceiling} but is no longer over {THRESHOLD} production lines \
320                 (or is gone or renamed): remove its entry from {CEILINGS_FILE}"
321            ));
322        }
323        if *ceiling >= EXIT_CAP {
324            out.push(format!(
325                "{key} has a ceiling of {ceiling}, at or over the {EXIT_CAP}-line exit cap: split it \
326                 along a seam before it grows that far"
327            ));
328        }
329    }
330    out
331}
332
333#[cfg(test)]
334mod tests {
335    use super::*;
336    use std::path::PathBuf;
337
338    fn lines_of(n: usize) -> String {
339        "x\n".repeat(n)
340    }
341
342    #[test]
343    fn module_lines_excludes_a_trailing_test_module() {
344        let src = format!(
345            "{}#[cfg(test)]\nmod tests {{\n{}}}\n",
346            lines_of(5),
347            lines_of(100)
348        );
349        // 5 production lines plus the attribute line, which sits outside the range.
350        assert_eq!(production_lines(&src), 6);
351    }
352
353    #[test]
354    fn module_lines_excludes_a_mid_file_test_module_but_keeps_what_follows() {
355        let src = format!(
356            "{}#[cfg(test)]\nmod tests {{\n{}}}\n{}",
357            lines_of(3),
358            lines_of(50),
359            lines_of(4)
360        );
361        assert_eq!(production_lines(&src), 3 + 1 + 4);
362    }
363
364    #[test]
365    fn module_lines_counts_comments_and_blank_lines() {
366        assert_eq!(production_lines("// c\n\nfn a() {}\n"), 3);
367    }
368
369    #[test]
370    fn module_lines_skips_whole_test_files() {
371        assert!(is_whole_test_file("tests.rs"));
372        assert!(is_whole_test_file("emitter/tests.rs"));
373        assert!(is_whole_test_file("parser_tests.rs"));
374        assert!(is_whole_test_file("tests/fixtures/a.rs"));
375        assert!(!is_whole_test_file("emitter/emit.rs"));
376        assert!(!is_whole_test_file("attests.rs"));
377    }
378
379    #[test]
380    fn module_lines_paths_read_crate_src_rel() {
381        let files = vec![("emitter/a.rs".to_string(), lines_of(7))];
382        assert_eq!(
383            module_lines_for_crate("bynk-emit", &files),
384            vec![("bynk-emit/src/emitter/a.rs".to_string(), 7)]
385        );
386    }
387
388    #[test]
389    fn module_lines_skips_files_declared_by_cfg_test_mod() {
390        let lib =
391            "#[cfg(test)]\npub(crate) mod testkit;\n\n#[cfg(test)]\nmod fixtures;\npub mod real;\n";
392        let files = vec![
393            ("lib.rs".to_string(), lib.to_string()),
394            ("testkit.rs".to_string(), lines_of(500)),
395            ("fixtures/mod.rs".to_string(), lines_of(50)),
396            ("fixtures/inner.rs".to_string(), lines_of(50)),
397            ("real.rs".to_string(), lines_of(9)),
398        ];
399        let got = module_lines_for_crate("c", &files);
400        let names: Vec<&str> = got.iter().map(|(p, _)| p.as_str()).collect();
401        assert_eq!(names, vec!["c/src/lib.rs", "c/src/real.rs"]);
402    }
403
404    #[test]
405    fn module_lines_declaration_gate_is_scoped_to_the_declaring_directory() {
406        // `emitter.rs` declares `emitter/testkit.rs`; a top-level `testkit.rs`
407        // that no `#[cfg(test)]` declaration gates stays production code.
408        let files = vec![
409            (
410                "emitter.rs".to_string(),
411                "#[cfg(test)]\nmod testkit;\n".to_string(),
412            ),
413            ("emitter/testkit.rs".to_string(), lines_of(30)),
414            ("testkit.rs".to_string(), lines_of(40)),
415            ("lib.rs".to_string(), "mod testkit;\n".to_string()),
416        ];
417        let got = module_lines_for_crate("c", &files);
418        assert!(got.iter().any(|(p, n)| p == "c/src/testkit.rs" && *n == 40));
419        assert!(!got.iter().any(|(p, _)| p.contains("emitter/testkit")));
420    }
421
422    fn m(file: &str, lines: usize) -> ModuleLines {
423        ModuleLines {
424            file: file.into(),
425            lines,
426        }
427    }
428
429    fn c(file: &str, lines: usize) -> (String, usize) {
430        (file.to_string(), lines)
431    }
432
433    #[test]
434    fn growth_a_new_crossing_and_a_stale_entry_are_each_reported() {
435        let measured = [
436            m("a/src/grew.rs", 2400),
437            m("a/src/fresh.rs", 2100),
438            m("a/src/ok.rs", 2000),
439        ];
440        let ceilings = vec![
441            c("a/src/grew.rs", 2300),
442            c("a/src/ok.rs", 2200),
443            c("a/src/gone.rs", 2500),
444        ];
445        let v = violations(&measured, &ceilings);
446        assert!(v.iter().any(|x| x.contains("a/src/grew.rs grew")), "{v:?}");
447        assert!(
448            v.iter()
449                .any(|x| x.contains("a/src/fresh.rs") && x.contains("no ceiling")),
450            "{v:?}"
451        );
452        assert!(
453            v.iter()
454                .any(|x| x.contains("a/src/gone.rs") && x.contains("remove")),
455            "{v:?}"
456        );
457    }
458
459    #[test]
460    fn a_renamed_file_is_a_stale_entry_and_a_new_crossing() {
461        let v = violations(
462            &[m("a/src/new_name.rs", 2100)],
463            &[c("a/src/old_name.rs", 2100)],
464        );
465        assert!(
466            v.iter()
467                .any(|x| x.contains("old_name.rs") && x.contains("renamed"))
468        );
469        assert!(
470            v.iter()
471                .any(|x| x.contains("new_name.rs") && x.contains("no ceiling"))
472        );
473    }
474
475    #[test]
476    fn a_file_that_shrank_but_stays_over_is_not_reported() {
477        assert!(violations(&[m("a/src/s.rs", 2100)], &[c("a/src/s.rs", 2500)]).is_empty());
478    }
479
480    #[test]
481    fn an_entry_at_the_exit_cap_is_reported() {
482        // 3,000 exactly is over the cap (the probe counts with `>=`).
483        let v = violations(&[m("a/src/big.rs", 3000)], &[c("a/src/big.rs", 3000)]);
484        assert!(v.iter().any(|x| x.contains("exit cap")), "{v:?}");
485        assert!(violations(&[m("a/src/big.rs", 2999)], &[c("a/src/big.rs", 2999)]).is_empty());
486    }
487
488    #[test]
489    fn a_malformed_ceiling_line_is_reported() {
490        let v = unparseable_lines("# c\n\na/src/x.rs = 2400\na/src/y.rs = 10,717\nnoequals\n");
491        assert_eq!(v.len(), 2, "{v:?}");
492        assert!(v[0].contains("10,717"));
493    }
494
495    #[test]
496    fn a_key_with_a_backslash_is_reported() {
497        let v = violations(&[m("a\\src\\b.rs", 2100)], &[c("a\\src\\b.rs", 2100)]);
498        assert!(v.iter().any(|x| x.contains("`\\`")), "{v:?}");
499    }
500
501    /// Built with `Path::join` per component, so on Windows the separator is `\\` and the key
502    /// must still read `/` (#4026).
503    #[test]
504    fn repo_rel_slash_joins_components_with_a_forward_slash() {
505        let root = PathBuf::from("repo");
506        let path = root.join("a").join("src").join("b").join("c.rs");
507        assert_eq!(repo_rel_slash(&path, &root), "a/src/b/c.rs");
508    }
509
510    #[test]
511    fn ceilings_round_trip_through_render_and_parse() {
512        let measured = [m("a/src/x.rs", 2400), m("b/src/y.rs", 2100)];
513        let parsed = parse_ceilings(&render_ceilings(&measured));
514        assert_eq!(parsed, vec![c("a/src/x.rs", 2400), c("b/src/y.rs", 2100)]);
515    }
516}