SPB Git

Repository Public

lib.rs 25.5 KB 750 lines rust

1//! ORIX Sonata2//! File: crates/sonata-lexer/src/lib.rs3//! Description: Sonata lexer: UTF-8 source to tokens with spans, comments kept as trivia.4//!5//! Author: Simon-Pierre Boucher6//! Contact: contact@spboucher.ai78use serde::Serialize;9use sonata_ir::{Diagnostic, FileId, Span};1011/// Largest accepted source, in bytes (4 MiB).12pub const MAX_SOURCE_BYTES: usize = 4 * 1024 * 1024;1314/// Unit suffix glued to a number literal.15#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize)]16pub enum UnitSuffix {17    Bpm,18    Hz,19    KHz,20    Db,21    Ms,22    S,23    St,24    Cents,25    Percent,26    Bars,27    Beats,28    Deg,29}3031impl UnitSuffix {32    pub const ALL: [(&'static str, UnitSuffix); 14] = [33        ("bpm", UnitSuffix::Bpm),34        ("Hz", UnitSuffix::Hz),35        ("kHz", UnitSuffix::KHz),36        ("dB", UnitSuffix::Db),37        ("ms", UnitSuffix::Ms),38        ("s", UnitSuffix::S),39        ("st", UnitSuffix::St),40        ("cents", UnitSuffix::Cents),41        ("%", UnitSuffix::Percent),42        ("bars", UnitSuffix::Bars),43        ("bar", UnitSuffix::Bars),44        ("beats", UnitSuffix::Beats),45        ("beat", UnitSuffix::Beats),46        ("deg", UnitSuffix::Deg),47    ];4849    pub fn parse(text: &str) -> Option<UnitSuffix> {50        Self::ALL.iter().find(|(s, _)| *s == text).map(|(_, u)| *u)51    }5253    /// Canonical spelling used by the formatter.54    pub fn as_str(self) -> &'static str {55        match self {56            UnitSuffix::Bpm => "bpm",57            UnitSuffix::Hz => "Hz",58            UnitSuffix::KHz => "kHz",59            UnitSuffix::Db => "dB",60            UnitSuffix::Ms => "ms",61            UnitSuffix::S => "s",62            UnitSuffix::St => "st",63            UnitSuffix::Cents => "cents",64            UnitSuffix::Percent => "%",65            UnitSuffix::Bars => "bars",66            UnitSuffix::Beats => "beats",67            UnitSuffix::Deg => "deg",68        }69    }70}7172/// Numeric literal value: integers stay exact.73#[derive(Clone, Copy, Debug, PartialEq, Serialize)]74pub enum NumLit {75    Int(i64),76    Float(f64),77}7879/// A note literal as written (`F#4`): letter 0 = C … 6 = B, accidental in semitones, octave.80#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize)]81pub struct NoteLit {82    pub letter: u8,83    pub accidental: i8,84    pub octave: i8,85}8687const LETTER_SEMITONES: [i32; 7] = [0, 2, 4, 5, 7, 9, 11];8889impl NoteLit {90    /// MIDI number (`C4` = 60, `A4` = 69). May fall outside 0..=127 for extreme spellings.91    pub fn midi(self) -> i32 {92        (self.octave as i32 + 1) * 12 + LETTER_SEMITONES[self.letter as usize % 7] + self.accidental as i3293    }94}9596/// A pitch-class literal as written (`Bb`).97#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize)]98pub struct PitchClassLit {99    pub letter: u8,100    pub accidental: i8,101}102103impl PitchClassLit {104    pub fn pitch_class(self) -> u8 {105        (LETTER_SEMITONES[self.letter as usize % 7] + self.accidental as i32).rem_euclid(12) as u8106    }107}108109/// Letter index (0 = C … 6 = B) of an ASCII note letter.110pub fn letter_index(c: u8) -> Option<u8> {111    match c {112        b'C' => Some(0),113        b'D' => Some(1),114        b'E' => Some(2),115        b'F' => Some(3),116        b'G' => Some(4),117        b'A' => Some(5),118        b'B' => Some(6),119        _ => None,120    }121}122123pub const LETTER_NAMES: [char; 7] = ['C', 'D', 'E', 'F', 'G', 'A', 'B'];124125#[derive(Clone, Debug, PartialEq)]126pub enum TokenKind {127    Ident(String),128    Number { value: NumLit, unit: Option<UnitSuffix> },129    Str(String),130    Note(NoteLit),131    PitchClass(PitchClassLit),132    LParen,133    RParen,134    LBrace,135    RBrace,136    LBracket,137    RBracket,138    Comma,139    Colon,140    Semi,141    Dot,142    DotDot,143    DotDotEq,144    Arrow,145    Assign,146    EqEq,147    NotEq,148    Lt,149    Le,150    Gt,151    Ge,152    Plus,153    Minus,154    Star,155    Slash,156    Percent,157    Eof,158}159160impl TokenKind {161    /// Human description used in "expected X, found Y" messages.162    pub fn describe(&self) -> String {163        match self {164            TokenKind::Ident(s) => format!("'{s}'"),165            TokenKind::Number { .. } => "a number".into(),166            TokenKind::Str(_) => "a string".into(),167            TokenKind::Note(_) => "a note".into(),168            TokenKind::PitchClass(_) => "a pitch class".into(),169            TokenKind::Eof => "end of file".into(),170            other => format!("'{}'", other.punct().unwrap_or("?")),171        }172    }173174    pub fn punct(&self) -> Option<&'static str> {175        Some(match self {176            TokenKind::LParen => "(",177            TokenKind::RParen => ")",178            TokenKind::LBrace => "{",179            TokenKind::RBrace => "}",180            TokenKind::LBracket => "[",181            TokenKind::RBracket => "]",182            TokenKind::Comma => ",",183            TokenKind::Colon => ":",184            TokenKind::Semi => ";",185            TokenKind::Dot => ".",186            TokenKind::DotDot => "..",187            TokenKind::DotDotEq => "..=",188            TokenKind::Arrow => "->",189            TokenKind::Assign => "=",190            TokenKind::EqEq => "==",191            TokenKind::NotEq => "!=",192            TokenKind::Lt => "<",193            TokenKind::Le => "<=",194            TokenKind::Gt => ">",195            TokenKind::Ge => ">=",196            TokenKind::Plus => "+",197            TokenKind::Minus => "-",198            TokenKind::Star => "*",199            TokenKind::Slash => "/",200            TokenKind::Percent => "%",201            _ => return None,202        })203    }204}205206#[derive(Clone, Debug, PartialEq)]207pub struct Token {208    pub kind: TokenKind,209    pub span: Span,210    /// True when at least one line break separates this token from the previous one.211    pub nl_before: bool,212}213214/// A comment, kept outside the token stream for the formatter.215#[derive(Clone, Debug, PartialEq, Eq)]216pub struct Comment {217    pub span: Span,218    /// Full text including the `//` or `/* */` delimiters.219    pub text: String,220    pub block: bool,221    /// True when the comment is the first thing on its line.222    pub own_line: bool,223}224225#[derive(Clone, Debug, Default)]226pub struct Lexed {227    /// Always ends with exactly one `Eof` token.228    pub tokens: Vec<Token>,229    pub comments: Vec<Comment>,230    pub diagnostics: Vec<Diagnostic>,231}232233/// Words that can never be identifiers.234pub const KEYWORDS: &[&str] = &[235    "import",236    "const",237    "let",238    "fn",239    "pattern",240    "instrument",241    "composition",242    "if",243    "then",244    "else",245    "for",246    "in",247    "repeat",248    "return",249    "true",250    "false",251    "and",252    "or",253    "not",254    "play",255    "chord",256    "rest",257    "sequence",258    "voice",259    "parallel",260    "at",261    "tuplet",262    "transpose",263    "swing",264    "tempo",265    "signature",266    "key",267    "seed",268    "tuning",269    "master",270    "bus",271    "audio",272    "clip",273    "marker",274    "effects",275    "automate",276    "graph",277    "node",278    "out",279    "model",280    "preset",281    "send",282    "default",283    "sonata",284];285286pub fn is_keyword(word: &str) -> bool {287    KEYWORDS.contains(&word)288}289290fn is_ident_start(c: u8) -> bool {291    c.is_ascii_alphabetic() || c == b'_'292}293fn is_ident_continue(c: u8) -> bool {294    c.is_ascii_alphanumeric() || c == b'_'295}296297/// Lexes arbitrary bytes. Invalid UTF-8 is reported (L0008) and replaced lossily, so the lexer298/// never fails and never panics.299pub fn lex_bytes(bytes: &[u8], file: FileId) -> (String, Lexed) {300    match std::str::from_utf8(bytes) {301        Ok(s) => (s.to_string(), lex(s, file)),302        Err(e) => {303            let text = String::from_utf8_lossy(bytes).into_owned();304            let mut lexed = lex(&text, file);305            let at = e.valid_up_to() as u32;306            lexed.diagnostics.insert(0, Diagnostic::error("L0008", Span::new(file, at, at + 1), "the source is not valid UTF-8"));307            (text, lexed)308        }309    }310}311312/// Lexes a source text. Never panics; every problem becomes a diagnostic and lexing continues.313pub fn lex(src: &str, file: FileId) -> Lexed {314    let mut out = Lexed::default();315    if src.len() > MAX_SOURCE_BYTES {316        out.diagnostics.push(Diagnostic::error(317            "L0007",318            Span::new(file, 0, 0),319            format!("the source is {} bytes; the limit is {} bytes", src.len(), MAX_SOURCE_BYTES),320        ));321        out.tokens.push(Token { kind: TokenKind::Eof, span: Span::new(file, 0, 0), nl_before: false });322        return out;323    }324    let b = src.as_bytes();325    let n = b.len();326    let mut i = 0usize;327    let mut nl = false;328    let mut line_has_token = false;329    let sp = |s: usize, e: usize| Span::new(file, s as u32, e as u32);330    while i < n {331        let c = b[i];332        match c {333            b'\n' => {334                nl = true;335                line_has_token = false;336                i += 1;337                continue;338            }339            b' ' | b'\t' | b'\r' => {340                i += 1;341                continue;342            }343            b'/' if i + 1 < n && b[i + 1] == b'/' => {344                let s = i;345                while i < n && b[i] != b'\n' {346                    i += 1;347                }348                out.comments.push(Comment { span: sp(s, i), text: src[s..i].trim_end().to_string(), block: false, own_line: !line_has_token });349                continue;350            }351            b'/' if i + 1 < n && b[i + 1] == b'*' => {352                let s = i;353                let own_line = !line_has_token;354                let mut depth = 1usize;355                i += 2;356                while i < n && depth > 0 {357                    if b[i] == b'/' && i + 1 < n && b[i + 1] == b'*' {358                        depth += 1;359                        i += 2;360                    } else if b[i] == b'*' && i + 1 < n && b[i + 1] == b'/' {361                        depth -= 1;362                        i += 2;363                    } else {364                        if b[i] == b'\n' {365                            nl = true;366                            line_has_token = false;367                        }368                        i += 1;369                    }370                }371                if depth > 0 {372                    out.diagnostics.push(Diagnostic::error("L0003", sp(s, (s + 2).min(n)), "this block comment is never closed").with_suggestion("add */"));373                }374                out.comments.push(Comment { span: sp(s, i), text: src[s..i].to_string(), block: true, own_line });375                continue;376            }377            _ => {}378        }379        let start = i;380        let kind = if c == b'"' {381            i += 1;382            let mut value = String::new();383            let mut closed = false;384            while i < n {385                match b[i] {386                    b'"' => {387                        i += 1;388                        closed = true;389                        break;390                    }391                    b'\n' => break,392                    b'\\' => {393                        let esc_start = i;394                        i += 1;395                        if i >= n {396                            break;397                        }398                        match b[i] {399                            b'n' => {400                                value.push('\n');401                                i += 1;402                            }403                            b't' => {404                                value.push('\t');405                                i += 1;406                            }407                            b'"' => {408                                value.push('"');409                                i += 1;410                            }411                            b'\\' => {412                                value.push('\\');413                                i += 1;414                            }415                            b'u' if i + 1 < n && b[i + 1] == b'{' => {416                                let mut j = i + 2;417                                while j < n && b[j].is_ascii_hexdigit() && j - (i + 2) < 6 {418                                    j += 1;419                                }420                                let ok = j < n && b[j] == b'}' && j > i + 2;421                                let ch = if ok { u32::from_str_radix(&src[i + 2..j], 16).ok().and_then(char::from_u32) } else { None };422                                match ch {423                                    Some(ch) => {424                                        value.push(ch);425                                        i = j + 1;426                                    }427                                    None => {428                                        out.diagnostics.push(429                                            Diagnostic::error("L0005", sp(esc_start, (i + 1).min(n)), "invalid unicode escape")430                                                .with_suggestion("write \\u{1F3B5} with 1 to 6 hexadecimal digits"),431                                        );432                                        i += 1;433                                    }434                                }435                            }436                            _ => {437                                // Advance over one whole character so we stay on a char boundary.438                                let ch_len = src[i..].chars().next().map(|ch| ch.len_utf8()).unwrap_or(1);439                                out.diagnostics.push(440                                    Diagnostic::error("L0005", sp(esc_start, i + ch_len), "unknown escape sequence")441                                        .with_suggestion("valid escapes are \\n \\t \\\" \\\\ \\u{HEX}"),442                                );443                                i += ch_len;444                            }445                        }446                    }447                    _ => {448                        let ch = src[i..].chars().next().unwrap_or(' ');449                        value.push(ch);450                        i += ch.len_utf8();451                    }452                }453            }454            if !closed {455                out.diagnostics.push(Diagnostic::error("L0002", sp(start, i), "this string is never closed").with_fix("close the string", sp(i, i), "\""));456            }457            TokenKind::Str(value)458        } else if c.is_ascii_digit() {459            while i < n && (b[i].is_ascii_digit() || b[i] == b'_') {460                i += 1;461            }462            let mut is_float = false;463            if i + 1 < n && b[i] == b'.' && b[i + 1].is_ascii_digit() {464                is_float = true;465                i += 1;466                while i < n && (b[i].is_ascii_digit() || b[i] == b'_') {467                    i += 1;468                }469            }470            let digits: String = src[start..i].chars().filter(|ch| *ch != '_').collect();471            let value = if is_float {472                NumLit::Float(digits.parse::<f64>().unwrap_or(0.0))473            } else {474                match digits.parse::<i64>() {475                    Ok(v) => NumLit::Int(v),476                    Err(_) => {477                        out.diagnostics.push(Diagnostic::error("L0006", sp(start, i), "this integer does not fit in 64 bits"));478                        NumLit::Int(0)479                    }480                }481            };482            let mut unit = None;483            if i < n && b[i] == b'%' {484                unit = Some(UnitSuffix::Percent);485                i += 1;486            } else if i < n && is_ident_start(b[i]) {487                let us = i;488                while i < n && is_ident_continue(b[i]) {489                    i += 1;490                }491                let word = &src[us..i];492                match UnitSuffix::parse(word) {493                    Some(u) => unit = Some(u),494                    None => {495                        let mut d = Diagnostic::error("L0004", sp(us, i), format!("unknown unit '{word}'"));496                        let lower = word.to_ascii_lowercase();497                        if let Some((good, _)) = UnitSuffix::ALL.iter().find(|(s, _)| s.to_ascii_lowercase() == lower) {498                            d = d.with_suggestion(format!("did you mean '{good}'?")).with_fix(format!("write '{good}'"), sp(us, i), *good);499                        } else {500                            d = d.with_suggestion("units are bpm, Hz, kHz, dB, ms, s, st, cents, %, bars, beats, deg; put a space before an identifier");501                        }502                        out.diagnostics.push(d);503                    }504                }505            }506            TokenKind::Number { value, unit }507        } else if is_ident_start(c) {508            // Note and pitch-class shapes win over identifiers.509            if let Some(tok) = lex_note(b, &mut i) {510                tok511            } else {512                while i < n && is_ident_continue(b[i]) {513                    i += 1;514                }515                TokenKind::Ident(src[start..i].to_string())516            }517        } else {518            let two = if i + 1 < n { Some((c, b[i + 1])) } else { None };519            let three = i + 2 < n && c == b'.' && b[i + 1] == b'.' && b[i + 2] == b'=';520            let (kind, len) = if three {521                (Some(TokenKind::DotDotEq), 3)522            } else {523                match two {524                    Some((b'.', b'.')) => (Some(TokenKind::DotDot), 2),525                    Some((b'-', b'>')) => (Some(TokenKind::Arrow), 2),526                    Some((b'=', b'=')) => (Some(TokenKind::EqEq), 2),527                    Some((b'!', b'=')) => (Some(TokenKind::NotEq), 2),528                    Some((b'<', b'=')) => (Some(TokenKind::Le), 2),529                    Some((b'>', b'=')) => (Some(TokenKind::Ge), 2),530                    _ => (531                        match c {532                            b'(' => Some(TokenKind::LParen),533                            b')' => Some(TokenKind::RParen),534                            b'{' => Some(TokenKind::LBrace),535                            b'}' => Some(TokenKind::RBrace),536                            b'[' => Some(TokenKind::LBracket),537                            b']' => Some(TokenKind::RBracket),538                            b',' => Some(TokenKind::Comma),539                            b':' => Some(TokenKind::Colon),540                            b';' => Some(TokenKind::Semi),541                            b'.' => Some(TokenKind::Dot),542                            b'=' => Some(TokenKind::Assign),543                            b'<' => Some(TokenKind::Lt),544                            b'>' => Some(TokenKind::Gt),545                            b'+' => Some(TokenKind::Plus),546                            b'-' => Some(TokenKind::Minus),547                            b'*' => Some(TokenKind::Star),548                            b'/' => Some(TokenKind::Slash),549                            b'%' => Some(TokenKind::Percent),550                            _ => None,551                        },552                        1,553                    ),554                }555            };556            match kind {557                Some(k) => {558                    i += len;559                    k560                }561                None => {562                    let ch = src[i..].chars().next().unwrap_or(' ');563                    i += ch.len_utf8().max(1);564                    // One diagnostic per run of unexpected characters keeps noise bounded.565                    let adjacent = out.diagnostics.last().map(|d| d.code == "L0001" && d.span.end as usize == start).unwrap_or(false);566                    if adjacent {567                        if let Some(d) = out.diagnostics.last_mut() {568                            d.span.end = i as u32;569                        }570                    } else {571                        out.diagnostics.push(Diagnostic::error("L0001", sp(start, i), format!("unexpected character '{}'", ch.escape_default())));572                    }573                    continue;574                }575            }576        };577        out.tokens.push(Token { kind, span: sp(start, i), nl_before: nl });578        nl = false;579        line_has_token = true;580    }581    out.tokens.push(Token { kind: TokenKind::Eof, span: sp(n, n), nl_before: nl });582    out583}584585/// Tries to read a note (`F#4`, `Bb-1`) or pitch-class (`F#`, `Bb`, `C`) literal at `*i`.586fn lex_note(b: &[u8], i: &mut usize) -> Option<TokenKind> {587    let n = b.len();588    let letter = letter_index(b[*i])?;589    let mut j = *i + 1;590    // Accidentals: ##, #, bb, b.591    let acc_candidates: [(&[u8], i8); 5] = [(b"##", 2), (b"#", 1), (b"bb", -2), (b"b", -1), (b"", 0)];592    for (text, acc) in acc_candidates {593        if b[j.min(n)..].starts_with(text) {594            let mut k = j + text.len();595            let octave = if k + 1 < n && b[k] == b'-' && b[k + 1] == b'1' {596                k += 2;597                Some(-1i8)598            } else if k < n && b[k].is_ascii_digit() {599                k += 1;600                Some((b[k - 1] - b'0') as i8)601            } else {602                None603            };604            if let Some(octave) = octave {605                if k >= n || !is_ident_continue(b[k]) {606                    *i = k;607                    return Some(TokenKind::Note(NoteLit { letter, accidental: acc, octave }));608                }609            }610        }611    }612    // Pitch class: letter with at most one accidental, not followed by an identifier character.613    let acc = if j < n && b[j] == b'#' {614        j += 1;615        1616    } else if j < n && b[j] == b'b' && (j + 1 >= n || !is_ident_continue(b[j + 1])) {617        j += 1;618        -1619    } else {620        0621    };622    if j >= n || !is_ident_continue(b[j]) {623        *i = j;624        return Some(TokenKind::PitchClass(PitchClassLit { letter, accidental: acc }));625    }626    None627}628629#[cfg(test)]630mod tests {631    use super::*;632633    fn kinds(src: &str) -> Vec<TokenKind> {634        let l = lex(src, 0);635        assert!(l.diagnostics.is_empty(), "{:?}", l.diagnostics);636        l.tokens.into_iter().map(|t| t.kind).collect()637    }638639    fn num(v: i64, u: Option<UnitSuffix>) -> TokenKind {640        TokenKind::Number { value: NumLit::Int(v), unit: u }641    }642643    #[test]644    fn numbers_and_units() {645        assert_eq!(kinds("120bpm -8dB 48000Hz 2kHz 5ms 2s 1/4 60% 3bars 1bar 2beats 25cents 7st 48_000 90deg"), {646            use UnitSuffix::*;647            vec![648                num(120, Some(Bpm)),649                TokenKind::Minus,650                num(8, Some(Db)),651                num(48000, Some(Hz)),652                num(2, Some(KHz)),653                num(5, Some(Ms)),654                num(2, Some(S)),655                num(1, None),656                TokenKind::Slash,657                num(4, None),658                num(60, Some(Percent)),659                num(3, Some(Bars)),660                num(1, Some(Bars)),661                num(2, Some(Beats)),662                num(25, Some(Cents)),663                num(7, Some(St)),664                num(48000, None),665                num(90, Some(Deg)),666                TokenKind::Eof,667            ]668        });669        assert_eq!(kinds("0.75 0..4 1..=3")[0], TokenKind::Number { value: NumLit::Float(0.75), unit: None });670        assert_eq!(kinds("0..4")[1], TokenKind::DotDot);671        assert_eq!(kinds("1..=3")[1], TokenKind::DotDotEq);672    }673674    #[test]675    fn notes_pitch_classes_and_identifiers() {676        let k = kinds("D3 F#4 Bb2 C-1 Abb3 C##5 D Bb F# Amp Bbx Db_1 delay Cmaj a4 B");677        let note = |l, a, o| TokenKind::Note(NoteLit { letter: l, accidental: a, octave: o });678        let pc = |l, a| TokenKind::PitchClass(PitchClassLit { letter: l, accidental: a });679        let id = |s: &str| TokenKind::Ident(s.into());680        assert_eq!(681            k,682            vec![683                note(1, 0, 3),684                note(3, 1, 4),685                note(6, -1, 2),686                note(0, 0, -1),687                note(5, -2, 3),688                note(0, 2, 5),689                pc(1, 0),690                pc(6, -1),691                pc(3, 1),692                id("Amp"),693                id("Bbx"),694                id("Db_1"),695                id("delay"),696                id("Cmaj"),697                id("a4"),698                pc(6, 0),699                TokenKind::Eof700            ]701        );702        assert_eq!(NoteLit { letter: 0, accidental: 0, octave: 4 }.midi(), 60);703        assert_eq!(NoteLit { letter: 5, accidental: 0, octave: 4 }.midi(), 69);704        assert_eq!(NoteLit { letter: 0, accidental: 0, octave: -1 }.midi(), 0);705        assert_eq!(PitchClassLit { letter: 6, accidental: -1 }.pitch_class(), 10);706    }707708    #[test]709    fn strings_comments_and_newlines() {710        let l = lex("// head\nplay \"a\\n\\\"b\\u{1F3B5}\" /* x /* nested */ y */ rest // tail\n;", 0);711        assert!(l.diagnostics.is_empty());712        assert_eq!(l.comments.len(), 3);713        assert!(l.comments[0].own_line && !l.comments[1].own_line && !l.comments[2].own_line);714        assert_eq!(l.tokens[1].kind, TokenKind::Str("a\n\"b🎵".into()));715        assert!(l.tokens[0].nl_before);716        assert!(!l.tokens[2].nl_before);717        assert!(l.tokens[3].nl_before);718    }719720    #[test]721    fn errors_are_reported_and_lexing_continues() {722        let l = lex("play 12BPM \"open\nrest @@@ 1/4 /* never", 0);723        let codes: Vec<&str> = l.diagnostics.iter().map(|d| d.code.as_str()).collect();724        assert_eq!(codes, vec!["L0004", "L0002", "L0001", "L0003"]);725        assert!(l.diagnostics[0].fix.is_some());726        assert!(matches!(l.tokens.last().unwrap().kind, TokenKind::Eof));727        let big = "9".repeat(40);728        assert_eq!(lex(&big, 0).diagnostics[0].code, "L0006");729        let (_, l) = lex_bytes(&[b'a', 0xff, b'b'], 0);730        assert_eq!(l.diagnostics[0].code, "L0008");731        assert_eq!(lex("\"\\q é\"", 0).diagnostics[0].code, "L0005");732    }733734    #[test]735    fn never_panics_on_arbitrary_bytes() {736        let mut state = 0x9E3779B97F4A7C15u64;737        for _ in 0..2000 {738            let mut bytes = Vec::new();739            for _ in 0..64 {740                state ^= state << 13;741                state ^= state >> 7;742                state ^= state << 17;743                bytes.push((state >> 24) as u8);744            }745            let (_, l) = lex_bytes(&bytes, 0);746            assert!(matches!(l.tokens.last().unwrap().kind, TokenKind::Eof));747        }748    }749}750
Files main
Menu

Theme