Skip to main content

meta_language/translation/lexer/
literals.rs

1// Literal token readers share the lexer namespace through include!.
2// The shared generated decision owns decimal/exponent/suffix boundaries.
3#[allow(
4    clippy::cast_precision_loss,
5    clippy::cast_possible_truncation,
6    clippy::cast_sign_loss
7)]
8fn rust_number(source: &Source, index: usize, units: &mut Option<Vec<f64>>) -> Result<Token> {
9    let encoded =
10        units.get_or_insert_with(|| source.units().iter().map(|unit| f64::from(*unit)).collect());
11    let bounds = read_rust_number_bounds(encoded, index as f64);
12    let end = bounds[0] as usize;
13    let suffix = bounds[1] as usize;
14    let floating = bounds[2] > 0.0;
15    let raw = source.slice(index, end);
16    let digits = source.slice(index, suffix);
17    if !source_whitespace::accept_rust_source_number_digit_boundary(
18        floating,
19        digits.ends_with('_'),
20        &source.slice(suffix, end),
21        is_identifier_part(source.at(end), Language::Rust),
22        source.at(end).map_or(-1.0, f64::from),
23    ) {
24        return Err(TranslationError::syntax(
25            format!("malformed number {raw}"),
26            Some(span(index, end)),
27        ));
28    }
29    let numeric = digits.replace('_', "");
30    let value = if floating {
31        let number = numeric.parse::<f64>().map_err(|_| {
32            TranslationError::syntax(format!("malformed number {raw}"), Some(span(index, end)))
33        })?;
34        if !number.is_finite() {
35            return Err(TranslationError::syntax(
36                format!("floating-point literal out of range {raw}"),
37                Some(span(index, end)),
38            ));
39        }
40        super::js_number::js_number(number)
41    } else {
42        numeric
43    };
44    let mut token = Token::new(TokenKind::Number, value, raw, index, end);
45    token.suffix = source.slice(suffix, end);
46    token.floating = floating;
47    Ok(token)
48}
49
50fn javascript_number_regex() -> &'static Regex {
51    static NUMBER: OnceLock<Regex> = OnceLock::new();
52    NUMBER.get_or_init(|| {
53        let run = |digit: &str| format!("{digit}(?:_?{digit})*");
54        let decimal = run("[0-9]");
55        Regex::new(&format!(
56            r"^(?:0[xX]{}|0[oO]{}|0[bB]{}|(?:(?:0|[1-9](?:_?{decimal})?)(?:\.(?:{decimal})?)?|\.{decimal})(?:[eE][+-]?{decimal})?)n?",
57            run("[0-9a-fA-F]"),
58            run("[0-7]"),
59            run("[01]"),
60        ))
61        .expect("JavaScript numeric literal")
62    })
63}
64
65/// An ECMAScript numeric literal. A `BigInt` (`5n`, `0x1fn`) keeps its decimal
66/// digits as `value` with suffix `n`; a Number keeps `String(Number(raw))`, the
67/// value JavaScript prints, with an empty suffix.
68fn javascript_number(source: &Source, index: usize) -> Result<Token> {
69    let rest = source.slice(index, source.len());
70    let found = javascript_number_regex().find(&rest);
71    let raw = found.map_or_else(|| source.slice(index, index + 1), |m| m.as_str().to_owned());
72    let end = index + raw.len();
73    let next = source.char_at(end);
74    let malformed = || {
75        let stop = if end < source.len() { end + 1 } else { end };
76        TranslationError::syntax(
77            format!("malformed number {}", source.slice(index, stop)),
78            Some(span(index, stop)),
79        )
80    };
81    // `08`, `1_`, `3in` and `1.5n` are SyntaxErrors in JavaScript.
82    if found.is_none()
83        || next.is_some_and(|ch| ch.is_ascii_alphanumeric() || ch == '_' || ch == '$')
84    {
85        return Err(malformed());
86    }
87    let text = raw.replace('_', "");
88    let token = if let Some(digits) = text.strip_suffix('n') {
89        let hex = digits.starts_with("0x") || digits.starts_with("0X");
90        if !hex && digits.contains(['.', 'e', 'E']) {
91            return Err(malformed());
92        }
93        let value = Decimal::parse(digits).ok_or_else(malformed)?;
94        let mut token = Token::new(TokenKind::Number, value.digits, raw, index, end);
95        token.suffix = String::from("n");
96        token
97    } else {
98        let value = js_number_literal(&text).ok_or_else(malformed)?;
99        Token::new(TokenKind::Number, value, raw, index, end)
100    };
101    Ok(token)
102}
103
104fn block_comment_end(source: &Source, index: usize, comments: &CommentSyntax) -> Result<usize> {
105    let open = comments.open.encode_utf16().count();
106    let close = comments.close.encode_utf16().count();
107    let mut depth = 0usize;
108    let mut cursor = index;
109    while cursor < source.len() {
110        if source.starts_with(comments.open, cursor) {
111            depth += 1;
112            cursor += open;
113            if !comments.nested && depth > 1 {
114                depth = 1;
115            }
116            continue;
117        }
118        if source.starts_with(comments.close, cursor) {
119            // A close before any open (impossible from `tokenize`) would go negative in JavaScript.
120            depth = depth.saturating_sub(1);
121            cursor += close;
122            if depth == 0 {
123                return Ok(cursor);
124            }
125            continue;
126        }
127        cursor += 1;
128    }
129    Err(TranslationError::syntax(
130        "unterminated block comment",
131        Some(span(index, source.len())),
132    ))
133}
134
135fn read_unicode_escape(
136    source: &Source,
137    cursor: usize,
138    language: Language,
139    units: &mut Option<Vec<f64>>,
140) -> Result<(char, usize)> {
141    let escape = if language == Language::Rust {
142        let encoded = units
143            .get_or_insert_with(|| source.units().iter().map(|unit| f64::from(*unit)).collect());
144        let start = serde_json::Number::from(cursor)
145            .as_f64()
146            .expect("UTF-16 source offset");
147        unicode_escapes::decode_rust_unicode_escape(encoded, start)
148    } else {
149        let encoded = source.units()[cursor..source.len().min(cursor + 12)]
150            .iter()
151            .map(|unit| f64::from(*unit))
152            .collect();
153        decode_unicode_escape(encoded, language == Language::JavaScript)
154    };
155    match escape {
156        UnicodeEscape::Scalar(code, end) => {
157            // The generated decoder returns integral scalar values and
158            // relative offsets inside the original source or generic window.
159            #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
160            let character = char::from_u32(code as u32).expect("decoded Unicode scalar");
161            #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
162            Ok((character, end as usize))
163        }
164        UnicodeEscape::Malformed => Err(TranslationError::syntax(
165            "malformed unicode escape",
166            Some(span(cursor, cursor + 2)),
167        )),
168        UnicodeEscape::Unsupported(end, escape_length) => {
169            #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
170            let (end, escape_length) = (end as usize, escape_length as usize);
171            Err(TranslationError::new(
172                ErrorKind::Unsupported,
173                format!(
174                    "unicode escape {} is not a scalar value; Rust strings hold scalar values only",
175                    source.slice(cursor, cursor + escape_length)
176                ),
177                Some(span(cursor, cursor + end)),
178            ))
179        }
180    }
181}
182
183fn raw_string_token(
184    source: &Source,
185    index: usize,
186    units: &mut Option<Vec<f64>>,
187) -> Result<Option<Token>> {
188    let encoded =
189        units.get_or_insert_with(|| source.units().iter().map(|unit| f64::from(*unit)).collect());
190    let start = serde_json::Number::from(index)
191        .as_f64()
192        .expect("UTF-16 source offset");
193    match raw_strings::decode_rust_raw_string(encoded, start) {
194        raw_strings::RustRawString::NotRaw => Ok(None),
195        raw_strings::RustRawString::Literal(content_start, content_end, end) => {
196            let mut cursor = super::frontend_rules::ml_array::number_index(content_start)
197                .expect("decoded raw string content start");
198            let content_end = super::frontend_rules::ml_array::number_index(content_end)
199                .expect("decoded raw string content end");
200            let end =
201                super::frontend_rules::ml_array::number_index(end).expect("decoded raw string end");
202            let mut value = Vec::new();
203            while cursor < content_end {
204                let start = serde_json::Number::from(cursor)
205                    .as_f64()
206                    .expect("UTF-16 source offset");
207                let (unit, end) = super::frontend_rules::ml_array::number_index(
208                    read_rust_source_line_break_end(encoded, start),
209                )
210                .map_or((source.units[cursor], cursor + 1), |end| {
211                    (u16::from(b'\n'), end)
212                });
213                value.push(unit);
214                cursor = end;
215            }
216            // The generated reader has checked every original scalar; retain
217            // those UTF-16 units while normalizing only its admitted CRLFs.
218            Ok(Some(Token::new(
219                TokenKind::String,
220                String::from_utf16_lossy(&value),
221                source.slice(index, end),
222                index,
223                end,
224            )))
225        }
226        raw_strings::RustRawString::TooManyDelimiters => Err(TranslationError::syntax(
227            "Rust raw string exceeds 255 delimiter hashes",
228            Some(span(index, source.len())),
229        )),
230        raw_strings::RustRawString::CarriageReturn(at) => {
231            let at = super::frontend_rules::ml_array::number_index(at)
232                .expect("decoded raw string carriage return offset");
233            Err(TranslationError::syntax(
234                "isolated carriage return in a Rust string",
235                Some(span(at, at + 1)),
236            ))
237        }
238        raw_strings::RustRawString::NonScalar(at) => {
239            let at = super::frontend_rules::ml_array::number_index(at)
240                .expect("decoded raw string nonscalar offset");
241            Err(TranslationError::syntax(
242                "unpaired Unicode surrogate in a Rust raw string",
243                Some(span(at, at + 1)),
244            ))
245        }
246        raw_strings::RustRawString::Unterminated => Err(TranslationError::syntax(
247            "unterminated Rust raw string literal",
248            Some(span(index, source.len())),
249        )),
250    }
251}
252
253// Thin host projection of the actual automatically emitted result enum.
254// Recorded source parameter loans borrow the original unit vector as &[f64].
255fn rust_character_token(
256    source: &Source,
257    index: usize,
258    units: &mut Option<Vec<f64>>,
259) -> Result<Option<Token>> {
260    use super::rust_character_rules::RustCharacterLiteral;
261
262    let encoded =
263        units.get_or_insert_with(|| source.units().iter().map(|unit| f64::from(*unit)).collect());
264    let start = serde_json::Number::from(index)
265        .as_f64()
266        .expect("UTF-16 source offset");
267    let position = |value| {
268        super::frontend_rules::ml_array::number_index(value)
269            .expect("generated character token source offset")
270    };
271    let (kind, value, end) =
272        match super::rust_character_rules::decode_rust_character_literal(encoded, start) {
273            RustCharacterLiteral::NotCharacter => return Ok(None),
274            RustCharacterLiteral::Char(value, _, _, end) => (TokenKind::Character, value, end),
275            RustCharacterLiteral::ByteChar(value, _, _, end) => {
276                (TokenKind::ByteCharacter, value, end)
277            }
278            RustCharacterLiteral::Malformed(at, end) => {
279                return Err(TranslationError::syntax(
280                    "malformed Rust character literal",
281                    Some(span(position(at), position(end))),
282                ));
283            }
284            RustCharacterLiteral::Unterminated(at, end) => {
285                return Err(TranslationError::syntax(
286                    "unterminated Rust character literal",
287                    Some(span(position(at), position(end))),
288                ));
289            }
290            RustCharacterLiteral::NonScalar(at, end) => {
291                return Err(TranslationError::new(
292                    ErrorKind::Unsupported,
293                    "Rust character literal is not a Unicode scalar value",
294                    Some(span(position(at), position(end))),
295                ));
296            }
297            RustCharacterLiteral::NonAscii(at, end) => {
298                return Err(TranslationError::syntax(
299                    "non-ASCII source in a Rust byte character literal",
300                    Some(span(position(at), position(end))),
301                ));
302            }
303            RustCharacterLiteral::UnicodeByteEscape(at, end) => {
304                return Err(TranslationError::syntax(
305                    "Unicode escape in a Rust byte character literal",
306                    Some(span(position(at), position(end))),
307                ));
308            }
309            RustCharacterLiteral::UnsupportedSuffix(at, end) => {
310                return Err(TranslationError::new(
311                    ErrorKind::Unsupported,
312                    "Rust character literal suffix is outside the supported lexical profile",
313                    Some(span(position(at), position(end))),
314                ));
315            }
316        };
317    let end = position(end);
318    Ok(Some(Token::new(
319        kind,
320        super::js_number::js_number(value),
321        source.slice(index, end),
322        index,
323        end,
324    )))
325}
326
327fn string_token(
328    source: &Source,
329    index: usize,
330    language: Language,
331    units: &mut Option<Vec<f64>>,
332) -> Result<Token> {
333    let quote = source.units[index];
334    let mut cursor = index + 1;
335    let mut value: Vec<u16> = Vec::new();
336    while cursor < source.len() {
337        let unit = source.units[cursor];
338        if unit == quote {
339            if language == Language::Rocq && source.is_char(cursor + 1, '"') {
340                value.push(u16::from(b'"'));
341                cursor += 2;
342                continue;
343            }
344            let mut token = Token::new(
345                TokenKind::String,
346                String::from_utf16_lossy(&value),
347                source.slice(index, cursor + 1),
348                index,
349                cursor + 1,
350            );
351            token.raw = source.slice(index, cursor + 1);
352            return Ok(token);
353        }
354        if unit == u16::from(b'\\') && language != Language::Rocq {
355            let escaped = source.char_at(cursor + 1);
356            if language == Language::Rust {
357                let encoded = units.get_or_insert_with(|| {
358                    source.units().iter().map(|unit| f64::from(*unit)).collect()
359                });
360                let start = serde_json::Number::from(cursor)
361                    .as_f64()
362                    .expect("UTF-16 source offset");
363                if let Some(end) = super::frontend_rules::ml_array::number_index(
364                    read_rust_string_continuation_end(encoded, start),
365                ) {
366                    cursor = end;
367                    continue;
368                }
369                if !cooked_strings::accept_rust_cooked_string_escape_prefix(
370                    encoded.get(cursor + 1).copied().unwrap_or(-1.0),
371                ) {
372                    return Err(TranslationError::syntax(
373                        format!(
374                            "unsupported string escape \\{}",
375                            escaped_text(source, cursor + 1)
376                        ),
377                        Some(span(cursor, cursor + 2)),
378                    ));
379                }
380                if escaped == Some('x') {
381                    let code = cooked_strings::read_rust_ascii_escape_value(
382                        encoded.get(cursor + 2).copied().unwrap_or(-1.0),
383                        encoded.get(cursor + 3).copied().unwrap_or(-1.0),
384                    );
385                    let character = super::frontend_rules::ml_array::number_index(code)
386                        .and_then(|code| u32::try_from(code).ok())
387                        .and_then(char::from_u32)
388                        .ok_or_else(|| {
389                            TranslationError::syntax(
390                                "malformed Rust ASCII escape",
391                                Some(span(cursor, cursor + 2)),
392                            )
393                        })?;
394                    let mut encoded = [0; 2];
395                    value.extend_from_slice(character.encode_utf16(&mut encoded));
396                    cursor += 4;
397                    continue;
398                }
399            }
400            if escaped == Some('u') || (language == Language::JavaScript && escaped == Some('x')) {
401                let (character, end) = read_unicode_escape(source, cursor, language, units)?;
402                let mut encoded = [0; 2];
403                value.extend_from_slice(character.encode_utf16(&mut encoded));
404                cursor += end;
405                continue;
406            }
407            if language == Language::JavaScript {
408                if escaped.is_some_and(|character| matches!(character, '1'..='9'))
409                    || (escaped == Some('0')
410                        && source
411                            .char_at(cursor + 2)
412                            .is_some_and(|character| character.is_ascii_digit()))
413                {
414                    return Err(TranslationError::syntax(
415                        "legacy octal string escape",
416                        Some(span(cursor, cursor + 2)),
417                    ));
418                }
419                if matches!(escaped, Some('\n' | '\r' | '\u{2028}' | '\u{2029}')) {
420                    cursor += if escaped == Some('\r') && source.is_char(cursor + 2, '\n') {
421                        3
422                    } else {
423                        2
424                    };
425                    continue;
426                }
427            }
428            let replacement = match escaped {
429                Some('n') => "\n",
430                Some('t') => "\t",
431                Some('r') => "\r",
432                Some('\\') => "\\",
433                Some('"') => "\"",
434                Some('\'') => "'",
435                Some('0') => "\0",
436                Some('{') if language == Language::JavaScript => "{",
437                Some('{') => "\\{",
438                Some('b') if language == Language::JavaScript => "\u{0008}",
439                Some('f') if language == Language::JavaScript => "\u{000c}",
440                Some('v') if language == Language::JavaScript => "\u{000b}",
441                Some(_) if language == Language::JavaScript => {
442                    value.push(source.units[cursor + 1]);
443                    cursor += 2;
444                    continue;
445                }
446                _ => {
447                    return Err(TranslationError::syntax(
448                        format!(
449                            "unsupported string escape \\{}",
450                            escaped_text(source, cursor + 1)
451                        ),
452                        Some(span(cursor, cursor + 2)),
453                    ));
454                }
455            };
456            value.extend(replacement.encode_utf16());
457            cursor += 2;
458            continue;
459        }
460        if language == Language::Rust && unit == u16::from(b'\r') {
461            let encoded = units.get_or_insert_with(|| {
462                source.units().iter().map(|unit| f64::from(*unit)).collect()
463            });
464            let start = serde_json::Number::from(cursor)
465                .as_f64()
466                .expect("UTF-16 source offset");
467            if let Some(end) = super::frontend_rules::ml_array::number_index(
468                read_rust_source_line_break_end(encoded, start),
469            ) {
470                value.push(u16::from(b'\n'));
471                cursor = end;
472                continue;
473            }
474            return Err(TranslationError::syntax(
475                "isolated carriage return in a Rust string",
476                Some(span(cursor, cursor + 1)),
477            ));
478        }
479        if (unit == u16::from(b'\n') || unit == u16::from(b'\r'))
480            && language == Language::JavaScript
481        {
482            break;
483        }
484        value.push(unit);
485        cursor += 1;
486    }
487    Err(TranslationError::syntax(
488        "unterminated string literal",
489        Some(span(index, source.len())),
490    ))
491}
492
493fn template_token(source: &Source, index: usize, units: &mut Option<Vec<f64>>) -> Result<Token> {
494    let mut parts = Vec::new();
495    let mut cursor = index + 1;
496    let mut text: Vec<u16> = Vec::new();
497    while cursor < source.len() {
498        let unit = source.units[cursor];
499        if unit == u16::from(b'`') {
500            parts.push(TemplatePart {
501                text: String::from_utf16_lossy(&text),
502                expression: None,
503            });
504            let raw = source.slice(index, cursor + 1);
505            let mut token = Token::new(TokenKind::Template, String::new(), raw, index, cursor + 1);
506            token.parts = parts;
507            return Ok(token);
508        }
509        if unit == u16::from(b'\\') {
510            if matches!(source.char_at(cursor + 1), Some('u' | 'x')) {
511                let (character, end) =
512                    read_unicode_escape(source, cursor, Language::JavaScript, units)?;
513                let mut encoded = [0; 2];
514                text.extend_from_slice(character.encode_utf16(&mut encoded));
515                cursor += end;
516                continue;
517            }
518            if source
519                .char_at(cursor + 1)
520                .is_some_and(|character| matches!(character, '1'..='9'))
521                || (source.char_at(cursor + 1) == Some('0')
522                    && source
523                        .char_at(cursor + 2)
524                        .is_some_and(|character| character.is_ascii_digit()))
525            {
526                return Err(TranslationError::syntax(
527                    "legacy octal template escape",
528                    Some(span(cursor, cursor + 3)),
529                ));
530            }
531            if matches!(
532                source.char_at(cursor + 1),
533                Some('\n' | '\r' | '\u{2028}' | '\u{2029}')
534            ) {
535                cursor += if source.is_char(cursor + 1, '\r') && source.is_char(cursor + 2, '\n') {
536                    3
537                } else {
538                    2
539                };
540                continue;
541            }
542            let replacement = match source.char_at(cursor + 1) {
543                Some('n') => '\n',
544                Some('t') => '\t',
545                Some('r') => '\r',
546                Some('b') => '\u{0008}',
547                Some('f') => '\u{000c}',
548                Some('v') => '\u{000b}',
549                Some('0') => '\0',
550                Some('\\') => '\\',
551                Some('`') => '`',
552                Some('$') => '$',
553                Some(character) => character,
554                None => {
555                    return Err(TranslationError::syntax(
556                        format!(
557                            "unsupported template escape \\{}",
558                            escaped_text(source, cursor + 1)
559                        ),
560                        Some(span(cursor, cursor + 2)),
561                    ));
562                }
563            };
564            text.push(replacement as u16);
565            cursor += 2;
566            continue;
567        }
568        if unit == u16::from(b'\r') {
569            text.push(u16::from(b'\n'));
570            cursor += if source.is_char(cursor + 1, '\n') {
571                2
572            } else {
573                1
574            };
575            continue;
576        }
577        if source.starts_with("${", cursor) {
578            let close = interpolation_boundary(source, cursor + 1, units)?;
579            parts.push(TemplatePart {
580                text: String::from_utf16_lossy(&text),
581                expression: Some(TemplateExpression {
582                    source: source.slice(cursor + 2, close),
583                    offset: cursor + 2,
584                }),
585            });
586            text.clear();
587            cursor = close + 1;
588            continue;
589        }
590        text.push(unit);
591        cursor += 1;
592    }
593    Err(TranslationError::syntax(
594        "unterminated template literal",
595        Some(span(index, source.len())),
596    ))
597}
598
599/// The escaped unit as JavaScript interpolates it (`undefined` past the end).
600fn escaped_text(source: &Source, index: usize) -> String {
601    if index < source.len() {
602        source.slice(index, index + 1)
603    } else {
604        "undefined".to_owned()
605    }
606}
607
608/// The index of the `}` closing the `{` at `open`.
609///
610/// # Errors
611///
612/// Returns a syntax error when the braces are unbalanced.
613pub fn matching_brace(source: &Source, open: usize) -> Result<usize> {
614    interpolation_boundary(source, open, &mut None)
615}
616
617fn interpolation_boundary(
618    source: &Source,
619    open: usize,
620    units: &mut Option<Vec<f64>>,
621) -> Result<usize> {
622    let tokens = tokenize_region(source, Language::JavaScript, open + 1, true, units)?;
623    let close = tokens.tokens.last().expect("end token").end;
624    if close < source.len() {
625        return Ok(close);
626    }
627    Err(TranslationError::syntax(
628        "unbalanced braces",
629        Some(span(open, source.len())),
630    ))
631}
632
633/// Cursor over a token list with the helpers every frontend needs.
634#[derive(Clone, Debug)]
635pub struct TokenCursor {
636    pub tokens: Vec<Token>,
637    pub language: Language,
638    pub index: usize,
639}
640
641impl TokenCursor {
642    #[must_use]
643    pub const fn new(tokens: Vec<Token>, language: Language) -> Self {
644        Self {
645            tokens,
646            language,
647            index: 0,
648        }
649    }
650
651    #[must_use]
652    pub fn peek(&self) -> &Token {
653        self.peek_at(0)
654    }
655
656    #[must_use]
657    pub fn peek_at(&self, offset: usize) -> &Token {
658        &self.tokens[(self.index + offset).min(self.tokens.len() - 1)]
659    }
660
661    pub fn advance(&mut self) -> Token {
662        let token = self.peek().clone();
663        if token.kind != TokenKind::Eof {
664            self.index += 1;
665        }
666        token
667    }
668
669    #[must_use]
670    pub fn is(&self, value: &str) -> bool {
671        self.is_at(value, 0)
672    }
673
674    #[must_use]
675    pub fn is_at(&self, value: &str, offset: usize) -> bool {
676        let token = self.peek_at(offset);
677        matches!(token.kind, TokenKind::Punct | TokenKind::Identifier) && token.value == value
678    }
679
680    #[must_use]
681    pub fn is_kind(&self, kind: TokenKind) -> bool {
682        self.peek().kind == kind
683    }
684
685    #[must_use]
686    pub fn is_kind_at(&self, kind: TokenKind, offset: usize) -> bool {
687        self.peek_at(offset).kind == kind
688    }
689
690    pub fn eat(&mut self, value: &str) -> Option<Token> {
691        if self.is(value) {
692            Some(self.advance())
693        } else {
694            None
695        }
696    }
697
698    /// Consumes `value`.
699    ///
700    /// # Errors
701    ///
702    /// Returns a syntax error naming the token found instead.
703    pub fn expect(&mut self, value: &str, context: Option<&str>) -> Result<Token> {
704        if self.is(value) {
705            return Ok(self.advance());
706        }
707        let token = self.peek();
708        Err(TranslationError::syntax(
709            format!(
710                "expected {value}{} but found {}",
711                context.map_or_else(String::new, |context| format!(" in {context}")),
712                describe(token)
713            ),
714            Some(token.span()),
715        ))
716    }
717
718    /// Consumes an identifier.
719    ///
720    /// # Errors
721    ///
722    /// Returns a syntax error naming the token found instead.
723    pub fn identifier(&mut self, context: Option<&str>) -> Result<Token> {
724        let token = self.peek();
725        if token.kind != TokenKind::Identifier {
726            return Err(TranslationError::syntax(
727                format!(
728                    "expected identifier{} but found {}",
729                    context.map_or_else(String::new, |context| format!(" in {context}")),
730                    describe(token)
731                ),
732                Some(token.span()),
733            ));
734        }
735        Ok(self.advance())
736    }
737
738    #[must_use]
739    pub fn at_end(&self) -> bool {
740        self.peek().kind == TokenKind::Eof
741    }
742}