1use 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
33pub const THRESHOLD: usize = 2000;
35
36pub const EXIT_CAP: usize = 3000;
39
40pub const CEILINGS_FILE: &str = "xtask/module-line-ceilings.txt";
42
43#[derive(Debug, Clone, PartialEq, Eq)]
45pub struct ModuleLines {
46 pub file: String,
48 pub lines: usize,
49}
50
51pub 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
65pub 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
75pub(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
84pub(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
94fn 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
121fn 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
148fn 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
157pub(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
172pub(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
179pub(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
200pub 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
216pub 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
234pub 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
240pub 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
269pub 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
289pub 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 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 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 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 #[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}