1use proc_macro::TokenStream;
2use quote::quote;
3use syn::{parse_macro_input, Data, DeriveInput, Fields, Ident, Type};
4
5#[proc_macro_derive(JsonMutatorSchema, attributes(json))]
6pub fn derive_json_mutator_schema(input: TokenStream) -> TokenStream {
7 let input = parse_macro_input!(input as DeriveInput);
8 match expand_derive(&input) {
9 Ok(tokens) => tokens.into(),
10 Err(err) => err.to_compile_error().into(),
11 }
12}
13
14fn expand_derive(input: &DeriveInput) -> Result<proc_macro2::TokenStream, syn::Error> {
15 let struct_name = &input.ident;
16 let mutator_name = Ident::new(&format!("{}Mutator", struct_name), struct_name.span());
17
18 let data = match &input.data {
19 Data::Struct(s) => s,
20 _ => {
21 return Err(syn::Error::new_spanned(
22 input,
23 "JsonMutatorSchema can only be derived on structs",
24 ));
25 }
26 };
27
28 let fields = match &data.fields {
29 Fields::Named(f) => &f.named,
30 _ => {
31 return Err(syn::Error::new_spanned(
32 input,
33 "JsonMutatorSchema can only be derived on structs with named fields",
34 ));
35 }
36 };
37
38 let mut field_reads = Vec::new();
39 let mut mutator_setters = Vec::new();
40 let mut path_statics = Vec::new();
41
42 for field in fields {
43 let field_name = field.ident.as_ref().ok_or_else(|| {
44 syn::Error::new_spanned(field, "JsonMutatorSchema requires named fields")
45 })?;
46 let field_type = &field.ty;
47 let raw_path = get_json_path(field)?;
48
49 let path_segments = parse_path_segments(&raw_path).map_err(|msg| {
50 syn::Error::new_spanned(
51 field,
52 format!("invalid #[json(path = ...)] value `{raw_path}`: {msg}"),
53 )
54 })?;
55
56 let path_const_name = Ident::new(
57 &format!("__JSHIFT_PATH_{}", field_name.to_string().to_uppercase()),
58 field_name.span(),
59 );
60
61 let seg_tokens: Vec<_> = path_segments
62 .iter()
63 .map(|s| match s {
64 DerSegment::Key(k) => quote! { jshift::PathSegment::Key(#k) },
65 DerSegment::Index(i) => quote! { jshift::PathSegment::Index(#i) },
66 })
67 .collect();
68
69 path_statics.push(quote! {
70 const #path_const_name: &'static [jshift::PathSegment<'static>] = &[
71 #(#seg_tokens),*
72 ];
73 });
74
75 let is_option = is_option_type(field_type);
76 let setter_name = Ident::new(&format!("set_{}", field_name), field_name.span());
77
78 if is_option {
79 field_reads.push(quote! {
80 #field_name: {
81 match jshift::find_value(json, Self::#path_const_name) {
82 Ok(slice) => {
83 jshift::FromJsonSlice::from_json_slice(slice)
84 .ok_or(jshift::Error::TypeMismatch {
85 expected: stringify!(#field_type),
86 found: "invalid format",
87 })?
88 }
89 Err(jshift::Error::PathNotFound) => None,
90 Err(e) => return Err(e),
91 }
92 }
93 });
94 } else {
95 field_reads.push(quote! {
96 #field_name: {
97 let slice = jshift::find_value(json, Self::#path_const_name)?;
98 jshift::FromJsonSlice::from_json_slice(slice)
99 .ok_or(jshift::Error::TypeMismatch {
100 expected: stringify!(#field_type),
101 found: "invalid format",
102 })?
103 }
104 });
105 }
106
107 mutator_setters.push(quote! {
108 pub fn #setter_name(&mut self, val: &(impl jshift::ToJsonBytes + ?Sized)) -> Result<(), jshift::Error> {
109 let bytes = jshift::ToJsonBytes::to_json_bytes(val);
110 jshift::mutate_value(self.json, #struct_name::#path_const_name, &bytes)
111 }
112 });
113
114 if is_vec_type(field_type) {
115 let append_name = Ident::new(&format!("append_{}", field_name), field_name.span());
116 mutator_setters.push(quote! {
117 pub fn #append_name(&mut self, val: &(impl jshift::ToJsonBytes + ?Sized)) -> Result<(), jshift::Error> {
118 let bytes = jshift::ToJsonBytes::to_json_bytes(val);
119 jshift::append_to_array(self.json, #struct_name::#path_const_name, &bytes)
120 }
121 });
122 }
123 }
124
125 Ok(quote! {
126 impl #struct_name {
127 #(#path_statics)*
128
129 pub fn read_from_json(json: &[u8]) -> Result<Self, jshift::Error> {
130 Ok(Self {
131 #(#field_reads),*
132 })
133 }
134
135 pub fn mutator(json: &mut Vec<u8>) -> #mutator_name {
136 #mutator_name { json }
137 }
138 }
139
140 pub struct #mutator_name<'a> {
141 json: &'a mut Vec<u8>,
142 }
143
144 impl<'a> #mutator_name<'a> {
145 #(#mutator_setters)*
146 }
147 })
148}
149
150fn get_json_path(field: &syn::Field) -> Result<String, syn::Error> {
151 let mut path_str = None;
152 for attr in &field.attrs {
153 if attr.path().is_ident("json") {
154 attr.parse_nested_meta(|meta| {
155 if meta.path.is_ident("path") {
156 let value = meta.value()?;
157 let lit: syn::LitStr = value.parse()?;
158 path_str = Some(lit.value());
159 Ok(())
160 } else {
161 Err(meta.error("unsupported json attribute; expected `path = \"...\"`"))
162 }
163 })?;
164 }
165 }
166
167 Ok(path_str.unwrap_or_else(|| {
168 field
169 .ident
170 .as_ref()
171 .expect("named field")
172 .to_string()
173 }))
174}
175
176fn is_vec_type(ty: &Type) -> bool {
177 type_last_ident(ty).is_some_and(|id| id == "Vec")
178}
179
180fn is_option_type(ty: &Type) -> bool {
181 type_last_ident(ty).is_some_and(|id| id == "Option")
182}
183
184fn type_last_ident(ty: &Type) -> Option<&syn::Ident> {
185 if let Type::Path(type_path) = ty {
186 type_path.path.segments.last().map(|s| &s.ident)
187 } else {
188 None
189 }
190}
191
192enum DerSegment {
193 Key(String),
194 Index(usize),
195}
196
197fn parse_path_segments(s: &str) -> Result<Vec<DerSegment>, &'static str> {
199 let mut rest = s;
200 let mut segments = Vec::new();
201 while !rest.is_empty() {
202 if rest.starts_with('.') {
203 rest = &rest[1..];
204 continue;
205 }
206 if rest.starts_with('[') {
207 match rest.find(']') {
208 Some(end_idx) => {
209 let idx_str = &rest[1..end_idx];
210 if idx_str.is_empty() {
211 return Err("empty array index brackets");
212 }
213 if !idx_str.bytes().all(|b| b.is_ascii_digit()) {
214 return Err("non-numeric array index");
215 }
216 let idx = idx_str
217 .parse::<usize>()
218 .map_err(|_| "array index out of range for usize")?;
219 segments.push(DerSegment::Index(idx));
220 rest = &rest[end_idx + 1..];
221 }
222 None => return Err("unclosed array index bracket '['"),
223 }
224 } else {
225 let end_key = rest.find(['.', '[']).unwrap_or(rest.len());
226 let key = &rest[..end_key];
227 if !key.is_empty() {
228 segments.push(DerSegment::Key(key.to_string()));
229 }
230 rest = &rest[end_key..];
231 }
232 }
233 Ok(segments)
234}