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
//! `$schema` and `$dsl`: which keys a file has (SPEC 4.10).

use indexmap::IndexMap;
use rustc_hash::FxHashMap as HashMap;
use scrusted_feel::{Budget, EvalOptions, Formula, MapEnv, Value, builtins};
use std::sync::Arc;

use crate::node::{KeyKind, NodeId, NodeKind, Tree, js_string};
use crate::problem::{Place, Problems};

/// One word of a schema: `title`, `agents*`, `files+`, `launch:Look`, `rules*:Rule`.
#[derive(Debug, Clone, PartialEq)]
pub struct Field {
    /// The field name.
    pub name: String,
    /// `agents*`: a list, or a map of items by name.
    pub many: bool,
    /// `files+`: one value, or a list of them.
    pub one_or_many: bool,
    /// `:Type`
    pub ty: Option<String>,
    /// Listed under `required`.
    pub required: bool,
}

impl Field {
    /// Reads a word.
    pub fn new(word: &str, required: bool) -> Field {
        let (name, ty) = match word.find(':') {
            Some(i) => (&word[..i], Some(word[i + 1..].to_string())),
            None => (word, None),
        };
        let many = name.ends_with('*');
        let one_or_many = name.ends_with('+');
        let name = if many || one_or_many { &name[..name.len() - 1] } else { name };
        Field { name: name.to_string(), many, one_or_many, ty, required }
    }
}

/// A check across the fields of one item: `valid!` must be true, or `message` is shown.
#[derive(Debug, Clone)]
pub struct Rule {
    /// The formula as written.
    pub source: String,
    /// The formula; Err when it does not parse.
    pub formula: Result<Formula, String>,
    /// Shown when the rule does not hold.
    pub message: String,
}

impl Rule {
    /// The names of fields the rule reads.
    pub fn reads(&self) -> Vec<String> {
        match &self.formula {
            Ok(f) => f.references().iter().filter(|r| !r.in_filter && !r.call).map(|r| r.head.to_string()).collect(),
            Err(_) => Vec::new(),
        }
    }

    /// None when the rule holds; its message when it gives anything but true; a description of
    /// the error when it cannot be computed.
    pub fn failure(&self, fields: scrusted_feel::Map, options: &EvalOptions) -> Option<String> {
        let formula = match &self.formula {
            Ok(f) => f,
            Err(e) => return Some(self.broken(e)),
        };
        // as scripted-yaml hands a rule to feelin: a one-word function of its own that is called takes
        // the place of a field of its name
        let mut fields = fields;
        for r in formula.references() {
            if r.call && builtins::is_own(&r.head) {
                fields.insert(
                    r.head.clone(),
                    Value::Function(std::sync::Arc::new(scrusted_feel::Function::Builtin(builtins::canonical(&r.head)))),
                );
            }
        }
        let budget = Budget::new(options.clone());
        match formula.evaluate(&MapEnv(fields), &budget) {
            Ok(Value::Bool(true)) => None,
            Ok(_) => Some(self.message.clone()),
            Err(e) => Some(self.broken(&e.message)),
        }
    }

    fn broken(&self, reason: &str) -> String {
        format!("the rule \"{}\" cannot be computed: {reason}", self.source)
    }
}

/// The fields a map may have.
#[derive(Debug, Clone)]
pub struct Shape {
    /// The type name; empty for the root.
    pub name: String,
    /// The fields, by name.
    pub fields: IndexMap<String, Field>,
    /// The rules.
    pub rules: Vec<Rule>,
    /// The field that names an item of this shape.
    pub key: String,
    /// Per field, the names the application supplies when it computes the field.
    pub with: HashMap<String, Vec<String>>,
}

fn words(v: Option<&Value>) -> Vec<String> {
    match v {
        Some(Value::List(items)) => items.iter().map(js_string).collect(),
        _ => Vec::new(),
    }
}

impl Shape {
    fn new(name: &str, data: &Value, at: &Place, problems: &mut Problems) -> Shape {
        let map = data.as_map();
        let get = |k: &str| map.and_then(|m| m.get(k));
        let mut fields = IndexMap::new();
        for w in words(get("required")) {
            let f = Field::new(&w, true);
            fields.insert(f.name.clone(), f);
        }
        for w in words(get("optional")) {
            let f = Field::new(&w, false);
            fields.insert(f.name.clone(), f);
        }
        let key = match get("key") {
            Some(Value::String(s)) => s.to_string(),
            _ => "id".to_string(),
        };
        let mut with = HashMap::default();
        if let Some(Value::Map(m)) = get("with") {
            for (k, v) in m.iter() {
                with.insert(k.to_string(), words(Some(v)));
            }
        }
        let mut shape = Shape { name: name.to_string(), fields, rules: Vec::new(), key, with };
        if let Some(Value::List(rules)) = get("rules") {
            for rule in rules.iter() {
                shape.rule(rule, at, problems);
            }
        }
        shape
    }

    fn rule(&mut self, data: &Value, at: &Place, problems: &mut Problems) {
        let get = |k: &str| data.as_map().and_then(|m| m.get(k)).cloned();
        let source = get("valid!").map(|v| js_string(&v)).filter(|_| get("valid!").is_some_and(|v| !v.is_null())).unwrap_or_default();
        let message =
            get("message").filter(|v| !v.is_null()).map(|v| js_string(&v)).unwrap_or_else(|| "a rule of the schema is broken".into());
        let label = if self.name.is_empty() { "the schema".to_string() } else { self.name.clone() };
        let formula = Formula::parse(&source).map_err(|e| e.message);
        match &formula {
            Err(e) => problems.error(at, format!("a rule of {label}: {e}")),
            Ok(f) => {
                for r in f.references() {
                    let known = r.in_filter || self.fields.contains_key(&*r.head) || (r.call && builtins::is_builtin(&r.head));
                    if !known {
                        problems.error(at, format!("a rule of {label} reads \"{}\", which is not one of its fields", r.head));
                    }
                    if r.call && builtins::is_builtin(&r.head) && self.fields.contains_key(&*r.head) {
                        problems.error(at, format!("a rule of {label}: {}", clash(&r.head)));
                    }
                }
            }
        }
        self.rules.push(Rule { source, formula, message });
    }
}

/// Why one formula may not both read a key and call the built-in of the same name.
pub fn clash(name: &str) -> String {
    format!("\"{name}\" is read as a key and called as a built-in function in one formula; put the call in a key of its own")
}

/// A `$schema`.
#[derive(Debug, Clone)]
pub struct Schema {
    /// The fields of the file itself.
    pub root: Arc<Shape>,
    /// Named shapes.
    pub shapes: HashMap<String, Arc<Shape>>,
    /// Named sets of words.
    pub words: HashMap<String, Vec<String>>,
    /// `markers: { decide: Decide }`
    pub markers: IndexMap<String, Field>,
}

impl Schema {
    /// Reads a `$schema` node.
    pub fn new(tree: &Tree, node: NodeId, problems: &mut Problems) -> Schema {
        let at = tree.place(node);
        let is_map = tree.is_map(node);
        if !is_map {
            problems.error(&at, "$schema must be a map with \"required\" and \"optional\"");
        }
        let data = if is_map { tree.to_data(node) } else { Value::from(scrusted_feel::Map::new()) };
        let root = Arc::new(Shape::new("", &data, &at, problems));
        let mut shapes = HashMap::default();
        let mut word_sets = HashMap::default();
        if let Some(map) = data.as_map() {
            for (name, value) in map.iter() {
                let first = name.chars().next().unwrap_or('a');
                if first.to_lowercase().next() == Some(first) {
                    continue;
                }
                match value {
                    Value::List(items) => {
                        word_sets.insert(name.to_string(), items.iter().map(js_string).collect());
                    }
                    other => {
                        let empty = Value::from(scrusted_feel::Map::new());
                        let v = if other.is_null() { &empty } else { other };
                        shapes.insert(name.to_string(), Arc::new(Shape::new(name, v, &at, problems)));
                    }
                }
            }
        }
        let mut markers = IndexMap::new();
        match data.as_map().and_then(|m| m.get("markers")) {
            None | Some(Value::Null) => {}
            Some(Value::Map(m)) => {
                for (marker, ty) in m.iter() {
                    markers.insert(marker.to_string(), Field::new(&format!("{marker}:{}", js_string(ty)), false));
                }
            }
            Some(_) => problems.error(&at, "$schema markers is a map of a marker to its type: markers: { decide: Decide }"),
        }
        let schema = Schema { root, shapes, words: word_sets, markers };
        let all_fields = std::iter::once(&schema.root)
            .chain(schema.shapes.values())
            .flat_map(|s| s.fields.values())
            .chain(schema.markers.values())
            .cloned()
            .collect::<Vec<_>>();
        for f in all_fields {
            if let Some(ty) = &f.ty
                && !schema.shapes.contains_key(ty)
                && !schema.words.contains_key(ty)
            {
                problems.error(&at, format!("the schema names the type \"{ty}\" and does not define it"));
            }
        }
        schema
    }
}

/// Checks a file against a schema and notes on each map the shape it has.
pub struct Fitter<'a> {
    /// The schema.
    pub schema: &'a Schema,
    /// The tree; lists get their key field.
    pub tree: &'a mut Tree,
    /// Problems found.
    pub problems: &'a mut Problems,
    /// True when a node holds a formula (not a text template).
    pub is_formula: &'a dyn Fn(NodeId) -> bool,
    /// True when a node holds a formula or a template.
    pub has_expression: &'a dyn Fn(NodeId) -> bool,
    /// The shape each map was checked against.
    pub shapes: &'a mut HashMap<NodeId, Arc<Shape>>,
    /// Options for computing rules.
    pub options: EvalOptions,
}

impl Fitter<'_> {
    /// Checks the file.
    pub fn check(&mut self, root: NodeId) {
        let shape = self.schema.root.clone();
        self.fit(root, shape, None);
        if !self.schema.markers.is_empty() {
            self.marked(root);
        }
    }

    fn marked(&mut self, node: NodeId) {
        for item in self.tree.items(node).to_vec() {
            self.marked(item);
        }
        for e in self.tree.entries_of(node).to_vec() {
            let entry = self.tree.entry(e).clone();
            if entry.key.kind() == KeyKind::Marked
                && let Some(field) = self.schema.markers.get(entry.key.marker_name())
            {
                let f = Field::new(&format!("{}:{}", entry.key.raw, field.ty.clone().unwrap_or_default()), false);
                self.one(entry.value, &f, None);
            }
            if entry.key.kind() != KeyKind::Formula {
                self.marked(entry.value);
            }
        }
    }

    fn fit(&mut self, map: NodeId, shape: Arc<Shape>, named: Option<&str>) {
        self.shapes.insert(map, shape.clone());
        for field in shape.fields.values() {
            if field.required && self.tree.get(map, &field.name).is_none() && Some(field.name.as_str()) != named {
                let at = self.tree.place(map);
                self.problems.error(&at, format!("missing required field \"{}\"", field.name));
            }
        }
        for e in self.tree.entries_of(map).to_vec() {
            let entry = self.tree.entry(e).clone();
            let field = shape.fields.get(&*entry.key.name);
            if field.is_none() && !entry.key.keyword() {
                let at = self.tree.entry_place(e);
                self.problems.warning(&at, format!("\"{}\" is not a field of the schema", entry.key.name));
            }
            if let Some(field) = field
                && entry.key.kind() == KeyKind::Plain
            {
                let field = field.clone();
                self.value(entry.value, &field);
            }
        }
        self.rules(map, &shape);
    }

    fn rules(&mut self, map: NodeId, shape: &Shape) {
        if self.tree.get(map, "$when").is_some() {
            return;
        }
        for rule in &shape.rules {
            let mut fields = scrusted_feel::Map::new();
            let mut settled = true;
            for name in rule.reads() {
                match self.tree.get(map, &name) {
                    None => {
                        fields.insert(name.into(), Value::Null);
                    }
                    Some(e) => {
                        let entry = self.tree.entry(e);
                        fields.insert(name.into(), self.tree.to_data(entry.value));
                        let ok = entry.key.kind() == KeyKind::Marked || (entry.key.kind() == KeyKind::Plain && self.settled(entry.value));
                        settled &= ok;
                    }
                }
            }
            if !settled {
                continue;
            }
            if let Some(failure) = rule.failure(fields, &self.options) {
                let at = self.tree.place(map);
                self.problems.error(&at, failure);
            }
        }
    }

    fn settled(&self, node: NodeId) -> bool {
        if (self.is_formula)(node) {
            return false;
        }
        match &self.tree.node(node).kind {
            NodeKind::List(items) => items.iter().all(|i| self.settled(*i)),
            NodeKind::Map(entries) => entries.iter().all(|e| {
                let entry = self.tree.entry(*e);
                entry.key.kind() == KeyKind::Marked || (entry.key.kind() == KeyKind::Plain && self.settled(entry.value))
            }),
            NodeKind::Scalar(_) => true,
        }
    }

    fn value(&mut self, node: NodeId, field: &Field) {
        if field.one_or_many {
            if self.tree.is_list(node) {
                for item in self.tree.items(node).to_vec() {
                    self.one(item, field, None);
                }
            } else {
                self.one(node, field, None);
            }
            return;
        }
        if !field.many {
            self.one(node, field, None);
            return;
        }
        let shape = field.ty.as_ref().and_then(|t| self.schema.shapes.get(t)).cloned();
        if self.tree.is_list(node) {
            if let Some(shape) = &shape {
                self.tree.nodes[node].key_field = shape.key.as_str().into();
            }
            for item in self.tree.items(node).to_vec() {
                self.one(item, field, None);
            }
        } else if self.tree.is_map(node) {
            for e in self.tree.entries_of(node).to_vec() {
                let entry = self.tree.entry(e).clone();
                if !entry.key.keyword() && entry.key.kind() == KeyKind::Plain {
                    let key = shape.as_ref().map(|s| s.key.clone());
                    self.one(entry.value, field, key.as_deref());
                }
            }
        } else {
            let at = self.tree.place(node);
            self.problems.error(&at, format!("\"{}\" takes many values: write a list", field.name));
        }
    }

    fn one(&mut self, node: NodeId, field: &Field, named: Option<&str>) {
        let Some(ty) = &field.ty else { return };
        if let Some(shape) = self.schema.shapes.get(ty).cloned() {
            if self.tree.is_map(node) {
                self.fit(node, shape, named);
            } else {
                let at = self.tree.place(node);
                self.problems.error(&at, format!("\"{}\" must be a map with the fields of {ty}", field.name));
            }
        } else if let Some(words) = self.schema.words.get(ty) {
            if (self.has_expression)(node) {
                return;
            }
            let word = self.tree.scalar_of(node).map(|s| js_string(&s.value));
            if word.as_ref().is_none_or(|w| !words.contains(w)) {
                let at = self.tree.place(node);
                self.problems.error(&at, format!("\"{}\" is not one of: {}", word.unwrap_or_else(|| field.name.clone()), words.join(", ")));
            }
        }
    }
}