1use std::path::Path;
48
49pub const FORBIDDEN: &[&str] = &[
54 "thread::spawn",
55 "thread::scope",
56 "thread::Builder",
57 "thread::sleep",
58 "thread::park",
59 "thread::yield_now",
60 "std::thread",
61 "thread::",
62 "thread as",
63 "spawn(",
64 "sleep(",
65 "park(",
66 "park_timeout(",
67 "yield_now(",
68 "scope(",
69 "spin_loop",
70 "Condvar",
71 "Barrier",
72 "mpsc",
73 "rayon",
74 ".wait(",
75 ".wait_timeout",
76 ".recv(",
77];
78
79const ALLOWED_THREAD: &str = "thread::available_parallelism";
81
82pub const CELL_FILLS: &[&str] = &[
86 "get_or_init",
87 "get_or_try_init",
88 "get_mut_or_init",
89 "LazyLock",
90 "LazyCell",
91 "call_once",
92 "OnceCell",
93];
94
95const ONCE_FILE: &str = "once.rs";
97
98#[must_use]
104pub fn waits(src: &Path) -> Vec<String> {
105 scan_tree(src, |_| true, FORBIDDEN)
106}
107
108#[must_use]
115pub fn cell_fills(src: &Path) -> Vec<String> {
116 scan_tree(src, |rel| rel != Path::new(ONCE_FILE), CELL_FILLS)
117}
118
119fn scan_tree(src: &Path, keep: impl Fn(&Path) -> bool, tokens: &[&str]) -> Vec<String> {
122 let mut files = Vec::new();
123 collect(src, &mut files);
124 files.sort();
125 let mut found = Vec::new();
126 for (name, text) in &files {
127 let path = Path::new(name);
128 if keep(path.strip_prefix(src).unwrap_or(path)) {
129 scan(name, text, tokens, &mut found);
130 }
131 }
132 found
133}
134
135fn collect(dir: &Path, out: &mut Vec<(String, String)>) {
136 for entry in std::fs::read_dir(dir).unwrap_or_else(|e| panic!("{}: {e}", dir.display())) {
137 let path = entry
138 .unwrap_or_else(|e| panic!("{}: {e}", dir.display()))
139 .path();
140 if path.is_dir() {
141 collect(&path, out);
142 } else if path.extension().is_some_and(|e| e == "rs") {
143 let text = std::fs::read_to_string(&path)
144 .unwrap_or_else(|e| panic!("{}: {e}", path.display()));
145 out.push((path.display().to_string(), text));
146 }
147 }
148}
149
150fn scan(name: &str, text: &str, tokens: &[&str], found: &mut Vec<String>) {
151 let code = live_text(text);
152 for (i, line) in code.lines().enumerate() {
153 let line = line.replace(ALLOWED_THREAD, "");
154 if let Some(token) = tokens.iter().find(|t| names(&line, t)) {
155 found.push(format!("{name}:{}: {token}", i + 1));
156 }
157 }
158}
159
160fn names(line: &str, token: &str) -> bool {
166 let ident = |c: u8| c.is_ascii_alphanumeric() || c == b'_';
167 let word = token.bytes().next().is_some_and(ident);
168 let (stem, call) = match token.strip_suffix('(') {
169 Some(stem) => (stem, true),
170 None => (token, false),
171 };
172 line.match_indices(stem).any(|(at, _)| {
173 let starts = !word || at == 0 || !ident(line.as_bytes()[at - 1]);
174 starts && (!call || opens_call(&line[at + stem.len()..]))
175 })
176}
177
178fn opens_call(rest: &str) -> bool {
181 let mut rest = rest.trim_start();
182 if let Some(generics) = rest.strip_prefix("::") {
183 let generics = generics.trim_start();
184 if !generics.starts_with('<') {
185 return false;
186 }
187 let mut depth = 0usize;
188 let mut end = None;
189 for (i, c) in generics.char_indices() {
190 match c {
191 '<' => depth += 1,
192 '>' => {
193 depth -= 1;
194 if depth == 0 {
195 end = Some(i + 1);
196 break;
197 }
198 }
199 _ => {}
200 }
201 }
202 let Some(end) = end else {
203 return true;
205 };
206 rest = generics[end..].trim_start();
207 }
208 rest.starts_with('(')
209}
210
211#[derive(Clone, Copy, PartialEq, Eq)]
213enum Class {
214 Code,
216 Literal,
218 Comment,
220}
221
222#[must_use]
227pub fn live_code(text: &str) -> String {
228 let live = live_text(text);
229 let class = classify(live.as_bytes());
230 let kept: Vec<u8> = live
231 .bytes()
232 .zip(class)
233 .map(|(b, c)| {
234 if c == Class::Literal && b != b'\n' {
235 b' '
236 } else {
237 b
238 }
239 })
240 .collect();
241 String::from_utf8_lossy(&kept).into_owned()
242}
243
244fn live_text(text: &str) -> String {
247 let bytes = text.as_bytes();
248 let class = classify(bytes);
249 let mut dead: Vec<bool> = class.iter().map(|c| *c == Class::Comment).collect();
250 let attr = b"#[cfg(test)]";
251 let mut i = 0;
252 while i < bytes.len() {
253 if class[i] == Class::Code && bytes[i..].starts_with(attr) {
254 let end = test_item_end(bytes, &class, i + attr.len());
255 for d in &mut dead[i..end] {
256 *d = true;
257 }
258 i = end;
259 } else {
260 i += 1;
261 }
262 }
263 let kept: Vec<u8> = bytes
264 .iter()
265 .zip(&dead)
266 .map(|(b, d)| if *d && *b != b'\n' { b' ' } else { *b })
267 .collect();
268 String::from_utf8_lossy(&kept).into_owned()
269}
270
271fn classify(b: &[u8]) -> Vec<Class> {
273 let mut class = vec![Class::Code; b.len()];
274 let mark = |class: &mut Vec<Class>, from: usize, to: usize, c: Class| {
275 for x in &mut class[from..to.min(b.len())] {
276 *x = c;
277 }
278 };
279 let mut i = 0;
280 while i < b.len() {
281 let rest = &b[i..];
282 let ident_before = i > 0 && (b[i - 1].is_ascii_alphanumeric() || b[i - 1] == b'_');
283 if rest.starts_with(b"//") {
284 let end = rest
285 .iter()
286 .position(|c| *c == b'\n')
287 .map_or(b.len(), |n| i + n);
288 mark(&mut class, i, end, Class::Comment);
289 i = end;
290 } else if rest.starts_with(b"/*") {
291 let end = block_comment_end(b, i);
292 mark(&mut class, i, end, Class::Comment);
293 i = end;
294 } else if let Some((open, hashes)) = raw_string_start(rest).filter(|_| !ident_before) {
295 let mut close = vec![b'"'];
296 close.extend(std::iter::repeat_n(b'#', hashes));
297 let body = i + open;
298 let end = b[body..]
299 .windows(close.len())
300 .position(|w| w == close.as_slice())
301 .map_or(b.len(), |n| body + n + close.len());
302 mark(&mut class, i, end, Class::Literal);
303 i = end;
304 } else if b[i] == b'"' {
305 let mut j = i + 1;
306 while j < b.len() && b[j] != b'"' {
307 j += if b[j] == b'\\' { 2 } else { 1 };
308 }
309 let end = (j + 1).min(b.len());
310 mark(&mut class, i, end, Class::Literal);
311 i = end;
312 } else if b[i] == b'\'' {
313 if let Some(n) = char_literal_len(rest) {
314 mark(&mut class, i, i + n, Class::Literal);
315 i += n;
316 } else {
317 i += 1; }
319 } else {
320 i += 1;
321 }
322 }
323 class
324}
325
326fn block_comment_end(b: &[u8], from: usize) -> usize {
328 let mut depth = 0;
329 let mut j = from;
330 while j < b.len() {
331 if b[j..].starts_with(b"/*") {
332 depth += 1;
333 j += 2;
334 } else if b[j..].starts_with(b"*/") {
335 depth -= 1;
336 j += 2;
337 if depth == 0 {
338 return j;
339 }
340 } else {
341 j += 1;
342 }
343 }
344 b.len()
345}
346
347fn raw_string_start(rest: &[u8]) -> Option<(usize, usize)> {
351 let after_b = usize::from(matches!(rest.first(), Some(b'b' | b'c')));
352 if rest.get(after_b) != Some(&b'r') {
353 return None;
354 }
355 let hashes = rest[after_b + 1..]
356 .iter()
357 .take_while(|c| **c == b'#')
358 .count();
359 let quote = after_b + 1 + hashes;
360 (rest.get(quote) == Some(&b'"')).then_some((quote + 1, hashes))
361}
362
363fn char_literal_len(rest: &[u8]) -> Option<usize> {
366 if rest.get(1) == Some(&b'\\') {
367 return rest
370 .iter()
371 .skip(3)
372 .take(10)
373 .position(|c| *c == b'\'')
374 .map(|n| n + 4);
375 }
376 let lead = *rest.get(1)?;
377 let width = match lead {
378 0x00..=0x7f => 1,
379 0xc0..=0xdf => 2,
380 0xe0..=0xef => 3,
381 _ => 4,
382 };
383 (rest.get(1 + width) == Some(&b'\'')).then_some(width + 2)
384}
385
386const ITEM_WORDS: &[&str] = &[
389 "fn",
390 "mod",
391 "impl",
392 "use",
393 "struct",
394 "enum",
395 "union",
396 "trait",
397 "type",
398 "const",
399 "static",
400 "extern",
401 "unsafe",
402 "async",
403 "macro_rules!",
404 "thread_local!",
405];
406
407fn test_item_end(b: &[u8], class: &[Class], from: usize) -> usize {
410 let item = starts_item(b, class, from);
411 let mut depth: i32 = 0;
412 for i in from..b.len() {
413 if class[i] != Class::Code {
414 continue;
415 }
416 match b[i] {
417 b'(' | b'[' | b'{' => depth += 1,
418 b')' | b']' | b'}' => {
419 depth -= 1;
420 if depth < 0 {
421 return i;
423 }
424 if depth == 0 && b[i] == b'}' {
425 return i + 1;
426 }
427 }
428 b';' if depth == 0 => return i + 1,
429 b',' if depth == 0 && !item => return i + 1,
430 _ => {}
431 }
432 }
433 b.len()
434}
435
436fn starts_item(b: &[u8], class: &[Class], from: usize) -> bool {
439 let mut i = from;
440 loop {
441 while i < b.len() && (b[i].is_ascii_whitespace() || class[i] == Class::Comment) {
442 i += 1;
443 }
444 if b[i..].starts_with(b"#[") {
445 let mut depth = 0;
447 while i < b.len() {
448 if class[i] == Class::Code {
449 if b[i] == b'[' {
450 depth += 1;
451 } else if b[i] == b']' {
452 depth -= 1;
453 if depth == 0 {
454 i += 1;
455 break;
456 }
457 }
458 }
459 i += 1;
460 }
461 continue;
462 }
463 if b[i..].starts_with(b"pub") {
464 i += 3;
465 while i < b.len() && b[i].is_ascii_whitespace() {
466 i += 1;
467 }
468 if b.get(i) == Some(&b'(') {
469 i += b[i..].iter().position(|c| *c == b')').map_or(0, |n| n + 1);
470 }
471 continue;
472 }
473 break;
474 }
475 let end = b[i..]
476 .iter()
477 .position(|c| !(c.is_ascii_alphanumeric() || *c == b'_' || *c == b'!'))
478 .map_or(b.len(), |n| i + n);
479 let word = &b[i..end];
480 ITEM_WORDS.iter().any(|w| w.as_bytes() == word)
481}
482
483#[cfg(test)]
484mod tests {
485 use super::{CELL_FILLS, FORBIDDEN, scan};
486
487 fn run(text: &str) -> Vec<String> {
488 let mut found = Vec::new();
489 scan("f.rs", text, FORBIDDEN, &mut found);
490 found
491 }
492
493 #[test]
494 fn code_outside_tests_is_flagged() {
495 assert_eq!(
496 run("fn go() {\n std::thread::spawn(|| {});\n cv.wait(g);\n}\n"),
497 ["f.rs:2: thread::spawn", "f.rs:3: .wait("]
498 );
499 }
500
501 #[test]
502 fn test_items_and_comments_are_not() {
503 let text = "\
504 // std::thread::sleep in a comment\n\
505 #[cfg(test)]\n\
506 thread_local! {\n static X: u8 = 0;\n}\n\
507 #[cfg(test)]\n\
508 use std::sync::Barrier;\n\
509 fn real() {\n #[cfg(test)]\n COUNT.with(|n| n.set(1));\n let x = rx.recv();\n}\n\
510 #[cfg(test)]\n\
511 mod tests {\n fn t() {\n std::thread::spawn(|| {});\n }\n}\n\
512 fn after() { std::thread::sleep(d); }\n";
513 assert_eq!(run(text), ["f.rs:11: .recv(", "f.rs:19: thread::sleep"]);
514 }
515
516 #[test]
517 fn a_test_field_arm_or_literal_field_skips_only_itself() {
518 let arm = "fn go(k: Kind) -> u8 {\n match k {\n #[cfg(test)]\n Kind::Probe => 0,\n Kind::Real => {\n std::thread::sleep(D);\n 1\n }\n }\n}\n";
522 assert_eq!(run(arm), ["f.rs:6: thread::sleep"]);
523 let literal = "fn make() -> Pool {\n Pool {\n #[cfg(test)]\n probes: 0,\n worker: std::thread::spawn(move || run()),\n }\n}\n";
524 assert_eq!(run(literal), ["f.rs:5: thread::spawn"]);
525 let last_field =
526 "struct S {\n #[cfg(test)]\n probe: u8\n}\nfn go() { std::thread::park(); }\n";
527 assert_eq!(run(last_field), ["f.rs:5: thread::park"]);
528 let block_arm = "fn go(k: Kind) {\n match k {\n #[cfg(test)]\n Kind::Probe => { let s = \"}\"; },\n Kind::Real => std::thread::yield_now(),\n }\n}\n";
529 assert_eq!(run(block_arm), ["f.rs:5: thread::yield_now"]);
530 let where_fn = "#[cfg(test)]\nfn t<A, B>() where A: X, B: Y {\n std::thread::spawn(|| {});\n}\nfn go() { rx.recv(); }\n";
531 assert_eq!(run(where_fn), ["f.rs:5: .recv("]);
532 }
533
534 #[test]
535 fn grouped_and_aliased_thread_imports_and_spins_are_flagged() {
536 assert_eq!(
538 run(
539 "use std::thread::{sleep, spawn};\nfn go() {\n spawn(|| {});\n sleep(D);\n}\n"
540 ),
541 ["f.rs:1: std::thread", "f.rs:3: spawn(", "f.rs:4: sleep("]
542 );
543 assert_eq!(
544 run("use std::thread as t;\nfn go() {\n t::spawn(|| {});\n}\n"),
545 ["f.rs:1: std::thread", "f.rs:3: spawn("]
546 );
547 assert_eq!(
548 run("use std::{sync::Arc, thread as t};\n"),
549 ["f.rs:1: thread as"]
550 );
551 assert_eq!(
552 run(
553 "fn go(f: &AtomicBool) {\n while !f.load(Acquire) {\n std::thread::yield_now();\n }\n}\n"
554 ),
555 ["f.rs:3: thread::yield_now"]
556 );
557 let none: [&str; 0] = [];
558 assert_eq!(
559 run(
560 "fn n() -> usize { std::thread::available_parallelism().map_or(1, usize::from) }\n"
561 ),
562 none
563 );
564 assert_eq!(
566 run("fn go() { registry_scope(x); spark(y); my_spawn(z); }\n"),
567 none
568 );
569 }
570
571 #[test]
572 fn calls_with_a_turbofish_or_spaces_and_spin_hints_are_flagged() {
573 assert_eq!(
576 run(
577 "use std::hint;\nfn go() {\n spawn::<F, T>(f);\n sleep (D);\n hint::spin_loop();\n rx.recv::<>();\n x.wait :: < Vec<u8> > (g);\n}\n"
578 ),
579 [
580 "f.rs:3: spawn(",
581 "f.rs:4: sleep(",
582 "f.rs:5: spin_loop",
583 "f.rs:6: .recv(",
584 "f.rs:7: .wait(",
585 ]
586 );
587 assert_eq!(
588 run("fn go() {\n core::sync::atomic::spin_loop_hint();\n}\n"),
589 ["f.rs:2: spin_loop"]
590 );
591 let none: [&str; 0] = [];
592 assert_eq!(
594 run("fn go() { spawned(x); let s = sleep_ms; my_sleep::<u8>(1); }\n"),
595 none
596 );
597 }
598
599 #[test]
600 fn a_cell_filled_by_turbofish_path_or_force_is_flagged() {
601 let mut found = Vec::new();
603 let text = "fn a(&self) -> &u8 {\n self.cell.get_or_init::<_>(|| 1)\n}\nfn b(&self) -> &u8 {\n self.cell.get_or_try_init::<_, E>(|| Ok(1)).unwrap()\n}\nfn c(o: &Once) {\n o.call_once_force(|_| ());\n}\nfn d(c: &OnceLock<u8>) -> &u8 {\n let f = OnceLock::get_or_init;\n f(c, || 1)\n}\n";
604 scan("f.rs", text, CELL_FILLS, &mut found);
605 assert_eq!(
606 found,
607 [
608 "f.rs:2: get_or_init",
609 "f.rs:5: get_or_try_init",
610 "f.rs:8: call_once",
611 "f.rs:11: get_or_init",
612 ]
613 );
614 }
615
616 #[test]
617 fn only_the_crates_own_once_rs_is_exempt_from_the_cell_scan() {
618 let scratch = crate::scratch::Scratch::new("waits");
621 let dir = scratch.to_path_buf();
622 let fill = "pub fn f(c: &std::sync::OnceLock<u8>) -> &u8 {\n c.get_or_init(|| 1)\n}\n";
623 std::fs::create_dir_all(dir.join("env")).unwrap();
624 std::fs::create_dir_all(dir.join("files")).unwrap();
625 for f in ["once.rs", "env/once.rs", "files/bonce.rs", "lib.rs"] {
626 std::fs::write(dir.join(f), fill).unwrap();
627 }
628 let found = super::cell_fills(&dir);
629 let rel: Vec<String> = found
630 .iter()
631 .map(|f| {
632 let f = f.strip_prefix(&dir.display().to_string()).unwrap();
633 f.trim_start_matches(std::path::MAIN_SEPARATOR).to_owned()
634 })
635 .collect();
636 let sep = std::path::MAIN_SEPARATOR;
637 assert_eq!(
638 rel,
639 [
640 format!("env{sep}once.rs:2: get_or_init"),
641 format!("files{sep}bonce.rs:2: get_or_init"),
642 "lib.rs:2: get_or_init".to_owned(),
643 ]
644 );
645 }
646
647 #[test]
648 fn a_cell_filled_with_its_value_inside_is_flagged_and_its_helper_is_not() {
649 let mut found = Vec::new();
653 let text = "fn entry(&self) -> &File {\n self.cell.get_or_init(|| parse(self))\n}\nstatic T: LazyLock<u8> = LazyLock::new(|| 1);\n#[cfg(test)]\nmod tests { fn t() { c.get_or_init(|| 1); } }\n";
654 scan("f.rs", text, CELL_FILLS, &mut found);
655 assert_eq!(found, ["f.rs:2: get_or_init", "f.rs:4: LazyLock"]);
656 }
657
658 #[test]
663 fn live_code_blanks_each_literal_and_keeps_the_code_after_it() {
664 let text = concat!(
665 "let a = \"{\\\"}\";\n",
666 "let b = r#\"{\"}\"#;\n",
667 "let c = cr#\"a\"b{\"#;\n",
668 "let d = c\"{\\\"}\";\n",
669 "let e = br\"}\";\n",
670 "let f = '\\'';\n",
671 "let g = b'{';\n",
672 "let h = b'\\'';\n",
673 "let i = '\\u{7B}';\n",
674 "/* /* nested } */ { */\n",
675 "fn live<'a>(m: &'a Meter) { m.work_used_up(); }\n",
676 );
677 let code = super::live_code(text);
678 let lines: Vec<&str> = code.lines().collect();
679 assert_eq!(lines.len(), 11, "{code}");
680 for (i, l) in lines.iter().take(9).enumerate() {
681 assert!(!l.contains(['{', '}', '"', '\'', '\\']), "line {i}: {l:?}");
682 assert!(l.trim_end().ends_with(';'), "line {i}: {l:?}");
683 }
684 assert_eq!(lines[9].trim(), "");
685 assert_eq!(lines[10], "fn live<'a>(m: &'a Meter) { m.work_used_up(); }");
686 }
687
688 #[test]
692 fn live_code_blanks_test_items_and_keeps_what_follows() {
693 let text = "fn a() { x(); }\n#[cfg(test)]\nfn t() { y(); }\nfn b() { z(); }\n\
694 #[cfg(test)] impl S { fn u() { w(); } }\n#[allow(dead_code)] impl T { fn v() {} }\n\
695 let r#fn = r#work_used_up();\n";
696 let code = super::live_code(text);
697 let lines: Vec<&str> = code.lines().map(str::trim).collect();
698 assert_eq!(
699 lines,
700 [
701 "fn a() { x(); }",
702 "",
703 "",
704 "fn b() { z(); }",
705 "",
706 "#[allow(dead_code)] impl T { fn v() {} }",
707 "let r#fn = r#work_used_up();",
708 ]
709 );
710 }
711
712 #[test]
713 fn literals_and_lifetimes_do_not_move_the_depth() {
714 let text = "#[cfg(test)]\nfn t<'a>(x: &'a str) {\n let _ = ('{', \"{{\", r#\"}\"#, b'(');\n}\nfn go() { rx.recv(); }\n";
715 assert_eq!(run(text), ["f.rs:5: .recv("]);
716 }
717}