From 87bbc1c711398b307c195b604cb6fdfe8a570a60 Mon Sep 17 00:00:00 2001 From: Zach Shallbetter Date: Fri, 16 Oct 2026 13:51:16 -0700 Subject: [PATCH 01/33] craft-testkit: add source-level platform regression guards (closes #139) Add craft-testkit with source guards for platform rules that broke before: - predefined_quit: flags calls of muda PredefinedMenuItem::quit that bypass dirty document save prompts and window teardown on macOS. - wgsl_float_literals: scans WGSL shaders using PhotoCraft's decimal float scanner and flags literals exceeding f32 finite range that fail on WebGPU compilers (Tint). - std_instant: flags lines naming std::time::Instant without web_time in code running on the web, preventing wasm32 runtime panics. - rust_sources: directory crawler discovering a crate's .rs sources while excluding test files and test directories. --- Cargo.lock | 4 + Cargo.toml | 1 + crates/testkit/Cargo.toml | 13 + crates/testkit/README.md | 79 ++++++ crates/testkit/src/guards.rs | 465 +++++++++++++++++++++++++++++++++ crates/testkit/src/lib.rs | 32 +++ crates/testkit/tests/guards.rs | 330 +++++++++++++++++++++++ 7 files changed, 924 insertions(+) create mode 100644 crates/testkit/Cargo.toml create mode 100644 crates/testkit/README.md create mode 100644 crates/testkit/src/guards.rs create mode 100644 crates/testkit/src/lib.rs create mode 100644 crates/testkit/tests/guards.rs diff --git a/Cargo.lock b/Cargo.lock index 3d8cf4a7b3..7b8d513e3b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2569,6 +2569,10 @@ dependencies = [ "kurbo 0.13.1", ] +[[package]] +name = "craft-testkit" +version = "0.1.0" + [[package]] name = "craft-text" version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index 576efca6f1..fab6b70440 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -138,6 +138,7 @@ craft-stencilcraft-format = { path = "crates/stencilcraft-format" } craft-stencilcraft-document = { path = "crates/stencilcraft-document" } craft-svg-paths = { path = "crates/svg-paths" } craft-stream-codecs = { path = "crates/stream-codecs" } +craft-testkit = { path = "crates/testkit" } craft-text = { path = "crates/text" } craft-texture = { path = "crates/texture" } craft-tga = { path = "crates/tga" } diff --git a/crates/testkit/Cargo.toml b/crates/testkit/Cargo.toml new file mode 100644 index 0000000000..d2a3b3179f --- /dev/null +++ b/crates/testkit/Cargo.toml @@ -0,0 +1,13 @@ +[package] +name = "craft-testkit" +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true +repository.workspace = true +description = "Source-level platform regression guards and verification utilities for the Craft application suite" + +[dependencies] + +[lints] +workspace = true diff --git a/crates/testkit/README.md b/crates/testkit/README.md new file mode 100644 index 0000000000..d7208396b6 --- /dev/null +++ b/crates/testkit/README.md @@ -0,0 +1,79 @@ +# craft-testkit + +Source-level platform regression guards and verification utilities for the Craft application suite. + +## Overview + +`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. 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 using PhotoCraft's decimal float scanner and flags literals whose absolute value exceeds `f32::MAX` (such as `3.40282347e38`). While native compilers (`naga`) round these down, browser WebGPU compilers (`Tint` in Chromium) reject them with fatal pipeline compilation errors, forcing applications into CPU fallback rendering. Exact values equal to `f32::MAX` must be written as exact hex float literals (`0x1.fffffep+127f`). +3. **`std_instant`**: Flags lines naming `std::time::Instant` outside comments without `web_time`. On `wasm32-unknown-unknown`, `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`), and build artifacts (`target/`, `.git/`). + +## Epistemic Scope: Syntactic Guards vs Runtime Validation + +Source-level guards provide deterministic syntactic evidence about codebase structure: + +### What They Establish +- Checked source files do not contain forbidden symbol invocations, known out-of-range literal representations, or platform-hazardous imports. +- Reusable, deterministic checks that run in milliseconds as regular Cargo tests without external runners. + +### What They Cannot Establish +- **Runtime execution safety**: Syntactic checks do not verify whether code branches actually execute at runtime. +- **Semantic type resolution**: The scanners do not resolve arbitrary type aliases (e.g. `use std::time as t; t::Instant::now()`) or expand procedural macros. +- **Complex target predicates**: While `std_instant` recognizes direct item-level non-wasm target conditions (e.g. `#[cfg(not(target_arch = "wasm32"))]`), it does not evaluate arbitrary multi-crate boolean expressions. Applications should scope `std_instant` tests to the specific crates that compile into their web distribution. +- **Driver and host OS behavior**: Syntactic checks do not verify WebGPU driver compatibility or host window manager event dispatch. + +Source guards serve as fast, zero-dependency regression gates in application test suites, complementing platform integration tests and CI workflows. + +## Consumer Adoption Examples + +### 1. PhotoCraft: Adopt `wgsl_float_literals` and `predefined_quit` + +In `photocraft/crates/gpu/src/lib.rs`, replace the in-tree `decimal_float_literals` helper with `craft_testkit::wgsl_float_literals`: + +```rust +#[test] +fn shader_float_literals_fit_f32() { + let bad = craft_testkit::wgsl_float_literals(SHADER); + assert!( + bad.is_empty(), + "float literals outside f32 finite range reject on WebGPU (Tint):\n{}", + bad.iter().map(|f| f.to_string()).collect::>().join("\n") + ); +} +``` + +In `photocraft/apps/photocraft/tests/native_menu_tests.rs`: + +```rust +#[test] +fn no_unintercepted_predefined_quit_in_menu() { + let sources = craft_testkit::rust_sources("src").expect("scan sources"); + let findings = craft_testkit::predefined_quit(&sources); + assert!( + findings.is_empty(), + "predefined muda Quit bypasses dirty document save prompts:\n{}", + findings.iter().map(|f| f.to_string()).collect::>().join("\n") + ); +} +``` + +### 2. FilmCraft: Adopt `std_instant` and `wgsl_float_literals` + +In `filmcraft/crates/engine/src/wasm_clock_tests.rs`, replace in-tree textual search with `craft_testkit::std_instant`: + +```rust +#[test] +fn no_std_instant_in_code_the_web_build_runs() { + let sources = craft_testkit::rust_sources(Path::new(env!("CARGO_MANIFEST_DIR")).join("src")) + .expect("scan engine sources"); + let findings = craft_testkit::std_instant(&sources); + assert!( + findings.is_empty(), + "std::time::Instant panics on wasm32; use web_time::Instant:\n{}", + findings.iter().map(|f| f.to_string()).collect::>().join("\n") + ); +} +``` diff --git a/crates/testkit/src/guards.rs b/crates/testkit/src/guards.rs new file mode 100644 index 0000000000..2f8c50d234 --- /dev/null +++ b/crates/testkit/src/guards.rs @@ -0,0 +1,465 @@ +//! Platform regression guards checking source code for known defects and lifecycle hazards. + +use std::fmt; +#[cfg(not(target_arch = "wasm32"))] +use std::path::Path; + +/// A diagnostic finding reported by a source guard. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Finding { + /// File path where the violation was detected. + pub path: String, + /// 1-based line number of the violation. + pub line: usize, + /// Diagnostic context (the offending code snippet or float literal). + pub text: String, +} + +impl Finding { + /// Create a new diagnostic finding. + pub fn new(path: impl Into, line: usize, text: impl Into) -> Self { + Self { path: path.into(), line, text: text.into() } + } +} + +impl fmt::Display for Finding { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + if self.path.is_empty() { write!(f, "{}: {}", self.line, self.text) } else { write!(f, "{}:{}: {}", self.path, self.line, self.text) } + } +} + +/// Abstraction over a source file path and its text content. +pub trait AsFileSource { + /// Path of the source file. + fn path(&self) -> &str; + /// Text content of the source file. + fn content(&self) -> &str; +} + +impl AsFileSource for (String, String) { + fn path(&self) -> &str { + &self.0 + } + fn content(&self) -> &str { + &self.1 + } +} + +impl AsFileSource for &(String, String) { + fn path(&self) -> &str { + &self.0 + } + fn content(&self) -> &str { + &self.1 + } +} + +impl AsFileSource for (&str, &str) { + fn path(&self) -> &str { + self.0 + } + fn content(&self) -> &str { + self.1 + } +} + +impl AsFileSource for &(&str, &str) { + fn path(&self) -> &str { + self.0 + } + fn content(&self) -> &str { + self.1 + } +} + +impl AsFileSource for (String, &str) { + fn path(&self) -> &str { + &self.0 + } + fn content(&self) -> &str { + self.1 + } +} + +impl AsFileSource for &(String, &str) { + fn path(&self) -> &str { + &self.0 + } + fn content(&self) -> &str { + self.1 + } +} + +impl AsFileSource for (&str, String) { + fn path(&self) -> &str { + self.0 + } + fn content(&self) -> &str { + &self.1 + } +} + +impl AsFileSource for &(&str, String) { + fn path(&self) -> &str { + self.0 + } + fn content(&self) -> &str { + &self.1 + } +} + +/// Replace code comments and string literals with whitespace while preserving newlines and line counts. +/// +/// Handles single-line comments (`//`), block comments (`/* ... */`, including nested comments), +/// normal string literals (`"..."`), and raw string literals (`r#"..."#`). +fn mask_comments_and_strings(code: &str) -> String { + let mut out = String::with_capacity(code.len()); + let chars: Vec = code.chars().collect(); + let len = chars.len(); + let mut i = 0; + let mut in_line_comment = false; + let mut block_comment_depth: usize = 0; + let mut in_normal_string = false; + let mut raw_string_hashes: Option = None; + let mut escape = false; + + while i < len { + let c = chars[i]; + if in_line_comment { + if c == '\n' { + in_line_comment = false; + out.push('\n'); + } else { + out.push(' '); + } + i += 1; + } else if block_comment_depth > 0 { + if c == '*' && i + 1 < len && chars[i + 1] == '/' { + block_comment_depth = block_comment_depth.saturating_sub(1); + out.push(' '); + out.push(' '); + i += 2; + } else if c == '/' && i + 1 < len && chars[i + 1] == '*' { + block_comment_depth = block_comment_depth.saturating_add(1); + out.push(' '); + out.push(' '); + i += 2; + } else if c == '\n' { + out.push('\n'); + i += 1; + } else { + out.push(' '); + i += 1; + } + } else if let Some(hashes) = raw_string_hashes { + if c == '"' { + let mut match_hashes = true; + if i + hashes < len { + for h in 0..hashes { + if chars[i + 1 + h] != '#' { + match_hashes = false; + break; + } + } + } else { + match_hashes = false; + } + if match_hashes { + raw_string_hashes = None; + for _ in 0..=hashes { + out.push(' '); + } + i += 1 + hashes; + continue; + } + } + if c == '\n' { + out.push('\n'); + } else { + out.push(' '); + } + i += 1; + } else if in_normal_string { + if escape { + escape = false; + out.push(' '); + } else if c == '\\' { + escape = true; + out.push(' '); + } else if c == '"' { + in_normal_string = false; + out.push(' '); + } else if c == '\n' { + out.push('\n'); + } else { + out.push(' '); + } + i += 1; + } else { + if c == '/' && i + 1 < len && chars[i + 1] == '/' { + in_line_comment = true; + out.push(' '); + out.push(' '); + i += 2; + } else if c == '/' && i + 1 < len && chars[i + 1] == '*' { + block_comment_depth = 1; + out.push(' '); + out.push(' '); + i += 2; + } else if c == '"' { + in_normal_string = true; + out.push(' '); + i += 1; + } else if c == 'r' && i + 1 < len && (chars[i + 1] == '"' || chars[i + 1] == '#') { + let mut j = i + 1; + let mut hashes = 0; + while j < len && chars[j] == '#' { + hashes += 1; + j += 1; + } + if j < len && chars[j] == '"' { + raw_string_hashes = Some(hashes); + for _ in i..=j { + out.push(' '); + } + i = j + 1; + } else { + out.push(c); + i += 1; + } + } else { + out.push(c); + i += 1; + } + } + } + out +} + +/// Guard: detects direct calls to `muda`'s predefined Quit menu item. +/// +/// Using `PredefinedMenuItem::quit` connects the macOS menu directly to `NSApplication terminate:`, +/// which bypasses dirty document checks, unsaved changes save prompts, and lifecycle cleanup. +/// Applications should route Quit through custom menu items or interceptors connected to `craft-quit`. +pub fn predefined_quit(files: I) -> Vec +where + I: IntoIterator, + I::Item: AsFileSource, +{ + let mut findings = Vec::new(); + for file in files { + let path = file.path(); + let content = file.content(); + let masked = mask_comments_and_strings(content); + + for (orig_line, (idx, masked_line)) in content.lines().zip(masked.lines().enumerate()) { + let normalized = masked_line.replace(' ', ""); + if normalized.contains("PredefinedMenuItem::quit") || normalized.contains("PredefinedMenuItem::Quit") { + findings.push(Finding::new(path, idx + 1, orig_line.trim())); + } + } + } + findings +} + +/// Guard: detects uses of `std::time::Instant` outside comments in code paths running on the web. +/// +/// On `wasm32-unknown-unknown`, `std::time::Instant::now()` panics with "time not implemented +/// on this platform". Crates running in the browser should use `web_time::Instant`, which maps to +/// `std::time::Instant` on native platforms and `performance.now()` on the web. +/// +/// ### Syntactic Scope and Limitations +/// +/// * **Targeted files**: Callers should pass files from crates that compile into the application's web build. +/// * **Allowed patterns**: Comments, string literals, lines containing `web_time`, and items decorated with +/// explicit non-wasm target conditions (e.g. `#[cfg(not(target_arch = "wasm32"))]` or `#[cfg(target_os = ...)]`) +/// are skipped. +/// * **Limitations**: This is a lexical source guard. It does not perform semantic type resolution, macro +/// expansion, or track arbitrary module aliases (e.g. `use std::time as t; t::Instant`). +pub fn std_instant(files: I) -> Vec +where + I: IntoIterator, + I::Item: AsFileSource, +{ + let mut findings = Vec::new(); + for file in files { + let path = file.path(); + let content = file.content(); + let masked = mask_comments_and_strings(content); + + let mut in_cfg_non_wasm = false; + let mut cfg_brace_depth: usize = 0; + + for (orig_line, (idx, masked_line)) in content.lines().zip(masked.lines().enumerate()) { + let is_comment_only = masked_line.trim().is_empty(); + let line_has_cfg_non_wasm = !is_comment_only + && (orig_line.contains("cfg(not(target_arch = \"wasm32\"))") + || orig_line.contains("cfg(target_arch = \"x86_64\")") + || orig_line.contains("cfg(target_arch = \"aarch64\")") + || orig_line.contains("cfg(target_os =")); + + if line_has_cfg_non_wasm { + in_cfg_non_wasm = true; + } + + let names_std_instant = + masked_line.contains("time::Instant") || (masked_line.contains("use std::time::") && masked_line.contains("Instant")); + + if names_std_instant && !masked_line.contains("web_time") && !in_cfg_non_wasm { + findings.push(Finding::new(path, idx + 1, orig_line.trim())); + } + + if in_cfg_non_wasm && !is_comment_only { + let opens = masked_line.chars().filter(|&c| c == '{').count(); + let closes = masked_line.chars().filter(|&c| c == '}').count(); + if cfg_brace_depth == 0 { + if opens > 0 { + cfg_brace_depth = cfg_brace_depth.saturating_add(opens).saturating_sub(closes); + if cfg_brace_depth == 0 { + in_cfg_non_wasm = false; + } + } else if masked_line.contains(';') { + in_cfg_non_wasm = false; + } + } else { + cfg_brace_depth = cfg_brace_depth.saturating_add(opens).saturating_sub(closes); + if cfg_brace_depth == 0 { + in_cfg_non_wasm = false; + } + } + } + } + } + findings +} + +/// Guard: scans a single WGSL shader string and detects decimal float literals outside `f32`'s finite range. +/// +/// Browser WebGPU compilers (such as Chrome's Tint) reject float literals exceeding `f32::MAX` +/// (e.g. `3.40282347e38`), triggering fatal pipeline build errors and fallback to CPU rendering. +/// Exact values equal to `f32::MAX` should be written as hex float literals (e.g. `0x1.fffffep+127f`). +/// +/// ### Policy and Limitations +/// +/// * **Conservative mathematical bound**: The guard evaluates the parsed mathematical magnitude against +/// `f64::from(f32::MAX)`. Any decimal literal exceeding this threshold is flagged, even if native +/// compilers like `naga` would round it down to `f32::MAX`. +/// * **Hexadecimal floats**: Exact hex float literals (`0x...p...`) are skipped as they represent exact bit patterns. +/// * **Comments and strings**: Comments (`//` and `/* ... */`) and string contents are masked out prior to scanning. +pub fn wgsl_float_literals(wgsl: &str) -> Vec { + wgsl_float_literals_in([("", wgsl)]) +} + +/// Guard: scans multiple WGSL shader files and detects decimal float literals outside `f32`'s finite range. +pub fn wgsl_float_literals_in(files: I) -> Vec +where + I: IntoIterator, + I::Item: AsFileSource, +{ + let mut findings = Vec::new(); + for file in files { + let path = file.path(); + let content = file.content(); + let masked = mask_comments_and_strings(content); + + for (n, line) in masked.lines().enumerate() { + let code = line.as_bytes(); + let mut i = 0; + while i < code.len() { + let digit_or_dot = code[i].is_ascii_digit() || (code[i] == b'.' && code.get(i + 1).is_some_and(u8::is_ascii_digit)); + let word_before = i > 0 && (code[i - 1].is_ascii_alphanumeric() || code[i - 1] == b'_' || code[i - 1] == b'.'); + if !digit_or_dot || word_before { + i += 1; + continue; + } + // Skip hex float literals (e.g. 0x1.fffffep+127f, 0x1.0p0h) + if code[i] == b'0' && matches!(code.get(i + 1), Some(b'x' | b'X')) { + i += 2; + while i < code.len() && (code[i].is_ascii_hexdigit() || matches!(code[i], b'.' | b'p' | b'P' | b'+' | b'-' | b'f' | b'h')) { + i += 1; + } + continue; + } + let start = i; + while i < code.len() && (code[i].is_ascii_digit() || code[i] == b'.') { + i += 1; + } + if i < code.len() && matches!(code[i], b'e' | b'E') { + let mut j = i + 1; + if j < code.len() && matches!(code[j], b'+' | b'-') { + j += 1; + } + if j < code.len() && code[j].is_ascii_digit() { + i = j; + while i < code.len() && code[i].is_ascii_digit() { + i += 1; + } + } + } + let literal = String::from_utf8_lossy(&code[start..i]); + if i < code.len() && matches!(code[i], b'f' | b'h') { + i += 1; + } + let is_overflow = match literal.parse::() { + Ok(v) => !v.is_finite() || v.abs() > f64::from(f32::MAX), + Err(_) => true, + }; + if is_overflow { + findings.push(Finding::new(path, n + 1, literal.into_owned())); + } + } + } + } + findings +} + +/// Recursively collect all Rust source files under `dir`, excluding test files and test directories. +/// +/// Excluded files: +/// * `tests.rs` +/// * `tests_*.rs` +/// * `*_tests.rs` +/// * `*_test.rs` +/// * `test.rs` +/// * Any file within a directory component named `tests`, `benches`, `examples`, `.git`, or `target`. +/// +/// Results are sorted lexicographically by file path for deterministic behavior across platforms. +#[cfg(not(target_arch = "wasm32"))] +pub fn rust_sources(dir: impl AsRef) -> std::io::Result> { + let root = dir.as_ref(); + let mut files = Vec::new(); + let mut dirs = vec![root.to_path_buf()]; + + while let Some(d) = dirs.pop() { + let entries = std::fs::read_dir(&d)?; + for entry in entries { + let entry = entry?; + let p = entry.path(); + let metadata = std::fs::metadata(&p)?; + if metadata.is_dir() { + let dirname = p.file_name().and_then(|n| n.to_str()).unwrap_or_default(); + if dirname.starts_with('.') || dirname == "target" || dirname == "tests" || dirname == "benches" || dirname == "examples" { + continue; + } + dirs.push(p); + } else if metadata.is_file() { + let name = p.file_name().and_then(|n| n.to_str()).unwrap_or_default(); + if !name.ends_with(".rs") { + continue; + } + if name == "tests.rs" || name.starts_with("tests_") || name.ends_with("_tests.rs") || name.ends_with("_test.rs") || name == "test.rs" + { + continue; + } + if p.components().any(|c| c.as_os_str() == "tests") { + continue; + } + let content = std::fs::read_to_string(&p)?; + files.push((p.display().to_string(), content)); + } + } + } + + files.sort_by(|a, b| a.0.cmp(&b.0)); + Ok(files) +} diff --git a/crates/testkit/src/lib.rs b/crates/testkit/src/lib.rs new file mode 100644 index 0000000000..b0e61fc8b5 --- /dev/null +++ b/crates/testkit/src/lib.rs @@ -0,0 +1,32 @@ +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +#![forbid(unsafe_code)] + +//! Source-level platform regression guards and verification utilities for the Craft application suite. +//! +//! This crate provides non-panicking source analysis guards that detect known platform hazards +//! and lifecycle regressions across Craft applications: +//! +//! * [`guards::predefined_quit`]: flags direct calls to `muda`'s predefined Quit item that bypass +//! dirty document save prompts and window teardown on macOS. +//! * [`guards::wgsl_float_literals`]: flags decimal float literals exceeding `f32`'s finite range, +//! which break browser WebGPU compilers (Tint) and trigger CPU fallbacks. +//! * [`guards::std_instant`]: flags uses of `std::time::Instant` in code paths targeting the web, +//! where `std::time::Instant::now()` panics on `wasm32`. +//! * [`guards::rust_sources`]: directory crawler collecting `.rs` sources while excluding tests. +//! +//! ### Epistemic Scope: What Source Guards Establish vs What They Cannot +//! +//! Source-level guards provide deterministic syntactic evidence about codebase structure. +//! They establish that checked source files do not contain forbidden symbol names, known invalid +//! literal patterns, or unsafe platform invocations. +//! +//! They do **not** establish runtime correctness, protocol concurrency safety, or platform behavior +//! under foreign host environments. They are lightweight syntactic regression gates designed to complement, +//! rather than replace, platform integration tests and CI execution. + +pub mod guards; + +pub use guards::{Finding, predefined_quit, std_instant, wgsl_float_literals, wgsl_float_literals_in}; + +#[cfg(not(target_arch = "wasm32"))] +pub use guards::rust_sources; diff --git a/crates/testkit/tests/guards.rs b/crates/testkit/tests/guards.rs new file mode 100644 index 0000000000..ee6daae7d7 --- /dev/null +++ b/crates/testkit/tests/guards.rs @@ -0,0 +1,330 @@ +use craft_testkit::{Finding, predefined_quit, std_instant, wgsl_float_literals, wgsl_float_literals_in}; + +#[test] +fn test_finding_display() { + let f1 = Finding::new("src/menu.rs", 42, "PredefinedMenuItem::quit()"); + assert_eq!(f1.to_string(), "src/menu.rs:42: PredefinedMenuItem::quit()"); + + let f2 = Finding::new("", 156, "3.40282347e38"); + assert_eq!(f2.to_string(), "156: 3.40282347e38"); +} + +#[test] +fn test_predefined_quit_positive() { + let source = r#" +fn setup_menu() { + let quit = PredefinedMenuItem::quit(Some("Quit")); + bar.add(quit); +} +"#; + let findings = predefined_quit([("src/menu.rs", source)]); + assert_eq!(findings.len(), 1); + assert_eq!(findings[0].path, "src/menu.rs"); + assert_eq!(findings[0].line, 3); + assert_eq!(findings[0].text, "let quit = PredefinedMenuItem::quit(Some(\"Quit\"));"); + assert_eq!(findings[0].to_string(), "src/menu.rs:3: let quit = PredefinedMenuItem::quit(Some(\"Quit\"));"); +} + +#[test] +fn test_predefined_quit_negative_and_comments() { + let source = r#" +// PredefinedMenuItem::quit(None) - do not use this! +/* + * PredefinedMenuItem::quit is hazardous + */ +fn setup_menu() { + let sep = PredefinedMenuItem::separator(); + let hide = PredefinedMenuItem::hide(Some("Hide")); + let note = "PredefinedMenuItem::quit in string should not trigger"; +} +"#; + let findings = predefined_quit([("src/safe_menu.rs", source)]); + assert!(findings.is_empty(), "expected zero findings for comments, separators, and strings: {findings:?}"); +} + +/// Historical failure: FilmCraft `apps/filmcraft/src/native_menu.rs:56` +/// used `PredefinedMenuItem::quit`, routing directly to `NSApplication terminate:` and bypassing save prompts. +#[test] +fn test_historical_filmcraft_native_menu_quit_regression() { + let problematic_source = r#" + let predefined = [ + (hide_label, PredefinedMenuItem::hide(Some(app.ui.language.tr(hide_label)))), + (hide_others_label, PredefinedMenuItem::hide_others(Some(app.ui.language.tr(hide_others_label)))), + (quit_label, PredefinedMenuItem::quit(Some(app.ui.language.tr(quit_label)))), + ]; +"#; + let findings = predefined_quit([("apps/filmcraft/src/native_menu.rs", problematic_source)]); + assert_eq!(findings.len(), 1); + assert_eq!(findings[0].line, 5); + assert_eq!(findings[0].text, "(quit_label, PredefinedMenuItem::quit(Some(app.ui.language.tr(quit_label)))),"); + + // Corrected source wires Quit via MenuItem::with_id and craft-quit lifecycle + let corrected_source = r#" + let quit = MenuItem::with_id("app.quit", label("app.quit", "Quit FilmCraft"), true, None); + let predefined = [ + (hide_label, PredefinedMenuItem::hide(Some(app.ui.language.tr(hide_label)))), + (hide_others_label, PredefinedMenuItem::hide_others(Some(app.ui.language.tr(hide_others_label)))), + ]; +"#; + let corrected_findings = predefined_quit([("apps/filmcraft/src/native_menu.rs", corrected_source)]); + assert!(corrected_findings.is_empty()); +} + +#[test] +fn test_std_instant_positive() { + let source = r#" +use std::time::Instant; +use std::time::{Duration, Instant as StdInstant}; + +fn measure() { + let t0 = std::time::Instant::now(); +} +"#; + let findings = std_instant([("src/clock.rs", source)]); + assert_eq!(findings.len(), 3); + assert_eq!(findings[0].line, 2); + assert_eq!(findings[1].line, 3); + assert_eq!(findings[2].line, 6); +} + +#[test] +fn test_std_instant_negative_and_web_time() { + let source = r#" +// std::time::Instant::now() causes wasm panic +/* + use std::time::Instant; +*/ +use web_time::Instant; +use std::time::Duration; + +fn measure() { + let t0 = web_time::Instant::now(); + let d = Duration::from_millis(100); +} +"#; + let findings = std_instant([("src/safe_clock.rs", source)]); + assert!(findings.is_empty(), "expected zero findings for web_time, duration, and comments: {findings:?}"); +} + +/// Historical failure: FilmCraft `crates/engine/src/wasm_clock_tests.rs` +/// jobs running synchronously on wasm32 called `std::time::Instant::now()`, panicking at runtime. +#[test] +fn test_historical_filmcraft_wasm_clock_instant_regression() { + let problematic_source = r#" + use std::time::Instant; + + pub fn run_job() { + let t0 = std::time::Instant::now(); + } +"#; + let findings = std_instant([("crates/engine/src/job.rs", problematic_source)]); + assert_eq!(findings.len(), 2); + + let corrected_source = r#" + use web_time::Instant; + + pub fn run_job() { + let t0 = web_time::Instant::now(); + } +"#; + let corrected_findings = std_instant([("crates/engine/src/job.rs", corrected_source)]); + assert!(corrected_findings.is_empty()); + + // User's specific conditional compilation test case: + let native_guarded_inline = r#" +#[cfg(not(target_arch = "wasm32"))] fn timestamp() -> std::time::Instant { std::time::Instant::now() } +"#; + assert!(std_instant([("src/native.rs", native_guarded_inline)]).is_empty()); + + let native_guarded_multiline = r#" +#[cfg(not(target_arch = "wasm32"))] +fn timestamp() -> std::time::Instant { + std::time::Instant::now() +} +"#; + assert!(std_instant([("src/native.rs", native_guarded_multiline)]).is_empty()); +} + +/// Historical failure: PhotoCraft PR #1722 / #1982 `crates/gpu/src/compose.wgsl:156` +/// `const F32_MAX: f32 = 3.40282347e38;` is slightly above f32::MAX. Naga rounds it natively, +/// but Chromium WebGPU compiler (Tint) rejects it, disabling the GPU compositor. +#[test] +fn test_historical_photocraft_compose_wgsl_regression() { + let problematic_shader = r#" +// line 156 of compose.wgsl +const F32_MAX: f32 = 3.40282347e38; +"#; + let findings = wgsl_float_literals(problematic_shader); + assert_eq!(findings.len(), 1); + assert_eq!(findings[0].line, 3); + assert_eq!(findings[0].text, "3.40282347e38"); + + // Corrected shader uses exact hexadecimal float representation + let corrected_shader = r#" +// exact f32::MAX bit for bit +const F32_MAX: f32 = 0x1.fffffep+127f; +"#; + let corrected_findings = wgsl_float_literals(corrected_shader); + assert!(corrected_findings.is_empty()); +} + +#[test] +fn test_wgsl_float_literals_controls() { + // 1. Scientific notation and signed values + let signed_and_sci = r#" +const OVER_POS: f32 = 1e39; +const OVER_NEG: f32 = -1e39; +const VALID_POS: f32 = 1.5e10; +const VALID_NEG: f32 = -1.5e10; +const VALID_TINY: f32 = 1e-40; +"#; + let findings = wgsl_float_literals(signed_and_sci); + assert_eq!(findings.len(), 2); + assert_eq!(findings[0].text, "1e39"); + assert_eq!(findings[1].text, "1e39"); // Scanned magnitude of -1e39 + + // 2. Hexadecimal floating-point representations + let hex_floats = r#" +const EXACT_MAX: f32 = 0x1.fffffep+127f; +const ONE_P0: f32 = 0x1.0p0; +const HALF_HEX: f32 = 0x1.0p-1h; +"#; + assert!(wgsl_float_literals(hex_floats).is_empty()); + + // 3. Literals appearing inside comments + let in_comments = r#" +// const F32_MAX = 3.40282347e38; +/* + const OVERFLOW = 1e40; +*/ +"#; + assert!(wgsl_float_literals(in_comments).is_empty()); + + // 4. Numeric suffixes (f, h) + let suffixes = r#" +const BAD_F: f32 = 3.40282347e38f; +const GOOD_F: f32 = 1.0f; +const GOOD_H: f16 = 0.5h; +"#; + let suffix_findings = wgsl_float_literals(suffixes); + assert_eq!(suffix_findings.len(), 1); + assert_eq!(suffix_findings[0].text, "3.40282347e38"); + + // 5. Embedded in identifiers or other tokens + let idents = r#" +let var_1 = 1.0; +let layer2 = 2.0; +let coord_0 = 0.0; +"#; + assert!(wgsl_float_literals(idents).is_empty()); +} + +#[test] +fn test_wgsl_float_literals_in_multiple_files() { + let s1 = "const A: f32 = 1.0;\nconst B: f32 = 3.40282347e38;\n"; + let s2 = "const OK: f32 = 0x1.fffffep+127f;\n"; + let s3 = "const BAD: f32 = 9.99e38;\n"; + + let files = [("shaders/compose.wgsl", s1), ("shaders/clean.wgsl", s2), ("shaders/fx.wgsl", s3)]; + let findings = wgsl_float_literals_in(files); + assert_eq!(findings.len(), 2); + assert_eq!(findings[0].path, "shaders/compose.wgsl"); + assert_eq!(findings[0].line, 2); + assert_eq!(findings[0].text, "3.40282347e38"); + assert_eq!(findings[1].path, "shaders/fx.wgsl"); + assert_eq!(findings[1].line, 1); + assert_eq!(findings[1].text, "9.99e38"); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn test_predefined_quit_qualified_and_whitespace() { + let source = r#" +fn setup() { + let q1 = muda::PredefinedMenuItem::quit(None); + let q2 = PredefinedMenuItem :: quit(Some("Quit")); + let q3 = crate::menu::PredefinedMenuItem::Quit; +} +"#; + let findings = predefined_quit([("src/menu.rs", source)]); + assert_eq!(findings.len(), 3); + assert_eq!(findings[0].line, 3); + assert_eq!(findings[1].line, 4); + assert_eq!(findings[2].line, 5); +} + +#[test] +fn test_std_instant_module_alias() { + let source = r#" +use std::time; + +fn run() { + let t0 = time::Instant::now(); +} +"#; + let findings = std_instant([("src/worker.rs", source)]); + assert_eq!(findings.len(), 1); + assert_eq!(findings[0].line, 5); +} + +#[test] +fn test_wgsl_exact_f32_max_boundary() { + // 3.4028234663852886e38 is mathematical f32::MAX bit for bit + let exact_valid = r#" +const EXACT_MAX: f32 = 3.4028234663852886e38; +const NEG_EXACT_MAX: f32 = -3.4028234663852886e38; +"#; + assert!(wgsl_float_literals(exact_valid).is_empty()); + + // 3.40282347e38 is slightly above f32::MAX + let just_over = r#" +const OVER_POS: f32 = 3.40282347e38; +const OVER_NEG: f32 = -3.40282347e38; +"#; + let findings = wgsl_float_literals(just_over); + assert_eq!(findings.len(), 2); + assert_eq!(findings[0].text, "3.40282347e38"); + assert_eq!(findings[1].text, "3.40282347e38"); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn test_rust_sources_filtering() { + use craft_testkit::rust_sources; + use std::fs::{self, File}; + use std::io::Write; + + let temp_dir = std::env::temp_dir().join(format!("craft_testkit_test_{}", std::process::id())); + let _ = fs::remove_dir_all(&temp_dir); + fs::create_dir_all(temp_dir.join("src").join("sub")).expect("create temp sub"); + fs::create_dir_all(temp_dir.join("tests")).expect("create temp tests"); + fs::create_dir_all(temp_dir.join("target")).expect("create temp target"); + fs::create_dir_all(temp_dir.join(".github")).expect("create temp dot-dir"); + + let create_file = |path: std::path::PathBuf, content: &str| { + let mut f = File::create(path).expect("create file"); + f.write_all(content.as_bytes()).expect("write content"); + }; + + create_file(temp_dir.join("src").join("lib.rs"), "pub fn lib() {}"); + create_file(temp_dir.join("src").join("sub").join("mod.rs"), "pub fn sub() {}"); + create_file(temp_dir.join("src").join("tests.rs"), "// should exclude"); + create_file(temp_dir.join("src").join("tests_foo.rs"), "// should exclude"); + create_file(temp_dir.join("src").join("foo_tests.rs"), "// should exclude"); + create_file(temp_dir.join("src").join("foo_test.rs"), "// should exclude"); + create_file(temp_dir.join("tests").join("integ.rs"), "// should exclude"); + create_file(temp_dir.join("target").join("gen.rs"), "// should exclude"); + create_file(temp_dir.join(".github").join("action.rs"), "// should exclude dot-dir"); + create_file(temp_dir.join("src").join("README.md"), "# Not a rust source"); + + let sources = rust_sources(&temp_dir).expect("rust_sources"); + let names: Vec = sources.iter().map(|(p, _)| std::path::Path::new(p).file_name().unwrap().to_string_lossy().into_owned()).collect(); + + assert_eq!(names, vec!["lib.rs", "mod.rs"]); + + // Test passing &[(&str, &str)] to guards + let findings = predefined_quit(&sources); + assert!(findings.is_empty()); + + let _ = fs::remove_dir_all(&temp_dir); +} From 52b917fce5bdab996288dc79c4d8b75af84bcb4d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 11:16:07 -0800 Subject: [PATCH 02/33] craft-testkit: guards read Rust tokens, check hex and f16 floats, and bound rust_sources predefined_quit and std_instant now run on a small Rust lexer instead of a masked line search: - Character and byte literals such as '"' no longer open a phantom string that hides the code after them. - A Quit call split by tabs or a line break around :: is reported, a different name such as MyPredefinedMenuItem or quitter is not, and a use muda::PredefinedMenuItem as X rename is followed. - std_instant reports std::time::Instant, ::Instant where a use binds m to std::time, and each use that imports std::time::Instant or std::time::*. A line that also names web_time is still reported, and an unrelated time::Instant is not. - cfg attributes are read from code, not from strings or comments, and evaluated for wasm32-unknown-unknown (all, any, not, unix, windows, target_* keys). An outer attribute covers the item after it, an inner one the rest of its module. A predicate that depends on a feature or test is checked. wgsl_float_literals skips integer literals, reports hexadecimal floats above f32::MAX, and checks an h-suffixed float against 65504. rust_sources does not follow symbolic links, skips folders that hold a CACHEDIR.TAG file, no longer drops every file when the root itself is under a folder named tests, and returns an error for a file over 8 MiB, more than 256 MiB in all or more than 50,000 files. rust_sources_with_limits takes other limits. The tests use a scratch folder that is never reused and is removed when a test panics. The crate is not published, and the root README lists it. --- README.md | 3 + crates/testkit/Cargo.toml | 1 + crates/testkit/README.md | 25 +- crates/testkit/src/guards.rs | 1012 ++++++++++++++++++++----- crates/testkit/src/lib.rs | 11 +- crates/testkit/tests/guards.rs | 397 +++++++++- crates/testkit/tests/source_limits.rs | 99 +++ 7 files changed, 1313 insertions(+), 235 deletions(-) create mode 100644 crates/testkit/tests/source_limits.rs diff --git a/README.md b/README.md index c6e95bd4f9..adbb6c120e 100644 --- a/README.md +++ b/README.md @@ -345,6 +345,9 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit check for drawing a tree with resvg. Apps take usvg from here, not as their own dependency. - [`craft-svg-paths`](crates/svg-paths/src/lib.rs): the former name of `craft-svg`'s `paths`, `color` and `write`; re-exports them for existing users. +- [`craft-testkit`](crates/testkit/README.md): test support for the apps' own tests. Its `guards` module + reports source patterns that broke platforms before: muda's predefined Quit item, WGSL float literals + out of range, and `std::time::Instant` in code the web build runs. Not published. - [`craft-text`](crates/text/README.md): text processing below the composer. Its `hyphen` module finds hyphenation points, with a bundled US English dictionary and patterns and optional hypher patterns for 47 more languages (one cargo feature each). diff --git a/crates/testkit/Cargo.toml b/crates/testkit/Cargo.toml index d2a3b3179f..d32ed735f4 100644 --- a/crates/testkit/Cargo.toml +++ b/crates/testkit/Cargo.toml @@ -6,6 +6,7 @@ license.workspace = true rust-version.workspace = true repository.workspace = true description = "Source-level platform regression guards and verification utilities for the Craft application suite" +publish = false [dependencies] diff --git a/crates/testkit/README.md b/crates/testkit/README.md index d7208396b6..75e74d7b82 100644 --- a/crates/testkit/README.md +++ b/crates/testkit/README.md @@ -6,10 +6,10 @@ 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. 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 using PhotoCraft's decimal float scanner and flags literals whose absolute value exceeds `f32::MAX` (such as `3.40282347e38`). While native compilers (`naga`) round these down, browser WebGPU compilers (`Tint` in Chromium) reject them with fatal pipeline compilation errors, forcing applications into CPU fallback rendering. Exact values equal to `f32::MAX` must be written as exact hex float literals (`0x1.fffffep+127f`). -3. **`std_instant`**: Flags lines naming `std::time::Instant` outside comments without `web_time`. On `wasm32-unknown-unknown`, `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`), and build artifacts (`target/`, `.git/`). +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 `::` 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. +2. **`wgsl_float_literals` / `wgsl_float_literals_in`**: Scans WGSL shader sources and flags decimal and hexadecimal float literals whose value exceeds `f32::MAX` (such as `3.40282347e38` or `0x1p+500f`), or 65504, the largest finite `f16`, for a literal with an `h` suffix. 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. Exact values equal to `f32::MAX` can be written as `3.4028234663852886e38` or as the hex float `0x1.fffffep+127f`. +3. **`std_instant`**: Flags `std::time::Instant` outside comments and strings: the full path, `::Instant` where a `use` binds `m` to `std::time`, and each `use` that imports `std::time::Instant` or `std::time::*`. Other crates' `Instant` (such as `web_time::Instant`) is not flagged, and neither is an item whose `cfg` attribute is false on `wasm32-unknown-unknown`. 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, `.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`. ## Epistemic Scope: Syntactic Guards vs Runtime Validation @@ -21,8 +21,8 @@ Source-level guards provide deterministic syntactic evidence about codebase stru ### What They Cannot Establish - **Runtime execution safety**: Syntactic checks do not verify whether code branches actually execute at runtime. -- **Semantic type resolution**: The scanners do not resolve arbitrary type aliases (e.g. `use std::time as t; t::Instant::now()`) or expand procedural macros. -- **Complex target predicates**: While `std_instant` recognizes direct item-level non-wasm target conditions (e.g. `#[cfg(not(target_arch = "wasm32"))]`), it does not evaluate arbitrary multi-crate boolean expressions. Applications should scope `std_instant` tests to the specific crates that compile into their web distribution. +- **Semantic type resolution**: The scanners follow `use` renames within one file only. They do not resolve paths through other modules or re-exports, a rename of `std` itself, or expand macros. +- **Complex target predicates**: `std_instant` evaluates `cfg` predicates (`all`, `any`, `not`, `unix`, `windows` and the `target_*` keys) for `wasm32-unknown-unknown`, on outer attributes for the item that follows and on inner attributes (`#![cfg(...)]`) for the rest of the module. A predicate that depends on a feature or on `test` is not known from the source, so its item is checked. Applications should scope `std_instant` tests to the specific crates that compile into their web distribution. - **Driver and host OS behavior**: Syntactic checks do not verify WebGPU driver compatibility or host window manager event dispatch. Source guards serve as fast, zero-dependency regression gates in application test suites, complementing platform integration tests and CI workflows. @@ -77,3 +77,16 @@ fn no_std_instant_in_code_the_web_build_runs() { ); } ``` + +## Origin + +| Module | Source | Path | Commit | +|---|---|---|---| +| `guards` | storytold/craft-libs#163 (zachshallbetter), with the rules of PhotoCraft's shader float test and FilmCraft's web clock test | `crates/testkit/src/guards.rs` | `e92825e427` | + +## Migration + +| Consumer | Guard | Replaces | State | +|---|---|---|---| +| PhotoCraft | `wgsl_float_literals` | `crates/gpu/src/tests.rs` scanner | Not started | +| FilmCraft | `std_instant` | `crates/engine/src/wasm_clock_tests.rs` search | Not started | diff --git a/crates/testkit/src/guards.rs b/crates/testkit/src/guards.rs index 2f8c50d234..a8a14401ef 100644 --- a/crates/testkit/src/guards.rs +++ b/crates/testkit/src/guards.rs @@ -1,5 +1,6 @@ //! Platform regression guards checking source code for known defects and lifecycle hazards. +use std::collections::BTreeSet; use std::fmt; #[cfg(not(target_arch = "wasm32"))] use std::path::Path; @@ -108,132 +109,529 @@ impl AsFileSource for &(&str, String) { } } -/// Replace code comments and string literals with whitespace while preserving newlines and line counts. +/// The deepest `use` group nesting and `cfg` predicate nesting the guards follow. Deeper input is +/// read as far as this depth, so hostile nesting cannot exhaust the stack. +const MAX_NESTING: usize = 64; + +/// The kind of a Rust token. Comments are dropped; string, character and number literals keep no text +/// except string contents, which `cfg` predicates compare. +#[derive(Debug, Clone, PartialEq, Eq)] +enum Kind { + Ident(String), + Punct(char), + Str(String), + Other, +} + +#[derive(Debug, Clone)] +struct Token { + kind: Kind, + line: usize, +} + +impl Token { + fn is_ident(&self, name: &str) -> bool { + matches!(&self.kind, Kind::Ident(s) if s == name) + } + + fn is_punct(&self, c: char) -> bool { + self.kind == Kind::Punct(c) + } +} + +fn is_ident_start(c: char) -> bool { + c == '_' || c.is_alphabetic() +} + +fn is_ident_continue(c: char) -> bool { + c == '_' || c.is_alphanumeric() +} + +/// Split Rust source into tokens with 1-based line numbers. /// -/// Handles single-line comments (`//`), block comments (`/* ... */`, including nested comments), -/// normal string literals (`"..."`), and raw string literals (`r#"..."#`). -fn mask_comments_and_strings(code: &str) -> String { - let mut out = String::with_capacity(code.len()); +/// Line comments, nested block comments, string literals (normal, byte, C and raw strings with any +/// number of `#`), character and byte literals, lifetimes and raw identifiers are recognized, so a quote +/// or comment marker inside one of them does not hide the code after it. Unterminated literals and +/// comments run to the end of the input. +fn lex_rust(code: &str) -> Vec { let chars: Vec = code.chars().collect(); let len = chars.len(); + let at = |i: usize| chars.get(i).copied(); + let mut tokens = Vec::new(); let mut i = 0; - let mut in_line_comment = false; - let mut block_comment_depth: usize = 0; - let mut in_normal_string = false; - let mut raw_string_hashes: Option = None; - let mut escape = false; + let mut line = 1usize; while i < len { let c = chars[i]; - if in_line_comment { - if c == '\n' { - in_line_comment = false; - out.push('\n'); - } else { - out.push(' '); - } + if c == '\n' { + line += 1; i += 1; - } else if block_comment_depth > 0 { - if c == '*' && i + 1 < len && chars[i + 1] == '/' { - block_comment_depth = block_comment_depth.saturating_sub(1); - out.push(' '); - out.push(' '); - i += 2; - } else if c == '/' && i + 1 < len && chars[i + 1] == '*' { - block_comment_depth = block_comment_depth.saturating_add(1); - out.push(' '); - out.push(' '); - i += 2; - } else if c == '\n' { - out.push('\n'); - i += 1; - } else { - out.push(' '); + } else if c.is_whitespace() { + i += 1; + } else if c == '/' && at(i + 1) == Some('/') { + while i < len && chars[i] != '\n' { i += 1; } - } else if let Some(hashes) = raw_string_hashes { - if c == '"' { - let mut match_hashes = true; - if i + hashes < len { - for h in 0..hashes { - if chars[i + 1 + h] != '#' { - match_hashes = false; - break; - } - } + } else if c == '/' && at(i + 1) == Some('*') { + let mut depth = 1usize; + i += 2; + while i < len && depth > 0 { + if chars[i] == '/' && at(i + 1) == Some('*') { + depth += 1; + i += 2; + } else if chars[i] == '*' && at(i + 1) == Some('/') { + depth -= 1; + i += 2; } else { - match_hashes = false; - } - if match_hashes { - raw_string_hashes = None; - for _ in 0..=hashes { - out.push(' '); + if chars[i] == '\n' { + line += 1; } - i += 1 + hashes; + i += 1; + } + } + } else if is_ident_start(c) { + let start = i; + while i < len && is_ident_continue(chars[i]) { + i += 1; + } + let word: String = chars[start..i].iter().collect(); + let token_line = line; + if matches!(word.as_str(), "r" | "br" | "cr") && matches!(at(i), Some('"' | '#')) { + let mut j = i; + while j < len && chars[j] == '#' { + j += 1; + } + let hashes = j - i; + if at(j) == Some('"') { + let (end, text) = scan_raw_string(&chars, j + 1, hashes, &mut line); + tokens.push(Token { kind: Kind::Str(text), line: token_line }); + i = end; + continue; + } + if word == "r" && hashes == 1 && at(j).is_some_and(is_ident_start) { + let name_start = j; + while j < len && is_ident_continue(chars[j]) { + j += 1; + } + tokens.push(Token { kind: Kind::Ident(chars[name_start..j].iter().collect()), line: token_line }); + i = j; continue; } } - if c == '\n' { - out.push('\n'); - } else { - out.push(' '); + if matches!(word.as_str(), "b" | "c") && at(i) == Some('"') { + let (end, text) = scan_string(&chars, i + 1, &mut line); + tokens.push(Token { kind: Kind::Str(text), line: token_line }); + i = end; + continue; } - i += 1; - } else if in_normal_string { - if escape { - escape = false; - out.push(' '); - } else if c == '\\' { - escape = true; - out.push(' '); - } else if c == '"' { - in_normal_string = false; - out.push(' '); - } else if c == '\n' { - out.push('\n'); - } else { - out.push(' '); + if word == "b" + && at(i) == Some('\'') + && let Some(end) = char_literal_end(&chars, i) + { + tokens.push(Token { kind: Kind::Other, line: token_line }); + i = end; + continue; } - i += 1; - } else { - if c == '/' && i + 1 < len && chars[i + 1] == '/' { - in_line_comment = true; - out.push(' '); - out.push(' '); - i += 2; - } else if c == '/' && i + 1 < len && chars[i + 1] == '*' { - block_comment_depth = 1; - out.push(' '); - out.push(' '); - i += 2; - } else if c == '"' { - in_normal_string = true; - out.push(' '); + tokens.push(Token { kind: Kind::Ident(word), line: token_line }); + } else if c.is_ascii_digit() { + while i < len && (is_ident_continue(chars[i]) || (chars[i] == '.' && at(i + 1).is_some_and(|d| d.is_ascii_digit()))) { i += 1; - } else if c == 'r' && i + 1 < len && (chars[i + 1] == '"' || chars[i + 1] == '#') { - let mut j = i + 1; - let mut hashes = 0; - while j < len && chars[j] == '#' { - hashes += 1; - j += 1; - } - if j < len && chars[j] == '"' { - raw_string_hashes = Some(hashes); - for _ in i..=j { - out.push(' '); - } - i = j + 1; - } else { - out.push(c); + } + tokens.push(Token { kind: Kind::Other, line }); + } else if c == '"' { + let token_line = line; + let (end, text) = scan_string(&chars, i + 1, &mut line); + tokens.push(Token { kind: Kind::Str(text), line: token_line }); + i = end; + } else if c == '\'' { + if let Some(end) = char_literal_end(&chars, i) { + i = end; + } else { + // A lifetime or a loop label. + i += 1; + while i < len && is_ident_continue(chars[i]) { i += 1; } - } else { - out.push(c); - i += 1; } + tokens.push(Token { kind: Kind::Other, line }); + } else { + tokens.push(Token { kind: Kind::Punct(c), line }); + i += 1; } } - out + tokens +} + +/// Read a normal string body starting after its opening quote. Returns the index after the closing +/// quote and the body as written, escapes included. +fn scan_string(chars: &[char], mut i: usize, line: &mut usize) -> (usize, String) { + let start = i; + while i < chars.len() { + match chars[i] { + '\\' => { + if chars.get(i + 1) == Some(&'\n') { + *line += 1; + } + i += 2; + } + '"' => return (i + 1, chars[start..i].iter().collect()), + '\n' => { + *line += 1; + i += 1; + } + _ => i += 1, + } + } + (chars.len(), chars[start.min(chars.len())..].iter().collect()) +} + +/// Read a raw string body starting after its opening quote; it ends at a quote followed by `hashes` `#`. +fn scan_raw_string(chars: &[char], mut i: usize, hashes: usize, line: &mut usize) -> (usize, String) { + let start = i; + while i < chars.len() { + if chars[i] == '"' && (1..=hashes).all(|h| chars.get(i + h) == Some(&'#')) { + return (i + 1 + hashes, chars[start..i].iter().collect()); + } + if chars[i] == '\n' { + *line += 1; + } + i += 1; + } + (chars.len(), chars[start.min(chars.len())..].iter().collect()) +} + +/// The index after a character or byte literal whose opening quote is at `quote`, or `None` when the +/// quote starts a lifetime or a label. +fn char_literal_end(chars: &[char], quote: usize) -> Option { + match chars.get(quote + 1) { + Some('\\') => { + // An escape: `\n`, `\'`, `\x7f`, `\u{10FFFF}`. The longest is twelve characters. + let mut j = quote + 3; + while j < chars.len() && j <= quote + 12 && chars[j] != '\'' && chars[j] != '\n' { + j += 1; + } + (chars.get(j) == Some(&'\'')).then_some(j + 1) + } + Some('\n') | None => None, + Some(_) => (chars.get(quote + 2) == Some(&'\'')).then_some(quote + 3), + } +} + +/// Rust keywords that can come right before a path that starts with `::`, as in `return ::std::time`. +/// `crate`, `self`, `super` and `Self` are path segments and are not listed. +const KEYWORDS: &[&str] = &[ + "as", "async", "await", "box", "break", "const", "continue", "dyn", "else", "enum", "extern", "fn", "for", "if", "impl", "in", "let", "loop", + "match", "mod", "move", "mut", "pub", "ref", "return", "static", "struct", "trait", "type", "unsafe", "use", "where", "while", "yield", +]; + +/// Whether `toks[i]` follows `::` that itself follows a path segment, as `time` does in `a::time`. +fn continues_a_path(toks: &[Token], i: usize) -> bool { + i >= 3 + && toks[i - 1].is_punct(':') + && toks[i - 2].is_punct(':') + && match &toks[i - 3].kind { + Kind::Ident(s) => !KEYWORDS.contains(&s.as_str()), + Kind::Punct('>') => true, + _ => false, + } +} + +/// Whether `toks[i..]` starts with `::` followed by the identifier `name`. +fn then_path(toks: &[Token], i: usize, name: impl Fn(&str) -> bool) -> bool { + toks.get(i).is_some_and(|t| t.is_punct(':')) + && toks.get(i + 1).is_some_and(|t| t.is_punct(':')) + && toks.get(i + 2).is_some_and(|t| matches!(&t.kind, Kind::Ident(s) if name(s))) +} + +/// One name a `use` declaration brings into scope. +#[derive(Debug)] +struct UseLeaf { + /// The full path, `self` removed and without a leading `::`. + path: Vec, + /// The name it is bound to; `None` for a glob import. + name: Option, + line: usize, + /// Index of the `use` keyword. + start: usize, +} + +/// Every name the `use` declarations of a file bring into scope. +fn use_leaves(toks: &[Token]) -> Vec { + let mut leaves = Vec::new(); + let mut i = 0; + while i < toks.len() { + if toks[i].is_ident("use") && !continues_a_path(toks, i) { + let start = i; + let end = (i + 1..toks.len()).find(|&j| toks[j].is_punct(';')).unwrap_or(toks.len()); + let mut pos = i + 1; + let mut prefix = Vec::new(); + parse_use_tree(&toks[..end], &mut pos, &mut prefix, start, &mut leaves, 0); + i = end; + } else { + i += 1; + } + } + leaves +} + +fn parse_use_tree(toks: &[Token], pos: &mut usize, prefix: &mut Vec, start: usize, out: &mut Vec, depth: usize) { + let base = prefix.len(); + if toks.get(*pos).is_some_and(|t| t.is_punct(':')) && toks.get(*pos + 1).is_some_and(|t| t.is_punct(':')) { + *pos += 2; + } + while let Some(tok) = toks.get(*pos) { + match &tok.kind { + Kind::Ident(name) => { + *pos += 1; + if toks.get(*pos).is_some_and(|t| t.is_punct(':')) && toks.get(*pos + 1).is_some_and(|t| t.is_punct(':')) { + prefix.push(name.clone()); + *pos += 2; + continue; + } + let mut path = prefix.clone(); + if name != "self" { + path.push(name.clone()); + } + let mut bound = path.last().cloned(); + if toks.get(*pos).is_some_and(|t| t.is_ident("as")) + && let Some(Kind::Ident(alias)) = toks.get(*pos + 1).map(|t| &t.kind) + { + bound = Some(alias.clone()); + *pos += 2; + } + if let Some(bound) = bound.filter(|b| b != "_") { + out.push(UseLeaf { path, name: Some(bound), line: tok.line, start }); + } + break; + } + Kind::Punct('*') => { + out.push(UseLeaf { path: prefix.clone(), name: None, line: tok.line, start }); + *pos += 1; + break; + } + Kind::Punct('{') => { + *pos += 1; + while let Some(t) = toks.get(*pos) { + if t.is_punct('}') { + *pos += 1; + break; + } + let before = *pos; + if !t.is_punct(',') && depth < MAX_NESTING { + parse_use_tree(toks, pos, prefix, start, out, depth + 1); + } + if *pos == before { + *pos += 1; + } + } + break; + } + _ => break, + } + } + prefix.truncate(base); +} + +/// A value of a `cfg` predicate on `wasm32-unknown-unknown`, where the value of a feature or of +/// `test` is not known from the source. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Tri { + True, + False, + Unknown, +} + +impl Tri { + fn from_bool(b: bool) -> Self { + if b { Self::True } else { Self::False } + } + + fn not(self) -> Self { + match self { + Self::True => Self::False, + Self::False => Self::True, + Self::Unknown => Self::Unknown, + } + } +} + +/// Evaluate the `cfg` predicate at `toks[*pos]` for `wasm32-unknown-unknown`. +fn eval_cfg(toks: &[Token], pos: &mut usize, depth: usize) -> Tri { + let Some(Kind::Ident(name)) = toks.get(*pos).map(|t| &t.kind) else { + return Tri::Unknown; + }; + *pos += 1; + if toks.get(*pos).is_some_and(|t| t.is_punct('=')) { + let value = match toks.get(*pos + 1).map(|t| &t.kind) { + Some(Kind::Str(v)) => v.clone(), + _ => return Tri::Unknown, + }; + *pos += 2; + let expected = match name.as_str() { + "target_arch" => "wasm32", + "target_os" | "target_vendor" => "unknown", + "target_family" => "wasm", + "target_env" => "", + "target_pointer_width" => "32", + "target_endian" => "little", + _ => return Tri::Unknown, + }; + return Tri::from_bool(value == expected); + } + if toks.get(*pos).is_some_and(|t| t.is_punct('(')) { + *pos += 1; + let mut values = Vec::new(); + while let Some(t) = toks.get(*pos) { + if t.is_punct(')') { + *pos += 1; + break; + } + if t.is_punct(',') || depth >= MAX_NESTING { + *pos += 1; + continue; + } + let before = *pos; + values.push(eval_cfg(toks, pos, depth + 1)); + if *pos == before { + *pos += 1; + } + } + return match name.as_str() { + "not" => values.first().map_or(Tri::Unknown, |v| v.not()), + "all" if values.contains(&Tri::False) => Tri::False, + "all" if values.contains(&Tri::Unknown) => Tri::Unknown, + "all" => Tri::True, + "any" if values.contains(&Tri::True) => Tri::True, + "any" if values.contains(&Tri::Unknown) => Tri::Unknown, + "any" => Tri::False, + _ => Tri::Unknown, + }; + } + match name.as_str() { + "unix" | "windows" => Tri::False, + _ => Tri::Unknown, + } +} + +/// The index of the token that closes the bracket opened at `open`, or `toks.len()`. +fn matching_close(toks: &[Token], open: usize) -> usize { + let mut depth = 0usize; + for (j, t) in toks.iter().enumerate().skip(open) { + match t.kind { + Kind::Punct('(' | '[' | '{') => depth += 1, + Kind::Punct(')' | ']' | '}') => { + depth = depth.saturating_sub(1); + if depth == 0 { + return j; + } + } + _ => {} + } + } + toks.len() +} + +/// Keywords whose item or expression ends with its closing brace rather than with `;`. +const BLOCK_KEYWORDS: &[&str] = + &["fn", "mod", "impl", "trait", "struct", "enum", "union", "extern", "macro_rules", "if", "match", "loop", "while", "for", "unsafe"]; + +/// The index after the item, statement, field or match arm that starts at `start`, or with `inner`, the +/// index of the bracket that closes the enclosing scope. +/// +/// It ends after a `;` or a `,` outside brackets, after the closing brace of a block item (one that +/// starts with a keyword in [`BLOCK_KEYWORDS`] or is a macro call with braces) or of a match arm's +/// block, or before a closing bracket of the enclosing scope. 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. +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 j = start; + while j < toks.len() { + let at_top = depth == 0 && !inner; + match &toks[j].kind { + Kind::Ident(k) if at_top && BLOCK_KEYWORDS.contains(&k.as_str()) => block_item = true, + Kind::Punct('!') if at_top && 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('>')) => arm = true, + Kind::Punct('(' | '[' | '{') => depth += 1, + Kind::Punct(c @ (')' | ']' | '}')) => { + if depth == 0 { + return j; + } + depth -= 1; + if depth == 0 && *c == '}' && (block_item || arm) && !inner { + if toks.get(j + 1).is_some_and(|t| t.is_ident("else")) { + j += 1; + continue; + } + let comma = toks.get(j + 1).is_some_and(|t| t.is_punct(',')); + return if arm && comma { j + 2 } else { j + 1 }; + } + } + Kind::Punct(';') if at_top => return j + 1, + Kind::Punct(',') if at_top && (arm || !block_item) => return j + 1, + _ => {} + } + j += 1; + } + toks.len() +} + +/// Mark the tokens of every item whose `cfg` attribute is false on `wasm32-unknown-unknown`. +/// +/// An outer attribute (`#[cfg(...)]`) covers the item after it; an inner attribute (`#![cfg(...)]`) +/// covers the rest of the module or block it is in. +fn native_only(toks: &[Token]) -> Vec { + let mut skip = vec![false; toks.len()]; + let mut i = 0; + while i < toks.len() { + if !toks[i].is_punct('#') { + i += 1; + continue; + } + let inner = toks.get(i + 1).is_some_and(|t| t.is_punct('!')); + let open = if inner { i + 2 } else { i + 1 }; + if !toks.get(open).is_some_and(|t| t.is_punct('[')) { + i += 1; + continue; + } + let close = matching_close(toks, open); + if close >= toks.len() { + // An unclosed attribute: no later bracket closes it, so nothing after it is an item. + break; + } + let excluded = toks.get(open + 1).is_some_and(|t| t.is_ident("cfg")) && toks.get(open + 2).is_some_and(|t| t.is_punct('(')) && { + let mut pos = open + 3; + eval_cfg(&toks[..close], &mut pos, 0) == Tri::False + }; + if !excluded { + i = close + 1; + continue; + } + // Further outer attributes on the same item. + let mut item = close + 1; + while !inner && item < toks.len() && toks[item].is_punct('#') && toks.get(item + 1).is_some_and(|t| t.is_punct('[')) { + item = matching_close(toks, item + 1).saturating_add(1); + } + let end = item_end(toks, item.min(toks.len()), inner); + for s in skip.iter_mut().take(end).skip(i) { + *s = true; + } + i = end.max(i + 1); + } + skip +} + +/// Add one finding for each line in `lines`, in line order, with the trimmed text of that line. +fn report(findings: &mut Vec, path: &str, content: &str, lines: &BTreeSet) { + if lines.is_empty() { + return; + } + let text: Vec<&str> = content.lines().collect(); + for &line in lines { + let line_text = text.get(line.saturating_sub(1)).map_or("", |s| s.trim()); + findings.push(Finding::new(path, line, line_text)); + } } /// Guard: detects direct calls to `muda`'s predefined Quit menu item. @@ -241,6 +639,12 @@ fn mask_comments_and_strings(code: &str) -> String { /// Using `PredefinedMenuItem::quit` connects the macOS menu directly to `NSApplication terminate:`, /// which bypasses dirty document checks, unsaved changes save prompts, and lifecycle cleanup. /// Applications should route Quit through custom menu items or interceptors connected to `craft-quit`. +/// +/// The guard reads Rust tokens, so comments, strings and character literals are ignored, and whitespace +/// or line breaks around `::` do not hide a call. 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. pub fn predefined_quit(files: I) -> Vec where I: IntoIterator, @@ -250,19 +654,27 @@ where for file in files { let path = file.path(); let content = file.content(); - let masked = mask_comments_and_strings(content); - - for (orig_line, (idx, masked_line)) in content.lines().zip(masked.lines().enumerate()) { - let normalized = masked_line.replace(' ', ""); - if normalized.contains("PredefinedMenuItem::quit") || normalized.contains("PredefinedMenuItem::Quit") { - findings.push(Finding::new(path, idx + 1, orig_line.trim())); + let toks = lex_rust(content); + let aliases: BTreeSet = use_leaves(&toks) + .into_iter() + .filter(|leaf| leaf.path == ["muda", "PredefinedMenuItem"]) + .filter_map(|leaf| leaf.name) + .filter(|name| name != "PredefinedMenuItem") + .collect(); + 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)); + if named && then_path(&toks, i + 1, |s| s == "quit" || s == "Quit") { + lines.insert(tok.line); } } + report(&mut findings, path, content, &lines); } findings } -/// Guard: detects uses of `std::time::Instant` outside comments in code paths running on the web. +/// Guard: detects uses of `std::time::Instant` in code paths running on the web. /// /// On `wasm32-unknown-unknown`, `std::time::Instant::now()` panics with "time not implemented /// on this platform". Crates running in the browser should use `web_time::Instant`, which maps to @@ -271,11 +683,19 @@ where /// ### Syntactic Scope and Limitations /// /// * **Targeted files**: Callers should pass files from crates that compile into the application's web build. -/// * **Allowed patterns**: Comments, string literals, lines containing `web_time`, and items decorated with -/// explicit non-wasm target conditions (e.g. `#[cfg(not(target_arch = "wasm32"))]` or `#[cfg(target_os = ...)]`) -/// are skipped. -/// * **Limitations**: This is a lexical source guard. It does not perform semantic type resolution, macro -/// expansion, or track arbitrary module aliases (e.g. `use std::time as t; t::Instant`). +/// * **What is reported**: the paths `std::time::Instant` and `::std::time::Instant`; `::Instant` where a +/// `use` outside a native-only item binds `m` to `std::time` (`use std::time;`, `use std::time as t;`, +/// `use std::time::{self as t}`); +/// and every `use` that imports `std::time::Instant` or `std::time::*`, under any name. Each finding names +/// the line where the path starts, once per line, in line order. +/// * **What is skipped**: comments, string and character literals, other crates' `Instant` (`web_time::Instant`, +/// a `time` module that is not `std::time`), and items whose `cfg` attribute is false on `wasm32-unknown-unknown` +/// (for example `#[cfg(not(target_arch = "wasm32"))]`, `#[cfg(all(unix, ...))]`, `#[cfg(target_os = "macos")]`, +/// or `#![cfg(...)]` for the rest of a module). A predicate that depends on a feature or on `test` is not +/// known from the source, so the item is checked. +/// * **Limitations**: This is a lexical source guard. It does not expand macros, resolve paths through other +/// modules or re-exports, rename `std` itself (`use std as s;`), or follow aliases in a different scope than +/// the file. pub fn std_instant(files: I) -> Vec where I: IntoIterator, @@ -285,72 +705,187 @@ where for file in files { let path = file.path(); let content = file.content(); - let masked = mask_comments_and_strings(content); + let toks = lex_rust(content); + let skip = native_only(&toks); + let leaves = use_leaves(&toks); + let modules: BTreeSet = leaves + .iter() + .filter(|leaf| leaf.path == ["std", "time"] && !skip.get(leaf.start).copied().unwrap_or(false)) + .filter_map(|leaf| leaf.name.clone()) + .collect(); + let is_std_time = |path: &[String]| path == ["std", "time"] || (path.len() == 1 && modules.contains(&path[0])); - let mut in_cfg_non_wasm = false; - let mut cfg_brace_depth: usize = 0; - - for (orig_line, (idx, masked_line)) in content.lines().zip(masked.lines().enumerate()) { - let is_comment_only = masked_line.trim().is_empty(); - let line_has_cfg_non_wasm = !is_comment_only - && (orig_line.contains("cfg(not(target_arch = \"wasm32\"))") - || orig_line.contains("cfg(target_arch = \"x86_64\")") - || orig_line.contains("cfg(target_arch = \"aarch64\")") - || orig_line.contains("cfg(target_os =")); - - if line_has_cfg_non_wasm { - in_cfg_non_wasm = true; + let mut lines = BTreeSet::new(); + for leaf in &leaves { + if skip.get(leaf.start).copied().unwrap_or(false) { + continue; } - - let names_std_instant = - masked_line.contains("time::Instant") || (masked_line.contains("use std::time::") && masked_line.contains("Instant")); - - if names_std_instant && !masked_line.contains("web_time") && !in_cfg_non_wasm { - findings.push(Finding::new(path, idx + 1, orig_line.trim())); - } - - if in_cfg_non_wasm && !is_comment_only { - let opens = masked_line.chars().filter(|&c| c == '{').count(); - let closes = masked_line.chars().filter(|&c| c == '}').count(); - if cfg_brace_depth == 0 { - if opens > 0 { - cfg_brace_depth = cfg_brace_depth.saturating_add(opens).saturating_sub(closes); - if cfg_brace_depth == 0 { - in_cfg_non_wasm = false; - } - } else if masked_line.contains(';') { - in_cfg_non_wasm = false; - } - } else { - cfg_brace_depth = cfg_brace_depth.saturating_add(opens).saturating_sub(closes); - if cfg_brace_depth == 0 { - in_cfg_non_wasm = false; - } - } + let imports_instant = if leaf.name.is_none() { + is_std_time(&leaf.path) + } else { + leaf.path.split_last().is_some_and(|(last, parent)| last == "Instant" && is_std_time(parent)) + }; + if imports_instant { + lines.insert(leaf.line); } } + for (i, tok) in toks.iter().enumerate() { + if skip[i] || continues_a_path(&toks, i) { + continue; + } + let Kind::Ident(name) = &tok.kind else { continue }; + let hit = if name == "std" { + then_path(&toks, i + 1, |s| s == "time") && then_path(&toks, i + 4, |s| s == "Instant") + } else { + modules.contains(name) && then_path(&toks, i + 1, |s| s == "Instant") + }; + if hit { + lines.insert(tok.line); + } + } + report(&mut findings, path, content, &lines); } findings } -/// Guard: scans a single WGSL shader string and detects decimal float literals outside `f32`'s finite range. +/// Replace WGSL comments (`//` and nested `/* ... */`) with spaces, keeping line breaks. +fn mask_wgsl_comments(code: &str) -> String { + let chars: Vec = code.chars().collect(); + let len = chars.len(); + let mut out = String::with_capacity(code.len()); + let mut i = 0; + let mut depth = 0usize; + let mut in_line = false; + while i < len { + let c = chars[i]; + let next = chars.get(i + 1).copied(); + if c == '\n' { + in_line = false; + out.push('\n'); + i += 1; + } else if in_line { + out.push(' '); + i += 1; + } else if c == '/' && next == Some('*') { + depth += 1; + out.push_str(" "); + i += 2; + } else if depth > 0 && c == '*' && next == Some('/') { + depth -= 1; + out.push_str(" "); + i += 2; + } else if depth > 0 { + out.push(' '); + i += 1; + } else if c == '/' && next == Some('/') { + in_line = true; + out.push_str(" "); + i += 2; + } else { + out.push(c); + i += 1; + } + } + out +} + +/// The largest finite value of the type a WGSL float literal with this suffix has. +fn float_limit(suffix: Option) -> f64 { + if suffix == Some(b'h') { 65504.0 } else { f64::from(f32::MAX) } +} + +/// Read a WGSL hexadecimal literal starting at the `0` of `0x`. Returns the index after it, the length of +/// its text without a suffix, and whether it is a float above the range of its type. +fn scan_wgsl_hex(code: &[u8], start: usize) -> (usize, usize, bool) { + // Significant hex digits kept; 15 hold 60 bits, more than an f64 mantissa. + const KEPT: usize = 15; + let mut i = start + 2; + let mut mantissa = 0f64; + let mut kept = 0usize; + let mut exponent: i64 = 0; + let mut digits = 0usize; + let mut digit = |d: u8, fraction: bool, exponent: &mut i64| { + let value = (d as char).to_digit(16).unwrap_or(0); + if mantissa == 0.0 && value == 0 { + if fraction { + *exponent -= 4; + } + } else if kept < KEPT { + mantissa = mantissa * 16.0 + f64::from(value); + kept += 1; + if fraction { + *exponent -= 4; + } + } else if !fraction { + *exponent += 4; + } + }; + while i < code.len() && code[i].is_ascii_hexdigit() { + digit(code[i], false, &mut exponent); + digits += 1; + i += 1; + } + let mut is_float = false; + if code.get(i) == Some(&b'.') { + is_float = true; + i += 1; + while i < code.len() && code[i].is_ascii_hexdigit() { + digit(code[i], true, &mut exponent); + digits += 1; + i += 1; + } + } + let mut has_exponent = false; + if matches!(code.get(i), Some(b'p' | b'P')) { + let mut j = i + 1; + let negative = code.get(j) == Some(&b'-'); + if matches!(code.get(j), Some(b'+' | b'-')) { + j += 1; + } + if code.get(j).is_some_and(u8::is_ascii_digit) { + let mut e: i64 = 0; + while j < code.len() && code[j].is_ascii_digit() { + e = (e * 10 + i64::from(code[j] - b'0')).min(1_000_000); + j += 1; + } + exponent += if negative { -e } else { e }; + has_exponent = true; + is_float = true; + i = j; + } + } + let text_len = i - start; + let suffix = if has_exponent && matches!(code.get(i), Some(b'f' | b'h')) { code.get(i).copied() } else { None }; + let end = if suffix.is_some() || (!is_float && matches!(code.get(i), Some(b'i' | b'u'))) { i + 1 } else { i }; + if !is_float || digits == 0 || mantissa == 0.0 { + return (end, text_len, false); + } + let scale = i32::try_from(exponent.clamp(-4000, 4000)).unwrap_or(0); + let value = mantissa * 2f64.powi(scale); + (end, text_len, !value.is_finite() || value > float_limit(suffix)) +} + +/// Guard: scans a single WGSL shader string and detects float literals outside their type's finite range. /// -/// Browser WebGPU compilers (such as Chrome's Tint) reject float literals exceeding `f32::MAX` -/// (e.g. `3.40282347e38`), triggering fatal pipeline build errors and fallback to CPU rendering. -/// Exact values equal to `f32::MAX` should be written as hex float literals (e.g. `0x1.fffffep+127f`). +/// WebGPU compilers in browsers reject a float literal above `f32::MAX` (e.g. `3.40282347e38`) with a +/// pipeline build error, which turns off GPU rendering. Exact values equal to `f32::MAX` can be written +/// as `3.4028234663852886e38` or as the hex float `0x1.fffffep+127f`. /// /// ### Policy and Limitations /// -/// * **Conservative mathematical bound**: The guard evaluates the parsed mathematical magnitude against -/// `f64::from(f32::MAX)`. Any decimal literal exceeding this threshold is flagged, even if native -/// compilers like `naga` would round it down to `f32::MAX`. -/// * **Hexadecimal floats**: Exact hex float literals (`0x...p...`) are skipped as they represent exact bit patterns. -/// * **Comments and strings**: Comments (`//` and `/* ... */`) and string contents are masked out prior to scanning. +/// * **Conservative mathematical bound**: The guard compares the literal's value, rounded to `f64`, +/// with `f64::from(f32::MAX)`, or with 65504 (the largest finite `f16`) for an `h` suffix. Any literal +/// above it is reported, even one that a compiler would round down to the maximum. +/// * **Which literals**: decimal floats (with a `.`, an exponent or an `f`/`h` suffix) and hexadecimal floats +/// (`0x` with a `.` or a `p` exponent). Integer literals (`123`, `123u`, `0xFFi`, `0x1f`) are not floats and +/// are not reported. A `-` in front is not part of the literal, so `-1e39` is reported as `1e39`. +/// * **Comments**: Comments (`//` and nested `/* ... */`) are masked out prior to scanning. pub fn wgsl_float_literals(wgsl: &str) -> Vec { wgsl_float_literals_in([("", wgsl)]) } -/// Guard: scans multiple WGSL shader files and detects decimal float literals outside `f32`'s finite range. +/// Guard: scans multiple WGSL shader files and detects float literals outside their type's finite range, +/// with the rules of [`wgsl_float_literals`]. pub fn wgsl_float_literals_in(files: I) -> Vec where I: IntoIterator, @@ -359,8 +894,7 @@ where let mut findings = Vec::new(); for file in files { let path = file.path(); - let content = file.content(); - let masked = mask_comments_and_strings(content); + let masked = mask_wgsl_comments(file.content()); for (n, line) in masked.lines().enumerate() { let code = line.as_bytes(); @@ -372,40 +906,61 @@ where i += 1; continue; } - // Skip hex float literals (e.g. 0x1.fffffep+127f, 0x1.0p0h) + let start = i; if code[i] == b'0' && matches!(code.get(i + 1), Some(b'x' | b'X')) { - i += 2; - while i < code.len() && (code[i].is_ascii_hexdigit() || matches!(code[i], b'.' | b'p' | b'P' | b'+' | b'-' | b'f' | b'h')) { - i += 1; + let (end, text_len, over) = scan_wgsl_hex(code, i); + if over { + findings.push(Finding::new(path, n + 1, String::from_utf8_lossy(&code[start..start + text_len]).into_owned())); } + i = end.max(i + 1); continue; } - let start = i; - while i < code.len() && (code[i].is_ascii_digit() || code[i] == b'.') { + let mut is_float = false; + while i < code.len() && code[i].is_ascii_digit() { i += 1; } - if i < code.len() && matches!(code[i], b'e' | b'E') { + if code.get(i) == Some(&b'.') { + is_float = true; + i += 1; + while i < code.len() && code[i].is_ascii_digit() { + i += 1; + } + } + if matches!(code.get(i), Some(b'e' | b'E')) { let mut j = i + 1; - if j < code.len() && matches!(code[j], b'+' | b'-') { + if matches!(code.get(j), Some(b'+' | b'-')) { j += 1; } - if j < code.len() && code[j].is_ascii_digit() { + if code.get(j).is_some_and(u8::is_ascii_digit) { + is_float = true; i = j; while i < code.len() && code[i].is_ascii_digit() { i += 1; } } } - let literal = String::from_utf8_lossy(&code[start..i]); - if i < code.len() && matches!(code[i], b'f' | b'h') { - i += 1; + let literal = String::from_utf8_lossy(&code[start..i]).into_owned(); + let suffix = match code.get(i) { + Some(&s @ (b'f' | b'h')) => { + is_float = true; + i += 1; + Some(s) + } + Some(b'i' | b'u') if !is_float => { + i += 1; + None + } + _ => None, + }; + if !is_float { + continue; } let is_overflow = match literal.parse::() { - Ok(v) => !v.is_finite() || v.abs() > f64::from(f32::MAX), + Ok(v) => !v.is_finite() || v.abs() > float_limit(suffix), Err(_) => true, }; if is_overflow { - findings.push(Finding::new(path, n + 1, literal.into_owned())); + findings.push(Finding::new(path, n + 1, literal)); } } } @@ -413,7 +968,42 @@ where findings } -/// Recursively collect all Rust source files under `dir`, excluding test files and test directories. +/// Size limits for [`rust_sources_with_limits`]. An input over a limit is an error. +#[cfg(not(target_arch = "wasm32"))] +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct SourceLimits { + /// The largest single file read, in bytes. Default 8 MiB. + pub max_file_bytes: u64, + /// The largest total of all files read, in bytes. Default 256 MiB. + pub max_total_bytes: u64, + /// The most files read. Default 50,000. + pub max_files: usize, +} + +#[cfg(not(target_arch = "wasm32"))] +impl Default for SourceLimits { + fn default() -> Self { + Self { max_file_bytes: 8 << 20, max_total_bytes: 256 << 20, max_files: 50_000 } + } +} + +/// The first line of a `CACHEDIR.TAG` file, which marks a folder of generated files +/// (). Cargo writes one in each target folder. +#[cfg(not(target_arch = "wasm32"))] +const CACHEDIR_SIGNATURE: &[u8] = b"Signature: 8a477f597d28d172789f06886806bc55"; + +#[cfg(not(target_arch = "wasm32"))] +fn is_cache_dir(dir: &Path) -> bool { + use std::io::Read; + let Ok(file) = std::fs::File::open(dir.join("CACHEDIR.TAG")) else { + return false; + }; + let mut head = Vec::with_capacity(CACHEDIR_SIGNATURE.len()); + file.take(CACHEDIR_SIGNATURE.len() as u64).read_to_end(&mut head).is_ok() && head == CACHEDIR_SIGNATURE +} + +/// Recursively collect all Rust source files under `dir`, excluding test files and test directories, +/// with the default [`SourceLimits`]. /// /// Excluded files: /// * `tests.rs` @@ -421,29 +1011,44 @@ where /// * `*_tests.rs` /// * `*_test.rs` /// * `test.rs` -/// * Any file within a directory component named `tests`, `benches`, `examples`, `.git`, or `target`. +/// * Any file below `dir` within a directory named `tests`, `benches`, `examples` or `target`, or whose +/// name starts with `.`, or that holds a `CACHEDIR.TAG` file (a build output folder with another name). +/// * Symbolic links (and, on Windows, junctions) to files or folders, which are not followed. /// /// Results are sorted lexicographically by file path for deterministic behavior across platforms. #[cfg(not(target_arch = "wasm32"))] pub fn rust_sources(dir: impl AsRef) -> std::io::Result> { + rust_sources_with_limits(dir, SourceLimits::default()) +} + +/// [`rust_sources`] with explicit size limits. A file over `max_file_bytes` returns an error of kind +/// [`std::io::ErrorKind::FileTooLarge`]; more than `max_files` files or `max_total_bytes` bytes in all +/// returns an error of kind [`std::io::ErrorKind::QuotaExceeded`]. +#[cfg(not(target_arch = "wasm32"))] +pub fn rust_sources_with_limits(dir: impl AsRef, limits: SourceLimits) -> std::io::Result> { + use std::io::{Error, ErrorKind, Read}; + let root = dir.as_ref(); let mut files = Vec::new(); + let mut total: u64 = 0; let mut dirs = vec![root.to_path_buf()]; while let Some(d) = dirs.pop() { - let entries = std::fs::read_dir(&d)?; - for entry in entries { + for entry in std::fs::read_dir(&d)? { let entry = entry?; let p = entry.path(); - let metadata = std::fs::metadata(&p)?; - if metadata.is_dir() { - let dirname = p.file_name().and_then(|n| n.to_str()).unwrap_or_default(); - if dirname.starts_with('.') || dirname == "target" || dirname == "tests" || dirname == "benches" || dirname == "examples" { + let kind = entry.file_type()?; + if kind.is_symlink() { + continue; + } + let name = entry.file_name(); + let name = name.to_string_lossy(); + if kind.is_dir() { + if name.starts_with('.') || name == "target" || name == "tests" || name == "benches" || name == "examples" || is_cache_dir(&p) { continue; } dirs.push(p); - } else if metadata.is_file() { - let name = p.file_name().and_then(|n| n.to_str()).unwrap_or_default(); + } else if kind.is_file() { if !name.ends_with(".rs") { continue; } @@ -451,10 +1056,29 @@ pub fn rust_sources(dir: impl AsRef) -> std::io::Result= limits.max_files { + return Err(Error::new( + ErrorKind::QuotaExceeded, + format!("more than {} Rust source files under {}", limits.max_files, root.display()), + )); + } + let over_file = || Error::new(ErrorKind::FileTooLarge, format!("{} is larger than {} bytes", p.display(), limits.max_file_bytes)); + if entry.metadata()?.len() > limits.max_file_bytes { + return Err(over_file()); + } + let mut content = String::new(); + std::fs::File::open(&p)?.take(limits.max_file_bytes.saturating_add(1)).read_to_string(&mut content)?; + let size = content.len() as u64; + if size > limits.max_file_bytes { + return Err(over_file()); + } + total = total.saturating_add(size); + if total > limits.max_total_bytes { + return Err(Error::new( + ErrorKind::QuotaExceeded, + format!("Rust sources under {} are larger than {} bytes in all", root.display(), limits.max_total_bytes), + )); } - let content = std::fs::read_to_string(&p)?; files.push((p.display().to_string(), content)); } } diff --git a/crates/testkit/src/lib.rs b/crates/testkit/src/lib.rs index b0e61fc8b5..b484c6ef69 100644 --- a/crates/testkit/src/lib.rs +++ b/crates/testkit/src/lib.rs @@ -8,11 +8,12 @@ //! //! * [`guards::predefined_quit`]: flags direct calls to `muda`'s predefined Quit item that bypass //! dirty document save prompts and window teardown on macOS. -//! * [`guards::wgsl_float_literals`]: flags decimal float literals exceeding `f32`'s finite range, -//! which break browser WebGPU compilers (Tint) and trigger CPU fallbacks. +//! * [`guards::wgsl_float_literals`]: flags WGSL float literals above the finite range of `f32` +//! (or of `f16` for an `h` suffix), which browser WebGPU compilers reject. //! * [`guards::std_instant`]: flags uses of `std::time::Instant` in code paths targeting the web, //! where `std::time::Instant::now()` panics on `wasm32`. -//! * [`guards::rust_sources`]: directory crawler collecting `.rs` sources while excluding tests. +//! * [`guards::rust_sources`]: directory crawler collecting `.rs` sources while excluding tests, with +//! size limits ([`guards::rust_sources_with_limits`]). It is not built for `wasm32`. //! //! ### Epistemic Scope: What Source Guards Establish vs What They Cannot //! @@ -26,7 +27,7 @@ pub mod guards; -pub use guards::{Finding, predefined_quit, std_instant, wgsl_float_literals, wgsl_float_literals_in}; +pub use guards::{AsFileSource, Finding, predefined_quit, std_instant, wgsl_float_literals, wgsl_float_literals_in}; #[cfg(not(target_arch = "wasm32"))] -pub use guards::rust_sources; +pub use guards::{SourceLimits, rust_sources, rust_sources_with_limits}; diff --git a/crates/testkit/tests/guards.rs b/crates/testkit/tests/guards.rs index ee6daae7d7..a2a419ca18 100644 --- a/crates/testkit/tests/guards.rs +++ b/crates/testkit/tests/guards.rs @@ -1,5 +1,54 @@ use craft_testkit::{Finding, predefined_quit, std_instant, wgsl_float_literals, wgsl_float_literals_in}; +/// A scratch folder under the system temporary folder that this test made and removes on drop, +/// also when the test panics. A folder that already exists is never emptied or reused. +#[cfg(not(target_arch = "wasm32"))] +struct ScratchDir(std::path::PathBuf); + +#[cfg(not(target_arch = "wasm32"))] +impl ScratchDir { + fn new(tag: &str) -> Self { + let base = std::env::temp_dir(); + for n in 0..1000u32 { + let path = base.join(format!("craft_testkit_{tag}_{}_{n}", std::process::id())); + match std::fs::create_dir(&path) { + Ok(()) => return Self(path), + Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => continue, + Err(e) => panic!("create scratch folder {}: {e}", path.display()), + } + } + panic!("no free scratch folder name for {tag}"); + } + + fn path(&self) -> &std::path::Path { + &self.0 + } + + fn write(&self, relative: &str, content: &str) { + let path = self.0.join(relative); + if let Some(parent) = path.parent() { + std::fs::create_dir_all(parent).expect("create parent folder"); + } + std::fs::write(path, content).expect("write file"); + } +} + +#[cfg(not(target_arch = "wasm32"))] +impl Drop for ScratchDir { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +#[cfg(not(target_arch = "wasm32"))] +fn file_names(sources: &[(String, String)]) -> Vec { + sources.iter().map(|(p, _)| std::path::Path::new(p).file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default()).collect() +} + +fn lines(findings: &[Finding]) -> Vec { + findings.iter().map(|f| f.line).collect() +} + #[test] fn test_finding_display() { let f1 = Finding::new("src/menu.rs", 42, "PredefinedMenuItem::quit()"); @@ -287,44 +336,332 @@ const OVER_NEG: f32 = -3.40282347e38; assert_eq!(findings[1].text, "3.40282347e38"); } +#[test] +fn character_literals_do_not_hide_the_code_after_them() { + let source = r#" +fn menu<'a>(label: &'a str) { + let quote = '"'; + let quit = PredefinedMenuItem::quit(None); + let apostrophe = '\''; + let t0 = std::time::Instant::now(); + let b = b'"'; + let later = PredefinedMenuItem::quit(Some(label)); +} +"#; + assert_eq!(lines(&predefined_quit([("src/menu.rs", source)])), vec![4, 8]); + assert_eq!(lines(&std_instant([("src/menu.rs", source)])), vec![6]); +} + +#[test] +fn strings_hold_comment_markers_without_hiding_code() { + let source = r##" +fn menu() { + let a = "/* not a comment"; + let quit = PredefinedMenuItem::quit(None); + let b = b"// not a comment either"; + let c = r#"*/ " still a raw string"#; + let t0 = std::time::Instant::now(); + let d = "PredefinedMenuItem::quit std::time::Instant"; +} +"##; + assert_eq!(lines(&predefined_quit([("src/menu.rs", source)])), vec![4]); + assert_eq!(lines(&std_instant([("src/menu.rs", source)])), vec![7]); +} + +#[test] +fn nested_block_comments_stay_masked() { + let source = "/* outer /* inner */ PredefinedMenuItem::quit(None); std::time::Instant::now(); */\nlet q = PredefinedMenuItem::quit(None);\n"; + assert_eq!(lines(&predefined_quit([("src/menu.rs", source)])), vec![2]); + assert!(std_instant([("src/menu.rs", source)]).is_empty()); +} + +#[test] +fn predefined_quit_sees_tabs_and_line_breaks_around_the_path_separator() { + let source = "fn menu() {\n let a = PredefinedMenuItem\t::\tquit(None);\n let b = muda::PredefinedMenuItem\n ::quit(None);\n}\n"; + let findings = predefined_quit([("src/menu.rs", source)]); + assert_eq!(lines(&findings), vec![2, 3]); + assert_eq!(findings[1].text, "let b = muda::PredefinedMenuItem"); +} + +#[test] +fn predefined_quit_matches_whole_names_only() { + let other_names = r#" +fn menu() { + let a = MyPredefinedMenuItem::quit(None); + let b = PredefinedMenuItem::quitter(); + let c = PredefinedMenuItem::quit_label(); +} +"#; + assert!(predefined_quit([("src/menu.rs", other_names)]).is_empty()); + + let aliased = r#" +use muda::{PredefinedMenuItem as Item, MenuItem}; +fn menu() { + let a = Item::quit(None); + let b = other::Item::quit(None); +} +"#; + assert_eq!(lines(&predefined_quit([("src/menu.rs", aliased)])), vec![4]); + + let other_crate = r#" +use other_menu::PredefinedMenuItem as Item; +fn menu() { + let a = Item::quit(None); +} +"#; + assert!(predefined_quit([("src/menu.rs", other_crate)]).is_empty()); +} + +#[test] +fn std_instant_ignores_an_alias_that_only_a_native_cfg_imports() { + let source = r#" +#[cfg(not(target_arch = "wasm32"))] +use std::time as clock; +#[cfg(target_arch = "wasm32")] +use web_time as clock; + +fn now() { + let t = clock::Instant::now(); +} +"#; + assert!(std_instant([("src/clock.rs", source)]).is_empty()); +} + +#[test] +fn std_instant_reads_cfg_from_code_not_from_strings_or_comments() { + let cfg_in_string = r##" +fn now() -> u64 { let _s = r#"cfg(target_os = "linux")"#; + let t = std::time::Instant::now(); + 0 +} +"##; + assert_eq!(lines(&std_instant([("src/a.rs", cfg_in_string)])), vec![3]); + + let cfg_in_comment = r#" +fn web() { // cfg(target_os = "linux") + let t = std::time::Instant::now(); +} +"#; + assert_eq!(lines(&std_instant([("src/b.rs", cfg_in_comment)])), vec![3]); +} + +#[test] +fn std_instant_skips_only_the_item_a_native_cfg_covers() { + let source = r#" +#[cfg(not(target_arch = "wasm32"))] +fn native() -> std::time::Instant { std::time::Instant::now() } +fn web() -> std::time::Instant { std::time::Instant::now() } + +#[cfg(all(unix, not(target_arch = "wasm32")))] +#[inline] +fn unix_only() { + let t = std::time::Instant::now(); +} + +#[cfg(feature = "native-clock")] +fn by_feature() { let t = std::time::Instant::now(); } + +#[cfg(any(target_arch = "wasm32", windows))] +fn also_web() { let t = std::time::Instant::now(); } + +#[cfg(target_os = "unknown")] +fn unknown_os() { let t = std::time::Instant::now(); } + +#[cfg(target_os = "macos")] +use std::time::Instant as MacInstant; +"#; + assert_eq!(lines(&std_instant([("src/clock.rs", source)])), vec![4, 13, 16, 19]); +} + +#[test] +fn std_instant_inner_cfg_covers_the_whole_file() { + let source = r#" +#![cfg(not(target_arch = "wasm32"))] +use std::time::Instant; + +fn now() -> Instant { + std::time::Instant::now() +} +"#; + assert!(std_instant([("src/native.rs", source)]).is_empty()); +} + +#[test] +fn std_instant_reports_a_std_use_on_a_line_that_also_names_web_time() { + let source = "fn pair() {\n let p = (web_time::Instant::now(), std::time::Instant::now());\n}\n"; + assert_eq!(lines(&std_instant([("src/pair.rs", source)])), vec![2]); +} + +#[test] +fn std_instant_needs_std_behind_a_bare_time_path() { + let source = r#" +use crate::time; + +fn tick() { + let t = time::Instant::new(); +} +"#; + assert!(std_instant([("src/tick.rs", source)]).is_empty()); +} + +#[test] +fn std_instant_follows_module_and_type_aliases() { + let source = r#" +use std::time as t; +use std::time::{self as clock, Duration}; +use std::{time::Instant as I, fmt}; +use web_time as wt; + +fn run() { + let a = t::Instant::now(); + let b = clock::Instant::now(); + let c = wt::Instant::now(); + let d = x::t::Instant::now(); +} +"#; + assert_eq!(lines(&std_instant([("src/run.rs", source)])), vec![4, 8, 9]); +} + +#[test] +fn wgsl_integer_literals_are_not_floats() { + let shader = r#" +const BIG_ABSTRACT = 400000000000000000000000000000000000000000; +const BIG_U = 1000000000000000000000000000000000000000u; +const BIG_I = 1000000000000000000000000000000000000000i; +const HEX_INT = 0xFFFFFFFFu; +const HEX_F_DIGIT = 0x1f; +const FLOAT_DOT: f32 = 340282356779733661637539395458142568448.0; +const FLOAT_SUFFIX: f32 = 400000000000000000000000000000000000000f; +const NEG_EXP: f32 = -4e38; +"#; + let findings = wgsl_float_literals(shader); + assert_eq!(lines(&findings), vec![7, 8, 9]); + assert_eq!(findings[0].text, "340282356779733661637539395458142568448.0"); + assert_eq!(findings[1].text, "400000000000000000000000000000000000000"); + assert_eq!(findings[2].text, "4e38"); +} + +#[test] +fn wgsl_hex_floats_outside_the_range_are_reported() { + let shader = r#" +const EXACT_MAX: f32 = 0x1.fffffep+127f; +const HUGE: f32 = 0x1p+500f; +const JUST_OVER: f32 = 0x1.000002p+128; +const UPPER: f32 = 0X1P128; +const TINY: f32 = 0x1p-500; +const ZERO: f32 = 0x0.0p99999; +const F16_MAX: f16 = 0x1.ffcp15h; +const F16_OVER: f16 = 0x1.0p16h; +"#; + let findings = wgsl_float_literals(shader); + assert_eq!(lines(&findings), vec![3, 4, 5, 9]); + assert_eq!(findings[0].text, "0x1p+500"); + assert_eq!(findings[3].text, "0x1.0p16"); +} + +#[test] +fn wgsl_block_comment_markers_inside_line_comments_do_not_open_a_comment() { + let shader = "// a /* inside a line comment\nconst BAD: f32 = 4e38;\n/* block // with a line marker */ const ALSO_BAD: f32 = 5e38;\n"; + let findings = wgsl_float_literals(shader); + assert_eq!(lines(&findings), vec![2, 3]); +} + +#[test] +fn wgsl_half_floats_use_the_f16_range() { + let shader = "const OK: f16 = 65504.0h;\nconst OVER: f16 = 70000.0h;\nconst F32_OK: f32 = 70000.0f;\n"; + let findings = wgsl_float_literals(shader); + assert_eq!(lines(&findings), vec![2]); + assert_eq!(findings[0].text, "70000.0"); +} + #[cfg(not(target_arch = "wasm32"))] #[test] fn test_rust_sources_filtering() { use craft_testkit::rust_sources; - use std::fs::{self, File}; - use std::io::Write; - let temp_dir = std::env::temp_dir().join(format!("craft_testkit_test_{}", std::process::id())); - let _ = fs::remove_dir_all(&temp_dir); - fs::create_dir_all(temp_dir.join("src").join("sub")).expect("create temp sub"); - fs::create_dir_all(temp_dir.join("tests")).expect("create temp tests"); - fs::create_dir_all(temp_dir.join("target")).expect("create temp target"); - fs::create_dir_all(temp_dir.join(".github")).expect("create temp dot-dir"); + let dir = ScratchDir::new("filtering"); + dir.write("src/lib.rs", "pub fn lib() {}"); + dir.write("src/sub/mod.rs", "pub fn sub() {}"); + dir.write("src/tests.rs", "// should exclude"); + dir.write("src/tests_foo.rs", "// should exclude"); + dir.write("src/foo_tests.rs", "// should exclude"); + dir.write("src/foo_test.rs", "// should exclude"); + dir.write("tests/integ.rs", "// should exclude"); + dir.write("target/gen.rs", "// should exclude"); + dir.write(".github/action.rs", "// should exclude dot-dir"); + dir.write("src/README.md", "# Not a rust source"); - let create_file = |path: std::path::PathBuf, content: &str| { - let mut f = File::create(path).expect("create file"); - f.write_all(content.as_bytes()).expect("write content"); - }; + let sources = rust_sources(dir.path()).expect("rust_sources"); + assert_eq!(file_names(&sources), vec!["lib.rs", "mod.rs"]); - create_file(temp_dir.join("src").join("lib.rs"), "pub fn lib() {}"); - create_file(temp_dir.join("src").join("sub").join("mod.rs"), "pub fn sub() {}"); - create_file(temp_dir.join("src").join("tests.rs"), "// should exclude"); - create_file(temp_dir.join("src").join("tests_foo.rs"), "// should exclude"); - create_file(temp_dir.join("src").join("foo_tests.rs"), "// should exclude"); - create_file(temp_dir.join("src").join("foo_test.rs"), "// should exclude"); - create_file(temp_dir.join("tests").join("integ.rs"), "// should exclude"); - create_file(temp_dir.join("target").join("gen.rs"), "// should exclude"); - create_file(temp_dir.join(".github").join("action.rs"), "// should exclude dot-dir"); - create_file(temp_dir.join("src").join("README.md"), "# Not a rust source"); - - let sources = rust_sources(&temp_dir).expect("rust_sources"); - let names: Vec = sources.iter().map(|(p, _)| std::path::Path::new(p).file_name().unwrap().to_string_lossy().into_owned()).collect(); - - assert_eq!(names, vec!["lib.rs", "mod.rs"]); - - // Test passing &[(&str, &str)] to guards + // Test passing &[(String, String)] to guards let findings = predefined_quit(&sources); assert!(findings.is_empty()); +} - let _ = fs::remove_dir_all(&temp_dir); +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn rust_sources_lists_a_root_inside_a_folder_named_tests() { + let dir = ScratchDir::new("root_in_tests"); + dir.write("tests/app/src/lib.rs", "pub fn lib() {}"); + let sources = craft_testkit::rust_sources(dir.path().join("tests").join("app")).expect("rust_sources"); + assert_eq!(file_names(&sources), vec!["lib.rs"]); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn rust_sources_skips_build_output_folders_marked_with_cachedir_tag() { + let dir = ScratchDir::new("cachedir"); + dir.write("src/lib.rs", "pub fn lib() {}"); + dir.write("out/CACHEDIR.TAG", "Signature: 8a477f597d28d172789f06886806bc55\n# build output\n"); + dir.write("out/debug/build/gen.rs", "pub fn generated() {}"); + dir.write("notes/CACHEDIR.TAG", "not a cache tag\n"); + dir.write("notes/kept.rs", "pub fn kept() {}"); + let sources = craft_testkit::rust_sources(dir.path()).expect("rust_sources"); + assert_eq!(file_names(&sources), vec!["kept.rs", "lib.rs"]); +} + +#[cfg(unix)] +#[test] +fn rust_sources_does_not_follow_a_symlink_out_of_the_root() { + let outside = ScratchDir::new("symlink_outside"); + outside.write("evil.rs", "pub fn evil() {}"); + let dir = ScratchDir::new("symlink_root"); + dir.write("src/lib.rs", "pub fn lib() {}"); + std::os::unix::fs::symlink(outside.path(), dir.path().join("src").join("linked")).expect("symlink folder"); + std::os::unix::fs::symlink(outside.path().join("evil.rs"), dir.path().join("src").join("evil.rs")).expect("symlink file"); + let sources = craft_testkit::rust_sources(dir.path()).expect("rust_sources"); + assert_eq!(file_names(&sources), vec!["lib.rs"]); +} + +#[cfg(unix)] +#[test] +fn rust_sources_does_not_loop_on_a_symlink_cycle() { + let dir = ScratchDir::new("symlink_cycle"); + dir.write("src/lib.rs", "pub fn lib() {}"); + std::os::unix::fs::symlink(dir.path().join("src"), dir.path().join("src").join("again")).expect("symlink cycle"); + let sources = craft_testkit::rust_sources(dir.path()).expect("rust_sources"); + assert_eq!(file_names(&sources), vec!["lib.rs"]); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn scratch_dirs_leave_existing_folders_alone_and_clean_up_on_panic() { + let taken = std::env::temp_dir().join(format!("craft_testkit_sentinel_{}_0", std::process::id())); + std::fs::create_dir(&taken).expect("create the folder the helper would pick first"); + std::fs::write(taken.join("sentinel"), "keep").expect("write sentinel"); + + let made = std::panic::catch_unwind(|| { + let dir = ScratchDir::new("sentinel"); + let path = dir.path().to_path_buf(); + assert!(path.exists()); + std::panic::panic_any(path); + }); + let payload = made.expect_err("the closure panics"); + let path = payload.downcast_ref::().expect("panic payload is the path").clone(); + + assert_ne!(path, taken); + assert!(!path.exists(), "the scratch folder is removed when the test panics"); + assert_eq!(std::fs::read_to_string(taken.join("sentinel")).expect("sentinel survives"), "keep"); + std::fs::remove_dir_all(&taken).expect("remove the pre-made folder"); } diff --git a/crates/testkit/tests/source_limits.rs b/crates/testkit/tests/source_limits.rs new file mode 100644 index 0000000000..a90b7f4cf4 --- /dev/null +++ b/crates/testkit/tests/source_limits.rs @@ -0,0 +1,99 @@ +#![cfg(not(target_arch = "wasm32"))] + +use craft_testkit::{SourceLimits, rust_sources_with_limits}; +use std::io::ErrorKind; +use std::path::{Path, PathBuf}; + +/// A scratch folder that this test made and removes on drop, also when the test panics. +struct ScratchDir(PathBuf); + +impl ScratchDir { + fn new(tag: &str) -> Self { + let base = std::env::temp_dir(); + for n in 0..1000u32 { + let path = base.join(format!("craft_testkit_limits_{tag}_{}_{n}", std::process::id())); + match std::fs::create_dir(&path) { + Ok(()) => return Self(path), + Err(e) if e.kind() == ErrorKind::AlreadyExists => continue, + Err(e) => panic!("create scratch folder {}: {e}", path.display()), + } + } + panic!("no free scratch folder name for {tag}"); + } + + fn path(&self) -> &Path { + &self.0 + } + + fn write(&self, relative: &str, content: &str) { + let path = self.0.join(relative); + if let Some(parent) = path.parent() { + std::fs::create_dir_all(parent).expect("create parent folder"); + } + std::fs::write(path, content).expect("write file"); + } +} + +impl Drop for ScratchDir { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +fn three_files(tag: &str) -> ScratchDir { + let dir = ScratchDir::new(tag); + dir.write("src/a.rs", "0123456789"); + dir.write("src/b.rs", "0123456789"); + dir.write("src/c.rs", "0123456789"); + dir +} + +#[test] +fn defaults_are_documented_values() { + let limits = SourceLimits::default(); + assert_eq!(limits.max_file_bytes, 8 << 20); + assert_eq!(limits.max_total_bytes, 256 << 20); + assert_eq!(limits.max_files, 50_000); +} + +#[test] +fn files_within_the_limits_are_read() { + let dir = three_files("within"); + let limits = SourceLimits { max_file_bytes: 10, max_total_bytes: 30, max_files: 3 }; + let sources = rust_sources_with_limits(dir.path(), limits).expect("within limits"); + assert_eq!(sources.len(), 3); + assert!(sources.iter().all(|(_, content)| content == "0123456789")); +} + +#[test] +fn a_file_over_the_size_limit_is_an_error() { + let dir = three_files("file"); + let limits = SourceLimits { max_file_bytes: 9, ..SourceLimits::default() }; + let err = rust_sources_with_limits(dir.path(), limits).expect_err("file over the limit"); + assert_eq!(err.kind(), ErrorKind::FileTooLarge); +} + +#[test] +fn files_over_the_total_limit_are_an_error() { + let dir = three_files("total"); + let limits = SourceLimits { max_total_bytes: 29, ..SourceLimits::default() }; + let err = rust_sources_with_limits(dir.path(), limits).expect_err("total over the limit"); + assert_eq!(err.kind(), ErrorKind::QuotaExceeded); +} + +#[test] +fn more_files_than_the_count_limit_is_an_error() { + let dir = three_files("count"); + let limits = SourceLimits { max_files: 2, ..SourceLimits::default() }; + let err = rust_sources_with_limits(dir.path(), limits).expect_err("too many files"); + assert_eq!(err.kind(), ErrorKind::QuotaExceeded); +} + +#[test] +fn files_the_filter_skips_do_not_count_against_the_limits() { + let dir = three_files("skipped"); + dir.write("src/tests.rs", &"x".repeat(100)); + dir.write("tests/big.rs", &"x".repeat(100)); + let limits = SourceLimits { max_file_bytes: 10, max_total_bytes: 30, max_files: 3 }; + assert_eq!(rust_sources_with_limits(dir.path(), limits).expect("skipped files are not read").len(), 3); +} From b9d451674eee23ac1b3858d4341e83be45f18153 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 11:40:45 -0800 Subject: [PATCH 03/33] craft-testkit: std_instant skips module files a native-only mod declares std_instant read each file on its own, so `#[cfg(not(target_arch = "wasm32"))] mod native;` in lib.rs did not stop it from reporting std::time::Instant in native.rs when both came from one rust_sources call. std_instant now first collects every `mod name;` declaration and treats the file it names as native-only when the declaration is inside an item whose cfg is false on wasm32-unknown-unknown, along with the files that file declares. A file that a declaration outside such items also reaches from a crate root is still checked. Module files are found by rustc's rules: next to lib.rs, main.rs and mod.rs, in the stem folder of any other file, below enclosing inline modules, and through #[path] on the declaration or on an enclosing inline module. Declarations inside more than 64 inline modules are not followed, so their files are checked. --- crates/testkit/README.md | 4 +- crates/testkit/src/guards.rs | 296 ++++++++++++++++++++++++++++++++- crates/testkit/tests/guards.rs | 145 ++++++++++++++++ 3 files changed, 441 insertions(+), 4 deletions(-) diff --git a/crates/testkit/README.md b/crates/testkit/README.md index 75e74d7b82..b6042e0bb1 100644 --- a/crates/testkit/README.md +++ b/crates/testkit/README.md @@ -8,7 +8,7 @@ Source-level platform regression guards and verification utilities for the Craft 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 `::` 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. 2. **`wgsl_float_literals` / `wgsl_float_literals_in`**: Scans WGSL shader sources and flags decimal and hexadecimal float literals whose value exceeds `f32::MAX` (such as `3.40282347e38` or `0x1p+500f`), or 65504, the largest finite `f16`, for a literal with an `h` suffix. 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. Exact values equal to `f32::MAX` can be written as `3.4028234663852886e38` or as the hex float `0x1.fffffep+127f`. -3. **`std_instant`**: Flags `std::time::Instant` outside comments and strings: the full path, `::Instant` where a `use` binds `m` to `std::time`, and each `use` that imports `std::time::Instant` or `std::time::*`. Other crates' `Instant` (such as `web_time::Instant`) is not flagged, and neither is an item whose `cfg` attribute is false on `wasm32-unknown-unknown`. 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`. +3. **`std_instant`**: Flags `std::time::Instant` outside comments and strings: the full path, `::Instant` where a `use` binds `m` to `std::time`, and each `use` that imports `std::time::Instant` or `std::time::*`. Other crates' `Instant` (such as `web_time::Instant`) is not flagged, and neither is an item whose `cfg` attribute is false on `wasm32-unknown-unknown`. 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, `.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`. ## Epistemic Scope: Syntactic Guards vs Runtime Validation @@ -22,7 +22,7 @@ Source-level guards provide deterministic syntactic evidence about codebase stru ### What They Cannot Establish - **Runtime execution safety**: Syntactic checks do not verify whether code branches actually execute at runtime. - **Semantic type resolution**: The scanners follow `use` renames within one file only. They do not resolve paths through other modules or re-exports, a rename of `std` itself, or expand macros. -- **Complex target predicates**: `std_instant` evaluates `cfg` predicates (`all`, `any`, `not`, `unix`, `windows` and the `target_*` keys) for `wasm32-unknown-unknown`, on outer attributes for the item that follows and on inner attributes (`#![cfg(...)]`) for the rest of the module. A predicate that depends on a feature or on `test` is not known from the source, so its item is checked. Applications should scope `std_instant` tests to the specific crates that compile into their web distribution. +- **Complex target predicates**: `std_instant` evaluates `cfg` predicates (`all`, `any`, `not`, `unix`, `windows` and the `target_*` keys) for `wasm32-unknown-unknown`, on outer attributes for the item that follows and on inner attributes (`#![cfg(...)]`) for the rest of the module, and on `mod name;` declarations for the module's file and its descendants. It compares file paths as text, so the files must come from one `rust_sources` call or be named the same way. A predicate that depends on a feature or on `test` is not known from the source, so its item is checked. Applications should scope `std_instant` tests to the specific crates that compile into their web distribution. - **Driver and host OS behavior**: Syntactic checks do not verify WebGPU driver compatibility or host window manager event dispatch. Source guards serve as fast, zero-dependency regression gates in application test suites, complementing platform integration tests and CI workflows. diff --git a/crates/testkit/src/guards.rs b/crates/testkit/src/guards.rs index a8a14401ef..1588884e7d 100644 --- a/crates/testkit/src/guards.rs +++ b/crates/testkit/src/guards.rs @@ -1,9 +1,10 @@ //! Platform regression guards checking source code for known defects and lifecycle hazards. -use std::collections::BTreeSet; +use std::collections::{BTreeMap, BTreeSet}; use std::fmt; #[cfg(not(target_arch = "wasm32"))] use std::path::Path; +use std::rc::Rc; /// A diagnostic finding reported by a source guard. #[derive(Debug, Clone, PartialEq, Eq)] @@ -622,6 +623,273 @@ fn native_only(toks: &[Token]) -> Vec { skip } +/// A module declaration, `mod name;` or the head of `mod name { ... }`. +#[derive(Debug, Clone)] +struct ModName { + name: String, + /// The string of a `#[path = "..."]` attribute on the declaration. + path_attribute: Option, +} + +/// An out-of-line module declaration, `mod name;`. +#[derive(Debug)] +struct ModDecl { + module: ModName, + /// The inline modules (`mod a { ... }`) the declaration is inside, outermost first, shared between the + /// declarations inside them. + inline: Vec>, + /// Whether the declaration is inside an item whose `cfg` is false on `wasm32-unknown-unknown`. + native: bool, +} + +/// The most tokens [`path_attribute`] reads back from one `mod` keyword, so that hostile nesting cannot +/// make the scan quadratic. +const ATTRIBUTE_SCAN_LIMIT: usize = 4096; + +/// The index of the bracket `open` that matches the bracket `close` at `toks[end - 1]`, reading back +/// from `end`, or `None` when it is not found within `budget` tokens. +fn matching_open_back(toks: &[Token], end: usize, open: char, close: char, budget: &mut usize) -> Option { + let mut depth = 0usize; + let mut j = end; + while j > 0 && *budget > 0 { + j -= 1; + *budget -= 1; + if toks[j].is_punct(close) { + depth += 1; + } else if toks[j].is_punct(open) { + depth = depth.saturating_sub(1); + if depth == 0 { + return Some(j); + } + } + } + None +} + +/// The string of a `#[path = "..."]` outer attribute on the item whose `mod` keyword is at `toks[m]`. +fn path_attribute(toks: &[Token], m: usize) -> Option { + let mut budget = ATTRIBUTE_SCAN_LIMIT; + let mut k = m; + if k > 0 && toks[k - 1].is_punct(')') { + // A visibility such as `pub(crate)`. + let j = matching_open_back(toks, k, '(', ')', &mut budget)?; + if j > 0 && toks[j - 1].is_ident("pub") { + k = j - 1; + } + } else if k > 0 && toks[k - 1].is_ident("pub") { + k -= 1; + } + let mut found = None; + while k > 0 && toks[k - 1].is_punct(']') { + let Some(j) = matching_open_back(toks, k, '[', ']', &mut budget) else { break }; + if j == 0 || !toks[j - 1].is_punct('#') { + break; + } + if toks.get(j + 1).is_some_and(|t| t.is_ident("path")) + && toks.get(j + 2).is_some_and(|t| t.is_punct('=')) + && let Some(Kind::Str(s)) = toks.get(j + 3).map(|t| &t.kind) + { + found = Some(s.clone()); + } + k = j - 1; + } + found +} + +/// What an open brace in [`module_decls`] opened. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Brace { + /// A block that is not an inline module. + Block, + /// An inline module, pushed on the inline stack. + Module, + /// An inline module deeper than [`MAX_NESTING`], not tracked. + TooDeep, +} + +/// 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. +fn module_decls(toks: &[Token], skip: &[bool]) -> Vec { + let mut decls = Vec::new(); + let mut braces: Vec = Vec::new(); + let mut inline: Vec> = Vec::new(); + let mut too_deep = 0usize; + for (i, tok) in toks.iter().enumerate() { + match &tok.kind { + Kind::Punct('{') => { + 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) })); + Brace::Module + } else { + too_deep += 1; + Brace::TooDeep + } + } + _ => Brace::Block, + }; + braces.push(brace); + } + Kind::Punct('}') => match braces.pop() { + Some(Brace::Module) => { + inline.pop(); + } + Some(Brace::TooDeep) => too_deep -= 1, + _ => {} + }, + Kind::Ident(k) if k == "mod" && too_deep == 0 => { + if let Some(Kind::Ident(name)) = toks.get(i + 1).map(|t| &t.kind) + && 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) }, + inline: inline.clone(), + native: skip.get(i).copied().unwrap_or(false), + }); + } + } + _ => {} + } + } + decls +} + +/// A path with `\` read as `/`, empty and `.` components removed and `..` applied to the component before it. +fn normalize_path(path: &str) -> String { + let path = path.replace('\\', "/"); + let absolute = path.starts_with('/'); + let mut parts: Vec<&str> = Vec::new(); + for part in path.split('/') { + match part { + "" | "." => {} + ".." if parts.last().is_some_and(|p| *p != "..") => { + parts.pop(); + } + p => parts.push(p), + } + } + let joined = parts.join("/"); + if absolute { format!("/{joined}") } else { joined } +} + +/// `child` below the folder `parent`, normalized. A `child` that is an absolute path (`/x`, `\x` or `C:...`) +/// stands alone. `\\` is read as one separator, since a string literal keeps its escapes. +fn join_path(parent: &str, child: &str) -> String { + let child = child.replace("\\\\", "/"); + if parent.is_empty() || child.starts_with('/') || child.starts_with('\\') || child.as_bytes().get(1) == Some(&b':') { + normalize_path(&child) + } else { + normalize_path(&format!("{parent}/{child}")) + } +} + +/// The paths, normalized, where the module `decl` declared in the file at `parent` (normalized) can be. +/// +/// The modules of `lib.rs`, `main.rs` and `mod.rs` are in the file's folder, and those of any other file +/// are in the folder named after its stem. Each inline module around the declaration adds a folder named +/// after it, or with a `path` attribute, moves to that path relative to the current folder (without the +/// stem folder). The module is then `.rs` or `/mod.rs` there, or with a `path` attribute, that +/// path relative to the current folder, again without the stem folder. +fn module_files(parent: &str, decl: &ModDecl) -> Vec { + let (dir, file) = match parent.rsplit_once('/') { + Some(("", file)) => ("/", file), + Some(split) => split, + None => ("", parent), + }; + let mut folder = dir.to_string(); + let mut stem = (!matches!(file, "lib.rs" | "main.rs" | "mod.rs")).then(|| file.strip_suffix(".rs").unwrap_or(file)); + for inline in &decl.inline { + if let Some(attr) = &inline.path_attribute { + folder = join_path(&folder, attr); + stem = None; + } else { + if let Some(stem) = stem.take() { + folder = join_path(&folder, stem); + } + folder = join_path(&folder, &inline.name); + } + } + if let Some(attr) = &decl.module.path_attribute { + return vec![join_path(&folder, attr)]; + } + if let Some(stem) = stem { + folder = join_path(&folder, stem); + } + let name = &decl.module.name; + vec![join_path(&folder, &format!("{name}.rs")), join_path(&folder, &format!("{name}/mod.rs"))] +} + +/// For each file, whether it is native-only: a `mod` declaration in a native-only item, or any declaration +/// in a native-only file, names it, and no chain of declarations outside native-only items reaches it from +/// a crate root (a file that no declaration names). +fn native_only_files(paths: &[String], decls: &[Vec]) -> Vec { + let mut index: BTreeMap<&str, Vec> = BTreeMap::new(); + for (i, path) in paths.iter().enumerate() { + index.entry(path.as_str()).or_default().push(i); + } + // The files each declaration names, in the order of `decls`. + let children: Vec)>> = decls + .iter() + .enumerate() + .map(|(parent, file_decls)| { + file_decls + .iter() + .map(|decl| { + let files = + module_files(&paths[parent], decl).iter().flat_map(|c| index.get(c.as_str()).into_iter().flatten().copied()).collect(); + (decl.native, files) + }) + .collect() + }) + .collect(); + + // Files the web build compiles: crate roots, and every file a declaration outside a native-only item + // of such a file names. + let mut named = vec![false; paths.len()]; + for (_, files) in children.iter().flatten() { + for &j in files { + named[j] = true; + } + } + let mut web = vec![false; paths.len()]; + let mut queue: Vec = (0..paths.len()).filter(|&j| !named[j]).collect(); + for &j in &queue { + web[j] = true; + } + while let Some(parent) = queue.pop() { + for (_, files) in children[parent].iter().filter(|(is_native, _)| !is_native) { + for &j in files { + if !web[j] { + web[j] = true; + queue.push(j); + } + } + } + } + + // Files a native-only declaration names, and their descendants. + let mut native = vec![false; paths.len()]; + let mut mark = |files: &[usize], queue: &mut Vec| { + for &j in files { + if !native[j] { + native[j] = true; + queue.push(j); + } + } + }; + for (_, files) in children.iter().flatten().filter(|(is_native, _)| *is_native) { + mark(files, &mut queue); + } + while let Some(parent) = queue.pop() { + for (_, files) in &children[parent] { + mark(files, &mut queue); + } + } + native.iter().zip(&web).map(|(&n, &w)| n && !w).collect() +} + /// Add one finding for each line in `lines`, in line order, with the trimmed text of that line. fn report(findings: &mut Vec, path: &str, content: &str, lines: &BTreeSet) { if lines.is_empty() { @@ -693,6 +961,15 @@ where /// (for example `#[cfg(not(target_arch = "wasm32"))]`, `#[cfg(all(unix, ...))]`, `#[cfg(target_os = "macos")]`, /// or `#![cfg(...)]` for the rest of a module). A predicate that depends on a feature or on `test` is not /// known from the source, so the item is checked. +/// * **Module files**: a `mod name;` inside such an item makes the module's file native-only, and so are the +/// files of the modules declared in it, when they are among `files`, unless a chain of declarations outside +/// such items also reaches the file from a crate root (a file that no declaration names). The module's file is `name.rs` or +/// `name/mod.rs` next to `lib.rs`, `main.rs` or `mod.rs`, and in the folder named after any other file's +/// stem, below the folders of enclosing inline modules; a `#[path = "..."]` attribute on the declaration +/// or on an enclosing inline module is followed. Paths are compared as text with `\` read as `/`, so the files must be named the same way +/// (for example all from one `rust_sources` call), and a crate root other than `lib.rs` or `main.rs` +/// (such as `src/bin/tool.rs`) is read as an ordinary module file. A declaration inside more than 64 inline +/// modules is not followed, so its file is checked. /// * **Limitations**: This is a lexical source guard. It does not expand macros, resolve paths through other /// modules or re-exports, rename `std` itself (`use std as s;`), or follow aliases in a different scope than /// the file. @@ -701,8 +978,23 @@ where I: IntoIterator, I::Item: AsFileSource, { + let files: Vec = files.into_iter().collect(); + let paths: Vec = files.iter().map(|file| normalize_path(file.path())).collect(); + // Only the declarations are kept from this pass, so the tokens of every file are never held at once. + let decls: Vec> = files + .iter() + .map(|file| { + let toks = lex_rust(file.content()); + module_decls(&toks, &native_only(&toks)) + }) + .collect(); + let excluded = native_only_files(&paths, &decls); + let mut findings = Vec::new(); - for file in files { + for (file, excluded) in files.iter().zip(excluded) { + if excluded { + continue; + } let path = file.path(); let content = file.content(); let toks = lex_rust(content); diff --git a/crates/testkit/tests/guards.rs b/crates/testkit/tests/guards.rs index a2a419ca18..a68209be9d 100644 --- a/crates/testkit/tests/guards.rs +++ b/crates/testkit/tests/guards.rs @@ -522,6 +522,151 @@ fn run() { assert_eq!(lines(&std_instant([("src/run.rs", source)])), vec![4, 8, 9]); } +fn finding_paths(findings: &[Finding]) -> Vec<&str> { + findings.iter().map(|f| f.path.as_str()).collect() +} + +#[test] +fn std_instant_skips_module_files_a_native_cfg_declares() { + let lib = r#" +#[cfg(not(target_arch = "wasm32"))] +mod native; +mod web; +#[cfg(feature = "extra")] +mod extra; +"#; + let native = "mod clock;\npub fn now() -> std::time::Instant { std::time::Instant::now() }\n"; + let native_clock = "use std::time::Instant;\n"; + let web = "#[cfg(unix)]\nmod imp;\npub fn now() { let _t = std::time::Instant::now(); }\n"; + let web_imp = "use std::time::Instant;\n"; + let sibling_imp = "use std::time::Instant;\n"; + let extra = "use std::time::Instant;\n"; + let files = [ + ("src/lib.rs", lib), + ("src/native.rs", native), + ("src/native/clock.rs", native_clock), + ("src/web.rs", web), + ("src/web/imp.rs", web_imp), + ("src/imp.rs", sibling_imp), + ("src/extra.rs", extra), + ]; + assert_eq!(finding_paths(&std_instant(files)), vec!["src/web.rs", "src/imp.rs", "src/extra.rs"]); +} + +#[test] +fn std_instant_skips_native_module_files_by_mod_rs_path_attribute_and_inline_module() { + let main = r#" +#[cfg(unix)] +pub(crate) mod sys; +#[cfg(target_os = "macos")] +#[path = "platform/mac_clock.rs"] +mod mac; +#[cfg(windows)] +mod outer { + mod inner; +} +#[cfg(unix)] +#[path = "platform/native.rs"] +pub(in crate) mod native; +"#; + let clock = "use std::time::Instant;\n"; + let files = [ + ("C:\\app\\src\\main.rs", main), + ("C:\\app\\src\\platform\\native.rs", clock), + ("C:\\app\\src\\sys\\mod.rs", "mod detail;\n"), + ("C:\\app\\src\\sys\\detail.rs", clock), + ("C:\\app\\src\\platform\\mac_clock.rs", clock), + ("C:\\app\\src\\outer\\inner.rs", clock), + ("C:\\app\\src\\mac.rs", clock), + ]; + assert_eq!(finding_paths(&std_instant(files)), vec!["C:\\app\\src\\mac.rs"]); +} + +#[test] +fn std_instant_checks_a_module_file_that_a_web_declaration_also_names() { + let lib = r#" +#[cfg(windows)] +mod imp; +#[cfg(target_arch = "wasm32")] +mod imp; +#[cfg(unix)] +mod sys; +"#; + let files = [ + ("src/lib.rs", lib), + ("src/imp.rs", "mod detail;\n"), + ("src/imp/detail.rs", "use std::time::Instant;\n"), + ("src/sys.rs", "#[path = \"imp/detail.rs\"]\nmod shared;\n"), + ]; + assert_eq!(finding_paths(&std_instant(files)), vec!["src/imp/detail.rs"]); +} + +#[test] +fn std_instant_reads_an_inline_module_path_attribute_as_the_folder_of_its_modules() { + let lib = r#" +#[cfg(unix)] +#[path = "native"] +mod platform { + mod clock; +} +mod web; +"#; + let web = r#" +#[path = "shared"] +mod inner { + #[cfg(windows)] + mod tick; +} +"#; + let clock = "use std::time::Instant;\n"; + let files = [ + ("src/lib.rs", lib), + ("src/native/clock.rs", clock), + ("src/platform/clock.rs", clock), + ("src/web.rs", web), + ("src/shared/tick.rs", clock), + ("src/web/shared/tick.rs", clock), + ]; + assert_eq!(finding_paths(&std_instant(files)), vec!["src/platform/clock.rs", "src/web/shared/tick.rs"]); +} + +#[test] +fn std_instant_reads_top_level_path_attributes_of_a_non_mod_rs_file_from_its_folder() { + let a = r#" +#[cfg(unix)] +#[path = "native.rs"] +mod imp; +#[cfg(unix)] +#[path = "native"] +mod platform { + mod clock; +} +"#; + let clock = "use std::time::Instant;\n"; + let files = [ + ("src/lib.rs", "mod a;\n"), + ("src/a.rs", a), + ("src/native.rs", clock), + ("src/native/clock.rs", clock), + ("src/a/native.rs", clock), + ("src/a/native/clock.rs", clock), + ]; + assert_eq!(finding_paths(&std_instant(files)), vec!["src/a/native.rs", "src/a/native/clock.rs"]); +} + +#[test] +fn std_instant_checks_module_files_declared_deeper_than_its_nesting_limit() { + let lib = format!("{}#[cfg(unix)]\nmod deep;\n{}", "mod m {\n".repeat(70), "}\n".repeat(70)); + let shallow_lib = format!("{}#[cfg(unix)]\nmod deep;\n{}", "mod m {\n".repeat(3), "}\n".repeat(3)); + let deep_path = format!("src/{}deep.rs", "m/".repeat(70)); + let shallow_path = format!("src/{}deep.rs", "m/".repeat(3)); + let clock = "use std::time::Instant;\n"; + let files = [("src/lib.rs", lib.as_str()), (deep_path.as_str(), clock)]; + assert_eq!(finding_paths(&std_instant(files)), vec![deep_path.as_str()]); + let files = [("src/lib.rs", shallow_lib.as_str()), (shallow_path.as_str(), clock)]; + assert!(std_instant(files).is_empty()); +} + #[test] fn wgsl_integer_literals_are_not_floats() { let shader = r#" From b89076646da878483fc56ed9790865697062e9c9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 11:55:02 -0800 Subject: [PATCH 04/33] craft-testkit: rust_sources docs name the CACHEDIR.TAG signature it checks rust_sources skips a folder only when its CACHEDIR.TAG starts with the line Signature: 8a477f597d28d172789f06886806bc55. The doc comment and the crate README now say so instead of naming any CACHEDIR.TAG file. --- crates/testkit/README.md | 2 +- crates/testkit/src/guards.rs | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/crates/testkit/README.md b/crates/testkit/README.md index b6042e0bb1..5fc8ea3de1 100644 --- a/crates/testkit/README.md +++ b/crates/testkit/README.md @@ -9,7 +9,7 @@ Source-level platform regression guards and verification utilities for the Craft 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 `::` 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. 2. **`wgsl_float_literals` / `wgsl_float_literals_in`**: Scans WGSL shader sources and flags decimal and hexadecimal float literals whose value exceeds `f32::MAX` (such as `3.40282347e38` or `0x1p+500f`), or 65504, the largest finite `f16`, for a literal with an `h` suffix. 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. Exact values equal to `f32::MAX` can be written as `3.4028234663852886e38` or as the hex float `0x1.fffffep+127f`. 3. **`std_instant`**: Flags `std::time::Instant` outside comments and strings: the full path, `::Instant` where a `use` binds `m` to `std::time`, and each `use` that imports `std::time::Instant` or `std::time::*`. Other crates' `Instant` (such as `web_time::Instant`) is not flagged, and neither is an item whose `cfg` attribute is false on `wasm32-unknown-unknown`. 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, `.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`. +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`. ## Epistemic Scope: Syntactic Guards vs Runtime Validation diff --git a/crates/testkit/src/guards.rs b/crates/testkit/src/guards.rs index 1588884e7d..f1ddbb781a 100644 --- a/crates/testkit/src/guards.rs +++ b/crates/testkit/src/guards.rs @@ -1304,7 +1304,8 @@ fn is_cache_dir(dir: &Path) -> bool { /// * `*_test.rs` /// * `test.rs` /// * Any file below `dir` within a directory named `tests`, `benches`, `examples` or `target`, or whose -/// name starts with `.`, or that holds a `CACHEDIR.TAG` file (a build output folder with another name). +/// name starts with `.`, or that holds a `CACHEDIR.TAG` file starting with the signature line +/// `Signature: 8a477f597d28d172789f06886806bc55` (a build output folder with another name). /// * Symbolic links (and, on Windows, junctions) to files or folders, which are not followed. /// /// Results are sorted lexicographically by file path for deterministic behavior across platforms. From 836433ccb9e2dc261da1f74b1c33bdcf94105ff9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 12:01:40 -0800 Subject: [PATCH 05/33] craft-testkit: wgsl_float_literals docs say the limit check uses the value rounded to f64 README item 2, the wgsl_float_literals rustdoc and the boundary test comment now say the scanner compares each literal's value rounded to f64, so a literal that exceeds the maximum by less than f64 precision, such as 0x1.fffffe000000001p+127f, is not reported. They also say 0x1.fffffep+127f equals f32::MAX and 3.4028234663852886e38 rounds to it. --- crates/testkit/README.md | 2 +- crates/testkit/src/guards.rs | 8 +++++--- crates/testkit/tests/guards.rs | 2 +- 3 files changed, 7 insertions(+), 5 deletions(-) diff --git a/crates/testkit/README.md b/crates/testkit/README.md index 5fc8ea3de1..36b87bb89d 100644 --- a/crates/testkit/README.md +++ b/crates/testkit/README.md @@ -7,7 +7,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 `::` 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. -2. **`wgsl_float_literals` / `wgsl_float_literals_in`**: Scans WGSL shader sources and flags decimal and hexadecimal float literals whose value exceeds `f32::MAX` (such as `3.40282347e38` or `0x1p+500f`), or 65504, the largest finite `f16`, for a literal with an `h` suffix. 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. Exact values equal to `f32::MAX` can be written as `3.4028234663852886e38` or as the hex float `0x1.fffffep+127f`. +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, `::Instant` where a `use` binds `m` to `std::time`, and each `use` that imports `std::time::Instant` or `std::time::*`. Other crates' `Instant` (such as `web_time::Instant`) is not flagged, and neither is an item whose `cfg` attribute is false on `wasm32-unknown-unknown`. 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`. diff --git a/crates/testkit/src/guards.rs b/crates/testkit/src/guards.rs index f1ddbb781a..3df0ad8667 100644 --- a/crates/testkit/src/guards.rs +++ b/crates/testkit/src/guards.rs @@ -1160,14 +1160,16 @@ fn scan_wgsl_hex(code: &[u8], start: usize) -> (usize, usize, bool) { /// Guard: scans a single WGSL shader string and detects float literals outside their type's finite range. /// /// WebGPU compilers in browsers reject a float literal above `f32::MAX` (e.g. `3.40282347e38`) with a -/// pipeline build error, which turns off GPU rendering. Exact values equal to `f32::MAX` can be written -/// as `3.4028234663852886e38` or as the hex float `0x1.fffffep+127f`. +/// pipeline build error, which turns off GPU 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. /// /// ### Policy and Limitations /// /// * **Conservative mathematical bound**: The guard compares the literal's value, rounded to `f64`, /// with `f64::from(f32::MAX)`, or with 65504 (the largest finite `f16`) for an `h` suffix. Any literal -/// above it is reported, even one that a compiler would round down to the maximum. +/// above it is reported, even one that a compiler would round down to the maximum. A literal that exceeds +/// the maximum by less than `f64` precision (such as `0x1.fffffe000000001p+127f`) rounds to the maximum and +/// is not reported. /// * **Which literals**: decimal floats (with a `.`, an exponent or an `f`/`h` suffix) and hexadecimal floats /// (`0x` with a `.` or a `p` exponent). Integer literals (`123`, `123u`, `0xFFi`, `0x1f`) are not floats and /// are not reported. A `-` in front is not part of the literal, so `-1e39` is reported as `1e39`. diff --git a/crates/testkit/tests/guards.rs b/crates/testkit/tests/guards.rs index a68209be9d..76b3e754ea 100644 --- a/crates/testkit/tests/guards.rs +++ b/crates/testkit/tests/guards.rs @@ -318,7 +318,7 @@ fn run() { #[test] fn test_wgsl_exact_f32_max_boundary() { - // 3.4028234663852886e38 is mathematical f32::MAX bit for bit + // 3.4028234663852886e38 rounds to f32::MAX, as an f32 and as an f64 let exact_valid = r#" const EXACT_MAX: f32 = 3.4028234663852886e38; const NEG_EXACT_MAX: f32 = -3.4028234663852886e38; From 5c53194e407c92e42958810348081ed41e50af1c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 12:12:08 -0800 Subject: [PATCH 06/33] craft-testkit: a native cfg on a block statement covers the block and its method-call suffix item_end now ends a cfg-gated statement that starts with a bare block at the block's closing brace, so code after it is checked. When a `.` or `?` follows the closing brace of a block item, the item runs on to its `;` or `,`, so a method call after a cfg-gated block or `unsafe` block stays covered by the cfg. --- crates/testkit/src/guards.rs | 16 +++++++++++++--- crates/testkit/tests/guards.rs | 28 ++++++++++++++++++++++++++++ 2 files changed, 41 insertions(+), 3 deletions(-) diff --git a/crates/testkit/src/guards.rs b/crates/testkit/src/guards.rs index 3df0ad8667..77006af6f3 100644 --- a/crates/testkit/src/guards.rs +++ b/crates/testkit/src/guards.rs @@ -540,9 +540,10 @@ const BLOCK_KEYWORDS: &[&str] = /// index of the bracket that closes the enclosing scope. /// /// It ends after a `;` or a `,` outside brackets, after the closing brace of a block item (one that -/// starts with a keyword in [`BLOCK_KEYWORDS`] or is a macro call with braces) or of a match arm's -/// block, or before a closing bracket of the enclosing scope. 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. +/// starts with `{` or a keyword in [`BLOCK_KEYWORDS`], or is a macro call with braces) or of a match +/// arm's block, or before a closing bracket of the enclosing scope. 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. fn item_end(toks: &[Token], start: usize, inner: bool) -> usize { let mut depth = 0usize; let mut block_item = false; @@ -550,6 +551,9 @@ fn item_end(toks: &[Token], start: usize, inner: bool) -> usize { let mut j = start; while j < toks.len() { let at_top = depth == 0 && !inner; + if j == start && at_top && toks[j].is_punct('{') { + block_item = true; + } match &toks[j].kind { Kind::Ident(k) if at_top && BLOCK_KEYWORDS.contains(&k.as_str()) => block_item = true, Kind::Punct('!') if at_top && toks.get(j + 1).is_some_and(|t| t.is_punct('{')) => block_item = true, @@ -565,6 +569,12 @@ fn item_end(toks: &[Token], start: usize, inner: bool) -> usize { j += 1; continue; } + if toks.get(j + 1).is_some_and(|t| t.is_punct('.') || t.is_punct('?')) { + // A method call, field or `?` after the block continues the expression to its `;` or `,`. + block_item = false; + j += 1; + continue; + } let comma = toks.get(j + 1).is_some_and(|t| t.is_punct(',')); return if arm && comma { j + 2 } else { j + 1 }; } diff --git a/crates/testkit/tests/guards.rs b/crates/testkit/tests/guards.rs index 76b3e754ea..5d3df778fe 100644 --- a/crates/testkit/tests/guards.rs +++ b/crates/testkit/tests/guards.rs @@ -473,6 +473,34 @@ use std::time::Instant as MacInstant; assert_eq!(lines(&std_instant([("src/clock.rs", source)])), vec![4, 13, 16, 19]); } +#[test] +fn std_instant_ends_a_native_cfg_block_statement_at_its_closing_brace() { + let source = r#" +fn run() { + #[cfg(unix)] { + let _a = std::time::Instant::now(); + } + let t = std::time::Instant::now(); +} +"#; + assert_eq!(lines(&std_instant([("src/run.rs", source)])), vec![6]); +} + +#[test] +fn std_instant_skips_a_method_call_after_a_native_cfg_block() { + let source = r#" +fn run(x: Option) -> Option { + #[cfg(unix)] + { 0u64 }.saturating_add(std::time::Instant::now().elapsed().as_nanos() as u64); + #[cfg(unix)] + unsafe { x }.map(|_| std::time::Instant::now())?; + let t = std::time::Instant::now(); + x +} +"#; + assert_eq!(lines(&std_instant([("src/run.rs", source)])), vec![7]); +} + #[test] fn std_instant_inner_cfg_covers_the_whole_file() { let source = r#" From 2abb1c6a8078eabf3bea5896bfb17c5805f5a651 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 13:03:11 -0800 Subject: [PATCH 07/33] craft-testkit: test the guards on split use groups, brace literals, escaped line breaks, deep nesting and broken links New tests cover cases the guards already handle: - wgsl_float_literals checks a literal that follows a hex literal and an operator (0x1.0p0+1e39, 0xFF+1e39, 0x1f-4e38). - std_instant reports Instant in a use group split over several lines. - '{' and '}' character literals do not end a native cfg item early. - An escaped line break in a string keeps the line numbers after it. - Use groups and cfg predicates nested 100,000 deep return without exhausting the stack. - rust_sources skips a broken symbolic link to a file or a folder. --- crates/testkit/tests/guards.rs | 71 ++++++++++++++++++++++++++++++++++ 1 file changed, 71 insertions(+) diff --git a/crates/testkit/tests/guards.rs b/crates/testkit/tests/guards.rs index 5d3df778fe..169fdd5734 100644 --- a/crates/testkit/tests/guards.rs +++ b/crates/testkit/tests/guards.rs @@ -550,6 +550,57 @@ fn run() { assert_eq!(lines(&std_instant([("src/run.rs", source)])), vec![4, 8, 9]); } +#[test] +fn std_instant_reads_a_use_group_split_over_several_lines() { + let source = r#" +use std::time::{ + Instant +}; +use std::time::{ + Duration, + Instant as Clock, +}; +"#; + let findings = std_instant([("src/clock.rs", source)]); + assert_eq!(lines(&findings), vec![3, 7]); + assert_eq!(findings[0].text, "Instant"); +} + +#[test] +fn std_instant_does_not_count_brace_character_literals_as_braces() { + let source = r#" +#[cfg(unix)] +fn native() { let open = '{'; let b = b'{'; let t = std::time::Instant::now(); } +fn web() { let close = '}'; let t = std::time::Instant::now(); } +#[cfg(unix)] +fn native_two() { let close = '}'; let t = std::time::Instant::now(); } +fn web_two() { let t = std::time::Instant::now(); } +"#; + assert_eq!(lines(&std_instant([("src/clock.rs", source)])), vec![4, 7]); +} + +#[test] +fn an_escaped_line_break_in_a_string_keeps_line_numbers() { + let source = + "fn web() {\n let s = \"one \\\n two\";\n let t = std::time::Instant::now();\n let q = PredefinedMenuItem::quit(None);\n}\n"; + assert_eq!(lines(&std_instant([("src/web.rs", source)])), vec![4]); + assert_eq!(lines(&predefined_quit([("src/web.rs", source)])), vec![5]); +} + +#[test] +fn deeply_nested_use_groups_and_cfg_predicates_do_not_exhaust_the_stack() { + let depth = 100_000; + let use_groups = format!("use std::time::{}Instant{};\nfn f() {{}}\n", "{".repeat(depth), "}".repeat(depth)); + assert!(std_instant([("src/deep.rs", use_groups.as_str())]).is_empty()); + assert!(predefined_quit([("src/deep.rs", use_groups.as_str())]).is_empty()); + + let cfg = format!("#[cfg({}unix{})]\nfn f() {{ let t = std::time::Instant::now(); }}\n", "not(".repeat(depth), ")".repeat(depth)); + assert_eq!(lines(&std_instant([("src/deep.rs", cfg.as_str())])), vec![2]); + + let shallow = "use std::time::{{{Instant}}};\n"; + assert_eq!(lines(&std_instant([("src/shallow.rs", shallow)])), vec![1]); +} + fn finding_paths(findings: &[Finding]) -> Vec<&str> { findings.iter().map(|f| f.path.as_str()).collect() } @@ -732,6 +783,15 @@ const F16_OVER: f16 = 0x1.0p16h; assert_eq!(findings[3].text, "0x1.0p16"); } +#[test] +fn wgsl_literals_after_a_hex_literal_and_an_operator_are_checked() { + let shader = "const A = 0x1.0p0+1e39;\nconst B = 0xFF+1e39;\nconst C = 0x1f-4e38;\nconst D = 0xAu*2.0+5e38;\nconst E = 0x1p1-0x1p+500;\n"; + let findings = wgsl_float_literals(shader); + assert_eq!(lines(&findings), vec![1, 2, 3, 4, 5]); + let texts: Vec<&str> = findings.iter().map(|f| f.text.as_str()).collect(); + assert_eq!(texts, vec!["1e39", "1e39", "4e38", "5e38", "0x1p+500"]); +} + #[test] fn wgsl_block_comment_markers_inside_line_comments_do_not_open_a_comment() { let shader = "// a /* inside a line comment\nconst BAD: f32 = 4e38;\n/* block // with a line marker */ const ALSO_BAD: f32 = 5e38;\n"; @@ -817,6 +877,17 @@ fn rust_sources_does_not_loop_on_a_symlink_cycle() { assert_eq!(file_names(&sources), vec!["lib.rs"]); } +#[cfg(unix)] +#[test] +fn rust_sources_skips_a_broken_symlink() { + let dir = ScratchDir::new("symlink_broken"); + dir.write("src/lib.rs", "pub fn lib() {}"); + std::os::unix::fs::symlink(dir.path().join("missing.rs"), dir.path().join("src").join("gone.rs")).expect("symlink file"); + std::os::unix::fs::symlink(dir.path().join("missing"), dir.path().join("src").join("gone")).expect("symlink folder"); + let sources = craft_testkit::rust_sources(dir.path()).expect("rust_sources"); + assert_eq!(file_names(&sources), vec!["lib.rs"]); +} + #[cfg(not(target_arch = "wasm32"))] #[test] fn scratch_dirs_leave_existing_folders_alone_and_clean_up_on_panic() { From a7b24b109af3bcdb4ae28e99a184b2595e9c98cc Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 14:58:16 -0800 Subject: [PATCH 08/33] Testkit: std_instant keeps a native cfg on the whole statement it covers A native-only `let`, `return` or other statement whose value holds an `if` or `match` block is now exempt up to its `;`, instead of only to the nested block's closing brace. A match arm whose value holds a block runs to its comma. Const blocks and labeled blocks at the head of a statement or arm end at their closing brace, so the next statement is checked. A `use` split over lines is reported once, on the line where its path starts. Adds tests for paths split by line breaks and comments (CRLF included), cfg attributes with code before and after them on one line, other time modules and longer names, literals and labels, and a large source. --- crates/testkit/README.md | 2 +- crates/testkit/src/guards.rs | 66 ++++++++++---- crates/testkit/tests/guards.rs | 154 +++++++++++++++++++++++++++++++++ 3 files changed, 205 insertions(+), 17 deletions(-) diff --git a/crates/testkit/README.md b/crates/testkit/README.md index 36b87bb89d..2cef797e6f 100644 --- a/crates/testkit/README.md +++ b/crates/testkit/README.md @@ -8,7 +8,7 @@ Source-level platform regression guards and verification utilities for the Craft 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 `::` 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. 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, `::Instant` where a `use` binds `m` to `std::time`, and each `use` that imports `std::time::Instant` or `std::time::*`. Other crates' `Instant` (such as `web_time::Instant`) is not flagged, and neither is an item whose `cfg` attribute is false on `wasm32-unknown-unknown`. 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`. +3. **`std_instant`**: Flags `std::time::Instant` outside comments and strings: the full path, `::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`. ## Epistemic Scope: Syntactic Guards vs Runtime Validation diff --git a/crates/testkit/src/guards.rs b/crates/testkit/src/guards.rs index 77006af6f3..ea2910f640 100644 --- a/crates/testkit/src/guards.rs +++ b/crates/testkit/src/guards.rs @@ -380,6 +380,8 @@ fn parse_use_tree(toks: &[Token], pos: &mut usize, prefix: &mut Vec, sta if toks.get(*pos).is_some_and(|t| t.is_punct(':')) && toks.get(*pos + 1).is_some_and(|t| t.is_punct(':')) { *pos += 2; } + // A leaf is reported on the line where its path starts in this tree, not where its last name is. + let line = toks.get(*pos).map_or(0, |t| t.line); while let Some(tok) = toks.get(*pos) { match &tok.kind { Kind::Ident(name) => { @@ -401,12 +403,12 @@ fn parse_use_tree(toks: &[Token], pos: &mut usize, prefix: &mut Vec, sta *pos += 2; } if let Some(bound) = bound.filter(|b| b != "_") { - out.push(UseLeaf { path, name: Some(bound), line: tok.line, start }); + out.push(UseLeaf { path, name: Some(bound), line, start }); } break; } Kind::Punct('*') => { - out.push(UseLeaf { path: prefix.clone(), name: None, line: tok.line, start }); + out.push(UseLeaf { path: prefix.clone(), name: None, line, start }); *pos += 1; break; } @@ -536,35 +538,63 @@ fn matching_close(toks: &[Token], open: usize) -> usize { const BLOCK_KEYWORDS: &[&str] = &["fn", "mod", "impl", "trait", "struct", "enum", "union", "extern", "macro_rules", "if", "match", "loop", "while", "for", "unsafe"]; +/// Keywords that start a statement whose value follows them, so a block keyword after them is part of +/// that value. +const VALUE_KEYWORDS: &[&str] = &["let", "return", "break", "yield", "become"]; + +/// 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)); + match toks.get(j).map(|t| &t.kind) { + Some(Kind::Punct('{')) => true, + Some(Kind::Other) => punct(j + 1, ':') && punct(j + 2, '{'), + Some(Kind::Ident(k)) => k == "const" && punct(j + 1, '{'), + _ => false, + } +} + /// The index after the item, statement, field or match arm that starts at `start`, or with `inner`, the /// index of the bracket that closes the enclosing scope. /// -/// It ends after a `;` or a `,` outside brackets, after the closing brace of a block item (one that -/// starts with `{` or a keyword in [`BLOCK_KEYWORDS`], or is a macro call with braces) or of a match -/// arm's block, or before a closing bracket of the enclosing scope. 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. +/// It ends after a `;` or a `,` outside brackets, after the closing brace of a block item, or before a +/// closing bracket of the enclosing scope. A block item starts with `{`, a labeled block, a `const` +/// block, a keyword in [`BLOCK_KEYWORDS`] or a macro call with braces, at the head of the item or of a +/// match arm's body (after its `=>`). An `async` block is not a block item: it runs on to its `;`. A +/// block keyword or macro brace after a `=`, a binary operator or a keyword in [`VALUE_KEYWORDS`] +/// 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. 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 j = start; while j < toks.len() { let at_top = depth == 0 && !inner; - if j == start && at_top && toks[j].is_punct('{') { + if j == start && at_top && starts_block(toks, j) { block_item = true; } match &toks[j].kind { - Kind::Ident(k) if at_top && BLOCK_KEYWORDS.contains(&k.as_str()) => block_item = true, - Kind::Punct('!') if at_top && 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('>')) => arm = true, + 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 && 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('>')) => { + // A match arm's body has a head of its own: a block or block keyword there ends the arm. + arm = true; + head = true; + block_item = starts_block(toks, j + 2); + j += 2; + continue; + } + Kind::Punct('=' | '+' | '-' | '*' | '/' | '%' | '^' | '|' | '&' | '<' | '>' | '!') if at_top && !block_item => head = false, Kind::Punct('(' | '[' | '{') => depth += 1, Kind::Punct(c @ (')' | ']' | '}')) => { if depth == 0 { return j; } depth -= 1; - if depth == 0 && *c == '}' && (block_item || arm) && !inner { + if depth == 0 && *c == '}' && block_item && !inner { if toks.get(j + 1).is_some_and(|t| t.is_ident("else")) { j += 1; continue; @@ -572,6 +602,7 @@ fn item_end(toks: &[Token], start: usize, inner: bool) -> usize { if toks.get(j + 1).is_some_and(|t| t.is_punct('.') || t.is_punct('?')) { // A method call, field or `?` after the block continues the expression to its `;` or `,`. block_item = false; + head = false; j += 1; continue; } @@ -964,13 +995,16 @@ where /// * **What is reported**: the paths `std::time::Instant` and `::std::time::Instant`; `::Instant` where a /// `use` outside a native-only item binds `m` to `std::time` (`use std::time;`, `use std::time as t;`, /// `use std::time::{self as t}`); -/// and every `use` that imports `std::time::Instant` or `std::time::*`, under any name. Each finding names -/// the line where the path starts, once per line, in line order. +/// and every `use` that imports `std::time::Instant` or `std::time::*`, under any name. Whitespace, comments +/// and line breaks may separate the parts of a path. Each finding names the line where the path starts (in a +/// `use` group, the line where the name's part of the group starts), once per line, in line order. /// * **What is skipped**: comments, string and character literals, other crates' `Instant` (`web_time::Instant`, /// a `time` module that is not `std::time`), and items whose `cfg` attribute is false on `wasm32-unknown-unknown` /// (for example `#[cfg(not(target_arch = "wasm32"))]`, `#[cfg(all(unix, ...))]`, `#[cfg(target_os = "macos")]`, -/// or `#![cfg(...)]` for the rest of a module). A predicate that depends on a feature or on `test` is not -/// known from the source, so the item is checked. +/// or `#![cfg(...)]` for the rest of a module). Such an attribute covers only its item: code before the +/// attribute or after the item on the same line is checked. A statement whose value holds a block, such as +/// `let n = match x { ... } as u64 + ...;`, is covered up to its `;`. A predicate that depends on a feature +/// or on `test` is not known from the source, so the item is checked. /// * **Module files**: a `mod name;` inside such an item makes the module's file native-only, and so are the /// files of the modules declared in it, when they are among `files`, unless a chain of declarations outside /// such items also reaches the file from a crate root (a file that no declaration names). The module's file is `name.rs` or diff --git a/crates/testkit/tests/guards.rs b/crates/testkit/tests/guards.rs index 169fdd5734..d4cb7ae111 100644 --- a/crates/testkit/tests/guards.rs +++ b/crates/testkit/tests/guards.rs @@ -501,6 +501,160 @@ fn run(x: Option) -> Option { assert_eq!(lines(&std_instant([("src/run.rs", source)])), vec![7]); } +#[test] +fn std_instant_skips_an_operator_after_a_block_inside_a_native_cfg_expression() { + let source = r#" +fn run(flag: bool) -> u64 { + #[cfg(unix)] + let _ = if flag { 1 } else { 2 } + std::time::Instant::now().elapsed().as_secs(); + #[cfg(unix)] + return if flag { 1 } else { 2 } * std::time::Instant::now().elapsed().as_secs(); + let t = std::time::Instant::now(); + 0 +} +"#; + assert_eq!(lines(&std_instant([("src/run.rs", source)])), vec![7]); +} + +#[test] +fn std_instant_skips_a_cast_after_a_match_inside_a_native_cfg_expression() { + let source = r#" +fn run(x: Option) -> u64 { + #[cfg(unix)] + let n = match x { Some(v) => v, None => 0 } as u64 + std::time::Instant::now().elapsed().as_secs(); + let t = std::time::Instant::now(); + 0 +} +"#; + assert_eq!(lines(&std_instant([("src/run.rs", source)])), vec![5]); +} + +#[test] +fn std_instant_runs_a_native_cfg_match_arm_to_its_comma_when_a_block_is_inside_its_value() { + let source = r#" +fn run(x: Option, y: bool) -> u64 { + match x { + #[cfg(unix)] + Some(v) => v as u64 + match y { true => 1, false => 0 } + std::time::Instant::now().elapsed().as_secs(), + #[cfg(unix)] + None => if y { 1 } else { 0 }, + #[cfg(unix)] Some(0) => { 0 } _ => std::time::Instant::now().elapsed().as_secs(), + } +} +"#; + assert_eq!(lines(&std_instant([("src/run.rs", source)])), vec![8]); +} + +#[test] +fn std_instant_ends_a_native_cfg_const_or_labeled_block_at_its_closing_brace() { + let source = r#" +fn run(x: Option) -> u64 { + #[cfg(unix)] + const { assert!(true) } + let a = std::time::Instant::now(); + #[cfg(unix)] + 'done: { let _ = std::time::Instant::now(); break 'done; } + let b = std::time::Instant::now(); + match x { + #[cfg(unix)] + Some(_) => 'arm: { let _ = std::time::Instant::now(); break 'arm; } + _ => { let c = std::time::Instant::now(); } + } + 0 +} +"#; + assert_eq!(lines(&std_instant([("src/run.rs", source)])), vec![5, 8, 12]); +} + +#[test] +fn std_instant_runs_a_native_cfg_async_block_statement_to_its_semicolon() { + let source = r#" +async fn run() { + #[cfg(unix)] + async { std::time::Instant::now() } + .await; + #[cfg(unix)] + async move { std::time::Instant::now() }; + let a = std::time::Instant::now(); +} +"#; + assert_eq!(lines(&std_instant([("src/run.rs", source)])), vec![8]); +} + +#[test] +fn std_instant_checks_code_before_and_after_a_native_cfg_item_on_the_same_line() { + let source = "fn run() { + let a = std::time::Instant::now(); #[cfg(unix)] let b = std::time::Instant::now(); let c = std::time::Instant::now(); + let d = 1; #[cfg(unix)] let e = std::time::Instant::now(); + #[cfg(unix)] let f = std::time::Instant::now(); let g = std::time::Instant::now(); +} +"; + assert_eq!(lines(&std_instant([("src/run.rs", source)])), vec![2, 4]); +} + +#[test] +fn std_instant_reads_paths_split_over_lines_and_comments_with_crlf() { + let source = "use std::time::\r\n Instant;\r\nfn run() {\r\n let t = std::time\r\n ::Instant::now();\r\n let u = std /* a */ :: time // b\r\n :: Instant::now();\r\n}\r\n"; + assert_eq!(lines(&std_instant([("src/run.rs", source)])), vec![1, 4, 6]); +} + +#[test] +fn std_instant_reports_a_use_on_the_line_where_its_path_starts() { + let source = "use std::time::\n Instant as Clock;\nuse std::time::{\n Duration,\n Instant,\n};\nuse std::\n time::*;\n"; + assert_eq!(lines(&std_instant([("src/run.rs", source)])), vec![1, 5, 7]); +} + +#[test] +fn std_instant_ignores_other_time_modules_longer_names_and_a_renamed_duration() { + let source = r#" +use tokio::time::Instant; +use std::time::{Duration as Instant}; +fn run() { + let a = my_time::Instant::now(); + let b = runtime::Instant::now(); + let c = crate::time::Instant::now(); + let d = tokio::time::Instant::now(); + let e = core::time::Instant::now(); + let f = std::time::InstantLike::now(); + let g = mystd::time::Instant::now(); + let h = std::time::Instant::now(); +} +"#; + assert_eq!(lines(&std_instant([("src/run.rs", source)])), vec![12]); +} + +#[test] +fn std_instant_ignores_paths_in_literals_and_comments_and_reads_labels_as_code() { + let source = r##" +fn run<'a>(s: &'a str) -> char { + let _x = "std::time::Instant"; let _r = r#"std::time::Instant"#; let _b = b"std::time::Instant"; let _c = c"std::time::Instant"; + // std::time::Instant + /* std::time::Instant */ + 'outer: loop { break 'outer; } + let q = '"'; let t = std::time::Instant::now(); + 'x' +} +"##; + assert_eq!(lines(&std_instant([("src/run.rs", source)])), vec![7]); +} + +#[test] +fn std_instant_scans_a_large_source_once() { + let mut source = String::from("fn run() {\n"); + for i in 0..20_000 { + if i % 2 == 0 { + source.push_str(" #[cfg(unix)] let a = std::time::Instant::now();\n"); + } else { + source.push_str(" let b = std::time::Instant::now();\n"); + } + } + source.push_str("}\n"); + let found = lines(&std_instant([("src/run.rs", source.as_str())])); + assert_eq!(found.len(), 10_000); + assert_eq!(found.first(), Some(&3)); + assert_eq!(found.last(), Some(&20_001)); +} + #[test] fn std_instant_inner_cfg_covers_the_whole_file() { let source = r#" From 4739754009aa9060f78d85feec802b7cdfab918c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 15:34:50 -0800 Subject: [PATCH 09/33] craft-testkit: guards read cfg literals, escapes and deep nesting, and bound use-path copies - A cfg predicate nested more than 64 levels deep is unknown, so its item is checked instead of skipped. - cfg(true) and cfg(false) are read as their values; r#true and r#false stay option names. - String values in cfg predicates have their escapes decoded; a string with an invalid escape is unknown. - The `:` after a field's name starts its type, so a native-only `callback: fn(),` field ends at its comma and later fields are checked. - use<...> is read as a capturing bound, not a declaration, and the guards keep use paths of at most eight segments of at most 32 bytes, so a long prefix or name shared by many leaves is not copied into each. - std_instant finds the modules of a file that a #[path] attribute names next to that file, separately from a plain load of the same file. - predefined_quit reports ::quit. - wgsl_float_literals ends line comments and counts lines at every WGSL line break, and skips digits inside Unicode identifiers. --- crates/testkit/README.md | 2 +- crates/testkit/src/guards.rs | 387 +++++++++++++++++++++++++-------- crates/testkit/tests/guards.rs | 157 +++++++++++++ 3 files changed, 453 insertions(+), 93 deletions(-) diff --git a/crates/testkit/README.md b/crates/testkit/README.md index 2cef797e6f..ff159f4da1 100644 --- a/crates/testkit/README.md +++ b/crates/testkit/README.md @@ -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 `::` 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 `::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. 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, `::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`. diff --git a/crates/testkit/src/guards.rs b/crates/testkit/src/guards.rs index ea2910f640..11709c05ab 100644 --- a/crates/testkit/src/guards.rs +++ b/crates/testkit/src/guards.rs @@ -114,8 +114,19 @@ impl AsFileSource for &(&str, String) { /// read as far as this depth, so hostile nesting cannot exhaust the stack. const MAX_NESTING: usize = 64; +/// The most segments of a `use` path that [`use_leaves`] keeps. The guards compare paths of at most +/// three segments, so a leaf with a longer path is left out, and a long prefix shared by many leaves +/// is not copied into each of them. +const MAX_USE_PATH: usize = 8; + +/// The longest segment, in bytes, of a `use` path that [`use_leaves`] keeps. The longest segment the +/// guards compare is `PredefinedMenuItem`, so a leaf with a longer segment is left out, and a long name +/// shared by many leaves is not copied into each of them. +const MAX_USE_SEGMENT: usize = 32; + /// The kind of a Rust token. Comments are dropped; string, character and number literals keep no text -/// except string contents, which `cfg` predicates compare. +/// except the decoded contents of strings, which `cfg` predicates compare. A string with an escape +/// that is not valid is `Other`. #[derive(Debug, Clone, PartialEq, Eq)] enum Kind { Ident(String), @@ -214,14 +225,14 @@ fn lex_rust(code: &str) -> Vec { while j < len && is_ident_continue(chars[j]) { j += 1; } - tokens.push(Token { kind: Kind::Ident(chars[name_start..j].iter().collect()), line: token_line }); + tokens.push(Token { kind: Kind::Ident(raw_identifier(&chars[name_start..j])), line: token_line }); i = j; continue; } } if matches!(word.as_str(), "b" | "c") && at(i) == Some('"') { - let (end, text) = scan_string(&chars, i + 1, &mut line); - tokens.push(Token { kind: Kind::Str(text), line: token_line }); + let (end, kind) = scan_string(&chars, i + 1, &mut line); + tokens.push(Token { kind, line: token_line }); i = end; continue; } @@ -241,8 +252,8 @@ fn lex_rust(code: &str) -> Vec { tokens.push(Token { kind: Kind::Other, line }); } else if c == '"' { let token_line = line; - let (end, text) = scan_string(&chars, i + 1, &mut line); - tokens.push(Token { kind: Kind::Str(text), line: token_line }); + let (end, kind) = scan_string(&chars, i + 1, &mut line); + tokens.push(Token { kind, line: token_line }); i = end; } else if c == '\'' { if let Some(end) = char_literal_end(&chars, i) { @@ -263,27 +274,101 @@ fn lex_rust(code: &str) -> Vec { 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`. +fn raw_identifier(name: &[char]) -> String { + let name: String = name.iter().collect(); + if matches!(name.as_str(), "true" | "false") { format!("r#{name}") } else { name } +} + /// Read a normal string body starting after its opening quote. Returns the index after the closing -/// quote and the body as written, escapes included. -fn scan_string(chars: &[char], mut i: usize, line: &mut usize) -> (usize, String) { - let start = i; +/// quote and the token for the body: `Str` with its escapes decoded, or `Other` when an escape is not +/// valid in a string. +fn scan_string(chars: &[char], mut i: usize, line: &mut usize) -> (usize, Kind) { + let mut text = Some(String::new()); while i < chars.len() { match chars[i] { '\\' => { - if chars.get(i + 1) == Some(&'\n') { + let (next, decoded) = string_escape(chars, i + 1, line); + match decoded { + Ok(Some(c)) => text.iter_mut().for_each(|t| t.push(c)), + Ok(None) => {} + Err(()) => text = None, + } + i = next; + } + '"' => return (i + 1, text.map_or(Kind::Other, Kind::Str)), + c => { + if c == '\n' { *line += 1; } - i += 2; - } - '"' => return (i + 1, chars[start..i].iter().collect()), - '\n' => { - *line += 1; + text.iter_mut().for_each(|t| t.push(c)); i += 1; } - _ => i += 1, } } - (chars.len(), chars[start.min(chars.len())..].iter().collect()) + (chars.len(), text.map_or(Kind::Other, Kind::Str)) +} + +/// Decode the string escape whose `\` is right before `chars[i]` +/// (). Returns the index after the +/// escape and the character it stands for, `None` for a line continuation, or an error when it is not +/// a valid escape. +fn string_escape(chars: &[char], i: usize, line: &mut usize) -> (usize, Result, ()>) { + let hex = |k: usize| chars.get(k).and_then(|c| c.to_digit(16)); + match chars.get(i) { + Some('n') => (i + 1, Ok(Some('\n'))), + Some('r') => (i + 1, Ok(Some('\r'))), + Some('t') => (i + 1, Ok(Some('\t'))), + Some('0') => (i + 1, Ok(Some('\0'))), + Some(&c @ ('\\' | '\'' | '"')) => (i + 1, Ok(Some(c))), + Some('x') => match (hex(i + 1), hex(i + 2)) { + (Some(high), Some(low)) if high < 8 => (i + 3, Ok(char::from_u32(high * 16 + low))), + _ => (i + 1, Err(())), + }, + Some('u') if chars.get(i + 1) == Some(&'{') => { + // At most six hex digits, with underscores, before the closing brace. + let mut value = 0u32; + let mut digits = 0; + let mut j = i + 2; + while let Some(&c) = chars.get(j) { + if c == '}' { + break; + } + if c != '_' { + match c.to_digit(16) { + Some(d) if digits < 6 => { + value = value * 16 + d; + digits += 1; + } + _ => return (j, Err(())), + } + } + j += 1; + } + match (chars.get(j), char::from_u32(value)) { + (Some('}'), Some(c)) if digits > 0 && chars.get(i + 2) != Some(&'_') => (j + 1, Ok(Some(c))), + _ => (j.min(chars.len()), Err(())), + } + } + Some('\n') => { + // A line continuation skips the line break and the whitespace after it. + let mut j = i; + while let Some(&c) = chars.get(j).filter(|c| matches!(c, ' ' | '\t' | '\n' | '\r')) { + if c == '\n' { + *line += 1; + } + j += 1; + } + (j, Ok(None)) + } + Some('\r') if chars.get(i + 1) == Some(&'\n') => { + let (j, _) = string_escape(chars, i + 1, line); + (j, Ok(None)) + } + Some(_) => (i + 1, Err(())), + None => (i, Err(())), + } } /// Read a raw string body starting after its opening quote; it ends at a quote followed by `hashes` `#`. @@ -344,6 +429,29 @@ fn then_path(toks: &[Token], i: usize, name: impl Fn(&str) -> bool) -> bool { && toks.get(i + 2).is_some_and(|t| matches!(&t.kind, Kind::Ident(s) if name(s))) } +/// Whether the path that ends at `toks[i]` starts right after the `<` of a qualified path, as in +/// `::quit`, rather than after the `<` of generic arguments (`Vec::new`, +/// `f::`). +fn opens_qualified_path(toks: &[Token], i: usize) -> bool { + let mut start = i; + while start >= 2 && toks[start - 1].is_punct(':') && toks[start - 2].is_punct(':') { + if start >= 3 && matches!(toks[start - 3].kind, Kind::Ident(_)) { + start -= 3; + } else { + start -= 2; + break; + } + } + start >= 1 + && toks[start - 1].is_punct('<') + && match start.checked_sub(2).map(|j| &toks[j].kind) { + None => true, + Some(Kind::Ident(s)) => KEYWORDS.contains(&s.as_str()), + Some(Kind::Punct(c)) => !matches!(*c, ':' | '>'), + Some(_) => false, + } +} + /// One name a `use` declaration brings into scope. #[derive(Debug)] struct UseLeaf { @@ -361,7 +469,8 @@ fn use_leaves(toks: &[Token]) -> Vec { let mut leaves = Vec::new(); let mut i = 0; while i < toks.len() { - if toks[i].is_ident("use") && !continues_a_path(toks, i) { + // `use<...>` is a precise capturing bound on `impl Trait`, not a `use` declaration. + if toks[i].is_ident("use") && !continues_a_path(toks, i) && !toks.get(i + 1).is_some_and(|t| t.is_punct('<')) { let start = i; let end = (i + 1..toks.len()).find(|&j| toks[j].is_punct(';')).unwrap_or(toks.len()); let mut pos = i + 1; @@ -391,24 +500,30 @@ fn parse_use_tree(toks: &[Token], pos: &mut usize, prefix: &mut Vec, sta *pos += 2; continue; } - let mut path = prefix.clone(); - if name != "self" { - path.push(name.clone()); - } - let mut bound = path.last().cloned(); - if toks.get(*pos).is_some_and(|t| t.is_ident("as")) - && let Some(Kind::Ident(alias)) = toks.get(*pos + 1).map(|t| &t.kind) - { - bound = Some(alias.clone()); - *pos += 2; - } - if let Some(bound) = bound.filter(|b| b != "_") { - out.push(UseLeaf { path, name: Some(bound), line, start }); + let length = prefix.len() + usize::from(name != "self"); + let alias = match (toks.get(*pos), toks.get(*pos + 1).map(|t| &t.kind)) { + (Some(t), Some(Kind::Ident(alias))) if t.is_ident("as") => { + *pos += 2; + Some(alias) + } + _ => None, + }; + if length <= MAX_USE_PATH && short_segments(prefix) && name.len() <= MAX_USE_SEGMENT { + let mut path = prefix.clone(); + if name != "self" { + path.push(name.clone()); + } + let bound = alias.cloned().or_else(|| path.last().cloned()); + if let Some(bound) = bound.filter(|b| b != "_") { + out.push(UseLeaf { path, name: Some(bound), line, start }); + } } break; } Kind::Punct('*') => { - out.push(UseLeaf { path: prefix.clone(), name: None, line, start }); + if prefix.len() <= MAX_USE_PATH && short_segments(prefix) { + out.push(UseLeaf { path: prefix.clone(), name: None, line, start }); + } *pos += 1; break; } @@ -435,6 +550,11 @@ fn parse_use_tree(toks: &[Token], pos: &mut usize, prefix: &mut Vec, sta prefix.truncate(base); } +/// Whether every segment of `path` is at most [`MAX_USE_SEGMENT`] bytes long. +fn short_segments(path: &[String]) -> bool { + path.iter().all(|segment| segment.len() <= MAX_USE_SEGMENT) +} + /// A value of a `cfg` predicate on `wasm32-unknown-unknown`, where the value of a feature or of /// `test` is not known from the source. #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -482,6 +602,11 @@ fn eval_cfg(toks: &[Token], pos: &mut usize, depth: usize) -> Tri { return Tri::from_bool(value == expected); } if toks.get(*pos).is_some_and(|t| t.is_punct('(')) { + if depth >= MAX_NESTING { + // Too deep to read: the predicate is skipped as a whole, and its value is not known. + *pos = matching_close(toks, *pos).saturating_add(1); + return Tri::Unknown; + } *pos += 1; let mut values = Vec::new(); while let Some(t) = toks.get(*pos) { @@ -489,7 +614,7 @@ fn eval_cfg(toks: &[Token], pos: &mut usize, depth: usize) -> Tri { *pos += 1; break; } - if t.is_punct(',') || depth >= MAX_NESTING { + if t.is_punct(',') { *pos += 1; continue; } @@ -511,7 +636,8 @@ fn eval_cfg(toks: &[Token], pos: &mut usize, depth: usize) -> Tri { }; } match name.as_str() { - "unix" | "windows" => Tri::False, + "unix" | "windows" | "false" => Tri::False, + "true" => Tri::True, _ => Tri::Unknown, } } @@ -587,6 +713,16 @@ fn item_end(toks: &[Token], start: usize, inner: bool) -> usize { j += 2; continue; } + // The `:` after a field's or a static's name starts its type, where `fn` is a function pointer + // type rather than an item. The `:` of a path (`::`) and the one after a loop label are not. + Kind::Punct(':') + if at_top + && !block_item + && !toks.get(j + 1).is_some_and(|t| t.is_punct(':')) + && j.checked_sub(1).is_none_or(|k| !toks[k].is_punct(':') && toks[k].kind != Kind::Other) => + { + head = false; + } Kind::Punct('=' | '+' | '-' | '*' | '/' | '%' | '^' | '|' | '&' | '<' | '>' | '!') if at_top && !block_item => head = false, Kind::Punct('(' | '[' | '{') => depth += 1, Kind::Punct(c @ (')' | ']' | '}')) => { @@ -828,19 +964,20 @@ fn join_path(parent: &str, child: &str) -> String { /// The paths, normalized, where the module `decl` declared in the file at `parent` (normalized) can be. /// -/// The modules of `lib.rs`, `main.rs` and `mod.rs` are in the file's folder, and those of any other file -/// are in the folder named after its stem. Each inline module around the declaration adds a folder named +/// The modules of `lib.rs`, `main.rs` and `mod.rs`, and with `path_loaded`, of a file that a `#[path]` +/// attribute names, are in the file's folder, and those of any other file are in the folder named after +/// its stem. Each inline module around the declaration adds a folder named /// after it, or with a `path` attribute, moves to that path relative to the current folder (without the /// stem folder). The module is then `.rs` or `/mod.rs` there, or with a `path` attribute, that /// path relative to the current folder, again without the stem folder. -fn module_files(parent: &str, decl: &ModDecl) -> Vec { +fn module_files(parent: &str, decl: &ModDecl, path_loaded: bool) -> Vec { let (dir, file) = match parent.rsplit_once('/') { Some(("", file)) => ("/", file), Some(split) => split, None => ("", parent), }; let mut folder = dir.to_string(); - let mut stem = (!matches!(file, "lib.rs" | "main.rs" | "mod.rs")).then(|| file.strip_suffix(".rs").unwrap_or(file)); + let mut stem = (!path_loaded && !matches!(file, "lib.rs" | "main.rs" | "mod.rs")).then(|| file.strip_suffix(".rs").unwrap_or(file)); for inline in &decl.inline { if let Some(attr) = &inline.path_attribute { folder = join_path(&folder, attr); @@ -870,67 +1007,88 @@ fn native_only_files(paths: &[String], decls: &[Vec]) -> Vec { for (i, path) in paths.iter().enumerate() { index.entry(path.as_str()).or_default().push(i); } - // The files each declaration names, in the order of `decls`. - let children: Vec)>> = decls - .iter() - .enumerate() - .map(|(parent, file_decls)| { - file_decls - .iter() - .map(|decl| { - let files = - module_files(&paths[parent], decl).iter().flat_map(|c| index.get(c.as_str()).into_iter().flatten().copied()).collect(); - (decl.native, files) - }) - .collect() + // rustc reads a file that a `#[path]` attribute names as if it were a `mod.rs`, so the modules it + // declares are in its own folder rather than its stem folder. Each file is therefore two nodes: node + // `2 * file` for the file loaded by a plain `mod name;` (or as a crate root), and node `2 * file + 1` + // for the file loaded through a `#[path]` attribute. Each node lists the nodes its declarations name, + // with whether the declaration is in a native-only item. + let edges: Vec> = (0..paths.len() * 2) + .map(|node| { + let (parent, path_loaded) = (node / 2, node % 2 == 1); + let mut targets = Vec::new(); + for decl in &decls[parent] { + let by_path = usize::from(decl.module.path_attribute.is_some()); + for candidate in module_files(&paths[parent], decl, path_loaded) { + for &j in index.get(candidate.as_str()).into_iter().flatten() { + targets.push((decl.native, 2 * j + by_path)); + } + } + } + targets }) .collect(); + // The nodes that are loaded: a file that no loaded node names is a crate root, loaded plainly, and a + // node is loaded when a loaded node names it. Every file starts out loaded plainly, and the set is + // narrowed until it stops changing, or after `MAX_MODULE_ROUNDS` rounds. + let mut loaded: Vec = (0..paths.len() * 2).map(|node| node % 2 == 0).collect(); + let mut named = vec![false; paths.len()]; + for _ in 0..MAX_MODULE_ROUNDS { + let mut reached = vec![false; paths.len() * 2]; + for (node, targets) in edges.iter().enumerate() { + if loaded[node] { + for &(_, target) in targets { + reached[target] = true; + } + } + } + named = (0..paths.len()).map(|j| reached[2 * j] || reached[2 * j + 1]).collect(); + let next: Vec = (0..paths.len() * 2).map(|node| reached[node] || (node % 2 == 0 && !named[node / 2])).collect(); + if next == loaded { + break; + } + loaded = next; + } + // Files the web build compiles: crate roots, and every file a declaration outside a native-only item // of such a file names. - let mut named = vec![false; paths.len()]; - for (_, files) in children.iter().flatten() { - for &j in files { - named[j] = true; - } - } - let mut web = vec![false; paths.len()]; - let mut queue: Vec = (0..paths.len()).filter(|&j| !named[j]).collect(); - for &j in &queue { - web[j] = true; + let mut web = vec![false; paths.len() * 2]; + let mut queue: Vec = (0..paths.len()).filter(|&j| !named[j]).map(|j| 2 * j).collect(); + for &node in &queue { + web[node] = true; } while let Some(parent) = queue.pop() { - for (_, files) in children[parent].iter().filter(|(is_native, _)| !is_native) { - for &j in files { - if !web[j] { - web[j] = true; - queue.push(j); - } + for &(_, target) in edges[parent].iter().filter(|(is_native, _)| !is_native) { + if !web[target] { + web[target] = true; + queue.push(target); } } } - // Files a native-only declaration names, and their descendants. - let mut native = vec![false; paths.len()]; - let mut mark = |files: &[usize], queue: &mut Vec| { - for &j in files { - if !native[j] { - native[j] = true; - queue.push(j); - } + // Files a native-only declaration of a loaded node names, and their descendants. + let mut native = vec![false; paths.len() * 2]; + let starts = edges.iter().enumerate().filter(|&(node, _)| loaded[node]).flat_map(|(_, targets)| targets.iter()); + for &(_, target) in starts.filter(|(is_native, _)| *is_native) { + if !native[target] { + native[target] = true; + queue.push(target); } - }; - for (_, files) in children.iter().flatten().filter(|(is_native, _)| *is_native) { - mark(files, &mut queue); } while let Some(parent) = queue.pop() { - for (_, files) in &children[parent] { - mark(files, &mut queue); + for &(_, target) in &edges[parent] { + if !native[target] { + native[target] = true; + queue.push(target); + } } } - native.iter().zip(&web).map(|(&n, &w)| n && !w).collect() + (0..paths.len()).map(|j| (native[2 * j] || native[2 * j + 1]) && !web[2 * j] && !web[2 * j + 1]).collect() } +/// The most rounds [`native_only_files`] spends narrowing the set of loaded files. +const MAX_MODULE_ROUNDS: usize = 16; + /// Add one finding for each line in `lines`, in line order, with the trimmed text of that line. fn report(findings: &mut Vec, path: &str, content: &str, lines: &BTreeSet) { if lines.is_empty() { @@ -950,7 +1108,8 @@ fn report(findings: &mut Vec, path: &str, content: &str, lines: &BTreeS /// Applications should route Quit through custom menu items or interceptors connected to `craft-quit`. /// /// The guard reads Rust tokens, so comments, strings and character literals are ignored, and whitespace -/// or line breaks around `::` do not hide a call. It also follows a `use` that renames muda's type +/// or line breaks around `::` do not hide a call. A qualified path such as `::quit` +/// is reported too. 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. @@ -974,7 +1133,10 @@ where 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)); - if named && then_path(&toks, i + 1, |s| s == "quit" || s == "Quit") { + let quit = |at: usize| then_path(&toks, at, |s| s == "quit" || s == "Quit"); + // `::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); + if named && (quit(i + 1) || qualified()) { lines.insert(tok.line); } } @@ -1003,13 +1165,14 @@ where /// (for example `#[cfg(not(target_arch = "wasm32"))]`, `#[cfg(all(unix, ...))]`, `#[cfg(target_os = "macos")]`, /// or `#![cfg(...)]` for the rest of a module). Such an attribute covers only its item: code before the /// attribute or after the item on the same line is checked. A statement whose value holds a block, such as -/// `let n = match x { ... } as u64 + ...;`, is covered up to its `;`. A predicate that depends on a feature -/// or on `test` is not known from the source, so the item is checked. +/// `let n = match x { ... } as u64 + ...;`, is covered up to its `;`. `cfg(false)` is false and `cfg(true)` +/// is true. A predicate that depends on a feature or on `test`, or that is nested more than 64 levels deep, +/// is not known from the source, so the item is checked. Escapes in a predicate's string values are decoded. /// * **Module files**: a `mod name;` inside such an item makes the module's file native-only, and so are the /// files of the modules declared in it, when they are among `files`, unless a chain of declarations outside /// such items also reaches the file from a crate root (a file that no declaration names). The module's file is `name.rs` or -/// `name/mod.rs` next to `lib.rs`, `main.rs` or `mod.rs`, and in the folder named after any other file's -/// stem, below the folders of enclosing inline modules; a `#[path = "..."]` attribute on the declaration +/// `name/mod.rs` next to `lib.rs`, `main.rs`, `mod.rs` or a file that a `#[path]` attribute names, and in +/// the folder named after any other file's stem, below the folders of enclosing inline modules; a `#[path = "..."]` attribute on the declaration /// or on an enclosing inline module is followed. Paths are compared as text with `\` read as `/`, so the files must be named the same way /// (for example all from one `rust_sources` call), and a crate root other than `lib.rs` or `main.rs` /// (such as `src/bin/tool.rs`) is read as an ordinary module file. A declaration inside more than 64 inline @@ -1084,7 +1247,11 @@ where findings } -/// Replace WGSL comments (`//` and nested `/* ... */`) with spaces, keeping line breaks. +/// Replace WGSL comments (`//` and nested `/* ... */`) with spaces, and write each WGSL line break as +/// `\n`: line feed, vertical tab, form feed, carriage return, carriage return and line feed as one +/// break, next line (U+0085), line separator (U+2028) and paragraph separator (U+2029) +/// (). A line comment ends at any of them, and `str::lines` +/// then counts lines the way WGSL does. fn mask_wgsl_comments(code: &str) -> String { let chars: Vec = code.chars().collect(); let len = chars.len(); @@ -1095,10 +1262,15 @@ fn mask_wgsl_comments(code: &str) -> String { while i < len { let c = chars[i]; let next = chars.get(i + 1).copied(); - if c == '\n' { + let line_break = match c { + '\r' if next == Some('\n') => 2, + '\n' | '\u{000B}' | '\u{000C}' | '\r' | '\u{0085}' | '\u{2028}' | '\u{2029}' => 1, + _ => 0, + }; + if line_break > 0 { in_line = false; out.push('\n'); - i += 1; + i += line_break; } else if in_line { out.push(' '); i += 1; @@ -1217,7 +1389,9 @@ fn scan_wgsl_hex(code: &[u8], start: usize) -> (usize, usize, bool) { /// * **Which literals**: decimal floats (with a `.`, an exponent or an `f`/`h` suffix) and hexadecimal floats /// (`0x` with a `.` or a `p` exponent). Integer literals (`123`, `123u`, `0xFFi`, `0x1f`) are not floats and /// are not reported. A `-` in front is not part of the literal, so `-1e39` is reported as `1e39`. -/// * **Comments**: Comments (`//` and nested `/* ... */`) are masked out prior to scanning. +/// * **Comments**: Comments (`//` and nested `/* ... */`) are masked out prior to scanning. A `//` comment +/// ends at any WGSL line break, a lone carriage return included, and finding lines count every one of them. +/// * **Identifiers**: digits inside an identifier, `π1e39` included, are not a literal. pub fn wgsl_float_literals(wgsl: &str) -> Vec { wgsl_float_literals_in([("", wgsl)]) } @@ -1239,7 +1413,14 @@ where let mut i = 0; while i < code.len() { let digit_or_dot = code[i].is_ascii_digit() || (code[i] == b'.' && code.get(i + 1).is_some_and(u8::is_ascii_digit)); - let word_before = i > 0 && (code[i - 1].is_ascii_alphanumeric() || code[i - 1] == b'_' || code[i - 1] == b'.'); + // Outside comments, a character that is not ASCII and not blankspace (U+200E, U+200F) is part of an + // identifier, as in `π1e39`. + let word_before = digit_or_dot + && i > 0 + && (code[i - 1].is_ascii_alphanumeric() + || code[i - 1] == b'_' + || code[i - 1] == b'.' + || (!code[i - 1].is_ascii() && !line[..i].ends_with(['\u{200E}', '\u{200F}']))); if !digit_or_dot || word_before { i += 1; continue; @@ -1426,3 +1607,25 @@ pub fn rust_sources_with_limits(dir: impl AsRef, limits: SourceLimits) -> files.sort_by(|a, b| a.0.cmp(&b.0)); Ok(files) } + +#[cfg(test)] +mod tests { + use super::{MAX_USE_PATH, MAX_USE_SEGMENT, lex_rust, use_leaves}; + + #[test] + fn use_leaves_keep_no_path_longer_than_the_limit() { + let source = format!("use {}{{x, y::z, *}};\nuse std::time::{{Instant, self as t}};\n", "a::".repeat(MAX_USE_PATH)); + let paths: Vec> = use_leaves(&lex_rust(&source)).into_iter().map(|leaf| leaf.path).collect(); + assert_eq!(paths, vec![vec!["a"; MAX_USE_PATH], vec!["std", "time", "Instant"], vec!["std", "time"]]); + } + + #[test] + fn use_leaves_keep_no_segment_longer_than_the_limit() { + let long = "n".repeat(MAX_USE_SEGMENT + 1); + let fits = "n".repeat(MAX_USE_SEGMENT); + let source = format!("use {long}::{{self, x, *}};\nuse a::{long};\nuse {fits}::{{self as b, *}};\n"); + let leaves = use_leaves(&lex_rust(&source)); + let paths: Vec<(Vec, Option)> = leaves.into_iter().map(|leaf| (leaf.path, leaf.name)).collect(); + assert_eq!(paths, vec![(vec![fits.clone()], Some("b".to_string())), (vec![fits], None)]); + } +} diff --git a/crates/testkit/tests/guards.rs b/crates/testkit/tests/guards.rs index d4cb7ae111..0065b1b5d3 100644 --- a/crates/testkit/tests/guards.rs +++ b/crates/testkit/tests/guards.rs @@ -412,6 +412,21 @@ fn menu() { assert!(predefined_quit([("src/menu.rs", other_crate)]).is_empty()); } +#[test] +fn predefined_quit_reports_a_qualified_path() { + let source = r#" +use muda::PredefinedMenuItem as Item; +fn menu() { + let a = ::quit(None); + let b = < PredefinedMenuItem >::quit(None); + let c = ::quit(None); + let d = Vec::::quit(None); + let e = Wrapper::quit(None); +} +"#; + assert_eq!(lines(&predefined_quit([("src/menu.rs", source)])), vec![4, 5, 6]); +} + #[test] fn std_instant_ignores_an_alias_that_only_a_native_cfg_imports() { let source = r#" @@ -473,6 +488,76 @@ use std::time::Instant as MacInstant; assert_eq!(lines(&std_instant([("src/clock.rs", source)])), vec![4, 13, 16, 19]); } +#[test] +fn std_instant_decodes_escapes_in_cfg_values() { + let source = r#" +#[cfg(target_arch = "\x77asm32")] +fn web() { let t = std::time::Instant::now(); } +#[cfg(target_arch = "w\u{61}sm32")] +fn web_two() { let t = std::time::Instant::now(); } +#[cfg(target_arch = r"\x77asm32")] +fn native() { let t = std::time::Instant::now(); } +#[cfg(not(target_arch = "\q"))] +fn unknown() { let t = std::time::Instant::now(); } +#[cfg(target_os = "lin\ + ux")] +fn native_two() { let t = std::time::Instant::now(); } +fn after() { let t = std::time::Instant::now(); } +"#; + assert_eq!(lines(&std_instant([("src/clock.rs", source)])), vec![3, 5, 9, 13]); +} + +#[test] +fn std_instant_reads_cfg_true_and_false() { + let source = r#" +#[cfg(false)] +fn disabled() { let t = std::time::Instant::now(); } +#[cfg(true)] +fn enabled() { let t = std::time::Instant::now(); } +#[cfg(not(true))] +fn never() { let t = std::time::Instant::now(); } +#[cfg(r#false)] +fn named_option() { let t = std::time::Instant::now(); } +#[cfg(not(r#true))] +fn other_option() { let t = std::time::Instant::now(); } +"#; + assert_eq!(lines(&std_instant([("src/clock.rs", source)])), vec![5, 9, 11]); +} + +#[test] +fn std_instant_checks_an_item_whose_cfg_is_nested_past_the_limit() { + let source = format!( + "#[cfg({}target_arch = \"wasm32\"{})]\nfn web() {{ let t = std::time::Instant::now(); }}\n#[cfg({}unix{})]\nfn native() {{ let t = std::time::Instant::now(); }}\n", + "any(".repeat(65), + ")".repeat(65), + "all(".repeat(10), + ")".repeat(10), + ); + assert_eq!(lines(&std_instant([("src/clock.rs", source.as_str())])), vec![2]); +} + +#[test] +fn std_instant_checks_the_fields_after_a_native_cfg_function_pointer_field() { + let source = r#" +struct S { + #[cfg(unix)] + callback: fn(), + clock: std::time::Instant, + #[cfg(unix)] + native: fn() -> std::time::Instant, + #[cfg(unix)] + pub(crate) boxed: Box, + other: std::time::Instant, +} +fn run() { + #[cfg(unix)] + 'outer: loop { let _a = std::time::Instant::now(); } + let t = std::time::Instant::now(); +} +"#; + assert_eq!(lines(&std_instant([("src/clock.rs", source)])), vec![5, 10, 15]); +} + #[test] fn std_instant_ends_a_native_cfg_block_statement_at_its_closing_brace() { let source = r#" @@ -720,6 +805,12 @@ use std::time::{ assert_eq!(findings[0].text, "Instant"); } +#[test] +fn std_instant_reads_a_use_after_a_precise_capturing_bound() { + let source = "fn clock() -> impl Fn() + use<> {\n use std::{time::Instant};\n || { let _ = Instant::now(); }\n}\n"; + assert_eq!(lines(&std_instant([("src/clock.rs", source)])), vec![2]); +} + #[test] fn std_instant_does_not_count_brace_character_literals_as_braces() { let source = r#" @@ -755,6 +846,23 @@ fn deeply_nested_use_groups_and_cfg_predicates_do_not_exhaust_the_stack() { assert_eq!(lines(&std_instant([("src/shallow.rs", shallow)])), vec![1]); } +#[test] +fn a_long_use_path_shared_by_many_names_is_read_without_copying_it_to_each() { + // 10,000 path segments shared by 10,000 names, followed by a `use` the guard reports. + let names: Vec = (0..10_000).map(|n| format!("x{n}")).collect(); + let source = format!("use {}{{{}}};\nuse std::time::Instant;\n", "a::".repeat(10_000), names.join(", ")); + assert_eq!(lines(&std_instant([("src/wide.rs", source.as_str())])), vec![2]); + assert!(predefined_quit([("src/wide.rs", source.as_str())]).is_empty()); +} + +#[test] +fn a_long_name_shared_by_many_use_leaves_is_read_without_copying_it_to_each() { + // A 40,000-byte name shared by 10,000 leaves, followed by a `use` the guard reports. + let source = format!("use {}::{{{}}};\nuse std::time::Instant;\n", "n".repeat(40_000), ["self"; 10_000].join(", ")); + assert_eq!(lines(&std_instant([("src/wide.rs", source.as_str())])), vec![2]); + assert!(predefined_quit([("src/wide.rs", source.as_str())]).is_empty()); +} + fn finding_paths(findings: &[Finding]) -> Vec<&str> { findings.iter().map(|f| f.path.as_str()).collect() } @@ -887,6 +995,39 @@ mod platform { assert_eq!(finding_paths(&std_instant(files)), vec!["src/a/native.rs", "src/a/native/clock.rs"]); } +#[test] +fn std_instant_finds_the_modules_of_a_path_attribute_file_next_to_it() { + let lib = r#" +#[cfg(not(target_arch = "wasm32"))] +#[path = "platform/native.rs"] +mod native; +"#; + let clock = "use std::time::Instant;\n"; + let files = [("src/lib.rs", lib), ("src/platform/native.rs", "mod clock;\n"), ("src/platform/clock.rs", clock), ("src/web.rs", clock)]; + assert_eq!(finding_paths(&std_instant(files)), vec!["src/web.rs"]); +} + +#[test] +fn std_instant_resolves_a_file_loaded_both_plainly_and_by_path_attribute_once_for_each() { + // `platform.rs` is a web module, and a native-only `#[path]` declaration loads it again. Its + // `mod clock;` is `src/platform/clock.rs` for the first and `src/clock.rs` for the second. + let lib = "mod platform;\n#[cfg(unix)]\n#[path = \"platform.rs\"]\nmod native;\n"; + let clock = "use std::time::Instant;\n"; + let files = [("src/lib.rs", lib), ("src/platform.rs", "mod clock;\n"), ("src/platform/clock.rs", clock), ("src/clock.rs", clock)]; + assert_eq!(finding_paths(&std_instant(files)), vec!["src/platform/clock.rs"]); +} + +#[test] +fn std_instant_checks_a_file_that_a_path_attribute_module_names_for_the_web_build() { + // The web module `entry.rs`, loaded through `#[path]`, names `src/clock.rs`, which a native-only + // module also names through `#[path]`. + let lib = "#[path = \"entry.rs\"]\nmod web;\n#[cfg(unix)]\nmod native;\n"; + let clock = "use std::time::Instant;\n"; + let files = + [("src/lib.rs", lib), ("src/entry.rs", "mod clock;\n"), ("src/native.rs", "#[path = \"clock.rs\"]\nmod clock;\n"), ("src/clock.rs", clock)]; + assert_eq!(finding_paths(&std_instant(files)), vec!["src/clock.rs"]); +} + #[test] fn std_instant_checks_module_files_declared_deeper_than_its_nesting_limit() { let lib = format!("{}#[cfg(unix)]\nmod deep;\n{}", "mod m {\n".repeat(70), "}\n".repeat(70)); @@ -961,6 +1102,22 @@ fn wgsl_half_floats_use_the_f16_range() { assert_eq!(findings[0].text, "70000.0"); } +#[test] +fn wgsl_line_comments_end_and_lines_count_at_every_line_break() { + let shader = "// note\rconst A: f32 = 4e38;\r\nconst B: f32 = 5e38;\n// x\u{2028}const C: f32 = 6e38;\u{2029}const D: f32 = 7e38;\u{000B}// y\u{0085}const E: f32 = 8e38;\u{000C}const F: f32 = 9e38;"; + let findings = wgsl_float_literals(shader); + assert_eq!(lines(&findings), vec![2, 3, 5, 6, 8, 9]); + assert_eq!(findings[0].text, "4e38"); +} + +#[test] +fn wgsl_digits_inside_unicode_identifiers_are_not_literals() { + let shader = "const π1e39 = 1.0;\nconst é2e40: f32 = 2.0;\nconst A: f32 =\u{200E}1e39;\n"; + let findings = wgsl_float_literals(shader); + assert_eq!(lines(&findings), vec![3]); + assert_eq!(findings[0].text, "1e39"); +} + #[cfg(not(target_arch = "wasm32"))] #[test] fn test_rust_sources_filtering() { From 811baa83c1fe844221d726672cd234fbf9f040eb Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 16:40:52 -0800 Subject: [PATCH 10/33] craft-testkit: test std_instant on items that follow a native cfg item on the same line A native-only item ends at its closing brace or `;`, so an item after it on the same line is checked, and a second native-only item there stays exempt. The tests cover `fn`, `impl`, `mod`, braced and tuple `struct` items, and a `use` with a native cfg after another gated item. --- crates/testkit/tests/guards.rs | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/crates/testkit/tests/guards.rs b/crates/testkit/tests/guards.rs index 0065b1b5d3..99e1054ade 100644 --- a/crates/testkit/tests/guards.rs +++ b/crates/testkit/tests/guards.rs @@ -677,6 +677,32 @@ fn std_instant_checks_code_before_and_after_a_native_cfg_item_on_the_same_line() assert_eq!(lines(&std_instant([("src/run.rs", source)])), vec![2, 4]); } +#[test] +fn std_instant_checks_an_item_after_a_native_cfg_item_on_the_same_line() { + let source = r#"#[cfg(target_os="linux")] fn native() {} fn web() { std::time::Instant::now(); } +"#; + assert_eq!(lines(&std_instant([("src/clock.rs", source)])), vec![1]); +} + +#[test] +fn std_instant_skips_gated_code_that_follows_a_native_cfg_item_on_the_same_line() { + let source = r#"#[cfg(target_os = "linux")] fn a() {} #[cfg(target_os = "macos")] fn b() { std::time::Instant::now(); } +#[cfg(unix)] fn c() {} #[cfg(windows)] use std::time::Instant as Native; +"#; + assert!(std_instant([("src/clock.rs", source)]).is_empty()); +} + +#[test] +fn std_instant_ends_native_cfg_impl_mod_and_struct_items_where_they_end_on_the_line() { + let source = r#"struct S; #[cfg(unix)] impl S { fn now() { std::time::Instant::now(); } } fn web() { std::time::Instant::now(); } +#[cfg(unix)] mod native { fn now() { std::time::Instant::now(); } } fn web_two() { std::time::Instant::now(); } +#[cfg(unix)] struct P { at: std::time::Instant } struct Q { at: std::time::Instant } +#[cfg(unix)] struct T(std::time::Instant); struct U(std::time::Instant); +#[cfg(unix)] impl S { fn a() {} } #[cfg(unix)] mod m { fn b() { std::time::Instant::now(); } } +"#; + assert_eq!(lines(&std_instant([("src/clock.rs", source)])), vec![1, 2, 3, 4]); +} + #[test] fn std_instant_reads_paths_split_over_lines_and_comments_with_crlf() { let source = "use std::time::\r\n Instant;\r\nfn run() {\r\n let t = std::time\r\n ::Instant::now();\r\n let u = std /* a */ :: time // b\r\n :: Instant::now();\r\n}\r\n"; From e1b53c6b44bbf8cc48375beccfcf9e62de71a228 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 17:01:49 -0800 Subject: [PATCH 11/33] 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. --- crates/testkit/README.md | 2 +- crates/testkit/src/guards.rs | 74 ++++++++++++++++++++++++---- crates/testkit/tests/guards.rs | 88 +++++++++++++++++++++++++++++++++- 3 files changed, 153 insertions(+), 11 deletions(-) diff --git a/crates/testkit/README.md b/crates/testkit/README.md index ff159f4da1..f65acf4134 100644 --- a/crates/testkit/README.md +++ b/crates/testkit/README.md @@ -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 `::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 `::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, `::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`. diff --git a/crates/testkit/src/guards.rs b/crates/testkit/src/guards.rs index 11709c05ab..592ac5ba1d 100644 --- a/crates/testkit/src/guards.rs +++ b/crates/testkit/src/guards.rs @@ -274,11 +274,13 @@ fn lex_rust(code: &str) -> Vec { 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 { 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 { && 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, 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 `::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"); // `::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); diff --git a/crates/testkit/tests/guards.rs b/crates/testkit/tests/guards.rs index 99e1054ade..e0bd03f5db 100644 --- a/crates/testkit/tests/guards.rs +++ b/crates/testkit/tests/guards.rs @@ -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 = ::quit(None); + let c = crate::menu::PredefinedMenuItem::Quit; + let d = other::muda::PredefinedMenuItem::quit(None); + let e = ::PredefinedMenuItem::quit(None); + let f = Other::quit(None); + let g = muda::PredefinedMenuItem::quit(None); + let h = ::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) -> 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#" From 7082905431b909fa2250fd4c8149f12ece01b0f3 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 17:35:10 -0800 Subject: [PATCH 12/33] craft-testkit: guards read paths through a long std::time alias and after arrows A use path whose first segment is longer than 32 bytes was dropped by the use-path copying limit. With `use std::time as ;`, std_instant missed `use ::{Instant as Clock};` and `use ::*;`. std_instant now reads the use declarations a second time with the names bound to std::time, and a path that starts with one of them is read as a path that starts with std::time. The alias is not copied into the leaves, so the limits still bound every other path. The `>` of `->` and `=>` was read as the end of a path, so both guards skipped an absolute path after it: `fn now() -> ::std::time::Instant` and `_ => ::muda::PredefinedMenuItem::quit(None)`. Those paths are now checked. --- crates/testkit/src/guards.rs | 46 +++++++++++++++++++-------- crates/testkit/tests/guards.rs | 58 ++++++++++++++++++++++++++++++++++ 2 files changed, 91 insertions(+), 13 deletions(-) diff --git a/crates/testkit/src/guards.rs b/crates/testkit/src/guards.rs index 592ac5ba1d..520741e2ed 100644 --- a/crates/testkit/src/guards.rs +++ b/crates/testkit/src/guards.rs @@ -413,13 +413,14 @@ const KEYWORDS: &[&str] = &[ ]; /// Whether `toks[i]` follows `::` that itself follows a path segment, as `time` does in `a::time`. +/// The `>` of `->` and `=>` ends no path, so `-> ::std::time` starts one. fn continues_a_path(toks: &[Token], i: usize) -> bool { i >= 3 && toks[i - 1].is_punct(':') && toks[i - 2].is_punct(':') && match &toks[i - 3].kind { Kind::Ident(s) => !KEYWORDS.contains(&s.as_str()), - Kind::Punct('>') => true, + Kind::Punct('>') => !(i >= 4 && (toks[i - 4].is_punct('-') || toks[i - 4].is_punct('='))), _ => false, } } @@ -466,8 +467,10 @@ struct UseLeaf { start: usize, } -/// Every name the `use` declarations of a file bring into scope. -fn use_leaves(toks: &[Token]) -> Vec { +/// Every name the `use` declarations of a file bring into scope. A path that starts with a name in +/// `time_aliases` is read as a path that starts with `std::time`, so the alias, at any length, is not +/// copied into the leaves and the limits do not drop them. +fn use_leaves(toks: &[Token], time_aliases: &BTreeSet) -> Vec { let mut leaves = Vec::new(); let mut i = 0; while i < toks.len() { @@ -477,7 +480,7 @@ fn use_leaves(toks: &[Token]) -> Vec { let end = (i + 1..toks.len()).find(|&j| toks[j].is_punct(';')).unwrap_or(toks.len()); let mut pos = i + 1; let mut prefix = Vec::new(); - parse_use_tree(&toks[..end], &mut pos, &mut prefix, start, &mut leaves, 0); + parse_use_tree(&toks[..end], &mut pos, &mut prefix, start, &mut leaves, time_aliases, 0); i = end; } else { i += 1; @@ -486,7 +489,15 @@ fn use_leaves(toks: &[Token]) -> Vec { leaves } -fn parse_use_tree(toks: &[Token], pos: &mut usize, prefix: &mut Vec, start: usize, out: &mut Vec, depth: usize) { +fn parse_use_tree( + toks: &[Token], + pos: &mut usize, + prefix: &mut Vec, + start: usize, + out: &mut Vec, + time_aliases: &BTreeSet, + depth: usize, +) { let base = prefix.len(); if toks.get(*pos).is_some_and(|t| t.is_punct(':')) && toks.get(*pos + 1).is_some_and(|t| t.is_punct(':')) { *pos += 2; @@ -498,7 +509,11 @@ fn parse_use_tree(toks: &[Token], pos: &mut usize, prefix: &mut Vec, sta Kind::Ident(name) => { *pos += 1; if toks.get(*pos).is_some_and(|t| t.is_punct(':')) && toks.get(*pos + 1).is_some_and(|t| t.is_punct(':')) { - prefix.push(name.clone()); + if prefix.is_empty() && time_aliases.contains(name) { + prefix.extend(["std".to_string(), "time".to_string()]); + } else { + prefix.push(name.clone()); + } *pos += 2; continue; } @@ -538,7 +553,7 @@ fn parse_use_tree(toks: &[Token], pos: &mut usize, prefix: &mut Vec, sta } let before = *pos; if !t.is_punct(',') && depth < MAX_NESTING { - parse_use_tree(toks, pos, prefix, start, out, depth + 1); + parse_use_tree(toks, pos, prefix, start, out, time_aliases, depth + 1); } if *pos == before { *pos += 1; @@ -1176,7 +1191,7 @@ where let path = file.path(); let content = file.content(); let toks = lex_rust(content); - let aliases: BTreeSet = use_leaves(&toks) + let aliases: BTreeSet = use_leaves(&toks, &BTreeSet::new()) .into_iter() .filter(|leaf| leaf.path == ["muda", "PredefinedMenuItem"]) .filter_map(|leaf| leaf.name) @@ -1213,7 +1228,8 @@ where /// * **What is reported**: the paths `std::time::Instant` and `::std::time::Instant`; `::Instant` where a /// `use` outside a native-only item binds `m` to `std::time` (`use std::time;`, `use std::time as t;`, /// `use std::time::{self as t}`); -/// and every `use` that imports `std::time::Instant` or `std::time::*`, under any name. Whitespace, comments +/// and every `use` that imports `std::time::Instant` or `std::time::*`, under any name, directly or through +/// such an `m` of any length (`use m::{Instant as Clock};`, `use m::*;`). Whitespace, comments /// and line breaks may separate the parts of a path. Each finding names the line where the path starts (in a /// `use` group, the line where the name's part of the group starts), once per line, in line order. /// * **What is skipped**: comments, string and character literals, other crates' `Instant` (`web_time::Instant`, @@ -1262,13 +1278,15 @@ where let content = file.content(); let toks = lex_rust(content); let skip = native_only(&toks); - let leaves = use_leaves(&toks); + let leaves = use_leaves(&toks, &BTreeSet::new()); let modules: BTreeSet = leaves .iter() .filter(|leaf| leaf.path == ["std", "time"] && !skip.get(leaf.start).copied().unwrap_or(false)) .filter_map(|leaf| leaf.name.clone()) .collect(); - let is_std_time = |path: &[String]| path == ["std", "time"] || (path.len() == 1 && modules.contains(&path[0])); + // Read again with the aliases of `std::time`, so a path through an alias starts with `std::time`. + let leaves = if modules.is_empty() { leaves } else { use_leaves(&toks, &modules) }; + let is_std_time = |path: &[String]| path == ["std", "time"]; let mut lines = BTreeSet::new(); for leaf in &leaves { @@ -1666,12 +1684,14 @@ pub fn rust_sources_with_limits(dir: impl AsRef, limits: SourceLimits) -> #[cfg(test)] mod tests { + use std::collections::BTreeSet; + use super::{MAX_USE_PATH, MAX_USE_SEGMENT, lex_rust, use_leaves}; #[test] fn use_leaves_keep_no_path_longer_than_the_limit() { let source = format!("use {}{{x, y::z, *}};\nuse std::time::{{Instant, self as t}};\n", "a::".repeat(MAX_USE_PATH)); - let paths: Vec> = use_leaves(&lex_rust(&source)).into_iter().map(|leaf| leaf.path).collect(); + let paths: Vec> = use_leaves(&lex_rust(&source), &BTreeSet::new()).into_iter().map(|leaf| leaf.path).collect(); assert_eq!(paths, vec![vec!["a"; MAX_USE_PATH], vec!["std", "time", "Instant"], vec!["std", "time"]]); } @@ -1680,7 +1700,7 @@ mod tests { let long = "n".repeat(MAX_USE_SEGMENT + 1); let fits = "n".repeat(MAX_USE_SEGMENT); let source = format!("use {long}::{{self, x, *}};\nuse a::{long};\nuse {fits}::{{self as b, *}};\n"); - let leaves = use_leaves(&lex_rust(&source)); + let leaves = use_leaves(&lex_rust(&source), &BTreeSet::new()); let paths: Vec<(Vec, Option)> = leaves.into_iter().map(|leaf| (leaf.path, leaf.name)).collect(); assert_eq!(paths, vec![(vec![fits.clone()], Some("b".to_string())), (vec![fits], None)]); } diff --git a/crates/testkit/tests/guards.rs b/crates/testkit/tests/guards.rs index e0bd03f5db..721e7a76a7 100644 --- a/crates/testkit/tests/guards.rs +++ b/crates/testkit/tests/guards.rs @@ -975,6 +975,64 @@ fn a_long_name_shared_by_many_use_leaves_is_read_without_copying_it_to_each() { assert!(predefined_quit([("src/wide.rs", source.as_str())]).is_empty()); } +#[test] +fn std_instant_reports_a_grouped_import_through_a_long_alias_of_std_time() { + let source = r#" +use std::time as standard_time_module_with_a_long_name; +use standard_time_module_with_a_long_name::{Instant as Clock}; +fn now() { + let _ = Clock::now(); +} +"#; + assert_eq!(lines(&std_instant([("src/clock.rs", source)])), vec![3]); +} + +#[test] +fn std_instant_reports_a_glob_through_a_long_alias_of_std_time() { + let source = r#" +use std::time as standard_time_module_with_a_long_name; +use standard_time_module_with_a_long_name::*; +use standard_time_module_with_a_long_name::{Duration, *}; +"#; + assert_eq!(lines(&std_instant([("src/clock.rs", source)])), vec![3, 4]); +} + +#[test] +fn std_instant_reports_a_path_of_nine_or_more_segments_that_starts_at_std_time() { + let source = r#" +use std::time as standard_time_module_with_a_long_name; +use std::time::Instant::a::b::c::d::e::f; +use standard_time_module_with_a_long_name::Instant::a::b::c::d::e::f::g; +"#; + assert_eq!(lines(&std_instant([("src/clock.rs", source)])), vec![3, 4]); +} + +#[test] +fn the_guards_read_an_absolute_path_after_a_return_arrow_or_a_match_arrow() { + let clock = r#" +fn now() -> ::std::time::Instant { + match 0 { _ => ::std::time::Instant::now() } +} +fn closure() { let _ = || -> ::std::time::Instant { todo() }; } +"#; + assert_eq!(lines(&std_instant([("src/clock.rs", clock)])), vec![2, 3, 5]); + + let menu = r#" +fn item() -> Item { + match 0 { _ => ::muda::PredefinedMenuItem::quit(None) } +} +"#; + assert_eq!(lines(&predefined_quit([("src/menu.rs", menu)])), vec![3]); +} + +#[test] +fn a_long_alias_of_std_time_shared_by_many_use_leaves_is_read_without_copying_it_to_each() { + // A 40,000-byte alias of `std::time` shared by 10,000 leaves. + let alias = "n".repeat(40_000); + let source = format!("use std::time as {alias};\nuse {alias}::{{{}}};\n", ["Instant"; 10_000].join(", ")); + assert_eq!(lines(&std_instant([("src/wide.rs", source.as_str())])), vec![2]); +} + fn finding_paths(findings: &[Finding]) -> Vec<&str> { findings.iter().map(|f| f.path.as_str()).collect() } From 97f970c58c9bd772c0aaa81b922461c418f18b08 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 17:56:14 -0800 Subject: [PATCH 13/33] craft-testkit: guards keep generic-bracket blocks in a native cfg item, read only a regular CACHEDIR.TAG and read names in their scope std_instant ended a native-only fn, impl, trait, struct, enum or union item at the closing brace of a block inside its angle brackets, such as the const generic default in `struct Native`, a `Foo<{ N }>` argument, a return type or a `where` clause. The rest of the item was then checked as web code. Blocks inside those angle brackets no longer end the item, and the `>` of `->` does not close a bracket. rust_sources opened a folder's CACHEDIR.TAG without checking its file type, so it followed a symbolic link and could block on a FIFO. It now reads the marker only when symlink_metadata reports a regular file; any other marker is not read and the folder is listed. predefined_quit reported a bare `PredefinedMenuItem::quit` when the file imported another crate's type under that name or defined its own, and applied a rename of muda's type (`use muda::PredefinedMenuItem as Item`) to the whole file. A name used on its own is now read in the innermost braces around it, within its module, that bind it: it is reported when they import or alias muda's type, and not when they only bind another type. An import or alias through `crate::`, `self::` or `super::`, a binding inside an item with a `cfg` attribute and an associated type in an `impl` or `trait` do not bind the name. std_instant applied an alias of `std::time` (`use std::time as clock`) to the whole file. A path or `use` through the alias is now reported only where the alias is in scope by the same rule, so another module's `use web_time as clock` is not read as `std::time`. --- crates/testkit/src/guards.rs | 297 +++++++++++++++++++++++++++++---- crates/testkit/tests/guards.rs | 173 +++++++++++++++++++ 2 files changed, 442 insertions(+), 28 deletions(-) diff --git a/crates/testkit/src/guards.rs b/crates/testkit/src/guards.rs index 520741e2ed..67bb79bb93 100644 --- a/crates/testkit/src/guards.rs +++ b/crates/testkit/src/guards.rs @@ -465,6 +465,8 @@ struct UseLeaf { line: usize, /// Index of the `use` keyword. start: usize, + /// Index of the alias of `std::time` that the path was read through, when [`use_leaves`] was given one. + alias: Option, } /// Every name the `use` declarations of a file bring into scope. A path that starts with a name in @@ -480,7 +482,7 @@ fn use_leaves(toks: &[Token], time_aliases: &BTreeSet) -> Vec { let end = (i + 1..toks.len()).find(|&j| toks[j].is_punct(';')).unwrap_or(toks.len()); let mut pos = i + 1; let mut prefix = Vec::new(); - parse_use_tree(&toks[..end], &mut pos, &mut prefix, start, &mut leaves, time_aliases, 0); + parse_use_tree(&toks[..end], &mut pos, &mut prefix, (start, None), &mut leaves, time_aliases, 0); i = end; } else { i += 1; @@ -493,7 +495,8 @@ fn parse_use_tree( toks: &[Token], pos: &mut usize, prefix: &mut Vec, - start: usize, + // The index of the `use` keyword, and of the alias of `std::time` that `prefix` was read through. + (start, mut via): (usize, Option), out: &mut Vec, time_aliases: &BTreeSet, depth: usize, @@ -511,6 +514,7 @@ fn parse_use_tree( if toks.get(*pos).is_some_and(|t| t.is_punct(':')) && toks.get(*pos + 1).is_some_and(|t| t.is_punct(':')) { if prefix.is_empty() && time_aliases.contains(name) { prefix.extend(["std".to_string(), "time".to_string()]); + via = Some(*pos - 1); } else { prefix.push(name.clone()); } @@ -532,14 +536,14 @@ fn parse_use_tree( } let bound = alias.cloned().or_else(|| path.last().cloned()); if let Some(bound) = bound.filter(|b| b != "_") { - out.push(UseLeaf { path, name: Some(bound), line, start }); + out.push(UseLeaf { path, name: Some(bound), line, start, alias: via }); } } break; } Kind::Punct('*') => { if prefix.len() <= MAX_USE_PATH && short_segments(prefix) { - out.push(UseLeaf { path: prefix.clone(), name: None, line, start }); + out.push(UseLeaf { path: prefix.clone(), name: None, line, start, alias: via }); } *pos += 1; break; @@ -553,7 +557,7 @@ fn parse_use_tree( } let before = *pos; if !t.is_punct(',') && depth < MAX_NESTING { - parse_use_tree(toks, pos, prefix, start, out, time_aliases, depth + 1); + parse_use_tree(toks, pos, prefix, (start, via), out, time_aliases, depth + 1); } if *pos == before { *pos += 1; @@ -730,12 +734,19 @@ fn starts_block(toks: &[Token], j: usize) -> bool { /// 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. +/// +/// In the head of an `fn`, `impl`, `trait`, `struct`, `enum` or `union` item, a block inside angle +/// brackets (a const generic default or argument such as ``, also in a +/// return type or a `where` clause) does not end the item. The `>` of `->` does not close an angle +/// bracket. 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 generics = false; + let mut angle = 0usize; let mut j = start; while j < toks.len() { let at_top = depth == 0 && !inner; @@ -751,8 +762,15 @@ fn item_end(toks: &[Token], start: usize, inner: bool) -> usize { _ => Condition::Done, }; } + if matches!(k.as_str(), "fn" | "impl" | "trait" | "struct" | "enum" | "union") { + generics = true; + } block_item = true; } + Kind::Punct('<') if at_top && generics => angle += 1, + Kind::Punct('>') if at_top && generics && !j.checked_sub(1).is_some_and(|k| toks[k].is_punct('-')) => { + angle = angle.saturating_sub(1); + } 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, @@ -788,7 +806,7 @@ fn item_end(toks: &[Token], start: usize, inner: bool) -> usize { return j; } depth -= 1; - if depth == 0 && *c == '}' && block_item && !inner && condition == Condition::Done { + if depth == 0 && *c == '}' && block_item && !inner && condition == Condition::Done && angle == 0 { 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")) { @@ -822,6 +840,12 @@ fn item_end(toks: &[Token], start: usize, inner: bool) -> usize { /// An outer attribute (`#[cfg(...)]`) covers the item after it; an inner attribute (`#![cfg(...)]`) /// covers the rest of the module or block it is in. fn native_only(toks: &[Token]) -> Vec { + cfg_covered(toks, false) +} + +/// Mark the tokens of every item that a `cfg` attribute covers: with `any`, whatever its predicate, +/// otherwise only when the predicate is false on `wasm32-unknown-unknown`, as [`native_only`] does. +fn cfg_covered(toks: &[Token], any: bool) -> Vec { let mut skip = vec![false; toks.len()]; let mut i = 0; while i < toks.len() { @@ -842,7 +866,7 @@ fn native_only(toks: &[Token]) -> Vec { } let excluded = toks.get(open + 1).is_some_and(|t| t.is_ident("cfg")) && toks.get(open + 2).is_some_and(|t| t.is_punct('(')) && { let mut pos = open + 3; - eval_cfg(&toks[..close], &mut pos, 0) == Tri::False + any || eval_cfg(&toks[..close], &mut pos, 0) == Tri::False }; if !excluded { i = close + 1; @@ -1156,6 +1180,42 @@ fn native_only_files(paths: &[String], decls: &[Vec]) -> Vec { /// The most rounds [`native_only_files`] spends narrowing the set of loaded files. const MAX_MODULE_ROUNDS: usize = 16; +/// The innermost `{` around each token, and for each `}` the `{` it closes. +fn brace_scopes(toks: &[Token]) -> (Vec>, Vec>) { + let mut around = vec![None; toks.len()]; + let mut opener = vec![None; toks.len()]; + let mut open = Vec::new(); + for (j, t) in toks.iter().enumerate() { + around[j] = open.last().copied(); + if t.is_punct('{') { + open.push(j); + } else if t.is_punct('}') { + opener[j] = open.pop(); + } + } + (around, opener) +} + +/// Look a name up from `toks[at]` outward through the braces around it (`around`, from +/// [`brace_scopes`]): the first value that `get` returns for a pair of braces, given the index of its +/// `{`, or for the file, given `None`. The search ends with the body of the `mod` it starts in, since a +/// module does not see the names its parent binds. `Some(None)` means no braces bind the name; `None` +/// means the search passed [`MAX_NESTING`] levels. +fn lookup(toks: &[Token], around: &[Option], at: usize, get: impl Fn(Option) -> Option) -> Option> { + let mut scope = around.get(at).copied().flatten(); + for _ in 0..=MAX_NESTING { + if let Some(value) = get(scope) { + return Some(Some(value)); + } + match scope { + Some(o) if o >= 2 && toks[o - 2].is_ident("mod") && matches!(toks[o - 1].kind, Kind::Ident(_)) => return Some(None), + Some(o) => scope = around[o], + None => return Some(None), + } + } + None +} + /// Add one finding for each line in `lines`, in line order, with the trimmed text of that line. fn report(findings: &mut Vec, path: &str, content: &str, lines: &BTreeSet) { if lines.is_empty() { @@ -1177,10 +1237,18 @@ fn report(findings: &mut Vec, 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 `::quit` /// 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. +/// `other::PredefinedMenuItem::quit`, is not. It also follows a `use` or a `type` alias that renames +/// muda's type (`use muda::PredefinedMenuItem as Item;` then `Item::quit`); a rename of another crate's +/// `PredefinedMenuItem` is not followed. +/// +/// A name used on its own (`PredefinedMenuItem::quit`, `Item::quit`) is read in the innermost braces +/// around it, within its module, or the file, that bind the name. It is reported when those braces +/// import or alias muda's type under it, and not when they only import another type under it +/// (`use other::PredefinedMenuItem;`) or define one (`struct PredefinedMenuItem`). Where no braces bind +/// it, `PredefinedMenuItem` is reported and a renamed name is not. An import or definition inside an +/// item with a `cfg` attribute, an import or a type alias through `crate::`, `self::` or `super::` +/// (which may be a re-export of muda's type), and an associated `type` in an `impl` or `trait` do not +/// bind the name. Each finding names the line where the type's name starts, once per line, in line order. pub fn predefined_quit(files: I) -> Vec where I: IntoIterator, @@ -1191,19 +1259,149 @@ where let path = file.path(); let content = file.content(); let toks = lex_rust(content); - let aliases: BTreeSet = use_leaves(&toks, &BTreeSet::new()) - .into_iter() - .filter(|leaf| leaf.path == ["muda", "PredefinedMenuItem"]) - .filter_map(|leaf| leaf.name) - .filter(|name| name != "PredefinedMenuItem") - .collect(); + let leaves = use_leaves(&toks, &BTreeSet::new()); + let is_muda = |leaf: &UseLeaf| leaf.path == ["muda", "PredefinedMenuItem"]; + let (around, opener) = brace_scopes(&toks); + // Whether the braces opened at `o` are the body of an `impl` or a `trait`, whose `type` items are + // associated types rather than names in scope. The head is read back from `o` to the `;`, `{` or + // `}` before it, stepping over a block in angle brackets (`impl Foo<{ N }>`), for at most + // `ATTRIBUTE_SCAN_LIMIT` tokens. + let assoc_body = |o: usize| { + let mut j = o; + let mut depth = 0usize; + let mut start = None; + for _ in 0..ATTRIBUTE_SCAN_LIMIT { + let Some(k) = j.checked_sub(1) else { + start = Some(0); + break; + }; + let t = &toks[k]; + if depth == 0 && (t.is_punct(';') || t.is_punct('{')) { + start = Some(k + 1); + break; + } + if depth == 0 && t.is_punct('}') { + let generic = opener[k].filter(|&b| b.checked_sub(1).is_some_and(|p| ['<', ',', '='].iter().any(|&c| toks[p].is_punct(c)))); + if let Some(b) = generic { + j = b; + continue; + } + start = Some(k + 1); + break; + } + match t.kind { + Kind::Punct(')' | ']') => depth += 1, + Kind::Punct('(' | '[') => depth = depth.saturating_sub(1), + _ => {} + } + j = k; + } + let Some(mut s) = start else { return false }; + // Attributes and modifiers before the keyword. + while s < o { + let next = |c: char| toks.get(s + 1).is_some_and(|t| t.is_punct(c)); + if (toks[s].is_punct('#') && next('[')) || (toks[s].is_ident("pub") && next('(')) { + // `#[...]` or `pub(...)`. + s = matching_close(&toks, s + 1).saturating_add(1); + } else if ["pub", "unsafe", "auto", "default"].iter().any(|m| toks[s].is_ident(m)) { + s += 1; + } else { + break; + } + } + s < o && (toks[s].is_ident("impl") || toks[s].is_ident("trait")) + }; + // Whether the `type` name at `i` is followed by `= muda::PredefinedMenuItem;` (or `::muda::...`). + let aliases_muda = |i: usize| { + let mut j = i + 1; + if !toks.get(j).is_some_and(|t| t.is_punct('=')) { + return false; + } + j += 1; + if toks.get(j).is_some_and(|t| t.is_punct(':')) && toks.get(j + 1).is_some_and(|t| t.is_punct(':')) { + j += 2; + } + toks.get(j).is_some_and(|t| t.is_ident("muda")) + && then_path(&toks, j + 1, |s| s == "PredefinedMenuItem") + && toks.get(j + 4).is_some_and(|t| t.is_punct(';')) + }; + let definition = + |i: usize| i.checked_sub(1).is_some_and(|k| ["struct", "enum", "union", "type", "trait"].iter().any(|kw| toks[k].is_ident(kw))); + // The names of muda's type: its own, and each name a `use` or a `type` alias gives it. + let mut names: BTreeSet<&str> = BTreeSet::from(["PredefinedMenuItem"]); + names.extend(leaves.iter().filter(|leaf| is_muda(leaf)).filter_map(|leaf| leaf.name.as_deref())); + for (i, t) in toks.iter().enumerate() { + if let Kind::Ident(name) = &t.kind + && i.checked_sub(1).is_some_and(|k| toks[k].is_ident("type")) + && aliases_muda(i) + { + names.insert(name); + } + } + // For each of those names and each pair of braces (`None` for the file), whether a `use` or a + // type alias in it binds the name to muda's type, and whether a `use` or an item definition in it + // binds the name to another type. A binding to another type inside an item with a `cfg` + // attribute may not apply on the platform the guard protects, so it is left out. + let gated = cfg_covered(&toks, true); + let mut bound: BTreeMap<(&str, Option), (bool, bool)> = BTreeMap::new(); + for leaf in &leaves { + let Some(name) = leaf.name.as_deref().filter(|name| names.contains(name)) else { continue }; + let muda = is_muda(leaf); + // A path into this crate (`crate::`, `self::`, `super::`) may lead to a re-export of muda's + // type, so it is not counted as another type. + let local = leaf.path.first().is_some_and(|s| matches!(s.as_str(), "crate" | "self" | "super")); + if muda || (!local && !gated.get(leaf.start).copied().unwrap_or(false)) { + let entry = bound.entry((name, around.get(leaf.start).copied().flatten())).or_default(); + if muda { + entry.0 = true; + } else { + entry.1 = true; + } + } + } + for (i, t) in toks.iter().enumerate() { + let Kind::Ident(name) = &t.kind else { continue }; + let Some(k) = i.checked_sub(1) else { continue }; + if !names.contains(name.as_str()) || !definition(i) { + continue; + } + if toks[k].is_ident("type") && around[i].is_some_and(assoc_body) { + continue; + } + // An alias of a path into this crate may name a re-export of muda's type, as an import does. + let local_alias = toks.get(i + 1).is_some_and(|t| t.is_punct('=')) + && toks.get(i + 2).is_some_and(|t| t.is_ident("crate") || t.is_ident("self") || t.is_ident("super")); + if toks[k].is_ident("type") && local_alias { + continue; + } + let key = (name.as_str(), around[i]); + if toks[k].is_ident("type") && aliases_muda(i) { + bound.entry(key).or_default().0 = true; + } else if !gated[i] { + bound.entry(key).or_default().1 = true; + } + } + // A name used on its own is muda's type when the innermost braces around it that bind it (within + // its module) bind it to muda's type, or only to nothing else. Where no braces bind it, only + // `PredefinedMenuItem` itself is muda's type. Past `MAX_NESTING` levels it is read as muda's type. + let bare_is_muda = |name: &str, i: usize| match lookup(&toks, &around, i, |scope| bound.get(&(name, scope)).copied()) { + None => true, + Some(Some((muda, other))) => muda || !other, + Some(None) => name == "PredefinedMenuItem", + }; let mut lines = BTreeSet::new(); for (i, tok) in toks.iter().enumerate() { let Kind::Ident(name) = &tok.kind else { continue }; + if !names.contains(name.as_str()) { + continue; + } // 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 named = if continues_a_path(&toks, i) { + name == "PredefinedMenuItem" && toks[i - 3].is_ident("muda") && !continues_a_path(&toks, i - 3) + } else { + bare_is_muda(name, i) + }; let quit = |at: usize| then_path(&toks, at, |s| s == "quit" || s == "Quit"); // `::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); @@ -1250,8 +1448,9 @@ where /// (such as `src/bin/tool.rs`) is read as an ordinary module file. A declaration inside more than 64 inline /// modules is not followed, so its file is checked. /// * **Limitations**: This is a lexical source guard. It does not expand macros, resolve paths through other -/// modules or re-exports, rename `std` itself (`use std as s;`), or follow aliases in a different scope than -/// the file. +/// modules or re-exports, or rename `std` itself (`use std as s;`). An alias of `std::time` counts inside the +/// braces of its `use` (or the file), down to but not into the body of a nested `mod`; nearer braces whose +/// `use` or `mod` binds the same name to something else hide it. pub fn std_instant(files: I) -> Vec where I: IntoIterator, @@ -1284,12 +1483,44 @@ where .filter(|leaf| leaf.path == ["std", "time"] && !skip.get(leaf.start).copied().unwrap_or(false)) .filter_map(|leaf| leaf.name.clone()) .collect(); + // For each alias name and each pair of braces (`None` for the file), whether a `use` in it binds + // the name to `std::time`, and whether a `use` or a `mod` in it binds the name to something else. + let (around, _) = brace_scopes(&toks); + let mut bound: BTreeMap<(&str, Option), (bool, bool)> = BTreeMap::new(); + for leaf in &leaves { + let Some(name) = leaf.name.as_deref().filter(|name| modules.contains(*name)) else { continue }; + if !skip.get(leaf.start).copied().unwrap_or(false) { + let entry = bound.entry((name, around.get(leaf.start).copied().flatten())).or_default(); + if leaf.path == ["std", "time"] { + entry.0 = true; + } else { + entry.1 = true; + } + } + } + for (i, t) in toks.iter().enumerate() { + if let Kind::Ident(name) = &t.kind + && modules.contains(name) + && !skip[i] + && i.checked_sub(1).is_some_and(|k| toks[k].is_ident("mod")) + { + bound.entry((name.as_str(), around[i])).or_default().1 = true; + } + } + // Whether `name` at `toks[at]` is an alias of `std::time`: the innermost braces around it that + // bind the name (within its module) bind it to `std::time`. Past `MAX_NESTING` levels it is. + let time_alias = |name: &str, at: usize| match lookup(&toks, &around, at, |scope| bound.get(&(name, scope)).copied()) { + None => true, + Some(Some((time, _))) => time, + Some(None) => false, + }; // Read again with the aliases of `std::time`, so a path through an alias starts with `std::time`. - let leaves = if modules.is_empty() { leaves } else { use_leaves(&toks, &modules) }; + let aliased = if modules.is_empty() { Vec::new() } else { use_leaves(&toks, &modules) }; + let leaves = if modules.is_empty() { &leaves } else { &aliased }; let is_std_time = |path: &[String]| path == ["std", "time"]; let mut lines = BTreeSet::new(); - for leaf in &leaves { + for leaf in leaves { if skip.get(leaf.start).copied().unwrap_or(false) { continue; } @@ -1298,7 +1529,9 @@ where } else { leaf.path.split_last().is_some_and(|(last, parent)| last == "Instant" && is_std_time(parent)) }; - if imports_instant { + // A path read through an alias counts only where the alias names `std::time`. + let through_other = leaf.alias.is_some_and(|a| matches!(&toks[a].kind, Kind::Ident(root) if !time_alias(root, leaf.start))); + if imports_instant && !through_other { lines.insert(leaf.line); } } @@ -1310,7 +1543,7 @@ where let hit = if name == "std" { then_path(&toks, i + 1, |s| s == "time") && then_path(&toks, i + 4, |s| s == "Instant") } else { - modules.contains(name) && then_path(&toks, i + 1, |s| s == "Instant") + modules.contains(name) && then_path(&toks, i + 1, |s| s == "Instant") && time_alias(name, i) }; if hit { lines.insert(tok.line); @@ -1585,10 +1818,16 @@ impl Default for SourceLimits { #[cfg(not(target_arch = "wasm32"))] const CACHEDIR_SIGNATURE: &[u8] = b"Signature: 8a477f597d28d172789f06886806bc55"; +/// Whether `dir` holds a `CACHEDIR.TAG` regular file that starts with [`CACHEDIR_SIGNATURE`]. A marker +/// that is a symbolic link, a folder, a FIFO or another special file is not opened and does not count. #[cfg(not(target_arch = "wasm32"))] fn is_cache_dir(dir: &Path) -> bool { use std::io::Read; - let Ok(file) = std::fs::File::open(dir.join("CACHEDIR.TAG")) else { + let marker = dir.join("CACHEDIR.TAG"); + if !std::fs::symlink_metadata(&marker).is_ok_and(|m| m.file_type().is_file()) { + return false; + } + let Ok(file) = std::fs::File::open(&marker) else { return false; }; let mut head = Vec::with_capacity(CACHEDIR_SIGNATURE.len()); @@ -1605,8 +1844,10 @@ fn is_cache_dir(dir: &Path) -> bool { /// * `*_test.rs` /// * `test.rs` /// * Any file below `dir` within a directory named `tests`, `benches`, `examples` or `target`, or whose -/// name starts with `.`, or that holds a `CACHEDIR.TAG` file starting with the signature line -/// `Signature: 8a477f597d28d172789f06886806bc55` (a build output folder with another name). +/// name starts with `.`, or that holds a `CACHEDIR.TAG` regular file starting with the signature line +/// `Signature: 8a477f597d28d172789f06886806bc55` (a build output folder with another name). A +/// `CACHEDIR.TAG` that is a symbolic link or a special file such as a FIFO is not read, and its folder +/// is listed. /// * Symbolic links (and, on Windows, junctions) to files or folders, which are not followed. /// /// Results are sorted lexicographically by file path for deterministic behavior across platforms. diff --git a/crates/testkit/tests/guards.rs b/crates/testkit/tests/guards.rs index 721e7a76a7..59c7760011 100644 --- a/crates/testkit/tests/guards.rs +++ b/crates/testkit/tests/guards.rs @@ -446,6 +446,125 @@ fn menu() { assert_eq!(lines(&predefined_quit([("src/menu.rs", source)])), vec![10, 11, 12]); } +#[test] +fn predefined_quit_ignores_a_bare_name_that_another_import_or_a_local_type_binds_in_its_scope() { + let imported = r#" +use other_menu::PredefinedMenuItem; +fn menu() { + let a = PredefinedMenuItem::quit(None); + let b = muda::PredefinedMenuItem::quit(None); +} +"#; + let grouped = "use other_menu::{PredefinedMenuItem, Menu};\nfn menu() { let a = PredefinedMenuItem::quit(None); }\n"; + let local = r#" +struct PredefinedMenuItem; +fn menu() { + let a = PredefinedMenuItem::quit(None); + let b = ::quit(None); +} +"#; + let both = r#" +use muda::PredefinedMenuItem; +mod other { pub struct PredefinedMenuItem; } +fn menu() { + let a = PredefinedMenuItem::quit(None); +} +"#; + let scoped = r#" +use muda::*; +mod other { + use other_menu::PredefinedMenuItem; + fn menu() { let a = PredefinedMenuItem::quit(None); } +} +mod local { struct PredefinedMenuItem; fn menu() { let b = PredefinedMenuItem::quit(None); } } +fn menu() { + let c = PredefinedMenuItem::quit(None); + { use other_menu::PredefinedMenuItem; let d = PredefinedMenuItem::quit(None); } + let e = PredefinedMenuItem::quit(None); +} +"#; + assert_eq!(lines(&predefined_quit([("src/imported.rs", imported)])), vec![5]); + assert!(predefined_quit([("src/grouped.rs", grouped)]).is_empty()); + assert!(predefined_quit([("src/local.rs", local)]).is_empty()); + assert_eq!(lines(&predefined_quit([("src/both.rs", both)])), vec![5]); + assert_eq!(lines(&predefined_quit([("src/scoped.rs", scoped)])), vec![9, 11]); + let child = r#" +use other_menu::PredefinedMenuItem; +mod child { + use muda::*; + fn menu() { let a = PredefinedMenuItem::quit(None); } +} +fn menu() { let b = PredefinedMenuItem::quit(None); } +"#; + assert_eq!(lines(&predefined_quit([("src/child.rs", child)])), vec![5]); + let renamed = r#" +mod a { + use muda::PredefinedMenuItem as Item; + fn menu() { let a = Item::quit(None); } +} +mod b { + struct Item; + fn menu() { let b = Item::quit(None); } +} +mod c { fn menu() { let c = Item::quit(None); } } +mod d { type Quit = muda::PredefinedMenuItem; fn menu() { let d = Quit::quit(None); } } +"#; + assert_eq!(lines(&predefined_quit([("src/renamed.rs", renamed)])), vec![4, 11]); + let aliased_or_gated = r#" +mod alias { + type PredefinedMenuItem = ::muda::PredefinedMenuItem; + fn menu() { let a = PredefinedMenuItem::quit(None); } +} +mod gated { + use muda::*; + #[cfg(windows)] + struct PredefinedMenuItem; + #[cfg(windows)] use other_menu::PredefinedMenuItem; + fn menu() { let b = PredefinedMenuItem::quit(None); } +} +mod other { type PredefinedMenuItem = other_menu::PredefinedMenuItem; fn menu() { let c = PredefinedMenuItem::quit(None); } } +mod assoc { + use muda::PredefinedMenuItem; + trait Menu { type PredefinedMenuItem; fn menu() { let d = PredefinedMenuItem::quit(None); } } + #[allow(dead_code)] unsafe impl Menu for Wrap<{ N }> { + fn menu() { let e = PredefinedMenuItem::quit(None); } + type PredefinedMenuItem = u8; + } +} +mod reexported { + use crate::PredefinedMenuItem; + fn menu() { let f = PredefinedMenuItem::quit(None); } + mod inner { use super::super::{self as up, PredefinedMenuItem}; fn menu() { let g = PredefinedMenuItem::quit(None); } } + mod aliased { type PredefinedMenuItem = crate::menu::PredefinedMenuItem; fn menu() { let h = PredefinedMenuItem::quit(None); } } +} +"#; + assert_eq!(lines(&predefined_quit([("src/aliased.rs", aliased_or_gated)])), vec![4, 11, 16, 18, 24, 25, 26]); +} + +#[test] +fn std_instant_reads_a_std_time_alias_only_in_its_scope() { + let source = r#" +mod native { + use std::time as clock; + fn now() { let a = clock::Instant::now(); } + use clock::Instant as A; +} +mod web { + use web_time as clock; + fn now() { let b = clock::Instant::now(); } + use clock::Instant as B; + use {clock::*, std::time::*}; +} +mod child { fn now() { let c = clock::Instant::now(); } } +fn run() { + use std::time as t; + let d = t::Instant::now(); + { mod t {} let e = t::Instant::now(); } +} +"#; + assert_eq!(lines(&std_instant([("src/lib.rs", source)])), vec![4, 5, 11, 16]); +} + #[test] fn std_instant_ignores_an_alias_that_only_a_native_cfg_imports() { let source = r#" @@ -789,6 +908,21 @@ fn std_instant_ends_native_cfg_impl_mod_and_struct_items_where_they_end_on_the_l assert_eq!(lines(&std_instant([("src/clock.rs", source)])), vec![1, 2, 3, 4]); } +#[test] +fn std_instant_reads_blocks_in_generic_brackets_as_part_of_a_native_cfg_item_head() { + let source = r#"#[cfg(unix)] struct Native { clock: std::time::Instant } +#[cfg(unix)] enum E { A(std::time::Instant) } +#[cfg(unix)] trait Tr: Sized where Self: Into> { fn now() -> std::time::Instant { std::time::Instant::now() } } +#[cfg(unix)] impl Tr<{ N }> for Native<{ N }> { fn now() -> std::time::Instant { std::time::Instant::now() } } +#[cfg(unix)] fn native() -> W<{ 1 + 1 }> where T: Into> { std::time::Instant::now(); W } +#[cfg(unix)] fn arrow u8>(f: F) -> impl Fn() -> W<{ 3 }> where F: Copy { let _t = std::time::Instant::now(); f } +struct Web { clock: std::time::Instant } +fn web() -> W<{ 1 }> where u8: Into> { std::time::Instant::now(); W } +#[cfg(unix)] struct A { a: std::time::Instant } fn after() { std::time::Instant::now(); } +"#; + assert_eq!(lines(&std_instant([("src/clock.rs", source)])), vec![7, 8, 9]); +} + #[test] fn std_instant_reads_paths_split_over_lines_and_comments_with_crlf() { let source = "use std::time::\r\n Instant;\r\nfn run() {\r\n let t = std::time\r\n ::Instant::now();\r\n let u = std /* a */ :: time // b\r\n :: Instant::now();\r\n}\r\n"; @@ -1335,6 +1469,45 @@ fn rust_sources_skips_build_output_folders_marked_with_cachedir_tag() { assert_eq!(file_names(&sources), vec!["kept.rs", "lib.rs"]); } +#[cfg(unix)] +#[test] +fn rust_sources_does_not_read_a_cachedir_tag_through_a_symlink() { + let outside = ScratchDir::new("cachedir_link_target"); + outside.write("CACHEDIR.TAG", "Signature: 8a477f597d28d172789f06886806bc55\n"); + let dir = ScratchDir::new("cachedir_link"); + dir.write("src/lib.rs", "pub fn lib() {}"); + dir.write("linked/kept.rs", "pub fn kept() {}"); + std::os::unix::fs::symlink(outside.path().join("CACHEDIR.TAG"), dir.path().join("linked").join("CACHEDIR.TAG")).expect("symlink marker"); + let sources = craft_testkit::rust_sources(dir.path()).expect("rust_sources"); + assert_eq!(file_names(&sources), vec!["kept.rs", "lib.rs"]); +} + +#[cfg(unix)] +#[test] +fn rust_sources_does_not_open_a_cachedir_tag_fifo() { + let dir = ScratchDir::new("cachedir_fifo"); + dir.write("src/lib.rs", "pub fn lib() {}"); + dir.write("piped/kept.rs", "pub fn kept() {}"); + let fifo = dir.path().join("piped").join("CACHEDIR.TAG"); + match std::process::Command::new("mkfifo").arg(&fifo).status() { + Ok(status) if status.success() => {} + other => { + eprintln!("skipped: mkfifo is not available here ({other:?})"); + return; + } + } + let root = dir.path().to_path_buf(); + let (tx, rx) = std::sync::mpsc::channel(); + std::thread::spawn(move || { + let _ = tx.send(craft_testkit::rust_sources(root)); + }); + let sources = rx + .recv_timeout(std::time::Duration::from_secs(30)) + .expect("rust_sources returns instead of blocking on the CACHEDIR.TAG FIFO") + .expect("rust_sources"); + assert_eq!(file_names(&sources), vec!["kept.rs", "lib.rs"]); +} + #[cfg(unix)] #[test] fn rust_sources_does_not_follow_a_symlink_out_of_the_root() { From 7da619dc4ebecb578922e0a63f18d4c73f40c488 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 19:11:43 -0800 Subject: [PATCH 14/33] craft-testkit: guards keep names past the use-path limits, report underscore imports in groups and keep crate roots in module cycles - A `use` whose path is longer than the copy limits still binds its name, and keeps its first segment, so another crate's long path no longer reads as an unbound `PredefinedMenuItem` and a long `crate::` path still reads as a possible re-export. - `std_instant` reports `use std::{time::Instant as _};`; `_` only stops the name from being bound. - `std_instant` checks the leaves read without aliases as well as the ones read through them, so an alias in a nested module no longer hides an outer `use std::{time::Instant};`. - A cycle of `mod` declarations that no other file names keeps a crate root: its `lib.rs` or `main.rs`, or every member when it has neither. A `lib.rs` that names itself through a disabled `#[path]` declaration is checked again. - `predefined_quit` does not report `muda::PredefinedMenuItem::quit` where a `use` or a `mod` in scope binds `muda` to something else (`use other_menu as muda;`); `::muda::` is still reported. --- crates/testkit/src/guards.rs | 230 ++++++++++++++++++++++++++++----- crates/testkit/tests/guards.rs | 115 +++++++++++++++++ 2 files changed, 310 insertions(+), 35 deletions(-) diff --git a/crates/testkit/src/guards.rs b/crates/testkit/src/guards.rs index 67bb79bb93..1515160dd9 100644 --- a/crates/testkit/src/guards.rs +++ b/crates/testkit/src/guards.rs @@ -115,13 +115,13 @@ impl AsFileSource for &(&str, String) { const MAX_NESTING: usize = 64; /// The most segments of a `use` path that [`use_leaves`] keeps. The guards compare paths of at most -/// three segments, so a leaf with a longer path is left out, and a long prefix shared by many leaves -/// is not copied into each of them. +/// three segments, so a leaf with a longer path keeps only the name it binds, and a long prefix shared +/// by many leaves is not copied into each of them. const MAX_USE_PATH: usize = 8; /// The longest segment, in bytes, of a `use` path that [`use_leaves`] keeps. The longest segment the -/// guards compare is `PredefinedMenuItem`, so a leaf with a longer segment is left out, and a long name -/// shared by many leaves is not copied into each of them. +/// guards compare is `PredefinedMenuItem`, so a leaf with a longer segment keeps only the name it binds, +/// and a long name shared by many leaves is not copied into each of them. const MAX_USE_SEGMENT: usize = 32; /// The kind of a Rust token. Comments are dropped; string, character and number literals keep no text @@ -458,10 +458,15 @@ fn opens_qualified_path(toks: &[Token], i: usize) -> bool { /// One name a `use` declaration brings into scope. #[derive(Debug)] struct UseLeaf { - /// The full path, `self` removed and without a leading `::`. + /// The full path, `self` removed and without a leading `::`. It is empty for a path longer than + /// [`MAX_USE_PATH`] segments or with a segment longer than [`MAX_USE_SEGMENT`] bytes, whose leaf then + /// records only the name it binds. path: Vec, - /// The name it is bound to; `None` for a glob import. - name: Option, + /// The name it is bound to, `_` for an underscore import; `None` for a glob import. The name is + /// shared with the other leaves that bind the same segment of one path. + name: Option>, + /// The first segment of the path, kept when the path is not. + root: Option>, line: usize, /// Index of the `use` keyword. start: usize, @@ -469,6 +474,14 @@ struct UseLeaf { alias: Option, } +impl UseLeaf { + /// The name the leaf binds in scope: `None` for a glob import and for an underscore import, which + /// imports an item without binding a name. + fn binding(&self) -> Option<&str> { + self.name.as_deref().filter(|name| *name != "_") + } +} + /// Every name the `use` declarations of a file bring into scope. A path that starts with a name in /// `time_aliases` is read as a path that starts with `std::time`, so the alias, at any length, is not /// copied into the leaves and the limits do not drop them. @@ -494,7 +507,7 @@ fn use_leaves(toks: &[Token], time_aliases: &BTreeSet) -> Vec { fn parse_use_tree( toks: &[Token], pos: &mut usize, - prefix: &mut Vec, + prefix: &mut Vec>, // The index of the `use` keyword, and of the alias of `std::time` that `prefix` was read through. (start, mut via): (usize, Option), out: &mut Vec, @@ -513,10 +526,10 @@ fn parse_use_tree( *pos += 1; if toks.get(*pos).is_some_and(|t| t.is_punct(':')) && toks.get(*pos + 1).is_some_and(|t| t.is_punct(':')) { if prefix.is_empty() && time_aliases.contains(name) { - prefix.extend(["std".to_string(), "time".to_string()]); + prefix.extend([Rc::from("std"), Rc::from("time")]); via = Some(*pos - 1); } else { - prefix.push(name.clone()); + prefix.push(Rc::from(name.as_str())); } *pos += 2; continue; @@ -529,21 +542,34 @@ fn parse_use_tree( } _ => None, }; - if length <= MAX_USE_PATH && short_segments(prefix) && name.len() <= MAX_USE_SEGMENT { - let mut path = prefix.clone(); + // The name the leaf binds: its alias, its last name, or for `self` the last segment of + // the prefix, shared rather than copied. + let bound = match alias { + Some(alias) => Some(Rc::from(alias.as_str())), + None if name != "self" => Some(Rc::from(name.as_str())), + None => prefix.last().cloned(), + }; + // A path past the limits is not copied, but the leaf still binds its name, so that the name + // does not read as unbound. + let path = if length <= MAX_USE_PATH && short_segments(prefix) && name.len() <= MAX_USE_SEGMENT { + let mut path: Vec = prefix.iter().map(|segment| segment.to_string()).collect(); if name != "self" { path.push(name.clone()); } - let bound = alias.cloned().or_else(|| path.last().cloned()); - if let Some(bound) = bound.filter(|b| b != "_") { - out.push(UseLeaf { path, name: Some(bound), line, start, alias: via }); - } + path + } else { + Vec::new() + }; + if bound.is_some() { + let root = prefix.first().cloned().or_else(|| Some(Rc::from(name.as_str()))); + out.push(UseLeaf { path, name: bound, root, line, start, alias: via }); } break; } Kind::Punct('*') => { if prefix.len() <= MAX_USE_PATH && short_segments(prefix) { - out.push(UseLeaf { path: prefix.clone(), name: None, line, start, alias: via }); + let path = prefix.iter().map(|segment| segment.to_string()).collect(); + out.push(UseLeaf { path, name: None, root: prefix.first().cloned(), line, start, alias: via }); } *pos += 1; break; @@ -572,7 +598,7 @@ fn parse_use_tree( } /// Whether every segment of `path` is at most [`MAX_USE_SEGMENT`] bytes long. -fn short_segments(path: &[String]) -> bool { +fn short_segments(path: &[Rc]) -> bool { path.iter().all(|segment| segment.len() <= MAX_USE_SEGMENT) } @@ -1092,7 +1118,8 @@ fn module_files(parent: &str, decl: &ModDecl, path_loaded: bool) -> Vec /// For each file, whether it is native-only: a `mod` declaration in a native-only item, or any declaration /// in a native-only file, names it, and no chain of declarations outside native-only items reaches it from -/// a crate root (a file that no declaration names). +/// a crate root (a file that no declaration names, or in a cycle of declarations that no file outside the +/// cycle names, its `lib.rs` or `main.rs`, or every member when it has neither). fn native_only_files(paths: &[String], decls: &[Vec]) -> Vec { let mut index: BTreeMap<&str, Vec> = BTreeMap::new(); for (i, path) in paths.iter().enumerate() { @@ -1119,6 +1146,30 @@ fn native_only_files(paths: &[String], decls: &[Vec]) -> Vec { }) .collect(); + // A group of files that name each other in a cycle, and that no file outside the group names, has no + // member that a crate root can reach. rustc does not load a cycle of enabled declarations, so such a + // cycle runs through a declaration the build leaves out. When the group holds a `lib.rs` or `main.rs`, + // those files are its crate roots and the declarations that name them are read as left out; otherwise + // no declaration of the group names its own members, and each of them can be a crate root. + let file_edges: Vec> = + (0..paths.len()).map(|file| edges[2 * file].iter().chain(&edges[2 * file + 1]).map(|&(_, target)| target / 2).collect()).collect(); + let component = components(&file_edges); + let root_file = |file: usize| matches!(paths[file].rsplit('/').next(), Some("lib.rs" | "main.rs")); + let mut entered = vec![false; paths.len()]; + let mut has_root = vec![false; paths.len()]; + for (file, targets) in file_edges.iter().enumerate() { + has_root[component[file]] |= root_file(file); + for &target in targets { + if component[target] != component[file] { + entered[component[target]] = true; + } + } + } + let names = |node: usize, target: usize| { + let group = component[target / 2]; + component[node / 2] != group || entered[group] || (has_root[group] && !root_file(target / 2)) + }; + // The nodes that are loaded: a file that no loaded node names is a crate root, loaded plainly, and a // node is loaded when a loaded node names it. Every file starts out loaded plainly, and the set is // narrowed until it stops changing, or after `MAX_MODULE_ROUNDS` rounds. @@ -1129,7 +1180,9 @@ fn native_only_files(paths: &[String], decls: &[Vec]) -> Vec { for (node, targets) in edges.iter().enumerate() { if loaded[node] { for &(_, target) in targets { - reached[target] = true; + if names(node, target) { + reached[target] = true; + } } } } @@ -1180,6 +1233,63 @@ fn native_only_files(paths: &[String], decls: &[Vec]) -> Vec { /// The most rounds [`native_only_files`] spends narrowing the set of loaded files. const MAX_MODULE_ROUNDS: usize = 16; +/// For each node of the graph `edges`, the number of its strongly connected component (Tarjan's +/// algorithm, with an explicit stack in place of recursion). +fn components(edges: &[Vec]) -> Vec { + const UNSEEN: usize = usize::MAX; + let mut index = vec![UNSEEN; edges.len()]; + let mut low = vec![0; edges.len()]; + let mut on_stack = vec![false; edges.len()]; + let mut component = vec![UNSEEN; edges.len()]; + let mut stack = Vec::new(); + let mut next = 0; + let mut count = 0; + for root in 0..edges.len() { + if index[root] != UNSEEN { + continue; + } + index[root] = next; + low[root] = next; + next += 1; + stack.push(root); + on_stack[root] = true; + // Each frame is a node and the position of the next edge of it to follow. + let mut work = vec![(root, 0usize)]; + while let Some(frame) = work.last_mut() { + let node = frame.0; + if let Some(&target) = edges[node].get(frame.1) { + frame.1 += 1; + if index[target] == UNSEEN { + index[target] = next; + low[target] = next; + next += 1; + stack.push(target); + on_stack[target] = true; + work.push((target, 0)); + } else if on_stack[target] { + low[node] = low[node].min(index[target]); + } + continue; + } + work.pop(); + if let Some(&(parent, _)) = work.last() { + low[parent] = low[parent].min(low[node]); + } + if low[node] == index[node] { + while let Some(member) = stack.pop() { + on_stack[member] = false; + component[member] = count; + if member == node { + break; + } + } + count += 1; + } + } + } + component +} + /// The innermost `{` around each token, and for each `}` the `{` it closes. fn brace_scopes(toks: &[Token]) -> (Vec>, Vec>) { let mut around = vec![None; toks.len()]; @@ -1237,7 +1347,9 @@ fn report(findings: &mut Vec, 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 `::quit` /// 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` or a `type` alias that renames +/// `other::PredefinedMenuItem::quit`, is not, and neither is a path through a name `muda` that the innermost +/// braces binding it bind only to something else (`use other_menu as muda;`, `mod muda`), read like a name +/// used on its own below; `::muda::PredefinedMenuItem` always names the crate. It also follows a `use` or a `type` alias that renames /// muda's type (`use muda::PredefinedMenuItem as Item;` then `Item::quit`); a rename of another crate's /// `PredefinedMenuItem` is not followed. /// @@ -1329,7 +1441,7 @@ where |i: usize| i.checked_sub(1).is_some_and(|k| ["struct", "enum", "union", "type", "trait"].iter().any(|kw| toks[k].is_ident(kw))); // The names of muda's type: its own, and each name a `use` or a `type` alias gives it. let mut names: BTreeSet<&str> = BTreeSet::from(["PredefinedMenuItem"]); - names.extend(leaves.iter().filter(|leaf| is_muda(leaf)).filter_map(|leaf| leaf.name.as_deref())); + names.extend(leaves.iter().filter(|leaf| is_muda(leaf)).filter_map(UseLeaf::binding)); for (i, t) in toks.iter().enumerate() { if let Kind::Ident(name) = &t.kind && i.checked_sub(1).is_some_and(|k| toks[k].is_ident("type")) @@ -1345,11 +1457,11 @@ where let gated = cfg_covered(&toks, true); let mut bound: BTreeMap<(&str, Option), (bool, bool)> = BTreeMap::new(); for leaf in &leaves { - let Some(name) = leaf.name.as_deref().filter(|name| names.contains(name)) else { continue }; + let Some(name) = leaf.binding().filter(|name| names.contains(name)) else { continue }; let muda = is_muda(leaf); // A path into this crate (`crate::`, `self::`, `super::`) may lead to a re-export of muda's // type, so it is not counted as another type. - let local = leaf.path.first().is_some_and(|s| matches!(s.as_str(), "crate" | "self" | "super")); + let local = leaf.root.as_deref().is_some_and(|s| matches!(s, "crate" | "self" | "super")); if muda || (!local && !gated.get(leaf.start).copied().unwrap_or(false)) { let entry = bound.entry((name, around.get(leaf.start).copied().flatten())).or_default(); if muda { @@ -1389,6 +1501,30 @@ where Some(Some((muda, other))) => muda || !other, Some(None) => name == "PredefinedMenuItem", }; + // For each pair of braces (`None` for the file), whether a `use` in it binds the name `muda` to the + // crate, and whether a `use` or a `mod` in it binds `muda` to something else, with the same + // exceptions as for the type's names. + let mut crate_bound: BTreeMap, (bool, bool)> = BTreeMap::new(); + for leaf in leaves.iter().filter(|leaf| leaf.binding() == Some("muda")) { + let local = leaf.root.as_deref().is_some_and(|s| matches!(s, "crate" | "self" | "super")); + let entry = around.get(leaf.start).copied().flatten(); + if leaf.path == ["muda"] { + crate_bound.entry(entry).or_default().0 = true; + } else if !local && !gated.get(leaf.start).copied().unwrap_or(false) { + crate_bound.entry(entry).or_default().1 = true; + } + } + for (i, t) in toks.iter().enumerate() { + if t.is_ident("muda") && i.checked_sub(1).is_some_and(|k| toks[k].is_ident("mod")) && !gated[i] { + crate_bound.entry(around[i]).or_default().1 = true; + } + } + // Whether `muda` at `i` names the crate: after a leading `::` it always does, and otherwise unless + // the innermost braces around it that bind `muda` bind it only to something else. + let crate_is_muda = |i: usize| { + let absolute = i >= 2 && toks[i - 1].is_punct(':') && toks[i - 2].is_punct(':'); + absolute || !matches!(lookup(&toks, &around, i, |scope| crate_bound.get(&scope).copied()), Some(Some((false, true)))) + }; let mut lines = BTreeSet::new(); for (i, tok) in toks.iter().enumerate() { let Kind::Ident(name) = &tok.kind else { continue }; @@ -1398,7 +1534,7 @@ where // A qualified name counts only as `muda::PredefinedMenuItem` (or `::muda::...`), not as // another crate's or module's type of the same name. let named = if continues_a_path(&toks, i) { - name == "PredefinedMenuItem" && toks[i - 3].is_ident("muda") && !continues_a_path(&toks, i - 3) + name == "PredefinedMenuItem" && toks[i - 3].is_ident("muda") && !continues_a_path(&toks, i - 3) && crate_is_muda(i - 3) } else { bare_is_muda(name, i) }; @@ -1440,7 +1576,9 @@ where /// is not known from the source, so the item is checked. Escapes in a predicate's string values are decoded. /// * **Module files**: a `mod name;` inside such an item makes the module's file native-only, and so are the /// files of the modules declared in it, when they are among `files`, unless a chain of declarations outside -/// such items also reaches the file from a crate root (a file that no declaration names). The module's file is `name.rs` or +/// such items also reaches the file from a crate root (a file that no declaration names, or in a cycle of +/// declarations that no file outside the cycle names, such as `lib.rs` naming itself through `#[path]`, the +/// cycle's `lib.rs` or `main.rs`, or every file of the cycle when it has neither). The module's file is `name.rs` or /// `name/mod.rs` next to `lib.rs`, `main.rs`, `mod.rs` or a file that a `#[path]` attribute names, and in /// the folder named after any other file's stem, below the folders of enclosing inline modules; a `#[path = "..."]` attribute on the declaration /// or on an enclosing inline module is followed. Paths are compared as text with `\` read as `/`, so the files must be named the same way @@ -1481,14 +1619,14 @@ where let modules: BTreeSet = leaves .iter() .filter(|leaf| leaf.path == ["std", "time"] && !skip.get(leaf.start).copied().unwrap_or(false)) - .filter_map(|leaf| leaf.name.clone()) + .filter_map(|leaf| leaf.binding().map(str::to_owned)) .collect(); // For each alias name and each pair of braces (`None` for the file), whether a `use` in it binds // the name to `std::time`, and whether a `use` or a `mod` in it binds the name to something else. let (around, _) = brace_scopes(&toks); let mut bound: BTreeMap<(&str, Option), (bool, bool)> = BTreeMap::new(); for leaf in &leaves { - let Some(name) = leaf.name.as_deref().filter(|name| modules.contains(*name)) else { continue }; + let Some(name) = leaf.binding().filter(|name| modules.contains(*name)) else { continue }; if !skip.get(leaf.start).copied().unwrap_or(false) { let entry = bound.entry((name, around.get(leaf.start).copied().flatten())).or_default(); if leaf.path == ["std", "time"] { @@ -1515,12 +1653,13 @@ where Some(None) => false, }; // Read again with the aliases of `std::time`, so a path through an alias starts with `std::time`. + // The leaves read without aliases are checked as well, since an alias does not reach every `use` + // whose path starts with its name (an alias in a nested module named `std`). let aliased = if modules.is_empty() { Vec::new() } else { use_leaves(&toks, &modules) }; - let leaves = if modules.is_empty() { &leaves } else { &aliased }; let is_std_time = |path: &[String]| path == ["std", "time"]; let mut lines = BTreeSet::new(); - for leaf in leaves { + for leaf in leaves.iter().chain(&aliased) { if skip.get(leaf.start).copied().unwrap_or(false) { continue; } @@ -1929,11 +2068,25 @@ mod tests { use super::{MAX_USE_PATH, MAX_USE_SEGMENT, lex_rust, use_leaves}; + fn paths_and_names(source: &str) -> Vec<(Vec, Option)> { + use_leaves(&lex_rust(source), &BTreeSet::new()).into_iter().map(|leaf| (leaf.path, leaf.name.map(|name| name.to_string()))).collect() + } + #[test] fn use_leaves_keep_no_path_longer_than_the_limit() { let source = format!("use {}{{x, y::z, *}};\nuse std::time::{{Instant, self as t}};\n", "a::".repeat(MAX_USE_PATH)); - let paths: Vec> = use_leaves(&lex_rust(&source), &BTreeSet::new()).into_iter().map(|leaf| leaf.path).collect(); - assert_eq!(paths, vec![vec!["a"; MAX_USE_PATH], vec!["std", "time", "Instant"], vec!["std", "time"]]); + let some = |name: &str| Some(name.to_string()); + let path = |segments: &[&str]| segments.iter().map(|s| s.to_string()).collect::>(); + assert_eq!( + paths_and_names(&source), + vec![ + (Vec::new(), some("x")), + (Vec::new(), some("z")), + (vec!["a".to_string(); MAX_USE_PATH], None), + (path(&["std", "time", "Instant"]), some("Instant")), + (path(&["std", "time"]), some("t")), + ] + ); } #[test] @@ -1941,8 +2094,15 @@ mod tests { let long = "n".repeat(MAX_USE_SEGMENT + 1); let fits = "n".repeat(MAX_USE_SEGMENT); let source = format!("use {long}::{{self, x, *}};\nuse a::{long};\nuse {fits}::{{self as b, *}};\n"); - let leaves = use_leaves(&lex_rust(&source), &BTreeSet::new()); - let paths: Vec<(Vec, Option)> = leaves.into_iter().map(|leaf| (leaf.path, leaf.name)).collect(); - assert_eq!(paths, vec![(vec![fits.clone()], Some("b".to_string())), (vec![fits], None)]); + assert_eq!( + paths_and_names(&source), + vec![ + (Vec::new(), Some(long.clone())), + (Vec::new(), Some("x".to_string())), + (Vec::new(), Some(long)), + (vec![fits.clone()], Some("b".to_string())), + (vec![fits], None), + ] + ); } } diff --git a/crates/testkit/tests/guards.rs b/crates/testkit/tests/guards.rs index 59c7760011..a7a4f67963 100644 --- a/crates/testkit/tests/guards.rs +++ b/crates/testkit/tests/guards.rs @@ -446,6 +446,32 @@ fn menu() { assert_eq!(lines(&predefined_quit([("src/menu.rs", source)])), vec![10, 11, 12]); } +#[test] +fn predefined_quit_ignores_a_muda_path_that_a_local_binding_of_muda_names() { + let source = r#" +use other_menu as muda; +fn menu() { + let a = muda::PredefinedMenuItem::quit(None); + let b = ::quit(None); + let c = ::muda::PredefinedMenuItem::quit(None); +} +mod inner { + use ::muda; + fn menu() { let d = muda::PredefinedMenuItem::quit(None); } +} +mod defined { + mod muda {} + fn menu() { let e = muda::PredefinedMenuItem::quit(None); } +} +mod gated { + #[cfg(unix)] + use other_menu as muda; + fn menu() { let f = muda::PredefinedMenuItem::quit(None); } +} +"#; + assert_eq!(lines(&predefined_quit([("src/menu.rs", source)])), vec![6, 10, 19]); +} + #[test] fn predefined_quit_ignores_a_bare_name_that_another_import_or_a_local_type_binds_in_its_scope() { let imported = r#" @@ -1167,6 +1193,65 @@ fn a_long_alias_of_std_time_shared_by_many_use_leaves_is_read_without_copying_it assert_eq!(lines(&std_instant([("src/wide.rs", source.as_str())])), vec![2]); } +#[test] +fn a_use_past_the_path_limits_still_binds_its_name() { + let segment = r#" +use other_menu::MenuItemWithAnExceptionallyLongName as PredefinedMenuItem; +fn quit() { PredefinedMenuItem::quit(None); } +"#; + let length = r#" +use a::b::c::d::e::f::g::h::Item as PredefinedMenuItem; +fn quit() { PredefinedMenuItem::quit(None); } +"#; + let shared = r#" +use other_menu::MenuItemWithAnExceptionallyLongName::{self as PredefinedMenuItem}; +fn quit() { PredefinedMenuItem::quit(None); } +"#; + assert!(predefined_quit([("src/menu.rs", segment), ("src/len.rs", length), ("src/shared.rs", shared)]).is_empty()); + + // A path into this crate past the limits may still be a re-export of muda's type. + let local = r#" +use crate::module_with_an_exceptionally_long_name::PredefinedMenuItem; +fn quit() { PredefinedMenuItem::quit(None); } +"#; + assert_eq!(lines(&predefined_quit([("src/local.rs", local)])), vec![3]); + + let clock = r#" +use std::time as t; +fn now() { + use other_clock::ClockModuleWithAnExceptionallyLongName as t; + let _ = t::Instant::now(); +} +fn later() { + use other_clock::ClockModuleWithAnExceptionallyLongName::{self as t}; + let _ = t::Instant::now(); +} +fn web() { let _ = t::Instant::now(); } +"#; + assert_eq!(lines(&std_instant([("src/clock.rs", clock)])), vec![11]); +} + +#[test] +fn std_instant_reports_an_underscore_import_of_instant_in_a_group() { + let source = r#" +use std::{time::Instant as _}; +use std::time::{Instant as _}; +use std::time::Instant as _; +use std::time::{self as _}; +"#; + assert_eq!(lines(&std_instant([("src/clock.rs", source)])), vec![2, 3, 4]); + assert!(predefined_quit([("src/menu.rs", "use muda::{PredefinedMenuItem as _};\nfn f() { _::quit(); }\n")]).is_empty()); +} + +#[test] +fn std_instant_keeps_an_import_that_an_alias_in_a_nested_module_shares_a_name_with() { + let source = r#" +mod unrelated { use ::std::time as std; } +use std::{time::Instant}; +"#; + assert_eq!(lines(&std_instant([("src/clock.rs", source)])), vec![3]); +} + fn finding_paths(findings: &[Finding]) -> Vec<&str> { findings.iter().map(|f| f.path.as_str()).collect() } @@ -1345,6 +1430,36 @@ fn std_instant_checks_module_files_declared_deeper_than_its_nesting_limit() { assert!(std_instant(files).is_empty()); } +#[test] +fn std_instant_checks_a_crate_root_that_a_disabled_declaration_names() { + let lib = r#" +#[cfg(any())] +#[path = "lib.rs"] +mod never; + +fn web() { + std::time::Instant::now(); +} +"#; + assert_eq!(lines(&std_instant([("src/lib.rs", lib)])), vec![7]); + + // A cycle of two files that only each other name, through declarations the web build leaves out. + let a = "#[cfg(unix)]\n#[path = \"b.rs\"]\nmod b;\nfn web() { std::time::Instant::now(); }\n"; + let b = "#[cfg(unix)]\n#[path = \"a.rs\"]\nmod a;\n"; + assert_eq!(finding_paths(&std_instant([("src/a.rs", a), ("src/b.rs", b)])), vec!["src/a.rs"]); + + // In a cycle with `lib.rs`, only `lib.rs` is a crate root, so its native-only module stays out. + let lib = "#[cfg(unix)]\n#[path = \"a.rs\"]\nmod a;\nfn web() {}\n"; + let a = "#[cfg(any())]\n#[path = \"lib.rs\"]\nmod root;\nuse std::time::Instant;\n"; + assert!(std_instant([("src/lib.rs", lib), ("src/a.rs", a)]).is_empty()); + + // A cycle that a crate root reaches keeps its native-only member out. + let lib = "mod a;\n"; + let a = "#[cfg(unix)]\nmod b;\n"; + let b = "#[path = \"../a.rs\"]\nmod again;\nuse std::time::Instant;\n"; + assert!(std_instant([("src/lib.rs", lib), ("src/a.rs", a), ("src/a/b.rs", b)]).is_empty()); +} + #[test] fn wgsl_integer_literals_are_not_floats() { let shader = r#" From 7ce5c2cc3d1d599cf0fd9d477fd8b49b2da903d6 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 20:08:41 -0800 Subject: [PATCH 15/33] craft-testkit: guards read blocks in a native cfg if condition, renames through a local muda and cfg-gated time shadows - A native-only `if`, `while`, `match` or `for` whose condition holds a block expression (`if { ready } { ... }`, `while !{ x }`, `unsafe`, `loop`, `async` and labeled blocks) is covered up to its real body, so `std_instant` skips the body. - `predefined_quit` no longer follows `use muda::PredefinedMenuItem as Item;` or `type Alias = muda::PredefinedMenuItem;` when the braces around it bind `muda` to something else (`use other_menu as muda;`). `::muda::` still names the crate. - In `std_instant`, a `use` or `mod` that binds an alias name to something else and carries its own `cfg` attribute that may be false on `wasm32-unknown-unknown` no longer hides an outer `use std::time as clock;`. --- crates/testkit/src/guards.rs | 158 ++++++++++++++++++++++++--------- crates/testkit/tests/guards.rs | 87 ++++++++++++++++++ 2 files changed, 205 insertions(+), 40 deletions(-) diff --git a/crates/testkit/src/guards.rs b/crates/testkit/src/guards.rs index 1515160dd9..f68c628b5e 100644 --- a/crates/testkit/src/guards.rs +++ b/crates/testkit/src/guards.rs @@ -472,6 +472,8 @@ struct UseLeaf { start: usize, /// Index of the alias of `std::time` that the path was read through, when [`use_leaves`] was given one. alias: Option, + /// Whether the path starts with `::`, so that its first segment names a crate. + absolute: bool, } impl UseLeaf { @@ -495,7 +497,7 @@ fn use_leaves(toks: &[Token], time_aliases: &BTreeSet) -> Vec { let end = (i + 1..toks.len()).find(|&j| toks[j].is_punct(';')).unwrap_or(toks.len()); let mut pos = i + 1; let mut prefix = Vec::new(); - parse_use_tree(&toks[..end], &mut pos, &mut prefix, (start, None), &mut leaves, time_aliases, 0); + parse_use_tree(&toks[..end], &mut pos, &mut prefix, (start, None, false), &mut leaves, time_aliases, 0); i = end; } else { i += 1; @@ -508,14 +510,16 @@ fn parse_use_tree( toks: &[Token], pos: &mut usize, prefix: &mut Vec>, - // The index of the `use` keyword, and of the alias of `std::time` that `prefix` was read through. - (start, mut via): (usize, Option), + // The index of the `use` keyword, the alias of `std::time` that `prefix` was read through, and whether + // the path starts with `::`. + (start, mut via, mut absolute): (usize, Option, bool), out: &mut Vec, time_aliases: &BTreeSet, depth: usize, ) { let base = prefix.len(); if toks.get(*pos).is_some_and(|t| t.is_punct(':')) && toks.get(*pos + 1).is_some_and(|t| t.is_punct(':')) { + absolute |= prefix.is_empty(); *pos += 2; } // A leaf is reported on the line where its path starts in this tree, not where its last name is. @@ -562,14 +566,14 @@ fn parse_use_tree( }; if bound.is_some() { let root = prefix.first().cloned().or_else(|| Some(Rc::from(name.as_str()))); - out.push(UseLeaf { path, name: bound, root, line, start, alias: via }); + out.push(UseLeaf { path, name: bound, root, line, start, alias: via, absolute }); } break; } Kind::Punct('*') => { if prefix.len() <= MAX_USE_PATH && short_segments(prefix) { let path = prefix.iter().map(|segment| segment.to_string()).collect(); - out.push(UseLeaf { path, name: None, root: prefix.first().cloned(), line, start, alias: via }); + out.push(UseLeaf { path, name: None, root: prefix.first().cloned(), line, start, alias: via, absolute }); } *pos += 1; break; @@ -583,7 +587,7 @@ fn parse_use_tree( } let before = *pos; if !t.is_punct(',') && depth < MAX_NESTING { - parse_use_tree(toks, pos, prefix, (start, via), out, time_aliases, depth + 1); + parse_use_tree(toks, pos, prefix, (start, via, absolute), out, time_aliases, depth + 1); } if *pos == before { *pos += 1; @@ -744,6 +748,20 @@ fn starts_block(toks: &[Token], j: usize) -> bool { } } +/// Whether the `{` at `toks[j]`, in the condition, scrutinee or iterator of an `if`, `while`, `match` or +/// `for`, stands where an operand is still needed, so it opens a block expression rather than the body: +/// right after the keyword, after `in`, after the `=` of a `let`, after an operator or `!`, after +/// `unsafe`, `const`, `loop`, `async` or `async move`, or after a loop label's `:`. +fn operand_expected(toks: &[Token], j: usize) -> bool { + let Some(k) = j.checked_sub(1) else { return false }; + match &toks[k].kind { + Kind::Ident(prev) => matches!(prev.as_str(), "if" | "while" | "match" | "in" | "unsafe" | "const" | "loop" | "async" | "move"), + Kind::Punct('=' | '+' | '-' | '*' | '/' | '%' | '^' | '|' | '&' | '<' | '>' | '!') => true, + Kind::Punct(':') => k.checked_sub(1).is_some_and(|l| toks[l].kind == Kind::Other), + _ => false, + } +} + /// The index after the item, statement, field or match arm that starts at `start`, or with `inner`, the /// index of the bracket that closes the enclosing scope. /// @@ -757,7 +775,9 @@ fn starts_block(toks: &[Token], j: usize) -> bool { /// 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 +/// condition, scrutinee or iterator. A `{` where the condition still needs an operand (see +/// [`operand_expected`]) opens a block expression in it, as in `if { ready() } { ... }`, and the body is +/// the next `{` after that block. 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. /// @@ -801,7 +821,11 @@ fn item_end(toks: &[Token], start: usize, inner: bool) -> usize { 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; + // A `{` where the condition still needs an operand opens a block expression inside it + // (`if { ready() } { ... }`); the body's `{` comes after the condition's last operand. + if !operand_expected(toks, j) { + condition = Condition::Done; + } depth += 1; } Kind::Ident(k) if at_top && VALUE_KEYWORDS.contains(&k.as_str()) => head = false, @@ -912,6 +936,48 @@ fn cfg_covered(toks: &[Token], any: bool) -> Vec { skip } +/// The index of the keyword of every item that carries an outer `cfg` attribute of its own whose predicate +/// is not known to be true on `wasm32-unknown-unknown`, so the item may be absent from the web build: the +/// token after the item's outer attributes and its visibility (`pub`, `pub(...)`). +fn cfg_items(toks: &[Token]) -> BTreeSet { + let mut items = BTreeSet::new(); + let mut i = 0; + while i < toks.len() { + let cfg = toks[i].is_punct('#') + && toks.get(i + 1).is_some_and(|t| t.is_punct('[')) + && toks.get(i + 2).is_some_and(|t| t.is_ident("cfg")) + && toks.get(i + 3).is_some_and(|t| t.is_punct('(')); + if !cfg { + i += 1; + continue; + } + let close = matching_close(toks, i + 1); + if close >= toks.len() { + break; + } + let mut pos = i + 4; + if eval_cfg(&toks[..close], &mut pos, 0) == Tri::True { + i = close + 1; + continue; + } + let mut item = close + 1; + while item < toks.len() && toks[item].is_punct('#') && toks.get(item + 1).is_some_and(|t| t.is_punct('[')) { + item = matching_close(toks, item + 1).saturating_add(1); + } + if toks.get(item).is_some_and(|t| t.is_ident("pub")) { + item += 1; + if toks.get(item).is_some_and(|t| t.is_punct('(')) { + item = matching_close(toks, item).saturating_add(1); + } + } + if item < toks.len() { + items.insert(item); + } + i = item.max(i + 1); + } + items +} + /// A module declaration, `mod name;` or the head of `mod name { ... }`. #[derive(Debug, Clone)] struct ModName { @@ -1351,7 +1417,8 @@ fn report(findings: &mut Vec, path: &str, content: &str, lines: &BTreeS /// braces binding it bind only to something else (`use other_menu as muda;`, `mod muda`), read like a name /// used on its own below; `::muda::PredefinedMenuItem` always names the crate. It also follows a `use` or a `type` alias that renames /// muda's type (`use muda::PredefinedMenuItem as Item;` then `Item::quit`); a rename of another crate's -/// `PredefinedMenuItem` is not followed. +/// `PredefinedMenuItem` is not followed, including one through a name `muda` that the braces around the +/// `use` or `type` bind to something else, read as for a qualified path. /// /// A name used on its own (`PredefinedMenuItem::quit`, `Item::quit`) is read in the innermost braces /// around it, within its module, or the file, that bind the name. It is reported when those braces @@ -1372,8 +1439,36 @@ where let content = file.content(); let toks = lex_rust(content); let leaves = use_leaves(&toks, &BTreeSet::new()); - let is_muda = |leaf: &UseLeaf| leaf.path == ["muda", "PredefinedMenuItem"]; let (around, opener) = brace_scopes(&toks); + let gated = cfg_covered(&toks, true); + // For each pair of braces (`None` for the file), whether a `use` in it binds the name `muda` to the + // crate, and whether a `use` or a `mod` in it binds `muda` to something else. A binding inside an + // item with a `cfg` attribute may not apply on the platform the guard protects, and a path into + // this crate (`crate::`, `self::`, `super::`) may lead to a re-export of the crate, so neither + // counts as something else. + let mut crate_bound: BTreeMap, (bool, bool)> = BTreeMap::new(); + for leaf in leaves.iter().filter(|leaf| leaf.binding() == Some("muda")) { + let local = leaf.root.as_deref().is_some_and(|s| matches!(s, "crate" | "self" | "super")); + let entry = around.get(leaf.start).copied().flatten(); + if leaf.path == ["muda"] { + crate_bound.entry(entry).or_default().0 = true; + } else if !local && !gated.get(leaf.start).copied().unwrap_or(false) { + crate_bound.entry(entry).or_default().1 = true; + } + } + for (i, t) in toks.iter().enumerate() { + if t.is_ident("muda") && i.checked_sub(1).is_some_and(|k| toks[k].is_ident("mod")) && !gated[i] { + crate_bound.entry(around[i]).or_default().1 = true; + } + } + // Whether a relative path's first segment `muda`, read from `toks[at]`, names the crate: unless the + // innermost braces around it that bind `muda` bind it only to something else. + let crate_at = |at: usize| !matches!(lookup(&toks, &around, at, |scope| crate_bound.get(&scope).copied()), Some(Some((false, true)))); + // Whether `muda` at `i` names the crate: after a leading `::` it always does. + let crate_is_muda = |i: usize| (i >= 2 && toks[i - 1].is_punct(':') && toks[i - 2].is_punct(':')) || crate_at(i); + // Whether a `use` leaf imports muda's type: its path is `muda::PredefinedMenuItem`, and `muda` names + // the crate where the `use` is. + let is_muda = |leaf: &UseLeaf| leaf.path == ["muda", "PredefinedMenuItem"] && (leaf.absolute || crate_at(leaf.start)); // Whether the braces opened at `o` are the body of an `impl` or a `trait`, whose `type` items are // associated types rather than names in scope. The head is read back from `o` to the `;`, `{` or // `}` before it, stepping over a block in angle brackets (`impl Foo<{ N }>`), for at most @@ -1434,6 +1529,7 @@ where j += 2; } toks.get(j).is_some_and(|t| t.is_ident("muda")) + && crate_is_muda(j) && then_path(&toks, j + 1, |s| s == "PredefinedMenuItem") && toks.get(j + 4).is_some_and(|t| t.is_punct(';')) }; @@ -1454,7 +1550,6 @@ where // type alias in it binds the name to muda's type, and whether a `use` or an item definition in it // binds the name to another type. A binding to another type inside an item with a `cfg` // attribute may not apply on the platform the guard protects, so it is left out. - let gated = cfg_covered(&toks, true); let mut bound: BTreeMap<(&str, Option), (bool, bool)> = BTreeMap::new(); for leaf in &leaves { let Some(name) = leaf.binding().filter(|name| names.contains(name)) else { continue }; @@ -1501,30 +1596,6 @@ where Some(Some((muda, other))) => muda || !other, Some(None) => name == "PredefinedMenuItem", }; - // For each pair of braces (`None` for the file), whether a `use` in it binds the name `muda` to the - // crate, and whether a `use` or a `mod` in it binds `muda` to something else, with the same - // exceptions as for the type's names. - let mut crate_bound: BTreeMap, (bool, bool)> = BTreeMap::new(); - for leaf in leaves.iter().filter(|leaf| leaf.binding() == Some("muda")) { - let local = leaf.root.as_deref().is_some_and(|s| matches!(s, "crate" | "self" | "super")); - let entry = around.get(leaf.start).copied().flatten(); - if leaf.path == ["muda"] { - crate_bound.entry(entry).or_default().0 = true; - } else if !local && !gated.get(leaf.start).copied().unwrap_or(false) { - crate_bound.entry(entry).or_default().1 = true; - } - } - for (i, t) in toks.iter().enumerate() { - if t.is_ident("muda") && i.checked_sub(1).is_some_and(|k| toks[k].is_ident("mod")) && !gated[i] { - crate_bound.entry(around[i]).or_default().1 = true; - } - } - // Whether `muda` at `i` names the crate: after a leading `::` it always does, and otherwise unless - // the innermost braces around it that bind `muda` bind it only to something else. - let crate_is_muda = |i: usize| { - let absolute = i >= 2 && toks[i - 1].is_punct(':') && toks[i - 2].is_punct(':'); - absolute || !matches!(lookup(&toks, &around, i, |scope| crate_bound.get(&scope).copied()), Some(Some((false, true)))) - }; let mut lines = BTreeSet::new(); for (i, tok) in toks.iter().enumerate() { let Kind::Ident(name) = &tok.kind else { continue }; @@ -1588,7 +1659,9 @@ where /// * **Limitations**: This is a lexical source guard. It does not expand macros, resolve paths through other /// modules or re-exports, or rename `std` itself (`use std as s;`). An alias of `std::time` counts inside the /// braces of its `use` (or the file), down to but not into the body of a nested `mod`; nearer braces whose -/// `use` or `mod` binds the same name to something else hide it. +/// `use` or `mod` binds the same name to something else hide it, unless that `use` or `mod` carries a `cfg` +/// attribute of its own that is not known to be true on `wasm32-unknown-unknown`, which may leave it out of +/// the web build. pub fn std_instant(files: I) -> Vec where I: IntoIterator, @@ -1622,14 +1695,19 @@ where .filter_map(|leaf| leaf.binding().map(str::to_owned)) .collect(); // For each alias name and each pair of braces (`None` for the file), whether a `use` in it binds - // the name to `std::time`, and whether a `use` or a `mod` in it binds the name to something else. + // the name to `std::time`, and whether a `use` or a `mod` binds the name to something else, unless + // its own `cfg` attribute may be false on the web. let (around, _) = brace_scopes(&toks); + let gated = cfg_items(&toks); let mut bound: BTreeMap<(&str, Option), (bool, bool)> = BTreeMap::new(); for leaf in &leaves { let Some(name) = leaf.binding().filter(|name| modules.contains(*name)) else { continue }; - if !skip.get(leaf.start).copied().unwrap_or(false) { + let time = leaf.path == ["std", "time"]; + // A `use` of something else that carries a `cfg` attribute of its own that may be false on the + // web may be absent from the web build, so it does not hide an outer alias. + if !skip.get(leaf.start).copied().unwrap_or(false) && (time || !gated.contains(&leaf.start)) { let entry = bound.entry((name, around.get(leaf.start).copied().flatten())).or_default(); - if leaf.path == ["std", "time"] { + if time { entry.0 = true; } else { entry.1 = true; @@ -1640,7 +1718,7 @@ where if let Kind::Ident(name) = &t.kind && modules.contains(name) && !skip[i] - && i.checked_sub(1).is_some_and(|k| toks[k].is_ident("mod")) + && i.checked_sub(1).is_some_and(|k| toks[k].is_ident("mod") && !gated.contains(&k)) { bound.entry((name.as_str(), around[i])).or_default().1 = true; } diff --git a/crates/testkit/tests/guards.rs b/crates/testkit/tests/guards.rs index a7a4f67963..88f068f472 100644 --- a/crates/testkit/tests/guards.rs +++ b/crates/testkit/tests/guards.rs @@ -472,6 +472,32 @@ mod gated { assert_eq!(lines(&predefined_quit([("src/menu.rs", source)])), vec![6, 10, 19]); } +#[test] +fn predefined_quit_ignores_a_rename_through_a_local_binding_of_muda() { + let source = r#" +use other_menu as muda; +use muda::PredefinedMenuItem as Item; +type Alias = muda::PredefinedMenuItem; +fn menu() { + let a = Item::quit(None); + let b = Alias::quit(None); +} +mod absolute { + use other_menu as muda; + use ::muda::PredefinedMenuItem as Item; + type Alias = ::muda::PredefinedMenuItem; + use ::{muda::PredefinedMenuItem as Grouped}; + fn menu() { let c = Item::quit(None); let d = Alias::quit(None); let e = Grouped::quit(None); } +} +mod crate_root { + use muda::PredefinedMenuItem as Item; + type Alias = muda::PredefinedMenuItem; + fn menu() { let f = Item::quit(None); let g = Alias::quit(None); } +} +"#; + assert_eq!(lines(&predefined_quit([("src/menu.rs", source)])), vec![14, 19]); +} + #[test] fn predefined_quit_ignores_a_bare_name_that_another_import_or_a_local_type_binds_in_its_scope() { let imported = r#" @@ -591,6 +617,34 @@ fn run() { assert_eq!(lines(&std_instant([("src/lib.rs", source)])), vec![4, 5, 11, 16]); } +#[test] +fn std_instant_keeps_an_alias_that_a_cfg_gated_import_may_shadow() { + let source = r#" +use std::time as clock; +fn now() { + #[cfg(feature = "web-clock")] + use web_time as clock; + let a = clock::Instant::now(); +} +fn gated() { + #[cfg(feature = "web-clock")] + mod clock {} + let b = clock::Instant::now(); +} +#[cfg(feature = "web-clock")] +fn web() { + use web_time as clock; + let c = clock::Instant::now(); +} +fn wasm() { + #[cfg(target_arch = "wasm32")] + use web_time as clock; + let d = clock::Instant::now(); +} +"#; + assert_eq!(lines(&std_instant([("src/lib.rs", source)])), vec![6, 11]); +} + #[test] fn std_instant_ignores_an_alias_that_only_a_native_cfg_imports() { let source = r#" @@ -840,6 +894,39 @@ fn run(state: State, other: State) { assert_eq!(lines(&std_instant([("src/run.rs", source)])), vec![6, 9, 12, 15, 18]); } +#[test] +fn std_instant_ends_a_native_cfg_if_at_its_body_not_at_a_block_in_its_condition() { + let source = r#" +fn run(ready: bool, items: Vec) { + #[cfg(unix)] + if { ready } { let _a = std::time::Instant::now(); } + let b = std::time::Instant::now(); + #[cfg(unix)] + while !{ ready } { let _c = std::time::Instant::now(); } + let d = std::time::Instant::now(); + #[cfg(unix)] + if ready && unsafe { check() } { let _e = std::time::Instant::now(); } + let f = std::time::Instant::now(); + #[cfg(unix)] + for item in { items } { let _g = std::time::Instant::now(); } + let h = std::time::Instant::now(); + #[cfg(unix)] + match { 1 } { _ => { let _i = std::time::Instant::now(); } } + let j = std::time::Instant::now(); + #[cfg(unix)] + if let true = { ready } { let _k = std::time::Instant::now(); } + let l = std::time::Instant::now(); + #[cfg(unix)] + if loop { break ready } { let _m = std::time::Instant::now(); } + let n = std::time::Instant::now(); + #[cfg(unix)] + if async move { ready }.await { let _o = std::time::Instant::now(); } + let p = std::time::Instant::now(); +} +"#; + assert_eq!(lines(&std_instant([("src/run.rs", source)])), vec![5, 8, 11, 14, 17, 20, 23, 26]); +} + #[test] fn std_instant_ends_a_native_cfg_let_else_and_match_with_struct_patterns_where_they_end() { let source = r#" From 2ec3ffee2be8928d625e363e32c24439f9ff18d6 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 20:12:06 -0800 Subject: [PATCH 16/33] craft-testkit: the CACHEDIR.TAG FIFO test runs without a timeout The test opens the FIFO for reading and writing and puts the signature in the pipe before the scan. A scan that opened the FIFO would read the signature and leave out `kept.rs` instead of blocking, so the test no longer waits on a thread with a 30-second bound. --- crates/testkit/tests/guards.rs | 16 +++++++--------- 1 file changed, 7 insertions(+), 9 deletions(-) diff --git a/crates/testkit/tests/guards.rs b/crates/testkit/tests/guards.rs index 88f068f472..56501a020e 100644 --- a/crates/testkit/tests/guards.rs +++ b/crates/testkit/tests/guards.rs @@ -1698,15 +1698,13 @@ fn rust_sources_does_not_open_a_cachedir_tag_fifo() { return; } } - let root = dir.path().to_path_buf(); - let (tx, rx) = std::sync::mpsc::channel(); - std::thread::spawn(move || { - let _ = tx.send(craft_testkit::rust_sources(root)); - }); - let sources = rx - .recv_timeout(std::time::Duration::from_secs(30)) - .expect("rust_sources returns instead of blocking on the CACHEDIR.TAG FIFO") - .expect("rust_sources"); + // Opening the FIFO for reading and writing does not wait for another end on Linux or macOS. The + // signature waits in the pipe, so a scan that opened the FIFO would read it and leave out `kept.rs` + // without blocking. + let mut pipe = std::fs::OpenOptions::new().read(true).write(true).open(&fifo).expect("open FIFO"); + std::io::Write::write_all(&mut pipe, b"Signature: 8a477f597d28d172789f06886806bc55\n").expect("write signature"); + let sources = craft_testkit::rust_sources(dir.path()).expect("rust_sources"); + drop(pipe); assert_eq!(file_names(&sources), vec!["kept.rs", "lib.rs"]); } From da534b341f88539b92c1c4497bbdc6efdd144d0d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 19:53:01 -0800 Subject: [PATCH 17/33] craft-testkit: guards follow names the muda crate is imported under predefined_quit reports menu::PredefinedMenuItem::quit after use muda as menu;, use muda::{self as menu}; or extern crate muda as menu;, and reads those names in the scope of each path and import. A leading :: names an external crate, an extern crate of another crate shadows the name, and use muda as menu; binds menu to the crate only where muda names it. --- crates/testkit/src/guards.rs | 166 ++++++++++++++++++++++++++------- crates/testkit/tests/guards.rs | 81 ++++++++++++++++ 2 files changed, 211 insertions(+), 36 deletions(-) diff --git a/crates/testkit/src/guards.rs b/crates/testkit/src/guards.rs index f68c628b5e..3541ea21b7 100644 --- a/crates/testkit/src/guards.rs +++ b/crates/testkit/src/guards.rs @@ -472,7 +472,7 @@ struct UseLeaf { start: usize, /// Index of the alias of `std::time` that the path was read through, when [`use_leaves`] was given one. alias: Option, - /// Whether the path starts with `::`, so that its first segment names a crate. + /// Whether the path starts with `::`, so that its first segment names an external crate. absolute: bool, } @@ -1404,6 +1404,98 @@ fn report(findings: &mut Vec, path: &str, content: &str, lines: &BTreeS } } +/// For each pair of braces (`None` for the file) and a name: whether a binding in those braces binds the +/// name to the muda crate, and whether one binds it to something else. +type CrateBindings<'a> = BTreeMap<(&'a str, Option), (bool, bool)>; + +/// The names of the muda crate in a file, and where each is bound. The names are `muda` itself and each +/// name that `use muda as m;`, `use muda::{self as m};` or `extern crate muda as m;` gives it. For each +/// name and each pair of braces, the bindings record whether a `use` or an `extern crate` in them binds +/// the name to the crate, and whether a `use`, an `extern crate` or a `mod` in them binds it to something +/// else. A binding to something else inside an item with a `cfg` attribute, or through `crate::`, `self::` +/// or `super::` (which may be a re-export of the crate), is left out. +fn muda_crate_bindings<'a>( + toks: &'a [Token], + leaves: &'a [UseLeaf], + around: &[Option], + gated: &[bool], +) -> (BTreeSet<&'a str>, CrateBindings<'a>) { + // Each `extern crate c;` or `extern crate c as n;`: whether `c` is muda, and the index of the name it + // binds. + let mut externs: Vec<(bool, &'a str, usize)> = Vec::new(); + for i in 0..toks.len() { + if toks[i].is_ident("extern") + && toks.get(i + 1).is_some_and(|t| t.is_ident("crate")) + && let Some(Kind::Ident(krate)) = toks.get(i + 2).map(|t| &t.kind) + { + let at = if toks.get(i + 3).is_some_and(|t| t.is_ident("as")) { i + 4 } else { i + 2 }; + if let Some(Kind::Ident(name)) = toks.get(at).map(|t| &t.kind) + && name != "_" + { + externs.push((krate == "muda", name.as_str(), at)); + } + } + } + let mut names: BTreeSet<&'a str> = BTreeSet::from(["muda"]); + names.extend(leaves.iter().filter(|leaf| leaf.path == ["muda"]).filter_map(UseLeaf::binding)); + names.extend(externs.iter().filter(|&&(muda, _, _)| muda).map(|&(_, name, _)| name)); + let mut bound: CrateBindings<'a> = BTreeMap::new(); + // `use muda as m;` binds `m` to the crate only where `muda` itself names the crate, so it is read + // after every other binding. + let renames = |leaf: &UseLeaf| leaf.path == ["muda"] && leaf.binding() != Some("muda"); + for leaf in leaves.iter().filter(|leaf| !renames(leaf)) { + let Some(name) = leaf.binding().filter(|name| names.contains(name)) else { continue }; + let local = leaf.root.as_deref().is_some_and(|s| matches!(s, "crate" | "self" | "super")); + let entry = bound.entry((name, around.get(leaf.start).copied().flatten())); + if leaf.path == ["muda"] { + entry.or_default().0 = true; + } else if !local && !gated.get(leaf.start).copied().unwrap_or(false) { + entry.or_default().1 = true; + } + } + for &(muda, name, at) in &externs { + if !names.contains(name) { + continue; + } + if muda { + bound.entry((name, around[at])).or_default().0 = true; + } else if !gated[at] { + bound.entry((name, around[at])).or_default().1 = true; + } + } + for (i, t) in toks.iter().enumerate() { + if let Kind::Ident(name) = &t.kind + && names.contains(name.as_str()) + && i.checked_sub(1).is_some_and(|k| toks[k].is_ident("mod")) + && !gated[i] + { + bound.entry((name, around[i])).or_default().1 = true; + } + } + let mut renamed = Vec::new(); + for leaf in leaves.iter().filter(|leaf| renames(leaf)) { + let Some(name) = leaf.binding() else { continue }; + let crate_here = + leaf.absolute || !matches!(lookup(toks, around, leaf.start, |scope| bound.get(&("muda", scope)).copied()), Some(Some((false, true)))); + let local = leaf.root.as_deref().is_some_and(|s| matches!(s, "crate" | "self" | "super")); + let scope = around.get(leaf.start).copied().flatten(); + if crate_here { + renamed.push((name, scope, true)); + } else if !local && !gated.get(leaf.start).copied().unwrap_or(false) { + renamed.push((name, scope, false)); + } + } + for (name, scope, muda) in renamed { + let entry = bound.entry((name, scope)).or_default(); + if muda { + entry.0 = true; + } else { + entry.1 = true; + } + } + (names, bound) +} + /// Guard: detects direct calls to `muda`'s predefined Quit menu item. /// /// Using `PredefinedMenuItem::quit` connects the macOS menu directly to `NSApplication terminate:`, @@ -1415,10 +1507,13 @@ fn report(findings: &mut Vec, path: &str, content: &str, lines: &BTreeS /// is reported too. A path that names the type through another crate or module, such as /// `other::PredefinedMenuItem::quit`, is not, and neither is a path through a name `muda` that the innermost /// braces binding it bind only to something else (`use other_menu as muda;`, `mod muda`), read like a name -/// used on its own below; `::muda::PredefinedMenuItem` always names the crate. It also follows a `use` or a `type` alias that renames -/// muda's type (`use muda::PredefinedMenuItem as Item;` then `Item::quit`); a rename of another crate's -/// `PredefinedMenuItem` is not followed, including one through a name `muda` that the braces around the -/// `use` or `type` bind to something else, read as for a qualified path. +/// used on its own below; `::muda::PredefinedMenuItem` always names the crate. A name that the crate is +/// imported under (`use muda as menu;`, `use muda::{self as menu};`, `extern crate muda as menu;`) is read +/// like `muda` in the braces that bind it, so `menu::PredefinedMenuItem::quit` is reported there. It also +/// follows a `use` or a `type` alias that renames muda's type (`use muda::PredefinedMenuItem as Item;` then +/// `Item::quit`); a rename of another crate's `PredefinedMenuItem` is not followed, including one through a +/// name `muda` that the braces around the `use` or `type` bind to something else, read as for a qualified +/// path. /// /// A name used on its own (`PredefinedMenuItem::quit`, `Item::quit`) is read in the innermost braces /// around it, within its module, or the file, that bind the name. It is reported when those braces @@ -1441,34 +1536,32 @@ where let leaves = use_leaves(&toks, &BTreeSet::new()); let (around, opener) = brace_scopes(&toks); let gated = cfg_covered(&toks, true); - // For each pair of braces (`None` for the file), whether a `use` in it binds the name `muda` to the - // crate, and whether a `use` or a `mod` in it binds `muda` to something else. A binding inside an - // item with a `cfg` attribute may not apply on the platform the guard protects, and a path into - // this crate (`crate::`, `self::`, `super::`) may lead to a re-export of the crate, so neither - // counts as something else. - let mut crate_bound: BTreeMap, (bool, bool)> = BTreeMap::new(); - for leaf in leaves.iter().filter(|leaf| leaf.binding() == Some("muda")) { - let local = leaf.root.as_deref().is_some_and(|s| matches!(s, "crate" | "self" | "super")); - let entry = around.get(leaf.start).copied().flatten(); - if leaf.path == ["muda"] { - crate_bound.entry(entry).or_default().0 = true; - } else if !local && !gated.get(leaf.start).copied().unwrap_or(false) { - crate_bound.entry(entry).or_default().1 = true; + let (crate_names, crate_bound) = muda_crate_bindings(&toks, &leaves, &around, &gated); + let names_crate = |s: &str| crate_names.contains(s); + // Whether `name`, read at token `i`, names the crate. After a leading `::` only `muda` does. + // Otherwise `muda` does unless the innermost braces around `i` that bind `muda` bind it only to + // something else, and another name of the crate does when those braces bind it to the crate, or + // only to nothing else. + let crate_name_at = |name: &str, i: usize, absolute: bool| { + if absolute || !names_crate(name) { + return name == "muda"; } - } - for (i, t) in toks.iter().enumerate() { - if t.is_ident("muda") && i.checked_sub(1).is_some_and(|k| toks[k].is_ident("mod")) && !gated[i] { - crate_bound.entry(around[i]).or_default().1 = true; + match lookup(&toks, &around, i, |scope| crate_bound.get(&(name, scope)).copied()) { + None => true, + Some(Some((muda, other))) => muda || !other, + Some(None) => name == "muda", } - } - // Whether a relative path's first segment `muda`, read from `toks[at]`, names the crate: unless the - // innermost braces around it that bind `muda` bind it only to something else. - let crate_at = |at: usize| !matches!(lookup(&toks, &around, at, |scope| crate_bound.get(&scope).copied()), Some(Some((false, true)))); - // Whether `muda` at `i` names the crate: after a leading `::` it always does. - let crate_is_muda = |i: usize| (i >= 2 && toks[i - 1].is_punct(':') && toks[i - 2].is_punct(':')) || crate_at(i); - // Whether a `use` leaf imports muda's type: its path is `muda::PredefinedMenuItem`, and `muda` names - // the crate where the `use` is. - let is_muda = |leaf: &UseLeaf| leaf.path == ["muda", "PredefinedMenuItem"] && (leaf.absolute || crate_at(leaf.start)); + }; + // Whether the identifier at `i` names the crate. + let crate_is_muda = |i: usize| { + let Kind::Ident(name) = &toks[i].kind else { return false }; + let absolute = i >= 2 && toks[i - 1].is_punct(':') && toks[i - 2].is_punct(':'); + crate_name_at(name, i, absolute) + }; + // A `use` path to muda's type, read through a name of the crate bound where the `use` is. After + // a leading `::` the first segment is an external crate, so only `muda` names it. + let is_muda = + |leaf: &UseLeaf| leaf.path.len() == 2 && leaf.path[1] == "PredefinedMenuItem" && crate_name_at(&leaf.path[0], leaf.start, leaf.absolute); // Whether the braces opened at `o` are the body of an `impl` or a `trait`, whose `type` items are // associated types rather than names in scope. The head is read back from `o` to the `;`, `{` or // `}` before it, stepping over a block in angle brackets (`impl Foo<{ N }>`), for at most @@ -1518,7 +1611,8 @@ where } s < o && (toks[s].is_ident("impl") || toks[s].is_ident("trait")) }; - // Whether the `type` name at `i` is followed by `= muda::PredefinedMenuItem;` (or `::muda::...`). + // Whether the `type` name at `i` is followed by `= muda::PredefinedMenuItem;` (or `::muda::...`, or + // a name of the crate in place of `muda`). let aliases_muda = |i: usize| { let mut j = i + 1; if !toks.get(j).is_some_and(|t| t.is_punct('=')) { @@ -1528,7 +1622,7 @@ where if toks.get(j).is_some_and(|t| t.is_punct(':')) && toks.get(j + 1).is_some_and(|t| t.is_punct(':')) { j += 2; } - toks.get(j).is_some_and(|t| t.is_ident("muda")) + j < toks.len() && crate_is_muda(j) && then_path(&toks, j + 1, |s| s == "PredefinedMenuItem") && toks.get(j + 4).is_some_and(|t| t.is_punct(';')) @@ -1602,10 +1696,10 @@ where if !names.contains(name.as_str()) { continue; } - // A qualified name counts only as `muda::PredefinedMenuItem` (or `::muda::...`), not as - // another crate's or module's type of the same name. + // A qualified name counts only as `muda::PredefinedMenuItem` (or `::muda::...`, or a name of the + // crate in place of `muda`), not as another crate's or module's type of the same name. let named = if continues_a_path(&toks, i) { - name == "PredefinedMenuItem" && toks[i - 3].is_ident("muda") && !continues_a_path(&toks, i - 3) && crate_is_muda(i - 3) + name == "PredefinedMenuItem" && !continues_a_path(&toks, i - 3) && crate_is_muda(i - 3) } else { bare_is_muda(name, i) }; diff --git a/crates/testkit/tests/guards.rs b/crates/testkit/tests/guards.rs index 56501a020e..64f54bfc5a 100644 --- a/crates/testkit/tests/guards.rs +++ b/crates/testkit/tests/guards.rs @@ -498,6 +498,87 @@ mod crate_root { assert_eq!(lines(&predefined_quit([("src/menu.rs", source)])), vec![14, 19]); } +#[test] +fn predefined_quit_follows_a_name_that_the_muda_crate_is_imported_under() { + let source = r#" +use muda as menu; +fn menu_bar() { + let a = menu::PredefinedMenuItem::quit(None); + let b = ::quit(None); + let c = ::menu::PredefinedMenuItem::quit(None); +} +mod grouped { + use muda::{self as m}; + fn menu_bar() { let d = m::PredefinedMenuItem::quit(None); } +} +mod renamed { + extern crate muda as native; + type Item = native::PredefinedMenuItem; + fn menu_bar() { let e = native::PredefinedMenuItem::quit(None); let f = Item::quit(None); } +} +mod imported { + use muda::{self as m}; + use m::PredefinedMenuItem as Quit; + fn menu_bar() { let g = Quit::quit(None); } +} +mod unbound { + fn menu_bar() { let h = m::PredefinedMenuItem::quit(None); } +} +mod shadowed { + use other_menu as menu; + fn menu_bar() { let i = menu::PredefinedMenuItem::quit(None); } +} +"#; + assert_eq!(lines(&predefined_quit([("src/menu.rs", source)])), vec![4, 5, 10, 15, 20]); +} + +#[test] +fn predefined_quit_reads_a_crate_name_in_an_import_where_the_import_is() { + let source = r#" +mod native { + use muda as menu; + use menu::PredefinedMenuItem as Item; + type Alias = menu::PredefinedMenuItem; + fn menu_bar() { let a = Item::quit(None); let b = Alias::quit(None); } +} +mod other { + use other_menu as menu; + use menu::PredefinedMenuItem as Item; + type Alias = menu::PredefinedMenuItem; + fn menu_bar() { let c = Item::quit(None); let d = Alias::quit(None); } +} +mod external { + use muda as menu; + use ::menu::PredefinedMenuItem as Item; + type Alias = ::menu::PredefinedMenuItem; + fn menu_bar() { let e = Item::quit(None); let f = Alias::quit(None); } +} +mod grouped { + use muda as menu; + use {::menu::PredefinedMenuItem as Item}; + fn menu_bar() { let g = Item::quit(None); } +} +mod shadowed { + use muda as menu; + fn menu_bar() { + extern crate other_menu as menu; + let h = menu::PredefinedMenuItem::quit(None); + } +} +mod renamed_module { + use other_menu as muda; + use muda as menu; + fn menu_bar() { let i = menu::PredefinedMenuItem::quit(None); } +} +mod renamed_crate { + mod muda {} + use ::muda as menu; + fn menu_bar() { let j = menu::PredefinedMenuItem::quit(None); } +} +"#; + assert_eq!(lines(&predefined_quit([("src/menu.rs", source)])), vec![6, 40]); +} + #[test] fn predefined_quit_ignores_a_bare_name_that_another_import_or_a_local_type_binds_in_its_scope() { let imported = r#" From 989a055a6f0d0f3d8853f83765ce7fd57605ab4d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 12:50:11 -0800 Subject: [PATCH 18/33] craft-testkit: check CACHEDIR.TAG and source files as they are opened is_cache_dir checked CACHEDIR.TAG with symlink_metadata and then opened it in a second step, so a symbolic link or a FIFO put in its place between the two was still opened, and a FIFO could block the open. The same gap applied to each .rs file rust_sources reads. Both now go through open_regular_file. On Unix it opens with O_NOFOLLOW, O_NONBLOCK and O_CLOEXEC through rustix and reads the type from the opened file, so a symbolic link, FIFO or other special file is skipped. On other platforms a symbolic link is skipped before the open and the opened file must be a regular file. Reads stay bounded by the signature length and max_file_bytes. --- Cargo.lock | 3 + crates/testkit/Cargo.toml | 3 + crates/testkit/src/guards.rs | 107 ++++++++++++++++++++++++++++++++--- 3 files changed, 105 insertions(+), 8 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 23bcce0b91..481f28ff1e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2740,6 +2740,9 @@ dependencies = [ [[package]] name = "craft-testkit" version = "0.1.0" +dependencies = [ + "rustix 1.1.5", +] [[package]] name = "craft-text" diff --git a/crates/testkit/Cargo.toml b/crates/testkit/Cargo.toml index d32ed735f4..bfb89fb742 100644 --- a/crates/testkit/Cargo.toml +++ b/crates/testkit/Cargo.toml @@ -10,5 +10,8 @@ publish = false [dependencies] +[target.'cfg(unix)'.dependencies] +rustix = { version = "1.1", default-features = false, features = ["std", "fs"] } + [lints] workspace = true diff --git a/crates/testkit/src/guards.rs b/crates/testkit/src/guards.rs index 3541ea21b7..df160ca8f4 100644 --- a/crates/testkit/src/guards.rs +++ b/crates/testkit/src/guards.rs @@ -2129,16 +2129,44 @@ impl Default for SourceLimits { #[cfg(not(target_arch = "wasm32"))] const CACHEDIR_SIGNATURE: &[u8] = b"Signature: 8a477f597d28d172789f06886806bc55"; +/// Open `path` for reading when it is a regular file. Returns `Ok(None)` when `path` is a symbolic +/// link, a folder, a FIFO or another special file. +/// +/// On Unix the open does not follow a symbolic link (`O_NOFOLLOW`) and does not wait for a writer on a +/// FIFO (`O_NONBLOCK`), and the type is then read from the opened file, so a file replaced between a +/// directory listing and the open is checked as it is when opened. On other platforms a path that is a +/// symbolic link is skipped before the open, and the opened file must be a regular file. +#[cfg(not(target_arch = "wasm32"))] +fn open_regular_file(path: &Path) -> std::io::Result> { + #[cfg(unix)] + let opened = { + use rustix::fs::{Mode, OFlags}; + rustix::fs::open(path, OFlags::RDONLY | OFlags::NOFOLLOW | OFlags::NONBLOCK | OFlags::CLOEXEC, Mode::empty()) + .map(std::fs::File::from) + .map_err(std::io::Error::from) + }; + #[cfg(not(unix))] + let opened = { + if std::fs::symlink_metadata(path)?.file_type().is_symlink() { + return Ok(None); + } + std::fs::File::open(path) + }; + let file = match opened { + Ok(file) => file, + // `O_NOFOLLOW` fails on a symbolic link (ELOOP on Linux and macOS, EMLINK on FreeBSD). + Err(_) if std::fs::symlink_metadata(path).is_ok_and(|m| m.file_type().is_symlink()) => return Ok(None), + Err(err) => return Err(err), + }; + Ok(file.metadata()?.file_type().is_file().then_some(file)) +} + /// Whether `dir` holds a `CACHEDIR.TAG` regular file that starts with [`CACHEDIR_SIGNATURE`]. A marker -/// that is a symbolic link, a folder, a FIFO or another special file is not opened and does not count. +/// that is a symbolic link, a folder, a FIFO or another special file is not read and does not count. #[cfg(not(target_arch = "wasm32"))] fn is_cache_dir(dir: &Path) -> bool { use std::io::Read; - let marker = dir.join("CACHEDIR.TAG"); - if !std::fs::symlink_metadata(&marker).is_ok_and(|m| m.file_type().is_file()) { - return false; - } - let Ok(file) = std::fs::File::open(&marker) else { + let Ok(Some(file)) = open_regular_file(&dir.join("CACHEDIR.TAG")) else { return false; }; let mut head = Vec::with_capacity(CACHEDIR_SIGNATURE.len()); @@ -2208,12 +2236,15 @@ pub fn rust_sources_with_limits(dir: impl AsRef, limits: SourceLimits) -> format!("more than {} Rust source files under {}", limits.max_files, root.display()), )); } + let Some(file) = open_regular_file(&p)? else { + continue; + }; let over_file = || Error::new(ErrorKind::FileTooLarge, format!("{} is larger than {} bytes", p.display(), limits.max_file_bytes)); - if entry.metadata()?.len() > limits.max_file_bytes { + if file.metadata()?.len() > limits.max_file_bytes { return Err(over_file()); } let mut content = String::new(); - std::fs::File::open(&p)?.take(limits.max_file_bytes.saturating_add(1)).read_to_string(&mut content)?; + file.take(limits.max_file_bytes.saturating_add(1)).read_to_string(&mut content)?; let size = content.len() as u64; if size > limits.max_file_bytes { return Err(over_file()); @@ -2244,6 +2275,66 @@ mod tests { use_leaves(&lex_rust(source), &BTreeSet::new()).into_iter().map(|leaf| (leaf.path, leaf.name.map(|name| name.to_string()))).collect() } + /// A new empty folder under the system temporary folder, removed when dropped. + #[cfg(unix)] + struct TempDir(std::path::PathBuf); + + #[cfg(unix)] + impl TempDir { + fn new(tag: &str) -> Self { + let path = std::env::temp_dir().join(format!("craft-testkit-unit-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&path); + std::fs::create_dir_all(&path).expect("create temp dir"); + Self(path) + } + } + + #[cfg(unix)] + impl Drop for TempDir { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } + } + + #[cfg(unix)] + #[test] + fn open_regular_file_opens_a_regular_file() { + let dir = TempDir::new("open_regular"); + let tag = dir.0.join("CACHEDIR.TAG"); + std::fs::write(&tag, super::CACHEDIR_SIGNATURE).expect("write tag"); + assert!(super::open_regular_file(&tag).expect("open").is_some()); + assert!(super::is_cache_dir(&dir.0)); + } + + #[cfg(unix)] + #[test] + fn open_regular_file_does_not_follow_a_symlink() { + let dir = TempDir::new("open_symlink"); + let target = dir.0.join("target.tag"); + std::fs::write(&target, super::CACHEDIR_SIGNATURE).expect("write target"); + let link = dir.0.join("CACHEDIR.TAG"); + std::os::unix::fs::symlink(&target, &link).expect("symlink"); + assert!(super::open_regular_file(&link).expect("open").is_none()); + assert!(!super::is_cache_dir(&dir.0)); + } + + /// The FIFO has no writer, so an open that waited for one would not return. + #[cfg(unix)] + #[test] + fn open_regular_file_does_not_wait_on_a_fifo() { + let dir = TempDir::new("open_fifo"); + let fifo = dir.0.join("CACHEDIR.TAG"); + match std::process::Command::new("mkfifo").arg(&fifo).status() { + Ok(status) if status.success() => {} + other => { + eprintln!("skipped: mkfifo is not available here ({other:?})"); + return; + } + } + assert!(super::open_regular_file(&fifo).expect("open").is_none()); + assert!(!super::is_cache_dir(&dir.0)); + } + #[test] fn use_leaves_keep_no_path_longer_than_the_limit() { let source = format!("use {}{{x, y::z, *}};\nuse std::time::{{Instant, self as t}};\n", "a::".repeat(MAX_USE_PATH)); From 70275fe34d4cd646167c5fe22728e674aea88435 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 13:32:52 -0800 Subject: [PATCH 19/33] craft-testkit: guards read absolute paths through the extern prelude and step over an if or match in a native cfg head - std_instant no longer reads `::m::Instant` or `use ::m::Instant;` through a local alias `m` of `std::time`; a path that starts with `::` names an external crate. - predefined_quit reads a name that `extern crate muda as m;` outside any braces of a crate root adds to the extern prelude like `muda`, with or without a leading `::`, in the root and in every file that a chain of `mod` declarations from it names. - An `if` or `match` expression in the condition, scrutinee or iterator of a native cfg `if`, `while`, `match` or `for` is read to its last block, so the body that follows is covered. --- crates/testkit/src/guards.rs | 194 +++++++++++++++++++++++++++------ crates/testkit/tests/guards.rs | 102 +++++++++++++++++ 2 files changed, 261 insertions(+), 35 deletions(-) diff --git a/crates/testkit/src/guards.rs b/crates/testkit/src/guards.rs index df160ca8f4..945124743d 100644 --- a/crates/testkit/src/guards.rs +++ b/crates/testkit/src/guards.rs @@ -529,7 +529,8 @@ fn parse_use_tree( Kind::Ident(name) => { *pos += 1; if toks.get(*pos).is_some_and(|t| t.is_punct(':')) && toks.get(*pos + 1).is_some_and(|t| t.is_punct(':')) { - if prefix.is_empty() && time_aliases.contains(name) { + // After a leading `::` the first segment names an external crate, never a local alias. + if prefix.is_empty() && !absolute && time_aliases.contains(name) { prefix.extend([Rc::from("std"), Rc::from("time")]); via = Some(*pos - 1); } else { @@ -781,11 +782,21 @@ fn operand_expected(toks: &[Token], j: usize) -> bool { /// `&&` 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. /// +/// An `if` or `match` expression in a condition, scrutinee or iterator, as in +/// `for x in if a { b } else { c } { ... }`, is read to the end of its last block (up to [`MAX_NESTING`] +/// levels of such expressions), and the body is the next `{` after it. +/// /// In the head of an `fn`, `impl`, `trait`, `struct`, `enum` or `union` item, a block inside angle /// brackets (a const generic default or argument such as ``, also in a /// return type or a `where` clause) does not end the item. The `>` of `->` does not close an angle /// bracket. fn item_end(toks: &[Token], start: usize, inner: bool) -> usize { + item_end_at(toks, start, inner, 0) +} + +/// [`item_end`] for an item or, with `nested` above 0, for an `if` or `match` expression inside the head of +/// another one, `nested` levels deep, which ends right after its last block. +fn item_end_at(toks: &[Token], start: usize, inner: bool, nested: usize) -> usize { let mut depth = 0usize; let mut block_item = false; let mut arm = false; @@ -800,6 +811,12 @@ fn item_end(toks: &[Token], start: usize, inner: bool) -> usize { block_item = true; } match &toks[j].kind { + // An `if` or `match` expression in the condition ends at its last block, so its blocks do not + // read as the body. + Kind::Ident(k) if at_top && condition == Condition::Expression && matches!(k.as_str(), "if" | "match") && nested < MAX_NESTING => { + j = item_end_at(toks, j, false, nested + 1).max(j + 1); + continue; + } 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() { @@ -859,12 +876,18 @@ fn item_end(toks: &[Token], start: usize, inner: bool) -> usize { if depth == 0 && *c == '}' && block_item && !inner && condition == Condition::Done && angle == 0 { 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. + // The `if` is stepped over, so it does not read as an `if` inside the condition. if toks.get(j + 2).is_some_and(|t| t.is_ident("if")) { condition = Condition::Expression; + j += 3; + } else { + j += 1; } - j += 1; continue; } + if nested > 0 { + return j + 1; + } if toks.get(j + 1).is_some_and(|t| t.is_punct('.') || t.is_punct('?')) { // A method call, field or `?` after the block continues the expression to its `;` or `,`. block_item = false; @@ -1408,21 +1431,10 @@ fn report(findings: &mut Vec, path: &str, content: &str, lines: &BTreeS /// name to the muda crate, and whether one binds it to something else. type CrateBindings<'a> = BTreeMap<(&'a str, Option), (bool, bool)>; -/// The names of the muda crate in a file, and where each is bound. The names are `muda` itself and each -/// name that `use muda as m;`, `use muda::{self as m};` or `extern crate muda as m;` gives it. For each -/// name and each pair of braces, the bindings record whether a `use` or an `extern crate` in them binds -/// the name to the crate, and whether a `use`, an `extern crate` or a `mod` in them binds it to something -/// else. A binding to something else inside an item with a `cfg` attribute, or through `crate::`, `self::` -/// or `super::` (which may be a re-export of the crate), is left out. -fn muda_crate_bindings<'a>( - toks: &'a [Token], - leaves: &'a [UseLeaf], - around: &[Option], - gated: &[bool], -) -> (BTreeSet<&'a str>, CrateBindings<'a>) { - // Each `extern crate c;` or `extern crate c as n;`: whether `c` is muda, and the index of the name it - // binds. - let mut externs: Vec<(bool, &'a str, usize)> = Vec::new(); +/// Each `extern crate c;` or `extern crate c as n;` in a file: whether `c` is muda, the name it binds, and +/// the index of that name. +fn extern_crates(toks: &[Token]) -> Vec<(bool, &str, usize)> { + let mut externs = Vec::new(); for i in 0..toks.len() { if toks[i].is_ident("extern") && toks.get(i + 1).is_some_and(|t| t.is_ident("crate")) @@ -1436,18 +1448,114 @@ fn muda_crate_bindings<'a>( } } } + externs +} + +/// For each of `paths`, the names that an `extern crate muda as m;` outside any braces of its crate root adds +/// to the crate's extern prelude, so that a path starting with `::m` names muda anywhere in the crate. +/// +/// The crate roots follow Cargo's layout: `src/lib.rs` and `src/main.rs`; `build.rs` and another `lib.rs` or +/// `main.rs` (such as `src/bin/tool/main.rs`) when no `mod` declaration in another of the files names it, +/// plainly or through a `#[path]` attribute; and each file directly in a `bin`, `examples`, `tests` or +/// `benches` folder other than `mod.rs` when no declaration without a `#[path]` attribute names it. A root's +/// names reach every file that a chain of declarations +/// from it names, where a file loaded through a `#[path]` attribute has its modules in its own folder, as +/// [`module_files`] reads them. +fn extern_prelude_names(paths: &[String], contents: &[&str]) -> Vec> { + let mut index: BTreeMap<&str, Vec> = BTreeMap::new(); + for (i, path) in paths.iter().enumerate() { + index.entry(path.as_str()).or_default().push(i); + } + let mut decls: Vec> = Vec::with_capacity(paths.len()); + let mut aliases: Vec> = Vec::with_capacity(paths.len()); + for content in contents { + let toks = lex_rust(content); + decls.push(module_decls(&toks, &vec![false; toks.len()])); + let (around, _) = brace_scopes(&toks); + aliases.push( + extern_crates(&toks).into_iter().filter(|&(muda, _, at)| muda && around[at].is_none()).map(|(_, name, _)| name.to_owned()).collect(), + ); + } + // Node `2 * file` is the file loaded plainly (or as a crate root) and node `2 * file + 1` the file loaded + // through a `#[path]` attribute. Each node lists the nodes its declarations name. + let mut named = vec![false; paths.len()]; + let mut named_plainly = vec![false; paths.len()]; + let edges: Vec> = (0..paths.len() * 2) + .map(|node| { + let (file, path_loaded) = (node / 2, node % 2 == 1); + let mut targets = Vec::new(); + for decl in &decls[file] { + let by_path = usize::from(decl.module.path_attribute.is_some()); + for candidate in module_files(&paths[file], decl, path_loaded) { + for &j in index.get(candidate.as_str()).into_iter().flatten() { + if j != file { + named[j] = true; + named_plainly[j] |= by_path == 0; + targets.push(2 * j + by_path); + } + } + } + } + targets + }) + .collect(); + let root = |file: usize| { + let mut segments = paths[file].rsplit('/'); + match (segments.next(), segments.next()) { + (Some("lib.rs" | "main.rs"), Some("src")) => true, + (Some("lib.rs" | "main.rs" | "build.rs"), _) => !named[file], + (Some(name), Some("bin" | "examples" | "tests" | "benches")) => name.ends_with(".rs") && name != "mod.rs" && !named_plainly[file], + _ => false, + } + }; + let mut prelude = vec![BTreeSet::new(); paths.len()]; + for start in (0..paths.len()).filter(|&file| !aliases[file].is_empty() && root(file)) { + let mut seen = vec![false; paths.len() * 2]; + let mut queue = vec![2 * start]; + seen[2 * start] = true; + while let Some(node) = queue.pop() { + prelude[node / 2].extend(aliases[start].iter().cloned()); + for &next in &edges[node] { + if !seen[next] { + seen[next] = true; + queue.push(next); + } + } + } + } + prelude +} + +/// The names of the muda crate in a file, and where each is bound. The names are `muda` itself, each name +/// in `prelude` (see [`extern_prelude_names`]), which names the crate as `muda` does, and each name that +/// `use muda as m;`, `use muda::{self as m};` or `extern crate muda as m;` gives it. For each +/// name and each pair of braces, the bindings record whether a `use` or an `extern crate` in them binds +/// the name to the crate, and whether a `use`, an `extern crate` or a `mod` in them binds it to something +/// else. A binding to something else inside an item with a `cfg` attribute, or through `crate::`, `self::` +/// or `super::` (which may be a re-export of the crate), is left out. +fn muda_crate_bindings<'a>( + toks: &'a [Token], + leaves: &'a [UseLeaf], + around: &[Option], + gated: &[bool], + prelude: &'a BTreeSet, +) -> (BTreeSet<&'a str>, CrateBindings<'a>) { + let externs = extern_crates(toks); + // Whether a `use` path names the crate itself: `muda`, or a name of the crate in the extern prelude. + let crate_path = |leaf: &UseLeaf| leaf.path.len() == 1 && (leaf.path[0] == "muda" || prelude.contains(&leaf.path[0])); let mut names: BTreeSet<&'a str> = BTreeSet::from(["muda"]); - names.extend(leaves.iter().filter(|leaf| leaf.path == ["muda"]).filter_map(UseLeaf::binding)); + names.extend(prelude.iter().map(String::as_str)); + names.extend(leaves.iter().filter(|leaf| crate_path(leaf)).filter_map(UseLeaf::binding)); names.extend(externs.iter().filter(|&&(muda, _, _)| muda).map(|&(_, name, _)| name)); let mut bound: CrateBindings<'a> = BTreeMap::new(); // `use muda as m;` binds `m` to the crate only where `muda` itself names the crate, so it is read - // after every other binding. - let renames = |leaf: &UseLeaf| leaf.path == ["muda"] && leaf.binding() != Some("muda"); + // after every other binding. The same holds for a name of the crate in the extern prelude. + let renames = |leaf: &UseLeaf| crate_path(leaf) && leaf.binding() != Some(leaf.path[0].as_str()); for leaf in leaves.iter().filter(|leaf| !renames(leaf)) { let Some(name) = leaf.binding().filter(|name| names.contains(name)) else { continue }; let local = leaf.root.as_deref().is_some_and(|s| matches!(s, "crate" | "self" | "super")); let entry = bound.entry((name, around.get(leaf.start).copied().flatten())); - if leaf.path == ["muda"] { + if crate_path(leaf) { entry.or_default().0 = true; } else if !local && !gated.get(leaf.start).copied().unwrap_or(false) { entry.or_default().1 = true; @@ -1475,8 +1583,8 @@ fn muda_crate_bindings<'a>( let mut renamed = Vec::new(); for leaf in leaves.iter().filter(|leaf| renames(leaf)) { let Some(name) = leaf.binding() else { continue }; - let crate_here = - leaf.absolute || !matches!(lookup(toks, around, leaf.start, |scope| bound.get(&("muda", scope)).copied()), Some(Some((false, true)))); + let crate_here = leaf.absolute + || !matches!(lookup(toks, around, leaf.start, |scope| bound.get(&(leaf.path[0].as_str(), scope)).copied()), Some(Some((false, true)))); let local = leaf.root.as_deref().is_some_and(|s| matches!(s, "crate" | "self" | "super")); let scope = around.get(leaf.start).copied().flatten(); if crate_here { @@ -1509,7 +1617,14 @@ fn muda_crate_bindings<'a>( /// braces binding it bind only to something else (`use other_menu as muda;`, `mod muda`), read like a name /// used on its own below; `::muda::PredefinedMenuItem` always names the crate. A name that the crate is /// imported under (`use muda as menu;`, `use muda::{self as menu};`, `extern crate muda as menu;`) is read -/// like `muda` in the braces that bind it, so `menu::PredefinedMenuItem::quit` is reported there. It also +/// like `muda` in the braces that bind it, so `menu::PredefinedMenuItem::quit` is reported there. An +/// `extern crate muda as menu;` outside any braces of a crate root (`src/lib.rs` and `src/main.rs`; `build.rs`, +/// another `lib.rs` or `main.rs`, or a file directly in a `bin`, `examples`, `tests` or `benches` folder other +/// than `mod.rs`, unless a `mod` declaration in another of `files` names it, for a file in those folders one +/// without a `#[path]` attribute) also adds `menu` to +/// the crate's extern prelude, so in that file and in every file of `files` that a chain of `mod` +/// declarations from it names, `menu` is read like `muda` and `::menu::PredefinedMenuItem::quit` is +/// reported. Elsewhere a path that starts with `::` names the crate only through `muda`. It also /// follows a `use` or a `type` alias that renames muda's type (`use muda::PredefinedMenuItem as Item;` then /// `Item::quit`); a rename of another crate's `PredefinedMenuItem` is not followed, including one through a /// name `muda` that the braces around the `use` or `type` bind to something else, read as for a qualified @@ -1528,28 +1643,34 @@ where I: IntoIterator, I::Item: AsFileSource, { + let files: Vec = files.into_iter().collect(); + let paths: Vec = files.iter().map(|file| normalize_path(file.path())).collect(); + let contents: Vec<&str> = files.iter().map(|file| file.content()).collect(); + let prelude = extern_prelude_names(&paths, &contents); let mut findings = Vec::new(); - for file in files { + for (index, file) in files.iter().enumerate() { let path = file.path(); let content = file.content(); let toks = lex_rust(content); let leaves = use_leaves(&toks, &BTreeSet::new()); let (around, opener) = brace_scopes(&toks); let gated = cfg_covered(&toks, true); - let (crate_names, crate_bound) = muda_crate_bindings(&toks, &leaves, &around, &gated); + let (crate_names, crate_bound) = muda_crate_bindings(&toks, &leaves, &around, &gated, &prelude[index]); let names_crate = |s: &str| crate_names.contains(s); - // Whether `name`, read at token `i`, names the crate. After a leading `::` only `muda` does. - // Otherwise `muda` does unless the innermost braces around `i` that bind `muda` bind it only to - // something else, and another name of the crate does when those braces bind it to the crate, or - // only to nothing else. + // Whether `name`, read at token `i`, names the crate. After a leading `::`, `muda` does, and so + // does a name that `extern crate muda as name;` outside any braces of the file's crate root gives it + // (a name in the extern prelude). Otherwise `muda` and a name in the extern prelude do unless the + // innermost braces around `i` that bind the name bind it only to something else, and another name + // of the crate does when those braces bind it to the crate, or only to nothing else. + let in_prelude = |name: &str| name == "muda" || prelude[index].contains(name); let crate_name_at = |name: &str, i: usize, absolute: bool| { if absolute || !names_crate(name) { - return name == "muda"; + return in_prelude(name); } match lookup(&toks, &around, i, |scope| crate_bound.get(&(name, scope)).copied()) { None => true, Some(Some((muda, other))) => muda || !other, - Some(None) => name == "muda", + Some(None) => in_prelude(name), } }; // Whether the identifier at `i` names the crate. @@ -1559,7 +1680,7 @@ where crate_name_at(name, i, absolute) }; // A `use` path to muda's type, read through a name of the crate bound where the `use` is. After - // a leading `::` the first segment is an external crate, so only `muda` names it. + // a leading `::` the first segment is an external crate, so only a name in the extern prelude names it. let is_muda = |leaf: &UseLeaf| leaf.path.len() == 2 && leaf.path[1] == "PredefinedMenuItem" && crate_name_at(&leaf.path[0], leaf.start, leaf.absolute); // Whether the braces opened at `o` are the body of an `impl` or a `trait`, whose `type` items are @@ -1755,7 +1876,8 @@ where /// braces of its `use` (or the file), down to but not into the body of a nested `mod`; nearer braces whose /// `use` or `mod` binds the same name to something else hide it, unless that `use` or `mod` carries a `cfg` /// attribute of its own that is not known to be true on `wasm32-unknown-unknown`, which may leave it out of -/// the web build. +/// the web build. A path that starts with `::` names an external crate, so `::m::Instant` and +/// `use ::m::Instant;` are not read through an alias `m`. pub fn std_instant(files: I) -> Vec where I: IntoIterator, @@ -1854,7 +1976,9 @@ where let hit = if name == "std" { then_path(&toks, i + 1, |s| s == "time") && then_path(&toks, i + 4, |s| s == "Instant") } else { - modules.contains(name) && then_path(&toks, i + 1, |s| s == "Instant") && time_alias(name, i) + // After a leading `::` the name is an external crate, not a local alias of `std::time`. + let absolute = i >= 2 && toks[i - 1].is_punct(':') && toks[i - 2].is_punct(':'); + !absolute && modules.contains(name) && then_path(&toks, i + 1, |s| s == "Instant") && time_alias(name, i) }; if hit { lines.insert(tok.line); diff --git a/crates/testkit/tests/guards.rs b/crates/testkit/tests/guards.rs index 64f54bfc5a..251adaa05b 100644 --- a/crates/testkit/tests/guards.rs +++ b/crates/testkit/tests/guards.rs @@ -532,6 +532,66 @@ mod shadowed { assert_eq!(lines(&predefined_quit([("src/menu.rs", source)])), vec![4, 5, 10, 15, 20]); } +#[test] +fn predefined_quit_reads_an_absolute_path_through_a_root_extern_crate_alias() { + let source = r#" +extern crate muda as menu; +use ::menu::PredefinedMenuItem as Item; +fn menu_bar() { + let a = ::menu::PredefinedMenuItem::quit(None); + let b = <::menu::PredefinedMenuItem>::quit(None); + let c = Item::quit(None); +} +mod nested { + extern crate muda as native; + fn menu_bar() { let d = ::native::PredefinedMenuItem::quit(None); let e = ::menu::PredefinedMenuItem::quit(None); } +} +"#; + assert_eq!(lines(&predefined_quit([("src/main.rs", source)])), vec![5, 6, 7, 11]); + // In a module file the declaration binds `menu` in that module only; `::menu` is the crate root's. + let module = "extern crate muda as menu;\nfn menu_bar() {\n let a = ::menu::PredefinedMenuItem::quit(None);\n let b = menu::PredefinedMenuItem::quit(None);\n}\n"; + assert_eq!(lines(&predefined_quit([("src/child.rs", module)])), vec![4]); + assert_eq!(lines(&predefined_quit([("src/bin/tool.rs", module)])), vec![3, 4]); + assert_eq!(lines(&predefined_quit([("src/bin/mod.rs", module)])), vec![4]); + // A `lib.rs` that another file loads through a `#[path]` attribute is a module. + let root = "#[path = \"nested/lib.rs\"]\nmod nested;\n"; + assert_eq!(lines(&predefined_quit([("src/lib.rs", root), ("src/nested/lib.rs", module)])), vec![4]); + // The root's alias reaches the module files it declares. + let root = "extern crate muda as menu;\nmod child;\n"; + let child = "fn menu_bar() {\n let a = ::menu::PredefinedMenuItem::quit(None);\n}\nuse ::menu::PredefinedMenuItem as Item;\nfn b() { Item::quit(None); }\n\ + fn c() { menu::PredefinedMenuItem::quit(None); }\nuse menu::PredefinedMenuItem as Other;\nfn d() { Other::quit(None); }\n\ + mod shadowed {\n use other_menu as menu;\n fn e() { menu::PredefinedMenuItem::quit(None); }\n}\n"; + let found = predefined_quit([("src/lib.rs", root), ("src/child.rs", child)]); + assert_eq!( + found.iter().map(|f| (f.path.as_str(), f.line)).collect::>(), + vec![("src/child.rs", 2), ("src/child.rs", 5), ("src/child.rs", 6), ("src/child.rs", 8)] + ); + // Without the root that declares the alias, `menu` is not muda. + assert!(predefined_quit([("src/child.rs", child)]).is_empty()); + // The alias follows the library's modules, not the binary's module of the same name, and `src/lib.rs` + // stays a root when another file also declares it as a module. + let call = "fn f() { ::menu::PredefinedMenuItem::quit(None); }\n"; + let found = predefined_quit([ + ("src/lib.rs", "extern crate muda as menu;\nmod outer;\nfn g() { ::menu::PredefinedMenuItem::quit(None); }\n"), + ("src/outer.rs", "mod child;\n"), + ("src/outer/child.rs", call), + ("src/main.rs", "mod child;\n#[path = \"lib.rs\"]\nmod lib;\n"), + ("src/child.rs", call), + ]); + assert_eq!(found.iter().map(|f| (f.path.as_str(), f.line)).collect::>(), vec![("src/lib.rs", 3), ("src/outer/child.rs", 1)]); + // A module file in a folder named `tests` is not a test crate's root. + let local = "extern crate muda as menu;\nfn f() { ::menu::PredefinedMenuItem::quit(None); }\n"; + assert!(predefined_quit([("src/tests/mod.rs", "mod child;\n"), ("src/tests/child.rs", local)]).is_empty()); + assert_eq!(lines(&predefined_quit([("tests/child.rs", local)])), vec![2]); + // A test that another test also loads by path stays a root, and its alias reaches its modules. + let found = predefined_quit([ + ("tests/foo.rs", "extern crate muda as menu;\nmod part;\n"), + ("tests/foo/part.rs", call), + ("tests/bar.rs", "#[path = \"foo.rs\"]\nmod foo;\n"), + ]); + assert_eq!(found.iter().map(|f| (f.path.as_str(), f.line)).collect::>(), vec![("tests/foo/part.rs", 1)]); +} + #[test] fn predefined_quit_reads_a_crate_name_in_an_import_where_the_import_is() { let source = r#" @@ -1008,6 +1068,32 @@ fn run(ready: bool, items: Vec) { assert_eq!(lines(&std_instant([("src/run.rs", source)])), vec![5, 8, 11, 14, 17, 20, 23, 26]); } +#[test] +fn std_instant_ends_a_native_cfg_loop_at_its_body_after_an_if_or_match_in_its_head() { + let source = r#" +fn run(flag: bool, n: u8) { + #[cfg(unix)] + for _ in if flag { [0] } else { [1] } { + let _a = std::time::Instant::now(); + } + let b = std::time::Instant::now(); + #[cfg(unix)] + for _ in if flag { [0] } else if n > 1 { [1] } else { [2] }.iter() { let _c = std::time::Instant::now(); } + let d = std::time::Instant::now(); + #[cfg(unix)] + if let Some(_) = match n { 0 => None, _ => Some(n) } { let _e = std::time::Instant::now(); } + let f = std::time::Instant::now(); + #[cfg(unix)] + while n == if if flag { true } else { false } { 1 } else { 2 } { let _g = std::time::Instant::now(); } + let h = std::time::Instant::now(); + #[cfg(unix)] + if flag { let _i = std::time::Instant::now(); } else if if flag { true } else { false } { let _j = std::time::Instant::now(); } + let k = std::time::Instant::now(); +} +"#; + assert_eq!(lines(&std_instant([("src/run.rs", source)])), vec![7, 10, 13, 16, 19]); +} + #[test] fn std_instant_ends_a_native_cfg_let_else_and_match_with_struct_patterns_where_they_end() { let source = r#" @@ -1229,6 +1315,22 @@ fn run() { assert_eq!(lines(&std_instant([("src/run.rs", source)])), vec![4, 8, 9]); } +#[test] +fn std_instant_does_not_read_an_absolute_path_through_a_local_alias() { + let source = r#" +use std::time as web_time; +use ::web_time::{Instant}; +use ::web_time::Instant as Clock; + +fn now() { + let a = ::web_time::Instant::now(); + let b = web_time::Instant::now(); + let c = ::std::time::Instant::now(); +} +"#; + assert_eq!(lines(&std_instant([("src/now.rs", source)])), vec![8, 9]); +} + #[test] fn std_instant_reads_a_use_group_split_over_several_lines() { let source = r#" From f50e7dceb9913640d4753877be31ec024c8b945b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 16:00:33 -0800 Subject: [PATCH 20/33] craft-testkit: open CACHEDIR.TAG and sources on Windows without following a reparse point On Windows, open_regular_file checked the path with symlink_metadata and then opened it with File::open, which follows a symbolic link or junction put in place between the two calls. It now opens with FILE_FLAG_OPEN_REPARSE_POINT, so a link opens as the link itself and is refused by the type check on the opened handle. A CACHEDIR.TAG whose opened handle is a reparse point of any kind, cloud placeholders included, does not count as a cache marker, so its folder is listed. The Unix path is unchanged. --- crates/testkit/src/guards.rs | 86 ++++++++++++++++++++++++++++++++---- 1 file changed, 78 insertions(+), 8 deletions(-) diff --git a/crates/testkit/src/guards.rs b/crates/testkit/src/guards.rs index 945124743d..69c6b8aa3b 100644 --- a/crates/testkit/src/guards.rs +++ b/crates/testkit/src/guards.rs @@ -2258,8 +2258,10 @@ const CACHEDIR_SIGNATURE: &[u8] = b"Signature: 8a477f597d28d172789f06886806bc55" /// /// On Unix the open does not follow a symbolic link (`O_NOFOLLOW`) and does not wait for a writer on a /// FIFO (`O_NONBLOCK`), and the type is then read from the opened file, so a file replaced between a -/// directory listing and the open is checked as it is when opened. On other platforms a path that is a -/// symbolic link is skipped before the open, and the opened file must be a regular file. +/// directory listing and the open is checked as it is when opened. On Windows the open does not follow +/// a reparse point (`FILE_FLAG_OPEN_REPARSE_POINT`), so an opened symbolic link or junction is the link +/// itself and returns `Ok(None)`. On other platforms a +/// path that is a symbolic link is skipped before the open, and the opened file must be a regular file. #[cfg(not(target_arch = "wasm32"))] fn open_regular_file(path: &Path) -> std::io::Result> { #[cfg(unix)] @@ -2269,7 +2271,9 @@ fn open_regular_file(path: &Path) -> std::io::Result> { .map(std::fs::File::from) .map_err(std::io::Error::from) }; - #[cfg(not(unix))] + #[cfg(windows)] + let opened = open_without_following(path); + #[cfg(not(any(unix, windows)))] let opened = { if std::fs::symlink_metadata(path)?.file_type().is_symlink() { return Ok(None); @@ -2285,14 +2289,38 @@ fn open_regular_file(path: &Path) -> std::io::Result> { Ok(file.metadata()?.file_type().is_file().then_some(file)) } +/// The Win32 `FILE_FLAG_OPEN_REPARSE_POINT` flag: open a reparse point itself instead of its target. +#[cfg(windows)] +const FILE_FLAG_OPEN_REPARSE_POINT: u32 = 0x0020_0000; + +/// Open `path` for reading without following a reparse point: a symbolic link or junction opens as the +/// link itself. +#[cfg(windows)] +fn open_without_following(path: &Path) -> std::io::Result { + use std::os::windows::fs::OpenOptionsExt; + std::fs::OpenOptions::new().read(true).custom_flags(FILE_FLAG_OPEN_REPARSE_POINT).open(path) +} + +/// The Win32 `FILE_ATTRIBUTE_REPARSE_POINT` attribute of a file that is a reparse point. +#[cfg(windows)] +const FILE_ATTRIBUTE_REPARSE_POINT: u32 = 0x0400; + /// Whether `dir` holds a `CACHEDIR.TAG` regular file that starts with [`CACHEDIR_SIGNATURE`]. A marker /// that is a symbolic link, a folder, a FIFO or another special file is not read and does not count. +/// On Windows a marker that is a reparse point of any kind, cloud placeholders included, does not count. #[cfg(not(target_arch = "wasm32"))] fn is_cache_dir(dir: &Path) -> bool { use std::io::Read; let Ok(Some(file)) = open_regular_file(&dir.join("CACHEDIR.TAG")) else { return false; }; + #[cfg(windows)] + { + use std::os::windows::fs::MetadataExt; + if !file.metadata().is_ok_and(|m| m.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT == 0) { + return false; + } + } let mut head = Vec::with_capacity(CACHEDIR_SIGNATURE.len()); file.take(CACHEDIR_SIGNATURE.len() as u64).read_to_end(&mut head).is_ok() && head == CACHEDIR_SIGNATURE } @@ -2310,7 +2338,8 @@ fn is_cache_dir(dir: &Path) -> bool { /// name starts with `.`, or that holds a `CACHEDIR.TAG` regular file starting with the signature line /// `Signature: 8a477f597d28d172789f06886806bc55` (a build output folder with another name). A /// `CACHEDIR.TAG` that is a symbolic link or a special file such as a FIFO is not read, and its folder -/// is listed. +/// is listed. On Windows a `CACHEDIR.TAG` that is a reparse point of any kind, cloud placeholders +/// included, does not mark its folder either. /// * Symbolic links (and, on Windows, junctions) to files or folders, which are not followed. /// /// Results are sorted lexicographically by file path for deterministic behavior across platforms. @@ -2400,10 +2429,10 @@ mod tests { } /// A new empty folder under the system temporary folder, removed when dropped. - #[cfg(unix)] + #[cfg(any(unix, windows))] struct TempDir(std::path::PathBuf); - #[cfg(unix)] + #[cfg(any(unix, windows))] impl TempDir { fn new(tag: &str) -> Self { let path = std::env::temp_dir().join(format!("craft-testkit-unit-{tag}-{}", std::process::id())); @@ -2413,14 +2442,14 @@ mod tests { } } - #[cfg(unix)] + #[cfg(any(unix, windows))] impl Drop for TempDir { fn drop(&mut self) { let _ = std::fs::remove_dir_all(&self.0); } } - #[cfg(unix)] + #[cfg(any(unix, windows))] #[test] fn open_regular_file_opens_a_regular_file() { let dir = TempDir::new("open_regular"); @@ -2459,6 +2488,47 @@ mod tests { assert!(!super::is_cache_dir(&dir.0)); } + /// A file symbolic link to `target` at `link`, or `None` with a printed note when this account may not + /// create symbolic links. + #[cfg(windows)] + fn windows_file_symlink(target: &std::path::Path, link: &std::path::Path) -> Option<()> { + match std::os::windows::fs::symlink_file(target, link) { + Ok(()) => Some(()), + Err(err) => { + eprintln!("skipped: symbolic links cannot be created here ({err})"); + None + } + } + } + + #[cfg(windows)] + #[test] + fn open_without_following_opens_the_link_itself() { + let dir = TempDir::new("open_no_follow"); + let target = dir.0.join("target.tag"); + std::fs::write(&target, super::CACHEDIR_SIGNATURE).expect("write target"); + let link = dir.0.join("CACHEDIR.TAG"); + if windows_file_symlink(&target, &link).is_none() { + return; + } + let opened = super::open_without_following(&link).expect("open"); + assert!(opened.metadata().expect("metadata").file_type().is_symlink()); + } + + #[cfg(windows)] + #[test] + fn a_symlinked_cachedir_tag_does_not_mark_its_folder() { + let dir = TempDir::new("tag_symlink"); + let target = dir.0.join("target.tag"); + std::fs::write(&target, super::CACHEDIR_SIGNATURE).expect("write target"); + let link = dir.0.join("CACHEDIR.TAG"); + if windows_file_symlink(&target, &link).is_none() { + return; + } + assert!(super::open_regular_file(&link).expect("open").is_none()); + assert!(!super::is_cache_dir(&dir.0)); + } + #[test] fn use_leaves_keep_no_path_longer_than_the_limit() { let source = format!("use {}{{x, y::z, *}};\nuse std::time::{{Instant, self as t}};\n", "a::".repeat(MAX_USE_PATH)); From ccaf31d4c98fe4018231ececd34bfb59e6d9fb55 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 19 Nov 2026 20:17:01 -0800 Subject: [PATCH 21/33] craft-testkit: guards read identifiers that hold combining marks The guards' lexer split an identifier at a nonspacing mark such as U+0301, so `use std::time as t\u{301};` bound `t` and a later `t\u{301}::Instant::now()` was not reported. Identifiers now follow the Unicode XID_Start and XID_Continue properties, as rustc reads them, through the unicode-ident crate that the workspace already locks. --- Cargo.lock | 1 + crates/testkit/Cargo.toml | 1 + crates/testkit/src/guards.rs | 7 +++++-- crates/testkit/tests/guards.rs | 11 +++++++++++ 4 files changed, 18 insertions(+), 2 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index d3c4e0343a..f4957a3a8e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3125,6 +3125,7 @@ name = "craft-testkit" version = "0.1.0" dependencies = [ "rustix 1.1.5", + "unicode-ident", ] [[package]] diff --git a/crates/testkit/Cargo.toml b/crates/testkit/Cargo.toml index bfb89fb742..5e58b0168b 100644 --- a/crates/testkit/Cargo.toml +++ b/crates/testkit/Cargo.toml @@ -9,6 +9,7 @@ description = "Source-level platform regression guards and verification utilitie publish = false [dependencies] +unicode-ident = "1" [target.'cfg(unix)'.dependencies] rustix = { version = "1.1", default-features = false, features = ["std", "fs"] } diff --git a/crates/testkit/src/guards.rs b/crates/testkit/src/guards.rs index 69c6b8aa3b..c9296d18d8 100644 --- a/crates/testkit/src/guards.rs +++ b/crates/testkit/src/guards.rs @@ -151,12 +151,15 @@ impl Token { } } +/// Whether `c` can start a Rust identifier: `_` or a character with the Unicode `XID_Start` property. fn is_ident_start(c: char) -> bool { - c == '_' || c.is_alphabetic() + c == '_' || unicode_ident::is_xid_start(c) } +/// Whether `c` can continue a Rust identifier: a character with the Unicode `XID_Continue` property, which +/// includes `_`, digits and combining marks such as U+0301. fn is_ident_continue(c: char) -> bool { - c == '_' || c.is_alphanumeric() + unicode_ident::is_xid_continue(c) } /// Split Rust source into tokens with 1-based line numbers. diff --git a/crates/testkit/tests/guards.rs b/crates/testkit/tests/guards.rs index 251adaa05b..725fb1f376 100644 --- a/crates/testkit/tests/guards.rs +++ b/crates/testkit/tests/guards.rs @@ -1405,6 +1405,17 @@ fn a_long_name_shared_by_many_use_leaves_is_read_without_copying_it_to_each() { assert!(predefined_quit([("src/wide.rs", source.as_str())]).is_empty()); } +#[test] +fn guards_read_names_that_hold_combining_marks() { + // `t` with U+0301 (a nonspacing mark) and Devanagari `ka` with U+093E (a spacing mark) are each one + // identifier, as rustc reads them. + let time = "use std::time as t\u{301};\nuse std::time as \u{915}\u{93E};\nfn run() {\n let a = t\u{301}::Instant::now();\n let b = \u{915}\u{93E}::Instant::now();\n}\n"; + assert_eq!(lines(&std_instant([("src/run.rs", time)])), vec![4, 5]); + + let menu = "use muda::{PredefinedMenuItem as Ite\u{301}m};\nfn menu() {\n let a = Ite\u{301}m::quit(None);\n}\n"; + assert_eq!(lines(&predefined_quit([("src/menu.rs", menu)])), vec![3]); +} + #[test] fn std_instant_reports_a_grouped_import_through_a_long_alias_of_std_time() { let source = r#" From abaaa097f9a715d07968aa84bb8f86b7fd851f9b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 19 Nov 2026 20:21:13 -0800 Subject: [PATCH 22/33] craft-testkit: a crate root's extern crate alias reaches modules beside it A crate root such as `src/bin/tool.rs` or `tests/foo.rs` declares its modules in its own folder, so `mod child;` names `src/bin/child.rs`. predefined_quit looked for them under `src/bin/tool/` and missed `::menu::PredefinedMenuItem::quit` in the child after `extern crate muda as menu;` in the root. --- crates/testkit/src/guards.rs | 10 ++++++---- crates/testkit/tests/guards.rs | 13 +++++++++++-- 2 files changed, 17 insertions(+), 6 deletions(-) diff --git a/crates/testkit/src/guards.rs b/crates/testkit/src/guards.rs index c9296d18d8..c788cc5cbd 100644 --- a/crates/testkit/src/guards.rs +++ b/crates/testkit/src/guards.rs @@ -1462,8 +1462,8 @@ fn extern_crates(toks: &[Token]) -> Vec<(bool, &str, usize)> { /// plainly or through a `#[path]` attribute; and each file directly in a `bin`, `examples`, `tests` or /// `benches` folder other than `mod.rs` when no declaration without a `#[path]` attribute names it. A root's /// names reach every file that a chain of declarations -/// from it names, where a file loaded through a `#[path]` attribute has its modules in its own folder, as -/// [`module_files`] reads them. +/// from it names, where a crate root and a file loaded through a `#[path]` attribute have their modules in their +/// own folder, as [`module_files`] reads them. fn extern_prelude_names(paths: &[String], contents: &[&str]) -> Vec> { let mut index: BTreeMap<&str, Vec> = BTreeMap::new(); for (i, path) in paths.iter().enumerate() { @@ -1513,9 +1513,11 @@ fn extern_prelude_names(paths: &[String], contents: &[&str]) -> Vec>(), vec![("tests/foo/part.rs", 1)]); + assert_eq!(found.iter().map(|f| (f.path.as_str(), f.line)).collect::>(), vec![("tests/part.rs", 1)]); + // A binary's root in `src/bin` declares its modules beside it, not in a folder named after it. + let found = predefined_quit([ + ("src/bin/tool.rs", "extern crate muda as menu;\nmod child;\n"), + ("src/bin/child/mod.rs", call), + ("src/bin/tool/child.rs", call), + ]); + assert_eq!(found.iter().map(|f| (f.path.as_str(), f.line)).collect::>(), vec![("src/bin/child/mod.rs", 1)]); } #[test] From 2477df8c8609bb3cdbf206da2ce98602359f1030 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 19 Nov 2026 20:27:34 -0800 Subject: [PATCH 23/33] craft-testkit: files in a package's target folders stay crate roots Cargo builds every file in a package's `src/bin`, `tests`, `examples` and `benches` folder as its own crate, also when another target declares it as a module. predefined_quit now reads such a file's `extern crate muda as menu;` as a crate root's. A target folder inside `src` or inside another target folder still holds modules. --- crates/testkit/src/guards.rs | 20 ++++++++++++++++---- crates/testkit/tests/guards.rs | 23 +++++++++++++++++++++++ 2 files changed, 39 insertions(+), 4 deletions(-) diff --git a/crates/testkit/src/guards.rs b/crates/testkit/src/guards.rs index c788cc5cbd..db5de5b35d 100644 --- a/crates/testkit/src/guards.rs +++ b/crates/testkit/src/guards.rs @@ -1459,8 +1459,11 @@ fn extern_crates(toks: &[Token]) -> Vec<(bool, &str, usize)> { /// /// The crate roots follow Cargo's layout: `src/lib.rs` and `src/main.rs`; `build.rs` and another `lib.rs` or /// `main.rs` (such as `src/bin/tool/main.rs`) when no `mod` declaration in another of the files names it, -/// plainly or through a `#[path]` attribute; and each file directly in a `bin`, `examples`, `tests` or -/// `benches` folder other than `mod.rs` when no declaration without a `#[path]` attribute names it. A root's +/// plainly or through a `#[path]` attribute; each file directly in a package's `src/bin`, `tests`, `examples` +/// or `benches` folder (one with no `src`, `bin`, `tests`, `examples` or `benches` folder above it), other than +/// `mod.rs`; and each other file directly in a +/// `bin`, `examples`, `tests` or `benches` folder other than `mod.rs` when no declaration without a `#[path]` +/// attribute names it. A root's /// names reach every file that a chain of declarations /// from it names, where a crate root and a file loaded through a `#[path]` attribute have their modules in their /// own folder, as [`module_files`] reads them. @@ -1507,7 +1510,14 @@ fn extern_prelude_names(paths: &[String], contents: &[&str]) -> Vec true, (Some("lib.rs" | "main.rs" | "build.rs"), _) => !named[file], - (Some(name), Some("bin" | "examples" | "tests" | "benches")) => name.ends_with(".rs") && name != "mod.rs" && !named_plainly[file], + (Some(name), Some(folder @ ("bin" | "examples" | "tests" | "benches"))) => { + // Cargo builds each file in a package's `src/bin`, `tests`, `examples` or `benches` folder as a + // crate of its own, also when another of them declares it as a module. Such a folder inside + // `src` or inside another of these folders holds modules. + let target = (folder != "bin" || segments.next() == Some("src")) + && !segments.any(|s| matches!(s, "src" | "bin" | "tests" | "examples" | "benches")); + name.ends_with(".rs") && name != "mod.rs" && (target || !named_plainly[file]) + } _ => false, } }; @@ -1626,7 +1636,9 @@ fn muda_crate_bindings<'a>( /// `extern crate muda as menu;` outside any braces of a crate root (`src/lib.rs` and `src/main.rs`; `build.rs`, /// another `lib.rs` or `main.rs`, or a file directly in a `bin`, `examples`, `tests` or `benches` folder other /// than `mod.rs`, unless a `mod` declaration in another of `files` names it, for a file in those folders one -/// without a `#[path]` attribute) also adds `menu` to +/// without a `#[path]` attribute; a file directly in a package's `src/bin`, `tests`, `examples` or `benches` +/// folder, one with no such folder or `src` above it, is a crate root even when a declaration names it) also +/// adds `menu` to /// the crate's extern prelude, so in that file and in every file of `files` that a chain of `mod` /// declarations from it names, `menu` is read like `muda` and `::menu::PredefinedMenuItem::quit` is /// reported. Elsewhere a path that starts with `::` names the crate only through `muda`. It also diff --git a/crates/testkit/tests/guards.rs b/crates/testkit/tests/guards.rs index 4e35639149..5014703a46 100644 --- a/crates/testkit/tests/guards.rs +++ b/crates/testkit/tests/guards.rs @@ -599,6 +599,29 @@ mod nested { ("src/bin/tool/child.rs", call), ]); assert_eq!(found.iter().map(|f| (f.path.as_str(), f.line)).collect::>(), vec![("src/bin/child/mod.rs", 1)]); + // A file in `tests` or `src/bin` is its own crate's root also when another target declares it as a module. + let found = predefined_quit([ + ("tests/foo.rs", "mod part;\n"), + ("tests/part.rs", local), + ("src/bin/tool.rs", "mod helper;\n"), + ("src/bin/helper.rs", local), + ]); + assert_eq!(found.iter().map(|f| (f.path.as_str(), f.line)).collect::>(), vec![("tests/part.rs", 2), ("src/bin/helper.rs", 2)]); + // A `tests` folder inside a test's module folder holds modules, so a declared file there is not a root. + assert!( + predefined_quit([ + ("tests/support/mod.rs", "mod tests;\n"), + ("tests/support/tests/mod.rs", "mod helper;\n"), + ("tests/support/tests/helper.rs", local) + ]) + .is_empty() + ); + // A child's own `menu` module, imported through `self::`, is not the crate. + let found = predefined_quit([ + ("src/lib.rs", "extern crate muda as menu;\nmod child;\n"), + ("src/child.rs", "mod menu {}\nuse self::menu as other;\nfn f() { other::PredefinedMenuItem::quit(None); }\n"), + ]); + assert!(found.is_empty()); } #[test] From fa829e4a37bc0baaf9fe1c7bfeba3a51df5f3eb5 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 19 Nov 2026 20:31:49 -0800 Subject: [PATCH 24/33] craft-testkit: read identifier characters with std only The guards need only std, so the unicode-ident dependency is removed. Outside literals and comments Rust allows a non-ASCII character only in an identifier or as white space, so the lexer reads every non-ASCII character other than white space as part of an identifier. The left-to-right and right-to-left marks and a byte order mark are read as white space, so `t\u{200F}::Instant::now()` is still reported. --- Cargo.lock | 1 - crates/testkit/Cargo.toml | 1 - crates/testkit/src/guards.rs | 21 +++++++++++++++------ crates/testkit/tests/guards.rs | 4 ++++ 4 files changed, 19 insertions(+), 8 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index f4957a3a8e..d3c4e0343a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3125,7 +3125,6 @@ name = "craft-testkit" version = "0.1.0" dependencies = [ "rustix 1.1.5", - "unicode-ident", ] [[package]] diff --git a/crates/testkit/Cargo.toml b/crates/testkit/Cargo.toml index 5e58b0168b..bfb89fb742 100644 --- a/crates/testkit/Cargo.toml +++ b/crates/testkit/Cargo.toml @@ -9,7 +9,6 @@ description = "Source-level platform regression guards and verification utilitie publish = false [dependencies] -unicode-ident = "1" [target.'cfg(unix)'.dependencies] rustix = { version = "1.1", default-features = false, features = ["std", "fs"] } diff --git a/crates/testkit/src/guards.rs b/crates/testkit/src/guards.rs index db5de5b35d..988f102e60 100644 --- a/crates/testkit/src/guards.rs +++ b/crates/testkit/src/guards.rs @@ -151,15 +151,22 @@ impl Token { } } -/// Whether `c` can start a Rust identifier: `_` or a character with the Unicode `XID_Start` property. +/// Whether `c` can start a Rust identifier: `_`, a letter, or another non-ASCII character that is not white +/// space (see [`non_ascii_word`]). fn is_ident_start(c: char) -> bool { - c == '_' || unicode_ident::is_xid_start(c) + c == '_' || c.is_alphabetic() || non_ascii_word(c) } -/// Whether `c` can continue a Rust identifier: a character with the Unicode `XID_Continue` property, which -/// includes `_`, digits and combining marks such as U+0301. +/// Whether `c` can continue a Rust identifier: `_`, a letter or digit, or another non-ASCII character that is +/// not white space, such as the combining mark U+0301. fn is_ident_continue(c: char) -> bool { - unicode_ident::is_xid_continue(c) + c == '_' || c.is_alphanumeric() || non_ascii_word(c) +} + +/// Whether `c` is a non-ASCII character other than Rust's white space and the byte order mark U+FEFF. Outside +/// literals and comments, Rust allows such a character only in an identifier, so it is read as part of one. +fn non_ascii_word(c: char) -> bool { + !c.is_ascii() && !c.is_whitespace() && !matches!(c, '\u{200E}' | '\u{200F}' | '\u{FEFF}') } /// Split Rust source into tokens with 1-based line numbers. @@ -181,7 +188,9 @@ fn lex_rust(code: &str) -> Vec { if c == '\n' { line += 1; i += 1; - } else if c.is_whitespace() { + } else if c.is_whitespace() || matches!(c, '\u{200E}' | '\u{200F}' | '\u{FEFF}') { + // Rust also reads the left-to-right and right-to-left marks as white space, and skips a byte + // order mark at the start of a file. i += 1; } else if c == '/' && at(i + 1) == Some('/') { while i < len && chars[i] != '\n' { diff --git a/crates/testkit/tests/guards.rs b/crates/testkit/tests/guards.rs index 5014703a46..b820b07272 100644 --- a/crates/testkit/tests/guards.rs +++ b/crates/testkit/tests/guards.rs @@ -1446,6 +1446,10 @@ fn guards_read_names_that_hold_combining_marks() { let menu = "use muda::{PredefinedMenuItem as Ite\u{301}m};\nfn menu() {\n let a = Ite\u{301}m::quit(None);\n}\n"; assert_eq!(lines(&predefined_quit([("src/menu.rs", menu)])), vec![3]); + + // A byte order mark and the left-to-right and right-to-left marks are not part of a name. + let marked = "\u{FEFF}use std::time::Instant;\nuse std::time as\u{200E}t;\nfn run() { t\u{200F}::Instant::now(); }\n"; + assert_eq!(lines(&std_instant([("src/marked.rs", marked)])), vec![1, 3]); } #[test] From 7120e4a2e57d312f6f0428691d985359892e218f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 19 Nov 2026 20:35:59 -0800 Subject: [PATCH 25/33] craft-testkit: a package's build.rs and binary main.rs stay crate roots Cargo builds a package's `build.rs` and `src/bin//main.rs` (and `main.rs` one folder inside `tests`, `examples` or `benches`) as crates of their own, also when another file loads them through `#[path]`. predefined_quit now reads their `extern crate muda as menu;` as a crate root's. --- crates/testkit/src/guards.rs | 49 +++++++++++++++++++++------------- crates/testkit/tests/guards.rs | 7 +++++ 2 files changed, 38 insertions(+), 18 deletions(-) diff --git a/crates/testkit/src/guards.rs b/crates/testkit/src/guards.rs index 988f102e60..d6b7f13f59 100644 --- a/crates/testkit/src/guards.rs +++ b/crates/testkit/src/guards.rs @@ -1466,13 +1466,10 @@ fn extern_crates(toks: &[Token]) -> Vec<(bool, &str, usize)> { /// For each of `paths`, the names that an `extern crate muda as m;` outside any braces of its crate root adds /// to the crate's extern prelude, so that a path starting with `::m` names muda anywhere in the crate. /// -/// The crate roots follow Cargo's layout: `src/lib.rs` and `src/main.rs`; `build.rs` and another `lib.rs` or -/// `main.rs` (such as `src/bin/tool/main.rs`) when no `mod` declaration in another of the files names it, -/// plainly or through a `#[path]` attribute; each file directly in a package's `src/bin`, `tests`, `examples` -/// or `benches` folder (one with no `src`, `bin`, `tests`, `examples` or `benches` folder above it), other than -/// `mod.rs`; and each other file directly in a -/// `bin`, `examples`, `tests` or `benches` folder other than `mod.rs` when no declaration without a `#[path]` -/// attribute names it. A root's +/// The crate roots follow Cargo's layout: `src/lib.rs` and `src/main.rs`; each file that [`cargo_target`] +/// accepts; another `build.rs`, `lib.rs` or `main.rs` when no `mod` declaration in another of the files names +/// it, plainly or through a `#[path]` attribute; and each other file directly in a `bin`, `examples`, `tests` +/// or `benches` folder other than `mod.rs` when no declaration without a `#[path]` attribute names it. A root's /// names reach every file that a chain of declarations /// from it names, where a crate root and a file loaded through a `#[path]` attribute have their modules in their /// own folder, as [`module_files`] reads them. @@ -1515,18 +1512,14 @@ fn extern_prelude_names(paths: &[String], contents: &[&str]) -> Vec true, (Some("lib.rs" | "main.rs" | "build.rs"), _) => !named[file], - (Some(name), Some(folder @ ("bin" | "examples" | "tests" | "benches"))) => { - // Cargo builds each file in a package's `src/bin`, `tests`, `examples` or `benches` folder as a - // crate of its own, also when another of them declares it as a module. Such a folder inside - // `src` or inside another of these folders holds modules. - let target = (folder != "bin" || segments.next() == Some("src")) - && !segments.any(|s| matches!(s, "src" | "bin" | "tests" | "examples" | "benches")); - name.ends_with(".rs") && name != "mod.rs" && (target || !named_plainly[file]) - } + (Some(name), Some("bin" | "examples" | "tests" | "benches")) => name.ends_with(".rs") && name != "mod.rs" && !named_plainly[file], _ => false, } }; @@ -1550,6 +1543,26 @@ fn extern_prelude_names(paths: &[String], contents: &[&str]) -> Vec bool { + let mut segments = path.rsplit('/'); + let Some(name) = segments.next() else { return false }; + if name == "mod.rs" || !name.ends_with(".rs") { + return false; + } + let folders: Vec<&str> = segments.collect(); + let package = |rest: &[&str]| !rest.iter().any(|s| matches!(*s, "src" | "bin" | "tests" | "examples" | "benches")); + match folders.as_slice() { + ["bin", "src", rest @ ..] | ["tests" | "examples" | "benches", rest @ ..] => package(rest), + [_, "bin", "src", rest @ ..] | [_, "tests" | "examples" | "benches", rest @ ..] if name == "main.rs" => package(rest), + rest if name == "build.rs" => package(rest), + _ => false, + } +} + /// The names of the muda crate in a file, and where each is bound. The names are `muda` itself, each name /// in `prelude` (see [`extern_prelude_names`]), which names the crate as `muda` does, and each name that /// `use muda as m;`, `use muda::{self as m};` or `extern crate muda as m;` gives it. For each @@ -1645,9 +1658,9 @@ fn muda_crate_bindings<'a>( /// `extern crate muda as menu;` outside any braces of a crate root (`src/lib.rs` and `src/main.rs`; `build.rs`, /// another `lib.rs` or `main.rs`, or a file directly in a `bin`, `examples`, `tests` or `benches` folder other /// than `mod.rs`, unless a `mod` declaration in another of `files` names it, for a file in those folders one -/// without a `#[path]` attribute; a file directly in a package's `src/bin`, `tests`, `examples` or `benches` -/// folder, one with no such folder or `src` above it, is a crate root even when a declaration names it) also -/// adds `menu` to +/// without a `#[path]` attribute; a package's `build.rs`, a file directly in its `src/bin`, `tests`, `examples` +/// or `benches` folder, and a `main.rs` one folder below those, are crate roots even when a declaration names +/// them, where a package folder has no such folder or `src` above it) also adds `menu` to /// the crate's extern prelude, so in that file and in every file of `files` that a chain of `mod` /// declarations from it names, `menu` is read like `muda` and `::menu::PredefinedMenuItem::quit` is /// reported. Elsewhere a path that starts with `::` names the crate only through `muda`. It also diff --git a/crates/testkit/tests/guards.rs b/crates/testkit/tests/guards.rs index b820b07272..9b5b9d9567 100644 --- a/crates/testkit/tests/guards.rs +++ b/crates/testkit/tests/guards.rs @@ -607,6 +607,13 @@ mod nested { ("src/bin/helper.rs", local), ]); assert_eq!(found.iter().map(|f| (f.path.as_str(), f.line)).collect::>(), vec![("tests/part.rs", 2), ("src/bin/helper.rs", 2)]); + // A package's `build.rs` and a binary's `main.rs` stay roots when a file loads them through `#[path]`. + let found = predefined_quit([ + ("src/lib.rs", "#[path = \"../build.rs\"]\nmod build;\n#[path = \"bin/tool/main.rs\"]\nmod tool;\n"), + ("build.rs", local), + ("src/bin/tool/main.rs", local), + ]); + assert_eq!(found.iter().map(|f| (f.path.as_str(), f.line)).collect::>(), vec![("build.rs", 2), ("src/bin/tool/main.rs", 2)]); // A `tests` folder inside a test's module folder holds modules, so a declared file there is not a root. assert!( predefined_quit([ From c451df07ae0d91a3dcf11ccda1a7145da60eba0b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 19 Nov 2026 20:40:23 -0800 Subject: [PATCH 26/33] craft-testkit: a src folder above the package keeps its targets crate roots `rust_sources` returns paths that include the folder it was given, so a package under a folder such as `~/src` made every `src/bin` file and its `build.rs` look nested, and predefined_quit missed `::menu` calls after their `extern crate muda as menu;`. Files directly in `src/bin`, and `main.rs` one folder below it, are now always crate roots, and another target folder counts as nested only directly inside `src` or below a `bin`, `tests`, `examples` or `benches` folder. --- crates/testkit/src/guards.rs | 23 ++++++++++++++--------- crates/testkit/tests/guards.rs | 11 +++++++++++ 2 files changed, 25 insertions(+), 9 deletions(-) diff --git a/crates/testkit/src/guards.rs b/crates/testkit/src/guards.rs index d6b7f13f59..032a175cb3 100644 --- a/crates/testkit/src/guards.rs +++ b/crates/testkit/src/guards.rs @@ -1544,9 +1544,11 @@ fn extern_prelude_names(paths: &[String], contents: &[&str]) -> Vec bool { let mut segments = path.rsplit('/'); let Some(name) = segments.next() else { return false }; @@ -1554,10 +1556,12 @@ fn cargo_target(path: &str) -> bool { return false; } let folders: Vec<&str> = segments.collect(); - let package = |rest: &[&str]| !rest.iter().any(|s| matches!(*s, "src" | "bin" | "tests" | "examples" | "benches")); + let package = |rest: &[&str]| rest.first() != Some(&"src") && !rest.iter().any(|s| matches!(*s, "bin" | "tests" | "examples" | "benches")); match folders.as_slice() { - ["bin", "src", rest @ ..] | ["tests" | "examples" | "benches", rest @ ..] => package(rest), - [_, "bin", "src", rest @ ..] | [_, "tests" | "examples" | "benches", rest @ ..] if name == "main.rs" => package(rest), + ["bin", "src", ..] => true, + [_, "bin", "src", ..] if name == "main.rs" => true, + ["tests" | "examples" | "benches", rest @ ..] => package(rest), + [_, "tests" | "examples" | "benches", rest @ ..] if name == "main.rs" => package(rest), rest if name == "build.rs" => package(rest), _ => false, } @@ -1658,9 +1662,10 @@ fn muda_crate_bindings<'a>( /// `extern crate muda as menu;` outside any braces of a crate root (`src/lib.rs` and `src/main.rs`; `build.rs`, /// another `lib.rs` or `main.rs`, or a file directly in a `bin`, `examples`, `tests` or `benches` folder other /// than `mod.rs`, unless a `mod` declaration in another of `files` names it, for a file in those folders one -/// without a `#[path]` attribute; a package's `build.rs`, a file directly in its `src/bin`, `tests`, `examples` -/// or `benches` folder, and a `main.rs` one folder below those, are crate roots even when a declaration names -/// them, where a package folder has no such folder or `src` above it) also adds `menu` to +/// without a `#[path]` attribute; a file directly in `src/bin`, a package's `build.rs`, a file directly in its +/// `tests`, `examples` or `benches` folder, and a `main.rs` one folder below those, are crate roots even when a +/// declaration names them, where a package folder is not directly inside `src` and has no `bin`, `tests`, +/// `examples` or `benches` folder above it) also adds `menu` to /// the crate's extern prelude, so in that file and in every file of `files` that a chain of `mod` /// declarations from it names, `menu` is read like `muda` and `::menu::PredefinedMenuItem::quit` is /// reported. Elsewhere a path that starts with `::` names the crate only through `muda`. It also diff --git a/crates/testkit/tests/guards.rs b/crates/testkit/tests/guards.rs index 9b5b9d9567..a8823795ba 100644 --- a/crates/testkit/tests/guards.rs +++ b/crates/testkit/tests/guards.rs @@ -614,6 +614,17 @@ mod nested { ("src/bin/tool/main.rs", local), ]); assert_eq!(found.iter().map(|f| (f.path.as_str(), f.line)).collect::>(), vec![("build.rs", 2), ("src/bin/tool/main.rs", 2)]); + // A folder named `src` above the package, as in a path `rust_sources` returns, does not change that. + let found = predefined_quit([ + ("/home/dev/src/app/src/bin/tool.rs", "mod helper;\n"), + ("/home/dev/src/app/src/bin/helper.rs", local), + ("/home/dev/src/app/src/lib.rs", "#[path = \"../build.rs\"]\nmod build;\n"), + ("/home/dev/src/app/build.rs", local), + ]); + assert_eq!( + found.iter().map(|f| (f.path.as_str(), f.line)).collect::>(), + vec![("/home/dev/src/app/src/bin/helper.rs", 2), ("/home/dev/src/app/build.rs", 2)] + ); // A `tests` folder inside a test's module folder holds modules, so a declared file there is not a root. assert!( predefined_quit([ From 1b5bcc24f0aa643cd8b08f20070c03831c50c1c9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 19 Nov 2026 21:39:24 -0800 Subject: [PATCH 27/33] craft-testkit: predefined_quit skips never-compiled and macro-input root aliases - A `mod` or `extern crate` declaration in an item whose `cfg` is false on every configuration (`cfg(any())`, `cfg(false)`, `cfg(not(all()))`) no longer carries a crate root's `extern crate muda as m;` alias to other files or binds `m` in its own file. A predicate that is false only on some targets still counts. - An `extern crate` inside parentheses or brackets, such as a macro's input, is not read as a declaration. - A `mod.rs` directly in `src/bin`, `tests`, `examples` or `benches` is a crate root, as Cargo's auto-discovery builds it as a target. - Target folders are read below the package folder only: the nearest folder above a file that holds a `src/lib.rs` or `src/main.rs` among the scanned files. A package under a folder named `tests` keeps its `build.rs` and test files as crate roots. --- crates/testkit/src/guards.rs | 125 ++++++++++++++++++++++++--------- crates/testkit/tests/guards.rs | 55 ++++++++++++++- 2 files changed, 145 insertions(+), 35 deletions(-) diff --git a/crates/testkit/src/guards.rs b/crates/testkit/src/guards.rs index 032a175cb3..f344ada063 100644 --- a/crates/testkit/src/guards.rs +++ b/crates/testkit/src/guards.rs @@ -642,8 +642,9 @@ impl Tri { } } -/// Evaluate the `cfg` predicate at `toks[*pos]` for `wasm32-unknown-unknown`. -fn eval_cfg(toks: &[Token], pos: &mut usize, depth: usize) -> Tri { +/// Evaluate the `cfg` predicate at `toks[*pos]` for `wasm32-unknown-unknown`, or with `every` for every +/// configuration at once, where only `true`, `false` and the operators over them have a known value. +fn eval_cfg(toks: &[Token], pos: &mut usize, depth: usize, every: bool) -> Tri { let Some(Kind::Ident(name)) = toks.get(*pos).map(|t| &t.kind) else { return Tri::Unknown; }; @@ -654,6 +655,9 @@ fn eval_cfg(toks: &[Token], pos: &mut usize, depth: usize) -> Tri { _ => return Tri::Unknown, }; *pos += 2; + if every { + return Tri::Unknown; + } let expected = match name.as_str() { "target_arch" => "wasm32", "target_os" | "target_vendor" => "unknown", @@ -683,7 +687,7 @@ fn eval_cfg(toks: &[Token], pos: &mut usize, depth: usize) -> Tri { continue; } let before = *pos; - values.push(eval_cfg(toks, pos, depth + 1)); + values.push(eval_cfg(toks, pos, depth + 1, every)); if *pos == before { *pos += 1; } @@ -700,7 +704,8 @@ fn eval_cfg(toks: &[Token], pos: &mut usize, depth: usize) -> Tri { }; } match name.as_str() { - "unix" | "windows" | "false" => Tri::False, + "false" => Tri::False, + "unix" | "windows" if !every => Tri::False, "true" => Tri::True, _ => Tri::Unknown, } @@ -925,12 +930,23 @@ fn item_end_at(toks: &[Token], start: usize, inner: bool, nested: usize) -> usiz /// An outer attribute (`#[cfg(...)]`) covers the item after it; an inner attribute (`#![cfg(...)]`) /// covers the rest of the module or block it is in. fn native_only(toks: &[Token]) -> Vec { - cfg_covered(toks, false) + cfg_covered(toks, Cover::NativeOnly) } -/// Mark the tokens of every item that a `cfg` attribute covers: with `any`, whatever its predicate, -/// otherwise only when the predicate is false on `wasm32-unknown-unknown`, as [`native_only`] does. -fn cfg_covered(toks: &[Token], any: bool) -> Vec { +/// Which `cfg` attributes [`cfg_covered`] marks the items of. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Cover { + /// Every `cfg` attribute, whatever its predicate. + Any, + /// A `cfg` attribute whose predicate is false on `wasm32-unknown-unknown`, as [`native_only`] reads it. + NativeOnly, + /// A `cfg` attribute whose predicate is false on every configuration, such as `cfg(any())` or + /// `cfg(false)`, so the item is never compiled. + Never, +} + +/// Mark the tokens of every item that a `cfg` attribute selected by `cover` covers. +fn cfg_covered(toks: &[Token], cover: Cover) -> Vec { let mut skip = vec![false; toks.len()]; let mut i = 0; while i < toks.len() { @@ -951,7 +967,7 @@ fn cfg_covered(toks: &[Token], any: bool) -> Vec { } let excluded = toks.get(open + 1).is_some_and(|t| t.is_ident("cfg")) && toks.get(open + 2).is_some_and(|t| t.is_punct('(')) && { let mut pos = open + 3; - any || eval_cfg(&toks[..close], &mut pos, 0) == Tri::False + cover == Cover::Any || eval_cfg(&toks[..close], &mut pos, 0, cover == Cover::Never) == Tri::False }; if !excluded { i = close + 1; @@ -991,7 +1007,7 @@ fn cfg_items(toks: &[Token]) -> BTreeSet { break; } let mut pos = i + 4; - if eval_cfg(&toks[..close], &mut pos, 0) == Tri::True { + if eval_cfg(&toks[..close], &mut pos, 0, false) == Tri::True { i = close + 1; continue; } @@ -1028,7 +1044,9 @@ struct ModDecl { /// The inline modules (`mod a { ... }`) the declaration is inside, outermost first, shared between the /// declarations inside them. inline: Vec>, - /// Whether the declaration is inside an item whose `cfg` is false on `wasm32-unknown-unknown`. + /// Whether the `skip` tokens given to [`module_decls`] cover the declaration: for [`std_instant`], an + /// item whose `cfg` is false on `wasm32-unknown-unknown`, and for [`predefined_quit`], one that is never + /// compiled. native: bool, } @@ -1444,11 +1462,21 @@ fn report(findings: &mut Vec, path: &str, content: &str, lines: &BTreeS type CrateBindings<'a> = BTreeMap<(&'a str, Option), (bool, bool)>; /// Each `extern crate c;` or `extern crate c as n;` in a file: whether `c` is muda, the name it binds, and -/// the index of that name. -fn extern_crates(toks: &[Token]) -> Vec<(bool, &str, usize)> { +/// the index of that name. A declaration in an item that `never` marks (see [`Cover::Never`]) is left out, +/// and so are the tokens inside parentheses or brackets, such as the input of `m!(...)`, since an item +/// is not written there. +fn extern_crates<'a>(toks: &'a [Token], never: &[bool]) -> Vec<(bool, &'a str, usize)> { let mut externs = Vec::new(); + let mut depth = 0usize; for i in 0..toks.len() { - if toks[i].is_ident("extern") + if toks[i].is_punct('(') || toks[i].is_punct('[') { + depth += 1; + } else if toks[i].is_punct(')') || toks[i].is_punct(']') { + depth = depth.saturating_sub(1); + } + if depth == 0 + && !never.get(i).copied().unwrap_or(false) + && toks[i].is_ident("extern") && toks.get(i + 1).is_some_and(|t| t.is_ident("crate")) && let Some(Kind::Ident(krate)) = toks.get(i + 2).map(|t| &t.kind) { @@ -1472,7 +1500,8 @@ fn extern_crates(toks: &[Token]) -> Vec<(bool, &str, usize)> { /// or `benches` folder other than `mod.rs` when no declaration without a `#[path]` attribute names it. A root's /// names reach every file that a chain of declarations /// from it names, where a crate root and a file loaded through a `#[path]` attribute have their modules in their -/// own folder, as [`module_files`] reads them. +/// own folder, as [`module_files`] reads them. A declaration in an item whose `cfg` is false on every +/// configuration neither adds a name nor loads a file. fn extern_prelude_names(paths: &[String], contents: &[&str]) -> Vec> { let mut index: BTreeMap<&str, Vec> = BTreeMap::new(); for (i, path) in paths.iter().enumerate() { @@ -1482,10 +1511,16 @@ fn extern_prelude_names(paths: &[String], contents: &[&str]) -> Vec> = Vec::with_capacity(paths.len()); for content in contents { let toks = lex_rust(content); - decls.push(module_decls(&toks, &vec![false; toks.len()])); + // A declaration in an item that is never compiled loads no file, and its alias is not in the prelude. + let never = cfg_covered(&toks, Cover::Never); + decls.push(module_decls(&toks, &never).into_iter().filter(|decl| !decl.native).collect()); let (around, _) = brace_scopes(&toks); aliases.push( - extern_crates(&toks).into_iter().filter(|&(muda, _, at)| muda && around[at].is_none()).map(|(_, name, _)| name.to_owned()).collect(), + extern_crates(&toks, &never) + .into_iter() + .filter(|&(muda, _, at)| muda && around[at].is_none()) + .map(|(_, name, _)| name.to_owned()) + .collect(), ); } // Node `2 * file` is the file loaded plainly (or as a crate root) and node `2 * file + 1` the file loaded @@ -1511,8 +1546,9 @@ fn extern_prelude_names(paths: &[String], contents: &[&str]) -> Vec Vec BTreeSet<&str> { + paths + .iter() + .filter_map(|path| path.strip_suffix("src/lib.rs").or_else(|| path.strip_suffix("src/main.rs"))) + .filter_map(|dir| dir.strip_suffix('/').or_else(|| dir.is_empty().then_some(""))) + .collect() +} + /// Whether Cargo builds `path` as a crate root of its own, also when another file declares it as a module: -/// each file other than `mod.rs` directly in a `src/bin` folder and each `main.rs` one folder below it; and in -/// a package folder, `build.rs`, each file other than `mod.rs` directly in its `tests`, `examples` or `benches` -/// folder, and each `main.rs` one folder below those. A package folder is one that is not directly inside -/// `src` and has no `bin`, `tests`, `examples` or `benches` folder above it, so a folder of that name inside -/// `src` or inside one of those folders holds modules. -fn cargo_target(path: &str) -> bool { - let mut segments = path.rsplit('/'); +/// each file directly in a `src/bin` folder and each `main.rs` one folder below it; and in a package folder, +/// `build.rs`, each file directly in its `tests`, `examples` or `benches` folder, and each `main.rs` one +/// folder below those. Cargo's auto-discovery takes a `mod.rs` directly in those folders as a target too. +/// The package folder is the nearest folder above `path` in `packages` (see [`package_folders`]). Without +/// one, a package folder is one that is not directly inside `src` and has no `bin`, `tests`, `examples` or +/// `benches` folder above it, so a folder of that name inside `src` or inside one of those folders holds +/// modules. With one, only the folders below it count. +fn cargo_target(path: &str, packages: &BTreeSet<&str>) -> bool { + let inside = path.rmatch_indices('/').map(|(i, _)| i).find(|&i| i > 0 && packages.contains(&path[..i])).map(|i| &path[i + 1..]); + let inside = inside.or_else(|| (packages.contains("") && !path.starts_with('/')).then_some(path)); + let mut segments = inside.unwrap_or(path).rsplit('/'); let Some(name) = segments.next() else { return false }; - if name == "mod.rs" || !name.ends_with(".rs") { + if !name.ends_with(".rs") { return false; } let folders: Vec<&str> = segments.collect(); @@ -1573,15 +1623,17 @@ fn cargo_target(path: &str) -> bool { /// name and each pair of braces, the bindings record whether a `use` or an `extern crate` in them binds /// the name to the crate, and whether a `use`, an `extern crate` or a `mod` in them binds it to something /// else. A binding to something else inside an item with a `cfg` attribute, or through `crate::`, `self::` -/// or `super::` (which may be a re-export of the crate), is left out. +/// or `super::` (which may be a re-export of the crate), is left out, and so is an `extern crate` in an +/// item that `never` marks or inside parentheses or brackets (see [`extern_crates`]). fn muda_crate_bindings<'a>( toks: &'a [Token], leaves: &'a [UseLeaf], around: &[Option], gated: &[bool], + never: &[bool], prelude: &'a BTreeSet, ) -> (BTreeSet<&'a str>, CrateBindings<'a>) { - let externs = extern_crates(toks); + let externs = extern_crates(toks, never); // Whether a `use` path names the crate itself: `muda`, or a name of the crate in the extern prelude. let crate_path = |leaf: &UseLeaf| leaf.path.len() == 1 && (leaf.path[0] == "muda" || prelude.contains(&leaf.path[0])); let mut names: BTreeSet<&'a str> = BTreeSet::from(["muda"]); @@ -1663,12 +1715,16 @@ fn muda_crate_bindings<'a>( /// another `lib.rs` or `main.rs`, or a file directly in a `bin`, `examples`, `tests` or `benches` folder other /// than `mod.rs`, unless a `mod` declaration in another of `files` names it, for a file in those folders one /// without a `#[path]` attribute; a file directly in `src/bin`, a package's `build.rs`, a file directly in its -/// `tests`, `examples` or `benches` folder, and a `main.rs` one folder below those, are crate roots even when a -/// declaration names them, where a package folder is not directly inside `src` and has no `bin`, `tests`, -/// `examples` or `benches` folder above it) also adds `menu` to +/// `tests`, `examples` or `benches` folder, `mod.rs` included, and a `main.rs` one folder below those, are crate +/// roots even when a declaration names them, where the package folder is the nearest folder above the file +/// that holds a `src/lib.rs` or `src/main.rs` of `files`, and without one, a folder not directly inside `src` +/// with no `bin`, `tests`, `examples` or `benches` folder above it) also adds `menu` to /// the crate's extern prelude, so in that file and in every file of `files` that a chain of `mod` /// declarations from it names, `menu` is read like `muda` and `::menu::PredefinedMenuItem::quit` is -/// reported. Elsewhere a path that starts with `::` names the crate only through `muda`. It also +/// reported. An `extern crate` or `mod` declaration in an item whose `cfg` is false on every configuration +/// (`cfg(any())`, `cfg(false)`) is read as absent, and so are the tokens of an `extern crate` inside +/// parentheses or brackets, such as a macro's input. Elsewhere a path that starts with `::` names the crate +/// only through `muda`. It also /// follows a `use` or a `type` alias that renames muda's type (`use muda::PredefinedMenuItem as Item;` then /// `Item::quit`); a rename of another crate's `PredefinedMenuItem` is not followed, including one through a /// name `muda` that the braces around the `use` or `type` bind to something else, read as for a qualified @@ -1698,8 +1754,9 @@ where let toks = lex_rust(content); let leaves = use_leaves(&toks, &BTreeSet::new()); let (around, opener) = brace_scopes(&toks); - let gated = cfg_covered(&toks, true); - let (crate_names, crate_bound) = muda_crate_bindings(&toks, &leaves, &around, &gated, &prelude[index]); + let gated = cfg_covered(&toks, Cover::Any); + let never = cfg_covered(&toks, Cover::Never); + let (crate_names, crate_bound) = muda_crate_bindings(&toks, &leaves, &around, &gated, &never, &prelude[index]); let names_crate = |s: &str| crate_names.contains(s); // Whether `name`, read at token `i`, names the crate. After a leading `::`, `muda` does, and so // does a name that `extern crate muda as name;` outside any braces of the file's crate root gives it diff --git a/crates/testkit/tests/guards.rs b/crates/testkit/tests/guards.rs index a8823795ba..63028ddc71 100644 --- a/crates/testkit/tests/guards.rs +++ b/crates/testkit/tests/guards.rs @@ -552,7 +552,10 @@ mod nested { let module = "extern crate muda as menu;\nfn menu_bar() {\n let a = ::menu::PredefinedMenuItem::quit(None);\n let b = menu::PredefinedMenuItem::quit(None);\n}\n"; assert_eq!(lines(&predefined_quit([("src/child.rs", module)])), vec![4]); assert_eq!(lines(&predefined_quit([("src/bin/tool.rs", module)])), vec![3, 4]); - assert_eq!(lines(&predefined_quit([("src/bin/mod.rs", module)])), vec![4]); + // Cargo's auto-discovery builds a `mod.rs` directly in `src/bin` or `tests` as a target, but not one below. + assert_eq!(lines(&predefined_quit([("src/bin/mod.rs", module)])), vec![3, 4]); + assert_eq!(lines(&predefined_quit([("tests/mod.rs", module)])), vec![3, 4]); + assert_eq!(lines(&predefined_quit([("src/bin/tool/mod.rs", module)])), vec![4]); // A `lib.rs` that another file loads through a `#[path]` attribute is a module. let root = "#[path = \"nested/lib.rs\"]\nmod nested;\n"; assert_eq!(lines(&predefined_quit([("src/lib.rs", root), ("src/nested/lib.rs", module)])), vec![4]); @@ -642,6 +645,56 @@ mod nested { assert!(found.is_empty()); } +#[test] +fn predefined_quit_skips_root_aliases_that_are_never_compiled_or_in_macro_input() { + let call = "fn f() { ::menu::PredefinedMenuItem::quit(None); }\n"; + let paths = |found: &[Finding]| found.iter().map(|f| (f.path.clone(), f.line)).collect::>(); + // A module declaration that is never compiled does not carry the alias to the file it names. + for gate in ["#[cfg(any())]", "#[cfg(false)]", "#[cfg(not(all()))]"] { + let lib = format!("extern crate muda as menu;\n{gate}\nmod shared;\n{gate}\n#[path = \"other.rs\"]\nmod other;\n"); + let main = "extern crate other_menu as menu;\nmod shared;\n"; + let found = predefined_quit([("src/lib.rs", lib.as_str()), ("src/main.rs", main), ("src/shared.rs", call), ("src/other.rs", call)]); + assert!(found.is_empty(), "{gate}: {found:?}"); + } + // One that a target may compile still does, plainly or through `#[path]`. + let lib = "extern crate muda as menu;\n#[cfg(unix)]\nmod shared;\n#[cfg(feature = \"x\")]\n#[path = \"other.rs\"]\nmod other;\n"; + let found = predefined_quit([("src/lib.rs", lib), ("src/shared.rs", call), ("src/other.rs", call)]); + assert_eq!(paths(&found), vec![("src/shared.rs".to_owned(), 1), ("src/other.rs".to_owned(), 1)]); + // An `extern crate` that is never compiled adds no name to the prelude; one that is false only on some + // targets does. + let lib = "#[cfg(any())]\nextern crate muda as menu;\nextern crate other_menu as menu;\nmod child;\nfn g() { ::menu::PredefinedMenuItem::quit(None); }\n"; + assert!(predefined_quit([("src/lib.rs", lib), ("src/child.rs", call)]).is_empty()); + let lib = "#[cfg(target_os = \"macos\")]\nextern crate muda as menu;\nmod child;\n"; + assert_eq!(paths(&predefined_quit([("src/lib.rs", lib), ("src/child.rs", call)])), vec![("src/child.rs".to_owned(), 1)]); + // Neither does an `extern crate` in a macro's input, while a real one beside it does. + for input in ["ignore!(extern crate muda as menu;);", "ignore![extern crate muda as menu;];"] { + let lib = format!("{input}\nmod child;\n"); + assert!(predefined_quit([("src/lib.rs", lib.as_str()), ("src/child.rs", call)]).is_empty(), "{input}"); + let lib = format!("{input}\nextern crate muda as native;\nmod child;\n"); + let child = "fn f() { ::native::PredefinedMenuItem::quit(None); ::menu::PredefinedMenuItem::quit(None); }\n"; + assert_eq!(paths(&predefined_quit([("src/lib.rs", lib.as_str()), ("src/child.rs", child)])), vec![("src/child.rs".to_owned(), 1)]); + } + // In a file, a never-compiled or macro-input `extern crate muda as menu;` does not bind `menu` to muda. + let module = "mod a {\n #[cfg(any())]\n extern crate muda as menu;\n fn f() { menu::PredefinedMenuItem::quit(None); }\n}\n\ + mod b {\n ignore!(extern crate muda as menu;);\n fn f() { menu::PredefinedMenuItem::quit(None); }\n}\n"; + assert!(predefined_quit([("src/child.rs", module)]).is_empty()); +} + +#[test] +fn predefined_quit_reads_target_folders_below_the_package_folder_only() { + let local = "extern crate muda as menu;\nfn f() { ::menu::PredefinedMenuItem::quit(None); }\n"; + let lib = "#[path = \"../build.rs\"]\nmod build;\n#[path = \"../tests/t.rs\"]\nmod t;\n"; + for dir in ["/work/tests/app", "tests/app", "C:/src/bin/app"] { + let (lib_path, build, test) = (format!("{dir}/src/lib.rs"), format!("{dir}/build.rs"), format!("{dir}/tests/t.rs")); + let found = predefined_quit([(lib_path.as_str(), lib), (build.as_str(), local), (test.as_str(), local)]); + let found: Vec<(&str, usize)> = found.iter().map(|f| (f.path.as_str(), f.line)).collect(); + assert_eq!(found, vec![(build.as_str(), 2), (test.as_str(), 2)], "{dir}"); + } + // Inside the package a `tests` folder in `src` still holds modules. + let lib = "mod tests;\n"; + assert!(predefined_quit([("/work/tests/app/src/lib.rs", lib), ("/work/tests/app/src/tests/mod.rs", local)]).is_empty()); +} + #[test] fn predefined_quit_reads_a_crate_name_in_an_import_where_the_import_is() { let source = r#" From 99cdde8d71c885482dc065845d543abf12ec6438 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 19 Nov 2026 21:49:17 -0800 Subject: [PATCH 28/33] craft-testkit: read target folders at their place in a known package only With a package folder found among the scanned files, `cargo_target` accepts only Cargo's own target places below it (`build.rs`, `src/bin/*.rs`, `src/bin/*/main.rs`, and the same in `tests`, `examples` and `benches`), so `src/foo/tests/helper.rs` and `src/foo/src/bin/x.rs` stay modules. A folder that holds files directly in `src/bin` is also a package folder, unless it is inside the `src` folder of a package with a `src/lib.rs` or `src/main.rs`, so a binary-only package keeps its binaries as crate roots. --- crates/testkit/src/guards.rs | 38 +++++++++++++++++++++++++++------- crates/testkit/tests/guards.rs | 18 ++++++++++++++++ 2 files changed, 49 insertions(+), 7 deletions(-) diff --git a/crates/testkit/src/guards.rs b/crates/testkit/src/guards.rs index f344ada063..ad44d0a4cf 100644 --- a/crates/testkit/src/guards.rs +++ b/crates/testkit/src/guards.rs @@ -1579,14 +1579,29 @@ fn extern_prelude_names(paths: &[String], contents: &[&str]) -> Vec BTreeSet<&str> { - paths + fn folder(dir: &str) -> Option<&str> { + dir.strip_suffix('/').or_else(|| dir.is_empty().then_some("")) + } + let roots: BTreeSet<&str> = + paths.iter().filter_map(|path| path.strip_suffix("src/lib.rs").or_else(|| path.strip_suffix("src/main.rs"))).filter_map(folder).collect(); + let in_src = |dir: &str| { + roots.iter().any(|root| { + let src = if root.is_empty() { "src".to_owned() } else { format!("{root}/src") }; + dir == src || dir.starts_with(&format!("{src}/")) + }) + }; + let bins: Vec<&str> = paths .iter() - .filter_map(|path| path.strip_suffix("src/lib.rs").or_else(|| path.strip_suffix("src/main.rs"))) - .filter_map(|dir| dir.strip_suffix('/').or_else(|| dir.is_empty().then_some(""))) - .collect() + .filter_map(|path| path.rsplit_once('/').map(|(dir, _)| dir)) + .filter_map(|dir| dir.strip_suffix("src/bin")) + .filter_map(folder) + .filter(|dir| !in_src(dir)) + .collect(); + roots.into_iter().chain(bins).collect() } /// Whether Cargo builds `path` as a crate root of its own, also when another file declares it as a module: @@ -1596,7 +1611,8 @@ fn package_folders(paths: &[String]) -> BTreeSet<&str> { /// The package folder is the nearest folder above `path` in `packages` (see [`package_folders`]). Without /// one, a package folder is one that is not directly inside `src` and has no `bin`, `tests`, `examples` or /// `benches` folder above it, so a folder of that name inside `src` or inside one of those folders holds -/// modules. With one, only the folders below it count. +/// modules. With one, only those places directly below it count, so `src/foo/tests/helper.rs` and +/// `src/foo/src/bin/helper.rs` hold modules. fn cargo_target(path: &str, packages: &BTreeSet<&str>) -> bool { let inside = path.rmatch_indices('/').map(|(i, _)| i).find(|&i| i > 0 && packages.contains(&path[..i])).map(|i| &path[i + 1..]); let inside = inside.or_else(|| (packages.contains("") && !path.starts_with('/')).then_some(path)); @@ -1606,6 +1622,14 @@ fn cargo_target(path: &str, packages: &BTreeSet<&str>) -> bool { return false; } let folders: Vec<&str> = segments.collect(); + if inside.is_some() { + return match folders.as_slice() { + ["bin", "src"] | ["tests" | "examples" | "benches"] => true, + [_, "bin", "src"] | [_, "tests" | "examples" | "benches"] => name == "main.rs", + [] => name == "build.rs", + _ => false, + }; + } let package = |rest: &[&str]| rest.first() != Some(&"src") && !rest.iter().any(|s| matches!(*s, "bin" | "tests" | "examples" | "benches")); match folders.as_slice() { ["bin", "src", ..] => true, diff --git a/crates/testkit/tests/guards.rs b/crates/testkit/tests/guards.rs index 63028ddc71..9f11ceb974 100644 --- a/crates/testkit/tests/guards.rs +++ b/crates/testkit/tests/guards.rs @@ -693,6 +693,24 @@ fn predefined_quit_reads_target_folders_below_the_package_folder_only() { // Inside the package a `tests` folder in `src` still holds modules. let lib = "mod tests;\n"; assert!(predefined_quit([("/work/tests/app/src/lib.rs", lib), ("/work/tests/app/src/tests/mod.rs", local)]).is_empty()); + // So do target folder names deeper in the package's modules. + let found = predefined_quit([ + ("src/lib.rs", "mod foo;\nmod src;\n"), + ("src/foo.rs", "mod tests;\nmod src;\n"), + ("src/foo/tests.rs", "mod helper;\n"), + ("src/foo/tests/helper.rs", local), + ("src/foo/src.rs", "mod bin;\n"), + ("src/foo/src/bin.rs", "mod helper;\n"), + ("src/foo/src/bin/helper.rs", local), + ("src/src.rs", "mod bin;\n"), + ("src/src/bin.rs", "mod helper;\n"), + ("src/src/bin/helper.rs", local), + ]); + assert!(found.is_empty(), "{found:?}"); + // A package with only binaries, beside the one with a library, keeps its binaries as roots. + let found = + predefined_quit([("outer/src/lib.rs", ""), ("outer/tools/src/bin/tool.rs", "mod helper;\n"), ("outer/tools/src/bin/helper.rs", local)]); + assert_eq!(found.iter().map(|f| (f.path.as_str(), f.line)).collect::>(), vec![("outer/tools/src/bin/helper.rs", 2)]); } #[test] From ba150c85dcd255f56972dd4ef99c6ae33326a8ad Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 23 Nov 2026 23:56:42 -0800 Subject: [PATCH 29/33] craft-testkit: keep extern crate in argument blocks and module target folders in their package An `extern crate` in a block inside a call's arguments or an array is a real declaration, so predefined_quit now reads it. The tokens skipped are a macro's input in parentheses or brackets, an attribute's input and the body of a `macro_rules!` definition. A file in a `tests`, `bin`, `examples` or `benches` folder inside a known package is a crate root only where cargo_target places it, so a module that a `#[path]` attribute loads from `src/foo/tests/` no longer adds its `extern crate` names to the crate's extern prelude. --- crates/testkit/src/guards.rs | 56 +++++++++++++++++++++++----------- crates/testkit/tests/guards.rs | 32 +++++++++++++++++++ 2 files changed, 71 insertions(+), 17 deletions(-) diff --git a/crates/testkit/src/guards.rs b/crates/testkit/src/guards.rs index ad44d0a4cf..c6058ab62e 100644 --- a/crates/testkit/src/guards.rs +++ b/crates/testkit/src/guards.rs @@ -1463,18 +1463,30 @@ type CrateBindings<'a> = BTreeMap<(&'a str, Option), (bool, bool)>; /// Each `extern crate c;` or `extern crate c as n;` in a file: whether `c` is muda, the name it binds, and /// the index of that name. A declaration in an item that `never` marks (see [`Cover::Never`]) is left out, -/// and so are the tokens inside parentheses or brackets, such as the input of `m!(...)`, since an item -/// is not written there. +/// and so are the tokens of a macro's input in parentheses or brackets, `m!(...)` or `m![...]`, of an +/// attribute, `#[...]` or `#![...]`, and the whole body of a `macro_rules!` definition, whose templates are +/// not expanded where they are written. A +/// declaration in a block inside other parentheses or brackets, such as a call's argument, is kept. fn extern_crates<'a>(toks: &'a [Token], never: &[bool]) -> Vec<(bool, &'a str, usize)> { let mut externs = Vec::new(); - let mut depth = 0usize; + // For each open delimiter, whether it starts a macro's input, an attribute or a `macro_rules!` body; and + // how many of those are open. + let mut open = Vec::new(); + let mut in_macro = 0usize; for i in 0..toks.len() { - if toks[i].is_punct('(') || toks[i].is_punct('[') { - depth += 1; - } else if toks[i].is_punct(')') || toks[i].is_punct(']') { - depth = depth.saturating_sub(1); + if toks[i].is_punct('(') || toks[i].is_punct('[') || toks[i].is_punct('{') { + let ident = |k: usize| matches!(toks[k].kind, Kind::Ident(_)); + let definition = i >= 3 && ident(i - 1) && toks[i - 2].is_punct('!') && toks[i - 3].is_ident("macro_rules"); + let input = !toks[i].is_punct('{') && i >= 2 && toks[i - 1].is_punct('!') && ident(i - 2); + let attribute = + toks[i].is_punct('[') && i >= 1 && (toks[i - 1].is_punct('#') || (i >= 2 && toks[i - 1].is_punct('!') && toks[i - 2].is_punct('#'))); + let skip = input || definition || attribute; + open.push(skip); + in_macro += usize::from(skip); + } else if (toks[i].is_punct(')') || toks[i].is_punct(']') || toks[i].is_punct('}')) && open.pop() == Some(true) { + in_macro = in_macro.saturating_sub(1); } - if depth == 0 + if in_macro == 0 && !never.get(i).copied().unwrap_or(false) && toks[i].is_ident("extern") && toks.get(i + 1).is_some_and(|t| t.is_ident("crate")) @@ -1497,7 +1509,8 @@ fn extern_crates<'a>(toks: &'a [Token], never: &[bool]) -> Vec<(bool, &'a str, u /// The crate roots follow Cargo's layout: `src/lib.rs` and `src/main.rs`; each file that [`cargo_target`] /// accepts; another `build.rs`, `lib.rs` or `main.rs` when no `mod` declaration in another of the files names /// it, plainly or through a `#[path]` attribute; and each other file directly in a `bin`, `examples`, `tests` -/// or `benches` folder other than `mod.rs` when no declaration without a `#[path]` attribute names it. A root's +/// or `benches` folder other than `mod.rs` when no package folder holds it and no declaration without a +/// `#[path]` attribute names it. A root's /// names reach every file that a chain of declarations /// from it names, where a crate root and a file loaded through a `#[path]` attribute have their modules in their /// own folder, as [`module_files`] reads them. A declaration in an item whose `cfg` is false on every @@ -1555,7 +1568,10 @@ fn extern_prelude_names(paths: &[String], contents: &[&str]) -> Vec true, (Some("lib.rs" | "main.rs" | "build.rs"), _) => !named[file], - (Some(name), Some("bin" | "examples" | "tests" | "benches")) => name.ends_with(".rs") && name != "mod.rs" && !named_plainly[file], + // In a known package, `cargo_target` has already placed the target folders. + (Some(name), Some("bin" | "examples" | "tests" | "benches")) => { + name.ends_with(".rs") && name != "mod.rs" && !named_plainly[file] && package_relative(&paths[file], &packages).is_none() + } _ => false, } }; @@ -1614,8 +1630,7 @@ fn package_folders(paths: &[String]) -> BTreeSet<&str> { /// modules. With one, only those places directly below it count, so `src/foo/tests/helper.rs` and /// `src/foo/src/bin/helper.rs` hold modules. fn cargo_target(path: &str, packages: &BTreeSet<&str>) -> bool { - let inside = path.rmatch_indices('/').map(|(i, _)| i).find(|&i| i > 0 && packages.contains(&path[..i])).map(|i| &path[i + 1..]); - let inside = inside.or_else(|| (packages.contains("") && !path.starts_with('/')).then_some(path)); + let inside = package_relative(path, packages); let mut segments = inside.unwrap_or(path).rsplit('/'); let Some(name) = segments.next() else { return false }; if !name.ends_with(".rs") { @@ -1641,6 +1656,13 @@ fn cargo_target(path: &str, packages: &BTreeSet<&str>) -> bool { } } +/// `path` relative to the nearest folder above it in `packages` (see [`package_folders`]), or `None` when no +/// package folder holds it. +fn package_relative<'a>(path: &'a str, packages: &BTreeSet<&str>) -> Option<&'a str> { + let inside = path.rmatch_indices('/').map(|(i, _)| i).find(|&i| i > 0 && packages.contains(&path[..i])).map(|i| &path[i + 1..]); + inside.or_else(|| (packages.contains("") && !path.starts_with('/')).then_some(path)) +} + /// The names of the muda crate in a file, and where each is bound. The names are `muda` itself, each name /// in `prelude` (see [`extern_prelude_names`]), which names the crate as `muda` does, and each name that /// `use muda as m;`, `use muda::{self as m};` or `extern crate muda as m;` gives it. For each @@ -1648,7 +1670,7 @@ fn cargo_target(path: &str, packages: &BTreeSet<&str>) -> bool { /// the name to the crate, and whether a `use`, an `extern crate` or a `mod` in them binds it to something /// else. A binding to something else inside an item with a `cfg` attribute, or through `crate::`, `self::` /// or `super::` (which may be a re-export of the crate), is left out, and so is an `extern crate` in an -/// item that `never` marks or inside parentheses or brackets (see [`extern_crates`]). +/// item that `never` marks, in a macro's input, in an attribute or in a `macro_rules!` body (see [`extern_crates`]). fn muda_crate_bindings<'a>( toks: &'a [Token], leaves: &'a [UseLeaf], @@ -1736,8 +1758,8 @@ fn muda_crate_bindings<'a>( /// imported under (`use muda as menu;`, `use muda::{self as menu};`, `extern crate muda as menu;`) is read /// like `muda` in the braces that bind it, so `menu::PredefinedMenuItem::quit` is reported there. An /// `extern crate muda as menu;` outside any braces of a crate root (`src/lib.rs` and `src/main.rs`; `build.rs`, -/// another `lib.rs` or `main.rs`, or a file directly in a `bin`, `examples`, `tests` or `benches` folder other -/// than `mod.rs`, unless a `mod` declaration in another of `files` names it, for a file in those folders one +/// another `lib.rs` or `main.rs`, or a file outside any package folder directly in a `bin`, `examples`, `tests` +/// or `benches` folder other than `mod.rs`, unless a `mod` declaration in another of `files` names it, for a file in those folders one /// without a `#[path]` attribute; a file directly in `src/bin`, a package's `build.rs`, a file directly in its /// `tests`, `examples` or `benches` folder, `mod.rs` included, and a `main.rs` one folder below those, are crate /// roots even when a declaration names them, where the package folder is the nearest folder above the file @@ -1746,8 +1768,8 @@ fn muda_crate_bindings<'a>( /// the crate's extern prelude, so in that file and in every file of `files` that a chain of `mod` /// declarations from it names, `menu` is read like `muda` and `::menu::PredefinedMenuItem::quit` is /// reported. An `extern crate` or `mod` declaration in an item whose `cfg` is false on every configuration -/// (`cfg(any())`, `cfg(false)`) is read as absent, and so are the tokens of an `extern crate` inside -/// parentheses or brackets, such as a macro's input. Elsewhere a path that starts with `::` names the crate +/// (`cfg(any())`, `cfg(false)`) is read as absent, and so are the tokens of an `extern crate` in a macro's +/// input in parentheses or brackets (`m!(...)`, `m![...]`), in an attribute or in a `macro_rules!` body. Elsewhere a path that starts with `::` names the crate /// only through `muda`. It also /// follows a `use` or a `type` alias that renames muda's type (`use muda::PredefinedMenuItem as Item;` then /// `Item::quit`); a rename of another crate's `PredefinedMenuItem` is not followed, including one through a diff --git a/crates/testkit/tests/guards.rs b/crates/testkit/tests/guards.rs index 9f11ceb974..9b94d78078 100644 --- a/crates/testkit/tests/guards.rs +++ b/crates/testkit/tests/guards.rs @@ -711,6 +711,38 @@ fn predefined_quit_reads_target_folders_below_the_package_folder_only() { let found = predefined_quit([("outer/src/lib.rs", ""), ("outer/tools/src/bin/tool.rs", "mod helper;\n"), ("outer/tools/src/bin/helper.rs", local)]); assert_eq!(found.iter().map(|f| (f.path.as_str(), f.line)).collect::>(), vec![("outer/tools/src/bin/helper.rs", 2)]); + // A file in the package's modules that a `#[path]` attribute loads from a `tests` folder is a module too, + // so its `extern crate` does not reach the crate's extern prelude. + let lib = "extern crate other_menu as menu;\n#[path = \"foo/tests/helper.rs\"]\nmod helper;\n"; + let found = predefined_quit([("src/lib.rs", lib), ("src/foo/tests/helper.rs", local)]); + assert!(found.is_empty(), "{found:?}"); +} + +#[test] +fn predefined_quit_reads_an_extern_crate_in_a_block_inside_call_arguments() { + let call = "fn f() {\n consume({\n extern crate muda as menu;\n menu::PredefinedMenuItem::quit(None)\n });\n}\n"; + assert_eq!(lines(&predefined_quit([("src/child.rs", call)])), vec![4]); + let array = "fn f() {\n let items = [{\n extern crate muda as menu;\n menu::PredefinedMenuItem::quit(None)\n }];\n}\n"; + assert_eq!(lines(&predefined_quit([("src/child.rs", array)])), vec![4]); + // In a crate root, a block in an argument binds the name in the block, not in the extern prelude. + let lib = "fn f() {\n consume({\n extern crate muda as menu;\n });\n}\nmod child;\n"; + let child = "fn g() { ::menu::PredefinedMenuItem::quit(None); }\n"; + assert!(predefined_quit([("src/lib.rs", lib), ("src/child.rs", child)]).is_empty()); + // A `macro_rules!` template is not a declaration where it is written, in any delimiter. + for body in [ + "macro_rules! m {\n () => (\n extern crate muda as menu;\n menu::PredefinedMenuItem::quit(None)\n );\n}\n", + "macro_rules! m {\n () => [\n extern crate muda as menu;\n menu::PredefinedMenuItem::quit(None)\n ];\n}\n", + "macro_rules! m (\n () => {\n extern crate muda as menu;\n menu::PredefinedMenuItem::quit(None)\n };\n);\n", + ] { + assert!(predefined_quit([("src/child.rs", body)]).is_empty(), "{body}"); + } + // Nor is an attribute's input, in a crate root or a module. + for attr in ["#[attr(extern crate muda as menu;)]\nfn h() {}\n", "#![attr(extern crate muda as menu;)]\n"] { + let lib = format!("{attr}mod child;\n"); + assert!(predefined_quit([("src/lib.rs", lib.as_str()), ("src/child.rs", child)]).is_empty(), "{attr}"); + let module = format!("{attr}fn g() {{ menu::PredefinedMenuItem::quit(None); }}\n"); + assert!(predefined_quit([("src/child.rs", module.as_str())]).is_empty(), "{attr}"); + } } #[test] From c6b28caf8e749a1795c378889367aee925034409 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 00:01:22 -0800 Subject: [PATCH 30/33] craft-testkit: skip mod declarations in macro input and nested src roots loaded as modules predefined_quit no longer follows a `mod` declaration in a macro's input, an attribute or a `macro_rules!` body when it carries a crate root's extern prelude names to other files. A `src/lib.rs` or `src/main.rs` below a package's `src` folder that a declaration loads is read as a module, not as a crate root of its own. --- crates/testkit/src/guards.rs | 45 +++++++++++++++++++++++++--------- crates/testkit/tests/guards.rs | 14 +++++++++++ 2 files changed, 47 insertions(+), 12 deletions(-) diff --git a/crates/testkit/src/guards.rs b/crates/testkit/src/guards.rs index c6058ab62e..282121beb8 100644 --- a/crates/testkit/src/guards.rs +++ b/crates/testkit/src/guards.rs @@ -1461,14 +1461,12 @@ fn report(findings: &mut Vec, path: &str, content: &str, lines: &BTreeS /// name to the muda crate, and whether one binds it to something else. type CrateBindings<'a> = BTreeMap<(&'a str, Option), (bool, bool)>; -/// Each `extern crate c;` or `extern crate c as n;` in a file: whether `c` is muda, the name it binds, and -/// the index of that name. A declaration in an item that `never` marks (see [`Cover::Never`]) is left out, -/// and so are the tokens of a macro's input in parentheses or brackets, `m!(...)` or `m![...]`, of an -/// attribute, `#[...]` or `#![...]`, and the whole body of a `macro_rules!` definition, whose templates are -/// not expanded where they are written. A -/// declaration in a block inside other parentheses or brackets, such as a call's argument, is kept. -fn extern_crates<'a>(toks: &'a [Token], never: &[bool]) -> Vec<(bool, &'a str, usize)> { - let mut externs = Vec::new(); +/// For each token, whether it is in a macro's input in parentheses or brackets, `m!(...)` or `m![...]`, in an +/// attribute, `#[...]` or `#![...]`, or in the body of a `macro_rules!` definition, whose templates are not +/// expanded where they are written. Tokens in a block inside other parentheses or brackets, such as a call's +/// argument, are not marked. +fn macro_tokens(toks: &[Token]) -> Vec { + let mut marked = Vec::with_capacity(toks.len()); // For each open delimiter, whether it starts a macro's input, an attribute or a `macro_rules!` body; and // how many of those are open. let mut open = Vec::new(); @@ -1486,7 +1484,19 @@ fn extern_crates<'a>(toks: &'a [Token], never: &[bool]) -> Vec<(bool, &'a str, u } else if (toks[i].is_punct(')') || toks[i].is_punct(']') || toks[i].is_punct('}')) && open.pop() == Some(true) { in_macro = in_macro.saturating_sub(1); } - if in_macro == 0 + marked.push(in_macro > 0); + } + marked +} + +/// Each `extern crate c;` or `extern crate c as n;` in a file: whether `c` is muda, the name it binds, and +/// the index of that name. A declaration in an item that `never` marks (see [`Cover::Never`]) is left out, +/// and so is one in a macro's input, an attribute or a `macro_rules!` body (see [`macro_tokens`]). +fn extern_crates<'a>(toks: &'a [Token], never: &[bool]) -> Vec<(bool, &'a str, usize)> { + let mut externs = Vec::new(); + let in_macro = macro_tokens(toks); + for i in 0..toks.len() { + if !in_macro[i] && !never.get(i).copied().unwrap_or(false) && toks[i].is_ident("extern") && toks.get(i + 1).is_some_and(|t| t.is_ident("crate")) @@ -1506,7 +1516,8 @@ fn extern_crates<'a>(toks: &'a [Token], never: &[bool]) -> Vec<(bool, &'a str, u /// For each of `paths`, the names that an `extern crate muda as m;` outside any braces of its crate root adds /// to the crate's extern prelude, so that a path starting with `::m` names muda anywhere in the crate. /// -/// The crate roots follow Cargo's layout: `src/lib.rs` and `src/main.rs`; each file that [`cargo_target`] +/// The crate roots follow Cargo's layout: `src/lib.rs` and `src/main.rs`, except one below another package's +/// `src` folder that a declaration names; each file that [`cargo_target`] /// accepts; another `build.rs`, `lib.rs` or `main.rs` when no `mod` declaration in another of the files names /// it, plainly or through a `#[path]` attribute; and each other file directly in a `bin`, `examples`, `tests` /// or `benches` folder other than `mod.rs` when no package folder holds it and no declaration without a @@ -1526,7 +1537,9 @@ fn extern_prelude_names(paths: &[String], contents: &[&str]) -> Vec = macro_tokens(&toks).into_iter().zip(&never).map(|(in_macro, &never)| in_macro || never).collect(); + decls.push(module_decls(&toks, &skip).into_iter().filter(|decl| !decl.native).collect()); let (around, _) = brace_scopes(&toks); aliases.push( extern_crates(&toks, &never) @@ -1560,13 +1573,21 @@ fn extern_prelude_names(paths: &[String], contents: &[&str]) -> Vec true, + // A `src/lib.rs` that a declaration in a package's `src` folder loads is a module there. + (Some("lib.rs" | "main.rs"), Some("src")) => !(named[file] && in_package_src(&paths[file])), (Some("lib.rs" | "main.rs" | "build.rs"), _) => !named[file], // In a known package, `cargo_target` has already placed the target folders. (Some(name), Some("bin" | "examples" | "tests" | "benches")) => { diff --git a/crates/testkit/tests/guards.rs b/crates/testkit/tests/guards.rs index 9b94d78078..17c237458a 100644 --- a/crates/testkit/tests/guards.rs +++ b/crates/testkit/tests/guards.rs @@ -716,6 +716,20 @@ fn predefined_quit_reads_target_folders_below_the_package_folder_only() { let lib = "extern crate other_menu as menu;\n#[path = \"foo/tests/helper.rs\"]\nmod helper;\n"; let found = predefined_quit([("src/lib.rs", lib), ("src/foo/tests/helper.rs", local)]); assert!(found.is_empty(), "{found:?}"); + // So is a `src/lib.rs` below the package's `src` folder that a `#[path]` attribute loads. + let lib = "extern crate other_menu as menu;\n#[path = \"nested/src/lib.rs\"]\nmod nested;\n"; + let found = predefined_quit([("src/lib.rs", lib), ("src/nested/src/lib.rs", local)]); + assert!(found.is_empty(), "{found:?}"); +} + +#[test] +fn predefined_quit_does_not_follow_a_mod_declaration_in_a_macro_input() { + let call = "fn f() { ::menu::PredefinedMenuItem::quit(None); }\n"; + for lib in ["extern crate muda as menu;\nignore!(mod child;);\n", "extern crate muda as menu;\n#[attr(mod child;)]\nfn h() {}\n"] { + assert!(predefined_quit([("src/lib.rs", lib), ("src/child.rs", call)]).is_empty(), "{lib}"); + } + let lib = "extern crate muda as menu;\nmod child;\n"; + assert_eq!(lines(&predefined_quit([("src/lib.rs", lib), ("src/child.rs", call)])), vec![1]); } #[test] From c48164d045b9b8798889974a6c682d0cdcbf4ed2 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 00:04:42 -0800 Subject: [PATCH 31/33] craft-testkit: skip brace-delimited macro input in predefined_quit A macro's input in braces, `m! { ... }`, is skipped like one in parentheses or brackets, so a `mod` or `extern crate` written there no longer carries a crate root's extern prelude names to other files. --- crates/testkit/src/guards.rs | 6 +++--- crates/testkit/tests/guards.rs | 8 ++++++-- 2 files changed, 9 insertions(+), 5 deletions(-) diff --git a/crates/testkit/src/guards.rs b/crates/testkit/src/guards.rs index 282121beb8..95ec54ed75 100644 --- a/crates/testkit/src/guards.rs +++ b/crates/testkit/src/guards.rs @@ -1461,7 +1461,7 @@ fn report(findings: &mut Vec, path: &str, content: &str, lines: &BTreeS /// name to the muda crate, and whether one binds it to something else. type CrateBindings<'a> = BTreeMap<(&'a str, Option), (bool, bool)>; -/// For each token, whether it is in a macro's input in parentheses or brackets, `m!(...)` or `m![...]`, in an +/// For each token, whether it is in a macro's input, `m!(...)`, `m![...]` or `m! { ... }`, in an /// attribute, `#[...]` or `#![...]`, or in the body of a `macro_rules!` definition, whose templates are not /// expanded where they are written. Tokens in a block inside other parentheses or brackets, such as a call's /// argument, are not marked. @@ -1475,7 +1475,7 @@ fn macro_tokens(toks: &[Token]) -> Vec { if toks[i].is_punct('(') || toks[i].is_punct('[') || toks[i].is_punct('{') { let ident = |k: usize| matches!(toks[k].kind, Kind::Ident(_)); let definition = i >= 3 && ident(i - 1) && toks[i - 2].is_punct('!') && toks[i - 3].is_ident("macro_rules"); - let input = !toks[i].is_punct('{') && i >= 2 && toks[i - 1].is_punct('!') && ident(i - 2); + let input = i >= 2 && toks[i - 1].is_punct('!') && ident(i - 2); let attribute = toks[i].is_punct('[') && i >= 1 && (toks[i - 1].is_punct('#') || (i >= 2 && toks[i - 1].is_punct('!') && toks[i - 2].is_punct('#'))); let skip = input || definition || attribute; @@ -1790,7 +1790,7 @@ fn muda_crate_bindings<'a>( /// declarations from it names, `menu` is read like `muda` and `::menu::PredefinedMenuItem::quit` is /// reported. An `extern crate` or `mod` declaration in an item whose `cfg` is false on every configuration /// (`cfg(any())`, `cfg(false)`) is read as absent, and so are the tokens of an `extern crate` in a macro's -/// input in parentheses or brackets (`m!(...)`, `m![...]`), in an attribute or in a `macro_rules!` body. Elsewhere a path that starts with `::` names the crate +/// input (`m!(...)`, `m![...]`, `m! { ... }`), in an attribute or in a `macro_rules!` body. Elsewhere a path that starts with `::` names the crate /// only through `muda`. It also /// follows a `use` or a `type` alias that renames muda's type (`use muda::PredefinedMenuItem as Item;` then /// `Item::quit`); a rename of another crate's `PredefinedMenuItem` is not followed, including one through a diff --git a/crates/testkit/tests/guards.rs b/crates/testkit/tests/guards.rs index 17c237458a..03620ab8a4 100644 --- a/crates/testkit/tests/guards.rs +++ b/crates/testkit/tests/guards.rs @@ -667,7 +667,7 @@ fn predefined_quit_skips_root_aliases_that_are_never_compiled_or_in_macro_input( let lib = "#[cfg(target_os = \"macos\")]\nextern crate muda as menu;\nmod child;\n"; assert_eq!(paths(&predefined_quit([("src/lib.rs", lib), ("src/child.rs", call)])), vec![("src/child.rs".to_owned(), 1)]); // Neither does an `extern crate` in a macro's input, while a real one beside it does. - for input in ["ignore!(extern crate muda as menu;);", "ignore![extern crate muda as menu;];"] { + for input in ["ignore!(extern crate muda as menu;);", "ignore![extern crate muda as menu;];", "ignore! { extern crate muda as menu; }"] { let lib = format!("{input}\nmod child;\n"); assert!(predefined_quit([("src/lib.rs", lib.as_str()), ("src/child.rs", call)]).is_empty(), "{input}"); let lib = format!("{input}\nextern crate muda as native;\nmod child;\n"); @@ -725,7 +725,11 @@ fn predefined_quit_reads_target_folders_below_the_package_folder_only() { #[test] fn predefined_quit_does_not_follow_a_mod_declaration_in_a_macro_input() { let call = "fn f() { ::menu::PredefinedMenuItem::quit(None); }\n"; - for lib in ["extern crate muda as menu;\nignore!(mod child;);\n", "extern crate muda as menu;\n#[attr(mod child;)]\nfn h() {}\n"] { + for lib in [ + "extern crate muda as menu;\nignore!(mod child;);\n", + "extern crate muda as menu;\nignore! {\n mod child;\n}\n", + "extern crate muda as menu;\n#[attr(mod child;)]\nfn h() {}\n", + ] { assert!(predefined_quit([("src/lib.rs", lib), ("src/child.rs", call)]).is_empty(), "{lib}"); } let lib = "extern crate muda as menu;\nmod child;\n"; From ee040418496f2cf2b27e45986abb1bb86d4a56d4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 16:39:37 -0800 Subject: [PATCH 32/33] Testkit: point the lockfile's rustix entry at 1.1.6 The merge of main took main's rustix 1.1.6 package entry but left craft-testkit's dependency line naming rustix 1.1.5, which no longer exists in Cargo.lock. Every job that builds with --locked then stopped because Cargo had to rewrite the lockfile. --- Cargo.lock | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Cargo.lock b/Cargo.lock index eb993104e3..43d88693d2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4229,7 +4229,7 @@ dependencies = [ name = "craft-testkit" version = "0.1.0" dependencies = [ - "rustix 1.1.5", + "rustix 1.1.6", ] [[package]] From 793744d7ce14d6b6d63bb45ced8985bffc1135e1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 16:53:01 -0800 Subject: [PATCH 33/33] Testkit: a nested library loaded by its own targets stays a crate root A `src/lib.rs` below another package's `src` folder was treated as a module whenever any declaration named it, including one in its own package's binary. Its `extern crate muda as m;` then did not reach its modules, and a `::m::PredefinedMenuItem::quit` call there was missed. Only a declaration outside the package's `build.rs` and its `src`, `tests`, `examples` and `benches` folders now makes it a module. --- crates/testkit/src/guards.rs | 14 ++++++++++++-- crates/testkit/tests/it/guards.rs | 17 +++++++++++++++++ 2 files changed, 29 insertions(+), 2 deletions(-) diff --git a/crates/testkit/src/guards.rs b/crates/testkit/src/guards.rs index 95ec54ed75..cb90fd38ab 100644 --- a/crates/testkit/src/guards.rs +++ b/crates/testkit/src/guards.rs @@ -1517,7 +1517,7 @@ fn extern_crates<'a>(toks: &'a [Token], never: &[bool]) -> Vec<(bool, &'a str, u /// to the crate's extern prelude, so that a path starting with `::m` names muda anywhere in the crate. /// /// The crate roots follow Cargo's layout: `src/lib.rs` and `src/main.rs`, except one below another package's -/// `src` folder that a declaration names; each file that [`cargo_target`] +/// `src` folder that a declaration outside its own package folder names; each file that [`cargo_target`] /// accepts; another `build.rs`, `lib.rs` or `main.rs` when no `mod` declaration in another of the files names /// it, plainly or through a `#[path]` attribute; and each other file directly in a `bin`, `examples`, `tests` /// or `benches` folder other than `mod.rs` when no package folder holds it and no declaration without a @@ -1553,6 +1553,9 @@ fn extern_prelude_names(paths: &[String], contents: &[&str]) -> Vec> = (0..paths.len() * 2) .map(|node| { let (file, path_loaded) = (node / 2, node % 2 == 1); @@ -1564,6 +1567,13 @@ fn extern_prelude_names(paths: &[String], contents: &[&str]) -> Vec Vec !(named[file] && in_package_src(&paths[file])), + (Some("lib.rs" | "main.rs"), Some("src")) => !(named_from_outside[file] && in_package_src(&paths[file])), (Some("lib.rs" | "main.rs" | "build.rs"), _) => !named[file], // In a known package, `cargo_target` has already placed the target folders. (Some(name), Some("bin" | "examples" | "tests" | "benches")) => { diff --git a/crates/testkit/tests/it/guards.rs b/crates/testkit/tests/it/guards.rs index 03620ab8a4..0262d28bb8 100644 --- a/crates/testkit/tests/it/guards.rs +++ b/crates/testkit/tests/it/guards.rs @@ -720,6 +720,23 @@ fn predefined_quit_reads_target_folders_below_the_package_folder_only() { let lib = "extern crate other_menu as menu;\n#[path = \"nested/src/lib.rs\"]\nmod nested;\n"; let found = predefined_quit([("src/lib.rs", lib), ("src/nested/src/lib.rs", local)]); assert!(found.is_empty(), "{found:?}"); + // A nested package's library that only its own binary loads stays a crate root, so its alias reaches its modules. + let nested = "extern crate muda as menu;\nmod child;\n"; + let found = predefined_quit([ + ("src/lib.rs", ""), + ("src/nested/src/lib.rs", nested), + ("src/nested/src/child.rs", "fn f() { ::menu::PredefinedMenuItem::quit(None); }\n"), + ("src/nested/src/bin/tool.rs", "#[path = \"../lib.rs\"]\nmod lib;\n"), + ]); + assert_eq!(found.iter().map(|f| (f.path.as_str(), f.line)).collect::>(), vec![("src/nested/src/child.rs", 1)]); + // One that a module beside its `src` folder loads is a module of the outer crate. + let found = predefined_quit([ + ("src/lib.rs", "mod nested;\n"), + ("src/nested/mod.rs", "#[path = \"src/lib.rs\"]\nmod inner;\n"), + ("src/nested/src/lib.rs", nested), + ("src/nested/src/child.rs", "fn f() { ::menu::PredefinedMenuItem::quit(None); }\n"), + ]); + assert!(found.is_empty(), "{found:?}"); } #[test]