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 pending_exports: Vec<(String, Span)>,
58 current_legacy_octal: bool,
59 scopes: Vec<Scope>,
60}
61
62#[derive(Debug, Clone, Copy)]
64struct FnCtx {
65 in_function: bool,
66 in_generator: bool,
67 in_async: bool,
68 in_method: bool,
70 in_derived_constructor: bool,
72 in_static_block: bool,
80 arguments_allowed: bool,
84}
85
86impl Default for FnCtx {
87 fn default() -> FnCtx {
88 FnCtx {
89 in_function: false,
90 in_generator: false,
91 in_async: false,
92 in_method: false,
93 in_derived_constructor: false,
94 in_static_block: false,
95 arguments_allowed: true,
98 }
99 }
100}
101
102#[derive(Debug, Clone, Copy, PartialEq, Eq)]
103enum LabelKind {
104 Iteration,
106 Other,
108}
109
110#[derive(Debug, Clone)]
111struct Label {
112 name: String,
113 kind: LabelKind,
114}
115
116#[derive(Debug, Clone, Default)]
118struct PrivateEnv {
119 names: Vec<PrivateName>,
120 pending: Vec<(String, Span)>,
128}
129
130#[derive(Debug, Clone)]
131struct PrivateName {
132 name: String,
133 has_get: bool,
134 has_set: bool,
135 is_accessor: bool,
141 accessor_is_static: bool,
147}
148
149impl PrivateEnv {
150 fn declare(&mut self, name: &str, accessor: Option<MethodKind>, is_static: bool) -> bool {
158 if let Some(existing) = self.names.iter_mut().find(|n| n.name == name) {
159 return match accessor {
160 Some(MethodKind::Get)
161 if existing.is_accessor
162 && !existing.has_get
163 && existing.accessor_is_static == is_static =>
164 {
165 existing.has_get = true;
166 true
167 }
168 Some(MethodKind::Set)
169 if existing.is_accessor
170 && !existing.has_set
171 && existing.accessor_is_static == is_static =>
172 {
173 existing.has_set = true;
174 true
175 }
176 _ => false,
177 };
178 }
179 let mut entry = PrivateName {
180 name: name.to_string(),
181 has_get: false,
182 has_set: false,
183 is_accessor: accessor.is_some(),
184 accessor_is_static: is_static,
185 };
186 match accessor {
187 Some(MethodKind::Get) => entry.has_get = true,
188 Some(MethodKind::Set) => entry.has_set = true,
189 _ => {}
190 }
191 self.names.push(entry);
192 true
193 }
194
195 fn contains(&self, name: &str) -> bool {
196 self.names.iter().any(|n| n.name == name)
197 }
198
199 fn from_names(names: &[String]) -> PrivateEnv {
208 PrivateEnv {
209 names: names
210 .iter()
211 .map(|name| PrivateName {
212 name: name.strip_prefix('#').unwrap_or(name).to_string(),
213 has_get: true,
214 has_set: true,
215 is_accessor: true,
216 accessor_is_static: false,
217 })
218 .collect(),
219 pending: Vec::new(),
220 }
221 }
222}
223
224#[derive(Debug, Clone, Copy, PartialEq, Eq)]
238enum Redefinition {
239 Lexical,
240 Global,
241 Variable,
242 Parameter,
243}
244
245impl Redefinition {
246 fn message(self) -> &'static str {
247 match self {
248 Redefinition::Lexical => "invalid redefinition of lexical identifier",
249 Redefinition::Global => "invalid redefinition of global identifier",
250 Redefinition::Variable => "invalid redefinition of a variable",
251 Redefinition::Parameter => "invalid redefinition of parameter name",
252 }
253 }
254}
255
256#[derive(Debug, Clone)]
257struct Scope {
258 is_var_scope: bool,
260 var_names: Vec<String>,
262 var_names_here: Vec<String>,
270 lex_names: Vec<String>,
272 fn_names: Vec<String>,
279 params: Vec<String>,
281 catch_names: Vec<String>,
289 plain_fn_names: Vec<String>,
298 import_names: Vec<String>,
305}
306
307impl Scope {
308 fn block() -> Scope {
309 Scope {
310 is_var_scope: false,
311 var_names: Vec::new(),
312 var_names_here: Vec::new(),
313 lex_names: Vec::new(),
314 fn_names: Vec::new(),
315 params: Vec::new(),
316 catch_names: Vec::new(),
317 plain_fn_names: Vec::new(),
318 import_names: Vec::new(),
319 }
320 }
321
322 fn function(params: Vec<String>) -> Scope {
323 Scope {
324 is_var_scope: true,
325 var_names: Vec::new(),
326 var_names_here: Vec::new(),
327 lex_names: Vec::new(),
328 fn_names: Vec::new(),
329 params,
330 catch_names: Vec::new(),
331 plain_fn_names: Vec::new(),
332 import_names: Vec::new(),
333 }
334 }
335}
336
337#[derive(Debug, Clone, Copy, PartialEq, Eq)]
339enum TargetKind {
340 Binding,
342 Assignment,
344}
345
346struct ArrowHead {
348 params: Vec<Pattern>,
349 is_async: bool,
350 span: Span,
351 params_span: Span,
352}
353
354pub const DEFAULT_MAX_DEPTH: u32 = if cfg!(debug_assertions) { 120 } else { 600 };
368
369pub struct Parser<'a> {
371 lexer: Lexer<'a>,
372 current: Token,
373 prev_end: Position,
374 strict: bool,
375 module: bool,
376 allow_in: bool,
377 ctx: FnCtx,
378 loop_depth: u32,
379 switch_depth: u32,
380 labels: Vec<Label>,
381 private: Vec<PrivateEnv>,
382 top_level: bool,
383 current_legacy_octal: bool,
386 in_case_clause: bool,
392 depth: u32,
395 max_depth: u32,
396
397 cover_inits: Vec<Span>,
401 pending_exports: Vec<(String, Span)>,
404 in_formal_parameters: bool,
414 scopes: Vec<Scope>,
416}
417
418pub fn parse_script(src: &str) -> Result<Program> {
420 Parser::new(src, false)?.parse_program()
421}
422
423pub fn parse_module(src: &str) -> Result<Program> {
425 Parser::new(src, true)?.parse_program()
426}
427
428pub fn parse_suspensible_script(src: &str) -> Result<Program> {
437 Parser::new_suspensible(src)?.parse_program()
438}
439
440pub fn parse_script_strict(src: &str) -> Result<Program> {
448 let mut parser = Parser::new(src, false)?;
449 parser.enter_strict()?;
450 parser.parse_program()
451}
452
453pub fn parse_eval_script(src: &str, strict: bool) -> Result<Program> {
460 parse_eval_script_in(src, strict, EvalContext::default())
461}
462
463#[derive(Debug, Clone, Default)]
465pub struct EvalContext {
466 pub in_method: bool,
469 pub in_derived_constructor: bool,
471 pub private_names: Vec<String>,
481 pub arguments_allowed: bool,
487 pub new_target_allowed: bool,
493}
494
495pub fn parse_eval_script_in(src: &str, strict: bool, context: EvalContext) -> Result<Program> {
501 let mut parser = Parser::new(src, false)?;
502 parser.ctx.in_function = context.new_target_allowed;
506 parser.ctx.in_method = context.in_method;
507 parser.ctx.in_derived_constructor = context.in_derived_constructor;
508 parser.ctx.arguments_allowed = context.arguments_allowed;
509 if !context.private_names.is_empty() {
513 parser
514 .private
515 .push(PrivateEnv::from_names(&context.private_names));
516 }
517 if strict {
518 parser.enter_strict()?;
519 }
520 parser.parse_program()
521}
522
523pub fn parse_suspensible_global_eval(src: &str, strict: bool) -> Result<Program> {
531 let mut parser = Parser::new_suspensible(src)?;
532 if strict {
533 parser.enter_strict()?;
534 }
535 parser.parse_program()
536}
537
538pub fn parse_expression(src: &str) -> Result<Expr> {
541 let mut parser = Parser::new(src, false)?;
542 let expr = parser.parse_expression(true)?;
543 if !parser.current.is_eof() {
544 return Err(parser.unexpected());
545 }
546 Ok(expr)
547}
548
549impl<'a> Parser<'a> {
550 pub fn new(src: &'a str, module: bool) -> Result<Parser<'a>> {
557 Parser::with_modes(src, module, false)
558 }
559
560 pub fn new_suspensible(src: &'a str) -> Result<Parser<'a>> {
567 Parser::with_modes(src, false, true)
568 }
569
570 fn with_modes(src: &'a str, module: bool, async_body: bool) -> Result<Parser<'a>> {
571 let mut lexer = Lexer::new(src);
572 lexer.set_strict(module);
573 let current = lexer.next_token()?;
574 let current_legacy_octal = lexer.had_legacy_octal();
575 if module && current_legacy_octal {
576 return Err(SyntaxError::new(
577 "octal literals and octal escape sequences are not allowed in strict mode",
578 current.span,
579 ));
580 }
581 Ok(Parser {
582 lexer,
583 current,
584 prev_end: Position::START,
585 strict: module,
586 module,
587 allow_in: true,
588 ctx: FnCtx {
589 in_async: module || async_body,
590 ..FnCtx::default()
591 },
592 loop_depth: 0,
593 switch_depth: 0,
594 labels: Vec::new(),
595 private: Vec::new(),
596 top_level: true,
597 current_legacy_octal,
598 in_case_clause: false,
599 depth: 0,
600 max_depth: DEFAULT_MAX_DEPTH,
601
602 cover_inits: Vec::new(),
603 pending_exports: Vec::new(),
604 in_formal_parameters: false,
605 scopes: vec![Scope::function(Vec::new())],
606 })
607 }
608
609 pub fn set_max_depth(&mut self, depth: u32) {
611 self.max_depth = depth;
612 }
613
614 fn enter(&mut self) -> Result<()> {
616 self.depth += 1;
617 if self.depth > self.max_depth {
618 return Err(SyntaxError::new("stack overflow", self.current.span));
619 }
620 Ok(())
621 }
622
623 fn leave(&mut self) {
624 self.depth -= 1;
625 }
626
627 pub fn parse_program(&mut self) -> Result<Program> {
629 let start = self.current.span.start;
630 let mut body = Vec::new();
631 let mut prologue = true;
632 while !self.current.is_eof() {
633 let stmt = self.parse_statement_list_item()?;
634 if prologue {
635 match self.directive_value(&stmt) {
636 Some(directive) if directive == "use strict" => self.enter_strict()?,
637 Some(_) => {}
638 None => prologue = false,
639 }
640 }
641 body.push(stmt);
642 }
643 if self.module {
644 self.check_module_exports(&body)?;
645 }
646 Ok(Program {
647 kind: if self.module {
648 ProgramKind::Module
649 } else {
650 ProgramKind::Script
651 },
652 body,
653 span: Span::new(start, self.prev_end),
654 strict: self.strict,
655 })
656 }
657
658 fn check_module_exports(&mut self, body: &[Stmt]) -> Result<()> {
661 if self.pending_exports.is_empty() {
662 return Ok(());
663 }
664 let mut declared: Vec<String> = Vec::new();
665 for stmt in body {
666 collect_module_binding(stmt, &mut declared);
667 }
668 let pending = std::mem::take(&mut self.pending_exports);
669 for (name, span) in pending {
670 if !declared.contains(&name) {
671 return Err(self
674 .error_at(format!("exported variable '{name}' does not exist"), span)
675 .positionless());
676 }
677 }
678 Ok(())
679 }
680
681 fn push_scope(&mut self, scope: Scope) {
684 self.scopes.push(scope);
685 }
686
687 fn pop_scope(&mut self) {
688 self.scopes.pop();
689 }
690
691 fn declare_lexical(&mut self, name: &str) -> Result<()> {
698 let Some(scope) = self.scopes.last() else {
699 return Ok(());
700 };
701 let reason = if scope.lex_names.iter().any(|n| n == name)
704 || scope.catch_names.iter().any(|n| n == name)
705 {
706 Some(Redefinition::Lexical)
707 } else if scope.params.iter().any(|n| n == name) {
708 Some(Redefinition::Parameter)
709 } else if scope.fn_names.iter().any(|n| n == name)
710 || scope.var_names.iter().any(|n| n == name)
711 {
712 Some(if self.at_top_level_scope() {
717 Redefinition::Global
718 } else {
719 Redefinition::Variable
720 })
721 } else {
722 None
723 };
724 if let Some(reason) = reason {
725 return Err(self.duplicate_declaration(reason));
726 }
727 if let Some(scope) = self.scopes.last_mut() {
728 scope.lex_names.push(name.to_string());
729 }
730 Ok(())
731 }
732
733 fn declare_var(&mut self, name: &str) -> Result<()> {
736 for scope in self.scopes.iter().rev() {
737 if scope.lex_names.iter().any(|n| n == name) {
738 return Err(self.duplicate_declaration(Redefinition::Lexical));
739 }
740 if scope.is_var_scope {
741 break;
742 }
743 }
744 let Some(index) = self.scopes.iter().rposition(|s| s.is_var_scope) else {
745 return Ok(());
746 };
747 for scope in &mut self.scopes[index..] {
750 if !scope.var_names.iter().any(|n| n == name) {
751 scope.var_names.push(name.to_string());
752 }
753 }
754 if let Some(scope) = self.scopes.last_mut()
755 && !scope.var_names_here.iter().any(|n| n == name)
756 {
757 scope.var_names_here.push(name.to_string());
758 }
759 Ok(())
760 }
761
762 fn check_duplicate_parameters(
783 &self,
784 params: &[Pattern],
785 plain_is_illegal: bool,
786 deferred_at: Span,
787 ) -> Result<()> {
788 let has_default = params.iter().any(pattern_has_default);
789 let mut seen: Vec<String> = Vec::new();
790 let mut deferred = false;
791 for param in params {
792 for (name, span, in_pattern) in parameter_bindings(param) {
793 if seen.iter().any(|seen| seen == &name) {
794 if has_default || in_pattern {
795 return Err(self.error_at(
796 "duplicate parameter names not allowed in this context".to_string(),
797 span,
798 ));
799 }
800 deferred = true;
801 }
802 seen.push(name);
803 }
804 }
805 if deferred && plain_is_illegal {
806 return Err(self.error_at(
807 "duplicate argument names not allowed in this context".to_string(),
808 deferred_at,
809 ));
810 }
811 Ok(())
812 }
813
814 fn declare_function(&mut self, name: &str) -> Result<()> {
830 if !self.scopes.last().is_none_or(|scope| scope.is_var_scope) {
831 return Ok(());
832 }
833 if !self.at_top_level_scope()
839 && self
840 .scopes
841 .last()
842 .is_some_and(|scope| scope.lex_names.iter().any(|n| n == name))
843 {
844 return Err(self.duplicate_declaration(Redefinition::Lexical));
845 }
846 if let Some(scope) = self.scopes.last_mut() {
847 if !scope.var_names.iter().any(|n| n == name) {
848 scope.var_names.push(name.to_string());
849 }
850 if !scope.fn_names.iter().any(|n| n == name) {
851 scope.fn_names.push(name.to_string());
852 }
853 }
854 Ok(())
855 }
856
857 fn declare_block_function(&mut self, name: &str, is_plain: bool) -> Result<()> {
866 if self.module
874 && self.at_top_level_scope()
875 && let Some(scope) = self.scopes.last()
876 {
877 let mut taken = scope.var_names_here.iter().any(|existing| existing == name);
883 if scope.is_var_scope {
884 let module_bindings = scope
885 .lex_names
886 .iter()
887 .filter(|existing| !scope.import_names.contains(existing))
888 .chain(&scope.fn_names);
889 taken |= module_bindings.into_iter().any(|existing| existing == name);
890 }
891 if taken {
892 return Err(self.error_at(
893 "invalid redefinition of global identifier in module code",
894 self.current.span,
895 ));
896 }
897 }
898 if self.scopes.last().is_none_or(|scope| scope.is_var_scope) {
899 return Ok(());
900 }
901 let Some(scope) = self.scopes.last() else {
902 return Ok(());
903 };
904 if scope.lex_names.iter().any(|n| n == name) || scope.catch_names.iter().any(|n| n == name)
905 {
906 let from_plain_function = scope.plain_fn_names.iter().any(|n| n == name);
910 if !(from_plain_function && is_plain && !self.strict) {
911 return Err(self.duplicate_declaration(Redefinition::Lexical));
912 }
913 } else if scope.var_names.iter().any(|n| n == name) {
914 let reason = if self.at_top_level_scope() {
918 Redefinition::Global
919 } else {
920 Redefinition::Variable
921 };
922 return Err(self.duplicate_declaration(reason));
923 }
924 if let Some(scope) = self.scopes.last_mut() {
925 if !scope.lex_names.iter().any(|n| n == name) {
926 scope.lex_names.push(name.to_string());
927 }
928 if !scope.fn_names.iter().any(|n| n == name) {
929 scope.fn_names.push(name.to_string());
930 }
931 if is_plain && !scope.plain_fn_names.iter().any(|n| n == name) {
932 scope.plain_fn_names.push(name.to_string());
933 }
934 }
935 Ok(())
936 }
937
938 fn duplicate_declaration(&self, reason: Redefinition) -> SyntaxError {
950 self.error_at(reason.message(), self.current.span)
951 }
952
953 fn at_top_level_scope(&self) -> bool {
959 self.scopes.iter().rposition(|scope| scope.is_var_scope) == Some(0)
960 }
961
962 fn declare_pattern(&mut self, pattern: &Pattern, is_var: bool) -> Result<()> {
964 let mut names = Vec::new();
965 pattern.bound_names(&mut names);
966 for name in names {
967 if is_var {
968 self.declare_var(&name.name)?;
969 } else {
970 self.declare_lexical(&name.name)?;
971 }
972 }
973 Ok(())
974 }
975
976 fn snapshot(&self) -> Snapshot<'a> {
979 Snapshot {
980 lexer: self.lexer.clone(),
981 current: self.current.clone(),
982 prev_end: self.prev_end,
983 strict: self.strict,
984 allow_in: self.allow_in,
985 ctx: self.ctx,
986 loop_depth: self.loop_depth,
987 switch_depth: self.switch_depth,
988 labels: self.labels.clone(),
989 private: self.private.clone(),
990 top_level: self.top_level,
991 cover_inits: self.cover_inits.clone(),
992 pending_exports: self.pending_exports.clone(),
993 current_legacy_octal: self.current_legacy_octal,
994 scopes: self.scopes.clone(),
995 }
996 }
997
998 fn restore(&mut self, snap: Snapshot<'a>) {
999 self.lexer = snap.lexer;
1000 self.current = snap.current;
1001 self.prev_end = snap.prev_end;
1002 self.strict = snap.strict;
1003 self.allow_in = snap.allow_in;
1004 self.ctx = snap.ctx;
1005 self.loop_depth = snap.loop_depth;
1006 self.switch_depth = snap.switch_depth;
1007 self.labels = snap.labels;
1008 self.private = snap.private;
1009 self.top_level = snap.top_level;
1010 self.cover_inits = snap.cover_inits;
1011 self.pending_exports = snap.pending_exports;
1012 self.current_legacy_octal = snap.current_legacy_octal;
1013 self.scopes = snap.scopes;
1014 }
1015
1016 fn bump(&mut self) -> Result<()> {
1017 self.prev_end = self.current.span.end;
1018 self.current = self.lexer.next_token()?;
1019 self.current_legacy_octal = self.lexer.had_legacy_octal();
1020 if self.strict && self.current_legacy_octal {
1021 return Err(SyntaxError::new(
1022 "octal literals and octal escape sequences are not allowed in strict mode",
1023 self.current.span,
1024 ));
1025 }
1026 Ok(())
1027 }
1028
1029 fn peek(&self) -> Result<Token> {
1030 let mut lexer = self.lexer.clone();
1031 lexer.next_token()
1032 }
1033
1034 fn enter_strict(&mut self) -> Result<()> {
1035 self.strict = true;
1036 self.lexer.set_strict(true);
1037 if self.current_legacy_octal {
1040 return Err(SyntaxError::new(
1041 "octal literals and octal escape sequences are not allowed in strict mode",
1042 self.current.span,
1043 ));
1044 }
1045 Ok(())
1046 }
1047
1048 fn at_punct(&self, p: Punct) -> bool {
1049 matches!(&self.current.kind, TokenKind::Punct(q) if *q == p)
1050 }
1051
1052 fn at_keyword(&self, k: Keyword) -> bool {
1053 matches!(&self.current.kind, TokenKind::Keyword(q) if *q == k)
1054 }
1055
1056 fn at_contextual(&self, name: &str) -> bool {
1057 self.at_ident(name)
1058 }
1059
1060 fn at_ident(&self, name: &str) -> bool {
1067 !self.current.escaped && matches!(&self.current.kind, TokenKind::Ident(n) if n == name)
1068 }
1069
1070 fn eat_punct(&mut self, p: Punct) -> Result<bool> {
1071 if self.at_punct(p) {
1072 self.bump()?;
1073 return Ok(true);
1074 }
1075 Ok(false)
1076 }
1077
1078 fn expect_punct(&mut self, p: Punct) -> Result<()> {
1079 if self.eat_punct(p)? {
1080 Ok(())
1081 } else {
1082 Err(self.error(format!("expecting '{}'", p.as_str())))
1087 }
1088 }
1089
1090 fn eat_keyword(&mut self, k: Keyword) -> Result<bool> {
1091 if self.at_keyword(k) {
1092 self.bump()?;
1093 return Ok(true);
1094 }
1095 Ok(false)
1096 }
1097
1098 fn eat_contextual(&mut self, name: &str) -> Result<bool> {
1099 if self.at_ident(name) {
1100 self.bump()?;
1101 return Ok(true);
1102 }
1103 Ok(false)
1104 }
1105
1106 fn unexpected(&self) -> SyntaxError {
1113 let source = self.lexer.source();
1114 let start = self.current.span.start.offset as usize;
1115 let end = self.current.span.end.offset as usize;
1116 let text = source.get(start..end).unwrap_or("");
1117 SyntaxError::new(
1118 format!("unexpected token in expression: '{text}'"),
1119 self.current.span,
1120 )
1121 }
1122
1123 fn error(&self, message: impl Into<String>) -> SyntaxError {
1124 SyntaxError::new(message, self.current.span)
1125 }
1126
1127 fn error_at(&self, message: impl Into<String>, span: Span) -> SyntaxError {
1128 SyntaxError::new(message, span)
1129 }
1130
1131 fn span_from(&self, start: Position) -> Span {
1132 Span::new(start, self.prev_end)
1133 }
1134
1135 fn expect_binding_ident(&mut self) -> Result<Ident> {
1138 let ident = self.expect_ident()?;
1139 self.check_binding_name(&ident.name, ident.span)?;
1140 Ok(ident)
1141 }
1142
1143 fn expect_ident(&mut self) -> Result<Ident> {
1145 match self.current.kind.clone() {
1146 TokenKind::Ident(name) => {
1147 if name == "await" && self.await_is_reserved() {
1150 return Err(self.error("variable name expected"));
1151 }
1152 let span = self.current.span;
1153 self.check_identifier(&name, span)?;
1154 self.bump()?;
1155 Ok(Ident { name, span })
1156 }
1157 _ => Err(self.error("variable name expected")),
1160 }
1161 }
1162
1163 fn at_formal_parameter(&self) -> bool {
1170 if self.at_punct(Punct::LBracket) || self.at_punct(Punct::LBrace) {
1171 return true;
1172 }
1173 match &self.current.kind {
1174 TokenKind::Ident(name) => !(name == "await" && self.await_is_reserved()),
1175 _ => false,
1176 }
1177 }
1178
1179 fn await_is_reserved(&self) -> bool {
1189 self.ctx.in_async || self.module || self.ctx.in_static_block
1192 }
1193
1194 fn check_identifier(&self, name: &str, span: Span) -> Result<()> {
1196 if Keyword::lookup(name).is_some() {
1197 return Err(self.error_at(format!("unexpected keyword '{name}'"), span));
1198 }
1199 if self.strict && Keyword::is_strict_reserved(name) {
1200 return Err(self.error_at(
1201 format!("invalid use of strict mode reserved word '{name}'"),
1202 span,
1203 ));
1204 }
1205 if self.ctx.in_generator && name == "yield" {
1206 return Err(self.error_at(
1207 "invalid use of 'yield' identifier in a generator function",
1208 span,
1209 ));
1210 }
1211 if name == "await" && self.await_is_reserved() {
1212 return Err(self.error_at("unexpected 'await' keyword", span));
1217 }
1218 Ok(())
1219 }
1220
1221 fn check_arguments_reference(&self, name: &str, span: Span) -> Result<()> {
1228 if name == "arguments" && !self.ctx.arguments_allowed {
1229 return Err(self.error_at(
1230 "'arguments' identifier is not allowed in class field initializer",
1231 span,
1232 ));
1233 }
1234 Ok(())
1235 }
1236
1237 fn check_binding_name(&self, name: &str, span: Span) -> Result<()> {
1240 self.check_identifier(name, span)?;
1241 if self.strict && (name == "eval" || name == "arguments") {
1242 return Err(self.error_at("invalid variable name in strict mode", span));
1245 }
1246 if self.strict && name == "let" {
1247 return Err(self.error_at(
1248 "invalid use of 'let' as a variable name in strict mode",
1249 span,
1250 ));
1251 }
1252 Ok(())
1253 }
1254
1255 fn directive_value(&self, stmt: &Stmt) -> Option<String> {
1258 let StmtKind::Expr(expr) = &stmt.kind else {
1259 return None;
1260 };
1261 let ExprKind::String(value) = &expr.unparen().kind else {
1262 return None;
1263 };
1264 let raw = self.slice(expr.span);
1265 if !raw.starts_with('"') && !raw.starts_with('\'') {
1266 return None;
1267 }
1268 if raw.trim_matches(|c| c == '"' || c == '\'').contains('\\') {
1269 return None;
1270 }
1271 Some(value.to_string_lossy().into_owned())
1274 }
1275
1276 fn slice(&self, span: Span) -> &'a str {
1277 let src = self.lexer.source();
1278 let start = span.start.offset as usize;
1279 let end = (span.end.offset as usize).min(src.len());
1280 src.get(start..end).unwrap_or("")
1281 }
1282
1283 fn can_insert_semicolon(&self) -> bool {
1286 self.current.is_eof() || self.at_punct(Punct::RBrace) || self.current.newline_before
1287 }
1288
1289 fn semicolon(&mut self) -> Result<()> {
1290 if self.eat_punct(Punct::Semicolon)? {
1291 return Ok(());
1292 }
1293 if self.can_insert_semicolon() {
1294 return Ok(());
1295 }
1296 Err(self.error("expecting ';'"))
1299 }
1300
1301 fn parse_statement_list_item(&mut self) -> Result<Stmt> {
1304 self.enter()?;
1305 let result = self.parse_statement_list_item_guarded();
1306 self.leave();
1307 result
1308 }
1309
1310 fn parse_statement_list_item_guarded(&mut self) -> Result<Stmt> {
1311 let cover_mark = self.cover_inits.len();
1312 let stmt = self.parse_statement_list_item_inner()?;
1313 if self.cover_inits.len() > cover_mark {
1314 let span = self.cover_inits[cover_mark];
1315 self.cover_inits.truncate(cover_mark);
1316 return Err(self.error_at("expecting '}'", span));
1317 }
1318 Ok(stmt)
1319 }
1320
1321 fn parse_statement_list_item_inner(&mut self) -> Result<Stmt> {
1322 if self.at_keyword(Keyword::Function) {
1323 let start = self.current.span.start;
1324 let func = self.parse_function(FunctionForm::Declaration, false, None)?;
1325 if let Some(name) = &func.name {
1326 self.declare_function(&name.name)?;
1327 }
1328 return Ok(Stmt::new(
1329 StmtKind::FuncDecl(Box::new(func)),
1330 self.span_from(start),
1331 ));
1332 }
1333 if self.at_ident("async") {
1334 let peek = self.peek()?;
1335 if matches!(peek.kind, TokenKind::Keyword(Keyword::Function)) && !peek.newline_before {
1336 let start = self.current.span.start;
1337 self.bump()?; let func = self.parse_function(FunctionForm::Declaration, true, Some(start))?;
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 }
1348 if self.at_keyword(Keyword::Class) {
1349 let start = self.current.span.start;
1350 let class = self.parse_class(false)?;
1351 if let Some(name) = &class.name {
1352 self.declare_lexical(&name.name)?;
1353 }
1354 return Ok(Stmt::new(
1355 StmtKind::ClassDecl(Box::new(class)),
1356 self.span_from(start),
1357 ));
1358 }
1359 if self.at_keyword(Keyword::Var) {
1360 let start = self.current.span.start;
1361 let decl = self.parse_var_decl(VarDeclKind::Var, false, true)?;
1362 self.semicolon()?;
1363 return Ok(Stmt::new(StmtKind::VarDecl(decl), self.span_from(start)));
1364 }
1365 if self.at_keyword(Keyword::Const) {
1366 let start = self.current.span.start;
1367 let decl = self.parse_var_decl(VarDeclKind::Const, false, true)?;
1368 self.semicolon()?;
1369 return Ok(Stmt::new(StmtKind::VarDecl(decl), self.span_from(start)));
1370 }
1371 if self.at_ident("let") && self.let_starts_declaration()? {
1372 let start = self.current.span.start;
1373 let decl = self.parse_var_decl(VarDeclKind::Let, false, true)?;
1374 self.semicolon()?;
1375 return Ok(Stmt::new(StmtKind::VarDecl(decl), self.span_from(start)));
1376 }
1377 if self.at_ident("await") && self.ctx.in_async && self.await_using_follows()? {
1380 let start = self.current.span.start;
1381 self.bump()?; let decl = self.parse_var_decl_with_keyword(VarDeclKind::AwaitUsing, "using")?;
1386 self.semicolon()?;
1387 return Ok(Stmt::new(StmtKind::VarDecl(decl), self.span_from(start)));
1388 }
1389 if self.at_ident("using") && self.using_starts_declaration()? {
1390 let start = self.current.span.start;
1391 if self.scopes.len() == 1 && !self.module {
1397 return Err(self.error_at(
1398 "using declaration is not allowed at the top level of a script",
1399 self.span_from(start),
1400 ));
1401 }
1402 if self.in_case_clause {
1407 return Err(self.error_at(
1408 "using declaration is not allowed in this context",
1409 self.span_from(start),
1410 ));
1411 }
1412 let decl = self.parse_var_decl(VarDeclKind::Using, false, true)?;
1413 self.semicolon()?;
1414 return Ok(Stmt::new(StmtKind::VarDecl(decl), self.span_from(start)));
1415 }
1416 let at_module_top_level = self.module && self.scopes.len() == 1;
1423 if at_module_top_level && self.at_keyword(Keyword::Import) {
1424 let peek = self.peek()?;
1425 if !matches!(
1427 peek.kind,
1428 TokenKind::Punct(Punct::LParen) | TokenKind::Punct(Punct::Dot)
1429 ) {
1430 return self.parse_import_decl();
1431 }
1432 }
1433 if at_module_top_level && self.at_keyword(Keyword::Export) {
1434 return self.parse_export_decl();
1435 }
1436 self.parse_statement()
1437 }
1438
1439 fn let_starts_declaration(&self) -> Result<bool> {
1441 let peek = self.peek()?;
1442 Ok(matches!(
1443 peek.kind,
1444 TokenKind::Ident(_)
1445 | TokenKind::Punct(Punct::LBracket)
1446 | TokenKind::Punct(Punct::LBrace)
1447 ))
1448 }
1449
1450 fn using_head_tail(&self, skip: usize) -> Result<Option<Token>> {
1456 let mut lexer = self.lexer.clone();
1457 let mut binding = None;
1461 for _ in 0..=skip {
1462 binding = Some(lexer.next_token()?);
1463 }
1464 let Some(binding) = binding else {
1465 return Ok(None);
1466 };
1467 if binding.newline_before || !matches!(binding.kind, TokenKind::Ident(_)) {
1468 return Ok(None);
1469 }
1470 Ok(Some(lexer.next_token()?))
1471 }
1472
1473 fn await_using_follows(&self) -> Result<bool> {
1479 Ok(matches!(
1480 self.using_head_tail(1)?.map(|token| token.kind),
1481 Some(TokenKind::Punct(Punct::Eq))
1482 ))
1483 }
1484
1485 fn using_starts_declaration(&self) -> Result<bool> {
1496 Ok(matches!(
1497 self.using_head_tail(0)?.map(|token| token.kind),
1498 Some(TokenKind::Punct(Punct::Eq))
1499 ))
1500 }
1501
1502 fn using_starts_for_head(&self) -> Result<bool> {
1507 Ok(matches!(
1508 self.using_head_tail(0)?.map(|token| token.kind),
1509 Some(TokenKind::Ident(name)) if name == "of" || name == "in"
1510 ))
1511 }
1512
1513 fn await_using_starts_for_head(&self) -> Result<bool> {
1515 Ok(matches!(
1516 self.using_head_tail(1)?.map(|token| token.kind),
1517 Some(TokenKind::Ident(name)) if name == "of" || name == "in"
1518 ))
1519 }
1520
1521 fn parse_statement(&mut self) -> Result<Stmt> {
1522 let start = self.current.span.start;
1523 if self.at_punct(Punct::Semicolon) {
1524 self.bump()?;
1525 return Ok(Stmt::new(StmtKind::Empty, self.span_from(start)));
1526 }
1527 if self.at_punct(Punct::LBrace) {
1528 let body = self.parse_block()?;
1529 return Ok(Stmt::new(StmtKind::Block(body), self.span_from(start)));
1530 }
1531 if self.at_keyword(Keyword::If) {
1532 return self.parse_if();
1533 }
1534 if self.at_keyword(Keyword::Do) {
1535 return self.parse_do_while();
1536 }
1537 if self.at_keyword(Keyword::While) {
1538 return self.parse_while();
1539 }
1540 if self.at_keyword(Keyword::For) {
1541 return self.parse_for();
1542 }
1543 if self.at_keyword(Keyword::Switch) {
1544 return self.parse_switch();
1545 }
1546 if self.at_keyword(Keyword::Try) {
1547 return self.parse_try();
1548 }
1549 if self.at_keyword(Keyword::Return) {
1550 return self.parse_return();
1551 }
1552 if self.at_keyword(Keyword::Throw) {
1553 return self.parse_throw();
1554 }
1555 if self.at_keyword(Keyword::Break) {
1556 return self.parse_break_continue(true);
1557 }
1558 if self.at_keyword(Keyword::Continue) {
1559 return self.parse_break_continue(false);
1560 }
1561 if self.at_keyword(Keyword::With) {
1562 return self.parse_with();
1563 }
1564 if self.at_keyword(Keyword::Debugger) {
1565 self.bump()?;
1566 self.semicolon()?;
1567 return Ok(Stmt::new(StmtKind::Debugger, self.span_from(start)));
1568 }
1569 if self.at_keyword(Keyword::Function) {
1570 if self.strict {
1573 return Err(
1574 self.error("invalid 'function' declaration in a single statement context")
1575 );
1576 }
1577 let func = self.parse_function(FunctionForm::Declaration, false, None)?;
1578 if let Some(name) = &func.name {
1579 self.declare_function(&name.name)?;
1580 }
1581 return Ok(Stmt::new(
1582 StmtKind::FuncDecl(Box::new(func)),
1583 self.span_from(start),
1584 ));
1585 }
1586 if self.at_keyword(Keyword::Class) {
1587 return Err(self.error("invalid 'class' declaration in a single statement context"));
1588 }
1589 if self.at_keyword(Keyword::Import) {
1590 let peek = self.peek()?;
1594 let expression = matches!(
1595 peek.kind,
1596 TokenKind::Punct(Punct::LParen) | TokenKind::Punct(Punct::Dot)
1597 );
1598 if !expression {
1599 return Err(self.error("'import' can only appear at the top level of a module"));
1600 }
1601 }
1602 if self.at_keyword(Keyword::Export) {
1603 return Err(self.error("'export' can only appear at the top level of a module"));
1604 }
1605 if let TokenKind::Ident(name) = &self.current.kind {
1607 if name == "await" && self.await_is_reserved() {
1611 if !self.ctx.in_async {
1612 let peek = self.peek()?;
1615 if matches!(peek.kind, TokenKind::Punct(Punct::Colon)) {
1616 return Err(self.error("unexpected 'await' keyword"));
1617 }
1618 }
1619 } else {
1623 let peek = self.peek()?;
1624 if matches!(peek.kind, TokenKind::Punct(Punct::Colon)) {
1625 return self.parse_labeled();
1626 }
1627 }
1628 }
1629 self.parse_expression_statement()
1630 }
1631
1632 fn parse_block(&mut self) -> Result<Vec<Stmt>> {
1633 self.expect_punct(Punct::LBrace)?;
1634 self.push_scope(Scope::block());
1635 let saved_in_case = self.in_case_clause;
1638 self.in_case_clause = false;
1639 let result = self.parse_block_body();
1640 self.in_case_clause = saved_in_case;
1641 self.pop_scope();
1642 let body = result?;
1643 self.bump()?; Ok(body)
1645 }
1646
1647 fn parse_catch_body(&mut self) -> Result<Vec<Stmt>> {
1649 self.expect_punct(Punct::LBrace)?;
1650 let body = self.parse_block_body()?;
1651 self.bump()?; Ok(body)
1653 }
1654
1655 fn parse_block_body(&mut self) -> Result<Vec<Stmt>> {
1656 let mut body = Vec::new();
1657 while !self.at_punct(Punct::RBrace) {
1658 if self.current.is_eof() {
1659 return Err(self.unexpected());
1660 }
1661 body.push(self.parse_statement_list_item()?);
1662 }
1663 Ok(body)
1664 }
1665
1666 fn parse_expression_statement(&mut self) -> Result<Stmt> {
1667 let start = self.current.span.start;
1668 let expr = self.parse_expression(true)?;
1669 self.semicolon()?;
1670 Ok(Stmt::new(
1671 StmtKind::Expr(Box::new(expr)),
1672 self.span_from(start),
1673 ))
1674 }
1675
1676 fn parse_if(&mut self) -> Result<Stmt> {
1677 let start = self.current.span.start;
1678 self.bump()?; self.expect_punct(Punct::LParen)?;
1680 let test = self.parse_expression(true)?;
1681 self.expect_punct(Punct::RParen)?;
1682 let cons = self.parse_statement()?;
1683 let alt = if self.eat_keyword(Keyword::Else)? {
1684 Some(Box::new(self.parse_statement()?))
1685 } else {
1686 None
1687 };
1688 Ok(Stmt::new(
1689 StmtKind::If {
1690 test: Box::new(test),
1691 cons: Box::new(cons),
1692 alt,
1693 },
1694 self.span_from(start),
1695 ))
1696 }
1697
1698 fn parse_do_while(&mut self) -> Result<Stmt> {
1699 let start = self.current.span.start;
1700 self.bump()?; self.loop_depth += 1;
1702 let body = self.parse_statement();
1703 self.loop_depth -= 1;
1704 let body = body?;
1705 if !self.eat_keyword(Keyword::While)? {
1706 return Err(self.unexpected());
1707 }
1708 self.expect_punct(Punct::LParen)?;
1709 let test = self.parse_expression(true)?;
1710 self.expect_punct(Punct::RParen)?;
1711 let _ = self.eat_punct(Punct::Semicolon)?;
1713 Ok(Stmt::new(
1714 StmtKind::DoWhile {
1715 body: Box::new(body),
1716 test: Box::new(test),
1717 },
1718 self.span_from(start),
1719 ))
1720 }
1721
1722 fn parse_while(&mut self) -> Result<Stmt> {
1723 let start = self.current.span.start;
1724 self.bump()?; self.expect_punct(Punct::LParen)?;
1726 let test = self.parse_expression(true)?;
1727 self.expect_punct(Punct::RParen)?;
1728 self.loop_depth += 1;
1729 let body = self.parse_statement();
1730 self.loop_depth -= 1;
1731 Ok(Stmt::new(
1732 StmtKind::While {
1733 test: Box::new(test),
1734 body: Box::new(body?),
1735 },
1736 self.span_from(start),
1737 ))
1738 }
1739
1740 fn parse_for(&mut self) -> Result<Stmt> {
1741 let start = self.current.span.start;
1742 self.bump()?; self.push_scope(Scope::block());
1744 let result = self.parse_for_inner(start);
1745 self.pop_scope();
1746 result
1747 }
1748
1749 fn parse_for_inner(&mut self, start: Position) -> Result<Stmt> {
1750 let mut is_await = false;
1751 if self.at_ident("await") && self.ctx.in_async {
1752 let peek = self.peek()?;
1753 if matches!(peek.kind, TokenKind::Punct(Punct::LParen)) && !peek.newline_before {
1754 is_await = true;
1755 self.bump()?;
1756 }
1757 }
1758 self.expect_punct(Punct::LParen)?;
1759
1760 if self.at_punct(Punct::Semicolon) {
1762 self.bump()?;
1763 return self.parse_for_classic(start, None);
1764 }
1765
1766 let decl_kind = if self.at_keyword(Keyword::Var) {
1768 Some(VarDeclKind::Var)
1769 } else if self.at_keyword(Keyword::Const) {
1770 Some(VarDeclKind::Const)
1771 } else if self.at_ident("let") && self.let_starts_declaration()? {
1772 Some(VarDeclKind::Let)
1773 } else if self.at_ident("using") && self.using_starts_for_head()? {
1774 Some(VarDeclKind::Using)
1775 } else if self.at_ident("await")
1776 && self.ctx.in_async
1777 && self.await_using_starts_for_head()?
1778 {
1779 self.bump()?; Some(VarDeclKind::AwaitUsing)
1781 } else {
1782 None
1783 };
1784 if let Some(kind) = decl_kind {
1785 let decl_start = self.current.span.start;
1786 let decl = self.parse_var_decl(kind, true, false)?;
1787 if self.at_for_head_keyword() {
1788 let is_of = self.at_contextual("of");
1789 if !is_of && decl.declarators.len() != 1 {
1790 return Err(self.error_at(
1791 "only one binding allowed in a for-in loop",
1792 self.span_from(decl_start),
1793 ));
1794 }
1795 if is_of && decl.declarators.len() != 1 {
1796 return Err(self.error_at(
1797 "only one binding allowed in a for-of loop",
1798 self.span_from(decl_start),
1799 ));
1800 }
1801 if let Some(declarator) = decl.declarators.first() {
1802 if declarator.init.is_some() {
1803 if is_of || kind.is_lexical() || self.strict {
1805 return Err(self.error_at(
1806 if is_of {
1807 "a declaration in the head of a for-of loop can't have an initializer"
1809 } else {
1810 "a declaration in the head of a for-in loop can't have an initializer"
1811 },
1812 declarator.span,
1813 ));
1814 }
1815 }
1816 }
1817 if is_await && !is_of {
1818 return Err(self.error("for await is only valid with 'of'"));
1819 }
1820 self.bump()?; let right = self.parse_expression(true)?;
1822 self.expect_punct(Punct::RParen)?;
1823 self.loop_depth += 1;
1824 let body = self.parse_statement();
1825 self.loop_depth -= 1;
1826 let head = ForHead::VarDecl(decl);
1827 let span = self.span_from(start);
1828 return Ok(Stmt::new(
1829 if is_of {
1830 StmtKind::ForOf {
1831 is_await,
1832 left: head,
1833 right: Box::new(right),
1834 body: Box::new(body?),
1835 }
1836 } else {
1837 StmtKind::ForIn {
1838 left: head,
1839 right: Box::new(right),
1840 body: Box::new(body?),
1841 }
1842 },
1843 span,
1844 ));
1845 }
1846 self.expect_punct(Punct::Semicolon)?;
1847 return self.parse_for_classic(start, Some(ForInit::VarDecl(decl)));
1848 }
1849
1850 let expr_start = self.current.span.start;
1852 let expr = self.parse_expression(false)?;
1853 if self.at_for_head_keyword() {
1854 let is_of = self.at_contextual("of");
1855 if is_await && !is_of {
1856 return Err(self.error("for await is only valid with 'of'"));
1857 }
1858 let target = self.expr_to_pattern(expr, TargetKind::Assignment)?;
1859 self.bump()?; let right = self.parse_expression(true)?;
1861 self.expect_punct(Punct::RParen)?;
1862 self.loop_depth += 1;
1863 let body = self.parse_statement();
1864 self.loop_depth -= 1;
1865 let head = ForHead::Assign(Box::new(target));
1866 let span = self.span_from(start);
1867 return Ok(Stmt::new(
1868 if is_of {
1869 StmtKind::ForOf {
1870 is_await,
1871 left: head,
1872 right: Box::new(right),
1873 body: Box::new(body?),
1874 }
1875 } else {
1876 StmtKind::ForIn {
1877 left: head,
1878 right: Box::new(right),
1879 body: Box::new(body?),
1880 }
1881 },
1882 span,
1883 ));
1884 }
1885 let _ = expr_start;
1886 self.expect_punct(Punct::Semicolon)?;
1887 self.parse_for_classic(start, Some(ForInit::Expr(Box::new(expr))))
1888 }
1889
1890 fn at_for_head_keyword(&self) -> bool {
1893 self.at_keyword(Keyword::In) || self.at_contextual("of")
1894 }
1895
1896 fn parse_for_classic(&mut self, start: Position, init: Option<ForInit>) -> Result<Stmt> {
1897 let test = if self.at_punct(Punct::Semicolon) {
1898 None
1899 } else {
1900 Some(Box::new(self.parse_expression(true)?))
1901 };
1902 self.expect_punct(Punct::Semicolon)?;
1903 let update = if self.at_punct(Punct::RParen) {
1904 None
1905 } else {
1906 Some(Box::new(self.parse_expression(true)?))
1907 };
1908 self.expect_punct(Punct::RParen)?;
1909 self.loop_depth += 1;
1910 let body = self.parse_statement();
1911 self.loop_depth -= 1;
1912 Ok(Stmt::new(
1913 StmtKind::For {
1914 init,
1915 test,
1916 update,
1917 body: Box::new(body?),
1918 },
1919 self.span_from(start),
1920 ))
1921 }
1922
1923 fn parse_switch(&mut self) -> Result<Stmt> {
1924 let start = self.current.span.start;
1925 self.bump()?; self.expect_punct(Punct::LParen)?;
1927 let discriminant = self.parse_expression(true)?;
1928 self.expect_punct(Punct::RParen)?;
1929 self.expect_punct(Punct::LBrace)?;
1930 self.switch_depth += 1;
1931 self.push_scope(Scope::block());
1932 let mut cases = Vec::new();
1933 let mut seen_default = false;
1934 while !self.at_punct(Punct::RBrace) {
1935 if self.current.is_eof() {
1936 self.switch_depth -= 1;
1937 return Err(self.unexpected());
1938 }
1939 let case_start = self.current.span.start;
1940 let test = if self.eat_keyword(Keyword::Case)? {
1941 Some(Box::new(self.parse_expression(true)?))
1942 } else if self.eat_keyword(Keyword::Default)? {
1943 if seen_default {
1944 self.switch_depth -= 1;
1945 return Err(self.error("duplicate 'default' clause in switch statement"));
1946 }
1947 seen_default = true;
1948 None
1949 } else {
1950 self.switch_depth -= 1;
1951 return Err(self.unexpected());
1952 };
1953 self.expect_punct(Punct::Colon)?;
1954 let mut body = Vec::new();
1955 let saved_in_case = self.in_case_clause;
1956 self.in_case_clause = true;
1957 while !self.at_punct(Punct::RBrace)
1958 && !self.at_keyword(Keyword::Case)
1959 && !self.at_keyword(Keyword::Default)
1960 {
1961 if self.current.is_eof() {
1962 self.in_case_clause = saved_in_case;
1963 self.switch_depth -= 1;
1964 return Err(self.unexpected());
1965 }
1966 match self.parse_statement_list_item() {
1967 Ok(stmt) => body.push(stmt),
1968 Err(error) => {
1969 self.in_case_clause = saved_in_case;
1970 self.switch_depth -= 1;
1971 return Err(error);
1972 }
1973 }
1974 }
1975 self.in_case_clause = saved_in_case;
1976 cases.push(SwitchCase {
1977 test,
1978 body,
1979 span: self.span_from(case_start),
1980 });
1981 }
1982 self.switch_depth -= 1;
1983 self.bump()?; self.pop_scope();
1992 Ok(Stmt::new(
1993 StmtKind::Switch {
1994 discriminant: Box::new(discriminant),
1995 cases,
1996 },
1997 self.span_from(start),
1998 ))
1999 }
2000
2001 fn parse_try(&mut self) -> Result<Stmt> {
2002 let start = self.current.span.start;
2003 self.bump()?; let block = self.parse_block()?;
2005 let mut handler = None;
2006 let mut finalizer = None;
2007 if self.at_keyword(Keyword::Catch) {
2008 let catch_start = self.current.span.start;
2009 self.bump()?;
2010 let param = if self.eat_punct(Punct::LParen)? {
2016 let pattern = self.parse_binding_target()?;
2017 self.expect_punct(Punct::RParen)?;
2018 Some(pattern)
2019 } else {
2020 None
2021 };
2022 self.push_scope(Scope::block());
2023 let body = match ¶m {
2024 Some(Pattern {
2027 kind: PatternKind::Ident(id),
2028 ..
2029 }) => {
2030 if let Some(scope) = self.scopes.last_mut() {
2031 scope.catch_names.push(id.name.clone());
2032 }
2033 self.parse_catch_body()
2034 }
2035 Some(pattern) => {
2040 self.declare_pattern(pattern, false)?;
2041 self.parse_block()
2042 }
2043 None => self.parse_catch_body(),
2044 };
2045 self.pop_scope();
2046 let body = body?;
2047 handler = Some(CatchClause {
2048 param,
2049 body,
2050 span: self.span_from(catch_start),
2051 });
2052 }
2053 if self.eat_keyword(Keyword::Finally)? {
2054 finalizer = Some(self.parse_block()?);
2055 }
2056 if handler.is_none() && finalizer.is_none() {
2057 return Err(self.error("expecting catch or finally"));
2058 }
2059 Ok(Stmt::new(
2060 StmtKind::Try {
2061 block,
2062 handler,
2063 finalizer,
2064 },
2065 self.span_from(start),
2066 ))
2067 }
2068
2069 fn parse_return(&mut self) -> Result<Stmt> {
2070 let start = self.current.span.start;
2071 let span = self.current.span;
2072 if !self.ctx.in_function {
2073 return Err(self.error_at("return not in a function", span));
2074 }
2075 if self.ctx.in_static_block {
2076 return Err(self.error_at("return in a static initializer block", span));
2080 }
2081 self.bump()?;
2082 let argument = if self.at_punct(Punct::Semicolon)
2083 || self.at_punct(Punct::RBrace)
2084 || self.current.is_eof()
2085 || self.current.newline_before
2086 {
2087 None
2088 } else {
2089 Some(Box::new(self.parse_expression(true)?))
2090 };
2091 self.semicolon()?;
2092 Ok(Stmt::new(StmtKind::Return(argument), self.span_from(start)))
2093 }
2094
2095 fn parse_throw(&mut self) -> Result<Stmt> {
2096 let start = self.current.span.start;
2097 self.bump()?; if self.current.newline_before {
2099 return Err(self.error("line terminator not allowed after 'throw'"));
2100 }
2101 let argument = self.parse_expression(true)?;
2102 self.semicolon()?;
2103 Ok(Stmt::new(
2104 StmtKind::Throw(Box::new(argument)),
2105 self.span_from(start),
2106 ))
2107 }
2108
2109 fn parse_break_continue(&mut self, is_break: bool) -> Result<Stmt> {
2110 let start = self.current.span.start;
2111 let keyword_span = self.current.span;
2112 self.bump()?;
2113 let label = if matches!(self.current.kind, TokenKind::Ident(_))
2114 && !self.current.newline_before
2115 {
2116 let ident = self.expect_ident()?;
2117 let found = self.labels.iter().rev().find(|l| l.name == ident.name);
2118 match found {
2119 None => {
2120 return Err(
2121 self.error_at(format!("label '{}' not found", ident.name), ident.span)
2122 );
2123 }
2124 Some(label) => {
2125 if !is_break && label.kind != LabelKind::Iteration {
2126 return Err(self.error_at(
2127 format!("continue must be inside loop (label '{}')", ident.name),
2128 ident.span,
2129 ));
2130 }
2131 }
2132 }
2133 Some(ident)
2134 } else {
2135 if !is_break && self.loop_depth == 0 {
2136 return Err(self.error_at("continue must be inside loop", keyword_span));
2137 }
2138 if is_break && self.loop_depth == 0 && self.switch_depth == 0 && self.labels.is_empty()
2139 {
2140 return Err(self.error_at("break must be inside loop or switch", keyword_span));
2141 }
2142 None
2143 };
2144 self.semicolon()?;
2145 Ok(Stmt::new(
2146 if is_break {
2147 StmtKind::Break(label)
2148 } else {
2149 StmtKind::Continue(label)
2150 },
2151 self.span_from(start),
2152 ))
2153 }
2154
2155 fn parse_with(&mut self) -> Result<Stmt> {
2156 let start = self.current.span.start;
2157 let span = self.current.span;
2158 if self.strict {
2159 return Err(self.error_at("invalid keyword: with", span));
2160 }
2161 self.bump()?; self.expect_punct(Punct::LParen)?;
2163 let object = self.parse_expression(true)?;
2164 self.expect_punct(Punct::RParen)?;
2165 let body = self.parse_statement()?;
2166 Ok(Stmt::new(
2167 StmtKind::With {
2168 object: Box::new(object),
2169 body: Box::new(body),
2170 },
2171 self.span_from(start),
2172 ))
2173 }
2174
2175 fn parse_labeled(&mut self) -> Result<Stmt> {
2176 let start = self.current.span.start;
2177 let label = self.expect_ident()?;
2178 self.expect_punct(Punct::Colon)?;
2179 if self.labels.iter().any(|l| l.name == label.name) {
2180 return Err(self.error_at(
2181 format!("label '{}' already declared", label.name),
2182 label.span,
2183 ));
2184 }
2185 let kind = if self.at_keyword(Keyword::For)
2186 || self.at_keyword(Keyword::While)
2187 || self.at_keyword(Keyword::Do)
2188 {
2189 LabelKind::Iteration
2190 } else {
2191 LabelKind::Other
2192 };
2193 self.labels.push(Label {
2194 name: label.name.clone(),
2195 kind,
2196 });
2197 let body = self.parse_statement();
2198 self.labels.pop();
2199 Ok(Stmt::new(
2200 StmtKind::Labeled {
2201 label,
2202 body: Box::new(body?),
2203 },
2204 self.span_from(start),
2205 ))
2206 }
2207
2208 fn parse_var_decl(
2211 &mut self,
2212 kind: VarDeclKind,
2213 in_for_head: bool,
2214 require_init: bool,
2215 ) -> Result<VarDecl> {
2216 let start = self.current.span.start;
2217 self.bump()?; self.parse_var_declarators(kind, in_for_head, require_init, start)
2219 }
2220
2221 fn parse_var_decl_with_keyword(&mut self, kind: VarDeclKind, keyword: &str) -> Result<VarDecl> {
2226 let start = self.current.span.start;
2227 if !self.at_ident(keyword) {
2228 return Err(self.error(format!("expected '{keyword}'")));
2229 }
2230 self.bump()?;
2231 self.parse_var_declarators(kind, false, true, start)
2232 }
2233
2234 fn parse_var_declarators(
2235 &mut self,
2236 kind: VarDeclKind,
2237 in_for_head: bool,
2238 require_init: bool,
2239 start: Position,
2240 ) -> Result<VarDecl> {
2241 let mut declarators = Vec::new();
2242 loop {
2243 let declarator_start = self.current.span.start;
2244 let target = self.parse_binding_target()?;
2245 self.declare_pattern(&target, !kind.is_lexical())?;
2250 if kind.is_using() && !matches!(target.unparen_kind(), PatternKind::Ident(_)) {
2253 return Err(self.error_at(
2254 "binding patterns are not allowed in using declarations",
2255 target.span,
2256 ));
2257 }
2258 let init = if self.eat_punct(Punct::Eq)? {
2259 Some(Box::new(self.parse_assignment(!in_for_head)?))
2262 } else {
2263 None
2264 };
2265 if init.is_none() && require_init {
2266 if kind == VarDeclKind::Const {
2267 return Err(self.error("missing initializer for const variable"));
2268 }
2269 if kind.is_using() {
2270 return Err(self.error("missing initializer in using declaration"));
2271 }
2272 if !matches!(target.unparen_kind(), PatternKind::Ident(_)) && !in_for_head {
2273 return Err(self.error_at(
2274 "missing initializer in destructuring declaration",
2275 target.span,
2276 ));
2277 }
2278 }
2279 if kind.is_lexical() {
2280 let mut names = Vec::new();
2281 target.bound_names(&mut names);
2282 if let Some(name) = names.iter().find(|n| n.name == "let") {
2283 return Err(self.error_at("'let' is not a valid lexical identifier", name.span));
2284 }
2285 }
2286 declarators.push(Declarator {
2287 target,
2288 init,
2289 span: self.span_from(declarator_start),
2290 });
2291 if !self.eat_punct(Punct::Comma)? {
2292 break;
2293 }
2294 }
2295 Ok(VarDecl {
2296 kind,
2297 declarators,
2298 span: self.span_from(start),
2299 })
2300 }
2301
2302 fn parse_binding_element(&mut self) -> Result<Pattern> {
2305 let pattern = self.parse_binding_target()?;
2306 if self.eat_punct(Punct::Eq)? {
2307 let start = pattern.span.start;
2308 let default = self.parse_assignment(self.allow_in)?;
2309 return Ok(Pattern::new(
2310 PatternKind::Assign {
2311 target: Box::new(pattern),
2312 default: Box::new(default),
2313 },
2314 self.span_from(start),
2315 ));
2316 }
2317 Ok(pattern)
2318 }
2319
2320 fn parse_binding_target(&mut self) -> Result<Pattern> {
2323 self.enter()?;
2324 let result = self.parse_binding_target_unguarded();
2325 self.leave();
2326 result
2327 }
2328
2329 fn parse_binding_target_unguarded(&mut self) -> Result<Pattern> {
2330 let start = self.current.span.start;
2331 if self.at_punct(Punct::LBracket) {
2332 return self.parse_array_pattern(start);
2333 }
2334 if self.at_punct(Punct::LBrace) {
2335 return self.parse_object_pattern(start);
2336 }
2337 let ident = self.expect_binding_ident()?;
2338 Ok(Pattern::new(
2339 PatternKind::Ident(ident),
2340 self.span_from(start),
2341 ))
2342 }
2343
2344 fn parse_array_pattern(&mut self, start: Position) -> Result<Pattern> {
2345 self.expect_punct(Punct::LBracket)?;
2346 let mut elements = Vec::new();
2347 let mut rest = None;
2348 loop {
2349 if self.at_punct(Punct::RBracket) {
2350 break;
2351 }
2352 if self.at_punct(Punct::Comma) {
2353 self.bump()?;
2354 elements.push(None);
2355 continue;
2356 }
2357 if self.at_punct(Punct::Ellipsis) {
2358 self.bump()?;
2359 let target = self.parse_binding_target()?;
2360 if self.at_punct(Punct::Comma) {
2361 return Err(self.error("rest element must be the last one"));
2362 }
2363 rest = Some(Box::new(RestElement::Pattern(target)));
2364 break;
2365 }
2366 let element_start = self.current.span.start;
2367 let element = self.parse_binding_element()?;
2368 let span = self.span_from(element_start);
2369 elements.push(Some(PatternElement::Pattern(element)));
2370 let _ = span;
2371 if !self.eat_punct(Punct::Comma)? {
2372 break;
2373 }
2374 }
2375 self.expect_punct(Punct::RBracket)?;
2376 Ok(Pattern::new(
2377 PatternKind::Array { elements, rest },
2378 self.span_from(start),
2379 ))
2380 }
2381
2382 fn parse_object_pattern(&mut self, start: Position) -> Result<Pattern> {
2383 self.expect_punct(Punct::LBrace)?;
2384 let mut properties = Vec::new();
2385 let mut rest = None;
2386 loop {
2387 if self.at_punct(Punct::RBrace) {
2388 break;
2389 }
2390 if self.at_punct(Punct::Ellipsis) {
2391 self.bump()?;
2392 let target = self.parse_binding_target()?;
2393 rest = Some(Box::new(RestElement::Pattern(target)));
2394 if self.at_punct(Punct::Comma) {
2395 return Err(self.error("rest element must be the last one"));
2396 }
2397 break;
2398 }
2399 let property_start = self.current.span.start;
2400 let key = self.parse_property_key()?;
2401 if self.eat_punct(Punct::Colon)? {
2402 let value = self.parse_binding_element()?;
2403 properties.push(Some(PatternElement::Property {
2404 key,
2405 value,
2406 shorthand: false,
2407 span: self.span_from(property_start),
2408 }));
2409 } else {
2410 let PropName::Literal(PropKey::Str(name)) = &key else {
2411 return Err(
2412 self.error("expecting ':' after a computed or numeric property key")
2413 );
2414 };
2415 let span = self.span_from(property_start);
2416 let ident = Ident {
2417 name: name.to_string_lossy().into_owned(),
2418 span,
2419 };
2420 self.check_binding_name(&ident.name, ident.span)?;
2421 let mut value = Pattern::new(PatternKind::Ident(ident), span);
2422 if self.eat_punct(Punct::Eq)? {
2423 let default = self.parse_assignment(self.allow_in)?;
2424 value = Pattern::new(
2425 PatternKind::Assign {
2426 target: Box::new(value),
2427 default: Box::new(default),
2428 },
2429 span,
2430 );
2431 }
2432 properties.push(Some(PatternElement::Property {
2433 key,
2434 value,
2435 shorthand: true,
2436 span,
2437 }));
2438 }
2439 if !self.eat_punct(Punct::Comma)? {
2440 break;
2441 }
2442 }
2443 self.expect_punct(Punct::RBrace)?;
2444 Ok(Pattern::new(
2445 PatternKind::Object { properties, rest },
2446 self.span_from(start),
2447 ))
2448 }
2449
2450 fn parse_property_key(&mut self) -> Result<PropName> {
2452 match self.current.kind.clone() {
2453 TokenKind::Ident(name) => {
2454 self.bump()?;
2455 Ok(PropName::Literal(PropKey::Str(Wtf8::new(name))))
2456 }
2457 TokenKind::Keyword(kw) => {
2458 self.bump()?;
2460 Ok(PropName::Literal(PropKey::Str(Wtf8::new(kw.as_str()))))
2461 }
2462 TokenKind::String(value) => {
2463 self.bump()?;
2464 Ok(PropName::Literal(PropKey::Str(value)))
2465 }
2466 TokenKind::Number(NumberLiteral::Int(v)) => {
2467 self.bump()?;
2468 Ok(PropName::Literal(PropKey::Num(v as f64)))
2469 }
2470 TokenKind::Number(NumberLiteral::Float(v)) => {
2471 self.bump()?;
2472 Ok(PropName::Literal(PropKey::Num(v)))
2473 }
2474 TokenKind::BigInt(big) => Err(self.error(format!(
2475 "BigInt property keys are not supported ('{}n')",
2476 big.digits
2477 ))),
2478 TokenKind::Punct(Punct::LBracket) => {
2479 self.bump()?;
2480 let expr = self.parse_assignment(true)?;
2481 self.expect_punct(Punct::RBracket)?;
2482 Ok(PropName::Computed(Box::new(expr)))
2483 }
2484 TokenKind::Punct(Punct::Hash) => {
2485 let ident = self.parse_private_name()?;
2486 Ok(PropName::Private(ident))
2487 }
2488 _ => Err(self.error("invalid property name")),
2491 }
2492 }
2493
2494 fn parse_function(
2504 &mut self,
2505 form: FunctionForm,
2506 is_async: bool,
2507 start: Option<Position>,
2508 ) -> Result<Function> {
2509 let start = start.unwrap_or(self.current.span.start);
2510 self.bump()?; let is_generator = self.eat_punct(Punct::Star)?;
2512 let name = if matches!(self.current.kind, TokenKind::Ident(_)) {
2513 let ident = if form == FunctionForm::Declaration {
2514 self.expect_binding_ident()?
2515 } else {
2516 self.expect_ident()?
2517 };
2518 if is_generator && ident.name == "yield" {
2519 return Err(self.error_at("invalid use of 'yield' as a function name", ident.span));
2520 }
2521 if is_async && ident.name == "await" {
2522 return Err(self.error_at("invalid use of 'await' as a function name", ident.span));
2523 }
2524 Some(ident)
2525 } else {
2526 if form == FunctionForm::Declaration {
2527 return Err(self.error("function name expected"));
2528 }
2529 None
2530 };
2531 if form == FunctionForm::Declaration
2541 && let Some(ident) = &name
2542 {
2543 self.declare_block_function(&ident.name, !is_async && !is_generator)?;
2544 }
2545 let saved = self.ctx;
2546 self.ctx = FnCtx {
2547 in_function: true,
2548 in_generator: is_generator,
2549 in_async: is_async,
2550 in_method: false,
2551 in_derived_constructor: false,
2552 in_static_block: false,
2553 arguments_allowed: true,
2554 };
2555 let saved_top = self.top_level;
2556 self.top_level = false;
2557 let params_result = self.parse_formal_parameters();
2563 let result = match params_result {
2564 Ok(params) => self.parse_function_body(params, false),
2565 Err(err) => Err(err),
2566 };
2567 self.ctx = saved;
2568 self.top_level = saved_top;
2569 let (params, params_span, body, strict) = result?;
2570 Ok(Function {
2571 name,
2572 params,
2573 body,
2574 is_async,
2575 is_generator,
2576 strict,
2577 is_arrow: false,
2578 span: self.span_from(start),
2579 params_span,
2580 source_span: None,
2581 })
2582 }
2583
2584 fn parse_formal_parameters(&mut self) -> Result<Vec<Pattern>> {
2585 let saved = self.in_formal_parameters;
2590 self.in_formal_parameters = true;
2591 let result = self.parse_formal_parameters_inner();
2592 self.in_formal_parameters = saved;
2593 result
2594 }
2595
2596 fn parse_formal_parameters_inner(&mut self) -> Result<Vec<Pattern>> {
2597 self.expect_punct(Punct::LParen)?;
2598 let mut params = Vec::new();
2599 loop {
2600 if self.at_punct(Punct::RParen) {
2601 break;
2602 }
2603 if self.at_punct(Punct::Ellipsis) {
2604 self.bump()?;
2605 if !self.at_formal_parameter() {
2608 return Err(self.error("missing formal parameter"));
2609 }
2610 let target = self.parse_binding_target()?;
2611 if matches!(target.unparen_kind(), PatternKind::Assign { .. }) {
2612 return Err(
2613 self.error_at("rest element cannot have a default value", target.span)
2614 );
2615 }
2616 params.push(Pattern::new(
2617 PatternKind::Rest(Box::new(target.clone())),
2618 target.span,
2619 ));
2620 if self.at_punct(Punct::Comma) {
2623 return Err(self.error("expecting ')'"));
2624 }
2625 break;
2626 }
2627 if !self.at_formal_parameter() {
2628 return Err(self.error("missing formal parameter"));
2629 }
2630 let param = self.parse_binding_element()?;
2631 self.check_parameter(¶m)?;
2632 params.push(param);
2633 if !self.eat_punct(Punct::Comma)? {
2634 break;
2635 }
2636 }
2637 self.expect_punct(Punct::RParen)?;
2638 Ok(params)
2639 }
2640
2641 fn check_parameter(&self, param: &Pattern) -> Result<()> {
2642 match ¶m.kind {
2643 PatternKind::Ident(ident) => self.check_binding_name(&ident.name, ident.span),
2644 PatternKind::Assign { target, .. } => self.check_parameter(target),
2645 _ => Ok(()),
2646 }
2647 }
2648
2649 fn parse_function_body(
2650 &mut self,
2651 params: Vec<Pattern>,
2652 is_method: bool,
2653 ) -> Result<(Vec<Pattern>, Span, FunctionBody, bool)> {
2654 let params_span = self.prev_end;
2655 let saved_strict = self.strict;
2660 if !self.at_punct(Punct::LBrace) {
2661 return Err(self.unexpected());
2662 }
2663 let saved_in_case = self.in_case_clause;
2666 self.in_case_clause = false;
2667 let param_names = simple_parameter_names(¶ms);
2668 let simple_params = params
2669 .iter()
2670 .all(|p| matches!(p.unparen_kind(), PatternKind::Ident(_)));
2671 let mut body = Vec::new();
2672 let mut prologue = true;
2673 let mut strict_seen = false;
2674 self.bump()?; let body_start = self.current.span;
2679 self.push_scope(Scope::function(param_names));
2680 while !self.at_punct(Punct::RBrace) {
2681 if self.current.is_eof() {
2682 return Err(self.unexpected());
2683 }
2684 let stmt = self.parse_statement_list_item()?;
2685 if prologue {
2686 match self.directive_value(&stmt) {
2687 Some(directive) if directive == "use strict" => {
2688 strict_seen = true;
2689 self.enter_strict()?;
2690 }
2691 Some(_) => {}
2692 None => prologue = false,
2693 }
2694 }
2695 body.push(stmt);
2696 }
2697 self.pop_scope();
2698 self.bump()?; let body_strict = self.strict;
2702 if strict_seen && !simple_params {
2703 return Err(self.error_at(
2704 "\"use strict\" not allowed in function with default or destructuring parameter",
2706 Span::new(params_span, params_span),
2707 ));
2708 }
2709 self.check_duplicate_parameters(
2720 ¶ms,
2721 body_strict || !simple_params || is_method,
2722 body_start,
2723 )?;
2724 if body_strict && !saved_strict {
2730 for param in ¶ms {
2731 let mut names = Vec::new();
2732 param.bound_names(&mut names);
2733 for name in names {
2734 if name.name == "eval" || name.name == "arguments" || name.name == "let" {
2735 return Err(
2736 self.error_at("invalid variable name in strict mode", name.span)
2737 );
2738 }
2739 }
2740 }
2741 }
2742 let params_span_value = Span::new(params_span, params_span);
2743 self.strict = saved_strict;
2744 self.lexer.set_strict(saved_strict);
2745 self.in_case_clause = saved_in_case;
2746 Ok((
2747 params,
2748 params_span_value,
2749 FunctionBody::Block(body),
2750 body_strict,
2751 ))
2752 }
2753
2754 fn parse_class(&mut self, is_expression: bool) -> Result<Class> {
2757 let saved_strict = self.strict;
2765 let enter = self.enter_strict();
2766 let result = match enter {
2767 Ok(()) => self.parse_class_body(is_expression),
2768 Err(error) => Err(error),
2769 };
2770 self.strict = saved_strict;
2771 self.lexer.set_strict(saved_strict);
2772 result
2773 }
2774
2775 fn parse_class_body(&mut self, is_expression: bool) -> Result<Class> {
2776 let start = self.current.span.start;
2777 self.bump()?; let name = if matches!(self.current.kind, TokenKind::Ident(_)) {
2779 if is_expression {
2780 Some(self.expect_ident()?)
2781 } else {
2782 Some(self.expect_binding_ident()?)
2783 }
2784 } else {
2785 if !is_expression {
2786 return Err(self.error("class statement requires a name"));
2787 }
2788 None
2789 };
2790 let super_class = if self.eat_keyword(Keyword::Extends)? {
2791 Some(Box::new(self.parse_lhs_expression()?))
2792 } else {
2793 None
2794 };
2795 let has_super = super_class.is_some();
2796 self.private.push(PrivateEnv::default());
2797 self.expect_punct(Punct::LBrace)?;
2798 let mut elements = Vec::new();
2799 let mut seen_constructor = false;
2800 let result = (|| -> Result<()> {
2801 while !self.at_punct(Punct::RBrace) {
2802 if self.eat_punct(Punct::Semicolon)? {
2806 continue;
2807 }
2808 elements.push(self.parse_class_element(has_super, &mut seen_constructor)?);
2809 }
2810 Ok(())
2811 })();
2812 let settled = match self.private.pop() {
2816 Some(mut env) => {
2817 let mut carried = Vec::new();
2818 for (name, span) in std::mem::take(&mut env.pending) {
2819 if env.contains(&name) {
2820 continue;
2821 }
2822 match self.private.last_mut() {
2823 Some(outer) => outer.pending.push((name, span)),
2824 None => carried.push((name, span)),
2825 }
2826 }
2827 carried
2828 }
2829 None => Vec::new(),
2830 };
2831 if let Some((name, span)) = settled
2832 .into_iter()
2833 .min_by_key(|(_, span)| span.start.offset)
2834 {
2835 return Err(self.error_at(format!("undefined private field '#{name}'"), span));
2836 }
2837 result?;
2838 let body_end = self.current.span.start;
2841 self.bump()?; let class_span = self.span_from(start);
2849 for element in &mut elements {
2850 if let ClassElement::Method {
2851 kind: MethodKind::Constructor,
2852 func,
2853 ..
2854 } = element
2855 {
2856 func.source_span = Some(class_span);
2857 }
2858 }
2859 Ok(Class {
2860 name,
2861 super_class,
2862 elements,
2863 span: class_span,
2864 body_end,
2865 })
2866 }
2867
2868 fn parse_static_block(&mut self, start: Position) -> Result<ClassElement> {
2876 let saved = self.ctx;
2877 let saved_top = self.top_level;
2878 self.ctx = FnCtx {
2879 in_function: true,
2880 in_generator: false,
2881 in_async: false,
2882 in_method: true,
2884 in_derived_constructor: false,
2885 in_static_block: true,
2886 arguments_allowed: false,
2887 };
2888 self.top_level = false;
2889 let saved_strict = self.strict;
2895 let enter = self.enter_strict();
2896 let saved_loop = self.loop_depth;
2899 let saved_switch = self.switch_depth;
2900 let saved_labels = std::mem::take(&mut self.labels);
2901 self.loop_depth = 0;
2902 self.switch_depth = 0;
2903 let body_start = self.current.span.start;
2904 let body = match enter {
2905 Ok(()) => self.parse_block(),
2906 Err(error) => Err(error),
2907 };
2908 self.strict = saved_strict;
2909 self.lexer.set_strict(saved_strict);
2910 self.ctx = saved;
2911 self.top_level = saved_top;
2912 self.loop_depth = saved_loop;
2913 self.switch_depth = saved_switch;
2914 self.labels = saved_labels;
2915 let body = body?;
2916 Ok(ClassElement::StaticBlock {
2917 body,
2918 body_start,
2919 span: self.span_from(start),
2920 })
2921 }
2922
2923 fn parse_class_element(
2924 &mut self,
2925 has_super: bool,
2926 seen_constructor: &mut bool,
2927 ) -> Result<ClassElement> {
2928 let start = self.current.span.start;
2929 let mut is_static = false;
2930 if self.at_ident("static") {
2931 let peek = self.peek()?;
2932 let is_modifier = !matches!(
2933 peek.kind,
2934 TokenKind::Punct(Punct::LParen)
2935 | TokenKind::Punct(Punct::Eq)
2936 | TokenKind::Punct(Punct::Semicolon)
2937 | TokenKind::Punct(Punct::RBrace)
2938 );
2939 if is_modifier {
2940 self.bump()?; if self.at_punct(Punct::LBrace) {
2942 return self.parse_static_block(start);
2943 }
2944 is_static = true;
2945 }
2946 }
2947 let reported_start = self.current.span.start;
2951
2952 let mut is_async = false;
2954 let mut is_generator = false;
2955 let mut accessor: Option<MethodKind> = None;
2956 if self.at_ident("async") {
2957 let peek = self.peek()?;
2958 let is_modifier = !matches!(
2959 peek.kind,
2960 TokenKind::Punct(Punct::LParen)
2961 | TokenKind::Punct(Punct::Eq)
2962 | TokenKind::Punct(Punct::Semicolon)
2963 | TokenKind::Punct(Punct::RBrace)
2964 ) && !peek.newline_before;
2965 if is_modifier {
2966 self.bump()?;
2967 is_async = true;
2968 }
2969 }
2970 if self.at_punct(Punct::Star) {
2971 self.bump()?;
2972 is_generator = true;
2973 }
2974 if accessor.is_none() && (self.at_ident("get") || self.at_ident("set")) {
2975 let is_get = self.at_ident("get");
2976 let peek = self.peek()?;
2977 if is_property_key_start(&peek.kind) {
2978 self.bump()?;
2979 accessor = Some(if is_get {
2980 MethodKind::Get
2981 } else {
2982 MethodKind::Set
2983 });
2984 }
2985 }
2986 let key = self.parse_property_key()?;
2987
2988 if matches!(&key, PropName::Private(ident) if ident.name == "constructor") {
2992 return Err(self.error("invalid method name"));
2993 }
2994 if !is_static
3000 && (is_generator || is_async || accessor.is_some())
3001 && matches!(&key, PropName::Literal(PropKey::Str(name)) if name.as_str() == Some("constructor"))
3002 {
3003 return Err(self.error("invalid method name"));
3004 }
3005
3006 if let PropName::Private(ident) = &key {
3008 if let Some(env) = self.private.last_mut() {
3009 if !env.declare(&ident.name, accessor, is_static) {
3010 return Err(self.error_at(
3011 "private class field is already defined".to_string(),
3014 ident.span,
3015 ));
3016 }
3017 }
3018 }
3019
3020 if self.at_punct(Punct::LParen) {
3021 let kind = match accessor {
3022 Some(kind) => kind,
3023 None => {
3024 let is_constructor = !is_static
3025 && !is_generator
3026 && !is_async
3027 && matches!(&key, PropName::Literal(PropKey::Str(s)) if s.as_str() == Some("constructor"));
3028 if is_constructor {
3029 if *seen_constructor {
3030 return Err(self.error_at(
3031 "property constructor appears more than once",
3032 self.span_from(start),
3033 ));
3034 }
3035 *seen_constructor = true;
3036 MethodKind::Constructor
3037 } else {
3038 MethodKind::Method
3039 }
3040 }
3041 };
3042 if kind == MethodKind::Constructor && (is_generator || is_async) {
3043 return Err(self.error("a constructor may not be a generator or async"));
3044 }
3045 let saved = self.ctx;
3046 self.ctx = FnCtx {
3047 in_function: true,
3048 in_generator: is_generator,
3049 in_async: is_async,
3050 in_method: true,
3051 in_derived_constructor: kind == MethodKind::Constructor && has_super,
3052 in_static_block: false,
3053 arguments_allowed: true,
3054 };
3055 let saved_top = self.top_level;
3056 self.top_level = false;
3057 let result = (|| -> Result<Function> {
3058 let params = self.parse_formal_parameters()?;
3059 let (params, params_span, body, strict) = self.parse_function_body(params, true)?;
3060 Ok(Function {
3061 name: None,
3062 params,
3063 body,
3064 is_async,
3065 is_generator,
3066 strict,
3067 is_arrow: false,
3068 span: Span::new(reported_start, self.prev_end),
3069 params_span,
3070 source_span: None,
3071 })
3072 })();
3073 self.ctx = saved;
3074 self.top_level = saved_top;
3075 let func = result?;
3076 if is_static {
3077 if let PropName::Literal(PropKey::Str(name)) = &key {
3078 if name == "prototype" {
3079 return Err(self.error_at("invalid method name", func.span));
3080 }
3081 }
3082 }
3083 if kind == MethodKind::Get && !func.params.is_empty() {
3084 return Err(self.error_at(
3085 "invalid number of arguments for getter or setter",
3086 func.span,
3087 ));
3088 }
3089 if kind == MethodKind::Set && func.params.len() != 1 {
3090 return Err(self.error_at(
3091 "invalid number of arguments for getter or setter",
3092 func.span,
3093 ));
3094 }
3095 return Ok(ClassElement::Method {
3096 key,
3097 is_static,
3098 kind,
3099 func: Box::new(func),
3100 span: self.span_from(start),
3101 });
3102 }
3103
3104 if accessor.is_some() {
3106 return Err(self.error("expecting '(' after an accessor name"));
3107 }
3108 if let PropName::Literal(PropKey::Str(name)) = &key {
3109 if name == "constructor" && !is_static {
3110 return Err(self.error("classes may not have a field named 'constructor'"));
3111 }
3112 if name == "prototype" && is_static {
3113 return Err(self.error("classes may not have a static property named 'prototype'"));
3114 }
3115 }
3116 let saved = self.ctx;
3120 let saved_top = self.top_level;
3121 self.ctx = FnCtx {
3122 in_function: true,
3123 in_generator: false,
3124 in_async: false,
3125 in_method: true,
3126 in_derived_constructor: false,
3127 in_static_block: false,
3128 arguments_allowed: false,
3129 };
3130 self.top_level = false;
3131 let value = self
3132 .eat_punct(Punct::Eq)?
3133 .then(|| self.parse_assignment(true));
3134 self.ctx = saved;
3135 self.top_level = saved_top;
3136 let value = match value {
3137 Some(value) => Some(Box::new(value?)),
3138 None => None,
3139 };
3140 self.semicolon()?;
3142 Ok(ClassElement::Field {
3143 key,
3144 is_static,
3145 value,
3146 span: self.span_from(start),
3147 })
3148 }
3149
3150 fn parse_import_decl(&mut self) -> Result<Stmt> {
3153 let start = self.current.span.start;
3154 self.bump()?; let mut specifiers = Vec::new();
3156 if let TokenKind::String(source) = self.current.kind.clone() {
3157 let source = as_specifier(&source);
3158 self.bump()?;
3159 let attributes = self.parse_import_attributes()?;
3160 self.semicolon()?;
3161 return Ok(Stmt::new(
3162 StmtKind::Import(Box::new(ImportDecl {
3163 specifiers,
3164 source,
3165 attributes,
3166 span: self.span_from(start),
3167 })),
3168 self.span_from(start),
3169 ));
3170 }
3171 if matches!(self.current.kind, TokenKind::Ident(_)) {
3173 let local = self.expect_ident()?;
3174 specifiers.push(ImportSpecifier::Default(local));
3175 if !self.eat_punct(Punct::Comma)? {
3176 return self.finish_import(start, specifiers);
3177 }
3178 }
3179 if self.at_punct(Punct::Star) {
3180 self.bump()?;
3181 if !self.eat_contextual("as")? {
3182 return Err(self.unexpected());
3183 }
3184 let local = self.expect_ident()?;
3185 specifiers.push(ImportSpecifier::Namespace(local));
3186 return self.finish_import(start, specifiers);
3187 }
3188 if self.at_punct(Punct::LBrace) {
3189 self.bump()?;
3190 while !self.at_punct(Punct::RBrace) {
3191 let imported = self.parse_module_name()?;
3192 let local = if self.eat_contextual("as")? {
3193 self.expect_ident()?
3194 } else {
3195 match &imported {
3196 ModuleName::Ident(id) => id.clone(),
3197 ModuleName::Str(_) => {
3198 return Err(self.error_at(
3199 "a string module name must be followed by 'as'",
3200 self.current.span,
3201 ));
3202 }
3203 }
3204 };
3205 specifiers.push(ImportSpecifier::Named { imported, local });
3206 if !self.eat_punct(Punct::Comma)? {
3207 break;
3208 }
3209 }
3210 self.expect_punct(Punct::RBrace)?;
3211 } else if !specifiers.is_empty() {
3212 return Err(self.unexpected());
3213 } else if self.at_punct(Punct::LBrace) {
3214 unreachable!("handled above");
3215 } else {
3216 return Err(self.unexpected());
3217 }
3218 self.finish_import(start, specifiers)
3219 }
3220
3221 fn finish_import(&mut self, start: Position, specifiers: Vec<ImportSpecifier>) -> Result<Stmt> {
3222 if !self.eat_contextual("from")? {
3223 return Err(self.unexpected());
3224 }
3225 let TokenKind::String(source) = self.current.kind.clone() else {
3226 return Err(self.error("string expected"));
3227 };
3228 let source = as_specifier(&source);
3229 self.bump()?;
3230 let attributes = self.parse_import_attributes()?;
3231 self.semicolon()?;
3232 let span = self.span_from(start);
3233 for specifier in &specifiers {
3234 let local = match specifier {
3235 ImportSpecifier::Default(id) => id,
3236 ImportSpecifier::Namespace(id) => id,
3237 ImportSpecifier::Named { local, .. } => local,
3238 };
3239 self.declare_lexical(&local.name)?;
3240 if let Some(scope) = self.scopes.last_mut()
3241 && !scope.import_names.iter().any(|n| n == &local.name)
3242 {
3243 scope.import_names.push(local.name.clone());
3244 }
3245 }
3246 Ok(Stmt::new(
3247 StmtKind::Import(Box::new(ImportDecl {
3248 specifiers,
3249 source,
3250 attributes,
3251 span,
3252 })),
3253 span,
3254 ))
3255 }
3256
3257 fn parse_import_attributes(&mut self) -> Result<Vec<ImportAttribute>> {
3258 let mut attributes = Vec::new();
3259 let has_with = self.at_keyword(Keyword::With) || self.at_ident("assert");
3260 if !has_with {
3261 return Ok(attributes);
3262 }
3263 let peek = self.peek()?;
3264 if !matches!(peek.kind, TokenKind::Punct(Punct::LBrace)) {
3265 return Ok(attributes);
3266 }
3267 self.bump()?; self.expect_punct(Punct::LBrace)?;
3269 while !self.at_punct(Punct::RBrace) {
3270 let attr_start = self.current.span.start;
3271 let key = match self.current.kind.clone() {
3272 TokenKind::Ident(name) => name,
3273 TokenKind::String(value) => as_specifier(&value),
3274 _ => return Err(self.error("expecting an import attribute name")),
3275 };
3276 self.bump()?;
3277 self.expect_punct(Punct::Colon)?;
3278 let TokenKind::String(value) = self.current.kind.clone() else {
3279 return Err(self.error("expecting an import attribute value string"));
3280 };
3281 let value = as_specifier(&value);
3282 self.bump()?;
3283 attributes.push(ImportAttribute {
3284 key,
3285 value,
3286 span: self.span_from(attr_start),
3287 });
3288 if !self.eat_punct(Punct::Comma)? {
3289 break;
3290 }
3291 }
3292 self.expect_punct(Punct::RBrace)?;
3293 Ok(attributes)
3294 }
3295
3296 fn parse_module_name(&mut self) -> Result<ModuleName> {
3297 match self.current.kind.clone() {
3298 TokenKind::String(value) => {
3299 self.bump()?;
3300 Ok(ModuleName::Str(as_specifier(&value)))
3301 }
3302 TokenKind::Ident(_) => Ok(ModuleName::Ident(self.expect_ident()?)),
3303 TokenKind::Keyword(kw) => {
3304 let span = self.current.span;
3305 self.bump()?;
3306 Ok(ModuleName::Ident(Ident {
3307 name: kw.as_str().to_string(),
3308 span,
3309 }))
3310 }
3311 _ => Err(self.error("identifier or string expected")),
3314 }
3315 }
3316
3317 fn parse_export_decl(&mut self) -> Result<Stmt> {
3318 let start = self.current.span.start;
3319 self.bump()?; if self.at_punct(Punct::Star) {
3321 self.bump()?;
3322 let mut exported = None;
3323 if self.eat_contextual("as")? {
3324 exported = Some(self.parse_module_name()?);
3325 }
3326 if !self.eat_contextual("from")? {
3327 return Err(self.error("expecting 'from' after 'export *'"));
3328 }
3329 let TokenKind::String(source) = self.current.kind.clone() else {
3330 return Err(self.error("string expected"));
3331 };
3332 let source = as_specifier(&source);
3333 self.bump()?;
3334 let attributes = self.parse_import_attributes()?;
3335 self.semicolon()?;
3336 let span = self.span_from(start);
3337 return Ok(Stmt::new(
3338 StmtKind::Export(Box::new(ExportDecl {
3339 kind: ExportKind::All {
3340 source,
3341 exported,
3342 attributes,
3343 },
3344 span,
3345 })),
3346 span,
3347 ));
3348 }
3349 if self.eat_keyword(Keyword::Default)? {
3350 let value = if self.at_keyword(Keyword::Function) {
3351 let func = self.parse_function(FunctionForm::Expression, false, None)?;
3352 Expr::new(ExprKind::Function(Box::new(func)), self.span_from(start))
3353 } else if self.at_ident("async") {
3354 let peek = self.peek()?;
3355 if matches!(peek.kind, TokenKind::Keyword(Keyword::Function)) {
3356 self.bump()?;
3357 let func = self.parse_function(FunctionForm::Expression, true, Some(start))?;
3358 Expr::new(ExprKind::Function(Box::new(func)), self.span_from(start))
3359 } else {
3360 self.parse_assignment(true)?
3361 }
3362 } else if self.at_keyword(Keyword::Class) {
3363 let class = self.parse_class(true)?;
3364 Expr::new(ExprKind::Class(Box::new(class)), self.span_from(start))
3365 } else {
3366 let expr = self.parse_assignment(true)?;
3367 self.semicolon()?;
3368 expr
3369 };
3370 let span = self.span_from(start);
3371 return Ok(Stmt::new(
3372 StmtKind::Export(Box::new(ExportDecl {
3373 kind: ExportKind::Default(Box::new(value)),
3374 span,
3375 })),
3376 span,
3377 ));
3378 }
3379 if self.at_keyword(Keyword::Var)
3380 || self.at_keyword(Keyword::Const)
3381 || self.at_keyword(Keyword::Function)
3382 || self.at_keyword(Keyword::Class)
3383 || (self.at_ident("let") && self.let_starts_declaration()?)
3384 {
3385 let decl = self.parse_statement_list_item()?;
3386 let span = self.span_from(start);
3387 return Ok(Stmt::new(
3388 StmtKind::Export(Box::new(ExportDecl {
3389 kind: ExportKind::Declaration(Box::new(decl)),
3390 span,
3391 })),
3392 span,
3393 ));
3394 }
3395 if self.at_ident("async") {
3396 let peek = self.peek()?;
3397 if matches!(peek.kind, TokenKind::Keyword(Keyword::Function)) && !peek.newline_before {
3398 let decl = self.parse_statement_list_item()?;
3399 let span = self.span_from(start);
3400 return Ok(Stmt::new(
3401 StmtKind::Export(Box::new(ExportDecl {
3402 kind: ExportKind::Declaration(Box::new(decl)),
3403 span,
3404 })),
3405 span,
3406 ));
3407 }
3408 }
3409 if self.at_punct(Punct::LBrace) {
3410 self.bump()?;
3411 let mut specifiers = Vec::new();
3412 let mut candidates: Vec<(String, Span)> = Vec::new();
3413 let mut source = None;
3414 while !self.at_punct(Punct::RBrace) {
3415 let spec_start = self.current.span.start;
3416 let local = self.parse_module_name()?;
3417 let exported = if self.eat_contextual("as")? {
3418 self.parse_module_name()?
3419 } else {
3420 local.clone()
3421 };
3422 if let ModuleName::Ident(id) = &local {
3426 candidates.push((id.name.clone(), id.span));
3427 }
3428 specifiers.push(ExportSpecifier {
3429 local,
3430 exported,
3431 span: self.span_from(spec_start),
3432 });
3433 if !self.eat_punct(Punct::Comma)? {
3434 break;
3435 }
3436 }
3437 self.expect_punct(Punct::RBrace)?;
3438 let mut attributes = Vec::new();
3439 let has_from = self.eat_contextual("from")?;
3440 if !has_from {
3441 self.pending_exports.extend(candidates);
3445 }
3446 if has_from {
3447 let TokenKind::String(value) = self.current.kind.clone() else {
3448 return Err(self.error("string expected"));
3449 };
3450 let value = as_specifier(&value);
3451 self.bump()?;
3452 source = Some(value);
3453 attributes = self.parse_import_attributes()?;
3454 }
3455 self.semicolon()?;
3456 let span = self.span_from(start);
3457 return Ok(Stmt::new(
3458 StmtKind::Export(Box::new(ExportDecl {
3459 kind: ExportKind::Named {
3460 specifiers,
3461 source,
3462 attributes,
3463 },
3464 span,
3465 })),
3466 span,
3467 ));
3468 }
3469 Err(self.unexpected())
3470 }
3471
3472 fn expr_to_pattern(&mut self, expr: Expr, kind: TargetKind) -> Result<Pattern> {
3475 self.expr_to_pattern_inner(expr, kind, false)
3476 }
3477
3478 fn expr_to_pattern_inner(
3479 &mut self,
3480 expr: Expr,
3481 kind: TargetKind,
3482 nested: bool,
3483 ) -> Result<Pattern> {
3484 let span = expr.span;
3485 match expr.kind {
3486 ExprKind::Ident(ident) => {
3487 if kind == TargetKind::Binding {
3488 self.check_binding_name(&ident.name, ident.span)?;
3489 } else {
3490 self.check_identifier(&ident.name, ident.span)?;
3491 if self.strict && (ident.name == "eval" || ident.name == "arguments") {
3492 return Err(self.error_at(
3493 format!("invalid assignment to '{}' in strict mode", ident.name),
3494 ident.span,
3495 ));
3496 }
3497 }
3498 Ok(Pattern::new(PatternKind::Ident(ident), span))
3499 }
3500 ExprKind::Paren(inner) => self.expr_to_pattern_inner(*inner, kind, nested),
3501 ExprKind::Array { elements } => {
3502 let mut out = Vec::new();
3503 let mut rest = None;
3504 let count = elements.len();
3505 for (index, element) in elements.into_iter().enumerate() {
3506 match element {
3507 None => out.push(None),
3508 Some(ArrayElement::Expr(expr)) => {
3509 let pattern = self.expr_to_pattern_inner(*expr, kind, true)?;
3510 out.push(Some(PatternElement::Pattern(pattern)));
3511 }
3512 Some(ArrayElement::Spread(expr)) => {
3513 if index + 1 != count {
3514 return Err(
3515 self.error_at("rest element must be the last one", expr.span)
3516 );
3517 }
3518 rest = Some(Box::new(self.expr_to_rest(*expr, kind)?));
3519 }
3520 }
3521 }
3522 Ok(Pattern::new(
3523 PatternKind::Array {
3524 elements: out,
3525 rest,
3526 },
3527 span,
3528 ))
3529 }
3530 ExprKind::Object(properties) => {
3531 self.cover_inits
3532 .retain(|cover| !span_contains(span, *cover));
3533 let mut out = Vec::new();
3534 let mut rest = None;
3535 let count = properties.len();
3536 for (index, property) in properties.into_iter().enumerate() {
3537 match property {
3538 ObjectProperty::Spread(expr) => {
3539 if index + 1 != count {
3540 return Err(
3541 self.error_at("rest element must be the last one", expr.span)
3542 );
3543 }
3544 rest = Some(Box::new(self.expr_to_rest(*expr, kind)?));
3545 }
3546 ObjectProperty::Property {
3547 key,
3548 value,
3549 kind: _,
3550 shorthand,
3551 span,
3552 } => {
3553 let pattern = self.expr_to_pattern_inner(*value, kind, true)?;
3554 out.push(Some(PatternElement::Property {
3555 key,
3556 value: pattern,
3557 shorthand,
3558 span,
3559 }));
3560 }
3561 }
3562 }
3563 Ok(Pattern::new(
3564 PatternKind::Object {
3565 properties: out,
3566 rest,
3567 },
3568 span,
3569 ))
3570 }
3571 ExprKind::Assign { op, target, value } if op.is_simple() => {
3572 let target = match target.kind {
3574 PatternKind::Ident(ident) => {
3575 Pattern::new(PatternKind::Ident(ident), target.span)
3576 }
3577 other => {
3578 let expr = pattern_to_expr(Pattern::new(other, target.span), target.span);
3579 self.expr_to_pattern_inner(expr, kind, nested)?
3580 }
3581 };
3582 Ok(Pattern::new(
3583 PatternKind::Assign {
3584 target: Box::new(target),
3585 default: value,
3586 },
3587 span,
3588 ))
3589 }
3590 ExprKind::Member {
3591 object,
3592 property,
3593 optional,
3594 } => {
3595 if kind == TargetKind::Binding {
3596 return Err(self.error_at("invalid binding pattern", span));
3597 }
3598 if optional {
3599 return Err(self.error_at("invalid assignment target", span));
3600 }
3601 let op_pos = expr.op_pos;
3602 Ok(Pattern::new(
3603 PatternKind::Member(Box::new(MemberPattern {
3604 object,
3605 property,
3606 span,
3607 op_pos,
3608 })),
3609 span,
3610 ))
3611 }
3612 ExprKind::OptionalChain(_) => {
3613 Err(self.error_at("invalid assignment left-hand side", span))
3614 }
3615 other @ ExprKind::Call { .. } if !nested && kind == TargetKind::Assignment => Ok(
3620 Pattern::new(PatternKind::Invalid(Box::new(Expr::new(other, span))), span),
3621 ),
3622 _ if kind == TargetKind::Binding => Err(self.error_at("invalid binding pattern", span)),
3623 _ if nested => Err(self.error_at("invalid destructuring target", span)),
3628 _ => Err(self.error_at("invalid assignment left-hand side", span)),
3629 }
3630 }
3631
3632 fn expr_to_rest(&mut self, expr: Expr, kind: TargetKind) -> Result<RestElement> {
3633 let expr = match expr.kind {
3636 ExprKind::Spread(inner) => *inner,
3637 other => Expr::new(other, expr.span),
3638 };
3639 if kind == TargetKind::Binding {
3640 return Ok(RestElement::Pattern(
3641 self.expr_to_pattern_inner(expr, kind, true)?,
3642 ));
3643 }
3644 match &expr.kind {
3645 ExprKind::Member { optional, .. } => {
3646 if *optional {
3647 return Err(self.error_at("invalid assignment target", expr.span));
3648 }
3649 match self.expr_to_pattern_inner(expr, kind, true)?.kind {
3650 PatternKind::Member(member) => Ok(RestElement::Member(member)),
3651 _ => unreachable!("member expressions convert to member patterns"),
3652 }
3653 }
3654 _ => Ok(RestElement::Pattern(
3655 self.expr_to_pattern_inner(expr, kind, true)?,
3656 )),
3657 }
3658 }
3659
3660 fn parse_expression(&mut self, allow_in: bool) -> Result<Expr> {
3664 self.enter()?;
3665 let result = self.parse_expression_unguarded(allow_in);
3666 self.leave();
3667 result
3668 }
3669
3670 fn parse_expression_unguarded(&mut self, allow_in: bool) -> Result<Expr> {
3671 let saved_allow_in = self.allow_in;
3676 self.allow_in = allow_in;
3677 let result = self.parse_expression_in(allow_in);
3678 self.allow_in = saved_allow_in;
3679 result
3680 }
3681
3682 fn parse_expression_in(&mut self, allow_in: bool) -> Result<Expr> {
3683 let start = self.current.span.start;
3684 let first = self.parse_assignment(allow_in)?;
3685 if !self.at_punct(Punct::Comma) {
3686 return Ok(first);
3687 }
3688 let mut items = vec![first];
3689 while self.eat_punct(Punct::Comma)? {
3690 items.push(self.parse_assignment(allow_in)?);
3691 }
3692 Ok(Expr::new(ExprKind::Sequence(items), self.span_from(start)))
3693 }
3694
3695 fn parse_assignment(&mut self, allow_in: bool) -> Result<Expr> {
3696 let start = self.current.span.start;
3697
3698 if self.ctx.in_generator && self.at_ident("yield") {
3701 if self.in_formal_parameters {
3702 return Err(self.error_at("yield in default expression", self.current.span));
3703 }
3704 return self.parse_yield(allow_in);
3705 }
3706
3707 let lhs = match self.try_parse_arrow(allow_in)? {
3708 Some(arrow) => return Ok(arrow),
3709 None => self.parse_conditional(allow_in)?,
3710 };
3711
3712 if let Some(op) = self.current.kind.as_punct().and_then(AssignOp::from_punct) {
3713 let op_pos = self.current.span.start;
3714 let target = self.expr_to_pattern(lhs, TargetKind::Assignment)?;
3715 self.bump()?;
3716 let value = self.parse_assignment(allow_in)?;
3717 return Ok(Expr::at_operator(
3718 ExprKind::Assign {
3719 op,
3720 target: Box::new(target),
3721 value: Box::new(value),
3722 },
3723 self.span_from(start),
3724 op_pos,
3725 ));
3726 }
3727 let _ = start;
3728 Ok(lhs)
3729 }
3730
3731 fn parse_yield(&mut self, allow_in: bool) -> Result<Expr> {
3732 let start = self.current.span.start;
3733 self.bump()?; let delegate = if self.at_punct(Punct::Star) && !self.current.newline_before {
3735 self.bump()?;
3736 true
3737 } else {
3738 false
3739 };
3740 let argument = if delegate {
3741 Some(Box::new(self.parse_assignment(allow_in)?))
3742 } else if self.current.newline_before
3743 || self.at_punct(Punct::RParen)
3744 || self.at_punct(Punct::RBracket)
3745 || self.at_punct(Punct::RBrace)
3746 || self.at_punct(Punct::Comma)
3747 || self.at_punct(Punct::Semicolon)
3748 || self.at_punct(Punct::Colon)
3749 || self.current.is_eof()
3750 {
3751 None
3752 } else {
3753 Some(Box::new(self.parse_assignment(allow_in)?))
3754 };
3755 Ok(Expr::new(
3756 ExprKind::Yield { argument, delegate },
3757 self.span_from(start),
3758 ))
3759 }
3760
3761 fn try_parse_arrow(&mut self, allow_in: bool) -> Result<Option<Expr>> {
3762 let starts_paren = self.at_punct(Punct::LParen);
3763 let starts_ident = matches!(self.current.kind, TokenKind::Ident(_));
3764 if !starts_paren && !starts_ident {
3765 return Ok(None);
3766 }
3767 if starts_paren && !self.arrow_follows_paren()? {
3771 return Ok(None);
3772 }
3773 let snapshot = self.snapshot();
3774 let head = match self.parse_arrow_head() {
3775 Ok(head) => head,
3776 Err(_) => {
3777 self.restore(snapshot);
3778 return Ok(None);
3779 }
3780 };
3781 let Some(head) = head else {
3782 self.restore(snapshot);
3783 return Ok(None);
3784 };
3785 let body_start = if self.at_punct(Punct::LBrace) {
3792 self.peek()?.span
3793 } else {
3794 self.current.span
3795 };
3796 self.check_duplicate_parameters(&head.params, true, body_start)?;
3797 let saved_ctx = self.ctx;
3798 let saved_loop = self.loop_depth;
3799 let saved_switch = self.switch_depth;
3800 let saved_labels = std::mem::take(&mut self.labels);
3801 let saved_top = self.top_level;
3802 self.ctx = FnCtx {
3803 in_function: true,
3804 in_generator: false,
3805 in_async: head.is_async,
3806 in_method: saved_ctx.in_method,
3807 in_derived_constructor: saved_ctx.in_derived_constructor,
3808 in_static_block: false,
3812 arguments_allowed: saved_ctx.arguments_allowed,
3813 };
3814 self.loop_depth = 0;
3815 self.switch_depth = 0;
3816 self.top_level = false;
3817 let body_start = self.current.span.start;
3818 let (body, strict) = if self.at_punct(Punct::LBrace) {
3819 let (block, strict) = self.parse_arrow_block(&head.params)?;
3820 (block, (self.prev_end, strict))
3821 } else {
3822 let expr = self.parse_assignment(allow_in)?;
3823 let end = expr.span.end;
3824 let strict = self.strict;
3826 (FunctionBody::Expr(Box::new(expr)), (end, strict))
3827 };
3828 self.ctx = saved_ctx;
3829 self.loop_depth = saved_loop;
3830 self.switch_depth = saved_switch;
3831 self.labels = saved_labels;
3832 self.top_level = saved_top;
3833 let _ = body_start;
3834 let (body, (end, strict)) = (body, strict);
3835 let span = Span::new(head.span.start, end);
3836 Ok(Some(Expr::new(
3837 ExprKind::Arrow(Box::new(Function {
3838 name: None,
3839 params: head.params,
3840 body,
3841 is_async: head.is_async,
3842 is_generator: false,
3843 strict,
3844 is_arrow: true,
3845 span,
3846 params_span: head.params_span,
3847 source_span: None,
3848 })),
3849 span,
3850 )))
3851 }
3852
3853 fn parse_arrow_block(&mut self, params: &[Pattern]) -> Result<(FunctionBody, bool)> {
3855 let saved_strict = self.strict;
3858 self.expect_punct(Punct::LBrace)?;
3859 self.push_scope(Scope::function(simple_parameter_names(params)));
3860 let result = (|| -> Result<Vec<Stmt>> {
3861 let mut body = Vec::new();
3862 let mut prologue = true;
3863 while !self.at_punct(Punct::RBrace) {
3864 if self.current.is_eof() {
3865 return Err(self.unexpected());
3866 }
3867 let stmt = self.parse_statement_list_item()?;
3868 if prologue {
3869 match self.directive_value(&stmt) {
3870 Some(directive) if directive == "use strict" => self.enter_strict()?,
3871 Some(_) => {}
3872 None => prologue = false,
3873 }
3874 }
3875 body.push(stmt);
3876 }
3877 Ok(body)
3878 })();
3879 self.pop_scope();
3880 let body_strict = self.strict;
3881 self.strict = saved_strict;
3882 self.lexer.set_strict(saved_strict);
3883 let body = result?;
3884 self.bump()?;
3885 Ok((FunctionBody::Block(body), body_strict))
3886 }
3887
3888 fn arrow_follows_paren(&self) -> Result<bool> {
3894 let mut lexer = self.lexer.clone();
3895 let mut depth = 1usize;
3897 let mut template_depth = 0usize;
3899 loop {
3900 let token = lexer.next_token()?;
3901 match token.kind {
3902 TokenKind::Eof => return Ok(false),
3903 TokenKind::Punct(Punct::Slash) | TokenKind::Punct(Punct::SlashEq) => {
3911 if lexer.re_scan_regex(token.span.start).is_err() {
3912 lexer.reset_to(token.span.end);
3913 }
3914 }
3915 TokenKind::Template(chunk) => match chunk.kind {
3923 crate::token::TemplateKind::NoSubstitution => {}
3925 crate::token::TemplateKind::Head => template_depth += 1,
3927 crate::token::TemplateKind::Middle => {}
3929 crate::token::TemplateKind::Tail => {
3931 template_depth = template_depth.saturating_sub(1);
3932 }
3933 },
3934 TokenKind::Punct(Punct::LParen)
3935 | TokenKind::Punct(Punct::LBracket)
3936 | TokenKind::Punct(Punct::LBrace) => depth += 1,
3937 TokenKind::Punct(Punct::RBrace) if template_depth > 0 => {
3938 template_depth -= 1;
3941 let token = lexer.re_scan_template_continue(token.span.start)?;
3942 if matches!(
3943 token.kind,
3944 TokenKind::Template(crate::token::TemplateToken {
3945 kind: crate::token::TemplateKind::Head
3946 | crate::token::TemplateKind::Middle,
3947 ..
3948 })
3949 ) {
3950 template_depth += 1;
3951 }
3952 }
3953 TokenKind::Punct(Punct::RParen)
3954 | TokenKind::Punct(Punct::RBracket)
3955 | TokenKind::Punct(Punct::RBrace) => {
3956 if depth == 0 {
3957 return Ok(false);
3959 }
3960 depth -= 1;
3961 if depth == 0 {
3962 let next = lexer.next_token()?;
3965 return Ok(matches!(next.kind, TokenKind::Punct(Punct::Arrow))
3966 && !next.newline_before);
3967 }
3968 }
3969 _ => {}
3970 }
3971 }
3972 }
3973
3974 fn parse_arrow_head(&mut self) -> Result<Option<ArrowHead>> {
3976 let start = self.current.span.start;
3977 let mut is_async = false;
3978 if self.at_ident("async") {
3979 let peek = self.peek()?;
3980 if peek.newline_before {
3981 return Ok(None);
3982 }
3983 let plausible =
3984 matches!(peek.kind, TokenKind::Punct(Punct::LParen)) || peek.kind.is_identifier();
3985 if !plausible {
3986 return Ok(None);
3987 }
3988 self.bump()?;
3989 is_async = true;
3990 }
3991 let params_start = self.current.span.start;
3992 let params = if self.at_punct(Punct::LParen) {
3993 self.parse_formal_parameters()?
3994 } else if matches!(self.current.kind, TokenKind::Ident(_)) {
3995 let ident = self.expect_ident()?;
3996 vec![Pattern::new(
3997 PatternKind::Ident(ident),
3998 self.span_from(params_start),
3999 )]
4000 } else {
4001 return Ok(None);
4002 };
4003 let params_span = self.span_from(params_start);
4004 if !self.at_punct(Punct::Arrow) || self.current.newline_before {
4005 return Ok(None);
4006 }
4007 self.bump()?; Ok(Some(ArrowHead {
4009 params,
4010 is_async,
4011 span: self.span_from(start),
4012 params_span,
4013 }))
4014 }
4015
4016 fn parse_conditional(&mut self, allow_in: bool) -> Result<Expr> {
4017 let start = self.current.span.start;
4018 let test = self.parse_binary(allow_in, 0)?;
4019 if !self.at_punct(Punct::Question) {
4020 return Ok(test);
4021 }
4022 self.bump()?;
4023 let consequent = self.parse_assignment(true)?;
4024 self.expect_punct(Punct::Colon)?;
4025 let alternate = self.parse_assignment(allow_in)?;
4026 Ok(Expr::new(
4027 ExprKind::Conditional {
4028 test: Box::new(test),
4029 cons: Box::new(consequent),
4030 alt: Box::new(alternate),
4031 },
4032 self.span_from(start),
4033 ))
4034 }
4035
4036 fn parse_binary(&mut self, allow_in: bool, min_prec: u8) -> Result<Expr> {
4037 let start = self.current.span.start;
4038 let mut lhs = self.parse_unary()?;
4039 while let Some((prec, op)) = binary_operator(&self.current.kind, allow_in) {
4040 if prec < min_prec {
4041 break;
4042 }
4043 let op_pos = self.current.span.start;
4044 self.bump()?;
4045 let next_min = if op.is_right_associative() {
4046 prec
4047 } else {
4048 prec + 1
4049 };
4050 let rhs = self.parse_binary(allow_in, next_min)?;
4051 lhs = build_binary(op, lhs, rhs, self.span_from(start), op_pos)?;
4052 }
4053 Ok(lhs)
4054 }
4055
4056 fn parse_unary(&mut self) -> Result<Expr> {
4059 let start = self.current.span.start;
4060 let unary = match &self.current.kind {
4062 TokenKind::Keyword(Keyword::Delete) => Some(UnaryOp::Delete),
4063 TokenKind::Keyword(Keyword::Void) => Some(UnaryOp::Void),
4064 TokenKind::Keyword(Keyword::Typeof) => Some(UnaryOp::Typeof),
4065 TokenKind::Punct(Punct::Plus) => Some(UnaryOp::Plus),
4066 TokenKind::Punct(Punct::Minus) => Some(UnaryOp::Minus),
4067 TokenKind::Punct(Punct::Bang) => Some(UnaryOp::Not),
4068 TokenKind::Punct(Punct::Tilde) => Some(UnaryOp::BitNot),
4069 _ => None,
4070 };
4071 if let Some(op) = unary {
4072 let op_pos = self.current.span.start;
4073 self.bump()?;
4074 let argument = self.parse_unary()?;
4075 if op == UnaryOp::Delete && self.strict {
4076 if let ExprKind::Ident(ident) = &argument.unparen().kind {
4077 return Err(self.error_at(
4078 "cannot delete a direct reference in strict mode",
4079 ident.span,
4080 ));
4081 }
4082 }
4083 if op == UnaryOp::Delete && deletes_a_private_member(&argument) {
4089 return Err(self.error("cannot delete a private class field"));
4093 }
4094 let expr = Expr::at_operator(
4095 ExprKind::Unary {
4096 op,
4097 argument: Box::new(argument),
4098 },
4099 self.span_from(start),
4100 op_pos,
4101 );
4102 if self.at_punct(Punct::StarStar) {
4103 return Err(self.error(
4104 "unparenthesized unary expression can't appear on the left-hand side of '**'",
4106 ));
4107 }
4108 return Ok(expr);
4109 }
4110 if self.at_punct(Punct::PlusPlus) || self.at_punct(Punct::MinusMinus) {
4112 let op_pos = self.current.span.start;
4113 let op = if self.at_punct(Punct::PlusPlus) {
4114 UpdateOp::Increment
4115 } else {
4116 UpdateOp::Decrement
4117 };
4118 self.bump()?;
4119 let argument = self.parse_unary()?;
4120 self.check_simple_target(&argument)?;
4121 return Ok(Expr::at_operator(
4122 ExprKind::Update {
4123 op,
4124 argument: Box::new(argument),
4125 prefix: true,
4126 },
4127 self.span_from(start),
4128 op_pos,
4129 ));
4130 }
4131 if self.at_ident("await") && self.ctx.in_async {
4138 if self.in_formal_parameters {
4141 return Err(self.error_at("await in default expression", self.current.span));
4142 }
4143 self.bump()?;
4144 let argument = self.parse_unary()?;
4145 return Ok(Expr::new(
4146 ExprKind::Await(Box::new(argument)),
4147 self.span_from(start),
4148 ));
4149 }
4150 let expr = self.parse_lhs_expression()?;
4151 let result = if (self.at_punct(Punct::PlusPlus) || self.at_punct(Punct::MinusMinus))
4153 && !self.current.newline_before
4154 {
4155 let op_pos = self.current.span.start;
4156 let op = if self.at_punct(Punct::PlusPlus) {
4157 UpdateOp::Increment
4158 } else {
4159 UpdateOp::Decrement
4160 };
4161 self.check_simple_target(&expr)?;
4162 self.bump()?;
4163 Expr::at_operator(
4164 ExprKind::Update {
4165 op,
4166 argument: Box::new(expr),
4167 prefix: false,
4168 },
4169 self.span_from(start),
4170 op_pos,
4171 )
4172 } else {
4173 expr
4174 };
4175 Ok(result)
4176 }
4177
4178 fn check_simple_target(&self, expr: &Expr) -> Result<()> {
4183 match &expr.unparen().kind {
4184 ExprKind::Ident(_) => Ok(()),
4185 ExprKind::Member {
4186 optional: false, ..
4187 } => Ok(()),
4188 _ => Err(self.error_at("invalid increment/decrement operand", expr.span)),
4189 }
4190 }
4191
4192 fn parse_lhs_expression(&mut self) -> Result<Expr> {
4193 let start = self.current.span.start;
4194 let mut expr = if self.at_keyword(Keyword::New) {
4195 self.parse_new_expression()?
4196 } else {
4197 self.parse_primary()?
4198 };
4199 let mut saw_optional = false;
4200 loop {
4201 let op_pos = self.current.span.start;
4204 match self.current.kind.clone() {
4205 TokenKind::Punct(Punct::Dot) => {
4206 self.bump()?;
4207 let property = self.parse_member_property()?;
4208 expr = Expr::at_operator(
4209 ExprKind::Member {
4210 object: Box::new(expr),
4211 property,
4212 optional: false,
4213 },
4214 self.span_from(start),
4215 op_pos,
4216 );
4217 }
4218 TokenKind::Punct(Punct::QuestionDot) => {
4219 saw_optional = true;
4220 self.bump()?;
4221 if self.at_punct(Punct::LParen) {
4222 let arguments = self.parse_arguments()?;
4223 expr = Expr::at_operator(
4224 ExprKind::Call {
4225 callee: Box::new(expr),
4226 arguments,
4227 optional: true,
4228 },
4229 self.span_from(start),
4230 op_pos,
4231 );
4232 } else if self.at_punct(Punct::LBracket) {
4233 self.bump()?;
4234 let index = self.parse_expression(true)?;
4235 self.expect_punct(Punct::RBracket)?;
4236 expr = Expr::at_operator(
4237 ExprKind::Member {
4238 object: Box::new(expr),
4239 property: MemberProp::Computed(Box::new(index)),
4240 optional: true,
4241 },
4242 self.span_from(start),
4243 op_pos,
4244 );
4245 } else {
4246 let property = self.parse_member_property()?;
4247 expr = Expr::at_operator(
4248 ExprKind::Member {
4249 object: Box::new(expr),
4250 property,
4251 optional: true,
4252 },
4253 self.span_from(start),
4254 op_pos,
4255 );
4256 }
4257 }
4258 TokenKind::Punct(Punct::LBracket) => {
4259 self.bump()?;
4260 let index = self.parse_expression(true)?;
4261 self.expect_punct(Punct::RBracket)?;
4262 expr = Expr::at_operator(
4263 ExprKind::Member {
4264 object: Box::new(expr),
4265 property: MemberProp::Computed(Box::new(index)),
4266 optional: false,
4267 },
4268 self.span_from(start),
4269 op_pos,
4270 );
4271 }
4272 TokenKind::Punct(Punct::LParen) => {
4273 let arguments = self.parse_arguments()?;
4274 expr = Expr::at_operator(
4275 ExprKind::Call {
4276 callee: Box::new(expr),
4277 arguments,
4278 optional: false,
4279 },
4280 self.span_from(start),
4281 op_pos,
4282 );
4283 }
4284 TokenKind::Template(_) => {
4285 if saw_optional || matches!(expr.unparen().kind, ExprKind::OptionalChain(_)) {
4286 return Err(
4287 self.error("tagged template cannot be used in an optional chain")
4288 );
4289 }
4290 let quasi = self.parse_template()?;
4291 expr = Expr::new(
4292 ExprKind::TaggedTemplate {
4293 tag: Box::new(expr),
4294 quasi: Box::new(quasi),
4295 },
4296 self.span_from(start),
4297 );
4298 }
4299 _ => break,
4300 }
4301 }
4302 if saw_optional {
4303 expr = Expr::new(
4304 ExprKind::OptionalChain(Box::new(expr)),
4305 self.span_from(start),
4306 );
4307 }
4308 Ok(expr)
4309 }
4310
4311 fn parse_private_name(&mut self) -> Result<Ident> {
4318 let hash = self.current.span;
4319 self.bump()?;
4320 let ident = self.expect_ident()?;
4321 if ident.span.start.offset != hash.end.offset {
4322 return Err(self.error_at("invalid first character of private name", hash));
4323 }
4324 Ok(ident)
4325 }
4326
4327 fn parse_member_property(&mut self) -> Result<MemberProp> {
4328 if self.at_punct(Punct::Hash) {
4329 let ident = self.parse_private_name()?;
4330 if !self.private.iter().any(|env| env.contains(&ident.name)) {
4331 let Some(innermost) = self.private.last_mut() else {
4337 return Err(self.error_at(
4338 format!("undefined private field '#{}'", ident.name),
4339 ident.span,
4340 ));
4341 };
4342 innermost.pending.push((ident.name.clone(), ident.span));
4346 }
4347 return Ok(MemberProp::Private(ident));
4348 }
4349 match self.current.kind.clone() {
4350 TokenKind::Ident(name) => {
4351 let span = self.current.span;
4352 self.bump()?;
4353 Ok(MemberProp::Ident(Ident { name, span }))
4354 }
4355 TokenKind::Keyword(kw) => {
4356 let span = self.current.span;
4357 self.bump()?;
4358 Ok(MemberProp::Ident(Ident {
4359 name: kw.as_str().to_string(),
4360 span,
4361 }))
4362 }
4363 _ => Err(self.error("expecting field name")),
4367 }
4368 }
4369
4370 fn parse_new_expression(&mut self) -> Result<Expr> {
4371 let start = self.current.span.start;
4372 self.bump()?; if self.at_punct(Punct::Dot) {
4374 self.bump()?;
4375 if !self.at_ident("target") {
4376 return Err(self.error("expecting target"));
4377 }
4378 if !self.ctx.in_function {
4379 return Err(self.error("new.target only allowed within functions"));
4380 }
4381 self.bump()?;
4382 return Ok(Expr::new(ExprKind::NewTarget, self.span_from(start)));
4383 }
4384 let mut callee = if self.at_keyword(Keyword::New) {
4385 self.parse_new_expression()?
4386 } else {
4387 self.parse_primary()?
4388 };
4389 loop {
4391 let op_pos = self.current.span.start;
4392 match self.current.kind.clone() {
4393 TokenKind::Punct(Punct::Dot) => {
4394 self.bump()?;
4395 let property = self.parse_member_property()?;
4396 callee = Expr::at_operator(
4397 ExprKind::Member {
4398 object: Box::new(callee),
4399 property,
4400 optional: false,
4401 },
4402 self.span_from(start),
4403 op_pos,
4404 );
4405 }
4406 TokenKind::Punct(Punct::LBracket) => {
4407 self.bump()?;
4408 let index = self.parse_expression(true)?;
4409 self.expect_punct(Punct::RBracket)?;
4410 callee = Expr::at_operator(
4411 ExprKind::Member {
4412 object: Box::new(callee),
4413 property: MemberProp::Computed(Box::new(index)),
4414 optional: false,
4415 },
4416 self.span_from(start),
4417 op_pos,
4418 );
4419 }
4420 TokenKind::Punct(Punct::QuestionDot) => {
4421 return Err(self.error("new keyword cannot be used with an optional chain"));
4422 }
4423 _ => break,
4424 }
4425 }
4426 if matches!(callee.unparen().kind, ExprKind::OptionalChain(_)) {
4427 return Err(self.error_at("cannot use 'new' with an optional chain", callee.span));
4428 }
4429 if let Some(import_call) = member_chain_import_call(&callee) {
4441 return Err(self.error_at("invalid use of 'import()'", import_call.span));
4442 }
4443 if matches!(&callee.kind, ExprKind::ImportCall(..)) {
4449 return Err(self.error_at("invalid use of 'import()'", callee.span));
4450 }
4451 let arguments = if self.at_punct(Punct::LParen) {
4452 let op_pos = self.current.span.start;
4454 let arguments = Some(self.parse_arguments()?);
4455 return Ok(Expr::at_operator(
4456 ExprKind::New {
4457 callee: Box::new(callee),
4458 arguments,
4459 },
4460 self.span_from(start),
4461 op_pos,
4462 ));
4463 } else {
4464 None
4465 };
4466 Ok(Expr::at_operator(
4470 ExprKind::New {
4471 callee: Box::new(callee),
4472 arguments,
4473 },
4474 self.span_from(start),
4475 self.current.span.start,
4476 ))
4477 }
4478
4479 fn parse_arguments(&mut self) -> Result<Vec<Expr>> {
4480 self.expect_punct(Punct::LParen)?;
4481 let mut arguments = Vec::new();
4482 while !self.at_punct(Punct::RParen) {
4483 if self.at_punct(Punct::Ellipsis) {
4484 let start = self.current.span.start;
4485 self.bump()?;
4486 let argument = self.parse_assignment(true)?;
4487 arguments.push(Expr::new(
4488 ExprKind::Spread(Box::new(argument)),
4489 self.span_from(start),
4490 ));
4491 } else {
4492 arguments.push(self.parse_assignment(true)?);
4493 }
4494 if !self.eat_punct(Punct::Comma)? {
4495 break;
4496 }
4497 }
4498 self.expect_punct(Punct::RParen)?;
4499 Ok(arguments)
4500 }
4501
4502 fn parse_primary(&mut self) -> Result<Expr> {
4509 let start = self.current.span.start;
4510 match self.current.kind.clone() {
4511 TokenKind::Number(NumberLiteral::Int(value)) => {
4512 self.bump()?;
4513 Ok(Expr::new(
4514 ExprKind::Number(value as f64),
4515 self.span_from(start),
4516 ))
4517 }
4518 TokenKind::Number(NumberLiteral::Float(value)) => {
4519 self.bump()?;
4520 Ok(Expr::new(ExprKind::Number(value), self.span_from(start)))
4521 }
4522 TokenKind::String(value) => {
4523 self.bump()?;
4524 Ok(Expr::new(ExprKind::String(value), self.span_from(start)))
4525 }
4526 TokenKind::Ident(name) if name == "async" && !self.current.escaped => {
4530 let peek = self.peek()?;
4531 if matches!(peek.kind, TokenKind::Keyword(Keyword::Function))
4532 && !peek.newline_before
4533 {
4534 self.bump()?; let func = self.parse_function(FunctionForm::Expression, true, Some(start))?;
4536 return Ok(Expr::new(
4537 ExprKind::Function(Box::new(func)),
4538 self.span_from(start),
4539 ));
4540 }
4541 let span = self.current.span;
4542 self.bump()?;
4543 Ok(Expr::new(ExprKind::Ident(Ident { name, span }), span))
4544 }
4545 TokenKind::Ident(name) => {
4546 let span = self.current.span;
4547 self.check_identifier(&name, span)?;
4548 self.check_arguments_reference(&name, span)?;
4549 self.bump()?;
4550 Ok(Expr::new(ExprKind::Ident(Ident { name, span }), span))
4551 }
4552 TokenKind::Keyword(Keyword::This) => {
4553 self.bump()?;
4554 Ok(Expr::new(ExprKind::This, self.span_from(start)))
4555 }
4556 TokenKind::Keyword(Keyword::Null) => {
4557 self.bump()?;
4558 Ok(Expr::new(ExprKind::Null, self.span_from(start)))
4559 }
4560 TokenKind::Keyword(Keyword::True) => {
4561 self.bump()?;
4562 Ok(Expr::new(ExprKind::Bool(true), self.span_from(start)))
4563 }
4564 TokenKind::Keyword(Keyword::False) => {
4565 self.bump()?;
4566 Ok(Expr::new(ExprKind::Bool(false), self.span_from(start)))
4567 }
4568 TokenKind::Punct(Punct::LParen) => {
4569 self.bump()?;
4570 let inner = self.parse_expression(true)?;
4571 self.expect_punct(Punct::RParen)?;
4572 Ok(Expr::new(
4573 ExprKind::Paren(Box::new(inner)),
4574 self.span_from(start),
4575 ))
4576 }
4577 TokenKind::Punct(Punct::Slash) | TokenKind::Punct(Punct::SlashEq) => {
4578 self.parse_regex_literal(start)
4579 }
4580 _ => self.parse_primary_complex(start),
4581 }
4582 }
4583
4584 #[inline(never)]
4587 fn parse_primary_complex(&mut self, start: Position) -> Result<Expr> {
4588 match self.current.kind.clone() {
4589 TokenKind::BigInt(literal) => {
4590 self.bump()?;
4591 Ok(Expr::new(
4592 ExprKind::BigInt {
4593 digits: literal.digits,
4594 radix: literal.radix,
4595 },
4596 self.span_from(start),
4597 ))
4598 }
4599 TokenKind::Template(_) => {
4600 let template = self.parse_template()?;
4601 Ok(Expr::new(
4602 ExprKind::Template(Box::new(template)),
4603 self.span_from(start),
4604 ))
4605 }
4606 TokenKind::Keyword(Keyword::Function) => {
4607 let func = self.parse_function(FunctionForm::Expression, false, None)?;
4608 Ok(Expr::new(
4609 ExprKind::Function(Box::new(func)),
4610 self.span_from(start),
4611 ))
4612 }
4613 TokenKind::Keyword(Keyword::Class) => {
4614 let class = self.parse_class(true)?;
4615 Ok(Expr::new(
4616 ExprKind::Class(Box::new(class)),
4617 self.span_from(start),
4618 ))
4619 }
4620 TokenKind::Keyword(Keyword::Import) => self.parse_import_expression(),
4621 TokenKind::Keyword(Keyword::Super) => self.parse_super(),
4622 TokenKind::Punct(Punct::LBracket) => self.parse_array_literal(),
4623 TokenKind::Punct(Punct::LBrace) => self.parse_object_literal(),
4624 TokenKind::Punct(Punct::Hash) if self.allow_in => self.parse_private_in(start),
4629 TokenKind::Punct(Punct::Hash) => {
4633 let hash = self.current.span;
4634 let name = match self.peek()?.kind.clone() {
4635 TokenKind::Ident(name) => format!("#{name}"),
4636 _ => "#".to_string(),
4637 };
4638 Err(SyntaxError::new(
4639 format!("unexpected token in expression: '{name}'"),
4640 hash,
4641 ))
4642 }
4643 _ => Err(self.unexpected()),
4644 }
4645 }
4646
4647 #[inline(never)]
4649 fn parse_super(&mut self) -> Result<Expr> {
4650 let start = self.current.span.start;
4651 self.bump()?;
4652 let after = self.current.span;
4658 if self.at_punct(Punct::LParen) {
4659 if !self.ctx.in_derived_constructor {
4660 return Err(self.error_at(
4661 "super() is only valid in a derived class constructor",
4662 after,
4663 ));
4664 }
4665 let arguments = self.parse_arguments()?;
4668 return Ok(Expr::at_operator(
4669 ExprKind::SuperCall(arguments),
4670 self.span_from(start),
4671 after.start,
4672 ));
4673 }
4674 if !self.ctx.in_method {
4675 let message = if self.at_punct(Punct::Dot) || self.at_punct(Punct::LBracket) {
4682 "'super' is only valid in a method"
4683 } else {
4684 "invalid use of 'super'"
4685 };
4686 return Err(self.error_at(message, after));
4687 }
4688 Ok(Expr::new(ExprKind::SuperProp, self.span_from(start)))
4689 }
4690
4691 #[inline(never)]
4693 fn parse_private_in(&mut self, start: Position) -> Result<Expr> {
4694 self.bump()?;
4695 let ident = self.expect_ident()?;
4696 if !self.private.iter().any(|env| env.contains(&ident.name)) {
4697 return Err(self.error_at(
4698 format!(
4699 "private field '#{}' must be declared in an enclosing class",
4700 ident.name
4701 ),
4702 ident.span,
4703 ));
4704 }
4705 if !self.at_keyword(Keyword::In) {
4706 return Err(self.error("expecting 'in' after a private name"));
4707 }
4708 self.bump()?;
4709 if self.at_punct(Punct::Hash) {
4713 let hash = self.current.span;
4714 let name = match self.peek()?.kind.clone() {
4715 TokenKind::Ident(name) => format!("#{name}"),
4716 _ => "#".to_string(),
4717 };
4718 return Err(SyntaxError::new(
4719 format!("unexpected token in expression: '{name}'"),
4720 hash,
4721 ));
4722 }
4723 let object = self.parse_unary()?;
4724 Ok(Expr::new(
4725 ExprKind::PrivateIn {
4726 name: ident,
4727 object: Box::new(object),
4728 },
4729 self.span_from(start),
4730 ))
4731 }
4732
4733 #[inline(never)]
4736 fn parse_regex_literal(&mut self, start: Position) -> Result<Expr> {
4737 let token = self.lexer.re_scan_regex(self.current.span.start)?;
4738 self.current = token;
4739 let TokenKind::RegExp { pattern, flags } = self.current.kind.clone() else {
4740 unreachable!("re_scan_regex returns a RegExp token")
4741 };
4742 let mut seen = 0u8;
4751 for flag in flags.chars() {
4752 let bit = match flag {
4753 'g' => 1 << 0,
4754 'i' => 1 << 1,
4755 'm' => 1 << 2,
4756 's' => 1 << 3,
4757 'y' => 1 << 4,
4758 'u' => 1 << 5,
4759 'd' => 1 << 6,
4760 'v' => 1 << 7,
4761 _ => {
4762 return Err(SyntaxError::new(
4763 "invalid regular expression flags",
4764 self.current.span,
4765 ));
4766 }
4767 };
4768 if seen & bit != 0 {
4769 return Err(SyntaxError::new(
4770 "duplicate regular expression flag",
4771 self.current.span,
4772 ));
4773 }
4774 seen |= bit;
4775 }
4776 if seen & (1 << 5) != 0 && seen & (1 << 7) != 0 {
4778 return Err(SyntaxError::new(
4779 "invalid regular expression flags",
4780 self.current.span,
4781 ));
4782 }
4783 self.bump()?;
4784 Ok(Expr::new(
4785 ExprKind::RegExp { pattern, flags },
4786 self.span_from(start),
4787 ))
4788 }
4789
4790 fn parse_import_expression(&mut self) -> Result<Expr> {
4791 let start = self.current.span.start;
4792 self.bump()?; if self.at_punct(Punct::Dot) {
4794 if !self.module {
4795 return Err(self.error_at(
4796 "import.meta only valid in module code",
4797 self.span_from(start),
4798 ));
4799 }
4800 self.bump()?;
4801 if !self.at_ident("meta") {
4802 return Err(self.error("expecting 'meta' after 'import.'"));
4803 }
4804 self.bump()?;
4805 return Ok(Expr::new(ExprKind::ImportMeta, self.span_from(start)));
4806 }
4807 if self.at_punct(Punct::LParen) {
4808 self.bump()?;
4809 let specifier = self.parse_assignment(true)?;
4810 let mut options = None;
4821 if self.at_punct(Punct::Comma) {
4822 self.bump()?;
4823 if !self.at_punct(Punct::RParen) {
4824 options = Some(Box::new(self.parse_assignment(true)?));
4825 if self.at_punct(Punct::Comma) {
4826 self.bump()?;
4827 }
4828 }
4829 }
4830 self.expect_punct(Punct::RParen)?;
4831 return Ok(Expr::new(
4832 ExprKind::ImportCall(Box::new(specifier), options),
4833 self.span_from(start),
4834 ));
4835 }
4836 Err(self.unexpected())
4837 }
4838
4839 fn parse_array_literal(&mut self) -> Result<Expr> {
4840 let start = self.current.span.start;
4841 self.expect_punct(Punct::LBracket)?;
4842 let mut elements = Vec::new();
4843 while !self.at_punct(Punct::RBracket) {
4844 if self.at_punct(Punct::Comma) {
4845 self.bump()?;
4846 elements.push(None);
4847 continue;
4848 }
4849 if self.at_punct(Punct::Ellipsis) {
4850 let spread_start = self.current.span.start;
4851 self.bump()?;
4852 let argument = self.parse_assignment(true)?;
4853 elements.push(Some(ArrayElement::Spread(Box::new(Expr::new(
4854 ExprKind::Spread(Box::new(argument)),
4855 self.span_from(spread_start),
4856 )))));
4857 } else {
4858 let expr = self.parse_assignment(true)?;
4859 elements.push(Some(ArrayElement::Expr(Box::new(expr))));
4860 }
4861 if !self.eat_punct(Punct::Comma)? {
4862 break;
4863 }
4864 }
4865 self.expect_punct(Punct::RBracket)?;
4866 Ok(Expr::new(
4867 ExprKind::Array { elements },
4868 self.span_from(start),
4869 ))
4870 }
4871
4872 fn parse_object_literal(&mut self) -> Result<Expr> {
4873 let start = self.current.span.start;
4874 self.expect_punct(Punct::LBrace)?;
4875 let mut properties: Vec<ObjectProperty> = Vec::new();
4876 let mut proto_count = 0;
4877 while !self.at_punct(Punct::RBrace) {
4878 let property_start = self.current.span.start;
4879 if self.at_punct(Punct::Ellipsis) {
4880 self.bump()?;
4881 let argument = self.parse_assignment(true)?;
4882 properties.push(ObjectProperty::Spread(Box::new(argument)));
4883 } else {
4884 let mut is_async = false;
4885 let mut is_generator = false;
4886 let mut accessor: Option<MethodKind> = None;
4887 if self.at_ident("async") {
4888 let peek = self.peek()?;
4889 let is_modifier = !matches!(
4890 peek.kind,
4891 TokenKind::Punct(Punct::LParen)
4892 | TokenKind::Punct(Punct::Colon)
4893 | TokenKind::Punct(Punct::Comma)
4894 | TokenKind::Punct(Punct::RBrace)
4895 | TokenKind::Punct(Punct::Eq)
4896 ) && !peek.newline_before;
4897 if is_modifier {
4898 self.bump()?;
4899 is_async = true;
4900 }
4901 }
4902 if self.at_punct(Punct::Star) {
4903 self.bump()?;
4904 is_generator = true;
4905 }
4906 if accessor.is_none() && (self.at_ident("get") || self.at_ident("set")) {
4907 let is_get = self.at_ident("get");
4908 let peek = self.peek()?;
4909 if is_property_key_start(&peek.kind) {
4910 self.bump()?;
4911 accessor = Some(if is_get {
4912 MethodKind::Get
4913 } else {
4914 MethodKind::Set
4915 });
4916 }
4917 }
4918 let key = self.parse_property_key()?;
4919 let is_computed = matches!(key, PropName::Computed(_));
4920 if self.at_punct(Punct::LParen) {
4921 let saved = self.ctx;
4922 self.ctx = FnCtx {
4923 in_function: true,
4924 in_generator: is_generator,
4925 in_async: is_async,
4926 in_method: true,
4927 in_derived_constructor: false,
4928 in_static_block: false,
4929 arguments_allowed: true,
4930 };
4931 let saved_top = self.top_level;
4932 self.top_level = false;
4933 let func_result = (|| -> Result<Function> {
4934 let params = self.parse_formal_parameters()?;
4935 let (params, params_span, body, strict) =
4936 self.parse_function_body(params, true)?;
4937 Ok(Function {
4938 name: None,
4939 params,
4940 body,
4941 is_async,
4942 is_generator,
4943 strict,
4944 is_arrow: false,
4945 span: self.span_from(property_start),
4946 params_span,
4947 source_span: None,
4948 })
4949 })();
4950 self.ctx = saved;
4951 self.top_level = saved_top;
4952 let func = func_result?;
4953 let kind = match accessor {
4954 Some(kind) => {
4955 if is_generator || is_async {
4956 return Err(self.error_at(
4957 "accessors may not be generators or async",
4958 func.span,
4959 ));
4960 }
4961 if kind == MethodKind::Get && !func.params.is_empty() {
4962 return Err(self.error_at(
4963 "invalid number of arguments for getter or setter",
4964 func.span,
4965 ));
4966 }
4967 if kind == MethodKind::Set && func.params.len() != 1 {
4968 return Err(self.error_at(
4969 "invalid number of arguments for getter or setter",
4970 func.span,
4971 ));
4972 }
4973 match kind {
4974 MethodKind::Get => PropertyKind::Get,
4975 MethodKind::Set => PropertyKind::Set,
4976 MethodKind::Method | MethodKind::Constructor => {
4977 PropertyKind::Method
4978 }
4979 }
4980 }
4981 None => PropertyKind::Method,
4982 };
4983 let span = self.span_from(property_start);
4984 properties.push(ObjectProperty::Property {
4985 key,
4986 value: Box::new(Expr::new(ExprKind::Function(Box::new(func)), span)),
4987 kind,
4988 shorthand: false,
4989 span,
4990 });
4991 } else if self.eat_punct(Punct::Colon)? {
4992 let value = self.parse_assignment(true)?;
4993 if !is_computed
4994 && let Some(PropKeyRef::Str(name)) = key.static_name()
4995 && name == "__proto__"
4996 {
4997 proto_count += 1;
4998 if proto_count > 1 {
4999 return Err(self.error_at(
5000 "duplicate __proto__ property name",
5001 self.span_from(property_start),
5002 ));
5003 }
5004 }
5005 properties.push(ObjectProperty::Property {
5006 key,
5007 value: Box::new(value),
5008 kind: PropertyKind::Value,
5009 shorthand: false,
5010 span: self.span_from(property_start),
5011 });
5012 } else {
5013 let PropName::Literal(PropKey::Str(name)) = &key else {
5016 return Err(self.error("expecting ':' after a property name"));
5017 };
5018 let ident_span = self.span_from(property_start);
5019 let ident = Ident {
5020 name: name.to_string_lossy().into_owned(),
5024 span: ident_span,
5025 };
5026 self.check_identifier(&ident.name, ident.span)?;
5027 let mut value = Expr::new(ExprKind::Ident(ident.clone()), ident_span);
5028 if self.at_punct(Punct::Eq) {
5029 self.cover_inits.push(ident_span);
5032 self.bump()?;
5033 let default = self.parse_assignment(true)?;
5034 let target = Pattern::new(PatternKind::Ident(ident), ident_span);
5035 value = Expr::new(
5036 ExprKind::Assign {
5037 op: AssignOp::Assign,
5038 target: Box::new(target),
5039 value: Box::new(default),
5040 },
5041 ident_span,
5042 );
5043 }
5044 properties.push(ObjectProperty::Property {
5045 key,
5046 value: Box::new(value),
5047 kind: PropertyKind::Value,
5048 shorthand: true,
5049 span: ident_span,
5050 });
5051 }
5052 }
5053 if !self.eat_punct(Punct::Comma)? {
5054 break;
5055 }
5056 }
5057 self.expect_punct(Punct::RBrace)?;
5058 Ok(Expr::new(
5059 ExprKind::Object(properties),
5060 self.span_from(start),
5061 ))
5062 }
5063
5064 fn parse_template(&mut self) -> Result<TemplateLiteral> {
5065 let mut quasis = Vec::new();
5066 let mut expressions = Vec::new();
5067 loop {
5068 let (cooked, raw, kind) = match self.current.kind.clone() {
5069 TokenKind::Template(chunk) => (chunk.cooked, chunk.raw, chunk.kind),
5070 _ => return Err(self.error("expecting a template literal")),
5071 };
5072 let tail = matches!(kind, TemplateKind::NoSubstitution | TemplateKind::Tail);
5073 quasis.push(TemplateChunk { cooked, raw, tail });
5074 if tail {
5075 self.bump()?;
5076 break;
5077 }
5078 self.bump()?; let expr = self.parse_expression(true)?;
5080 expressions.push(expr);
5081 if !self.at_punct(Punct::RBrace) {
5082 return Err(self.error("expecting '}' in a template substitution"));
5083 }
5084 let brace = self.current.span.start;
5085 let token = self.lexer.re_scan_template_continue(brace)?;
5086 self.current = token;
5087 }
5088 Ok(TemplateLiteral {
5089 quasis,
5090 expressions,
5091 })
5092 }
5093}
5094
5095#[derive(Debug, Clone, Copy, PartialEq, Eq)]
5097enum FunctionForm {
5098 Declaration,
5099 Expression,
5100}
5101
5102fn is_plain_identifier(param: &Pattern) -> bool {
5110 matches!(param.unparen_kind(), PatternKind::Ident(_))
5111}
5112
5113fn parameter_bindings(param: &Pattern) -> Vec<(String, Span, bool)> {
5119 fn walk(pattern: &Pattern, in_pattern: bool, out: &mut Vec<(String, Span, bool)>) {
5120 match &pattern.kind {
5121 PatternKind::Ident(ident) => out.push((ident.name.clone(), ident.span, in_pattern)),
5122 PatternKind::Assign { target, default } => {
5123 walk(target, in_pattern, out);
5124 let _ = default;
5126 }
5127 PatternKind::Rest(target) => walk(target, !is_plain_identifier(target), out),
5128 PatternKind::Array { .. } | PatternKind::Object { .. } => {
5129 let mut names = Vec::new();
5130 pattern.bound_names(&mut names);
5131 for name in names {
5132 out.push((name.name, name.span, true));
5133 }
5134 }
5135 _ => {}
5136 }
5137 }
5138 let mut out = Vec::new();
5139 let in_pattern = !is_plain_identifier(param);
5140 walk(param, in_pattern, &mut out);
5141 if out.is_empty() {
5144 let mut names = Vec::new();
5145 param.bound_names(&mut names);
5146 out.extend(names.into_iter().map(|name| (name.name, name.span, false)));
5147 }
5148 out
5149}
5150
5151fn pattern_has_default(pattern: &Pattern) -> bool {
5157 let element = |element: &Option<PatternElement>| {
5158 element.as_ref().is_some_and(|element| match element {
5159 PatternElement::Pattern(inner) => pattern_has_default(inner),
5160 PatternElement::Property { value, .. } => pattern_has_default(value),
5161 })
5162 };
5163 let rest = |rest: &Option<Box<RestElement>>| {
5164 rest.as_ref().is_some_and(|rest| match rest.as_ref() {
5165 RestElement::Pattern(inner) => pattern_has_default(inner),
5166 RestElement::Member(_) => false,
5167 })
5168 };
5169 match &pattern.kind {
5170 PatternKind::Assign { .. } => true,
5171 PatternKind::Array {
5172 elements,
5173 rest: tail,
5174 } => elements.iter().any(element) || rest(tail),
5175 PatternKind::Object {
5176 properties,
5177 rest: tail,
5178 } => properties.iter().any(element) || rest(tail),
5179 PatternKind::Rest(target) => pattern_has_default(target),
5180 _ => false,
5181 }
5182}
5183
5184fn simple_parameter_names(params: &[Pattern]) -> Vec<String> {
5185 params
5186 .iter()
5187 .filter_map(|param| match ¶m.kind {
5188 PatternKind::Ident(id) => Some(id.name.clone()),
5189 _ => None,
5190 })
5191 .collect()
5192}
5193
5194fn collect_module_binding(stmt: &Stmt, out: &mut Vec<String>) {
5197 match &stmt.kind {
5198 StmtKind::VarDecl(decl) => {
5199 if decl.kind.is_using() {
5205 return;
5206 }
5207 for declarator in &decl.declarators {
5208 let mut names = Vec::new();
5209 declarator.target.bound_names(&mut names);
5210 out.extend(names.into_iter().map(|n| n.name));
5211 }
5212 }
5213 StmtKind::FuncDecl(func) => {
5214 if let Some(name) = &func.name {
5215 out.push(name.name.clone());
5216 }
5217 }
5218 StmtKind::ClassDecl(class) => {
5219 if let Some(name) = &class.name {
5220 out.push(name.name.clone());
5221 }
5222 }
5223 StmtKind::Import(decl) => {
5224 for specifier in &decl.specifiers {
5225 match specifier {
5226 ImportSpecifier::Default(id) => out.push(id.name.clone()),
5227 ImportSpecifier::Namespace(id) => out.push(id.name.clone()),
5228 ImportSpecifier::Named { local, .. } => out.push(local.name.clone()),
5229 }
5230 }
5231 }
5232 StmtKind::Export(decl) => match &decl.kind {
5233 ExportKind::Declaration(inner) => collect_module_binding(inner, out),
5234 ExportKind::Default(expr) => match &expr.unparen().kind {
5235 ExprKind::Function(func) => {
5236 if let Some(name) = &func.name {
5237 out.push(name.name.clone());
5238 }
5239 }
5240 ExprKind::Class(class) => {
5241 if let Some(name) = &class.name {
5242 out.push(name.name.clone());
5243 }
5244 }
5245 _ => {}
5246 },
5247 _ => {}
5248 },
5249 _ => {}
5250 }
5251}
5252
5253fn span_contains(outer: Span, inner: Span) -> bool {
5255 inner.start.offset >= outer.start.offset && inner.end.offset <= outer.end.offset
5256}
5257
5258fn is_property_key_start(kind: &TokenKind) -> bool {
5259 matches!(
5260 kind,
5261 TokenKind::Ident(_)
5262 | TokenKind::Keyword(_)
5263 | TokenKind::String(_)
5264 | TokenKind::Number(_)
5265 | TokenKind::Punct(Punct::LBracket)
5266 | TokenKind::Punct(Punct::Hash)
5267 )
5268}
5269
5270#[derive(Debug, Clone, Copy)]
5272enum BinOp {
5273 Binary(BinaryOp),
5274 Logical(LogicalOp),
5275}
5276
5277impl BinOp {
5278 fn is_right_associative(self) -> bool {
5279 matches!(self, BinOp::Binary(BinaryOp::Pow))
5280 }
5281}
5282
5283fn binary_operator(kind: &TokenKind, allow_in: bool) -> Option<(u8, BinOp)> {
5284 use BinaryOp as B;
5285 use LogicalOp as L;
5286 let result = match kind {
5287 TokenKind::Punct(Punct::QuestionQuestion) => (1, BinOp::Logical(L::Coalesce)),
5288 TokenKind::Punct(Punct::PipePipe) => (2, BinOp::Logical(L::Or)),
5289 TokenKind::Punct(Punct::AmpAmp) => (3, BinOp::Logical(L::And)),
5290 TokenKind::Punct(Punct::Pipe) => (4, BinOp::Binary(B::BitOr)),
5291 TokenKind::Punct(Punct::Caret) => (5, BinOp::Binary(B::BitXor)),
5292 TokenKind::Punct(Punct::Amp) => (6, BinOp::Binary(B::BitAnd)),
5293 TokenKind::Punct(Punct::EqEq) => (7, BinOp::Binary(B::Eq)),
5294 TokenKind::Punct(Punct::NotEq) => (7, BinOp::Binary(B::NotEq)),
5295 TokenKind::Punct(Punct::EqEqEq) => (7, BinOp::Binary(B::StrictEq)),
5296 TokenKind::Punct(Punct::NotEqEq) => (7, BinOp::Binary(B::StrictNotEq)),
5297 TokenKind::Punct(Punct::Lt) => (8, BinOp::Binary(B::Lt)),
5298 TokenKind::Punct(Punct::LtEq) => (8, BinOp::Binary(B::LtEq)),
5299 TokenKind::Punct(Punct::Gt) => (8, BinOp::Binary(B::Gt)),
5300 TokenKind::Punct(Punct::GtEq) => (8, BinOp::Binary(B::GtEq)),
5301 TokenKind::Keyword(Keyword::Instanceof) => (8, BinOp::Binary(B::Instanceof)),
5302 TokenKind::Keyword(Keyword::In) if allow_in => (8, BinOp::Binary(B::In)),
5303 TokenKind::Punct(Punct::Shl) => (9, BinOp::Binary(B::Shl)),
5304 TokenKind::Punct(Punct::Shr) => (9, BinOp::Binary(B::Shr)),
5305 TokenKind::Punct(Punct::UShr) => (9, BinOp::Binary(B::UShr)),
5306 TokenKind::Punct(Punct::Plus) => (10, BinOp::Binary(B::Add)),
5307 TokenKind::Punct(Punct::Minus) => (10, BinOp::Binary(B::Sub)),
5308 TokenKind::Punct(Punct::Star) => (11, BinOp::Binary(B::Mul)),
5309 TokenKind::Punct(Punct::Slash) => (11, BinOp::Binary(B::Div)),
5310 TokenKind::Punct(Punct::Percent) => (11, BinOp::Binary(B::Mod)),
5311 TokenKind::Punct(Punct::StarStar) => (12, BinOp::Binary(B::Pow)),
5312 _ => return None,
5313 };
5314 Some(result)
5315}
5316
5317fn build_binary(op: BinOp, left: Expr, right: Expr, span: Span, op_pos: Position) -> Result<Expr> {
5318 match op {
5319 BinOp::Binary(op) => Ok(Expr::at_operator(
5320 ExprKind::Binary {
5321 op,
5322 left: Box::new(left),
5323 right: Box::new(right),
5324 },
5325 span,
5326 op_pos,
5327 )),
5328 BinOp::Logical(op) => {
5329 let mixes = |expr: &Expr, op: LogicalOp| {
5333 matches!(&expr.kind, ExprKind::Logical { op: inner, .. }
5334 if (op == LogicalOp::Coalesce) != (*inner == LogicalOp::Coalesce))
5335 };
5336 if mixes(&left, op) || mixes(&right, op) {
5337 return Err(SyntaxError::new(
5338 "cannot mix ?? with && or ||",
5341 span,
5342 ));
5343 }
5344 Ok(Expr::at_operator(
5345 ExprKind::Logical {
5346 op,
5347 left: Box::new(left),
5348 right: Box::new(right),
5349 },
5350 span,
5351 op_pos,
5352 ))
5353 }
5354 }
5355}
5356
5357fn pattern_to_expr(pattern: Pattern, span: Span) -> Expr {
5360 match pattern.kind {
5361 PatternKind::Ident(ident) => Expr::new(ExprKind::Ident(ident), span),
5362 PatternKind::Assign { target, default } => Expr::new(
5363 ExprKind::Assign {
5364 op: AssignOp::Assign,
5365 target,
5366 value: default,
5367 },
5368 span,
5369 ),
5370 PatternKind::Member(member) => {
5374 let MemberPattern {
5375 object,
5376 property,
5377 span,
5378 op_pos,
5379 } = *member;
5380 Expr {
5381 kind: ExprKind::Member {
5382 object,
5383 property,
5384 optional: false,
5385 },
5386 span,
5387 op_pos,
5388 }
5389 }
5390 PatternKind::Object { properties, rest } => {
5391 let mut out = Vec::new();
5392 for element in properties {
5393 match element {
5394 Some(PatternElement::Property {
5395 key,
5396 value,
5397 shorthand,
5398 span: _,
5399 }) => {
5400 let span = value.span;
5401 out.push(ObjectProperty::Property {
5402 key,
5403 value: Box::new(pattern_to_expr(value, span)),
5404 kind: PropertyKind::Value,
5405 shorthand,
5406 span,
5407 });
5408 }
5409 None | Some(PatternElement::Pattern(_)) => {}
5412 }
5413 }
5414 if let Some(rest) = rest
5415 && let RestElement::Pattern(pattern) = *rest
5416 {
5417 let span = pattern.span;
5418 out.push(ObjectProperty::Spread(Box::new(pattern_to_expr(
5419 pattern, span,
5420 ))));
5421 }
5422 Expr::new(ExprKind::Object(out), span)
5423 }
5424 PatternKind::Array { elements, rest } => {
5425 let mut out = Vec::new();
5426 for element in elements {
5427 match element {
5428 Some(PatternElement::Pattern(pattern)) => {
5429 let span = pattern.span;
5430 out.push(Some(ArrayElement::Expr(Box::new(pattern_to_expr(
5431 pattern, span,
5432 )))));
5433 }
5434 Some(PatternElement::Property { .. }) | None => out.push(None),
5435 }
5436 }
5437 if let Some(rest) = rest {
5438 let RestElement::Pattern(pattern) = *rest else {
5439 return Expr::new(ExprKind::Null, span);
5440 };
5441 let span = pattern.span;
5442 out.push(Some(ArrayElement::Spread(Box::new(pattern_to_expr(
5443 pattern, span,
5444 )))));
5445 }
5446 Expr::new(ExprKind::Array { elements: out }, span)
5447 }
5448 _ => Expr::new(ExprKind::Null, span),
5449 }
5450}
5451
5452impl Pattern {
5453 fn unparen_kind(&self) -> &PatternKind {
5456 &self.kind
5457 }
5458}
5459
5460fn member_chain_import_call(expr: &Expr) -> Option<&Expr> {
5478 match &expr.kind {
5479 ExprKind::ImportCall(..) => Some(expr),
5480 ExprKind::Member { object, .. } => member_chain_import_call(object),
5481 _ => None,
5483 }
5484}
5485
5486fn deletes_a_private_member(expr: &Expr) -> bool {
5487 match &expr.unparen().kind {
5488 ExprKind::Member { property, .. } => matches!(property, MemberProp::Private(_)),
5489 ExprKind::Call { callee, .. } => deletes_a_private_member(callee),
5490 _ => false,
5491 }
5492}
5493
5494fn as_specifier(value: &Wtf8) -> String {
5501 value.to_string_lossy().into_owned()
5502}