use indexmap::IndexMap;
use rustc_hash::FxHashMap as HashMap;
use scrusted_feel::{EvalOptions, Map, Value};
use std::sync::{Arc, RwLock};
use crate::checker::Checked;
use crate::marker::Markers;
use crate::node::{EntryId, KeyKind, NodeId};
use crate::problem::{Problem, Problems};
use crate::resolution::{HostFunctions, Resolution};
use crate::scope::{Expression, Scope, Target};
use crate::source::{HostFunctionDecl, Model, Variable};
#[derive(Clone)]
pub struct MarkedKey {
inner: Arc<DocInner>,
entry: EntryId,
}
impl MarkedKey {
pub fn path(&self) -> String {
self.inner.model.tree.entry_path(self.entry)
}
pub fn marker(&self) -> String {
self.inner.model.tree.entry(self.entry).key.marker_name().to_string()
}
pub fn source(&self) -> Value {
let tree = &self.inner.model.tree;
tree.to_data(tree.entry(self.entry).value)
}
pub fn value(&self) -> Value {
self.inner.marked_value(self.entry)
}
pub fn set(&self, value: Value) {
if let Some(cell) = self.inner.marked.get(&self.entry) {
*cell.write().unwrap_or_else(|e| e.into_inner()) = (value, true);
}
}
}
#[derive(Debug, Clone, PartialEq, serde::Serialize)]
pub struct TestResult {
pub about: String,
pub failures: Vec<String>,
}
impl TestResult {
pub fn passed(&self) -> bool {
self.failures.is_empty()
}
}
#[derive(Clone, Default)]
pub struct ResolveOptions {
pub functions: crate::api::Functions,
pub clock: Option<scrusted_feel::Clock>,
pub strict_nulls: bool,
pub limits: scrusted_feel::Limits,
}
impl ResolveOptions {
pub fn function(mut self, name: &str, f: impl Fn(&[Value]) -> Result<Value, scrusted_feel::HostError> + Send + Sync + 'static) -> Self {
self.functions = self.functions.add_raw(name, f);
self
}
pub fn functions(mut self, functions: crate::api::Functions) -> Self {
self.functions = functions;
self
}
pub(crate) fn eval_options(&self) -> EvalOptions {
EvalOptions { clock: self.clock.clone(), strict_nulls: self.strict_nulls, limits: self.limits }
}
}
impl std::fmt::Debug for ResolveOptions {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ResolveOptions").field("functions", &self.functions).field("strict_nulls", &self.strict_nulls).finish()
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct ResolveError {
pub problems: Vec<Problem>,
}
impl ResolveError {
pub fn file(&self) -> &str {
self.problems.first().map(|p| p.file.as_str()).unwrap_or("")
}
pub fn key(&self) -> &str {
self.problems.first().map(|p| p.key.as_str()).unwrap_or("")
}
pub fn message(&self) -> &str {
self.problems.first().map(|p| p.message.as_str()).unwrap_or("")
}
}
impl std::fmt::Display for ResolveError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&crate::problem::error_text(&self.problems))
}
}
impl std::error::Error for ResolveError {}
pub struct DocInner {
pub(crate) model: Model,
pub(crate) checked: Checked,
pub(crate) imports: IndexMap<String, Document>,
pub(crate) markers: Markers,
pub(crate) marked: HashMap<EntryId, RwLock<(Value, bool)>>,
pub(crate) marked_order: Vec<EntryId>,
}
impl DocInner {
pub(crate) fn marked_value(&self, e: EntryId) -> Value {
self.marked.get(&e).map(|c| c.read().unwrap_or_else(|e| e.into_inner()).0.clone()).unwrap_or(Value::Null)
}
pub(crate) fn marked_set(&self, e: EntryId) -> bool {
self.marked.get(&e).is_some_and(|c| c.read().unwrap_or_else(|e| e.into_inner()).1)
}
}
#[derive(Clone)]
pub struct Document {
pub(crate) inner: Arc<DocInner>,
}
impl std::fmt::Debug for Document {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Document").field("file", &self.inner.model.file).finish()
}
}
#[derive(Debug, Clone)]
pub enum Data {
Value(Value),
Formula {
source: String,
reads: Vec<String>,
},
Text {
source: String,
reads: Vec<String>,
},
Map(IndexMap<String, Data>),
List(Vec<Data>),
Marked(Value),
}
impl Document {
pub(crate) fn build(
model: Model,
checked: Checked,
imports: IndexMap<String, Document>,
markers: Markers,
problems: &mut Problems,
) -> Document {
let mut marked = HashMap::default();
let mut marked_order = Vec::new();
{
let scope = Scope { model: &model, shapes: &checked.shapes };
let tree = &model.tree;
let mut order = Vec::new();
fn walk(tree: &crate::node::Tree, model: &Model, node: NodeId, scope: &Scope<'_>, checked: &Checked, out: &mut Vec<EntryId>) {
for item in tree.items(node) {
walk(tree, model, *item, scope, checked, out);
}
let own: Vec<EntryId> = if node == model.root { model.data() } else { tree.entries_of(node).to_vec() };
for e in own {
let entry = tree.entry(e);
if entry.key.kind() == KeyKind::Marked {
out.push(e);
} else {
walk(tree, model, entry.value, scope, checked, out);
}
let mut holder = e;
while let Some(base) = tree.entry(holder).base {
if !reads_base(scope, checked, holder) {
break;
}
if tree.entry(base).key.kind() == KeyKind::Marked {
out.push(base);
} else {
walk(tree, model, tree.entry(base).value, scope, checked, out);
}
holder = base;
}
}
}
walk(tree, &model, model.root, &scope, &checked, &mut order);
for e in order {
let entry = tree.entry(e);
let marker = entry.key.marker_name().to_string();
let at = tree.entry_place(e);
match markers.functions.get(&marker) {
Some(Some(f)) => {
let source = tree.to_data(entry.value);
match f(&source) {
Ok(out) => {
marked.insert(e, RwLock::new((out.into_value(), false)));
marked_order.push(e);
}
Err(error) => problems.error(&at, format!("the function of the marker \"{marker}\" failed: {error}")),
}
}
_ => problems
.error(&at, format!("the marker \"{marker}\" was registered by name only; loading a file needs its function")),
}
}
}
Document { inner: Arc::new(DocInner { model, checked, imports, markers, marked, marked_order }) }
}
pub fn file(&self) -> &str {
&self.inner.model.file
}
pub fn vars(&self) -> Vec<Variable> {
self.inner.model.variables.declared.values().cloned().collect()
}
pub fn functions(&self) -> Vec<HostFunctionDecl> {
self.inner.model.hosted.values().cloned().collect()
}
pub fn marked(&self) -> Vec<MarkedKey> {
self.inner.marked_order.iter().map(|e| MarkedKey { inner: self.inner.clone(), entry: *e }).collect()
}
pub fn data(&self) -> Data {
self.data_of(self.inner.model.root)
}
fn data_of(&self, node: NodeId) -> Data {
let inner = &self.inner;
let tree = &inner.model.tree;
if let Some(expression) = inner.checked.expressions.get(&node) {
let reads = inner.checked.reads.get(&node).cloned().unwrap_or_default();
let source = expression.source().to_string();
return match expression {
Expression::Formula(_) => {
Data::Formula { source: tree.scalar_of(node).map(|s| s.source.to_string()).unwrap_or(source), reads }
}
Expression::Text(_) => Data::Text { source, reads },
};
}
if tree.is_list(node) {
return Data::List(tree.items(node).iter().map(|i| self.data_of(*i)).collect());
}
if tree.is_map(node) {
let entries = if node == inner.model.root { inner.model.data() } else { tree.entries_of(node).to_vec() };
let mut out = IndexMap::new();
for e in entries {
let entry = tree.entry(e);
let value =
if entry.key.kind() == KeyKind::Marked { Data::Marked(inner.marked_value(e)) } else { self.data_of(entry.value) };
out.insert(entry.key.name.to_string(), value);
}
return Data::Map(out);
}
Data::Value(tree.to_data(node))
}
pub fn resolve(&self, vars: &(impl crate::api::AsVars + ?Sized), options: &ResolveOptions) -> Result<Value, ResolveError> {
let vars = vars.as_vars();
let resolution = Resolution::new(&self.inner, vars, &options.functions.0, options.eval_options())
.map_err(|p| ResolveError { problems: vec![*p] })?;
resolution.run().map_err(|p| ResolveError { problems: vec![*p] })
}
pub fn resolve_as<T: serde::de::DeserializeOwned>(
&self,
vars: &(impl crate::api::AsVars + ?Sized),
options: &ResolveOptions,
) -> Result<T, ResolveError> {
let value = self.resolve(vars, options)?;
scrusted_feel::serde_value::from_value(value).map_err(|e| ResolveError {
problems: vec![Problem {
file: self.file().to_string(),
line: 0,
column: 0,
key: String::new(),
message: format!("the result does not fit the type {}: {}", std::any::type_name::<T>(), e.0),
severity: crate::problem::Severity::Error,
}],
})
}
pub(crate) fn view(&self, vars: &Map, functions: &HostFunctions, options: EvalOptions) -> Result<Value, Vec<Problem>> {
let resolution = Resolution::new(&self.inner, vars, functions, options).map_err(|p| vec![*p])?;
resolution.view().map_err(|p| vec![*p])
}
pub fn test(&self, options: &ResolveOptions) -> Vec<TestResult> {
let tests = self.inner.model.tests();
tests
.iter()
.enumerate()
.map(|(index, test)| {
let get = |k: &str| test.as_map().and_then(|m| m.get(k)).cloned().unwrap_or(Value::Null);
let about = get("about").as_str().map(str::to_string).unwrap_or_else(|| format!("test {}", index + 1));
let vars = get("vars").as_map().cloned().unwrap_or_default();
let expect = get("expect").as_map().cloned().unwrap_or_default();
let mut failures = Vec::new();
match Resolution::new(&self.inner, &vars, &options.functions.0, options.eval_options()) {
Err(p) => failures.push(p.to_string()),
Ok(resolution) => match resolution.run() {
Err(p) => failures.push(p.to_string()),
Ok(_) => {
for (path, expected) in expect.iter() {
match resolution.probe(path) {
Ok(actual) => {
if actual.feel_eq(expected) != Some(true) {
failures.push(format!("{path}: expected {}, got {}", show(expected), show(&actual)));
}
}
Err(p) => failures.push(p.to_string()),
}
}
}
},
}
TestResult { about, failures }
})
.collect()
}
pub fn merged(&self) -> Value {
let inner = &self.inner;
let scope = Scope { model: &inner.model, shapes: &inner.checked.shapes };
let reads = |e: EntryId| reads_base(&scope, &inner.checked, e);
crate::merged::write(&inner.model.tree, inner.model.root, &reads)
}
pub fn merged_text(&self) -> String {
crate::yaml_out::to_yaml(&self.merged())
}
pub fn expressions(&self) -> usize {
self.inner.checked.expressions.len()
}
}
fn show(v: &Value) -> String {
match v {
Value::Null => "null".into(),
other => scrusted_feel::json::to_json(other).to_string(),
}
}
pub(crate) fn reads_base(scope: &Scope<'_>, checked: &Checked, entry: EntryId) -> bool {
let tree = &scope.model.tree;
let Some(base) = tree.entry(entry).base else { return false };
fn visit(scope: &Scope<'_>, checked: &Checked, node: NodeId, base: EntryId) -> bool {
let tree = &scope.model.tree;
if let Some(expression) = checked.expressions.get(&node) {
for f in expression.formulas() {
for r in f.references() {
if &*r.head == "base" && scope.resolve(node, r) == Target::Base(base) {
return true;
}
}
}
}
if tree.items(node).iter().any(|i| visit(scope, checked, *i, base)) {
return true;
}
tree.entries_of(node).iter().any(|e| {
let entry = tree.entry(*e);
visit(scope, checked, entry.value, base) || entry.base.is_some_and(|b| visit(scope, checked, tree.entry(b).value, base))
})
}
visit(scope, checked, tree.entry(entry).value, base)
}