xlsynth 0.44.0

Accelerated Hardware Synthesis (XLS/XLSynth) via Rust
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
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
// SPDX-License-Identifier: Apache-2.0

use xlsynth_sys::{CIrBits, CIrValue};

use crate::{
    lib_support::{
        xls_bits_make_bits_from_bytes, xls_bits_make_sbits, xls_bits_make_ubits, xls_bits_to_bytes,
        xls_bits_to_debug_str, xls_bits_to_int64, xls_bits_to_string, xls_bits_to_uint64,
        xls_format_preference_from_string, xls_value_eq, xls_value_free, xls_value_get_bits,
        xls_value_get_element, xls_value_get_element_count, xls_value_make_array,
        xls_value_make_sbits, xls_value_make_token, xls_value_make_tuple, xls_value_make_ubits,
        xls_value_to_string, xls_value_to_string_format_preference,
    },
    xls_parse_typed_value,
    xlsynth_error::XlsynthError,
};

pub struct IrBits {
    pub(crate) ptr: *mut CIrBits,
}

impl IrBits {
    fn from_raw(ptr: *mut CIrBits) -> Self {
        Self { ptr }
    }

    fn apply_binary_op(
        &self,
        rhs: &IrBits,
        op: unsafe extern "C" fn(*const CIrBits, *const CIrBits) -> *mut CIrBits,
    ) -> Self {
        let result = unsafe { op(self.ptr, rhs.ptr) };
        Self::from_raw(result)
    }

    fn apply_unary_op(&self, op: unsafe extern "C" fn(*const CIrBits) -> *mut CIrBits) -> Self {
        let result = unsafe { op(self.ptr) };
        Self::from_raw(result)
    }

    fn assert_matching_bit_count(&self, other: &IrBits) {
        let self_count = self.get_bit_count();
        let other_count = other.get_bit_count();
        assert!(
            self_count == other_count,
            "Bit width mismatch: left bits[{}] vs right bits[{}]",
            self_count,
            other_count
        );
    }

    /// Converts a `&[bool]` slice into an IR `Bits` value.
    ///
    /// ```
    /// use xlsynth::ir_value::IrFormatPreference;
    /// use xlsynth::IrBits;
    ///
    /// let bools = vec![true, false, true, false]; // LSB is bools[0]
    /// let ir_bits: IrBits = IrBits::from_lsb_is_0(&bools);
    /// assert_eq!(ir_bits.to_string_fmt(IrFormatPreference::Binary, false), "0b101");
    /// assert_eq!(ir_bits.get_bit_count(), 4);
    /// assert_eq!(ir_bits.get_bit(0).unwrap(), true); // LSB
    /// assert_eq!(ir_bits.get_bit(1).unwrap(), false);
    /// assert_eq!(ir_bits.get_bit(2).unwrap(), true);
    /// assert_eq!(ir_bits.get_bit(3).unwrap(), false); // MSB
    /// ```
    pub fn from_lsb_is_0(bits: &[bool]) -> Self {
        if bits.is_empty() {
            return IrBits::make_ubits(0, 0).unwrap();
        }
        let mut s: String = format!("bits[{}]:0b", bits.len());
        for b in bits.iter().rev() {
            s.push(if *b { '1' } else { '0' });
        }
        IrValue::parse_typed(&s).unwrap().to_bits().unwrap()
    }

    /// Turns a boolean slice into an IR `Bits` value under the assumption that
    /// index 0 in the slice is the most significant bit (MSb).
    pub fn from_msb_is_0(bits: &[bool]) -> Self {
        if bits.is_empty() {
            return IrBits::make_ubits(0, 0).unwrap();
        }
        let mut s: String = format!("bits[{}]:0b", bits.len());
        for b in bits {
            s.push(if *b { '1' } else { '0' });
        }
        IrValue::parse_typed(&s).unwrap().to_bits().unwrap()
    }

    pub fn make_ubits(bit_count: usize, value: u64) -> Result<Self, XlsynthError> {
        xls_bits_make_ubits(bit_count, value)
    }

    pub fn make_sbits(bit_count: usize, value: i64) -> Result<Self, XlsynthError> {
        xls_bits_make_sbits(bit_count, value)
    }

    /// Builds an `IrBits` value from little-endian payload bytes.
    ///
    /// The input must contain exactly the number of bytes required by
    /// `bit_count`, and any unused high bits in the final byte must be zero.
    ///
    /// # Errors
    ///
    /// Returns an error when the byte count does not match `bit_count`, when
    /// unused high bits are set, or when the underlying XLS value construction
    /// fails.
    pub fn from_le_bytes(bit_count: usize, bytes: &[u8]) -> Result<Self, XlsynthError> {
        let expected_byte_count = bit_count.div_ceil(8);
        if bytes.len() != expected_byte_count {
            return Err(XlsynthError(format!(
                "Expected {expected_byte_count} bytes for bits[{bit_count}], got {}",
                bytes.len()
            )));
        }
        let bit_remainder = bit_count % 8;
        if bit_remainder != 0 && (bytes[expected_byte_count - 1] >> bit_remainder) != 0 {
            return Err(XlsynthError(format!(
                "High bits are set outside bits[{bit_count}] in final byte"
            )));
        }
        xls_bits_make_bits_from_bytes(bit_count, bytes)
    }

    pub fn zero(bit_count: usize) -> Self {
        Self::make_ubits(bit_count, 0).expect("zero literal must construct")
    }

    pub fn all_ones(bit_count: usize) -> Self {
        Self::from_lsb_is_0(&vec![true; bit_count])
    }

    pub fn signed_max_value(bit_count: usize) -> Self {
        if bit_count == 0 {
            return Self::zero(0);
        }
        let mut bits = vec![true; bit_count];
        bits[bit_count - 1] = false;
        Self::from_lsb_is_0(&bits)
    }

    pub fn signed_min_value(bit_count: usize) -> Self {
        if bit_count == 0 {
            return Self::zero(0);
        }
        let mut bits = vec![false; bit_count];
        bits[bit_count - 1] = true;
        Self::from_lsb_is_0(&bits)
    }

    pub fn bool(value: bool) -> Self {
        Self::make_ubits(1, u64::from(value)).unwrap()
    }

    pub fn u32(value: u32) -> Self {
        // Unwrap should be ok since the u32 always fits.
        Self::make_ubits(32, value as u64).unwrap()
    }

    pub fn get_bit_count(&self) -> usize {
        let bit_count = unsafe { xlsynth_sys::xls_bits_get_bit_count(self.ptr) };
        assert!(bit_count >= 0);
        bit_count as usize
    }

    pub fn to_debug_str(&self) -> String {
        xls_bits_to_debug_str(self.ptr)
    }

    /// Note: index 0 is the least significant bit (LSb).
    pub fn get_bit(&self, index: usize) -> Result<bool, XlsynthError> {
        if self.get_bit_count() <= index {
            return Err(XlsynthError(format!(
                "Index {} out of bounds for bits[{}]:{}",
                index,
                self.get_bit_count(),
                self.to_debug_str()
            )));
        }
        let bit = unsafe { xlsynth_sys::xls_bits_get_bit(self.ptr, index as i64) };
        Ok(bit)
    }

    pub fn equals(&self, rhs: &IrBits) -> bool {
        unsafe { xlsynth_sys::xls_bits_eq(self.ptr, rhs.ptr) }
    }

    pub fn to_string_fmt(&self, format: IrFormatPreference, include_bit_count: bool) -> String {
        let fmt_pref: xlsynth_sys::XlsFormatPreference =
            xls_format_preference_from_string(format.to_string()).unwrap();
        xls_bits_to_string(self.ptr, fmt_pref, include_bit_count).unwrap()
    }

    #[allow(dead_code)]
    fn to_hex_string(&self) -> String {
        let value = self.to_string_fmt(IrFormatPreference::Hex, false);
        format!("bits[{}]:{}", self.get_bit_count(), value)
    }

    pub fn to_u64(&self) -> Result<u64, XlsynthError> {
        xls_bits_to_uint64(self.ptr)
    }

    pub fn to_i64(&self) -> Result<i64, XlsynthError> {
        xls_bits_to_int64(self.ptr)
    }

    /// Returns little-endian payload bytes for this value.
    ///
    /// # Errors
    ///
    /// Returns an error if the underlying XLS conversion fails.
    pub fn to_le_bytes(&self) -> Result<Vec<u8>, XlsynthError> {
        xls_bits_to_bytes(self.ptr)
    }

    /// Returns little-endian payload bytes for this value.
    ///
    /// This is the legacy spelling of [`IrBits::to_le_bytes`].
    ///
    /// # Errors
    ///
    /// Returns an error if the underlying XLS conversion fails.
    pub fn to_bytes(&self) -> Result<Vec<u8>, XlsynthError> {
        self.to_le_bytes()
    }

    pub fn is_zero(&self) -> bool {
        if self.get_bit_count() == 0 {
            return true;
        }
        self.to_le_bytes()
            .expect("to_le_bytes should succeed for IrBits")
            .iter()
            .all(|b| *b == 0)
    }

    /// Returns whether this bits value equals the given `u64` integer value.
    ///
    /// This routine is **width-agnostic**: it works for bits widths larger than
    /// 64 by requiring all bits above bit 63 to be zero.
    ///
    /// Note that `bits[0]` can only represent the value 0.
    pub fn equals_u64_value(&self, value: u64) -> bool {
        let w = self.get_bit_count();
        if w == 0 {
            return value == 0;
        }
        // If the width of this bits object is smaller than the value needs, it cannot
        // be represented, and so cannot be equal.
        if w < 64 && (value >> w) != 0 {
            return false;
        }
        // Delegate the representation details to libxls: at this point we know
        // the integer `value` is representable in `w` bits (either `w >= 64` or
        // the high bits above `w` are clear), so constructing `bits[w]:value`
        // must succeed.
        let expected =
            IrBits::make_ubits(w, value).expect("IrBits::make_ubits should succeed for u64 value");
        self.equals(&expected)
    }

    pub fn add(&self, rhs: &IrBits) -> IrBits {
        self.apply_binary_op(rhs, xlsynth_sys::xls_bits_add)
    }

    pub fn sub(&self, rhs: &IrBits) -> IrBits {
        self.apply_binary_op(rhs, xlsynth_sys::xls_bits_sub)
    }

    pub fn umul(&self, rhs: &IrBits) -> IrBits {
        self.apply_binary_op(rhs, xlsynth_sys::xls_bits_umul)
    }

    pub fn smul(&self, rhs: &IrBits) -> IrBits {
        self.apply_binary_op(rhs, xlsynth_sys::xls_bits_smul)
    }

    pub fn negate(&self) -> IrBits {
        self.apply_unary_op(xlsynth_sys::xls_bits_negate)
    }

    pub fn abs(&self) -> IrBits {
        self.apply_unary_op(xlsynth_sys::xls_bits_abs)
    }

    pub fn msb(&self) -> bool {
        self.get_bit(self.get_bit_count() - 1).unwrap()
    }

    pub fn is_negative(&self) -> bool {
        let width = self.get_bit_count();
        width != 0
            && self
                .get_bit(width - 1)
                .expect("sign bit index must be in bounds")
    }

    pub fn udiv(&self, rhs: &IrBits) -> IrBits {
        self.assert_matching_bit_count(rhs);
        self.apply_binary_op(rhs, xlsynth_sys::xls_bits_udiv)
    }

    pub fn umod(&self, rhs: &IrBits) -> IrBits {
        self.assert_matching_bit_count(rhs);
        self.apply_binary_op(rhs, xlsynth_sys::xls_bits_umod)
    }

    pub fn sdiv(&self, rhs: &IrBits) -> IrBits {
        self.assert_matching_bit_count(rhs);
        self.apply_binary_op(rhs, xlsynth_sys::xls_bits_sdiv)
    }

    pub fn smod(&self, rhs: &IrBits) -> IrBits {
        self.assert_matching_bit_count(rhs);
        self.apply_binary_op(rhs, xlsynth_sys::xls_bits_smod)
    }

    pub fn shll(&self, shift_amount: i64) -> IrBits {
        let result = unsafe { xlsynth_sys::xls_bits_shift_left_logical(self.ptr, shift_amount) };
        IrBits { ptr: result }
    }

    pub fn shrl(&self, shift_amount: i64) -> IrBits {
        let result = unsafe { xlsynth_sys::xls_bits_shift_right_logical(self.ptr, shift_amount) };
        IrBits { ptr: result }
    }

    pub fn shra(&self, shift_amount: i64) -> IrBits {
        let result =
            unsafe { xlsynth_sys::xls_bits_shift_right_arithmetic(self.ptr, shift_amount) };
        IrBits { ptr: result }
    }

    pub fn width_slice(&self, start: i64, width: i64) -> IrBits {
        let result = unsafe { xlsynth_sys::xls_bits_width_slice(self.ptr, start, width) };
        IrBits { ptr: result }
    }

    pub fn not(&self) -> IrBits {
        self.apply_unary_op(xlsynth_sys::xls_bits_not)
    }

    pub fn and(&self, rhs: &IrBits) -> IrBits {
        self.apply_binary_op(rhs, xlsynth_sys::xls_bits_and)
    }

    pub fn or(&self, rhs: &IrBits) -> IrBits {
        self.apply_binary_op(rhs, xlsynth_sys::xls_bits_or)
    }

    pub fn xor(&self, rhs: &IrBits) -> IrBits {
        self.apply_binary_op(rhs, xlsynth_sys::xls_bits_xor)
    }

    pub fn ult(&self, other: &IrBits) -> bool {
        self.assert_matching_bit_count(other);
        unsafe { xlsynth_sys::xls_bits_ult(self.ptr, other.ptr) }
    }

    pub fn ule(&self, other: &IrBits) -> bool {
        self.assert_matching_bit_count(other);
        unsafe { xlsynth_sys::xls_bits_ule(self.ptr, other.ptr) }
    }

    pub fn ugt(&self, other: &IrBits) -> bool {
        self.assert_matching_bit_count(other);
        unsafe { xlsynth_sys::xls_bits_ugt(self.ptr, other.ptr) }
    }

    pub fn uge(&self, other: &IrBits) -> bool {
        self.assert_matching_bit_count(other);
        unsafe { xlsynth_sys::xls_bits_uge(self.ptr, other.ptr) }
    }

    pub fn slt(&self, other: &IrBits) -> bool {
        self.assert_matching_bit_count(other);
        unsafe { xlsynth_sys::xls_bits_slt(self.ptr, other.ptr) }
    }

    pub fn sle(&self, other: &IrBits) -> bool {
        self.assert_matching_bit_count(other);
        unsafe { xlsynth_sys::xls_bits_sle(self.ptr, other.ptr) }
    }

    pub fn sgt(&self, other: &IrBits) -> bool {
        self.assert_matching_bit_count(other);
        unsafe { xlsynth_sys::xls_bits_sgt(self.ptr, other.ptr) }
    }

    pub fn sge(&self, other: &IrBits) -> bool {
        self.assert_matching_bit_count(other);
        unsafe { xlsynth_sys::xls_bits_sge(self.ptr, other.ptr) }
    }
}

impl Clone for IrBits {
    fn clone(&self) -> Self {
        // TODO(cdleary): 2025-04-14 Right now we don't have a direct clone API for
        // IrBits. Adding one would make this more efficient.
        let value = IrValue::from_bits(self);
        let clone = value.clone();
        clone.to_bits().unwrap()
    }
}

impl Drop for IrBits {
    fn drop(&mut self) {
        unsafe { xlsynth_sys::xls_bits_free(self.ptr) }
    }
}

impl std::cmp::PartialEq for IrBits {
    fn eq(&self, other: &Self) -> bool {
        self.equals(other)
    }
}

impl std::fmt::Debug for IrBits {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.to_debug_str())
    }
}

impl From<&IrBits> for IrValue {
    fn from(bits: &IrBits) -> Self {
        IrValue::from_bits(bits)
    }
}

impl std::fmt::Display for IrBits {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "bits[{}]:{}",
            self.get_bit_count(),
            self.to_string_fmt(IrFormatPreference::Default, false)
        )
    }
}

// SAFETY: `IrBits` is a thin wrapper around a raw pointer to an immutable
// FFI object managed by the underlying XLS library. The pointer value itself
// may be freely transferred across thread boundaries so long as the
// underlying object is not concurrently mutated through other avenues. The
// XLS C API does not provide any mutation operations that would violate this
// assumption for the usage patterns within xlsynth, so it is sound to mark
// `IrBits` as `Send` and `Sync`.

unsafe impl Send for IrBits {}
unsafe impl Sync for IrBits {}

impl std::ops::Add for IrBits {
    type Output = Self;

    fn add(self, rhs: Self) -> Self::Output {
        IrBits::add(&self, &rhs)
    }
}

impl std::ops::Sub for IrBits {
    type Output = Self;

    fn sub(self, rhs: Self) -> Self::Output {
        IrBits::sub(&self, &rhs)
    }
}

impl std::ops::BitAnd for IrBits {
    type Output = Self;

    fn bitand(self, rhs: Self) -> Self::Output {
        IrBits::and(&self, &rhs)
    }
}

impl std::ops::BitOr for IrBits {
    type Output = Self;

    fn bitor(self, rhs: Self) -> Self::Output {
        IrBits::or(&self, &rhs)
    }
}

impl std::ops::BitXor for IrBits {
    type Output = Self;

    fn bitxor(self, rhs: Self) -> Self::Output {
        IrBits::xor(&self, &rhs)
    }
}

impl std::ops::Not for IrBits {
    type Output = Self;

    fn not(self) -> Self::Output {
        IrBits::not(&self)
    }
}

// --

pub enum IrFormatPreference {
    Default,
    Binary,
    SignedDecimal,
    UnsignedDecimal,
    Hex,
    PlainBinary,
    ZeroPaddedBinary,
    PlainHex,
    ZeroPaddedHex,
}

impl IrFormatPreference {
    pub fn to_string(&self) -> &'static str {
        match self {
            IrFormatPreference::Default => "default",
            IrFormatPreference::Binary => "binary",
            IrFormatPreference::SignedDecimal => "signed_decimal",
            IrFormatPreference::UnsignedDecimal => "unsigned_decimal",
            IrFormatPreference::Hex => "hex",
            IrFormatPreference::PlainBinary => "plain_binary",
            IrFormatPreference::ZeroPaddedBinary => "zero_padded_binary",
            IrFormatPreference::PlainHex => "plain_hex",
            IrFormatPreference::ZeroPaddedHex => "zero_padded_hex",
        }
    }
}

pub struct IrValue {
    pub(crate) ptr: *mut CIrValue,
}

impl IrValue {
    pub fn make_token() -> Self {
        xls_value_make_token()
    }

    pub fn make_tuple(elements: &[IrValue]) -> Self {
        xls_value_make_tuple(elements)
    }

    /// Returns an error if the elements do not all have the same type.
    pub fn make_array(elements: &[IrValue]) -> Result<Self, XlsynthError> {
        xls_value_make_array(elements)
    }

    pub fn from_bits(bits: &IrBits) -> Self {
        let ptr = unsafe { xlsynth_sys::xls_value_from_bits(bits.ptr) };
        Self { ptr }
    }

    pub fn parse_typed(s: &str) -> Result<Self, XlsynthError> {
        xls_parse_typed_value(s)
    }

    pub fn bool(value: bool) -> Self {
        xls_value_make_ubits(value as u64, 1).unwrap()
    }

    pub fn u32(value: u32) -> Self {
        // Unwrap should be ok since the u32 always fits.
        xls_value_make_ubits(value as u64, 32).unwrap()
    }

    pub fn u64(value: u64) -> Self {
        // Unwrap should be ok since the u64 always fits.
        xls_value_make_ubits(value, 64).unwrap()
    }

    pub fn make_ubits(bit_count: usize, value: u64) -> Result<Self, XlsynthError> {
        xls_value_make_ubits(value, bit_count)
    }

    pub fn make_sbits(bit_count: usize, value: i64) -> Result<Self, XlsynthError> {
        xls_value_make_sbits(value, bit_count)
    }

    pub fn all_ones_bits(bit_count: usize) -> Self {
        let bits = IrBits::all_ones(bit_count);
        Self::from_bits(&bits)
    }

    pub fn signed_max_bits(bit_count: usize) -> Self {
        let bits = IrBits::signed_max_value(bit_count);
        Self::from_bits(&bits)
    }

    pub fn signed_min_bits(bit_count: usize) -> Self {
        let bits = IrBits::signed_min_value(bit_count);
        Self::from_bits(&bits)
    }

    pub fn bit_count(&self) -> Result<usize, XlsynthError> {
        // TODO(cdleary): 2024-06-23 Expose a more efficient API for this from libxls.so
        let bits = self.to_bits()?;
        Ok(bits.get_bit_count())
    }

    pub fn to_string_fmt(&self, format: IrFormatPreference) -> Result<String, XlsynthError> {
        let fmt_pref: xlsynth_sys::XlsFormatPreference =
            xls_format_preference_from_string(format.to_string())?;
        xls_value_to_string_format_preference(self.ptr, fmt_pref)
    }

    pub fn to_string_fmt_no_prefix(
        &self,
        format: IrFormatPreference,
    ) -> Result<String, XlsynthError> {
        let s = self.to_string_fmt(format)?;
        // Use a regex for now to strip out all `bits[N]:` prefixes.
        let re = regex::Regex::new(r"bits\[[0-9]+\]:").unwrap();
        Ok(re.replace_all(&s, "").to_string())
    }

    pub fn to_bool(&self) -> Result<bool, XlsynthError> {
        let bits = self.to_bits()?;
        if bits.get_bit_count() != 1 {
            return Err(XlsynthError(format!(
                "IrValue {self} is not single-bit; must be bits[1] to convert to bool"
            )));
        }
        bits.get_bit(0)
    }

    pub fn to_i64(&self) -> Result<i64, XlsynthError> {
        let bits = self.to_bits()?;
        let width = bits.get_bit_count();
        if width > 64 {
            return Err(XlsynthError(format!(
                "IrValue::to_i64(): width {width} exceeds 64 bits"
            )));
        }
        let unsigned = self.to_u64()?;
        let shift = 64 - width;
        Ok(((unsigned << shift) as i64) >> shift)
    }

    pub fn to_u64(&self) -> Result<u64, XlsynthError> {
        let bits = self.to_bits()?;
        let width = bits.get_bit_count();
        if width > 64 {
            return Err(XlsynthError(format!(
                "IrValue::to_u64(): width {width} exceeds 64 bits"
            )));
        }
        let mut val: u64 = 0;
        for idx in (0..width).rev() {
            val = (val << 1) | bits.get_bit(idx)? as u64;
        }
        Ok(val)
    }

    pub fn to_u32(&self) -> Result<u32, XlsynthError> {
        let val = self.to_u64()?;
        if val > u32::MAX as u64 {
            return Err(XlsynthError(format!(
                "IrValue::to_u32() value {val} does not fit in u32"
            )));
        }
        Ok(val as u32)
    }

    /// Attempts to extract the bits contents underlying this value.
    ///
    /// If this value is not a bits type, an error is returned.
    pub fn to_bits(&self) -> Result<IrBits, XlsynthError> {
        xls_value_get_bits(self.ptr)
    }

    /// Returns whether this value is a bits-typed literal equal to `value`.
    ///
    /// This routine is width-agnostic for values wider than 64 bits: it works
    /// by inspecting the underlying `IrBits` bytes rather than using
    /// `to_u64()`.
    pub fn bits_equals_u64_value(&self, value: u64) -> bool {
        let Ok(bits) = self.to_bits() else {
            return false;
        };
        bits.equals_u64_value(value)
    }

    pub fn get_element(&self, index: usize) -> Result<IrValue, XlsynthError> {
        xls_value_get_element(self.ptr, index)
    }

    pub fn get_element_count(&self) -> Result<usize, XlsynthError> {
        xls_value_get_element_count(self.ptr)
    }

    pub fn get_elements(&self) -> Result<Vec<IrValue>, XlsynthError> {
        let count = self.get_element_count()?;
        let mut elements = Vec::with_capacity(count);
        for i in 0..count {
            let element = self.get_element(i)?;
            elements.push(element);
        }
        Ok(elements)
    }
}

unsafe impl Send for IrValue {}
unsafe impl Sync for IrValue {}

impl From<bool> for IrValue {
    fn from(val: bool) -> Self {
        IrValue::bool(val)
    }
}
impl From<u32> for IrValue {
    fn from(val: u32) -> Self {
        IrValue::u32(val)
    }
}
impl From<u64> for IrValue {
    fn from(val: u64) -> Self {
        IrValue::u64(val)
    }
}

impl std::cmp::PartialEq for IrValue {
    fn eq(&self, other: &Self) -> bool {
        xls_value_eq(self.ptr, other.ptr).expect("eq success")
    }
}

// `Eq` is safe because XLS values are immutable and `xls_value_eq` defines a
// proper equivalence relation.
impl Eq for IrValue {}

impl std::fmt::Display for IrValue {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "{}",
            xls_value_to_string(self.ptr).expect("stringify success")
        )
    }
}

impl std::fmt::Debug for IrValue {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "{}",
            xls_value_to_string(self.ptr).expect("stringify success")
        )
    }
}

impl Drop for IrValue {
    fn drop(&mut self) {
        xls_value_free(self.ptr)
    }
}

impl Clone for IrValue {
    fn clone(&self) -> Self {
        let ptr = unsafe { xlsynth_sys::xls_value_clone(self.ptr) };
        Self { ptr }
    }
}

/// Typed wrapper around an `IrBits` value that has a particular
/// compile-time-known bit width and whose type notes the value
/// should be treated as unsigned.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct IrUBits<const BIT_COUNT: usize> {
    wrapped: IrBits,
}

impl<const BIT_COUNT: usize> IrUBits<BIT_COUNT> {
    /// Indicates that this typed bits wrapper uses unsigned integer semantics.
    pub const SIGNEDNESS: bool = false;

    /// Wraps arbitrary-width bits after checking the compile-time bit width.
    ///
    /// # Errors
    ///
    /// Returns an error when `wrapped` does not have exactly `BIT_COUNT` bits.
    pub fn new(wrapped: IrBits) -> Result<Self, XlsynthError> {
        if wrapped.get_bit_count() != BIT_COUNT {
            return Err(XlsynthError(format!(
                "Expected {} bits, got {}",
                BIT_COUNT,
                wrapped.get_bit_count()
            )));
        }
        Ok(Self { wrapped })
    }

    /// Creates an unsigned typed bits value from a `u64`.
    ///
    /// # Errors
    ///
    /// Returns an error when `value` cannot be represented in `BIT_COUNT` bits.
    pub fn from_u64(value: u64) -> Result<Self, XlsynthError> {
        Self::new(IrBits::make_ubits(BIT_COUNT, value)?)
    }

    /// Creates an unsigned typed bits value from little-endian payload bytes.
    ///
    /// # Errors
    ///
    /// Returns an error when the byte payload is not canonical for `BIT_COUNT`.
    pub fn from_le_bytes(bytes: &[u8]) -> Result<Self, XlsynthError> {
        Self::new(IrBits::from_le_bytes(BIT_COUNT, bytes)?)
    }

    /// Converts this value to a `u64` when the bit width fits.
    ///
    /// # Errors
    ///
    /// Returns an error when `BIT_COUNT` is wider than `u64`.
    pub fn to_u64(&self) -> Result<u64, XlsynthError> {
        self.wrapped.to_u64()
    }

    /// Returns little-endian payload bytes for this value.
    ///
    /// # Errors
    ///
    /// Returns an error if the underlying XLS conversion fails.
    pub fn to_le_bytes(&self) -> Result<Vec<u8>, XlsynthError> {
        self.wrapped.to_le_bytes()
    }

    /// Borrows the underlying arbitrary-width bits value.
    pub fn as_bits(&self) -> &IrBits {
        &self.wrapped
    }
}

/// Typed wrapper around an `IrBits` value that has a particular
/// compile-time-known bit width and whose type notes the value
/// should be treated as signed.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct IrSBits<const BIT_COUNT: usize> {
    wrapped: IrBits,
}

impl<const BIT_COUNT: usize> IrSBits<BIT_COUNT> {
    /// Indicates that this typed bits wrapper uses signed integer semantics.
    pub const SIGNEDNESS: bool = true;

    /// Wraps arbitrary-width bits after checking the compile-time bit width.
    ///
    /// # Errors
    ///
    /// Returns an error when `wrapped` does not have exactly `BIT_COUNT` bits.
    pub fn new(wrapped: IrBits) -> Result<Self, XlsynthError> {
        if wrapped.get_bit_count() != BIT_COUNT {
            return Err(XlsynthError(format!(
                "Expected {} bits, got {}",
                BIT_COUNT,
                wrapped.get_bit_count()
            )));
        }
        Ok(Self { wrapped })
    }

    /// Creates a signed typed bits value from an `i64`.
    ///
    /// # Errors
    ///
    /// Returns an error when `value` cannot be represented in `BIT_COUNT` bits.
    pub fn from_i64(value: i64) -> Result<Self, XlsynthError> {
        Self::new(IrBits::make_sbits(BIT_COUNT, value)?)
    }

    /// Creates a signed typed bits value from little-endian payload bytes.
    ///
    /// # Errors
    ///
    /// Returns an error when the byte payload is not canonical for `BIT_COUNT`.
    pub fn from_le_bytes(bytes: &[u8]) -> Result<Self, XlsynthError> {
        Self::new(IrBits::from_le_bytes(BIT_COUNT, bytes)?)
    }

    /// Converts this value to an `i64` when the bit width fits.
    ///
    /// # Errors
    ///
    /// Returns an error when `BIT_COUNT` is wider than `i64`.
    pub fn to_i64(&self) -> Result<i64, XlsynthError> {
        self.wrapped.to_i64()
    }

    /// Returns little-endian payload bytes for this value.
    ///
    /// # Errors
    ///
    /// Returns an error if the underlying XLS conversion fails.
    pub fn to_le_bytes(&self) -> Result<Vec<u8>, XlsynthError> {
        self.wrapped.to_le_bytes()
    }

    /// Borrows the underlying arbitrary-width bits value.
    pub fn as_bits(&self) -> &IrBits {
        &self.wrapped
    }
}

impl std::cmp::Eq for IrBits {}

impl std::hash::Hash for IrBits {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        // Since IrBits has a pointer field, we need to hash the actual bits
        // We can use the debug string representation as a stable hash
        self.to_debug_str().hash(state);
    }
}

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

    #[test]
    fn test_ir_value_eq() {
        let v1 = IrValue::parse_typed("bits[32]:42").expect("parse success");
        let v2 = IrValue::parse_typed("bits[32]:42").expect("parse success");
        assert_eq!(v1, v2);
    }

    #[test]
    fn test_ir_value_eq_fail() {
        let v1 = IrValue::parse_typed("bits[32]:42").expect("parse success");
        let v2 = IrValue::parse_typed("bits[32]:43").expect("parse success");
        assert_ne!(v1, v2);
    }

    #[test]
    fn test_ir_value_display() {
        let v = IrValue::parse_typed("bits[32]:42").expect("parse success");
        assert_eq!(format!("{v}"), "bits[32]:42");
    }

    #[test]
    fn test_ir_value_debug() {
        let v = IrValue::parse_typed("bits[32]:42").expect("parse success");
        assert_eq!(format!("{v:?}"), "bits[32]:42");
    }

    #[test]
    fn test_ir_value_drop() {
        let v = IrValue::parse_typed("bits[32]:42").expect("parse success");
        drop(v);
    }

    #[test]
    fn test_ir_value_fmt_pref() {
        let v = IrValue::parse_typed("bits[32]:42").expect("parse success");
        assert_eq!(
            v.to_string_fmt(IrFormatPreference::Default)
                .expect("fmt success"),
            "bits[32]:42"
        );
        assert_eq!(
            v.to_string_fmt(IrFormatPreference::Binary)
                .expect("fmt success"),
            "bits[32]:0b10_1010"
        );
        assert_eq!(
            v.to_string_fmt(IrFormatPreference::SignedDecimal)
                .expect("fmt success"),
            "bits[32]:42"
        );
        assert_eq!(
            v.to_string_fmt(IrFormatPreference::UnsignedDecimal)
                .expect("fmt success"),
            "bits[32]:42"
        );
        assert_eq!(
            v.to_string_fmt(IrFormatPreference::Hex)
                .expect("fmt success"),
            "bits[32]:0x2a"
        );
        assert_eq!(
            v.to_string_fmt(IrFormatPreference::PlainBinary)
                .expect("fmt success"),
            "bits[32]:101010"
        );
        assert_eq!(
            v.to_string_fmt(IrFormatPreference::PlainHex)
                .expect("fmt success"),
            "bits[32]:2a"
        );
    }

    #[test]
    fn test_ir_value_from_rust() {
        let v = IrValue::u64(42);

        // Check formatting for default stringification.
        assert_eq!(
            v.to_string_fmt(IrFormatPreference::Default)
                .expect("fmt success"),
            "bits[64]:42"
        );
        // Check the bit count is as we specified.
        assert_eq!(v.bit_count().unwrap(), 64);

        // Check we can't convert a 64-bit value to a bool.
        v.to_bool()
            .expect_err("bool conversion should error for u64");

        let v_i64 = v.to_i64().expect("i64 conversion success");
        assert_eq!(v_i64, 42);

        let f = IrValue::parse_typed("bits[1]:0").expect("parse success");
        assert!(!f.to_bool().unwrap());

        let t = IrValue::parse_typed("bits[1]:1").expect("parse success");
        assert!(t.to_bool().unwrap());
    }

    #[test]
    fn test_ir_value_get_bits() {
        let v = IrValue::parse_typed("bits[32]:42").expect("parse success");
        let bits = v.to_bits().expect("to_bits success");

        // Equality comparison.
        let v2 = IrValue::u32(42);
        assert_eq!(v, v2);

        // Getting at bit values; 42 = 0b101010.
        assert!(!bits.get_bit(0).unwrap());
        assert!(bits.get_bit(1).unwrap());
        assert!(!bits.get_bit(2).unwrap());
        assert!(bits.get_bit(3).unwrap());
        assert!(!bits.get_bit(4).unwrap());
        assert!(bits.get_bit(5).unwrap());
        assert!(!bits.get_bit(6).unwrap());
        for i in 7..32 {
            assert!(!bits.get_bit(i).unwrap());
        }
        assert!(
            bits.get_bit(32).is_err(),
            "Expected an error for out of bounds index"
        );
        assert!(bits
            .get_bit(32)
            .unwrap_err()
            .to_string()
            .contains("Index 32 out of bounds for bits[32]:0b00000000000000000000000000101010"));

        let debug_fmt = format!("{bits:?}");
        assert_eq!(debug_fmt, "0b00000000000000000000000000101010");
    }

    #[test]
    fn test_ir_value_make_bits() {
        let zero_u2 = IrValue::make_ubits(2, 0).expect("make_ubits success");
        assert_eq!(
            zero_u2
                .to_string_fmt(IrFormatPreference::Default)
                .expect("fmt success"),
            "bits[2]:0"
        );

        let three_u2 = IrValue::make_ubits(2, 3).expect("make_ubits success");
        assert_eq!(
            three_u2
                .to_string_fmt(IrFormatPreference::Default)
                .expect("fmt success"),
            "bits[2]:3"
        );
    }

    #[test]
    fn test_ir_value_parse_array_value() {
        let text = "[bits[32]:1, bits[32]:2]";
        let v = IrValue::parse_typed(text).expect("parse success");
        assert_eq!(v.to_string(), text);
    }

    #[test]
    fn test_ir_value_parse_2d_array_value() {
        let text = "[[bits[32]:1, bits[32]:2], [bits[32]:3, bits[32]:4], [bits[32]:5, bits[32]:6]]";
        let v = IrValue::parse_typed(text).expect("parse success");
        assert_eq!(v.to_string(), text);
    }

    #[test]
    fn test_ir_bits_add() {
        let two = IrBits::u32(2);
        let three = IrBits::u32(3);
        let sum = two.add(&three);
        assert_eq!(sum.to_string(), "bits[32]:5");

        // Ensure the originals were not consumed by the add method.
        assert_eq!(two.to_string(), "bits[32]:2");
        assert_eq!(three.to_string(), "bits[32]:3");

        // The `+` operator should behave equivalently.
        let sum_op = two.clone() + three.clone();
        assert_eq!(sum, sum_op);
    }

    #[test]
    fn test_ir_bits_sub() {
        let five = IrBits::u32(5);
        let two = IrBits::u32(2);
        let diff = five.sub(&two);
        assert_eq!(diff.to_string(), "bits[32]:3");

        // Ensure the originals were not consumed by the sub method.
        assert_eq!(five.to_string(), "bits[32]:5");
        assert_eq!(two.to_string(), "bits[32]:2");

        // The `-` operator should behave equivalently.
        let diff_op = five.clone() - two.clone();
        assert_eq!(diff, diff_op);
    }

    #[test]
    fn test_ir_bits_eq() {
        let a = IrBits::u32(0x12345678);
        let b = IrBits::u32(0x12345678);
        let c = IrBits::u32(0x87654321);
        assert!(a.equals(&b));
        assert!(!a.equals(&c));
        assert_eq!(a, b);
        assert_ne!(a, c);
    }

    #[test]
    fn test_ir_bits_umul_two_times_three() {
        let two = IrBits::u32(2);
        let three = IrBits::u32(3);
        let product = two.umul(&three);
        assert_eq!(product.to_string(), "bits[64]:6");
    }

    #[test]
    fn test_ir_bits_smul_two_times_neg_three() {
        let two = IrBits::u32(2);
        let neg_three = IrBits::u32(3).negate();
        let product = two.smul(&neg_three);
        assert!(product.msb());
        assert_eq!(product.abs().to_string(), "bits[64]:6");
    }

    #[test]
    fn test_ir_bits_negate() {
        let three = IrBits::u32(3);
        let neg = three.negate();
        assert_eq!(neg.to_hex_string(), "bits[32]:0xffff_fffd");
    }

    #[test]
    fn test_ir_bits_abs() {
        let neg_three = IrBits::u32(3).negate();
        let abs = neg_three.abs();
        assert_eq!(abs.to_string(), "bits[32]:3");
    }

    #[test]
    fn test_ir_bits_width_slice() {
        let bits = IrBits::u32(0x12345678);
        let slice = bits.width_slice(8, 16);
        assert_eq!(slice.to_hex_string(), "bits[16]:0x3456");
    }

    #[test]
    fn test_ir_bits_shll() {
        let bits = IrBits::u32(0x12345678);
        let shifted = bits.shll(8);
        assert_eq!(shifted.to_hex_string(), "bits[32]:0x3456_7800");
    }

    #[test]
    fn test_ir_bits_shrl() {
        let bits = IrBits::u32(0x12345678);
        let shifted = bits.shrl(8);
        assert_eq!(shifted.to_hex_string(), "bits[32]:0x12_3456");
    }

    #[test]
    fn test_ir_bits_shra() {
        let bits = IrBits::u32(0x92345678);
        let shifted = bits.shra(8);
        assert_eq!(shifted.to_hex_string(), "bits[32]:0xff92_3456");
    }

    #[test]
    fn test_ir_bits_u32() {
        let bits = IrBits::u32(0x12345678);
        assert_eq!(bits.to_hex_string(), "bits[32]:0x1234_5678");
    }

    #[test]
    fn test_ir_bits_get_bit() {
        let bits = IrBits::u32(0b1010);
        assert!(!bits.get_bit(0).unwrap());
        assert!(bits.get_bit(1).unwrap());
        assert!(bits.get_bit(3).unwrap());
        assert!(bits.get_bit(32).is_err());
    }

    #[test]
    fn test_ir_bits_to_u64() {
        let bits = IrBits::u32(0x12345678);
        assert_eq!(bits.to_u64().unwrap(), 0x12345678);
    }

    #[test]
    fn test_ir_bits_to_i64() {
        let bits = IrBits::make_sbits(8, -5).expect("make_sbits success");
        assert_eq!(bits.to_i64().unwrap(), -5);
    }

    // Verifies: `IrBits` byte conversion exposes little-endian payload order.
    // Catches: accidental reintroduction of ambiguous `to_bytes` semantics.
    #[test]
    fn test_ir_bits_to_le_bytes() {
        let bits = IrBits::u32(0x12345678);
        assert_eq!(bits.to_le_bytes().unwrap(), vec![0x78, 0x56, 0x34, 0x12]);
    }

    #[test]
    fn test_ir_bits_equals_u64_value_zero_width() {
        let bits0 = IrBits::make_ubits(0, 0).expect("make_ubits success");
        assert!(bits0.equals_u64_value(0));
        assert!(!bits0.equals_u64_value(1));
    }

    #[test]
    fn test_ir_bits_equals_u64_value_wide() {
        let bits128 = IrBits::make_ubits(128, 1).expect("make_ubits success");
        assert!(bits128.equals_u64_value(1));
        assert!(!bits128.equals_u64_value(2));
    }

    #[test]
    fn test_ir_bits_equals_u64_value_non_byte_aligned_width() {
        let bits9 = IrBits::make_ubits(9, 0x1ff).expect("make_ubits success");
        assert!(bits9.equals_u64_value(0x1ff));
        assert!(!bits9.equals_u64_value(0x3ff));
    }

    #[test]
    fn test_ir_bits_and() {
        let lhs = IrBits::u32(0x5a5a5a5a);
        let rhs = IrBits::u32(0xa5a5a5a5);
        assert_eq!(lhs.and(&rhs).to_hex_string(), "bits[32]:0x0");
        assert_eq!(lhs.and(&rhs.not()).to_hex_string(), "bits[32]:0x5a5a_5a5a");
    }

    #[test]
    fn test_ir_bits_or() {
        let lhs = IrBits::u32(0x5a5a5a5a);
        let rhs = IrBits::u32(0xa5a5a5a5);
        assert_eq!(lhs.or(&rhs).to_hex_string(), "bits[32]:0xffff_ffff");
        assert_eq!(lhs.or(&rhs.not()).to_hex_string(), "bits[32]:0x5a5a_5a5a");
    }

    #[test]
    fn test_ir_bits_xor() {
        let lhs = IrBits::u32(0x5a5a5a5a);
        let rhs = IrBits::u32(0xa5a5a5a5);
        assert_eq!(lhs.xor(&rhs).to_hex_string(), "bits[32]:0xffff_ffff");
        assert_eq!(lhs.xor(&rhs.not()).to_hex_string(), "bits[32]:0x0");
    }

    #[test]
    fn test_ir_bits_not() {
        let zero = IrBits::u32(0);
        assert_eq!(zero.not().to_hex_string(), "bits[32]:0xffff_ffff");
    }

    #[test]
    fn test_make_tuple_and_get_elements() {
        let _ = env_logger::builder().is_test(true).try_init();
        let b1_v0 = IrValue::make_ubits(1, 0).expect("make_ubits success");
        let b2_v1 = IrValue::make_ubits(2, 1).expect("make_ubits success");
        let b3_v2 = IrValue::make_ubits(3, 2).expect("make_ubits success");
        let tuple = IrValue::make_tuple(&[b1_v0.clone(), b2_v1.clone(), b3_v2.clone()]);
        let elements = tuple.get_elements().expect("get_elements success");
        assert_eq!(elements.len(), 3);
        assert_eq!(elements[0].to_string(), "bits[1]:0");
        assert_eq!(elements[0], b1_v0);
        assert_eq!(elements[1].to_string(), "bits[2]:1");
        assert_eq!(elements[1], b2_v1);
        assert_eq!(elements[2].to_string(), "bits[3]:2");
        assert_eq!(elements[2], b3_v2);
    }

    #[test]
    fn test_make_ir_value_bits_that_does_not_fit() {
        let result = IrValue::make_ubits(1, 2);
        assert!(result.is_err());
        let error = result.unwrap_err();
        assert!(
            error.to_string().contains(
                "0x2 requires 2 bits to fit in an unsigned datatype, but attempting to fit in 1 bit"
            ),
            "got: {}",
            error
        );

        let result = IrValue::make_sbits(1, -2);
        assert!(result.is_err());
        let error = result.unwrap_err();
        assert!(error.to_string().contains("0xfffffffffffffffe requires 2 bits to fit in an signed datatype, but attempting to fit in 1 bit"), "got: {}", error);
    }

    #[test]
    fn test_make_ir_value_array() {
        let b2_v0 = IrValue::make_ubits(2, 0).expect("make_ubits success");
        let b2_v1 = IrValue::make_ubits(2, 1).expect("make_ubits success");
        let b2_v2 = IrValue::make_ubits(2, 2).expect("make_ubits success");
        let b2_v3 = IrValue::make_ubits(2, 3).expect("make_ubits success");
        let array = IrValue::make_array(&[b2_v0, b2_v1, b2_v2, b2_v3]).expect("make_array success");
        assert_eq!(
            array.to_string(),
            "[bits[2]:0, bits[2]:1, bits[2]:2, bits[2]:3]"
        );
    }

    #[test]
    fn test_make_ir_value_empty_array() {
        IrValue::make_array(&[]).expect_err("make_array should fail for empty array");
    }

    #[test]
    fn test_make_ir_value_array_with_mixed_types() {
        let b2_v0 = IrValue::make_ubits(2, 0).expect("make_ubits success");
        let b3_v1 = IrValue::make_ubits(3, 1).expect("make_ubits success");
        let result = IrValue::make_array(&[b2_v0, b3_v1]);
        assert!(result.is_err());
        let error = result.unwrap_err();
        assert!(error.to_string().contains("SameTypeAs"));
    }

    #[test]
    fn test_ir_value_bits_convenience_constructors() {
        assert_eq!(IrValue::all_ones_bits(8).to_string(), "bits[8]:255");
        assert_eq!(IrValue::signed_max_bits(8).to_string(), "bits[8]:127");
        assert_eq!(IrValue::signed_min_bits(8).to_string(), "bits[8]:128");
        assert_eq!(IrValue::all_ones_bits(0).to_string(), "bits[0]:0");
    }
}