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
use crate::ast::{ArrayPatternElement, ClassOrObjectMemberKey, NodeId, Syntax};
use crate::error::{SyntaxErrorType, SyntaxResult};
use crate::parse::expr::parse_expr_until_either;
use crate::parse::literal::parse_class_or_object_member_key;
use crate::parse::parser::Parser;
use crate::symbol::{ScopeId, Symbol};
use crate::token::{TokenType, UNRESERVED_KEYWORDS};

#[derive(Clone, Copy, PartialEq, Eq)]
pub enum ParsePatternAction {
    None,
    AddToBlockScope,
    // For var statements. Note that this won't add to the top-level if it's a global and that's the closest, since global declarators cannot be minified.
    AddToClosureScope,
}

pub struct ParsePatternSyntax {
    // `await` is not allowed as an arrow function parameter or a parameter/variable inside an async function.
    pub await_allowed: bool,
    // `yield` is not allowed as a parameter/variable inside a generator function.
    pub yield_allowed: bool,
}

pub fn is_valid_pattern_identifier(typ: TokenType, syntax: &ParsePatternSyntax) -> bool {
    match typ {
        TokenType::Identifier => true,
        TokenType::KeywordAwait if syntax.await_allowed => true,
        TokenType::KeywordYield if syntax.yield_allowed => true,
        t if UNRESERVED_KEYWORDS.contains(&t) => true,
        _ => false,
    }
}

fn parse_pattern_identifier(
    scope: ScopeId,
    parser: &mut Parser,
    action: ParsePatternAction,
    syntax: &ParsePatternSyntax,
) -> SyntaxResult<NodeId> {
    if !is_valid_pattern_identifier(parser.peek()?.typ(), syntax) {
        return Err(parser
            .peek()?
            .error(SyntaxErrorType::ExpectedSyntax("identifier")));
    }
    let t = parser.next()?;
    let node_id = parser.create_node(
        scope,
        t.loc().clone(),
        Syntax::IdentifierPattern {
            name: t.loc().clone(),
        },
    );
    match action {
        ParsePatternAction::None => {}
        ParsePatternAction::AddToBlockScope => {
            let scope = &mut parser[scope];
            scope.add_block_symbol(t.loc().clone(), Symbol::new(node_id))?;
        }
        ParsePatternAction::AddToClosureScope => {
            if let Some(closure_id) = parser[scope].self_or_ancestor_closure() {
                parser[closure_id].add_symbol(t.loc().clone(), Symbol::new(node_id))?;
            };
        }
    };
    Ok(node_id)
}

pub fn parse_pattern(
    scope: ScopeId,
    parser: &mut Parser,
    action: ParsePatternAction,
    syntax: &ParsePatternSyntax,
) -> SyntaxResult<NodeId> {
    let checkpoint = parser.checkpoint();
    let t = parser.next()?;
    Ok(match t.typ() {
        t if is_valid_pattern_identifier(t, syntax) => {
            parser.restore_checkpoint(checkpoint);
            parse_pattern_identifier(scope, parser, action, syntax)?
        }
        TokenType::BraceOpen => {
            let mut properties = Vec::<NodeId>::new();
            let mut rest = None;
            loop {
                if parser.peek()?.typ() == TokenType::BraceClose {
                    break;
                };
                let mut loc = parser.peek()?.loc_take();
                // Check inside loop to ensure that it must come first or after a comma.
                if parser.consume_if(TokenType::DotDotDot)?.is_match() {
                    rest = Some(parse_pattern_identifier(scope, parser, action, syntax)?);
                    break;
                };

                let key = parse_class_or_object_member_key(scope, parser, syntax)?;
                let target = if parser.consume_if(TokenType::Colon)?.is_match() {
                    Some(parse_pattern(scope, parser, action, syntax)?)
                } else {
                    if let ClassOrObjectMemberKey::Computed(name) = key {
                        return Err(parser[name].error(SyntaxErrorType::ExpectedSyntax(
                            "object pattern property subpattern",
                        )));
                    };
                    None
                };
                let default_value = if parser.consume_if(TokenType::Equals)?.is_match() {
                    Some(parse_expr_until_either(
                        scope,
                        parser,
                        TokenType::Comma,
                        TokenType::BraceClose,
                        syntax,
                    )?)
                } else {
                    None
                };
                if let Some(n) = default_value.or(target) {
                    loc.extend(parser[n].loc());
                };
                let direct_key_name = match &key {
                    ClassOrObjectMemberKey::Direct(name) => Some(name.clone()),
                    _ => None,
                };
                let property = parser.create_node(
                    scope,
                    loc,
                    Syntax::ObjectPatternProperty {
                        key,
                        target,
                        default_value,
                    },
                );
                properties.push(property);
                match (direct_key_name, target, action) {
                    (Some(name), None, ParsePatternAction::AddToBlockScope) => {
                        parser[scope].add_block_symbol(name, Symbol::new(property))?;
                    }
                    (Some(name), None, ParsePatternAction::AddToClosureScope) => {
                        if let Some(closure_id) = parser[scope].self_or_ancestor_closure() {
                            parser[closure_id].add_symbol(name, Symbol::new(property))?;
                        }
                    }
                    _ => {}
                };
                // This will break if `}`.
                if !parser.consume_if(TokenType::Comma)?.is_match() {
                    break;
                };
            }
            let close = parser.require(TokenType::BraceClose)?;
            parser.create_node(
                scope,
                t.loc() + close.loc(),
                Syntax::ObjectPattern { properties, rest },
            )
        }
        TokenType::BracketOpen => {
            let mut elements = Vec::<Option<ArrayPatternElement>>::new();
            let mut rest = None;
            loop {
                if parser.consume_if(TokenType::BracketClose)?.is_match() {
                    break;
                };
                // Check inside loop to ensure that it must come first or after a comma.
                if parser.consume_if(TokenType::DotDotDot)?.is_match() {
                    rest = Some(parse_pattern(scope, parser, action, syntax)?);
                    break;
                };

                // An unnamed element is allowed to ignore that element.
                if parser.consume_if(TokenType::Comma)?.is_match() {
                    elements.push(None);
                } else {
                    let target = parse_pattern(scope, parser, action, syntax)?;
                    let default_value = if parser.consume_if(TokenType::Equals)?.is_match() {
                        Some(parse_expr_until_either(
                            scope,
                            parser,
                            TokenType::Comma,
                            TokenType::BracketClose,
                            syntax,
                        )?)
                    } else {
                        None
                    };
                    elements.push(Some(ArrayPatternElement {
                        target,
                        default_value,
                    }));
                    // This will break if `]`.
                    if !parser.consume_if(TokenType::Comma)?.is_match() {
                        break;
                    };
                };
            }
            let close = parser.require(TokenType::BracketClose)?;
            parser.create_node(
                scope,
                t.loc() + close.loc(),
                Syntax::ArrayPattern { elements, rest },
            )
        }
        _ => return Err(t.error(SyntaxErrorType::ExpectedSyntax("pattern"))),
    })
}