run-rs 0.2.16

Run a subset of Rust as an interpreted script
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
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
//! The compiled form a script runs as. The compiler lowers the `syn` AST into a
//! `Chunk` of register based instructions once, then the VM executes it without
//! ever touching the parse tree again. Registers are numbered slots in a flat
//! frame, so variable access is an array read, not a name lookup.

use std::rc::Rc;
use std::sync::Arc;

use super::typeir::{CastIr, TypeIr};

pub type Reg = u16;

/// A literal constant baked into a chunk, value model neutral so both the fast
/// `Rc` engine and the parallel `Arc` engine share the same compiler output.
/// Each engine materializes a `Const` into its own value type when a
/// `LoadConst` runs.
/// Only literals that need a side table land here. Integers, booleans, and unit
/// are emitted as their own inline load ops, so they are not `Const` variants.
#[derive(Clone)]
pub enum Const {
    Float(f64),
    /// An f32 literal, parsed from its digits at f32 precision so the value
    /// never takes a detour through f64 rounding.
    F32(f32),
    Char(char),
    Str(Arc<str>),
    /// A byte string literal `b"..."`, materialized into a vec of integers.
    Bytes(Arc<[u8]>),
}

/// Sentinel destination for a method call whose result a statement discards.
/// The VM skips building and writing the return value, which lets hot ops
/// like map insert avoid allocating a `Some(old)` nobody reads.
pub const DISCARD: Reg = Reg::MAX;

/// Binary operators, kept separate from `syn` so the hot loop carries no parse
/// tree types.
#[derive(Clone, Copy, Debug)]
pub enum BinKind {
    Add,
    Sub,
    Mul,
    Div,
    Rem,
    Eq,
    Ne,
    Lt,
    Le,
    Gt,
    Ge,
    BitAnd,
    BitOr,
    BitXor,
    Shl,
    Shr,
}

/// The verb real Rust uses in the overflow panic for each arithmetic op.
pub fn overflow_message(op: BinKind) -> &'static str {
    match op {
        BinKind::Add => "attempt to add with overflow",
        BinKind::Sub => "attempt to subtract with overflow",
        BinKind::Mul => "attempt to multiply with overflow",
        BinKind::Div => "attempt to divide with overflow",
        BinKind::Rem => "attempt to calculate the remainder with overflow",
        _ => "attempt to compute with overflow",
    }
}

#[derive(Clone, Copy, Debug)]
pub enum UnKind {
    Neg,
    Not,
}

/// A field being read or written, named for structs, positional for tuples.
#[derive(Clone)]
pub enum Member {
    Named(Rc<str>),
    Indexed(usize),
}

/// Where a closure upvalue is copied from when the closure is built.
#[derive(Clone, Copy)]
pub enum CapSource {
    /// A local register in the enclosing function.
    Local(Reg),
    /// An upvalue of the enclosing closure.
    Upvalue(u16),
    /// A local register shared through a mutable capture cell.
    MutableLocal(Reg),
    /// A mutable capture cell from the enclosing closure.
    MutableUpvalue(u16),
}

impl CapSource {
    pub fn is_mutable(self) -> bool {
        matches!(self, Self::MutableLocal(_) | Self::MutableUpvalue(_))
    }
}

/// A struct literal, fields already ordered to match the declaration so
/// serialization matches the compiler. The shape is built once at compile
/// time and shared by every instance the literal creates.
pub struct StructLit {
    /// Field names in the register order `base..base+fields.len()`.
    pub shape: Rc<super::value::StructShape>,
    /// Whether a trailing `..rest` value sits in the register after the fields.
    pub has_rest: bool,
}

#[derive(Clone)]
pub struct EnumVariant {
    pub enum_name: Rc<str>,
    pub variant: Rc<str>,
}

/// A method name with its builtin id resolved once at compile time, so hot
/// dispatch matches an enum instead of comparing strings.
#[derive(Clone)]
pub struct MethodName {
    pub text: String,
    pub id: BuiltinId,
    /// The scalar type of an explicit turbofish, `s.parse::<u8>()` for one.
    /// Names are allocated per call site, so this rides along without an
    /// extra operand. Without it `parse` had to guess its target from the
    /// text, which made `"300".parse::<u8>()` an `Ok(300)`.
    pub scalar: Option<ScalarTy>,
}

/// A concrete type a turbofish can name, for the methods whose result type is
/// chosen by the caller rather than by the receiver. The containers nest so a
/// payload stays readable through more than one layer, which is what
/// `Some(None::<f64>).unwrap_or_default().unwrap_or_default()` needs.
#[derive(Clone, PartialEq, Eq, Debug)]
pub enum ScalarTy {
    Int(super::numeric::IntWidth),
    F32,
    F64,
    Bool,
    Char,
    Str,
    /// `Option<T>`. Its own `Default` is `None`, and `T` is what one more
    /// unwrap answers with.
    Opt(Box<ScalarTy>),
    /// `Vec<T>`, whose `Default` is the empty vec.
    List(Box<ScalarTy>),
    /// A type the source named but this model does not describe, a user
    /// struct for one. Only its presence matters, never its identity.
    Other,
}

impl ScalarTy {
    /// Lower a turbofish type argument, or `None` for anything that is not one
    /// of these scalars.
    pub fn lower(ty: &syn::Type) -> Option<Self> {
        let syn::Type::Path(path) = ty else {
            return None;
        };
        let segment = path.path.segments.last()?;
        if let syn::PathArguments::AngleBracketed(args) = &segment.arguments {
            // A container knows its own `Default` whatever it holds, and the
            // element type is still carried so one more unwrap can read it.
            let inner = || Box::new(Self::first_arg(args).unwrap_or(Self::Other));
            return match segment.ident.to_string().as_str() {
                "Option" => Some(Self::Opt(inner())),
                "Vec" | "VecDeque" => Some(Self::List(inner())),
                _ => None,
            };
        }
        Some(match segment.ident.to_string().as_str() {
            "f32" => Self::F32,
            "f64" => Self::F64,
            "bool" => Self::Bool,
            "char" => Self::Char,
            "String" | "str" => Self::Str,
            name => Self::Int(super::numeric::IntWidth::parse(name)?),
        })
    }

    /// The first type argument of a generic path segment.
    fn first_arg(args: &syn::AngleBracketedGenericArguments) -> Option<Self> {
        args.args.iter().find_map(|arg| match arg {
            syn::GenericArgument::Type(ty) => Self::lower(ty),
            _ => None,
        })
    }

    /// What one more unwrap of this type answers with, for a chain like
    /// `Some(None::<f64>).unwrap_or_default().unwrap_or_default()`.
    pub fn payload(&self) -> Option<&ScalarTy> {
        match self {
            Self::Opt(inner) | Self::List(inner) => Some(inner),
            _ => None,
        }
    }
}

/// Ids for the builtin and higher-order methods the dispatcher special-cases.
/// `Other` falls back to name-string dispatch, so an unlisted method still
/// works, it just pays the string compares.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum BuiltinId {
    Len,
    IsEmpty,
    Clone,
    ToString,
    Get,
    Insert,
    ContainsKey,
    Remove,
    Entry,
    Keys,
    Values,
    Iter,
    IterMut,
    Push,
    Pop,
    First,
    Last,
    SplitFirst,
    Contains,
    Sort,
    Join,
    Concat,
    Sum,
    Product,
    Enumerate,
    Rev,
    Count,
    Take,
    Skip,
    PushStr,
    /// `bool::then`, which takes a closure.
    Then,
    /// `clone_from`, which replaces the receiver and so is handled by the VM.
    CloneFrom,
    SplitWhitespace,
    Split,
    Chars,
    Lines,
    Trim,
    StartsWith,
    EndsWith,
    Parse,
    Unwrap,
    UnwrapOr,
    Copied,
    // Higher-order methods, dispatched before the plain builtins.
    Map,
    Filter,
    FilterMap,
    FlatMap,
    ForEach,
    Find,
    Position,
    Any,
    All,
    Fold,
    Reduce,
    Retain,
    SortByKey,
    SortByCachedKey,
    SortBy,
    MaxByKey,
    MinByKey,
    TakeWhile,
    SkipWhile,
    Partition,
    AndThen,
    MapErr,
    MapOr,
    UnwrapOrElse,
    OkOrElse,
    WithContext,
    OrInsertWith,
    OrInsertWithKey,
    AndModify,
    Other,
}

impl BuiltinId {
    pub fn resolve(name: &str) -> BuiltinId {
        use BuiltinId::*;
        match name {
            "len" => Len,
            "is_empty" => IsEmpty,
            "clone" => Clone,
            "to_string" => ToString,
            // A returned container is Rc shared, so mutating it reaches the
            // original. That is what `get_mut` is for, so it resolves to the
            // same op rather than needing a mutable borrow the VM has no
            // concept of.
            "get" | "get_mut" => Get,
            "then" => Then,
            "clone_from" => CloneFrom,
            "insert" => Insert,
            "contains_key" => ContainsKey,
            "remove" => Remove,
            "entry" => Entry,
            "keys" => Keys,
            "values" => Values,
            "iter" | "into_iter" => Iter,
            "iter_mut" => IterMut,
            "push" => Push,
            "pop" => Pop,
            "first" => First,
            "last" => Last,
            "split_first" => SplitFirst,
            "contains" => Contains,
            "sort" => Sort,
            "join" => Join,
            "concat" => Concat,
            "sum" => Sum,
            "product" => Product,
            "enumerate" => Enumerate,
            "rev" => Rev,
            "count" => Count,
            "take" => Take,
            "skip" => Skip,
            "push_str" => PushStr,
            "split_whitespace" => SplitWhitespace,
            "split" => Split,
            "chars" => Chars,
            "lines" => Lines,
            "trim" => Trim,
            "starts_with" => StartsWith,
            "ends_with" => EndsWith,
            "parse" => Parse,
            "unwrap" => Unwrap,
            "unwrap_or" => UnwrapOr,
            "copied" | "cloned" => Copied,
            "map" => Map,
            "filter" => Filter,
            "filter_map" => FilterMap,
            "flat_map" => FlatMap,
            "for_each" => ForEach,
            "find" => Find,
            "position" => Position,
            "any" => Any,
            "all" => All,
            "fold" => Fold,
            "reduce" => Reduce,
            "retain" => Retain,
            "sort_by_key" => SortByKey,
            "sort_by_cached_key" => SortByCachedKey,
            "sort_by" => SortBy,
            "max_by_key" => MaxByKey,
            "min_by_key" => MinByKey,
            "take_while" => TakeWhile,
            "skip_while" => SkipWhile,
            "partition" => Partition,
            "and_then" => AndThen,
            "map_err" => MapErr,
            "map_or" => MapOr,
            "unwrap_or_else" => UnwrapOrElse,
            "ok_or_else" => OkOrElse,
            "with_context" => WithContext,
            "or_insert_with" => OrInsertWith,
            "or_insert_with_key" => OrInsertWithKey,
            "and_modify" => AndModify,
            _ => Other,
        }
    }

    /// Whether this method takes a closure and must run through the
    /// interpreter's higher-order dispatch.
    pub fn is_higher_order(self) -> bool {
        use BuiltinId::*;
        matches!(
            self,
            Then | Map
                | Filter
                | FilterMap
                | FlatMap
                | ForEach
                | Find
                | Position
                | Any
                | All
                | Fold
                | Reduce
                | Retain
                | SortByKey
                | SortByCachedKey
                | SortBy
                | MaxByKey
                | MinByKey
                | TakeWhile
                | SkipWhile
                | Partition
                | AndThen
                | MapErr
                | MapOr
                | UnwrapOrElse
                | OkOrElse
                | WithContext
                | OrInsertWith
                | OrInsertWithKey
                | AndModify
                | Other
        )
    }
}

/// A precompiled format template plus where each argument lives.
#[derive(Clone)]
pub struct FmtSpec {
    pub template: String,
    /// Positional argument registers, in order.
    pub positional: Vec<Reg>,
    /// Named and inline `{name}` arguments.
    pub named: Vec<(String, Reg)>,
}

/// A pattern plus the register each name it binds writes into.
pub struct PatInfo {
    pub pat: PPat,
    pub binds: Vec<(String, Reg)>,
}

#[derive(Clone)]
pub enum PLit {
    Int(i64),
    Float(f64),
    Bool(bool),
    Str(String),
    Char(char),
}

#[derive(Clone)]
pub enum PPat {
    Wild,
    Rest,
    Ident {
        name: String,
        sub: Option<Box<PPat>>,
    },
    Lit(PLit),
    Tuple(Vec<PPat>),
    TupleStruct {
        name: Option<String>,
        elems: Vec<PPat>,
    },
    Path {
        name: Option<String>,
    },
    Struct {
        name: Option<String>,
        fields: Vec<(String, PPat)>,
    },
    Or(Vec<PPat>),
    Slice(Vec<PPat>),
    /// A literal range like `b'a'..=b'z'`, `'0'..='9'`, or `1..5`. A missing
    /// endpoint leaves that side unbounded.
    Range {
        lo: Option<PLit>,
        hi: Option<PLit>,
        inclusive: bool,
    },
    Unsupported,
}

#[derive(Clone, Copy)]
pub enum MacroKind {
    Println,
    Print,
    Eprintln,
    Eprint,
    Panic,
    Anyhow,
    Bail,
}

#[derive(Clone)]
pub enum Op {
    LoadConst {
        dst: Reg,
        k: u16,
    },
    LoadInt {
        dst: Reg,
        v: i64,
    },
    /// A width-tagged integer literal: a suffixed one, an annotated one, or a
    /// bare literal past i64::MAX, which real Rust can only type as u64 or
    /// usize. `v` is the storage form of `super::numeric::IntWidth`.
    LoadIntW {
        dst: Reg,
        v: i64,
        w: super::numeric::IntWidth,
    },
    LoadBool {
        dst: Reg,
        v: bool,
    },
    LoadUnit {
        dst: Reg,
    },
    LoadUpvalue {
        dst: Reg,
        idx: u16,
    },
    LoadCell {
        dst: Reg,
        cell: Reg,
    },
    StoreCell {
        cell: Reg,
        src: Reg,
    },
    StoreUpvalue {
        idx: u16,
        src: Reg,
    },
    /// Read a module level const or static, evaluated lazily on first use.
    LoadGlobal {
        dst: Reg,
        idx: u32,
    },
    Move {
        dst: Reg,
        src: Reg,
    },

    Bin {
        dst: Reg,
        a: Reg,
        b: Reg,
        op: BinKind,
    },
    /// Binary op with an integer literal right operand, `n - 1`, `i < len`.
    BinImm {
        dst: Reg,
        a: Reg,
        imm: i64,
        op: BinKind,
    },
    Un {
        dst: Reg,
        a: Reg,
        op: UnKind,
    },

    Jump {
        to: u32,
    },
    JumpIfFalse {
        cond: Reg,
        to: u32,
    },
    JumpIfTrue {
        cond: Reg,
        to: u32,
    },
    /// Fused compare and branch: jump to `to` when `a op b` is false.
    CmpJump {
        a: Reg,
        b: Reg,
        op: BinKind,
        to: u32,
    },
    /// Fused compare and branch against an integer literal.
    CmpJumpImm {
        a: Reg,
        imm: i64,
        op: BinKind,
        to: u32,
    },

    /// Direct call of a known top level function, by global index.
    /// `targ` indexes the caller chunk's `call_type_args`, or `u32::MAX` when
    /// the call had no turbofish type arguments.
    CallFn {
        dst: Reg,
        func: u32,
        base: Reg,
        argc: u16,
        targ: u32,
    },
    /// Call a closure value held in a register.
    CallValue {
        dst: Reg,
        callee: Reg,
        base: Reg,
        argc: u16,
    },
    /// Any other call, `Type::assoc`, a bridge, a constructor, resolved by path.
    CallPath {
        dst: Reg,
        path: u16,
        base: Reg,
        argc: u16,
    },
    /// A path used as a value, `None`, a unit enum variant, `consts::OS`.
    PathValue {
        dst: Reg,
        path: u16,
    },
    /// `recv.method(args)`.
    Method {
        dst: Reg,
        recv: Reg,
        name: u16,
        base: Reg,
        argc: u16,
    },
    /// Fused `recv.get(key).copied().unwrap_or(default)`. One probe, no
    /// intermediate Option built. Falls back to the three real methods for
    /// receivers that are not a map or a vector.
    GetOrDefault {
        dst: Reg,
        recv: Reg,
        key: Reg,
        default: Reg,
    },
    Ret {
        src: Reg,
    },

    MakeVec {
        dst: Reg,
        base: Reg,
        count: u16,
    },
    MakeTuple {
        dst: Reg,
        base: Reg,
        count: u16,
    },
    MakeArrayRepeat {
        dst: Reg,
        val: Reg,
        count: Reg,
    },
    MakeRange {
        dst: Reg,
        start: Reg,
        end: Reg,
        inclusive: bool,
    },
    /// Materialize any iterable in `src` into an iterator held in `dst`.
    IterInit {
        dst: Reg,
        src: Reg,
    },
    /// Read the next item of the iterator in `iter` into `val`, advancing `idx`.
    /// Jumps to `to` when exhausted.
    ForNext {
        iter: Reg,
        idx: Reg,
        val: Reg,
        to: u32,
    },
    MakeStruct {
        dst: Reg,
        info: u16,
        base: Reg,
    },
    MakeEnum {
        dst: Reg,
        info: u16,
        base: Reg,
        count: u16,
    },
    LoadEnum {
        dst: Reg,
        info: u16,
    },
    MakeClosure {
        dst: Reg,
        child: u16,
    },

    Index {
        dst: Reg,
        base: Reg,
        key: Reg,
    },
    SetIndex {
        base: Reg,
        key: Reg,
        val: Reg,
    },
    Deref {
        dst: Reg,
        src: Reg,
    },
    SetDeref {
        target: Reg,
        val: Reg,
    },
    GetField {
        dst: Reg,
        base: Reg,
        member: u16,
    },
    SetField {
        base: Reg,
        member: u16,
        val: Reg,
    },

    /// The `?` operator. Unwraps Ok/Some into `dst`, or returns early on Err/None.
    Try {
        dst: Reg,
        src: Reg,
    },
    Cast {
        dst: Reg,
        src: Reg,
        ty: u16,
    },
    /// Coerce a dynamic value into an annotated type, `let c: Config = ..`.
    Coerce {
        dst: Reg,
        src: Reg,
        ty: u16,
    },

    /// Test `val` against a pattern, binding its names into their registers.
    /// `dst` receives a bool.
    TestBind {
        val: Reg,
        pat: u16,
        dst: Reg,
    },

    /// Render a format template into `dst`.
    Fmt {
        dst: Reg,
        spec: u16,
    },
    /// A statement macro that renders a template then acts on it.
    MacroCall {
        kind: MacroKind,
        dst: Reg,
        spec: u16,
    },
    /// `dbg!` takes plain registers, not a template.
    Dbg {
        dst: Reg,
        base: Reg,
        argc: u16,
    },

    /// Spawn child closure `child` as a tokio task, writing a JoinHandle into
    /// `dst`. Emitted only for `#[tokio::main]` scripts, run by the parallel VM.
    Spawn {
        dst: Reg,
        child: u16,
    },
    /// Await the future or JoinHandle in `src`, writing its result into `dst`.
    /// Parallel VM only.
    Await {
        dst: Reg,
        src: Reg,
    },
}

/// One compiled function, method, or closure body.
pub struct Chunk {
    pub code: Vec<Op>,
    /// Source line of each op, parallel to `code`. Zero means unknown, so a
    /// synthesized chunk with no lines still traces by function name alone.
    pub lines: Vec<u32>,
    /// Source file this body was written in, shown in runtime error traces.
    pub file: Arc<str>,
    pub num_regs: usize,
    pub num_params: usize,
    pub name: String,
    /// Module this body was written in, for runtime type resolution.
    pub module: u16,

    // Side tables referenced by instruction operands.
    pub consts: Vec<Const>,
    pub members: Vec<Member>,
    pub pats: Vec<PatInfo>,
    pub fmts: Vec<FmtSpec>,
    pub struct_lits: Vec<StructLit>,
    pub enum_variants: Vec<EnumVariant>,
    pub casts: Vec<CastIr>,
    /// Annotated `let` coercion targets, referenced by `Coerce`.
    pub coerces: Vec<TypeIr>,
    /// Path calls, the segments plus an optional turbofish coercion type.
    pub paths: Vec<(Vec<String>, Option<TypeIr>)>,
    pub names: Vec<MethodName>,
    /// Nested closure bodies, referenced by `MakeClosure`.
    pub children: Vec<Rc<Chunk>>,
    /// For each child, where to copy its upvalues from.
    pub child_caps: Vec<Vec<CapSource>>,
    /// Generic parameter names of this function, in order, e.g. `["T"]`. Used
    /// to bind a caller's turbofish type args when the body resolves them.
    pub generics: Vec<Rc<str>>,
    /// Turbofish type args recorded at `CallFn` sites, referenced by `targ`.
    pub call_type_args: Vec<Arc<[TypeIr]>>,
}

impl Chunk {
    pub fn empty(name: impl Into<String>) -> Chunk {
        Chunk {
            code: Vec::new(),
            lines: Vec::new(),
            file: Arc::from(""),
            num_regs: 0,
            num_params: 0,
            name: name.into(),
            module: 0,
            consts: Vec::new(),
            members: Vec::new(),
            pats: Vec::new(),
            fmts: Vec::new(),
            struct_lits: Vec::new(),
            enum_variants: Vec::new(),
            casts: Vec::new(),
            coerces: Vec::new(),
            paths: Vec::new(),
            names: Vec::new(),
            children: Vec::new(),
            child_caps: Vec::new(),
            generics: Vec::new(),
            call_type_args: Vec::new(),
        }
    }
}