Crate macro_tools

source ·
Expand description

§Module :: proc_macro_tools

experimental rust-status docs.rs Open in Gitpod discord

Tools for writing procedural macros.

§Example: Trivial One

The purpose of typ::type_parameters is to extract type parameters from a given Rust type. In this example, we generate a type core::option::Option<i8, i16, i32, i64> and extract its type parameters.

#[ cfg( not( feature = "enabled" ) ) ]
fn main(){}
#[ cfg( feature = "enabled" ) ]
fn main()
{
  // Import necessary macros and modules from the `macro_tools` crate.
  use macro_tools::{ typ, qt };

  // Generate a token stream representing the type `core::option::Option<i8, i16, i32, i64>`.
  let code = qt!( core::option::Option< i8, i16, i32, i64 > );

  // Parse the generated token stream into a `syn::Type` object.
  // `syn::Type` is a syntax tree node representing a Rust type.
  let tree_type = syn::parse2::< syn::Type >( code ).unwrap();

  // Extract type parameters from the parsed type.
  // `typ::type_parameters` takes a reference to a `syn::Type` and a range.
  // It returns a vector of type parameters within the specified range.
  // Here, `0..=2` specifies that we are interested in the first three type parameters.
  let got = typ::type_parameters( &tree_type, 0..=2 );

  // Iterate over the extracted type parameters and print each one.
  // The `qt!` macro is used to convert the type parameter back to a token stream for printing.
  got.iter().for_each( | e | println!( "{}", qt!( #e ) ) );

  /* Expected output:
     i8
     i16
     i32
  */
}

Try out cargo run --example macro_tools_trivial.
See code.

§Example: Attribute Properties

This example demonstrates an approach to parsing attributes and their properties. The attributes are collected into a struct that aggregates them, and attribute properties are parsed using reusable components from a library. The example shows how to use AttributePropertyBoolean for parsing boolean properties and the roles of the traits AttributePropertyComponent and AttributeComponent. The Assign trait is also used to simplify the logic of assigning fields.

Attributes are collected into a ItemAttributes struct, and attribute properties are parsed using reusable components like AttributePropertyBoolean.

  • AttributeComponent: A trait that defines how an attribute should be parsed from a syn::Attribute.
  • AttributePropertyComponent: A trait that defines a marker for attribute properties.
  • Assign: A trait that simplifies the logic of assigning fields to a struct. Using a component-based approach requires each field to have a unique type, which aligns with the strengths of strongly-typed languages. This method ensures that the logic of assigning values to fields is encapsulated within the fields themselves, promoting modularity and reusability.

The reusable property components from the library come with parameters that distinguish different properties of the same type. This is useful when an attribute has multiple boolean properties, for instance. Such an approach helps to avoid limitations where it is always possible to define traits for custom types, while it may not be possible for types defined in other crates.


#[ cfg( not( all( feature = "enabled", debug_assertions ) )  ) ]
fn main(){}
#[ cfg( all( feature = "enabled", debug_assertions )  ) ]
fn main()
{

  use macro_tools::
  {
    attr,
    syn_err,
    return_syn_err,
    qt,
    Result,
    AttributeComponent,
    AttributePropertyComponent,
    AttributePropertyBoolean,
    AttributePropertySingletone,
  };
  use former_types::Assign;

  /// Represents the attributes of a struct. Aggregates all its attributes.
  #[ derive( Debug, Default ) ]
  pub struct ItemAttributes
  {
    /// Attribute for customizing the mutation process.
    pub mutator : AttributeMutator,
  }

  impl ItemAttributes
  {
    /// Constructs a `ItemAttributes` instance from an iterator of attributes.
    ///
    /// This function parses the provided attributes and assigns them to the
    /// appropriate fields in the `ItemAttributes` struct.
    pub fn from_attrs< 'a >( attrs : impl Iterator< Item = & 'a syn::Attribute > ) -> Result< Self >
    {
      let mut result = Self::default();

      // Closure to generate an error message for unknown attributes.
      let error = | attr : & syn::Attribute | -> syn::Error
      {
        let known_attributes = const_format::concatcp!
        (
          "Known attributes are: ",
          "debug",
          ", ", AttributeMutator::KEYWORD,
          "."
        );
        syn_err!
        (
          attr,
          "Expects an attribute of format '#[ attribute( key1 = val1, key2 = val2 ) ]'\n  {known_attributes}\n  But got: '{}'",
          qt! { #attr }
        )
      };

      for attr in attrs
      {
        let key_ident = attr.path().get_ident().ok_or_else( || error( attr ) )?;
        let key_str = format!( "{}", key_ident );
        match key_str.as_ref()
        {
          AttributeMutator::KEYWORD => result.assign( AttributeMutator::from_meta( attr )? ),
          "debug" => {},
          _ => {},
        }
      }

      Ok( result )
    }
  }

  /// Represents attributes for customizing the mutation process in a forming operation.
  ///
  /// ## Example of code
  ///
  /// ```ignore
  /// #[ mutator( custom = true, debug = true ) ]
  /// ```
  #[ derive( Debug, Default ) ]
  pub struct AttributeMutator
  {
    /// Indicates whether a custom mutator should be generated.
    /// Defaults to `false`, meaning no custom mutator is generated unless explicitly requested.
    pub custom : AttributePropertyCustom,
    /// Specifies whether to print code generated for the field.
    /// Defaults to `false`, which means no hint is provided unless explicitly requested.
    pub debug : AttributePropertyDebug,
  }

  impl AttributeComponent for AttributeMutator
  {
    const KEYWORD : & 'static str = "mutator";

    /// Parses a `syn::Attribute` into an `AttributeMutator`.
    fn from_meta( attr : & syn::Attribute ) -> Result< Self >
    {
      match attr.meta
      {
        syn::Meta::List( ref meta_list ) =>
        {
          return syn::parse2::< AttributeMutator >( meta_list.tokens.clone() );
        },
        syn::Meta::Path( ref _path ) =>
        {
          return Ok( Default::default() )
        },
        _ => return_syn_err!
        (
          attr,
          "Expects an attribute of format `#[ mutator( custom = true ) ]`. \nGot: {}",
          qt! { #attr }
        ),
      }
    }
  }

  // Implement `Assign` trait to allow assigning `AttributeMutator` to `ItemAttributes`.
  impl< IntoT > Assign< AttributeMutator, IntoT > for ItemAttributes
  where
    IntoT : Into< AttributeMutator >,
  {
    #[ inline( always ) ]
    fn assign( & mut self, component : IntoT )
    {
      self.mutator = component.into();
    }
  }

  // Implement `Assign` trait to allow assigning `AttributePropertyDebug` to `AttributeMutator`.
  impl< IntoT > Assign< AttributePropertyDebug, IntoT > for AttributeMutator
  where
    IntoT : Into< AttributePropertyDebug >,
  {
    #[ inline( always ) ]
    fn assign( & mut self, component : IntoT )
    {
      self.debug = component.into();
    }
  }

  // Implement `Assign` trait to allow assigning `AttributePropertyCustom` to `AttributeMutator`.
  impl< IntoT > Assign< AttributePropertyCustom, IntoT > for AttributeMutator
  where
    IntoT : Into< AttributePropertyCustom >,
  {
    #[ inline( always ) ]
    fn assign( & mut self, component : IntoT )
    {
      self.custom = component.into();
    }
  }

  impl syn::parse::Parse for AttributeMutator
  {
    fn parse( input : syn::parse::ParseStream< '_ > ) -> syn::Result< Self >
    {
      let mut result = Self::default();

      let error = | ident : & syn::Ident | -> syn::Error
      {
        let known = const_format::concatcp!
        (
          "Known entries of attribute ", AttributeMutator::KEYWORD, " are: ",
          AttributePropertyCustom::KEYWORD,
          ", ", AttributePropertyDebug::KEYWORD,
          "."
        );
        syn_err!
        (
          ident,
          r#"Expects an attribute of format '#[ mutator( custom = false ) ]'
    {known}
    But got: '{}'
  "#,
          qt! { #ident }
        )
      };

      while !input.is_empty()
      {
        let lookahead = input.lookahead1();
        if lookahead.peek( syn::Ident )
        {
          let ident : syn::Ident = input.parse()?;

          match ident.to_string().as_str()
          {
            AttributePropertyCustom::KEYWORD => result.assign( AttributePropertyCustom::parse( input )? ),
            AttributePropertyDebug::KEYWORD => result.assign( AttributePropertyDebug::from( true ) ),
            _ => return Err( error( & ident ) ),
          }
        }
        else
        {
          return Err( lookahead.error() );
        }

        // Optional comma handling
        if input.peek( syn::Token![,] )
        {
          input.parse::< syn::Token![,] >()?;
        }
      }

      Ok( result )
    }
  }

  // == Attribute properties

  /// Marker type for attribute property to specify whether to provide a sketch as a hint.
  /// Defaults to `false`, which means no hint is provided unless explicitly requested.
  #[ derive( Debug, Default, Clone, Copy ) ]
  pub struct AttributePropertyDebugMarker;

  impl AttributePropertyComponent for AttributePropertyDebugMarker
  {
    const KEYWORD : & 'static str = "debug";
  }

  /// Specifies whether to provide a sketch as a hint.
  /// Defaults to `false`, which means no hint is provided unless explicitly requested.
  pub type AttributePropertyDebug = AttributePropertySingletone< AttributePropertyDebugMarker >;

  // ==

  /// Marker type for attribute property to indicate whether a custom code should be generated.
  /// Defaults to `false`, meaning no custom code is generated unless explicitly requested.
  #[ derive( Debug, Default, Clone, Copy ) ]
  pub struct AttributePropertyCustomMarker;

  impl AttributePropertyComponent for AttributePropertyCustomMarker
  {
    const KEYWORD : & 'static str = "custom";
  }

  /// Indicates whether a custom code should be generated.
  /// Defaults to `false`, meaning no custom code is generated unless explicitly requested.
  pub type AttributePropertyCustom = AttributePropertyBoolean< AttributePropertyCustomMarker >;

  // == test code

  // Parse an attribute and construct a `ItemAttributes` instance.
  let input : syn::Attribute = syn::parse_quote!( #[ mutator( custom = true ) ] );
  let attrs : ItemAttributes = ItemAttributes::from_attrs( std::iter::once( & input ) ).unwrap();
  println!( "{:?}", attrs );

  // Test `AttributePropertyBoolean` functionality.
  let attr : AttributePropertyBoolean< AttributePropertyDebugMarker > = AttributePropertyBoolean::default();
  assert_eq!( attr.internal(), false );
  let attr : AttributePropertyBoolean< AttributePropertyDebugMarker > = true.into();
  assert_eq!( attr.internal(), true );
  let attr : AttributePropertyBoolean< AttributePropertyDebugMarker > = false.into();
  assert_eq!( attr.internal(), false );

}

Try out cargo run --example macro_tools_attr_prop.
See code.

§To add to your project

cargo add proc_macro_tools

§Try out from the repository

git clone https://github.com/Wandalen/wTools
cd wTools
cd examples/macro_tools_trivial
cargo run

Modules§

  • Protected namespace of the module.
  • Protected namespace of the module.
  • Protected namespace of the module.
  • Dependencies of the module.
  • Protected namespace of the module.
  • Protected namespace of the module.
  • Protected namespace of the module.
  • Protected namespace of the module.
  • Exposed namespace of the module.
  • Protected namespace of the module.
  • Functions and structures to handle and manipulate generic parameters using the syn crate. It’s designed to support macro-driven code generation by simplifying, merging, extracting, and decomposing syn::Generics.
  • This module provides various utilities and namespaces for working with syn::Item, specifically focusing on ensuring syntactical correctness and managing different visibility levels within the code. It includes functions to manipulate the structure of items, handle different kinds of fields, and provide a structured approach to organizing the codebase into different access levels.
  • Protected namespace of the module.
  • Protected namespace of the module.
  • Protected namespace of the module.
  • Parented namespace of the module.
  • Responsible for generating marker PhantomData fields to avoid the rule requiring the usage of all generic parameters in a struct. This is often necessary to ensure that Rust’s type system correctly tracks the ownership and lifetimes of these parameters without needing them to be explicitly used in the struct’s fields.
  • Prelude to use essentials: use my_module::prelude::*.
  • Protected namespace of the module.
  • Structures and functions for handling syn::punctuated::Punctuated collections.
  • Protected namespace of the module.
  • Protected namespace of the module.
  • Protected namespace of the module.
  • Protected namespace of the module.

Macros§

  • A type-macro that expands to the name of the Rust type representation of a given token.
  • Parse a set of curly braces and expose their content to subsequent parsers.
  • Parse a set of square brackets and expose their content to subsequent parsers.
  • Macro for diagnostics purpose to diagnose source code behind it and export it into a string.
  • Macro for diagnostics purpose to print both syntax tree and source code behind it without syntax tree.
  • Macro to export source code behind a syntax tree into a string.
  • Define a type that supports parsing and printing a given identifier as if it were a keyword.
  • Define a type that supports parsing and printing a multi-character symbol as if it were a punctuation token.
  • Formatting macro for constructing Idents.
  • Parse a set of parentheses and expose their content to subsequent parsers.
  • Parse the input TokenStream of a macro, triggering a compile error if the tokens fail to parse.
  • Quasi-quotation macro that accepts input like the quote! macro but uses type inference to figure out a return type for those tokens.
  • This macro is parse_quote! + quote_spanned!.
  • Quasi-quotation macro that accepts input like the quote! macro but uses type inference to figure out a return type for those tokens.
  • This macro is parse_quote! + quote_spanned!.
  • Macro to generate syn error either with span of a syntax tree element or with default one proc_macro2::Span::call_site().
  • Macro to generate syn error either with span of a syntax tree element or with default one proc_macro2::Span::call_site().
  • Macro for diagnostics purpose to export both syntax tree and source code behind it into a string.
  • Macro for diagnostics purpose to print both syntax tree and source code behind it with syntax tree.

Structs§

Traits§

  • Marker saying how to parse several elements of such type in a row.
  • Trait for components of a structure aggregating attributes that can be constructed from a meta attribute.
  • Trait for properties of an attribute component that can be identified by a keyword.
  • A trait for converting a reference to an existing type into a syn::AngleBracketedGenericArguments.
  • Convert it into canonical interval.
  • Trait that encapsulates an iterator with specific characteristics, tailored for use with the syn crate.
  • Interval adapter. Interface to interval-like structures.
  • Trait to get name of an syntax element.
  • Interval adapter. Interface to interval-like structures.
  • A trait that can provide the Span of the complete contents of a syntax tree node.

Functions§

  • Adds indentation and optional prefix/postfix to each line of the given string.
  • Formats a debugging report for code transformation processes, detailing both the original and generated code for easy comparison and review.
  • Prints a debugging report for a pair of token streams to the standard output.

Type Aliases§