Skip to main content

unityrs_testkit/
waits.rs

1//! The source scans behind plan section 4.1's rules that the core never
2//! waits and never starts a thread, and that it computes no lazy value
3//! inside its cell.
4//!
5//! **Waits.** A batch engine runs core calls on its own pool threads, so a
6//! core call that parks, sleeps, spins, waits on a condition or a channel,
7//! or hands work to a thread of its own would let the pool starve itself, or
8//! escape the engine's bound on threads. [`waits`] lists every line outside
9//! test code that names one of [`FORBIDDEN`]: a thread function by its path
10//! or bare (as a grouped or aliased import calls it), any use of
11//! `std::thread` but `available_parallelism`, an alias of it, a spin hint
12//! (`std::hint::spin_loop`, the older `spin_loop_hint`), a condition
13//! variable, a barrier, a channel or a thread pool. A call token (one that
14//! ends in `(`) matches with a turbofish and with spaces before its
15//! parenthesis too (`spawn::<F, T>(`, `sleep (`).
16//!
17//! **Cells.** A value computed inside `OnceLock::get_or_init` (or a
18//! `LazyLock`, a `Once`) runs caller code with the cell locked, which a
19//! callback that reaches the same cell, or a thread holding Python's GIL,
20//! deadlocks on (plan 3.16). [`cell_fills`] lists every line outside test
21//! code and outside the crate's own `src/once.rs` (that one file: a `once.rs`
22//! elsewhere in the tree is scanned) that names a cell-filling method or
23//! type, by any form of call, a turbofish's included, or as a path, so
24//! fills a cell any other way than through
25//! `once::get_or_publish` or `get_or_publish_result`, whose tests pin that
26//! only a move runs inside the cell. So every lazy value of the core, the
27//! stubs' included once they are written, goes through the tested helper.
28//!
29//! **What neither scan checks: locks.** The scan cannot tell a lock held for
30//! a lookup from one held across a call into caller code (a codec, a
31//! provider, a resolver, a fetcher). That no core lock is held across caller
32//! code is checked by tests that re-enter each public path that takes one:
33//! the provider chain's (`provider::tests`), and packages C's and D's for
34//! the bundle and the Environment (plan 4.1, 7.4, 7.5).
35//!
36//! **Test code** is an item, field, match arm or statement under
37//! `#[cfg(test)]`, found by bracket depth, not by line endings: an item
38//! (`fn`, `mod`, `impl`, `use`, a macro such as `thread_local!`) ends at the
39//! `;` or the closing `}` of its first block at its own depth; anything
40//! else (a struct field, a struct literal's field, a match arm, a statement)
41//! also ends at a `,` at its own depth, and at the `}` or `)` that closes
42//! what encloses it. String and character literals and comments do not
43//! count toward the depth; comments are never scanned.
44//!
45//! Owner: the scaffold (implemented).
46
47use std::path::Path;
48
49/// What the core never names outside tests: thread starts, sleeps, parks,
50/// spins and scopes (by path, or bare as an import calls them), `std::thread`
51/// itself and its aliases (only `available_parallelism` is allowed), spin
52/// hints, condition variables, barriers, channels, a thread pool.
53pub 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
79/// The one `std::thread` item the core may name: it starts nothing.
80const ALLOWED_THREAD: &str = "thread::available_parallelism";
81
82/// What fills a cell with caller code inside it, outside `once.rs`: each
83/// named at the start of a word, whatever follows (a call, a turbofish, a
84/// path), so `call_once` names `call_once_force` too.
85pub 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
95/// The file that holds the one cell helper, relative to `src`.
96const ONCE_FILE: &str = "once.rs";
97
98/// Every `file:line: token` under `src` where non-test code names a
99/// [`FORBIDDEN`] token (the first on the line).
100///
101/// # Panics
102/// When `src` cannot be read (a test helper).
103#[must_use]
104pub fn waits(src: &Path) -> Vec<String> {
105    scan_tree(src, |_| true, FORBIDDEN)
106}
107
108/// Every `file:line: token` under `src`, `src/once.rs` itself excepted,
109/// where non-test code fills a cell other than through the `once` helper
110/// ([`CELL_FILLS`]).
111///
112/// # Panics
113/// When `src` cannot be read (a test helper).
114#[must_use]
115pub fn cell_fills(src: &Path) -> Vec<String> {
116    scan_tree(src, |rel| rel != Path::new(ONCE_FILE), CELL_FILLS)
117}
118
119/// Scans every `.rs` file under `src` whose path relative to `src` `keep`
120/// accepts.
121fn 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
160/// Whether `line` names `token`: a token that starts with an identifier
161/// character must start a word there (`registry_scope(` is not `scope(`,
162/// `t::spawn(` is `spawn(`), and a call token (one ending in `(`) matches
163/// its name followed by spaces and a turbofish before the parenthesis too
164/// (`spawn::<F, T>(`, `sleep (`), but not a longer name (`spawned(`).
165fn 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
178/// Whether `rest` (what follows a name) opens its call: spaces, an optional
179/// turbofish `::<…>` (nested angle brackets counted), spaces, then `(`.
180fn 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            // The turbofish runs past the line: a call split over lines.
204            return true;
205        };
206        rest = generics[end..].trim_start();
207    }
208    rest.starts_with('(')
209}
210
211/// What a byte of the source is.
212#[derive(Clone, Copy, PartialEq, Eq)]
213enum Class {
214    /// Code: counted toward depth, scanned.
215    Code,
216    /// Inside a string or character literal: scanned, not counted.
217    Literal,
218    /// A comment: neither.
219    Comment,
220}
221
222/// The source's live code: every comment, every test item and every
223/// string and character literal blanked to spaces (newlines kept, so line
224/// numbers hold), for a scan that matches code forms and counts braces
225/// (the core's CR8 refusal scan, `counters_scan_tests.rs`).
226#[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
244/// The source with every comment and every test item blanked to spaces
245/// (newlines kept, so line numbers hold).
246fn 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
271/// Classifies every byte: code, literal or comment.
272fn 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; // a lifetime
318            }
319        } else {
320            i += 1;
321        }
322    }
323    class
324}
325
326/// Where the (nested) block comment that opens at `from` ends.
327fn 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
347/// `r"`, `r#"`, `br##"`, `cr#"`…: the bytes up to the body, and the `#`
348/// count (round 3 of CR8: a raw C string was read as two plain strings, so
349/// the code after it was blanked as a literal).
350fn 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
363/// The length of a character literal starting at `rest[0] == '\''`, or
364/// `None` for a lifetime.
365fn char_literal_len(rest: &[u8]) -> Option<usize> {
366    if rest.get(1) == Some(&b'\\') {
367        // An escape: the closing quote comes after the escaped character
368        // (which may itself be a quote, `'\''`), within a `\u{10FFFF}`.
369        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
386/// Words that start an item, which ends at its `;` or its first block's
387/// closing `}`, never at a `,`.
388const 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
407/// Where the test item after `#[cfg(test)]` (which ends at `from`) ends:
408/// the index just past its last byte (module docs).
409fn 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                    // It closed what encloses the item: the item ended before it.
422                    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
436/// Whether the code after `from` (past further attributes, comments and a
437/// visibility) starts with an item word.
438fn 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            // Another attribute: skip to its closing bracket.
446            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        // Round 4: a test item that ended with `,` made the scan skip the
519        // next block as test code, so the code after a `#[cfg(test)]` match
520        // arm or struct field went unseen.
521        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        // Round 4: these named no listed token.
537        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        // A name that only ends in one is not one.
565        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        // Round 5: `spawn::<F, T>(` and `std::hint::spin_loop()` named no
574        // listed token.
575        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        // A longer name, or a path that is not a call, is not a call.
593        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        // Round 5: `get_or_init::<_>(` and `call_once_force` passed the scan.
602        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        // Round 5: the scan exempted every file whose path ended in
619        // `once.rs` (`src/files/bonce.rs`, `src/env/once.rs`).
620        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        // Plan 4.1 (round 4): a lazy value computed inside its cell runs
650        // caller code with the cell locked; only `once.rs` may call
651        // `get_or_init`, and only to move a computed value in.
652        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    /// `live_code` blanks every kind of literal, its braces and quotes
659    /// with it, and every comment, nested ones too, and keeps the code
660    /// around them (round 3 of CR8: a raw C string and `'\''` were
661    /// misread, so the code after them was blanked).
662    #[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    /// A test item mid-file is blanked, an attribute on its item's line
689    /// included, and the live code after it is kept; a raw identifier is
690    /// code.
691    #[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}