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
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
use crate::syntax::ast::constant::Const;
use crate::syntax::ast::expr::{Expr, ExprDef};
use crate::syntax::ast::keyword::Keyword;
use crate::syntax::ast::op::{BinOp, BitOp, CompOp, LogOp, NumOp, Operator, UnaryOp};
use crate::syntax::ast::punc::Punctuator;
use crate::syntax::ast::token::{Token, TokenData};
use std::collections::btree_map::BTreeMap;

macro_rules! mk (
    ($this:expr, $def:expr) => {
        {
            Expr::new($def)
        }
    };
    ($this:expr, $def:expr, $first:expr) => {
        Expr::new($def)
    };
);

/// ParseError is an enum which represents errors encounted during parsing an expression
#[derive(Debug, Clone)]
pub enum ParseError {
    /// When it expected a certain kind of token, but got another as part of something
    Expected(Vec<TokenData>, Token, &'static str),
    /// When it expected a certain expression, but got another
    ExpectedExpr(&'static str, Expr),
    /// When it didn't expect this keyword
    UnexpectedKeyword(Keyword),
    /// When there is an abrupt end to the parsing
    AbruptEnd,
}

pub type ParseResult = Result<Expr, ParseError>;

pub struct Parser {
    /// The tokens being input
    tokens: Vec<Token>,
    /// The current position within the tokens
    pos: usize,
}

impl Parser {
    /// Create a new parser, using `tokens` as input
    pub fn new(tokens: Vec<Token>) -> Parser {
        Parser {
            tokens: tokens,
            pos: 0,
        }
    }

    /// Parse all expressions in the token array
    pub fn parse_all(&mut self) -> ParseResult {
        let mut exprs = Vec::new();
        while self.pos < self.tokens.len() {
            let result = r#try!(self.parse());
            exprs.push(result);
        }

        // In the case of `BlockExpr` the Positions seem unnecessary
        // TODO: refactor this or the `mk!` perhaps?
        Ok(Expr::new(ExprDef::BlockExpr(exprs)))
    }

    fn get_token(&self, pos: usize) -> Result<Token, ParseError> {
        if pos < self.tokens.len() {
            Ok(self.tokens[pos].clone())
        } else {
            Err(ParseError::AbruptEnd)
        }
    }

    fn parse_struct(&mut self, keyword: Keyword) -> ParseResult {
        match keyword {
            Keyword::Throw => {
                let thrown = r#try!(self.parse());
                Ok(mk!(self, ExprDef::ThrowExpr(Box::new(thrown))))
            }
            // vars, lets and consts are similar in parsing structure, we can group them together
            Keyword::Var | Keyword::Let | Keyword::Const => {
                let mut vars = Vec::new();
                loop {
                    let name = match self.get_token(self.pos) {
                        Ok(Token {
                            data: TokenData::Identifier(ref name),
                            ..
                        }) => name.clone(),
                        Ok(tok) => {
                            return Err(ParseError::Expected(
                                vec![TokenData::Identifier("identifier".to_string())],
                                tok,
                                "var statement",
                            ))
                        }
                        Err(ParseError::AbruptEnd) => break,
                        Err(e) => return Err(e),
                    };
                    self.pos += 1;
                    match self.get_token(self.pos) {
                        Ok(Token {
                            data: TokenData::Punctuator(Punctuator::Assign),
                            ..
                        }) => {
                            self.pos += 1;
                            let val = self.parse()?;
                            vars.push((name, Some(val)));
                            match self.get_token(self.pos) {
                                Ok(Token {
                                    data: TokenData::Punctuator(Punctuator::Comma),
                                    ..
                                }) => self.pos += 1,
                                _ => break,
                            }
                        }
                        Ok(Token {
                            data: TokenData::Punctuator(Punctuator::Comma),
                            ..
                        }) => {
                            self.pos += 1;
                            vars.push((name, None));
                        }
                        _ => {
                            vars.push((name, None));
                            break;
                        }
                    }
                }

                match keyword {
                    Keyword::Let => Ok(Expr::new(ExprDef::LetDeclExpr(vars))),
                    Keyword::Const => Ok(Expr::new(ExprDef::ConstDeclExpr(vars))),
                    _ => Ok(Expr::new(ExprDef::VarDeclExpr(vars))),
                }
            }
            Keyword::Return => Ok(mk!(
                self,
                ExprDef::ReturnExpr(Some(Box::new(self.parse()?.clone())))
            )),
            Keyword::New => {
                let call = self.parse()?;
                match call.def {
                    ExprDef::CallExpr(ref func, ref args) => Ok(mk!(
                        self,
                        ExprDef::ConstructExpr(func.clone(), args.clone())
                    )),
                    _ => Err(ParseError::ExpectedExpr("constructor", call)),
                }
            }
            Keyword::TypeOf => Ok(mk!(self, ExprDef::TypeOfExpr(Box::new(self.parse()?)))),
            Keyword::If => {
                self.expect_punc(Punctuator::OpenParen, "if block")?;
                let cond = self.parse()?;
                self.expect_punc(Punctuator::CloseParen, "if block")?;
                let expr = self.parse()?;
                let next = self.get_token(self.pos + 1);
                Ok(mk!(
                    self,
                    ExprDef::IfExpr(
                        Box::new(cond),
                        Box::new(expr),
                        if next.is_ok() && next.unwrap().data == TokenData::Keyword(Keyword::Else) {
                            self.pos += 2;
                            Some(Box::new(self.parse()?))
                        } else {
                            None
                        }
                    )
                ))
            }
            Keyword::While => {
                self.expect_punc(Punctuator::OpenParen, "while condition")?;
                let cond = self.parse()?;
                self.expect_punc(Punctuator::CloseParen, "while condition")?;
                let expr = self.parse()?;
                Ok(mk!(
                    self,
                    ExprDef::WhileLoopExpr(Box::new(cond), Box::new(expr))
                ))
            }
            Keyword::Switch => {
                r#try!(self.expect_punc(Punctuator::OpenParen, "switch value"));
                let value = self.parse();
                r#try!(self.expect_punc(Punctuator::CloseParen, "switch value"));
                r#try!(self.expect_punc(Punctuator::OpenBlock, "switch block"));
                let mut cases = Vec::new();
                let mut default = None;
                while self.pos + 1 < self.tokens.len() {
                    let tok = self.get_token(self.pos)?;
                    self.pos += 1;
                    match tok.data {
                        TokenData::Keyword(Keyword::Case) => {
                            let cond = self.parse();
                            let mut block = Vec::new();
                            r#try!(self.expect_punc(Punctuator::Colon, "switch case"));
                            loop {
                                match r#try!(self.get_token(self.pos)).data {
                                    TokenData::Keyword(Keyword::Case)
                                    | TokenData::Keyword(Keyword::Default) => break,
                                    TokenData::Punctuator(Punctuator::CloseBlock) => break,
                                    _ => block.push(r#try!(self.parse())),
                                }
                            }
                            cases.push((cond.unwrap(), block));
                        }
                        TokenData::Keyword(Keyword::Default) => {
                            let mut block = Vec::new();
                            r#try!(self.expect_punc(Punctuator::Colon, "default switch case"));
                            loop {
                                match r#try!(self.get_token(self.pos)).data {
                                    TokenData::Keyword(Keyword::Case)
                                    | TokenData::Keyword(Keyword::Default) => break,
                                    TokenData::Punctuator(Punctuator::CloseBlock) => break,
                                    _ => block.push(r#try!(self.parse())),
                                }
                            }
                            default = Some(mk!(self, ExprDef::BlockExpr(block)));
                        }
                        TokenData::Punctuator(Punctuator::CloseBlock) => break,
                        _ => {
                            return Err(ParseError::Expected(
                                vec![
                                    TokenData::Keyword(Keyword::Case),
                                    TokenData::Keyword(Keyword::Default),
                                    TokenData::Punctuator(Punctuator::CloseBlock),
                                ],
                                tok,
                                "switch block",
                            ))
                        }
                    }
                }
                r#try!(self.expect_punc(Punctuator::CloseBlock, "switch block"));
                Ok(mk!(
                    self,
                    ExprDef::SwitchExpr(
                        Box::new(value.unwrap()),
                        cases,
                        match default {
                            Some(v) => Some(Box::new(v)),
                            None => None,
                        }
                    )
                ))
            }
            Keyword::Function => {
                // function [identifier] () { etc }
                let tk = r#try!(self.get_token(self.pos));
                let name = match tk.data {
                    TokenData::Identifier(ref name) => {
                        self.pos += 1;
                        Some(name.clone())
                    }
                    TokenData::Punctuator(Punctuator::OpenParen) => None,
                    _ => {
                        return Err(ParseError::Expected(
                            vec![TokenData::Identifier("identifier".to_string())],
                            tk.clone(),
                            "function name",
                        ))
                    }
                };
                // Now we have the function identifier we should have an open paren for arguments ( )
                self.expect_punc(Punctuator::OpenParen, "function")?;
                let mut args: Vec<String> = Vec::new();
                let mut tk = self.get_token(self.pos)?;
                while tk.data != TokenData::Punctuator(Punctuator::CloseParen) {
                    match tk.data {
                        TokenData::Identifier(ref id) => args.push(id.clone()),
                        _ => {
                            return Err(ParseError::Expected(
                                vec![TokenData::Identifier("identifier".to_string())],
                                tk.clone(),
                                "function arguments",
                            ))
                        }
                    }
                    self.pos += 1;
                    if r#try!(self.get_token(self.pos)).data
                        == TokenData::Punctuator(Punctuator::Comma)
                    {
                        self.pos += 1;
                    }
                    tk = self.get_token(self.pos)?;
                }
                self.pos += 1;
                let block = self.parse()?;
                Ok(mk!(
                    self,
                    ExprDef::FunctionDeclExpr(name, args, Box::new(block))
                ))
            }
            _ => Err(ParseError::UnexpectedKeyword(keyword)),
        }
    }

    /// Parse a single expression
    pub fn parse(&mut self) -> ParseResult {
        if self.pos > self.tokens.len() {
            return Err(ParseError::AbruptEnd);
        }
        let token = r#try!(self.get_token(self.pos));
        self.pos += 1;
        let expr: Expr = match token.data {
            TokenData::Punctuator(Punctuator::Semicolon) | TokenData::Comment(_)
                if self.pos < self.tokens.len() =>
            {
                r#try!(self.parse())
            }
            TokenData::Punctuator(Punctuator::Semicolon) | TokenData::Comment(_) => {
                mk!(self, ExprDef::ConstExpr(Const::Undefined))
            }
            TokenData::NumericLiteral(num) => mk!(self, ExprDef::ConstExpr(Const::Num(num))),
            TokenData::NullLiteral => mk!(self, ExprDef::ConstExpr(Const::Null)),
            TokenData::StringLiteral(text) => mk!(self, ExprDef::ConstExpr(Const::String(text))),
            TokenData::BooleanLiteral(val) => mk!(self, ExprDef::ConstExpr(Const::Bool(val))),
            TokenData::Identifier(ref s) if s == "undefined" => {
                mk!(self, ExprDef::ConstExpr(Const::Undefined))
            }
            TokenData::Identifier(s) => mk!(self, ExprDef::LocalExpr(s)),
            TokenData::Keyword(keyword) => r#try!(self.parse_struct(keyword)),
            TokenData::Punctuator(Punctuator::OpenParen) => {
                match r#try!(self.get_token(self.pos)).data {
                    TokenData::Punctuator(Punctuator::CloseParen)
                        if r#try!(self.get_token(self.pos + 1)).data
                            == TokenData::Punctuator(Punctuator::Arrow) =>
                    {
                        self.pos += 2;
                        let expr = r#try!(self.parse());
                        mk!(
                            self,
                            ExprDef::ArrowFunctionDeclExpr(Vec::new(), Box::new(expr)),
                            token
                        )
                    }
                    _ => {
                        let next = r#try!(self.parse());
                        let next_tok = r#try!(self.get_token(self.pos));
                        self.pos += 1;
                        match next_tok.data {
                            TokenData::Punctuator(Punctuator::CloseParen) => next,
                            TokenData::Punctuator(Punctuator::Comma) => {
                                // at this point it's probably gonna be an arrow function
                                let mut args = vec![
                                    match next.def {
                                        ExprDef::LocalExpr(ref name) => (*name).clone(),
                                        _ => "".to_string(),
                                    },
                                    match r#try!(self.get_token(self.pos)).data {
                                        TokenData::Identifier(ref id) => id.clone(),
                                        _ => "".to_string(),
                                    },
                                ];
                                let mut expect_ident = true;
                                loop {
                                    self.pos += 1;
                                    let curr_tk = r#try!(self.get_token(self.pos));
                                    match curr_tk.data {
                                        TokenData::Identifier(ref id) if expect_ident => {
                                            args.push(id.clone());
                                            expect_ident = false;
                                        }
                                        TokenData::Punctuator(Punctuator::Comma) => {
                                            expect_ident = true;
                                        }
                                        TokenData::Punctuator(Punctuator::CloseParen) => {
                                            self.pos += 1;
                                            break;
                                        }
                                        _ if expect_ident => {
                                            return Err(ParseError::Expected(
                                                vec![TokenData::Identifier(
                                                    "identifier".to_string(),
                                                )],
                                                curr_tk.clone(),
                                                "arrow function",
                                            ))
                                        }
                                        _ => {
                                            return Err(ParseError::Expected(
                                                vec![
                                                    TokenData::Punctuator(Punctuator::Comma),
                                                    TokenData::Punctuator(Punctuator::CloseParen),
                                                ],
                                                curr_tk,
                                                "arrow function",
                                            ))
                                        }
                                    }
                                }
                                r#try!(self.expect(
                                    TokenData::Punctuator(Punctuator::Arrow),
                                    "arrow function"
                                ));
                                let expr = r#try!(self.parse());
                                mk!(
                                    self,
                                    ExprDef::ArrowFunctionDeclExpr(args, Box::new(expr)),
                                    token
                                )
                            }
                            _ => {
                                return Err(ParseError::Expected(
                                    vec![TokenData::Punctuator(Punctuator::CloseParen)],
                                    next_tok,
                                    "brackets",
                                ))
                            }
                        }
                    }
                }
            }
            TokenData::Punctuator(Punctuator::OpenBracket) => {
                let mut array: Vec<Expr> = Vec::new();
                let mut expect_comma_or_end = r#try!(self.get_token(self.pos)).data
                    == TokenData::Punctuator(Punctuator::CloseBracket);
                loop {
                    let token = r#try!(self.get_token(self.pos));
                    if token.data == TokenData::Punctuator(Punctuator::CloseBracket)
                        && expect_comma_or_end
                    {
                        self.pos += 1;
                        break;
                    } else if token.data == TokenData::Punctuator(Punctuator::Comma)
                        && expect_comma_or_end
                    {
                        expect_comma_or_end = false;
                    } else if token.data == TokenData::Punctuator(Punctuator::Comma)
                        && !expect_comma_or_end
                    {
                        array.push(mk!(self, ExprDef::ConstExpr(Const::Null)));
                        expect_comma_or_end = false;
                    } else if expect_comma_or_end {
                        return Err(ParseError::Expected(
                            vec![
                                TokenData::Punctuator(Punctuator::Comma),
                                TokenData::Punctuator(Punctuator::CloseBracket),
                            ],
                            token.clone(),
                            "array declaration",
                        ));
                    } else {
                        let parsed = r#try!(self.parse());
                        self.pos -= 1;
                        array.push(parsed);
                        expect_comma_or_end = true;
                    }
                    self.pos += 1;
                }
                mk!(self, ExprDef::ArrayDeclExpr(array), token)
            }
            TokenData::Punctuator(Punctuator::OpenBlock)
                if r#try!(self.get_token(self.pos)).data
                    == TokenData::Punctuator(Punctuator::CloseBlock) =>
            {
                self.pos += 1;
                mk!(
                    self,
                    ExprDef::ObjectDeclExpr(Box::new(BTreeMap::new())),
                    token
                )
            }
            TokenData::Punctuator(Punctuator::OpenBlock)
                if r#try!(self.get_token(self.pos + 1)).data
                    == TokenData::Punctuator(Punctuator::Colon) =>
            {
                let mut map = Box::new(BTreeMap::new());
                while r#try!(self.get_token(self.pos - 1)).data
                    == TokenData::Punctuator(Punctuator::Comma)
                    || map.len() == 0
                {
                    let tk = r#try!(self.get_token(self.pos));
                    let name = match tk.data {
                        TokenData::Identifier(ref id) => id.clone(),
                        TokenData::StringLiteral(ref str) => str.clone(),
                        _ => {
                            return Err(ParseError::Expected(
                                vec![
                                    TokenData::Identifier("identifier".to_string()),
                                    TokenData::StringLiteral("string".to_string()),
                                ],
                                tk,
                                "object declaration",
                            ))
                        }
                    };
                    self.pos += 1;
                    r#try!(self.expect(
                        TokenData::Punctuator(Punctuator::Colon),
                        "object declaration"
                    ));
                    let value = r#try!(self.parse());
                    map.insert(name, value);
                    self.pos += 1;
                }
                mk!(self, ExprDef::ObjectDeclExpr(map), token)
            }
            TokenData::Punctuator(Punctuator::OpenBlock) => {
                let mut exprs = Vec::new();
                loop {
                    if r#try!(self.get_token(self.pos)).data
                        == TokenData::Punctuator(Punctuator::CloseBlock)
                    {
                        break;
                    } else {
                        exprs.push(r#try!(self.parse()));
                    }
                }
                self.pos += 1;
                mk!(self, ExprDef::BlockExpr(exprs), token)
            }
            TokenData::Punctuator(Punctuator::Sub) => mk!(
                self,
                ExprDef::UnaryOpExpr(UnaryOp::Minus, Box::new(r#try!(self.parse())))
            ),
            TokenData::Punctuator(Punctuator::Add) => mk!(
                self,
                ExprDef::UnaryOpExpr(UnaryOp::Plus, Box::new(r#try!(self.parse())))
            ),
            TokenData::Punctuator(Punctuator::Not) => mk!(
                self,
                ExprDef::UnaryOpExpr(UnaryOp::Not, Box::new(r#try!(self.parse())))
            ),
            TokenData::Punctuator(Punctuator::Inc) => mk!(
                self,
                ExprDef::UnaryOpExpr(UnaryOp::IncrementPre, Box::new(r#try!(self.parse())))
            ),
            TokenData::Punctuator(Punctuator::Dec) => mk!(
                self,
                ExprDef::UnaryOpExpr(UnaryOp::DecrementPre, Box::new(r#try!(self.parse())))
            ),
            _ => return Err(ParseError::Expected(Vec::new(), token.clone(), "script")),
        };
        if self.pos >= self.tokens.len() {
            Ok(expr)
        } else {
            self.parse_next(expr)
        }
    }

    fn parse_next(&mut self, expr: Expr) -> ParseResult {
        let next = self.get_token(self.pos)?;
        let mut carry_on = true;
        let mut result = expr.clone();
        match next.data {
            TokenData::Punctuator(Punctuator::Dot) => {
                self.pos += 1;
                let tk = r#try!(self.get_token(self.pos));
                match tk.data {
                    TokenData::Identifier(ref s) => {
                        result = mk!(
                            self,
                            ExprDef::GetConstFieldExpr(Box::new(expr), s.to_string())
                        )
                    }
                    _ => {
                        return Err(ParseError::Expected(
                            vec![TokenData::Identifier("identifier".to_string())],
                            tk,
                            "field access",
                        ))
                    }
                }
                self.pos += 1;
            }
            TokenData::Punctuator(Punctuator::OpenParen) => {
                let mut args = Vec::new();
                let mut expect_comma_or_end = r#try!(self.get_token(self.pos + 1)).data
                    == TokenData::Punctuator(Punctuator::CloseParen);
                loop {
                    self.pos += 1;
                    let token = r#try!(self.get_token(self.pos));
                    if token.data == TokenData::Punctuator(Punctuator::CloseParen)
                        && expect_comma_or_end
                    {
                        self.pos += 1;
                        break;
                    } else if token.data == TokenData::Punctuator(Punctuator::Comma)
                        && expect_comma_or_end
                    {
                        expect_comma_or_end = false;
                    } else if expect_comma_or_end {
                        return Err(ParseError::Expected(
                            vec![
                                TokenData::Punctuator(Punctuator::Comma),
                                TokenData::Punctuator(Punctuator::CloseParen),
                            ],
                            token,
                            "function call arguments",
                        ));
                    } else {
                        let parsed = r#try!(self.parse());
                        self.pos -= 1;
                        args.push(parsed);
                        expect_comma_or_end = true;
                    }
                }
                result = mk!(self, ExprDef::CallExpr(Box::new(expr), args));
            }
            TokenData::Punctuator(Punctuator::Question) => {
                self.pos += 1;
                let if_e = r#try!(self.parse());
                r#try!(self.expect(TokenData::Punctuator(Punctuator::Colon), "if expression"));
                let else_e = r#try!(self.parse());
                result = mk!(
                    self,
                    ExprDef::IfExpr(Box::new(expr), Box::new(if_e), Some(Box::new(else_e)))
                );
            }
            TokenData::Punctuator(Punctuator::OpenBracket) => {
                self.pos += 1;
                let index = r#try!(self.parse());
                r#try!(self.expect(
                    TokenData::Punctuator(Punctuator::CloseBracket),
                    "array index"
                ));
                result = mk!(self, ExprDef::GetFieldExpr(Box::new(expr), Box::new(index)));
            }
            TokenData::Punctuator(Punctuator::Semicolon) | TokenData::Comment(_) => {
                self.pos += 1;
            }
            TokenData::Punctuator(Punctuator::Assign) => {
                self.pos += 1;
                let next = r#try!(self.parse());
                result = mk!(self, ExprDef::AssignExpr(Box::new(expr), Box::new(next)));
            }
            TokenData::Punctuator(Punctuator::Arrow) => {
                self.pos += 1;
                let mut args = Vec::with_capacity(1);
                match result.def {
                    ExprDef::LocalExpr(ref name) => args.push((*name).clone()),
                    _ => return Err(ParseError::ExpectedExpr("identifier", result)),
                }
                let next = r#try!(self.parse());
                result = mk!(self, ExprDef::ArrowFunctionDeclExpr(args, Box::new(next)));
            }
            TokenData::Punctuator(Punctuator::Add) => {
                result = r#try!(self.binop(BinOp::Num(NumOp::Add), expr))
            }
            TokenData::Punctuator(Punctuator::Sub) => {
                result = r#try!(self.binop(BinOp::Num(NumOp::Sub), expr))
            }
            TokenData::Punctuator(Punctuator::Mul) => {
                result = r#try!(self.binop(BinOp::Num(NumOp::Mul), expr))
            }
            TokenData::Punctuator(Punctuator::Div) => {
                result = r#try!(self.binop(BinOp::Num(NumOp::Div), expr))
            }
            TokenData::Punctuator(Punctuator::Mod) => {
                result = r#try!(self.binop(BinOp::Num(NumOp::Mod), expr))
            }
            TokenData::Punctuator(Punctuator::BoolAnd) => {
                result = r#try!(self.binop(BinOp::Log(LogOp::And), expr))
            }
            TokenData::Punctuator(Punctuator::BoolOr) => {
                result = r#try!(self.binop(BinOp::Log(LogOp::Or), expr))
            }
            TokenData::Punctuator(Punctuator::And) => {
                result = r#try!(self.binop(BinOp::Bit(BitOp::And), expr))
            }
            TokenData::Punctuator(Punctuator::Or) => {
                result = r#try!(self.binop(BinOp::Bit(BitOp::Or), expr))
            }
            TokenData::Punctuator(Punctuator::Xor) => {
                result = r#try!(self.binop(BinOp::Bit(BitOp::Xor), expr))
            }
            TokenData::Punctuator(Punctuator::LeftSh) => {
                result = r#try!(self.binop(BinOp::Bit(BitOp::Shl), expr))
            }
            TokenData::Punctuator(Punctuator::RightSh) => {
                result = r#try!(self.binop(BinOp::Bit(BitOp::Shr), expr))
            }
            TokenData::Punctuator(Punctuator::Eq) => {
                result = r#try!(self.binop(BinOp::Comp(CompOp::Equal), expr))
            }
            TokenData::Punctuator(Punctuator::NotEq) => {
                result = r#try!(self.binop(BinOp::Comp(CompOp::NotEqual), expr))
            }
            TokenData::Punctuator(Punctuator::StrictEq) => {
                result = r#try!(self.binop(BinOp::Comp(CompOp::StrictEqual), expr))
            }
            TokenData::Punctuator(Punctuator::StrictNotEq) => {
                result = r#try!(self.binop(BinOp::Comp(CompOp::StrictNotEqual), expr))
            }
            TokenData::Punctuator(Punctuator::LessThan) => {
                result = r#try!(self.binop(BinOp::Comp(CompOp::LessThan), expr))
            }
            TokenData::Punctuator(Punctuator::LessThanOrEq) => {
                result = r#try!(self.binop(BinOp::Comp(CompOp::LessThanOrEqual), expr))
            }
            TokenData::Punctuator(Punctuator::GreaterThan) => {
                result = r#try!(self.binop(BinOp::Comp(CompOp::GreaterThan), expr))
            }
            TokenData::Punctuator(Punctuator::GreaterThanOrEq) => {
                result = r#try!(self.binop(BinOp::Comp(CompOp::GreaterThanOrEqual), expr))
            }
            TokenData::Punctuator(Punctuator::Inc) => {
                result = mk!(
                    self,
                    ExprDef::UnaryOpExpr(UnaryOp::IncrementPost, Box::new(r#try!(self.parse())))
                )
            }
            TokenData::Punctuator(Punctuator::Dec) => {
                result = mk!(
                    self,
                    ExprDef::UnaryOpExpr(UnaryOp::DecrementPost, Box::new(r#try!(self.parse())))
                )
            }
            _ => carry_on = false,
        };
        if carry_on && self.pos < self.tokens.len() {
            self.parse_next(result)
        } else {
            Ok(result)
        }
    }

    fn binop(&mut self, op: BinOp, orig: Expr) -> Result<Expr, ParseError> {
        let (precedence, assoc) = op.get_precedence_and_assoc();
        self.pos += 1;
        let next = r#try!(self.parse());
        Ok(match next.def {
            ExprDef::BinOpExpr(ref op2, ref a, ref b) => {
                let other_precedence = op2.get_precedence();
                if precedence < other_precedence || (precedence == other_precedence && !assoc) {
                    mk!(
                        self,
                        ExprDef::BinOpExpr(
                            op2.clone(),
                            b.clone(),
                            Box::new(mk!(
                                self,
                                ExprDef::BinOpExpr(op.clone(), Box::new(orig), a.clone())
                            ))
                        )
                    )
                } else {
                    mk!(
                        self,
                        ExprDef::BinOpExpr(op, Box::new(orig), Box::new(next.clone()))
                    )
                }
            }
            _ => mk!(self, ExprDef::BinOpExpr(op, Box::new(orig), Box::new(next))),
        })
    }

    /// Returns an error if the next symbol is not `tk`
    fn expect(&mut self, tk: TokenData, routine: &'static str) -> Result<(), ParseError> {
        self.pos += 1;
        let curr_tk = self.get_token(self.pos - 1)?;
        if curr_tk.data != tk {
            Err(ParseError::Expected(vec![tk], curr_tk, routine))
        } else {
            Ok(())
        }
    }

    /// Returns an error if the next symbol is not the punctuator `p`
    #[inline(always)]
    fn expect_punc(&mut self, p: Punctuator, routine: &'static str) -> Result<(), ParseError> {
        self.expect(TokenData::Punctuator(p), routine)
    }
}