1use crate::ast::*;
38use crate::error::{Result, SyntaxError};
39use crate::lexer::Lexer;
40use crate::token::{Keyword, NumberLiteral, Position, Punct, Span, TemplateKind, Token, TokenKind};
41use crate::wtf8::Wtf8;
42
43struct Snapshot<'a> {
45 lexer: Lexer<'a>,
46 current: Token,
47 prev_end: Position,
48 strict: bool,
49 allow_in: bool,
50 ctx: FnCtx,
51 loop_depth: u32,
52 switch_depth: u32,
53 labels: Vec<Label>,
54 private: Vec<PrivateEnv>,
55 top_level: bool,
56 cover_inits: Vec<Span>,
57 spread_trailing_comma: Vec<Span>,
66 pending_exports: Vec<(String, Span)>,
67 current_legacy_octal: bool,
68 scopes: Vec<Scope>,
69}
70
71#[derive(Debug, Clone, Copy)]
73struct FnCtx {
74 in_function: bool,
75 in_generator: bool,
76 in_async: bool,
77 in_method: bool,
79 in_derived_constructor: bool,
81 in_static_block: bool,
89 arguments_allowed: bool,
93}
94
95impl Default for FnCtx {
96 fn default() -> FnCtx {
97 FnCtx {
98 in_function: false,
99 in_generator: false,
100 in_async: false,
101 in_method: false,
102 in_derived_constructor: false,
103 in_static_block: false,
104 arguments_allowed: true,
107 }
108 }
109}
110
111#[derive(Debug, Clone, Copy, PartialEq, Eq)]
112enum LabelKind {
113 Iteration,
115 Other,
117}
118
119#[derive(Debug, Clone)]
120struct Label {
121 name: String,
122 kind: LabelKind,
123}
124
125#[derive(Debug, Clone, Default)]
127struct PrivateEnv {
128 names: Vec<PrivateName>,
129 pending: Vec<(String, Span)>,
137}
138
139#[derive(Debug, Clone)]
140struct PrivateName {
141 name: String,
142 has_get: bool,
143 has_set: bool,
144 is_accessor: bool,
150 accessor_is_static: bool,
156}
157
158impl PrivateEnv {
159 fn declare(&mut self, name: &str, accessor: Option<MethodKind>, is_static: bool) -> bool {
167 if let Some(existing) = self.names.iter_mut().find(|n| n.name == name) {
168 return match accessor {
169 Some(MethodKind::Get)
170 if existing.is_accessor
171 && !existing.has_get
172 && existing.accessor_is_static == is_static =>
173 {
174 existing.has_get = true;
175 true
176 }
177 Some(MethodKind::Set)
178 if existing.is_accessor
179 && !existing.has_set
180 && existing.accessor_is_static == is_static =>
181 {
182 existing.has_set = true;
183 true
184 }
185 _ => false,
186 };
187 }
188 let mut entry = PrivateName {
189 name: name.to_string(),
190 has_get: false,
191 has_set: false,
192 is_accessor: accessor.is_some(),
193 accessor_is_static: is_static,
194 };
195 match accessor {
196 Some(MethodKind::Get) => entry.has_get = true,
197 Some(MethodKind::Set) => entry.has_set = true,
198 _ => {}
199 }
200 self.names.push(entry);
201 true
202 }
203
204 fn contains(&self, name: &str) -> bool {
205 self.names.iter().any(|n| n.name == name)
206 }
207
208 fn from_names(names: &[String]) -> PrivateEnv {
217 PrivateEnv {
218 names: names
219 .iter()
220 .map(|name| PrivateName {
221 name: name.strip_prefix('#').unwrap_or(name).to_string(),
222 has_get: true,
223 has_set: true,
224 is_accessor: true,
225 accessor_is_static: false,
226 })
227 .collect(),
228 pending: Vec::new(),
229 }
230 }
231}
232
233#[derive(Debug, Clone, Copy, PartialEq, Eq)]
247enum Redefinition {
248 Lexical,
249 Global,
250 Variable,
251 Parameter,
252}
253
254impl Redefinition {
255 fn message(self) -> &'static str {
256 match self {
257 Redefinition::Lexical => "invalid redefinition of lexical identifier",
258 Redefinition::Global => "invalid redefinition of global identifier",
259 Redefinition::Variable => "invalid redefinition of a variable",
260 Redefinition::Parameter => "invalid redefinition of parameter name",
261 }
262 }
263}
264
265#[derive(Debug, Clone)]
266struct Scope {
267 is_var_scope: bool,
269 var_names: Vec<String>,
271 var_names_here: Vec<String>,
279 lex_names: Vec<String>,
281 fn_names: Vec<String>,
288 params: Vec<String>,
290 catch_names: Vec<String>,
298 plain_fn_names: Vec<String>,
307 import_names: Vec<String>,
314}
315
316impl Scope {
317 fn block() -> Scope {
318 Scope {
319 is_var_scope: false,
320 var_names: Vec::new(),
321 var_names_here: Vec::new(),
322 lex_names: Vec::new(),
323 fn_names: Vec::new(),
324 params: Vec::new(),
325 catch_names: Vec::new(),
326 plain_fn_names: Vec::new(),
327 import_names: Vec::new(),
328 }
329 }
330
331 fn function(params: Vec<String>) -> Scope {
332 Scope {
333 is_var_scope: true,
334 var_names: Vec::new(),
335 var_names_here: Vec::new(),
336 lex_names: Vec::new(),
337 fn_names: Vec::new(),
338 params,
339 catch_names: Vec::new(),
340 plain_fn_names: Vec::new(),
341 import_names: Vec::new(),
342 }
343 }
344}
345
346#[derive(Debug, Clone, Copy, PartialEq, Eq)]
348enum TargetKind {
349 Binding,
351 Assignment,
353}
354
355struct ArrowHead {
357 params: Vec<Pattern>,
358 is_async: bool,
359 span: Span,
360 params_span: Span,
361}
362
363pub const DEFAULT_MAX_DEPTH: u32 = if cfg!(debug_assertions) { 120 } else { 600 };
377
378pub struct Parser<'a> {
380 lexer: Lexer<'a>,
381 current: Token,
382 prev_end: Position,
383 strict: bool,
384 module: bool,
385 allow_in: bool,
386 ctx: FnCtx,
387 loop_depth: u32,
388 switch_depth: u32,
389 labels: Vec<Label>,
390 private: Vec<PrivateEnv>,
391 top_level: bool,
392 current_legacy_octal: bool,
395 in_case_clause: bool,
401 depth: u32,
404 max_depth: u32,
405
406 cover_inits: Vec<Span>,
410 spread_trailing_comma: Vec<Span>,
412 pending_exports: Vec<(String, Span)>,
415 in_formal_parameters: bool,
425 arrow_head_committed: bool,
433 scopes: Vec<Scope>,
435}
436
437pub fn parse_script(src: &str) -> Result<Program> {
439 Parser::new(src, false)?.parse_program()
440}
441
442pub fn parse_module(src: &str) -> Result<Program> {
444 Parser::new(src, true)?.parse_program()
445}
446
447pub fn parse_suspensible_script(src: &str) -> Result<Program> {
456 Parser::new_suspensible(src)?.parse_program()
457}
458
459pub fn parse_script_strict(src: &str) -> Result<Program> {
467 let mut parser = Parser::new(src, false)?;
468 parser.enter_strict()?;
469 parser.parse_program()
470}
471
472pub fn parse_eval_script(src: &str, strict: bool) -> Result<Program> {
479 parse_eval_script_in(src, strict, EvalContext::default())
480}
481
482#[derive(Debug, Clone, Default)]
484pub struct EvalContext {
485 pub in_method: bool,
488 pub in_derived_constructor: bool,
490 pub private_names: Vec<String>,
500 pub arguments_allowed: bool,
506 pub new_target_allowed: bool,
512}
513
514pub fn parse_eval_script_in(src: &str, strict: bool, context: EvalContext) -> Result<Program> {
520 let mut parser = Parser::new(src, false)?;
521 parser.ctx.in_function = context.new_target_allowed;
525 parser.ctx.in_method = context.in_method;
526 parser.ctx.in_derived_constructor = context.in_derived_constructor;
527 parser.ctx.arguments_allowed = context.arguments_allowed;
528 if !context.private_names.is_empty() {
532 parser
533 .private
534 .push(PrivateEnv::from_names(&context.private_names));
535 }
536 if strict {
537 parser.enter_strict()?;
538 }
539 parser.parse_program()
540}
541
542pub fn parse_suspensible_global_eval(src: &str, strict: bool) -> Result<Program> {
550 let mut parser = Parser::new_suspensible(src)?;
551 if strict {
552 parser.enter_strict()?;
553 }
554 parser.parse_program()
555}
556
557pub fn parse_expression(src: &str) -> Result<Expr> {
560 let mut parser = Parser::new(src, false)?;
561 let expr = parser.parse_expression(true)?;
562 if !parser.current.is_eof() {
563 return Err(parser.unexpected());
564 }
565 Ok(expr)
566}
567
568impl<'a> Parser<'a> {
569 pub fn new(src: &'a str, module: bool) -> Result<Parser<'a>> {
576 Parser::with_modes(src, module, false)
577 }
578
579 pub fn new_suspensible(src: &'a str) -> Result<Parser<'a>> {
586 Parser::with_modes(src, false, true)
587 }
588
589 fn with_modes(src: &'a str, module: bool, async_body: bool) -> Result<Parser<'a>> {
590 let mut lexer = Lexer::new(src);
591 lexer.set_strict(module);
592 let current = lexer.next_token()?;
593 let current_legacy_octal = lexer.had_legacy_octal();
594 if module && current_legacy_octal {
595 return Err(SyntaxError::new(
596 "octal literals and octal escape sequences are not allowed in strict mode",
597 current.span,
598 ));
599 }
600 Ok(Parser {
601 lexer,
602 current,
603 prev_end: Position::START,
604 strict: module,
605 module,
606 allow_in: true,
607 ctx: FnCtx {
608 in_async: module || async_body,
609 ..FnCtx::default()
610 },
611 loop_depth: 0,
612 switch_depth: 0,
613 labels: Vec::new(),
614 private: Vec::new(),
615 top_level: true,
616 current_legacy_octal,
617 in_case_clause: false,
618 depth: 0,
619 max_depth: DEFAULT_MAX_DEPTH,
620
621 cover_inits: Vec::new(),
622 spread_trailing_comma: Vec::new(),
623 pending_exports: Vec::new(),
624 in_formal_parameters: false,
625 arrow_head_committed: false,
626 scopes: vec![Scope::function(Vec::new())],
627 })
628 }
629
630 pub fn set_max_depth(&mut self, depth: u32) {
632 self.max_depth = depth;
633 }
634
635 fn enter(&mut self) -> Result<()> {
637 self.depth += 1;
638 if self.depth > self.max_depth {
639 return Err(SyntaxError::new("stack overflow", self.current.span));
640 }
641 Ok(())
642 }
643
644 fn leave(&mut self) {
645 self.depth -= 1;
646 }
647
648 pub fn parse_program(&mut self) -> Result<Program> {
650 let start = self.current.span.start;
651 let mut body = Vec::new();
652 let mut prologue = true;
653 while !self.current.is_eof() {
654 let stmt = self.parse_statement_list_item()?;
655 if prologue {
656 match self.directive_value(&stmt) {
657 Some(directive) if directive == "use strict" => self.enter_strict()?,
658 Some(_) => {}
659 None => prologue = false,
660 }
661 }
662 body.push(stmt);
663 }
664 if self.module {
665 self.check_module_exports(&body)?;
666 }
667 Ok(Program {
668 kind: if self.module {
669 ProgramKind::Module
670 } else {
671 ProgramKind::Script
672 },
673 body,
674 span: Span::new(start, self.prev_end),
675 strict: self.strict,
676 })
677 }
678
679 fn check_module_exports(&mut self, body: &[Stmt]) -> Result<()> {
682 if self.pending_exports.is_empty() {
683 return Ok(());
684 }
685 let mut declared: Vec<String> = Vec::new();
686 for stmt in body {
687 collect_module_binding(stmt, &mut declared);
688 }
689 let pending = std::mem::take(&mut self.pending_exports);
690 for (name, span) in pending {
691 if !declared.contains(&name) {
692 return Err(self
695 .error_at(format!("exported variable '{name}' does not exist"), span)
696 .positionless());
697 }
698 }
699 Ok(())
700 }
701
702 fn push_scope(&mut self, scope: Scope) {
705 self.scopes.push(scope);
706 }
707
708 fn pop_scope(&mut self) {
709 self.scopes.pop();
710 }
711
712 fn declare_lexical(&mut self, name: &str) -> Result<()> {
719 let Some(scope) = self.scopes.last() else {
720 return Ok(());
721 };
722 let reason = if scope.lex_names.iter().any(|n| n == name)
725 || scope.catch_names.iter().any(|n| n == name)
726 {
727 Some(Redefinition::Lexical)
728 } else if scope.params.iter().any(|n| n == name) {
729 Some(Redefinition::Parameter)
730 } else if scope.fn_names.iter().any(|n| n == name)
731 || scope.var_names.iter().any(|n| n == name)
732 {
733 Some(if self.at_top_level_scope() {
738 Redefinition::Global
739 } else {
740 Redefinition::Variable
741 })
742 } else {
743 None
744 };
745 if let Some(reason) = reason {
746 return Err(self.duplicate_declaration(reason));
747 }
748 if let Some(scope) = self.scopes.last_mut() {
749 scope.lex_names.push(name.to_string());
750 }
751 Ok(())
752 }
753
754 fn declare_var(&mut self, name: &str) -> Result<()> {
757 for scope in self.scopes.iter().rev() {
758 if scope.lex_names.iter().any(|n| n == name) {
759 return Err(self.duplicate_declaration(Redefinition::Lexical));
760 }
761 if scope.is_var_scope {
762 break;
763 }
764 }
765 let Some(index) = self.scopes.iter().rposition(|s| s.is_var_scope) else {
766 return Ok(());
767 };
768 for scope in &mut self.scopes[index..] {
771 if !scope.var_names.iter().any(|n| n == name) {
772 scope.var_names.push(name.to_string());
773 }
774 }
775 if let Some(scope) = self.scopes.last_mut()
776 && !scope.var_names_here.iter().any(|n| n == name)
777 {
778 scope.var_names_here.push(name.to_string());
779 }
780 Ok(())
781 }
782
783 fn check_duplicate_parameters(
804 &self,
805 params: &[Pattern],
806 plain_is_illegal: bool,
807 deferred_at: Span,
808 ) -> Result<()> {
809 let has_default = params.iter().any(pattern_has_default);
810 let mut seen: Vec<String> = Vec::new();
811 let mut deferred = false;
812 for param in params {
813 for (name, span, in_pattern) in parameter_bindings(param) {
814 if seen.iter().any(|seen| seen == &name) {
815 if has_default || in_pattern {
816 return Err(self.error_at(
817 "duplicate parameter names not allowed in this context".to_string(),
818 span,
819 ));
820 }
821 deferred = true;
822 }
823 seen.push(name);
824 }
825 }
826 if deferred && plain_is_illegal {
827 return Err(self.error_at(
828 "duplicate argument names not allowed in this context".to_string(),
829 deferred_at,
830 ));
831 }
832 Ok(())
833 }
834
835 fn declare_function(&mut self, name: &str) -> Result<()> {
851 if !self.scopes.last().is_none_or(|scope| scope.is_var_scope) {
852 return Ok(());
853 }
854 if !self.at_top_level_scope()
860 && self
861 .scopes
862 .last()
863 .is_some_and(|scope| scope.lex_names.iter().any(|n| n == name))
864 {
865 return Err(self.duplicate_declaration(Redefinition::Lexical));
866 }
867 if let Some(scope) = self.scopes.last_mut() {
868 if !scope.var_names.iter().any(|n| n == name) {
869 scope.var_names.push(name.to_string());
870 }
871 if !scope.fn_names.iter().any(|n| n == name) {
872 scope.fn_names.push(name.to_string());
873 }
874 }
875 Ok(())
876 }
877
878 fn declare_block_function(&mut self, name: &str, is_plain: bool) -> Result<()> {
887 if self.module
895 && self.at_top_level_scope()
896 && let Some(scope) = self.scopes.last()
897 {
898 let mut taken = scope.var_names_here.iter().any(|existing| existing == name);
904 if scope.is_var_scope {
905 let module_bindings = scope
906 .lex_names
907 .iter()
908 .filter(|existing| !scope.import_names.contains(existing))
909 .chain(&scope.fn_names);
910 taken |= module_bindings.into_iter().any(|existing| existing == name);
911 }
912 if taken {
913 return Err(self.error_at(
914 "invalid redefinition of global identifier in module code",
915 self.current.span,
916 ));
917 }
918 }
919 if self.scopes.last().is_none_or(|scope| scope.is_var_scope) {
920 return Ok(());
921 }
922 let Some(scope) = self.scopes.last() else {
923 return Ok(());
924 };
925 if scope.lex_names.iter().any(|n| n == name) || scope.catch_names.iter().any(|n| n == name)
926 {
927 let from_plain_function = scope.plain_fn_names.iter().any(|n| n == name);
931 if !(from_plain_function && is_plain && !self.strict) {
932 return Err(self.duplicate_declaration(Redefinition::Lexical));
933 }
934 } else if scope.var_names.iter().any(|n| n == name) {
935 let reason = if self.at_top_level_scope() {
939 Redefinition::Global
940 } else {
941 Redefinition::Variable
942 };
943 return Err(self.duplicate_declaration(reason));
944 }
945 if let Some(scope) = self.scopes.last_mut() {
946 if !scope.lex_names.iter().any(|n| n == name) {
947 scope.lex_names.push(name.to_string());
948 }
949 if !scope.fn_names.iter().any(|n| n == name) {
950 scope.fn_names.push(name.to_string());
951 }
952 if is_plain && !scope.plain_fn_names.iter().any(|n| n == name) {
953 scope.plain_fn_names.push(name.to_string());
954 }
955 }
956 Ok(())
957 }
958
959 fn duplicate_declaration(&self, reason: Redefinition) -> SyntaxError {
971 self.error_at(reason.message(), self.current.span)
972 }
973
974 fn at_top_level_scope(&self) -> bool {
980 self.scopes.iter().rposition(|scope| scope.is_var_scope) == Some(0)
981 }
982
983 fn declare_pattern(&mut self, pattern: &Pattern, is_var: bool) -> Result<()> {
985 let mut names = Vec::new();
986 pattern.bound_names(&mut names);
987 for name in names {
988 if is_var {
989 self.declare_var(&name.name)?;
990 } else {
991 self.declare_lexical(&name.name)?;
992 }
993 }
994 Ok(())
995 }
996
997 fn snapshot(&self) -> Snapshot<'a> {
1000 Snapshot {
1001 lexer: self.lexer.clone(),
1002 current: self.current.clone(),
1003 prev_end: self.prev_end,
1004 strict: self.strict,
1005 allow_in: self.allow_in,
1006 ctx: self.ctx,
1007 loop_depth: self.loop_depth,
1008 switch_depth: self.switch_depth,
1009 labels: self.labels.clone(),
1010 private: self.private.clone(),
1011 top_level: self.top_level,
1012 cover_inits: self.cover_inits.clone(),
1013 spread_trailing_comma: self.spread_trailing_comma.clone(),
1014 pending_exports: self.pending_exports.clone(),
1015 current_legacy_octal: self.current_legacy_octal,
1016 scopes: self.scopes.clone(),
1017 }
1018 }
1019
1020 fn restore(&mut self, snap: Snapshot<'a>) {
1021 self.lexer = snap.lexer;
1022 self.current = snap.current;
1023 self.prev_end = snap.prev_end;
1024 self.strict = snap.strict;
1025 self.allow_in = snap.allow_in;
1026 self.ctx = snap.ctx;
1027 self.loop_depth = snap.loop_depth;
1028 self.switch_depth = snap.switch_depth;
1029 self.labels = snap.labels;
1030 self.private = snap.private;
1031 self.top_level = snap.top_level;
1032 self.cover_inits = snap.cover_inits;
1033 self.spread_trailing_comma = snap.spread_trailing_comma;
1034 self.pending_exports = snap.pending_exports;
1035 self.current_legacy_octal = snap.current_legacy_octal;
1036 self.scopes = snap.scopes;
1037 }
1038
1039 fn bump(&mut self) -> Result<()> {
1040 self.prev_end = self.current.span.end;
1041 self.current = self.lexer.next_token()?;
1042 self.current_legacy_octal = self.lexer.had_legacy_octal();
1043 if self.strict && self.current_legacy_octal {
1044 return Err(SyntaxError::new(
1045 "octal literals and octal escape sequences are not allowed in strict mode",
1046 self.current.span,
1047 ));
1048 }
1049 Ok(())
1050 }
1051
1052 fn peek(&self) -> Result<Token> {
1053 let mut lexer = self.lexer.clone();
1054 lexer.next_token()
1055 }
1056
1057 fn enter_strict(&mut self) -> Result<()> {
1058 self.strict = true;
1059 self.lexer.set_strict(true);
1060 if self.current_legacy_octal {
1063 return Err(SyntaxError::new(
1064 "octal literals and octal escape sequences are not allowed in strict mode",
1065 self.current.span,
1066 ));
1067 }
1068 Ok(())
1069 }
1070
1071 fn at_punct(&self, p: Punct) -> bool {
1072 matches!(&self.current.kind, TokenKind::Punct(q) if *q == p)
1073 }
1074
1075 fn at_keyword(&self, k: Keyword) -> bool {
1076 matches!(&self.current.kind, TokenKind::Keyword(q) if *q == k)
1077 }
1078
1079 fn at_contextual(&self, name: &str) -> bool {
1080 self.at_ident(name)
1081 }
1082
1083 fn at_ident(&self, name: &str) -> bool {
1090 !self.current.escaped && matches!(&self.current.kind, TokenKind::Ident(n) if n == name)
1091 }
1092
1093 fn eat_punct(&mut self, p: Punct) -> Result<bool> {
1094 if self.at_punct(p) {
1095 self.bump()?;
1096 return Ok(true);
1097 }
1098 Ok(false)
1099 }
1100
1101 fn expect_punct(&mut self, p: Punct) -> Result<()> {
1102 if self.eat_punct(p)? {
1103 Ok(())
1104 } else {
1105 Err(self.error(format!("expecting '{}'", p.as_str())))
1110 }
1111 }
1112
1113 fn eat_keyword(&mut self, k: Keyword) -> Result<bool> {
1114 if self.at_keyword(k) {
1115 self.bump()?;
1116 return Ok(true);
1117 }
1118 Ok(false)
1119 }
1120
1121 fn eat_contextual(&mut self, name: &str) -> Result<bool> {
1122 if self.at_ident(name) {
1123 self.bump()?;
1124 return Ok(true);
1125 }
1126 Ok(false)
1127 }
1128
1129 fn unexpected(&self) -> SyntaxError {
1136 let source = self.lexer.source();
1137 let start = self.current.span.start.offset as usize;
1138 let end = self.current.span.end.offset as usize;
1139 let text = source.get(start..end).unwrap_or("");
1140 SyntaxError::new(
1141 format!("unexpected token in expression: '{text}'"),
1142 self.current.span,
1143 )
1144 }
1145
1146 fn error(&self, message: impl Into<String>) -> SyntaxError {
1147 SyntaxError::new(message, self.current.span)
1148 }
1149
1150 fn error_at(&self, message: impl Into<String>, span: Span) -> SyntaxError {
1151 SyntaxError::new(message, span)
1152 }
1153
1154 fn span_from(&self, start: Position) -> Span {
1155 Span::new(start, self.prev_end)
1156 }
1157
1158 fn expect_binding_ident(&mut self) -> Result<Ident> {
1161 let ident = self.expect_ident()?;
1162 self.check_binding_name(&ident.name, ident.span)?;
1163 Ok(ident)
1164 }
1165
1166 fn expect_ident(&mut self) -> Result<Ident> {
1168 match self.current.kind.clone() {
1169 TokenKind::Ident(name) => {
1170 if name == "await" && self.await_is_reserved() {
1173 return Err(self.error("variable name expected"));
1174 }
1175 let span = self.current.span;
1176 self.check_identifier(&name, span)?;
1177 self.bump()?;
1178 Ok(Ident { name, span })
1179 }
1180 _ => Err(self.error("variable name expected")),
1183 }
1184 }
1185
1186 fn at_formal_parameter(&self) -> bool {
1193 if self.at_punct(Punct::LBracket) || self.at_punct(Punct::LBrace) {
1194 return true;
1195 }
1196 match &self.current.kind {
1197 TokenKind::Ident(name) => !(name == "await" && self.await_is_reserved()),
1198 _ => false,
1199 }
1200 }
1201
1202 fn await_is_reserved(&self) -> bool {
1212 self.ctx.in_async || self.module || self.ctx.in_static_block
1215 }
1216
1217 fn check_identifier(&self, name: &str, span: Span) -> Result<()> {
1219 if Keyword::lookup(name).is_some() {
1220 return Err(self.error_at(format!("unexpected keyword '{name}'"), span));
1221 }
1222 if self.strict && Keyword::is_strict_reserved(name) {
1223 return Err(self.error_at(
1224 format!("invalid use of strict mode reserved word '{name}'"),
1225 span,
1226 ));
1227 }
1228 if self.ctx.in_generator && name == "yield" {
1229 return Err(self.error_at(
1230 "invalid use of 'yield' identifier in a generator function",
1231 span,
1232 ));
1233 }
1234 if name == "await" && self.await_is_reserved() {
1235 return Err(self.error_at("unexpected 'await' keyword", span));
1240 }
1241 Ok(())
1242 }
1243
1244 fn check_arguments_reference(&self, name: &str, span: Span) -> Result<()> {
1251 if name == "arguments" && !self.ctx.arguments_allowed {
1252 return Err(self.error_at(
1253 "'arguments' identifier is not allowed in class field initializer",
1254 span,
1255 ));
1256 }
1257 Ok(())
1258 }
1259
1260 fn check_binding_name(&self, name: &str, span: Span) -> Result<()> {
1263 self.check_identifier(name, span)?;
1264 if self.strict && (name == "eval" || name == "arguments") {
1265 let message = if self.in_formal_parameters {
1270 "invalid argument name in strict code"
1271 } else {
1272 "invalid variable name in strict mode"
1273 };
1274 return Err(self.error_at(message, span));
1275 }
1276 if self.strict && name == "let" {
1277 return Err(self.error_at(
1278 "invalid use of 'let' as a variable name in strict mode",
1279 span,
1280 ));
1281 }
1282 Ok(())
1283 }
1284
1285 fn directive_value(&self, stmt: &Stmt) -> Option<String> {
1288 let StmtKind::Expr(expr) = &stmt.kind else {
1289 return None;
1290 };
1291 let ExprKind::String(value) = &expr.unparen().kind else {
1292 return None;
1293 };
1294 let raw = self.slice(expr.span);
1295 if !raw.starts_with('"') && !raw.starts_with('\'') {
1296 return None;
1297 }
1298 if raw.trim_matches(|c| c == '"' || c == '\'').contains('\\') {
1299 return None;
1300 }
1301 Some(value.to_string_lossy().into_owned())
1304 }
1305
1306 fn slice(&self, span: Span) -> &'a str {
1307 let src = self.lexer.source();
1308 let start = span.start.offset as usize;
1309 let end = (span.end.offset as usize).min(src.len());
1310 src.get(start..end).unwrap_or("")
1311 }
1312
1313 fn can_insert_semicolon(&self) -> bool {
1316 self.current.is_eof() || self.at_punct(Punct::RBrace) || self.current.newline_before
1317 }
1318
1319 fn semicolon(&mut self) -> Result<()> {
1320 if self.eat_punct(Punct::Semicolon)? {
1321 return Ok(());
1322 }
1323 if self.can_insert_semicolon() {
1324 return Ok(());
1325 }
1326 Err(self.error("expecting ';'"))
1329 }
1330
1331 fn parse_statement_list_item(&mut self) -> Result<Stmt> {
1334 self.enter()?;
1335 let result = self.parse_statement_list_item_guarded();
1336 self.leave();
1337 result
1338 }
1339
1340 fn parse_statement_list_item_guarded(&mut self) -> Result<Stmt> {
1341 let cover_mark = self.cover_inits.len();
1342 let stmt = self.parse_statement_list_item_inner()?;
1343 if self.cover_inits.len() > cover_mark {
1344 let span = self.cover_inits[cover_mark];
1345 self.cover_inits.truncate(cover_mark);
1346 return Err(self.error_at("expecting '}'", span));
1347 }
1348 Ok(stmt)
1349 }
1350
1351 fn parse_statement_list_item_inner(&mut self) -> Result<Stmt> {
1352 if self.at_keyword(Keyword::Function) {
1353 let start = self.current.span.start;
1354 let func = self.parse_function(FunctionForm::Declaration, false, None)?;
1355 if let Some(name) = &func.name {
1356 self.declare_function(&name.name)?;
1357 }
1358 return Ok(Stmt::new(
1359 StmtKind::FuncDecl(Box::new(func)),
1360 self.span_from(start),
1361 ));
1362 }
1363 if self.at_ident("async") {
1364 let peek = self.peek()?;
1365 if matches!(peek.kind, TokenKind::Keyword(Keyword::Function)) && !peek.newline_before {
1366 let start = self.current.span.start;
1367 self.bump()?; let func = self.parse_function(FunctionForm::Declaration, true, Some(start))?;
1369 if let Some(name) = &func.name {
1370 self.declare_function(&name.name)?;
1371 }
1372 return Ok(Stmt::new(
1373 StmtKind::FuncDecl(Box::new(func)),
1374 self.span_from(start),
1375 ));
1376 }
1377 }
1378 if self.at_keyword(Keyword::Class) {
1379 let start = self.current.span.start;
1380 let class = self.parse_class(false)?;
1381 if let Some(name) = &class.name {
1382 self.declare_lexical(&name.name)?;
1383 }
1384 return Ok(Stmt::new(
1385 StmtKind::ClassDecl(Box::new(class)),
1386 self.span_from(start),
1387 ));
1388 }
1389 if self.at_keyword(Keyword::Var) {
1390 let start = self.current.span.start;
1391 let decl = self.parse_var_decl(VarDeclKind::Var, false, true)?;
1392 self.semicolon()?;
1393 return Ok(Stmt::new(StmtKind::VarDecl(decl), self.span_from(start)));
1394 }
1395 if self.at_keyword(Keyword::Const) {
1396 let start = self.current.span.start;
1397 let decl = self.parse_var_decl(VarDeclKind::Const, false, true)?;
1398 self.semicolon()?;
1399 return Ok(Stmt::new(StmtKind::VarDecl(decl), self.span_from(start)));
1400 }
1401 if self.at_ident("let") && self.let_starts_declaration()? {
1402 let start = self.current.span.start;
1403 let decl = self.parse_var_decl(VarDeclKind::Let, false, true)?;
1404 self.semicolon()?;
1405 return Ok(Stmt::new(StmtKind::VarDecl(decl), self.span_from(start)));
1406 }
1407 if self.at_ident("await") && self.ctx.in_async && self.await_using_follows()? {
1410 let start = self.current.span.start;
1411 if self.in_case_clause {
1420 return Err(self.error_at(
1421 "using declaration is not allowed in this context",
1422 self.span_from(start),
1423 ));
1424 }
1425 self.bump()?; let decl = self.parse_var_decl_with_keyword(VarDeclKind::AwaitUsing, "using")?;
1427 self.semicolon()?;
1428 return Ok(Stmt::new(StmtKind::VarDecl(decl), self.span_from(start)));
1429 }
1430 if self.at_ident("using") && self.using_starts_declaration()? {
1431 let start = self.current.span.start;
1432 if self.scopes.len() == 1 && !self.module {
1438 return Err(self.error_at(
1439 "using declaration is not allowed at the top level of a script",
1440 self.span_from(start),
1441 ));
1442 }
1443 if self.in_case_clause {
1448 return Err(self.error_at(
1449 "using declaration is not allowed in this context",
1450 self.span_from(start),
1451 ));
1452 }
1453 let decl = self.parse_var_decl(VarDeclKind::Using, false, true)?;
1454 self.semicolon()?;
1455 return Ok(Stmt::new(StmtKind::VarDecl(decl), self.span_from(start)));
1456 }
1457 let at_module_top_level = self.module && self.scopes.len() == 1;
1464 if at_module_top_level && self.at_keyword(Keyword::Import) {
1465 let peek = self.peek()?;
1466 if !matches!(
1468 peek.kind,
1469 TokenKind::Punct(Punct::LParen) | TokenKind::Punct(Punct::Dot)
1470 ) {
1471 return self.parse_import_decl();
1472 }
1473 }
1474 if at_module_top_level && self.at_keyword(Keyword::Export) {
1475 return self.parse_export_decl();
1476 }
1477 self.parse_statement()
1478 }
1479
1480 fn let_starts_declaration(&self) -> Result<bool> {
1482 let peek = self.peek()?;
1483 Ok(matches!(
1484 peek.kind,
1485 TokenKind::Ident(_)
1486 | TokenKind::Punct(Punct::LBracket)
1487 | TokenKind::Punct(Punct::LBrace)
1488 ))
1489 }
1490
1491 fn using_head_tail(&self, skip: usize) -> Result<Option<Token>> {
1497 let mut lexer = self.lexer.clone();
1498 let mut binding = None;
1502 for _ in 0..=skip {
1503 binding = Some(lexer.next_token()?);
1504 }
1505 let Some(binding) = binding else {
1506 return Ok(None);
1507 };
1508 if binding.newline_before || !matches!(binding.kind, TokenKind::Ident(_)) {
1509 return Ok(None);
1510 }
1511 Ok(Some(lexer.next_token()?))
1512 }
1513
1514 fn await_using_follows(&self) -> Result<bool> {
1520 Ok(matches!(
1521 self.using_head_tail(1)?.map(|token| token.kind),
1522 Some(TokenKind::Punct(Punct::Eq))
1523 ))
1524 }
1525
1526 fn using_starts_declaration(&self) -> Result<bool> {
1537 Ok(matches!(
1538 self.using_head_tail(0)?.map(|token| token.kind),
1539 Some(TokenKind::Punct(Punct::Eq))
1540 ))
1541 }
1542
1543 fn using_starts_for_head(&self) -> Result<bool> {
1548 Ok(matches!(
1549 self.using_head_tail(0)?.map(|token| token.kind),
1550 Some(TokenKind::Ident(name)) if name == "of" || name == "in"
1551 ))
1552 }
1553
1554 fn await_using_starts_for_head(&self) -> Result<bool> {
1556 Ok(matches!(
1557 self.using_head_tail(1)?.map(|token| token.kind),
1558 Some(TokenKind::Ident(name)) if name == "of" || name == "in"
1559 ))
1560 }
1561
1562 fn parse_statement(&mut self) -> Result<Stmt> {
1563 let start = self.current.span.start;
1564 if self.at_punct(Punct::Semicolon) {
1565 self.bump()?;
1566 return Ok(Stmt::new(StmtKind::Empty, self.span_from(start)));
1567 }
1568 if self.at_punct(Punct::LBrace) {
1569 let body = self.parse_block()?;
1570 return Ok(Stmt::new(StmtKind::Block(body), self.span_from(start)));
1571 }
1572 if self.at_keyword(Keyword::If) {
1573 return self.parse_if();
1574 }
1575 if self.at_keyword(Keyword::Do) {
1576 return self.parse_do_while();
1577 }
1578 if self.at_keyword(Keyword::While) {
1579 return self.parse_while();
1580 }
1581 if self.at_keyword(Keyword::For) {
1582 return self.parse_for();
1583 }
1584 if self.at_keyword(Keyword::Switch) {
1585 return self.parse_switch();
1586 }
1587 if self.at_keyword(Keyword::Try) {
1588 return self.parse_try();
1589 }
1590 if self.at_keyword(Keyword::Return) {
1591 return self.parse_return();
1592 }
1593 if self.at_keyword(Keyword::Throw) {
1594 return self.parse_throw();
1595 }
1596 if self.at_keyword(Keyword::Break) {
1597 return self.parse_break_continue(true);
1598 }
1599 if self.at_keyword(Keyword::Continue) {
1600 return self.parse_break_continue(false);
1601 }
1602 if self.at_keyword(Keyword::Var) {
1607 let decl = self.parse_var_decl(VarDeclKind::Var, false, true)?;
1608 self.semicolon()?;
1609 return Ok(Stmt::new(StmtKind::VarDecl(decl), self.span_from(start)));
1610 }
1611 if self.at_keyword(Keyword::With) {
1612 return self.parse_with();
1613 }
1614 if self.at_keyword(Keyword::Debugger) {
1615 self.bump()?;
1616 self.semicolon()?;
1617 return Ok(Stmt::new(StmtKind::Debugger, self.span_from(start)));
1618 }
1619 if self.at_ident("async") {
1625 let peek = self.peek()?;
1626 if matches!(peek.kind, TokenKind::Keyword(Keyword::Function)) && !peek.newline_before {
1627 return Err(self
1628 .error("invalid 'async function' declaration in a single statement context"));
1629 }
1630 }
1631 if self.at_keyword(Keyword::Function) {
1632 if self.strict {
1635 return Err(
1636 self.error("invalid 'function' declaration in a single statement context")
1637 );
1638 }
1639 let func = self.parse_function(FunctionForm::Declaration, false, None)?;
1640 if let Some(name) = &func.name {
1641 self.declare_function(&name.name)?;
1642 }
1643 return Ok(Stmt::new(
1644 StmtKind::FuncDecl(Box::new(func)),
1645 self.span_from(start),
1646 ));
1647 }
1648 if self.at_keyword(Keyword::Class) {
1649 return Err(self.error("invalid 'class' declaration in a single statement context"));
1650 }
1651 if self.at_keyword(Keyword::Import) {
1652 let peek = self.peek()?;
1656 let expression = matches!(
1657 peek.kind,
1658 TokenKind::Punct(Punct::LParen) | TokenKind::Punct(Punct::Dot)
1659 );
1660 if !expression {
1661 return Err(self.error("'import' can only appear at the top level of a module"));
1662 }
1663 }
1664 if self.at_keyword(Keyword::Export) {
1665 return Err(self.error("'export' can only appear at the top level of a module"));
1666 }
1667 if let TokenKind::Ident(name) = &self.current.kind {
1669 if name == "await" && self.await_is_reserved() {
1673 if !self.ctx.in_async {
1674 let peek = self.peek()?;
1677 if matches!(peek.kind, TokenKind::Punct(Punct::Colon)) {
1678 return Err(self.error("unexpected 'await' keyword"));
1679 }
1680 }
1681 } else {
1685 let peek = self.peek()?;
1686 if matches!(peek.kind, TokenKind::Punct(Punct::Colon)) {
1687 return self.parse_labeled();
1688 }
1689 }
1690 }
1691 if self.at_ident("let") {
1696 let peek = self.peek()?;
1697 if matches!(peek.kind, TokenKind::Punct(Punct::LBracket)) {
1698 return Err(self.error("unexpected 'let [' in a statement"));
1699 }
1700 }
1701 self.parse_expression_statement()
1702 }
1703
1704 fn parse_block(&mut self) -> Result<Vec<Stmt>> {
1705 self.expect_punct(Punct::LBrace)?;
1706 self.push_scope(Scope::block());
1707 let saved_in_case = self.in_case_clause;
1710 self.in_case_clause = false;
1711 let result = self.parse_block_body();
1712 self.in_case_clause = saved_in_case;
1713 self.pop_scope();
1714 let body = result?;
1715 self.bump()?; Ok(body)
1717 }
1718
1719 fn parse_catch_body(&mut self) -> Result<Vec<Stmt>> {
1721 self.expect_punct(Punct::LBrace)?;
1722 let body = self.parse_block_body()?;
1723 self.bump()?; Ok(body)
1725 }
1726
1727 fn parse_block_body(&mut self) -> Result<Vec<Stmt>> {
1728 let mut body = Vec::new();
1729 while !self.at_punct(Punct::RBrace) {
1730 if self.current.is_eof() {
1731 return Err(self.unexpected());
1732 }
1733 body.push(self.parse_statement_list_item()?);
1734 }
1735 Ok(body)
1736 }
1737
1738 fn parse_expression_statement(&mut self) -> Result<Stmt> {
1739 let start = self.current.span.start;
1740 let expr = self.parse_expression(true)?;
1741 self.semicolon()?;
1742 Ok(Stmt::new(
1743 StmtKind::Expr(Box::new(expr)),
1744 self.span_from(start),
1745 ))
1746 }
1747
1748 fn parse_if(&mut self) -> Result<Stmt> {
1749 let start = self.current.span.start;
1750 self.bump()?; self.expect_punct(Punct::LParen)?;
1752 let test = self.parse_expression(true)?;
1753 self.expect_punct(Punct::RParen)?;
1754 let cons = self.parse_statement()?;
1755 let alt = if self.eat_keyword(Keyword::Else)? {
1756 Some(Box::new(self.parse_statement()?))
1757 } else {
1758 None
1759 };
1760 Ok(Stmt::new(
1761 StmtKind::If {
1762 test: Box::new(test),
1763 cons: Box::new(cons),
1764 alt,
1765 },
1766 self.span_from(start),
1767 ))
1768 }
1769
1770 fn parse_do_while(&mut self) -> Result<Stmt> {
1771 let start = self.current.span.start;
1772 self.bump()?; self.loop_depth += 1;
1774 let body = self.parse_single_statement();
1775 self.loop_depth -= 1;
1776 let body = body?;
1777 if !self.eat_keyword(Keyword::While)? {
1778 return Err(self.unexpected());
1779 }
1780 self.expect_punct(Punct::LParen)?;
1781 let test = self.parse_expression(true)?;
1782 self.expect_punct(Punct::RParen)?;
1783 let _ = self.eat_punct(Punct::Semicolon)?;
1785 Ok(Stmt::new(
1786 StmtKind::DoWhile {
1787 body: Box::new(body),
1788 test: Box::new(test),
1789 },
1790 self.span_from(start),
1791 ))
1792 }
1793
1794 fn parse_while(&mut self) -> Result<Stmt> {
1795 let start = self.current.span.start;
1796 self.bump()?; self.expect_punct(Punct::LParen)?;
1798 let test = self.parse_expression(true)?;
1799 self.expect_punct(Punct::RParen)?;
1800 self.loop_depth += 1;
1801 let body = self.parse_single_statement();
1802 self.loop_depth -= 1;
1803 Ok(Stmt::new(
1804 StmtKind::While {
1805 test: Box::new(test),
1806 body: Box::new(body?),
1807 },
1808 self.span_from(start),
1809 ))
1810 }
1811
1812 fn parse_for(&mut self) -> Result<Stmt> {
1813 let start = self.current.span.start;
1814 self.bump()?; self.push_scope(Scope::block());
1816 let result = self.parse_for_inner(start);
1817 self.pop_scope();
1818 result
1819 }
1820
1821 fn parse_for_inner(&mut self, start: Position) -> Result<Stmt> {
1822 let mut is_await = false;
1823 if self.at_ident("await") && self.ctx.in_async {
1824 let peek = self.peek()?;
1825 if matches!(peek.kind, TokenKind::Punct(Punct::LParen)) && !peek.newline_before {
1826 is_await = true;
1827 self.bump()?;
1828 }
1829 }
1830 self.expect_punct(Punct::LParen)?;
1831
1832 if self.at_punct(Punct::Semicolon) {
1834 self.bump()?;
1835 return self.parse_for_classic(start, None);
1836 }
1837
1838 let decl_kind = if self.at_keyword(Keyword::Var) {
1840 Some(VarDeclKind::Var)
1841 } else if self.at_keyword(Keyword::Const) {
1842 Some(VarDeclKind::Const)
1843 } else if self.at_ident("let") && self.let_starts_declaration()? {
1844 Some(VarDeclKind::Let)
1845 } else if self.at_ident("using") && self.using_starts_for_head()? {
1846 Some(VarDeclKind::Using)
1847 } else if self.at_ident("await")
1848 && self.ctx.in_async
1849 && self.await_using_starts_for_head()?
1850 {
1851 self.bump()?; Some(VarDeclKind::AwaitUsing)
1853 } else {
1854 None
1855 };
1856 if let Some(kind) = decl_kind {
1857 let decl_start = self.current.span.start;
1858 let decl = self.parse_var_decl(kind, true, false)?;
1859 if self.at_for_head_keyword() {
1860 let is_of = self.at_contextual("of");
1861 if !is_of && decl.declarators.len() != 1 {
1862 return Err(self.error_at(
1863 "only one binding allowed in a for-in loop",
1864 self.span_from(decl_start),
1865 ));
1866 }
1867 if is_of && decl.declarators.len() != 1 {
1868 return Err(self.error_at(
1869 "only one binding allowed in a for-of loop",
1870 self.span_from(decl_start),
1871 ));
1872 }
1873 if let Some(declarator) = decl.declarators.first() {
1874 if declarator.init.is_some() {
1875 if is_of || kind.is_lexical() || self.strict {
1877 return Err(self.error_at(
1878 if is_of {
1879 "a declaration in the head of a for-of loop can't have an initializer"
1881 } else {
1882 "a declaration in the head of a for-in loop can't have an initializer"
1883 },
1884 declarator.span,
1885 ));
1886 }
1887 }
1888 }
1889 if is_await && !is_of {
1890 return Err(self.error("for await is only valid with 'of'"));
1891 }
1892 self.bump()?; let right = self.parse_expression(true)?;
1894 self.expect_punct(Punct::RParen)?;
1895 self.loop_depth += 1;
1896 let body = self.parse_single_statement();
1897 self.loop_depth -= 1;
1898 let head = ForHead::VarDecl(decl);
1899 let span = self.span_from(start);
1900 return Ok(Stmt::new(
1901 if is_of {
1902 StmtKind::ForOf {
1903 is_await,
1904 left: head,
1905 right: Box::new(right),
1906 body: Box::new(body?),
1907 }
1908 } else {
1909 StmtKind::ForIn {
1910 left: head,
1911 right: Box::new(right),
1912 body: Box::new(body?),
1913 }
1914 },
1915 span,
1916 ));
1917 }
1918 self.expect_punct(Punct::Semicolon)?;
1919 return self.parse_for_classic(start, Some(ForInit::VarDecl(decl)));
1920 }
1921
1922 let expr_start = self.current.span.start;
1924 let expr = self.parse_expression(false)?;
1925 if self.at_for_head_keyword() {
1926 let is_of = self.at_contextual("of");
1927 if is_await && !is_of {
1928 return Err(self.error("for await is only valid with 'of'"));
1929 }
1930 let target = self.expr_to_pattern(expr, TargetKind::Assignment)?;
1931 self.bump()?; let right = self.parse_expression(true)?;
1933 self.expect_punct(Punct::RParen)?;
1934 self.loop_depth += 1;
1935 let body = self.parse_single_statement();
1936 self.loop_depth -= 1;
1937 let head = ForHead::Assign(Box::new(target));
1938 let span = self.span_from(start);
1939 return Ok(Stmt::new(
1940 if is_of {
1941 StmtKind::ForOf {
1942 is_await,
1943 left: head,
1944 right: Box::new(right),
1945 body: Box::new(body?),
1946 }
1947 } else {
1948 StmtKind::ForIn {
1949 left: head,
1950 right: Box::new(right),
1951 body: Box::new(body?),
1952 }
1953 },
1954 span,
1955 ));
1956 }
1957 let _ = expr_start;
1958 self.expect_punct(Punct::Semicolon)?;
1959 self.parse_for_classic(start, Some(ForInit::Expr(Box::new(expr))))
1960 }
1961
1962 fn at_for_head_keyword(&self) -> bool {
1965 self.at_keyword(Keyword::In) || self.at_contextual("of")
1966 }
1967
1968 fn parse_for_classic(&mut self, start: Position, init: Option<ForInit>) -> Result<Stmt> {
1969 let test = if self.at_punct(Punct::Semicolon) {
1970 None
1971 } else {
1972 Some(Box::new(self.parse_expression(true)?))
1973 };
1974 self.expect_punct(Punct::Semicolon)?;
1975 let update = if self.at_punct(Punct::RParen) {
1976 None
1977 } else {
1978 Some(Box::new(self.parse_expression(true)?))
1979 };
1980 self.expect_punct(Punct::RParen)?;
1981 self.loop_depth += 1;
1982 let body = self.parse_single_statement();
1983 self.loop_depth -= 1;
1984 Ok(Stmt::new(
1985 StmtKind::For {
1986 init,
1987 test,
1988 update,
1989 body: Box::new(body?),
1990 },
1991 self.span_from(start),
1992 ))
1993 }
1994
1995 fn parse_switch(&mut self) -> Result<Stmt> {
1996 let start = self.current.span.start;
1997 self.bump()?; self.expect_punct(Punct::LParen)?;
1999 let discriminant = self.parse_expression(true)?;
2000 self.expect_punct(Punct::RParen)?;
2001 self.expect_punct(Punct::LBrace)?;
2002 self.switch_depth += 1;
2003 self.push_scope(Scope::block());
2004 let mut cases = Vec::new();
2005 let mut seen_default = false;
2006 while !self.at_punct(Punct::RBrace) {
2007 if self.current.is_eof() {
2008 self.switch_depth -= 1;
2009 return Err(self.unexpected());
2010 }
2011 let case_start = self.current.span.start;
2012 let test = if self.eat_keyword(Keyword::Case)? {
2013 Some(Box::new(self.parse_expression(true)?))
2014 } else if self.eat_keyword(Keyword::Default)? {
2015 if seen_default {
2016 self.switch_depth -= 1;
2017 return Err(self.error("duplicate 'default' clause in switch statement"));
2018 }
2019 seen_default = true;
2020 None
2021 } else {
2022 self.switch_depth -= 1;
2023 return Err(self.unexpected());
2024 };
2025 self.expect_punct(Punct::Colon)?;
2026 let mut body = Vec::new();
2027 let saved_in_case = self.in_case_clause;
2028 self.in_case_clause = true;
2029 while !self.at_punct(Punct::RBrace)
2030 && !self.at_keyword(Keyword::Case)
2031 && !self.at_keyword(Keyword::Default)
2032 {
2033 if self.current.is_eof() {
2034 self.in_case_clause = saved_in_case;
2035 self.switch_depth -= 1;
2036 return Err(self.unexpected());
2037 }
2038 match self.parse_statement_list_item() {
2039 Ok(stmt) => body.push(stmt),
2040 Err(error) => {
2041 self.in_case_clause = saved_in_case;
2042 self.switch_depth -= 1;
2043 return Err(error);
2044 }
2045 }
2046 }
2047 self.in_case_clause = saved_in_case;
2048 cases.push(SwitchCase {
2049 test,
2050 body,
2051 span: self.span_from(case_start),
2052 });
2053 }
2054 self.switch_depth -= 1;
2055 self.bump()?; self.pop_scope();
2064 Ok(Stmt::new(
2065 StmtKind::Switch {
2066 discriminant: Box::new(discriminant),
2067 cases,
2068 },
2069 self.span_from(start),
2070 ))
2071 }
2072
2073 fn parse_try(&mut self) -> Result<Stmt> {
2074 let start = self.current.span.start;
2075 self.bump()?; let block = self.parse_block()?;
2077 let mut handler = None;
2078 let mut finalizer = None;
2079 if self.at_keyword(Keyword::Catch) {
2080 let catch_start = self.current.span.start;
2081 self.bump()?;
2082 let param = if self.eat_punct(Punct::LParen)? {
2088 let pattern = self.parse_binding_target()?;
2089 self.expect_punct(Punct::RParen)?;
2090 Some(pattern)
2091 } else {
2092 None
2093 };
2094 self.push_scope(Scope::block());
2095 let body = match ¶m {
2096 Some(Pattern {
2099 kind: PatternKind::Ident(id),
2100 ..
2101 }) => {
2102 if let Some(scope) = self.scopes.last_mut() {
2103 scope.catch_names.push(id.name.clone());
2104 }
2105 self.parse_catch_body()
2106 }
2107 Some(pattern) => {
2112 self.declare_pattern(pattern, false)?;
2113 self.parse_block()
2114 }
2115 None => self.parse_catch_body(),
2116 };
2117 self.pop_scope();
2118 let body = body?;
2119 handler = Some(CatchClause {
2120 param,
2121 body,
2122 span: self.span_from(catch_start),
2123 });
2124 }
2125 if self.eat_keyword(Keyword::Finally)? {
2126 finalizer = Some(self.parse_block()?);
2127 }
2128 if handler.is_none() && finalizer.is_none() {
2129 return Err(self.error("expecting catch or finally"));
2130 }
2131 Ok(Stmt::new(
2132 StmtKind::Try {
2133 block,
2134 handler,
2135 finalizer,
2136 },
2137 self.span_from(start),
2138 ))
2139 }
2140
2141 fn parse_return(&mut self) -> Result<Stmt> {
2142 let start = self.current.span.start;
2143 let span = self.current.span;
2144 if !self.ctx.in_function {
2145 return Err(self.error_at("return not in a function", span));
2146 }
2147 if self.ctx.in_static_block {
2148 return Err(self.error_at("return in a static initializer block", span));
2152 }
2153 self.bump()?;
2154 let argument = if self.at_punct(Punct::Semicolon)
2155 || self.at_punct(Punct::RBrace)
2156 || self.current.is_eof()
2157 || self.current.newline_before
2158 {
2159 None
2160 } else {
2161 Some(Box::new(self.parse_expression(true)?))
2162 };
2163 self.semicolon()?;
2164 Ok(Stmt::new(StmtKind::Return(argument), self.span_from(start)))
2165 }
2166
2167 fn parse_throw(&mut self) -> Result<Stmt> {
2168 let start = self.current.span.start;
2169 self.bump()?; if self.current.newline_before {
2171 return Err(self.error("line terminator not allowed after 'throw'"));
2172 }
2173 let argument = self.parse_expression(true)?;
2174 self.semicolon()?;
2175 Ok(Stmt::new(
2176 StmtKind::Throw(Box::new(argument)),
2177 self.span_from(start),
2178 ))
2179 }
2180
2181 fn parse_break_continue(&mut self, is_break: bool) -> Result<Stmt> {
2182 let start = self.current.span.start;
2183 let keyword_span = self.current.span;
2184 self.bump()?;
2185 let label = if matches!(self.current.kind, TokenKind::Ident(_))
2186 && !self.current.newline_before
2187 {
2188 let ident = self.expect_ident()?;
2189 let found = self.labels.iter().rev().find(|l| l.name == ident.name);
2190 match found {
2191 None => {
2192 return Err(
2193 self.error_at(format!("label '{}' not found", ident.name), ident.span)
2194 );
2195 }
2196 Some(label) => {
2197 if !is_break && label.kind != LabelKind::Iteration {
2198 return Err(self.error_at(
2199 format!("continue must be inside loop (label '{}')", ident.name),
2200 ident.span,
2201 ));
2202 }
2203 }
2204 }
2205 Some(ident)
2206 } else {
2207 if !is_break && self.loop_depth == 0 {
2208 return Err(self.error_at("continue must be inside loop", keyword_span));
2209 }
2210 if is_break && self.loop_depth == 0 && self.switch_depth == 0 && self.labels.is_empty()
2211 {
2212 return Err(self.error_at("break must be inside loop or switch", keyword_span));
2213 }
2214 None
2215 };
2216 self.semicolon()?;
2217 Ok(Stmt::new(
2218 if is_break {
2219 StmtKind::Break(label)
2220 } else {
2221 StmtKind::Continue(label)
2222 },
2223 self.span_from(start),
2224 ))
2225 }
2226
2227 fn parse_single_statement(&mut self) -> Result<Stmt> {
2236 let stmt = self.parse_statement()?;
2237 let mut innermost = &stmt;
2241 while let StmtKind::Labeled { body, .. } = &innermost.kind {
2242 innermost = body;
2243 }
2244 if matches!(innermost.kind, StmtKind::FuncDecl(_)) {
2245 return Err(self.error_at(
2246 "function declarations can't appear in single-statement context",
2247 stmt.span,
2248 ));
2249 }
2250 Ok(stmt)
2251 }
2252
2253 fn parse_with(&mut self) -> Result<Stmt> {
2254 let start = self.current.span.start;
2255 let span = self.current.span;
2256 if self.strict {
2257 return Err(self.error_at("invalid keyword: with", span));
2258 }
2259 self.bump()?; self.expect_punct(Punct::LParen)?;
2261 let object = self.parse_expression(true)?;
2262 self.expect_punct(Punct::RParen)?;
2263 let body = self.parse_single_statement()?;
2264 Ok(Stmt::new(
2265 StmtKind::With {
2266 object: Box::new(object),
2267 body: Box::new(body),
2268 },
2269 self.span_from(start),
2270 ))
2271 }
2272
2273 fn parse_labeled(&mut self) -> Result<Stmt> {
2274 let start = self.current.span.start;
2275 let label = self.expect_ident()?;
2276 self.expect_punct(Punct::Colon)?;
2277 if self.labels.iter().any(|l| l.name == label.name) {
2278 return Err(self.error_at(
2279 format!("label '{}' already declared", label.name),
2280 label.span,
2281 ));
2282 }
2283 let kind = if self.at_keyword(Keyword::For)
2284 || self.at_keyword(Keyword::While)
2285 || self.at_keyword(Keyword::Do)
2286 {
2287 LabelKind::Iteration
2288 } else {
2289 LabelKind::Other
2290 };
2291 self.labels.push(Label {
2292 name: label.name.clone(),
2293 kind,
2294 });
2295 let body = self.parse_statement();
2296 self.labels.pop();
2297 Ok(Stmt::new(
2298 StmtKind::Labeled {
2299 label,
2300 body: Box::new(body?),
2301 },
2302 self.span_from(start),
2303 ))
2304 }
2305
2306 fn parse_var_decl(
2309 &mut self,
2310 kind: VarDeclKind,
2311 in_for_head: bool,
2312 require_init: bool,
2313 ) -> Result<VarDecl> {
2314 let start = self.current.span.start;
2315 self.bump()?; self.parse_var_declarators(kind, in_for_head, require_init, start)
2317 }
2318
2319 fn parse_var_decl_with_keyword(&mut self, kind: VarDeclKind, keyword: &str) -> Result<VarDecl> {
2324 let start = self.current.span.start;
2325 if !self.at_ident(keyword) {
2326 return Err(self.error(format!("expected '{keyword}'")));
2327 }
2328 self.bump()?;
2329 self.parse_var_declarators(kind, false, true, start)
2330 }
2331
2332 fn parse_var_declarators(
2333 &mut self,
2334 kind: VarDeclKind,
2335 in_for_head: bool,
2336 require_init: bool,
2337 start: Position,
2338 ) -> Result<VarDecl> {
2339 let mut declarators = Vec::new();
2340 loop {
2341 let declarator_start = self.current.span.start;
2342 let target = self.parse_binding_target()?;
2343 self.declare_pattern(&target, !kind.is_lexical())?;
2348 if kind.is_using() && !matches!(target.unparen_kind(), PatternKind::Ident(_)) {
2351 return Err(self.error_at(
2352 "binding patterns are not allowed in using declarations",
2353 target.span,
2354 ));
2355 }
2356 let init = if self.eat_punct(Punct::Eq)? {
2357 Some(Box::new(self.parse_assignment(!in_for_head)?))
2360 } else {
2361 None
2362 };
2363 if init.is_none() && require_init {
2364 if kind == VarDeclKind::Const {
2365 return Err(self.error("missing initializer for const variable"));
2366 }
2367 if kind.is_using() {
2368 return Err(self.error("missing initializer in using declaration"));
2369 }
2370 if !matches!(target.unparen_kind(), PatternKind::Ident(_)) && !in_for_head {
2371 return Err(self.error_at(
2372 "missing initializer in destructuring declaration",
2373 target.span,
2374 ));
2375 }
2376 }
2377 if kind.is_lexical() {
2378 let mut names = Vec::new();
2379 target.bound_names(&mut names);
2380 if let Some(name) = names.iter().find(|n| n.name == "let") {
2381 return Err(self.error_at("'let' is not a valid lexical identifier", name.span));
2382 }
2383 }
2384 declarators.push(Declarator {
2385 target,
2386 init,
2387 span: self.span_from(declarator_start),
2388 });
2389 if !self.eat_punct(Punct::Comma)? {
2390 break;
2391 }
2392 }
2393 Ok(VarDecl {
2394 kind,
2395 declarators,
2396 span: self.span_from(start),
2397 })
2398 }
2399
2400 fn parse_binding_element(&mut self) -> Result<Pattern> {
2403 let pattern = self.parse_binding_target()?;
2404 if self.eat_punct(Punct::Eq)? {
2405 let start = pattern.span.start;
2406 let default = self.parse_assignment(self.allow_in)?;
2407 return Ok(Pattern::new(
2408 PatternKind::Assign {
2409 target: Box::new(pattern),
2410 default: Box::new(default),
2411 },
2412 self.span_from(start),
2413 ));
2414 }
2415 Ok(pattern)
2416 }
2417
2418 fn parse_binding_target(&mut self) -> Result<Pattern> {
2421 self.enter()?;
2422 let result = self.parse_binding_target_unguarded();
2423 self.leave();
2424 result
2425 }
2426
2427 fn parse_binding_target_unguarded(&mut self) -> Result<Pattern> {
2428 let start = self.current.span.start;
2429 if self.at_punct(Punct::LBracket) {
2430 return self.parse_array_pattern(start);
2431 }
2432 if self.at_punct(Punct::LBrace) {
2433 return self.parse_object_pattern(start);
2434 }
2435 let ident = self.expect_binding_ident()?;
2436 Ok(Pattern::new(
2437 PatternKind::Ident(ident),
2438 self.span_from(start),
2439 ))
2440 }
2441
2442 fn parse_array_pattern(&mut self, start: Position) -> Result<Pattern> {
2443 self.expect_punct(Punct::LBracket)?;
2444 let mut elements = Vec::new();
2445 let mut rest = None;
2446 loop {
2447 if self.at_punct(Punct::RBracket) {
2448 break;
2449 }
2450 if self.at_punct(Punct::Comma) {
2451 self.bump()?;
2452 elements.push(None);
2453 continue;
2454 }
2455 if self.at_punct(Punct::Ellipsis) {
2456 self.bump()?;
2457 let target = self.parse_binding_target()?;
2458 if self.at_punct(Punct::Comma) {
2459 return Err(self.error("rest element must be the last one"));
2460 }
2461 rest = Some(Box::new(RestElement::Pattern(target)));
2462 break;
2463 }
2464 let element_start = self.current.span.start;
2465 let element = self.parse_binding_element()?;
2466 let span = self.span_from(element_start);
2467 elements.push(Some(PatternElement::Pattern(element)));
2468 let _ = span;
2469 if !self.eat_punct(Punct::Comma)? {
2470 break;
2471 }
2472 }
2473 self.expect_punct(Punct::RBracket)?;
2474 Ok(Pattern::new(
2475 PatternKind::Array { elements, rest },
2476 self.span_from(start),
2477 ))
2478 }
2479
2480 fn parse_object_pattern(&mut self, start: Position) -> Result<Pattern> {
2481 self.expect_punct(Punct::LBrace)?;
2482 let mut properties = Vec::new();
2483 let mut rest = None;
2484 loop {
2485 if self.at_punct(Punct::RBrace) {
2486 break;
2487 }
2488 if self.at_punct(Punct::Ellipsis) {
2489 self.bump()?;
2490 let target = self.parse_binding_target()?;
2491 rest = Some(Box::new(RestElement::Pattern(target)));
2492 if self.at_punct(Punct::Comma) {
2493 return Err(self.error("rest element must be the last one"));
2494 }
2495 break;
2496 }
2497 let property_start = self.current.span.start;
2498 let key = self.parse_property_key()?;
2499 if self.eat_punct(Punct::Colon)? {
2500 let value = self.parse_binding_element()?;
2501 properties.push(Some(PatternElement::Property {
2502 key,
2503 value,
2504 shorthand: false,
2505 span: self.span_from(property_start),
2506 }));
2507 } else {
2508 let PropName::Literal(PropKey::Str(name)) = &key else {
2509 return Err(
2510 self.error("expecting ':' after a computed or numeric property key")
2511 );
2512 };
2513 let span = self.span_from(property_start);
2514 let ident = Ident {
2515 name: name.to_string_lossy().into_owned(),
2516 span,
2517 };
2518 self.check_binding_name(&ident.name, ident.span)?;
2519 let mut value = Pattern::new(PatternKind::Ident(ident), span);
2520 if self.eat_punct(Punct::Eq)? {
2521 let default = self.parse_assignment(self.allow_in)?;
2522 value = Pattern::new(
2523 PatternKind::Assign {
2524 target: Box::new(value),
2525 default: Box::new(default),
2526 },
2527 span,
2528 );
2529 }
2530 properties.push(Some(PatternElement::Property {
2531 key,
2532 value,
2533 shorthand: true,
2534 span,
2535 }));
2536 }
2537 if !self.eat_punct(Punct::Comma)? {
2538 break;
2539 }
2540 }
2541 self.expect_punct(Punct::RBrace)?;
2542 Ok(Pattern::new(
2543 PatternKind::Object { properties, rest },
2544 self.span_from(start),
2545 ))
2546 }
2547
2548 fn parse_property_key(&mut self) -> Result<PropName> {
2550 match self.current.kind.clone() {
2551 TokenKind::Ident(name) => {
2552 self.bump()?;
2553 Ok(PropName::Literal(PropKey::Str(Wtf8::new(name))))
2554 }
2555 TokenKind::Keyword(kw) => {
2556 self.bump()?;
2558 Ok(PropName::Literal(PropKey::Str(Wtf8::new(kw.as_str()))))
2559 }
2560 TokenKind::String(value) => {
2561 self.bump()?;
2562 Ok(PropName::Literal(PropKey::Str(value)))
2563 }
2564 TokenKind::Number(NumberLiteral::Int(v)) => {
2565 self.bump()?;
2566 Ok(PropName::Literal(PropKey::Num(v as f64)))
2567 }
2568 TokenKind::Number(NumberLiteral::Float(v)) => {
2569 self.bump()?;
2570 Ok(PropName::Literal(PropKey::Num(v)))
2571 }
2572 TokenKind::BigInt(big) => Err(self.error(format!(
2573 "BigInt property keys are not supported ('{}n')",
2574 big.digits
2575 ))),
2576 TokenKind::Punct(Punct::LBracket) => {
2577 self.bump()?;
2578 let expr = self.parse_assignment(true)?;
2579 self.expect_punct(Punct::RBracket)?;
2580 Ok(PropName::Computed(Box::new(expr)))
2581 }
2582 TokenKind::Punct(Punct::Hash) => {
2583 let ident = self.parse_private_name()?;
2584 Ok(PropName::Private(ident))
2585 }
2586 _ => Err(self.error("invalid property name")),
2589 }
2590 }
2591
2592 fn parse_function(
2602 &mut self,
2603 form: FunctionForm,
2604 is_async: bool,
2605 start: Option<Position>,
2606 ) -> Result<Function> {
2607 let start = start.unwrap_or(self.current.span.start);
2608 self.bump()?; let is_generator = self.eat_punct(Punct::Star)?;
2610 let name = if matches!(self.current.kind, TokenKind::Ident(_)) {
2611 let ident = if form == FunctionForm::Declaration {
2612 self.expect_binding_ident()?
2613 } else {
2614 self.expect_ident()?
2615 };
2616 if is_generator && ident.name == "yield" {
2617 return Err(self.error_at("invalid use of 'yield' as a function name", ident.span));
2618 }
2619 if is_async && ident.name == "await" {
2620 return Err(self.error_at("invalid use of 'await' as a function name", ident.span));
2621 }
2622 if self.strict && (ident.name == "eval" || ident.name == "arguments") {
2629 return Err(self.error_at("invalid function name in strict code", ident.span));
2630 }
2631 Some(ident)
2632 } else {
2633 if form == FunctionForm::Declaration {
2634 return Err(self.error("function name expected"));
2635 }
2636 None
2637 };
2638 if form == FunctionForm::Declaration
2648 && let Some(ident) = &name
2649 {
2650 self.declare_block_function(&ident.name, !is_async && !is_generator)?;
2651 }
2652 let saved = self.ctx;
2653 self.ctx = FnCtx {
2654 in_function: true,
2655 in_generator: is_generator,
2656 in_async: is_async,
2657 in_method: false,
2658 in_derived_constructor: false,
2659 in_static_block: false,
2660 arguments_allowed: true,
2661 };
2662 let saved_top = self.top_level;
2663 self.top_level = false;
2664 let params_result = self.parse_formal_parameters();
2670 let result = match params_result {
2671 Ok(params) => self.parse_function_body(params, false),
2672 Err(err) => Err(err),
2673 };
2674 self.ctx = saved;
2675 self.top_level = saved_top;
2676 let (params, params_span, body, strict) = result?;
2677 if strict
2685 && let Some(ident) = &name
2686 && (ident.name == "eval" || ident.name == "arguments")
2687 {
2688 let span = ident.span;
2689 return Err(self.error_at("invalid function name in strict code", span));
2690 }
2691 Ok(Function {
2692 name,
2693 params,
2694 body,
2695 is_async,
2696 is_generator,
2697 strict,
2698 is_arrow: false,
2699 span: self.span_from(start),
2700 params_span,
2701 source_span: None,
2702 })
2703 }
2704
2705 fn parse_formal_parameters(&mut self) -> Result<Vec<Pattern>> {
2706 let saved = self.in_formal_parameters;
2711 self.in_formal_parameters = true;
2712 let result = self.parse_formal_parameters_inner();
2713 self.in_formal_parameters = saved;
2714 result
2715 }
2716
2717 fn parse_formal_parameters_inner(&mut self) -> Result<Vec<Pattern>> {
2718 self.expect_punct(Punct::LParen)?;
2719 let mut params = Vec::new();
2720 loop {
2721 if self.at_punct(Punct::RParen) {
2722 break;
2723 }
2724 if self.at_punct(Punct::Ellipsis) {
2725 self.bump()?;
2726 if !self.at_formal_parameter() {
2729 return Err(self.error("missing formal parameter"));
2730 }
2731 let target = self.parse_binding_target()?;
2732 if matches!(target.unparen_kind(), PatternKind::Assign { .. }) {
2733 return Err(
2734 self.error_at("rest element cannot have a default value", target.span)
2735 );
2736 }
2737 params.push(Pattern::new(
2738 PatternKind::Rest(Box::new(target.clone())),
2739 target.span,
2740 ));
2741 if self.at_punct(Punct::Comma) {
2744 return Err(self.error("expecting ')'"));
2745 }
2746 break;
2747 }
2748 if !self.at_formal_parameter() {
2749 return Err(self.error("missing formal parameter"));
2750 }
2751 let param = self.parse_binding_element()?;
2752 self.check_parameter(¶m)?;
2753 params.push(param);
2754 if !self.eat_punct(Punct::Comma)? {
2755 break;
2756 }
2757 }
2758 self.expect_punct(Punct::RParen)?;
2759 Ok(params)
2760 }
2761
2762 fn check_parameter(&self, param: &Pattern) -> Result<()> {
2763 match ¶m.kind {
2764 PatternKind::Ident(ident) => self.check_binding_name(&ident.name, ident.span),
2765 PatternKind::Assign { target, .. } => self.check_parameter(target),
2766 _ => Ok(()),
2767 }
2768 }
2769
2770 fn parse_function_body(
2771 &mut self,
2772 params: Vec<Pattern>,
2773 is_method: bool,
2774 ) -> Result<(Vec<Pattern>, Span, FunctionBody, bool)> {
2775 let params_span = self.prev_end;
2776 let saved_strict = self.strict;
2781 if !self.at_punct(Punct::LBrace) {
2782 return Err(self.unexpected());
2783 }
2784 let saved_in_case = self.in_case_clause;
2787 self.in_case_clause = false;
2788 let param_names = simple_parameter_names(¶ms);
2789 let simple_params = params
2790 .iter()
2791 .all(|p| matches!(p.unparen_kind(), PatternKind::Ident(_)));
2792 let mut body = Vec::new();
2793 let mut prologue = true;
2794 let mut strict_seen = false;
2795 self.bump()?; let body_start = self.current.span;
2800 self.push_scope(Scope::function(param_names));
2801 while !self.at_punct(Punct::RBrace) {
2802 if self.current.is_eof() {
2803 return Err(self.unexpected());
2804 }
2805 let stmt = self.parse_statement_list_item()?;
2806 if prologue {
2807 match self.directive_value(&stmt) {
2808 Some(directive) if directive == "use strict" => {
2809 strict_seen = true;
2810 self.enter_strict()?;
2811 }
2812 Some(_) => {}
2813 None => prologue = false,
2814 }
2815 }
2816 body.push(stmt);
2817 }
2818 self.pop_scope();
2819 self.bump()?; let body_strict = self.strict;
2823 if strict_seen && !simple_params {
2824 return Err(self.error_at(
2825 "\"use strict\" not allowed in function with default or destructuring parameter",
2827 Span::new(params_span, params_span),
2828 ));
2829 }
2830 self.check_duplicate_parameters(
2841 ¶ms,
2842 body_strict || !simple_params || is_method,
2843 body_start,
2844 )?;
2845 if body_strict && !saved_strict {
2851 for param in ¶ms {
2852 let mut names = Vec::new();
2853 param.bound_names(&mut names);
2854 for name in names {
2855 if name.name == "eval" || name.name == "arguments" || name.name == "let" {
2856 return Err(
2857 self.error_at("invalid variable name in strict mode", name.span)
2858 );
2859 }
2860 }
2861 }
2862 }
2863 let params_span_value = Span::new(params_span, params_span);
2864 self.strict = saved_strict;
2865 self.lexer.set_strict(saved_strict);
2866 self.in_case_clause = saved_in_case;
2867 Ok((
2868 params,
2869 params_span_value,
2870 FunctionBody::Block(body),
2871 body_strict,
2872 ))
2873 }
2874
2875 fn parse_class(&mut self, is_expression: bool) -> Result<Class> {
2878 let saved_strict = self.strict;
2886 let enter = self.enter_strict();
2887 let result = match enter {
2888 Ok(()) => self.parse_class_body(is_expression),
2889 Err(error) => Err(error),
2890 };
2891 self.strict = saved_strict;
2892 self.lexer.set_strict(saved_strict);
2893 result
2894 }
2895
2896 fn parse_class_body(&mut self, is_expression: bool) -> Result<Class> {
2897 let start = self.current.span.start;
2898 self.bump()?; let name = if matches!(self.current.kind, TokenKind::Ident(_)) {
2900 if is_expression {
2901 Some(self.expect_ident()?)
2902 } else {
2903 Some(self.expect_binding_ident()?)
2904 }
2905 } else {
2906 if !is_expression {
2907 return Err(self.error("class statement requires a name"));
2908 }
2909 None
2910 };
2911 let super_class = if self.eat_keyword(Keyword::Extends)? {
2912 Some(Box::new(self.parse_lhs_expression()?))
2913 } else {
2914 None
2915 };
2916 let has_super = super_class.is_some();
2917 self.private.push(PrivateEnv::default());
2918 self.expect_punct(Punct::LBrace)?;
2919 let mut elements = Vec::new();
2920 let mut seen_constructor = false;
2921 let result = (|| -> Result<()> {
2922 while !self.at_punct(Punct::RBrace) {
2923 if self.eat_punct(Punct::Semicolon)? {
2927 continue;
2928 }
2929 elements.push(self.parse_class_element(has_super, &mut seen_constructor)?);
2930 }
2931 Ok(())
2932 })();
2933 let settled = match self.private.pop() {
2937 Some(mut env) => {
2938 let mut carried = Vec::new();
2939 for (name, span) in std::mem::take(&mut env.pending) {
2940 if env.contains(&name) {
2941 continue;
2942 }
2943 match self.private.last_mut() {
2944 Some(outer) => outer.pending.push((name, span)),
2945 None => carried.push((name, span)),
2946 }
2947 }
2948 carried
2949 }
2950 None => Vec::new(),
2951 };
2952 if let Some((name, span)) = settled
2953 .into_iter()
2954 .min_by_key(|(_, span)| span.start.offset)
2955 {
2956 return Err(self.error_at(format!("undefined private field '#{name}'"), span));
2957 }
2958 result?;
2959 let body_end = self.current.span.start;
2962 self.bump()?; let class_span = self.span_from(start);
2970 for element in &mut elements {
2971 if let ClassElement::Method {
2972 kind: MethodKind::Constructor,
2973 func,
2974 ..
2975 } = element
2976 {
2977 func.source_span = Some(class_span);
2978 }
2979 }
2980 Ok(Class {
2981 name,
2982 super_class,
2983 elements,
2984 span: class_span,
2985 body_end,
2986 })
2987 }
2988
2989 fn parse_static_block(&mut self, start: Position) -> Result<ClassElement> {
2997 let saved = self.ctx;
2998 let saved_top = self.top_level;
2999 self.ctx = FnCtx {
3000 in_function: true,
3001 in_generator: false,
3002 in_async: false,
3003 in_method: true,
3005 in_derived_constructor: false,
3006 in_static_block: true,
3007 arguments_allowed: false,
3008 };
3009 self.top_level = false;
3010 let saved_strict = self.strict;
3016 let enter = self.enter_strict();
3017 let saved_loop = self.loop_depth;
3020 let saved_switch = self.switch_depth;
3021 let saved_labels = std::mem::take(&mut self.labels);
3022 self.loop_depth = 0;
3023 self.switch_depth = 0;
3024 let body_start = self.current.span.start;
3025 let body = match enter {
3026 Ok(()) => self.parse_block(),
3027 Err(error) => Err(error),
3028 };
3029 self.strict = saved_strict;
3030 self.lexer.set_strict(saved_strict);
3031 self.ctx = saved;
3032 self.top_level = saved_top;
3033 self.loop_depth = saved_loop;
3034 self.switch_depth = saved_switch;
3035 self.labels = saved_labels;
3036 let body = body?;
3037 Ok(ClassElement::StaticBlock {
3038 body,
3039 body_start,
3040 span: self.span_from(start),
3041 })
3042 }
3043
3044 fn parse_class_element(
3045 &mut self,
3046 has_super: bool,
3047 seen_constructor: &mut bool,
3048 ) -> Result<ClassElement> {
3049 let start = self.current.span.start;
3050 let mut is_static = false;
3051 if self.at_ident("static") {
3052 let peek = self.peek()?;
3053 let is_modifier = !matches!(
3054 peek.kind,
3055 TokenKind::Punct(Punct::LParen)
3056 | TokenKind::Punct(Punct::Eq)
3057 | TokenKind::Punct(Punct::Semicolon)
3058 | TokenKind::Punct(Punct::RBrace)
3059 );
3060 if is_modifier {
3061 self.bump()?; if self.at_punct(Punct::LBrace) {
3063 return self.parse_static_block(start);
3064 }
3065 is_static = true;
3066 }
3067 }
3068 let reported_start = self.current.span.start;
3072
3073 let mut is_async = false;
3075 let mut is_generator = false;
3076 let mut accessor: Option<MethodKind> = None;
3077 if self.at_ident("async") {
3078 let peek = self.peek()?;
3079 let is_modifier = !matches!(
3080 peek.kind,
3081 TokenKind::Punct(Punct::LParen)
3082 | TokenKind::Punct(Punct::Eq)
3083 | TokenKind::Punct(Punct::Semicolon)
3084 | TokenKind::Punct(Punct::RBrace)
3085 ) && !peek.newline_before;
3086 if is_modifier {
3087 self.bump()?;
3088 is_async = true;
3089 }
3090 }
3091 if self.at_punct(Punct::Star) {
3092 self.bump()?;
3093 is_generator = true;
3094 }
3095 if accessor.is_none() && (self.at_ident("get") || self.at_ident("set")) {
3096 let is_get = self.at_ident("get");
3097 let peek = self.peek()?;
3098 if is_property_key_start(&peek.kind) {
3099 self.bump()?;
3100 accessor = Some(if is_get {
3101 MethodKind::Get
3102 } else {
3103 MethodKind::Set
3104 });
3105 }
3106 }
3107 let key = self.parse_property_key()?;
3108
3109 if matches!(&key, PropName::Private(ident) if ident.name == "constructor") {
3113 return Err(self.error("invalid method name"));
3114 }
3115 if !is_static
3121 && (is_generator || is_async || accessor.is_some())
3122 && matches!(&key, PropName::Literal(PropKey::Str(name)) if name.as_str() == Some("constructor"))
3123 {
3124 return Err(self.error("invalid method name"));
3125 }
3126
3127 if let PropName::Private(ident) = &key {
3129 if let Some(env) = self.private.last_mut() {
3130 if !env.declare(&ident.name, accessor, is_static) {
3131 return Err(self.error_at(
3132 "private class field is already defined".to_string(),
3135 ident.span,
3136 ));
3137 }
3138 }
3139 }
3140
3141 if self.at_punct(Punct::LParen) {
3142 let kind = match accessor {
3143 Some(kind) => kind,
3144 None => {
3145 let is_constructor = !is_static
3146 && !is_generator
3147 && !is_async
3148 && matches!(&key, PropName::Literal(PropKey::Str(s)) if s.as_str() == Some("constructor"));
3149 if is_constructor {
3150 if *seen_constructor {
3151 return Err(self.error_at(
3152 "property constructor appears more than once",
3153 self.span_from(start),
3154 ));
3155 }
3156 *seen_constructor = true;
3157 MethodKind::Constructor
3158 } else {
3159 MethodKind::Method
3160 }
3161 }
3162 };
3163 if kind == MethodKind::Constructor && (is_generator || is_async) {
3164 return Err(self.error("a constructor may not be a generator or async"));
3165 }
3166 let saved = self.ctx;
3167 self.ctx = FnCtx {
3168 in_function: true,
3169 in_generator: is_generator,
3170 in_async: is_async,
3171 in_method: true,
3172 in_derived_constructor: kind == MethodKind::Constructor && has_super,
3173 in_static_block: false,
3174 arguments_allowed: true,
3175 };
3176 let saved_top = self.top_level;
3177 self.top_level = false;
3178 let result = (|| -> Result<Function> {
3179 let params = self.parse_formal_parameters()?;
3180 let (params, params_span, body, strict) = self.parse_function_body(params, true)?;
3181 Ok(Function {
3182 name: None,
3183 params,
3184 body,
3185 is_async,
3186 is_generator,
3187 strict,
3188 is_arrow: false,
3189 span: Span::new(reported_start, self.prev_end),
3190 params_span,
3191 source_span: None,
3192 })
3193 })();
3194 self.ctx = saved;
3195 self.top_level = saved_top;
3196 let func = result?;
3197 if is_static {
3198 if let PropName::Literal(PropKey::Str(name)) = &key {
3199 if name == "prototype" {
3200 return Err(self.error_at("invalid method name", func.span));
3201 }
3202 }
3203 }
3204 if kind == MethodKind::Get && !func.params.is_empty() {
3205 return Err(self.error_at(
3206 "invalid number of arguments for getter or setter",
3207 func.span,
3208 ));
3209 }
3210 if kind == MethodKind::Set && func.params.len() != 1 {
3211 return Err(self.error_at(
3212 "invalid number of arguments for getter or setter",
3213 func.span,
3214 ));
3215 }
3216 return Ok(ClassElement::Method {
3217 key,
3218 is_static,
3219 kind,
3220 func: Box::new(func),
3221 span: self.span_from(start),
3222 });
3223 }
3224
3225 if accessor.is_some() {
3227 return Err(self.error("expecting '(' after an accessor name"));
3228 }
3229 if let PropName::Literal(PropKey::Str(name)) = &key {
3230 if name == "constructor" {
3237 return Err(self.error("classes may not have a field named 'constructor'"));
3238 }
3239 if name == "prototype" && is_static {
3240 return Err(self.error("classes may not have a static property named 'prototype'"));
3241 }
3242 }
3243 let saved = self.ctx;
3247 let saved_top = self.top_level;
3248 self.ctx = FnCtx {
3249 in_function: true,
3250 in_generator: false,
3251 in_async: false,
3252 in_method: true,
3253 in_derived_constructor: false,
3254 in_static_block: false,
3255 arguments_allowed: false,
3256 };
3257 self.top_level = false;
3258 let value = self
3259 .eat_punct(Punct::Eq)?
3260 .then(|| self.parse_assignment(true));
3261 self.ctx = saved;
3262 self.top_level = saved_top;
3263 let value = match value {
3264 Some(value) => Some(Box::new(value?)),
3265 None => None,
3266 };
3267 self.semicolon()?;
3269 Ok(ClassElement::Field {
3270 key,
3271 is_static,
3272 value,
3273 span: self.span_from(start),
3274 })
3275 }
3276
3277 fn parse_import_decl(&mut self) -> Result<Stmt> {
3280 let start = self.current.span.start;
3281 self.bump()?; let mut specifiers = Vec::new();
3283 if let TokenKind::String(source) = self.current.kind.clone() {
3284 let source = as_specifier(&source);
3285 self.bump()?;
3286 let attributes = self.parse_import_attributes()?;
3287 self.semicolon()?;
3288 return Ok(Stmt::new(
3289 StmtKind::Import(Box::new(ImportDecl {
3290 specifiers,
3291 source,
3292 attributes,
3293 span: self.span_from(start),
3294 })),
3295 self.span_from(start),
3296 ));
3297 }
3298 if matches!(self.current.kind, TokenKind::Ident(_)) {
3300 let local = self.expect_ident()?;
3301 specifiers.push(ImportSpecifier::Default(local));
3302 if !self.eat_punct(Punct::Comma)? {
3303 return self.finish_import(start, specifiers);
3304 }
3305 }
3306 if self.at_punct(Punct::Star) {
3307 self.bump()?;
3308 if !self.eat_contextual("as")? {
3309 return Err(self.unexpected());
3310 }
3311 let local = self.expect_ident()?;
3312 specifiers.push(ImportSpecifier::Namespace(local));
3313 return self.finish_import(start, specifiers);
3314 }
3315 if self.at_punct(Punct::LBrace) {
3316 self.bump()?;
3317 while !self.at_punct(Punct::RBrace) {
3318 let imported = self.parse_module_name()?;
3319 let local = if self.eat_contextual("as")? {
3320 self.expect_ident()?
3321 } else {
3322 match &imported {
3323 ModuleName::Ident(id) => id.clone(),
3324 ModuleName::Str(_) => {
3325 return Err(self.error_at(
3326 "a string module name must be followed by 'as'",
3327 self.current.span,
3328 ));
3329 }
3330 }
3331 };
3332 specifiers.push(ImportSpecifier::Named { imported, local });
3333 if !self.eat_punct(Punct::Comma)? {
3334 break;
3335 }
3336 }
3337 self.expect_punct(Punct::RBrace)?;
3338 } else if !specifiers.is_empty() {
3339 return Err(self.unexpected());
3340 } else if self.at_punct(Punct::LBrace) {
3341 unreachable!("handled above");
3342 } else {
3343 return Err(self.unexpected());
3344 }
3345 self.finish_import(start, specifiers)
3346 }
3347
3348 fn finish_import(&mut self, start: Position, specifiers: Vec<ImportSpecifier>) -> Result<Stmt> {
3349 if !self.eat_contextual("from")? {
3350 return Err(self.unexpected());
3351 }
3352 let TokenKind::String(source) = self.current.kind.clone() else {
3353 return Err(self.error("string expected"));
3354 };
3355 let source = as_specifier(&source);
3356 self.bump()?;
3357 let attributes = self.parse_import_attributes()?;
3358 self.semicolon()?;
3359 let span = self.span_from(start);
3360 for specifier in &specifiers {
3361 let local = match specifier {
3362 ImportSpecifier::Default(id) => id,
3363 ImportSpecifier::Namespace(id) => id,
3364 ImportSpecifier::Named { local, .. } => local,
3365 };
3366 self.declare_lexical(&local.name)?;
3367 if let Some(scope) = self.scopes.last_mut()
3368 && !scope.import_names.iter().any(|n| n == &local.name)
3369 {
3370 scope.import_names.push(local.name.clone());
3371 }
3372 }
3373 Ok(Stmt::new(
3374 StmtKind::Import(Box::new(ImportDecl {
3375 specifiers,
3376 source,
3377 attributes,
3378 span,
3379 })),
3380 span,
3381 ))
3382 }
3383
3384 fn parse_import_attributes(&mut self) -> Result<Vec<ImportAttribute>> {
3385 let mut attributes = Vec::new();
3386 let has_with = self.at_keyword(Keyword::With) || self.at_ident("assert");
3387 if !has_with {
3388 return Ok(attributes);
3389 }
3390 let peek = self.peek()?;
3391 if !matches!(peek.kind, TokenKind::Punct(Punct::LBrace)) {
3392 return Ok(attributes);
3393 }
3394 self.bump()?; self.expect_punct(Punct::LBrace)?;
3396 while !self.at_punct(Punct::RBrace) {
3397 let attr_start = self.current.span.start;
3398 let key = match self.current.kind.clone() {
3399 TokenKind::Ident(name) => name,
3400 TokenKind::String(value) => as_specifier(&value),
3401 _ => return Err(self.error("expecting an import attribute name")),
3402 };
3403 self.bump()?;
3404 self.expect_punct(Punct::Colon)?;
3405 let TokenKind::String(value) = self.current.kind.clone() else {
3406 return Err(self.error("expecting an import attribute value string"));
3407 };
3408 let value = as_specifier(&value);
3409 self.bump()?;
3410 attributes.push(ImportAttribute {
3411 key,
3412 value,
3413 span: self.span_from(attr_start),
3414 });
3415 if !self.eat_punct(Punct::Comma)? {
3416 break;
3417 }
3418 }
3419 self.expect_punct(Punct::RBrace)?;
3420 Ok(attributes)
3421 }
3422
3423 fn parse_module_name(&mut self) -> Result<ModuleName> {
3424 match self.current.kind.clone() {
3425 TokenKind::String(value) => {
3426 self.bump()?;
3427 Ok(ModuleName::Str(as_specifier(&value)))
3428 }
3429 TokenKind::Ident(_) => Ok(ModuleName::Ident(self.expect_ident()?)),
3430 TokenKind::Keyword(kw) => {
3431 let span = self.current.span;
3432 self.bump()?;
3433 Ok(ModuleName::Ident(Ident {
3434 name: kw.as_str().to_string(),
3435 span,
3436 }))
3437 }
3438 _ => Err(self.error("identifier or string expected")),
3441 }
3442 }
3443
3444 fn parse_export_decl(&mut self) -> Result<Stmt> {
3445 let start = self.current.span.start;
3446 self.bump()?; if self.at_punct(Punct::Star) {
3448 self.bump()?;
3449 let mut exported = None;
3450 if self.eat_contextual("as")? {
3451 exported = Some(self.parse_module_name()?);
3452 }
3453 if !self.eat_contextual("from")? {
3454 return Err(self.error("expecting 'from' after 'export *'"));
3455 }
3456 let TokenKind::String(source) = self.current.kind.clone() else {
3457 return Err(self.error("string expected"));
3458 };
3459 let source = as_specifier(&source);
3460 self.bump()?;
3461 let attributes = self.parse_import_attributes()?;
3462 self.semicolon()?;
3463 let span = self.span_from(start);
3464 return Ok(Stmt::new(
3465 StmtKind::Export(Box::new(ExportDecl {
3466 kind: ExportKind::All {
3467 source,
3468 exported,
3469 attributes,
3470 },
3471 span,
3472 })),
3473 span,
3474 ));
3475 }
3476 if self.eat_keyword(Keyword::Default)? {
3477 let value = if self.at_keyword(Keyword::Function) {
3478 let func = self.parse_function(FunctionForm::Expression, false, None)?;
3479 Expr::new(ExprKind::Function(Box::new(func)), self.span_from(start))
3480 } else if self.at_ident("async") {
3481 let peek = self.peek()?;
3482 if matches!(peek.kind, TokenKind::Keyword(Keyword::Function)) {
3483 self.bump()?;
3484 let func = self.parse_function(FunctionForm::Expression, true, Some(start))?;
3485 Expr::new(ExprKind::Function(Box::new(func)), self.span_from(start))
3486 } else {
3487 self.parse_assignment(true)?
3488 }
3489 } else if self.at_keyword(Keyword::Class) {
3490 let class = self.parse_class(true)?;
3491 Expr::new(ExprKind::Class(Box::new(class)), self.span_from(start))
3492 } else {
3493 let expr = self.parse_assignment(true)?;
3494 self.semicolon()?;
3495 expr
3496 };
3497 let span = self.span_from(start);
3498 return Ok(Stmt::new(
3499 StmtKind::Export(Box::new(ExportDecl {
3500 kind: ExportKind::Default(Box::new(value)),
3501 span,
3502 })),
3503 span,
3504 ));
3505 }
3506 if self.at_keyword(Keyword::Var)
3507 || self.at_keyword(Keyword::Const)
3508 || self.at_keyword(Keyword::Function)
3509 || self.at_keyword(Keyword::Class)
3510 || (self.at_ident("let") && self.let_starts_declaration()?)
3511 {
3512 let decl = self.parse_statement_list_item()?;
3513 let span = self.span_from(start);
3514 return Ok(Stmt::new(
3515 StmtKind::Export(Box::new(ExportDecl {
3516 kind: ExportKind::Declaration(Box::new(decl)),
3517 span,
3518 })),
3519 span,
3520 ));
3521 }
3522 if self.at_ident("async") {
3523 let peek = self.peek()?;
3524 if matches!(peek.kind, TokenKind::Keyword(Keyword::Function)) && !peek.newline_before {
3525 let decl = self.parse_statement_list_item()?;
3526 let span = self.span_from(start);
3527 return Ok(Stmt::new(
3528 StmtKind::Export(Box::new(ExportDecl {
3529 kind: ExportKind::Declaration(Box::new(decl)),
3530 span,
3531 })),
3532 span,
3533 ));
3534 }
3535 }
3536 if self.at_punct(Punct::LBrace) {
3537 self.bump()?;
3538 let mut specifiers = Vec::new();
3539 let mut candidates: Vec<(String, Span)> = Vec::new();
3540 let mut source = None;
3541 while !self.at_punct(Punct::RBrace) {
3542 let spec_start = self.current.span.start;
3543 let local = self.parse_module_name()?;
3544 let exported = if self.eat_contextual("as")? {
3545 self.parse_module_name()?
3546 } else {
3547 local.clone()
3548 };
3549 if let ModuleName::Ident(id) = &local {
3553 candidates.push((id.name.clone(), id.span));
3554 }
3555 specifiers.push(ExportSpecifier {
3556 local,
3557 exported,
3558 span: self.span_from(spec_start),
3559 });
3560 if !self.eat_punct(Punct::Comma)? {
3561 break;
3562 }
3563 }
3564 self.expect_punct(Punct::RBrace)?;
3565 let mut attributes = Vec::new();
3566 let has_from = self.eat_contextual("from")?;
3567 if !has_from {
3568 self.pending_exports.extend(candidates);
3572 }
3573 if has_from {
3574 let TokenKind::String(value) = self.current.kind.clone() else {
3575 return Err(self.error("string expected"));
3576 };
3577 let value = as_specifier(&value);
3578 self.bump()?;
3579 source = Some(value);
3580 attributes = self.parse_import_attributes()?;
3581 }
3582 self.semicolon()?;
3583 let span = self.span_from(start);
3584 return Ok(Stmt::new(
3585 StmtKind::Export(Box::new(ExportDecl {
3586 kind: ExportKind::Named {
3587 specifiers,
3588 source,
3589 attributes,
3590 },
3591 span,
3592 })),
3593 span,
3594 ));
3595 }
3596 Err(self.unexpected())
3597 }
3598
3599 fn expr_to_pattern(&mut self, expr: Expr, kind: TargetKind) -> Result<Pattern> {
3602 self.expr_to_pattern_inner(expr, kind, false)
3603 }
3604
3605 fn expr_to_pattern_inner(
3606 &mut self,
3607 expr: Expr,
3608 kind: TargetKind,
3609 nested: bool,
3610 ) -> Result<Pattern> {
3611 let span = expr.span;
3612 match expr.kind {
3613 ExprKind::Ident(ident) => {
3614 if kind == TargetKind::Binding {
3615 self.check_binding_name(&ident.name, ident.span)?;
3616 } else {
3617 self.check_identifier(&ident.name, ident.span)?;
3618 if self.strict && (ident.name == "eval" || ident.name == "arguments") {
3619 return Err(self.error_at(
3620 format!("invalid assignment to '{}' in strict mode", ident.name),
3621 ident.span,
3622 ));
3623 }
3624 }
3625 Ok(Pattern::new(PatternKind::Ident(ident), span))
3626 }
3627 ExprKind::Paren(inner) => {
3634 let pattern = self.expr_to_pattern_inner(*inner, kind, nested)?;
3635 if matches!(
3636 pattern.unparen_kind(),
3637 PatternKind::Object { .. } | PatternKind::Array { .. }
3638 ) {
3639 return Err(self.error_at("invalid assignment target", span));
3640 }
3641 Ok(pattern)
3642 }
3643 ExprKind::Array { elements } => {
3644 self.check_spread_trailing_comma(span, "rest element must be the last one")?;
3645 let mut out = Vec::new();
3646 let mut rest = None;
3647 let count = elements.len();
3648 for (index, element) in elements.into_iter().enumerate() {
3649 match element {
3650 None => out.push(None),
3651 Some(ArrayElement::Expr(expr)) => {
3652 let pattern = self.expr_to_pattern_inner(*expr, kind, true)?;
3653 out.push(Some(PatternElement::Pattern(pattern)));
3654 }
3655 Some(ArrayElement::Spread(expr)) => {
3656 if index + 1 != count {
3657 return Err(
3658 self.error_at("rest element must be the last one", expr.span)
3659 );
3660 }
3661 rest = Some(Box::new(self.expr_to_rest(*expr, kind)?));
3662 }
3663 }
3664 }
3665 Ok(Pattern::new(
3666 PatternKind::Array {
3667 elements: out,
3668 rest,
3669 },
3670 span,
3671 ))
3672 }
3673 ExprKind::Object(properties) => {
3674 self.check_spread_trailing_comma(span, "assignment rest property must be last")?;
3675 self.cover_inits
3676 .retain(|cover| !span_contains(span, *cover));
3677 let mut out = Vec::new();
3678 let mut rest = None;
3679 let count = properties.len();
3680 for (index, property) in properties.into_iter().enumerate() {
3681 match property {
3682 ObjectProperty::Spread(expr) => {
3683 if index + 1 != count {
3684 return Err(
3685 self.error_at("rest element must be the last one", expr.span)
3686 );
3687 }
3688 rest = Some(Box::new(self.expr_to_rest(*expr, kind)?));
3689 }
3690 ObjectProperty::Property {
3691 key,
3692 value,
3693 kind: _,
3694 shorthand,
3695 span,
3696 } => {
3697 let pattern = self.expr_to_pattern_inner(*value, kind, true)?;
3698 out.push(Some(PatternElement::Property {
3699 key,
3700 value: pattern,
3701 shorthand,
3702 span,
3703 }));
3704 }
3705 }
3706 }
3707 Ok(Pattern::new(
3708 PatternKind::Object {
3709 properties: out,
3710 rest,
3711 },
3712 span,
3713 ))
3714 }
3715 ExprKind::Assign { op, target, value } if op.is_simple() => {
3716 let target = match target.kind {
3718 PatternKind::Ident(ident) => {
3719 self.check_target_name(&ident.name, ident.span, kind)?;
3727 Pattern::new(PatternKind::Ident(ident), target.span)
3728 }
3729 other => {
3730 let expr = pattern_to_expr(Pattern::new(other, target.span), target.span);
3731 self.expr_to_pattern_inner(expr, kind, nested)?
3732 }
3733 };
3734 Ok(Pattern::new(
3735 PatternKind::Assign {
3736 target: Box::new(target),
3737 default: value,
3738 },
3739 span,
3740 ))
3741 }
3742 ExprKind::Member {
3743 object,
3744 property,
3745 optional,
3746 } => {
3747 if kind == TargetKind::Binding {
3748 return Err(self.error_at("invalid binding pattern", span));
3749 }
3750 if optional {
3751 return Err(self.error_at("invalid assignment target", span));
3752 }
3753 let op_pos = expr.op_pos;
3754 Ok(Pattern::new(
3755 PatternKind::Member(Box::new(MemberPattern {
3756 object,
3757 property,
3758 span,
3759 op_pos,
3760 })),
3761 span,
3762 ))
3763 }
3764 ExprKind::OptionalChain(_) => {
3765 Err(self.error_at("invalid assignment left-hand side", span))
3766 }
3767 other @ ExprKind::Call { .. } if !nested && kind == TargetKind::Assignment => Ok(
3772 Pattern::new(PatternKind::Invalid(Box::new(Expr::new(other, span))), span),
3773 ),
3774 _ if kind == TargetKind::Binding => Err(self.error_at("invalid binding pattern", span)),
3775 _ if nested => Err(self.error_at("invalid destructuring target", span)),
3780 _ => Err(self.error_at("invalid assignment left-hand side", span)),
3781 }
3782 }
3783
3784 fn check_spread_trailing_comma(&mut self, span: Span, message: &str) -> Result<()> {
3787 if let Some(position) = self.spread_trailing_comma.iter().position(|s| *s == span) {
3788 self.spread_trailing_comma.remove(position);
3789 return Err(self.error_at(message, span));
3790 }
3791 self.spread_trailing_comma
3795 .retain(|candidate| !span_contains(span, *candidate));
3796 Ok(())
3797 }
3798
3799 fn check_target_name(&mut self, name: &str, span: Span, kind: TargetKind) -> Result<()> {
3804 if kind == TargetKind::Binding {
3805 self.check_binding_name(name, span)?;
3806 } else {
3807 self.check_identifier(name, span)?;
3808 if self.strict && (name == "eval" || name == "arguments") {
3809 return Err(self.error_at(
3810 format!("invalid assignment to '{name}' in strict mode"),
3811 span,
3812 ));
3813 }
3814 }
3815 Ok(())
3816 }
3817
3818 fn expr_to_rest(&mut self, expr: Expr, kind: TargetKind) -> Result<RestElement> {
3819 let expr = match expr.kind {
3822 ExprKind::Spread(inner) => *inner,
3823 other => Expr::new(other, expr.span),
3824 };
3825 if let ExprKind::Assign { op, .. } = &expr.unparen().kind
3830 && op.is_simple()
3831 {
3832 return Err(self.error_at("rest element cannot have a default value", expr.span));
3833 }
3834 if kind == TargetKind::Binding {
3835 return Ok(RestElement::Pattern(
3836 self.expr_to_pattern_inner(expr, kind, true)?,
3837 ));
3838 }
3839 match &expr.kind {
3840 ExprKind::Member { optional, .. } => {
3841 if *optional {
3842 return Err(self.error_at("invalid assignment target", expr.span));
3843 }
3844 match self.expr_to_pattern_inner(expr, kind, true)?.kind {
3845 PatternKind::Member(member) => Ok(RestElement::Member(member)),
3846 _ => unreachable!("member expressions convert to member patterns"),
3847 }
3848 }
3849 _ => Ok(RestElement::Pattern(
3850 self.expr_to_pattern_inner(expr, kind, true)?,
3851 )),
3852 }
3853 }
3854
3855 fn parse_expression(&mut self, allow_in: bool) -> Result<Expr> {
3859 self.enter()?;
3860 let result = self.parse_expression_unguarded(allow_in);
3861 self.leave();
3862 result
3863 }
3864
3865 fn parse_expression_unguarded(&mut self, allow_in: bool) -> Result<Expr> {
3866 let saved_allow_in = self.allow_in;
3871 self.allow_in = allow_in;
3872 let result = self.parse_expression_in(allow_in);
3873 self.allow_in = saved_allow_in;
3874 result
3875 }
3876
3877 fn parse_expression_in(&mut self, allow_in: bool) -> Result<Expr> {
3878 let start = self.current.span.start;
3879 let first = self.parse_assignment(allow_in)?;
3880 if !self.at_punct(Punct::Comma) {
3881 return Ok(first);
3882 }
3883 let mut items = vec![first];
3884 while self.eat_punct(Punct::Comma)? {
3885 items.push(self.parse_assignment(allow_in)?);
3886 }
3887 Ok(Expr::new(ExprKind::Sequence(items), self.span_from(start)))
3888 }
3889
3890 fn parse_assignment(&mut self, allow_in: bool) -> Result<Expr> {
3891 let start = self.current.span.start;
3892
3893 if self.ctx.in_generator && self.at_ident("yield") {
3896 if self.in_formal_parameters {
3897 return Err(self.error_at("yield in default expression", self.current.span));
3898 }
3899 return self.parse_yield(allow_in);
3900 }
3901
3902 let lhs = match self.try_parse_arrow(allow_in)? {
3903 Some(arrow) => return Ok(arrow),
3904 None => self.parse_conditional(allow_in)?,
3905 };
3906
3907 if let Some(op) = self.current.kind.as_punct().and_then(AssignOp::from_punct) {
3908 let op_pos = self.current.span.start;
3909 let target = self.expr_to_pattern(lhs, TargetKind::Assignment)?;
3910 self.bump()?;
3911 let value = self.parse_assignment(allow_in)?;
3912 return Ok(Expr::at_operator(
3913 ExprKind::Assign {
3914 op,
3915 target: Box::new(target),
3916 value: Box::new(value),
3917 },
3918 self.span_from(start),
3919 op_pos,
3920 ));
3921 }
3922 let _ = start;
3923 Ok(lhs)
3924 }
3925
3926 fn parse_yield(&mut self, allow_in: bool) -> Result<Expr> {
3927 let start = self.current.span.start;
3928 self.bump()?; let delegate = if self.at_punct(Punct::Star) && !self.current.newline_before {
3930 self.bump()?;
3931 true
3932 } else {
3933 false
3934 };
3935 let argument = if delegate {
3936 Some(Box::new(self.parse_assignment(allow_in)?))
3937 } else if self.current.newline_before
3938 || self.at_punct(Punct::RParen)
3939 || self.at_punct(Punct::RBracket)
3940 || self.at_punct(Punct::RBrace)
3941 || self.at_punct(Punct::Comma)
3942 || self.at_punct(Punct::Semicolon)
3943 || self.at_punct(Punct::Colon)
3944 || self.current.is_eof()
3945 {
3946 None
3947 } else {
3948 Some(Box::new(self.parse_assignment(allow_in)?))
3949 };
3950 Ok(Expr::new(
3951 ExprKind::Yield { argument, delegate },
3952 self.span_from(start),
3953 ))
3954 }
3955
3956 fn try_parse_arrow(&mut self, allow_in: bool) -> Result<Option<Expr>> {
3957 let starts_paren = self.at_punct(Punct::LParen);
3958 let starts_ident = matches!(self.current.kind, TokenKind::Ident(_));
3959 if !starts_paren && !starts_ident {
3960 return Ok(None);
3961 }
3962 if starts_paren && !self.arrow_follows_paren()? {
3966 return Ok(None);
3967 }
3968 let snapshot = self.snapshot();
3969 let head = match self.parse_arrow_head() {
3970 Ok(head) => head,
3971 Err(error) => {
3972 self.restore(snapshot);
3978 if starts_paren || self.arrow_head_committed {
3979 return Err(error);
3980 }
3981 return Ok(None);
3982 }
3983 };
3984 let Some(head) = head else {
3985 self.restore(snapshot);
3986 return Ok(None);
3987 };
3988 let body_start = if self.at_punct(Punct::LBrace) {
3995 self.peek()?.span
3996 } else {
3997 self.current.span
3998 };
3999 self.check_duplicate_parameters(&head.params, true, body_start)?;
4000 let saved_ctx = self.ctx;
4001 let saved_loop = self.loop_depth;
4002 let saved_switch = self.switch_depth;
4003 let saved_labels = std::mem::take(&mut self.labels);
4004 let saved_top = self.top_level;
4005 self.ctx = FnCtx {
4006 in_function: true,
4007 in_generator: false,
4008 in_async: head.is_async,
4009 in_method: saved_ctx.in_method,
4010 in_derived_constructor: saved_ctx.in_derived_constructor,
4011 in_static_block: false,
4015 arguments_allowed: saved_ctx.arguments_allowed,
4016 };
4017 self.loop_depth = 0;
4018 self.switch_depth = 0;
4019 self.top_level = false;
4020 let body_start = self.current.span.start;
4021 let (body, strict) = if self.at_punct(Punct::LBrace) {
4022 let (block, strict) = self.parse_arrow_block(&head.params)?;
4023 (block, (self.prev_end, strict))
4024 } else {
4025 let expr = self.parse_assignment(allow_in)?;
4026 let end = expr.span.end;
4027 let strict = self.strict;
4029 (FunctionBody::Expr(Box::new(expr)), (end, strict))
4030 };
4031 self.ctx = saved_ctx;
4032 self.loop_depth = saved_loop;
4033 self.switch_depth = saved_switch;
4034 self.labels = saved_labels;
4035 self.top_level = saved_top;
4036 let _ = body_start;
4037 let (body, (end, strict)) = (body, strict);
4038 let span = Span::new(head.span.start, end);
4039 Ok(Some(Expr::new(
4040 ExprKind::Arrow(Box::new(Function {
4041 name: None,
4042 params: head.params,
4043 body,
4044 is_async: head.is_async,
4045 is_generator: false,
4046 strict,
4047 is_arrow: true,
4048 span,
4049 params_span: head.params_span,
4050 source_span: None,
4051 })),
4052 span,
4053 )))
4054 }
4055
4056 fn parse_arrow_block(&mut self, params: &[Pattern]) -> Result<(FunctionBody, bool)> {
4058 let saved_strict = self.strict;
4061 let params_span = self.prev_end;
4062 let simple_params = params
4070 .iter()
4071 .all(|pattern| matches!(pattern.unparen_kind(), PatternKind::Ident(_)));
4072 self.expect_punct(Punct::LBrace)?;
4073 self.push_scope(Scope::function(simple_parameter_names(params)));
4074 let mut strict_seen = false;
4075 let result = (|| -> Result<Vec<Stmt>> {
4076 let mut body = Vec::new();
4077 let mut prologue = true;
4078 while !self.at_punct(Punct::RBrace) {
4079 if self.current.is_eof() {
4080 return Err(self.unexpected());
4081 }
4082 let stmt = self.parse_statement_list_item()?;
4083 if prologue {
4084 match self.directive_value(&stmt) {
4085 Some(directive) if directive == "use strict" => {
4086 strict_seen = true;
4087 self.enter_strict()?;
4088 }
4089 Some(_) => {}
4090 None => prologue = false,
4091 }
4092 }
4093 body.push(stmt);
4094 }
4095 Ok(body)
4096 })();
4097 self.pop_scope();
4098 let body_strict = self.strict;
4099 self.strict = saved_strict;
4100 self.lexer.set_strict(saved_strict);
4101 let body = result?;
4102 if strict_seen && !simple_params {
4103 return Err(self.error_at(
4104 "\"use strict\" not allowed in function with default or destructuring parameter",
4105 Span::new(params_span, params_span),
4106 ));
4107 }
4108 self.bump()?;
4109 Ok((FunctionBody::Block(body), body_strict))
4110 }
4111
4112 fn arrow_follows_paren(&self) -> Result<bool> {
4118 let mut lexer = self.lexer.clone();
4119 let mut depth = 1usize;
4121 let mut template_depth = 0usize;
4123 loop {
4124 let token = lexer.next_token()?;
4125 match token.kind {
4126 TokenKind::Eof => return Ok(false),
4127 TokenKind::Punct(Punct::Slash) | TokenKind::Punct(Punct::SlashEq) => {
4135 if lexer.re_scan_regex(token.span.start).is_err() {
4136 lexer.reset_to(token.span.end);
4137 }
4138 }
4139 TokenKind::Template(chunk) => match chunk.kind {
4147 crate::token::TemplateKind::NoSubstitution => {}
4149 crate::token::TemplateKind::Head => template_depth += 1,
4151 crate::token::TemplateKind::Middle => {}
4153 crate::token::TemplateKind::Tail => {
4155 template_depth = template_depth.saturating_sub(1);
4156 }
4157 },
4158 TokenKind::Punct(Punct::LParen)
4159 | TokenKind::Punct(Punct::LBracket)
4160 | TokenKind::Punct(Punct::LBrace) => depth += 1,
4161 TokenKind::Punct(Punct::RBrace) if template_depth > 0 => {
4162 template_depth -= 1;
4165 let token = lexer.re_scan_template_continue(token.span.start)?;
4166 if matches!(
4167 token.kind,
4168 TokenKind::Template(crate::token::TemplateToken {
4169 kind: crate::token::TemplateKind::Head
4170 | crate::token::TemplateKind::Middle,
4171 ..
4172 })
4173 ) {
4174 template_depth += 1;
4175 }
4176 }
4177 TokenKind::Punct(Punct::RParen)
4178 | TokenKind::Punct(Punct::RBracket)
4179 | TokenKind::Punct(Punct::RBrace) => {
4180 if depth == 0 {
4181 return Ok(false);
4183 }
4184 depth -= 1;
4185 if depth == 0 {
4186 let next = lexer.next_token()?;
4189 return Ok(matches!(next.kind, TokenKind::Punct(Punct::Arrow))
4190 && !next.newline_before);
4191 }
4192 }
4193 _ => {}
4194 }
4195 }
4196 }
4197
4198 fn parse_arrow_head(&mut self) -> Result<Option<ArrowHead>> {
4200 let start = self.current.span.start;
4201 self.arrow_head_committed = false;
4202 let mut is_async = false;
4203 if self.at_ident("async") {
4204 let peek = self.peek()?;
4205 if peek.newline_before {
4206 return Ok(None);
4207 }
4208 let plausible =
4209 matches!(peek.kind, TokenKind::Punct(Punct::LParen)) || peek.kind.is_identifier();
4210 if !plausible {
4211 return Ok(None);
4212 }
4213 self.bump()?;
4214 is_async = true;
4215 }
4216 let params_start = self.current.span.start;
4217 let saved_ctx = self.ctx;
4228 if is_async {
4229 self.ctx.in_async = true;
4230 self.ctx.in_generator = false;
4231 }
4232 let params = if self.at_punct(Punct::LParen) {
4233 self.parse_formal_parameters()
4234 } else if matches!(self.current.kind, TokenKind::Ident(_)) {
4235 self.expect_ident().map(|ident| {
4236 vec![Pattern::new(
4237 PatternKind::Ident(ident),
4238 self.span_from(params_start),
4239 )]
4240 })
4241 } else {
4242 self.ctx = saved_ctx;
4243 return Ok(None);
4244 };
4245 self.ctx = saved_ctx;
4246 let params = params?;
4247 let params_span = self.span_from(params_start);
4248 if !self.at_punct(Punct::Arrow) || self.current.newline_before {
4249 return Ok(None);
4250 }
4251 self.bump()?; self.arrow_head_committed = true;
4253 let saved_formals = self.in_formal_parameters;
4262 self.in_formal_parameters = true;
4263 let checked = params
4264 .iter()
4265 .try_for_each(|param| self.check_parameter(param));
4266 self.in_formal_parameters = saved_formals;
4267 checked?;
4268 Ok(Some(ArrowHead {
4269 params,
4270 is_async,
4271 span: self.span_from(start),
4272 params_span,
4273 }))
4274 }
4275
4276 fn parse_conditional(&mut self, allow_in: bool) -> Result<Expr> {
4277 let start = self.current.span.start;
4278 let test = self.parse_binary(allow_in, 0)?;
4279 if !self.at_punct(Punct::Question) {
4280 return Ok(test);
4281 }
4282 self.bump()?;
4283 let consequent = self.parse_assignment(true)?;
4284 self.expect_punct(Punct::Colon)?;
4285 let alternate = self.parse_assignment(allow_in)?;
4286 Ok(Expr::new(
4287 ExprKind::Conditional {
4288 test: Box::new(test),
4289 cons: Box::new(consequent),
4290 alt: Box::new(alternate),
4291 },
4292 self.span_from(start),
4293 ))
4294 }
4295
4296 fn parse_binary(&mut self, allow_in: bool, min_prec: u8) -> Result<Expr> {
4297 let start = self.current.span.start;
4298 let mut lhs = self.parse_unary()?;
4299 while let Some((prec, op)) = binary_operator(&self.current.kind, allow_in) {
4300 if prec < min_prec {
4301 break;
4302 }
4303 let op_pos = self.current.span.start;
4304 self.bump()?;
4305 let next_min = if op.is_right_associative() {
4306 prec
4307 } else {
4308 prec + 1
4309 };
4310 let rhs = self.parse_binary(allow_in, next_min)?;
4311 lhs = build_binary(op, lhs, rhs, self.span_from(start), op_pos)?;
4312 }
4313 Ok(lhs)
4314 }
4315
4316 fn parse_unary(&mut self) -> Result<Expr> {
4319 let start = self.current.span.start;
4320 let unary = match &self.current.kind {
4322 TokenKind::Keyword(Keyword::Delete) => Some(UnaryOp::Delete),
4323 TokenKind::Keyword(Keyword::Void) => Some(UnaryOp::Void),
4324 TokenKind::Keyword(Keyword::Typeof) => Some(UnaryOp::Typeof),
4325 TokenKind::Punct(Punct::Plus) => Some(UnaryOp::Plus),
4326 TokenKind::Punct(Punct::Minus) => Some(UnaryOp::Minus),
4327 TokenKind::Punct(Punct::Bang) => Some(UnaryOp::Not),
4328 TokenKind::Punct(Punct::Tilde) => Some(UnaryOp::BitNot),
4329 _ => None,
4330 };
4331 if let Some(op) = unary {
4332 let op_pos = self.current.span.start;
4333 self.bump()?;
4334 let argument = self.parse_unary()?;
4335 if op == UnaryOp::Delete && self.strict {
4336 if let ExprKind::Ident(ident) = &argument.unparen().kind {
4337 return Err(self.error_at(
4338 "cannot delete a direct reference in strict mode",
4339 ident.span,
4340 ));
4341 }
4342 }
4343 if op == UnaryOp::Delete && deletes_a_private_member(&argument) {
4349 return Err(self.error("cannot delete a private class field"));
4353 }
4354 let expr = Expr::at_operator(
4355 ExprKind::Unary {
4356 op,
4357 argument: Box::new(argument),
4358 },
4359 self.span_from(start),
4360 op_pos,
4361 );
4362 if self.at_punct(Punct::StarStar) {
4363 return Err(self.error(
4364 "unparenthesized unary expression can't appear on the left-hand side of '**'",
4366 ));
4367 }
4368 return Ok(expr);
4369 }
4370 if self.at_punct(Punct::PlusPlus) || self.at_punct(Punct::MinusMinus) {
4372 let op_pos = self.current.span.start;
4373 let op = if self.at_punct(Punct::PlusPlus) {
4374 UpdateOp::Increment
4375 } else {
4376 UpdateOp::Decrement
4377 };
4378 self.bump()?;
4379 let argument = self.parse_unary()?;
4380 self.check_simple_target(&argument)?;
4381 return Ok(Expr::at_operator(
4382 ExprKind::Update {
4383 op,
4384 argument: Box::new(argument),
4385 prefix: true,
4386 },
4387 self.span_from(start),
4388 op_pos,
4389 ));
4390 }
4391 if self.at_ident("await") && self.ctx.in_async {
4398 if self.in_formal_parameters {
4401 return Err(self.error_at("await in default expression", self.current.span));
4402 }
4403 self.bump()?;
4404 let argument = self.parse_unary()?;
4405 return Ok(Expr::new(
4406 ExprKind::Await(Box::new(argument)),
4407 self.span_from(start),
4408 ));
4409 }
4410 let expr = self.parse_lhs_expression()?;
4411 let result = if (self.at_punct(Punct::PlusPlus) || self.at_punct(Punct::MinusMinus))
4413 && !self.current.newline_before
4414 {
4415 let op_pos = self.current.span.start;
4416 let op = if self.at_punct(Punct::PlusPlus) {
4417 UpdateOp::Increment
4418 } else {
4419 UpdateOp::Decrement
4420 };
4421 self.check_simple_target(&expr)?;
4422 self.bump()?;
4423 Expr::at_operator(
4424 ExprKind::Update {
4425 op,
4426 argument: Box::new(expr),
4427 prefix: false,
4428 },
4429 self.span_from(start),
4430 op_pos,
4431 )
4432 } else {
4433 expr
4434 };
4435 Ok(result)
4436 }
4437
4438 fn check_simple_target(&self, expr: &Expr) -> Result<()> {
4443 match &expr.unparen().kind {
4444 ExprKind::Ident(ident) => {
4450 if self.strict && (ident.name == "eval" || ident.name == "arguments") {
4451 return Err(self.error_at(
4452 format!("invalid assignment to '{}' in strict mode", ident.name),
4453 ident.span,
4454 ));
4455 }
4456 Ok(())
4457 }
4458 ExprKind::Member {
4459 optional: false, ..
4460 } => Ok(()),
4461 _ => Err(self.error_at("invalid increment/decrement operand", expr.span)),
4462 }
4463 }
4464
4465 fn parse_lhs_expression(&mut self) -> Result<Expr> {
4466 let start = self.current.span.start;
4467 let mut expr = if self.at_keyword(Keyword::New) {
4468 self.parse_new_expression()?
4469 } else {
4470 self.parse_primary()?
4471 };
4472 let mut saw_optional = false;
4473 loop {
4474 let op_pos = self.current.span.start;
4477 match self.current.kind.clone() {
4478 TokenKind::Punct(Punct::Dot) => {
4479 self.bump()?;
4480 let property = self.parse_member_property()?;
4481 expr = Expr::at_operator(
4482 ExprKind::Member {
4483 object: Box::new(expr),
4484 property,
4485 optional: false,
4486 },
4487 self.span_from(start),
4488 op_pos,
4489 );
4490 }
4491 TokenKind::Punct(Punct::QuestionDot) => {
4492 saw_optional = true;
4493 self.bump()?;
4494 if self.at_punct(Punct::LParen) {
4495 let arguments = self.parse_arguments()?;
4496 expr = Expr::at_operator(
4497 ExprKind::Call {
4498 callee: Box::new(expr),
4499 arguments,
4500 optional: true,
4501 },
4502 self.span_from(start),
4503 op_pos,
4504 );
4505 } else if self.at_punct(Punct::LBracket) {
4506 self.bump()?;
4507 let index = self.parse_expression(true)?;
4508 self.expect_punct(Punct::RBracket)?;
4509 expr = Expr::at_operator(
4510 ExprKind::Member {
4511 object: Box::new(expr),
4512 property: MemberProp::Computed(Box::new(index)),
4513 optional: true,
4514 },
4515 self.span_from(start),
4516 op_pos,
4517 );
4518 } else {
4519 let property = self.parse_member_property()?;
4520 expr = Expr::at_operator(
4521 ExprKind::Member {
4522 object: Box::new(expr),
4523 property,
4524 optional: true,
4525 },
4526 self.span_from(start),
4527 op_pos,
4528 );
4529 }
4530 }
4531 TokenKind::Punct(Punct::LBracket) => {
4532 self.bump()?;
4533 let index = self.parse_expression(true)?;
4534 self.expect_punct(Punct::RBracket)?;
4535 expr = Expr::at_operator(
4536 ExprKind::Member {
4537 object: Box::new(expr),
4538 property: MemberProp::Computed(Box::new(index)),
4539 optional: false,
4540 },
4541 self.span_from(start),
4542 op_pos,
4543 );
4544 }
4545 TokenKind::Punct(Punct::LParen) => {
4546 let arguments = self.parse_arguments()?;
4547 expr = Expr::at_operator(
4548 ExprKind::Call {
4549 callee: Box::new(expr),
4550 arguments,
4551 optional: false,
4552 },
4553 self.span_from(start),
4554 op_pos,
4555 );
4556 }
4557 TokenKind::Template(_) => {
4558 if saw_optional || matches!(expr.unparen().kind, ExprKind::OptionalChain(_)) {
4559 return Err(
4560 self.error("tagged template cannot be used in an optional chain")
4561 );
4562 }
4563 let quasi = self.parse_template()?;
4564 expr = Expr::new(
4565 ExprKind::TaggedTemplate {
4566 tag: Box::new(expr),
4567 quasi: Box::new(quasi),
4568 },
4569 self.span_from(start),
4570 );
4571 }
4572 _ => break,
4573 }
4574 }
4575 if saw_optional {
4576 expr = Expr::new(
4577 ExprKind::OptionalChain(Box::new(expr)),
4578 self.span_from(start),
4579 );
4580 }
4581 Ok(expr)
4582 }
4583
4584 fn parse_private_name(&mut self) -> Result<Ident> {
4591 let hash = self.current.span;
4592 self.bump()?;
4593 let ident = self.expect_ident()?;
4594 if ident.span.start.offset != hash.end.offset {
4595 return Err(self.error_at("invalid first character of private name", hash));
4596 }
4597 Ok(ident)
4598 }
4599
4600 fn parse_member_property(&mut self) -> Result<MemberProp> {
4601 if self.at_punct(Punct::Hash) {
4602 let ident = self.parse_private_name()?;
4603 if !self.private.iter().any(|env| env.contains(&ident.name)) {
4604 let Some(innermost) = self.private.last_mut() else {
4610 return Err(self.error_at(
4611 format!("undefined private field '#{}'", ident.name),
4612 ident.span,
4613 ));
4614 };
4615 innermost.pending.push((ident.name.clone(), ident.span));
4619 }
4620 return Ok(MemberProp::Private(ident));
4621 }
4622 match self.current.kind.clone() {
4623 TokenKind::Ident(name) => {
4624 let span = self.current.span;
4625 self.bump()?;
4626 Ok(MemberProp::Ident(Ident { name, span }))
4627 }
4628 TokenKind::Keyword(kw) => {
4629 let span = self.current.span;
4630 self.bump()?;
4631 Ok(MemberProp::Ident(Ident {
4632 name: kw.as_str().to_string(),
4633 span,
4634 }))
4635 }
4636 _ => Err(self.error("expecting field name")),
4640 }
4641 }
4642
4643 fn parse_new_expression(&mut self) -> Result<Expr> {
4644 let start = self.current.span.start;
4645 self.bump()?; if self.at_punct(Punct::Dot) {
4647 self.bump()?;
4648 if !self.at_ident("target") {
4649 return Err(self.error("expecting target"));
4650 }
4651 if !self.ctx.in_function {
4652 return Err(self.error("new.target only allowed within functions"));
4653 }
4654 self.bump()?;
4655 return Ok(Expr::new(ExprKind::NewTarget, self.span_from(start)));
4656 }
4657 let mut callee = if self.at_keyword(Keyword::New) {
4658 self.parse_new_expression()?
4659 } else {
4660 self.parse_primary()?
4661 };
4662 loop {
4664 let op_pos = self.current.span.start;
4665 match self.current.kind.clone() {
4666 TokenKind::Punct(Punct::Dot) => {
4667 self.bump()?;
4668 let property = self.parse_member_property()?;
4669 callee = Expr::at_operator(
4670 ExprKind::Member {
4671 object: Box::new(callee),
4672 property,
4673 optional: false,
4674 },
4675 self.span_from(start),
4676 op_pos,
4677 );
4678 }
4679 TokenKind::Punct(Punct::LBracket) => {
4680 self.bump()?;
4681 let index = self.parse_expression(true)?;
4682 self.expect_punct(Punct::RBracket)?;
4683 callee = Expr::at_operator(
4684 ExprKind::Member {
4685 object: Box::new(callee),
4686 property: MemberProp::Computed(Box::new(index)),
4687 optional: false,
4688 },
4689 self.span_from(start),
4690 op_pos,
4691 );
4692 }
4693 TokenKind::Punct(Punct::QuestionDot) => {
4694 return Err(self.error("new keyword cannot be used with an optional chain"));
4695 }
4696 _ => break,
4697 }
4698 }
4699 if matches!(callee.unparen().kind, ExprKind::OptionalChain(_)) {
4700 return Err(self.error_at("cannot use 'new' with an optional chain", callee.span));
4701 }
4702 if let Some(import_call) = member_chain_import_call(&callee) {
4714 return Err(self.error_at("invalid use of 'import()'", import_call.span));
4715 }
4716 if matches!(&callee.kind, ExprKind::ImportCall(..)) {
4722 return Err(self.error_at("invalid use of 'import()'", callee.span));
4723 }
4724 let arguments = if self.at_punct(Punct::LParen) {
4725 let op_pos = self.current.span.start;
4727 let arguments = Some(self.parse_arguments()?);
4728 return Ok(Expr::at_operator(
4729 ExprKind::New {
4730 callee: Box::new(callee),
4731 arguments,
4732 },
4733 self.span_from(start),
4734 op_pos,
4735 ));
4736 } else {
4737 None
4738 };
4739 Ok(Expr::at_operator(
4743 ExprKind::New {
4744 callee: Box::new(callee),
4745 arguments,
4746 },
4747 self.span_from(start),
4748 self.current.span.start,
4749 ))
4750 }
4751
4752 fn parse_arguments(&mut self) -> Result<Vec<Expr>> {
4753 self.expect_punct(Punct::LParen)?;
4754 let mut arguments = Vec::new();
4755 while !self.at_punct(Punct::RParen) {
4756 if self.at_punct(Punct::Ellipsis) {
4757 let start = self.current.span.start;
4758 self.bump()?;
4759 let argument = self.parse_assignment(true)?;
4760 arguments.push(Expr::new(
4761 ExprKind::Spread(Box::new(argument)),
4762 self.span_from(start),
4763 ));
4764 } else {
4765 arguments.push(self.parse_assignment(true)?);
4766 }
4767 if !self.eat_punct(Punct::Comma)? {
4768 break;
4769 }
4770 }
4771 self.expect_punct(Punct::RParen)?;
4772 Ok(arguments)
4773 }
4774
4775 fn parse_primary(&mut self) -> Result<Expr> {
4782 let start = self.current.span.start;
4783 match self.current.kind.clone() {
4784 TokenKind::Number(NumberLiteral::Int(value)) => {
4785 self.bump()?;
4786 Ok(Expr::new(
4787 ExprKind::Number(value as f64),
4788 self.span_from(start),
4789 ))
4790 }
4791 TokenKind::Number(NumberLiteral::Float(value)) => {
4792 self.bump()?;
4793 Ok(Expr::new(ExprKind::Number(value), self.span_from(start)))
4794 }
4795 TokenKind::String(value) => {
4796 self.bump()?;
4797 Ok(Expr::new(ExprKind::String(value), self.span_from(start)))
4798 }
4799 TokenKind::Ident(name) if name == "async" && !self.current.escaped => {
4803 let peek = self.peek()?;
4804 if matches!(peek.kind, TokenKind::Keyword(Keyword::Function))
4805 && !peek.newline_before
4806 {
4807 self.bump()?; let func = self.parse_function(FunctionForm::Expression, true, Some(start))?;
4809 return Ok(Expr::new(
4810 ExprKind::Function(Box::new(func)),
4811 self.span_from(start),
4812 ));
4813 }
4814 let span = self.current.span;
4815 self.bump()?;
4816 Ok(Expr::new(ExprKind::Ident(Ident { name, span }), span))
4817 }
4818 TokenKind::Ident(name) => {
4819 let span = self.current.span;
4820 self.check_identifier(&name, span)?;
4821 self.check_arguments_reference(&name, span)?;
4822 self.bump()?;
4823 Ok(Expr::new(ExprKind::Ident(Ident { name, span }), span))
4824 }
4825 TokenKind::Keyword(Keyword::This) => {
4826 self.bump()?;
4827 Ok(Expr::new(ExprKind::This, self.span_from(start)))
4828 }
4829 TokenKind::Keyword(Keyword::Null) => {
4830 self.bump()?;
4831 Ok(Expr::new(ExprKind::Null, self.span_from(start)))
4832 }
4833 TokenKind::Keyword(Keyword::True) => {
4834 self.bump()?;
4835 Ok(Expr::new(ExprKind::Bool(true), self.span_from(start)))
4836 }
4837 TokenKind::Keyword(Keyword::False) => {
4838 self.bump()?;
4839 Ok(Expr::new(ExprKind::Bool(false), self.span_from(start)))
4840 }
4841 TokenKind::Punct(Punct::LParen) => {
4842 self.bump()?;
4843 let inner = self.parse_expression(true)?;
4844 self.expect_punct(Punct::RParen)?;
4845 Ok(Expr::new(
4846 ExprKind::Paren(Box::new(inner)),
4847 self.span_from(start),
4848 ))
4849 }
4850 TokenKind::Punct(Punct::Slash) | TokenKind::Punct(Punct::SlashEq) => {
4851 self.parse_regex_literal(start)
4852 }
4853 _ => self.parse_primary_complex(start),
4854 }
4855 }
4856
4857 #[inline(never)]
4860 fn parse_primary_complex(&mut self, start: Position) -> Result<Expr> {
4861 match self.current.kind.clone() {
4862 TokenKind::BigInt(literal) => {
4863 self.bump()?;
4864 Ok(Expr::new(
4865 ExprKind::BigInt {
4866 digits: literal.digits,
4867 radix: literal.radix,
4868 },
4869 self.span_from(start),
4870 ))
4871 }
4872 TokenKind::Template(_) => {
4873 let template = self.parse_template()?;
4874 Ok(Expr::new(
4875 ExprKind::Template(Box::new(template)),
4876 self.span_from(start),
4877 ))
4878 }
4879 TokenKind::Keyword(Keyword::Function) => {
4880 let func = self.parse_function(FunctionForm::Expression, false, None)?;
4881 Ok(Expr::new(
4882 ExprKind::Function(Box::new(func)),
4883 self.span_from(start),
4884 ))
4885 }
4886 TokenKind::Keyword(Keyword::Class) => {
4887 let class = self.parse_class(true)?;
4888 Ok(Expr::new(
4889 ExprKind::Class(Box::new(class)),
4890 self.span_from(start),
4891 ))
4892 }
4893 TokenKind::Keyword(Keyword::Import) => self.parse_import_expression(),
4894 TokenKind::Keyword(Keyword::Super) => self.parse_super(),
4895 TokenKind::Punct(Punct::LBracket) => self.parse_array_literal(),
4896 TokenKind::Punct(Punct::LBrace) => self.parse_object_literal(),
4897 TokenKind::Punct(Punct::Hash) if self.allow_in => self.parse_private_in(start),
4902 TokenKind::Punct(Punct::Hash) => {
4906 let hash = self.current.span;
4907 let name = match self.peek()?.kind.clone() {
4908 TokenKind::Ident(name) => format!("#{name}"),
4909 _ => "#".to_string(),
4910 };
4911 Err(SyntaxError::new(
4912 format!("unexpected token in expression: '{name}'"),
4913 hash,
4914 ))
4915 }
4916 _ => Err(self.unexpected()),
4917 }
4918 }
4919
4920 #[inline(never)]
4922 fn parse_super(&mut self) -> Result<Expr> {
4923 let start = self.current.span.start;
4924 self.bump()?;
4925 let after = self.current.span;
4931 if self.at_punct(Punct::LParen) {
4932 if !self.ctx.in_derived_constructor {
4933 return Err(self.error_at(
4934 "super() is only valid in a derived class constructor",
4935 after,
4936 ));
4937 }
4938 let arguments = self.parse_arguments()?;
4941 return Ok(Expr::at_operator(
4942 ExprKind::SuperCall(arguments),
4943 self.span_from(start),
4944 after.start,
4945 ));
4946 }
4947 if !self.ctx.in_method {
4948 let message = if self.at_punct(Punct::Dot) || self.at_punct(Punct::LBracket) {
4955 "'super' is only valid in a method"
4956 } else {
4957 "invalid use of 'super'"
4958 };
4959 return Err(self.error_at(message, after));
4960 }
4961 Ok(Expr::new(ExprKind::SuperProp, self.span_from(start)))
4962 }
4963
4964 #[inline(never)]
4966 fn parse_private_in(&mut self, start: Position) -> Result<Expr> {
4967 self.bump()?;
4968 let ident = self.expect_ident()?;
4969 if !self.private.iter().any(|env| env.contains(&ident.name)) {
4970 return Err(self.error_at(
4971 format!(
4972 "private field '#{}' must be declared in an enclosing class",
4973 ident.name
4974 ),
4975 ident.span,
4976 ));
4977 }
4978 if !self.at_keyword(Keyword::In) {
4979 return Err(self.error("expecting 'in' after a private name"));
4980 }
4981 self.bump()?;
4982 if self.at_punct(Punct::Hash) {
4986 let hash = self.current.span;
4987 let name = match self.peek()?.kind.clone() {
4988 TokenKind::Ident(name) => format!("#{name}"),
4989 _ => "#".to_string(),
4990 };
4991 return Err(SyntaxError::new(
4992 format!("unexpected token in expression: '{name}'"),
4993 hash,
4994 ));
4995 }
4996 let object = self.parse_unary()?;
4997 Ok(Expr::new(
4998 ExprKind::PrivateIn {
4999 name: ident,
5000 object: Box::new(object),
5001 },
5002 self.span_from(start),
5003 ))
5004 }
5005
5006 #[inline(never)]
5009 fn parse_regex_literal(&mut self, start: Position) -> Result<Expr> {
5010 let token = self.lexer.re_scan_regex(self.current.span.start)?;
5011 self.current = token;
5012 let TokenKind::RegExp { pattern, flags } = self.current.kind.clone() else {
5013 unreachable!("re_scan_regex returns a RegExp token")
5014 };
5015 let mut seen = 0u8;
5024 for flag in flags.chars() {
5025 let bit = match flag {
5026 'g' => 1 << 0,
5027 'i' => 1 << 1,
5028 'm' => 1 << 2,
5029 's' => 1 << 3,
5030 'y' => 1 << 4,
5031 'u' => 1 << 5,
5032 'd' => 1 << 6,
5033 'v' => 1 << 7,
5034 _ => {
5035 return Err(SyntaxError::new(
5036 "invalid regular expression flags",
5037 self.current.span,
5038 ));
5039 }
5040 };
5041 if seen & bit != 0 {
5042 return Err(SyntaxError::new(
5043 "duplicate regular expression flag",
5044 self.current.span,
5045 ));
5046 }
5047 seen |= bit;
5048 }
5049 if seen & (1 << 5) != 0 && seen & (1 << 7) != 0 {
5051 return Err(SyntaxError::new(
5052 "invalid regular expression flags",
5053 self.current.span,
5054 ));
5055 }
5056 self.bump()?;
5057 Ok(Expr::new(
5058 ExprKind::RegExp { pattern, flags },
5059 self.span_from(start),
5060 ))
5061 }
5062
5063 fn parse_import_expression(&mut self) -> Result<Expr> {
5064 let start = self.current.span.start;
5065 self.bump()?; if self.at_punct(Punct::Dot) {
5067 if !self.module {
5068 return Err(self.error_at(
5069 "import.meta only valid in module code",
5070 self.span_from(start),
5071 ));
5072 }
5073 self.bump()?;
5074 if !self.at_ident("meta") {
5075 return Err(self.error("expecting 'meta' after 'import.'"));
5076 }
5077 self.bump()?;
5078 return Ok(Expr::new(ExprKind::ImportMeta, self.span_from(start)));
5079 }
5080 if self.at_punct(Punct::LParen) {
5081 self.bump()?;
5082 let specifier = self.parse_assignment(true)?;
5083 let mut options = None;
5094 if self.at_punct(Punct::Comma) {
5095 self.bump()?;
5096 if !self.at_punct(Punct::RParen) {
5097 options = Some(Box::new(self.parse_assignment(true)?));
5098 if self.at_punct(Punct::Comma) {
5099 self.bump()?;
5100 }
5101 }
5102 }
5103 self.expect_punct(Punct::RParen)?;
5104 return Ok(Expr::new(
5105 ExprKind::ImportCall(Box::new(specifier), options),
5106 self.span_from(start),
5107 ));
5108 }
5109 Err(self.unexpected())
5110 }
5111
5112 fn parse_array_literal(&mut self) -> Result<Expr> {
5113 let start = self.current.span.start;
5114 self.expect_punct(Punct::LBracket)?;
5115 let mut elements = Vec::new();
5116 let mut spread_comma_closed = false;
5119 while !self.at_punct(Punct::RBracket) {
5120 if self.at_punct(Punct::Comma) {
5121 self.bump()?;
5122 elements.push(None);
5123 spread_comma_closed = false;
5124 continue;
5125 }
5126 let spread = self.at_punct(Punct::Ellipsis);
5127 if spread {
5128 let spread_start = self.current.span.start;
5129 self.bump()?;
5130 let argument = self.parse_assignment(true)?;
5131 elements.push(Some(ArrayElement::Spread(Box::new(Expr::new(
5132 ExprKind::Spread(Box::new(argument)),
5133 self.span_from(spread_start),
5134 )))));
5135 } else {
5136 let expr = self.parse_assignment(true)?;
5137 elements.push(Some(ArrayElement::Expr(Box::new(expr))));
5138 }
5139 if !self.eat_punct(Punct::Comma)? {
5140 break;
5141 }
5142 spread_comma_closed = spread && self.at_punct(Punct::RBracket);
5143 }
5144 self.expect_punct(Punct::RBracket)?;
5145 let span = self.span_from(start);
5146 if spread_comma_closed {
5147 self.spread_trailing_comma.push(span);
5148 }
5149 Ok(Expr::new(ExprKind::Array { elements }, span))
5150 }
5151
5152 fn parse_object_literal(&mut self) -> Result<Expr> {
5153 let start = self.current.span.start;
5154 self.expect_punct(Punct::LBrace)?;
5155 let mut properties: Vec<ObjectProperty> = Vec::new();
5156 let mut proto_count = 0;
5157 let mut spread_comma_closed = false;
5158 while !self.at_punct(Punct::RBrace) {
5159 let property_start = self.current.span.start;
5160 if self.at_punct(Punct::Ellipsis) {
5161 self.bump()?;
5162 let argument = self.parse_assignment(true)?;
5163 properties.push(ObjectProperty::Spread(Box::new(argument)));
5164 } else {
5165 let mut is_async = false;
5166 let mut is_generator = false;
5167 let mut accessor: Option<MethodKind> = None;
5168 if self.at_ident("async") {
5169 let peek = self.peek()?;
5170 let is_modifier = !matches!(
5171 peek.kind,
5172 TokenKind::Punct(Punct::LParen)
5173 | TokenKind::Punct(Punct::Colon)
5174 | TokenKind::Punct(Punct::Comma)
5175 | TokenKind::Punct(Punct::RBrace)
5176 | TokenKind::Punct(Punct::Eq)
5177 ) && !peek.newline_before;
5178 if is_modifier {
5179 self.bump()?;
5180 is_async = true;
5181 }
5182 }
5183 if self.at_punct(Punct::Star) {
5184 self.bump()?;
5185 is_generator = true;
5186 }
5187 if accessor.is_none() && (self.at_ident("get") || self.at_ident("set")) {
5188 let is_get = self.at_ident("get");
5189 let peek = self.peek()?;
5190 if is_property_key_start(&peek.kind) {
5191 self.bump()?;
5192 accessor = Some(if is_get {
5193 MethodKind::Get
5194 } else {
5195 MethodKind::Set
5196 });
5197 }
5198 }
5199 let key = self.parse_property_key()?;
5200 let is_computed = matches!(key, PropName::Computed(_));
5201 if self.at_punct(Punct::LParen) {
5202 let saved = self.ctx;
5203 self.ctx = FnCtx {
5204 in_function: true,
5205 in_generator: is_generator,
5206 in_async: is_async,
5207 in_method: true,
5208 in_derived_constructor: false,
5209 in_static_block: false,
5210 arguments_allowed: true,
5211 };
5212 let saved_top = self.top_level;
5213 self.top_level = false;
5214 let func_result = (|| -> Result<Function> {
5215 let params = self.parse_formal_parameters()?;
5216 let (params, params_span, body, strict) =
5217 self.parse_function_body(params, true)?;
5218 Ok(Function {
5219 name: None,
5220 params,
5221 body,
5222 is_async,
5223 is_generator,
5224 strict,
5225 is_arrow: false,
5226 span: self.span_from(property_start),
5227 params_span,
5228 source_span: None,
5229 })
5230 })();
5231 self.ctx = saved;
5232 self.top_level = saved_top;
5233 let func = func_result?;
5234 let kind = match accessor {
5235 Some(kind) => {
5236 if is_generator || is_async {
5237 return Err(self.error_at(
5238 "accessors may not be generators or async",
5239 func.span,
5240 ));
5241 }
5242 if kind == MethodKind::Get && !func.params.is_empty() {
5243 return Err(self.error_at(
5244 "invalid number of arguments for getter or setter",
5245 func.span,
5246 ));
5247 }
5248 if kind == MethodKind::Set && func.params.len() != 1 {
5249 return Err(self.error_at(
5250 "invalid number of arguments for getter or setter",
5251 func.span,
5252 ));
5253 }
5254 match kind {
5255 MethodKind::Get => PropertyKind::Get,
5256 MethodKind::Set => PropertyKind::Set,
5257 MethodKind::Method | MethodKind::Constructor => {
5258 PropertyKind::Method
5259 }
5260 }
5261 }
5262 None => PropertyKind::Method,
5263 };
5264 let span = self.span_from(property_start);
5265 properties.push(ObjectProperty::Property {
5266 key,
5267 value: Box::new(Expr::new(ExprKind::Function(Box::new(func)), span)),
5268 kind,
5269 shorthand: false,
5270 span,
5271 });
5272 } else if self.eat_punct(Punct::Colon)? {
5273 let value = self.parse_assignment(true)?;
5274 if !is_computed
5275 && let Some(PropKeyRef::Str(name)) = key.static_name()
5276 && name == "__proto__"
5277 {
5278 proto_count += 1;
5279 if proto_count > 1 {
5280 return Err(self.error_at(
5281 "duplicate __proto__ property name",
5282 self.span_from(property_start),
5283 ));
5284 }
5285 }
5286 properties.push(ObjectProperty::Property {
5287 key,
5288 value: Box::new(value),
5289 kind: PropertyKind::Value,
5290 shorthand: false,
5291 span: self.span_from(property_start),
5292 });
5293 } else {
5294 let PropName::Literal(PropKey::Str(name)) = &key else {
5297 return Err(self.error("expecting ':' after a property name"));
5298 };
5299 let ident_span = self.span_from(property_start);
5300 let ident = Ident {
5301 name: name.to_string_lossy().into_owned(),
5305 span: ident_span,
5306 };
5307 self.check_identifier(&ident.name, ident.span)?;
5308 let mut value = Expr::new(ExprKind::Ident(ident.clone()), ident_span);
5309 if self.at_punct(Punct::Eq) {
5310 self.cover_inits.push(ident_span);
5313 self.bump()?;
5314 let default = self.parse_assignment(true)?;
5315 let target = Pattern::new(PatternKind::Ident(ident), ident_span);
5316 value = Expr::new(
5317 ExprKind::Assign {
5318 op: AssignOp::Assign,
5319 target: Box::new(target),
5320 value: Box::new(default),
5321 },
5322 ident_span,
5323 );
5324 }
5325 properties.push(ObjectProperty::Property {
5326 key,
5327 value: Box::new(value),
5328 kind: PropertyKind::Value,
5329 shorthand: true,
5330 span: ident_span,
5331 });
5332 }
5333 }
5334 let spread = matches!(properties.last(), Some(ObjectProperty::Spread(_)));
5337 if !self.eat_punct(Punct::Comma)? {
5338 break;
5339 }
5340 spread_comma_closed = spread && self.at_punct(Punct::RBrace);
5341 }
5342 self.expect_punct(Punct::RBrace)?;
5343 let span = self.span_from(start);
5344 if spread_comma_closed {
5345 self.spread_trailing_comma.push(span);
5346 }
5347 Ok(Expr::new(ExprKind::Object(properties), span))
5348 }
5349
5350 fn parse_template(&mut self) -> Result<TemplateLiteral> {
5351 let mut quasis = Vec::new();
5352 let mut expressions = Vec::new();
5353 loop {
5354 let (cooked, raw, kind) = match self.current.kind.clone() {
5355 TokenKind::Template(chunk) => (chunk.cooked, chunk.raw, chunk.kind),
5356 _ => return Err(self.error("expecting a template literal")),
5357 };
5358 let tail = matches!(kind, TemplateKind::NoSubstitution | TemplateKind::Tail);
5359 quasis.push(TemplateChunk { cooked, raw, tail });
5360 if tail {
5361 self.bump()?;
5362 break;
5363 }
5364 self.bump()?; let expr = self.parse_expression(true)?;
5366 expressions.push(expr);
5367 if !self.at_punct(Punct::RBrace) {
5368 return Err(self.error("expecting '}' in a template substitution"));
5369 }
5370 let brace = self.current.span.start;
5371 let token = self.lexer.re_scan_template_continue(brace)?;
5372 self.current = token;
5373 }
5374 Ok(TemplateLiteral {
5375 quasis,
5376 expressions,
5377 })
5378 }
5379}
5380
5381#[derive(Debug, Clone, Copy, PartialEq, Eq)]
5383enum FunctionForm {
5384 Declaration,
5385 Expression,
5386}
5387
5388fn is_plain_identifier(param: &Pattern) -> bool {
5396 matches!(param.unparen_kind(), PatternKind::Ident(_))
5397}
5398
5399fn parameter_bindings(param: &Pattern) -> Vec<(String, Span, bool)> {
5405 fn walk(pattern: &Pattern, in_pattern: bool, out: &mut Vec<(String, Span, bool)>) {
5406 match &pattern.kind {
5407 PatternKind::Ident(ident) => out.push((ident.name.clone(), ident.span, in_pattern)),
5408 PatternKind::Assign { target, default } => {
5409 walk(target, in_pattern, out);
5410 let _ = default;
5412 }
5413 PatternKind::Rest(target) => walk(target, !is_plain_identifier(target), out),
5414 PatternKind::Array { .. } | PatternKind::Object { .. } => {
5415 let mut names = Vec::new();
5416 pattern.bound_names(&mut names);
5417 for name in names {
5418 out.push((name.name, name.span, true));
5419 }
5420 }
5421 _ => {}
5422 }
5423 }
5424 let mut out = Vec::new();
5425 let in_pattern = !is_plain_identifier(param);
5426 walk(param, in_pattern, &mut out);
5427 if out.is_empty() {
5430 let mut names = Vec::new();
5431 param.bound_names(&mut names);
5432 out.extend(names.into_iter().map(|name| (name.name, name.span, false)));
5433 }
5434 out
5435}
5436
5437fn pattern_has_default(pattern: &Pattern) -> bool {
5443 let element = |element: &Option<PatternElement>| {
5444 element.as_ref().is_some_and(|element| match element {
5445 PatternElement::Pattern(inner) => pattern_has_default(inner),
5446 PatternElement::Property { value, .. } => pattern_has_default(value),
5447 })
5448 };
5449 let rest = |rest: &Option<Box<RestElement>>| {
5450 rest.as_ref().is_some_and(|rest| match rest.as_ref() {
5451 RestElement::Pattern(inner) => pattern_has_default(inner),
5452 RestElement::Member(_) => false,
5453 })
5454 };
5455 match &pattern.kind {
5456 PatternKind::Assign { .. } => true,
5457 PatternKind::Array {
5458 elements,
5459 rest: tail,
5460 } => elements.iter().any(element) || rest(tail),
5461 PatternKind::Object {
5462 properties,
5463 rest: tail,
5464 } => properties.iter().any(element) || rest(tail),
5465 PatternKind::Rest(target) => pattern_has_default(target),
5466 _ => false,
5467 }
5468}
5469
5470fn simple_parameter_names(params: &[Pattern]) -> Vec<String> {
5471 params
5472 .iter()
5473 .filter_map(|param| match ¶m.kind {
5474 PatternKind::Ident(id) => Some(id.name.clone()),
5475 _ => None,
5476 })
5477 .collect()
5478}
5479
5480fn collect_module_binding(stmt: &Stmt, out: &mut Vec<String>) {
5483 match &stmt.kind {
5484 StmtKind::VarDecl(decl) => {
5485 if decl.kind.is_using() {
5491 return;
5492 }
5493 for declarator in &decl.declarators {
5494 let mut names = Vec::new();
5495 declarator.target.bound_names(&mut names);
5496 out.extend(names.into_iter().map(|n| n.name));
5497 }
5498 }
5499 StmtKind::FuncDecl(func) => {
5500 if let Some(name) = &func.name {
5501 out.push(name.name.clone());
5502 }
5503 }
5504 StmtKind::ClassDecl(class) => {
5505 if let Some(name) = &class.name {
5506 out.push(name.name.clone());
5507 }
5508 }
5509 StmtKind::Import(decl) => {
5510 for specifier in &decl.specifiers {
5511 match specifier {
5512 ImportSpecifier::Default(id) => out.push(id.name.clone()),
5513 ImportSpecifier::Namespace(id) => out.push(id.name.clone()),
5514 ImportSpecifier::Named { local, .. } => out.push(local.name.clone()),
5515 }
5516 }
5517 }
5518 StmtKind::Export(decl) => match &decl.kind {
5519 ExportKind::Declaration(inner) => collect_module_binding(inner, out),
5520 ExportKind::Default(expr) => match &expr.unparen().kind {
5521 ExprKind::Function(func) => {
5522 if let Some(name) = &func.name {
5523 out.push(name.name.clone());
5524 }
5525 }
5526 ExprKind::Class(class) => {
5527 if let Some(name) = &class.name {
5528 out.push(name.name.clone());
5529 }
5530 }
5531 _ => {}
5532 },
5533 _ => {}
5534 },
5535 _ => {}
5536 }
5537}
5538
5539fn span_contains(outer: Span, inner: Span) -> bool {
5541 inner.start.offset >= outer.start.offset && inner.end.offset <= outer.end.offset
5542}
5543
5544fn is_property_key_start(kind: &TokenKind) -> bool {
5545 matches!(
5546 kind,
5547 TokenKind::Ident(_)
5548 | TokenKind::Keyword(_)
5549 | TokenKind::String(_)
5550 | TokenKind::Number(_)
5551 | TokenKind::Punct(Punct::LBracket)
5552 | TokenKind::Punct(Punct::Hash)
5553 )
5554}
5555
5556#[derive(Debug, Clone, Copy)]
5558enum BinOp {
5559 Binary(BinaryOp),
5560 Logical(LogicalOp),
5561}
5562
5563impl BinOp {
5564 fn is_right_associative(self) -> bool {
5565 matches!(self, BinOp::Binary(BinaryOp::Pow))
5566 }
5567}
5568
5569fn binary_operator(kind: &TokenKind, allow_in: bool) -> Option<(u8, BinOp)> {
5570 use BinaryOp as B;
5571 use LogicalOp as L;
5572 let result = match kind {
5573 TokenKind::Punct(Punct::QuestionQuestion) => (1, BinOp::Logical(L::Coalesce)),
5574 TokenKind::Punct(Punct::PipePipe) => (2, BinOp::Logical(L::Or)),
5575 TokenKind::Punct(Punct::AmpAmp) => (3, BinOp::Logical(L::And)),
5576 TokenKind::Punct(Punct::Pipe) => (4, BinOp::Binary(B::BitOr)),
5577 TokenKind::Punct(Punct::Caret) => (5, BinOp::Binary(B::BitXor)),
5578 TokenKind::Punct(Punct::Amp) => (6, BinOp::Binary(B::BitAnd)),
5579 TokenKind::Punct(Punct::EqEq) => (7, BinOp::Binary(B::Eq)),
5580 TokenKind::Punct(Punct::NotEq) => (7, BinOp::Binary(B::NotEq)),
5581 TokenKind::Punct(Punct::EqEqEq) => (7, BinOp::Binary(B::StrictEq)),
5582 TokenKind::Punct(Punct::NotEqEq) => (7, BinOp::Binary(B::StrictNotEq)),
5583 TokenKind::Punct(Punct::Lt) => (8, BinOp::Binary(B::Lt)),
5584 TokenKind::Punct(Punct::LtEq) => (8, BinOp::Binary(B::LtEq)),
5585 TokenKind::Punct(Punct::Gt) => (8, BinOp::Binary(B::Gt)),
5586 TokenKind::Punct(Punct::GtEq) => (8, BinOp::Binary(B::GtEq)),
5587 TokenKind::Keyword(Keyword::Instanceof) => (8, BinOp::Binary(B::Instanceof)),
5588 TokenKind::Keyword(Keyword::In) if allow_in => (8, BinOp::Binary(B::In)),
5589 TokenKind::Punct(Punct::Shl) => (9, BinOp::Binary(B::Shl)),
5590 TokenKind::Punct(Punct::Shr) => (9, BinOp::Binary(B::Shr)),
5591 TokenKind::Punct(Punct::UShr) => (9, BinOp::Binary(B::UShr)),
5592 TokenKind::Punct(Punct::Plus) => (10, BinOp::Binary(B::Add)),
5593 TokenKind::Punct(Punct::Minus) => (10, BinOp::Binary(B::Sub)),
5594 TokenKind::Punct(Punct::Star) => (11, BinOp::Binary(B::Mul)),
5595 TokenKind::Punct(Punct::Slash) => (11, BinOp::Binary(B::Div)),
5596 TokenKind::Punct(Punct::Percent) => (11, BinOp::Binary(B::Mod)),
5597 TokenKind::Punct(Punct::StarStar) => (12, BinOp::Binary(B::Pow)),
5598 _ => return None,
5599 };
5600 Some(result)
5601}
5602
5603fn build_binary(op: BinOp, left: Expr, right: Expr, span: Span, op_pos: Position) -> Result<Expr> {
5604 match op {
5605 BinOp::Binary(op) => Ok(Expr::at_operator(
5606 ExprKind::Binary {
5607 op,
5608 left: Box::new(left),
5609 right: Box::new(right),
5610 },
5611 span,
5612 op_pos,
5613 )),
5614 BinOp::Logical(op) => {
5615 let mixes = |expr: &Expr, op: LogicalOp| {
5619 matches!(&expr.kind, ExprKind::Logical { op: inner, .. }
5620 if (op == LogicalOp::Coalesce) != (*inner == LogicalOp::Coalesce))
5621 };
5622 if mixes(&left, op) || mixes(&right, op) {
5623 return Err(SyntaxError::new(
5624 "cannot mix ?? with && or ||",
5627 span,
5628 ));
5629 }
5630 Ok(Expr::at_operator(
5631 ExprKind::Logical {
5632 op,
5633 left: Box::new(left),
5634 right: Box::new(right),
5635 },
5636 span,
5637 op_pos,
5638 ))
5639 }
5640 }
5641}
5642
5643fn pattern_to_expr(pattern: Pattern, span: Span) -> Expr {
5646 match pattern.kind {
5647 PatternKind::Ident(ident) => Expr::new(ExprKind::Ident(ident), span),
5648 PatternKind::Assign { target, default } => Expr::new(
5649 ExprKind::Assign {
5650 op: AssignOp::Assign,
5651 target,
5652 value: default,
5653 },
5654 span,
5655 ),
5656 PatternKind::Member(member) => {
5660 let MemberPattern {
5661 object,
5662 property,
5663 span,
5664 op_pos,
5665 } = *member;
5666 Expr {
5667 kind: ExprKind::Member {
5668 object,
5669 property,
5670 optional: false,
5671 },
5672 span,
5673 op_pos,
5674 }
5675 }
5676 PatternKind::Object { properties, rest } => {
5677 let mut out = Vec::new();
5678 for element in properties {
5679 match element {
5680 Some(PatternElement::Property {
5681 key,
5682 value,
5683 shorthand,
5684 span: _,
5685 }) => {
5686 let span = value.span;
5687 out.push(ObjectProperty::Property {
5688 key,
5689 value: Box::new(pattern_to_expr(value, span)),
5690 kind: PropertyKind::Value,
5691 shorthand,
5692 span,
5693 });
5694 }
5695 None | Some(PatternElement::Pattern(_)) => {}
5698 }
5699 }
5700 if let Some(rest) = rest
5701 && let RestElement::Pattern(pattern) = *rest
5702 {
5703 let span = pattern.span;
5704 out.push(ObjectProperty::Spread(Box::new(pattern_to_expr(
5705 pattern, span,
5706 ))));
5707 }
5708 Expr::new(ExprKind::Object(out), span)
5709 }
5710 PatternKind::Array { elements, rest } => {
5711 let mut out = Vec::new();
5712 for element in elements {
5713 match element {
5714 Some(PatternElement::Pattern(pattern)) => {
5715 let span = pattern.span;
5716 out.push(Some(ArrayElement::Expr(Box::new(pattern_to_expr(
5717 pattern, span,
5718 )))));
5719 }
5720 Some(PatternElement::Property { .. }) | None => out.push(None),
5721 }
5722 }
5723 if let Some(rest) = rest {
5724 let RestElement::Pattern(pattern) = *rest else {
5725 return Expr::new(ExprKind::Null, span);
5726 };
5727 let span = pattern.span;
5728 out.push(Some(ArrayElement::Spread(Box::new(pattern_to_expr(
5729 pattern, span,
5730 )))));
5731 }
5732 Expr::new(ExprKind::Array { elements: out }, span)
5733 }
5734 _ => Expr::new(ExprKind::Null, span),
5735 }
5736}
5737
5738impl Pattern {
5739 fn unparen_kind(&self) -> &PatternKind {
5742 &self.kind
5743 }
5744}
5745
5746fn member_chain_import_call(expr: &Expr) -> Option<&Expr> {
5764 match &expr.kind {
5765 ExprKind::ImportCall(..) => Some(expr),
5766 ExprKind::Member { object, .. } => member_chain_import_call(object),
5767 _ => None,
5769 }
5770}
5771
5772fn deletes_a_private_member(expr: &Expr) -> bool {
5773 match &expr.unparen().kind {
5774 ExprKind::Member { property, .. } => matches!(property, MemberProp::Private(_)),
5775 ExprKind::Call { callee, .. } => deletes_a_private_member(callee),
5776 _ => false,
5777 }
5778}
5779
5780fn as_specifier(value: &Wtf8) -> String {
5787 value.to_string_lossy().into_owned()
5788}