1use crate::ast::*;
38use crate::error::{Result, SyntaxError};
39use crate::lexer::Lexer;
40use crate::token::{Keyword, NumberLiteral, Position, Punct, Span, TemplateKind, Token, TokenKind};
41
42struct Snapshot<'a> {
44 lexer: Lexer<'a>,
45 current: Token,
46 prev_end: Position,
47 strict: bool,
48 allow_in: bool,
49 ctx: FnCtx,
50 loop_depth: u32,
51 switch_depth: u32,
52 labels: Vec<Label>,
53 private: Vec<PrivateEnv>,
54 top_level: bool,
55 cover_inits: Vec<Span>,
56 pending_exports: Vec<(String, Span)>,
57 current_legacy_octal: bool,
58 scopes: Vec<Scope>,
59}
60
61#[derive(Debug, Clone, Copy)]
63struct FnCtx {
64 in_function: bool,
65 in_generator: bool,
66 in_async: bool,
67 in_method: bool,
69 in_derived_constructor: bool,
71 in_static_block: bool,
79 arguments_allowed: bool,
83}
84
85impl Default for FnCtx {
86 fn default() -> FnCtx {
87 FnCtx {
88 in_function: false,
89 in_generator: false,
90 in_async: false,
91 in_method: false,
92 in_derived_constructor: false,
93 in_static_block: false,
94 arguments_allowed: true,
97 }
98 }
99}
100
101#[derive(Debug, Clone, Copy, PartialEq, Eq)]
102enum LabelKind {
103 Iteration,
105 Other,
107}
108
109#[derive(Debug, Clone)]
110struct Label {
111 name: String,
112 kind: LabelKind,
113}
114
115#[derive(Debug, Clone, Default)]
117struct PrivateEnv {
118 names: Vec<PrivateName>,
119}
120
121#[derive(Debug, Clone)]
122struct PrivateName {
123 name: String,
124 has_get: bool,
125 has_set: bool,
126 is_accessor: bool,
132 accessor_is_static: bool,
138}
139
140impl PrivateEnv {
141 fn declare(&mut self, name: &str, accessor: Option<MethodKind>, is_static: bool) -> bool {
149 if let Some(existing) = self.names.iter_mut().find(|n| n.name == name) {
150 return match accessor {
151 Some(MethodKind::Get)
152 if existing.is_accessor
153 && !existing.has_get
154 && existing.accessor_is_static == is_static =>
155 {
156 existing.has_get = true;
157 true
158 }
159 Some(MethodKind::Set)
160 if existing.is_accessor
161 && !existing.has_set
162 && existing.accessor_is_static == is_static =>
163 {
164 existing.has_set = true;
165 true
166 }
167 _ => false,
168 };
169 }
170 let mut entry = PrivateName {
171 name: name.to_string(),
172 has_get: false,
173 has_set: false,
174 is_accessor: accessor.is_some(),
175 accessor_is_static: is_static,
176 };
177 match accessor {
178 Some(MethodKind::Get) => entry.has_get = true,
179 Some(MethodKind::Set) => entry.has_set = true,
180 _ => {}
181 }
182 self.names.push(entry);
183 true
184 }
185
186 fn contains(&self, name: &str) -> bool {
187 self.names.iter().any(|n| n.name == name)
188 }
189}
190
191#[derive(Debug, Clone, Copy, PartialEq, Eq)]
205enum Redefinition {
206 Lexical,
207 Global,
208 Variable,
209 Parameter,
210}
211
212impl Redefinition {
213 fn message(self) -> &'static str {
214 match self {
215 Redefinition::Lexical => "invalid redefinition of lexical identifier",
216 Redefinition::Global => "invalid redefinition of global identifier",
217 Redefinition::Variable => "invalid redefinition of a variable",
218 Redefinition::Parameter => "invalid redefinition of parameter name",
219 }
220 }
221}
222
223#[derive(Debug, Clone)]
224struct Scope {
225 is_var_scope: bool,
227 var_names: Vec<String>,
229 var_names_here: Vec<String>,
237 lex_names: Vec<String>,
239 fn_names: Vec<String>,
246 params: Vec<String>,
248 catch_names: Vec<String>,
256 plain_fn_names: Vec<String>,
265 import_names: Vec<String>,
272}
273
274impl Scope {
275 fn block() -> Scope {
276 Scope {
277 is_var_scope: false,
278 var_names: Vec::new(),
279 var_names_here: Vec::new(),
280 lex_names: Vec::new(),
281 fn_names: Vec::new(),
282 params: Vec::new(),
283 catch_names: Vec::new(),
284 plain_fn_names: Vec::new(),
285 import_names: Vec::new(),
286 }
287 }
288
289 fn function(params: Vec<String>) -> Scope {
290 Scope {
291 is_var_scope: true,
292 var_names: Vec::new(),
293 var_names_here: Vec::new(),
294 lex_names: Vec::new(),
295 fn_names: Vec::new(),
296 params,
297 catch_names: Vec::new(),
298 plain_fn_names: Vec::new(),
299 import_names: Vec::new(),
300 }
301 }
302}
303
304#[derive(Debug, Clone, Copy, PartialEq, Eq)]
306enum TargetKind {
307 Binding,
309 Assignment,
311}
312
313struct ArrowHead {
315 params: Vec<Pattern>,
316 is_async: bool,
317 span: Span,
318 params_span: Span,
319}
320
321pub const DEFAULT_MAX_DEPTH: u32 = if cfg!(debug_assertions) { 120 } else { 600 };
335
336pub struct Parser<'a> {
338 lexer: Lexer<'a>,
339 current: Token,
340 prev_end: Position,
341 strict: bool,
342 module: bool,
343 allow_in: bool,
344 ctx: FnCtx,
345 loop_depth: u32,
346 switch_depth: u32,
347 labels: Vec<Label>,
348 private: Vec<PrivateEnv>,
349 top_level: bool,
350 current_legacy_octal: bool,
353 in_case_clause: bool,
359 depth: u32,
362 max_depth: u32,
363
364 cover_inits: Vec<Span>,
368 pending_exports: Vec<(String, Span)>,
371 scopes: Vec<Scope>,
373}
374
375pub fn parse_script(src: &str) -> Result<Program> {
377 Parser::new(src, false)?.parse_program()
378}
379
380pub fn parse_module(src: &str) -> Result<Program> {
382 Parser::new(src, true)?.parse_program()
383}
384
385pub fn parse_suspensible_script(src: &str) -> Result<Program> {
394 Parser::new_suspensible(src)?.parse_program()
395}
396
397pub fn parse_script_strict(src: &str) -> Result<Program> {
405 let mut parser = Parser::new(src, false)?;
406 parser.enter_strict()?;
407 parser.parse_program()
408}
409
410pub fn parse_eval_script(src: &str, strict: bool) -> Result<Program> {
417 parse_eval_script_in(src, strict, EvalContext::default())
418}
419
420#[derive(Debug, Clone, Copy, Default)]
422pub struct EvalContext {
423 pub in_method: bool,
426 pub in_derived_constructor: bool,
428}
429
430pub fn parse_eval_script_in(src: &str, strict: bool, context: EvalContext) -> Result<Program> {
436 let mut parser = Parser::new(src, false)?;
437 parser.ctx.in_function = true;
438 parser.ctx.in_method = context.in_method;
439 parser.ctx.in_derived_constructor = context.in_derived_constructor;
440 if strict {
441 parser.enter_strict()?;
442 }
443 parser.parse_program()
444}
445
446pub fn parse_suspensible_global_eval(src: &str, strict: bool) -> Result<Program> {
454 let mut parser = Parser::new_suspensible(src)?;
455 if strict {
456 parser.enter_strict()?;
457 }
458 parser.parse_program()
459}
460
461pub fn parse_expression(src: &str) -> Result<Expr> {
464 let mut parser = Parser::new(src, false)?;
465 let expr = parser.parse_expression(true)?;
466 if !parser.current.is_eof() {
467 return Err(parser.unexpected());
468 }
469 Ok(expr)
470}
471
472impl<'a> Parser<'a> {
473 pub fn new(src: &'a str, module: bool) -> Result<Parser<'a>> {
480 Parser::with_modes(src, module, false)
481 }
482
483 pub fn new_suspensible(src: &'a str) -> Result<Parser<'a>> {
490 Parser::with_modes(src, false, true)
491 }
492
493 fn with_modes(src: &'a str, module: bool, async_body: bool) -> Result<Parser<'a>> {
494 let mut lexer = Lexer::new(src);
495 lexer.set_strict(module);
496 let current = lexer.next_token()?;
497 let current_legacy_octal = lexer.had_legacy_octal();
498 if module && current_legacy_octal {
499 return Err(SyntaxError::new(
500 "octal literals and octal escape sequences are not allowed in strict mode",
501 current.span,
502 ));
503 }
504 Ok(Parser {
505 lexer,
506 current,
507 prev_end: Position::START,
508 strict: module,
509 module,
510 allow_in: true,
511 ctx: FnCtx {
512 in_async: module || async_body,
513 ..FnCtx::default()
514 },
515 loop_depth: 0,
516 switch_depth: 0,
517 labels: Vec::new(),
518 private: Vec::new(),
519 top_level: true,
520 current_legacy_octal,
521 in_case_clause: false,
522 depth: 0,
523 max_depth: DEFAULT_MAX_DEPTH,
524
525 cover_inits: Vec::new(),
526 pending_exports: Vec::new(),
527 scopes: vec![Scope::function(Vec::new())],
528 })
529 }
530
531 pub fn set_max_depth(&mut self, depth: u32) {
533 self.max_depth = depth;
534 }
535
536 fn enter(&mut self) -> Result<()> {
538 self.depth += 1;
539 if self.depth > self.max_depth {
540 return Err(SyntaxError::new("stack overflow", self.current.span));
541 }
542 Ok(())
543 }
544
545 fn leave(&mut self) {
546 self.depth -= 1;
547 }
548
549 pub fn parse_program(&mut self) -> Result<Program> {
551 let start = self.current.span.start;
552 let mut body = Vec::new();
553 let mut prologue = true;
554 while !self.current.is_eof() {
555 let stmt = self.parse_statement_list_item()?;
556 if prologue {
557 match self.directive_value(&stmt) {
558 Some(directive) if directive == "use strict" => self.enter_strict()?,
559 Some(_) => {}
560 None => prologue = false,
561 }
562 }
563 body.push(stmt);
564 }
565 if self.module {
566 self.check_module_exports(&body)?;
567 }
568 Ok(Program {
569 kind: if self.module {
570 ProgramKind::Module
571 } else {
572 ProgramKind::Script
573 },
574 body,
575 span: Span::new(start, self.prev_end),
576 strict: self.strict,
577 })
578 }
579
580 fn check_module_exports(&mut self, body: &[Stmt]) -> Result<()> {
583 if self.pending_exports.is_empty() {
584 return Ok(());
585 }
586 let mut declared: Vec<String> = Vec::new();
587 for stmt in body {
588 collect_module_binding(stmt, &mut declared);
589 }
590 let pending = std::mem::take(&mut self.pending_exports);
591 for (name, span) in pending {
592 if !declared.contains(&name) {
593 return Err(self
596 .error_at(format!("exported variable '{name}' does not exist"), span)
597 .positionless());
598 }
599 }
600 Ok(())
601 }
602
603 fn push_scope(&mut self, scope: Scope) {
606 self.scopes.push(scope);
607 }
608
609 fn pop_scope(&mut self) {
610 self.scopes.pop();
611 }
612
613 fn declare_lexical(&mut self, name: &str) -> Result<()> {
620 let Some(scope) = self.scopes.last() else {
621 return Ok(());
622 };
623 let reason = if scope.lex_names.iter().any(|n| n == name)
626 || scope.catch_names.iter().any(|n| n == name)
627 {
628 Some(Redefinition::Lexical)
629 } else if scope.params.iter().any(|n| n == name) {
630 Some(Redefinition::Parameter)
631 } else if scope.fn_names.iter().any(|n| n == name)
632 || scope.var_names.iter().any(|n| n == name)
633 {
634 Some(if self.at_top_level_scope() {
639 Redefinition::Global
640 } else {
641 Redefinition::Variable
642 })
643 } else {
644 None
645 };
646 if let Some(reason) = reason {
647 return Err(self.duplicate_declaration(reason));
648 }
649 if let Some(scope) = self.scopes.last_mut() {
650 scope.lex_names.push(name.to_string());
651 }
652 Ok(())
653 }
654
655 fn declare_var(&mut self, name: &str) -> Result<()> {
658 for scope in self.scopes.iter().rev() {
659 if scope.lex_names.iter().any(|n| n == name) {
660 return Err(self.duplicate_declaration(Redefinition::Lexical));
661 }
662 if scope.is_var_scope {
663 break;
664 }
665 }
666 let Some(index) = self.scopes.iter().rposition(|s| s.is_var_scope) else {
667 return Ok(());
668 };
669 for scope in &mut self.scopes[index..] {
672 if !scope.var_names.iter().any(|n| n == name) {
673 scope.var_names.push(name.to_string());
674 }
675 }
676 if let Some(scope) = self.scopes.last_mut()
677 && !scope.var_names_here.iter().any(|n| n == name)
678 {
679 scope.var_names_here.push(name.to_string());
680 }
681 Ok(())
682 }
683
684 fn check_duplicate_parameters(
705 &self,
706 params: &[Pattern],
707 plain_is_illegal: bool,
708 deferred_at: Span,
709 ) -> Result<()> {
710 let has_default = params.iter().any(pattern_has_default);
711 let mut seen: Vec<String> = Vec::new();
712 let mut deferred = false;
713 for param in params {
714 for (name, span, in_pattern) in parameter_bindings(param) {
715 if seen.iter().any(|seen| seen == &name) {
716 if has_default || in_pattern {
717 return Err(self.error_at(
718 "duplicate parameter names not allowed in this context".to_string(),
719 span,
720 ));
721 }
722 deferred = true;
723 }
724 seen.push(name);
725 }
726 }
727 if deferred && plain_is_illegal {
728 return Err(self.error_at(
729 "duplicate argument names not allowed in this context".to_string(),
730 deferred_at,
731 ));
732 }
733 Ok(())
734 }
735
736 fn declare_function(&mut self, name: &str) -> Result<()> {
752 if !self.scopes.last().is_none_or(|scope| scope.is_var_scope) {
753 return Ok(());
754 }
755 if !self.at_top_level_scope()
761 && self
762 .scopes
763 .last()
764 .is_some_and(|scope| scope.lex_names.iter().any(|n| n == name))
765 {
766 return Err(self.duplicate_declaration(Redefinition::Lexical));
767 }
768 if let Some(scope) = self.scopes.last_mut() {
769 if !scope.var_names.iter().any(|n| n == name) {
770 scope.var_names.push(name.to_string());
771 }
772 if !scope.fn_names.iter().any(|n| n == name) {
773 scope.fn_names.push(name.to_string());
774 }
775 }
776 Ok(())
777 }
778
779 fn declare_block_function(&mut self, name: &str, is_plain: bool) -> Result<()> {
788 if self.module
796 && self.at_top_level_scope()
797 && let Some(scope) = self.scopes.last()
798 {
799 let mut taken = scope.var_names_here.iter().any(|existing| existing == name);
805 if scope.is_var_scope {
806 let module_bindings = scope
807 .lex_names
808 .iter()
809 .filter(|existing| !scope.import_names.contains(existing))
810 .chain(&scope.fn_names);
811 taken |= module_bindings.into_iter().any(|existing| existing == name);
812 }
813 if taken {
814 return Err(self.error_at(
815 "invalid redefinition of global identifier in module code",
816 self.current.span,
817 ));
818 }
819 }
820 if self.scopes.last().is_none_or(|scope| scope.is_var_scope) {
821 return Ok(());
822 }
823 let Some(scope) = self.scopes.last() else {
824 return Ok(());
825 };
826 if scope.lex_names.iter().any(|n| n == name) || scope.catch_names.iter().any(|n| n == name)
827 {
828 let from_plain_function = scope.plain_fn_names.iter().any(|n| n == name);
832 if !(from_plain_function && is_plain && !self.strict) {
833 return Err(self.duplicate_declaration(Redefinition::Lexical));
834 }
835 } else if scope.var_names.iter().any(|n| n == name) {
836 let reason = if self.at_top_level_scope() {
840 Redefinition::Global
841 } else {
842 Redefinition::Variable
843 };
844 return Err(self.duplicate_declaration(reason));
845 }
846 if let Some(scope) = self.scopes.last_mut() {
847 if !scope.lex_names.iter().any(|n| n == name) {
848 scope.lex_names.push(name.to_string());
849 }
850 if !scope.fn_names.iter().any(|n| n == name) {
851 scope.fn_names.push(name.to_string());
852 }
853 if is_plain && !scope.plain_fn_names.iter().any(|n| n == name) {
854 scope.plain_fn_names.push(name.to_string());
855 }
856 }
857 Ok(())
858 }
859
860 fn duplicate_declaration(&self, reason: Redefinition) -> SyntaxError {
872 self.error_at(reason.message(), self.current.span)
873 }
874
875 fn at_top_level_scope(&self) -> bool {
881 self.scopes.iter().rposition(|scope| scope.is_var_scope) == Some(0)
882 }
883
884 fn declare_pattern(&mut self, pattern: &Pattern, is_var: bool) -> Result<()> {
886 let mut names = Vec::new();
887 pattern.bound_names(&mut names);
888 for name in names {
889 if is_var {
890 self.declare_var(&name.name)?;
891 } else {
892 self.declare_lexical(&name.name)?;
893 }
894 }
895 Ok(())
896 }
897
898 fn snapshot(&self) -> Snapshot<'a> {
901 Snapshot {
902 lexer: self.lexer.clone(),
903 current: self.current.clone(),
904 prev_end: self.prev_end,
905 strict: self.strict,
906 allow_in: self.allow_in,
907 ctx: self.ctx,
908 loop_depth: self.loop_depth,
909 switch_depth: self.switch_depth,
910 labels: self.labels.clone(),
911 private: self.private.clone(),
912 top_level: self.top_level,
913 cover_inits: self.cover_inits.clone(),
914 pending_exports: self.pending_exports.clone(),
915 current_legacy_octal: self.current_legacy_octal,
916 scopes: self.scopes.clone(),
917 }
918 }
919
920 fn restore(&mut self, snap: Snapshot<'a>) {
921 self.lexer = snap.lexer;
922 self.current = snap.current;
923 self.prev_end = snap.prev_end;
924 self.strict = snap.strict;
925 self.allow_in = snap.allow_in;
926 self.ctx = snap.ctx;
927 self.loop_depth = snap.loop_depth;
928 self.switch_depth = snap.switch_depth;
929 self.labels = snap.labels;
930 self.private = snap.private;
931 self.top_level = snap.top_level;
932 self.cover_inits = snap.cover_inits;
933 self.pending_exports = snap.pending_exports;
934 self.current_legacy_octal = snap.current_legacy_octal;
935 self.scopes = snap.scopes;
936 }
937
938 fn bump(&mut self) -> Result<()> {
939 self.prev_end = self.current.span.end;
940 self.current = self.lexer.next_token()?;
941 self.current_legacy_octal = self.lexer.had_legacy_octal();
942 if self.strict && self.current_legacy_octal {
943 return Err(SyntaxError::new(
944 "octal literals and octal escape sequences are not allowed in strict mode",
945 self.current.span,
946 ));
947 }
948 Ok(())
949 }
950
951 fn peek(&self) -> Result<Token> {
952 let mut lexer = self.lexer.clone();
953 lexer.next_token()
954 }
955
956 fn enter_strict(&mut self) -> Result<()> {
957 self.strict = true;
958 self.lexer.set_strict(true);
959 if self.current_legacy_octal {
962 return Err(SyntaxError::new(
963 "octal literals and octal escape sequences are not allowed in strict mode",
964 self.current.span,
965 ));
966 }
967 Ok(())
968 }
969
970 fn at_punct(&self, p: Punct) -> bool {
971 matches!(&self.current.kind, TokenKind::Punct(q) if *q == p)
972 }
973
974 fn at_keyword(&self, k: Keyword) -> bool {
975 matches!(&self.current.kind, TokenKind::Keyword(q) if *q == k)
976 }
977
978 fn at_contextual(&self, name: &str) -> bool {
979 self.at_ident(name)
980 }
981
982 fn at_ident(&self, name: &str) -> bool {
989 !self.current.escaped && matches!(&self.current.kind, TokenKind::Ident(n) if n == name)
990 }
991
992 fn eat_punct(&mut self, p: Punct) -> Result<bool> {
993 if self.at_punct(p) {
994 self.bump()?;
995 return Ok(true);
996 }
997 Ok(false)
998 }
999
1000 fn expect_punct(&mut self, p: Punct) -> Result<()> {
1001 if self.eat_punct(p)? {
1002 Ok(())
1003 } else {
1004 Err(self.error(format!("expecting '{}'", p.as_str())))
1009 }
1010 }
1011
1012 fn eat_keyword(&mut self, k: Keyword) -> Result<bool> {
1013 if self.at_keyword(k) {
1014 self.bump()?;
1015 return Ok(true);
1016 }
1017 Ok(false)
1018 }
1019
1020 fn eat_contextual(&mut self, name: &str) -> Result<bool> {
1021 if self.at_ident(name) {
1022 self.bump()?;
1023 return Ok(true);
1024 }
1025 Ok(false)
1026 }
1027
1028 fn unexpected(&self) -> SyntaxError {
1035 let source = self.lexer.source();
1036 let start = self.current.span.start.offset as usize;
1037 let end = self.current.span.end.offset as usize;
1038 let text = source.get(start..end).unwrap_or("");
1039 SyntaxError::new(
1040 format!("unexpected token in expression: '{text}'"),
1041 self.current.span,
1042 )
1043 }
1044
1045 fn error(&self, message: impl Into<String>) -> SyntaxError {
1046 SyntaxError::new(message, self.current.span)
1047 }
1048
1049 fn error_at(&self, message: impl Into<String>, span: Span) -> SyntaxError {
1050 SyntaxError::new(message, span)
1051 }
1052
1053 fn span_from(&self, start: Position) -> Span {
1054 Span::new(start, self.prev_end)
1055 }
1056
1057 fn expect_binding_ident(&mut self) -> Result<Ident> {
1060 let ident = self.expect_ident()?;
1061 self.check_binding_name(&ident.name, ident.span)?;
1062 Ok(ident)
1063 }
1064
1065 fn expect_ident(&mut self) -> Result<Ident> {
1067 match self.current.kind.clone() {
1068 TokenKind::Ident(name) => {
1069 if name == "await" && self.await_is_reserved() {
1072 return Err(self.error("variable name expected"));
1073 }
1074 let span = self.current.span;
1075 self.check_identifier(&name, span)?;
1076 self.bump()?;
1077 Ok(Ident { name, span })
1078 }
1079 _ => Err(self.error("variable name expected")),
1082 }
1083 }
1084
1085 fn at_formal_parameter(&self) -> bool {
1092 if self.at_punct(Punct::LBracket) || self.at_punct(Punct::LBrace) {
1093 return true;
1094 }
1095 match &self.current.kind {
1096 TokenKind::Ident(name) => !(name == "await" && self.await_is_reserved()),
1097 _ => false,
1098 }
1099 }
1100
1101 fn await_is_reserved(&self) -> bool {
1111 self.ctx.in_async || self.module || self.ctx.in_static_block
1114 }
1115
1116 fn check_identifier(&self, name: &str, span: Span) -> Result<()> {
1118 if Keyword::lookup(name).is_some() {
1119 return Err(self.error_at(format!("unexpected keyword '{name}'"), span));
1120 }
1121 if self.strict && Keyword::is_strict_reserved(name) {
1122 return Err(self.error_at(
1123 format!("invalid use of strict mode reserved word '{name}'"),
1124 span,
1125 ));
1126 }
1127 if self.ctx.in_generator && name == "yield" {
1128 return Err(self.error_at(
1129 "invalid use of 'yield' identifier in a generator function",
1130 span,
1131 ));
1132 }
1133 if name == "await" && self.await_is_reserved() {
1134 return Err(self.error_at("unexpected 'await' keyword", span));
1139 }
1140 Ok(())
1141 }
1142
1143 fn check_arguments_reference(&self, name: &str, span: Span) -> Result<()> {
1150 if name == "arguments" && !self.ctx.arguments_allowed {
1151 return Err(self.error_at(
1152 "'arguments' identifier is not allowed in class field initializer",
1153 span,
1154 ));
1155 }
1156 Ok(())
1157 }
1158
1159 fn check_binding_name(&self, name: &str, span: Span) -> Result<()> {
1162 self.check_identifier(name, span)?;
1163 if self.strict && (name == "eval" || name == "arguments") {
1164 return Err(self.error_at("invalid variable name in strict mode", span));
1167 }
1168 if self.strict && name == "let" {
1169 return Err(self.error_at(
1170 "invalid use of 'let' as a variable name in strict mode",
1171 span,
1172 ));
1173 }
1174 Ok(())
1175 }
1176
1177 fn directive_value(&self, stmt: &Stmt) -> Option<String> {
1180 let StmtKind::Expr(expr) = &stmt.kind else {
1181 return None;
1182 };
1183 let ExprKind::String(value) = &expr.unparen().kind else {
1184 return None;
1185 };
1186 let raw = self.slice(expr.span);
1187 if !raw.starts_with('"') && !raw.starts_with('\'') {
1188 return None;
1189 }
1190 if raw.trim_matches(|c| c == '"' || c == '\'').contains('\\') {
1191 return None;
1192 }
1193 Some(value.clone())
1194 }
1195
1196 fn slice(&self, span: Span) -> &'a str {
1197 let src = self.lexer.source();
1198 let start = span.start.offset as usize;
1199 let end = (span.end.offset as usize).min(src.len());
1200 src.get(start..end).unwrap_or("")
1201 }
1202
1203 fn can_insert_semicolon(&self) -> bool {
1206 self.current.is_eof() || self.at_punct(Punct::RBrace) || self.current.newline_before
1207 }
1208
1209 fn semicolon(&mut self) -> Result<()> {
1210 if self.eat_punct(Punct::Semicolon)? {
1211 return Ok(());
1212 }
1213 if self.can_insert_semicolon() {
1214 return Ok(());
1215 }
1216 Err(self.error("expecting ';'"))
1219 }
1220
1221 fn parse_statement_list_item(&mut self) -> Result<Stmt> {
1224 self.enter()?;
1225 let result = self.parse_statement_list_item_guarded();
1226 self.leave();
1227 result
1228 }
1229
1230 fn parse_statement_list_item_guarded(&mut self) -> Result<Stmt> {
1231 let cover_mark = self.cover_inits.len();
1232 let stmt = self.parse_statement_list_item_inner()?;
1233 if self.cover_inits.len() > cover_mark {
1234 let span = self.cover_inits[cover_mark];
1235 self.cover_inits.truncate(cover_mark);
1236 return Err(self.error_at("expecting '}'", span));
1237 }
1238 Ok(stmt)
1239 }
1240
1241 fn parse_statement_list_item_inner(&mut self) -> Result<Stmt> {
1242 if self.at_keyword(Keyword::Function) {
1243 let start = self.current.span.start;
1244 let func = self.parse_function(FunctionForm::Declaration, false, None)?;
1245 if let Some(name) = &func.name {
1246 self.declare_function(&name.name)?;
1247 }
1248 return Ok(Stmt::new(
1249 StmtKind::FuncDecl(Box::new(func)),
1250 self.span_from(start),
1251 ));
1252 }
1253 if self.at_ident("async") {
1254 let peek = self.peek()?;
1255 if matches!(peek.kind, TokenKind::Keyword(Keyword::Function)) && !peek.newline_before {
1256 let start = self.current.span.start;
1257 self.bump()?; let func = self.parse_function(FunctionForm::Declaration, true, Some(start))?;
1259 if let Some(name) = &func.name {
1260 self.declare_function(&name.name)?;
1261 }
1262 return Ok(Stmt::new(
1263 StmtKind::FuncDecl(Box::new(func)),
1264 self.span_from(start),
1265 ));
1266 }
1267 }
1268 if self.at_keyword(Keyword::Class) {
1269 let start = self.current.span.start;
1270 let class = self.parse_class(false)?;
1271 if let Some(name) = &class.name {
1272 self.declare_lexical(&name.name)?;
1273 }
1274 return Ok(Stmt::new(
1275 StmtKind::ClassDecl(Box::new(class)),
1276 self.span_from(start),
1277 ));
1278 }
1279 if self.at_keyword(Keyword::Var) {
1280 let start = self.current.span.start;
1281 let decl = self.parse_var_decl(VarDeclKind::Var, false, true)?;
1282 self.semicolon()?;
1283 return Ok(Stmt::new(StmtKind::VarDecl(decl), self.span_from(start)));
1284 }
1285 if self.at_keyword(Keyword::Const) {
1286 let start = self.current.span.start;
1287 let decl = self.parse_var_decl(VarDeclKind::Const, false, true)?;
1288 self.semicolon()?;
1289 return Ok(Stmt::new(StmtKind::VarDecl(decl), self.span_from(start)));
1290 }
1291 if self.at_ident("let") && self.let_starts_declaration()? {
1292 let start = self.current.span.start;
1293 let decl = self.parse_var_decl(VarDeclKind::Let, false, true)?;
1294 self.semicolon()?;
1295 return Ok(Stmt::new(StmtKind::VarDecl(decl), self.span_from(start)));
1296 }
1297 if self.at_ident("await") && self.ctx.in_async && self.await_using_follows()? {
1300 let start = self.current.span.start;
1301 self.bump()?; let decl = self.parse_var_decl_with_keyword(VarDeclKind::AwaitUsing, "using")?;
1306 self.semicolon()?;
1307 return Ok(Stmt::new(StmtKind::VarDecl(decl), self.span_from(start)));
1308 }
1309 if self.at_ident("using") && self.using_starts_declaration()? {
1310 let start = self.current.span.start;
1311 if self.scopes.len() == 1 && !self.module {
1317 return Err(self.error_at(
1318 "using declaration is not allowed at the top level of a script",
1319 self.span_from(start),
1320 ));
1321 }
1322 if self.in_case_clause {
1327 return Err(self.error_at(
1328 "using declaration is not allowed in this context",
1329 self.span_from(start),
1330 ));
1331 }
1332 let decl = self.parse_var_decl(VarDeclKind::Using, false, true)?;
1333 self.semicolon()?;
1334 return Ok(Stmt::new(StmtKind::VarDecl(decl), self.span_from(start)));
1335 }
1336 let at_module_top_level = self.module && self.scopes.len() == 1;
1343 if at_module_top_level && self.at_keyword(Keyword::Import) {
1344 let peek = self.peek()?;
1345 if !matches!(
1347 peek.kind,
1348 TokenKind::Punct(Punct::LParen) | TokenKind::Punct(Punct::Dot)
1349 ) {
1350 return self.parse_import_decl();
1351 }
1352 }
1353 if at_module_top_level && self.at_keyword(Keyword::Export) {
1354 return self.parse_export_decl();
1355 }
1356 self.parse_statement()
1357 }
1358
1359 fn let_starts_declaration(&self) -> Result<bool> {
1361 let peek = self.peek()?;
1362 Ok(matches!(
1363 peek.kind,
1364 TokenKind::Ident(_)
1365 | TokenKind::Punct(Punct::LBracket)
1366 | TokenKind::Punct(Punct::LBrace)
1367 ))
1368 }
1369
1370 fn using_head_tail(&self, skip: usize) -> Result<Option<Token>> {
1376 let mut lexer = self.lexer.clone();
1377 let mut binding = None;
1381 for _ in 0..=skip {
1382 binding = Some(lexer.next_token()?);
1383 }
1384 let Some(binding) = binding else {
1385 return Ok(None);
1386 };
1387 if binding.newline_before || !matches!(binding.kind, TokenKind::Ident(_)) {
1388 return Ok(None);
1389 }
1390 Ok(Some(lexer.next_token()?))
1391 }
1392
1393 fn await_using_follows(&self) -> Result<bool> {
1399 Ok(matches!(
1400 self.using_head_tail(1)?.map(|token| token.kind),
1401 Some(TokenKind::Punct(Punct::Eq))
1402 ))
1403 }
1404
1405 fn using_starts_declaration(&self) -> Result<bool> {
1416 Ok(matches!(
1417 self.using_head_tail(0)?.map(|token| token.kind),
1418 Some(TokenKind::Punct(Punct::Eq))
1419 ))
1420 }
1421
1422 fn using_starts_for_head(&self) -> Result<bool> {
1427 Ok(matches!(
1428 self.using_head_tail(0)?.map(|token| token.kind),
1429 Some(TokenKind::Ident(name)) if name == "of" || name == "in"
1430 ))
1431 }
1432
1433 fn await_using_starts_for_head(&self) -> Result<bool> {
1435 Ok(matches!(
1436 self.using_head_tail(1)?.map(|token| token.kind),
1437 Some(TokenKind::Ident(name)) if name == "of" || name == "in"
1438 ))
1439 }
1440
1441 fn parse_statement(&mut self) -> Result<Stmt> {
1442 let start = self.current.span.start;
1443 if self.at_punct(Punct::Semicolon) {
1444 self.bump()?;
1445 return Ok(Stmt::new(StmtKind::Empty, self.span_from(start)));
1446 }
1447 if self.at_punct(Punct::LBrace) {
1448 let body = self.parse_block()?;
1449 return Ok(Stmt::new(StmtKind::Block(body), self.span_from(start)));
1450 }
1451 if self.at_keyword(Keyword::If) {
1452 return self.parse_if();
1453 }
1454 if self.at_keyword(Keyword::Do) {
1455 return self.parse_do_while();
1456 }
1457 if self.at_keyword(Keyword::While) {
1458 return self.parse_while();
1459 }
1460 if self.at_keyword(Keyword::For) {
1461 return self.parse_for();
1462 }
1463 if self.at_keyword(Keyword::Switch) {
1464 return self.parse_switch();
1465 }
1466 if self.at_keyword(Keyword::Try) {
1467 return self.parse_try();
1468 }
1469 if self.at_keyword(Keyword::Return) {
1470 return self.parse_return();
1471 }
1472 if self.at_keyword(Keyword::Throw) {
1473 return self.parse_throw();
1474 }
1475 if self.at_keyword(Keyword::Break) {
1476 return self.parse_break_continue(true);
1477 }
1478 if self.at_keyword(Keyword::Continue) {
1479 return self.parse_break_continue(false);
1480 }
1481 if self.at_keyword(Keyword::With) {
1482 return self.parse_with();
1483 }
1484 if self.at_keyword(Keyword::Debugger) {
1485 self.bump()?;
1486 self.semicolon()?;
1487 return Ok(Stmt::new(StmtKind::Debugger, self.span_from(start)));
1488 }
1489 if self.at_keyword(Keyword::Function) {
1490 if self.strict {
1493 return Err(
1494 self.error("invalid 'function' declaration in a single statement context")
1495 );
1496 }
1497 let func = self.parse_function(FunctionForm::Declaration, false, None)?;
1498 if let Some(name) = &func.name {
1499 self.declare_function(&name.name)?;
1500 }
1501 return Ok(Stmt::new(
1502 StmtKind::FuncDecl(Box::new(func)),
1503 self.span_from(start),
1504 ));
1505 }
1506 if self.at_keyword(Keyword::Class) {
1507 return Err(self.error("invalid 'class' declaration in a single statement context"));
1508 }
1509 if self.at_keyword(Keyword::Import) {
1510 let peek = self.peek()?;
1514 let expression = matches!(
1515 peek.kind,
1516 TokenKind::Punct(Punct::LParen) | TokenKind::Punct(Punct::Dot)
1517 );
1518 if !expression {
1519 return Err(self.error("'import' can only appear at the top level of a module"));
1520 }
1521 }
1522 if self.at_keyword(Keyword::Export) {
1523 return Err(self.error("'export' can only appear at the top level of a module"));
1524 }
1525 if let TokenKind::Ident(name) = &self.current.kind {
1527 if name == "await" && self.await_is_reserved() {
1531 if !self.ctx.in_async {
1532 let peek = self.peek()?;
1535 if matches!(peek.kind, TokenKind::Punct(Punct::Colon)) {
1536 return Err(self.error("unexpected 'await' keyword"));
1537 }
1538 }
1539 } else {
1543 let peek = self.peek()?;
1544 if matches!(peek.kind, TokenKind::Punct(Punct::Colon)) {
1545 return self.parse_labeled();
1546 }
1547 }
1548 }
1549 self.parse_expression_statement()
1550 }
1551
1552 fn parse_block(&mut self) -> Result<Vec<Stmt>> {
1553 self.expect_punct(Punct::LBrace)?;
1554 self.push_scope(Scope::block());
1555 let saved_in_case = self.in_case_clause;
1558 self.in_case_clause = false;
1559 let result = self.parse_block_body();
1560 self.in_case_clause = saved_in_case;
1561 self.pop_scope();
1562 let body = result?;
1563 self.bump()?; Ok(body)
1565 }
1566
1567 fn parse_catch_body(&mut self) -> Result<Vec<Stmt>> {
1569 self.expect_punct(Punct::LBrace)?;
1570 let body = self.parse_block_body()?;
1571 self.bump()?; Ok(body)
1573 }
1574
1575 fn parse_block_body(&mut self) -> Result<Vec<Stmt>> {
1576 let mut body = Vec::new();
1577 while !self.at_punct(Punct::RBrace) {
1578 if self.current.is_eof() {
1579 return Err(self.unexpected());
1580 }
1581 body.push(self.parse_statement_list_item()?);
1582 }
1583 Ok(body)
1584 }
1585
1586 fn parse_expression_statement(&mut self) -> Result<Stmt> {
1587 let start = self.current.span.start;
1588 let expr = self.parse_expression(true)?;
1589 self.semicolon()?;
1590 Ok(Stmt::new(
1591 StmtKind::Expr(Box::new(expr)),
1592 self.span_from(start),
1593 ))
1594 }
1595
1596 fn parse_if(&mut self) -> Result<Stmt> {
1597 let start = self.current.span.start;
1598 self.bump()?; self.expect_punct(Punct::LParen)?;
1600 let test = self.parse_expression(true)?;
1601 self.expect_punct(Punct::RParen)?;
1602 let cons = self.parse_statement()?;
1603 let alt = if self.eat_keyword(Keyword::Else)? {
1604 Some(Box::new(self.parse_statement()?))
1605 } else {
1606 None
1607 };
1608 Ok(Stmt::new(
1609 StmtKind::If {
1610 test: Box::new(test),
1611 cons: Box::new(cons),
1612 alt,
1613 },
1614 self.span_from(start),
1615 ))
1616 }
1617
1618 fn parse_do_while(&mut self) -> Result<Stmt> {
1619 let start = self.current.span.start;
1620 self.bump()?; self.loop_depth += 1;
1622 let body = self.parse_statement();
1623 self.loop_depth -= 1;
1624 let body = body?;
1625 if !self.eat_keyword(Keyword::While)? {
1626 return Err(self.unexpected());
1627 }
1628 self.expect_punct(Punct::LParen)?;
1629 let test = self.parse_expression(true)?;
1630 self.expect_punct(Punct::RParen)?;
1631 let _ = self.eat_punct(Punct::Semicolon)?;
1633 Ok(Stmt::new(
1634 StmtKind::DoWhile {
1635 body: Box::new(body),
1636 test: Box::new(test),
1637 },
1638 self.span_from(start),
1639 ))
1640 }
1641
1642 fn parse_while(&mut self) -> Result<Stmt> {
1643 let start = self.current.span.start;
1644 self.bump()?; self.expect_punct(Punct::LParen)?;
1646 let test = self.parse_expression(true)?;
1647 self.expect_punct(Punct::RParen)?;
1648 self.loop_depth += 1;
1649 let body = self.parse_statement();
1650 self.loop_depth -= 1;
1651 Ok(Stmt::new(
1652 StmtKind::While {
1653 test: Box::new(test),
1654 body: Box::new(body?),
1655 },
1656 self.span_from(start),
1657 ))
1658 }
1659
1660 fn parse_for(&mut self) -> Result<Stmt> {
1661 let start = self.current.span.start;
1662 self.bump()?; self.push_scope(Scope::block());
1664 let result = self.parse_for_inner(start);
1665 self.pop_scope();
1666 result
1667 }
1668
1669 fn parse_for_inner(&mut self, start: Position) -> Result<Stmt> {
1670 let mut is_await = false;
1671 if self.at_ident("await") && self.ctx.in_async {
1672 let peek = self.peek()?;
1673 if matches!(peek.kind, TokenKind::Punct(Punct::LParen)) && !peek.newline_before {
1674 is_await = true;
1675 self.bump()?;
1676 }
1677 }
1678 self.expect_punct(Punct::LParen)?;
1679
1680 if self.at_punct(Punct::Semicolon) {
1682 self.bump()?;
1683 return self.parse_for_classic(start, None);
1684 }
1685
1686 let decl_kind = if self.at_keyword(Keyword::Var) {
1688 Some(VarDeclKind::Var)
1689 } else if self.at_keyword(Keyword::Const) {
1690 Some(VarDeclKind::Const)
1691 } else if self.at_ident("let") && self.let_starts_declaration()? {
1692 Some(VarDeclKind::Let)
1693 } else if self.at_ident("using") && self.using_starts_for_head()? {
1694 Some(VarDeclKind::Using)
1695 } else if self.at_ident("await")
1696 && self.ctx.in_async
1697 && self.await_using_starts_for_head()?
1698 {
1699 self.bump()?; Some(VarDeclKind::AwaitUsing)
1701 } else {
1702 None
1703 };
1704 if let Some(kind) = decl_kind {
1705 let decl_start = self.current.span.start;
1706 let decl = self.parse_var_decl(kind, true, false)?;
1707 if self.at_for_head_keyword() {
1708 let is_of = self.at_contextual("of");
1709 if !is_of && decl.declarators.len() != 1 {
1710 return Err(self.error_at(
1711 "only one binding allowed in a for-in loop",
1712 self.span_from(decl_start),
1713 ));
1714 }
1715 if is_of && decl.declarators.len() != 1 {
1716 return Err(self.error_at(
1717 "only one binding allowed in a for-of loop",
1718 self.span_from(decl_start),
1719 ));
1720 }
1721 if let Some(declarator) = decl.declarators.first() {
1722 if declarator.init.is_some() {
1723 if is_of || kind.is_lexical() || self.strict {
1725 return Err(self.error_at(
1726 if is_of {
1727 "a declaration in the head of a for-of loop can't have an initializer"
1729 } else {
1730 "a declaration in the head of a for-in loop can't have an initializer"
1731 },
1732 declarator.span,
1733 ));
1734 }
1735 }
1736 }
1737 if is_await && !is_of {
1738 return Err(self.error("for await is only valid with 'of'"));
1739 }
1740 self.bump()?; let right = self.parse_expression(true)?;
1742 self.expect_punct(Punct::RParen)?;
1743 self.loop_depth += 1;
1744 let body = self.parse_statement();
1745 self.loop_depth -= 1;
1746 let head = ForHead::VarDecl(decl);
1747 let span = self.span_from(start);
1748 return Ok(Stmt::new(
1749 if is_of {
1750 StmtKind::ForOf {
1751 is_await,
1752 left: head,
1753 right: Box::new(right),
1754 body: Box::new(body?),
1755 }
1756 } else {
1757 StmtKind::ForIn {
1758 left: head,
1759 right: Box::new(right),
1760 body: Box::new(body?),
1761 }
1762 },
1763 span,
1764 ));
1765 }
1766 self.expect_punct(Punct::Semicolon)?;
1767 return self.parse_for_classic(start, Some(ForInit::VarDecl(decl)));
1768 }
1769
1770 let expr_start = self.current.span.start;
1772 let expr = self.parse_expression(false)?;
1773 if self.at_for_head_keyword() {
1774 let is_of = self.at_contextual("of");
1775 if is_await && !is_of {
1776 return Err(self.error("for await is only valid with 'of'"));
1777 }
1778 let target = self.expr_to_pattern(expr, TargetKind::Assignment)?;
1779 self.bump()?; let right = self.parse_expression(true)?;
1781 self.expect_punct(Punct::RParen)?;
1782 self.loop_depth += 1;
1783 let body = self.parse_statement();
1784 self.loop_depth -= 1;
1785 let head = ForHead::Assign(Box::new(target));
1786 let span = self.span_from(start);
1787 return Ok(Stmt::new(
1788 if is_of {
1789 StmtKind::ForOf {
1790 is_await,
1791 left: head,
1792 right: Box::new(right),
1793 body: Box::new(body?),
1794 }
1795 } else {
1796 StmtKind::ForIn {
1797 left: head,
1798 right: Box::new(right),
1799 body: Box::new(body?),
1800 }
1801 },
1802 span,
1803 ));
1804 }
1805 let _ = expr_start;
1806 self.expect_punct(Punct::Semicolon)?;
1807 self.parse_for_classic(start, Some(ForInit::Expr(Box::new(expr))))
1808 }
1809
1810 fn at_for_head_keyword(&self) -> bool {
1813 self.at_keyword(Keyword::In) || self.at_contextual("of")
1814 }
1815
1816 fn parse_for_classic(&mut self, start: Position, init: Option<ForInit>) -> Result<Stmt> {
1817 let test = if self.at_punct(Punct::Semicolon) {
1818 None
1819 } else {
1820 Some(Box::new(self.parse_expression(true)?))
1821 };
1822 self.expect_punct(Punct::Semicolon)?;
1823 let update = if self.at_punct(Punct::RParen) {
1824 None
1825 } else {
1826 Some(Box::new(self.parse_expression(true)?))
1827 };
1828 self.expect_punct(Punct::RParen)?;
1829 self.loop_depth += 1;
1830 let body = self.parse_statement();
1831 self.loop_depth -= 1;
1832 Ok(Stmt::new(
1833 StmtKind::For {
1834 init,
1835 test,
1836 update,
1837 body: Box::new(body?),
1838 },
1839 self.span_from(start),
1840 ))
1841 }
1842
1843 fn parse_switch(&mut self) -> Result<Stmt> {
1844 let start = self.current.span.start;
1845 self.bump()?; self.expect_punct(Punct::LParen)?;
1847 let discriminant = self.parse_expression(true)?;
1848 self.expect_punct(Punct::RParen)?;
1849 self.expect_punct(Punct::LBrace)?;
1850 self.switch_depth += 1;
1851 self.push_scope(Scope::block());
1852 let mut cases = Vec::new();
1853 let mut seen_default = false;
1854 while !self.at_punct(Punct::RBrace) {
1855 if self.current.is_eof() {
1856 self.switch_depth -= 1;
1857 return Err(self.unexpected());
1858 }
1859 let case_start = self.current.span.start;
1860 let test = if self.eat_keyword(Keyword::Case)? {
1861 Some(Box::new(self.parse_expression(true)?))
1862 } else if self.eat_keyword(Keyword::Default)? {
1863 if seen_default {
1864 self.switch_depth -= 1;
1865 return Err(self.error("duplicate 'default' clause in switch statement"));
1866 }
1867 seen_default = true;
1868 None
1869 } else {
1870 self.switch_depth -= 1;
1871 return Err(self.unexpected());
1872 };
1873 self.expect_punct(Punct::Colon)?;
1874 let mut body = Vec::new();
1875 let saved_in_case = self.in_case_clause;
1876 self.in_case_clause = true;
1877 while !self.at_punct(Punct::RBrace)
1878 && !self.at_keyword(Keyword::Case)
1879 && !self.at_keyword(Keyword::Default)
1880 {
1881 if self.current.is_eof() {
1882 self.in_case_clause = saved_in_case;
1883 self.switch_depth -= 1;
1884 return Err(self.unexpected());
1885 }
1886 match self.parse_statement_list_item() {
1887 Ok(stmt) => body.push(stmt),
1888 Err(error) => {
1889 self.in_case_clause = saved_in_case;
1890 self.switch_depth -= 1;
1891 return Err(error);
1892 }
1893 }
1894 }
1895 self.in_case_clause = saved_in_case;
1896 cases.push(SwitchCase {
1897 test,
1898 body,
1899 span: self.span_from(case_start),
1900 });
1901 }
1902 self.switch_depth -= 1;
1903 self.bump()?; self.pop_scope();
1912 Ok(Stmt::new(
1913 StmtKind::Switch {
1914 discriminant: Box::new(discriminant),
1915 cases,
1916 },
1917 self.span_from(start),
1918 ))
1919 }
1920
1921 fn parse_try(&mut self) -> Result<Stmt> {
1922 let start = self.current.span.start;
1923 self.bump()?; let block = self.parse_block()?;
1925 let mut handler = None;
1926 let mut finalizer = None;
1927 if self.at_keyword(Keyword::Catch) {
1928 let catch_start = self.current.span.start;
1929 self.bump()?;
1930 let param = if self.eat_punct(Punct::LParen)? {
1936 let pattern = self.parse_binding_target()?;
1937 self.expect_punct(Punct::RParen)?;
1938 Some(pattern)
1939 } else {
1940 None
1941 };
1942 self.push_scope(Scope::block());
1943 let body = match ¶m {
1944 Some(Pattern {
1947 kind: PatternKind::Ident(id),
1948 ..
1949 }) => {
1950 if let Some(scope) = self.scopes.last_mut() {
1951 scope.catch_names.push(id.name.clone());
1952 }
1953 self.parse_catch_body()
1954 }
1955 Some(pattern) => {
1960 self.declare_pattern(pattern, false)?;
1961 self.parse_block()
1962 }
1963 None => self.parse_catch_body(),
1964 };
1965 self.pop_scope();
1966 let body = body?;
1967 handler = Some(CatchClause {
1968 param,
1969 body,
1970 span: self.span_from(catch_start),
1971 });
1972 }
1973 if self.eat_keyword(Keyword::Finally)? {
1974 finalizer = Some(self.parse_block()?);
1975 }
1976 if handler.is_none() && finalizer.is_none() {
1977 return Err(self.error("expecting catch or finally"));
1978 }
1979 Ok(Stmt::new(
1980 StmtKind::Try {
1981 block,
1982 handler,
1983 finalizer,
1984 },
1985 self.span_from(start),
1986 ))
1987 }
1988
1989 fn parse_return(&mut self) -> Result<Stmt> {
1990 let start = self.current.span.start;
1991 let span = self.current.span;
1992 if !self.ctx.in_function {
1993 return Err(self.error_at("return not in a function", span));
1994 }
1995 if self.ctx.in_static_block {
1996 return Err(self.error_at("return in a static initializer block", span));
2000 }
2001 self.bump()?;
2002 let argument = if self.at_punct(Punct::Semicolon)
2003 || self.at_punct(Punct::RBrace)
2004 || self.current.is_eof()
2005 || self.current.newline_before
2006 {
2007 None
2008 } else {
2009 Some(Box::new(self.parse_expression(true)?))
2010 };
2011 self.semicolon()?;
2012 Ok(Stmt::new(StmtKind::Return(argument), self.span_from(start)))
2013 }
2014
2015 fn parse_throw(&mut self) -> Result<Stmt> {
2016 let start = self.current.span.start;
2017 self.bump()?; if self.current.newline_before {
2019 return Err(self.error("line terminator not allowed after 'throw'"));
2020 }
2021 let argument = self.parse_expression(true)?;
2022 self.semicolon()?;
2023 Ok(Stmt::new(
2024 StmtKind::Throw(Box::new(argument)),
2025 self.span_from(start),
2026 ))
2027 }
2028
2029 fn parse_break_continue(&mut self, is_break: bool) -> Result<Stmt> {
2030 let start = self.current.span.start;
2031 let keyword_span = self.current.span;
2032 self.bump()?;
2033 let label = if matches!(self.current.kind, TokenKind::Ident(_))
2034 && !self.current.newline_before
2035 {
2036 let ident = self.expect_ident()?;
2037 let found = self.labels.iter().rev().find(|l| l.name == ident.name);
2038 match found {
2039 None => {
2040 return Err(
2041 self.error_at(format!("label '{}' not found", ident.name), ident.span)
2042 );
2043 }
2044 Some(label) => {
2045 if !is_break && label.kind != LabelKind::Iteration {
2046 return Err(self.error_at(
2047 format!("continue must be inside loop (label '{}')", ident.name),
2048 ident.span,
2049 ));
2050 }
2051 }
2052 }
2053 Some(ident)
2054 } else {
2055 if !is_break && self.loop_depth == 0 {
2056 return Err(self.error_at("continue must be inside loop", keyword_span));
2057 }
2058 if is_break && self.loop_depth == 0 && self.switch_depth == 0 && self.labels.is_empty()
2059 {
2060 return Err(self.error_at("break must be inside loop or switch", keyword_span));
2061 }
2062 None
2063 };
2064 self.semicolon()?;
2065 Ok(Stmt::new(
2066 if is_break {
2067 StmtKind::Break(label)
2068 } else {
2069 StmtKind::Continue(label)
2070 },
2071 self.span_from(start),
2072 ))
2073 }
2074
2075 fn parse_with(&mut self) -> Result<Stmt> {
2076 let start = self.current.span.start;
2077 let span = self.current.span;
2078 if self.strict {
2079 return Err(self.error_at("invalid keyword: with", span));
2080 }
2081 self.bump()?; self.expect_punct(Punct::LParen)?;
2083 let object = self.parse_expression(true)?;
2084 self.expect_punct(Punct::RParen)?;
2085 let body = self.parse_statement()?;
2086 Ok(Stmt::new(
2087 StmtKind::With {
2088 object: Box::new(object),
2089 body: Box::new(body),
2090 },
2091 self.span_from(start),
2092 ))
2093 }
2094
2095 fn parse_labeled(&mut self) -> Result<Stmt> {
2096 let start = self.current.span.start;
2097 let label = self.expect_ident()?;
2098 self.expect_punct(Punct::Colon)?;
2099 if self.labels.iter().any(|l| l.name == label.name) {
2100 return Err(self.error_at(
2101 format!("label '{}' already declared", label.name),
2102 label.span,
2103 ));
2104 }
2105 let kind = if self.at_keyword(Keyword::For)
2106 || self.at_keyword(Keyword::While)
2107 || self.at_keyword(Keyword::Do)
2108 {
2109 LabelKind::Iteration
2110 } else {
2111 LabelKind::Other
2112 };
2113 self.labels.push(Label {
2114 name: label.name.clone(),
2115 kind,
2116 });
2117 let body = self.parse_statement();
2118 self.labels.pop();
2119 Ok(Stmt::new(
2120 StmtKind::Labeled {
2121 label,
2122 body: Box::new(body?),
2123 },
2124 self.span_from(start),
2125 ))
2126 }
2127
2128 fn parse_var_decl(
2131 &mut self,
2132 kind: VarDeclKind,
2133 in_for_head: bool,
2134 require_init: bool,
2135 ) -> Result<VarDecl> {
2136 let start = self.current.span.start;
2137 self.bump()?; self.parse_var_declarators(kind, in_for_head, require_init, start)
2139 }
2140
2141 fn parse_var_decl_with_keyword(&mut self, kind: VarDeclKind, keyword: &str) -> Result<VarDecl> {
2146 let start = self.current.span.start;
2147 if !self.at_ident(keyword) {
2148 return Err(self.error(format!("expected '{keyword}'")));
2149 }
2150 self.bump()?;
2151 self.parse_var_declarators(kind, false, true, start)
2152 }
2153
2154 fn parse_var_declarators(
2155 &mut self,
2156 kind: VarDeclKind,
2157 in_for_head: bool,
2158 require_init: bool,
2159 start: Position,
2160 ) -> Result<VarDecl> {
2161 let mut declarators = Vec::new();
2162 loop {
2163 let declarator_start = self.current.span.start;
2164 let target = self.parse_binding_target()?;
2165 self.declare_pattern(&target, !kind.is_lexical())?;
2170 if kind.is_using() && !matches!(target.unparen_kind(), PatternKind::Ident(_)) {
2173 return Err(self.error_at(
2174 "binding patterns are not allowed in using declarations",
2175 target.span,
2176 ));
2177 }
2178 let init = if self.eat_punct(Punct::Eq)? {
2179 Some(Box::new(self.parse_assignment(!in_for_head)?))
2182 } else {
2183 None
2184 };
2185 if init.is_none() && require_init {
2186 if kind == VarDeclKind::Const {
2187 return Err(self.error("missing initializer for const variable"));
2188 }
2189 if kind.is_using() {
2190 return Err(self.error("missing initializer in using declaration"));
2191 }
2192 if !matches!(target.unparen_kind(), PatternKind::Ident(_)) && !in_for_head {
2193 return Err(self.error_at(
2194 "missing initializer in destructuring declaration",
2195 target.span,
2196 ));
2197 }
2198 }
2199 if kind.is_lexical() {
2200 let mut names = Vec::new();
2201 target.bound_names(&mut names);
2202 if let Some(name) = names.iter().find(|n| n.name == "let") {
2203 return Err(self.error_at("'let' is not a valid lexical identifier", name.span));
2204 }
2205 }
2206 declarators.push(Declarator {
2207 target,
2208 init,
2209 span: self.span_from(declarator_start),
2210 });
2211 if !self.eat_punct(Punct::Comma)? {
2212 break;
2213 }
2214 }
2215 Ok(VarDecl {
2216 kind,
2217 declarators,
2218 span: self.span_from(start),
2219 })
2220 }
2221
2222 fn parse_binding_element(&mut self) -> Result<Pattern> {
2225 let pattern = self.parse_binding_target()?;
2226 if self.eat_punct(Punct::Eq)? {
2227 let start = pattern.span.start;
2228 let default = self.parse_assignment(self.allow_in)?;
2229 return Ok(Pattern::new(
2230 PatternKind::Assign {
2231 target: Box::new(pattern),
2232 default: Box::new(default),
2233 },
2234 self.span_from(start),
2235 ));
2236 }
2237 Ok(pattern)
2238 }
2239
2240 fn parse_binding_target(&mut self) -> Result<Pattern> {
2243 self.enter()?;
2244 let result = self.parse_binding_target_unguarded();
2245 self.leave();
2246 result
2247 }
2248
2249 fn parse_binding_target_unguarded(&mut self) -> Result<Pattern> {
2250 let start = self.current.span.start;
2251 if self.at_punct(Punct::LBracket) {
2252 return self.parse_array_pattern(start);
2253 }
2254 if self.at_punct(Punct::LBrace) {
2255 return self.parse_object_pattern(start);
2256 }
2257 let ident = self.expect_binding_ident()?;
2258 Ok(Pattern::new(
2259 PatternKind::Ident(ident),
2260 self.span_from(start),
2261 ))
2262 }
2263
2264 fn parse_array_pattern(&mut self, start: Position) -> Result<Pattern> {
2265 self.expect_punct(Punct::LBracket)?;
2266 let mut elements = Vec::new();
2267 let mut rest = None;
2268 loop {
2269 if self.at_punct(Punct::RBracket) {
2270 break;
2271 }
2272 if self.at_punct(Punct::Comma) {
2273 self.bump()?;
2274 elements.push(None);
2275 continue;
2276 }
2277 if self.at_punct(Punct::Ellipsis) {
2278 self.bump()?;
2279 let target = self.parse_binding_target()?;
2280 if self.at_punct(Punct::Comma) {
2281 return Err(self.error("rest element must be the last one"));
2282 }
2283 rest = Some(Box::new(RestElement::Pattern(target)));
2284 break;
2285 }
2286 let element_start = self.current.span.start;
2287 let element = self.parse_binding_element()?;
2288 let span = self.span_from(element_start);
2289 elements.push(Some(PatternElement::Pattern(element)));
2290 let _ = span;
2291 if !self.eat_punct(Punct::Comma)? {
2292 break;
2293 }
2294 }
2295 self.expect_punct(Punct::RBracket)?;
2296 Ok(Pattern::new(
2297 PatternKind::Array { elements, rest },
2298 self.span_from(start),
2299 ))
2300 }
2301
2302 fn parse_object_pattern(&mut self, start: Position) -> Result<Pattern> {
2303 self.expect_punct(Punct::LBrace)?;
2304 let mut properties = Vec::new();
2305 let mut rest = None;
2306 loop {
2307 if self.at_punct(Punct::RBrace) {
2308 break;
2309 }
2310 if self.at_punct(Punct::Ellipsis) {
2311 self.bump()?;
2312 let target = self.parse_binding_target()?;
2313 rest = Some(Box::new(RestElement::Pattern(target)));
2314 if self.at_punct(Punct::Comma) {
2315 return Err(self.error("rest element must be the last one"));
2316 }
2317 break;
2318 }
2319 let property_start = self.current.span.start;
2320 let key = self.parse_property_key()?;
2321 if self.eat_punct(Punct::Colon)? {
2322 let value = self.parse_binding_element()?;
2323 properties.push(Some(PatternElement::Property {
2324 key,
2325 value,
2326 shorthand: false,
2327 span: self.span_from(property_start),
2328 }));
2329 } else {
2330 let PropName::Literal(PropKey::Str(name)) = &key else {
2331 return Err(
2332 self.error("expecting ':' after a computed or numeric property key")
2333 );
2334 };
2335 let span = self.span_from(property_start);
2336 let ident = Ident {
2337 name: name.clone(),
2338 span,
2339 };
2340 self.check_binding_name(&ident.name, ident.span)?;
2341 let mut value = Pattern::new(PatternKind::Ident(ident), span);
2342 if self.eat_punct(Punct::Eq)? {
2343 let default = self.parse_assignment(self.allow_in)?;
2344 value = Pattern::new(
2345 PatternKind::Assign {
2346 target: Box::new(value),
2347 default: Box::new(default),
2348 },
2349 span,
2350 );
2351 }
2352 properties.push(Some(PatternElement::Property {
2353 key,
2354 value,
2355 shorthand: true,
2356 span,
2357 }));
2358 }
2359 if !self.eat_punct(Punct::Comma)? {
2360 break;
2361 }
2362 }
2363 self.expect_punct(Punct::RBrace)?;
2364 Ok(Pattern::new(
2365 PatternKind::Object { properties, rest },
2366 self.span_from(start),
2367 ))
2368 }
2369
2370 fn parse_property_key(&mut self) -> Result<PropName> {
2372 match self.current.kind.clone() {
2373 TokenKind::Ident(name) => {
2374 self.bump()?;
2375 Ok(PropName::Literal(PropKey::Str(name)))
2376 }
2377 TokenKind::Keyword(kw) => {
2378 self.bump()?;
2380 Ok(PropName::Literal(PropKey::Str(kw.as_str().to_string())))
2381 }
2382 TokenKind::String(value) => {
2383 self.bump()?;
2384 Ok(PropName::Literal(PropKey::Str(value)))
2385 }
2386 TokenKind::Number(NumberLiteral::Int(v)) => {
2387 self.bump()?;
2388 Ok(PropName::Literal(PropKey::Num(v as f64)))
2389 }
2390 TokenKind::Number(NumberLiteral::Float(v)) => {
2391 self.bump()?;
2392 Ok(PropName::Literal(PropKey::Num(v)))
2393 }
2394 TokenKind::BigInt(big) => Err(self.error(format!(
2395 "BigInt property keys are not supported ('{}n')",
2396 big.digits
2397 ))),
2398 TokenKind::Punct(Punct::LBracket) => {
2399 self.bump()?;
2400 let expr = self.parse_assignment(true)?;
2401 self.expect_punct(Punct::RBracket)?;
2402 Ok(PropName::Computed(Box::new(expr)))
2403 }
2404 TokenKind::Punct(Punct::Hash) => {
2405 let ident = self.parse_private_name()?;
2406 Ok(PropName::Private(ident))
2407 }
2408 _ => Err(self.error("invalid property name")),
2411 }
2412 }
2413
2414 fn parse_function(
2424 &mut self,
2425 form: FunctionForm,
2426 is_async: bool,
2427 start: Option<Position>,
2428 ) -> Result<Function> {
2429 let start = start.unwrap_or(self.current.span.start);
2430 self.bump()?; let is_generator = self.eat_punct(Punct::Star)?;
2432 let name = if matches!(self.current.kind, TokenKind::Ident(_)) {
2433 let ident = if form == FunctionForm::Declaration {
2434 self.expect_binding_ident()?
2435 } else {
2436 self.expect_ident()?
2437 };
2438 if is_generator && ident.name == "yield" {
2439 return Err(self.error_at("invalid use of 'yield' as a function name", ident.span));
2440 }
2441 if is_async && ident.name == "await" {
2442 return Err(self.error_at("invalid use of 'await' as a function name", ident.span));
2443 }
2444 Some(ident)
2445 } else {
2446 if form == FunctionForm::Declaration {
2447 return Err(self.error("function name expected"));
2448 }
2449 None
2450 };
2451 if form == FunctionForm::Declaration
2461 && let Some(ident) = &name
2462 {
2463 self.declare_block_function(&ident.name, !is_async && !is_generator)?;
2464 }
2465 let saved = self.ctx;
2466 self.ctx = FnCtx {
2467 in_function: true,
2468 in_generator: is_generator,
2469 in_async: is_async,
2470 in_method: false,
2471 in_derived_constructor: false,
2472 in_static_block: false,
2473 arguments_allowed: true,
2474 };
2475 let saved_top = self.top_level;
2476 self.top_level = false;
2477 let params_result = self.parse_formal_parameters();
2483 let result = match params_result {
2484 Ok(params) => self.parse_function_body(params, false),
2485 Err(err) => Err(err),
2486 };
2487 self.ctx = saved;
2488 self.top_level = saved_top;
2489 let (params, params_span, body, strict) = result?;
2490 Ok(Function {
2491 name,
2492 params,
2493 body,
2494 is_async,
2495 is_generator,
2496 strict,
2497 is_arrow: false,
2498 span: self.span_from(start),
2499 params_span,
2500 })
2501 }
2502
2503 fn parse_formal_parameters(&mut self) -> Result<Vec<Pattern>> {
2504 self.expect_punct(Punct::LParen)?;
2505 let mut params = Vec::new();
2506 loop {
2507 if self.at_punct(Punct::RParen) {
2508 break;
2509 }
2510 if self.at_punct(Punct::Ellipsis) {
2511 self.bump()?;
2512 if !self.at_formal_parameter() {
2515 return Err(self.error("missing formal parameter"));
2516 }
2517 let target = self.parse_binding_target()?;
2518 if matches!(target.unparen_kind(), PatternKind::Assign { .. }) {
2519 return Err(
2520 self.error_at("rest element cannot have a default value", target.span)
2521 );
2522 }
2523 params.push(Pattern::new(
2524 PatternKind::Rest(Box::new(target.clone())),
2525 target.span,
2526 ));
2527 if self.at_punct(Punct::Comma) {
2530 return Err(self.error("expecting ')'"));
2531 }
2532 break;
2533 }
2534 if !self.at_formal_parameter() {
2535 return Err(self.error("missing formal parameter"));
2536 }
2537 let param = self.parse_binding_element()?;
2538 self.check_parameter(¶m)?;
2539 params.push(param);
2540 if !self.eat_punct(Punct::Comma)? {
2541 break;
2542 }
2543 }
2544 self.expect_punct(Punct::RParen)?;
2545 Ok(params)
2546 }
2547
2548 fn check_parameter(&self, param: &Pattern) -> Result<()> {
2549 match ¶m.kind {
2550 PatternKind::Ident(ident) => self.check_binding_name(&ident.name, ident.span),
2551 PatternKind::Assign { target, .. } => self.check_parameter(target),
2552 _ => Ok(()),
2553 }
2554 }
2555
2556 fn parse_function_body(
2557 &mut self,
2558 params: Vec<Pattern>,
2559 is_method: bool,
2560 ) -> Result<(Vec<Pattern>, Span, FunctionBody, bool)> {
2561 let params_span = self.prev_end;
2562 let saved_strict = self.strict;
2567 if !self.at_punct(Punct::LBrace) {
2568 return Err(self.unexpected());
2569 }
2570 let saved_in_case = self.in_case_clause;
2573 self.in_case_clause = false;
2574 let param_names = simple_parameter_names(¶ms);
2575 let simple_params = params
2576 .iter()
2577 .all(|p| matches!(p.unparen_kind(), PatternKind::Ident(_)));
2578 let mut body = Vec::new();
2579 let mut prologue = true;
2580 let mut strict_seen = false;
2581 self.bump()?; let body_start = self.current.span;
2586 self.push_scope(Scope::function(param_names));
2587 while !self.at_punct(Punct::RBrace) {
2588 if self.current.is_eof() {
2589 return Err(self.unexpected());
2590 }
2591 let stmt = self.parse_statement_list_item()?;
2592 if prologue {
2593 match self.directive_value(&stmt) {
2594 Some(directive) if directive == "use strict" => {
2595 strict_seen = true;
2596 self.enter_strict()?;
2597 }
2598 Some(_) => {}
2599 None => prologue = false,
2600 }
2601 }
2602 body.push(stmt);
2603 }
2604 self.pop_scope();
2605 self.bump()?; let body_strict = self.strict;
2609 if strict_seen && !simple_params {
2610 return Err(self.error_at(
2611 "\"use strict\" not allowed in function with default or destructuring parameter",
2613 Span::new(params_span, params_span),
2614 ));
2615 }
2616 self.check_duplicate_parameters(
2627 ¶ms,
2628 body_strict || !simple_params || is_method,
2629 body_start,
2630 )?;
2631 let params_span_value = Span::new(params_span, params_span);
2632 self.strict = saved_strict;
2633 self.lexer.set_strict(saved_strict);
2634 self.in_case_clause = saved_in_case;
2635 Ok((
2636 params,
2637 params_span_value,
2638 FunctionBody::Block(body),
2639 body_strict,
2640 ))
2641 }
2642
2643 fn parse_class(&mut self, is_expression: bool) -> Result<Class> {
2646 let saved_strict = self.strict;
2654 let enter = self.enter_strict();
2655 let result = match enter {
2656 Ok(()) => self.parse_class_body(is_expression),
2657 Err(error) => Err(error),
2658 };
2659 self.strict = saved_strict;
2660 self.lexer.set_strict(saved_strict);
2661 result
2662 }
2663
2664 fn parse_class_body(&mut self, is_expression: bool) -> Result<Class> {
2665 let start = self.current.span.start;
2666 self.bump()?; let name = if matches!(self.current.kind, TokenKind::Ident(_)) {
2668 if is_expression {
2669 Some(self.expect_ident()?)
2670 } else {
2671 Some(self.expect_binding_ident()?)
2672 }
2673 } else {
2674 if !is_expression {
2675 return Err(self.error("class statement requires a name"));
2676 }
2677 None
2678 };
2679 let super_class = if self.eat_keyword(Keyword::Extends)? {
2680 Some(Box::new(self.parse_lhs_expression()?))
2681 } else {
2682 None
2683 };
2684 let has_super = super_class.is_some();
2685 self.private.push(PrivateEnv::default());
2686 self.expect_punct(Punct::LBrace)?;
2687 let mut elements = Vec::new();
2688 let mut seen_constructor = false;
2689 let result = (|| -> Result<()> {
2690 while !self.at_punct(Punct::RBrace) {
2691 if self.eat_punct(Punct::Semicolon)? {
2695 continue;
2696 }
2697 elements.push(self.parse_class_element(has_super, &mut seen_constructor)?);
2698 }
2699 Ok(())
2700 })();
2701 self.private.pop();
2702 result?;
2703 let body_end = self.current.span.start;
2706 self.bump()?; Ok(Class {
2708 name,
2709 super_class,
2710 elements,
2711 span: self.span_from(start),
2712 body_end,
2713 })
2714 }
2715
2716 fn parse_static_block(&mut self, start: Position) -> Result<ClassElement> {
2724 let saved = self.ctx;
2725 let saved_top = self.top_level;
2726 self.ctx = FnCtx {
2727 in_function: true,
2728 in_generator: false,
2729 in_async: false,
2730 in_method: true,
2732 in_derived_constructor: false,
2733 in_static_block: true,
2734 arguments_allowed: false,
2735 };
2736 self.top_level = false;
2737 let saved_strict = self.strict;
2743 let enter = self.enter_strict();
2744 let saved_loop = self.loop_depth;
2747 let saved_switch = self.switch_depth;
2748 let saved_labels = std::mem::take(&mut self.labels);
2749 self.loop_depth = 0;
2750 self.switch_depth = 0;
2751 let body_start = self.current.span.start;
2752 let body = match enter {
2753 Ok(()) => self.parse_block(),
2754 Err(error) => Err(error),
2755 };
2756 self.strict = saved_strict;
2757 self.lexer.set_strict(saved_strict);
2758 self.ctx = saved;
2759 self.top_level = saved_top;
2760 self.loop_depth = saved_loop;
2761 self.switch_depth = saved_switch;
2762 self.labels = saved_labels;
2763 let body = body?;
2764 Ok(ClassElement::StaticBlock {
2765 body,
2766 body_start,
2767 span: self.span_from(start),
2768 })
2769 }
2770
2771 fn parse_class_element(
2772 &mut self,
2773 has_super: bool,
2774 seen_constructor: &mut bool,
2775 ) -> Result<ClassElement> {
2776 let start = self.current.span.start;
2777 let mut is_static = false;
2778 if self.at_ident("static") {
2779 let peek = self.peek()?;
2780 let is_modifier = !matches!(
2781 peek.kind,
2782 TokenKind::Punct(Punct::LParen)
2783 | TokenKind::Punct(Punct::Eq)
2784 | TokenKind::Punct(Punct::Semicolon)
2785 | TokenKind::Punct(Punct::RBrace)
2786 );
2787 if is_modifier {
2788 self.bump()?; if self.at_punct(Punct::LBrace) {
2790 return self.parse_static_block(start);
2791 }
2792 is_static = true;
2793 }
2794 }
2795
2796 let mut is_async = false;
2798 let mut is_generator = false;
2799 let mut accessor: Option<MethodKind> = None;
2800 if self.at_ident("async") {
2801 let peek = self.peek()?;
2802 let is_modifier = !matches!(
2803 peek.kind,
2804 TokenKind::Punct(Punct::LParen)
2805 | TokenKind::Punct(Punct::Eq)
2806 | TokenKind::Punct(Punct::Semicolon)
2807 | TokenKind::Punct(Punct::RBrace)
2808 ) && !peek.newline_before;
2809 if is_modifier {
2810 self.bump()?;
2811 is_async = true;
2812 }
2813 }
2814 if self.at_punct(Punct::Star) {
2815 self.bump()?;
2816 is_generator = true;
2817 }
2818 if accessor.is_none() && (self.at_ident("get") || self.at_ident("set")) {
2819 let is_get = self.at_ident("get");
2820 let peek = self.peek()?;
2821 if is_property_key_start(&peek.kind) {
2822 self.bump()?;
2823 accessor = Some(if is_get {
2824 MethodKind::Get
2825 } else {
2826 MethodKind::Set
2827 });
2828 }
2829 }
2830 let key = self.parse_property_key()?;
2831
2832 if matches!(&key, PropName::Private(ident) if ident.name == "constructor") {
2836 return Err(self.error("invalid method name"));
2837 }
2838 if !is_static
2844 && (is_generator || is_async || accessor.is_some())
2845 && matches!(&key, PropName::Literal(PropKey::Str(name)) if name == "constructor")
2846 {
2847 return Err(self.error("invalid method name"));
2848 }
2849
2850 if let PropName::Private(ident) = &key {
2852 if let Some(env) = self.private.last_mut() {
2853 if !env.declare(&ident.name, accessor, is_static) {
2854 return Err(self.error_at(
2855 "private class field is already defined".to_string(),
2858 ident.span,
2859 ));
2860 }
2861 }
2862 }
2863
2864 if self.at_punct(Punct::LParen) {
2865 let kind = match accessor {
2866 Some(kind) => kind,
2867 None => {
2868 let is_constructor = !is_static
2869 && !is_generator
2870 && !is_async
2871 && matches!(&key, PropName::Literal(PropKey::Str(s)) if s == "constructor");
2872 if is_constructor {
2873 if *seen_constructor {
2874 return Err(self.error_at(
2875 "property constructor appears more than once",
2876 self.span_from(start),
2877 ));
2878 }
2879 *seen_constructor = true;
2880 MethodKind::Constructor
2881 } else {
2882 MethodKind::Method
2883 }
2884 }
2885 };
2886 if kind == MethodKind::Constructor && (is_generator || is_async) {
2887 return Err(self.error("a constructor may not be a generator or async"));
2888 }
2889 let saved = self.ctx;
2890 self.ctx = FnCtx {
2891 in_function: true,
2892 in_generator: is_generator,
2893 in_async: is_async,
2894 in_method: true,
2895 in_derived_constructor: kind == MethodKind::Constructor && has_super,
2896 in_static_block: false,
2897 arguments_allowed: true,
2898 };
2899 let saved_top = self.top_level;
2900 self.top_level = false;
2901 let result = (|| -> Result<Function> {
2902 let params = self.parse_formal_parameters()?;
2903 let (params, params_span, body, strict) = self.parse_function_body(params, true)?;
2904 Ok(Function {
2905 name: None,
2906 params,
2907 body,
2908 is_async,
2909 is_generator,
2910 strict,
2911 is_arrow: false,
2912 span: self.span_from(start),
2913 params_span,
2914 })
2915 })();
2916 self.ctx = saved;
2917 self.top_level = saved_top;
2918 let func = result?;
2919 if is_static {
2920 if let PropName::Literal(PropKey::Str(name)) = &key {
2921 if name == "prototype" {
2922 return Err(self.error_at("invalid method name", func.span));
2923 }
2924 }
2925 }
2926 if kind == MethodKind::Get && !func.params.is_empty() {
2927 return Err(self.error_at(
2928 "invalid number of arguments for getter or setter",
2929 func.span,
2930 ));
2931 }
2932 if kind == MethodKind::Set && func.params.len() != 1 {
2933 return Err(self.error_at(
2934 "invalid number of arguments for getter or setter",
2935 func.span,
2936 ));
2937 }
2938 return Ok(ClassElement::Method {
2939 key,
2940 is_static,
2941 kind,
2942 func: Box::new(func),
2943 span: self.span_from(start),
2944 });
2945 }
2946
2947 if accessor.is_some() {
2949 return Err(self.error("expecting '(' after an accessor name"));
2950 }
2951 if let PropName::Literal(PropKey::Str(name)) = &key {
2952 if name == "constructor" && !is_static {
2953 return Err(self.error("classes may not have a field named 'constructor'"));
2954 }
2955 if name == "prototype" && is_static {
2956 return Err(self.error("classes may not have a static property named 'prototype'"));
2957 }
2958 }
2959 let saved = self.ctx;
2963 let saved_top = self.top_level;
2964 self.ctx = FnCtx {
2965 in_function: true,
2966 in_generator: false,
2967 in_async: false,
2968 in_method: true,
2969 in_derived_constructor: false,
2970 in_static_block: false,
2971 arguments_allowed: false,
2972 };
2973 self.top_level = false;
2974 let value = self
2975 .eat_punct(Punct::Eq)?
2976 .then(|| self.parse_assignment(true));
2977 self.ctx = saved;
2978 self.top_level = saved_top;
2979 let value = match value {
2980 Some(value) => Some(Box::new(value?)),
2981 None => None,
2982 };
2983 self.semicolon()?;
2985 Ok(ClassElement::Field {
2986 key,
2987 is_static,
2988 value,
2989 span: self.span_from(start),
2990 })
2991 }
2992
2993 fn parse_import_decl(&mut self) -> Result<Stmt> {
2996 let start = self.current.span.start;
2997 self.bump()?; let mut specifiers = Vec::new();
2999 if let TokenKind::String(source) = self.current.kind.clone() {
3000 self.bump()?;
3001 let attributes = self.parse_import_attributes()?;
3002 self.semicolon()?;
3003 return Ok(Stmt::new(
3004 StmtKind::Import(Box::new(ImportDecl {
3005 specifiers,
3006 source,
3007 attributes,
3008 span: self.span_from(start),
3009 })),
3010 self.span_from(start),
3011 ));
3012 }
3013 if matches!(self.current.kind, TokenKind::Ident(_)) {
3015 let local = self.expect_ident()?;
3016 specifiers.push(ImportSpecifier::Default(local));
3017 if !self.eat_punct(Punct::Comma)? {
3018 return self.finish_import(start, specifiers);
3019 }
3020 }
3021 if self.at_punct(Punct::Star) {
3022 self.bump()?;
3023 if !self.eat_contextual("as")? {
3024 return Err(self.unexpected());
3025 }
3026 let local = self.expect_ident()?;
3027 specifiers.push(ImportSpecifier::Namespace(local));
3028 return self.finish_import(start, specifiers);
3029 }
3030 if self.at_punct(Punct::LBrace) {
3031 self.bump()?;
3032 while !self.at_punct(Punct::RBrace) {
3033 let imported = self.parse_module_name()?;
3034 let local = if self.eat_contextual("as")? {
3035 self.expect_ident()?
3036 } else {
3037 match &imported {
3038 ModuleName::Ident(id) => id.clone(),
3039 ModuleName::Str(_) => {
3040 return Err(self.error_at(
3041 "a string module name must be followed by 'as'",
3042 self.current.span,
3043 ));
3044 }
3045 }
3046 };
3047 specifiers.push(ImportSpecifier::Named { imported, local });
3048 if !self.eat_punct(Punct::Comma)? {
3049 break;
3050 }
3051 }
3052 self.expect_punct(Punct::RBrace)?;
3053 } else if !specifiers.is_empty() {
3054 return Err(self.unexpected());
3055 } else if self.at_punct(Punct::LBrace) {
3056 unreachable!("handled above");
3057 } else {
3058 return Err(self.unexpected());
3059 }
3060 self.finish_import(start, specifiers)
3061 }
3062
3063 fn finish_import(&mut self, start: Position, specifiers: Vec<ImportSpecifier>) -> Result<Stmt> {
3064 if !self.eat_contextual("from")? {
3065 return Err(self.unexpected());
3066 }
3067 let TokenKind::String(source) = self.current.kind.clone() else {
3068 return Err(self.error("string expected"));
3069 };
3070 self.bump()?;
3071 let attributes = self.parse_import_attributes()?;
3072 self.semicolon()?;
3073 let span = self.span_from(start);
3074 for specifier in &specifiers {
3075 let local = match specifier {
3076 ImportSpecifier::Default(id) => id,
3077 ImportSpecifier::Namespace(id) => id,
3078 ImportSpecifier::Named { local, .. } => local,
3079 };
3080 self.declare_lexical(&local.name)?;
3081 if let Some(scope) = self.scopes.last_mut()
3082 && !scope.import_names.iter().any(|n| n == &local.name)
3083 {
3084 scope.import_names.push(local.name.clone());
3085 }
3086 }
3087 Ok(Stmt::new(
3088 StmtKind::Import(Box::new(ImportDecl {
3089 specifiers,
3090 source,
3091 attributes,
3092 span,
3093 })),
3094 span,
3095 ))
3096 }
3097
3098 fn parse_import_attributes(&mut self) -> Result<Vec<ImportAttribute>> {
3099 let mut attributes = Vec::new();
3100 let has_with = self.at_keyword(Keyword::With) || self.at_ident("assert");
3101 if !has_with {
3102 return Ok(attributes);
3103 }
3104 let peek = self.peek()?;
3105 if !matches!(peek.kind, TokenKind::Punct(Punct::LBrace)) {
3106 return Ok(attributes);
3107 }
3108 self.bump()?; self.expect_punct(Punct::LBrace)?;
3110 while !self.at_punct(Punct::RBrace) {
3111 let attr_start = self.current.span.start;
3112 let key = match self.current.kind.clone() {
3113 TokenKind::Ident(name) => name,
3114 TokenKind::String(value) => value,
3115 _ => return Err(self.error("expecting an import attribute name")),
3116 };
3117 self.bump()?;
3118 self.expect_punct(Punct::Colon)?;
3119 let TokenKind::String(value) = self.current.kind.clone() else {
3120 return Err(self.error("expecting an import attribute value string"));
3121 };
3122 self.bump()?;
3123 attributes.push(ImportAttribute {
3124 key,
3125 value,
3126 span: self.span_from(attr_start),
3127 });
3128 if !self.eat_punct(Punct::Comma)? {
3129 break;
3130 }
3131 }
3132 self.expect_punct(Punct::RBrace)?;
3133 Ok(attributes)
3134 }
3135
3136 fn parse_module_name(&mut self) -> Result<ModuleName> {
3137 match self.current.kind.clone() {
3138 TokenKind::String(value) => {
3139 self.bump()?;
3140 Ok(ModuleName::Str(value))
3141 }
3142 TokenKind::Ident(_) => Ok(ModuleName::Ident(self.expect_ident()?)),
3143 TokenKind::Keyword(kw) => {
3144 let span = self.current.span;
3145 self.bump()?;
3146 Ok(ModuleName::Ident(Ident {
3147 name: kw.as_str().to_string(),
3148 span,
3149 }))
3150 }
3151 _ => Err(self.error("identifier or string expected")),
3154 }
3155 }
3156
3157 fn parse_export_decl(&mut self) -> Result<Stmt> {
3158 let start = self.current.span.start;
3159 self.bump()?; if self.at_punct(Punct::Star) {
3161 self.bump()?;
3162 let mut exported = None;
3163 if self.eat_contextual("as")? {
3164 exported = Some(self.parse_module_name()?);
3165 }
3166 if !self.eat_contextual("from")? {
3167 return Err(self.error("expecting 'from' after 'export *'"));
3168 }
3169 let TokenKind::String(source) = self.current.kind.clone() else {
3170 return Err(self.error("string expected"));
3171 };
3172 self.bump()?;
3173 let attributes = self.parse_import_attributes()?;
3174 self.semicolon()?;
3175 let span = self.span_from(start);
3176 return Ok(Stmt::new(
3177 StmtKind::Export(Box::new(ExportDecl {
3178 kind: ExportKind::All {
3179 source,
3180 exported,
3181 attributes,
3182 },
3183 span,
3184 })),
3185 span,
3186 ));
3187 }
3188 if self.eat_keyword(Keyword::Default)? {
3189 let value = if self.at_keyword(Keyword::Function) {
3190 let func = self.parse_function(FunctionForm::Expression, false, None)?;
3191 Expr::new(ExprKind::Function(Box::new(func)), self.span_from(start))
3192 } else if self.at_ident("async") {
3193 let peek = self.peek()?;
3194 if matches!(peek.kind, TokenKind::Keyword(Keyword::Function)) {
3195 self.bump()?;
3196 let func = self.parse_function(FunctionForm::Expression, true, Some(start))?;
3197 Expr::new(ExprKind::Function(Box::new(func)), self.span_from(start))
3198 } else {
3199 self.parse_assignment(true)?
3200 }
3201 } else if self.at_keyword(Keyword::Class) {
3202 let class = self.parse_class(true)?;
3203 Expr::new(ExprKind::Class(Box::new(class)), self.span_from(start))
3204 } else {
3205 let expr = self.parse_assignment(true)?;
3206 self.semicolon()?;
3207 expr
3208 };
3209 let span = self.span_from(start);
3210 return Ok(Stmt::new(
3211 StmtKind::Export(Box::new(ExportDecl {
3212 kind: ExportKind::Default(Box::new(value)),
3213 span,
3214 })),
3215 span,
3216 ));
3217 }
3218 if self.at_keyword(Keyword::Var)
3219 || self.at_keyword(Keyword::Const)
3220 || self.at_keyword(Keyword::Function)
3221 || self.at_keyword(Keyword::Class)
3222 || (self.at_ident("let") && self.let_starts_declaration()?)
3223 {
3224 let decl = self.parse_statement_list_item()?;
3225 let span = self.span_from(start);
3226 return Ok(Stmt::new(
3227 StmtKind::Export(Box::new(ExportDecl {
3228 kind: ExportKind::Declaration(Box::new(decl)),
3229 span,
3230 })),
3231 span,
3232 ));
3233 }
3234 if self.at_ident("async") {
3235 let peek = self.peek()?;
3236 if matches!(peek.kind, TokenKind::Keyword(Keyword::Function)) && !peek.newline_before {
3237 let decl = self.parse_statement_list_item()?;
3238 let span = self.span_from(start);
3239 return Ok(Stmt::new(
3240 StmtKind::Export(Box::new(ExportDecl {
3241 kind: ExportKind::Declaration(Box::new(decl)),
3242 span,
3243 })),
3244 span,
3245 ));
3246 }
3247 }
3248 if self.at_punct(Punct::LBrace) {
3249 self.bump()?;
3250 let mut specifiers = Vec::new();
3251 let mut candidates: Vec<(String, Span)> = Vec::new();
3252 let mut source = None;
3253 while !self.at_punct(Punct::RBrace) {
3254 let spec_start = self.current.span.start;
3255 let local = self.parse_module_name()?;
3256 let exported = if self.eat_contextual("as")? {
3257 self.parse_module_name()?
3258 } else {
3259 local.clone()
3260 };
3261 if let ModuleName::Ident(id) = &local {
3265 candidates.push((id.name.clone(), id.span));
3266 }
3267 specifiers.push(ExportSpecifier {
3268 local,
3269 exported,
3270 span: self.span_from(spec_start),
3271 });
3272 if !self.eat_punct(Punct::Comma)? {
3273 break;
3274 }
3275 }
3276 self.expect_punct(Punct::RBrace)?;
3277 let mut attributes = Vec::new();
3278 let has_from = self.eat_contextual("from")?;
3279 if !has_from {
3280 self.pending_exports.extend(candidates);
3284 }
3285 if has_from {
3286 let TokenKind::String(value) = self.current.kind.clone() else {
3287 return Err(self.error("string expected"));
3288 };
3289 self.bump()?;
3290 source = Some(value);
3291 attributes = self.parse_import_attributes()?;
3292 }
3293 self.semicolon()?;
3294 let span = self.span_from(start);
3295 return Ok(Stmt::new(
3296 StmtKind::Export(Box::new(ExportDecl {
3297 kind: ExportKind::Named {
3298 specifiers,
3299 source,
3300 attributes,
3301 },
3302 span,
3303 })),
3304 span,
3305 ));
3306 }
3307 Err(self.unexpected())
3308 }
3309
3310 fn expr_to_pattern(&mut self, expr: Expr, kind: TargetKind) -> Result<Pattern> {
3313 self.expr_to_pattern_inner(expr, kind, false)
3314 }
3315
3316 fn expr_to_pattern_inner(
3317 &mut self,
3318 expr: Expr,
3319 kind: TargetKind,
3320 nested: bool,
3321 ) -> Result<Pattern> {
3322 let span = expr.span;
3323 match expr.kind {
3324 ExprKind::Ident(ident) => {
3325 if kind == TargetKind::Binding {
3326 self.check_binding_name(&ident.name, ident.span)?;
3327 } else {
3328 self.check_identifier(&ident.name, ident.span)?;
3329 if self.strict && (ident.name == "eval" || ident.name == "arguments") {
3330 return Err(self.error_at(
3331 format!("invalid assignment to '{}' in strict mode", ident.name),
3332 ident.span,
3333 ));
3334 }
3335 }
3336 Ok(Pattern::new(PatternKind::Ident(ident), span))
3337 }
3338 ExprKind::Paren(inner) => self.expr_to_pattern_inner(*inner, kind, nested),
3339 ExprKind::Array { elements } => {
3340 let mut out = Vec::new();
3341 let mut rest = None;
3342 let count = elements.len();
3343 for (index, element) in elements.into_iter().enumerate() {
3344 match element {
3345 None => out.push(None),
3346 Some(ArrayElement::Expr(expr)) => {
3347 let pattern = self.expr_to_pattern_inner(*expr, kind, true)?;
3348 out.push(Some(PatternElement::Pattern(pattern)));
3349 }
3350 Some(ArrayElement::Spread(expr)) => {
3351 if index + 1 != count {
3352 return Err(
3353 self.error_at("rest element must be the last one", expr.span)
3354 );
3355 }
3356 rest = Some(Box::new(self.expr_to_rest(*expr, kind)?));
3357 }
3358 }
3359 }
3360 Ok(Pattern::new(
3361 PatternKind::Array {
3362 elements: out,
3363 rest,
3364 },
3365 span,
3366 ))
3367 }
3368 ExprKind::Object(properties) => {
3369 self.cover_inits
3370 .retain(|cover| !span_contains(span, *cover));
3371 let mut out = Vec::new();
3372 let mut rest = None;
3373 let count = properties.len();
3374 for (index, property) in properties.into_iter().enumerate() {
3375 match property {
3376 ObjectProperty::Spread(expr) => {
3377 if index + 1 != count {
3378 return Err(
3379 self.error_at("rest element must be the last one", expr.span)
3380 );
3381 }
3382 rest = Some(Box::new(self.expr_to_rest(*expr, kind)?));
3383 }
3384 ObjectProperty::Property {
3385 key,
3386 value,
3387 kind: _,
3388 shorthand,
3389 span,
3390 } => {
3391 let pattern = self.expr_to_pattern_inner(*value, kind, true)?;
3392 out.push(Some(PatternElement::Property {
3393 key,
3394 value: pattern,
3395 shorthand,
3396 span,
3397 }));
3398 }
3399 }
3400 }
3401 Ok(Pattern::new(
3402 PatternKind::Object {
3403 properties: out,
3404 rest,
3405 },
3406 span,
3407 ))
3408 }
3409 ExprKind::Assign { op, target, value } if op.is_simple() => {
3410 let target = match target.kind {
3412 PatternKind::Ident(ident) => {
3413 Pattern::new(PatternKind::Ident(ident), target.span)
3414 }
3415 other => {
3416 let expr = pattern_to_expr(Pattern::new(other, target.span), target.span);
3417 self.expr_to_pattern_inner(expr, kind, nested)?
3418 }
3419 };
3420 Ok(Pattern::new(
3421 PatternKind::Assign {
3422 target: Box::new(target),
3423 default: value,
3424 },
3425 span,
3426 ))
3427 }
3428 ExprKind::Member {
3429 object,
3430 property,
3431 optional,
3432 } => {
3433 if kind == TargetKind::Binding {
3434 return Err(self.error_at("invalid binding pattern", span));
3435 }
3436 if optional {
3437 return Err(self.error_at("invalid assignment target", span));
3438 }
3439 let op_pos = expr.op_pos;
3440 Ok(Pattern::new(
3441 PatternKind::Member(Box::new(MemberPattern {
3442 object,
3443 property,
3444 span,
3445 op_pos,
3446 })),
3447 span,
3448 ))
3449 }
3450 ExprKind::OptionalChain(_) => {
3451 Err(self.error_at("invalid assignment left-hand side", span))
3452 }
3453 other @ ExprKind::Call { .. } if !nested && kind == TargetKind::Assignment => Ok(
3458 Pattern::new(PatternKind::Invalid(Box::new(Expr::new(other, span))), span),
3459 ),
3460 _ if kind == TargetKind::Binding => Err(self.error_at("invalid binding pattern", span)),
3461 _ if nested => Err(self.error_at("invalid destructuring target", span)),
3466 _ => Err(self.error_at("invalid assignment left-hand side", span)),
3467 }
3468 }
3469
3470 fn expr_to_rest(&mut self, expr: Expr, kind: TargetKind) -> Result<RestElement> {
3471 let expr = match expr.kind {
3474 ExprKind::Spread(inner) => *inner,
3475 other => Expr::new(other, expr.span),
3476 };
3477 if kind == TargetKind::Binding {
3478 return Ok(RestElement::Pattern(
3479 self.expr_to_pattern_inner(expr, kind, true)?,
3480 ));
3481 }
3482 match &expr.kind {
3483 ExprKind::Member { optional, .. } => {
3484 if *optional {
3485 return Err(self.error_at("invalid assignment target", expr.span));
3486 }
3487 match self.expr_to_pattern_inner(expr, kind, true)?.kind {
3488 PatternKind::Member(member) => Ok(RestElement::Member(member)),
3489 _ => unreachable!("member expressions convert to member patterns"),
3490 }
3491 }
3492 _ => Ok(RestElement::Pattern(
3493 self.expr_to_pattern_inner(expr, kind, true)?,
3494 )),
3495 }
3496 }
3497
3498 fn parse_expression(&mut self, allow_in: bool) -> Result<Expr> {
3502 self.enter()?;
3503 let result = self.parse_expression_unguarded(allow_in);
3504 self.leave();
3505 result
3506 }
3507
3508 fn parse_expression_unguarded(&mut self, allow_in: bool) -> Result<Expr> {
3509 let saved_allow_in = self.allow_in;
3514 self.allow_in = allow_in;
3515 let result = self.parse_expression_in(allow_in);
3516 self.allow_in = saved_allow_in;
3517 result
3518 }
3519
3520 fn parse_expression_in(&mut self, allow_in: bool) -> Result<Expr> {
3521 let start = self.current.span.start;
3522 let first = self.parse_assignment(allow_in)?;
3523 if !self.at_punct(Punct::Comma) {
3524 return Ok(first);
3525 }
3526 let mut items = vec![first];
3527 while self.eat_punct(Punct::Comma)? {
3528 items.push(self.parse_assignment(allow_in)?);
3529 }
3530 Ok(Expr::new(ExprKind::Sequence(items), self.span_from(start)))
3531 }
3532
3533 fn parse_assignment(&mut self, allow_in: bool) -> Result<Expr> {
3534 let start = self.current.span.start;
3535
3536 if self.ctx.in_generator && self.at_ident("yield") {
3538 return self.parse_yield(allow_in);
3539 }
3540
3541 let lhs = match self.try_parse_arrow(allow_in)? {
3542 Some(arrow) => return Ok(arrow),
3543 None => self.parse_conditional(allow_in)?,
3544 };
3545
3546 if let Some(op) = self.current.kind.as_punct().and_then(AssignOp::from_punct) {
3547 let op_pos = self.current.span.start;
3548 let target = self.expr_to_pattern(lhs, TargetKind::Assignment)?;
3549 self.bump()?;
3550 let value = self.parse_assignment(allow_in)?;
3551 return Ok(Expr::at_operator(
3552 ExprKind::Assign {
3553 op,
3554 target: Box::new(target),
3555 value: Box::new(value),
3556 },
3557 self.span_from(start),
3558 op_pos,
3559 ));
3560 }
3561 let _ = start;
3562 Ok(lhs)
3563 }
3564
3565 fn parse_yield(&mut self, allow_in: bool) -> Result<Expr> {
3566 let start = self.current.span.start;
3567 self.bump()?; let delegate = if self.at_punct(Punct::Star) && !self.current.newline_before {
3569 self.bump()?;
3570 true
3571 } else {
3572 false
3573 };
3574 let argument = if delegate {
3575 Some(Box::new(self.parse_assignment(allow_in)?))
3576 } else if self.current.newline_before
3577 || self.at_punct(Punct::RParen)
3578 || self.at_punct(Punct::RBracket)
3579 || self.at_punct(Punct::RBrace)
3580 || self.at_punct(Punct::Comma)
3581 || self.at_punct(Punct::Semicolon)
3582 || self.at_punct(Punct::Colon)
3583 || self.current.is_eof()
3584 {
3585 None
3586 } else {
3587 Some(Box::new(self.parse_assignment(allow_in)?))
3588 };
3589 Ok(Expr::new(
3590 ExprKind::Yield { argument, delegate },
3591 self.span_from(start),
3592 ))
3593 }
3594
3595 fn try_parse_arrow(&mut self, allow_in: bool) -> Result<Option<Expr>> {
3596 let starts_paren = self.at_punct(Punct::LParen);
3597 let starts_ident = matches!(self.current.kind, TokenKind::Ident(_));
3598 if !starts_paren && !starts_ident {
3599 return Ok(None);
3600 }
3601 if starts_paren && !self.arrow_follows_paren()? {
3605 return Ok(None);
3606 }
3607 let snapshot = self.snapshot();
3608 let head = match self.parse_arrow_head() {
3609 Ok(head) => head,
3610 Err(_) => {
3611 self.restore(snapshot);
3612 return Ok(None);
3613 }
3614 };
3615 let Some(head) = head else {
3616 self.restore(snapshot);
3617 return Ok(None);
3618 };
3619 let body_start = if self.at_punct(Punct::LBrace) {
3626 self.peek()?.span
3627 } else {
3628 self.current.span
3629 };
3630 self.check_duplicate_parameters(&head.params, true, body_start)?;
3631 let saved_ctx = self.ctx;
3632 let saved_loop = self.loop_depth;
3633 let saved_switch = self.switch_depth;
3634 let saved_labels = std::mem::take(&mut self.labels);
3635 let saved_top = self.top_level;
3636 self.ctx = FnCtx {
3637 in_function: true,
3638 in_generator: false,
3639 in_async: head.is_async,
3640 in_method: saved_ctx.in_method,
3641 in_derived_constructor: saved_ctx.in_derived_constructor,
3642 in_static_block: false,
3646 arguments_allowed: saved_ctx.arguments_allowed,
3647 };
3648 self.loop_depth = 0;
3649 self.switch_depth = 0;
3650 self.top_level = false;
3651 let body_start = self.current.span.start;
3652 let (body, strict) = if self.at_punct(Punct::LBrace) {
3653 let (block, strict) = self.parse_arrow_block(&head.params)?;
3654 (block, (self.prev_end, strict))
3655 } else {
3656 let expr = self.parse_assignment(allow_in)?;
3657 let end = expr.span.end;
3658 let strict = self.strict;
3660 (FunctionBody::Expr(Box::new(expr)), (end, strict))
3661 };
3662 self.ctx = saved_ctx;
3663 self.loop_depth = saved_loop;
3664 self.switch_depth = saved_switch;
3665 self.labels = saved_labels;
3666 self.top_level = saved_top;
3667 let _ = body_start;
3668 let (body, (end, strict)) = (body, strict);
3669 let span = Span::new(head.span.start, end);
3670 Ok(Some(Expr::new(
3671 ExprKind::Arrow(Box::new(Function {
3672 name: None,
3673 params: head.params,
3674 body,
3675 is_async: head.is_async,
3676 is_generator: false,
3677 strict,
3678 is_arrow: true,
3679 span,
3680 params_span: head.params_span,
3681 })),
3682 span,
3683 )))
3684 }
3685
3686 fn parse_arrow_block(&mut self, params: &[Pattern]) -> Result<(FunctionBody, bool)> {
3688 let saved_strict = self.strict;
3691 self.expect_punct(Punct::LBrace)?;
3692 self.push_scope(Scope::function(simple_parameter_names(params)));
3693 let result = (|| -> Result<Vec<Stmt>> {
3694 let mut body = Vec::new();
3695 let mut prologue = true;
3696 while !self.at_punct(Punct::RBrace) {
3697 if self.current.is_eof() {
3698 return Err(self.unexpected());
3699 }
3700 let stmt = self.parse_statement_list_item()?;
3701 if prologue {
3702 match self.directive_value(&stmt) {
3703 Some(directive) if directive == "use strict" => self.enter_strict()?,
3704 Some(_) => {}
3705 None => prologue = false,
3706 }
3707 }
3708 body.push(stmt);
3709 }
3710 Ok(body)
3711 })();
3712 self.pop_scope();
3713 let body_strict = self.strict;
3714 self.strict = saved_strict;
3715 self.lexer.set_strict(saved_strict);
3716 let body = result?;
3717 self.bump()?;
3718 Ok((FunctionBody::Block(body), body_strict))
3719 }
3720
3721 fn arrow_follows_paren(&self) -> Result<bool> {
3727 let mut lexer = self.lexer.clone();
3728 let mut depth = 1usize;
3730 loop {
3731 let token = lexer.next_token()?;
3732 match token.kind {
3733 TokenKind::Eof => return Ok(false),
3734 TokenKind::Punct(Punct::LParen)
3735 | TokenKind::Punct(Punct::LBracket)
3736 | TokenKind::Punct(Punct::LBrace) => depth += 1,
3737 TokenKind::Punct(Punct::RParen)
3738 | TokenKind::Punct(Punct::RBracket)
3739 | TokenKind::Punct(Punct::RBrace) => {
3740 if depth == 0 {
3741 return Ok(false);
3743 }
3744 depth -= 1;
3745 if depth == 0 {
3746 let next = lexer.next_token()?;
3749 return Ok(matches!(next.kind, TokenKind::Punct(Punct::Arrow))
3750 && !next.newline_before);
3751 }
3752 }
3753 _ => {}
3754 }
3755 }
3756 }
3757
3758 fn parse_arrow_head(&mut self) -> Result<Option<ArrowHead>> {
3760 let start = self.current.span.start;
3761 let mut is_async = false;
3762 if self.at_ident("async") {
3763 let peek = self.peek()?;
3764 if peek.newline_before {
3765 return Ok(None);
3766 }
3767 let plausible =
3768 matches!(peek.kind, TokenKind::Punct(Punct::LParen)) || peek.kind.is_identifier();
3769 if !plausible {
3770 return Ok(None);
3771 }
3772 self.bump()?;
3773 is_async = true;
3774 }
3775 let params_start = self.current.span.start;
3776 let params = if self.at_punct(Punct::LParen) {
3777 self.parse_formal_parameters()?
3778 } else if matches!(self.current.kind, TokenKind::Ident(_)) {
3779 let ident = self.expect_ident()?;
3780 vec![Pattern::new(
3781 PatternKind::Ident(ident),
3782 self.span_from(params_start),
3783 )]
3784 } else {
3785 return Ok(None);
3786 };
3787 let params_span = self.span_from(params_start);
3788 if !self.at_punct(Punct::Arrow) || self.current.newline_before {
3789 return Ok(None);
3790 }
3791 self.bump()?; Ok(Some(ArrowHead {
3793 params,
3794 is_async,
3795 span: self.span_from(start),
3796 params_span,
3797 }))
3798 }
3799
3800 fn parse_conditional(&mut self, allow_in: bool) -> Result<Expr> {
3801 let start = self.current.span.start;
3802 let test = self.parse_binary(allow_in, 0)?;
3803 if !self.at_punct(Punct::Question) {
3804 return Ok(test);
3805 }
3806 self.bump()?;
3807 let consequent = self.parse_assignment(true)?;
3808 self.expect_punct(Punct::Colon)?;
3809 let alternate = self.parse_assignment(allow_in)?;
3810 Ok(Expr::new(
3811 ExprKind::Conditional {
3812 test: Box::new(test),
3813 cons: Box::new(consequent),
3814 alt: Box::new(alternate),
3815 },
3816 self.span_from(start),
3817 ))
3818 }
3819
3820 fn parse_binary(&mut self, allow_in: bool, min_prec: u8) -> Result<Expr> {
3821 let start = self.current.span.start;
3822 let mut lhs = self.parse_unary()?;
3823 while let Some((prec, op)) = binary_operator(&self.current.kind, allow_in) {
3824 if prec < min_prec {
3825 break;
3826 }
3827 let op_pos = self.current.span.start;
3828 self.bump()?;
3829 let next_min = if op.is_right_associative() {
3830 prec
3831 } else {
3832 prec + 1
3833 };
3834 let rhs = self.parse_binary(allow_in, next_min)?;
3835 lhs = build_binary(op, lhs, rhs, self.span_from(start), op_pos)?;
3836 }
3837 Ok(lhs)
3838 }
3839
3840 fn parse_unary(&mut self) -> Result<Expr> {
3843 let start = self.current.span.start;
3844 let unary = match &self.current.kind {
3846 TokenKind::Keyword(Keyword::Delete) => Some(UnaryOp::Delete),
3847 TokenKind::Keyword(Keyword::Void) => Some(UnaryOp::Void),
3848 TokenKind::Keyword(Keyword::Typeof) => Some(UnaryOp::Typeof),
3849 TokenKind::Punct(Punct::Plus) => Some(UnaryOp::Plus),
3850 TokenKind::Punct(Punct::Minus) => Some(UnaryOp::Minus),
3851 TokenKind::Punct(Punct::Bang) => Some(UnaryOp::Not),
3852 TokenKind::Punct(Punct::Tilde) => Some(UnaryOp::BitNot),
3853 _ => None,
3854 };
3855 if let Some(op) = unary {
3856 let op_pos = self.current.span.start;
3857 self.bump()?;
3858 let argument = self.parse_unary()?;
3859 if op == UnaryOp::Delete && self.strict {
3860 if let ExprKind::Ident(ident) = &argument.unparen().kind {
3861 return Err(self.error_at(
3862 "cannot delete a direct reference in strict mode",
3863 ident.span,
3864 ));
3865 }
3866 }
3867 if op == UnaryOp::Delete && deletes_a_private_member(&argument) {
3873 return Err(self.error("cannot delete a private class field"));
3877 }
3878 let expr = Expr::at_operator(
3879 ExprKind::Unary {
3880 op,
3881 argument: Box::new(argument),
3882 },
3883 self.span_from(start),
3884 op_pos,
3885 );
3886 if self.at_punct(Punct::StarStar) {
3887 return Err(self.error(
3888 "unparenthesized unary expression can't appear on the left-hand side of '**'",
3890 ));
3891 }
3892 return Ok(expr);
3893 }
3894 if self.at_punct(Punct::PlusPlus) || self.at_punct(Punct::MinusMinus) {
3896 let op_pos = self.current.span.start;
3897 let op = if self.at_punct(Punct::PlusPlus) {
3898 UpdateOp::Increment
3899 } else {
3900 UpdateOp::Decrement
3901 };
3902 self.bump()?;
3903 let argument = self.parse_unary()?;
3904 self.check_simple_target(&argument)?;
3905 return Ok(Expr::at_operator(
3906 ExprKind::Update {
3907 op,
3908 argument: Box::new(argument),
3909 prefix: true,
3910 },
3911 self.span_from(start),
3912 op_pos,
3913 ));
3914 }
3915 if self.at_ident("await") && self.ctx.in_async {
3922 self.bump()?;
3923 let argument = self.parse_unary()?;
3924 return Ok(Expr::new(
3925 ExprKind::Await(Box::new(argument)),
3926 self.span_from(start),
3927 ));
3928 }
3929 let expr = self.parse_lhs_expression()?;
3930 let result = if (self.at_punct(Punct::PlusPlus) || self.at_punct(Punct::MinusMinus))
3932 && !self.current.newline_before
3933 {
3934 let op_pos = self.current.span.start;
3935 let op = if self.at_punct(Punct::PlusPlus) {
3936 UpdateOp::Increment
3937 } else {
3938 UpdateOp::Decrement
3939 };
3940 self.check_simple_target(&expr)?;
3941 self.bump()?;
3942 Expr::at_operator(
3943 ExprKind::Update {
3944 op,
3945 argument: Box::new(expr),
3946 prefix: false,
3947 },
3948 self.span_from(start),
3949 op_pos,
3950 )
3951 } else {
3952 expr
3953 };
3954 Ok(result)
3955 }
3956
3957 fn check_simple_target(&self, expr: &Expr) -> Result<()> {
3962 match &expr.unparen().kind {
3963 ExprKind::Ident(_) => Ok(()),
3964 ExprKind::Member {
3965 optional: false, ..
3966 } => Ok(()),
3967 _ => Err(self.error_at("invalid increment/decrement operand", expr.span)),
3968 }
3969 }
3970
3971 fn parse_lhs_expression(&mut self) -> Result<Expr> {
3972 let start = self.current.span.start;
3973 let mut expr = if self.at_keyword(Keyword::New) {
3974 self.parse_new_expression()?
3975 } else {
3976 self.parse_primary()?
3977 };
3978 let mut saw_optional = false;
3979 loop {
3980 let op_pos = self.current.span.start;
3983 match self.current.kind.clone() {
3984 TokenKind::Punct(Punct::Dot) => {
3985 self.bump()?;
3986 let property = self.parse_member_property()?;
3987 expr = Expr::at_operator(
3988 ExprKind::Member {
3989 object: Box::new(expr),
3990 property,
3991 optional: false,
3992 },
3993 self.span_from(start),
3994 op_pos,
3995 );
3996 }
3997 TokenKind::Punct(Punct::QuestionDot) => {
3998 saw_optional = true;
3999 self.bump()?;
4000 if self.at_punct(Punct::LParen) {
4001 let arguments = self.parse_arguments()?;
4002 expr = Expr::at_operator(
4003 ExprKind::Call {
4004 callee: Box::new(expr),
4005 arguments,
4006 optional: true,
4007 },
4008 self.span_from(start),
4009 op_pos,
4010 );
4011 } else if self.at_punct(Punct::LBracket) {
4012 self.bump()?;
4013 let index = self.parse_expression(true)?;
4014 self.expect_punct(Punct::RBracket)?;
4015 expr = Expr::at_operator(
4016 ExprKind::Member {
4017 object: Box::new(expr),
4018 property: MemberProp::Computed(Box::new(index)),
4019 optional: true,
4020 },
4021 self.span_from(start),
4022 op_pos,
4023 );
4024 } else {
4025 let property = self.parse_member_property()?;
4026 expr = Expr::at_operator(
4027 ExprKind::Member {
4028 object: Box::new(expr),
4029 property,
4030 optional: true,
4031 },
4032 self.span_from(start),
4033 op_pos,
4034 );
4035 }
4036 }
4037 TokenKind::Punct(Punct::LBracket) => {
4038 self.bump()?;
4039 let index = self.parse_expression(true)?;
4040 self.expect_punct(Punct::RBracket)?;
4041 expr = Expr::at_operator(
4042 ExprKind::Member {
4043 object: Box::new(expr),
4044 property: MemberProp::Computed(Box::new(index)),
4045 optional: false,
4046 },
4047 self.span_from(start),
4048 op_pos,
4049 );
4050 }
4051 TokenKind::Punct(Punct::LParen) => {
4052 let arguments = self.parse_arguments()?;
4053 expr = Expr::at_operator(
4054 ExprKind::Call {
4055 callee: Box::new(expr),
4056 arguments,
4057 optional: false,
4058 },
4059 self.span_from(start),
4060 op_pos,
4061 );
4062 }
4063 TokenKind::Template(_) => {
4064 if saw_optional || matches!(expr.unparen().kind, ExprKind::OptionalChain(_)) {
4065 return Err(
4066 self.error("tagged template cannot be used in an optional chain")
4067 );
4068 }
4069 let quasi = self.parse_template()?;
4070 expr = Expr::new(
4071 ExprKind::TaggedTemplate {
4072 tag: Box::new(expr),
4073 quasi: Box::new(quasi),
4074 },
4075 self.span_from(start),
4076 );
4077 }
4078 _ => break,
4079 }
4080 }
4081 if saw_optional {
4082 expr = Expr::new(
4083 ExprKind::OptionalChain(Box::new(expr)),
4084 self.span_from(start),
4085 );
4086 }
4087 Ok(expr)
4088 }
4089
4090 fn parse_private_name(&mut self) -> Result<Ident> {
4097 let hash = self.current.span;
4098 self.bump()?;
4099 let ident = self.expect_ident()?;
4100 if ident.span.start.offset != hash.end.offset {
4101 return Err(self.error_at("invalid first character of private name", hash));
4102 }
4103 Ok(ident)
4104 }
4105
4106 fn parse_member_property(&mut self) -> Result<MemberProp> {
4107 if self.at_punct(Punct::Hash) {
4108 let ident = self.parse_private_name()?;
4109 if !self.private.iter().any(|env| env.contains(&ident.name)) {
4110 return Err(self.error_at(
4113 format!("undefined private field '#{}'", ident.name),
4114 ident.span,
4115 ));
4116 }
4117 return Ok(MemberProp::Private(ident));
4118 }
4119 match self.current.kind.clone() {
4120 TokenKind::Ident(name) => {
4121 let span = self.current.span;
4122 self.bump()?;
4123 Ok(MemberProp::Ident(Ident { name, span }))
4124 }
4125 TokenKind::Keyword(kw) => {
4126 let span = self.current.span;
4127 self.bump()?;
4128 Ok(MemberProp::Ident(Ident {
4129 name: kw.as_str().to_string(),
4130 span,
4131 }))
4132 }
4133 _ => Err(self.error("expecting field name")),
4137 }
4138 }
4139
4140 fn parse_new_expression(&mut self) -> Result<Expr> {
4141 let start = self.current.span.start;
4142 self.bump()?; if self.at_punct(Punct::Dot) {
4144 self.bump()?;
4145 if !self.at_ident("target") {
4146 return Err(self.error("expecting target"));
4147 }
4148 if !self.ctx.in_function {
4149 return Err(self.error("new.target only allowed within functions"));
4150 }
4151 self.bump()?;
4152 return Ok(Expr::new(ExprKind::NewTarget, self.span_from(start)));
4153 }
4154 let mut callee = if self.at_keyword(Keyword::New) {
4155 self.parse_new_expression()?
4156 } else {
4157 self.parse_primary()?
4158 };
4159 loop {
4161 let op_pos = self.current.span.start;
4162 match self.current.kind.clone() {
4163 TokenKind::Punct(Punct::Dot) => {
4164 self.bump()?;
4165 let property = self.parse_member_property()?;
4166 callee = Expr::at_operator(
4167 ExprKind::Member {
4168 object: Box::new(callee),
4169 property,
4170 optional: false,
4171 },
4172 self.span_from(start),
4173 op_pos,
4174 );
4175 }
4176 TokenKind::Punct(Punct::LBracket) => {
4177 self.bump()?;
4178 let index = self.parse_expression(true)?;
4179 self.expect_punct(Punct::RBracket)?;
4180 callee = Expr::at_operator(
4181 ExprKind::Member {
4182 object: Box::new(callee),
4183 property: MemberProp::Computed(Box::new(index)),
4184 optional: false,
4185 },
4186 self.span_from(start),
4187 op_pos,
4188 );
4189 }
4190 TokenKind::Punct(Punct::QuestionDot) => {
4191 return Err(self.error("new keyword cannot be used with an optional chain"));
4192 }
4193 _ => break,
4194 }
4195 }
4196 if matches!(callee.unparen().kind, ExprKind::OptionalChain(_)) {
4197 return Err(self.error_at("cannot use 'new' with an optional chain", callee.span));
4198 }
4199 if matches!(callee.unparen().kind, ExprKind::ImportCall(_)) {
4204 return Err(self.error_at("invalid use of 'import()'", callee.span));
4205 }
4206 let arguments = if self.at_punct(Punct::LParen) {
4207 let op_pos = self.current.span.start;
4209 let arguments = Some(self.parse_arguments()?);
4210 return Ok(Expr::at_operator(
4211 ExprKind::New {
4212 callee: Box::new(callee),
4213 arguments,
4214 },
4215 self.span_from(start),
4216 op_pos,
4217 ));
4218 } else {
4219 None
4220 };
4221 Ok(Expr::at_operator(
4225 ExprKind::New {
4226 callee: Box::new(callee),
4227 arguments,
4228 },
4229 self.span_from(start),
4230 self.current.span.start,
4231 ))
4232 }
4233
4234 fn parse_arguments(&mut self) -> Result<Vec<Expr>> {
4235 self.expect_punct(Punct::LParen)?;
4236 let mut arguments = Vec::new();
4237 while !self.at_punct(Punct::RParen) {
4238 if self.at_punct(Punct::Ellipsis) {
4239 let start = self.current.span.start;
4240 self.bump()?;
4241 let argument = self.parse_assignment(true)?;
4242 arguments.push(Expr::new(
4243 ExprKind::Spread(Box::new(argument)),
4244 self.span_from(start),
4245 ));
4246 } else {
4247 arguments.push(self.parse_assignment(true)?);
4248 }
4249 if !self.eat_punct(Punct::Comma)? {
4250 break;
4251 }
4252 }
4253 self.expect_punct(Punct::RParen)?;
4254 Ok(arguments)
4255 }
4256
4257 fn parse_primary(&mut self) -> Result<Expr> {
4264 let start = self.current.span.start;
4265 match self.current.kind.clone() {
4266 TokenKind::Number(NumberLiteral::Int(value)) => {
4267 self.bump()?;
4268 Ok(Expr::new(
4269 ExprKind::Number(value as f64),
4270 self.span_from(start),
4271 ))
4272 }
4273 TokenKind::Number(NumberLiteral::Float(value)) => {
4274 self.bump()?;
4275 Ok(Expr::new(ExprKind::Number(value), self.span_from(start)))
4276 }
4277 TokenKind::String(value) => {
4278 self.bump()?;
4279 Ok(Expr::new(ExprKind::String(value), self.span_from(start)))
4280 }
4281 TokenKind::Ident(name) if name == "async" && !self.current.escaped => {
4285 let peek = self.peek()?;
4286 if matches!(peek.kind, TokenKind::Keyword(Keyword::Function))
4287 && !peek.newline_before
4288 {
4289 self.bump()?; let func = self.parse_function(FunctionForm::Expression, true, Some(start))?;
4291 return Ok(Expr::new(
4292 ExprKind::Function(Box::new(func)),
4293 self.span_from(start),
4294 ));
4295 }
4296 let span = self.current.span;
4297 self.bump()?;
4298 Ok(Expr::new(ExprKind::Ident(Ident { name, span }), span))
4299 }
4300 TokenKind::Ident(name) => {
4301 let span = self.current.span;
4302 self.check_identifier(&name, span)?;
4303 self.check_arguments_reference(&name, span)?;
4304 self.bump()?;
4305 Ok(Expr::new(ExprKind::Ident(Ident { name, span }), span))
4306 }
4307 TokenKind::Keyword(Keyword::This) => {
4308 self.bump()?;
4309 Ok(Expr::new(ExprKind::This, self.span_from(start)))
4310 }
4311 TokenKind::Keyword(Keyword::Null) => {
4312 self.bump()?;
4313 Ok(Expr::new(ExprKind::Null, self.span_from(start)))
4314 }
4315 TokenKind::Keyword(Keyword::True) => {
4316 self.bump()?;
4317 Ok(Expr::new(ExprKind::Bool(true), self.span_from(start)))
4318 }
4319 TokenKind::Keyword(Keyword::False) => {
4320 self.bump()?;
4321 Ok(Expr::new(ExprKind::Bool(false), self.span_from(start)))
4322 }
4323 TokenKind::Punct(Punct::LParen) => {
4324 self.bump()?;
4325 let inner = self.parse_expression(true)?;
4326 self.expect_punct(Punct::RParen)?;
4327 Ok(Expr::new(
4328 ExprKind::Paren(Box::new(inner)),
4329 self.span_from(start),
4330 ))
4331 }
4332 TokenKind::Punct(Punct::Slash) | TokenKind::Punct(Punct::SlashEq) => {
4333 self.parse_regex_literal(start)
4334 }
4335 _ => self.parse_primary_complex(start),
4336 }
4337 }
4338
4339 #[inline(never)]
4342 fn parse_primary_complex(&mut self, start: Position) -> Result<Expr> {
4343 match self.current.kind.clone() {
4344 TokenKind::BigInt(literal) => {
4345 self.bump()?;
4346 Ok(Expr::new(
4347 ExprKind::BigInt {
4348 digits: literal.digits,
4349 radix: literal.radix,
4350 },
4351 self.span_from(start),
4352 ))
4353 }
4354 TokenKind::Template(_) => {
4355 let template = self.parse_template()?;
4356 Ok(Expr::new(
4357 ExprKind::Template(Box::new(template)),
4358 self.span_from(start),
4359 ))
4360 }
4361 TokenKind::Keyword(Keyword::Function) => {
4362 let func = self.parse_function(FunctionForm::Expression, false, None)?;
4363 Ok(Expr::new(
4364 ExprKind::Function(Box::new(func)),
4365 self.span_from(start),
4366 ))
4367 }
4368 TokenKind::Keyword(Keyword::Class) => {
4369 let class = self.parse_class(true)?;
4370 Ok(Expr::new(
4371 ExprKind::Class(Box::new(class)),
4372 self.span_from(start),
4373 ))
4374 }
4375 TokenKind::Keyword(Keyword::Import) => self.parse_import_expression(),
4376 TokenKind::Keyword(Keyword::Super) => self.parse_super(),
4377 TokenKind::Punct(Punct::LBracket) => self.parse_array_literal(),
4378 TokenKind::Punct(Punct::LBrace) => self.parse_object_literal(),
4379 TokenKind::Punct(Punct::Hash) if self.allow_in => self.parse_private_in(start),
4384 TokenKind::Punct(Punct::Hash) => {
4388 let hash = self.current.span;
4389 let name = match self.peek()?.kind.clone() {
4390 TokenKind::Ident(name) => format!("#{name}"),
4391 _ => "#".to_string(),
4392 };
4393 Err(SyntaxError::new(
4394 format!("unexpected token in expression: '{name}'"),
4395 hash,
4396 ))
4397 }
4398 _ => Err(self.unexpected()),
4399 }
4400 }
4401
4402 #[inline(never)]
4404 fn parse_super(&mut self) -> Result<Expr> {
4405 let start = self.current.span.start;
4406 self.bump()?;
4407 let after = self.current.span;
4413 if self.at_punct(Punct::LParen) {
4414 if !self.ctx.in_derived_constructor {
4415 return Err(self.error_at(
4416 "super() is only valid in a derived class constructor",
4417 after,
4418 ));
4419 }
4420 let arguments = self.parse_arguments()?;
4423 return Ok(Expr::at_operator(
4424 ExprKind::SuperCall(arguments),
4425 self.span_from(start),
4426 after.start,
4427 ));
4428 }
4429 if !self.ctx.in_method {
4430 let message = if self.at_punct(Punct::Dot) || self.at_punct(Punct::LBracket) {
4437 "'super' is only valid in a method"
4438 } else {
4439 "invalid use of 'super'"
4440 };
4441 return Err(self.error_at(message, after));
4442 }
4443 Ok(Expr::new(ExprKind::SuperProp, self.span_from(start)))
4444 }
4445
4446 #[inline(never)]
4448 fn parse_private_in(&mut self, start: Position) -> Result<Expr> {
4449 self.bump()?;
4450 let ident = self.expect_ident()?;
4451 if !self.private.iter().any(|env| env.contains(&ident.name)) {
4452 return Err(self.error_at(
4453 format!(
4454 "private field '#{}' must be declared in an enclosing class",
4455 ident.name
4456 ),
4457 ident.span,
4458 ));
4459 }
4460 if !self.at_keyword(Keyword::In) {
4461 return Err(self.error("expecting 'in' after a private name"));
4462 }
4463 self.bump()?;
4464 if self.at_punct(Punct::Hash) {
4468 let hash = self.current.span;
4469 let name = match self.peek()?.kind.clone() {
4470 TokenKind::Ident(name) => format!("#{name}"),
4471 _ => "#".to_string(),
4472 };
4473 return Err(SyntaxError::new(
4474 format!("unexpected token in expression: '{name}'"),
4475 hash,
4476 ));
4477 }
4478 let object = self.parse_unary()?;
4479 Ok(Expr::new(
4480 ExprKind::PrivateIn {
4481 name: ident,
4482 object: Box::new(object),
4483 },
4484 self.span_from(start),
4485 ))
4486 }
4487
4488 #[inline(never)]
4491 fn parse_regex_literal(&mut self, start: Position) -> Result<Expr> {
4492 let token = self.lexer.re_scan_regex(self.current.span.start)?;
4493 self.current = token;
4494 let TokenKind::RegExp { pattern, flags } = self.current.kind.clone() else {
4495 unreachable!("re_scan_regex returns a RegExp token")
4496 };
4497 self.bump()?;
4498 Ok(Expr::new(
4499 ExprKind::RegExp { pattern, flags },
4500 self.span_from(start),
4501 ))
4502 }
4503
4504 fn parse_import_expression(&mut self) -> Result<Expr> {
4505 let start = self.current.span.start;
4506 self.bump()?; if self.at_punct(Punct::Dot) {
4508 if !self.module {
4509 return Err(self.error_at(
4510 "import.meta only valid in module code",
4511 self.span_from(start),
4512 ));
4513 }
4514 self.bump()?;
4515 if !self.at_ident("meta") {
4516 return Err(self.error("expecting 'meta' after 'import.'"));
4517 }
4518 self.bump()?;
4519 return Ok(Expr::new(ExprKind::ImportMeta, self.span_from(start)));
4520 }
4521 if self.at_punct(Punct::LParen) {
4522 self.bump()?;
4523 let specifier = self.parse_assignment(true)?;
4524 if self.at_punct(Punct::Comma) {
4525 return Err(self.error("import() takes exactly one argument"));
4526 }
4527 self.expect_punct(Punct::RParen)?;
4528 return Ok(Expr::new(
4529 ExprKind::ImportCall(Box::new(specifier)),
4530 self.span_from(start),
4531 ));
4532 }
4533 Err(self.unexpected())
4534 }
4535
4536 fn parse_array_literal(&mut self) -> Result<Expr> {
4537 let start = self.current.span.start;
4538 self.expect_punct(Punct::LBracket)?;
4539 let mut elements = Vec::new();
4540 while !self.at_punct(Punct::RBracket) {
4541 if self.at_punct(Punct::Comma) {
4542 self.bump()?;
4543 elements.push(None);
4544 continue;
4545 }
4546 if self.at_punct(Punct::Ellipsis) {
4547 let spread_start = self.current.span.start;
4548 self.bump()?;
4549 let argument = self.parse_assignment(true)?;
4550 elements.push(Some(ArrayElement::Spread(Box::new(Expr::new(
4551 ExprKind::Spread(Box::new(argument)),
4552 self.span_from(spread_start),
4553 )))));
4554 } else {
4555 let expr = self.parse_assignment(true)?;
4556 elements.push(Some(ArrayElement::Expr(Box::new(expr))));
4557 }
4558 if !self.eat_punct(Punct::Comma)? {
4559 break;
4560 }
4561 }
4562 self.expect_punct(Punct::RBracket)?;
4563 Ok(Expr::new(
4564 ExprKind::Array { elements },
4565 self.span_from(start),
4566 ))
4567 }
4568
4569 fn parse_object_literal(&mut self) -> Result<Expr> {
4570 let start = self.current.span.start;
4571 self.expect_punct(Punct::LBrace)?;
4572 let mut properties: Vec<ObjectProperty> = Vec::new();
4573 let mut proto_count = 0;
4574 while !self.at_punct(Punct::RBrace) {
4575 let property_start = self.current.span.start;
4576 if self.at_punct(Punct::Ellipsis) {
4577 self.bump()?;
4578 let argument = self.parse_assignment(true)?;
4579 properties.push(ObjectProperty::Spread(Box::new(argument)));
4580 } else {
4581 let mut is_async = false;
4582 let mut is_generator = false;
4583 let mut accessor: Option<MethodKind> = None;
4584 if self.at_ident("async") {
4585 let peek = self.peek()?;
4586 let is_modifier = !matches!(
4587 peek.kind,
4588 TokenKind::Punct(Punct::LParen)
4589 | TokenKind::Punct(Punct::Colon)
4590 | TokenKind::Punct(Punct::Comma)
4591 | TokenKind::Punct(Punct::RBrace)
4592 | TokenKind::Punct(Punct::Eq)
4593 ) && !peek.newline_before;
4594 if is_modifier {
4595 self.bump()?;
4596 is_async = true;
4597 }
4598 }
4599 if self.at_punct(Punct::Star) {
4600 self.bump()?;
4601 is_generator = true;
4602 }
4603 if accessor.is_none() && (self.at_ident("get") || self.at_ident("set")) {
4604 let is_get = self.at_ident("get");
4605 let peek = self.peek()?;
4606 if is_property_key_start(&peek.kind) {
4607 self.bump()?;
4608 accessor = Some(if is_get {
4609 MethodKind::Get
4610 } else {
4611 MethodKind::Set
4612 });
4613 }
4614 }
4615 let key = self.parse_property_key()?;
4616 let is_computed = matches!(key, PropName::Computed(_));
4617 if self.at_punct(Punct::LParen) {
4618 let saved = self.ctx;
4619 self.ctx = FnCtx {
4620 in_function: true,
4621 in_generator: is_generator,
4622 in_async: is_async,
4623 in_method: true,
4624 in_derived_constructor: false,
4625 in_static_block: false,
4626 arguments_allowed: true,
4627 };
4628 let saved_top = self.top_level;
4629 self.top_level = false;
4630 let func_result = (|| -> Result<Function> {
4631 let params = self.parse_formal_parameters()?;
4632 let (params, params_span, body, strict) =
4633 self.parse_function_body(params, true)?;
4634 Ok(Function {
4635 name: None,
4636 params,
4637 body,
4638 is_async,
4639 is_generator,
4640 strict,
4641 is_arrow: false,
4642 span: self.span_from(property_start),
4643 params_span,
4644 })
4645 })();
4646 self.ctx = saved;
4647 self.top_level = saved_top;
4648 let func = func_result?;
4649 let kind = match accessor {
4650 Some(kind) => {
4651 if is_generator || is_async {
4652 return Err(self.error_at(
4653 "accessors may not be generators or async",
4654 func.span,
4655 ));
4656 }
4657 if kind == MethodKind::Get && !func.params.is_empty() {
4658 return Err(self.error_at(
4659 "invalid number of arguments for getter or setter",
4660 func.span,
4661 ));
4662 }
4663 if kind == MethodKind::Set && func.params.len() != 1 {
4664 return Err(self.error_at(
4665 "invalid number of arguments for getter or setter",
4666 func.span,
4667 ));
4668 }
4669 match kind {
4670 MethodKind::Get => PropertyKind::Get,
4671 MethodKind::Set => PropertyKind::Set,
4672 MethodKind::Method | MethodKind::Constructor => {
4673 PropertyKind::Method
4674 }
4675 }
4676 }
4677 None => PropertyKind::Method,
4678 };
4679 let span = self.span_from(property_start);
4680 properties.push(ObjectProperty::Property {
4681 key,
4682 value: Box::new(Expr::new(ExprKind::Function(Box::new(func)), span)),
4683 kind,
4684 shorthand: false,
4685 span,
4686 });
4687 } else if self.eat_punct(Punct::Colon)? {
4688 let value = self.parse_assignment(true)?;
4689 if !is_computed {
4690 if let Some(PropKeyRef::Str("__proto__")) = key.static_name() {
4691 proto_count += 1;
4692 if proto_count > 1 {
4693 return Err(self.error_at(
4694 "duplicate __proto__ property name",
4695 self.span_from(property_start),
4696 ));
4697 }
4698 }
4699 }
4700 properties.push(ObjectProperty::Property {
4701 key,
4702 value: Box::new(value),
4703 kind: PropertyKind::Value,
4704 shorthand: false,
4705 span: self.span_from(property_start),
4706 });
4707 } else {
4708 let PropName::Literal(PropKey::Str(name)) = &key else {
4711 return Err(self.error("expecting ':' after a property name"));
4712 };
4713 let ident_span = self.span_from(property_start);
4714 let ident = Ident {
4715 name: name.clone(),
4716 span: ident_span,
4717 };
4718 self.check_identifier(&ident.name, ident.span)?;
4719 let mut value = Expr::new(ExprKind::Ident(ident.clone()), ident_span);
4720 if self.at_punct(Punct::Eq) {
4721 self.cover_inits.push(ident_span);
4724 self.bump()?;
4725 let default = self.parse_assignment(true)?;
4726 let target = Pattern::new(PatternKind::Ident(ident), ident_span);
4727 value = Expr::new(
4728 ExprKind::Assign {
4729 op: AssignOp::Assign,
4730 target: Box::new(target),
4731 value: Box::new(default),
4732 },
4733 ident_span,
4734 );
4735 }
4736 properties.push(ObjectProperty::Property {
4737 key,
4738 value: Box::new(value),
4739 kind: PropertyKind::Value,
4740 shorthand: true,
4741 span: ident_span,
4742 });
4743 }
4744 }
4745 if !self.eat_punct(Punct::Comma)? {
4746 break;
4747 }
4748 }
4749 self.expect_punct(Punct::RBrace)?;
4750 Ok(Expr::new(
4751 ExprKind::Object(properties),
4752 self.span_from(start),
4753 ))
4754 }
4755
4756 fn parse_template(&mut self) -> Result<TemplateLiteral> {
4757 let mut quasis = Vec::new();
4758 let mut expressions = Vec::new();
4759 loop {
4760 let (cooked, raw, kind) = match self.current.kind.clone() {
4761 TokenKind::Template(chunk) => (chunk.cooked, chunk.raw, chunk.kind),
4762 _ => return Err(self.error("expecting a template literal")),
4763 };
4764 let tail = matches!(kind, TemplateKind::NoSubstitution | TemplateKind::Tail);
4765 quasis.push(TemplateChunk { cooked, raw, tail });
4766 if tail {
4767 self.bump()?;
4768 break;
4769 }
4770 self.bump()?; let expr = self.parse_expression(true)?;
4772 expressions.push(expr);
4773 if !self.at_punct(Punct::RBrace) {
4774 return Err(self.error("expecting '}' in a template substitution"));
4775 }
4776 let brace = self.current.span.start;
4777 let token = self.lexer.re_scan_template_continue(brace)?;
4778 self.current = token;
4779 }
4780 Ok(TemplateLiteral {
4781 quasis,
4782 expressions,
4783 })
4784 }
4785}
4786
4787#[derive(Debug, Clone, Copy, PartialEq, Eq)]
4789enum FunctionForm {
4790 Declaration,
4791 Expression,
4792}
4793
4794fn is_plain_identifier(param: &Pattern) -> bool {
4802 matches!(param.unparen_kind(), PatternKind::Ident(_))
4803}
4804
4805fn parameter_bindings(param: &Pattern) -> Vec<(String, Span, bool)> {
4811 fn walk(pattern: &Pattern, in_pattern: bool, out: &mut Vec<(String, Span, bool)>) {
4812 match &pattern.kind {
4813 PatternKind::Ident(ident) => out.push((ident.name.clone(), ident.span, in_pattern)),
4814 PatternKind::Assign { target, default } => {
4815 walk(target, in_pattern, out);
4816 let _ = default;
4818 }
4819 PatternKind::Rest(target) => walk(target, !is_plain_identifier(target), out),
4820 PatternKind::Array { .. } | PatternKind::Object { .. } => {
4821 let mut names = Vec::new();
4822 pattern.bound_names(&mut names);
4823 for name in names {
4824 out.push((name.name, name.span, true));
4825 }
4826 }
4827 _ => {}
4828 }
4829 }
4830 let mut out = Vec::new();
4831 let in_pattern = !is_plain_identifier(param);
4832 walk(param, in_pattern, &mut out);
4833 if out.is_empty() {
4836 let mut names = Vec::new();
4837 param.bound_names(&mut names);
4838 out.extend(names.into_iter().map(|name| (name.name, name.span, false)));
4839 }
4840 out
4841}
4842
4843fn pattern_has_default(pattern: &Pattern) -> bool {
4849 let element = |element: &Option<PatternElement>| {
4850 element.as_ref().is_some_and(|element| match element {
4851 PatternElement::Pattern(inner) => pattern_has_default(inner),
4852 PatternElement::Property { value, .. } => pattern_has_default(value),
4853 })
4854 };
4855 let rest = |rest: &Option<Box<RestElement>>| {
4856 rest.as_ref().is_some_and(|rest| match rest.as_ref() {
4857 RestElement::Pattern(inner) => pattern_has_default(inner),
4858 RestElement::Member(_) => false,
4859 })
4860 };
4861 match &pattern.kind {
4862 PatternKind::Assign { .. } => true,
4863 PatternKind::Array {
4864 elements,
4865 rest: tail,
4866 } => elements.iter().any(element) || rest(tail),
4867 PatternKind::Object {
4868 properties,
4869 rest: tail,
4870 } => properties.iter().any(element) || rest(tail),
4871 PatternKind::Rest(target) => pattern_has_default(target),
4872 _ => false,
4873 }
4874}
4875
4876fn simple_parameter_names(params: &[Pattern]) -> Vec<String> {
4877 params
4878 .iter()
4879 .filter_map(|param| match ¶m.kind {
4880 PatternKind::Ident(id) => Some(id.name.clone()),
4881 _ => None,
4882 })
4883 .collect()
4884}
4885
4886fn collect_module_binding(stmt: &Stmt, out: &mut Vec<String>) {
4889 match &stmt.kind {
4890 StmtKind::VarDecl(decl) => {
4891 if decl.kind.is_using() {
4897 return;
4898 }
4899 for declarator in &decl.declarators {
4900 let mut names = Vec::new();
4901 declarator.target.bound_names(&mut names);
4902 out.extend(names.into_iter().map(|n| n.name));
4903 }
4904 }
4905 StmtKind::FuncDecl(func) => {
4906 if let Some(name) = &func.name {
4907 out.push(name.name.clone());
4908 }
4909 }
4910 StmtKind::ClassDecl(class) => {
4911 if let Some(name) = &class.name {
4912 out.push(name.name.clone());
4913 }
4914 }
4915 StmtKind::Import(decl) => {
4916 for specifier in &decl.specifiers {
4917 match specifier {
4918 ImportSpecifier::Default(id) => out.push(id.name.clone()),
4919 ImportSpecifier::Namespace(id) => out.push(id.name.clone()),
4920 ImportSpecifier::Named { local, .. } => out.push(local.name.clone()),
4921 }
4922 }
4923 }
4924 StmtKind::Export(decl) => match &decl.kind {
4925 ExportKind::Declaration(inner) => collect_module_binding(inner, out),
4926 ExportKind::Default(expr) => match &expr.unparen().kind {
4927 ExprKind::Function(func) => {
4928 if let Some(name) = &func.name {
4929 out.push(name.name.clone());
4930 }
4931 }
4932 ExprKind::Class(class) => {
4933 if let Some(name) = &class.name {
4934 out.push(name.name.clone());
4935 }
4936 }
4937 _ => {}
4938 },
4939 _ => {}
4940 },
4941 _ => {}
4942 }
4943}
4944
4945fn span_contains(outer: Span, inner: Span) -> bool {
4947 inner.start.offset >= outer.start.offset && inner.end.offset <= outer.end.offset
4948}
4949
4950fn is_property_key_start(kind: &TokenKind) -> bool {
4951 matches!(
4952 kind,
4953 TokenKind::Ident(_)
4954 | TokenKind::Keyword(_)
4955 | TokenKind::String(_)
4956 | TokenKind::Number(_)
4957 | TokenKind::Punct(Punct::LBracket)
4958 | TokenKind::Punct(Punct::Hash)
4959 )
4960}
4961
4962#[derive(Debug, Clone, Copy)]
4964enum BinOp {
4965 Binary(BinaryOp),
4966 Logical(LogicalOp),
4967}
4968
4969impl BinOp {
4970 fn is_right_associative(self) -> bool {
4971 matches!(self, BinOp::Binary(BinaryOp::Pow))
4972 }
4973}
4974
4975fn binary_operator(kind: &TokenKind, allow_in: bool) -> Option<(u8, BinOp)> {
4976 use BinaryOp as B;
4977 use LogicalOp as L;
4978 let result = match kind {
4979 TokenKind::Punct(Punct::QuestionQuestion) => (1, BinOp::Logical(L::Coalesce)),
4980 TokenKind::Punct(Punct::PipePipe) => (2, BinOp::Logical(L::Or)),
4981 TokenKind::Punct(Punct::AmpAmp) => (3, BinOp::Logical(L::And)),
4982 TokenKind::Punct(Punct::Pipe) => (4, BinOp::Binary(B::BitOr)),
4983 TokenKind::Punct(Punct::Caret) => (5, BinOp::Binary(B::BitXor)),
4984 TokenKind::Punct(Punct::Amp) => (6, BinOp::Binary(B::BitAnd)),
4985 TokenKind::Punct(Punct::EqEq) => (7, BinOp::Binary(B::Eq)),
4986 TokenKind::Punct(Punct::NotEq) => (7, BinOp::Binary(B::NotEq)),
4987 TokenKind::Punct(Punct::EqEqEq) => (7, BinOp::Binary(B::StrictEq)),
4988 TokenKind::Punct(Punct::NotEqEq) => (7, BinOp::Binary(B::StrictNotEq)),
4989 TokenKind::Punct(Punct::Lt) => (8, BinOp::Binary(B::Lt)),
4990 TokenKind::Punct(Punct::LtEq) => (8, BinOp::Binary(B::LtEq)),
4991 TokenKind::Punct(Punct::Gt) => (8, BinOp::Binary(B::Gt)),
4992 TokenKind::Punct(Punct::GtEq) => (8, BinOp::Binary(B::GtEq)),
4993 TokenKind::Keyword(Keyword::Instanceof) => (8, BinOp::Binary(B::Instanceof)),
4994 TokenKind::Keyword(Keyword::In) if allow_in => (8, BinOp::Binary(B::In)),
4995 TokenKind::Punct(Punct::Shl) => (9, BinOp::Binary(B::Shl)),
4996 TokenKind::Punct(Punct::Shr) => (9, BinOp::Binary(B::Shr)),
4997 TokenKind::Punct(Punct::UShr) => (9, BinOp::Binary(B::UShr)),
4998 TokenKind::Punct(Punct::Plus) => (10, BinOp::Binary(B::Add)),
4999 TokenKind::Punct(Punct::Minus) => (10, BinOp::Binary(B::Sub)),
5000 TokenKind::Punct(Punct::Star) => (11, BinOp::Binary(B::Mul)),
5001 TokenKind::Punct(Punct::Slash) => (11, BinOp::Binary(B::Div)),
5002 TokenKind::Punct(Punct::Percent) => (11, BinOp::Binary(B::Mod)),
5003 TokenKind::Punct(Punct::StarStar) => (12, BinOp::Binary(B::Pow)),
5004 _ => return None,
5005 };
5006 Some(result)
5007}
5008
5009fn build_binary(op: BinOp, left: Expr, right: Expr, span: Span, op_pos: Position) -> Result<Expr> {
5010 match op {
5011 BinOp::Binary(op) => Ok(Expr::at_operator(
5012 ExprKind::Binary {
5013 op,
5014 left: Box::new(left),
5015 right: Box::new(right),
5016 },
5017 span,
5018 op_pos,
5019 )),
5020 BinOp::Logical(op) => {
5021 let mixes = |expr: &Expr, op: LogicalOp| {
5025 matches!(&expr.kind, ExprKind::Logical { op: inner, .. }
5026 if (op == LogicalOp::Coalesce) != (*inner == LogicalOp::Coalesce))
5027 };
5028 if mixes(&left, op) || mixes(&right, op) {
5029 return Err(SyntaxError::new(
5030 "cannot mix ?? with && or ||",
5033 span,
5034 ));
5035 }
5036 Ok(Expr::at_operator(
5037 ExprKind::Logical {
5038 op,
5039 left: Box::new(left),
5040 right: Box::new(right),
5041 },
5042 span,
5043 op_pos,
5044 ))
5045 }
5046 }
5047}
5048
5049fn pattern_to_expr(pattern: Pattern, span: Span) -> Expr {
5052 match pattern.kind {
5053 PatternKind::Ident(ident) => Expr::new(ExprKind::Ident(ident), span),
5054 PatternKind::Assign { target, default } => Expr::new(
5055 ExprKind::Assign {
5056 op: AssignOp::Assign,
5057 target,
5058 value: default,
5059 },
5060 span,
5061 ),
5062 PatternKind::Member(member) => {
5066 let MemberPattern {
5067 object,
5068 property,
5069 span,
5070 op_pos,
5071 } = *member;
5072 Expr {
5073 kind: ExprKind::Member {
5074 object,
5075 property,
5076 optional: false,
5077 },
5078 span,
5079 op_pos,
5080 }
5081 }
5082 PatternKind::Object { properties, rest } => {
5083 let mut out = Vec::new();
5084 for element in properties {
5085 match element {
5086 Some(PatternElement::Property {
5087 key,
5088 value,
5089 shorthand,
5090 span: _,
5091 }) => {
5092 let span = value.span;
5093 out.push(ObjectProperty::Property {
5094 key,
5095 value: Box::new(pattern_to_expr(value, span)),
5096 kind: PropertyKind::Value,
5097 shorthand,
5098 span,
5099 });
5100 }
5101 None | Some(PatternElement::Pattern(_)) => {}
5104 }
5105 }
5106 if let Some(rest) = rest
5107 && let RestElement::Pattern(pattern) = *rest
5108 {
5109 let span = pattern.span;
5110 out.push(ObjectProperty::Spread(Box::new(pattern_to_expr(
5111 pattern, span,
5112 ))));
5113 }
5114 Expr::new(ExprKind::Object(out), span)
5115 }
5116 PatternKind::Array { elements, rest } => {
5117 let mut out = Vec::new();
5118 for element in elements {
5119 match element {
5120 Some(PatternElement::Pattern(pattern)) => {
5121 let span = pattern.span;
5122 out.push(Some(ArrayElement::Expr(Box::new(pattern_to_expr(
5123 pattern, span,
5124 )))));
5125 }
5126 Some(PatternElement::Property { .. }) | None => out.push(None),
5127 }
5128 }
5129 if let Some(rest) = rest {
5130 let RestElement::Pattern(pattern) = *rest else {
5131 return Expr::new(ExprKind::Null, span);
5132 };
5133 let span = pattern.span;
5134 out.push(Some(ArrayElement::Spread(Box::new(pattern_to_expr(
5135 pattern, span,
5136 )))));
5137 }
5138 Expr::new(ExprKind::Array { elements: out }, span)
5139 }
5140 _ => Expr::new(ExprKind::Null, span),
5141 }
5142}
5143
5144impl Pattern {
5145 fn unparen_kind(&self) -> &PatternKind {
5148 &self.kind
5149 }
5150}
5151
5152fn deletes_a_private_member(expr: &Expr) -> bool {
5163 match &expr.unparen().kind {
5164 ExprKind::Member { property, .. } => matches!(property, MemberProp::Private(_)),
5165 ExprKind::Call { callee, .. } => deletes_a_private_member(callee),
5166 _ => false,
5167 }
5168}