scrusted-yaml 0.2.0

Validates, loads and resolves scripted-yaml files: YAML with FEEL formulas in marked keys, reloaded live.
Documentation
//! Rust types from a `$schema` (SPEC 13, milestone 8): `scrusted-yaml types <file>`.

use std::fmt::Write;

use crate::Document;
use crate::schema::{Field, Schema, Shape};

const KEYWORDS: &[&str] = &[
    "as", "break", "const", "continue", "crate", "else", "enum", "extern", "false", "fn", "for", "if", "impl", "in", "let", "loop",
    "match", "mod", "move", "mut", "pub", "ref", "return", "self", "Self", "static", "struct", "super", "trait", "true", "type", "unsafe",
    "use", "where", "while", "async", "await", "dyn", "abstract", "become", "box", "do", "final", "macro", "override", "priv", "typeof",
    "unsized", "virtual", "yield", "try", "gen",
];

fn pascal(name: &str) -> String {
    let out = scrusted_feel::builtins::pascal_case(name);
    if out.is_empty() || out.starts_with(|c: char| c.is_ascii_digit()) { format!("T{out}") } else { out }
}

fn snake(name: &str) -> String {
    let out = scrusted_feel::builtins::snake_case(name);
    let out = if out.is_empty() || out.starts_with(|c: char| c.is_ascii_digit()) { format!("f_{out}") } else { out };
    if KEYWORDS.contains(&out.as_str()) { format!("r#{out}") } else { out }
}

struct Writer<'a> {
    schema: &'a Schema,
    out: String,
    one_or_many: bool,
    many: bool,
}

impl Writer<'_> {
    fn field_type(&self, field: &Field) -> String {
        let item = match &field.ty {
            // text unless said, but a field written `key!` computes any value
            None => "scrusted_yaml::Value".to_string(),
            Some(t) => pascal(t),
        };
        if field.many {
            format!("Many<{item}>")
        } else if field.one_or_many {
            format!("OneOrMany<{item}>")
        } else {
            item
        }
    }

    fn shape(&mut self, name: &str, shape: &Shape, about: &str) {
        let _ = writeln!(self.out, "/// {about}");
        let _ = writeln!(self.out, "#[derive(Debug, Clone, PartialEq, serde::Deserialize)]");
        let _ = writeln!(self.out, "pub struct {} {{", pascal(name));
        for field in shape.fields.values() {
            self.one_or_many |= field.one_or_many;
            self.many |= field.many;
            let ident = snake(&field.name);
            let plain = ident.trim_start_matches("r#");
            if plain != field.name {
                let _ = writeln!(self.out, "    #[serde(rename = \"{}\")]", field.name);
            }
            let ty = self.field_type(field);
            let ty = if field.required { ty } else { format!("Option<{ty}>") };
            let _ = writeln!(self.out, "    pub {ident}: {ty},");
        }
        let _ = writeln!(self.out, "}}\n");
    }

    fn words(&mut self, name: &str, words: &[String]) {
        let _ = writeln!(self.out, "/// One of: {}.", words.join(", "));
        let _ = writeln!(self.out, "#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Deserialize)]");
        let _ = writeln!(self.out, "pub enum {} {{", pascal(name));
        for word in words {
            let _ = writeln!(self.out, "    #[serde(rename = \"{word}\")]");
            let _ = writeln!(self.out, "    {},", pascal(word));
        }
        let _ = writeln!(self.out, "}}\n");
    }
}

/// Rust structs for the `$schema` of a document: the file itself, each shape, each set of words.
/// None when the file has no schema.
pub fn rust_types(document: &Document) -> Option<String> {
    let schema = document.inner.model.schema.as_ref()?;
    let file = document.file().rsplit('/').next().unwrap_or("file");
    let root_name = file.split('.').next().unwrap_or("file");
    let mut w = Writer { schema, out: String::new(), one_or_many: false, many: false };
    let _ = writeln!(w.out, "// Generated by `scrusted-yaml types {}` from its $schema.\n", document.file());
    let root = schema.root.clone();
    w.shape(root_name, &root, &format!("The resolved file {}.", document.file()));
    let mut shapes: Vec<_> = w.schema.shapes.iter().map(|(n, s)| (n.clone(), s.clone())).collect();
    shapes.sort_by(|a, b| a.0.cmp(&b.0));
    for (name, shape) in shapes {
        w.shape(&name, &shape, &format!("A {name} of the schema."));
    }
    let mut words: Vec<_> = w.schema.words.iter().map(|(n, s)| (n.clone(), s.clone())).collect();
    words.sort_by(|a, b| a.0.cmp(&b.0));
    for (name, list) in words {
        w.words(&name, &list);
    }
    if w.many {
        w.out.push_str(
            "/// Many values (`agents*`): a list, or a map whose keys are the items' names.\n#[derive(Debug, Clone, PartialEq, serde::Deserialize)]\n#[serde(untagged)]\npub enum Many<T> {\n    /// A list.\n    List(Vec<T>),\n    /// A map of items by name.\n    Map(std::collections::BTreeMap<String, T>),\n}\n\n",
        );
    }
    if w.one_or_many {
        w.out.push_str(
            "/// One value, or a list of them (`files+`).\n#[derive(Debug, Clone, PartialEq, serde::Deserialize)]\n#[serde(untagged)]\npub enum OneOrMany<T> {\n    /// One value.\n    One(T),\n    /// A list.\n    Many(Vec<T>),\n}\n",
        );
    }
    Some(w.out.trim_end().to_string() + "\n")
}