mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-26 03:17:43 +00:00
MemoProps: every_pass, covered_by and address derive attributes; the framework's own keys stay hand-written in ui-contract
The derive takes #[memo_props(every_pass = "why")] on a type (it keys in every pass and feeds no field), #[memo_props(covered_by = "<field>", reason = "why")] on a field another field of the same variant stands for (the named field must exist and feed the key) and #[memo_props(address = "why")] on a &'static field. Group, menu level, timeline and canvas contexts and GuideDrag key in every pass; CaptionIcons, Catalog and ModalRules name the field that covers the rest (ModalRules' allowlist entry goes); CardStory keys its registration by address. design-lint allows hand impls of framework keys in ui-contract (values.rs, icon.rs, memo_view.rs beside memo.rs) and lists the gallery's &mut state views and the two presets walks with their reasons. Doctests for each attribute.
This commit is contained in:
@@ -135,11 +135,22 @@ const NO_GLOBAL_STATE_PREFIXES: &[&str] = &[
|
||||
/// 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.
|
||||
// The trait's home crate: it implements `MemoProps` by hand for std and framework value types, and for the
|
||||
// framework's own keys the derive cannot write: a binding by its source's address, its check and the check's `fn`
|
||||
// (values.rs), an icon's glyph by the type of its `dyn Glyph` (icon.rs), and the write-only `Outbox` (memo_view.rs).
|
||||
("crates/ui-contract/src/contract/memo.rs", "MemoProps"),
|
||||
// Settled fact: `ModalRules` holds a closure the derive cannot take; it keys on its plain fields and the revision
|
||||
// the app moves with every rule change, which stands for the closure.
|
||||
("crates/menu/src/modal.rs", "MemoProps"),
|
||||
("crates/ui-contract/src/contract/values.rs", "MemoProps"),
|
||||
("crates/ui-contract/src/contract/memo_view.rs", "MemoProps"),
|
||||
("crates/ui-contract/src/primitives/icon.rs", "MemoProps"),
|
||||
// Settled fact: a card's view of a story's state keys by the story value's revision, whether the start is taken, the
|
||||
// dialog's flags and the reset count; the view of every shown story's state is one fixed-size digest of those keys.
|
||||
// Both are props held as `&mut`, which the derive does not take.
|
||||
("crates/ui-gallery/src/viewer/picks.rs", "MemoProps"),
|
||||
// Settled fact: the names of a preset group key by a walk over the group and its folders (`dyn EachName`), which
|
||||
// the derive cannot see through.
|
||||
("crates/ui-patterns/src/patterns/presets/model/library.rs", "MemoProps"),
|
||||
// Settled fact: a name check keys by its inputs and its `fn` behind `dyn NameChecker`, as `Bind::check_with` does.
|
||||
("crates/ui-patterns/src/patterns/presets/named.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"),
|
||||
|
||||
@@ -12,7 +12,7 @@ use std::fmt;
|
||||
use std::sync::Arc;
|
||||
|
||||
use craft_keymap::CommandRef;
|
||||
use craft_ui::contract::{MemoKey, MemoProps};
|
||||
use craft_ui::contract::MemoProps;
|
||||
|
||||
use crate::driver::Gate;
|
||||
use crate::model::{Builtin, Item};
|
||||
@@ -37,7 +37,7 @@ pub type PendingRule = Arc<dyn Fn(&CommandRef) -> bool + Send + Sync>;
|
||||
/// assert!(gate.allows_under(&rules, &"view.zoomIn".into()));
|
||||
/// assert!(!gate.allows_under(&rules, &"image.crop".into()));
|
||||
/// ```
|
||||
#[derive(Clone, Default)]
|
||||
#[derive(Clone, Default, MemoProps)]
|
||||
#[non_exhaustive]
|
||||
pub struct ModalRules {
|
||||
/// Commands that still run while [`Gate::modal`] is set (a dialog or prompt is open), by
|
||||
@@ -48,6 +48,7 @@ pub struct ModalRules {
|
||||
pub workspace: bool,
|
||||
/// A pending operation is open (an uncommitted crop): only the commands this returns true for
|
||||
/// run. `None`: no pending operation.
|
||||
#[memo_props(covered_by = "revision", reason = "the caller moves the revision with every rule change")]
|
||||
pub pending: Option<PendingRule>,
|
||||
/// The caller's count of rule changes. A rule holds a closure and cannot be compared, so the
|
||||
/// caller says when the rules changed; the menu skips the resync, and the runtime's command gate keeps its answers,
|
||||
@@ -88,18 +89,6 @@ impl ModalRules {
|
||||
}
|
||||
}
|
||||
|
||||
/// As props of the runtime's command gate: the plain fields and [`ModalRules::revision`], which stands for the
|
||||
/// [`ModalRules::pending`] closure. The derive cannot take the closure, and the revision is the caller's count of rule
|
||||
/// changes, so equal keys mean equal rules as long as the caller moves it with every change.
|
||||
impl MemoProps for ModalRules {
|
||||
fn key(&self, key: &mut MemoKey) {
|
||||
let ModalRules { in_dialogs, workspace, pending: _, revision } = self;
|
||||
in_dialogs.key(key);
|
||||
workspace.key(key);
|
||||
revision.key(key);
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Debug for ModalRules {
|
||||
// new: `PendingRule` is a closure; print whether one is set.
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
|
||||
@@ -127,16 +127,10 @@ impl TimeAxis {
|
||||
}
|
||||
|
||||
/// The env value that carries the axis of the innermost [`TimelineView`]; `None` outside one.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, craft_ui::contract::MemoProps)]
|
||||
#[memo_props(every_pass = "the axis the timeline rebuilds each pass from its view")]
|
||||
struct InTimeline(Option<TimeAxis>);
|
||||
|
||||
/// The axis the timeline rebuilds each pass from its view: a view under it runs in every pass.
|
||||
impl craft_ui::contract::MemoProps for InTimeline {
|
||||
fn key(&self, key: &mut craft_ui::contract::MemoKey) {
|
||||
key.changes_every_pass();
|
||||
}
|
||||
}
|
||||
|
||||
impl EnvValue for InTimeline {
|
||||
fn root() -> Self {
|
||||
InTimeline(None)
|
||||
|
||||
@@ -159,16 +159,10 @@ pub fn snap_tolerance(view: &CanvasView, mods: Mods, os: Platform, tool_reads_co
|
||||
(!snap_suspended(mods, os, tool_reads_control)).then(|| view.doc_len(SNAP_PX as f32))
|
||||
}
|
||||
|
||||
#[derive(Clone, PartialEq)]
|
||||
#[derive(Clone, PartialEq, crate::contract::MemoProps)]
|
||||
#[memo_props(every_pass = "a context the canvas rebuilds each pass")]
|
||||
struct InCanvasSnap(Option<Snap>);
|
||||
|
||||
/// A context the canvas rebuilds each pass: a view under it runs in every pass.
|
||||
impl crate::contract::MemoProps for InCanvasSnap {
|
||||
fn key(&self, key: &mut crate::contract::MemoKey) {
|
||||
key.changes_every_pass();
|
||||
}
|
||||
}
|
||||
|
||||
impl EnvValue for InCanvasSnap {
|
||||
fn root() -> Self {
|
||||
InCanvasSnap(None)
|
||||
|
||||
@@ -347,37 +347,21 @@ pub(crate) fn context_menu<C: Component>(cx: &mut Cx<'_, C>, part: impl Into<Par
|
||||
|
||||
/// The env value that carries the space of the innermost canvas; `None` outside a canvas and inside a canvas that
|
||||
/// has no view.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, crate::contract::MemoProps)]
|
||||
#[memo_props(every_pass = "a context the canvas rebuilds each pass")]
|
||||
struct InCanvas(Option<CanvasSpace>);
|
||||
|
||||
/// A context the canvas rebuilds each pass: a view under it runs in every pass.
|
||||
impl crate::contract::MemoProps for InCanvas {
|
||||
fn key(&self, key: &mut crate::contract::MemoKey) {
|
||||
key.changes_every_pass();
|
||||
}
|
||||
}
|
||||
|
||||
impl EnvValue for InCanvas {
|
||||
fn root() -> Self {
|
||||
InCanvas(None)
|
||||
}
|
||||
}
|
||||
|
||||
/// The env value that carries the guide a drag out of the canvas's rulers is placing in this pass.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
/// The env value that carries the guide a drag out of the canvas's rulers is placing in this pass: a view under the
|
||||
/// canvas runs in every pass of the drag (`GuideDrag` keys in every pass), and replays when no drag is placing one.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, crate::contract::MemoProps)]
|
||||
struct InRulerGuide(Option<super::GuideDrag>);
|
||||
|
||||
/// A guide a ruler drag places in this pass: a view under the canvas runs in every pass of the drag, and replays when no
|
||||
/// drag is placing one.
|
||||
impl crate::contract::MemoProps for InRulerGuide {
|
||||
fn key(&self, key: &mut crate::contract::MemoKey) {
|
||||
match self.0 {
|
||||
None => key.write_u32(0),
|
||||
Some(_) => key.changes_every_pass(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl EnvValue for InRulerGuide {
|
||||
fn root() -> Self {
|
||||
InRulerGuide(None)
|
||||
|
||||
@@ -388,16 +388,10 @@ fn keys_down(ctx: &Context, holds: &[Key]) -> Vec<Key> {
|
||||
}
|
||||
|
||||
/// The tool input a canvas publishes to its body.
|
||||
#[derive(Clone, PartialEq)]
|
||||
#[derive(Clone, PartialEq, crate::contract::MemoProps)]
|
||||
#[memo_props(every_pass = "a context the canvas rebuilds each pass")]
|
||||
struct InToolPass(Option<ToolPass>);
|
||||
|
||||
/// A context the canvas rebuilds each pass: a view under it runs in every pass.
|
||||
impl crate::contract::MemoProps for InToolPass {
|
||||
fn key(&self, key: &mut crate::contract::MemoKey) {
|
||||
key.changes_every_pass();
|
||||
}
|
||||
}
|
||||
|
||||
impl EnvValue for InToolPass {
|
||||
fn root() -> Self {
|
||||
InToolPass(None)
|
||||
|
||||
@@ -32,6 +32,8 @@ impl<M> Default for GroupState<M> {
|
||||
|
||||
/// A group form's handle, put into its body's env with `content_env`. Members and body code read it with
|
||||
/// `cx.env.get::<GroupHandle<..>>()`; a member outside any group gets the inert root handle.
|
||||
#[derive(crate::contract::MemoProps)]
|
||||
#[memo_props(every_pass = "a handle to group state its members write during the pass: a key cannot follow it")]
|
||||
pub struct GroupHandle<G: GroupKind> {
|
||||
state: Option<Arc<Mutex<GroupState<G::Member>>>>,
|
||||
kind: PhantomData<fn() -> G>,
|
||||
@@ -53,14 +55,6 @@ impl<G: GroupKind> PartialEq for GroupHandle<G> {
|
||||
}
|
||||
}
|
||||
|
||||
/// A handle to group state its members write during the pass: a key cannot follow it, so a view under a group runs in
|
||||
/// every pass.
|
||||
impl<G: GroupKind> crate::contract::MemoProps for GroupHandle<G> {
|
||||
fn key(&self, key: &mut crate::contract::MemoKey) {
|
||||
key.changes_every_pass();
|
||||
}
|
||||
}
|
||||
|
||||
impl<G: GroupKind> EnvValue for GroupHandle<G> {
|
||||
fn root() -> Self {
|
||||
GroupHandle { state: None, kind: PhantomData }
|
||||
|
||||
@@ -204,6 +204,102 @@
|
||||
//! }
|
||||
//! ```
|
||||
//!
|
||||
//! A field another field stands for feeds nothing: `#[memo_props(covered_by = "<field>", reason = "why")]`. The named
|
||||
//! field must be one of the same struct or variant that feeds the key itself, and the reason is required. A closure the
|
||||
//! caller's revision covers:
|
||||
//!
|
||||
//! ```
|
||||
//! # extern crate craft_ui_contract as craft_ui;
|
||||
//! use craft_ui::contract::{MemoKey, MemoProps};
|
||||
//! use std::sync::Arc;
|
||||
//! #[derive(MemoProps)]
|
||||
//! struct Rules {
|
||||
//! #[memo_props(covered_by = "revision", reason = "the caller moves the revision with every rule change")]
|
||||
//! allows: Arc<dyn Fn(&str) -> bool + Send + Sync>,
|
||||
//! revision: u64,
|
||||
//! }
|
||||
//! let rules = |revision, allows: fn(&str) -> bool| Rules { allows: Arc::new(allows), revision };
|
||||
//! assert_eq!(MemoKey::of(&rules(1, |_| true)), MemoKey::of(&rules(1, |_| false)));
|
||||
//! assert_ne!(MemoKey::of(&rules(1, |_| true)), MemoKey::of(&rules(2, |_| true)));
|
||||
//! ```
|
||||
//!
|
||||
//! ```compile_fail
|
||||
//! # extern crate craft_ui_contract as craft_ui;
|
||||
//! #[derive(craft_ui::contract::MemoProps)]
|
||||
//! struct Rules {
|
||||
//! #[memo_props(covered_by = "generation", reason = "no such field")]
|
||||
//! allows: std::sync::Arc<dyn Fn(&str) -> bool + Send + Sync>,
|
||||
//! revision: u64,
|
||||
//! }
|
||||
//! ```
|
||||
//!
|
||||
//! ```compile_fail
|
||||
//! # extern crate craft_ui_contract as craft_ui;
|
||||
//! #[derive(craft_ui::contract::MemoProps)]
|
||||
//! struct Rules {
|
||||
//! #[memo_props(covered_by = "revision")]
|
||||
//! allows: std::sync::Arc<dyn Fn(&str) -> bool + Send + Sync>,
|
||||
//! revision: u64,
|
||||
//! }
|
||||
//! ```
|
||||
//!
|
||||
//! A `&'static` reference to a static item feeds where it points: `#[memo_props(address = "why")]`. Any other field
|
||||
//! type is an error:
|
||||
//!
|
||||
//! ```
|
||||
//! # extern crate craft_ui_contract as craft_ui;
|
||||
//! use craft_ui::contract::{MemoKey, MemoProps};
|
||||
//! struct Registration(&'static str);
|
||||
//! // Equal registrations at two places: two items.
|
||||
//! static FIRST: Registration = Registration("Button");
|
||||
//! static SECOND: Registration = Registration("Button");
|
||||
//! #[derive(MemoProps)]
|
||||
//! struct Card {
|
||||
//! #[memo_props(address = "registrations are static items")]
|
||||
//! story: &'static Registration,
|
||||
//! }
|
||||
//! assert_eq!(MemoKey::of(&Card { story: &FIRST }), MemoKey::of(&Card { story: &FIRST }));
|
||||
//! assert_ne!(MemoKey::of(&Card { story: &FIRST }), MemoKey::of(&Card { story: &SECOND }));
|
||||
//! ```
|
||||
//!
|
||||
//! ```compile_fail
|
||||
//! # extern crate craft_ui_contract as craft_ui;
|
||||
//! #[derive(craft_ui::contract::MemoProps)]
|
||||
//! struct Card<'a> {
|
||||
//! #[memo_props(address = "a borrowed value")]
|
||||
//! story: &'a u32,
|
||||
//! }
|
||||
//! ```
|
||||
//!
|
||||
//! A handle to state written during the pass, or a context rebuilt each pass, is keyed in every pass:
|
||||
//! `#[memo_props(every_pass = "why")]` on the type. It feeds no field (a field attribute there is an error), and a view
|
||||
//! whose key holds it runs in every pass; outside a view's key it feeds nothing:
|
||||
//!
|
||||
//! ```
|
||||
//! # extern crate craft_ui_contract as craft_ui;
|
||||
//! use craft_ui::contract::{MemoKey, MemoProps};
|
||||
//! use std::sync::{Arc, Mutex};
|
||||
//! #[derive(MemoProps)]
|
||||
//! #[memo_props(every_pass = "its members write the shared state during the pass")]
|
||||
//! struct Handle(Arc<Mutex<Vec<u32>>>);
|
||||
//! let handle = Handle(Arc::default());
|
||||
//! assert_eq!(MemoKey::of(&handle), MemoKey::of(&handle));
|
||||
//! ```
|
||||
//!
|
||||
//! ```compile_fail
|
||||
//! # extern crate craft_ui_contract as craft_ui;
|
||||
//! #[derive(craft_ui::contract::MemoProps)]
|
||||
//! #[memo_props(every_pass = "")]
|
||||
//! struct Handle(std::sync::Arc<std::sync::Mutex<Vec<u32>>>);
|
||||
//! ```
|
||||
//!
|
||||
//! ```compile_fail
|
||||
//! # extern crate craft_ui_contract as craft_ui;
|
||||
//! #[derive(craft_ui::contract::MemoProps)]
|
||||
//! #[memo_props(every_pass = "rebuilt each pass")]
|
||||
//! struct Handle(#[memo_props(hash = "a number")] u32);
|
||||
//! ```
|
||||
//!
|
||||
//! Plain props derive, recursive types included:
|
||||
//!
|
||||
//! ```
|
||||
|
||||
@@ -60,25 +60,18 @@ pub struct Look {
|
||||
}
|
||||
|
||||
/// One story a card shows.
|
||||
#[derive(MemoProps)]
|
||||
#[non_exhaustive]
|
||||
pub struct CardStory<'a> {
|
||||
/// The index of the story in the catalog: the key of its state.
|
||||
pub index: usize,
|
||||
/// The story.
|
||||
#[memo_props(address = "registrations are static items")]
|
||||
pub story: &'static StoryRegistration,
|
||||
/// The story's caption.
|
||||
pub caption: &'a str,
|
||||
}
|
||||
|
||||
/// The story's index, its caption and which registration it is (an address: registrations are static items).
|
||||
impl MemoProps for CardStory<'_> {
|
||||
fn key(&self, key: &mut craft_ui::contract::MemoKey) {
|
||||
self.index.key(key);
|
||||
self.caption.key(key);
|
||||
(std::ptr::from_ref(self.story) as usize).key(key);
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> CardStory<'a> {
|
||||
/// The story at catalog index `index`, under `caption`.
|
||||
pub fn new(index: usize, story: &'static StoryRegistration, caption: &'a str) -> Self {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! What the viewer lists: every registered story, grouped by the component it shows.
|
||||
|
||||
use craft_ui::contract::{self, Level, MemoKey, MemoProps, Probe, Registration, Tracked};
|
||||
use craft_ui::contract::{self, Level, MemoProps, Probe, Registration, Tracked};
|
||||
use craft_ui::testing::{StoryRegistration, stories};
|
||||
use std::collections::HashMap;
|
||||
use std::sync::OnceLock;
|
||||
@@ -171,27 +171,25 @@ pub fn components(entries: &[Entry]) -> Vec<ComponentInfo> {
|
||||
|
||||
/// Every registered story, the components they show and what the registrations say about each type. Fixed once
|
||||
/// built: a memoized view that reads it keys on its source, never on its contents.
|
||||
#[derive(MemoProps)]
|
||||
#[non_exhaustive]
|
||||
pub struct Catalog {
|
||||
/// The stories, ordered by type then story name.
|
||||
#[memo_props(covered_by = "source", reason = "a catalog does not change once built")]
|
||||
pub entries: Vec<Entry>,
|
||||
/// The components of the stories.
|
||||
#[memo_props(covered_by = "source", reason = "a catalog does not change once built")]
|
||||
pub components: Vec<ComponentInfo>,
|
||||
/// The registration of each type.
|
||||
#[memo_props(covered_by = "source", reason = "a catalog does not change once built")]
|
||||
pub declared: HashMap<&'static str, Declared>,
|
||||
/// Each component's place in `components` and the catalog indices of its stories, in the order of its `stories`.
|
||||
#[memo_props(covered_by = "source", reason = "a catalog does not change once built")]
|
||||
by_type: HashMap<&'static str, (usize, Vec<usize>)>,
|
||||
/// A revision source unique to this catalog: what its readers' keys hold of it.
|
||||
source: Tracked<()>,
|
||||
}
|
||||
|
||||
/// By the catalog's source: a catalog does not change once built, so two catalogs with one source are one catalog.
|
||||
impl MemoProps for Catalog {
|
||||
fn key(&self, key: &mut MemoKey) {
|
||||
self.source.key(key);
|
||||
}
|
||||
}
|
||||
|
||||
impl Catalog {
|
||||
/// The catalog of the stories linked into the running binary.
|
||||
pub fn linked() -> Self {
|
||||
|
||||
@@ -100,9 +100,14 @@ pub fn derive_plain_data(input: TokenStream) -> TokenStream {
|
||||
/// 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<E>`, which no fn item or closure implements
|
||||
/// `MemoProps` for, is bound by `'static` only (`struct Bar<#[memo_props(stateless)] E> { english: Stateless<E> }`).
|
||||
/// other); the reason is required. A `&'static` reference to a static item (a registration) carries
|
||||
/// `#[memo_props(address = "why")]` and feeds where it points. A field another field of the same variant stands for (a
|
||||
/// closure a generation counter covers) carries `#[memo_props(covered_by = "<field>", reason = "why")]` and feeds
|
||||
/// nothing; the named field must exist and feed the key itself. A type parameter is bound by `MemoProps`, except one
|
||||
/// marked `#[memo_props(stateless)]`: the type of a callback held as `Stateless<E>`, which no fn item or closure
|
||||
/// implements `MemoProps` for, is bound by `'static` only (`struct Bar<#[memo_props(stateless)] E> { english:
|
||||
/// Stateless<E> }`). A type that is a handle to state written during the pass, or a context rebuilt each pass, carries
|
||||
/// `#[memo_props(every_pass = "why")]`: it feeds no field, and a view whose key holds it runs in every pass.
|
||||
#[proc_macro_derive(MemoProps, attributes(memo_props))]
|
||||
pub fn derive_memo_props(input: TokenStream) -> TokenStream {
|
||||
expanded(memo::derive(input.into()))
|
||||
|
||||
+171
-14
@@ -1,26 +1,130 @@
|
||||
//! `#[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 bounds and the escapes 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.
|
||||
//! so each rejected field gives one error that names it. A field that feeds by its address or that another field stands
|
||||
//! for is not checked: its key is written here.
|
||||
|
||||
use crate::plain::{Escape, FieldChecks, ParamEscape, escaped, field_checks};
|
||||
use crate::plain::{EscapeRule, FieldChecks, ParamEscape, 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};
|
||||
use syn::{Data, DeriveInput, Fields, LitStr};
|
||||
|
||||
/// The escape for a foreign plain type: the field feeds the key through its `Hash`. A type parameter only such fields
|
||||
/// name (a dock's panel type) is bound by what `MemoKey::feed_hash` needs.
|
||||
fn escape() -> Escape {
|
||||
Escape { attr: "memo_props", keyword: "hash", bound: Some(quote!(::core::hash::Hash + ::core::marker::Sync)) }
|
||||
const ATTR: &str = "memo_props";
|
||||
|
||||
/// How one field feeds the key.
|
||||
enum Feed {
|
||||
/// Through its `MemoProps`.
|
||||
Props,
|
||||
/// Through its `Hash`: `hash = "why the type is plain"`.
|
||||
Hash,
|
||||
/// By where it points: `address = "why"`, on a `&'static` reference to a static item.
|
||||
Address,
|
||||
/// Not at all: the named field of the same variant stands for it, `covered_by = "<field>", reason = "why"`.
|
||||
Covered(LitStr),
|
||||
}
|
||||
|
||||
/// A reason given as `key = "reason"`; empty is an error.
|
||||
fn reason(key: &str, value: &LitStr) -> syn::Result<()> {
|
||||
if value.value().trim().is_empty() {
|
||||
return Err(syn::Error::new(value.span(), format!("`{key}` needs a reason")));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// How `field` feeds the key, from its `#[memo_props(..)]`.
|
||||
fn feed_of(field: &syn::Field) -> syn::Result<Feed> {
|
||||
let mut feed = Feed::Props;
|
||||
let (mut covered, mut why): (Option<LitStr>, Option<LitStr>) = (None, None);
|
||||
for attr in field.attrs.iter().filter(|attr| attr.path().is_ident(ATTR)) {
|
||||
attr.parse_nested_meta(|meta| {
|
||||
let key = meta.path.get_ident().map(ToString::to_string).unwrap_or_default();
|
||||
let value: LitStr = meta.value()?.parse()?;
|
||||
let set = |feed: &mut Feed, to: Feed| {
|
||||
if !matches!(feed, Feed::Props) {
|
||||
return Err(meta.error("a field feeds the key one way: `hash`, `address` or `covered_by`"));
|
||||
}
|
||||
*feed = to;
|
||||
Ok(())
|
||||
};
|
||||
match key.as_str() {
|
||||
"hash" => {
|
||||
reason(&key, &value)?;
|
||||
set(&mut feed, Feed::Hash)
|
||||
}
|
||||
"address" => {
|
||||
reason(&key, &value)?;
|
||||
set(&mut feed, Feed::Address)
|
||||
}
|
||||
"covered_by" => {
|
||||
covered = Some(value.clone());
|
||||
set(&mut feed, Feed::Covered(value))
|
||||
}
|
||||
"reason" => {
|
||||
reason(&key, &value)?;
|
||||
why = Some(value);
|
||||
Ok(())
|
||||
}
|
||||
_ => Err(meta.error(format!(
|
||||
"expected `#[{ATTR}(hash = \"why\")]`, `#[{ATTR}(address = \"why\")]` or `#[{ATTR}(covered_by = \"<field>\", reason = \"why\")]`"
|
||||
))),
|
||||
}
|
||||
})?;
|
||||
}
|
||||
match (&covered, &why) {
|
||||
(Some(field), None) => return Err(syn::Error::new(field.span(), "`covered_by` needs a `reason`")),
|
||||
(None, Some(why)) => return Err(syn::Error::new(why.span(), "`reason` goes with `covered_by`")),
|
||||
_ => {}
|
||||
}
|
||||
if matches!(feed, Feed::Address) && !is_static_ref(&field.ty) {
|
||||
return Err(syn::Error::new(field.ty.span(), "`address` keys a `&'static` reference by where it points"));
|
||||
}
|
||||
Ok(feed)
|
||||
}
|
||||
|
||||
/// Whether `ty` is `&'static T`.
|
||||
fn is_static_ref(ty: &syn::Type) -> bool {
|
||||
matches!(ty, syn::Type::Reference(reference) if reference.mutability.is_none() && reference.lifetime.as_ref().is_some_and(|l| l.ident == "static"))
|
||||
}
|
||||
|
||||
/// The field escapes of `MemoProps`: `hash` binds a type parameter only such fields name by what `MemoKey::feed_hash`
|
||||
/// needs (a dock's panel type); `address` and `covered_by` fields are not checked and keep the trait's bound.
|
||||
struct MemoEscapes;
|
||||
|
||||
impl EscapeRule for MemoEscapes {
|
||||
fn escape(&self, field: &syn::Field) -> syn::Result<Option<Option<TokenStream>>> {
|
||||
Ok(match feed_of(field)? {
|
||||
Feed::Props => None,
|
||||
Feed::Hash => Some(Some(quote!(::core::hash::Hash + ::core::marker::Sync))),
|
||||
Feed::Address | Feed::Covered(_) => Some(None),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// The escape for a callback's type parameter (`Stateless<E>`): bound by what `Stateless<E>: MemoProps` needs.
|
||||
fn stateless() -> ParamEscape {
|
||||
ParamEscape { attr: "memo_props", keyword: "stateless", bound: quote!('static) }
|
||||
ParamEscape { attr: ATTR, keyword: "stateless", bound: quote!('static) }
|
||||
}
|
||||
|
||||
/// The reason of a type-level `#[memo_props(every_pass = "why")]`: the type is a handle to state written during the
|
||||
/// pass, or a context rebuilt each pass, which no key can follow.
|
||||
fn every_pass(input: &DeriveInput) -> syn::Result<Option<LitStr>> {
|
||||
let mut found = None;
|
||||
for attr in input.attrs.iter().filter(|attr| attr.path().is_ident(ATTR)) {
|
||||
attr.parse_nested_meta(|meta| {
|
||||
if !meta.path.is_ident("every_pass") {
|
||||
return Err(meta.error(format!("expected `#[{ATTR}(every_pass = \"why\")]` on the type")));
|
||||
}
|
||||
let value: LitStr = meta.value()?.parse()?;
|
||||
reason("every_pass", &value)?;
|
||||
found = Some(value);
|
||||
Ok(())
|
||||
})?;
|
||||
}
|
||||
Ok(found)
|
||||
}
|
||||
|
||||
/// The pattern binding every field of `fields` to a generated name (`{ a: __f0, b: __f1 }`, `(__f0, __f1)` or
|
||||
@@ -40,9 +144,34 @@ fn feed(fields: &Fields, k: &TokenStream) -> syn::Result<(TokenStream, Vec<Token
|
||||
Fields::Unnamed(_) => quote!(( #(#names),* )),
|
||||
Fields::Unit => quote!(),
|
||||
};
|
||||
// A field is named by its name, or a tuple field by its index.
|
||||
let label = |at: usize, field: &syn::Field| field.ident.as_ref().map_or_else(|| at.to_string(), ToString::to_string);
|
||||
let feeds: Vec<Feed> = fields.iter().map(feed_of).collect::<syn::Result<_>>()?;
|
||||
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);) });
|
||||
for (at, ((field, name), feed)) in fields.iter().zip(&names).zip(&feeds).enumerate() {
|
||||
statements.push(match feed {
|
||||
Feed::Props => quote!(#k::contract::MemoProps::key(#name, key);),
|
||||
Feed::Hash => quote!(key.feed_hash(#name);),
|
||||
Feed::Address => quote!(#k::contract::MemoProps::key(&::core::ptr::from_ref(*#name).cast::<()>().addr(), key);),
|
||||
Feed::Covered(by) => {
|
||||
let target = by.value();
|
||||
let standing = fields.iter().enumerate().position(|(other, field)| label(other, field) == target);
|
||||
match standing.map(|other| (other, &feeds[other])) {
|
||||
Some((other, _)) if other == at => return Err(syn::Error::new(by.span(), "a field cannot stand for itself")),
|
||||
Some((_, Feed::Covered(_))) => {
|
||||
return Err(syn::Error::new(
|
||||
by.span(),
|
||||
format!("`{target}` is covered by another field itself: name the field that feeds the key"),
|
||||
));
|
||||
}
|
||||
Some(_) => quote!(),
|
||||
None => {
|
||||
let what = field.ident.as_ref().map_or_else(|| "this field".to_owned(), |ident| format!("`{ident}`"));
|
||||
return Err(syn::Error::new(by.span(), format!("no field `{target}` stands for {what}")));
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
Ok((pattern, statements))
|
||||
}
|
||||
@@ -51,7 +180,27 @@ pub(crate) fn derive(input: TokenStream) -> syn::Result<TokenStream> {
|
||||
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 ident = &input.ident;
|
||||
let (_, type_generics, _) = input.generics.split_for_impl();
|
||||
if every_pass(&input)?.is_some() {
|
||||
if let Some(attr) = memo_field_attrs(&input).next() {
|
||||
return Err(syn::Error::new_spanned(attr, "a type keyed in every pass feeds no field"));
|
||||
}
|
||||
let mut generics = input.generics.clone();
|
||||
for param in generics.type_params_mut() {
|
||||
param.attrs.clear();
|
||||
}
|
||||
let (impl_generics, _, where_clause) = generics.split_for_impl();
|
||||
return Ok(quote! {
|
||||
#[automatically_derived]
|
||||
impl #impl_generics #trait_path for #ident #type_generics #where_clause {
|
||||
fn key(&self, key: &mut #k::contract::MemoKey) {
|
||||
key.changes_every_pass();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
let FieldChecks { generics, .. } = field_checks(&input, &trait_path, Some(&MemoEscapes), Some(&stateless()))?;
|
||||
let body = match &input.data {
|
||||
Data::Struct(data) => {
|
||||
let (pattern, statements) = feed(&data.fields, &k)?;
|
||||
@@ -82,9 +231,7 @@ pub(crate) fn derive(input: TokenStream) -> syn::Result<TokenStream> {
|
||||
// `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 {
|
||||
@@ -95,3 +242,13 @@ pub(crate) fn derive(input: TokenStream) -> syn::Result<TokenStream> {
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// The `#[memo_props(..)]` attributes of the fields of `input`.
|
||||
fn memo_field_attrs(input: &DeriveInput) -> impl Iterator<Item = &syn::Attribute> {
|
||||
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(_) => Vec::new(),
|
||||
};
|
||||
fields.into_iter().flat_map(|field| field.attrs.iter()).filter(|attr| attr.path().is_ident(ATTR))
|
||||
}
|
||||
|
||||
@@ -43,6 +43,19 @@ pub(crate) struct Escape {
|
||||
pub(crate) bound: Option<TokenStream>,
|
||||
}
|
||||
|
||||
/// Which fields a derive does not check, and what a type parameter that only those fields name is bound by.
|
||||
pub(crate) trait EscapeRule {
|
||||
/// `None` when `field` is checked; else `Some(bound)`: what a type parameter that only escaped fields name is bound
|
||||
/// by instead of the derive's trait (`None` keeps the trait).
|
||||
fn escape(&self, field: &syn::Field) -> syn::Result<Option<Option<TokenStream>>>;
|
||||
}
|
||||
|
||||
impl EscapeRule for Escape {
|
||||
fn escape(&self, field: &syn::Field) -> syn::Result<Option<Option<TokenStream>>> {
|
||||
Ok(escaped(field, self)?.then(|| self.bound.clone()))
|
||||
}
|
||||
}
|
||||
|
||||
/// The escape a derive allows for one type parameter, `#[<attr>(<keyword>)]`: the parameter is bound by `bound`
|
||||
/// instead of the derive's trait.
|
||||
pub(crate) struct ParamEscape {
|
||||
@@ -59,13 +72,13 @@ pub(crate) struct ParamEscape {
|
||||
/// `check::<Field>()` spanned at the field's type, so a rejected field (`Cell<T>` included) is an error at the derive
|
||||
/// that names the field, and a recursive type (a node holding `Vec<Self>` or `Vec<Node<T>>`) 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; a type parameter that only escaped fields name is bound by the escape's `bound`, when it has one. A type
|
||||
/// checked; a type parameter that only escaped fields name is bound by the escape's bound, when it has one. 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>,
|
||||
escape: Option<&dyn EscapeRule>,
|
||||
param_escape: Option<&ParamEscape>,
|
||||
) -> syn::Result<FieldChecks> {
|
||||
let fields: Vec<&syn::Field> = match &input.data {
|
||||
@@ -90,12 +103,20 @@ pub(crate) fn field_checks(
|
||||
// The type parameters each kind of field names: a parameter only escaped fields name is bound by the escape's
|
||||
// bound, when it has one.
|
||||
let (mut named, mut named_escaped) = (Named::default(), Named::default());
|
||||
// The bound of the escaped fields that name each parameter, in field order.
|
||||
let mut escaped_bounds: Vec<(syn::Ident, TokenStream)> = Vec::new();
|
||||
for field in &fields {
|
||||
let is_escaped = match escape {
|
||||
Some(escape) => escaped(field, escape)?,
|
||||
None => false,
|
||||
};
|
||||
syn::visit::Visit::visit_type(if is_escaped { &mut named_escaped } else { &mut named }, &field.ty);
|
||||
match escape.map(|escape| escape.escape(field)).transpose()?.flatten() {
|
||||
Some(bound) => {
|
||||
let mut names = Named::default();
|
||||
syn::visit::Visit::visit_type(&mut names, &field.ty);
|
||||
if let Some(bound) = bound {
|
||||
escaped_bounds.extend(names.0.iter().map(|ident| (ident.clone(), bound.clone())));
|
||||
}
|
||||
named_escaped.0.extend(names.0);
|
||||
}
|
||||
None => syn::visit::Visit::visit_type(&mut named, &field.ty),
|
||||
}
|
||||
}
|
||||
// Each type parameter takes the derive's bound beside its own, in one place: a second place for it is a lint in
|
||||
// the type's crate (`clippy::multiple_bound_locations`).
|
||||
@@ -108,7 +129,8 @@ pub(crate) fn field_checks(
|
||||
param.attrs.clear();
|
||||
let ident = ¶m.ident;
|
||||
let only_escaped = named_escaped.0.contains(ident) && !named.0.contains(ident);
|
||||
let bound = match (param_escape, escape.and_then(|escape| escape.bound.as_ref())) {
|
||||
let escape_bound = escaped_bounds.iter().find(|(named, _)| named == ident).map(|(_, bound)| bound);
|
||||
let bound = match (param_escape, escape_bound) {
|
||||
(Some(ParamEscape { bound, .. }), _) if escaped => quote!(#bound),
|
||||
(_, Some(bound)) if only_escaped => quote!(#bound),
|
||||
_ => quote!(#trait_path),
|
||||
@@ -122,7 +144,7 @@ pub(crate) fn field_checks(
|
||||
let mut checked = Vec::new();
|
||||
for field in fields {
|
||||
if let Some(escape) = escape
|
||||
&& escaped(field, escape)?
|
||||
&& escape.escape(field)?.is_some()
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -131,7 +131,8 @@ impl Guide {
|
||||
|
||||
/// A guide being created or dragged, as the ruler drag or the guide's own part reports it. Build one with
|
||||
/// [`GuideDrag::new_guide`] for a guide dragged out of a ruler and [`GuideDrag::moving`] for an existing guide.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, crate::contract::MemoProps)]
|
||||
#[memo_props(every_pass = "a guide being placed moves with the pointer in every pass of its drag")]
|
||||
#[non_exhaustive]
|
||||
pub struct GuideDrag {
|
||||
/// The guide being moved; `None` for a new guide dragged out of a ruler.
|
||||
|
||||
@@ -52,23 +52,17 @@ pub type RenderIconFn = dyn Fn(CaptionIcon, u32) -> Option<CaptionMask> + Send +
|
||||
|
||||
/// The round buttons' glyphs from the desktop's icon theme (Linux: `window-*-symbolic`), drawn in the glyph colour
|
||||
/// as symbolic icons are. A glyph the theme lacks draws the family's own.
|
||||
#[derive(Clone)]
|
||||
#[derive(Clone, crate::contract::MemoProps)]
|
||||
pub struct CaptionIcons {
|
||||
theme: String,
|
||||
generation: u64,
|
||||
#[memo_props(
|
||||
covered_by = "generation",
|
||||
reason = "the generation changes whenever `render` may answer differently (`new`), and icons read again take a new one (`for_desktop`)"
|
||||
)]
|
||||
render: Arc<RenderIconFn>,
|
||||
}
|
||||
|
||||
/// By the theme and the generation, which covers `render`: the generation changes whenever `render` may answer
|
||||
/// differently (`new`), and icons read again take a new one (`for_desktop`), so equal keys draw the same glyphs.
|
||||
impl crate::contract::MemoProps for CaptionIcons {
|
||||
fn key(&self, key: &mut crate::contract::MemoKey) {
|
||||
let CaptionIcons { theme, generation, render: _ } = self;
|
||||
crate::contract::MemoProps::key(theme, key);
|
||||
crate::contract::MemoProps::key(generation, key);
|
||||
}
|
||||
}
|
||||
|
||||
impl CaptionIcons {
|
||||
/// Icons of `theme` rendered by `render`. `generation` changes whenever `render` may answer differently (a
|
||||
/// reinstalled theme, a size that finished rendering); the textures made from it follow. Use 0 for icons that
|
||||
|
||||
@@ -92,18 +92,12 @@ impl LevelState {
|
||||
/// The rows of one menu level: each registers its label, and the level gives every row its mnemonic from the
|
||||
/// registrations of this pass. It also holds the level's one open submenu row and its active row. Rows
|
||||
/// outside any menu get an inert level.
|
||||
#[derive(Clone)]
|
||||
#[derive(Clone, crate::contract::MemoProps)]
|
||||
#[memo_props(every_pass = "a handle to the level's state, which its rows write during the pass")]
|
||||
pub(crate) struct MenuLevel {
|
||||
state: Option<Arc<Mutex<LevelState>>>,
|
||||
}
|
||||
|
||||
/// A handle to the level's state, which its rows write during the pass: a view under a menu level runs in every pass.
|
||||
impl crate::contract::MemoProps for MenuLevel {
|
||||
fn key(&self, key: &mut crate::contract::MemoKey) {
|
||||
key.changes_every_pass();
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialEq for MenuLevel {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
match (&self.state, &other.state) {
|
||||
|
||||
Reference in New Issue
Block a user