use indexmap::IndexMap;
use regex::Regex;
use scrusted_feel::Value;
use std::sync::Arc;
use crate::files::Files;
use crate::node::{EntryId, KeyKind, NodeId, Tree, js_string};
use crate::patch::Patch;
use crate::problem::{Place, Problems};
use crate::schema::Schema;
use crate::{merged, reader};
pub const ROOT_KEYWORDS: &[&str] = &["$vars", "$functions", "$import", "$schema", "$dsl", "$extends", "$tests"];
#[derive(Debug, Clone)]
pub enum Input {
Text(String),
Data(Value),
}
#[derive(Debug, Clone, PartialEq)]
pub struct Variable {
pub name: String,
pub optional: bool,
pub secret: bool,
pub host: bool,
pub ty: Option<String>,
pub about: Option<String>,
pub default: Option<Value>,
}
impl Variable {
pub fn required(&self) -> bool {
!self.optional && self.default.is_none()
}
pub fn mismatch(&self, value: &Value) -> Option<String> {
if value.is_null() {
return None;
}
let fits = match self.ty.as_deref()? {
"text" => matches!(value, Value::String(_)),
"number" => matches!(value, Value::Number(_)),
"boolean" => matches!(value, Value::Bool(_)),
"list" => matches!(value, Value::List(_)),
_ => return None,
};
if fits {
None
} else {
Some(format!("variable \"{}\" must be a {}; variables are not converted", self.name, self.ty.as_deref().unwrap_or("")))
}
}
}
#[derive(Debug, Clone, Default)]
pub struct Variables {
pub declared: IndexMap<String, Variable>,
patterns: Vec<Regex>,
known: Vec<String>,
}
pub struct VarValues {
pub values: scrusted_feel::Map,
pub missing: Vec<String>,
pub mismatches: Vec<String>,
}
impl Variables {
pub fn add(&mut self, tree: &Tree, node: Option<NodeId>, problems: &mut Problems, for_checking: bool) {
let Some(node) = node else { return };
if !tree.is_map(node) {
problems.error(&tree.place(node), "$vars must be a map of variable names");
return;
}
for e in tree.entries_of(node) {
let entry = tree.entry(*e);
let name = entry.key.raw.to_string();
if name.len() > 2 && name.starts_with('/') && name.ends_with('/') {
match Regex::new(&format!("^(?:{})$", &name[1..name.len() - 1])) {
Ok(re) => self.patterns.push(re),
Err(error) => problems.error(&tree.entry_place(*e), format!("not a regular expression: {error}")),
}
} else if for_checking {
self.known.push(name);
} else {
let settings = tree.to_data(entry.value);
if !settings.is_null() && !tree.is_map(entry.value) {
problems.error(
&tree.place(entry.value),
format!("variable \"{name}\" is declared with a map: {{ default: …, optional: true }}"),
);
continue;
}
let get = |k: &str| settings.as_map().and_then(|m| m.get(k)).cloned();
let text = |k: &str| get(k).and_then(|v| v.as_str().map(str::to_string));
let variable = Variable {
name: name.clone(),
optional: get("optional") == Some(Value::Bool(true)),
secret: get("secret") == Some(Value::Bool(true)),
host: get("host") == Some(Value::Bool(true)),
ty: text("type"),
about: text("about"),
default: settings.as_map().and_then(|m| m.get("default")).filter(|v| !v.is_null()).cloned(),
};
self.declared.insert(name, variable);
}
}
}
pub fn knows(&self, name: &str) -> bool {
self.declared.contains_key(name) || self.known.iter().any(|k| k == name) || self.patterns.iter().any(|p| p.is_match(name))
}
pub fn values(&self, input: &scrusted_feel::Map) -> VarValues {
let mut values = scrusted_feel::Map::new();
for (k, v) in input {
let v = if v.as_str() == Some("") { Value::Null } else { v.clone() };
values.insert(k.clone(), v);
}
let mut missing = Vec::new();
let mut mismatches = Vec::new();
for var in self.declared.values() {
let current = values.get(var.name.as_str()).cloned().unwrap_or(Value::Null);
let current = if current.is_null() { var.default.clone().unwrap_or(Value::Null) } else { current };
if current.is_null() && var.required() {
missing.push(var.name.clone());
}
if let Some(m) = var.mismatch(¤t) {
mismatches.push(m);
}
values.insert(var.name.as_str().into(), current);
}
VarValues { values, missing, mismatches }
}
pub fn secrets(&self) -> Vec<String> {
self.declared.values().filter(|v| v.secret).map(|v| v.name.clone()).collect()
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct HostFunctionDecl {
pub name: String,
pub parameters: Option<Vec<String>>,
pub about: Option<String>,
pub entry: EntryId,
}
pub struct Signature {
pub name: String,
pub parameters: Option<Vec<String>>,
}
impl Signature {
pub fn new(key: &str) -> Signature {
match key.find('(') {
Some(open) if open > 0 && key.ends_with(')') => Signature {
name: key[..open].trim().to_string(),
parameters: Some(key[open + 1..key.len() - 1].split(',').map(|p| p.trim().to_string()).filter(|p| !p.is_empty()).collect()),
},
_ => Signature { name: key.to_string(), parameters: None },
}
}
pub fn define(&self, body: &str) -> String {
format!("function({}) {body}", self.parameters.as_deref().unwrap_or(&[]).join(", "))
}
}
#[derive(Debug, Clone)]
pub struct ImportSpec {
pub path: String,
pub file: String,
pub text: String,
pub name: String,
pub entry: EntryId,
pub found: bool,
}
pub struct Model {
pub file: String,
pub tree: Tree,
pub root: NodeId,
pub variables: Variables,
pub functions: IndexMap<String, EntryId>,
pub function_text: std::collections::HashMap<EntryId, String>,
pub hosted: IndexMap<String, HostFunctionDecl>,
pub imported: IndexMap<String, ImportSpec>,
pub schema: Option<Schema>,
}
pub fn code_hint(names: &[String]) -> String {
let example = names.first().map(|n| format!("{n}(…)")).unwrap_or_else(|| "fileExists(path)".into());
format!("Scrusted-yaml does not import code. Declare `{example}` under `$functions` without `!`, and pass it to `resolve`.")
}
impl Model {
pub fn data(&self) -> Vec<EntryId> {
self.tree.entries_of(self.root).iter().copied().filter(|e| !ROOT_KEYWORDS.contains(&&*self.tree.entry(*e).key.name)).collect()
}
pub fn tests(&self) -> Vec<Value> {
match self.tree.get(self.root, "$tests").map(|e| self.tree.to_data(self.tree.entry(e).value)) {
Some(Value::List(items)) => items.to_vec(),
_ => Vec::new(),
}
}
fn read_functions(&mut self, problems: &mut Problems) {
let Some(e) = self.tree.get(self.root, "$functions") else { return };
let node = self.tree.entry(e).value;
if !self.tree.is_map(node) {
problems.error(&self.tree.place(node), "$functions must be a map: name(parameter)!: formula");
return;
}
for f in self.tree.entries_of(node).to_vec() {
let entry = self.tree.entry(f).clone();
let signature = Signature::new(&entry.key.name);
let at = self.tree.entry_place(f);
match entry.key.kind() {
KeyKind::Plain => {
let settings = self.tree.to_data(entry.value);
if !settings.is_null() && !self.tree.is_map(entry.value) {
problems.error(&at, format!("\"{}\" declares a function the application passes, with a map: {{ about: … }}; for a formula, write \"{}!\"", entry.key.raw, entry.key.raw));
continue;
}
if self.functions.contains_key(&signature.name) || self.hosted.contains_key(&signature.name) {
problems.error(&at, format!("the function \"{}\" is declared twice in $functions; keep one", signature.name));
continue;
}
let about = settings.as_map().and_then(|m| m.get("about")).and_then(|v| v.as_str().map(str::to_string));
self.hosted.insert(
signature.name.clone(),
HostFunctionDecl { name: signature.name.clone(), parameters: signature.parameters.clone(), about, entry: f },
);
}
KeyKind::Marked => problems.error(&at, format!("a function is a formula: write \"{}(…)!: …\"", signature.name)),
KeyKind::Formula => {
if self.hosted.contains_key(&signature.name) {
problems.error(&at, format!("the function \"{}\" is declared twice in $functions; keep one", signature.name));
}
if signature.parameters.is_some()
&& let Some(s) = self.tree.scalar_of(entry.value)
{
self.function_text.insert(f, signature.define(&s.source));
}
self.functions.insert(signature.name.clone(), f);
}
}
}
}
fn read_imports(&mut self, loader: &Loader<'_>, problems: &mut Problems) {
let Some(e) = self.tree.get(self.root, "$import") else { return };
let node = self.tree.entry(e).value;
if !self.tree.is_map(node) {
problems.error(&self.tree.place(node), "$import must be a map: path: names");
return;
}
for i in self.tree.entries_of(node).to_vec() {
let entry = self.tree.entry(i).clone();
let path = entry.key.raw.to_string();
let at = self.tree.entry_place(i);
let wanted = self.tree.to_data(entry.value);
if [".ts", ".js"].iter().any(|x| path.ends_with(x)) {
let names: Vec<String> = match &wanted {
Value::List(l) => l.iter().map(js_string).collect(),
Value::String(s) => vec![s.to_string()],
_ => Vec::new(),
};
problems.error(&at, format!("cannot import \"{path}\": {}", code_hint(&names)));
continue;
}
if path.ends_with(".md") {
problems.error(&at, format!("cannot import \"{path}\": Scrusted-yaml does not import Markdown. Read it in the application and pass what a formula needs as a variable, or declare a function under `$functions` without `!` and pass it to `resolve`."));
continue;
}
if !(path.ends_with(".yml") || path.ends_with(".yaml")) {
problems.error(&at, format!("cannot import \"{path}\": there is no importer for this kind of file (only .yml, .yaml)"));
continue;
}
let Value::String(name) = &wanted else {
problems.error(&at, format!("\"{path}\" is imported under one name: {path}: name"));
continue;
};
let found = loader.find(&self.tree, i, &path, "import", problems);
let spec = ImportSpec {
path: path.clone(),
file: found.as_ref().map(|f| f.name.clone()).unwrap_or_else(|| path.clone()),
text: found.as_ref().map(|f| f.text.clone()).unwrap_or_default(),
name: name.to_string(),
entry: i,
found: found.is_some(),
};
self.imported.insert(name.to_string(), spec);
}
}
}
pub struct Loader<'a> {
pub files: &'a dyn Files,
}
impl Loader<'_> {
pub fn load(&self, input: &Input, file: &str, base: Option<(&str, &Input)>, problems: &mut Problems) -> Option<Model> {
let mut tree = Tree::default();
let chain = vec![self.files.key(file)];
let root = match base {
Some((base_file, base_input)) => {
let patch = self.parse(&mut tree, input, file, problems)?;
if let Some(e) = tree.get(patch, "$extends") {
problems.error(&tree.entry_place(e), "a patch given its base by the application does not name one with $extends");
return None;
}
let mut chain = chain.clone();
chain.push(self.files.key(base_file));
let target = self.tree(&mut tree, base_input, base_file, &chain, problems)?;
Patch { tree: &mut tree, problems }.apply(patch, target);
target
}
None => self.tree(&mut tree, input, file, &chain, problems)?,
};
let mut model = Model {
file: file.to_string(),
tree,
root,
variables: Variables::default(),
functions: IndexMap::new(),
function_text: Default::default(),
hosted: IndexMap::new(),
imported: IndexMap::new(),
schema: None,
};
let vars = model.tree.get(root, "$vars").map(|e| model.tree.entry(e).value);
model.variables.add(&model.tree, vars, problems, false);
model.read_functions(problems);
model.read_imports(self, problems);
let dsl = self.read_dsl(&mut model, problems);
let schema = model.tree.get(root, "$schema").map(|e| model.tree.entry(e).value).or_else(|| {
let d = dsl?;
model.tree.get(d, "$schema").map(|e| model.tree.entry(e).value)
});
if let Some(schema) = schema {
model.schema = Some(Schema::new(&model.tree, schema, problems));
}
Some(model)
}
fn read_dsl(&self, model: &mut Model, problems: &mut Problems) -> Option<NodeId> {
let e = model.tree.get(model.root, "$dsl")?;
let value = model.tree.entry(e).value;
let Some(path) = model.tree.scalar_of(value).and_then(|s| s.value.as_str().map(str::to_string)) else {
problems.error(&model.tree.entry_place(e), "$dsl names one file by its path");
return None;
};
let dsl = self.read(&mut model.tree, e, &path, &[], problems)?;
let vars = model.tree.get(dsl, "$vars").map(|v| model.tree.entry(v).value);
let mut variables = std::mem::take(&mut model.variables);
variables.add(&model.tree, vars, problems, true);
model.variables = variables;
Some(dsl)
}
pub fn find(&self, tree: &Tree, from: EntryId, path: &str, purpose: &str, problems: &mut Problems) -> Option<crate::files::Source> {
let file = tree.entry(from).pos.file.to_string();
let from_name = if file.is_empty() { None } else { Some(file.as_str()) };
match self.files.read(path, from_name) {
Ok(Some(found)) => Some(found),
Ok(None) => {
problems.error(&tree.entry_place(from), format!("cannot {purpose} \"{path}\": the file does not exist"));
None
}
Err(error) => {
problems.error(&tree.entry_place(from), error.to_string());
None
}
}
}
fn read(&self, tree: &mut Tree, from: EntryId, path: &str, chain: &[String], problems: &mut Problems) -> Option<NodeId> {
let found = self.find(tree, from, path, "read", problems)?;
let key = self.files.key(&found.name);
if chain.contains(&key) {
problems.error(&tree.entry_place(from), format!("\"{path}\" extends itself, directly or through other files"));
return None;
}
let mut chain = chain.to_vec();
chain.push(key);
self.tree(tree, &Input::Text(found.text), &found.name, &chain, problems)
}
fn tree(&self, tree: &mut Tree, input: &Input, file: &str, chain: &[String], problems: &mut Problems) -> Option<NodeId> {
let root = self.parse(tree, input, file, problems)?;
let Some(base) = tree.get(root, "$extends") else { return Some(root) };
let value = tree.entry(base).value;
let Some(path) = tree.scalar_of(value).and_then(|s| s.value.as_str().map(str::to_string)) else {
problems.error(&tree.entry_place(base), "$extends names one file by its path");
return None;
};
let target = self.read(tree, base, &path, chain, problems)?;
Patch { tree, problems }.apply(root, target);
Some(target)
}
fn parse(&self, tree: &mut Tree, input: &Input, file: &str, problems: &mut Problems) -> Option<NodeId> {
let root = match input {
Input::Text(text) => reader::read_text(tree, text, file, problems)?,
Input::Data(value) => {
if value.is_null() {
tree.map(crate::node::Pos { file: file.into(), line: 0, column: 0 })
} else {
let root = reader::read_value(tree, value, file);
if !tree.is_map(root) {
problems.error(
&Place { file: file.to_string(), line: 1, column: 1, key: String::new() },
"the root of a file must be a map of keys",
);
return None;
}
root
}
}
};
merged::restore(tree, root, problems);
Some(root)
}
}
pub type Imported = Arc<ImportSpec>;