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
/// Internal namespace.
mod internal
{

  ///
  /// Result with syn::Error.
  ///

  pub type Result< T > = std::result::Result< T, syn::Error >;

  ///
  /// Many items.
  ///

  // #[ allow( dead_code ) ]
  #[ derive( Debug ) ]
  pub struct Items
  (
    pub Vec< syn::Item >,
  );

  impl syn::parse::Parse for Items
  {
    fn parse( input : syn::parse::ParseStream< '_ > ) -> Result< Self >
    {

      let mut items = vec![];
      while !input.is_empty()
      {
        let item : syn::Item = input.parse()?;
        items.push( item );
      }

      Ok( Self( items ) )
    }
  }

  impl quote::ToTokens for Items
  {
    fn to_tokens( &self, tokens : &mut proc_macro2::TokenStream )
    {
      // use quote::ToTokens;
      self.0.iter().for_each( | item | item.to_tokens( tokens ) );
    }
  }

  ///
  /// Macro for diagnostics purpose to print both syntax tree and source code behind it.
  ///
  /// # Sample
  /// ```
  /// use proc_macro_tools::*;
  /// use quote::quote;
  ///
  /// let code = quote!( std::collections::HashMap< i32, i32 > );
  /// let tree_type = syn::parse2::< syn::Type >( code ).unwrap();
  /// tree_print!( tree_type );
  /// ```
  ///

  #[ macro_export ]
  // #[ macro_use ]
  macro_rules! _tree_print
  {
    ( $src : expr ) =>
    {{
      let result = $crate::tree_export_str!( $src );
      println!( "{}", result );
      result
    }};
    ( $( $src : expr ),+ $(,)? ) =>
    {{
      $( $crate::tree_print!( $src ) );+
    }};
  }

  ///
  /// Macro for diagnostics purpose to export both syntax tree and source code behind it into string.
  ///

  #[ macro_export ]
  // #[ macro_use ]
  macro_rules! _tree_export_str
  {
    ( $src : expr ) =>
    {{
      let src2 = &$src;
      format!( "{} : {} :\n{:#?}", stringify!( $src ), quote!{ #src2 }, $src )
    }};
  }

  ///
  /// Macro to generate syn error either with span of a syntax tree element or with default one `proc_macro2::Span::call_site()`.
  ///
  /// # Sample
  /// ```
  /// # use proc_macro_tools::*;
  /// syn_err!( "No attr" );
  /// # ()
  /// ```
  ///

  #[ macro_export ]
  // #[ macro_use ]
  macro_rules! _syn_err
  {

    ( $msg : expr ) =>
    {
      syn::Error::new( proc_macro2::Span::call_site(), $msg )
    };
    ( _, $msg : expr ) =>
    {
      syn::Error::new( proc_macro2::Span::call_site(), $msg )
    };
    ( $span : expr, $msg : expr ) =>
    {
      // syn::Error::new( ( $span ).span(), $msg )
      syn::Error::new( syn::spanned::Spanned::span( &( $span ) ), $msg )
    };
    ( $span : expr, $msg : expr, $( $arg : expr ),+ ) =>
    {
      // syn::Error::new( ( $span ).span(), format!( $msg, $( $arg ),+ ) )
      syn::Error::new( syn::spanned::Spanned::span( &( $span ) ), format!( $msg, $( $arg ),+ ) )
    };
    ( _, $msg : expr, $( $arg : expr ),+ ) =>
    {
      syn::Error::new( proc_macro2::Span::call_site(), format!( $msg, $( $arg ),+ ) )
    };

  }

  ///
  /// Kind of container.
  ///

  #[derive( Debug, PartialEq, Copy, Clone )]
  pub enum ContainerKind
  {
    /// Not a container.
    No,
    /// Vector-like.
    Vector,
    /// Hash map-like.
    HashMap,
    /// Hash set-like.
    HashSet,
  }

  /// Return kind of container specified by type.
  ///
  /// Good to verify `alloc::vec::Vec< i32 >` is vector.
  /// Good to verify `std::collections::HashMap< i32, i32 >` is hash map.
  ///
  /// # Sample
  /// ```
  /// use proc_macro_tools::*;
  /// use quote::quote;
  ///
  /// let code = quote!( std::collections::HashMap< i32, i32 > );
  /// let tree_type = syn::parse2::< syn::Type >( code ).unwrap();
  /// let kind = type_container_kind( &tree_type );
  /// assert_eq!( kind, ContainerKind::HashMap );
  /// ```

  pub fn type_container_kind( ty : &syn::Type ) -> ContainerKind
  {

    if let syn::Type::Path( path ) = ty
    {
      let last = &path.path.segments.last();
      if last.is_none()
      {
        return ContainerKind::No
      }
      match last.unwrap().ident.to_string().as_ref()
      {
        "Vec" => { return ContainerKind::Vector }
        "HashMap" => { return ContainerKind::HashMap }
        "HashSet" => { return ContainerKind::HashSet }
        _ => { return ContainerKind::No }
      }
    }
    ContainerKind::No
  }

  /// Return kind of container specified by type. Unlike [type_container_kind] it also understand optional types.
  ///
  /// Good to verify `Option< alloc::vec::Vec< i32 > >` is optional vector.
  ///
  /// # Sample
  /// ```
  /// use proc_macro_tools::*;
  /// use quote::quote;
  ///
  /// let code = quote!( Option< std::collections::HashMap< i32, i32 > > );
  /// let tree_type = syn::parse2::< syn::Type >( code ).unwrap();
  /// let ( kind, optional ) = type_optional_container_kind( &tree_type );
  /// assert_eq!( kind, ContainerKind::HashMap );
  /// assert_eq!( optional, true );
  /// ```

  pub fn type_optional_container_kind( ty : &syn::Type ) -> ( ContainerKind, bool )
  {

    // use inspect_type::*;

    if type_rightmost( ty ) == Some( "Option".to_string() )
    {
      let ty2 = type_parameters( ty, 0 ..= 0 ).first().map( | e | *e );
      // inspect_type::inspect_type_of!( ty2 );
      if ty2.is_none()
      {
        return ( ContainerKind::No, false )
      }
      let ty2 = ty2.unwrap();
      return ( type_container_kind( ty2 ), true );
    }

    return ( type_container_kind( ty ), false );
  }

  /// Check is the rightmost item of path refering a type is specified type.
  ///
  /// Good to verify `core::option::Option< i32 >` is optional.
  /// Good to verify `alloc::vec::Vec< i32 >` is vector.
  ///
  /// # Sample
  /// ```
  /// use proc_macro_tools::*;
  /// use quote::quote;
  ///
  /// let code = quote!( core::option::Option< i32 > );
  /// let tree_type = syn::parse2::< syn::Type >( code ).unwrap();
  /// let got = type_rightmost( &tree_type );
  /// assert_eq!( got, Some( "Option".to_string() ) );
  /// ```

  pub fn type_rightmost( ty : &syn::Type ) -> Option< String >
  {
    if let syn::Type::Path( path ) = ty
    {
      let last = &path.path.segments.last();
      if last.is_none()
      {
        return None;
      }
      return Some( last.unwrap().ident.to_string() );
    }
    None
  }

  use winterval::*;

  /// Return the specified number of parameters of the type.
  ///
  /// Good to getting `i32` from `core::option::Option< i32 >` or `alloc::vec::Vec< i32 >`
  ///
  /// # Sample
  /// ```
  /// use proc_macro_tools::*;
  /// use quote::quote;
  ///
  /// let code = quote!( core::option::Option< i8, i16, i32, i64 > );
  /// let tree_type = syn::parse2::< syn::Type >( code ).unwrap();
  /// let got = type_parameters( &tree_type, 0..=2 );
  /// got.iter().for_each( | e | println!( "{}", quote!( #e ) ) );
  /// // < i8
  /// // < i16
  /// // < i32
  /// ```

  pub fn type_parameters< R >( ty : &syn::Type, range : R ) -> Vec< &syn::Type >
  where
    R : std::convert::Into< Interval >
  {
    let range = range.into();
    if let syn::Type::Path( syn::TypePath{ path : syn::Path { ref segments, .. }, .. } ) = ty
    {
      let last = &segments.last();
      if last.is_none()
      {
        return vec![ &ty ]
      }
      let args = &last.unwrap().arguments;
      if let syn::PathArguments::AngleBracketed( ref args2 ) = args
      {
        let args3 = &args2.args;
        let selected : Vec< &syn::Type > = args3
        .iter()
        .skip_while( | e | if let syn::GenericArgument::Type( _ ) = e { false } else { true } )
        .skip( range.first().try_into().unwrap() )
        .take( range.len().try_into().unwrap() )
        .map( | e | if let syn::GenericArgument::Type( ty ) = e { ty } else { unreachable!( "Expects Type" ) } )
        .collect();
        return selected;
      }
    }
    vec![ &ty ]
  }

  ///
  /// For attribute like `#[former( default = 31 )]` return key `default` and value `31`,
  /// as well as syn::Meta as the last element of result tuple.
  ///
  /// # Sample
  /// ``` ignore
  /// let ( key, val, meta ) = attr_pair_single( &attr )?;
  /// ```

  pub fn attr_pair_single( attr : &syn::Attribute ) -> Result< ( String, syn::Lit, syn::Meta ) >
  {
    use syn::spanned::Spanned;
    let meta = attr.parse_meta()?;

    let ( key, val );
    match meta
    {
      syn::Meta::List( ref meta_list ) =>
      match meta_list.nested.first()
      {
        Some( nested_meta ) => match nested_meta
        {
          syn::NestedMeta::Meta( meta2 ) => match meta2
          {
            syn::Meta::NameValue( name_value ) => // match &name_value.lit
            {
              if meta_list.nested.len() != 1
              {
                return Err( syn::Error::new( attr.span(), format!( "Expected single element of the list, but got {}", meta_list.nested.len() ) ) );
              }
              key = name_value.path.get_ident().unwrap().to_string();
              val = name_value.lit.clone();
            },
            _ => return Err( syn::Error::new( attr.span(), "Unknown format of attribute, expected syn::Meta::NameValue( name_value )" ) ),
          },
          _ => return Err( syn::Error::new( attr.span(), "Unknown format of attribute, expected syn::NestedMeta::Meta( meta2 )" ) ),
        },
        _ => return Err( syn::Error::new( attr.span(), "Unknown format of attribute, expected Some( nested_meta )" ) ),
      },
      _ => return Err( syn::Error::new( attr.span(), "Unknown format of attribute, expected syn::Meta::List( meta_list )" ) ),
    };

    Ok( ( key, val, meta ) )
  }

  pub use _tree_print;
  pub use _tree_export_str;
  pub use _syn_err;

}

// ///
// /// Canonize path and return it in string format.
// ///
//
// pub fn path_of( syn_path : &syn::Path ) -> String
// {
//   // use quote::*;
//   use syn::*;
//   let result : String = format!( "{}", syn_path.to_token_stream() );
//   // let result : String = format!( "{}", quote!{ #syn_path } );
//   result
// }

//

// don't delete!
// good example of overloading to reuse
//
// pub use syn::spanned::Spanned;
//
// /// Trait to implement method span() for those structures which [module::syn](https://docs.rs/syn/latest/syn/spanned/index.html) do not have it implemented.
//
// pub trait Spanned2
// {
//   /// Returns a Span covering the complete contents of this syntax tree node, or Span::call_site() if this node is empty.
//   fn span2( &self ) -> proc_macro2::Span;
// }
//
// //
//
// impl Spanned2 for syn::Data
// {
//   fn span2( &self ) -> proc_macro2::Span
//   {
//     // data_fields_of( &self ).span()
//     match self
//     {
//       syn::Data::Struct( syn::DataStruct { ref fields, .. } ) => fields.span(),
//       syn::Data::Enum( syn::DataEnum { ref variants, .. } ) => variants.span(),
//       syn::Data::Union( syn::DataUnion { ref fields, .. } ) => fields.span(),
//     }
//   }
// }
//
// impl< T : Spanned2 > Spanned2 for &T
// {
//   fn span2( &self ) -> proc_macro2::Span
//   {
//     ( *self ).span2()
//   }
// }
//
// //
//
// #[ doc( hidden ) ]
// pub struct Data< 'a, T >( &'a T );
//
// #[ doc( hidden ) ]
// pub trait Span1
// {
//   fn act( self ) -> proc_macro2::Span;
// }
//
// impl< 'a, T > Span1
// for Data< 'a, T >
// where T : syn::spanned::Spanned,
// {
//   fn act( self ) -> proc_macro2::Span
//   {
//     self.0.span()
//   }
// }
//
//
// #[ doc( hidden ) ]
// pub trait Span2
// {
//   fn act( self ) -> proc_macro2::Span;
// }
//
// impl< 'a, T > Span2
// for Data< 'a, T >
// where T : Spanned2,
// {
//   fn act( self ) -> proc_macro2::Span
//   {
//     self.0.span2()
//   }
// }
//
// #[ doc( hidden ) ]
// pub fn _span_of< T : Sized >( src : &T ) -> Data< T >
// {
//   Data( src )
// }
//
// // fn span2_of< T : Sized >( src : &T )
// // {
// //   _span_of( src ).act()
// // }
//
// /// Returns a Span covering the complete contents of this syntax tree node, or Span::call_site() if this node is empty.
//
// #[ macro_export ]
// macro_rules! span_of
// {
//   ( $src : expr ) =>
//   {
//     $crate::_span_of( &$src ).act()
//   }
// }
//
// /// Returns a Span covering the complete contents of this syntax tree node, or Span::call_site() if this node is empty.
// ///
// /// Works only for items for which span is not implemented in [module::syn](https://docs.rs/syn/latest/syn/spanned/index.html). For other use macro [`span_of!`](span_of!).
//
// pub fn span_of< Src : Spanned2 >( src : &Src ) -> proc_macro2::Span
// {
//   src.span2()
// }
//

// =

// repeat!{ ( pub use internal::, ) ( ; ) ( ; )
// {
//
//   ContainerKind
//
//   type_container_kind
//   type_optional_container_kind
//   type_rightmost
//   type_parameters
//   attr_pair_single
//
// }}

// --

// mod_expose!{
// {
//
//   _tree_print as tree_print,
//   _tree_export_str as tree_export_str,
//   _syn_err as syn_err,
//
//   ContainerKind,
//
//   type_container_kind,
//   type_optional_container_kind,
//   type_rightmost,
//   type_parameters,
//   attr_pair_single,
//
// }};

/// Exposed namespace of the module.
pub mod exposed
{
  pub use super::prelude::*;
  use super::internal as i;

  pub use i::Result;
  pub use i::Items;

  pub use i::ContainerKind;
  pub use i::type_container_kind;
  pub use i::type_optional_container_kind;
  pub use i::type_rightmost;
  pub use i::type_parameters;
  pub use i::attr_pair_single;

}

pub use exposed::*;

/// Prelude to use: `use wtools::prelude::*`.
pub mod prelude
{
  use super::internal as i;

  pub use i::_tree_print as tree_print;
  pub use i::_tree_export_str as tree_export_str;
  pub use i::_syn_err as syn_err;

}