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, lexed
7//! outside of logos (see [`tokenize`]).
8
9use logos::Logos;
10
11use crate::error::CompileError;
12use crate::span::Span;
13
14/// v0.142 (ADR 0166): strip `_` digit separators from a numeric literal's lexeme
15/// before it is parsed into a value. The lexer's `IntLit`/`FloatLit` regexes only
16/// admit an `_` between two digit groups, so removing every `_` yields a plain
17/// digit string; the separators are purely visual. Allocates only when the
18/// literal actually carries a separator (the common case does not).
19pub(crate) fn strip_digit_separators(lexeme: &str) -> std::borrow::Cow<'_, str> {
20    if lexeme.as_bytes().contains(&b'_') {
21        std::borrow::Cow::Owned(lexeme.replace('_', ""))
22    } else {
23        std::borrow::Cow::Borrowed(lexeme)
24    }
25}
26
27/// Token kinds. Discriminants without payload data; the lexeme is recovered
28/// from the source string via the token's [`Span`].
29///
30/// Note: `--` line comments and `---` doc block markers are handled outside
31/// logos (see [`tokenize`]), because doc blocks are delimited by `---` lines
32/// containing only the marker and may span multiple source lines.
33#[derive(Logos, Debug, Clone, Copy, PartialEq, Eq)]
34#[logos(skip r"[ \t\r\n]+")]
35pub enum TokenKind {
36    // Keywords
37    #[token("commons")]
38    Commons,
39    #[token("type")]
40    Type,
41    #[token("fn")]
42    Fn,
43    #[token("where")]
44    Where,
45    // #548: the `and` keyword was retired — refinement predicates now join with
46    // `&&` (the one conjunction spelling). `and` is a free identifier again.
47    #[token("true")]
48    True,
49    #[token("false")]
50    False,
51    #[token("Int")]
52    Int,
53    #[token("String")]
54    String,
55    #[token("Bool")]
56    Bool,
57    // v0.21 keyword
58    #[token("Float")]
59    Float,
60    // v0.86 keyword (ADR 0112): the `Duration` base type.
61    #[token("Duration")]
62    Duration,
63    // v0.90 keyword (ADR 0114): the `Instant` base type.
64    #[token("Instant")]
65    Instant,
66    // v0.110 keyword (ADR 0142): the `Bytes` base type.
67    #[token("Bytes")]
68    Bytes,
69    // v0.1 keywords
70    #[token("let")]
71    Let,
72    #[token("if")]
73    If,
74    #[token("else")]
75    Else,
76    #[token("Ok")]
77    Ok,
78    #[token("Err")]
79    Err,
80    #[token("Result")]
81    Result,
82    #[token("ValidationError")]
83    ValidationError,
84    // v0.22b keyword
85    #[token("JsonError")]
86    JsonError,
87    // v0.2 keywords
88    #[token("enum")]
89    Enum,
90    #[token("match")]
91    Match,
92    #[token("Option")]
93    Option,
94    #[token("record")]
95    Record,
96    #[token("self")]
97    Self_,
98    #[token("Some")]
99    Some,
100    #[token("None")]
101    None,
102    #[token("is")]
103    Is,
104    // v0.3 keywords
105    #[token("opaque")]
106    Opaque,
107    #[token("uses")]
108    Uses,
109    // v0.4 keywords
110    #[token("context")]
111    Context,
112    #[token("consumes")]
113    Consumes,
114    #[token("exports")]
115    Exports,
116    #[token("transparent")]
117    Transparent,
118    // v0.6 keywords
119    #[token("as")]
120    As,
121    // v0.7 keywords (v0.112: `assert`→`expect`, `test`→`suite`/`case`;
122    // v0.118: `mocks` retired — test doubles are stubs at a seam; the stub form
123    // moved off the punned `provides` keyword to its own `stub` keyword in the
124    // keyword-hygiene batch, #548)
125    #[token("expect")]
126    Expect,
127    #[token("suite")]
128    Suite,
129    #[token("case")]
130    Case,
131    // Keyword-hygiene batch (#548): the test-scope stub `stub Cap.op(…) <rhs>`,
132    // formerly the third pun on `provides`. `provides` now heads only a provider
133    // declaration / external provider.
134    #[token("stub")]
135    Stub,
136    // v0.114 keyword — generative tests (testing track slice 2). `for` and `all`
137    // are deliberately *not* keywords: `all` is a list combinator (`all(xs, p)`)
138    // and must stay a usable identifier. The `for all` binder is parsed
139    // contextually (two identifiers) inside a `property` body instead.
140    #[token("property")]
141    Property,
142    // v0.17 keywords
143    #[token("adapter")]
144    Adapter,
145    #[token("binding")]
146    Binding,
147    // v0.5 keywords
148    #[token("agent")]
149    Agent,
150    #[token("capability")]
151    Capability,
152    #[token("Effect")]
153    Effect,
154    // v0.146 keyword (ADR 0170): `do e` — an effect-performing expression
155    // statement (the binder-free `let _ <- e` for a unit effect).
156    #[token("do")]
157    Do,
158    #[token("given")]
159    Given,
160    #[token("on")]
161    On,
162    // v0.9 keyword
163    #[token("http")]
164    Http,
165    // v0.10a keyword
166    #[token("cron")]
167    Cron,
168    // v0.10b keyword
169    #[token("queue")]
170    Queue,
171    // v0.44 keywords: `from` heads a service's protocol clause; `protocol` is
172    // reserved (protocols are a closed, compiler-known set — no declaration kind).
173    #[token("from")]
174    From,
175    #[token("protocol")]
176    Protocol,
177    #[token("provides")]
178    Provides,
179    #[token("service")]
180    Service,
181    // v0.45 keywords: `actor` heads a boundary-contract declaration; `by`
182    // heads a handler's actor clause.
183    #[token("actor")]
184    Actor,
185    #[token("by")]
186    By,
187    // v0.80 keywords: `invariant` heads an agent invariant declaration; `implies`
188    // is the directional logical-implication operator (`P implies Q` ≡ `!P || Q`).
189    #[token("invariant")]
190    Invariant,
191    #[token("implies")]
192    Implies,
193    // v0.115 keywords — function contracts (testing track slice 3). `requires`
194    // and `ensures` head a contract clause on a `fn` signature (between the
195    // return type and the body). `result` is deliberately *not* a keyword: it is
196    // the ordinary value name outside a contract, so it stays a usable
197    // identifier; inside an `ensures` predicate it is bound contextually as the
198    // function's return value (parsed by scope, like `for`/`all` in slice 2).
199    // Distinct from ADR 0127's capability `@requires` annotation.
200    #[token("requires")]
201    Requires,
202    #[token("ensures")]
203    Ensures,
204    // v0.116 keyword — step invariants (testing track slice 4). `transition` heads
205    // an agent step-invariant declaration (beside `invariant`), a predicate over
206    // the pre- and post-commit state pair. `old` and `new` are deliberately *not*
207    // keywords: they stay ordinary value names outside a `transition`, and inside a
208    // `transition` predicate they are bound contextually to the old/new state
209    // records (parsed by scope, like `result` in an `ensures`).
210    #[token("transition")]
211    Transition,
212    /// `...` — used in record-spread expressions (v0.5).
213    #[token("...")]
214    DotDotDot,
215    /// `<-` — Effect bind operator (v0.5).
216    #[token("<-")]
217    LArrow,
218    /// `~>` — asynchronous fire-and-forget send marker (v0.79). A leading
219    /// statement marker, never on the RHS of a `let`; distinct from `<-` so the
220    /// call site shows whether the caller waits.
221    #[token("~>")]
222    TildeArrow,
223    /// `:=` — Cell write (v0.81, storage track). A handler statement
224    /// `cell := expr`; distinct from `=` (binding) and `:` (annotation). Longer
225    /// than `:`/`=` so logos matches it as one token.
226    #[token(":=")]
227    ColonEq,
228
229    /// A documentation block: `---` line ... `---` line. The token's span
230    /// covers the full block including both `---` markers. The body content
231    /// is recovered from the source via the span (see [`doc_block_content`]).
232    /// Inserted by [`tokenize`]; not lexed by logos directly.
233    DocBlock,
234
235    /// A line comment: `-- ...` running to end of line. The span starts at
236    /// the `--` marker and runs through the last character before the
237    /// terminating newline (exclusive). The trivia body (the text after the
238    /// `--` marker) is recovered from the source via the span. Inserted by
239    /// [`tokenize`]; not lexed by logos directly so it cannot be mistaken
240    /// for an `--` operator sequence.
241    Comment,
242
243    // Identifier
244    #[regex(r"[A-Za-z][A-Za-z0-9_]*")]
245    Ident,
246
247    // Literals. v0.142 (ADR 0166): an `_` digit separator may appear between
248    // digits (`1_048_576`) — never leading, trailing, or doubled (each `_` must
249    // sit between two digit groups). The separators are stripped before the value
250    // is parsed; they are purely visual.
251    #[regex(r"[0-9]+(_[0-9]+)*")]
252    IntLit,
253    // A float literal: fraction with a digit on both sides of the `.`, an
254    // exponent, or both (v0.21 §3). `1.` and `.5` are NOT float literals —
255    // the digit-both-sides rule keeps `2.5.round()` / `1.toFloat()` lexing
256    // as method calls on numeric literals. Digit separators (v0.142) may appear
257    // in any digit group, including the exponent.
258    #[regex(
259        r"[0-9]+(_[0-9]+)*\.[0-9]+(_[0-9]+)*([eE][+-]?[0-9]+(_[0-9]+)*)?|[0-9]+(_[0-9]+)*[eE][+-]?[0-9]+(_[0-9]+)*"
260    )]
261    FloatLit,
262    // A double-quoted string with simple escapes. The body excludes the closing
263    // quote; we accept any non-quote/non-backslash/non-newline char, or a
264    // backslash followed by one of the four allowed escapes.
265    #[regex(r#""([^"\\\n]|\\[nt"\\])*""#)]
266    StrLit,
267    // An interpolated string `"… \(expr) …"` (v0.43). Hand-scanned in
268    // `tokenize` (logos cannot balance the holes' parens), never produced by
269    // the logos lexer — like [`TokenKind::DocBlock`]/[`TokenKind::Comment`].
270    // The span covers the whole `"…"`; the parser splits chunks from holes.
271    InterpStr,
272
273    // Multi-char operators
274    #[token("->")]
275    Arrow,
276    #[token("==")]
277    EqEq,
278    #[token("!=")]
279    BangEq,
280    #[token("<=")]
281    LtEq,
282    #[token(">=")]
283    GtEq,
284    #[token("&&")]
285    AmpAmp,
286    #[token("||")]
287    PipePipe,
288
289    // Single-char operators
290    #[token("+")]
291    Plus,
292    #[token("-")]
293    Minus,
294    #[token("*")]
295    Star,
296    #[token("/")]
297    Slash,
298    #[token("!")]
299    Bang,
300    #[token("=")]
301    Eq,
302    #[token("<")]
303    Lt,
304    #[token(">")]
305    Gt,
306    // v0.1 postfix operator
307    #[token("?")]
308    Question,
309    // v0.2 match-arm arrow
310    #[token("=>")]
311    FatArrow,
312    // v0.2 wildcard pattern (also valid as identifier start; the lexer
313    // prefers identifier for any longer match, so `_foo` is still Ident).
314    #[token("_")]
315    Underscore,
316    // v0.2 sum-type variant separator (also used as future bitwise OR);
317    // single `|` distinct from `||`.
318    #[token("|")]
319    Pipe,
320    /// `@` — storage-annotation marker (v0.85, storage track; ADR 0111). Leads a
321    /// `@name(args)` annotation on a `store` field (`@ttl(…)`/`@indexed(…)`); it
322    /// appears only in store-field-declaration position, never as an expression
323    /// operator.
324    #[token("@")]
325    At,
326
327    // Punctuation
328    #[token("(")]
329    LParen,
330    #[token(")")]
331    RParen,
332    #[token("{")]
333    LBrace,
334    #[token("}")]
335    RBrace,
336    #[token("[")]
337    LBracket,
338    #[token("]")]
339    RBracket,
340    #[token(",")]
341    Comma,
342    #[token(":")]
343    Colon,
344    #[token(".")]
345    Dot,
346}
347
348impl TokenKind {
349    /// Human-readable display name for diagnostics.
350    pub fn describe(self) -> &'static str {
351        use TokenKind::*;
352        match self {
353            Commons => "`commons`",
354            Type => "`type`",
355            Fn => "`fn`",
356            Where => "`where`",
357            True => "`true`",
358            False => "`false`",
359            Int => "`Int`",
360            String => "`String`",
361            Bool => "`Bool`",
362            Float => "`Float`",
363            Duration => "`Duration`",
364            Instant => "`Instant`",
365            Bytes => "`Bytes`",
366            Let => "`let`",
367            If => "`if`",
368            Else => "`else`",
369            Ok => "`Ok`",
370            Err => "`Err`",
371            Result => "`Result`",
372            ValidationError => "`ValidationError`",
373            JsonError => "`JsonError`",
374            Enum => "`enum`",
375            Match => "`match`",
376            Option => "`Option`",
377            Record => "`record`",
378            Self_ => "`self`",
379            Some => "`Some`",
380            None => "`None`",
381            Is => "`is`",
382            Opaque => "`opaque`",
383            Uses => "`uses`",
384            Context => "`context`",
385            Consumes => "`consumes`",
386            Exports => "`exports`",
387            Transparent => "`transparent`",
388            As => "`as`",
389            Expect => "`expect`",
390            Suite => "`suite`",
391            Case => "`case`",
392            Property => "`property`",
393            Adapter => "`adapter`",
394            Binding => "`binding`",
395            Agent => "`agent`",
396            Capability => "`capability`",
397            Effect => "`Effect`",
398            Do => "`do`",
399            Given => "`given`",
400            On => "`on`",
401            Http => "`http`",
402            Cron => "`cron`",
403            Queue => "`queue`",
404            From => "`from`",
405            Protocol => "`protocol`",
406            Provides => "`provides`",
407            Stub => "`stub`",
408            Service => "`service`",
409            Actor => "`actor`",
410            By => "`by`",
411            Invariant => "`invariant`",
412            Implies => "`implies`",
413            Requires => "`requires`",
414            Ensures => "`ensures`",
415            Transition => "`transition`",
416            ColonEq => "`:=`",
417            DotDotDot => "`...`",
418            LArrow => "`<-`",
419            TildeArrow => "`~>`",
420            DocBlock => "documentation block",
421            Comment => "line comment",
422            Ident => "identifier",
423            IntLit => "integer literal",
424            FloatLit => "float literal",
425            StrLit => "string literal",
426            InterpStr => "interpolated string",
427            Arrow => "`->`",
428            EqEq => "`==`",
429            BangEq => "`!=`",
430            LtEq => "`<=`",
431            GtEq => "`>=`",
432            AmpAmp => "`&&`",
433            PipePipe => "`||`",
434            Plus => "`+`",
435            Minus => "`-`",
436            Star => "`*`",
437            Slash => "`/`",
438            Bang => "`!`",
439            Eq => "`=`",
440            Lt => "`<`",
441            Gt => "`>`",
442            Question => "`?`",
443            FatArrow => "`=>`",
444            Underscore => "`_`",
445            Pipe => "`|`",
446            At => "`@`",
447            LParen => "`(`",
448            RParen => "`)`",
449            LBrace => "`{`",
450            RBrace => "`}`",
451            LBracket => "`[`",
452            RBracket => "`]`",
453            Comma => "`,`",
454            Colon => "`:`",
455            Dot => "`.`",
456        }
457    }
458}
459
460/// A token plus its source span.
461#[derive(Debug, Clone, Copy)]
462pub struct Token {
463    pub kind: TokenKind,
464    pub span: Span,
465}
466
467/// Tokenise a source string. Returns the full token vector or the first
468/// lexical error.
469///
470/// Doc blocks (`---` ... `---`) and line comments (`-- ...`) are recognised
471/// outside the logos-generated lexer: we scan the source one segment at a
472/// time, dispatching to logos for ordinary tokens between non-token spans.
473pub fn tokenize(source: &str) -> Result<Vec<Token>, CompileError> {
474    let mut tokens = Vec::new();
475    let bytes = source.as_bytes();
476    let mut pos = 0;
477    while pos < bytes.len() {
478        // Detect a `---` doc-block marker at the start of a line (the line may
479        // begin with leading whitespace; the marker itself must be alone on
480        // its line).
481        if let Some(open_end) = doc_block_open_at(source, pos) {
482            // Find the matching closing `---` line.
483            match doc_block_close(source, open_end) {
484                Some((close_start, close_end)) => {
485                    let span = Span::new(pos, close_end);
486                    tokens.push(Token {
487                        kind: TokenKind::DocBlock,
488                        span,
489                    });
490                    let _ = close_start;
491                    pos = close_end;
492                    continue;
493                }
494                None => {
495                    return Err(CompileError::new(
496                        "bynk.lex.unclosed_doc_block",
497                        Span::new(pos, open_end),
498                        "documentation block opened but never closed",
499                    )
500                    .with_note(
501                        "a doc block must be terminated by another `---` on a line by itself",
502                    ));
503                }
504            }
505        }
506        // A `--` line comment: emit a `Comment` token covering everything
507        // up to (but not including) the terminating newline. Doc-block
508        // detection above already ruled out a `---` marker at line start
509        // — and once we've consumed past the leading `--`, any further
510        // dashes are part of the comment body. Preserving comments as
511        // trivia tokens lets the parser attach them to declarations so
512        // the formatter can emit them in place (v1.1 LSP spec §3.5).
513        //
514        // #548 (keyword-hygiene batch): a `--` opens a comment only when it is
515        // at the start of input or **preceded by whitespace**. Adjacent to a
516        // preceding token (`a--b`), the `--` is *not* a comment — it lexes as two
517        // `-` operators (`a - -b`), so a subtraction-of-negation is never
518        // silently swallowed as a line comment. This resolves the `a--b`
519        // "comment vs subtraction" ambiguity in favour of subtraction.
520        let comment_eligible = pos == 0 || matches!(bytes[pos - 1], b' ' | b'\t' | b'\r' | b'\n');
521        if comment_eligible && pos + 1 < bytes.len() && bytes[pos] == b'-' && bytes[pos + 1] == b'-'
522        {
523            let start = pos;
524            while pos < bytes.len() && bytes[pos] != b'\n' {
525                pos += 1;
526            }
527            tokens.push(Token {
528                kind: TokenKind::Comment,
529                span: Span::new(start, pos),
530            });
531            continue;
532        }
533        // Skip ordinary whitespace inline (logos handles it too, but we may
534        // be in the middle of the source between specials).
535        if matches!(bytes[pos], b' ' | b'\t' | b'\r' | b'\n') {
536            pos += 1;
537            continue;
538        }
539        // An interpolated string `"… \(expr) …"` (v0.43): only strings that
540        // actually contain a `\(` hole are hand-scanned here; plain strings
541        // fall through to the logos `StrLit` path unchanged. `\(` is an
542        // invalid escape in the logos grammar, so this never re-routes a
543        // currently-valid literal.
544        if bytes[pos] == b'"' && has_interp_hole(bytes, pos) {
545            let end = scan_str(bytes, source, pos)?;
546            tokens.push(Token {
547                kind: TokenKind::InterpStr,
548                span: Span::new(pos, end),
549            });
550            pos = end;
551            continue;
552        }
553        // Otherwise dispatch a single logos token starting at `pos`.
554        let mut lex = TokenKind::lexer(&source[pos..]);
555        let Some(result) = lex.next() else {
556            // No token at this position; treat as unexpected character so
557            // the user sees something useful.
558            let ch = source[pos..].chars().next().unwrap_or('\0');
559            let span = Span::new(pos, pos + ch.len_utf8());
560            return Err(CompileError::new(
561                "bynk.lex.unexpected_character",
562                span,
563                format!("unexpected character `{ch}`"),
564            ));
565        };
566        let local = lex.span();
567        let span: Span = Span::new(pos + local.start, pos + local.end);
568        match result {
569            Ok(kind) => {
570                if kind == TokenKind::IntLit {
571                    let slice = &source[span.range()];
572                    if strip_digit_separators(slice).parse::<i64>().is_err() {
573                        return Err(CompileError::new(
574                            "bynk.lex.integer_overflow",
575                            span,
576                            format!(
577                                "integer literal `{slice}` is out of range for a 64-bit signed integer"
578                            ),
579                        )
580                        .with_note("the range is -2^63 to 2^63 - 1"));
581                    }
582                }
583                if kind == TokenKind::FloatLit {
584                    let slice = &source[span.range()];
585                    match strip_digit_separators(slice).parse::<f64>() {
586                        Ok(v) if v.is_finite() => {}
587                        _ => {
588                            return Err(CompileError::new(
589                                "bynk.lex.float_literal_overflow",
590                                span,
591                                format!(
592                                    "float literal `{slice}` is out of range for a 64-bit float"
593                                ),
594                            )
595                            .with_note(
596                                "the literal does not fit a finite IEEE 754 double; \
597                                 the largest finite value is ~1.8e308",
598                            ));
599                        }
600                    }
601                }
602                tokens.push(Token { kind, span });
603                pos = span.end;
604            }
605            Err(()) => {
606                let slice = &source[span.range()];
607                let ch = slice.chars().next().unwrap_or('\0');
608                let err = if ch == '"' {
609                    CompileError::new(
610                        "bynk.lex.unterminated_string",
611                        span,
612                        "unterminated string literal",
613                    )
614                    .with_note(
615                        "string literals must close with `\"` on the same line; \
616                         supported escapes are `\\n`, `\\t`, `\\\"`, `\\\\`",
617                    )
618                } else {
619                    CompileError::new(
620                        "bynk.lex.unexpected_character",
621                        span,
622                        format!("unexpected character `{ch}`"),
623                    )
624                };
625                return Err(err);
626            }
627        }
628    }
629    Ok(tokens)
630}
631
632/// Like [`tokenize`], but with every interpolated-string token replaced by the
633/// tokens of its holes — each hole's bytes re-lexed and its token spans rebased
634/// to absolute source positions (the same rebase [`crate::parser`] applies when
635/// parsing a hole), recursing through nested interpolation. Chunk (literal) text
636/// between holes yields no tokens.
637///
638/// An interpolated string lexes to a single opaque `InterpStr` token, so the
639/// LSP's token-based cursor resolution (hover, go-to-definition, references,
640/// semantic tokens) is otherwise blind to identifiers inside `"… \(name) …"`.
641/// Expanding the holes makes those identifiers visible as ordinary `Ident`
642/// tokens with their real spans. (Issue #473.)
643///
644/// On a malformed interpolation (an `InterpStr` whose holes don't split, or a
645/// hole whose bytes don't re-lex) the offending token is kept opaque rather than
646/// dropped, so resolution degrades to the pre-fix behaviour instead of losing
647/// tokens.
648pub fn tokenize_expanding_holes(source: &str) -> Result<Vec<Token>, CompileError> {
649    let mut out = Vec::new();
650    for tok in tokenize(source)? {
651        expand_hole_token(source, tok, &mut out);
652    }
653    Ok(out)
654}
655
656/// Push `tok` onto `out`, expanding it into its holes' tokens if it is an
657/// `InterpStr` (see [`tokenize_expanding_holes`]); otherwise push it as-is.
658fn expand_hole_token(source: &str, tok: Token, out: &mut Vec<Token>) {
659    if tok.kind != TokenKind::InterpStr {
660        out.push(tok);
661        return;
662    }
663    let Ok(segments) = split_interp(source, tok.span) else {
664        out.push(tok); // malformed interpolation — keep the opaque token
665        return;
666    };
667    for segment in segments {
668        let InterpSegment::Hole(hole) = segment else {
669            continue; // chunk text carries no tokens
670        };
671        let Ok(hole_tokens) = tokenize(&source[hole.range()]) else {
672            continue;
673        };
674        for mut t in hole_tokens {
675            // Rebase the hole's local spans to absolute source positions.
676            t.span = Span::new(t.span.start + hole.start, t.span.end + hole.start);
677            expand_hole_token(source, t, out); // recurse for nested interpolation
678        }
679    }
680}
681
682/// Cheap routing pre-scan (v0.43): does the string opening at `start` contain a
683/// `\(` interpolation hole before it closes (or the line ends)? Decides whether
684/// `tokenize` hand-scans the string as an `InterpStr` or defers to logos for a
685/// plain `StrLit`. Deliberately tolerant — a malformed string with a hole is
686/// routed here so the hole-aware scanner produces the precise error.
687fn has_interp_hole(bytes: &[u8], start: usize) -> bool {
688    let mut i = start + 1;
689    while i < bytes.len() {
690        match bytes[i] {
691            b'\n' | b'"' => return false,
692            b'\\' => {
693                if bytes.get(i + 1) == Some(&b'(') {
694                    return true;
695                }
696                i += 2;
697            }
698            _ => i += 1,
699        }
700    }
701    false
702}
703
704/// Scan a double-quoted string starting at `start` (the opening `"`), returning
705/// the byte offset just past the closing `"`. Recognises the four simple
706/// escapes plus `\(…)` interpolation holes, whose parens are balanced (and
707/// whose nested strings are skipped) by [`scan_hole`]. (v0.43.)
708fn scan_str(bytes: &[u8], source: &str, start: usize) -> Result<usize, CompileError> {
709    debug_assert_eq!(bytes[start], b'"');
710    let mut i = start + 1;
711    loop {
712        if i >= bytes.len() || bytes[i] == b'\n' {
713            return Err(CompileError::new(
714                "bynk.lex.unterminated_string",
715                Span::new(start, i.min(bytes.len())),
716                "unterminated string literal",
717            )
718            .with_note(
719                "string literals must close with `\"` on the same line; \
720                 supported escapes are `\\n`, `\\t`, `\\\"`, `\\\\`, and `\\(…)` interpolation",
721            ));
722        }
723        match bytes[i] {
724            b'"' => return Ok(i + 1),
725            b'\\' => match bytes.get(i + 1) {
726                Some(b'n' | b't' | b'"' | b'\\') => i += 2,
727                Some(b'(') => i = scan_hole(bytes, source, i + 2)?,
728                other => {
729                    let shown = other.map(|b| (*b as char).to_string()).unwrap_or_default();
730                    // Cover `\` plus the whole offending char, advanced to a char
731                    // boundary so the span never splits a multibyte codepoint
732                    // (e.g. `\é`) — a fuzz invariant.
733                    let mut end = (i + 2).min(bytes.len());
734                    while end < source.len() && !source.is_char_boundary(end) {
735                        end += 1;
736                    }
737                    return Err(CompileError::new(
738                        "bynk.lex.bad_escape",
739                        Span::new(i, end),
740                        format!("invalid escape sequence `\\{shown}` in string literal"),
741                    )
742                    .with_note("supported escapes: \\n \\t \\\" \\\\ \\(…)"));
743                }
744            },
745            // Any other byte advances one position. UTF-8 continuation bytes
746            // are all >= 0x80, so they never collide with the ASCII specials.
747            _ => i += 1,
748        }
749    }
750}
751
752/// Scan an interpolation hole body. `start` points just past the `\(`; returns
753/// the offset just past the matching `)`. Tracks paren depth and skips nested
754/// strings (whose own parens must not close the hole), recursing through
755/// [`scan_str`] so nested interpolation nests correctly. (v0.43.)
756fn scan_hole(bytes: &[u8], source: &str, start: usize) -> Result<usize, CompileError> {
757    let mut i = start;
758    let mut depth = 1usize;
759    loop {
760        if i >= bytes.len() || bytes[i] == b'\n' {
761            return Err(CompileError::new(
762                "bynk.lex.unterminated_interpolation",
763                Span::new(start.saturating_sub(2), i.min(bytes.len())),
764                "unterminated interpolation hole",
765            )
766            .with_note(
767                "an interpolation hole `\\(…)` must close with a matching `)` on the same line",
768            ));
769        }
770        match bytes[i] {
771            b'(' => {
772                depth += 1;
773                i += 1;
774            }
775            b')' => {
776                depth -= 1;
777                i += 1;
778                if depth == 0 {
779                    return Ok(i);
780                }
781            }
782            b'"' => i = scan_str(bytes, source, i)?,
783            _ => i += 1,
784        }
785    }
786}
787
788/// One segment of a split interpolated string (v0.43): literal text (escapes
789/// resolved) or the absolute source span of a hole's expression (the bytes
790/// between `\(` and its matching `)`). The parser turns the latter into a real
791/// `Expr`; the lexer owns only the scanning.
792pub(crate) enum InterpSegment {
793    Chunk(String),
794    Hole(Span),
795}
796
797/// Split an `InterpStr` token (its `span` covers the whole `"…"`) into chunks
798/// and hole spans. Escapes in the chunks are resolved here (mirroring
799/// [`parse_string_literal`]); holes are returned as spans for the parser to
800/// re-lex and parse as expressions. (v0.43.)
801pub(crate) fn split_interp(source: &str, span: Span) -> Result<Vec<InterpSegment>, CompileError> {
802    let bytes = source.as_bytes();
803    let inner_end = span.end - 1; // the closing `"`
804    let mut segments = Vec::new();
805    let mut chunk = String::new();
806    let mut i = span.start + 1; // past the opening `"`
807    while i < inner_end {
808        match bytes[i] {
809            b'\\' => match bytes[i + 1] {
810                b'n' => {
811                    chunk.push('\n');
812                    i += 2;
813                }
814                b't' => {
815                    chunk.push('\t');
816                    i += 2;
817                }
818                b'"' => {
819                    chunk.push('"');
820                    i += 2;
821                }
822                b'\\' => {
823                    chunk.push('\\');
824                    i += 2;
825                }
826                b'(' => {
827                    if !chunk.is_empty() {
828                        segments.push(InterpSegment::Chunk(std::mem::take(&mut chunk)));
829                    }
830                    let hole_start = i + 2;
831                    let after = scan_hole(bytes, source, hole_start)?;
832                    // `after` is one past the matching `)`; the hole body is
833                    // everything up to that `)`.
834                    segments.push(InterpSegment::Hole(Span::new(hole_start, after - 1)));
835                    i = after;
836                }
837                // The lexer already validated every escape, so nothing else
838                // can appear here.
839                other => unreachable!("unvalidated escape `\\{}` in InterpStr", other as char),
840            },
841            _ => {
842                let ch = source[i..].chars().next().unwrap();
843                chunk.push(ch);
844                i += ch.len_utf8();
845            }
846        }
847    }
848    if !chunk.is_empty() {
849        segments.push(InterpSegment::Chunk(chunk));
850    }
851    Ok(segments)
852}
853
854/// If a `---` doc-block marker line starts at or shortly after `pos` (which
855/// must be at a line boundary), return the byte offset just past the marker
856/// line (after the terminating newline, or at EOF). The doc-block grammar
857/// requires the marker to be alone on its line; leading horizontal whitespace
858/// is allowed and ignored.
859fn doc_block_open_at(source: &str, pos: usize) -> Option<usize> {
860    let bytes = source.as_bytes();
861    if !at_line_start(source, pos) {
862        return None;
863    }
864    // Skip leading horizontal whitespace.
865    let mut i = pos;
866    while i < bytes.len() && (bytes[i] == b' ' || bytes[i] == b'\t') {
867        i += 1;
868    }
869    if i + 3 > bytes.len() {
870        return None;
871    }
872    if &bytes[i..i + 3] != b"---" {
873        return None;
874    }
875    i += 3;
876    // The marker may have additional trailing dashes (per spec "three or more
877    // consecutive hyphens"). Consume them.
878    while i < bytes.len() && bytes[i] == b'-' {
879        i += 1;
880    }
881    // After the dashes, allow only horizontal whitespace then newline/EOF.
882    while i < bytes.len() && (bytes[i] == b' ' || bytes[i] == b'\t' || bytes[i] == b'\r') {
883        i += 1;
884    }
885    if i == bytes.len() {
886        return Some(i);
887    }
888    if bytes[i] == b'\n' {
889        return Some(i + 1);
890    }
891    None
892}
893
894/// Find the next closing `---` line at or after `pos`. Returns
895/// `(start_of_line, end_of_line)` (`end_of_line` is just past the
896/// terminating newline, or at EOF).
897fn doc_block_close(source: &str, mut pos: usize) -> Option<(usize, usize)> {
898    let bytes = source.as_bytes();
899    while pos < bytes.len() {
900        // Advance pos to the start of a line.
901        let line_start = pos;
902        // Find the end of this line.
903        let mut line_end = line_start;
904        while line_end < bytes.len() && bytes[line_end] != b'\n' {
905            line_end += 1;
906        }
907        // Check this line.
908        if let Some(end) = doc_block_open_at(source, line_start) {
909            return Some((line_start, end));
910        }
911        // Move to the next line.
912        pos = if line_end < bytes.len() {
913            line_end + 1
914        } else {
915            line_end
916        };
917    }
918    None
919}
920
921/// Returns true if byte offset `pos` is at a line start (column 0).
922fn at_line_start(source: &str, pos: usize) -> bool {
923    if pos == 0 {
924        return true;
925    }
926    let bytes = source.as_bytes();
927    bytes[pos - 1] == b'\n'
928}
929
930/// Extract the body content of a doc-block token from its source span.
931/// Strips the leading and trailing `---` marker lines and returns the body
932/// verbatim. If every non-empty content line begins with the same horizontal
933/// whitespace prefix (e.g., because the doc block sits inside a brace-form
934/// commons body), that common prefix is removed so the body reads naturally
935/// when emitted as JSDoc.
936pub fn doc_block_content(source: &str, span: Span) -> String {
937    let slice = &source[span.range()];
938    // Drop the first line (opening marker).
939    let after_open = match slice.find('\n') {
940        Some(i) => &slice[i + 1..],
941        None => return String::new(),
942    };
943    let bytes = after_open.as_bytes();
944    // Trim the trailing closing-marker line.
945    let mut i = bytes.len();
946    if i > 0 && bytes[i - 1] == b'\n' {
947        i -= 1;
948    }
949    while i > 0 && matches!(bytes[i - 1], b' ' | b'\t' | b'\r') {
950        i -= 1;
951    }
952    while i > 0 && bytes[i - 1] == b'-' {
953        i -= 1;
954    }
955    if i > 0 && bytes[i - 1] == b'\n' {
956        i -= 1;
957    }
958    let body = &after_open[..i];
959
960    // Compute the common leading-whitespace prefix across all non-empty lines
961    // and strip it. This lets writers indent the doc block alongside the
962    // declaration it documents without bleeding the indent into the JSDoc.
963    let common: Option<usize> = body
964        .lines()
965        .filter(|l| !l.trim().is_empty())
966        .map(|l| l.bytes().take_while(|&b| b == b' ' || b == b'\t').count())
967        .min();
968    let strip = common.unwrap_or(0);
969    if strip == 0 {
970        return body.to_string();
971    }
972    let mut out = String::with_capacity(body.len());
973    let mut first = true;
974    for line in body.lines() {
975        if !first {
976            out.push('\n');
977        }
978        first = false;
979        if line.trim().is_empty() {
980            // Preserve blank lines.
981            continue;
982        }
983        let leading: usize = line
984            .bytes()
985            .take_while(|&b| b == b' ' || b == b'\t')
986            .count();
987        let drop = strip.min(leading);
988        out.push_str(&line[drop..]);
989    }
990    out
991}
992
993/// Extract the body of a `Comment` trivia token: everything after the
994/// leading `--` marker, preserving its inline whitespace verbatim. Used by
995/// the parser when attaching comments to declarations.
996pub fn comment_body(source: &str, span: Span) -> &str {
997    let slice = &source[span.range()];
998    // Strip leading "--" if present (defensive — the lexer always emits
999    // Comment tokens whose span begins with `--`).
1000    slice.strip_prefix("--").unwrap_or(slice)
1001}
1002
1003/// Returns true if there is a blank line (a line containing only whitespace)
1004/// in `source` strictly between byte offsets `from` (inclusive) and `to`
1005/// (exclusive). Used by the parser to detect orphan doc blocks.
1006///
1007/// A doc-block token's span ends just past the closing-marker line's
1008/// terminating newline. So if the next declaration begins on the immediately
1009/// following line, the substring between contains no newline (only optional
1010/// indentation). Any newline in the substring therefore implies at least one
1011/// entirely-blank line separating the doc from the declaration.
1012pub fn has_blank_line_between(source: &str, from: usize, to: usize) -> bool {
1013    if to <= from {
1014        return false;
1015    }
1016    let bytes = source.as_bytes();
1017    let mut i = from;
1018    while i < to {
1019        if bytes[i] == b'\n' {
1020            return true;
1021        }
1022        if !matches!(bytes[i], b' ' | b'\t' | b'\r') {
1023            return false;
1024        }
1025        i += 1;
1026    }
1027    false
1028}
1029
1030#[cfg(test)]
1031mod tests {
1032    use super::*;
1033
1034    fn kinds(source: &str) -> Vec<TokenKind> {
1035        tokenize(source)
1036            .unwrap()
1037            .into_iter()
1038            .map(|t| t.kind)
1039            .collect()
1040    }
1041
1042    #[test]
1043    fn keywords_and_idents() {
1044        use TokenKind::*;
1045        assert_eq!(
1046            kinds("commons type fn where true false Int String Bool foo bar"),
1047            vec![
1048                Commons, Type, Fn, Where, True, False, Int, String, Bool, Ident, Ident
1049            ],
1050        );
1051        // #548: `and` is no longer a keyword — it lexes as an ordinary identifier.
1052        assert_eq!(kinds("and"), vec![Ident]);
1053    }
1054
1055    #[test]
1056    fn integer_and_string_literals() {
1057        use TokenKind::*;
1058        assert_eq!(
1059            kinds(r#"0 42 "hello" "with\nescape""#),
1060            vec![IntLit, IntLit, StrLit, StrLit]
1061        );
1062    }
1063
1064    #[test]
1065    fn operators() {
1066        use TokenKind::*;
1067        assert_eq!(
1068            kinds("-> == != <= >= && || + - * / ! = < > ( ) { } [ ] , : . @"),
1069            vec![
1070                Arrow, EqEq, BangEq, LtEq, GtEq, AmpAmp, PipePipe, Plus, Minus, Star, Slash, Bang,
1071                Eq, Lt, Gt, LParen, RParen, LBrace, RBrace, LBracket, RBracket, Comma, Colon, Dot,
1072                At,
1073            ],
1074        );
1075    }
1076
1077    #[test]
1078    fn line_comments_emitted_as_trivia() {
1079        // v1.1: line comments are preserved as Comment tokens so the
1080        // formatter can attach and re-emit them.
1081        use TokenKind::*;
1082        let src = "-- a comment\ntype X = Int -- trailing\n";
1083        assert_eq!(kinds(src), vec![Comment, Type, Ident, Eq, Int, Comment],);
1084    }
1085
1086    #[test]
1087    fn comment_body_extracts_text_after_marker() {
1088        let toks = tokenize("-- hello world\n").unwrap();
1089        assert_eq!(toks.len(), 1);
1090        assert_eq!(toks[0].kind, TokenKind::Comment);
1091        assert_eq!(
1092            comment_body("-- hello world\n", toks[0].span),
1093            " hello world"
1094        );
1095    }
1096
1097    #[test]
1098    fn comment_does_not_consume_newline() {
1099        // Two adjacent comment lines should produce two distinct tokens
1100        // — the newline between them is not part of either comment's span.
1101        let toks = tokenize("-- one\n-- two\n").unwrap();
1102        assert_eq!(toks.len(), 2);
1103        assert!(toks.iter().all(|t| t.kind == TokenKind::Comment));
1104    }
1105
1106    #[test]
1107    fn dashdash_opens_a_comment_only_when_whitespace_preceded() {
1108        // #548: a `--` opens a comment at the start of input, or when preceded by
1109        // whitespace/line-start. Adjacent to a preceding token it is *not* a
1110        // comment — `a--b` lexes as `a - -b`, never a swallowed line comment.
1111        use TokenKind::*;
1112        assert_eq!(kinds("a--b"), vec![Ident, Minus, Minus, Ident]);
1113        // A trailing decrement-looking `x--` is two operators, not a comment
1114        // that eats the rest of the line — including at end-of-input with no
1115        // trailing newline (the `pos + 1 < len` guard still holds for `x--`).
1116        assert_eq!(kinds("x--\ny"), vec![Ident, Minus, Minus, Ident]);
1117        assert_eq!(kinds("x--"), vec![Ident, Minus, Minus]);
1118        // Whitespace-preceded and start-of-input `--` are still comments.
1119        assert_eq!(kinds("a -- c"), vec![Ident, Comment]);
1120        assert_eq!(kinds("-- c"), vec![Comment]);
1121        // Start of a fresh line (newline-preceded) is a comment.
1122        assert_eq!(kinds("a\n-- c"), vec![Ident, Comment]);
1123        // The comment/doc-block asymmetry: `--` needs only whitespace before it,
1124        // so a mid-line `a ---b` is a *comment* (the leading `-` of the three is
1125        // whitespace-preceded); a `---` doc-block additionally needs line-start,
1126        // which `a ---b` is not.
1127        assert_eq!(kinds("a ---b"), vec![Ident, Comment]);
1128        // A single `-` between terms is unaffected.
1129        assert_eq!(kinds("a - b"), vec![Ident, Minus, Ident]);
1130    }
1131
1132    #[test]
1133    fn unterminated_string_is_error() {
1134        let err = tokenize("\"oops\n").unwrap_err();
1135        assert_eq!(err.category, "bynk.lex.unterminated_string");
1136    }
1137
1138    #[test]
1139    fn integer_overflow_is_error() {
1140        let err = tokenize("99999999999999999999").unwrap_err();
1141        assert_eq!(err.category, "bynk.lex.integer_overflow");
1142    }
1143
1144    #[test]
1145    fn digit_separators_lex_as_one_number() {
1146        use TokenKind::*;
1147        // v0.142 (ADR 0166): `_` between digit groups keeps the literal a single
1148        // token for both Int and Float.
1149        assert_eq!(kinds("1_048_576"), vec![IntLit]);
1150        assert_eq!(kinds("1_000.500_5"), vec![FloatLit]);
1151        assert_eq!(kinds("1_000e1_0"), vec![FloatLit]);
1152        // A separator-carrying literal that is in range still lexes (the value is
1153        // validated after stripping the separators).
1154        assert!(tokenize("9_223_372_036_854_775_807").is_ok());
1155        // Overflow is still caught on the separator-free value.
1156        let err = tokenize("9_999_999_999_999_999_999_9").unwrap_err();
1157        assert_eq!(err.category, "bynk.lex.integer_overflow");
1158    }
1159
1160    #[test]
1161    fn strip_digit_separators_removes_underscores() {
1162        assert_eq!(strip_digit_separators("1_048_576"), "1048576");
1163        assert_eq!(strip_digit_separators("42"), "42");
1164    }
1165
1166    #[test]
1167    fn unexpected_character_is_error() {
1168        let err = tokenize("type X = Int $").unwrap_err();
1169        assert_eq!(err.category, "bynk.lex.unexpected_character");
1170    }
1171
1172    #[test]
1173    fn v0_1_keywords() {
1174        use TokenKind::*;
1175        assert_eq!(
1176            kinds("let if else Ok Err Result ValidationError"),
1177            vec![Let, If, Else, Ok, Err, Result, ValidationError],
1178        );
1179    }
1180
1181    #[test]
1182    fn question_token() {
1183        use TokenKind::*;
1184        assert_eq!(kinds("x?"), vec![Ident, Question]);
1185    }
1186
1187    #[test]
1188    fn v0_2_keywords() {
1189        use TokenKind::*;
1190        assert_eq!(
1191            kinds("enum match Option record self Some None is"),
1192            vec![Enum, Match, Option, Record, Self_, Some, None, Is],
1193        );
1194    }
1195
1196    #[test]
1197    fn pipe_and_pipe_pipe_disambiguated() {
1198        use TokenKind::*;
1199        assert_eq!(kinds("| || |"), vec![Pipe, PipePipe, Pipe]);
1200    }
1201
1202    #[test]
1203    fn v0_7_keywords() {
1204        use TokenKind::*;
1205        assert_eq!(kinds("expect suite case"), vec![Expect, Suite, Case],);
1206        // v0.118: `mocks` and `wires` are retired — plain identifiers now.
1207        assert_eq!(kinds("mocks wires"), vec![Ident, Ident]);
1208    }
1209
1210    #[test]
1211    fn fat_arrow_and_underscore() {
1212        use TokenKind::*;
1213        assert_eq!(kinds("_ =>"), vec![Underscore, FatArrow]);
1214    }
1215
1216    // -- v0.43 string interpolation --
1217
1218    #[test]
1219    fn interp_string_is_one_token() {
1220        use TokenKind::*;
1221        assert_eq!(kinds(r#""Hello, \(name)!""#), vec![InterpStr]);
1222        // A plain string (no hole) stays a `StrLit`, via the logos path.
1223        assert_eq!(kinds(r#""Hello, world""#), vec![StrLit]);
1224    }
1225
1226    #[test]
1227    fn interp_balances_nested_parens_and_strings() {
1228        use TokenKind::*;
1229        // The `)` inside `f(x)` must not close the hole early.
1230        assert_eq!(kinds(r#""= \(f(x))""#), vec![InterpStr]);
1231        // A `)` inside a nested string inside the hole is also ignored.
1232        assert_eq!(kinds(r#""= \(label(")"))""#), vec![InterpStr]);
1233        // A nested interpolated string inside a hole.
1234        assert_eq!(kinds(r#""out \("in \(x)")""#), vec![InterpStr]);
1235    }
1236
1237    // Issue #473: hole-expanding tokenisation makes identifiers inside `\(…)`
1238    // visible to the LSP's token-based cursor resolution.
1239    #[test]
1240    fn expanding_holes_exposes_hole_identifiers() {
1241        use TokenKind::*;
1242        let expand = |src: &str| {
1243            tokenize_expanding_holes(src)
1244                .unwrap()
1245                .into_iter()
1246                .map(|t| t.kind)
1247                .collect::<Vec<_>>()
1248        };
1249        // The opaque `InterpStr` is replaced by its hole's tokens; the chunk
1250        // text (`Hello, ` / `!`) carries none.
1251        assert_eq!(expand(r#""Hello, \(name)!""#), vec![Ident]);
1252        // A call hole exposes every token of the call expression.
1253        assert_eq!(expand(r#""= \(f(x))""#), vec![Ident, LParen, Ident, RParen]);
1254        // Nested interpolation recurses to the innermost hole's identifier.
1255        assert_eq!(expand(r#""out \("in \(x)")""#), vec![Ident]);
1256        // A plain (hole-free) string is untouched.
1257        assert_eq!(expand(r#""Hello, world""#), vec![StrLit]);
1258    }
1259
1260    #[test]
1261    fn expanding_holes_rebases_spans_to_absolute() {
1262        let src = r#""Hello, \(name)!""#;
1263        let toks = tokenize_expanding_holes(src).unwrap();
1264        let ident = toks
1265            .iter()
1266            .find(|t| t.kind == TokenKind::Ident)
1267            .expect("the hole identifier is exposed");
1268        // The span points at `name` in the original source, not a hole-local 0.
1269        assert_eq!(&src[ident.span.range()], "name");
1270        assert_eq!(ident.span.start, src.find("name").unwrap());
1271    }
1272
1273    #[test]
1274    fn escaped_open_paren_is_not_a_hole() {
1275        use TokenKind::*;
1276        // `\\(` is a literal backslash followed by `(` — no hole, so the
1277        // string lexes as a plain `StrLit` on the logos path.
1278        assert_eq!(kinds(r#""a \\(b) c""#), vec![StrLit]);
1279    }
1280
1281    #[test]
1282    fn unterminated_hole_is_an_error() {
1283        // The hole runs to end of line without its closing `)`.
1284        let err = tokenize("\"value \\(x + 1\n\"").unwrap_err();
1285        assert_eq!(err.category, "bynk.lex.unterminated_interpolation");
1286    }
1287
1288    #[test]
1289    fn unterminated_interp_string_is_an_error() {
1290        // A hole closes but the string never does (newline before the `"`).
1291        let err = tokenize("\"value \\(x) more\n").unwrap_err();
1292        assert_eq!(err.category, "bynk.lex.unterminated_string");
1293    }
1294
1295    #[test]
1296    fn bad_escape_in_interp_string_is_an_error() {
1297        let err = tokenize(r#""a \q \(x)""#).unwrap_err();
1298        assert_eq!(err.category, "bynk.lex.bad_escape");
1299    }
1300}