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
//!
//! Parse structures, like `struct { a : i32 }`.
//!

/// Internal namespace.
mod private
{
  use crate::*;

  /// Enum to encapsulate either a field from a struct or a variant from an enum.
  #[ derive( Debug, PartialEq, Clone ) ]
  pub enum FieldOrVariant< 'a >
  {
    /// Represents a field within a struct or union.
    Field( &'a syn::Field ),
    /// Represents a variant within an enum.
    Variant( &'a syn::Variant ),
  }

  impl< 'a > Copy for FieldOrVariant< 'a >
  {
  }

  impl< 'a > From< &'a syn::Field > for FieldOrVariant< 'a >
  {
    fn from( field : &'a syn::Field ) -> Self
    {
      FieldOrVariant::Field( field )
    }
  }

  impl< 'a > From< &'a syn::Variant > for FieldOrVariant< 'a >
  {
    fn from( variant : &'a syn::Variant ) -> Self
    {
      FieldOrVariant::Variant( variant )
    }
  }

  impl quote::ToTokens for FieldOrVariant< '_ >
  {
    fn to_tokens( &self, tokens : &mut proc_macro2::TokenStream )
    {
      match self
      {
        FieldOrVariant::Field( item ) =>
        {
          item.to_tokens( tokens );
        },
        FieldOrVariant::Variant( item ) =>
        {
          item.to_tokens( tokens );
        },
      }
    }
  }

  impl< 'a > FieldOrVariant< 'a >
  {

    /// Returns a reference to the attributes of the item.
    pub fn attrs( &self ) -> &Vec< syn::Attribute >
    {
      match self
      {
        FieldOrVariant::Field( e ) => &e.attrs,
        FieldOrVariant::Variant( e ) => &e.attrs,
      }
    }

    /// Returns a reference to the visibility of the item.
    pub fn vis( &self ) -> Option< &syn::Visibility >
    {
      match self
      {
        FieldOrVariant::Field( e ) => Some( &e.vis ),
        FieldOrVariant::Variant( _ ) => None,
      }
    }

    /// Returns a reference to the mutability of the item.
    pub fn mutability( &self ) -> Option< &syn::FieldMutability >
    {
      match self
      {
        FieldOrVariant::Field( e ) => Some( &e.mutability ),
        FieldOrVariant::Variant( _ ) => None,
      }
    }

    /// Returns a reference to the identifier of the item.
    pub fn ident( &self ) -> Option< &syn::Ident >
    {
      match self
      {
        FieldOrVariant::Field( e ) => e.ident.as_ref(),
        FieldOrVariant::Variant( e ) => Some( &e.ident ),
      }
    }

    /// Returns an iterator over elements of the item.
    pub fn typ( &self ) -> Option< &syn::Type >
    {
      match self
      {
        FieldOrVariant::Field( e ) =>
        {
          Some( &e.ty )
        },
        FieldOrVariant::Variant( _e ) =>
        {
          None
        },
      }
    }

    /// Returns a reference to the fields of the item.
    pub fn fields( &self ) -> Option< &syn::Fields >
    {
      match self
      {
        FieldOrVariant::Field( _ ) => None,
        FieldOrVariant::Variant( e ) => Some( &e.fields ),
      }
    }

    /// Returns a reference to the discriminant of the item.
    pub fn discriminant( &self ) -> Option< &( syn::token::Eq, syn::Expr ) >
    {
      match self
      {
        FieldOrVariant::Field( _ ) => None,
        FieldOrVariant::Variant( e ) => e.discriminant.as_ref(),
      }
    }

  }

  /// Represents various struct-like constructs in Rust code.
  ///
  /// This enum enables differentiation among unit types, structs, and enums, allowing
  /// for syntactic analysis and manipulation within macros. `StructLike` is designed to be
  /// used in macro contexts where behaviors may vary based on the struct-like type being processed.
  ///
  /// Variants:
  /// - `Unit`: Represents unit structs, which are types without any fields or data. Useful in scenarios where
  ///   a type needs to exist but does not hold any data itself, typically used for type-safe markers.
  /// - `Struct`: Represents regular Rust structs that contain fields. This variant is used to handle data structures
  ///   that hold multiple related data pieces together in a named format.
  /// - `Enum`: Represents enums in Rust, which are types that can hold one of multiple possible variants. This is particularly
  ///   useful for type-safe state or option handling without the use of external discriminators.
  ///
  #[ derive( Debug, PartialEq ) ]
  pub enum StructLike
  {
    /// A unit struct with no fields.
    Unit( syn::ItemStruct ),
    /// A typical Rust struct with named fields.
    Struct( syn::ItemStruct ),
    /// A Rust enum, which can be one of several defined variants.
    Enum( syn::ItemEnum ),
  }

  impl From< syn::ItemStruct > for StructLike
  {
    fn from( item_struct : syn::ItemStruct ) -> Self
    {
      if item_struct.fields.is_empty()
      {
        StructLike::Unit( item_struct )
      }
      else
      {
        StructLike::Struct( item_struct )
      }
    }
  }

  impl From< syn::ItemEnum > for StructLike
  {
    fn from( item_enum : syn::ItemEnum ) -> Self
    {
      StructLike::Enum( item_enum )
    }
  }

  impl syn::parse::Parse for StructLike
  {
    fn parse( input : syn::parse::ParseStream< '_ > ) -> syn::Result< Self >
    {
      use syn::{ ItemStruct, ItemEnum, Visibility, Attribute };

      // Parse attributes
      let attributes : Vec< Attribute > = input.call( Attribute::parse_outer )?;
      // Parse visibility
      let visibility : Visibility = input.parse().unwrap_or( syn::Visibility::Inherited );

      // Fork input stream to handle struct/enum keyword without consuming
      let lookahead = input.lookahead1();
      if lookahead.peek( syn::Token![ struct ] )
      {
        // Parse ItemStruct
        let mut item_struct : ItemStruct = input.parse()?;
        item_struct.vis = visibility;
        item_struct.attrs = attributes.into();
        if item_struct.fields.is_empty()
        {
          Ok( StructLike::Unit( item_struct ) )
        }
        else
        {
          Ok( StructLike::Struct( item_struct ) )
        }
      }
      else if lookahead.peek( syn::Token![ enum ] )
      {
        // Parse ItemEnum
        let mut item_enum : ItemEnum = input.parse()?;
        item_enum.vis = visibility;
        item_enum.attrs = attributes.into();
        Ok( StructLike::Enum( item_enum ) )
      }
      else
      {
        Err( lookahead.error() )
      }
    }
  }

  impl quote::ToTokens for StructLike
  {
    fn to_tokens( &self, tokens : &mut proc_macro2::TokenStream )
    {
      match self
      {
        StructLike::Unit( item ) | StructLike::Struct( item ) =>
        {
          item.to_tokens( tokens );
        },
        StructLike::Enum( item ) =>
        {
          item.to_tokens( tokens );
        },
      }
    }
  }

  impl StructLike
  {


    /// Returns an iterator over elements of the item.
    // pub fn elements< 'a >( &'a self ) -> impl IterTrait< 'a, FieldOrVariant< 'a > > + 'a
    pub fn elements< 'a >( &'a self ) -> BoxedIter< 'a, FieldOrVariant< 'a > >
    {
      match self
      {
        StructLike::Unit( _ ) =>
        {
          let empty : Vec< FieldOrVariant< 'a > > = vec![];
          Box::new( empty.into_iter() )
        },
        StructLike::Struct( item ) =>
        {
          let fields = item.fields.iter().map( FieldOrVariant::from );
          Box::new( fields )
        },
        StructLike::Enum( item ) =>
        {
          let variants = item.variants.iter().map( FieldOrVariant::from );
          Box::new( variants )
        },
      }
    }

    /// Returns an iterator over elements of the item.
    pub fn attrs( &self ) -> &Vec< syn::Attribute >
    {
      match self
      {
        StructLike::Unit( item ) =>
        {
          &item.attrs
        },
        StructLike::Struct( item ) =>
        {
          &item.attrs
        },
        StructLike::Enum( item ) =>
        {
          &item.attrs
        },
      }
    }

    /// Returns an iterator over elements of the item.
    pub fn vis( &self ) -> &syn::Visibility
    {
      match self
      {
        StructLike::Unit( item ) =>
        {
          &item.vis
        },
        StructLike::Struct( item ) =>
        {
          &item.vis
        },
        StructLike::Enum( item ) =>
        {
          &item.vis
        },
      }
    }

    /// Returns an iterator over elements of the item.
    pub fn ident( &self ) -> &syn::Ident
    {
      match self
      {
        StructLike::Unit( item ) =>
        {
          &item.ident
        },
        StructLike::Struct( item ) =>
        {
          &item.ident
        },
        StructLike::Enum( item ) =>
        {
          &item.ident
        },
      }
    }

    /// Returns an iterator over elements of the item.
    pub fn generics( &self ) -> &syn::Generics
    {
      match self
      {
        StructLike::Unit( item ) =>
        {
          &item.generics
        },
        StructLike::Struct( item ) =>
        {
          &item.generics
        },
        StructLike::Enum( item ) =>
        {
          &item.generics
        },
      }
    }

    /// Returns an iterator over fields of the item.
    // pub fn fields< 'a >( &'a self ) -> impl IterTrait< 'a, &'a syn::Field >
    pub fn fields< 'a >( &'a self ) -> BoxedIter< 'a, &'a syn::Field >
    {
      let result : BoxedIter< 'a, &'a syn::Field > = match self
      {
        StructLike::Unit( _item ) =>
        {
          Box::new( std::iter::empty() )
        },
        StructLike::Struct( item ) =>
        {
          Box::new( item.fields.iter() )
        },
        StructLike::Enum( _item ) =>
        {
          Box::new( std::iter::empty() )
        },
      };
      result
    }

    /// Extracts the name of each field.
    // pub fn field_names< 'a >( &'a self ) -> Option< impl IterTrait< 'a, &'a syn::Ident > + '_ >
    pub fn field_names< 'a >( &'a self ) -> Option< BoxedIter< 'a, &'a syn::Ident >>
    {
      match self
      {
        StructLike::Unit( item ) =>
        {
          item_struct::field_names( item )
        },
        StructLike::Struct( item ) =>
        {
          item_struct::field_names( item )
        },
        StructLike::Enum( _item ) =>
        {
          let iter = Box::new( self.fields().map( | field | field.ident.as_ref().unwrap() ) );
          Some( iter )
        },
      }
    }

    /// Extracts the type of each field.
    pub fn field_types<'a>( &'a self )
    -> BoxedIter< 'a, &'a syn::Type >
    // -> std::iter::Map
    // <
    //   std::boxed::Box< dyn _IterTrait< '_, &syn::Field > + 'a >,
    //   impl FnMut( &'a syn::Field ) -> &'a syn::Type + 'a,
    // >
    {
      Box::new( self.fields().map( move | field | &field.ty ) )
    }

    /// Extracts the name of each field.
    // pub fn field_attrs< 'a >( &'a self ) -> impl IterTrait< 'a, &'a Vec< syn::Attribute > >
    pub fn field_attrs<'a>( &'a self )
    -> BoxedIter< 'a, &'a Vec< syn::Attribute > >
    // -> std::iter::Map
    // <
    //   std::boxed::Box< dyn _IterTrait< '_, &syn::Field > + 'a >,
    //   impl FnMut( &'a syn::Field ) -> &'a Vec< syn::Attribute > + 'a,
    // >
    {
      Box::new( self.fields().map( | field | &field.attrs ) )
    }

    /// Extract the first field.
    pub fn first_field( &self ) -> Option< &syn::Field >
    {
      self.fields().next()
      // .ok_or( syn_err!( self.span(), "Expects at least one field" ) )
    }

  }

  //

}

#[ doc( inline ) ]
#[ allow( unused_imports ) ]
pub use own::*;

/// Own namespace of the module.
#[ allow( unused_imports ) ]
pub mod own
{
  use super::*;
  #[ doc( inline ) ]
  pub use orphan::*;
  #[ doc( inline ) ]
  pub use private::
  {
    StructLike,
    FieldOrVariant,
  };
}

/// Orphan namespace of the module.
#[ allow( unused_imports ) ]
pub mod orphan
{
  use super::*;
  #[ doc( inline ) ]
  pub use exposed::*;
}

/// Exposed namespace of the module.
#[ allow( unused_imports ) ]
pub mod exposed
{
  use super::*;
  pub use super::super::struct_like;

  #[ doc( inline ) ]
  pub use prelude::*;
}

/// Prelude to use essentials: `use my_module::prelude::*`.
#[ allow( unused_imports ) ]
pub mod prelude
{
  use super::*;
}