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
// Copyright 2022 Garrit Franke
// Copyright 2021 Alexey Yerin
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use crate::*;
use std::sync::Arc;

#[test]
fn qbe_value() {
    let val = Value::Temporary("temp42".into());
    assert_eq!(format!("{val}"), "%temp42");

    let val = Value::Global("main".into());
    assert_eq!(format!("{val}"), "$main");

    let val = Value::Const(1337);
    assert_eq!(format!("{val}"), "1337");
}

#[test]
fn block() {
    let blk = Block {
        label: "start".into(),
        items: vec![BlockItem::Statement(Statement::Volatile(Instr::Ret(None)))],
    };

    let formatted = format!("{blk}");
    let mut lines = formatted.lines();
    assert_eq!(lines.next().unwrap(), "@start");
    assert_eq!(lines.next().unwrap(), "\tret");

    let blk = Block {
        label: "start".into(),
        items: vec![
            BlockItem::Comment("Comment".into()),
            BlockItem::Statement(Statement::Assign(
                Value::Temporary("foo".into()),
                Type::Word,
                Instr::Add(Value::Const(2), Value::Const(2)),
            )),
            BlockItem::Statement(Statement::Volatile(Instr::Ret(Some(Value::Temporary(
                "foo".into(),
            ))))),
        ],
    };

    let formatted = format!("{blk}");
    let mut lines = formatted.lines();
    assert_eq!(lines.next().unwrap(), "@start");
    assert_eq!(lines.next().unwrap(), "\t# Comment");
    assert_eq!(lines.next().unwrap(), "\t%foo =w add 2, 2");
    assert_eq!(lines.next().unwrap(), "\tret %foo");
}

#[test]
fn instr_blit() {
    let blk = Block {
        label: "start".into(),
        items: vec![BlockItem::Statement(Statement::Volatile(Instr::Blit(
            Value::Temporary("src".into()),
            Value::Temporary("dst".into()),
            4,
        )))],
    };

    let formatted = format!("{blk}");
    let mut lines = formatted.lines();
    assert_eq!(lines.next().unwrap(), "@start");
    assert_eq!(lines.next().unwrap(), "\tblit %src, %dst, 4");
}

#[test]
fn function() {
    let func = Function {
        linkage: Linkage::public(),
        return_ty: None,
        name: "main".into(),
        arguments: Vec::new(),
        blocks: vec![Block {
            label: "start".into(),
            items: vec![BlockItem::Statement(Statement::Volatile(Instr::Ret(None)))],
        }],
    };

    let formatted = format!("{func}");
    let mut lines = formatted.lines();
    assert_eq!(lines.next().unwrap(), "export function $main() {");
    assert_eq!(lines.next().unwrap(), "@start");
    assert_eq!(lines.next().unwrap(), "\tret");
    assert_eq!(lines.next().unwrap(), "}");
}

#[test]
fn function_new_equivalence() {
    let func1 = Function {
        linkage: Linkage::public(),
        return_ty: None,
        name: "main".into(),
        arguments: Vec::new(),
        blocks: Vec::new(),
    };

    let func2 = Function::new(Linkage::public(), "main", Vec::new(), None);

    assert_eq!(func1, func2);
}

#[test]
fn datadef() {
    let datadef = DataDef {
        linkage: Linkage::public(),
        name: "hello".into(),
        align: None,
        items: vec![
            (Type::Byte, DataItem::Str("Hello, World!".into())),
            (Type::Byte, DataItem::Const(0)),
        ],
    };

    let formatted = format!("{datadef}");
    assert_eq!(
        formatted,
        "export data $hello = { b \"Hello, World!\", b 0 }"
    );
}

#[test]
fn datadef_new_equivalence() {
    let datadef1 = DataDef {
        linkage: Linkage::public(),
        name: "hello".into(),
        align: None,
        items: vec![],
    };

    let datadef2 = DataDef::new(Linkage::public(), "hello", None, vec![]);

    assert_eq!(datadef1, datadef2);
}

#[test]
fn typedef_regular() {
    let typedef = TypeDef::Regular {
        ident: "person".into(),
        align: None,
        items: vec![(Type::Long, 1), (Type::Word, 2), (Type::Byte, 1)],
    };

    let formatted = format!("{typedef}");
    assert_eq!(formatted, "type :person = { l, w 2, b }");

    let typedef_with_align = TypeDef::Regular {
        ident: "person".into(),
        align: Some(8),
        items: vec![(Type::Long, 1), (Type::Word, 2), (Type::Byte, 1)],
    };

    let formatted = format!("{typedef_with_align}");
    assert_eq!(formatted, "type :person = align 8 { l, w 2, b }");

    let ty = Type::aggregate(&Arc::new(typedef));
    let formatted = format!("{ty}");
    assert_eq!(formatted, ":person");
}

#[test]
fn typedef_union() {
    let typedef = TypeDef::Union {
        ident: "data".into(),
        align: None,
        variations: vec![
            vec![(Type::Long, 1), (Type::Word, 2), (Type::Byte, 1)],
            vec![(Type::Long, 2)],
        ],
    };

    let formatted = format!("{typedef}");
    assert_eq!(formatted, "type :data = { { l, w 2, b } { l 2 } }");

    let typedef_with_align = TypeDef::Union {
        ident: "data".into(),
        align: Some(8),
        variations: vec![
            vec![(Type::Long, 1), (Type::Word, 2), (Type::Byte, 1)],
            vec![(Type::Long, 2)],
        ],
    };

    let formatted = format!("{typedef_with_align}");
    assert_eq!(formatted, "type :data = align 8 { { l, w 2, b } { l 2 } }");

    let ty = Type::aggregate(&Arc::new(typedef));
    let formatted = format!("{ty}");
    assert_eq!(formatted, ":data");
}

#[test]
fn typedef_opaque() {
    let typedef = TypeDef::Opaque {
        ident: "data".into(),
        align: 8,
        size: 64,
    };

    let formatted = format!("{typedef}");
    assert_eq!(formatted, "type :data = align 8 { 64 }");

    let ty = Type::aggregate(&Arc::new(typedef));
    let formatted = format!("{ty}");
    assert_eq!(formatted, ":data");
}

#[test]
fn type_size() {
    assert!(Type::Byte.size() == 1);
    assert!(Type::SignedByte.size() == 1);
    assert!(Type::UnsignedByte.size() == 1);
    assert!(Type::Halfword.size() == 2);
    assert!(Type::SignedHalfword.size() == 2);
    assert!(Type::UnsignedHalfword.size() == 2);
    assert!(Type::Word.size() == 4);
    assert!(Type::Single.size() == 4);
    assert!(Type::Long.size() == 8);
    assert!(Type::Double.size() == 8);

    let typedef_regular = TypeDef::Regular {
        ident: "person".into(),
        align: None,
        items: vec![(Type::Long, 1), (Type::Word, 2), (Type::Byte, 1)],
    };
    let aggregate = Type::aggregate(&Arc::new(typedef_regular));
    assert_eq!(aggregate.size(), 24);

    let typedef_union = Arc::new(TypeDef::Union {
        ident: "data".into(),
        align: None,
        variations: vec![
            vec![(Type::Long, 1), (Type::Word, 2), (Type::Byte, 1)],
            vec![(Type::Long, 5)],
        ],
    });
    let aggregate = Type::aggregate(&typedef_union);
    assert_eq!(aggregate.size(), 40);

    let typedef_opaque = Arc::new(TypeDef::Opaque {
        ident: "data".into(),
        align: 8,
        size: 64,
    });
    let aggregate = Type::aggregate(&typedef_opaque);
    assert_eq!(aggregate.size(), 64);
}

#[test]
fn type_align() {
    assert!(Type::Byte.align() == 1);
    assert!(Type::SignedByte.align() == 1);
    assert!(Type::UnsignedByte.align() == 1);
    assert!(Type::Halfword.align() == 2);
    assert!(Type::SignedHalfword.align() == 2);
    assert!(Type::UnsignedHalfword.align() == 2);
    assert!(Type::Word.align() == 4);
    assert!(Type::Single.align() == 4);
    assert!(Type::Long.align() == 8);
    assert!(Type::Double.align() == 8);

    let typedef_regular = TypeDef::Regular {
        ident: "person".into(),
        align: None,
        items: vec![(Type::Long, 1), (Type::Word, 2), (Type::Byte, 1)],
    };
    let aggregate = Type::aggregate(&Arc::new(typedef_regular));
    assert_eq!(aggregate.align(), 8);

    let typedef_union = Arc::new(TypeDef::Union {
        ident: "data".into(),
        align: None,
        variations: vec![
            vec![(Type::Word, 1), (Type::Word, 2), (Type::Byte, 1)],
            vec![(Type::Long, 5)],
        ],
    });
    let aggregate = Type::aggregate(&typedef_union);
    assert_eq!(aggregate.align(), 8);

    let typedef_opaque = Arc::new(TypeDef::Opaque {
        ident: "data".into(),
        align: 8,
        size: 64,
    });
    let aggregate = Type::aggregate(&typedef_opaque);
    assert_eq!(aggregate.align(), 8);
}

#[test]
fn type_size_nested_aggregate() {
    let inner = Arc::new(TypeDef::Regular {
        ident: "dog".into(),
        align: None,
        items: vec![(Type::Long, 2)],
    });
    let inner_aggregate = Type::aggregate(&inner);

    assert!(inner_aggregate.size() == 16);

    let typedef = Arc::new(TypeDef::Regular {
        ident: "person".into(),
        align: None,
        items: vec![
            (Type::Long, 1),
            (Type::Word, 2),
            (Type::Byte, 1),
            (Type::aggregate(&inner), 1),
        ],
    });
    let aggregate = Type::aggregate(&typedef);

    assert_eq!(aggregate.size(), 40);
}

#[test]
fn type_into_abi() {
    // Base types and aggregates should stay unchanged
    let unchanged = |ty: Type| assert_eq!(ty.clone().into_abi(), ty);
    unchanged(Type::Word);
    unchanged(Type::Long);
    unchanged(Type::Single);
    unchanged(Type::Double);
    let typedef = Arc::new(TypeDef::Regular {
        ident: "foo".into(),
        align: None,
        items: Vec::new(),
    });
    unchanged(Type::aggregate(&typedef));

    // Extended types are transformed into closest base types
    assert_eq!(Type::Byte.into_abi(), Type::Word);
    assert_eq!(Type::UnsignedByte.into_abi(), Type::Word);
    assert_eq!(Type::SignedByte.into_abi(), Type::Word);
    assert_eq!(Type::Halfword.into_abi(), Type::Word);
    assert_eq!(Type::UnsignedHalfword.into_abi(), Type::Word);
    assert_eq!(Type::SignedHalfword.into_abi(), Type::Word);
}

#[test]
fn type_into_base() {
    // Base types should stay unchanged
    let unchanged = |ty: Type| assert_eq!(ty.clone().into_base(), ty);
    unchanged(Type::Word);
    unchanged(Type::Long);
    unchanged(Type::Single);
    unchanged(Type::Double);

    // Extended and aggregate types are transformed into closest base types
    assert_eq!(Type::Byte.into_base(), Type::Word);
    assert_eq!(Type::UnsignedByte.into_base(), Type::Word);
    assert_eq!(Type::SignedHalfword.into_base(), Type::Word);
    assert_eq!(Type::Halfword.into_base(), Type::Word);
    assert_eq!(Type::UnsignedHalfword.into_base(), Type::Word);
    assert_eq!(Type::SignedHalfword.into_base(), Type::Word);
    let typedef = Arc::new(TypeDef::Regular {
        ident: "foo".into(),
        align: None,
        items: Vec::new(),
    });
    assert_eq!(Type::aggregate(&typedef).into_base(), Type::Long);
}

#[test]
fn add_function_to_module() {
    let mut module = Module::new();

    let function = Function {
        linkage: Linkage::public(),
        name: "foo".into(),
        arguments: Vec::new(),
        blocks: Vec::new(),
        return_ty: None,
    };

    module.add_function(function.clone());

    assert_eq!(module.functions.into_iter().next().unwrap(), function);
}

#[test]
fn variadic_call() {
    let instr = Instr::Call(
        "printf".into(),
        vec![
            (Type::Long, Value::Global("fmt".into())),
            (Type::Word, Value::Const(0)),
        ],
        Some(1),
    );

    assert_eq!(instr.to_string(), "call $printf(l $fmt, ..., w 0)");
}

#[test]
fn module_fmt_order() {
    // Create a module
    let mut module = Module::new();

    // Add a type definition to the module
    let typedef = Arc::new(TypeDef::Regular {
        ident: "test_type".into(),
        align: None,
        items: vec![(Type::Long, 1)],
    });
    module.add_type(typedef);

    // Add a function to the module
    let mut func = Function::new(Linkage::public(), "test_func", Vec::new(), None);

    // Add a block to the function and an instruction to the block
    let block = func.add_block("entry");
    block.add_instr(Instr::Ret(None));

    module.add_function(func);

    // Add some data to the module for completeness
    let data = DataDef::new(
        Linkage::private(),
        "test_data",
        None,
        vec![(Type::Word, DataItem::Const(42))],
    );
    module.add_data(data);

    // Format the module to a string
    let formatted = format!("{module}");

    // Verify the order: types, then functions, then data
    let type_pos = formatted
        .find("type :test_type")
        .expect("Type definition not found");
    let func_pos = formatted
        .find("export function $test_func")
        .expect("Function not found");
    let data_pos = formatted
        .find("data $test_data")
        .expect("Data definition not found");

    assert!(
        type_pos < func_pos,
        "Type definition should appear before function"
    );
    assert!(
        func_pos < data_pos,
        "Function should appear before data definition"
    );
}

#[test]
fn comparison_types() {
    // Test ordered/unordered comparisons for floating point
    let ordered_cmp = Statement::Volatile(Instr::Cmp(
        Type::Double,
        Cmp::O,
        Value::Temporary("a".into()),
        Value::Temporary("b".into()),
    ));
    assert_eq!(format!("{ordered_cmp}"), "cod %a, %b");

    let unordered_cmp = Statement::Volatile(Instr::Cmp(
        Type::Single,
        Cmp::Uo,
        Value::Temporary("a".into()),
        Value::Temporary("b".into()),
    ));
    assert_eq!(format!("{unordered_cmp}"), "cuos %a, %b");

    // Test unsigned comparisons for integers
    let unsigned_lt = Statement::Volatile(Instr::Cmp(
        Type::Word,
        Cmp::Ult,
        Value::Temporary("a".into()),
        Value::Temporary("b".into()),
    ));
    assert_eq!(format!("{unsigned_lt}"), "cultw %a, %b");

    let unsigned_le = Statement::Volatile(Instr::Cmp(
        Type::Long,
        Cmp::Ule,
        Value::Temporary("a".into()),
        Value::Temporary("b".into()),
    ));
    assert_eq!(format!("{unsigned_le}"), "culel %a, %b");

    let unsigned_gt = Statement::Volatile(Instr::Cmp(
        Type::Word,
        Cmp::Ugt,
        Value::Temporary("a".into()),
        Value::Temporary("b".into()),
    ));
    assert_eq!(format!("{unsigned_gt}"), "cugtw %a, %b");

    let unsigned_ge = Statement::Volatile(Instr::Cmp(
        Type::Long,
        Cmp::Uge,
        Value::Temporary("a".into()),
        Value::Temporary("b".into()),
    ));
    assert_eq!(format!("{unsigned_ge}"), "cugel %a, %b");
}

#[test]
fn unsigned_arithmetic_instructions() {
    let udiv = Statement::Assign(
        Value::Temporary("result".into()),
        Type::Word,
        Instr::Udiv(Value::Temporary("a".into()), Value::Temporary("b".into())),
    );
    assert_eq!(format!("{udiv}"), "%result =w udiv %a, %b");

    let urem = Statement::Assign(
        Value::Temporary("result".into()),
        Type::Long,
        Instr::Urem(Value::Temporary("a".into()), Value::Temporary("b".into())),
    );
    assert_eq!(format!("{urem}"), "%result =l urem %a, %b");
}

#[test]
fn shift_instructions() {
    let sar = Statement::Assign(
        Value::Temporary("result".into()),
        Type::Word,
        Instr::Sar(Value::Temporary("a".into()), Value::Temporary("b".into())),
    );
    assert_eq!(format!("{sar}"), "%result =w sar %a, %b");

    let shr = Statement::Assign(
        Value::Temporary("result".into()),
        Type::Long,
        Instr::Shr(Value::Temporary("a".into()), Value::Temporary("b".into())),
    );
    assert_eq!(format!("{shr}"), "%result =l shr %a, %b");

    let shl = Statement::Assign(
        Value::Temporary("result".into()),
        Type::Word,
        Instr::Shl(Value::Temporary("a".into()), Value::Temporary("b".into())),
    );
    assert_eq!(format!("{shl}"), "%result =w shl %a, %b");
}

#[test]
fn cast_instruction() {
    let cast_int_to_float = Statement::Assign(
        Value::Temporary("result".into()),
        Type::Single,
        Instr::Cast(Value::Temporary("a".into())),
    );
    assert_eq!(format!("{cast_int_to_float}"), "%result =s cast %a");

    let cast_float_to_int = Statement::Assign(
        Value::Temporary("result".into()),
        Type::Word,
        Instr::Cast(Value::Temporary("f".into())),
    );
    assert_eq!(format!("{cast_float_to_int}"), "%result =w cast %f");
}

#[test]
fn extension_operations() {
    let extsw = Statement::Assign(
        Value::Temporary("result".into()),
        Type::Long,
        Instr::Extsw(Value::Temporary("a".into())),
    );
    assert_eq!(format!("{extsw}"), "%result =l extsw %a");

    let extuw = Statement::Assign(
        Value::Temporary("result".into()),
        Type::Long,
        Instr::Extuw(Value::Temporary("a".into())),
    );
    assert_eq!(format!("{extuw}"), "%result =l extuw %a");

    let extsh = Statement::Assign(
        Value::Temporary("result".into()),
        Type::Word,
        Instr::Extsh(Value::Temporary("a".into())),
    );
    assert_eq!(format!("{extsh}"), "%result =w extsh %a");

    let extuh = Statement::Assign(
        Value::Temporary("result".into()),
        Type::Word,
        Instr::Extuh(Value::Temporary("a".into())),
    );
    assert_eq!(format!("{extuh}"), "%result =w extuh %a");

    let extsb = Statement::Assign(
        Value::Temporary("result".into()),
        Type::Word,
        Instr::Extsb(Value::Temporary("a".into())),
    );
    assert_eq!(format!("{extsb}"), "%result =w extsb %a");

    let extub = Statement::Assign(
        Value::Temporary("result".into()),
        Type::Word,
        Instr::Extub(Value::Temporary("a".into())),
    );
    assert_eq!(format!("{extub}"), "%result =w extub %a");
}

#[test]
fn float_precision_conversion() {
    let exts = Statement::Assign(
        Value::Temporary("result".into()),
        Type::Double,
        Instr::Exts(Value::Temporary("a".into())),
    );
    assert_eq!(format!("{exts}"), "%result =d exts %a");

    let truncd = Statement::Assign(
        Value::Temporary("result".into()),
        Type::Single,
        Instr::Truncd(Value::Temporary("a".into())),
    );
    assert_eq!(format!("{truncd}"), "%result =s truncd %a");
}

#[test]
fn float_integer_conversions() {
    let stosi = Statement::Assign(
        Value::Temporary("result".into()),
        Type::Word,
        Instr::Stosi(Value::Temporary("a".into())),
    );
    assert_eq!(format!("{stosi}"), "%result =w stosi %a");

    let stoui = Statement::Assign(
        Value::Temporary("result".into()),
        Type::Word,
        Instr::Stoui(Value::Temporary("a".into())),
    );
    assert_eq!(format!("{stoui}"), "%result =w stoui %a");

    let dtosi = Statement::Assign(
        Value::Temporary("result".into()),
        Type::Long,
        Instr::Dtosi(Value::Temporary("a".into())),
    );
    assert_eq!(format!("{dtosi}"), "%result =l dtosi %a");

    let dtoui = Statement::Assign(
        Value::Temporary("result".into()),
        Type::Long,
        Instr::Dtoui(Value::Temporary("a".into())),
    );
    assert_eq!(format!("{dtoui}"), "%result =l dtoui %a");

    let swtof = Statement::Assign(
        Value::Temporary("result".into()),
        Type::Single,
        Instr::Swtof(Value::Temporary("a".into())),
    );
    assert_eq!(format!("{swtof}"), "%result =s swtof %a");

    let uwtof = Statement::Assign(
        Value::Temporary("result".into()),
        Type::Single,
        Instr::Uwtof(Value::Temporary("a".into())),
    );
    assert_eq!(format!("{uwtof}"), "%result =s uwtof %a");

    let sltof = Statement::Assign(
        Value::Temporary("result".into()),
        Type::Double,
        Instr::Sltof(Value::Temporary("a".into())),
    );
    assert_eq!(format!("{sltof}"), "%result =d sltof %a");

    let ultof = Statement::Assign(
        Value::Temporary("result".into()),
        Type::Double,
        Instr::Ultof(Value::Temporary("a".into())),
    );
    assert_eq!(format!("{ultof}"), "%result =d ultof %a");
}

#[test]
fn variadic_instructions() {
    let vastart = Statement::Volatile(Instr::Vastart(Value::Temporary("ap".into())));
    assert_eq!(format!("{vastart}"), "vastart %ap");

    let vaarg = Statement::Assign(
        Value::Temporary("arg".into()),
        Type::Word,
        Instr::Vaarg(Type::Word, Value::Temporary("ap".into())),
    );
    assert_eq!(format!("{vaarg}"), "%arg =w vaargw %ap");
}

#[test]
fn phi_instruction() {
    let phi = Instr::Phi(vec![
        ("ift".into(), Value::Const(2)),
        ("iff".into(), Value::Temporary("3".into())),
    ]);
    assert_eq!(format!("{phi}"), "phi @ift 2, @iff %3");

    let phi = Statement::Assign(
        Value::Temporary("result".into()),
        Type::Word,
        Instr::Phi(vec![
            ("start".into(), Value::Temporary("1".into())),
            ("loop".into(), Value::Global("tmp".into())),
        ]),
    );
    assert_eq!(format!("{phi}"), "%result =w phi @start %1, @loop $tmp");

    let phi = Instr::Phi(vec![
        ("case1".into(), Value::Const(10)),
        ("case2".into(), Value::Const(20)),
        ("case3".into(), Value::Const(30)),
    ]);
    assert_eq!(format!("{phi}"), "phi @case1 10, @case2 20, @case3 30");

    let phi = Statement::Assign(
        Value::Temporary("merged".into()),
        Type::Long,
        Instr::Phi(vec![
            ("path_a".into(), Value::Temporary("x".into())),
            ("path_b".into(), Value::Temporary("y".into())),
            ("path_c".into(), Value::Global("global_val".into())),
            ("path_d".into(), Value::Const(42)),
        ]),
    );
    assert_eq!(
        format!("{phi}"),
        "%merged =l phi @path_a %x, @path_b %y, @path_c $global_val, @path_d 42"
    );
}

#[test]
fn halt_instruction() {
    let hlt = Statement::Volatile(Instr::Hlt);
    assert_eq!(format!("{hlt}"), "hlt");
}

#[test]
fn thread_local_linkage() {
    let thread_local = Linkage::thread_local();
    assert_eq!(format!("{thread_local}"), "thread ");

    let exported_thread_local = Linkage::exported_thread_local();
    assert_eq!(format!("{exported_thread_local}"), "export thread ");

    let thread_local_with_section = Linkage::thread_local_with_section("data");
    assert_eq!(
        format!("{thread_local_with_section}"),
        "thread section \"data\" "
    );

    // Test in a data definition
    let data_def = DataDef {
        linkage: Linkage::thread_local(),
        name: "thread_var".into(),
        align: None,
        items: vec![(Type::Word, DataItem::Const(42))],
    };
    assert_eq!(format!("{data_def}"), "thread data $thread_var = { w 42 }");
}

#[test]
fn zero_initialized_data() {
    let zero_data = DataItem::Zero(1000);
    assert_eq!(format!("{zero_data}"), "z 1000");

    // Test in a data definition
    let data_def = DataDef {
        linkage: Linkage::private(),
        name: "zero_array".into(),
        align: None,
        items: vec![(Type::Byte, DataItem::Zero(1000))],
    };
    assert_eq!(format!("{data_def}"), "data $zero_array = { b z 1000 }");

    // Test mixed with other items
    let data_def = DataDef {
        linkage: Linkage::private(),
        name: "mixed_data".into(),
        align: None,
        items: vec![
            (Type::Word, DataItem::Const(1)),
            (Type::Byte, DataItem::Zero(10)),
            (Type::Word, DataItem::Const(2)),
        ],
    };
    assert_eq!(
        format!("{data_def}"),
        "data $mixed_data = { w 1, b z 10, w 2 }"
    );
}

#[test]
fn complex_block_with_multiple_instructions() {
    // Create a block using several instructions
    let mut block = Block {
        label: "test_block".into(),
        items: Vec::new(),
    };

    // Add unsigned division
    block.assign_instr(
        Value::Temporary("udiv_result".into()),
        Type::Word,
        Instr::Udiv(Value::Temporary("a".into()), Value::Temporary("b".into())),
    );

    // Add a shift operation
    block.assign_instr(
        Value::Temporary("shift_result".into()),
        Type::Word,
        Instr::Shl(Value::Temporary("a".into()), Value::Temporary("b".into())),
    );

    // Add a cast operation
    block.assign_instr(
        Value::Temporary("cast_result".into()),
        Type::Single,
        Instr::Cast(Value::Temporary("shift_result".into())),
    );

    // Add a comparison (unordered)
    block.assign_instr(
        Value::Temporary("cmp_result".into()),
        Type::Word,
        Instr::Cmp(
            Type::Single,
            Cmp::Uo,
            Value::Temporary("cast_result".into()),
            Value::Temporary("x".into()),
        ),
    );

    // Add a termination
    block.add_instr(Instr::Hlt);

    // Format the block and check the output
    let formatted = format!("{block}");
    let lines: Vec<&str> = formatted.lines().collect();

    assert_eq!(lines[0], "@test_block");
    assert_eq!(lines[1], "\t%udiv_result =w udiv %a, %b");
    assert_eq!(lines[2], "\t%shift_result =w shl %a, %b");
    assert_eq!(lines[3], "\t%cast_result =s cast %shift_result");
    assert_eq!(lines[4], "\t%cmp_result =w cuos %cast_result, %x");
    assert_eq!(lines[5], "\thlt");
}

#[test]
fn assign_instr_aggregate_type_coercion() {
    let mut block = Block {
        label: "test_block".into(),
        items: Vec::new(),
    };

    let typedef = Arc::new(TypeDef::Regular {
        ident: "person".into(),
        align: None,
        items: vec![(Type::Long, 1), (Type::Word, 2), (Type::Byte, 1)],
    });

    block.assign_instr(
        Value::Temporary("human".into()),
        Type::aggregate(&typedef),
        Instr::Alloc8(Type::aggregate(&typedef).size()),
    );

    block.assign_instr(
        Value::Temporary("result".into()),
        Type::aggregate(&typedef),
        Instr::Call("new_person".into(), vec![], None),
    );

    let formatted = format!("{block}");
    let lines: Vec<&str> = formatted.lines().collect();

    assert_eq!(lines[0], "@test_block");
    assert_eq!(lines[1], "\t%human =l alloc8 24");
    assert_eq!(lines[2], "\t%result =:person call $new_person()");
}

#[test]
fn load_valid_types() {
    let src = Value::Temporary("addr".into());
    assert_eq!(
        format!("{}", Instr::Load(Type::SignedByte, src.clone())),
        "loadsb %addr"
    );
    assert_eq!(
        format!("{}", Instr::Load(Type::UnsignedByte, src.clone())),
        "loadub %addr"
    );
    assert_eq!(
        format!("{}", Instr::Load(Type::SignedHalfword, src.clone())),
        "loadsh %addr"
    );
    assert_eq!(
        format!("{}", Instr::Load(Type::UnsignedHalfword, src.clone())),
        "loaduh %addr"
    );
    assert_eq!(
        format!("{}", Instr::Load(Type::Word, src.clone())),
        "loadw %addr"
    );
    assert_eq!(
        format!("{}", Instr::Load(Type::Long, src.clone())),
        "loadl %addr"
    );
    assert_eq!(
        format!("{}", Instr::Load(Type::Single, src.clone())),
        "loads %addr"
    );
    assert_eq!(
        format!("{}", Instr::Load(Type::Double, src.clone())),
        "loadd %addr"
    );
}

#[test]
#[should_panic(expected = "ambiguous sub-word load")]
fn load_byte_panics() {
    let src = Value::Temporary("addr".into());
    let _ = format!("{}", Instr::Load(Type::Byte, src));
}

#[test]
#[should_panic(expected = "ambiguous sub-word load")]
fn load_halfword_panics() {
    let src = Value::Temporary("addr".into());
    let _ = format!("{}", Instr::Load(Type::Halfword, src));
}

#[test]
fn store_valid_types() {
    let dest = Value::Temporary("addr".into());
    let val = Value::Temporary("val".into());
    assert_eq!(
        format!("{}", Instr::Store(Type::Byte, dest.clone(), val.clone())),
        "storeb %val, %addr"
    );
    assert_eq!(
        format!(
            "{}",
            Instr::Store(Type::SignedByte, dest.clone(), val.clone())
        ),
        "storeb %val, %addr"
    );
    assert_eq!(
        format!(
            "{}",
            Instr::Store(Type::UnsignedByte, dest.clone(), val.clone())
        ),
        "storeb %val, %addr"
    );
    assert_eq!(
        format!(
            "{}",
            Instr::Store(Type::Halfword, dest.clone(), val.clone())
        ),
        "storeh %val, %addr"
    );
    assert_eq!(
        format!(
            "{}",
            Instr::Store(Type::SignedHalfword, dest.clone(), val.clone())
        ),
        "storeh %val, %addr"
    );
    assert_eq!(
        format!(
            "{}",
            Instr::Store(Type::UnsignedHalfword, dest.clone(), val.clone())
        ),
        "storeh %val, %addr"
    );
    assert_eq!(
        format!("{}", Instr::Store(Type::Word, dest.clone(), val.clone())),
        "storew %val, %addr"
    );
    assert_eq!(
        format!("{}", Instr::Store(Type::Long, dest.clone(), val.clone())),
        "storel %val, %addr"
    );
    assert_eq!(
        format!("{}", Instr::Store(Type::Single, dest.clone(), val.clone())),
        "stores %val, %addr"
    );
    assert_eq!(
        format!("{}", Instr::Store(Type::Double, dest.clone(), val.clone())),
        "stored %val, %addr"
    );
}