scrusted-yaml 0.2.0

Validates, loads and resolves scripted-yaml files: YAML with FEEL formulas in marked keys, reloaded live.
Documentation
//! What a name in a formula stands for at a place in the file (SPEC 4.3).

use rustc_hash::FxHashMap as HashMap;
use scrusted_feel::{Formula, Reference, Template, builtins};
use std::sync::Arc;

use crate::node::{EntryId, KeyKind, NodeId, Tree};
use crate::schema::Shape;
use crate::source::{Model, ROOT_KEYWORDS};

/// A formula or a text with `{{ }}`.
#[derive(Debug, Clone)]
pub enum Expression {
    /// `key!: formula`
    Formula(Formula),
    /// `key: text {{ formula }}`
    Text(Template),
}

impl Expression {
    /// Each formula it holds.
    pub fn formulas(&self) -> Vec<&Formula> {
        match self {
            Expression::Formula(f) => vec![f],
            Expression::Text(t) => t.formulas().collect(),
        }
    }

    /// The text as written.
    pub fn source(&self) -> &str {
        match self {
            Expression::Formula(f) => f.source(),
            Expression::Text(t) => t.source(),
        }
    }
}

/// What a name stands for.
#[derive(Debug, Clone, PartialEq)]
pub enum Target {
    /// Nothing.
    Unknown,
    /// A built-in function.
    Builtin,
    /// `vars`
    Vars,
    /// The `$as` name of a `$each!` item.
    Each(NodeId),
    /// A name a schema says the application supplies (`with`).
    Given,
    /// `base` in a patch: the entry that was replaced.
    Base(EntryId),
    /// A `$functions` formula.
    Function(EntryId),
    /// A `$functions` entry the application passes.
    Hosted(String),
    /// An imported name.
    Import(String),
    /// A key of the file.
    Key(EntryId),
}

/// How far a path such as `stages.explore.when` goes through the file before a value takes over.
#[derive(Debug, Clone)]
pub struct Reach {
    /// The entry reached; None for a list item.
    pub entry: Option<EntryId>,
    /// The node reached.
    pub node: NodeId,
    /// The path names followed through the file.
    pub steps: Vec<String>,
    /// The node after each step; the first is the value of the head key.
    pub nodes: Vec<NodeId>,
    /// A name that is not a key of the map it was looked up in: the name and the map.
    pub missing: Option<(String, NodeId)>,
    /// The whole path.
    pub path: Vec<Arc<str>>,
}

impl Reach {
    /// The path names left for FEEL to follow inside the value.
    pub fn rest(&self) -> &[Arc<str>] {
        &self.path[self.steps.len()..]
    }
}

/// Name lookup in a file.
pub struct Scope<'a> {
    /// The file.
    pub model: &'a Model,
    /// The shape each map was checked against.
    pub shapes: &'a HashMap<NodeId, Arc<Shape>>,
}

/// The name a `$each!` item gives each value: its `$as`, or `item`.
pub fn each_name(tree: &Tree, item: NodeId) -> String {
    tree.scalar_field(item, "$as").map(crate::node::js_string).unwrap_or_else(|| "item".into())
}

impl Scope<'_> {
    fn tree(&self) -> &Tree {
        &self.model.tree
    }

    /// What `r` means when it is read at `reader`.
    pub fn resolve(&self, reader: NodeId, r: &Reference) -> Target {
        let tree = self.tree();
        let chain = std::iter::successors(Some(reader), |n| tree.node(*n).parent);
        for node in chain.clone() {
            if tree.is_map(node)
                && let Some(each) = tree.get(node, "$each")
                && tree.node(reader).entry != Some(each)
                && *r.head == *each_name(tree, node)
            {
                return Target::Each(node);
            }
            if let Some(e) = tree.node(node).entry {
                let entry = tree.entry(e);
                if let Some(shape) = self.shapes.get(&entry.map)
                    && shape.with.get(&*entry.key.name).is_some_and(|names| names.iter().any(|n| **n == *r.head))
                {
                    return Target::Given;
                }
            }
        }
        if &*r.head == "vars" {
            return Target::Vars;
        }
        let replaced = chain.clone().find_map(|n| tree.node(n).entry.and_then(|e| tree.entry(e).base));
        if &*r.head == "base"
            && let Some(b) = replaced
        {
            return Target::Base(b);
        }
        if r.call
            && let Some(t) = self.callable(&r.head, true)
        {
            return t;
        }
        for map in self.maps(reader) {
            if let Some(e) = tree.find(map, &r.head)
                && !tree.entry(e).key.keyword()
            {
                return Target::Key(e);
            }
        }
        self.callable(&r.head, r.call).unwrap_or(Target::Unknown)
    }

    /// What a name means in a formula written at the top of the file (a key under `expect`).
    pub fn resolve_root(&self, r: &Reference) -> Target {
        if &*r.head == "vars" {
            return Target::Vars;
        }
        if r.call
            && let Some(t) = self.callable(&r.head, true)
        {
            return t;
        }
        if let Some(e) = self.tree().find(self.model.root, &r.head)
            && !self.tree().entry(e).key.keyword()
        {
            return Target::Key(e);
        }
        self.callable(&r.head, r.call).unwrap_or(Target::Unknown)
    }

    /// Follows a path from a key through the maps and lists of the file.
    pub fn walk(&self, start: EntryId, path: &[Arc<str>], find: &dyn Fn(NodeId, &str) -> Option<EntryId>) -> Reach {
        let tree = self.tree();
        let first = tree.entry(start).value;
        let mut reach =
            Reach { entry: Some(start), node: first, steps: Vec::new(), nodes: vec![first], missing: None, path: path.to_vec() };
        for name in path {
            if let Some(e) = reach.entry
                && tree.entry(e).key.kind() != KeyKind::Plain
            {
                break;
            }
            let node = reach.node;
            if tree.is_map(node) {
                match find(node, name).filter(|e| !tree.entry(*e).key.keyword()) {
                    Some(next) => {
                        reach.entry = Some(next);
                        reach.node = tree.entry(next).value;
                    }
                    None => {
                        if tree.get(node, "$value").is_none() {
                            reach.missing = Some((name.to_string(), node));
                        }
                        break;
                    }
                }
            } else if tree.is_list(node) {
                match tree.by_id(node, name) {
                    Some(item) => {
                        reach.entry = None;
                        reach.node = item;
                    }
                    None => break,
                }
            } else {
                break;
            }
            reach.steps.push(name.to_string());
            reach.nodes.push(reach.node);
        }
        reach
    }

    /// The names a formula at this place could have meant, for "did you mean".
    pub fn names(&self, reader: NodeId) -> Vec<String> {
        let tree = self.tree();
        let mut out = vec!["vars".to_string()];
        for map in self.maps(reader) {
            for e in tree.entries_of(map) {
                let entry = tree.entry(*e);
                if !entry.key.keyword() {
                    out.push(entry.key.name.to_string());
                }
            }
        }
        out.extend(self.model.functions.keys().cloned());
        out.extend(self.model.hosted.keys().cloned());
        out.extend(self.model.imported.keys().cloned());
        out
    }

    fn callable(&self, name: &str, builtins_too: bool) -> Option<Target> {
        if let Some(e) = self.model.functions.get(name) {
            return Some(Target::Function(*e));
        }
        if self.model.hosted.contains_key(name) {
            return Some(Target::Hosted(name.to_string()));
        }
        if self.model.imported.contains_key(name) {
            return Some(Target::Import(name.to_string()));
        }
        (builtins_too && builtins::is_builtin(name)).then_some(Target::Builtin)
    }

    /// The maps a bare name is looked up in: the one around the formula, each enclosing one, the root.
    pub fn maps(&self, reader: NodeId) -> Vec<NodeId> {
        let tree = self.tree();
        let root = self.model.root;
        let mut chain = vec![reader];
        chain.extend(tree.ancestors(reader));
        let top = chain.iter().find(|n| tree.node(**n).parent == Some(root));
        if let Some(top) = top
            && let Some(e) = tree.node(*top).entry
            && ROOT_KEYWORDS.contains(&&*tree.entry(e).key.name)
        {
            return vec![root];
        }
        tree.ancestors(reader).into_iter().filter(|n| tree.is_map(*n)).collect()
    }
}