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
// Copyright (c) 2016-2020 Fabian Schuiki

//! An implementation of the verilog type system.

use crate::{crate_prelude::*, hir::HirNode, ParamEnv};
use std::fmt::{self, Display, Formatter};

/// A verilog type.
pub type Type<'t> = &'t TypeKind<'t>;

/// Type data.
#[derive(Debug, PartialEq, Eq, Hash)]
pub enum TypeKind<'t> {
    /// An error occurred during type computation.
    Error,
    /// The `void` type.
    Void,
    /// The `time` type.
    Time,
    /// A single bit type.
    Bit(Domain),
    /// An integer type.
    Int(usize, Domain),
    /// A named type.
    ///
    /// The first field represents how the type was originally named by the
    /// user. The second field represents the binding of the resolved name. The
    /// third field represents the actual type.
    Named(Spanned<Name>, NodeId, Type<'t>),
    /// A struct type.
    Struct(NodeId),
    /// A packed array type.
    PackedArray(usize, Type<'t>),
    /// A single bit type.
    BitScalar { domain: Domain, sign: Sign },
    /// A simple bit vector type (SBVT).
    ///
    /// The innermost dimension of a multi-dimensional bit vector type is always
    /// represented as a SBVT.
    BitVector {
        domain: Domain,
        sign: Sign,
        range: Range,
        dubbed: bool,
    },
}

/// The number of values each bit of a type can assume.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Domain {
    /// Two-valued types such as `bit` or `int`.
    TwoValued,
    /// Four-valued types such as `logic` or `integer`.
    FourValued,
}

/// Whether a type is signed or unsigned.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[allow(missing_docs)]
pub enum Sign {
    Signed,
    Unsigned,
}

/// The `[a:b]` part in a vector/array type such as `logic [a:b]`.
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub struct Range {
    /// The total number of bits, given as `|a-b|+1`.
    pub size: usize,
    /// The direction of the vector, i.e. whether `a > b` or `a < b`.
    pub dir: RangeDir,
    /// The starting offset of the range.
    pub offset: isize,
}

/// Which side is greater in a range `[a:b]`.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum RangeDir {
    /// `a < b`
    Up,
    /// `a > b`
    Down,
}

impl std::fmt::Debug for Range {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "{}", self)
    }
}

impl<'t> TypeKind<'t> {
    /// Check if this is the error type.
    pub fn is_error(&self) -> bool {
        match *self.resolve_name() {
            TypeKind::Error => true,
            _ => false,
        }
    }

    /// Check if this is the void type.
    pub fn is_void(&self) -> bool {
        match *self.resolve_name() {
            TypeKind::Void => true,
            _ => false,
        }
    }

    /// Check if this is a struct type.
    pub fn is_struct(&self) -> bool {
        match *self.resolve_name() {
            TypeKind::Struct(..) => true,
            _ => false,
        }
    }

    /// Check if this is an array type.
    pub fn is_array(&self) -> bool {
        match *self.resolve_name() {
            TypeKind::PackedArray(..) => true,
            _ => false,
        }
    }

    /// Get the definition of a struct.
    pub fn get_struct_def(&self) -> Option<NodeId> {
        match *self.resolve_name() {
            TypeKind::Struct(id) => Some(id),
            _ => None,
        }
    }

    /// Get the element type of an array.
    pub fn get_array_element(&self) -> Option<Type<'t>> {
        match *self.resolve_name() {
            TypeKind::PackedArray(_, e) => Some(e),
            _ => None,
        }
    }

    /// Get the length of an array.
    pub fn get_array_length(&self) -> Option<usize> {
        match *self.resolve_name() {
            TypeKind::PackedArray(l, _) => Some(l),
            _ => None,
        }
    }

    /// Get the width of the type.
    ///
    /// Panics if the type is not an integer.
    pub fn width(&self) -> usize {
        match *self.resolve_name() {
            TypeKind::Bit(_) => 1,
            TypeKind::Int(w, _) => w,
            TypeKind::BitScalar { .. } => 1,
            TypeKind::BitVector { range, .. } => range.size,
            _ => panic!("{:?} has no width", self),
        }
    }

    /// Check if this is a bit vector type.
    pub fn is_bit_vector(&self) -> bool {
        match *self.resolve_name() {
            TypeKind::BitVector { .. } => true,
            _ => false,
        }
    }

    /// Check if this is a bit scalar type.
    pub fn is_bit_scalar(&self) -> bool {
        match *self.resolve_name() {
            TypeKind::BitScalar { .. } => true,
            _ => false,
        }
    }

    /// Check if this type uses a predefined type alias as name.
    pub fn is_dubbed(&self) -> bool {
        match *self.resolve_name() {
            TypeKind::BitScalar { .. } => true,
            TypeKind::BitVector { dubbed, .. } => dubbed,
            _ => false,
        }
    }

    /// Check if this type is a valid boolean.
    pub fn is_bool(&self) -> bool {
        ty::identical(self, &ty::BIT_TYPE) || ty::identical(self, &ty::LOGIC_TYPE)
    }

    /// Remove all typedefs and reveal the concrete fundamental type.
    pub fn resolve_name(&self) -> &Self {
        match self {
            TypeKind::Named(_, _, ty) => ty.resolve_name(),
            _ => self,
        }
    }

    /// Return the domain of the type, if it has one.
    pub fn get_value_domain(&self) -> Option<Domain> {
        match *self.resolve_name() {
            TypeKind::Bit(d) => Some(d),
            TypeKind::Int(_, d) => Some(d),
            TypeKind::BitScalar { domain, .. } => Some(domain),
            TypeKind::BitVector { domain, .. } => Some(domain),
            TypeKind::PackedArray(_, ty) => ty.get_value_domain(),
            _ => None,
        }
    }

    /// Return the sign of the type, if it has one.
    pub fn get_sign(&self) -> Option<Sign> {
        match *self.resolve_name() {
            TypeKind::Bit(..) => Some(Sign::Unsigned),
            TypeKind::Int(..) => Some(Sign::Unsigned),
            TypeKind::BitScalar { sign, .. } => Some(sign),
            TypeKind::BitVector { sign, .. } => Some(sign),
            TypeKind::PackedArray(_, ty) => ty.get_sign(),
            _ => None,
        }
    }

    /// Return the range of the type, if it has one.
    pub fn get_range(&self) -> Option<Range> {
        match self.resolve_name() {
            TypeKind::Bit(..) => Some(Range {
                size: 1,
                dir: RangeDir::Down,
                offset: 0isize,
            }),
            TypeKind::Int(..) => Some(Range {
                size: 32,
                dir: RangeDir::Down,
                offset: 0isize,
            }),
            TypeKind::BitScalar { .. } => Some(Range {
                size: 1,
                dir: RangeDir::Down,
                offset: 0isize,
            }),
            TypeKind::BitVector { range, .. } => Some(*range),
            _ => None,
        }
    }

    /// Check whether the type is unsigned.
    ///
    /// Returns false for types which have no sign.
    pub fn is_unsigned(&self) -> bool {
        self.get_sign() == Some(Sign::Unsigned)
    }

    /// Check whether the type is signed.
    ///
    /// Returns false for types which have no sign.
    pub fn is_signed(&self) -> bool {
        self.get_sign() == Some(Sign::Signed)
    }

    /// Change the value domain of a type.
    pub fn change_value_domain<'gcx>(
        &'gcx self,
        cx: &impl Context<'gcx>,
        domain: Domain,
    ) -> Type<'gcx> {
        if self.get_value_domain() == Some(domain) {
            return self;
        }
        match *self.resolve_name() {
            TypeKind::Bit(_) => cx.intern_type(TypeKind::BitScalar {
                domain,
                sign: Sign::Unsigned,
            }),
            TypeKind::Int(size, _) => cx.intern_type(TypeKind::BitVector {
                domain,
                sign: Sign::Signed,
                range: Range {
                    size,
                    dir: RangeDir::Down,
                    offset: 0isize,
                },
                dubbed: true,
            }),
            TypeKind::BitScalar { sign, .. } => {
                cx.intern_type(TypeKind::BitScalar { domain, sign })
            }
            TypeKind::BitVector {
                sign,
                range,
                dubbed,
                ..
            } => cx.intern_type(TypeKind::BitVector {
                domain,
                sign,
                range,
                dubbed,
            }),
            _ => self,
        }
    }

    /// Change the sign of a simple bit type.
    pub fn change_sign<'gcx>(&'gcx self, cx: &impl Context<'gcx>, sign: Sign) -> Type<'gcx> {
        if self.get_sign() == Some(sign) {
            return self;
        }
        match *self.resolve_name() {
            TypeKind::BitScalar { domain, .. } => {
                cx.intern_type(TypeKind::BitScalar { domain, sign })
            }
            TypeKind::BitVector {
                domain,
                range,
                dubbed,
                ..
            } => cx.intern_type(TypeKind::BitVector {
                domain,
                sign,
                range,
                dubbed,
            }),
            _ => self,
        }
    }

    /// Change the range of a simple bit type.
    pub fn change_range<'gcx>(&'gcx self, cx: &impl Context<'gcx>, range: Range) -> Type<'gcx> {
        if self.get_range() == Some(range) {
            return self;
        }
        match *self.resolve_name() {
            TypeKind::Bit(domain) => cx.intern_type(TypeKind::BitVector {
                domain,
                sign: Sign::Unsigned,
                range,
                dubbed: false,
            }),
            TypeKind::Int(_, domain) => cx.intern_type(TypeKind::BitVector {
                domain,
                sign: Sign::Signed,
                range,
                dubbed: false,
            }),
            TypeKind::BitScalar { domain, sign } => cx.intern_type(TypeKind::BitVector {
                domain,
                sign,
                range,
                dubbed: false,
            }),
            TypeKind::BitVector {
                domain,
                sign,
                dubbed,
                ..
            } => cx.intern_type(TypeKind::BitVector {
                domain,
                sign,
                range,
                dubbed,
            }),
            _ => self,
        }
    }

    /// Check if this type has a simple bit vector equivalent.
    pub fn has_simple_bit_vector(&self) -> bool {
        match self.resolve_name() {
            TypeKind::Error | TypeKind::Void | TypeKind::Time => false,
            TypeKind::BitVector { .. } | TypeKind::BitScalar { .. } => true,
            TypeKind::Bit(..)
            | TypeKind::Int(..)
            | TypeKind::Struct(..)
            | TypeKind::PackedArray(..) => true,
            TypeKind::Named(..) => unreachable!("handled by resolve_name()"),
        }
    }

    /// Check if this type is a simple bit vector type.
    pub fn is_simple_bit_vector(&self) -> bool {
        match self.resolve_name() {
            TypeKind::Error | TypeKind::Void | TypeKind::Time => false,
            TypeKind::BitVector { .. } | TypeKind::BitScalar { .. } => true,
            TypeKind::Bit(..) => true,
            TypeKind::Int(..) => true,
            TypeKind::Struct(..) | TypeKind::PackedArray(..) => false,
            TypeKind::Named(..) => unreachable!("handled by resolve_name()"),
        }
    }

    /// Try to convert to an equivalent simple bit vector type.
    ///
    /// All *integral* data types have an equivalent *simple bit vector type*.
    /// These include the following:
    ///
    /// - all basic integers
    /// - packed arrays
    /// - packed structures
    /// - packed unions
    /// - enums
    /// - time (excluded in this implementation)
    ///
    /// If `force_vector` is `true`, the returned type has range `[0:0]` if it
    /// would otherwise be a single bit.
    pub fn get_simple_bit_vector<'gcx>(
        &'gcx self,
        cx: &impl Context<'gcx>,
        env: ParamEnv,
        force_vector: bool,
    ) -> Option<Type<'gcx>> {
        let bits = match *self.resolve_name() {
            TypeKind::Error | TypeKind::Void | TypeKind::Time => return None,
            TypeKind::BitVector { .. } => return Some(self),
            TypeKind::BitScalar { .. } if force_vector => 1,
            TypeKind::BitScalar { .. } => return Some(self),
            TypeKind::Bit(..)
            | TypeKind::Int(..)
            | TypeKind::Struct(..)
            | TypeKind::PackedArray(..) => bit_size_of_type(cx, self, env).ok()?,
            TypeKind::Named(..) => unreachable!("handled by resolve_name()"),
        };
        Some(cx.intern_type(TypeKind::BitVector {
            domain: ty::Domain::FourValued, // TODO(fschuiki): check if this is correct
            sign: ty::Sign::Unsigned,
            range: ty::Range {
                size: bits,
                dir: ty::RangeDir::Down,
                offset: 0isize,
            },
            dubbed: false,
        }))
    }

    /// Compute the size of the type in bits.
    pub fn try_bit_size<'gcx>(&'gcx self, cx: &impl Context<'gcx>, env: ParamEnv) -> Result<usize> {
        match *self {
            TypeKind::Error | TypeKind::Void => Ok(0),
            TypeKind::Time => panic!("time value has no bit size"),
            TypeKind::Bit(_) => Ok(1),
            TypeKind::Int(width, _) => Ok(width),
            TypeKind::Named(_, _, ty) => bit_size_of_type(cx, ty, env),
            TypeKind::Struct(struct_id) => {
                let fields = match cx.hir_of(struct_id)? {
                    HirNode::Type(hir::Type {
                        kind: hir::TypeKind::Struct(ref fields),
                        ..
                    }) => fields,
                    _ => unreachable!(),
                };
                let mut size = 0;
                for &field in fields {
                    size += bit_size_of_type(cx, cx.type_of(field, env)?, env)?;
                }
                Ok(size)
            }
            TypeKind::PackedArray(elements, ty) => Ok(elements * bit_size_of_type(cx, ty, env)?),
            TypeKind::BitScalar { .. } => Ok(1),
            TypeKind::BitVector {
                range: Range { size, .. },
                ..
            } => Ok(size),
        }
    }
}

impl<'t> Display for TypeKind<'t> {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        match *self {
            TypeKind::Error => write!(f, "<error>"),
            TypeKind::Void => write!(f, "void"),
            TypeKind::Time => write!(f, "time"),
            TypeKind::Bit(Domain::TwoValued) => write!(f, "bit"),
            TypeKind::Bit(Domain::FourValued) => write!(f, "logic"),
            TypeKind::Int(32, Domain::TwoValued) => write!(f, "int"),
            TypeKind::Int(32, Domain::FourValued) => write!(f, "integer"),
            TypeKind::Int(width, Domain::TwoValued) => write!(f, "int<{}>", width),
            TypeKind::Int(width, Domain::FourValued) => write!(f, "integer<{}>", width),
            TypeKind::Named(name, ..) => write!(f, "{}", name.value),
            TypeKind::Struct(_) => write!(f, "struct"),
            TypeKind::PackedArray(length, ty) => write!(f, "{} [{}:0]", ty, length - 1),
            TypeKind::BitScalar { domain, sign } => {
                write!(f, "{}", domain.bit_name())?;
                if sign == Sign::Signed {
                    write!(f, " signed")?;
                }
                Ok(())
            }
            TypeKind::BitVector {
                domain,
                sign,
                range,
                dubbed,
            } => {
                // Use the builtin name if called such by the user.
                if dubbed {
                    let dub = match range.size {
                        8 if domain == Domain::TwoValued => Some("byte"),
                        16 if domain == Domain::TwoValued => Some("shortint"),
                        32 if domain == Domain::TwoValued => Some("int"),
                        32 if domain == Domain::FourValued => Some("integer"),
                        64 if domain == Domain::TwoValued => Some("longint"),
                        _ => None,
                    };
                    if let Some(dub) = dub {
                        write!(f, "{}", dub)?;
                        if sign != Sign::Signed {
                            write!(f, " {}", sign)?;
                        }
                        return Ok(());
                    }
                }

                // Otherwise use the regular bit name with vector range.
                write!(f, "{}", domain.bit_name())?;
                if sign != Sign::Unsigned {
                    write!(f, " {}", sign)?;
                }
                write!(f, " {}", range)
            }
        }
    }
}

impl Domain {
    /// Return the single-bit name for this domain (`bit` or `logic`).
    pub fn bit_name(&self) -> &'static str {
        match self {
            Domain::TwoValued => "bit",
            Domain::FourValued => "logic",
        }
    }

    /// Return the single-bit type for this domain (`bit` or `logic`).
    pub fn bit_type(&self) -> &'static TypeKind<'static> {
        match self {
            Domain::TwoValued => &BIT_TYPE,
            Domain::FourValued => &LOGIC_TYPE,
        }
    }
}

impl Sign {
    /// Check whether the type is unsigned.
    ///
    /// Returns false for types which have no sign.
    pub fn is_unsigned(&self) -> bool {
        *self == Sign::Unsigned
    }

    /// Check whether the type is signed.
    ///
    /// Returns false for types which have no sign.
    pub fn is_signed(&self) -> bool {
        *self == Sign::Signed
    }
}

impl Display for Sign {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        match self {
            Sign::Signed => write!(f, "signed"),
            Sign::Unsigned => write!(f, "unsigned"),
        }
    }
}

impl Display for Range {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        let lo = self.offset;
        let hi = lo + self.size as isize - 1;
        let (lhs, rhs) = match self.dir {
            RangeDir::Up => (lo, hi),
            RangeDir::Down => (hi, lo),
        };
        write!(f, "[{}:{}]", lhs, rhs)
    }
}

/// The `<error>` type.
pub static ERROR_TYPE: TypeKind<'static> = TypeKind::Error;

/// The `void` type.
pub static VOID_TYPE: TypeKind<'static> = TypeKind::Void;

/// The `time` type.
pub static TIME_TYPE: TypeKind<'static> = TypeKind::Time;

/// The `bit` type.
pub static BIT_TYPE: TypeKind<'static> = TypeKind::BitScalar {
    domain: ty::Domain::TwoValued,
    sign: Sign::Unsigned,
};

/// The `logic` type.
pub static LOGIC_TYPE: TypeKind<'static> = TypeKind::BitScalar {
    domain: ty::Domain::FourValued,
    sign: Sign::Unsigned,
};

/// The `byte` type.
pub static BYTE_TYPE: TypeKind<'static> = TypeKind::BitVector {
    domain: Domain::TwoValued,
    sign: Sign::Signed,
    range: Range {
        size: 8,
        dir: RangeDir::Down,
        offset: 0isize,
    },
    dubbed: true,
};

/// The `shortint` type.
pub static SHORTINT_TYPE: TypeKind<'static> = TypeKind::BitVector {
    domain: Domain::TwoValued,
    sign: Sign::Signed,
    range: Range {
        size: 16,
        dir: RangeDir::Down,
        offset: 0isize,
    },
    dubbed: true,
};

/// The `int` type.
pub static INT_TYPE: TypeKind<'static> = TypeKind::BitVector {
    domain: Domain::TwoValued,
    sign: Sign::Signed,
    range: Range {
        size: 32,
        dir: RangeDir::Down,
        offset: 0isize,
    },
    dubbed: true,
};

/// The `integer` type.
pub static INTEGER_TYPE: TypeKind<'static> = TypeKind::BitVector {
    domain: Domain::FourValued,
    sign: Sign::Signed,
    range: Range {
        size: 32,
        dir: RangeDir::Down,
        offset: 0isize,
    },
    dubbed: true,
};

/// The `longint` type.
pub static LONGINT_TYPE: TypeKind<'static> = TypeKind::BitVector {
    domain: Domain::TwoValued,
    sign: Sign::Signed,
    range: Range {
        size: 64,
        dir: RangeDir::Down,
        offset: 0isize,
    },
    dubbed: true,
};

// Compute the size of a type in bits.
pub fn bit_size_of_type<'gcx>(
    cx: &impl Context<'gcx>,
    ty: Type<'gcx>,
    env: ParamEnv,
) -> Result<usize> {
    ty.try_bit_size(cx, env)
}

/// Check if two types are identical.
///
/// This is not the same as a check for equality, since the types may contain
/// names and spans in the source code which are different, yet still refer to
/// the same type.
pub fn identical(a: Type, b: Type) -> bool {
    let a = a.resolve_name();
    let b = b.resolve_name();
    match (a, b) {
        (
            TypeKind::BitVector {
                domain: da,
                sign: sa,
                range: ra,
                ..
            },
            TypeKind::BitVector {
                domain: db,
                sign: sb,
                range: rb,
                ..
            },
        ) => da == db && sa == sb && ra == rb,

        (TypeKind::PackedArray(sa, ta), TypeKind::PackedArray(sb, tb)) => {
            sa == sb && identical(ta, tb)
        }

        _ => a == b,
    }
}

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

    #[test]
    fn builtin_type_names() {
        // Check the builtint dubbed types.
        assert_eq!(format!("{}", BYTE_TYPE), "byte");
        assert_eq!(format!("{}", SHORTINT_TYPE), "shortint");
        assert_eq!(format!("{}", INT_TYPE), "int");
        assert_eq!(format!("{}", INTEGER_TYPE), "integer");
        assert_eq!(format!("{}", LONGINT_TYPE), "longint");

        // Check the direction and offset.
        assert_eq!(
            format!(
                "{}",
                TypeKind::BitVector {
                    domain: Domain::TwoValued,
                    sign: Sign::Unsigned,
                    range: Range {
                        size: 42,
                        dir: RangeDir::Up,
                        offset: 0isize,
                    },
                    dubbed: false,
                }
            ),
            "bit [0:41]"
        );
        assert_eq!(
            format!(
                "{}",
                TypeKind::BitVector {
                    domain: Domain::TwoValued,
                    sign: Sign::Unsigned,
                    range: Range {
                        size: 42,
                        dir: RangeDir::Down,
                        offset: 0isize,
                    },
                    dubbed: false,
                }
            ),
            "bit [41:0]"
        );
        assert_eq!(
            format!(
                "{}",
                TypeKind::BitVector {
                    domain: Domain::TwoValued,
                    sign: Sign::Unsigned,
                    range: Range {
                        size: 42,
                        dir: RangeDir::Down,
                        offset: -2isize,
                    },
                    dubbed: false,
                }
            ),
            "bit [39:-2]"
        );
        assert_eq!(
            format!(
                "{}",
                TypeKind::BitVector {
                    domain: Domain::TwoValued,
                    sign: Sign::Unsigned,
                    range: Range {
                        size: 42,
                        dir: RangeDir::Down,
                        offset: 3isize,
                    },
                    dubbed: false,
                }
            ),
            "bit [44:3]"
        );

        // Check the domain.
        assert_eq!(
            format!(
                "{}",
                TypeKind::BitVector {
                    domain: Domain::FourValued,
                    sign: Sign::Unsigned,
                    range: Range {
                        size: 42,
                        dir: RangeDir::Down,
                        offset: 0isize,
                    },
                    dubbed: false,
                }
            ),
            "logic [41:0]"
        );

        // Check the sign.
        assert_eq!(
            format!(
                "{}",
                TypeKind::BitVector {
                    domain: Domain::FourValued,
                    sign: Sign::Signed,
                    range: Range {
                        size: 42,
                        dir: RangeDir::Down,
                        offset: 0isize,
                    },
                    dubbed: false,
                }
            ),
            "logic signed [41:0]"
        );
    }
}