Skip to main content

xtask/
fn_length.rs

1//! The ratcheted maximum function length (#3167).
2//!
3//! A very long function is a place where shape and hygiene go unchecked: the
4//! 2026-10-01 review measured `emit_agent` at 2,064 lines and `lower_method_call`
5//! at 1,118. This module measures every non-test function in the workspace and
6//! compares the ones over [`THRESHOLD`] lines against the committed ceilings in
7//! `xtask/fn-length-ceilings.txt`.
8//!
9//! The rule is a ratchet, not a target: a function over the threshold may not grow
10//! past its ceiling, no function may *newly* cross the threshold, and a ceiling
11//! whose function has since shrunk below the threshold (or gone) must be removed.
12//! A function that shrinks but stays over the threshold keeps its looser ceiling
13//! until someone lowers it with `cargo xtask fn-lengths --apply`, which rewrites the
14//! file from the tree. Lowering a ceiling is always allowed; raising one is the
15//! review conversation this probe exists to force.
16//!
17//! A method name repeated in one file (`fn emit` in two `impl` blocks) is keyed `name`,
18//! `name#2`, … in source order, so each over-threshold one has its own ceiling.
19//!
20//! The measurement reuses the greenfield probes' scanner, which skips braces inside
21//! strings, character literals and comments, and the extents of `#[cfg(test)]`
22//! modules. What is counted: every function in a workspace crate's `src/`. What is
23//! not: `#[cfg(test)]` modules and anything under a crate's `tests/` (or `benches/`),
24//! and, because none is checked in, generated Rust (the files that *write* generated
25//! docs are ordinary source and are counted). A generated source file added later
26//! should be excluded here deliberately, with the reason.
27
28use std::path::Path;
29
30use crate::greenfield_status::{
31    BraceScanState, brace_delta, in_test_range, rust_files, test_mod_ranges, top_level_crate_dirs,
32};
33
34/// Functions of at least this many lines (signature to closing brace) are tracked.
35pub const THRESHOLD: usize = 300;
36
37/// The committed ceilings, relative to the repository root.
38pub const CEILINGS_FILE: &str = "xtask/fn-length-ceilings.txt";
39
40/// One measured function.
41#[derive(Debug, Clone, PartialEq, Eq)]
42pub struct FnLen {
43    /// `crate/src/path.rs`, with forward slashes.
44    pub file: String,
45    pub name: String,
46    pub lines: usize,
47}
48
49impl FnLen {
50    /// The key a ceiling is recorded under: `file::name`.
51    pub fn key(&self) -> String {
52        format!("{}::{}", self.file, self.name)
53    }
54}
55
56/// The name of the function a source line declares, if it declares one
57/// (`pub(crate) async fn name<…>(…`), else `None`.
58fn declared_fn_name(line: &str) -> Option<&str> {
59    let mut rest = line.trim_start();
60    loop {
61        let before = rest;
62        for prefix in ["pub ", "default ", "const ", "async ", "unsafe "] {
63            if let Some(r) = rest.strip_prefix(prefix) {
64                rest = r.trim_start();
65            }
66        }
67        // `extern fn` and `extern "C" fn`.
68        if let Some(r) = rest.strip_prefix("extern ") {
69            rest = r.trim_start();
70            if let Some(abi) = rest.strip_prefix('"')
71                && let Some(end) = abi.find('"')
72            {
73                rest = abi[end + 1..].trim_start();
74            }
75        }
76        if let Some(r) = rest.strip_prefix("pub(")
77            && let Some(end) = r.find(')')
78        {
79            rest = r[end + 1..].trim_start();
80        }
81        if rest == before {
82            break;
83        }
84    }
85    let after = rest.strip_prefix("fn ")?;
86    let end = after
87        .find(|c: char| !(c.is_ascii_alphanumeric() || c == '_'))
88        .unwrap_or(after.len());
89    (end > 0).then(|| &after[..end])
90}
91
92/// `line` without a trailing `//` comment, so a declaration such as `fn a(&self); // note`
93/// or `fn c() -> u8 { 1 } // why` still ends in `;` or `}`. A `//` inside a string literal
94/// (an odd number of unescaped quotes before it) is not a comment.
95fn without_trailing_comment(line: &str) -> &str {
96    let bytes = line.as_bytes();
97    let mut quotes = 0;
98    let mut i = 0;
99    while i < bytes.len() {
100        match bytes[i] {
101            b'\\' => i += 1,
102            b'"' => quotes += 1,
103            b'/' if quotes % 2 == 0 && bytes.get(i + 1) == Some(&b'/') => return &line[..i],
104            _ => {}
105        }
106        i += 1;
107    }
108    line
109}
110
111/// Every function in `source` (non-test), as `(name, lines)`.
112pub fn measure_source(source: &str) -> Vec<(String, usize)> {
113    let lines: Vec<&str> = source.lines().collect();
114    let tests = test_mod_ranges(&lines);
115    struct Open {
116        name: String,
117        start: usize,
118        depth_before: i32,
119        opened: bool,
120    }
121    let mut open: Vec<Open> = Vec::new();
122    let mut out = Vec::new();
123    let mut depth = 0i32;
124    let mut state = BraceScanState::Normal;
125    for (i, line) in lines.iter().enumerate() {
126        let normal_at_start = state == BraceScanState::Normal;
127        if normal_at_start
128            && !in_test_range(i, &tests)
129            && let Some(name) = declared_fn_name(line)
130        {
131            open.push(Open {
132                name: name.to_string(),
133                start: i,
134                depth_before: depth,
135                opened: false,
136            });
137        }
138        let (delta, new_state) = brace_delta(line, state);
139        state = new_state;
140        depth += delta;
141        let mut k = 0;
142        while k < open.len() {
143            let o = &mut open[k];
144            if !o.opened && depth > o.depth_before {
145                o.opened = true;
146            }
147            if o.opened && depth <= o.depth_before {
148                let o = open.remove(k);
149                out.push((o.name, i - o.start + 1));
150                continue;
151            }
152            // A body opened and closed on one line (`fn f() {}`) never raises the depth
153            // across the line.
154            if !o.opened
155                && depth == o.depth_before
156                && line.contains('{')
157                && without_trailing_comment(line).trim_end().ends_with('}')
158            {
159                let o = open.remove(k);
160                out.push((o.name, i - o.start + 1));
161                continue;
162            }
163            // A declaration with no body (`fn f();`) never opens.
164            if !o.opened
165                && depth == o.depth_before
166                && without_trailing_comment(line).trim_end().ends_with(';')
167            {
168                open.remove(k);
169                continue;
170            }
171            k += 1;
172        }
173    }
174    out
175}
176
177/// The functions of one file at or over [`THRESHOLD`], with a same-named later one (a
178/// method of the same name in another `impl` block) keyed `name#2`, `name#3`, in source
179/// order, so each is held to its own ceiling.
180fn disambiguate(file: &str, measured: Vec<(String, usize)>) -> Vec<FnLen> {
181    let mut seen: std::collections::BTreeMap<String, usize> = std::collections::BTreeMap::new();
182    let mut out = Vec::new();
183    for (name, lines) in measured {
184        if lines < THRESHOLD {
185            continue;
186        }
187        let n = seen.entry(name.clone()).or_insert(0);
188        *n += 1;
189        let name = if *n == 1 { name } else { format!("{name}#{n}") };
190        out.push(FnLen {
191            file: file.to_string(),
192            name,
193            lines,
194        });
195    }
196    out
197}
198
199/// Every non-test function in the workspace over [`THRESHOLD`] lines, longest first.
200pub fn measure(root: &Path) -> Vec<FnLen> {
201    let mut all: Vec<FnLen> = Vec::new();
202    for krate in top_level_crate_dirs(root) {
203        for (path, contents) in rust_files(&krate.join("src")) {
204            let file = crate::module_lines::repo_rel_slash(&path, root);
205            all.extend(disambiguate(&file, measure_source(&contents)));
206        }
207    }
208    let mut v = all;
209    v.sort_by(|a, b| b.lines.cmp(&a.lines).then_with(|| a.key().cmp(&b.key())));
210    v
211}
212
213/// The committed ceilings: `file::name = lines`, one per line; `#` starts a comment.
214pub fn read_ceilings(root: &Path) -> Vec<(String, usize)> {
215    let text = std::fs::read_to_string(root.join(CEILINGS_FILE)).unwrap_or_default();
216    text.lines()
217        .filter_map(|l| {
218            let l = l.split('#').next().unwrap_or("").trim();
219            let (key, n) = l.split_once('=')?;
220            Some((key.trim().to_string(), n.trim().parse().ok()?))
221        })
222        .collect()
223}
224
225/// The ceilings file's text for a measurement: every function over the threshold,
226/// at its current length.
227pub fn render_ceilings(measured: &[FnLen]) -> String {
228    let mut s = format!(
229        "# Ratcheted maximum function length (#3167). `file::function = lines`, for every\n\
230         # non-test function of at least {THRESHOLD} lines. A function may not grow past its\n\
231         # ceiling, none may newly reach {THRESHOLD} lines, and an entry whose function has dropped\n\
232         # below {THRESHOLD} (or gone) must be removed. Prefer splitting a function to raising its\n\
233         # ceiling; a raise needs its justification in review. `cargo xtask fn-lengths --apply`\n\
234         # rewrites this file from the tree (lowering ceilings after a function shrinks).\n"
235    );
236    for f in measured {
237        s.push_str(&format!("{} = {}\n", f.key(), f.lines));
238    }
239    s
240}
241
242/// What is wrong, if anything: a function that grew past its ceiling, one that newly
243/// crossed the threshold, and a ceiling that no longer names a function over it.
244pub fn violations(measured: &[FnLen], ceilings: &[(String, usize)]) -> Vec<String> {
245    let mut out = Vec::new();
246    for f in measured {
247        match ceilings.iter().find(|(k, _)| *k == f.key()) {
248            None => out.push(format!(
249                "{} is {} lines, over the {THRESHOLD}-line threshold, and has no ceiling: split it \
250                 into functions with one concern each, or, if it must be this long, justify that in \
251                 review and record it with `cargo xtask fn-lengths --apply`",
252                f.key(),
253                f.lines
254            )),
255            Some((_, ceiling)) if f.lines > *ceiling => out.push(format!(
256                "{} grew to {} lines, past its ceiling of {ceiling}: split the new code into its own \
257                 function, or, if the growth is warranted, justify it in review and record it with \
258                 `cargo xtask fn-lengths --apply`",
259                f.key(),
260                f.lines
261            )),
262            Some(_) => {}
263        }
264    }
265    for (key, ceiling) in ceilings {
266        if !measured.iter().any(|f| f.key() == *key) {
267            out.push(format!(
268                "{key} has a ceiling of {ceiling} but is no longer over {THRESHOLD} lines (or is gone): \
269                 remove its entry from {CEILINGS_FILE}"
270            ));
271        }
272    }
273    out
274}
275
276#[cfg(test)]
277mod tests {
278    use super::*;
279
280    #[test]
281    fn a_trailing_comment_does_not_leave_a_declaration_open() {
282        // A commented bodiless declaration must not borrow the next function's span.
283        let src =
284            "trait T {\n    fn a(&self); // note\n}\nimpl S {\n    fn b() {\n        1\n    }\n}\n";
285        assert_eq!(measure_source(src), vec![("b".to_string(), 3)]);
286        // A one-line body followed by a comment is a one-line function.
287        let src = "fn c() -> u8 { 1 } // why\nimpl S {\n    fn d() {\n        1\n    }\n}\n";
288        assert_eq!(
289            measure_source(src),
290            vec![("c".to_string(), 1), ("d".to_string(), 3)]
291        );
292    }
293
294    #[test]
295    fn a_double_slash_inside_a_string_is_not_a_comment() {
296        assert_eq!(
297            without_trailing_comment("let u = \"http://x\"; // c"),
298            "let u = \"http://x\"; "
299        );
300        assert_eq!(
301            without_trailing_comment("fn f() { g(\"//\") }"),
302            "fn f() { g(\"//\") }"
303        );
304    }
305
306    #[test]
307    fn extern_functions_are_measured() {
308        let src = "pub unsafe extern \"C\" fn a() {\n    1\n}\nextern fn b() {\n}\n";
309        assert_eq!(
310            measure_source(src),
311            vec![("a".to_string(), 3), ("b".to_string(), 2)]
312        );
313    }
314
315    #[test]
316    fn same_named_functions_in_one_file_get_their_own_keys() {
317        let long = |n: usize| (String::from("emit"), n);
318        let v = disambiguate("c/src/a.rs", vec![long(350), long(10), long(320)]);
319        let names: Vec<(&str, usize)> = v.iter().map(|f| (f.name.as_str(), f.lines)).collect();
320        assert_eq!(names, vec![("emit", 350), ("emit#2", 320)]);
321    }
322
323    #[test]
324    fn a_function_is_measured_from_its_signature_to_its_closing_brace() {
325        let src = "fn a() {\n    1\n}\n\npub(crate) fn b(\n    x: u8,\n) -> u8 {\n    x\n}\n";
326        assert_eq!(
327            measure_source(src),
328            vec![("a".to_string(), 3), ("b".to_string(), 5)]
329        );
330    }
331
332    #[test]
333    fn braces_inside_strings_and_comments_do_not_end_a_function() {
334        let src = "fn a() {\n    let s = \"}\";\n    // }\n    let c = '}';\n}\nfn b() {}\n";
335        assert_eq!(
336            measure_source(src),
337            vec![("a".to_string(), 5), ("b".to_string(), 1)]
338        );
339    }
340
341    #[test]
342    fn a_nested_function_is_counted_by_itself_and_inside_its_parent() {
343        let src = "fn outer() {\n    fn inner() {\n        1;\n    }\n}\n";
344        let mut got = measure_source(src);
345        got.sort();
346        assert_eq!(
347            got,
348            vec![("inner".to_string(), 3), ("outer".to_string(), 5)]
349        );
350    }
351
352    #[test]
353    fn a_bodiless_declaration_and_a_test_module_are_ignored() {
354        let src =
355            "trait T {\n    fn f(&self);\n}\n#[cfg(test)]\nmod tests {\n    fn t() {\n    }\n}\n";
356        assert!(measure_source(src).is_empty());
357    }
358
359    #[test]
360    fn a_fn_inside_a_string_is_not_a_function() {
361        let src = "const S: &str = \"\nfn not_real() {\n}\n\";\nfn real() {}\n";
362        assert_eq!(measure_source(src), vec![("real".to_string(), 1)]);
363    }
364
365    #[test]
366    fn growth_a_new_long_function_and_a_stale_entry_are_each_reported() {
367        let m = |n: &str, l| FnLen {
368            file: "a.rs".into(),
369            name: n.into(),
370            lines: l,
371        };
372        let measured = [m("grew", 400), m("fresh", 350), m("ok", 300)];
373        let ceilings = vec![
374            ("a.rs::grew".to_string(), 390),
375            ("a.rs::ok".to_string(), 320),
376            ("a.rs::gone".to_string(), 500),
377        ];
378        let v = violations(&measured, &ceilings);
379        assert_eq!(v.len(), 3, "{v:?}");
380        assert!(v.iter().any(|m| m.contains("a.rs::grew grew")));
381        assert!(
382            v.iter()
383                .any(|m| m.contains("a.rs::fresh") && m.contains("no ceiling"))
384        );
385        assert!(
386            v.iter()
387                .any(|m| m.contains("a.rs::gone") && m.contains("remove"))
388        );
389        // A function that shrank but is still over the threshold is not a violation.
390        assert!(violations(&[m("ok", 310)], &[("a.rs::ok".to_string(), 320)]).is_empty());
391    }
392}