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
|
use ra_syntax::SmolStr;
use crate::macros::tt;
#[derive(Debug)]
pub(crate) struct MacroRules {
rules: Vec<Rule>,
}
#[derive(Debug)]
struct Rule {
lhs: Subtree,
rhs: Subtree,
}
#[derive(Debug)]
enum TokenTree {
Leaf(Leaf),
Subtree(Subtree),
Repeat(Repeat),
}
#[derive(Debug)]
enum Leaf {
Literal(Literal),
Punct(Punct),
Ident(Ident),
Var(Var),
}
#[derive(Debug)]
struct Subtree {
delimiter: Delimiter,
token_trees: Vec<TokenTree>,
}
#[derive(Debug)]
enum Delimiter {
Parenthesis,
Brace,
Bracket,
None,
}
#[derive(Debug)]
struct Repeat {
subtree: Subtree,
kind: RepeatKind,
}
#[derive(Debug)]
enum RepeatKind {
ZeroOrMore,
OneOrMore,
ZeroOrOne,
}
#[derive(Debug)]
struct Literal {
text: SmolStr,
}
#[derive(Debug)]
struct Punct {
char: char,
}
#[derive(Debug)]
struct Ident {
text: SmolStr,
}
#[derive(Debug)]
struct Var {
text: SmolStr,
}
pub(crate) fn parse(tt: &tt::Subtree) -> Option<MacroRules> {
let mut parser = RulesParser::new(tt);
let mut rules = Vec::new();
while !parser.is_eof() {
rules.push(parse_rule(&mut parser)?)
}
Some(MacroRules { rules })
}
fn parse_rule(p: &mut RulesParser) -> Option<Rule> {
let lhs = parse_subtree(p.eat_subtree()?)?;
p.eat_punct('=')?;
p.eat_punct('>')?;
let rhs = parse_subtree(p.eat_subtree()?)?;
Some(Rule { lhs, rhs })
}
fn parse_subtree(tt: &tt::Subtree) -> Option<Subtree> {
Some(Subtree {
token_trees: Vec::new(),
delimiter: Delimiter::None,
})
}
struct RulesParser<'a> {
subtree: &'a tt::Subtree,
pos: usize,
}
impl<'a> RulesParser<'a> {
fn new(subtree: &'a tt::Subtree) -> RulesParser<'a> {
RulesParser { subtree, pos: 0 }
}
fn is_eof(&self) -> bool {
self.pos == self.subtree.token_trees.len()
}
fn current(&self) -> Option<&'a tt::TokenTree> {
self.subtree.token_trees.get(self.pos)
}
fn bump(&mut self) {
self.pos += 1;
}
fn eat_subtree(&mut self) -> Option<&'a tt::Subtree> {
match self.current()? {
tt::TokenTree::Subtree(sub) => {
self.bump();
Some(sub)
}
_ => return None,
}
}
fn eat_punct(&mut self, char: char) -> Option<()> {
match self.current()? {
tt::TokenTree::Leaf(tt::Leaf::Punct(tt::Punct { char: c })) if *c == char => {
self.bump();
Some(())
}
_ => None,
}
}
}
|