anathema-templates 0.2.6

Anathema template parser (aml)
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
use std::collections::HashMap;

use anathema_store::slab::{Slab, SlabIndex};

use crate::expressions::Expression;

#[derive(Debug, Default, Clone)]
pub struct Globals(HashMap<String, Variable>);

impl Globals {
    pub fn empty() -> Self {
        Self(HashMap::new())
    }

    pub fn new(hm: HashMap<String, Variable>) -> Self {
        Self(hm)
    }

    pub fn get(&self, ident: &str) -> Option<&Expression> {
        match self.0.get(ident) {
            Some(Variable::Global(expr)) => Some(expr),
            _ => None,
        }
    }

    pub fn take(&mut self) -> Self {
        std::mem::take(self)
    }
}

impl From<Variables> for Globals {
    fn from(value: Variables) -> Self {
        Self(value.into())
    }
}

#[derive(Debug, Copy, Clone, PartialEq)]
pub struct VarId(usize);

impl SlabIndex for VarId {
    const MAX: usize = usize::MAX;

    fn as_usize(&self) -> usize {
        self.0
    }

    fn from_usize(index: usize) -> Self
    where
        Self: Sized,
    {
        Self(index)
    }
}

#[derive(Debug, Clone)]
pub enum Variable {
    LocalIdent,
    Global(Expression),
}

// #[derive(Debug, Clone, PartialEq)]
// pub enum Variable {
//     Static(Primitive),
//     Str(Rc<str>),
// }

// impl From<&str> for Variable {
//     fn from(value: &str) -> Self {
//         Self::Str(value.into())
//     }
// }

// impl From<Primitive> for Variable {
//     fn from(value: Primitive) -> Self {
//         Self::Static(value)
//     }
// }

/// The scope id acts as a path made up of indices
/// into the scope tree.
/// E.g `[0, 1, 0]` would point to `root.children[0].children[1].children[0]`.
#[derive(Debug, Clone, PartialEq, PartialOrd)]
pub struct ScopeId(Box<[u16]>);

impl ScopeId {
    // Create the next child id.
    #[cfg(test)]
    fn next(&self, index: u16) -> Self {
        let mut scope_id = Vec::with_capacity(self.0.len() + 1);
        scope_id.extend_from_slice(&self.0);
        scope_id.push(index);
        Self(scope_id.into())
    }

    // Get the parent id as a slice.
    #[cfg(test)]
    fn parent(&self) -> &[u16] {
        // Can't get the parent of the root
        debug_assert!(self.0.len() > 1);

        let to = self.0.len() - 1;
        &self.0[..to]
    }

    // Check if either `id` or `self` is a sub path of the other.
    // If it is, return the length of the shortest of the two.
    #[cfg(test)]
    fn sub_path_len(&self, id: impl AsRef<[u16]>) -> Option<usize> {
        let id = id.as_ref();
        let len = id.len().min(self.0.len());
        let lhs = &self.0[..len];
        let rhs = &id[..len];
        (lhs == rhs).then_some(len)
    }

    #[cfg(test)]
    fn as_slice(&self) -> &[u16] {
        &self.0
    }

    #[cfg(test)]
    // Does other contain self
    fn contains(&self, other: impl AsRef<[u16]>) -> Option<&ScopeId> {
        let other = other.as_ref();
        let len = self.0.len();

        match other.len() >= len {
            true => (*self.0 == other[..len]).then_some(self),
            false => None,
        }
    }
}

impl AsRef<[u16]> for ScopeId {
    fn as_ref(&self) -> &[u16] {
        &self.0
    }
}

impl From<&[u16]> for ScopeId {
    fn from(value: &[u16]) -> Self {
        Self(value.into())
    }
}

impl<const N: usize> From<[u16; N]> for ScopeId {
    fn from(value: [u16; N]) -> Self {
        Self(value.into())
    }
}

#[derive(Debug)]
struct RootScope(Scope);

impl Default for RootScope {
    fn default() -> Self {
        Self(Scope::new(ScopeId(vec![0].into())))
    }
}

impl RootScope {
    fn get_scope_mut(&mut self, id: impl AsRef<[u16]>) -> &mut Scope {
        let mut scope = &mut self.0;
        let mut id = &id.as_ref()[1..];

        while !id.is_empty() {
            scope = &mut scope.children[id[0] as usize];
            id = &id[1..];
        }

        scope
    }

    // Get the value id "closest" to the given scope id.
    //
    // e.g
    // ident0 @ scope [0]
    // ident1 @ scope [0, 0]
    // ident2 @ scope [0, 1]
    // ident3 @ scope [0, 1, 1]
    //
    // given an id of [0, 1, 1, 2, 3] would find `ident3` as the closest.
    //
    // If there is no value with the given ident within reach
    // then return `None`.
    fn get_var_id(&self, id: impl AsRef<[u16]>, ident: &str) -> Option<VarId> {
        let mut scope = &self.0;
        let mut id = &id.as_ref()[1..];
        let mut var = self.0.variables.get(ident).and_then(|values| values.last()).copied();

        while !id.is_empty() {
            scope = &scope.children[id[0] as usize];
            id = &id[1..];

            if let val @ Some(_) = scope.variables.get(ident).and_then(|values| values.last()).copied() {
                var = val;
            }
        }

        var
    }

    #[cfg(test)]
    fn id(&self) -> &ScopeId {
        &self.0.id
    }

    #[cfg(test)]
    fn insert(&mut self, ident: impl Into<String>, var: VarId) {
        self.0.insert(ident.into(), var)
    }

    #[cfg(test)]
    fn create_child(&mut self) -> ScopeId {
        self.0.create_child()
    }
}

/// A scope stores versioned values
#[derive(Debug)]
pub struct Scope {
    variables: HashMap<String, Vec<VarId>>,
    id: ScopeId,
    children: Vec<Scope>,
}

impl Scope {
    fn new(id: ScopeId) -> Self {
        Self {
            id,
            variables: Default::default(),
            children: vec![],
        }
    }

    // Create the next child scope id.
    // ```
    // let mut current = ScopeId::from([0]);
    // let next = current.next_scope(); // scope 0,0
    // let next = current.next_scope(); // scope 0,1
    // ```
    #[cfg(test)]
    fn create_child(&mut self) -> ScopeId {
        let index = self.children.len();
        let id = self.id.next(index as u16);
        self.children.push(Scope::new(id.clone()));
        id
    }

    // Every call to `insert` will shadow the previous value, not replace it.
    fn insert(&mut self, ident: impl Into<String>, value: VarId) {
        let entry = self.variables.entry(ident.into()).or_default();
        entry.push(value);
    }
}

#[derive(Debug)]
struct Declarations(HashMap<String, Vec<(ScopeId, VarId)>>);

impl Declarations {
    fn new() -> Self {
        Self(HashMap::new())
    }

    fn add(&mut self, ident: impl Into<String>, id: impl Into<ScopeId>, value_id: impl Into<VarId>) {
        let value_id = value_id.into();
        let ids = self.0.entry(ident.into()).or_default();
        ids.push((id.into(), value_id));
    }

    #[cfg(test)]
    // Get the scope id that is closest to the argument
    fn get(&self, ident: &str, id: impl AsRef<[u16]>) -> Option<(&ScopeId, VarId)> {
        self.0
            .get(ident)
            .unwrap()
            .iter()
            .rev()
            .filter_map(|(scope, value)| scope.contains(&id).map(|s| (s, *value)))
            .next()
    }

    #[cfg(test)]
    fn get_ref(&self, ident: &str, id: impl AsRef<[u16]>) -> &[u16] {
        self.get(ident, id).unwrap().0.as_ref()
    }
}

/// Variable access, declaration and assignment
/// during the compilation step.
#[derive(Debug)]
pub struct Variables {
    root: RootScope,
    current: ScopeId,
    store: Slab<VarId, Variable>,
    declarations: Declarations,
}

impl Default for Variables {
    fn default() -> Self {
        let root = RootScope::default();
        Self {
            current: root.0.id.clone(),
            root,
            store: Slab::empty(),
            declarations: Declarations::new(),
        }
    }
}

impl Variables {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn take(&mut self) -> Self {
        std::mem::take(self)
    }

    fn declare_at(&mut self, ident: impl Into<String>, var_id: VarId, id: ScopeId) -> VarId {
        let ident = ident.into();
        let scope = self.root.get_scope_mut(id);
        scope.insert(ident.clone(), var_id);
        self.declarations.add(ident, scope.id.clone(), var_id);
        var_id
    }

    pub fn declare(&mut self, ident: impl Into<String>, value: impl Into<Expression>) -> VarId {
        let value = value.into();
        let var_id = self.store.insert(Variable::Global(value));
        let scope_id = self.current.clone();
        self.declare_at(ident, var_id, scope_id)
    }

    pub fn declare_local(&mut self, ident: impl Into<String>) -> VarId {
        let value = Variable::LocalIdent;
        let var_id = self.store.insert(value);
        let scope_id = self.current.clone();
        self.declare_at(ident, var_id, scope_id)
    }

    /// Fetch a value starting from the current path.
    pub fn fetch(&self, ident: &str) -> Option<Expression> {
        self.root
            .get_var_id(&self.current, ident)
            .and_then(|id| self.store.get(id).cloned())
            .and_then(|val| match val {
                Variable::Global(expression) => Some(expression),
                Variable::LocalIdent => None,
            })
    }

    /// Create a new child and set the new childs id as the `current` id.
    /// Any operations done from here on out are acting upon the new child scope.
    #[cfg(test)]
    pub(crate) fn push(&mut self) {
        let parent = self.root.get_scope_mut(&self.current);
        self.current = parent.create_child();
    }

    /// Pop the current child scope, making the current into the parent of
    /// the child.
    ///
    /// E.e if the current id is `[0, 1, 2]` `pop` would result in a new
    /// id of `[0, 1]`.
    #[cfg(test)]
    pub(crate) fn pop(&mut self) {
        // panic!("drain and insert phi");
        self.current = self.current.parent().into();
    }

    #[cfg(test)]
    fn by_value_ref(&self, var: VarId) -> Expression {
        self.store
            .get(var)
            .cloned()
            .map(|val| match val {
                Variable::LocalIdent => unreachable!("this is a test function"),
                Variable::Global(expression) => expression,
            })
            .expect("it would be an Anathema compilation error if this failed")
    }
}

impl From<Variables> for HashMap<String, Variable> {
    fn from(mut vars: Variables) -> Self {
        let mut hm = HashMap::new();

        for (key, mut ids) in vars.declarations.0.into_iter() {
            let (_, var_id) = ids
                .pop()
                .expect("there is always at least one var id associated with a key");
            let val = vars.store.remove(var_id);
            hm.insert(key, val);
        }

        hm
    }
}

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

    impl From<usize> for VarId {
        fn from(value: usize) -> Self {
            VarId(value)
        }
    }

    #[test]
    fn scope_id_next() {
        let id = ScopeId::from([0]);
        assert_eq!(id.next(0).as_slice(), &[0, 0]);
    }

    #[test]
    fn scope_id_parent() {
        let id = ScopeId::from([1, 0]);
        assert_eq!(id.parent(), &[1]);
    }

    #[test]
    fn scope_min() {
        let a = ScopeId::from([1, 0]);
        let b = ScopeId::from([1, 0, 0, 1]);
        let expected = [1, 0].len();
        let actual = a.sub_path_len(b).unwrap();
        assert_eq!(actual, expected);
    }

    #[test]
    fn create_child() {
        let mut root = RootScope::default();
        let child_id = root.create_child();
        assert_eq!(root.0.children.len(), 1);
        assert_eq!(child_id.as_ref(), &[0, 0]);
    }

    #[test]
    fn get_value() {
        let expected: VarId = 123.into();

        let mut root = RootScope::default();
        root.insert("var", expected);
        let actual = root.get_var_id(root.id(), "var").unwrap();
        assert_eq!(expected, actual);
    }

    #[test]
    fn child_get_value() {
        let expected: VarId = 1.into();
        let ident = "var";

        let mut root = RootScope::default();
        let child_id = root.create_child();
        let child = root.get_scope_mut(&child_id);
        child.insert(ident, expected);
        let actual = root.get_var_id(&child_id, ident).unwrap();
        assert_eq!(expected, actual);
    }

    #[test]
    fn variable_declaration() {
        let mut vars = Variables::new();
        let expected = Expression::from(123i64);

        vars.declare("var", expected.clone());
        let value = vars.fetch("var").unwrap();

        assert_eq!(expected, value);
    }

    #[test]
    fn shadow_value() {
        let ident = "var";
        let mut vars = Variables::new();
        let value_a = Expression::from("1");
        let value_b = Expression::from("2");

        let first_value_ref = vars.declare(ident, value_a.clone());
        let second_value_ref = vars.declare(ident, value_b.clone());
        assert_eq!(value_a, vars.by_value_ref(first_value_ref));
        assert_eq!(value_b, vars.by_value_ref(second_value_ref));
    }

    #[test]
    fn scoping_variables_inaccessible_sibling() {
        // Declare a variable in a sibling and fail to access that value
        let mut vars = Variables::new();
        let ident = "var";

        vars.push();
        vars.declare(ident, "inaccessible");
        assert!(vars.fetch(ident).is_some());
        vars.pop();

        // Here we should have no access to the value via the root.
        assert!(vars.fetch(ident).is_none());

        // Here we should have no access to the value via the sibling.
        vars.push();
        assert!(vars.fetch(ident).is_none());
    }

    #[test]
    fn declaration_lookup() {
        let mut dec = Declarations::new();
        dec.add("var", [0], 0);
        let root = dec.get_ref("var", [0, 0]);
        assert_eq!(root, &[0]);
    }

    #[test]
    fn declaration_failed_lookup() {
        let mut dec = Declarations::new();
        dec.add("var", [0], 0);
        let root = dec.get("var", [1, 0]);
        assert!(root.is_none());
    }

    #[test]
    fn multi_level_declarations() {
        let mut dec = Declarations::new();
        let ident = "var";
        dec.add(ident, [0], 0);
        dec.add(ident, [0, 0], 0);
        dec.add(ident, [0, 0, 0], 0);

        assert_eq!(dec.get_ref(ident, [0, 0]), &[0, 0]);
        assert_eq!(dec.get_ref(ident, [0, 0, 0, 1, 1]), &[0, 0, 0]);
    }

    #[test]
    fn unreachable_declaration() {
        let mut dec = Declarations::new();
        dec.add("var", [0, 1], 0);
        assert!(dec.get("var", [0, 0, 1]).is_none());
    }
}