1#![forbid(unsafe_code)]
14#![warn(missing_docs)]
15
16#[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#[derive(Debug, Clone, PartialEq)]
60pub enum LoadError {
61 Invalid(Vec<Problem>),
63}
64
65impl LoadError {
66 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#[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
101pub(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#[derive(Clone)]
118pub struct ScrustedYaml {
119 inner: Arc<Library>,
120}
121
122pub struct Builder {
124 files: Arc<dyn Files>,
125 markers: Markers,
126 strict: bool,
127 live: LiveConfig,
128}
129
130impl Builder {
131 pub fn files(mut self, files: impl Files + 'static) -> Self {
133 self.files = Arc::new(files);
134 self
135 }
136
137 pub fn shared_files(mut self, files: Arc<dyn Files>) -> Self {
139 self.files = files;
140 self
141 }
142
143 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 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 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 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 pub fn strict(mut self, strict: bool) -> Self {
176 self.strict = strict;
177 self
178 }
179
180 pub fn run_tests(mut self, run: bool) -> Self {
182 self.live.run_tests = run;
183 self
184 }
185
186 #[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 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 pub fn debounce(mut self, wait: std::time::Duration) -> Self {
201 self.live.debounce = wait;
202 self
203 }
204
205 pub fn poll(mut self, every: std::time::Duration) -> Self {
207 self.live.poll = Some(every);
208 self
209 }
210
211 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
224pub(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 pub fn builder() -> Builder {
234 Builder { files: Arc::new(MemoryFiles::new()), markers: Markers::default(), strict: false, live: LiveConfig::default() }
235 }
236
237 pub fn files(&self) -> Arc<dyn Files> {
239 self.inner.files.clone()
240 }
241
242 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 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 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 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 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 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 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 pub fn marker_names_registered(&self) -> HashSet<String> {
350 self.inner.markers.functions.keys().cloned().collect()
351 }
352}
353
354#[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
371pub 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}