Skip to main content

Template

Enum Template 

Source
#[non_exhaustive]
pub enum Template<K> { Token { token: Token<K>, ctx: Context, }, Group { open: Token<K>, close: Token<K>, body: Vec<Template<K>>, }, Var(Symbol), Repeat { body: Vec<Template<K>>, separator: Option<Token<K>>, }, RepeatSeparated { body: Vec<Template<K>>, separator: Token<K>, ctx: Context, }, }
Expand description

One element of a rule’s template — the right-hand side of a macro_rules! arm.

A template is a sequence of elements written out in order when its rule matches. Literal tokens and groups are copied into the output; a Var is replaced by whatever its metavariable captured; a Repeat writes its body once per captured repetition.

Literal tokens are where hygiene happens. Every literal token written by an expansion receives a fresh Context minted for that expansion, so a name the template introduces — a temporary, a loop label — can never be confused with the same name at the call site. Substituted captures keep the context they arrived with; they belong to the caller.

The enum is #[non_exhaustive] so that new kinds of template element can be added in a minor release. Constructing any variant is unaffected; code that matches on a Template needs a wildcard arm.

§Examples

The template ( $($arg)+* ) — the captured arguments joined by +:

use macro_lang::Template;
use intern_lang::Interner;
use token_lang::{Span, Token};

let mut names = Interner::new();
let template: Vec<Template<char>> = vec![Template::Group {
    open: Token::new('(', Span::new(30, 31)),
    close: Token::new(')', Span::new(40, 41)),
    body: vec![Template::Repeat {
        body: vec![Template::Var(names.intern("arg"))],
        separator: Some(Token::new('+', Span::new(36, 37))),
    }],
}];
assert_eq!(template.len(), 1);

Variants (Non-exhaustive)§

This enum is marked as non-exhaustive
Non-exhaustive enums could have additional variants added in future. Therefore, when matching against variants of non-exhaustive enums, an extra wildcard arm must be added to account for any future variants.
§

Token

A literal token, written out with a context minted for the expansion.

Fields

§token: Token<K>

The token to write: its kind and its span in the macro definition.

§ctx: Context

The context the token has in the macro definition. For a macro written directly in source this is Context::ROOT; for a macro defined by another macro’s expansion it is the context that expansion gave the token.

§

Group

A literal group, written out with its delimiters and its expanded body.

Fields

§open: Token<K>

The opening delimiter.

§close: Token<K>

The closing delimiter.

§body: Vec<Template<K>>

The template expanded between the delimiters.

§

Var(Symbol)

The tree a metavariable captured, substituted unchanged — $name.

The name must be bound by the rule’s pattern. A metavariable captured inside n pattern repetitions must be used inside at least n template repetitions; one used inside more is repeated as a whole.

§

Repeat

The body written once per captured repetition — $( ... ) sep *.

The number of repetitions comes from the metavariables used in the body: every metavariable repeating at this depth must have captured the same number of trees, and at least one must be present.

Fields

§body: Vec<Template<K>>

The template written on each repetition.

§separator: Option<Token<K>>

A token written between repetitions, such as ,. Hygiene treats it as a token defined in the root context, which is exact for a macro written in source. A macro whose definition was itself produced by an expansion should use RepeatSeparated, which carries the separator’s definition context.

§

RepeatSeparated

The body written once per captured repetition with separator written between repetitions — $( ... ) sep * — where the separator carries its definition context like a Token does.

The separator is a literal token of the template, so it is marked exactly like one: it receives the context this expansion mints for ctx, the same context every literal token defined in ctx receives, and Origin::parent reports ctx. A front end lowering a macro definition that an earlier expansion produced passes the separator token’s own context here, so the separator binds and resolves like the tokens around it. For ctx equal to Context::ROOT this behaves exactly like Repeat with Some(separator).

Repetition counts follow the same rules as Repeat.

Added in 1.1.0.

§Examples

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

let mut names = Interner::new();
let x = names.intern("x");
// A context some earlier expansion gave this macro's definition.
let mut expander = Expander::new();
let def = names.intern("def");
let maker = Macro::new(def, vec![Rule {
    pattern: vec![],
    template: vec![Template::token('k', Span::new(0, 1))],
}])?;
let Some(Tree::Token { ctx: def_ctx, .. }) =
    expander.expand(&maker, &[], Span::new(0, 1), Context::ROOT)?.first().cloned()
else {
    return Err("expected a token".into());
};

// join!($($x:tt)*) => $($x);*  — with `;` defined in `def_ctx`
let join = Macro::new(names.intern("join"), vec![Rule {
    pattern: vec![Pattern::Repeat {
        body: vec![Pattern::Bind { name: x, fragment: Fragment::Tree }],
        separator: None,
        kleene: Kleene::ZeroOrMore,
    }],
    template: vec![Template::RepeatSeparated {
        body: vec![Template::Var(x)],
        separator: Token::new(';', Span::new(9, 10)),
        ctx: def_ctx,
    }],
}])?;

let input = [Tree::token('a', Span::new(0, 1)), Tree::token('b', Span::new(1, 2))];
let out = expander.expand(&join, &input, Span::new(0, 2), Context::ROOT)?;
let Some(Tree::Token { ctx: sep_ctx, .. }) = out.get(1) else {
    return Err("expected the separator".into());
};
let origin = expander.origin(*sep_ctx).ok_or("separator not marked")?;
assert_eq!(origin.parent, def_ctx);

Fields

§body: Vec<Template<K>>

The template written on each repetition.

§separator: Token<K>

The token written between repetitions.

§ctx: Context

The context the separator has in the macro definition.

Implementations§

Source§

impl<K> Template<K>

Source

pub const fn token(kind: K, span: Span) -> Self

Builds a literal token defined in the root context — a token written in a macro definition in source.

§Examples
use macro_lang::{Context, Template};
use token_lang::{Span, Token};

assert_eq!(
    Template::token(';', Span::new(8, 9)),
    Template::Token { token: Token::new(';', Span::new(8, 9)), ctx: Context::ROOT },
);

Trait Implementations§

Source§

impl<K: Clone> Clone for Template<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> Debug for Template<K>

Source§

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

Formats the value using the given formatter. Read more
Source§

impl<K: Eq> Eq for Template<K>

Source§

impl<K: Hash> Hash for Template<K>

Source§

fn hash<__H: Hasher>(&self, state: &mut __H)

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl<K: PartialEq> PartialEq for Template<K>

Source§

fn eq(&self, other: &Self) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl<K: PartialEq> StructuralPartialEq for Template<K>

Auto Trait Implementations§

§

impl<K> Forget for Template<K>

§

impl<K> Freeze for Template<K>
where Token<K>: Freeze, Vec<Template<K>>: Freeze, Option<Token<K>>: Freeze,

§

impl<K> Move for Template<K>

§

impl<K> RefUnwindSafe for Template<K>

§

impl<K> Send for Template<K>
where Token<K>: Send, Vec<Template<K>>: Send, Option<Token<K>>: Send,

§

impl<K> Sync for Template<K>
where Token<K>: Sync, Vec<Template<K>>: Sync, Option<Token<K>>: Sync,

§

impl<K> Unpin for Template<K>
where Token<K>: Unpin, Vec<Template<K>>: Unpin, Option<Token<K>>: Unpin,

§

impl<K> UnsafeUnpin for Template<K>

§

impl<K> UnwindSafe for Template<K>

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.