forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

test_source.rs103 lines, 4.0 KiBHistoryRawDownload
1#![cfg(test)]
2//! Test-only access to a crate module's SOURCE TEXT.
3//!
4//! The source-scanning gates used to `include_str!("decode.rs")`, which names
5//! one file. Once a module is split into a directory (`decode/mod.rs` plus its
6//! children) that include stops compiling, and every gate pinning it goes stale
7//! on the next move. These helpers read the module's files at test run time
8//! instead: `src/<name>.rs` when it exists, then every `*.rs` under
9//! `src/<name>/` recursively, concatenated in sorted path order. A file added to
10//! that directory is therefore scanned without touching any gate.
11//!
12//! [`module_production_source`] is the same text minus the test-only files
13//! (`tests.rs` and `*_tests.rs`), for gates that must not count their own test
14//! fixtures. An inline `mod tests { .. }` in a single file is not removed by
15//! that function; a gate that needs the production prefix cuts it itself.
16
17use std::collections::BTreeMap;
18use std::path::{Path, PathBuf};
19use std::sync::{Mutex, OnceLock};
20
21type Cache = Mutex<BTreeMap<(String, bool), &'static str>>;
22static CACHE: OnceLock<Cache> = OnceLock::new();
23
24/// The whole source text of module `name`: `src/<name>.rs` and every `*.rs`
25/// under `src/<name>/`, in sorted path order.
26pub fn module_source(name: &str) -> &'static str {
27 cached(name, false)
28}
29
30/// [`module_source`] without the test-only files (`tests.rs`, `*_tests.rs`).
31pub fn module_production_source(name: &str) -> &'static str {
32 cached(name, true)
33}
34
35/// Each module is read once per test process. The text is leaked, which is
36/// bounded by the handful of modules the gates name and is test-only.
37fn cached(name: &str, production_only: bool) -> &'static str {
38 let cache = CACHE.get_or_init(|| Mutex::new(BTreeMap::new()));
39 let mut map = cache.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
40 let key = (name.to_string(), production_only);
41 if let Some(&text) = map.get(&key) {
42 return text;
43 }
44 let text: &'static str = Box::leak(read_module(name, production_only).into_boxed_str());
45 map.insert(key, text);
46 text
47}
48
49fn read_module(name: &str, production_only: bool) -> String {
50 assert!(
51 !name.is_empty() && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_'),
52 "{name:?} is not a module name"
53 );
54 let src = Path::new(env!("CARGO_MANIFEST_DIR")).join("src");
55 let mut files: Vec<PathBuf> = Vec::new();
56 let single = src.join(format!("{name}.rs"));
57 if single.is_file() {
58 files.push(single);
59 }
60 let dir = src.join(name);
61 if dir.is_dir() {
62 collect_rs(&dir, &mut files);
63 }
64 assert!(
65 !files.is_empty(),
66 "module {name} has neither src/{name}.rs nor src/{name}/"
67 );
68 files.sort();
69 // A split moved some top-level fns to `pub(super) fn` so sibling modules can call them. The
70 // scanners match header text (`\nfn name(`); normalize only that visibility so they see the
71 // same headers as before the split. Bodies and assertions are unchanged.
72 let mut text = String::new();
73 for path in files {
74 if production_only && is_test_file(&path) {
75 continue;
76 }
77 let body = std::fs::read_to_string(&path)
78 .unwrap_or_else(|e| panic!("reading {}: {e}", path.display()));
79 text.push_str(&body);
80 if !body.ends_with('\n') {
81 text.push('\n');
82 }
83 }
84 text.replace("\npub(super) fn ", "\nfn ").replace("\n pub(super) fn ", "\n fn ")
85}
86
87fn collect_rs(dir: &Path, out: &mut Vec<PathBuf>) {
88 let entries =
89 std::fs::read_dir(dir).unwrap_or_else(|e| panic!("reading {}: {e}", dir.display()));
90 for entry in entries {
91 let path = entry.expect("reading a directory entry").path();
92 if path.is_dir() {
93 collect_rs(&path, out);
94 } else if path.extension().is_some_and(|ext| ext == "rs") {
95 out.push(path);
96 }
97 }
98}
99
100fn is_test_file(path: &Path) -> bool {
101 let stem = path.file_stem().and_then(|s| s.to_str()).unwrap_or("");
102 stem == "tests" || stem.ends_with("_tests")
103}