/
flimsy_syntax.rs
285 lines (265 loc) · 10.3 KB
/
flimsy_syntax.rs
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
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
#![macro_use]
// For testing purposes, we want to generate valid Asts without a full-fledged parser.
// `ast!` is clunky and makes it *super* easy to leave off `QuoteMore`, `QuoteLess`, and `ExtendEnv`
// We'll assume that the form itself is known and that we can drop all the literals on the ground.
// The result is a terse way to make valid ASTs.
// It's weird to be relying on the grammar while ignoring parts of it, hence "flimsy",
// but errors are much more likely to be compile-time than inscrutable test problems.
use ast::Ast::{self, *};
use grammar::FormPat;
use name::*;
use std::iter::{Iterator, Peekable};
use util::mbe::EnvMBE;
// First, transforms from `[a b c; d e f; g h i]` to `[g h i] {[a b c] [d e f]}`
// to get around a Rust macro parsing restriction,
// then makes a REP flimsy shape for it.
macro_rules! u_rep {
([; $( $ts:tt )*] $acc_cur:tt { $( $acc_rest:tt )* }) => {
u_rep!( [ $( $ts )* ] [] { $( $acc_rest )* $acc_cur })
};
([$t:tt $( $ts:tt )*] [ $( $acc_cur:tt )* ] { $( $acc_rest:tt )* }) => {
u_rep!( [ $( $ts )* ] [$($acc_cur)* $t] { $( $acc_rest )* })
};
([] [] {}) => {
// Empty repeat
::ast::Shape(vec![::ast::Atom(n("REP"))])
};
([] [ $( $acc_cur:tt )* ] { $( [ $( $acc_rest:tt )* ] )* }) => {
::ast::Shape(vec![
::ast::Atom(n("REP")),
$( u!( $($acc_rest)* ), )*
u!( $($acc_cur)* )
])
};
}
thread_local! {
pub static default_nt: std::cell::RefCell<String> = std::cell::RefCell::new("Expr".to_owned());
}
macro_rules! u {
($atom:ident) => {
// Default to this, because `Call` will use whatever it's given, without a grammar:
::ast::VariableReference(n(stringify!($atom)))
};
( [ $( $ts:tt )* ] ) => {
u_rep!( [$($ts)*] [] {} )
};
( { $form:ident : $( $ts:tt )*} ) => {
{
::macros::flimsy_syntax::default_nt.with(|def_nt| {
let f = ::core_forms::find_core_form(&def_nt.borrow(), stringify!($form));
::ast::Node(f.clone(),
::macros::flimsy_syntax::parse_flimsy_mbe(&u!( (~ $($ts)* ) ), &f.grammar)
.unwrap_or_else(::util::mbe::EnvMBE::new),
::beta::ExportBeta::Nothing)
})
}
};
( { $nt:ident $form:ident : $( $ts:tt )*} ) => {
{
let mut old_default_nt = "".to_owned();
let f = ::macros::flimsy_syntax::default_nt.with(|def_nt| {
old_default_nt = def_nt.borrow().clone();
let nt = stringify!($nt);
*def_nt.borrow_mut() = nt.to_string();
::core_forms::find_core_form(&nt, stringify!($form))
});
let res = ::ast::Node(f.clone(),
::macros::flimsy_syntax::parse_flimsy_mbe(&u!( (~ $($ts)* ) ), &f.grammar)
.unwrap_or_else(::util::mbe::EnvMBE::new),
::beta::ExportBeta::Nothing);
::macros::flimsy_syntax::default_nt.with(|def_nt| {
*def_nt.borrow_mut() = old_default_nt;
});
res
}
};
// The need for explicit exports is unfortunate;
// that information is part of `Scope`, not `Form` (maybe we should change that?)
( { $form:ident => $ebeta:tt : $( $ts:tt )*} ) => {
{
::macros::flimsy_syntax::default_nt.with(|def_nt| {
let f = ::core_forms::find_core_form(&def_nt.borrow(), stringify!($form));
::ast::Node(f.clone(),
::macros::flimsy_syntax::parse_flimsy_mbe(&u!( (~ $($ts)* ) ), &f.grammar)
.unwrap_or_else(::util::mbe::EnvMBE::new),
ebeta!($ebeta))
})
}
};
( { $nt:ident $form:ident => $ebeta:tt : $( $ts:tt )*} ) => {
{
// code duplication from above ) :
let mut old_default_nt = "".to_owned();
let f = ::macros::flimsy_syntax::default_nt.with(|def_nt| {
old_default_nt = def_nt.borrow().clone();
let nt = stringify!($nt);
*def_nt.borrow_mut() = nt.to_string();
::core_forms::find_core_form(&nt, stringify!($form))
});
let res =::ast::Node(f.clone(),
::macros::flimsy_syntax::parse_flimsy_mbe(&u!( (~ $($ts)* ) ), &f.grammar)
.unwrap_or_else(::util::mbe::EnvMBE::new),
ebeta!($ebeta));
::macros::flimsy_syntax::default_nt.with(|def_nt| {
*def_nt.borrow_mut() = old_default_nt;
});
res
}
};
( { $form:expr ; $( $ts:tt )*} ) => {
{
let f = $form;
::ast::Node(f.clone(),
::macros::flimsy_syntax::parse_flimsy_mbe(&u!( (~ $($ts)* ) ), &f.grammar)
.unwrap_or_else(::util::mbe::EnvMBE::new),
::beta::ExportBeta::Nothing)
}
};
({ $( $anything:tt )* }) => {
panic!("Needed a : or ; in u!");
};
// Currently, nested `Seq`s need to correspond to nested `SEQ`s, so this creates one explicitly:
((~ $($ts:tt)*)) => {
::ast::Shape(vec![
::ast::Atom(n("SEQ")),
$( u!( $ts ) ),*
])
};
((at $t:tt)) => {
::ast::Atom(n(stringify!($t)))
};
((prim $t:tt)) => {
::core_type_forms::get__primitive_type(n(stringify!($t))).concrete()
};
((, $interpolate:expr)) => {
$interpolate
};
// Two or more token trees (avoid infinite regress)
( $t_first:tt $t_second:tt $( $t:tt )* ) => {
::ast::Shape(vec![
::ast::Atom(n("SEQ")),
u!( $t_first ), u!( $t_second ), $( u!( $t ) ),*
])
};
}
macro_rules! uty {
($( $ts:tt )*) => {
{
let mut old_default_nt = "".to_owned();
::macros::flimsy_syntax::default_nt.with(|def_nt| {
old_default_nt = def_nt.borrow().clone();
*def_nt.borrow_mut() = "Type".to_owned();
});
let res = Ty(u!( $($ts)* ));
::macros::flimsy_syntax::default_nt.with(|def_nt| {
*def_nt.borrow_mut() = old_default_nt;
});
res
}
};
}
fn parse_flimsy_seq<'a, I>(flimsy_seq: &mut Peekable<I>, grammar: &FormPat) -> EnvMBE<Ast>
where I: Iterator<Item = &'a Ast> {
use grammar::FormPat::*;
match grammar {
Seq(ref grammar_parts) => {
let mut result = EnvMBE::new();
for grammar_part in grammar_parts {
result = result.combine_overriding(&parse_flimsy_seq(flimsy_seq, grammar_part));
}
result
}
_ => {
let flimsy = *match flimsy_seq.peek() {
None => return EnvMBE::new(), // Or is this an error?
Some(f) => f,
};
match parse_flimsy_mbe(flimsy, grammar) {
None => EnvMBE::new(),
Some(res) => {
// `Anyways`es shouldn't consume anything (and they'll always be `Named`):
let consuming = match grammar {
Named(_, ref body) => match **body {
Anyways(_) => false,
_ => true,
},
_ => true,
};
if consuming {
let _ = flimsy_seq.next();
}
res
}
}
}
}
}
pub fn parse_flimsy_mbe(flimsy: &Ast, grammar: &FormPat) -> Option<EnvMBE<Ast>> {
use grammar::FormPat::*;
match grammar {
Literal(_, _) => None,
Seq(_) => match flimsy {
Shape(flimsy_parts) => {
if flimsy_parts[0] != Atom(n("SEQ")) {
panic!("Needed a SEQ, got {}", flimsy)
}
let mut fpi = flimsy_parts[1..].iter().peekable();
Some(parse_flimsy_seq(&mut fpi, grammar))
}
_ => panic!("Needed a SEQ shape, got {}", flimsy),
},
Star(ref body) | Plus(ref body) => match flimsy {
Shape(flimsy_parts) => {
if flimsy_parts[0] != Atom(n("REP")) {
panic!("Need a REP")
}
let mut reps = vec![];
for flimsy_part in flimsy_parts[1..].iter() {
reps.push(parse_flimsy_mbe(flimsy_part, &*body).unwrap());
}
Some(EnvMBE::new_from_anon_repeat(reps))
}
_ => panic!("Needed a REP shape"),
},
Alt(ref subs) => {
// HACK: always pick the first branch of the `Alt`
// (mainly affects unquotation, where it skips the type annotation)
parse_flimsy_mbe(flimsy, &*subs[0])
}
Named(name, ref body) => Some(EnvMBE::new_from_leaves(
::util::assoc::Assoc::new().set(*name, parse_flimsy_ast(flimsy, &*body)),
)),
SynImport(_, _, _) => panic!("`SynImport` can't work without a real parser"),
NameImport(_, _) => panic!("`NameImport` should live underneath `Named`: {:?}", grammar),
_ => unimplemented!("Can't handle {:?}", grammar),
}
}
fn parse_flimsy_ast(flimsy: &Ast, grammar: &FormPat) -> Ast {
use grammar::FormPat::*;
match grammar {
Anyways(ref a) => a.clone(),
Impossible => unimplemented!(),
Literal(_, _) => Trivial,
VarRef(_) => match flimsy {
VariableReference(a) => VariableReference(*a),
non_atom => panic!("Needed an atom, got {}", non_atom),
},
NameImport(body, beta) => {
ExtendEnv(Box::new(parse_flimsy_ast(flimsy, &*body)), beta.clone())
}
QuoteDeepen(body, pos) => QuoteMore(Box::new(parse_flimsy_ast(flimsy, &*body)), *pos),
QuoteEscape(body, depth) => QuoteLess(Box::new(parse_flimsy_ast(flimsy, &*body)), *depth),
Call(name) => {
// HACK: don't descend into `Call(n("DefaultName"))
if *name == n("DefaultName") {
match flimsy {
VariableReference(a) => Atom(*a),
non_atom => panic!("Needed an atom, got {}", non_atom),
}
} else {
flimsy.clone()
}
}
_ => unimplemented!(),
}
}