tblgen 0.9.1

Safe Rust bindings for TableGen.
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
// Original work Copyright 2016 Alexander Stocko <as@coder.gg>.
// Modified work Copyright 2023 Daan Vanoverloop
// See the COPYRIGHT file at the top-level directory of this distribution.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use paste::paste;
use std::{ffi::c_void, marker::PhantomData};

use crate::raw::{
    TableGenRecTyKind::TableGenInvalidRecTyKind as RawInvalidRecTyKind, TableGenRecordRef,
    TableGenRecordValRef, tableGenIntArrayFree, tableGenRecordDump, tableGenRecordGetDefInit,
    tableGenRecordGetFieldType, tableGenRecordGetFirstValue, tableGenRecordGetID,
    tableGenRecordGetLoc, tableGenRecordGetName, tableGenRecordGetNameInit,
    tableGenRecordGetNumSuperClasses, tableGenRecordGetNumTemplateArgs,
    tableGenRecordGetSuperClass, tableGenRecordGetTemplateArgName, tableGenRecordGetValue,
    tableGenRecordGetValueAsBit, tableGenRecordGetValueAsBitsInit, tableGenRecordGetValueAsDag,
    tableGenRecordGetValueAsDef, tableGenRecordGetValueAsInt, tableGenRecordGetValueAsListInit,
    tableGenRecordGetValueAsListOfDefs, tableGenRecordGetValueAsListOfInts,
    tableGenRecordGetValueAsListOfStrings, tableGenRecordGetValueAsOptionalDef,
    tableGenRecordGetValueAsOptionalString, tableGenRecordGetValueAsString,
    tableGenRecordHasDirectSuperClass, tableGenRecordIsAnonymous, tableGenRecordIsClass,
    tableGenRecordIsSubclassOf, tableGenRecordIsValueUnset, tableGenRecordPrint,
    tableGenRecordRecTyGetClass, tableGenRecordRecTyGetNumClasses, tableGenRecordRecTyIsSubClassOf,
    tableGenRecordValDump, tableGenRecordValGetBitsWidth, tableGenRecordValGetListElementType,
    tableGenRecordValGetLoc, tableGenRecordValGetNameInit, tableGenRecordValGetValue,
    tableGenRecordValIsNonconcreteOK, tableGenRecordValIsTemplateArg, tableGenRecordValNext,
    tableGenRecordValPrint, tableGenStringRefArrayFree,
};

use crate::{
    error::{Error, SourceLoc, SourceLocation, TableGenError, WithLocation},
    init::{BitInit, BitsInit, DagInit, DefInit, ListInit, StringInit, TypedInit},
    string_ref::StringRef,
    util::print_callback,
};
use std::fmt::{self, Debug, Display, Formatter};

/// An immutable reference to a TableGen record.
///
/// This reference cannot outlive the
/// [`RecordKeeper`](crate::record_keeper::RecordKeeper) from which it is
/// borrowed.
#[derive(Clone, Copy, PartialEq, Eq)]
pub struct Record<'a> {
    raw: TableGenRecordRef,
    _reference: PhantomData<&'a TableGenRecordRef>,
}

impl Display for Record<'_> {
    fn fmt(&self, formatter: &mut Formatter) -> fmt::Result {
        let mut data = (formatter, Ok(()));

        unsafe {
            tableGenRecordPrint(
                self.raw,
                Some(print_callback),
                &mut data as *mut _ as *mut c_void,
            );
        }

        data.1
    }
}

impl Debug for Record<'_> {
    fn fmt(&self, formatter: &mut Formatter) -> fmt::Result {
        writeln!(formatter, "Record(")?;
        Display::fmt(self, formatter)?;
        write!(formatter, ")")
    }
}

impl std::hash::Hash for Record<'_> {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        self.raw.hash(state);
    }
}

macro_rules! record_value {
    ($(#[$attr:meta])* $name:ident, $type:ty) => {
        paste! {
            $(#[$attr])*
            pub fn [<$name _value>](self, name: &str) -> Result<$type, Error> {
                self.value(name)?.try_into()
            }
        }
    };
}

impl<'a> Record<'a> {
    /// Creates a record from a raw object.
    ///
    /// # Safety
    ///
    /// The raw object must be valid.
    pub unsafe fn from_raw(ptr: TableGenRecordRef) -> Record<'a> {
        Record {
            raw: ptr,
            _reference: PhantomData,
        }
    }

    /// Returns the name of the record.
    ///
    /// # Errors
    ///
    /// Returns an error if the name is not a valid UTF-8 string.
    pub fn name(self) -> Result<&'a str, Error> {
        unsafe { StringRef::from_raw(tableGenRecordGetName(self.raw)) }
            .try_into()
            .map_err(TableGenError::from)
            .map_err(|e| e.with_location(self))
    }

    record_value!(
        /// Returns the field with the given name converted to a [`Vec<bool>`]
        /// if this field is of type [`BitsInit`](crate::init::BitsInit).
        bits,
        Vec<bool>
    );
    record_value!(
        /// Returns the field with the given name converted to a [`String`]
        /// if this field is of type [`StringInit`](crate::init::StringInit).
        ///
        /// Note that this copies the string into a new string.
        code,
        String
    );
    record_value!(
        /// Returns the field with the given name converted to a [`&str`]
        /// if this field is of type [`StringInit`](crate::init::StringInit).
        code_str,
        &'a str
    );
    record_value!(
        /// Returns the field with the given name converted to a [`String`]
        /// if this field is of type [`StringInit`](crate::init::StringInit).
        ///
        /// Note that this copies the string into a new string.
        string,
        String
    );

    /// Returns a [`RecordValue`] for the field with the given name.
    pub fn value<'n>(self, name: &'n str) -> Result<RecordValue<'a>, Error> {
        let value = unsafe { tableGenRecordGetValue(self.raw, StringRef::from(name).to_raw()) };
        if !value.is_null() {
            Ok(unsafe { RecordValue::from_raw(value) })
        } else {
            Err(TableGenError::MissingValue(String::from(name)).with_location(self))
        }
    }

    /// Returns true if the record is anonymous.
    pub fn anonymous(self) -> bool {
        unsafe { tableGenRecordIsAnonymous(self.raw) > 0 }
    }

    /// Returns true if the record is a subclass of the class with the given
    /// name.
    pub fn subclass_of(self, class: &str) -> bool {
        unsafe { tableGenRecordIsSubclassOf(self.raw, StringRef::from(class).to_raw()) > 0 }
    }

    /// Returns an iterator over the fields of the record.
    ///
    /// The iterator yields [`RecordValue`] structs
    pub fn values(self) -> RecordValueIter<'a> {
        RecordValueIter::new(self)
    }

    /// Returns `true` if the record has a field with the given name.
    pub fn has_field(self, name: &str) -> bool {
        let v = unsafe { tableGenRecordGetValue(self.raw, StringRef::from(name).to_raw()) };
        !v.is_null()
    }

    /// Returns the [`TableGenRecTyKind`](crate::raw::TableGenRecTyKind) of the
    /// field with the given name, or `None` if the field does not exist.
    pub fn field_type(self, name: &str) -> Option<crate::raw::TableGenRecTyKind::Type> {
        use crate::raw::TableGenRecTyKind::TableGenInvalidRecTyKind;
        let kind = unsafe { tableGenRecordGetFieldType(self.raw, StringRef::from(name).to_raw()) };
        if kind == TableGenInvalidRecTyKind {
            None
        } else {
            Some(kind)
        }
    }

    /// Dumps the record to stderr (for debugging).
    pub fn dump(self) {
        unsafe { tableGenRecordDump(self.raw) }
    }

    /// Returns the number of template arguments.
    pub fn num_template_args(self) -> usize {
        unsafe { tableGenRecordGetNumTemplateArgs(self.raw) }
    }

    /// Returns the template argument name at the given index.
    pub fn template_arg_name(self, index: usize) -> Option<&'a str> {
        unsafe { StringRef::from_option_raw(tableGenRecordGetTemplateArgName(self.raw, index)) }
            .and_then(|s| s.try_into().ok())
    }

    /// Returns an iterator over the template argument names.
    pub fn template_args(self) -> TemplateArgIter<'a> {
        let back = self.num_template_args();
        TemplateArgIter {
            record: self,
            index: 0,
            back,
        }
    }

    /// Returns the number of direct super classes.
    pub fn num_super_classes(self) -> usize {
        unsafe { tableGenRecordGetNumSuperClasses(self.raw) }
    }

    /// Returns the super class at the given index.
    pub fn super_class(self, index: usize) -> Option<Record<'a>> {
        let ptr = unsafe { tableGenRecordGetSuperClass(self.raw, index) };
        if ptr.is_null() {
            None
        } else {
            Some(unsafe { Record::from_raw(ptr) })
        }
    }

    /// Returns an iterator over the direct super classes.
    pub fn direct_super_classes(self) -> SuperClassIter<'a> {
        let back = self.num_super_classes();
        SuperClassIter {
            record: self,
            index: 0,
            back,
        }
    }

    /// Returns the integer value of the field with the given name.
    pub fn int_value(self, name: &str) -> Result<i64, Error> {
        let mut out: i64 = 0;
        let ok = unsafe {
            tableGenRecordGetValueAsInt(self.raw, StringRef::from(name).to_raw(), &mut out)
        };
        if ok > 0 {
            Ok(out)
        } else {
            Err(TableGenError::MissingValue(name.into()).with_location(self))
        }
    }

    /// Returns the string value of the field with the given name as a `&str`.
    pub fn str_value(self, name: &str) -> Result<&'a str, Error> {
        let raw =
            unsafe { tableGenRecordGetValueAsString(self.raw, StringRef::from(name).to_raw()) };
        if raw.data.is_null() {
            Err(TableGenError::MissingValue(name.into()).with_location(self))
        } else {
            unsafe { StringRef::from_raw(raw) }
                .try_into()
                .map_err(TableGenError::from)
                .map_err(|e| e.with_location(self))
        }
    }

    /// Returns the bit (boolean) value of the field with the given name.
    pub fn bit_value(self, name: &str) -> Result<bool, Error> {
        let mut out: i8 = 0;
        let ok = unsafe {
            tableGenRecordGetValueAsBit(self.raw, StringRef::from(name).to_raw(), &mut out)
        };
        if ok > 0 {
            Ok(out != 0)
        } else {
            Err(TableGenError::MissingValue(name.into()).with_location(self))
        }
    }

    /// Returns the def value of the field with the given name as a [`Record`].
    pub fn def_value(self, name: &str) -> Result<Record<'a>, Error> {
        let ptr = unsafe { tableGenRecordGetValueAsDef(self.raw, StringRef::from(name).to_raw()) };
        if ptr.is_null() {
            Err(TableGenError::MissingValue(name.into()).with_location(self))
        } else {
            Ok(unsafe { Record::from_raw(ptr) })
        }
    }

    /// Returns the dag value of the field with the given name.
    pub fn dag_value(self, name: &str) -> Result<DagInit<'a>, Error> {
        let ptr = unsafe { tableGenRecordGetValueAsDag(self.raw, StringRef::from(name).to_raw()) };
        if ptr.is_null() {
            Err(TableGenError::MissingValue(name.into()).with_location(self))
        } else {
            Ok(unsafe { DagInit::from_raw(ptr) })
        }
    }

    /// Returns the bits init of the field with the given name.
    pub fn bits_init_value(self, name: &str) -> Result<BitsInit<'a>, Error> {
        let ptr =
            unsafe { tableGenRecordGetValueAsBitsInit(self.raw, StringRef::from(name).to_raw()) };
        if ptr.is_null() {
            Err(TableGenError::MissingValue(name.into()).with_location(self))
        } else {
            Ok(unsafe { BitsInit::from_raw(ptr) })
        }
    }

    /// Returns the list init of the field with the given name.
    pub fn list_init_value(self, name: &str) -> Result<ListInit<'a>, Error> {
        let ptr =
            unsafe { tableGenRecordGetValueAsListInit(self.raw, StringRef::from(name).to_raw()) };
        if ptr.is_null() {
            Err(TableGenError::MissingValue(name.into()).with_location(self))
        } else {
            Ok(unsafe { ListInit::from_raw(ptr) })
        }
    }

    /// Returns the list-of-defs value of the field with the given name.
    pub fn list_of_defs_value(self, name: &str) -> Result<Vec<Record<'a>>, Error> {
        let ptr =
            unsafe { tableGenRecordGetValueAsListOfDefs(self.raw, StringRef::from(name).to_raw()) };
        if ptr.is_null() {
            return Err(TableGenError::MissingValue(name.into()).with_location(self));
        }
        let len = unsafe { crate::raw::tableGenRecordVectorSize(ptr) };
        let mut result = Vec::with_capacity(len);
        for i in 0..len {
            let rec = unsafe { crate::raw::tableGenRecordVectorGet(ptr, i) };
            result.push(unsafe { Record::from_raw(rec) });
        }
        unsafe { crate::raw::tableGenRecordVectorFree(ptr) };
        Ok(result)
    }

    /// Returns the list-of-ints value of the field with the given name.
    pub fn list_of_ints_value(self, name: &str) -> Result<Vec<i64>, Error> {
        let mut arr = std::ptr::null_mut();
        let mut len: usize = 0;
        let ok = unsafe {
            tableGenRecordGetValueAsListOfInts(
                self.raw,
                StringRef::from(name).to_raw(),
                &mut arr,
                &mut len,
            )
        };
        if ok == 0 {
            return Err(TableGenError::MissingValue(name.into()).with_location(self));
        }
        let result = unsafe { std::slice::from_raw_parts(arr, len) }.to_vec();
        unsafe { tableGenIntArrayFree(arr) };
        Ok(result)
    }

    /// Returns the list-of-strings value of the field with the given name.
    pub fn list_of_strings_value(self, name: &str) -> Result<Vec<&'a str>, Error> {
        let mut arr = std::ptr::null_mut();
        let mut len: usize = 0;
        let ok = unsafe {
            tableGenRecordGetValueAsListOfStrings(
                self.raw,
                StringRef::from(name).to_raw(),
                &mut arr,
                &mut len,
            )
        };
        if ok == 0 {
            return Err(TableGenError::MissingValue(name.into()).with_location(self));
        }
        let raw_refs = unsafe { std::slice::from_raw_parts(arr, len) };
        let mut result = Vec::with_capacity(len);
        for raw_ref in raw_refs {
            let s: &'a str = unsafe { StringRef::from_raw(*raw_ref) }
                .try_into()
                .map_err(TableGenError::from)
                .map_err(|e| e.with_location(self))?;
            result.push(s);
        }
        unsafe { tableGenStringRefArrayFree(arr) };
        Ok(result)
    }

    /// Returns the optional string value of the field, or `None` if unset.
    ///
    /// Returns `Err` if the field does not exist or is not a string/unset.
    pub fn optional_str_value(self, name: &str) -> Result<Option<&'a str>, Error> {
        let mut out = crate::raw::TableGenStringRef {
            data: std::ptr::null(),
            len: 0,
        };
        let ok = unsafe {
            tableGenRecordGetValueAsOptionalString(
                self.raw,
                StringRef::from(name).to_raw(),
                &mut out,
            )
        };
        if ok == 0 {
            return Err(TableGenError::MissingValue(name.into()).with_location(self));
        }
        if out.data.is_null() {
            Ok(None)
        } else {
            let s: &'a str = unsafe { StringRef::from_raw(out) }
                .try_into()
                .map_err(TableGenError::from)
                .map_err(|e| e.with_location(self))?;
            Ok(Some(s))
        }
    }

    /// Returns the optional def value of the field, or `None` if unset.
    pub fn optional_def_value(self, name: &str) -> Option<Record<'a>> {
        let ptr = unsafe {
            tableGenRecordGetValueAsOptionalDef(self.raw, StringRef::from(name).to_raw())
        };
        if ptr.is_null() {
            None
        } else {
            Some(unsafe { Record::from_raw(ptr) })
        }
    }

    /// Returns true if the named field exists and has an unset value (`?`).
    pub fn is_value_unset(self, name: &str) -> bool {
        unsafe { tableGenRecordIsValueUnset(self.raw, StringRef::from(name).to_raw()) > 0 }
    }

    /// Returns true if this record is a class definition (not a def).
    pub fn is_class(self) -> bool {
        unsafe { tableGenRecordIsClass(self.raw) > 0 }
    }

    /// Returns the [`DefInit`] for this record.
    pub fn def_init(self) -> DefInit<'a> {
        unsafe { DefInit::from_raw(tableGenRecordGetDefInit(self.raw)) }
    }

    /// Returns the unique numeric ID of this record.
    pub fn id(self) -> u32 {
        unsafe { tableGenRecordGetID(self.raw) }
    }

    /// Returns the name as a raw [`TypedInit`].
    pub fn name_init(self) -> TypedInit<'a> {
        unsafe { TypedInit::from_raw(tableGenRecordGetNameInit(self.raw)) }
    }

    /// Returns true if the given record is a direct superclass of this record.
    pub fn has_direct_super_class(self, super_class: Record<'a>) -> bool {
        unsafe { tableGenRecordHasDirectSuperClass(self.raw, super_class.raw) > 0 }
    }

    /// Returns the number of classes in this record's type.
    pub fn num_type_classes(self) -> usize {
        unsafe { tableGenRecordRecTyGetNumClasses(self.raw) }
    }

    /// Returns the class at the given index in this record's type.
    pub fn type_class(self, index: usize) -> Option<Record<'a>> {
        let ptr = unsafe { tableGenRecordRecTyGetClass(self.raw, index) };
        if ptr.is_null() {
            None
        } else {
            Some(unsafe { Record::from_raw(ptr) })
        }
    }

    /// Returns true if this record's type is a subclass of the given class.
    pub fn type_is_subclass_of(self, class: Record<'a>) -> bool {
        unsafe { tableGenRecordRecTyIsSubClassOf(self.raw, class.raw) > 0 }
    }
}

impl SourceLoc for Record<'_> {
    fn source_location(self) -> SourceLocation {
        unsafe { SourceLocation::from_raw(tableGenRecordGetLoc(self.raw)) }
    }
}

macro_rules! try_into {
    ($type:ty) => {
        impl<'a> TryFrom<RecordValue<'a>> for $type {
            type Error = Error;

            fn try_from(record_value: RecordValue<'a>) -> Result<Self, Self::Error> {
                Self::try_from(record_value.init).map_err(|e| e.set_location(record_value))
            }
        }
    };
}

try_into!(bool);
try_into!(Vec<bool>);
try_into!(Vec<BitInit<'a>>);
try_into!(i64);
try_into!(ListInit<'a>);
try_into!(DagInit<'a>);
try_into!(Record<'a>);
try_into!(String);
try_into!(&'a str);

impl<'a> From<RecordValue<'a>> for TypedInit<'a> {
    fn from(value: RecordValue<'a>) -> Self {
        value.init
    }
}

/// Struct that represents a field of a [`Record`].
///
/// Can be converted into a Rust type using the [`TryInto`] trait.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct RecordValue<'a> {
    raw: TableGenRecordValRef,
    pub name: StringInit<'a>,
    pub init: TypedInit<'a>,
    _reference: PhantomData<&'a TableGenRecordRef>,
}

impl Display for RecordValue<'_> {
    fn fmt(&self, formatter: &mut Formatter) -> fmt::Result {
        let mut data = (formatter, Ok(()));

        unsafe {
            tableGenRecordValPrint(
                self.raw,
                Some(print_callback),
                &mut data as *mut _ as *mut c_void,
            );
        }

        data.1
    }
}

impl std::hash::Hash for RecordValue<'_> {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        self.raw.hash(state);
    }
}

impl RecordValue<'_> {
    /// Creates a record from a raw object.
    ///
    /// # Safety
    ///
    /// The raw object must be valid.
    pub unsafe fn from_raw(ptr: TableGenRecordValRef) -> Self {
        let name = unsafe { StringInit::from_raw(tableGenRecordValGetNameInit(ptr)) };
        let value = unsafe { TypedInit::from_raw(tableGenRecordValGetValue(ptr)) };
        Self {
            name,
            init: value,
            raw: ptr,
            _reference: PhantomData,
        }
    }

    /// Dumps this record value to stderr (for debugging).
    pub fn dump(self) {
        unsafe { tableGenRecordValDump(self.raw) }
    }

    /// Returns true if this field is a template argument.
    pub fn is_template_arg(self) -> bool {
        unsafe { tableGenRecordValIsTemplateArg(self.raw) > 0 }
    }

    /// Returns true if nonconcrete values are allowed for this field.
    pub fn is_nonconcrete_ok(self) -> bool {
        unsafe { tableGenRecordValIsNonconcreteOK(self.raw) > 0 }
    }

    /// If this field is bits-typed, returns the bit width.
    pub fn bits_width(self) -> Option<usize> {
        let w = unsafe { tableGenRecordValGetBitsWidth(self.raw) };
        if w == 0 { None } else { Some(w) }
    }

    /// If this field is list-typed, returns the element type kind.
    pub fn list_element_type(self) -> Option<crate::raw::TableGenRecTyKind::Type> {
        let k = unsafe { tableGenRecordValGetListElementType(self.raw) };
        if k == RawInvalidRecTyKind {
            None
        } else {
            Some(k)
        }
    }
}

impl SourceLoc for RecordValue<'_> {
    fn source_location(self) -> SourceLocation {
        unsafe { SourceLocation::from_raw(tableGenRecordValGetLoc(self.raw)) }
    }
}

/// Iterator over the fields of a [`Record`].
#[derive(Debug, Clone)]
pub struct RecordValueIter<'a> {
    record: TableGenRecordRef,
    current: TableGenRecordValRef,
    _reference: PhantomData<&'a TableGenRecordRef>,
}

impl<'a> RecordValueIter<'a> {
    fn new(record: Record<'a>) -> RecordValueIter<'a> {
        unsafe {
            RecordValueIter {
                record: record.raw,
                current: tableGenRecordGetFirstValue(record.raw),
                _reference: PhantomData,
            }
        }
    }
}

impl<'a> Iterator for RecordValueIter<'a> {
    type Item = RecordValue<'a>;

    fn next(&mut self) -> Option<RecordValue<'a>> {
        if self.current.is_null() {
            return None;
        }
        let res = unsafe { RecordValue::from_raw(self.current) };
        self.current = unsafe { tableGenRecordValNext(self.record, self.current) };
        Some(res)
    }
}

impl std::iter::FusedIterator for RecordValueIter<'_> {}

/// Iterator over the template argument names of a [`Record`].
#[derive(Debug, Clone)]
pub struct TemplateArgIter<'a> {
    record: Record<'a>,
    index: usize,
    back: usize,
}

impl<'a> Iterator for TemplateArgIter<'a> {
    type Item = &'a str;

    fn next(&mut self) -> Option<Self::Item> {
        if self.index >= self.back {
            return None;
        }
        let name = self.record.template_arg_name(self.index);
        self.index += 1;
        name
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        let remaining = self.back.saturating_sub(self.index);
        (remaining, Some(remaining))
    }
}

impl<'a> DoubleEndedIterator for TemplateArgIter<'a> {
    fn next_back(&mut self) -> Option<Self::Item> {
        if self.index >= self.back {
            return None;
        }
        self.back -= 1;
        match self.record.template_arg_name(self.back) {
            Some(name) => Some(name),
            None => {
                self.back += 1;
                None
            }
        }
    }
}

impl ExactSizeIterator for TemplateArgIter<'_> {}

impl std::iter::FusedIterator for TemplateArgIter<'_> {}

/// Iterator over the direct super classes of a [`Record`].
#[derive(Debug, Clone)]
pub struct SuperClassIter<'a> {
    record: Record<'a>,
    index: usize,
    back: usize,
}

impl<'a> Iterator for SuperClassIter<'a> {
    type Item = Record<'a>;

    fn next(&mut self) -> Option<Self::Item> {
        if self.index >= self.back {
            return None;
        }
        let class = self.record.super_class(self.index);
        self.index += 1;
        class
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        let remaining = self.back.saturating_sub(self.index);
        (remaining, Some(remaining))
    }
}

impl<'a> DoubleEndedIterator for SuperClassIter<'a> {
    fn next_back(&mut self) -> Option<Self::Item> {
        if self.index >= self.back {
            return None;
        }
        self.back -= 1;
        match self.record.super_class(self.back) {
            Some(class) => Some(class),
            None => {
                self.back += 1;
                None
            }
        }
    }
}

impl ExactSizeIterator for SuperClassIter<'_> {}

impl std::iter::FusedIterator for SuperClassIter<'_> {}

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

    #[test]
    fn record() {
        let rk = TableGenParser::new()
            .add_source(
                r#"
                class A;
                class B;
                class C;

                def D1: A;
                def D2: A, B;
                def : B, C;
                "#,
            )
            .unwrap()
            .parse()
            .expect("valid tablegen");
        let d2 = rk.def("D2").expect("D2 exists");
        assert!(d2.subclass_of("A"));
        assert!(d2.subclass_of("B"));
        assert!(!d2.subclass_of("C"));
        assert!(!d2.subclass_of("D"));
        let anon = rk
            .defs()
            .map(|(_name, def)| def)
            .find(|d| d.anonymous())
            .expect("anonymous class exists");
        assert!(!anon.subclass_of("A"));
        assert!(anon.subclass_of("B"));
        assert!(anon.subclass_of("C"));
    }

    #[test]
    fn single_value() {
        let rk = TableGenParser::new()
            .add_source(
                r#"
                def A {
                    int size = 42;
                }
                "#,
            )
            .unwrap()
            .parse()
            .expect("valid tablegen");
        let a = rk.def("A").expect("def A exists");
        assert_eq!(a.name(), Ok("A"));
        assert_eq!(a.int_value("size"), Ok(42));
        assert_eq!(
            a.value("size")
                .and_then(|v| {
                    assert!(v.name.to_str() == Ok("size"));
                    v.init.as_int().map_err(|e| e.set_location(v))
                })
                .and_then(|i| {
                    i64::try_from(i)
                        .map_err(|e| e.with_location(crate::error::SourceLocation::none()))
                }),
            Ok(42)
        );
    }

    #[test]
    fn values() {
        let rk = TableGenParser::new()
            .add_source(
                r#"
                def A {
                    int a = 5;
                    string n = "hello";
                }
                "#,
            )
            .unwrap()
            .parse()
            .expect("valid tablegen");
        let a = rk.def("A").expect("def A exists");
        let values = a.values();
        assert_eq!(values.clone().count(), 2);
        for v in values {
            match v.init {
                TypedInit::Int(i) => {
                    assert_eq!(v.name.to_str(), Ok("a"));
                    assert_eq!(i64::try_from(i).unwrap(), 5);
                }
                TypedInit::String(i) => {
                    assert_eq!(v.name.to_str(), Ok("n"));
                    assert_eq!(i.to_str(), Ok("hello"));
                }
                _ => panic!("unexpected type"),
            }
        }
    }

    #[test]
    fn empty_record_values() {
        let rk = TableGenParser::new()
            .add_source("def Empty;")
            .unwrap()
            .parse()
            .expect("valid tablegen");
        let r = rk.def("Empty").expect("def Empty exists");
        assert_eq!(r.values().count(), 0);
        // Calling next() on an already-exhausted iterator must not invoke UB.
        let mut iter = r.values();
        assert!(iter.next().is_none());
        assert!(iter.next().is_none());
    }

    #[test]
    fn print_error() {
        let rk = TableGenParser::new()
            .add_source(
                r#"
                class C<int test> {
                    int a = test;
                }
                def A : C<4>;
                "#,
            )
            .unwrap()
            .parse()
            .expect("valid tablegen");
        let a = rk.def("A").expect("def A exists");
        if let Err(e) = a.string_value("a") {
            // With source info
            let msg = format!("{}", e.clone().add_source_info(rk.source_info()));
            let msg = msg.trim();
            // LLVM 22+ changed PrintMessage formatting for in-memory buffers.
            #[cfg(any(
                feature = "llvm16-0",
                feature = "llvm17-0",
                feature = "llvm18-0",
                feature = "llvm19-0",
                feature = "llvm20-0",
                feature = "llvm21-0"
            ))]
            assert_eq!(
                msg,
                r#"
                  error: invalid conversion from Int to alloc::string::String
                    int a = test;
                        ^
                "#
                .trim()
            );
            #[cfg(feature = "llvm22-0")]
            assert!(
                msg.contains("error: invalid conversion from Int to alloc::string::String"),
                "unexpected error message: {msg}"
            );

            // Without source info
            drop(rk);
            assert_eq!(
                format!("{}", e).trim(),
                r#"
                  invalid conversion from Int to alloc::string::String
                "#
                .trim()
            );

            // With incorrect source info
            let rk = TableGenParser::new()
                .add_source("def A;")
                .unwrap()
                .parse()
                .expect("valid tablegen");
            assert_eq!(
                format!("{}", e.add_source_info(rk.source_info())).trim(),
                "invalid conversion from Int to alloc::string::String\nfailed to print source information: invalid source location"
                .trim()
            );
        } else {
            panic!("expected error")
        }
    }

    #[test]
    fn has_field() {
        let rk = TableGenParser::new()
            .add_source("def A { int x = 1; }")
            .unwrap()
            .parse()
            .expect("valid tablegen");
        let a = rk.def("A").expect("def A exists");
        assert!(a.has_field("x"));
        assert!(!a.has_field("y"));
    }

    #[test]
    fn field_type() {
        use crate::raw::TableGenRecTyKind::{
            TableGenBitRecTyKind, TableGenIntRecTyKind, TableGenStringRecTyKind,
        };
        let rk = TableGenParser::new()
            .add_source("def A { int i = 1; string s = \"hi\"; bit b = 1; }")
            .unwrap()
            .parse()
            .expect("valid tablegen");
        let a = rk.def("A").expect("def A exists");
        assert_eq!(a.field_type("i"), Some(TableGenIntRecTyKind));
        assert_eq!(a.field_type("s"), Some(TableGenStringRecTyKind));
        assert_eq!(a.field_type("b"), Some(TableGenBitRecTyKind));
        assert_eq!(a.field_type("nonexistent"), None);
    }

    #[test]
    fn template_args() {
        let rk = TableGenParser::new()
            .add_source("class Foo<int x, string y>;")
            .unwrap()
            .parse()
            .expect("valid tablegen");
        let foo = rk.class("Foo").expect("class Foo exists");
        assert_eq!(foo.num_template_args(), 2);
        assert_eq!(foo.template_arg_name(0), Some("Foo:x"));
        assert_eq!(foo.template_arg_name(1), Some("Foo:y"));
        assert_eq!(foo.template_arg_name(2), None);
        let names: Vec<_> = foo.template_args().collect();
        assert_eq!(names, vec!["Foo:x", "Foo:y"]);
        // Double-ended
        let mut iter = foo.template_args();
        assert_eq!(iter.next_back(), Some("Foo:y"));
        assert_eq!(iter.next(), Some("Foo:x"));
        assert!(iter.next().is_none());
    }

    #[test]
    fn template_args_on_def() {
        let rk = TableGenParser::new()
            .add_source("class A; def D: A;")
            .unwrap()
            .parse()
            .expect("valid tablegen");
        let d = rk.def("D").expect("def D exists");
        assert_eq!(d.num_template_args(), 0);
        assert_eq!(d.template_arg_name(0), None);
        assert_eq!(d.template_args().count(), 0);
    }

    #[test]
    fn template_args_no_params() {
        let rk = TableGenParser::new()
            .add_source("class Foo;")
            .unwrap()
            .parse()
            .expect("valid tablegen");
        let foo = rk.class("Foo").expect("class Foo exists");
        assert_eq!(foo.num_template_args(), 0);
        assert_eq!(foo.template_args().count(), 0);
        let mut iter = foo.template_args();
        assert!(iter.next().is_none());
        assert!(iter.next_back().is_none());
    }

    #[test]
    fn template_args_len_tracks() {
        let rk = TableGenParser::new()
            .add_source("class Foo<int a, int b, int c>;")
            .unwrap()
            .parse()
            .expect("valid tablegen");
        let foo = rk.class("Foo").expect("class Foo exists");
        let mut iter = foo.template_args();
        assert_eq!(iter.len(), 3);
        iter.next();
        assert_eq!(iter.len(), 2);
        iter.next_back();
        assert_eq!(iter.len(), 1);
        iter.next();
        assert_eq!(iter.len(), 0);
        assert!(iter.next().is_none());
        assert!(iter.next_back().is_none());
    }

    #[test]
    fn super_classes() {
        let rk = TableGenParser::new()
            .add_source(
                r#"
                class A;
                class B;
                class C;
                def D: A, B, C;
                "#,
            )
            .unwrap()
            .parse()
            .expect("valid tablegen");
        let d = rk.def("D").expect("def D exists");
        assert_eq!(d.num_super_classes(), 3);
        assert_eq!(d.super_class(0).unwrap().name().unwrap(), "A");
        assert_eq!(d.super_class(1).unwrap().name().unwrap(), "B");
        assert_eq!(d.super_class(2).unwrap().name().unwrap(), "C");
        assert!(d.super_class(3).is_none());
        let names: Vec<_> = d
            .direct_super_classes()
            .map(|r| r.name().unwrap().to_string())
            .collect();
        assert_eq!(names, vec!["A", "B", "C"]);
        // Double-ended
        let mut iter = d.direct_super_classes();
        assert_eq!(iter.next_back().unwrap().name().unwrap(), "C");
        assert_eq!(iter.next().unwrap().name().unwrap(), "A");
        assert_eq!(iter.next().unwrap().name().unwrap(), "B");
        assert!(iter.next().is_none());
    }

    #[test]
    fn super_classes_on_class() {
        let rk = TableGenParser::new()
            .add_source("class A; class B: A; class C: A, B;")
            .unwrap()
            .parse()
            .expect("valid tablegen");
        let b = rk.class("B").expect("class B exists");
        assert_eq!(b.num_super_classes(), 1);
        assert_eq!(b.super_class(0).unwrap().name().unwrap(), "A");
        let c = rk.class("C").expect("class C exists");
        assert_eq!(c.num_super_classes(), 2);
        let names: Vec<_> = c
            .direct_super_classes()
            .map(|r| r.name().unwrap().to_string())
            .collect();
        assert_eq!(names, vec!["A", "B"]);
    }

    #[test]
    fn super_classes_empty() {
        let rk = TableGenParser::new()
            .add_source("def D;")
            .unwrap()
            .parse()
            .expect("valid tablegen");
        let d = rk.def("D").expect("def D exists");
        assert_eq!(d.num_super_classes(), 0);
        assert!(d.super_class(0).is_none());
        assert_eq!(d.direct_super_classes().count(), 0);
        let mut iter = d.direct_super_classes();
        assert!(iter.next().is_none());
        assert!(iter.next_back().is_none());
    }

    #[test]
    fn super_classes_len_tracks() {
        let rk = TableGenParser::new()
            .add_source("class A; class B; class C; def D: A, B, C;")
            .unwrap()
            .parse()
            .expect("valid tablegen");
        let d = rk.def("D").expect("def D exists");
        let mut iter = d.direct_super_classes();
        assert_eq!(iter.len(), 3);
        iter.next();
        assert_eq!(iter.len(), 2);
        iter.next_back();
        assert_eq!(iter.len(), 1);
        iter.next();
        assert_eq!(iter.len(), 0);
        assert!(iter.next().is_none());
        assert!(iter.next_back().is_none());
    }
}