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
use crate::ast::{NodeId, Syntax, VarDeclMode, VariableDeclarator};
use crate::error::{SyntaxErrorType, SyntaxResult};
use crate::parse::parser::Parser;
use crate::parse::pattern::parse_pattern;
use crate::parse::signature::parse_signature_function;
use crate::parse::stmt::parse_stmt_block;
use crate::symbol::{ScopeId, ScopeType, Symbol};
use crate::token::TokenType;

use super::class_or_object::{parse_class_body, ParseClassBodyResult};
use super::expr::{parse_expr, parse_expr_until_either_with_asi, Asi};
use super::pattern::{is_valid_pattern_identifier, ParsePatternAction, ParsePatternSyntax};

#[derive(Clone, Copy, PartialEq, Eq)]
pub enum VarDeclParseMode {
    // Standard parsing mode for var/let/const statement.
    Asi,
    // Parse as many valid declarators as possible, then break before the first invalid token (i.e. not a comma). Used by for-loop parser.
    Leftmost,
}

pub fn parse_decl_var(
    scope: ScopeId,
    parser: &mut Parser,
    parse_mode: VarDeclParseMode,
    syntax: &ParsePatternSyntax,
) -> SyntaxResult<NodeId> {
    let t = parser.next()?;
    let mode = match t.typ() {
        TokenType::KeywordLet => VarDeclMode::Let,
        TokenType::KeywordConst => VarDeclMode::Const,
        TokenType::KeywordVar => VarDeclMode::Var,
        _ => return Err(t.error(SyntaxErrorType::ExpectedSyntax("variable declaration"))),
    };
    let mut declarators = vec![];
    let mut loc = t.loc().clone();
    loop {
        let pattern = parse_pattern(
            scope,
            parser,
            match mode {
                VarDeclMode::Var => ParsePatternAction::AddToClosureScope,
                _ => ParsePatternAction::AddToBlockScope,
            },
            syntax,
        )?;
        loc.extend(parser[pattern].loc());
        let mut asi = match parse_mode {
            VarDeclParseMode::Asi => Asi::can(),
            VarDeclParseMode::Leftmost => Asi::no(),
        };
        let initializer = if parser.consume_if(TokenType::Equals)?.is_match() {
            let expr = parse_expr_until_either_with_asi(
                scope,
                parser,
                TokenType::Semicolon,
                TokenType::Comma,
                &mut asi,
                syntax,
            )?;
            loc.extend(parser[expr].loc());
            Some(expr)
        } else {
            None
        };
        declarators.push(VariableDeclarator {
            pattern,
            initializer,
        });
        match parse_mode {
            VarDeclParseMode::Asi => {
                if parser.consume_if(TokenType::Semicolon)?.is_match() || asi.did_end_with_asi {
                    break;
                }
                let t = parser.peek()?;
                if t.preceded_by_line_terminator() && t.typ() != TokenType::Comma {
                    break;
                };
                parser.require(TokenType::Comma)?;
            }
            VarDeclParseMode::Leftmost => {
                if !parser.consume_if(TokenType::Comma)?.is_match() {
                    break;
                }
            }
        }
    }
    Ok(parser.create_node(scope, loc, Syntax::VarDecl { mode, declarators }))
}

pub fn parse_decl_function(
    scope: ScopeId,
    parser: &mut Parser,
    syntax: &ParsePatternSyntax,
) -> SyntaxResult<NodeId> {
    let fn_scope = parser.create_child_scope(scope, ScopeType::Closure);
    let is_async = parser.consume_if(TokenType::KeywordAsync)?.is_match();
    let start = parser.require(TokenType::KeywordFunction)?.loc().clone();
    let generator = parser.consume_if(TokenType::Asterisk)?.is_match();
    // WARNING: The name belongs in the containing scope, not the function's scope.
    // For example, `function a() { let a = 1; }` is legal.
    // The name can only be omitted in default exports.
    let name = match parser
        .consume_if_pred(|t| is_valid_pattern_identifier(t.typ(), syntax))?
        .match_loc_take()
    {
        Some(name) => {
            let name_node = parser.create_node(
                scope,
                name.clone(),
                Syntax::ClassOrFunctionName { name: name.clone() },
            );
            if let Some(closure_id) = parser[scope].self_or_ancestor_closure() {
                parser[closure_id].add_symbol(name.clone(), Symbol::new(name_node))?;
            };
            Some(name_node)
        }
        _ => None,
    };
    let signature = parse_signature_function(fn_scope, parser, syntax)?;
    let body = parse_stmt_block(fn_scope, parser, syntax)?;
    Ok(parser.create_node(
        scope,
        &start + parser[body].loc(),
        Syntax::FunctionDecl {
            is_async,
            generator,
            name,
            signature,
            body,
        },
    ))
}

pub fn parse_decl_class(
    scope: ScopeId,
    parser: &mut Parser,
    syntax: &ParsePatternSyntax,
) -> SyntaxResult<NodeId> {
    let start = parser.require(TokenType::KeywordClass)?.loc().clone();
    // Names can be omitted only in default exports.
    let name = match parser
        .consume_if_pred(|t| is_valid_pattern_identifier(t.typ(), syntax))?
        .match_loc_take()
    {
        Some(name) => {
            let name_node = parser.create_node(
                scope,
                name.clone(),
                Syntax::ClassOrFunctionName { name: name.clone() },
            );
            parser[scope].add_block_symbol(name.clone(), Symbol::new(name_node))?;
            Some(name_node)
        }
        None => None,
    };
    // Unlike functions, classes are scoped to their block.
    let extends = if parser.consume_if(TokenType::KeywordExtends)?.is_match() {
        Some(parse_expr(scope, parser, TokenType::BraceOpen, syntax)?)
    } else {
        None
    };
    let ParseClassBodyResult { end, members } = parse_class_body(scope, parser, syntax)?;
    Ok(parser.create_node(
        scope,
        &start + &end,
        Syntax::ClassDecl {
            name,
            extends,
            members,
        },
    ))
}