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
//! A loaded file: its data with formulas kept as formulas, and the way to compute them (SPEC 5.4).

use indexmap::IndexMap;
use rustc_hash::FxHashMap as HashMap;
use scrusted_feel::{EvalOptions, Map, Value};
use std::sync::{Arc, RwLock};

use crate::checker::Checked;
use crate::marker::Markers;
use crate::node::{EntryId, KeyKind, NodeId};
use crate::problem::{Problem, Problems};
use crate::resolution::{HostFunctions, Resolution};
use crate::scope::{Expression, Scope, Target};
use crate::source::{HostFunctionDecl, Model, Variable};

/// One marked key of a loaded file: what is written under it, and the value its marker gave.
#[derive(Clone)]
pub struct MarkedKey {
    inner: Arc<DocInner>,
    entry: EntryId,
}

impl MarkedKey {
    /// The path of the key, as problems name it: `stages.build.check.$value!sh`.
    pub fn path(&self) -> String {
        self.inner.model.tree.entry_path(self.entry)
    }

    /// The marker name.
    pub fn marker(&self) -> String {
        self.inner.model.tree.entry(self.entry).key.marker_name().to_string()
    }

    /// The value as written.
    pub fn source(&self) -> Value {
        let tree = &self.inner.model.tree;
        tree.to_data(tree.entry(self.entry).value)
    }

    /// What the marker function returned, or what the application set since.
    pub fn value(&self) -> Value {
        self.inner.marked_value(self.entry)
    }

    /// Sets the value the next resolve reads (SPEC 4.6).
    pub fn set(&self, value: Value) {
        if let Some(cell) = self.inner.marked.get(&self.entry) {
            *cell.write().unwrap_or_else(|e| e.into_inner()) = (value, true);
        }
    }
}

/// The result of one test of `$tests`.
#[derive(Debug, Clone, PartialEq, serde::Serialize)]
pub struct TestResult {
    /// What the test says it checks.
    pub about: String,
    /// One line per expectation that did not hold.
    pub failures: Vec<String>,
}

impl TestResult {
    /// True when every expectation held.
    pub fn passed(&self) -> bool {
        self.failures.is_empty()
    }
}

/// Options of `resolve` (SPEC 5.5).
#[derive(Clone, Default)]
pub struct ResolveOptions {
    /// Declared `$functions`, by name.
    pub functions: crate::api::Functions,
    /// `now()` and `today()`; the system clock when None.
    pub clock: Option<scrusted_feel::Clock>,
    /// Every "null, not reported" case of SPEC 3.4 is an error.
    pub strict_nulls: bool,
    /// The limits of SPEC 7.
    pub limits: scrusted_feel::Limits,
}

impl ResolveOptions {
    /// Adds a host function taking and giving values.
    pub fn function(mut self, name: &str, f: impl Fn(&[Value]) -> Result<Value, scrusted_feel::HostError> + Send + Sync + 'static) -> Self {
        self.functions = self.functions.add_raw(name, f);
        self
    }

    /// Sets the functions.
    pub fn functions(mut self, functions: crate::api::Functions) -> Self {
        self.functions = functions;
        self
    }

    pub(crate) fn eval_options(&self) -> EvalOptions {
        EvalOptions { clock: self.clock.clone(), strict_nulls: self.strict_nulls, limits: self.limits }
    }
}

impl std::fmt::Debug for ResolveOptions {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ResolveOptions").field("functions", &self.functions).field("strict_nulls", &self.strict_nulls).finish()
    }
}

/// What a resolve that fails reports.
#[derive(Debug, Clone, PartialEq)]
pub struct ResolveError {
    /// The problems; the first is where it failed.
    pub problems: Vec<Problem>,
}

impl ResolveError {
    /// The file of the first problem.
    pub fn file(&self) -> &str {
        self.problems.first().map(|p| p.file.as_str()).unwrap_or("")
    }

    /// The key of the first problem.
    pub fn key(&self) -> &str {
        self.problems.first().map(|p| p.key.as_str()).unwrap_or("")
    }

    /// The message of the first problem.
    pub fn message(&self) -> &str {
        self.problems.first().map(|p| p.message.as_str()).unwrap_or("")
    }
}

impl std::fmt::Display for ResolveError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&crate::problem::error_text(&self.problems))
    }
}

impl std::error::Error for ResolveError {}

/// The shared inside of a document.
pub struct DocInner {
    pub(crate) model: Model,
    pub(crate) checked: Checked,
    pub(crate) imports: IndexMap<String, Document>,
    pub(crate) markers: Markers,
    pub(crate) marked: HashMap<EntryId, RwLock<(Value, bool)>>,
    pub(crate) marked_order: Vec<EntryId>,
}

impl DocInner {
    pub(crate) fn marked_value(&self, e: EntryId) -> Value {
        self.marked.get(&e).map(|c| c.read().unwrap_or_else(|e| e.into_inner()).0.clone()).unwrap_or(Value::Null)
    }

    pub(crate) fn marked_set(&self, e: EntryId) -> bool {
        self.marked.get(&e).is_some_and(|c| c.read().unwrap_or_else(|e| e.into_inner()).1)
    }
}

/// A loaded file. Immutable apart from marked values the application sets; cheap to clone and
/// share between threads.
#[derive(Clone)]
pub struct Document {
    pub(crate) inner: Arc<DocInner>,
}

impl std::fmt::Debug for Document {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Document").field("file", &self.inner.model.file).finish()
    }
}

/// A node of the file as `Document::data` shows it.
#[derive(Debug, Clone)]
pub enum Data {
    /// Plain data.
    Value(Value),
    /// A formula: its source and the names it reads.
    Formula {
        /// As written.
        source: String,
        /// The names it reads: `vars.URL`, `b.c`.
        reads: Vec<String>,
    },
    /// Text with `{{ }}`.
    Text {
        /// As written.
        source: String,
        /// The names it reads.
        reads: Vec<String>,
    },
    /// A map, keys without markers.
    Map(IndexMap<String, Data>),
    /// A list.
    List(Vec<Data>),
    /// What a marker function returned.
    Marked(Value),
}

impl Document {
    pub(crate) fn build(
        model: Model,
        checked: Checked,
        imports: IndexMap<String, Document>,
        markers: Markers,
        problems: &mut Problems,
    ) -> Document {
        let mut marked = HashMap::default();
        let mut marked_order = Vec::new();
        {
            let scope = Scope { model: &model, shapes: &checked.shapes };
            let tree = &model.tree;
            // walk in file order
            let mut order = Vec::new();
            fn walk(tree: &crate::node::Tree, model: &Model, node: NodeId, scope: &Scope<'_>, checked: &Checked, out: &mut Vec<EntryId>) {
                for item in tree.items(node) {
                    walk(tree, model, *item, scope, checked, out);
                }
                let own: Vec<EntryId> = if node == model.root { model.data() } else { tree.entries_of(node).to_vec() };
                for e in own {
                    let entry = tree.entry(e);
                    if entry.key.kind() == KeyKind::Marked {
                        out.push(e);
                    } else {
                        walk(tree, model, entry.value, scope, checked, out);
                    }
                    let mut holder = e;
                    while let Some(base) = tree.entry(holder).base {
                        if !reads_base(scope, checked, holder) {
                            break;
                        }
                        if tree.entry(base).key.kind() == KeyKind::Marked {
                            out.push(base);
                        } else {
                            walk(tree, model, tree.entry(base).value, scope, checked, out);
                        }
                        holder = base;
                    }
                }
            }
            walk(tree, &model, model.root, &scope, &checked, &mut order);
            for e in order {
                let entry = tree.entry(e);
                let marker = entry.key.marker_name().to_string();
                let at = tree.entry_place(e);
                match markers.functions.get(&marker) {
                    Some(Some(f)) => {
                        let source = tree.to_data(entry.value);
                        match f(&source) {
                            Ok(out) => {
                                marked.insert(e, RwLock::new((out.into_value(), false)));
                                marked_order.push(e);
                            }
                            Err(error) => problems.error(&at, format!("the function of the marker \"{marker}\" failed: {error}")),
                        }
                    }
                    _ => problems
                        .error(&at, format!("the marker \"{marker}\" was registered by name only; loading a file needs its function")),
                }
            }
        }
        Document { inner: Arc::new(DocInner { model, checked, imports, markers, marked, marked_order }) }
    }

    /// The name of the file.
    pub fn file(&self) -> &str {
        &self.inner.model.file
    }

    /// The variables the file declares under `$vars`.
    pub fn vars(&self) -> Vec<Variable> {
        self.inner.model.variables.declared.values().cloned().collect()
    }

    /// The functions the file declares for the application to pass.
    pub fn functions(&self) -> Vec<HostFunctionDecl> {
        self.inner.model.hosted.values().cloned().collect()
    }

    /// Every marked key, in file order.
    pub fn marked(&self) -> Vec<MarkedKey> {
        self.inner.marked_order.iter().map(|e| MarkedKey { inner: self.inner.clone(), entry: *e }).collect()
    }

    /// The file as a tree: formulas as formulas, markers removed from key names.
    pub fn data(&self) -> Data {
        self.data_of(self.inner.model.root)
    }

    fn data_of(&self, node: NodeId) -> Data {
        let inner = &self.inner;
        let tree = &inner.model.tree;
        if let Some(expression) = inner.checked.expressions.get(&node) {
            let reads = inner.checked.reads.get(&node).cloned().unwrap_or_default();
            let source = expression.source().to_string();
            return match expression {
                Expression::Formula(_) => {
                    Data::Formula { source: tree.scalar_of(node).map(|s| s.source.to_string()).unwrap_or(source), reads }
                }
                Expression::Text(_) => Data::Text { source, reads },
            };
        }
        if tree.is_list(node) {
            return Data::List(tree.items(node).iter().map(|i| self.data_of(*i)).collect());
        }
        if tree.is_map(node) {
            let entries = if node == inner.model.root { inner.model.data() } else { tree.entries_of(node).to_vec() };
            let mut out = IndexMap::new();
            for e in entries {
                let entry = tree.entry(e);
                let value =
                    if entry.key.kind() == KeyKind::Marked { Data::Marked(inner.marked_value(e)) } else { self.data_of(entry.value) };
                out.insert(entry.key.name.to_string(), value);
            }
            return Data::Map(out);
        }
        Data::Value(tree.to_data(node))
    }

    /// All variables in, all values out (SPEC 5.5).
    pub fn resolve(&self, vars: &(impl crate::api::AsVars + ?Sized), options: &ResolveOptions) -> Result<Value, ResolveError> {
        let vars = vars.as_vars();
        let resolution = Resolution::new(&self.inner, vars, &options.functions.0, options.eval_options())
            .map_err(|p| ResolveError { problems: vec![*p] })?;
        resolution.run().map_err(|p| ResolveError { problems: vec![*p] })
    }

    /// Resolves into any `Deserialize` type: `$value` maps with `#[serde(rename = "$value")]`.
    pub fn resolve_as<T: serde::de::DeserializeOwned>(
        &self,
        vars: &(impl crate::api::AsVars + ?Sized),
        options: &ResolveOptions,
    ) -> Result<T, ResolveError> {
        let value = self.resolve(vars, options)?;
        scrusted_feel::serde_value::from_value(value).map_err(|e| ResolveError {
            problems: vec![Problem {
                file: self.file().to_string(),
                line: 0,
                column: 0,
                key: String::new(),
                message: format!("the result does not fit the type {}: {}", std::any::type_name::<T>(), e.0),
                severity: crate::problem::Severity::Error,
            }],
        })
    }

    /// The file as a formula of another file reads it.
    pub(crate) fn view(&self, vars: &Map, functions: &HostFunctions, options: EvalOptions) -> Result<Value, Vec<Problem>> {
        let resolution = Resolution::new(&self.inner, vars, functions, options).map_err(|p| vec![*p])?;
        resolution.view().map_err(|p| vec![*p])
    }

    /// Runs the file's `$tests` (SPEC 4.8).
    pub fn test(&self, options: &ResolveOptions) -> Vec<TestResult> {
        let tests = self.inner.model.tests();
        tests
            .iter()
            .enumerate()
            .map(|(index, test)| {
                let get = |k: &str| test.as_map().and_then(|m| m.get(k)).cloned().unwrap_or(Value::Null);
                let about = get("about").as_str().map(str::to_string).unwrap_or_else(|| format!("test {}", index + 1));
                let vars = get("vars").as_map().cloned().unwrap_or_default();
                let expect = get("expect").as_map().cloned().unwrap_or_default();
                let mut failures = Vec::new();
                match Resolution::new(&self.inner, &vars, &options.functions.0, options.eval_options()) {
                    Err(p) => failures.push(p.to_string()),
                    Ok(resolution) => match resolution.run() {
                        Err(p) => failures.push(p.to_string()),
                        Ok(_) => {
                            for (path, expected) in expect.iter() {
                                match resolution.probe(path) {
                                    Ok(actual) => {
                                        if actual.feel_eq(expected) != Some(true) {
                                            failures.push(format!("{path}: expected {}, got {}", show(expected), show(&actual)));
                                        }
                                    }
                                    Err(p) => failures.push(p.to_string()),
                                }
                            }
                        }
                    },
                }
                TestResult { about, failures }
            })
            .collect()
    }

    /// The merged form (SPEC 4.11): one file with the base applied, as data.
    pub fn merged(&self) -> Value {
        let inner = &self.inner;
        let scope = Scope { model: &inner.model, shapes: &inner.checked.shapes };
        let reads = |e: EntryId| reads_base(&scope, &inner.checked, e);
        crate::merged::write(&inner.model.tree, inner.model.root, &reads)
    }

    /// The merged form as YAML text.
    pub fn merged_text(&self) -> String {
        crate::yaml_out::to_yaml(&self.merged())
    }

    /// The parsed formula or template of a node, for tools.
    pub fn expressions(&self) -> usize {
        self.inner.checked.expressions.len()
    }
}

fn show(v: &Value) -> String {
    match v {
        Value::Null => "null".into(),
        other => scrusted_feel::json::to_json(other).to_string(),
    }
}

/// True when a formula under the entry reads `base` and means this entry's base.
pub(crate) fn reads_base(scope: &Scope<'_>, checked: &Checked, entry: EntryId) -> bool {
    let tree = &scope.model.tree;
    let Some(base) = tree.entry(entry).base else { return false };
    fn visit(scope: &Scope<'_>, checked: &Checked, node: NodeId, base: EntryId) -> bool {
        let tree = &scope.model.tree;
        if let Some(expression) = checked.expressions.get(&node) {
            for f in expression.formulas() {
                for r in f.references() {
                    if &*r.head == "base" && scope.resolve(node, r) == Target::Base(base) {
                        return true;
                    }
                }
            }
        }
        if tree.items(node).iter().any(|i| visit(scope, checked, *i, base)) {
            return true;
        }
        tree.entries_of(node).iter().any(|e| {
            let entry = tree.entry(*e);
            visit(scope, checked, entry.value, base) || entry.base.is_some_and(|b| visit(scope, checked, tree.entry(b).value, base))
        })
    }
    visit(scope, checked, tree.entry(entry).value, base)
}