bynk-syntax 0.142.0

Bynk's syntax foundation: lexer, parser, AST, spans, the CompileError type, and the diagnostic-code registry — the lowest leaf of the compiler crate set.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
//! Type parsing — type declarations (refined/opaque/record/sum), signed
//! numeric literals, and type references (`parse_type_ref`/`parse_type_atom`
//! incl. function-type arrows). Split out of `parser.rs` (ADR 0060) as a
//! further `impl Parser` block; the scanning core and the other concerns
//! stay in the parent module, reached as ancestor privates via `self`.

use super::*;

impl<'a> Parser<'a> {
    // -- type declarations --

    pub(crate) fn parse_type_decl(&mut self) -> Result<TypeDecl, CompileError> {
        let kw = self.expect(TokenKind::Type, "to start a type declaration")?;
        let name = self.expect_ident("after `type`")?;
        // v0.20a (Open-narrow): generic *type* declarations stay rejected —
        // `List`/`Map` (built-in) remain the only generic types.
        if self.peek_kind() == Some(TokenKind::LBracket) {
            let open = self.bump().unwrap();
            return Err(CompileError::new(
                "bynk.generics.no_generic_types",
                open.span,
                format!(
                    "type `{}` declares type parameters — generic type declarations are not in v0.20a (type parameters belong to functions)",
                    name.name
                ),
            )
            .with_note("only functions take type parameters (`fn name[A, B](…)`); the built-in generic types are fixed"));
        }
        self.expect(TokenKind::Eq, "after the type name")?;
        // Dispatch on the head token to decide which kind of type body to parse:
        //   `{ ... }`         → record body (v0.2)
        //   `|` ...           → pipe-form sum (v0.2)
        //   `enum { ... }`    → enum-form sum (v0.2)
        //   `opaque ...`      → opaque base type (v0.3)
        //   anything else     → refined base type (v0)
        let (body, end_span) = match self.peek_kind() {
            Some(TokenKind::LBrace) => {
                let r = self.parse_record_body()?;
                let span = r.span;
                (TypeBody::Record(r), span)
            }
            Some(TokenKind::Pipe) => {
                let s = self.parse_sum_body_pipe()?;
                let span = s.span;
                (TypeBody::Sum(s), span)
            }
            Some(TokenKind::Enum) => {
                let s = self.parse_sum_body_enum()?;
                let span = s.span;
                (TypeBody::Sum(s), span)
            }
            Some(TokenKind::Opaque) => {
                self.bump();
                let (base, base_span) = self.parse_base_type()?;
                let mut refinement = None;
                let mut end_span = base_span;
                if self.eat(TokenKind::Where).is_some() {
                    let r = self.parse_refinement()?;
                    end_span = r.span;
                    refinement = Some(r);
                }
                (
                    TypeBody::Opaque {
                        base,
                        base_span,
                        refinement,
                    },
                    end_span,
                )
            }
            _ => {
                let (base, base_span) = self.parse_base_type()?;
                let mut refinement = None;
                let mut end_span = base_span;
                if self.eat(TokenKind::Where).is_some() {
                    let r = self.parse_refinement()?;
                    end_span = r.span;
                    refinement = Some(r);
                }
                (
                    TypeBody::Refined {
                        base,
                        base_span,
                        refinement,
                    },
                    end_span,
                )
            }
        };
        Ok(TypeDecl {
            name,
            body,
            documentation: None,
            span: kw.span.merge(end_span),
            trivia: Trivia::default(),
        })
    }

    /// Parse the body of a record type: `{ field, field, ... }`.
    /// Each field is `name : type-ref (where refinement)?`; trailing
    /// comma after the last field is allowed.
    fn parse_record_body(&mut self) -> Result<RecordBody, CompileError> {
        let open = self.expect(TokenKind::LBrace, "to open the record body")?;
        let mut fields = Vec::new();
        while self.peek_kind() != Some(TokenKind::RBrace) {
            fields.push(self.parse_record_field()?);
            if self.eat(TokenKind::Comma).is_none() {
                break;
            }
        }
        let close = self.expect(TokenKind::RBrace, "to close the record body")?;
        Ok(RecordBody {
            fields,
            span: open.span.merge(close.span),
        })
    }

    pub(crate) fn parse_record_field(&mut self) -> Result<RecordField, CompileError> {
        let name = self.expect_ident("as a record field name")?;
        self.expect(TokenKind::Colon, "after the field name")?;
        let type_ref = self.parse_type_ref("as the field type")?;
        let mut refinement = None;
        let mut end_span = type_ref.span();
        if self.eat(TokenKind::Where).is_some() {
            let r = self.parse_refinement()?;
            end_span = r.span;
            refinement = Some(r);
        }
        // v0.11: an optional `= <expr>` initial-value, used by agent state
        // fields. Parsed for every record field; the checker restricts where it
        // is meaningful.
        let mut init = None;
        if self.eat(TokenKind::Eq).is_some() {
            let e = self.parse_expr()?;
            end_span = e.span;
            init = Some(e);
        }
        Ok(RecordField {
            name: name.clone(),
            type_ref,
            refinement,
            init,
            span: name.span.merge(end_span),
        })
    }

    /// Parse a pipe-form sum body: `| Variant | Variant(field, ...)`.
    /// The leading `|` is required (spec v0.2 §3.2).
    fn parse_sum_body_pipe(&mut self) -> Result<SumBody, CompileError> {
        let mut variants = Vec::new();
        let mut span: Option<Span> = None;
        while self.peek_kind() == Some(TokenKind::Pipe) {
            let bar = self.bump().unwrap();
            let name = self.expect_ident("after `|` in a sum variant")?;
            let mut payload = Vec::new();
            let mut end_span = name.span;
            if self.peek_kind() == Some(TokenKind::LParen) {
                self.bump();
                if self.peek_kind() != Some(TokenKind::RParen) {
                    payload.push(self.parse_variant_field()?);
                    while self.eat(TokenKind::Comma).is_some() {
                        if self.peek_kind() == Some(TokenKind::RParen) {
                            break;
                        }
                        payload.push(self.parse_variant_field()?);
                    }
                }
                let close =
                    self.expect(TokenKind::RParen, "to close the variant's payload list")?;
                end_span = close.span;
            }
            let v_span = bar.span.merge(end_span);
            variants.push(Variant {
                name,
                payload,
                span: v_span,
            });
            span = Some(match span {
                Some(s) => s.merge(v_span),
                None => v_span,
            });
        }
        let span = span.expect("parse_sum_body_pipe called without `|`");
        Ok(SumBody { variants, span })
    }

    /// Parse an enum-shorthand sum body: `enum { Tag, Tag, Tag }`.
    fn parse_sum_body_enum(&mut self) -> Result<SumBody, CompileError> {
        let kw = self.expect(TokenKind::Enum, "to start an enum-form sum body")?;
        self.expect(TokenKind::LBrace, "after `enum`")?;
        let mut variants = Vec::new();
        while self.peek_kind() != Some(TokenKind::RBrace) {
            let name = self.expect_ident("as an enum tag name")?;
            let span = name.span;
            variants.push(Variant {
                name,
                payload: Vec::new(),
                span,
            });
            if self.eat(TokenKind::Comma).is_none() {
                break;
            }
        }
        let close = self.expect(TokenKind::RBrace, "to close the enum body")?;
        Ok(SumBody {
            variants,
            span: kw.span.merge(close.span),
        })
    }

    fn parse_variant_field(&mut self) -> Result<VariantField, CompileError> {
        let name = self.expect_ident("as a variant payload field name")?;
        self.expect(TokenKind::Colon, "after the variant payload field name")?;
        let type_ref = self.parse_type_ref("as the variant payload field type")?;
        let span = name.span.merge(type_ref.span());
        Ok(VariantField {
            name,
            type_ref,
            span,
        })
    }

    fn parse_base_type(&mut self) -> Result<(BaseType, Span), CompileError> {
        match self.peek() {
            Some(t) => match t.kind {
                TokenKind::Int => {
                    self.bump();
                    Ok((BaseType::Int, t.span))
                }
                TokenKind::String => {
                    self.bump();
                    Ok((BaseType::String, t.span))
                }
                TokenKind::Bool => {
                    self.bump();
                    Ok((BaseType::Bool, t.span))
                }
                TokenKind::Float => {
                    self.bump();
                    Ok((BaseType::Float, t.span))
                }
                TokenKind::Duration => {
                    self.bump();
                    Ok((BaseType::Duration, t.span))
                }
                TokenKind::Instant => {
                    self.bump();
                    Ok((BaseType::Instant, t.span))
                }
                TokenKind::Bytes => {
                    self.bump();
                    Ok((BaseType::Bytes, t.span))
                }
                _ => Err(CompileError::new(
                    "bynk.parse.expected_base_type",
                    t.span,
                    format!(
                        "expected `Int`, `String`, `Bool`, `Float`, `Duration`, `Instant`, or `Bytes`, found {}",
                        t.kind.describe()
                    ),
                )
                .with_note("type declarations are refined base types in v0")),
            },
            None => Err(CompileError::new(
                "bynk.parse.unexpected_eof",
                self.eof_span(),
                "expected `Int`, `String`, `Bool`, or `Float`, found end of file",
            )),
        }
    }

    fn parse_refinement(&mut self) -> Result<Refinement, CompileError> {
        let mut predicates = vec![self.parse_refinement_pred()?];
        let mut span = predicates[0].span;
        while self.eat(TokenKind::And).is_some() {
            let p = self.parse_refinement_pred()?;
            span = span.merge(p.span);
            predicates.push(p);
        }
        Ok(Refinement { predicates, span })
    }

    fn parse_refinement_pred(&mut self) -> Result<RefinementPred, CompileError> {
        let t = self.peek().ok_or_else(|| {
            CompileError::new(
                "bynk.parse.unexpected_eof",
                self.eof_span(),
                "expected a refinement predicate, found end of file",
            )
        })?;
        // Allow `Int` etc. through here would be wrong; predicate names are plain
        // identifiers (and not keywords).
        if t.kind != TokenKind::Ident {
            return Err(CompileError::new(
                "bynk.parse.expected_predicate",
                t.span,
                format!(
                    "expected a refinement predicate name, found {}",
                    t.kind.describe()
                ),
            )
            .with_note(
                "valid predicates: Matches, InRange, MinLength, MaxLength, Length, \
                 NonNegative, Positive, NonEmpty",
            ));
        }
        self.bump();
        let name = self.slice(t.span);
        let start = t.span;
        let (kind, end_span) = match name {
            "Matches" => {
                self.expect(TokenKind::LParen, "after `Matches`")?;
                let s_tok = self.expect(TokenKind::StrLit, "as the argument to `Matches`")?;
                let pat = parse_string_literal(self.slice(s_tok.span), s_tok.span)?;
                let close = self.expect(TokenKind::RParen, "after the `Matches` argument")?;
                (PredKind::Matches(pat), close.span)
            }
            "InRange" => {
                self.expect(TokenKind::LParen, "after `InRange`")?;
                let lo = self.parse_signed_num_literal("as the lower bound of `InRange`")?;
                self.expect(TokenKind::Comma, "between `InRange` arguments")?;
                let hi = self.parse_signed_num_literal("as the upper bound of `InRange`")?;
                let close = self.expect(TokenKind::RParen, "after the `InRange` arguments")?;
                let kind = match (lo, hi) {
                    (SignedNumLit::Int(a), SignedNumLit::Int(b)) => PredKind::InRange(a, b),
                    (SignedNumLit::Float(a), SignedNumLit::Float(b)) => PredKind::InRangeF(a, b),
                    _ => {
                        return Err(CompileError::new(
                            "bynk.types.no_numeric_coercion",
                            start.merge(close.span),
                            "`InRange` bounds mix an `Int` literal and a `Float` literal",
                        )
                        .with_note(
                            "both bounds must be the same numeric type — \
                             write `InRange(0, 1)` or `InRange(0.0, 1.0)`",
                        ));
                    }
                };
                (kind, close.span)
            }
            "MinLength" => {
                self.expect(TokenKind::LParen, "after `MinLength`")?;
                let n = self.parse_signed_int_literal("as the argument to `MinLength`")?;
                let close = self.expect(TokenKind::RParen, "after the `MinLength` argument")?;
                (PredKind::MinLength(n), close.span)
            }
            "MaxLength" => {
                self.expect(TokenKind::LParen, "after `MaxLength`")?;
                let n = self.parse_signed_int_literal("as the argument to `MaxLength`")?;
                let close = self.expect(TokenKind::RParen, "after the `MaxLength` argument")?;
                (PredKind::MaxLength(n), close.span)
            }
            "Length" => {
                self.expect(TokenKind::LParen, "after `Length`")?;
                let n = self.parse_signed_int_literal("as the argument to `Length`")?;
                let close = self.expect(TokenKind::RParen, "after the `Length` argument")?;
                (PredKind::Length(n), close.span)
            }
            "NonNegative" => (PredKind::NonNegative, t.span),
            "Positive" => (PredKind::Positive, t.span),
            "NonEmpty" => (PredKind::NonEmpty, t.span),
            other => {
                return Err(CompileError::new(
                    "bynk.parse.unknown_predicate",
                    t.span,
                    format!("unknown refinement predicate `{other}`"),
                )
                .with_note(
                    "valid predicates: Matches, InRange, MinLength, MaxLength, Length, \
                     NonNegative, Positive, NonEmpty",
                ));
            }
        };
        Ok(RefinementPred {
            kind,
            span: start.merge(end_span),
        })
    }

    fn parse_signed_int_literal(&mut self, ctx: &str) -> Result<i64, CompileError> {
        let neg = self.eat(TokenKind::Minus).is_some();
        let t = self.expect(TokenKind::IntLit, ctx)?;
        let slice = self.slice(t.span);
        let n: i64 = slice.parse().map_err(|_| {
            CompileError::new(
                "bynk.lex.integer_overflow",
                t.span,
                format!("integer literal `{slice}` is out of range for a 64-bit signed integer"),
            )
        })?;
        Ok(if neg { -n } else { n })
    }

    /// A signed numeric literal in refinement-bound position (v0.21):
    /// either an `Int` or a `Float` literal, optionally negated. The float
    /// form keeps its (signed) lexeme for byte-stable emission.
    fn parse_signed_num_literal(&mut self, ctx: &str) -> Result<SignedNumLit, CompileError> {
        // v0.40 (ADR 0073): the bound span covers a leading `-` so the swap
        // quick-fix replaces `-10` as a unit.
        let minus = self.eat(TokenKind::Minus);
        let neg = minus.is_some();
        let span_of = |lit: Span| match &minus {
            Some(m) => m.span.merge(lit),
            None => lit,
        };
        match self.peek() {
            Some(t) if t.kind == TokenKind::IntLit => {
                self.bump();
                let slice = self.slice(t.span);
                let n: i64 = slice.parse().map_err(|_| {
                    CompileError::new(
                        "bynk.lex.integer_overflow",
                        t.span,
                        format!(
                            "integer literal `{slice}` is out of range for a 64-bit signed integer"
                        ),
                    )
                })?;
                Ok(SignedNumLit::Int(IntBound {
                    value: if neg { -n } else { n },
                    span: span_of(t.span),
                }))
            }
            Some(t) if t.kind == TokenKind::FloatLit => {
                self.bump();
                let slice = self.slice(t.span);
                // tokenize() already rejected non-finite literals.
                let v: f64 = slice.parse().unwrap_or(f64::NAN);
                let (value, lexeme) = if neg {
                    (-v, format!("-{slice}"))
                } else {
                    (v, slice.to_string())
                };
                Ok(SignedNumLit::Float(FloatBound {
                    value,
                    lexeme,
                    span: span_of(t.span),
                }))
            }
            Some(t) => Err(CompileError::new(
                "bynk.parse.expected_token",
                t.span,
                format!(
                    "expected a numeric literal {ctx}, found {}",
                    t.kind.describe()
                ),
            )),
            None => Err(CompileError::new(
                "bynk.parse.unexpected_eof",
                self.eof_span(),
                format!("expected a numeric literal {ctx}, found end of file"),
            )),
        }
    }

    /// v0.20a: a type reference — an atom, a parenthesised group, or a
    /// function type. `->` is **right-associative** (`A -> B -> C` is
    /// `A -> (B -> C)`). A parenthesised list is a function-type parameter
    /// list when followed by `->`; a grouping when it holds exactly one type
    /// (`(A -> B)` — unwrapped, so the formatter canonicalises); and the unit
    /// type when empty and arrow-free. The disambiguation is deferred to the
    /// arrow peek, so no extra lookahead is needed.
    pub(crate) fn parse_type_ref(&mut self, ctx: &str) -> Result<TypeRef, CompileError> {
        enum Group {
            Unit(Span),
            Single(TypeRef, Span),
            Multi(Vec<TypeRef>, Span),
        }
        let group = if self.peek_kind() == Some(TokenKind::LParen) {
            let open = self.bump().unwrap();
            if self.peek_kind() == Some(TokenKind::RParen) {
                let close = self.bump().unwrap();
                Group::Unit(open.span.merge(close.span))
            } else {
                let mut items = vec![self.parse_type_ref(ctx)?];
                while self.eat(TokenKind::Comma).is_some() {
                    items.push(self.parse_type_ref(ctx)?);
                }
                let close = self.expect(TokenKind::RParen, "to close the parenthesised type")?;
                let span = open.span.merge(close.span);
                if items.len() == 1 {
                    Group::Single(items.pop().unwrap(), span)
                } else {
                    Group::Multi(items, span)
                }
            }
        } else {
            let t = self.parse_type_atom(ctx)?;
            let span = t.span();
            Group::Single(t, span)
        };
        if self.peek_kind() == Some(TokenKind::Arrow) {
            self.bump();
            // Recursing through parse_type_ref makes `->` right-associative.
            let ret = self.parse_type_ref(ctx)?;
            let (params, start) = match group {
                Group::Unit(s) => (Vec::new(), s),
                Group::Single(t, s) => (vec![t], s),
                Group::Multi(ts, s) => (ts, s),
            };
            let span = start.merge(ret.span());
            return Ok(TypeRef::Fn(params, Box::new(ret), span));
        }
        match group {
            Group::Unit(s) => Ok(TypeRef::Unit(s)),
            Group::Single(t, _) => Ok(t),
            Group::Multi(_, s) => Err(CompileError::new(
                "bynk.parse.expected_token",
                s,
                "expected `->` after a parenthesised parameter list — a bare `(A, B)` is not a type",
            )),
        }
    }

    fn parse_type_atom(&mut self, ctx: &str) -> Result<TypeRef, CompileError> {
        match self.peek() {
            Some(t) => match t.kind {
                TokenKind::Int => {
                    self.bump();
                    Ok(TypeRef::Base(BaseType::Int, t.span))
                }
                TokenKind::String => {
                    self.bump();
                    Ok(TypeRef::Base(BaseType::String, t.span))
                }
                TokenKind::Bool => {
                    self.bump();
                    Ok(TypeRef::Base(BaseType::Bool, t.span))
                }
                TokenKind::Float => {
                    self.bump();
                    Ok(TypeRef::Base(BaseType::Float, t.span))
                }
                TokenKind::Duration => {
                    self.bump();
                    Ok(TypeRef::Base(BaseType::Duration, t.span))
                }
                TokenKind::Instant => {
                    self.bump();
                    Ok(TypeRef::Base(BaseType::Instant, t.span))
                }
                TokenKind::Bytes => {
                    self.bump();
                    Ok(TypeRef::Base(BaseType::Bytes, t.span))
                }
                TokenKind::Result => {
                    self.bump();
                    // Must be followed by `[T, E]`.
                    let lb = self.peek().map(|t| t.kind);
                    if lb != Some(TokenKind::LBracket) {
                        return Err(CompileError::new(
                            "bynk.parse.expected_token",
                            t.span,
                            "the built-in `Result` type requires two type arguments: `Result[T, E]`",
                        )
                        .with_note(
                            "`Result` cannot appear without its `[T, E]` parameters in v0.1",
                        ));
                    }
                    self.bump();
                    let arg_t = self.parse_type_ref("as the first `Result` type argument")?;
                    // Check for missing comma — typical user error is `Result[T]`.
                    if self.peek_kind() == Some(TokenKind::RBracket) {
                        let close = self.bump().unwrap();
                        return Err(CompileError::new(
                            "bynk.parse.generic_arg_count",
                            t.span.merge(close.span),
                            "the built-in `Result` type requires two type arguments: `Result[T, E]`",
                        )
                        .with_note("v0.1 has no other generic types; `Result` always has two parameters"));
                    }
                    self.expect(TokenKind::Comma, "between the `Result` type arguments")?;
                    let arg_e = self.parse_type_ref("as the second `Result` type argument")?;
                    let close =
                        self.expect(TokenKind::RBracket, "to close the `Result` type arguments")?;
                    Ok(TypeRef::Result(
                        Box::new(arg_t),
                        Box::new(arg_e),
                        t.span.merge(close.span),
                    ))
                }
                TokenKind::ValidationError => {
                    self.bump();
                    Ok(TypeRef::ValidationError(t.span))
                }
                TokenKind::JsonError => {
                    self.bump();
                    Ok(TypeRef::JsonError(t.span))
                }
                TokenKind::Option => {
                    self.bump();
                    if self.peek_kind() != Some(TokenKind::LBracket) {
                        return Err(CompileError::new(
                            "bynk.parse.expected_token",
                            t.span,
                            "the built-in `Option` type requires one type argument: `Option[T]`",
                        ));
                    }
                    self.bump();
                    let arg = self.parse_type_ref("as the `Option` type argument")?;
                    let close =
                        self.expect(TokenKind::RBracket, "to close the `Option` type argument")?;
                    Ok(TypeRef::Option(Box::new(arg), t.span.merge(close.span)))
                }
                TokenKind::Effect => {
                    self.bump();
                    if self.peek_kind() != Some(TokenKind::LBracket) {
                        return Err(CompileError::new(
                            "bynk.parse.expected_token",
                            t.span,
                            "the built-in `Effect` type requires one type argument: `Effect[T]`",
                        ));
                    }
                    self.bump();
                    let arg = self.parse_type_ref("as the `Effect` type argument")?;
                    let close =
                        self.expect(TokenKind::RBracket, "to close the `Effect` type argument")?;
                    Ok(TypeRef::Effect(Box::new(arg), t.span.merge(close.span)))
                }
                TokenKind::Ident => {
                    self.bump();
                    let name = self.slice(t.span).to_string();
                    // v0.9: `HttpResult` is a predeclared built-in generic.
                    if name == "HttpResult" {
                        if self.peek_kind() != Some(TokenKind::LBracket) {
                            return Err(CompileError::new(
                                "bynk.parse.expected_token",
                                t.span,
                                "the built-in `HttpResult` type requires one type argument: `HttpResult[T]`",
                            ));
                        }
                        self.bump();
                        let arg = self.parse_type_ref("as the `HttpResult` type argument")?;
                        let close = self.expect(
                            TokenKind::RBracket,
                            "to close the `HttpResult` type argument",
                        )?;
                        return Ok(TypeRef::HttpResult(Box::new(arg), t.span.merge(close.span)));
                    }
                    // v0.44: `QueueResult` is a predeclared non-generic built-in.
                    if name == "QueueResult" {
                        return Ok(TypeRef::QueueResult(t.span));
                    }
                    // v0.20b: `List` and `Map` are predeclared built-in generics.
                    if name == "List" {
                        if self.peek_kind() != Some(TokenKind::LBracket) {
                            return Err(CompileError::new(
                                "bynk.parse.expected_token",
                                t.span,
                                "the built-in `List` type requires one type argument: `List[T]`",
                            ));
                        }
                        self.bump();
                        let arg = self.parse_type_ref("as the `List` type argument")?;
                        let close =
                            self.expect(TokenKind::RBracket, "to close the `List` type argument")?;
                        return Ok(TypeRef::List(Box::new(arg), t.span.merge(close.span)));
                    }
                    // v0.91 (ADR 0115): `Query[T]` — the lazy storage-read type.
                    if name == "Query" {
                        if self.peek_kind() != Some(TokenKind::LBracket) {
                            return Err(CompileError::new(
                                "bynk.parse.expected_token",
                                t.span,
                                "the built-in `Query` type requires one type argument: `Query[T]`",
                            ));
                        }
                        self.bump();
                        let arg = self.parse_type_ref("as the `Query` type argument")?;
                        let close =
                            self.expect(TokenKind::RBracket, "to close the `Query` type argument")?;
                        return Ok(TypeRef::Query(Box::new(arg), t.span.merge(close.span)));
                    }
                    // v0.100: `Stream[T]` — the value-over-time primitive
                    // (real-time track, slice 0).
                    if name == "Stream" {
                        if self.peek_kind() != Some(TokenKind::LBracket) {
                            return Err(CompileError::new(
                                "bynk.parse.expected_token",
                                t.span,
                                "the built-in `Stream` type requires one type argument: `Stream[T]`",
                            ));
                        }
                        self.bump();
                        let arg = self.parse_type_ref("as the `Stream` type argument")?;
                        let close = self
                            .expect(TokenKind::RBracket, "to close the `Stream` type argument")?;
                        return Ok(TypeRef::Stream(Box::new(arg), t.span.merge(close.span)));
                    }
                    // v0.102: `Connection[F]` — a held WebSocket connection
                    // (real-time track, slice 2). `F` is the server→client frame
                    // type.
                    if name == "Connection" {
                        if self.peek_kind() != Some(TokenKind::LBracket) {
                            return Err(CompileError::new(
                                "bynk.parse.expected_token",
                                t.span,
                                "the built-in `Connection` type requires one type argument: `Connection[F]`",
                            ));
                        }
                        self.bump();
                        let arg = self.parse_type_ref("as the `Connection` frame type")?;
                        let close = self.expect(
                            TokenKind::RBracket,
                            "to close the `Connection` type argument",
                        )?;
                        return Ok(TypeRef::Connection(Box::new(arg), t.span.merge(close.span)));
                    }
                    // v0.119 (testing track slice 7, ADR 0155): `History[Agent]` — a
                    // generated, driven call-history. A test-only generator; the checker
                    // admits it only in `for all` binding position inside a `property`.
                    if name == "History" {
                        if self.peek_kind() != Some(TokenKind::LBracket) {
                            return Err(CompileError::new(
                                "bynk.parse.expected_token",
                                t.span,
                                "the built-in `History` type requires one type argument: `History[Agent]`",
                            ));
                        }
                        self.bump();
                        let arg = self.parse_type_ref("as the `History` type argument")?;
                        let close = self
                            .expect(TokenKind::RBracket, "to close the `History` type argument")?;
                        return Ok(TypeRef::History(Box::new(arg), t.span.merge(close.span)));
                    }
                    if name == "Map" {
                        if self.peek_kind() != Some(TokenKind::LBracket) {
                            return Err(CompileError::new(
                                "bynk.parse.expected_token",
                                t.span,
                                "the built-in `Map` type requires two type arguments: `Map[K, V]`",
                            ));
                        }
                        self.bump();
                        let arg_k = self.parse_type_ref("as the first `Map` type argument")?;
                        if self.peek_kind() == Some(TokenKind::RBracket) {
                            let close = self.bump().unwrap();
                            return Err(CompileError::new(
                                "bynk.parse.generic_arg_count",
                                t.span.merge(close.span),
                                "the built-in `Map` type requires two type arguments: `Map[K, V]`",
                            ));
                        }
                        self.expect(TokenKind::Comma, "between the `Map` type arguments")?;
                        let arg_v = self.parse_type_ref("as the second `Map` type argument")?;
                        let close =
                            self.expect(TokenKind::RBracket, "to close the `Map` type arguments")?;
                        return Ok(TypeRef::Map(
                            Box::new(arg_k),
                            Box::new(arg_v),
                            t.span.merge(close.span),
                        ));
                    }
                    Ok(TypeRef::Named(Ident { name, span: t.span }))
                }
                _ => Err(CompileError::new(
                    "bynk.parse.expected_type",
                    t.span,
                    format!("expected a type {ctx}, found {}", t.kind.describe()),
                )),
            },
            None => Err(CompileError::new(
                "bynk.parse.unexpected_eof",
                self.eof_span(),
                format!("expected a type {ctx}, found end of file"),
            )),
        }
    }
}