Mike Gerwitz

Activist for User Freedom

aboutsummaryrefslogtreecommitdiffstats
blob: d0841d1b925bcea46677108aad1712de5c63c6d4 (plain)
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
// ASG identifiers
//
//  Copyright (C) 2014-2020 Ryan Specialty Group, LLC.
//
//  This file is part of TAME.
//
//  This program is free software: you can redistribute it and/or modify
//  it under the terms of the GNU General Public License as published by
//  the Free Software Foundation, either version 3 of the License, or
//  (at your option) any later version.
//
//  This program is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU General Public License for more details.
//
//  You should have received a copy of the GNU General Public License
//  along with this program.  If not, see <http://www.gnu.org/licenses/>.

//! Identifiers (a type of [object][super::object::IdentObject]).

use crate::ir::legacyir::{SymAttrs, SymDtype, SymType};
use std::convert::TryFrom;
use std::error::Error;

/// Types of identifiers.
///
/// Here, the term _calculation_ refers to a composable expression that
///   produces a numeric result.
///
/// These are derived from [`legacyir::SymType`][crate::ir::legacyir::SymType]
///   and will be generalized in the future.
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum IdentKind {
    /// Classification generator.
    ///
    /// This has the same number of dimensions as its highest-dimension
    ///   predicate.
    /// Every [`Class`][IdentKind::Class] has an associated generator.
    Cgen(Dim),

    /// Boolean classification.
    ///
    /// This is an artifact of an ancient system.
    /// The dimensions here refers to the dimensions of the associated
    ///   [`Cgen`][IdentKind::Cgen].
    Class(Dim),

    /// Constant value.
    Const(Dim, DataType),

    /// Re-usable encapsulated expression.
    ///
    /// Functions are nothing more than expressions that can be re-used with
    ///   dynamic values at runtime.
    /// See also [`Lparam`][IdentKind::Lparam].
    Func(Dim, DataType),

    /// Generating calculation.
    ///
    /// Generators are associated with iterative expressions,
    ///   such as sums and products.
    /// They always have a parent [`Rate`][IdentKind::Rate].
    Gen(Dim, DataType),

    /// Local (non-global) parameter.
    ///
    /// Local parameters are lexically scoped to their parent expression:
    ///   - [`Func`][IdentKind::Func], where there exists one per defined
    ///     function parameter; and
    ///   - `let` expression bindings.
    ///
    /// This is not to be confused with the global
    ///   [`Param`][IdentKind::Param].
    Lparam(Dim, DataType),

    /// Global parameter.
    ///
    /// These parameters serve as inputs to the system.
    /// Input values are bound using [`Map`][IdentKind::Map].
    Param(Dim, DataType),

    /// Scalar result of a named calculation.
    ///
    /// The verb "rate" is historical,
    ///   since TAME was developed for insurance rating systems.
    /// This represents a named expression that yields a scalar value.
    ///
    /// This serves as a parent to [`Gen`][IdentKind::Gen].
    Rate(DataType),

    /// Template definition.
    ///
    /// A template is used only at expansion-time and,
    ///   unlike most other things in the system,
    ///   have no runtime value.
    Tpl,

    /// User-defined data type.
    ///
    /// The only types typically defined are enums and unions of enums.
    /// The type itself has no runtime value,
    ///   but each of the enum variants have an associated value of type
    ///   [`DataType`].
    Type(DataType),

    /// Input map head (meta identifier generated by compiler for each input
    ///   map).
    MapHead,

    /// Input field→param mapping.
    ///
    /// These may only map to [`Param`][IdentKind::Param].
    /// The source data is arbitrary and provided at runtime.
    Map,

    /// Input map tail (meta symbol generated by compiler for each input
    ///   map).
    MapTail,

    /// Return map head (meta symbol generated by compiler for each return
    ///   map).
    RetMapHead,

    /// Return param→field mapping.
    ///
    /// Return mappings export data to calling systems.
    /// They can map back any globally defined numeric expression.
    RetMap,

    /// Return map tail (meta symbol generated by compiler for each return
    ///   map).
    RetMapTail,

    /// Arbitrary metadata.
    ///
    /// This permits the definition of static key/value data that is
    ///   compiled into the final executable.
    Meta,

    /// Rating worksheet (generated by compiler for worksheet packages).
    ///
    /// The worksheet exposes intermediate calculation values in a much more
    ///   concise form than that of the Summary Page.
    Worksheet,
}

impl std::fmt::Display for IdentKind {
    /// Format identifier type for display to the user.
    ///
    /// TODO: We have not yet finalized how we will represent types in the
    ///   new type system,
    ///     so for now this just uses a syntax similar to Rust.
    fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result {
        match self {
            Self::Cgen(dim) => {
                write!(fmt, "cgen[{}; {}]", DataType::Boolean, dim)
            }
            Self::Class(dim) => {
                write!(fmt, "class[{}; {}]", DataType::Boolean, dim)
            }
            Self::Const(dim, dtype) => write!(fmt, "const[{}; {}]", dtype, dim),
            Self::Func(dim, dtype) => write!(fmt, "func[{}; {}]", dtype, dim),
            Self::Gen(dim, dtype) => write!(fmt, "gen[{}; {}]", dtype, dim),
            Self::Lparam(dim, dtype) => {
                write!(fmt, "lparam[{}; {}]", dtype, dim)
            }
            Self::Param(dim, dtype) => write!(fmt, "param[{}; {}]", dtype, dim),
            Self::Rate(dtype) => write!(fmt, "rate[{}; 0]", dtype),
            Self::Tpl => write!(fmt, "tpl"),
            Self::Type(dtype) => write!(fmt, "type[{}]", dtype),
            Self::MapHead => write!(fmt, "map:head"),
            Self::Map => write!(fmt, "map"),
            Self::MapTail => write!(fmt, "map:tail"),
            Self::RetMapHead => write!(fmt, "retmap:head"),
            Self::RetMap => write!(fmt, "retmap"),
            Self::RetMapTail => write!(fmt, "retmap:tail"),
            Self::Meta => write!(fmt, "meta"),
            Self::Worksheet => write!(fmt, "worksheet"),
        }
    }
}

impl<'i> TryFrom<SymAttrs<'i>> for IdentKind {
    type Error = IdentKindError;

    /// Attempt to raise [`SymAttrs`] into an [`IdentKind`].
    ///
    /// Certain [`IdentKind`] require that certain attributes be present,
    ///   otherwise the conversion will fail.
    fn try_from(attrs: SymAttrs<'i>) -> Result<Self, Self::Error> {
        Self::try_from(&attrs)
    }
}

impl<'i> TryFrom<&SymAttrs<'i>> for IdentKind {
    type Error = IdentKindError;

    /// Attempt to raise [`SymAttrs`] into an [`IdentKind`].
    ///
    /// Certain [`IdentKind`] require that certain attributes be present,
    ///   otherwise the conversion will fail.
    fn try_from(attrs: &SymAttrs<'i>) -> Result<Self, Self::Error> {
        let ty = attrs.ty.as_ref().ok_or(Self::Error::MissingType)?;

        macro_rules! ident {
            ($to:expr) => {
                Ok($to)
            };
            ($to:expr, dim) => {
                Ok($to(Dim(attrs.dim.ok_or(Self::Error::MissingDim)?)))
            };
            ($to:expr, dtype) => {
                Ok($to(attrs.dtype.ok_or(Self::Error::MissingDtype)?))
            };
            ($to:expr, dim, dtype) => {
                Ok($to(
                    Dim(attrs.dim.ok_or(Self::Error::MissingDim)?),
                    attrs.dtype.ok_or(Self::Error::MissingDtype)?,
                ))
            };
        }

        match ty {
            SymType::Cgen => ident!(Self::Cgen, dim),
            SymType::Class => ident!(Self::Class, dim),
            SymType::Const => ident!(Self::Const, dim, dtype),
            SymType::Func => ident!(Self::Func, dim, dtype),
            SymType::Gen => ident!(Self::Gen, dim, dtype),
            SymType::Lparam => ident!(IdentKind::Lparam, dim, dtype),
            SymType::Param => ident!(IdentKind::Param, dim, dtype),
            SymType::Rate => ident!(IdentKind::Rate, dtype),
            SymType::Tpl => ident!(IdentKind::Tpl),
            SymType::Type => ident!(IdentKind::Type, dtype),
            SymType::MapHead => ident!(IdentKind::MapHead),
            SymType::Map => ident!(IdentKind::Map),
            SymType::MapTail => ident!(IdentKind::MapTail),
            SymType::RetMapHead => ident!(IdentKind::RetMapHead),
            SymType::RetMap => ident!(IdentKind::RetMap),
            SymType::RetMapTail => ident!(IdentKind::RetMapTail),
            SymType::Meta => ident!(IdentKind::Meta),
            SymType::Worksheet => ident!(IdentKind::Worksheet),
        }
    }
}

#[derive(Debug, PartialEq, Eq)]
pub enum IdentKindError {
    /// Symbol type was not provided.
    MissingType,

    /// Number of symbol dimensions were not provided.
    MissingDim,

    /// Symbol dtype was not provided.
    MissingDtype,
}

impl std::fmt::Display for IdentKindError {
    fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result {
        match self {
            Self::MissingType => write!(fmt, "missing symbol type"),
            Self::MissingDim => write!(fmt, "missing dim"),
            Self::MissingDtype => write!(fmt, "missing dtype"),
        }
    }
}

impl Error for IdentKindError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        None
    }
}

/// Identifier dimensions.
///
/// This determines the number of subscripts needed to access a scalar
///   value.
/// A value of `0` indicates a scalar;
///   a value of `1` indicates a vector;
///   a value of `2` indicates a matrix;
///   and a value of `n` indicates a multi-dimensional array of
///     depth `n`.
#[derive(Debug, PartialEq, Eq, Clone, Copy, Default)]
pub struct Dim(u8);

impl Dim {
    pub fn from_u8(value: u8) -> Self {
        // TODO: 0≤n<10
        Self(value)
    }
}

/// Underlying datatype of identifier.
///
/// TODO: This will always be 0≤n≤9, so let's introduce a newtype for it.
impl AsRef<str> for Dim {
    fn as_ref(&self) -> &str {
        match self.0 {
            0 => &"0",
            1 => &"1",
            2 => &"2",
            3 => &"3",
            4 => &"4",
            5 => &"5",
            6 => &"6",
            7 => &"7",
            8 => &"8",
            9 => &"9",
            _ => unreachable!(),
        }
    }
}

impl std::fmt::Display for Dim {
    fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result {
        (self.0).fmt(fmt)
    }
}

/// Underlying datatype of identifier.
pub type DataType = SymDtype;

#[cfg(test)]
mod test {
    use super::*;
    use std::convert::TryInto;

    #[test]
    fn dim_from_u8() {
        let n = 5u8;

        assert_eq!(Dim(n), Dim::from_u8(n));
    }

    #[test]
    fn dim_to_str() {
        // we'll just test high and low
        let low: &str = Dim(0).as_ref();
        let high: &str = Dim(9).as_ref();

        assert_eq!("0", low);
        assert_eq!("9", high);
    }

    macro_rules! test_kind {
        ($name:ident, $src:expr => $dest:expr) => {
            #[test]
            fn $name() {
                assert_eq!(
                    Ok($dest),
                    SymAttrs {
                        ty: Some($src),
                        ..Default::default()
                    }
                    .try_into()
                );
            }
        };

        ($name:ident, $src:expr => $dest:expr, dim) => {
            #[test]
            fn $name() {
                let dim = 1;

                assert_eq!(
                    Ok($dest(Dim(dim))),
                    SymAttrs {
                        ty: Some($src),
                        dim: Some(dim),
                        ..Default::default()
                    }
                    .try_into()
                );

                // no dim
                let result = IdentKind::try_from(SymAttrs {
                    ty: Some($src),
                    ..Default::default()
                })
                .expect_err("must fail when missing dim");

                assert_eq!(IdentKindError::MissingDim, result);
            }
        };

        ($name:ident, $src:expr => $dest:expr, dtype) => {
            #[test]
            fn $name() {
                let dtype = SymDtype::Float;

                assert_eq!(
                    Ok($dest(dtype)),
                    SymAttrs {
                        ty: Some($src),
                        dtype: Some(dtype),
                        ..Default::default()
                    }
                    .try_into()
                );

                // no dtype
                let result = IdentKind::try_from(SymAttrs {
                    ty: Some($src),
                    ..Default::default()
                })
                .expect_err("must fail when missing dtype");

                assert_eq!(IdentKindError::MissingDtype, result);
            }
        };

        ($name:ident, $src:expr => $dest:expr, dim, dtype) => {
            #[test]
            fn $name() {
                let dim = 1;
                let dtype = SymDtype::Float;

                assert_eq!(
                    Ok($dest(Dim(dim), dtype)),
                    SymAttrs {
                        ty: Some($src),
                        dim: Some(dim),
                        dtype: Some(dtype),
                        ..Default::default()
                    }
                    .try_into()
                );

                // no dim
                let dim_result = IdentKind::try_from(SymAttrs {
                    ty: Some($src),
                    dtype: Some(dtype),
                    ..Default::default()
                })
                .expect_err("must fail when missing dim");

                assert_eq!(IdentKindError::MissingDim, dim_result);

                // no dtype
                let dtype_result = IdentKind::try_from(SymAttrs {
                    ty: Some($src),
                    dim: Some(dim),
                    ..Default::default()
                })
                .expect_err("must fail when missing dtype");

                assert_eq!(IdentKindError::MissingDtype, dtype_result);
            }
        };
    }

    test_kind!(cgen, SymType::Cgen => IdentKind::Cgen, dim);
    test_kind!(class, SymType::Class => IdentKind::Class, dim);
    test_kind!(r#const, SymType::Const => IdentKind::Const, dim, dtype);
    test_kind!(func, SymType::Func => IdentKind::Func, dim, dtype);
    test_kind!(gen, SymType::Gen => IdentKind::Gen, dim, dtype);
    test_kind!(lparam, SymType::Lparam => IdentKind::Lparam, dim, dtype);
    test_kind!(param, SymType::Param => IdentKind::Param, dim, dtype);
    test_kind!(rate, SymType::Rate => IdentKind::Rate, dtype);
    test_kind!(tpl, SymType::Tpl => IdentKind::Tpl);
    test_kind!(r#type, SymType::Type => IdentKind::Type, dtype);
    test_kind!(maphead, SymType::MapHead => IdentKind::MapHead);
    test_kind!(map, SymType::Map => IdentKind::Map);
    test_kind!(maptail, SymType::MapTail => IdentKind::MapTail);
    test_kind!(retmaphead, SymType::RetMapHead => IdentKind::RetMapHead);
    test_kind!(retmap, SymType::RetMap => IdentKind::RetMap);
    test_kind!(retmaptail, SymType::RetMapTail => IdentKind::RetMapTail);
    test_kind!(meta, SymType::Meta => IdentKind::Meta);
    test_kind!(worksheet, SymType::Worksheet => IdentKind::Worksheet);
}