craft-testkit: guards end a native cfg if let at its body and read only muda's qualified type

- A native-only `if`, `while`, `match` or `for` now ends at its body's
  closing brace, or at the last block of an `else` chain. A `{` in the
  pattern of a `let` (also after `&&` in a chain) or a `for` opens a
  struct pattern, so `#[cfg(unix)] if let State::Ready { .. } = s { .. }`
  no longer ends at the pattern's brace and leaves its body checked.
- A raw identifier spelled like a keyword (`r#let`, `r#in`, `r#match`)
  is read as a name. `mod r#match;` still names `match.rs`.
- predefined_quit reports a qualified path only as
  `muda::PredefinedMenuItem` (or `::muda::...`), so
  `other_crate::PredefinedMenuItem::quit` is not reported. The plain
  name and a `use muda::PredefinedMenuItem as X` rename still are.
This commit is contained in:
dotCooCoo committed 2026-11-14 17:01:49 -08:00
1 parent 811baa83c1
commit e1b53c6b44
3 files changed
+153 -11

No files matched your search

+1 -1
View File
@@ -6,7 +6,7 @@ Source-level platform regression guards and verification utilities for the Craft
`craft-testkit` provides lightweight, non-panicking source guards that prevent applications in the Craft ecosystem from repeating platform defects that were previously diagnosed and resolved in peer applications:
1. **`predefined_quit`**: Flags direct calls to `muda`'s `PredefinedMenuItem::quit` outside comments, strings and character literals, also with whitespace or a line break around `::`, in the qualified form `<muda::PredefinedMenuItem>::quit`, and through a `use muda::PredefinedMenuItem as ...` rename. On macOS, this predefined menu item routes directly to `NSApplication terminate:`, completely bypassing application dirty document checks and unsaved changes save prompts. Applications should instead wire Quit through `craft-quit` lifecycle interceptors.
1. **`predefined_quit`**: Flags direct calls to `muda`'s `PredefinedMenuItem::quit` outside comments, strings and character literals, also with whitespace or a line break around `::`, in the qualified form `<muda::PredefinedMenuItem>::quit`, and through a `use muda::PredefinedMenuItem as ...` rename. A type of the same name reached through another crate or module, such as `other::PredefinedMenuItem::quit`, is not flagged. On macOS, this predefined menu item routes directly to `NSApplication terminate:`, completely bypassing application dirty document checks and unsaved changes save prompts. Applications should instead wire Quit through `craft-quit` lifecycle interceptors.
2. **`wgsl_float_literals` / `wgsl_float_literals_in`**: Scans WGSL shader sources and flags decimal and hexadecimal float literals whose value, rounded to `f64`, exceeds `f32::MAX` (such as `3.40282347e38` or `0x1p+500f`), or 65504, the largest finite `f16`, for a literal with an `h` suffix. A literal that exceeds the maximum by less than `f64` precision rounds to the maximum and is not reported. Integer literals are not checked. Some native compilers round such literals down, but browser WebGPU compilers reject them with pipeline compilation errors, forcing applications into CPU fallback rendering. `f32::MAX` can be written as the hex float `0x1.fffffep+127f`, which equals it, or as the decimal `3.4028234663852886e38`, which rounds to it.
3. **`std_instant`**: Flags `std::time::Instant` outside comments and strings: the full path, `<m>::Instant` where a `use` binds `m` to `std::time`, and each `use` that imports `std::time::Instant` or `std::time::*`, under any name. The parts of a path may be split by whitespace, comments or line breaks. Other crates' `Instant` (such as `web_time::Instant` or `tokio::time::Instant`) is not flagged, and neither is an item whose `cfg` attribute is false on `wasm32-unknown-unknown`; code before that attribute or after its item on the same line is still checked. A `mod name;` inside such an item also skips the module's file (`name.rs` or `name/mod.rs`, or the file a `#[path]` attribute names) and the files of the modules declared in it, when they are among the files passed in and no declaration outside such items also reaches them. On that target, `std::time::Instant::now()` panics at runtime with `"time not implemented on this platform"`. Code targeting the web must use `web_time::Instant`.
4. **`rust_sources`**: Recursively discovers a crate's `.rs` source files while excluding integration tests (`tests/`), test modules (`tests.rs`, `tests_*.rs`, `*_tests.rs`, `*_test.rs`), build artifacts (`target/`, any folder holding a `CACHEDIR.TAG` file that starts with the line `Signature: 8a477f597d28d172789f06886806bc55`, `.git/` and other folders whose name starts with `.`) and symbolic links, which it does not follow. A file over 8 MiB, more than 256 MiB in all or more than 50,000 files returns an error; `rust_sources_with_limits` takes other limits. It is not built for `wasm32`.
+65 -9
View File
@@ -274,11 +274,13 @@ fn lex_rust(code: &str) -> Vec<Token> {
tokens
}
/// The name of a raw identifier written after `r#`. `r#true` and `r#false` keep their prefix, so a `cfg`
/// predicate does not read them as the literals `true` and `false`.
/// The name of a raw identifier written after `r#`. A raw identifier spelled like a keyword the guards
/// read (`r#let`, `r#in`, `r#match`, `r#true`) keeps its prefix, so it is read as a name rather than as
/// that keyword or as a `cfg` literal.
fn raw_identifier(name: &[char]) -> String {
let name: String = name.iter().collect();
if matches!(name.as_str(), "true" | "false") { format!("r#{name}") } else { name }
let keyword = |list: &[&str]| list.contains(&name.as_str());
if keyword(&["true", "false"]) || keyword(KEYWORDS) || keyword(BLOCK_KEYWORDS) || keyword(VALUE_KEYWORDS) { format!("r#{name}") } else { name }
}
/// Read a normal string body starting after its opening quote. Returns the index after the closing
@@ -668,6 +670,24 @@ const BLOCK_KEYWORDS: &[&str] =
/// that value.
const VALUE_KEYWORDS: &[&str] = &["let", "return", "break", "yield", "become"];
/// Where [`item_end`] is in the head of an `if`, `while`, `match` or `for` before its body's `{`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Condition {
/// Not in such a head: the next `{` outside brackets opens the body.
Done,
/// In the pattern of a `let` or a `for`, where a `{` opens a struct pattern.
Pattern,
/// In a condition, a scrutinee or an iterator, where the next `{` outside brackets opens the body.
Expression,
}
/// Whether the `=` at `toks[j]` stands alone, as the `=` between a `let` pattern and its value, rather
/// than as part of `==`, `!=`, `<=`, `>=`, `=>` or the range pattern `..=`.
fn lone_equals(toks: &[Token], j: usize) -> bool {
let punct = |k: usize, cs: &[char]| toks.get(k).is_some_and(|t| cs.iter().any(|&c| t.is_punct(c)));
!punct(j + 1, &['=', '>']) && j.checked_sub(1).is_none_or(|k| !punct(k, &['=', '!', '<', '>', '.']))
}
/// Whether a block expression starts at `j`: `{`, a labeled block (`'label: {`) or a `const` block.
fn starts_block(toks: &[Token], j: usize) -> bool {
let punct = |k: usize, c: char| toks.get(k).is_some_and(|t| t.is_punct(c));
@@ -690,11 +710,17 @@ fn starts_block(toks: &[Token], j: usize) -> bool {
/// outside brackets is part of an expression, which runs on to its `;` or `,`. When a `.` or `?`
/// follows the closing brace of a block item, the item runs on to its `;` or `,`. A `,` inside the angle
/// brackets of a field's or a `let`'s type ends the item early, which leaves the rest of it checked.
///
/// The body of an `if`, `while`, `match` or `for` at the head is the first `{` outside brackets after its
/// condition, scrutinee or iterator. A `{` in the pattern of a `let` (`if let S { .. } = s`, also after
/// `&&` in a chain) or of a `for` opens a struct pattern and does not end the item. An `else` chain ends
/// at its last block.
fn item_end(toks: &[Token], start: usize, inner: bool) -> usize {
let mut depth = 0usize;
let mut block_item = false;
let mut arm = false;
let mut head = true;
let mut condition = Condition::Done;
let mut j = start;
while j < toks.len() {
let at_top = depth == 0 && !inner;
@@ -702,7 +728,23 @@ fn item_end(toks: &[Token], start: usize, inner: bool) -> usize {
block_item = true;
}
match &toks[j].kind {
Kind::Ident(k) if at_top && head && (BLOCK_KEYWORDS.contains(&k.as_str()) || starts_block(toks, j)) => block_item = true,
Kind::Ident(k) if at_top && head && (BLOCK_KEYWORDS.contains(&k.as_str()) || starts_block(toks, j)) => {
if !block_item {
condition = match k.as_str() {
"if" | "while" | "match" => Condition::Expression,
"for" => Condition::Pattern,
_ => Condition::Done,
};
}
block_item = true;
}
Kind::Ident(k) if at_top && condition == Condition::Expression && k == "let" => condition = Condition::Pattern,
Kind::Ident(k) if at_top && condition == Condition::Pattern && k == "in" => condition = Condition::Expression,
Kind::Punct('=') if at_top && condition == Condition::Pattern && lone_equals(toks, j) => condition = Condition::Expression,
Kind::Punct('{') if at_top && condition == Condition::Expression => {
condition = Condition::Done;
depth += 1;
}
Kind::Ident(k) if at_top && VALUE_KEYWORDS.contains(&k.as_str()) => head = false,
Kind::Punct('!') if at_top && head && toks.get(j + 1).is_some_and(|t| t.is_punct('{')) => block_item = true,
Kind::Punct('=') if at_top && toks.get(j + 1).is_some_and(|t| t.is_punct('>')) => {
@@ -710,6 +752,7 @@ fn item_end(toks: &[Token], start: usize, inner: bool) -> usize {
arm = true;
head = true;
block_item = starts_block(toks, j + 2);
condition = Condition::Done;
j += 2;
continue;
}
@@ -730,8 +773,12 @@ fn item_end(toks: &[Token], start: usize, inner: bool) -> usize {
return j;
}
depth -= 1;
if depth == 0 && *c == '}' && block_item && !inner {
if depth == 0 && *c == '}' && block_item && !inner && condition == Condition::Done {
if toks.get(j + 1).is_some_and(|t| t.is_ident("else")) {
// `else if` has a condition of its own before its body; `else {` opens the body.
if toks.get(j + 2).is_some_and(|t| t.is_ident("if")) {
condition = Condition::Expression;
}
j += 1;
continue;
}
@@ -884,6 +931,11 @@ enum Brace {
TooDeep,
}
/// The name of a module's file or folder: a raw identifier such as `r#match` names `match`.
fn module_name(name: &str) -> String {
name.strip_prefix("r#").unwrap_or(name).to_owned()
}
/// Every out-of-line module declaration in a file, in one pass that tracks the inline modules around it.
///
/// Declarations inside more than [`MAX_NESTING`] inline modules are left out, so their files are checked.
@@ -898,7 +950,7 @@ fn module_decls(toks: &[Token], skip: &[bool]) -> Vec<ModDecl> {
let brace = match i.checked_sub(2).map(|j| (&toks[j], &toks[j + 1].kind)) {
Some((m, Kind::Ident(name))) if m.is_ident("mod") => {
if too_deep == 0 && inline.len() < MAX_NESTING {
inline.push(Rc::new(ModName { name: name.clone(), path_attribute: path_attribute(toks, i - 2) }));
inline.push(Rc::new(ModName { name: module_name(name), path_attribute: path_attribute(toks, i - 2) }));
Brace::Module
} else {
too_deep += 1;
@@ -921,7 +973,7 @@ fn module_decls(toks: &[Token], skip: &[bool]) -> Vec<ModDecl> {
&& toks.get(i + 2).is_some_and(|t| t.is_punct(';'))
{
decls.push(ModDecl {
module: ModName { name: name.clone(), path_attribute: path_attribute(toks, i) },
module: ModName { name: module_name(name), path_attribute: path_attribute(toks, i) },
inline: inline.clone(),
native: skip.get(i).copied().unwrap_or(false),
});
@@ -1109,7 +1161,8 @@ fn report(findings: &mut Vec<Finding>, path: &str, content: &str, lines: &BTreeS
///
/// The guard reads Rust tokens, so comments, strings and character literals are ignored, and whitespace
/// or line breaks around `::` do not hide a call. A qualified path such as `<muda::PredefinedMenuItem>::quit`
/// is reported too. It also follows a `use` that renames muda's type
/// is reported too. A path that names the type through another crate or module, such as
/// `other::PredefinedMenuItem::quit`, is not. It also follows a `use` that renames muda's type
/// (`use muda::PredefinedMenuItem as Item;` then `Item::quit`); a rename of another crate's
/// `PredefinedMenuItem` is not followed. Each finding names the line where the
/// type's name starts, once per line, in line order.
@@ -1132,7 +1185,10 @@ where
let mut lines = BTreeSet::new();
for (i, tok) in toks.iter().enumerate() {
let Kind::Ident(name) = &tok.kind else { continue };
let named = name == "PredefinedMenuItem" || (aliases.contains(name) && !continues_a_path(&toks, i));
// A qualified name counts only as `muda::PredefinedMenuItem` (or `::muda::...`), not as
// another crate's or module's type of the same name.
let muda_path = !continues_a_path(&toks, i) || (toks[i - 3].is_ident("muda") && !continues_a_path(&toks, i - 3));
let named = (name == "PredefinedMenuItem" && muda_path) || (aliases.contains(name) && !continues_a_path(&toks, i));
let quit = |at: usize| then_path(&toks, at, |s| s == "quit" || s == "Quit");
// `<muda::PredefinedMenuItem>::quit`, a qualified path to the same function.
let qualified = || toks.get(i + 1).is_some_and(|t| t.is_punct('>')) && quit(i + 2) && opens_qualified_path(&toks, i);
+87 -1
View File
@@ -292,7 +292,7 @@ fn test_predefined_quit_qualified_and_whitespace() {
fn setup() {
let q1 = muda::PredefinedMenuItem::quit(None);
let q2 = PredefinedMenuItem :: quit(Some("Quit"));
let q3 = crate::menu::PredefinedMenuItem::Quit;
let q3 = ::muda::PredefinedMenuItem::Quit;
}
"#;
let findings = predefined_quit([("src/menu.rs", source)]);
@@ -427,6 +427,25 @@ fn menu() {
assert_eq!(lines(&predefined_quit([("src/menu.rs", source)])), vec![4, 5, 6]);
}
#[test]
fn predefined_quit_ignores_another_crates_type_in_a_qualified_path() {
let source = r#"
use other_menu::PredefinedMenuItem as Other;
fn menu() {
let a = other_crate::PredefinedMenuItem::quit(None);
let b = <other_crate::PredefinedMenuItem>::quit(None);
let c = crate::menu::PredefinedMenuItem::Quit;
let d = other::muda::PredefinedMenuItem::quit(None);
let e = <T as Menu>::PredefinedMenuItem::quit(None);
let f = Other::quit(None);
let g = muda::PredefinedMenuItem::quit(None);
let h = <muda :: PredefinedMenuItem>::quit(None);
let i = PredefinedMenuItem::quit(None);
}
"#;
assert_eq!(lines(&predefined_quit([("src/menu.rs", source)])), vec![10, 11, 12]);
}
#[test]
fn std_instant_ignores_an_alias_that_only_a_native_cfg_imports() {
let source = r#"
@@ -651,6 +670,73 @@ fn run(x: Option<u32>) -> u64 {
assert_eq!(lines(&std_instant([("src/run.rs", source)])), vec![5, 8, 12]);
}
#[test]
fn std_instant_ends_a_native_cfg_if_let_at_its_body_not_at_a_struct_pattern() {
let source = r#"
enum State { Ready { at: u64 }, Idle }
fn run(state: State, other: State) {
#[cfg(unix)]
if let State::Ready { .. } = state { let _a = std::time::Instant::now(); }
let b = std::time::Instant::now();
#[cfg(unix)]
while let State::Ready { at } = other { let _c = std::time::Instant::now(); }
let d = std::time::Instant::now();
#[cfg(unix)]
if let State::Idle = state { 0 } else if let State::Ready { at: 0..=9 } = state { let _e = std::time::Instant::now(); } else { let _f = std::time::Instant::now(); }
let g = std::time::Instant::now();
#[cfg(unix)]
if let State::Ready { .. } = state && let State::Ready { at } = other { let _h = std::time::Instant::now(); }
let i = std::time::Instant::now();
#[cfg(unix)]
for State::Ready { at } in [state] { let _j = std::time::Instant::now(); }
let k = std::time::Instant::now();
}
"#;
assert_eq!(lines(&std_instant([("src/run.rs", source)])), vec![6, 9, 12, 15, 18]);
}
#[test]
fn std_instant_ends_a_native_cfg_let_else_and_match_with_struct_patterns_where_they_end() {
let source = r#"
enum State { Ready { at: u64 }, Idle }
fn run(state: State, other: State) -> u64 {
#[cfg(unix)]
let State::Ready { at } = state else { let _a = std::time::Instant::now(); return 0; };
let b = std::time::Instant::now();
#[cfg(unix)]
match other { State::Ready { at } => { let _c = std::time::Instant::now(); } State::Idle => {} }
let d = std::time::Instant::now();
match state {
#[cfg(unix)]
State::Ready { at } => if let State::Ready { .. } = other { let _e = std::time::Instant::now(); },
_ => { let f = std::time::Instant::now(); }
}
0
}
"#;
assert_eq!(lines(&std_instant([("src/run.rs", source)])), vec![6, 9, 13]);
}
#[test]
fn std_instant_reads_raw_identifiers_as_names_not_keywords() {
let source = r#"
fn run(r#let: bool, r#in: [u8; 1]) {
#[cfg(unix)]
if r#let { let _a = std::time::Instant::now(); }
let b = std::time::Instant::now();
#[cfg(unix)]
for x in r#in { let _c = std::time::Instant::now(); }
let d = std::time::Instant::now();
}
"#;
assert_eq!(lines(&std_instant([("src/run.rs", source)])), vec![5, 8]);
let lib = "#[cfg(unix)]\nmod r#match;\nmod r#loop;\n";
let native = "use std::time::Instant;\n";
let web = "use std::time::Instant;\n";
assert_eq!(finding_paths(&std_instant([("src/lib.rs", lib), ("src/match.rs", native), ("src/loop.rs", web)])), vec!["src/loop.rs"]);
}
#[test]
fn std_instant_runs_a_native_cfg_async_block_statement_to_its_semicolon() {
let source = r#"