diff --git a/crates/design-lint/README.md b/crates/design-lint/README.md index 817b02e7a..7751a0f6c 100644 --- a/crates/design-lint/README.md +++ b/crates/design-lint/README.md @@ -81,7 +81,7 @@ Egui paths are resolved through the file's `use` items (one table per file, grou Names are resolved through the file's `use` items, per module scope: grouped imports, renames (`use egui::Margin as M`), module aliases (`use crate::theme as t`) and glob imports (`use crate::theme::*`) all reach the rule table, so `margin(4.0)` is flagged after `use crate::theme::margin`. A bare name that a fn in the same module defines is not extended through globs. Imports in a module do not apply in sibling modules. -A literal is a number, optionally negated, parenthesised, cast or in arithmetic; zero is never flagged. A name is flagged when a `const` or `static` in the same file with that name has such a value. Consts are keyed by module and impl scope: a bare name takes the innermost scope that defines it, `Self::X`, `self::X`, `super::X`, `crate::X`, `Type::X` and `module::X` (last two segments) the scope they name, and a name with several candidates is flagged when any is non-zero. +A literal is a number, optionally negated, parenthesised, cast or in arithmetic; zero is never flagged. A name is flagged when a `const` or `static` in the same file with that name has such a value, unless it is a component constant: a module- or impl-level `const` with a doc comment, the named place for a dimension of one component's own drawing (craft-framework.md 5.4). A name that resolves to a component constant is not a literal size, and its initializer is its definition, so the literals in it are not flagged either. A `const` inside a fn body, a `static` and an undocumented `const` are flagged as literals. Consts are keyed by module and impl scope: a bare name takes the innermost scope that defines it, `Self::X`, `self::X`, `super::X`, `crate::X`, `Type::X` and `module::X` (last two segments) the scope they name, and a name with several candidates is flagged when any is non-zero. ## Markers diff --git a/crates/design-lint/src/rules.rs b/crates/design-lint/src/rules.rs index 58720f847..d3dec56b4 100644 --- a/crates/design-lint/src/rules.rs +++ b/crates/design-lint/src/rules.rs @@ -150,6 +150,7 @@ pub(crate) fn analyze_file(src: &str, file: &syn::File, include_tests: bool) -> imports: Vec::new(), fns: Vec::new(), scope: Vec::new(), + in_named_const: false, out: Analysis::default(), include_tests, }; @@ -184,6 +185,9 @@ struct ConstDef { line: usize, expr: Expr, value: Option, + /// A component constant: a module- or impl-level `const` with a doc comment. A name that resolves to it is not a + /// literal size, and its initializer is its definition, not a call site. + named: bool, } /// A `use` declaration: `alias` is the name it brings in, `None` for a glob (`path::*`). @@ -202,6 +206,8 @@ struct Linter<'a> { fns: Vec<(Vec, String)>, /// The modules and impl blocks around the item being visited. scope: Vec, + /// Inside the initializer of a named const, where `literal-size/*` does not apply. + in_named_const: bool, out: Analysis, include_tests: bool, } @@ -212,17 +218,21 @@ struct ConstCollector { imports: Vec, fns: Vec<(Vec, String)>, scope: Vec, + /// How many fn bodies enclose the item being visited. + fn_depth: usize, include_tests: bool, } impl ConstCollector { - fn add(&mut self, name: &syn::Ident, expr: &Expr) { + /// Records a const or static; `documented` is whether it is a `const` with a doc comment. + fn add(&mut self, name: &syn::Ident, expr: &Expr, documented: bool) { self.defs.push(ConstDef { scope: self.scope.clone(), name: name.to_string(), line: name.span().start().line, expr: expr.clone(), value: None, + named: documented && self.fn_depth == 0, }); } @@ -256,9 +266,21 @@ impl<'ast> Visit<'ast> for ConstCollector { fn visit_item_fn(&mut self, i: &'ast syn::ItemFn) { if !self.skipped(&i.attrs) { self.fns.push((module_scope(&self.scope).to_vec(), i.sig.ident.to_string())); + self.fn_depth += 1; visit::visit_item_fn(self, i); + self.fn_depth -= 1; } } + fn visit_impl_item_fn(&mut self, i: &'ast syn::ImplItemFn) { + self.fn_depth += 1; + visit::visit_impl_item_fn(self, i); + self.fn_depth -= 1; + } + fn visit_trait_item_fn(&mut self, i: &'ast syn::TraitItemFn) { + self.fn_depth += 1; + visit::visit_trait_item_fn(self, i); + self.fn_depth -= 1; + } fn visit_item_use(&mut self, i: &'ast syn::ItemUse) { if !self.skipped(&i.attrs) { let mut found = Vec::new(); @@ -268,15 +290,15 @@ impl<'ast> Visit<'ast> for ConstCollector { } } fn visit_item_const(&mut self, i: &'ast syn::ItemConst) { - self.add(&i.ident, &i.expr); + self.add(&i.ident, &i.expr, has_doc(&i.attrs)); visit::visit_item_const(self, i); } fn visit_item_static(&mut self, i: &'ast syn::ItemStatic) { - self.add(&i.ident, &i.expr); + self.add(&i.ident, &i.expr, false); visit::visit_item_static(self, i); } fn visit_impl_item_const(&mut self, i: &'ast syn::ImplItemConst) { - self.add(&i.ident, &i.expr); + self.add(&i.ident, &i.expr, has_doc(&i.attrs)); visit::visit_impl_item_const(self, i); } } @@ -349,6 +371,11 @@ fn last_ident(path: &syn::Path) -> Option { path.segments.last().map(|s| s.ident.to_string()) } +/// Whether an item carries a doc comment (`///` or `#[doc = ...]`). +fn has_doc(attrs: &[Attribute]) -> bool { + attrs.iter().any(|a| a.path().is_ident("doc")) +} + fn cfg_is_test(meta: &Meta) -> bool { match meta { Meta::Path(p) => p.is_ident("test"), @@ -420,8 +447,14 @@ impl Linter<'_> { } fn resolve_consts(&mut self, file: &syn::File) { - let mut collector = - ConstCollector { defs: Vec::new(), imports: Vec::new(), fns: Vec::new(), scope: Vec::new(), include_tests: self.include_tests }; + let mut collector = ConstCollector { + defs: Vec::new(), + imports: Vec::new(), + fns: Vec::new(), + scope: Vec::new(), + fn_depth: 0, + include_tests: self.include_tests, + }; collector.visit_file(file); self.defs = collector.defs; self.imports = collector.imports; @@ -431,7 +464,8 @@ impl Linter<'_> { .defs .iter() .enumerate() - .filter(|(_, d)| d.value.is_none()) + // A named const keeps no literal value: a name that resolves to it reads like a token. + .filter(|(_, d)| d.value.is_none() && !d.named) .filter_map(|(i, d)| self.eval_in(&d.expr, &d.scope).map(|v| (i, v))) .collect(); if resolved.is_empty() { @@ -552,12 +586,21 @@ impl Linter<'_> { Some((shown, def.line)) } + /// Whether the const item named `ident` is a named const (`ConstDef::named`). + fn is_named_const(&self, ident: &syn::Ident) -> bool { + let line = ident.span().start().line; + self.defs.iter().any(|d| d.named && d.line == line && *ident == d.name) + } + fn is_flagged_size(&self, e: &Expr) -> bool { self.eval(e).is_some_and(|v| v != 0.0) } /// Reports `what` when any of `args` is a non-zero literal size. fn size_rule<'e>(&mut self, rule: &'static str, what: proc_macro2::Span, args: impl IntoIterator) { + if self.in_named_const { + return; + } let args: Vec<&Expr> = args.into_iter().collect(); // A vector of literal -1, 0 and 1 is a direction, not a size. if rule == VEC2 && args.iter().all(|a| is_unit_literal(a)) { @@ -726,11 +769,21 @@ fn is_unit_literal(e: &Expr) -> bool { fn hint(rule: &str) -> &'static str { match rule { - VEC2 => "use a size token (`Tokens::of(ui).size.control.md`, `space.gap.inline`) or mark `// design: allow()`", - ADD_SPACE => "use a spacing token (`Tokens::of(ui).space.gap.inline`) or mark `// design: allow()`", - CORNER_RADIUS => "use a radius token from `Tokens::of(ui)` or mark `// design: allow()`", - STROKE => "use a stroke width token from `Tokens::of(ui)` or mark `// design: allow()`", - MARGIN => "use a spacing token (`Tokens::of(ui).space`) or mark `// design: allow()`", + VEC2 => { + "use a size token (`Tokens::of(ui).size.control.md`, `space.gap.inline`), a documented module-level const for a dimension of the component's own drawing, or mark `// design: allow()`" + } + ADD_SPACE => { + "use a spacing token (`Tokens::of(ui).space.gap.inline`), a documented module-level const for a dimension of the component's own drawing, or mark `// design: allow()`" + } + CORNER_RADIUS => { + "use a radius token from `Tokens::of(ui)`, a documented module-level const for a dimension of the component's own drawing, or mark `// design: allow()`" + } + STROKE => { + "use a stroke width token from `Tokens::of(ui)`, a documented module-level const for a dimension of the component's own drawing, or mark `// design: allow()`" + } + MARGIN => { + "use a spacing token (`Tokens::of(ui).space`), a documented module-level const for a dimension of the component's own drawing, or mark `// design: allow()`" + } TOOLTIP => "use `craft_ui::contract::Props::tooltip` or `craft_ui::contract::Show::show_with_tip` or mark `// design: allow()`", STYLE_MUTATION => "set styles through the theme (craft-ui installs them from the tokens) or mark `// design: allow()`", _ => "use a type-size token from `Tokens::of(ui)` or mark `// design: allow()`", @@ -774,9 +827,18 @@ impl<'ast> Visit<'ast> for Linter<'_> { } fn visit_item_const(&mut self, i: &'ast syn::ItemConst) { if !self.skips(&i.attrs, i.span()) { + let named = self.in_named_const || self.is_named_const(&i.ident); + let outer = std::mem::replace(&mut self.in_named_const, named); visit::visit_item_const(self, i); + self.in_named_const = outer; } } + fn visit_impl_item_const(&mut self, i: &'ast syn::ImplItemConst) { + let named = self.in_named_const || self.is_named_const(&i.ident); + let outer = std::mem::replace(&mut self.in_named_const, named); + visit::visit_impl_item_const(self, i); + self.in_named_const = outer; + } fn visit_item_static(&mut self, i: &'ast syn::ItemStatic) { if !self.skips(&i.attrs, i.span()) { visit::visit_item_static(self, i); diff --git a/crates/design-lint/src/workspace.rs b/crates/design-lint/src/workspace.rs index 3dab5fe16..24e52ea6a 100644 --- a/crates/design-lint/src/workspace.rs +++ b/crates/design-lint/src/workspace.rs @@ -58,6 +58,7 @@ const CLOSED: &[&str] = &[ "ReorderMove", // built or matched in craft-ui-patterns "RowState", // built or matched in craft-ui-widgets "RuleLook", // built or matched in craft-ui-canvas + "RulerFace", // matched by every ruler (craft-text, craft-pages, craft-ui-canvas): a new face must be drawn by each "ShellRegions", // built or matched in craft-ui-shell "SizeLimits", // built or matched in craft-ui-panels "StoryOutput", // built or matched in craft-ui-widgets diff --git a/crates/design-lint/tests/rules.rs b/crates/design-lint/tests/rules.rs index 11b6b8efc..cba0e2fe9 100644 --- a/crates/design-lint/tests/rules.rs +++ b/crates/design-lint/tests/rules.rs @@ -67,6 +67,20 @@ fn consts_resolve_by_module_and_impl_scope() { assert_eq!(run(src).len(), 3); } +#[test] +fn documented_consts_are_component_constants() { + // A documented module or impl const is a named value, its initializer included; arithmetic on it reads like a token. + let src = "/// The tick.\nconst TICK: f32 = 3.0;\n/// The room.\nconst ROOM: Vec2 = vec2(30.0, 40.0);\nstruct A;\nimpl A {\n /// The pad.\n const PAD: f32 = 6.0;\n fn f(&self, ui: &mut Ui) { ui.add_space(Self::PAD); ui.add_space(TICK * 2.0); let v = vec2(TICK, ROOM.y); }\n}\n"; + assert!(clean(src)); + + // An undocumented const, a documented const in a fn body and a literal stay flagged. + let src = "const GAP: f32 = 4.0;\nfn f(ui: &mut Ui) { ui.add_space(GAP); }\nfn g(ui: &mut Ui) {\n /// The gap.\n const LOCAL: f32 = 4.0;\n ui.add_space(LOCAL);\n}\nfn h(ui: &mut Ui) { ui.add_space(4.0); }\n"; + assert_eq!(run(src).iter().map(|f| f.line).collect::>(), [2, 6, 8]); + + // The initializer of an undocumented const is a call site. + assert!(flagged("const ROOM: Vec2 = vec2(30.0, 40.0);\n", "literal-size/vec2")); +} + #[test] fn clippy_allow_attributes_are_counted_and_inner_ones_flagged() { let src = "#![allow(clippy::disallowed_methods, reason = \"stock widgets\")]\n#[expect(clippy::disallowed_types)]\nstruct S;\n#[allow(clippy::too_many_arguments)]\nfn f() {}\nmod m {\n #![expect(clippy::disallowed_methods)]\n}\n"; diff --git a/crates/draw/src/ui/pen/anchor_tool.rs b/crates/draw/src/ui/pen/anchor_tool.rs index 41cb41592..6a97242d4 100644 --- a/crates/draw/src/ui/pen/anchor_tool.rs +++ b/crates/draw/src/ui/pen/anchor_tool.rs @@ -10,7 +10,6 @@ use craft_ui::primitives::{Draw, ToolIcon}; use egui::Vec2; /// The apex of the Convert Point icon's caret, in the units of the icon's box. -// design: allow[literal-size/vec2](the cursor art's hot spot offset in icon units, not a layout size) const CONVERT_TIP: Vec2 = Vec2::new(ICON_BOX / 2.0, 5.5); /// The canvas tool of Add Anchor Point, Delete Anchor Point, Convert Point and Direct Selection. Every press of these diff --git a/crates/pages/src/ui/page_rulers.rs b/crates/pages/src/ui/page_rulers.rs index d93d4a906..044bc3500 100644 --- a/crates/pages/src/ui/page_rulers.rs +++ b/crates/pages/src/ui/page_rulers.rs @@ -17,7 +17,7 @@ use craft_ui::contract::{ Access, Bind, Common, Component, Cx, Focus as _, IdSource, Input, MeasureCx, Name, NoValue, Numeric, Outcome, PaintUi, PartsCx, Pointer as _, Props as _, Remember as _, Role, Show as _, Styled as _, WordSetCx as _, }; -use craft_ui::primitives::{PaintShape, StrokeWidth, TextRun, Tick, TickEdge, TickRank}; +use craft_ui::primitives::{PaintShape, RulerFace, StrokeWidth, TextRun, Tick, TickEdge, TickRank}; use craft_ui::runtime::env::{Env, Label}; use craft_ui::runtime::focus::{ActivateKeys, FocusShape, KeyUse}; use craft_ui::style::{ComponentStyle, FocusLook, StyleColor, StyleCx, TextLook, TypeRole}; @@ -80,6 +80,10 @@ pub struct VerticalRulerStyle { metrics: Metrics, #[style(focus)] focus: FocusLook, + /// The face: the prop's, else the component set's. + face: RulerFace, + /// The strip round the centred face's bar. + strip: StyleColor, /// The text range. fill: StyleColor, /// The margins above and below it. @@ -113,6 +117,9 @@ struct Held(Option<(usize, f32)>); /// shaded as margin and the text range filled, and a drag of a grip is one gesture. /// /// - Ticks and numbers count from the page's top in the unit, through the canvas rulers' tick rule. +/// - The face ([`RulerFace`]) is the prop's, else the component set's: the edge face hangs the ticks from the strip's +/// inner edge with each number below its whole-unit tick; the centred face (Word's) draws a bar inset in the strip +/// with the ticks centred on it and the numbers in place of the whole-unit ticks, over the text range only. /// - A grip drag reports a [`RowDrag`]: Begin, Update per move, Commit on release, Cancel on Escape. It snaps to the /// ruler's step; Alt reports in `mods` that the drag is free of the snap and the position is not snapped. /// - The grips are one Tab stop: Page Down and Page Up pick the next or previous grip, the arrows nudge the focused one @@ -133,13 +140,17 @@ pub struct VerticalRuler<'a> { /// The table row bottoms, points from the page's top, each a grip. #[prop] rows: &'a [f32], + /// The face; unset, the scope's component set picks it ([`RulerFace::of`]). + #[style_key] + #[prop] + face: Option, report: Option, } impl<'a> VerticalRuler<'a> { /// The ruler named `label` along `page`. pub fn new(label: impl Into