variadic_from_meta 0.32.0

Variadic from, proc-macro part.
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
#![ doc( html_logo_url = "https://raw.githubusercontent.com/Wandalen/wTools/master/asset/img/logo_v3_trans_square.png" ) ]
#![ doc
(
  html_favicon_url = "https://raw.githubusercontent.com/Wandalen/wTools/alpha/asset/img/logo_v3_trans_square_icon_small_v2.ico"
) ]
#![ doc( html_root_url = "https://docs.rs/variadic_from_meta/latest/variadic_from_meta/" ) ]
//! Procedural macros for the `variadic_from` crate.

use macro_tools::{ proc_macro2, quote, quote::ToTokens, syn };

/// Context for generating `VariadicFrom` implementations.
struct VariadicFromContext< 'a >
{
  name : &'a syn::Ident,
  field_types : Vec< &'a syn::Type >,
  field_names_or_indices : Vec< proc_macro2::TokenStream >,
  is_tuple_struct : bool,
  num_fields : usize,
  generics : &'a syn::Generics,
}

impl< 'a > VariadicFromContext< 'a >
{
  fn new( ast : &'a syn::DeriveInput ) -> syn::Result< Self >
  {
    let name = &ast.ident;

    let ( field_types, field_names_or_indices, is_tuple_struct ) : ( Vec< &syn::Type >, Vec< proc_macro2::TokenStream >, bool ) =
    match &ast.data
    {
      syn::Data::Struct( data ) => match &data.fields
      {
        syn::Fields::Named( fields ) =>
        {
          let types = fields.named.iter().map( |f| &f.ty ).collect();
          let names = fields
          .named
          .iter()
          .map( |f| f.ident.as_ref().unwrap().to_token_stream() )
          .collect();
          ( types, names, false )
        }
        syn::Fields::Unnamed( fields ) =>
        {
          let types = fields.unnamed.iter().map( |f| &f.ty ).collect();
          let indices = ( 0..fields.unnamed.len() )
          .map( |i| syn::Index::from( i ).to_token_stream() )
          .collect();
          ( types, indices, true )
        }
        syn::Fields::Unit =>
        {
          return Err( syn::Error::new_spanned(
            ast,
            "VariadicFrom can only be derived for structs with named or unnamed fields.",
          ) )
        }
      },
      _ => return Err( syn::Error::new_spanned( ast, "VariadicFrom can only be derived for structs." ) ),
    };

    let num_fields = field_types.len();

    Ok( Self
    {
      name,
      field_types,
      field_names_or_indices,
      is_tuple_struct,
      num_fields,
      generics : &ast.generics,
    } )
  }

  /// Generates the struct constructor expression using per-field argument names.
  fn constructor( &self, args : &[ proc_macro2::Ident ] ) -> proc_macro2::TokenStream
  {
    if self.is_tuple_struct
    {
      quote! { ( #( #args ),* ) }
    }
    else
    {
      let named_field_inits = self
      .field_names_or_indices
      .iter()
      .zip( args.iter() )
      .map( |( name, arg )| { quote! { #name : #arg } } )
      .collect::< Vec< _ > >();
      quote! { { #( #named_field_inits ),* } }
    }
  }

  /// Generates the struct constructor expression when every field receives the same argument.
  fn constructor_uniform( &self, arg : &proc_macro2::Ident ) -> proc_macro2::TokenStream
  {
    if self.is_tuple_struct
    {
      let repeated_args = ( 0..self.num_fields ).map( |_| arg ).collect::< Vec< _ > >();
      quote! { ( #( #repeated_args ),* ) }
    }
    else
    {
      let named_field_inits = self
      .field_names_or_indices
      .iter()
      .map( |name| { quote! { #name : #arg } } )
      .collect::< Vec< _ > >();
      quote! { { #( #named_field_inits ),* } }
    }
  }

  /// Returns true when all field types are identical under token-string comparison.
  fn are_all_field_types_identical( &self ) -> bool
  {
    if self.num_fields == 0
    {
      return true;
    }
    let first_type = &self.field_types[ 0 ];
    // Fragile: token-string comparison — aliases and fully-qualified paths will not match.
    self
    .field_types
    .iter()
    .all( |ty| ty.to_token_stream().to_string() == first_type.to_token_stream().to_string() )
  }

  /// Returns true when all field types from `start_idx` onward are identical.
  fn are_field_types_identical_from( &self, start_idx : usize ) -> bool
  {
    if start_idx >= self.num_fields
    {
      return true;
    }
    let first_type = &self.field_types[ start_idx ];
    // Fragile: token-string comparison — aliases and fully-qualified paths will not match.
    self.field_types[ start_idx.. ]
    .iter()
    .all( |ty| ty.to_token_stream().to_string() == first_type.to_token_stream().to_string() )
  }
}

/// Returns true when the type is `String` under token-string comparison.
// Fragile: matches only the bare path `String`; fully-qualified paths and type aliases will not match.
fn is_type_string( ty : &syn::Type ) -> bool
{
  ty.to_token_stream().to_string() == quote! { String }.to_string()
}

/// Generates `From1`, `From2`, and `From3` trait implementations for the given field count.
#[ allow( clippy ::similar_names ) ]
fn generate_from_n_impls
(
  context : &VariadicFromContext< '_ >,
  from_fn_args : &[ proc_macro2::Ident ],
) -> proc_macro2::TokenStream
{
  let mut impls = quote! {};
  let name = context.name;
  let num_fields = context.num_fields;
  let ( impl_generics, ty_generics, where_clause ) = context.generics.split_for_impl();

  if num_fields == 1
  {
    let from_fn_arg1 = &from_fn_args[ 0 ];
    let field_type = &context.field_types[ 0 ];
    let constructor = context.constructor( core::slice::from_ref( from_fn_arg1 ) );
    impls.extend( quote!
    {
      impl #impl_generics ::variadic_from::exposed::From1< #field_type > for #name #ty_generics #where_clause
      {
        fn from1( #from_fn_arg1 : #field_type ) -> Self
        {
          Self #constructor
        }
      }
    } );
  }
  else if num_fields == 2
  {
    let from_fn_arg1 = &from_fn_args[ 0 ];
    let from_fn_arg2 = &from_fn_args[ 1 ];
    let field_type1 = &context.field_types[ 0 ];
    let field_type2 = &context.field_types[ 1 ];
    let constructor = context.constructor( &[ from_fn_arg1.clone(), from_fn_arg2.clone() ] );
    impls.extend( quote!
    {
      impl #impl_generics ::variadic_from::exposed::From2< #field_type1, #field_type2 > for #name #ty_generics #where_clause
      {
        fn from2( #from_fn_arg1 : #field_type1, #from_fn_arg2 : #field_type2 ) -> Self
        {
          Self #constructor
        }
      }
    } );
  }
  else if num_fields == 3
  {
    let from_fn_arg1 = &from_fn_args[ 0 ];
    let from_fn_arg2 = &from_fn_args[ 1 ];
    let from_fn_arg3 = &from_fn_args[ 2 ];
    let field_type1 = &context.field_types[ 0 ];
    let field_type2 = &context.field_types[ 1 ];
    let field_type3 = &context.field_types[ 2 ];
    let constructor = context.constructor( &[ from_fn_arg1.clone(), from_fn_arg2.clone(), from_fn_arg3.clone() ] );
    impls.extend( quote!
    {
      impl #impl_generics ::variadic_from::exposed::From3< #field_type1, #field_type2, #field_type3 > for #name #ty_generics #where_clause
      {
        fn from3( #from_fn_arg1 : #field_type1, #from_fn_arg2 : #field_type2, #from_fn_arg3 : #field_type3 ) -> Self
        {
          Self #constructor
        }
      }
    } );
  }

  impls
}

/// Generates `From< T >` (1-field) or `From< ( T1, ..., TN ) >` (multi-field) implementations.
#[ allow( clippy ::similar_names ) ]
fn generate_from_tuple_impl
(
  context : &VariadicFromContext< '_ >,
  from_fn_args : &[ proc_macro2::Ident ],
) -> proc_macro2::TokenStream
{
  let mut impls = quote! {};
  let name = context.name;
  let num_fields = context.num_fields;
  let ( impl_generics, ty_generics, where_clause ) = context.generics.split_for_impl();

  if num_fields == 1
  {
    let from_fn_arg1 = &from_fn_args[ 0 ];
    let field_type = &context.field_types[ 0 ];
    impls.extend( quote!
    {
      impl #impl_generics From< #field_type > for #name #ty_generics #where_clause
      {
        #[ inline( always ) ]
        fn from( #from_fn_arg1 : #field_type ) -> Self
        {
          Self::from1( #from_fn_arg1.clone() )
        }
      }
    } );
  }
  else if num_fields == 2
  {
    let from_fn_arg1 = &from_fn_args[ 0 ];
    let from_fn_arg2 = &from_fn_args[ 1 ];
    let field_type1 = &context.field_types[ 0 ];
    let field_type2 = &context.field_types[ 1 ];
    let tuple_types = quote! { #field_type1, #field_type2 };
    let from_fn_args_pattern = quote! { #from_fn_arg1, #from_fn_arg2 };
    impls.extend( quote!
    {
      impl #impl_generics From< ( #tuple_types ) > for #name #ty_generics #where_clause
      {
        #[ inline( always ) ]
        fn from( ( #from_fn_args_pattern ) : ( #tuple_types ) ) -> Self
        {
          Self::from2( #from_fn_arg1.clone(), #from_fn_arg2.clone() )
        }
      }
    } );
  }
  else if num_fields == 3
  {
    let from_fn_arg1 = &from_fn_args[ 0 ];
    let from_fn_arg2 = &from_fn_args[ 1 ];
    let from_fn_arg3 = &from_fn_args[ 2 ];
    let field_type1 = &context.field_types[ 0 ];
    let field_type2 = &context.field_types[ 1 ];
    let field_type3 = &context.field_types[ 2 ];
    let tuple_types = quote! { #field_type1, #field_type2, #field_type3 };
    let from_fn_args_pattern = quote! { #from_fn_arg1, #from_fn_arg2, #from_fn_arg3 };
    impls.extend( quote!
    {
      impl #impl_generics From< ( #tuple_types ) > for #name #ty_generics #where_clause
      {
        #[ inline( always ) ]
        fn from( ( #from_fn_args_pattern ) : ( #tuple_types ) ) -> Self
        {
          Self::from3( #from_fn_arg1.clone(), #from_fn_arg2.clone(), #from_fn_arg3.clone() )
        }
      }
    } );
  }

  impls
}

/// Generates convenience `From1` and `From2` implementations when field types allow it.
#[ allow( clippy ::similar_names ) ]
#[ allow( clippy ::too_many_lines ) ]
fn generate_convenience_impls
(
  context : &VariadicFromContext< '_ >,
  from_fn_args : &[ proc_macro2::Ident ],
) -> proc_macro2::TokenStream
{
  let mut impls = quote! {};
  let name = context.name;
  let num_fields = context.num_fields;
  let ( impl_generics, ty_generics, where_clause ) = context.generics.split_for_impl();

  if num_fields == 2
  {
    if context.are_all_field_types_identical()
    {
      let from_fn_arg1 = &from_fn_args[ 0 ];
      let field_type = &context.field_types[ 0 ];
      let constructor = context.constructor_uniform( from_fn_arg1 );
      impls.extend( quote!
      {
        impl #impl_generics ::variadic_from::exposed::From1< #field_type > for #name #ty_generics #where_clause
        {
          fn from1( #from_fn_arg1 : #field_type ) -> Self
          {
            Self #constructor
          }
        }
      } );
    }
  }
  else if num_fields == 3
  {
    let from_fn_arg1 = &from_fn_args[ 0 ];
    let from_fn_arg2 = &from_fn_args[ 1 ];
    let field_type1 = &context.field_types[ 0 ];
    let constructor_uniform_all = context.constructor_uniform( from_fn_arg1 );

    if context.are_all_field_types_identical()
    {
      impls.extend( quote!
      {
        impl #impl_generics ::variadic_from::exposed::From1< #field_type1 > for #name #ty_generics #where_clause
        {
          fn from1( #from_fn_arg1 : #field_type1 ) -> Self
          {
            Self #constructor_uniform_all
          }
        }
      } );
    }

    let field_type1 = &context.field_types[ 0 ];
    let field_type2 = &context.field_types[ 1 ];
    let constructor_uniform_last_two = if context.is_tuple_struct
    {
      let arg1 = from_fn_arg1;
      let arg2_for_first_use = if is_type_string( context.field_types[ 1 ] )
      {
        quote! { #from_fn_arg2.clone() }
      }
      else
      {
        quote! { #from_fn_arg2 }
      };
      let arg2_for_second_use = if is_type_string( context.field_types[ 2 ] )
      {
        quote! { #from_fn_arg2.clone() }
      }
      else
      {
        quote! { #from_fn_arg2 }
      };
      quote! { ( #arg1, #arg2_for_first_use, #arg2_for_second_use ) }
    }
    else
    {
      let field_name_or_index1 = &context.field_names_or_indices[ 0 ];
      let field_name_or_index2 = &context.field_names_or_indices[ 1 ];
      let field_name_or_index3 = &context.field_names_or_indices[ 2 ];
      let arg1 = from_fn_arg1;
      let arg2_for_first_use = if is_type_string( context.field_types[ 1 ] )
      {
        quote! { #from_fn_arg2.clone() }
      }
      else
      {
        quote! { #from_fn_arg2 }
      };
      let arg2_for_second_use = if is_type_string( context.field_types[ 2 ] )
      {
        quote! { #from_fn_arg2.clone() }
      }
      else
      {
        quote! { #from_fn_arg2 }
      };
      quote! { { #field_name_or_index1 : #arg1, #field_name_or_index2 : #arg2_for_first_use, #field_name_or_index3 : #arg2_for_second_use } }
    };

    if context.are_field_types_identical_from( 1 )
    {
      impls.extend( quote!
      {
        impl #impl_generics ::variadic_from::exposed::From2< #field_type1, #field_type2 > for #name #ty_generics #where_clause
        {
          fn from2( #from_fn_arg1 : #field_type1, #from_fn_arg2 : #field_type2 ) -> Self
          {
            Self #constructor_uniform_last_two
          }
        }
      } );
    }
  }

  impls
}

/// Derive macro for `VariadicFrom`.
#[ proc_macro_derive( VariadicFrom ) ]
pub fn variadic_from_derive( input : proc_macro::TokenStream ) -> proc_macro::TokenStream
{
  let ast = syn::parse_macro_input!( input as syn::DeriveInput );
  let context = match VariadicFromContext::new( &ast )
  {
    Ok( c ) => c,
    Err( e ) => return e.to_compile_error().into(),
  };

  if context.num_fields == 0 || context.num_fields > 3
  {
    return proc_macro::TokenStream::new();
  }

  let from_fn_args : Vec< proc_macro2::Ident > = ( 0..context.num_fields )
  .map( |i| proc_macro2::Ident::new( &format!( "__a{}", i + 1 ), proc_macro2::Span::call_site() ) )
  .collect();

  let mut impls = quote! {};
  impls.extend( generate_from_n_impls( &context, &from_fn_args ) );
  impls.extend( generate_from_tuple_impl( &context, &from_fn_args ) );
  impls.extend( generate_convenience_impls( &context, &from_fn_args ) );

  quote! { #impls }.into()
}