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
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
pub mod expr;
pub mod stmt;
pub mod build;
mod display;
use crate::prelude::*;
use crate::error::{
ParseError,
ParseResult,
};
pub use self::expr::*;
pub use self::stmt::*;
#[derive(Debug)]
pub struct Program {
pub body: BlockStatement, globals: Vec<Binding>, }
impl Program {
pub fn globals_iter(&self) -> impl Iterator<Item = &Binding> {
self.globals.iter()
}
pub fn bindings_iter(&self) -> BlockBindings {
self.body.bindings_iter()
}
}
impl PartialEq for Program {
fn eq(&self, other: &Self) -> bool {
self.body == other.body
}
}
impl Eq for Program {}
impl TryFrom<Expression> for Program {
type Error = ParseError;
fn try_from(expr: Expression) -> Result<Self, Self::Error> {
LexicalContext::new_program(|ctx| ctx.block(|_| Ok(vec![Statement::from(expr)])))
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Binding {
kind: DeclarationKind,
name: Identifier,
func: Option<Rc<Function>>,
}
impl Binding {
pub fn name(&self) -> &Identifier {
&self.name
}
pub fn as_func(&self) -> Option<FunctionExpression> {
self.func.clone().map(|func| FunctionExpression { func })
}
pub fn as_letconst(&self) -> Option<LetConst> {
use DeclarationKind::*;
if self.kind != Let && self.kind != Const {
return None;
}
let is_const = self.kind == Const;
Some(LetConst {
name: self.name.clone(),
is_const,
})
}
pub fn is_const(&self) -> bool {
self.kind == DeclarationKind::Const
}
}
impl Default for Binding {
fn default() -> Self {
Binding {
kind: DeclarationKind::Var, name: Identifier::from(""),
func: None,
}
}
}
impl From<FuncBinding> for Binding {
fn from(fb: FuncBinding) -> Self {
Binding {
kind: DeclarationKind::Var,
name: fb.name,
func: Some(fb.func),
}
}
}
impl From<LetConst> for Binding {
fn from(lb: LetConst) -> Self {
let kind = if lb.is_const {
DeclarationKind::Const
} else {
DeclarationKind::Let
};
Binding {
kind,
name: lb.name,
func: None,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LetConst {
name: Identifier,
is_const: bool,
}
#[derive(Debug, Clone)]
pub struct FuncBinding {
name: Identifier,
func: Rc<Function>,
}
impl FuncBinding {
pub fn name(&self) -> &str {
self.name.as_str()
}
}
#[derive(Debug)]
pub struct LexicalContext {
declarations: Vec<Binding>,
let_names: HashSet<Identifier>, used_ids: HashSet<Identifier>, }
impl LexicalContext {
pub fn new_program<F>(action: F) -> ParseResult<Program>
where
F: FnOnce(&mut LexicalContext) -> ParseResult<BlockStatement>,
{
let mut this = LexicalContext::default();
let mut body = action(&mut this)?;
let functions = core::mem::take(&mut body.functions);
let mut globals = this.declarations; globals.extend(functions.into_iter().map(Binding::from));
Ok(Program { body, globals })
}
pub fn id(&mut self, name: &str) -> Expression {
Expression::from(self.new_id(JSString::from(name)))
}
pub fn new_id(&mut self, name: JSString) -> Identifier {
let id = Identifier(name);
self.used_ids.insert(id.clone());
id
}
pub fn var(&mut self, name: &str) -> ParseResult<Statement> {
let kind = DeclarationKind::Var;
let name = Identifier::from(name);
self.declare_var(kind, &name)?;
let declarations = vec![(name, None)];
Ok(Statement::from(VariableDeclaration { kind, declarations }))
}
pub fn var_(&mut self, name: &str, initexpr: Expression) -> ParseResult<Statement> {
let kind = DeclarationKind::Var;
let name = Identifier::from(name);
self.declare_var(kind, &name)?;
let declarations = vec![(name, Some(initexpr))];
Ok(Statement::from(VariableDeclaration { kind, declarations }))
}
pub fn declare_var(&mut self, kind: DeclarationKind, name: &Identifier) -> ParseResult<()> {
let binding = Binding {
kind,
name: name.clone(),
func: None,
};
if let Some(lb) = binding.as_letconst() {
if !self.let_names.insert(lb.name) {
return Err(ParseError::BindingRedeclared { name: name.clone() });
}
}
self.declarations.push(binding);
Ok(())
}
pub fn function<F>(&mut self, argnames: &[&str], body: F) -> ParseResult<Expression>
where
F: FnMut(&mut LexicalContext) -> ParseResult<Vec<Statement>>,
{
let func = self.enter_function(|ctx| {
let mut params = vec![];
for &arg in argnames {
ctx.var(arg)?;
params.push(Identifier::from(arg));
}
let body = ctx.enter_block(body)?;
Ok((None, params, body))
})?;
let func = Rc::new(func);
Ok(Expression::from(FunctionExpression { func }))
}
pub fn declare_func(&mut self, function: &FunctionDeclaration) -> ParseResult<()> {
self.declarations.push(Binding {
kind: DeclarationKind::Var,
name: function.get_name(),
func: Some(Rc::clone(&function.func)),
});
Ok(())
}
pub fn block<F>(&mut self, action: F) -> ParseResult<BlockStatement>
where
F: FnOnce(&mut Self) -> ParseResult<Vec<Statement>>,
{
self.enter_block(action)
}
pub fn enter_block<F>(&mut self, action: F) -> ParseResult<BlockStatement>
where
F: FnOnce(&mut LexicalContext) -> ParseResult<Vec<Statement>>,
{
let mut inner_ctx = LexicalContext::default();
let result = action(&mut inner_ctx);
let (functions, bindings) = self.consume(inner_ctx)?;
let body = result?;
Ok(BlockStatement {
body,
functions,
bindings,
})
}
pub fn enter_function<F>(&mut self, action: F) -> ParseResult<Function>
where
F: FnOnce(
&mut LexicalContext,
) -> ParseResult<(Option<Identifier>, Vec<Pattern>, BlockStatement)>,
{
let mut ctx = LexicalContext::default();
ctx.var("arguments")?;
let (id, params, body) = action(&mut ctx)?;
let locals = ctx.drain_declarations()?;
let free_variables = Vec::from_iter(ctx.used_ids.iter().cloned());
Ok(Function {
id,
params,
body,
locals,
free_variables,
})
}
fn split_off_block_bindings(&mut self) -> ParseResult<(Vec<FuncBinding>, Vec<LetConst>)> {
use DeclarationKind::*;
let mut lets = Vec::new();
let mut funcs = HashMap::<Identifier, Rc<Function>>::new();
let mut var_at = 0;
for at in 0..self.declarations.len() {
let name = self.declarations[at].name.clone();
self.used_ids.remove(&name);
if let Some(func) = self.declarations[at].func.take() {
if self.let_names.contains(&name) {
return Err(ParseError::BindingRedeclared { name });
}
funcs.insert(name, func);
continue;
}
let kind = self.declarations[at].kind;
match kind {
Var => {
if var_at != at {
self.declarations[var_at] = Binding::default();
self.declarations.as_mut_slice().swap(var_at, at);
}
var_at += 1;
}
Let | Const => {
let is_const = kind == Const;
lets.push(LetConst { name, is_const })
}
}
}
let funcs = Vec::from_iter(funcs.drain().map(|(name, func)| FuncBinding { name, func }));
self.declarations.truncate(var_at);
self.let_names = HashSet::new(); Ok((funcs, lets))
}
fn consume(&mut self, mut other: Self) -> ParseResult<(Vec<FuncBinding>, Vec<LetConst>)> {
let (functions, bindings) = other.split_off_block_bindings()?;
self.used_ids.extend(other.used_ids.into_iter());
self.declarations.extend(other.declarations.into_iter()); Ok((functions, bindings))
}
fn drain_declarations(&mut self) -> ParseResult<Vec<Binding>> {
let vars = core::mem::take(&mut self.declarations);
for b in vars.iter() {
self.used_ids.remove(b.name());
}
Ok(vars)
}
}
impl Default for LexicalContext {
fn default() -> Self {
LexicalContext {
declarations: Vec::new(),
let_names: HashSet::new(),
used_ids: HashSet::new(),
}
}
}