Skip to main content

bynk_syntax/
lexer.rs

1//! Lexer for Bynk v0.
2//!
3//! Token kinds correspond to the terminals defined in the grammar (spec §3
4//! and §4). Whitespace is skipped; `//` line comments are emitted as `Comment`
5//! tokens so the formatter can preserve them through round-trips (v1.1 LSP
6//! spec §3.5). Doc blocks (`---`) are emitted as `DocBlock` tokens, and
7//! one-line docs (`--- text`, #2203) as `DocLine` tokens, both lexed outside
8//! of logos (see [`tokenize`]).
9//!
10//! #2203: the legacy spellings, a `--` comment and a `--|` doc line, still lex
11//! as `Comment` and `DocLine` tokens, so every tool keeps working on an
12//! unmigrated file and the formatter can rewrite it. The parser reports each
13//! as an error with a machine-applicable fix ([`legacy_comment_error`],
14//! [`legacy_doc_line_error`]); [`comment_is_legacy`] and
15//! [`doc_line_is_legacy`] tell the spellings apart.
16
17use logos::Logos;
18
19use crate::error::{Applicability, CompileError};
20use crate::span::{FileId, Span};
21
22/// #1657: the largest `Int`, `Number.MAX_SAFE_INTEGER` (2^53 − 1). An `Int`
23/// is a JS safe integer; the range is symmetric.
24pub const MAX_SAFE_INT: i64 = 9_007_199_254_740_991;
25
26/// v0.142 (ADR 0166): strip `_` digit separators from a numeric literal's lexeme
27/// before it is parsed into a value. The lexer's `IntLit`/`FloatLit` regexes only
28/// admit an `_` between two digit groups, so removing every `_` yields a plain
29/// digit string; the separators are purely visual. Allocates only when the
30/// literal actually carries a separator (the common case does not).
31pub(crate) fn strip_digit_separators(lexeme: &str) -> std::borrow::Cow<'_, str> {
32    if lexeme.as_bytes().contains(&b'_') {
33        std::borrow::Cow::Owned(lexeme.replace('_', ""))
34    } else {
35        std::borrow::Cow::Borrowed(lexeme)
36    }
37}
38
39/// Token kinds. Discriminants without payload data; the lexeme is recovered
40/// from the source string via the token's [`Span`].
41///
42/// Note: `--` line comments and `---` doc block markers are handled outside
43/// logos (see [`tokenize`]), because doc blocks are delimited by `---` lines
44/// containing only the marker and may span multiple source lines.
45#[derive(Logos, Debug, Clone, Copy, PartialEq, Eq)]
46#[logos(skip r"[ \t\r\n]+")]
47pub enum TokenKind {
48    // Keywords
49    #[token("commons")]
50    Commons,
51    #[token("type")]
52    Type,
53    // Events track, slice 0 (spine #936): `event Name = { fields }` — a
54    // context-only item declaring a typed fact. RESERVED_CONTEXTUAL, not
55    // hard, per ADR 0272's `messages` postmortem (a hard keyword broke the
56    // dotted-name case its own worked example used); `event` is at least as
57    // likely a parameter/local name (`on event(event: T)`).
58    #[token("event")]
59    Event,
60    // #1883 (static assets), slice 1a: `asset name = "path"` — a context or
61    // commons item declaring one static file the platform serves.
62    // RESERVED_CONTEXTUAL, not hard, for the same reason as `event` (ADR
63    // 0272's `messages` postmortem): `asset` is a likely local or segment name.
64    #[token("asset")]
65    Asset,
66    // #2387 (embedded text), slice 1: `embed name = "path"` — a context or
67    // commons item whose value is a project file's text. RESERVED_CONTEXTUAL,
68    // for the same reason as `asset`: `embed` is a likely local name.
69    #[token("embed")]
70    Embed,
71    // #2617 (named constants): `const Name: Type = <static expression>` — a
72    // context or commons item naming a value. RESERVED_CONTEXTUAL, for the
73    // same reason as `embed`: `const` is a plausible local or field name, and
74    // it was a free identifier before this keyword existed.
75    #[token("const")]
76    Const,
77    #[token("fn")]
78    Fn,
79    #[token("where")]
80    Where,
81    // #548: the `and` keyword was retired — refinement predicates now join with
82    // `&&` (the one conjunction spelling). `and` is a free identifier again.
83    #[token("true")]
84    True,
85    #[token("false")]
86    False,
87    #[token("Int")]
88    Int,
89    #[token("String")]
90    String,
91    #[token("Bool")]
92    Bool,
93    // v0.21 keyword
94    #[token("Float")]
95    Float,
96    // v0.86 keyword (ADR 0112): the `Duration` base type.
97    #[token("Duration")]
98    Duration,
99    // v0.90 keyword (ADR 0114): the `Instant` base type.
100    #[token("Instant")]
101    Instant,
102    // v0.110 keyword (ADR 0142): the `Bytes` base type.
103    #[token("Bytes")]
104    Bytes,
105    // ADR (#2622): the `Decimal` base type.
106    #[token("Decimal")]
107    Decimal,
108    // v0.1 keywords
109    #[token("let")]
110    Let,
111    #[token("if")]
112    If,
113    #[token("else")]
114    Else,
115    #[token("Ok")]
116    Ok,
117    #[token("Err")]
118    Err,
119    #[token("Result")]
120    Result,
121    #[token("ValidationError")]
122    ValidationError,
123    // v0.22b keyword (renamed from `JsonError`, ADR 0047 → the DecodeError rename)
124    #[token("DecodeError")]
125    DecodeError,
126    // The deprecated spelling of `DecodeError`: still lexed (and still reserved,
127    // so no program can declare a type of that name), parsed to the same type,
128    // and reported as a warning with an auto-fix by the parser.
129    #[token("JsonError")]
130    JsonErrorDeprecated,
131    // v0.2 keywords
132    #[token("enum")]
133    Enum,
134    #[token("match")]
135    Match,
136    #[token("Option")]
137    Option,
138    #[token("record")]
139    Record,
140    #[token("self")]
141    Self_,
142    #[token("Some")]
143    Some,
144    #[token("None")]
145    None,
146    #[token("is")]
147    Is,
148    // v0.3 keywords
149    #[token("opaque")]
150    Opaque,
151    #[token("uses")]
152    Uses,
153    // v0.4 keywords
154    #[token("context")]
155    Context,
156    #[token("consumes")]
157    Consumes,
158    #[token("exports")]
159    Exports,
160    #[token("transparent")]
161    Transparent,
162    // v0.6 keywords
163    #[token("as")]
164    As,
165    // v0.7 keywords (v0.112: `assert`→`expect`, `test`→`suite`/`case`;
166    // v0.118: `mocks` retired — test doubles are stubs at a seam; the stub form
167    // moved off the punned `provides` keyword to its own `stub` keyword in the
168    // keyword-hygiene batch, #548)
169    #[token("expect")]
170    Expect,
171    #[token("suite")]
172    Suite,
173    #[token("case")]
174    Case,
175    // Keyword-hygiene batch (#548): the test-scope stub `stub Cap.op(…) <rhs>`,
176    // formerly the third pun on `provides`. `provides` now heads only a provider
177    // declaration / external provider.
178    #[token("stub")]
179    Stub,
180    // v0.114 keyword — generative tests (testing track slice 2). `for` and `all`
181    // are deliberately *not* keywords: `all` is a list combinator (`all(xs, p)`)
182    // and must stay a usable identifier. The `for all` binder is parsed
183    // contextually (two identifiers) inside a `property` body instead.
184    #[token("property")]
185    Property,
186    // v0.17 keywords
187    #[token("adapter")]
188    Adapter,
189    #[token("binding")]
190    Binding,
191    // v0.5 keywords
192    #[token("agent")]
193    Agent,
194    #[token("capability")]
195    Capability,
196    #[token("Effect")]
197    Effect,
198    // v0.146 keyword (ADR 0170): `do e` — an effect-performing expression
199    // statement (the binder-free `let _ <- e` for a unit effect).
200    #[token("do")]
201    Do,
202    #[token("given")]
203    Given,
204    #[token("on")]
205    On,
206    // v0.9 keyword
207    #[token("http")]
208    Http,
209    // v0.10a keyword
210    #[token("cron")]
211    Cron,
212    // v0.10b keyword
213    #[token("queue")]
214    Queue,
215    // v0.44 keywords: `from` heads a service's protocol clause; `protocol` is
216    // reserved (protocols are a closed, compiler-known set — no declaration kind).
217    #[token("from")]
218    From,
219    #[token("protocol")]
220    Protocol,
221    #[token("provides")]
222    Provides,
223    #[token("service")]
224    Service,
225    // v0.45 keywords: `actor` heads a boundary-contract declaration. (`by`,
226    // which heads a handler's actor clause, is contextual since #3191: it lexes
227    // as an `Ident` and the parser reads it by text in its clause positions.)
228    #[token("actor")]
229    Actor,
230    // v0.80 keywords: `invariant` heads an agent invariant declaration; `implies`
231    // is the directional logical-implication operator (`P implies Q` ≡ `!P || Q`).
232    #[token("invariant")]
233    Invariant,
234    #[token("implies")]
235    Implies,
236    // v0.115 keywords — function contracts (testing track slice 3). `requires`
237    // and `ensures` head a contract clause on a `fn` signature (between the
238    // return type and the body). `result` is deliberately *not* a keyword: it is
239    // the ordinary value name outside a contract, so it stays a usable
240    // identifier; inside an `ensures` predicate it is bound contextually as the
241    // function's return value (parsed by scope, like `for`/`all` in slice 2).
242    // Distinct from ADR 0127's capability `@requires` annotation.
243    #[token("requires")]
244    Requires,
245    #[token("ensures")]
246    Ensures,
247    // v0.116 keyword — step invariants (testing track slice 4). `transition` heads
248    // an agent step-invariant declaration (beside `invariant`), a predicate over
249    // the pre- and post-commit state pair. `old` and `new` are deliberately *not*
250    // keywords: they stay ordinary value names outside a `transition`, and inside a
251    // `transition` predicate they are bound contextually to the old/new state
252    // records (parsed by scope, like `result` in an `ensures`).
253    #[token("transition")]
254    Transition,
255    // message-bundles track, slice 1: `messages <tag> { "code" => "template" }`
256    // — a commons item declaring one locale's message bundle.
257    #[token("messages")]
258    Messages,
259    /// `...` — used in record-spread expressions (v0.5).
260    #[token("...")]
261    DotDotDot,
262    /// `..` — the "rest of the fields" marker on an events subscription
263    /// pattern (Events track slice 1, spine #936): `from Events(E { region:
264    /// Region.Domestic, .. })`. A genuine token, not two adjacent `Dot`s —
265    /// logos maximal-munches `...`/`..`/`.` correctly once all three are
266    /// registered, and a real token keeps this in agreement with
267    /// tree-sitter's grammar (which declares `".."` as one literal), so the
268    /// two parsers cannot diverge on a whitespace-split `. .` the way ADR
269    /// 0253 D4 found a leaking `where`-check divergence once before.
270    #[token("..")]
271    DotDot,
272    /// `<-` — Effect bind operator (v0.5).
273    #[token("<-")]
274    LArrow,
275    /// `~>` — the removed fire-and-forget send marker (v0.79; removed in favour
276    /// of `e.detach()`, #3443). Still lexed, and only so that the parser can
277    /// refuse it with `bynk.parse.removed_send_arrow` instead of a generic
278    /// "unexpected character" error. No production accepts it.
279    #[token("~>")]
280    TildeArrow,
281    /// `:=` — Cell write (v0.81, storage track). A handler statement
282    /// `cell := expr`; distinct from `=` (binding) and `:` (annotation). Longer
283    /// than `:`/`=` so logos matches it as one token.
284    #[token(":=")]
285    ColonEq,
286
287    /// A documentation block: `---` line ... `---` line. The token's span
288    /// covers the full block including both `---` markers. The body content
289    /// is recovered from the source via the span (see [`doc_block_content`]).
290    /// Inserted by [`tokenize`]; not lexed by logos directly.
291    DocBlock,
292
293    /// #2203: the one-line doc form, `--- text`: a marker of three or more
294    /// dashes, at least one space or tab, then text, first on its line
295    /// (indentation aside). An optional closer, a final run of exactly the
296    /// opener's dashes preceded by whitespace, is not part of the doc. A
297    /// marker alone on its line is a [`TokenKind::DocBlock`] fence instead.
298    /// Like [`TokenKind::DocBlock`], the span runs from the marker through the
299    /// terminating newline (or EOF), so the parser's blank-line check treats
300    /// both forms alike ([`doc_line_text`] recovers the text). The legacy
301    /// `--| text` spelling (#1888) lexes as this token too, and the parser
302    /// reports it ([`doc_line_is_legacy`]). Inserted by [`tokenize`].
303    DocLine,
304
305    /// A line comment: `// ...` running to end of line, anywhere (#2203). The
306    /// span starts at the `//` marker and runs through the last character
307    /// before the terminating newline (exclusive). The trivia body (the text
308    /// after the marker) is recovered from the source via the span
309    /// ([`comment_body`]). The legacy `-- ...` spelling lexes as this token
310    /// too, and the parser reports it ([`comment_is_legacy`]). Inserted by
311    /// [`tokenize`]; not lexed by logos directly.
312    Comment,
313
314    // Identifier
315    #[regex(r"[A-Za-z][A-Za-z0-9_]*")]
316    Ident,
317
318    // Literals. v0.142 (ADR 0166): an `_` digit separator may appear between
319    // digits (`1_048_576`) — never leading, trailing, or doubled (each `_` must
320    // sit between two digit groups). The separators are stripped before the value
321    // is parsed; they are purely visual.
322    #[regex(r"[0-9]+(_[0-9]+)*")]
323    IntLit,
324    // A float literal: fraction with a digit on both sides of the `.`, an
325    // exponent, or both (v0.21 §3). `1.` and `.5` are NOT float literals —
326    // the digit-both-sides rule keeps `2.5.round()` / `1.toFloat()` lexing
327    // as method calls on numeric literals. Digit separators (v0.142) may appear
328    // in any digit group, including the exponent.
329    #[regex(
330        r"[0-9]+(_[0-9]+)*\.[0-9]+(_[0-9]+)*([eE][+-]?[0-9]+(_[0-9]+)*)?|[0-9]+(_[0-9]+)*[eE][+-]?[0-9]+(_[0-9]+)*"
331    )]
332    FloatLit,
333    // A decimal literal (#2622): an integer or fraction with a trailing `d`
334    // (`1.20d`, `5d`). The as-written scale is the number of fraction digits.
335    // No exponent form. Digit separators may appear in either group.
336    #[regex(r"[0-9]+(_[0-9]+)*(\.[0-9]+(_[0-9]+)*)?d")]
337    DecimalLit,
338    // A string literal with no interpolation hole: `"…"`, the raw forms
339    // `r"…"` / `r#"…"#`, and the multi-line forms `"""…"""` / `r"""…"""`
340    // (#2619). Hand-scanned in `tokenize` (never produced by logos) so one
341    // scanner owns every form; the span covers the whole lexeme and
342    // [`decode_string_literal`] recovers the value.
343    StrLit,
344    // An interpolated string `"… \(expr) …"` (v0.43). Hand-scanned in
345    // `tokenize` (logos cannot balance the holes' parens), never produced by
346    // the logos lexer — like [`TokenKind::DocBlock`]/[`TokenKind::Comment`].
347    // The span covers the whole `"…"`; the parser splits chunks from holes.
348    InterpStr,
349
350    // Multi-char operators
351    #[token("->")]
352    Arrow,
353    #[token("==")]
354    EqEq,
355    #[token("!=")]
356    BangEq,
357    #[token("<=")]
358    LtEq,
359    #[token(">=")]
360    GtEq,
361    #[token("&&")]
362    AmpAmp,
363    #[token("||")]
364    PipePipe,
365
366    // Single-char operators
367    #[token("+")]
368    Plus,
369    #[token("-")]
370    Minus,
371    #[token("*")]
372    Star,
373    #[token("/")]
374    Slash,
375    /// #2804: not an operator. Bynk has no `%`; it lexes so the parser can say
376    /// so and point at `Int.rem` / `Int.mod`, not report a stray character.
377    #[token("%")]
378    Percent,
379    #[token("!")]
380    Bang,
381    #[token("=")]
382    Eq,
383    #[token("<")]
384    Lt,
385    #[token(">")]
386    Gt,
387    // v0.1 postfix operator
388    #[token("?")]
389    Question,
390    // v0.2 match-arm arrow
391    #[token("=>")]
392    FatArrow,
393    // v0.2 wildcard pattern. An identifier must start with a letter, so
394    // `_foo` lexes as `_` then `foo`, never as one Ident.
395    #[token("_")]
396    Underscore,
397    // v0.2 sum-type variant separator (also used as future bitwise OR);
398    // single `|` distinct from `||`.
399    #[token("|")]
400    Pipe,
401    /// `@` — storage-annotation marker (v0.85, storage track; ADR 0111). Leads a
402    /// `@name(args)` annotation on a `store` field (`@ttl(…)`/`@indexed(…)`); it
403    /// appears only in store-field-declaration position, never as an expression
404    /// operator.
405    #[token("@")]
406    At,
407
408    // Punctuation
409    #[token("(")]
410    LParen,
411    #[token(")")]
412    RParen,
413    #[token("{")]
414    LBrace,
415    #[token("}")]
416    RBrace,
417    #[token("[")]
418    LBracket,
419    #[token("]")]
420    RBracket,
421    #[token(",")]
422    Comma,
423    #[token(":")]
424    Colon,
425    #[token(".")]
426    Dot,
427}
428
429impl TokenKind {
430    /// Human-readable display name for diagnostics.
431    pub fn describe(self) -> &'static str {
432        use TokenKind::*;
433        match self {
434            Commons => "`commons`",
435            Type => "`type`",
436            Event => "`event`",
437            Asset => "`asset`",
438            Embed => "`embed`",
439            Const => "`const`",
440            Fn => "`fn`",
441            Where => "`where`",
442            True => "`true`",
443            False => "`false`",
444            Int => "`Int`",
445            String => "`String`",
446            Bool => "`Bool`",
447            Float => "`Float`",
448            Duration => "`Duration`",
449            Instant => "`Instant`",
450            Bytes => "`Bytes`",
451            Decimal => "`Decimal`",
452            Let => "`let`",
453            If => "`if`",
454            Else => "`else`",
455            Ok => "`Ok`",
456            Err => "`Err`",
457            Result => "`Result`",
458            ValidationError => "`ValidationError`",
459            DecodeError => "`DecodeError`",
460            JsonErrorDeprecated => "`JsonError`",
461            Enum => "`enum`",
462            Match => "`match`",
463            Option => "`Option`",
464            Record => "`record`",
465            Self_ => "`self`",
466            Some => "`Some`",
467            None => "`None`",
468            Is => "`is`",
469            Opaque => "`opaque`",
470            Uses => "`uses`",
471            Context => "`context`",
472            Consumes => "`consumes`",
473            Exports => "`exports`",
474            Transparent => "`transparent`",
475            As => "`as`",
476            Expect => "`expect`",
477            Suite => "`suite`",
478            Case => "`case`",
479            Property => "`property`",
480            Adapter => "`adapter`",
481            Binding => "`binding`",
482            Agent => "`agent`",
483            Capability => "`capability`",
484            Effect => "`Effect`",
485            Do => "`do`",
486            Given => "`given`",
487            On => "`on`",
488            Http => "`http`",
489            Cron => "`cron`",
490            Queue => "`queue`",
491            From => "`from`",
492            Protocol => "`protocol`",
493            Provides => "`provides`",
494            Stub => "`stub`",
495            Service => "`service`",
496            Actor => "`actor`",
497            Invariant => "`invariant`",
498            Implies => "`implies`",
499            Requires => "`requires`",
500            Ensures => "`ensures`",
501            Transition => "`transition`",
502            Messages => "`messages`",
503            ColonEq => "`:=`",
504            DotDotDot => "`...`",
505            DotDot => "`..`",
506            LArrow => "`<-`",
507            TildeArrow => "`~>`",
508            DocBlock => "documentation block",
509            DocLine => "one-line documentation (`--- text`)",
510            Comment => "line comment",
511            Ident => "identifier",
512            IntLit => "integer literal",
513            FloatLit => "float literal",
514            DecimalLit => "decimal literal",
515            StrLit => "string literal",
516            InterpStr => "interpolated string",
517            Arrow => "`->`",
518            EqEq => "`==`",
519            BangEq => "`!=`",
520            LtEq => "`<=`",
521            GtEq => "`>=`",
522            AmpAmp => "`&&`",
523            PipePipe => "`||`",
524            Plus => "`+`",
525            Minus => "`-`",
526            Star => "`*`",
527            Slash => "`/`",
528            Percent => "`%`",
529            Bang => "`!`",
530            Eq => "`=`",
531            Lt => "`<`",
532            Gt => "`>`",
533            Question => "`?`",
534            FatArrow => "`=>`",
535            Underscore => "`_`",
536            Pipe => "`|`",
537            At => "`@`",
538            LParen => "`(`",
539            RParen => "`)`",
540            LBrace => "`{`",
541            RBrace => "`}`",
542            LBracket => "`[`",
543            RBracket => "`]`",
544            Comma => "`,`",
545            Colon => "`:`",
546            Dot => "`.`",
547        }
548    }
549}
550
551/// A token plus its source span.
552#[derive(Debug, Clone, Copy)]
553pub struct Token {
554    pub kind: TokenKind,
555    pub span: Span,
556}
557
558/// Tokenise a source string with no real file identity — every span's
559/// [`FileId`] defaults to [`FileId::UNKNOWN`]. See [`tokenize_in`] for the
560/// real-identity entry point production callers use.
561pub fn tokenize(source: &str) -> Result<Vec<Token>, CompileError> {
562    tokenize_in(source, FileId::UNKNOWN)
563}
564
565/// Tokenise a source string, stamping every token's span with `file`.
566/// Returns the full token vector or the first lexical error
567/// ([`tokenize_recovering_in`] keeps going past it).
568///
569/// Doc blocks (`---` ... `---`), one-line docs (`--- text`) and line comments
570/// (`// ...`) are recognised outside the logos-generated lexer: we scan the
571/// source one segment at a time, dispatching to logos for ordinary tokens
572/// between non-token spans.
573pub fn tokenize_in(source: &str, file: FileId) -> Result<Vec<Token>, CompileError> {
574    tokenize_mode(source, file, false)
575}
576
577/// #2203: tokenise `source` as the lexer read it before `//` comments, for
578/// the formatter's migration of a file that still uses the legacy spellings.
579/// A `--` opens a comment wherever it starts the input or follows whitespace
580/// (ADR 0188 D1), so `--note` and a `--- Helpers ---` divider are comments, as
581/// they were; `--|` first on its line is a doc line. `//` comments and `---`
582/// blocks lex as in [`tokenize`], so a half-migrated file reads too. Every
583/// legacy token keeps its legacy spelling, so [`comment_body`] and
584/// [`doc_line_text`] read it and the formatter prints the new one.
585pub fn tokenize_legacy(source: &str) -> Result<Vec<Token>, CompileError> {
586    tokenize_mode(source, FileId::UNKNOWN, true)
587}
588
589fn tokenize_mode(source: &str, file: FileId, legacy: bool) -> Result<Vec<Token>, CompileError> {
590    let (tokens, errors) = tokenize_mode_recovering(source, file, legacy);
591    match errors.into_iter().next() {
592        Some(first) => Err(first),
593        None => Ok(tokens),
594    }
595}
596
597/// #2807: tokenise `source`, recovering from lexical errors instead of
598/// stopping at the first. Every error is returned, in source order, beside the
599/// tokens of everything the lexer could read: a bad character, a malformed or
600/// out-of-range literal, an unterminated string, an unclosed doc block and a
601/// `///` doc habit each yield an error and are then skipped (a string to the end
602/// of its line), so the text after them still lexes. The skipped text produces
603/// no token, which the parser sees as a gap; [`without_lex_echoes`] drops the
604/// syntax errors that gap causes.
605///
606/// The strict entry points ([`tokenize`] and kin) are this function with the
607/// first error kept and the tokens dropped. Callers that must not act on a file
608/// holding any lex error (the formatter, which would delete the skipped text)
609/// use those.
610pub fn tokenize_recovering_in(source: &str, file: FileId) -> (Vec<Token>, Vec<CompileError>) {
611    tokenize_mode_recovering(source, file, false)
612}
613
614/// [`tokenize_recovering_in`] with no real file identity.
615pub fn tokenize_recovering(source: &str) -> (Vec<Token>, Vec<CompileError>) {
616    tokenize_recovering_in(source, FileId::UNKNOWN)
617}
618
619/// The offset just past the line holding `from` (its newline included), or the
620/// end of `bytes`. A newline is ASCII, so the result is a character boundary.
621fn skip_line(bytes: &[u8], from: usize) -> usize {
622    match bytes[from.min(bytes.len())..]
623        .iter()
624        .position(|&b| b == b'\n')
625    {
626        Some(i) => from + i + 1,
627        None => bytes.len(),
628    }
629}
630
631/// Where lexing resumes after `err`, a failed string literal opened at `pos`.
632/// An unterminated literal has no closer, so the rest of its line goes. Any
633/// other fault (a bad escape, an under-indented body line, a bad hole) leaves a
634/// literal that does close: resume after its real closer, found by rescanning
635/// with escapes skipped, so the body and the closing quote are not lexed as code.
636/// No closer on the line (or at all, for a multi-line literal) falls back to
637/// skipping the line.
638fn string_error_resume(bytes: &[u8], pos: usize, err: &CompileError) -> usize {
639    let fallback = skip_line(bytes, err.span.end.max(pos + 1));
640    if err.category == "bynk.lex.unterminated_string" {
641        return fallback;
642    }
643    let Some(open) = string_open(bytes, pos) else {
644        return fallback;
645    };
646    let mut p = open.body;
647    while p < bytes.len() {
648        match bytes[p] {
649            b'\\' if !open.raw && bytes.get(p + 1) == Some(&b'(') => {
650                // An interpolation hole: its own strings and parens are not
651                // the literal's closer.
652                match hole_end(bytes, p + 2) {
653                    Some(end) => p = end,
654                    None => return fallback,
655                }
656            }
657            b'\\' if !open.raw => p += 2,
658            b'\n' if !open.multi => return fallback,
659            b'"' if open.multi => {
660                if bytes[p..].starts_with(b"\"\"\"") {
661                    return p + 3;
662                }
663                p += 1;
664            }
665            b'"' => {
666                let hashes = &bytes[p + 1..];
667                if hashes.len() >= open.hashes && hashes[..open.hashes].iter().all(|&b| b == b'#') {
668                    return p + 1 + open.hashes;
669                }
670                p += 1;
671            }
672            _ => p += 1,
673        }
674    }
675    fallback
676}
677
678/// The offset just past the `)` closing an interpolation hole whose body starts
679/// at `from`, skipping nested parens and string literals. `None` if it does not
680/// close before a newline or the end.
681fn hole_end(bytes: &[u8], from: usize) -> Option<usize> {
682    let (mut p, mut depth) = (from, 1usize);
683    while p < bytes.len() {
684        match bytes[p] {
685            b'\n' => return None,
686            b'(' => depth += 1,
687            b')' => {
688                depth -= 1;
689                if depth == 0 {
690                    return Some(p + 1);
691                }
692            }
693            b'"' => {
694                p += 1;
695                while p < bytes.len() && bytes[p] != b'"' {
696                    match bytes[p] {
697                        b'\n' => return None,
698                        b'\\' => p += 1,
699                        _ => {}
700                    }
701                    p += 1;
702                }
703            }
704            _ => {}
705        }
706        p += 1;
707    }
708    None
709}
710
711/// Record `err`, folding a run of adjacent stray characters into one error (a
712/// pasted block of them would otherwise be one diagnostic per character).
713fn push_lex_error(errors: &mut Vec<CompileError>, err: CompileError) {
714    const UNEXPECTED: &str = "bynk.lex.unexpected_character";
715    if err.category == UNEXPECTED
716        && let Some(prev) = errors.last_mut()
717        && prev.category == UNEXPECTED
718        && prev.span.end == err.span.start
719    {
720        prev.span.end = err.span.end;
721        prev.message = "unexpected characters".to_string();
722        return;
723    }
724    errors.push(err);
725}
726
727fn tokenize_mode_recovering(
728    source: &str,
729    file: FileId,
730    legacy: bool,
731) -> (Vec<Token>, Vec<CompileError>) {
732    let mut tokens = Vec::new();
733    let mut errors: Vec<CompileError> = Vec::new();
734    let bytes = source.as_bytes();
735    let mut pos = 0;
736    while pos < bytes.len() {
737        // Detect a `---` doc-block marker at the start of a line (the line may
738        // begin with leading whitespace; the marker itself must be alone on
739        // its line).
740        if let Some((open_end, dashes)) = doc_block_open_at(source, pos) {
741            // Find the matching closing marker: a line of exactly as many
742            // dashes as the opener (#1885), so a `----` block can hold `---`.
743            match doc_block_close(source, open_end, dashes) {
744                Some((close_start, close_end)) => {
745                    let span = Span::new_in(file, pos, close_end);
746                    tokens.push(Token {
747                        kind: TokenKind::DocBlock,
748                        span,
749                    });
750                    let _ = close_start;
751                    pos = close_end;
752                    continue;
753                }
754                None => {
755                    errors.push(CompileError::new(
756                        "bynk.lex.unclosed_doc_block",
757                        Span::new_in(file, pos, open_end),
758                        "documentation block opened but never closed",
759                    )
760                    .with_note(format!(
761                        "a doc block is closed by a line of exactly {dashes} dashes on its own; \
762                         a line of three or more dashes is a doc-block marker, not a divider, so \
763                         for a divider use a line comment, such as `// ---------`"
764                    )));
765                    // The block is the rest of the file, as the error says: its
766                    // prose lexed as code would only add errors.
767                    pos = bytes.len();
768                    continue;
769                }
770            }
771        }
772        let line_first = only_indent_before(bytes, pos);
773        // #2203: a `--- text` line is a one-line doc, its span running through
774        // the newline as a doc block's does. Before #2203 it was a `--`
775        // comment, and a legacy read keeps it one.
776        if line_first && doc_line_marker(bytes, pos) {
777            if legacy {
778                pos = push_comment(&mut tokens, bytes, pos, file);
779            } else {
780                pos = push_doc_line(&mut tokens, bytes, pos, file);
781            }
782            continue;
783        }
784        // #2203 (DECISION E): `///` first on its line is a Rust or C# doc
785        // habit. It never lexed (Bynk has no prefix `/`), so it is a plain
786        // lexical error pointing at `---`. A longer run of slashes is a `//`
787        // comment, as `////` is in Rust.
788        if line_first && bytes[pos..].starts_with(b"///") && bytes.get(pos + 3) != Some(&b'/') {
789            errors.push(slash_doc_error(bytes, pos, file));
790            pos = skip_line(bytes, pos);
791            continue;
792        }
793        // #1888: the legacy `--|` doc line, first on its line. It still lexes
794        // as a doc line; the parser reports its spelling.
795        if line_first && bytes[pos..].starts_with(b"--|") {
796            pos = push_doc_line(&mut tokens, bytes, pos, file);
797            continue;
798        }
799        // #2203: a `//` line comment, anywhere: emit a `Comment` token covering
800        // everything up to (but not including) the terminating newline.
801        // Preserving comments as trivia tokens lets the parser attach them to
802        // declarations so the formatter can emit them in place (v1.1 LSP spec
803        // §3.5). There is no prefix `/`, so `a//b` cannot mean anything else
804        // and needs no whitespace rule.
805        if bytes[pos..].starts_with(b"//") {
806            pos = push_comment(&mut tokens, bytes, pos, file);
807            continue;
808        }
809        // The legacy `--` comment (DECISION E): at the start of the input or
810        // after whitespace, followed by a space or the end of the line, or by
811        // `|` (a `--|` after code was a comment, #1888 DECISION E). It
812        // still lexes as a comment, so an old `x = 1 -- note` is never read as
813        // `1 - -note`; the parser reports its spelling. Any other `--` is two
814        // `-` operators, so `a--b` and `x--` are subtraction. A legacy read
815        // takes ADR 0188 D1's rule instead: any whitespace-preceded `--`.
816        let after_space = pos == 0 || matches!(bytes[pos - 1], b' ' | b'\t' | b'\r' | b'\n');
817        if after_space
818            && bytes[pos..].starts_with(b"--")
819            && (legacy
820                || matches!(
821                    bytes.get(pos + 2),
822                    None | Some(b' ' | b'\t' | b'\r' | b'\n' | b'|')
823                ))
824        {
825            pos = push_comment(&mut tokens, bytes, pos, file);
826            continue;
827        }
828        // Skip ordinary whitespace inline (logos handles it too, but we may
829        // be in the middle of the source between specials).
830        if matches!(bytes[pos], b' ' | b'\t' | b'\r' | b'\n') {
831            pos += 1;
832            continue;
833        }
834        // A string literal in any of its forms (#2619): plain, raw, or
835        // multi-line. One hand-scanner validates and decodes the literal; a
836        // literal holding a `\(` hole lexes as `InterpStr`, any other as
837        // `StrLit`.
838        if string_open(bytes, pos).is_some() {
839            let (end, segments) = match lex_string(source, pos, 0, file) {
840                Ok(lexed) => lexed,
841                Err(e) => {
842                    // The literal's remains are not code; lexing them as such
843                    // would only echo the error.
844                    pos = string_error_resume(bytes, pos, &e);
845                    errors.push(e);
846                    continue;
847                }
848            };
849            let kind = if segments.iter().any(|s| matches!(s, InterpSegment::Hole(_))) {
850                TokenKind::InterpStr
851            } else {
852                TokenKind::StrLit
853            };
854            tokens.push(Token {
855                kind,
856                span: Span::new_in(file, pos, end),
857            });
858            pos = end;
859            continue;
860        }
861        // Otherwise dispatch a single logos token starting at `pos`.
862        let mut lex = TokenKind::lexer(&source[pos..]);
863        let Some(result) = lex.next() else {
864            // No token at this position; treat as unexpected character so
865            // the user sees something useful.
866            let ch = source[pos..].chars().next().unwrap_or('\0');
867            let span = Span::new_in(file, pos, pos + ch.len_utf8());
868            push_lex_error(
869                &mut errors,
870                CompileError::new(
871                    "bynk.lex.unexpected_character",
872                    span,
873                    format!("unexpected character `{ch}`"),
874                ),
875            );
876            pos += ch.len_utf8();
877            continue;
878        };
879        let local = lex.span();
880        let span: Span = Span::new_in(file, pos + local.start, pos + local.end);
881        match result {
882            Ok(kind) => {
883                // #1657 (runtime-semantics track §3.4): an `Int` is a JS safe
884                // integer, ±(2^53 − 1), the range the runtime represents
885                // exactly. A larger literal would round silently
886                // (`9007199254740993 == 9007199254740992`). The sign is a
887                // separate operator, and the bound is symmetric, so the
888                // magnitude decides.
889                if kind == TokenKind::IntLit {
890                    let slice = &source[span.range()];
891                    if !strip_digit_separators(slice)
892                        .parse::<i64>()
893                        .is_ok_and(|n| n <= MAX_SAFE_INT)
894                    {
895                        errors.push(
896                            CompileError::new(
897                                "bynk.lex.integer_overflow",
898                                span,
899                                format!("integer literal `{slice}` is out of range for an `Int`"),
900                            )
901                            .with_note(
902                                "an `Int` is a safe integer, -(2^53 - 1) to 2^53 - 1 \
903                             (±9007199254740991); use a `Float` or a `String` for a larger value",
904                            ),
905                        );
906                        pos = span.end;
907                        continue;
908                    }
909                }
910                if kind == TokenKind::DecimalLit {
911                    // #2622: the limits every `Decimal` obeys, so a literal
912                    // always encodes to text the wire decoder accepts.
913                    let slice = &source[span.range()];
914                    let body = strip_digit_separators(&slice[..slice.len() - 1]).into_owned();
915                    let frac = body.split_once('.').map_or(0, |(_, f)| f.len());
916                    if frac > 100 || body.len() > 1000 {
917                        errors.push(
918                            CompileError::new(
919                                "bynk.lex.decimal_literal_too_large",
920                                span,
921                                "decimal literal is too large",
922                            )
923                            .with_note(
924                                "a `Decimal` has at most 100 fraction digits and 1000 characters",
925                            ),
926                        );
927                        pos = span.end;
928                        continue;
929                    }
930                }
931                if kind == TokenKind::FloatLit {
932                    let slice = &source[span.range()];
933                    match strip_digit_separators(slice).parse::<f64>() {
934                        Ok(v) if v.is_finite() => {}
935                        _ => {
936                            errors.push(
937                                CompileError::new(
938                                    "bynk.lex.float_literal_overflow",
939                                    span,
940                                    format!(
941                                        "float literal `{slice}` is out of range for a 64-bit float"
942                                    ),
943                                )
944                                .with_note(
945                                    "the literal does not fit a finite IEEE 754 double; \
946                                 the largest finite value is ~1.8e308",
947                                ),
948                            );
949                            pos = span.end;
950                            continue;
951                        }
952                    }
953                }
954                tokens.push(Token { kind, span });
955                pos = span.end;
956            }
957            Err(()) => {
958                let slice = &source[span.range()];
959                let ch = slice.chars().next().unwrap_or('\0');
960                let err = if ch == '"' {
961                    CompileError::new(
962                        "bynk.lex.unterminated_string",
963                        span,
964                        "unterminated string literal",
965                    )
966                    .with_note(
967                        "string literals must close with `\"` on the same line; \
968                         supported escapes are `\\n`, `\\t`, `\\\"`, `\\\\`",
969                    )
970                } else {
971                    CompileError::new(
972                        "bynk.lex.unexpected_character",
973                        span,
974                        format!("unexpected character `{ch}`"),
975                    )
976                };
977                push_lex_error(&mut errors, err);
978                pos = if ch == '"' {
979                    skip_line(bytes, span.end.max(pos + 1))
980                } else {
981                    span.end.max(pos + ch.len_utf8())
982                };
983            }
984        }
985    }
986    (tokens, errors)
987}
988
989/// #2807: `parse_errors` without the ones a lexical error caused. Recovery
990/// skips the text a lex error covers, so the parser meets a gap where the
991/// literal or character stood and complains about it at the same spot. An error
992/// that starts in a lex error's span, or at the token right after it, is that
993/// echo and is dropped; every other syntax error stays. `tokens` is the
994/// recovering lex's token list. A heuristic: a genuine syntax error at that next
995/// token (the `fn` after a stray character on its own line) is dropped with the
996/// echo, and surfaces once the lexical error is fixed.
997pub fn without_lex_echoes(
998    lex_errors: &[CompileError],
999    tokens: &[Token],
1000    parse_errors: Vec<CompileError>,
1001) -> Vec<CompileError> {
1002    let echo_ranges: Vec<(usize, usize)> = lex_errors
1003        .iter()
1004        .map(|le| {
1005            // `tokens` are in source order. Trivia is not a token the parser
1006            // sees, and with no token after the error the gap runs to the end
1007            // of the file (an EOF error is its echo).
1008            let first = tokens.partition_point(|t| t.span.start < le.span.end);
1009            let next_end = tokens[first..]
1010                .iter()
1011                .find(|t| !matches!(t.kind, TokenKind::Comment | TokenKind::DocLine))
1012                .map_or(usize::MAX, |t| t.span.end);
1013            (le.span.start, next_end)
1014        })
1015        .collect();
1016    parse_errors
1017        .into_iter()
1018        .filter(|e| {
1019            !echo_ranges
1020                .iter()
1021                .any(|&(lo, hi)| e.span.start >= lo && e.span.start <= hi)
1022        })
1023        .collect()
1024}
1025
1026/// Like [`tokenize`], but with every interpolated-string token replaced by the
1027/// tokens of its holes — each hole's bytes re-lexed and its token spans rebased
1028/// to absolute source positions (the same rebase [`crate::parser`] applies when
1029/// parsing a hole), recursing through nested interpolation. Chunk (literal) text
1030/// between holes yields no tokens.
1031///
1032/// An interpolated string lexes to a single opaque `InterpStr` token, so the
1033/// LSP's token-based cursor resolution (hover, go-to-definition, references,
1034/// semantic tokens) is otherwise blind to identifiers inside `"… \(name) …"`.
1035/// Expanding the holes makes those identifiers visible as ordinary `Ident`
1036/// tokens with their real spans. (Issue #473.)
1037///
1038/// On a malformed interpolation (an `InterpStr` whose holes don't split, or a
1039/// hole whose bytes don't re-lex) the offending token is kept opaque rather than
1040/// dropped, so resolution degrades to the pre-fix behaviour instead of losing
1041/// tokens.
1042pub fn tokenize_expanding_holes(source: &str) -> Result<Vec<Token>, CompileError> {
1043    tokenize_expanding_holes_in(source, FileId::UNKNOWN)
1044}
1045
1046/// Like [`tokenize_expanding_holes`], but stamping every token's span
1047/// (including rebased hole tokens) with `file`.
1048pub fn tokenize_expanding_holes_in(source: &str, file: FileId) -> Result<Vec<Token>, CompileError> {
1049    let mut out = Vec::new();
1050    for tok in tokenize_in(source, file)? {
1051        expand_hole_token(source, file, tok, &mut out);
1052    }
1053    Ok(out)
1054}
1055
1056/// Push `tok` onto `out`, expanding it into its holes' tokens if it is an
1057/// `InterpStr` (see [`tokenize_expanding_holes`]); otherwise push it as-is.
1058fn expand_hole_token(source: &str, file: FileId, tok: Token, out: &mut Vec<Token>) {
1059    if tok.kind != TokenKind::InterpStr {
1060        out.push(tok);
1061        return;
1062    }
1063    let Ok(segments) = split_interp(source, tok.span) else {
1064        out.push(tok); // malformed interpolation — keep the opaque token
1065        return;
1066    };
1067    for segment in segments {
1068        let InterpSegment::Hole(hole) = segment else {
1069            continue; // chunk text carries no tokens
1070        };
1071        let Ok(hole_tokens) = tokenize_in(&source[hole.range()], file) else {
1072            continue;
1073        };
1074        for mut t in hole_tokens {
1075            // Rebase the hole's local spans to absolute source positions.
1076            t.span = Span::new_in(file, t.span.start + hole.start, t.span.end + hole.start);
1077            expand_hole_token(source, file, t, out); // recurse for nested interpolation
1078        }
1079    }
1080}
1081
1082// ---- String literals (v0.43 interpolation; #2619 raw / multi-line / more escapes) ----
1083
1084/// The shape of a string literal opening at some offset.
1085#[derive(Clone, Copy)]
1086struct StringOpen {
1087    /// `r"…"`, `r#"…"#`, `r"""…"""`: no escapes, no interpolation.
1088    raw: bool,
1089    /// `"""…"""` / `r"""…"""`: the body spans lines.
1090    multi: bool,
1091    /// Number of `#` between the `r` and the opening quote (single-line raw only).
1092    hashes: usize,
1093    /// Offset just past the opening delimiter (`"`, `"""`, `r#"`, …).
1094    body: usize,
1095}
1096
1097fn is_ident_byte(b: u8) -> bool {
1098    b.is_ascii_alphanumeric() || b == b'_'
1099}
1100
1101/// Does a string literal open at `start`? `r` opens a raw string only when it
1102/// is *immediately* followed by `#`s and a `"`, so an identifier `r` followed by
1103/// a (spaced) string is unaffected.
1104fn string_open(bytes: &[u8], start: usize) -> Option<StringOpen> {
1105    let raw = bytes.get(start) == Some(&b'r');
1106    let mut p = start + usize::from(raw);
1107    let mut hashes = 0;
1108    if raw {
1109        while bytes.get(p) == Some(&b'#') {
1110            hashes += 1;
1111            p += 1;
1112        }
1113    }
1114    if bytes.get(p) != Some(&b'"') {
1115        return None;
1116    }
1117    let multi = hashes == 0 && bytes[p..].starts_with(b"\"\"\"");
1118    Some(StringOpen {
1119        raw,
1120        multi,
1121        hashes,
1122        body: if multi { p + 3 } else { p + 1 },
1123    })
1124}
1125
1126fn unterminated_string(file: FileId, start: usize, end: usize, multi: bool) -> CompileError {
1127    let note = if multi {
1128        "a multi-line string closes with `\"\"\"` on a line of its own"
1129    } else {
1130        "string literals must close with `\"` on the same line (use `\"\"\"` for a multi-line string); \
1131         supported escapes: \\n \\r \\t \\0 \\\" \\\\ \\u{…} and `\\(…)` interpolation"
1132    };
1133    CompileError::new(
1134        "bynk.lex.unterminated_string",
1135        Span::new_in(file, start, end),
1136        "unterminated string literal",
1137    )
1138    .with_note(note)
1139}
1140
1141/// Span of the byte range `from..to`, advanced to a char boundary so it never
1142/// splits a multibyte codepoint (a fuzz invariant).
1143fn boundary_span(source: &str, file: FileId, from: usize, to: usize) -> Span {
1144    let mut end = to.min(source.len());
1145    while end < source.len() && !source.is_char_boundary(end) {
1146        end += 1;
1147    }
1148    Span::new_in(file, from, end)
1149}
1150
1151const ESCAPE_NOTE: &str = "supported escapes: \\n \\r \\t \\0 \\\" \\\\ \\u{…} \\(…)";
1152
1153/// Scan and decode the string literal opening at `start`, returning the offset
1154/// just past it and its segments (literal chunks with escapes resolved, and the
1155/// spans of any `\(…)` holes). This is the single scanner for every form.
1156fn lex_string(
1157    source: &str,
1158    start: usize,
1159    depth: usize,
1160    file: FileId,
1161) -> Result<(usize, Vec<InterpSegment>), CompileError> {
1162    let bytes = source.as_bytes();
1163    let open = string_open(bytes, start).expect("caller checked string_open");
1164    if depth > crate::MAX_NESTING_DEPTH {
1165        // Anchor on the opening `"` of the string that tipped over the limit.
1166        return Err(too_deeply_nested_interpolation(Span::new_in(
1167            file,
1168            start,
1169            start + 1,
1170        )));
1171    }
1172    let mut segments = Vec::new();
1173    let mut chunk = String::new();
1174    if open.multi {
1175        let end = lex_multiline(source, start, open, depth, file, &mut segments, &mut chunk)?;
1176        if !chunk.is_empty() {
1177            segments.push(InterpSegment::Chunk(chunk));
1178        }
1179        return Ok((end, segments));
1180    }
1181    if open.raw {
1182        // `r#"…"#`: the body runs to the first `"` followed by `hashes` `#`s.
1183        let mut i = open.body;
1184        loop {
1185            if i >= bytes.len() || bytes[i] == b'\n' {
1186                return Err(unterminated_string(file, start, i.min(bytes.len()), false));
1187            }
1188            if bytes[i] == b'"' && (1..=open.hashes).all(|k| bytes.get(i + k) == Some(&b'#')) {
1189                break;
1190            }
1191            i += 1;
1192        }
1193        chunk.push_str(&source[open.body..i]);
1194        if !chunk.is_empty() {
1195            segments.push(InterpSegment::Chunk(chunk));
1196        }
1197        return Ok((i + 1 + open.hashes, segments));
1198    }
1199    let end = decode_run(
1200        source,
1201        open.body,
1202        Stop::Quote(start),
1203        depth,
1204        file,
1205        &mut segments,
1206        &mut chunk,
1207    )?;
1208    if !chunk.is_empty() {
1209        segments.push(InterpSegment::Chunk(chunk));
1210    }
1211    Ok((end + 1, segments))
1212}
1213
1214/// Where a [`decode_run`] stops.
1215#[derive(Clone, Copy)]
1216enum Stop {
1217    /// At the closing `"` of a single-line string (the payload is the literal's
1218    /// start, for the unterminated error); a newline or end of input first is an
1219    /// error.
1220    Quote(usize),
1221    /// At a fixed offset: one line of a multi-line string, where a bare `"""`
1222    /// inside the line is an error (the closing delimiter has a line to itself).
1223    End(usize),
1224}
1225
1226/// Decode non-raw string text from `from`, appending to `chunk` / `segments`.
1227/// Returns the offset where it stopped (the closing `"` for [`Stop::Quote`]).
1228fn decode_run(
1229    source: &str,
1230    from: usize,
1231    stop: Stop,
1232    depth: usize,
1233    file: FileId,
1234    segments: &mut Vec<InterpSegment>,
1235    chunk: &mut String,
1236) -> Result<usize, CompileError> {
1237    let bytes = source.as_bytes();
1238    let limit = match stop {
1239        Stop::Quote(_) => bytes.len(),
1240        Stop::End(e) => e,
1241    };
1242    let mut i = from;
1243    loop {
1244        if i >= limit {
1245            match stop {
1246                Stop::End(_) => return Ok(i),
1247                Stop::Quote(start) => {
1248                    return Err(unterminated_string(file, start, i.min(bytes.len()), false));
1249                }
1250            }
1251        }
1252        match bytes[i] {
1253            b'\n' if matches!(stop, Stop::Quote(_)) => {
1254                let Stop::Quote(start) = stop else {
1255                    unreachable!()
1256                };
1257                return Err(unterminated_string(file, start, i, false));
1258            }
1259            b'"' => match stop {
1260                Stop::Quote(_) => return Ok(i),
1261                Stop::End(e) => {
1262                    if bytes[i..e].starts_with(b"\"\"\"") {
1263                        return Err(CompileError::new(
1264                            "bynk.lex.multiline_close_not_own_line",
1265                            Span::new_in(file, i, i + 3),
1266                            "a `\"\"\"` inside a multi-line string closes it, but it is not on a line of its own",
1267                        )
1268                        .with_note(
1269                            "put the closing `\"\"\"` on its own line, or escape a quote as `\\\"`",
1270                        ));
1271                    }
1272                    chunk.push('"');
1273                    i += 1;
1274                }
1275            },
1276            b'\\' => {
1277                let next = if i + 1 < limit {
1278                    Some(bytes[i + 1])
1279                } else {
1280                    None
1281                };
1282                match next {
1283                    Some(b'n') => {
1284                        chunk.push('\n');
1285                        i += 2;
1286                    }
1287                    Some(b't') => {
1288                        chunk.push('\t');
1289                        i += 2;
1290                    }
1291                    Some(b'r') => {
1292                        chunk.push('\r');
1293                        i += 2;
1294                    }
1295                    Some(b'0') => {
1296                        chunk.push('\0');
1297                        i += 2;
1298                    }
1299                    Some(b'"') => {
1300                        chunk.push('"');
1301                        i += 2;
1302                    }
1303                    Some(b'\\') => {
1304                        chunk.push('\\');
1305                        i += 2;
1306                    }
1307                    Some(b'u') => {
1308                        let (ch, after) = decode_unicode_escape(source, i, limit, file)?;
1309                        chunk.push(ch);
1310                        i = after;
1311                    }
1312                    Some(b'(') => {
1313                        if !chunk.is_empty() {
1314                            segments.push(InterpSegment::Chunk(std::mem::take(chunk)));
1315                        }
1316                        let hole_start = i + 2;
1317                        let after = scan_hole(bytes, source, hole_start, depth + 1, file)?;
1318                        // `after` is one past the matching `)`; the hole body is
1319                        // everything up to that `)`.
1320                        segments.push(InterpSegment::Hole(Span::new_in(
1321                            file,
1322                            hole_start,
1323                            after - 1,
1324                        )));
1325                        i = after;
1326                    }
1327                    other => {
1328                        let shown = other.map(|b| (b as char).to_string()).unwrap_or_default();
1329                        // Cover `\` plus the whole offending char, advanced to a
1330                        // char boundary.
1331                        return Err(CompileError::new(
1332                            "bynk.lex.bad_escape",
1333                            boundary_span(source, file, i, i + 2),
1334                            format!("invalid escape sequence `\\{shown}` in string literal"),
1335                        )
1336                        .with_note(ESCAPE_NOTE));
1337                    }
1338                }
1339            }
1340            // Any other byte: copy the whole char. UTF-8 continuation bytes are
1341            // all >= 0x80, so they never collide with the ASCII specials.
1342            _ => {
1343                let ch = source[i..].chars().next().unwrap();
1344                chunk.push(ch);
1345                i += ch.len_utf8();
1346            }
1347        }
1348    }
1349}
1350
1351/// Decode `\u{…}` at `i` (the `\`): 1–6 hex digits naming a Unicode scalar
1352/// value. Returns the char and the offset past the `}`. A lone surrogate
1353/// (D800–DFFF) or a value above 10FFFF is a lexical error, so every literal is
1354/// valid UTF-8 text.
1355fn decode_unicode_escape(
1356    source: &str,
1357    i: usize,
1358    limit: usize,
1359    file: FileId,
1360) -> Result<(char, usize), CompileError> {
1361    let bytes = source.as_bytes();
1362    let malformed = |end: usize| {
1363        CompileError::new(
1364            "bynk.lex.bad_escape",
1365            Span::new_in(file, i, end),
1366            "invalid `\\u{…}` escape in string literal",
1367        )
1368        .with_note(
1369            "a Unicode escape is `\\u{` followed by 1 to 6 hex digits and `}`, e.g. `\\u{1F600}`",
1370        )
1371    };
1372    let mut p = i + 2; // past `\u`
1373    if p >= limit || bytes[p] != b'{' {
1374        return Err(malformed(p));
1375    }
1376    p += 1;
1377    let digits_start = p;
1378    while p < limit && bytes[p].is_ascii_hexdigit() {
1379        p += 1;
1380    }
1381    let digits = p - digits_start;
1382    if digits == 0 || digits > 6 || p >= limit || bytes[p] != b'}' {
1383        return Err(malformed(p.min(limit)));
1384    }
1385    let value = u32::from_str_radix(&source[digits_start..p], 16).expect("hex digits");
1386    p += 1; // past `}`
1387    match char::from_u32(value) {
1388        Some(ch) => Ok((ch, p)),
1389        None => Err(CompileError::new(
1390            "bynk.lex.bad_unicode_escape",
1391            Span::new_in(file, i, p),
1392            format!("`\\u{{{value:X}}}` is not a Unicode scalar value"),
1393        )
1394        .with_note(
1395            "surrogate code points (D800 to DFFF) and values above 10FFFF cannot appear in a string",
1396        )),
1397    }
1398}
1399
1400/// The rest of a multi-line literal's opening line, from `body` (just past the
1401/// `"""`): an optional language tag `[a-z][a-z0-9_-]*` (#2958), then — only
1402/// after a tag — spaces or tabs, then `\n` or `\r\n`. Returns the tag's byte
1403/// range (empty when there is none) and the offset where the first body line
1404/// starts. `None` when the line holds anything else.
1405///
1406/// The tag is editor metadata (which language the text is, for embedded
1407/// highlighting): it is not part of the value.
1408fn multiline_opener(bytes: &[u8], body: usize) -> Option<(std::ops::Range<usize>, usize)> {
1409    let mut p = body;
1410    if bytes.get(p).is_some_and(u8::is_ascii_lowercase) {
1411        p += 1;
1412        while bytes.get(p).is_some_and(|&b| {
1413            b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_' || b == b'-'
1414        }) {
1415            p += 1;
1416        }
1417    }
1418    let tag = body..p;
1419    if !tag.is_empty() {
1420        while matches!(bytes.get(p), Some(b' ' | b'\t')) {
1421            p += 1;
1422        }
1423    }
1424    match (bytes.get(p), bytes.get(p + 1)) {
1425        (Some(b'\n'), _) => Some((tag, p + 1)),
1426        (Some(b'\r'), Some(b'\n')) => Some((tag, p + 2)),
1427        _ => None,
1428    }
1429}
1430
1431/// Scan and decode a multi-line literal (`"""` / `r"""`) opening at `start`.
1432/// Returns the offset just past the closing `"""`. The closing delimiter sits on
1433/// a line of its own; its indentation is stripped from every body line, and a
1434/// non-blank line indented less is an error. Newlines in the value are always
1435/// `\n`, whatever the file's line endings.
1436fn lex_multiline(
1437    source: &str,
1438    start: usize,
1439    open: StringOpen,
1440    depth: usize,
1441    file: FileId,
1442    segments: &mut Vec<InterpSegment>,
1443    chunk: &mut String,
1444) -> Result<usize, CompileError> {
1445    let bytes = source.as_bytes();
1446    // The opening `"""` is followed by an optional language tag (#2958) and a
1447    // newline (`\n` or `\r\n`).
1448    let Some((_, mut pos)) = multiline_opener(bytes, open.body) else {
1449        return Err(CompileError::new(
1450            "bynk.lex.multiline_open",
1451            Span::new_in(file, start, open.body),
1452            "the opening `\"\"\"` of a multi-line string must be followed by a newline",
1453        )
1454        .with_note(
1455            "the text starts on the next line; write `\"\"\"` then press enter. \
1456             An optional language tag may sit directly after the delimiter \
1457             (`\"\"\"sql`): a lowercase letter, then lowercase letters, digits, `_` or `-`",
1458        ));
1459    };
1460    // Pass 1: split into lines up to the closing line.
1461    let mut lines: Vec<(usize, usize)> = Vec::new(); // (start, end) excluding the `\n` / `\r\n`
1462    let (indent_len, end) = loop {
1463        if pos >= bytes.len() {
1464            return Err(unterminated_string(file, start, bytes.len(), true));
1465        }
1466        let line_end = bytes[pos..]
1467            .iter()
1468            .position(|&b| b == b'\n')
1469            .map_or(bytes.len(), |n| pos + n);
1470        let mut ws = pos;
1471        while ws < line_end && matches!(bytes[ws], b' ' | b'\t') {
1472            ws += 1;
1473        }
1474        // A closing delimiter ends its line's text: `"""quoted"""` is body text
1475        // holding a stray `"""`, which `decode_run` reports.
1476        if bytes[ws..line_end].starts_with(b"\"\"\"")
1477            && !bytes
1478                .get(ws + 3)
1479                .is_some_and(|&b| is_ident_byte(b) || b == b'"')
1480        {
1481            break (ws - pos, ws + 3);
1482        }
1483        let trimmed_end = if line_end > pos && bytes[line_end - 1] == b'\r' {
1484            line_end - 1
1485        } else {
1486            line_end
1487        };
1488        lines.push((pos, trimmed_end));
1489        if line_end >= bytes.len() {
1490            return Err(unterminated_string(file, start, bytes.len(), true));
1491        }
1492        pos = line_end + 1;
1493    };
1494    let closing_line_start = end - 3 - indent_len;
1495    let indent = &bytes[closing_line_start..closing_line_start + indent_len];
1496    // Pass 2: strip the indentation and decode each line.
1497    for (n, &(ls, le)) in lines.iter().enumerate() {
1498        if n > 0 {
1499            chunk.push('\n');
1500        }
1501        let line = &bytes[ls..le];
1502        let blank = line.iter().all(|b| matches!(b, b' ' | b'\t'));
1503        let content = if line.starts_with(indent) {
1504            ls + indent_len
1505        } else if blank {
1506            le // a blank line shorter than the indentation is empty
1507        } else {
1508            return Err(CompileError::new(
1509                "bynk.lex.multiline_indent",
1510                boundary_span(source, file, ls, le),
1511                "a line of this multi-line string is indented less than its closing `\"\"\"`",
1512            )
1513            .with_note(if line.len() >= indent.len() {
1514                "the indentation must match the closing delimiter's character for character: \
1515                 a tab does not match a space, so mixed tabs and spaces fail here"
1516            } else {
1517                "every non-blank line must start with the closing delimiter's indentation, \
1518                 which is stripped from the value"
1519            }));
1520        };
1521        if open.raw {
1522            let text = &source[content..le];
1523            if let Some(at) = text.find("\"\"\"") {
1524                return Err(CompileError::new(
1525                    "bynk.lex.multiline_close_not_own_line",
1526                    Span::new_in(file, content + at, content + at + 3),
1527                    "a `\"\"\"` inside a multi-line string closes it, but it is not on a line of its own",
1528                )
1529                .with_note("put the closing `\"\"\"` on its own line"));
1530            }
1531            chunk.push_str(text);
1532        } else {
1533            decode_run(source, content, Stop::End(le), depth, file, segments, chunk)?;
1534        }
1535    }
1536    Ok(end)
1537}
1538
1539/// Scan an interpolation hole body. `start` points just past the `\(`; returns
1540/// the offset just past the matching `)`. Tracks paren depth and skips nested
1541/// strings (whose own parens must not close the hole), recursing through
1542/// [`lex_string`] so nested interpolation nests correctly. (v0.43.)
1543fn scan_hole(
1544    bytes: &[u8],
1545    source: &str,
1546    start: usize,
1547    nesting: usize,
1548    file: FileId,
1549) -> Result<usize, CompileError> {
1550    if nesting > crate::MAX_NESTING_DEPTH {
1551        // Anchor on the `\(` opener that tipped over the limit; it sits two
1552        // bytes before `start` and is pure ASCII, so the span stays on char
1553        // boundaries (a fuzz invariant).
1554        return Err(too_deeply_nested_interpolation(Span::new_in(
1555            file,
1556            start.saturating_sub(2),
1557            start,
1558        )));
1559    }
1560    let mut i = start;
1561    let mut depth = 1usize;
1562    loop {
1563        if i >= bytes.len() || bytes[i] == b'\n' {
1564            return Err(CompileError::new(
1565                "bynk.lex.unterminated_interpolation",
1566                Span::new_in(file, start.saturating_sub(2), i.min(bytes.len())),
1567                "unterminated interpolation hole",
1568            )
1569            .with_note(
1570                "an interpolation hole `\\(…)` must close with a matching `)` on the same line",
1571            ));
1572        }
1573        match bytes[i] {
1574            b'(' => {
1575                depth += 1;
1576                i += 1;
1577            }
1578            b')' => {
1579                depth -= 1;
1580                i += 1;
1581                if depth == 0 {
1582                    return Ok(i);
1583                }
1584            }
1585            b'"' => i = nested_string(source, i, nesting, file)?,
1586            // A nested raw string: `r"…"` (not the tail of an identifier).
1587            b'r' if (i == start || !is_ident_byte(bytes[i - 1]))
1588                && string_open(bytes, i).is_some() =>
1589            {
1590                i = nested_string(source, i, nesting, file)?
1591            }
1592            _ => i += 1,
1593        }
1594    }
1595}
1596
1597/// Skip a string literal nested in an interpolation hole. A hole closes on the
1598/// line it opens on, so a multi-line string cannot sit inside one (#2619).
1599fn nested_string(
1600    source: &str,
1601    at: usize,
1602    nesting: usize,
1603    file: FileId,
1604) -> Result<usize, CompileError> {
1605    if string_open(source.as_bytes(), at).is_some_and(|o| o.multi) {
1606        return Err(CompileError::new(
1607            "bynk.lex.multiline_in_hole",
1608            Span::new_in(file, at, at + 3),
1609            "a multi-line string cannot appear inside an interpolation hole",
1610        )
1611        .with_note(
1612            "an interpolation hole `\\(…)` closes on the line it opens on; \
1613             bind the multi-line text to a name and interpolate that",
1614        ));
1615    }
1616    Ok(lex_string(source, at, nesting + 1, file)?.0)
1617}
1618
1619/// The bounded-depth diagnostic for interpolation that nests past
1620/// [`crate::MAX_NESTING_DEPTH`]. `\("\("\(…` mutually recurses
1621/// [`lex_string`] ↔ [`scan_hole`], one stack frame per level, so an unbounded
1622/// scanner overflows and aborts `tokenize` (#713). `span` anchors the report on
1623/// the opener that tipped over the limit (the `"` or the `\(`).
1624fn too_deeply_nested_interpolation(span: Span) -> CompileError {
1625    CompileError::new(
1626        "bynk.lex.interpolation_too_deep",
1627        span,
1628        format!(
1629            "string interpolation nests more than {} levels deep",
1630            crate::MAX_NESTING_DEPTH
1631        ),
1632    )
1633    .with_note(
1634        "deeply nested `\\(…)` interpolation is rejected to keep the lexer from \
1635         overflowing its stack and aborting; flatten or split the string",
1636    )
1637}
1638
1639/// One segment of a split interpolated string (v0.43): literal text (escapes
1640/// resolved) or the absolute source span of a hole's expression (the bytes
1641/// between `\(` and its matching `)`). The parser turns the latter into a real
1642/// `Expr`; the lexer owns only the scanning.
1643pub(crate) enum InterpSegment {
1644    Chunk(String),
1645    Hole(Span),
1646}
1647
1648/// Split a string token (its `span` covers the whole lexeme) into chunks and
1649/// hole spans. Escapes in the chunks are resolved by [`lex_string`], the one
1650/// decoder every form shares; holes are returned as spans for the parser to
1651/// re-lex and parse as expressions. (v0.43, #2619.)
1652pub(crate) fn split_interp(source: &str, span: Span) -> Result<Vec<InterpSegment>, CompileError> {
1653    lex_string(source, span.start, 0, span.file).map(|(_, segments)| segments)
1654}
1655
1656/// A highlighted part of a string literal (#2619), for the semantic tokens.
1657#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1658pub enum StringPart {
1659    /// An escape sequence (`\n`, `\u{1F600}`, …).
1660    Escape,
1661    /// A raw literal's delimiter (`r#"` or `"#`), which the TextMate grammar
1662    /// cannot tell from an identifier `r` and a quote.
1663    RawDelimiter,
1664    /// A multi-line literal's language tag (`sql` in `"""sql`, #2958): editor
1665    /// metadata, not part of the value.
1666    Tag,
1667}
1668
1669/// The escape sequences and raw delimiters of every string literal in `source`
1670/// (including those inside interpolation holes), for the editor's semantic
1671/// tokens. Empty when the file does not lex.
1672pub fn string_parts(source: &str) -> Vec<(Span, StringPart)> {
1673    let mut out = Vec::new();
1674    if let Ok(tokens) = tokenize(source) {
1675        for tok in tokens {
1676            string_parts_of(source, tok, &mut out);
1677        }
1678    }
1679    out
1680}
1681
1682/// [`string_parts`] for one token, recursing into the holes of an
1683/// interpolated string (each hole re-lexed and rebased to absolute offsets).
1684fn string_parts_of(source: &str, tok: Token, out: &mut Vec<(Span, StringPart)>) {
1685    if !matches!(tok.kind, TokenKind::StrLit | TokenKind::InterpStr) {
1686        return;
1687    }
1688    let bytes = source.as_bytes();
1689    let file = tok.span.file;
1690    let Some(open) = string_open(bytes, tok.span.start) else {
1691        return;
1692    };
1693    if open.multi
1694        && let Some((tag, _)) = multiline_opener(bytes, open.body)
1695        && !tag.is_empty()
1696    {
1697        out.push((Span::new_in(file, tag.start, tag.end), StringPart::Tag));
1698    }
1699    if open.raw {
1700        // `r#"` and the closing `"#`; a multi-line raw literal's `r"""` /
1701        // `"""` likewise.
1702        let close = if open.multi { 3 } else { 1 + open.hashes };
1703        out.push((
1704            Span::new_in(file, tok.span.start, open.body),
1705            StringPart::RawDelimiter,
1706        ));
1707        out.push((
1708            Span::new_in(file, tok.span.end - close, tok.span.end),
1709            StringPart::RawDelimiter,
1710        ));
1711        return;
1712    }
1713    let Ok(segments) = split_interp(source, tok.span) else {
1714        return;
1715    };
1716    let holes: Vec<Span> = segments
1717        .iter()
1718        .filter_map(|s| match s {
1719            InterpSegment::Hole(h) => Some(*h),
1720            InterpSegment::Chunk(_) => None,
1721        })
1722        .collect();
1723    let mut i = open.body;
1724    let end = tok.span.end - if open.multi { 3 } else { 1 };
1725    while i < end {
1726        if bytes[i] != b'\\' {
1727            i += 1;
1728            continue;
1729        }
1730        if let Some(hole) = holes.iter().find(|h| h.start == i + 2) {
1731            i = hole.end + 1; // past the hole's `)`
1732            continue;
1733        }
1734        let len = if bytes.get(i + 1) == Some(&b'u') {
1735            bytes[i..end]
1736                .iter()
1737                .position(|&b| b == b'}')
1738                .map_or(2, |n| n + 1)
1739        } else {
1740            2
1741        };
1742        out.push((Span::new_in(file, i, i + len), StringPart::Escape));
1743        i += len;
1744    }
1745    for hole in holes {
1746        let Ok(hole_tokens) = tokenize_in(&source[hole.range()], file) else {
1747            continue;
1748        };
1749        for mut t in hole_tokens {
1750            t.span = Span::new_in(file, t.span.start + hole.start, t.span.end + hole.start);
1751            string_parts_of(source, t, out);
1752        }
1753    }
1754}
1755
1756/// The value of a hole-free string lexeme (any form), for callers that hold the
1757/// lexeme rather than the surrounding source. `span` locates the lexeme in the
1758/// file so a (normally unreachable — the lexer already validated it) error
1759/// points at the right place.
1760pub fn decode_string_literal(lexeme: &str, span: Span) -> Result<String, CompileError> {
1761    let (_, segments) =
1762        lex_string(lexeme, 0, 0, span.file).map_err(|e| e.offset_spans(span.start))?;
1763    let mut out = String::with_capacity(lexeme.len());
1764    for segment in segments {
1765        if let InterpSegment::Chunk(text) = segment {
1766            out.push_str(&text);
1767        }
1768    }
1769    Ok(out)
1770}
1771
1772/// If a `---` doc-block marker line starts at or shortly after `pos` (which
1773/// must be at a line boundary), return the byte offset just past the marker
1774/// line (after the terminating newline, or at EOF), and the marker's dash
1775/// count (three or more). The doc-block grammar requires the marker to be
1776/// alone on its line; leading horizontal whitespace is allowed and ignored.
1777fn doc_block_open_at(source: &str, pos: usize) -> Option<(usize, usize)> {
1778    let bytes = source.as_bytes();
1779    if !at_line_start(source, pos) {
1780        return None;
1781    }
1782    // Skip leading horizontal whitespace.
1783    let mut i = pos;
1784    while i < bytes.len() && (bytes[i] == b' ' || bytes[i] == b'\t') {
1785        i += 1;
1786    }
1787    if i + 3 > bytes.len() {
1788        return None;
1789    }
1790    if &bytes[i..i + 3] != b"---" {
1791        return None;
1792    }
1793    let dash_start = i;
1794    i += 3;
1795    // The marker may have additional trailing dashes (per spec "three or more
1796    // consecutive hyphens"). Consume them.
1797    while i < bytes.len() && bytes[i] == b'-' {
1798        i += 1;
1799    }
1800    let dashes = i - dash_start;
1801    // After the dashes, allow only horizontal whitespace then newline/EOF.
1802    while i < bytes.len() && (bytes[i] == b' ' || bytes[i] == b'\t' || bytes[i] == b'\r') {
1803        i += 1;
1804    }
1805    if i == bytes.len() {
1806        return Some((i, dashes));
1807    }
1808    if bytes[i] == b'\n' {
1809        return Some((i + 1, dashes));
1810    }
1811    None
1812}
1813
1814/// Find the next closing marker line at or after `pos`: a marker of exactly
1815/// `dashes` dashes, the opener's count (#1885), as with a Markdown code fence.
1816/// A marker line of any other length is content, so a longer fence can hold a
1817/// shorter one. Returns `(start_of_line, end_of_line)` (`end_of_line` is just
1818/// past the terminating newline, or at EOF).
1819fn doc_block_close(source: &str, mut pos: usize, dashes: usize) -> Option<(usize, usize)> {
1820    let bytes = source.as_bytes();
1821    while pos < bytes.len() {
1822        // Advance pos to the start of a line.
1823        let line_start = pos;
1824        // Find the end of this line.
1825        let mut line_end = line_start;
1826        while line_end < bytes.len() && bytes[line_end] != b'\n' {
1827            line_end += 1;
1828        }
1829        // Check this line.
1830        if let Some((end, n)) = doc_block_open_at(source, line_start)
1831            && n == dashes
1832        {
1833            return Some((line_start, end));
1834        }
1835        // Move to the next line.
1836        pos = if line_end < bytes.len() {
1837            line_end + 1
1838        } else {
1839            line_end
1840        };
1841    }
1842    None
1843}
1844
1845/// Returns true if byte offset `pos` is at a line start (column 0).
1846/// #1888: true when only horizontal whitespace precedes `pos` on its line.
1847fn only_indent_before(bytes: &[u8], pos: usize) -> bool {
1848    bytes[..pos]
1849        .iter()
1850        .rev()
1851        .take_while(|&&b| b != b'\n')
1852        .all(|&b| matches!(b, b' ' | b'\t' | b'\r'))
1853}
1854
1855/// #2203: a `--- text` one-line doc starts at `pos`: three or more dashes, a
1856/// space or tab, then something other than whitespace on the line. A marker
1857/// with only whitespace after it is a doc-block fence, which
1858/// [`doc_block_open_at`] has already taken.
1859fn doc_line_marker(bytes: &[u8], pos: usize) -> bool {
1860    let dashes = bytes[pos..].iter().take_while(|&&b| b == b'-').count();
1861    if dashes < 3 || !matches!(bytes.get(pos + dashes), Some(b' ' | b'\t')) {
1862        return false;
1863    }
1864    bytes[pos + dashes..]
1865        .iter()
1866        .take_while(|&&b| b != b'\n')
1867        .any(|b| !b.is_ascii_whitespace())
1868}
1869
1870/// Push a [`TokenKind::DocLine`] from `start` through the end of its line,
1871/// newline included, and return the position after it.
1872fn push_doc_line(tokens: &mut Vec<Token>, bytes: &[u8], start: usize, file: FileId) -> usize {
1873    let mut pos = start;
1874    while pos < bytes.len() && bytes[pos] != b'\n' {
1875        pos += 1;
1876    }
1877    if pos < bytes.len() {
1878        pos += 1;
1879    }
1880    tokens.push(Token {
1881        kind: TokenKind::DocLine,
1882        span: Span::new_in(file, start, pos),
1883    });
1884    pos
1885}
1886
1887/// Push a [`TokenKind::Comment`] from `start` up to (not including) the end of
1888/// its line, and return the position after it.
1889fn push_comment(tokens: &mut Vec<Token>, bytes: &[u8], start: usize, file: FileId) -> usize {
1890    let mut pos = start;
1891    while pos < bytes.len() && bytes[pos] != b'\n' {
1892        pos += 1;
1893    }
1894    tokens.push(Token {
1895        kind: TokenKind::Comment,
1896        span: Span::new_in(file, start, pos),
1897    });
1898    pos
1899}
1900
1901/// #2203: the `bynk.lex.slash_doc` error for a `///` at `pos`, with the fix to
1902/// `---` (and a separating space when text follows straight on).
1903fn slash_doc_error(bytes: &[u8], pos: usize, file: FileId) -> CompileError {
1904    let marker = Span::new_in(file, pos, pos + 3);
1905    let fix = match bytes.get(pos + 3) {
1906        None | Some(b' ' | b'\t' | b'\r' | b'\n') => "---",
1907        Some(_) => "--- ",
1908    };
1909    CompileError::new(
1910        "bynk.lex.slash_doc",
1911        marker,
1912        "`///` is not a doc comment in Bynk; a doc is written with dashes",
1913    )
1914    .with_note(
1915        "a one-line doc is `--- text`, and a longer doc is a block between two `---` lines; \
1916         a comment is `//`",
1917    )
1918    .with_suggestion(
1919        "write `---`",
1920        vec![(marker, fix.to_string())],
1921        Applicability::MachineApplicable,
1922    )
1923}
1924
1925/// The text of a [`TokenKind::DocLine`] token: everything after the marker,
1926/// less one separating space or tab, less a closer (#2203: a final run of
1927/// exactly the opener's dashes, preceded by whitespace, with that whitespace),
1928/// and less the line ending. Further indentation is kept, so a doc line can
1929/// indent a Markdown code block. A legacy `--|` line (#1888) has no closer.
1930pub fn doc_line_text(source: &str, span: Span) -> &str {
1931    let slice = source[span.range()].trim_end_matches(['\n', '\r']);
1932    if let Some(rest) = slice.strip_prefix("--|") {
1933        return rest.strip_prefix(' ').unwrap_or(rest);
1934    }
1935    let dashes = slice.bytes().take_while(|&b| b == b'-').count();
1936    let rest = &slice[dashes..];
1937    let rest = rest.strip_prefix([' ', '\t']).unwrap_or(rest);
1938    let body = rest.trim_end_matches([' ', '\t']);
1939    let run = body.len() - body.trim_end_matches('-').len();
1940    if run == dashes {
1941        let before = &body[..body.len() - run];
1942        if before.is_empty() || before.ends_with([' ', '\t']) {
1943            return before.trim_end_matches([' ', '\t']);
1944        }
1945    }
1946    rest
1947}
1948
1949/// #2203: the source spelling of a one-line doc whose text is `text`: `--- `
1950/// and the text, or a `----` marker when the text ends in a whitespace-preceded
1951/// run of three dashes (which a `---` marker would read as its closer). Empty
1952/// text is spelled with a closer, `--- ---`, since a bare `---` opens a block.
1953pub fn one_line_doc(text: &str) -> String {
1954    let body = text.trim_end_matches([' ', '\t']);
1955    if body.trim().is_empty() {
1956        return "--- ---".to_string();
1957    }
1958    let run = body.len() - body.trim_end_matches('-').len();
1959    let before = &body[..body.len() - run];
1960    let closer_shaped = run == 3 && (before.is_empty() || before.ends_with([' ', '\t']));
1961    let marker = if closer_shaped { "----" } else { "---" };
1962    format!("{marker} {text}")
1963}
1964
1965/// #1885: the dash count of the fence a doc block holding `doc` is printed
1966/// with: one more than the longest marker-shaped line in it (a line of three
1967/// or more dashes alone, surrounding whitespace aside), and never fewer than
1968/// three. A shorter fence would close at that line.
1969pub fn doc_fence_len(doc: &str) -> usize {
1970    doc.lines()
1971        .map(str::trim)
1972        .filter(|l| l.len() >= 3 && l.bytes().all(|b| b == b'-'))
1973        .map(|l| l.len() + 1)
1974        .fold(3, usize::max)
1975}
1976
1977/// #2203: whether a [`TokenKind::DocLine`] token is spelled the legacy way,
1978/// `--|` (#1888), rather than `--- text`.
1979pub fn doc_line_is_legacy(source: &str, span: Span) -> bool {
1980    source[span.range()].starts_with("--|")
1981}
1982
1983/// #2203: whether a [`TokenKind::Comment`] token is spelled the legacy way,
1984/// `--`, rather than `//`.
1985pub fn comment_is_legacy(source: &str, span: Span) -> bool {
1986    source[span.range()].starts_with("--")
1987}
1988
1989/// #2203 (DECISION E): the `bynk.lex.legacy_comment` error for the legacy `--`
1990/// comment at `span` (a [`TokenKind::Comment`] token), with the fix to `//`.
1991pub fn legacy_comment_error(span: Span) -> CompileError {
1992    let marker = Span::new_in(span.file, span.start, span.start + 2);
1993    CompileError::new(
1994        "bynk.lex.legacy_comment",
1995        marker,
1996        "`--` no longer starts a comment; a line comment is `//`",
1997    )
1998    .with_note(
1999        "`bynk fmt` rewrites every legacy comment; for subtraction of a negation, write `a - -b`",
2000    )
2001    .with_suggestion(
2002        "write `//`",
2003        vec![(marker, "//".to_string())],
2004        Applicability::MachineApplicable,
2005    )
2006}
2007
2008/// #2203 (DECISION E): the `bynk.lex.legacy_doc_line` error for the legacy
2009/// `--|` doc line at `span` (a [`TokenKind::DocLine`] token), with the fix to
2010/// `--- text`. A `--|` with no text has no one-line spelling (a bare `---`
2011/// opens a block), so it gets no fix.
2012pub fn legacy_doc_line_error(source: &str, span: Span) -> CompileError {
2013    let marker = Span::new_in(span.file, span.start, span.start + 3);
2014    let err = CompileError::new(
2015        "bynk.lex.legacy_doc_line",
2016        marker,
2017        "`--|` no longer starts a doc; a one-line doc is `--- text`",
2018    );
2019    let text = doc_line_text(source, span);
2020    if text.trim().is_empty() {
2021        return err.with_note(
2022            "a one-line doc holds text; a doc of more than one paragraph is a block between \
2023             two `---` lines",
2024        );
2025    }
2026    let line = Span::new_in(span.file, span.start, doc_line_text_range(source, span).end);
2027    err.with_note("`bynk fmt` rewrites every legacy doc line")
2028        .with_suggestion(
2029            "write `--- `",
2030            vec![(line, one_line_doc(text))],
2031            Applicability::MachineApplicable,
2032        )
2033}
2034
2035/// #1888: the byte range of a doc line's text within `source`, as
2036/// [`doc_line_text`] returns it, for callers that map positions in a doc
2037/// back to the source (document links).
2038pub fn doc_line_text_range(source: &str, span: Span) -> std::ops::Range<usize> {
2039    let text = doc_line_text(source, span);
2040    let start = text.as_ptr() as usize - source.as_ptr() as usize;
2041    start..start + text.len()
2042}
2043
2044fn at_line_start(source: &str, pos: usize) -> bool {
2045    if pos == 0 {
2046        return true;
2047    }
2048    let bytes = source.as_bytes();
2049    bytes[pos - 1] == b'\n'
2050}
2051
2052/// The doc-block body as a byte range into `source` — leading/trailing `---`
2053/// marker lines stripped, no further processing (unlike [`doc_block_content`],
2054/// which additionally strips a common per-line indent — not offset-preserving).
2055/// Callers that need to map a position in the body back to `source` (e.g.
2056/// document-link spans) use this instead of re-deriving it from the string
2057/// `doc_block_content` returns.
2058pub fn doc_block_body_range(source: &str, span: Span) -> Option<std::ops::Range<usize>> {
2059    let slice = &source[span.range()];
2060    // Drop the first line (opening marker).
2061    let after_open_rel = slice.find('\n')? + 1;
2062    let after_open = &slice[after_open_rel..];
2063    let bytes = after_open.as_bytes();
2064    // Trim the trailing closing-marker line.
2065    let mut i = bytes.len();
2066    if i > 0 && bytes[i - 1] == b'\n' {
2067        i -= 1;
2068    }
2069    while i > 0 && matches!(bytes[i - 1], b' ' | b'\t' | b'\r') {
2070        i -= 1;
2071    }
2072    while i > 0 && bytes[i - 1] == b'-' {
2073        i -= 1;
2074    }
2075    if i > 0 && bytes[i - 1] == b'\n' {
2076        i -= 1;
2077    }
2078    let start = span.range().start + after_open_rel;
2079    Some(start..start + i)
2080}
2081
2082/// Extract the body content of a doc-block token from its source span.
2083/// Strips the leading and trailing `---` marker lines and returns the body
2084/// verbatim. If every non-empty content line begins with the same horizontal
2085/// whitespace prefix (e.g., because the doc block sits inside a brace-form
2086/// commons body), that common prefix is removed so the body reads naturally
2087/// when emitted as JSDoc.
2088pub fn doc_block_content(source: &str, span: Span) -> String {
2089    let Some(range) = doc_block_body_range(source, span) else {
2090        return String::new();
2091    };
2092    let body = &source[range];
2093
2094    // Compute the common leading-whitespace prefix across all non-empty lines
2095    // and strip it. This lets writers indent the doc block alongside the
2096    // declaration it documents without bleeding the indent into the JSDoc.
2097    let common: Option<usize> = body
2098        .lines()
2099        .filter(|l| !l.trim().is_empty())
2100        .map(|l| l.bytes().take_while(|&b| b == b' ' || b == b'\t').count())
2101        .min();
2102    let strip = common.unwrap_or(0);
2103    if strip == 0 {
2104        return body.to_string();
2105    }
2106    let mut out = String::with_capacity(body.len());
2107    let mut first = true;
2108    for line in body.lines() {
2109        if !first {
2110            out.push('\n');
2111        }
2112        first = false;
2113        if line.trim().is_empty() {
2114            // Preserve blank lines.
2115            continue;
2116        }
2117        let leading: usize = line
2118            .bytes()
2119            .take_while(|&b| b == b' ' || b == b'\t')
2120            .count();
2121        let drop = strip.min(leading);
2122        out.push_str(&line[drop..]);
2123    }
2124    out
2125}
2126
2127/// Extract the body of a `Comment` trivia token: everything after the
2128/// leading `//` marker, preserving its inline whitespace verbatim. Used by
2129/// the parser when attaching comments to declarations.
2130///
2131/// #2203: a legacy `--` comment's body is what follows its `--`, so the
2132/// formatter prints it after `//`. A legacy body that starts with a dash (a
2133/// `--- Helpers ---` divider, read by [`tokenize_legacy`]) keeps all of its
2134/// dashes behind a space instead, as `// --- Helpers ---`, and a legacy
2135/// `--|` after code (#1888) drops its `|`.
2136pub fn comment_body(source: &str, span: Span) -> std::borrow::Cow<'_, str> {
2137    let slice = &source[span.range()];
2138    if let Some(rest) = slice.strip_prefix("//") {
2139        return rest.into();
2140    }
2141    match slice.strip_prefix("--") {
2142        Some(rest) if rest.starts_with('-') => format!(" {slice}").into(),
2143        // A `--|` after code was a comment (#1888); its `|` was not text.
2144        Some(rest) => rest.strip_prefix('|').unwrap_or(rest).into(),
2145        None => slice.into(),
2146    }
2147}
2148
2149/// Returns true if there is a blank line (a line containing only whitespace)
2150/// in `source` strictly between byte offsets `from` (inclusive) and `to`
2151/// (exclusive). Used by the parser to detect orphan doc blocks.
2152///
2153/// A doc-block token's span ends just past the closing-marker line's
2154/// terminating newline. So if the next declaration begins on the immediately
2155/// following line, the substring between contains no newline (only optional
2156/// indentation). Any newline in the substring therefore implies at least one
2157/// entirely-blank line separating the doc from the declaration.
2158pub fn has_blank_line_between(source: &str, from: usize, to: usize) -> bool {
2159    if to <= from {
2160        return false;
2161    }
2162    let bytes = source.as_bytes();
2163    let mut i = from;
2164    while i < to {
2165        if bytes[i] == b'\n' {
2166            return true;
2167        }
2168        if !matches!(bytes[i], b' ' | b'\t' | b'\r') {
2169            return false;
2170        }
2171        i += 1;
2172    }
2173    false
2174}
2175
2176#[cfg(test)]
2177mod tests {
2178    use super::*;
2179
2180    fn kinds(source: &str) -> Vec<TokenKind> {
2181        tokenize(source)
2182            .unwrap()
2183            .into_iter()
2184            .map(|t| t.kind)
2185            .collect()
2186    }
2187
2188    #[test]
2189    fn keywords_and_idents() {
2190        use TokenKind::*;
2191        assert_eq!(
2192            kinds("commons type fn where true false Int String Bool foo bar"),
2193            vec![
2194                Commons, Type, Fn, Where, True, False, Int, String, Bool, Ident, Ident
2195            ],
2196        );
2197        // #548: `and` is no longer a keyword — it lexes as an ordinary identifier.
2198        assert_eq!(kinds("and"), vec![Ident]);
2199    }
2200
2201    #[test]
2202    fn deeply_nested_interpolation_is_bounded_not_overflowed() {
2203        // `"\("\("\(…` mutually recurses lex_string <-> scan_hole, one frame per
2204        // level, and an unbounded scanner overflows `tokenize` and aborts the
2205        // process (#713). Well past the limit it must return a bounded-depth
2206        // diagnostic instead. The holes are left open so the depth guard, not a
2207        // later `)`, stops the scan.
2208        let depth = crate::MAX_NESTING_DEPTH + 8;
2209        let src = format!("\"{}", "\\(\"".repeat(depth));
2210        let err = tokenize(&src).unwrap_err();
2211        assert_eq!(err.category, "bynk.lex.interpolation_too_deep");
2212    }
2213
2214    #[test]
2215    fn integer_and_string_literals() {
2216        use TokenKind::*;
2217        assert_eq!(
2218            kinds(r#"0 42 "hello" "with\nescape""#),
2219            vec![IntLit, IntLit, StrLit, StrLit]
2220        );
2221    }
2222
2223    #[test]
2224    fn operators() {
2225        use TokenKind::*;
2226        assert_eq!(
2227            kinds("-> == != <= >= && || + - * / % ! = < > ( ) { } [ ] , : . @"),
2228            vec![
2229                Arrow, EqEq, BangEq, LtEq, GtEq, AmpAmp, PipePipe, Plus, Minus, Star, Slash,
2230                Percent, Bang, Eq, Lt, Gt, LParen, RParen, LBrace, RBrace, LBracket, RBracket,
2231                Comma, Colon, Dot, At,
2232            ],
2233        );
2234    }
2235
2236    #[test]
2237    fn dot_family_maximal_munch() {
2238        // Events track slice 1 (spine #936): `..` must lex as one `DotDot`
2239        // token, not two `Dot`s — a real token keeps agreement with
2240        // tree-sitter (which declares `".."` as one literal), so a
2241        // whitespace-split `. .` cannot silently parse where a real `..`
2242        // is required. Also confirms `...`/`..`/`.` don't shadow each other
2243        // regardless of declaration order (logos maximal-munch).
2244        use TokenKind::*;
2245        assert_eq!(
2246            kinds("a .. b ... c . d . ."),
2247            vec![Ident, DotDot, Ident, DotDotDot, Ident, Dot, Ident, Dot, Dot,],
2248        );
2249    }
2250
2251    #[test]
2252    fn line_comments_emitted_as_trivia() {
2253        // v1.1: line comments are preserved as Comment tokens so the
2254        // formatter can attach and re-emit them.
2255        use TokenKind::*;
2256        let src = "// a comment\ntype X = Int // trailing\n";
2257        assert_eq!(kinds(src), vec![Comment, Type, Ident, Eq, Int, Comment],);
2258    }
2259
2260    #[test]
2261    fn comment_body_extracts_text_after_marker() {
2262        let toks = tokenize("// hello world\n").unwrap();
2263        assert_eq!(toks.len(), 1);
2264        assert_eq!(toks[0].kind, TokenKind::Comment);
2265        assert_eq!(
2266            comment_body("// hello world\n", toks[0].span),
2267            " hello world"
2268        );
2269    }
2270
2271    #[test]
2272    fn comment_does_not_consume_newline() {
2273        // Two adjacent comment lines should produce two distinct tokens
2274        // — the newline between them is not part of either comment's span.
2275        let toks = tokenize("// one\n// two\n").unwrap();
2276        assert_eq!(toks.len(), 2);
2277        assert!(toks.iter().all(|t| t.kind == TokenKind::Comment));
2278    }
2279
2280    /// #2203: `//` is a comment anywhere, with no whitespace rule, and `--` is
2281    /// two `-` operators unless it is spelled like a legacy comment.
2282    #[test]
2283    fn slash_slash_is_a_comment_and_dash_dash_is_subtraction() {
2284        use TokenKind::*;
2285        assert_eq!(kinds("a//b"), vec![Ident, Comment]);
2286        assert_eq!(kinds("a--b"), vec![Ident, Minus, Minus, Ident]);
2287        assert_eq!(kinds("x--\ny"), vec![Ident, Minus, Minus, Ident]);
2288        assert_eq!(kinds("x--"), vec![Ident, Minus, Minus]);
2289        assert_eq!(kinds("a - -b"), vec![Ident, Minus, Minus, Ident]);
2290        assert_eq!(kinds("a --b"), vec![Ident, Minus, Minus, Ident]);
2291        // A `////` ruler is a comment, as in Rust.
2292        assert_eq!(kinds("////////\n"), vec![Comment]);
2293        assert_eq!(kinds("// -------\n"), vec![Comment]);
2294    }
2295
2296    /// #2203 (DECISION E): a `--` at the start of a line or after whitespace,
2297    /// followed by a space or the end of the line, lexes as a comment still,
2298    /// spelled the legacy way, so it is never read as `- -`.
2299    #[test]
2300    fn a_legacy_dash_dash_comment_still_lexes_as_a_comment() {
2301        use TokenKind::*;
2302        assert_eq!(kinds("a -- c"), vec![Ident, Comment]);
2303        assert_eq!(kinds("-- c"), vec![Comment]);
2304        assert_eq!(kinds("a\n--\nb"), vec![Ident, Comment, Ident]);
2305        assert_eq!(kinds("x --"), vec![Ident, Comment]);
2306        assert_eq!(
2307            kinds("a: Int, --| note"),
2308            vec![Ident, Colon, Int, Comma, Comment]
2309        );
2310        let src = "x = 1 -- note\n";
2311        let toks = tokenize(src).unwrap();
2312        let c = toks.last().unwrap().span;
2313        assert!(comment_is_legacy(src, c));
2314        assert_eq!(comment_body(src, c), " note");
2315        let err = legacy_comment_error(c);
2316        assert_eq!(err.category, "bynk.lex.legacy_comment");
2317        assert_eq!(err.suggestions[0].edits[0].1, "//");
2318        assert_eq!(&src[err.suggestions[0].edits[0].0.range()], "--");
2319    }
2320
2321    /// #2203 (DECISION C): `--- text` first on its line is a one-line doc; its
2322    /// closer is a final run of exactly the opener's dashes after whitespace.
2323    #[test]
2324    fn a_dash_marker_with_text_is_a_doc_line() {
2325        use TokenKind::*;
2326        assert_eq!(kinds("--- doc\ntype"), vec![DocLine, Type]);
2327        assert_eq!(kinds("  ---- doc\n\t--- x"), vec![DocLine, DocLine]);
2328        let text = |src: &str| {
2329            let toks = tokenize(src).unwrap();
2330            assert_eq!(toks[0].kind, DocLine, "{src}");
2331            doc_line_text(src, toks[0].span).to_string()
2332        };
2333        assert_eq!(text("--- The repo.\n"), "The repo.");
2334        assert_eq!(text("--- The repo. ---\n"), "The repo.");
2335        assert_eq!(text("---- The repo. ----\r\n"), "The repo.");
2336        // A trailing run of another length is text.
2337        assert_eq!(text("--- a -- b ----\n"), "a -- b ----");
2338        assert_eq!(text("---- a ---\n"), "a ---");
2339        assert_eq!(text("--- a---\n"), "a---");
2340        // Further indentation is kept.
2341        assert_eq!(text("---   indented\n"), "  indented");
2342        // A marker alone is a block fence, and a `---` with no space after it
2343        // is not a doc.
2344        assert_eq!(kinds("---\nx\n---\n"), vec![DocBlock]);
2345        assert_eq!(kinds("---x\n"), vec![Minus, Minus, Minus, Ident]);
2346        // After code, `---` is operators (the parser rejects it).
2347        assert_eq!(kinds("a --- b"), vec![Ident, Minus, Minus, Minus, Ident]);
2348        let src = "  --- A doc.  \nx";
2349        let toks = tokenize(src).unwrap();
2350        assert_eq!(&src[doc_line_text_range(src, toks[0].span)], "A doc.  ");
2351    }
2352
2353    /// #2203: the one-line spelling of a doc's text never reads its own end as
2354    /// a closer.
2355    #[test]
2356    fn one_line_doc_spelling_round_trips() {
2357        for text in [
2358            "The repo.",
2359            "a ---",
2360            "---",
2361            "----",
2362            "a -- b",
2363            "  indented",
2364            "",
2365        ] {
2366            let src = format!("{}\n", one_line_doc(text));
2367            let toks = tokenize(&src).unwrap();
2368            assert_eq!(toks[0].kind, TokenKind::DocLine, "{src}");
2369            assert_eq!(doc_line_text(&src, toks[0].span), text, "{src}");
2370        }
2371    }
2372
2373    /// #1888's `--|` first on its line is a doc line still, spelled the legacy
2374    /// way; its fix is `--- text`.
2375    #[test]
2376    fn a_legacy_bar_doc_line_still_lexes_as_a_doc_line() {
2377        use TokenKind::{DocLine, Type};
2378        assert_eq!(kinds("--| doc\ntype"), vec![DocLine, Type]);
2379        assert_eq!(kinds("  --| doc\n\t--|\n"), vec![DocLine, DocLine]);
2380        let src = "  --|  indented  \r\n--|bare\n--|";
2381        let toks = tokenize(src).unwrap();
2382        assert!(doc_line_is_legacy(src, toks[0].span));
2383        assert_eq!(&src[toks[0].span.range()], "--|  indented  \r\n");
2384        assert_eq!(doc_line_text(src, toks[0].span), " indented  ");
2385        assert_eq!(doc_line_text(src, toks[1].span), "bare");
2386        assert_eq!(doc_line_text(src, toks[2].span), "");
2387        let fix = |i: usize| {
2388            let err = legacy_doc_line_error(src, toks[i].span);
2389            assert_eq!(err.category, "bynk.lex.legacy_doc_line");
2390            err.suggestions
2391                .first()
2392                .map(|s| (src[s.edits[0].0.range()].to_string(), s.edits[0].1.clone()))
2393        };
2394        assert_eq!(
2395            fix(1),
2396            Some(("--|bare".to_string(), "--- bare".to_string()))
2397        );
2398        assert_eq!(fix(2), None, "an empty `--|` has no one-line spelling");
2399    }
2400
2401    /// #2203: `///` first on its line is `bynk.lex.slash_doc`, fixed to `---`.
2402    #[test]
2403    fn a_slash_doc_is_an_error_with_a_fix() {
2404        for (src, fix) in [
2405            ("/// A doc.\n", "---"),
2406            ("///A doc.\n", "--- "),
2407            ("  ///", "---"),
2408        ] {
2409            let err = tokenize(src).unwrap_err();
2410            assert_eq!(err.category, "bynk.lex.slash_doc");
2411            let (span, text) = &err.suggestions[0].edits[0];
2412            assert_eq!(&src[span.range()], "///");
2413            assert_eq!(text, fix);
2414        }
2415    }
2416
2417    /// #2203: a legacy read takes ADR 0188 D1's rule, so a `--- Helpers ---`
2418    /// divider and a `--note` are comments, as they were before `//`.
2419    #[test]
2420    fn a_legacy_read_keeps_the_old_comment_rule() {
2421        let src = "--- Helpers ---\nx --note\na--b\n--| doc\n// new\n";
2422        let toks = tokenize_legacy(src).unwrap();
2423        let kinds: Vec<_> = toks.iter().map(|t| t.kind).collect();
2424        use TokenKind::*;
2425        assert_eq!(
2426            kinds,
2427            vec![
2428                Comment, Ident, Comment, Ident, Minus, Minus, Ident, DocLine, Comment
2429            ]
2430        );
2431        assert_eq!(comment_body(src, toks[0].span), " --- Helpers ---");
2432        assert_eq!(comment_body(src, toks[2].span), "note");
2433    }
2434
2435    #[test]
2436    fn unterminated_string_is_error() {
2437        let err = tokenize("\"oops\n").unwrap_err();
2438        assert_eq!(err.category, "bynk.lex.unterminated_string");
2439    }
2440
2441    #[test]
2442    fn integer_overflow_is_error() {
2443        let err = tokenize("99999999999999999999").unwrap_err();
2444        assert_eq!(err.category, "bynk.lex.integer_overflow");
2445    }
2446
2447    #[test]
2448    fn an_int_literal_must_be_a_safe_integer() {
2449        // #1657: the `Int` range is ±(2^53 − 1). The largest safe integer lexes;
2450        // one more, and i64-range values above it, do not.
2451        assert!(tokenize("9007199254740991").is_ok());
2452        assert!(tokenize("9_007_199_254_740_991").is_ok());
2453        for over in [
2454            "9007199254740992",
2455            "9007199254740993",
2456            "9223372036854775807",
2457        ] {
2458            let err = tokenize(over).unwrap_err();
2459            assert_eq!(err.category, "bynk.lex.integer_overflow", "{over}");
2460        }
2461    }
2462
2463    #[test]
2464    fn range_bounds_never_lex_as_a_float() {
2465        use TokenKind::*;
2466        // #2699: a float needs a digit on both sides of its `.`, so every range
2467        // spelling is `IntLit DotDot IntLit`, with the sign a separate `Minus`.
2468        assert_eq!(kinds("0..9"), vec![IntLit, DotDot, IntLit]);
2469        assert_eq!(kinds("18.."), vec![IntLit, DotDot]);
2470        assert_eq!(kinds("..-1"), vec![DotDot, Minus, IntLit]);
2471        assert_eq!(kinds("-5..-1"), vec![Minus, IntLit, DotDot, Minus, IntLit]);
2472        assert_eq!(kinds("1_000..2_000"), vec![IntLit, DotDot, IntLit]);
2473    }
2474
2475    #[test]
2476    fn a_decimal_literal_is_one_token_with_a_d_suffix() {
2477        use TokenKind::*;
2478        // #2622: digits, an optional fraction, a trailing `d`.
2479        assert_eq!(kinds("1.20d"), vec![DecimalLit]);
2480        assert_eq!(kinds("5d"), vec![DecimalLit]);
2481        assert_eq!(kinds("1_000.50d"), vec![DecimalLit]);
2482        // No `d` is still an `Int` or a `Float`, and the other numeric forms are
2483        // unchanged (a duration unit, a method on a literal, a range).
2484        assert_eq!(kinds("1.20"), vec![FloatLit]);
2485        assert_eq!(kinds("5.days"), vec![IntLit, Dot, Ident]);
2486        assert_eq!(
2487            kinds("2.5.round()"),
2488            vec![FloatLit, Dot, Ident, LParen, RParen]
2489        );
2490        assert_eq!(kinds("0..9"), vec![IntLit, DotDot, IntLit]);
2491        // The sign stays a separate operator; there is no exponent form, so an
2492        // exponent is a float followed by an identifier.
2493        assert_eq!(kinds("-1.5d"), vec![Minus, DecimalLit]);
2494        assert_eq!(kinds("1e5d"), vec![FloatLit, Ident]);
2495        // `Decimal` is a keyword.
2496        assert_eq!(kinds("Decimal"), vec![Decimal]);
2497    }
2498
2499    #[test]
2500    fn a_decimal_literal_obeys_the_decimal_limits() {
2501        let frac = |n: usize| format!("0.{}d", "1".repeat(n));
2502        assert!(tokenize(&frac(100)).is_ok());
2503        assert!(tokenize(&frac(101)).is_err());
2504        assert!(tokenize(&format!("{}d", "9".repeat(1000))).is_ok());
2505        assert!(tokenize(&format!("{}d", "9".repeat(1001))).is_err());
2506    }
2507
2508    #[test]
2509    fn digit_separators_lex_as_one_number() {
2510        use TokenKind::*;
2511        // v0.142 (ADR 0166): `_` between digit groups keeps the literal a single
2512        // token for both Int and Float.
2513        assert_eq!(kinds("1_048_576"), vec![IntLit]);
2514        assert_eq!(kinds("1_000.500_5"), vec![FloatLit]);
2515        assert_eq!(kinds("1_000e1_0"), vec![FloatLit]);
2516        // A separator-carrying literal that is in range still lexes (the value is
2517        // validated after stripping the separators).
2518        assert!(tokenize("9_007_199_254_740_991").is_ok());
2519        // Overflow is still caught on the separator-free value.
2520        let err = tokenize("9_999_999_999_999_999_999_9").unwrap_err();
2521        assert_eq!(err.category, "bynk.lex.integer_overflow");
2522    }
2523
2524    #[test]
2525    fn strip_digit_separators_removes_underscores() {
2526        assert_eq!(strip_digit_separators("1_048_576"), "1048576");
2527        assert_eq!(strip_digit_separators("42"), "42");
2528    }
2529
2530    #[test]
2531    fn unexpected_character_is_error() {
2532        let err = tokenize("type X = Int $").unwrap_err();
2533        assert_eq!(err.category, "bynk.lex.unexpected_character");
2534    }
2535
2536    #[test]
2537    fn v0_1_keywords() {
2538        use TokenKind::*;
2539        assert_eq!(
2540            kinds("let if else Ok Err Result ValidationError"),
2541            vec![Let, If, Else, Ok, Err, Result, ValidationError],
2542        );
2543    }
2544
2545    #[test]
2546    fn question_token() {
2547        use TokenKind::*;
2548        assert_eq!(kinds("x?"), vec![Ident, Question]);
2549    }
2550
2551    #[test]
2552    fn v0_2_keywords() {
2553        use TokenKind::*;
2554        assert_eq!(
2555            kinds("enum match Option record self Some None is"),
2556            vec![Enum, Match, Option, Record, Self_, Some, None, Is],
2557        );
2558    }
2559
2560    #[test]
2561    fn pipe_and_pipe_pipe_disambiguated() {
2562        use TokenKind::*;
2563        assert_eq!(kinds("| || |"), vec![Pipe, PipePipe, Pipe]);
2564    }
2565
2566    #[test]
2567    fn v0_7_keywords() {
2568        use TokenKind::*;
2569        assert_eq!(kinds("expect suite case"), vec![Expect, Suite, Case],);
2570        // v0.118: `mocks` and `wires` are retired — plain identifiers now.
2571        assert_eq!(kinds("mocks wires"), vec![Ident, Ident]);
2572    }
2573
2574    #[test]
2575    fn fat_arrow_and_underscore() {
2576        use TokenKind::*;
2577        assert_eq!(kinds("_ =>"), vec![Underscore, FatArrow]);
2578    }
2579
2580    // -- v0.43 string interpolation --
2581
2582    #[test]
2583    fn interp_string_is_one_token() {
2584        use TokenKind::*;
2585        assert_eq!(kinds(r#""Hello, \(name)!""#), vec![InterpStr]);
2586        // A plain string (no hole) stays a `StrLit`, via the logos path.
2587        assert_eq!(kinds(r#""Hello, world""#), vec![StrLit]);
2588    }
2589
2590    #[test]
2591    fn interp_balances_nested_parens_and_strings() {
2592        use TokenKind::*;
2593        // The `)` inside `f(x)` must not close the hole early.
2594        assert_eq!(kinds(r#""= \(f(x))""#), vec![InterpStr]);
2595        // A `)` inside a nested string inside the hole is also ignored.
2596        assert_eq!(kinds(r#""= \(label(")"))""#), vec![InterpStr]);
2597        // A nested interpolated string inside a hole.
2598        assert_eq!(kinds(r#""out \("in \(x)")""#), vec![InterpStr]);
2599    }
2600
2601    // Issue #473: hole-expanding tokenisation makes identifiers inside `\(…)`
2602    // visible to the LSP's token-based cursor resolution.
2603    #[test]
2604    fn expanding_holes_exposes_hole_identifiers() {
2605        use TokenKind::*;
2606        let expand = |src: &str| {
2607            tokenize_expanding_holes(src)
2608                .unwrap()
2609                .into_iter()
2610                .map(|t| t.kind)
2611                .collect::<Vec<_>>()
2612        };
2613        // The opaque `InterpStr` is replaced by its hole's tokens; the chunk
2614        // text (`Hello, ` / `!`) carries none.
2615        assert_eq!(expand(r#""Hello, \(name)!""#), vec![Ident]);
2616        // A call hole exposes every token of the call expression.
2617        assert_eq!(expand(r#""= \(f(x))""#), vec![Ident, LParen, Ident, RParen]);
2618        // Nested interpolation recurses to the innermost hole's identifier.
2619        assert_eq!(expand(r#""out \("in \(x)")""#), vec![Ident]);
2620        // A plain (hole-free) string is untouched.
2621        assert_eq!(expand(r#""Hello, world""#), vec![StrLit]);
2622    }
2623
2624    #[test]
2625    fn expanding_holes_rebases_spans_to_absolute() {
2626        let src = r#""Hello, \(name)!""#;
2627        let toks = tokenize_expanding_holes(src).unwrap();
2628        let ident = toks
2629            .iter()
2630            .find(|t| t.kind == TokenKind::Ident)
2631            .expect("the hole identifier is exposed");
2632        // The span points at `name` in the original source, not a hole-local 0.
2633        assert_eq!(&src[ident.span.range()], "name");
2634        assert_eq!(ident.span.start, src.find("name").unwrap());
2635    }
2636
2637    #[test]
2638    fn escaped_open_paren_is_not_a_hole() {
2639        use TokenKind::*;
2640        // `\\(` is a literal backslash followed by `(` — no hole, so the
2641        // string lexes as a plain `StrLit` on the logos path.
2642        assert_eq!(kinds(r#""a \\(b) c""#), vec![StrLit]);
2643    }
2644
2645    #[test]
2646    fn unterminated_hole_is_an_error() {
2647        // The hole runs to end of line without its closing `)`.
2648        let err = tokenize("\"value \\(x + 1\n\"").unwrap_err();
2649        assert_eq!(err.category, "bynk.lex.unterminated_interpolation");
2650    }
2651
2652    #[test]
2653    fn unterminated_interp_string_is_an_error() {
2654        // A hole closes but the string never does (newline before the `"`).
2655        let err = tokenize("\"value \\(x) more\n").unwrap_err();
2656        assert_eq!(err.category, "bynk.lex.unterminated_string");
2657    }
2658
2659    #[test]
2660    fn bad_escape_in_interp_string_is_an_error() {
2661        let err = tokenize(r#""a \q \(x)""#).unwrap_err();
2662        assert_eq!(err.category, "bynk.lex.bad_escape");
2663    }
2664
2665    /// The decoded value of the one string token in `src`.
2666    fn string_value(src: &str) -> String {
2667        let toks = tokenize(src).unwrap();
2668        assert_eq!(toks.len(), 1, "{src:?}");
2669        assert_eq!(toks[0].kind, TokenKind::StrLit, "{src:?}");
2670        decode_string_literal(&src[toks[0].span.range()], toks[0].span).unwrap()
2671    }
2672
2673    /// #2619: `\r`, `\0` and `\u{…}` join the escape set.
2674    #[test]
2675    fn new_escapes_decode() {
2676        assert_eq!(string_value(r#""a\r\nb""#), "a\r\nb");
2677        assert_eq!(string_value(r#""\0""#), "\0");
2678        assert_eq!(string_value(r#""\u{1F600}""#), "\u{1F600}");
2679        assert_eq!(string_value(r#""a\u{00A0}b""#), "a\u{A0}b");
2680        assert_eq!(string_value(r#""\u{41}\u{000041}""#), "AA");
2681        assert_eq!(string_value(r#""\u{10FFFF}""#), "\u{10FFFF}");
2682    }
2683
2684    #[test]
2685    fn bad_unicode_escapes_are_lexical_errors() {
2686        for src in [r#""\u{D800}""#, r#""\u{DFFF}""#, r#""\u{110000}""#] {
2687            assert_eq!(
2688                tokenize(src).unwrap_err().category,
2689                "bynk.lex.bad_unicode_escape",
2690                "{src}"
2691            );
2692        }
2693        for src in [
2694            r#""\u""#,
2695            r#""\u{}""#,
2696            r#""\u{1234567}""#,
2697            r#""\u{12""#,
2698            r#""\u{zz}""#,
2699        ] {
2700            assert_eq!(
2701                tokenize(src).unwrap_err().category,
2702                "bynk.lex.bad_escape",
2703                "{src}"
2704            );
2705        }
2706    }
2707
2708    #[test]
2709    fn raw_strings_keep_backslashes_and_do_not_interpolate() {
2710        assert_eq!(string_value(r#"r"\d+\.\d+""#), "\\d+\\.\\d+");
2711        assert_eq!(string_value(r#"r"a\(b)""#), "a\\(b)");
2712        assert_eq!(string_value(r###"r#"say "hi""#"###), "say \"hi\"");
2713        assert_eq!(string_value(r#"r"""#), "");
2714        // `r` followed by a space is an identifier then a string.
2715        use TokenKind::*;
2716        assert_eq!(kinds(r#"r "x""#), vec![Ident, StrLit]);
2717        assert_eq!(kinds(r#"bar"x""#), vec![Ident, StrLit]);
2718        // A raw string is not terminated by a newline.
2719        assert_eq!(
2720            tokenize("r\"abc\n\"").unwrap_err().category,
2721            "bynk.lex.unterminated_string"
2722        );
2723    }
2724
2725    #[test]
2726    fn multiline_strings_strip_the_closing_indentation() {
2727        let src = "\"\"\"\n    SELECT id\n      FROM t\n\n    \"\"\"";
2728        assert_eq!(string_value(src), "SELECT id\n  FROM t\n");
2729        // No indentation, and escapes still apply.
2730        assert_eq!(string_value("\"\"\"\na\\tb\n\"\"\""), "a\tb");
2731        // An empty body.
2732        assert_eq!(string_value("\"\"\"\n\"\"\""), "");
2733        // Quotes inside are fine; the raw form keeps backslashes.
2734        assert_eq!(
2735            string_value("\"\"\"\n  a \"q\" \"\"b\n  \"\"\""),
2736            "a \"q\" \"\"b"
2737        );
2738        assert_eq!(string_value("r\"\"\"\n  \\d+\n  \"\"\""), "\\d+");
2739    }
2740
2741    /// Decision D: newlines are `\n` whatever the source's line endings.
2742    #[test]
2743    fn multiline_newlines_are_normalised() {
2744        assert_eq!(string_value("\"\"\"\r\n  a\r\n  b\r\n  \"\"\""), "a\nb");
2745    }
2746
2747    #[test]
2748    fn multiline_with_a_hole_is_an_interpolated_string() {
2749        use TokenKind::*;
2750        assert_eq!(kinds("\"\"\"\n  hi \\(name)\n  \"\"\""), vec![InterpStr]);
2751    }
2752
2753    /// Pinned by review of #2619: edge cases of the multi-line rules.
2754    #[test]
2755    fn multiline_edge_cases() {
2756        // A hole at the start of an indented line: the margin is stripped
2757        // first, never inside the hole.
2758        let src = "\"\"\"\n    \\(a)\n      \\(b) x\n    \"\"\"";
2759        let toks = tokenize(src).unwrap();
2760        assert_eq!(toks[0].kind, TokenKind::InterpStr);
2761        let segs = split_interp(src, toks[0].span).unwrap();
2762        let shape: Vec<String> = segs
2763            .iter()
2764            .map(|s| match s {
2765                InterpSegment::Chunk(c) => format!("{c:?}"),
2766                InterpSegment::Hole(h) => src[h.range()].to_string(),
2767            })
2768            .collect();
2769        assert_eq!(shape, ["a", "\"\\n  \"", "b", "\" x\""]);
2770        // A whitespace-only line shallower than the margin is empty.
2771        assert_eq!(
2772            string_value("\"\"\"\n    a\n  \n    b\n    \"\"\""),
2773            "a\n\nb"
2774        );
2775        // Mixed tabs and spaces that do not match the margin exactly.
2776        let err = tokenize("\"\"\"\n\t  a\n    \"\"\"").unwrap_err();
2777        assert_eq!(err.category, "bynk.lex.multiline_indent");
2778        assert!(err.notes[0].contains("character for character"));
2779        // CRLF inside a raw multi-line string; a lone CR is not a line break.
2780        assert_eq!(
2781            string_value("r\"\"\"\r\n  a\\\r\n  b\r\n  \"\"\""),
2782            "a\\\nb"
2783        );
2784        assert_eq!(string_value("\"\"\"\n  a\rb\n  \"\"\""), "a\rb");
2785        // The raw form holds `"` and `""` but not `"""`.
2786        assert_eq!(string_value("r\"\"\"\n  \"a\"\" b\n  \"\"\""), "\"a\"\" b");
2787        // Empty `\u{}` and an eight-digit escape.
2788        assert!(tokenize(r#""\u{}""#).is_err());
2789        assert!(tokenize(r#""\u{00000041}""#).is_err());
2790    }
2791
2792    /// Review of #2619: a multi-line string cannot nest in a hole, and a
2793    /// `"""` followed by text is not a closing delimiter.
2794    #[test]
2795    fn multiline_in_hole_and_stray_delimiters() {
2796        let cat = |src: &str| tokenize(src).unwrap_err().category;
2797        assert_eq!(
2798            cat("\"a \\(f(\"\"\"\n  x\n  \"\"\")) b\""),
2799            "bynk.lex.multiline_in_hole"
2800        );
2801        assert_eq!(
2802            cat("\"\"\"\n  \\(g(\"\"\"\n  x\n  \"\"\"))\n  \"\"\""),
2803            "bynk.lex.multiline_in_hole"
2804        );
2805        // `"""quoted"""` on a body line is a stray delimiter, not a close.
2806        assert_eq!(
2807            cat("\"\"\"\n  \"\"\"quoted\"\"\"\n  \"\"\""),
2808            "bynk.lex.multiline_close_not_own_line"
2809        );
2810        // A closing delimiter may be followed by punctuation.
2811        let toks = tokenize("\"\"\"\n  a\n  \"\"\", x)").unwrap();
2812        assert_eq!(toks.len(), 4);
2813    }
2814
2815    #[test]
2816    fn multiline_errors() {
2817        let cat = |src: &str| tokenize(src).unwrap_err().category;
2818        // Under-indented line.
2819        assert_eq!(
2820            cat("\"\"\"\n    a\n  b\n    \"\"\""),
2821            "bynk.lex.multiline_indent"
2822        );
2823        // Text after the opening delimiter that is not a language tag.
2824        assert_eq!(cat("\"\"\" abc\n\"\"\""), "bynk.lex.multiline_open");
2825        assert_eq!(cat("\"\"\"ABC\n\"\"\""), "bynk.lex.multiline_open");
2826        // Never closed.
2827        assert_eq!(cat("\"\"\"\n  a\n"), "bynk.lex.unterminated_string");
2828        // A closing delimiter that shares a line with text.
2829        assert_eq!(
2830            cat("\"\"\"\n  a \"\"\" b\n  \"\"\""),
2831            "bynk.lex.multiline_close_not_own_line"
2832        );
2833    }
2834
2835    /// #2958: a language tag after the opening `"""` is metadata: the value
2836    /// is that of the untagged literal, in every form.
2837    #[test]
2838    fn multiline_tag_is_value_neutral() {
2839        let body = "\n    SELECT 1\n      FROM t\n    \"\"\"";
2840        let plain = string_value(&format!("\"\"\"{body}"));
2841        for opener in [
2842            "\"\"\"sql",
2843            "\"\"\"sql  ",
2844            "\"\"\"sql\t",
2845            "\"\"\"x",
2846            "\"\"\"my-lang_2",
2847        ] {
2848            assert_eq!(
2849                string_value(&format!("{opener}{body}")),
2850                plain,
2851                "{opener:?}"
2852            );
2853        }
2854        // CRLF after a tag, and the raw form.
2855        assert_eq!(
2856            string_value("\"\"\"sql\r\n  a\r\n  \"\"\""),
2857            string_value("\"\"\"\r\n  a\r\n  \"\"\"")
2858        );
2859        assert_eq!(string_value("r\"\"\"regex\n  ^\\d+$\n  \"\"\""), "^\\d+$");
2860        // An interpolating tagged literal is still an interpolated string.
2861        assert_eq!(
2862            kinds("\"\"\"sql\n  hi \\(name)\n  \"\"\""),
2863            vec![TokenKind::InterpStr]
2864        );
2865    }
2866
2867    /// #2958: what is not a tag stays `bynk.lex.multiline_open`.
2868    #[test]
2869    fn multiline_malformed_tags() {
2870        let cat = |src: &str| tokenize(src).unwrap_err().category;
2871        for opener in [
2872            "\"\"\" sql",  // a space before the tag
2873            "\"\"\"sql x", // text after the tag
2874            "\"\"\"SQL",   // uppercase
2875            "\"\"\"1sql",  // starts with a digit
2876            "\"\"\"-sql",  // starts with punctuation
2877            "\"\"\"sql.x", // a character outside the tag alphabet
2878            "\"\"\"   ",   // trailing spaces with no tag, as before
2879            "r\"\"\" sql",
2880        ] {
2881            assert_eq!(
2882                cat(&format!("{opener}\n  a\n  \"\"\"")),
2883                "bynk.lex.multiline_open",
2884                "{opener:?}"
2885            );
2886        }
2887        // The note names the tag.
2888        let err = tokenize("\"\"\"SQL\n  a\n  \"\"\"").unwrap_err();
2889        assert!(err.notes[0].contains("language tag"));
2890    }
2891
2892    /// #2619: the semantic-token parts of the three string forms.
2893    #[test]
2894    fn string_parts_cover_escapes_and_raw_delimiters() {
2895        let src = "\"a\\n\\u{41}\" r#\"x\\n\"# \"\"\"\n  \\t \\(\"\\r\")\n  \"\"\" \
2896                   \"\"\"sql\n  a\\n\n  \"\"\" r\"\"\"regex\n  \\d\n  \"\"\"";
2897        let texts: Vec<(&str, StringPart)> = string_parts(src)
2898            .into_iter()
2899            .map(|(s, p)| (&src[s.range()], p))
2900            .collect();
2901        use StringPart::*;
2902        assert_eq!(
2903            texts,
2904            vec![
2905                ("\\n", Escape),
2906                ("\\u{41}", Escape),
2907                ("r#\"", RawDelimiter),
2908                ("\"#", RawDelimiter),
2909                ("\\t", Escape),
2910                ("\\r", Escape),
2911                ("sql", Tag),
2912                ("\\n", Escape),
2913                ("regex", Tag),
2914                ("r\"\"\"", RawDelimiter),
2915                ("\"\"\"", RawDelimiter),
2916            ]
2917        );
2918    }
2919
2920    fn doc_block_span(source: &str) -> Span {
2921        tokenize(source)
2922            .unwrap()
2923            .into_iter()
2924            .find(|t| t.kind == TokenKind::DocBlock)
2925            .expect("a DocBlock token")
2926            .span
2927    }
2928
2929    #[test]
2930    fn doc_block_body_range_slices_to_the_same_bytes_doc_block_content_would_strip() {
2931        let src = "---\nHello there.\n---\nfn f() -> Int = 1\n";
2932        let span = doc_block_span(src);
2933        let range = doc_block_body_range(src, span).unwrap();
2934        assert_eq!(&src[range], "Hello there.");
2935    }
2936
2937    #[test]
2938    fn doc_block_body_range_is_offset_preserving_unlike_doc_block_content() {
2939        // A content line indented relative to its (unindented) markers:
2940        // doc_block_content strips the common indent (not offset-preserving),
2941        // doc_block_body_range does not — its slice still contains the raw
2942        // indentation, so span-based callers can map a position in the raw
2943        // body straight back to `src`.
2944        let src = "---\n  See [Foo].\n---\nfn f() -> Int = 1\n";
2945        let span = doc_block_span(src);
2946        let range = doc_block_body_range(src, span).unwrap();
2947        assert_eq!(&src[range.clone()], "  See [Foo].");
2948        assert_eq!(doc_block_content(src, span), "See [Foo].");
2949        // The raw range still locates `[Foo]` correctly within `src`.
2950        let bracket_rel = src[range.clone()].find('[').unwrap();
2951        assert_eq!(
2952            &src[range.start + bracket_rel..range.start + bracket_rel + 5],
2953            "[Foo]"
2954        );
2955    }
2956
2957    #[test]
2958    fn doc_block_content_and_body_range_agree_on_empty_body() {
2959        let src = "---\n---\nfn f() -> Int = 1\n";
2960        let span = doc_block_span(src);
2961        let range = doc_block_body_range(src, span).unwrap();
2962        assert_eq!(&src[range], "");
2963        assert_eq!(doc_block_content(src, span), "");
2964    }
2965
2966    /// #1885 (DECISION A): a `----` block closes only on `----`, so the `---`
2967    /// lines inside it are content, a nested doc example among them.
2968    #[test]
2969    fn a_longer_fence_holds_shorter_marker_lines() {
2970        let src = "----\nIntro.\n---\nInner doc.\n---\nTail.\n----\nfn f() -> Int = 1\n";
2971        let tokens = tokenize(src).unwrap();
2972        let docs: Vec<_> = tokens
2973            .iter()
2974            .filter(|t| t.kind == TokenKind::DocBlock)
2975            .collect();
2976        assert_eq!(docs.len(), 1, "one block, not three");
2977        assert_eq!(
2978            doc_block_content(src, docs[0].span),
2979            "Intro.\n---\nInner doc.\n---\nTail."
2980        );
2981    }
2982
2983    /// The trailing-dash trim in `doc_block_body_range` stops at the closer's
2984    /// line, so a body that ends in a shorter marker line keeps it.
2985    #[test]
2986    fn a_body_ending_in_a_shorter_marker_line_keeps_it() {
2987        let src = "----\nAbove.\n---\n----\nfn f() -> Int = 1\n";
2988        let span = doc_block_span(src);
2989        assert_eq!(doc_block_content(src, span), "Above.\n---");
2990    }
2991
2992    /// #1885: a marker of another length does not close the block, so a
2993    /// `----` opened and only `---` seen after is unclosed at EOF, and the note
2994    /// names the length that would close it.
2995    #[test]
2996    fn a_marker_of_another_length_does_not_close_the_block() {
2997        let err = tokenize("----\nText.\n---\nfn f() -> Int = 1\n").unwrap_err();
2998        assert_eq!(err.category, "bynk.lex.unclosed_doc_block");
2999        let note = err.notes.join(" ");
3000        assert!(note.contains("exactly 4 dashes"), "{note}");
3001        assert!(note.contains("not a divider"), "{note}");
3002        // The other way round: a `---` block does not close on `----`.
3003        let err = tokenize("---\nText.\n----\n").unwrap_err();
3004        assert_eq!(err.category, "bynk.lex.unclosed_doc_block");
3005    }
3006
3007    /// #2807: the recovering lexer reads past every lexical error, reports each
3008    /// in source order and keeps the tokens around them.
3009    #[test]
3010    fn recovering_lex_collects_every_error_and_keeps_the_rest() {
3011        let src = "fn a() $ 1\nlet n = 99999999999999999999\n\"oops\nfn b() ~ 2\n";
3012        let (tokens, errors) = tokenize_recovering(src);
3013        let cats: Vec<_> = errors.iter().map(|e| e.category).collect();
3014        assert_eq!(
3015            cats,
3016            [
3017                "bynk.lex.unexpected_character",
3018                "bynk.lex.integer_overflow",
3019                "bynk.lex.unterminated_string",
3020                "bynk.lex.unexpected_character",
3021            ]
3022        );
3023        assert!(errors.windows(2).all(|w| w[0].span.start < w[1].span.start));
3024        // The text between the errors still lexes.
3025        let fns = tokens.iter().filter(|t| t.kind == TokenKind::Fn).count();
3026        assert_eq!(fns, 2, "{tokens:?}");
3027        // The strict entry point still reports the first error alone.
3028        assert_eq!(tokenize(src).unwrap_err().span.start, errors[0].span.start);
3029    }
3030
3031    /// #2807: recovery always advances, whatever it meets, and never splits a
3032    /// multi-byte character.
3033    #[test]
3034    fn recovering_lex_terminates_on_hostile_input() {
3035        for src in [
3036            "é",
3037            "\"é",
3038            "\"\"\"é",
3039            "$é$",
3040            "///é",
3041            "----\né",
3042            "r\"é",
3043            "\"\\(é",
3044            "9é99999999999999999999é",
3045        ] {
3046            let (_, errors) = tokenize_recovering(src);
3047            assert!(!errors.is_empty(), "{src:?}");
3048        }
3049    }
3050
3051    /// #2807: recovery from a bad escape resumes after the literal's closer,
3052    /// even when a hole holds a string.
3053    #[test]
3054    fn string_recovery_skips_a_hole_holding_a_string() {
3055        let src = "fn f() { show(\"a\\q \\(g(\"x\")) b\", 1) }\nfn k() $";
3056        let (tokens, errors) = tokenize_recovering(src);
3057        let cats: Vec<_> = errors.iter().map(|e| e.category).collect();
3058        assert_eq!(
3059            cats,
3060            ["bynk.lex.bad_escape", "bynk.lex.unexpected_character"]
3061        );
3062        // `, 1) }` after the literal still lexes: nothing of the hole leaked.
3063        assert!(!tokens.iter().any(|t| t.kind == TokenKind::StrLit));
3064        let kinds: Vec<_> = tokens.iter().map(|t| t.kind).collect();
3065        assert_eq!(
3066            &kinds[kinds.len() - 8..kinds.len() - 4],
3067            [
3068                TokenKind::Comma,
3069                TokenKind::IntLit,
3070                TokenKind::RParen,
3071                TokenKind::RBrace
3072            ]
3073        );
3074    }
3075
3076    #[test]
3077    fn adjacent_stray_characters_are_one_error() {
3078        let (_, errors) = tokenize_recovering("fn $$$ f é$");
3079        assert_eq!(errors.len(), 2, "{errors:?}");
3080        assert_eq!(errors[0].span.end - errors[0].span.start, 3);
3081    }
3082
3083    #[test]
3084    fn an_unclosed_doc_block_swallows_the_rest_without_more_errors() {
3085        let (tokens, errors) =
3086            tokenize_recovering("fn a() = 1\n---\nit's prose; don't lex #this\nfn b() = 2\n");
3087        assert_eq!(errors.len(), 1, "{errors:?}");
3088        assert_eq!(errors[0].category, "bynk.lex.unclosed_doc_block");
3089        assert_eq!(tokens.iter().filter(|t| t.kind == TokenKind::Fn).count(), 1);
3090    }
3091
3092    /// #2807: the parse errors a skipped character causes are dropped (also past
3093    /// a comment, and at the end of the file); a real error elsewhere stays.
3094    #[test]
3095    fn lex_echoes_are_dropped() {
3096        let src = "commons d\n\nfn f(a: Int, b: Int) -> Int { a $ b }\n";
3097        let (tokens, lex_errors) = tokenize_recovering(src);
3098        let parse_errors = crate::parser::parse_units_recovering(&tokens, src).errors;
3099        assert!(!parse_errors.is_empty(), "`a b` is a syntax error");
3100        assert!(without_lex_echoes(&lex_errors, &tokens, parse_errors).is_empty());
3101    }
3102
3103    fn surviving(src: &str) -> usize {
3104        let (tokens, lex_errors) = tokenize_recovering(src);
3105        let parse_errors = crate::parser::parse_units_recovering(&tokens, src).errors;
3106        without_lex_echoes(&lex_errors, &tokens, parse_errors).len()
3107    }
3108
3109    #[test]
3110    fn lex_echo_window_skips_comments_and_runs_to_eof() {
3111        assert_eq!(
3112            surviving("commons d\n\nfn f(a: Int, b: Int) -> Int { a $ // why\n b }\n"),
3113            0
3114        );
3115        // An unclosed doc block inside a body: the missing `}` is its echo.
3116        assert_eq!(
3117            surviving("commons d\n\nfn f() -> Int {\n  1\n---\nprose\n"),
3118            0
3119        );
3120        // A genuine syntax error well away from the lex error stays.
3121        assert_eq!(
3122            surviving("commons d\n\nfn f() -> Int { 1 $ }\n\nfn g( -> Int { 1 }\n"),
3123            1
3124        );
3125    }
3126}