#![forbid(unsafe_code)]
#![warn(missing_docs)]
#[cfg(doctest)]
#[doc = include_str!("../../../README.md")]
pub struct ReadmeDoctests;
pub mod api;
pub mod checker;
pub mod document;
pub mod files;
#[cfg(feature = "live")]
pub mod live;
pub mod marker;
pub mod merged;
pub mod node;
pub mod patch;
pub mod problem;
pub mod reader;
pub mod resolution;
pub mod schema;
pub mod scope;
pub mod source;
pub mod types;
pub mod yaml_out;
use indexmap::IndexMap;
use std::collections::HashSet;
use std::sync::Arc;
pub use api::{AsVars, FromValue, Functions, HostFunction, IntoValue, Marked, Typed, Vars};
pub use document::{Data, Document, MarkedKey, ResolveError, ResolveOptions, TestResult};
pub use files::{DiskFiles, Files, MemoryFiles, Source, Templates};
pub use marker::{MarkerFn, MarkerOutput, Placeholder, placeholder};
pub use problem::{Problem, Severity};
pub use scrusted_feel::{self as feel, HostError, HostValue, Limits, Map, Value};
pub use source::{HostFunctionDecl, Input, Variable};
use crate::checker::Checker;
use crate::files::WithTemplates;
use crate::marker::Markers;
use crate::problem::{Place, Problems};
use crate::source::Loader;
#[derive(Debug, Clone, PartialEq)]
pub enum LoadError {
Invalid(Vec<Problem>),
}
impl LoadError {
pub fn problems(&self) -> &[Problem] {
match self {
LoadError::Invalid(p) => p,
}
}
}
impl std::fmt::Display for LoadError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&problem::error_text(self.problems()))
}
}
impl std::error::Error for LoadError {}
struct Library {
files: Arc<dyn Files>,
markers: Markers,
strict: bool,
#[cfg_attr(not(feature = "live"), allow(dead_code))]
live: LiveConfig,
}
#[derive(Clone)]
#[cfg_attr(not(feature = "live"), allow(dead_code))]
pub(crate) struct LiveConfig {
pub(crate) run_tests: bool,
pub(crate) shapes: Vec<(String, Arc<ShapeCheck>)>,
pub(crate) samples: Vec<(String, Map)>,
pub(crate) debounce: std::time::Duration,
pub(crate) poll: Option<std::time::Duration>,
}
pub(crate) type ShapeCheck = dyn Fn(&Document, &[Map], &ResolveOptions) -> Vec<String> + Send + Sync;
impl Default for LiveConfig {
fn default() -> Self {
LiveConfig {
run_tests: false,
shapes: Vec::new(),
samples: Vec::new(),
debounce: std::time::Duration::from_millis(150),
poll: None,
}
}
}
#[derive(Clone)]
pub struct ScrustedYaml {
inner: Arc<Library>,
}
pub struct Builder {
files: Arc<dyn Files>,
markers: Markers,
strict: bool,
live: LiveConfig,
}
impl Builder {
pub fn files(mut self, files: impl Files + 'static) -> Self {
self.files = Arc::new(files);
self
}
pub fn shared_files(mut self, files: Arc<dyn Files>) -> Self {
self.files = files;
self
}
pub fn marker(mut self, name: &str, f: impl Fn(&Value) -> Result<MarkerOutput, HostError> + Send + Sync + 'static) -> Self {
self.markers.functions.insert(name.to_string(), Some(Arc::new(f)));
self
}
pub fn computed_marker(mut self, name: &str, f: impl Fn(&Value) -> Result<MarkerOutput, HostError> + Send + Sync + 'static) -> Self {
self.markers.functions.insert(name.to_string(), Some(Arc::new(f)));
self.markers.computed.insert(name.to_string());
self
}
pub fn marker_names<S: AsRef<str>>(mut self, names: impl IntoIterator<Item = S>) -> Self {
for n in names {
self.markers.functions.entry(n.as_ref().to_string()).or_insert(None);
}
self
}
pub fn computed_names<S: AsRef<str>>(mut self, names: impl IntoIterator<Item = S>) -> Self {
for n in names {
self.markers.computed.insert(n.as_ref().to_string());
self.markers.functions.entry(n.as_ref().to_string()).or_insert(None);
}
self
}
pub fn strict(mut self, strict: bool) -> Self {
self.strict = strict;
self
}
pub fn run_tests(mut self, run: bool) -> Self {
self.live.run_tests = run;
self
}
#[cfg(feature = "live")]
pub fn shape<T: serde::de::DeserializeOwned + 'static>(mut self, file: &str) -> Self {
self.live.shapes.push((file.to_string(), live::shape_check::<T>()));
self
}
pub fn sample(mut self, file: &str, vars: impl Into<Map>) -> Self {
self.live.samples.push((file.to_string(), vars.into()));
self
}
pub fn debounce(mut self, wait: std::time::Duration) -> Self {
self.live.debounce = wait;
self
}
pub fn poll(mut self, every: std::time::Duration) -> Self {
self.live.poll = Some(every);
self
}
pub fn build(self) -> Result<ScrustedYaml, LoadError> {
Ok(ScrustedYaml {
inner: Arc::new(Library {
files: Arc::new(WithTemplates(self.files)),
markers: self.markers,
strict: self.strict,
live: self.live,
}),
})
}
}
pub(crate) struct CheckedFile {
pub(crate) model: Option<source::Model>,
pub(crate) checked: checker::Checked,
pub(crate) problems: Problems,
}
impl ScrustedYaml {
pub fn builder() -> Builder {
Builder { files: Arc::new(MemoryFiles::new()), markers: Markers::default(), strict: false, live: LiveConfig::default() }
}
pub fn files(&self) -> Arc<dyn Files> {
self.inner.files.clone()
}
pub fn is_strict(&self) -> bool {
self.inner.strict
}
fn read_file(&self, path: &str) -> Result<files::Source, Vec<Problem>> {
let fail = |message: String| {
vec![Problem { file: path.to_string(), line: 0, column: 0, key: String::new(), message, severity: Severity::Error }]
};
match self.inner.files.read(path, None) {
Ok(Some(found)) => Ok(found),
Ok(None) => Err(fail("cannot read the file: it does not exist".into())),
Err(e) => Err(fail(e.to_string())),
}
}
pub fn validate(&self, path: &str) -> Vec<Problem> {
match self.read_file(path) {
Ok(found) => self.validate_text(&found.text, &found.name),
Err(problems) => problems,
}
}
pub fn validate_text(&self, text: &str, file: &str) -> Vec<Problem> {
self.check(&Input::Text(text.to_string()), file, None).problems.list
}
pub fn validate_input(&self, input: &Input, file: &str, base: Option<&Input>) -> Vec<Problem> {
let base_name = format!("{file} (base)");
self.check(input, file, base.map(|b| (base_name.as_str(), b))).problems.list
}
pub(crate) fn check(&self, input: &Input, file: &str, base: Option<(&str, &Input)>) -> CheckedFile {
let mut problems = Problems::default();
let loader = Loader { files: &*self.inner.files };
let mut model = loader.load(input, file, base, &mut problems);
let mut checked = checker::Checked::default();
if let Some(m) = model.as_mut() {
let names = self.inner.markers.names();
checked = Checker::new(m, &names, &self.inner.markers.computed, &mut problems).run();
}
if self.inner.strict {
problems.strict();
}
problems.sort();
CheckedFile { model, checked, problems }
}
pub fn load(&self, path: &str) -> Result<Document, LoadError> {
let found = self.read_file(path).map_err(LoadError::Invalid)?;
self.load_text(&found.text, &found.name)
}
pub fn load_text(&self, text: &str, file: &str) -> Result<Document, LoadError> {
self.load_input(&Input::Text(text.to_string()), file, None)
}
pub fn load_input(&self, input: &Input, file: &str, base: Option<&Input>) -> Result<Document, LoadError> {
let base_name = format!("{file} (base)");
self.open(input, file, base.map(|b| (base_name.as_str(), b)), &mut Vec::new())
}
fn open(&self, input: &Input, file: &str, base: Option<(&str, &Input)>, chain: &mut Vec<String>) -> Result<Document, LoadError> {
let CheckedFile { model, checked, mut problems } = self.check(input, file, base);
let Some(model) = model else { return Err(LoadError::Invalid(problems.list)) };
if problems.failed() {
return Err(LoadError::Invalid(problems.list));
}
let key = self.inner.files.key(file);
let mut imports = IndexMap::new();
let specs: Vec<source::ImportSpec> = model.imported.values().filter(|s| s.found).cloned().collect();
for spec in specs {
let at: Place = model.tree.entry_place(spec.entry);
let target = self.inner.files.key(&spec.file);
if target == key || chain.contains(&target) {
problems.error(&at, "the import comes back to this file: an import cycle");
continue;
}
chain.push(key.clone());
let opened = self.open(&Input::Text(spec.text.clone()), &spec.file, None, chain);
chain.pop();
match opened {
Ok(doc) => {
imports.insert(spec.name.clone(), doc);
}
Err(e) => {
let first = e.problems().iter().find(|p| p.severity == Severity::Error).map(|p| p.to_string()).unwrap_or_default();
problems.error(&at, format!("cannot import \"{}\": {first}", spec.path));
}
}
}
let document = Document::build(model, checked, imports, self.inner.markers.clone(), &mut problems);
problems.sort();
if problems.failed() {
return Err(LoadError::Invalid(problems.list));
}
Ok(document)
}
pub fn marker_names_registered(&self) -> HashSet<String> {
self.inner.markers.functions.keys().cloned().collect()
}
}
#[macro_export]
macro_rules! vars {
() => { $crate::Vars::new() };
($($name:ident : $value:expr),+ $(,)?) => {{
let mut map = $crate::Vars::new();
$( map.insert(stringify!($name).into(), $crate::to_value(&$value).expect("a variable that serializes")); )+
map
}};
}
pub fn to_value<T: serde::Serialize + ?Sized>(value: &T) -> Result<Value, String> {
feel::serde_value::to_value(value).map_err(|e| e.0)
}