Skip to main content

macro_lang/
template.rs

1//! The output side of a rule: what an invocation expands to.
2
3use alloc::vec::Vec;
4
5use intern_lang::Symbol;
6use token_lang::{Span, Token};
7
8use crate::Context;
9
10/// One element of a rule's template — the right-hand side of a `macro_rules!`
11/// arm.
12///
13/// A template is a sequence of elements written out in order when its rule
14/// matches. Literal tokens and groups are copied into the output; a
15/// [`Var`](Template::Var) is replaced by whatever its metavariable captured; a
16/// [`Repeat`](Template::Repeat) writes its body once per captured repetition.
17///
18/// Literal tokens are where hygiene happens. Every literal token written by an
19/// expansion receives a fresh [`Context`] minted for that expansion, so a name
20/// the template introduces — a temporary, a loop label — can never be confused
21/// with the same name at the call site. Substituted captures keep the context
22/// they arrived with; they belong to the caller.
23///
24/// The enum is `#[non_exhaustive]` so that new kinds of template element can be
25/// added in a minor release. Constructing any variant is unaffected; code that
26/// matches on a `Template` needs a wildcard arm.
27///
28/// # Examples
29///
30/// The template `( $($arg)+* )` — the captured arguments joined by `+`:
31///
32/// ```
33/// use macro_lang::Template;
34/// use intern_lang::Interner;
35/// use token_lang::{Span, Token};
36///
37/// let mut names = Interner::new();
38/// let template: Vec<Template<char>> = vec![Template::Group {
39///     open: Token::new('(', Span::new(30, 31)),
40///     close: Token::new(')', Span::new(40, 41)),
41///     body: vec![Template::Repeat {
42///         body: vec![Template::Var(names.intern("arg"))],
43///         separator: Some(Token::new('+', Span::new(36, 37))),
44///     }],
45/// }];
46/// assert_eq!(template.len(), 1);
47/// ```
48#[derive(Clone, Debug, PartialEq, Eq, Hash)]
49#[non_exhaustive]
50pub enum Template<K> {
51    /// A literal token, written out with a context minted for the expansion.
52    Token {
53        /// The token to write: its kind and its span in the macro definition.
54        token: Token<K>,
55        /// The context the token has in the macro definition. For a macro
56        /// written directly in source this is [`Context::ROOT`]; for a macro
57        /// defined by another macro's expansion it is the context that expansion
58        /// gave the token.
59        ctx: Context,
60    },
61    /// A literal group, written out with its delimiters and its expanded body.
62    Group {
63        /// The opening delimiter.
64        open: Token<K>,
65        /// The closing delimiter.
66        close: Token<K>,
67        /// The template expanded between the delimiters.
68        body: Vec<Template<K>>,
69    },
70    /// The tree a metavariable captured, substituted unchanged — `$name`.
71    ///
72    /// The name must be bound by the rule's pattern. A metavariable captured
73    /// inside `n` pattern repetitions must be used inside at least `n` template
74    /// repetitions; one used inside more is repeated as a whole.
75    Var(Symbol),
76    /// The body written once per captured repetition — `$( ... ) sep *`.
77    ///
78    /// The number of repetitions comes from the metavariables used in the body:
79    /// every metavariable repeating at this depth must have captured the same
80    /// number of trees, and at least one must be present.
81    Repeat {
82        /// The template written on each repetition.
83        body: Vec<Template<K>>,
84        /// A token written between repetitions, such as `,`. Hygiene treats it
85        /// as a token defined in the [root](Context::ROOT) context, which is
86        /// exact for a macro written in source. A macro whose definition was
87        /// itself produced by an expansion should use
88        /// [`RepeatSeparated`](Template::RepeatSeparated), which carries the
89        /// separator's definition context.
90        separator: Option<Token<K>>,
91    },
92    /// The body written once per captured repetition with `separator` written
93    /// between repetitions — `$( ... ) sep *` — where the separator carries its
94    /// definition context like a [`Token`](Template::Token) does.
95    ///
96    /// The separator is a literal token of the template, so it is marked
97    /// exactly like one: it receives the context this expansion mints for
98    /// `ctx`, the same context every literal token defined in `ctx` receives,
99    /// and [`Origin::parent`](crate::Origin::parent) reports `ctx`. A front end
100    /// lowering a macro definition that an earlier expansion produced passes
101    /// the separator token's own context here, so the separator binds and
102    /// resolves like the tokens around it. For `ctx` equal to
103    /// [`Context::ROOT`] this behaves exactly like
104    /// [`Repeat`](Template::Repeat) with `Some(separator)`.
105    ///
106    /// Repetition counts follow the same rules as [`Repeat`](Template::Repeat).
107    ///
108    /// Added in 1.1.0.
109    ///
110    /// # Examples
111    ///
112    /// ```
113    /// use macro_lang::{Context, Expander, Fragment, Kleene, Macro, Pattern, Rule, Template, Tree};
114    /// use intern_lang::Interner;
115    /// use token_lang::{Span, Token};
116    ///
117    /// let mut names = Interner::new();
118    /// let x = names.intern("x");
119    /// // A context some earlier expansion gave this macro's definition.
120    /// let mut expander = Expander::new();
121    /// let def = names.intern("def");
122    /// let maker = Macro::new(def, vec![Rule {
123    ///     pattern: vec![],
124    ///     template: vec![Template::token('k', Span::new(0, 1))],
125    /// }])?;
126    /// let Some(Tree::Token { ctx: def_ctx, .. }) =
127    ///     expander.expand(&maker, &[], Span::new(0, 1), Context::ROOT)?.first().cloned()
128    /// else {
129    ///     return Err("expected a token".into());
130    /// };
131    ///
132    /// // join!($($x:tt)*) => $($x);*  — with `;` defined in `def_ctx`
133    /// let join = Macro::new(names.intern("join"), vec![Rule {
134    ///     pattern: vec![Pattern::Repeat {
135    ///         body: vec![Pattern::Bind { name: x, fragment: Fragment::Tree }],
136    ///         separator: None,
137    ///         kleene: Kleene::ZeroOrMore,
138    ///     }],
139    ///     template: vec![Template::RepeatSeparated {
140    ///         body: vec![Template::Var(x)],
141    ///         separator: Token::new(';', Span::new(9, 10)),
142    ///         ctx: def_ctx,
143    ///     }],
144    /// }])?;
145    ///
146    /// let input = [Tree::token('a', Span::new(0, 1)), Tree::token('b', Span::new(1, 2))];
147    /// let out = expander.expand(&join, &input, Span::new(0, 2), Context::ROOT)?;
148    /// let Some(Tree::Token { ctx: sep_ctx, .. }) = out.get(1) else {
149    ///     return Err("expected the separator".into());
150    /// };
151    /// let origin = expander.origin(*sep_ctx).ok_or("separator not marked")?;
152    /// assert_eq!(origin.parent, def_ctx);
153    /// # Ok::<(), Box<dyn std::error::Error>>(())
154    /// ```
155    RepeatSeparated {
156        /// The template written on each repetition.
157        body: Vec<Template<K>>,
158        /// The token written between repetitions.
159        separator: Token<K>,
160        /// The context the separator has in the macro definition.
161        ctx: Context,
162    },
163}
164
165impl<K> Template<K> {
166    /// Builds a literal token defined in the [root](Context::ROOT) context —
167    /// a token written in a macro definition in source.
168    ///
169    /// # Examples
170    ///
171    /// ```
172    /// use macro_lang::{Context, Template};
173    /// use token_lang::{Span, Token};
174    ///
175    /// assert_eq!(
176    ///     Template::token(';', Span::new(8, 9)),
177    ///     Template::Token { token: Token::new(';', Span::new(8, 9)), ctx: Context::ROOT },
178    /// );
179    /// ```
180    #[inline]
181    #[must_use]
182    pub const fn token(kind: K, span: Span) -> Self {
183        Self::Token {
184            token: Token::new(kind, span),
185            ctx: Context::ROOT,
186        }
187    }
188}
189
190#[cfg(test)]
191mod tests {
192    use super::*;
193
194    #[test]
195    fn test_token_uses_root_context() {
196        assert_eq!(
197            Template::token(5u8, Span::new(1, 2)),
198            Template::Token {
199                token: Token::new(5, Span::new(1, 2)),
200                ctx: Context::ROOT,
201            }
202        );
203    }
204}