vhdl_lang 0.24.0

VHDL Language Frontend
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
// 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 super::formal_region::FormalRegion;
use super::implicits::ImplicitVec;
use super::region::Region;
use crate::ast::*;
use crate::data::*;
use arc_swap::ArcSwapWeak;
use fnv::FnvHashSet;
use std::borrow::Borrow;
use std::ops::Deref;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;

pub enum Type {
    // Some types have an optional list of implicit declarations
    // Use Weak reference since implicit declaration typically reference the type itself
    Array {
        implicit: ImplicitVec,
        // Indexes are Option<> to handle unknown types
        indexes: Vec<Option<Arc<NamedEntity>>>,
        elem_type: TypeEnt,
    },
    Enum(ImplicitVec, FnvHashSet<Designator>),
    Integer(ImplicitVec),
    Real(ImplicitVec),
    Physical(ImplicitVec),
    Access(Subtype, ImplicitVec),
    Record(Arc<Region<'static>>),
    // Weak references since incomplete access types can create cycles
    // The reference is for the full type which is filled in after creation
    Incomplete(ArcSwapWeak<NamedEntity>),
    Subtype(Subtype),
    // The region of the protected type which needs to be extendend by the body
    Protected(Arc<Region<'static>>),
    File(ImplicitVec),
    Interface,
    Alias(TypeEnt),
}

impl Type {
    pub fn implicit_declarations(&self) -> impl Iterator<Item = Arc<NamedEntity>> + '_ {
        self.implicits().into_iter().flat_map(|imp| imp.iter())
    }

    pub fn implicits(&self) -> Option<&ImplicitVec> {
        match self {
            Type::Array { ref implicit, .. } => Some(implicit),
            Type::Enum(ref implicit, _) => Some(implicit),
            Type::Real(ref implicit) => Some(implicit),
            Type::Integer(ref implicit) => Some(implicit),
            Type::Physical(ref implicit) => Some(implicit),
            Type::File(ref implicit) => Some(implicit),
            Type::Access(.., ref implicit) => Some(implicit),
            Type::Incomplete(..)
            | Type::Interface
            | Type::Protected(..)
            | Type::Record(..)
            | Type::Subtype(..)
            | Type::Alias(..) => None,
        }
    }

    pub fn describe(&self) -> &str {
        match self {
            Type::Alias(..) => "alias",
            Type::Record(..) => "record type",
            Type::Array { .. } => "array type",
            Type::Enum(..) => "type",
            Type::Integer(..) => "integer type",
            Type::Real(..) => "real type",
            Type::Physical(..) => "physical type",
            Type::Access(..) => "access type",
            Type::Subtype(..) => "subtype",
            Type::Incomplete(..) => "type",
            Type::Interface => "type",
            Type::File(..) => "file type",
            Type::Protected(..) => "protected type",
        }
    }
}

pub enum NamedEntityKind {
    NonObjectAlias(Arc<NamedEntity>),
    ExternalAlias {
        class: ExternalObjectClass,
        type_mark: TypeEnt,
    },
    ObjectAlias {
        base_object: ObjectEnt,
        type_mark: TypeEnt,
    },
    File(Subtype),
    InterfaceFile(TypeEnt),
    Component(Region<'static>),
    Attribute,
    SubprogramDecl(Signature),
    Subprogram(Signature),
    EnumLiteral(Signature),
    // An optional list of implicit declarations
    // Use Weak reference since implicit declaration typically reference the type itself
    Type(Type),
    ElementDeclaration(Subtype),
    Label,
    Object(Object),
    LoopParameter,
    PhysicalLiteral(TypeEnt),
    DeferredConstant(Subtype),
    Library,
    Entity(Arc<Region<'static>>),
    Configuration(Arc<Region<'static>>),
    Package(Arc<Region<'static>>),
    UninstPackage(Arc<Region<'static>>),
    PackageInstance(Arc<Region<'static>>),
    Context(Arc<Region<'static>>),
    LocalPackageInstance(Arc<Region<'static>>),
}

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

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

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

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

    pub fn implicit_declarations(&self) -> impl Iterator<Item = Arc<NamedEntity>> + '_ {
        match self {
            NamedEntityKind::Type(typ) => Some(typ.implicit_declarations()),
            _ => None,
        }
        .into_iter()
        .flatten()
    }

    pub fn describe(&self) -> &str {
        use NamedEntityKind::*;
        match self {
            NonObjectAlias(..) => "alias",
            ObjectAlias { .. } => "object alias",
            ExternalAlias { .. } => "external alias",
            File(..) => "file",
            InterfaceFile(..) => "file",
            ElementDeclaration(..) => "element declaration",
            Component(..) => "component",
            Attribute => "attribute",
            SubprogramDecl(signature) | Subprogram(signature) => {
                if signature.return_type.is_some() {
                    "function"
                } else {
                    "procedure"
                }
            }
            EnumLiteral(..) => "enum literal",
            Label => "label",
            LoopParameter => "loop parameter",
            Object(object) => object.class.describe(),
            PhysicalLiteral(..) => "physical literal",
            DeferredConstant(..) => "deferred constant",
            Library => "library",
            Entity(..) => "entity",
            Configuration(..) => "configuration",
            Package(..) => "package",
            UninstPackage(..) => "uninstantiated package",
            PackageInstance(..) => "package instance",
            Context(..) => "context",
            LocalPackageInstance(..) => "package instance",
            Type(typ) => typ.describe(),
        }
    }
}

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

/// An object or an interface object,
/// example signal, variable, constant
/// Is either an object (mode = None) or an interface object (mode = Some)
#[derive(Clone)]
pub struct Object {
    pub class: ObjectClass,
    pub mode: Option<Mode>,
    pub subtype: Subtype,
    pub has_default: bool,
}

#[derive(Clone)]
pub struct Subtype {
    type_mark: TypeEnt,
}

impl Subtype {
    pub fn new(type_mark: TypeEnt) -> Subtype {
        Subtype { type_mark }
    }

    pub fn type_mark(&self) -> &TypeEnt {
        &self.type_mark
    }

    pub fn base_type(&self) -> &TypeEnt {
        let flat = self.type_mark.flatten_alias();
        match flat.kind() {
            Type::Subtype(ref subtype) => subtype.base_type(),
            _ => flat.base_type(),
        }
    }
}

#[derive(Clone)]
pub struct Signature {
    /// Vector of InterfaceObject or InterfaceFile
    pub params: FormalRegion,
    return_type: Option<TypeEnt>,
}

impl Signature {
    pub fn new(params: FormalRegion, return_type: Option<TypeEnt>) -> Signature {
        Signature {
            params,
            return_type: return_type.as_ref().map(TypeEnt::to_owned),
        }
    }

    pub fn key(&self) -> SignatureKey {
        let params = self
            .params
            .iter()
            .map(|param| param.base_type().id())
            .collect();
        let return_type = self.return_type.as_ref().map(|ent| ent.base_type().id());

        SignatureKey {
            params,
            return_type,
        }
    }

    pub fn describe(&self) -> String {
        let mut result = String::new();
        result.push('[');
        for (i, param) in self.params.iter().enumerate() {
            result.push_str(&param.type_mark().designator().to_string());

            if i + 1 < self.params.len() {
                result.push_str(", ");
            }
        }

        if !self.params.is_empty() && self.return_type.is_some() {
            result.push(' ');
        }

        if let Some(ref return_type) = self.return_type {
            result.push_str("return ");
            result.push_str(&return_type.designator().to_string());
        }

        result.push(']');
        result
    }

    /// Returns true if the function has no arguments
    /// or all arguments have defaults
    pub fn can_be_called_without_parameters(&self) -> bool {
        self.params.iter().all(|param| param.has_default())
    }

    pub fn can_be_called_with_single_parameter(&self, typ: &TypeEnt) -> bool {
        let mut params = self.params.iter();
        if let Some(first) = params.next() {
            if params.all(|param| param.has_default()) {
                return first.base_type() == typ.base_type();
            }
        }
        false
    }

    pub fn return_type(&self) -> Option<&TypeEnt> {
        self.return_type.as_ref()
    }

    pub fn match_return_type(&self, typ: Option<&TypeEnt>) -> bool {
        self.return_type().map(|ent| ent.base_type()) == typ.map(|ent| ent.base_type())
    }
}

#[derive(Clone, PartialEq, Eq, Hash, Debug)]
pub struct SignatureKey {
    params: Vec<EntityId>,
    return_type: Option<EntityId>,
}

impl SignatureKey {
    pub fn new(params: Vec<EntityId>, return_type: Option<EntityId>) -> SignatureKey {
        SignatureKey {
            params,
            return_type,
        }
    }
}

impl ObjectClass {
    fn describe(&self) -> &str {
        use ObjectClass::*;
        match self {
            Constant => "constant",
            Variable => "variable",
            Signal => "signal",
            SharedVariable => "shared variable",
        }
    }
}

#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
pub struct EntityId {
    id: usize,
}

/// A named entity as defined in LRM 6.1.
///
/// Every declaration creates one or more named entities.
#[derive(Debug)]
pub struct NamedEntity {
    /// A unique id of the entity.
    /// Entities with the same id will be the same.
    id: EntityId,
    pub implicit_of: Option<Arc<NamedEntity>>,
    /// The location where the declaration was made.
    /// Builtin and implicit declaration will not have a source position.
    designator: Designator,
    kind: NamedEntityKind,
    decl_pos: Option<SrcPos>,
}

impl NamedEntity {
    pub fn new(
        designator: impl Into<Designator>,
        kind: NamedEntityKind,
        decl_pos: Option<&SrcPos>,
    ) -> NamedEntity {
        NamedEntity::new_with_id(new_id(), designator.into(), kind, decl_pos.cloned())
    }

    pub fn new_with_id(
        id: EntityId,
        designator: Designator,
        kind: NamedEntityKind,
        decl_pos: Option<SrcPos>,
    ) -> NamedEntity {
        NamedEntity {
            id,
            implicit_of: None,
            decl_pos,
            designator,
            kind,
        }
    }

    pub fn implicit(
        of_ent: Arc<NamedEntity>,
        designator: impl Into<Designator>,
        kind: NamedEntityKind,
        decl_pos: Option<&SrcPos>,
    ) -> NamedEntity {
        NamedEntity {
            id: new_id(),
            implicit_of: Some(of_ent),
            decl_pos: decl_pos.cloned(),
            designator: designator.into(),
            kind,
        }
    }

    pub fn id(&self) -> EntityId {
        self.id
    }

    pub fn is_implicit(&self) -> bool {
        self.implicit_of.is_some()
    }

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

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

    pub fn is_explicit(&self) -> bool {
        self.implicit_of.is_none()
    }

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

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

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

    /// Create a copy of this named entity with the same ID but with an updated kind
    /// The use case is to overwrite an entity with a new kind when the full kind cannot
    /// Be created initially due to cyclic dependencies such as when defining an enum literal
    /// With a reference to the enum type where the enum type also needs to know about the literals
    /// @TODO investigate get_mut_unchecked instead
    pub fn clone_with_kind(&self, kind: NamedEntityKind) -> NamedEntity {
        NamedEntity::new_with_id(
            self.id(),
            self.designator.clone(),
            kind,
            self.decl_pos.clone(),
        )
    }

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

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

    pub fn signature(&self) -> Option<&Signature> {
        match self.actual_kind() {
            NamedEntityKind::Subprogram(ref signature)
            | NamedEntityKind::SubprogramDecl(ref signature)
            | NamedEntityKind::EnumLiteral(ref signature) => Some(signature),
            _ => None,
        }
    }

    /// Strip aliases and return reference to actual named entity
    pub fn flatten_alias(ent: &Arc<NamedEntity>) -> &Arc<NamedEntity> {
        match ent.kind() {
            NamedEntityKind::NonObjectAlias(ref ent) => NamedEntity::flatten_alias(ent),
            NamedEntityKind::Type(Type::Alias(ref ent)) => NamedEntity::flatten_alias(&ent.0),
            _ => ent,
        }
    }

    pub fn as_actual(&self) -> &NamedEntity {
        match self.kind() {
            NamedEntityKind::NonObjectAlias(ref ent) => ent.as_actual(),
            NamedEntityKind::Type(Type::Alias(ref ent)) => ent.as_actual(),
            _ => self,
        }
    }

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

    /// Returns true if self is alias of other
    pub fn is_alias_of(&self, other: &NamedEntity) -> bool {
        match self.kind() {
            NamedEntityKind::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 {
            NamedEntityKind::NonObjectAlias(..) => format!(
                "alias '{}' of {}",
                self.designator,
                self.as_actual().describe()
            ),
            NamedEntityKind::Object(Object {
                ref class,
                mode: Some(ref mode),
                ..
            }) => {
                if *class == ObjectClass::Constant {
                    format!("interface {} '{}'", class.describe(), self.designator,)
                } else {
                    format!(
                        "interface {} '{}' : {}",
                        class.describe(),
                        self.designator,
                        mode
                    )
                }
            }
            NamedEntityKind::EnumLiteral(ref signature)
            | NamedEntityKind::SubprogramDecl(ref signature)
            | NamedEntityKind::Subprogram(ref signature) => format!(
                "{} '{}' with signature {}",
                self.kind.describe(),
                self.designator,
                signature.describe()
            ),
            _ => format!("{} '{}'", self.kind.describe(), self.designator),
        }
    }
}

static COUNTER: AtomicUsize = AtomicUsize::new(1);

// Using 64-bits we can create 5 * 10**9 ids per second for 100 years before wrapping
pub fn new_id() -> EntityId {
    EntityId {
        id: COUNTER.fetch_add(1, Ordering::Relaxed),
    }
}

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

// A named entity that is known to be an object
#[derive(Clone, Debug)]
pub struct ObjectEnt {
    pub ent: Arc<NamedEntity>,
}

impl ObjectEnt {
    pub fn new(ent: Arc<NamedEntity>) -> Self {
        debug_assert!(matches!(ent.actual_kind(), NamedEntityKind::Object(..)));
        Self { ent }
    }

    pub fn class(&self) -> ObjectClass {
        self.object().class
    }

    pub fn mode(&self) -> Option<Mode> {
        self.object().mode
    }

    pub fn describe_class(&self) -> String {
        if let Some(mode) = self.mode() {
            if self.class() == ObjectClass::Constant {
                format!("interface {}", self.class())
            } else {
                format!("interface {} of mode {}", self.class(), mode)
            }
        } else {
            format!("{}", self.class())
        }
    }

    pub fn object(&self) -> &Object {
        if let NamedEntityKind::Object(object) = self.ent.actual_kind() {
            object
        } else {
            unreachable!("Must be object");
        }
    }
}

// A named entity that is known to be a type
#[derive(Clone, Debug)]
pub struct TypeEnt(Arc<NamedEntity>);

impl TypeEnt {
    pub fn define_with_opt_id(
        id: Option<EntityId>,
        ident: &mut WithDecl<Ident>,
        kind: Type,
    ) -> TypeEnt {
        let ent = Arc::new(NamedEntity {
            id: id.unwrap_or_else(new_id),
            implicit_of: None,
            decl_pos: Some(ident.tree.pos.clone()),
            designator: ident.tree.item.clone().into(),
            kind: NamedEntityKind::Type(kind),
        });
        ident.decl = Some(ent.clone());
        TypeEnt(ent)
    }

    pub fn from_any(ent: Arc<NamedEntity>) -> Result<TypeEnt, Arc<NamedEntity>> {
        if matches!(ent.kind(), NamedEntityKind::Type(..)) {
            Ok(TypeEnt(ent))
        } else {
            Err(ent)
        }
    }

    pub fn kind(&self) -> &Type {
        if let NamedEntityKind::Type(typ) = self.0.kind() {
            typ
        } else {
            unreachable!("Must be a type");
        }
    }

    // Flatten all aliases
    pub fn flatten_alias(&self) -> &TypeEnt {
        if let Type::Alias(alias) = self.kind() {
            alias.flatten_alias()
        } else {
            self
        }
    }

    pub fn base_type(&self) -> &TypeEnt {
        let actual = self.flatten_alias();
        match actual.kind() {
            Type::Subtype(ref subtype) => subtype.base_type(),
            _ => actual,
        }
    }
}

impl From<TypeEnt> for Arc<NamedEntity> {
    fn from(ent: TypeEnt) -> Self {
        ent.0
    }
}

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

impl std::ops::Deref for TypeEnt {
    type Target = NamedEntity;
    fn deref(&self) -> &NamedEntity {
        let val: &Arc<NamedEntity> = self.0.borrow();
        val.as_ref()
    }
}

/// This trait is implemented for Ast-nodes which declare named entities
pub trait HasNamedEntity {
    fn named_entity(&self) -> Option<&Arc<NamedEntity>>;
}

impl HasNamedEntity for AnyPrimaryUnit {
    fn named_entity(&self) -> Option<&Arc<NamedEntity>> {
        delegate_primary!(self, unit, unit.ident.decl.as_ref())
    }
}

impl WithDecl<Ident> {
    pub fn define(&mut self, kind: NamedEntityKind) -> Arc<NamedEntity> {
        let ent = Arc::new(NamedEntity::new(
            self.tree.name().clone(),
            kind,
            Some(self.tree.pos()),
        ));
        self.decl = Some(ent.clone());
        ent
    }
    pub fn define_with_id(&mut self, id: EntityId, kind: NamedEntityKind) -> Arc<NamedEntity> {
        let ent = Arc::new(NamedEntity::new_with_id(
            id,
            self.tree.name().clone().into(),
            kind,
            Some(self.tree.pos().clone()),
        ));
        self.decl = Some(ent.clone());
        ent
    }
}

impl WithDecl<WithPos<SubprogramDesignator>> {
    pub fn define(&mut self, kind: NamedEntityKind) -> Arc<NamedEntity> {
        let ent = Arc::new(NamedEntity::new(
            self.tree.item.clone().into_designator(),
            kind,
            Some(&self.tree.pos),
        ));
        self.decl = Some(ent.clone());
        ent
    }
}

impl WithDecl<WithPos<Designator>> {
    pub fn define(&mut self, kind: NamedEntityKind) -> Arc<NamedEntity> {
        let ent = Arc::new(NamedEntity::new(
            self.tree.item.clone(),
            kind,
            Some(&self.tree.pos),
        ));
        self.decl = Some(ent.clone());
        ent
    }
}

impl SubprogramDeclaration {
    pub fn define(&mut self, kind: NamedEntityKind) -> Arc<NamedEntity> {
        match self {
            SubprogramDeclaration::Function(f) => f.designator.define(kind),
            SubprogramDeclaration::Procedure(p) => p.designator.define(kind),
        }
    }
}