anathema-templates 0.2.11

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
use anathema_store::smallmap::SmallMap;
use anathema_store::storage::strings::StringId;

use super::const_eval::const_eval;
use super::{Context, Statement, Statements};
use crate::blueprints::{Blueprint, Component, ControlFlow, Else, For, Single, With};
use crate::error::{ErrorKind, Result};
use crate::expressions::{Equality, Expression};
use crate::{ComponentBlueprintId, Primitive};

pub(crate) struct Scope {
    statements: Statements,
}

impl Scope {
    pub(crate) fn new(statements: Statements) -> Self {
        Self { statements }
    }

    pub(crate) fn eval(mut self, ctx: &mut Context<'_>) -> Result<Vec<Blueprint>> {
        let mut output = vec![];

        while let Some(statement) = self.statements.next() {
            match statement {
                Statement::Node(ident) => output.push(self.eval_node(ident, ctx)?),
                Statement::Component(component_id) => output.push(self.eval_component(component_id, ctx)?),
                Statement::For {
                    binding: binding_id,
                    data,
                } => {
                    let binding = ctx.strings.get_unchecked(binding_id);
                    if "state" == binding {
                        return Err(
                            ErrorKind::InvalidStatement(format!("{binding} is a reserved identifier"))
                                .to_error(ctx.template.path()),
                        );
                    }
                    if let Some(expr) = self.eval_for(binding_id, data, ctx)? {
                        output.push(expr);
                    }
                }
                Statement::With { binding, data } => {
                    if let Some(expr) = self.eval_with(binding, data, ctx)? {
                        output.push(expr);
                    }
                }
                Statement::If(cond) => output.push(self.eval_if(cond, ctx)?),
                Statement::Switch(cond) => output.push(self.eval_switch(cond, ctx)?),
                Statement::Declaration {
                    binding,
                    value,
                    is_global,
                } => {
                    let Some(value) = const_eval(value, ctx) else { continue };
                    let binding = ctx.strings.get_unchecked(binding);
                    if binding == "state" {
                        return Err(
                            ErrorKind::InvalidStatement(format!("{binding} is a reserved identifier"))
                                .to_error(ctx.template.path()),
                        );
                    }
                    match is_global {
                        false => _ = ctx.variables.define_local(binding, value),
                        true => match ctx.variables.define_global(binding, value) {
                            Ok(()) => (),
                            Err(kind) => return Err(kind.to_error(ctx.template.path())),
                        },
                    }
                }
                Statement::ComponentSlot(slot_id) => {
                    if let Some(bp) = ctx.slots.get(&slot_id).cloned() {
                        output.push(Blueprint::Slot(bp));
                    }
                }
                Statement::ScopeStart
                | Statement::ScopeEnd
                | Statement::LoadAttribute { .. }
                | Statement::AssociatedFunction { .. }
                | Statement::Else(_)
                | Statement::LoadValue(_)
                | Statement::Case(_)
                | Statement::Default => {
                    return Err(ErrorKind::InvalidStatement(format!("{statement:?}")).to_error(ctx.template.path()));
                }
                Statement::Eof => break,
            }
        }
        Ok(output)
    }

    fn eval_node(&mut self, ident: StringId, ctx: &mut Context<'_>) -> Result<Blueprint> {
        let ident = ctx.strings.get_unchecked(ident);
        let attributes = self.eval_attributes(ctx)?;
        let value = self.statements.take_value().and_then(|v| const_eval(v, ctx));

        ctx.variables.push();
        let children = self.consume_scope(ctx)?;
        ctx.variables.pop();

        let node = Blueprint::Single(Single {
            ident,
            children,
            attributes,
            value,
        });

        Ok(node)
    }

    fn eval_for(&mut self, binding: StringId, data: Expression, ctx: &mut Context<'_>) -> Result<Option<Blueprint>> {
        let Some(data) = const_eval(data, ctx) else { return Ok(None) };
        let binding = ctx.strings.get_unchecked(binding);
        // add binding to globals so nothing can resolve past the binding outside of the loop
        ctx.variables.declare_local(binding.clone());
        let body = self.consume_scope(ctx)?;
        let node = Blueprint::For(For { binding, data, body });
        Ok(Some(node))
    }

    fn eval_with(&mut self, binding: StringId, data: Expression, ctx: &mut Context<'_>) -> Result<Option<Blueprint>> {
        let Some(data) = const_eval(data, ctx) else { return Ok(None) };
        let binding = ctx.strings.get_unchecked(binding);
        // add binding to globals so nothing can resolve past the binding outside of the loop
        ctx.variables.declare_local(binding.clone());
        let body = self.consume_scope(ctx)?;
        let node = Blueprint::With(With { binding, data, body });
        Ok(Some(node))
    }

    fn consume_scope(&mut self, ctx: &mut Context<'_>) -> Result<Vec<Blueprint>> {
        let scope = Scope::new(self.statements.take_scope());
        scope.eval(ctx)
    }

    fn eval_attributes(&mut self, ctx: &mut Context<'_>) -> Result<SmallMap<String, Expression>> {
        let mut hm = SmallMap::empty();

        for (key, value) in self.statements.take_attributes() {
            let Some(value) = const_eval(value, ctx) else { continue };
            let key = ctx.strings.get_unchecked(key);
            hm.set(key, value);
        }

        Ok(hm)
    }

    fn eval_if(&mut self, cond: Expression, ctx: &mut Context<'_>) -> Result<Blueprint> {
        // Const eval fail = static false
        let cond = const_eval(cond, ctx).unwrap_or(Expression::Primitive(Primitive::Bool(false)));
        let body = self.consume_scope(ctx)?;
        if body.is_empty() {
            return Err(ErrorKind::EmptyBody.to_error(ctx.template.path()));
        }

        let mut elses = vec![Else { cond: Some(cond), body }];

        while let Some(cond) = self.statements.next_else() {
            let body = self.consume_scope(ctx)?;
            let cond = cond.and_then(|v| const_eval(v, ctx));

            if body.is_empty() {
                return Err(ErrorKind::EmptyBody.to_error(ctx.template.path()));
            }

            elses.push(Else { cond, body });
        }
        Ok(Blueprint::ControlFlow(ControlFlow { elses }))
    }

    fn eval_switch(&mut self, cond: Expression, ctx: &mut Context<'_>) -> Result<Blueprint> {
        let switch = const_eval(cond, ctx);
        let mut elses = vec![];

        let mut body = self.statements.take_scope();
        let mut default = None;

        while let Some(case) = body.next_case() {
            let cond = match switch {
                Some(ref switch) => Expression::Equality(switch.clone().into(), case.into(), Equality::Eq),
                None => Expression::Primitive(Primitive::Bool(false)),
            };

            let body = match body.is_next_scope() {
                true => body.take_scope(),
                false => body.take_until_case_or_default(),
            };
            let body = Scope::new(body).eval(ctx)?;

            elses.push(Else { cond: Some(cond), body });
        }

        if body.next_default() {
            let body = match body.is_next_scope() {
                true => body.take_scope(),
                false => body.take_until_case_or_default(),
            };
            default = Some(Scope::new(body).eval(ctx)?);
        }

        if let Some(body) = default {
            elses.push(Else { cond: None, body });
        }

        Ok(Blueprint::ControlFlow(ControlFlow { elses }))
    }

    fn eval_component(&mut self, component_id: ComponentBlueprintId, ctx: &mut Context<'_>) -> Result<Blueprint> {
        let parent = ctx.component_parent();

        // Associated functions
        let assoc_functions = self.statements.take_assoc_functions();

        // Attributes
        let attributes = self.eval_attributes(ctx)?;

        // Scope variables to the component
        ctx.variables.push_scope_boundary();

        // Slots
        let mut slots = SmallMap::empty();
        let mut scope = self.statements.take_scope();

        // If the next statement is NOT a slot id then assume $children
        // and still try to take the scope
        if !scope.is_empty() {
            if !scope.is_next_slot() {
                let slot_id = ctx.strings.children();
                let scope = Scope::new(scope);
                let body = scope.eval(ctx)?;
                slots.set(slot_id, body);
            } else {
                // for each slot take the scope and associate it with the slot id
                while let Some(slot_id) = scope.next_slot() {
                    let scope = Scope::new(scope.take_scope());
                    let body = scope.eval(ctx)?;
                    slots.set(slot_id, body);
                }
            }
        }

        let body = ctx.load_component(component_id, slots)?;
        let name_id = ctx.components.name(component_id);
        let name = ctx.strings.get_unchecked(name_id);

        let component = Component {
            name,
            name_id,
            id: component_id,
            body,
            attributes,
            assoc_functions,
            parent,
        };

        ctx.variables.pop_scope_boundary();
        Ok(Blueprint::Component(component))
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use crate::document::Document;
    use crate::{ToSourceKind, single};

    #[test]
    fn eval_node() {
        let mut doc = Document::new("node");
        let (bp, _) = doc.compile().unwrap();
        assert_eq!(bp, single!("node"));
    }

    #[test]
    fn eval_node_with_children() {
        let src = "
        a
            b
        ";
        let mut doc = Document::new(src);
        let (blueprint, _) = doc.compile().unwrap();
        assert_eq!(blueprint, single!(children @ "a", vec![single!("b")]));
    }

    #[test]
    fn eval_nested_nodes() {
        let src = "
            node a
                node a
        ";

        let mut doc = Document::new(src);
        let (blueprint, _) = doc.compile().unwrap();
        assert!(matches!(blueprint, Blueprint::Single(Single { value: Some(_), .. })));
    }

    #[test]
    fn eval_declaration_should_not_uses_reserved_identifiers() {
        let src = "let state = 1";

        let mut doc = Document::new(src);
        let response = doc.compile();
        assert_eq!(
            response.err().unwrap().to_string(),
            "invalid statement: state is a reserved identifier"
        );
    }

    #[test]
    fn for_loop_binding_reserved_identifier() {
        let src = "
        for state in []
            node
        ";

        let mut doc = Document::new(src);
        let response = doc.compile();
        assert_eq!(
            response.err().unwrap().to_string(),
            "invalid statement: state is a reserved identifier"
        );
    }

    #[test]
    fn eval_for() {
        let src = "
            for a in a
                node
        ";
        let mut doc = Document::new(src);
        let (blueprint, _) = doc.compile().unwrap();
        assert!(matches!(blueprint, Blueprint::For(For { .. })));
    }

    #[test]
    fn if_else() {
        let src = "
            if 1 == 2
                text
            else
                border
        ";

        let mut doc = Document::new(src);
        let (blueprint, _) = doc.compile().unwrap();
        let Blueprint::ControlFlow(controlflow) = blueprint else { panic!() };
        assert!(matches!(controlflow.elses[0], Else { .. }));
        assert!(!controlflow.elses.is_empty());
    }

    #[test]
    fn eval_switch_case_single() {
        let src = "
            switch 1 == 2
                case true: text 'yay'
                case false: text 'yay'
        ";

        let mut doc = Document::new(src);
        let (blueprint, _) = doc.compile().unwrap();
        let Blueprint::ControlFlow(controlflow) = blueprint else { panic!() };
        assert!(matches!(controlflow.elses[0], Else { .. }));
        assert!(!controlflow.elses.is_empty());
    }

    #[test]
    fn eval_switch_case_multi_line() {
        let src = "
            switch 1 == 2
                case true: 
                    text 'yay'
                case false: 
                    text 'yay'
                    text 'yay'
        ";

        let mut doc = Document::new(src);
        let (blueprint, _) = doc.compile().unwrap();
        let Blueprint::ControlFlow(controlflow) = blueprint else { panic!() };
        assert!(matches!(controlflow.elses[0], Else { .. }));
        assert!(!controlflow.elses.is_empty());
    }

    #[test]
    fn eval_component() {
        let src = "@comp [a: 1]";
        let comp_src = "node a + 2";

        let mut doc = Document::new(src);
        doc.add_component("comp", comp_src.to_template()).unwrap();
        let (blueprint, _) = doc.compile().unwrap();
        assert!(matches!(blueprint, Blueprint::Component(Component { .. })));
    }

    #[test]
    fn eval_component_slots() {
        // TODO: this test is incomplete.
        // It should verify that node '1' and node '2' are in the components
        // blueprint
        let src = "
            @comp
                $s1
                    node '1'
                $s2
                    node '2'
        ";

        let comp_src = "
            node
                $s1
                $s2
        ";

        let mut doc = Document::new(src);
        doc.add_component("comp", comp_src.to_template()).unwrap();
        let (blueprint, _) = doc.compile().unwrap();
        assert!(matches!(blueprint, Blueprint::Component(Component { .. })));
    }

    #[test]
    fn eval_two_identical_components() {
        let src = "
            vstack
                @comp (a->b) [ a: 1 ]
                @comp (a->b) [ a: 2 ]
        ";

        let mut doc = Document::new(src);
        doc.add_component("comp", "node a".to_template()).unwrap();
        let _ = doc.compile().unwrap();
    }

    #[test]
    fn component_with_assoc_attrs_state() {
        let src = "
            @comp (a->b) [a: 1]
        ";

        let mut doc = Document::new(src);
        doc.add_component("comp", "node a".to_template()).unwrap();
        let _ = doc.compile().unwrap();
    }

    #[test]
    fn with_value() {
        let src = "
            with val as 1 + 1
                text val
        ";

        let mut doc = Document::new(src);
        doc.add_component("comp", "node a".to_template()).unwrap();
        let (blueprint, _) = doc.compile().unwrap();
        assert!(matches!(blueprint, Blueprint::With(With { .. })));
    }
}