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

//! Enumeration types.

use std::fmt::{self, Display};
use std::iter::{once, repeat};

pub use num::BigInt;

use crate::common::name::{get_name_table, Name};
use crate::ty2::prelude::*;
use crate::ty2::ScalarSubtype;

/// An enumeration type.
///
/// This can either be an `EnumBasetype` or an `EnumSubtype`.
pub trait EnumType: Type {
    /// Convert to a type.
    fn as_type(&self) -> &Type;

    /// The variants of this enumeration type.
    fn variants(&self) -> &[EnumVariant];

    /// The range of variants this type can assume.
    ///
    /// This is used to support subtyping of enumerations, where a subtype might
    /// only accept a subrange of the original variants.
    fn range(&self) -> Range<usize>;

    /// The base type of this enumeration.
    fn base_type(&self) -> &Type;

    /// The resolution function associated with this type.
    fn resolution_func(&self) -> Option<usize> {
        None
    }

    /// Returns `Some` if self is an `EnumBasetype`, `None` otherwise.
    fn as_basetype(&self) -> Option<&EnumBasetype> {
        None
    }

    /// Returns `Some` if self is an `EnumSubtype`, `None` otherwise.
    fn as_subtype(&self) -> Option<&EnumSubtype> {
        None
    }

    /// Returns an `&EnumBasetype` or panics if the type is not a basetype.
    fn unwrap_basetype(&self) -> &EnumBasetype {
        self.as_basetype()
            .expect("enumeration type is not a basetype")
    }

    /// Returns an `&EnumSubtype` or panics if the type is not a subtype.
    fn unwrap_subtype(&self) -> &EnumSubtype {
        self.as_subtype()
            .expect("enumeration type is not a subtype")
    }

    /// Check if two enumeration types are equal.
    fn is_equal(&self, other: &EnumType) -> bool;
}

impl<'t> PartialEq for EnumType + 't {
    fn eq(&self, other: &EnumType) -> bool {
        EnumType::is_equal(self, other)
    }
}

impl<'t> Eq for EnumType + 't {}

macro_rules! common_type_impl {
    () => {
        fn is_scalar(&self) -> bool {
            true
        }

        fn is_discrete(&self) -> bool {
            true
        }

        fn is_numeric(&self) -> bool {
            false
        }

        fn is_composite(&self) -> bool {
            false
        }

        fn as_any(&self) -> AnyType {
            AnyType::Enum(self)
        }
    };
}

/// An enumeration base type.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EnumBasetype {
    /// The enumeration variants.
    lits: Vec<EnumVariant>,
}

impl EnumBasetype {
    /// Create a new enumeration type.
    ///
    /// # Example
    ///
    /// ```
    /// use moore_vhdl::ty2::{Type, EnumBasetype};
    ///
    /// let ty = EnumBasetype::new(vec![
    ///     "first".into(),
    ///     "second".into(),
    ///     '0'.into(),
    ///     '1'.into(),
    /// ]);
    ///
    /// assert_eq!(format!("{}", ty), "(first, second, '0', '1')");
    /// ```
    pub fn new<I: IntoIterator<Item = EnumVariant>>(lits: I) -> EnumBasetype {
        EnumBasetype {
            lits: lits.into_iter().collect(),
        }
    }
}

impl Type for EnumBasetype {
    common_type_impl!();

    fn into_owned<'a>(self) -> OwnedType<'a>
    where
        Self: 'a,
    {
        OwnedType::EnumBasetype(self)
    }

    fn to_owned<'a>(&self) -> OwnedType<'a>
    where
        Self: 'a,
    {
        OwnedType::EnumBasetype(self.clone())
    }
}

impl EnumType for EnumBasetype {
    fn as_type(&self) -> &Type {
        self
    }

    fn variants(&self) -> &[EnumVariant] {
        &self.lits
    }

    fn range(&self) -> Range<usize> {
        Range::ascending(0usize, self.lits.len())
    }

    fn base_type(&self) -> &Type {
        self
    }

    fn as_basetype(&self) -> Option<&EnumBasetype> {
        Some(self)
    }

    fn is_equal(&self, other: &EnumType) -> bool {
        other.as_basetype().map(|t| self == t).unwrap_or(false)
    }
}

impl Display for EnumBasetype {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "(")?;
        for (sep, lit) in once("").chain(repeat(", ")).zip(self.lits.iter()) {
            write!(f, "{}{}", sep, lit)?;
        }
        write!(f, ")")?;
        Ok(())
    }
}

/// A subtype of an enumeration type.
pub type EnumSubtype<'t> = ScalarSubtype<'t, EnumType, usize>;

impl<'t> EnumSubtype<'t> {
    /// Create a new enumeration subtype.
    ///
    /// # Example
    ///
    /// ```
    /// use moore_vhdl::ty2::{Type, TypeMark, EnumBasetype, EnumSubtype, Range};
    /// use moore_common::name::get_name_table;
    ///
    /// let ty = EnumBasetype::new(vec![
    ///     "first".into(),
    ///     "second".into(),
    ///     '0'.into(),
    ///     '1'.into(),
    /// ]);
    /// let tm = TypeMark::new(
    ///     get_name_table().intern("MY_TYPE", false),
    ///     &ty,
    /// );
    /// let subty = EnumSubtype::new(&tm, Range::ascending(1usize, 2usize)).unwrap();
    ///
    /// assert_eq!(format!("{}", subty), "MY_TYPE range second to '0'");
    /// ```
    pub fn new(mark: &'t TypeMark<'t>, range: Range<usize>) -> Option<EnumSubtype<'t>> {
        let base = mark.as_any().unwrap_enum();
        let base_range = base.range();
        if base_range.has_subrange(&range) {
            Some(EnumSubtype {
                resfn: None,
                mark: mark,
                base: base,
                con: range,
            })
        } else {
            None
        }
    }
}

impl<'t> Type for EnumSubtype<'t> {
    common_type_impl!();

    fn into_owned<'a>(self) -> OwnedType<'a>
    where
        Self: 'a,
    {
        OwnedType::EnumSubtype(self)
    }

    fn to_owned<'a>(&self) -> OwnedType<'a>
    where
        Self: 'a,
    {
        OwnedType::EnumSubtype(self.clone())
    }
}

impl<'t> EnumType for EnumSubtype<'t> {
    fn as_type(&self) -> &Type {
        self
    }

    fn variants(&self) -> &[EnumVariant] {
        self.base.variants()
    }

    fn range(&self) -> Range<usize> {
        self.con
    }

    fn base_type(&self) -> &Type {
        self.base.as_type()
    }

    fn as_subtype(&self) -> Option<&EnumSubtype> {
        Some(self)
    }

    fn is_equal(&self, other: &EnumType) -> bool {
        other.as_subtype().map(|t| self == t).unwrap_or(false)
    }
}

impl<'t> Display for EnumSubtype<'t> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(
            f,
            "{} range {} {} {}",
            self.mark,
            self.base.variants()[*self.con.left()],
            self.con.dir(),
            self.base.variants()[*self.con.right()],
        )
    }
}

/// An enumeration variant.
///
/// Distinguishes between:
/// - identifier literals such as `FOO`, and
/// - character literals such as `'0'`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum EnumVariant {
    /// An identifier enumeration literal.
    Ident(Name),
    /// A character enumeration ltieral.
    Char(char),
}

impl<'a> From<&'a str> for EnumVariant {
    fn from(n: &'a str) -> EnumVariant {
        EnumVariant::Ident(get_name_table().intern(n, false))
    }
}

impl From<Name> for EnumVariant {
    fn from(n: Name) -> EnumVariant {
        EnumVariant::Ident(n)
    }
}

impl From<char> for EnumVariant {
    fn from(c: char) -> EnumVariant {
        EnumVariant::Char(c)
    }
}

impl Display for EnumVariant {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            EnumVariant::Ident(n) => write!(f, "{}", n),
            EnumVariant::Char(c) => write!(f, "'{}'", c),
        }
    }
}