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
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this file,
// You can obtain one at http://mozilla.org/MPL/2.0/.
//
// Copyright (c) 2022, Olof Kraigher olof.kraigher@gmail.com

use crate::ast::{
    AliasDeclaration, AnyDesignUnit, AnyPrimaryUnit, AnySecondaryUnit, Attribute,
    AttributeDeclaration, AttributeSpecification, ComponentDeclaration, Declaration, Designator,
    FileDeclaration, HasIdent, Ident, InterfaceFileDeclaration, InterfacePackageDeclaration,
    ModeViewDeclaration, ObjectClass, ObjectDeclaration, PackageInstantiation, SubprogramBody,
    SubprogramInstantiation, SubprogramSpecification, TypeDeclaration, WithDecl,
};
use crate::ast::{ExternalObjectClass, InterfaceDeclaration, InterfaceObjectDeclaration};
use crate::data::*;
mod types;
use fnv::FnvHashMap;
pub use types::{BaseType, Subtype, Type, TypeEnt, TypedSelection, UniversalType};
mod overloaded;
pub use overloaded::{Overloaded, OverloadedEnt, Signature, SignatureKey, SubprogramKey};
mod object;
pub use object::{InterfaceMode, Object, ObjectEnt, ObjectInterface, ViewEnt};
mod design;
pub use design::{Design, DesignEnt};
mod attribute;
pub use attribute::AttributeEnt;
mod arena;
pub use arena::{Arena, ArenaId, EntityId, FinalArena, Reference};
mod visibility;
pub use visibility::{Visibility, Visible};
mod region;
pub(crate) use region::RegionKind;
pub use region::{AsUnique, NamedEntities, OverloadedName, Region, SetReference};
mod formal_region;
use crate::ast::token_range::{WithToken, WithTokenSpan};
use crate::data::error_codes::ErrorCode;
use crate::{TokenAccess, TokenSpan};
pub use formal_region::{
    FormalRegion, GpkgInterfaceEnt, GpkgRegion, InterfaceClass, InterfaceEnt, RecordElement,
    RecordRegion,
};

pub enum AnyEntKind<'a> {
    ExternalAlias {
        class: ExternalObjectClass,
        type_mark: TypeEnt<'a>,
    },
    ObjectAlias {
        base_object: ObjectEnt<'a>,
        type_mark: TypeEnt<'a>,
    },
    File(Subtype<'a>),
    InterfaceFile(TypeEnt<'a>),
    Component(Region<'a>),
    Attribute(TypeEnt<'a>),
    Overloaded(Overloaded<'a>),
    Type(Type<'a>),
    ElementDeclaration(Subtype<'a>),
    Concurrent(Option<Concurrent>),
    Sequential(Option<Sequential>),
    Object(Object<'a>),
    LoopParameter(Option<BaseType<'a>>),
    PhysicalLiteral(TypeEnt<'a>),
    DeferredConstant(Subtype<'a>),
    Library,
    Design(Design<'a>),
    View(Subtype<'a>),
}

impl<'a> AnyEntKind<'a> {
    pub(crate) fn new_function_decl(
        formals: FormalRegion<'a>,
        return_type: TypeEnt<'a>,
    ) -> AnyEntKind<'a> {
        AnyEntKind::Overloaded(Overloaded::SubprogramDecl(Signature::new(
            formals,
            Some(return_type),
        )))
    }

    pub(crate) fn new_procedure_decl(formals: FormalRegion<'a>) -> AnyEntKind<'a> {
        AnyEntKind::Overloaded(Overloaded::SubprogramDecl(Signature::new(formals, None)))
    }

    pub fn is_deferred_constant(&self) -> bool {
        matches!(self, AnyEntKind::DeferredConstant(..))
    }

    pub fn is_non_deferred_constant(&self) -> bool {
        matches!(
            self,
            AnyEntKind::Object(Object {
                class: ObjectClass::Constant,
                iface: None,
                ..
            })
        )
    }

    pub fn is_protected_type(&self) -> bool {
        matches!(self, AnyEntKind::Type(Type::Protected(..)))
    }

    pub fn is_type(&self) -> bool {
        matches!(self, AnyEntKind::Type(..))
    }

    pub fn describe(&self) -> &str {
        use AnyEntKind::*;
        match self {
            ObjectAlias { .. } => "object alias",
            ExternalAlias { .. } => "external alias",
            File(..) => "file",
            InterfaceFile(..) => "file parameter",
            ElementDeclaration(..) => "record element",
            Component(..) => "component",
            Attribute(..) => "attribute",
            Overloaded(overloaded) => overloaded.describe(),
            Concurrent(Some(c)) => c.describe(),
            Concurrent(None) => "label",
            Sequential(Some(s)) => s.describe(),
            Sequential(None) => "label",
            LoopParameter(_) => "loop parameter",
            Object(object) => object.class.describe(),
            PhysicalLiteral(..) => "physical literal",
            DeferredConstant(..) => "deferred constant",
            Library => "library",
            Design(design) => design.describe(),
            Type(typ) => typ.describe(),
            View(..) => "view",
        }
    }
}

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

impl<'a> std::fmt::Debug for AnyEnt<'a> {
    // We need a custom debug implementation for AnyEnt to avoid stack overflow on circular references
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let AnyEnt {
            id,
            parent,
            related,
            implicits,
            designator,
            kind,
            decl_pos,
            src_span,
            source,
            attrs,
        } = self;

        let mut s = f.debug_struct(stringify!(AnyEnt));
        s.field(stringify!(id), id);
        s.field(stringify!(parent), &parent.is_some());
        s.field(stringify!(related), related);
        s.field(stringify!(implicits), &implicits.len());
        s.field(stringify!(designator), designator);
        s.field(stringify!(kind), kind);
        s.field(stringify!(decl_pos), decl_pos);
        s.field(stringify!(src_span), src_span);
        s.field(stringify!(source), source);
        s.field(stringify!(attrs), attrs);
        s.finish()
    }
}

pub type EntRef<'a> = &'a AnyEnt<'a>;

#[derive(Debug, Copy, Clone)]
pub enum Related<'a> {
    ImplicitOf(EntRef<'a>),
    InstanceOf(EntRef<'a>),
    DeclaredBy(EntRef<'a>),
    None,
}

/// A named entity as defined in LRM 6.1.
///
/// Every declaration creates one or more named entities.
pub struct AnyEnt<'a> {
    /// A unique id of the entity.
    /// Entities with the same id will be the same.
    pub id: EntityId,
    pub parent: Option<EntRef<'a>>,
    pub related: Related<'a>,
    pub implicits: Vec<EntRef<'a>>,
    /// The location where the declaration was made.
    /// Builtin and implicit declaration will not have a source position.
    pub designator: Designator,
    pub kind: AnyEntKind<'a>,
    pub decl_pos: Option<SrcPos>,
    pub src_span: TokenSpan,
    pub source: Option<Source>,

    /// Custom attributes on this entity
    pub attrs: FnvHashMap<Symbol, (SrcPos, AttributeEnt<'a>)>,
}

impl Arena {
    pub fn implicit<'a>(
        &'a self,
        of_ent: EntRef<'a>,
        designator: impl Into<Designator>,
        kind: AnyEntKind<'a>,
        decl_pos: Option<&SrcPos>,
        src_span: TokenSpan,
        source: Option<Source>,
    ) -> EntRef<'a> {
        self.alloc(
            designator.into(),
            of_ent.parent,
            Related::ImplicitOf(of_ent),
            kind,
            decl_pos.cloned(),
            src_span,
            source,
        )
    }

    pub fn define<'a, T: HasIdent>(
        &'a self,
        ctx: &dyn TokenAccess,
        decl: &mut WithDecl<T>,
        parent: EntRef<'a>,
        kind: AnyEntKind<'a>,
        src_span: TokenSpan,
        source: Option<Source>,
    ) -> EntRef<'a> {
        let ent = self.explicit(
            decl.tree.name().clone(),
            parent,
            kind,
            Some(decl.tree.ident_pos(ctx)),
            src_span,
            source,
        );
        decl.decl.set(ent.id());
        ent
    }

    pub fn explicit<'a>(
        &'a self,
        designator: impl Into<Designator>,
        parent: EntRef<'a>,
        kind: AnyEntKind<'a>,
        decl_pos: Option<&SrcPos>,
        src_span: TokenSpan,
        source: Option<Source>,
    ) -> EntRef<'a> {
        self.alloc(
            designator.into(),
            Some(parent),
            Related::None,
            kind,
            decl_pos.cloned(),
            src_span,
            source,
        )
    }
}

impl<'a> AnyEnt<'a> {
    pub fn id(&self) -> EntityId {
        self.id
    }

    pub fn declaration(&'a self) -> EntRef<'a> {
        if let Related::DeclaredBy(other) = self.related {
            other
        } else {
            self
        }
    }

    pub fn is_implicit(&self) -> bool {
        match self.related {
            Related::ImplicitOf(_) => true,
            Related::InstanceOf(ent) => ent.is_implicit(),
            Related::DeclaredBy(_) => false,
            Related::None => false,
        }
    }

    pub fn is_subprogram(&self) -> bool {
        matches!(
            self.kind,
            AnyEntKind::Overloaded(Overloaded::Subprogram(..))
        )
    }

    pub fn is_subprogram_decl(&self) -> bool {
        matches!(
            self.kind,
            AnyEntKind::Overloaded(Overloaded::SubprogramDecl(..))
        )
    }

    pub fn is_uninst_subprogram_decl(&self) -> bool {
        matches!(
            self.kind,
            AnyEntKind::Overloaded(Overloaded::UninstSubprogramDecl(..))
        )
    }

    pub fn is_uninst_subprogram_body(&self) -> bool {
        matches!(
            self.kind(),
            AnyEntKind::Overloaded(Overloaded::UninstSubprogram(..))
        )
    }

    pub fn is_uninst_subprogram(&self) -> bool {
        matches!(
            self.kind(),
            AnyEntKind::Overloaded(Overloaded::UninstSubprogram(..))
                | AnyEntKind::Overloaded(Overloaded::UninstSubprogramDecl(..))
        )
    }

    pub fn is_protected_type(&self) -> bool {
        matches!(
            self.kind,
            AnyEntKind::Type(Type::Protected(_, is_body)) if !is_body
        )
    }

    pub fn is_protected_type_body(&self) -> bool {
        matches!(
            self.kind,
            AnyEntKind::Type(Type::Protected(_, is_body)) if is_body
        )
    }

    pub fn is_declared_by(&self, other: EntRef) -> bool {
        if let Related::DeclaredBy(ent) = self.related {
            if ent.id() == other.id() {
                return true;
            }
        }

        false
    }

    pub fn is_explicit(&self) -> bool {
        !self.is_implicit()
    }

    /// A statement without a label
    pub fn is_anonymous(&self) -> bool {
        matches!(self.designator(), Designator::Anonymous(_))
    }

    pub fn decl_pos(&self) -> Option<&SrcPos> {
        self.decl_pos.as_ref()
    }

    pub fn parent_in_same_source(&self) -> Option<EntRef<'a>> {
        let source = self.source.as_ref()?;
        let mut ent = self;

        while let Some(parent) = ent.parent {
            if let Some(pos) = &parent.source {
                return if pos == source { Some(parent) } else { None };
            }
            ent = parent;
        }
        None
    }

    pub fn library_name(&self) -> Option<&Symbol> {
        if let AnyEntKind::Library = self.kind() {
            if let Designator::Identifier(symbol) = self.designator() {
                return Some(symbol);
            }
        }

        if let Some(parent) = self.parent {
            parent.library_name()
        } else {
            None
        }
    }

    pub fn designator(&self) -> &Designator {
        &self.designator
    }

    pub fn path_name(&self) -> String {
        if let Some(parent) = self.parent {
            format!("{}.{}", parent.path_name(), self.designator())
        } else {
            self.designator().to_string()
        }
    }

    pub fn kind(&self) -> &AnyEntKind {
        &self.kind
    }

    pub fn error(
        &self,
        diagnostics: &mut dyn DiagnosticHandler,
        message: impl Into<String>,
        code: ErrorCode,
    ) {
        if let Some(ref pos) = self.decl_pos {
            diagnostics.add(pos, message, code);
        }
    }

    pub fn is_overloaded(&self) -> bool {
        self.signature().is_some()
    }

    pub fn signature(&self) -> Option<&Signature> {
        match self.actual_kind() {
            AnyEntKind::Overloaded(ref overloaded) => Some(overloaded.signature()),
            _ => None,
        }
    }

    pub fn as_actual(&self) -> &AnyEnt {
        match self.kind() {
            AnyEntKind::Overloaded(Overloaded::Alias(ref ent)) => ent.as_actual(),
            AnyEntKind::Type(Type::Alias(ref ent)) => ent.as_actual(),
            AnyEntKind::ObjectAlias { base_object, .. } => base_object.as_actual(),
            _ => self,
        }
    }

    pub(crate) fn add_implicit(&mut self, ent: EntRef<'a>) {
        self.implicits.push(ent);
    }

    pub(crate) fn add_attribute(
        &mut self,
        ent: AttributeEnt<'a>,
        pos: &SrcPos,
    ) -> Result<(), Diagnostic> {
        use std::collections::hash_map::Entry;
        match self.attrs.entry(ent.name().clone()) {
            Entry::Occupied(entry) => {
                let last_pos = entry.get().0.clone();
                Err(Diagnostic::new(
                    pos,
                    format!(
                        "Duplicate specification of attribute '{}' for {}",
                        ent.name(),
                        self.describe()
                    ),
                    ErrorCode::Duplicate,
                )
                .related(last_pos, "Previously specified here"))
            }
            Entry::Vacant(entry) => {
                entry.insert((pos.clone(), ent));
                Ok(())
            }
        }
    }

    pub fn get_attribute(&self, name: &Symbol) -> Option<AttributeEnt<'a>> {
        self.attrs.get(name).map(|(_, ent)| *ent)
    }

    /// Strip aliases and return reference to actual entity kind
    pub fn actual_kind(&self) -> &AnyEntKind {
        self.as_actual().kind()
    }

    /// Returns true if self is alias of other
    pub fn is_alias_of(&self, other: &AnyEnt) -> bool {
        match self.kind() {
            AnyEntKind::Type(Type::Alias(ref ent)) => {
                if ent.id() == other.id() {
                    true
                } else {
                    ent.is_alias_of(other)
                }
            }
            _ => false,
        }
    }

    pub fn describe(&self) -> String {
        match self.kind {
            AnyEntKind::Object(_) => ObjectEnt::from_any(self).unwrap().describe(),
            AnyEntKind::Overloaded(_) => OverloadedEnt::from_any(self).unwrap().describe(),

            AnyEntKind::Type(_) => TypeEnt::from_any(self).unwrap().describe(),
            _ => {
                if matches!(self.designator, Designator::Anonymous(_)) {
                    self.kind.describe().to_string()
                } else {
                    format!("{} '{}'", self.kind.describe(), self.designator)
                }
            }
        }
    }

    #[cfg(test)]
    pub fn lookup_implicit_of(&self, name: &str) -> OverloadedEnt<'a> {
        let ent = self
            .implicits
            .iter()
            .find(|ent| matches!(ent.designator(), Designator::Identifier(ident) if ident.name_utf8() == name))
            .unwrap();
        OverloadedEnt::from_any(ent).unwrap()
    }

    #[allow(clippy::mut_from_ref)]
    #[allow(invalid_reference_casting)]
    unsafe fn unsafe_ref_mut(&self) -> &mut Self {
        // NOTE: Use read_volatile to prevent compiler to optimization away assignment to the returned reference
        let const_ptr = std::ptr::read_volatile(&self) as *const Self;
        let mut_ptr = const_ptr as *mut Self;
        &mut *mut_ptr
    }

    // Used to update the kind of pre-declared symbols that are visible before they have been fully analyzed
    pub(crate) unsafe fn set_kind(&self, kind: AnyEntKind) {
        unsafe {
            self.unsafe_ref_mut().kind = kind;
        }
    }

    pub(crate) unsafe fn set_declared_by(&self, ent: EntRef<'a>) {
        unsafe {
            self.unsafe_ref_mut().related = Related::DeclaredBy(ent);
        }
    }
}

impl<'a> std::cmp::PartialEq for AnyEnt<'a> {
    fn eq(&self, other: &Self) -> bool {
        self.id == other.id
    }
}

impl<'a> std::hash::Hash for AnyEnt<'a> {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        self.id().hash(state)
    }
}

impl<'a> Eq for AnyEnt<'a> {}

/// This trait is implemented for Ast-nodes which declare named entities
pub trait HasEntityId {
    fn ent_id(&self) -> Option<EntityId>;
}

impl HasEntityId for AnyPrimaryUnit {
    fn ent_id(&self) -> Option<EntityId> {
        delegate_primary!(self, unit, unit.ident.decl.get())
    }
}

impl HasEntityId for AnyDesignUnit {
    fn ent_id(&self) -> Option<EntityId> {
        match self {
            AnyDesignUnit::Primary(primary) => match primary {
                AnyPrimaryUnit::Entity(ent) => ent.ident.decl.get(),
                AnyPrimaryUnit::Configuration(config) => config.ident.decl.get(),
                AnyPrimaryUnit::Package(pkg) => pkg.ident.decl.get(),
                AnyPrimaryUnit::PackageInstance(inst) => inst.ident.decl.get(),
                AnyPrimaryUnit::Context(ctx) => ctx.ident.decl.get(),
            },
            AnyDesignUnit::Secondary(secondary) => match secondary {
                AnySecondaryUnit::Architecture(arch) => arch.ident.decl.get(),
                AnySecondaryUnit::PackageBody(bod) => bod.ident.decl.get(),
            },
        }
    }
}

impl HasEntityId for InterfaceDeclaration {
    fn ent_id(&self) -> Option<EntityId> {
        match self {
            InterfaceDeclaration::Object(object) => object.ent_id(),
            InterfaceDeclaration::File(file) => file.ent_id(),
            InterfaceDeclaration::Type(typ) => typ.decl.get(),
            InterfaceDeclaration::Subprogram(declaration) => declaration.specification.ent_id(),
            InterfaceDeclaration::Package(pkg) => pkg.ent_id(),
        }
    }
}

impl HasEntityId for InterfaceObjectDeclaration {
    fn ent_id(&self) -> Option<EntityId> {
        self.ident.decl.get()
    }
}

impl HasEntityId for InterfaceFileDeclaration {
    fn ent_id(&self) -> Option<EntityId> {
        self.ident.decl.get()
    }
}

impl HasEntityId for SubprogramSpecification {
    fn ent_id(&self) -> Option<EntityId> {
        match self {
            SubprogramSpecification::Procedure(proc) => proc.designator.decl.get(),
            SubprogramSpecification::Function(func) => func.designator.decl.get(),
        }
    }
}

impl HasEntityId for InterfacePackageDeclaration {
    fn ent_id(&self) -> Option<EntityId> {
        self.ident.decl.get()
    }
}

impl HasEntityId for Declaration {
    fn ent_id(&self) -> Option<EntityId> {
        match self {
            Declaration::Object(object) => object.ent_id(),
            Declaration::File(file) => file.ent_id(),
            Declaration::Type(typ) => typ.ent_id(),
            Declaration::Component(comp) => comp.ent_id(),
            Declaration::Attribute(attr) => attr.ent_id(),
            Declaration::Alias(alias) => alias.ent_id(),
            Declaration::SubprogramDeclaration(decl) => decl.specification.ent_id(),
            Declaration::SubprogramBody(body) => body.ent_id(),
            Declaration::SubprogramInstantiation(decl) => decl.ent_id(),
            Declaration::Package(pkg) => pkg.ent_id(),
            Declaration::Use(_) => None,
            Declaration::Configuration(_) => None,
            Declaration::View(decl) => decl.ent_id(),
        }
    }
}

impl HasEntityId for SubprogramInstantiation {
    fn ent_id(&self) -> Option<EntityId> {
        self.ident.decl.get()
    }
}

impl HasEntityId for PackageInstantiation {
    fn ent_id(&self) -> Option<EntityId> {
        self.ident.decl.get()
    }
}

impl HasEntityId for SubprogramBody {
    fn ent_id(&self) -> Option<EntityId> {
        self.specification.ent_id()
    }
}

impl HasEntityId for AliasDeclaration {
    fn ent_id(&self) -> Option<EntityId> {
        self.designator.decl.get()
    }
}

impl HasEntityId for ObjectDeclaration {
    fn ent_id(&self) -> Option<EntityId> {
        self.ident.decl.get()
    }
}

impl HasEntityId for FileDeclaration {
    fn ent_id(&self) -> Option<EntityId> {
        self.ident.decl.get()
    }
}

impl HasEntityId for TypeDeclaration {
    fn ent_id(&self) -> Option<EntityId> {
        self.ident.decl.get()
    }
}

impl HasEntityId for ComponentDeclaration {
    fn ent_id(&self) -> Option<EntityId> {
        self.ident.decl.get()
    }
}

impl HasEntityId for Attribute {
    fn ent_id(&self) -> Option<EntityId> {
        match self {
            Attribute::Specification(spec) => spec.ent_id(),
            Attribute::Declaration(decl) => decl.ent_id(),
        }
    }
}

impl HasEntityId for AttributeDeclaration {
    fn ent_id(&self) -> Option<EntityId> {
        self.ident.decl.get()
    }
}

impl HasEntityId for AttributeSpecification {
    fn ent_id(&self) -> Option<EntityId> {
        self.ident.reference.get()
    }
}

impl HasEntityId for ModeViewDeclaration {
    fn ent_id(&self) -> Option<EntityId> {
        self.ident.decl.get()
    }
}

impl<T> HasEntityId for WithTokenSpan<T>
where
    T: HasEntityId,
{
    fn ent_id(&self) -> Option<EntityId> {
        self.item.ent_id()
    }
}

impl WithDecl<Ident> {
    pub fn define<'a>(
        &mut self,
        ctx: &dyn TokenAccess,
        arena: &'a Arena,
        parent: EntRef<'a>,
        kind: AnyEntKind<'a>,
        src_span: TokenSpan,
        source: Option<Source>,
    ) -> EntRef<'a> {
        let ent = arena.explicit(
            self.tree.name().clone(),
            parent,
            kind,
            Some(self.tree.pos(ctx)),
            src_span,
            source,
        );
        self.decl.set(ent.id());
        ent
    }
}

impl WithDecl<WithToken<Designator>> {
    pub fn define<'a>(
        &mut self,
        ctx: &dyn TokenAccess,
        arena: &'a Arena,
        parent: EntRef<'a>,
        kind: AnyEntKind<'a>,
        src_span: TokenSpan,
        source: Option<Source>,
    ) -> EntRef<'a> {
        let ent = arena.explicit(
            self.tree.item.clone(),
            parent,
            kind,
            Some(self.tree.pos(ctx)),
            src_span,
            source,
        );
        self.decl.set(ent.id());
        ent
    }
}

impl SubprogramSpecification {
    pub fn set_decl_id(&mut self, id: EntityId) {
        match self {
            SubprogramSpecification::Function(f) => f.designator.decl.set(id),
            SubprogramSpecification::Procedure(p) => p.designator.decl.set(id),
        }
    }
}

#[derive(Copy, Clone, Debug)]
pub enum Concurrent {
    Block,
    Process,
    Generate,
    Instance,
}

impl Concurrent {
    fn describe(&self) -> &'static str {
        match self {
            Concurrent::Block => "block",
            Concurrent::Process => "process",
            Concurrent::Generate => "generate",
            Concurrent::Instance => "instance",
        }
    }
}

#[derive(Copy, Clone, Debug)]
pub enum Sequential {
    Loop,
    If,
    Case,
}

impl Sequential {
    fn describe(&self) -> &'static str {
        match self {
            Sequential::Case => "case statement",
            Sequential::If => "if statement",
            Sequential::Loop => "loop statement",
        }
    }
}