Skip to main content

ignite_macros/
lib.rs

1//! Derive macro for Ignite resources: `#[derive(IgniteResource)]`.
2//!
3//! The derive reads an Orbit model and writes the `ignite_core::IgniteResource` impl that
4//! the panel needs: the form fields, the list columns, the query methods, and
5//! the input struct that create and update take. The model must also derive
6//! `OrbitModel` and `Serialize`, because the derive does not write them.
7
8use proc_macro::TokenStream;
9use proc_macro2::{Span, TokenStream as TokenStream2};
10use quote::{format_ident, quote};
11use syn::{
12    parse_macro_input, Data, DeriveInput, Fields, GenericArgument, LitBool, LitStr, PathArguments,
13    Token, Type,
14};
15
16/// Writes `impl ignite_core::IgniteResource` for a struct that models a table.
17///
18/// Struct attributes:
19/// - `#[ignite(table = widgets)]`: the table, required. Its name is the URL slug, and it must be the
20///   table of the model's `#[orbit(table = ...)]` (or the default name of the struct). A mismatch is a
21///   compile error.
22/// - `#[ignite(title = "Widgets")]`: the heading and nav label. Defaults to the table name, capitalized.
23/// - `#[ignite(singular = "Widget")]`: the name of one record, for "New Widget". Defaults to the title without a trailing `s`.
24/// - `#[ignite(navigation_label = "All widgets")]`: the label of the resource's navigation entry, as Filament's `$navigationLabel`. Defaults to the title.
25/// - `#[ignite(navigation_group = "Shop")]`: the navigation group the entry is listed under, as Filament's `$navigationGroup`. Defaults to none: the entry is listed before the groups.
26/// - `#[ignite(navigation_sort = 2)]`: the entry's place, as Filament's `$navigationSort`: lower first. Defaults to none, which comes before any number.
27/// - `#[ignite(navigation_parent_item = "Posts")]`: the navigation entry the resource is listed under, as Filament's `$navigationParentItem`: the parent's label or slug, in the same navigation group. Defaults to none: the resource is an entry of its own.
28/// - `#[ignite(navigation_parent_items = ["Posts", "Pages"])]`: more navigation entries the resource is listed under, each by label or slug: it is listed under each of them that the sidebar shows, as a taxonomy's screen under every post type it is attached to (Filament takes one parent item; this is Ignite's addition). Defaults to none.
29/// - `#[ignite(should_register_navigation = false)]`: leaves the resource out of the sidebar, as Filament's `$shouldRegisterNavigation`, and with it the entries listed only under it. Its pages still answer. Defaults to `true`.
30/// - `#[ignite(navigation_icon = "post")]`: the name of the entry's icon, as Filament's `$navigationIcon`: what the resource is (`post`, `page`, `media`, `comment`, `users`, `settings`, or a name of the app's own), not a CSS class. The admin theme maps the name to its icon. Defaults to the theme's generic resource icon.
31/// - `#[ignite(navigation_create_item = false)]`: leaves the create link out of the resource's navigation group. Defaults to `true`: the entry's group lists a link to the create page, for a user who may create a record.
32/// - `#[ignite(navigation_create_label = "Add New Post")]`: the label of that create link. Defaults to `"Add new"`.
33/// - `#[ignite(conditions = post_conditions)]`: the conditions that show or hide the form's fields, and the live fields, as Filament's `visible()`, `hidden()` and `live()`: the path of a `fn() -> ignite_core::FieldConditions`. Defaults to none: every field shows. A field that a condition may hide should be an `Option`, so it is NULL on create and keeps its stored value on update.
34/// - `#[ignite(tabs = post_tabs)]`: the tabs of the list page, as Filament's `getTabs()`: the path of a `fn() -> Vec<ignite_core::Tab>`. The list query applies the active tab's conditions. Defaults to none: the list has no tabs.
35/// - `#[ignite(default_active_tab = "drafts")]`: the key of the tab shown when the list has no `tab` parameter, as Filament's `getDefaultActiveTab()`. Defaults to the first tab.
36/// - `#[ignite(tab_counts_follow_search = true)]`: each tab's count is for the current search. Defaults to `false`: a tab counts all its rows, as a Filament tab's `badge()` counts its own query.
37/// - `#[ignite(hide_empty_tabs = false)]`: renders the tabs whose count is 0 too. Defaults to `true`: an empty tab is left out, except the default tab and the tab shown.
38/// - `#[ignite(badges = post_badges)]`: the list columns shown as coloured badges, as Filament's `badge()` and `color()` on a text column: the path of a `fn() -> ignite_core::ColumnBadges`. Defaults to none: every cell is plain text.
39/// - `#[ignite(bulk_actions = post_bulk_actions)]`: the actions on the records ticked in the list, as Filament's `toolbarActions()`: the path of a `fn() -> Vec<ignite_core::BulkAction>`. Defaults to none: the list has no checkboxes.
40/// - `#[ignite(row_actions = post_actions)]`: the actions on each row of the list, as Filament's `recordActions()`: the path of a `fn() -> Vec<ignite_core::RowAction>`. Defaults to none: each row has its Edit and Delete buttons only.
41/// - `#[ignite(hide_default_delete_when = in_trash)]`: hides the built-in Delete button (and refuses the delete) on the records that meet a filter, as Filament's `DeleteAction::make()->hidden(...)`: the path of a `fn() -> ignite_core::ListFilter`. Defaults to none.
42/// - `#[ignite(form_layout = post_layout)]`: the layout of the create and edit forms, as Filament's `Grid`, `Section`, `Group`, `columns()` and `columnSpan()`: the path of a `fn() -> ignite_core::FormLayout`. Defaults to none: the form renders as one card of fields.
43///
44/// Field attributes:
45/// - `primary_key`: the key column. Defaults to a field named `id`.
46/// - `label = "..."`: the label. Defaults to the field name, capitalized and spaced.
47/// - `form_type = "text" | "textarea" | "password" | "number" | "checkbox" | "date"`: the input. Defaults from the type.
48/// - `form_type = "email" | "url" | "color" | "link" | "wysiwyg" | "image" | "file" | "gallery"`: the field types for custom fields (see `ignite_core::FieldKind`). The field must be a `String`; an `image` or `file` may also be an integer, the media item's id. A `link` and a `gallery` store JSON text.
49/// - `form_type = "radio"` with `options = [...]`: the choices as radio buttons. `form_type = "post_object" | "taxonomy" | "user"` with `options = load_choices` or `belongs_to`: a lookup of that kind. `form_type = "relationship"` with `options = load_choices`: several choices, stored as a JSON list in a `String`.
50/// - `form_type = "repeater" | "group" | "clone"` with `fields = SUB_FIELDS`, or `form_type = "flexible_content"` with `blocks = BLOCKS`: a structured field whose sub-fields are a `&'static [ignite_core::Field]` (or blocks a `&'static [ignite_core::Block]`) constant. The field must be a `String`, and stores JSON text.
51/// - `options = [("draft", "Draft"), ...]`: a select with a fixed list of choices. The field must be a `String`.
52/// - `options = load_choices`: a select whose choices come from an async function, `async fn(&Database) -> Result<Vec<(String, String)>, orbit_orm::Error>`, called each time the form is shown. The field must be a `String` or an integer.
53/// - `belongs_to = Category, display = name`: a relation. `Category` is the related model (an `OrbitModel`). The field stores the related row's key, the select lists the related table's rows by `display`, and the list shows that name. The field must be an `i32` or `i64`.
54/// - `step = "0.01"`: the browser's step for an `f32` or `f64` input. The default is `"any"`.
55/// - `required` or `required = false`: whether a blank value is rejected. An `Option` field is optional by default and `required` makes it required. A field that is not an `Option` is always required: `required = false` on it is a compile error (make it an `Option` instead). A `bool` is the exception: it is a checkbox and is never blank.
56/// - `searchable`, `sortable`: the list's search and sort columns.
57/// - `hidden_on_index`: leaves the column out of the list.
58///
59/// Supported field types: `String`, `i16`, `i32`, `i64`, `f32`, `f64`, `bool`,
60/// `chrono::NaiveDate`, `chrono::NaiveDateTime`, and `Option` of any of them. The primary
61/// key must be `i32` or `i64`. A `String` field is a text input (or a textarea, a password
62/// or a select, by attribute); an `f32` or `f64` is a decimal input; a `NaiveDateTime` is a
63/// date-and-time input; a `bool` is a checkbox.
64///
65/// Saving: create writes every field; an `Option` field left blank is NULL. Update writes
66/// every field the form sent: an `Option` field sent blank is written as NULL, so a user
67/// clears an optional value by emptying it on the edit form (since 0.3.0; before, a blank
68/// optional field was skipped on update and kept its value), and an `Option` field the form
69/// did not send at all is left out, so its stored value is kept. A password field is the
70/// exception: left blank on edit, it is not written, so the stored hash is kept. A checkbox
71/// is never blank: one the form did not send is `false`. A field that is not an `Option` is
72/// required. Errors are keyed by the field's name in `ignite_core::FieldErrors`, whose keys
73/// are owned `String`s since 0.3.0.
74///
75/// The generated input struct (`<Model>Input`) has a hidden `__ignite_sent` field that
76/// records which optional fields the form sent. `validate` and `validate_update` fill it.
77/// Code that builds the input with a struct literal must set it (since 0.3.0):
78/// `__ignite_sent: Vec::new()` keeps the stored value of every optional field that is `None`
79/// on update, and listing a field's name, as in `vec!["note"]`, writes NULL for it. An update
80/// that has nothing to write runs no query, and returns the row (or `NotFound`).
81#[proc_macro_derive(IgniteResource, attributes(ignite))]
82pub fn derive_ignite_resource(input: TokenStream) -> TokenStream {
83    let input = parse_macro_input!(input as DeriveInput);
84    match expand(&input) {
85        Ok(tokens) => tokens.into(),
86        Err(error) => error.to_compile_error().into(),
87    }
88}
89
90/// One field of the model, with its attributes resolved.
91struct Field {
92    ident: syn::Ident,
93    ty: Type,
94    /// The inner type, for `Option<T>`; otherwise the type itself.
95    inner: Type,
96    /// What the inner type parses from form text.
97    base: Base,
98    optional: bool,
99    kind: Kind,
100    label: String,
101    required: bool,
102    primary_key: bool,
103    searchable: bool,
104    sortable: bool,
105    hidden_on_index: bool,
106    /// A password: hashed on save, and blank on an edit keeps the stored hash.
107    is_password: bool,
108    /// The choices of a static select.
109    choices: Vec<(String, String)>,
110    /// Where a lookup field's choices come from.
111    lookup: Option<Lookup>,
112    /// The step of a decimal input, as written.
113    step: Option<String>,
114    /// The sub-fields of a repeater, group or clone, or the blocks of a flexible content
115    /// field: the path of a constant.
116    sub_fields: Option<syn::Path>,
117}
118
119#[derive(Clone, Copy, PartialEq, Eq)]
120enum Kind {
121    Text,
122    Textarea,
123    Password,
124    Number,
125    Decimal,
126    Checkbox,
127    Select,
128    Lookup,
129    Date,
130    DateTime,
131    Email,
132    Url,
133    Radio,
134    Color,
135    Image,
136    File,
137    Link,
138    Wysiwyg,
139    PostObject,
140    Relationship,
141    Taxonomy,
142    User,
143    Repeater,
144    Group,
145    FlexibleContent,
146    Gallery,
147    Clone,
148}
149
150impl Kind {
151    /// Whether `ignite_core::Field::check_value` checks the field's text: the kinds added
152    /// for custom fields, except the lookups stored as an integer.
153    fn checks_value(self) -> bool {
154        !matches!(
155            self,
156            Kind::Text
157                | Kind::Textarea
158                | Kind::Password
159                | Kind::Number
160                | Kind::Decimal
161                | Kind::Checkbox
162                | Kind::Select
163                | Kind::Lookup
164                | Kind::Date
165                | Kind::DateTime
166        )
167    }
168}
169
170/// The Rust base type the field parses from form text.
171#[derive(Clone, Copy, PartialEq, Eq)]
172enum Base {
173    Text,
174    Integer,
175    Decimal,
176    Bool,
177    Date,
178    DateTime,
179}
180
181/// The `options` attribute: fixed choices, or a function that loads them.
182enum OptionsSpec {
183    Static(Vec<(String, String)>),
184    Dynamic(syn::Path),
185}
186
187/// Where a lookup field's choices come from.
188enum Lookup {
189    /// A function that returns the choices.
190    Dynamic(syn::Path),
191    /// The rows of a related table: `id` as the value, the `display` column as the label.
192    Related {
193        table: syn::Path,
194        display: syn::Ident,
195    },
196}
197
198fn expand(input: &DeriveInput) -> syn::Result<TokenStream2> {
199    let name = &input.ident;
200    let vis = &input.vis;
201    let fields_data = match &input.data {
202        Data::Struct(data) => match &data.fields {
203            Fields::Named(named) => &named.named,
204            _ => {
205                return Err(syn::Error::new_spanned(
206                    name,
207                    "IgniteResource needs a struct with named fields",
208                ))
209            }
210        },
211        _ => {
212            return Err(syn::Error::new_spanned(
213                name,
214                "IgniteResource can only be derived for a struct",
215            ))
216        }
217    };
218
219    let (table, title, singular, latest, navigation, conditions, form_layout, list_attrs) =
220        struct_attrs(input)?;
221    let table_name = table
222        .segments
223        .last()
224        .map(|s| s.ident.to_string())
225        .unwrap_or_default();
226    let title = title.unwrap_or_else(|| capitalize(&table_name));
227    let singular =
228        singular.unwrap_or_else(|| title.strip_suffix('s').unwrap_or(&title).to_string());
229
230    let mut fields = Vec::new();
231    for field in fields_data {
232        fields.push(field_attrs(field)?);
233    }
234
235    let primary = fields
236        .iter()
237        .find(|f| f.primary_key)
238        .or_else(|| fields.iter().find(|f| f.ident == "id"))
239        .ok_or_else(|| syn::Error::new_spanned(name, "IgniteResource needs a primary key: a field named `id` or one marked `primary_key`"))?;
240    if !is_key_type(&primary.inner) {
241        return Err(syn::Error::new_spanned(
242            &primary.ty,
243            "the primary key must be an i32 or i64",
244        ));
245    }
246    let pk_ident = primary.ident.clone();
247    let pk_name = pk_ident.to_string();
248
249    let latest_records = match &latest {
250        Some(spec) => latest_records_tokens(spec, &fields, &title, name)?,
251        None => quote! { ::core::option::Option::None },
252    };
253
254    let navigation_consts = navigation.consts();
255    let conditions_method = conditions.map(|path| {
256        quote! {
257            fn conditions() -> ::ignite_core::FieldConditions {
258                #path()
259            }
260        }
261    });
262
263    let form_layout_method = form_layout.map(|path| {
264        quote! {
265            fn form_layout() -> ::ignite_core::FormLayout {
266                #path()
267            }
268        }
269    });
270
271    let list_methods = list_attrs.methods();
272
273    let form_fields: Vec<&Field> = fields.iter().filter(|f| f.ident != pk_ident).collect();
274    let input_name = format_ident!("{}Input", name);
275
276    for f in &form_fields {
277        if f.is_password && f.base != Base::Text {
278            return Err(syn::Error::new_spanned(
279                &f.ty,
280                "a password field must be a String (or Option<String>), so the derive can hash it",
281            ));
282        }
283        if !f.optional && !f.required && f.base != Base::Bool {
284            return Err(syn::Error::new_spanned(
285                &f.ty,
286                "a field that is not an Option is required; remove `required = false` or make the field an Option",
287            ));
288        }
289    }
290
291    let input_fields = form_fields.iter().map(|f| {
292        let ident = &f.ident;
293        // A password is Option<String> on input, so a blank edit leaves the column as it is.
294        if f.is_password {
295            quote! { pub #ident: ::core::option::Option<::std::string::String> }
296        } else {
297            let ty = &f.ty;
298            quote! { pub #ident: #ty }
299        }
300    });
301    // The optional fields whose absence from an update keeps the stored value: every
302    // `Option` that is not a password (a password has its own rule) or a checkbox (an
303    // unticked checkbox sends nothing, so absent means false).
304    let sent_names: Vec<String> = form_fields
305        .iter()
306        .filter(|f| tracks_sent(f))
307        .map(|f| f.ident.to_string())
308        .collect();
309    let input_struct = quote! {
310        #vis struct #input_name {
311            #(#input_fields,)*
312            /// The optional fields the form sent, blank or not. An update writes NULL for an
313            /// optional field sent blank, and leaves out one that was not sent, so its stored
314            /// value is kept. Filled by `validate` and `validate_update`.
315            #[doc(hidden)]
316            pub __ignite_sent: ::std::vec::Vec<&'static str>,
317        }
318    };
319
320    // The columns an insert or update writes, from the input struct.
321    let value_steps = form_fields.iter().map(|f| value_step(f));
322
323    let lookup_fields: Vec<&Field> = form_fields
324        .iter()
325        .copied()
326        .filter(|f| f.lookup.is_some())
327        .collect();
328    let options_fn = options_method(&lookup_fields);
329
330    let field_defs = form_fields.iter().map(|f| {
331        let name_lit = f.ident.to_string();
332        let label = &f.label;
333        let kind = kind_tokens(f);
334        let required = f.required;
335        quote! {
336            ::ignite_core::Field {
337                name: #name_lit,
338                label: #label,
339                kind: #kind,
340                required: #required,
341            }
342        }
343    });
344
345    let column_defs = fields
346        .iter()
347        .filter(|f| !f.hidden_on_index && !f.is_password)
348        .map(|f| {
349            let key = f.ident.to_string();
350            let label = &f.label;
351            let sortable = f.sortable;
352            let searchable = f.searchable;
353            quote! {
354                ::ignite_core::Column {
355                    key: #key,
356                    label: #label,
357                    sortable: #sortable,
358                    searchable: #searchable,
359                }
360            }
361        });
362
363    let searchable: Vec<String> = fields
364        .iter()
365        .filter(|f| f.searchable)
366        .map(|f| f.ident.to_string())
367        .collect();
368    // One LIKE per searchable column, joined with OR inside a group, as the search always was.
369    let search_filter = if searchable.is_empty() {
370        quote! {}
371    } else {
372        let first = &searchable[0];
373        let rest = &searchable[1..];
374        quote! {
375            if let ::core::option::Option::Some(pattern) = &pattern {
376                let like = |q: ::orbit_orm::Query<#name>| {
377                    q.where_group(|q| {
378                        q.where_op(#first, ::orbit_orm::Operator::Like, pattern.clone())
379                            #(.or_where_op(#rest, ::orbit_orm::Operator::Like, pattern.clone()))*
380                    })
381                };
382                rows = like(rows);
383                count = like(count);
384            }
385        }
386    };
387
388    let sort_arms = fields.iter().filter(|f| f.sortable).map(|f| {
389        let key = f.ident.to_string();
390        quote! { (::core::option::Option::Some(#key), true) => (#key, ::orbit_orm::Direction::Asc), (::core::option::Option::Some(#key), false) => (#key, ::orbit_orm::Direction::Desc), }
391    });
392
393    let validate_steps = form_fields.iter().map(|f| validate_expr(f));
394    let validate_idents: Vec<&syn::Ident> = form_fields.iter().map(|f| &f.ident).collect();
395    let validate_patterns = form_fields.iter().map(|f| {
396        let ident = &f.ident;
397        if f.optional || f.is_password {
398            quote! { #ident }
399        } else {
400            quote! { ::core::option::Option::Some(#ident) }
401        }
402    });
403
404    let table_check = quote! {
405        const _: () = ::core::assert!(
406            ::ignite_core::table_name_is(<#name as ::orbit_orm::Model>::TABLE, #table_name),
407            "the #[ignite(table = ...)] attribute must name the table of the model's #[orbit(table = ...)]"
408        );
409    };
410
411    Ok(quote! {
412        #table_check
413
414        #input_struct
415
416        impl #name {
417            /// The columns that an insert (`creating`) or an update write, from the input.
418            /// An `Option` that is `None` is written as NULL on create. On update it is written
419            /// as NULL when the form sent it blank, so a cleared optional field is cleared, and
420            /// skipped when the form did not send it. A blank password is skipped on update.
421            #[doc(hidden)]
422            #[allow(unused_mut)]
423            fn __ignite_values(
424                input: &#input_name,
425                creating: bool,
426            ) -> ::std::vec::Vec<(&'static str, ::orbit_orm::Value)> {
427                let _ = creating;
428                let mut values = ::std::vec::Vec::new();
429                #(#value_steps)*
430                values
431            }
432
433            /// Shared by `validate` and `validate_update`. `creating` decides
434            /// whether a blank password is an error.
435            #[doc(hidden)]
436            #[allow(clippy::nonminimal_bool, clippy::needless_bool)]
437            fn __ignite_validate(
438                form: &::ignite_core::FormInput,
439                creating: bool,
440            ) -> ::core::result::Result<#input_name, ::ignite_core::FieldErrors> {
441                let _ = creating;
442                let mut errors = ::ignite_core::FieldErrors::new();
443                #(#validate_steps)*
444                let __ignite_optional: &[&'static str] = &[#(#sent_names),*];
445                let __ignite_sent: ::std::vec::Vec<&'static str> = __ignite_optional
446                    .iter()
447                    .copied()
448                    .filter(|name| form.has(name))
449                    .collect();
450                match (#(#validate_idents,)*) {
451                    (#(#validate_patterns,)*) if errors.is_empty() => {
452                        ::core::result::Result::Ok(#input_name { #(#validate_idents,)* __ignite_sent })
453                    }
454                    _ => ::core::result::Result::Err(errors),
455                }
456            }
457        }
458
459        impl ::ignite_core::IgniteResource for #name {
460            type Record = #name;
461            type Input = #input_name;
462
463            const SLUG: &'static str = #table_name;
464            const TITLE: &'static str = #title;
465            const SINGULAR: &'static str = #singular;
466            #navigation_consts
467
468            fn fields() -> &'static [::ignite_core::Field] {
469                &[#(#field_defs),*]
470            }
471
472            fn columns() -> &'static [::ignite_core::Column] {
473                &[#(#column_defs),*]
474            }
475
476            async fn list(
477                db: &::ignite_core::Database,
478                query: &::ignite_core::ListQuery,
479            ) -> ::core::result::Result<::ignite_core::Page<#name>, ::orbit_orm::Error> {
480                let pattern = query
481                    .search
482                    .as_ref()
483                    .map(|s| format!("%{}%", ::ignite_core::escape_like(s)));
484                let mut rows = query.filter.apply(<#name as ::orbit_orm::Model>::query());
485                let mut count = query.filter.apply(<#name as ::orbit_orm::Model>::query());
486                #search_filter
487
488                let asc = !matches!(query.sort, ::core::option::Option::Some((_, ::ignite_core::Direction::Desc)));
489                let (column, direction) = match (query.sort.as_ref().map(|(k, _)| k.as_str()), asc) {
490                    #(#sort_arms)*
491                    _ => (#pk_name, ::orbit_orm::Direction::Asc),
492                };
493                rows = rows.order_by(column, direction);
494
495                let total = count.count(db).await?;
496                let rows = rows
497                    .limit(query.per_page.max(0) as u64)
498                    .offset(query.offset().max(0) as u64)
499                    .get(db)
500                    .await?;
501                Ok(::ignite_core::Page { rows, total })
502            }
503
504            async fn find(
505                db: &::ignite_core::Database,
506                id: i64,
507            ) -> ::core::result::Result<::core::option::Option<#name>, ::orbit_orm::Error> {
508                <#name as ::orbit_orm::Model>::query().find(db, id).await
509            }
510
511            fn latest_records() -> ::core::option::Option<::ignite_core::LatestRecords> {
512                #latest_records
513            }
514
515            #conditions_method
516            #form_layout_method
517            #list_methods
518
519            async fn latest(
520                db: &::ignite_core::Database,
521                limit: i64,
522            ) -> ::core::result::Result<::std::vec::Vec<#name>, ::orbit_orm::Error> {
523                <#name as ::orbit_orm::Model>::query()
524                    .order_by(#pk_name, ::orbit_orm::Direction::Desc)
525                    .limit(limit.max(0) as u64)
526                    .get(db)
527                    .await
528            }
529
530            async fn create(
531                db: &::ignite_core::Database,
532                input: #input_name,
533            ) -> ::core::result::Result<#name, ::orbit_orm::Error> {
534                let values = #name::__ignite_values(&input, true);
535                let id = <#name as ::orbit_orm::Model>::query().insert(db, &values).await?;
536                <#name as ::ignite_core::IgniteResource>::find(db, id as i64)
537                    .await?
538                    .ok_or(::orbit_orm::Error::NotFound { table: <#name as ::orbit_orm::Model>::TABLE })
539            }
540
541            async fn update(
542                db: &::ignite_core::Database,
543                id: i64,
544                input: #input_name,
545            ) -> ::core::result::Result<#name, ::orbit_orm::Error> {
546                let values = #name::__ignite_values(&input, false);
547                // An update that writes nothing (every field it has was not sent) succeeds
548                // without a query, and returns the row when it exists.
549                if !values.is_empty() {
550                    let changed = <#name as ::orbit_orm::Model>::query()
551                        .where_eq(#pk_name, id)
552                        .update(db, &values)
553                        .await?;
554                    if changed == 0 {
555                        return Err(::orbit_orm::Error::NotFound { table: <#name as ::orbit_orm::Model>::TABLE });
556                    }
557                }
558                <#name as ::ignite_core::IgniteResource>::find(db, id)
559                    .await?
560                    .ok_or(::orbit_orm::Error::NotFound { table: <#name as ::orbit_orm::Model>::TABLE })
561            }
562
563            async fn delete(
564                db: &::ignite_core::Database,
565                id: i64,
566            ) -> ::core::result::Result<u64, ::orbit_orm::Error> {
567                <#name as ::orbit_orm::Model>::query()
568                    .where_eq(#pk_name, id)
569                    .delete(db)
570                    .await
571            }
572
573            fn validate(
574                form: &::ignite_core::FormInput,
575            ) -> ::core::result::Result<#input_name, ::ignite_core::FieldErrors> {
576                #name::__ignite_validate(form, true)
577            }
578
579            fn validate_update(
580                form: &::ignite_core::FormInput,
581            ) -> ::core::result::Result<#input_name, ::ignite_core::FieldErrors> {
582                #name::__ignite_validate(form, false)
583            }
584
585            #options_fn
586        }
587    })
588}
589
590/// One block of the generated `__ignite_values`: pushes the column of `field`. An `Option`
591/// that is `None` is written as NULL on create. On update (since 0.3.0) it is written as NULL
592/// when the form sent it blank, so clearing an optional field on the edit form clears the
593/// stored value, and skipped when the form did not send it, so the stored value is kept, as
594/// Laravel's `update` with validated data leaves out a key the request did not have. A
595/// password is the exception: a blank one is NULL on create and skipped on update, so the
596/// stored hash is kept.
597fn value_step(field: &Field) -> TokenStream2 {
598    let ident = &field.ident;
599    let column = ident.to_string();
600    let convert = value_of(field.base, quote! { x });
601    // A password's input is an `Option` too, so a blank edit leaves the column alone.
602    if field.is_password {
603        quote! {
604            match &input.#ident {
605                ::core::option::Option::Some(x) => values.push((#column, #convert)),
606                ::core::option::Option::None if creating => values.push((#column, ::orbit_orm::Value::Null)),
607                ::core::option::Option::None => {}
608            }
609        }
610    } else if tracks_sent(field) {
611        quote! {
612            match &input.#ident {
613                ::core::option::Option::Some(x) => values.push((#column, #convert)),
614                ::core::option::Option::None if creating || input.__ignite_sent.contains(&#column) => {
615                    values.push((#column, ::orbit_orm::Value::Null))
616                }
617                ::core::option::Option::None => {}
618            }
619        }
620    } else if field.optional {
621        // An optional checkbox: always Some, as an unticked box is false.
622        quote! {
623            match &input.#ident {
624                ::core::option::Option::Some(x) => values.push((#column, #convert)),
625                ::core::option::Option::None => values.push((#column, ::orbit_orm::Value::Null)),
626            }
627        }
628    } else {
629        quote! {
630            {
631                let x = &input.#ident;
632                values.push((#column, #convert));
633            }
634        }
635    }
636}
637
638/// Whether an update keeps the stored value of `field` when the form does not send it: an
639/// `Option` that is neither a password nor a checkbox.
640fn tracks_sent(field: &Field) -> bool {
641    field.optional && !field.is_password && field.base != Base::Bool
642}
643
644/// The `Value` of a reference `x` to a field's base value.
645fn value_of(base: Base, x: TokenStream2) -> TokenStream2 {
646    match base {
647        Base::Text => quote! { ::orbit_orm::Value::from(#x.as_str()) },
648        Base::Integer => quote! { ::orbit_orm::Value::from(*#x as i64) },
649        Base::Decimal => quote! { ::orbit_orm::Value::from(*#x as f64) },
650        Base::Bool | Base::Date | Base::DateTime => quote! { ::orbit_orm::Value::from(*#x) },
651    }
652}
653
654/// The `#[ignite(latest_records(...))]` attribute, as written.
655struct LatestSpec {
656    /// The table heading. Defaults to "Latest" and the title.
657    title: Option<String>,
658    /// The most rows the dashboard table shows.
659    limit: i64,
660    /// Each column key, with the span of the string it came from.
661    columns: Vec<(String, Span)>,
662}
663
664/// The navigation attributes of the struct, as Filament's resource properties. Each one left
665/// out keeps the trait's default.
666#[derive(Default)]
667struct Navigation {
668    label: Option<String>,
669    group: Option<String>,
670    sort: Option<i32>,
671    parent_item: Option<String>,
672    parent_items: Option<Vec<String>>,
673    register: Option<bool>,
674    icon: Option<String>,
675    create_item: Option<bool>,
676    create_label: Option<String>,
677}
678
679impl Navigation {
680    /// The `NAVIGATION_*` constants of the attributes that were given.
681    fn consts(&self) -> TokenStream2 {
682        let label = self.label.as_ref().map(|label| {
683            quote! { const NAVIGATION_LABEL: ::core::option::Option<&'static str> = ::core::option::Option::Some(#label); }
684        });
685        let group = self.group.as_ref().map(|group| {
686            quote! { const NAVIGATION_GROUP: ::core::option::Option<&'static str> = ::core::option::Option::Some(#group); }
687        });
688        let sort = self.sort.map(|sort| {
689            quote! { const NAVIGATION_SORT: ::core::option::Option<i32> = ::core::option::Option::Some(#sort); }
690        });
691        let parent_item = self.parent_item.as_ref().map(|parent| {
692            quote! { const NAVIGATION_PARENT_ITEM: ::core::option::Option<&'static str> = ::core::option::Option::Some(#parent); }
693        });
694        let parent_items = self.parent_items.as_ref().map(|parents| {
695            quote! { const NAVIGATION_PARENT_ITEMS: &'static [&'static str] = &[#(#parents),*]; }
696        });
697        let register = self.register.map(|listed| {
698            quote! { const SHOULD_REGISTER_NAVIGATION: bool = #listed; }
699        });
700        let icon = self.icon.as_ref().map(|icon| {
701            quote! { const NAVIGATION_ICON: ::core::option::Option<&'static str> = ::core::option::Option::Some(#icon); }
702        });
703        let create_item = self.create_item.map(|listed| {
704            quote! { const NAVIGATION_CREATE_ITEM: bool = #listed; }
705        });
706        let create_label = self.create_label.as_ref().map(|label| {
707            quote! { const NAVIGATION_CREATE_LABEL: &'static str = #label; }
708        });
709        quote! { #label #group #sort #parent_item #parent_items #register #icon #create_item #create_label }
710    }
711}
712
713/// What the struct-level attributes give: the table, the title, the singular name, the
714/// dashboard table, the navigation, the paths of the functions that give the conditions
715/// and the form layout, and the list page's tabs and badges.
716type StructAttrs = (
717    syn::Path,
718    Option<String>,
719    Option<String>,
720    Option<LatestSpec>,
721    Navigation,
722    Option<syn::Path>,
723    Option<syn::Path>,
724    ListAttrs,
725);
726
727/// The list page's attributes: the tabs, the default tab and the badge columns.
728#[derive(Default)]
729struct ListAttrs {
730    tabs: Option<syn::Path>,
731    default_active_tab: Option<String>,
732    badges: Option<syn::Path>,
733    tab_counts_follow_search: Option<bool>,
734    hide_empty_tabs: Option<bool>,
735    row_actions: Option<syn::Path>,
736    bulk_actions: Option<syn::Path>,
737    hide_default_delete_when: Option<syn::Path>,
738}
739
740impl ListAttrs {
741    /// The `tabs`, `default_active_tab` and `column_badges` methods of the attributes given.
742    fn methods(&self) -> TokenStream2 {
743        let tabs = self.tabs.as_ref().map(|path| {
744            quote! {
745                fn tabs() -> ::std::vec::Vec<::ignite_core::Tab> {
746                    #path()
747                }
748            }
749        });
750        let default = self.default_active_tab.as_ref().map(|key| {
751            quote! {
752                fn default_active_tab() -> ::core::option::Option<&'static str> {
753                    ::core::option::Option::Some(#key)
754                }
755            }
756        });
757        let badges = self.badges.as_ref().map(|path| {
758            quote! {
759                fn column_badges() -> ::ignite_core::ColumnBadges {
760                    #path()
761                }
762            }
763        });
764        let follow = self.tab_counts_follow_search.map(|follow| {
765            quote! {
766                fn tab_counts_follow_search() -> bool {
767                    #follow
768                }
769            }
770        });
771        let hide = self.hide_empty_tabs.map(|hide| {
772            quote! {
773                fn hide_empty_tabs() -> bool {
774                    #hide
775                }
776            }
777        });
778        let actions = self.row_actions.as_ref().map(|path| {
779            quote! {
780                fn row_actions() -> ::std::vec::Vec<::ignite_core::RowAction> {
781                    #path()
782                }
783            }
784        });
785        let bulk = self.bulk_actions.as_ref().map(|path| {
786            quote! {
787                fn bulk_actions() -> ::std::vec::Vec<::ignite_core::BulkAction> {
788                    #path()
789                }
790            }
791        });
792        let hide_delete = self.hide_default_delete_when.as_ref().map(|path| {
793            quote! {
794                fn hide_default_delete_when() -> ::core::option::Option<::ignite_core::ListFilter> {
795                    ::core::option::Option::Some(#path())
796                }
797            }
798        });
799        quote! { #tabs #default #badges #follow #hide #actions #bulk #hide_delete }
800    }
801}
802
803/// Reads `#[ignite(...)]` on the struct: the table, the title, the singular name, the
804/// dashboard table, the navigation, the conditions and the form layout.
805fn struct_attrs(input: &DeriveInput) -> syn::Result<StructAttrs> {
806    let mut table = None;
807    let mut title = None;
808    let mut singular = None;
809    let mut latest = None;
810    let mut navigation = Navigation::default();
811    let mut conditions = None;
812    let mut form_layout = None;
813    let mut list = ListAttrs::default();
814    for attr in input.attrs.iter().filter(|a| a.path().is_ident("ignite")) {
815        attr.parse_nested_meta(|meta| {
816            if meta.path.is_ident("table") {
817                table = Some(meta.value()?.parse::<syn::Path>()?);
818                Ok(())
819            } else if meta.path.is_ident("title") {
820                title = Some(meta.value()?.parse::<LitStr>()?.value());
821                Ok(())
822            } else if meta.path.is_ident("singular") {
823                singular = Some(meta.value()?.parse::<LitStr>()?.value());
824                Ok(())
825            } else if meta.path.is_ident("latest_records") {
826                latest = Some(latest_spec(&meta)?);
827                Ok(())
828            } else if meta.path.is_ident("navigation_label") {
829                navigation.label = Some(meta.value()?.parse::<LitStr>()?.value());
830                Ok(())
831            } else if meta.path.is_ident("navigation_group") {
832                navigation.group = Some(meta.value()?.parse::<LitStr>()?.value());
833                Ok(())
834            } else if meta.path.is_ident("navigation_parent_item") {
835                navigation.parent_item = Some(meta.value()?.parse::<LitStr>()?.value());
836                Ok(())
837            } else if meta.path.is_ident("navigation_parent_items") {
838                let list = meta.value()?.parse::<syn::ExprArray>()?;
839                let mut parents = Vec::new();
840                for element in &list.elems {
841                    match element {
842                        syn::Expr::Lit(syn::ExprLit {
843                            lit: syn::Lit::Str(parent),
844                            ..
845                        }) => parents.push(parent.value()),
846                        other => {
847                            return Err(syn::Error::new_spanned(
848                                other,
849                                "expected a string: the parent entry's label or slug",
850                            ))
851                        }
852                    }
853                }
854                navigation.parent_items = Some(parents);
855                Ok(())
856            } else if meta.path.is_ident("should_register_navigation") {
857                navigation.register = Some(meta.value()?.parse::<syn::LitBool>()?.value);
858                Ok(())
859            } else if meta.path.is_ident("navigation_create_item") {
860                navigation.create_item = Some(meta.value()?.parse::<syn::LitBool>()?.value);
861                Ok(())
862            } else if meta.path.is_ident("navigation_create_label") {
863                navigation.create_label = Some(meta.value()?.parse::<LitStr>()?.value());
864                Ok(())
865            } else if meta.path.is_ident("navigation_icon") {
866                let icon = meta.value()?.parse::<LitStr>()?;
867                let name = icon.value();
868                // Before 0.6.2 the value was CSS classes, such as `dashicons dashicons-admin-post`.
869                if name.trim().is_empty() || name.chars().any(char::is_whitespace) {
870                    return Err(syn::Error::new(
871                        icon.span(),
872                        "`navigation_icon` takes an icon name such as \"post\", \"media\" or \"settings\", which the admin theme maps to its icon, not CSS classes",
873                    ));
874                }
875                navigation.icon = Some(name);
876                Ok(())
877            } else if meta.path.is_ident("navigation_sort") {
878                navigation.sort = Some(sort_value(&meta.value()?.parse::<syn::Expr>()?)?);
879                Ok(())
880            } else if meta.path.is_ident("conditions") {
881                conditions = Some(meta.value()?.parse::<syn::Path>()?);
882                Ok(())
883            } else if meta.path.is_ident("form_layout") {
884                form_layout = Some(meta.value()?.parse::<syn::Path>()?);
885                Ok(())
886            } else if meta.path.is_ident("tabs") {
887                list.tabs = Some(meta.value()?.parse::<syn::Path>()?);
888                Ok(())
889            } else if meta.path.is_ident("default_active_tab") {
890                list.default_active_tab = Some(meta.value()?.parse::<LitStr>()?.value());
891                Ok(())
892            } else if meta.path.is_ident("badges") {
893                list.badges = Some(meta.value()?.parse::<syn::Path>()?);
894                Ok(())
895            } else if meta.path.is_ident("tab_counts_follow_search") {
896                list.tab_counts_follow_search = Some(meta.value()?.parse::<syn::LitBool>()?.value);
897                Ok(())
898            } else if meta.path.is_ident("hide_default_delete_when") {
899                list.hide_default_delete_when = Some(meta.value()?.parse::<syn::Path>()?);
900                Ok(())
901            } else if meta.path.is_ident("bulk_actions") {
902                list.bulk_actions = Some(meta.value()?.parse::<syn::Path>()?);
903                Ok(())
904            } else if meta.path.is_ident("row_actions") {
905                list.row_actions = Some(meta.value()?.parse::<syn::Path>()?);
906                Ok(())
907            } else if meta.path.is_ident("hide_empty_tabs") {
908                list.hide_empty_tabs = Some(meta.value()?.parse::<syn::LitBool>()?.value);
909                Ok(())
910            } else {
911                Err(meta.error(
912                    "unknown ignite attribute on the struct; expected `table`, `title`, `singular`, `latest_records`, `navigation_label`, `navigation_group`, `navigation_sort`, `navigation_parent_item`, `navigation_parent_items`, `should_register_navigation`, `navigation_icon`, `navigation_create_item`, `navigation_create_label`, `conditions`, `form_layout`, `tabs`, `default_active_tab`, `badges`, `tab_counts_follow_search`, `hide_empty_tabs`, `row_actions`, `bulk_actions` or `hide_default_delete_when`",
913                ))
914            }
915        })?;
916    }
917    let table = table.ok_or_else(|| {
918        syn::Error::new_spanned(
919            &input.ident,
920            "IgniteResource needs #[ignite(table = <table name>)]",
921        )
922    })?;
923    Ok((
924        table,
925        title,
926        singular,
927        latest,
928        navigation,
929        conditions,
930        form_layout,
931        list,
932    ))
933}
934
935/// The `i32` of a `navigation_sort` value: an integer literal, or a negative one such as `-1`.
936fn sort_value(expr: &syn::Expr) -> syn::Result<i32> {
937    match expr {
938        syn::Expr::Lit(syn::ExprLit {
939            lit: syn::Lit::Int(int),
940            ..
941        }) => int.base10_parse::<i32>(),
942        syn::Expr::Unary(syn::ExprUnary {
943            op: syn::UnOp::Neg(_),
944            expr: inner,
945            ..
946        }) => match inner.as_ref() {
947            syn::Expr::Lit(syn::ExprLit {
948                lit: syn::Lit::Int(int),
949                ..
950            }) => format!("-{}", int.base10_digits())
951                .parse::<i32>()
952                .map_err(|_| syn::Error::new_spanned(expr, "navigation_sort must fit in an i32")),
953            _ => Err(syn::Error::new_spanned(
954                expr,
955                "navigation_sort takes a whole number",
956            )),
957        },
958        _ => Err(syn::Error::new_spanned(
959            expr,
960            "navigation_sort takes a whole number",
961        )),
962    }
963}
964
965/// Reads `latest_records(limit = 5, columns = "name,email", title = "...")`.
966fn latest_spec(meta: &syn::meta::ParseNestedMeta<'_>) -> syn::Result<LatestSpec> {
967    let mut title = None;
968    let mut limit = 5i64;
969    let mut columns = None;
970    meta.parse_nested_meta(|inner| {
971        if inner.path.is_ident("limit") {
972            let value: syn::LitInt = inner.value()?.parse()?;
973            limit = value.base10_parse::<i64>()?;
974            if limit < 1 {
975                return Err(syn::Error::new(value.span(), "limit must be at least 1"));
976            }
977            Ok(())
978        } else if inner.path.is_ident("columns") {
979            let list: LitStr = inner.value()?.parse()?;
980            let span = list.span();
981            let names: Vec<(String, Span)> = list
982                .value()
983                .split(',')
984                .map(|name| (name.trim().to_string(), span))
985                .collect();
986            columns = Some(names);
987            Ok(())
988        } else if inner.path.is_ident("title") {
989            title = Some(inner.value()?.parse::<LitStr>()?.value());
990            Ok(())
991        } else {
992            Err(inner.error("latest_records takes limit, columns and title"))
993        }
994    })?;
995    let columns = columns.ok_or_else(|| {
996        meta.error(
997            "latest_records needs columns = \"name,email\": the columns the dashboard table shows",
998        )
999    })?;
1000    Ok(LatestSpec {
1001        title,
1002        limit,
1003        columns,
1004    })
1005}
1006
1007/// Writes the body of `latest_records()` from the attribute, after checking each
1008/// column: it must be a field of the model, and it must not be a password.
1009fn latest_records_tokens(
1010    spec: &LatestSpec,
1011    fields: &[Field],
1012    title: &str,
1013    name: &syn::Ident,
1014) -> syn::Result<TokenStream2> {
1015    let mut keys = Vec::new();
1016    for (key, span) in &spec.columns {
1017        if key.is_empty() {
1018            return Err(syn::Error::new(
1019                *span,
1020                "latest_records has an empty column name",
1021            ));
1022        }
1023        let field = fields
1024            .iter()
1025            .find(|f| f.ident == key.as_str())
1026            .ok_or_else(|| syn::Error::new(*span, format!("`{key}` is not a field of {name}")))?;
1027        if field.is_password {
1028            return Err(syn::Error::new(
1029                *span,
1030                format!("`{key}` is a password and cannot be shown on the dashboard"),
1031            ));
1032        }
1033        keys.push(key.clone());
1034    }
1035    let table_title = spec
1036        .title
1037        .clone()
1038        .unwrap_or_else(|| format!("Latest {title}"));
1039    let limit = spec.limit;
1040    Ok(quote! {
1041        ::core::option::Option::Some(::ignite_core::LatestRecords {
1042            title: #table_title,
1043            columns: &[#(#keys),*],
1044            limit: #limit,
1045        })
1046    })
1047}
1048
1049/// Reads the `#[ignite(...)]` attributes of a field and resolves its defaults.
1050fn field_attrs(field: &syn::Field) -> syn::Result<Field> {
1051    let ident = field
1052        .ident
1053        .clone()
1054        .ok_or_else(|| syn::Error::new_spanned(field, "IgniteResource needs named fields"))?;
1055    let ty = field.ty.clone();
1056    let (optional, inner) = match option_inner(&ty) {
1057        Some(inner) => (true, inner.clone()),
1058        None => (false, ty.clone()),
1059    };
1060    let base = base_of(&inner).ok_or_else(|| {
1061        syn::Error::new_spanned(
1062            &ty,
1063            "unsupported field type: use String, i16, i32, i64, f32, f64, bool, chrono::NaiveDate, chrono::NaiveDateTime, or Option of one",
1064        )
1065    })?;
1066
1067    let mut label = None;
1068    let mut form_type = None;
1069    let mut required_attr = None;
1070    let mut primary_key = false;
1071    let mut searchable = false;
1072    let mut sortable = false;
1073    let mut hidden_on_index = false;
1074    let mut options = None;
1075    let mut belongs_to = None;
1076    let mut display = None;
1077    let mut step = None;
1078    let mut sub_fields = None;
1079    let mut blocks = None;
1080    for attr in field.attrs.iter().filter(|a| a.path().is_ident("ignite")) {
1081        attr.parse_nested_meta(|meta| {
1082            if meta.path.is_ident("label") {
1083                label = Some(meta.value()?.parse::<LitStr>()?.value());
1084            } else if meta.path.is_ident("form_type") {
1085                form_type = Some(meta.value()?.parse::<LitStr>()?);
1086            } else if meta.path.is_ident("required") {
1087                let value = if meta.input.peek(Token![=]) {
1088                    meta.value()?.parse::<LitBool>()?.value
1089                } else {
1090                    true
1091                };
1092                required_attr = Some(value);
1093            } else if meta.path.is_ident("primary_key") {
1094                primary_key = true;
1095            } else if meta.path.is_ident("searchable") {
1096                searchable = true;
1097            } else if meta.path.is_ident("sortable") {
1098                sortable = true;
1099            } else if meta.path.is_ident("hidden_on_index") {
1100                hidden_on_index = true;
1101            } else if meta.path.is_ident("options") {
1102                let expr: syn::Expr = meta.value()?.parse()?;
1103                options = Some(options_of(&expr)?);
1104            } else if meta.path.is_ident("belongs_to") {
1105                belongs_to = Some(meta.value()?.parse::<syn::Path>()?);
1106            } else if meta.path.is_ident("display") {
1107                display = Some(meta.value()?.parse::<syn::Ident>()?);
1108            } else if meta.path.is_ident("step") {
1109                step = Some(meta.value()?.parse::<LitStr>()?);
1110            } else if meta.path.is_ident("fields") {
1111                sub_fields = Some(meta.value()?.parse::<syn::Path>()?);
1112            } else if meta.path.is_ident("blocks") {
1113                blocks = Some(meta.value()?.parse::<syn::Path>()?);
1114            } else {
1115                return Err(meta.error(
1116                    "unknown ignite attribute; expected label, form_type, required, primary_key, searchable, sortable, hidden_on_index, options, belongs_to, display, step, fields or blocks",
1117                ));
1118            }
1119            Ok(())
1120        })?;
1121    }
1122
1123    // Options and a relation both make a select, so neither takes a form_type of its own,
1124    // except the kinds that are a select by another name: radio buttons for fixed options,
1125    // and a post object, taxonomy, user or relationship for loaded ones.
1126    let lookup_attr = options.is_some() || belongs_to.is_some();
1127    let choice_kind = match form_type.as_ref().map(|s| s.value()).as_deref() {
1128        Some("radio") if matches!(options, Some(OptionsSpec::Static(_))) => Some(Kind::Radio),
1129        Some("post_object") if lookup_attr && !matches!(options, Some(OptionsSpec::Static(_))) => {
1130            Some(Kind::PostObject)
1131        }
1132        Some("taxonomy") if lookup_attr && !matches!(options, Some(OptionsSpec::Static(_))) => {
1133            Some(Kind::Taxonomy)
1134        }
1135        Some("user") if lookup_attr && !matches!(options, Some(OptionsSpec::Static(_))) => {
1136            Some(Kind::User)
1137        }
1138        Some("relationship") if matches!(options, Some(OptionsSpec::Dynamic(_))) => {
1139            Some(Kind::Relationship)
1140        }
1141        _ => None,
1142    };
1143    if lookup_attr && form_type.is_some() && choice_kind.is_none() {
1144        return Err(syn::Error::new_spanned(
1145            &ty,
1146            "a field with options or belongs_to is a select: remove form_type",
1147        ));
1148    }
1149    if belongs_to.is_some() != display.is_some() {
1150        return Err(syn::Error::new_spanned(
1151            &ty,
1152            "belongs_to and display go together: belongs_to = <model type>, display = <column>",
1153        ));
1154    }
1155    if options.is_some() && belongs_to.is_some() {
1156        return Err(syn::Error::new_spanned(
1157            &ty,
1158            "a field takes options or belongs_to, not both",
1159        ));
1160    }
1161
1162    let mut choices = Vec::new();
1163    let mut lookup = None;
1164    let kind = if let Some(spec) = options {
1165        match spec {
1166            OptionsSpec::Static(pairs) => {
1167                if base != Base::Text {
1168                    return Err(syn::Error::new_spanned(
1169                        &ty,
1170                        "a field with a list of options must be a String (or Option<String>)",
1171                    ));
1172                }
1173                choices = pairs;
1174                choice_kind.unwrap_or(Kind::Select)
1175            }
1176            OptionsSpec::Dynamic(path) => {
1177                if !matches!(base, Base::Text | Base::Integer) {
1178                    return Err(syn::Error::new_spanned(
1179                        &ty,
1180                        "a field with options from a function must be a String or an integer",
1181                    ));
1182                }
1183                if choice_kind == Some(Kind::Relationship) && base != Base::Text {
1184                    return Err(syn::Error::new_spanned(
1185                        &ty,
1186                        "a relationship stores a JSON list, so it must be a String (or Option<String>)",
1187                    ));
1188                }
1189                lookup = Some(Lookup::Dynamic(path));
1190                choice_kind.unwrap_or(Kind::Lookup)
1191            }
1192        }
1193    } else if let Some(table) = belongs_to {
1194        if base != Base::Integer {
1195            return Err(syn::Error::new_spanned(
1196                &ty,
1197                "a belongs_to field stores the related row's id, so it must be an i32 or i64",
1198            ));
1199        }
1200        lookup = Some(Lookup::Related {
1201            table,
1202            display: display
1203                .clone()
1204                .expect("checked: display is set with belongs_to"),
1205        });
1206        choice_kind.unwrap_or(Kind::Lookup)
1207    } else {
1208        match form_type.as_ref().map(|s| s.value()) {
1209            None => match base {
1210                Base::Bool => Kind::Checkbox,
1211                Base::Integer => Kind::Number,
1212                Base::Decimal => Kind::Decimal,
1213                Base::Date => Kind::Date,
1214                Base::DateTime => Kind::DateTime,
1215                Base::Text => Kind::Text,
1216            },
1217            Some(value) => match value.as_str() {
1218                "text" => Kind::Text,
1219                "textarea" => Kind::Textarea,
1220                "password" => Kind::Password,
1221                "number" if base == Base::Decimal => Kind::Decimal,
1222                "number" => Kind::Number,
1223                "checkbox" => Kind::Checkbox,
1224                "date" => Kind::Date,
1225                "email" => Kind::Email,
1226                "url" => Kind::Url,
1227                "color" => Kind::Color,
1228                "image" => Kind::Image,
1229                "file" => Kind::File,
1230                "link" => Kind::Link,
1231                "wysiwyg" => Kind::Wysiwyg,
1232                "gallery" => Kind::Gallery,
1233                "repeater" => Kind::Repeater,
1234                "group" => Kind::Group,
1235                "clone" => Kind::Clone,
1236                "flexible_content" => Kind::FlexibleContent,
1237                "radio" | "post_object" | "taxonomy" | "user" | "relationship" => {
1238                    return Err(syn::Error::new(
1239                        form_type.map(|s| s.span()).unwrap_or_else(Span::call_site),
1240                        "form_type radio takes options = [...]; post_object, taxonomy and user take options = <function> or belongs_to; relationship takes options = <function>",
1241                    ))
1242                }
1243                _ => return Err(syn::Error::new(
1244                    form_type.map(|s| s.span()).unwrap_or_else(Span::call_site),
1245                    "form_type must be one of text, textarea, password, number, checkbox, date, email, url, color, image, file, link, wysiwyg, gallery, radio, post_object, taxonomy, user, relationship, repeater, group, clone or flexible_content",
1246                )),
1247            },
1248        }
1249    };
1250
1251    // A structured field names its sub-fields (or blocks), and only it does.
1252    let sub_fields = match kind {
1253        Kind::Repeater | Kind::Group | Kind::Clone => match (sub_fields, blocks) {
1254            (Some(path), None) => Some(path),
1255            _ => {
1256                return Err(syn::Error::new_spanned(
1257                    &ty,
1258                    "a repeater, group or clone takes fields = <a &'static [ignite_core::Field] constant>",
1259                ))
1260            }
1261        },
1262        Kind::FlexibleContent => match (blocks, sub_fields) {
1263            (Some(path), None) => Some(path),
1264            _ => {
1265                return Err(syn::Error::new_spanned(
1266                    &ty,
1267                    "a flexible_content field takes blocks = <a &'static [ignite_core::Block] constant>",
1268                ))
1269            }
1270        },
1271        _ if sub_fields.is_some() || blocks.is_some() => {
1272            return Err(syn::Error::new_spanned(
1273                &ty,
1274                "fields and blocks apply to a repeater, group, clone or flexible_content field",
1275            ))
1276        }
1277        _ => None,
1278    };
1279    // The kinds for custom fields store text, except a media id, which may be an integer.
1280    let text_kind =
1281        kind.checks_value() && !matches!(kind, Kind::PostObject | Kind::Taxonomy | Kind::User);
1282    if text_kind
1283        && base != Base::Text
1284        && !(matches!(kind, Kind::Image | Kind::File) && base == Base::Integer)
1285    {
1286        return Err(syn::Error::new_spanned(
1287            &ty,
1288            "this form_type stores text, so the field must be a String (or Option<String>); an image or file may also be an integer",
1289        ));
1290    }
1291
1292    if step.is_some() && base != Base::Decimal {
1293        return Err(syn::Error::new_spanned(
1294            &ty,
1295            "step applies to an f32 or f64 field",
1296        ));
1297    }
1298
1299    // A checkbox is never blank, so it is not required unless asked.
1300    let required = required_attr.unwrap_or(!optional && base != Base::Bool);
1301    let label = label.unwrap_or_else(|| capitalize(&ident.to_string().replace('_', " ")));
1302
1303    Ok(Field {
1304        ident,
1305        ty,
1306        inner,
1307        base,
1308        optional,
1309        kind,
1310        label,
1311        required,
1312        primary_key,
1313        searchable,
1314        sortable,
1315        hidden_on_index,
1316        is_password: kind == Kind::Password,
1317        choices,
1318        lookup,
1319        step: step.map(|s| s.value()),
1320        sub_fields,
1321    })
1322}
1323
1324/// The `options = ...` attribute: a list of `("value", "Label")` pairs, or the path of a
1325/// function that returns the choices from the database.
1326fn options_of(expr: &syn::Expr) -> syn::Result<OptionsSpec> {
1327    match expr {
1328        syn::Expr::Array(array) => {
1329            let mut pairs = Vec::new();
1330            for element in &array.elems {
1331                let syn::Expr::Tuple(tuple) = element else {
1332                    return Err(syn::Error::new_spanned(
1333                        element,
1334                        "each option is a pair, such as (\"draft\", \"Draft\")",
1335                    ));
1336                };
1337                let [value, label] = tuple.elems.iter().collect::<Vec<_>>()[..] else {
1338                    return Err(syn::Error::new_spanned(
1339                        tuple,
1340                        "each option is a pair, such as (\"draft\", \"Draft\")",
1341                    ));
1342                };
1343                pairs.push((string_literal(value)?, string_literal(label)?));
1344            }
1345            Ok(OptionsSpec::Static(pairs))
1346        }
1347        syn::Expr::Path(path) => Ok(OptionsSpec::Dynamic(path.path.clone())),
1348        _ => Err(syn::Error::new_spanned(
1349            expr,
1350            "options is a list of (\"value\", \"Label\") pairs, or the path of a function that returns them",
1351        )),
1352    }
1353}
1354
1355/// The text of a string literal, or an error at the expression.
1356fn string_literal(expr: &syn::Expr) -> syn::Result<String> {
1357    match expr {
1358        syn::Expr::Lit(syn::ExprLit {
1359            lit: syn::Lit::Str(text),
1360            ..
1361        }) => Ok(text.value()),
1362        _ => Err(syn::Error::new_spanned(expr, "expected a string literal")),
1363    }
1364}
1365
1366/// The type inside `Option<T>`, if the type is one.
1367fn option_inner(ty: &Type) -> Option<&Type> {
1368    let Type::Path(path) = ty else { return None };
1369    let segment = path.path.segments.last()?;
1370    if segment.ident != "Option" {
1371        return None;
1372    }
1373    let PathArguments::AngleBracketed(args) = &segment.arguments else {
1374        return None;
1375    };
1376    match args.args.first()? {
1377        GenericArgument::Type(inner) => Some(inner),
1378        _ => None,
1379    }
1380}
1381
1382/// What a supported base type parses from form text, or `None` if it is unsupported.
1383fn base_of(ty: &Type) -> Option<Base> {
1384    let Type::Path(path) = ty else { return None };
1385    let ident = path.path.segments.last()?.ident.to_string();
1386    match ident.as_str() {
1387        "String" => Some(Base::Text),
1388        "i16" | "i32" | "i64" => Some(Base::Integer),
1389        "f32" | "f64" => Some(Base::Decimal),
1390        "bool" => Some(Base::Bool),
1391        "NaiveDate" => Some(Base::Date),
1392        "NaiveDateTime" => Some(Base::DateTime),
1393        _ => None,
1394    }
1395}
1396
1397/// Whether a primary key has a type the query methods accept: `i32` or `i64`.
1398fn is_key_type(ty: &Type) -> bool {
1399    let Type::Path(path) = ty else { return false };
1400    path.path
1401        .segments
1402        .last()
1403        .is_some_and(|s| matches!(s.ident.to_string().as_str(), "i32" | "i64"))
1404}
1405
1406/// The `FieldKind` a field's form input has, as tokens.
1407fn kind_tokens(field: &Field) -> TokenStream2 {
1408    match field.kind {
1409        Kind::Text => quote! { ::ignite_core::FieldKind::Text },
1410        Kind::Textarea => quote! { ::ignite_core::FieldKind::Textarea },
1411        Kind::Password => quote! { ::ignite_core::FieldKind::Password },
1412        Kind::Number => quote! { ::ignite_core::FieldKind::Number },
1413        Kind::Decimal => {
1414            let step = field.step.as_deref().unwrap_or("any");
1415            quote! { ::ignite_core::FieldKind::Decimal(#step) }
1416        }
1417        Kind::Checkbox => quote! { ::ignite_core::FieldKind::Checkbox },
1418        Kind::Select => {
1419            let pairs = choice_pairs(&field.choices);
1420            quote! { ::ignite_core::FieldKind::Select(&[#(#pairs),*]) }
1421        }
1422        Kind::Lookup => quote! { ::ignite_core::FieldKind::Lookup },
1423        Kind::Date => quote! { ::ignite_core::FieldKind::Date },
1424        Kind::DateTime => quote! { ::ignite_core::FieldKind::DateTime },
1425        Kind::Email => quote! { ::ignite_core::FieldKind::Email },
1426        Kind::Url => quote! { ::ignite_core::FieldKind::Url },
1427        Kind::Radio => {
1428            let pairs = choice_pairs(&field.choices);
1429            quote! { ::ignite_core::FieldKind::Radio(&[#(#pairs),*]) }
1430        }
1431        Kind::Color => quote! { ::ignite_core::FieldKind::Color },
1432        Kind::Image => quote! { ::ignite_core::FieldKind::Image },
1433        Kind::File => quote! { ::ignite_core::FieldKind::File },
1434        Kind::Link => quote! { ::ignite_core::FieldKind::Link },
1435        Kind::Wysiwyg => quote! { ::ignite_core::FieldKind::Wysiwyg },
1436        Kind::PostObject => quote! { ::ignite_core::FieldKind::PostObject },
1437        Kind::Relationship => quote! { ::ignite_core::FieldKind::Relationship },
1438        Kind::Taxonomy => quote! { ::ignite_core::FieldKind::Taxonomy },
1439        Kind::User => quote! { ::ignite_core::FieldKind::User },
1440        Kind::Gallery => quote! { ::ignite_core::FieldKind::Gallery },
1441        Kind::Repeater | Kind::Group | Kind::Clone | Kind::FlexibleContent => {
1442            let path = field
1443                .sub_fields
1444                .as_ref()
1445                .expect("checked: a structured field has its sub-fields");
1446            match field.kind {
1447                Kind::Repeater => quote! { ::ignite_core::FieldKind::Repeater(#path) },
1448                Kind::Group => quote! { ::ignite_core::FieldKind::Group(#path) },
1449                Kind::Clone => quote! { ::ignite_core::FieldKind::Clone(#path) },
1450                _ => quote! { ::ignite_core::FieldKind::FlexibleContent(#path) },
1451            }
1452        }
1453    }
1454}
1455
1456/// The `(value, label)` tuples of a static list of options.
1457fn choice_pairs(choices: &[(String, String)]) -> Vec<TokenStream2> {
1458    choices
1459        .iter()
1460        .map(|(value, label)| quote! { (#value, #label) })
1461        .collect()
1462}
1463
1464/// One `let` in `validate`: reads the field from the form into an `Option` of its base value,
1465/// and records an error when the value is blank (required) or does not parse.
1466fn validate_expr(field: &Field) -> TokenStream2 {
1467    let ident = &field.ident;
1468    let name = ident.to_string();
1469    let label = &field.label;
1470    let kind = kind_tokens(field);
1471    let required = field.required;
1472    let base = field.base;
1473    let is_password = field.is_password;
1474    let ty = &field.inner;
1475
1476    let convert = match base {
1477        Base::Text if is_password => {
1478            let message = "Could not save this password.".to_string();
1479            quote! {
1480                match ::ignite_core::hash_password(text) {
1481                    Ok(hash) => ::core::option::Option::Some(hash),
1482                    Err(_) => {
1483                        errors.insert(#name.to_string(), #message.to_string());
1484                        ::core::option::Option::None
1485                    }
1486                }
1487            }
1488        }
1489        Base::Text if field.kind == Kind::Select => {
1490            let pairs = choice_pairs(&field.choices);
1491            quote! {
1492                {
1493                    let text = text.trim();
1494                    let choices: &[(&str, &str)] = &[#(#pairs),*];
1495                    if field.check_choice(text, choices, &mut errors) {
1496                        ::core::option::Option::Some(text.to_string())
1497                    } else {
1498                        ::core::option::Option::None
1499                    }
1500                }
1501            }
1502        }
1503        // The kinds for custom fields: the text their check returns.
1504        Base::Text if field.kind.checks_value() => quote! { field.check_value(text, &mut errors) },
1505        Base::Text => quote! { ::core::option::Option::Some(text.to_string()) },
1506        Base::Bool => quote! { ::core::option::Option::Some(form.checkbox(#name)) },
1507        // A media id stored as an integer: checked as a media id, then parsed.
1508        Base::Integer if matches!(field.kind, Kind::Image | Kind::File) => quote! {
1509            field
1510                .check_value(text, &mut errors)
1511                .and_then(|id| id.parse::<#ty>().ok())
1512        },
1513        Base::Integer => quote! { field.check_whole_number::<#ty>(text, &mut errors) },
1514        Base::Decimal => quote! { field.check_decimal::<#ty>(text, &mut errors) },
1515        Base::Date => quote! { field.check_date(text, &mut errors) },
1516        Base::DateTime => quote! { field.check_datetime(text, &mut errors) },
1517    };
1518
1519    // Booleans are never blank: an unticked checkbox is false.
1520    if base == Base::Bool {
1521        return quote! { let #ident = #convert; };
1522    }
1523
1524    // A password is required only when creating. On an edit a blank password
1525    // keeps the stored hash.
1526    quote! {
1527        let #ident = {
1528            let field = ::ignite_core::Field { name: #name, label: #label, kind: #kind, required: #required };
1529            let present = if #required && (creating || !#is_password) {
1530                field.check_required(form, &mut errors)
1531            } else {
1532                form.get(#name)
1533            };
1534            match present {
1535                ::core::option::Option::Some(text) => { let text: &str = text; #convert }
1536                ::core::option::Option::None => ::core::option::Option::None,
1537            }
1538        };
1539    }
1540}
1541
1542/// The `options` method, which the panel calls for each lookup field. It is written
1543/// only when the model has one, so the trait's default serves the rest.
1544fn options_method(lookups: &[&Field]) -> TokenStream2 {
1545    if lookups.is_empty() {
1546        return quote! {};
1547    }
1548    let arms = lookups.iter().map(|f| {
1549        let name_lit = f.ident.to_string();
1550        match f.lookup.as_ref().expect("checked: a lookup field") {
1551            Lookup::Dynamic(path) => quote! { #name_lit => #path(db).await, },
1552            Lookup::Related { table, display } => {
1553                let key_ty = &f.inner;
1554                let display_lit = display.to_string();
1555                quote! {
1556                    #name_lit => {
1557                        let rows: ::std::vec::Vec<(#key_ty, ::std::string::String)> =
1558                            <#table as ::orbit_orm::Model>::query()
1559                                .select(&[<#table as ::orbit_orm::Model>::PRIMARY_KEY, #display_lit])
1560                                .order_by(#display_lit, ::orbit_orm::Direction::Asc)
1561                                .get_as(db)
1562                                .await?;
1563                        ::core::result::Result::Ok(
1564                            rows.into_iter().map(|(id, label)| (id.to_string(), label)).collect(),
1565                        )
1566                    }
1567                }
1568            }
1569        }
1570    });
1571    quote! {
1572        async fn options(
1573            db: &::ignite_core::Database,
1574            field: &str,
1575        ) -> ::core::result::Result<::std::vec::Vec<(::std::string::String, ::std::string::String)>, ::orbit_orm::Error> {
1576            match field {
1577                #(#arms)*
1578                _ => ::core::result::Result::Ok(::std::vec::Vec::new()),
1579            }
1580        }
1581    }
1582}
1583
1584fn capitalize(text: &str) -> String {
1585    let mut chars = text.chars();
1586    match chars.next() {
1587        Some(first) => first.to_uppercase().collect::<String>() + chars.as_str(),
1588        None => String::new(),
1589    }
1590}