1use 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#[proc_macro_derive(IgniteResource, attributes(ignite))]
68pub fn derive_ignite_resource(input: TokenStream) -> TokenStream {
69 let input = parse_macro_input!(input as DeriveInput);
70 match expand(&input) {
71 Ok(tokens) => tokens.into(),
72 Err(error) => error.to_compile_error().into(),
73 }
74}
75
76struct Field {
78 ident: syn::Ident,
79 ty: Type,
80 inner: Type,
82 base: Base,
84 optional: bool,
85 kind: Kind,
86 label: String,
87 required: bool,
88 primary_key: bool,
89 searchable: bool,
90 sortable: bool,
91 hidden_on_index: bool,
92 is_password: bool,
94 choices: Vec<(String, String)>,
96 lookup: Option<Lookup>,
98 step: Option<String>,
100 sub_fields: Option<syn::Path>,
103}
104
105#[derive(Clone, Copy, PartialEq, Eq)]
106enum Kind {
107 Text,
108 Textarea,
109 Password,
110 Number,
111 Decimal,
112 Checkbox,
113 Select,
114 Lookup,
115 Date,
116 DateTime,
117 Email,
118 Url,
119 Radio,
120 Color,
121 Image,
122 File,
123 Link,
124 Wysiwyg,
125 PostObject,
126 Relationship,
127 Taxonomy,
128 User,
129 Repeater,
130 Group,
131 FlexibleContent,
132 Gallery,
133 Clone,
134}
135
136impl Kind {
137 fn checks_value(self) -> bool {
140 !matches!(
141 self,
142 Kind::Text
143 | Kind::Textarea
144 | Kind::Password
145 | Kind::Number
146 | Kind::Decimal
147 | Kind::Checkbox
148 | Kind::Select
149 | Kind::Lookup
150 | Kind::Date
151 | Kind::DateTime
152 )
153 }
154}
155
156#[derive(Clone, Copy, PartialEq, Eq)]
158enum Base {
159 Text,
160 Integer,
161 Decimal,
162 Bool,
163 Date,
164 DateTime,
165}
166
167enum OptionsSpec {
169 Static(Vec<(String, String)>),
170 Dynamic(syn::Path),
171}
172
173enum Lookup {
175 Dynamic(syn::Path),
177 Related {
179 table: syn::Path,
180 display: syn::Ident,
181 },
182}
183
184fn expand(input: &DeriveInput) -> syn::Result<TokenStream2> {
185 let name = &input.ident;
186 let vis = &input.vis;
187 let fields_data = match &input.data {
188 Data::Struct(data) => match &data.fields {
189 Fields::Named(named) => &named.named,
190 _ => {
191 return Err(syn::Error::new_spanned(
192 name,
193 "IgniteResource needs a struct with named fields",
194 ))
195 }
196 },
197 _ => {
198 return Err(syn::Error::new_spanned(
199 name,
200 "IgniteResource can only be derived for a struct",
201 ))
202 }
203 };
204
205 let (table, title, singular, latest, navigation, conditions) = struct_attrs(input)?;
206 let table_name = table
207 .segments
208 .last()
209 .map(|s| s.ident.to_string())
210 .unwrap_or_default();
211 let title = title.unwrap_or_else(|| capitalize(&table_name));
212 let singular =
213 singular.unwrap_or_else(|| title.strip_suffix('s').unwrap_or(&title).to_string());
214
215 let mut fields = Vec::new();
216 for field in fields_data {
217 fields.push(field_attrs(field)?);
218 }
219
220 let primary = fields
221 .iter()
222 .find(|f| f.primary_key)
223 .or_else(|| fields.iter().find(|f| f.ident == "id"))
224 .ok_or_else(|| syn::Error::new_spanned(name, "IgniteResource needs a primary key: a field named `id` or one marked `primary_key`"))?;
225 if !is_key_type(&primary.inner) {
226 return Err(syn::Error::new_spanned(
227 &primary.ty,
228 "the primary key must be an i32 or i64",
229 ));
230 }
231 let pk_ident = primary.ident.clone();
232 let pk_name = pk_ident.to_string();
233
234 let latest_records = match &latest {
235 Some(spec) => latest_records_tokens(spec, &fields, &title, name)?,
236 None => quote! { ::core::option::Option::None },
237 };
238
239 let navigation_consts = navigation.consts();
240 let conditions_method = conditions.map(|path| {
241 quote! {
242 fn conditions() -> ::ignite_core::FieldConditions {
243 #path()
244 }
245 }
246 });
247
248 let form_fields: Vec<&Field> = fields.iter().filter(|f| f.ident != pk_ident).collect();
249 let input_name = format_ident!("{}Input", name);
250
251 for f in &form_fields {
252 if f.is_password && f.base != Base::Text {
253 return Err(syn::Error::new_spanned(
254 &f.ty,
255 "a password field must be a String (or Option<String>), so the derive can hash it",
256 ));
257 }
258 if !f.optional && !f.required && f.base != Base::Bool {
259 return Err(syn::Error::new_spanned(
260 &f.ty,
261 "a field that is not an Option is required; remove `required = false` or make the field an Option",
262 ));
263 }
264 }
265
266 let input_fields = form_fields.iter().map(|f| {
267 let ident = &f.ident;
268 if f.is_password {
270 quote! { pub #ident: ::core::option::Option<::std::string::String> }
271 } else {
272 let ty = &f.ty;
273 quote! { pub #ident: #ty }
274 }
275 });
276 let sent_names: Vec<String> = form_fields
280 .iter()
281 .filter(|f| tracks_sent(f))
282 .map(|f| f.ident.to_string())
283 .collect();
284 let input_struct = quote! {
285 #vis struct #input_name {
286 #(#input_fields,)*
287 #[doc(hidden)]
291 pub __ignite_sent: ::std::vec::Vec<&'static str>,
292 }
293 };
294
295 let value_steps = form_fields.iter().map(|f| value_step(f));
297
298 let lookup_fields: Vec<&Field> = form_fields
299 .iter()
300 .copied()
301 .filter(|f| f.lookup.is_some())
302 .collect();
303 let options_fn = options_method(&lookup_fields);
304
305 let field_defs = form_fields.iter().map(|f| {
306 let name_lit = f.ident.to_string();
307 let label = &f.label;
308 let kind = kind_tokens(f);
309 let required = f.required;
310 quote! {
311 ::ignite_core::Field {
312 name: #name_lit,
313 label: #label,
314 kind: #kind,
315 required: #required,
316 }
317 }
318 });
319
320 let column_defs = fields
321 .iter()
322 .filter(|f| !f.hidden_on_index && !f.is_password)
323 .map(|f| {
324 let key = f.ident.to_string();
325 let label = &f.label;
326 let sortable = f.sortable;
327 let searchable = f.searchable;
328 quote! {
329 ::ignite_core::Column {
330 key: #key,
331 label: #label,
332 sortable: #sortable,
333 searchable: #searchable,
334 }
335 }
336 });
337
338 let searchable: Vec<String> = fields
339 .iter()
340 .filter(|f| f.searchable)
341 .map(|f| f.ident.to_string())
342 .collect();
343 let search_filter = if searchable.is_empty() {
345 quote! {}
346 } else {
347 let first = &searchable[0];
348 let rest = &searchable[1..];
349 quote! {
350 if let ::core::option::Option::Some(pattern) = &pattern {
351 let like = |q: ::orbit_orm::Query<#name>| {
352 q.where_group(|q| {
353 q.where_op(#first, ::orbit_orm::Operator::Like, pattern.clone())
354 #(.or_where_op(#rest, ::orbit_orm::Operator::Like, pattern.clone()))*
355 })
356 };
357 rows = like(rows);
358 count = like(count);
359 }
360 }
361 };
362
363 let sort_arms = fields.iter().filter(|f| f.sortable).map(|f| {
364 let key = f.ident.to_string();
365 quote! { (::core::option::Option::Some(#key), true) => (#key, ::orbit_orm::Direction::Asc), (::core::option::Option::Some(#key), false) => (#key, ::orbit_orm::Direction::Desc), }
366 });
367
368 let validate_steps = form_fields.iter().map(|f| validate_expr(f));
369 let validate_idents: Vec<&syn::Ident> = form_fields.iter().map(|f| &f.ident).collect();
370 let validate_patterns = form_fields.iter().map(|f| {
371 let ident = &f.ident;
372 if f.optional || f.is_password {
373 quote! { #ident }
374 } else {
375 quote! { ::core::option::Option::Some(#ident) }
376 }
377 });
378
379 let table_check = quote! {
380 const _: () = ::core::assert!(
381 ::ignite_core::table_name_is(<#name as ::orbit_orm::Model>::TABLE, #table_name),
382 "the #[ignite(table = ...)] attribute must name the table of the model's #[orbit(table = ...)]"
383 );
384 };
385
386 Ok(quote! {
387 #table_check
388
389 #input_struct
390
391 impl #name {
392 #[doc(hidden)]
397 #[allow(unused_mut)]
398 fn __ignite_values(
399 input: &#input_name,
400 creating: bool,
401 ) -> ::std::vec::Vec<(&'static str, ::orbit_orm::Value)> {
402 let _ = creating;
403 let mut values = ::std::vec::Vec::new();
404 #(#value_steps)*
405 values
406 }
407
408 #[doc(hidden)]
411 #[allow(clippy::nonminimal_bool, clippy::needless_bool)]
412 fn __ignite_validate(
413 form: &::ignite_core::FormInput,
414 creating: bool,
415 ) -> ::core::result::Result<#input_name, ::ignite_core::FieldErrors> {
416 let _ = creating;
417 let mut errors = ::ignite_core::FieldErrors::new();
418 #(#validate_steps)*
419 let __ignite_optional: &[&'static str] = &[#(#sent_names),*];
420 let __ignite_sent: ::std::vec::Vec<&'static str> = __ignite_optional
421 .iter()
422 .copied()
423 .filter(|name| form.has(name))
424 .collect();
425 match (#(#validate_idents,)*) {
426 (#(#validate_patterns,)*) if errors.is_empty() => {
427 ::core::result::Result::Ok(#input_name { #(#validate_idents,)* __ignite_sent })
428 }
429 _ => ::core::result::Result::Err(errors),
430 }
431 }
432 }
433
434 impl ::ignite_core::IgniteResource for #name {
435 type Record = #name;
436 type Input = #input_name;
437
438 const SLUG: &'static str = #table_name;
439 const TITLE: &'static str = #title;
440 const SINGULAR: &'static str = #singular;
441 #navigation_consts
442
443 fn fields() -> &'static [::ignite_core::Field] {
444 &[#(#field_defs),*]
445 }
446
447 fn columns() -> &'static [::ignite_core::Column] {
448 &[#(#column_defs),*]
449 }
450
451 async fn list(
452 db: &::ignite_core::Database,
453 query: &::ignite_core::ListQuery,
454 ) -> ::core::result::Result<::ignite_core::Page<#name>, ::orbit_orm::Error> {
455 let pattern = query
456 .search
457 .as_ref()
458 .map(|s| format!("%{}%", ::ignite_core::escape_like(s)));
459 let mut rows = <#name as ::orbit_orm::Model>::query();
460 let mut count = <#name as ::orbit_orm::Model>::query();
461 #search_filter
462
463 let asc = !matches!(query.sort, ::core::option::Option::Some((_, ::ignite_core::Direction::Desc)));
464 let (column, direction) = match (query.sort.as_ref().map(|(k, _)| k.as_str()), asc) {
465 #(#sort_arms)*
466 _ => (#pk_name, ::orbit_orm::Direction::Asc),
467 };
468 rows = rows.order_by(column, direction);
469
470 let total = count.count(db).await?;
471 let rows = rows
472 .limit(query.per_page.max(0) as u64)
473 .offset(query.offset().max(0) as u64)
474 .get(db)
475 .await?;
476 Ok(::ignite_core::Page { rows, total })
477 }
478
479 async fn find(
480 db: &::ignite_core::Database,
481 id: i64,
482 ) -> ::core::result::Result<::core::option::Option<#name>, ::orbit_orm::Error> {
483 <#name as ::orbit_orm::Model>::query().find(db, id).await
484 }
485
486 fn latest_records() -> ::core::option::Option<::ignite_core::LatestRecords> {
487 #latest_records
488 }
489
490 #conditions_method
491
492 async fn latest(
493 db: &::ignite_core::Database,
494 limit: i64,
495 ) -> ::core::result::Result<::std::vec::Vec<#name>, ::orbit_orm::Error> {
496 <#name as ::orbit_orm::Model>::query()
497 .order_by(#pk_name, ::orbit_orm::Direction::Desc)
498 .limit(limit.max(0) as u64)
499 .get(db)
500 .await
501 }
502
503 async fn create(
504 db: &::ignite_core::Database,
505 input: #input_name,
506 ) -> ::core::result::Result<#name, ::orbit_orm::Error> {
507 let values = #name::__ignite_values(&input, true);
508 let id = <#name as ::orbit_orm::Model>::query().insert(db, &values).await?;
509 <#name as ::ignite_core::IgniteResource>::find(db, id as i64)
510 .await?
511 .ok_or(::orbit_orm::Error::NotFound { table: <#name as ::orbit_orm::Model>::TABLE })
512 }
513
514 async fn update(
515 db: &::ignite_core::Database,
516 id: i64,
517 input: #input_name,
518 ) -> ::core::result::Result<#name, ::orbit_orm::Error> {
519 let values = #name::__ignite_values(&input, false);
520 if !values.is_empty() {
523 let changed = <#name as ::orbit_orm::Model>::query()
524 .where_eq(#pk_name, id)
525 .update(db, &values)
526 .await?;
527 if changed == 0 {
528 return Err(::orbit_orm::Error::NotFound { table: <#name as ::orbit_orm::Model>::TABLE });
529 }
530 }
531 <#name as ::ignite_core::IgniteResource>::find(db, id)
532 .await?
533 .ok_or(::orbit_orm::Error::NotFound { table: <#name as ::orbit_orm::Model>::TABLE })
534 }
535
536 async fn delete(
537 db: &::ignite_core::Database,
538 id: i64,
539 ) -> ::core::result::Result<u64, ::orbit_orm::Error> {
540 <#name as ::orbit_orm::Model>::query()
541 .where_eq(#pk_name, id)
542 .delete(db)
543 .await
544 }
545
546 fn validate(
547 form: &::ignite_core::FormInput,
548 ) -> ::core::result::Result<#input_name, ::ignite_core::FieldErrors> {
549 #name::__ignite_validate(form, true)
550 }
551
552 fn validate_update(
553 form: &::ignite_core::FormInput,
554 ) -> ::core::result::Result<#input_name, ::ignite_core::FieldErrors> {
555 #name::__ignite_validate(form, false)
556 }
557
558 #options_fn
559 }
560 })
561}
562
563fn value_step(field: &Field) -> TokenStream2 {
571 let ident = &field.ident;
572 let column = ident.to_string();
573 let convert = value_of(field.base, quote! { x });
574 if field.is_password {
576 quote! {
577 match &input.#ident {
578 ::core::option::Option::Some(x) => values.push((#column, #convert)),
579 ::core::option::Option::None if creating => values.push((#column, ::orbit_orm::Value::Null)),
580 ::core::option::Option::None => {}
581 }
582 }
583 } else if tracks_sent(field) {
584 quote! {
585 match &input.#ident {
586 ::core::option::Option::Some(x) => values.push((#column, #convert)),
587 ::core::option::Option::None if creating || input.__ignite_sent.contains(&#column) => {
588 values.push((#column, ::orbit_orm::Value::Null))
589 }
590 ::core::option::Option::None => {}
591 }
592 }
593 } else if field.optional {
594 quote! {
596 match &input.#ident {
597 ::core::option::Option::Some(x) => values.push((#column, #convert)),
598 ::core::option::Option::None => values.push((#column, ::orbit_orm::Value::Null)),
599 }
600 }
601 } else {
602 quote! {
603 {
604 let x = &input.#ident;
605 values.push((#column, #convert));
606 }
607 }
608 }
609}
610
611fn tracks_sent(field: &Field) -> bool {
614 field.optional && !field.is_password && field.base != Base::Bool
615}
616
617fn value_of(base: Base, x: TokenStream2) -> TokenStream2 {
619 match base {
620 Base::Text => quote! { ::orbit_orm::Value::from(#x.as_str()) },
621 Base::Integer => quote! { ::orbit_orm::Value::from(*#x as i64) },
622 Base::Decimal => quote! { ::orbit_orm::Value::from(*#x as f64) },
623 Base::Bool | Base::Date | Base::DateTime => quote! { ::orbit_orm::Value::from(*#x) },
624 }
625}
626
627struct LatestSpec {
629 title: Option<String>,
631 limit: i64,
633 columns: Vec<(String, Span)>,
635}
636
637#[derive(Default)]
640struct Navigation {
641 label: Option<String>,
642 group: Option<String>,
643 sort: Option<i32>,
644 icon: Option<String>,
645}
646
647impl Navigation {
648 fn consts(&self) -> TokenStream2 {
650 let label = self.label.as_ref().map(|label| {
651 quote! { const NAVIGATION_LABEL: ::core::option::Option<&'static str> = ::core::option::Option::Some(#label); }
652 });
653 let group = self.group.as_ref().map(|group| {
654 quote! { const NAVIGATION_GROUP: ::core::option::Option<&'static str> = ::core::option::Option::Some(#group); }
655 });
656 let sort = self.sort.map(|sort| {
657 quote! { const NAVIGATION_SORT: ::core::option::Option<i32> = ::core::option::Option::Some(#sort); }
658 });
659 let icon = self.icon.as_ref().map(|icon| {
660 quote! { const NAVIGATION_ICON: ::core::option::Option<&'static str> = ::core::option::Option::Some(#icon); }
661 });
662 quote! { #label #group #sort #icon }
663 }
664}
665
666type StructAttrs = (
669 syn::Path,
670 Option<String>,
671 Option<String>,
672 Option<LatestSpec>,
673 Navigation,
674 Option<syn::Path>,
675);
676
677fn struct_attrs(input: &DeriveInput) -> syn::Result<StructAttrs> {
680 let mut table = None;
681 let mut title = None;
682 let mut singular = None;
683 let mut latest = None;
684 let mut navigation = Navigation::default();
685 let mut conditions = None;
686 for attr in input.attrs.iter().filter(|a| a.path().is_ident("ignite")) {
687 attr.parse_nested_meta(|meta| {
688 if meta.path.is_ident("table") {
689 table = Some(meta.value()?.parse::<syn::Path>()?);
690 Ok(())
691 } else if meta.path.is_ident("title") {
692 title = Some(meta.value()?.parse::<LitStr>()?.value());
693 Ok(())
694 } else if meta.path.is_ident("singular") {
695 singular = Some(meta.value()?.parse::<LitStr>()?.value());
696 Ok(())
697 } else if meta.path.is_ident("latest_records") {
698 latest = Some(latest_spec(&meta)?);
699 Ok(())
700 } else if meta.path.is_ident("navigation_label") {
701 navigation.label = Some(meta.value()?.parse::<LitStr>()?.value());
702 Ok(())
703 } else if meta.path.is_ident("navigation_group") {
704 navigation.group = Some(meta.value()?.parse::<LitStr>()?.value());
705 Ok(())
706 } else if meta.path.is_ident("navigation_icon") {
707 let icon = meta.value()?.parse::<LitStr>()?;
708 let name = icon.value();
709 if name.trim().is_empty() || name.chars().any(char::is_whitespace) {
711 return Err(syn::Error::new(
712 icon.span(),
713 "`navigation_icon` takes an icon name such as \"post\", \"media\" or \"settings\", which the admin theme maps to its icon, not CSS classes",
714 ));
715 }
716 navigation.icon = Some(name);
717 Ok(())
718 } else if meta.path.is_ident("navigation_sort") {
719 navigation.sort = Some(sort_value(&meta.value()?.parse::<syn::Expr>()?)?);
720 Ok(())
721 } else if meta.path.is_ident("conditions") {
722 conditions = Some(meta.value()?.parse::<syn::Path>()?);
723 Ok(())
724 } else {
725 Err(meta.error(
726 "unknown ignite attribute on the struct; expected `table`, `title`, `singular`, `latest_records`, `navigation_label`, `navigation_group`, `navigation_sort`, `navigation_icon` or `conditions`",
727 ))
728 }
729 })?;
730 }
731 let table = table.ok_or_else(|| {
732 syn::Error::new_spanned(
733 &input.ident,
734 "IgniteResource needs #[ignite(table = <table name>)]",
735 )
736 })?;
737 Ok((table, title, singular, latest, navigation, conditions))
738}
739
740fn sort_value(expr: &syn::Expr) -> syn::Result<i32> {
742 match expr {
743 syn::Expr::Lit(syn::ExprLit {
744 lit: syn::Lit::Int(int),
745 ..
746 }) => int.base10_parse::<i32>(),
747 syn::Expr::Unary(syn::ExprUnary {
748 op: syn::UnOp::Neg(_),
749 expr: inner,
750 ..
751 }) => match inner.as_ref() {
752 syn::Expr::Lit(syn::ExprLit {
753 lit: syn::Lit::Int(int),
754 ..
755 }) => format!("-{}", int.base10_digits())
756 .parse::<i32>()
757 .map_err(|_| syn::Error::new_spanned(expr, "navigation_sort must fit in an i32")),
758 _ => Err(syn::Error::new_spanned(
759 expr,
760 "navigation_sort takes a whole number",
761 )),
762 },
763 _ => Err(syn::Error::new_spanned(
764 expr,
765 "navigation_sort takes a whole number",
766 )),
767 }
768}
769
770fn latest_spec(meta: &syn::meta::ParseNestedMeta<'_>) -> syn::Result<LatestSpec> {
772 let mut title = None;
773 let mut limit = 5i64;
774 let mut columns = None;
775 meta.parse_nested_meta(|inner| {
776 if inner.path.is_ident("limit") {
777 let value: syn::LitInt = inner.value()?.parse()?;
778 limit = value.base10_parse::<i64>()?;
779 if limit < 1 {
780 return Err(syn::Error::new(value.span(), "limit must be at least 1"));
781 }
782 Ok(())
783 } else if inner.path.is_ident("columns") {
784 let list: LitStr = inner.value()?.parse()?;
785 let span = list.span();
786 let names: Vec<(String, Span)> = list
787 .value()
788 .split(',')
789 .map(|name| (name.trim().to_string(), span))
790 .collect();
791 columns = Some(names);
792 Ok(())
793 } else if inner.path.is_ident("title") {
794 title = Some(inner.value()?.parse::<LitStr>()?.value());
795 Ok(())
796 } else {
797 Err(inner.error("latest_records takes limit, columns and title"))
798 }
799 })?;
800 let columns = columns.ok_or_else(|| {
801 meta.error(
802 "latest_records needs columns = \"name,email\": the columns the dashboard table shows",
803 )
804 })?;
805 Ok(LatestSpec {
806 title,
807 limit,
808 columns,
809 })
810}
811
812fn latest_records_tokens(
815 spec: &LatestSpec,
816 fields: &[Field],
817 title: &str,
818 name: &syn::Ident,
819) -> syn::Result<TokenStream2> {
820 let mut keys = Vec::new();
821 for (key, span) in &spec.columns {
822 if key.is_empty() {
823 return Err(syn::Error::new(
824 *span,
825 "latest_records has an empty column name",
826 ));
827 }
828 let field = fields
829 .iter()
830 .find(|f| f.ident == key.as_str())
831 .ok_or_else(|| syn::Error::new(*span, format!("`{key}` is not a field of {name}")))?;
832 if field.is_password {
833 return Err(syn::Error::new(
834 *span,
835 format!("`{key}` is a password and cannot be shown on the dashboard"),
836 ));
837 }
838 keys.push(key.clone());
839 }
840 let table_title = spec
841 .title
842 .clone()
843 .unwrap_or_else(|| format!("Latest {title}"));
844 let limit = spec.limit;
845 Ok(quote! {
846 ::core::option::Option::Some(::ignite_core::LatestRecords {
847 title: #table_title,
848 columns: &[#(#keys),*],
849 limit: #limit,
850 })
851 })
852}
853
854fn field_attrs(field: &syn::Field) -> syn::Result<Field> {
856 let ident = field
857 .ident
858 .clone()
859 .ok_or_else(|| syn::Error::new_spanned(field, "IgniteResource needs named fields"))?;
860 let ty = field.ty.clone();
861 let (optional, inner) = match option_inner(&ty) {
862 Some(inner) => (true, inner.clone()),
863 None => (false, ty.clone()),
864 };
865 let base = base_of(&inner).ok_or_else(|| {
866 syn::Error::new_spanned(
867 &ty,
868 "unsupported field type: use String, i16, i32, i64, f32, f64, bool, chrono::NaiveDate, chrono::NaiveDateTime, or Option of one",
869 )
870 })?;
871
872 let mut label = None;
873 let mut form_type = None;
874 let mut required_attr = None;
875 let mut primary_key = false;
876 let mut searchable = false;
877 let mut sortable = false;
878 let mut hidden_on_index = false;
879 let mut options = None;
880 let mut belongs_to = None;
881 let mut display = None;
882 let mut step = None;
883 let mut sub_fields = None;
884 let mut blocks = None;
885 for attr in field.attrs.iter().filter(|a| a.path().is_ident("ignite")) {
886 attr.parse_nested_meta(|meta| {
887 if meta.path.is_ident("label") {
888 label = Some(meta.value()?.parse::<LitStr>()?.value());
889 } else if meta.path.is_ident("form_type") {
890 form_type = Some(meta.value()?.parse::<LitStr>()?);
891 } else if meta.path.is_ident("required") {
892 let value = if meta.input.peek(Token![=]) {
893 meta.value()?.parse::<LitBool>()?.value
894 } else {
895 true
896 };
897 required_attr = Some(value);
898 } else if meta.path.is_ident("primary_key") {
899 primary_key = true;
900 } else if meta.path.is_ident("searchable") {
901 searchable = true;
902 } else if meta.path.is_ident("sortable") {
903 sortable = true;
904 } else if meta.path.is_ident("hidden_on_index") {
905 hidden_on_index = true;
906 } else if meta.path.is_ident("options") {
907 let expr: syn::Expr = meta.value()?.parse()?;
908 options = Some(options_of(&expr)?);
909 } else if meta.path.is_ident("belongs_to") {
910 belongs_to = Some(meta.value()?.parse::<syn::Path>()?);
911 } else if meta.path.is_ident("display") {
912 display = Some(meta.value()?.parse::<syn::Ident>()?);
913 } else if meta.path.is_ident("step") {
914 step = Some(meta.value()?.parse::<LitStr>()?);
915 } else if meta.path.is_ident("fields") {
916 sub_fields = Some(meta.value()?.parse::<syn::Path>()?);
917 } else if meta.path.is_ident("blocks") {
918 blocks = Some(meta.value()?.parse::<syn::Path>()?);
919 } else {
920 return Err(meta.error(
921 "unknown ignite attribute; expected label, form_type, required, primary_key, searchable, sortable, hidden_on_index, options, belongs_to, display, step, fields or blocks",
922 ));
923 }
924 Ok(())
925 })?;
926 }
927
928 let lookup_attr = options.is_some() || belongs_to.is_some();
932 let choice_kind = match form_type.as_ref().map(|s| s.value()).as_deref() {
933 Some("radio") if matches!(options, Some(OptionsSpec::Static(_))) => Some(Kind::Radio),
934 Some("post_object") if lookup_attr && !matches!(options, Some(OptionsSpec::Static(_))) => {
935 Some(Kind::PostObject)
936 }
937 Some("taxonomy") if lookup_attr && !matches!(options, Some(OptionsSpec::Static(_))) => {
938 Some(Kind::Taxonomy)
939 }
940 Some("user") if lookup_attr && !matches!(options, Some(OptionsSpec::Static(_))) => {
941 Some(Kind::User)
942 }
943 Some("relationship") if matches!(options, Some(OptionsSpec::Dynamic(_))) => {
944 Some(Kind::Relationship)
945 }
946 _ => None,
947 };
948 if lookup_attr && form_type.is_some() && choice_kind.is_none() {
949 return Err(syn::Error::new_spanned(
950 &ty,
951 "a field with options or belongs_to is a select: remove form_type",
952 ));
953 }
954 if belongs_to.is_some() != display.is_some() {
955 return Err(syn::Error::new_spanned(
956 &ty,
957 "belongs_to and display go together: belongs_to = <model type>, display = <column>",
958 ));
959 }
960 if options.is_some() && belongs_to.is_some() {
961 return Err(syn::Error::new_spanned(
962 &ty,
963 "a field takes options or belongs_to, not both",
964 ));
965 }
966
967 let mut choices = Vec::new();
968 let mut lookup = None;
969 let kind = if let Some(spec) = options {
970 match spec {
971 OptionsSpec::Static(pairs) => {
972 if base != Base::Text {
973 return Err(syn::Error::new_spanned(
974 &ty,
975 "a field with a list of options must be a String (or Option<String>)",
976 ));
977 }
978 choices = pairs;
979 choice_kind.unwrap_or(Kind::Select)
980 }
981 OptionsSpec::Dynamic(path) => {
982 if !matches!(base, Base::Text | Base::Integer) {
983 return Err(syn::Error::new_spanned(
984 &ty,
985 "a field with options from a function must be a String or an integer",
986 ));
987 }
988 if choice_kind == Some(Kind::Relationship) && base != Base::Text {
989 return Err(syn::Error::new_spanned(
990 &ty,
991 "a relationship stores a JSON list, so it must be a String (or Option<String>)",
992 ));
993 }
994 lookup = Some(Lookup::Dynamic(path));
995 choice_kind.unwrap_or(Kind::Lookup)
996 }
997 }
998 } else if let Some(table) = belongs_to {
999 if base != Base::Integer {
1000 return Err(syn::Error::new_spanned(
1001 &ty,
1002 "a belongs_to field stores the related row's id, so it must be an i32 or i64",
1003 ));
1004 }
1005 lookup = Some(Lookup::Related {
1006 table,
1007 display: display
1008 .clone()
1009 .expect("checked: display is set with belongs_to"),
1010 });
1011 choice_kind.unwrap_or(Kind::Lookup)
1012 } else {
1013 match form_type.as_ref().map(|s| s.value()) {
1014 None => match base {
1015 Base::Bool => Kind::Checkbox,
1016 Base::Integer => Kind::Number,
1017 Base::Decimal => Kind::Decimal,
1018 Base::Date => Kind::Date,
1019 Base::DateTime => Kind::DateTime,
1020 Base::Text => Kind::Text,
1021 },
1022 Some(value) => match value.as_str() {
1023 "text" => Kind::Text,
1024 "textarea" => Kind::Textarea,
1025 "password" => Kind::Password,
1026 "number" if base == Base::Decimal => Kind::Decimal,
1027 "number" => Kind::Number,
1028 "checkbox" => Kind::Checkbox,
1029 "date" => Kind::Date,
1030 "email" => Kind::Email,
1031 "url" => Kind::Url,
1032 "color" => Kind::Color,
1033 "image" => Kind::Image,
1034 "file" => Kind::File,
1035 "link" => Kind::Link,
1036 "wysiwyg" => Kind::Wysiwyg,
1037 "gallery" => Kind::Gallery,
1038 "repeater" => Kind::Repeater,
1039 "group" => Kind::Group,
1040 "clone" => Kind::Clone,
1041 "flexible_content" => Kind::FlexibleContent,
1042 "radio" | "post_object" | "taxonomy" | "user" | "relationship" => {
1043 return Err(syn::Error::new(
1044 form_type.map(|s| s.span()).unwrap_or_else(Span::call_site),
1045 "form_type radio takes options = [...]; post_object, taxonomy and user take options = <function> or belongs_to; relationship takes options = <function>",
1046 ))
1047 }
1048 _ => return Err(syn::Error::new(
1049 form_type.map(|s| s.span()).unwrap_or_else(Span::call_site),
1050 "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",
1051 )),
1052 },
1053 }
1054 };
1055
1056 let sub_fields = match kind {
1058 Kind::Repeater | Kind::Group | Kind::Clone => match (sub_fields, blocks) {
1059 (Some(path), None) => Some(path),
1060 _ => {
1061 return Err(syn::Error::new_spanned(
1062 &ty,
1063 "a repeater, group or clone takes fields = <a &'static [ignite_core::Field] constant>",
1064 ))
1065 }
1066 },
1067 Kind::FlexibleContent => match (blocks, sub_fields) {
1068 (Some(path), None) => Some(path),
1069 _ => {
1070 return Err(syn::Error::new_spanned(
1071 &ty,
1072 "a flexible_content field takes blocks = <a &'static [ignite_core::Block] constant>",
1073 ))
1074 }
1075 },
1076 _ if sub_fields.is_some() || blocks.is_some() => {
1077 return Err(syn::Error::new_spanned(
1078 &ty,
1079 "fields and blocks apply to a repeater, group, clone or flexible_content field",
1080 ))
1081 }
1082 _ => None,
1083 };
1084 let text_kind =
1086 kind.checks_value() && !matches!(kind, Kind::PostObject | Kind::Taxonomy | Kind::User);
1087 if text_kind
1088 && base != Base::Text
1089 && !(matches!(kind, Kind::Image | Kind::File) && base == Base::Integer)
1090 {
1091 return Err(syn::Error::new_spanned(
1092 &ty,
1093 "this form_type stores text, so the field must be a String (or Option<String>); an image or file may also be an integer",
1094 ));
1095 }
1096
1097 if step.is_some() && base != Base::Decimal {
1098 return Err(syn::Error::new_spanned(
1099 &ty,
1100 "step applies to an f32 or f64 field",
1101 ));
1102 }
1103
1104 let required = required_attr.unwrap_or(!optional && base != Base::Bool);
1106 let label = label.unwrap_or_else(|| capitalize(&ident.to_string().replace('_', " ")));
1107
1108 Ok(Field {
1109 ident,
1110 ty,
1111 inner,
1112 base,
1113 optional,
1114 kind,
1115 label,
1116 required,
1117 primary_key,
1118 searchable,
1119 sortable,
1120 hidden_on_index,
1121 is_password: kind == Kind::Password,
1122 choices,
1123 lookup,
1124 step: step.map(|s| s.value()),
1125 sub_fields,
1126 })
1127}
1128
1129fn options_of(expr: &syn::Expr) -> syn::Result<OptionsSpec> {
1132 match expr {
1133 syn::Expr::Array(array) => {
1134 let mut pairs = Vec::new();
1135 for element in &array.elems {
1136 let syn::Expr::Tuple(tuple) = element else {
1137 return Err(syn::Error::new_spanned(
1138 element,
1139 "each option is a pair, such as (\"draft\", \"Draft\")",
1140 ));
1141 };
1142 let [value, label] = tuple.elems.iter().collect::<Vec<_>>()[..] else {
1143 return Err(syn::Error::new_spanned(
1144 tuple,
1145 "each option is a pair, such as (\"draft\", \"Draft\")",
1146 ));
1147 };
1148 pairs.push((string_literal(value)?, string_literal(label)?));
1149 }
1150 Ok(OptionsSpec::Static(pairs))
1151 }
1152 syn::Expr::Path(path) => Ok(OptionsSpec::Dynamic(path.path.clone())),
1153 _ => Err(syn::Error::new_spanned(
1154 expr,
1155 "options is a list of (\"value\", \"Label\") pairs, or the path of a function that returns them",
1156 )),
1157 }
1158}
1159
1160fn string_literal(expr: &syn::Expr) -> syn::Result<String> {
1162 match expr {
1163 syn::Expr::Lit(syn::ExprLit {
1164 lit: syn::Lit::Str(text),
1165 ..
1166 }) => Ok(text.value()),
1167 _ => Err(syn::Error::new_spanned(expr, "expected a string literal")),
1168 }
1169}
1170
1171fn option_inner(ty: &Type) -> Option<&Type> {
1173 let Type::Path(path) = ty else { return None };
1174 let segment = path.path.segments.last()?;
1175 if segment.ident != "Option" {
1176 return None;
1177 }
1178 let PathArguments::AngleBracketed(args) = &segment.arguments else {
1179 return None;
1180 };
1181 match args.args.first()? {
1182 GenericArgument::Type(inner) => Some(inner),
1183 _ => None,
1184 }
1185}
1186
1187fn base_of(ty: &Type) -> Option<Base> {
1189 let Type::Path(path) = ty else { return None };
1190 let ident = path.path.segments.last()?.ident.to_string();
1191 match ident.as_str() {
1192 "String" => Some(Base::Text),
1193 "i16" | "i32" | "i64" => Some(Base::Integer),
1194 "f32" | "f64" => Some(Base::Decimal),
1195 "bool" => Some(Base::Bool),
1196 "NaiveDate" => Some(Base::Date),
1197 "NaiveDateTime" => Some(Base::DateTime),
1198 _ => None,
1199 }
1200}
1201
1202fn is_key_type(ty: &Type) -> bool {
1204 let Type::Path(path) = ty else { return false };
1205 path.path
1206 .segments
1207 .last()
1208 .is_some_and(|s| matches!(s.ident.to_string().as_str(), "i32" | "i64"))
1209}
1210
1211fn kind_tokens(field: &Field) -> TokenStream2 {
1213 match field.kind {
1214 Kind::Text => quote! { ::ignite_core::FieldKind::Text },
1215 Kind::Textarea => quote! { ::ignite_core::FieldKind::Textarea },
1216 Kind::Password => quote! { ::ignite_core::FieldKind::Password },
1217 Kind::Number => quote! { ::ignite_core::FieldKind::Number },
1218 Kind::Decimal => {
1219 let step = field.step.as_deref().unwrap_or("any");
1220 quote! { ::ignite_core::FieldKind::Decimal(#step) }
1221 }
1222 Kind::Checkbox => quote! { ::ignite_core::FieldKind::Checkbox },
1223 Kind::Select => {
1224 let pairs = choice_pairs(&field.choices);
1225 quote! { ::ignite_core::FieldKind::Select(&[#(#pairs),*]) }
1226 }
1227 Kind::Lookup => quote! { ::ignite_core::FieldKind::Lookup },
1228 Kind::Date => quote! { ::ignite_core::FieldKind::Date },
1229 Kind::DateTime => quote! { ::ignite_core::FieldKind::DateTime },
1230 Kind::Email => quote! { ::ignite_core::FieldKind::Email },
1231 Kind::Url => quote! { ::ignite_core::FieldKind::Url },
1232 Kind::Radio => {
1233 let pairs = choice_pairs(&field.choices);
1234 quote! { ::ignite_core::FieldKind::Radio(&[#(#pairs),*]) }
1235 }
1236 Kind::Color => quote! { ::ignite_core::FieldKind::Color },
1237 Kind::Image => quote! { ::ignite_core::FieldKind::Image },
1238 Kind::File => quote! { ::ignite_core::FieldKind::File },
1239 Kind::Link => quote! { ::ignite_core::FieldKind::Link },
1240 Kind::Wysiwyg => quote! { ::ignite_core::FieldKind::Wysiwyg },
1241 Kind::PostObject => quote! { ::ignite_core::FieldKind::PostObject },
1242 Kind::Relationship => quote! { ::ignite_core::FieldKind::Relationship },
1243 Kind::Taxonomy => quote! { ::ignite_core::FieldKind::Taxonomy },
1244 Kind::User => quote! { ::ignite_core::FieldKind::User },
1245 Kind::Gallery => quote! { ::ignite_core::FieldKind::Gallery },
1246 Kind::Repeater | Kind::Group | Kind::Clone | Kind::FlexibleContent => {
1247 let path = field
1248 .sub_fields
1249 .as_ref()
1250 .expect("checked: a structured field has its sub-fields");
1251 match field.kind {
1252 Kind::Repeater => quote! { ::ignite_core::FieldKind::Repeater(#path) },
1253 Kind::Group => quote! { ::ignite_core::FieldKind::Group(#path) },
1254 Kind::Clone => quote! { ::ignite_core::FieldKind::Clone(#path) },
1255 _ => quote! { ::ignite_core::FieldKind::FlexibleContent(#path) },
1256 }
1257 }
1258 }
1259}
1260
1261fn choice_pairs(choices: &[(String, String)]) -> Vec<TokenStream2> {
1263 choices
1264 .iter()
1265 .map(|(value, label)| quote! { (#value, #label) })
1266 .collect()
1267}
1268
1269fn validate_expr(field: &Field) -> TokenStream2 {
1272 let ident = &field.ident;
1273 let name = ident.to_string();
1274 let label = &field.label;
1275 let kind = kind_tokens(field);
1276 let required = field.required;
1277 let base = field.base;
1278 let is_password = field.is_password;
1279 let ty = &field.inner;
1280
1281 let convert = match base {
1282 Base::Text if is_password => {
1283 let message = "Could not save this password.".to_string();
1284 quote! {
1285 match ::ignite_core::hash_password(text) {
1286 Ok(hash) => ::core::option::Option::Some(hash),
1287 Err(_) => {
1288 errors.insert(#name.to_string(), #message.to_string());
1289 ::core::option::Option::None
1290 }
1291 }
1292 }
1293 }
1294 Base::Text if field.kind == Kind::Select => {
1295 let pairs = choice_pairs(&field.choices);
1296 quote! {
1297 {
1298 let text = text.trim();
1299 let choices: &[(&str, &str)] = &[#(#pairs),*];
1300 if field.check_choice(text, choices, &mut errors) {
1301 ::core::option::Option::Some(text.to_string())
1302 } else {
1303 ::core::option::Option::None
1304 }
1305 }
1306 }
1307 }
1308 Base::Text if field.kind.checks_value() => quote! { field.check_value(text, &mut errors) },
1310 Base::Text => quote! { ::core::option::Option::Some(text.to_string()) },
1311 Base::Bool => quote! { ::core::option::Option::Some(form.checkbox(#name)) },
1312 Base::Integer if matches!(field.kind, Kind::Image | Kind::File) => quote! {
1314 field
1315 .check_value(text, &mut errors)
1316 .and_then(|id| id.parse::<#ty>().ok())
1317 },
1318 Base::Integer => quote! { field.check_whole_number::<#ty>(text, &mut errors) },
1319 Base::Decimal => quote! { field.check_decimal::<#ty>(text, &mut errors) },
1320 Base::Date => quote! { field.check_date(text, &mut errors) },
1321 Base::DateTime => quote! { field.check_datetime(text, &mut errors) },
1322 };
1323
1324 if base == Base::Bool {
1326 return quote! { let #ident = #convert; };
1327 }
1328
1329 quote! {
1332 let #ident = {
1333 let field = ::ignite_core::Field { name: #name, label: #label, kind: #kind, required: #required };
1334 let present = if #required && (creating || !#is_password) {
1335 field.check_required(form, &mut errors)
1336 } else {
1337 form.get(#name)
1338 };
1339 match present {
1340 ::core::option::Option::Some(text) => { let text: &str = text; #convert }
1341 ::core::option::Option::None => ::core::option::Option::None,
1342 }
1343 };
1344 }
1345}
1346
1347fn options_method(lookups: &[&Field]) -> TokenStream2 {
1350 if lookups.is_empty() {
1351 return quote! {};
1352 }
1353 let arms = lookups.iter().map(|f| {
1354 let name_lit = f.ident.to_string();
1355 match f.lookup.as_ref().expect("checked: a lookup field") {
1356 Lookup::Dynamic(path) => quote! { #name_lit => #path(db).await, },
1357 Lookup::Related { table, display } => {
1358 let key_ty = &f.inner;
1359 let display_lit = display.to_string();
1360 quote! {
1361 #name_lit => {
1362 let rows: ::std::vec::Vec<(#key_ty, ::std::string::String)> =
1363 <#table as ::orbit_orm::Model>::query()
1364 .select(&[<#table as ::orbit_orm::Model>::PRIMARY_KEY, #display_lit])
1365 .order_by(#display_lit, ::orbit_orm::Direction::Asc)
1366 .get_as(db)
1367 .await?;
1368 ::core::result::Result::Ok(
1369 rows.into_iter().map(|(id, label)| (id.to_string(), label)).collect(),
1370 )
1371 }
1372 }
1373 }
1374 }
1375 });
1376 quote! {
1377 async fn options(
1378 db: &::ignite_core::Database,
1379 field: &str,
1380 ) -> ::core::result::Result<::std::vec::Vec<(::std::string::String, ::std::string::String)>, ::orbit_orm::Error> {
1381 match field {
1382 #(#arms)*
1383 _ => ::core::result::Result::Ok(::std::vec::Vec::new()),
1384 }
1385 }
1386 }
1387}
1388
1389fn capitalize(text: &str) -> String {
1390 let mut chars = text.chars();
1391 match chars.next() {
1392 Some(first) => first.to_uppercase().collect::<String>() + chars.as_str(),
1393 None => String::new(),
1394 }
1395}