| 7 | use crate::{TypeSet, get_paths, struct_fields}; |
| 8 | |
| 9 | pub fn derive_patch(input: TokenStream) -> syn::Result<TokenStream2> { |
| 10 | let input: syn::DeriveInput = syn::parse(input)?; |
| 11 | let identifier = &input.ident; |
| 12 | let (firewheel_path, diff_path) = get_paths(); |
| 13 | |
| 14 | let patch_ident = format_ident!("{identifier}Patch"); |
| 15 | let vis = &input.vis; |
| 16 | |
| 17 | let PatchOutput { |
| 18 | create_update_struct, |
| 19 | patch_body, |
| 20 | apply_body, |
| 21 | bounds, |
| 22 | fields, |
| 23 | } = match &input.data { |
| 24 | syn::Data::Struct(data) => PatchOutput::from_struct(data, &diff_path, &patch_ident)?, |
| 25 | syn::Data::Enum(data) => { |
| 26 | PatchOutput::from_enum(identifier, data, &diff_path, &patch_ident)? |
| 27 | } |
| 28 | syn::Data::Union(_) => { |
| 29 | return Err(syn::Error::new( |
| 30 | input.span(), |
| 31 | "`Patch` cannot be derived on unions.", |
| 32 | )); |
| 33 | } |
| 34 | }; |
| 35 | |
| 36 | let (impl_generics, ty_generics, where_generics) = input.generics.split_for_impl(); |
| 37 | |
| 38 | let where_generics = match where_generics { |
| 39 | Some(wg) => { |
| 40 | quote! { |
| 41 | #wg |
| 42 | #(#bounds,)* |
| 43 | } |
| 44 | } |
| 45 | None => { |
| 46 | if bounds.is_empty() { |
| 47 | quote! {} |
| 48 | } else { |
| 49 | quote! { |
| 50 | where #(#bounds,)* |
| 51 | } |
| 52 | } |
| 53 | } |
| 54 | }; |
| 55 | |
| 56 | let update_struct = create_update_struct.then(|| { |
| 57 | let line_one = format!( |
| 58 | "The patch enum for [`{}`], generated by Firewheel's `Patch` derive macro.", |
| 59 | identifier |
| 60 | ); |
| 61 | |
| 62 | let line_two = format!( |
| 63 | "This value can be constructed with [`{}::patch`].", |
| 64 | identifier, |
| 65 | ); |
| 66 | |