Skip to main content

scrusted_yaml/
lib.rs

1//! Scrusted-yaml: validates, loads and resolves scripted-yaml files, YAML with small pieces of
2//! logic in marked keys (`key!:`), with formulas written in FEEL (SPEC.md).
3//!
4//! ```
5//! use scrusted_yaml::{MemoryFiles, ScrustedYaml, ResolveOptions, vars};
6//!
7//! let files = MemoryFiles::from_pairs([("limits.yml", "$vars:\n  plan: {}\nper_minute!: if vars.plan = \"pro\" then 600 else 60\n")]);
8//! let scrusted = ScrustedYaml::builder().files(files).build().unwrap();
9//! let document = scrusted.load("limits.yml").unwrap();
10//! let value = document.resolve(&vars! { plan: "pro" }, &ResolveOptions::default()).unwrap();
11//! assert_eq!(value.as_map().unwrap()["per_minute"], scrusted_feel::Value::from(600));
12//! ```
13#![forbid(unsafe_code)]
14#![warn(missing_docs)]
15
16/// The examples of the README, run as doctests.
17#[cfg(doctest)]
18#[doc = include_str!("../../../README.md")]
19pub struct ReadmeDoctests;
20
21pub mod api;
22pub mod checker;
23pub mod document;
24pub mod files;
25#[cfg(feature = "live")]
26pub mod live;
27pub mod marker;
28pub mod merged;
29pub mod node;
30pub mod patch;
31pub mod problem;
32pub mod reader;
33pub mod resolution;
34pub mod schema;
35pub mod scope;
36pub mod source;
37pub mod types;
38pub mod yaml_out;
39
40use indexmap::IndexMap;
41use std::collections::HashSet;
42use std::sync::Arc;
43
44pub use api::{AsVars, FromValue, Functions, HostFunction, IntoValue, Marked, Typed, Vars};
45pub use document::{Data, Document, MarkedKey, ResolveError, ResolveOptions, TestResult};
46pub use files::{DiskFiles, Files, MemoryFiles, Source, Templates};
47pub use marker::{MarkerFn, MarkerOutput, Placeholder, placeholder};
48pub use problem::{Problem, Severity};
49pub use scrusted_feel::{self as feel, HostError, HostValue, Limits, Map, Value};
50pub use source::{HostFunctionDecl, Input, Variable};
51
52use crate::checker::Checker;
53use crate::files::WithTemplates;
54use crate::marker::Markers;
55use crate::problem::{Place, Problems};
56use crate::source::Loader;
57
58/// Why a file does not load.
59#[derive(Debug, Clone, PartialEq)]
60pub enum LoadError {
61    /// The file has errors: every problem found, warnings included.
62    Invalid(Vec<Problem>),
63}
64
65impl LoadError {
66    /// The problems.
67    pub fn problems(&self) -> &[Problem] {
68        match self {
69            LoadError::Invalid(p) => p,
70        }
71    }
72}
73
74impl std::fmt::Display for LoadError {
75    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
76        f.write_str(&problem::error_text(self.problems()))
77    }
78}
79
80impl std::error::Error for LoadError {}
81
82struct Library {
83    files: Arc<dyn Files>,
84    markers: Markers,
85    strict: bool,
86    #[cfg_attr(not(feature = "live"), allow(dead_code))]
87    live: LiveConfig,
88}
89
90/// What a live set checks before a change goes live, and how it learns of changes (SPEC 6).
91#[derive(Clone)]
92#[cfg_attr(not(feature = "live"), allow(dead_code))]
93pub(crate) struct LiveConfig {
94    pub(crate) run_tests: bool,
95    pub(crate) shapes: Vec<(String, Arc<ShapeCheck>)>,
96    pub(crate) samples: Vec<(String, Map)>,
97    pub(crate) debounce: std::time::Duration,
98    pub(crate) poll: Option<std::time::Duration>,
99}
100
101/// The shape gate of one file: checks a document against a Rust type.
102pub(crate) type ShapeCheck = dyn Fn(&Document, &[Map], &ResolveOptions) -> Vec<String> + Send + Sync;
103
104impl Default for LiveConfig {
105    fn default() -> Self {
106        LiveConfig {
107            run_tests: false,
108            shapes: Vec::new(),
109            samples: Vec::new(),
110            debounce: std::time::Duration::from_millis(150),
111            poll: None,
112        }
113    }
114}
115
116/// Validates and loads scripted-yaml files. `Send + Sync + Clone`.
117#[derive(Clone)]
118pub struct ScrustedYaml {
119    inner: Arc<Library>,
120}
121
122/// Builds a [`ScrustedYaml`].
123pub struct Builder {
124    files: Arc<dyn Files>,
125    markers: Markers,
126    strict: bool,
127    live: LiveConfig,
128}
129
130impl Builder {
131    /// Where paths are read from. Default: no files (memory).
132    pub fn files(mut self, files: impl Files + 'static) -> Self {
133        self.files = Arc::new(files);
134        self
135    }
136
137    /// Files shared with something else.
138    pub fn shared_files(mut self, files: Arc<dyn Files>) -> Self {
139        self.files = files;
140        self
141    }
142
143    /// A marker function: it gets the value as written.
144    pub fn marker(mut self, name: &str, f: impl Fn(&Value) -> Result<MarkerOutput, HostError> + Send + Sync + 'static) -> Self {
145        self.markers.functions.insert(name.to_string(), Some(Arc::new(f)));
146        self
147    }
148
149    /// A computed marker: its value is checked and computed like any value; at resolve its
150    /// function gets the computed value (SPEC 4.6).
151    pub fn computed_marker(mut self, name: &str, f: impl Fn(&Value) -> Result<MarkerOutput, HostError> + Send + Sync + 'static) -> Self {
152        self.markers.functions.insert(name.to_string(), Some(Arc::new(f)));
153        self.markers.computed.insert(name.to_string());
154        self
155    }
156
157    /// Markers by name only, for a checker that validates and does not load.
158    pub fn marker_names<S: AsRef<str>>(mut self, names: impl IntoIterator<Item = S>) -> Self {
159        for n in names {
160            self.markers.functions.entry(n.as_ref().to_string()).or_insert(None);
161        }
162        self
163    }
164
165    /// Names of markers whose value is computed like any value.
166    pub fn computed_names<S: AsRef<str>>(mut self, names: impl IntoIterator<Item = S>) -> Self {
167        for n in names {
168            self.markers.computed.insert(n.as_ref().to_string());
169            self.markers.functions.entry(n.as_ref().to_string()).or_insert(None);
170        }
171        self
172    }
173
174    /// Every warning is an error.
175    pub fn strict(mut self, strict: bool) -> Self {
176        self.strict = strict;
177        self
178    }
179
180    /// Runs each `$tests` entry of every file before a change goes live (SPEC 6.2, gate 5).
181    pub fn run_tests(mut self, run: bool) -> Self {
182        self.live.run_tests = run;
183        self
184    }
185
186    /// A file whose result must deserialize into `T` (SPEC 6.2, gate 6).
187    #[cfg(feature = "live")]
188    pub fn shape<T: serde::de::DeserializeOwned + 'static>(mut self, file: &str) -> Self {
189        self.live.shapes.push((file.to_string(), live::shape_check::<T>()));
190        self
191    }
192
193    /// Variables a file is resolved with before a change goes live; the result must fit its shape.
194    pub fn sample(mut self, file: &str, vars: impl Into<Map>) -> Self {
195        self.live.samples.push((file.to_string(), vars.into()));
196        self
197    }
198
199    /// How long a change on disk settles before it is read (default 150 ms).
200    pub fn debounce(mut self, wait: std::time::Duration) -> Self {
201        self.live.debounce = wait;
202        self
203    }
204
205    /// Asks the source for versions at this interval, for sources that are not a folder on disk.
206    pub fn poll(mut self, every: std::time::Duration) -> Self {
207        self.live.poll = Some(every);
208        self
209    }
210
211    /// The library.
212    pub fn build(self) -> Result<ScrustedYaml, LoadError> {
213        Ok(ScrustedYaml {
214            inner: Arc::new(Library {
215                files: Arc::new(WithTemplates(self.files)),
216                markers: self.markers,
217                strict: self.strict,
218                live: self.live,
219            }),
220        })
221    }
222}
223
224/// What `check` leaves: the model and its validation, and the problems.
225pub(crate) struct CheckedFile {
226    pub(crate) model: Option<source::Model>,
227    pub(crate) checked: checker::Checked,
228    pub(crate) problems: Problems,
229}
230
231impl ScrustedYaml {
232    /// A builder.
233    pub fn builder() -> Builder {
234        Builder { files: Arc::new(MemoryFiles::new()), markers: Markers::default(), strict: false, live: LiveConfig::default() }
235    }
236
237    /// The files the library reads.
238    pub fn files(&self) -> Arc<dyn Files> {
239        self.inner.files.clone()
240    }
241
242    /// True when warnings are errors.
243    pub fn is_strict(&self) -> bool {
244        self.inner.strict
245    }
246
247    fn read_file(&self, path: &str) -> Result<files::Source, Vec<Problem>> {
248        let fail = |message: String| {
249            vec![Problem { file: path.to_string(), line: 0, column: 0, key: String::new(), message, severity: Severity::Error }]
250        };
251        match self.inner.files.read(path, None) {
252            Ok(Some(found)) => Ok(found),
253            Ok(None) => Err(fail("cannot read the file: it does not exist".into())),
254            Err(e) => Err(fail(e.to_string())),
255        }
256    }
257
258    /// Checks a file and returns its problems (SPEC 5.3).
259    pub fn validate(&self, path: &str) -> Vec<Problem> {
260        match self.read_file(path) {
261            Ok(found) => self.validate_text(&found.text, &found.name),
262            Err(problems) => problems,
263        }
264    }
265
266    /// Checks text that is not in a file; `file` names it in the problems.
267    pub fn validate_text(&self, text: &str, file: &str) -> Vec<Problem> {
268        self.check(&Input::Text(text.to_string()), file, None).problems.list
269    }
270
271    /// Checks text or data, optionally as a patch of a base the application holds.
272    pub fn validate_input(&self, input: &Input, file: &str, base: Option<&Input>) -> Vec<Problem> {
273        let base_name = format!("{file} (base)");
274        self.check(input, file, base.map(|b| (base_name.as_str(), b))).problems.list
275    }
276
277    pub(crate) fn check(&self, input: &Input, file: &str, base: Option<(&str, &Input)>) -> CheckedFile {
278        let mut problems = Problems::default();
279        let loader = Loader { files: &*self.inner.files };
280        let mut model = loader.load(input, file, base, &mut problems);
281        let mut checked = checker::Checked::default();
282        if let Some(m) = model.as_mut() {
283            let names = self.inner.markers.names();
284            checked = Checker::new(m, &names, &self.inner.markers.computed, &mut problems).run();
285        }
286        if self.inner.strict {
287            problems.strict();
288        }
289        problems.sort();
290        CheckedFile { model, checked, problems }
291    }
292
293    /// Validates a file, applies `$extends`, loads `.yml` imports and calls each marker function
294    /// once. No formula is computed (SPEC 5.4).
295    pub fn load(&self, path: &str) -> Result<Document, LoadError> {
296        let found = self.read_file(path).map_err(LoadError::Invalid)?;
297        self.load_text(&found.text, &found.name)
298    }
299
300    /// The same for text that is not in a file.
301    pub fn load_text(&self, text: &str, file: &str) -> Result<Document, LoadError> {
302        self.load_input(&Input::Text(text.to_string()), file, None)
303    }
304
305    /// The same for text or data, optionally as a patch of a base the application holds.
306    pub fn load_input(&self, input: &Input, file: &str, base: Option<&Input>) -> Result<Document, LoadError> {
307        let base_name = format!("{file} (base)");
308        self.open(input, file, base.map(|b| (base_name.as_str(), b)), &mut Vec::new())
309    }
310
311    fn open(&self, input: &Input, file: &str, base: Option<(&str, &Input)>, chain: &mut Vec<String>) -> Result<Document, LoadError> {
312        let CheckedFile { model, checked, mut problems } = self.check(input, file, base);
313        let Some(model) = model else { return Err(LoadError::Invalid(problems.list)) };
314        if problems.failed() {
315            return Err(LoadError::Invalid(problems.list));
316        }
317        let key = self.inner.files.key(file);
318        let mut imports = IndexMap::new();
319        let specs: Vec<source::ImportSpec> = model.imported.values().filter(|s| s.found).cloned().collect();
320        for spec in specs {
321            let at: Place = model.tree.entry_place(spec.entry);
322            let target = self.inner.files.key(&spec.file);
323            if target == key || chain.contains(&target) {
324                problems.error(&at, "the import comes back to this file: an import cycle");
325                continue;
326            }
327            chain.push(key.clone());
328            let opened = self.open(&Input::Text(spec.text.clone()), &spec.file, None, chain);
329            chain.pop();
330            match opened {
331                Ok(doc) => {
332                    imports.insert(spec.name.clone(), doc);
333                }
334                Err(e) => {
335                    let first = e.problems().iter().find(|p| p.severity == Severity::Error).map(|p| p.to_string()).unwrap_or_default();
336                    problems.error(&at, format!("cannot import \"{}\": {first}", spec.path));
337                }
338            }
339        }
340        let document = Document::build(model, checked, imports, self.inner.markers.clone(), &mut problems);
341        problems.sort();
342        if problems.failed() {
343            return Err(LoadError::Invalid(problems.list));
344        }
345        Ok(document)
346    }
347
348    /// The names of the registered markers.
349    pub fn marker_names_registered(&self) -> HashSet<String> {
350        self.inner.markers.functions.keys().cloned().collect()
351    }
352}
353
354/// Builds the variables of a resolve from `name: value` pairs; values are anything
355/// `serde::Serialize` (SPEC 5.6).
356///
357/// ```
358/// let vars = scrusted_yaml::vars! { plan: "pro", per_day: 1000 };
359/// assert_eq!(vars.len(), 2);
360/// ```
361#[macro_export]
362macro_rules! vars {
363    () => { $crate::Vars::new() };
364    ($($name:ident : $value:expr),+ $(,)?) => {{
365        let mut map = $crate::Vars::new();
366        $( map.insert(stringify!($name).into(), $crate::to_value(&$value).expect("a variable that serializes")); )+
367        map
368    }};
369}
370
371/// Any `serde::Serialize` as a value.
372pub fn to_value<T: serde::Serialize + ?Sized>(value: &T) -> Result<Value, String> {
373    feel::serde_value::to_value(value).map_err(|e| e.0)
374}