1use crate::ast::*;
38use crate::error::{Result, SyntaxError};
39use crate::lexer::Lexer;
40use crate::token::{Keyword, NumberLiteral, Position, Punct, Span, TemplateKind, Token, TokenKind};
41
42struct Snapshot<'a> {
44 lexer: Lexer<'a>,
45 current: Token,
46 prev_end: Position,
47 strict: bool,
48 allow_in: bool,
49 ctx: FnCtx,
50 loop_depth: u32,
51 switch_depth: u32,
52 labels: Vec<Label>,
53 private: Vec<PrivateEnv>,
54 top_level: bool,
55 cover_inits: Vec<Span>,
56 pending_exports: Vec<(String, Span)>,
57 current_legacy_octal: bool,
58 scopes: Vec<Scope>,
59}
60
61#[derive(Debug, Clone, Copy)]
63struct FnCtx {
64 in_function: bool,
65 in_generator: bool,
66 in_async: bool,
67 in_method: bool,
69 in_derived_constructor: bool,
71 in_static_block: bool,
79 arguments_allowed: bool,
83}
84
85impl Default for FnCtx {
86 fn default() -> FnCtx {
87 FnCtx {
88 in_function: false,
89 in_generator: false,
90 in_async: false,
91 in_method: false,
92 in_derived_constructor: false,
93 in_static_block: false,
94 arguments_allowed: true,
97 }
98 }
99}
100
101#[derive(Debug, Clone, Copy, PartialEq, Eq)]
102enum LabelKind {
103 Iteration,
105 Other,
107}
108
109#[derive(Debug, Clone)]
110struct Label {
111 name: String,
112 kind: LabelKind,
113}
114
115#[derive(Debug, Clone, Default)]
117struct PrivateEnv {
118 names: Vec<PrivateName>,
119}
120
121#[derive(Debug, Clone)]
122struct PrivateName {
123 name: String,
124 has_get: bool,
125 has_set: bool,
126}
127
128impl PrivateEnv {
129 fn declare(&mut self, name: &str, accessor: Option<MethodKind>) -> bool {
132 if let Some(existing) = self.names.iter_mut().find(|n| n.name == name) {
133 return match accessor {
134 Some(MethodKind::Get) if !existing.has_get => {
135 existing.has_get = true;
136 true
137 }
138 Some(MethodKind::Set) if !existing.has_set => {
139 existing.has_set = true;
140 true
141 }
142 _ => false,
143 };
144 }
145 let mut entry = PrivateName {
146 name: name.to_string(),
147 has_get: false,
148 has_set: false,
149 };
150 match accessor {
151 Some(MethodKind::Get) => entry.has_get = true,
152 Some(MethodKind::Set) => entry.has_set = true,
153 _ => {}
154 }
155 self.names.push(entry);
156 true
157 }
158
159 fn contains(&self, name: &str) -> bool {
160 self.names.iter().any(|n| n.name == name)
161 }
162}
163
164#[derive(Debug, Clone, Copy, PartialEq, Eq)]
178enum Redefinition {
179 Lexical,
180 Global,
181 Variable,
182 Parameter,
183}
184
185impl Redefinition {
186 fn message(self) -> &'static str {
187 match self {
188 Redefinition::Lexical => "invalid redefinition of lexical identifier",
189 Redefinition::Global => "invalid redefinition of global identifier",
190 Redefinition::Variable => "invalid redefinition of a variable",
191 Redefinition::Parameter => "invalid redefinition of parameter name",
192 }
193 }
194}
195
196#[derive(Debug, Clone)]
197struct Scope {
198 is_var_scope: bool,
200 var_names: Vec<String>,
202 var_names_here: Vec<String>,
210 lex_names: Vec<String>,
212 fn_names: Vec<String>,
219 params: Vec<String>,
221 catch_names: Vec<String>,
229 plain_fn_names: Vec<String>,
238 import_names: Vec<String>,
245}
246
247impl Scope {
248 fn block() -> Scope {
249 Scope {
250 is_var_scope: false,
251 var_names: Vec::new(),
252 var_names_here: Vec::new(),
253 lex_names: Vec::new(),
254 fn_names: Vec::new(),
255 params: Vec::new(),
256 catch_names: Vec::new(),
257 plain_fn_names: Vec::new(),
258 import_names: Vec::new(),
259 }
260 }
261
262 fn function(params: Vec<String>) -> Scope {
263 Scope {
264 is_var_scope: true,
265 var_names: Vec::new(),
266 var_names_here: Vec::new(),
267 lex_names: Vec::new(),
268 fn_names: Vec::new(),
269 params,
270 catch_names: Vec::new(),
271 plain_fn_names: Vec::new(),
272 import_names: Vec::new(),
273 }
274 }
275}
276
277#[derive(Debug, Clone, Copy, PartialEq, Eq)]
279enum TargetKind {
280 Binding,
282 Assignment,
284}
285
286struct ArrowHead {
288 params: Vec<Pattern>,
289 is_async: bool,
290 span: Span,
291 params_span: Span,
292}
293
294pub const DEFAULT_MAX_DEPTH: u32 = if cfg!(debug_assertions) { 120 } else { 600 };
308
309pub struct Parser<'a> {
311 lexer: Lexer<'a>,
312 current: Token,
313 prev_end: Position,
314 strict: bool,
315 module: bool,
316 allow_in: bool,
317 ctx: FnCtx,
318 loop_depth: u32,
319 switch_depth: u32,
320 labels: Vec<Label>,
321 private: Vec<PrivateEnv>,
322 top_level: bool,
323 current_legacy_octal: bool,
326 in_case_clause: bool,
332 depth: u32,
335 max_depth: u32,
336
337 cover_inits: Vec<Span>,
341 pending_exports: Vec<(String, Span)>,
344 scopes: Vec<Scope>,
346}
347
348pub fn parse_script(src: &str) -> Result<Program> {
350 Parser::new(src, false)?.parse_program()
351}
352
353pub fn parse_module(src: &str) -> Result<Program> {
355 Parser::new(src, true)?.parse_program()
356}
357
358pub fn parse_suspensible_script(src: &str) -> Result<Program> {
367 Parser::new_suspensible(src)?.parse_program()
368}
369
370pub fn parse_script_strict(src: &str) -> Result<Program> {
378 let mut parser = Parser::new(src, false)?;
379 parser.enter_strict()?;
380 parser.parse_program()
381}
382
383pub fn parse_eval_script(src: &str, strict: bool) -> Result<Program> {
390 parse_eval_script_in(src, strict, EvalContext::default())
391}
392
393#[derive(Debug, Clone, Copy, Default)]
395pub struct EvalContext {
396 pub in_method: bool,
399 pub in_derived_constructor: bool,
401}
402
403pub fn parse_eval_script_in(src: &str, strict: bool, context: EvalContext) -> Result<Program> {
409 let mut parser = Parser::new(src, false)?;
410 parser.ctx.in_function = true;
411 parser.ctx.in_method = context.in_method;
412 parser.ctx.in_derived_constructor = context.in_derived_constructor;
413 if strict {
414 parser.enter_strict()?;
415 }
416 parser.parse_program()
417}
418
419pub fn parse_suspensible_global_eval(src: &str, strict: bool) -> Result<Program> {
427 let mut parser = Parser::new_suspensible(src)?;
428 if strict {
429 parser.enter_strict()?;
430 }
431 parser.parse_program()
432}
433
434pub fn parse_expression(src: &str) -> Result<Expr> {
437 let mut parser = Parser::new(src, false)?;
438 let expr = parser.parse_expression(true)?;
439 if !parser.current.is_eof() {
440 return Err(parser.unexpected());
441 }
442 Ok(expr)
443}
444
445impl<'a> Parser<'a> {
446 pub fn new(src: &'a str, module: bool) -> Result<Parser<'a>> {
453 Parser::with_modes(src, module, false)
454 }
455
456 pub fn new_suspensible(src: &'a str) -> Result<Parser<'a>> {
463 Parser::with_modes(src, false, true)
464 }
465
466 fn with_modes(src: &'a str, module: bool, async_body: bool) -> Result<Parser<'a>> {
467 let mut lexer = Lexer::new(src);
468 lexer.set_strict(module);
469 let current = lexer.next_token()?;
470 let current_legacy_octal = lexer.had_legacy_octal();
471 if module && current_legacy_octal {
472 return Err(SyntaxError::new(
473 "octal literals and octal escape sequences are not allowed in strict mode",
474 current.span,
475 ));
476 }
477 Ok(Parser {
478 lexer,
479 current,
480 prev_end: Position::START,
481 strict: module,
482 module,
483 allow_in: true,
484 ctx: FnCtx {
485 in_async: module || async_body,
486 ..FnCtx::default()
487 },
488 loop_depth: 0,
489 switch_depth: 0,
490 labels: Vec::new(),
491 private: Vec::new(),
492 top_level: true,
493 current_legacy_octal,
494 in_case_clause: false,
495 depth: 0,
496 max_depth: DEFAULT_MAX_DEPTH,
497
498 cover_inits: Vec::new(),
499 pending_exports: Vec::new(),
500 scopes: vec![Scope::function(Vec::new())],
501 })
502 }
503
504 pub fn set_max_depth(&mut self, depth: u32) {
506 self.max_depth = depth;
507 }
508
509 fn enter(&mut self) -> Result<()> {
511 self.depth += 1;
512 if self.depth > self.max_depth {
513 return Err(SyntaxError::new("stack overflow", self.current.span));
514 }
515 Ok(())
516 }
517
518 fn leave(&mut self) {
519 self.depth -= 1;
520 }
521
522 pub fn parse_program(&mut self) -> Result<Program> {
524 let start = self.current.span.start;
525 let mut body = Vec::new();
526 let mut prologue = true;
527 while !self.current.is_eof() {
528 let stmt = self.parse_statement_list_item()?;
529 if prologue {
530 match self.directive_value(&stmt) {
531 Some(directive) if directive == "use strict" => self.enter_strict()?,
532 Some(_) => {}
533 None => prologue = false,
534 }
535 }
536 body.push(stmt);
537 }
538 if self.module {
539 self.check_module_exports(&body)?;
540 }
541 Ok(Program {
542 kind: if self.module {
543 ProgramKind::Module
544 } else {
545 ProgramKind::Script
546 },
547 body,
548 span: Span::new(start, self.prev_end),
549 strict: self.strict,
550 })
551 }
552
553 fn check_module_exports(&mut self, body: &[Stmt]) -> Result<()> {
556 if self.pending_exports.is_empty() {
557 return Ok(());
558 }
559 let mut declared: Vec<String> = Vec::new();
560 for stmt in body {
561 collect_module_binding(stmt, &mut declared);
562 }
563 let pending = std::mem::take(&mut self.pending_exports);
564 for (name, span) in pending {
565 if !declared.contains(&name) {
566 return Err(self
569 .error_at(format!("exported variable '{name}' does not exist"), span)
570 .positionless());
571 }
572 }
573 Ok(())
574 }
575
576 fn push_scope(&mut self, scope: Scope) {
579 self.scopes.push(scope);
580 }
581
582 fn pop_scope(&mut self) {
583 self.scopes.pop();
584 }
585
586 fn declare_lexical(&mut self, name: &str) -> Result<()> {
593 let Some(scope) = self.scopes.last() else {
594 return Ok(());
595 };
596 let reason = if scope.lex_names.iter().any(|n| n == name)
599 || scope.catch_names.iter().any(|n| n == name)
600 {
601 Some(Redefinition::Lexical)
602 } else if scope.params.iter().any(|n| n == name) {
603 Some(Redefinition::Parameter)
604 } else if scope.fn_names.iter().any(|n| n == name)
605 || scope.var_names.iter().any(|n| n == name)
606 {
607 Some(if self.at_top_level_scope() {
612 Redefinition::Global
613 } else {
614 Redefinition::Variable
615 })
616 } else {
617 None
618 };
619 if let Some(reason) = reason {
620 return Err(self.duplicate_declaration(reason));
621 }
622 if let Some(scope) = self.scopes.last_mut() {
623 scope.lex_names.push(name.to_string());
624 }
625 Ok(())
626 }
627
628 fn declare_var(&mut self, name: &str) -> Result<()> {
631 for scope in self.scopes.iter().rev() {
632 if scope.lex_names.iter().any(|n| n == name) {
633 return Err(self.duplicate_declaration(Redefinition::Lexical));
634 }
635 if scope.is_var_scope {
636 break;
637 }
638 }
639 let Some(index) = self.scopes.iter().rposition(|s| s.is_var_scope) else {
640 return Ok(());
641 };
642 for scope in &mut self.scopes[index..] {
645 if !scope.var_names.iter().any(|n| n == name) {
646 scope.var_names.push(name.to_string());
647 }
648 }
649 if let Some(scope) = self.scopes.last_mut()
650 && !scope.var_names_here.iter().any(|n| n == name)
651 {
652 scope.var_names_here.push(name.to_string());
653 }
654 Ok(())
655 }
656
657 fn check_duplicate_parameters(
678 &self,
679 params: &[Pattern],
680 plain_is_illegal: bool,
681 deferred_at: Span,
682 ) -> Result<()> {
683 let has_default = params.iter().any(pattern_has_default);
684 let mut seen: Vec<String> = Vec::new();
685 let mut deferred = false;
686 for param in params {
687 for (name, span, in_pattern) in parameter_bindings(param) {
688 if seen.iter().any(|seen| seen == &name) {
689 if has_default || in_pattern {
690 return Err(self.error_at(
691 "duplicate parameter names not allowed in this context".to_string(),
692 span,
693 ));
694 }
695 deferred = true;
696 }
697 seen.push(name);
698 }
699 }
700 if deferred && plain_is_illegal {
701 return Err(self.error_at(
702 "duplicate argument names not allowed in this context".to_string(),
703 deferred_at,
704 ));
705 }
706 Ok(())
707 }
708
709 fn declare_function(&mut self, name: &str) -> Result<()> {
725 if !self.scopes.last().is_none_or(|scope| scope.is_var_scope) {
726 return Ok(());
727 }
728 if !self.at_top_level_scope()
734 && self
735 .scopes
736 .last()
737 .is_some_and(|scope| scope.lex_names.iter().any(|n| n == name))
738 {
739 return Err(self.duplicate_declaration(Redefinition::Lexical));
740 }
741 if let Some(scope) = self.scopes.last_mut() {
742 if !scope.var_names.iter().any(|n| n == name) {
743 scope.var_names.push(name.to_string());
744 }
745 if !scope.fn_names.iter().any(|n| n == name) {
746 scope.fn_names.push(name.to_string());
747 }
748 }
749 Ok(())
750 }
751
752 fn declare_block_function(&mut self, name: &str, is_plain: bool) -> Result<()> {
761 if self.module
769 && self.at_top_level_scope()
770 && let Some(scope) = self.scopes.last()
771 {
772 let mut taken = scope.var_names_here.iter().any(|existing| existing == name);
778 if scope.is_var_scope {
779 let module_bindings = scope
780 .lex_names
781 .iter()
782 .filter(|existing| !scope.import_names.contains(existing))
783 .chain(&scope.fn_names);
784 taken |= module_bindings.into_iter().any(|existing| existing == name);
785 }
786 if taken {
787 return Err(self.error_at(
788 "invalid redefinition of global identifier in module code",
789 self.current.span,
790 ));
791 }
792 }
793 if self.scopes.last().is_none_or(|scope| scope.is_var_scope) {
794 return Ok(());
795 }
796 let Some(scope) = self.scopes.last() else {
797 return Ok(());
798 };
799 if scope.lex_names.iter().any(|n| n == name) || scope.catch_names.iter().any(|n| n == name)
800 {
801 let from_plain_function = scope.plain_fn_names.iter().any(|n| n == name);
805 if !(from_plain_function && is_plain && !self.strict) {
806 return Err(self.duplicate_declaration(Redefinition::Lexical));
807 }
808 } else if scope.var_names.iter().any(|n| n == name) {
809 let reason = if self.at_top_level_scope() {
813 Redefinition::Global
814 } else {
815 Redefinition::Variable
816 };
817 return Err(self.duplicate_declaration(reason));
818 }
819 if let Some(scope) = self.scopes.last_mut() {
820 if !scope.lex_names.iter().any(|n| n == name) {
821 scope.lex_names.push(name.to_string());
822 }
823 if !scope.fn_names.iter().any(|n| n == name) {
824 scope.fn_names.push(name.to_string());
825 }
826 if is_plain && !scope.plain_fn_names.iter().any(|n| n == name) {
827 scope.plain_fn_names.push(name.to_string());
828 }
829 }
830 Ok(())
831 }
832
833 fn duplicate_declaration(&self, reason: Redefinition) -> SyntaxError {
845 self.error_at(reason.message(), self.current.span)
846 }
847
848 fn at_top_level_scope(&self) -> bool {
854 self.scopes.iter().rposition(|scope| scope.is_var_scope) == Some(0)
855 }
856
857 fn declare_pattern(&mut self, pattern: &Pattern, is_var: bool) -> Result<()> {
859 let mut names = Vec::new();
860 pattern.bound_names(&mut names);
861 for name in names {
862 if is_var {
863 self.declare_var(&name.name)?;
864 } else {
865 self.declare_lexical(&name.name)?;
866 }
867 }
868 Ok(())
869 }
870
871 fn snapshot(&self) -> Snapshot<'a> {
874 Snapshot {
875 lexer: self.lexer.clone(),
876 current: self.current.clone(),
877 prev_end: self.prev_end,
878 strict: self.strict,
879 allow_in: self.allow_in,
880 ctx: self.ctx,
881 loop_depth: self.loop_depth,
882 switch_depth: self.switch_depth,
883 labels: self.labels.clone(),
884 private: self.private.clone(),
885 top_level: self.top_level,
886 cover_inits: self.cover_inits.clone(),
887 pending_exports: self.pending_exports.clone(),
888 current_legacy_octal: self.current_legacy_octal,
889 scopes: self.scopes.clone(),
890 }
891 }
892
893 fn restore(&mut self, snap: Snapshot<'a>) {
894 self.lexer = snap.lexer;
895 self.current = snap.current;
896 self.prev_end = snap.prev_end;
897 self.strict = snap.strict;
898 self.allow_in = snap.allow_in;
899 self.ctx = snap.ctx;
900 self.loop_depth = snap.loop_depth;
901 self.switch_depth = snap.switch_depth;
902 self.labels = snap.labels;
903 self.private = snap.private;
904 self.top_level = snap.top_level;
905 self.cover_inits = snap.cover_inits;
906 self.pending_exports = snap.pending_exports;
907 self.current_legacy_octal = snap.current_legacy_octal;
908 self.scopes = snap.scopes;
909 }
910
911 fn bump(&mut self) -> Result<()> {
912 self.prev_end = self.current.span.end;
913 self.current = self.lexer.next_token()?;
914 self.current_legacy_octal = self.lexer.had_legacy_octal();
915 if self.strict && self.current_legacy_octal {
916 return Err(SyntaxError::new(
917 "octal literals and octal escape sequences are not allowed in strict mode",
918 self.current.span,
919 ));
920 }
921 Ok(())
922 }
923
924 fn peek(&self) -> Result<Token> {
925 let mut lexer = self.lexer.clone();
926 lexer.next_token()
927 }
928
929 fn enter_strict(&mut self) -> Result<()> {
930 self.strict = true;
931 self.lexer.set_strict(true);
932 if self.current_legacy_octal {
935 return Err(SyntaxError::new(
936 "octal literals and octal escape sequences are not allowed in strict mode",
937 self.current.span,
938 ));
939 }
940 Ok(())
941 }
942
943 fn at_punct(&self, p: Punct) -> bool {
944 matches!(&self.current.kind, TokenKind::Punct(q) if *q == p)
945 }
946
947 fn at_keyword(&self, k: Keyword) -> bool {
948 matches!(&self.current.kind, TokenKind::Keyword(q) if *q == k)
949 }
950
951 fn at_contextual(&self, name: &str) -> bool {
952 self.at_ident(name)
953 }
954
955 fn at_ident(&self, name: &str) -> bool {
956 matches!(&self.current.kind, TokenKind::Ident(n) if n == name)
957 }
958
959 fn eat_punct(&mut self, p: Punct) -> Result<bool> {
960 if self.at_punct(p) {
961 self.bump()?;
962 return Ok(true);
963 }
964 Ok(false)
965 }
966
967 fn expect_punct(&mut self, p: Punct) -> Result<()> {
968 if self.eat_punct(p)? {
969 Ok(())
970 } else {
971 Err(self.error(format!("expecting '{}'", p.as_str())))
976 }
977 }
978
979 fn eat_keyword(&mut self, k: Keyword) -> Result<bool> {
980 if self.at_keyword(k) {
981 self.bump()?;
982 return Ok(true);
983 }
984 Ok(false)
985 }
986
987 fn eat_contextual(&mut self, name: &str) -> Result<bool> {
988 if self.at_ident(name) {
989 self.bump()?;
990 return Ok(true);
991 }
992 Ok(false)
993 }
994
995 fn unexpected(&self) -> SyntaxError {
1002 let source = self.lexer.source();
1003 let start = self.current.span.start.offset as usize;
1004 let end = self.current.span.end.offset as usize;
1005 let text = source.get(start..end).unwrap_or("");
1006 SyntaxError::new(
1007 format!("unexpected token in expression: '{text}'"),
1008 self.current.span,
1009 )
1010 }
1011
1012 fn error(&self, message: impl Into<String>) -> SyntaxError {
1013 SyntaxError::new(message, self.current.span)
1014 }
1015
1016 fn error_at(&self, message: impl Into<String>, span: Span) -> SyntaxError {
1017 SyntaxError::new(message, span)
1018 }
1019
1020 fn span_from(&self, start: Position) -> Span {
1021 Span::new(start, self.prev_end)
1022 }
1023
1024 fn expect_binding_ident(&mut self) -> Result<Ident> {
1027 let ident = self.expect_ident()?;
1028 self.check_binding_name(&ident.name, ident.span)?;
1029 Ok(ident)
1030 }
1031
1032 fn expect_ident(&mut self) -> Result<Ident> {
1034 match self.current.kind.clone() {
1035 TokenKind::Ident(name) => {
1036 if name == "await" && self.await_is_reserved() {
1039 return Err(self.error("variable name expected"));
1040 }
1041 let span = self.current.span;
1042 self.check_identifier(&name, span)?;
1043 self.bump()?;
1044 Ok(Ident { name, span })
1045 }
1046 _ => Err(self.error("variable name expected")),
1049 }
1050 }
1051
1052 fn at_formal_parameter(&self) -> bool {
1059 if self.at_punct(Punct::LBracket) || self.at_punct(Punct::LBrace) {
1060 return true;
1061 }
1062 match &self.current.kind {
1063 TokenKind::Ident(name) => !(name == "await" && self.await_is_reserved()),
1064 _ => false,
1065 }
1066 }
1067
1068 fn await_is_reserved(&self) -> bool {
1078 self.ctx.in_async || self.module || self.ctx.in_static_block
1081 }
1082
1083 fn check_identifier(&self, name: &str, span: Span) -> Result<()> {
1085 if Keyword::lookup(name).is_some() {
1086 return Err(self.error_at(format!("unexpected keyword '{name}'"), span));
1087 }
1088 if self.strict && Keyword::is_strict_reserved(name) {
1089 return Err(self.error_at(
1090 format!("invalid use of strict mode reserved word '{name}'"),
1091 span,
1092 ));
1093 }
1094 if self.ctx.in_generator && name == "yield" {
1095 return Err(self.error_at(
1096 "invalid use of 'yield' identifier in a generator function",
1097 span,
1098 ));
1099 }
1100 if name == "await" && self.await_is_reserved() {
1101 return Err(self.error_at("unexpected 'await' keyword", span));
1106 }
1107 Ok(())
1108 }
1109
1110 fn check_arguments_reference(&self, name: &str, span: Span) -> Result<()> {
1117 if name == "arguments" && !self.ctx.arguments_allowed {
1118 return Err(self.error_at(
1119 "'arguments' identifier is not allowed in class field initializer",
1120 span,
1121 ));
1122 }
1123 Ok(())
1124 }
1125
1126 fn check_binding_name(&self, name: &str, span: Span) -> Result<()> {
1129 self.check_identifier(name, span)?;
1130 if self.strict && (name == "eval" || name == "arguments") {
1131 return Err(self.error_at("invalid variable name in strict mode", span));
1134 }
1135 if self.strict && name == "let" {
1136 return Err(self.error_at(
1137 "invalid use of 'let' as a variable name in strict mode",
1138 span,
1139 ));
1140 }
1141 Ok(())
1142 }
1143
1144 fn directive_value(&self, stmt: &Stmt) -> Option<String> {
1147 let StmtKind::Expr(expr) = &stmt.kind else {
1148 return None;
1149 };
1150 let ExprKind::String(value) = &expr.unparen().kind else {
1151 return None;
1152 };
1153 let raw = self.slice(expr.span);
1154 if !raw.starts_with('"') && !raw.starts_with('\'') {
1155 return None;
1156 }
1157 if raw.trim_matches(|c| c == '"' || c == '\'').contains('\\') {
1158 return None;
1159 }
1160 Some(value.clone())
1161 }
1162
1163 fn slice(&self, span: Span) -> &'a str {
1164 let src = self.lexer.source();
1165 let start = span.start.offset as usize;
1166 let end = (span.end.offset as usize).min(src.len());
1167 src.get(start..end).unwrap_or("")
1168 }
1169
1170 fn can_insert_semicolon(&self) -> bool {
1173 self.current.is_eof() || self.at_punct(Punct::RBrace) || self.current.newline_before
1174 }
1175
1176 fn semicolon(&mut self) -> Result<()> {
1177 if self.eat_punct(Punct::Semicolon)? {
1178 return Ok(());
1179 }
1180 if self.can_insert_semicolon() {
1181 return Ok(());
1182 }
1183 Err(self.error("expecting ';'"))
1186 }
1187
1188 fn parse_statement_list_item(&mut self) -> Result<Stmt> {
1191 self.enter()?;
1192 let result = self.parse_statement_list_item_guarded();
1193 self.leave();
1194 result
1195 }
1196
1197 fn parse_statement_list_item_guarded(&mut self) -> Result<Stmt> {
1198 let cover_mark = self.cover_inits.len();
1199 let stmt = self.parse_statement_list_item_inner()?;
1200 if self.cover_inits.len() > cover_mark {
1201 let span = self.cover_inits[cover_mark];
1202 self.cover_inits.truncate(cover_mark);
1203 return Err(self.error_at("expecting '}'", span));
1204 }
1205 Ok(stmt)
1206 }
1207
1208 fn parse_statement_list_item_inner(&mut self) -> Result<Stmt> {
1209 if self.at_keyword(Keyword::Function) {
1210 let start = self.current.span.start;
1211 let func = self.parse_function(FunctionForm::Declaration, false)?;
1212 if let Some(name) = &func.name {
1213 self.declare_function(&name.name)?;
1214 }
1215 return Ok(Stmt::new(
1216 StmtKind::FuncDecl(Box::new(func)),
1217 self.span_from(start),
1218 ));
1219 }
1220 if self.at_ident("async") {
1221 let peek = self.peek()?;
1222 if matches!(peek.kind, TokenKind::Keyword(Keyword::Function)) && !peek.newline_before {
1223 let start = self.current.span.start;
1224 self.bump()?; let func = self.parse_function(FunctionForm::Declaration, true)?;
1226 if let Some(name) = &func.name {
1227 self.declare_function(&name.name)?;
1228 }
1229 return Ok(Stmt::new(
1230 StmtKind::FuncDecl(Box::new(func)),
1231 self.span_from(start),
1232 ));
1233 }
1234 }
1235 if self.at_keyword(Keyword::Class) {
1236 let start = self.current.span.start;
1237 let class = self.parse_class(false)?;
1238 if let Some(name) = &class.name {
1239 self.declare_lexical(&name.name)?;
1240 }
1241 return Ok(Stmt::new(
1242 StmtKind::ClassDecl(Box::new(class)),
1243 self.span_from(start),
1244 ));
1245 }
1246 if self.at_keyword(Keyword::Var) {
1247 let start = self.current.span.start;
1248 let decl = self.parse_var_decl(VarDeclKind::Var, false, true)?;
1249 self.semicolon()?;
1250 return Ok(Stmt::new(StmtKind::VarDecl(decl), self.span_from(start)));
1251 }
1252 if self.at_keyword(Keyword::Const) {
1253 let start = self.current.span.start;
1254 let decl = self.parse_var_decl(VarDeclKind::Const, false, true)?;
1255 self.semicolon()?;
1256 return Ok(Stmt::new(StmtKind::VarDecl(decl), self.span_from(start)));
1257 }
1258 if self.at_ident("let") && self.let_starts_declaration()? {
1259 let start = self.current.span.start;
1260 let decl = self.parse_var_decl(VarDeclKind::Let, false, true)?;
1261 self.semicolon()?;
1262 return Ok(Stmt::new(StmtKind::VarDecl(decl), self.span_from(start)));
1263 }
1264 if self.at_ident("await") && self.ctx.in_async && self.await_using_follows()? {
1267 let start = self.current.span.start;
1268 self.bump()?; let decl = self.parse_var_decl_with_keyword(VarDeclKind::AwaitUsing, "using")?;
1273 self.semicolon()?;
1274 return Ok(Stmt::new(StmtKind::VarDecl(decl), self.span_from(start)));
1275 }
1276 if self.at_ident("using") && self.using_starts_declaration()? {
1277 let start = self.current.span.start;
1278 if self.scopes.len() == 1 && !self.module {
1284 return Err(self.error_at(
1285 "using declaration is not allowed at the top level of a script",
1286 self.span_from(start),
1287 ));
1288 }
1289 if self.in_case_clause {
1294 return Err(self.error_at(
1295 "using declaration is not allowed in this context",
1296 self.span_from(start),
1297 ));
1298 }
1299 let decl = self.parse_var_decl(VarDeclKind::Using, false, true)?;
1300 self.semicolon()?;
1301 return Ok(Stmt::new(StmtKind::VarDecl(decl), self.span_from(start)));
1302 }
1303 if self.module && self.at_keyword(Keyword::Import) {
1304 let peek = self.peek()?;
1305 if !matches!(
1307 peek.kind,
1308 TokenKind::Punct(Punct::LParen) | TokenKind::Punct(Punct::Dot)
1309 ) {
1310 return self.parse_import_decl();
1311 }
1312 }
1313 if self.module && self.at_keyword(Keyword::Export) {
1314 return self.parse_export_decl();
1315 }
1316 self.parse_statement()
1317 }
1318
1319 fn let_starts_declaration(&self) -> Result<bool> {
1321 let peek = self.peek()?;
1322 Ok(matches!(
1323 peek.kind,
1324 TokenKind::Ident(_)
1325 | TokenKind::Punct(Punct::LBracket)
1326 | TokenKind::Punct(Punct::LBrace)
1327 ))
1328 }
1329
1330 fn using_head_tail(&self, skip: usize) -> Result<Option<Token>> {
1336 let mut lexer = self.lexer.clone();
1337 let mut binding = None;
1341 for _ in 0..=skip {
1342 binding = Some(lexer.next_token()?);
1343 }
1344 let Some(binding) = binding else {
1345 return Ok(None);
1346 };
1347 if binding.newline_before || !matches!(binding.kind, TokenKind::Ident(_)) {
1348 return Ok(None);
1349 }
1350 Ok(Some(lexer.next_token()?))
1351 }
1352
1353 fn await_using_follows(&self) -> Result<bool> {
1359 Ok(matches!(
1360 self.using_head_tail(1)?.map(|token| token.kind),
1361 Some(TokenKind::Punct(Punct::Eq))
1362 ))
1363 }
1364
1365 fn using_starts_declaration(&self) -> Result<bool> {
1376 Ok(matches!(
1377 self.using_head_tail(0)?.map(|token| token.kind),
1378 Some(TokenKind::Punct(Punct::Eq))
1379 ))
1380 }
1381
1382 fn using_starts_for_head(&self) -> Result<bool> {
1387 Ok(matches!(
1388 self.using_head_tail(0)?.map(|token| token.kind),
1389 Some(TokenKind::Ident(name)) if name == "of" || name == "in"
1390 ))
1391 }
1392
1393 fn await_using_starts_for_head(&self) -> Result<bool> {
1395 Ok(matches!(
1396 self.using_head_tail(1)?.map(|token| token.kind),
1397 Some(TokenKind::Ident(name)) if name == "of" || name == "in"
1398 ))
1399 }
1400
1401 fn parse_statement(&mut self) -> Result<Stmt> {
1402 let start = self.current.span.start;
1403 if self.at_punct(Punct::Semicolon) {
1404 self.bump()?;
1405 return Ok(Stmt::new(StmtKind::Empty, self.span_from(start)));
1406 }
1407 if self.at_punct(Punct::LBrace) {
1408 let body = self.parse_block()?;
1409 return Ok(Stmt::new(StmtKind::Block(body), self.span_from(start)));
1410 }
1411 if self.at_keyword(Keyword::If) {
1412 return self.parse_if();
1413 }
1414 if self.at_keyword(Keyword::Do) {
1415 return self.parse_do_while();
1416 }
1417 if self.at_keyword(Keyword::While) {
1418 return self.parse_while();
1419 }
1420 if self.at_keyword(Keyword::For) {
1421 return self.parse_for();
1422 }
1423 if self.at_keyword(Keyword::Switch) {
1424 return self.parse_switch();
1425 }
1426 if self.at_keyword(Keyword::Try) {
1427 return self.parse_try();
1428 }
1429 if self.at_keyword(Keyword::Return) {
1430 return self.parse_return();
1431 }
1432 if self.at_keyword(Keyword::Throw) {
1433 return self.parse_throw();
1434 }
1435 if self.at_keyword(Keyword::Break) {
1436 return self.parse_break_continue(true);
1437 }
1438 if self.at_keyword(Keyword::Continue) {
1439 return self.parse_break_continue(false);
1440 }
1441 if self.at_keyword(Keyword::With) {
1442 return self.parse_with();
1443 }
1444 if self.at_keyword(Keyword::Debugger) {
1445 self.bump()?;
1446 self.semicolon()?;
1447 return Ok(Stmt::new(StmtKind::Debugger, self.span_from(start)));
1448 }
1449 if self.at_keyword(Keyword::Function) {
1450 if self.strict {
1453 return Err(
1454 self.error("invalid 'function' declaration in a single statement context")
1455 );
1456 }
1457 let func = self.parse_function(FunctionForm::Declaration, false)?;
1458 if let Some(name) = &func.name {
1459 self.declare_function(&name.name)?;
1460 }
1461 return Ok(Stmt::new(
1462 StmtKind::FuncDecl(Box::new(func)),
1463 self.span_from(start),
1464 ));
1465 }
1466 if self.at_keyword(Keyword::Class) {
1467 return Err(self.error("invalid 'class' declaration in a single statement context"));
1468 }
1469 if self.at_keyword(Keyword::Import) {
1470 let peek = self.peek()?;
1474 let expression = matches!(
1475 peek.kind,
1476 TokenKind::Punct(Punct::LParen) | TokenKind::Punct(Punct::Dot)
1477 );
1478 if !expression {
1479 return Err(self.error("'import' can only appear at the top level of a module"));
1480 }
1481 }
1482 if self.at_keyword(Keyword::Export) {
1483 return Err(self.error("'export' can only appear at the top level of a module"));
1484 }
1485 if let TokenKind::Ident(name) = &self.current.kind {
1487 if name == "await" && self.await_is_reserved() {
1491 if !self.ctx.in_async {
1492 let peek = self.peek()?;
1495 if matches!(peek.kind, TokenKind::Punct(Punct::Colon)) {
1496 return Err(self.error("unexpected 'await' keyword"));
1497 }
1498 }
1499 } else {
1503 let peek = self.peek()?;
1504 if matches!(peek.kind, TokenKind::Punct(Punct::Colon)) {
1505 return self.parse_labeled();
1506 }
1507 }
1508 }
1509 self.parse_expression_statement()
1510 }
1511
1512 fn parse_block(&mut self) -> Result<Vec<Stmt>> {
1513 self.expect_punct(Punct::LBrace)?;
1514 self.push_scope(Scope::block());
1515 let saved_in_case = self.in_case_clause;
1518 self.in_case_clause = false;
1519 let result = self.parse_block_body();
1520 self.in_case_clause = saved_in_case;
1521 self.pop_scope();
1522 let body = result?;
1523 self.bump()?; Ok(body)
1525 }
1526
1527 fn parse_catch_body(&mut self) -> Result<Vec<Stmt>> {
1529 self.expect_punct(Punct::LBrace)?;
1530 let body = self.parse_block_body()?;
1531 self.bump()?; Ok(body)
1533 }
1534
1535 fn parse_block_body(&mut self) -> Result<Vec<Stmt>> {
1536 let mut body = Vec::new();
1537 while !self.at_punct(Punct::RBrace) {
1538 if self.current.is_eof() {
1539 return Err(self.unexpected());
1540 }
1541 body.push(self.parse_statement_list_item()?);
1542 }
1543 Ok(body)
1544 }
1545
1546 fn parse_expression_statement(&mut self) -> Result<Stmt> {
1547 let start = self.current.span.start;
1548 let expr = self.parse_expression(true)?;
1549 self.semicolon()?;
1550 Ok(Stmt::new(
1551 StmtKind::Expr(Box::new(expr)),
1552 self.span_from(start),
1553 ))
1554 }
1555
1556 fn parse_if(&mut self) -> Result<Stmt> {
1557 let start = self.current.span.start;
1558 self.bump()?; self.expect_punct(Punct::LParen)?;
1560 let test = self.parse_expression(true)?;
1561 self.expect_punct(Punct::RParen)?;
1562 let cons = self.parse_statement()?;
1563 let alt = if self.eat_keyword(Keyword::Else)? {
1564 Some(Box::new(self.parse_statement()?))
1565 } else {
1566 None
1567 };
1568 Ok(Stmt::new(
1569 StmtKind::If {
1570 test: Box::new(test),
1571 cons: Box::new(cons),
1572 alt,
1573 },
1574 self.span_from(start),
1575 ))
1576 }
1577
1578 fn parse_do_while(&mut self) -> Result<Stmt> {
1579 let start = self.current.span.start;
1580 self.bump()?; self.loop_depth += 1;
1582 let body = self.parse_statement();
1583 self.loop_depth -= 1;
1584 let body = body?;
1585 if !self.eat_keyword(Keyword::While)? {
1586 return Err(self.unexpected());
1587 }
1588 self.expect_punct(Punct::LParen)?;
1589 let test = self.parse_expression(true)?;
1590 self.expect_punct(Punct::RParen)?;
1591 let _ = self.eat_punct(Punct::Semicolon)?;
1593 Ok(Stmt::new(
1594 StmtKind::DoWhile {
1595 body: Box::new(body),
1596 test: Box::new(test),
1597 },
1598 self.span_from(start),
1599 ))
1600 }
1601
1602 fn parse_while(&mut self) -> Result<Stmt> {
1603 let start = self.current.span.start;
1604 self.bump()?; self.expect_punct(Punct::LParen)?;
1606 let test = self.parse_expression(true)?;
1607 self.expect_punct(Punct::RParen)?;
1608 self.loop_depth += 1;
1609 let body = self.parse_statement();
1610 self.loop_depth -= 1;
1611 Ok(Stmt::new(
1612 StmtKind::While {
1613 test: Box::new(test),
1614 body: Box::new(body?),
1615 },
1616 self.span_from(start),
1617 ))
1618 }
1619
1620 fn parse_for(&mut self) -> Result<Stmt> {
1621 let start = self.current.span.start;
1622 self.bump()?; self.push_scope(Scope::block());
1624 let result = self.parse_for_inner(start);
1625 self.pop_scope();
1626 result
1627 }
1628
1629 fn parse_for_inner(&mut self, start: Position) -> Result<Stmt> {
1630 let mut is_await = false;
1631 if self.at_ident("await") && self.ctx.in_async {
1632 let peek = self.peek()?;
1633 if matches!(peek.kind, TokenKind::Punct(Punct::LParen)) && !peek.newline_before {
1634 is_await = true;
1635 self.bump()?;
1636 }
1637 }
1638 self.expect_punct(Punct::LParen)?;
1639
1640 if self.at_punct(Punct::Semicolon) {
1642 self.bump()?;
1643 return self.parse_for_classic(start, None);
1644 }
1645
1646 let decl_kind = if self.at_keyword(Keyword::Var) {
1648 Some(VarDeclKind::Var)
1649 } else if self.at_keyword(Keyword::Const) {
1650 Some(VarDeclKind::Const)
1651 } else if self.at_ident("let") && self.let_starts_declaration()? {
1652 Some(VarDeclKind::Let)
1653 } else if self.at_ident("using") && self.using_starts_for_head()? {
1654 Some(VarDeclKind::Using)
1655 } else if self.at_ident("await")
1656 && self.ctx.in_async
1657 && self.await_using_starts_for_head()?
1658 {
1659 self.bump()?; Some(VarDeclKind::AwaitUsing)
1661 } else {
1662 None
1663 };
1664 if let Some(kind) = decl_kind {
1665 let decl_start = self.current.span.start;
1666 let decl = self.parse_var_decl(kind, true, false)?;
1667 if self.at_for_head_keyword() {
1668 let is_of = self.at_contextual("of");
1669 if !is_of && decl.declarators.len() != 1 {
1670 return Err(self.error_at(
1671 "only one binding allowed in a for-in loop",
1672 self.span_from(decl_start),
1673 ));
1674 }
1675 if is_of && decl.declarators.len() != 1 {
1676 return Err(self.error_at(
1677 "only one binding allowed in a for-of loop",
1678 self.span_from(decl_start),
1679 ));
1680 }
1681 if let Some(declarator) = decl.declarators.first() {
1682 if declarator.init.is_some() {
1683 if is_of || kind.is_lexical() || self.strict {
1685 return Err(self.error_at(
1686 if is_of {
1687 "a declaration in the head of a for-of loop can't have an initializer"
1689 } else {
1690 "a declaration in the head of a for-in loop can't have an initializer"
1691 },
1692 declarator.span,
1693 ));
1694 }
1695 }
1696 }
1697 if is_await && !is_of {
1698 return Err(self.error("for await is only valid with 'of'"));
1699 }
1700 self.bump()?; let right = self.parse_expression(true)?;
1702 self.expect_punct(Punct::RParen)?;
1703 self.loop_depth += 1;
1704 let body = self.parse_statement();
1705 self.loop_depth -= 1;
1706 let head = ForHead::VarDecl(decl);
1707 let span = self.span_from(start);
1708 return Ok(Stmt::new(
1709 if is_of {
1710 StmtKind::ForOf {
1711 is_await,
1712 left: head,
1713 right: Box::new(right),
1714 body: Box::new(body?),
1715 }
1716 } else {
1717 StmtKind::ForIn {
1718 left: head,
1719 right: Box::new(right),
1720 body: Box::new(body?),
1721 }
1722 },
1723 span,
1724 ));
1725 }
1726 self.expect_punct(Punct::Semicolon)?;
1727 return self.parse_for_classic(start, Some(ForInit::VarDecl(decl)));
1728 }
1729
1730 let expr_start = self.current.span.start;
1732 let expr = self.parse_expression(false)?;
1733 if self.at_for_head_keyword() {
1734 let is_of = self.at_contextual("of");
1735 if is_await && !is_of {
1736 return Err(self.error("for await is only valid with 'of'"));
1737 }
1738 let target = self.expr_to_pattern(expr, TargetKind::Assignment)?;
1739 self.bump()?; let right = self.parse_expression(true)?;
1741 self.expect_punct(Punct::RParen)?;
1742 self.loop_depth += 1;
1743 let body = self.parse_statement();
1744 self.loop_depth -= 1;
1745 let head = ForHead::Assign(Box::new(target));
1746 let span = self.span_from(start);
1747 return Ok(Stmt::new(
1748 if is_of {
1749 StmtKind::ForOf {
1750 is_await,
1751 left: head,
1752 right: Box::new(right),
1753 body: Box::new(body?),
1754 }
1755 } else {
1756 StmtKind::ForIn {
1757 left: head,
1758 right: Box::new(right),
1759 body: Box::new(body?),
1760 }
1761 },
1762 span,
1763 ));
1764 }
1765 let _ = expr_start;
1766 self.expect_punct(Punct::Semicolon)?;
1767 self.parse_for_classic(start, Some(ForInit::Expr(Box::new(expr))))
1768 }
1769
1770 fn at_for_head_keyword(&self) -> bool {
1773 self.at_keyword(Keyword::In) || self.at_contextual("of")
1774 }
1775
1776 fn parse_for_classic(&mut self, start: Position, init: Option<ForInit>) -> Result<Stmt> {
1777 let test = if self.at_punct(Punct::Semicolon) {
1778 None
1779 } else {
1780 Some(Box::new(self.parse_expression(true)?))
1781 };
1782 self.expect_punct(Punct::Semicolon)?;
1783 let update = if self.at_punct(Punct::RParen) {
1784 None
1785 } else {
1786 Some(Box::new(self.parse_expression(true)?))
1787 };
1788 self.expect_punct(Punct::RParen)?;
1789 self.loop_depth += 1;
1790 let body = self.parse_statement();
1791 self.loop_depth -= 1;
1792 Ok(Stmt::new(
1793 StmtKind::For {
1794 init,
1795 test,
1796 update,
1797 body: Box::new(body?),
1798 },
1799 self.span_from(start),
1800 ))
1801 }
1802
1803 fn parse_switch(&mut self) -> Result<Stmt> {
1804 let start = self.current.span.start;
1805 self.bump()?; self.expect_punct(Punct::LParen)?;
1807 let discriminant = self.parse_expression(true)?;
1808 self.expect_punct(Punct::RParen)?;
1809 self.expect_punct(Punct::LBrace)?;
1810 self.switch_depth += 1;
1811 self.push_scope(Scope::block());
1812 let mut cases = Vec::new();
1813 let mut seen_default = false;
1814 while !self.at_punct(Punct::RBrace) {
1815 if self.current.is_eof() {
1816 self.switch_depth -= 1;
1817 return Err(self.unexpected());
1818 }
1819 let case_start = self.current.span.start;
1820 let test = if self.eat_keyword(Keyword::Case)? {
1821 Some(Box::new(self.parse_expression(true)?))
1822 } else if self.eat_keyword(Keyword::Default)? {
1823 if seen_default {
1824 self.switch_depth -= 1;
1825 return Err(self.error("duplicate 'default' clause in switch statement"));
1826 }
1827 seen_default = true;
1828 None
1829 } else {
1830 self.switch_depth -= 1;
1831 return Err(self.unexpected());
1832 };
1833 self.expect_punct(Punct::Colon)?;
1834 let mut body = Vec::new();
1835 let saved_in_case = self.in_case_clause;
1836 self.in_case_clause = true;
1837 while !self.at_punct(Punct::RBrace)
1838 && !self.at_keyword(Keyword::Case)
1839 && !self.at_keyword(Keyword::Default)
1840 {
1841 if self.current.is_eof() {
1842 self.in_case_clause = saved_in_case;
1843 self.switch_depth -= 1;
1844 return Err(self.unexpected());
1845 }
1846 match self.parse_statement_list_item() {
1847 Ok(stmt) => body.push(stmt),
1848 Err(error) => {
1849 self.in_case_clause = saved_in_case;
1850 self.switch_depth -= 1;
1851 return Err(error);
1852 }
1853 }
1854 }
1855 self.in_case_clause = saved_in_case;
1856 cases.push(SwitchCase {
1857 test,
1858 body,
1859 span: self.span_from(case_start),
1860 });
1861 }
1862 self.switch_depth -= 1;
1863 self.bump()?; self.pop_scope();
1872 Ok(Stmt::new(
1873 StmtKind::Switch {
1874 discriminant: Box::new(discriminant),
1875 cases,
1876 },
1877 self.span_from(start),
1878 ))
1879 }
1880
1881 fn parse_try(&mut self) -> Result<Stmt> {
1882 let start = self.current.span.start;
1883 self.bump()?; let block = self.parse_block()?;
1885 let mut handler = None;
1886 let mut finalizer = None;
1887 if self.at_keyword(Keyword::Catch) {
1888 let catch_start = self.current.span.start;
1889 self.bump()?;
1890 let param = if self.eat_punct(Punct::LParen)? {
1896 let pattern = self.parse_binding_target()?;
1897 self.expect_punct(Punct::RParen)?;
1898 Some(pattern)
1899 } else {
1900 None
1901 };
1902 self.push_scope(Scope::block());
1903 let body = match ¶m {
1904 Some(Pattern {
1907 kind: PatternKind::Ident(id),
1908 ..
1909 }) => {
1910 if let Some(scope) = self.scopes.last_mut() {
1911 scope.catch_names.push(id.name.clone());
1912 }
1913 self.parse_catch_body()
1914 }
1915 Some(pattern) => {
1920 self.declare_pattern(pattern, false)?;
1921 self.parse_block()
1922 }
1923 None => self.parse_catch_body(),
1924 };
1925 self.pop_scope();
1926 let body = body?;
1927 handler = Some(CatchClause {
1928 param,
1929 body,
1930 span: self.span_from(catch_start),
1931 });
1932 }
1933 if self.eat_keyword(Keyword::Finally)? {
1934 finalizer = Some(self.parse_block()?);
1935 }
1936 if handler.is_none() && finalizer.is_none() {
1937 return Err(self.error("expecting catch or finally"));
1938 }
1939 Ok(Stmt::new(
1940 StmtKind::Try {
1941 block,
1942 handler,
1943 finalizer,
1944 },
1945 self.span_from(start),
1946 ))
1947 }
1948
1949 fn parse_return(&mut self) -> Result<Stmt> {
1950 let start = self.current.span.start;
1951 let span = self.current.span;
1952 if !self.ctx.in_function {
1953 return Err(self.error_at("return not in a function", span));
1954 }
1955 if self.ctx.in_static_block {
1956 return Err(self.error_at("return in a static initializer block", span));
1960 }
1961 self.bump()?;
1962 let argument = if self.at_punct(Punct::Semicolon)
1963 || self.at_punct(Punct::RBrace)
1964 || self.current.is_eof()
1965 || self.current.newline_before
1966 {
1967 None
1968 } else {
1969 Some(Box::new(self.parse_expression(true)?))
1970 };
1971 self.semicolon()?;
1972 Ok(Stmt::new(StmtKind::Return(argument), self.span_from(start)))
1973 }
1974
1975 fn parse_throw(&mut self) -> Result<Stmt> {
1976 let start = self.current.span.start;
1977 self.bump()?; if self.current.newline_before {
1979 return Err(self.error("line terminator not allowed after 'throw'"));
1980 }
1981 let argument = self.parse_expression(true)?;
1982 self.semicolon()?;
1983 Ok(Stmt::new(
1984 StmtKind::Throw(Box::new(argument)),
1985 self.span_from(start),
1986 ))
1987 }
1988
1989 fn parse_break_continue(&mut self, is_break: bool) -> Result<Stmt> {
1990 let start = self.current.span.start;
1991 let keyword_span = self.current.span;
1992 self.bump()?;
1993 let label = if matches!(self.current.kind, TokenKind::Ident(_))
1994 && !self.current.newline_before
1995 {
1996 let ident = self.expect_ident()?;
1997 let found = self.labels.iter().rev().find(|l| l.name == ident.name);
1998 match found {
1999 None => {
2000 return Err(
2001 self.error_at(format!("label '{}' not found", ident.name), ident.span)
2002 );
2003 }
2004 Some(label) => {
2005 if !is_break && label.kind != LabelKind::Iteration {
2006 return Err(self.error_at(
2007 format!("continue must be inside loop (label '{}')", ident.name),
2008 ident.span,
2009 ));
2010 }
2011 }
2012 }
2013 Some(ident)
2014 } else {
2015 if !is_break && self.loop_depth == 0 {
2016 return Err(self.error_at("continue must be inside loop", keyword_span));
2017 }
2018 if is_break && self.loop_depth == 0 && self.switch_depth == 0 && self.labels.is_empty()
2019 {
2020 return Err(self.error_at("break must be inside loop or switch", keyword_span));
2021 }
2022 None
2023 };
2024 self.semicolon()?;
2025 Ok(Stmt::new(
2026 if is_break {
2027 StmtKind::Break(label)
2028 } else {
2029 StmtKind::Continue(label)
2030 },
2031 self.span_from(start),
2032 ))
2033 }
2034
2035 fn parse_with(&mut self) -> Result<Stmt> {
2036 let start = self.current.span.start;
2037 let span = self.current.span;
2038 if self.strict {
2039 return Err(self.error_at("invalid keyword: with", span));
2040 }
2041 self.bump()?; self.expect_punct(Punct::LParen)?;
2043 let object = self.parse_expression(true)?;
2044 self.expect_punct(Punct::RParen)?;
2045 let body = self.parse_statement()?;
2046 Ok(Stmt::new(
2047 StmtKind::With {
2048 object: Box::new(object),
2049 body: Box::new(body),
2050 },
2051 self.span_from(start),
2052 ))
2053 }
2054
2055 fn parse_labeled(&mut self) -> Result<Stmt> {
2056 let start = self.current.span.start;
2057 let label = self.expect_ident()?;
2058 self.expect_punct(Punct::Colon)?;
2059 if self.labels.iter().any(|l| l.name == label.name) {
2060 return Err(self.error_at(
2061 format!("label '{}' already declared", label.name),
2062 label.span,
2063 ));
2064 }
2065 let kind = if self.at_keyword(Keyword::For)
2066 || self.at_keyword(Keyword::While)
2067 || self.at_keyword(Keyword::Do)
2068 {
2069 LabelKind::Iteration
2070 } else {
2071 LabelKind::Other
2072 };
2073 self.labels.push(Label {
2074 name: label.name.clone(),
2075 kind,
2076 });
2077 let body = self.parse_statement();
2078 self.labels.pop();
2079 Ok(Stmt::new(
2080 StmtKind::Labeled {
2081 label,
2082 body: Box::new(body?),
2083 },
2084 self.span_from(start),
2085 ))
2086 }
2087
2088 fn parse_var_decl(
2091 &mut self,
2092 kind: VarDeclKind,
2093 in_for_head: bool,
2094 require_init: bool,
2095 ) -> Result<VarDecl> {
2096 let start = self.current.span.start;
2097 self.bump()?; self.parse_var_declarators(kind, in_for_head, require_init, start)
2099 }
2100
2101 fn parse_var_decl_with_keyword(&mut self, kind: VarDeclKind, keyword: &str) -> Result<VarDecl> {
2106 let start = self.current.span.start;
2107 if !self.at_ident(keyword) {
2108 return Err(self.error(format!("expected '{keyword}'")));
2109 }
2110 self.bump()?;
2111 self.parse_var_declarators(kind, false, true, start)
2112 }
2113
2114 fn parse_var_declarators(
2115 &mut self,
2116 kind: VarDeclKind,
2117 in_for_head: bool,
2118 require_init: bool,
2119 start: Position,
2120 ) -> Result<VarDecl> {
2121 let mut declarators = Vec::new();
2122 loop {
2123 let declarator_start = self.current.span.start;
2124 let target = self.parse_binding_target()?;
2125 self.declare_pattern(&target, !kind.is_lexical())?;
2130 if kind.is_using() && !matches!(target.unparen_kind(), PatternKind::Ident(_)) {
2133 return Err(self.error_at(
2134 "binding patterns are not allowed in using declarations",
2135 target.span,
2136 ));
2137 }
2138 let init = if self.eat_punct(Punct::Eq)? {
2139 Some(Box::new(self.parse_assignment(!in_for_head)?))
2142 } else {
2143 None
2144 };
2145 if init.is_none() && require_init {
2146 if kind == VarDeclKind::Const {
2147 return Err(self.error("missing initializer for const variable"));
2148 }
2149 if kind.is_using() {
2150 return Err(self.error("missing initializer in using declaration"));
2151 }
2152 if !matches!(target.unparen_kind(), PatternKind::Ident(_)) && !in_for_head {
2153 return Err(self.error_at(
2154 "missing initializer in destructuring declaration",
2155 target.span,
2156 ));
2157 }
2158 }
2159 if kind.is_lexical() {
2160 let mut names = Vec::new();
2161 target.bound_names(&mut names);
2162 if let Some(name) = names.iter().find(|n| n.name == "let") {
2163 return Err(self.error_at("'let' is not a valid lexical identifier", name.span));
2164 }
2165 }
2166 declarators.push(Declarator {
2167 target,
2168 init,
2169 span: self.span_from(declarator_start),
2170 });
2171 if !self.eat_punct(Punct::Comma)? {
2172 break;
2173 }
2174 }
2175 Ok(VarDecl {
2176 kind,
2177 declarators,
2178 span: self.span_from(start),
2179 })
2180 }
2181
2182 fn parse_binding_element(&mut self) -> Result<Pattern> {
2185 let pattern = self.parse_binding_target()?;
2186 if self.eat_punct(Punct::Eq)? {
2187 let start = pattern.span.start;
2188 let default = self.parse_assignment(self.allow_in)?;
2189 return Ok(Pattern::new(
2190 PatternKind::Assign {
2191 target: Box::new(pattern),
2192 default: Box::new(default),
2193 },
2194 self.span_from(start),
2195 ));
2196 }
2197 Ok(pattern)
2198 }
2199
2200 fn parse_binding_target(&mut self) -> Result<Pattern> {
2203 self.enter()?;
2204 let result = self.parse_binding_target_unguarded();
2205 self.leave();
2206 result
2207 }
2208
2209 fn parse_binding_target_unguarded(&mut self) -> Result<Pattern> {
2210 let start = self.current.span.start;
2211 if self.at_punct(Punct::LBracket) {
2212 return self.parse_array_pattern(start);
2213 }
2214 if self.at_punct(Punct::LBrace) {
2215 return self.parse_object_pattern(start);
2216 }
2217 let ident = self.expect_binding_ident()?;
2218 Ok(Pattern::new(
2219 PatternKind::Ident(ident),
2220 self.span_from(start),
2221 ))
2222 }
2223
2224 fn parse_array_pattern(&mut self, start: Position) -> Result<Pattern> {
2225 self.expect_punct(Punct::LBracket)?;
2226 let mut elements = Vec::new();
2227 let mut rest = None;
2228 loop {
2229 if self.at_punct(Punct::RBracket) {
2230 break;
2231 }
2232 if self.at_punct(Punct::Comma) {
2233 self.bump()?;
2234 elements.push(None);
2235 continue;
2236 }
2237 if self.at_punct(Punct::Ellipsis) {
2238 self.bump()?;
2239 let target = self.parse_binding_target()?;
2240 if self.at_punct(Punct::Comma) {
2241 return Err(self.error("rest element must be the last one"));
2242 }
2243 rest = Some(Box::new(RestElement::Pattern(target)));
2244 break;
2245 }
2246 let element_start = self.current.span.start;
2247 let element = self.parse_binding_element()?;
2248 let span = self.span_from(element_start);
2249 elements.push(Some(PatternElement::Pattern(element)));
2250 let _ = span;
2251 if !self.eat_punct(Punct::Comma)? {
2252 break;
2253 }
2254 }
2255 self.expect_punct(Punct::RBracket)?;
2256 Ok(Pattern::new(
2257 PatternKind::Array { elements, rest },
2258 self.span_from(start),
2259 ))
2260 }
2261
2262 fn parse_object_pattern(&mut self, start: Position) -> Result<Pattern> {
2263 self.expect_punct(Punct::LBrace)?;
2264 let mut properties = Vec::new();
2265 let mut rest = None;
2266 loop {
2267 if self.at_punct(Punct::RBrace) {
2268 break;
2269 }
2270 if self.at_punct(Punct::Ellipsis) {
2271 self.bump()?;
2272 let target = self.parse_binding_target()?;
2273 rest = Some(Box::new(RestElement::Pattern(target)));
2274 if self.at_punct(Punct::Comma) {
2275 return Err(self.error("rest element must be the last one"));
2276 }
2277 break;
2278 }
2279 let property_start = self.current.span.start;
2280 let key = self.parse_property_key()?;
2281 if self.eat_punct(Punct::Colon)? {
2282 let value = self.parse_binding_element()?;
2283 properties.push(Some(PatternElement::Property {
2284 key,
2285 value,
2286 shorthand: false,
2287 span: self.span_from(property_start),
2288 }));
2289 } else {
2290 let PropName::Literal(PropKey::Str(name)) = &key else {
2291 return Err(
2292 self.error("expecting ':' after a computed or numeric property key")
2293 );
2294 };
2295 let span = self.span_from(property_start);
2296 let ident = Ident {
2297 name: name.clone(),
2298 span,
2299 };
2300 self.check_binding_name(&ident.name, ident.span)?;
2301 let mut value = Pattern::new(PatternKind::Ident(ident), span);
2302 if self.eat_punct(Punct::Eq)? {
2303 let default = self.parse_assignment(self.allow_in)?;
2304 value = Pattern::new(
2305 PatternKind::Assign {
2306 target: Box::new(value),
2307 default: Box::new(default),
2308 },
2309 span,
2310 );
2311 }
2312 properties.push(Some(PatternElement::Property {
2313 key,
2314 value,
2315 shorthand: true,
2316 span,
2317 }));
2318 }
2319 if !self.eat_punct(Punct::Comma)? {
2320 break;
2321 }
2322 }
2323 self.expect_punct(Punct::RBrace)?;
2324 Ok(Pattern::new(
2325 PatternKind::Object { properties, rest },
2326 self.span_from(start),
2327 ))
2328 }
2329
2330 fn parse_property_key(&mut self) -> Result<PropName> {
2332 match self.current.kind.clone() {
2333 TokenKind::Ident(name) => {
2334 self.bump()?;
2335 Ok(PropName::Literal(PropKey::Str(name)))
2336 }
2337 TokenKind::Keyword(kw) => {
2338 self.bump()?;
2340 Ok(PropName::Literal(PropKey::Str(kw.as_str().to_string())))
2341 }
2342 TokenKind::String(value) => {
2343 self.bump()?;
2344 Ok(PropName::Literal(PropKey::Str(value)))
2345 }
2346 TokenKind::Number(NumberLiteral::Int(v)) => {
2347 self.bump()?;
2348 Ok(PropName::Literal(PropKey::Num(v as f64)))
2349 }
2350 TokenKind::Number(NumberLiteral::Float(v)) => {
2351 self.bump()?;
2352 Ok(PropName::Literal(PropKey::Num(v)))
2353 }
2354 TokenKind::BigInt(big) => Err(self.error(format!(
2355 "BigInt property keys are not supported ('{}n')",
2356 big.digits
2357 ))),
2358 TokenKind::Punct(Punct::LBracket) => {
2359 self.bump()?;
2360 let expr = self.parse_assignment(true)?;
2361 self.expect_punct(Punct::RBracket)?;
2362 Ok(PropName::Computed(Box::new(expr)))
2363 }
2364 TokenKind::Punct(Punct::Hash) => {
2365 self.bump()?;
2366 let ident = self.expect_ident()?;
2367 Ok(PropName::Private(ident))
2368 }
2369 _ => Err(self.error("invalid property name")),
2372 }
2373 }
2374
2375 fn parse_function(&mut self, form: FunctionForm, is_async: bool) -> Result<Function> {
2378 let start = self.current.span.start;
2379 self.bump()?; let is_generator = self.eat_punct(Punct::Star)?;
2381 let name = if matches!(self.current.kind, TokenKind::Ident(_)) {
2382 let ident = if form == FunctionForm::Declaration {
2383 self.expect_binding_ident()?
2384 } else {
2385 self.expect_ident()?
2386 };
2387 if is_generator && ident.name == "yield" {
2388 return Err(self.error_at("invalid use of 'yield' as a function name", ident.span));
2389 }
2390 if is_async && ident.name == "await" {
2391 return Err(self.error_at("invalid use of 'await' as a function name", ident.span));
2392 }
2393 Some(ident)
2394 } else {
2395 if form == FunctionForm::Declaration {
2396 return Err(self.error("function name expected"));
2397 }
2398 None
2399 };
2400 if form == FunctionForm::Declaration
2410 && let Some(ident) = &name
2411 {
2412 self.declare_block_function(&ident.name, !is_async && !is_generator)?;
2413 }
2414 let saved = self.ctx;
2415 self.ctx = FnCtx {
2416 in_function: true,
2417 in_generator: is_generator,
2418 in_async: is_async,
2419 in_method: false,
2420 in_derived_constructor: false,
2421 in_static_block: false,
2422 arguments_allowed: true,
2423 };
2424 let saved_top = self.top_level;
2425 self.top_level = false;
2426 let params_result = self.parse_formal_parameters();
2432 let result = match params_result {
2433 Ok(params) => self.parse_function_body(params, false),
2434 Err(err) => Err(err),
2435 };
2436 self.ctx = saved;
2437 self.top_level = saved_top;
2438 let (params, params_span, body, strict) = result?;
2439 Ok(Function {
2440 name,
2441 params,
2442 body,
2443 is_async,
2444 is_generator,
2445 strict,
2446 is_arrow: false,
2447 span: self.span_from(start),
2448 params_span,
2449 })
2450 }
2451
2452 fn parse_formal_parameters(&mut self) -> Result<Vec<Pattern>> {
2453 self.expect_punct(Punct::LParen)?;
2454 let mut params = Vec::new();
2455 loop {
2456 if self.at_punct(Punct::RParen) {
2457 break;
2458 }
2459 if self.at_punct(Punct::Ellipsis) {
2460 self.bump()?;
2461 if !self.at_formal_parameter() {
2464 return Err(self.error("missing formal parameter"));
2465 }
2466 let target = self.parse_binding_target()?;
2467 if matches!(target.unparen_kind(), PatternKind::Assign { .. }) {
2468 return Err(
2469 self.error_at("rest element cannot have a default value", target.span)
2470 );
2471 }
2472 params.push(Pattern::new(
2473 PatternKind::Rest(Box::new(target.clone())),
2474 target.span,
2475 ));
2476 if self.at_punct(Punct::Comma) {
2479 return Err(self.error("expecting ')'"));
2480 }
2481 break;
2482 }
2483 if !self.at_formal_parameter() {
2484 return Err(self.error("missing formal parameter"));
2485 }
2486 let param = self.parse_binding_element()?;
2487 self.check_parameter(¶m)?;
2488 params.push(param);
2489 if !self.eat_punct(Punct::Comma)? {
2490 break;
2491 }
2492 }
2493 self.expect_punct(Punct::RParen)?;
2494 Ok(params)
2495 }
2496
2497 fn check_parameter(&self, param: &Pattern) -> Result<()> {
2498 match ¶m.kind {
2499 PatternKind::Ident(ident) => self.check_binding_name(&ident.name, ident.span),
2500 PatternKind::Assign { target, .. } => self.check_parameter(target),
2501 _ => Ok(()),
2502 }
2503 }
2504
2505 fn parse_function_body(
2506 &mut self,
2507 params: Vec<Pattern>,
2508 is_method: bool,
2509 ) -> Result<(Vec<Pattern>, Span, FunctionBody, bool)> {
2510 let params_span = self.prev_end;
2511 let saved_strict = self.strict;
2516 if !self.at_punct(Punct::LBrace) {
2517 return Err(self.unexpected());
2518 }
2519 let saved_in_case = self.in_case_clause;
2522 self.in_case_clause = false;
2523 let param_names = simple_parameter_names(¶ms);
2524 let simple_params = params
2525 .iter()
2526 .all(|p| matches!(p.unparen_kind(), PatternKind::Ident(_)));
2527 let mut body = Vec::new();
2528 let mut prologue = true;
2529 let mut strict_seen = false;
2530 self.bump()?; let body_start = self.current.span;
2535 self.push_scope(Scope::function(param_names));
2536 while !self.at_punct(Punct::RBrace) {
2537 if self.current.is_eof() {
2538 return Err(self.unexpected());
2539 }
2540 let stmt = self.parse_statement_list_item()?;
2541 if prologue {
2542 match self.directive_value(&stmt) {
2543 Some(directive) if directive == "use strict" => {
2544 strict_seen = true;
2545 self.enter_strict()?;
2546 }
2547 Some(_) => {}
2548 None => prologue = false,
2549 }
2550 }
2551 body.push(stmt);
2552 }
2553 self.pop_scope();
2554 self.bump()?; let body_strict = self.strict;
2558 if strict_seen && !simple_params {
2559 return Err(self.error_at(
2560 "\"use strict\" not allowed in function with default or destructuring parameter",
2562 Span::new(params_span, params_span),
2563 ));
2564 }
2565 self.check_duplicate_parameters(
2576 ¶ms,
2577 body_strict || !simple_params || is_method,
2578 body_start,
2579 )?;
2580 let params_span_value = Span::new(params_span, params_span);
2581 self.strict = saved_strict;
2582 self.lexer.set_strict(saved_strict);
2583 self.in_case_clause = saved_in_case;
2584 Ok((
2585 params,
2586 params_span_value,
2587 FunctionBody::Block(body),
2588 body_strict,
2589 ))
2590 }
2591
2592 fn parse_class(&mut self, is_expression: bool) -> Result<Class> {
2595 let start = self.current.span.start;
2596 self.bump()?; let name = if matches!(self.current.kind, TokenKind::Ident(_)) {
2598 if is_expression {
2599 Some(self.expect_ident()?)
2600 } else {
2601 Some(self.expect_binding_ident()?)
2602 }
2603 } else {
2604 if !is_expression {
2605 return Err(self.error("class statement requires a name"));
2606 }
2607 None
2608 };
2609 let super_class = if self.eat_keyword(Keyword::Extends)? {
2610 Some(Box::new(self.parse_lhs_expression()?))
2611 } else {
2612 None
2613 };
2614 let has_super = super_class.is_some();
2615 self.private.push(PrivateEnv::default());
2616 self.expect_punct(Punct::LBrace)?;
2617 let mut elements = Vec::new();
2618 let mut seen_constructor = false;
2619 let result = (|| -> Result<()> {
2620 while !self.at_punct(Punct::RBrace) {
2621 if self.eat_punct(Punct::Semicolon)? {
2625 continue;
2626 }
2627 elements.push(self.parse_class_element(has_super, &mut seen_constructor)?);
2628 }
2629 Ok(())
2630 })();
2631 self.private.pop();
2632 result?;
2633 let body_end = self.current.span.start;
2636 self.bump()?; Ok(Class {
2638 name,
2639 super_class,
2640 elements,
2641 span: self.span_from(start),
2642 body_end,
2643 })
2644 }
2645
2646 fn parse_static_block(&mut self, start: Position) -> Result<ClassElement> {
2654 let saved = self.ctx;
2655 let saved_top = self.top_level;
2656 self.ctx = FnCtx {
2657 in_function: true,
2658 in_generator: false,
2659 in_async: false,
2660 in_method: true,
2662 in_derived_constructor: false,
2663 in_static_block: true,
2664 arguments_allowed: false,
2665 };
2666 self.top_level = false;
2667 let saved_strict = self.strict;
2673 let enter = self.enter_strict();
2674 let saved_loop = self.loop_depth;
2677 let saved_switch = self.switch_depth;
2678 let saved_labels = std::mem::take(&mut self.labels);
2679 self.loop_depth = 0;
2680 self.switch_depth = 0;
2681 let body_start = self.current.span.start;
2682 let body = match enter {
2683 Ok(()) => self.parse_block(),
2684 Err(error) => Err(error),
2685 };
2686 self.strict = saved_strict;
2687 self.lexer.set_strict(saved_strict);
2688 self.ctx = saved;
2689 self.top_level = saved_top;
2690 self.loop_depth = saved_loop;
2691 self.switch_depth = saved_switch;
2692 self.labels = saved_labels;
2693 let body = body?;
2694 Ok(ClassElement::StaticBlock {
2695 body,
2696 body_start,
2697 span: self.span_from(start),
2698 })
2699 }
2700
2701 fn parse_class_element(
2702 &mut self,
2703 has_super: bool,
2704 seen_constructor: &mut bool,
2705 ) -> Result<ClassElement> {
2706 let start = self.current.span.start;
2707 let mut is_static = false;
2708 if self.at_ident("static") {
2709 let peek = self.peek()?;
2710 let is_modifier = !matches!(
2711 peek.kind,
2712 TokenKind::Punct(Punct::LParen)
2713 | TokenKind::Punct(Punct::Eq)
2714 | TokenKind::Punct(Punct::Semicolon)
2715 | TokenKind::Punct(Punct::RBrace)
2716 );
2717 if is_modifier {
2718 self.bump()?; if self.at_punct(Punct::LBrace) {
2720 return self.parse_static_block(start);
2721 }
2722 is_static = true;
2723 }
2724 }
2725
2726 let mut is_async = false;
2728 let mut is_generator = false;
2729 let mut accessor: Option<MethodKind> = None;
2730 if self.at_ident("async") {
2731 let peek = self.peek()?;
2732 let is_modifier = !matches!(
2733 peek.kind,
2734 TokenKind::Punct(Punct::LParen)
2735 | TokenKind::Punct(Punct::Eq)
2736 | TokenKind::Punct(Punct::Semicolon)
2737 | TokenKind::Punct(Punct::RBrace)
2738 ) && !peek.newline_before;
2739 if is_modifier {
2740 self.bump()?;
2741 is_async = true;
2742 }
2743 }
2744 if self.at_punct(Punct::Star) {
2745 self.bump()?;
2746 is_generator = true;
2747 }
2748 if accessor.is_none() && (self.at_ident("get") || self.at_ident("set")) {
2749 let is_get = self.at_ident("get");
2750 let peek = self.peek()?;
2751 if is_property_key_start(&peek.kind) {
2752 self.bump()?;
2753 accessor = Some(if is_get {
2754 MethodKind::Get
2755 } else {
2756 MethodKind::Set
2757 });
2758 }
2759 }
2760 let key = self.parse_property_key()?;
2761
2762 if let PropName::Private(ident) = &key {
2764 if let Some(env) = self.private.last_mut() {
2765 if !env.declare(&ident.name, accessor) {
2766 return Err(self.error_at(
2767 "private class field is already defined".to_string(),
2770 ident.span,
2771 ));
2772 }
2773 }
2774 }
2775
2776 if self.at_punct(Punct::LParen) {
2777 let kind = match accessor {
2778 Some(kind) => kind,
2779 None => {
2780 let is_constructor = !is_static
2781 && !is_generator
2782 && !is_async
2783 && matches!(&key, PropName::Literal(PropKey::Str(s)) if s == "constructor");
2784 if is_constructor {
2785 if *seen_constructor {
2786 return Err(self.error_at(
2787 "property constructor appears more than once",
2788 self.span_from(start),
2789 ));
2790 }
2791 *seen_constructor = true;
2792 MethodKind::Constructor
2793 } else {
2794 MethodKind::Method
2795 }
2796 }
2797 };
2798 if kind == MethodKind::Constructor && (is_generator || is_async) {
2799 return Err(self.error("a constructor may not be a generator or async"));
2800 }
2801 let saved = self.ctx;
2802 self.ctx = FnCtx {
2803 in_function: true,
2804 in_generator: is_generator,
2805 in_async: is_async,
2806 in_method: true,
2807 in_derived_constructor: kind == MethodKind::Constructor && has_super,
2808 in_static_block: false,
2809 arguments_allowed: true,
2810 };
2811 let saved_top = self.top_level;
2812 self.top_level = false;
2813 let result = (|| -> Result<Function> {
2814 let params = self.parse_formal_parameters()?;
2815 let (params, params_span, body, strict) = self.parse_function_body(params, true)?;
2816 Ok(Function {
2817 name: None,
2818 params,
2819 body,
2820 is_async,
2821 is_generator,
2822 strict,
2823 is_arrow: false,
2824 span: self.span_from(start),
2825 params_span,
2826 })
2827 })();
2828 self.ctx = saved;
2829 self.top_level = saved_top;
2830 let func = result?;
2831 if is_static {
2832 if let PropName::Literal(PropKey::Str(name)) = &key {
2833 if name == "prototype" {
2834 return Err(self.error_at("invalid method name", func.span));
2835 }
2836 }
2837 }
2838 if kind == MethodKind::Get && !func.params.is_empty() {
2839 return Err(self.error_at(
2840 "invalid number of arguments for getter or setter",
2841 func.span,
2842 ));
2843 }
2844 if kind == MethodKind::Set && func.params.len() != 1 {
2845 return Err(self.error_at(
2846 "invalid number of arguments for getter or setter",
2847 func.span,
2848 ));
2849 }
2850 return Ok(ClassElement::Method {
2851 key,
2852 is_static,
2853 kind,
2854 func: Box::new(func),
2855 span: self.span_from(start),
2856 });
2857 }
2858
2859 if accessor.is_some() {
2861 return Err(self.error("expecting '(' after an accessor name"));
2862 }
2863 if let PropName::Literal(PropKey::Str(name)) = &key {
2864 if name == "constructor" && !is_static {
2865 return Err(self.error("classes may not have a field named 'constructor'"));
2866 }
2867 if name == "prototype" && is_static {
2868 return Err(self.error("classes may not have a static property named 'prototype'"));
2869 }
2870 }
2871 let saved = self.ctx;
2875 let saved_top = self.top_level;
2876 self.ctx = FnCtx {
2877 in_function: true,
2878 in_generator: false,
2879 in_async: false,
2880 in_method: true,
2881 in_derived_constructor: false,
2882 in_static_block: false,
2883 arguments_allowed: false,
2884 };
2885 self.top_level = false;
2886 let value = self
2887 .eat_punct(Punct::Eq)?
2888 .then(|| self.parse_assignment(true));
2889 self.ctx = saved;
2890 self.top_level = saved_top;
2891 let value = match value {
2892 Some(value) => Some(Box::new(value?)),
2893 None => None,
2894 };
2895 self.semicolon()?;
2897 Ok(ClassElement::Field {
2898 key,
2899 is_static,
2900 value,
2901 span: self.span_from(start),
2902 })
2903 }
2904
2905 fn parse_import_decl(&mut self) -> Result<Stmt> {
2908 let start = self.current.span.start;
2909 self.bump()?; let mut specifiers = Vec::new();
2911 if let TokenKind::String(source) = self.current.kind.clone() {
2912 self.bump()?;
2913 let attributes = self.parse_import_attributes()?;
2914 self.semicolon()?;
2915 return Ok(Stmt::new(
2916 StmtKind::Import(Box::new(ImportDecl {
2917 specifiers,
2918 source,
2919 attributes,
2920 span: self.span_from(start),
2921 })),
2922 self.span_from(start),
2923 ));
2924 }
2925 if matches!(self.current.kind, TokenKind::Ident(_)) {
2927 let local = self.expect_ident()?;
2928 specifiers.push(ImportSpecifier::Default(local));
2929 if !self.eat_punct(Punct::Comma)? {
2930 return self.finish_import(start, specifiers);
2931 }
2932 }
2933 if self.at_punct(Punct::Star) {
2934 self.bump()?;
2935 if !self.eat_contextual("as")? {
2936 return Err(self.unexpected());
2937 }
2938 let local = self.expect_ident()?;
2939 specifiers.push(ImportSpecifier::Namespace(local));
2940 return self.finish_import(start, specifiers);
2941 }
2942 if self.at_punct(Punct::LBrace) {
2943 self.bump()?;
2944 while !self.at_punct(Punct::RBrace) {
2945 let imported = self.parse_module_name()?;
2946 let local = if self.eat_contextual("as")? {
2947 self.expect_ident()?
2948 } else {
2949 match &imported {
2950 ModuleName::Ident(id) => id.clone(),
2951 ModuleName::Str(_) => {
2952 return Err(self.error_at(
2953 "a string module name must be followed by 'as'",
2954 self.current.span,
2955 ));
2956 }
2957 }
2958 };
2959 specifiers.push(ImportSpecifier::Named { imported, local });
2960 if !self.eat_punct(Punct::Comma)? {
2961 break;
2962 }
2963 }
2964 self.expect_punct(Punct::RBrace)?;
2965 } else if !specifiers.is_empty() {
2966 return Err(self.unexpected());
2967 } else if self.at_punct(Punct::LBrace) {
2968 unreachable!("handled above");
2969 } else {
2970 return Err(self.unexpected());
2971 }
2972 self.finish_import(start, specifiers)
2973 }
2974
2975 fn finish_import(&mut self, start: Position, specifiers: Vec<ImportSpecifier>) -> Result<Stmt> {
2976 if !self.eat_contextual("from")? {
2977 return Err(self.unexpected());
2978 }
2979 let TokenKind::String(source) = self.current.kind.clone() else {
2980 return Err(self.error("string expected"));
2981 };
2982 self.bump()?;
2983 let attributes = self.parse_import_attributes()?;
2984 self.semicolon()?;
2985 let span = self.span_from(start);
2986 for specifier in &specifiers {
2987 let local = match specifier {
2988 ImportSpecifier::Default(id) => id,
2989 ImportSpecifier::Namespace(id) => id,
2990 ImportSpecifier::Named { local, .. } => local,
2991 };
2992 self.declare_lexical(&local.name)?;
2993 if let Some(scope) = self.scopes.last_mut()
2994 && !scope.import_names.iter().any(|n| n == &local.name)
2995 {
2996 scope.import_names.push(local.name.clone());
2997 }
2998 }
2999 Ok(Stmt::new(
3000 StmtKind::Import(Box::new(ImportDecl {
3001 specifiers,
3002 source,
3003 attributes,
3004 span,
3005 })),
3006 span,
3007 ))
3008 }
3009
3010 fn parse_import_attributes(&mut self) -> Result<Vec<ImportAttribute>> {
3011 let mut attributes = Vec::new();
3012 let has_with = self.at_keyword(Keyword::With) || self.at_ident("assert");
3013 if !has_with {
3014 return Ok(attributes);
3015 }
3016 let peek = self.peek()?;
3017 if !matches!(peek.kind, TokenKind::Punct(Punct::LBrace)) {
3018 return Ok(attributes);
3019 }
3020 self.bump()?; self.expect_punct(Punct::LBrace)?;
3022 while !self.at_punct(Punct::RBrace) {
3023 let attr_start = self.current.span.start;
3024 let key = match self.current.kind.clone() {
3025 TokenKind::Ident(name) => name,
3026 TokenKind::String(value) => value,
3027 _ => return Err(self.error("expecting an import attribute name")),
3028 };
3029 self.bump()?;
3030 self.expect_punct(Punct::Colon)?;
3031 let TokenKind::String(value) = self.current.kind.clone() else {
3032 return Err(self.error("expecting an import attribute value string"));
3033 };
3034 self.bump()?;
3035 attributes.push(ImportAttribute {
3036 key,
3037 value,
3038 span: self.span_from(attr_start),
3039 });
3040 if !self.eat_punct(Punct::Comma)? {
3041 break;
3042 }
3043 }
3044 self.expect_punct(Punct::RBrace)?;
3045 Ok(attributes)
3046 }
3047
3048 fn parse_module_name(&mut self) -> Result<ModuleName> {
3049 match self.current.kind.clone() {
3050 TokenKind::String(value) => {
3051 self.bump()?;
3052 Ok(ModuleName::Str(value))
3053 }
3054 TokenKind::Ident(_) => Ok(ModuleName::Ident(self.expect_ident()?)),
3055 TokenKind::Keyword(kw) => {
3056 let span = self.current.span;
3057 self.bump()?;
3058 Ok(ModuleName::Ident(Ident {
3059 name: kw.as_str().to_string(),
3060 span,
3061 }))
3062 }
3063 _ => Err(self.error("identifier or string expected")),
3066 }
3067 }
3068
3069 fn parse_export_decl(&mut self) -> Result<Stmt> {
3070 let start = self.current.span.start;
3071 self.bump()?; if self.at_punct(Punct::Star) {
3073 self.bump()?;
3074 let mut exported = None;
3075 if self.eat_contextual("as")? {
3076 exported = Some(self.parse_module_name()?);
3077 }
3078 if !self.eat_contextual("from")? {
3079 return Err(self.error("expecting 'from' after 'export *'"));
3080 }
3081 let TokenKind::String(source) = self.current.kind.clone() else {
3082 return Err(self.error("string expected"));
3083 };
3084 self.bump()?;
3085 let attributes = self.parse_import_attributes()?;
3086 self.semicolon()?;
3087 let span = self.span_from(start);
3088 return Ok(Stmt::new(
3089 StmtKind::Export(Box::new(ExportDecl {
3090 kind: ExportKind::All {
3091 source,
3092 exported,
3093 attributes,
3094 },
3095 span,
3096 })),
3097 span,
3098 ));
3099 }
3100 if self.eat_keyword(Keyword::Default)? {
3101 let value = if self.at_keyword(Keyword::Function) {
3102 let func = self.parse_function(FunctionForm::Expression, false)?;
3103 Expr::new(ExprKind::Function(Box::new(func)), self.span_from(start))
3104 } else if self.at_ident("async") {
3105 let peek = self.peek()?;
3106 if matches!(peek.kind, TokenKind::Keyword(Keyword::Function)) {
3107 self.bump()?;
3108 let func = self.parse_function(FunctionForm::Expression, true)?;
3109 Expr::new(ExprKind::Function(Box::new(func)), self.span_from(start))
3110 } else {
3111 self.parse_assignment(true)?
3112 }
3113 } else if self.at_keyword(Keyword::Class) {
3114 let class = self.parse_class(true)?;
3115 Expr::new(ExprKind::Class(Box::new(class)), self.span_from(start))
3116 } else {
3117 let expr = self.parse_assignment(true)?;
3118 self.semicolon()?;
3119 expr
3120 };
3121 let span = self.span_from(start);
3122 return Ok(Stmt::new(
3123 StmtKind::Export(Box::new(ExportDecl {
3124 kind: ExportKind::Default(Box::new(value)),
3125 span,
3126 })),
3127 span,
3128 ));
3129 }
3130 if self.at_keyword(Keyword::Var)
3131 || self.at_keyword(Keyword::Const)
3132 || self.at_keyword(Keyword::Function)
3133 || self.at_keyword(Keyword::Class)
3134 || (self.at_ident("let") && self.let_starts_declaration()?)
3135 {
3136 let decl = self.parse_statement_list_item()?;
3137 let span = self.span_from(start);
3138 return Ok(Stmt::new(
3139 StmtKind::Export(Box::new(ExportDecl {
3140 kind: ExportKind::Declaration(Box::new(decl)),
3141 span,
3142 })),
3143 span,
3144 ));
3145 }
3146 if self.at_ident("async") {
3147 let peek = self.peek()?;
3148 if matches!(peek.kind, TokenKind::Keyword(Keyword::Function)) && !peek.newline_before {
3149 let decl = self.parse_statement_list_item()?;
3150 let span = self.span_from(start);
3151 return Ok(Stmt::new(
3152 StmtKind::Export(Box::new(ExportDecl {
3153 kind: ExportKind::Declaration(Box::new(decl)),
3154 span,
3155 })),
3156 span,
3157 ));
3158 }
3159 }
3160 if self.at_punct(Punct::LBrace) {
3161 self.bump()?;
3162 let mut specifiers = Vec::new();
3163 let mut candidates: Vec<(String, Span)> = Vec::new();
3164 let mut source = None;
3165 while !self.at_punct(Punct::RBrace) {
3166 let spec_start = self.current.span.start;
3167 let local = self.parse_module_name()?;
3168 let exported = if self.eat_contextual("as")? {
3169 self.parse_module_name()?
3170 } else {
3171 local.clone()
3172 };
3173 if let ModuleName::Ident(id) = &local {
3177 candidates.push((id.name.clone(), id.span));
3178 }
3179 specifiers.push(ExportSpecifier {
3180 local,
3181 exported,
3182 span: self.span_from(spec_start),
3183 });
3184 if !self.eat_punct(Punct::Comma)? {
3185 break;
3186 }
3187 }
3188 self.expect_punct(Punct::RBrace)?;
3189 let mut attributes = Vec::new();
3190 let has_from = self.eat_contextual("from")?;
3191 if !has_from {
3192 self.pending_exports.extend(candidates);
3196 }
3197 if has_from {
3198 let TokenKind::String(value) = self.current.kind.clone() else {
3199 return Err(self.error("string expected"));
3200 };
3201 self.bump()?;
3202 source = Some(value);
3203 attributes = self.parse_import_attributes()?;
3204 }
3205 self.semicolon()?;
3206 let span = self.span_from(start);
3207 return Ok(Stmt::new(
3208 StmtKind::Export(Box::new(ExportDecl {
3209 kind: ExportKind::Named {
3210 specifiers,
3211 source,
3212 attributes,
3213 },
3214 span,
3215 })),
3216 span,
3217 ));
3218 }
3219 Err(self.unexpected())
3220 }
3221
3222 fn expr_to_pattern(&mut self, expr: Expr, kind: TargetKind) -> Result<Pattern> {
3225 self.expr_to_pattern_inner(expr, kind, false)
3226 }
3227
3228 fn expr_to_pattern_inner(
3229 &mut self,
3230 expr: Expr,
3231 kind: TargetKind,
3232 nested: bool,
3233 ) -> Result<Pattern> {
3234 let span = expr.span;
3235 match expr.kind {
3236 ExprKind::Ident(ident) => {
3237 if kind == TargetKind::Binding {
3238 self.check_binding_name(&ident.name, ident.span)?;
3239 } else {
3240 self.check_identifier(&ident.name, ident.span)?;
3241 if self.strict && (ident.name == "eval" || ident.name == "arguments") {
3242 return Err(self.error_at(
3243 format!("invalid assignment to '{}' in strict mode", ident.name),
3244 ident.span,
3245 ));
3246 }
3247 }
3248 Ok(Pattern::new(PatternKind::Ident(ident), span))
3249 }
3250 ExprKind::Paren(inner) => self.expr_to_pattern_inner(*inner, kind, nested),
3251 ExprKind::Array { elements } => {
3252 let mut out = Vec::new();
3253 let mut rest = None;
3254 let count = elements.len();
3255 for (index, element) in elements.into_iter().enumerate() {
3256 match element {
3257 None => out.push(None),
3258 Some(ArrayElement::Expr(expr)) => {
3259 let pattern = self.expr_to_pattern_inner(*expr, kind, true)?;
3260 out.push(Some(PatternElement::Pattern(pattern)));
3261 }
3262 Some(ArrayElement::Spread(expr)) => {
3263 if index + 1 != count {
3264 return Err(
3265 self.error_at("rest element must be the last one", expr.span)
3266 );
3267 }
3268 rest = Some(Box::new(self.expr_to_rest(*expr, kind)?));
3269 }
3270 }
3271 }
3272 Ok(Pattern::new(
3273 PatternKind::Array {
3274 elements: out,
3275 rest,
3276 },
3277 span,
3278 ))
3279 }
3280 ExprKind::Object(properties) => {
3281 self.cover_inits
3282 .retain(|cover| !span_contains(span, *cover));
3283 let mut out = Vec::new();
3284 let mut rest = None;
3285 let count = properties.len();
3286 for (index, property) in properties.into_iter().enumerate() {
3287 match property {
3288 ObjectProperty::Spread(expr) => {
3289 if index + 1 != count {
3290 return Err(
3291 self.error_at("rest element must be the last one", expr.span)
3292 );
3293 }
3294 rest = Some(Box::new(self.expr_to_rest(*expr, kind)?));
3295 }
3296 ObjectProperty::Property {
3297 key,
3298 value,
3299 kind: _,
3300 shorthand,
3301 span,
3302 } => {
3303 let pattern = self.expr_to_pattern_inner(*value, kind, true)?;
3304 out.push(Some(PatternElement::Property {
3305 key,
3306 value: pattern,
3307 shorthand,
3308 span,
3309 }));
3310 }
3311 }
3312 }
3313 Ok(Pattern::new(
3314 PatternKind::Object {
3315 properties: out,
3316 rest,
3317 },
3318 span,
3319 ))
3320 }
3321 ExprKind::Assign { op, target, value } if op.is_simple() => {
3322 let target = match target.kind {
3324 PatternKind::Ident(ident) => {
3325 Pattern::new(PatternKind::Ident(ident), target.span)
3326 }
3327 other => {
3328 let expr = pattern_to_expr(Pattern::new(other, target.span), target.span);
3329 self.expr_to_pattern_inner(expr, kind, nested)?
3330 }
3331 };
3332 Ok(Pattern::new(
3333 PatternKind::Assign {
3334 target: Box::new(target),
3335 default: value,
3336 },
3337 span,
3338 ))
3339 }
3340 ExprKind::Member {
3341 object,
3342 property,
3343 optional,
3344 } => {
3345 if kind == TargetKind::Binding {
3346 return Err(self.error_at("invalid binding pattern", span));
3347 }
3348 if optional {
3349 return Err(self.error_at("invalid assignment target", span));
3350 }
3351 let op_pos = expr.op_pos;
3352 Ok(Pattern::new(
3353 PatternKind::Member(Box::new(MemberPattern {
3354 object,
3355 property,
3356 span,
3357 op_pos,
3358 })),
3359 span,
3360 ))
3361 }
3362 ExprKind::OptionalChain(_) => {
3363 Err(self.error_at("invalid assignment left-hand side", span))
3364 }
3365 other @ ExprKind::Call { .. } if !nested && kind == TargetKind::Assignment => Ok(
3370 Pattern::new(PatternKind::Invalid(Box::new(Expr::new(other, span))), span),
3371 ),
3372 _ if kind == TargetKind::Binding => Err(self.error_at("invalid binding pattern", span)),
3373 _ if nested => Err(self.error_at("invalid destructuring target", span)),
3378 _ => Err(self.error_at("invalid assignment left-hand side", span)),
3379 }
3380 }
3381
3382 fn expr_to_rest(&mut self, expr: Expr, kind: TargetKind) -> Result<RestElement> {
3383 let expr = match expr.kind {
3386 ExprKind::Spread(inner) => *inner,
3387 other => Expr::new(other, expr.span),
3388 };
3389 if kind == TargetKind::Binding {
3390 return Ok(RestElement::Pattern(
3391 self.expr_to_pattern_inner(expr, kind, true)?,
3392 ));
3393 }
3394 match &expr.kind {
3395 ExprKind::Member { optional, .. } => {
3396 if *optional {
3397 return Err(self.error_at("invalid assignment target", expr.span));
3398 }
3399 match self.expr_to_pattern_inner(expr, kind, true)?.kind {
3400 PatternKind::Member(member) => Ok(RestElement::Member(member)),
3401 _ => unreachable!("member expressions convert to member patterns"),
3402 }
3403 }
3404 _ => Ok(RestElement::Pattern(
3405 self.expr_to_pattern_inner(expr, kind, true)?,
3406 )),
3407 }
3408 }
3409
3410 fn parse_expression(&mut self, allow_in: bool) -> Result<Expr> {
3414 self.enter()?;
3415 let result = self.parse_expression_unguarded(allow_in);
3416 self.leave();
3417 result
3418 }
3419
3420 fn parse_expression_unguarded(&mut self, allow_in: bool) -> Result<Expr> {
3421 let start = self.current.span.start;
3422 let first = self.parse_assignment(allow_in)?;
3423 if !self.at_punct(Punct::Comma) {
3424 return Ok(first);
3425 }
3426 let mut items = vec![first];
3427 while self.eat_punct(Punct::Comma)? {
3428 items.push(self.parse_assignment(allow_in)?);
3429 }
3430 Ok(Expr::new(ExprKind::Sequence(items), self.span_from(start)))
3431 }
3432
3433 fn parse_assignment(&mut self, allow_in: bool) -> Result<Expr> {
3434 let start = self.current.span.start;
3435
3436 if self.ctx.in_generator && self.at_ident("yield") {
3438 return self.parse_yield(allow_in);
3439 }
3440
3441 let lhs = match self.try_parse_arrow(allow_in)? {
3442 Some(arrow) => return Ok(arrow),
3443 None => self.parse_conditional(allow_in)?,
3444 };
3445
3446 if let Some(op) = self.current.kind.as_punct().and_then(AssignOp::from_punct) {
3447 let op_pos = self.current.span.start;
3448 let target = self.expr_to_pattern(lhs, TargetKind::Assignment)?;
3449 self.bump()?;
3450 let value = self.parse_assignment(allow_in)?;
3451 return Ok(Expr::at_operator(
3452 ExprKind::Assign {
3453 op,
3454 target: Box::new(target),
3455 value: Box::new(value),
3456 },
3457 self.span_from(start),
3458 op_pos,
3459 ));
3460 }
3461 let _ = start;
3462 Ok(lhs)
3463 }
3464
3465 fn parse_yield(&mut self, allow_in: bool) -> Result<Expr> {
3466 let start = self.current.span.start;
3467 self.bump()?; let delegate = if self.at_punct(Punct::Star) && !self.current.newline_before {
3469 self.bump()?;
3470 true
3471 } else {
3472 false
3473 };
3474 let argument = if delegate {
3475 Some(Box::new(self.parse_assignment(allow_in)?))
3476 } else if self.current.newline_before
3477 || self.at_punct(Punct::RParen)
3478 || self.at_punct(Punct::RBracket)
3479 || self.at_punct(Punct::RBrace)
3480 || self.at_punct(Punct::Comma)
3481 || self.at_punct(Punct::Semicolon)
3482 || self.at_punct(Punct::Colon)
3483 || self.current.is_eof()
3484 {
3485 None
3486 } else {
3487 Some(Box::new(self.parse_assignment(allow_in)?))
3488 };
3489 Ok(Expr::new(
3490 ExprKind::Yield { argument, delegate },
3491 self.span_from(start),
3492 ))
3493 }
3494
3495 fn try_parse_arrow(&mut self, allow_in: bool) -> Result<Option<Expr>> {
3496 let starts_paren = self.at_punct(Punct::LParen);
3497 let starts_ident = matches!(self.current.kind, TokenKind::Ident(_));
3498 if !starts_paren && !starts_ident {
3499 return Ok(None);
3500 }
3501 if starts_paren && !self.arrow_follows_paren()? {
3505 return Ok(None);
3506 }
3507 let snapshot = self.snapshot();
3508 let head = match self.parse_arrow_head() {
3509 Ok(head) => head,
3510 Err(_) => {
3511 self.restore(snapshot);
3512 return Ok(None);
3513 }
3514 };
3515 let Some(head) = head else {
3516 self.restore(snapshot);
3517 return Ok(None);
3518 };
3519 let body_start = if self.at_punct(Punct::LBrace) {
3526 self.peek()?.span
3527 } else {
3528 self.current.span
3529 };
3530 self.check_duplicate_parameters(&head.params, true, body_start)?;
3531 let saved_ctx = self.ctx;
3532 let saved_loop = self.loop_depth;
3533 let saved_switch = self.switch_depth;
3534 let saved_labels = std::mem::take(&mut self.labels);
3535 let saved_top = self.top_level;
3536 self.ctx = FnCtx {
3537 in_function: true,
3538 in_generator: false,
3539 in_async: head.is_async,
3540 in_method: saved_ctx.in_method,
3541 in_derived_constructor: saved_ctx.in_derived_constructor,
3542 in_static_block: false,
3546 arguments_allowed: saved_ctx.arguments_allowed,
3547 };
3548 self.loop_depth = 0;
3549 self.switch_depth = 0;
3550 self.top_level = false;
3551 let body_start = self.current.span.start;
3552 let (body, strict) = if self.at_punct(Punct::LBrace) {
3553 let (block, strict) = self.parse_arrow_block(&head.params)?;
3554 (block, (self.prev_end, strict))
3555 } else {
3556 let expr = self.parse_assignment(allow_in)?;
3557 let end = expr.span.end;
3558 let strict = self.strict;
3560 (FunctionBody::Expr(Box::new(expr)), (end, strict))
3561 };
3562 self.ctx = saved_ctx;
3563 self.loop_depth = saved_loop;
3564 self.switch_depth = saved_switch;
3565 self.labels = saved_labels;
3566 self.top_level = saved_top;
3567 let _ = body_start;
3568 let (body, (end, strict)) = (body, strict);
3569 let span = Span::new(head.span.start, end);
3570 Ok(Some(Expr::new(
3571 ExprKind::Arrow(Box::new(Function {
3572 name: None,
3573 params: head.params,
3574 body,
3575 is_async: head.is_async,
3576 is_generator: false,
3577 strict,
3578 is_arrow: true,
3579 span,
3580 params_span: head.params_span,
3581 })),
3582 span,
3583 )))
3584 }
3585
3586 fn parse_arrow_block(&mut self, params: &[Pattern]) -> Result<(FunctionBody, bool)> {
3588 let saved_strict = self.strict;
3591 self.expect_punct(Punct::LBrace)?;
3592 self.push_scope(Scope::function(simple_parameter_names(params)));
3593 let result = (|| -> Result<Vec<Stmt>> {
3594 let mut body = Vec::new();
3595 let mut prologue = true;
3596 while !self.at_punct(Punct::RBrace) {
3597 if self.current.is_eof() {
3598 return Err(self.unexpected());
3599 }
3600 let stmt = self.parse_statement_list_item()?;
3601 if prologue {
3602 match self.directive_value(&stmt) {
3603 Some(directive) if directive == "use strict" => self.enter_strict()?,
3604 Some(_) => {}
3605 None => prologue = false,
3606 }
3607 }
3608 body.push(stmt);
3609 }
3610 Ok(body)
3611 })();
3612 self.pop_scope();
3613 let body_strict = self.strict;
3614 self.strict = saved_strict;
3615 self.lexer.set_strict(saved_strict);
3616 let body = result?;
3617 self.bump()?;
3618 Ok((FunctionBody::Block(body), body_strict))
3619 }
3620
3621 fn arrow_follows_paren(&self) -> Result<bool> {
3627 let mut lexer = self.lexer.clone();
3628 let mut depth = 1usize;
3630 loop {
3631 let token = lexer.next_token()?;
3632 match token.kind {
3633 TokenKind::Eof => return Ok(false),
3634 TokenKind::Punct(Punct::LParen)
3635 | TokenKind::Punct(Punct::LBracket)
3636 | TokenKind::Punct(Punct::LBrace) => depth += 1,
3637 TokenKind::Punct(Punct::RParen)
3638 | TokenKind::Punct(Punct::RBracket)
3639 | TokenKind::Punct(Punct::RBrace) => {
3640 if depth == 0 {
3641 return Ok(false);
3643 }
3644 depth -= 1;
3645 if depth == 0 {
3646 let next = lexer.next_token()?;
3649 return Ok(matches!(next.kind, TokenKind::Punct(Punct::Arrow))
3650 && !next.newline_before);
3651 }
3652 }
3653 _ => {}
3654 }
3655 }
3656 }
3657
3658 fn parse_arrow_head(&mut self) -> Result<Option<ArrowHead>> {
3660 let start = self.current.span.start;
3661 let mut is_async = false;
3662 if self.at_ident("async") {
3663 let peek = self.peek()?;
3664 if peek.newline_before {
3665 return Ok(None);
3666 }
3667 let plausible =
3668 matches!(peek.kind, TokenKind::Punct(Punct::LParen)) || peek.kind.is_identifier();
3669 if !plausible {
3670 return Ok(None);
3671 }
3672 self.bump()?;
3673 is_async = true;
3674 }
3675 let params_start = self.current.span.start;
3676 let params = if self.at_punct(Punct::LParen) {
3677 self.parse_formal_parameters()?
3678 } else if matches!(self.current.kind, TokenKind::Ident(_)) {
3679 let ident = self.expect_ident()?;
3680 vec![Pattern::new(
3681 PatternKind::Ident(ident),
3682 self.span_from(params_start),
3683 )]
3684 } else {
3685 return Ok(None);
3686 };
3687 let params_span = self.span_from(params_start);
3688 if !self.at_punct(Punct::Arrow) || self.current.newline_before {
3689 return Ok(None);
3690 }
3691 self.bump()?; Ok(Some(ArrowHead {
3693 params,
3694 is_async,
3695 span: self.span_from(start),
3696 params_span,
3697 }))
3698 }
3699
3700 fn parse_conditional(&mut self, allow_in: bool) -> Result<Expr> {
3701 let start = self.current.span.start;
3702 let test = self.parse_binary(allow_in, 0)?;
3703 if !self.at_punct(Punct::Question) {
3704 return Ok(test);
3705 }
3706 self.bump()?;
3707 let consequent = self.parse_assignment(true)?;
3708 self.expect_punct(Punct::Colon)?;
3709 let alternate = self.parse_assignment(allow_in)?;
3710 Ok(Expr::new(
3711 ExprKind::Conditional {
3712 test: Box::new(test),
3713 cons: Box::new(consequent),
3714 alt: Box::new(alternate),
3715 },
3716 self.span_from(start),
3717 ))
3718 }
3719
3720 fn parse_binary(&mut self, allow_in: bool, min_prec: u8) -> Result<Expr> {
3721 let start = self.current.span.start;
3722 let mut lhs = self.parse_unary()?;
3723 while let Some((prec, op)) = binary_operator(&self.current.kind, allow_in) {
3724 if prec < min_prec {
3725 break;
3726 }
3727 let op_pos = self.current.span.start;
3728 self.bump()?;
3729 let next_min = if op.is_right_associative() {
3730 prec
3731 } else {
3732 prec + 1
3733 };
3734 let rhs = self.parse_binary(allow_in, next_min)?;
3735 lhs = build_binary(op, lhs, rhs, self.span_from(start), op_pos)?;
3736 }
3737 Ok(lhs)
3738 }
3739
3740 fn parse_unary(&mut self) -> Result<Expr> {
3743 let start = self.current.span.start;
3744 let unary = match &self.current.kind {
3746 TokenKind::Keyword(Keyword::Delete) => Some(UnaryOp::Delete),
3747 TokenKind::Keyword(Keyword::Void) => Some(UnaryOp::Void),
3748 TokenKind::Keyword(Keyword::Typeof) => Some(UnaryOp::Typeof),
3749 TokenKind::Punct(Punct::Plus) => Some(UnaryOp::Plus),
3750 TokenKind::Punct(Punct::Minus) => Some(UnaryOp::Minus),
3751 TokenKind::Punct(Punct::Bang) => Some(UnaryOp::Not),
3752 TokenKind::Punct(Punct::Tilde) => Some(UnaryOp::BitNot),
3753 _ => None,
3754 };
3755 if let Some(op) = unary {
3756 let op_pos = self.current.span.start;
3757 self.bump()?;
3758 let argument = self.parse_unary()?;
3759 if op == UnaryOp::Delete && self.strict {
3760 if let ExprKind::Ident(ident) = &argument.unparen().kind {
3761 return Err(self.error_at(
3762 "cannot delete a direct reference in strict mode",
3763 ident.span,
3764 ));
3765 }
3766 }
3767 let expr = Expr::at_operator(
3768 ExprKind::Unary {
3769 op,
3770 argument: Box::new(argument),
3771 },
3772 self.span_from(start),
3773 op_pos,
3774 );
3775 if self.at_punct(Punct::StarStar) {
3776 return Err(self.error(
3777 "unparenthesized unary expression can't appear on the left-hand side of '**'",
3779 ));
3780 }
3781 return Ok(expr);
3782 }
3783 if self.at_punct(Punct::PlusPlus) || self.at_punct(Punct::MinusMinus) {
3785 let op_pos = self.current.span.start;
3786 let op = if self.at_punct(Punct::PlusPlus) {
3787 UpdateOp::Increment
3788 } else {
3789 UpdateOp::Decrement
3790 };
3791 self.bump()?;
3792 let argument = self.parse_unary()?;
3793 self.check_simple_target(&argument)?;
3794 return Ok(Expr::at_operator(
3795 ExprKind::Update {
3796 op,
3797 argument: Box::new(argument),
3798 prefix: true,
3799 },
3800 self.span_from(start),
3801 op_pos,
3802 ));
3803 }
3804 if self.at_ident("await") && self.ctx.in_async {
3811 self.bump()?;
3812 let argument = self.parse_unary()?;
3813 return Ok(Expr::new(
3814 ExprKind::Await(Box::new(argument)),
3815 self.span_from(start),
3816 ));
3817 }
3818 let expr = self.parse_lhs_expression()?;
3819 let result = if (self.at_punct(Punct::PlusPlus) || self.at_punct(Punct::MinusMinus))
3821 && !self.current.newline_before
3822 {
3823 let op_pos = self.current.span.start;
3824 let op = if self.at_punct(Punct::PlusPlus) {
3825 UpdateOp::Increment
3826 } else {
3827 UpdateOp::Decrement
3828 };
3829 self.check_simple_target(&expr)?;
3830 self.bump()?;
3831 Expr::at_operator(
3832 ExprKind::Update {
3833 op,
3834 argument: Box::new(expr),
3835 prefix: false,
3836 },
3837 self.span_from(start),
3838 op_pos,
3839 )
3840 } else {
3841 expr
3842 };
3843 Ok(result)
3844 }
3845
3846 fn check_simple_target(&self, expr: &Expr) -> Result<()> {
3851 match &expr.unparen().kind {
3852 ExprKind::Ident(_) => Ok(()),
3853 ExprKind::Member {
3854 optional: false, ..
3855 } => Ok(()),
3856 _ => Err(self.error_at("invalid increment/decrement operand", expr.span)),
3857 }
3858 }
3859
3860 fn parse_lhs_expression(&mut self) -> Result<Expr> {
3861 let start = self.current.span.start;
3862 let mut expr = if self.at_keyword(Keyword::New) {
3863 self.parse_new_expression()?
3864 } else {
3865 self.parse_primary()?
3866 };
3867 let mut saw_optional = false;
3868 loop {
3869 let op_pos = self.current.span.start;
3872 match self.current.kind.clone() {
3873 TokenKind::Punct(Punct::Dot) => {
3874 self.bump()?;
3875 let property = self.parse_member_property()?;
3876 expr = Expr::at_operator(
3877 ExprKind::Member {
3878 object: Box::new(expr),
3879 property,
3880 optional: false,
3881 },
3882 self.span_from(start),
3883 op_pos,
3884 );
3885 }
3886 TokenKind::Punct(Punct::QuestionDot) => {
3887 saw_optional = true;
3888 self.bump()?;
3889 if self.at_punct(Punct::LParen) {
3890 let arguments = self.parse_arguments()?;
3891 expr = Expr::at_operator(
3892 ExprKind::Call {
3893 callee: Box::new(expr),
3894 arguments,
3895 optional: true,
3896 },
3897 self.span_from(start),
3898 op_pos,
3899 );
3900 } else if self.at_punct(Punct::LBracket) {
3901 self.bump()?;
3902 let index = self.parse_expression(true)?;
3903 self.expect_punct(Punct::RBracket)?;
3904 expr = Expr::at_operator(
3905 ExprKind::Member {
3906 object: Box::new(expr),
3907 property: MemberProp::Computed(Box::new(index)),
3908 optional: true,
3909 },
3910 self.span_from(start),
3911 op_pos,
3912 );
3913 } else {
3914 let property = self.parse_member_property()?;
3915 expr = Expr::at_operator(
3916 ExprKind::Member {
3917 object: Box::new(expr),
3918 property,
3919 optional: true,
3920 },
3921 self.span_from(start),
3922 op_pos,
3923 );
3924 }
3925 }
3926 TokenKind::Punct(Punct::LBracket) => {
3927 self.bump()?;
3928 let index = self.parse_expression(true)?;
3929 self.expect_punct(Punct::RBracket)?;
3930 expr = Expr::at_operator(
3931 ExprKind::Member {
3932 object: Box::new(expr),
3933 property: MemberProp::Computed(Box::new(index)),
3934 optional: false,
3935 },
3936 self.span_from(start),
3937 op_pos,
3938 );
3939 }
3940 TokenKind::Punct(Punct::LParen) => {
3941 let arguments = self.parse_arguments()?;
3942 expr = Expr::at_operator(
3943 ExprKind::Call {
3944 callee: Box::new(expr),
3945 arguments,
3946 optional: false,
3947 },
3948 self.span_from(start),
3949 op_pos,
3950 );
3951 }
3952 TokenKind::Template(_) => {
3953 if saw_optional || matches!(expr.unparen().kind, ExprKind::OptionalChain(_)) {
3954 return Err(
3955 self.error("tagged template cannot be used in an optional chain")
3956 );
3957 }
3958 let quasi = self.parse_template()?;
3959 expr = Expr::new(
3960 ExprKind::TaggedTemplate {
3961 tag: Box::new(expr),
3962 quasi: Box::new(quasi),
3963 },
3964 self.span_from(start),
3965 );
3966 }
3967 _ => break,
3968 }
3969 }
3970 if saw_optional {
3971 expr = Expr::new(
3972 ExprKind::OptionalChain(Box::new(expr)),
3973 self.span_from(start),
3974 );
3975 }
3976 Ok(expr)
3977 }
3978
3979 fn parse_member_property(&mut self) -> Result<MemberProp> {
3980 if self.at_punct(Punct::Hash) {
3981 self.bump()?;
3982 let ident = self.expect_ident()?;
3983 if !self.private.iter().any(|env| env.contains(&ident.name)) {
3984 return Err(self.error_at(
3987 format!("undefined private field '#{}'", ident.name),
3988 ident.span,
3989 ));
3990 }
3991 return Ok(MemberProp::Private(ident));
3992 }
3993 match self.current.kind.clone() {
3994 TokenKind::Ident(name) => {
3995 let span = self.current.span;
3996 self.bump()?;
3997 Ok(MemberProp::Ident(Ident { name, span }))
3998 }
3999 TokenKind::Keyword(kw) => {
4000 let span = self.current.span;
4001 self.bump()?;
4002 Ok(MemberProp::Ident(Ident {
4003 name: kw.as_str().to_string(),
4004 span,
4005 }))
4006 }
4007 _ => Err(self.error("expecting field name")),
4011 }
4012 }
4013
4014 fn parse_new_expression(&mut self) -> Result<Expr> {
4015 let start = self.current.span.start;
4016 self.bump()?; if self.at_punct(Punct::Dot) {
4018 self.bump()?;
4019 if !self.at_ident("target") {
4020 return Err(self.error("expecting target"));
4021 }
4022 if !self.ctx.in_function {
4023 return Err(self.error("new.target only allowed within functions"));
4024 }
4025 self.bump()?;
4026 return Ok(Expr::new(ExprKind::NewTarget, self.span_from(start)));
4027 }
4028 let mut callee = if self.at_keyword(Keyword::New) {
4029 self.parse_new_expression()?
4030 } else {
4031 self.parse_primary()?
4032 };
4033 loop {
4035 let op_pos = self.current.span.start;
4036 match self.current.kind.clone() {
4037 TokenKind::Punct(Punct::Dot) => {
4038 self.bump()?;
4039 let property = self.parse_member_property()?;
4040 callee = Expr::at_operator(
4041 ExprKind::Member {
4042 object: Box::new(callee),
4043 property,
4044 optional: false,
4045 },
4046 self.span_from(start),
4047 op_pos,
4048 );
4049 }
4050 TokenKind::Punct(Punct::LBracket) => {
4051 self.bump()?;
4052 let index = self.parse_expression(true)?;
4053 self.expect_punct(Punct::RBracket)?;
4054 callee = Expr::at_operator(
4055 ExprKind::Member {
4056 object: Box::new(callee),
4057 property: MemberProp::Computed(Box::new(index)),
4058 optional: false,
4059 },
4060 self.span_from(start),
4061 op_pos,
4062 );
4063 }
4064 TokenKind::Punct(Punct::QuestionDot) => {
4065 return Err(self.error("new keyword cannot be used with an optional chain"));
4066 }
4067 _ => break,
4068 }
4069 }
4070 if matches!(callee.unparen().kind, ExprKind::OptionalChain(_)) {
4071 return Err(self.error_at("cannot use 'new' with an optional chain", callee.span));
4072 }
4073 let arguments = if self.at_punct(Punct::LParen) {
4074 let op_pos = self.current.span.start;
4076 let arguments = Some(self.parse_arguments()?);
4077 return Ok(Expr::at_operator(
4078 ExprKind::New {
4079 callee: Box::new(callee),
4080 arguments,
4081 },
4082 self.span_from(start),
4083 op_pos,
4084 ));
4085 } else {
4086 None
4087 };
4088 Ok(Expr::at_operator(
4092 ExprKind::New {
4093 callee: Box::new(callee),
4094 arguments,
4095 },
4096 self.span_from(start),
4097 self.current.span.start,
4098 ))
4099 }
4100
4101 fn parse_arguments(&mut self) -> Result<Vec<Expr>> {
4102 self.expect_punct(Punct::LParen)?;
4103 let mut arguments = Vec::new();
4104 while !self.at_punct(Punct::RParen) {
4105 if self.at_punct(Punct::Ellipsis) {
4106 let start = self.current.span.start;
4107 self.bump()?;
4108 let argument = self.parse_assignment(true)?;
4109 arguments.push(Expr::new(
4110 ExprKind::Spread(Box::new(argument)),
4111 self.span_from(start),
4112 ));
4113 } else {
4114 arguments.push(self.parse_assignment(true)?);
4115 }
4116 if !self.eat_punct(Punct::Comma)? {
4117 break;
4118 }
4119 }
4120 self.expect_punct(Punct::RParen)?;
4121 Ok(arguments)
4122 }
4123
4124 fn parse_primary(&mut self) -> Result<Expr> {
4131 let start = self.current.span.start;
4132 match self.current.kind.clone() {
4133 TokenKind::Number(NumberLiteral::Int(value)) => {
4134 self.bump()?;
4135 Ok(Expr::new(
4136 ExprKind::Number(value as f64),
4137 self.span_from(start),
4138 ))
4139 }
4140 TokenKind::Number(NumberLiteral::Float(value)) => {
4141 self.bump()?;
4142 Ok(Expr::new(ExprKind::Number(value), self.span_from(start)))
4143 }
4144 TokenKind::String(value) => {
4145 self.bump()?;
4146 Ok(Expr::new(ExprKind::String(value), self.span_from(start)))
4147 }
4148 TokenKind::Ident(name) if name == "async" => {
4149 let peek = self.peek()?;
4150 if matches!(peek.kind, TokenKind::Keyword(Keyword::Function))
4151 && !peek.newline_before
4152 {
4153 self.bump()?; let func = self.parse_function(FunctionForm::Expression, true)?;
4155 return Ok(Expr::new(
4156 ExprKind::Function(Box::new(func)),
4157 self.span_from(start),
4158 ));
4159 }
4160 let span = self.current.span;
4161 self.bump()?;
4162 Ok(Expr::new(ExprKind::Ident(Ident { name, span }), span))
4163 }
4164 TokenKind::Ident(name) => {
4165 let span = self.current.span;
4166 self.check_identifier(&name, span)?;
4167 self.check_arguments_reference(&name, span)?;
4168 self.bump()?;
4169 Ok(Expr::new(ExprKind::Ident(Ident { name, span }), span))
4170 }
4171 TokenKind::Keyword(Keyword::This) => {
4172 self.bump()?;
4173 Ok(Expr::new(ExprKind::This, self.span_from(start)))
4174 }
4175 TokenKind::Keyword(Keyword::Null) => {
4176 self.bump()?;
4177 Ok(Expr::new(ExprKind::Null, self.span_from(start)))
4178 }
4179 TokenKind::Keyword(Keyword::True) => {
4180 self.bump()?;
4181 Ok(Expr::new(ExprKind::Bool(true), self.span_from(start)))
4182 }
4183 TokenKind::Keyword(Keyword::False) => {
4184 self.bump()?;
4185 Ok(Expr::new(ExprKind::Bool(false), self.span_from(start)))
4186 }
4187 TokenKind::Punct(Punct::LParen) => {
4188 self.bump()?;
4189 let inner = self.parse_expression(true)?;
4190 self.expect_punct(Punct::RParen)?;
4191 Ok(Expr::new(
4192 ExprKind::Paren(Box::new(inner)),
4193 self.span_from(start),
4194 ))
4195 }
4196 TokenKind::Punct(Punct::Slash) | TokenKind::Punct(Punct::SlashEq) => {
4197 self.parse_regex_literal(start)
4198 }
4199 _ => self.parse_primary_complex(start),
4200 }
4201 }
4202
4203 #[inline(never)]
4206 fn parse_primary_complex(&mut self, start: Position) -> Result<Expr> {
4207 match self.current.kind.clone() {
4208 TokenKind::BigInt(literal) => {
4209 self.bump()?;
4210 Ok(Expr::new(
4211 ExprKind::BigInt {
4212 digits: literal.digits,
4213 radix: literal.radix,
4214 },
4215 self.span_from(start),
4216 ))
4217 }
4218 TokenKind::Template(_) => {
4219 let template = self.parse_template()?;
4220 Ok(Expr::new(
4221 ExprKind::Template(Box::new(template)),
4222 self.span_from(start),
4223 ))
4224 }
4225 TokenKind::Keyword(Keyword::Function) => {
4226 let func = self.parse_function(FunctionForm::Expression, false)?;
4227 Ok(Expr::new(
4228 ExprKind::Function(Box::new(func)),
4229 self.span_from(start),
4230 ))
4231 }
4232 TokenKind::Keyword(Keyword::Class) => {
4233 let class = self.parse_class(true)?;
4234 Ok(Expr::new(
4235 ExprKind::Class(Box::new(class)),
4236 self.span_from(start),
4237 ))
4238 }
4239 TokenKind::Keyword(Keyword::Import) => self.parse_import_expression(),
4240 TokenKind::Keyword(Keyword::Super) => self.parse_super(),
4241 TokenKind::Punct(Punct::LBracket) => self.parse_array_literal(),
4242 TokenKind::Punct(Punct::LBrace) => self.parse_object_literal(),
4243 TokenKind::Punct(Punct::Hash) => self.parse_private_in(start),
4244 _ => Err(self.unexpected()),
4245 }
4246 }
4247
4248 #[inline(never)]
4250 fn parse_super(&mut self) -> Result<Expr> {
4251 let start = self.current.span.start;
4252 self.bump()?;
4253 let after = self.current.span;
4259 if self.at_punct(Punct::LParen) {
4260 if !self.ctx.in_derived_constructor {
4261 return Err(self.error_at(
4262 "super() is only valid in a derived class constructor",
4263 after,
4264 ));
4265 }
4266 let arguments = self.parse_arguments()?;
4269 return Ok(Expr::at_operator(
4270 ExprKind::SuperCall(arguments),
4271 self.span_from(start),
4272 after.start,
4273 ));
4274 }
4275 if !self.ctx.in_method {
4276 let message = if self.at_punct(Punct::Dot) || self.at_punct(Punct::LBracket) {
4283 "'super' is only valid in a method"
4284 } else {
4285 "invalid use of 'super'"
4286 };
4287 return Err(self.error_at(message, after));
4288 }
4289 Ok(Expr::new(ExprKind::SuperProp, self.span_from(start)))
4290 }
4291
4292 #[inline(never)]
4294 fn parse_private_in(&mut self, start: Position) -> Result<Expr> {
4295 self.bump()?;
4296 let ident = self.expect_ident()?;
4297 if !self.private.iter().any(|env| env.contains(&ident.name)) {
4298 return Err(self.error_at(
4299 format!(
4300 "private field '#{}' must be declared in an enclosing class",
4301 ident.name
4302 ),
4303 ident.span,
4304 ));
4305 }
4306 if !self.at_keyword(Keyword::In) {
4307 return Err(self.error("expecting 'in' after a private name"));
4308 }
4309 self.bump()?;
4310 let object = self.parse_unary()?;
4311 Ok(Expr::new(
4312 ExprKind::PrivateIn {
4313 name: ident,
4314 object: Box::new(object),
4315 },
4316 self.span_from(start),
4317 ))
4318 }
4319
4320 #[inline(never)]
4323 fn parse_regex_literal(&mut self, start: Position) -> Result<Expr> {
4324 let token = self.lexer.re_scan_regex(self.current.span.start)?;
4325 self.current = token;
4326 let TokenKind::RegExp { pattern, flags } = self.current.kind.clone() else {
4327 unreachable!("re_scan_regex returns a RegExp token")
4328 };
4329 self.bump()?;
4330 Ok(Expr::new(
4331 ExprKind::RegExp { pattern, flags },
4332 self.span_from(start),
4333 ))
4334 }
4335
4336 fn parse_import_expression(&mut self) -> Result<Expr> {
4337 let start = self.current.span.start;
4338 self.bump()?; if self.at_punct(Punct::Dot) {
4340 if !self.module {
4341 return Err(self.error_at(
4342 "import.meta only valid in module code",
4343 self.span_from(start),
4344 ));
4345 }
4346 self.bump()?;
4347 if !self.at_ident("meta") {
4348 return Err(self.error("expecting 'meta' after 'import.'"));
4349 }
4350 self.bump()?;
4351 return Ok(Expr::new(ExprKind::ImportMeta, self.span_from(start)));
4352 }
4353 if self.at_punct(Punct::LParen) {
4354 self.bump()?;
4355 let specifier = self.parse_assignment(true)?;
4356 if self.at_punct(Punct::Comma) {
4357 return Err(self.error("import() takes exactly one argument"));
4358 }
4359 self.expect_punct(Punct::RParen)?;
4360 return Ok(Expr::new(
4361 ExprKind::ImportCall(Box::new(specifier)),
4362 self.span_from(start),
4363 ));
4364 }
4365 Err(self.unexpected())
4366 }
4367
4368 fn parse_array_literal(&mut self) -> Result<Expr> {
4369 let start = self.current.span.start;
4370 self.expect_punct(Punct::LBracket)?;
4371 let mut elements = Vec::new();
4372 while !self.at_punct(Punct::RBracket) {
4373 if self.at_punct(Punct::Comma) {
4374 self.bump()?;
4375 elements.push(None);
4376 continue;
4377 }
4378 if self.at_punct(Punct::Ellipsis) {
4379 let spread_start = self.current.span.start;
4380 self.bump()?;
4381 let argument = self.parse_assignment(true)?;
4382 elements.push(Some(ArrayElement::Spread(Box::new(Expr::new(
4383 ExprKind::Spread(Box::new(argument)),
4384 self.span_from(spread_start),
4385 )))));
4386 } else {
4387 let expr = self.parse_assignment(true)?;
4388 elements.push(Some(ArrayElement::Expr(Box::new(expr))));
4389 }
4390 if !self.eat_punct(Punct::Comma)? {
4391 break;
4392 }
4393 }
4394 self.expect_punct(Punct::RBracket)?;
4395 Ok(Expr::new(
4396 ExprKind::Array { elements },
4397 self.span_from(start),
4398 ))
4399 }
4400
4401 fn parse_object_literal(&mut self) -> Result<Expr> {
4402 let start = self.current.span.start;
4403 self.expect_punct(Punct::LBrace)?;
4404 let mut properties: Vec<ObjectProperty> = Vec::new();
4405 let mut proto_count = 0;
4406 while !self.at_punct(Punct::RBrace) {
4407 let property_start = self.current.span.start;
4408 if self.at_punct(Punct::Ellipsis) {
4409 self.bump()?;
4410 let argument = self.parse_assignment(true)?;
4411 properties.push(ObjectProperty::Spread(Box::new(argument)));
4412 } else {
4413 let mut is_async = false;
4414 let mut is_generator = false;
4415 let mut accessor: Option<MethodKind> = None;
4416 if self.at_ident("async") {
4417 let peek = self.peek()?;
4418 let is_modifier = !matches!(
4419 peek.kind,
4420 TokenKind::Punct(Punct::LParen)
4421 | TokenKind::Punct(Punct::Colon)
4422 | TokenKind::Punct(Punct::Comma)
4423 | TokenKind::Punct(Punct::RBrace)
4424 | TokenKind::Punct(Punct::Eq)
4425 ) && !peek.newline_before;
4426 if is_modifier {
4427 self.bump()?;
4428 is_async = true;
4429 }
4430 }
4431 if self.at_punct(Punct::Star) {
4432 self.bump()?;
4433 is_generator = true;
4434 }
4435 if accessor.is_none() && (self.at_ident("get") || self.at_ident("set")) {
4436 let is_get = self.at_ident("get");
4437 let peek = self.peek()?;
4438 if is_property_key_start(&peek.kind) {
4439 self.bump()?;
4440 accessor = Some(if is_get {
4441 MethodKind::Get
4442 } else {
4443 MethodKind::Set
4444 });
4445 }
4446 }
4447 let key = self.parse_property_key()?;
4448 let is_computed = matches!(key, PropName::Computed(_));
4449 if self.at_punct(Punct::LParen) {
4450 let saved = self.ctx;
4451 self.ctx = FnCtx {
4452 in_function: true,
4453 in_generator: is_generator,
4454 in_async: is_async,
4455 in_method: true,
4456 in_derived_constructor: false,
4457 in_static_block: false,
4458 arguments_allowed: true,
4459 };
4460 let saved_top = self.top_level;
4461 self.top_level = false;
4462 let func_result = (|| -> Result<Function> {
4463 let params = self.parse_formal_parameters()?;
4464 let (params, params_span, body, strict) =
4465 self.parse_function_body(params, true)?;
4466 Ok(Function {
4467 name: None,
4468 params,
4469 body,
4470 is_async,
4471 is_generator,
4472 strict,
4473 is_arrow: false,
4474 span: self.span_from(property_start),
4475 params_span,
4476 })
4477 })();
4478 self.ctx = saved;
4479 self.top_level = saved_top;
4480 let func = func_result?;
4481 let kind = match accessor {
4482 Some(kind) => {
4483 if is_generator || is_async {
4484 return Err(self.error_at(
4485 "accessors may not be generators or async",
4486 func.span,
4487 ));
4488 }
4489 if kind == MethodKind::Get && !func.params.is_empty() {
4490 return Err(self.error_at(
4491 "invalid number of arguments for getter or setter",
4492 func.span,
4493 ));
4494 }
4495 if kind == MethodKind::Set && func.params.len() != 1 {
4496 return Err(self.error_at(
4497 "invalid number of arguments for getter or setter",
4498 func.span,
4499 ));
4500 }
4501 match kind {
4502 MethodKind::Get => PropertyKind::Get,
4503 MethodKind::Set => PropertyKind::Set,
4504 MethodKind::Method | MethodKind::Constructor => {
4505 PropertyKind::Method
4506 }
4507 }
4508 }
4509 None => PropertyKind::Method,
4510 };
4511 let span = self.span_from(property_start);
4512 properties.push(ObjectProperty::Property {
4513 key,
4514 value: Box::new(Expr::new(ExprKind::Function(Box::new(func)), span)),
4515 kind,
4516 shorthand: false,
4517 span,
4518 });
4519 } else if self.eat_punct(Punct::Colon)? {
4520 let value = self.parse_assignment(true)?;
4521 if !is_computed {
4522 if let Some(PropKeyRef::Str("__proto__")) = key.static_name() {
4523 proto_count += 1;
4524 if proto_count > 1 {
4525 return Err(self.error_at(
4526 "duplicate __proto__ property name",
4527 self.span_from(property_start),
4528 ));
4529 }
4530 }
4531 }
4532 properties.push(ObjectProperty::Property {
4533 key,
4534 value: Box::new(value),
4535 kind: PropertyKind::Value,
4536 shorthand: false,
4537 span: self.span_from(property_start),
4538 });
4539 } else {
4540 let PropName::Literal(PropKey::Str(name)) = &key else {
4543 return Err(self.error("expecting ':' after a property name"));
4544 };
4545 let ident_span = self.span_from(property_start);
4546 let ident = Ident {
4547 name: name.clone(),
4548 span: ident_span,
4549 };
4550 self.check_identifier(&ident.name, ident.span)?;
4551 let mut value = Expr::new(ExprKind::Ident(ident.clone()), ident_span);
4552 if self.at_punct(Punct::Eq) {
4553 self.cover_inits.push(ident_span);
4556 self.bump()?;
4557 let default = self.parse_assignment(true)?;
4558 let target = Pattern::new(PatternKind::Ident(ident), ident_span);
4559 value = Expr::new(
4560 ExprKind::Assign {
4561 op: AssignOp::Assign,
4562 target: Box::new(target),
4563 value: Box::new(default),
4564 },
4565 ident_span,
4566 );
4567 }
4568 properties.push(ObjectProperty::Property {
4569 key,
4570 value: Box::new(value),
4571 kind: PropertyKind::Value,
4572 shorthand: true,
4573 span: ident_span,
4574 });
4575 }
4576 }
4577 if !self.eat_punct(Punct::Comma)? {
4578 break;
4579 }
4580 }
4581 self.expect_punct(Punct::RBrace)?;
4582 Ok(Expr::new(
4583 ExprKind::Object(properties),
4584 self.span_from(start),
4585 ))
4586 }
4587
4588 fn parse_template(&mut self) -> Result<TemplateLiteral> {
4589 let mut quasis = Vec::new();
4590 let mut expressions = Vec::new();
4591 loop {
4592 let (cooked, raw, kind) = match self.current.kind.clone() {
4593 TokenKind::Template(chunk) => (chunk.cooked, chunk.raw, chunk.kind),
4594 _ => return Err(self.error("expecting a template literal")),
4595 };
4596 let tail = matches!(kind, TemplateKind::NoSubstitution | TemplateKind::Tail);
4597 quasis.push(TemplateChunk { cooked, raw, tail });
4598 if tail {
4599 self.bump()?;
4600 break;
4601 }
4602 self.bump()?; let expr = self.parse_expression(true)?;
4604 expressions.push(expr);
4605 if !self.at_punct(Punct::RBrace) {
4606 return Err(self.error("expecting '}' in a template substitution"));
4607 }
4608 let brace = self.current.span.start;
4609 let token = self.lexer.re_scan_template_continue(brace)?;
4610 self.current = token;
4611 }
4612 Ok(TemplateLiteral {
4613 quasis,
4614 expressions,
4615 })
4616 }
4617}
4618
4619#[derive(Debug, Clone, Copy, PartialEq, Eq)]
4621enum FunctionForm {
4622 Declaration,
4623 Expression,
4624}
4625
4626fn is_plain_identifier(param: &Pattern) -> bool {
4634 matches!(param.unparen_kind(), PatternKind::Ident(_))
4635}
4636
4637fn parameter_bindings(param: &Pattern) -> Vec<(String, Span, bool)> {
4643 fn walk(pattern: &Pattern, in_pattern: bool, out: &mut Vec<(String, Span, bool)>) {
4644 match &pattern.kind {
4645 PatternKind::Ident(ident) => out.push((ident.name.clone(), ident.span, in_pattern)),
4646 PatternKind::Assign { target, default } => {
4647 walk(target, in_pattern, out);
4648 let _ = default;
4650 }
4651 PatternKind::Rest(target) => walk(target, !is_plain_identifier(target), out),
4652 PatternKind::Array { .. } | PatternKind::Object { .. } => {
4653 let mut names = Vec::new();
4654 pattern.bound_names(&mut names);
4655 for name in names {
4656 out.push((name.name, name.span, true));
4657 }
4658 }
4659 _ => {}
4660 }
4661 }
4662 let mut out = Vec::new();
4663 let in_pattern = !is_plain_identifier(param);
4664 walk(param, in_pattern, &mut out);
4665 if out.is_empty() {
4668 let mut names = Vec::new();
4669 param.bound_names(&mut names);
4670 out.extend(names.into_iter().map(|name| (name.name, name.span, false)));
4671 }
4672 out
4673}
4674
4675fn pattern_has_default(pattern: &Pattern) -> bool {
4681 let element = |element: &Option<PatternElement>| {
4682 element.as_ref().is_some_and(|element| match element {
4683 PatternElement::Pattern(inner) => pattern_has_default(inner),
4684 PatternElement::Property { value, .. } => pattern_has_default(value),
4685 })
4686 };
4687 let rest = |rest: &Option<Box<RestElement>>| {
4688 rest.as_ref().is_some_and(|rest| match rest.as_ref() {
4689 RestElement::Pattern(inner) => pattern_has_default(inner),
4690 RestElement::Member(_) => false,
4691 })
4692 };
4693 match &pattern.kind {
4694 PatternKind::Assign { .. } => true,
4695 PatternKind::Array {
4696 elements,
4697 rest: tail,
4698 } => elements.iter().any(element) || rest(tail),
4699 PatternKind::Object {
4700 properties,
4701 rest: tail,
4702 } => properties.iter().any(element) || rest(tail),
4703 PatternKind::Rest(target) => pattern_has_default(target),
4704 _ => false,
4705 }
4706}
4707
4708fn simple_parameter_names(params: &[Pattern]) -> Vec<String> {
4709 params
4710 .iter()
4711 .filter_map(|param| match ¶m.kind {
4712 PatternKind::Ident(id) => Some(id.name.clone()),
4713 _ => None,
4714 })
4715 .collect()
4716}
4717
4718fn collect_module_binding(stmt: &Stmt, out: &mut Vec<String>) {
4721 match &stmt.kind {
4722 StmtKind::VarDecl(decl) => {
4723 if decl.kind.is_using() {
4729 return;
4730 }
4731 for declarator in &decl.declarators {
4732 let mut names = Vec::new();
4733 declarator.target.bound_names(&mut names);
4734 out.extend(names.into_iter().map(|n| n.name));
4735 }
4736 }
4737 StmtKind::FuncDecl(func) => {
4738 if let Some(name) = &func.name {
4739 out.push(name.name.clone());
4740 }
4741 }
4742 StmtKind::ClassDecl(class) => {
4743 if let Some(name) = &class.name {
4744 out.push(name.name.clone());
4745 }
4746 }
4747 StmtKind::Import(decl) => {
4748 for specifier in &decl.specifiers {
4749 match specifier {
4750 ImportSpecifier::Default(id) => out.push(id.name.clone()),
4751 ImportSpecifier::Namespace(id) => out.push(id.name.clone()),
4752 ImportSpecifier::Named { local, .. } => out.push(local.name.clone()),
4753 }
4754 }
4755 }
4756 StmtKind::Export(decl) => match &decl.kind {
4757 ExportKind::Declaration(inner) => collect_module_binding(inner, out),
4758 ExportKind::Default(expr) => match &expr.unparen().kind {
4759 ExprKind::Function(func) => {
4760 if let Some(name) = &func.name {
4761 out.push(name.name.clone());
4762 }
4763 }
4764 ExprKind::Class(class) => {
4765 if let Some(name) = &class.name {
4766 out.push(name.name.clone());
4767 }
4768 }
4769 _ => {}
4770 },
4771 _ => {}
4772 },
4773 _ => {}
4774 }
4775}
4776
4777fn span_contains(outer: Span, inner: Span) -> bool {
4779 inner.start.offset >= outer.start.offset && inner.end.offset <= outer.end.offset
4780}
4781
4782fn is_property_key_start(kind: &TokenKind) -> bool {
4783 matches!(
4784 kind,
4785 TokenKind::Ident(_)
4786 | TokenKind::Keyword(_)
4787 | TokenKind::String(_)
4788 | TokenKind::Number(_)
4789 | TokenKind::Punct(Punct::LBracket)
4790 | TokenKind::Punct(Punct::Hash)
4791 )
4792}
4793
4794#[derive(Debug, Clone, Copy)]
4796enum BinOp {
4797 Binary(BinaryOp),
4798 Logical(LogicalOp),
4799}
4800
4801impl BinOp {
4802 fn is_right_associative(self) -> bool {
4803 matches!(self, BinOp::Binary(BinaryOp::Pow))
4804 }
4805}
4806
4807fn binary_operator(kind: &TokenKind, allow_in: bool) -> Option<(u8, BinOp)> {
4808 use BinaryOp as B;
4809 use LogicalOp as L;
4810 let result = match kind {
4811 TokenKind::Punct(Punct::QuestionQuestion) => (1, BinOp::Logical(L::Coalesce)),
4812 TokenKind::Punct(Punct::PipePipe) => (2, BinOp::Logical(L::Or)),
4813 TokenKind::Punct(Punct::AmpAmp) => (3, BinOp::Logical(L::And)),
4814 TokenKind::Punct(Punct::Pipe) => (4, BinOp::Binary(B::BitOr)),
4815 TokenKind::Punct(Punct::Caret) => (5, BinOp::Binary(B::BitXor)),
4816 TokenKind::Punct(Punct::Amp) => (6, BinOp::Binary(B::BitAnd)),
4817 TokenKind::Punct(Punct::EqEq) => (7, BinOp::Binary(B::Eq)),
4818 TokenKind::Punct(Punct::NotEq) => (7, BinOp::Binary(B::NotEq)),
4819 TokenKind::Punct(Punct::EqEqEq) => (7, BinOp::Binary(B::StrictEq)),
4820 TokenKind::Punct(Punct::NotEqEq) => (7, BinOp::Binary(B::StrictNotEq)),
4821 TokenKind::Punct(Punct::Lt) => (8, BinOp::Binary(B::Lt)),
4822 TokenKind::Punct(Punct::LtEq) => (8, BinOp::Binary(B::LtEq)),
4823 TokenKind::Punct(Punct::Gt) => (8, BinOp::Binary(B::Gt)),
4824 TokenKind::Punct(Punct::GtEq) => (8, BinOp::Binary(B::GtEq)),
4825 TokenKind::Keyword(Keyword::Instanceof) => (8, BinOp::Binary(B::Instanceof)),
4826 TokenKind::Keyword(Keyword::In) if allow_in => (8, BinOp::Binary(B::In)),
4827 TokenKind::Punct(Punct::Shl) => (9, BinOp::Binary(B::Shl)),
4828 TokenKind::Punct(Punct::Shr) => (9, BinOp::Binary(B::Shr)),
4829 TokenKind::Punct(Punct::UShr) => (9, BinOp::Binary(B::UShr)),
4830 TokenKind::Punct(Punct::Plus) => (10, BinOp::Binary(B::Add)),
4831 TokenKind::Punct(Punct::Minus) => (10, BinOp::Binary(B::Sub)),
4832 TokenKind::Punct(Punct::Star) => (11, BinOp::Binary(B::Mul)),
4833 TokenKind::Punct(Punct::Slash) => (11, BinOp::Binary(B::Div)),
4834 TokenKind::Punct(Punct::Percent) => (11, BinOp::Binary(B::Mod)),
4835 TokenKind::Punct(Punct::StarStar) => (12, BinOp::Binary(B::Pow)),
4836 _ => return None,
4837 };
4838 Some(result)
4839}
4840
4841fn build_binary(op: BinOp, left: Expr, right: Expr, span: Span, op_pos: Position) -> Result<Expr> {
4842 match op {
4843 BinOp::Binary(op) => Ok(Expr::at_operator(
4844 ExprKind::Binary {
4845 op,
4846 left: Box::new(left),
4847 right: Box::new(right),
4848 },
4849 span,
4850 op_pos,
4851 )),
4852 BinOp::Logical(op) => {
4853 let mixes = |expr: &Expr, op: LogicalOp| {
4857 matches!(&expr.kind, ExprKind::Logical { op: inner, .. }
4858 if (op == LogicalOp::Coalesce) != (*inner == LogicalOp::Coalesce))
4859 };
4860 if mixes(&left, op) || mixes(&right, op) {
4861 return Err(SyntaxError::new(
4862 "cannot mix ?? with && or ||",
4865 span,
4866 ));
4867 }
4868 Ok(Expr::at_operator(
4869 ExprKind::Logical {
4870 op,
4871 left: Box::new(left),
4872 right: Box::new(right),
4873 },
4874 span,
4875 op_pos,
4876 ))
4877 }
4878 }
4879}
4880
4881fn pattern_to_expr(pattern: Pattern, span: Span) -> Expr {
4884 match pattern.kind {
4885 PatternKind::Ident(ident) => Expr::new(ExprKind::Ident(ident), span),
4886 PatternKind::Assign { target, default } => Expr::new(
4887 ExprKind::Assign {
4888 op: AssignOp::Assign,
4889 target,
4890 value: default,
4891 },
4892 span,
4893 ),
4894 PatternKind::Array { elements, rest } => {
4895 let mut out = Vec::new();
4896 for element in elements {
4897 match element {
4898 Some(PatternElement::Pattern(pattern)) => {
4899 let span = pattern.span;
4900 out.push(Some(ArrayElement::Expr(Box::new(pattern_to_expr(
4901 pattern, span,
4902 )))));
4903 }
4904 Some(PatternElement::Property { .. }) | None => out.push(None),
4905 }
4906 }
4907 if let Some(rest) = rest {
4908 let RestElement::Pattern(pattern) = *rest else {
4909 return Expr::new(ExprKind::Null, span);
4910 };
4911 let span = pattern.span;
4912 out.push(Some(ArrayElement::Spread(Box::new(pattern_to_expr(
4913 pattern, span,
4914 )))));
4915 }
4916 Expr::new(ExprKind::Array { elements: out }, span)
4917 }
4918 _ => Expr::new(ExprKind::Null, span),
4919 }
4920}
4921
4922impl Pattern {
4923 fn unparen_kind(&self) -> &PatternKind {
4926 &self.kind
4927 }
4928}