From fc4fce56a040d46fd163f35457b5e25ccecc08ae Mon Sep 17 00:00:00 2001 From: aiongg Date: Thu, 19 Nov 2026 06:43:32 +0000 Subject: [PATCH] design-lint: contract/no-global-state (#2336) --- crates/design-lint/README.md | 1 + .../design-lint/src/contract/global_state.rs | 134 ++++++++++++++++++ crates/design-lint/src/contract/mod.rs | 7 +- crates/design-lint/src/workspace.rs | 65 +++++++++ crates/design-lint/tests/contract_rules.rs | 18 ++- .../contract-rules/accept/global-state.rs | 17 +++ .../reject/contract-global-state.rs | 20 +++ .../reject/contract-unsafe-allow.rs | 4 +- 8 files changed, 260 insertions(+), 6 deletions(-) create mode 100644 crates/design-lint/src/contract/global_state.rs create mode 100644 crates/design-lint/tests/fixtures/contract-rules/accept/global-state.rs create mode 100644 crates/design-lint/tests/fixtures/contract-rules/reject/contract-global-state.rs diff --git a/crates/design-lint/README.md b/crates/design-lint/README.md index 8dc858f0f..eff1954ab 100644 --- a/crates/design-lint/README.md +++ b/crates/design-lint/README.md @@ -75,6 +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` (only the derive implements it). 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` | 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 new file mode 100644 index 000000000..b85e663f2 --- /dev/null +++ b/crates/design-lint/src/contract/global_state.rs @@ -0,0 +1,134 @@ +//! `contract/no-global-state`: no process-level state in UI crates. A memoized view's inputs are its props and the +//! environment keys the framework tracks; a `static`, a `thread_local!`, a filesystem read or a hand-written `MemoProps` +//! impl is an input the framework cannot see. +//! +//! Clocks are covered by `contract/motion:clock`, and `unsafe_code` by the workspace `forbid` plus `contract/unsafe-allow`. +//! Build scripts and binaries (`build.rs`, `src/bin/`) are not views and are skipped. + +use syn::visit::{self, Visit}; +use syn::{Attribute, ItemImpl, ItemMacro, ItemMod, ItemStatic, ItemUse, Path as SynPath, UseTree}; + +use crate::report::Finding; + +use super::Cx; + +pub const ID: &str = "contract/no-global-state"; + +const PATH_FS: [&str; 2] = ["std", "fs"]; + +struct Hits { + found: Vec<(proc_macro2::Span, String)>, +} + +fn is_cfg_test(attrs: &[Attribute]) -> bool { + attrs.iter().any(|a| { + a.path().is_ident("cfg") + && matches!(&a.meta, syn::Meta::List(list) if list.tokens.clone().into_iter().any(|t| matches!(t, proc_macro2::TokenTree::Ident(i) if i == "test"))) + }) +} + +fn names_fs(segments: &[String]) -> bool { + segments.windows(2).any(|w| w[0] == PATH_FS[0] && w[1] == PATH_FS[1]) +} + +fn use_paths(tree: &UseTree, prefix: &mut Vec, out: &mut Vec<(proc_macro2::Span, Vec)>) { + match tree { + UseTree::Path(p) => { + prefix.push(p.ident.to_string()); + use_paths(&p.tree, prefix, out); + prefix.pop(); + } + UseTree::Name(n) => { + let mut full = prefix.clone(); + full.push(n.ident.to_string()); + out.push((n.ident.span(), full)); + } + UseTree::Rename(n) => { + let mut full = prefix.clone(); + full.push(n.ident.to_string()); + out.push((n.ident.span(), full)); + } + UseTree::Glob(g) => out.push((g.star_token.span, prefix.clone())), + UseTree::Group(g) => g.items.iter().for_each(|t| use_paths(t, prefix, out)), + } +} + +impl Visit<'_> for Hits { + fn visit_item_mod(&mut self, node: &ItemMod) { + if !is_cfg_test(&node.attrs) { + visit::visit_item_mod(self, node); + } + } + + fn visit_item_static(&mut self, node: &ItemStatic) { + let what = if matches!(node.mutability, syn::StaticMutability::Mut(_)) { "static mut" } else { "static" }; + 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), + )); + visit::visit_item_static(self, node); + } + + fn visit_item_macro(&mut self, node: &ItemMacro) { + self.macro_path(&node.mac.path); + visit::visit_item_macro(self, node); + } + + fn visit_stmt_macro(&mut self, node: &syn::StmtMacro) { + self.macro_path(&node.mac.path); + visit::visit_stmt_macro(self, node); + } + + fn visit_item_use(&mut self, node: &ItemUse) { + let mut paths = Vec::new(); + 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())); + } + } + visit::visit_item_use(self, node); + } + + 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(), + )); + } + visit::visit_path(self, node); + } + + fn visit_item_impl(&mut self, node: &ItemImpl) { + if let Some((_, path, _)) = &node.trait_ + && path.segments.last().is_some_and(|s| s.ident == "MemoProps") + { + self.found.push((node.impl_token.span, "`MemoProps` is implemented by the derive only".to_owned())); + } + visit::visit_item_impl(self, node); + } +} + +impl Hits { + fn macro_path(&mut self, path: &SynPath) { + if let Some(last) = 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))); + } + } +} + +pub(super) fn check(cx: &Cx<'_>, out: &mut Vec) { + let normal = cx.path.to_string_lossy().replace('\\', "/"); + if normal.ends_with("/build.rs") || normal == "build.rs" || normal.contains("/src/bin/") { + return; + } + let mut hits = Hits { found: Vec::new() }; + hits.visit_file(cx.file); + for (span, message) in hits.found { + cx.flag_span(out, ID, ID, span, message); + } +} diff --git a/crates/design-lint/src/contract/mod.rs b/crates/design-lint/src/contract/mod.rs index 4ae66e4db..4aa6a400b 100644 --- a/crates/design-lint/src/contract/mod.rs +++ b/crates/design-lint/src/contract/mod.rs @@ -10,6 +10,7 @@ mod egui_import; mod egui_widget; mod entry; mod facts; +mod global_state; mod keys; mod layers; mod memory; @@ -39,7 +40,7 @@ use crate::report::Finding; use sites::Site; /// Every rule id of this module, for the marker and exemption validation in [`crate::RULES`]. -pub(crate) const IDS: [&str; 39] = [ +pub(crate) const IDS: [&str; 40] = [ egui_import::ID, runtime_egui::ID, text_edit::ID, @@ -79,12 +80,13 @@ pub(crate) const IDS: [&str; 39] = [ shape::OVERLAY_FLAG, shape::REGISTRATION, unsafe_allow::ID, + global_state::ID, ]; type Check = fn(&Cx<'_>, &mut Vec); /// REGISTRY: add a rule by adding its `check` here and its ids to [`IDS`]. -const REGISTRY: [Check; 21] = [ +const REGISTRY: [Check; 22] = [ egui_import::check, runtime_egui::check, text_edit::check, @@ -106,6 +108,7 @@ const REGISTRY: [Check; 21] = [ entry::check, shape::check, unsafe_allow::check, + global_state::check, ]; /// One file as the rules see it. diff --git a/crates/design-lint/src/workspace.rs b/crates/design-lint/src/workspace.rs index eded9fe6a..fb81d44a3 100644 --- a/crates/design-lint/src/workspace.rs +++ b/crates/design-lint/src/workspace.rs @@ -120,6 +120,68 @@ 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] = &[ + // Framework runtime: the state the memoized views read through environment keys. + "crates/ui-contract/src/runtime", + // Compile-time code, not a view: the proc macro reads the compiling crate's Cargo.toml. + "crates/ui-macros/src/component.rs", + // 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", + // 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", + // Environment fact: the icon-set registry, filled at app start before the first pass. + "crates/ui-contract/src/primitives/svg_set.rs", + // Settled fact: the thumbnail texture cache, keyed by its content. + "crates/ui-contract/src/primitives/textures/thumbnails.rs", + // Settled fact: the log-once set of unknown token names; it has no effect on output. + "crates/ui-contract/src/style/tokens.rs", + // Settled fact: the viewer's component catalog, computed once from compile-time input and immutable after init. + "crates/ui-gallery/src/viewer/catalog.rs", + // Settled fact: reads a file the user dropped, in the drop handler and not during the pass. + "crates/ui-gallery/src/chrome/shell.rs", + // Settled fact: the fallback text format, computed once from constants and immutable after init. + "crates/ui-canvas/src/canvas/tool.rs", + // Settled fact: the identity curve, computed once from constants and immutable after init. + "crates/imaging/src/ui/curve/preview.rs", + // Settled fact: the default layer-style draft and its preview paint, computed once from constants. + "crates/imaging/src/ui/layer_style/hosted.rs", + // Settled fact: a test fake of the font store; it writes a temporary folder. + "crates/font-manager/src/store/fake.rs", + // later task of #2336: the dock node id counter is hidden state. + "crates/behavior/src/dock/node.rs", + // later task of #2336: the brush trail id counter is hidden state. + "crates/ui-canvas/src/canvas_controls/brush/trail.rs", + // later task of #2336: the outline hover generation counter is hidden state. + "crates/ui-canvas/src/canvas_controls/outline/hover.rs", + // later task of #2336: the texture serial counter is hidden state. + "crates/imaging/src/ui/transform_preview/textures.rs", + // later task of #2336: the mock image read cache is hidden state. + "crates/imaging/src/ui/mock_image.rs", + // later task of #2336: the ranking cache is hidden state. + "crates/font-manager/src/picker/rank.rs", + // later task of #2336: the face loader reads file sizes during the pass. + "crates/font-manager/src/panel/faces.rs", + // later task of #2336: the gallery's set of seen names is hidden state. + "crates/ui-gallery/src/viewer/layout.rs", + // 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", +]; + +/// 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") + || file.components().any(|c| c.as_os_str() == "stories") + || file.file_stem().is_some_and(|stem| stem == "stories") +} + struct CrateInfo { name: String, dir: PathBuf, @@ -287,6 +349,9 @@ 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 key == "test/layout" { return file.starts_with(krate.dir.join("tests").join("it")); } diff --git a/crates/design-lint/tests/contract_rules.rs b/crates/design-lint/tests/contract_rules.rs index 90ac096ac..19a4c6437 100644 --- a/crates/design-lint/tests/contract_rules.rs +++ b/crates/design-lint/tests/contract_rules.rs @@ -31,7 +31,7 @@ fn rules_at(src: &str, path: &str, scope: &StaticScope) -> Vec<&'static str> { } /// Reject fixtures: file and the rules it must trigger (all of them, nothing else). -const REJECT: [(&str, &[&str]); 19] = [ +const REJECT: [(&str, &[&str]); 20] = [ ("behavior-pipeline-only.rs", &["behavior/pipeline-only"]), ("props-reserved-setter.rs", &["props/reserved-setter"]), ("props-hand-setter.rs", &["props/hand-setter"]), @@ -51,6 +51,7 @@ const REJECT: [(&str, &[&str]); 19] = [ ("contract-overlay-flag.rs", &["contract/overlay-flag"]), ("contract-unsafe-allow.rs", &["contract/unsafe-allow"]), ("contract-registration.rs", &["contract/registration"]), + ("contract-global-state.rs", &["contract/no-global-state"]), ]; #[test] @@ -72,7 +73,7 @@ fn unsafe_allow_is_accepted_only_in_the_ffi_crates() { #[test] fn accept_fixtures_pass() { - for file in ["behavior-pipeline-only.rs", "props.rs", "style.rs", "entry.rs"] { + for file in ["behavior-pipeline-only.rs", "props.rs", "style.rs", "entry.rs", "global-state.rs"] { let findings = analyze_contract(&fixture("accept", file), Path::new(FAMILY), &scope(), false); assert!(findings.is_empty(), "{file}: {findings:?}"); } @@ -94,3 +95,16 @@ fn type_facts_cross_files_of_a_crate() { ] ); } + +#[test] +fn global_state_counts_every_form_and_honours_the_allowlist() { + let src = fixture("reject", "contract-global-state.rs"); + let found = analyze_contract(&src, Path::new(FAMILY), &scope(), false); + // static, static mut, static OnceLock, thread_local!, impl MemoProps, a static in a fn, `use std::fs`, `std::fs::read`. + assert_eq!(found.iter().filter(|f| f.rule == "contract/no-global-state").count(), 8, "{found:?}"); + let allowed = StaticScope::new().allow("contract/no-global-state", "crates/x/src/chips"); + assert!(rules_at(&src, FAMILY, &allowed).is_empty()); + 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/fixtures/contract-rules/accept/global-state.rs b/crates/design-lint/tests/fixtures/contract-rules/accept/global-state.rs new file mode 100644 index 000000000..11d96951c --- /dev/null +++ b/crates/design-lint/tests/fixtures/contract-rules/accept/global-state.rs @@ -0,0 +1,17 @@ +use std::path::Path; + +const COLUMNS: [u32; 2] = [1, 2]; + +#[derive(MemoProps)] +struct Props { + path: String, +} + +fn exists(path: &Path) -> bool { + COLUMNS.len() > 1 && path.is_absolute() +} + +#[cfg(test)] +mod tests { + static SEEN: std::sync::Mutex = std::sync::Mutex::new(0); +} diff --git a/crates/design-lint/tests/fixtures/contract-rules/reject/contract-global-state.rs b/crates/design-lint/tests/fixtures/contract-rules/reject/contract-global-state.rs new file mode 100644 index 000000000..0e7401d29 --- /dev/null +++ b/crates/design-lint/tests/fixtures/contract-rules/reject/contract-global-state.rs @@ -0,0 +1,20 @@ +use std::cell::RefCell; +use std::fs; +use std::sync::{Mutex, OnceLock}; + +static COUNTER: Mutex = Mutex::new(0); +static mut RAW: u32 = 0; +static CACHE: OnceLock = OnceLock::new(); + +thread_local! { + static LOCAL: RefCell = const { RefCell::new(0) }; +} + +struct Props; + +impl MemoProps for Props {} + +fn read(path: &str) -> Vec { + static INNER: Mutex = Mutex::new(0); + std::fs::read(path).unwrap_or_default() +} diff --git a/crates/design-lint/tests/fixtures/contract-rules/reject/contract-unsafe-allow.rs b/crates/design-lint/tests/fixtures/contract-rules/reject/contract-unsafe-allow.rs index 2b90f29a8..b811d6dc8 100644 --- a/crates/design-lint/tests/fixtures/contract-rules/reject/contract-unsafe-allow.rs +++ b/crates/design-lint/tests/fixtures/contract-rules/reject/contract-unsafe-allow.rs @@ -1,7 +1,7 @@ #![allow(unsafe_code)] #[allow(unsafe_code)] -static REGISTRATION: u8 = 0; +const REGISTRATION: u8 = 0; #[expect(unsafe_code, reason = "link section")] -static OTHER: u8 = 0; +const OTHER: u8 = 0;