macro_tools 0.85.0

Tools for writing procedural macroses.
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
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
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
//!
//! Attributes analyzys and manipulation.
//!

/// Define a private namespace for all its items.
mod private 
{

  use crate :: *;
  use crate ::qt;

  /// Checks if the given iterator of attributes contains an attribute named `debug`.
  ///
  /// This function iterates over an input sequence of `syn ::Attribute`, typically associated with a struct,
  /// enum, or other item in a Rust Abstract Syntax Tree ( AST ), and determines whether any of the attributes
  /// is exactly named `debug`.
  ///
  /// # Parameters
  /// - `attrs` : An iterator over `syn ::Attribute`. This could be obtained from parsing Rust code
  ///   with the `syn` crate, where the iterator represents attributes applied to a Rust item ( like a struct or function ).
  ///
  /// # Returns
  /// - `Ok( true )` if the `debug` attribute is present.
  /// - `Ok( false )` if the `debug` attribute is not found.
  /// - `Err( syn ::Error )` if an unknown or improperly formatted attribute is encountered.
  ///
  /// # Example
  ///
  /// Suppose you have the following struct definition in a procedural macro input :
  ///
  /// ```rust, ignore
  /// #[ derive( SomeDerive ) ]
  /// #[ debug ]
  /// struct MyStruct
  /// {
  ///   field: i32,
  /// }
  /// ```
  ///
  /// You can use `has_debug` to check for the presence of the `debug` attribute :
  ///
  /// ```rust
  /// use macro_tools ::exposed :: *;
  ///
  /// // Example struct attribute
  /// let attrs: Vec< syn ::Attribute > = vec![ syn ::parse_quote!( #[ debug ] ) ];
  ///
  /// // Checking for 'debug' attribute
  /// let contains_debug = attr ::has_debug( ( &attrs ).into_iter() ).unwrap();
  ///
  /// assert!( contains_debug, "Expected to find 'debug' attribute" );
  /// ```
  /// # Errors
  /// qqq: doc
  pub fn has_debug< 'a >(attrs: impl Iterator< Item = &'a syn ::Attribute >) -> syn ::Result< bool >
  {
  for attr in attrs 
  {
   if let Some(ident) = attr.path().get_ident() 
   {
  let ident_string = format!("{ident}");
  if ident_string == "debug" 
  {
   return Ok(true);
 }
 } else {
  return_syn_err!("Unknown structure attribute: \n{}", qt! { attr });
 }
 }
  Ok(false)
 }

  /// Checks if the given attribute name is a standard Rust attribute.
  ///
  /// Standard Rust attributes are those which are recognized and processed
  /// directly by the Rust compiler. They influence various aspects of compilation,
  /// including but not limited to conditional compilation, optimization hints,
  /// code visibility, and procedural macro behavior.
  ///
  /// This function is useful when developing tools that need to interact with or
  /// understand the significance of specific attributes in Rust source code, such
  /// as linters, code analyzers, or procedural macros.
  ///
  /// This function does not cover all possible attributes but includes many of the
  /// common ones that are relevant to most Rust projects. Developers are encouraged
  /// to update this function as needed to suit more specialized needs, especially
  /// when dealing with nightly-only compiler attributes or deprecated ones.
  ///
  /// # Parameters
  /// - `attr_name` : A string slice that holds the name of the attribute to check.
  ///
  /// # Returns
  /// Returns `true` if `attr_name` is a recognized standard Rust attribute. Otherwise,
  /// returns `false`.
  ///
  /// # Examples
  ///
  /// Standard attributes :
  ///
  /// ```
  /// assert_eq!( macro_tools ::attr ::is_standard( "cfg" ), true );
  /// assert_eq!( macro_tools ::attr ::is_standard( "inline" ), true );
  /// assert_eq!( macro_tools ::attr ::is_standard( "derive" ), true );
  /// ```
  ///
  /// Non-standard or custom attributes :
  ///
  /// ```
  /// assert_eq!( macro_tools ::attr ::is_standard( "custom_attr" ), false );
  /// assert_eq!( macro_tools ::attr ::is_standard( "my_attribute" ), false );
  /// ```
  ///
  #[ must_use ]
  #[ allow( clippy ::match_same_arms ) ]
  pub fn is_standard(attr_name: &str) -> bool
  {
  match attr_name 
  {
   // Conditional compilation
   "cfg" | "cfg_attr" => true,

   // Compiler instructions and optimizations
   "inline" | "repr" | "derive" | "allow" | "warn" | "deny" | "forbid" => true,

   // Testing attributes
   "test" | "bench" => true,

   // Documentation attributes
   "doc" => true,

   // Visibility and accessibility
   "pub" => true, // This would typically need context to be accurate

   // Safety and ABI
   "unsafe" | "no_mangle" | "extern" => true,

   // Module and Crate configuration
   "path" | "macro_use" | "crate_type" | "crate_name" => true,

   // Linking
   "link" | "link_name" | "link_section" => true,

   // Usage warnings
   "must_use" => true,

   // Other attributes
   "cold" | "export_name" | "global_allocator" => true,

   // Module handling
   "used" | "unused" => true,

   // Procedural macros and hygiene
   "proc_macro" | "proc_macro_derive" | "proc_macro_attribute" => true,

   // Stability attributes
   "stable"
   | "unstable"
   | "rustc_const_unstable"
   | "rustc_const_stable"
   | "rustc_diagnostic_item"
   | "rustc_deprecated"
   | "rustc_legacy_const_generics" => true,

   // Special compiler attributes
   "feature" | "non_exhaustive" => true,

   // Future compatibility
   "rustc_paren_sugar" | "rustc_insignificant_dtor" => true,

   // Type system extensions
   "opaque" => true,

   // Miscellaneous
   "track_caller" => true,

   // Default case
   _ => false,
 }
 }

  /// Checks if the given iterator of attributes contains an attribute named `deref`.
  ///
  /// This function iterates over an input sequence of `syn ::Attribute`, typically associated with a struct,
  /// enum, or other item in a Rust Abstract Syntax Tree ( AST ), and determines whether any of the attributes
  /// is exactly named `deref`.
  ///
  /// # Parameters
  /// - `attrs` : An iterator over `syn ::Attribute`. This could be obtained from parsing Rust code
  ///   with the `syn` crate, where the iterator represents attributes applied to a Rust item ( like a struct or function ).
  ///
  /// # Returns
  /// - `Ok( true )` if the `deref` attribute is present.
  /// - `Ok( false )` if the `deref` attribute is not found.
  /// - `Err( syn ::Error )` if an unknown or improperly formatted attribute is encountered.
  ///
  /// # Errors
  /// qqq: doc
  pub fn has_deref< 'a >(attrs: impl Iterator< Item = &'a syn ::Attribute >) -> syn ::Result< bool >
  {
  for attr in attrs 
  {
   if let Some(ident) = attr.path().get_ident() 
   {
  let ident_string = format!("{ident}");
  if ident_string == "deref" 
  {
   return Ok(true);
 }
 } else {
  return_syn_err!("Unknown structure attribute: \n{}", qt! { attr });
 }
 }
  Ok(false)
 }

  /// Checks if the given iterator of attributes contains an attribute named `deref_mut`.
  ///
  /// This function iterates over an input sequence of `syn ::Attribute`, typically associated with a struct,
  /// enum, or other item in a Rust Abstract Syntax Tree ( AST ), and determines whether any of the attributes
  /// is exactly named `deref_mut`.
  ///
  /// # Parameters
  /// - `attrs` : An iterator over `syn ::Attribute`. This could be obtained from parsing Rust code
  ///   with the `syn` crate, where the iterator represents attributes applied to a Rust item ( like a struct or function ).
  ///
  /// # Returns
  /// - `Ok( true )` if the `deref_mut` attribute is present.
  /// - `Ok( false )` if the `deref_mut` attribute is not found.
  /// - `Err( syn ::Error )` if an unknown or improperly formatted attribute is encountered.
  ///
  /// # Errors
  /// qqq: doc
  pub fn has_deref_mut< 'a >(attrs: impl Iterator< Item = &'a syn ::Attribute >) -> syn ::Result< bool >
  {
  for attr in attrs 
  {
   if let Some(ident) = attr.path().get_ident() 
   {
  let ident_string = format!("{ident}");
  if ident_string == "deref_mut" 
  {
   return Ok(true);
 }
 } else {
  return_syn_err!("Unknown structure attribute: \n{}", qt! { attr });
 }
 }
  Ok(false)
 }

  /// Checks if the given iterator of attributes contains an attribute named `from`.
  ///
  /// This function iterates over an input sequence of `syn ::Attribute`, typically associated with a struct,
  /// enum, or other item in a Rust Abstract Syntax Tree ( AST ), and determines whether any of the attributes
  /// is exactly named `from`.
  ///
  /// # Parameters
  /// - `attrs` : An iterator over `syn ::Attribute`. This could be obtained from parsing Rust code
  ///   with the `syn` crate, where the iterator represents attributes applied to a Rust item ( like a struct or function ).
  ///
  /// # Returns
  /// - `Ok( true )` if the `from` attribute is present.
  /// - `Ok( false )` if the `from` attribute is not found.
  /// - `Err( syn ::Error )` if an unknown or improperly formatted attribute is encountered.
  ///
  /// # Errors
  /// qqq: doc
  pub fn has_from< 'a >(attrs: impl Iterator< Item = &'a syn ::Attribute >) -> syn ::Result< bool >
  {
  for attr in attrs 
  {
   if let Some(ident) = attr.path().get_ident() 
   {
  let ident_string = format!("{ident}");
  if ident_string == "from"
  {
   return Ok(true);
 }
 } else {
  return_syn_err!("Unknown structure attribute: \n{}", qt! { attr });
 }
 }
  Ok(false)
 }

  /// Checks if the given iterator of attributes contains an attribute named `index_mut`.
  ///
  /// This function iterates over an input sequence of `syn ::Attribute`, typically associated with a struct,
  /// enum, or other item in a Rust Abstract Syntax Tree ( AST ), and determines whether any of the attributes
  /// is exactly named `index_mut`.
  ///
  /// # Parameters
  /// - `attrs` : An iterator over `syn ::Attribute`. This could be obtained from parsing Rust code
  ///   with the `syn` crate, where the iterator represents attributes applied to a Rust item ( like a struct or function ).
  ///
  /// # Returns
  /// - `Ok( true )` if the `index_mut` attribute is present.
  /// - `Ok( false )` if the `index_mut` attribute is not found.
  /// - `Err( syn ::Error )` if an unknown or improperly formatted attribute is encountered.
  ///
  /// # Errors
  /// qqq: doc
  pub fn has_index_mut< 'a >(attrs: impl Iterator< Item = &'a syn ::Attribute >) -> syn ::Result< bool >
  {
  for attr in attrs 
  {
   if let Some(ident) = attr.path().get_ident() 
   {
  let ident_string = format!("{ident}");
  if ident_string == "index_mut"
  {
   return Ok(true);
 }
 } else {
  return_syn_err!("Unknown structure attribute: \n{}", qt! { attr });
 }
 }
  Ok(false)
 }
  /// Checks if the given iterator of attributes contains an attribute named `as_mut`.
  ///
  /// This function iterates over an input sequence of `syn ::Attribute`, typically associated with a struct,
  /// enum, or other item in a Rust Abstract Syntax Tree ( AST ), and determines whether any of the attributes
  /// is exactly named `as_mut`.
  ///
  /// # Parameters
  /// - `attrs` : An iterator over `syn ::Attribute`. This could be obtained from parsing Rust code
  ///   with the `syn` crate, where the iterator represents attributes applied to a Rust item ( like a struct or function ).
  ///
  /// # Returns
  /// - `Ok( true )` if the `as_mut` attribute is present.
  /// - `Ok( false )` if the `as_mut` attribute is not found.
  /// - `Err( syn ::Error )` if an unknown or improperly formatted attribute is encountered.
  ///
  /// # Errors
  /// qqq: doc
  pub fn has_as_mut< 'a >(attrs: impl Iterator< Item = &'a syn ::Attribute >) -> syn ::Result< bool >
  {
  for attr in attrs 
  {
   if let Some(ident) = attr.path().get_ident() 
   {
  let ident_string = format!("{ident}");
  if ident_string == "as_mut"
  {
   return Ok(true);
 }
 } else {
  return_syn_err!("Unknown structure attribute: \n{}", qt! { attr });
 }
 }
  Ok(false)
 }
  ///
  /// Attribute which is inner.
  ///
  /// For example: `// #![ deny( missing_docs ) ]`.
  ///
  #[ derive( Debug, PartialEq, Eq, Clone, Default ) ]
  pub struct AttributesInner(pub Vec< syn ::Attribute >);

  impl From< Vec< syn ::Attribute > > for AttributesInner 
  {
  #[ inline( always ) ]
  fn from(src: Vec< syn ::Attribute >) -> Self 
  {
   Self(src)
 }
 }

  impl From< AttributesInner > for Vec< syn ::Attribute > 
  {
  #[ inline( always ) ]
  fn from(src: AttributesInner) -> Self 
  {
   src.0
 }
 }

  #[ allow( clippy ::iter_without_into_iter ) ]
  impl AttributesInner 
  {
  /// Iterator
  pub fn iter( &self ) -> core ::slice ::Iter< '_, syn ::Attribute >
  {
   self.0.iter()
 }
 }

  #[ allow( clippy ::default_trait_access ) ]
  impl syn ::parse ::Parse for AttributesInner 
  {
  fn parse(input: ParseStream< '_ >) -> syn ::Result< Self > 
  {
   // let mut result: Self = from!();
   let mut result: Self = Default ::default();
   loop
   {
  if !input.peek(Token![ # ]) || !input.peek2(Token![!]) 
  {
   break;
 }
  let input2;
  let element = syn ::Attribute {
   pound_token: input.parse()?,
   style: syn ::AttrStyle ::Inner(input.parse()?),
   bracket_token: bracketed!( input2 in input ),
   // path: input2.call( syn ::Path ::parse_mod_style )?,
   // tokens: input2.parse()?,
   meta: input2.parse()?,
 };
  result.0.push(element);
 }
   Ok(result)
 }
 }

  impl quote ::ToTokens for AttributesInner 
  {
  fn to_tokens(&self, tokens: &mut proc_macro2 ::TokenStream) 
  {
   use crate ::quote ::TokenStreamExt;
   tokens.append_all(self.0.iter());
 }
 }

  /// Represents a collection of outer attributes.
  ///
  /// This struct wraps a `Vec< syn ::Attribute >`, providing utility methods for parsing,
  /// converting, and iterating over outer attributes. Outer attributes are those that
  /// appear outside of an item, such as `#[ ... ]` annotations in Rust.
  ///
  #[ derive( Debug, PartialEq, Eq, Clone, Default ) ]
  pub struct AttributesOuter(pub Vec< syn ::Attribute >);

  impl From< Vec< syn ::Attribute > > for AttributesOuter 
  {
  #[ inline( always ) ]
  fn from(src: Vec< syn ::Attribute >) -> Self 
  {
   Self(src)
 }
 }

  impl From< AttributesOuter > for Vec< syn ::Attribute > 
  {
  #[ inline( always ) ]
  fn from(src: AttributesOuter) -> Self 
  {
   src.0
 }
 }

  #[ allow( clippy ::iter_without_into_iter ) ]
  impl AttributesOuter 
  {
  /// Iterator
  pub fn iter( &self ) -> core ::slice ::Iter< '_, syn ::Attribute >
  {
   self.0.iter()
 }
 }

  #[ allow( clippy ::default_trait_access ) ]
  impl syn ::parse ::Parse for AttributesOuter 
  {
  fn parse(input: ParseStream< '_ >) -> syn ::Result< Self > 
  {
   let mut result: Self = Default ::default();
   loop
   {
  if !input.peek(Token![ # ]) || input.peek2(Token![!]) 
  {
   break;
 }
  let input2;
  let element = syn ::Attribute {
   pound_token: input.parse()?,
   style: syn ::AttrStyle ::Outer,
   bracket_token: bracketed!( input2 in input ),
   // path: input2.call( syn ::Path ::parse_mod_style )?,
   // tokens: input2.parse()?,
   meta: input2.parse()?,
 };
  result.0.push(element);
 }
   Ok(result)
 }
 }

  impl quote ::ToTokens for AttributesOuter 
  {
  fn to_tokens(&self, tokens: &mut proc_macro2 ::TokenStream) 
  {
   use crate ::quote ::TokenStreamExt;
   tokens.append_all(self.0.iter());
 }
 }

  impl syn ::parse ::Parse for Many< AttributesInner > 
  {
  fn parse(input: ParseStream< '_ >) -> syn ::Result< Self > 
  {
   let mut result = Self ::new();
   loop
   {
  // let lookahead = input.lookahead1();
  if !input.peek(Token![ # ]) 
  {
   break;
 }
  result.0.push(input.parse()?);
 }
   Ok(result)
 }
 }

  impl syn ::parse ::Parse for Many< AttributesOuter > 
  {
  fn parse(input: ParseStream< '_ >) -> syn ::Result< Self > 
  {
   let mut result = Self ::new();
   loop
   {
  // let lookahead = input.lookahead1();
  if !input.peek(Token![ # ]) 
  {
   break;
 }
  result.0.push(input.parse()?);
 }
   Ok(result)
 }
 }

  impl AsMuchAsPossibleNoDelimiter for syn ::Item {}

  /// Trait for components of a structure aggregating attributes that can be constructed from a meta attribute.
  ///
  /// The `AttributeComponent` trait defines the interface for components that can be created
  /// from a `syn ::Attribute` meta item. Implementors of this trait are required to define
  /// a constant `KEYWORD` that identifies the type of the component and a method `from_meta`
  /// that handles the construction of the component from the given attribute.
  ///
  /// This trait is designed to facilitate modular and reusable parsing of attributes applied
  /// to structs, enums, or other constructs. By implementing this trait, you can create specific
  /// components from attributes and then aggregate these components into a larger structure.
  ///
  /// # Example
  ///
  /// ```rust
  /// use macro_tools :: { AttributeComponent, syn ::Result };
  /// use syn :: { Attribute, Error };
  ///
  /// struct MyComponent;
  ///
  /// impl AttributeComponent for MyComponent
  /// {
  ///   const KEYWORD: &'static str = "my_component";
  ///
  ///   fn from_meta( attr: &Attribute ) -> syn ::Result< Self >
  ///   {
  ///     // Parsing logic here
  ///     // Return Ok(MyComponent) if parsing is successful
  ///     // Return Err(Error ::new_spanned(attr, "error message")) if parsing fails
  ///     Ok( MyComponent )
  /// }
  /// }
  /// ```
  ///
  /// # Parameters
  ///
  /// - `attr` : A reference to the `syn ::Attribute` from which the component is to be constructed.
  ///
  /// # Returns
  ///
  /// A `syn ::Result` containing the constructed component if successful, or an error if the parsing fails.
  ///
  pub trait AttributeComponent
  where
  Self: Sized,
  {
  /// The keyword that identifies the component.
  /// This constant is used to match the attribute to the corresponding component.
  /// Each implementor of this trait must provide a unique keyword for its type.
  const KEYWORD: &'static str;

  /// Constructs the component from the given meta attribute.
  /// This method is responsible for parsing the provided `syn ::Attribute` and
  /// returning an instance of the component. If the attribute cannot be parsed
  /// into the component, an error should be returned.
  ///
  /// # Parameters
  ///
  /// - `attr` : A reference to the `syn ::Attribute` from which the component is to be constructed.
  ///
  /// # Returns
  ///
  /// A `syn ::Result` containing the constructed component if successful, or an error if the parsing fails.
  ///
  /// # Errors
  /// qqq: doc
  fn from_meta(attr: &syn ::Attribute) -> syn ::Result< Self >;

  // zzz: redo maybe
 }

}

#[ 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 :: {
  // equation,
  has_debug,
  is_standard,
  has_deref,
  has_deref_mut,
  has_from,
  has_index_mut,
  has_as_mut,
 };
}

/// 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 ::attr;

  #[ doc( inline ) ]
  pub use prelude :: *;
  #[ doc( inline ) ]
  pub use private :: { AttributesInner, AttributesOuter, AttributeComponent };
}

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