Skip to main content

Macro

Struct Macro 

Source
pub struct Macro<K> { /* private fields */ }
Expand description

A validated, compiled macro: a name and an ordered list of rules.

Building a Macro does all the work that does not depend on an invocation: it checks every rule (see MacroError) and compiles each pattern into a matching automaton and each template into a flat program. A macro is immutable once built and can be expanded any number of times, by any number of Expanders.

When expanded, the rules are tried in order and the first rule whose pattern matches the invocation is used, exactly like the arms of macro_rules!.

§Examples

A two-rule macro: () expands to 0, anything else is passed through.

use macro_lang::{Fragment, Kleene, Macro, Pattern, Rule, Template};
use intern_lang::Interner;
use token_lang::Span;

let mut names = Interner::new();
let t = names.intern("t");
let mac: Macro<char> = Macro::new(names.intern("or_zero"), vec![
    Rule { pattern: vec![], template: vec![Template::token('0', Span::new(0, 1))] },
    Rule {
        pattern: vec![Pattern::Repeat {
            body: vec![Pattern::Bind { name: t, fragment: Fragment::Tree }],
            separator: None,
            kleene: Kleene::OneOrMore,
        }],
        template: vec![Template::Repeat { body: vec![Template::Var(t)], separator: None }],
    },
])?;
assert_eq!(mac.name(), names.intern("or_zero"));

Implementations§

Source§

impl<K> Macro<K>

Source

pub fn new(name: Symbol, rules: Vec<Rule<K>>) -> Result<Self, MacroError>

Validates and compiles a macro from its rules.

§Parameters
  • name — the macro’s name. It is recorded in the Origin of every context the macro’s expansions mint, so diagnostics can say which macro introduced a token.
  • rules — the arms, in the order they are tried.
§Errors

Returns the first problem found, checking rules in order:

§Examples
use macro_lang::{Fragment, Kleene, Macro, MacroError, Pattern, Rule, Template};
use intern_lang::Interner;

let mut names = Interner::new();
let x = names.intern("x");

// `$($x:tt)*` captured `x` inside a repetition, so the template cannot
// use it bare.
let err = Macro::<char>::new(names.intern("m"), vec![Rule {
    pattern: vec![Pattern::Repeat {
        body: vec![Pattern::Bind { name: x, fragment: Fragment::Tree }],
        separator: None,
        kleene: Kleene::ZeroOrMore,
    }],
    template: vec![Template::Var(x)],
}]).unwrap_err();
assert_eq!(err, MacroError::StillRepeating { rule: 0, name: x });

assert_eq!(Macro::<char>::new(x, vec![]).unwrap_err(), MacroError::NoRules);
Source

pub const fn name(&self) -> Symbol

Returns the macro’s name.

§Examples
use macro_lang::{Macro, Rule};
use intern_lang::Interner;

let mut names = Interner::new();
let empty = names.intern("empty");
let mac: Macro<char> = Macro::new(empty, vec![Rule { pattern: vec![], template: vec![] }])?;
assert_eq!(names.resolve(mac.name()), Some("empty"));

Trait Implementations§

Source§

impl<K: Clone> Clone for Macro<K>

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<K> Debug for Macro<K>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl<K> Forget for Macro<K>

§

impl<K> Freeze for Macro<K>
where Vec<CompiledRule<K>>: Freeze,

§

impl<K> Move for Macro<K>

§

impl<K> RefUnwindSafe for Macro<K>
where Vec<CompiledRule<K>>: RefUnwindSafe,

§

impl<K> Send for Macro<K>
where Vec<CompiledRule<K>>: Send,

§

impl<K> Sync for Macro<K>
where Vec<CompiledRule<K>>: Sync,

§

impl<K> Unpin for Macro<K>
where Vec<CompiledRule<K>>: Unpin,

§

impl<K> UnsafeUnpin for Macro<K>
where Vec<CompiledRule<K>>: UnsafeUnpin,

§

impl<K> UnwindSafe for Macro<K>
where Vec<CompiledRule<K>>: UnwindSafe,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.