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 scopes: Vec<Scope>,
427}
428
429pub fn parse_script(src: &str) -> Result<Program> {
431 Parser::new(src, false)?.parse_program()
432}
433
434pub fn parse_module(src: &str) -> Result<Program> {
436 Parser::new(src, true)?.parse_program()
437}
438
439pub fn parse_suspensible_script(src: &str) -> Result<Program> {
448 Parser::new_suspensible(src)?.parse_program()
449}
450
451pub fn parse_script_strict(src: &str) -> Result<Program> {
459 let mut parser = Parser::new(src, false)?;
460 parser.enter_strict()?;
461 parser.parse_program()
462}
463
464pub fn parse_eval_script(src: &str, strict: bool) -> Result<Program> {
471 parse_eval_script_in(src, strict, EvalContext::default())
472}
473
474#[derive(Debug, Clone, Default)]
476pub struct EvalContext {
477 pub in_method: bool,
480 pub in_derived_constructor: bool,
482 pub private_names: Vec<String>,
492 pub arguments_allowed: bool,
498 pub new_target_allowed: bool,
504}
505
506pub fn parse_eval_script_in(src: &str, strict: bool, context: EvalContext) -> Result<Program> {
512 let mut parser = Parser::new(src, false)?;
513 parser.ctx.in_function = context.new_target_allowed;
517 parser.ctx.in_method = context.in_method;
518 parser.ctx.in_derived_constructor = context.in_derived_constructor;
519 parser.ctx.arguments_allowed = context.arguments_allowed;
520 if !context.private_names.is_empty() {
524 parser
525 .private
526 .push(PrivateEnv::from_names(&context.private_names));
527 }
528 if strict {
529 parser.enter_strict()?;
530 }
531 parser.parse_program()
532}
533
534pub fn parse_suspensible_global_eval(src: &str, strict: bool) -> Result<Program> {
542 let mut parser = Parser::new_suspensible(src)?;
543 if strict {
544 parser.enter_strict()?;
545 }
546 parser.parse_program()
547}
548
549pub fn parse_expression(src: &str) -> Result<Expr> {
552 let mut parser = Parser::new(src, false)?;
553 let expr = parser.parse_expression(true)?;
554 if !parser.current.is_eof() {
555 return Err(parser.unexpected());
556 }
557 Ok(expr)
558}
559
560impl<'a> Parser<'a> {
561 pub fn new(src: &'a str, module: bool) -> Result<Parser<'a>> {
568 Parser::with_modes(src, module, false)
569 }
570
571 pub fn new_suspensible(src: &'a str) -> Result<Parser<'a>> {
578 Parser::with_modes(src, false, true)
579 }
580
581 fn with_modes(src: &'a str, module: bool, async_body: bool) -> Result<Parser<'a>> {
582 let mut lexer = Lexer::new(src);
583 lexer.set_strict(module);
584 let current = lexer.next_token()?;
585 let current_legacy_octal = lexer.had_legacy_octal();
586 if module && current_legacy_octal {
587 return Err(SyntaxError::new(
588 "octal literals and octal escape sequences are not allowed in strict mode",
589 current.span,
590 ));
591 }
592 Ok(Parser {
593 lexer,
594 current,
595 prev_end: Position::START,
596 strict: module,
597 module,
598 allow_in: true,
599 ctx: FnCtx {
600 in_async: module || async_body,
601 ..FnCtx::default()
602 },
603 loop_depth: 0,
604 switch_depth: 0,
605 labels: Vec::new(),
606 private: Vec::new(),
607 top_level: true,
608 current_legacy_octal,
609 in_case_clause: false,
610 depth: 0,
611 max_depth: DEFAULT_MAX_DEPTH,
612
613 cover_inits: Vec::new(),
614 spread_trailing_comma: Vec::new(),
615 pending_exports: Vec::new(),
616 in_formal_parameters: false,
617 scopes: vec![Scope::function(Vec::new())],
618 })
619 }
620
621 pub fn set_max_depth(&mut self, depth: u32) {
623 self.max_depth = depth;
624 }
625
626 fn enter(&mut self) -> Result<()> {
628 self.depth += 1;
629 if self.depth > self.max_depth {
630 return Err(SyntaxError::new("stack overflow", self.current.span));
631 }
632 Ok(())
633 }
634
635 fn leave(&mut self) {
636 self.depth -= 1;
637 }
638
639 pub fn parse_program(&mut self) -> Result<Program> {
641 let start = self.current.span.start;
642 let mut body = Vec::new();
643 let mut prologue = true;
644 while !self.current.is_eof() {
645 let stmt = self.parse_statement_list_item()?;
646 if prologue {
647 match self.directive_value(&stmt) {
648 Some(directive) if directive == "use strict" => self.enter_strict()?,
649 Some(_) => {}
650 None => prologue = false,
651 }
652 }
653 body.push(stmt);
654 }
655 if self.module {
656 self.check_module_exports(&body)?;
657 }
658 Ok(Program {
659 kind: if self.module {
660 ProgramKind::Module
661 } else {
662 ProgramKind::Script
663 },
664 body,
665 span: Span::new(start, self.prev_end),
666 strict: self.strict,
667 })
668 }
669
670 fn check_module_exports(&mut self, body: &[Stmt]) -> Result<()> {
673 if self.pending_exports.is_empty() {
674 return Ok(());
675 }
676 let mut declared: Vec<String> = Vec::new();
677 for stmt in body {
678 collect_module_binding(stmt, &mut declared);
679 }
680 let pending = std::mem::take(&mut self.pending_exports);
681 for (name, span) in pending {
682 if !declared.contains(&name) {
683 return Err(self
686 .error_at(format!("exported variable '{name}' does not exist"), span)
687 .positionless());
688 }
689 }
690 Ok(())
691 }
692
693 fn push_scope(&mut self, scope: Scope) {
696 self.scopes.push(scope);
697 }
698
699 fn pop_scope(&mut self) {
700 self.scopes.pop();
701 }
702
703 fn declare_lexical(&mut self, name: &str) -> Result<()> {
710 let Some(scope) = self.scopes.last() else {
711 return Ok(());
712 };
713 let reason = if scope.lex_names.iter().any(|n| n == name)
716 || scope.catch_names.iter().any(|n| n == name)
717 {
718 Some(Redefinition::Lexical)
719 } else if scope.params.iter().any(|n| n == name) {
720 Some(Redefinition::Parameter)
721 } else if scope.fn_names.iter().any(|n| n == name)
722 || scope.var_names.iter().any(|n| n == name)
723 {
724 Some(if self.at_top_level_scope() {
729 Redefinition::Global
730 } else {
731 Redefinition::Variable
732 })
733 } else {
734 None
735 };
736 if let Some(reason) = reason {
737 return Err(self.duplicate_declaration(reason));
738 }
739 if let Some(scope) = self.scopes.last_mut() {
740 scope.lex_names.push(name.to_string());
741 }
742 Ok(())
743 }
744
745 fn declare_var(&mut self, name: &str) -> Result<()> {
748 for scope in self.scopes.iter().rev() {
749 if scope.lex_names.iter().any(|n| n == name) {
750 return Err(self.duplicate_declaration(Redefinition::Lexical));
751 }
752 if scope.is_var_scope {
753 break;
754 }
755 }
756 let Some(index) = self.scopes.iter().rposition(|s| s.is_var_scope) else {
757 return Ok(());
758 };
759 for scope in &mut self.scopes[index..] {
762 if !scope.var_names.iter().any(|n| n == name) {
763 scope.var_names.push(name.to_string());
764 }
765 }
766 if let Some(scope) = self.scopes.last_mut()
767 && !scope.var_names_here.iter().any(|n| n == name)
768 {
769 scope.var_names_here.push(name.to_string());
770 }
771 Ok(())
772 }
773
774 fn check_duplicate_parameters(
795 &self,
796 params: &[Pattern],
797 plain_is_illegal: bool,
798 deferred_at: Span,
799 ) -> Result<()> {
800 let has_default = params.iter().any(pattern_has_default);
801 let mut seen: Vec<String> = Vec::new();
802 let mut deferred = false;
803 for param in params {
804 for (name, span, in_pattern) in parameter_bindings(param) {
805 if seen.iter().any(|seen| seen == &name) {
806 if has_default || in_pattern {
807 return Err(self.error_at(
808 "duplicate parameter names not allowed in this context".to_string(),
809 span,
810 ));
811 }
812 deferred = true;
813 }
814 seen.push(name);
815 }
816 }
817 if deferred && plain_is_illegal {
818 return Err(self.error_at(
819 "duplicate argument names not allowed in this context".to_string(),
820 deferred_at,
821 ));
822 }
823 Ok(())
824 }
825
826 fn declare_function(&mut self, name: &str) -> Result<()> {
842 if !self.scopes.last().is_none_or(|scope| scope.is_var_scope) {
843 return Ok(());
844 }
845 if !self.at_top_level_scope()
851 && self
852 .scopes
853 .last()
854 .is_some_and(|scope| scope.lex_names.iter().any(|n| n == name))
855 {
856 return Err(self.duplicate_declaration(Redefinition::Lexical));
857 }
858 if let Some(scope) = self.scopes.last_mut() {
859 if !scope.var_names.iter().any(|n| n == name) {
860 scope.var_names.push(name.to_string());
861 }
862 if !scope.fn_names.iter().any(|n| n == name) {
863 scope.fn_names.push(name.to_string());
864 }
865 }
866 Ok(())
867 }
868
869 fn declare_block_function(&mut self, name: &str, is_plain: bool) -> Result<()> {
878 if self.module
886 && self.at_top_level_scope()
887 && let Some(scope) = self.scopes.last()
888 {
889 let mut taken = scope.var_names_here.iter().any(|existing| existing == name);
895 if scope.is_var_scope {
896 let module_bindings = scope
897 .lex_names
898 .iter()
899 .filter(|existing| !scope.import_names.contains(existing))
900 .chain(&scope.fn_names);
901 taken |= module_bindings.into_iter().any(|existing| existing == name);
902 }
903 if taken {
904 return Err(self.error_at(
905 "invalid redefinition of global identifier in module code",
906 self.current.span,
907 ));
908 }
909 }
910 if self.scopes.last().is_none_or(|scope| scope.is_var_scope) {
911 return Ok(());
912 }
913 let Some(scope) = self.scopes.last() else {
914 return Ok(());
915 };
916 if scope.lex_names.iter().any(|n| n == name) || scope.catch_names.iter().any(|n| n == name)
917 {
918 let from_plain_function = scope.plain_fn_names.iter().any(|n| n == name);
922 if !(from_plain_function && is_plain && !self.strict) {
923 return Err(self.duplicate_declaration(Redefinition::Lexical));
924 }
925 } else if scope.var_names.iter().any(|n| n == name) {
926 let reason = if self.at_top_level_scope() {
930 Redefinition::Global
931 } else {
932 Redefinition::Variable
933 };
934 return Err(self.duplicate_declaration(reason));
935 }
936 if let Some(scope) = self.scopes.last_mut() {
937 if !scope.lex_names.iter().any(|n| n == name) {
938 scope.lex_names.push(name.to_string());
939 }
940 if !scope.fn_names.iter().any(|n| n == name) {
941 scope.fn_names.push(name.to_string());
942 }
943 if is_plain && !scope.plain_fn_names.iter().any(|n| n == name) {
944 scope.plain_fn_names.push(name.to_string());
945 }
946 }
947 Ok(())
948 }
949
950 fn duplicate_declaration(&self, reason: Redefinition) -> SyntaxError {
962 self.error_at(reason.message(), self.current.span)
963 }
964
965 fn at_top_level_scope(&self) -> bool {
971 self.scopes.iter().rposition(|scope| scope.is_var_scope) == Some(0)
972 }
973
974 fn declare_pattern(&mut self, pattern: &Pattern, is_var: bool) -> Result<()> {
976 let mut names = Vec::new();
977 pattern.bound_names(&mut names);
978 for name in names {
979 if is_var {
980 self.declare_var(&name.name)?;
981 } else {
982 self.declare_lexical(&name.name)?;
983 }
984 }
985 Ok(())
986 }
987
988 fn snapshot(&self) -> Snapshot<'a> {
991 Snapshot {
992 lexer: self.lexer.clone(),
993 current: self.current.clone(),
994 prev_end: self.prev_end,
995 strict: self.strict,
996 allow_in: self.allow_in,
997 ctx: self.ctx,
998 loop_depth: self.loop_depth,
999 switch_depth: self.switch_depth,
1000 labels: self.labels.clone(),
1001 private: self.private.clone(),
1002 top_level: self.top_level,
1003 cover_inits: self.cover_inits.clone(),
1004 spread_trailing_comma: self.spread_trailing_comma.clone(),
1005 pending_exports: self.pending_exports.clone(),
1006 current_legacy_octal: self.current_legacy_octal,
1007 scopes: self.scopes.clone(),
1008 }
1009 }
1010
1011 fn restore(&mut self, snap: Snapshot<'a>) {
1012 self.lexer = snap.lexer;
1013 self.current = snap.current;
1014 self.prev_end = snap.prev_end;
1015 self.strict = snap.strict;
1016 self.allow_in = snap.allow_in;
1017 self.ctx = snap.ctx;
1018 self.loop_depth = snap.loop_depth;
1019 self.switch_depth = snap.switch_depth;
1020 self.labels = snap.labels;
1021 self.private = snap.private;
1022 self.top_level = snap.top_level;
1023 self.cover_inits = snap.cover_inits;
1024 self.spread_trailing_comma = snap.spread_trailing_comma;
1025 self.pending_exports = snap.pending_exports;
1026 self.current_legacy_octal = snap.current_legacy_octal;
1027 self.scopes = snap.scopes;
1028 }
1029
1030 fn bump(&mut self) -> Result<()> {
1031 self.prev_end = self.current.span.end;
1032 self.current = self.lexer.next_token()?;
1033 self.current_legacy_octal = self.lexer.had_legacy_octal();
1034 if self.strict && self.current_legacy_octal {
1035 return Err(SyntaxError::new(
1036 "octal literals and octal escape sequences are not allowed in strict mode",
1037 self.current.span,
1038 ));
1039 }
1040 Ok(())
1041 }
1042
1043 fn peek(&self) -> Result<Token> {
1044 let mut lexer = self.lexer.clone();
1045 lexer.next_token()
1046 }
1047
1048 fn enter_strict(&mut self) -> Result<()> {
1049 self.strict = true;
1050 self.lexer.set_strict(true);
1051 if self.current_legacy_octal {
1054 return Err(SyntaxError::new(
1055 "octal literals and octal escape sequences are not allowed in strict mode",
1056 self.current.span,
1057 ));
1058 }
1059 Ok(())
1060 }
1061
1062 fn at_punct(&self, p: Punct) -> bool {
1063 matches!(&self.current.kind, TokenKind::Punct(q) if *q == p)
1064 }
1065
1066 fn at_keyword(&self, k: Keyword) -> bool {
1067 matches!(&self.current.kind, TokenKind::Keyword(q) if *q == k)
1068 }
1069
1070 fn at_contextual(&self, name: &str) -> bool {
1071 self.at_ident(name)
1072 }
1073
1074 fn at_ident(&self, name: &str) -> bool {
1081 !self.current.escaped && matches!(&self.current.kind, TokenKind::Ident(n) if n == name)
1082 }
1083
1084 fn eat_punct(&mut self, p: Punct) -> Result<bool> {
1085 if self.at_punct(p) {
1086 self.bump()?;
1087 return Ok(true);
1088 }
1089 Ok(false)
1090 }
1091
1092 fn expect_punct(&mut self, p: Punct) -> Result<()> {
1093 if self.eat_punct(p)? {
1094 Ok(())
1095 } else {
1096 Err(self.error(format!("expecting '{}'", p.as_str())))
1101 }
1102 }
1103
1104 fn eat_keyword(&mut self, k: Keyword) -> Result<bool> {
1105 if self.at_keyword(k) {
1106 self.bump()?;
1107 return Ok(true);
1108 }
1109 Ok(false)
1110 }
1111
1112 fn eat_contextual(&mut self, name: &str) -> Result<bool> {
1113 if self.at_ident(name) {
1114 self.bump()?;
1115 return Ok(true);
1116 }
1117 Ok(false)
1118 }
1119
1120 fn unexpected(&self) -> SyntaxError {
1127 let source = self.lexer.source();
1128 let start = self.current.span.start.offset as usize;
1129 let end = self.current.span.end.offset as usize;
1130 let text = source.get(start..end).unwrap_or("");
1131 SyntaxError::new(
1132 format!("unexpected token in expression: '{text}'"),
1133 self.current.span,
1134 )
1135 }
1136
1137 fn error(&self, message: impl Into<String>) -> SyntaxError {
1138 SyntaxError::new(message, self.current.span)
1139 }
1140
1141 fn error_at(&self, message: impl Into<String>, span: Span) -> SyntaxError {
1142 SyntaxError::new(message, span)
1143 }
1144
1145 fn span_from(&self, start: Position) -> Span {
1146 Span::new(start, self.prev_end)
1147 }
1148
1149 fn expect_binding_ident(&mut self) -> Result<Ident> {
1152 let ident = self.expect_ident()?;
1153 self.check_binding_name(&ident.name, ident.span)?;
1154 Ok(ident)
1155 }
1156
1157 fn expect_ident(&mut self) -> Result<Ident> {
1159 match self.current.kind.clone() {
1160 TokenKind::Ident(name) => {
1161 if name == "await" && self.await_is_reserved() {
1164 return Err(self.error("variable name expected"));
1165 }
1166 let span = self.current.span;
1167 self.check_identifier(&name, span)?;
1168 self.bump()?;
1169 Ok(Ident { name, span })
1170 }
1171 _ => Err(self.error("variable name expected")),
1174 }
1175 }
1176
1177 fn at_formal_parameter(&self) -> bool {
1184 if self.at_punct(Punct::LBracket) || self.at_punct(Punct::LBrace) {
1185 return true;
1186 }
1187 match &self.current.kind {
1188 TokenKind::Ident(name) => !(name == "await" && self.await_is_reserved()),
1189 _ => false,
1190 }
1191 }
1192
1193 fn await_is_reserved(&self) -> bool {
1203 self.ctx.in_async || self.module || self.ctx.in_static_block
1206 }
1207
1208 fn check_identifier(&self, name: &str, span: Span) -> Result<()> {
1210 if Keyword::lookup(name).is_some() {
1211 return Err(self.error_at(format!("unexpected keyword '{name}'"), span));
1212 }
1213 if self.strict && Keyword::is_strict_reserved(name) {
1214 return Err(self.error_at(
1215 format!("invalid use of strict mode reserved word '{name}'"),
1216 span,
1217 ));
1218 }
1219 if self.ctx.in_generator && name == "yield" {
1220 return Err(self.error_at(
1221 "invalid use of 'yield' identifier in a generator function",
1222 span,
1223 ));
1224 }
1225 if name == "await" && self.await_is_reserved() {
1226 return Err(self.error_at("unexpected 'await' keyword", span));
1231 }
1232 Ok(())
1233 }
1234
1235 fn check_arguments_reference(&self, name: &str, span: Span) -> Result<()> {
1242 if name == "arguments" && !self.ctx.arguments_allowed {
1243 return Err(self.error_at(
1244 "'arguments' identifier is not allowed in class field initializer",
1245 span,
1246 ));
1247 }
1248 Ok(())
1249 }
1250
1251 fn check_binding_name(&self, name: &str, span: Span) -> Result<()> {
1254 self.check_identifier(name, span)?;
1255 if self.strict && (name == "eval" || name == "arguments") {
1256 return Err(self.error_at("invalid variable name in strict mode", span));
1259 }
1260 if self.strict && name == "let" {
1261 return Err(self.error_at(
1262 "invalid use of 'let' as a variable name in strict mode",
1263 span,
1264 ));
1265 }
1266 Ok(())
1267 }
1268
1269 fn directive_value(&self, stmt: &Stmt) -> Option<String> {
1272 let StmtKind::Expr(expr) = &stmt.kind else {
1273 return None;
1274 };
1275 let ExprKind::String(value) = &expr.unparen().kind else {
1276 return None;
1277 };
1278 let raw = self.slice(expr.span);
1279 if !raw.starts_with('"') && !raw.starts_with('\'') {
1280 return None;
1281 }
1282 if raw.trim_matches(|c| c == '"' || c == '\'').contains('\\') {
1283 return None;
1284 }
1285 Some(value.to_string_lossy().into_owned())
1288 }
1289
1290 fn slice(&self, span: Span) -> &'a str {
1291 let src = self.lexer.source();
1292 let start = span.start.offset as usize;
1293 let end = (span.end.offset as usize).min(src.len());
1294 src.get(start..end).unwrap_or("")
1295 }
1296
1297 fn can_insert_semicolon(&self) -> bool {
1300 self.current.is_eof() || self.at_punct(Punct::RBrace) || self.current.newline_before
1301 }
1302
1303 fn semicolon(&mut self) -> Result<()> {
1304 if self.eat_punct(Punct::Semicolon)? {
1305 return Ok(());
1306 }
1307 if self.can_insert_semicolon() {
1308 return Ok(());
1309 }
1310 Err(self.error("expecting ';'"))
1313 }
1314
1315 fn parse_statement_list_item(&mut self) -> Result<Stmt> {
1318 self.enter()?;
1319 let result = self.parse_statement_list_item_guarded();
1320 self.leave();
1321 result
1322 }
1323
1324 fn parse_statement_list_item_guarded(&mut self) -> Result<Stmt> {
1325 let cover_mark = self.cover_inits.len();
1326 let stmt = self.parse_statement_list_item_inner()?;
1327 if self.cover_inits.len() > cover_mark {
1328 let span = self.cover_inits[cover_mark];
1329 self.cover_inits.truncate(cover_mark);
1330 return Err(self.error_at("expecting '}'", span));
1331 }
1332 Ok(stmt)
1333 }
1334
1335 fn parse_statement_list_item_inner(&mut self) -> Result<Stmt> {
1336 if self.at_keyword(Keyword::Function) {
1337 let start = self.current.span.start;
1338 let func = self.parse_function(FunctionForm::Declaration, false, None)?;
1339 if let Some(name) = &func.name {
1340 self.declare_function(&name.name)?;
1341 }
1342 return Ok(Stmt::new(
1343 StmtKind::FuncDecl(Box::new(func)),
1344 self.span_from(start),
1345 ));
1346 }
1347 if self.at_ident("async") {
1348 let peek = self.peek()?;
1349 if matches!(peek.kind, TokenKind::Keyword(Keyword::Function)) && !peek.newline_before {
1350 let start = self.current.span.start;
1351 self.bump()?; let func = self.parse_function(FunctionForm::Declaration, true, Some(start))?;
1353 if let Some(name) = &func.name {
1354 self.declare_function(&name.name)?;
1355 }
1356 return Ok(Stmt::new(
1357 StmtKind::FuncDecl(Box::new(func)),
1358 self.span_from(start),
1359 ));
1360 }
1361 }
1362 if self.at_keyword(Keyword::Class) {
1363 let start = self.current.span.start;
1364 let class = self.parse_class(false)?;
1365 if let Some(name) = &class.name {
1366 self.declare_lexical(&name.name)?;
1367 }
1368 return Ok(Stmt::new(
1369 StmtKind::ClassDecl(Box::new(class)),
1370 self.span_from(start),
1371 ));
1372 }
1373 if self.at_keyword(Keyword::Var) {
1374 let start = self.current.span.start;
1375 let decl = self.parse_var_decl(VarDeclKind::Var, false, true)?;
1376 self.semicolon()?;
1377 return Ok(Stmt::new(StmtKind::VarDecl(decl), self.span_from(start)));
1378 }
1379 if self.at_keyword(Keyword::Const) {
1380 let start = self.current.span.start;
1381 let decl = self.parse_var_decl(VarDeclKind::Const, false, true)?;
1382 self.semicolon()?;
1383 return Ok(Stmt::new(StmtKind::VarDecl(decl), self.span_from(start)));
1384 }
1385 if self.at_ident("let") && self.let_starts_declaration()? {
1386 let start = self.current.span.start;
1387 let decl = self.parse_var_decl(VarDeclKind::Let, false, true)?;
1388 self.semicolon()?;
1389 return Ok(Stmt::new(StmtKind::VarDecl(decl), self.span_from(start)));
1390 }
1391 if self.at_ident("await") && self.ctx.in_async && self.await_using_follows()? {
1394 let start = self.current.span.start;
1395 self.bump()?; let decl = self.parse_var_decl_with_keyword(VarDeclKind::AwaitUsing, "using")?;
1400 self.semicolon()?;
1401 return Ok(Stmt::new(StmtKind::VarDecl(decl), self.span_from(start)));
1402 }
1403 if self.at_ident("using") && self.using_starts_declaration()? {
1404 let start = self.current.span.start;
1405 if self.scopes.len() == 1 && !self.module {
1411 return Err(self.error_at(
1412 "using declaration is not allowed at the top level of a script",
1413 self.span_from(start),
1414 ));
1415 }
1416 if self.in_case_clause {
1421 return Err(self.error_at(
1422 "using declaration is not allowed in this context",
1423 self.span_from(start),
1424 ));
1425 }
1426 let decl = self.parse_var_decl(VarDeclKind::Using, false, true)?;
1427 self.semicolon()?;
1428 return Ok(Stmt::new(StmtKind::VarDecl(decl), self.span_from(start)));
1429 }
1430 let at_module_top_level = self.module && self.scopes.len() == 1;
1437 if at_module_top_level && self.at_keyword(Keyword::Import) {
1438 let peek = self.peek()?;
1439 if !matches!(
1441 peek.kind,
1442 TokenKind::Punct(Punct::LParen) | TokenKind::Punct(Punct::Dot)
1443 ) {
1444 return self.parse_import_decl();
1445 }
1446 }
1447 if at_module_top_level && self.at_keyword(Keyword::Export) {
1448 return self.parse_export_decl();
1449 }
1450 self.parse_statement()
1451 }
1452
1453 fn let_starts_declaration(&self) -> Result<bool> {
1455 let peek = self.peek()?;
1456 Ok(matches!(
1457 peek.kind,
1458 TokenKind::Ident(_)
1459 | TokenKind::Punct(Punct::LBracket)
1460 | TokenKind::Punct(Punct::LBrace)
1461 ))
1462 }
1463
1464 fn using_head_tail(&self, skip: usize) -> Result<Option<Token>> {
1470 let mut lexer = self.lexer.clone();
1471 let mut binding = None;
1475 for _ in 0..=skip {
1476 binding = Some(lexer.next_token()?);
1477 }
1478 let Some(binding) = binding else {
1479 return Ok(None);
1480 };
1481 if binding.newline_before || !matches!(binding.kind, TokenKind::Ident(_)) {
1482 return Ok(None);
1483 }
1484 Ok(Some(lexer.next_token()?))
1485 }
1486
1487 fn await_using_follows(&self) -> Result<bool> {
1493 Ok(matches!(
1494 self.using_head_tail(1)?.map(|token| token.kind),
1495 Some(TokenKind::Punct(Punct::Eq))
1496 ))
1497 }
1498
1499 fn using_starts_declaration(&self) -> Result<bool> {
1510 Ok(matches!(
1511 self.using_head_tail(0)?.map(|token| token.kind),
1512 Some(TokenKind::Punct(Punct::Eq))
1513 ))
1514 }
1515
1516 fn using_starts_for_head(&self) -> Result<bool> {
1521 Ok(matches!(
1522 self.using_head_tail(0)?.map(|token| token.kind),
1523 Some(TokenKind::Ident(name)) if name == "of" || name == "in"
1524 ))
1525 }
1526
1527 fn await_using_starts_for_head(&self) -> Result<bool> {
1529 Ok(matches!(
1530 self.using_head_tail(1)?.map(|token| token.kind),
1531 Some(TokenKind::Ident(name)) if name == "of" || name == "in"
1532 ))
1533 }
1534
1535 fn parse_statement(&mut self) -> Result<Stmt> {
1536 let start = self.current.span.start;
1537 if self.at_punct(Punct::Semicolon) {
1538 self.bump()?;
1539 return Ok(Stmt::new(StmtKind::Empty, self.span_from(start)));
1540 }
1541 if self.at_punct(Punct::LBrace) {
1542 let body = self.parse_block()?;
1543 return Ok(Stmt::new(StmtKind::Block(body), self.span_from(start)));
1544 }
1545 if self.at_keyword(Keyword::If) {
1546 return self.parse_if();
1547 }
1548 if self.at_keyword(Keyword::Do) {
1549 return self.parse_do_while();
1550 }
1551 if self.at_keyword(Keyword::While) {
1552 return self.parse_while();
1553 }
1554 if self.at_keyword(Keyword::For) {
1555 return self.parse_for();
1556 }
1557 if self.at_keyword(Keyword::Switch) {
1558 return self.parse_switch();
1559 }
1560 if self.at_keyword(Keyword::Try) {
1561 return self.parse_try();
1562 }
1563 if self.at_keyword(Keyword::Return) {
1564 return self.parse_return();
1565 }
1566 if self.at_keyword(Keyword::Throw) {
1567 return self.parse_throw();
1568 }
1569 if self.at_keyword(Keyword::Break) {
1570 return self.parse_break_continue(true);
1571 }
1572 if self.at_keyword(Keyword::Continue) {
1573 return self.parse_break_continue(false);
1574 }
1575 if self.at_keyword(Keyword::With) {
1576 return self.parse_with();
1577 }
1578 if self.at_keyword(Keyword::Debugger) {
1579 self.bump()?;
1580 self.semicolon()?;
1581 return Ok(Stmt::new(StmtKind::Debugger, self.span_from(start)));
1582 }
1583 if self.at_keyword(Keyword::Function) {
1584 if self.strict {
1587 return Err(
1588 self.error("invalid 'function' declaration in a single statement context")
1589 );
1590 }
1591 let func = self.parse_function(FunctionForm::Declaration, false, None)?;
1592 if let Some(name) = &func.name {
1593 self.declare_function(&name.name)?;
1594 }
1595 return Ok(Stmt::new(
1596 StmtKind::FuncDecl(Box::new(func)),
1597 self.span_from(start),
1598 ));
1599 }
1600 if self.at_keyword(Keyword::Class) {
1601 return Err(self.error("invalid 'class' declaration in a single statement context"));
1602 }
1603 if self.at_keyword(Keyword::Import) {
1604 let peek = self.peek()?;
1608 let expression = matches!(
1609 peek.kind,
1610 TokenKind::Punct(Punct::LParen) | TokenKind::Punct(Punct::Dot)
1611 );
1612 if !expression {
1613 return Err(self.error("'import' can only appear at the top level of a module"));
1614 }
1615 }
1616 if self.at_keyword(Keyword::Export) {
1617 return Err(self.error("'export' can only appear at the top level of a module"));
1618 }
1619 if let TokenKind::Ident(name) = &self.current.kind {
1621 if name == "await" && self.await_is_reserved() {
1625 if !self.ctx.in_async {
1626 let peek = self.peek()?;
1629 if matches!(peek.kind, TokenKind::Punct(Punct::Colon)) {
1630 return Err(self.error("unexpected 'await' keyword"));
1631 }
1632 }
1633 } else {
1637 let peek = self.peek()?;
1638 if matches!(peek.kind, TokenKind::Punct(Punct::Colon)) {
1639 return self.parse_labeled();
1640 }
1641 }
1642 }
1643 self.parse_expression_statement()
1644 }
1645
1646 fn parse_block(&mut self) -> Result<Vec<Stmt>> {
1647 self.expect_punct(Punct::LBrace)?;
1648 self.push_scope(Scope::block());
1649 let saved_in_case = self.in_case_clause;
1652 self.in_case_clause = false;
1653 let result = self.parse_block_body();
1654 self.in_case_clause = saved_in_case;
1655 self.pop_scope();
1656 let body = result?;
1657 self.bump()?; Ok(body)
1659 }
1660
1661 fn parse_catch_body(&mut self) -> Result<Vec<Stmt>> {
1663 self.expect_punct(Punct::LBrace)?;
1664 let body = self.parse_block_body()?;
1665 self.bump()?; Ok(body)
1667 }
1668
1669 fn parse_block_body(&mut self) -> Result<Vec<Stmt>> {
1670 let mut body = Vec::new();
1671 while !self.at_punct(Punct::RBrace) {
1672 if self.current.is_eof() {
1673 return Err(self.unexpected());
1674 }
1675 body.push(self.parse_statement_list_item()?);
1676 }
1677 Ok(body)
1678 }
1679
1680 fn parse_expression_statement(&mut self) -> Result<Stmt> {
1681 let start = self.current.span.start;
1682 let expr = self.parse_expression(true)?;
1683 self.semicolon()?;
1684 Ok(Stmt::new(
1685 StmtKind::Expr(Box::new(expr)),
1686 self.span_from(start),
1687 ))
1688 }
1689
1690 fn parse_if(&mut self) -> Result<Stmt> {
1691 let start = self.current.span.start;
1692 self.bump()?; self.expect_punct(Punct::LParen)?;
1694 let test = self.parse_expression(true)?;
1695 self.expect_punct(Punct::RParen)?;
1696 let cons = self.parse_statement()?;
1697 let alt = if self.eat_keyword(Keyword::Else)? {
1698 Some(Box::new(self.parse_statement()?))
1699 } else {
1700 None
1701 };
1702 Ok(Stmt::new(
1703 StmtKind::If {
1704 test: Box::new(test),
1705 cons: Box::new(cons),
1706 alt,
1707 },
1708 self.span_from(start),
1709 ))
1710 }
1711
1712 fn parse_do_while(&mut self) -> Result<Stmt> {
1713 let start = self.current.span.start;
1714 self.bump()?; self.loop_depth += 1;
1716 let body = self.parse_statement();
1717 self.loop_depth -= 1;
1718 let body = body?;
1719 if !self.eat_keyword(Keyword::While)? {
1720 return Err(self.unexpected());
1721 }
1722 self.expect_punct(Punct::LParen)?;
1723 let test = self.parse_expression(true)?;
1724 self.expect_punct(Punct::RParen)?;
1725 let _ = self.eat_punct(Punct::Semicolon)?;
1727 Ok(Stmt::new(
1728 StmtKind::DoWhile {
1729 body: Box::new(body),
1730 test: Box::new(test),
1731 },
1732 self.span_from(start),
1733 ))
1734 }
1735
1736 fn parse_while(&mut self) -> Result<Stmt> {
1737 let start = self.current.span.start;
1738 self.bump()?; self.expect_punct(Punct::LParen)?;
1740 let test = self.parse_expression(true)?;
1741 self.expect_punct(Punct::RParen)?;
1742 self.loop_depth += 1;
1743 let body = self.parse_statement();
1744 self.loop_depth -= 1;
1745 Ok(Stmt::new(
1746 StmtKind::While {
1747 test: Box::new(test),
1748 body: Box::new(body?),
1749 },
1750 self.span_from(start),
1751 ))
1752 }
1753
1754 fn parse_for(&mut self) -> Result<Stmt> {
1755 let start = self.current.span.start;
1756 self.bump()?; self.push_scope(Scope::block());
1758 let result = self.parse_for_inner(start);
1759 self.pop_scope();
1760 result
1761 }
1762
1763 fn parse_for_inner(&mut self, start: Position) -> Result<Stmt> {
1764 let mut is_await = false;
1765 if self.at_ident("await") && self.ctx.in_async {
1766 let peek = self.peek()?;
1767 if matches!(peek.kind, TokenKind::Punct(Punct::LParen)) && !peek.newline_before {
1768 is_await = true;
1769 self.bump()?;
1770 }
1771 }
1772 self.expect_punct(Punct::LParen)?;
1773
1774 if self.at_punct(Punct::Semicolon) {
1776 self.bump()?;
1777 return self.parse_for_classic(start, None);
1778 }
1779
1780 let decl_kind = if self.at_keyword(Keyword::Var) {
1782 Some(VarDeclKind::Var)
1783 } else if self.at_keyword(Keyword::Const) {
1784 Some(VarDeclKind::Const)
1785 } else if self.at_ident("let") && self.let_starts_declaration()? {
1786 Some(VarDeclKind::Let)
1787 } else if self.at_ident("using") && self.using_starts_for_head()? {
1788 Some(VarDeclKind::Using)
1789 } else if self.at_ident("await")
1790 && self.ctx.in_async
1791 && self.await_using_starts_for_head()?
1792 {
1793 self.bump()?; Some(VarDeclKind::AwaitUsing)
1795 } else {
1796 None
1797 };
1798 if let Some(kind) = decl_kind {
1799 let decl_start = self.current.span.start;
1800 let decl = self.parse_var_decl(kind, true, false)?;
1801 if self.at_for_head_keyword() {
1802 let is_of = self.at_contextual("of");
1803 if !is_of && decl.declarators.len() != 1 {
1804 return Err(self.error_at(
1805 "only one binding allowed in a for-in loop",
1806 self.span_from(decl_start),
1807 ));
1808 }
1809 if is_of && decl.declarators.len() != 1 {
1810 return Err(self.error_at(
1811 "only one binding allowed in a for-of loop",
1812 self.span_from(decl_start),
1813 ));
1814 }
1815 if let Some(declarator) = decl.declarators.first() {
1816 if declarator.init.is_some() {
1817 if is_of || kind.is_lexical() || self.strict {
1819 return Err(self.error_at(
1820 if is_of {
1821 "a declaration in the head of a for-of loop can't have an initializer"
1823 } else {
1824 "a declaration in the head of a for-in loop can't have an initializer"
1825 },
1826 declarator.span,
1827 ));
1828 }
1829 }
1830 }
1831 if is_await && !is_of {
1832 return Err(self.error("for await is only valid with 'of'"));
1833 }
1834 self.bump()?; let right = self.parse_expression(true)?;
1836 self.expect_punct(Punct::RParen)?;
1837 self.loop_depth += 1;
1838 let body = self.parse_statement();
1839 self.loop_depth -= 1;
1840 let head = ForHead::VarDecl(decl);
1841 let span = self.span_from(start);
1842 return Ok(Stmt::new(
1843 if is_of {
1844 StmtKind::ForOf {
1845 is_await,
1846 left: head,
1847 right: Box::new(right),
1848 body: Box::new(body?),
1849 }
1850 } else {
1851 StmtKind::ForIn {
1852 left: head,
1853 right: Box::new(right),
1854 body: Box::new(body?),
1855 }
1856 },
1857 span,
1858 ));
1859 }
1860 self.expect_punct(Punct::Semicolon)?;
1861 return self.parse_for_classic(start, Some(ForInit::VarDecl(decl)));
1862 }
1863
1864 let expr_start = self.current.span.start;
1866 let expr = self.parse_expression(false)?;
1867 if self.at_for_head_keyword() {
1868 let is_of = self.at_contextual("of");
1869 if is_await && !is_of {
1870 return Err(self.error("for await is only valid with 'of'"));
1871 }
1872 let target = self.expr_to_pattern(expr, TargetKind::Assignment)?;
1873 self.bump()?; let right = self.parse_expression(true)?;
1875 self.expect_punct(Punct::RParen)?;
1876 self.loop_depth += 1;
1877 let body = self.parse_statement();
1878 self.loop_depth -= 1;
1879 let head = ForHead::Assign(Box::new(target));
1880 let span = self.span_from(start);
1881 return Ok(Stmt::new(
1882 if is_of {
1883 StmtKind::ForOf {
1884 is_await,
1885 left: head,
1886 right: Box::new(right),
1887 body: Box::new(body?),
1888 }
1889 } else {
1890 StmtKind::ForIn {
1891 left: head,
1892 right: Box::new(right),
1893 body: Box::new(body?),
1894 }
1895 },
1896 span,
1897 ));
1898 }
1899 let _ = expr_start;
1900 self.expect_punct(Punct::Semicolon)?;
1901 self.parse_for_classic(start, Some(ForInit::Expr(Box::new(expr))))
1902 }
1903
1904 fn at_for_head_keyword(&self) -> bool {
1907 self.at_keyword(Keyword::In) || self.at_contextual("of")
1908 }
1909
1910 fn parse_for_classic(&mut self, start: Position, init: Option<ForInit>) -> Result<Stmt> {
1911 let test = if self.at_punct(Punct::Semicolon) {
1912 None
1913 } else {
1914 Some(Box::new(self.parse_expression(true)?))
1915 };
1916 self.expect_punct(Punct::Semicolon)?;
1917 let update = if self.at_punct(Punct::RParen) {
1918 None
1919 } else {
1920 Some(Box::new(self.parse_expression(true)?))
1921 };
1922 self.expect_punct(Punct::RParen)?;
1923 self.loop_depth += 1;
1924 let body = self.parse_statement();
1925 self.loop_depth -= 1;
1926 Ok(Stmt::new(
1927 StmtKind::For {
1928 init,
1929 test,
1930 update,
1931 body: Box::new(body?),
1932 },
1933 self.span_from(start),
1934 ))
1935 }
1936
1937 fn parse_switch(&mut self) -> Result<Stmt> {
1938 let start = self.current.span.start;
1939 self.bump()?; self.expect_punct(Punct::LParen)?;
1941 let discriminant = self.parse_expression(true)?;
1942 self.expect_punct(Punct::RParen)?;
1943 self.expect_punct(Punct::LBrace)?;
1944 self.switch_depth += 1;
1945 self.push_scope(Scope::block());
1946 let mut cases = Vec::new();
1947 let mut seen_default = false;
1948 while !self.at_punct(Punct::RBrace) {
1949 if self.current.is_eof() {
1950 self.switch_depth -= 1;
1951 return Err(self.unexpected());
1952 }
1953 let case_start = self.current.span.start;
1954 let test = if self.eat_keyword(Keyword::Case)? {
1955 Some(Box::new(self.parse_expression(true)?))
1956 } else if self.eat_keyword(Keyword::Default)? {
1957 if seen_default {
1958 self.switch_depth -= 1;
1959 return Err(self.error("duplicate 'default' clause in switch statement"));
1960 }
1961 seen_default = true;
1962 None
1963 } else {
1964 self.switch_depth -= 1;
1965 return Err(self.unexpected());
1966 };
1967 self.expect_punct(Punct::Colon)?;
1968 let mut body = Vec::new();
1969 let saved_in_case = self.in_case_clause;
1970 self.in_case_clause = true;
1971 while !self.at_punct(Punct::RBrace)
1972 && !self.at_keyword(Keyword::Case)
1973 && !self.at_keyword(Keyword::Default)
1974 {
1975 if self.current.is_eof() {
1976 self.in_case_clause = saved_in_case;
1977 self.switch_depth -= 1;
1978 return Err(self.unexpected());
1979 }
1980 match self.parse_statement_list_item() {
1981 Ok(stmt) => body.push(stmt),
1982 Err(error) => {
1983 self.in_case_clause = saved_in_case;
1984 self.switch_depth -= 1;
1985 return Err(error);
1986 }
1987 }
1988 }
1989 self.in_case_clause = saved_in_case;
1990 cases.push(SwitchCase {
1991 test,
1992 body,
1993 span: self.span_from(case_start),
1994 });
1995 }
1996 self.switch_depth -= 1;
1997 self.bump()?; self.pop_scope();
2006 Ok(Stmt::new(
2007 StmtKind::Switch {
2008 discriminant: Box::new(discriminant),
2009 cases,
2010 },
2011 self.span_from(start),
2012 ))
2013 }
2014
2015 fn parse_try(&mut self) -> Result<Stmt> {
2016 let start = self.current.span.start;
2017 self.bump()?; let block = self.parse_block()?;
2019 let mut handler = None;
2020 let mut finalizer = None;
2021 if self.at_keyword(Keyword::Catch) {
2022 let catch_start = self.current.span.start;
2023 self.bump()?;
2024 let param = if self.eat_punct(Punct::LParen)? {
2030 let pattern = self.parse_binding_target()?;
2031 self.expect_punct(Punct::RParen)?;
2032 Some(pattern)
2033 } else {
2034 None
2035 };
2036 self.push_scope(Scope::block());
2037 let body = match ¶m {
2038 Some(Pattern {
2041 kind: PatternKind::Ident(id),
2042 ..
2043 }) => {
2044 if let Some(scope) = self.scopes.last_mut() {
2045 scope.catch_names.push(id.name.clone());
2046 }
2047 self.parse_catch_body()
2048 }
2049 Some(pattern) => {
2054 self.declare_pattern(pattern, false)?;
2055 self.parse_block()
2056 }
2057 None => self.parse_catch_body(),
2058 };
2059 self.pop_scope();
2060 let body = body?;
2061 handler = Some(CatchClause {
2062 param,
2063 body,
2064 span: self.span_from(catch_start),
2065 });
2066 }
2067 if self.eat_keyword(Keyword::Finally)? {
2068 finalizer = Some(self.parse_block()?);
2069 }
2070 if handler.is_none() && finalizer.is_none() {
2071 return Err(self.error("expecting catch or finally"));
2072 }
2073 Ok(Stmt::new(
2074 StmtKind::Try {
2075 block,
2076 handler,
2077 finalizer,
2078 },
2079 self.span_from(start),
2080 ))
2081 }
2082
2083 fn parse_return(&mut self) -> Result<Stmt> {
2084 let start = self.current.span.start;
2085 let span = self.current.span;
2086 if !self.ctx.in_function {
2087 return Err(self.error_at("return not in a function", span));
2088 }
2089 if self.ctx.in_static_block {
2090 return Err(self.error_at("return in a static initializer block", span));
2094 }
2095 self.bump()?;
2096 let argument = if self.at_punct(Punct::Semicolon)
2097 || self.at_punct(Punct::RBrace)
2098 || self.current.is_eof()
2099 || self.current.newline_before
2100 {
2101 None
2102 } else {
2103 Some(Box::new(self.parse_expression(true)?))
2104 };
2105 self.semicolon()?;
2106 Ok(Stmt::new(StmtKind::Return(argument), self.span_from(start)))
2107 }
2108
2109 fn parse_throw(&mut self) -> Result<Stmt> {
2110 let start = self.current.span.start;
2111 self.bump()?; if self.current.newline_before {
2113 return Err(self.error("line terminator not allowed after 'throw'"));
2114 }
2115 let argument = self.parse_expression(true)?;
2116 self.semicolon()?;
2117 Ok(Stmt::new(
2118 StmtKind::Throw(Box::new(argument)),
2119 self.span_from(start),
2120 ))
2121 }
2122
2123 fn parse_break_continue(&mut self, is_break: bool) -> Result<Stmt> {
2124 let start = self.current.span.start;
2125 let keyword_span = self.current.span;
2126 self.bump()?;
2127 let label = if matches!(self.current.kind, TokenKind::Ident(_))
2128 && !self.current.newline_before
2129 {
2130 let ident = self.expect_ident()?;
2131 let found = self.labels.iter().rev().find(|l| l.name == ident.name);
2132 match found {
2133 None => {
2134 return Err(
2135 self.error_at(format!("label '{}' not found", ident.name), ident.span)
2136 );
2137 }
2138 Some(label) => {
2139 if !is_break && label.kind != LabelKind::Iteration {
2140 return Err(self.error_at(
2141 format!("continue must be inside loop (label '{}')", ident.name),
2142 ident.span,
2143 ));
2144 }
2145 }
2146 }
2147 Some(ident)
2148 } else {
2149 if !is_break && self.loop_depth == 0 {
2150 return Err(self.error_at("continue must be inside loop", keyword_span));
2151 }
2152 if is_break && self.loop_depth == 0 && self.switch_depth == 0 && self.labels.is_empty()
2153 {
2154 return Err(self.error_at("break must be inside loop or switch", keyword_span));
2155 }
2156 None
2157 };
2158 self.semicolon()?;
2159 Ok(Stmt::new(
2160 if is_break {
2161 StmtKind::Break(label)
2162 } else {
2163 StmtKind::Continue(label)
2164 },
2165 self.span_from(start),
2166 ))
2167 }
2168
2169 fn parse_with(&mut self) -> Result<Stmt> {
2170 let start = self.current.span.start;
2171 let span = self.current.span;
2172 if self.strict {
2173 return Err(self.error_at("invalid keyword: with", span));
2174 }
2175 self.bump()?; self.expect_punct(Punct::LParen)?;
2177 let object = self.parse_expression(true)?;
2178 self.expect_punct(Punct::RParen)?;
2179 let body = self.parse_statement()?;
2180 Ok(Stmt::new(
2181 StmtKind::With {
2182 object: Box::new(object),
2183 body: Box::new(body),
2184 },
2185 self.span_from(start),
2186 ))
2187 }
2188
2189 fn parse_labeled(&mut self) -> Result<Stmt> {
2190 let start = self.current.span.start;
2191 let label = self.expect_ident()?;
2192 self.expect_punct(Punct::Colon)?;
2193 if self.labels.iter().any(|l| l.name == label.name) {
2194 return Err(self.error_at(
2195 format!("label '{}' already declared", label.name),
2196 label.span,
2197 ));
2198 }
2199 let kind = if self.at_keyword(Keyword::For)
2200 || self.at_keyword(Keyword::While)
2201 || self.at_keyword(Keyword::Do)
2202 {
2203 LabelKind::Iteration
2204 } else {
2205 LabelKind::Other
2206 };
2207 self.labels.push(Label {
2208 name: label.name.clone(),
2209 kind,
2210 });
2211 let body = self.parse_statement();
2212 self.labels.pop();
2213 Ok(Stmt::new(
2214 StmtKind::Labeled {
2215 label,
2216 body: Box::new(body?),
2217 },
2218 self.span_from(start),
2219 ))
2220 }
2221
2222 fn parse_var_decl(
2225 &mut self,
2226 kind: VarDeclKind,
2227 in_for_head: bool,
2228 require_init: bool,
2229 ) -> Result<VarDecl> {
2230 let start = self.current.span.start;
2231 self.bump()?; self.parse_var_declarators(kind, in_for_head, require_init, start)
2233 }
2234
2235 fn parse_var_decl_with_keyword(&mut self, kind: VarDeclKind, keyword: &str) -> Result<VarDecl> {
2240 let start = self.current.span.start;
2241 if !self.at_ident(keyword) {
2242 return Err(self.error(format!("expected '{keyword}'")));
2243 }
2244 self.bump()?;
2245 self.parse_var_declarators(kind, false, true, start)
2246 }
2247
2248 fn parse_var_declarators(
2249 &mut self,
2250 kind: VarDeclKind,
2251 in_for_head: bool,
2252 require_init: bool,
2253 start: Position,
2254 ) -> Result<VarDecl> {
2255 let mut declarators = Vec::new();
2256 loop {
2257 let declarator_start = self.current.span.start;
2258 let target = self.parse_binding_target()?;
2259 self.declare_pattern(&target, !kind.is_lexical())?;
2264 if kind.is_using() && !matches!(target.unparen_kind(), PatternKind::Ident(_)) {
2267 return Err(self.error_at(
2268 "binding patterns are not allowed in using declarations",
2269 target.span,
2270 ));
2271 }
2272 let init = if self.eat_punct(Punct::Eq)? {
2273 Some(Box::new(self.parse_assignment(!in_for_head)?))
2276 } else {
2277 None
2278 };
2279 if init.is_none() && require_init {
2280 if kind == VarDeclKind::Const {
2281 return Err(self.error("missing initializer for const variable"));
2282 }
2283 if kind.is_using() {
2284 return Err(self.error("missing initializer in using declaration"));
2285 }
2286 if !matches!(target.unparen_kind(), PatternKind::Ident(_)) && !in_for_head {
2287 return Err(self.error_at(
2288 "missing initializer in destructuring declaration",
2289 target.span,
2290 ));
2291 }
2292 }
2293 if kind.is_lexical() {
2294 let mut names = Vec::new();
2295 target.bound_names(&mut names);
2296 if let Some(name) = names.iter().find(|n| n.name == "let") {
2297 return Err(self.error_at("'let' is not a valid lexical identifier", name.span));
2298 }
2299 }
2300 declarators.push(Declarator {
2301 target,
2302 init,
2303 span: self.span_from(declarator_start),
2304 });
2305 if !self.eat_punct(Punct::Comma)? {
2306 break;
2307 }
2308 }
2309 Ok(VarDecl {
2310 kind,
2311 declarators,
2312 span: self.span_from(start),
2313 })
2314 }
2315
2316 fn parse_binding_element(&mut self) -> Result<Pattern> {
2319 let pattern = self.parse_binding_target()?;
2320 if self.eat_punct(Punct::Eq)? {
2321 let start = pattern.span.start;
2322 let default = self.parse_assignment(self.allow_in)?;
2323 return Ok(Pattern::new(
2324 PatternKind::Assign {
2325 target: Box::new(pattern),
2326 default: Box::new(default),
2327 },
2328 self.span_from(start),
2329 ));
2330 }
2331 Ok(pattern)
2332 }
2333
2334 fn parse_binding_target(&mut self) -> Result<Pattern> {
2337 self.enter()?;
2338 let result = self.parse_binding_target_unguarded();
2339 self.leave();
2340 result
2341 }
2342
2343 fn parse_binding_target_unguarded(&mut self) -> Result<Pattern> {
2344 let start = self.current.span.start;
2345 if self.at_punct(Punct::LBracket) {
2346 return self.parse_array_pattern(start);
2347 }
2348 if self.at_punct(Punct::LBrace) {
2349 return self.parse_object_pattern(start);
2350 }
2351 let ident = self.expect_binding_ident()?;
2352 Ok(Pattern::new(
2353 PatternKind::Ident(ident),
2354 self.span_from(start),
2355 ))
2356 }
2357
2358 fn parse_array_pattern(&mut self, start: Position) -> Result<Pattern> {
2359 self.expect_punct(Punct::LBracket)?;
2360 let mut elements = Vec::new();
2361 let mut rest = None;
2362 loop {
2363 if self.at_punct(Punct::RBracket) {
2364 break;
2365 }
2366 if self.at_punct(Punct::Comma) {
2367 self.bump()?;
2368 elements.push(None);
2369 continue;
2370 }
2371 if self.at_punct(Punct::Ellipsis) {
2372 self.bump()?;
2373 let target = self.parse_binding_target()?;
2374 if self.at_punct(Punct::Comma) {
2375 return Err(self.error("rest element must be the last one"));
2376 }
2377 rest = Some(Box::new(RestElement::Pattern(target)));
2378 break;
2379 }
2380 let element_start = self.current.span.start;
2381 let element = self.parse_binding_element()?;
2382 let span = self.span_from(element_start);
2383 elements.push(Some(PatternElement::Pattern(element)));
2384 let _ = span;
2385 if !self.eat_punct(Punct::Comma)? {
2386 break;
2387 }
2388 }
2389 self.expect_punct(Punct::RBracket)?;
2390 Ok(Pattern::new(
2391 PatternKind::Array { elements, rest },
2392 self.span_from(start),
2393 ))
2394 }
2395
2396 fn parse_object_pattern(&mut self, start: Position) -> Result<Pattern> {
2397 self.expect_punct(Punct::LBrace)?;
2398 let mut properties = Vec::new();
2399 let mut rest = None;
2400 loop {
2401 if self.at_punct(Punct::RBrace) {
2402 break;
2403 }
2404 if self.at_punct(Punct::Ellipsis) {
2405 self.bump()?;
2406 let target = self.parse_binding_target()?;
2407 rest = Some(Box::new(RestElement::Pattern(target)));
2408 if self.at_punct(Punct::Comma) {
2409 return Err(self.error("rest element must be the last one"));
2410 }
2411 break;
2412 }
2413 let property_start = self.current.span.start;
2414 let key = self.parse_property_key()?;
2415 if self.eat_punct(Punct::Colon)? {
2416 let value = self.parse_binding_element()?;
2417 properties.push(Some(PatternElement::Property {
2418 key,
2419 value,
2420 shorthand: false,
2421 span: self.span_from(property_start),
2422 }));
2423 } else {
2424 let PropName::Literal(PropKey::Str(name)) = &key else {
2425 return Err(
2426 self.error("expecting ':' after a computed or numeric property key")
2427 );
2428 };
2429 let span = self.span_from(property_start);
2430 let ident = Ident {
2431 name: name.to_string_lossy().into_owned(),
2432 span,
2433 };
2434 self.check_binding_name(&ident.name, ident.span)?;
2435 let mut value = Pattern::new(PatternKind::Ident(ident), span);
2436 if self.eat_punct(Punct::Eq)? {
2437 let default = self.parse_assignment(self.allow_in)?;
2438 value = Pattern::new(
2439 PatternKind::Assign {
2440 target: Box::new(value),
2441 default: Box::new(default),
2442 },
2443 span,
2444 );
2445 }
2446 properties.push(Some(PatternElement::Property {
2447 key,
2448 value,
2449 shorthand: true,
2450 span,
2451 }));
2452 }
2453 if !self.eat_punct(Punct::Comma)? {
2454 break;
2455 }
2456 }
2457 self.expect_punct(Punct::RBrace)?;
2458 Ok(Pattern::new(
2459 PatternKind::Object { properties, rest },
2460 self.span_from(start),
2461 ))
2462 }
2463
2464 fn parse_property_key(&mut self) -> Result<PropName> {
2466 match self.current.kind.clone() {
2467 TokenKind::Ident(name) => {
2468 self.bump()?;
2469 Ok(PropName::Literal(PropKey::Str(Wtf8::new(name))))
2470 }
2471 TokenKind::Keyword(kw) => {
2472 self.bump()?;
2474 Ok(PropName::Literal(PropKey::Str(Wtf8::new(kw.as_str()))))
2475 }
2476 TokenKind::String(value) => {
2477 self.bump()?;
2478 Ok(PropName::Literal(PropKey::Str(value)))
2479 }
2480 TokenKind::Number(NumberLiteral::Int(v)) => {
2481 self.bump()?;
2482 Ok(PropName::Literal(PropKey::Num(v as f64)))
2483 }
2484 TokenKind::Number(NumberLiteral::Float(v)) => {
2485 self.bump()?;
2486 Ok(PropName::Literal(PropKey::Num(v)))
2487 }
2488 TokenKind::BigInt(big) => Err(self.error(format!(
2489 "BigInt property keys are not supported ('{}n')",
2490 big.digits
2491 ))),
2492 TokenKind::Punct(Punct::LBracket) => {
2493 self.bump()?;
2494 let expr = self.parse_assignment(true)?;
2495 self.expect_punct(Punct::RBracket)?;
2496 Ok(PropName::Computed(Box::new(expr)))
2497 }
2498 TokenKind::Punct(Punct::Hash) => {
2499 let ident = self.parse_private_name()?;
2500 Ok(PropName::Private(ident))
2501 }
2502 _ => Err(self.error("invalid property name")),
2505 }
2506 }
2507
2508 fn parse_function(
2518 &mut self,
2519 form: FunctionForm,
2520 is_async: bool,
2521 start: Option<Position>,
2522 ) -> Result<Function> {
2523 let start = start.unwrap_or(self.current.span.start);
2524 self.bump()?; let is_generator = self.eat_punct(Punct::Star)?;
2526 let name = if matches!(self.current.kind, TokenKind::Ident(_)) {
2527 let ident = if form == FunctionForm::Declaration {
2528 self.expect_binding_ident()?
2529 } else {
2530 self.expect_ident()?
2531 };
2532 if is_generator && ident.name == "yield" {
2533 return Err(self.error_at("invalid use of 'yield' as a function name", ident.span));
2534 }
2535 if is_async && ident.name == "await" {
2536 return Err(self.error_at("invalid use of 'await' as a function name", ident.span));
2537 }
2538 Some(ident)
2539 } else {
2540 if form == FunctionForm::Declaration {
2541 return Err(self.error("function name expected"));
2542 }
2543 None
2544 };
2545 if form == FunctionForm::Declaration
2555 && let Some(ident) = &name
2556 {
2557 self.declare_block_function(&ident.name, !is_async && !is_generator)?;
2558 }
2559 let saved = self.ctx;
2560 self.ctx = FnCtx {
2561 in_function: true,
2562 in_generator: is_generator,
2563 in_async: is_async,
2564 in_method: false,
2565 in_derived_constructor: false,
2566 in_static_block: false,
2567 arguments_allowed: true,
2568 };
2569 let saved_top = self.top_level;
2570 self.top_level = false;
2571 let params_result = self.parse_formal_parameters();
2577 let result = match params_result {
2578 Ok(params) => self.parse_function_body(params, false),
2579 Err(err) => Err(err),
2580 };
2581 self.ctx = saved;
2582 self.top_level = saved_top;
2583 let (params, params_span, body, strict) = result?;
2584 Ok(Function {
2585 name,
2586 params,
2587 body,
2588 is_async,
2589 is_generator,
2590 strict,
2591 is_arrow: false,
2592 span: self.span_from(start),
2593 params_span,
2594 source_span: None,
2595 })
2596 }
2597
2598 fn parse_formal_parameters(&mut self) -> Result<Vec<Pattern>> {
2599 let saved = self.in_formal_parameters;
2604 self.in_formal_parameters = true;
2605 let result = self.parse_formal_parameters_inner();
2606 self.in_formal_parameters = saved;
2607 result
2608 }
2609
2610 fn parse_formal_parameters_inner(&mut self) -> Result<Vec<Pattern>> {
2611 self.expect_punct(Punct::LParen)?;
2612 let mut params = Vec::new();
2613 loop {
2614 if self.at_punct(Punct::RParen) {
2615 break;
2616 }
2617 if self.at_punct(Punct::Ellipsis) {
2618 self.bump()?;
2619 if !self.at_formal_parameter() {
2622 return Err(self.error("missing formal parameter"));
2623 }
2624 let target = self.parse_binding_target()?;
2625 if matches!(target.unparen_kind(), PatternKind::Assign { .. }) {
2626 return Err(
2627 self.error_at("rest element cannot have a default value", target.span)
2628 );
2629 }
2630 params.push(Pattern::new(
2631 PatternKind::Rest(Box::new(target.clone())),
2632 target.span,
2633 ));
2634 if self.at_punct(Punct::Comma) {
2637 return Err(self.error("expecting ')'"));
2638 }
2639 break;
2640 }
2641 if !self.at_formal_parameter() {
2642 return Err(self.error("missing formal parameter"));
2643 }
2644 let param = self.parse_binding_element()?;
2645 self.check_parameter(¶m)?;
2646 params.push(param);
2647 if !self.eat_punct(Punct::Comma)? {
2648 break;
2649 }
2650 }
2651 self.expect_punct(Punct::RParen)?;
2652 Ok(params)
2653 }
2654
2655 fn check_parameter(&self, param: &Pattern) -> Result<()> {
2656 match ¶m.kind {
2657 PatternKind::Ident(ident) => self.check_binding_name(&ident.name, ident.span),
2658 PatternKind::Assign { target, .. } => self.check_parameter(target),
2659 _ => Ok(()),
2660 }
2661 }
2662
2663 fn parse_function_body(
2664 &mut self,
2665 params: Vec<Pattern>,
2666 is_method: bool,
2667 ) -> Result<(Vec<Pattern>, Span, FunctionBody, bool)> {
2668 let params_span = self.prev_end;
2669 let saved_strict = self.strict;
2674 if !self.at_punct(Punct::LBrace) {
2675 return Err(self.unexpected());
2676 }
2677 let saved_in_case = self.in_case_clause;
2680 self.in_case_clause = false;
2681 let param_names = simple_parameter_names(¶ms);
2682 let simple_params = params
2683 .iter()
2684 .all(|p| matches!(p.unparen_kind(), PatternKind::Ident(_)));
2685 let mut body = Vec::new();
2686 let mut prologue = true;
2687 let mut strict_seen = false;
2688 self.bump()?; let body_start = self.current.span;
2693 self.push_scope(Scope::function(param_names));
2694 while !self.at_punct(Punct::RBrace) {
2695 if self.current.is_eof() {
2696 return Err(self.unexpected());
2697 }
2698 let stmt = self.parse_statement_list_item()?;
2699 if prologue {
2700 match self.directive_value(&stmt) {
2701 Some(directive) if directive == "use strict" => {
2702 strict_seen = true;
2703 self.enter_strict()?;
2704 }
2705 Some(_) => {}
2706 None => prologue = false,
2707 }
2708 }
2709 body.push(stmt);
2710 }
2711 self.pop_scope();
2712 self.bump()?; let body_strict = self.strict;
2716 if strict_seen && !simple_params {
2717 return Err(self.error_at(
2718 "\"use strict\" not allowed in function with default or destructuring parameter",
2720 Span::new(params_span, params_span),
2721 ));
2722 }
2723 self.check_duplicate_parameters(
2734 ¶ms,
2735 body_strict || !simple_params || is_method,
2736 body_start,
2737 )?;
2738 if body_strict && !saved_strict {
2744 for param in ¶ms {
2745 let mut names = Vec::new();
2746 param.bound_names(&mut names);
2747 for name in names {
2748 if name.name == "eval" || name.name == "arguments" || name.name == "let" {
2749 return Err(
2750 self.error_at("invalid variable name in strict mode", name.span)
2751 );
2752 }
2753 }
2754 }
2755 }
2756 let params_span_value = Span::new(params_span, params_span);
2757 self.strict = saved_strict;
2758 self.lexer.set_strict(saved_strict);
2759 self.in_case_clause = saved_in_case;
2760 Ok((
2761 params,
2762 params_span_value,
2763 FunctionBody::Block(body),
2764 body_strict,
2765 ))
2766 }
2767
2768 fn parse_class(&mut self, is_expression: bool) -> Result<Class> {
2771 let saved_strict = self.strict;
2779 let enter = self.enter_strict();
2780 let result = match enter {
2781 Ok(()) => self.parse_class_body(is_expression),
2782 Err(error) => Err(error),
2783 };
2784 self.strict = saved_strict;
2785 self.lexer.set_strict(saved_strict);
2786 result
2787 }
2788
2789 fn parse_class_body(&mut self, is_expression: bool) -> Result<Class> {
2790 let start = self.current.span.start;
2791 self.bump()?; let name = if matches!(self.current.kind, TokenKind::Ident(_)) {
2793 if is_expression {
2794 Some(self.expect_ident()?)
2795 } else {
2796 Some(self.expect_binding_ident()?)
2797 }
2798 } else {
2799 if !is_expression {
2800 return Err(self.error("class statement requires a name"));
2801 }
2802 None
2803 };
2804 let super_class = if self.eat_keyword(Keyword::Extends)? {
2805 Some(Box::new(self.parse_lhs_expression()?))
2806 } else {
2807 None
2808 };
2809 let has_super = super_class.is_some();
2810 self.private.push(PrivateEnv::default());
2811 self.expect_punct(Punct::LBrace)?;
2812 let mut elements = Vec::new();
2813 let mut seen_constructor = false;
2814 let result = (|| -> Result<()> {
2815 while !self.at_punct(Punct::RBrace) {
2816 if self.eat_punct(Punct::Semicolon)? {
2820 continue;
2821 }
2822 elements.push(self.parse_class_element(has_super, &mut seen_constructor)?);
2823 }
2824 Ok(())
2825 })();
2826 let settled = match self.private.pop() {
2830 Some(mut env) => {
2831 let mut carried = Vec::new();
2832 for (name, span) in std::mem::take(&mut env.pending) {
2833 if env.contains(&name) {
2834 continue;
2835 }
2836 match self.private.last_mut() {
2837 Some(outer) => outer.pending.push((name, span)),
2838 None => carried.push((name, span)),
2839 }
2840 }
2841 carried
2842 }
2843 None => Vec::new(),
2844 };
2845 if let Some((name, span)) = settled
2846 .into_iter()
2847 .min_by_key(|(_, span)| span.start.offset)
2848 {
2849 return Err(self.error_at(format!("undefined private field '#{name}'"), span));
2850 }
2851 result?;
2852 let body_end = self.current.span.start;
2855 self.bump()?; let class_span = self.span_from(start);
2863 for element in &mut elements {
2864 if let ClassElement::Method {
2865 kind: MethodKind::Constructor,
2866 func,
2867 ..
2868 } = element
2869 {
2870 func.source_span = Some(class_span);
2871 }
2872 }
2873 Ok(Class {
2874 name,
2875 super_class,
2876 elements,
2877 span: class_span,
2878 body_end,
2879 })
2880 }
2881
2882 fn parse_static_block(&mut self, start: Position) -> Result<ClassElement> {
2890 let saved = self.ctx;
2891 let saved_top = self.top_level;
2892 self.ctx = FnCtx {
2893 in_function: true,
2894 in_generator: false,
2895 in_async: false,
2896 in_method: true,
2898 in_derived_constructor: false,
2899 in_static_block: true,
2900 arguments_allowed: false,
2901 };
2902 self.top_level = false;
2903 let saved_strict = self.strict;
2909 let enter = self.enter_strict();
2910 let saved_loop = self.loop_depth;
2913 let saved_switch = self.switch_depth;
2914 let saved_labels = std::mem::take(&mut self.labels);
2915 self.loop_depth = 0;
2916 self.switch_depth = 0;
2917 let body_start = self.current.span.start;
2918 let body = match enter {
2919 Ok(()) => self.parse_block(),
2920 Err(error) => Err(error),
2921 };
2922 self.strict = saved_strict;
2923 self.lexer.set_strict(saved_strict);
2924 self.ctx = saved;
2925 self.top_level = saved_top;
2926 self.loop_depth = saved_loop;
2927 self.switch_depth = saved_switch;
2928 self.labels = saved_labels;
2929 let body = body?;
2930 Ok(ClassElement::StaticBlock {
2931 body,
2932 body_start,
2933 span: self.span_from(start),
2934 })
2935 }
2936
2937 fn parse_class_element(
2938 &mut self,
2939 has_super: bool,
2940 seen_constructor: &mut bool,
2941 ) -> Result<ClassElement> {
2942 let start = self.current.span.start;
2943 let mut is_static = false;
2944 if self.at_ident("static") {
2945 let peek = self.peek()?;
2946 let is_modifier = !matches!(
2947 peek.kind,
2948 TokenKind::Punct(Punct::LParen)
2949 | TokenKind::Punct(Punct::Eq)
2950 | TokenKind::Punct(Punct::Semicolon)
2951 | TokenKind::Punct(Punct::RBrace)
2952 );
2953 if is_modifier {
2954 self.bump()?; if self.at_punct(Punct::LBrace) {
2956 return self.parse_static_block(start);
2957 }
2958 is_static = true;
2959 }
2960 }
2961 let reported_start = self.current.span.start;
2965
2966 let mut is_async = false;
2968 let mut is_generator = false;
2969 let mut accessor: Option<MethodKind> = None;
2970 if self.at_ident("async") {
2971 let peek = self.peek()?;
2972 let is_modifier = !matches!(
2973 peek.kind,
2974 TokenKind::Punct(Punct::LParen)
2975 | TokenKind::Punct(Punct::Eq)
2976 | TokenKind::Punct(Punct::Semicolon)
2977 | TokenKind::Punct(Punct::RBrace)
2978 ) && !peek.newline_before;
2979 if is_modifier {
2980 self.bump()?;
2981 is_async = true;
2982 }
2983 }
2984 if self.at_punct(Punct::Star) {
2985 self.bump()?;
2986 is_generator = true;
2987 }
2988 if accessor.is_none() && (self.at_ident("get") || self.at_ident("set")) {
2989 let is_get = self.at_ident("get");
2990 let peek = self.peek()?;
2991 if is_property_key_start(&peek.kind) {
2992 self.bump()?;
2993 accessor = Some(if is_get {
2994 MethodKind::Get
2995 } else {
2996 MethodKind::Set
2997 });
2998 }
2999 }
3000 let key = self.parse_property_key()?;
3001
3002 if matches!(&key, PropName::Private(ident) if ident.name == "constructor") {
3006 return Err(self.error("invalid method name"));
3007 }
3008 if !is_static
3014 && (is_generator || is_async || accessor.is_some())
3015 && matches!(&key, PropName::Literal(PropKey::Str(name)) if name.as_str() == Some("constructor"))
3016 {
3017 return Err(self.error("invalid method name"));
3018 }
3019
3020 if let PropName::Private(ident) = &key {
3022 if let Some(env) = self.private.last_mut() {
3023 if !env.declare(&ident.name, accessor, is_static) {
3024 return Err(self.error_at(
3025 "private class field is already defined".to_string(),
3028 ident.span,
3029 ));
3030 }
3031 }
3032 }
3033
3034 if self.at_punct(Punct::LParen) {
3035 let kind = match accessor {
3036 Some(kind) => kind,
3037 None => {
3038 let is_constructor = !is_static
3039 && !is_generator
3040 && !is_async
3041 && matches!(&key, PropName::Literal(PropKey::Str(s)) if s.as_str() == Some("constructor"));
3042 if is_constructor {
3043 if *seen_constructor {
3044 return Err(self.error_at(
3045 "property constructor appears more than once",
3046 self.span_from(start),
3047 ));
3048 }
3049 *seen_constructor = true;
3050 MethodKind::Constructor
3051 } else {
3052 MethodKind::Method
3053 }
3054 }
3055 };
3056 if kind == MethodKind::Constructor && (is_generator || is_async) {
3057 return Err(self.error("a constructor may not be a generator or async"));
3058 }
3059 let saved = self.ctx;
3060 self.ctx = FnCtx {
3061 in_function: true,
3062 in_generator: is_generator,
3063 in_async: is_async,
3064 in_method: true,
3065 in_derived_constructor: kind == MethodKind::Constructor && has_super,
3066 in_static_block: false,
3067 arguments_allowed: true,
3068 };
3069 let saved_top = self.top_level;
3070 self.top_level = false;
3071 let result = (|| -> Result<Function> {
3072 let params = self.parse_formal_parameters()?;
3073 let (params, params_span, body, strict) = self.parse_function_body(params, true)?;
3074 Ok(Function {
3075 name: None,
3076 params,
3077 body,
3078 is_async,
3079 is_generator,
3080 strict,
3081 is_arrow: false,
3082 span: Span::new(reported_start, self.prev_end),
3083 params_span,
3084 source_span: None,
3085 })
3086 })();
3087 self.ctx = saved;
3088 self.top_level = saved_top;
3089 let func = result?;
3090 if is_static {
3091 if let PropName::Literal(PropKey::Str(name)) = &key {
3092 if name == "prototype" {
3093 return Err(self.error_at("invalid method name", func.span));
3094 }
3095 }
3096 }
3097 if kind == MethodKind::Get && !func.params.is_empty() {
3098 return Err(self.error_at(
3099 "invalid number of arguments for getter or setter",
3100 func.span,
3101 ));
3102 }
3103 if kind == MethodKind::Set && func.params.len() != 1 {
3104 return Err(self.error_at(
3105 "invalid number of arguments for getter or setter",
3106 func.span,
3107 ));
3108 }
3109 return Ok(ClassElement::Method {
3110 key,
3111 is_static,
3112 kind,
3113 func: Box::new(func),
3114 span: self.span_from(start),
3115 });
3116 }
3117
3118 if accessor.is_some() {
3120 return Err(self.error("expecting '(' after an accessor name"));
3121 }
3122 if let PropName::Literal(PropKey::Str(name)) = &key {
3123 if name == "constructor" && !is_static {
3124 return Err(self.error("classes may not have a field named 'constructor'"));
3125 }
3126 if name == "prototype" && is_static {
3127 return Err(self.error("classes may not have a static property named 'prototype'"));
3128 }
3129 }
3130 let saved = self.ctx;
3134 let saved_top = self.top_level;
3135 self.ctx = FnCtx {
3136 in_function: true,
3137 in_generator: false,
3138 in_async: false,
3139 in_method: true,
3140 in_derived_constructor: false,
3141 in_static_block: false,
3142 arguments_allowed: false,
3143 };
3144 self.top_level = false;
3145 let value = self
3146 .eat_punct(Punct::Eq)?
3147 .then(|| self.parse_assignment(true));
3148 self.ctx = saved;
3149 self.top_level = saved_top;
3150 let value = match value {
3151 Some(value) => Some(Box::new(value?)),
3152 None => None,
3153 };
3154 self.semicolon()?;
3156 Ok(ClassElement::Field {
3157 key,
3158 is_static,
3159 value,
3160 span: self.span_from(start),
3161 })
3162 }
3163
3164 fn parse_import_decl(&mut self) -> Result<Stmt> {
3167 let start = self.current.span.start;
3168 self.bump()?; let mut specifiers = Vec::new();
3170 if let TokenKind::String(source) = self.current.kind.clone() {
3171 let source = as_specifier(&source);
3172 self.bump()?;
3173 let attributes = self.parse_import_attributes()?;
3174 self.semicolon()?;
3175 return Ok(Stmt::new(
3176 StmtKind::Import(Box::new(ImportDecl {
3177 specifiers,
3178 source,
3179 attributes,
3180 span: self.span_from(start),
3181 })),
3182 self.span_from(start),
3183 ));
3184 }
3185 if matches!(self.current.kind, TokenKind::Ident(_)) {
3187 let local = self.expect_ident()?;
3188 specifiers.push(ImportSpecifier::Default(local));
3189 if !self.eat_punct(Punct::Comma)? {
3190 return self.finish_import(start, specifiers);
3191 }
3192 }
3193 if self.at_punct(Punct::Star) {
3194 self.bump()?;
3195 if !self.eat_contextual("as")? {
3196 return Err(self.unexpected());
3197 }
3198 let local = self.expect_ident()?;
3199 specifiers.push(ImportSpecifier::Namespace(local));
3200 return self.finish_import(start, specifiers);
3201 }
3202 if self.at_punct(Punct::LBrace) {
3203 self.bump()?;
3204 while !self.at_punct(Punct::RBrace) {
3205 let imported = self.parse_module_name()?;
3206 let local = if self.eat_contextual("as")? {
3207 self.expect_ident()?
3208 } else {
3209 match &imported {
3210 ModuleName::Ident(id) => id.clone(),
3211 ModuleName::Str(_) => {
3212 return Err(self.error_at(
3213 "a string module name must be followed by 'as'",
3214 self.current.span,
3215 ));
3216 }
3217 }
3218 };
3219 specifiers.push(ImportSpecifier::Named { imported, local });
3220 if !self.eat_punct(Punct::Comma)? {
3221 break;
3222 }
3223 }
3224 self.expect_punct(Punct::RBrace)?;
3225 } else if !specifiers.is_empty() {
3226 return Err(self.unexpected());
3227 } else if self.at_punct(Punct::LBrace) {
3228 unreachable!("handled above");
3229 } else {
3230 return Err(self.unexpected());
3231 }
3232 self.finish_import(start, specifiers)
3233 }
3234
3235 fn finish_import(&mut self, start: Position, specifiers: Vec<ImportSpecifier>) -> Result<Stmt> {
3236 if !self.eat_contextual("from")? {
3237 return Err(self.unexpected());
3238 }
3239 let TokenKind::String(source) = self.current.kind.clone() else {
3240 return Err(self.error("string expected"));
3241 };
3242 let source = as_specifier(&source);
3243 self.bump()?;
3244 let attributes = self.parse_import_attributes()?;
3245 self.semicolon()?;
3246 let span = self.span_from(start);
3247 for specifier in &specifiers {
3248 let local = match specifier {
3249 ImportSpecifier::Default(id) => id,
3250 ImportSpecifier::Namespace(id) => id,
3251 ImportSpecifier::Named { local, .. } => local,
3252 };
3253 self.declare_lexical(&local.name)?;
3254 if let Some(scope) = self.scopes.last_mut()
3255 && !scope.import_names.iter().any(|n| n == &local.name)
3256 {
3257 scope.import_names.push(local.name.clone());
3258 }
3259 }
3260 Ok(Stmt::new(
3261 StmtKind::Import(Box::new(ImportDecl {
3262 specifiers,
3263 source,
3264 attributes,
3265 span,
3266 })),
3267 span,
3268 ))
3269 }
3270
3271 fn parse_import_attributes(&mut self) -> Result<Vec<ImportAttribute>> {
3272 let mut attributes = Vec::new();
3273 let has_with = self.at_keyword(Keyword::With) || self.at_ident("assert");
3274 if !has_with {
3275 return Ok(attributes);
3276 }
3277 let peek = self.peek()?;
3278 if !matches!(peek.kind, TokenKind::Punct(Punct::LBrace)) {
3279 return Ok(attributes);
3280 }
3281 self.bump()?; self.expect_punct(Punct::LBrace)?;
3283 while !self.at_punct(Punct::RBrace) {
3284 let attr_start = self.current.span.start;
3285 let key = match self.current.kind.clone() {
3286 TokenKind::Ident(name) => name,
3287 TokenKind::String(value) => as_specifier(&value),
3288 _ => return Err(self.error("expecting an import attribute name")),
3289 };
3290 self.bump()?;
3291 self.expect_punct(Punct::Colon)?;
3292 let TokenKind::String(value) = self.current.kind.clone() else {
3293 return Err(self.error("expecting an import attribute value string"));
3294 };
3295 let value = as_specifier(&value);
3296 self.bump()?;
3297 attributes.push(ImportAttribute {
3298 key,
3299 value,
3300 span: self.span_from(attr_start),
3301 });
3302 if !self.eat_punct(Punct::Comma)? {
3303 break;
3304 }
3305 }
3306 self.expect_punct(Punct::RBrace)?;
3307 Ok(attributes)
3308 }
3309
3310 fn parse_module_name(&mut self) -> Result<ModuleName> {
3311 match self.current.kind.clone() {
3312 TokenKind::String(value) => {
3313 self.bump()?;
3314 Ok(ModuleName::Str(as_specifier(&value)))
3315 }
3316 TokenKind::Ident(_) => Ok(ModuleName::Ident(self.expect_ident()?)),
3317 TokenKind::Keyword(kw) => {
3318 let span = self.current.span;
3319 self.bump()?;
3320 Ok(ModuleName::Ident(Ident {
3321 name: kw.as_str().to_string(),
3322 span,
3323 }))
3324 }
3325 _ => Err(self.error("identifier or string expected")),
3328 }
3329 }
3330
3331 fn parse_export_decl(&mut self) -> Result<Stmt> {
3332 let start = self.current.span.start;
3333 self.bump()?; if self.at_punct(Punct::Star) {
3335 self.bump()?;
3336 let mut exported = None;
3337 if self.eat_contextual("as")? {
3338 exported = Some(self.parse_module_name()?);
3339 }
3340 if !self.eat_contextual("from")? {
3341 return Err(self.error("expecting 'from' after 'export *'"));
3342 }
3343 let TokenKind::String(source) = self.current.kind.clone() else {
3344 return Err(self.error("string expected"));
3345 };
3346 let source = as_specifier(&source);
3347 self.bump()?;
3348 let attributes = self.parse_import_attributes()?;
3349 self.semicolon()?;
3350 let span = self.span_from(start);
3351 return Ok(Stmt::new(
3352 StmtKind::Export(Box::new(ExportDecl {
3353 kind: ExportKind::All {
3354 source,
3355 exported,
3356 attributes,
3357 },
3358 span,
3359 })),
3360 span,
3361 ));
3362 }
3363 if self.eat_keyword(Keyword::Default)? {
3364 let value = if self.at_keyword(Keyword::Function) {
3365 let func = self.parse_function(FunctionForm::Expression, false, None)?;
3366 Expr::new(ExprKind::Function(Box::new(func)), self.span_from(start))
3367 } else if self.at_ident("async") {
3368 let peek = self.peek()?;
3369 if matches!(peek.kind, TokenKind::Keyword(Keyword::Function)) {
3370 self.bump()?;
3371 let func = self.parse_function(FunctionForm::Expression, true, Some(start))?;
3372 Expr::new(ExprKind::Function(Box::new(func)), self.span_from(start))
3373 } else {
3374 self.parse_assignment(true)?
3375 }
3376 } else if self.at_keyword(Keyword::Class) {
3377 let class = self.parse_class(true)?;
3378 Expr::new(ExprKind::Class(Box::new(class)), self.span_from(start))
3379 } else {
3380 let expr = self.parse_assignment(true)?;
3381 self.semicolon()?;
3382 expr
3383 };
3384 let span = self.span_from(start);
3385 return Ok(Stmt::new(
3386 StmtKind::Export(Box::new(ExportDecl {
3387 kind: ExportKind::Default(Box::new(value)),
3388 span,
3389 })),
3390 span,
3391 ));
3392 }
3393 if self.at_keyword(Keyword::Var)
3394 || self.at_keyword(Keyword::Const)
3395 || self.at_keyword(Keyword::Function)
3396 || self.at_keyword(Keyword::Class)
3397 || (self.at_ident("let") && self.let_starts_declaration()?)
3398 {
3399 let decl = self.parse_statement_list_item()?;
3400 let span = self.span_from(start);
3401 return Ok(Stmt::new(
3402 StmtKind::Export(Box::new(ExportDecl {
3403 kind: ExportKind::Declaration(Box::new(decl)),
3404 span,
3405 })),
3406 span,
3407 ));
3408 }
3409 if self.at_ident("async") {
3410 let peek = self.peek()?;
3411 if matches!(peek.kind, TokenKind::Keyword(Keyword::Function)) && !peek.newline_before {
3412 let decl = self.parse_statement_list_item()?;
3413 let span = self.span_from(start);
3414 return Ok(Stmt::new(
3415 StmtKind::Export(Box::new(ExportDecl {
3416 kind: ExportKind::Declaration(Box::new(decl)),
3417 span,
3418 })),
3419 span,
3420 ));
3421 }
3422 }
3423 if self.at_punct(Punct::LBrace) {
3424 self.bump()?;
3425 let mut specifiers = Vec::new();
3426 let mut candidates: Vec<(String, Span)> = Vec::new();
3427 let mut source = None;
3428 while !self.at_punct(Punct::RBrace) {
3429 let spec_start = self.current.span.start;
3430 let local = self.parse_module_name()?;
3431 let exported = if self.eat_contextual("as")? {
3432 self.parse_module_name()?
3433 } else {
3434 local.clone()
3435 };
3436 if let ModuleName::Ident(id) = &local {
3440 candidates.push((id.name.clone(), id.span));
3441 }
3442 specifiers.push(ExportSpecifier {
3443 local,
3444 exported,
3445 span: self.span_from(spec_start),
3446 });
3447 if !self.eat_punct(Punct::Comma)? {
3448 break;
3449 }
3450 }
3451 self.expect_punct(Punct::RBrace)?;
3452 let mut attributes = Vec::new();
3453 let has_from = self.eat_contextual("from")?;
3454 if !has_from {
3455 self.pending_exports.extend(candidates);
3459 }
3460 if has_from {
3461 let TokenKind::String(value) = self.current.kind.clone() else {
3462 return Err(self.error("string expected"));
3463 };
3464 let value = as_specifier(&value);
3465 self.bump()?;
3466 source = Some(value);
3467 attributes = self.parse_import_attributes()?;
3468 }
3469 self.semicolon()?;
3470 let span = self.span_from(start);
3471 return Ok(Stmt::new(
3472 StmtKind::Export(Box::new(ExportDecl {
3473 kind: ExportKind::Named {
3474 specifiers,
3475 source,
3476 attributes,
3477 },
3478 span,
3479 })),
3480 span,
3481 ));
3482 }
3483 Err(self.unexpected())
3484 }
3485
3486 fn expr_to_pattern(&mut self, expr: Expr, kind: TargetKind) -> Result<Pattern> {
3489 self.expr_to_pattern_inner(expr, kind, false)
3490 }
3491
3492 fn expr_to_pattern_inner(
3493 &mut self,
3494 expr: Expr,
3495 kind: TargetKind,
3496 nested: bool,
3497 ) -> Result<Pattern> {
3498 let span = expr.span;
3499 match expr.kind {
3500 ExprKind::Ident(ident) => {
3501 if kind == TargetKind::Binding {
3502 self.check_binding_name(&ident.name, ident.span)?;
3503 } else {
3504 self.check_identifier(&ident.name, ident.span)?;
3505 if self.strict && (ident.name == "eval" || ident.name == "arguments") {
3506 return Err(self.error_at(
3507 format!("invalid assignment to '{}' in strict mode", ident.name),
3508 ident.span,
3509 ));
3510 }
3511 }
3512 Ok(Pattern::new(PatternKind::Ident(ident), span))
3513 }
3514 ExprKind::Paren(inner) => self.expr_to_pattern_inner(*inner, kind, nested),
3515 ExprKind::Array { elements } => {
3516 self.check_spread_trailing_comma(span, "rest element must be the last one")?;
3517 let mut out = Vec::new();
3518 let mut rest = None;
3519 let count = elements.len();
3520 for (index, element) in elements.into_iter().enumerate() {
3521 match element {
3522 None => out.push(None),
3523 Some(ArrayElement::Expr(expr)) => {
3524 let pattern = self.expr_to_pattern_inner(*expr, kind, true)?;
3525 out.push(Some(PatternElement::Pattern(pattern)));
3526 }
3527 Some(ArrayElement::Spread(expr)) => {
3528 if index + 1 != count {
3529 return Err(
3530 self.error_at("rest element must be the last one", expr.span)
3531 );
3532 }
3533 rest = Some(Box::new(self.expr_to_rest(*expr, kind)?));
3534 }
3535 }
3536 }
3537 Ok(Pattern::new(
3538 PatternKind::Array {
3539 elements: out,
3540 rest,
3541 },
3542 span,
3543 ))
3544 }
3545 ExprKind::Object(properties) => {
3546 self.check_spread_trailing_comma(span, "assignment rest property must be last")?;
3547 self.cover_inits
3548 .retain(|cover| !span_contains(span, *cover));
3549 let mut out = Vec::new();
3550 let mut rest = None;
3551 let count = properties.len();
3552 for (index, property) in properties.into_iter().enumerate() {
3553 match property {
3554 ObjectProperty::Spread(expr) => {
3555 if index + 1 != count {
3556 return Err(
3557 self.error_at("rest element must be the last one", expr.span)
3558 );
3559 }
3560 rest = Some(Box::new(self.expr_to_rest(*expr, kind)?));
3561 }
3562 ObjectProperty::Property {
3563 key,
3564 value,
3565 kind: _,
3566 shorthand,
3567 span,
3568 } => {
3569 let pattern = self.expr_to_pattern_inner(*value, kind, true)?;
3570 out.push(Some(PatternElement::Property {
3571 key,
3572 value: pattern,
3573 shorthand,
3574 span,
3575 }));
3576 }
3577 }
3578 }
3579 Ok(Pattern::new(
3580 PatternKind::Object {
3581 properties: out,
3582 rest,
3583 },
3584 span,
3585 ))
3586 }
3587 ExprKind::Assign { op, target, value } if op.is_simple() => {
3588 let target = match target.kind {
3590 PatternKind::Ident(ident) => {
3591 self.check_target_name(&ident.name, ident.span, kind)?;
3599 Pattern::new(PatternKind::Ident(ident), target.span)
3600 }
3601 other => {
3602 let expr = pattern_to_expr(Pattern::new(other, target.span), target.span);
3603 self.expr_to_pattern_inner(expr, kind, nested)?
3604 }
3605 };
3606 Ok(Pattern::new(
3607 PatternKind::Assign {
3608 target: Box::new(target),
3609 default: value,
3610 },
3611 span,
3612 ))
3613 }
3614 ExprKind::Member {
3615 object,
3616 property,
3617 optional,
3618 } => {
3619 if kind == TargetKind::Binding {
3620 return Err(self.error_at("invalid binding pattern", span));
3621 }
3622 if optional {
3623 return Err(self.error_at("invalid assignment target", span));
3624 }
3625 let op_pos = expr.op_pos;
3626 Ok(Pattern::new(
3627 PatternKind::Member(Box::new(MemberPattern {
3628 object,
3629 property,
3630 span,
3631 op_pos,
3632 })),
3633 span,
3634 ))
3635 }
3636 ExprKind::OptionalChain(_) => {
3637 Err(self.error_at("invalid assignment left-hand side", span))
3638 }
3639 other @ ExprKind::Call { .. } if !nested && kind == TargetKind::Assignment => Ok(
3644 Pattern::new(PatternKind::Invalid(Box::new(Expr::new(other, span))), span),
3645 ),
3646 _ if kind == TargetKind::Binding => Err(self.error_at("invalid binding pattern", span)),
3647 _ if nested => Err(self.error_at("invalid destructuring target", span)),
3652 _ => Err(self.error_at("invalid assignment left-hand side", span)),
3653 }
3654 }
3655
3656 fn check_spread_trailing_comma(&mut self, span: Span, message: &str) -> Result<()> {
3659 if let Some(position) = self.spread_trailing_comma.iter().position(|s| *s == span) {
3660 self.spread_trailing_comma.remove(position);
3661 return Err(self.error_at(message, span));
3662 }
3663 self.spread_trailing_comma
3667 .retain(|candidate| !span_contains(span, *candidate));
3668 Ok(())
3669 }
3670
3671 fn check_target_name(&mut self, name: &str, span: Span, kind: TargetKind) -> Result<()> {
3676 if kind == TargetKind::Binding {
3677 self.check_binding_name(name, span)?;
3678 } else {
3679 self.check_identifier(name, span)?;
3680 if self.strict && (name == "eval" || name == "arguments") {
3681 return Err(self.error_at(
3682 format!("invalid assignment to '{name}' in strict mode"),
3683 span,
3684 ));
3685 }
3686 }
3687 Ok(())
3688 }
3689
3690 fn expr_to_rest(&mut self, expr: Expr, kind: TargetKind) -> Result<RestElement> {
3691 let expr = match expr.kind {
3694 ExprKind::Spread(inner) => *inner,
3695 other => Expr::new(other, expr.span),
3696 };
3697 if let ExprKind::Assign { op, .. } = &expr.unparen().kind
3702 && op.is_simple()
3703 {
3704 return Err(self.error_at("rest element cannot have a default value", expr.span));
3705 }
3706 if kind == TargetKind::Binding {
3707 return Ok(RestElement::Pattern(
3708 self.expr_to_pattern_inner(expr, kind, true)?,
3709 ));
3710 }
3711 match &expr.kind {
3712 ExprKind::Member { optional, .. } => {
3713 if *optional {
3714 return Err(self.error_at("invalid assignment target", expr.span));
3715 }
3716 match self.expr_to_pattern_inner(expr, kind, true)?.kind {
3717 PatternKind::Member(member) => Ok(RestElement::Member(member)),
3718 _ => unreachable!("member expressions convert to member patterns"),
3719 }
3720 }
3721 _ => Ok(RestElement::Pattern(
3722 self.expr_to_pattern_inner(expr, kind, true)?,
3723 )),
3724 }
3725 }
3726
3727 fn parse_expression(&mut self, allow_in: bool) -> Result<Expr> {
3731 self.enter()?;
3732 let result = self.parse_expression_unguarded(allow_in);
3733 self.leave();
3734 result
3735 }
3736
3737 fn parse_expression_unguarded(&mut self, allow_in: bool) -> Result<Expr> {
3738 let saved_allow_in = self.allow_in;
3743 self.allow_in = allow_in;
3744 let result = self.parse_expression_in(allow_in);
3745 self.allow_in = saved_allow_in;
3746 result
3747 }
3748
3749 fn parse_expression_in(&mut self, allow_in: bool) -> Result<Expr> {
3750 let start = self.current.span.start;
3751 let first = self.parse_assignment(allow_in)?;
3752 if !self.at_punct(Punct::Comma) {
3753 return Ok(first);
3754 }
3755 let mut items = vec![first];
3756 while self.eat_punct(Punct::Comma)? {
3757 items.push(self.parse_assignment(allow_in)?);
3758 }
3759 Ok(Expr::new(ExprKind::Sequence(items), self.span_from(start)))
3760 }
3761
3762 fn parse_assignment(&mut self, allow_in: bool) -> Result<Expr> {
3763 let start = self.current.span.start;
3764
3765 if self.ctx.in_generator && self.at_ident("yield") {
3768 if self.in_formal_parameters {
3769 return Err(self.error_at("yield in default expression", self.current.span));
3770 }
3771 return self.parse_yield(allow_in);
3772 }
3773
3774 let lhs = match self.try_parse_arrow(allow_in)? {
3775 Some(arrow) => return Ok(arrow),
3776 None => self.parse_conditional(allow_in)?,
3777 };
3778
3779 if let Some(op) = self.current.kind.as_punct().and_then(AssignOp::from_punct) {
3780 let op_pos = self.current.span.start;
3781 let target = self.expr_to_pattern(lhs, TargetKind::Assignment)?;
3782 self.bump()?;
3783 let value = self.parse_assignment(allow_in)?;
3784 return Ok(Expr::at_operator(
3785 ExprKind::Assign {
3786 op,
3787 target: Box::new(target),
3788 value: Box::new(value),
3789 },
3790 self.span_from(start),
3791 op_pos,
3792 ));
3793 }
3794 let _ = start;
3795 Ok(lhs)
3796 }
3797
3798 fn parse_yield(&mut self, allow_in: bool) -> Result<Expr> {
3799 let start = self.current.span.start;
3800 self.bump()?; let delegate = if self.at_punct(Punct::Star) && !self.current.newline_before {
3802 self.bump()?;
3803 true
3804 } else {
3805 false
3806 };
3807 let argument = if delegate {
3808 Some(Box::new(self.parse_assignment(allow_in)?))
3809 } else if self.current.newline_before
3810 || self.at_punct(Punct::RParen)
3811 || self.at_punct(Punct::RBracket)
3812 || self.at_punct(Punct::RBrace)
3813 || self.at_punct(Punct::Comma)
3814 || self.at_punct(Punct::Semicolon)
3815 || self.at_punct(Punct::Colon)
3816 || self.current.is_eof()
3817 {
3818 None
3819 } else {
3820 Some(Box::new(self.parse_assignment(allow_in)?))
3821 };
3822 Ok(Expr::new(
3823 ExprKind::Yield { argument, delegate },
3824 self.span_from(start),
3825 ))
3826 }
3827
3828 fn try_parse_arrow(&mut self, allow_in: bool) -> Result<Option<Expr>> {
3829 let starts_paren = self.at_punct(Punct::LParen);
3830 let starts_ident = matches!(self.current.kind, TokenKind::Ident(_));
3831 if !starts_paren && !starts_ident {
3832 return Ok(None);
3833 }
3834 if starts_paren && !self.arrow_follows_paren()? {
3838 return Ok(None);
3839 }
3840 let snapshot = self.snapshot();
3841 let head = match self.parse_arrow_head() {
3842 Ok(head) => head,
3843 Err(_) => {
3844 self.restore(snapshot);
3845 return Ok(None);
3846 }
3847 };
3848 let Some(head) = head else {
3849 self.restore(snapshot);
3850 return Ok(None);
3851 };
3852 let body_start = if self.at_punct(Punct::LBrace) {
3859 self.peek()?.span
3860 } else {
3861 self.current.span
3862 };
3863 self.check_duplicate_parameters(&head.params, true, body_start)?;
3864 let saved_ctx = self.ctx;
3865 let saved_loop = self.loop_depth;
3866 let saved_switch = self.switch_depth;
3867 let saved_labels = std::mem::take(&mut self.labels);
3868 let saved_top = self.top_level;
3869 self.ctx = FnCtx {
3870 in_function: true,
3871 in_generator: false,
3872 in_async: head.is_async,
3873 in_method: saved_ctx.in_method,
3874 in_derived_constructor: saved_ctx.in_derived_constructor,
3875 in_static_block: false,
3879 arguments_allowed: saved_ctx.arguments_allowed,
3880 };
3881 self.loop_depth = 0;
3882 self.switch_depth = 0;
3883 self.top_level = false;
3884 let body_start = self.current.span.start;
3885 let (body, strict) = if self.at_punct(Punct::LBrace) {
3886 let (block, strict) = self.parse_arrow_block(&head.params)?;
3887 (block, (self.prev_end, strict))
3888 } else {
3889 let expr = self.parse_assignment(allow_in)?;
3890 let end = expr.span.end;
3891 let strict = self.strict;
3893 (FunctionBody::Expr(Box::new(expr)), (end, strict))
3894 };
3895 self.ctx = saved_ctx;
3896 self.loop_depth = saved_loop;
3897 self.switch_depth = saved_switch;
3898 self.labels = saved_labels;
3899 self.top_level = saved_top;
3900 let _ = body_start;
3901 let (body, (end, strict)) = (body, strict);
3902 let span = Span::new(head.span.start, end);
3903 Ok(Some(Expr::new(
3904 ExprKind::Arrow(Box::new(Function {
3905 name: None,
3906 params: head.params,
3907 body,
3908 is_async: head.is_async,
3909 is_generator: false,
3910 strict,
3911 is_arrow: true,
3912 span,
3913 params_span: head.params_span,
3914 source_span: None,
3915 })),
3916 span,
3917 )))
3918 }
3919
3920 fn parse_arrow_block(&mut self, params: &[Pattern]) -> Result<(FunctionBody, bool)> {
3922 let saved_strict = self.strict;
3925 self.expect_punct(Punct::LBrace)?;
3926 self.push_scope(Scope::function(simple_parameter_names(params)));
3927 let result = (|| -> Result<Vec<Stmt>> {
3928 let mut body = Vec::new();
3929 let mut prologue = true;
3930 while !self.at_punct(Punct::RBrace) {
3931 if self.current.is_eof() {
3932 return Err(self.unexpected());
3933 }
3934 let stmt = self.parse_statement_list_item()?;
3935 if prologue {
3936 match self.directive_value(&stmt) {
3937 Some(directive) if directive == "use strict" => self.enter_strict()?,
3938 Some(_) => {}
3939 None => prologue = false,
3940 }
3941 }
3942 body.push(stmt);
3943 }
3944 Ok(body)
3945 })();
3946 self.pop_scope();
3947 let body_strict = self.strict;
3948 self.strict = saved_strict;
3949 self.lexer.set_strict(saved_strict);
3950 let body = result?;
3951 self.bump()?;
3952 Ok((FunctionBody::Block(body), body_strict))
3953 }
3954
3955 fn arrow_follows_paren(&self) -> Result<bool> {
3961 let mut lexer = self.lexer.clone();
3962 let mut depth = 1usize;
3964 let mut template_depth = 0usize;
3966 loop {
3967 let token = lexer.next_token()?;
3968 match token.kind {
3969 TokenKind::Eof => return Ok(false),
3970 TokenKind::Punct(Punct::Slash) | TokenKind::Punct(Punct::SlashEq) => {
3978 if lexer.re_scan_regex(token.span.start).is_err() {
3979 lexer.reset_to(token.span.end);
3980 }
3981 }
3982 TokenKind::Template(chunk) => match chunk.kind {
3990 crate::token::TemplateKind::NoSubstitution => {}
3992 crate::token::TemplateKind::Head => template_depth += 1,
3994 crate::token::TemplateKind::Middle => {}
3996 crate::token::TemplateKind::Tail => {
3998 template_depth = template_depth.saturating_sub(1);
3999 }
4000 },
4001 TokenKind::Punct(Punct::LParen)
4002 | TokenKind::Punct(Punct::LBracket)
4003 | TokenKind::Punct(Punct::LBrace) => depth += 1,
4004 TokenKind::Punct(Punct::RBrace) if template_depth > 0 => {
4005 template_depth -= 1;
4008 let token = lexer.re_scan_template_continue(token.span.start)?;
4009 if matches!(
4010 token.kind,
4011 TokenKind::Template(crate::token::TemplateToken {
4012 kind: crate::token::TemplateKind::Head
4013 | crate::token::TemplateKind::Middle,
4014 ..
4015 })
4016 ) {
4017 template_depth += 1;
4018 }
4019 }
4020 TokenKind::Punct(Punct::RParen)
4021 | TokenKind::Punct(Punct::RBracket)
4022 | TokenKind::Punct(Punct::RBrace) => {
4023 if depth == 0 {
4024 return Ok(false);
4026 }
4027 depth -= 1;
4028 if depth == 0 {
4029 let next = lexer.next_token()?;
4032 return Ok(matches!(next.kind, TokenKind::Punct(Punct::Arrow))
4033 && !next.newline_before);
4034 }
4035 }
4036 _ => {}
4037 }
4038 }
4039 }
4040
4041 fn parse_arrow_head(&mut self) -> Result<Option<ArrowHead>> {
4043 let start = self.current.span.start;
4044 let mut is_async = false;
4045 if self.at_ident("async") {
4046 let peek = self.peek()?;
4047 if peek.newline_before {
4048 return Ok(None);
4049 }
4050 let plausible =
4051 matches!(peek.kind, TokenKind::Punct(Punct::LParen)) || peek.kind.is_identifier();
4052 if !plausible {
4053 return Ok(None);
4054 }
4055 self.bump()?;
4056 is_async = true;
4057 }
4058 let params_start = self.current.span.start;
4059 let params = if self.at_punct(Punct::LParen) {
4060 self.parse_formal_parameters()?
4061 } else if matches!(self.current.kind, TokenKind::Ident(_)) {
4062 let ident = self.expect_ident()?;
4063 vec![Pattern::new(
4064 PatternKind::Ident(ident),
4065 self.span_from(params_start),
4066 )]
4067 } else {
4068 return Ok(None);
4069 };
4070 let params_span = self.span_from(params_start);
4071 if !self.at_punct(Punct::Arrow) || self.current.newline_before {
4072 return Ok(None);
4073 }
4074 self.bump()?; Ok(Some(ArrowHead {
4076 params,
4077 is_async,
4078 span: self.span_from(start),
4079 params_span,
4080 }))
4081 }
4082
4083 fn parse_conditional(&mut self, allow_in: bool) -> Result<Expr> {
4084 let start = self.current.span.start;
4085 let test = self.parse_binary(allow_in, 0)?;
4086 if !self.at_punct(Punct::Question) {
4087 return Ok(test);
4088 }
4089 self.bump()?;
4090 let consequent = self.parse_assignment(true)?;
4091 self.expect_punct(Punct::Colon)?;
4092 let alternate = self.parse_assignment(allow_in)?;
4093 Ok(Expr::new(
4094 ExprKind::Conditional {
4095 test: Box::new(test),
4096 cons: Box::new(consequent),
4097 alt: Box::new(alternate),
4098 },
4099 self.span_from(start),
4100 ))
4101 }
4102
4103 fn parse_binary(&mut self, allow_in: bool, min_prec: u8) -> Result<Expr> {
4104 let start = self.current.span.start;
4105 let mut lhs = self.parse_unary()?;
4106 while let Some((prec, op)) = binary_operator(&self.current.kind, allow_in) {
4107 if prec < min_prec {
4108 break;
4109 }
4110 let op_pos = self.current.span.start;
4111 self.bump()?;
4112 let next_min = if op.is_right_associative() {
4113 prec
4114 } else {
4115 prec + 1
4116 };
4117 let rhs = self.parse_binary(allow_in, next_min)?;
4118 lhs = build_binary(op, lhs, rhs, self.span_from(start), op_pos)?;
4119 }
4120 Ok(lhs)
4121 }
4122
4123 fn parse_unary(&mut self) -> Result<Expr> {
4126 let start = self.current.span.start;
4127 let unary = match &self.current.kind {
4129 TokenKind::Keyword(Keyword::Delete) => Some(UnaryOp::Delete),
4130 TokenKind::Keyword(Keyword::Void) => Some(UnaryOp::Void),
4131 TokenKind::Keyword(Keyword::Typeof) => Some(UnaryOp::Typeof),
4132 TokenKind::Punct(Punct::Plus) => Some(UnaryOp::Plus),
4133 TokenKind::Punct(Punct::Minus) => Some(UnaryOp::Minus),
4134 TokenKind::Punct(Punct::Bang) => Some(UnaryOp::Not),
4135 TokenKind::Punct(Punct::Tilde) => Some(UnaryOp::BitNot),
4136 _ => None,
4137 };
4138 if let Some(op) = unary {
4139 let op_pos = self.current.span.start;
4140 self.bump()?;
4141 let argument = self.parse_unary()?;
4142 if op == UnaryOp::Delete && self.strict {
4143 if let ExprKind::Ident(ident) = &argument.unparen().kind {
4144 return Err(self.error_at(
4145 "cannot delete a direct reference in strict mode",
4146 ident.span,
4147 ));
4148 }
4149 }
4150 if op == UnaryOp::Delete && deletes_a_private_member(&argument) {
4156 return Err(self.error("cannot delete a private class field"));
4160 }
4161 let expr = Expr::at_operator(
4162 ExprKind::Unary {
4163 op,
4164 argument: Box::new(argument),
4165 },
4166 self.span_from(start),
4167 op_pos,
4168 );
4169 if self.at_punct(Punct::StarStar) {
4170 return Err(self.error(
4171 "unparenthesized unary expression can't appear on the left-hand side of '**'",
4173 ));
4174 }
4175 return Ok(expr);
4176 }
4177 if self.at_punct(Punct::PlusPlus) || self.at_punct(Punct::MinusMinus) {
4179 let op_pos = self.current.span.start;
4180 let op = if self.at_punct(Punct::PlusPlus) {
4181 UpdateOp::Increment
4182 } else {
4183 UpdateOp::Decrement
4184 };
4185 self.bump()?;
4186 let argument = self.parse_unary()?;
4187 self.check_simple_target(&argument)?;
4188 return Ok(Expr::at_operator(
4189 ExprKind::Update {
4190 op,
4191 argument: Box::new(argument),
4192 prefix: true,
4193 },
4194 self.span_from(start),
4195 op_pos,
4196 ));
4197 }
4198 if self.at_ident("await") && self.ctx.in_async {
4205 if self.in_formal_parameters {
4208 return Err(self.error_at("await in default expression", self.current.span));
4209 }
4210 self.bump()?;
4211 let argument = self.parse_unary()?;
4212 return Ok(Expr::new(
4213 ExprKind::Await(Box::new(argument)),
4214 self.span_from(start),
4215 ));
4216 }
4217 let expr = self.parse_lhs_expression()?;
4218 let result = if (self.at_punct(Punct::PlusPlus) || self.at_punct(Punct::MinusMinus))
4220 && !self.current.newline_before
4221 {
4222 let op_pos = self.current.span.start;
4223 let op = if self.at_punct(Punct::PlusPlus) {
4224 UpdateOp::Increment
4225 } else {
4226 UpdateOp::Decrement
4227 };
4228 self.check_simple_target(&expr)?;
4229 self.bump()?;
4230 Expr::at_operator(
4231 ExprKind::Update {
4232 op,
4233 argument: Box::new(expr),
4234 prefix: false,
4235 },
4236 self.span_from(start),
4237 op_pos,
4238 )
4239 } else {
4240 expr
4241 };
4242 Ok(result)
4243 }
4244
4245 fn check_simple_target(&self, expr: &Expr) -> Result<()> {
4250 match &expr.unparen().kind {
4251 ExprKind::Ident(_) => Ok(()),
4252 ExprKind::Member {
4253 optional: false, ..
4254 } => Ok(()),
4255 _ => Err(self.error_at("invalid increment/decrement operand", expr.span)),
4256 }
4257 }
4258
4259 fn parse_lhs_expression(&mut self) -> Result<Expr> {
4260 let start = self.current.span.start;
4261 let mut expr = if self.at_keyword(Keyword::New) {
4262 self.parse_new_expression()?
4263 } else {
4264 self.parse_primary()?
4265 };
4266 let mut saw_optional = false;
4267 loop {
4268 let op_pos = self.current.span.start;
4271 match self.current.kind.clone() {
4272 TokenKind::Punct(Punct::Dot) => {
4273 self.bump()?;
4274 let property = self.parse_member_property()?;
4275 expr = Expr::at_operator(
4276 ExprKind::Member {
4277 object: Box::new(expr),
4278 property,
4279 optional: false,
4280 },
4281 self.span_from(start),
4282 op_pos,
4283 );
4284 }
4285 TokenKind::Punct(Punct::QuestionDot) => {
4286 saw_optional = true;
4287 self.bump()?;
4288 if self.at_punct(Punct::LParen) {
4289 let arguments = self.parse_arguments()?;
4290 expr = Expr::at_operator(
4291 ExprKind::Call {
4292 callee: Box::new(expr),
4293 arguments,
4294 optional: true,
4295 },
4296 self.span_from(start),
4297 op_pos,
4298 );
4299 } else if self.at_punct(Punct::LBracket) {
4300 self.bump()?;
4301 let index = self.parse_expression(true)?;
4302 self.expect_punct(Punct::RBracket)?;
4303 expr = Expr::at_operator(
4304 ExprKind::Member {
4305 object: Box::new(expr),
4306 property: MemberProp::Computed(Box::new(index)),
4307 optional: true,
4308 },
4309 self.span_from(start),
4310 op_pos,
4311 );
4312 } else {
4313 let property = self.parse_member_property()?;
4314 expr = Expr::at_operator(
4315 ExprKind::Member {
4316 object: Box::new(expr),
4317 property,
4318 optional: true,
4319 },
4320 self.span_from(start),
4321 op_pos,
4322 );
4323 }
4324 }
4325 TokenKind::Punct(Punct::LBracket) => {
4326 self.bump()?;
4327 let index = self.parse_expression(true)?;
4328 self.expect_punct(Punct::RBracket)?;
4329 expr = Expr::at_operator(
4330 ExprKind::Member {
4331 object: Box::new(expr),
4332 property: MemberProp::Computed(Box::new(index)),
4333 optional: false,
4334 },
4335 self.span_from(start),
4336 op_pos,
4337 );
4338 }
4339 TokenKind::Punct(Punct::LParen) => {
4340 let arguments = self.parse_arguments()?;
4341 expr = Expr::at_operator(
4342 ExprKind::Call {
4343 callee: Box::new(expr),
4344 arguments,
4345 optional: false,
4346 },
4347 self.span_from(start),
4348 op_pos,
4349 );
4350 }
4351 TokenKind::Template(_) => {
4352 if saw_optional || matches!(expr.unparen().kind, ExprKind::OptionalChain(_)) {
4353 return Err(
4354 self.error("tagged template cannot be used in an optional chain")
4355 );
4356 }
4357 let quasi = self.parse_template()?;
4358 expr = Expr::new(
4359 ExprKind::TaggedTemplate {
4360 tag: Box::new(expr),
4361 quasi: Box::new(quasi),
4362 },
4363 self.span_from(start),
4364 );
4365 }
4366 _ => break,
4367 }
4368 }
4369 if saw_optional {
4370 expr = Expr::new(
4371 ExprKind::OptionalChain(Box::new(expr)),
4372 self.span_from(start),
4373 );
4374 }
4375 Ok(expr)
4376 }
4377
4378 fn parse_private_name(&mut self) -> Result<Ident> {
4385 let hash = self.current.span;
4386 self.bump()?;
4387 let ident = self.expect_ident()?;
4388 if ident.span.start.offset != hash.end.offset {
4389 return Err(self.error_at("invalid first character of private name", hash));
4390 }
4391 Ok(ident)
4392 }
4393
4394 fn parse_member_property(&mut self) -> Result<MemberProp> {
4395 if self.at_punct(Punct::Hash) {
4396 let ident = self.parse_private_name()?;
4397 if !self.private.iter().any(|env| env.contains(&ident.name)) {
4398 let Some(innermost) = self.private.last_mut() else {
4404 return Err(self.error_at(
4405 format!("undefined private field '#{}'", ident.name),
4406 ident.span,
4407 ));
4408 };
4409 innermost.pending.push((ident.name.clone(), ident.span));
4413 }
4414 return Ok(MemberProp::Private(ident));
4415 }
4416 match self.current.kind.clone() {
4417 TokenKind::Ident(name) => {
4418 let span = self.current.span;
4419 self.bump()?;
4420 Ok(MemberProp::Ident(Ident { name, span }))
4421 }
4422 TokenKind::Keyword(kw) => {
4423 let span = self.current.span;
4424 self.bump()?;
4425 Ok(MemberProp::Ident(Ident {
4426 name: kw.as_str().to_string(),
4427 span,
4428 }))
4429 }
4430 _ => Err(self.error("expecting field name")),
4434 }
4435 }
4436
4437 fn parse_new_expression(&mut self) -> Result<Expr> {
4438 let start = self.current.span.start;
4439 self.bump()?; if self.at_punct(Punct::Dot) {
4441 self.bump()?;
4442 if !self.at_ident("target") {
4443 return Err(self.error("expecting target"));
4444 }
4445 if !self.ctx.in_function {
4446 return Err(self.error("new.target only allowed within functions"));
4447 }
4448 self.bump()?;
4449 return Ok(Expr::new(ExprKind::NewTarget, self.span_from(start)));
4450 }
4451 let mut callee = if self.at_keyword(Keyword::New) {
4452 self.parse_new_expression()?
4453 } else {
4454 self.parse_primary()?
4455 };
4456 loop {
4458 let op_pos = self.current.span.start;
4459 match self.current.kind.clone() {
4460 TokenKind::Punct(Punct::Dot) => {
4461 self.bump()?;
4462 let property = self.parse_member_property()?;
4463 callee = Expr::at_operator(
4464 ExprKind::Member {
4465 object: Box::new(callee),
4466 property,
4467 optional: false,
4468 },
4469 self.span_from(start),
4470 op_pos,
4471 );
4472 }
4473 TokenKind::Punct(Punct::LBracket) => {
4474 self.bump()?;
4475 let index = self.parse_expression(true)?;
4476 self.expect_punct(Punct::RBracket)?;
4477 callee = Expr::at_operator(
4478 ExprKind::Member {
4479 object: Box::new(callee),
4480 property: MemberProp::Computed(Box::new(index)),
4481 optional: false,
4482 },
4483 self.span_from(start),
4484 op_pos,
4485 );
4486 }
4487 TokenKind::Punct(Punct::QuestionDot) => {
4488 return Err(self.error("new keyword cannot be used with an optional chain"));
4489 }
4490 _ => break,
4491 }
4492 }
4493 if matches!(callee.unparen().kind, ExprKind::OptionalChain(_)) {
4494 return Err(self.error_at("cannot use 'new' with an optional chain", callee.span));
4495 }
4496 if let Some(import_call) = member_chain_import_call(&callee) {
4508 return Err(self.error_at("invalid use of 'import()'", import_call.span));
4509 }
4510 if matches!(&callee.kind, ExprKind::ImportCall(..)) {
4516 return Err(self.error_at("invalid use of 'import()'", callee.span));
4517 }
4518 let arguments = if self.at_punct(Punct::LParen) {
4519 let op_pos = self.current.span.start;
4521 let arguments = Some(self.parse_arguments()?);
4522 return Ok(Expr::at_operator(
4523 ExprKind::New {
4524 callee: Box::new(callee),
4525 arguments,
4526 },
4527 self.span_from(start),
4528 op_pos,
4529 ));
4530 } else {
4531 None
4532 };
4533 Ok(Expr::at_operator(
4537 ExprKind::New {
4538 callee: Box::new(callee),
4539 arguments,
4540 },
4541 self.span_from(start),
4542 self.current.span.start,
4543 ))
4544 }
4545
4546 fn parse_arguments(&mut self) -> Result<Vec<Expr>> {
4547 self.expect_punct(Punct::LParen)?;
4548 let mut arguments = Vec::new();
4549 while !self.at_punct(Punct::RParen) {
4550 if self.at_punct(Punct::Ellipsis) {
4551 let start = self.current.span.start;
4552 self.bump()?;
4553 let argument = self.parse_assignment(true)?;
4554 arguments.push(Expr::new(
4555 ExprKind::Spread(Box::new(argument)),
4556 self.span_from(start),
4557 ));
4558 } else {
4559 arguments.push(self.parse_assignment(true)?);
4560 }
4561 if !self.eat_punct(Punct::Comma)? {
4562 break;
4563 }
4564 }
4565 self.expect_punct(Punct::RParen)?;
4566 Ok(arguments)
4567 }
4568
4569 fn parse_primary(&mut self) -> Result<Expr> {
4576 let start = self.current.span.start;
4577 match self.current.kind.clone() {
4578 TokenKind::Number(NumberLiteral::Int(value)) => {
4579 self.bump()?;
4580 Ok(Expr::new(
4581 ExprKind::Number(value as f64),
4582 self.span_from(start),
4583 ))
4584 }
4585 TokenKind::Number(NumberLiteral::Float(value)) => {
4586 self.bump()?;
4587 Ok(Expr::new(ExprKind::Number(value), self.span_from(start)))
4588 }
4589 TokenKind::String(value) => {
4590 self.bump()?;
4591 Ok(Expr::new(ExprKind::String(value), self.span_from(start)))
4592 }
4593 TokenKind::Ident(name) if name == "async" && !self.current.escaped => {
4597 let peek = self.peek()?;
4598 if matches!(peek.kind, TokenKind::Keyword(Keyword::Function))
4599 && !peek.newline_before
4600 {
4601 self.bump()?; let func = self.parse_function(FunctionForm::Expression, true, Some(start))?;
4603 return Ok(Expr::new(
4604 ExprKind::Function(Box::new(func)),
4605 self.span_from(start),
4606 ));
4607 }
4608 let span = self.current.span;
4609 self.bump()?;
4610 Ok(Expr::new(ExprKind::Ident(Ident { name, span }), span))
4611 }
4612 TokenKind::Ident(name) => {
4613 let span = self.current.span;
4614 self.check_identifier(&name, span)?;
4615 self.check_arguments_reference(&name, span)?;
4616 self.bump()?;
4617 Ok(Expr::new(ExprKind::Ident(Ident { name, span }), span))
4618 }
4619 TokenKind::Keyword(Keyword::This) => {
4620 self.bump()?;
4621 Ok(Expr::new(ExprKind::This, self.span_from(start)))
4622 }
4623 TokenKind::Keyword(Keyword::Null) => {
4624 self.bump()?;
4625 Ok(Expr::new(ExprKind::Null, self.span_from(start)))
4626 }
4627 TokenKind::Keyword(Keyword::True) => {
4628 self.bump()?;
4629 Ok(Expr::new(ExprKind::Bool(true), self.span_from(start)))
4630 }
4631 TokenKind::Keyword(Keyword::False) => {
4632 self.bump()?;
4633 Ok(Expr::new(ExprKind::Bool(false), self.span_from(start)))
4634 }
4635 TokenKind::Punct(Punct::LParen) => {
4636 self.bump()?;
4637 let inner = self.parse_expression(true)?;
4638 self.expect_punct(Punct::RParen)?;
4639 Ok(Expr::new(
4640 ExprKind::Paren(Box::new(inner)),
4641 self.span_from(start),
4642 ))
4643 }
4644 TokenKind::Punct(Punct::Slash) | TokenKind::Punct(Punct::SlashEq) => {
4645 self.parse_regex_literal(start)
4646 }
4647 _ => self.parse_primary_complex(start),
4648 }
4649 }
4650
4651 #[inline(never)]
4654 fn parse_primary_complex(&mut self, start: Position) -> Result<Expr> {
4655 match self.current.kind.clone() {
4656 TokenKind::BigInt(literal) => {
4657 self.bump()?;
4658 Ok(Expr::new(
4659 ExprKind::BigInt {
4660 digits: literal.digits,
4661 radix: literal.radix,
4662 },
4663 self.span_from(start),
4664 ))
4665 }
4666 TokenKind::Template(_) => {
4667 let template = self.parse_template()?;
4668 Ok(Expr::new(
4669 ExprKind::Template(Box::new(template)),
4670 self.span_from(start),
4671 ))
4672 }
4673 TokenKind::Keyword(Keyword::Function) => {
4674 let func = self.parse_function(FunctionForm::Expression, false, None)?;
4675 Ok(Expr::new(
4676 ExprKind::Function(Box::new(func)),
4677 self.span_from(start),
4678 ))
4679 }
4680 TokenKind::Keyword(Keyword::Class) => {
4681 let class = self.parse_class(true)?;
4682 Ok(Expr::new(
4683 ExprKind::Class(Box::new(class)),
4684 self.span_from(start),
4685 ))
4686 }
4687 TokenKind::Keyword(Keyword::Import) => self.parse_import_expression(),
4688 TokenKind::Keyword(Keyword::Super) => self.parse_super(),
4689 TokenKind::Punct(Punct::LBracket) => self.parse_array_literal(),
4690 TokenKind::Punct(Punct::LBrace) => self.parse_object_literal(),
4691 TokenKind::Punct(Punct::Hash) if self.allow_in => self.parse_private_in(start),
4696 TokenKind::Punct(Punct::Hash) => {
4700 let hash = self.current.span;
4701 let name = match self.peek()?.kind.clone() {
4702 TokenKind::Ident(name) => format!("#{name}"),
4703 _ => "#".to_string(),
4704 };
4705 Err(SyntaxError::new(
4706 format!("unexpected token in expression: '{name}'"),
4707 hash,
4708 ))
4709 }
4710 _ => Err(self.unexpected()),
4711 }
4712 }
4713
4714 #[inline(never)]
4716 fn parse_super(&mut self) -> Result<Expr> {
4717 let start = self.current.span.start;
4718 self.bump()?;
4719 let after = self.current.span;
4725 if self.at_punct(Punct::LParen) {
4726 if !self.ctx.in_derived_constructor {
4727 return Err(self.error_at(
4728 "super() is only valid in a derived class constructor",
4729 after,
4730 ));
4731 }
4732 let arguments = self.parse_arguments()?;
4735 return Ok(Expr::at_operator(
4736 ExprKind::SuperCall(arguments),
4737 self.span_from(start),
4738 after.start,
4739 ));
4740 }
4741 if !self.ctx.in_method {
4742 let message = if self.at_punct(Punct::Dot) || self.at_punct(Punct::LBracket) {
4749 "'super' is only valid in a method"
4750 } else {
4751 "invalid use of 'super'"
4752 };
4753 return Err(self.error_at(message, after));
4754 }
4755 Ok(Expr::new(ExprKind::SuperProp, self.span_from(start)))
4756 }
4757
4758 #[inline(never)]
4760 fn parse_private_in(&mut self, start: Position) -> Result<Expr> {
4761 self.bump()?;
4762 let ident = self.expect_ident()?;
4763 if !self.private.iter().any(|env| env.contains(&ident.name)) {
4764 return Err(self.error_at(
4765 format!(
4766 "private field '#{}' must be declared in an enclosing class",
4767 ident.name
4768 ),
4769 ident.span,
4770 ));
4771 }
4772 if !self.at_keyword(Keyword::In) {
4773 return Err(self.error("expecting 'in' after a private name"));
4774 }
4775 self.bump()?;
4776 if self.at_punct(Punct::Hash) {
4780 let hash = self.current.span;
4781 let name = match self.peek()?.kind.clone() {
4782 TokenKind::Ident(name) => format!("#{name}"),
4783 _ => "#".to_string(),
4784 };
4785 return Err(SyntaxError::new(
4786 format!("unexpected token in expression: '{name}'"),
4787 hash,
4788 ));
4789 }
4790 let object = self.parse_unary()?;
4791 Ok(Expr::new(
4792 ExprKind::PrivateIn {
4793 name: ident,
4794 object: Box::new(object),
4795 },
4796 self.span_from(start),
4797 ))
4798 }
4799
4800 #[inline(never)]
4803 fn parse_regex_literal(&mut self, start: Position) -> Result<Expr> {
4804 let token = self.lexer.re_scan_regex(self.current.span.start)?;
4805 self.current = token;
4806 let TokenKind::RegExp { pattern, flags } = self.current.kind.clone() else {
4807 unreachable!("re_scan_regex returns a RegExp token")
4808 };
4809 let mut seen = 0u8;
4818 for flag in flags.chars() {
4819 let bit = match flag {
4820 'g' => 1 << 0,
4821 'i' => 1 << 1,
4822 'm' => 1 << 2,
4823 's' => 1 << 3,
4824 'y' => 1 << 4,
4825 'u' => 1 << 5,
4826 'd' => 1 << 6,
4827 'v' => 1 << 7,
4828 _ => {
4829 return Err(SyntaxError::new(
4830 "invalid regular expression flags",
4831 self.current.span,
4832 ));
4833 }
4834 };
4835 if seen & bit != 0 {
4836 return Err(SyntaxError::new(
4837 "duplicate regular expression flag",
4838 self.current.span,
4839 ));
4840 }
4841 seen |= bit;
4842 }
4843 if seen & (1 << 5) != 0 && seen & (1 << 7) != 0 {
4845 return Err(SyntaxError::new(
4846 "invalid regular expression flags",
4847 self.current.span,
4848 ));
4849 }
4850 self.bump()?;
4851 Ok(Expr::new(
4852 ExprKind::RegExp { pattern, flags },
4853 self.span_from(start),
4854 ))
4855 }
4856
4857 fn parse_import_expression(&mut self) -> Result<Expr> {
4858 let start = self.current.span.start;
4859 self.bump()?; if self.at_punct(Punct::Dot) {
4861 if !self.module {
4862 return Err(self.error_at(
4863 "import.meta only valid in module code",
4864 self.span_from(start),
4865 ));
4866 }
4867 self.bump()?;
4868 if !self.at_ident("meta") {
4869 return Err(self.error("expecting 'meta' after 'import.'"));
4870 }
4871 self.bump()?;
4872 return Ok(Expr::new(ExprKind::ImportMeta, self.span_from(start)));
4873 }
4874 if self.at_punct(Punct::LParen) {
4875 self.bump()?;
4876 let specifier = self.parse_assignment(true)?;
4877 let mut options = None;
4888 if self.at_punct(Punct::Comma) {
4889 self.bump()?;
4890 if !self.at_punct(Punct::RParen) {
4891 options = Some(Box::new(self.parse_assignment(true)?));
4892 if self.at_punct(Punct::Comma) {
4893 self.bump()?;
4894 }
4895 }
4896 }
4897 self.expect_punct(Punct::RParen)?;
4898 return Ok(Expr::new(
4899 ExprKind::ImportCall(Box::new(specifier), options),
4900 self.span_from(start),
4901 ));
4902 }
4903 Err(self.unexpected())
4904 }
4905
4906 fn parse_array_literal(&mut self) -> Result<Expr> {
4907 let start = self.current.span.start;
4908 self.expect_punct(Punct::LBracket)?;
4909 let mut elements = Vec::new();
4910 let mut spread_comma_closed = false;
4913 while !self.at_punct(Punct::RBracket) {
4914 if self.at_punct(Punct::Comma) {
4915 self.bump()?;
4916 elements.push(None);
4917 spread_comma_closed = false;
4918 continue;
4919 }
4920 let spread = self.at_punct(Punct::Ellipsis);
4921 if spread {
4922 let spread_start = self.current.span.start;
4923 self.bump()?;
4924 let argument = self.parse_assignment(true)?;
4925 elements.push(Some(ArrayElement::Spread(Box::new(Expr::new(
4926 ExprKind::Spread(Box::new(argument)),
4927 self.span_from(spread_start),
4928 )))));
4929 } else {
4930 let expr = self.parse_assignment(true)?;
4931 elements.push(Some(ArrayElement::Expr(Box::new(expr))));
4932 }
4933 if !self.eat_punct(Punct::Comma)? {
4934 break;
4935 }
4936 spread_comma_closed = spread && self.at_punct(Punct::RBracket);
4937 }
4938 self.expect_punct(Punct::RBracket)?;
4939 let span = self.span_from(start);
4940 if spread_comma_closed {
4941 self.spread_trailing_comma.push(span);
4942 }
4943 Ok(Expr::new(ExprKind::Array { elements }, span))
4944 }
4945
4946 fn parse_object_literal(&mut self) -> Result<Expr> {
4947 let start = self.current.span.start;
4948 self.expect_punct(Punct::LBrace)?;
4949 let mut properties: Vec<ObjectProperty> = Vec::new();
4950 let mut proto_count = 0;
4951 let mut spread_comma_closed = false;
4952 while !self.at_punct(Punct::RBrace) {
4953 let property_start = self.current.span.start;
4954 if self.at_punct(Punct::Ellipsis) {
4955 self.bump()?;
4956 let argument = self.parse_assignment(true)?;
4957 properties.push(ObjectProperty::Spread(Box::new(argument)));
4958 } else {
4959 let mut is_async = false;
4960 let mut is_generator = false;
4961 let mut accessor: Option<MethodKind> = None;
4962 if self.at_ident("async") {
4963 let peek = self.peek()?;
4964 let is_modifier = !matches!(
4965 peek.kind,
4966 TokenKind::Punct(Punct::LParen)
4967 | TokenKind::Punct(Punct::Colon)
4968 | TokenKind::Punct(Punct::Comma)
4969 | TokenKind::Punct(Punct::RBrace)
4970 | TokenKind::Punct(Punct::Eq)
4971 ) && !peek.newline_before;
4972 if is_modifier {
4973 self.bump()?;
4974 is_async = true;
4975 }
4976 }
4977 if self.at_punct(Punct::Star) {
4978 self.bump()?;
4979 is_generator = true;
4980 }
4981 if accessor.is_none() && (self.at_ident("get") || self.at_ident("set")) {
4982 let is_get = self.at_ident("get");
4983 let peek = self.peek()?;
4984 if is_property_key_start(&peek.kind) {
4985 self.bump()?;
4986 accessor = Some(if is_get {
4987 MethodKind::Get
4988 } else {
4989 MethodKind::Set
4990 });
4991 }
4992 }
4993 let key = self.parse_property_key()?;
4994 let is_computed = matches!(key, PropName::Computed(_));
4995 if self.at_punct(Punct::LParen) {
4996 let saved = self.ctx;
4997 self.ctx = FnCtx {
4998 in_function: true,
4999 in_generator: is_generator,
5000 in_async: is_async,
5001 in_method: true,
5002 in_derived_constructor: false,
5003 in_static_block: false,
5004 arguments_allowed: true,
5005 };
5006 let saved_top = self.top_level;
5007 self.top_level = false;
5008 let func_result = (|| -> Result<Function> {
5009 let params = self.parse_formal_parameters()?;
5010 let (params, params_span, body, strict) =
5011 self.parse_function_body(params, true)?;
5012 Ok(Function {
5013 name: None,
5014 params,
5015 body,
5016 is_async,
5017 is_generator,
5018 strict,
5019 is_arrow: false,
5020 span: self.span_from(property_start),
5021 params_span,
5022 source_span: None,
5023 })
5024 })();
5025 self.ctx = saved;
5026 self.top_level = saved_top;
5027 let func = func_result?;
5028 let kind = match accessor {
5029 Some(kind) => {
5030 if is_generator || is_async {
5031 return Err(self.error_at(
5032 "accessors may not be generators or async",
5033 func.span,
5034 ));
5035 }
5036 if kind == MethodKind::Get && !func.params.is_empty() {
5037 return Err(self.error_at(
5038 "invalid number of arguments for getter or setter",
5039 func.span,
5040 ));
5041 }
5042 if kind == MethodKind::Set && func.params.len() != 1 {
5043 return Err(self.error_at(
5044 "invalid number of arguments for getter or setter",
5045 func.span,
5046 ));
5047 }
5048 match kind {
5049 MethodKind::Get => PropertyKind::Get,
5050 MethodKind::Set => PropertyKind::Set,
5051 MethodKind::Method | MethodKind::Constructor => {
5052 PropertyKind::Method
5053 }
5054 }
5055 }
5056 None => PropertyKind::Method,
5057 };
5058 let span = self.span_from(property_start);
5059 properties.push(ObjectProperty::Property {
5060 key,
5061 value: Box::new(Expr::new(ExprKind::Function(Box::new(func)), span)),
5062 kind,
5063 shorthand: false,
5064 span,
5065 });
5066 } else if self.eat_punct(Punct::Colon)? {
5067 let value = self.parse_assignment(true)?;
5068 if !is_computed
5069 && let Some(PropKeyRef::Str(name)) = key.static_name()
5070 && name == "__proto__"
5071 {
5072 proto_count += 1;
5073 if proto_count > 1 {
5074 return Err(self.error_at(
5075 "duplicate __proto__ property name",
5076 self.span_from(property_start),
5077 ));
5078 }
5079 }
5080 properties.push(ObjectProperty::Property {
5081 key,
5082 value: Box::new(value),
5083 kind: PropertyKind::Value,
5084 shorthand: false,
5085 span: self.span_from(property_start),
5086 });
5087 } else {
5088 let PropName::Literal(PropKey::Str(name)) = &key else {
5091 return Err(self.error("expecting ':' after a property name"));
5092 };
5093 let ident_span = self.span_from(property_start);
5094 let ident = Ident {
5095 name: name.to_string_lossy().into_owned(),
5099 span: ident_span,
5100 };
5101 self.check_identifier(&ident.name, ident.span)?;
5102 let mut value = Expr::new(ExprKind::Ident(ident.clone()), ident_span);
5103 if self.at_punct(Punct::Eq) {
5104 self.cover_inits.push(ident_span);
5107 self.bump()?;
5108 let default = self.parse_assignment(true)?;
5109 let target = Pattern::new(PatternKind::Ident(ident), ident_span);
5110 value = Expr::new(
5111 ExprKind::Assign {
5112 op: AssignOp::Assign,
5113 target: Box::new(target),
5114 value: Box::new(default),
5115 },
5116 ident_span,
5117 );
5118 }
5119 properties.push(ObjectProperty::Property {
5120 key,
5121 value: Box::new(value),
5122 kind: PropertyKind::Value,
5123 shorthand: true,
5124 span: ident_span,
5125 });
5126 }
5127 }
5128 let spread = matches!(properties.last(), Some(ObjectProperty::Spread(_)));
5131 if !self.eat_punct(Punct::Comma)? {
5132 break;
5133 }
5134 spread_comma_closed = spread && self.at_punct(Punct::RBrace);
5135 }
5136 self.expect_punct(Punct::RBrace)?;
5137 let span = self.span_from(start);
5138 if spread_comma_closed {
5139 self.spread_trailing_comma.push(span);
5140 }
5141 Ok(Expr::new(ExprKind::Object(properties), span))
5142 }
5143
5144 fn parse_template(&mut self) -> Result<TemplateLiteral> {
5145 let mut quasis = Vec::new();
5146 let mut expressions = Vec::new();
5147 loop {
5148 let (cooked, raw, kind) = match self.current.kind.clone() {
5149 TokenKind::Template(chunk) => (chunk.cooked, chunk.raw, chunk.kind),
5150 _ => return Err(self.error("expecting a template literal")),
5151 };
5152 let tail = matches!(kind, TemplateKind::NoSubstitution | TemplateKind::Tail);
5153 quasis.push(TemplateChunk { cooked, raw, tail });
5154 if tail {
5155 self.bump()?;
5156 break;
5157 }
5158 self.bump()?; let expr = self.parse_expression(true)?;
5160 expressions.push(expr);
5161 if !self.at_punct(Punct::RBrace) {
5162 return Err(self.error("expecting '}' in a template substitution"));
5163 }
5164 let brace = self.current.span.start;
5165 let token = self.lexer.re_scan_template_continue(brace)?;
5166 self.current = token;
5167 }
5168 Ok(TemplateLiteral {
5169 quasis,
5170 expressions,
5171 })
5172 }
5173}
5174
5175#[derive(Debug, Clone, Copy, PartialEq, Eq)]
5177enum FunctionForm {
5178 Declaration,
5179 Expression,
5180}
5181
5182fn is_plain_identifier(param: &Pattern) -> bool {
5190 matches!(param.unparen_kind(), PatternKind::Ident(_))
5191}
5192
5193fn parameter_bindings(param: &Pattern) -> Vec<(String, Span, bool)> {
5199 fn walk(pattern: &Pattern, in_pattern: bool, out: &mut Vec<(String, Span, bool)>) {
5200 match &pattern.kind {
5201 PatternKind::Ident(ident) => out.push((ident.name.clone(), ident.span, in_pattern)),
5202 PatternKind::Assign { target, default } => {
5203 walk(target, in_pattern, out);
5204 let _ = default;
5206 }
5207 PatternKind::Rest(target) => walk(target, !is_plain_identifier(target), out),
5208 PatternKind::Array { .. } | PatternKind::Object { .. } => {
5209 let mut names = Vec::new();
5210 pattern.bound_names(&mut names);
5211 for name in names {
5212 out.push((name.name, name.span, true));
5213 }
5214 }
5215 _ => {}
5216 }
5217 }
5218 let mut out = Vec::new();
5219 let in_pattern = !is_plain_identifier(param);
5220 walk(param, in_pattern, &mut out);
5221 if out.is_empty() {
5224 let mut names = Vec::new();
5225 param.bound_names(&mut names);
5226 out.extend(names.into_iter().map(|name| (name.name, name.span, false)));
5227 }
5228 out
5229}
5230
5231fn pattern_has_default(pattern: &Pattern) -> bool {
5237 let element = |element: &Option<PatternElement>| {
5238 element.as_ref().is_some_and(|element| match element {
5239 PatternElement::Pattern(inner) => pattern_has_default(inner),
5240 PatternElement::Property { value, .. } => pattern_has_default(value),
5241 })
5242 };
5243 let rest = |rest: &Option<Box<RestElement>>| {
5244 rest.as_ref().is_some_and(|rest| match rest.as_ref() {
5245 RestElement::Pattern(inner) => pattern_has_default(inner),
5246 RestElement::Member(_) => false,
5247 })
5248 };
5249 match &pattern.kind {
5250 PatternKind::Assign { .. } => true,
5251 PatternKind::Array {
5252 elements,
5253 rest: tail,
5254 } => elements.iter().any(element) || rest(tail),
5255 PatternKind::Object {
5256 properties,
5257 rest: tail,
5258 } => properties.iter().any(element) || rest(tail),
5259 PatternKind::Rest(target) => pattern_has_default(target),
5260 _ => false,
5261 }
5262}
5263
5264fn simple_parameter_names(params: &[Pattern]) -> Vec<String> {
5265 params
5266 .iter()
5267 .filter_map(|param| match ¶m.kind {
5268 PatternKind::Ident(id) => Some(id.name.clone()),
5269 _ => None,
5270 })
5271 .collect()
5272}
5273
5274fn collect_module_binding(stmt: &Stmt, out: &mut Vec<String>) {
5277 match &stmt.kind {
5278 StmtKind::VarDecl(decl) => {
5279 if decl.kind.is_using() {
5285 return;
5286 }
5287 for declarator in &decl.declarators {
5288 let mut names = Vec::new();
5289 declarator.target.bound_names(&mut names);
5290 out.extend(names.into_iter().map(|n| n.name));
5291 }
5292 }
5293 StmtKind::FuncDecl(func) => {
5294 if let Some(name) = &func.name {
5295 out.push(name.name.clone());
5296 }
5297 }
5298 StmtKind::ClassDecl(class) => {
5299 if let Some(name) = &class.name {
5300 out.push(name.name.clone());
5301 }
5302 }
5303 StmtKind::Import(decl) => {
5304 for specifier in &decl.specifiers {
5305 match specifier {
5306 ImportSpecifier::Default(id) => out.push(id.name.clone()),
5307 ImportSpecifier::Namespace(id) => out.push(id.name.clone()),
5308 ImportSpecifier::Named { local, .. } => out.push(local.name.clone()),
5309 }
5310 }
5311 }
5312 StmtKind::Export(decl) => match &decl.kind {
5313 ExportKind::Declaration(inner) => collect_module_binding(inner, out),
5314 ExportKind::Default(expr) => match &expr.unparen().kind {
5315 ExprKind::Function(func) => {
5316 if let Some(name) = &func.name {
5317 out.push(name.name.clone());
5318 }
5319 }
5320 ExprKind::Class(class) => {
5321 if let Some(name) = &class.name {
5322 out.push(name.name.clone());
5323 }
5324 }
5325 _ => {}
5326 },
5327 _ => {}
5328 },
5329 _ => {}
5330 }
5331}
5332
5333fn span_contains(outer: Span, inner: Span) -> bool {
5335 inner.start.offset >= outer.start.offset && inner.end.offset <= outer.end.offset
5336}
5337
5338fn is_property_key_start(kind: &TokenKind) -> bool {
5339 matches!(
5340 kind,
5341 TokenKind::Ident(_)
5342 | TokenKind::Keyword(_)
5343 | TokenKind::String(_)
5344 | TokenKind::Number(_)
5345 | TokenKind::Punct(Punct::LBracket)
5346 | TokenKind::Punct(Punct::Hash)
5347 )
5348}
5349
5350#[derive(Debug, Clone, Copy)]
5352enum BinOp {
5353 Binary(BinaryOp),
5354 Logical(LogicalOp),
5355}
5356
5357impl BinOp {
5358 fn is_right_associative(self) -> bool {
5359 matches!(self, BinOp::Binary(BinaryOp::Pow))
5360 }
5361}
5362
5363fn binary_operator(kind: &TokenKind, allow_in: bool) -> Option<(u8, BinOp)> {
5364 use BinaryOp as B;
5365 use LogicalOp as L;
5366 let result = match kind {
5367 TokenKind::Punct(Punct::QuestionQuestion) => (1, BinOp::Logical(L::Coalesce)),
5368 TokenKind::Punct(Punct::PipePipe) => (2, BinOp::Logical(L::Or)),
5369 TokenKind::Punct(Punct::AmpAmp) => (3, BinOp::Logical(L::And)),
5370 TokenKind::Punct(Punct::Pipe) => (4, BinOp::Binary(B::BitOr)),
5371 TokenKind::Punct(Punct::Caret) => (5, BinOp::Binary(B::BitXor)),
5372 TokenKind::Punct(Punct::Amp) => (6, BinOp::Binary(B::BitAnd)),
5373 TokenKind::Punct(Punct::EqEq) => (7, BinOp::Binary(B::Eq)),
5374 TokenKind::Punct(Punct::NotEq) => (7, BinOp::Binary(B::NotEq)),
5375 TokenKind::Punct(Punct::EqEqEq) => (7, BinOp::Binary(B::StrictEq)),
5376 TokenKind::Punct(Punct::NotEqEq) => (7, BinOp::Binary(B::StrictNotEq)),
5377 TokenKind::Punct(Punct::Lt) => (8, BinOp::Binary(B::Lt)),
5378 TokenKind::Punct(Punct::LtEq) => (8, BinOp::Binary(B::LtEq)),
5379 TokenKind::Punct(Punct::Gt) => (8, BinOp::Binary(B::Gt)),
5380 TokenKind::Punct(Punct::GtEq) => (8, BinOp::Binary(B::GtEq)),
5381 TokenKind::Keyword(Keyword::Instanceof) => (8, BinOp::Binary(B::Instanceof)),
5382 TokenKind::Keyword(Keyword::In) if allow_in => (8, BinOp::Binary(B::In)),
5383 TokenKind::Punct(Punct::Shl) => (9, BinOp::Binary(B::Shl)),
5384 TokenKind::Punct(Punct::Shr) => (9, BinOp::Binary(B::Shr)),
5385 TokenKind::Punct(Punct::UShr) => (9, BinOp::Binary(B::UShr)),
5386 TokenKind::Punct(Punct::Plus) => (10, BinOp::Binary(B::Add)),
5387 TokenKind::Punct(Punct::Minus) => (10, BinOp::Binary(B::Sub)),
5388 TokenKind::Punct(Punct::Star) => (11, BinOp::Binary(B::Mul)),
5389 TokenKind::Punct(Punct::Slash) => (11, BinOp::Binary(B::Div)),
5390 TokenKind::Punct(Punct::Percent) => (11, BinOp::Binary(B::Mod)),
5391 TokenKind::Punct(Punct::StarStar) => (12, BinOp::Binary(B::Pow)),
5392 _ => return None,
5393 };
5394 Some(result)
5395}
5396
5397fn build_binary(op: BinOp, left: Expr, right: Expr, span: Span, op_pos: Position) -> Result<Expr> {
5398 match op {
5399 BinOp::Binary(op) => Ok(Expr::at_operator(
5400 ExprKind::Binary {
5401 op,
5402 left: Box::new(left),
5403 right: Box::new(right),
5404 },
5405 span,
5406 op_pos,
5407 )),
5408 BinOp::Logical(op) => {
5409 let mixes = |expr: &Expr, op: LogicalOp| {
5413 matches!(&expr.kind, ExprKind::Logical { op: inner, .. }
5414 if (op == LogicalOp::Coalesce) != (*inner == LogicalOp::Coalesce))
5415 };
5416 if mixes(&left, op) || mixes(&right, op) {
5417 return Err(SyntaxError::new(
5418 "cannot mix ?? with && or ||",
5421 span,
5422 ));
5423 }
5424 Ok(Expr::at_operator(
5425 ExprKind::Logical {
5426 op,
5427 left: Box::new(left),
5428 right: Box::new(right),
5429 },
5430 span,
5431 op_pos,
5432 ))
5433 }
5434 }
5435}
5436
5437fn pattern_to_expr(pattern: Pattern, span: Span) -> Expr {
5440 match pattern.kind {
5441 PatternKind::Ident(ident) => Expr::new(ExprKind::Ident(ident), span),
5442 PatternKind::Assign { target, default } => Expr::new(
5443 ExprKind::Assign {
5444 op: AssignOp::Assign,
5445 target,
5446 value: default,
5447 },
5448 span,
5449 ),
5450 PatternKind::Member(member) => {
5454 let MemberPattern {
5455 object,
5456 property,
5457 span,
5458 op_pos,
5459 } = *member;
5460 Expr {
5461 kind: ExprKind::Member {
5462 object,
5463 property,
5464 optional: false,
5465 },
5466 span,
5467 op_pos,
5468 }
5469 }
5470 PatternKind::Object { properties, rest } => {
5471 let mut out = Vec::new();
5472 for element in properties {
5473 match element {
5474 Some(PatternElement::Property {
5475 key,
5476 value,
5477 shorthand,
5478 span: _,
5479 }) => {
5480 let span = value.span;
5481 out.push(ObjectProperty::Property {
5482 key,
5483 value: Box::new(pattern_to_expr(value, span)),
5484 kind: PropertyKind::Value,
5485 shorthand,
5486 span,
5487 });
5488 }
5489 None | Some(PatternElement::Pattern(_)) => {}
5492 }
5493 }
5494 if let Some(rest) = rest
5495 && let RestElement::Pattern(pattern) = *rest
5496 {
5497 let span = pattern.span;
5498 out.push(ObjectProperty::Spread(Box::new(pattern_to_expr(
5499 pattern, span,
5500 ))));
5501 }
5502 Expr::new(ExprKind::Object(out), span)
5503 }
5504 PatternKind::Array { elements, rest } => {
5505 let mut out = Vec::new();
5506 for element in elements {
5507 match element {
5508 Some(PatternElement::Pattern(pattern)) => {
5509 let span = pattern.span;
5510 out.push(Some(ArrayElement::Expr(Box::new(pattern_to_expr(
5511 pattern, span,
5512 )))));
5513 }
5514 Some(PatternElement::Property { .. }) | None => out.push(None),
5515 }
5516 }
5517 if let Some(rest) = rest {
5518 let RestElement::Pattern(pattern) = *rest else {
5519 return Expr::new(ExprKind::Null, span);
5520 };
5521 let span = pattern.span;
5522 out.push(Some(ArrayElement::Spread(Box::new(pattern_to_expr(
5523 pattern, span,
5524 )))));
5525 }
5526 Expr::new(ExprKind::Array { elements: out }, span)
5527 }
5528 _ => Expr::new(ExprKind::Null, span),
5529 }
5530}
5531
5532impl Pattern {
5533 fn unparen_kind(&self) -> &PatternKind {
5536 &self.kind
5537 }
5538}
5539
5540fn member_chain_import_call(expr: &Expr) -> Option<&Expr> {
5558 match &expr.kind {
5559 ExprKind::ImportCall(..) => Some(expr),
5560 ExprKind::Member { object, .. } => member_chain_import_call(object),
5561 _ => None,
5563 }
5564}
5565
5566fn deletes_a_private_member(expr: &Expr) -> bool {
5567 match &expr.unparen().kind {
5568 ExprKind::Member { property, .. } => matches!(property, MemberProp::Private(_)),
5569 ExprKind::Call { callee, .. } => deletes_a_private_member(callee),
5570 _ => false,
5571 }
5572}
5573
5574fn as_specifier(value: &Wtf8) -> String {
5581 value.to_string_lossy().into_owned()
5582}