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