vpf-runner 0.4.0

The reference runner of the Verifiable Plan Format (VPF): runs a plan step by step and proves each step.
Documentation
//! References: `{{id}}`, `{{id.field}}`, `{{asked}}` and `{{item}}`, filled with the texts they name.

use std::collections::HashMap;
use std::hash::BuildHasher;

use serde_json::Value;

/// The text with each reference to a known name filled. A field that is not there gives an empty text; a name
/// that is not known stays as it is.
pub fn fill<S: BuildHasher>(text: &str, answers: &HashMap<String, String, S>) -> String {
    let mut filled = String::with_capacity(text.len());
    let mut rest = text;
    while let Some(open) = rest.find("{{") {
        filled.push_str(&rest[..open]);
        let after = &rest[open + 2..];
        let known = after.find("}}").and_then(|close| {
            let reference = after[..close].trim();
            let (name, fields) = reference
                .split_once('.')
                .map_or((reference, None), |(name, fields)| (name, Some(fields)));
            let answer = answers.get(name)?;
            Some((field(answer, fields), close))
        });
        if let Some((answer, close)) = known {
            filled.push_str(&answer);
            rest = &after[close + 2..];
        } else {
            filled.push_str("{{");
            rest = after;
        }
    }
    filled.push_str(rest);
    filled
}

/// The answer itself, or the field `a.b` of it when it is a JSON object.
fn field(answer: &str, fields: Option<&str>) -> String {
    let Some(fields) = fields else {
        return answer.to_owned();
    };
    let Ok(mut value) = serde_json::from_str::<Value>(answer) else {
        return String::new();
    };
    for name in fields.split('.') {
        match value.get_mut(name.trim()) {
            Some(found) => value = found.take(),
            None => return String::new(),
        }
    }
    text(&value)
}

/// A JSON value as a reference fills it: a text as it is, nothing as empty, anything else as JSON.
pub fn text(value: &Value) -> String {
    match value {
        Value::String(text) => text.clone(),
        Value::Null => String::new(),
        other => other.to_string(),
    }
}

/// Whether the text names `asked`.
pub fn names_asked(text: &str) -> bool {
    let mut rest = text;
    while let Some(open) = rest.find("{{") {
        let after = &rest[open + 2..];
        if after
            .find("}}")
            .is_some_and(|close| after[..close].trim() == "asked")
        {
            return true;
        }
        rest = after;
    }
    false
}

#[cfg(test)]
mod tests {
    use std::collections::HashMap;

    use super::{fill, names_asked};

    #[test]
    fn references_are_filled() {
        let answers = HashMap::from([
            ("asked".to_owned(), "March".to_owned()),
            ("numbers".to_owned(), "sales.csv".to_owned()),
        ]);
        assert_eq!(
            fill("Report {{asked}} from {{ numbers }}.", &answers),
            "Report March from sales.csv."
        );
        assert_eq!(fill("{{later}} and {{", &answers), "{{later}} and {{");
        assert_eq!(fill("{{{{asked}}}}", &answers), "{{March}}");
    }

    #[test]
    fn fields_of_json_answers_are_filled() {
        let answers = HashMap::from([
            (
                "deal".to_owned(),
                r#"{"client":{"name":"Ana"},"total":12.5,"tags":["a"],"none":null}"#.to_owned(),
            ),
            ("plain".to_owned(), "not JSON".to_owned()),
        ]);
        assert_eq!(fill("{{deal.client.name}}", &answers), "Ana");
        assert_eq!(fill("{{ deal.total }}", &answers), "12.5");
        assert_eq!(fill("{{deal.tags}}", &answers), r#"["a"]"#);
        assert_eq!(
            fill("[{{deal.none}}|{{deal.missing}}|{{plain.x}}]", &answers),
            "[||]"
        );
    }

    #[test]
    fn asked_is_found() {
        assert!(names_asked("Do {{ asked }}."));
        assert!(!names_asked("Do {{task}}."));
    }
}