pm2 0.1.5

Useful proc macros.
Documentation
mod mune;

use proc_macro::{
  Delimiter, Spacing, TokenStream,
  TokenTree::{self, *},
  token_stream::IntoIter,
};

/// Extend enums to provide additional functionality
///
/// # Added constants
///
/// ## <code>REPR: [Option]<&[str]></code>
///
/// The type declared in `#[repr]` if present, as a string
///
/// ## <code>NUM_VARIANTS: [usize]</code>
///
/// The number of variants in the enum
///
/// ## `FIRST_VARIANT: Self`
///
/// The first variant as defined in source order
///
/// ## `LAST_VARIANT: Self`
///
/// The last variant as defined in source order
///
/// ## `MAX_DISCRIMINANT: <repr>`
///
/// **Available only on numeric `#[repr]`s.**
///
/// The highest numerical discriminant value among all variants. The type is the same as the
/// `#[repr]` of the enum
///
/// # Features
///
/// ## `#[mune(deref_discriminant)]`
///
/// **Available only on numeric `#[repr]`s.**
///
/// Implements [`Deref`][::core::ops::Deref] with a [`Target`][::core::ops::Deref::Target] of the
/// `#[repr]` of the enum allowing you to simply do `*MyEnum::Variant` to get the value of the
/// discriminant
///
/// ## `#[mune(bitflags = <name_format: string>)]`
///
/// **Available only on unsigned numeric `#[repr]`s apart from `usize`.**
///
/// Generates associated bitflag constants for every variant in the enum using a `1 << i` shift
/// pattern. `<name_format>` must be a string literal containing a single `{}` placeholder to format
/// the names of the generated constants. The type of each constant will be the same as the `#[repr]`
/// of the enum
///
/// **Note:** The `{}` placeholder will be replaced with the name of each variant converted to
/// `SCREAMING_SNAKE_CASE` as per the [rust style guide](https://doc.rust-lang.org/style-guide/advice.html#names).
/// The conversion is done using [`heck::ToShoutySnakeCase`]
///
/// # Limitations
///
/// * Generic parameters and `where` clauses are currently unsupported
/// * Only unit enums are supported for now, and without explicit discriminants
/// * Only `#[repr]`s with the type are supported
///
/// # Examples
///
/// ```
/// #[pm2::mune]
/// #[derive(Debug, PartialEq)]
/// enum MyEnum {
///   A,
///   B,
///   C,
///   D,
/// }
///
/// assert_eq!(MyEnum::REPR, None);
/// assert_eq!(MyEnum::NUM_VARIANTS, 4);
/// assert_eq!(MyEnum::FIRST_VARIANT, MyEnum::A);
/// assert_eq!(MyEnum::LAST_VARIANT, MyEnum::D);
/// ```
///
/// ```
/// #[pm2::mune]
/// #[repr(u8)]
/// #[derive(Debug, PartialEq)]
/// enum MyEnum {
///   A,
///   B,
///   C,
///   D,
/// }
///
/// assert_eq!(MyEnum::REPR, Some("u8"));
/// ```
///
/// ```
/// #[pm2::mune(deref_discriminant)]
/// #[repr(u8)]
/// #[derive(Debug, PartialEq)]
/// enum MyEnum {
///   A,
///   B,
///   C,
///   D,
/// }
///
/// let a: u8 = *MyEnum::A;
/// assert_eq!(a, 0);
///
/// assert_eq!(*MyEnum::B, 1);
/// assert_eq!(*MyEnum::C, 2);
/// assert_eq!(*MyEnum::D, 3);
/// ```
///
/// ```
/// #[pm2::mune(bitflags = "FLAG_{}")]
/// #[repr(u8)]
/// enum ModifierKey {
///   Control,
///   Alt,
///   LeftShift,
///   RightShift,
///   Meta,
/// }
///
/// assert_eq!(ModifierKey::FLAG_CONTROL, 1);
/// assert_eq!(ModifierKey::FLAG_ALT, 2);
/// assert_eq!(ModifierKey::FLAG_LEFT_SHIFT, 4);
/// assert_eq!(ModifierKey::FLAG_RIGHT_SHIFT, 8);
/// assert_eq!(ModifierKey::FLAG_META, 16);
/// ```
#[proc_macro_attribute]
pub fn mune(attr: TokenStream, item: TokenStream) -> TokenStream {
  mune::run(attr, item)
}

fn seek_and_collect_ident(s: &mut IntoIter, tokens: &mut Vec<TokenTree>, ident: &str) -> bool {
  for t in s {
    if let Ident(i) = &t
      && i.to_string() == ident
    {
      return true;
    }

    tokens.push(t);
  }

  false
}

fn seek_ident(s: &mut IntoIter, ident: &str) -> bool {
  for t in s {
    if let Ident(i) = t
      && i.to_string() == ident
    {
      return true;
    }
  }

  false
}

fn get_idents(tt: &[TokenTree]) -> Vec<String> {
  tt.iter()
    .filter_map(|t| {
      if let Ident(i) = t {
        Some(i.to_string())
      } else {
        None
      }
    })
    .collect()
}

fn get_repr(tt: &[TokenTree]) -> Option<String> {
  for (i, t) in tt.iter().enumerate() {
    if let Punct(p) = t
      && *p == '#'
      && p.spacing() == Spacing::Alone
      && i < tt.len() - 1
      && let Group(g) = &tt[i + 1]
      && g.delimiter() == Delimiter::Bracket
      && let mut s = g.stream().into_iter()
      && let Some(Ident(id)) = s.next()
      && id.to_string() == "repr"
      && let Some(Group(g)) = s.next()
      && g.delimiter() == Delimiter::Parenthesis
      && let mut s = g.stream().into_iter()
      && let Some(Ident(id)) = s.next()
    {
      return Some(id.to_string());
    }
  }

  None
}