pub(crate) mod branch_semantics;
pub(crate) mod compute;
pub(crate) mod conversion_trace;
pub mod evaluate_data;
pub mod explanations;
pub mod expression;
pub(crate) mod list_ops;
pub(crate) mod lookup;
pub(crate) mod narration;
pub mod response;
pub(crate) mod rows;
pub(crate) mod tree;
pub use crate::computation::OperationResult;
use crate::computation::VetoType;
use crate::evaluation::response::EvaluatedRule;
use crate::planning::execution_plan::{
reachable_data_paths, reachable_data_paths_and_unsettled, ExecutableRule, ExecutionPlan,
ReachableInput, RuleIndex, TargetForce,
};
use crate::planning::normalize::{LeafKind, NormalFormId, NormalFormKind};
use crate::planning::semantics::{
lemma_type_arc_with_display_binding, BoundValueKind, DataDefinition, DataPath,
ImportEffectivePin, InstanceKey, LemmaType, ListValue, LiteralValue, ReferenceTarget,
RowBinding, RowEnd, RowInstance, RulePath, TypedLiteral, ValueKind,
};
use crate::string_distance::closest_name;
pub use evaluate_data::{EvaluateData, EvaluateDataValue};
use indexmap::IndexMap;
pub use response::{Response, RuleResult};
use std::cell::RefCell;
use std::collections::{HashMap, HashSet};
use std::rc::Rc;
use std::sync::Arc;
fn closest_ignored_key(needed: &str, ignored: &[String]) -> Option<String> {
closest_name(needed, ignored)
}
#[cfg(feature = "call-graph-check")]
fn member_scale_read(
template: &ExecutionPlan,
target: &crate::planning::semantics::ReferenceTarget,
) -> Option<crate::planning::execution_plan::CallSite> {
use crate::planning::semantics::ReferenceTarget;
let (segments, end) = match target {
ReferenceTarget::Data(path) => (
&path.segments,
RowEnd::Data(DataPath::local(path.data.clone())),
),
ReferenceTarget::Rule(path) => (
&path.segments,
RowEnd::Rule(crate::planning::semantics::RulePath::new(
Vec::new(),
path.rule.clone(),
)),
),
};
if segments.is_empty() || segments.iter().any(|segment| segment.row.is_some()) {
return None;
}
let mut current = template;
let mut rows = Vec::with_capacity(segments.len());
for segment in segments {
let Some(DataDefinition::Import { row, .. }) =
current.data.get(&DataPath::local(segment.uses.to_string()))
else {
return None;
};
rows.push(Arc::as_ptr(row) as usize);
current = current.row_template(&row.identity);
}
Some(crate::planning::execution_plan::CallSite::Read(rows, end))
}
#[cfg(feature = "call-graph-check")]
fn check_call_log(plan: &ExecutionPlan, caches: &RequestCaches) {
let what = &plan.spec_name;
use crate::planning::execution_plan::CallSite;
use crate::planning::semantics::RowOrigin;
fn locate<'p>(
plan: &'p ExecutionPlan,
context: Option<&InstanceKey>,
representatives: &HashMap<usize, usize>,
) -> (&'p ExecutionPlan, Vec<usize>, Vec<usize>) {
let mut chain: Vec<&InstanceKey> = Vec::new();
let mut cursor = context;
while let Some(key) = cursor {
chain.push(key);
cursor = key.owner();
}
chain.reverse();
let mut current = plan;
let mut closed: Vec<usize> = Vec::new();
let mut rows: Vec<usize> = Vec::new();
for key in chain {
let address = Arc::as_ptr(&key.row) as usize;
let made_by_request = key.row.origin.is_request();
if made_by_request {
{
for binding in key.row.bindings.iter().flatten() {
assert!(
!key.row.origin.is_inline()
|| !matches!(binding, RowBinding::Deferred { .. }),
"BUG: row {key}, written inline, carries a deferred binding"
);
}
current = current.row_template(&key.row.identity);
closed.push(address);
rows.clear();
}
continue;
}
match key.row.origin {
RowOrigin::Numbered { .. } | RowOrigin::Inline { .. } => {
unreachable!("BUG: a row the request made is closed above")
}
RowOrigin::Import { .. } => rows.push(address),
RowOrigin::Written { .. } => {
rows.push(*representatives.get(&address).unwrap_or(&address))
}
}
}
(current, closed, rows)
}
let site = |rows: Vec<usize>, end: &RowEnd| match (rows.is_empty(), end) {
(true, RowEnd::Rule(rule)) => Some(CallSite::Rule(rule.clone())),
(true, RowEnd::Data(_)) => None,
(false, end) => Some(CallSite::Read(rows, end.clone())),
};
let mut plans: Vec<&ExecutionPlan> = vec![plan];
let mut seen_plans: HashSet<*const ExecutionPlan> = HashSet::new();
let mut representatives: HashMap<usize, usize> = HashMap::new();
while let Some(holder) = plans.pop() {
if !seen_plans.insert(holder) {
continue;
}
for source in holder.instance_lists.values() {
representatives.extend(
source
.store
.shape_representatives()
.map(|(row, first)| (Arc::as_ptr(row) as usize, Arc::as_ptr(first) as usize)),
);
}
plans.extend(holder.row_templates.values().map(AsRef::as_ref));
}
let log = caches.call_log.borrow();
let callers: HashMap<*const CallAt, Option<&Rc<CallAt>>> = log
.iter()
.map(|start| (Rc::as_ptr(&start.started), start.caller.as_ref()))
.collect();
let starts: HashSet<&CallStart> = log.iter().collect();
let piece_at = |piece: &CallAt| match piece {
CallAt::In(at, end) => Some((at.clone(), end.clone())),
CallAt::Settle(at, rule) => Some((Some(at.clone()), RowEnd::Rule(rule.clone()))),
CallAt::Materialize(_) => None,
};
'starts: for CallStart {
caller,
started,
nesting,
} in starts
{
let Some((started_at, started_end)) = piece_at(started) else {
assert!(
caller.is_none(),
"{what}: a row materialized inside {caller:?}"
);
continue;
};
let (started_plan, started_closed, started_rows) =
locate(plan, started_at.as_ref(), &representatives);
if started_closed.is_empty() {
assert!(
*nesting <= plan.call_graph.depth,
"{what}: {nesting} pieces nested at {started:?}, past the call graph's bound {}",
plan.call_graph.depth
);
}
let mut piece = match caller {
Some(piece) => piece,
None => continue,
};
let (caller_plan, caller_rows, caller_end) = loop {
let Some((caller_at, caller_end)) = piece_at(piece) else {
continue 'starts;
};
let (caller_plan, caller_closed, caller_rows) =
locate(plan, caller_at.as_ref(), &representatives);
if started_closed.last() == caller_closed.last() {
break (caller_plan, caller_rows, caller_end);
}
if started_closed
.last()
.is_some_and(|row| !caller_closed.contains(row))
{
continue 'starts;
}
piece = callers
.get(&Rc::as_ptr(piece))
.copied()
.flatten()
.unwrap_or_else(|| {
panic!(
"{what}: {caller:?} started {started:?}, outside the closed row it runs under"
)
});
};
let (caller_end, started_end) = (&caller_end, &started_end);
assert!(
std::ptr::eq(caller_plan, started_plan),
"BUG: one closed row, two plans"
);
let to = site(started_rows, started_end).unwrap_or_else(|| {
panic!("{what}: {caller:?} started {started:?}, a closed row's own data")
});
let Some(from) = site(caller_rows, caller_end) else {
let RowEnd::Data(path) = caller_end else {
unreachable!("BUG: only a data end has no site");
};
let needs: Vec<CallSite> = caller_plan
.options_rule_of(path)
.into_iter()
.chain(match caller_plan.reference_ends.get(path) {
Some(crate::planning::semantics::ReferenceEnd::Rule(rule)) => {
Some(rule.clone())
}
Some(crate::planning::semantics::ReferenceEnd::Promptable(_)) | None => None,
})
.chain(
caller_plan.data_scale_targets(path).iter().filter_map(
|scale| match caller_plan.target_force(&scale.target) {
Some(TargetForce::Rule(rule)) => {
Some(caller_plan.rule_at(rule).path.clone())
}
Some(TargetForce::Member(_)) | None => None,
},
),
)
.map(CallSite::Rule)
.chain(
caller_plan
.data_scale_targets(path)
.iter()
.filter_map(|scale| member_scale_read(caller_plan, &scale.target)),
)
.collect();
assert!(
needs.contains(&to),
"{what}: {caller:?} started {started:?}, which its data does not need"
);
continue;
};
let mut found = caller_plan
.call_graph
.callees
.get(&from)
.is_some_and(|callees| callees.contains(&to));
let mut reached: Vec<CallSite> = if found {
Vec::new()
} else {
vec![from.clone()]
};
let mut seen: HashSet<CallSite> = HashSet::new();
while let Some(site) = reached.pop() {
if !seen.insert(site.clone()) {
continue;
}
for callee in caller_plan
.call_graph
.callees
.get(&site)
.into_iter()
.flatten()
{
if *callee == to {
found = true;
}
let inline = match (&from, callee) {
(CallSite::Read(rows, _), CallSite::Read(callee_rows, _)) => {
rows == callee_rows
}
(CallSite::Rule(_), CallSite::Rule(_)) => true,
(CallSite::Rule(_), CallSite::Read(..))
| (CallSite::Read(..), CallSite::Rule(_)) => false,
};
if inline {
reached.push(callee.clone());
}
}
}
assert!(
found,
"{what}: {caller:?} started {started:?}, which the call graph of '{}' has no edge for ({from:?} -> {to:?}); it lists {:?}",
caller_plan.spec_name,
caller_plan.call_graph.callees.get(&from)
);
}
}
fn run_request_program(
plan: &ExecutionPlan,
context: &mut EvaluationContext,
requested: impl IntoIterator<Item = RuleIndex>,
) {
use crate::planning::program::{request_program, Entry, RequestStep};
for step in request_program(plan, requested) {
match step {
RequestStep::Run(Entry::Rule(rule)) => tree::ensure_rule_values(rule, plan, context),
RequestStep::Run(Entry::Leaf(leaf)) => {
if context.leaf_unsettled(leaf.index()) {
tree::ensure_leaf_value(leaf, plan, context);
}
}
RequestStep::Run(entry @ (Entry::Cell(_) | Entry::Materialize)) => {
panic!("BUG: a request's root program runs no {entry:?}")
}
RequestStep::SelectBody(slot) => {
let (path, definition) = plan
.data
.get_index(slot)
.expect("BUG: a body selection names a slot of the plan");
let DataDefinition::Import { pin: Some(pin), .. } = definition else {
panic!("BUG: body selection on '{path}', which has no `-> effective` pin");
};
let body = select_dynamic_body(plan, context, path, pin);
context.caches.select_body(None, path.clone(), body);
}
}
}
}
pub(crate) fn select_dynamic_body(
plan: &ExecutionPlan,
context: &mut EvaluationContext,
path: &DataPath,
pin: &ImportEffectivePin,
) -> Result<Arc<RowInstance>, OperationResult> {
let at = evaluate_effective_pin(plan, context, pin)?;
plan.select_dynamic_import_row(path, &at)
.map(Arc::clone)
.ok_or_else(|| {
OperationResult::Veto(VetoType::computation(format!(
"no version of this import is active at {at}"
)))
})
}
pub(crate) fn read_import_key(
plan: &ExecutionPlan,
holder: Option<&InstanceKey>,
slot: &DataPath,
caches: &RequestCaches,
) -> Option<InstanceKey> {
let selected = match plan.data.get(slot) {
Some(DataDefinition::Import { pin: Some(_), .. }) => match caches.body(holder, slot) {
Some(Ok(body)) => Some(body),
Some(Err(_)) | None => return None,
},
_ => None,
};
Some(plan.import_key(holder, slot, selected.as_ref(), &caches.globals))
}
fn evaluate_effective_pin(
plan: &ExecutionPlan,
context: &mut EvaluationContext,
pin: &ImportEffectivePin,
) -> Result<crate::parsing::ast::EffectiveDate, OperationResult> {
match pin {
ImportEffectivePin::Data(path) => {
let Some(slot) = plan.data.get_index_of(path) else {
panic!("BUG: effective pin data '{path}' missing from plan");
};
let leaf = plan.data_slot_leaves[slot];
match &context.values[leaf.index()] {
None => Err(OperationResult::Veto(VetoType::missing_data(
path.clone(),
None,
))),
Some(OperationResult::Veto(_)) => {
Err(context.values[leaf.index()].clone().expect("veto"))
}
Some(OperationResult::Value(literal)) => match &literal.value {
ValueKind::Date(date) => Ok(crate::parsing::ast::EffectiveDate::DateTimeValue(
semantic_date_to_datetime(date),
)),
other => panic!(
"BUG: `-> effective` pin '{path}' is not a date after planning, got {other:?}"
),
},
}
}
ImportEffectivePin::Rule(rule_path) => {
let index = plan.rule_index(rule_path);
match &context.rule_values[index.index()] {
None => panic!("BUG: effective pin rule '{rule_path}' read before it was evaluated"),
Some(OperationResult::Veto(_)) => {
Err(context.rule_values[index.index()].clone().expect("veto"))
}
Some(OperationResult::Value(literal)) => match &literal.value {
ValueKind::Date(date) => Ok(crate::parsing::ast::EffectiveDate::DateTimeValue(
semantic_date_to_datetime(date),
)),
other => panic!(
"BUG: `-> effective` pin rule '{rule_path}' is not a date after planning, got {other:?}"
),
},
}
}
}
}
fn semantic_date_to_datetime(
date: &crate::planning::semantics::SemanticDateTime,
) -> crate::parsing::ast::DateTimeValue {
crate::parsing::ast::DateTimeValue {
year: date.year,
month: date.month,
day: date.day,
hour: date.hour,
minute: date.minute,
second: date.second,
microsecond: date.microsecond,
timezone: date
.timezone
.as_ref()
.map(crate::literals::TimezoneValue::from),
granularity: crate::literals::DateGranularity::Full,
}
}
#[cfg(test)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum EntryAt {
Top,
Row,
Cell(NormalFormId),
Rule(crate::planning::execution_plan::RuleIndex),
}
#[cfg(test)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum EntryRun {
Rule(crate::planning::execution_plan::RuleIndex),
Leaf(NormalFormId),
Member(NormalFormId),
Settle(NormalFormId),
Materialize,
}
pub(crate) struct EvaluationContext {
pub(crate) values: Vec<Option<OperationResult>>,
pub(crate) rule_values: Vec<Option<OperationResult>>,
now: LiteralValue,
ignored_unknown: Vec<String>,
pub(crate) exhaustive: bool,
pub(crate) rule_explanations: RefCell<HashMap<RulePath, narration::ArenaId>>,
pub(crate) row_stack: Vec<CurrentRow>,
pub(crate) caches: Rc<RequestCaches>,
pub(crate) owner_row: Option<InstanceKey>,
pub(crate) missing_row_keys: Vec<String>,
unsettled_leaves: HashSet<usize>,
pub(crate) row_missing: HashMap<NormalFormId, Vec<String>>,
pub(crate) row_reads_log: Vec<rows::RowRead>,
pub(crate) row_reads: HashMap<NormalFormId, Vec<rows::RowRead>>,
#[cfg(test)]
pub(crate) store_log: Vec<NormalFormId>,
#[cfg(test)]
pub(crate) row_log: Vec<(NormalFormId, Vec<Option<usize>>, OperationResult)>,
#[cfg(test)]
pub(crate) scan_log: Vec<(NormalFormId, usize, usize, OperationResult)>,
#[cfg(test)]
pub(crate) entry_log: Vec<(EntryRun, usize, usize, EntryAt)>,
#[cfg(test)]
pub(crate) frame_tops: Vec<EntryAt>,
#[cfg(test)]
pub(crate) open_entries: usize,
}
type SelectedBody = Result<Arc<RowInstance>, OperationResult>;
#[derive(Clone)]
pub(crate) enum CurrentRow {
Value(TypedLiteral),
Instance {
key: InstanceKey,
position: usize,
},
}
#[derive(Clone, Copy)]
pub(crate) struct RowLogMark {
missing: usize,
reads: usize,
}
pub(crate) struct RequestCaches {
pub(crate) row_contexts: RefCell<IndexMap<InstanceKey, EvaluationContext>>,
pub(crate) supplied: lookup::Supplied,
writes: Arc<crate::planning::fill::WritesIndex>,
root: Arc<crate::planning::semantics::SpecIdentity>,
pub(crate) globals: crate::planning::execution_plan::RequestGlobals,
bodies: RefCell<HashMap<(Option<InstanceKey>, DataPath), SelectedBody>>,
#[cfg(feature = "call-graph-check")]
pub(crate) call_log: RefCell<Vec<CallStart>>,
}
#[cfg(feature = "call-graph-check")]
#[derive(Debug, PartialEq, Eq, Hash)]
pub(crate) struct CallStart {
pub(crate) caller: Option<Rc<CallAt>>,
pub(crate) started: Rc<CallAt>,
pub(crate) nesting: usize,
}
#[cfg(feature = "call-graph-check")]
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub(crate) enum CallAt {
In(Option<InstanceKey>, RowEnd),
Settle(InstanceKey, RulePath),
Materialize(InstanceKey),
}
#[cfg(feature = "call-graph-check")]
impl CallAt {
pub(crate) fn in_planned_rows(&self) -> bool {
let mut row = match self {
Self::In(row, _) => row.as_ref(),
Self::Settle(row, _) => Some(row),
Self::Materialize(_) => return false,
};
while let Some(key) = row {
if key.row.origin.is_request() {
return false;
}
row = key.owner();
}
true
}
}
impl RequestCaches {
fn new(plan: &ExecutionPlan, evaluate_data: &EvaluateData) -> Rc<Self> {
Rc::new(Self {
row_contexts: RefCell::new(IndexMap::new()),
supplied: evaluate_data.supplied.clone(),
writes: Arc::clone(&plan.writes_by_spec),
root: Arc::clone(&plan.writes_root),
globals: plan.request_globals(),
bodies: RefCell::new(HashMap::new()),
#[cfg(feature = "call-graph-check")]
call_log: RefCell::new(Vec::new()),
})
}
pub(crate) fn field<'a>(
&'a self,
instance: &'a InstanceKey,
template: &ExecutionPlan,
slot: usize,
) -> Option<lookup::Field<'a>> {
lookup::field(
instance,
template,
slot,
&self.writes,
&self.root,
&self.supplied,
)
}
pub(crate) fn binding<'a>(
&'a self,
instance: &'a InstanceKey,
template: &ExecutionPlan,
slot: usize,
) -> Option<std::borrow::Cow<'a, RowBinding>> {
self.field(instance, template, slot)
.map(|field| field.binding)
}
pub(crate) fn first_copied<'a>(
&self,
instance: &'a InstanceKey,
) -> std::borrow::Cow<'a, InstanceKey> {
let mut found = std::borrow::Cow::Borrowed(instance);
while let Some(source) = lookup::copy_source(&found, &self.writes, &self.root) {
found = std::borrow::Cow::Owned(source);
}
found
}
pub(crate) fn list_above(
&self,
holder: Option<&InstanceKey>,
list: &DataPath,
) -> Option<&Arc<crate::planning::instance_list::RowStore>> {
if let Some(rows) = lookup::list_above(holder, list, &self.writes, &self.root) {
return Some(rows);
}
let mut source = lookup::copy_source(holder?, &self.writes, &self.root)?;
loop {
if let Some(rows) = lookup::list_above(Some(&source), list, &self.writes, &self.root) {
return Some(rows);
}
source = lookup::copy_source(&source, &self.writes, &self.root)?;
}
}
pub(crate) fn is_rekeyed_above(&self, holder: Option<&InstanceKey>, list: &DataPath) -> bool {
lookup::is_rekeyed_above(holder, list, &self.writes, &self.root)
}
pub(crate) fn reads_in<'a>(
&'a self,
instance: &'a InstanceKey,
template: &ExecutionPlan,
slot: usize,
) -> Option<std::borrow::Cow<'a, InstanceKey>> {
self.field(instance, template, slot)
.and_then(|field| field.resolves_in)
}
pub(crate) fn body(
&self,
holder: Option<&InstanceKey>,
slot: &DataPath,
) -> Option<SelectedBody> {
self.bodies
.borrow()
.get(&(holder.cloned(), slot.clone()))
.cloned()
}
pub(crate) fn select_body(
&self,
holder: Option<InstanceKey>,
slot: DataPath,
body: SelectedBody,
) {
let previous = self.bodies.borrow_mut().insert((holder, slot), body);
assert!(
previous.is_none(),
"BUG: a `-> effective` body is selected twice"
);
}
pub(crate) fn selected_bodies(&self) -> evaluate_data::BodyChoice {
self.bodies
.borrow()
.iter()
.filter_map(|((holder, slot), body)| match body {
Ok(body) => Some((holder.clone(), slot.clone(), Arc::clone(body))),
Err(_) => None,
})
.collect()
}
}
impl EvaluationContext {
#[cfg(test)]
pub(crate) fn log_entry(&mut self, run: EntryRun, at: EntryAt) {
self.entry_log
.push((run, self.store_log.len(), self.open_entries, at));
self.open_entries += 1;
}
#[cfg(test)]
pub(crate) fn log_entry_end(&mut self) {
self.open_entries = self
.open_entries
.checked_sub(1)
.expect("an entry ends after it started");
}
#[cfg(test)]
pub(crate) fn log_body(&mut self, body: &tree::RowBody, at: EntryAt) {
match body {
tree::RowBody::Leaf(cell) => self.log_entry(EntryRun::Leaf(*cell), at),
tree::RowBody::Member(cell) => self.log_entry(EntryRun::Member(*cell), at),
tree::RowBody::Settle(root) => self.log_entry(EntryRun::Settle(*root), at),
tree::RowBody::Materialize => self.log_entry(EntryRun::Materialize, at),
tree::RowBody::Rule(_) | tree::RowBody::Nothing => {}
}
}
#[cfg(test)]
pub(crate) fn log_scan(
&mut self,
command: NormalFormId,
row: usize,
field: usize,
value: &OperationResult,
) {
self.scan_log.push((command, row, field, value.clone()));
}
#[cfg(test)]
pub(crate) fn log_store(
&mut self,
plan: &ExecutionPlan,
id: NormalFormId,
result: &OperationResult,
) {
if plan.row_mask[id.index()] == 0 {
self.store_log.push(id);
return;
}
let positions = self
.row_stack
.iter()
.map(|row| match row {
CurrentRow::Instance { position, .. } => Some(*position),
CurrentRow::Value(_) => None,
})
.collect();
self.row_log.push((id, positions, result.clone()));
}
pub(crate) fn child_row(
&self,
template: &ExecutionPlan,
bindings: &[(usize, OperationResult)],
unbound: &[usize],
) -> Self {
assert!(
bindings.windows(2).all(|pair| pair[0].0 < pair[1].0),
"BUG: row bindings of '{}' out of slot order",
template.spec_name
);
assert!(
unbound.windows(2).all(|pair| pair[0] < pair[1]),
"BUG: unbound row slots of '{}' out of slot order",
template.spec_name
);
let mut values = Self::template_values(template);
if !bindings.is_empty() || !unbound.is_empty() {
for (slot, binding) in bindings {
values[template.data_slot_leaves[*slot].index()] = Some(binding.clone());
}
for slot in unbound {
values[template.data_slot_leaves[*slot].index()] = None;
}
template.copy_reference_targets(&mut values, |slot, _| {
bindings
.binary_search_by_key(&slot, |(bound, _)| *bound)
.is_ok()
|| unbound.binary_search(&slot).is_ok()
});
}
Self::with_values(
template,
values,
self.now.clone(),
Vec::new(),
self.exhaustive,
Rc::clone(&self.caches),
)
}
fn new(
plan: &ExecutionPlan,
evaluate_data: &EvaluateData,
now: LiteralValue,
exhaustive: bool,
caches: Rc<RequestCaches>,
) -> Self {
let mut values = Self::template_values(plan);
if !evaluate_data.bindings.is_empty() {
for (slot, binding) in &evaluate_data.bindings {
values[plan.data_slot_leaves[*slot].index()] = Some(binding.clone());
}
plan.copy_reference_targets(&mut values, |slot, _| {
evaluate_data.bindings.contains_key(&slot)
});
}
Self::with_values(
plan,
values,
now,
evaluate_data.ignored_unknown.clone(),
exhaustive,
caches,
)
}
fn template_values(plan: &ExecutionPlan) -> Vec<Option<OperationResult>> {
assert_eq!(
plan.initial_values.len(),
plan.normal_forms.len(),
"BUG: plan evaluation tables not populated"
);
plan.initial_values.clone()
}
fn with_values(
plan: &ExecutionPlan,
values: Vec<Option<OperationResult>>,
now: LiteralValue,
ignored_unknown: Vec<String>,
exhaustive: bool,
caches: Rc<RequestCaches>,
) -> Self {
let mut unsettled_leaves = HashSet::new();
for &leaf in &plan.walk_settled_leaves {
if values[leaf.index()].is_some() {
unsettled_leaves.insert(leaf.index());
}
}
Self {
values,
rule_values: vec![None; plan.rules.len()],
now,
ignored_unknown,
exhaustive,
rule_explanations: RefCell::new(HashMap::new()),
row_stack: Vec::new(),
caches,
owner_row: None,
missing_row_keys: Vec::new(),
unsettled_leaves,
row_missing: HashMap::new(),
row_reads_log: Vec::new(),
row_reads: HashMap::new(),
#[cfg(test)]
store_log: Vec::new(),
#[cfg(test)]
row_log: Vec::new(),
#[cfg(test)]
scan_log: Vec::new(),
#[cfg(test)]
entry_log: Vec::new(),
#[cfg(test)]
open_entries: 0,
#[cfg(test)]
frame_tops: Vec::new(),
}
}
pub(crate) fn leaf_unsettled(&self, leaf: usize) -> bool {
self.unsettled_leaves.contains(&leaf)
}
pub(crate) fn settle_leaf(&mut self, leaf: usize) {
self.unsettled_leaves.remove(&leaf);
}
pub(crate) fn row_log_mark(&self) -> RowLogMark {
RowLogMark {
missing: self.missing_row_keys.len(),
reads: self.row_reads_log.len(),
}
}
pub(crate) fn record_row_log(&mut self, id: NormalFormId, mark: RowLogMark) {
if self.missing_row_keys.len() > mark.missing {
let keys = self.row_missing.entry(id).or_default();
for key in &self.missing_row_keys[mark.missing..] {
if !keys.contains(key) {
keys.push(key.clone());
}
}
}
if self.row_reads_log.len() > mark.reads {
let reads = self.row_reads.entry(id).or_default();
for read in &self.row_reads_log[mark.reads..] {
if !reads.iter().any(|seen| seen.same_field(read)) {
reads.push(read.clone());
}
}
}
}
pub(crate) fn rule_value<'a>(
&'a self,
plan: &ExecutionPlan,
path: &RulePath,
) -> &'a OperationResult {
self.rule_values[plan.rule_index(path).index()]
.as_ref()
.unwrap_or_else(|| {
panic!(
"BUG: rule '{}' rule reference read before evaluation",
path.rule
)
})
}
pub(crate) fn now(&self) -> &LiteralValue {
&self.now
}
#[must_use]
pub(crate) fn data_display_type(
plan: &ExecutionPlan,
path: &DataPath,
settled: &OperationResult,
) -> Arc<LemmaType> {
let def = plan
.data
.get(path)
.expect("BUG: data path leaf missing from plan.data");
let schema = def
.resolved_type_arc()
.expect("BUG: data path leaf missing schema type");
lemma_type_arc_with_display_binding(
schema,
settled.value(),
def.bound_value(),
def.bound_suggestion(),
)
}
#[must_use]
pub(crate) fn rule_result_type(
&self,
plan: &ExecutionPlan,
rule: &ExecutableRule,
) -> Arc<LemmaType> {
let planned = &rule.rule_type;
if planned.unit().is_some() {
return Arc::clone(planned);
}
let settled = self
.rule_values
.get(plan.rule_index(&rule.path).index())
.and_then(|slot| slot.as_ref())
.and_then(OperationResult::value);
match &plan.normal_form(rule.normal_form).kind {
crate::planning::normalize::NormalFormKind::Leaf(
crate::planning::normalize::LeafKind::DataPath(path),
) => {
let def = plan
.data
.get(path)
.expect("BUG: rule DataPath leaf missing from plan.data");
lemma_type_arc_with_display_binding(
planned,
settled,
def.bound_value(),
def.bound_suggestion(),
)
}
_ => lemma_type_arc_with_display_binding(planned, settled, None, None),
}
}
pub(crate) fn data_slot(
&self,
plan: &ExecutionPlan,
data_path: &DataPath,
) -> Option<&OperationResult> {
let leaf = *plan
.data_leaf
.get(data_path)
.unwrap_or_else(|| panic!("BUG: data path '{data_path}' has no data_leaf entry"));
self.values[leaf.index()].as_ref()
}
pub(crate) fn bind_resolved_slots(
&mut self,
plan: &ExecutionPlan,
resolved: Vec<(DataPath, OperationResult)>,
row_bound: impl Fn(usize) -> bool,
) {
if resolved.is_empty() {
return;
}
for (data_path, value) in resolved {
let leaf = *plan
.data_leaf
.get(&data_path)
.unwrap_or_else(|| panic!("BUG: data path '{data_path}' has no data_leaf entry"));
if self.values[leaf.index()].is_none() {
self.values[leaf.index()] = Some(value);
if plan.walk_settled_leaves.contains(&leaf) {
self.unsettled_leaves.insert(leaf.index());
}
}
}
plan.copy_reference_targets(&mut self.values, |slot, _| row_bound(slot));
}
pub(crate) fn missing_data_suggestion(&self, data_path: &DataPath) -> Option<String> {
closest_ignored_key(&data_path.input_key(), &self.ignored_unknown)
}
pub(crate) fn missing_data_for_rule(
&self,
plan: &ExecutionPlan,
rule_root: NormalFormId,
instance: Option<&InstanceKey>,
) -> Vec<String> {
let (candidates, unsettled) = missing_candidates(plan, self, rule_root, None);
assert!(
unsettled.is_empty(),
"BUG: missing data of a rule read before its live work settled"
);
self.collect_missing(candidates, plan, instance)
}
pub(crate) fn settled_missing_data_for_rule(
&mut self,
plan: &ExecutionPlan,
rule_root: NormalFormId,
) -> Vec<String> {
let candidates = self.settle(plan, |ctx| missing_candidates(plan, ctx, rule_root, None));
self.collect_missing(candidates, plan, None)
}
pub(crate) fn settled_missing_data_for_instance(
&mut self,
root_plan: &ExecutionPlan,
template: &ExecutionPlan,
rule_root: NormalFormId,
instance: &InstanceKey,
) -> Vec<String> {
let query = |ctx: &EvaluationContext| {
let contexts = ctx.caches.row_contexts.borrow();
missing_candidates(
root_plan,
ctx,
rule_root,
Some((instance, template, contexts.get(instance))),
)
};
let candidates = self.settle(root_plan, query);
self.collect_missing(candidates, root_plan, None)
}
fn settle<'p>(
&mut self,
plan: &'p ExecutionPlan,
query: impl Fn(&EvaluationContext) -> (Vec<MissingCandidate>, Vec<Unsettled<'p>>),
) -> Vec<MissingCandidate> {
loop {
let (candidates, unsettled) = query(self);
if unsettled.is_empty() {
return candidates;
}
for work in unsettled {
let at = work.at.as_ref().map(|key| (key, work.template));
tree::settle_live_work(work.root, at, plan, self);
}
}
}
fn collect_missing(
&self,
candidates: Vec<MissingCandidate>,
plan: &ExecutionPlan,
instance: Option<&InstanceKey>,
) -> Vec<String> {
let mut out = Vec::new();
let mut seen = HashSet::new();
for candidate in candidates {
let key = match candidate {
MissingCandidate::Data(path) => match self.data_slot(plan, &path) {
Some(held) => {
let held = match instance {
None => held.clone(),
Some(instance) => {
rows::row_result(held.clone(), instance, plan, &self.caches)
}
};
match held {
OperationResult::Veto(VetoType::MissingRowData { key }) => key,
OperationResult::Veto(VetoType::MissingData { data, .. }) => {
data.input_key()
}
OperationResult::Value(_) | OperationResult::Veto(_) => continue,
}
}
None => match instance {
None => path.input_key(),
Some(instance) => match rows::row_key(instance, &path, &self.caches) {
Some(key) => key,
None => continue,
},
},
},
MissingCandidate::Row(key) => key,
};
if seen.insert(key.clone()) {
out.push(key);
}
}
out
}
}
fn rule_ref_origin(plan: &ExecutionPlan, id: NormalFormId) -> NormalFormId {
let mut current = id;
for _ in 0..=plan.rules.len() {
let Some(rule) = &plan.normal_form(current).rule_ref else {
return current;
};
current = plan
.rules
.get(rule)
.unwrap_or_else(|| panic!("BUG: rule reference '{rule}' missing from plan.rules"))
.normal_form;
}
panic!("BUG: rule reference chain from {id:?} does not terminate");
}
enum MissingCandidate {
Data(DataPath),
Row(String),
}
fn missing_candidates<'p>(
plan: &'p ExecutionPlan,
ctx: &EvaluationContext,
root: NormalFormId,
at: Option<(&InstanceKey, &'p ExecutionPlan, Option<&EvaluationContext>)>,
) -> (Vec<MissingCandidate>, Vec<Unsettled<'p>>) {
struct Walk<'p, 'c> {
inputs: std::vec::IntoIter<ReachableInput>,
template: &'p ExecutionPlan,
instance: Option<InstanceKey>,
context: Option<&'c EvaluationContext>,
writers_only: bool,
}
fn open<'p, 'c>(
template: &'p ExecutionPlan,
root: NormalFormId,
instance: Option<InstanceKey>,
context: Option<&'c EvaluationContext>,
unsettled: &mut Vec<Unsettled<'p>>,
) -> Walk<'p, 'c> {
let inputs = match context {
Some(context) => {
let (inputs, has_unsettled) =
reachable_data_paths_and_unsettled(template, root, &context.values);
if has_unsettled {
let work = Unsettled {
at: instance.clone(),
template,
root,
};
if !unsettled.contains(&work) {
unsettled.push(work);
}
}
inputs
}
None => reachable_data_paths(template, root, &[]),
};
Walk {
inputs: inputs.into_iter(),
template,
instance,
context,
writers_only: false,
}
}
let contexts = ctx.caches.row_contexts.borrow();
let mut out = Vec::new();
let mut unsettled = Vec::new();
let mut walks = match at {
None => vec![open(plan, root, None, Some(ctx), &mut unsettled)],
Some((instance, template, context)) => vec![open(
template,
root,
Some(instance.clone()),
context,
&mut unsettled,
)],
};
while let Some(walk) = walks.last_mut() {
let Some(input) = walk.inputs.next() else {
walks.pop();
continue;
};
let template = walk.template;
match input {
ReachableInput::Data(path) => {
let Some(promptable) = template.promptable_data_path(&path) else {
continue;
};
let Some(instance) = &walk.instance else {
assert!(
!walk.writers_only,
"BUG: a writers-only walk is a walk of an instance"
);
out.push(MissingCandidate::Data(promptable.clone()));
continue;
};
let key = rows::row_key(instance, promptable, &ctx.caches);
let slot = template
.data
.get_index_of(promptable)
.expect("BUG: promptable path is data of its template");
let binding_held = ctx.caches.binding(instance, template, slot);
let binding = binding_held.as_deref();
let writer_missing = match binding {
Some(RowBinding::Deferred { target }) => {
let owner_held = ctx.caches.reads_in(instance, template, slot);
let owner = owner_held.as_deref();
let resolvable = owner == ctx.owner_row.as_ref() || ctx.owner_row.is_none();
resolvable && {
let owner_plan = match owner {
Some(owner_key) if owner != ctx.owner_row.as_ref() => {
plan.row_template(&owner_key.row.identity)
}
_ => plan,
};
owner_plan.target_force(target).is_some()
}
}
_ => false,
} && walk.context.is_some_and(|context| {
matches!(
context.data_slot(template, promptable),
Some(OperationResult::Veto(
VetoType::MissingRowData { .. } | VetoType::MissingData { .. }
))
)
});
if walk.writers_only && !writer_missing {
continue;
}
match walk.context.filter(|_| !writer_missing) {
Some(context) => match context.data_slot(template, promptable) {
Some(OperationResult::Veto(VetoType::MissingRowData { key })) => {
out.push(MissingCandidate::Row(key.clone()));
}
Some(OperationResult::Veto(VetoType::MissingData { data, .. })) => {
out.push(MissingCandidate::Row(data.input_key()));
}
Some(_) => {}
None => out.extend(key.map(MissingCandidate::Row)),
},
None => {
let slot = template
.data
.get_index_of(promptable)
.expect("BUG: promptable path is data of its template");
match ctx.caches.binding(instance, template, slot).as_deref() {
None => {
let leaf = template
.data_leaf
.get(promptable)
.expect("BUG: promptable path has a data_leaf entry");
if template.initial_values[leaf.index()].is_none() {
out.extend(key.map(MissingCandidate::Row));
}
}
Some(RowBinding::Deferred { target }) => {
let owner_held = ctx.caches.reads_in(instance, template, slot);
let owner = owner_held.as_deref();
let own = owner == ctx.owner_row.as_ref();
let owner_plan = match owner {
Some(owner_key) if !own => {
plan.row_template(&owner_key.row.identity)
}
_ => plan,
};
let owner_ctx = match owner {
Some(owner_key) if !own => contexts.get(owner_key),
_ => Some(ctx),
};
let owner_instance = if own { None } else { owner.cloned() };
let body = match owner_plan.target_force(target) {
Some(TargetForce::Rule(rule)) => {
Some(owner_plan.rule_at(rule).normal_form)
}
Some(TargetForce::Member(cell)) => Some(cell),
None => None,
};
match (body, target) {
(Some(body), _) => walks.push(open(
owner_plan,
body,
owner_instance,
owner_ctx,
&mut unsettled,
)),
(None, ReferenceTarget::Data(path)) => {
let Some(promptable) =
owner_plan.promptable_data_path(path)
else {
continue;
};
match &owner_instance {
None => {
out.push(MissingCandidate::Data(
promptable.clone(),
));
}
Some(owner_key) => out.extend(
rows::row_key(owner_key, promptable, &ctx.caches)
.map(MissingCandidate::Row),
),
}
}
(None, ReferenceTarget::Rule(rule)) => {
unreachable!("BUG: rule target '{rule}' forces no rule")
}
}
}
Some(RowBinding::Bound(_)) => {}
}
}
}
}
ReachableInput::RowReads(id) => {
let mut writers_only = walk.writers_only;
let recorded = rule_ref_origin(template, id);
if let Some(context) = walk.context {
if let Some(keys) = context.row_missing.get(&recorded) {
if !walk.writers_only {
out.extend(keys.iter().cloned().map(MissingCandidate::Row));
}
writers_only = true;
} else if context.values[id.index()].is_some() {
continue;
}
}
let member_read = match &template.normal_form(id).kind {
NormalFormKind::SpecMember { base, row, .. } => {
match &template.normal_form(*base).kind {
NormalFormKind::Leaf(LeafKind::DataPath(slot))
if matches!(
template.data.get(slot),
Some(DataDefinition::Import { .. })
) =>
{
Some((slot, row))
}
_ => None,
}
}
_ => None,
};
let Some((slot, row)) = member_read else {
continue;
};
let holder = match &walk.instance {
Some(instance) => Some(instance.clone()),
None => ctx.owner_row.clone(),
};
let (end, hops) = row
.ends
.split_last()
.expect("BUG: a member read has a last end");
let Some(mut instance) =
read_import_key(template, holder.as_ref(), slot, &ctx.caches)
else {
continue;
};
let mut member_template = template.row_template(&instance.row.identity);
let mut unread = false;
for hop in hops {
let RowEnd::Data(hop) = hop else {
panic!("BUG: member hop '{hop:?}' is a rule, not a `uses` slot");
};
let Some(next) =
read_import_key(member_template, Some(&instance), hop, &ctx.caches)
else {
unread = true;
break;
};
instance = next;
member_template = template.row_template(&instance.row.identity);
}
if unread {
continue;
}
let context = contexts.get(&instance);
match end {
RowEnd::Data(path) => walks.push(Walk {
inputs: vec![ReachableInput::Data(path.clone())].into_iter(),
template: member_template,
instance: Some(instance),
context,
writers_only,
}),
RowEnd::Rule(rule) => {
let body = member_template
.rules
.get(rule)
.unwrap_or_else(|| {
panic!("BUG: member rule '{rule}' missing from its template")
})
.normal_form;
let mut member_walk = open(
member_template,
body,
Some(instance),
context,
&mut unsettled,
);
member_walk.writers_only = writers_only;
walks.push(member_walk);
}
}
}
}
}
(out, unsettled)
}
struct Unsettled<'p> {
at: Option<InstanceKey>,
template: &'p ExecutionPlan,
root: NormalFormId,
}
impl PartialEq for Unsettled<'_> {
fn eq(&self, other: &Self) -> bool {
self.at == other.at
&& std::ptr::eq(self.template, other.template)
&& self.root == other.root
}
}
fn closed_missing(
ctx: &mut EvaluationContext,
plan: &ExecutionPlan,
keys: Vec<String>,
) -> (Vec<String>, IndexMap<String, Vec<EvaluateDataValue>>) {
let mut keys = keys;
let mut missing_data_options = IndexMap::new();
let mut index = 0;
while index < keys.len() {
let key = keys[index].clone();
let Some(path) = plan
.data
.keys()
.find(|path| path.input_key() == key)
.cloned()
else {
let fields = evaluate_data::row_field_definitions(
plan,
&ctx.caches.globals,
&key,
ctx.caches.selected_bodies(),
);
let read: Vec<_> = {
let contexts = ctx.caches.row_contexts.borrow();
fields
.iter()
.filter(|(_, _, instance, _)| contexts.contains_key(instance))
.cloned()
.collect()
};
let fields = if read.is_empty() { fields } else { read };
let mut values: Vec<EvaluateDataValue> = Vec::new();
let mut blockers: Vec<String> = Vec::new();
for (template, definition, instance, field) in fields {
match row_field_options(ctx, plan, &key, template, definition, &instance, field) {
Some(KeyOptions::Values(options)) => {
for option in options {
if !values.contains(&option) {
values.push(option);
}
}
}
Some(KeyOptions::Blocked(found)) => {
for blocker in found {
if !blockers.contains(&blocker) {
blockers.push(blocker);
}
}
}
None => {}
}
}
if blockers.is_empty() {
if !values.is_empty() {
missing_data_options.insert(key, values);
}
index += 1;
continue;
}
keys.remove(index);
for blocker in blockers.into_iter().rev() {
if !keys.iter().any(|existing| existing == &blocker) {
keys.insert(index, blocker);
}
}
continue;
};
let Some(lemma_type) = plan
.data
.get(&path)
.and_then(|definition| definition.schema_type())
else {
index += 1;
continue;
};
let Some(rule_name) = lemma_type.options_rule() else {
let options = options_for(lemma_type, None);
if !options.is_empty() {
missing_data_options.insert(key, options);
}
index += 1;
continue;
};
let rule_path = plan.options_rule_of(&path).unwrap_or_else(|| {
panic!("BUG: options rule '{rule_name}' of '{key}' missing after planning")
});
tree::ensure_rule_values(plan.rule_index(&rule_path), plan, ctx);
match options_rule_list(ctx, plan, &rule_path) {
Some(rows) => {
missing_data_options.insert(key, options_for(lemma_type, Some(&rows)));
index += 1;
}
None => {
keys.remove(index);
let rule = plan
.rules
.get(&rule_path)
.expect("BUG: options rule missing after options_rule_of asserted it");
let blockers = ctx.settled_missing_data_for_rule(plan, rule.normal_form);
for blocker in blockers.into_iter().rev() {
if !keys.iter().any(|existing| existing == &blocker) {
keys.insert(index, blocker);
}
}
}
}
}
(keys, missing_data_options)
}
enum KeyOptions {
Values(Vec<EvaluateDataValue>),
Blocked(Vec<String>),
}
fn row_field_options(
ctx: &mut EvaluationContext,
plan: &ExecutionPlan,
key: &str,
template: &ExecutionPlan,
definition: &DataDefinition,
instance: &InstanceKey,
field: &DataPath,
) -> Option<KeyOptions> {
let lemma_type = definition.schema_type()?;
let Some(rule_name) = lemma_type.options_rule() else {
return Some(KeyOptions::Values(options_for(lemma_type, None)));
};
let rule_path = template.options_rule_of(field).unwrap_or_else(|| {
panic!("BUG: options rule '{rule_name}' of '{key}' missing after planning")
});
let rule = template.rules.get(&rule_path).unwrap_or_else(|| {
panic!("BUG: options rule '{rule_path}' missing after options_rule_of asserted it")
});
if !ctx.caches.row_contexts.borrow().contains_key(instance) {
return Some(KeyOptions::Blocked(ctx.settled_missing_data_for_instance(
plan,
template,
rule.normal_form,
instance,
)));
}
tree::ensure_row_rule_value(instance, &rule_path, plan, ctx);
let contexts = ctx.caches.row_contexts.borrow();
let instance_ctx = contexts
.get(instance)
.expect("BUG: row context missing after its options rule was read");
if let Some(rows) = options_rule_list(instance_ctx, template, &rule_path) {
return Some(KeyOptions::Values(options_for(lemma_type, Some(&rows))));
}
Some(KeyOptions::Blocked(instance_ctx.missing_data_for_rule(
template,
rule.normal_form,
Some(instance),
)))
}
fn options_rule_list(
ctx: &EvaluationContext,
plan: &ExecutionPlan,
rule_path: &RulePath,
) -> Option<ListValue> {
let index = plan.rules.get_index_of(rule_path)?;
let result = ctx.rule_values.get(index)?.as_ref()?;
match result.value().map(|bound| &bound.value) {
Some(ValueKind::List(rows)) => Some(rows.clone()),
_ => None,
}
}
fn options_for(lemma_type: &LemmaType, rule_rows: Option<&ListValue>) -> Vec<EvaluateDataValue> {
let mut options = Vec::new();
push_type_options(lemma_type, &mut options);
if let crate::planning::semantics::TypeSpecification::List { element, .. } =
&lemma_type.specifications
{
push_type_options(element, &mut options);
}
if let Some(rows) = rule_rows {
for row in rows.iter() {
push_option(&mut options, publish_typed(&row));
}
}
options
}
fn push_type_options(lemma_type: &LemmaType, options: &mut Vec<EvaluateDataValue>) {
for option in &lemma_type.options.values {
push_option(options, publish_bound(lemma_type, &option.value));
}
}
fn publish_bound(lemma_type: &LemmaType, bound: &BoundValueKind) -> EvaluateDataValue {
match &bound.value {
ValueKind::Boolean(bit) => EvaluateDataValue::Boolean(*bit),
ValueKind::Spec(_) => unreachable!("BUG: {SPEC_OPTIONS_NEVER_MISSING}"),
_ => EvaluateDataValue::Literal(lemma_type.display_bound(bound)),
}
}
fn publish_typed(typed: &TypedLiteral) -> EvaluateDataValue {
match &typed.value {
ValueKind::Boolean(bit) => EvaluateDataValue::Boolean(*bit),
ValueKind::Spec(_) => unreachable!("BUG: {SPEC_OPTIONS_NEVER_MISSING}"),
_ => EvaluateDataValue::Literal(typed.display_value()),
}
}
const SPEC_OPTIONS_NEVER_MISSING: &str = "missing-data options hold no spec value: a spec type is only a list element, a list of spec instances takes no options, and a spec list has its rows (possibly none) and is never missing data";
fn push_option(options: &mut Vec<EvaluateDataValue>, option: EvaluateDataValue) {
if options.iter().any(|existing| existing == &option) {
return;
}
options.push(option);
}
#[derive(Default)]
pub(crate) struct Evaluator;
impl Evaluator {
pub(crate) fn evaluate(
&self,
plan: &ExecutionPlan,
evaluate_data: &EvaluateData,
now: LiteralValue,
requested: Vec<&RulePath>,
explain: bool,
) -> Response {
let (response, context) =
self.evaluate_retaining(plan, evaluate_data, now, requested, explain);
context.caches.row_contexts.borrow_mut().clear();
response
}
fn evaluate_retaining(
&self,
plan: &ExecutionPlan,
evaluate_data: &EvaluateData,
now: LiteralValue,
requested: Vec<&RulePath>,
explain: bool,
) -> (Response, EvaluationContext) {
let effective = match &now.value {
ValueKind::Date(date) => date.to_string(),
other => panic!("BUG: evaluation now must be a date, got {other:?}"),
};
let mut context = EvaluationContext::new(
plan,
evaluate_data,
now,
explain,
RequestCaches::new(plan, evaluate_data),
);
let mut response = Response {
spec_name: plan.spec_name.clone(),
effective,
spec_effective_from: None,
spec_effective_to: None,
results: IndexMap::with_capacity(requested.len()),
rows: Vec::new(),
};
let mut rows = response::RowTable::default();
run_request_program(
plan,
&mut context,
requested.iter().map(|path| {
assert!(
plan.rules.contains_key(*path),
"BUG: non-local rule in validated response set: {path}"
);
plan.rule_index(path)
}),
);
let mut arena = narration::ExplanationArena::default();
if explain {
narration::narrate_row_contexts(plan, &context, &mut arena);
let mut session = narration::NarrationSession {
root_plan: plan,
root_ctx: &context,
arena: &mut arena,
pending: Vec::new(),
};
for (index, rule) in plan.rules.values().enumerate() {
if context.rule_values[index].is_some() {
narration::narrate_rule(rule, plan, &context, None, &mut session);
}
}
}
for path in requested {
let (rule_type, explanation, missing_keys, source, result, runtime_scales) = {
let exec_rule = &plan.rules[path];
let result = context.rule_value(plan, path).clone();
let rule_type = context.rule_result_type(plan, exec_rule);
let explanation = explain.then(|| {
narration::explanation_for(
path,
exec_rule,
plan,
&context,
&arena,
&result,
Arc::clone(&rule_type),
)
});
let missing_keys = result.is_missing_data().then(|| {
let mut keys =
context.settled_missing_data_for_rule(plan, exec_rule.normal_form);
if keys.is_empty() {
match &result {
OperationResult::Veto(VetoType::MissingRowData { key }) => {
keys.push(key.clone());
}
OperationResult::Veto(VetoType::MissingData { data, .. }) => {
keys.push(data.input_key());
}
OperationResult::Value(_) | OperationResult::Veto(_) => {}
}
}
keys
});
let runtime_scales = compute::display_scale_factors(
result.value(),
rule_type.as_ref(),
plan,
&context,
);
(
rule_type,
explanation,
missing_keys,
exec_rule.source.clone(),
result,
runtime_scales,
)
};
let (missing_data, missing_data_options) = match missing_keys {
Some(keys) => closed_missing(&mut context, plan, keys),
None => (Vec::new(), IndexMap::new()),
};
let mut rule_result = RuleResult::from_evaluated(
EvaluatedRule {
name: path.input_key(),
path: path.clone(),
source_location: source,
rule_type: Arc::clone(&rule_type),
},
&result,
rule_type.as_ref(),
&plan.family_units,
explanation,
missing_data,
Some(&runtime_scales),
)
.with_missing_data_options(missing_data_options);
if let (OperationResult::Value(bound), Some(value)) =
(&result, rule_result.result.as_mut())
{
response::fill_spec_values(&bound.value, value, plan, &mut context, &mut rows);
}
response.add_result(rule_result);
}
response.rows = rows.into_rows();
#[cfg(feature = "call-graph-check")]
check_call_log(plan, &context.caches);
(response, context)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::parsing::ast::DateTimeValue;
use crate::Engine;
fn planned_schedule(
plan: &ExecutionPlan,
ctx: &EvaluationContext,
prefilled: &HashSet<usize>,
entries: &[(EntryRun, usize, usize, EntryAt)],
) -> Vec<NormalFormId> {
use crate::planning::program::{segment, Entry, Guard, RegionId, Segment, Step};
let mut segments: Vec<Segment> = plan
.rules
.keys()
.map(|rule| segment(plan, Entry::Rule(plan.rule_index(rule))))
.collect();
const SETTLE: usize = usize::MAX / 2;
let mut settle_roots: Vec<NormalFormId> = Vec::new();
let starts: Vec<(usize, usize, usize, EntryAt)> = entries
.iter()
.map(|(entry, at, depth, started_at)| {
let index = match entry {
EntryRun::Rule(rule) => rule.index(),
EntryRun::Leaf(cell) => {
segments.push(segment(plan, Entry::Leaf(*cell)));
segments.len() - 1
}
EntryRun::Member(cell) => {
segments.push(segment(plan, Entry::Cell(*cell)));
segments.len() - 1
}
EntryRun::Settle(root) => {
settle_roots.push(*root);
SETTLE + settle_roots.len() - 1
}
EntryRun::Materialize => {
segments.push(segment(plan, Entry::Materialize));
segments.len() - 1
}
};
(index, *at, *depth, *started_at)
})
.collect();
let mut per_row: HashMap<(NormalFormId, Vec<Option<usize>>), OperationResult> =
HashMap::new();
for (cell, positions, result) in &ctx.row_log {
per_row
.entry((*cell, positions.clone()))
.or_insert_with(|| result.clone());
}
struct Running {
lp: u32,
start: usize,
rows: Vec<TypedLiteral>,
current: usize,
}
let positions_of = |running: &[Running]| -> Vec<Option<usize>> {
running
.iter()
.map(|lp| match &lp.rows[lp.current].value {
ValueKind::Spec(crate::planning::semantics::SpecValue::Row(_)) => {
Some(lp.current)
}
_ => None,
})
.collect()
};
let value = |id: NormalFormId, running: &[Running]| -> OperationResult {
if plan.row_mask[id.index()] != 0 {
return per_row
.get(&(id, positions_of(running)))
.cloned()
.unwrap_or_else(|| {
panic!("per-row decision cell {} has no value", id.index())
});
}
let cell = plan.normal_form(id);
if cell.rule_ref.is_none() {
if let NormalFormKind::Leaf(LeafKind::DataPath(path)) = &cell.kind {
if !matches!(plan.data.get(path), Some(DataDefinition::Import { .. })) {
return expression::resolve_data_path_value(path, plan, ctx);
}
}
}
ctx.values[id.index()]
.clone()
.unwrap_or_else(|| panic!("decision cell {} has no value", id.index()))
};
let guard_holds = |segment: &Segment, guard: Guard, running: &[Running]| -> bool {
let value = |id| value(id, running);
match guard {
Guard::ScanOpen { in_loop, field } => {
let lp = running
.iter()
.rfind(|lp| lp.lp == in_loop)
.expect("a scan guard inside its loop");
let command = segment.loops[in_loop as usize].command;
let fields = match &plan.normal_form(command).kind {
NormalFormKind::ListCommand {
op: crate::planning::normalize::NormalFormListOp::Key { .. },
..
} => list_ops::list_key(plan.result_type(command)),
NormalFormKind::ListCommand { list, .. } => {
list_ops::list_key(plan.result_type(*list))
}
other => panic!("scan guard on {other:?}"),
};
let count = match fields {
crate::planning::semantics::ListKey::Fields(fields) => fields.len(),
crate::planning::semantics::ListKey::Numbered => 0,
};
(0..=lp.current).all(|row| {
let upto = if row == lp.current {
field as usize
} else {
count
};
(0..upto).all(|read| {
ctx.scan_log.iter().any(|(logged, r, f, value)| {
*logged == command && *r == row && *f == read && !value.vetoed()
})
})
})
}
Guard::Unindexed(command) => {
let NormalFormKind::ListCommand { list, .. } = &plan.normal_form(command).kind
else {
panic!("unindexed guard on a cell that is not a list command");
};
let crate::planning::semantics::ListKey::Fields(fields) =
list_ops::list_key(plan.result_type(*list))
else {
panic!("unindexed guard on a numbered list");
};
match value(*list) {
OperationResult::Value(bound) => match &bound.value {
ValueKind::List(rows) => !rows.index().is_some_and(|index| {
index
.fields
.iter()
.eq(fields.iter().map(|field| &field.name))
}),
other => panic!("find list is {other:?}"),
},
OperationResult::Veto(_) => false,
}
}
Guard::Entry => true,
Guard::Explain => ctx.exhaustive,
Guard::Bound(leaf) => ctx.values[leaf.index()].is_some(),
Guard::Taken(condition) => matches!(
branch_semantics::condition_outcome(&value(condition)),
branch_semantics::BranchOutcome::Taken
),
Guard::NotTaken(condition) => matches!(
branch_semantics::condition_outcome(&value(condition)),
branch_semantics::BranchOutcome::NotTaken
),
Guard::NotDefinitiveVeto(operand) => {
let operand = value(operand);
ctx.exhaustive || !operand.vetoed() || operand.is_missing_data()
}
Guard::Value(operand) => !value(operand).vetoed(),
Guard::Vetoed(operand) => value(operand).vetoed(),
Guard::FoldOpen { fold, operands } => {
let (NormalFormKind::Sum(terms) | NormalFormKind::Product(terms)) =
&plan.normal_form(fold).kind
else {
panic!("fold guard on a cell that is not a fold");
};
let (mut acc, mut veto) = (None, None);
for (index, term) in terms.iter().take(operands).enumerate() {
compute::fold_term(
&mut acc,
&mut veto,
fold,
index,
value(term.operand),
plan,
);
}
ctx.exhaustive || !compute::fold_settled(veto.as_ref())
}
Guard::LogicalOpen { logical, operands } => {
let NormalFormKind::Logical(connective, children) =
&plan.normal_form(logical).kind
else {
panic!("logical guard on a cell that is not logical");
};
let mut veto = None;
children.iter().take(operands).all(|child| {
compute::logical_operand(*connective, &mut veto, value(*child)).is_none()
})
}
Guard::Dispatch { dispatch, index } => {
let NormalFormKind::OrderedDispatch {
scrutinee,
boundaries,
..
} = &plan.normal_form(dispatch).kind
else {
panic!("dispatch guard on a cell that is not a dispatch");
};
match value(*scrutinee) {
OperationResult::Value(bound) => {
crate::planning::ordered_dispatch::region_of_scrutinee(
boundaries,
&bound.value,
) == Ok(index)
}
OperationResult::Veto(_) => false,
}
}
Guard::ArgumentsOpen { command, operands } => {
let NormalFormKind::ListCommand { list, args, .. } =
&plan.normal_form(command).kind
else {
panic!("arguments guard on a cell that is not a list command");
};
!value(*list).vetoed()
&& args.iter().take(operands).all(|arg| !value(*arg).vetoed())
}
}
};
let live = |segment: &Segment, region: RegionId, running: &[Running]| -> bool {
let mut chain = Vec::new();
let mut current = Some(region);
while let Some(region) = current {
chain.push(region);
current = segment.regions[region.index()].parent;
}
chain
.iter()
.rev()
.all(|region| guard_holds(segment, segment.regions[region.index()].guard, running))
};
let loop_end = |segment: &Segment, lp: u32| -> usize {
segment
.points
.iter()
.position(|point| point.step == Step::LoopEnd(lp))
.expect("a loop has an end")
};
let mut filled: HashSet<usize> = prefilled.clone();
let mut filled_per_row: HashSet<(NormalFormId, Vec<Option<usize>>)> = HashSet::new();
let mut rule_done = vec![false; plan.rules.len()];
let mut order = Vec::new();
let mut next_entry = 0;
let mut settles: Vec<Vec<crate::planning::execution_plan::LiveWork>> =
vec![Vec::new(); settle_roots.len()];
let mut stack: Vec<(usize, usize, Vec<Running>)> = Vec::new();
let mut entry_frames: Vec<bool> = Vec::new();
loop {
while let Some(&(current, pc, _)) = stack.last() {
if current >= SETTLE || pc < segments[current].points.len() {
break;
}
if current < plan.rules.len() {
rule_done[current] = true;
}
stack.pop();
entry_frames.pop();
}
if let Some(&(index, at, depth, started_at)) = starts.get(next_entry) {
assert!(
at >= order.len() && depth <= entry_frames.iter().filter(|entry| **entry).count(),
"the walk started entry {next_entry} inside {depth} entries after {at} cells; the program passed it with {} running after {}: {:?}",
entry_frames.iter().filter(|entry| **entry).count(),
order.len(),
order
);
let in_settle = stack
.last()
.is_some_and(|(current, _, _)| *current >= SETTLE);
if at == order.len()
&& depth == entry_frames.iter().filter(|entry| **entry).count()
&& !in_settle
{
let current = stack.last().map(|(segment, pc, running)| {
let points = &segments[*segment].points;
let mut at = *pc;
while let Some(point) = points.get(at) {
let runs = match point.step {
Step::Cell(cell) => {
live(&segments[*segment], point.region, running)
&& if plan.row_mask[cell.index()] != 0 {
!filled_per_row.contains(&(cell, positions_of(running)))
} else {
!filled.contains(&cell.index())
}
}
Step::Rule(forced) => {
!rule_done[forced.index()]
&& live(&segments[*segment], point.region, running)
}
Step::LoopStart(_) | Step::LoopEnd(_) | Step::ScanRead(_) => true,
};
if runs {
break;
}
at += 1;
}
(*segment, points.get(at).copied().unwrap_or(points[*pc]))
});
let rule_of_entry = (index < plan.rules.len()).then_some(index);
let matches = match (started_at, current) {
(EntryAt::Top, None) => true,
(EntryAt::Row, None) => true,
(EntryAt::Row, Some((_, point))) | (EntryAt::Rule(_), Some((_, point)))
if matches!(point.step, Step::Rule(_)) =>
{
let Step::Rule(forced) = point.step else {
unreachable!()
};
Some(forced.index()) == rule_of_entry
&& match started_at {
EntryAt::Rule(owner) => {
current.map(|(segment, _)| segment) == Some(owner.index())
}
_ => true,
}
}
(EntryAt::Cell(cell), Some((segment, point))) => match point.step {
Step::Cell(at_cell) => at_cell == cell,
Step::LoopStart(lp) | Step::LoopEnd(lp) => {
segments[segment].loops[lp as usize].command == cell
}
Step::ScanRead(_) => point.in_loop.is_some_and(|lp| {
segments[segment].loops[lp as usize].command == cell
}),
Step::Rule(_) => false,
},
_ => false,
};
if matches {
stack.push((index, 0, Vec::new()));
entry_frames.push(true);
next_entry += 1;
continue;
}
}
}
let Some((current, pc)) = stack.last().map(|(current, pc, _)| (*current, *pc)) else {
assert_eq!(
next_entry,
starts.len(),
"the program ran out before the walk's entry {next_entry}: {:?}",
order
);
break;
};
if current >= SETTLE {
let id = current - SETTLE;
if settles[id].is_empty() {
let masked: Vec<Option<OperationResult>> = (0..plan.normal_forms.len())
.map(|index| {
if filled.contains(&index) {
ctx.values[index].clone()
} else {
None
}
})
.collect();
let mut round = crate::planning::execution_plan::unsettled_live_work(
plan,
settle_roots[id],
&masked,
);
if round.is_empty() {
stack.pop();
entry_frames.pop();
continue;
}
round.reverse();
settles[id] = round;
continue;
}
let work = settles[id].pop().expect("a pending settle item");
match work {
crate::planning::execution_plan::LiveWork::Cell(cell) => {
if !filled.contains(&cell.index()) {
segments.push(segment(plan, Entry::Cell(cell)));
stack.push((segments.len() - 1, 0, Vec::new()));
entry_frames.push(false);
}
}
crate::planning::execution_plan::LiveWork::Rule(rule) => {
if !rule_done[rule.index()] {
let next = starts.get(next_entry).copied();
assert_eq!(
next,
Some((
rule.index(),
order.len(),
entry_frames.iter().filter(|entry| **entry).count(),
EntryAt::Row
)),
"the settle pass needs rule {} after {} cells; the walk's next entry is {next:?}",
plan.rule_at(rule).path,
order.len()
);
stack.push((rule.index(), 0, Vec::new()));
entry_frames.push(true);
next_entry += 1;
}
}
}
continue;
}
let segment = &segments[current];
let point = segment.points[pc];
let is_live = live(
segment,
point.region,
&stack.last().expect("a running segment").2,
);
let frame = stack.last_mut().expect("a running segment");
match point.step {
Step::LoopStart(lp) => {
let rows = if is_live {
match value(segment.loops[lp as usize].list, &frame.2) {
OperationResult::Value(bound) => match &bound.value {
ValueKind::List(rows) => (0..rows.len())
.map(|index| rows.get(index).expect("a row").into_owned())
.collect(),
other => panic!("loop list is {other:?}"),
},
OperationResult::Veto(_) => Vec::new(),
}
} else {
Vec::new()
};
if rows.is_empty() {
frame.1 = loop_end(segment, lp) + 1;
} else {
frame.2.push(Running {
lp,
start: pc,
rows,
current: 0,
});
frame.1 += 1;
}
}
Step::LoopEnd(lp) => {
let running = frame.2.last_mut().expect("a loop ends inside it");
assert_eq!(running.lp, lp);
running.current += 1;
if running.current < running.rows.len() {
frame.1 = running.start + 1;
} else {
frame.2.pop();
frame.1 += 1;
}
}
Step::ScanRead(_) => frame.1 += 1,
Step::Rule(forced) => {
assert!(
!is_live || rule_done[forced.index()],
"the program forces rule {} the walk had not run at {}: {:?}",
plan.rule_at(forced).path,
order.len(),
order
);
frame.1 += 1;
}
Step::Cell(cell) => {
let per_row_cell = plan.row_mask[cell.index()] != 0;
let key = (cell, positions_of(&frame.2));
let is_filled = if per_row_cell {
filled_per_row.contains(&key)
} else {
filled.contains(&cell.index())
};
if is_filled || !is_live {
frame.1 += 1;
continue;
}
if let Some(pin) = crate::planning::program::pin_rule(plan, cell) {
assert!(
rule_done[pin.index()],
"the program reads a slot pinned to rule {} the walk had not run at {}: {:?}",
plan.rule_at(pin).path,
order.len(),
order
);
}
if let Some(referenced) = plan.rule_ref_indexes[cell.index()] {
assert!(
rule_done[referenced.index()],
"the program reads rule {} the walk had not run at {}: {:?}",
plan.rule_at(referenced).path,
order.len(),
order
);
}
if per_row_cell {
filled_per_row.insert(key);
} else {
filled.insert(cell.index());
order.push(cell);
}
frame.1 += 1;
}
}
}
order
}
fn assert_schedule(engine: &Engine, spec: &str, data: &[(&str, &str)], explain: bool) {
assert_schedule_of(engine, spec, data, None, explain);
}
fn assert_schedule_of(
engine: &Engine,
spec: &str,
data: &[(&str, &str)],
rules: Option<&[&str]>,
explain: bool,
) {
let request: Vec<(&str, crate::EvaluateDataValue)> = data
.iter()
.map(|(key, value)| (*key, crate::EvaluateDataValue::Literal(value.to_string())))
.collect();
assert_schedule_with(engine, spec, &request, rules, explain);
}
fn assert_schedule_with(
engine: &Engine,
spec: &str,
data: &[(&str, crate::EvaluateDataValue)],
rules: Option<&[&str]>,
explain: bool,
) {
let now = DateTimeValue::now();
let plan = engine.plan(None, spec, Some(&now)).expect("plan");
let request: IndexMap<String, crate::EvaluateDataValue> = data
.iter()
.map(|(key, value)| (key.to_string(), value.clone()))
.collect();
let evaluate_data =
EvaluateData::resolve(plan, request, &crate::limits::ResourceLimits::default())
.expect("data");
let now_literal =
LiteralValue::date(crate::planning::semantics::date_time_to_semantic(&now));
let mut ctx = EvaluationContext::new(
plan,
&evaluate_data,
now_literal,
explain,
RequestCaches::new(plan, &evaluate_data),
);
let prefilled: HashSet<usize> = (0..plan.normal_forms.len())
.filter(|&index| ctx.values[index].is_some() && !ctx.leaf_unsettled(index))
.collect();
let requested: Vec<RuleIndex> = match rules {
None => plan
.rules
.keys()
.map(|rule| plan.rule_index(rule))
.collect(),
Some(names) => names
.iter()
.map(|name| plan.rule_index(&RulePath::new(Vec::new(), name.to_string())))
.collect(),
};
for &rule in &requested {
tree::ensure_rule_values(rule, plan, &mut ctx);
}
assert_context_schedule(
plan,
&ctx,
&prefilled,
&format!("{spec} {data:?} {rules:?} explain={explain}"),
);
let contexts = ctx.caches.row_contexts.borrow();
for (key, row_ctx) in contexts.iter() {
let template = plan.row_template(&key.row.identity);
let logged: HashSet<NormalFormId> = row_ctx.store_log.iter().copied().collect();
let prefilled: HashSet<usize> = (0..template.normal_forms.len())
.filter(|&index| {
row_ctx.values[index].is_some()
&& !logged.contains(&NormalFormId::from_index(index))
})
.collect();
assert_context_schedule(
template,
row_ctx,
&prefilled,
&format!("{spec} {data:?} {rules:?} explain={explain}: row {key}"),
);
}
drop(contexts);
assert_full_schedule(engine, spec, data, explain);
}
fn assert_full_schedule(
engine: &Engine,
spec: &str,
data: &[(&str, crate::EvaluateDataValue)],
explain: bool,
) {
let now = DateTimeValue::now();
let plan = engine.plan(None, spec, Some(&now)).expect("plan");
let request: IndexMap<String, crate::EvaluateDataValue> = data
.iter()
.map(|(key, value)| (key.to_string(), value.clone()))
.collect();
let evaluate_data =
EvaluateData::resolve(plan, request, &crate::limits::ResourceLimits::default())
.expect("data");
let now_literal =
LiteralValue::date(crate::planning::semantics::date_time_to_semantic(&now));
let requested = plan
.validated_response_rule_paths(None)
.expect("every rule");
let requested_rules: Vec<RuleIndex> =
requested.iter().map(|path| plan.rule_index(path)).collect();
let unsettled_at_intake = EvaluationContext::new(
plan,
&evaluate_data,
now_literal.clone(),
explain,
RequestCaches::new(plan, &evaluate_data),
)
.unsettled_leaves;
let (_, ctx) =
Evaluator.evaluate_retaining(plan, &evaluate_data, now_literal, requested, explain);
let what = format!("{spec} {data:?} full explain={explain}");
assert_request_program(plan, &ctx, &requested_rules, &unsettled_at_intake, &what);
let logged: HashSet<NormalFormId> = ctx.store_log.iter().copied().collect();
let prefilled: HashSet<usize> = (0..plan.normal_forms.len())
.filter(|&index| {
ctx.values[index].is_some() && !logged.contains(&NormalFormId::from_index(index))
})
.collect();
assert_context_schedule(plan, &ctx, &prefilled, &what);
{
let contexts = ctx.caches.row_contexts.borrow();
for (key, row_ctx) in contexts.iter() {
let template = plan.row_template(&key.row.identity);
let logged: HashSet<NormalFormId> = row_ctx.store_log.iter().copied().collect();
let prefilled: HashSet<usize> = (0..template.normal_forms.len())
.filter(|&index| {
row_ctx.values[index].is_some()
&& !logged.contains(&NormalFormId::from_index(index))
})
.collect();
assert_context_schedule(
template,
row_ctx,
&prefilled,
&format!("{what}: row {key}"),
);
}
}
ctx.caches.row_contexts.borrow_mut().clear();
}
fn assert_request_program(
plan: &ExecutionPlan,
ctx: &EvaluationContext,
requested: &[RuleIndex],
unsettled_at_intake: &HashSet<usize>,
what: &str,
) {
use crate::planning::program::{request_program, Entry, RequestStep};
let tops: Vec<usize> = (0..ctx.entry_log.len())
.filter(|&index| ctx.entry_log[index].3 == EntryAt::Top)
.collect();
let mut next = 0;
for step in request_program(plan, requested.iter().copied()) {
let RequestStep::Run(entry) = step else {
continue;
};
let (before_entries, before_stores) = match tops.get(next) {
Some(&index) => (index, ctx.entry_log[index].1),
None => (ctx.entry_log.len(), ctx.store_log.len()),
};
let (expected, runs) = match entry {
Entry::Rule(rule) => (
EntryRun::Rule(rule),
!ctx.entry_log[..before_entries]
.iter()
.any(|(run, ..)| *run == EntryRun::Rule(rule)),
),
Entry::Leaf(leaf) => (
EntryRun::Leaf(leaf),
unsettled_at_intake.contains(&leaf.index())
&& !ctx.store_log[..before_stores].contains(&leaf),
),
Entry::Cell(_) | Entry::Materialize => {
panic!("{what}: a request's root program runs no {entry:?}")
}
};
if !runs {
continue;
}
let index = *tops
.get(next)
.unwrap_or_else(|| panic!("{what}: the walk ran no top-level entry for {entry:?}"));
assert_eq!(
ctx.entry_log[index].0, expected,
"{what}: top-level entry {next} of the walk is not the root program's next step"
);
next += 1;
}
}
fn assert_context_schedule(
plan: &ExecutionPlan,
ctx: &EvaluationContext,
prefilled: &HashSet<usize>,
what: &str,
) {
let raw = &ctx.store_log[..];
let mut walked: Vec<NormalFormId> = Vec::new();
let mut distinct_before: Vec<usize> = Vec::with_capacity(raw.len() + 1);
let mut seen = HashSet::new();
for &cell in raw {
distinct_before.push(walked.len());
if seen.insert(cell) {
walked.push(cell);
}
}
distinct_before.push(walked.len());
let entries: Vec<(EntryRun, usize, usize, EntryAt)> = ctx
.entry_log
.iter()
.map(|(entry, at, depth, started_at)| {
(*entry, distinct_before[*at], *depth, *started_at)
})
.collect();
let planned = planned_schedule(plan, ctx, prefilled, &entries);
let show = |cells: &[NormalFormId]| -> Vec<String> {
cells
.iter()
.map(|cell| format!("{}:{:?}", cell.index(), plan.normal_form(*cell).kind))
.collect()
};
assert_eq!(
show(&planned),
show(&walked),
"{what}: entries {entries:?}: planned schedule differs from the walk"
);
}
const SCHEDULE_SPEC: &str = r#"
spec s
data x: number
data y: number
data m: boolean
data n: boolean
data code: text
rule shared: false
unless x > 5 or y > 5 then true
unless m then x > 5
rule both: m and n
rule either: m or n
rule fold: x + y * 2 - x / y
rule quotient: x / y
rule guarded: veto "no"
rule after_veto: guarded + x
rule chosen: "none"
unless code is "NL" then "Netherlands"
unless code is "BE" then "Belgium"
rule from_rules: fold + quotient
rule negated: not m
"#;
#[test]
fn planned_schedule_matches_the_walk_on_the_examples() {
let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR"));
let mut checked = 0;
for dir in [
"../cli/tests/integrations/examples",
"documentation/examples",
"benches/specs",
"tests/fixtures/explain",
] {
let mut files: Vec<_> = std::fs::read_dir(root.join(dir))
.expect("example directory")
.map(|entry| entry.expect("directory entry").path())
.filter(|path| path.extension().is_some_and(|ext| ext == "lemma"))
.filter(|path| !path.ends_with("12_registry_references.lemma"))
.collect();
files.sort();
for path in files {
let code = std::fs::read_to_string(&path).expect("example source");
let mut engine = Engine::new();
engine
.load([(crate::parsing::source::SourceType::Volatile, code.clone())])
.unwrap_or_else(|errors| panic!("{}: {errors:?}", path.display()));
let specs: Vec<String> = engine
.specs()
.iter()
.filter(|repository| repository.repository.is_none())
.flat_map(|repository| repository.specs.iter().map(|spec| spec.name.clone()))
.collect();
for spec in specs {
for explain in [false, true] {
assert_schedule(&engine, &spec, &[], explain);
assert_full_schedule(&engine, &spec, &[], explain);
checked += 1;
}
}
}
}
assert!(checked > 0);
}
#[test]
fn planned_schedule_matches_the_walk_across_instances() {
let code = r#"
spec inner
data x: number
rule total: x * 2
spec middle
uses j: inner
data y: number
rule combined: j.total + y
spec outer
data base: number
data extra: number
data mode: text
rule rate: base + extra
uses i: inner
-> with x: rate
uses m: middle
-> with j.x: base
-> with y: extra
rule result: 0
unless mode is "use" then i.total
rule direct: i.total
rule nested: m.combined
rule deep: m.j.total
spec item
data bonus: number
rule doubled: bonus * 2
spec lists
uses item
data base: number
rule extra: base + 1
data items: item list
-> with bonus: extra
-> with bonus: 3
rule first_bonus: (items -> first).bonus
rule last_doubled: (items -> last).doubled
rule total: items -> sum items.doubled
rule many: items -> count
spec scales
data factor: number
spec reader
uses global scales
data amount: number
rule scaled: amount * scales.factor
spec provider
uses global scales -> with factor: 3
uses r: reader
-> with amount: 2
rule result: r.scaled
"#;
let mut engine = Engine::new();
engine
.load([(
crate::parsing::source::SourceType::Volatile,
code.to_string(),
)])
.unwrap_or_else(|errors| panic!("load: {errors:?}"));
let cases: &[(&str, &[(&str, &str)])] = &[
("outer", &[]),
("outer", &[("base", "2")]),
("outer", &[("base", "2"), ("extra", "3")]),
("outer", &[("base", "2"), ("extra", "3"), ("mode", "use")]),
("outer", &[("mode", "skip")]),
("lists", &[]),
("lists", &[("base", "4")]),
("provider", &[]),
];
for (spec, data) in cases {
for explain in [false, true] {
assert_schedule(&engine, spec, data, explain);
}
}
let single: &[(&str, &str)] = &[
("outer", "result"),
("outer", "direct"),
("outer", "nested"),
("outer", "deep"),
("lists", "first_bonus"),
("lists", "last_doubled"),
("lists", "total"),
("lists", "many"),
("provider", "result"),
];
for (spec, rule) in single {
for data in [
&[][..],
&[("base", "2"), ("extra", "3"), ("mode", "use")][..],
] {
for explain in [false, true] {
assert_schedule_of(&engine, spec, data, Some(&[rule]), explain);
}
}
}
}
#[test]
fn planned_schedule_matches_the_walk_over_keyed_rows() {
let code = r#"
spec item
data code: text
data price: number
rule doubled: price * 2
spec shop
uses item
data base: number
rule first_code: "a"
rule second_price: base + 1
data items: item list
-> with code: first_code, price: 1
-> with code: "b", price: second_price
rule by_key: (items -> key code -> find "b").price
rule keyed: items -> key code -> count
rule head: (items -> first).doubled
rule tail: (items -> last).price
rule many: items -> count
rule cheap: items -> where items.price < 5 -> count
"#;
let mut engine = Engine::new();
engine
.load([(
crate::parsing::source::SourceType::Volatile,
code.to_string(),
)])
.unwrap_or_else(|errors| panic!("load: {errors:?}"));
for rule in ["by_key", "keyed", "head", "tail", "many", "cheap"] {
for data in [&[][..], &[("base", "4")][..]] {
for explain in [false, true] {
assert_schedule_of(&engine, "shop", data, Some(&[rule]), explain);
}
}
}
for data in [&[][..], &[("base", "4")][..]] {
for explain in [false, true] {
assert_schedule(&engine, "shop", data, explain);
}
}
}
#[test]
fn planned_schedule_matches_the_walk_over_run_data_rows() {
let code = r#"
spec item
data code: text
data price: number
spec shop
uses item
data items: item list
data stock: item list
-> key code
rule by_key: (items -> key code -> find "c").price
rule indexed: (stock -> find "c").price
rule cheapest: items -> min items.price
"#;
let mut engine = Engine::new();
engine
.load([(
crate::parsing::source::SourceType::Volatile,
code.to_string(),
)])
.unwrap_or_else(|errors| panic!("load: {errors:?}"));
let row = |fields: &[(&str, &str)]| {
crate::EvaluateDataValue::Map(
fields
.iter()
.map(|(name, value)| {
(
name.to_string(),
crate::EvaluateDataValue::Literal(value.to_string()),
)
})
.collect(),
)
};
let complete = crate::EvaluateDataValue::List(vec![
row(&[("code", "a"), ("price", "1")]),
row(&[("code", "c"), ("price", "3")]),
]);
let gap = crate::EvaluateDataValue::List(vec![
row(&[("code", "a"), ("price", "1")]),
row(&[("price", "2")]),
row(&[("code", "c"), ("price", "3")]),
]);
for rule in ["by_key", "indexed", "cheapest"] {
for rows in [&complete, &gap] {
for explain in [false, true] {
let data = [("items", rows.clone()), ("stock", complete.clone())];
assert_schedule_with(&engine, "shop", &data, Some(&[rule]), explain);
}
}
}
}
#[test]
fn planned_schedule_matches_the_walk_through_nested_bindings() {
let code = r#"
spec inner
data x: number
rule total: x * 2
spec middle
uses j: inner
data y: number
rule combined: j.total + y
spec outer
data base: number
rule rate: base + 1
uses m: middle
-> with j.x: rate
-> with y: 4
rule deep: m.j.total
rule nested: m.combined
rule direct: m.j.x
"#;
let mut engine = Engine::new();
engine
.load([(
crate::parsing::source::SourceType::Volatile,
code.to_string(),
)])
.unwrap_or_else(|errors| panic!("load: {errors:?}"));
for rule in ["deep", "nested", "direct"] {
for data in [&[][..], &[("base", "2")][..]] {
for explain in [false, true] {
assert_schedule_of(&engine, "outer", data, Some(&[rule]), explain);
}
}
}
}
#[test]
fn planned_schedule_matches_the_walk_where_guards_skip_work() {
let code = r#"
spec s
data off: boolean
data unused_flag: boolean
data spare: number
data per_usd: number
rule blocked: veto "no"
rule cut: blocked - spare
rule gate: off and unused_flag
rule rate: per_usd * 2
data money: measure
-> unit eur: 1
-> unit usd: rate
rule total: 10 usd as eur
"#;
let mut engine = Engine::new();
engine
.load([(
crate::parsing::source::SourceType::Volatile,
code.to_string(),
)])
.unwrap_or_else(|errors| panic!("load: {errors:?}"));
for (rule, data) in [
("cut", &[][..]),
("cut", &[("spare", "3")][..]),
("gate", &[("off", "false")][..]),
("gate", &[("off", "true")][..]),
("total", &[("per_usd", "4")][..]),
("total", &[][..]),
] {
for explain in [false, true] {
assert_schedule_of(&engine, "s", data, Some(&[rule]), explain);
}
}
}
#[test]
fn planned_schedule_matches_the_walk_through_pins() {
let code = r#"
spec rate 2020-01-01
data base: number
rule amount: base * 2
spec rate 2023-01-01
data base: number
rule amount: base * 3
spec holder
data when: date
rule chosen: when
uses by_data: rate
-> effective when
-> with base: 5
uses by_rule: rate
-> effective chosen
-> with base: 7
rule from_data: by_data.amount
rule from_rule: by_rule.amount
spec outer
uses h: holder
rule nested: h.from_rule + h.from_data
spec checked
data dates: date list
rule offered: dates
data when: date
-> options offered
uses by_data: rate
-> effective when
-> with base: 5
rule from_data: by_data.amount
"#;
let mut engine = Engine::new();
engine
.load([(
crate::parsing::source::SourceType::Volatile,
code.to_string(),
)])
.unwrap_or_else(|errors| panic!("load: {errors:?}"));
for (spec, rule, data) in [
("holder", "from_data", &[("when", "2021-06-01")][..]),
("holder", "from_data", &[][..]),
("holder", "from_rule", &[("when", "2024-06-01")][..]),
("holder", "from_rule", &[][..]),
("outer", "nested", &[("h.when", "2021-06-01")][..]),
("outer", "nested", &[][..]),
] {
for explain in [false, true] {
assert_schedule_of(&engine, spec, data, Some(&[rule]), explain);
}
}
let literal = |value: &str| crate::EvaluateDataValue::Literal(value.to_string());
let dates =
crate::EvaluateDataValue::List(vec![literal("2021-06-01"), literal("2024-06-01")]);
for when in [Some("2021-06-01"), Some("2022-06-01"), None] {
let mut data = vec![("dates", dates.clone())];
if let Some(when) = when {
data.push(("when", literal(when)));
}
for explain in [false, true] {
assert_schedule_with(&engine, "checked", &data, Some(&["from_data"]), explain);
}
}
}
#[test]
fn planned_schedule_matches_the_walk_through_settle_passes() {
let code = r#"
spec item
data a: number
data b: number
data flag: boolean
rule chosen: a * 2
unless flag then b + 1
spec order
uses item
data items: item list
rule first_chosen: (items -> first).chosen
rule total: items -> sum items.chosen
"#;
let mut engine = Engine::new();
engine
.load([(
crate::parsing::source::SourceType::Volatile,
code.to_string(),
)])
.unwrap_or_else(|errors| panic!("load: {errors:?}"));
let literal = |value: &str| crate::EvaluateDataValue::Literal(value.to_string());
let row = |fields: &[(&str, &str)]| {
crate::EvaluateDataValue::Map(
fields
.iter()
.map(|(name, value)| (name.to_string(), literal(value)))
.collect(),
)
};
for rows in [
vec![row(&[])],
vec![row(&[("a", "1")]), row(&[("flag", "true")])],
vec![row(&[("flag", "false"), ("a", "2")]), row(&[("b", "3")])],
] {
for rule in ["first_chosen", "total"] {
for explain in [false, true] {
let data = [("items", crate::EvaluateDataValue::List(rows.clone()))];
assert_schedule_with(&engine, "order", &data, Some(&[rule]), explain);
}
}
}
}
#[test]
fn planned_schedule_matches_the_walk() {
let cases: &[&[(&str, &str)]] = &[
&[],
&[("x", "10")],
&[("x", "1")],
&[("x", "1"), ("y", "0")],
&[
("x", "3"),
("y", "4"),
("m", "true"),
("n", "false"),
("code", "BE"),
],
&[
("x", "3"),
("y", "4"),
("m", "false"),
("n", "true"),
("code", "DE"),
],
&[("m", "true")],
&[("n", "false")],
&[("code", "NL")],
];
let mut engine = Engine::new();
engine
.load([(
crate::parsing::source::SourceType::Volatile,
SCHEDULE_SPEC.to_string(),
)])
.unwrap_or_else(|errors| panic!("load: {errors:?}"));
for data in cases {
for explain in [false, true] {
assert_schedule(&engine, "s", data, explain);
}
}
}
#[test]
fn reference_runtime_value_carries_resolved_type_not_target_type() {
let code = r#"
spec inner
data slot: number -> minimum 0 -> maximum 100
spec source_spec
data v: 5
spec outer
uses i: inner
-> with slot: src.v
uses src: source_spec
rule r: i.slot
"#;
let mut engine = Engine::new();
engine
.load([(
crate::SourceType::Path(std::sync::Arc::new(std::path::PathBuf::from(
"ref_invariant.lemma",
))),
code.to_string(),
)])
.expect("must load");
let plan_basis = engine
.plans
.get_plans(None, "outer")
.and_then(|plans| plans.values().next())
.expect("must plan");
let crate::planning::semantics::DataDefinition::Import { row, .. } = plan_basis
.data
.get(&DataPath::local("i".to_string()))
.expect("`uses i` is data of the consumer plan")
else {
panic!("`i` must be an import");
};
let template = plan_basis.row_template(&row.identity);
let slot_path = DataPath::local("slot".to_string());
assert!(
matches!(
row.get_binding(template, &slot_path),
Some(RowBinding::Deferred { .. })
),
"`slot` of `i` is bound by `uses -> with` to a reference of the consumer"
);
let resolved_type = template
.data
.get(&slot_path)
.and_then(|definition| definition.resolved_type_arc())
.map(Arc::clone)
.expect("`slot` must be typed by the imported field");
let evaluate_data = EvaluateData::default();
let now = DateTimeValue::now();
let now_lit = LiteralValue {
value: crate::planning::semantics::ValueKind::Date(
crate::planning::semantics::date_time_to_semantic(&now),
),
};
let mut context = EvaluationContext::new(
plan_basis,
&evaluate_data,
now_lit,
false,
RequestCaches::new(plan_basis, &evaluate_data),
);
let rule = RulePath::new(Vec::new(), "r".to_string());
tree::ensure_rule_values(plan_basis.rule_index(&rule), plan_basis, &mut context);
let stored = context.rule_value(plan_basis, &rule).clone();
let OperationResult::Value(value) = stored else {
panic!("reference path must hold a value, got {stored:?}");
};
assert!(
matches!(
resolved_type.specifications,
crate::planning::semantics::TypeSpecification::Number {
minimum: Some(_),
maximum: Some(_),
..
}
),
"reference resolved_type must keep LHS constraints, got {:?}",
resolved_type.specifications
);
assert!(
matches!(
value.value,
crate::planning::semantics::ValueKind::Number(_)
),
"stored value must be the copied number, got {:?}",
value.value
);
}
}