scrusted-yaml 0.2.0

Validates, loads and resolves scripted-yaml files: YAML with FEEL formulas in marked keys, reloaded live.
Documentation
//! What the application registers: marker functions (SPEC 4.6, 5.7).

use scrusted_feel::{HostError, HostValue, Value};
use std::collections::{HashMap, HashSet};
use std::sync::Arc;

/// What a marker function returns.
#[derive(Clone, Debug)]
pub enum MarkerOutput {
    /// Eager: the value is known at load.
    Value(Value),
    /// Lazy: kept, and read only when a formula reads the marked key.
    Host(Arc<dyn HostValue>),
}

impl MarkerOutput {
    /// As a value: a host value is wrapped.
    pub fn into_value(self) -> Value {
        match self {
            MarkerOutput::Value(v) => v,
            MarkerOutput::Host(h) => Value::Host(h),
        }
    }
}

impl From<Value> for MarkerOutput {
    fn from(v: Value) -> Self {
        MarkerOutput::Value(v)
    }
}

/// A marker function: it gets the value as written (or computed, for a computed marker).
pub type MarkerFn = Arc<dyn Fn(&Value) -> Result<MarkerOutput, HostError> + Send + Sync>;

/// The markers of a library: a function per name, or the name alone for checking only.
#[derive(Clone, Default)]
pub struct Markers {
    /// By name; None: registered by name only.
    pub functions: HashMap<String, Option<MarkerFn>>,
    /// Markers whose value is text or data computed like any other.
    pub computed: HashSet<String>,
}

impl Markers {
    /// The registered names, sorted.
    pub fn names(&self) -> Vec<String> {
        let mut names: Vec<String> = self.functions.keys().cloned().collect();
        names.sort();
        names
    }
}

/// A marked value as the command line and the conformance suite show it: the marker and the
/// value as written. A formula that reads it gets the text written.
#[derive(Debug, Clone)]
pub struct Placeholder {
    /// The marker name.
    pub marker: String,
    /// The value as written.
    pub source: Value,
}

impl HostValue for Placeholder {
    fn read(&self) -> Result<Value, HostError> {
        Ok(match &self.source {
            Value::String(s) => Value::String(s.clone()),
            other => Value::from(scrusted_feel::json::to_json(other).to_string()),
        })
    }

    fn serialize(&self) -> Option<serde_json::Value> {
        Some(serde_json::json!({ "marker": self.marker, "source": scrusted_feel::json::to_json(&self.source) }))
    }
}

/// A marker function that keeps the value as written, as a [`Placeholder`].
pub fn placeholder(name: &str) -> MarkerFn {
    let name = name.to_string();
    Arc::new(move |source: &Value| Ok(MarkerOutput::Host(Arc::new(Placeholder { marker: name.clone(), source: source.clone() }))))
}