buildlang 1.15.0

BuildLang (buildc): an effects-oriented compiler with a verified C path, shader output, experimental backends, opt-in linear types, and re-checkable accountability + scientific-runtime receipts
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
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
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
// ===============================================================================
// BUILDLANG CODE GENERATOR - MIR BUILDER
// ===============================================================================
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (c) 2022-2026 Zain Dana Harper.
// ===============================================================================

//! MIR builder for constructing MIR code programmatically.

use std::collections::HashSet;
use std::sync::Arc;

use super::ir::*;

/// Builder for constructing MIR functions.
pub struct MirBuilder {
    /// The function being built.
    func: MirFunction,
    /// Current block ID.
    current_block: BlockId,
    /// Next local ID.
    next_local: u32,
    /// MIR-level struct/enum type names (as they appear in `MirType::Struct`)
    /// that are `#[linear]`. Checked by `create_local`/`create_named_local`
    /// (and the parameter/return-local setup below) so every local-creation
    /// path is tagged from one place instead of touching each of the ~240
    /// call sites across the lowerer. Empty for builder users that don't
    /// care about linearity (backends' own tests, hand-built MIR, etc.).
    linear_type_names: Arc<HashSet<Arc<str>>>,
    /// Source span to attach to the next statement/terminator emitted.
    /// Set by the lowerer (via `set_current_span`) before each
    /// statement/terminator-producing call so that `push_stmt`/
    /// `set_terminator` can record it into `func.spans` without a new
    /// parameter at every one of the ~240 emission call sites.
    current_span: Option<crate::lexer::Span>,
}

impl MirBuilder {
    /// Create a new MIR builder.
    pub fn new(name: impl Into<Arc<str>>, sig: MirFnSig) -> Self {
        Self::with_linear_type_names(name, sig, Arc::new(HashSet::new()))
    }

    /// Create a new MIR builder that tags locals whose type is one of
    /// `linear_type_names` (MIR-level struct names, e.g. `"Qubit"` or a
    /// module-prefixed `"mod_Qubit"`) with the `"linear"` annotation.
    pub fn with_linear_type_names(
        name: impl Into<Arc<str>>,
        sig: MirFnSig,
        linear_type_names: Arc<HashSet<Arc<str>>>,
    ) -> Self {
        let mut func = MirFunction::new(name, sig.clone());

        // Create entry block
        let entry = MirBlock::new(BlockId::ENTRY);
        func.add_block(entry);

        // Add parameters as locals
        let mut next_local = 0u32;
        for (i, param_ty) in sig.params.iter().enumerate() {
            let local_id = LocalId(next_local);
            let mut local = MirLocal::new(local_id, param_ty.clone());
            local.is_param = true;
            local.name = Some(Arc::from(format!("arg{}", i)));
            if Self::type_is_linear(&local.ty, &linear_type_names) {
                local.annotations.push(Arc::from("linear"));
            }
            func.locals.push(local);
            next_local += 1;
        }

        // Add return local if not void
        if sig.ret != MirType::Void {
            let local_id = LocalId(next_local);
            let mut local = MirLocal::new(local_id, sig.ret.clone());
            local.name = Some(Arc::from("_ret"));
            if Self::type_is_linear(&local.ty, &linear_type_names) {
                local.annotations.push(Arc::from("linear"));
            }
            func.locals.push(local);
            next_local += 1;
        }

        Self {
            func,
            current_block: BlockId::ENTRY,
            next_local,
            linear_type_names,
            current_span: None,
        }
    }

    /// Whether `ty` is a `#[linear]` ADT, per the MIR-level type name set
    /// this builder was constructed with. Only `MirType::Struct`/enum-backed
    /// names are checked (linearity is a nominal-ADT property); anything
    /// else (generics not yet monomorphized, primitives, etc.) is
    /// conservatively not tagged -- correct per the 2a groundwork spec,
    /// since an untagged local is simply invisible to the 2b checker.
    fn type_is_linear(ty: &MirType, linear_type_names: &HashSet<Arc<str>>) -> bool {
        matches!(ty, MirType::Struct(name) if linear_type_names.contains(name))
    }

    /// Set the source span to attach to the next statement or terminator
    /// recorded by this builder. Cleared implicitly by nothing -- callers
    /// (the lowerer) set it immediately before each emission so stale spans
    /// don't leak onto unrelated statements.
    pub fn set_current_span(&mut self, span: crate::lexer::Span) {
        self.current_span = Some(span);
    }

    /// Finish building and return the function.
    pub fn build(self) -> MirFunction {
        self.func
    }

    /// Get the current block ID.
    pub fn current_block(&self) -> BlockId {
        self.current_block
    }

    /// Create a new block and return its ID.
    pub fn create_block(&mut self) -> BlockId {
        let id = BlockId(self.func.blocks.as_ref().map(|b| b.len()).unwrap_or(0) as u32);
        let block = MirBlock::new(id);
        self.func.add_block(block);
        id
    }

    /// Create a new labeled block.
    pub fn create_labeled_block(&mut self, label: impl Into<Arc<str>>) -> BlockId {
        let id = BlockId(self.func.blocks.as_ref().map(|b| b.len()).unwrap_or(0) as u32);
        let block = MirBlock::with_label(id, label);
        self.func.add_block(block);
        id
    }

    /// Switch to a different block.
    pub fn switch_to_block(&mut self, block: BlockId) {
        self.current_block = block;
    }

    /// Create a new local variable.
    pub fn create_local(&mut self, ty: MirType) -> LocalId {
        let id = LocalId(self.next_local);
        self.next_local += 1;
        let mut local = MirLocal::new(id, ty);
        if Self::type_is_linear(&local.ty, &self.linear_type_names) {
            local.annotations.push(Arc::from("linear"));
        }
        self.func.add_local(local);
        id
    }

    /// Create a new named local variable.
    pub fn create_named_local(&mut self, name: impl Into<Arc<str>>, ty: MirType) -> LocalId {
        let id = LocalId(self.next_local);
        self.next_local += 1;
        let mut local = MirLocal::named(id, name, ty);
        if Self::type_is_linear(&local.ty, &self.linear_type_names) {
            local.annotations.push(Arc::from("linear"));
        }
        self.func.add_local(local);
        id
    }

    /// Get the return local (if not void).
    pub fn return_local(&self) -> Option<LocalId> {
        if self.func.sig.ret != MirType::Void {
            // Return local is after params
            Some(LocalId(self.func.sig.params.len() as u32))
        } else {
            None
        }
    }

    /// Get a parameter local.
    pub fn param_local(&self, index: usize) -> LocalId {
        LocalId(index as u32)
    }

    /// The number of parameters; their locals are ids `0..param_count()`.
    pub fn param_count(&self) -> usize {
        self.func.sig.params.len()
    }

    /// Look up the type of a local variable by its ID.
    pub fn local_type(&self, id: LocalId) -> Option<MirType> {
        self.func
            .locals
            .iter()
            .find(|l| l.id == id)
            .map(|l| l.ty.clone())
    }

    /// Change the type of an existing local.  Used when a let binding has
    /// an explicit type annotation but the init expression produced a
    /// fallback type (i32).
    pub fn retype_local(&mut self, id: LocalId, new_ty: MirType) {
        if let Some(local) = self.func.locals.iter_mut().find(|l| l.id == id) {
            local.ty = new_ty;
        }
    }

    /// Check if a local ID exists in this function.
    pub fn local_exists(&self, id: LocalId) -> bool {
        self.func.locals.iter().any(|l| l.id == id)
    }

    /// Get the function's return type.
    pub fn return_type(&self) -> &MirType {
        &self.func.sig.ret
    }

    /// Change the function's return type, for a body whose type is known
    /// only after it is lowered. The return local keeps its id; retype it
    /// with `retype_local`.
    pub fn set_return_type(&mut self, ret: MirType) {
        self.func.sig.ret = ret;
    }

    /// Rename a parameter local.
    pub fn set_param_name(&mut self, index: usize, name: impl Into<Arc<str>>) {
        if let Some(local) = self.func.locals.get_mut(index) {
            local.name = Some(name.into());
        }
    }

    /// Set type annotations on a parameter local (e.g., ColorSpace, Precision).
    pub fn set_param_annotations(&mut self, index: usize, annotations: Vec<Arc<str>>) {
        if let Some(local) = self.func.locals.get_mut(index) {
            local.annotations = annotations;
        }
    }

    /// Mark a parameter local's mutability. Threaded from the AST parameter type
    /// (`&mut T` vs `&T`) so backends can distinguish a writable output buffer
    /// from a read-only input. `MirLocal::is_mut` defaults to `false`; a bare
    /// `&T` reference stays read-only.
    pub fn set_param_mut(&mut self, index: usize, is_mut: bool) {
        if let Some(local) = self.func.locals.get_mut(index) {
            local.is_mut = is_mut;
        }
    }

    // =========================================================================
    // STATEMENTS
    // =========================================================================

    /// Add a statement to the current block. Records `current_span` (if set)
    /// into `func.spans.stmt` keyed by this statement's `(block, index)`.
    fn push_stmt(&mut self, kind: MirStmtKind) {
        let block_id = self.current_block;
        if let Some(block) = self.func.block_mut(block_id) {
            let idx = block.stmts.len();
            block.push_stmt(MirStmt::new(kind));
            if let Some(span) = self.current_span {
                self.func.spans.stmt.insert((block_id.0, idx), span);
            }
        }
    }

    /// Assign a value to a local.
    pub fn assign(&mut self, dest: LocalId, value: MirRValue) {
        self.push_stmt(MirStmtKind::Assign { dest, value });
    }

    /// Assign a constant to a local.
    pub fn assign_const(&mut self, dest: LocalId, value: MirConst) {
        self.assign(dest, MirRValue::Use(MirValue::Const(value)));
    }

    /// Copy a local to another.
    pub fn copy_local(&mut self, dest: LocalId, src: LocalId) {
        self.assign(dest, MirRValue::Use(MirValue::Local(src)));
    }

    /// Mark storage as live.
    pub fn storage_live(&mut self, local: LocalId) {
        self.push_stmt(MirStmtKind::StorageLive(local));
    }

    /// Mark storage as dead.
    pub fn storage_dead(&mut self, local: LocalId) {
        self.push_stmt(MirStmtKind::StorageDead(local));
    }

    /// Add a no-op.
    pub fn nop(&mut self) {
        self.push_stmt(MirStmtKind::Nop);
    }

    // =========================================================================
    // OPERATIONS
    // =========================================================================

    /// Binary operation.
    pub fn binary_op(&mut self, dest: LocalId, op: BinOp, left: MirValue, right: MirValue) {
        self.assign(dest, MirRValue::BinaryOp { op, left, right });
    }

    /// Unary operation.
    pub fn unary_op(&mut self, dest: LocalId, op: UnaryOp, operand: MirValue) {
        self.assign(dest, MirRValue::UnaryOp { op, operand });
    }

    /// Cast operation.
    pub fn cast(&mut self, dest: LocalId, kind: CastKind, value: MirValue, ty: MirType) {
        self.assign(dest, MirRValue::Cast { kind, value, ty });
    }

    /// Create a reference.
    pub fn make_ref(&mut self, dest: LocalId, is_mut: bool, place: MirPlace) {
        self.assign(dest, MirRValue::Ref { is_mut, place });
    }

    /// Store through a pointer (dereference assignment): `*ptr = value`
    pub fn push_deref_assign(&mut self, ptr: LocalId, value: MirRValue) {
        self.push_stmt(MirStmtKind::DerefAssign { ptr, value });
    }

    /// Store to a field through a pointer: `ptr->field = value`
    pub fn push_field_deref_assign(
        &mut self,
        ptr: LocalId,
        field_name: Arc<str>,
        value: MirRValue,
    ) {
        self.push_stmt(MirStmtKind::FieldDerefAssign {
            ptr,
            field_name,
            value,
        });
    }

    /// Store to a field on a local struct: `local.field = value`
    pub fn push_field_assign(&mut self, base: LocalId, field_name: Arc<str>, value: MirRValue) {
        self.push_stmt(MirStmtKind::FieldAssign {
            base,
            field_name,
            value,
        });
    }

    /// Store to a module global / mutable static: `GLOBAL = value`.
    pub fn push_global_store(&mut self, name: Arc<str>, value: MirRValue) {
        self.push_stmt(MirStmtKind::GlobalStore { name, value });
    }

    /// Indexed store into a slice/array/pointer base: `base[index] = value`.
    pub fn push_index_store(
        &mut self,
        base: MirValue,
        index: MirValue,
        elem_ty: MirType,
        value: MirRValue,
    ) {
        self.push_stmt(MirStmtKind::IndexStore {
            base,
            index,
            elem_ty,
            value,
        });
    }

    /// Create an aggregate (tuple, struct, array).
    pub fn aggregate(&mut self, dest: LocalId, kind: AggregateKind, operands: Vec<MirValue>) {
        self.assign(dest, MirRValue::Aggregate { kind, operands });
    }

    /// Emit a GPU workgroup barrier (`workgroupBarrier()`): a void statement, not
    /// an rvalue. Lowered by the SPIR-V backend to `OpControlBarrier`; a no-op on
    /// CPU/non-GPU backends.
    pub fn push_workgroup_barrier(&mut self) {
        self.push_stmt(MirStmtKind::WorkgroupBarrier);
    }

    /// Rename an existing local by id (for legible diagnostics when a binding
    /// aliases a previously-created local, e.g. a workgroup scratch slot).
    pub fn set_local_name(&mut self, id: LocalId, name: impl Into<Arc<str>>) {
        if let Some(local) = self.func.locals.iter_mut().find(|l| l.id == id) {
            local.name = Some(name.into());
        }
    }

    /// Append a type annotation to an existing local (e.g. `"Workgroup:64"` to
    /// mark a workgroup-shared scratch array). Used for GPU compute metadata that
    /// the SPIR-V backend reads back to place the local in the `Workgroup` storage
    /// class rather than as an ordinary function-local array.
    pub fn annotate_local(&mut self, id: LocalId, annotation: impl Into<Arc<str>>) {
        if let Some(local) = self.func.locals.iter_mut().find(|l| l.id == id) {
            local.annotations.push(annotation.into());
        }
    }

    // =========================================================================
    // TERMINATORS
    // =========================================================================

    /// Set the terminator for the current block. Records `current_span` (if
    /// set) into `func.spans.terminator` keyed by this block's id.
    fn set_terminator(&mut self, term: MirTerminator) {
        let block_id = self.current_block;
        if let Some(block) = self.func.block_mut(block_id) {
            block.set_terminator(term);
            if let Some(span) = self.current_span {
                self.func.spans.terminator.insert(block_id.0, span);
            }
        }
    }

    /// Unconditional goto.
    pub fn goto(&mut self, target: BlockId) {
        self.set_terminator(MirTerminator::Goto(target));
    }

    /// Conditional branch.
    pub fn branch(&mut self, cond: MirValue, then_block: BlockId, else_block: BlockId) {
        self.set_terminator(MirTerminator::If {
            cond,
            then_block,
            else_block,
        });
    }

    /// Switch statement.
    pub fn switch(&mut self, value: MirValue, targets: Vec<(MirConst, BlockId)>, default: BlockId) {
        self.set_terminator(MirTerminator::Switch {
            value,
            targets,
            default,
        });
    }

    /// Function call.
    pub fn call(
        &mut self,
        func: MirValue,
        args: Vec<MirValue>,
        dest: Option<LocalId>,
        target: BlockId,
    ) {
        self.set_terminator(MirTerminator::Call {
            func,
            args,
            dest,
            target: Some(target),
            unwind: None,
        });
    }

    /// Void function call (no return value).
    pub fn call_void(&mut self, func: MirValue, args: Vec<MirValue>, target: BlockId) {
        self.call(func, args, None, target);
    }

    /// Return from function.
    pub fn ret(&mut self, value: Option<MirValue>) {
        self.set_terminator(MirTerminator::Return(value));
    }

    /// Return void.
    pub fn ret_void(&mut self) {
        self.ret(None);
    }

    /// Unreachable.
    pub fn unreachable(&mut self) {
        self.set_terminator(MirTerminator::Unreachable);
    }

    /// Assert.
    pub fn assert(
        &mut self,
        cond: MirValue,
        expected: bool,
        msg: impl Into<Arc<str>>,
        target: BlockId,
    ) {
        self.set_terminator(MirTerminator::Assert {
            cond,
            expected,
            msg: msg.into(),
            target,
            unwind: None,
        });
    }

    /// Abort.
    pub fn abort(&mut self) {
        self.set_terminator(MirTerminator::Abort);
    }
}

/// Builder for constructing MIR modules.
pub struct MirModuleBuilder {
    /// The module being built.
    module: MirModule,
}

impl MirModuleBuilder {
    /// Create a new module builder.
    pub fn new(name: impl Into<Arc<str>>) -> Self {
        Self {
            module: MirModule::new(name),
        }
    }

    /// Finish building and return the module.
    pub fn build(self) -> MirModule {
        self.module
    }

    /// Find a global variable by name.
    pub fn find_global(&self, name: &str) -> Option<&MirGlobal> {
        self.module.find_global(name)
    }

    /// Get mutable access to the underlying MirModule.
    pub fn module_mut(&mut self) -> &mut MirModule {
        &mut self.module
    }

    /// Add a function.
    pub fn add_function(&mut self, func: MirFunction) {
        self.module.add_function(func);
    }

    /// Add a global variable.
    pub fn add_global(&mut self, global: MirGlobal) {
        self.module.add_global(global);
    }

    /// Add a type definition.
    pub fn add_type(&mut self, ty: MirTypeDef) {
        self.module.add_type(ty);
    }

    /// Add an external declaration.
    pub fn add_external(&mut self, ext: MirExternal) {
        self.module.externals.push(ext);
    }

    /// Intern a string.
    pub fn intern_string(&mut self, s: impl Into<Arc<str>>) -> u32 {
        self.module.intern_string(s)
    }

    /// Set the return type of every entry named `name`, the declaration and
    /// the definition. A function that returns a closure learns its return
    /// type from its body.
    pub fn set_return_type(&mut self, name: &str, ret: &MirType) {
        for func in self.module.functions.iter_mut() {
            if func.name.as_ref() == name {
                func.sig.ret = ret.clone();
            }
        }
    }

    /// Declare an external function.
    pub fn declare_function(&mut self, name: impl Into<Arc<str>>, sig: MirFnSig) {
        let func = MirFunction::declaration(name, sig);
        self.module.add_function(func);
    }

    /// Create a struct type.
    pub fn create_struct(
        &mut self,
        name: impl Into<Arc<str>>,
        fields: Vec<(Option<Arc<str>>, MirType)>,
    ) {
        let ty = MirTypeDef {
            name: name.into(),
            kind: TypeDefKind::Struct {
                fields,
                packed: false,
            },
        };
        self.module.add_type(ty);
    }

    /// Create an enum type.
    pub fn create_enum(
        &mut self,
        name: impl Into<Arc<str>>,
        discriminant_ty: MirType,
        variants: Vec<MirEnumVariant>,
    ) {
        let ty = MirTypeDef {
            name: name.into(),
            kind: TypeDefKind::Enum {
                discriminant_ty,
                variants,
            },
        };
        self.module.add_type(ty);
    }

    /// Find a function by name in the module built so far.
    pub fn find_function(&self, name: &str) -> Option<&MirFunction> {
        self.module.find_function(name)
    }

    /// Find a type definition by name.
    pub fn find_type(&self, name: &str) -> Option<&MirTypeDef> {
        self.module.types.iter().find(|t| t.name.as_ref() == name)
    }

    /// Find a type whose name ends with `_suffix`.
    /// Used to resolve cross-module references: `Operator` → `tonemap_Operator`.
    pub fn find_type_by_suffix(&self, suffix: &str) -> Option<String> {
        let pattern = format!("_{}", suffix);
        self.module
            .types
            .iter()
            .find(|t| t.name.ends_with(&pattern))
            .map(|t| t.name.to_string())
    }

    /// Find the type of field `field_name` of a struct-like enum VARIANT named
    /// `variant_name`, searching every enum's variants. A struct-like variant
    /// (`Has { item: Coin }`) is not registered as a `Struct` type; its name is
    /// the synthetic variant struct name a record-pattern binding sees. This
    /// recovers the true field type (e.g. a `#[linear]` payload) that a plain
    /// struct-field lookup on the variant name would miss.
    pub fn find_variant_field_type(&self, variant_name: &str, field_name: &str) -> Option<MirType> {
        for type_def in &self.module.types {
            if let crate::codegen::ir::TypeDefKind::Enum { variants, .. } = &type_def.kind {
                for v in variants {
                    if v.name.as_ref() == variant_name {
                        for (fname, fty) in &v.fields {
                            if fname.as_deref() == Some(field_name) {
                                return Some(fty.clone());
                            }
                        }
                    }
                }
            }
        }
        None
    }
}

/// Helper to create common MIR values.
pub mod values {
    use super::*;

    /// Create a local value.
    pub fn local(id: LocalId) -> MirValue {
        MirValue::Local(id)
    }

    /// Create an i32 constant.
    pub fn i32(v: i32) -> MirValue {
        MirValue::Const(MirConst::Int(v as i128, MirType::i32()))
    }

    /// Create an i64 constant.
    pub fn i64(v: i64) -> MirValue {
        MirValue::Const(MirConst::Int(v as i128, MirType::i64()))
    }

    /// Create a u32 constant.
    pub fn u32(v: u32) -> MirValue {
        MirValue::Const(MirConst::Uint(v as u128, MirType::u32()))
    }

    /// Create a u64 constant.
    pub fn u64(v: u64) -> MirValue {
        MirValue::Const(MirConst::Uint(v as u128, MirType::u64()))
    }

    /// Create a bool constant.
    pub fn bool(v: bool) -> MirValue {
        MirValue::Const(MirConst::Bool(v))
    }

    /// Create a float constant.
    pub fn f32(v: f32) -> MirValue {
        MirValue::Const(MirConst::Float(v as f64, MirType::f32()))
    }

    /// Create a float constant.
    pub fn f64(v: f64) -> MirValue {
        MirValue::Const(MirConst::Float(v, MirType::f64()))
    }

    /// Create a unit constant.
    pub fn unit() -> MirValue {
        MirValue::Const(MirConst::Unit)
    }

    /// Create a null pointer.
    pub fn null(ty: MirType) -> MirValue {
        MirValue::Const(MirConst::Null(ty))
    }

    /// Create a function reference.
    pub fn func(name: impl Into<Arc<str>>) -> MirValue {
        MirValue::Function(name.into())
    }

    /// Create a global reference.
    pub fn global(name: impl Into<Arc<str>>) -> MirValue {
        MirValue::Global(name.into())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    // =========================================================================
    // MIR BUILDER TESTS
    // =========================================================================

    #[test]
    fn test_builder_simple_function() {
        // Build: fn add(a: i32, b: i32) -> i32 { a + b }
        let sig = MirFnSig::new(vec![MirType::i32(), MirType::i32()], MirType::i32());
        let mut builder = MirBuilder::new("add", sig);

        let a = builder.param_local(0);
        let b = builder.param_local(1);
        let result = builder.create_local(MirType::i32());

        builder.binary_op(result, BinOp::Add, values::local(a), values::local(b));
        builder.ret(Some(values::local(result)));

        let func = builder.build();
        assert_eq!(func.name.as_ref(), "add");
        assert!(!func.is_declaration());
    }

    #[test]
    fn test_builder_with_branch() {
        // Build: fn max(a: i32, b: i32) -> i32 { if a > b { a } else { b } }
        let sig = MirFnSig::new(vec![MirType::i32(), MirType::i32()], MirType::i32());
        let mut builder = MirBuilder::new("max", sig);

        let a = builder.param_local(0);
        let b = builder.param_local(1);
        let cond = builder.create_local(MirType::Bool);

        let then_block = builder.create_block();
        let else_block = builder.create_block();

        // Entry block: compare a > b
        builder.binary_op(cond, BinOp::Gt, values::local(a), values::local(b));
        builder.branch(values::local(cond), then_block, else_block);

        // Then block: return a
        builder.switch_to_block(then_block);
        builder.ret(Some(values::local(a)));

        // Else block: return b
        builder.switch_to_block(else_block);
        builder.ret(Some(values::local(b)));

        let func = builder.build();
        assert_eq!(func.blocks.as_ref().unwrap().len(), 3);
    }

    #[test]
    fn test_builder_void_function() {
        let sig = MirFnSig::new(vec![], MirType::Void);
        let mut builder = MirBuilder::new("noop", sig);
        builder.ret_void();

        let func = builder.build();
        assert_eq!(func.name.as_ref(), "noop");
        assert!(func.sig.params.is_empty());
        assert_eq!(func.sig.ret, MirType::Void);
    }

    #[test]
    fn test_builder_create_local() {
        let sig = MirFnSig::new(vec![], MirType::Void);
        let mut builder = MirBuilder::new("test", sig);

        let local1 = builder.create_local(MirType::i32());
        let local2 = builder.create_local(MirType::f64());
        let local3 = builder.create_named_local("named", MirType::Bool);

        assert_ne!(local1, local2);
        assert_ne!(local2, local3);

        builder.ret_void();
        let func = builder.build();

        // Should have the locals we created
        assert!(func.locals.len() >= 3);
    }

    #[test]
    fn test_builder_unary_op() {
        let sig = MirFnSig::new(vec![MirType::i32()], MirType::i32());
        let mut builder = MirBuilder::new("negate", sig);

        let input = builder.param_local(0);
        let result = builder.create_local(MirType::i32());

        builder.unary_op(result, UnaryOp::Neg, values::local(input));
        builder.ret(Some(values::local(result)));

        let func = builder.build();
        let blocks = func.blocks.as_ref().unwrap();
        assert!(!blocks[0].stmts.is_empty());
    }

    #[test]
    fn test_builder_assign_const() {
        let sig = MirFnSig::new(vec![], MirType::i32());
        let mut builder = MirBuilder::new("const_42", sig);

        let result = builder.create_local(MirType::i32());
        builder.assign_const(result, MirConst::Int(42, MirType::i32()));
        builder.ret(Some(values::local(result)));

        let func = builder.build();
        let blocks = func.blocks.as_ref().unwrap();
        assert_eq!(blocks[0].stmts.len(), 1);
    }

    #[test]
    fn test_builder_goto() {
        let sig = MirFnSig::new(vec![], MirType::Void);
        let mut builder = MirBuilder::new("test_goto", sig);

        let target = builder.create_block();
        builder.goto(target);

        builder.switch_to_block(target);
        builder.ret_void();

        let func = builder.build();
        let blocks = func.blocks.as_ref().unwrap();
        assert_eq!(blocks.len(), 2);
    }

    #[test]
    fn test_builder_switch() {
        let sig = MirFnSig::new(vec![MirType::i32()], MirType::i32());
        let mut builder = MirBuilder::new("test_switch", sig);

        let input = builder.param_local(0);
        let case1 = builder.create_block();
        let case2 = builder.create_block();
        let default = builder.create_block();

        builder.switch(
            values::local(input),
            vec![
                (MirConst::Int(1, MirType::i32()), case1),
                (MirConst::Int(2, MirType::i32()), case2),
            ],
            default,
        );

        builder.switch_to_block(case1);
        builder.ret(Some(values::i32(100)));

        builder.switch_to_block(case2);
        builder.ret(Some(values::i32(200)));

        builder.switch_to_block(default);
        builder.ret(Some(values::i32(0)));

        let func = builder.build();
        assert_eq!(func.blocks.as_ref().unwrap().len(), 4);
    }

    #[test]
    fn test_builder_call() {
        let sig = MirFnSig::new(vec![], MirType::i32());
        let mut builder = MirBuilder::new("caller", sig);

        let result = builder.create_local(MirType::i32());
        let cont = builder.create_block();

        builder.call(
            values::func("other_func"),
            vec![values::i32(10)],
            Some(result),
            cont,
        );

        builder.switch_to_block(cont);
        builder.ret(Some(values::local(result)));

        let func = builder.build();
        assert_eq!(func.blocks.as_ref().unwrap().len(), 2);
    }

    #[test]
    fn test_builder_unreachable() {
        let sig = MirFnSig::new(vec![], MirType::Never);
        let mut builder = MirBuilder::new("panic_fn", sig);
        builder.unreachable();

        let func = builder.build();
        let blocks = func.blocks.as_ref().unwrap();
        assert!(matches!(
            blocks[0].terminator,
            Some(MirTerminator::Unreachable)
        ));
    }

    #[test]
    fn test_builder_abort() {
        let sig = MirFnSig::new(vec![], MirType::Never);
        let mut builder = MirBuilder::new("abort_fn", sig);
        builder.abort();

        let func = builder.build();
        let blocks = func.blocks.as_ref().unwrap();
        assert!(matches!(blocks[0].terminator, Some(MirTerminator::Abort)));
    }

    #[test]
    fn test_builder_labeled_block() {
        let sig = MirFnSig::new(vec![], MirType::Void);
        let mut builder = MirBuilder::new("test", sig);

        let loop_block = builder.create_labeled_block("loop_start");
        builder.goto(loop_block);

        builder.switch_to_block(loop_block);
        builder.ret_void();

        let func = builder.build();
        let blocks = func.blocks.as_ref().unwrap();
        assert_eq!(blocks[1].label.as_ref().unwrap().as_ref(), "loop_start");
    }

    // =========================================================================
    // MODULE BUILDER TESTS
    // =========================================================================

    #[test]
    fn test_module_builder_new() {
        let builder = MirModuleBuilder::new("test_module");
        let module = builder.build();
        assert_eq!(module.name.as_ref(), "test_module");
    }

    #[test]
    fn test_module_builder_add_function() {
        let mut builder = MirModuleBuilder::new("test");

        let sig = MirFnSig::new(vec![], MirType::Void);
        let func = MirFunction::new("my_func", sig);
        builder.add_function(func);

        let module = builder.build();
        assert_eq!(module.functions.len(), 1);
    }

    #[test]
    fn test_module_builder_add_global() {
        let mut builder = MirModuleBuilder::new("test");

        let global = MirGlobal::new("CONSTANT", MirType::i32());
        builder.add_global(global);

        let module = builder.build();
        assert_eq!(module.globals.len(), 1);
    }

    #[test]
    fn test_module_builder_intern_string() {
        let mut builder = MirModuleBuilder::new("test");

        let idx1 = builder.intern_string("hello");
        let idx2 = builder.intern_string("world");
        let idx3 = builder.intern_string("hello"); // Duplicate

        assert_eq!(idx1, 0);
        assert_eq!(idx2, 1);
        assert_eq!(idx3, 0); // Same as first
    }

    #[test]
    fn test_module_builder_declare_function() {
        let mut builder = MirModuleBuilder::new("test");

        let sig = MirFnSig::new(vec![MirType::i32()], MirType::i32());
        builder.declare_function("external_fn", sig);

        let module = builder.build();
        assert!(module.functions[0].is_declaration());
    }

    #[test]
    fn test_module_builder_create_struct() {
        let mut builder = MirModuleBuilder::new("test");

        builder.create_struct(
            "Point",
            vec![
                (Some(Arc::from("x")), MirType::i32()),
                (Some(Arc::from("y")), MirType::i32()),
            ],
        );

        let module = builder.build();
        assert_eq!(module.types.len(), 1);
        match &module.types[0].kind {
            TypeDefKind::Struct { fields, .. } => assert_eq!(fields.len(), 2),
            _ => panic!("Expected struct"),
        }
    }

    #[test]
    fn test_module_builder_create_enum() {
        let mut builder = MirModuleBuilder::new("test");

        builder.create_enum(
            "Color",
            MirType::i32(),
            vec![
                MirEnumVariant {
                    name: Arc::from("Red"),
                    discriminant: 0,
                    fields: vec![],
                },
                MirEnumVariant {
                    name: Arc::from("Green"),
                    discriminant: 1,
                    fields: vec![],
                },
            ],
        );

        let module = builder.build();
        assert_eq!(module.types.len(), 1);
    }

    // =========================================================================
    // VALUES HELPER TESTS
    // =========================================================================

    #[test]
    fn test_values_local() {
        let val = values::local(LocalId(5));
        match val {
            MirValue::Local(id) => assert_eq!(id.0, 5),
            _ => panic!("Expected Local"),
        }
    }

    #[test]
    fn test_values_i32() {
        let val = values::i32(42);
        match val {
            MirValue::Const(MirConst::Int(v, ty)) => {
                assert_eq!(v, 42);
                assert_eq!(ty, MirType::i32());
            }
            _ => panic!("Expected i32 const"),
        }
    }

    #[test]
    fn test_values_i64() {
        let val = values::i64(1234567890123i64);
        match val {
            MirValue::Const(MirConst::Int(v, ty)) => {
                assert_eq!(v, 1234567890123);
                assert_eq!(ty, MirType::i64());
            }
            _ => panic!("Expected i64 const"),
        }
    }

    #[test]
    fn test_values_bool() {
        let val_true = values::bool(true);
        let val_false = values::bool(false);

        match val_true {
            MirValue::Const(MirConst::Bool(b)) => assert!(b),
            _ => panic!("Expected bool true"),
        }
        match val_false {
            MirValue::Const(MirConst::Bool(b)) => assert!(!b),
            _ => panic!("Expected bool false"),
        }
    }

    #[test]
    fn test_values_f32() {
        let val = values::f32(2.5f32);
        match val {
            MirValue::Const(MirConst::Float(_, ty)) => {
                assert_eq!(ty, MirType::f32());
            }
            _ => panic!("Expected f32 const"),
        }
    }

    #[test]
    fn test_values_f64() {
        let val = values::f64(2.5);
        match val {
            MirValue::Const(MirConst::Float(v, ty)) => {
                assert!((v - 2.5).abs() < 1e-10);
                assert_eq!(ty, MirType::f64());
            }
            _ => panic!("Expected f64 const"),
        }
    }

    #[test]
    fn test_values_unit() {
        let val = values::unit();
        match val {
            MirValue::Const(MirConst::Unit) => {}
            _ => panic!("Expected unit"),
        }
    }

    #[test]
    fn test_values_null() {
        let val = values::null(MirType::Ptr(Box::new(MirType::i32())));
        match val {
            MirValue::Const(MirConst::Null(_)) => {}
            _ => panic!("Expected null"),
        }
    }

    #[test]
    fn test_values_func() {
        let val = values::func("my_function");
        match val {
            MirValue::Function(name) => assert_eq!(name.as_ref(), "my_function"),
            _ => panic!("Expected function ref"),
        }
    }

    #[test]
    fn test_values_global() {
        let val = values::global("GLOBAL_VAR");
        match val {
            MirValue::Global(name) => assert_eq!(name.as_ref(), "GLOBAL_VAR"),
            _ => panic!("Expected global ref"),
        }
    }
}