From 065c2c2beb2be2ccf68da3088ddc33c904909c80 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 22:12:55 +0000 Subject: [PATCH] test: keep split modules visible to the source scans The i18n coverage scan and prefs_usage stopped reading a file at its first `#[cfg(test)] mod`. A split parent declares `#[cfg(test)] mod tests;` before the rest of its code, so the scans skipped that code, and on main an inline test module in the middle of panels.rs hid the code after it. Both now drop only the body of an inline test module. The prefs audits in scorecard and prefs_usage count a read when the section and the field appear in the same file. Both now also treat a split module (`foo.rs` with `foo/`) as one file, and prefs_usage leaves out `engine/src/prefs/` as scorecard already does, since that directory now holds the rest of the prefs model. On main and on this branch: the i18n coverage report is identical (2,142 source keys; the old scan found 2,049 on main), `cargo xtask scorecard --check` is up to date, and prefs_usage passes. --- crates/engine/tests/it/prefs_usage.rs | 57 +++++++++++++++++----- xtask/src/i18n_coverage.rs | 68 ++++++++++++++++++++------- xtask/src/scorecard.rs | 17 ++++++- 3 files changed, 110 insertions(+), 32 deletions(-) diff --git a/crates/engine/tests/it/prefs_usage.rs b/crates/engine/tests/it/prefs_usage.rs index 7b9adebdd1..eabad21ed8 100644 --- a/crates/engine/tests/it/prefs_usage.rs +++ b/crates/engine/tests/it/prefs_usage.rs @@ -44,15 +44,36 @@ fn has_ident(text: &str, prefix: &str, ident: &str) -> bool { }) } -/// Production source of a file: everything before its unit-test module. -fn production(text: &str) -> &str { +/// Production source of a file: the file without its inline unit-test modules +/// (`#[cfg(test)] mod tests { … }` at the top level, closed by `}` at column 0). A declaration +/// (`#[cfg(test)] mod tests;`) can come before the rest of the code, so it doesn't end the scan. +fn production(text: &str) -> String { // Windows checkouts may use CRLF; test-only reads must stay excluded. - let cut = ["#[cfg(test)]\nmod ", "#[cfg(test)]\r\nmod ", "#[cfg(test)]\npub mod ", "#[cfg(test)]\r\npub mod "] - .into_iter() - .filter_map(|marker| text.find(marker)) - .min() - .unwrap_or(text.len()); - &text[..cut] + let marker = "#[cfg(test)]"; + let mut out = String::with_capacity(text.len()); + let mut rest = text; + while let Some(at) = rest.match_indices(marker).map(|(i, _)| i).find(|&i| i == 0 || rest[..i].ends_with('\n')) { + let after = &rest[at + marker.len()..]; + let item = after.trim_start(); + let item = item.strip_prefix("pub ").unwrap_or(item); + let body = item.strip_prefix("mod ").and_then(|m| { + let name_end = m.find(|c: char| !c.is_alphanumeric() && c != '_')?; + m[name_end..].trim_start().strip_prefix('{') + }); + let Some(body) = body else { + out.push_str(&rest[..at + marker.len()]); + rest = after; + continue; + }; + out.push_str(&rest[..at]); + let Some(end) = body.match_indices("\n}").map(|(i, _)| i + 2).find(|&e| matches!(body[e..].chars().next(), None | Some('\r' | '\n'))) else { + return out; + }; + let tail = &body[end..]; + rest = tail.strip_prefix("\r\n").or_else(|| tail.strip_prefix('\n')).unwrap_or(tail); + } + out.push_str(rest); + out } fn rust_sources(dir: &Path, out: &mut Vec) { @@ -96,12 +117,22 @@ fn every_preference_is_read_or_hidden() { let mut files = Vec::new(); rust_sources(&root.join("crates"), &mut files); rust_sources(&root.join("apps"), &mut files); - let sources: Vec = files - .iter() - .filter(|p| !p.ends_with("engine/src/prefs.rs")) - .filter_map(|p| std::fs::read_to_string(p).ok()) - .map(|t| production(&t).to_string()) + let prefs_dir = root.join("crates/engine/src/prefs"); + let files: Vec<(PathBuf, String)> = files + .into_iter() + .filter(|p| !p.ends_with("engine/src/prefs.rs") && !p.starts_with(&prefs_dir)) + .filter_map(|p| std::fs::read_to_string(&p).ok().map(|t| (p, production(&t)))) .collect(); + let mut sources: Vec = files.iter().map(|(_, t)| t.clone()).collect(); + // A module split into child files (`foo.rs` + `foo/*.rs`) counts as one file too, so a section + // named in the parent and a field read in a child still count as a read. + for (path, text) in &files { + let dir = path.with_extension(""); + let children: Vec<&str> = files.iter().filter(|(p, _)| p.starts_with(&dir)).map(|(_, t)| t.as_str()).collect(); + if !children.is_empty() { + sources.push([text.as_str()].into_iter().chain(children).collect::>().join("\n")); + } + } assert!(sources.len() > 100, "found only {} source files under {}", sources.len(), root.display()); // Section key → struct name, from `pub : ,` in `struct Preferences`. diff --git a/xtask/src/i18n_coverage.rs b/xtask/src/i18n_coverage.rs index e8c221905f..c84eaf7678 100644 --- a/xtask/src/i18n_coverage.rs +++ b/xtask/src/i18n_coverage.rs @@ -179,8 +179,8 @@ fn tl_keys(sources: &[(PathBuf, String)]) -> BTreeSet { if path.ends_with("ui-egui/src/i18n.rs") { continue; } - let code = before_test_module(source); - let mut rest = code; + let code = without_test_modules(source); + let mut rest = code.as_str(); while let Some(at) = rest.find("tl!(\"") { rest = rest.get(at + 5..).unwrap_or(""); let bytes = rest.as_bytes(); @@ -205,8 +205,8 @@ fn plural_keys(sources: &[(PathBuf, String)]) -> BTreeSet { if path.ends_with("ui-egui/src/i18n.rs") { continue; } - let code = before_test_module(source); - let mut rest = code; + let code = without_test_modules(source); + let mut rest = code.as_str(); while let Some(at) = rest.find("trn(") { rest = rest.get(at + 4..).unwrap_or(""); let Some(end) = call_end(rest) else { break }; @@ -258,7 +258,8 @@ fn engine_command_labels(sources: &[(PathBuf, String)]) -> BTreeSet { let mut keys = BTreeSet::new(); let mut command_macros = HashSet::new(); for (_, source) in sources { - let mut rest = before_test_module(source); + let code = without_test_modules(source); + let mut rest = code.as_str(); while let Some(at) = rest.find("macro_rules!") { rest = rest.get(at + "macro_rules!".len()..).unwrap_or(""); let name = rest.trim_start().split(|c: char| !c.is_ascii_alphanumeric() && c != '_').next().unwrap_or(""); @@ -273,8 +274,8 @@ fn engine_command_labels(sources: &[(PathBuf, String)]) -> BTreeSet { } } for (_, source) in sources { - let code = before_test_module(source); - let mut rest = code; + let code = without_test_modules(source); + let mut rest = code.as_str(); while let Some(at) = rest.find("CommandSpec {") { rest = rest.get(at + "CommandSpec {".len()..).unwrap_or(""); let Some(end) = balanced_end(rest, '{', '}') else { break }; @@ -295,7 +296,7 @@ fn engine_command_labels(sources: &[(PathBuf, String)]) -> BTreeSet { } for name in &command_macros { let marker = format!("{name}!("); - let mut rest = code; + let mut rest = code.as_str(); while let Some(at) = rest.find(&marker) { rest = rest.get(at + marker.len()..).unwrap_or(""); let Some(end) = call_end(rest) else { break }; @@ -310,18 +311,49 @@ fn engine_command_labels(sources: &[(PathBuf, String)]) -> BTreeSet { keys } -fn before_test_module(source: &str) -> &str { +/// Drops the bodies of inline `#[cfg(test)] mod name { … }` modules. A declaration +/// (`#[cfg(test)] mod tests;`) can sit before the rest of a file's code, so only an inline +/// module's own body is skipped. +fn without_test_modules(source: &str) -> String { let marker = "#[cfg(test)]"; - let mut offset = 0; - while let Some(relative) = source.get(offset..).and_then(|rest| rest.find(marker)) { - let start = offset + relative; - let after_attribute = source.get(start + marker.len()..).unwrap_or("").trim_start(); - if after_attribute.strip_prefix("mod").is_some_and(|rest| rest.chars().next().is_some_and(char::is_whitespace)) { - return source.get(..start).unwrap_or(source); - } - offset = start + marker.len(); + let mut code = String::with_capacity(source.len()); + let mut rest = source; + while let Some(at) = rest.find(marker) { + let after_marker = rest.get(at + marker.len()..).unwrap_or(""); + let Some(body) = inline_module_body(after_marker) else { + code.push_str(rest.get(..at + marker.len()).unwrap_or(rest)); + rest = after_marker; + continue; + }; + code.push_str(rest.get(..at).unwrap_or(rest)); + let Some(end) = balanced_end(body, '{', '}') else { return code }; + rest = body.get(end + 1..).unwrap_or(""); } - source + code.push_str(rest); + code +} + +/// After a `#[cfg(test)]`: the text following the `{` of an inline `mod name {`, past any further +/// attributes, or `None` for anything else. +fn inline_module_body(mut rest: &str) -> Option<&str> { + loop { + rest = rest.trim_start(); + if !rest.starts_with("#[") { + break; + } + let end = balanced_end(rest.get(2..)?, '[', ']')?; + rest = rest.get(end + 3..)?; + } + let rest = rest.strip_prefix("mod")?; + if !rest.starts_with(char::is_whitespace) { + return None; + } + let rest = rest.trim_start(); + let name_end = rest.find(|c: char| !c.is_ascii_alphanumeric() && c != '_').unwrap_or(rest.len()); + if name_end == 0 { + return None; + } + rest.get(name_end..)?.trim_start().strip_prefix('{') } fn menu_command_label(args: &str) -> Option { diff --git a/xtask/src/scorecard.rs b/xtask/src/scorecard.rs index ba7673a886..5c9985c945 100644 --- a/xtask/src/scorecard.rs +++ b/xtask/src/scorecard.rs @@ -387,6 +387,19 @@ fn audit_sources(root: &Path) -> Vec<(PathBuf, String)> { .collect() } +/// Each `foo.rs` that has a `foo/` directory, joined with every file under it, so a module split +/// into child files still counts `.section` and `.field` as being in the same file. +fn split_modules(sources: &[(PathBuf, String)]) -> Vec { + sources + .iter() + .filter_map(|(path, src)| { + let dir = path.with_extension(""); + let children: Vec<&str> = sources.iter().filter(|(p, _)| p.starts_with(&dir)).map(|(_, s)| s.as_str()).collect(); + (!children.is_empty()).then(|| [src.as_str()].into_iter().chain(children).collect::>().join("\n")) + }) + .collect() +} + /// Preferences that nothing reads (sorted paths). pub fn prefs_audit(root: &Path) -> Result<(usize, Vec), String> { let src = std::fs::read_to_string(root.join(PREFS_RS)).map_err(|e| format!("read {PREFS_RS}: {e}"))?; @@ -394,7 +407,9 @@ pub fn prefs_audit(root: &Path) -> Result<(usize, Vec), String> { if fields.is_empty() { return Err(format!("{PREFS_RS}: no `pub struct Preferences` fields found (did the struct move?)")); } - let mut files: Vec = audit_sources(root).iter().map(|(_, s)| accesses(s)).collect(); + let sources = audit_sources(root); + let mut files: Vec = sources.iter().map(|(_, s)| accesses(s)).collect(); + files.extend(split_modules(&sources).iter().map(|s| accesses(s))); files.push(accesses(&session_code(&strip_tests(&src)))); let unread: Vec = fields.iter().filter(|f| !is_read(f, &files)).map(PrefField::path).collect(); Ok((fields.len(), unread))