diff --git a/Cargo.lock b/Cargo.lock index f2351888f..efb9465f8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4218,6 +4218,8 @@ dependencies = [ "log", "proc-macro2", "serde", + "serde_json", + "siphasher", "skrifa 0.44.0", "smallvec", "syn 2.0.119", diff --git a/crates/behavior/src/fit.rs b/crates/behavior/src/fit.rs index 8b57e2b93..0abbabacf 100644 --- a/crates/behavior/src/fit.rs +++ b/crates/behavior/src/fit.rs @@ -186,7 +186,7 @@ fn squeeze(natural: &[f32], indices: &[usize], total: f32, minimum: f32) -> Vec< } /// Whether an item may move into the overflow menu, or lives there. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum FitKeep { /// The item leaves the strip when the room runs out, last item first. diff --git a/crates/ui-contract/Cargo.toml b/crates/ui-contract/Cargo.toml index 07aa7ae2d..b96c932c0 100644 --- a/crates/ui-contract/Cargo.toml +++ b/crates/ui-contract/Cargo.toml @@ -36,6 +36,10 @@ craft-theme = { workspace = true } craft-ui-macros = { workspace = true } # `Tracked`: app models whose revision keys memoized views and write-through bindings. craft-tracked = { workspace = true } +# `MemoKey`: SipHash-1-3 with a 128-bit output. +siphasher = "1" +# `CommandRef.params`, which a memo key walks. +serde_json = { workspace = true } craft-settings = { workspace = true } toml = { version = "1.1", default-features = false, features = ["std", "parse", "serde"] } egui = { workspace = true } diff --git a/crates/ui-contract/src/contract/memo.rs b/crates/ui-contract/src/contract/memo.rs new file mode 100644 index 000000000..3fe67ad42 --- /dev/null +++ b/crates/ui-contract/src/contract/memo.rs @@ -0,0 +1,826 @@ +//! `MemoProps` and `MemoKey`: every input of a memoized view, as one key the framework compares. +//! +//! A memoized view's content is a `fn` pointer, which captures nothing, and its props are its only argument besides the +//! `Ui`. `MemoProps` is implemented only for types that cannot change behind a shared reference and that the key can +//! feed completely: plain values, strings, containers of props, references to props, `Tracked` (by its revision), +//! callbacks as [`Stateless`] and the framework's value types. The types the plain-data derives reject (`Cell`, +//! `RefCell`, `OnceCell`, `OnceLock`, `Mutex`, `RwLock`, atomics, raw pointers, `dyn` trait objects, closures; the list +//! is on [`PlainData`](craft_tracked::PlainData)) have no implementation, so props holding one do not compile, and the +//! error points at the field: +//! +//! ```compile_fail,E0277 +//! # extern crate craft_ui_contract as craft_ui; +//! #[derive(craft_ui::contract::MemoProps)] +//! struct Props { +//! count: std::cell::Cell, +//! } +//! ``` +//! +//! ```compile_fail,E0277 +//! # extern crate craft_ui_contract as craft_ui; +//! #[derive(craft_ui::contract::MemoProps)] +//! struct Props<'a> { +//! count: &'a std::cell::RefCell, +//! } +//! ``` +//! +//! ```compile_fail,E0277 +//! # extern crate craft_ui_contract as craft_ui; +//! #[derive(craft_ui::contract::MemoProps)] +//! struct Props { +//! name: std::cell::OnceCell, +//! } +//! ``` +//! +//! ```compile_fail,E0277 +//! # extern crate craft_ui_contract as craft_ui; +//! #[derive(craft_ui::contract::MemoProps)] +//! struct Props { +//! name: std::sync::OnceLock, +//! } +//! ``` +//! +//! ```compile_fail,E0277 +//! # extern crate craft_ui_contract as craft_ui; +//! #[derive(craft_ui::contract::MemoProps)] +//! struct Props { +//! count: std::sync::Mutex, +//! } +//! ``` +//! +//! ```compile_fail,E0277 +//! # extern crate craft_ui_contract as craft_ui; +//! #[derive(craft_ui::contract::MemoProps)] +//! struct Props { +//! count: std::sync::RwLock, +//! } +//! ``` +//! +//! ```compile_fail,E0277 +//! # extern crate craft_ui_contract as craft_ui; +//! #[derive(craft_ui::contract::MemoProps)] +//! struct Props { +//! count: std::sync::atomic::AtomicU32, +//! } +//! ``` +//! +//! ```compile_fail,E0277 +//! # extern crate craft_ui_contract as craft_ui; +//! #[derive(craft_ui::contract::MemoProps)] +//! struct Props { +//! at: *const u8, +//! } +//! ``` +//! +//! ```compile_fail,E0277 +//! # extern crate craft_ui_contract as craft_ui; +//! #[derive(craft_ui::contract::MemoProps)] +//! struct Props<'a> { +//! label: &'a dyn Fn() -> String, +//! } +//! ``` +//! +//! ```compile_fail,E0277 +//! # extern crate craft_ui_contract as craft_ui; +//! #[derive(craft_ui::contract::MemoProps)] +//! struct Props { +//! label: Box String>, +//! } +//! ``` +//! +//! A closure, a field of a generic type and a field inside an enum variant are checked the same way: +//! +//! ```compile_fail,E0277 +//! # extern crate craft_ui_contract as craft_ui; +//! #[derive(craft_ui::contract::MemoProps)] +//! struct Props { +//! label: F, +//! } +//! let n = 3; +//! craft_ui::contract::MemoKey::of(&Props { label: move || n }); +//! ``` +//! +//! ```compile_fail,E0277 +//! # extern crate craft_ui_contract as craft_ui; +//! #[derive(craft_ui::contract::MemoProps)] +//! struct Props { +//! value: T, +//! } +//! craft_ui::contract::MemoKey::of(&Props { value: std::cell::Cell::new(3) }); +//! ``` +//! +//! ```compile_fail,E0277 +//! # extern crate craft_ui_contract as craft_ui; +//! #[derive(craft_ui::contract::MemoProps)] +//! enum Props { +//! Empty, +//! Count(std::cell::Cell), +//! } +//! ``` +//! +//! A field of a foreign plain type that has no implementation feeds the key through its `Hash`, with the reason it is +//! plain: `#[memo_props(hash = "why")]`. The type must be `Hash + Sync`, and its `Hash` must cover everything the view +//! shows and be prefix-free (two different values never feed bytes of which one starts the other). `Sync` keeps out +//! raw pointers, `NonNull`, `Cell` and `RefCell`, whose `Hash` (where they have one) says nothing about what they point +//! at or hold. A type without `Hash`, a raw pointer and a `NonNull` still fail: +//! +//! ```compile_fail,E0277 +//! # extern crate craft_ui_contract as craft_ui; +//! #[derive(craft_ui::contract::MemoProps)] +//! struct Props { +//! #[memo_props(hash = "an address")] +//! at: *const u8, +//! } +//! ``` +//! +//! ```compile_fail,E0277 +//! # extern crate craft_ui_contract as craft_ui; +//! #[derive(craft_ui::contract::MemoProps)] +//! struct Props { +//! #[memo_props(hash = "an address")] +//! at: std::ptr::NonNull, +//! } +//! ``` +//! +//! ```compile_fail,E0277 +//! # extern crate craft_ui_contract as craft_ui; +//! #[derive(craft_ui::contract::MemoProps)] +//! struct Props { +//! #[memo_props(hash = "a plain number")] +//! count: std::cell::Cell, +//! } +//! ``` +//! +//! A callback's type can't be named, so props holding a [`Stateless`] are generic over it. Its parameter is marked +//! `#[memo_props(stateless)]`, which bounds it by what `Stateless` needs instead of `MemoProps`: +//! +//! ``` +//! # extern crate craft_ui_contract as craft_ui; +//! use craft_ui::contract::{MemoKey, MemoProps, Stateless}; +//! #[derive(MemoProps)] +//! struct Props<#[memo_props(stateless)] E> { +//! title: String, +//! english: Stateless, +//! } +//! fn english() -> &'static str { +//! "English" +//! } +//! let props = |title: &str| Props { title: title.to_owned(), english: Stateless::new(english) }; +//! assert_eq!(MemoKey::of(&props("a")), MemoKey::of(&props("a"))); +//! assert_ne!(MemoKey::of(&props("a")), MemoKey::of(&props("b"))); +//! ``` +//! +//! The mark only lifts the bound: a marked parameter held as a bare field is still checked, and an unmarked parameter +//! holding a fn item is not props: +//! +//! ```compile_fail,E0277 +//! # extern crate craft_ui_contract as craft_ui; +//! #[derive(craft_ui::contract::MemoProps)] +//! struct Props<#[memo_props(stateless)] E> { +//! english: E, +//! } +//! ``` +//! +//! ```compile_fail,E0277 +//! # extern crate craft_ui_contract as craft_ui; +//! use craft_ui::contract::{MemoKey, MemoProps, Stateless}; +//! #[derive(MemoProps)] +//! struct Props { +//! english: Stateless, +//! } +//! fn english() -> &'static str { +//! "English" +//! } +//! MemoKey::of(&Props { english: Stateless::new(english) }); +//! ``` +//! +//! The mark is for type parameters only: +//! +//! ```compile_fail +//! # extern crate craft_ui_contract as craft_ui; +//! #[derive(craft_ui::contract::MemoProps)] +//! struct Props<#[memo_props(stateless)] 'a> { +//! title: &'a str, +//! } +//! ``` +//! +//! Plain props derive, recursive types included: +//! +//! ``` +//! # extern crate craft_ui_contract as craft_ui; +//! use craft_ui::contract::{MemoKey, MemoProps}; +//! #[derive(MemoProps)] +//! enum Node { +//! Leaf(String), +//! Branch(Vec), +//! } +//! let tree = |name: &str| Node::Branch(vec![Node::Leaf(name.to_owned())]); +//! assert_eq!(MemoKey::of(&tree("a")), MemoKey::of(&tree("a"))); +//! assert_ne!(MemoKey::of(&tree("a")), MemoKey::of(&tree("b"))); +//! ``` +//! +//! What the types cannot see: process-level state the `fn` or its callees read (`static`, `thread_local!`, `OnceLock`, +//! clocks, files, environment variables) and `unsafe` code. A design-lint rule covers UI crates and the replay audit +//! covers the rest. + +use std::any::TypeId; +use std::borrow::Cow; +use std::cmp::Ordering; +use std::collections::{BTreeMap, BTreeSet}; +use std::ffi::{OsStr, OsString}; +use std::hash::{Hash, Hasher}; +use std::marker::PhantomData; +use std::num::{ + NonZeroI8, NonZeroI16, NonZeroI32, NonZeroI64, NonZeroI128, NonZeroIsize, NonZeroU8, NonZeroU16, NonZeroU32, NonZeroU64, NonZeroU128, + NonZeroUsize, +}; +use std::ops::{Range, RangeInclusive}; +use std::path::{Path, PathBuf}; +use std::rc::Rc; +use std::sync::Arc; +use std::time::Duration; + +use craft_tracked::{PlainData, Revision, Tracked}; +use siphasher::sip128::{Hasher128, SipHasher13}; + +pub use craft_ui_macros::MemoProps; + +/// Every input a memoized view reads, fed into a [`MemoKey`]. Two equal keys mean equal inputs. +/// +/// Derive it (`#[derive(MemoProps)]`): the derive feeds every field in order and requires `MemoProps` of each, so a +/// field the view could read without the key seeing it does not compile. Implementations by hand belong to this crate +/// only. +#[diagnostic::on_unimplemented( + message = "`{Self}` cannot be memo props", + label = "not memo props", + note = "memo props hold plain values, strings, containers and references of props, `Tracked` and framework value types; interior mutability (`Cell`, `RefCell`, `Mutex`, atomics), closures, `dyn` trait objects and raw pointers are rejected, because a memoized view could read them without its key seeing the change", + note = "large app data goes in `Tracked`, which keys by revision; a callback is a `Stateless` fn item or capture-free closure; a foreign plain type takes `#[memo_props(hash = \"why\")]`" +)] +pub trait MemoProps { + /// Feeds every input the view reads into `key`. + fn key(&self, key: &mut MemoKey); +} + +/// A 128-bit hash of a memoized view's props (SipHash-1-3 with a 128-bit output, a fixed key). A collision has a chance +/// of about 2⁻¹²⁸ per compare. A [`Stateless`] callback feeds the 64 bits its `TypeId` hashes, so two callbacks key +/// apart unless those collide. +#[derive(Clone, Debug, Default)] +pub struct MemoKey { + hasher: SipHasher13, + bytes: usize, +} + +impl MemoKey { + /// An empty key. + pub fn new() -> MemoKey { + MemoKey::default() + } + + /// The key of `props`. + pub fn of(props: &P) -> u128 { + let mut key = MemoKey::new(); + props.key(&mut key); + key.finish() + } + + /// Feeds `bytes`. + pub fn write(&mut self, bytes: &[u8]) { + self.hasher.write(bytes); + self.bytes += bytes.len(); + } + + /// Feeds a length or an enum variant's index. + pub fn write_u32(&mut self, value: u32) { + self.write(&value.to_le_bytes()); + } + + /// How many bytes fed the key: the view that takes the key adds them to the pass's key-byte count. + pub fn bytes(&self) -> usize { + self.bytes + } + + /// The key of everything fed so far. + pub fn finish(&self) -> u128 { + self.hasher.finish128().as_u128() + } + + /// Feeds `value` through its `Hash`: for a foreign plain type whose `Hash` is derived over every field (this + /// crate's implementations, and `#[memo_props(hash = "..")]` fields). `Sync` keeps out raw pointers, `NonNull`, + /// `Cell` and `RefCell`. + #[doc(hidden)] + pub fn feed_hash(&mut self, value: &T) { + value.hash(&mut Feed(self)); + } + + fn write_len(&mut self, len: usize) { + self.write(&(len as u64).to_le_bytes()); + } +} + +/// `Hasher` over a key, for [`MemoKey::feed_hash`]. +struct Feed<'k>(&'k mut MemoKey); + +impl Hasher for Feed<'_> { + fn finish(&self) -> u64 { + // Never read: the key finishes itself. + 0 + } + + fn write(&mut self, bytes: &[u8]) { + self.0.write(bytes); + } +} + +macro_rules! bytes { + ($($t:ty),* $(,)?) => { + $(impl MemoProps for $t { + fn key(&self, key: &mut MemoKey) { + key.write(&self.to_le_bytes()); + } + })* + }; +} + +bytes!(u8, u16, u32, u64, u128, usize, i8, i16, i32, i64, i128, isize); + +impl MemoProps for bool { + fn key(&self, key: &mut MemoKey) { + key.write(&[u8::from(*self)]); + } +} + +impl MemoProps for char { + fn key(&self, key: &mut MemoKey) { + key.write_u32(u32::from(*self)); + } +} + +impl MemoProps for f32 { + fn key(&self, key: &mut MemoKey) { + key.write(&self.to_bits().to_le_bytes()); + } +} + +impl MemoProps for f64 { + fn key(&self, key: &mut MemoKey) { + key.write(&self.to_bits().to_le_bytes()); + } +} + +impl MemoProps for () { + fn key(&self, _: &mut MemoKey) {} +} + +impl MemoProps for PhantomData { + fn key(&self, _: &mut MemoKey) {} +} + +impl MemoProps for str { + fn key(&self, key: &mut MemoKey) { + // The length first, so ("ab", "") and ("a", "b") differ. + key.write_len(self.len()); + key.write(self.as_bytes()); + } +} + +impl MemoProps for String { + fn key(&self, key: &mut MemoKey) { + self.as_str().key(key); + } +} + +impl MemoProps for Cow<'_, B> { + fn key(&self, key: &mut MemoKey) { + (**self).key(key); + } +} + +impl MemoProps for &T { + fn key(&self, key: &mut MemoKey) { + (**self).key(key); + } +} + +impl MemoProps for Box { + fn key(&self, key: &mut MemoKey) { + (**self).key(key); + } +} + +/// By walking the value, as `Arc`: a large shared model goes in `Tracked`, which keys by revision. +impl MemoProps for Rc { + fn key(&self, key: &mut MemoKey) { + (**self).key(key); + } +} + +/// By walking the value: a large shared model goes in `Tracked`, which keys by revision. +impl MemoProps for Arc { + fn key(&self, key: &mut MemoKey) { + (**self).key(key); + } +} + +impl MemoProps for Option { + fn key(&self, key: &mut MemoKey) { + match self { + None => key.write(&[0]), + Some(value) => { + key.write(&[1]); + value.key(key); + } + } + } +} + +impl MemoProps for Result { + fn key(&self, key: &mut MemoKey) { + match self { + Ok(value) => { + key.write(&[0]); + value.key(key); + } + Err(error) => { + key.write(&[1]); + error.key(key); + } + } + } +} + +impl MemoProps for Range { + fn key(&self, key: &mut MemoKey) { + let Range { start, end } = self; + start.key(key); + end.key(key); + } +} + +impl MemoProps for RangeInclusive { + fn key(&self, key: &mut MemoKey) { + self.start().key(key); + self.end().key(key); + // An iterated-out range is empty whatever its ends. + self.is_empty().key(key); + } +} + +impl MemoProps for Duration { + fn key(&self, key: &mut MemoKey) { + (self.as_secs(), self.subsec_nanos()).key(key); + } +} + +impl MemoProps for Ordering { + fn key(&self, key: &mut MemoKey) { + (*self as i8).key(key); + } +} + +macro_rules! non_zero { + ($($t:ty),* $(,)?) => { + $(impl MemoProps for $t { + fn key(&self, key: &mut MemoKey) { + self.get().key(key); + } + })* + }; +} + +non_zero!( + NonZeroU8, + NonZeroU16, + NonZeroU32, + NonZeroU64, + NonZeroU128, + NonZeroUsize, + NonZeroI8, + NonZeroI16, + NonZeroI32, + NonZeroI64, + NonZeroI128, + NonZeroIsize, +); + +/// Its bytes as the platform encodes them, length first. +impl MemoProps for OsStr { + fn key(&self, key: &mut MemoKey) { + let bytes = self.as_encoded_bytes(); + key.write_len(bytes.len()); + key.write(bytes); + } +} + +impl MemoProps for OsString { + fn key(&self, key: &mut MemoKey) { + self.as_os_str().key(key); + } +} + +impl MemoProps for Path { + fn key(&self, key: &mut MemoKey) { + self.as_os_str().key(key); + } +} + +impl MemoProps for PathBuf { + fn key(&self, key: &mut MemoKey) { + self.as_os_str().key(key); + } +} + +impl MemoProps for [T] { + fn key(&self, key: &mut MemoKey) { + key.write_len(self.len()); + for value in self { + value.key(key); + } + } +} + +impl MemoProps for [T; N] { + fn key(&self, key: &mut MemoKey) { + self.as_slice().key(key); + } +} + +impl MemoProps for Vec { + fn key(&self, key: &mut MemoKey) { + self.as_slice().key(key); + } +} + +impl MemoProps for BTreeMap { + fn key(&self, key: &mut MemoKey) { + key.write_len(self.len()); + for (k, v) in self { + k.key(key); + v.key(key); + } + } +} + +impl MemoProps for BTreeSet { + fn key(&self, key: &mut MemoKey) { + key.write_len(self.len()); + for value in self { + value.key(key); + } + } +} + +macro_rules! tuples { + ($(($($n:ident $i:tt),+)),* $(,)?) => { + $(impl<$($n: MemoProps),+> MemoProps for ($($n,)+) { + fn key(&self, key: &mut MemoKey) { + $(self.$i.key(key);)+ + } + })* + }; +} + +tuples!( + (A 0), + (A 0, B 1), + (A 0, B 1, C 2), + (A 0, B 1, C 2, D 3), + (A 0, B 1, C 2, D 3, E 4), + (A 0, B 1, C 2, D 3, E 4, F 5), + (A 0, B 1, C 2, D 3, E 4, F 5, G 6), + (A 0, B 1, C 2, D 3, E 4, F 5, G 6, H 7), +); + +impl MemoProps for Revision { + fn key(&self, key: &mut MemoKey) { + let Revision { source, count } = *self; + (source, count).key(key); + } +} + +/// By revision: equal revisions mean equal data. +impl MemoProps for Tracked { + fn key(&self, key: &mut MemoKey) { + self.revision().key(key); + } +} + +/// A callback in props: a fn item or a capture-free closure, which is zero-sized, so its type alone says what it +/// does, and its `TypeId` keys it. A capturing closure is not zero-sized and fails to build where `Stateless::new` is +/// called (not at `cargo check`: the assertion is evaluated when the call is compiled): +/// +/// ```compile_fail,E0080 +/// # extern crate craft_ui_contract as craft_ui; +/// let n = 3; +/// let _ = craft_ui::contract::Stateless::new(move || n); +/// ``` +/// +/// ``` +/// # extern crate craft_ui_contract as craft_ui; +/// use craft_ui::contract::{MemoKey, Stateless}; +/// let three = Stateless::new(|| 3); +/// assert_eq!(three.get()(), 3); +/// assert_ne!(MemoKey::of(&three), MemoKey::of(&Stateless::new(|| 3))); +/// ``` +#[derive(Clone, Copy)] +pub struct Stateless(F); + +impl Stateless { + /// `f` as a prop; `f` must capture nothing. + pub const fn new(f: F) -> Stateless { + const { assert!(size_of::() == 0, "a Stateless callback captures nothing: pass a fn item or a capture-free closure") }; + Stateless(f) + } + + /// The callback. + pub fn get(&self) -> F { + self.0 + } +} + +impl std::fmt::Debug for Stateless { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(std::any::type_name::()) + } +} + +impl MemoProps for Stateless { + fn key(&self, key: &mut MemoKey) { + key.feed_hash(&TypeId::of::()); + } +} + +// The framework's value types and the foreign plain types they hold. Structs are destructured without `..`, so a new +// field fails to build here until it feeds the key. Types this crate cannot destructure (`#[non_exhaustive]` types of +// other crates, private fields) feed their `Hash`, which each derives over every field. + +impl MemoProps for crate::runtime::env::Label { + fn key(&self, key: &mut MemoKey) { + use crate::runtime::env::Label; + // `Static` and `Shared` of the same text show the same. + match self { + Label::Empty => key.write_u32(0), + Label::Static(text) => { + key.write_u32(1); + text.key(key); + } + Label::Shared(text) => { + key.write_u32(1); + text.key(key); + } + Label::Word(word) => { + key.write_u32(2); + MemoProps::key(word, key); + } + } + } +} + +/// Derived `Hash` (`#[non_exhaustive]`). +impl MemoProps for craft_i18n::Word { + fn key(&self, key: &mut MemoKey) { + key.feed_hash(self); + } +} + +impl MemoProps for craft_keymap::CommandRef { + fn key(&self, key: &mut MemoKey) { + let craft_keymap::CommandRef { id, params } = self; + id.key(key); + params.key(key); + } +} + +/// Every value in order; an object's entries in the map's order. +impl MemoProps for serde_json::Value { + fn key(&self, key: &mut MemoKey) { + use serde_json::Value; + match self { + Value::Null => key.write_u32(0), + Value::Bool(value) => { + key.write_u32(1); + value.key(key); + } + Value::Number(number) => { + key.write_u32(2); + // A number is exactly one of these; its text keys it whole. + if let Some(value) = number.as_u64() { + key.write_u32(0); + value.key(key); + } else if let Some(value) = number.as_i64() { + key.write_u32(1); + value.key(key); + } else { + key.write_u32(2); + number.to_string().key(key); + } + } + Value::String(text) => { + key.write_u32(3); + text.key(key); + } + Value::Array(values) => { + key.write_u32(4); + values.key(key); + } + Value::Object(map) => { + key.write_u32(5); + key.write_len(map.len()); + for (name, value) in map { + name.key(key); + value.key(key); + } + } + } + } +} + +impl MemoProps for craft_keymap::Mods { + fn key(&self, key: &mut MemoKey) { + let craft_keymap::Mods { cmd, ctrl, alt, shift } = *self; + (cmd, ctrl, alt, shift).key(key); + } +} + +/// Derived `Hash` (`#[non_exhaustive]`). +impl MemoProps for craft_keymap::Key { + fn key(&self, key: &mut MemoKey) { + key.feed_hash(self); + } +} + +impl MemoProps for craft_keymap::Chord { + fn key(&self, key: &mut MemoKey) { + let craft_keymap::Chord { mods, key: pressed } = *self; + mods.key(key); + pressed.key(key); + } +} + +impl MemoProps for craft_theme::Srgba { + fn key(&self, key: &mut MemoKey) { + let craft_theme::Srgba { r, g, b, a } = *self; + (r, g, b, a).key(key); + } +} + +/// Derived `Hash` (`#[non_exhaustive]`). +impl MemoProps for craft_theme::variant::Tone { + fn key(&self, key: &mut MemoKey) { + key.feed_hash(self); + } +} + +impl MemoProps for craft_behavior::IconId { + fn key(&self, key: &mut MemoKey) { + // The name is the whole id. + self.name().key(key); + } +} + +/// Derived `Hash` (`#[non_exhaustive]`). +impl MemoProps for craft_behavior::fit::FitKeep { + fn key(&self, key: &mut MemoKey) { + key.feed_hash(self); + } +} + +/// Derived `Hash` (`#[non_exhaustive]`). +impl MemoProps for craft_host::target::WindowKind { + fn key(&self, key: &mut MemoKey) { + key.feed_hash(self); + } +} + +/// Derived `Hash` (an opaque hash value). +impl MemoProps for egui::Id { + fn key(&self, key: &mut MemoKey) { + key.feed_hash(self); + } +} + +impl MemoProps for egui::Vec2 { + fn key(&self, key: &mut MemoKey) { + let egui::Vec2 { x, y } = *self; + (x, y).key(key); + } +} + +impl MemoProps for egui::Pos2 { + fn key(&self, key: &mut MemoKey) { + let egui::Pos2 { x, y } = *self; + (x, y).key(key); + } +} + +impl MemoProps for egui::Rect { + fn key(&self, key: &mut MemoKey) { + let egui::Rect { min, max } = *self; + (min, max).key(key); + } +} + +impl MemoProps for egui::Color32 { + fn key(&self, key: &mut MemoKey) { + key.write(&self.to_array()); + } +} diff --git a/crates/ui-contract/src/contract/mod.rs b/crates/ui-contract/src/contract/mod.rs index ed42534f6..3b1a33cac 100644 --- a/crates/ui-contract/src/contract/mod.rs +++ b/crates/ui-contract/src/contract/mod.rs @@ -20,6 +20,7 @@ mod level; #[cfg(feature = "testing")] mod level_table; mod looks; +mod memo; mod mount; pub mod overlay; mod pages; @@ -92,6 +93,7 @@ pub use lazy::Lazy; #[cfg(feature = "testing")] pub use level::{Catalog, CatalogEntry, Level, StoryLayout, Surface, catalog, stale_table_rows, story_title}; pub use looks::Looks; +pub use memo::{MemoKey, MemoProps, Stateless}; pub use overlay::{Overlay, OverlayUi, Overlays, Popup, PopupHandle, SizeLimits, Trigger}; pub use pages::Pages; pub use paint_ui::PaintUi; diff --git a/crates/ui-contract/src/contract/overlay/place.rs b/crates/ui-contract/src/contract/overlay/place.rs index ac085d4ec..a0898aad6 100644 --- a/crates/ui-contract/src/contract/overlay/place.rs +++ b/crates/ui-contract/src/contract/overlay/place.rs @@ -164,7 +164,7 @@ impl ResizeEdges { /// producing inverted rects. A maximum constrains a pane when its sibling can take the remainder. A tab group takes /// the largest minimum and the largest maximum of its panels, so a panel without a maximum lifts the maximum of the /// panels it joins. -#[derive(Clone, Copy, Debug, Default, PartialEq)] +#[derive(Clone, Copy, Debug, Default, PartialEq, crate::contract::MemoProps)] pub struct SizeLimits { /// Smallest size. pub min: Vec2, diff --git a/crates/ui-contract/src/primitives/icon.rs b/crates/ui-contract/src/primitives/icon.rs index 36d9a1b18..e11bb8b2e 100644 --- a/crates/ui-contract/src/primitives/icon.rs +++ b/crates/ui-contract/src/primitives/icon.rs @@ -12,7 +12,7 @@ use egui::{Color32, Painter, Rect, pos2, vec2}; pub use super::svg_set::IconSet; /// Whether a directional icon flips under right-to-left. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Default, crate::contract::MemoProps)] #[non_exhaustive] pub enum Mirror { /// Flips a directional icon under right-to-left. diff --git a/crates/ui-contract/src/style/key.rs b/crates/ui-contract/src/style/key.rs index 603da650d..dfc0e9429 100644 --- a/crates/ui-contract/src/style/key.rs +++ b/crates/ui-contract/src/style/key.rs @@ -11,7 +11,7 @@ use std::hash::{Hash, Hasher}; pub trait StyleKey: Copy + Eq + Hash + Send + Sync + 'static {} /// The text and icon colour that reads on a surface, resolved at step 12. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Default)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Default, crate::contract::MemoProps)] #[non_exhaustive] pub enum Ink { /// On panels, raised and sunken surfaces: the normal text colour. diff --git a/crates/ui-contract/src/style/look.rs b/crates/ui-contract/src/style/look.rs index 0bf3dfe9c..f0483fa00 100644 --- a/crates/ui-contract/src/style/look.rs +++ b/crates/ui-contract/src/style/look.rs @@ -7,7 +7,7 @@ use egui::{Color32, CornerRadius, Stroke}; /// A colour a style builder picked from tokens. `Draw` accepts only this or `DataColor`. It has no /// `From`: the one constructor is `StyleCx::color`. -#[derive(Clone, Copy, Debug, PartialEq)] +#[derive(Clone, Copy, Debug, PartialEq, crate::contract::MemoProps)] pub struct StyleColor(#[doc(hidden)] pub Color32); impl StyleColor { @@ -25,7 +25,7 @@ impl Mix for StyleColor { } /// A colour from data (a swatch, a layer label dot). -#[derive(Clone, Copy, Debug, PartialEq)] +#[derive(Clone, Copy, Debug, PartialEq, crate::contract::MemoProps)] pub struct DataColor(#[doc(hidden)] pub Color32); impl DataColor { diff --git a/crates/ui-contract/tests/it/contract/memo_key.rs b/crates/ui-contract/tests/it/contract/memo_key.rs new file mode 100644 index 000000000..f4fb8f3fd --- /dev/null +++ b/crates/ui-contract/tests/it/contract/memo_key.rs @@ -0,0 +1,133 @@ +//! Memo keys: equal props key alike, and every input feeds the key. + +use craft_keymap::CommandRef; +use craft_ui::contract::{MemoKey, MemoProps, Stateless, Tracked}; +use craft_ui::runtime::env::Label; +use craft_ui::testing::trial; + +#[derive(Clone, MemoProps)] +struct Inner { + size: f32, + names: Vec, +} + +#[derive(Clone, MemoProps)] +struct Pair(u8, u8); + +#[derive(Clone, MemoProps)] +enum Mode { + Off, + Count(u32), + Range { from: u32, to: u32 }, +} + +#[derive(Clone, MemoProps)] +struct Props<'a, #[memo_props(stateless)] F> { + title: &'a str, + rest: &'a str, + shown: Option, + inner: Inner, + pair: Pair, + mode: Mode, + choice: Option, + grid: Vec>, + key: u32, + label: Label, + command: CommandRef, + model: &'a Tracked>, + path: std::path::PathBuf, + #[memo_props(hash = "four bytes; the derived Hash feeds them all")] + address: std::net::Ipv4Addr, + english: Stateless, +} + +fn english() -> &'static str { + "English" +} + +fn other() -> &'static str { + "Other" +} + +fn props<'a, F>(model: &'a Tracked>, english: Stateless) -> Props<'a, F> { + Props { + title: "ab", + rest: "", + shown: None, + inner: Inner { size: 1.0, names: vec!["x".to_owned()] }, + pair: Pair(1, 2), + mode: Mode::Count(3), + choice: Some(Mode::Off), + grid: vec![vec![1, 2], vec![3]], + key: 7, + label: Label::Static("Open"), + command: CommandRef::with_params("file.open", serde_json::json!({ "recent": 1 })), + model, + path: "a/b".into(), + address: std::net::Ipv4Addr::new(10, 0, 0, 1), + english, + } +} + +fn base(model: &Tracked>) -> Props<'_, impl Copy + 'static> { + props(model, Stateless::new(english)) +} + +/// Props built twice key alike; changing any one input, a nested field and an enum variant or its field included, gives +/// a key no other change gives. +#[trial] +fn equal_props_give_equal_keys_and_any_change_gives_a_new_key() { + let model = Tracked::new(vec!["a".to_owned()]); + let start = MemoKey::of(&base(&model)); + assert_eq!(MemoKey::of(&base(&model)), start, "equal props key alike"); + assert_eq!(MemoKey::of(&base(&model).clone()), start, "a clone keys alike"); + let mut shared = base(&model); + shared.label = Label::Shared("Open".into()); + assert_eq!(MemoKey::of(&shared), start, "a label keys by its text"); + + let mut keys = vec![start, MemoKey::of(&props(&model, Stateless::new(other)))]; + let mut changed = |change: &dyn Fn(&mut Props<'_, _>)| { + let mut props = base(&model); + change(&mut props); + keys.push(MemoKey::of(&props)); + }; + changed(&|props| props.title = "abc"); + changed(&|props| (props.title, props.rest) = ("a", "b")); + changed(&|props| props.shown = Some(0)); + changed(&|props| props.inner.size = 2.0); + changed(&|props| props.inner.names[0].push('y')); + changed(&|props| props.inner.names.push(String::new())); + changed(&|props| props.pair = Pair(2, 1)); + changed(&|props| props.mode = Mode::Count(4)); + changed(&|props| props.mode = Mode::Off); + changed(&|props| props.mode = Mode::Range { from: 3, to: 0 }); + changed(&|props| props.label = Label::Static("Close")); + changed(&|props| props.command = CommandRef::with_params("file.open", serde_json::json!({ "recent": 2 }))); + changed(&|props| props.command = CommandRef::new("file.open")); + changed(&|props| props.path = "a/c".into()); + changed(&|props| props.choice = None); + changed(&|props| props.choice = Some(Mode::Count(0))); + changed(&|props| props.choice = Some(Mode::Range { from: 0, to: 0 })); + changed(&|props| props.grid = vec![vec![1], vec![2, 3]]); + changed(&|props| props.grid = vec![vec![1, 2, 3]]); + changed(&|props| props.key = 8); + changed(&|props| props.address = std::net::Ipv4Addr::new(10, 0, 0, 2)); + + let mut written = model.clone(); + let cloned = MemoKey::of(&base(&written)); + written.push("b".to_owned()); + keys.extend([cloned, MemoKey::of(&base(&written))]); + + let mut distinct = keys.clone(); + distinct.sort_unstable(); + distinct.dedup(); + assert_eq!(distinct.len(), keys.len(), "every change gives its own key: {keys:x?}"); + + // Props key by their values only: two empty props types key alike. The memoized view's own key adds the props + // type's `TypeId`. + #[derive(MemoProps)] + struct Empty; + #[derive(MemoProps)] + struct Nothing {} + assert_eq!(MemoKey::of(&Empty), MemoKey::of(&Nothing {})); +} diff --git a/crates/ui-contract/tests/it/contract/mod.rs b/crates/ui-contract/tests/it/contract/mod.rs index b85c87339..3c39bfedc 100644 --- a/crates/ui-contract/tests/it/contract/mod.rs +++ b/crates/ui-contract/tests/it/contract/mod.rs @@ -3,6 +3,7 @@ mod fixes; mod gesture; mod hit_order; +mod memo_key; mod pages; mod pointer; mod style; diff --git a/crates/ui-macros/src/lib.rs b/crates/ui-macros/src/lib.rs index 05958548b..7db0607d2 100644 --- a/crates/ui-macros/src/lib.rs +++ b/crates/ui-macros/src/lib.rs @@ -1,10 +1,11 @@ -//! Macros of craft-ui: `#[derive(Component, Pattern, Props, ComponentStyle, TokenGroup, CommandSet, EnvValue, PlainData)]`, +//! Macros of craft-ui: `#[derive(Component, Pattern, Props, ComponentStyle, TokenGroup, CommandSet, EnvValue, PlainData, MemoProps)]`, //! `words!`, `#[story]`, `#[craft_ui::testing::trial]` and `register_contract!`. #![warn(missing_docs)] mod command_set; mod component; mod env; +mod memo; mod pattern; mod plain; mod props; @@ -93,6 +94,20 @@ pub fn derive_plain_data(input: TokenStream) -> TokenStream { expanded(plain::derive(input.into())) } +/// Writes `MemoProps`: every field feeds the memo key, in order (an enum's variant index first), and every field's type +/// must implement `MemoProps`, so a field holding interior mutability, a closure, a trait object or a raw pointer is a +/// compile error at that field. Works on structs, tuple structs and enums. A field of a foreign plain type without an +/// implementation carries `#[memo_props(hash = "why the type is plain")]`: it feeds the key through its `Hash`, and its +/// type must be `Hash + Sync` (which keeps out raw pointers, `NonNull`, `Cell` and `RefCell`), with a `Hash` that covers +/// everything the view shows and is prefix-free (two different values never feed bytes of which one starts the +/// other); the reason is required. A type parameter is bound by `MemoProps`, except one marked +/// `#[memo_props(stateless)]`: the type of a callback held as `Stateless`, which no fn item or closure implements +/// `MemoProps` for, is bound by `'static` only (`struct Bar<#[memo_props(stateless)] E> { english: Stateless }`). +#[proc_macro_derive(MemoProps, attributes(memo_props))] +pub fn derive_memo_props(input: TokenStream) -> TokenStream { + expanded(memo::derive(input.into())) +} + /// Writes `ComponentStyle` from `#[style(surface)]`, `#[style(focus)]` and `#[style(metrics)]` fields (one each), /// any number of `#[style(text)]` (`TextLook`) and `#[style(icon)]` (`IconLook`) fields, and /// `#[style(variants = [..])]` on the type. diff --git a/crates/ui-macros/src/memo.rs b/crates/ui-macros/src/memo.rs new file mode 100644 index 000000000..2e7e3c859 --- /dev/null +++ b/crates/ui-macros/src/memo.rs @@ -0,0 +1,94 @@ +//! `#[derive(MemoProps)]`: every field feeds the key, in order, and every field must implement `MemoProps`. An enum +//! feeds its variant's index before the variant's fields. +//! +//! The bounds and the escape come from the shared field check ([`plain`](crate::plain)). Its check item is left out: +//! the key body already uses every field through `MemoProps` (or `Hash`, for an escaped field), at the field's binding, +//! so each rejected field gives one error that names it. + +use crate::plain::{Escape, FieldChecks, ParamEscape, escaped, field_checks}; +use crate::util::ui_crate; +use proc_macro2::TokenStream; +use quote::{format_ident, quote}; +use syn::spanned::Spanned; +use syn::{Data, DeriveInput, Fields}; + +/// The escape for a foreign plain type: the field feeds the key through its `Hash`. +const ESCAPE: Escape = Escape { attr: "memo_props", keyword: "hash" }; + +/// The escape for a callback's type parameter (`Stateless`): bound by what `Stateless: MemoProps` needs. +fn stateless() -> ParamEscape { + ParamEscape { attr: "memo_props", keyword: "stateless", bound: quote!('static) } +} + +/// The pattern binding every field of `fields` to a generated name (`{ a: __f0, b: __f1 }`, `(__f0, __f1)` or +/// nothing), so no field shadows the `key` parameter, and the statements feeding each. +fn feed(fields: &Fields, k: &TokenStream) -> syn::Result<(TokenStream, Vec)> { + // Spanned at the field's name, or a tuple field's type, so an error points at the field. + let names: Vec = fields + .iter() + .enumerate() + .map(|(at, field)| format_ident!("__f{at}", span = field.ident.as_ref().map_or_else(|| field.ty.span(), syn::Ident::span))) + .collect(); + let pattern = match fields { + Fields::Named(named) => { + let fields = named.named.iter().filter_map(|field| field.ident.as_ref()); + quote!({ #(#fields: #names),* }) + } + Fields::Unnamed(_) => quote!(( #(#names),* )), + Fields::Unit => quote!(), + }; + let mut statements = Vec::new(); + for (field, name) in fields.iter().zip(&names) { + statements.push(if escaped(field, &ESCAPE)? { quote!(key.feed_hash(#name);) } else { quote!(#k::contract::MemoProps::key(#name, key);) }); + } + Ok((pattern, statements)) +} + +pub(crate) fn derive(input: TokenStream) -> syn::Result { + let input: DeriveInput = syn::parse2(input)?; + let k = ui_crate(); + let trait_path = quote!(#k::contract::MemoProps); + let FieldChecks { generics, .. } = field_checks(&input, &trait_path, Some(&ESCAPE), Some(&stateless()))?; + let body = match &input.data { + Data::Struct(data) => { + let (pattern, statements) = feed(&data.fields, &k)?; + quote! { + let Self #pattern = self; + #(#statements)* + } + } + Data::Enum(data) => { + let mut arms = Vec::new(); + for (at, variant) in data.variants.iter().enumerate() { + let name = &variant.ident; + let (pattern, statements) = feed(&variant.fields, &k)?; + let at = u32::try_from(at).map_err(|_| syn::Error::new_spanned(name, "too many variants"))?; + arms.push(quote! { + Self::#name #pattern => { + key.write_u32(#at); + #(#statements)* + } + }); + } + quote! { + match self { + #(#arms)* + } + } + } + // `field_checks` rejects a union. + Data::Union(_) => quote!(), + }; + let ident = &input.ident; + let (impl_generics, _, where_clause) = generics.split_for_impl(); + let (_, type_generics, _) = input.generics.split_for_impl(); + Ok(quote! { + #[automatically_derived] + impl #impl_generics #trait_path for #ident #type_generics #where_clause { + #[allow(unused_variables)] + fn key(&self, key: &mut #k::contract::MemoKey) { + #body + } + } + }) +} diff --git a/crates/ui-macros/src/plain.rs b/crates/ui-macros/src/plain.rs index 1416ce0b2..1328b1415 100644 --- a/crates/ui-macros/src/plain.rs +++ b/crates/ui-macros/src/plain.rs @@ -39,23 +39,66 @@ pub(crate) struct Escape { pub(crate) keyword: &'static str, } +/// The escape a derive allows for one type parameter, `#[()]`: the parameter is bound by `bound` +/// instead of the derive's trait. +pub(crate) struct ParamEscape { + /// The attribute's name (`memo_props`). + pub(crate) attr: &'static str, + /// The one flag it takes (`stateless`). + pub(crate) keyword: &'static str, + /// What the parameter is bound by instead (`'static`). + pub(crate) bound: TokenStream, +} + /// Requires `trait_path` of every field of `input` (structs, tuple structs, enums; a union is an error). The impl /// bounds each type parameter by `trait_path`; every field is checked under those bounds by a generated /// `check::()` spanned at the field's type, so a rejected field (`Cell` included) is an error at the derive /// that names the field, and a recursive type (a node holding `Vec` or `Vec>`) does not make its impl /// require itself. A field type written with `Self` is checked as the type itself. A field carrying `escape` is not -/// checked. -pub(crate) fn field_checks(input: &DeriveInput, trait_path: &TokenStream, escape: Option<&Escape>) -> syn::Result { +/// checked. A type parameter carrying `param_escape` is bound by its `bound` instead of `trait_path`; its fields are +/// still checked under that bound. +pub(crate) fn field_checks( + input: &DeriveInput, + trait_path: &TokenStream, + escape: Option<&Escape>, + param_escape: Option<&ParamEscape>, +) -> syn::Result { let fields: Vec<&syn::Field> = match &input.data { Data::Struct(data) => data.fields.iter().collect(), Data::Enum(data) => data.variants.iter().flat_map(|variant| variant.fields.iter()).collect(), Data::Union(data) => return Err(syn::Error::new(data.union_token.span(), "a union cannot hold only plain data")), }; let mut generics = input.generics.clone(); - let params: Vec = input.generics.type_params().map(|param| param.ident.clone()).collect(); + if let Some(param_escape) = param_escape { + for param in &generics.params { + let attrs = match param { + syn::GenericParam::Type(_) => continue, + syn::GenericParam::Lifetime(param) => ¶m.attrs, + syn::GenericParam::Const(param) => ¶m.attrs, + }; + if let Some(attr) = attrs.iter().find(|attr| attr.path().is_ident(param_escape.attr)) { + let ParamEscape { attr: name, keyword, .. } = param_escape; + return Err(syn::Error::new_spanned(attr, format!("`#[{name}({keyword})]` marks a type parameter"))); + } + } + } + let mut bounds = Vec::new(); + for param in generics.type_params_mut() { + let escaped = match param_escape { + Some(param_escape) => param_escaped(param, param_escape)?, + None => false, + }; + // A derive's helper attributes are not attributes of the impl. + param.attrs.clear(); + let ident = ¶m.ident; + bounds.push(match param_escape { + Some(ParamEscape { bound, .. }) if escaped => quote!(#ident: #bound), + _ => quote!(#ident: #trait_path), + }); + } let where_clause = generics.make_where_clause(); - for param in ¶ms { - where_clause.predicates.push(syn::parse2(quote!(#param: #trait_path))?); + for bound in bounds { + where_clause.predicates.push(syn::parse2(bound)?); } let ident = &input.ident; let (_, type_generics, _) = input.generics.split_for_impl(); @@ -101,6 +144,21 @@ impl VisitMut for ReplaceSelf<'_> { } } +/// Whether `param` carries `#[()]`. Any other content of the attribute is an error. +fn param_escaped(param: &syn::TypeParam, escape: &ParamEscape) -> syn::Result { + let mut found = false; + for attr in param.attrs.iter().filter(|attr| attr.path().is_ident(escape.attr)) { + attr.parse_nested_meta(|meta| { + if !meta.path.is_ident(escape.keyword) { + return Err(meta.error(format!("expected `#[{}({})]`", escape.attr, escape.keyword))); + } + found = true; + Ok(()) + })?; + } + Ok(found) +} + /// Whether `field` carries `#[( = "reason")]`. Any other content of the attribute, or an empty /// reason, is an error. pub(crate) fn escaped(field: &syn::Field, escape: &Escape) -> syn::Result { @@ -144,7 +202,7 @@ pub(crate) fn derive(input: TokenStream) -> syn::Result { let input: DeriveInput = syn::parse2(input)?; let k = tracked_crate(); let trait_path = quote!(#k::PlainData); - let FieldChecks { generics, checks } = field_checks(&input, &trait_path, Some(&Escape { attr: "plain_data", keyword: "assume" }))?; + let FieldChecks { generics, checks } = field_checks(&input, &trait_path, Some(&Escape { attr: "plain_data", keyword: "assume" }), None)?; let ident = &input.ident; let (impl_generics, _, where_clause) = generics.split_for_impl(); let (_, type_generics, _) = input.generics.split_for_impl();