spade_ast/
lib.rs

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
use itertools::Itertools;
use num::{BigInt, BigUint, Signed, Zero};
use spade_common::{
    location_info::{Loc, WithLocation},
    name::{Identifier, Path},
    num_ext::InfallibleToBigInt,
};
use std::fmt::Display;
pub mod testutil;

#[derive(PartialEq, Debug, Clone)]
pub enum TypeExpression {
    TypeSpec(Box<Loc<TypeSpec>>),
    Integer(BigInt),
    ConstGeneric(Box<Loc<Expression>>),
}
impl WithLocation for TypeExpression {}

impl std::fmt::Display for TypeExpression {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            TypeExpression::TypeSpec(inner) => write!(f, "{inner}"),
            TypeExpression::Integer(inner) => write!(f, "{inner}"),
            TypeExpression::ConstGeneric(_) => write!(f, "{{...}}"),
        }
    }
}

#[derive(PartialEq, Debug, Clone)]
pub enum NamedTurbofish {
    Short(Loc<Identifier>),
    Full(Loc<Identifier>, Loc<TypeExpression>),
}
impl WithLocation for NamedTurbofish {}

#[derive(PartialEq, Debug, Clone)]
pub enum TurbofishInner {
    Named(Vec<Loc<NamedTurbofish>>),
    Positional(Vec<Loc<TypeExpression>>),
}
impl WithLocation for TurbofishInner {}

/// A specification of a type to be used. For example, the types of input/output arguments the type
/// of fields in a struct etc.
#[derive(PartialEq, Debug, Clone)]
pub enum TypeSpec {
    Tuple(Vec<Loc<TypeExpression>>),
    Array {
        inner: Box<Loc<TypeExpression>>,
        size: Box<Loc<TypeExpression>>,
    },
    Named(Loc<Path>, Option<Loc<Vec<Loc<TypeExpression>>>>),
    Unit(Loc<()>),
    /// An inverted signal (`~`), its "direction" is the inverse of normal. A `~&T` taken as an
    /// argument is an output, and a returned `~&T` is an input. This used to be expressed as `&mut
    /// T` Inversions cancel each other, i.e. `~~&T` is effectively `&T` Inverted signals are
    /// ports.
    /// If applied to a struct port, all fields are inverted.
    Inverted(Box<Loc<TypeExpression>>),
    Wire(Box<Loc<TypeExpression>>),
    Wildcard,
}
impl WithLocation for TypeSpec {}

impl std::fmt::Display for TypeSpec {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            TypeSpec::Tuple(inner) => {
                write!(f, "({})", inner.iter().map(|i| format!("{i}")).join(", "))
            }
            TypeSpec::Array { inner, size } => write!(f, "[{inner}; {size}]"),
            TypeSpec::Named(name, args) => {
                let args = match args {
                    Some(a) => a.iter().map(|a| format!("{a}")).join(", "),
                    None => String::new(),
                };
                write!(f, "{name}{args}")
            }
            TypeSpec::Unit(_) => write!(f, "()"),
            TypeSpec::Inverted(inner) => write!(f, "inv {inner}"),
            TypeSpec::Wire(inner) => write!(f, "&{inner}"),
            TypeSpec::Wildcard => write!(f, "_"),
        }
    }
}

#[derive(PartialEq, Debug, Clone)]
pub enum ArgumentPattern {
    Named(Vec<(Loc<Identifier>, Option<Loc<Pattern>>)>),
    Positional(Vec<Loc<Pattern>>),
}
impl WithLocation for ArgumentPattern {}

#[derive(PartialEq, Debug, Clone)]
pub enum Pattern {
    Integer(IntLiteral),
    Bool(bool),
    Path(Loc<Path>),
    Tuple(Vec<Loc<Pattern>>),
    Array(Vec<Loc<Pattern>>),
    Type(Loc<Path>, Loc<ArgumentPattern>),
}
impl WithLocation for Pattern {}

// Helper constructors for writing neater tests
impl Pattern {
    pub fn integer(val: i32) -> Self {
        Pattern::Integer(IntLiteral::Unsized(val.to_bigint()))
    }
    pub fn name(name: &str) -> Loc<Self> {
        Pattern::Path(Path(vec![Identifier(name.to_string()).nowhere()]).nowhere()).nowhere()
    }
}

#[derive(PartialEq, Debug, Clone)]
pub enum NamedArgument {
    Full(Loc<Identifier>, Loc<Expression>),
    /// Binds a local variable to an argument with the same name
    Short(Loc<Identifier>),
}
impl WithLocation for NamedArgument {}

#[derive(PartialEq, Debug, Clone)]
pub enum ArgumentList {
    Positional(Vec<Loc<Expression>>),
    Named(Vec<NamedArgument>),
}
impl WithLocation for ArgumentList {}

#[derive(PartialEq, Debug, Clone)]
pub enum WhereClause {
    GenericInt {
        target: Loc<Path>,
        expression: Loc<Expression>,
    },
    TraitBounds {
        target: Loc<Path>,
        traits: Vec<Loc<TraitSpec>>,
    },
}
impl WhereClause {
    pub fn target(&self) -> &Loc<Path> {
        match self {
            WhereClause::GenericInt {
                target,
                expression: _,
            } => target,
            WhereClause::TraitBounds { target, traits: _ } => target,
        }
    }
}
impl WithLocation for WhereClause {}

#[derive(PartialEq, Debug, Clone)]
pub enum BinaryOperator {
    Add,
    Sub,
    Mul,
    Div,
    Mod,
    Equals,
    NotEquals,
    Lt,
    Gt,
    Le,
    Ge,
    LogicalAnd,
    LogicalOr,
    LogicalXor,
    LeftShift,
    RightShift,
    ArithmeticRightShift,
    BitwiseAnd,
    BitwiseOr,
    BitwiseXor,
}
impl WithLocation for BinaryOperator {}

impl std::fmt::Display for BinaryOperator {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            BinaryOperator::Add => write!(f, "+"),
            BinaryOperator::Sub => write!(f, "-"),
            BinaryOperator::Mul => write!(f, "*"),
            BinaryOperator::Div => write!(f, "/"),
            BinaryOperator::Mod => write!(f, "%"),
            BinaryOperator::Equals => write!(f, "=="),
            BinaryOperator::NotEquals => write!(f, "!="),
            BinaryOperator::Lt => write!(f, "<"),
            BinaryOperator::Gt => write!(f, ">"),
            BinaryOperator::Le => write!(f, "<="),
            BinaryOperator::Ge => write!(f, ">="),
            BinaryOperator::LogicalAnd => write!(f, "&"),
            BinaryOperator::LogicalOr => write!(f, "|"),
            BinaryOperator::LogicalXor => write!(f, "^"),
            BinaryOperator::LeftShift => write!(f, "<<"),
            BinaryOperator::RightShift => write!(f, ">>"),
            BinaryOperator::ArithmeticRightShift => write!(f, ">>>"),
            BinaryOperator::BitwiseAnd => write!(f, "&&"),
            BinaryOperator::BitwiseOr => write!(f, "||"),
            BinaryOperator::BitwiseXor => write!(f, "^^"),
        }
    }
}

#[derive(PartialEq, Debug, Clone)]
pub enum UnaryOperator {
    Sub,
    Not,
    BitwiseNot,
    Dereference,
    Reference,
}
impl WithLocation for UnaryOperator {}

impl std::fmt::Display for UnaryOperator {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            UnaryOperator::Sub => write!(f, "-"),
            UnaryOperator::Not => write!(f, "!"),
            UnaryOperator::BitwiseNot => write!(f, "~"),
            UnaryOperator::Dereference => write!(f, "*"),
            UnaryOperator::Reference => write!(f, "&"),
        }
    }
}

#[derive(PartialEq, Debug, Clone)]
pub enum PipelineStageReference {
    Relative(Loc<TypeExpression>),
    Absolute(Loc<Identifier>),
}

#[derive(PartialEq, Debug, Clone)]
pub enum CallKind {
    Function,
    Entity(Loc<()>),
    Pipeline(Loc<()>, Loc<TypeExpression>),
}
impl WithLocation for CallKind {}

#[derive(PartialEq, Debug, Clone)]
pub enum BitLiteral {
    Low,
    High,
    HighImp,
}
impl WithLocation for BitLiteral {}

#[derive(PartialEq, Debug, Clone)]
pub enum Expression {
    Identifier(Loc<Path>),
    IntLiteral(IntLiteral),
    BoolLiteral(bool),
    BitLiteral(BitLiteral),
    /// `[1, 2, 3]`
    ArrayLiteral(Vec<Loc<Expression>>),
    /// `[<expr>; <amount>]`
    /// amount is a const generic
    ArrayShorthandLiteral(Box<Loc<Expression>>, Box<Loc<Expression>>),
    Index(Box<Loc<Expression>>, Box<Loc<Expression>>),
    RangeIndex {
        target: Box<Loc<Expression>>,
        // NOTE: These are const generics
        start: Box<Loc<Expression>>,
        end: Box<Loc<Expression>>,
    },
    TupleLiteral(Vec<Loc<Expression>>),
    TupleIndex(Box<Loc<Expression>>, Loc<u128>),
    FieldAccess(Box<Loc<Expression>>, Loc<Identifier>),
    CreatePorts,
    Call {
        kind: CallKind,
        callee: Loc<Path>,
        args: Loc<ArgumentList>,
        turbofish: Option<Loc<TurbofishInner>>,
    },
    MethodCall {
        target: Box<Loc<Expression>>,
        name: Loc<Identifier>,
        args: Loc<ArgumentList>,
        kind: CallKind,
        turbofish: Option<Loc<TurbofishInner>>,
    },
    If(
        Box<Loc<Expression>>,
        Box<Loc<Expression>>,
        Box<Loc<Expression>>,
    ),
    TypeLevelIf(
        Box<Loc<Expression>>,
        Box<Loc<Expression>>,
        Box<Loc<Expression>>,
    ),
    Match(
        Box<Loc<Expression>>,
        Loc<Vec<(Loc<Pattern>, Loc<Expression>)>>,
    ),
    UnaryOperator(Loc<UnaryOperator>, Box<Loc<Expression>>),
    BinaryOperator(
        Box<Loc<Expression>>,
        Loc<BinaryOperator>,
        Box<Loc<Expression>>,
    ),
    Block(Box<Block>),
    /// E.g. `stage(-5).x`, `stage('b).y`
    PipelineReference {
        /// ```text
        /// stage(-5).xyz
        /// ^^^^^^^^^
        /// ```
        stage_kw_and_reference_loc: Loc<()>,
        /// ```text
        /// stage(-5).xyz
        ///       ^^
        /// ```
        stage: PipelineStageReference,
        /// ```text
        /// stage(-5).xyz
        ///           ^^^
        /// ```
        name: Loc<Identifier>,
    },
    StageValid,
    StageReady,
}
impl WithLocation for Expression {}

impl Expression {
    pub fn int_literal_signed(val: i32) -> Self {
        Self::IntLiteral(IntLiteral::unsized_(val))
    }

    pub fn as_int_literal(self) -> Option<IntLiteral> {
        match self {
            Expression::IntLiteral(lit) => Some(lit),
            _ => None,
        }
    }

    pub fn assume_block(&self) -> &Block {
        if let Expression::Block(inner) = self {
            inner
        } else {
            panic!("Expected block")
        }
    }

    pub fn variant_str(&self) -> &'static str {
        match self {
            Expression::Identifier(_) => "identifier",
            Expression::IntLiteral(_) => "int literal",
            Expression::BoolLiteral(_) => "bool literal",
            Expression::BitLiteral(_) => "bit literal",
            Expression::ArrayLiteral(_) => "array literal",
            Expression::ArrayShorthandLiteral(_, _) => "array shorthand literal",
            Expression::CreatePorts => "port",
            Expression::Index(_, _) => "index",
            Expression::RangeIndex { .. } => "range index",
            Expression::TupleLiteral(_) => "tuple literal",
            Expression::TupleIndex(_, _) => "tuple index",
            Expression::FieldAccess(_, _) => "field access",
            Expression::If(_, _, _) => "if",
            Expression::TypeLevelIf(_, _, _) => "type level if",
            Expression::Match(_, _) => "match",
            Expression::Call { .. } => "call",
            Expression::MethodCall { .. } => "method call",
            Expression::UnaryOperator(_, _) => "unary operator",
            Expression::BinaryOperator(_, _, _) => "binary operator",
            Expression::Block(_) => "block",
            Expression::PipelineReference { .. } => "pipeline reference",
            Expression::StageValid => "stage.valid",
            Expression::StageReady => "stage.ready",
        }
    }
}

/// An integer literal, which may or may not have been suffixed with `U` to indicate
/// it being an unsigned literal.
#[derive(PartialEq, Debug, Clone)]
pub enum IntLiteral {
    Unsized(BigInt),
    Signed { val: BigInt, size: BigUint },
    Unsigned { val: BigUint, size: BigUint },
}
impl WithLocation for IntLiteral {}

impl IntLiteral {
    pub fn unsized_(val: i32) -> IntLiteral {
        IntLiteral::Unsized(val.to_bigint())
    }

    /// Returns this number as a signed number. Unsigned numbers are losslessly converted to
    /// signed
    pub fn as_signed(self) -> BigInt {
        match self {
            IntLiteral::Signed { val, size: _ } => val,
            IntLiteral::Unsigned { val, size: _ } => val.to_bigint(),
            IntLiteral::Unsized(val) => val,
        }
    }

    // Returns the signed, or unsigned number as a BigUint if it is positive, otherwise,
    // None
    pub fn as_unsigned(self) -> Option<BigUint> {
        match self {
            IntLiteral::Signed { val, size: _ } | IntLiteral::Unsized(val) => {
                if val >= BigInt::zero() {
                    Some(val.to_biguint().unwrap())
                } else {
                    None
                }
            }
            IntLiteral::Unsigned { val, size: _ } => Some(val),
        }
    }

    pub fn is_negative(&self) -> bool {
        match self {
            IntLiteral::Unsized(val) | IntLiteral::Signed { val, size: _ } => val.is_negative(),
            IntLiteral::Unsigned { .. } => false,
        }
    }
}

impl Display for IntLiteral {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            // this is not dry
            IntLiteral::Unsized(val) | IntLiteral::Signed { val, .. } => write!(f, "{}", val),
            IntLiteral::Unsigned { val, .. } => write!(f, "{}", val),
        }
    }
}

#[derive(PartialEq, Debug, Clone)]
pub struct Block {
    pub statements: Vec<Loc<Statement>>,
    pub result: Option<Loc<Expression>>,
}
impl WithLocation for Block {}

#[derive(PartialEq, Debug, Clone)]
pub struct Binding {
    pub pattern: Loc<Pattern>,
    pub ty: Option<Loc<TypeSpec>>,
    pub value: Loc<Expression>,
    pub attrs: AttributeList,
}

#[derive(PartialEq, Debug, Clone)]
pub enum Statement {
    Label(Loc<Identifier>),
    Declaration(Vec<Loc<Identifier>>),
    Binding(Binding),
    PipelineRegMarker(Option<Loc<TypeExpression>>, Option<Loc<Expression>>),
    Register(Loc<Register>),
    /// Sets the value of the target expression, which must be a Backward port to
    /// the value of `value`
    Set {
        target: Loc<Expression>,
        value: Loc<Expression>,
    },
    Assert(Loc<Expression>),
}
impl WithLocation for Statement {}

impl Statement {
    // Creates a binding from name, type and values without any attributes.
    pub fn binding(
        pattern: Loc<Pattern>,
        ty: Option<Loc<TypeSpec>>,
        value: Loc<Expression>,
    ) -> Self {
        Self::Binding(Binding {
            pattern,
            ty,
            value,
            attrs: AttributeList::empty(),
        })
    }
}

/// A generic type parameter
#[derive(PartialEq, Debug, Clone)]
pub enum TypeParam {
    TypeName {
        name: Loc<Identifier>,
        traits: Vec<Loc<TraitSpec>>,
    },
    TypeWithMeta {
        meta: Loc<Identifier>,
        name: Loc<Identifier>,
    },
}
impl WithLocation for TypeParam {}
impl TypeParam {
    pub fn name(&self) -> &Loc<Identifier> {
        match self {
            TypeParam::TypeName { name, traits: _ } => name,
            TypeParam::TypeWithMeta { meta: _, name } => name,
        }
    }
}

#[derive(PartialEq, Debug, Clone)]
pub enum GenericBound {
    IntegerConstraint(Loc<Path>, Loc<Expression>),
    TypeConstraint(Loc<Path>, Vec<Loc<Identifier>>),
}

impl WithLocation for GenericBound {}

impl GenericBound {
    pub fn path(&self) -> &Loc<Path> {
        match self {
            GenericBound::IntegerConstraint(path, _) => path,
            GenericBound::TypeConstraint(path, _) => path,
        }
    }
}

#[derive(PartialEq, Debug, Clone)]
pub enum Attribute {
    Optimize {
        passes: Vec<Loc<String>>,
    },
    NoMangle {
        all: bool,
    },
    Fsm {
        state: Option<Loc<Identifier>>,
    },
    WalTraceable {
        suffix: Option<Loc<Identifier>>,
        uses_clk: bool,
        uses_rst: bool,
    },
    WalTrace {
        clk: Option<Loc<Expression>>,
        rst: Option<Loc<Expression>>,
    },
    /// Create a copy of the marked signal with the specified suffix applied
    WalSuffix {
        suffix: Loc<Identifier>,
    },
}

impl Attribute {
    pub fn name(&self) -> &str {
        match self {
            Attribute::Optimize { passes: _ } => "optimize",
            Attribute::NoMangle { .. } => "no_mangle",
            Attribute::Fsm { state: _ } => "fsm",
            Attribute::WalTraceable { .. } => "wal_traceable",
            Attribute::WalTrace { .. } => "wal_trace",
            Attribute::WalSuffix { .. } => "wal_suffix",
        }
    }
}

impl WithLocation for Attribute {}

#[derive(PartialEq, Debug, Clone)]
pub struct AttributeList(pub Vec<Loc<Attribute>>);
impl AttributeList {
    pub fn empty() -> Self {
        Self(vec![])
    }

    pub fn from_vec(attrs: Vec<Loc<Attribute>>) -> Self {
        Self(attrs)
    }
}

#[derive(PartialEq, Debug, Clone)]
pub struct ParameterList {
    pub self_: Option<Loc<()>>,
    pub args: Vec<(AttributeList, Loc<Identifier>, Loc<TypeSpec>)>,
}
impl WithLocation for ParameterList {}

impl ParameterList {
    pub fn without_self(args: Vec<(Loc<Identifier>, Loc<TypeSpec>)>) -> Self {
        Self {
            self_: None,
            args: args
                .into_iter()
                .map(|(n, t)| (AttributeList::empty(), n, t))
                .collect(),
        }
    }

    pub fn with_self(self_: Loc<()>, args: Vec<(Loc<Identifier>, Loc<TypeSpec>)>) -> Self {
        Self {
            self_: Some(self_),
            args: args
                .into_iter()
                .map(|(n, t)| (AttributeList::empty(), n, t))
                .collect(),
        }
    }
}

#[derive(PartialEq, Debug, Clone)]
pub enum UnitKind {
    Function,
    Entity,
    Pipeline(Loc<TypeExpression>),
}
impl WithLocation for UnitKind {}

impl UnitKind {
    pub fn is_pipeline(&self) -> bool {
        match self {
            UnitKind::Function => false,
            UnitKind::Entity => false,
            UnitKind::Pipeline(_) => true,
        }
    }
}

impl std::fmt::Display for UnitKind {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            UnitKind::Function => write!(f, "fn"),
            UnitKind::Entity => write!(f, "entity"),
            UnitKind::Pipeline(_) => write!(f, "pipeline"),
        }
    }
}

#[derive(PartialEq, Debug, Clone)]
pub struct UnitHead {
    pub attributes: AttributeList,
    pub unit_kind: Loc<UnitKind>,
    pub name: Loc<Identifier>,
    pub inputs: Loc<ParameterList>,
    pub output_type: Option<(Loc<()>, Loc<TypeSpec>)>,
    pub type_params: Option<Loc<Vec<Loc<TypeParam>>>>,
    pub where_clauses: Vec<WhereClause>,
}
impl WithLocation for UnitHead {}

#[derive(PartialEq, Debug, Clone)]
pub struct Unit {
    pub head: UnitHead,
    /// The body is an expression for ID assignment purposes, but semantic analysis
    /// ensures that it is always a block. If body is `None`, the entity is __builtin__
    pub body: Option<Loc<Expression>>,
}
impl WithLocation for Unit {}

#[derive(PartialEq, Debug, Clone)]
pub struct Register {
    pub pattern: Loc<Pattern>,
    pub clock: Loc<Expression>,
    pub reset: Option<(Loc<Expression>, Loc<Expression>)>,
    pub initial: Option<Loc<Expression>>,
    pub value: Loc<Expression>,
    pub value_type: Option<Loc<TypeSpec>>,
    pub attributes: AttributeList,
}
impl WithLocation for Register {}

/// A definition of a trait
#[derive(PartialEq, Debug, Clone)]
pub struct TraitDef {
    pub name: Loc<Identifier>,
    pub type_params: Option<Loc<Vec<Loc<TypeParam>>>>,
    pub where_clauses: Vec<WhereClause>,
    pub methods: Vec<Loc<UnitHead>>,
}
impl WithLocation for TraitDef {}

/// A specification of a trait with type parameters
#[derive(PartialEq, Debug, Clone)]
pub struct TraitSpec {
    pub path: Loc<Path>,
    pub type_params: Option<Loc<Vec<Loc<TypeExpression>>>>,
}
impl WithLocation for TraitSpec {}

#[derive(PartialEq, Debug, Clone)]
pub struct ImplBlock {
    pub r#trait: Option<Loc<TraitSpec>>,
    pub type_params: Option<Loc<Vec<Loc<TypeParam>>>>,
    pub where_clauses: Vec<WhereClause>,
    pub target: Loc<TypeSpec>,
    pub units: Vec<Loc<Unit>>,
}
impl WithLocation for ImplBlock {}

/// Declaration of an enum
#[derive(PartialEq, Debug, Clone)]
pub struct Enum {
    pub name: Loc<Identifier>,
    pub options: Vec<(Loc<Identifier>, Option<Loc<ParameterList>>)>,
}
impl WithLocation for Enum {}

#[derive(PartialEq, Debug, Clone)]
pub struct Struct {
    pub attributes: AttributeList,
    pub name: Loc<Identifier>,
    pub members: Loc<ParameterList>,
    pub port_keyword: Option<Loc<()>>,
}
impl WithLocation for Struct {}

impl Struct {
    pub fn is_port(&self) -> bool {
        self.port_keyword.is_some()
    }
}

#[derive(PartialEq, Debug, Clone)]
pub enum TypeDeclKind {
    Enum(Loc<Enum>),
    Struct(Loc<Struct>),
}

/// A declaration of a new type
#[derive(PartialEq, Debug, Clone)]
pub struct TypeDeclaration {
    pub name: Loc<Identifier>,
    pub kind: TypeDeclKind,
    pub generic_args: Option<Loc<Vec<Loc<TypeParam>>>>,
}
impl WithLocation for TypeDeclaration {}

#[derive(PartialEq, Debug, Clone)]
pub struct UseStatement {
    pub path: Loc<Path>,
    pub alias: Option<Loc<Identifier>>,
}
impl WithLocation for UseStatement {}

/// Items are things typically present at the top level of a module such as
/// entities, pipelines, submodules etc.
#[derive(PartialEq, Debug, Clone)]
pub enum Item {
    Unit(Loc<Unit>),
    TraitDef(Loc<TraitDef>),
    Type(Loc<TypeDeclaration>),
    Module(Loc<Module>),
    Use(Loc<UseStatement>),
    ImplBlock(Loc<ImplBlock>),
}
impl WithLocation for Item {}

impl Item {
    pub fn name(&self) -> Option<&Identifier> {
        match self {
            Item::Unit(u) => Some(&u.head.name.inner),
            Item::TraitDef(t) => Some(&t.name.inner),
            Item::Type(t) => Some(&t.name.inner),
            Item::Module(m) => Some(&m.name.inner),
            Item::Use(u) => u.alias.as_ref().map(|name| &name.inner),
            Item::ImplBlock(_) => None,
        }
    }

    pub fn variant_str(&self) -> &'static str {
        match self {
            Item::Unit(_) => "unit",
            Item::TraitDef(_) => "trait definition",
            Item::Type(_) => "type",
            Item::Module(_) => "module",
            Item::Use(_) => "use",
            Item::ImplBlock(_) => "impl",
        }
    }
}

#[derive(PartialEq, Debug, Clone)]
pub struct Module {
    pub name: Loc<Identifier>,
    pub body: Loc<ModuleBody>,
}
impl WithLocation for Module {}

#[derive(PartialEq, Debug, Clone)]
pub struct ModuleBody {
    pub members: Vec<Item>,
}
impl WithLocation for ModuleBody {}