|
| 1 | +use std::collections::HashMap; |
| 2 | + |
| 3 | +use proc_macro2::{Span, TokenStream}; |
| 4 | +use quote::quote; |
| 5 | +use syn::{Ident, ItemStruct, Lit, Meta, NestedMeta, Result}; |
| 6 | + |
| 7 | +pub fn make_rx_impl(mut orig_struct: ItemStruct, name: Ident) -> TokenStream { |
| 8 | + // So that we don't have to worry about unit structs or unnamed fields, we'll just copy the struct and change the parts we want to |
| 9 | + let mut new_struct = orig_struct.clone(); |
| 10 | + let ItemStruct { |
| 11 | + vis, |
| 12 | + ident, |
| 13 | + generics, |
| 14 | + .. |
| 15 | + } = orig_struct.clone(); |
| 16 | + |
| 17 | + new_struct.ident = name.clone(); |
| 18 | + // Reset the attributes entirely (we don't want any Serde derivations in there) |
| 19 | + // Look through the attributes for any that warn about nested fields |
| 20 | + // These can't exist on the fields themselves because they'd be parsed before this macro, and tehy're technically invalid syntax (grr.) |
| 21 | + // When we come across these fields, we'll run `.make_rx()` on them instead of naively wrapping them in a `Signal` |
| 22 | + let nested_fields = new_struct |
| 23 | + .attrs |
| 24 | + .iter() |
| 25 | + // We only care about our own attributes |
| 26 | + .filter(|attr| { |
| 27 | + attr.path.segments.len() == 2 |
| 28 | + && attr.path.segments.first().unwrap().ident == "rx" |
| 29 | + && attr.path.segments.last().unwrap().ident == "nested" |
| 30 | + }) |
| 31 | + // Remove any attributes that can't be parsed as a `MetaList`, returning the internal list of what can (the 'arguments' to the attribute) |
| 32 | + // We need them to be two elements long (a field name and a wrapper type) |
| 33 | + .filter_map(|attr| match attr.parse_meta() { |
| 34 | + Ok(Meta::List(list)) if list.nested.len() == 2 => Some(list.nested), |
| 35 | + _ => None, |
| 36 | + }) |
| 37 | + // Now parse the tokens within these to an `(Ident, Ident)`, the first being the name of the field and the second being the wrapper type to use |
| 38 | + .map(|meta_list| { |
| 39 | + // Extract field name and wrapper type (we know this only has two elements) |
| 40 | + let field_name = match meta_list.first().unwrap() { |
| 41 | + NestedMeta::Lit(Lit::Str(s)) => Ident::new(s.value().as_str(), Span::call_site()), |
| 42 | + NestedMeta::Lit(val) => { |
| 43 | + return Err(syn::Error::new_spanned( |
| 44 | + val, |
| 45 | + "first argument must be string literal field name", |
| 46 | + )) |
| 47 | + } |
| 48 | + NestedMeta::Meta(meta) => { |
| 49 | + return Err(syn::Error::new_spanned( |
| 50 | + meta, |
| 51 | + "first argument must be string literal field name", |
| 52 | + )) |
| 53 | + } |
| 54 | + }; |
| 55 | + let wrapper_ty = match meta_list.last().unwrap() { |
| 56 | + // TODO Is this `.unwrap()` actually safe to use? |
| 57 | + NestedMeta::Meta(meta) => &meta.path().segments.first().unwrap().ident, |
| 58 | + NestedMeta::Lit(val) => { |
| 59 | + return Err(syn::Error::new_spanned( |
| 60 | + val, |
| 61 | + "second argument must be reactive wrapper type", |
| 62 | + )) |
| 63 | + } |
| 64 | + }; |
| 65 | + |
| 66 | + Ok::<(Ident, Ident), syn::Error>((field_name, wrapper_ty.clone())) |
| 67 | + }) |
| 68 | + .collect::<Vec<Result<(Ident, Ident)>>>(); |
| 69 | + // Handle any errors produced by that final transformation and create a map |
| 70 | + let mut nested_fields_map = HashMap::new(); |
| 71 | + for res in nested_fields { |
| 72 | + match res { |
| 73 | + Ok((k, v)) => nested_fields_map.insert(k, v), |
| 74 | + Err(err) => return err.to_compile_error(), |
| 75 | + }; |
| 76 | + } |
| 77 | + // Now remove our attributes from both the original and the new `struct`s |
| 78 | + let mut filtered_attrs_orig = Vec::new(); |
| 79 | + let mut filtered_attrs_new = Vec::new(); |
| 80 | + for attr in orig_struct.attrs.iter() { |
| 81 | + if !(attr.path.segments.len() == 2 |
| 82 | + && attr.path.segments.first().unwrap().ident == "rx" |
| 83 | + && attr.path.segments.last().unwrap().ident == "nested") |
| 84 | + { |
| 85 | + filtered_attrs_orig.push(attr.clone()); |
| 86 | + filtered_attrs_new.push(attr.clone()); |
| 87 | + } |
| 88 | + } |
| 89 | + orig_struct.attrs = filtered_attrs_orig; |
| 90 | + new_struct.attrs = filtered_attrs_new; |
| 91 | + |
| 92 | + match new_struct.fields { |
| 93 | + syn::Fields::Named(ref mut fields) => { |
| 94 | + for field in fields.named.iter_mut() { |
| 95 | + let orig_ty = &field.ty; |
| 96 | + // Check if this field was registered as one to use nested reactivity |
| 97 | + let wrapper_ty = nested_fields_map.get(field.ident.as_ref().unwrap()); |
| 98 | + field.ty = if let Some(wrapper_ty) = wrapper_ty { |
| 99 | + syn::Type::Verbatim(quote!(#wrapper_ty)) |
| 100 | + } else { |
| 101 | + syn::Type::Verbatim(quote!(::sycamore::prelude::Signal<#orig_ty>)) |
| 102 | + }; |
| 103 | + // Remove any `serde` attributes (Serde can't be used with the reactive version) |
| 104 | + let mut new_attrs = Vec::new(); |
| 105 | + for attr in field.attrs.iter() { |
| 106 | + if !(attr.path.segments.len() == 1 |
| 107 | + && attr.path.segments.first().unwrap().ident == "serde") |
| 108 | + { |
| 109 | + new_attrs.push(attr.clone()); |
| 110 | + } |
| 111 | + } |
| 112 | + field.attrs = new_attrs; |
| 113 | + } |
| 114 | + } |
| 115 | + syn::Fields::Unnamed(_) => return syn::Error::new_spanned( |
| 116 | + new_struct, |
| 117 | + "tuple structs can't be made reactive with this macro (try using named fields instead)", |
| 118 | + ) |
| 119 | + .to_compile_error(), |
| 120 | + syn::Fields::Unit => { |
| 121 | + return syn::Error::new_spanned( |
| 122 | + new_struct, |
| 123 | + "it's pointless to make a unit struct reactive since it has no fields", |
| 124 | + ) |
| 125 | + .to_compile_error() |
| 126 | + } |
| 127 | + }; |
| 128 | + |
| 129 | + // Create a list of fields for the `.make_rx()` method |
| 130 | + let make_rx_fields = match new_struct.fields { |
| 131 | + syn::Fields::Named(ref mut fields) => { |
| 132 | + let mut field_assignments = quote!(); |
| 133 | + for field in fields.named.iter_mut() { |
| 134 | + // We know it has an identifier because it's a named field |
| 135 | + let field_name = field.ident.as_ref().unwrap(); |
| 136 | + // Check if this field was registered as one to use nested reactivity |
| 137 | + if nested_fields_map.contains_key(field.ident.as_ref().unwrap()) { |
| 138 | + field_assignments.extend(quote! { |
| 139 | + #field_name: self.#field_name.make_rx(), |
| 140 | + }) |
| 141 | + } else { |
| 142 | + field_assignments.extend(quote! { |
| 143 | + #field_name: ::sycamore::prelude::Signal::new(self.#field_name), |
| 144 | + }); |
| 145 | + } |
| 146 | + } |
| 147 | + quote! { |
| 148 | + #name { |
| 149 | + #field_assignments |
| 150 | + } |
| 151 | + } |
| 152 | + } |
| 153 | + // We filtered out the other types before |
| 154 | + _ => unreachable!(), |
| 155 | + }; |
| 156 | + |
| 157 | + quote! { |
| 158 | + // We add a Serde derivation because it will always be necessary for Perseus on the original `struct`, and it's really difficult and brittle to filter it out |
| 159 | + #[derive(::serde::Serialize, ::serde::Deserialize)] |
| 160 | + #orig_struct |
| 161 | + #new_struct |
| 162 | + impl#generics #ident#generics { |
| 163 | + /// Converts an instance of `#ident` into an instance of `#name`, making it reactive. This consumes `self`. |
| 164 | + #vis fn make_rx(self) -> #name { |
| 165 | + #make_rx_fields |
| 166 | + } |
| 167 | + } |
| 168 | + } |
| 169 | +} |
0 commit comments