vhdl_lang 0.21.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
// 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) 20, Olof Kraigher olof.kraigher@gmail.com
use super::region::Region;
use crate::ast::*;
use crate::data::*;
use arc_swap::ArcSwapWeak;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Weak};

pub enum NamedEntityKind {
    NonObjectAlias(Arc<NamedEntity>),
    ExternalAlias {
        class: ExternalObjectClass,
        type_mark: Arc<NamedEntity>,
    },
    ObjectAlias {
        base_object: ObjectEnt,
        type_mark: Arc<NamedEntity>,
    },
    File,
    InterfaceFile(Arc<NamedEntity>),
    Component,
    Attribute,
    SubprogramDecl(Signature),
    Subprogram(Signature),
    EnumLiteral(Signature),
    // An optional list of implicit declarations
    // Use Weak reference since implicit declaration typically reference the type itself
    TypeDeclaration(Vec<Weak<NamedEntity>>),
    // Indexes are Option<> to handle unknown types
    ArrayType {
        implicit: Vec<Weak<NamedEntity>>,
        indexes: Vec<Option<Arc<NamedEntity>>>,
        elem_type: Arc<NamedEntity>,
    },
    IntegerType(Vec<Weak<NamedEntity>>),
    AccessType(Subtype),
    RecordType(Arc<Region<'static>>),
    ElementDeclaration(Subtype),
    Subtype(Subtype),
    // Weak references since incomplete access types can create cycles
    // The reference is for the full type which is filled in after creation
    IncompleteType(ArcSwapWeak<NamedEntity>),
    InterfaceType,
    Label,
    Object(Object),
    LoopParameter,
    PhysicalLiteral(Arc<NamedEntity>),
    DeferredConstant(Subtype),
    // The region of the protected type which needs to be extendend by the body
    ProtectedType(Arc<Region<'static>>),
    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::ProtectedType(..))
    }

    pub fn is_type(&self) -> bool {
        matches!(
            self,
            NamedEntityKind::IncompleteType(..)
                | NamedEntityKind::ProtectedType(..)
                | NamedEntityKind::InterfaceType
                | NamedEntityKind::Subtype(..)
                | NamedEntityKind::TypeDeclaration(..)
                | NamedEntityKind::ArrayType { .. }
                | NamedEntityKind::IntegerType(..)
                | NamedEntityKind::AccessType(..)
                | NamedEntityKind::RecordType(..)
        )
    }

    pub fn implicit_declarations(&self) -> Vec<Arc<NamedEntity>> {
        let weak = match self {
            NamedEntityKind::TypeDeclaration(ref implicit) => implicit,
            NamedEntityKind::ArrayType { ref implicit, .. } => implicit,
            NamedEntityKind::IntegerType(ref implicit) => implicit,
            _ => {
                return Vec::new();
            }
        };

        weak.iter()
            // We expect the implicit declarations to live as long as the type so unwrap
            .map(|ent| ent.upgrade().unwrap())
            .collect()
    }

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

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: Arc<NamedEntity>,
}

impl Subtype {
    pub fn new(type_mark: Arc<NamedEntity>) -> Subtype {
        debug_assert!(type_mark.actual_kind().is_type());
        Subtype { type_mark }
    }

    pub fn type_mark(&self) -> &Arc<NamedEntity> {
        &self.type_mark
    }

    pub fn base_type(&self) -> &Arc<NamedEntity> {
        base_type(&self.type_mark)
    }
}

// Strip aliases and subtypes down to base type
pub fn base_type(ent: &Arc<NamedEntity>) -> &Arc<NamedEntity> {
    match ent.kind() {
        NamedEntityKind::NonObjectAlias(ref ent) => base_type(ent),
        NamedEntityKind::ObjectAlias { type_mark, .. } => base_type(type_mark),
        NamedEntityKind::Subtype(ref ent) => ent.base_type(),
        _ => ent,
    }
}

#[derive(Clone)]
pub struct Parameter {
    /// InterfaceObject or InterfaceFile
    param: Arc<NamedEntity>,
}

#[derive(Clone, Default)]
pub struct ParameterList {
    params: Vec<Parameter>,
}

impl Parameter {
    pub fn new(param: Arc<NamedEntity>) -> Self {
        debug_assert!(matches!(
            param.kind(),
            NamedEntityKind::Object(Object { mode: Some(_), .. })
                | NamedEntityKind::InterfaceFile(..)
        ));
        Self { param }
    }

    pub fn has_default(&self) -> bool {
        if let NamedEntityKind::Object(Object { has_default, .. }) = self.param.kind() {
            *has_default
        } else {
            false
        }
    }

    pub fn base_type(&self) -> &NamedEntity {
        match self.param.kind() {
            NamedEntityKind::Object(obj) => obj.subtype.base_type(),
            NamedEntityKind::InterfaceFile(file_type) => file_type.base_type(),
            _ => {
                unreachable!();
            }
        }
    }

    pub fn type_mark(&self) -> &NamedEntity {
        match self.param.kind() {
            NamedEntityKind::Object(obj) => obj.subtype.type_mark(),
            NamedEntityKind::InterfaceFile(file_type) => file_type,
            _ => {
                unreachable!();
            }
        }
    }
}

impl ParameterList {
    pub fn add_param(&mut self, param: Arc<NamedEntity>) {
        self.params.push(Parameter::new(param));
    }
}

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

impl Signature {
    pub fn new(params: ParameterList, return_type: Option<Arc<NamedEntity>>) -> Signature {
        if let Some(ref return_type) = return_type {
            debug_assert!(return_type.actual_kind().is_type());
        }
        Signature {
            params,
            return_type,
        }
    }

    pub fn key(&self) -> SignatureKey {
        let params = self
            .params
            .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.params.iter().enumerate() {
            result.push_str(&param.type_mark().designator().to_string());

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

        if !self.params.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.params.iter().all(|param| param.has_default())
    }

    pub fn return_type(&self) -> Option<&NamedEntity> {
        self.return_type.as_ref().map(|ent| ent.as_ref())
    }

    pub fn return_base_type(&self) -> Option<&NamedEntity> {
        self.return_type().map(|ent| ent.base_type())
    }

    pub fn match_return_type(&self, typ: &NamedEntity) -> bool {
        if let Some(return_type) = self.return_base_type() {
            return_type == typ
        } else {
            false
        }
    }
}

#[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,
    implicit: bool,
    /// 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, kind, decl_pos)
    }

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

    pub fn new_with_opt_id(
        id: Option<EntityId>,
        designator: impl Into<Designator>,
        kind: NamedEntityKind,
        decl_pos: Option<&SrcPos>,
    ) -> NamedEntity {
        NamedEntity {
            id: id.unwrap_or_else(new_id),
            implicit: false,
            decl_pos: decl_pos.cloned(),
            designator: designator.into(),
            kind,
        }
    }

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

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

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

    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
    }

    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.as_ref(),
        )
    }

    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 as_actual(&self) -> &NamedEntity {
        match self.kind() {
            NamedEntityKind::NonObjectAlias(ref ent) => ent.as_actual(),
            _ => self,
        }
    }

    /// Strip aliases and subtypes down to base type
    pub fn base_type(&self) -> &NamedEntity {
        match self.kind() {
            NamedEntityKind::NonObjectAlias(ref ent) => ent.base_type(),
            NamedEntityKind::ObjectAlias { ref type_mark, .. } => type_mark.base_type(),
            NamedEntityKind::Subtype(ref subtype) => subtype.base_type(),
            NamedEntityKind::Object(ref ent) => ent.subtype.base_type(),
            NamedEntityKind::DeferredConstant(ref subtype) => subtype.base_type(),
            NamedEntityKind::ElementDeclaration(ref subtype) => subtype.base_type(),
            NamedEntityKind::PhysicalLiteral(ref base_type) => base_type,
            _ => self,
        }
    }

    pub fn type_mark(&self) -> &NamedEntity {
        match self.kind() {
            NamedEntityKind::NonObjectAlias(ref ent) => ent.type_mark(),
            NamedEntityKind::Subtype(ref subtype) => subtype.type_mark(),
            NamedEntityKind::Object(ref ent) => ent.subtype.type_mark(),
            NamedEntityKind::DeferredConstant(ref subtype) => subtype.type_mark(),
            NamedEntityKind::ElementDeclaration(ref subtype) => subtype.type_mark(),
            NamedEntityKind::PhysicalLiteral(ref base_type) => base_type,
            _ => 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::NonObjectAlias(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)]
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");
        }
    }
}