scrusted-yaml 0.2.0

Validates, loads and resolves scripted-yaml files: YAML with FEEL formulas in marked keys, reloaded live.
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
//! Validation of one file (SPEC 5.3): keywords, markers, formula syntax, names, schema, cycles.
//! It runs no marker function and computes no formula but schema rules on items written out.

use rustc_hash::{FxHashMap as HashMap, FxHashSet as HashSet};
use scrusted_feel::{EvalOptions, Formula, Reference, Template, builtins};
use std::sync::Arc;

use crate::node::{EntryId, KeyKind, NodeId, NodeKind, Tree};
use crate::problem::{Place, Problems};
use crate::schema::{Fitter, Shape, clash};
use crate::scope::{Expression, Reach, Scope, Target};
use crate::source::{Model, ROOT_KEYWORDS};

const STRUCTURE: &[&str] = &["$value", "$if", "$unless", "$each", "$as", "$when", "$else"];
const CONDITIONS: &[&str] = &["$if", "$unless", "$each"];
const PATCHING: &[&str] = &["$replace", "$before", "$after", "$add", "$remove"];

/// What validation leaves on the file for loading and resolving.
#[derive(Debug, Default, Clone)]
pub struct Checked {
    /// The formula or template of each node that holds one.
    pub expressions: HashMap<NodeId, Expression>,
    /// The names each expression reads, as written: `vars.URL`, `prerequisites.staging`.
    pub reads: HashMap<NodeId, Vec<String>>,
    /// The shape each map was checked against.
    pub shapes: HashMap<NodeId, Arc<Shape>>,
    /// Every node with an expression, in the order found.
    pub computed: Vec<NodeId>,
}

/// Damerau-Levenshtein distance (optimal string alignment).
fn distance(a: &str, b: &str) -> usize {
    let a: Vec<char> = a.chars().collect();
    let b: Vec<char> = b.chars().collect();
    let mut d = vec![vec![0usize; b.len() + 1]; a.len() + 1];
    for (i, row) in d.iter_mut().enumerate() {
        row[0] = i;
    }
    for (j, cell) in d[0].iter_mut().enumerate() {
        *cell = j;
    }
    for i in 1..=a.len() {
        for j in 1..=b.len() {
            let cost = usize::from(a[i - 1] != b[j - 1]);
            d[i][j] = (d[i - 1][j] + 1).min(d[i][j - 1] + 1).min(d[i - 1][j - 1] + cost);
            if i > 1 && j > 1 && a[i - 1] == b[j - 2] && a[i - 2] == b[j - 1] {
                d[i][j] = d[i][j].min(d[i - 2][j - 2] + 1);
            }
        }
    }
    d[a.len()][b.len()]
}

/// Suggests the name that was probably meant (SPEC 4.3: Damerau-Levenshtein ≤ 2).
pub fn hint(name: &str, candidates: &[String], otherwise: &str) -> String {
    if candidates.iter().any(|c| c.starts_with(&format!("{name}-")) || c.ends_with(&format!("-{name}"))) {
        return "; a key with a dash cannot be read by a formula: name it with an underscore".into();
    }
    let limit = 2.min(1.max(name.chars().count() / 3));
    match candidates.iter().find(|c| c.as_str() != name && distance(name, c) <= limit) {
        Some(close) => format!("; did you mean \"{close}\"?"),
        None => otherwise.to_string(),
    }
}

/// Why a function or an import may not have the name of a built-in.
pub fn taken(what: &str, name: &str) -> String {
    let advice = if builtins::TEXT_FUNCTIONS.contains(&name) {
        format!("remove it and call {name}(text), which is built in, or give it another name")
    } else if builtins::MAP_FUNCTIONS.contains(&name) {
        format!("remove it and call {name}(map, key), which is built in, or give it another name")
    } else {
        "give it another name".to_string()
    };
    format!("the {what} \"{name}\" has the name of a built-in function; {advice}")
}

/// Validates one model.
pub struct Checker<'a> {
    model: &'a mut Model,
    markers: &'a [String],
    computed_markers: &'a std::collections::HashSet<String>,
    problems: &'a mut Problems,
    checked: Checked,
    undeclared: HashSet<String>,
    options: EvalOptions,
}

impl<'a> Checker<'a> {
    /// A checker for a model, with the marker names the application registered.
    pub fn new(
        model: &'a mut Model,
        markers: &'a [String],
        computed_markers: &'a std::collections::HashSet<String>,
        problems: &'a mut Problems,
    ) -> Self {
        Checker {
            model,
            markers,
            computed_markers,
            problems,
            checked: Checked::default(),
            undeclared: HashSet::default(),
            options: EvalOptions::default(),
        }
    }

    /// Runs every check; returns what loading needs.
    pub fn run(mut self) -> Checked {
        let root = self.model.root;
        self.check_map(root, true);
        for e in self.model.functions.values().copied().collect::<Vec<_>>() {
            self.formula(e);
        }
        self.check_function_names();
        if self.model.schema.is_some() && !self.model.data().is_empty() {
            let schema = self.model.schema.take();
            if let Some(schema) = &schema {
                let expressions = &self.checked.expressions;
                let is_formula = |n: NodeId| matches!(expressions.get(&n), Some(Expression::Formula(_)));
                let has_expression = |n: NodeId| expressions.contains_key(&n);
                let mut shapes = HashMap::default();
                Fitter {
                    schema,
                    tree: &mut self.model.tree,
                    problems: self.problems,
                    is_formula: &is_formula,
                    has_expression: &has_expression,
                    shapes: &mut shapes,
                    options: self.options.clone(),
                }
                .check(root);
                self.checked.shapes = shapes;
            }
            self.model.schema = schema;
        }
        for node in self.checked.computed.clone() {
            self.check_names(node);
        }
        self.check_cycles();
        self.checked
    }

    fn tree(&self) -> &Tree {
        &self.model.tree
    }

    // ── keys, keywords, markers, syntax ──

    fn check_map(&mut self, map: NodeId, root: bool) {
        let mut seen: HashMap<String, EntryId> = HashMap::default();
        for e in self.tree().entries_of(map).to_vec() {
            let key = self.tree().entry(e).key.clone();
            if let Some(first) = seen.get(&*key.name) {
                let first_raw = self.tree().entry(*first).key.raw.clone();
                let at = self.tree().entry_place(e);
                self.problems.error(&at, format!("\"{first_raw}\" and \"{}\" are the same key \"{}\": keep one", key.raw, key.name));
            }
            seen.insert(key.name.to_string(), e);
            if root && ROOT_KEYWORDS.contains(&&*key.name) {
                continue;
            }
            if key.keyword() && !self.keyword(e) {
                continue;
            }
            self.check_entry(e);
        }
    }

    /// True when the `$` key is a word of the language that may stand here.
    fn keyword(&mut self, e: EntryId) -> bool {
        let entry = self.tree().entry(e).clone();
        let name = &*entry.key.name;
        let at = self.tree().entry_place(e);
        if ROOT_KEYWORDS.contains(&name) {
            self.problems.error(&at, format!("{name} belongs at the top of the file"));
        } else if PATCHING.contains(&name) {
            self.problems.error(&at, format!("{name} changes a base file: it needs $extends at the top of this file"));
        } else if !STRUCTURE.contains(&name) {
            let candidates: Vec<String> = ROOT_KEYWORDS.iter().chain(STRUCTURE).map(|s| s.to_string()).collect();
            self.problems.error(&at, format!("unknown keyword \"{name}\"{}", hint(name, &candidates, "")));
        } else if CONDITIONS.contains(&name) && entry.key.kind() != KeyKind::Formula {
            self.problems.error(&at, format!("{name} is a formula: write \"{name}!\""));
        } else if name == "$as" {
            let plain = self.tree().scalar_of(entry.value).map(|s| crate::node::js_string(&s.value));
            let ok = plain.as_deref().is_some_and(|p| {
                Formula::parse(p)
                    .ok()
                    .is_some_and(|f| matches!(f.references(), [r] if *r.head == *p && r.path.is_empty() && !p.contains(' ')))
            });
            if !ok {
                self.problems.error(&at, "$as gives one plain name");
            }
        } else if name == "$when" {
            return self.when(e);
        } else {
            return true;
        }
        false
    }

    fn when(&mut self, e: EntryId) -> bool {
        let entry = self.tree().entry(e).clone();
        let tree = self.tree();
        let cases = tree.items(entry.value);
        let fine = entry.key.kind() == KeyKind::Plain
            && tree.is_list(entry.value)
            && !cases.is_empty()
            && cases.iter().all(|c| {
                tree.is_map(*c) && (tree.get(*c, "$if").is_some() || tree.get(*c, "$unless").is_some() || tree.get(*c, "$else").is_some())
            });
        if !fine {
            let at = self.tree().entry_place(e);
            self.problems.error(&at, "$when is a list of cases; each case has $if!, $unless! or $else");
        }
        fine
    }

    fn check_entry(&mut self, e: EntryId) {
        if let Some(base) = self.tree().entry(e).base {
            self.check_entry(base);
        }
        let entry = self.tree().entry(e).clone();
        match entry.key.kind() {
            KeyKind::Marked => {
                let marker = entry.key.marker_name().to_string();
                if !self.markers.contains(&marker) {
                    let at = self.tree().entry_place(e);
                    self.problems.error(&at, format!("no function is registered for the marker \"{marker}\""));
                }
                if self.computed_markers.contains(&marker) {
                    self.check_value(entry.value);
                }
            }
            KeyKind::Formula => self.formula(e),
            KeyKind::Plain => self.check_value(entry.value),
        }
    }

    fn check_value(&mut self, node: NodeId) {
        match self.tree().node(node).kind.clone() {
            NodeKind::Map(_) => self.check_map(node, false),
            NodeKind::List(items) => {
                for item in items {
                    self.check_value(item);
                }
            }
            NodeKind::Scalar(s) => {
                if let Some(text) = s.value.as_str()
                    && Template::holds(text)
                {
                    let at = self.tree().at(node);
                    match Template::parse(text) {
                        Ok(t) => self.expression(node, Expression::Text(t)),
                        Err(error) => self.problems.error(&at, error.message),
                    }
                }
            }
        }
    }

    fn formula(&mut self, e: EntryId) {
        let entry = self.tree().entry(e).clone();
        let at = self.tree().entry_place(e);
        let Some(scalar) = self.tree().scalar_of(entry.value) else {
            self.problems.error(&at, format!("\"{}\" is a formula, so its value is text; for data, remove the \"!\"", entry.key.raw));
            return;
        };
        let text = self.model.function_text.get(&e).cloned().unwrap_or_else(|| scalar.source.to_string());
        match Formula::parse(&text) {
            Ok(f) => self.expression(entry.value, Expression::Formula(f)),
            Err(error) => {
                let message = if error.message.starts_with("not a valid formula") || error.message == "the formula is empty" {
                    error.message
                } else {
                    format!("not a valid formula: {}", error.message)
                };
                self.problems.error(&at, message);
            }
        }
    }

    fn expression(&mut self, node: NodeId, expression: Expression) {
        self.checked.expressions.insert(node, expression);
        self.checked.computed.push(node);
    }

    /// A function may not have the name of a built-in, and a key may not have the name of a function.
    fn check_function_names(&mut self) {
        let mut errors: Vec<(Place, String)> = Vec::new();
        for (name, e) in &self.model.functions {
            let at = self.tree().entry_place(*e);
            if builtins::is_builtin(name) {
                errors.push((at.clone(), taken("function", name)));
            }
            if self.model.imported.contains_key(name) {
                errors.push((at, format!("\"{name}\" is both defined in $functions and imported")));
            }
        }
        for (name, h) in &self.model.hosted {
            let at = self.tree().entry_place(h.entry);
            if builtins::is_builtin(name) {
                errors.push((at.clone(), taken("function", name)));
            }
            if self.model.imported.contains_key(name) {
                errors.push((at, format!("\"{name}\" is both declared in $functions and imported")));
            }
        }
        for (name, spec) in &self.model.imported {
            if builtins::is_builtin(name) {
                errors.push((self.tree().entry_place(spec.entry), taken("imported name", name)));
            }
        }
        let taken_name = |m: &Model, e: EntryId| {
            let entry = m.tree.entry(e);
            !entry.key.keyword()
                && (m.functions.contains_key(&*entry.key.name)
                    || m.hosted.contains_key(&*entry.key.name)
                    || m.imported.contains_key(&*entry.key.name))
        };
        let mut stack: Vec<EntryId> = self.model.data();
        while let Some(e) = stack.pop() {
            let entry = self.tree().entry(e).clone();
            if taken_name(self.model, e) {
                errors.push((
                    self.tree().entry_place(e),
                    format!("the key \"{}\" has the name of a function of this file; rename one of them", entry.key.name),
                ));
            }
            if entry.key.kind() == KeyKind::Plain {
                let mut nodes = vec![entry.value];
                while let Some(n) = nodes.pop() {
                    match &self.tree().node(n).kind {
                        NodeKind::List(items) => nodes.extend(items.iter().copied()),
                        NodeKind::Map(entries) => stack.extend(entries.iter().copied()),
                        NodeKind::Scalar(_) => {}
                    }
                }
            }
        }
        for (at, message) in errors {
            self.problems.error(&at, message);
        }
    }

    // ── names ──

    fn at(&self, node: NodeId) -> Place {
        self.tree().at(node)
    }

    fn check_names(&mut self, node: NodeId) {
        let Some(expression) = self.checked.expressions.get(&node).cloned() else { return };
        let mut reads: Vec<String> = Vec::new();
        let mut reaches: Vec<(Reference, Reach)> = Vec::new();
        for formula in expression.formulas() {
            let mut called = HashSet::default();
            let mut keys = HashSet::default();
            for r in formula.references() {
                let Some(reach) = self.check_ref(node, r) else { continue };
                if !r.call && !reads.contains(&r.name()) {
                    reads.push(r.name());
                }
                match reach {
                    Ok(()) => {
                        if r.call && builtins::is_builtin(&r.head) {
                            called.insert(r.head.to_string());
                        }
                    }
                    Err(reach) => {
                        keys.insert(r.head.to_string());
                        reaches.push((r.clone(), reach));
                    }
                }
            }
            for name in &called {
                if keys.contains(name) {
                    let at = self.at(node);
                    self.problems.error(&at, clash(name));
                }
            }
        }
        self.checked.reads.insert(node, reads);
        self.check_overlap(node, &reaches);
    }

    /// None: names nothing. Some(Ok): fine and not a key. Some(Err(reach)): a key, reached so far.
    fn check_ref(&mut self, node: NodeId, r: &Reference) -> Option<Result<(), Reach>> {
        let scope = Scope { model: self.model, shapes: &self.checked.shapes };
        let target = scope.resolve(node, r);
        match target {
            Target::Unknown => {
                if r.in_filter {
                    return None;
                }
                let what = if r.call { "unknown function" } else { "unknown name" };
                let names = scope.names(node);
                let otherwise = if r.call { "" } else { "; for text, remove the \"!\"" };
                let message = format!("{what} \"{}\"{}", r.head, hint(&r.head, &names, otherwise));
                let at = self.at(node);
                self.problems.error(&at, message);
                None
            }
            Target::Vars => {
                if let Some(name) = r.path.first()
                    && !self.model.variables.knows(name)
                    && !self.undeclared.contains(&**name)
                {
                    self.undeclared.insert(name.to_string());
                    let at = self.at(node);
                    self.problems.warning(
                        &at,
                        format!("the variable \"{name}\" is not declared in $vars; it is null unless the application passes it"),
                    );
                }
                Some(Ok(()))
            }
            Target::Key(e) => {
                if r.in_filter && self.tree().entry(e).value == node {
                    return None;
                }
                let tree = &self.model.tree;
                let reach = scope.walk(e, &r.path, &|map, name| tree.find(map, name));
                if let Some((missing, map)) = &reach.missing {
                    let keys: Vec<String> = tree.entries_of(*map).iter().map(|k| tree.entry(*k).key.name.to_string()).collect();
                    let message =
                        format!("\"{}\": there is no key \"{missing}\" in \"{}\"{}", r.name(), tree.path(*map), hint(missing, &keys, ""));
                    let at = self.at(node);
                    self.problems.error(&at, message);
                }
                Some(Err(reach))
            }
            _ => Some(Ok(())),
        }
    }

    /// One formula cannot read a node as a value and also a key beside that value.
    fn check_overlap(&mut self, node: NodeId, reaches: &[(Reference, Reach)]) {
        let tree = self.tree();
        for (short_ref, short) in reaches {
            for (long_ref, long) in reaches {
                if short_ref.head != long_ref.head || short.steps.len() >= long.steps.len() {
                    continue;
                }
                if !short.rest().is_empty() || !short.steps.iter().zip(&long.steps).all(|(a, b)| a == b) {
                    continue;
                }
                let crossed = &long.nodes[short.steps.len()..long.nodes.len() - 1];
                if !crossed.iter().any(|n| tree.is_list(*n) || (tree.is_map(*n) && tree.get(*n, "$value").is_some())) {
                    continue;
                }
                let shorter = std::iter::once(short_ref.head.to_string()).chain(short.steps.iter().cloned()).collect::<Vec<_>>().join(".");
                let message = format!(
                    "one formula reads \"{shorter}\" as a value and \"{}\" inside it; read one of them through a key of its own",
                    long_ref.name()
                );
                let at = self.at(node);
                self.problems.error(&at, message);
                return;
            }
        }
    }

    // ── cycles ──

    fn needs(&self, node: NodeId) -> Vec<NodeId> {
        let scope = Scope { model: self.model, shapes: &self.checked.shapes };
        let tree = self.tree();
        let mut needs = Vec::new();
        let Some(expression) = self.checked.expressions.get(&node) else { return needs };
        for formula in expression.formulas() {
            for r in formula.references() {
                match scope.resolve(node, r) {
                    Target::Function(e) => needs.push(tree.entry(e).value),
                    Target::Base(e) => self.under(Some(e), tree.entry(e).value, &mut needs),
                    Target::Key(e) => {
                        if r.in_filter && tree.entry(e).value == node {
                            continue;
                        }
                        let reach = scope.walk(e, &r.path, &|map, name| tree.find(map, name));
                        self.under(reach.entry, reach.node, &mut needs);
                    }
                    _ => {}
                }
            }
        }
        needs
    }

    fn under(&self, entry: Option<EntryId>, node: NodeId, into: &mut Vec<NodeId>) {
        let tree = self.tree();
        if entry.is_some_and(|e| tree.entry(e).key.kind() == KeyKind::Marked) {
            return;
        }
        if self.checked.expressions.contains_key(&node) {
            into.push(node);
        }
        for item in tree.items(node) {
            self.under(None, *item, into);
        }
        if !tree.is_map(node) {
            return;
        }
        match tree.get(node, "$value") {
            Some(v) => self.under(Some(v), tree.entry(v).value, into),
            None => {
                for e in tree.entries_of(node) {
                    self.under(Some(*e), tree.entry(*e).value, into);
                }
            }
        }
    }

    fn check_cycles(&mut self) {
        #[derive(PartialEq)]
        enum State {
            Open,
            Done,
        }
        struct Walk<'c, 'a> {
            checker: &'c Checker<'a>,
            state: HashMap<NodeId, State>,
            reported: HashSet<NodeId>,
            stack: Vec<NodeId>,
            errors: Vec<(NodeId, Vec<NodeId>)>,
        }
        impl Walk<'_, '_> {
            fn visit(&mut self, node: NodeId) {
                if !self.checker.checked.expressions.contains_key(&node) {
                    return;
                }
                match self.state.get(&node) {
                    Some(State::Done) => return,
                    Some(State::Open) => {
                        if self.reported.insert(node) {
                            let from = self.stack.iter().position(|n| *n == node).unwrap_or(0);
                            let mut cycle = self.stack[from..].to_vec();
                            cycle.push(node);
                            self.errors.push((node, cycle));
                        }
                        return;
                    }
                    None => {}
                }
                self.state.insert(node, State::Open);
                self.stack.push(node);
                for next in self.checker.needs(node) {
                    self.visit(next);
                }
                self.stack.pop();
                self.state.insert(node, State::Done);
            }
        }
        let mut walk =
            Walk { checker: self, state: HashMap::default(), reported: HashSet::default(), stack: Vec::new(), errors: Vec::new() };
        for node in self.checked.computed.clone() {
            walk.visit(node);
        }
        let errors = walk.errors;
        for (node, cycle) in errors {
            let at = self.at(node);
            let names: Vec<String> = cycle.iter().map(|n| self.tree().path(*n)).collect();
            self.problems.error(&at, format!("reads itself, directly or through other keys: {}", names.join(" → ")));
        }
    }
}