Skip to main content

tilo_resource_macros/
lib.rs

1//! Procedural macros for `tilo-resource`. See that crate for the API; this
2//! crate only generates calls into it.
3
4use proc_macro::TokenStream;
5use proc_macro2::Span;
6use proc_macro2::TokenStream as Tokens;
7use quote::{format_ident, quote};
8use syn::spanned::Spanned;
9use syn::{
10    Attribute, Data, DeriveInput, Expr, ExprLit, Fields, GenericArgument, ItemImpl, Lit, Meta,
11    MetaNameValue, PathArguments, Type, parse_macro_input,
12};
13
14const CRATE: &str = "tilo_resource";
15
16/// Generated code names the runtime crate by a relative path, so it resolves
17/// either as a direct dependency or through `tilo_app::prelude::*`, which
18/// re-exports it under the same name.
19fn krate() -> Tokens {
20    let name = format_ident!("{}", CRATE);
21    quote!(#name)
22}
23
24/// The app's compiled surface, the file `tilolang surface --write` writes beside its authored
25/// `surface.toml`: `Option<&'static str>`, `Some` when it has a `surface.json` at its root, else
26/// `None`.
27///
28/// The value is the canonical compiled form, the one form the system commits, addresses and
29/// sends, so the shell's built-in apps and the web desktop read their surfaces without a TOML
30/// parser. A file that is not the canonical compiled form fails the build, where such a process
31/// would otherwise find that the surface declares nothing.
32#[proc_macro]
33pub fn committed_surface(_input: TokenStream) -> TokenStream {
34    let dir = std::env::var_os("CARGO_MANIFEST_DIR").map(std::path::PathBuf::from);
35    let Some(dir) = dir else {
36        return quote::quote! { ::core::option::Option::<&'static str>::None }.into();
37    };
38    let path = dir.join("surface.json");
39    if !path.is_file() {
40        return quote::quote! { ::core::option::Option::<&'static str>::None }.into();
41    }
42    let json = match std::fs::read_to_string(&path) {
43        Ok(json) => json,
44        Err(error) => {
45            let error = format!("{}: {error}", path.display());
46            return syn::Error::new(Span::call_site(), error)
47                .to_compile_error()
48                .into();
49        }
50    };
51    let canonical = serde_json::from_str::<serde_json::Value>(&json)
52        .map(|value| tilo_canonical_json::to_string(&value));
53    if !canonical.is_ok_and(|canonical| canonical == json) {
54        let error = format!(
55            "{}: not the canonical compiled form of a surface; run `tilolang surface --write`",
56            path.display()
57        );
58        return syn::Error::new(Span::call_site(), error)
59            .to_compile_error()
60            .into();
61    }
62    // The files are inputs of the crate's build like its sources: a changed surface rebuilds the
63    // crate, rather than leaving the surface it was built with in a cached build.
64    let tracked = path.display().to_string();
65    let authored = dir.join("surface.toml");
66    let thumb = authored.is_file().then(|| authored.display().to_string());
67    let tracked = if let Some(authored) = thumb {
68        quote::quote! {
69            const _: &[u8] = ::core::include_bytes!(#tracked);
70            const _: &[u8] = ::core::include_bytes!(#authored);
71        }
72    } else {
73        quote::quote! { const _: &[u8] = ::core::include_bytes!(#tracked); }
74    };
75    quote::quote! {
76        {
77            #tracked
78            ::core::option::Option::Some(#json)
79        }
80    }
81    .into()
82}
83
84/// What `tilo_resource::word!` expands to: the word `key` of the catalogue
85/// beside the crate being built, named through `krate`, the path that crate
86/// reaches `tilo_resource` by, its placeables filled with the arguments the
87/// word carries.
88#[proc_macro]
89pub fn word(input: TokenStream) -> TokenStream {
90    let WordInput {
91        krate,
92        key,
93        catalogue,
94        arguments,
95    } = parse_macro_input!(input as WordInput);
96    let catalogue = words::Catalogue::read(catalogue.as_deref().unwrap_or(words::LOCALES));
97    match catalogue.named(&krate, key.span(), &key.value(), &arguments) {
98        Ok(word) => word.into(),
99        Err(error) => error.to_compile_error().into(),
100    }
101}
102
103/// What `word!` takes: the path to `tilo_resource`, a key, the arguments its
104/// placeables show (`name = …`), and the catalogue it is in when not
105/// `locales`.
106struct WordInput {
107    krate: Tokens,
108    key: syn::LitStr,
109    catalogue: Option<String>,
110    arguments: Vec<(syn::Ident, syn::Expr)>,
111}
112
113impl syn::parse::Parse for WordInput {
114    fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result<Self> {
115        let mut krate = Tokens::new();
116        while !input.peek(syn::Token![,]) {
117            krate.extend([input.parse::<proc_macro2::TokenTree>()?]);
118        }
119        input.parse::<syn::Token![,]>()?;
120        let key = input.parse()?;
121        let mut catalogue = None;
122        let mut arguments = Vec::new();
123        while input.parse::<Option<syn::Token![,]>>()?.is_some() && !input.is_empty() {
124            let name: syn::Ident = input.parse()?;
125            input.parse::<syn::Token![=]>()?;
126            if name == "catalogue" {
127                catalogue = Some(input.parse::<syn::LitStr>()?.value());
128            } else {
129                arguments.push((name, input.parse()?));
130            }
131        }
132        Ok(Self {
133            krate,
134            key,
135            catalogue,
136            arguments,
137        })
138    }
139}
140
141/// Derive `Model` (and `Fields` for structs with named fields).
142///
143/// * a struct with named fields is a map, one key per field;
144/// * a newtype struct is its inner value;
145/// * an enum of unit variants is a string naming the variant; the variant
146///   marked `#[default]` is the value of an absent slot;
147/// * an enum whose variants carry fields is a map: the variant's name under
148///   `$variant` and each field under a key of its variant
149///   (`$field/<variant>/<field>`, a tuple variant's fields named `0`, `1`,
150///   …), so edits of one variant merge field by field, a change of variant is
151///   last writer wins, and no variant reads a field another one wrote.
152///
153/// Field attributes: `#[model(rename = "key")]`, `#[model(skip)]` (not
154/// stored; the containing type's `Default` on read), `#[model(atom)]` on a
155/// `String`, an `Id`, a `Vec` or an `Option` of one (written whole, last writer
156/// wins, as `Atom` is: a colour or a list of points two people set at once
157/// is one of theirs, never a mix),
158/// `#[model(whole)]` (read every part of a value that loads on demand,
159/// rich text's paragraphs), `#[model(demanded)]` (a view's reader leaves it
160/// unread, as its type's missing value, until a view demands the item
161/// holding it: an issue's description and thread, which a list of thousands
162/// of issues never shows), `#[model(resource)]` on a field whose type is a
163/// resource with its own operations (rich text: published beneath the
164/// record's resource, an item's or the record's own, at `<record>/<key>`,
165/// its actions applied as field edits; see `tilo_resource::child`), `#[model(remove = "quiet")]` on a collection whose items are cheap to
166/// remove (removing one by field edit asks no confirmation),
167/// `#[model(default = expr)]` (what the field reads as when the document
168/// holds none: a required field with a sensible derivation, so an item
169/// missing it still reads; the next whole write stores it),
170/// `#[model(trust = "sensitive")]` (every edit of it asks for confirmation:
171/// a change can expose the person), `#[model(trust = "weakening")]`
172/// (it also crosses a security boundary: any change can weaken the person's
173/// security, so an agent or script acting for them needs their own grant)
174/// and `#[model(weaker = ..)]` (only a change making it weaker than it is
175/// now does: `weaker = "higher"` or `"lower"` for a number, with
176/// `weakest = N` for the value weaker than any, such as a lock delay's `0`
177/// for never; `weaker = true` or `false` for a switch; a list of values
178/// from the strongest to the weakest for a choice), `#[model(range =
179/// low..=high)]` on a number and `#[model(choices = expr)]` on a text (what
180/// the field may hold: published in its value's schema and held by the
181/// record's own check, through every API).
182///
183/// Type attributes: `#[model(check = path)]` (its invariant, with
184/// `check_reads`/`check_items` saying what it reads), `#[model(label =
185/// "..")]`, `#[model(defaults)]` (the type's `Default` is what each field
186/// holds until changed, published with it) and `#[model(field(name,
187/// options..))]` (a field's options given on the type, for a record whose
188/// fields a shared macro writes).
189///
190/// A struct's `Model::SHAPE` lists its stored fields, so layout-aware services
191/// (History restore) reconcile it field by field.
192#[proc_macro_derive(Model, attributes(model))]
193pub fn derive_model(input: TokenStream) -> TokenStream {
194    let input = parse_macro_input!(input as DeriveInput);
195    match derive(&input) {
196        Ok(tokens) => tokens.into(),
197        Err(error) => error.to_compile_error().into(),
198    }
199}
200
201/// Derive `JsonSchema`: the JSON Schema of the type's serde JSON form.
202///
203/// Reads the serde attributes that change the form — `rename`,
204/// `rename_all`, `tag`, `content`, `transparent`, `default`, `skip` — and
205/// refuses those it cannot describe (`flatten`, `untagged`, `with`), so the
206/// schema never differs from what serde reads. Doc comments become
207/// descriptions. Every field's type must implement `JsonSchema` too.
208///
209/// `#[schema(range(min = 1, max = 100))]` on a numeric field narrows its
210/// bounds (either side may be left out): the range is published in the
211/// schema and binding refuses a value outside it, so a `u8` that means
212/// 1 to 100 does not read as `0..255`.
213#[proc_macro_derive(JsonSchema, attributes(serde, schema))]
214pub fn derive_json_schema(input: TokenStream) -> TokenStream {
215    let input = parse_macro_input!(input as DeriveInput);
216    match schema::derive(&input) {
217        Ok(tokens) => tokens.into(),
218        Err(error) => error.to_compile_error().into(),
219    }
220}
221
222mod data_enum;
223mod schema;
224
225/// Derive `Effect`: an enum's variants become the app's published effects —
226/// work with no document delta, invoked by buttons, the palette, agents and
227/// scripts alike. See `tilo_resource::effect`.
228///
229/// `#[effect(operation = "app.effects")]` names the vocabulary's operation
230/// type. Each variant is unit or has named fields (the effect's typed
231/// parameters, `#[param("…")]` describing one); its id is the variant name in
232/// kebab case and its label the crate's catalogue message
233/// `<operation>-<id>` (separators as dashes), or the key `label = "..."`
234/// names. `#[effect(catalogue = "dir")]` on the enum reads another catalogue
235/// than `locales/`. Variant options: `#[effect(label = "key", view, document, prompted, row, job, cancellable, returns,
236/// destructive, privileged, idempotent, own_device, attended, screen, audience = "agents", untrusted, opens_path, member, risk = "path", kind = "read",
237/// host_render, tag = some::TAG)]`. `host_render` marks an effect a host
238/// answers in a render service of its own rather than the record's app
239/// worker; `tag` (repeatable) adds a contract tag, a `&'static str` constant;
240/// `outside_with = "path"` makes a `kind = "read"` effect reach outside only
241/// when that parameter is given (an export writing the file it names).
242/// `document` publishes the effect as a document operation the app's own
243/// registry applies to its record, as the history verbs are; its operation
244/// type is the action's, never an operation the surface answers. `prompted`
245/// keeps a named verb's prompt in the palette where every parameter may be
246/// left out (undo asks how many steps).
247/// `item = field` offers it on each item of a collection, its first parameter
248/// bound to the item's id; `on = RowType` offers it on each row of a
249/// `#[derive(Row)]` type, bound to the row's id.
250/// Who may run an effect is decided by what it declares, like any action.
251/// Every effect states its kind: `kind = "read"`, `"undoable"` or `"outside"`
252/// (a change checked against the caller's grants). `view` implies `read`,
253/// `edit` implies `undoable`, and an effect that names none of them does not
254/// build. A `screen`
255/// effect only changes what is on the screen it is invoked on (a form, a
256/// panel, a place it shows): it reads, answers nothing, only the person at
257/// that screen invokes it and no agent is listed it. An
258/// `own_device` effect's whole scope is the invoking person's own device,
259/// touching nothing shared and no one else (their clipboard, their own
260/// appearance): a room's grants have nothing to consent to. An `attended`
261/// effect needs its person attending (a chooser, a sign-in, a secret shown):
262/// whoever acts for them is always asked first, while the person's own click
263/// is their decision and, like an `own_device` effect, needs no room's
264/// consent and runs only on their own device. Generates `impl Effect` and one `ActionRef`
265/// constant per variant (`Backups::RESTORE`) for binding controls.
266#[proc_macro_derive(Effect, attributes(effect, param))]
267pub fn derive_effect(input: TokenStream) -> TokenStream {
268    let input = parse_macro_input!(input as DeriveInput);
269    match effect::derive(&input) {
270        Ok(tokens) => tokens.into(),
271        Err(error) => error.to_compile_error().into(),
272    }
273}
274
275mod effect;
276mod row;
277mod words;
278
279/// Derive `Row`: a plain struct as the type of the entities a surface
280/// publishes that live outside any document — processes, devices,
281/// containers, journal entries, a fetched catalogue's rows. See
282/// `tilo_resource::words`.
283///
284/// `#[row(kind = "app.thing", label = "Thing")]` names what a row of it is to
285/// search, exactly as a `#[resource]` type's items say theirs; `label`
286/// defaults to the type's name in words. `effects = Type` names the
287/// vocabulary offered on every row of the type (`#[effect(on = Thing)]`),
288/// each bound to the row's id; `LiveRow::typed` publishes them, so a press on
289/// the row is one of the type's effects or `open`. Generates
290/// `impl tilo_resource::words::RowType`.
291///
292/// How a row's effects take their arguments: the first parameter is the row
293/// id, parsed as that field's type (`String`, `u64`, an identity), and a row
294/// whose id is not one is published unavailable with the reason.
295/// `LiveRow::labelled` names one effect for that row alone; `RowBindings`
296/// with `LiveRow::typed_with` offers only the effects the row's state says
297/// apply, binding further arguments by name (`operation`, `folder`) or the
298/// row id itself; `LiveRow::prefilled` leaves an argument asked and fills its
299/// field with the value the row knows (a calendar's current colour, a
300/// switch's next state). A destructive effect's `phrase` is published on
301/// every spec it produces, so a row-bound invocation still asks what it
302/// loses. `#[param(resource = "kind")]` makes a parameter a picker of an
303/// existing resource of that kind; a parameter's description named in the
304/// catalogue (`<label key>-<param>`) is read in the person's language.
305#[proc_macro_derive(Row, attributes(row))]
306pub fn derive_row(input: TokenStream) -> TokenStream {
307    let input = parse_macro_input!(input as DeriveInput);
308    match row::derive(&input) {
309        Ok(tokens) => tokens.into(),
310        Err(error) => error.to_compile_error().into(),
311    }
312}
313
314#[derive(Default)]
315#[allow(
316    clippy::struct_excessive_bools,
317    reason = "each is one independent field attribute"
318)]
319struct FieldOptions {
320    rename: Option<String>,
321    /// `title = "…"`: what a person reads as the field's name, in code rather
322    /// than inferred from the doc comment above it.
323    title: Option<String>,
324    skip: bool,
325    label: bool,
326    readonly: bool,
327    unit: bool,
328    atom: bool,
329    quiet_remove: bool,
330    whole: bool,
331    /// `demanded`: a view's reader leaves it unread until a view demands
332    /// the item holding it.
333    demanded: bool,
334    resource: bool,
335    /// `default = expr`: what an absent field reads as.
336    default: Option<Expr>,
337    /// `trust = "sensitive" | "weakening"`: the `Trust` variant it names.
338    trust: Option<syn::LitStr>,
339    /// `weaker = "higher" | "lower" | bool | ["strongest", .., "weakest"]`:
340    /// which way a change weakens security.
341    weaker: Option<Expr>,
342    /// `weakest = N`: the number weaker than any (a delay's `0`, never).
343    weakest: Option<syn::LitInt>,
344    /// `range = low..=high`: the numbers it may hold.
345    range: Option<(Expr, Expr)>,
346    /// `choices = expr`: the texts it may hold, any expression a `&[&str]`
347    /// borrows.
348    choices: Option<Expr>,
349}
350
351impl FieldOptions {
352    /// The field's `Trust`, as an expression.
353    fn trust(&self, krate: &Tokens) -> syn::Result<Tokens> {
354        let named = self.trust.as_ref().map(syn::LitStr::value);
355        let numeric = matches!(
356            &self.weaker,
357            Some(Expr::Lit(syn::ExprLit {
358                lit: syn::Lit::Str(_),
359                ..
360            }))
361        );
362        if let Some(weakest) = self.weakest.as_ref().filter(|_| !numeric) {
363            return Err(syn::Error::new(
364                weakest.span(),
365                "`weakest` goes with `weaker = \"higher\"` or `weaker = \"lower\"`",
366            ));
367        }
368        let Some(weaker) = &self.weaker else {
369            return Ok(match named.as_deref() {
370                None => quote!(#krate::Trust::Ordinary),
371                Some("sensitive") => quote!(#krate::Trust::Sensitive),
372                Some("weakening") => quote!(#krate::Trust::Weakening),
373                Some(_) => {
374                    return Err(syn::Error::new(
375                        self.trust.span(),
376                        "expected `trust = \"sensitive\"` or `trust = \"weakening\"`",
377                    ));
378                }
379            });
380        };
381        if named.as_deref().is_some_and(|named| named != "weakening") {
382            return Err(syn::Error::new(
383                self.trust.span(),
384                "`weaker` makes the field weaken one way: drop `trust` or make it \"weakening\"",
385            ));
386        }
387        let unexpected = || {
388            syn::Error::new(
389                weaker.span(),
390                "expected `weaker = \"higher\"`, `\"lower\"`, `true`, `false` or a list of \
391                 values from the strongest to the weakest",
392            )
393        };
394        let weakest = if let Some(weakest) = &self.weakest {
395            let weakest: i64 = weakest.base10_parse()?;
396            quote!(::core::option::Option::Some(#weakest))
397        } else {
398            quote!(::core::option::Option::None)
399        };
400        let string = |expr: &Expr| match expr {
401            Expr::Lit(syn::ExprLit {
402                lit: syn::Lit::Str(text),
403                ..
404            }) => Some(text.value()),
405            _ => None,
406        };
407        let weaker = match weaker {
408            Expr::Lit(syn::ExprLit {
409                lit: syn::Lit::Str(rule),
410                ..
411            }) if rule.value() == "higher" => {
412                quote!(#krate::Weaker::Higher { weakest: #weakest })
413            }
414            Expr::Lit(syn::ExprLit {
415                lit: syn::Lit::Str(rule),
416                ..
417            }) if rule.value() == "lower" => quote!(#krate::Weaker::Lower { weakest: #weakest }),
418            Expr::Lit(syn::ExprLit {
419                lit: syn::Lit::Bool(weak),
420                ..
421            }) => {
422                let order = if weak.value {
423                    ["false", "true"]
424                } else {
425                    ["true", "false"]
426                };
427                quote!(#krate::Weaker::Order(&[#(#order),*]))
428            }
429            Expr::Array(values) => {
430                // Each value as the JSON text of the string it serializes to.
431                let order = values
432                    .elems
433                    .iter()
434                    .map(|value| {
435                        string(value)
436                            .filter(|text| {
437                                !text
438                                    .chars()
439                                    .any(|c| c == '"' || c == '\\' || c.is_control())
440                            })
441                            .map(|text| format!("\"{text}\""))
442                            .ok_or_else(unexpected)
443                    })
444                    .collect::<syn::Result<Vec<_>>>()?;
445                quote!(#krate::Weaker::Order(&[#(#order),*]))
446            }
447            _ => return Err(unexpected()),
448        };
449        Ok(quote!(#krate::Trust::Weakens(#weaker)))
450    }
451}
452
453fn field_options(attrs: &[Attribute]) -> syn::Result<FieldOptions> {
454    let mut options = FieldOptions::default();
455    for attr in attrs.iter().filter(|attr| attr.path().is_ident("model")) {
456        attr.parse_nested_meta(|meta| {
457            if meta.path.is_ident("skip") {
458                options.skip = true;
459            } else if meta.path.is_ident("rename") {
460                let value: syn::LitStr = meta.value()?.parse()?;
461                options.rename = Some(value.value());
462            } else if meta.path.is_ident("title") {
463                let value: syn::LitStr = meta.value()?.parse()?;
464                options.title = Some(value.value());
465            } else if meta.path.is_ident("label") {
466                options.label = true;
467            } else if meta.path.is_ident("readonly") {
468                options.readonly = true;
469            } else if meta.path.is_ident("unit") {
470                options.unit = true;
471            } else if meta.path.is_ident("atom") {
472                options.atom = true;
473            } else if meta.path.is_ident("whole") {
474                options.whole = true;
475            } else if meta.path.is_ident("demanded") {
476                options.demanded = true;
477            } else if meta.path.is_ident("resource") {
478                options.resource = true;
479            } else if meta.path.is_ident("default") {
480                options.default = Some(meta.value()?.parse()?);
481            } else if meta.path.is_ident("trust") {
482                options.trust = Some(meta.value()?.parse()?);
483            } else if meta.path.is_ident("weaker") {
484                options.weaker = Some(meta.value()?.parse()?);
485            } else if meta.path.is_ident("weakest") {
486                options.weakest = Some(meta.value()?.parse()?);
487            } else if meta.path.is_ident("range") {
488                let range: syn::ExprRange = meta.value()?.parse()?;
489                match (range.start, range.limits, range.end) {
490                    (Some(start), syn::RangeLimits::Closed(_), Some(end)) => {
491                        options.range = Some((*start, *end));
492                    }
493                    _ => return Err(meta.error("expected `range = low..=high`")),
494                }
495            } else if meta.path.is_ident("choices") {
496                options.choices = Some(meta.value()?.parse()?);
497            } else if meta.path.is_ident("remove") {
498                let how: syn::LitStr = meta.value()?.parse()?;
499                if how.value() != "quiet" {
500                    return Err(meta.error("expected `remove = \"quiet\"`"));
501                }
502                options.quiet_remove = true;
503            } else {
504                return Err(meta.error(
505                    "expected `skip`, `rename = \"...\"`, `title = \"...\"`, `label`, `readonly`, `unit`, `atom`, \
506                     `whole`, `demanded`, `resource`, `default = ..`, `trust = \"..\"`, `weaker = ..`, \
507                     `weakest = N`, `range = low..=high`, `choices = ..` or \
508                     `remove = \"quiet\"`",
509                ));
510            }
511            Ok(())
512        })?;
513    }
514    Ok(options)
515}
516
517/// What `#[model(..)]` on a record type says.
518#[derive(Default)]
519struct ContainerOptions {
520    /// `check = path`: its invariant.
521    check: Option<syn::Path>,
522    /// `label = "first last"`: the fields whose texts, joined by spaces,
523    /// name a value.
524    label: Vec<String>,
525    /// `label = path`: the function that names a value, where its name is
526    /// not a field's text as stored (a place kept as `xdg:documents` is
527    /// "Documents").
528    label_with: Option<syn::Path>,
529    /// `check_reads = "a b"`: the fields the invariant reads; an edit of
530    /// none of them (nor of an item of `check_items`) cannot break it.
531    check_reads: Option<Vec<String>>,
532    /// `check_items = "c"`: the collections whose items the invariant
533    /// counts (not reads): adding or removing one can break it, an edit
534    /// inside one cannot.
535    check_items: Vec<String>,
536    /// `defaults`: the type's `Default` is what each field holds until
537    /// someone changes it, published with the field.
538    defaults: bool,
539    /// `field(name, options..)`: a field's options given on the type, for a
540    /// record whose fields a shared macro writes.
541    field_options: Vec<(String, Tokens)>,
542}
543
544/// `audience = "people" | "agents" | "everyone"` on an action or effect:
545/// the `tilo_actions::Audience` variant it names.
546fn audience_option(meta: &syn::meta::ParseNestedMeta<'_>) -> syn::Result<syn::Ident> {
547    let value = meta.value()?.parse::<syn::LitStr>()?;
548    let variant = match value.value().as_str() {
549        "everyone" => "Everyone",
550        "people" => "People",
551        "agents" => "Agents",
552        _ => {
553            return Err(syn::Error::new(
554                value.span(),
555                "expected `audience = \"people\"`, `\"agents\"` or `\"everyone\"`",
556            ));
557        }
558    };
559    Ok(syn::Ident::new(variant, value.span()))
560}
561
562/// `step = "create"`: the kind of step an action takes, named by the
563/// `tilo_actions::StepKind` variant it is.
564fn step_option(meta: &syn::meta::ParseNestedMeta<'_>) -> syn::Result<syn::Ident> {
565    let value = meta.value()?.parse::<syn::LitStr>()?;
566    let variant = match value.value().as_str() {
567        "create" => "Create",
568        "write" => "Write",
569        "edit" => "Edit",
570        "delete" => "Delete",
571        "move" => "Move",
572        "read" => "Read",
573        "run" => "Run",
574        "work" => "Work",
575        _ => {
576            return Err(syn::Error::new(
577                value.span(),
578                "expected `step = \"create\"`, \"write\", \"edit\", \"delete\", \"move\", \"read\", \
579                 \"run\" or \"work\"",
580            ));
581        }
582    };
583    Ok(syn::Ident::new(variant, value.span()))
584}
585
586/// Fields named by a space-separated `"a b"` list.
587/// `keywords = "mkdir, make directory"`: an action's other words, one
588/// phrase each, comma separated. An empty phrase or one that is the same
589/// word twice is a mistake in the declaration, not a word anyone types.
590fn keyword_list(list: &syn::LitStr) -> syn::Result<Vec<String>> {
591    let mut words: Vec<String> = Vec::new();
592    for word in list.value().split(',').map(str::trim) {
593        if word.is_empty() {
594            return Err(syn::Error::new(list.span(), "a keyword is empty"));
595        }
596        if words.iter().any(|seen| seen.eq_ignore_ascii_case(word)) {
597            return Err(syn::Error::new(
598                list.span(),
599                format!("the keyword `{word}` is listed twice"),
600            ));
601        }
602        words.push(word.to_owned());
603    }
604    Ok(words)
605}
606
607/// `icon = "folder-plus"`: a picture by its Lucide name, lowercase words
608/// joined by hyphens. Whether the toolkit draws that name is checked where
609/// the toolkit is: each app's tests resolve every icon it declares.
610fn icon_name(name: &syn::LitStr) -> syn::Result<String> {
611    let value = name.value();
612    let well_formed = !value.is_empty()
613        && value.split('-').all(|word| {
614            !word.is_empty()
615                && word
616                    .chars()
617                    .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit())
618        });
619    if !well_formed {
620        return Err(syn::Error::new(
621            name.span(),
622            "an icon is named by its Lucide name, such as `folder-plus`",
623        ));
624    }
625    Ok(value)
626}
627
628/// `Some("…")` or `None`, as tokens of an `Option<&'static str>`.
629fn optional_str(value: Option<&str>) -> proc_macro2::TokenStream {
630    value.map_or_else(
631        || quote::quote!(::core::option::Option::None),
632        |value| quote::quote!(::core::option::Option::Some(#value)),
633    )
634}
635
636fn field_list(meta: &syn::meta::ParseNestedMeta<'_>) -> syn::Result<Vec<String>> {
637    let fields = meta.value()?.parse::<syn::LitStr>()?;
638    Ok(fields
639        .value()
640        .split_whitespace()
641        .map(str::to_owned)
642        .collect())
643}
644
645/// `#[model(check = path, label = "first last")]` on the type, or
646/// `label = path` naming the function `fn(&Self) -> String` that names it.
647fn container_options(attrs: &[Attribute]) -> syn::Result<ContainerOptions> {
648    let mut options = ContainerOptions::default();
649    for attr in attrs.iter().filter(|attr| attr.path().is_ident("model")) {
650        attr.parse_nested_meta(|meta| {
651            if meta.path.is_ident("check") {
652                options.check = Some(meta.value()?.parse::<syn::Path>()?);
653                Ok(())
654            } else if meta.path.is_ident("check_reads") {
655                options.check_reads = Some(field_list(&meta)?);
656                Ok(())
657            } else if meta.path.is_ident("check_items") {
658                options.check_items = field_list(&meta)?;
659                Ok(())
660            } else if meta.path.is_ident("defaults") {
661                options.defaults = true;
662                Ok(())
663            } else if meta.path.is_ident("field") {
664                let content;
665                syn::parenthesized!(content in meta.input);
666                let field: syn::Ident = content.parse()?;
667                content.parse::<syn::Token![,]>()?;
668                options
669                    .field_options
670                    .push((field.to_string(), content.parse::<Tokens>()?));
671                Ok(())
672            } else if meta.path.is_ident("label") {
673                let value = meta.value()?;
674                if !value.peek(syn::LitStr) {
675                    options.label_with = Some(value.parse::<syn::Path>()?);
676                    return Ok(());
677                }
678                options.label = value
679                    .parse::<syn::LitStr>()?
680                    .value()
681                    .split_whitespace()
682                    .map(str::to_owned)
683                    .collect();
684                if options.label.is_empty() {
685                    return Err(meta.error("`label = \"..\"` names the fields that make the label"));
686                }
687                Ok(())
688            } else {
689                Err(meta.error(
690                    "expected `check = path`, `check_reads = \"field ..\"`, \
691                     `check_items = \"field ..\"`, `defaults`, `field(name, options..)`, \
692                     `label = \"field field ..\"` or `label = path` on the type",
693                ))
694            }
695        })?;
696    }
697    if options.check.is_none() && (options.check_reads.is_some() || !options.check_items.is_empty())
698    {
699        return Err(syn::Error::new(
700            Span::call_site(),
701            "`check_reads` and `check_items` say what a `check = path` reads",
702        ));
703    }
704    // A field named twice is not the label twice: the second mention would
705    // silently name no field, and the label would read as if it had.
706    let mut named: Vec<&str> = Vec::new();
707    for part in &options.label {
708        if named.contains(&part.as_str()) {
709            return Err(syn::Error::new(
710                Span::call_site(),
711                format!("`label = \"..\"` names `{part}` twice"),
712            ));
713        }
714        named.push(part);
715    }
716    Ok(options)
717}
718
719/// `const TABLE` of a model type: for a type without generic parameters, a
720/// `static` in the crate defining it, so that a crate using the type links
721/// that one table and the functions it names rather than building its own.
722fn table_const(input: &DeriveInput, table: &Tokens, value: impl Fn(Tokens) -> Tokens) -> Tokens {
723    if input.generics.params.is_empty() {
724        let name = &input.ident;
725        let value = value(quote!(#name));
726        quote! {
727            const TABLE: &'static #table::ModelTable = {
728                static TABLE: #table::ModelTable = #value;
729                &TABLE
730            };
731        }
732    } else {
733        let value = value(quote!(Self));
734        quote!(const TABLE: &'static #table::ModelTable = &#value;)
735    }
736}
737
738#[allow(
739    clippy::too_many_lines,
740    reason = "one expansion per data shape, each read top to bottom"
741)]
742fn derive(input: &DeriveInput) -> syn::Result<Tokens> {
743    let krate = krate();
744    let name = &input.ident;
745    let (impl_generics, type_generics, where_clause) = input.generics.split_for_impl();
746    match &input.data {
747        Data::Struct(data) => match &data.fields {
748            Fields::Named(fields) => derive_named(input, fields),
749            Fields::Unnamed(fields) if fields.unnamed.len() == 1 => {
750                let ty = fields
751                    .unnamed
752                    .first()
753                    .map(|field| &field.ty)
754                    .ok_or_else(|| syn::Error::new(fields.span(), "expected one field"))?;
755                let table = quote!(#krate::table);
756                let newtype_table =
757                    table_const(input, &table, |ty| quote!(#table::TableOf::<#ty>::TABLE));
758                Ok(quote! {
759                    impl #impl_generics #krate::Model for #name #type_generics #where_clause {
760                        const SHAPE: #krate::Shape = <#ty as #krate::Model>::SHAPE;
761                        const CHECKS: bool = <#ty as #krate::Model>::CHECKS;
762                        const SCALAR: bool = <#ty as #krate::Model>::SCALAR;
763                        const NULLABLE: bool = <#ty as #krate::Model>::NULLABLE;
764                        const OPS: bool = <#ty as #krate::Model>::OPS;
765                        #newtype_table
766                        type Paths<__R> = #krate::Path<__R, Self>;
767
768                        fn paths_at<__R>(path: #krate::Path<__R, Self>) -> #krate::Path<__R, Self> {
769                            path
770                        }
771                        fn to_json(&self) -> #krate::__private::serde_json::Value {
772                            #krate::Model::to_json(&self.0)
773                        }
774                        fn from_json(
775                            value: &#krate::__private::serde_json::Value,
776                        ) -> ::core::result::Result<Self, #krate::ModelError> {
777                            <#ty as #krate::Model>::from_json(value).map(Self)
778                        }
779                        fn edit(
780                            doc: &mut #krate::Doc,
781                            slot: #krate::Slot<'_>,
782                            path: &[#krate::Segment],
783                            op: &#krate::EditOp,
784                            cx: &mut #krate::ActionCx,
785                        ) -> ::core::result::Result<(), #krate::ModelError> {
786                            <#ty as #krate::Model>::edit(doc, slot, path, op, cx)
787                        }
788                        fn check(&self) -> ::core::result::Result<(), #krate::Refusal> {
789                            #krate::Model::check(&self.0)
790                        }
791                        fn label(&self) -> ::core::option::Option<::std::string::String> {
792                            #krate::Model::label(&self.0)
793                        }
794
795                        fn load(
796                            doc: &#krate::Doc,
797                            value: &#krate::__private::Value<'_>,
798                            id: &#krate::__private::ObjId,
799                        ) -> ::core::result::Result<Self, #krate::ModelError> {
800                            <#ty as #krate::Model>::load(doc, value, id).map(Self)
801                        }
802                        fn value_schema() -> #krate::__private::serde_json::Value {
803                            <#ty as #krate::Model>::value_schema()
804                        }
805                        fn field_type(types: &mut #krate::TypeSet) -> #krate::FieldType {
806                            <#ty as #krate::Model>::field_type(types)
807                        }
808                        fn missing() -> ::core::result::Result<Self, #krate::ModelError> {
809                            <#ty as #krate::Model>::missing().map(Self)
810                        }
811                        fn store(
812                            &self,
813                            doc: &mut #krate::Doc,
814                            slot: #krate::Slot<'_>,
815                        ) -> ::core::result::Result<(), #krate::ModelError> {
816                            #krate::Model::store(&self.0, doc, slot)
817                        }
818                        fn stores_as(&self, before: &Self) -> bool {
819                            #krate::Model::stores_as(&self.0, &before.0)
820                        }
821                        fn store_changed(
822                            &self,
823                            before: &Self,
824                            doc: &mut #krate::Doc,
825                            slot: #krate::Slot<'_>,
826                            dirty: &#krate::Delta,
827                        ) -> ::core::result::Result<(), #krate::ModelError> {
828                            #krate::Model::store_changed(&self.0, &before.0, doc, slot, dirty)
829                        }
830                        fn refresh(
831                            &mut self,
832                            doc: &#krate::Doc,
833                            value: &#krate::__private::Value<'_>,
834                            id: &#krate::__private::ObjId,
835                            delta: &#krate::Delta,
836                        ) -> ::core::result::Result<(), #krate::ModelError> {
837                            #krate::Model::refresh(&mut self.0, doc, value, id, delta)
838                        }
839                        fn collect_text(&self, out: &mut ::std::vec::Vec<::std::string::String>) {
840                            #krate::Model::collect_text(&self.0, out);
841                        }
842                    }
843                })
844            }
845            _ => Err(syn::Error::new(
846                input.span(),
847                "Model derives for structs with named fields or one unnamed field",
848            )),
849        },
850        Data::Enum(data)
851            if data
852                .variants
853                .iter()
854                .any(|variant| !matches!(variant.fields, Fields::Unit)) =>
855        {
856            data_enum::derive(input, data)
857        }
858        Data::Enum(data) => {
859            let mut names = Vec::new();
860            let mut wires = Vec::new();
861            let mut idents = Vec::new();
862            let mut default = None;
863            let rule = crate::schema::wire_rule(&input.attrs)?;
864            for variant in &data.variants {
865                let options = field_options(&variant.attrs)?;
866                let key = options
867                    .rename
868                    .unwrap_or_else(|| snake_case(&variant.ident.to_string()));
869                let wire = crate::schema::wire_name(&variant.ident, &variant.attrs, rule.as_ref())?;
870                if variant
871                    .attrs
872                    .iter()
873                    .any(|attr| attr.path().is_ident("default"))
874                {
875                    default = Some(variant.ident.clone());
876                }
877                names.push(key);
878                wires.push(wire);
879                idents.push(variant.ident.clone());
880            }
881            let table = quote!(#krate::table);
882            let type_name = name.to_string();
883            let type_doc = first_doc_line(&input.attrs);
884            let positions: Vec<proc_macro2::Literal> = (0..idents.len())
885                .map(proc_macro2::Literal::usize_unsuffixed)
886                .collect();
887            let default_index = default.map_or_else(
888                || quote!(::core::option::Option::None),
889                |ident| {
890                    let position = idents.iter().position(|candidate| *candidate == ident);
891                    let position = proc_macro2::Literal::usize_unsuffixed(position.unwrap_or(0));
892                    quote!(::core::option::Option::Some(#position))
893                },
894            );
895            let unit_table = table_const(
896                input,
897                &table,
898                |ty| quote!(#table::ModelTable::of_unit(&#ty::__UNIT)),
899            );
900            Ok(quote! {
901                impl #impl_generics #name #type_generics #where_clause {
902                    /// The enum as data: its variants' stored names, and the
903                    /// names it has in a value's JSON form.
904                    #[doc(hidden)]
905                    pub const __UNIT: #table::UnitDesc = #table::UnitDesc {
906                        names: &[#(#names),*],
907                        wire: &[#(#wires),*],
908                        default: #default_index,
909                        index: Self::__index,
910                        make: Self::__make,
911                        set: Self::__set,
912                        staged: (#table::empty_of::<Self>, #table::unwrap_of::<Self>),
913                    };
914
915                    fn __index(value: &dyn ::core::any::Any) -> ::core::option::Option<usize> {
916                        match value.downcast_ref::<Self>()? {
917                            #(Self::#idents => ::core::option::Option::Some(#positions),)*
918                        }
919                    }
920
921                    fn __variant(index: usize) -> ::core::option::Option<Self> {
922                        match index {
923                            #(#positions => ::core::option::Option::Some(Self::#idents),)*
924                            _ => ::core::option::Option::None,
925                        }
926                    }
927
928                    fn __make(
929                        index: usize,
930                        out: &mut dyn ::core::any::Any,
931                    ) -> ::core::result::Result<(), #krate::ModelError> {
932                        #table::put_variant(Self::__variant(index), out)
933                    }
934
935                    fn __set(
936                        index: usize,
937                        target: &mut dyn ::core::any::Any,
938                    ) -> ::core::result::Result<(), #krate::ModelError> {
939                        #table::set_variant(Self::__variant(index), target)
940                    }
941                }
942
943                impl #impl_generics #krate::Settable for #name #type_generics #where_clause {}
944
945                impl #impl_generics #krate::Model for #name #type_generics #where_clause {
946                    #unit_table
947                    type Paths<__R> = #krate::Path<__R, Self>;
948
949                    fn paths_at<__R>(path: #krate::Path<__R, Self>) -> #krate::Path<__R, Self> {
950                        path
951                    }
952                    #krate::__table_functions!();
953                    fn value_schema() -> #krate::__private::serde_json::Value {
954                        #table::unit_schema(&[#(#wires),*])
955                    }
956                    fn field_type(types: &mut #krate::TypeSet) -> #krate::FieldType {
957                        #krate::surface::enum_type(
958                            types,
959                            ::core::any::type_name::<Self>(),
960                            #type_name,
961                            #type_doc,
962                            &[#((#wires, "", &[])),*],
963                        )
964                    }
965                    #[inline]
966                    fn missing() -> ::core::result::Result<Self, #krate::ModelError> {
967                        #table::Run(Self::TABLE).missing()
968                    }
969                }
970            })
971        }
972        Data::Union(_) => Err(syn::Error::new(
973            input.span(),
974            "Model does not derive for unions",
975        )),
976    }
977}
978
979#[allow(
980    clippy::too_many_lines,
981    reason = "one linear expansion: the field table, the reach into a record, and the trait impls"
982)]
983fn derive_named(input: &DeriveInput, fields: &syn::FieldsNamed) -> syn::Result<Tokens> {
984    let krate = krate();
985    let table = quote!(#krate::table);
986    let name = &input.ident;
987    let vis = &input.vis;
988    let (impl_generics, type_generics, where_clause) = input.generics.split_for_impl();
989    let ContainerOptions {
990        check,
991        label: label_parts,
992        label_with,
993        check_reads,
994        check_items,
995        defaults,
996        field_options: given_options,
997    } = container_options(&input.attrs)?;
998    for (given, _) in &given_options {
999        if !fields
1000            .named
1001            .iter()
1002            .any(|field| field.ident.as_ref().is_some_and(|ident| ident == given))
1003        {
1004            return Err(syn::Error::new(
1005                Span::call_site(),
1006                format!("`field({given}, ..)` names no field of `{name}`"),
1007            ));
1008        }
1009    }
1010    // Each stored field's key by its name, for what the check reads.
1011    let mut keys: Vec<(String, String)> = Vec::new();
1012    let paths_name = format_ident!("{}Paths", name);
1013    let mut paths_generics = input.generics.clone();
1014    paths_generics.params.insert(0, syn::parse_quote!(__R));
1015    let (paths_impl_generics, paths_type_generics, _) = paths_generics.split_for_impl();
1016    let generic_args: Vec<Tokens> = input
1017        .generics
1018        .params
1019        .iter()
1020        .map(|param| match param {
1021            syn::GenericParam::Type(ty) => {
1022                let ident = &ty.ident;
1023                quote!(#ident)
1024            }
1025            syn::GenericParam::Lifetime(lifetime) => {
1026                let lifetime = &lifetime.lifetime;
1027                quote!(#lifetime)
1028            }
1029            syn::GenericParam::Const(constant) => {
1030                let ident = &constant.ident;
1031                quote!(#ident)
1032            }
1033        })
1034        .collect();
1035
1036    // The record's stored fields, in declaration order: what the field
1037    // table lists, what `__field` reaches by position, and what `__build`
1038    // takes from its source one after the other.
1039    let mut descs = Vec::new();
1040    let mut builds = Vec::new();
1041    let mut reach = Vec::new();
1042    let mut reach_mut = Vec::new();
1043    let mut shapes = Vec::new();
1044    let mut checks_const = vec![if check.is_some() {
1045        quote!(true)
1046    } else {
1047        quote!(false)
1048    }];
1049    let mut ops_const = vec![quote!(false)];
1050    let mut label = None;
1051    let mut label_fields = Vec::new();
1052    let mut path_fields = Vec::new();
1053    let mut path_inits = Vec::new();
1054    let mut path_clones = Vec::new();
1055    let mut collection_names = Vec::new();
1056    let mut outbox_names = Vec::new();
1057    // What each field declares it may hold (`range`, `choices`): checked
1058    // with the record's own invariant, by the keys of the fields declaring.
1059    let mut declared_checks = Vec::new();
1060    let mut declared_keys = Vec::new();
1061    // Each field's published value schema, narrowed by its declarations.
1062    let mut schema_fns = Vec::new();
1063    let owner = snake_case(&name.to_string()).replace('_', "-");
1064    let type_name = name.to_string();
1065    let type_doc = first_doc_line(&input.attrs);
1066    for field in &fields.named {
1067        let ident = field
1068            .ident
1069            .as_ref()
1070            .ok_or_else(|| syn::Error::new(field.span(), "named field without a name"))?;
1071        let ty = &field.ty;
1072        let field_vis = &field.vis;
1073        let mut attrs = field.attrs.clone();
1074        for (given, tokens) in &given_options {
1075            if *ident == given {
1076                attrs.push(syn::parse_quote!(#[model(#tokens)]));
1077            }
1078        }
1079        let options = field_options(&attrs)?;
1080        let key = options.rename.clone().unwrap_or_else(|| ident.to_string());
1081        if !options.skip {
1082            keys.push((ident.to_string(), key.clone()));
1083        }
1084        if options.skip {
1085            // The containing type's default when it has one, which may
1086            // differ from the field type's (`is_admin: true`).
1087            builds.push(quote!(#ident: {
1088                #[allow(unused_imports, reason = "one of the two applies")]
1089                use #krate::__private::{HasDefault as _, NoDefault as _};
1090                (&#krate::__private::DefaultOf::<Self>::new())
1091                    .default_value()
1092                    .map_or_else(::core::default::Default::default, |value: Self| value.#ident)
1093            }));
1094            continue;
1095        }
1096        let index = proc_macro2::Literal::usize_unsuffixed(descs.len());
1097        let field_name = ident.to_string();
1098        let title = options.title.clone().unwrap_or_else(|| {
1099            doc_lines(&field.attrs)
1100                .into_iter()
1101                .find(|line| !line.is_empty())
1102                .map_or_else(
1103                    || humanize(&field_name),
1104                    |line| line.trim_end_matches('.').to_owned(),
1105                )
1106        });
1107        // An outbox is its own storage unit: what a change queues in it is
1108        // what reaches outside the record, and a receiver tells that from
1109        // the units the change wrote without the app's code.
1110        let outbox = last_ident(ty).is_some_and(|(name, _)| name == "Outbox");
1111        let (unit, readonly, is_label) = (options.unit || outbox, options.readonly, options.label);
1112        let label_part = label_parts
1113            .iter()
1114            .position(|part| *part == field_name)
1115            .map_or(0_u8, |position| {
1116                u8::try_from(position).unwrap_or(u8::MAX).saturating_add(1)
1117            });
1118        if label_part > 0 {
1119            label_fields.push((label_part, descs.len()));
1120        }
1121        let quiet_remove = options.quiet_remove;
1122        let atom = options.atom;
1123        let trust = options.trust(&krate)?;
1124        if is_label {
1125            if label.is_some() {
1126                return Err(syn::Error::new(
1127                    field.span(),
1128                    "one field per type is its `#[model(label)]`",
1129                ));
1130            }
1131            label = Some(descs.len());
1132        }
1133        let field_table = if options.atom {
1134            quote!(<#ty as #table::Atomic>::ATOM)
1135        } else {
1136            quote!(<#ty as #krate::Model>::TABLE)
1137        };
1138        if outbox {
1139            outbox_names.push(field_name.clone());
1140        }
1141        let keyed = last_ident(ty).is_some_and(|(name, _)| name == "Keyed" || name == "Ordered");
1142        let items = if keyed || last_ident(ty).is_some_and(|(name, _)| name == "Collection") {
1143            collection_names.push(field_name.clone());
1144            quote!(::core::option::Option::Some(&#table::ItemOpsOf::<#ty>::OPS))
1145        } else {
1146            quote!(::core::option::Option::None)
1147        };
1148        let (whole, demanded) = (options.whole, options.demanded);
1149        descs.push(quote!(#table::FieldDesc {
1150            key: #key,
1151            name: #field_name,
1152            table: #field_table,
1153            readonly: #readonly,
1154            whole: #whole,
1155            demanded: #demanded,
1156            items: #items,
1157        }));
1158        builds.push(if let Some(default) = &options.default {
1159            quote!(#ident: #table::take_or::<#ty>(source, || #default)?)
1160        } else {
1161            quote!(#ident: #table::take::<#ty>(source)?)
1162        });
1163        reach.push(quote!(#index => ::core::option::Option::Some(&value.#ident),));
1164        reach_mut.push(quote!(#index => ::core::option::Option::Some(&mut value.#ident),));
1165        checks_const.push(quote!(<#ty as #krate::Model>::CHECKS));
1166        ops_const.push(quote!(<#ty as #krate::Model>::OPS));
1167        let resource = if options.resource {
1168            quote!(::core::option::Option::Some(#krate::child::NestedResource::of::<#ty>()))
1169        } else {
1170            quote!(::core::option::Option::None)
1171        };
1172        let schema_fn = format_ident!("__schema_{}", ident);
1173        let mut narrowed = quote!(<#ty as #krate::Model>::value_schema());
1174        if let Some((low, high)) = &options.range {
1175            narrowed = quote!(#krate::schema::range(
1176                #narrowed,
1177                ::core::option::Option::Some(#krate::__private::serde_json::json!(#low)),
1178                ::core::option::Option::Some(#krate::__private::serde_json::json!(#high)),
1179            ));
1180            declared_checks.push(quote!(#krate::__private::declared_range(
1181                &value.#ident,
1182                #krate::__private::declared_bound(&(#low)),
1183                #krate::__private::declared_bound(&(#high)),
1184                #key,
1185            )?;));
1186        }
1187        if let Some(choices) = &options.choices {
1188            narrowed = quote!(#krate::schema::choices(#narrowed, &#choices));
1189            declared_checks.push(quote!(#krate::__private::declared_choices(
1190                &value.#ident,
1191                &#choices,
1192                #key,
1193            )?;));
1194        }
1195        if options.range.is_some() || options.choices.is_some() {
1196            declared_keys.push(key.clone());
1197        }
1198        if defaults {
1199            narrowed = quote!(#krate::schema::with_default(
1200                #narrowed,
1201                ::core::option::Option::Some(#krate::Model::to_json(
1202                    &<Self as ::core::default::Default>::default().#ident,
1203                )),
1204            ));
1205        }
1206        schema_fns.push(quote! {
1207            #[doc(hidden)]
1208            fn #schema_fn() -> #krate::__private::serde_json::Value {
1209                #narrowed
1210            }
1211        });
1212        let ty_text = quote!(#ty)
1213            .to_string()
1214            .replace(" < ", "<")
1215            .replace("< ", "<")
1216            .replace(" <", "<")
1217            .replace(" >", ">")
1218            .replace(" :: ", "::")
1219            .replace(":: ", "::")
1220            .replace(" ,", ",");
1221        shapes.push(quote!(#krate::FieldShape {
1222            key: #key,
1223            owner: #owner,
1224            name: #field_name,
1225            ty: #ty_text,
1226            title: #title,
1227            shape: <#ty as #krate::Model>::SHAPE,
1228            unit: #unit,
1229            readonly: #readonly,
1230            atom: #atom,
1231            label: #is_label,
1232            label_part: #label_part,
1233            quiet_remove: #quiet_remove,
1234            trust: #trust,
1235            schema: Self::#schema_fn,
1236            field_type: <#ty as #krate::Model>::field_type,
1237            text: #krate::stored_text::<#ty>,
1238            absent: #krate::absent_scalar::<#ty>,
1239            resource: #resource,
1240        }));
1241        path_fields.push(quote!(#field_vis #ident: <#ty as #krate::Model>::Paths<__R>));
1242        path_inits.push(quote!(#ident: <#ty as #krate::Model>::paths_at(
1243            path.child(#krate::Segment::Field(::std::string::String::from(#key)))
1244        )));
1245        path_clones.push(quote!(#ident: ::core::clone::Clone::clone(&self.#ident)));
1246    }
1247    if label_fields.len() != label_parts.len() {
1248        return Err(syn::Error::new(
1249            Span::call_site(),
1250            format!(
1251                "`#[model(label = \"..\")]` names {} field(s) `{name}` does not have",
1252                label_parts.len().saturating_sub(label_fields.len())
1253            ),
1254        ));
1255    }
1256    let key_of = |field: &String| {
1257        keys.iter()
1258            .find(|(name, _)| name == field)
1259            .map(|(_, key)| key.clone())
1260            .ok_or_else(|| {
1261                syn::Error::new(
1262                    Span::call_site(),
1263                    format!("`{name}` has no stored field `{field}` for its check to read"),
1264                )
1265            })
1266    };
1267    let own_check_const = check.is_some() || !declared_checks.is_empty();
1268    if !declared_checks.is_empty() {
1269        checks_const.push(quote!(true));
1270    }
1271    // A record checking only what its fields declare reads only them.
1272    let check_reads = match (check.is_some(), check_reads) {
1273        (false, _) => Some(Vec::new()),
1274        (true, reads) => reads,
1275    };
1276    let check_reads = match check_reads {
1277        Some(fields) => {
1278            let mut fields = fields.iter().map(key_of).collect::<syn::Result<Vec<_>>>()?;
1279            for key in &declared_keys {
1280                if !fields.contains(key) {
1281                    fields.push(key.clone());
1282                }
1283            }
1284            let items = check_items
1285                .iter()
1286                .map(key_of)
1287                .collect::<syn::Result<Vec<_>>>()?;
1288            quote!(::core::option::Option::Some(#table::CheckReads {
1289                fields: &[#(#fields),*],
1290                items: &[#(#items),*],
1291            }))
1292        }
1293        None if !check_items.is_empty() => {
1294            let items = check_items
1295                .iter()
1296                .map(key_of)
1297                .collect::<syn::Result<Vec<_>>>()?;
1298            quote!(::core::option::Option::Some(#table::CheckReads {
1299                fields: &[],
1300                items: &[#(#items),*],
1301            }))
1302        }
1303        None => quote!(::core::option::Option::None),
1304    };
1305    label_fields.sort_by_key(|(part, _)| *part);
1306    let label_positions: Vec<proc_macro2::Literal> = label_fields
1307        .iter()
1308        .map(|(_, position)| proc_macro2::Literal::usize_unsuffixed(*position))
1309        .collect();
1310    let label_index = label.map_or_else(
1311        || quote!(::core::option::Option::None),
1312        |position| {
1313            let position = proc_macro2::Literal::usize_unsuffixed(position);
1314            quote!(::core::option::Option::Some(#position))
1315        },
1316    );
1317    let label_with_desc = label_with.as_ref().map_or_else(
1318        || quote!(::core::option::Option::None),
1319        |_| quote!(::core::option::Option::Some(Self::__label_with)),
1320    );
1321    let label_with_fn = label_with.as_ref().map_or_else(
1322        || quote!(),
1323        |path| {
1324            quote! {
1325                #[doc(hidden)]
1326                fn __label_with(
1327                    value: &dyn ::core::any::Any,
1328                ) -> ::core::option::Option<::std::string::String> {
1329                    value.downcast_ref::<Self>().map(#path)
1330                }
1331            }
1332        },
1333    );
1334    let label_fn = if label.is_none() && label_fields.is_empty() && label_with.is_none() {
1335        quote!()
1336    } else {
1337        quote! {
1338            /// The label: what its `label = path` names it, else the texts
1339            /// of its label fields joined by spaces, else its
1340            /// `#[model(label)]` field.
1341            #[inline]
1342            fn label(&self) -> ::core::option::Option<::std::string::String> {
1343                #table::label(&Self::__RECORD, self)
1344            }
1345        }
1346    };
1347    let user_check = check
1348        .as_ref()
1349        .map(|path| quote!(#krate::__private::check_outcome(#path(value))?;));
1350    let (own_check, own_check_fns) = if own_check_const {
1351        (
1352            quote!(::core::option::Option::Some(#table::OwnCheck {
1353                check: Self::__own_check,
1354                read: Self::__read_record,
1355                reads: #check_reads,
1356            })),
1357            quote! {
1358                fn __own_check(
1359                    value: &dyn ::core::any::Any,
1360                ) -> ::core::result::Result<(), #krate::Refusal> {
1361                    match value.downcast_ref::<Self>() {
1362                        ::core::option::Option::Some(value) => {
1363                            #(#declared_checks)*
1364                            #user_check
1365                            ::core::result::Result::Ok(())
1366                        }
1367                        ::core::option::Option::None => ::core::result::Result::Ok(()),
1368                    }
1369                }
1370
1371                fn __read_record(
1372                    doc: &#krate::Doc,
1373                    obj: &#krate::__private::ObjId,
1374                ) -> ::core::result::Result<
1375                    ::std::boxed::Box<dyn ::core::any::Any>,
1376                    #krate::ModelError,
1377                > {
1378                    ::core::result::Result::Ok(::std::boxed::Box::new(
1379                        <Self as #krate::Fields>::read_fields(doc, obj)?,
1380                    ))
1381                }
1382            },
1383        )
1384    } else {
1385        (quote!(::core::option::Option::None), quote!())
1386    };
1387    let collections = if collection_names.is_empty() {
1388        quote!()
1389    } else {
1390        quote! {
1391            #[inline]
1392            fn item_collections(&self) -> ::std::vec::Vec<#krate::items::ItemCollection> {
1393                #table::item_collections(&Self::__RECORD, self)
1394            }
1395
1396            #[inline]
1397            fn item_collection_sizes(&self) -> ::std::vec::Vec<(&'static str, usize)> {
1398                #table::item_collection_sizes(&Self::__RECORD, self)
1399            }
1400
1401            #[inline]
1402            fn item_label(
1403                &self,
1404                field: &str,
1405                id: &#krate::Id,
1406            ) -> ::core::option::Option<::std::string::String> {
1407                #table::item_label(&Self::__RECORD, self, field, id)
1408            }
1409
1410            #[inline]
1411            fn item_named(
1412                &self,
1413                field: &str,
1414                reference: &str,
1415            ) -> ::core::result::Result<#krate::Id, #krate::Refusal> {
1416                #table::item_named(&Self::__RECORD, self, field, reference)
1417            }
1418
1419            #[inline]
1420            fn item_named_as(
1421                &self,
1422                field: &str,
1423                what: (&str, &str),
1424                reference: &str,
1425            ) -> ::core::result::Result<#krate::Id, #krate::Refusal> {
1426                #table::item_named_as(
1427                    &Self::__RECORD,
1428                    self,
1429                    field,
1430                    ::core::option::Option::Some(what),
1431                    reference,
1432                )
1433            }
1434
1435            #[inline]
1436            fn item_holds(&self, field: &str, id: &str) -> bool {
1437                #table::item_holds(&Self::__RECORD, self, field, id)
1438            }
1439
1440            #[inline]
1441            fn item_id_any(&self, reference: &str) -> bool {
1442                #table::item_id_any(&Self::__RECORD, self, reference)
1443            }
1444
1445            #[inline]
1446            fn item_search(&self) -> ::std::vec::Vec<#krate::items::ItemText> {
1447                #table::item_search(&Self::__RECORD, self)
1448            }
1449        }
1450    };
1451    let nested_fn = if collection_names.is_empty() {
1452        quote!()
1453    } else {
1454        quote! {
1455            #[inline]
1456            fn nested_collections(&self) -> ::std::vec::Vec<#krate::items::ItemCollection> {
1457                #table::item_collections(&Self::__RECORD, self)
1458            }
1459        }
1460    };
1461    let reach_value = if reach.is_empty() {
1462        quote!(let _ = value;)
1463    } else {
1464        quote!(let value = value.downcast_ref::<Self>()?;)
1465    };
1466    let reach_value_mut = if reach.is_empty() {
1467        quote!(let _ = value;)
1468    } else {
1469        quote!(let value = value.downcast_mut::<Self>()?;)
1470    };
1471    let paths_doc = format!("The typed paths into a [`{name}`], one per field.");
1472    let paths_fn_doc = format!("The typed paths into a [`{name}`], rooted at it.");
1473    let fields_table = table_const(
1474        input,
1475        &table,
1476        |ty| quote!(#table::ModelTable::of_resource(&#ty::__RECORD)),
1477    );
1478    Ok(quote! {
1479        impl #impl_generics #name #type_generics #where_clause {
1480            /// The record as data: its fields' table and how to reach them.
1481            #[doc(hidden)]
1482            pub const __RECORD: #table::ResourceDesc = #table::ResourceDesc {
1483                fields: &[#(#descs),*],
1484                field: Self::__field,
1485                field_mut: Self::__field_mut,
1486                build: Self::__build,
1487                empty: #table::empty_of::<Self>,
1488                unwrap: #table::unwrap_of::<Self>,
1489                replace: #table::replace_of::<Self>,
1490                own_check: #own_check,
1491                label: #label_index,
1492                label_parts: &[#(#label_positions),*],
1493                label_with: #label_with_desc,
1494                name: ::core::any::type_name::<Self>,
1495                shape: <Self as #krate::Model>::SHAPE,
1496                checks: <Self as #krate::Model>::CHECKS,
1497                has_ops: <Self as #krate::Model>::OPS,
1498            };
1499
1500            #label_with_fn
1501
1502            #[allow(clippy::match_single_binding, reason = "a record with no stored fields leaves only the fallback arm")]
1503            fn __field(
1504                value: &dyn ::core::any::Any,
1505                index: usize,
1506            ) -> ::core::option::Option<&dyn ::core::any::Any> {
1507                #reach_value
1508                match index {
1509                    #(#reach)*
1510                    _ => ::core::option::Option::None,
1511                }
1512            }
1513
1514            #[allow(clippy::match_single_binding, reason = "a record with no stored fields leaves only the fallback arm")]
1515            fn __field_mut(
1516                value: &mut dyn ::core::any::Any,
1517                index: usize,
1518            ) -> ::core::option::Option<&mut dyn ::core::any::Any> {
1519                #reach_value_mut
1520                match index {
1521                    #(#reach_mut)*
1522                    _ => ::core::option::Option::None,
1523                }
1524            }
1525
1526            fn __build(
1527                source: &mut dyn #table::FieldSource,
1528                out: &mut dyn ::core::any::Any,
1529            ) -> ::core::result::Result<(), #krate::ModelError> {
1530                let _ = &source;
1531                #table::put(out, Self { #(#builds,)* })
1532            }
1533
1534            #own_check_fns
1535
1536            #(#schema_fns)*
1537
1538            /// The fields holding a `Collection`, by name: where actions on
1539            /// an item can act.
1540            #[doc(hidden)]
1541            pub const __COLLECTIONS: &'static [&'static str] = &[#(#collection_names),*];
1542
1543            /// Whether the type holds an invariant of its own
1544            /// (`#[model(check = path)]`), which a change of one item
1545            /// cannot be checked against without the whole value.
1546            #[doc(hidden)]
1547            pub const __OWN_CHECK: bool = #own_check_const;
1548
1549            /// The fields holding an `Outbox`, by name: verbs may act on an
1550            /// entry of one (`#[action(item = field)]`).
1551            #[doc(hidden)]
1552            pub const __OUTBOXES: &'static [&'static str] = &[#(#outbox_names),*];
1553
1554            #[doc = #paths_fn_doc]
1555            #vis fn paths() -> #paths_name<Self, #(#generic_args),*> {
1556                <Self as #krate::Model>::paths_at(#krate::Path::root())
1557            }
1558        }
1559
1560        impl #impl_generics #krate::Model for #name #type_generics #where_clause {
1561            const SHAPE: #krate::Shape = #krate::Shape::Record(&[#(#shapes),*]);
1562            const CHECKS: bool = #(#checks_const)||*;
1563            const OPS: bool = #(#ops_const)||*;
1564            #fields_table
1565            type Paths<__R> = #paths_name<__R, #(#generic_args),*>;
1566
1567            fn paths_at<__R>(path: #krate::Path<__R, Self>) -> Self::Paths<__R> {
1568                #paths_name {
1569                    #(#path_inits,)*
1570                    __path: path,
1571                }
1572            }
1573
1574            #[inline]
1575            fn to_json(&self) -> #krate::__private::serde_json::Value {
1576                #table::to_json(&Self::__RECORD, self)
1577            }
1578
1579            #[inline]
1580            fn from_json(
1581                value: &#krate::__private::serde_json::Value,
1582            ) -> ::core::result::Result<Self, #krate::ModelError> {
1583                let mut out = ::core::option::Option::None;
1584                #table::from_json(&Self::__RECORD, value, &mut out)?;
1585                #table::filled(out)
1586            }
1587
1588            #[inline]
1589            fn edit(
1590                doc: &mut #krate::Doc,
1591                slot: #krate::Slot<'_>,
1592                path: &[#krate::Segment],
1593                op: &#krate::EditOp,
1594                cx: &mut #krate::ActionCx,
1595            ) -> ::core::result::Result<(), #krate::ModelError> {
1596                #table::edit(&Self::__RECORD, doc, slot, path, op, cx)
1597            }
1598
1599            #[inline]
1600            fn check(&self) -> ::core::result::Result<(), #krate::Refusal> {
1601                #table::check(&Self::__RECORD, self)
1602            }
1603
1604            #label_fn
1605
1606            #[inline]
1607            fn op_coalesces(
1608                path: &[#krate::Segment],
1609                previous: &#krate::__private::serde_json::Value,
1610                next: &#krate::__private::serde_json::Value,
1611            ) -> ::core::option::Option<bool> {
1612                #table::op_coalesces(&Self::__RECORD, path, previous, next)
1613            }
1614
1615            #[inline]
1616            fn op_continuable(
1617                path: &[#krate::Segment],
1618                op: &#krate::__private::serde_json::Value,
1619            ) -> ::core::option::Option<bool> {
1620                #table::op_continuable(&Self::__RECORD, path, op)
1621            }
1622
1623            #[inline]
1624            fn diff<__E>(
1625                &self,
1626                after: &Self,
1627                path: &[#krate::Segment],
1628                out: &mut ::std::vec::Vec<#krate::Edit<__E>>,
1629            ) {
1630                #table::diff_into(&Self::__RECORD, self, after, path, out);
1631            }
1632
1633            #[inline]
1634            fn op_describe(
1635                path: &[#krate::Segment],
1636                op: &#krate::__private::serde_json::Value,
1637            ) -> ::core::option::Option<#krate::path::OpDescription> {
1638                #table::op_describe(&Self::__RECORD, path, op)
1639            }
1640
1641            #[inline]
1642            fn op_lands(
1643                &self,
1644                path: &[#krate::Segment],
1645                op: &#krate::__private::serde_json::Value,
1646            ) -> ::core::option::Option<#krate::Place> {
1647                #table::op_lands(&Self::__RECORD, self, path, op)
1648            }
1649
1650            #[inline]
1651            fn op_schemas(
1652                prefix: &str,
1653                out: &mut ::std::vec::Vec<(::std::string::String, #krate::__private::serde_json::Value)>,
1654            ) {
1655                #table::op_schemas(&Self::__RECORD, prefix, out);
1656            }
1657
1658            #[inline]
1659            fn get_at(
1660                &self,
1661                path: &[#krate::Segment],
1662            ) -> ::core::option::Option<&dyn ::core::any::Any> {
1663                #table::get_at(&Self::__RECORD, self, path)
1664            }
1665
1666            #[inline]
1667            fn load(
1668                doc: &#krate::Doc,
1669                value: &#krate::__private::Value<'_>,
1670                id: &#krate::__private::ObjId,
1671            ) -> ::core::result::Result<Self, #krate::ModelError> {
1672                let mut out = ::core::option::Option::None;
1673                #table::load(&Self::__RECORD, doc, value, id, &mut out)?;
1674                #table::filled(out)
1675            }
1676            #nested_fn
1677
1678            #[inline(never)]
1679            fn value_schema() -> #krate::__private::serde_json::Value {
1680                #krate::__private::resource_value_schema(<Self as #krate::Model>::SHAPE)
1681            }
1682
1683            fn field_type(types: &mut #krate::TypeSet) -> #krate::FieldType {
1684                #krate::surface::resource_type(
1685                    types,
1686                    ::core::any::type_name::<Self>(),
1687                    #type_name,
1688                    #type_doc,
1689                    <Self as #krate::Model>::SHAPE,
1690                )
1691            }
1692
1693            #[inline]
1694            fn missing() -> ::core::result::Result<Self, #krate::ModelError> {
1695                let mut out = ::core::option::Option::None;
1696                #table::missing(&Self::__RECORD, &mut out)?;
1697                #table::filled(out)
1698            }
1699
1700            #[inline]
1701            fn store(
1702                &self,
1703                doc: &mut #krate::Doc,
1704                slot: #krate::Slot<'_>,
1705            ) -> ::core::result::Result<(), #krate::ModelError> {
1706                #table::store(&Self::__RECORD, self, doc, slot)
1707            }
1708
1709            #[inline]
1710            fn stores_as(&self, before: &Self) -> bool {
1711                #table::stores_as(&Self::__RECORD, self, before)
1712            }
1713
1714            #[inline]
1715            fn store_changed(
1716                &self,
1717                before: &Self,
1718                doc: &mut #krate::Doc,
1719                slot: #krate::Slot<'_>,
1720                dirty: &#krate::Delta,
1721            ) -> ::core::result::Result<(), #krate::ModelError> {
1722                #table::store_changed(&Self::__RECORD, self, before, doc, slot, dirty)
1723            }
1724
1725            #[inline]
1726            fn refresh(
1727                &mut self,
1728                doc: &#krate::Doc,
1729                value: &#krate::__private::Value<'_>,
1730                id: &#krate::__private::ObjId,
1731                delta: &#krate::Delta,
1732            ) -> ::core::result::Result<(), #krate::ModelError> {
1733                #table::refresh(&Self::__RECORD, self, doc, value, id, delta)
1734            }
1735
1736            #[inline]
1737            fn collect_text(&self, out: &mut ::std::vec::Vec<::std::string::String>) {
1738                #table::collect_text(&Self::__RECORD, self, out);
1739            }
1740        }
1741
1742        impl #impl_generics #krate::Settable for #name #type_generics #where_clause {}
1743
1744        impl #impl_generics #krate::Fields for #name #type_generics #where_clause {
1745            const ITEM_FIELDS: &'static [&'static str] = Self::__COLLECTIONS;
1746
1747            #[inline]
1748            fn read_fields(
1749                doc: &#krate::Doc,
1750                obj: &#krate::__private::ObjId,
1751            ) -> ::core::result::Result<Self, #krate::ModelError> {
1752                let mut out = ::core::option::Option::None;
1753                #table::read_fields(&Self::__RECORD, doc, obj, &mut out)?;
1754                #table::filled(out)
1755            }
1756
1757            #[inline]
1758            fn write_fields(
1759                &self,
1760                doc: &mut #krate::Doc,
1761                obj: &#krate::__private::ObjId,
1762            ) -> ::core::result::Result<(), #krate::ModelError> {
1763                #table::write_fields(&Self::__RECORD, self, doc, obj)
1764            }
1765
1766            #[inline]
1767            fn write_changed_fields(
1768                &self,
1769                before: &Self,
1770                doc: &mut #krate::Doc,
1771                obj: &#krate::__private::ObjId,
1772                dirty: &#krate::Delta,
1773            ) -> ::core::result::Result<(), #krate::ModelError> {
1774                #table::write_changed_fields(&Self::__RECORD, self, before, doc, obj, dirty)
1775            }
1776
1777            #[inline]
1778            fn edit_fields(
1779                doc: &mut #krate::Doc,
1780                obj: &#krate::__private::ObjId,
1781                path: &[#krate::Segment],
1782                op: &#krate::EditOp,
1783                cx: &mut #krate::ActionCx,
1784            ) -> ::core::result::Result<(), #krate::ModelError> {
1785                #table::edit_fields(&Self::__RECORD, doc, obj, path, op, cx)
1786            }
1787
1788            #collections
1789
1790            #[inline]
1791            fn refresh_fields(
1792                &mut self,
1793                doc: &#krate::Doc,
1794                obj: &#krate::__private::ObjId,
1795                delta: &#krate::Delta,
1796            ) -> ::core::result::Result<(), #krate::ModelError> {
1797                #table::refresh_fields(&Self::__RECORD, self, doc, obj, delta)
1798            }
1799        }
1800
1801        #[doc = #paths_doc]
1802        #vis struct #paths_name #paths_impl_generics #where_clause {
1803            #(#path_fields,)*
1804            __path: #krate::Path<__R, #name #type_generics>,
1805        }
1806
1807        impl #paths_impl_generics ::core::clone::Clone for #paths_name #paths_type_generics #where_clause {
1808            fn clone(&self) -> Self {
1809                Self {
1810                    #(#path_clones,)*
1811                    __path: ::core::clone::Clone::clone(&self.__path),
1812                }
1813            }
1814        }
1815
1816        impl #paths_impl_generics #paths_name #paths_type_generics #where_clause {
1817            /// The path of the whole value.
1818            #vis fn path(&self) -> &#krate::Path<__R, #name #type_generics> {
1819                &self.__path
1820            }
1821        }
1822    })
1823}
1824
1825fn snake_case(name: &str) -> String {
1826    let mut out = String::new();
1827    for (index, c) in name.chars().enumerate() {
1828        if c.is_uppercase() {
1829            if index > 0 {
1830                out.push('_');
1831            }
1832            out.extend(c.to_lowercase());
1833        } else {
1834            out.push(c);
1835        }
1836    }
1837    out
1838}
1839
1840fn humanize(name: &str) -> String {
1841    let words = name.replace('_', " ");
1842    let mut chars = words.chars();
1843    chars.next().map_or_else(String::new, |first| {
1844        first.to_uppercase().chain(chars).collect()
1845    })
1846}
1847
1848/// The first sentence of the doc comment in `attrs`, its lines joined, or
1849/// empty: what a published type says it is.
1850fn first_doc_line(attrs: &[Attribute]) -> String {
1851    let lines = doc_lines(attrs);
1852    let paragraph: Vec<&str> = lines
1853        .iter()
1854        .map(String::as_str)
1855        .skip_while(|line| line.is_empty())
1856        .take_while(|line| !line.is_empty())
1857        .collect();
1858    let text = paragraph.join(" ");
1859    match text.find(". ") {
1860        Some(end) => text.get(..=end).unwrap_or_default().to_owned(),
1861        None => text,
1862    }
1863}
1864
1865fn doc_lines(attrs: &[Attribute]) -> Vec<String> {
1866    attrs
1867        .iter()
1868        .filter(|attr| attr.path().is_ident("doc"))
1869        .filter_map(|attr| match &attr.meta {
1870            Meta::NameValue(MetaNameValue {
1871                value:
1872                    Expr::Lit(ExprLit {
1873                        lit: Lit::Str(text),
1874                        ..
1875                    }),
1876                ..
1877            }) => Some(text.value().trim().to_owned()),
1878            _ => None,
1879        })
1880        .collect()
1881}
1882
1883fn last_ident(ty: &Type) -> Option<(String, Option<&Type>)> {
1884    let Type::Path(path) = ty else { return None };
1885    let segment = path.path.segments.last()?;
1886    let inner = match &segment.arguments {
1887        PathArguments::AngleBracketed(args) => args.args.iter().find_map(|arg| match arg {
1888            GenericArgument::Type(ty) => Some(ty),
1889            _ => None,
1890        }),
1891        _ => None,
1892    };
1893    Some((segment.ident.to_string(), inner))
1894}
1895
1896/// The declared type of a parameter of Rust type `ty`, and whether it is
1897/// optional. An app's own type is what its schema says it is written as
1898/// when `schema` (the type implements `JsonSchema`), else an object.
1899/// The parameter type of `ty` when its name says it, and whether it is
1900/// optional; `None` for a type whose schema says it.
1901/// Whether `ty` is a resource's address (`String`, `Id`, ...) rather than a reference record:
1902/// what a parameter picking one of an existing resource declares when the verb stores its
1903/// address.
1904fn is_address_type(ty: &Type) -> bool {
1905    match last_ident(ty) {
1906        Some((name, None)) => matches!(name.as_str(), "String" | "Id" | "Uuid" | "Atom"),
1907        Some((name, Some(inner))) if name == "Option" => is_address_type(inner),
1908        _ => false,
1909    }
1910}
1911
1912fn known_param_type(ty: &Type) -> (Option<Tokens>, bool) {
1913    let krate = krate();
1914    let pt = quote!(#krate::__private::ParamType);
1915    let (name, inner) = last_ident(ty).unwrap_or_default();
1916    match name.as_str() {
1917        "Option" => inner.map_or_else(
1918            || (Some(quote!(#pt::Object)), true),
1919            |inner| (known_param_type(inner).0, true),
1920        ),
1921        "String" | "Id" | "Uuid" | "Atom" => (Some(quote!(#pt::Text)), false),
1922        "f32" | "f64" => (Some(quote!(#pt::Number)), false),
1923        "i8" | "i16" | "i32" | "i64" | "u8" | "u16" | "u32" | "u64" | "usize" | "isize" => {
1924            (Some(quote!(#pt::Integer)), false)
1925        }
1926        "bool" => (Some(quote!(#pt::Boolean)), false),
1927        "Vec" => (Some(quote!(#pt::Array)), false),
1928        _ => (None, false),
1929    }
1930}
1931
1932/// The type whose schema says the parameter type of `ty`: the present value
1933/// of an `Option`, else `ty`.
1934fn schema_param_type(ty: &Type) -> &Type {
1935    match last_ident(ty) {
1936        Some((name, Some(inner))) if name == "Option" => schema_param_type(inner),
1937        _ => ty,
1938    }
1939}
1940
1941/// The value a parameter of `ty` carries, past the wrappers whose JSON form is
1942/// their element's: what must describe itself for the parameter to publish a
1943/// type, so the refusal names it rather than the wrapper.
1944fn parameter_value_type(ty: &Type) -> &Type {
1945    match last_ident(ty) {
1946        Some((name, Some(inner))) if matches!(name.as_str(), "Option" | "Vec" | "Box" | "Arc") => {
1947            parameter_value_type(inner)
1948        }
1949        _ => ty,
1950    }
1951}
1952
1953/// The owned type an argument is carried as in the action payload, and
1954/// whether the method borrows it (`&str` is carried as `String`, `&[T]` as
1955/// `Vec<T>`, `&T` as `T`).
1956fn owned_type(ty: &Type) -> (Type, bool) {
1957    let Type::Reference(reference) = ty else {
1958        return (ty.clone(), false);
1959    };
1960    let owned = match &*reference.elem {
1961        Type::Path(path) if path.path.is_ident("str") => syn::parse_quote!(::std::string::String),
1962        Type::Slice(slice) => {
1963            let elem = &slice.elem;
1964            syn::parse_quote!(::std::vec::Vec<#elem>)
1965        }
1966        elem => elem.clone(),
1967    };
1968    (owned, true)
1969}
1970
1971fn is_action_cx(ty: &Type) -> bool {
1972    let Type::Reference(reference) = ty else {
1973        return false;
1974    };
1975    // An action that only reads the context takes it shared; one that mints
1976    // ids takes it mutably.
1977    last_ident(&reference.elem).is_some_and(|(name, _)| name == "ActionCx")
1978}
1979
1980/// Turn a record's `#[action]` methods into its replayable, published action
1981/// vocabulary, and implement `Resource` for it.
1982///
1983/// ```ignore
1984/// #[resource(kind = "example.note")]
1985/// impl Note {
1986///     /// Replace the note's text.
1987///     #[action]
1988///     pub fn edit(&mut self, #[param("Note text")] text: String) { self.body = text; }
1989/// }
1990/// ```
1991///
1992/// The record is called by the message `example-note` of the crate's
1993/// `locales/en-US.ftl` and each action by `<kind>-<id>` (`example-note-edit`),
1994/// read in the person's language whenever it is published; a key the
1995/// catalogue does not hold does not build. Each parameter is called by
1996/// `<action key>-<param>`, else `<kind>-<param>`, where the catalogue has it.
1997///
1998/// Generates, per action, a parameter struct in a module named after the
1999/// type (`note::Edit { text }`, with a JSON Schema derived from the
2000/// parameter types), a variant of `NoteAction` carrying it, and
2001/// `Note::EDIT`, an `ActionRef` views bind controls to and tests apply;
2002/// then `impl Resource`. Field edits are a built-in variant.
2003///
2004/// An action method takes `&mut self`, optionally `cx: &mut ActionCx` (or
2005/// `cx: &ActionCx`, for one that only reads it) and
2006/// `&mut Outbox<T>` fields of the record (by field name: such an action
2007/// reaches outside the document), then its parameters, and returns `()` or
2008/// `Result<(), impl Into<Refusal>>`. Its public id is its name in kebab case
2009/// unless `#[action(id = "...")]`; a parameter is published under its name
2010/// unless `#[param(name = "...")]`, and `#[param("Description", example =
2011/// value)]` describes it.
2012///
2013/// An action whose first parameter is an item `Id` is also published on each
2014/// item of the collection it acts on, with the id bound: the collection named
2015/// like the parameter, or the record's only one; `#[action(item = field)]`
2016/// names it otherwise, and anything else does not compile.
2017///
2018/// Action options: `label = "key"` (another key of the catalogue), `destructive` (it deletes or overwrites:
2019/// when Undo takes it back, as it does any change of the document alone, it
2020/// runs at once and offers Undo; otherwise people confirm it, through any
2021/// API), `irreversible` (it also loses what Undo cannot bring back, such
2022/// as a secret every device forgets: a destructive one is confirmed even
2023/// though Undo reverts its document change), `housekeeping` (a change
2024/// about the record rather than to it,
2025/// such as a read marker), `external` (content from outside, nobody's undo
2026/// step), `local` (an action of a record with a `queue` that queues nothing,
2027/// so an undoable change rather than one reaching outside), `by_app` (the
2028/// app's own bookkeeping of the record, such as what its engine listed: only
2029/// the app's code applies it, on a record it holds; it is declared to no
2030/// caller, so it is not published, nothing builds it by its id, and `apply`,
2031/// `group` and every API refuse it), `field = "..."` (an action that writes only that field is placed
2032/// below it, so a grant on the field reaches it: someone who may only
2033/// comment may add to the `comments`).
2034///
2035/// Resource options: `label`, `params = module` (the parameter module's
2036/// name), `initialize = path` (`fn() -> Self`, the deterministic genesis),
2037/// `seed = path` (`fn(&mut Self, &mut ActionCx)`, the creator's first
2038/// content), `available = path` (`fn(&Self, module::Verb) -> Availability`),
2039/// `children = path` (`fn(&Self) -> Vec<Derived<Self>>`), `child = path`
2040/// (`fn(&Self, &str) -> Option<ResourceSpec>`, a child the published page of
2041/// `children` leaves out), `search = path`,
2042/// `scopes = path`, `read_content = path` (`fn(&Self, Option<&Id>) ->
2043/// Result<serde_json::Value, String>`), `read_content_in_doc = path` (the same
2044/// read, `fn(&Self, &Doc, Option<&Id>) -> ...`, for one that needs the
2045/// document itself), `read = false` (the record answers no read on purpose:
2046/// what it holds must not reach anyone holding its path, and its doc comment
2047/// says why), `facts = path` (`fn(&Self) -> Result<serde_json::Value,
2048/// String>`, the compact summary `Resource::facts` states) and `views = path`.
2049#[proc_macro_attribute]
2050pub fn resource(attr: TokenStream, item: TokenStream) -> TokenStream {
2051    let options = match verbs::resource_options(attr) {
2052        Ok(options) => options,
2053        Err(error) => return error.to_compile_error().into(),
2054    };
2055    let mut item = parse_macro_input!(item as ItemImpl);
2056    match verbs::expand(&options, &mut item) {
2057        Ok(tokens) => tokens.into(),
2058        Err(error) => error.to_compile_error().into(),
2059    }
2060}
2061
2062mod verbs;