aboutsummaryrefslogtreecommitdiff
path: root/crates/mbe/src/parser.rs
blob: d681905f5728f1b093c0ca88763edc2edfb1353c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
//! Parser recognizes special macro syntax, `$var` and `$(repeat)*`, in token
//! trees.

use smallvec::SmallVec;
use syntax::SmolStr;

use crate::{tt_iter::TtIter, ExpandError};

#[derive(Debug)]
pub(crate) enum Op<'a> {
    Var { name: &'a SmolStr, kind: Option<&'a SmolStr> },
    Repeat { subtree: &'a tt::Subtree, kind: RepeatKind, separator: Option<Separator> },
    TokenTree(&'a tt::TokenTree),
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) enum RepeatKind {
    ZeroOrMore,
    OneOrMore,
    ZeroOrOne,
}

#[derive(Clone, Debug, Eq)]
pub(crate) enum Separator {
    Literal(tt::Literal),
    Ident(tt::Ident),
    Puncts(SmallVec<[tt::Punct; 3]>),
}

// Note that when we compare a Separator, we just care about its textual value.
impl PartialEq for Separator {
    fn eq(&self, other: &Separator) -> bool {
        use Separator::*;

        match (self, other) {
            (Ident(ref a), Ident(ref b)) => a.text == b.text,
            (Literal(ref a), Literal(ref b)) => a.text == b.text,
            (Puncts(ref a), Puncts(ref b)) if a.len() == b.len() => {
                let a_iter = a.iter().map(|a| a.char);
                let b_iter = b.iter().map(|b| b.char);
                a_iter.eq(b_iter)
            }
            _ => false,
        }
    }
}

pub(crate) fn parse_template(
    template: &tt::Subtree,
) -> impl Iterator<Item = Result<Op<'_>, ExpandError>> {
    parse_inner(template, Mode::Template)
}

pub(crate) fn parse_pattern(
    pattern: &tt::Subtree,
) -> impl Iterator<Item = Result<Op<'_>, ExpandError>> {
    parse_inner(pattern, Mode::Pattern)
}

#[derive(Clone, Copy)]
enum Mode {
    Pattern,
    Template,
}

fn parse_inner(src: &tt::Subtree, mode: Mode) -> impl Iterator<Item = Result<Op<'_>, ExpandError>> {
    let mut src = TtIter::new(src);
    std::iter::from_fn(move || {
        let first = src.next()?;
        Some(next_op(first, &mut src, mode))
    })
}

macro_rules! err {
    ($($tt:tt)*) => {
        ExpandError::UnexpectedToken
    };
}

macro_rules! bail {
    ($($tt:tt)*) => {
        return Err(err!($($tt)*))
    };
}

fn next_op<'a>(
    first: &'a tt::TokenTree,
    src: &mut TtIter<'a>,
    mode: Mode,
) -> Result<Op<'a>, ExpandError> {
    let res = match first {
        tt::TokenTree::Leaf(tt::Leaf::Punct(tt::Punct { char: '$', .. })) => {
            // Note that the '$' itself is a valid token inside macro_rules.
            let second = match src.next() {
                None => return Ok(Op::TokenTree(first)),
                Some(it) => it,
            };
            match second {
                tt::TokenTree::Subtree(subtree) => {
                    let (separator, kind) = parse_repeat(src)?;
                    Op::Repeat { subtree, separator, kind }
                }
                tt::TokenTree::Leaf(leaf) => match leaf {
                    tt::Leaf::Punct(punct) => {
                        static UNDERSCORE: SmolStr = SmolStr::new_inline("_");

                        if punct.char != '_' {
                            return Err(ExpandError::UnexpectedToken);
                        }
                        let name = &UNDERSCORE;
                        let kind = eat_fragment_kind(src, mode)?;
                        Op::Var { name, kind }
                    }
                    tt::Leaf::Ident(ident) => {
                        let name = &ident.text;
                        let kind = eat_fragment_kind(src, mode)?;
                        Op::Var { name, kind }
                    }
                    tt::Leaf::Literal(lit) => {
                        if is_boolean_literal(lit) {
                            let name = &lit.text;
                            let kind = eat_fragment_kind(src, mode)?;
                            Op::Var { name, kind }
                        } else {
                            bail!("bad var 2");
                        }
                    }
                },
            }
        }
        tt => Op::TokenTree(tt),
    };
    Ok(res)
}

fn eat_fragment_kind<'a>(
    src: &mut TtIter<'a>,
    mode: Mode,
) -> Result<Option<&'a SmolStr>, ExpandError> {
    if let Mode::Pattern = mode {
        src.expect_char(':').map_err(|()| err!("bad fragment specifier 1"))?;
        let ident = src.expect_ident().map_err(|()| err!("bad fragment specifier 1"))?;
        return Ok(Some(&ident.text));
    };
    Ok(None)
}

fn is_boolean_literal(lit: &tt::Literal) -> bool {
    matches!(lit.text.as_str(), "true" | "false")
}

fn parse_repeat(src: &mut TtIter) -> Result<(Option<Separator>, RepeatKind), ExpandError> {
    let mut separator = Separator::Puncts(SmallVec::new());
    for tt in src {
        let tt = match tt {
            tt::TokenTree::Leaf(leaf) => leaf,
            tt::TokenTree::Subtree(_) => return Err(ExpandError::InvalidRepeat),
        };
        let has_sep = match &separator {
            Separator::Puncts(puncts) => !puncts.is_empty(),
            _ => true,
        };
        match tt {
            tt::Leaf::Ident(_) | tt::Leaf::Literal(_) if has_sep => {
                return Err(ExpandError::InvalidRepeat)
            }
            tt::Leaf::Ident(ident) => separator = Separator::Ident(ident.clone()),
            tt::Leaf::Literal(lit) => separator = Separator::Literal(lit.clone()),
            tt::Leaf::Punct(punct) => {
                let repeat_kind = match punct.char {
                    '*' => RepeatKind::ZeroOrMore,
                    '+' => RepeatKind::OneOrMore,
                    '?' => RepeatKind::ZeroOrOne,
                    _ => {
                        match &mut separator {
                            Separator::Puncts(puncts) => {
                                if puncts.len() == 3 {
                                    return Err(ExpandError::InvalidRepeat);
                                }
                                puncts.push(punct.clone())
                            }
                            _ => return Err(ExpandError::InvalidRepeat),
                        }
                        continue;
                    }
                };
                let separator = if has_sep { Some(separator) } else { None };
                return Ok((separator, repeat_kind));
            }
        }
    }
    Err(ExpandError::InvalidRepeat)
}