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
use super::ParseCtx;
use super::Parser;
use crate::ast::ArrayPatternElement;
use crate::ast::ClassOrObjectMemberKey;
use crate::ast::Node;
use crate::ast::Syntax;
use crate::error::SyntaxErrorType;
use crate::error::SyntaxResult;
use crate::token::TokenType;
use crate::token::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,
}

#[derive(Clone, Copy)]
pub struct ParsePatternRules {
  // `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,
}

impl ParsePatternRules {
  pub fn with_await_allowed(&self, await_allowed: bool) -> ParsePatternRules {
    Self {
      await_allowed,
      ..*self
    }
  }

  pub fn with_yield_allowed(&self, yield_allowed: bool) -> ParsePatternRules {
    Self {
      yield_allowed,
      ..*self
    }
  }
}

pub fn is_valid_pattern_identifier(typ: TokenType, rules: ParsePatternRules) -> bool {
  match typ {
    TokenType::Identifier => true,
    TokenType::KeywordAwait => rules.await_allowed,
    TokenType::KeywordYield => rules.yield_allowed,
    t => UNRESERVED_KEYWORDS.contains(&t),
  }
}

impl<'a> Parser<'a> {
  fn parse_pattern_identifier(
    &mut self,
    ctx: ParseCtx<'a>,
    action: ParsePatternAction,
  ) -> SyntaxResult<'a, Node<'a>> {
    if !is_valid_pattern_identifier(self.peek()?.typ, ctx.rules) {
      return Err(
        self
          .peek()?
          .error(SyntaxErrorType::ExpectedSyntax("identifier")),
      );
    }
    let t = self.next()?;
    let node = ctx.create_node(t.loc, Syntax::IdentifierPattern { name: t.loc });
    match action {
      ParsePatternAction::None => {}
      ParsePatternAction::AddToBlockScope => {
        ctx.scope.add_block_symbol(t.loc)?;
      }
      ParsePatternAction::AddToClosureScope => {
        if let Some(closure) = ctx.scope.find_self_or_ancestor(|t| t.is_closure()) {
          closure.add_symbol(t.loc)?;
        };
      }
    };
    Ok(node)
  }

  pub fn parse_pattern(
    &mut self,
    ctx: ParseCtx<'a>,
    action: ParsePatternAction,
  ) -> SyntaxResult<'a, Node<'a>> {
    let checkpoint = self.checkpoint();
    let t = self.next()?;
    Ok(match t.typ {
      t if is_valid_pattern_identifier(t, ctx.rules) => {
        self.restore_checkpoint(checkpoint);
        self.parse_pattern_identifier(ctx, action)?
      }
      TokenType::BraceOpen => {
        let mut properties = ctx.session.new_vec();
        let mut rest = None;
        loop {
          if self.peek()?.typ == TokenType::BraceClose {
            break;
          };
          let mut loc = self.peek()?.loc;
          // Check inside loop to ensure that it must come first or after a comma.
          if self.consume_if(TokenType::DotDotDot)?.is_match() {
            rest = Some(self.parse_pattern_identifier(ctx, action)?);
            break;
          };

          let key = if self.consume_if(TokenType::BracketOpen)?.is_match() {
            let expr = self.parse_expr(ctx, TokenType::BracketClose)?;
            self.require(TokenType::BracketClose)?;
            ClassOrObjectMemberKey::Computed(expr)
          } else {
            let name = self.next()?;
            if !is_valid_pattern_identifier(name.typ, ctx.rules) {
              return Err(name.error(SyntaxErrorType::ExpectedNotFound));
            };
            ClassOrObjectMemberKey::Direct(name.loc)
          };
          let (shorthand, target) = if self.consume_if(TokenType::Colon)?.is_match() {
            (false, self.parse_pattern(ctx, action)?)
          } else {
            match key {
              ClassOrObjectMemberKey::Computed(name) => {
                return Err(name.error(SyntaxErrorType::ExpectedSyntax(
                  "object pattern property subpattern",
                )));
              }
              ClassOrObjectMemberKey::Direct(name) => (
                true,
                ctx.create_node(name, Syntax::IdentifierPattern { name }),
              ),
            }
          };
          let default_value = if self.consume_if(TokenType::Equals)?.is_match() {
            Some(self.parse_expr_until_either(ctx, TokenType::Comma, TokenType::BraceClose)?)
          } else {
            None
          };
          loc.extend(default_value.as_ref().unwrap_or(&target).loc);
          let direct_key_name = match &key {
            ClassOrObjectMemberKey::Direct(name) => Some(name.clone()),
            _ => None,
          };
          let property = ctx.create_node(loc, Syntax::ObjectPatternProperty {
            key,
            target,
            default_value,
            shorthand,
          });
          properties.push(property);
          match (direct_key_name, shorthand, action) {
            (Some(name), true, ParsePatternAction::AddToBlockScope) => {
              ctx.scope.add_block_symbol(name)?;
            }
            (Some(name), true, ParsePatternAction::AddToClosureScope) => {
              if let Some(closure) = ctx.scope.find_self_or_ancestor(|t| t.is_closure()) {
                closure.add_symbol(name)?;
              }
            }
            _ => {}
          };
          // This will break if `}`.
          if !self.consume_if(TokenType::Comma)?.is_match() {
            break;
          };
        }
        let close = self.require(TokenType::BraceClose)?;
        ctx.create_node(t.loc + close.loc, Syntax::ObjectPattern {
          properties,
          rest,
        })
      }
      TokenType::BracketOpen => {
        let mut elements = ctx.session.new_vec::<Option<ArrayPatternElement>>();
        let mut rest = None;
        loop {
          if self.consume_if(TokenType::BracketClose)?.is_match() {
            break;
          };
          // Check inside loop to ensure that it must come first or after a comma.
          if self.consume_if(TokenType::DotDotDot)?.is_match() {
            rest = Some(self.parse_pattern(ctx, action)?);
            break;
          };

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