Skip to main content

scrusted_yaml/
document.rs

1//! A loaded file: its data with formulas kept as formulas, and the way to compute them (SPEC 5.4).
2
3use indexmap::IndexMap;
4use rustc_hash::FxHashMap as HashMap;
5use scrusted_feel::{EvalOptions, Map, Value};
6use std::sync::{Arc, RwLock};
7
8use crate::checker::Checked;
9use crate::marker::Markers;
10use crate::node::{EntryId, KeyKind, NodeId};
11use crate::problem::{Problem, Problems};
12use crate::resolution::{HostFunctions, Resolution};
13use crate::scope::{Expression, Scope, Target};
14use crate::source::{HostFunctionDecl, Model, Variable};
15
16/// One marked key of a loaded file: what is written under it, and the value its marker gave.
17#[derive(Clone)]
18pub struct MarkedKey {
19    inner: Arc<DocInner>,
20    entry: EntryId,
21}
22
23impl MarkedKey {
24    /// The path of the key, as problems name it: `stages.build.check.$value!sh`.
25    pub fn path(&self) -> String {
26        self.inner.model.tree.entry_path(self.entry)
27    }
28
29    /// The marker name.
30    pub fn marker(&self) -> String {
31        self.inner.model.tree.entry(self.entry).key.marker_name().to_string()
32    }
33
34    /// The value as written.
35    pub fn source(&self) -> Value {
36        let tree = &self.inner.model.tree;
37        tree.to_data(tree.entry(self.entry).value)
38    }
39
40    /// What the marker function returned, or what the application set since.
41    pub fn value(&self) -> Value {
42        self.inner.marked_value(self.entry)
43    }
44
45    /// Sets the value the next resolve reads (SPEC 4.6).
46    pub fn set(&self, value: Value) {
47        if let Some(cell) = self.inner.marked.get(&self.entry) {
48            *cell.write().unwrap_or_else(|e| e.into_inner()) = (value, true);
49        }
50    }
51}
52
53/// The result of one test of `$tests`.
54#[derive(Debug, Clone, PartialEq, serde::Serialize)]
55pub struct TestResult {
56    /// What the test says it checks.
57    pub about: String,
58    /// One line per expectation that did not hold.
59    pub failures: Vec<String>,
60}
61
62impl TestResult {
63    /// True when every expectation held.
64    pub fn passed(&self) -> bool {
65        self.failures.is_empty()
66    }
67}
68
69/// Options of `resolve` (SPEC 5.5).
70#[derive(Clone, Default)]
71pub struct ResolveOptions {
72    /// Declared `$functions`, by name.
73    pub functions: crate::api::Functions,
74    /// `now()` and `today()`; the system clock when None.
75    pub clock: Option<scrusted_feel::Clock>,
76    /// Every "null, not reported" case of SPEC 3.4 is an error.
77    pub strict_nulls: bool,
78    /// The limits of SPEC 7.
79    pub limits: scrusted_feel::Limits,
80}
81
82impl ResolveOptions {
83    /// Adds a host function taking and giving values.
84    pub fn function(mut self, name: &str, f: impl Fn(&[Value]) -> Result<Value, scrusted_feel::HostError> + Send + Sync + 'static) -> Self {
85        self.functions = self.functions.add_raw(name, f);
86        self
87    }
88
89    /// Sets the functions.
90    pub fn functions(mut self, functions: crate::api::Functions) -> Self {
91        self.functions = functions;
92        self
93    }
94
95    pub(crate) fn eval_options(&self) -> EvalOptions {
96        EvalOptions { clock: self.clock.clone(), strict_nulls: self.strict_nulls, limits: self.limits }
97    }
98}
99
100impl std::fmt::Debug for ResolveOptions {
101    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
102        f.debug_struct("ResolveOptions").field("functions", &self.functions).field("strict_nulls", &self.strict_nulls).finish()
103    }
104}
105
106/// What a resolve that fails reports.
107#[derive(Debug, Clone, PartialEq)]
108pub struct ResolveError {
109    /// The problems; the first is where it failed.
110    pub problems: Vec<Problem>,
111}
112
113impl ResolveError {
114    /// The file of the first problem.
115    pub fn file(&self) -> &str {
116        self.problems.first().map(|p| p.file.as_str()).unwrap_or("")
117    }
118
119    /// The key of the first problem.
120    pub fn key(&self) -> &str {
121        self.problems.first().map(|p| p.key.as_str()).unwrap_or("")
122    }
123
124    /// The message of the first problem.
125    pub fn message(&self) -> &str {
126        self.problems.first().map(|p| p.message.as_str()).unwrap_or("")
127    }
128}
129
130impl std::fmt::Display for ResolveError {
131    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
132        f.write_str(&crate::problem::error_text(&self.problems))
133    }
134}
135
136impl std::error::Error for ResolveError {}
137
138/// The shared inside of a document.
139pub struct DocInner {
140    pub(crate) model: Model,
141    pub(crate) checked: Checked,
142    pub(crate) imports: IndexMap<String, Document>,
143    pub(crate) markers: Markers,
144    pub(crate) marked: HashMap<EntryId, RwLock<(Value, bool)>>,
145    pub(crate) marked_order: Vec<EntryId>,
146}
147
148impl DocInner {
149    pub(crate) fn marked_value(&self, e: EntryId) -> Value {
150        self.marked.get(&e).map(|c| c.read().unwrap_or_else(|e| e.into_inner()).0.clone()).unwrap_or(Value::Null)
151    }
152
153    pub(crate) fn marked_set(&self, e: EntryId) -> bool {
154        self.marked.get(&e).is_some_and(|c| c.read().unwrap_or_else(|e| e.into_inner()).1)
155    }
156}
157
158/// A loaded file. Immutable apart from marked values the application sets; cheap to clone and
159/// share between threads.
160#[derive(Clone)]
161pub struct Document {
162    pub(crate) inner: Arc<DocInner>,
163}
164
165impl std::fmt::Debug for Document {
166    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
167        f.debug_struct("Document").field("file", &self.inner.model.file).finish()
168    }
169}
170
171/// A node of the file as `Document::data` shows it.
172#[derive(Debug, Clone)]
173pub enum Data {
174    /// Plain data.
175    Value(Value),
176    /// A formula: its source and the names it reads.
177    Formula {
178        /// As written.
179        source: String,
180        /// The names it reads: `vars.URL`, `b.c`.
181        reads: Vec<String>,
182    },
183    /// Text with `{{ }}`.
184    Text {
185        /// As written.
186        source: String,
187        /// The names it reads.
188        reads: Vec<String>,
189    },
190    /// A map, keys without markers.
191    Map(IndexMap<String, Data>),
192    /// A list.
193    List(Vec<Data>),
194    /// What a marker function returned.
195    Marked(Value),
196}
197
198impl Document {
199    pub(crate) fn build(
200        model: Model,
201        checked: Checked,
202        imports: IndexMap<String, Document>,
203        markers: Markers,
204        problems: &mut Problems,
205    ) -> Document {
206        let mut marked = HashMap::default();
207        let mut marked_order = Vec::new();
208        {
209            let scope = Scope { model: &model, shapes: &checked.shapes };
210            let tree = &model.tree;
211            // walk in file order
212            let mut order = Vec::new();
213            fn walk(tree: &crate::node::Tree, model: &Model, node: NodeId, scope: &Scope<'_>, checked: &Checked, out: &mut Vec<EntryId>) {
214                for item in tree.items(node) {
215                    walk(tree, model, *item, scope, checked, out);
216                }
217                let own: Vec<EntryId> = if node == model.root { model.data() } else { tree.entries_of(node).to_vec() };
218                for e in own {
219                    let entry = tree.entry(e);
220                    if entry.key.kind() == KeyKind::Marked {
221                        out.push(e);
222                    } else {
223                        walk(tree, model, entry.value, scope, checked, out);
224                    }
225                    let mut holder = e;
226                    while let Some(base) = tree.entry(holder).base {
227                        if !reads_base(scope, checked, holder) {
228                            break;
229                        }
230                        if tree.entry(base).key.kind() == KeyKind::Marked {
231                            out.push(base);
232                        } else {
233                            walk(tree, model, tree.entry(base).value, scope, checked, out);
234                        }
235                        holder = base;
236                    }
237                }
238            }
239            walk(tree, &model, model.root, &scope, &checked, &mut order);
240            for e in order {
241                let entry = tree.entry(e);
242                let marker = entry.key.marker_name().to_string();
243                let at = tree.entry_place(e);
244                match markers.functions.get(&marker) {
245                    Some(Some(f)) => {
246                        let source = tree.to_data(entry.value);
247                        match f(&source) {
248                            Ok(out) => {
249                                marked.insert(e, RwLock::new((out.into_value(), false)));
250                                marked_order.push(e);
251                            }
252                            Err(error) => problems.error(&at, format!("the function of the marker \"{marker}\" failed: {error}")),
253                        }
254                    }
255                    _ => problems
256                        .error(&at, format!("the marker \"{marker}\" was registered by name only; loading a file needs its function")),
257                }
258            }
259        }
260        Document { inner: Arc::new(DocInner { model, checked, imports, markers, marked, marked_order }) }
261    }
262
263    /// The name of the file.
264    pub fn file(&self) -> &str {
265        &self.inner.model.file
266    }
267
268    /// The variables the file declares under `$vars`.
269    pub fn vars(&self) -> Vec<Variable> {
270        self.inner.model.variables.declared.values().cloned().collect()
271    }
272
273    /// The functions the file declares for the application to pass.
274    pub fn functions(&self) -> Vec<HostFunctionDecl> {
275        self.inner.model.hosted.values().cloned().collect()
276    }
277
278    /// Every marked key, in file order.
279    pub fn marked(&self) -> Vec<MarkedKey> {
280        self.inner.marked_order.iter().map(|e| MarkedKey { inner: self.inner.clone(), entry: *e }).collect()
281    }
282
283    /// The file as a tree: formulas as formulas, markers removed from key names.
284    pub fn data(&self) -> Data {
285        self.data_of(self.inner.model.root)
286    }
287
288    fn data_of(&self, node: NodeId) -> Data {
289        let inner = &self.inner;
290        let tree = &inner.model.tree;
291        if let Some(expression) = inner.checked.expressions.get(&node) {
292            let reads = inner.checked.reads.get(&node).cloned().unwrap_or_default();
293            let source = expression.source().to_string();
294            return match expression {
295                Expression::Formula(_) => {
296                    Data::Formula { source: tree.scalar_of(node).map(|s| s.source.to_string()).unwrap_or(source), reads }
297                }
298                Expression::Text(_) => Data::Text { source, reads },
299            };
300        }
301        if tree.is_list(node) {
302            return Data::List(tree.items(node).iter().map(|i| self.data_of(*i)).collect());
303        }
304        if tree.is_map(node) {
305            let entries = if node == inner.model.root { inner.model.data() } else { tree.entries_of(node).to_vec() };
306            let mut out = IndexMap::new();
307            for e in entries {
308                let entry = tree.entry(e);
309                let value =
310                    if entry.key.kind() == KeyKind::Marked { Data::Marked(inner.marked_value(e)) } else { self.data_of(entry.value) };
311                out.insert(entry.key.name.to_string(), value);
312            }
313            return Data::Map(out);
314        }
315        Data::Value(tree.to_data(node))
316    }
317
318    /// All variables in, all values out (SPEC 5.5).
319    pub fn resolve(&self, vars: &(impl crate::api::AsVars + ?Sized), options: &ResolveOptions) -> Result<Value, ResolveError> {
320        let vars = vars.as_vars();
321        let resolution = Resolution::new(&self.inner, vars, &options.functions.0, options.eval_options())
322            .map_err(|p| ResolveError { problems: vec![*p] })?;
323        resolution.run().map_err(|p| ResolveError { problems: vec![*p] })
324    }
325
326    /// Resolves into any `Deserialize` type: `$value` maps with `#[serde(rename = "$value")]`.
327    pub fn resolve_as<T: serde::de::DeserializeOwned>(
328        &self,
329        vars: &(impl crate::api::AsVars + ?Sized),
330        options: &ResolveOptions,
331    ) -> Result<T, ResolveError> {
332        let value = self.resolve(vars, options)?;
333        scrusted_feel::serde_value::from_value(value).map_err(|e| ResolveError {
334            problems: vec![Problem {
335                file: self.file().to_string(),
336                line: 0,
337                column: 0,
338                key: String::new(),
339                message: format!("the result does not fit the type {}: {}", std::any::type_name::<T>(), e.0),
340                severity: crate::problem::Severity::Error,
341            }],
342        })
343    }
344
345    /// The file as a formula of another file reads it.
346    pub(crate) fn view(&self, vars: &Map, functions: &HostFunctions, options: EvalOptions) -> Result<Value, Vec<Problem>> {
347        let resolution = Resolution::new(&self.inner, vars, functions, options).map_err(|p| vec![*p])?;
348        resolution.view().map_err(|p| vec![*p])
349    }
350
351    /// Runs the file's `$tests` (SPEC 4.8).
352    pub fn test(&self, options: &ResolveOptions) -> Vec<TestResult> {
353        let tests = self.inner.model.tests();
354        tests
355            .iter()
356            .enumerate()
357            .map(|(index, test)| {
358                let get = |k: &str| test.as_map().and_then(|m| m.get(k)).cloned().unwrap_or(Value::Null);
359                let about = get("about").as_str().map(str::to_string).unwrap_or_else(|| format!("test {}", index + 1));
360                let vars = get("vars").as_map().cloned().unwrap_or_default();
361                let expect = get("expect").as_map().cloned().unwrap_or_default();
362                let mut failures = Vec::new();
363                match Resolution::new(&self.inner, &vars, &options.functions.0, options.eval_options()) {
364                    Err(p) => failures.push(p.to_string()),
365                    Ok(resolution) => match resolution.run() {
366                        Err(p) => failures.push(p.to_string()),
367                        Ok(_) => {
368                            for (path, expected) in expect.iter() {
369                                match resolution.probe(path) {
370                                    Ok(actual) => {
371                                        if actual.feel_eq(expected) != Some(true) {
372                                            failures.push(format!("{path}: expected {}, got {}", show(expected), show(&actual)));
373                                        }
374                                    }
375                                    Err(p) => failures.push(p.to_string()),
376                                }
377                            }
378                        }
379                    },
380                }
381                TestResult { about, failures }
382            })
383            .collect()
384    }
385
386    /// The merged form (SPEC 4.11): one file with the base applied, as data.
387    pub fn merged(&self) -> Value {
388        let inner = &self.inner;
389        let scope = Scope { model: &inner.model, shapes: &inner.checked.shapes };
390        let reads = |e: EntryId| reads_base(&scope, &inner.checked, e);
391        crate::merged::write(&inner.model.tree, inner.model.root, &reads)
392    }
393
394    /// The merged form as YAML text.
395    pub fn merged_text(&self) -> String {
396        crate::yaml_out::to_yaml(&self.merged())
397    }
398
399    /// The parsed formula or template of a node, for tools.
400    pub fn expressions(&self) -> usize {
401        self.inner.checked.expressions.len()
402    }
403}
404
405fn show(v: &Value) -> String {
406    match v {
407        Value::Null => "null".into(),
408        other => scrusted_feel::json::to_json(other).to_string(),
409    }
410}
411
412/// True when a formula under the entry reads `base` and means this entry's base.
413pub(crate) fn reads_base(scope: &Scope<'_>, checked: &Checked, entry: EntryId) -> bool {
414    let tree = &scope.model.tree;
415    let Some(base) = tree.entry(entry).base else { return false };
416    fn visit(scope: &Scope<'_>, checked: &Checked, node: NodeId, base: EntryId) -> bool {
417        let tree = &scope.model.tree;
418        if let Some(expression) = checked.expressions.get(&node) {
419            for f in expression.formulas() {
420                for r in f.references() {
421                    if &*r.head == "base" && scope.resolve(node, r) == Target::Base(base) {
422                        return true;
423                    }
424                }
425            }
426        }
427        if tree.items(node).iter().any(|i| visit(scope, checked, *i, base)) {
428            return true;
429        }
430        tree.entries_of(node).iter().any(|e| {
431            let entry = tree.entry(*e);
432            visit(scope, checked, entry.value, base) || entry.base.is_some_and(|b| visit(scope, checked, tree.entry(b).value, base))
433        })
434    }
435    visit(scope, checked, tree.entry(entry).value, base)
436}