dterror-derive 0.2.0

Proc-macros for the dterror CtxError and FromContext traits
Documentation
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
//! This module expands the kind path.
//! The derive generates the `{Kind}Ctx` type, its constructors,
//! the `From<{Kind}Ctx<'_>> for {Kind}` impl, and the `FromContext` impl.

use proc_macro2::TokenStream as TokenStream2;
use quote::{format_ident, quote};
use syn::{Data, DataEnum, DataStruct, DeriveInput, Field, Fields, Ident, Variant, parse_quote};

use super::derive_attr::{CtxDerives, parse_ctx_derives};
use super::expand_enum::{check_unique_constructor_names, parse_constructor_override};
use super::field::{CtxField, CtxTarget, bind_lifetimes_to_ctx, contains_lifetime};
use super::naming::to_snek_case;
use super::validate::validate_generics;

const DERIVE_NAME: &str = "FromContext";

/// This struct stores one constructible kind variant and its resolved constructor name.
/// The default constructor name uses `snake_case`.
/// A `#[context(constructor = "...")]` attribute overrides the default name.
struct KindVariant<'a> {
    /// This field stores the original `syn` variant definition.
    variant: &'a Variant,
    /// This field stores the context fields of this variant in the declaration order.
    fields: Vec<CtxField<'a>>,
    /// This field stores the name of the generated constructor on `{Kind}Ctx`.
    ctor_name: Ident,
}

/// The derive expands `#[derive(FromContext)]`.
/// The function selects the expansion path based on the shape of the item.
pub(crate) fn expand_kind_item(input: &DeriveInput) -> syn::Result<TokenStream2> {
    let derives = parse_ctx_derives(input)?;
    let ctx_ident = format_ident!("{}Ctx", input.ident);
    match &input.data {
        Data::Struct(data) => expand_struct(input, data, &ctx_ident, &derives),
        Data::Enum(data) => expand_enum(input, data, &ctx_ident, &derives),
        Data::Union(data) => Err(syn::Error::new_spanned(
            data.union_token,
            "`#[derive(FromContext)]` does not support unions",
        )),
    }
}

/// This function classifies the named fields of a kind scope.
/// Every field becomes a context field.
fn classify_fields<'a>(
    fields: impl IntoIterator<Item = &'a Field>,
) -> syn::Result<Vec<CtxField<'a>>> {
    fields.into_iter().map(CtxField::parse).collect()
}

/// This function checks whether a field requires `'ctx` on the generated `{Kind}Ctx`.
/// A borrowed field stores `&'ctx Target`, which requires `'ctx`.
/// A from-target that mentions lifetimes binds those lifetimes to `'ctx`.
/// The derive omits `'ctx` when no field requires it. This avoids E0392.
fn has_ctx_lifetime<'a>(fields: impl IntoIterator<Item = &'a CtxField<'a>>) -> bool {
    fields.into_iter().any(|cf| match &cf.target {
        CtxTarget::Borrow(_) => true,
        CtxTarget::From(target) => contains_lifetime(target),
        CtxTarget::Field => false,
    })
}

/// This function returns the type that `{Kind}Ctx` stores for a context field.
/// A borrowed field stores `&'ctx TargetType`.
/// A from-marked field stores the owned target type with lifetimes bound to `'ctx`.
/// An unmarked field stores the type of the field itself.
fn stored_ty(cf: &CtxField) -> TokenStream2 {
    match &cf.target {
        CtxTarget::Borrow(target) => quote! { &'ctx #target },
        CtxTarget::From(target) => {
            let target = bind_lifetimes_to_ctx(target);
            quote! { #target }
        }
        CtxTarget::Field => {
            let ty = cf.ty();
            quote! { #ty }
        }
    }
}

/// This function builds the constructor argument for a context field.
/// A borrowed field takes `&'ctx TargetType` directly so that the macro does not clone or allocate a value.
/// Every other field takes `impl Into<...>` of the stored type.
fn ctor_arg(cf: &CtxField) -> TokenStream2 {
    let ident = cf.ident();
    match &cf.target {
        CtxTarget::Borrow(target) => quote! { #ident: &'ctx #target },
        CtxTarget::From(target) => {
            let target = bind_lifetimes_to_ctx(target);
            quote! { #ident: impl Into<#target> }
        }
        CtxTarget::Field => {
            let ty = cf.ty();
            quote! { #ident: impl Into<#ty> }
        }
    }
}

/// This function builds the type that `{Kind}Ctx` has in the argument position of the `From` impl.
/// The injected `'ctx` becomes an elided lifetime because that impl carries only the generics of the kind.
fn from_arg_ty(
    ctx_ident: &Ident,
    input: &DeriveInput,
    has_ctx_lifetime: bool,
    kind_type_generics: &syn::TypeGenerics<'_>,
) -> TokenStream2 {
    if has_ctx_lifetime {
        let type_params = input.generics.type_params().map(|param| &param.ident);
        quote! { #ctx_ident < '_ , #(#type_params),* > }
    } else {
        quote! { #ctx_ident #kind_type_generics }
    }
}

/// This function builds the `impl dterror::FromContext for {Kind}` that aliases the generated `{Kind}Ctx`.
fn from_context_impl(
    kind_ident: &Ident,
    ctx_ident: &Ident,
    has_ctx_lifetime: bool,
    impl_generics: &syn::ImplGenerics<'_>,
    kind_type_generics: &syn::TypeGenerics<'_>,
    where_clause: Option<&syn::WhereClause>,
    ctx_type_generics: &syn::TypeGenerics<'_>,
) -> TokenStream2 {
    // The GAT alias references the Ctx with `'ctx` when a field requires it, or without it.
    // When no field requires `'ctx`, the alias includes `'ctx` as an unused phantom lifetime.
    let gat_type_alias = if has_ctx_lifetime {
        quote! { #ctx_ident #ctx_type_generics }
    } else {
        quote! { #ctx_ident #kind_type_generics }
    };

    quote! {
        #[automatically_derived]
        impl #impl_generics ::dterror::FromContext for #kind_ident #kind_type_generics #where_clause {
            type Ctx<'ctx> = #gat_type_alias;
        }
    }
}

/// This function expands the struct path.
/// The derive generates the `{Kind}Ctx` struct, the `new` constructor, the `From` impl, and the `FromContext` impl.
fn expand_struct(
    input: &DeriveInput,
    data: &DataStruct,
    ctx_ident: &Ident,
    derives: &CtxDerives,
) -> syn::Result<TokenStream2> {
    let Fields::Named(fields) = &data.fields else {
        return Err(syn::Error::new_spanned(
            input,
            "`#[derive(FromContext)]` only supports structs with named fields",
        ));
    };

    let context_fields = classify_fields(&fields.named)?;

    if context_fields.is_empty() {
        return Err(syn::Error::new_spanned(
            input,
            "`#[derive(FromContext)]` requires at least one field",
        ));
    }

    validate_generics(input, DERIVE_NAME, &context_fields)?;

    let kind_ident = &input.ident;
    let vis = &input.vis;
    let has_ctx_lifetime = has_ctx_lifetime(&context_fields);

    let (impl_generics, kind_type_generics, where_clause) = input.generics.split_for_impl();

    // The code builds a second `Generics` set that inserts `'ctx` as the first lifetime parameter.
    let mut ctx_generics_lifetime = input.generics.clone();
    if has_ctx_lifetime {
        ctx_generics_lifetime.params.insert(0, parse_quote!('ctx));
    }
    let (ctx_impl_generics, ctx_type_generics, _) = ctx_generics_lifetime.split_for_impl();

    let ctx_fields = context_fields.iter().map(|cf| {
        let fvis = cf.vis();
        let ident = cf.ident();
        let stored = stored_ty(cf);
        quote! { #fvis #ident: #stored }
    });
    let struct_generics = if has_ctx_lifetime {
        quote! { #ctx_impl_generics }
    } else {
        quote! { #impl_generics }
    };
    let derive_attr = derives.derive_attr();
    let ctx_struct = quote! {
        #[allow(dead_code)]
        #derive_attr
        #vis struct #ctx_ident #struct_generics #where_clause {
            #(#ctx_fields,)*
        }
    };

    let new_args = context_fields.iter().map(ctor_arg);
    let new_body = context_fields.iter().map(|cf| {
        let ident = cf.ident();
        if let CtxTarget::Borrow(_) = &cf.target {
            quote! { #ident: #ident, }
        } else {
            quote! { #ident: #ident.into(), }
        }
    });
    let (new_impl_generics, new_type_generics) = if has_ctx_lifetime {
        (&ctx_impl_generics, &ctx_type_generics)
    } else {
        (&impl_generics, &kind_type_generics)
    };
    let new_impl = quote! {
        impl #new_impl_generics #ctx_ident #new_type_generics #where_clause {
            /// Construct the context from one argument per field, in declaration order.
            pub fn new(#(#new_args),*) -> Self {
                Self {
                    #(#new_body)*
                }
            }
        }
    };

    let from_inits = context_fields.iter().map(|cf| {
        let ident = cf.ident();
        if let CtxTarget::Field = &cf.target {
            quote! { #ident: value.#ident, }
        } else {
            quote! { #ident: value.#ident.into(), }
        }
    });
    let from_arg = from_arg_ty(ctx_ident, input, has_ctx_lifetime, &kind_type_generics);
    let from_impl = quote! {
        #[automatically_derived]
        impl #impl_generics ::core::convert::From<#from_arg> for #kind_ident #kind_type_generics #where_clause {
            fn from(value: #from_arg) -> Self {
                Self {
                    #(#from_inits)*
                }
            }
        }
    };

    let trait_impl = from_context_impl(
        kind_ident,
        ctx_ident,
        has_ctx_lifetime,
        &impl_generics,
        &kind_type_generics,
        where_clause,
        &ctx_type_generics,
    );

    Ok(quote! {
        #ctx_struct
        #new_impl
        #from_impl
        #trait_impl
    })
}

fn get_variants<'a>(input: &DeriveInput, data: &'a DataEnum) -> syn::Result<Vec<KindVariant<'a>>> {
    let mut kind_variants = vec![];

    for variant in &data.variants {
        match &variant.fields {
            // Unit variants construct a unit Ctx variant with a zero-argument constructor.
            Fields::Unit => kind_variants.push(KindVariant {
                variant,
                fields: Vec::new(),
                ctor_name: parse_constructor_override(variant)?
                    .unwrap_or_else(|| to_snek_case(&variant.ident)),
            }),
            Fields::Unnamed(_) => {
                return Err(syn::Error::new_spanned(
                    variant,
                    "`#[derive(FromContext)]` only supports variants with named fields",
                ));
            }
            Fields::Named(fields) => kind_variants.push(KindVariant {
                variant,
                fields: classify_fields(&fields.named)?,
                ctor_name: parse_constructor_override(variant)?
                    .unwrap_or_else(|| to_snek_case(&variant.ident)),
            }),
        }
    }

    if kind_variants.is_empty() {
        return Err(syn::Error::new_spanned(
            input,
            "`#[derive(FromContext)]` requires at least one variant",
        ));
    }

    Ok(kind_variants)
}

fn expand_enum_variant(kv: &KindVariant<'_>) -> TokenStream2 {
    let vident = &kv.variant.ident;
    if kv.fields.is_empty() {
        return quote! { #vident };
    }
    let ctx_fields = kv.fields.iter().map(|cf| {
        let fvis = cf.vis();
        let ident = cf.ident();
        let stored = stored_ty(cf);
        quote! { #fvis #ident: #stored }
    });
    quote! { #vident { #(#ctx_fields,)* } }
}

fn expand_enum_variant_fn(kv: &KindVariant<'_>) -> TokenStream2 {
    let vident = &kv.variant.ident;
    let name = &kv.ctor_name;
    if kv.fields.is_empty() {
        let doc = format!("Construct the `{vident}` context variant.");
        return quote! {
            #[doc = #doc]
            pub fn #name() -> Self {
                Self::#vident
            }
        };
    }
    let args = kv.fields.iter().map(ctor_arg);
    let body = kv.fields.iter().map(|cf| {
        let ident = cf.ident();
        if let CtxTarget::Borrow(_) = &cf.target {
            quote! { #ident: #ident, }
        } else {
            quote! { #ident: #ident.into(), }
        }
    });
    let doc = format!(
        "Construct the `{vident}` context variant from one argument per field, in declaration order."
    );
    quote! {
        #[doc = #doc]
        pub fn #name(#(#args),*) -> Self {
            Self::#vident {
                #(#body)*
            }
        }
    }
}

/// This function expands the enum path.
/// The derive classifies every variant and validates the names and generics.
/// The derive generates the Ctx enum, the constructors for each variant, the `From` impl, and the `FromContext` impl.
fn expand_enum(
    input: &DeriveInput,
    data: &DataEnum,
    ctx_ident: &Ident,
    derives: &CtxDerives,
) -> syn::Result<TokenStream2> {
    let kind_variants = get_variants(input, data)?;

    check_unique_constructor_names(kind_variants.iter().map(|kv| (&kv.ctor_name, kv.variant)))?;

    // The Ctx enum declares the full type-parameter list of the item.
    // The derive validates generics for all variants together.
    let context_fields = kind_variants.iter().flat_map(|kv| kv.fields.iter());
    validate_generics(input, DERIVE_NAME, context_fields)?;

    let kind_ident = &input.ident;
    let vis = &input.vis;
    let has_ctx_lifetime = has_ctx_lifetime(kind_variants.iter().flat_map(|kv| kv.fields.iter()));

    let (impl_generics, kind_type_generics, where_clause) = input.generics.split_for_impl();

    // The code builds a second `Generics` set that inserts `'ctx` as the first lifetime parameter.
    let mut ctx_generics_lifetime = input.generics.clone();
    if has_ctx_lifetime {
        ctx_generics_lifetime.params.insert(0, parse_quote!('ctx));
    }
    let (ctx_impl_generics, ctx_type_generics, _) = ctx_generics_lifetime.split_for_impl();

    let variants = kind_variants.iter().map(expand_enum_variant);
    let enum_generics = if has_ctx_lifetime {
        quote! { #ctx_impl_generics }
    } else {
        quote! { #impl_generics }
    };
    let derive_attr = derives.derive_attr();
    let ctx_enum = quote! {
        #[allow(dead_code)]
        #derive_attr
        #vis enum #ctx_ident #enum_generics #where_clause {
            #(#variants,)*
        }
    };

    let fns = kind_variants.iter().map(expand_enum_variant_fn);
    let (ctor_impl_generics, ctor_type_generics) = if has_ctx_lifetime {
        (&ctx_impl_generics, &ctx_type_generics)
    } else {
        (&impl_generics, &kind_type_generics)
    };
    let constructors = quote! {
        impl #ctor_impl_generics #ctx_ident #ctor_type_generics #where_clause {
            #(#fns)*
        }
    };

    let arms = kind_variants.iter().map(|kv| {
        let vident = &kv.variant.ident;
        if kv.fields.is_empty() {
            return quote! {
                #ctx_ident::#vident => #kind_ident::#vident,
            };
        }
        let bindings = kv.fields.iter().map(CtxField::ident);
        let inits = kv.fields.iter().map(|cf| {
            let ident = cf.ident();
            if let CtxTarget::Field = &cf.target {
                quote! { #ident: #ident, }
            } else {
                quote! { #ident: #ident.into(), }
            }
        });
        quote! {
            #ctx_ident::#vident { #(#bindings),* } => #kind_ident::#vident {
                #(#inits)*
            },
        }
    });

    let from_arg = from_arg_ty(ctx_ident, input, has_ctx_lifetime, &kind_type_generics);
    let from_impl = quote! {
        #[automatically_derived]
        impl #impl_generics ::core::convert::From<#from_arg> for #kind_ident #kind_type_generics #where_clause {
            fn from(value: #from_arg) -> Self {
                match value {
                    #(#arms)*
                }
            }
        }
    };

    let trait_impl = from_context_impl(
        kind_ident,
        ctx_ident,
        has_ctx_lifetime,
        &impl_generics,
        &kind_type_generics,
        where_clause,
        &ctx_type_generics,
    );

    Ok(quote! {
        #ctx_enum
        #constructors
        #from_impl
        #trait_impl
    })
}