1use 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
34pub const THRESHOLD: usize = 300;
36
37pub const CEILINGS_FILE: &str = "xtask/fn-length-ceilings.txt";
39
40#[derive(Debug, Clone, PartialEq, Eq)]
42pub struct FnLen {
43 pub file: String,
45 pub name: String,
46 pub lines: usize,
47}
48
49impl FnLen {
50 pub fn key(&self) -> String {
52 format!("{}::{}", self.file, self.name)
53 }
54}
55
56fn 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 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
92fn 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
111pub 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 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 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
177fn 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
199pub 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
213pub 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
225pub 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
242pub 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 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 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 assert!(violations(&[m("ok", 310)], &[("a.rs::ok".to_string(), 320)]).is_empty());
391 }
392}