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
#![allow(dead_code, unused_variables)]
#![deny(non_snake_case)]
use self::{input::ParserInput, util::ParseObject};
use crate::{
    error::SyntaxError,
    lexer::{Input, Lexer},
    parser_macros::parser,
    token::{Token, Word},
    Context, Session, Syntax,
};
use ast::*;
use std::ops::{Deref, DerefMut};
use swc_atoms::JsWord;
use swc_common::{errors::DiagnosticBuilder, BytePos, Span};

#[macro_use]
mod macros;
mod class_and_fn;
mod expr;
mod ident;
pub mod input;
mod jsx;
mod object;
mod pat;
mod stmt;
mod typescript;
mod util;

/// When error ocurred, error is emiited and parser returnes Err(()).
pub type PResult<'a, T> = Result<T, DiagnosticBuilder<'a>>;

/// EcmaScript parser.
#[derive(Clone)]
pub struct Parser<'a, I: Input> {
    session: Session<'a>,
    state: State,
    input: ParserInput<'a, I>,
}

#[derive(Clone, Default)]
struct State {
    labels: Vec<JsWord>,
    /// Start position of an assignment expression.
    potential_arrow_start: Option<BytePos>,
}

#[parser]
impl<'a, I: Input> Parser<'a, I> {
    pub fn new(session: Session<'a>, syntax: Syntax, input: I) -> Self {
        Parser {
            session,
            input: ParserInput::new(Lexer::new(session, syntax, input)),
            state: Default::default(),
        }
    }

    pub fn parse_script(&mut self) -> PResult<'a, (Vec<Stmt>)> {
        let ctx = Context {
            module: false,
            ..self.ctx()
        };
        self.set_ctx(ctx);

        self.parse_block_body(true, true, None)
    }

    pub fn parse_module(&mut self) -> PResult<'a, Module> {
        //TOOD: parse() -> PResult<'a, Program>
        let ctx = Context {
            module: true,
            strict: true,
            ..self.ctx()
        };
        // module code is always in strict mode
        self.set_ctx(ctx);

        let start = cur_pos!();
        self.parse_block_body(true, true, None).map(|body| Module {
            span: span!(start),
            body,
        })
    }

    fn ctx(&self) -> Context {
        self.input.get_ctx()
    }
}

#[cfg(test)]
pub fn test_parser<F, Ret>(s: &'static str, syntax: Syntax, f: F) -> Ret
where
    F: for<'a> FnOnce(&'a mut Parser<'a, ::SourceFileInput>) -> Result<Ret, ()>,
{
    crate::with_test_sess(s, |sess, input| f(&mut Parser::new(sess, syntax, input)))
        .unwrap_or_else(|output| panic!("test_parser(): failed to parse \n{}\n{}", s, output))
}