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
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
pub mod estree;
mod heapnode;
mod jsonnode;
#[cfg(test)]
mod test;

use crate::ast::*;
use crate::prelude::*; // yes, EVERYTHING.

use crate::{
    error::{
        ParseError,
        ParseResult,
    },
    source,
    JSON,
};

pub use self::heapnode::HeapNode;

/// `ParseFrom` is a unifying interface for constructing all `ast::*` types.
///
/// It's not strictly necessary, `impl ast::X { fn parse_from(...) -> ParseResult<X> {...} }`
/// would do just fine. On the other hand, it feels like a good idea to have all of these
/// to conform to one interface.
trait ParseFrom: Sized {
    fn parse_from<S>(source: &S, ctx: &mut LexicalContext) -> ParseResult<Self>
    where
        S: SourceNode;
}

/// `SourceNode` is how `ParseFrom::parse_from` sees AST nodes.
pub trait SourceNode: Sized {
    /// Location of the node where an error happened.
    fn to_error(&self) -> JSON;

    /// Try to get source mapping for `self`.
    fn get_location(&self) -> Option<source::Location>;

    /// Use the node as a literal.
    fn get_literal(&self, property: &str) -> ParseResult<Literal>;

    /// Get the boolean value of a child node with name `property`.
    /// It's a ParseError if it does not exist or does not have a boolean meaning.
    fn get_bool(&self, property: &str) -> ParseResult<bool>;

    /// Get the string value of a child node with name `property`.
    /// It's a ParseError if it does not exist or does not have a string meaning.
    fn get_str(&self, property: &str) -> ParseResult<JSString>;

    /// Check that the value of `property` is a string equal to `value`.
    /// Depends on [`SourceNode::get_str`].
    fn expect_str(&self, property: &str, value: &'static str) -> ParseResult<()> {
        let got = self.get_str(property)?;
        match got.as_str() == value {
            true => Ok(()),
            false => Err(ParseError::UnexpectedValue {
                want: value,
                value: self.to_error(),
            }),
        }
    }

    /// Get a child node with this name; if it does not exist, return None.
    /// Then transform it through `action`, propagating its Result out.
    /// A child node exis
    fn map_node<T, F>(&self, property: &str, action: F) -> ParseResult<T>
    where
        F: FnMut(&Self) -> ParseResult<T>;

    fn map_opt_node<T, F>(&self, property: &str, action: F) -> ParseResult<Option<T>>
    where
        F: FnMut(&Self) -> ParseResult<T>,
    {
        match self.map_node(property, action) {
            Ok(stmt) => Ok(Some(stmt)),
            Err(ParseError::ObjectWithout { .. }) => Ok(None),
            Err(e) => Err(e),
        }
    }

    /// Map the array of children of a child node with name `property`.
    /// It's a ParseError if it does not exist or does not have an array meaning.
    fn map_array<T, F>(&self, property: &str, func: F) -> ParseResult<Vec<T>>
    where
        F: FnMut(&Self) -> ParseResult<T>;
}

impl Program {
    /// Makes a [`Program`] from anything that implements [`SourceNode`]
    ///
    /// e.g. from a [`JSON`] ESTree.
    pub fn parse_from<S: SourceNode>(source: &S) -> ParseResult<Program> {
        source.expect_str("type", "Program")?;

        LexicalContext::new_program(|ctx| BlockStatement::parse_from(source, ctx))
    }
}

impl ParseFrom for Statement {
    fn parse_from<S: SourceNode>(source: &S, ctx: &mut LexicalContext) -> ParseResult<Self> {
        let loc = source.get_location().map(Box::new);

        let typ = source.get_str("type")?;
        let stmt = match typ.as_str() {
            "BlockStatement" => Stmt::Block(BlockStatement::parse_from(source, ctx)?),
            "BreakStatement" => Stmt::Break(BreakStatement::parse_from(source, ctx)?),
            "ContinueStatement" => Stmt::Continue(ContinueStatement::parse_from(source, ctx)?),
            "DoWhileStatement" => {
                let stmt = DoWhileStatement::parse_from(source, ctx)?;
                Stmt::DoWhile(stmt)
            }
            "EmptyStatement" => Stmt::Empty,
            "ExpressionStatement" => Stmt::Expr(ExpressionStatement::parse_from(source, ctx)?),
            "ForStatement" | "WhileStatement" => {
                let stmt = ForStatement::parse_from(source, ctx)?;
                Stmt::For(Box::new(stmt))
            }
            "ForInStatement" => {
                let stmt = ForInStatement::parse_from(source, ctx)?;
                Stmt::ForIn(Box::new(stmt))
            }
            "FunctionDeclaration" => Stmt::Function(FunctionDeclaration::parse_from(source, ctx)?),
            "IfStatement" => {
                let stmt = IfStatement::parse_from(source, ctx)?;
                Stmt::If(Box::new(stmt))
            }
            "LabeledStatement" => {
                let stmt = LabelStatement::parse_from(source, ctx)?;
                Stmt::Label(Box::new(stmt))
            }
            "ReturnStatement" => Stmt::Return(ReturnStatement::parse_from(source, ctx)?),
            "SwitchStatement" => Stmt::Switch(SwitchStatement::parse_from(source, ctx)?),
            "ThrowStatement" => Stmt::Throw(ThrowStatement::parse_from(source, ctx)?),
            "TryStatement" => Stmt::Try(TryStatement::parse_from(source, ctx)?),
            "VariableDeclaration" => Stmt::Variable(VariableDeclaration::parse_from(source, ctx)?),
            unknown => {
                let value = serde_json::json!({"type": unknown, "source": source.to_error()});
                return Err(ParseError::UnknownNodeType { value });
            }
        };
        Ok(Statement { stmt, loc })
    }
}

impl ParseFrom for BlockStatement {
    fn parse_from<S: SourceNode>(source: &S, ctx: &mut LexicalContext) -> ParseResult<Self> {
        // "type" can be: "Program", "BlockStatement"
        ctx.enter_block(|ctx| source.map_array("body", |jstmt| Statement::parse_from(jstmt, ctx)))
    }
}

impl ParseFrom for IfStatement {
    fn parse_from<S: SourceNode>(source: &S, ctx: &mut LexicalContext) -> ParseResult<Self> {
        source.expect_str("type", "IfStatement")?;

        let test = source.map_node("test", |jtest| Expression::parse_from(jtest, ctx))?;
        let consequent =
            source.map_node("consequent", |jthen| Statement::parse_from(jthen, ctx))?;
        let alternate =
            source.map_opt_node("alternate", |jelse| Statement::parse_from(jelse, ctx))?;

        Ok(IfStatement {
            test,
            consequent,
            alternate,
        })
    }
}

impl ParseFrom for SwitchStatement {
    fn parse_from<S: SourceNode>(source: &S, ctx: &mut LexicalContext) -> ParseResult<Self> {
        source.expect_str("type", "SwitchStatement")?;

        let discriminant = source.map_node("discriminant", |jdiscriminant| {
            Expression::parse_from(jdiscriminant, ctx)
        })?;

        let cases = source.map_array("cases", |jcase| {
            let test = jcase.map_opt_node("test", |jtest| Expression::parse_from(jtest, ctx))?;
            let consequent =
                jcase.map_array("consequent", |jstmt| Statement::parse_from(jstmt, ctx))?;
            Ok(SwitchCase { test, consequent })
        })?;

        Ok(SwitchStatement {
            discriminant,
            cases,
        })
    }
}

impl ParseFrom for ForStatement {
    fn parse_from<S: SourceNode>(source: &S, ctx: &mut LexicalContext) -> ParseResult<Self> {
        let for_ok = source.expect_str("type", "ForStatement");
        let while_ok = source.expect_str("type", "WhileStatement");
        for_ok.or(while_ok)?;

        let init = source.map_opt_node("init", |jinit| {
            //let loc = source.get_location();
            match jinit.get_str("type")?.as_str() {
                "VariableDeclaration" => {
                    let vardecls = VariableDeclaration::parse_from(jinit, ctx)?;
                    Ok(ForTarget::Var(vardecls))
                }
                "AssignmentExpression" => {
                    let expr = Expression::parse_from(jinit, ctx)?;
                    let expr = ExpressionStatement::from(expr);
                    Ok(ForTarget::Expr(expr))
                }
                ty => Err(ParseError::UnexpectedValue {
                    want: "variable or expression",
                    value: serde_json::json!({
                        "type": ty.to_string(),
                        "node": jinit.to_error(),
                    }),
                }),
            }
        })?;

        let test = source.map_opt_node("test", |jtest| Expression::parse_from(jtest, ctx))?;
        let update =
            source.map_opt_node("update", |jupdate| Expression::parse_from(jupdate, ctx))?;
        let body = source.map_node("body", |jbody| Statement::parse_from(jbody, ctx))?;
        Ok(ForStatement {
            init,
            test,
            update,
            body,
        })
    }
}

impl ParseFrom for ForInStatement {
    fn parse_from<S: SourceNode>(source: &S, ctx: &mut LexicalContext) -> ParseResult<Self> {
        source.expect_str("type", "ForInStatement")?;

        let left = source.map_node("left", |jleft| {
            if let Ok(vardecl) = VariableDeclaration::parse_from(jleft, ctx) {
                Ok(ForTarget::Var(vardecl))
            } else if let Ok(exprstmt) = ExpressionStatement::parse_from(jleft, ctx) {
                Ok(ForTarget::Expr(exprstmt))
            } else {
                Err(ParseError::UnexpectedValue {
                    want: "VariableDeclaration | Pattern",
                    value: jleft.to_error(),
                })
            }
        })?;
        let right = source.map_node("right", |jright| Expression::parse_from(jright, ctx))?;
        let body = source.map_node("body", |jbody| Statement::parse_from(jbody, ctx))?;
        Ok(ForInStatement { left, right, body })
    }
}

impl ParseFrom for DoWhileStatement {
    fn parse_from<S: SourceNode>(source: &S, ctx: &mut LexicalContext) -> ParseResult<Self> {
        let body = source.map_node("body", |jbody| Statement::parse_from(jbody, ctx))?;
        let body = Box::new(body);
        let test = source.map_opt_node("test", |jtest| Expression::parse_from(jtest, ctx))?;
        Ok(DoWhileStatement { body, test })
    }
}

impl ParseFrom for BreakStatement {
    fn parse_from<S: SourceNode>(source: &S, ctx: &mut LexicalContext) -> ParseResult<Self> {
        source.expect_str("type", "BreakStatement")?;

        let label = source.map_opt_node("label", |jlabel| Identifier::parse_from(jlabel, ctx))?;
        Ok(BreakStatement(label))
    }
}

impl ParseFrom for ContinueStatement {
    fn parse_from<S: SourceNode>(source: &S, ctx: &mut LexicalContext) -> ParseResult<Self> {
        source.expect_str("type", "ContinueStatement")?;

        let label = source.map_opt_node("label", |jlabel| Identifier::parse_from(jlabel, ctx))?;
        Ok(ContinueStatement(label))
    }
}

impl ParseFrom for LabelStatement {
    fn parse_from<S: SourceNode>(source: &S, ctx: &mut LexicalContext) -> ParseResult<Self> {
        source.expect_str("type", "LabeledStatement")?;

        let label = source.map_node("label", |jlabel| Identifier::parse_from(jlabel, ctx))?;
        let body = source.map_node("body", |jbody| Statement::parse_from(jbody, ctx))?;
        Ok(LabelStatement(label, body))
    }
}

impl ParseFrom for ReturnStatement {
    fn parse_from<S: SourceNode>(source: &S, ctx: &mut LexicalContext) -> ParseResult<Self> {
        source.expect_str("type", "ReturnStatement")?;

        let argument =
            source.map_opt_node("argument", |jobject| Expression::parse_from(jobject, ctx))?;
        Ok(ReturnStatement(argument))
    }
}

impl ParseFrom for ThrowStatement {
    fn parse_from<S: SourceNode>(source: &S, ctx: &mut LexicalContext) -> ParseResult<Self> {
        source.expect_str("type", "ThrowStatement")?;

        let argument = source.map_node("argument", |jarg| Expression::parse_from(jarg, ctx))?;
        Ok(ThrowStatement(argument))
    }
}

impl ParseFrom for TryStatement {
    fn parse_from<S: SourceNode>(source: &S, ctx: &mut LexicalContext) -> ParseResult<Self> {
        source.expect_str("type", "TryStatement")?;

        let block = source.map_node("block", |jblock| BlockStatement::parse_from(jblock, ctx))?;

        let handler = source.map_opt_node("handler", |jhandler| {
            let param = jhandler.map_node("param", |jparam| Identifier::parse_from(jparam, ctx))?;
            let body = jhandler.map_node("body", |jbody| BlockStatement::parse_from(jbody, ctx))?;
            Ok(CatchClause { param, body })
        })?;

        let finalizer = source.map_opt_node("finalizer", |jobject| {
            BlockStatement::parse_from(jobject, ctx)
        })?;

        Ok(TryStatement {
            block,
            handler,
            finalizer,
        })
    }
}

impl ParseFrom for VariableDeclaration {
    fn parse_from<S: SourceNode>(source: &S, ctx: &mut LexicalContext) -> ParseResult<Self> {
        source.expect_str("type", "VariableDeclaration")?;

        let kind = match source.get_str("kind")?.as_str() {
            "const" => DeclarationKind::Const,
            "let" => DeclarationKind::Let,
            "var" => DeclarationKind::Var,
            _ => {
                return Err(ParseError::UnexpectedValue {
                    want: "var | let | const",
                    value: source.map_node("kind", |node| Ok(node.to_error()))?,
                })?;
            }
        };
        let declarations = source.map_array("declarations", |decl| {
            decl.expect_str("type", "VariableDeclarator")?;

            let name = decl.map_node("id", |jid| Identifier::parse_from(jid, ctx))?;
            let init = decl.map_opt_node("init", |jinit| {
                let expr = Expression::parse_from(jinit, ctx)?;
                Ok(expr)
            })?;

            ctx.declare_var(kind, &name)?;
            Ok((name, init))
        })?;

        Ok(VariableDeclaration { kind, declarations })
    }
}

impl ParseFrom for FunctionDeclaration {
    fn parse_from<S: SourceNode>(source: &S, ctx: &mut LexicalContext) -> ParseResult<Self> {
        source.expect_str("type", "FunctionDeclaration")?;

        let func = parse_function(source, ctx)?;
        let func = Rc::new(func);

        // id is mandatory in FunctionDeclaration:
        let _ = func
            .id
            .as_ref()
            .ok_or_else(|| ParseError::no_attr("id", source.to_error()))?;

        let funcdecl = FunctionDeclaration { func };
        ctx.declare_func(&funcdecl)?;
        Ok(funcdecl)
    }
}

impl ParseFrom for ExpressionStatement {
    fn parse_from<S: SourceNode>(source: &S, ctx: &mut LexicalContext) -> ParseResult<Self> {
        source.expect_str("type", "ExpressionStatement")?;

        let expression =
            source.map_node("expression", |jexpr| Expression::parse_from(jexpr, ctx))?;
        Ok(ExpressionStatement { expression })
    }
}

impl ParseFrom for Expression {
    fn parse_from<S: SourceNode>(source: &S, ctx: &mut LexicalContext) -> ParseResult<Self> {
        let loc = source.get_location().map(Box::new);

        let expr_type = source.get_str("type")?;
        let expr = match expr_type.as_str() {
            "ArrayExpression" => {
                let expr = ArrayExpression::parse_from(source, ctx)?;
                Expr::Array(expr)
            }
            "AssignmentExpression" => {
                let expr = AssignmentExpression::parse_from(source, ctx)?;
                Expr::Assign(Box::new(expr))
            }
            "BinaryExpression" => {
                let expr = BinaryExpression::parse_from(source, ctx)?;
                Expr::BinaryOp(Box::new(expr))
            }
            "CallExpression" => {
                let expr = CallExpression::parse_from(source, ctx)?;
                Expr::Call(Box::new(expr))
            }
            "ConditionalExpression" => {
                let expr = ConditionalExpression::parse_from(source, ctx)?;
                Expr::Conditional(Box::new(expr))
            }
            "FunctionExpression" => {
                let expr = FunctionExpression::parse_from(source, ctx)?;
                Expr::Function(expr)
            }
            "Identifier" => {
                let expr = Identifier::parse_from(source, ctx)?;
                Expr::Identifier(expr)
            }
            "Literal" => {
                let lit = source.get_literal("value")?;
                Expr::Literal(lit)
            }
            "LogicalExpression" => {
                let expr = LogicalExpression::parse_from(source, ctx)?;
                Expr::LogicalOp(Box::new(expr))
            }
            "MemberExpression" => {
                let expr = MemberExpression::parse_from(source, ctx)?;
                Expr::Member(Box::new(expr))
            }
            "NewExpression" => {
                let expr = NewExpression::parse_from(source, ctx)?;
                Expr::New(Box::new(expr))
            }
            "ObjectExpression" => {
                let expr = ObjectExpression::parse_from(source, ctx)?;
                Expr::Object(expr)
            }
            "SequenceExpression" => {
                let expr = SequenceExpression::parse_from(source, ctx)?;
                Expr::Sequence(expr)
            }
            "ThisExpression" => Expr::This,
            "UnaryExpression" => {
                let expr = UnaryExpression::parse_from(source, ctx)?;
                Expr::Unary(Box::new(expr))
            }
            "UpdateExpression" => {
                let expr = UpdateExpression::parse_from(source, ctx)?;
                Expr::Update(Box::new(expr))
            }
            unknown => {
                let value = serde_json::json!({"type": unknown, "source": source.to_error()});
                return Err(ParseError::UnknownNodeType { value });
            }
        };
        Ok(Expression { expr, loc })
    }
}

impl ParseFrom for Identifier {
    fn parse_from<S: SourceNode>(source: &S, ctx: &mut LexicalContext) -> ParseResult<Self> {
        let name = source.get_str("name")?;
        let identifier = ctx.new_id(name);
        Ok(identifier)
    }
}

impl ParseFrom for UnaryExpression {
    fn parse_from<S: SourceNode>(source: &S, ctx: &mut LexicalContext) -> ParseResult<Self> {
        let jop = source.get_str("operator")?;
        let op = match jop.as_str() {
            "+" => UnOp::Plus,
            "-" => UnOp::Minus,
            "!" => UnOp::Exclamation,
            "~" => UnOp::Tilde,
            "delete" => UnOp::Delete,
            "typeof" => UnOp::Typeof,
            "void" => UnOp::Void,
            _ => {
                return Err(ParseError::UnexpectedValue {
                    want: "+ | - | ! | ~ | typeof | void",
                    value: source.to_error(),
                })
            }
        };

        let argument = source.map_node("argument", |jarg| Expression::parse_from(jarg, ctx))?;
        Ok(UnaryExpression(op, argument))
    }
}

impl ParseFrom for UpdateExpression {
    fn parse_from<S: SourceNode>(source: &S, ctx: &mut LexicalContext) -> ParseResult<Self> {
        let argument = source.map_node("argument", |jarg| Expression::parse_from(jarg, ctx))?;
        let prefix = source.get_bool("prefix")?;
        let operator = source.get_str("operator")?;

        let op = match operator.as_str() {
            "++" => UpdOp::Increment,
            "--" => UpdOp::Decrement,
            _ => {
                return Err(ParseError::UnexpectedValue {
                    want: "++ or --",
                    value: source.to_error(),
                })
            }
        };
        Ok(UpdateExpression(op, prefix, argument))
    }
}

impl ParseFrom for SequenceExpression {
    fn parse_from<S: SourceNode>(source: &S, ctx: &mut LexicalContext) -> ParseResult<Self> {
        let exprs = source.map_array("expressions", |jexpr| Expression::parse_from(jexpr, ctx))?;
        Ok(SequenceExpression(exprs))
    }
}

impl ParseFrom for BinaryExpression {
    fn parse_from<S: SourceNode>(source: &S, ctx: &mut LexicalContext) -> ParseResult<Self> {
        let left = source.map_node("left", |jleft| Expression::parse_from(jleft, ctx))?;
        let right = source.map_node("right", |jright| Expression::parse_from(jright, ctx))?;

        let opstr = source.get_str("operator")?;
        let op = match opstr.as_str() {
            "+" => BinOp::Plus,
            "-" => BinOp::Minus,
            "*" => BinOp::Star,
            "/" => BinOp::Slash,
            "%" => BinOp::Percent,
            "==" => BinOp::EqEq,
            "===" => BinOp::EqEqEq,
            "!=" => BinOp::NotEq,
            "!==" => BinOp::NotEqEq,
            "<" => BinOp::Less,
            ">" => BinOp::Greater,
            "<=" => BinOp::LtEq,
            ">=" => BinOp::GtEq,
            "|" => BinOp::Pipe,
            "^" => BinOp::Hat,
            "&" => BinOp::Ampersand,
            "<<" => BinOp::LtLt,
            ">>" => BinOp::GtGt,
            ">>>" => BinOp::GtGtGt,
            "in" => BinOp::In,
            "instanceof" => BinOp::InstanceOf,
            _ => {
                return Err(ParseError::UnexpectedValue {
                    want: "one of: + - * / % == === != < > <= >= instanceof | ^ & << >> >>>",
                    value: source.map_node("operator", |jop| Ok(jop.to_error()))?,
                })
            }
        };
        Ok(BinaryExpression(left, op, right))
    }
}

impl ParseFrom for LogicalExpression {
    fn parse_from<S: SourceNode>(source: &S, ctx: &mut LexicalContext) -> ParseResult<Self> {
        let opstr = source.get_str("operator")?;
        let op = match opstr.as_str() {
            "&&" => BoolOp::And,
            "||" => BoolOp::Or,
            _ => {
                return Err(ParseError::UnexpectedValue {
                    want: "&& or ||",
                    value: source.map_node("operator", |jop| Ok(jop.to_error()))?,
                })
            }
        };
        let left = source.map_node("left", |jleft| Expression::parse_from(jleft, ctx))?;
        let right = source.map_node("right", |jright| Expression::parse_from(jright, ctx))?;

        Ok(LogicalExpression(left, op, right))
    }
}

impl ParseFrom for ConditionalExpression {
    fn parse_from<S: SourceNode>(source: &S, ctx: &mut LexicalContext) -> ParseResult<Self> {
        let condexpr = source.map_node("test", |jtest| Expression::parse_from(jtest, ctx))?;
        let thenexpr = source.map_node("consequent", |jthen| Expression::parse_from(jthen, ctx))?;
        let elseexpr = source.map_node("alternate", |jelse| Expression::parse_from(jelse, ctx))?;
        Ok(ConditionalExpression {
            condexpr,
            thenexpr,
            elseexpr,
        })
    }
}

impl ParseFrom for AssignmentExpression {
    fn parse_from<S: SourceNode>(source: &S, ctx: &mut LexicalContext) -> ParseResult<Self> {
        let jop = source.get_str("operator")?;
        let modop = match jop.as_str() {
            "=" => None,
            "+=" => Some(BinOp::Plus),
            "-=" => Some(BinOp::Minus),
            "*=" => Some(BinOp::Star),
            "/=" => Some(BinOp::Slash),
            "%=" => Some(BinOp::Percent),
            "<<=" => Some(BinOp::LtLt),
            ">>=" => Some(BinOp::GtGt),
            ">>>=" => Some(BinOp::GtGtGt),
            "|=" => Some(BinOp::Pipe),
            "^=" => Some(BinOp::Hat),
            "&=" => Some(BinOp::Ampersand),
            _ => {
                return Err(ParseError::UnexpectedValue {
                    want: "one of: = += -= *= /= %= <<= >>= >>>= |= ^= &=",
                    value: source.map_node("operator", |jop| Ok(jop.to_error()))?,
                })
            }
        };

        let right = source.map_node("right", |jright| Expression::parse_from(jright, ctx))?;
        let left = source.map_node("left", |jleft| Expression::parse_from(jleft, ctx))?;

        Ok(AssignmentExpression(left, modop, right))
    }
}

impl ParseFrom for MemberExpression {
    fn parse_from<S: SourceNode>(source: &S, ctx: &mut LexicalContext) -> ParseResult<Self> {
        let computed = source.get_bool("computed")?;
        let object = source.map_node("object", |jobj| Expression::parse_from(jobj, ctx))?;
        let property = source.map_node("property", |jprop| Expression::parse_from(jprop, ctx))?;
        Ok(MemberExpression(object, property, computed))
    }
}

impl ParseFrom for CallExpression {
    fn parse_from<S: SourceNode>(source: &S, ctx: &mut LexicalContext) -> ParseResult<Self> {
        let callee = source.map_node("callee", |jcallee| Expression::parse_from(jcallee, ctx))?;
        let arguments = source.map_array("arguments", |jarg| Expression::parse_from(jarg, ctx))?;
        Ok(CallExpression(callee, arguments))
    }
}

impl ParseFrom for NewExpression {
    fn parse_from<S: SourceNode>(source: &S, ctx: &mut LexicalContext) -> ParseResult<Self> {
        let callee = source.map_node("callee", |jcallee| Expression::parse_from(jcallee, ctx))?;
        let arguments = source.map_array("arguments", |jarg| Expression::parse_from(jarg, ctx))?;
        Ok(NewExpression(callee, arguments))
    }
}

impl ParseFrom for ArrayExpression {
    fn parse_from<S: SourceNode>(source: &S, ctx: &mut LexicalContext) -> ParseResult<Self> {
        source.expect_str("type", "ArrayExpression")?;
        let elements = source.map_array("elements", |jelem| Expression::parse_from(jelem, ctx))?;
        Ok(ArrayExpression(elements))
    }
}

impl ParseFrom for ObjectExpression {
    fn parse_from<S: SourceNode>(source: &S, ctx: &mut LexicalContext) -> ParseResult<Self> {
        source.expect_str("type", "ObjectExpression")?;

        let properties = source.map_array("properties", |jprop| {
            jprop.expect_str("type", "Property")?;

            let keyexpr = jprop.map_node("key", |jkey| Expression::parse_from(jkey, ctx))?;
            let key = if jprop.get_bool("computed")? {
                ObjectKey::Computed(keyexpr)
            } else {
                match keyexpr.expr {
                    Expr::Identifier(ident) => ObjectKey::Identifier(ident.0),
                    Expr::Literal(lit) => match lit.to_json().as_str() {
                        Some(val) => ObjectKey::Identifier(val.into()),
                        None => ObjectKey::Identifier(lit.to_string().into()),
                    },
                    _ => {
                        return Err(ParseError::UnexpectedValue {
                            want: "Identifier|Literal",
                            value: jprop.to_error(),
                        })
                    }
                }
            };
            let value = jprop.map_node("value", |jval| Expression::parse_from(jval, ctx))?;
            Ok((key, value))
        })?;

        Ok(ObjectExpression(properties))
    }
}

impl ParseFrom for FunctionExpression {
    fn parse_from<S: SourceNode>(source: &S, ctx: &mut LexicalContext) -> ParseResult<Self> {
        let func = parse_function(source, ctx)?;
        let func = Rc::new(func);
        Ok(FunctionExpression { func })
    }
}

fn parse_function<S: SourceNode>(source: &S, ctx: &mut LexicalContext) -> ParseResult<Function> {
    let is_generator = source.get_bool("generator").unwrap_or(false);
    let is_expression = source.get_bool("expression").unwrap_or(false);
    let is_async = source.get_bool("async").unwrap_or(false);
    if is_generator || is_expression || is_async {
        let value = serde_json::json!({
            "is_generator": is_generator,
            "is_expression": is_expression,
            "is_async": is_async,
            "loc": source.get_location(),
        });
        return Err(ParseError::want(
            "no async/generator/expression functions",
            value,
        ));
    }

    let id: Option<Identifier> =
        source.map_opt_node("id", |jid| Identifier::parse_from(jid, ctx))?;

    ctx.enter_function(move |ctx| {
        let params = source.map_array("params", |jparam| {
            let argname = Identifier::parse_from(jparam, ctx)?;
            ctx.declare_var(DeclarationKind::Var, &argname)?;
            Ok(argname)
        })?;
        let body = source.map_node("body", |jbody| BlockStatement::parse_from(jbody, ctx))?;
        Ok((id, params, body))
    })
}