From 6d1d6bb6d14d60109451125dda64c8f3d61e693d Mon Sep 17 00:00:00 2001 From: aiongg Date: Thu, 19 Nov 2026 06:53:55 +0000 Subject: [PATCH] design-lint: per-item no-global-state allowlist; motion:clock flags clock fn values (#2336) --- crates/design-lint/README.md | 2 +- .../design-lint/src/contract/global_state.rs | 55 ++++++--- crates/design-lint/src/contract/mod.rs | 1 + crates/design-lint/src/contract/motion.rs | 10 +- crates/design-lint/src/workspace.rs | 110 ++++++++++++------ crates/design-lint/tests/contract_rules.rs | 12 +- crates/design-lint/tests/egui_rules.rs | 3 +- .../reject/contract-motion-clock-fn.rs | 3 + 8 files changed, 141 insertions(+), 55 deletions(-) create mode 100644 crates/design-lint/tests/fixtures/egui-rules/reject/contract-motion-clock-fn.rs diff --git a/crates/design-lint/README.md b/crates/design-lint/README.md index 5c69c2bff..c3a66b336 100644 --- a/crates/design-lint/README.md +++ b/crates/design-lint/README.md @@ -75,7 +75,7 @@ reason = "document-space drawing" | `contract/entry` | in layers 5 and 6 (not layer 8): an inherent `pub fn show`, `show_at`, `show_in` or `ui` on a `pub` type that the file does not make a `Component` or `Pattern`; a `pub fn` taking `&mut Ui` and returning a `*Response` | | `contract/shadow`, `contract/widget`, `contract/overlay-flag` | an inherent `show`, `show_at`, `show_in`, `show_with_tip` or `show_at_with_tip` on a component; `impl egui::Widget`; an `overlay` override on a type without `#[component(overlay)]`. Derive output is the only allowed place, so no file is | | `contract/registration` | an `impl Component for` or `impl Pattern for` a type defined in the file that neither derives that trait nor appears in a `register_contract!(..)` invocation of the file. | -| `contract/no-global-state` | every `static` (including `static mut` and statics inside functions), `thread_local!` and `lazy_static!`; `std::fs` by path or `use`; `impl MemoProps for` and `impl PlainData for` (only the derives implement them; no allowed location); any source occurrence of `__from_field_path` (only the `field!` expansion calls it; no allowed location). Skipped: `#[cfg(test)]` modules, `build.rs`, `src/bin/`. Allowed in: stories and `ui-contract`'s `testing`, and the reviewed list `NO_GLOBAL_STATE` in `workspace.rs`, each entry with the fact or later task that covers it. Clocks are `contract/motion:clock`; `unsafe_code` is the workspace `forbid` plus `contract/unsafe-allow` | +| `contract/no-global-state` | every `static` (including `static mut` and statics inside functions), `thread_local!` and `lazy_static!`; `std::fs` by path or `use`; `impl MemoProps for` and `impl PlainData for` (only the derives implement them; no allowed location); any source occurrence of `__from_field_path` (only the `field!` expansion calls it; no allowed location). Skipped: `#[cfg(test)]` modules, `build.rs`, `src/bin/`. Allowed in: stories and `ui-contract`'s `testing`, and the reviewed per-item list `NO_GLOBAL_STATE` in `workspace.rs` (a file and the item's identifier or `std::fs`), each entry with the fact or later task that covers it. Clocks, called or passed as a fn value, are `contract/motion:clock`; `unsafe_code` is the workspace `forbid` plus `contract/unsafe-allow` | Egui paths are resolved through the file's `use` items (one table per file, grouped, renamed and glob imports), so a craft type that shares a name with an egui type is not flagged unless it is imported from egui. diff --git a/crates/design-lint/src/contract/global_state.rs b/crates/design-lint/src/contract/global_state.rs index fccc503b8..f1791c0da 100644 --- a/crates/design-lint/src/contract/global_state.rs +++ b/crates/design-lint/src/contract/global_state.rs @@ -14,6 +14,10 @@ use super::Cx; pub const ID: &str = "contract/no-global-state"; +/// What an allowlist entry names for file-system use. +pub(crate) const FS: &str = "std::fs"; +const FS_MESSAGE: &str = "`std::fs` reads the file system, which the framework does not track; read it outside the view"; + const PATH_FS: [&str; 2] = ["std", "fs"]; /// Permission keys of the two derive-only rules; no location is allowed. @@ -24,11 +28,27 @@ const PROJECTION: &str = "contract/no-global-state:projection"; const FROM_FIELD_PATH: &str = "__from_field_path"; struct Hits { - found: Vec<(proc_macro2::Span, String)>, + found: Vec<(proc_macro2::Span, String, String)>, derive_only: Vec<(proc_macro2::Span, String)>, projection: Vec<(proc_macro2::Span, String)>, } +/// The identifiers after `static` in a `thread_local!` or `lazy_static!` body. +fn static_names(tokens: proc_macro2::TokenStream, out: &mut Vec) { + let mut after_static = false; + for token in tokens { + match token { + proc_macro2::TokenTree::Ident(i) if after_static => { + out.push(i.to_string()); + after_static = false; + } + proc_macro2::TokenTree::Ident(i) => after_static = i == "static", + proc_macro2::TokenTree::Group(g) => static_names(g.stream(), out), + _ => after_static = false, + } + } +} + fn field_path_in(tokens: proc_macro2::TokenStream, out: &mut Vec) { for token in tokens { match token { @@ -84,17 +104,18 @@ impl Visit<'_> for Hits { self.found.push(( node.static_token.span, format!("`{what} {}` is process-level state; use `const`, or pass it as a prop or environment key", node.ident), + node.ident.to_string(), )); visit::visit_item_static(self, node); } fn visit_item_macro(&mut self, node: &ItemMacro) { - self.macro_path(&node.mac.path); + self.macro_path(&node.mac); visit::visit_item_macro(self, node); } fn visit_stmt_macro(&mut self, node: &syn::StmtMacro) { - self.macro_path(&node.mac.path); + self.macro_path(&node.mac); visit::visit_stmt_macro(self, node); } @@ -103,7 +124,7 @@ impl Visit<'_> for Hits { use_paths(&node.tree, &mut Vec::new(), &mut paths); for (span, path) in paths { if names_fs(&path) { - self.found.push((span, "`std::fs` reads the file system, which the framework does not track; read it outside the view".to_owned())); + self.found.push((span, FS_MESSAGE.to_owned(), FS.to_owned())); } } visit::visit_item_use(self, node); @@ -127,10 +148,7 @@ impl Visit<'_> for Hits { fn visit_path(&mut self, node: &SynPath) { let names: Vec = node.segments.iter().map(|s| s.ident.to_string()).collect(); if names_fs(&names) { - self.found.push(( - node.segments[0].ident.span(), - "`std::fs` reads the file system, which the framework does not track; read it outside the view".to_owned(), - )); + self.found.push((node.segments[0].ident.span(), FS_MESSAGE.to_owned(), FS.to_owned())); } visit::visit_path(self, node); } @@ -141,7 +159,7 @@ impl Visit<'_> for Hits { { let message = format!("`{name}` is implemented by the derive only"); if name == "MemoProps" { - self.found.push((node.impl_token.span, message)); + self.found.push((node.impl_token.span, message, name)); } else { self.derive_only.push((node.impl_token.span, message)); } @@ -151,11 +169,20 @@ impl Visit<'_> for Hits { } impl Hits { - fn macro_path(&mut self, path: &SynPath) { - if let Some(last) = path.segments.last() + fn macro_path(&mut self, mac: &syn::Macro) { + if let Some(last) = mac.path.segments.last() && matches!(last.ident.to_string().as_str(), "thread_local" | "lazy_static") { - self.found.push((last.ident.span(), format!("`{}!` declares process-level state; pass it as a prop or environment key", last.ident))); + let mut names = Vec::new(); + static_names(mac.tokens.clone(), &mut names); + let listed = names.join("`, `"); + for name in if names.is_empty() { vec![last.ident.to_string()] } else { names } { + self.found.push(( + last.ident.span(), + format!("`{}!` declares process-level state (`{listed}`); pass it as a prop or environment key", last.ident), + name, + )); + } } } } @@ -167,8 +194,8 @@ pub(super) fn check(cx: &Cx<'_>, out: &mut Vec) { } let mut hits = Hits { found: Vec::new(), derive_only: Vec::new(), projection: Vec::new() }; hits.visit_file(cx.file); - for (span, message) in hits.found { - cx.flag_span(out, ID, ID, span, message); + for (span, message, what) in hits.found { + cx.flag_span(out, ID, &format!("{ID}:{what}"), span, message); } for (span, message) in hits.derive_only { cx.flag_span(out, ID, PLAIN_DATA, span, message); diff --git a/crates/design-lint/src/contract/mod.rs b/crates/design-lint/src/contract/mod.rs index 4aa6a400b..28449dc33 100644 --- a/crates/design-lint/src/contract/mod.rs +++ b/crates/design-lint/src/contract/mod.rs @@ -11,6 +11,7 @@ mod egui_widget; mod entry; mod facts; mod global_state; +pub(crate) use global_state::FS; mod keys; mod layers; mod memory; diff --git a/crates/design-lint/src/contract/motion.rs b/crates/design-lint/src/contract/motion.rs index edc888c82..bbd1af79f 100644 --- a/crates/design-lint/src/contract/motion.rs +++ b/crates/design-lint/src/contract/motion.rs @@ -16,12 +16,18 @@ pub(super) fn check(cx: &Cx<'_>, out: &mut Vec) { name.starts_with("animate_") || matches!(name, "request_repaint_after" | "animation_time" | "prefers_reduced_motion" | "reduced_motion") }); for site in &cx.sites { - if let Kind::Path { path, call: true, .. } = &site.kind + if let Kind::Path { path, in_use: false, .. } = &site.kind && path.len() >= 2 && matches!(path[path.len() - 2].as_str(), "Instant" | "SystemTime") && path[path.len() - 1] == "now" { - cx.flag(out, ID, CLOCK, site, format!("`{}` reads a clock; read the runtime's motion clock", path.join("::"))); + cx.flag( + out, + ID, + CLOCK, + site, + format!("`{}` reads a clock, called or passed as a fn value; read the runtime's motion clock", path.join("::")), + ); } } } diff --git a/crates/design-lint/src/workspace.rs b/crates/design-lint/src/workspace.rs index fb81d44a3..17510ae8e 100644 --- a/crates/design-lint/src/workspace.rs +++ b/crates/design-lint/src/workspace.rs @@ -7,7 +7,7 @@ use std::collections::{BTreeMap, BTreeSet}; use std::path::{Path, PathBuf}; -use crate::contract::RuleScope; +use crate::contract::{FS, RuleScope}; use crate::graph::{Metadata, Package}; use crate::layers::{LayerMaps, relative}; use crate::resolve::Index; @@ -120,66 +120,95 @@ fn places(key: &str) -> Vec { } } -/// The reviewed allowlist of `contract/no-global-state`: path prefixes (relative to the repository root, as in -/// findings), each with the settled fact or environment key that covers it, or the later task of craft-libs#2336 that -/// removes the state. Stories and test helpers are allowed by [`no_global_state_everywhere`]. -const NO_GLOBAL_STATE: &[&str] = &[ +/// Locations of `contract/no-global-state` where everything is allowed, as path prefixes relative to the repository +/// root, as in findings. +const NO_GLOBAL_STATE_PREFIXES: &[&str] = &[ // Framework runtime: the state the memoized views read through environment keys. "crates/ui-contract/src/runtime", + // Test helpers. + "crates/ui-contract/src/testing", // Compile-time code, not a view: the proc macro reads the compiling crate's Cargo.toml. "crates/ui-macros/src/component.rs", +]; + +/// The reviewed per-item allowlist of `contract/no-global-state`: a file and what it may hold, either the identifier of +/// a `static` or `thread_local!` item or [`FS`] for `std::fs`. Each group names the settled fact or environment key that +/// covers it, or the later task of craft-libs#2336 that removes the state. A new item in these files is flagged. +const NO_GLOBAL_STATE: &[(&str, &str)] = &[ // Settled fact: constant font bytes, decompressed once from compile-time input and immutable after init. - "crates/ui-contract/src/fonts/defaults.rs", - // Environment fact (font environment): the font providers, the system UI face and its repaint waiters, and the - // locale lists derived from them. - "crates/ui-contract/src/fonts/system", + ("crates/ui-contract/src/fonts/defaults.rs", "HACK"), + ("crates/ui-contract/src/fonts/defaults.rs", "EGUI_ICONS"), + ("crates/ui-contract/src/fonts/defaults.rs", "UBUNTU_LIGHT"), + ("crates/ui-contract/src/fonts/defaults.rs", "NOTO_EMOJI"), + ("crates/ui-contract/src/fonts/defaults.rs", "EMOJI_ICON_FONT"), + ("crates/ui-contract/src/fonts/defaults.rs", "INTER_REGULAR"), + ("crates/ui-contract/src/fonts/defaults.rs", "INTER_SEMIBOLD"), + // Environment fact (font environment): the system font index and the locale list derived from it, the font + // providers, the system UI face and its repaint waiters. + ("crates/ui-contract/src/fonts/system/fontique.rs", "INDEX"), + ("crates/ui-contract/src/fonts/system/fontique.rs", "HAN_LOCALES"), + ("crates/ui-contract/src/fonts/system/mod.rs", "PROVIDERS"), + ("crates/ui-contract/src/fonts/system/ui_face.rs", "FACE"), + ("crates/ui-contract/src/fonts/system/ui_face.rs", "WAITING"), // Environment fact (font environment): the scan of the font folders and the font files read from them. - "crates/ui-contract/src/fonts/on_demand", - "crates/ui-contract/src/fonts/on_demand.rs", + ("crates/ui-contract/src/fonts/on_demand/files.rs", "FILES"), + ("crates/ui-contract/src/fonts/on_demand/files.rs", "SCAN"), + ("crates/ui-contract/src/fonts/on_demand/files.rs", FS), + ("crates/ui-contract/src/fonts/on_demand.rs", FS), // Environment fact: the icon-set registry, filled at app start before the first pass. - "crates/ui-contract/src/primitives/svg_set.rs", + ("crates/ui-contract/src/primitives/svg_set.rs", "APPS"), // Settled fact: the thumbnail texture cache, keyed by its content. - "crates/ui-contract/src/primitives/textures/thumbnails.rs", + ("crates/ui-contract/src/primitives/textures/thumbnails.rs", "MADE"), // Settled fact: the log-once set of unknown token names; it has no effect on output. - "crates/ui-contract/src/style/tokens.rs", + ("crates/ui-contract/src/style/tokens.rs", "REPORTED"), // Settled fact: the viewer's component catalog, computed once from compile-time input and immutable after init. - "crates/ui-gallery/src/viewer/catalog.rs", + ("crates/ui-gallery/src/viewer/catalog.rs", "CATALOG"), // Settled fact: reads a file the user dropped, in the drop handler and not during the pass. - "crates/ui-gallery/src/chrome/shell.rs", + ("crates/ui-gallery/src/chrome/shell.rs", FS), // Settled fact: the fallback text format, computed once from constants and immutable after init. - "crates/ui-canvas/src/canvas/tool.rs", + ("crates/ui-canvas/src/canvas/tool.rs", "FALLBACK"), // Settled fact: the identity curve, computed once from constants and immutable after init. - "crates/imaging/src/ui/curve/preview.rs", + ("crates/imaging/src/ui/curve/preview.rs", "IDENTITY"), // Settled fact: the default layer-style draft and its preview paint, computed once from constants. - "crates/imaging/src/ui/layer_style/hosted.rs", + ("crates/imaging/src/ui/layer_style/hosted.rs", "DRAFT"), + ("crates/imaging/src/ui/layer_style/hosted.rs", "PAINT"), // Settled fact: a test fake of the font store; it writes a temporary folder. - "crates/font-manager/src/store/fake.rs", + ("crates/font-manager/src/store/fake.rs", FS), // later task of #2336: the dock node id counter is hidden state. - "crates/behavior/src/dock/node.rs", + ("crates/behavior/src/dock/node.rs", "NEXT"), // later task of #2336: the brush trail id counter is hidden state. - "crates/ui-canvas/src/canvas_controls/brush/trail.rs", + ("crates/ui-canvas/src/canvas_controls/brush/trail.rs", "NEXT_ID"), // later task of #2336: the outline hover generation counter is hidden state. - "crates/ui-canvas/src/canvas_controls/outline/hover.rs", + ("crates/ui-canvas/src/canvas_controls/outline/hover.rs", "GENERATIONS"), // later task of #2336: the texture serial counter is hidden state. - "crates/imaging/src/ui/transform_preview/textures.rs", + ("crates/imaging/src/ui/transform_preview/textures.rs", "SERIAL"), // later task of #2336: the mock image read cache is hidden state. - "crates/imaging/src/ui/mock_image.rs", + ("crates/imaging/src/ui/mock_image.rs", "READS"), // later task of #2336: the ranking cache is hidden state. - "crates/font-manager/src/picker/rank.rs", + ("crates/font-manager/src/picker/rank.rs", "CACHE"), // later task of #2336: the face loader reads file sizes during the pass. - "crates/font-manager/src/panel/faces.rs", + ("crates/font-manager/src/panel/faces.rs", FS), // later task of #2336: the gallery's set of seen names is hidden state. - "crates/ui-gallery/src/viewer/layout.rs", + ("crates/ui-gallery/src/viewer/layout.rs", "NAMES"), // later task of #2336: the LUT picker reads the process clock and scans folders during the pass. + ("crates/color-ui/src/ui/lut_picker.rs", "START"), + ("crates/color-ui/src/ui/lut_picker.rs", FS), +]; + +/// Files that may read a clock (`contract/motion:clock`) beyond the runtime's motion module. A file key, because +/// color-ui has no layer map. +const MOTION_CLOCK_FILES: &[&str] = &[ + // later task of #2336: the LUT picker reads the process clock during the pass. "crates/color-ui/src/ui/lut_picker.rs", ]; -/// Stories hold constant demo data and pure caches of it (the owner's rule allows caches of pure test data), and -/// `ui-contract`'s `testing` modules are test helpers. -fn no_global_state_everywhere(file: &Path) -> bool { - file.starts_with("crates/ui-contract/src/testing") +/// Whether `what` (an item identifier or [`FS`]) may be declared or used in `file` for `contract/no-global-state`. +/// Stories hold constant demo data and pure caches of it (the owner's rule allows caches of pure test data). +fn no_global_state_allows(what: &str, file: &Path) -> bool { + NO_GLOBAL_STATE_PREFIXES.iter().any(|prefix| file.starts_with(prefix)) || file.components().any(|c| c.as_os_str() == "stories") || file.file_stem().is_some_and(|stem| stem == "stories") + || NO_GLOBAL_STATE.iter().any(|(path, item)| *item == what && file == Path::new(path)) } struct CrateInfo { @@ -349,8 +378,11 @@ fn has_prefix(path: &[String], prefix: &[&str]) -> bool { impl RuleScope for WorkspaceScope { fn allows(&self, key: &str, file: &Path) -> bool { let Some(krate) = self.crate_of(file) else { return false }; - if key == "contract/no-global-state" { - return no_global_state_everywhere(file) || NO_GLOBAL_STATE.iter().any(|prefix| file.starts_with(prefix)); + if let Some(what) = key.strip_prefix("contract/no-global-state:") { + return no_global_state_allows(what, file); + } + if key == "contract/motion:clock" && MOTION_CLOCK_FILES.iter().any(|f| file == Path::new(f)) { + return true; } if key == "test/layout" { return file.starts_with(krate.dir.join("tests").join("it")); @@ -401,6 +433,16 @@ pub fn check_workspace(root: &Path, config: &Config, meta: &Metadata) -> Result< mod tests { use super::*; + #[test] + fn no_global_state_allowlist_is_per_item() { + let file = Path::new("crates/imaging/src/ui/curve/preview.rs"); + assert!(no_global_state_allows("IDENTITY", file)); + assert!(!no_global_state_allows("SECOND", file), "a new static in an allowlisted file is flagged"); + assert!(!no_global_state_allows(FS, file)); + assert!(no_global_state_allows("ANYTHING", Path::new("crates/ui-contract/src/runtime/focus.rs"))); + assert!(no_global_state_allows("ANYTHING", Path::new("crates/x/src/ui/stories.rs"))); + } + fn package(name: &str, features: &str, dependencies: &[&str]) -> String { format!(r#"{{"name":"{name}","features":{{{features}}},"dependencies":[{}],"targets":[]}}"#, dependencies.join(",")) } diff --git a/crates/design-lint/tests/contract_rules.rs b/crates/design-lint/tests/contract_rules.rs index 3070bffae..bd10dae4d 100644 --- a/crates/design-lint/tests/contract_rules.rs +++ b/crates/design-lint/tests/contract_rules.rs @@ -103,10 +103,16 @@ fn global_state_counts_every_form_and_honours_the_allowlist() { // static, static mut, static OnceLock, thread_local!, impl MemoProps, a static in a fn, `use std::fs`, `std::fs::read`, // and the two derive-only forms: impl PlainData and a direct `__from_field_path`. assert_eq!(found.iter().filter(|f| f.rule == "contract/no-global-state").count(), 10, "{found:?}"); - let allowed = StaticScope::new().allow("contract/no-global-state", "crates/x/src/chips"); - // The derive-only forms have no allowed location, whatever the scope says. + // An entry names one item; the rest of the file is still flagged. The three derive-only forms have no entry. + let mut allowed = StaticScope::new(); + for what in ["COUNTER", "RAW", "CACHE", "LOCAL", "INNER", "std::fs"] { + allowed = allowed.allow(&format!("contract/no-global-state:{what}"), "crates/x/src/chips"); + } let left = analyze_contract(&src, Path::new(FAMILY), &allowed, false); - assert_eq!(left.len(), 2, "{left:?}"); + assert_eq!(left.len(), 3, "{left:?}"); + let some = StaticScope::new().allow("contract/no-global-state:COUNTER", "crates/x/src/chips"); + let left = analyze_contract(&src, Path::new(FAMILY), &some, false); + assert_eq!(left.len(), 9, "a second static in an allowlisted file is flagged: {left:?}"); for skipped in ["crates/x/build.rs", "crates/x/src/bin/tool.rs"] { assert!(rules_at(&src, skipped, &scope()).is_empty(), "{skipped}"); } diff --git a/crates/design-lint/tests/egui_rules.rs b/crates/design-lint/tests/egui_rules.rs index 56b29f7e5..e6f39e183 100644 --- a/crates/design-lint/tests/egui_rules.rs +++ b/crates/design-lint/tests/egui_rules.rs @@ -35,7 +35,7 @@ fn rules_at(src: &str, path: &str, scope: &StaticScope) -> Vec<&'static str> { } /// Reject fixtures: file, the rule it must trigger, the path it is checked at. -const REJECT: [(&str, &str, &str); 21] = [ +const REJECT: [(&str, &str, &str); 22] = [ ("contract-egui-import.rs", "contract/egui-import", "src/ui/a.rs"), ("contract-allocate.rs", "contract/allocate", "src/ui/a.rs"), ("contract-egui-widget.rs", "contract/egui-widget", "src/ui/a.rs"), @@ -47,6 +47,7 @@ const REJECT: [(&str, &str, &str); 21] = [ ("contract-pointer.rs", "contract/pointer", "src/ui/a.rs"), ("contract-motion.rs", "contract/motion", "src/ui/a.rs"), ("contract-motion-clock.rs", "contract/motion", "src/ui/a.rs"), + ("contract-motion-clock-fn.rs", "contract/motion", "src/ui/a.rs"), ("contract-containers.rs", "contract/containers", "src/ui/a.rs"), ("contract-containers-scroll.rs", "contract/containers", "src/ui/a.rs"), ("contract-platform.rs", "contract/platform", "src/ui/a.rs"), diff --git a/crates/design-lint/tests/fixtures/egui-rules/reject/contract-motion-clock-fn.rs b/crates/design-lint/tests/fixtures/egui-rules/reject/contract-motion-clock-fn.rs new file mode 100644 index 000000000..1b303589e --- /dev/null +++ b/crates/design-lint/tests/fixtures/egui-rules/reject/contract-motion-clock-fn.rs @@ -0,0 +1,3 @@ +fn f(cell: &std::sync::OnceLock) -> std::time::Instant { + *cell.get_or_init(std::time::Instant::now) +}