macro_lang/pattern.rs
1//! The match side of a rule: what an invocation must look like.
2
3use alloc::vec::Vec;
4
5use intern_lang::Symbol;
6
7/// One element of a rule's pattern — the left-hand side of a `macro_rules!` arm.
8///
9/// A pattern is a sequence of elements matched against an invocation's token
10/// trees from left to right. Literal tokens and groups must appear exactly;
11/// a [`Bind`](Pattern::Bind) captures a tree under a name the template can
12/// substitute; a [`Repeat`](Pattern::Repeat) matches its body any number of
13/// times. The whole pattern must consume the whole invocation.
14///
15/// Patterns are plain data: a language's front end parses its own macro
16/// syntax (say `$x:ident` or `$($e:expr),*`) and lowers it into these
17/// elements. [`Macro::new`](crate::Macro::new) validates and compiles them.
18///
19/// Literal tokens compare by kind alone. Spans never matter to a match, and
20/// neither do hygiene contexts: a literal `else` in a pattern matches an `else`
21/// token whichever expansion introduced it.
22///
23/// The enum is `#[non_exhaustive]` so that new kinds of pattern element can be
24/// added in a minor release. Constructing any variant is unaffected; code that
25/// matches on a `Pattern` needs a wildcard arm.
26///
27/// # Examples
28///
29/// The pattern `$name:tt = ( $($arg:tt),* )` with `char` tokens:
30///
31/// ```
32/// use macro_lang::{Fragment, Kleene, Pattern};
33/// use intern_lang::Interner;
34///
35/// let mut names = Interner::new();
36/// let pattern: Vec<Pattern<char>> = vec![
37/// Pattern::Bind { name: names.intern("name"), fragment: Fragment::Tree },
38/// Pattern::Token('='),
39/// Pattern::Group {
40/// open: '(',
41/// close: ')',
42/// body: vec![Pattern::Repeat {
43/// body: vec![Pattern::Bind { name: names.intern("arg"), fragment: Fragment::Tree }],
44/// separator: Some(','),
45/// kleene: Kleene::ZeroOrMore,
46/// }],
47/// },
48/// ];
49/// assert_eq!(pattern.len(), 3);
50/// ```
51#[derive(Clone, Debug)]
52#[non_exhaustive]
53pub enum Pattern<K> {
54 /// Matches a single token whose kind equals this one.
55 Token(K),
56 /// Matches a delimited group with these delimiter kinds whose contents
57 /// match `body` exactly.
58 Group {
59 /// The kind of the opening delimiter.
60 open: K,
61 /// The kind of the closing delimiter.
62 close: K,
63 /// The pattern the group's contents must match, in full.
64 body: Vec<Pattern<K>>,
65 },
66 /// Captures one tree under `name` — a metavariable, `$name:fragment`.
67 Bind {
68 /// The metavariable name the template refers to. Unique within a rule.
69 name: Symbol,
70 /// What the captured tree may be.
71 fragment: Fragment<K>,
72 },
73 /// Matches `body` repeatedly — `$( ... ) sep kleene`.
74 ///
75 /// Every metavariable bound inside the body captures one tree per
76 /// repetition, and a template must expand it inside a matching
77 /// [`Template::Repeat`](crate::Template::Repeat).
78 Repeat {
79 /// The pattern matched on each repetition. It must consume at least one
80 /// tree; a body that can match nothing is rejected, since it could
81 /// repeat forever.
82 body: Vec<Pattern<K>>,
83 /// A token kind required between repetitions, such as `,`. Not allowed
84 /// with [`Kleene::ZeroOrOne`], which never repeats.
85 separator: Option<K>,
86 /// How many repetitions are allowed.
87 kleene: Kleene,
88 },
89}
90
91/// What a [`Pattern::Bind`] may capture: the fragment specifier.
92///
93/// macro-lang knows no grammar, so it cannot offer `expr` or `ty` fragments;
94/// those need a parser. What it can offer is the structural fragment every
95/// macro system has — any single token tree — and a token-level test the
96/// language supplies, which covers specifiers like `ident` and `literal`.
97///
98/// The enum is `#[non_exhaustive]` so that new fragment kinds can be added in a
99/// minor release; code that matches on a `Fragment` needs a wildcard arm.
100///
101/// # Examples
102///
103/// ```
104/// use macro_lang::Fragment;
105///
106/// // Any single tree: a token or a whole delimited group (`$x:tt`).
107/// let any: Fragment<char> = Fragment::Tree;
108///
109/// // A single token whose kind passes a test (`$x:ident`).
110/// let ident: Fragment<char> = Fragment::Kind(|c: &char| c.is_alphabetic());
111///
112/// assert!(matches!(any, Fragment::Tree));
113/// assert!(matches!(ident, Fragment::Kind(test) if test(&'x') && !test(&'1')));
114/// ```
115#[derive(Clone, Copy, Debug)]
116#[non_exhaustive]
117pub enum Fragment<K> {
118 /// Any single token tree: one token, or one whole delimited group. This is
119 /// the `tt` specifier.
120 Tree,
121 /// A single token (never a group) whose kind satisfies the test — for
122 /// example `Fragment::Kind(Kind::is_ident)` for an `ident` specifier.
123 Kind(fn(&K) -> bool),
124}
125
126/// How many times a [`Pattern::Repeat`] may match: the Kleene operator.
127///
128/// # Examples
129///
130/// ```
131/// use macro_lang::Kleene;
132///
133/// assert!(Kleene::ZeroOrMore.allows(0));
134/// assert!(!Kleene::OneOrMore.allows(0));
135/// assert!(!Kleene::ZeroOrOne.allows(2));
136/// ```
137#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
138pub enum Kleene {
139 /// Any number of repetitions, including none — `*`.
140 ZeroOrMore,
141 /// At least one repetition — `+`.
142 OneOrMore,
143 /// At most one repetition — `?`.
144 ZeroOrOne,
145}
146
147impl Kleene {
148 /// Returns `true` if a repetition may match exactly `count` times.
149 ///
150 /// # Examples
151 ///
152 /// ```
153 /// use macro_lang::Kleene;
154 ///
155 /// assert!(Kleene::OneOrMore.allows(3));
156 /// assert!(Kleene::ZeroOrOne.allows(0));
157 /// assert!(Kleene::ZeroOrOne.allows(1));
158 /// ```
159 #[inline]
160 #[must_use]
161 pub const fn allows(self, count: usize) -> bool {
162 match self {
163 Self::ZeroOrMore => true,
164 Self::OneOrMore => count >= 1,
165 Self::ZeroOrOne => count <= 1,
166 }
167 }
168}
169
170#[cfg(test)]
171mod tests {
172 use super::*;
173
174 #[test]
175 fn test_kleene_bounds() {
176 for count in 0..4 {
177 assert!(Kleene::ZeroOrMore.allows(count));
178 assert_eq!(Kleene::OneOrMore.allows(count), count >= 1);
179 assert_eq!(Kleene::ZeroOrOne.allows(count), count <= 1);
180 }
181 }
182
183 #[test]
184 fn test_fragment_kind_calls_the_test() {
185 let digit: Fragment<char> = Fragment::Kind(|c: &char| c.is_ascii_digit());
186 assert!(matches!(digit, Fragment::Kind(test) if test(&'7') && !test(&'x')));
187 }
188}