1use proc_macro::TokenStream;
62use proc_macro2::TokenStream as TokenStream2;
63use quote::quote;
64use syn::spanned::Spanned;
65use syn::{
66 parse_macro_input, Data, DataEnum, DeriveInput, Fields, GenericArgument, Ident, PathArguments,
67 Type,
68};
69
70mod sql;
71
72#[proc_macro]
89pub fn sql(input: TokenStream) -> TokenStream {
90 sql::expand_sql(input)
91}
92
93#[proc_macro_derive(RecordDecode, attributes(record, serde))]
98pub fn derive_record_decode(input: TokenStream) -> TokenStream {
99 let input = parse_macro_input!(input as DeriveInput);
100 let output = match expand_derive(&input) {
101 Ok(tokens) => tokens,
102 Err(err) => err.to_compile_error(),
103 };
104 output.into()
105}
106
107#[proc_macro_derive(RecordEncode, attributes(record, serde))]
114pub fn derive_record_encode(input: TokenStream) -> TokenStream {
115 let input = parse_macro_input!(input as DeriveInput);
116 let output = match expand_encode_derive(&input) {
117 Ok(tokens) => tokens,
118 Err(err) => err.to_compile_error(),
119 };
120 output.into()
121}
122
123fn check_alt_hasher_fields(input: &DeriveInput) -> syn::Result<()> {
133 match &input.data {
134 Data::Struct(d) => {
135 for field in d.fields.iter() {
136 check_alt_hasher_type(&field.ty)?;
137 }
138 }
139 Data::Enum(e) => {
140 for variant in &e.variants {
141 for field in variant.fields.iter() {
142 check_alt_hasher_type(&field.ty)?;
143 }
144 }
145 }
146 Data::Union(_) => {}
147 }
148 Ok(())
149}
150
151fn check_alt_hasher_type(ty: &Type) -> syn::Result<()> {
153 match ty {
154 Type::Path(tp) => {
155 if let Some(seg) = tp.path.segments.last() {
156 let name = seg.ident.to_string();
157 if name == "AHashMap" && !cfg!(feature = "ahash") {
158 return Err(syn::Error::new(
159 ty.span(),
160 "RecordEncode/RecordDecode: `AHashMap` fields need the `ahash` feature",
161 ));
162 }
163 if name == "FxHashMap" && !cfg!(feature = "fxhash") {
164 return Err(syn::Error::new(
165 ty.span(),
166 "RecordEncode/RecordDecode: `FxHashMap` fields need the `fxhash` feature",
167 ));
168 }
169 if name == "AHashSet" && !cfg!(feature = "ahash") {
170 return Err(syn::Error::new(
171 ty.span(),
172 "RecordEncode/RecordDecode: `AHashSet` fields need the `ahash` feature",
173 ));
174 }
175 if name == "FxHashSet" && !cfg!(feature = "fxhash") {
176 return Err(syn::Error::new(
177 ty.span(),
178 "RecordEncode/RecordDecode: `FxHashSet` fields need the `fxhash` feature",
179 ));
180 }
181 if let PathArguments::AngleBracketed(args) = &seg.arguments {
184 for arg in &args.args {
185 if let GenericArgument::Type(inner) = arg {
186 check_alt_hasher_type(inner)?;
187 }
188 }
189 }
190 }
191 Ok(())
192 }
193 Type::Reference(r) => check_alt_hasher_type(&r.elem),
194 Type::Slice(s) => check_alt_hasher_type(&s.elem),
195 Type::Array(a) => check_alt_hasher_type(&a.elem),
196 Type::Paren(p) => check_alt_hasher_type(&p.elem),
197 Type::Group(g) => check_alt_hasher_type(&g.elem),
198 _ => Ok(()),
199 }
200}
201
202fn expand_derive(input: &DeriveInput) -> syn::Result<TokenStream2> {
203 let name = &input.ident;
204 check_alt_hasher_fields(input)?;
205 let mut lifetimes: Vec<&syn::LifetimeParam> = input
210 .generics
211 .params
212 .iter()
213 .filter_map(|p| match p {
214 syn::GenericParam::Lifetime(lt) => Some(lt),
215 _ => None,
216 })
217 .collect();
218 if lifetimes.len() > 1 {
219 return Err(syn::Error::new(
220 input.generics.span(),
221 "RecordDecode supports at most one lifetime parameter",
222 ));
223 }
224
225 let borrowed = lifetimes.pop();
226 let borrow = match borrowed {
227 Some(lt) => {
228 let life = <.lifetime;
229 BorrowCfg {
230 clause: quote! { <#life> },
231 inherent_clause: quote! { <#life> },
232 self_ty: quote! { #name<#life> },
233 helper_clause: quote! {},
234 lt: life.clone(),
235 owned_try_from: false,
236 }
237 }
238 None => BorrowCfg {
239 clause: quote! { <'de> },
240 inherent_clause: quote! {},
241 self_ty: quote! { #name },
242 helper_clause: quote! { <'de> },
243 lt: syn::Lifetime::new("'de", proc_macro2::Span::call_site()),
244 owned_try_from: true,
245 },
246 };
247 if let Some(p) = input
248 .generics
249 .params
250 .iter()
251 .find(|p| !matches!(p, syn::GenericParam::Lifetime(_)))
252 {
253 return Err(syn::Error::new(
254 p.span(),
255 "RecordDecode does not support type/const generic parameters",
256 ));
257 }
258
259 let container = ContainerCfg::parse(input)?;
260
261 match &input.data {
262 Data::Struct(data) => expand_struct(name, data, &container, &borrow),
263 Data::Enum(data) => expand_enum(name, data, &container, &borrow),
264 Data::Union(data) => Err(syn::Error::new(
265 data.union_token.span(),
266 "RecordDecode does not support unions",
267 )),
268 }
269}
270
271struct BorrowCfg {
273 clause: TokenStream2,
275 inherent_clause: TokenStream2,
279 self_ty: TokenStream2,
281 helper_clause: TokenStream2,
284 lt: syn::Lifetime,
286 owned_try_from: bool,
289}
290
291fn expand_struct(
292 name: &Ident,
293 data: &syn::DataStruct,
294 container: &ContainerCfg,
295 borrow: &BorrowCfg,
296) -> syn::Result<TokenStream2> {
297 let Fields::Named(fields) = &data.fields else {
298 return expand_tuple_struct(name, data, container, borrow);
299 };
300
301 let crate_path = &container.crate_path;
302
303 let mut field_lets = Vec::new();
305 let mut flat_fields: Vec<(Ident, Type, Option<Type>)> = Vec::new();
306 let mut non_flat_keys: Vec<String> = Vec::new();
307 let mut wire_kinds: Vec<(String, String)> = Vec::new();
308
309 for field in &fields.named {
310 let fident = field.ident.as_ref().expect("named field ident").clone();
311 let cfg = FieldCfg::parse(field)?;
312 let ty = &field.ty;
313
314 let wire = match (&cfg.rename, container.rename_all) {
318 (Some(r), _) => r.clone(),
319 (None, Some(rule)) => rule.apply_to_field(&fident.to_string()),
320 (None, None) => fident.to_string(),
321 };
322
323 if cfg.skip_decode {
324 field_lets.push(quote! {
325 let #fident: #ty = ::core::default::Default::default();
326 });
327 continue;
328 }
329
330 if cfg.with.is_none() {
334 if let Some(db_type) = db_type_of(ty) {
335 wire_kinds.push((wire.clone(), db_type));
336 }
337 }
338
339 if cfg.flatten {
341 if !flat_fields.is_empty() {
342 return Err(syn::Error::new(
343 field.span(),
344 "RecordDecode supports at most one flattened field per struct",
345 ));
346 }
347 if cfg.with.is_some() {
348 return Err(syn::Error::new(
349 field.span(),
350 "RecordDecode: `with` cannot be combined with a flattened field",
351 ));
352 }
353 let opt_inner = option_inner(ty);
354 flat_fields.push((fident, ty.clone(), opt_inner));
355 continue;
356 }
357
358 non_flat_keys.push(wire.clone());
359
360 if wire == "@rid" || wire == "@type" {
367 let syn = if wire == "@rid" {
368 quote! { __arcade_syn_rid }
369 } else {
370 quote! { __arcade_syn_type }
371 };
372 if cfg.with.is_some() {
373 return Err(syn::Error::new(
374 field.span(),
375 "RecordDecode: `with` cannot be combined with `@rid`/`@type` synthesis",
376 ));
377 }
378 field_lets.push(synth_field_let(
379 &fident,
380 ty,
381 &wire,
382 &cfg.default,
383 &syn,
384 crate_path,
385 )?);
386 continue;
387 }
388
389 if let Some(with_path) = &cfg.with {
393 let call = if let Some(inner) = option_inner(ty) {
394 quote! {
395 #[allow(clippy::redundant_closure_call)]
396 let #fident: #ty = #crate_path::record::get_opt_with::<#inner>(
397 __arcade_props,
398 __arcade_taken,
399 #wire,
400 #with_path,
401 )?;
402 }
403 } else if cfg.default.is_some() {
404 let fallback = default_fallback(&cfg.default);
405 quote! {
406 #[allow(clippy::redundant_closure_call)]
407 let #fident: #ty = #crate_path::record::get_with_or::<#ty>(
408 __arcade_props,
409 __arcade_taken,
410 #wire,
411 #with_path,
412 #fallback,
413 )?;
414 }
415 } else {
416 quote! {
417 #[allow(clippy::redundant_closure_call)]
418 let #fident: #ty = #crate_path::record::get_with::<#ty>(
419 __arcade_props,
420 __arcade_taken,
421 #wire,
422 #with_path,
423 )?;
424 }
425 };
426 field_lets.push(call);
427 continue;
428 }
429
430 if let Some(inner) = option_inner(ty) {
432 let call = if vec_u8(&inner) {
433 quote! {
435 let #fident: #ty = #crate_path::record::get_opt_bytes(
436 __arcade_props,
437 __arcade_taken,
438 #wire,
439 )?;
440 }
441 } else {
442 quote! {
443 let #fident: #ty = #crate_path::record::get_opt(
444 __arcade_props,
445 __arcade_taken,
446 #wire,
447 )?;
448 }
449 };
450 field_lets.push(call);
451 continue;
452 }
453
454 if vec_u8(ty) {
457 let call = match &cfg.default {
458 None => quote! {
459 let #fident: #ty = #crate_path::record::get_bytes(__arcade_props, __arcade_taken, #wire)?;
460 },
461 Some(None) => quote! {
462 let #fident: #ty = #crate_path::record::get_bytes_or(
463 __arcade_props,
464 __arcade_taken,
465 #wire,
466 ::core::default::Default::default,
467 )?;
468 },
469 Some(Some(path)) => quote! {
470 let #fident: #ty = #crate_path::record::get_bytes_or(
471 __arcade_props,
472 __arcade_taken,
473 #wire,
474 #path,
475 )?;
476 },
477 };
478 field_lets.push(call);
479 continue;
480 }
481
482 match &cfg.default {
484 None => {
485 field_lets.push(quote! {
486 let #fident: #ty = #crate_path::record::get(
487 __arcade_props,
488 __arcade_taken,
489 #wire,
490 )?;
491 });
492 }
493 Some(None) => {
494 field_lets.push(quote! {
495 let #fident: #ty = #crate_path::record::get_or(
496 __arcade_props,
497 __arcade_taken,
498 #wire,
499 ::core::default::Default::default,
500 )?;
501 });
502 }
503 Some(Some(path)) => {
504 field_lets.push(quote! {
505 let #fident: #ty = #crate_path::record::get_or(
506 __arcade_props,
507 __arcade_taken,
508 #wire,
509 #path,
510 )?;
511 });
512 }
513 }
514 }
515
516 let wire_kind_pairs: Vec<TokenStream2> = wire_kinds
517 .iter()
518 .map(|(w, k)| quote! { (#w, #k) })
519 .collect();
520
521 for (fident, ty, opt_inner) in &flat_fields {
527 let own_taken = &non_flat_keys;
530 let own_len = own_taken.len();
531 let taken_stmt = quote! {
532 let mut __arcade_t: ::std::vec::Vec<&str> =
533 ::std::vec::Vec::with_capacity(__arcade_taken.len() + #own_len);
534 __arcade_t.extend(__arcade_taken.iter().copied());
535 __arcade_t.extend([#(#own_taken),*]);
536 };
537 if let Some(inner) = opt_inner {
538 field_lets.push(quote! {
539 let #fident: #ty = {
540 #taken_stmt
541 if __arcade_props
545 .keys()
546 .any(|__arcade_k| !__arcade_t.contains(&__arcade_k.as_str()))
547 {
548 ::core::option::Option::Some(
549 <#inner as #crate_path::record::DecodeFromMap>::from_map(
550 __arcade_props,
551 &__arcade_t,
552 ::core::option::Option::None,
553 ::core::option::Option::None,
554 )
555 .map_err(|e| e.with_field(stringify!(#fident)))?
556 )
557 } else {
558 ::core::option::Option::None
559 }
560 };
561 });
562 } else {
563 field_lets.push(quote! {
564 #taken_stmt
565 let #fident: #ty = <#ty as #crate_path::record::DecodeFromMap>::from_map(
566 __arcade_props,
567 &__arcade_t,
568 ::core::option::Option::None,
569 ::core::option::Option::None,
570 )
571 .map_err(|e| e.with_field(stringify!(#fident)))?;
572 });
573 }
574 }
575
576 let assigns = fields.named.iter().map(|f| {
577 let ident = f.ident.as_ref().expect("named field ident");
578 quote! { #ident }
579 });
580
581 let synth = quote! {
585 let __arcade_props = &rec.properties;
586 };
587
588 let BorrowCfg {
589 clause,
590 inherent_clause,
591 self_ty,
592 helper_clause,
593 lt,
594 owned_try_from,
595 } = borrow;
596 let owned_try_from = owned_try_from.then(|| {
600 quote! {
601 #[automatically_derived]
602 impl ::core::convert::TryFrom<#crate_path::GrpcRecord> for #self_ty {
603 type Error = #crate_path::record::RecordDecodeError;
604
605 fn try_from(
606 rec: #crate_path::GrpcRecord,
607 ) -> ::std::result::Result<Self, Self::Error> {
608 Self::try_from(&rec)
609 }
610 }
611 }
612 });
613
614 Ok(quote! {
615 #[automatically_derived]
616 #[allow(non_snake_case)]
620 impl #inherent_clause #self_ty {
621 #[doc(hidden)]
622 #[allow(clippy::too_many_arguments)]
623 fn __arcade_decode_from_map #helper_clause (
624 __arcade_props: & #lt ::std::collections::HashMap<
625 ::std::string::String,
626 #crate_path::GrpcValue,
627 >,
628 __arcade_taken: &[&str],
629 __arcade_syn_rid: ::core::option::Option<&::std::string::String>,
630 __arcade_syn_type: ::core::option::Option<&::std::string::String>,
631 ) -> ::std::result::Result<Self, #crate_path::record::RecordDecodeError> {
632 #(#field_lets)*
633 ::std::result::Result::Ok(Self { #(#assigns),* })
634 }
635
636 pub const WIRES: &'static [&'static str] = &[#(#non_flat_keys),*];
641
642 pub fn select_list() -> &'static str {
647 static LIST: ::std::sync::OnceLock<&'static str> = ::std::sync::OnceLock::new();
648 LIST.get_or_init(|| Self::WIRES.join(", ").leak())
649 }
650
651 pub const WIRE_KINDS: &'static [(&'static str, &'static str)] =
657 &[#(#wire_kind_pairs),*];
658 }
659
660 #[automatically_derived]
661 impl #clause #crate_path::record::DecodeFromMap<#lt> for #self_ty {
662 fn from_map(
663 __arcade_props: & #lt ::std::collections::HashMap<
664 ::std::string::String,
665 #crate_path::GrpcValue,
666 >,
667 __arcade_taken: &[&str],
668 __arcade_syn_rid: ::core::option::Option<&::std::string::String>,
669 __arcade_syn_type: ::core::option::Option<&::std::string::String>,
670 ) -> ::std::result::Result<Self, #crate_path::record::RecordDecodeError> {
671 Self::__arcade_decode_from_map(
672 __arcade_props,
673 __arcade_taken,
674 __arcade_syn_rid,
675 __arcade_syn_type,
676 )
677 }
678 }
679
680 #[automatically_derived]
681 impl #clause #crate_path::record::FromGrpcValue<#lt> for #self_ty {
682 fn from_grpc_value(
683 __arcade_v: & #lt #crate_path::GrpcValue,
684 ) -> ::std::result::Result<Self, #crate_path::record::RecordDecodeError> {
685 match &__arcade_v.kind {
686 ::core::option::Option::Some(#crate_path::Kind::EmbeddedValue(__arcade_e)) => {
687 Self::__arcade_decode_from_map(
688 &__arcade_e.fields,
689 &[],
690 ::core::option::Option::None,
691 ::core::option::Option::None,
692 )
693 }
694 ::core::option::Option::Some(#crate_path::Kind::MapValue(__arcade_m)) => {
695 Self::__arcade_decode_from_map(
696 &__arcade_m.entries,
697 &[],
698 ::core::option::Option::None,
699 ::core::option::Option::None,
700 )
701 }
702 _ => ::std::result::Result::Err(
703 #crate_path::record::RecordDecodeError::type_mismatch(
704 "embedded record",
705 #crate_path::record::kind_name(&__arcade_v.kind),
706 ),
707 ),
708 }
709 }
710 }
711
712 #[automatically_derived]
713 impl #clause ::core::convert::TryFrom<&#lt #crate_path::GrpcRecord>
714 for #self_ty
715 {
716 type Error = #crate_path::record::RecordDecodeError;
717
718 fn try_from(rec: &#lt #crate_path::GrpcRecord) -> ::std::result::Result<Self, Self::Error> {
719 #synth
720 Self::__arcade_decode_from_map(
721 __arcade_props,
722 &[],
723 (!rec.rid.is_empty()).then_some(&rec.rid),
724 (!rec.r#type.is_empty()).then_some(&rec.r#type),
725 )
726 }
727 }
728
729 #owned_try_from
730 })
731}
732
733fn expand_tuple_struct(
743 name: &Ident,
744 data: &syn::DataStruct,
745 container: &ContainerCfg,
746 borrow: &BorrowCfg,
747) -> syn::Result<TokenStream2> {
748 let crate_path = &container.crate_path;
749 match &data.fields {
750 Fields::Unnamed(fields) if fields.unnamed.len() == 1 => {
751 let inner = &fields.unnamed[0].ty;
752 let BorrowCfg {
753 clause,
754 self_ty,
755 lt,
756 ..
757 } = borrow;
758
759 Ok(quote! {
760 #[automatically_derived]
761 impl #clause #crate_path::record::FromGrpcValue<#lt>
762 for #self_ty
763 {
764 fn from_grpc_value(
765 __arcade_v: & #lt #crate_path::GrpcValue,
766 ) -> ::std::result::Result<Self, #crate_path::record::RecordDecodeError> {
767 let __arcade_inner =
768 <#inner as #crate_path::record::FromGrpcValue<#lt>>::from_grpc_value(
769 __arcade_v,
770 )?;
771 ::std::result::Result::Ok(#name(__arcade_inner))
772 }
773 }
774 })
775 }
776 _ => Ok(quote! {}),
779 }
780}
781
782fn expand_enum(
787 name: &Ident,
788 data: &DataEnum,
789 container: &ContainerCfg,
790 borrow: &BorrowCfg,
791) -> syn::Result<TokenStream2> {
792 let crate_path = &container.crate_path;
793
794 if let Some(tag) = &container.tag {
798 return expand_internally_tagged_enum(name, data, container, tag, borrow);
799 }
800
801 let mut variants = Vec::new();
802 for variant in &data.variants {
803 if !matches!(variant.fields, Fields::Unit) {
804 return Err(syn::Error::new(
805 variant.span(),
806 "RecordDecode on enums supports unit variants only; \
807 for data-carrying variants implement `FromGrpcValue` manually \
808 (or decode with `#[record(with = \"...\")]`)",
809 ));
810 }
811 let vident = &variant.ident;
812 let wire = variant_wire_name(variant, container)?;
813 variants.push(quote! { #wire => ::core::result::Result::Ok(Self::#vident) });
814 }
815
816 let BorrowCfg {
817 clause,
818 self_ty,
819 lt,
820 ..
821 } = borrow;
822 Ok(quote! {
823 #[automatically_derived]
824 impl #clause #crate_path::record::FromGrpcValue<#lt> for #self_ty {
825 fn from_grpc_value(
826 __arcade_v: & #lt #crate_path::GrpcValue,
827 ) -> ::std::result::Result<Self, #crate_path::record::RecordDecodeError> {
828 let __arcade_s = match &__arcade_v.kind {
829 ::core::option::Option::Some(#crate_path::Kind::StringValue(__arcade_s)) => {
830 __arcade_s.as_str()
831 }
832 _ => {
833 return ::std::result::Result::Err(
834 #crate_path::record::RecordDecodeError::type_mismatch(
835 "string",
836 #crate_path::record::kind_name(&__arcade_v.kind),
837 ),
838 )
839 }
840 };
841 match __arcade_s {
842 #(#variants,)*
843 __other => ::std::result::Result::Err(
844 #crate_path::record::RecordDecodeError::unknown_variant(__other),
845 ),
846 }
847 }
848 }
849 })
850}
851
852fn expand_internally_tagged_enum(
860 _name: &Ident,
861 data: &DataEnum,
862 container: &ContainerCfg,
863 tag: &str,
864 borrow: &BorrowCfg,
865) -> syn::Result<TokenStream2> {
866 let crate_path = &container.crate_path;
867 let props = syn::Ident::new("__arcade_map", proc_macro2::Span::call_site());
868
869 let mut arms = Vec::new();
870 for variant in &data.variants {
871 let vident = &variant.ident;
872 let wire = variant_wire_name(variant, container)?;
873 match &variant.fields {
874 Fields::Unit => {
875 arms.push(quote! { #wire => ::std::result::Result::Ok(Self::#vident) });
876 }
877 Fields::Named(fields) => {
878 let lets = variant_field_lets(fields, container, &props)?;
879 let assigns = fields
880 .named
881 .iter()
882 .map(|f| f.ident.as_ref().expect("named field ident"));
883 arms.push(quote! {
884 #wire => {
885 #(#lets)*
886 ::std::result::Result::Ok(Self::#vident { #(#assigns),* })
887 }
888 });
889 }
890 Fields::Unnamed(_) => {
891 return Err(syn::Error::new(
892 variant.span(),
893 "RecordDecode on internally-tagged enums supports struct variants only",
894 ));
895 }
896 }
897 }
898
899 let BorrowCfg {
900 clause,
901 self_ty,
902 lt,
903 ..
904 } = borrow;
905
906 let walk = quote! {
909 let __arcade_tag = match #crate_path::record::visible(__arcade_map, #tag, __arcade_taken) {
910 ::core::option::Option::Some(__arcade_t) => __arcade_t,
911 ::core::option::Option::None => {
912 return ::std::result::Result::Err(
913 #crate_path::record::RecordDecodeError::missing_field(#tag),
914 )
915 }
916 };
917 let __arcade_wire = match &__arcade_tag.kind {
918 ::core::option::Option::Some(#crate_path::Kind::StringValue(__arcade_s)) => {
919 __arcade_s.as_str()
920 }
921 _ => {
922 return ::std::result::Result::Err(
923 #crate_path::record::RecordDecodeError::type_mismatch(
924 "string",
925 #crate_path::record::kind_name(&__arcade_tag.kind),
926 ),
927 )
928 }
929 };
930 match __arcade_wire {
931 #(#arms,)*
932 __other => ::std::result::Result::Err(
933 #crate_path::record::RecordDecodeError::unknown_variant(__other),
934 ),
935 }
936 };
937
938 Ok(quote! {
939 #[automatically_derived]
940 impl #clause #crate_path::record::FromGrpcValue<#lt> for #self_ty {
941 fn from_grpc_value(
942 __arcade_v: & #lt #crate_path::GrpcValue,
943 ) -> ::std::result::Result<Self, #crate_path::record::RecordDecodeError> {
944 let __arcade_taken: &[&str] = &[];
946 let __arcade_map = match &__arcade_v.kind {
947 ::core::option::Option::Some(#crate_path::Kind::EmbeddedValue(__arcade_e)) => {
948 &__arcade_e.fields
949 }
950 ::core::option::Option::Some(#crate_path::Kind::MapValue(__arcade_m)) => {
951 &__arcade_m.entries
952 }
953 _ => {
954 return ::std::result::Result::Err(
955 #crate_path::record::RecordDecodeError::type_mismatch(
956 "record/map",
957 #crate_path::record::kind_name(&__arcade_v.kind),
958 ),
959 )
960 }
961 };
962 #walk
963 }
964 }
965
966 #[automatically_derived]
967 impl #clause #crate_path::record::DecodeFromMap<#lt> for #self_ty {
968 fn from_map(
969 __arcade_props: & #lt ::std::collections::HashMap<
970 ::std::string::String,
971 #crate_path::GrpcValue,
972 >,
973 __arcade_taken: &[&str],
974 _syn_rid: ::core::option::Option<&::std::string::String>,
975 _syn_type: ::core::option::Option<&::std::string::String>,
976 ) -> ::std::result::Result<Self, #crate_path::record::RecordDecodeError> {
977 let __arcade_map = __arcade_props;
978 #walk
979 }
980 }
981 })
982}
983
984fn variant_field_lets(
988 fields: &syn::FieldsNamed,
989 container: &ContainerCfg,
990 props: &syn::Ident,
991) -> syn::Result<Vec<TokenStream2>> {
992 let crate_path = &container.crate_path;
993
994 let mut lets = Vec::new();
995 for field in &fields.named {
996 let fident = field.ident.as_ref().expect("named field ident").clone();
997 let cfg = FieldCfg::parse(field)?;
998 let ty = &field.ty;
999
1000 if cfg.flatten {
1001 return Err(syn::Error::new(
1002 field.span(),
1003 "RecordDecode: `flatten` is not supported inside enum variants",
1004 ));
1005 }
1006 if cfg.skip_decode {
1007 lets.push(quote! {
1008 let #fident: #ty = ::core::default::Default::default();
1009 });
1010 continue;
1011 }
1012
1013 let wire = match (&cfg.rename, container.rename_all_fields) {
1014 (Some(r), _) => r.clone(),
1015 (None, Some(rule)) => rule.apply_to_field(&fident.to_string()),
1016 (None, None) => fident.to_string(),
1017 };
1018
1019 if let Some(with_path) = &cfg.with {
1021 if let Some(inner) = option_inner(ty) {
1022 lets.push(quote! {
1023 let #fident: #ty = #crate_path::record::get_opt_with::<#inner>(
1024 #props,
1025 __arcade_taken,
1026 #wire,
1027 #with_path,
1028 )?;
1029 });
1030 } else if cfg.default.is_some() {
1031 let fallback = default_fallback(&cfg.default);
1032 lets.push(quote! {
1033 let #fident: #ty = #crate_path::record::get_with_or::<#ty>(
1034 #props,
1035 __arcade_taken,
1036 #wire,
1037 #with_path,
1038 #fallback,
1039 )?;
1040 });
1041 } else {
1042 lets.push(quote! {
1043 let #fident: #ty = #crate_path::record::get_with::<#ty>(
1044 #props,
1045 __arcade_taken,
1046 #wire,
1047 #with_path,
1048 )?;
1049 });
1050 }
1051 continue;
1052 }
1053
1054 if option_inner(ty).is_some() {
1055 lets.push(quote! {
1056 let #fident: #ty = #crate_path::record::get_opt(
1057 #props,
1058 __arcade_taken,
1059 #wire,
1060 )?;
1061 });
1062 continue;
1063 }
1064
1065 match &cfg.default {
1066 None => {
1067 lets.push(quote! {
1068 let #fident: #ty = #crate_path::record::get(#props, __arcade_taken, #wire)?;
1069 });
1070 }
1071 Some(None) => {
1072 lets.push(quote! {
1073 let #fident: #ty = #crate_path::record::get_or(
1074 #props,
1075 __arcade_taken,
1076 #wire,
1077 ::core::default::Default::default,
1078 )?;
1079 });
1080 }
1081 Some(Some(path)) => {
1082 lets.push(quote! {
1083 let #fident: #ty = #crate_path::record::get_or(
1084 #props,
1085 __arcade_taken,
1086 #wire,
1087 #path,
1088 )?;
1089 });
1090 }
1091 }
1092 }
1093 Ok(lets)
1094}
1095
1096fn default_fallback(default: &Option<Option<syn::Path>>) -> TokenStream2 {
1099 match default {
1100 Some(None) => quote! { ::core::default::Default::default },
1101 Some(Some(path)) => quote! { #path },
1102 None => quote! { ::core::default::Default::default },
1104 }
1105}
1106
1107fn variant_wire_name(variant: &syn::Variant, container: &ContainerCfg) -> syn::Result<String> {
1111 for attr in &variant.attrs {
1112 if attr.path().is_ident("serde") {
1113 let mut rename = None;
1114 let mut serialize_rename = None;
1115 attr.parse_nested_meta(|meta| {
1116 if meta.path.is_ident("rename") {
1117 parse_rename(&meta, &mut rename, &mut serialize_rename)?;
1118 } else {
1119 ignore_meta(&meta)?;
1120 }
1121 Ok(())
1122 })?;
1123 if let Some(r) = rename {
1124 return Ok(r);
1125 }
1126 }
1127 }
1128 if let Some(rule) = container.rename_all {
1129 return Ok(rule.apply_to_variant(&variant.ident.to_string()));
1130 }
1131 Ok(variant.ident.to_string())
1132}
1133
1134struct ContainerCfg {
1140 crate_path: syn::Path,
1141 rename_all: Option<RenameRule>,
1142 rename_all_fields: Option<RenameRule>,
1146 tag: Option<String>,
1149}
1150
1151impl ContainerCfg {
1152 fn parse(input: &DeriveInput) -> syn::Result<Self> {
1153 let mut crate_path: Option<syn::Path> = None;
1154 let mut rename_all: Option<RenameRule> = None;
1155 let mut rename_all_fields: Option<RenameRule> = None;
1156 let mut tag: Option<String> = None;
1157
1158 for attr in &input.attrs {
1159 if attr.path().is_ident("serde") {
1160 attr.parse_nested_meta(|meta| {
1161 if meta.path.is_ident("rename_all") || meta.path.is_ident("rename_all_fields") {
1162 let value = meta.value()?;
1163 let s: syn::LitStr = value.parse()?;
1164 let rule = RenameRule::parse(&s.value()).ok_or_else(|| {
1165 meta.error(format!(
1166 "unknown rename_all rule `{}`; expected one of `lowercase`, \
1167 `UPPERCASE`, `PascalCase`, `camelCase`, `snake_case`, \
1168 `SCREAMING_SNAKE_CASE`, `kebab-case`, `SCREAMING-KEBAB-CASE`",
1169 s.value(),
1170 ))
1171 })?;
1172 if meta.path.is_ident("rename_all") {
1173 rename_all = Some(rule);
1174 } else {
1175 rename_all_fields = Some(rule);
1176 }
1177 Ok(())
1178 } else if meta.path.is_ident("tag") {
1179 let value = meta.value()?;
1180 let s: syn::LitStr = value.parse()?;
1181 tag = Some(s.value());
1182 Ok(())
1183 } else {
1184 ignore_meta(&meta)
1186 }
1187 })?;
1188 } else if attr.path().is_ident("record") {
1189 attr.parse_nested_meta(|meta| {
1190 if meta.path.is_ident("crate_path") {
1191 let value = meta.value()?;
1192 let s: syn::LitStr = value.parse()?;
1193 crate_path = Some(s.parse()?);
1194 Ok(())
1195 } else {
1196 Err(meta.error("unknown `record` container attribute"))
1197 }
1198 })?;
1199 }
1200 }
1201
1202 Ok(Self {
1203 crate_path: crate_path.unwrap_or_else(|| syn::parse_quote!(::arcadedb_protocol)),
1204 rename_all,
1205 rename_all_fields,
1206 tag,
1207 })
1208 }
1209}
1210
1211struct FieldCfg {
1213 rename: Option<String>,
1215 serialize_rename: Option<String>,
1219 default: Option<Option<syn::Path>>,
1222 with: Option<syn::Path>,
1225 skip_decode: bool,
1227 skip_encode: bool,
1229 skip_serializing_if: Option<syn::Path>,
1232 key: bool,
1236 flatten: bool,
1237}
1238
1239impl FieldCfg {
1240 fn parse(field: &syn::Field) -> syn::Result<Self> {
1241 let mut cfg = FieldCfg {
1242 rename: None,
1243 serialize_rename: None,
1244 default: None,
1245 with: None,
1246 skip_decode: false,
1247 skip_encode: false,
1248 skip_serializing_if: None,
1249 key: false,
1250 flatten: false,
1251 };
1252
1253 for attr in &field.attrs {
1254 if attr.path().is_ident("serde") {
1255 attr.parse_nested_meta(|meta| Self::parse_meta(&mut cfg, &meta, false))?;
1256 } else if attr.path().is_ident("record") {
1257 attr.parse_nested_meta(|meta| Self::parse_meta(&mut cfg, &meta, true))?;
1258 }
1259 }
1260 Ok(cfg)
1261 }
1262
1263 fn parse_meta(
1271 cfg: &mut FieldCfg,
1272 meta: &syn::meta::ParseNestedMeta<'_>,
1273 record_ns: bool,
1274 ) -> syn::Result<()> {
1275 if meta.path.is_ident("rename") {
1276 parse_rename(meta, &mut cfg.rename, &mut cfg.serialize_rename)
1277 } else if meta.path.is_ident("default") {
1278 parse_default(meta, &mut cfg.default)
1279 } else if meta.path.is_ident("flatten") {
1280 cfg.flatten = true;
1281 Ok(())
1282 } else if meta.path.is_ident("skip") {
1283 cfg.skip_decode = true;
1286 cfg.skip_encode = true;
1287 Ok(())
1288 } else if meta.path.is_ident("skip_serializing") {
1289 cfg.skip_encode = true;
1290 Ok(())
1291 } else if meta.path.is_ident("skip_deserializing") {
1292 cfg.skip_decode = true;
1293 Ok(())
1294 } else if meta.path.is_ident("skip_serializing_if") {
1295 let value = meta.value()?;
1296 let s: syn::LitStr = value.parse()?;
1297 cfg.skip_serializing_if = Some(s.parse()?);
1298 Ok(())
1299 } else if record_ns
1300 && (meta.path.is_ident("with") || meta.path.is_ident("deserialize_with"))
1301 {
1302 let value = meta.value()?;
1303 let s: syn::LitStr = value.parse()?;
1304 cfg.with = Some(s.parse()?);
1305 Ok(())
1306 } else if record_ns && meta.path.is_ident("key") {
1307 cfg.key = true;
1310 Ok(())
1311 } else if record_ns && meta.path.is_ident("crate_path") {
1312 Err(meta.error("`crate_path` is a container-level attribute"))
1313 } else if record_ns {
1314 Err(meta.error("unknown `record` attribute"))
1315 } else {
1316 ignore_meta(meta)
1319 }
1320 }
1321}
1322
1323fn parse_rename(
1327 meta: &syn::meta::ParseNestedMeta<'_>,
1328 rename: &mut Option<String>,
1329 serialize_rename: &mut Option<String>,
1330) -> syn::Result<()> {
1331 if meta.input.peek(syn::Token![=]) {
1332 let value = meta.value()?;
1333 let s: syn::LitStr = value.parse()?;
1334 let name = s.value();
1335 *rename = Some(name.clone());
1336 *serialize_rename = Some(name);
1337 } else {
1338 meta.parse_nested_meta(|inner| {
1339 if inner.path.is_ident("deserialize") {
1340 let value = inner.value()?;
1341 let s: syn::LitStr = value.parse()?;
1342 *rename = Some(s.value());
1343 } else if inner.path.is_ident("serialize") {
1344 let value = inner.value()?;
1345 let s: syn::LitStr = value.parse()?;
1346 *serialize_rename = Some(s.value());
1347 }
1348 ignore_meta(&inner)
1349 })?;
1350 }
1351 Ok(())
1352}
1353
1354fn parse_default(
1356 meta: &syn::meta::ParseNestedMeta<'_>,
1357 default: &mut Option<Option<syn::Path>>,
1358) -> syn::Result<()> {
1359 if meta.input.peek(syn::Token![=]) {
1360 let value = meta.value()?;
1361 let s: syn::LitStr = value.parse()?;
1362 *default = Some(Some(s.parse()?));
1363 } else {
1364 *default = Some(None);
1365 }
1366 Ok(())
1367}
1368
1369fn ignore_meta(meta: &syn::meta::ParseNestedMeta<'_>) -> syn::Result<()> {
1378 if meta.input.peek(syn::Token![=]) {
1379 let _: syn::Expr = meta.value()?.parse()?;
1380 } else if meta.input.peek(syn::token::Paren) {
1381 let content;
1382 syn::parenthesized!(content in meta.input);
1383 let _: syn::punctuated::Punctuated<syn::Meta, syn::Token![,]> =
1384 content.parse_terminated(syn::parse::Parse::parse, syn::Token![,])?;
1385 }
1386 Ok(())
1387}
1388
1389fn option_inner(ty: &Type) -> Option<Type> {
1391 let Type::Path(tp) = ty else { return None };
1392 let seg = tp.path.segments.last()?;
1393 if seg.ident != "Option" {
1394 return None;
1395 }
1396 let PathArguments::AngleBracketed(args) = &seg.arguments else {
1397 return None;
1398 };
1399 match args.args.last() {
1400 Some(GenericArgument::Type(inner)) => Some(inner.clone()),
1401 _ => None,
1402 }
1403}
1404
1405fn vec_u8(ty: &Type) -> bool {
1408 let Type::Path(tp) = ty else { return false };
1409 let Some(seg) = tp.path.segments.last() else {
1410 return false;
1411 };
1412 if seg.ident != "Vec" {
1413 return false;
1414 }
1415 let PathArguments::AngleBracketed(args) = &seg.arguments else {
1416 return false;
1417 };
1418 matches!(
1419 args.args.last(),
1420 Some(GenericArgument::Type(Type::Path(t))) if t.path.is_ident("u8")
1421 )
1422}
1423
1424fn type_has_lifetime(ty: &Type) -> bool {
1429 match ty {
1430 Type::Path(tp) => tp.path.segments.iter().any(|seg| {
1431 let PathArguments::AngleBracketed(args) = &seg.arguments else {
1432 return false;
1433 };
1434 args.args.iter().any(|arg| match arg {
1435 GenericArgument::Lifetime(_) => true,
1436 GenericArgument::Type(inner) => type_has_lifetime(inner),
1437 _ => false,
1438 })
1439 }),
1440 Type::Reference(r) => r.lifetime.is_some() || type_has_lifetime(&r.elem),
1441 Type::Tuple(tuple) => tuple.elems.iter().any(type_has_lifetime),
1442 Type::Paren(paren) => type_has_lifetime(&paren.elem),
1443 Type::Group(group) => type_has_lifetime(&group.elem),
1444 _ => false,
1445 }
1446}
1447
1448fn synth_field_let(
1453 fident: &Ident,
1454 ty: &Type,
1455 wire: &str,
1456 default: &Option<Option<syn::Path>>,
1457 syn: &TokenStream2,
1458 crate_path: &syn::Path,
1459) -> syn::Result<TokenStream2> {
1460 let owned_guard = |target: &Type| {
1461 if type_has_lifetime(target) {
1462 Err(syn::Error::new(
1463 fident.span(),
1464 "RecordDecode: `@rid`/`@type` synthesis supports owned targets \
1465 only (a borrowed target can't outlive the fallback value)",
1466 ))
1467 } else {
1468 Ok(())
1469 }
1470 };
1471
1472 if let Some(inner) = option_inner(ty) {
1474 owned_guard(&inner)?;
1475 return Ok(quote! {
1476 let #fident: #ty = match __arcade_props.get(#wire) {
1477 ::core::option::Option::Some(__arcade_v) => {
1478 <::core::option::Option<#inner> as #crate_path::record::FromGrpcValue>::from_grpc_value(
1479 __arcade_v,
1480 )
1481 .map_err(|e| e.with_field(#wire))?
1482 }
1483 ::core::option::Option::None => match #syn {
1484 ::core::option::Option::Some(__arcade_s) => {
1485 let __arcade_syn_gv = #crate_path::GrpcValue {
1486 kind: ::core::option::Option::Some(
1487 #crate_path::Kind::StringValue(__arcade_s.clone()),
1488 ),
1489 logical_type: ::std::string::String::new(),
1490 };
1491 ::core::option::Option::Some(
1492 <#inner as #crate_path::record::FromGrpcValue>::from_grpc_value(
1493 &__arcade_syn_gv,
1494 )
1495 .map_err(|e| e.with_field(#wire))?,
1496 )
1497 }
1498 ::core::option::Option::None => ::core::option::Option::None,
1499 },
1500 };
1501 });
1502 }
1503
1504 owned_guard(ty)?;
1505
1506 let synth_occurrence = quote! {
1507 let __arcade_syn_gv = #crate_path::GrpcValue {
1508 kind: ::core::option::Option::Some(#crate_path::Kind::StringValue(
1509 __arcade_s.clone(),
1510 )),
1511 logical_type: ::std::string::String::new(),
1512 };
1513 <#ty as #crate_path::record::FromGrpcValue>::from_grpc_value(&__arcade_syn_gv)
1514 .map_err(|e| e.with_field(#wire))?
1515 };
1516 let absent = match default {
1517 None => quote! {
1518 ::std::result::Result::Err(#crate_path::record::RecordDecodeError::missing_field(
1519 #wire,
1520 ))?
1521 },
1522 Some(_) => default_fallback(default),
1523 };
1524
1525 Ok(quote! {
1526 let #fident: #ty = match __arcade_props.get(#wire) {
1527 ::core::option::Option::Some(__arcade_v) => {
1528 <#ty as #crate_path::record::FromGrpcValue>::from_grpc_value(__arcade_v)
1529 .map_err(|e| e.with_field(#wire))?
1530 }
1531 ::core::option::Option::None => match #syn {
1532 ::core::option::Option::Some(__arcade_s) => { #synth_occurrence }
1535 ::core::option::Option::None => #absent,
1536 },
1537 };
1538 })
1539}
1540
1541fn expand_encode_derive(input: &DeriveInput) -> syn::Result<TokenStream2> {
1546 let name = &input.ident;
1547 check_alt_hasher_fields(input)?;
1548 let lifetimes: Vec<&syn::LifetimeParam> = input
1552 .generics
1553 .params
1554 .iter()
1555 .filter_map(|p| match p {
1556 syn::GenericParam::Lifetime(lt) => Some(lt),
1557 _ => None,
1558 })
1559 .collect();
1560 if lifetimes.len() > 1 {
1561 return Err(syn::Error::new(
1562 input.generics.span(),
1563 "RecordEncode supports at most one lifetime parameter",
1564 ));
1565 }
1566 if let Some(p) = input
1567 .generics
1568 .params
1569 .iter()
1570 .find(|p| !matches!(p, syn::GenericParam::Lifetime(_)))
1571 {
1572 return Err(syn::Error::new(
1573 p.span(),
1574 "RecordEncode does not support type/const generic parameters",
1575 ));
1576 }
1577 let (impl_clause, self_ty) = match lifetimes.first() {
1578 Some(lt) => {
1579 let life = <.lifetime;
1580 (quote! { <#life> }, quote! { #name<#life> })
1581 }
1582 None => (quote! {}, quote! { #name }),
1583 };
1584
1585 let container = ContainerCfg::parse(input)?;
1586
1587 match &input.data {
1588 Data::Struct(data) => expand_encode_struct(data, &container, &impl_clause, &self_ty),
1589 Data::Enum(data) => expand_encode_enum(data, &container, &impl_clause, &self_ty),
1590 Data::Union(data) => Err(syn::Error::new(
1591 data.union_token.span(),
1592 "RecordEncode does not support unions",
1593 )),
1594 }
1595}
1596
1597fn expand_encode_enum(
1604 data: &DataEnum,
1605 container: &ContainerCfg,
1606 impl_clause: &TokenStream2,
1607 self_ty: &TokenStream2,
1608) -> syn::Result<TokenStream2> {
1609 let crate_path = &container.crate_path;
1610 let tagged = container.tag.as_deref();
1611
1612 let mut value_arms = Vec::new();
1613 let mut props_arms = Vec::new();
1614 for variant in &data.variants {
1615 let vident = &variant.ident;
1616 let wire = variant_wire_name(variant, container)?;
1617 match &variant.fields {
1618 Fields::Unit => {
1619 value_arms.push(quote! {
1620 Self::#vident => #crate_path::__private::str_v(#wire)
1621 });
1622 props_arms.push(quote! {
1623 Self::#vident => ::std::vec::Vec::new()
1624 });
1625 }
1626 Fields::Named(fields) => {
1627 let Some(tag) = tagged else {
1628 return Err(syn::Error::new(
1629 variant.span(),
1630 "RecordEncode: data-carrying variants require `#[serde(tag = \"...\")]` \
1631 (internally-tagged); plain unit-variant enums need no tag",
1632 ));
1633 };
1634 let bindings = fields
1635 .named
1636 .iter()
1637 .map(|f| f.ident.as_ref().expect("named field ident"))
1638 .collect::<Vec<_>>();
1639 let pairs = variant_field_pairs(fields, container)?;
1640 let pairs_len = fields.named.len() + 1;
1642 value_arms.push(quote! {
1644 Self::#vident { #(#bindings),* } => {
1645 let mut __arcade_pairs: ::std::vec::Vec<(
1646 &str,
1647 #crate_path::GrpcValue,
1648 )> = ::std::vec::Vec::with_capacity(#pairs_len);
1649 __arcade_pairs.push((#tag, #crate_path::__private::str_v(#wire)));
1650 #pairs
1651 #crate_path::GrpcValue {
1652 kind: ::core::option::Option::Some(#crate_path::Kind::MapValue(
1653 #crate_path::GrpcMap {
1654 entries: __arcade_pairs
1655 .into_iter()
1656 .map(|(k, v)| (k.to_string(), v))
1657 .collect(),
1658 },
1659 )),
1660 logical_type: ::std::string::String::new(),
1661 }
1662 }
1663 });
1664 props_arms.push(quote! {
1666 Self::#vident { #(#bindings),* } => {
1667 let mut __arcade_pairs: ::std::vec::Vec<(
1668 &str,
1669 #crate_path::GrpcValue,
1670 )> = ::std::vec::Vec::with_capacity(#pairs_len);
1671 __arcade_pairs.push((#tag, #crate_path::__private::str_v(#wire)));
1672 #pairs
1673 __arcade_pairs
1674 }
1675 });
1676 }
1677 Fields::Unnamed(_) => {
1678 return Err(syn::Error::new(
1679 variant.span(),
1680 "RecordEncode on enums supports struct variants only",
1681 ));
1682 }
1683 }
1684 }
1685
1686 Ok(quote! {
1687 #[automatically_derived]
1688 impl #impl_clause #crate_path::record::ToGrpcRecord for #self_ty {
1689 fn props(&self) -> ::std::vec::Vec<(&str, #crate_path::GrpcValue)> {
1690 match self {
1691 #(#props_arms,)*
1692 }
1693 }
1694
1695 fn to_grpc_value(&self) -> #crate_path::GrpcValue {
1696 match self {
1697 #(#value_arms,)*
1698 }
1699 }
1700 }
1701 })
1702}
1703
1704fn variant_field_pairs(
1709 fields: &syn::FieldsNamed,
1710 container: &ContainerCfg,
1711) -> syn::Result<TokenStream2> {
1712 let crate_path = &container.crate_path;
1713 let mut pushes = Vec::new();
1714 for field in &fields.named {
1715 let fident = field.ident.as_ref().expect("named field ident").clone();
1716 let cfg = FieldCfg::parse(field)?;
1717 let ty = &field.ty;
1718
1719 if cfg.flatten {
1720 return Err(syn::Error::new(
1721 field.span(),
1722 "RecordEncode: `flatten` is not supported inside enum variants",
1723 ));
1724 }
1725 if cfg.key {
1726 return Err(syn::Error::new(
1727 field.span(),
1728 "RecordEncode: `key` is not supported inside enum variants",
1729 ));
1730 }
1731
1732 let wire = match (
1733 &cfg.serialize_rename,
1734 &cfg.rename,
1735 container.rename_all_fields,
1736 ) {
1737 (Some(r), _, _) => r.clone(),
1738 (None, Some(r), _) => r.clone(),
1739 (None, None, Some(rule)) => rule.apply_to_field(&fident.to_string()),
1740 (None, None, None) => fident.to_string(),
1741 };
1742
1743 if cfg.skip_encode {
1744 continue;
1745 }
1746
1747 if let Some(with) = &cfg.with {
1748 if option_inner(ty).is_some() {
1749 pushes.push(quote! {
1750 if let ::core::option::Option::Some(__arcade_f) = #fident {
1751 __arcade_pairs.push((#wire, #with(__arcade_f)));
1752 }
1753 });
1754 } else {
1755 pushes.push(quote! {
1756 __arcade_pairs.push((#wire, #with(#fident)));
1757 });
1758 }
1759 continue;
1760 }
1761
1762 if let Some(inner) = option_inner(ty) {
1763 let val = encode_field_value(&inner, "e! { __arcade_f }, crate_path)?;
1764 pushes.push(quote! {
1765 if let ::core::option::Option::Some(__arcade_f) = #fident {
1766 __arcade_pairs.push((#wire, #val));
1767 }
1768 });
1769 continue;
1770 }
1771
1772 let val = encode_field_value(ty, "e! { #fident }, crate_path)?;
1773 let push = quote! { __arcade_pairs.push((#wire, #val)); };
1774 if let Some(pred) = &cfg.skip_serializing_if {
1775 pushes.push(quote! {
1776 if !#pred(#fident) {
1777 #push
1778 }
1779 });
1780 } else {
1781 pushes.push(push);
1782 }
1783 }
1784 Ok(quote! { #(#pushes)* })
1785}
1786
1787fn expand_encode_struct(
1790 data: &syn::DataStruct,
1791 container: &ContainerCfg,
1792 impl_clause: &TokenStream2,
1793 self_ty: &TokenStream2,
1794) -> syn::Result<TokenStream2> {
1795 let Fields::Named(fields) = &data.fields else {
1796 return Err(syn::Error::new(
1797 data.fields.span(),
1798 "RecordEncode supports named-field structs only; newtype wrappers \
1799 plug in through `#[record(with = \"...\")]` on the field instead",
1800 ));
1801 };
1802
1803 let crate_path = &container.crate_path;
1804 let mut pushes = Vec::new();
1805 let mut move_pushes = Vec::new();
1806 let mut diff_conds = Vec::new();
1807 let mut key_wires: Vec<String> = Vec::new();
1808 for field in &fields.named {
1809 let fident = field.ident.as_ref().expect("named field ident").clone();
1810 let cfg = FieldCfg::parse(field)?;
1811 let ty = &field.ty;
1812
1813 let wire = match (&cfg.serialize_rename, &cfg.rename, container.rename_all) {
1814 (Some(r), _, _) => r.clone(),
1815 (None, Some(r), _) => r.clone(),
1816 (None, None, Some(rule)) => rule.apply_to_field(&fident.to_string()),
1817 (None, None, None) => fident.to_string(),
1818 };
1819
1820 if cfg.key {
1821 if cfg.skip_encode {
1822 return Err(syn::Error::new(
1823 fident.span(),
1824 "RecordEncode: `key` cannot be combined with `skip`",
1825 ));
1826 }
1827 key_wires.push(wire.clone());
1828 }
1829
1830 pushes.push(encode_field_push(&fident, ty, &wire, &cfg, crate_path)?);
1831 move_pushes.push(encode_field_push_move(
1832 &fident, ty, &wire, &cfg, crate_path,
1833 )?);
1834 diff_conds.push(diff_cond(&fident, ty, &wire, &cfg, crate_path));
1835 }
1836 let props_capacity = fields.named.len();
1839
1840 Ok(quote! {
1841 #[automatically_derived]
1842 #[allow(clippy::cast_possible_wrap, clippy::cast_possible_truncation)]
1845 impl #impl_clause #crate_path::record::ToGrpcRecord for #self_ty {
1846 const KEY_COLUMNS: &'static [&'static str] = &[#(#key_wires),*];
1849
1850 fn props(&self) -> ::std::vec::Vec<(&str, #crate_path::GrpcValue)> {
1851 let mut __out: ::std::vec::Vec<(&str, #crate_path::GrpcValue)> =
1852 ::std::vec::Vec::with_capacity(#props_capacity);
1853 #(#pushes)*
1854 __out
1855 }
1856
1857 fn changed_wires(&self, other: &Self) -> ::std::vec::Vec<::std::string::String> {
1860 let mut __arcade_changed: ::std::vec::Vec<::std::string::String> =
1861 ::std::vec::Vec::new();
1862 #(#diff_conds)*
1863 __arcade_changed
1864 }
1865
1866 fn into_grpc_record(self, class: &str) -> #crate_path::GrpcRecord {
1871 let mut __out: ::std::vec::Vec<(&str, #crate_path::GrpcValue)> =
1872 ::std::vec::Vec::with_capacity(#props_capacity);
1873 #(#move_pushes)*
1874 #crate_path::rec(class, __out)
1875 }
1876 }
1877 })
1878}
1879
1880fn diff_cond(
1885 fident: &Ident,
1886 ty: &Type,
1887 wire: &str,
1888 cfg: &FieldCfg,
1889 crate_path: &syn::Path,
1890) -> TokenStream2 {
1891 let wire = syn::LitStr::new(wire, proc_macro2::Span::call_site());
1892 if cfg.skip_encode {
1893 return quote! {};
1894 }
1895 let is_option = option_inner(ty).is_some();
1896 let differs = if cfg.flatten {
1897 quote! {
1900 <#ty as #crate_path::record::ToGrpcRecord>::to_grpc_value(&self.#fident)
1901 != <#ty as #crate_path::record::ToGrpcRecord>::to_grpc_value(&other.#fident)
1902 }
1903 } else if let Some(w) = &cfg.with {
1904 if is_option {
1905 quote! { other.#fident.is_some() && #w(&self.#fident) != #w(&other.#fident) }
1906 } else {
1907 quote! { #w(&self.#fident) != #w(&other.#fident) }
1908 }
1909 } else if is_option {
1910 quote! { other.#fident.is_some() && self.#fident != other.#fident }
1911 } else {
1912 quote! { self.#fident != other.#fident }
1913 };
1914 let guarded = match &cfg.skip_serializing_if {
1915 Some(pred) => quote! { !#pred(&other.#fident) && (#differs) },
1916 None => differs,
1917 };
1918 quote! {
1919 if #guarded {
1920 __arcade_changed.push(#wire.to_string());
1921 }
1922 }
1923}
1924
1925fn encode_field_push_move(
1929 fident: &Ident,
1930 ty: &Type,
1931 wire: &str,
1932 cfg: &FieldCfg,
1933 crate_path: &syn::Path,
1934) -> syn::Result<TokenStream2> {
1935 let wire = syn::LitStr::new(wire, proc_macro2::Span::call_site());
1936 if cfg.skip_encode {
1937 return Ok(quote! {});
1938 }
1939
1940 if cfg.flatten || cfg.with.is_some() {
1942 let borrow = encode_field_push(fident, ty, wire.value().as_str(), cfg, crate_path)?;
1943 return Ok(borrow);
1944 }
1945
1946 let val_plain = encode_field_value_move(ty, "e! { self.#fident }, crate_path);
1947 let push_plain = quote! { __out.push((#wire, #val_plain)); };
1948 if let Some(inner) = option_inner(ty) {
1949 let val_opt = encode_field_value_move(&inner, "e! { __arcade_f }, crate_path);
1950 return Ok(quote! {
1951 if let ::core::option::Option::Some(__arcade_f) = self.#fident {
1952 __out.push((#wire, #val_opt));
1953 }
1954 });
1955 }
1956 if let Some(pred) = &cfg.skip_serializing_if {
1957 return Ok(quote! {
1959 if !#pred(&self.#fident) {
1960 #push_plain
1961 }
1962 });
1963 }
1964 Ok(push_plain)
1965}
1966
1967fn encode_field_value_move(ty: &Type, expr: &TokenStream2, crate_path: &syn::Path) -> TokenStream2 {
1971 if let Type::Reference(r) = ty {
1972 return encode_field_value(&r.elem, expr, crate_path)
1973 .unwrap_or_else(|e| e.to_compile_error());
1974 }
1975 let Type::Path(tp) = ty else {
1976 return encode_field_value(ty, expr, crate_path).unwrap_or_else(|e| e.to_compile_error());
1977 };
1978 let Some(seg) = tp.path.segments.last() else {
1979 return encode_field_value(ty, expr, crate_path).unwrap_or_else(|e| e.to_compile_error());
1980 };
1981 match seg.ident.to_string().as_str() {
1982 "String" => quote! { #crate_path::__private::str_v(#expr) },
1983 "char" => quote! { #crate_path::__private::str_v((#expr).to_string()) },
1984 "Cow" => {
1985 if let Ok(inner) = container_inner(ty, seg, "Cow") {
1986 match inner {
1987 Type::Path(p) if p.path.is_ident("str") => {
1988 quote! { #crate_path::__private::str_v((#expr).into_owned()) }
1989 }
1990 Type::Slice(sl) if matches!(&*sl.elem, Type::Path(p) if p.path.is_ident("u8")) =>
1991 {
1992 quote! { #crate_path::__private::bytes_v((#expr).into_owned()) }
1993 }
1994 _ => encode_field_value(ty, "e! { &#expr }, crate_path)
1995 .unwrap_or_else(|e| e.to_compile_error()),
1996 }
1997 } else {
1998 encode_field_value(ty, "e! { &#expr }, crate_path)
1999 .unwrap_or_else(|e| e.to_compile_error())
2000 }
2001 }
2002 "bool" => quote! { #crate_path::__private::bool_v(#expr) },
2003 "i32" => quote! { #crate_path::__private::i32_v(#expr) },
2004 "i8" | "i16" | "u8" | "u16" => quote! { #crate_path::__private::i32_v(i32::from(#expr)) },
2005 "i64" | "u32" => quote! { #crate_path::__private::i64_v(i64::from(#expr)) },
2006 "u64" => quote! { #crate_path::__private::i64_v(#expr as i64) },
2007 "f32" => quote! { #crate_path::__private::f32_v(#expr) },
2008 "f64" => quote! { #crate_path::__private::f64_v(#expr) },
2009 "DateTime" => quote! {
2010 #crate_path::GrpcValue {
2011 kind: ::core::option::Option::Some(#crate_path::Kind::TimestampValue(
2012 #crate_path::Timestamp {
2013 seconds: (#expr).timestamp(),
2014 nanos: (#expr).timestamp_subsec_nanos() as i32,
2015 },
2016 )),
2017 logical_type: ::std::string::String::new(),
2018 }
2019 },
2020 "Value" => quote! { #crate_path::json_to_grpc_value(&#expr) },
2021 "Link" => quote! {
2022 #crate_path::GrpcValue {
2023 kind: ::core::option::Option::Some(#crate_path::Kind::LinkValue(
2024 #crate_path::GrpcLink {
2025 rid: (#expr).to_string(),
2026 r#type: ::std::string::String::new(),
2027 },
2028 )),
2029 logical_type: ::std::string::String::new(),
2030 }
2031 },
2032 _ => {
2033 if seg.ident != "Vec" {
2038 encode_field_value(ty, "e! { &#expr }, crate_path)
2039 .unwrap_or_else(|e| e.to_compile_error())
2040 } else if vec_u8(ty) {
2041 quote! { #crate_path::__private::bytes_v(#expr) }
2042 } else if matches!(container_inner(ty, seg, "Vec"), Ok(inner)
2043 if matches!(inner, Type::Path(p) if p.path.is_ident("String")))
2044 {
2045 quote! {
2046 #crate_path::GrpcValue {
2047 kind: ::core::option::Option::Some(#crate_path::Kind::ListValue(
2048 #crate_path::GrpcList {
2049 values: (#expr)
2050 .into_iter()
2051 .map(|__arcade_e| #crate_path::__private::str_v(__arcade_e))
2052 .collect(),
2053 },
2054 )),
2055 logical_type: ::std::string::String::new(),
2056 }
2057 }
2058 } else {
2059 encode_field_value(ty, "e! { &#expr }, crate_path)
2060 .unwrap_or_else(|e| e.to_compile_error())
2061 }
2062 }
2063 }
2064}
2065
2066fn encode_field_push(
2069 fident: &Ident,
2070 ty: &Type,
2071 wire: &str,
2072 cfg: &FieldCfg,
2073 crate_path: &syn::Path,
2074) -> syn::Result<TokenStream2> {
2075 let wire = syn::LitStr::new(wire, proc_macro2::Span::call_site());
2076 if cfg.skip_encode {
2077 return Ok(quote! {});
2078 }
2079
2080 if cfg.flatten {
2082 if cfg.with.is_some() {
2085 return Err(syn::Error::new(
2086 fident.span(),
2087 "RecordEncode: `with` cannot be combined with a flattened field",
2088 ));
2089 }
2090 return if let Some(inner) = option_inner(ty) {
2091 Ok(quote! {
2092 if let ::core::option::Option::Some(__arcade_f) = &self.#fident {
2093 __out.extend(<#inner as #crate_path::record::ToGrpcRecord>::props(
2094 __arcade_f,
2095 ));
2096 }
2097 })
2098 } else {
2099 Ok(quote! {
2100 __out.extend(<#ty as #crate_path::record::ToGrpcRecord>::props(
2101 &self.#fident,
2102 ));
2103 })
2104 };
2105 }
2106
2107 if let Some(inner) = option_inner(ty) {
2110 let val = match &cfg.with {
2111 Some(w) => quote! { #w(__arcade_f) },
2112 None => encode_field_value(&inner, "e! { __arcade_f }, crate_path)?,
2113 };
2114 return Ok(quote! {
2115 if let ::core::option::Option::Some(__arcade_f) = &self.#fident {
2116 __out.push((#wire, #val));
2117 }
2118 });
2119 }
2120
2121 let val = match &cfg.with {
2122 Some(w) => quote! { #w(&self.#fident) },
2123 None => encode_field_value(ty, "e! { &self.#fident }, crate_path)?,
2124 };
2125 let push = quote! { __out.push((#wire, #val)); };
2126 if let Some(pred) = &cfg.skip_serializing_if {
2127 return Ok(quote! {
2128 if !#pred(&self.#fident) {
2129 #push
2130 }
2131 });
2132 }
2133 Ok(push)
2134}
2135
2136fn container_inner<'a>(
2143 ty: &'a Type,
2144 seg: &'a syn::PathSegment,
2145 what: &str,
2146) -> syn::Result<&'a Type> {
2147 let PathArguments::AngleBracketed(args) = &seg.arguments else {
2148 return Err(syn::Error::new(
2149 ty.span(),
2150 format!("`{what}` needs a type argument"),
2151 ));
2152 };
2153 let Some(GenericArgument::Type(inner)) = args.args.last() else {
2154 return Err(syn::Error::new(
2155 ty.span(),
2156 format!("`{what}` needs a type argument"),
2157 ));
2158 };
2159 Ok(inner)
2160}
2161
2162fn map_value_type<'a>(ty: &'a Type, seg: &'a syn::PathSegment) -> syn::Result<&'a Type> {
2166 let PathArguments::AngleBracketed(args) = &seg.arguments else {
2167 return Err(syn::Error::new(ty.span(), "`map` needs type arguments"));
2168 };
2169 let mut types = args.args.iter().filter_map(|a| match a {
2170 GenericArgument::Type(t) => Some(t),
2171 _ => None,
2172 });
2173 let key = types
2174 .next()
2175 .ok_or_else(|| syn::Error::new(ty.span(), "`map` needs a key type"))?;
2176 if !matches!(key, Type::Path(p) if p.path.is_ident("String")) {
2177 return Err(syn::Error::new(
2178 key.span(),
2179 "RecordEncode: map keys must be `String` (the wire map is string-keyed)",
2180 ));
2181 }
2182 let value = types
2183 .next()
2184 .ok_or_else(|| syn::Error::new(ty.span(), "`map` needs a value type"))?;
2185 if types.next().is_some() {
2186 return Err(syn::Error::new(
2187 ty.span(),
2188 "`map` expects exactly two type arguments",
2189 ));
2190 }
2191 Ok(value)
2192}
2193
2194enum DbType {
2204 Str,
2206 Char,
2208 Bool,
2209 Int32(Int32W),
2211 Int64(Int64W),
2213 F32,
2214 F64,
2215 Bytes,
2218 Json,
2220 Link,
2221 DateTime,
2222 NaiveDate,
2223 Decimal,
2227 List(Box<Option<DbType>>),
2233 Map(Box<Option<DbType>>),
2236}
2237
2238enum Int32W {
2240 Direct,
2242 Widened,
2244}
2245
2246enum Int64W {
2248 Direct,
2250 FromU32,
2252 NarrowedU64,
2254}
2255
2256enum Classification {
2260 Known(DbType),
2261 Foreign,
2262}
2263
2264fn classify(ty: &Type) -> syn::Result<Classification> {
2268 if let Type::Reference(r) = ty {
2269 return classify(&r.elem);
2270 }
2271 if let Type::Slice(s) = ty {
2272 return Ok(Classification::Known(DbType::List(Box::new(
2274 elem_classification(&s.elem)?,
2275 ))));
2276 }
2277 if let Some(ref inner) = option_inner(ty) {
2278 return classify(inner);
2279 }
2280 let Type::Path(tp) = ty else {
2281 return Ok(Classification::Foreign);
2282 };
2283 let seg = tp.path.segments.last().expect("path always has segments");
2284
2285 if seg.ident == "Cow" {
2286 let inner = container_inner(ty, seg, "Cow")?;
2287 return match inner {
2288 Type::Path(p) if p.path.is_ident("str") => Ok(Classification::Known(DbType::Str)),
2289 Type::Slice(s) if matches!(&*s.elem, Type::Path(p) if p.path.is_ident("u8")) => {
2290 Ok(Classification::Known(DbType::Bytes))
2291 }
2292 _ => Err(syn::Error::new(
2293 ty.span(),
2294 "RecordEncode: `Cow` fields must be `Cow<str>` or `Cow<[u8]>`",
2295 )),
2296 };
2297 }
2298
2299 let db = match seg.ident.to_string().as_str() {
2300 "str" | "String" => DbType::Str,
2301 "char" => DbType::Char,
2302 "bool" => DbType::Bool,
2303 "i8" => DbType::Int32(Int32W::Widened),
2304 "i16" => DbType::Int32(Int32W::Widened),
2305 "i32" => DbType::Int32(Int32W::Direct),
2306 "u8" => DbType::Int32(Int32W::Widened),
2307 "u16" => DbType::Int32(Int32W::Widened),
2308 "i64" => DbType::Int64(Int64W::Direct),
2309 "u32" => DbType::Int64(Int64W::FromU32),
2310 "u64" => DbType::Int64(Int64W::NarrowedU64),
2313 "f32" => DbType::F32,
2314 "f64" => DbType::F64,
2315 "Value" => DbType::Json,
2316 "Link" => DbType::Link,
2317 "DateTime" => DbType::DateTime,
2318 "NaiveDate" => DbType::NaiveDate,
2319 "Decimal" => DbType::Decimal,
2320 "Vec" | "HashSet" | "BTreeSet" | "AHashSet" | "FxHashSet" => {
2321 if seg.ident == "AHashSet" && !cfg!(feature = "ahash") {
2322 return Err(syn::Error::new(
2323 ty.span(),
2324 "RecordEncode/RecordDecode: `AHashSet` fields need the `ahash` feature",
2325 ));
2326 }
2327 if seg.ident == "FxHashSet" && !cfg!(feature = "fxhash") {
2328 return Err(syn::Error::new(
2329 ty.span(),
2330 "RecordEncode/RecordDecode: `FxHashSet` fields need the `fxhash` feature",
2331 ));
2332 }
2333 if vec_u8(ty) {
2334 DbType::Bytes
2335 } else {
2336 let elem_ty = container_inner(ty, seg, "list container")?;
2337 DbType::List(Box::new(elem_classification(elem_ty)?))
2338 }
2339 }
2340 "HashMap" | "BTreeMap" | "AHashMap" | "FxHashMap" => {
2341 if seg.ident == "AHashMap" && !cfg!(feature = "ahash") {
2346 return Err(syn::Error::new(
2347 ty.span(),
2348 "RecordEncode/RecordDecode: `AHashMap` fields need the `ahash` feature",
2349 ));
2350 }
2351 if seg.ident == "FxHashMap" && !cfg!(feature = "fxhash") {
2352 return Err(syn::Error::new(
2353 ty.span(),
2354 "RecordEncode/RecordDecode: `FxHashMap` fields need the `fxhash` feature",
2355 ));
2356 }
2357 let value_ty = map_value_type(ty, seg)?;
2358 DbType::Map(Box::new(elem_classification(value_ty)?))
2359 }
2360 _ => return Ok(Classification::Foreign),
2361 };
2362 Ok(Classification::Known(db))
2363}
2364
2365fn elem_classification(ty: &Type) -> syn::Result<Option<DbType>> {
2368 match classify(ty)? {
2369 Classification::Known(db) => Ok(Some(db)),
2370 Classification::Foreign => Ok(None),
2371 }
2372}
2373
2374fn render(db: &DbType) -> Option<String> {
2378 match db {
2379 DbType::Str | DbType::Char => Some("STRING".to_string()),
2380 DbType::Bool => Some("BOOLEAN".to_string()),
2381 DbType::Int32(_) => Some("INTEGER".to_string()),
2382 DbType::Int64(_) => Some("LONG".to_string()),
2383 DbType::F32 => Some("FLOAT".to_string()),
2384 DbType::F64 => Some("DOUBLE".to_string()),
2385 DbType::Bytes | DbType::Json => None,
2386 DbType::Link => Some("LINK".to_string()),
2387 DbType::DateTime => Some("DATETIME".to_string()),
2388 DbType::NaiveDate => Some("DATE".to_string()),
2389 DbType::Decimal => Some("DECIMAL".to_string()),
2392 DbType::List(inner) => render_inner(inner).map(|s| format!("LIST OF {s}")),
2395 DbType::Map(_) => Some("MAP".to_string()),
2396 }
2397}
2398
2399fn render_inner(inner: &Option<DbType>) -> Option<String> {
2400 inner.as_ref().and_then(render)
2401}
2402
2403fn value_from_db(db: &DbType, expr: &TokenStream2, crate_path: &syn::Path) -> TokenStream2 {
2408 match db {
2409 DbType::Str | DbType::Char => quote! { #crate_path::__private::str_v((#expr).to_string()) },
2410 DbType::Bool => quote! { #crate_path::__private::bool_v(*#expr) },
2411 DbType::Int32(Int32W::Direct) => quote! { #crate_path::__private::i32_v(*#expr) },
2412 DbType::Int32(Int32W::Widened) => {
2413 quote! { #crate_path::__private::i32_v(i32::from(*#expr)) }
2414 }
2415 DbType::Int64(Int64W::Direct) => quote! { #crate_path::__private::i64_v(*#expr) },
2416 DbType::Int64(Int64W::FromU32) => {
2417 quote! { #crate_path::__private::i64_v(i64::from(*#expr)) }
2418 }
2419 DbType::Int64(Int64W::NarrowedU64) => {
2420 quote! { #crate_path::__private::i64_v(*#expr as i64) }
2421 }
2422 DbType::F32 => quote! { #crate_path::__private::f32_v(*#expr) },
2423 DbType::F64 => quote! { #crate_path::__private::f64_v(*#expr) },
2424 DbType::Bytes => quote! { #crate_path::__private::bytes_v((#expr).clone()) },
2425 DbType::Json => quote! { #crate_path::json_to_grpc_value(#expr) },
2426 DbType::Link => quote! {
2427 #crate_path::GrpcValue {
2428 kind: ::core::option::Option::Some(#crate_path::Kind::LinkValue(
2429 #crate_path::GrpcLink {
2430 rid: (#expr).to_string(),
2431 r#type: ::std::string::String::new(),
2432 },
2433 )),
2434 logical_type: ::std::string::String::new(),
2435 }
2436 },
2437 DbType::DateTime => quote! {
2441 #crate_path::GrpcValue {
2442 kind: ::core::option::Option::Some(#crate_path::Kind::TimestampValue(
2443 #crate_path::Timestamp {
2444 seconds: (#expr).timestamp(),
2445 nanos: (#expr).timestamp_subsec_nanos() as i32,
2446 },
2447 )),
2448 logical_type: ::std::string::String::new(),
2449 }
2450 },
2451 DbType::NaiveDate => quote! { #crate_path::__private::date_v(*#expr) },
2452 DbType::Decimal => quote! { #crate_path::__private::decimal_v(*#expr) },
2453 DbType::List(inner) => {
2454 let inner: &Option<DbType> = inner;
2455 let elem = elem_tokens(inner.as_ref(), "e! { __arcade_e }, crate_path);
2456 quote! {
2457 #crate_path::GrpcValue {
2458 kind: ::core::option::Option::Some(#crate_path::Kind::ListValue(
2459 #crate_path::GrpcList {
2460 values: (#expr)
2461 .iter()
2462 .map(|__arcade_e| #elem)
2463 .collect(),
2464 },
2465 )),
2466 logical_type: ::std::string::String::new(),
2467 }
2468 }
2469 }
2470 DbType::Map(inner) => {
2471 let inner: &Option<DbType> = inner;
2472 let value = elem_tokens(inner.as_ref(), "e! { __arcade_v }, crate_path);
2473 quote! {
2474 #crate_path::GrpcValue {
2475 kind: ::core::option::Option::Some(#crate_path::Kind::MapValue(
2476 #crate_path::GrpcMap {
2477 entries: (#expr)
2478 .iter()
2479 .map(|(__arcade_k, __arcade_v)| (__arcade_k.clone(), #value))
2480 .collect(),
2481 },
2482 )),
2483 logical_type: ::std::string::String::new(),
2484 }
2485 }
2486 }
2487 }
2488}
2489
2490fn elem_tokens(inner: Option<&DbType>, var: &TokenStream2, crate_path: &syn::Path) -> TokenStream2 {
2494 match inner {
2495 Some(db) => value_from_db(db, var, crate_path),
2496 None => quote! {
2497 <_ as #crate_path::record::ToGrpcRecord>::to_grpc_value(#var)
2498 },
2499 }
2500}
2501
2502fn encode_field_value(
2505 ty: &Type,
2506 expr: &TokenStream2,
2507 crate_path: &syn::Path,
2508) -> syn::Result<TokenStream2> {
2509 match classify(ty)? {
2510 Classification::Known(db) => Ok(value_from_db(&db, expr, crate_path)),
2511 Classification::Foreign => Ok(quote! {
2512 <#ty as #crate_path::record::ToGrpcRecord>::to_grpc_value(#expr)
2513 }),
2514 }
2515}
2516
2517fn db_type_of(ty: &Type) -> Option<String> {
2526 match classify(ty) {
2527 Ok(Classification::Known(db)) => render(&db),
2528 _ => None,
2529 }
2530}
2531
2532#[derive(Clone, Copy)]
2542enum RenameRule {
2543 Lower,
2544 Upper,
2545 Pascal,
2546 Camel,
2547 Snake,
2548 ScreamingSnake,
2549 Kebab,
2550 ScreamingKebab,
2551}
2552
2553impl RenameRule {
2554 fn parse(s: &str) -> Option<Self> {
2557 match s {
2558 "lowercase" => Some(Self::Lower),
2559 "UPPERCASE" => Some(Self::Upper),
2560 "PascalCase" => Some(Self::Pascal),
2561 "camelCase" => Some(Self::Camel),
2562 "snake_case" => Some(Self::Snake),
2563 "SCREAMING_SNAKE_CASE" => Some(Self::ScreamingSnake),
2564 "kebab-case" => Some(Self::Kebab),
2565 "SCREAMING-KEBAB-CASE" => Some(Self::ScreamingKebab),
2566 _ => None,
2567 }
2568 }
2569
2570 fn apply_to_variant(self, variant: &str) -> String {
2573 match self {
2574 Self::Pascal => variant.to_owned(),
2575 Self::Lower => variant.to_ascii_lowercase(),
2576 Self::Upper => variant.to_ascii_uppercase(),
2577 Self::Camel => lower_first(variant),
2578 Self::Snake => {
2579 let mut snake = String::with_capacity(variant.len() + 4);
2580 for (i, ch) in variant.char_indices() {
2581 if i > 0 && ch.is_uppercase() {
2582 snake.push('_');
2583 }
2584 snake.push(ch.to_ascii_lowercase());
2585 }
2586 snake
2587 }
2588 Self::ScreamingSnake => Self::Snake.apply_to_variant(variant).to_ascii_uppercase(),
2589 Self::Kebab => Self::Snake.apply_to_variant(variant).replace('_', "-"),
2590 Self::ScreamingKebab => Self::ScreamingSnake
2591 .apply_to_variant(variant)
2592 .replace('_', "-"),
2593 }
2594 }
2595
2596 fn apply_to_field(self, field: &str) -> String {
2600 match self {
2601 Self::Lower | Self::Snake => field.to_owned(),
2602 Self::Upper => field.to_ascii_uppercase(),
2603 Self::Pascal => {
2604 let mut pascal = String::with_capacity(field.len());
2605 let mut capitalize = true;
2606 for ch in field.chars() {
2607 if ch == '_' {
2608 capitalize = true;
2609 } else if capitalize {
2610 pascal.push(ch.to_ascii_uppercase());
2611 capitalize = false;
2612 } else {
2613 pascal.push(ch);
2614 }
2615 }
2616 pascal
2617 }
2618 Self::Camel => lower_first(&Self::Pascal.apply_to_field(field)),
2619 Self::ScreamingSnake => field.to_ascii_uppercase(),
2620 Self::Kebab => field.replace('_', "-"),
2621 Self::ScreamingKebab => Self::ScreamingSnake.apply_to_field(field).replace('_', "-"),
2622 }
2623 }
2624}
2625
2626fn lower_first(s: &str) -> String {
2628 let mut chars = s.chars();
2629 chars
2630 .next()
2631 .map(|c| c.to_lowercase().collect::<String>())
2632 .unwrap_or_default()
2633 + chars.as_str()
2634}
2635
2636#[cfg(test)]
2637mod dbtype_tests {
2638 use super::*;
2639 use syn::parse_quote;
2640
2641 fn rendered(ty: Type) -> Option<String> {
2642 match classify(&ty).expect("type must classify") {
2643 Classification::Known(db) => render(&db),
2644 Classification::Foreign => None,
2645 }
2646 }
2647
2648 #[test]
2652 fn classification_matrix_is_complete() {
2653 let cases: Vec<(Type, Option<&str>)> = vec![
2654 (parse_quote!(String), Some("STRING")),
2655 (parse_quote!(char), Some("STRING")),
2656 (parse_quote!(bool), Some("BOOLEAN")),
2657 (parse_quote!(i8), Some("INTEGER")),
2658 (parse_quote!(u16), Some("INTEGER")),
2659 (parse_quote!(i32), Some("INTEGER")),
2660 (parse_quote!(i64), Some("LONG")),
2661 (parse_quote!(u32), Some("LONG")),
2662 (parse_quote!(f32), Some("FLOAT")),
2663 (parse_quote!(f64), Some("DOUBLE")),
2664 (
2665 parse_quote!(chrono::DateTime<chrono::Utc>),
2666 Some("DATETIME"),
2667 ),
2668 (parse_quote!(chrono::NaiveDate), Some("DATE")),
2669 (parse_quote!(rust_decimal::Decimal), Some("DECIMAL")),
2670 (parse_quote!(arcadedb_protocol::Link), Some("LINK")),
2671 (parse_quote!(Vec<i32>), Some("LIST OF INTEGER")),
2672 (
2673 parse_quote!(std::collections::HashSet<String>),
2674 Some("LIST OF STRING"),
2675 ),
2676 (
2677 parse_quote!(std::collections::BTreeSet<u8>),
2678 Some("LIST OF INTEGER"),
2679 ),
2680 (parse_quote!(Vec<Vec<f64>>), Some("LIST OF LIST OF DOUBLE")),
2681 (
2682 parse_quote!(std::collections::HashMap<String, i64>),
2683 Some("MAP"),
2684 ),
2685 (
2686 parse_quote!(std::collections::BTreeMap<String, f64>),
2687 Some("MAP"),
2688 ),
2689 (parse_quote!(Vec<u8>), None),
2691 (parse_quote!(SomeExternalStruct), None),
2693 (parse_quote!(Option<i64>), Some("LONG")),
2694 (parse_quote!(&[i32]), Some("LIST OF INTEGER")),
2695 ];
2696 for (ty, expected) in cases {
2697 assert_eq!(rendered(ty), expected.map(str::to_string));
2698 }
2699 }
2700
2701 #[test]
2703 fn malformed_cow_is_an_error() {
2704 let ty: Type = parse_quote!(Cow<f64>);
2705 assert!(classify(&ty).is_err());
2706 }
2707}