1use std::char;
2use std::collections::HashSet;
3
4const MAX_SOURCE_BYTES: usize = 16 * 1024 * 1024;
5const MAX_TOKENS: usize = 1_000_000;
6const MAX_NESTING: usize = 512;
7
8#[derive(Clone, Debug)]
9pub enum Literal {
10 Undefined,
11 Null,
12 Bool(bool),
13 Number(f64),
14 String(Vec<u16>),
15}
16
17#[derive(Clone, Debug)]
18pub enum Pattern {
19 Ident(String),
20 Array(Vec<Option<Pattern>>),
21 Object(Vec<(String, Pattern)>),
22 Rest(Box<Pattern>),
23 Default(Box<Pattern>, Box<Expr>),
24}
25
26#[derive(Clone, Debug)]
27pub struct FunctionExpr {
28 pub params: Vec<Pattern>,
29 pub body: Vec<Stmt>,
30 pub arrow: bool,
31 pub asynchronous: bool,
32 pub name: Option<String>,
33 pub source_offset: Option<usize>,
34}
35
36#[derive(Clone, Debug)]
37pub struct ClassExpr {
38 pub name: Option<String>,
39 pub extends: Option<Box<Expr>>,
40 pub methods: Vec<ClassMethod>,
41 pub fields: Vec<(String, Option<Expr>, bool)>,
42}
43
44#[derive(Clone, Debug)]
45pub struct ClassMethod {
46 pub name: String,
47 pub function: FunctionExpr,
48 pub getter: bool,
49 pub setter: bool,
50 pub is_static: bool,
51}
52
53#[derive(Clone, Debug)]
54pub enum ObjectEntry {
55 Property(String, Expr),
56 Computed(Expr, Expr),
57 Spread(Expr),
58 Method(String, FunctionExpr),
59 Getter(String, FunctionExpr),
60 Setter(String, FunctionExpr),
61}
62
63#[derive(Clone, Debug)]
64pub enum TemplatePart {
65 Text(Vec<u16>),
66 Expression(Expr),
67}
68
69#[derive(Clone, Debug)]
70pub enum ChainPart {
71 Member(Expr, bool),
72 Call(Vec<Expr>, bool),
73}
74
75#[derive(Clone, Debug)]
76pub enum Expr {
77 Literal(Literal),
78 Ident(String),
79 This,
80 Array(Vec<Option<Expr>>),
81 Object(Vec<ObjectEntry>),
82 Function(FunctionExpr),
83 Class(ClassExpr),
84 Unary(String, Box<Expr>),
85 Binary(String, Box<Expr>, Box<Expr>),
86 Conditional(Box<Expr>, Box<Expr>, Box<Expr>),
87 Assign(String, Box<Expr>, Box<Expr>),
88 Update(String, Box<Expr>, bool),
89 Member(Box<Expr>, Box<Expr>),
90 Call(Box<Expr>, Vec<Expr>),
91 New(Box<Expr>, Vec<Expr>),
92 Sequence(Vec<Expr>),
93 Await(Box<Expr>),
94 Spread(Box<Expr>),
95 Template(Vec<TemplatePart>),
96 Chain(Box<Expr>, Vec<ChainPart>),
97}
98
99#[derive(Clone, Debug)]
100pub enum VarKind {
101 Var,
102 Let,
103 Const,
104}
105
106#[derive(Clone, Debug)]
107pub enum Stmt {
108 Empty,
109 Expr(Expr),
110 Block(Vec<Stmt>),
111 Var(VarKind, Vec<(Pattern, Option<Expr>)>),
112 FunctionDecl(String, FunctionExpr),
113 ClassDecl(String, ClassExpr),
114 Return(Option<Expr>),
115 Throw(Expr),
116 If(Expr, Box<Stmt>, Option<Box<Stmt>>),
117 While(Expr, Box<Stmt>),
118 DoWhile(Box<Stmt>, Expr),
119 For {
120 init: Option<Box<Stmt>>,
121 test: Option<Expr>,
122 update: Option<Expr>,
123 body: Box<Stmt>,
124 },
125 ForEach {
126 pattern: Pattern,
127 kind: Option<VarKind>,
128 iterable: Expr,
129 body: Box<Stmt>,
130 keys: bool,
131 },
132 Try {
133 body: Box<Stmt>,
134 catch: Option<(Option<Pattern>, Box<Stmt>)>,
135 finally: Option<Box<Stmt>>,
136 },
137 Switch(Expr, Vec<(Option<Expr>, Vec<Stmt>)>),
138 Break,
139 Continue,
140}
141
142#[derive(Clone, Debug)]
143enum TemplateLex {
144 Text(Vec<u16>),
145 Expr(String, usize),
146}
147
148#[derive(Clone, Debug)]
149enum Kind {
150 Ident(String),
151 Number(f64),
152 String(Vec<u16>),
153 Template(Vec<TemplateLex>),
154 Regex(String, String),
155 Punct(String),
156 Eof,
157}
158
159#[derive(Clone, Debug)]
160struct Token {
161 kind: Kind,
162 at: usize,
163 line_break_before: bool,
164}
165
166struct Lexer<'a> {
167 source: &'a str,
168 pos: usize,
169 tokens: Vec<Token>,
170 previous_line: bool,
171}
172
173impl<'a> Lexer<'a> {
174 fn new(source: &'a str) -> Self {
175 Self {
176 source,
177 pos: 0,
178 tokens: Vec::new(),
179 previous_line: false,
180 }
181 }
182
183 fn tokenize(mut self) -> Result<Vec<Token>, String> {
184 if self.source.len() > MAX_SOURCE_BYTES {
185 return Err(String::from(
186 "SyntaxError at byte 0: source size limit exceeded",
187 ));
188 }
189 while self.pos < self.source.len() {
190 self.skip_space_and_comments()?;
191 if self.pos == self.source.len() {
192 break;
193 }
194 let at = self.pos;
195 let ch = self
196 .peek()
197 .ok_or_else(|| self.error(at, "invalid character boundary"))?;
198 let kind = if ch == '\'' || ch == '"' {
199 Kind::String(self.read_string(ch)?)
200 } else if ch == '`' {
201 Kind::Template(self.read_template()?)
202 } else if ch.is_ascii_digit()
203 || (ch == '.' && self.peek_after(1).is_some_and(|c| c.is_ascii_digit()))
204 {
205 Kind::Number(self.read_number()?)
206 } else if ch == '/' && self.regex_allowed() {
207 let (source, flags) = self.read_regex()?;
208 Kind::Regex(source, flags)
209 } else if is_ident_start(ch) {
210 Kind::Ident(self.read_identifier())
211 } else {
212 Kind::Punct(self.read_punct()?)
213 };
214 self.tokens.push(Token {
215 kind,
216 at,
217 line_break_before: std::mem::take(&mut self.previous_line),
218 });
219 if self.tokens.len() > MAX_TOKENS {
220 return Err(self.error(at, "token limit exceeded"));
221 }
222 }
223 self.tokens.push(Token {
224 kind: Kind::Eof,
225 at: self.source.len(),
226 line_break_before: self.previous_line,
227 });
228 Ok(self.tokens)
229 }
230
231 fn peek(&self) -> Option<char> {
232 self.source.get(self.pos..)?.chars().next()
233 }
234
235 fn regex_allowed(&self) -> bool {
236 match self.tokens.last().map(|token| &token.kind) {
237 None => true,
238 Some(Kind::Punct(token)) => matches!(
239 token.as_str(),
240 "(" | "["
241 | "{"
242 | ","
243 | ":"
244 | ";"
245 | "="
246 | "=>"
247 | "?"
248 | "!"
249 | "~"
250 | "&&"
251 | "||"
252 | "??"
253 | "+"
254 | "-"
255 | "*"
256 | "%"
257 | "=="
258 | "==="
259 | "!="
260 | "!=="
261 | "&"
262 | "|"
263 | "^"
264 ),
265 Some(Kind::Ident(token)) => matches!(
266 token.as_str(),
267 "return" | "throw" | "case" | "typeof" | "void" | "delete" | "in" | "of" | "await"
268 ),
269 _ => false,
270 }
271 }
272
273 fn read_regex(&mut self) -> Result<(String, String), String> {
274 let at = self.pos;
275 self.bump();
276 let mut source = String::new();
277 let mut class = false;
278 while let Some(ch) = self.bump() {
279 match ch {
280 '\n' | '\r' => return Err(self.error(at, "unterminated regular expression")),
281 '\\' => {
282 source.push(ch);
283 source.push(
284 self.bump().ok_or_else(|| {
285 self.error(at, "unterminated regular expression escape")
286 })?,
287 );
288 }
289 '[' => {
290 class = true;
291 source.push(ch);
292 }
293 ']' => {
294 class = false;
295 source.push(ch);
296 }
297 '/' if !class => {
298 let mut flags = String::new();
299 while self.peek().is_some_and(is_ident_start) {
300 if let Some(flag) = self.bump() {
301 flags.push(flag);
302 }
303 }
304 return Ok((source, flags));
305 }
306 _ => source.push(ch),
307 }
308 }
309 Err(self.error(at, "unterminated regular expression"))
310 }
311
312 fn peek_after(&self, chars: usize) -> Option<char> {
313 self.source.get(self.pos..)?.chars().nth(chars)
314 }
315
316 fn bump(&mut self) -> Option<char> {
317 let ch = self.peek()?;
318 self.pos += ch.len_utf8();
319 Some(ch)
320 }
321
322 fn starts(&self, text: &str) -> bool {
323 self.source
324 .get(self.pos..)
325 .is_some_and(|tail| tail.starts_with(text))
326 }
327
328 fn skip_space_and_comments(&mut self) -> Result<(), String> {
329 loop {
330 let Some(ch) = self.peek() else { return Ok(()) };
331 if ch.is_whitespace() || ch == '\u{feff}' {
332 self.previous_line |=
333 ch == '\n' || ch == '\r' || ch == '\u{2028}' || ch == '\u{2029}';
334 self.bump();
335 } else if self.starts("//") {
336 self.pos += 2;
337 while let Some(next) = self.peek() {
338 if next == '\n' || next == '\r' || next == '\u{2028}' || next == '\u{2029}' {
339 break;
340 }
341 self.bump();
342 }
343 } else if self.starts("/*") {
344 let at = self.pos;
345 self.pos += 2;
346 let mut closed = false;
347 while self.pos < self.source.len() {
348 if self.starts("*/") {
349 self.pos += 2;
350 closed = true;
351 break;
352 }
353 if let Some(next) = self.bump() {
354 self.previous_line |= next == '\n'
355 || next == '\r'
356 || next == '\u{2028}'
357 || next == '\u{2029}';
358 }
359 }
360 if !closed {
361 return Err(self.error(at, "unterminated block comment"));
362 }
363 } else {
364 return Ok(());
365 }
366 }
367 }
368
369 fn read_identifier(&mut self) -> String {
370 let start = self.pos;
371 self.bump();
372 while self.peek().is_some_and(is_ident_continue) {
373 self.bump();
374 }
375 self.source[start..self.pos].to_owned()
376 }
377
378 fn read_number(&mut self) -> Result<f64, String> {
379 let start = self.pos;
380 if self.starts("0x")
381 || self.starts("0X")
382 || self.starts("0b")
383 || self.starts("0B")
384 || self.starts("0o")
385 || self.starts("0O")
386 {
387 let radix = match self.source.as_bytes()[self.pos + 1] {
388 b'x' | b'X' => 16,
389 b'b' | b'B' => 2,
390 _ => 8,
391 };
392 self.pos += 2;
393 let digits = self.pos;
394 while self
395 .peek()
396 .is_some_and(|c| c.is_ascii_hexdigit() || c == '_')
397 {
398 self.bump();
399 }
400 let clean: String = self.source[digits..self.pos]
401 .chars()
402 .filter(|c| *c != '_')
403 .collect();
404 if clean.is_empty() || !clean.chars().all(|c| c.is_digit(radix)) {
405 return Err(self.error(start, "malformed numeric literal"));
406 }
407 let value = u64::from_str_radix(&clean, radix)
408 .map_err(|_| self.error(start, "numeric literal out of range"))?;
409 if self.peek() == Some('n') {
410 return Err(self.error(self.pos, "BigInt literals are unsupported"));
411 }
412 return Ok(value as f64);
413 }
414 let mut saw_dot = false;
415 let mut saw_exp = false;
416 while self.peek().is_some_and(|c| c.is_ascii_digit() || c == '_') {
417 self.bump();
418 }
419 if self.peek() == Some('.') {
420 saw_dot = true;
421 self.bump();
422 while self.peek().is_some_and(|c| c.is_ascii_digit() || c == '_') {
423 self.bump();
424 }
425 }
426 if self.peek().is_some_and(|c| c == 'e' || c == 'E') {
427 saw_exp = true;
428 self.bump();
429 if self.peek().is_some_and(|c| c == '+' || c == '-') {
430 self.bump();
431 }
432 let exp_start = self.pos;
433 while self.peek().is_some_and(|c| c.is_ascii_digit() || c == '_') {
434 self.bump();
435 }
436 if exp_start == self.pos {
437 return Err(self.error(start, "malformed exponent"));
438 }
439 }
440 let raw: String = self.source[start..self.pos]
441 .chars()
442 .filter(|c| *c != '_')
443 .collect();
444 if raw.ends_with('_') || raw.contains("__") || raw.starts_with('_') {
445 return Err(self.error(start, "malformed numeric separator"));
446 }
447 let value = raw
448 .parse::<f64>()
449 .map_err(|_| self.error(start, "malformed numeric literal"))?;
450 if self.peek() == Some('n') {
451 return Err(self.error(self.pos, "BigInt literals are unsupported"));
452 }
453 let _ = (saw_dot, saw_exp);
454 Ok(value)
455 }
456
457 fn read_string(&mut self, quote: char) -> Result<Vec<u16>, String> {
458 let start = self.pos;
459 self.bump();
460 let mut out = Vec::new();
461 loop {
462 let Some(ch) = self.bump() else {
463 return Err(self.error(start, "unterminated string literal"));
464 };
465 if ch == quote {
466 break;
467 }
468 if ch == '\n' || ch == '\r' || ch == '\u{2028}' || ch == '\u{2029}' {
469 return Err(self.error(self.pos, "line terminator in string literal"));
470 }
471 if ch != '\\' {
472 out.extend(ch.encode_utf16(&mut [0; 2]).iter().copied());
473 continue;
474 }
475 let esc_at = self.pos - 1;
476 let Some(esc) = self.bump() else {
477 return Err(self.error(esc_at, "unterminated escape"));
478 };
479 match esc {
480 'n' => out.push(10),
481 'r' => out.push(13),
482 't' => out.push(9),
483 'b' => out.push(8),
484 'f' => out.push(12),
485 'v' => out.push(11),
486 '0' => out.push(0),
487 '\'' => out.push(39),
488 '"' => out.push(34),
489 '\\' => out.push(92),
490 '\n' => {}
491 '\r' => {
492 if self.peek() == Some('\n') {
493 self.bump();
494 }
495 }
496 'x' => out.push(self.read_hex(2, esc_at)? as u16),
497 'u' => {
498 if self.peek() == Some('{') {
499 self.bump();
500 let cp_start = self.pos;
501 while self.peek().is_some_and(|c| c.is_ascii_hexdigit()) {
502 self.bump();
503 }
504 if cp_start == self.pos || self.bump() != Some('}') {
505 return Err(self.error(esc_at, "malformed Unicode escape"));
506 }
507 let cp = u32::from_str_radix(&self.source[cp_start..self.pos - 1], 16)
508 .map_err(|_| self.error(esc_at, "malformed Unicode escape"))?;
509 if cp > 0x10ffff {
510 return Err(self.error(esc_at, "Unicode escape out of range"));
511 }
512 if let Some(scalar) = char::from_u32(cp) {
513 let mut buf = [0; 2];
514 out.extend_from_slice(scalar.encode_utf16(&mut buf));
515 }
516 } else {
517 out.push(self.read_hex(4, esc_at)? as u16);
518 }
519 }
520 _ => out.extend(esc.encode_utf16(&mut [0; 2]).iter().copied()),
521 }
522 }
523 Ok(out)
524 }
525
526 fn read_hex(&mut self, count: usize, at: usize) -> Result<u32, String> {
527 let start = self.pos;
528 for _ in 0..count {
529 if !self.peek().is_some_and(|c| c.is_ascii_hexdigit()) {
530 return Err(self.error(at, "malformed hexadecimal escape"));
531 }
532 self.bump();
533 }
534 u32::from_str_radix(&self.source[start..self.pos], 16)
535 .map_err(|_| self.error(at, "malformed hexadecimal escape"))
536 }
537
538 fn read_template(&mut self) -> Result<Vec<TemplateLex>, String> {
539 let start = self.pos;
540 self.bump();
541 let mut parts = Vec::new();
542 let mut text = Vec::new();
543 loop {
544 let Some(ch) = self.bump() else {
545 return Err(self.error(start, "unterminated template literal"));
546 };
547 match ch {
548 '`' => {
549 if !text.is_empty() || parts.is_empty() {
550 parts.push(TemplateLex::Text(text));
551 }
552 return Ok(parts);
553 }
554 '\\' => {
555 let Some(escaped) = self.bump() else {
556 return Err(self.error(start, "unterminated template escape"));
557 };
558 match escaped {
559 'n' => text.push(10),
560 'r' => text.push(13),
561 't' => text.push(9),
562 '`' => text.push(96),
563 '$' => text.push(36),
564 '\\' => text.push(92),
565 '\n' => {}
566 '\r' => {
567 if self.peek() == Some('\n') {
568 self.bump();
569 }
570 }
571 'u' => {
572 if self.peek() == Some('{') {
573 self.bump();
574 let cp_start = self.pos;
575 while self.peek().is_some_and(|c| c.is_ascii_hexdigit()) {
576 self.bump();
577 }
578 if cp_start == self.pos || self.bump() != Some('}') {
579 return Err(
580 self.error(self.pos, "malformed template Unicode escape")
581 );
582 }
583 let cp =
584 u32::from_str_radix(&self.source[cp_start..self.pos - 1], 16)
585 .map_err(|_| {
586 self.error(cp_start, "malformed template Unicode escape")
587 })?;
588 let scalar = char::from_u32(cp).ok_or_else(|| {
589 self.error(cp_start, "template Unicode escape out of range")
590 })?;
591 let mut buf = [0; 2];
592 text.extend_from_slice(scalar.encode_utf16(&mut buf));
593 } else {
594 let unit = self.read_hex(4, self.pos - 2)? as u16;
595 text.push(unit);
596 }
597 }
598 other => text.extend(other.encode_utf16(&mut [0; 2]).iter().copied()),
599 }
600 }
601 '$' if self.peek() == Some('{') => {
602 self.bump();
603 if !text.is_empty() || parts.is_empty() {
604 parts.push(TemplateLex::Text(std::mem::take(&mut text)));
605 }
606 let expr_start = self.pos;
607 let (expr_end, after) = find_template_expr(self.source, expr_start)
608 .ok_or_else(|| {
609 self.error(expr_start, "unterminated template interpolation")
610 })?;
611 let expr = self.source[expr_start..expr_end].to_owned();
612 parts.push(TemplateLex::Expr(expr, expr_start));
613 self.pos = after;
614 }
615 other => text.extend(other.encode_utf16(&mut [0; 2]).iter().copied()),
616 }
617 }
618 }
619
620 fn read_punct(&mut self) -> Result<String, String> {
621 const PUNCT: [&str; 33] = [
622 ">>>=", "**=", "&&=", "||=", "??=", "<<=", ">>=", "===", "!==", ">>>", "...", "=>",
623 "==", "!=", "<=", ">=", "++", "--", "&&", "||", "??", "**", "+=", "-=", "*=", "/=",
624 "%=", "&=", "|=", "^=", "<<", ">>", "?.",
625 ];
626 for punct in PUNCT {
627 if self.starts(punct) {
628 self.pos += punct.len();
629 return Ok(punct.to_owned());
630 }
631 }
632 let ch = self
633 .bump()
634 .ok_or_else(|| self.error(self.pos, "unexpected end of source"))?;
635 if "{}[]();,:.?~!+-*/%<>=&|^".contains(ch) {
636 Ok(ch.to_string())
637 } else {
638 Err(self.error(self.pos - ch.len_utf8(), "unsupported character"))
639 }
640 }
641
642 fn error(&self, at: usize, message: &str) -> String {
643 located_error(self.source, at, message)
644 }
645}
646
647fn find_template_expr(source: &str, start: usize) -> Option<(usize, usize)> {
648 let bytes = source.as_bytes();
649 let mut i = start;
650 let mut depth = 1usize;
651 while i < bytes.len() {
652 match bytes[i] {
653 b'\'' | b'"' => {
654 let quote = bytes[i];
655 i += 1;
656 while i < bytes.len() {
657 if bytes[i] == b'\\' {
658 i = i.saturating_add(2);
659 } else if bytes[i] == quote {
660 i += 1;
661 break;
662 } else {
663 i += 1;
664 }
665 }
666 }
667 b'`' => {
668 i += 1;
669 while i < bytes.len() {
670 if bytes[i] == b'\\' {
671 i = i.saturating_add(2);
672 } else if bytes[i] == b'`' {
673 i += 1;
674 break;
675 } else {
676 i += 1;
677 }
678 }
679 }
680 b'/' if bytes.get(i + 1) == Some(&b'/') => {
681 i += 2;
682 while i < bytes.len() && bytes[i] != b'\n' {
683 i += 1;
684 }
685 }
686 b'/' if bytes.get(i + 1) == Some(&b'*') => {
687 i += 2;
688 while i + 1 < bytes.len() && !(bytes[i] == b'*' && bytes[i + 1] == b'/') {
689 i += 1;
690 }
691 i = i.saturating_add(2);
692 }
693 b'{' => {
694 depth += 1;
695 i += 1;
696 }
697 b'}' => {
698 depth -= 1;
699 if depth == 0 {
700 return Some((i, i + 1));
701 }
702 i += 1;
703 }
704 _ => {
705 let ch = source.get(i..)?.chars().next()?;
706 i += ch.len_utf8();
707 }
708 }
709 }
710 None
711}
712
713fn is_ident_start(ch: char) -> bool {
714 ch == '$' || ch == '_' || ch.is_alphabetic() || (ch as u32) >= 0x80
715}
716fn is_ident_continue(ch: char) -> bool {
717 is_ident_start(ch) || ch.is_ascii_digit() || ch == '\u{200c}' || ch == '\u{200d}'
718}
719
720fn located_error(source: &str, at: usize, message: &str) -> String {
721 let safe = at.min(source.len());
722 let prefix = &source[..safe];
723 let line = prefix.bytes().filter(|b| *b == b'\n').count() + 1;
724 let column = prefix.rsplit('\n').next().unwrap_or("").chars().count() + 1;
725 format!("SyntaxError at {line}:{column}: {message}")
726}
727
728struct Parser<'a> {
729 source: &'a str,
730 tokens: Vec<Token>,
731 pos: usize,
732 nesting: usize,
733 function_depth: usize,
734 allow_in: bool,
735 rejected_arrow_params: HashSet<usize>,
738}
739
740impl<'a> Parser<'a> {
741 fn new(source: &'a str) -> Result<Self, String> {
742 Ok(Self {
743 source,
744 tokens: Lexer::new(source).tokenize()?,
745 pos: 0,
746 nesting: 0,
747 function_depth: 0,
748 allow_in: true,
749 rejected_arrow_params: HashSet::new(),
750 })
751 }
752
753 fn parse_program(mut self) -> Result<Vec<Stmt>, String> {
754 let mut body = Vec::new();
755 while !self.eof() {
756 let before = self.pos;
757 body.push(self.statement()?);
758 if self.pos == before {
759 return Err(self.error_here("parser made no progress"));
760 }
761 }
762 Ok(body)
763 }
764
765 fn statement(&mut self) -> Result<Stmt, String> {
766 if self.eat_punct(";") {
767 return Ok(Stmt::Empty);
768 }
769 if self.is_punct("{") {
770 return self.block();
771 }
772 if let Some(kind) = self.eat_var_kind() {
773 return self.variable_statement(kind, true);
774 }
775 if self.eat_ident("async") {
776 if self.eat_ident("function") {
777 return self.function_declaration(true);
778 }
779 if self.is_ident("function") {
780 self.bump();
781 return self.function_declaration(true);
782 }
783 self.pos -= 1;
784 }
785 if self.eat_ident("function") {
786 return self.function_declaration(false);
787 }
788 if self.eat_ident("class") {
789 return self.class_declaration();
790 }
791 if self.eat_ident("return") {
792 if self.function_depth == 0 {
793 return Err(self.error_previous("return outside function"));
794 }
795 let value = if self.line_break_before()
796 || self.is_punct(";")
797 || self.is_punct("}")
798 || self.eof()
799 {
800 None
801 } else {
802 Some(self.expression()?)
803 };
804 self.semicolon()?;
805 return Ok(Stmt::Return(value));
806 }
807 if self.eat_ident("throw") {
808 if self.line_break_before() {
809 return Err(self.error_previous("line terminator after throw"));
810 }
811 let value = self.expression()?;
812 self.semicolon()?;
813 return Ok(Stmt::Throw(value));
814 }
815 if self.eat_ident("if") {
816 self.expect_punct("(")?;
817 let test = self.expression()?;
818 self.expect_punct(")")?;
819 let then = Box::new(self.statement()?);
820 let otherwise = if self.eat_ident("else") {
821 Some(Box::new(self.statement()?))
822 } else {
823 None
824 };
825 return Ok(Stmt::If(test, then, otherwise));
826 }
827 if self.eat_ident("while") {
828 self.expect_punct("(")?;
829 let test = self.expression()?;
830 self.expect_punct(")")?;
831 return Ok(Stmt::While(test, Box::new(self.statement()?)));
832 }
833 if self.eat_ident("do") {
834 let body = Box::new(self.statement()?);
835 self.expect_ident("while")?;
836 self.expect_punct("(")?;
837 let test = self.expression()?;
838 self.expect_punct(")")?;
839 self.semicolon()?;
840 return Ok(Stmt::DoWhile(body, test));
841 }
842 if self.eat_ident("for") {
843 return self.for_statement();
844 }
845 if self.eat_ident("try") {
846 let body = Box::new(self.statement()?);
847 let catch = if self.eat_ident("catch") {
848 let binding = if self.eat_punct("(") {
849 let pat = if self.is_punct(")") {
850 None
851 } else {
852 Some(self.pattern()?)
853 };
854 self.expect_punct(")")?;
855 pat
856 } else {
857 None
858 };
859 Some((binding, Box::new(self.statement()?)))
860 } else {
861 None
862 };
863 let finally = if self.eat_ident("finally") {
864 Some(Box::new(self.statement()?))
865 } else {
866 None
867 };
868 if catch.is_none() && finally.is_none() {
869 return Err(self.error_previous("try requires catch or finally"));
870 }
871 return Ok(Stmt::Try {
872 body,
873 catch,
874 finally,
875 });
876 }
877 if self.eat_ident("switch") {
878 return self.switch_statement();
879 }
880 if self.eat_ident("break") {
881 self.semicolon()?;
882 return Ok(Stmt::Break);
883 }
884 if self.eat_ident("continue") {
885 self.semicolon()?;
886 return Ok(Stmt::Continue);
887 }
888 if self.eat_ident("debugger") {
889 self.semicolon()?;
890 return Ok(Stmt::Empty);
891 }
892 if self.eat_ident("import") {
893 return Err(self.error_previous("import declarations are unsupported"));
894 }
895 if self.eat_ident("export") {
896 return self.export_statement();
897 }
898 let expr = self.expression()?;
899 self.semicolon()?;
900 Ok(Stmt::Expr(expr))
901 }
902
903 fn block(&mut self) -> Result<Stmt, String> {
904 self.enter()?;
905 self.expect_punct("{")?;
906 let mut statements = Vec::new();
907 while !self.eof() && !self.is_punct("}") {
908 statements.push(self.statement()?);
909 }
910 self.expect_punct("}")?;
911 self.leave();
912 Ok(Stmt::Block(statements))
913 }
914
915 fn eat_var_kind(&mut self) -> Option<VarKind> {
916 if self.eat_ident("var") {
917 Some(VarKind::Var)
918 } else if self.eat_ident("let") {
919 Some(VarKind::Let)
920 } else if self.eat_ident("const") {
921 Some(VarKind::Const)
922 } else {
923 None
924 }
925 }
926
927 fn variable_statement(&mut self, kind: VarKind, semi: bool) -> Result<Stmt, String> {
928 let mut declarations = Vec::new();
929 loop {
930 let pattern = self.pattern()?;
931 let (pattern, init) = if let Pattern::Default(pattern, initial) = pattern {
932 (*pattern, Some(*initial))
933 } else {
934 let initial = if self.eat_punct("=") {
935 Some(self.assignment_expression()?)
936 } else {
937 None
938 };
939 (pattern, initial)
940 };
941 if semi && init.is_none() && declarations.is_empty() && self.last_binding_is_const() {
942 return Err(self.error_previous("const declaration requires an initializer"));
943 }
944 declarations.push((pattern, init));
945 if !self.eat_punct(",") {
946 break;
947 }
948 }
949 if semi {
950 self.semicolon()?;
951 }
952 Ok(Stmt::Var(kind, declarations))
953 }
954
955 fn last_binding_is_const(&self) -> bool {
956 self.tokens[..self.pos]
957 .iter()
958 .rev()
959 .find_map(|t| match &t.kind {
960 Kind::Ident(s) if ["var", "let", "const"].contains(&s.as_str()) => {
961 Some(s == "const")
962 }
963 _ => None,
964 })
965 .unwrap_or(false)
966 }
967
968 fn function_declaration(&mut self, asynchronous: bool) -> Result<Stmt, String> {
969 let name = self.expect_identifier_name()?;
970 let mut function = self.function_tail(Some(name.clone()), false)?;
971 function.asynchronous = asynchronous;
972 Ok(Stmt::FunctionDecl(name, function))
973 }
974
975 fn class_declaration(&mut self) -> Result<Stmt, String> {
976 let name = self.expect_identifier_name()?;
977 let class = self.class_tail(Some(name.clone()))?;
978 Ok(Stmt::ClassDecl(name, class))
979 }
980
981 fn class_tail(&mut self, name: Option<String>) -> Result<ClassExpr, String> {
982 self.enter()?;
983 let extends = if self.eat_ident("extends") {
984 Some(Box::new(self.left_hand_side()?))
985 } else {
986 None
987 };
988 self.expect_punct("{")?;
989 let mut methods = Vec::new();
990 let mut fields = Vec::new();
991 while !self.eof() && !self.is_punct("}") {
992 if self.eat_punct(";") {
993 continue;
994 }
995 let is_static = if self.is_ident("static") && !self.peek_n_punct(1, "(") {
996 self.bump();
997 true
998 } else {
999 false
1000 };
1001 let asynchronous = self.is_ident("async")
1002 && !self.peek_n_linebreak(1)
1003 && !self.peek_n_punct(1, "(")
1004 && !self.peek_n_punct(1, "=")
1005 && !self.peek_n_punct(1, ";")
1006 && !self.peek_n_punct(1, "}");
1007 if asynchronous {
1008 self.bump();
1009 }
1010 let mut getter = false;
1011 let mut setter = false;
1012 if (self.is_ident("get") || self.is_ident("set")) && !self.peek_n_punct(1, "(") {
1013 getter = self.is_ident("get");
1014 setter = !getter;
1015 self.bump();
1016 }
1017 let method_name = self.property_name()?;
1018 if !self.is_punct("(") && !getter && !setter {
1019 let initial = if self.eat_punct("=") {
1020 Some(self.assignment_expression()?)
1021 } else {
1022 None
1023 };
1024 self.semicolon()?;
1025 fields.push((method_name, initial, is_static));
1026 continue;
1027 }
1028 if asynchronous && (getter || setter || method_name == "constructor") {
1029 return Err(self.error_previous("this class method cannot be async"));
1030 }
1031 let mut function = self.method_function(Some(method_name.clone()))?;
1032 function.asynchronous = asynchronous;
1033 methods.push(ClassMethod {
1034 name: method_name,
1035 function,
1036 getter,
1037 setter,
1038 is_static,
1039 });
1040 }
1041 self.expect_punct("}")?;
1042 self.leave();
1043 Ok(ClassExpr {
1044 name,
1045 extends,
1046 methods,
1047 fields,
1048 })
1049 }
1050
1051 fn function_tail(&mut self, name: Option<String>, arrow: bool) -> Result<FunctionExpr, String> {
1052 let source_offset = Some(self.current().at);
1053 let params = self.parameters()?;
1054 self.function_depth += 1;
1055 let body = match self.block()? {
1056 Stmt::Block(stmts) => stmts,
1057 _ => Vec::new(),
1058 };
1059 self.function_depth -= 1;
1060 Ok(FunctionExpr {
1061 params,
1062 body,
1063 arrow,
1064 asynchronous: false,
1065 name,
1066 source_offset,
1067 })
1068 }
1069
1070 fn method_function(&mut self, name: Option<String>) -> Result<FunctionExpr, String> {
1071 self.function_tail(name, false)
1072 }
1073
1074 fn parameters(&mut self) -> Result<Vec<Pattern>, String> {
1075 self.enter()?;
1076 self.expect_punct("(")?;
1077 let mut params = Vec::new();
1078 if !self.is_punct(")") {
1079 loop {
1080 let pattern = if self.eat_punct("...") {
1081 Pattern::Rest(Box::new(self.pattern()?))
1082 } else {
1083 self.pattern()?
1084 };
1085 params.push(pattern);
1086 if !self.eat_punct(",") {
1087 break;
1088 }
1089 if self.is_punct(")") {
1090 break;
1091 }
1092 }
1093 }
1094 self.expect_punct(")")?;
1095 self.leave();
1096 Ok(params)
1097 }
1098
1099 fn for_statement(&mut self) -> Result<Stmt, String> {
1100 self.expect_punct("(")?;
1101 let init = if self.eat_punct(";") {
1102 None
1103 } else if let Some(kind) = self.eat_var_kind() {
1104 Some(Box::new(self.variable_statement(kind, false)?))
1105 } else {
1106 let allow_in = self.allow_in;
1107 self.allow_in = false;
1108 let parsed = self.expression();
1109 self.allow_in = allow_in;
1110 Some(Box::new(Stmt::Expr(parsed?)))
1111 };
1112 if self.eat_ident("in") || self.eat_ident("of") {
1113 let keys = self.previous_is_ident("in");
1114 let (pattern, kind) = match init {
1115 Some(boxed) => match *boxed {
1116 Stmt::Expr(e) => (expr_to_pattern(e)?, None),
1117 Stmt::Var(kind, mut v) if v.len() == 1 => (v.remove(0).0, Some(kind)),
1118 _ => return Err(self.error_previous("invalid for-each binding")),
1119 },
1120 None => return Err(self.error_previous("missing for-each binding")),
1121 };
1122 let iterable = self.expression()?;
1123 self.expect_punct(")")?;
1124 let body = Box::new(self.statement()?);
1125 return Ok(Stmt::ForEach {
1126 pattern,
1127 kind,
1128 iterable,
1129 body,
1130 keys,
1131 });
1132 }
1133 if init.is_some() {
1134 self.expect_punct(";")?;
1135 }
1136 let test = if self.is_punct(";") {
1137 None
1138 } else {
1139 Some(self.expression()?)
1140 };
1141 self.expect_punct(";")?;
1142 let update = if self.is_punct(")") {
1143 None
1144 } else {
1145 Some(self.expression()?)
1146 };
1147 self.expect_punct(")")?;
1148 let body = Box::new(self.statement()?);
1149 Ok(Stmt::For {
1150 init,
1151 test,
1152 update,
1153 body,
1154 })
1155 }
1156
1157 fn switch_statement(&mut self) -> Result<Stmt, String> {
1158 self.expect_punct("(")?;
1159 let value = self.expression()?;
1160 self.expect_punct(")")?;
1161 self.expect_punct("{")?;
1162 let mut cases = Vec::new();
1163 while !self.eof() && !self.is_punct("}") {
1164 let test = if self.eat_ident("case") {
1165 Some(self.expression_no_comma()?)
1166 } else if self.eat_ident("default") {
1167 None
1168 } else {
1169 return Err(self.error_here("expected case or default"));
1170 };
1171 self.expect_punct(":")?;
1172 let mut body = Vec::new();
1173 while !self.eof()
1174 && !self.is_punct("}")
1175 && !self.is_ident("case")
1176 && !self.is_ident("default")
1177 {
1178 body.push(self.statement()?);
1179 }
1180 cases.push((test, body));
1181 }
1182 self.expect_punct("}")?;
1183 Ok(Stmt::Switch(value, cases))
1184 }
1185
1186 fn export_statement(&mut self) -> Result<Stmt, String> {
1187 if self.eat_punct("*") {
1188 return Err(self.error_previous("export star declarations are unsupported"));
1189 }
1190 if self.eat_ident("default") {
1191 if self.eat_ident("function") {
1192 return self.function_declaration(false);
1193 }
1194 if self.eat_ident("class") {
1195 return self.class_declaration();
1196 }
1197 let expr = self.assignment_expression()?;
1198 self.semicolon()?;
1199 return Ok(Stmt::Expr(expr));
1200 }
1201 if let Some(kind) = self.eat_var_kind() {
1202 return self.variable_statement(kind, true);
1203 }
1204 if self.eat_ident("function") {
1205 return self.function_declaration(false);
1206 }
1207 if self.eat_ident("class") {
1208 return self.class_declaration();
1209 }
1210 Err(self.error_previous("unsupported export form"))
1211 }
1212
1213 fn expression(&mut self) -> Result<Expr, String> {
1214 let mut expr = self.assignment_expression()?;
1215 if self.eat_punct(",") {
1216 let mut values = vec![expr];
1217 loop {
1218 values.push(self.assignment_expression()?);
1219 if !self.eat_punct(",") {
1220 break;
1221 }
1222 }
1223 expr = Expr::Sequence(values);
1224 }
1225 Ok(expr)
1226 }
1227
1228 fn expression_no_comma(&mut self) -> Result<Expr, String> {
1229 self.assignment_expression()
1230 }
1231
1232 fn assignment_expression(&mut self) -> Result<Expr, String> {
1233 if let Some((params, is_async)) = self.try_arrow_params()? {
1234 return self.arrow_tail(params, is_async);
1235 }
1236 let left = self.conditional_expression()?;
1237 if let Some(op) = self.assignment_operator() {
1238 self.bump();
1239 if !is_assignable(&left) {
1240 return Err(self.error_previous("invalid assignment target"));
1241 }
1242 let right = self.assignment_expression()?;
1243 Ok(Expr::Assign(op, Box::new(left), Box::new(right)))
1244 } else {
1245 Ok(left)
1246 }
1247 }
1248
1249 fn try_arrow_params(&mut self) -> Result<Option<(Vec<Pattern>, bool)>, String> {
1250 let save = self.pos;
1251 let saved_nesting = self.nesting;
1252 let is_async = if self.is_ident("async") && !self.peek_n_linebreak(1) {
1253 self.bump();
1254 true
1255 } else {
1256 false
1257 };
1258 if let Kind::Ident(name) = self.current().kind.clone() {
1259 self.bump();
1260 if self.eat_punct("=>") {
1261 return Ok(Some((vec![Pattern::Ident(name)], is_async)));
1262 }
1263 } else if self.is_punct("(") && !self.rejected_arrow_params.contains(&self.pos) {
1264 let open = self.pos;
1265 if let Ok(params) = self.parameters() {
1266 if self.eat_punct("=>") {
1267 return Ok(Some((params, is_async)));
1268 }
1269 }
1270 self.rejected_arrow_params.insert(open);
1271 }
1272 self.pos = save;
1273 self.nesting = saved_nesting;
1274 Ok(None)
1275 }
1276
1277 fn arrow_tail(&mut self, params: Vec<Pattern>, asynchronous: bool) -> Result<Expr, String> {
1278 let source_offset = Some(self.current().at);
1279 let body = if self.eat_punct("{") {
1280 self.pos -= 1;
1281 self.function_depth += 1;
1282 let parsed = self.block()?;
1283 self.function_depth -= 1;
1284 match parsed {
1285 Stmt::Block(body) => body,
1286 _ => Vec::new(),
1287 }
1288 } else {
1289 vec![Stmt::Return(Some(self.assignment_expression()?))]
1290 };
1291 Ok(Expr::Function(FunctionExpr {
1292 params,
1293 body,
1294 arrow: true,
1295 asynchronous,
1296 name: None,
1297 source_offset,
1298 }))
1299 }
1300
1301 fn conditional_expression(&mut self) -> Result<Expr, String> {
1302 let test = self.binary_expression(1)?;
1303 if self.eat_punct("?") {
1304 let yes = self.assignment_expression()?;
1305 self.expect_punct(":")?;
1306 let no = self.assignment_expression()?;
1307 Ok(Expr::Conditional(
1308 Box::new(test),
1309 Box::new(yes),
1310 Box::new(no),
1311 ))
1312 } else {
1313 Ok(test)
1314 }
1315 }
1316
1317 fn binary_expression(&mut self, min_prec: u8) -> Result<Expr, String> {
1318 let mut left = self.unary_expression()?;
1319 while let Some((op, prec, right_assoc)) = self.binary_op() {
1320 if prec < min_prec {
1321 break;
1322 }
1323 self.bump();
1324 let right = self.binary_expression(if right_assoc { prec } else { prec + 1 })?;
1325 left = Expr::Binary(op, Box::new(left), Box::new(right));
1326 }
1327 Ok(left)
1328 }
1329
1330 fn unary_expression(&mut self) -> Result<Expr, String> {
1331 if self.eat_ident("await") {
1332 return Ok(Expr::Await(Box::new(self.unary_expression()?)));
1333 }
1334 if self.eat_ident("yield") {
1335 return Err(self.error_previous("yield expressions are unsupported"));
1336 }
1337 if self.eat_ident("typeof")
1338 || self.eat_ident("void")
1339 || self.eat_ident("delete")
1340 || self.eat_punct("!")
1341 || self.eat_punct("~")
1342 || self.eat_punct("+")
1343 || self.eat_punct("-")
1344 {
1345 let op = self.previous_text();
1346 return Ok(Expr::Unary(op, Box::new(self.unary_expression()?)));
1347 }
1348 if self.eat_punct("++") || self.eat_punct("--") {
1349 let op = self.previous_text();
1350 let target = self.unary_expression()?;
1351 if !is_assignable(&target) {
1352 return Err(self.error_previous("invalid update target"));
1353 }
1354 return Ok(Expr::Update(op, Box::new(target), true));
1355 }
1356 let mut expr = self.left_hand_side()?;
1357 if (self.eat_punct("++") || self.eat_punct("--")) && !self.line_break_before() {
1358 let op = self.previous_text();
1359 if !is_assignable(&expr) {
1360 return Err(self.error_previous("invalid update target"));
1361 }
1362 expr = Expr::Update(op, Box::new(expr), false);
1363 }
1364 Ok(expr)
1365 }
1366
1367 fn left_hand_side(&mut self) -> Result<Expr, String> {
1368 if self.eat_ident("new") {
1369 let mut callee = self.primary()?;
1370 loop {
1371 if self.eat_punct(".") {
1372 let key = self.property_name()?;
1373 callee = Expr::Member(
1374 Box::new(callee),
1375 Box::new(Expr::Literal(Literal::String(key.encode_utf16().collect()))),
1376 );
1377 } else if self.eat_punct("[") {
1378 let key = self.expression()?;
1379 self.expect_punct("]")?;
1380 callee = Expr::Member(Box::new(callee), Box::new(key));
1381 } else {
1382 break;
1383 }
1384 }
1385 let args = if self.is_punct("(") {
1386 self.arguments()?
1387 } else {
1388 Vec::new()
1389 };
1390 return self.postfix(Expr::New(Box::new(callee), args));
1391 }
1392 self.member_only()
1393 }
1394
1395 fn member_only(&mut self) -> Result<Expr, String> {
1396 let expr = self.primary()?;
1397 self.postfix(expr)
1398 }
1399
1400 fn postfix(&mut self, mut expr: Expr) -> Result<Expr, String> {
1401 let mut parts = Vec::new();
1402 let mut optional = false;
1403 loop {
1404 if self.eat_punct(".") {
1405 let key = self.property_name()?;
1406 parts.push(ChainPart::Member(
1407 Expr::Literal(Literal::String(key.encode_utf16().collect())),
1408 false,
1409 ));
1410 } else if self.eat_punct("[") {
1411 let key = self.expression()?;
1412 self.expect_punct("]")?;
1413 parts.push(ChainPart::Member(key, false));
1414 } else if self.is_punct("(") {
1415 let args = self.arguments()?;
1416 parts.push(ChainPart::Call(args, false));
1417 } else if self.eat_punct("?.") {
1418 optional = true;
1419 if self.eat_punct("[") {
1420 let key = self.expression()?;
1421 self.expect_punct("]")?;
1422 parts.push(ChainPart::Member(key, true));
1423 } else if self.is_punct("(") {
1424 let args = self.arguments()?;
1425 parts.push(ChainPart::Call(args, true));
1426 } else {
1427 let key = self.property_name()?;
1428 parts.push(ChainPart::Member(
1429 Expr::Literal(Literal::String(key.encode_utf16().collect())),
1430 true,
1431 ));
1432 }
1433 } else {
1434 break;
1435 }
1436 }
1437 if optional {
1438 return Ok(Expr::Chain(Box::new(expr), parts));
1439 }
1440 for part in parts {
1441 expr = match part {
1442 ChainPart::Member(key, _) => Expr::Member(Box::new(expr), Box::new(key)),
1443 ChainPart::Call(args, _) => Expr::Call(Box::new(expr), args),
1444 };
1445 }
1446 Ok(expr)
1447 }
1448
1449 fn arguments(&mut self) -> Result<Vec<Expr>, String> {
1450 self.enter()?;
1451 self.expect_punct("(")?;
1452 let mut args = Vec::new();
1453 if !self.is_punct(")") {
1454 loop {
1455 if self.eat_punct("...") {
1456 args.push(Expr::Spread(Box::new(self.assignment_expression()?)));
1457 } else {
1458 args.push(self.assignment_expression()?);
1459 }
1460 if !self.eat_punct(",") {
1461 break;
1462 }
1463 if self.is_punct(")") {
1464 break;
1465 }
1466 }
1467 }
1468 self.expect_punct(")")?;
1469 self.leave();
1470 Ok(args)
1471 }
1472
1473 fn primary(&mut self) -> Result<Expr, String> {
1474 let token = self.bump().clone();
1475 match token.kind {
1476 Kind::Number(n) => Ok(Expr::Literal(Literal::Number(n))),
1477 Kind::String(s) => Ok(Expr::Literal(Literal::String(s))),
1478 Kind::Template(parts) => self.template_expr(parts, token.at),
1479 Kind::Regex(source, flags) => Ok(Expr::New(
1480 Box::new(Expr::Ident("RegExp".into())),
1481 vec![
1482 Expr::Literal(Literal::String(source.encode_utf16().collect())),
1483 Expr::Literal(Literal::String(flags.encode_utf16().collect())),
1484 ],
1485 )),
1486 Kind::Ident(name) => match name.as_str() {
1487 "true" => Ok(Expr::Literal(Literal::Bool(true))),
1488 "false" => Ok(Expr::Literal(Literal::Bool(false))),
1489 "null" => Ok(Expr::Literal(Literal::Null)),
1490 "undefined" => Ok(Expr::Literal(Literal::Undefined)),
1491 "this" => Ok(Expr::This),
1492 "function" => {
1493 let name = if self.is_identifier_name() && !self.is_punct("(") {
1494 Some(self.expect_identifier_name()?)
1495 } else {
1496 None
1497 };
1498 Ok(Expr::Function(self.function_tail(name, false)?))
1499 }
1500 "async" if self.eat_ident("function") => {
1501 let name = if self.is_identifier_name() && !self.is_punct("(") {
1502 Some(self.expect_identifier_name()?)
1503 } else {
1504 None
1505 };
1506 let mut function = self.function_tail(name, false)?;
1507 function.asynchronous = true;
1508 Ok(Expr::Function(function))
1509 }
1510 "class" => {
1511 let name = if self.is_identifier_name()
1512 && !self.is_punct("{")
1513 && !self.is_ident("extends")
1514 {
1515 Some(self.expect_identifier_name()?)
1516 } else {
1517 None
1518 };
1519 Ok(Expr::Class(self.class_tail(name)?))
1520 }
1521 _ => Ok(Expr::Ident(name)),
1522 },
1523 Kind::Punct(p) if p == "(" => {
1524 self.enter()?;
1525 let expr = self.expression()?;
1526 self.expect_punct(")")?;
1527 self.leave();
1528 Ok(expr)
1529 }
1530 Kind::Punct(p) if p == "[" => self.array_literal(),
1531 Kind::Punct(p) if p == "{" => self.object_literal(),
1532 _ => Err(self.error_at(token.at, "expected expression")),
1533 }
1534 }
1535
1536 fn template_expr(&mut self, parts: Vec<TemplateLex>, at: usize) -> Result<Expr, String> {
1537 let mut parsed = Vec::new();
1538 for part in parts {
1539 match part {
1540 TemplateLex::Text(text) => parsed.push(TemplatePart::Text(text)),
1541 TemplateLex::Expr(source, offset) => {
1542 let mut sub = Parser::new(&source)
1543 .map_err(|e| format!("{e} in template at {}", self.location(offset)))?;
1544 let expr = sub
1545 .expression()
1546 .map_err(|e| format!("{e} in template at {}", self.location(offset)))?;
1547 if !sub.eof() {
1548 return Err(self.error_at(
1549 offset + sub.current().at,
1550 "unexpected token in template interpolation",
1551 ));
1552 }
1553 parsed.push(TemplatePart::Expression(expr));
1554 }
1555 }
1556 }
1557 let _ = at;
1558 Ok(Expr::Template(parsed))
1559 }
1560
1561 fn array_literal(&mut self) -> Result<Expr, String> {
1562 self.enter()?;
1563 let mut items = Vec::new();
1564 while !self.eof() && !self.is_punct("]") {
1565 if self.eat_punct(",") {
1566 items.push(None);
1567 continue;
1568 }
1569 if self.eat_punct("...") {
1570 items.push(Some(Expr::Spread(Box::new(self.assignment_expression()?))));
1571 } else {
1572 items.push(Some(self.assignment_expression()?));
1573 }
1574 if !self.eat_punct(",") {
1575 break;
1576 }
1577 }
1578 self.expect_punct("]")?;
1579 self.leave();
1580 Ok(Expr::Array(items))
1581 }
1582
1583 fn object_literal(&mut self) -> Result<Expr, String> {
1584 self.enter()?;
1585 let mut entries = Vec::new();
1586 while !self.eof() && !self.is_punct("}") {
1587 if self.eat_punct("...") {
1588 entries.push(ObjectEntry::Spread(self.assignment_expression()?));
1589 } else {
1590 let accessor = (self.is_ident("get") || self.is_ident("set"))
1591 && !self.peek_n_punct(1, "(")
1592 && !self.peek_n_punct(1, ":")
1593 && !self.peek_n_punct(1, ",")
1594 && !self.peek_n_punct(1, "}");
1595 let mut getter = false;
1596 let mut setter = false;
1597 if accessor {
1598 getter = self.is_ident("get");
1599 setter = !getter;
1600 self.bump();
1601 }
1602 if self.eat_punct("[") {
1603 let key = self.expression()?;
1604 self.expect_punct("]")?;
1605 if self.eat_punct(":") {
1606 entries.push(ObjectEntry::Computed(key, self.assignment_expression()?));
1607 } else if self.is_punct("(") {
1608 let fun = self.method_function(None)?;
1609 entries.push(ObjectEntry::Computed(key, Expr::Function(fun)));
1610 } else {
1611 return Err(self.error_here("invalid computed object property"));
1612 }
1613 } else {
1614 let name = self.property_name()?;
1615 if self.eat_punct(":") {
1616 entries.push(ObjectEntry::Property(name, self.assignment_expression()?));
1617 } else if self.is_punct("(") {
1618 let fun = self.method_function(Some(name.clone()))?;
1619 if getter {
1620 entries.push(ObjectEntry::Getter(name, fun));
1621 } else if setter {
1622 entries.push(ObjectEntry::Setter(name, fun));
1623 } else {
1624 entries.push(ObjectEntry::Method(name, fun));
1625 }
1626 } else {
1627 if getter || setter {
1628 return Err(self.error_here("accessor must have a method body"));
1629 }
1630 entries.push(ObjectEntry::Property(name.clone(), Expr::Ident(name)));
1631 }
1632 }
1633 }
1634 if !self.eat_punct(",") {
1635 break;
1636 }
1637 }
1638 self.expect_punct("}")?;
1639 self.leave();
1640 Ok(Expr::Object(entries))
1641 }
1642
1643 fn pattern(&mut self) -> Result<Pattern, String> {
1644 self.enter()?;
1645 let mut pattern = if self.eat_punct("...") {
1646 Pattern::Rest(Box::new(self.pattern()?))
1647 } else if self.eat_punct("[") {
1648 let mut items = Vec::new();
1649 while !self.eof() && !self.is_punct("]") {
1650 if self.eat_punct(",") {
1651 items.push(None);
1652 continue;
1653 }
1654 items.push(Some(self.pattern()?));
1655 if !self.eat_punct(",") {
1656 break;
1657 }
1658 }
1659 self.expect_punct("]")?;
1660 Pattern::Array(items)
1661 } else if self.eat_punct("{") {
1662 let mut fields = Vec::new();
1663 while !self.eof() && !self.is_punct("}") {
1664 if self.eat_punct("...") {
1665 fields.push((
1666 String::from("..."),
1667 Pattern::Rest(Box::new(self.pattern()?)),
1668 ));
1669 if !self.eat_punct(",") {
1670 break;
1671 }
1672 continue;
1673 }
1674 let key = self.property_name()?;
1675 let value = if self.eat_punct(":") {
1676 self.pattern()?
1677 } else {
1678 Pattern::Ident(key.clone())
1679 };
1680 fields.push((key, value));
1681 if !self.eat_punct(",") {
1682 break;
1683 }
1684 }
1685 self.expect_punct("}")?;
1686 Pattern::Object(fields)
1687 } else {
1688 Pattern::Ident(self.expect_identifier_name()?)
1689 };
1690 if self.eat_punct("=") {
1691 pattern = Pattern::Default(Box::new(pattern), Box::new(self.assignment_expression()?));
1692 }
1693 self.leave();
1694 Ok(pattern)
1695 }
1696
1697 fn property_name(&mut self) -> Result<String, String> {
1698 match self.bump().kind.clone() {
1699 Kind::Ident(name) => Ok(name),
1700 Kind::String(units) => Ok(String::from_utf16_lossy(&units)),
1701 Kind::Number(number) => Ok(number.to_string()),
1702 Kind::Punct(p) if p == "[" => {
1703 Err(self.error_previous("computed name requires expression context"))
1704 }
1705 _ => Err(self.error_previous("expected property name")),
1706 }
1707 }
1708
1709 fn binary_op(&self) -> Option<(String, u8, bool)> {
1710 let op = self.punct_text()?;
1711 let item = match op {
1712 "||" => (1, false),
1713 "??" => (1, false),
1714 "&&" => (2, false),
1715 "|" => (3, false),
1716 "^" => (4, false),
1717 "&" => (5, false),
1718 "==" | "!=" | "===" | "!==" => (6, false),
1719 "<" | ">" | "<=" | ">=" => (7, false),
1720 "in" if self.allow_in => (7, false),
1721 "instanceof" => (7, false),
1722 "<<" | ">>" | ">>>" => (8, false),
1723 "+" | "-" => (9, false),
1724 "*" | "/" | "%" => (10, false),
1725 "**" => (11, true),
1726 _ => return None,
1727 };
1728 Some((op.to_owned(), item.0, item.1))
1729 }
1730
1731 fn assignment_operator(&self) -> Option<String> {
1732 let op = self.punct_text()?;
1733 if [
1734 "=", "+=", "-=", "*=", "/=", "%=", "&=", "|=", "^=", "<<=", ">>=", ">>>=", "**=",
1735 "&&=", "||=", "??=",
1736 ]
1737 .contains(&op)
1738 {
1739 Some(op.to_owned())
1740 } else {
1741 None
1742 }
1743 }
1744
1745 fn semicolon(&mut self) -> Result<(), String> {
1746 if self.eat_punct(";") || self.eof() || self.is_punct("}") || self.line_break_before() {
1747 Ok(())
1748 } else {
1749 Err(self.error_here("expected semicolon"))
1750 }
1751 }
1752
1753 fn enter(&mut self) -> Result<(), String> {
1754 self.nesting += 1;
1755 if self.nesting > MAX_NESTING {
1756 return Err(self.error_here("nesting limit exceeded"));
1757 }
1758 Ok(())
1759 }
1760 fn leave(&mut self) {
1761 self.nesting = self.nesting.saturating_sub(1);
1762 }
1763
1764 fn current(&self) -> &Token {
1765 &self.tokens[self.pos.min(self.tokens.len() - 1)]
1766 }
1767 fn bump(&mut self) -> &Token {
1768 let p = self.pos;
1769 if !self.eof() {
1770 self.pos += 1;
1771 }
1772 &self.tokens[p]
1773 }
1774 fn eof(&self) -> bool {
1775 matches!(self.current().kind, Kind::Eof)
1776 }
1777 fn is_punct(&self, p: &str) -> bool {
1778 matches!(&self.current().kind, Kind::Punct(s) if s == p)
1779 }
1780 fn eat_punct(&mut self, p: &str) -> bool {
1781 if self.is_punct(p) {
1782 self.bump();
1783 true
1784 } else {
1785 false
1786 }
1787 }
1788 fn expect_punct(&mut self, p: &str) -> Result<(), String> {
1789 if self.eat_punct(p) {
1790 Ok(())
1791 } else {
1792 Err(self.error_here(&format!("expected '{p}'")))
1793 }
1794 }
1795 fn is_ident(&self, name: &str) -> bool {
1796 matches!(&self.current().kind, Kind::Ident(s) if s == name)
1797 }
1798 fn eat_ident(&mut self, name: &str) -> bool {
1799 if self.is_ident(name) {
1800 self.bump();
1801 true
1802 } else {
1803 false
1804 }
1805 }
1806 fn expect_ident(&mut self, name: &str) -> Result<(), String> {
1807 if self.eat_ident(name) {
1808 Ok(())
1809 } else {
1810 Err(self.error_here(&format!("expected {name}")))
1811 }
1812 }
1813 fn is_identifier_name(&self) -> bool {
1814 matches!(self.current().kind, Kind::Ident(_))
1815 || matches!(&self.current().kind, Kind::Punct(p) if p == "default")
1816 }
1817 fn expect_identifier_name(&mut self) -> Result<String, String> {
1818 match self.bump().kind.clone() {
1819 Kind::Ident(name) => Ok(name),
1820 _ => Err(self.error_previous("expected identifier")),
1821 }
1822 }
1823 fn line_break_before(&self) -> bool {
1824 self.current().line_break_before
1825 }
1826 fn peek_n_linebreak(&self, n: usize) -> bool {
1827 self.tokens
1828 .get(self.pos + n)
1829 .is_some_and(|t| t.line_break_before)
1830 }
1831 fn peek_n_punct(&self, n: usize, p: &str) -> bool {
1832 matches!(self.tokens.get(self.pos + n).map(|t| &t.kind), Some(Kind::Punct(s)) if s == p)
1833 }
1834 fn punct_text(&self) -> Option<&str> {
1835 match &self.current().kind {
1836 Kind::Punct(s) => Some(s),
1837 Kind::Ident(s) if s == "in" || s == "instanceof" => Some(s),
1838 _ => None,
1839 }
1840 }
1841 fn previous_text(&self) -> String {
1842 match &self.tokens[self.pos.saturating_sub(1)].kind {
1843 Kind::Punct(s) | Kind::Ident(s) => s.clone(),
1844 _ => String::new(),
1845 }
1846 }
1847 fn previous_is_ident(&self, name: &str) -> bool {
1848 matches!(&self.tokens[self.pos.saturating_sub(1)].kind, Kind::Ident(s) if s == name)
1849 }
1850 fn error_here(&self, message: &str) -> String {
1851 self.error_at(self.current().at, message)
1852 }
1853 fn error_previous(&self, message: &str) -> String {
1854 self.error_at(self.tokens[self.pos.saturating_sub(1)].at, message)
1855 }
1856 fn error_at(&self, at: usize, message: &str) -> String {
1857 located_error(self.source, at, message)
1858 }
1859 fn location(&self, at: usize) -> String {
1860 let e = located_error(self.source, at, "");
1861 e.trim_end_matches(": ").to_owned()
1862 }
1863}
1864
1865fn is_assignable(expr: &Expr) -> bool {
1866 match expr {
1867 Expr::Ident(_) | Expr::Member(_, _) => true,
1868 Expr::Array(items) => items.iter().flatten().all(is_assignable),
1869 Expr::Object(entries) => entries.iter().all(|entry| match entry {
1870 ObjectEntry::Property(_, value) => is_assignable(value),
1871 ObjectEntry::Computed(_, value) => is_assignable(value),
1872 ObjectEntry::Spread(value) => is_assignable(value),
1873 _ => false,
1874 }),
1875 _ => false,
1876 }
1877}
1878
1879fn expr_to_pattern(expr: Expr) -> Result<Pattern, String> {
1880 match expr {
1881 Expr::Ident(name) => Ok(Pattern::Ident(name)),
1882 Expr::Array(items) => Ok(Pattern::Array(
1883 items
1884 .into_iter()
1885 .map(|item| item.map(expr_to_pattern).transpose())
1886 .collect::<Result<Vec<_>, _>>()?,
1887 )),
1888 Expr::Object(entries) => {
1889 let mut fields = Vec::new();
1890 for entry in entries {
1891 match entry {
1892 ObjectEntry::Property(name, value) => {
1893 fields.push((name, expr_to_pattern(value)?))
1894 }
1895 _ => {
1896 return Err(String::from(
1897 "SyntaxError at 1:1: unsupported object assignment pattern",
1898 ));
1899 }
1900 }
1901 }
1902 Ok(Pattern::Object(fields))
1903 }
1904 Expr::Assign(_, left, right) => {
1905 Ok(Pattern::Default(Box::new(expr_to_pattern(*left)?), right))
1906 }
1907 Expr::Spread(value) => Ok(Pattern::Rest(Box::new(expr_to_pattern(*value)?))),
1908 _ => Err(String::from("SyntaxError at 1:1: invalid binding pattern")),
1909 }
1910}
1911
1912pub fn parse(source: &str) -> Result<Vec<Stmt>, String> {
1913 Parser::new(source)?.parse_program()
1914}