scrusted-yaml 0.2.0

Validates, loads and resolves scripted-yaml files: YAML with FEEL formulas in marked keys, reloaded live.
Documentation
//! Reads YAML text into the tree, from `saphyr-parser` events (SPEC 4.12, 10): positions,
//! duplicate keys, tags and merge keys are checked here.

use rust_decimal::Decimal;
use saphyr_parser::{Event, Parser, ScalarStyle};
use scrusted_feel::Value;
use std::collections::HashMap;
use std::str::FromStr;
use std::sync::Arc;

use crate::node::{NodeId, Pos, Tree};
use crate::problem::{Place, Problems};

/// Reads YAML text into the tree. Returns the root map, or None when the text cannot be used.
pub fn read_text(tree: &mut Tree, text: &str, file: &str, problems: &mut Problems) -> Option<NodeId> {
    let file: Arc<str> = file.into();
    let mut events = Vec::new();
    let mut parser = Parser::new_from_str(text);
    loop {
        match parser.next_event() {
            None => break,
            Some(Ok((event, span))) => {
                let pos = Pos { file: file.clone(), line: span.start.line() as u32, column: span.start.col() as u32 + 1 };
                let end = matches!(event, Event::StreamEnd);
                events.push((event, pos));
                if end {
                    break;
                }
            }
            Some(Err(error)) => {
                let marker = error.marker();
                let at = Place { file: file.to_string(), line: marker.line() as u32, column: marker.col() as u32 + 1, key: String::new() };
                problems.error(&at, error.info().to_string());
                return None;
            }
        }
    }
    let mut reader = Reader { tree, events, at: 0, file: file.clone(), problems, anchors: HashMap::new() };
    reader.document()
}

struct Reader<'t, 'p, 'e> {
    tree: &'t mut Tree,
    events: Vec<(Event<'e>, Pos)>,
    at: usize,
    file: Arc<str>,
    problems: &'p mut Problems,
    anchors: HashMap<usize, NodeId>,
}

fn place(pos: &Pos) -> Place {
    Place { file: pos.file.to_string(), line: pos.line, column: pos.column, key: String::new() }
}

impl Reader<'_, '_, '_> {
    fn document(&mut self) -> Option<NodeId> {
        let mut root = None;
        let mut documents = 0;
        while self.at < self.events.len() {
            let (event, pos) = &self.events[self.at];
            match event {
                Event::DocumentStart(_) => {
                    documents += 1;
                    if documents > 1 {
                        let at = place(pos);
                        self.problems.error(&at, "a file holds one YAML document; Markdown below a second `---` is not YAML");
                        return None;
                    }
                    self.at += 1;
                    if matches!(self.events.get(self.at), Some((Event::DocumentEnd, _))) {
                        continue;
                    }
                    let pos = self.events[self.at].1.clone();
                    let node = self.node()?;
                    if !self.tree.is_map(node) {
                        self.problems.error(
                            &Place { file: self.file.to_string(), line: 1, column: 1, key: String::new() },
                            "the root of a file must be a map of keys",
                        );
                        return None;
                    }
                    let _ = pos;
                    root = Some(node);
                }
                _ => self.at += 1,
            }
        }
        if self.problems.failed() {
            return None;
        }
        Some(root.unwrap_or_else(|| self.tree.map(Pos { file: self.file.clone(), line: 1, column: 1 })))
    }

    fn refuse_tag(&mut self, pos: &Pos, tag: &str) {
        let message = format!("a tag (`{tag}`) is not supported: YAML would drop it; for not, write not(x); for text, quote the value");
        self.problems.error(&place(pos), message);
    }

    fn node(&mut self) -> Option<NodeId> {
        let (event, pos) = self.events.get(self.at).cloned()?;
        self.at += 1;
        match event {
            Event::Alias(id) => match self.anchors.get(&id).copied() {
                Some(target) => Some(self.tree.clone_node(target)),
                None => {
                    self.problems.error(&place(&pos), "the alias names no anchor");
                    Some(self.tree.scalar(Value::Null, "", pos))
                }
            },
            Event::Scalar(text, style, anchor, tag) => {
                if let Some(tag) = &tag {
                    self.refuse_tag(&pos, &format!("{}{}", tag.handle, tag.suffix));
                }
                let value = if style == ScalarStyle::Plain { plain(&text) } else { Value::String(text.as_ref().into()) };
                let id = self.tree.scalar(value, text.as_ref(), pos);
                if anchor > 0 {
                    self.anchors.insert(anchor, id);
                }
                Some(id)
            }
            Event::SequenceStart(anchor, tag) => {
                if let Some(tag) = &tag {
                    self.refuse_tag(&pos, &format!("{}{}", tag.handle, tag.suffix));
                }
                let list = self.tree.list(pos);
                while !matches!(self.events.get(self.at), Some((Event::SequenceEnd, _)) | None) {
                    let item = self.node()?;
                    self.tree.push_item(list, item, None);
                }
                self.at += 1;
                if anchor > 0 {
                    self.anchors.insert(anchor, list);
                }
                Some(list)
            }
            Event::MappingStart(anchor, tag) => {
                if let Some(tag) = &tag {
                    self.refuse_tag(&pos, &format!("{}{}", tag.handle, tag.suffix));
                }
                let map = self.tree.map(pos);
                // A block map starts at its first key; keep that place.
                if let Some((_, first)) = self.events.get(self.at)
                    && !matches!(self.events.get(self.at), Some((Event::MappingEnd, _)))
                {
                    self.tree.nodes[map].pos = first.clone();
                }
                let mut seen: HashMap<String, ()> = HashMap::new();
                while !matches!(self.events.get(self.at), Some((Event::MappingEnd, _)) | None) {
                    let (key_event, key_pos) = self.events[self.at].clone();
                    let key = match key_event {
                        Event::Scalar(text, style, _, tag) => {
                            self.at += 1;
                            if let Some(tag) = &tag {
                                self.refuse_tag(&key_pos, &format!("{}{}", tag.handle, tag.suffix));
                            }
                            if style == ScalarStyle::Plain && text == "<<" {
                                self.problems.error(&place(&key_pos), "merge keys (<<) are not supported: write the keys out");
                            }
                            Some(text.to_string())
                        }
                        Event::Alias(id) => {
                            self.at += 1;
                            self.anchors.get(&id).and_then(|n| self.tree.scalar_of(*n)).map(|s| s.source.to_string())
                        }
                        _ => {
                            self.problems.error(&place(&key_pos), "a key must be text");
                            let _ = self.node()?;
                            None
                        }
                    };
                    let value = self.node()?;
                    let Some(key) = key else { continue };
                    if seen.insert(key.clone(), ()).is_some() {
                        self.problems.error(&place(&key_pos), format!("Map keys must be unique: \"{key}\" is written twice"));
                        continue;
                    }
                    self.tree.set(map, &key, value, key_pos, None);
                }
                self.at += 1;
                if anchor > 0 {
                    self.anchors.insert(anchor, map);
                }
                Some(map)
            }
            _ => Some(self.tree.scalar(Value::Null, "", pos)),
        }
    }
}

/// The value of a plain scalar, YAML 1.2 core schema: `yes`, `no`, `on`, `off` are text.
pub fn plain(text: &str) -> Value {
    match text {
        "" | "~" | "null" | "Null" | "NULL" => return Value::Null,
        "true" | "True" | "TRUE" => return Value::Bool(true),
        "false" | "False" | "FALSE" => return Value::Bool(false),
        _ => {}
    }
    let bytes = text.as_bytes();
    let digits = |s: &str| !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit());
    let body = text.strip_prefix(['-', '+']).unwrap_or(text);
    if digits(body) {
        if let Ok(n) = Decimal::from_str(text.trim_start_matches('+')) {
            return Value::Number(n.normalize());
        }
        if let Ok(f) = text.parse::<f64>() {
            return Value::from_f64(f);
        }
    }
    if let Some(oct) = text.strip_prefix("0o")
        && !oct.is_empty()
        && oct.bytes().all(|b| (b'0'..=b'7').contains(&b))
        && let Ok(n) = i64::from_str_radix(oct, 8)
    {
        return Value::from(n);
    }
    if let Some(hex) = text.strip_prefix("0x")
        && !hex.is_empty()
        && hex.bytes().all(|b| b.is_ascii_hexdigit())
        && let Ok(n) = i64::from_str_radix(hex, 16)
    {
        return Value::from(n);
    }
    // [-+]?(\.[0-9]+|[0-9]+(\.[0-9]*)?)([eE][-+]?[0-9]+)?
    let (mantissa, exponent) = match body.find(['e', 'E']) {
        Some(i) => (&body[..i], Some(&body[i + 1..])),
        None => (body, None),
    };
    let mantissa_ok = match mantissa.split_once('.') {
        Some((a, b)) => (digits(a) && (b.is_empty() || digits(b))) || (a.is_empty() && digits(b)),
        None => digits(mantissa),
    };
    let exponent_ok = exponent.is_none_or(|e| digits(e.strip_prefix(['-', '+']).unwrap_or(e)));
    if mantissa_ok && exponent_ok && !bytes.is_empty() {
        let clean = text.trim_start_matches('+');
        if exponent.is_none()
            && let Ok(n) = Decimal::from_str(clean.trim_end_matches('.'))
        {
            return Value::Number(n.normalize());
        }
        if let Ok(n) = Decimal::from_scientific(clean) {
            return Value::Number(n.normalize());
        }
        if let Ok(f) = clean.parse::<f64>() {
            return Value::from_f64(f);
        }
    }
    Value::String(text.into())
}

/// Reads data that something else parsed (front matter, JSON): no lines.
pub fn read_value(tree: &mut Tree, value: &Value, file: &str) -> NodeId {
    let pos = Pos { file: file.into(), line: 0, column: 0 };
    match value {
        Value::List(items) => {
            let list = tree.list(pos);
            for item in items.iter() {
                let id = read_value(tree, item, file);
                tree.push_item(list, id, None);
            }
            list
        }
        Value::Map(map) => {
            let node = tree.map(pos.clone());
            for (k, v) in map.iter() {
                let id = read_value(tree, v, file);
                tree.set(node, k, id, pos.clone(), None);
            }
            node
        }
        other => {
            let source = match other {
                Value::Null => String::new(),
                v => v.to_feel_string(),
            };
            tree.scalar(other.clone(), source, pos)
        }
    }
}

/// Reads YAML text as plain data (for variables from a file): keys as written, nothing computed.
pub fn parse_data(text: &str, file: &str) -> Result<Value, Vec<crate::problem::Problem>> {
    let mut tree = Tree::default();
    let mut problems = Problems::default();
    match read_text(&mut tree, text, file, &mut problems) {
        Some(root) if !problems.failed() => Ok(tree.to_data(root)),
        _ => Err(problems.list),
    }
}