diff --git a/crates/browse/src/ui/relink/badge.rs b/crates/browse/src/ui/relink/badge.rs index 8451a06ea..b1981a39d 100644 --- a/crates/browse/src/ui/relink/badge.rs +++ b/crates/browse/src/ui/relink/badge.rs @@ -34,10 +34,10 @@ enum StatusGlyph { Modified, } -static MISSING: StatusGlyph = StatusGlyph::Missing; -static UNREADABLE: StatusGlyph = StatusGlyph::Unreadable; -static REFUSED: StatusGlyph = StatusGlyph::Refused; -static MODIFIED: StatusGlyph = StatusGlyph::Modified; +const MISSING: StatusGlyph = StatusGlyph::Missing; +const UNREADABLE: StatusGlyph = StatusGlyph::Unreadable; +const REFUSED: StatusGlyph = StatusGlyph::Refused; +const MODIFIED: StatusGlyph = StatusGlyph::Modified; impl Glyph for StatusGlyph { fn paint(&self, painter: &Painter, tokens: &UiTokens, rect: Rect, _: Color32, _: bool) { diff --git a/crates/color-ui/src/ui/info.rs b/crates/color-ui/src/ui/info.rs index 46238e585..1c7d6ef4e 100644 --- a/crates/color-ui/src/ui/info.rs +++ b/crates/color-ui/src/ui/info.rs @@ -21,7 +21,7 @@ const DASH: &str = "–"; /// The grid's columns: a name and its value, twice, so that the two readouts of a line stand side by side and each /// column lines up down the grid. -static COLUMNS: [ColumnWidth; 4] = [ColumnWidth::Content, ColumnWidth::Content, ColumnWidth::Content, ColumnWidth::Content]; +const COLUMNS: [ColumnWidth; 4] = [ColumnWidth::Content, ColumnWidth::Content, ColumnWidth::Content, ColumnWidth::Content]; craft_ui::words! { /// The words of the Info panel, in the installed language unless set. diff --git a/crates/color-ui/src/ui/picker/stories.rs b/crates/color-ui/src/ui/picker/stories.rs index ca0df2461..a3302806a 100644 --- a/crates/color-ui/src/ui/picker/stories.rs +++ b/crates/color-ui/src/ui/picker/stories.rs @@ -52,7 +52,7 @@ impl ColorModel for NaiveCmyk { } } -static CMYK_MODEL: NaiveCmyk = NaiveCmyk; +const CMYK_MODEL: NaiveCmyk = NaiveCmyk; /// The picker's output with the readout of its latest event, kept in the story's data across passes. fn with_readout(data: &mut StoryData, shown: ColorPickerOutput) -> StoryOutput { diff --git a/crates/design-lint/README.md b/crates/design-lint/README.md index 8dc858f0f..817b02e7a 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` and `impl PlainData for` (only the derives implement them; no allowed location); any source occurrence of `__split_for_bind` (only the `bind_tracked!` 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 new file mode 100644 index 000000000..1da609cd7 --- /dev/null +++ b/crates/design-lint/src/contract/global_state.rs @@ -0,0 +1,206 @@ +//! `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"; + +/// 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. +const PLAIN_DATA: &str = "contract/no-global-state:plain-data"; +const PROJECTION: &str = "contract/no-global-state:projection"; + +/// The hidden `Tracked::__split_for_bind`, called only by `bind_tracked!`; the lint reads source before macro expansion, so every textual hit is a direct call. +const SPLIT_FOR_BIND: &str = "__split_for_bind"; + +struct Hits { + 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 { + proc_macro2::TokenTree::Ident(i) if i == SPLIT_FOR_BIND => out.push(i.span()), + proc_macro2::TokenTree::Group(g) => field_path_in(g.stream(), out), + _ => {} + } + } +} + +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), + node.ident.to_string(), + )); + visit::visit_item_static(self, node); + } + + fn visit_item_macro(&mut self, node: &ItemMacro) { + 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); + 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, FS_MESSAGE.to_owned(), FS.to_owned())); + } + } + visit::visit_item_use(self, node); + } + + fn visit_ident(&mut self, node: &proc_macro2::Ident) { + if node == SPLIT_FOR_BIND { + self.projection.push((node.span(), format!("`{SPLIT_FOR_BIND}` is called by `bind_tracked!` only"))); + } + } + + fn visit_macro(&mut self, node: &syn::Macro) { + let mut spans = Vec::new(); + field_path_in(node.tokens.clone(), &mut spans); + for span in spans { + self.projection.push((span, format!("`{SPLIT_FOR_BIND}` is called by `bind_tracked!` only"))); + } + visit::visit_macro(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(), FS_MESSAGE.to_owned(), FS.to_owned())); + } + visit::visit_path(self, node); + } + + fn visit_item_impl(&mut self, node: &ItemImpl) { + if let Some((_, path, _)) = &node.trait_ + && let Some(name) = path.segments.last().map(|s| s.ident.to_string()).filter(|n| n == "MemoProps" || n == "PlainData") + { + let message = format!("`{name}` is implemented by the derive only"); + if name == "MemoProps" { + self.found.push((node.impl_token.span, message, name)); + } else { + self.derive_only.push((node.impl_token.span, message)); + } + } + visit::visit_item_impl(self, node); + } +} + +impl Hits { + 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") + { + 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, + )); + } + } + } +} + +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(), derive_only: Vec::new(), projection: Vec::new() }; + hits.visit_file(cx.file); + 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); + } + for (span, message) in hits.projection { + cx.flag_span(out, ID, PROJECTION, span, message); + } +} diff --git a/crates/design-lint/src/contract/mod.rs b/crates/design-lint/src/contract/mod.rs index 4ae66e4db..28449dc33 100644 --- a/crates/design-lint/src/contract/mod.rs +++ b/crates/design-lint/src/contract/mod.rs @@ -10,6 +10,8 @@ mod egui_import; mod egui_widget; mod entry; mod facts; +mod global_state; +pub(crate) use global_state::FS; mod keys; mod layers; mod memory; @@ -39,7 +41,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 +81,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 +109,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/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 eded9fe6a..80d4f53f8 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,6 +120,99 @@ fn places(key: &str) -> Vec { } } +/// 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)] = &[ + // The trait's home crate: it implements `MemoProps` by hand for std and framework value types. + ("crates/ui-contract/src/contract/memo.rs", "MemoProps"), + // Settled fact: constant font bytes, decompressed once from compile-time input and immutable after init. + ("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/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", "APPS"), + // Settled fact: the thumbnail texture cache, keyed by its content. + ("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", "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", "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", FS), + // Settled fact: the fallback text format, computed once from constants and immutable after init. + ("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", "IDENTITY"), + // Settled fact: the default layer-style draft and its preview paint, computed once from constants. + ("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", FS), + // later task of #2336: the dock node id counter is hidden state. + ("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", "NEXT_ID"), + // later task of #2336: the outline hover generation counter is hidden state. + ("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", "SERIAL"), + // later task of #2336: the mock image read cache is hidden state. + ("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", "CACHE"), + // later task of #2336: the face loader reads file sizes during the pass. + ("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", "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", +]; + +/// 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 { name: String, dir: PathBuf, @@ -287,6 +380,12 @@ 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 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")); } @@ -336,6 +435,20 @@ 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 memo = Path::new("crates/ui-contract/src/contract/memo.rs"); + assert!(no_global_state_allows("MemoProps", memo)); + assert!(!no_global_state_allows("MemoProps", Path::new("crates/ui-contract/src/contract/entry.rs"))); + assert!(!no_global_state_allows("SOMETHING", memo)); + 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 90ac096ac..5d4354354 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,25 @@ 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`, + // and the two derive-only forms: impl PlainData and a direct `__split_for_bind`. + assert_eq!(found.iter().filter(|f| f.rule == "contract/no-global-state").count(), 10, "{found:?}"); + // 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(), 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/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..01b98cdac --- /dev/null +++ b/crates/design-lint/tests/fixtures/contract-rules/reject/contract-global-state.rs @@ -0,0 +1,26 @@ +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 {} + +impl PlainData for Props {} + +fn project() -> Tracked { + Tracked::__split_for_bind(&[]) +} + +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; 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) +} diff --git a/crates/draw/src/ui/transform/transform_fields.rs b/crates/draw/src/ui/transform/transform_fields.rs index 86c62b5ad..6514371c4 100644 --- a/crates/draw/src/ui/transform/transform_fields.rs +++ b/crates/draw/src/ui/transform/transform_fields.rs @@ -359,9 +359,9 @@ struct Cells<'a> { } /// The panel form's columns: a field, the link, a field; the fields share the width. -static FIELD_COLUMNS: [ColumnWidth; 3] = [ColumnWidth::fill(1.0), ColumnWidth::Content, ColumnWidth::fill(1.0)]; +const FIELD_COLUMNS: [ColumnWidth; 3] = [ColumnWidth::fill(1.0), ColumnWidth::Content, ColumnWidth::fill(1.0)]; /// The panel form's columns with the reference point before them. -static REFERENCE_COLUMNS: [ColumnWidth; 4] = [ColumnWidth::Content, ColumnWidth::fill(1.0), ColumnWidth::Content, ColumnWidth::fill(1.0)]; +const REFERENCE_COLUMNS: [ColumnWidth; 4] = [ColumnWidth::Content, ColumnWidth::fill(1.0), ColumnWidth::Content, ColumnWidth::fill(1.0)]; /// Which form the cells show in. #[derive(Clone, Copy, PartialEq, Eq)] diff --git a/crates/font-manager/src/panel/app.rs b/crates/font-manager/src/panel/app.rs index dc92fc3af..e3feab10d 100644 --- a/crates/font-manager/src/panel/app.rs +++ b/crates/font-manager/src/panel/app.rs @@ -42,7 +42,7 @@ pub fn install_interface_fonts(ctx: &Context, language: &str, craft_faces: &[Emb } /// The filters column takes the width of its widest section; the list and toolbar take the rest. -static PANES: [ColumnWidth; 2] = [ColumnWidth::Content, ColumnWidth::fill(1.0)]; +const PANES: [ColumnWidth; 2] = [ColumnWidth::Content, ColumnWidth::fill(1.0)]; /// Preview downloads: at most this much per file, and this many faces in a session. const PREVIEW_LIMITS: Limits = Limits { max_file_bytes: 64 << 20, max_faces_per_file: 512, max_added_faces: 20_000 }; diff --git a/crates/font-manager/src/panel/browse.rs b/crates/font-manager/src/panel/browse.rs index d954b2c05..574b36113 100644 --- a/crates/font-manager/src/panel/browse.rs +++ b/crates/font-manager/src/panel/browse.rs @@ -159,7 +159,7 @@ impl Texts<'_> { const TABS_SHARE: f32 = 2.0; /// The search field's share of the top bar beside the tabs. const SEARCH_SHARE: f32 = 1.0; -static TOP_BAR: [ColumnWidth; 2] = [ColumnWidth::fill(TABS_SHARE), ColumnWidth::fill(SEARCH_SHARE)]; +const TOP_BAR: [ColumnWidth; 2] = [ColumnWidth::fill(TABS_SHARE), ColumnWidth::fill(SEARCH_SHARE)]; impl FontsPanel { pub(crate) fn top_bar(&mut self, ui: &mut Ui, browse: &FontsBrowseWords, format: &Format, search: Id) { diff --git a/crates/font-manager/src/panel/details.rs b/crates/font-manager/src/panel/details.rs index c47105448..f38fe36c1 100644 --- a/crates/font-manager/src/panel/details.rs +++ b/crates/font-manager/src/panel/details.rs @@ -37,7 +37,7 @@ const HERO_POINTS: f32 = 96.0; const LANGUAGES_SHOWN: usize = 60; /// The facts' labels over their values. -static FACT_COLUMNS: [ColumnWidth; 2] = [ColumnWidth::Content, ColumnWidth::fill(1.0)]; +const FACT_COLUMNS: [ColumnWidth; 2] = [ColumnWidth::Content, ColumnWidth::fill(1.0)]; /// The installed catalog and the preview catalog, which the faces of the two owners load from. type Catalogs = (Arc, Arc); diff --git a/crates/imaging/src/ui/scopes/panel.rs b/crates/imaging/src/ui/scopes/panel.rs index 9ef85fd14..76686ea94 100644 --- a/crates/imaging/src/ui/scopes/panel.rs +++ b/crates/imaging/src/ui/scopes/panel.rs @@ -33,7 +33,7 @@ use craft_ui::style::TypeRole; use egui::{Rect, Response, Ui, pos2}; /// The columns of the statistics grid: label and value, twice. -static STATISTICS_COLUMNS: [ColumnWidth; 4] = [ColumnWidth::Content; 4]; +const STATISTICS_COLUMNS: [ColumnWidth; 4] = [ColumnWidth::Content; 4]; /// Runs `content` in a block that resolves the dark mode when `dark`, else in the flow. fn themed(ui: &mut Ui, dark: bool, mut content: impl FnMut(&mut Ui) -> R) -> Option { diff --git a/crates/menu/src/shortcuts/view.rs b/crates/menu/src/shortcuts/view.rs index cbb4858d7..524d7566c 100644 --- a/crates/menu/src/shortcuts/view.rs +++ b/crates/menu/src/shortcuts/view.rs @@ -35,7 +35,7 @@ use crate::shortcuts::{keyboard, review, sets}; const TABLE_SHARE: f32 = 0.62; /// The detail pane's share of the width beside the table. const DETAIL_SHARE: f32 = 0.38; -static PANES: [ColumnWidth; 2] = [ColumnWidth::fill(TABLE_SHARE), ColumnWidth::fill(DETAIL_SHARE)]; +const PANES: [ColumnWidth; 2] = [ColumnWidth::fill(TABLE_SHARE), ColumnWidth::fill(DETAIL_SHARE)]; /// One frame of the dialog body. pub(crate) fn body(ui: &mut Ui, cx: &mut BodyCx<'_>, env: &mut Env<'_>, state: &mut DialogState) { diff --git a/crates/table/src/ui/error_tag/stories.rs b/crates/table/src/ui/error_tag/stories.rs index 39c295e28..1084b9e6b 100644 --- a/crates/table/src/ui/error_tag/stories.rs +++ b/crates/table/src/ui/error_tag/stories.rs @@ -6,7 +6,7 @@ use craft_ui::runtime::env::Label; use craft_ui::testing::{Drive, Fixture, StoryData, StoryOutput, story}; use egui::Ui; -static FIXES: [Label; 3] = [Label::Static("Convert to Number"), Label::Static("Help on this Error"), Label::Static("Ignore Error")]; +const FIXES: [Label; 3] = [Label::Static("Convert to Number"), Label::Static("Help on this Error"), Label::Static("Ignore Error")]; #[story(ErrorTag<'static>, covers = [Default], drive = Drive::Activate)] fn error_tag(ui: &mut Ui, _: &mut StoryData) -> StoryOutput { diff --git a/crates/text/src/ui/character.rs b/crates/text/src/ui/character.rs index 4d45ed78f..34e186e24 100644 --- a/crates/text/src/ui/character.rs +++ b/crates/text/src/ui/character.rs @@ -135,7 +135,7 @@ const TRACKING_RANGE: RangeInclusive = -1000.0..=10000.0; /// The range of the scale fields, percent. const SCALE_RANGE: RangeInclusive = 0.0..=1000.0; /// Two columns of the same share, for the rows of two fields. -static TWO_COLUMNS: [ColumnWidth; 2] = [ColumnWidth::fill(1.0), ColumnWidth::fill(1.0)]; +const TWO_COLUMNS: [ColumnWidth; 2] = [ColumnWidth::fill(1.0), ColumnWidth::fill(1.0)]; /// The variable-font axes of the current face: what the axis sliders under the style row show. #[cfg(feature = "font-picker")] diff --git a/crates/ui-canvas/src/canvas/full_window_parts/stories.rs b/crates/ui-canvas/src/canvas/full_window_parts/stories.rs index 101de494e..dc8fe5de4 100644 --- a/crates/ui-canvas/src/canvas/full_window_parts/stories.rs +++ b/crates/ui-canvas/src/canvas/full_window_parts/stories.rs @@ -104,8 +104,8 @@ fn status_failed(ui: &mut Ui, _: &mut StoryData) -> StoryOutput { #[story(FullWindowCanvas<'static>, covers = [], drive = Drive::Never)] fn canvas(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - static IMAGE_SOURCE: Flat = Flat { colour: Color32::from_rgb(0x4a, 0x7f, 0xc1), half: true }; - static MASK: Flat = Flat { colour: Color32::from_rgba_premultiplied(0x40, 0x00, 0x00, 0x40), half: false }; + const IMAGE_SOURCE: Flat = Flat { colour: Color32::from_rgb(0x4a, 0x7f, 0xc1), half: true }; + const MASK: Flat = Flat { colour: Color32::from_rgba_premultiplied(0x40, 0x00, 0x00, 0x40), half: false }; let checkerboard = *data.value("checkerboard", true); let overlay = *data.value("overlay", true); let tint = *data.value("tint", true); diff --git a/crates/ui-contract/src/contract/entry.rs b/crates/ui-contract/src/contract/entry.rs index 51bae9f28..dfffeaf84 100644 --- a/crates/ui-contract/src/contract/entry.rs +++ b/crates/ui-contract/src/contract/entry.rs @@ -6,7 +6,7 @@ use crate::runtime::env::Label; use craft_theme::Srgba; /// The label of a separator, which has none. -static NO_LABEL: Label = Label::Empty; +const NO_LABEL: Label = Label::Empty; /// A row of entries: an item that reports its value when picked, a heading over a group of items, or a separator /// between groups of items. diff --git a/crates/ui-contract/src/testing/icon_trials.rs b/crates/ui-contract/src/testing/icon_trials.rs index db89c9f64..27c72f843 100644 --- a/crates/ui-contract/src/testing/icon_trials.rs +++ b/crates/ui-contract/src/testing/icon_trials.rs @@ -17,8 +17,8 @@ const DISC: &[u8] = b""; -static FIRST_SET: AppIcons = AppIcons { name: "t10-first", stroke_width: None, icons: &[(FIRST_NAME, DISC), (CATALOG_NAME, DISC)] }; -static SECOND_SET: AppIcons = AppIcons { name: "t10-second", stroke_width: None, icons: &[(FIRST_NAME, SQUARE), (SECOND_NAME, SQUARE)] }; +const FIRST_SET: AppIcons = AppIcons { name: "t10-first", stroke_width: None, icons: &[(FIRST_NAME, DISC), (CATALOG_NAME, DISC)] }; +const SECOND_SET: AppIcons = AppIcons { name: "t10-second", stroke_width: None, icons: &[(FIRST_NAME, SQUARE), (SECOND_NAME, SQUARE)] }; fn icon(name: &'static str) -> Option { let tokens = style::tokens(Mode::Light, Contrast::Standard); diff --git a/crates/ui-gallery/src/chrome/card.rs b/crates/ui-gallery/src/chrome/card.rs index 9f5d56520..75754c601 100644 --- a/crates/ui-gallery/src/chrome/card.rs +++ b/crates/ui-gallery/src/chrome/card.rs @@ -123,7 +123,7 @@ pub struct CardEvents { } /// The column lists of story grids, by count. -static COLUMNS: [ColumnWidth; 4] = [ColumnWidth::fill(1.0); 4]; +const COLUMNS: [ColumnWidth; 4] = [ColumnWidth::fill(1.0); 4]; /// The columns of a form-rows card: the captions, the stories, then the values they show. The stories' column is as /// wide as its widest story, so each value sits a gap past its control, as the old gallery showed it. diff --git a/crates/ui-patterns/src/patterns/form_dialogs/new_document.rs b/crates/ui-patterns/src/patterns/form_dialogs/new_document.rs index 95b449b17..c9b8f6745 100644 --- a/crates/ui-patterns/src/patterns/form_dialogs/new_document.rs +++ b/crates/ui-patterns/src/patterns/form_dialogs/new_document.rs @@ -377,7 +377,7 @@ impl Outcome for NewDocumentOutput { } /// The columns of the body: the cards take the room the details column leaves. -static COLUMNS: [ColumnWidth; 2] = [ColumnWidth::fill(1.0), ColumnWidth::Content]; +const COLUMNS: [ColumnWidth; 2] = [ColumnWidth::fill(1.0), ColumnWidth::Content]; /// The body of the dialog: the columns, then what they asked for. fn body(ui: &mut Ui, form: &mut FormCx<'_, '_>, values: &mut DocumentOptions, shared: &Shared<'_>) -> bool { diff --git a/crates/ui-widgets/src/controls/disclosure.rs b/crates/ui-widgets/src/controls/disclosure.rs index 8f306a17f..7453bdd4c 100644 --- a/crates/ui-widgets/src/controls/disclosure.rs +++ b/crates/ui-widgets/src/controls/disclosure.rs @@ -53,11 +53,11 @@ pub struct DisclosureGlyph { } /// The arrow of a field or picker. -static DROPDOWN: DisclosureGlyph = DisclosureGlyph::dropdown_form(); +const DROPDOWN: DisclosureGlyph = DisclosureGlyph::dropdown_form(); /// The arrow of a button that opens a menu. -static MENU_BUTTON: DisclosureGlyph = DisclosureGlyph { open: 1.0, form: ArrowForm::Dropdown, stroke: StrokeWidth::Medium }; +const MENU_BUTTON: DisclosureGlyph = DisclosureGlyph { open: 1.0, form: ArrowForm::Dropdown, stroke: StrokeWidth::Medium }; /// The submenu arrow. -static SUBMENU: DisclosureGlyph = DisclosureGlyph { open: 0.0, form: ArrowForm::Submenu, stroke: StrokeWidth::Thin }; +const SUBMENU: DisclosureGlyph = DisclosureGlyph { open: 0.0, form: ArrowForm::Submenu, stroke: StrokeWidth::Thin }; impl DisclosureGlyph { /// The disclosure triangle `open` of the way turned. diff --git a/crates/ui-widgets/src/display/spinner/stories.rs b/crates/ui-widgets/src/display/spinner/stories.rs index 5d8569835..ad6a865f0 100644 --- a/crates/ui-widgets/src/display/spinner/stories.rs +++ b/crates/ui-widgets/src/display/spinner/stories.rs @@ -9,7 +9,7 @@ use craft_behavior::ColumnWidth; use egui::Ui; /// The name and the spinner of each size, in two columns that fit their content. -static COLUMNS: [ColumnWidth; 2] = [ColumnWidth::Content, ColumnWidth::Content]; +const COLUMNS: [ColumnWidth; 2] = [ColumnWidth::Content, ColumnWidth::Content]; #[story(Spinner, covers = [Default], drive = Drive::Never)] fn spinner(ui: &mut Ui, _: &mut StoryData) -> StoryOutput { diff --git a/crates/ui-widgets/src/graph/stories.rs b/crates/ui-widgets/src/graph/stories.rs index c644dcabb..71240217d 100644 --- a/crates/ui-widgets/src/graph/stories.rs +++ b/crates/ui-widgets/src/graph/stories.rs @@ -26,7 +26,7 @@ enum CompEdit { /// Two inputs on the left and an output on the right. struct Mix; -static MIX: Mix = Mix; +const MIX: Mix = Mix; impl NodeKind for Mix { fn title(&self) -> &str { diff --git a/crates/ui-widgets/src/layout_components/stories.rs b/crates/ui-widgets/src/layout_components/stories.rs index 50bb18891..f2f3472d5 100644 --- a/crates/ui-widgets/src/layout_components/stories.rs +++ b/crates/ui-widgets/src/layout_components/stories.rs @@ -32,14 +32,14 @@ fn stack_footer(ui: &mut Ui, _: &mut StoryData) -> StoryOutput { outlined(ui, |ui| Stack::new().gap(Gap::Stack).pad(Pad::Regular).footer(|ui, _| words(ui, 2..3)).show(ui, |ui, _| words(ui, 0..2)).into()) } -static COLUMNS: [ColumnWidth; 2] = [ColumnWidth::Content, ColumnWidth::Fixed(60.0)]; +const COLUMNS: [ColumnWidth; 2] = [ColumnWidth::Content, ColumnWidth::Fixed(60.0)]; #[story(Grid, covers = [Default])] fn grid(ui: &mut Ui, _: &mut StoryData) -> StoryOutput { outlined(ui, |ui| Grid::new(&COLUMNS).pad(Pad::Regular).show(ui, |ui, _| words(ui, 0..4)).into()) } -static FIXED: [ColumnWidth; 3] = [ColumnWidth::Content, ColumnWidth::Content, ColumnWidth::Content]; +const FIXED: [ColumnWidth; 3] = [ColumnWidth::Content, ColumnWidth::Content, ColumnWidth::Content]; /// A grid whose arrangement is fixed: in a room narrower than its columns it keeps them beside each other and /// overflows, and its second row leaves the first cell empty, so the cells after it stay in their columns. @@ -58,7 +58,7 @@ fn grid_fixed(ui: &mut Ui, _: &mut StoryData) -> StoryOutput { }) } -static TOP: [ColumnWidth; 2] = [ColumnWidth::Content, ColumnWidth::Content]; +const TOP: [ColumnWidth; 2] = [ColumnWidth::Content, ColumnWidth::Content]; /// A grid whose cells stand at the top of their row: a short column of words beside a taller one starts level with it. #[story(Grid, covers = [])]