1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
use convert_case::Casing as _;
use proc_macro2::{Span, TokenStream};
use quote::quote;
use syn::{ConstParam, DeriveInput, Generics, Ident, LifetimeParam, TypeParam};
use crate::config::MacroConfig;
pub struct MacroContext {
pub config: MacroConfig,
pub input: DeriveInput,
}
#[allow(dead_code)]
impl MacroContext {
pub fn new(config: MacroConfig, input: DeriveInput) -> Self {
Self { config, input }
}
pub fn ident(&self) -> &Ident {
&self.input.ident
}
/// Returns the type to construct when parsing.
///
/// - For `opaque = "T"`: returns self type (then converts via `.into()`)
/// - For `proxy = "T"`: returns the target type (direct struct literal)
/// - Otherwise: returns self type
pub fn target_type(&self) -> TokenStream {
match &self.config.proxy {
Some(proxy) if !proxy.is_opaque => {
// proxy = "T": use target type directly for struct literal
let target = &proxy.target;
quote! { #target }
}
_ => {
// opaque = "T" or no proxy: construct self type
let ident = self.ident();
quote! { #ident }
}
}
}
/// Returns the opaque target type if `opaque = "T"` is set.
/// Returns `None` for `proxy = "T"` or no proxy attribute.
pub fn opaque_target(&self) -> Option<&syn::Type> {
self.config
.proxy
.as_ref()
.filter(|p| p.is_opaque)
.map(|p| &p.target)
}
pub fn opaque_error_span(&self) -> Span {
self.config
.opaque_span
.unwrap_or_else(|| self.ident().span())
}
pub fn generics(&self) -> &Generics {
&self.input.generics
}
/// Returns generics for the impl<...>
pub fn impl_generics(&self) -> Vec<TokenStream> {
self.generics()
.lifetimes()
.map(
|LifetimeParam {
lifetime,
colon_token,
bounds,
..
}| {
quote! { #lifetime #colon_token #bounds }
},
)
.chain(self.generics().const_params().map(
|ConstParam {
const_token,
colon_token,
ty,
..
}| {
quote! { #const_token #colon_token #ty }
},
))
.chain(self.generics().type_params().map(
|TypeParam {
ident,
colon_token,
bounds,
..
}| {
quote! { #ident #colon_token #bounds }
},
))
.collect()
}
/// Returns generics for the for #ident<...>
pub fn for_generics(&self) -> Vec<TokenStream> {
self.generics()
.lifetimes()
.map(|LifetimeParam { lifetime, .. }| {
quote! { #lifetime }
})
.chain(
self.generics()
.const_params()
.map(|ConstParam { const_token, .. }| {
quote! { #const_token }
}),
)
.chain(
self.generics()
.type_params()
.map(|TypeParam { ident, .. }| {
quote! { #ident }
}),
)
.collect()
}
#[allow(non_snake_case)]
pub fn FromEure(&self) -> TokenStream {
let document_crate = &self.config.document_crate;
quote!(#document_crate::parse::FromEure)
}
#[allow(non_snake_case)]
pub fn ParseError(&self) -> TokenStream {
if let Some(ref custom_error) = self.config.parse_error {
custom_error.clone()
} else {
let document_crate = &self.config.document_crate;
quote!(#document_crate::parse::ParseError)
}
}
#[allow(non_snake_case)]
pub fn ParseContext(&self) -> TokenStream {
let document_crate = &self.config.document_crate;
quote!(#document_crate::parse::ParseContext)
}
#[allow(non_snake_case)]
pub fn IntoEure(&self) -> TokenStream {
let document_crate = &self.config.document_crate;
quote!(#document_crate::write::IntoEure)
}
#[allow(non_snake_case)]
pub fn RecordWriter(&self) -> TokenStream {
let document_crate = &self.config.document_crate;
quote!(#document_crate::write::RecordWriter)
}
#[allow(non_snake_case)]
pub fn WriteError(&self) -> TokenStream {
let document_crate = &self.config.document_crate;
quote!(#document_crate::write::WriteError)
}
#[allow(non_snake_case)]
pub fn WriteImplError(&self) -> TokenStream {
if let Some(ref custom_error) = self.config.write_error {
custom_error.clone()
} else {
self.WriteError()
}
}
#[allow(non_snake_case)]
pub fn DocumentConstructor(&self) -> TokenStream {
let document_crate = &self.config.document_crate;
quote!(#document_crate::constructor::DocumentConstructor)
}
#[allow(non_snake_case)]
pub fn VariantLiteralParser(&self, value: TokenStream, mapper: TokenStream) -> TokenStream {
let document_crate = &self.config.document_crate;
quote!(#document_crate::parse::DocumentParserExt::map(#document_crate::parse::VariantLiteralParser(#value), #mapper))
}
/// Applies container-level `rename_all` to a name.
/// For structs: renames fields. For enums: renames variants.
pub fn apply_rename(&self, name: &str) -> String {
match self.config.rename_all {
Some(rename_all) => name.to_case(rename_all.to_case()),
None => name.to_string(),
}
}
/// Applies `rename_all_fields` to a field name in an enum struct variant.
/// This is separate from `rename_all` which only affects variant names in enums.
pub fn apply_field_rename(&self, name: &str) -> String {
match self.config.rename_all_fields {
Some(rename_all_fields) => name.to_case(rename_all_fields.to_case()),
None => name.to_string(),
}
}
pub fn impl_from_eure(&self, parse_body: TokenStream) -> TokenStream {
// Delegate to impl_from_eure_for with appropriate target type
if let Some(ref proxy) = self.config.proxy {
let target = &proxy.target;
self.impl_from_eure_for(parse_body, Some(quote! { #target }))
} else {
// For non-proxy types, target defaults to Self (omit second type param)
self.impl_from_eure_for(parse_body, None)
}
}
pub fn impl_into_eure(&self, write_body: TokenStream) -> TokenStream {
self.impl_into_eure_with_where_and_flatten(write_body, None, &[])
}
pub fn impl_into_eure_with_where_and_flatten(
&self,
write_body: TokenStream,
flatten_body: Option<TokenStream>,
extra_where: &[TokenStream],
) -> TokenStream {
// Delegate to impl_into_eure_for with appropriate target type
if let Some(ref proxy) = self.config.proxy {
let target = &proxy.target;
self.impl_into_eure_for(
write_body,
flatten_body,
Some(quote! { #target }),
extra_where,
)
} else {
// For non-proxy types, target defaults to Self (omit second type param)
self.impl_into_eure_for(write_body, flatten_body, None, extra_where)
}
}
/// Generate FromEure implementation with specified target type.
///
/// When `target_type` is `None`, this generates standard `FromEure<'doc>`.
/// When `target_type` is `Some(T)`, this generates `FromEure<'doc, T>`.
fn impl_from_eure_for(
&self,
parse_body: TokenStream,
target_type: Option<TokenStream>,
) -> TokenStream {
let ident = self.ident();
let for_generics = self.for_generics();
let parse_document = self.FromEure();
let parse_context = self.ParseContext();
let parse_error = self.ParseError();
let type_params: Vec<_> = self.generics().type_params().collect();
let has_custom_error = self.config.parse_error.is_some();
// Trait signature: FromEure<'doc> or FromEure<'doc, RemoteType>
let trait_sig = match &target_type {
Some(remote) => quote! { #parse_document<'doc, #remote> },
None => quote! { #parse_document<'doc> },
};
// Return type: Self or RemoteType
let return_type = match &target_type {
Some(remote) => quote! { #remote },
None => quote! { Self },
};
// Build impl generics based on the number of type parameters and error configuration
if type_params.is_empty() {
// No type parameters: use default or custom error
let impl_generics = self.impl_generics();
quote! {
impl<'doc, #(#impl_generics),*> #trait_sig for #ident<#(#for_generics),*> {
type Error = #parse_error;
fn parse(ctx: &#parse_context<'doc>) -> Result<#return_type, Self::Error> {
#parse_body
}
}
}
} else if has_custom_error {
// Custom error specified: add FromEure bounds and CustomErr: From<T::Error> bounds
let base_generics = self.impl_generics_with_parse_document_bounds();
let from_bounds: Vec<_> = type_params
.iter()
.map(|tp| {
let ident = &tp.ident;
quote! { #parse_error: From<<#ident as #parse_document<'doc>>::Error> }
})
.collect();
quote! {
impl<'doc, #(#base_generics),*> #trait_sig for #ident<#(#for_generics),*>
where
#(#from_bounds),*
{
type Error = #parse_error;
fn parse(ctx: &#parse_context<'doc>) -> Result<#return_type, Self::Error> {
#parse_body
}
}
}
} else {
// Generic type parameters: require all to have Error = ParseError
// This ensures compatibility with the existing eure-document API constraints
let base_generics = self.impl_generics_with_unified_error_bounds(parse_error.clone());
quote! {
impl<'doc, #(#base_generics),*> #trait_sig for #ident<#(#for_generics),*> {
type Error = #parse_error;
fn parse(ctx: &#parse_context<'doc>) -> Result<#return_type, Self::Error> {
#parse_body
}
}
}
}
}
/// Generate IntoEure implementation with specified target type.
///
/// When `target_type` is `None`, this generates standard `IntoEure`.
/// When `target_type` is `Some(T)`, this generates `IntoEure<T>`.
fn impl_into_eure_for(
&self,
write_body: TokenStream,
flatten_body: Option<TokenStream>,
target_type: Option<TokenStream>,
extra_where: &[TokenStream],
) -> TokenStream {
let ident = self.ident();
let for_generics = self.for_generics();
let into_eure = self.IntoEure();
let write_error = self.WriteImplError();
let document_constructor = self.DocumentConstructor();
let record_writer = self.RecordWriter();
let type_params: Vec<_> = self.generics().type_params().collect();
let mut where_preds: Vec<TokenStream> = extra_where.to_vec();
for tp in &type_params {
let ident = &tp.ident;
where_preds.push(quote! {
#write_error: ::core::convert::From<<#ident as #into_eure>::Error>
});
}
let where_clause = if where_preds.is_empty() {
quote! {}
} else {
quote! { where #(#where_preds),* }
};
// Trait signature: IntoEure or IntoEure<RemoteType>
let trait_sig = match &target_type {
Some(remote) => quote! { #into_eure<#remote> },
None => quote! { #into_eure },
};
// Value type in signature: Self or RemoteType
let value_type = match &target_type {
Some(remote) => quote! { #remote },
None => quote! { Self },
};
let flatten_method = if let Some(flatten_body) = flatten_body {
quote! {
fn write_flatten(value: #value_type, rec: &mut #record_writer<'_>) -> ::core::result::Result<(), Self::Error> {
#flatten_body
}
}
} else {
quote! {}
};
// Build impl generics based on the number of type parameters
if type_params.is_empty() {
let impl_generics = self.impl_generics();
if impl_generics.is_empty() {
quote! {
impl #trait_sig for #ident #where_clause {
type Error = #write_error;
fn write(value: #value_type, c: &mut #document_constructor) -> ::core::result::Result<(), Self::Error> {
#write_body
}
#flatten_method
}
}
} else {
quote! {
impl<#(#impl_generics),*> #trait_sig for #ident<#(#for_generics),*> #where_clause {
type Error = #write_error;
fn write(value: #value_type, c: &mut #document_constructor) -> ::core::result::Result<(), Self::Error> {
#write_body
}
#flatten_method
}
}
}
} else {
// Generic type parameters: require all to impl IntoEure
let base_generics = self.impl_generics_with_into_eure_bounds();
quote! {
impl<#(#base_generics),*> #trait_sig for #ident<#(#for_generics),*> #where_clause {
type Error = #write_error;
fn write(value: #value_type, c: &mut #document_constructor) -> ::core::result::Result<(), Self::Error> {
#write_body
}
#flatten_method
}
}
}
}
/// Returns impl generics with IntoEure bounds added to type parameters.
fn impl_generics_with_into_eure_bounds(&self) -> Vec<TokenStream> {
let into_eure = self.IntoEure();
self.generics()
.lifetimes()
.map(
|LifetimeParam {
lifetime,
colon_token,
bounds,
..
}| {
quote! { #lifetime #colon_token #bounds }
},
)
.chain(self.generics().const_params().map(
|ConstParam {
const_token,
colon_token,
ty,
..
}| {
quote! { #const_token #colon_token #ty }
},
))
.chain(self.generics().type_params().map(
|TypeParam {
ident,
colon_token,
bounds,
..
}| {
if bounds.is_empty() {
quote! { #ident: #into_eure }
} else {
quote! { #ident #colon_token #bounds + #into_eure }
}
},
))
.collect()
}
/// Returns impl generics with FromEure<'doc> bounds added to type parameters.
fn impl_generics_with_parse_document_bounds(&self) -> Vec<TokenStream> {
let parse_document = self.FromEure();
self.generics()
.lifetimes()
.map(
|LifetimeParam {
lifetime,
colon_token,
bounds,
..
}| {
quote! { #lifetime #colon_token #bounds }
},
)
.chain(self.generics().const_params().map(
|ConstParam {
const_token,
colon_token,
ty,
..
}| {
quote! { #const_token #colon_token #ty }
},
))
.chain(self.generics().type_params().map(
|TypeParam {
ident,
colon_token,
bounds,
..
}| {
if bounds.is_empty() {
quote! { #ident: #parse_document<'doc> }
} else {
quote! { #ident #colon_token #bounds + #parse_document<'doc> }
}
},
))
.collect()
}
/// Returns impl generics with unified error type bounds for multiple type parameters.
fn impl_generics_with_unified_error_bounds(&self, error_type: TokenStream) -> Vec<TokenStream> {
let parse_document = self.FromEure();
self.generics()
.lifetimes()
.map(
|LifetimeParam {
lifetime,
colon_token,
bounds,
..
}| {
quote! { #lifetime #colon_token #bounds }
},
)
.chain(self.generics().const_params().map(
|ConstParam {
const_token,
colon_token,
ty,
..
}| {
quote! { #const_token #colon_token #ty }
},
))
.chain(self.generics().type_params().map(
|TypeParam {
ident,
colon_token,
bounds,
..
}| {
if bounds.is_empty() {
quote! { #ident: #parse_document<'doc, Error = #error_type> }
} else {
quote! { #ident #colon_token #bounds + #parse_document<'doc, Error = #error_type> }
}
},
))
.collect()
}
// ========================================================================
// BuildSchema helpers
// ========================================================================
/// Returns the path to the schema crate (eure_schema)
pub fn schema_crate(&self) -> TokenStream {
// For now, always use ::eure_schema
// In the future, this could be configurable via an attribute
quote!(::eure_schema)
}
/// Generates the BuildSchema impl block
pub fn impl_build_schema(&self, build_body: TokenStream) -> TokenStream {
let ident = self.ident();
let impl_generics = self.impl_generics();
let for_generics = self.for_generics();
let schema_crate = self.schema_crate();
// Add BuildSchema + 'static bounds to type parameters
let impl_generics_with_bounds: Vec<_> = self
.generics()
.lifetimes()
.map(
|LifetimeParam {
lifetime,
colon_token,
bounds,
..
}| {
quote! { #lifetime #colon_token #bounds }
},
)
.chain(self.generics().const_params().map(
|ConstParam {
const_token,
colon_token,
ty,
..
}| {
quote! { #const_token #colon_token #ty }
},
))
.chain(self.generics().type_params().map(
|TypeParam {
ident,
colon_token,
bounds,
..
}| {
if bounds.is_empty() {
quote! { #ident: #schema_crate::BuildSchema + 'static }
} else {
quote! { #ident #colon_token #bounds + #schema_crate::BuildSchema + 'static }
}
},
))
.collect();
// Generate type_name() if configured
let type_name_impl = if let Some(ref name) = self.config.type_name {
quote! {
fn type_name() -> Option<&'static str> {
Some(#name)
}
}
} else {
quote! {}
};
// Handle empty generics case
if impl_generics.is_empty() {
quote! {
impl #schema_crate::BuildSchema for #ident {
#type_name_impl
fn build_schema(ctx: &mut #schema_crate::SchemaBuilder) -> #schema_crate::SchemaNodeContent {
use #schema_crate::BuildSchema;
#build_body
}
}
}
} else {
quote! {
impl<#(#impl_generics_with_bounds),*> #schema_crate::BuildSchema for #ident<#(#for_generics),*> {
#type_name_impl
fn build_schema(ctx: &mut #schema_crate::SchemaBuilder) -> #schema_crate::SchemaNodeContent {
use #schema_crate::BuildSchema;
#build_body
}
}
}
}
}
}