use crate::computation::{OperationResult, VetoType};
use crate::evaluation::branch_semantics::{condition_outcome, BranchOutcome};
use crate::evaluation::compute::{
self, borrow_value, find_keyed, first_operand, options_rule_blocker,
};
use crate::evaluation::compute::{
bare_target_row, composed_unit_scale_factor, resolve_stored_target, runtime_scales_for,
stored_list, unforced_reference, unforced_target,
};
use crate::evaluation::expression::resolve_data_path_value;
use crate::evaluation::list_ops::{self, ListFold};
use crate::evaluation::lookup;
use crate::evaluation::rows::{self, RowRead};
use crate::evaluation::RequestCaches;
use crate::evaluation::{CurrentRow, EvaluationContext, RowLogMark};
use crate::parsing::ast::LogicalConnective;
use crate::planning::execution_plan::{unsettled_live_work, ExecutionPlan, LiveWork, RuleIndex};
use crate::planning::instance_list::{row_end_type, typed_from_bound, KeyIndex};
use crate::planning::normalize::{
ArithmeticTerm, DispatchRegion, LeafKind, NormalFormId, NormalFormKind, NormalFormListOp,
};
use crate::planning::ordered_dispatch::{region_count, region_of_scrutinee};
use crate::planning::semantics::InstanceFactors;
use crate::planning::semantics::{
BoundValueKind, DataDefinition, DataPath, InstanceKey, KeyField, LemmaType, ListKey, ListValue,
LiteralValue, ReferenceEnd, ReferenceTarget, RowBinding, RowEnd, RowOrigin, RulePath,
ScaleTarget, SpecValue, TypedLiteral, ValueKind,
};
use std::cmp::Ordering;
use std::collections::{HashMap, HashSet};
use std::sync::Arc;
pub(crate) fn ensure_rule_values(
rule: RuleIndex,
plan: &ExecutionPlan,
ctx: &mut EvaluationContext,
) {
run(plan, ctx, Frame::rule(rule));
}
pub(crate) fn ensure_leaf_value(
leaf: NormalFormId,
plan: &ExecutionPlan,
ctx: &mut EvaluationContext,
) {
run(plan, ctx, Frame::cell(leaf));
}
pub(crate) fn settle_live_work<'p>(
rule_root: NormalFormId,
at: Option<(&InstanceKey, &'p ExecutionPlan)>,
plan: &'p ExecutionPlan,
ctx: &mut EvaluationContext,
) {
let first = match at {
None => Frame::settle(rule_root),
Some((key, template)) => {
Frame::row_scope(key.clone(), template, RowBody::Settle(rule_root))
}
};
run(plan, ctx, first);
}
pub(crate) fn ensure_row_rule_value(
key: &InstanceKey,
rule: &RulePath,
plan: &ExecutionPlan,
ctx: &mut EvaluationContext,
) {
run(
plan,
ctx,
Frame::read_row(key.clone(), RowEnd::Rule(rule.clone()), None),
);
}
pub(crate) fn ensure_row_rule(
key: &InstanceKey,
template: &ExecutionPlan,
rule: RuleIndex,
plan: &ExecutionPlan,
ctx: &mut EvaluationContext,
) {
run(
plan,
ctx,
Frame::row_scope(key.clone(), template, RowBody::Rule(rule)),
);
}
pub(crate) fn materialize_row(
key: &InstanceKey,
template: &ExecutionPlan,
plan: &ExecutionPlan,
ctx: &mut EvaluationContext,
) {
run(
plan,
ctx,
Frame::row_scope(key.clone(), template, RowBody::Materialize),
);
}
type WalkDone = HashMap<NormalFormId, OperationResult>;
type Delivered = Option<OperationResult>;
fn ready(id: NormalFormId, ctx: &EvaluationContext, walk: &WalkDone) -> Option<OperationResult> {
if ctx.leaf_unsettled(id.index()) {
return None;
}
walk.get(&id)
.cloned()
.or_else(|| ctx.values[id.index()].clone())
}
fn finish(
id: NormalFormId,
result: OperationResult,
plan: &ExecutionPlan,
ctx: &mut EvaluationContext,
) -> OperationResult {
#[cfg(test)]
ctx.log_store(plan, id, &result);
let cell = plan.normal_form(id);
let result = result.held_as(&cell.result_type);
let data_missing = match (&cell.kind, &result) {
(
NormalFormKind::Leaf(LeafKind::DataPath(path)),
OperationResult::Veto(VetoType::MissingData { .. }),
) if cell.rule_ref.is_none() => {
!matches!(plan.data.get(path), Some(DataDefinition::Import { .. }))
}
_ => false,
};
let leave_unbound = data_missing && ctx.values[id.index()].is_none();
let per_row_unscaled = !ctx.row_stack.is_empty()
&& matches!(
&cell.kind,
NormalFormKind::Leaf(LeafKind::Literal(literal))
if literal.value.has_unscaled_measure()
);
if !leave_unbound && plan.row_mask[id.index()] == 0 && !per_row_unscaled {
ctx.values[id.index()] = Some(result.clone());
}
result
}
struct Scope<'p> {
plan: &'p ExecutionPlan,
ctx: EvaluationContext,
}
#[derive(Clone, Copy)]
enum WalkMode {
Same,
New,
}
enum Outcome<'p> {
Finish(Delivered),
Spawn(Frame<'p>, WalkMode),
Enter(Scope<'p>),
Exit(Delivered, InstanceKey),
}
fn spawn<'p>(frame: Frame<'p>, mode: WalkMode) -> Outcome<'p> {
Outcome::Spawn(frame, mode)
}
struct Frame<'p> {
kind: Kind<'p>,
walk: usize,
owns_walk: bool,
depth: usize,
inbox: Delivered,
#[cfg(test)]
entry: bool,
#[cfg(test)]
forced: bool,
#[cfg(feature = "call-graph-check")]
piece: Option<std::rc::Rc<crate::evaluation::CallAt>>,
#[cfg(feature = "call-graph-check")]
nesting: usize,
}
const SCOPE_INHERIT: usize = usize::MAX;
enum Kind<'p> {
Cell(CellFrame),
Rule(RuleFrame),
RowScope(RowScopeFrame<'p>),
ReadRow(ReadRowFrame),
ListOp(ListOpFrame<'p>),
Settle(SettleFrame),
}
impl<'p> Frame<'p> {
fn of(kind: Kind<'p>) -> Self {
Self {
kind,
walk: 0,
owns_walk: false,
depth: SCOPE_INHERIT,
inbox: None,
#[cfg(test)]
entry: false,
#[cfg(test)]
forced: false,
#[cfg(feature = "call-graph-check")]
piece: None,
#[cfg(feature = "call-graph-check")]
nesting: 0,
}
}
fn cell(id: NormalFormId) -> Self {
Self::of(Kind::Cell(CellFrame {
id,
cursor: 0,
acc: None,
veto: None,
settled: None,
resume: None,
member_mark: None,
}))
}
fn rule(index: RuleIndex) -> Self {
Self::of(Kind::Rule(RuleFrame {
index,
depth: 0,
saved_rows: None,
scale_cursor: 0,
body_spawned: false,
}))
}
fn settle(root: NormalFormId) -> Self {
Self::of(Kind::Settle(SettleFrame {
root,
pending: Vec::new(),
forced: None,
}))
}
fn row_scope(key: InstanceKey, template: &'p ExecutionPlan, body: RowBody) -> Self {
Self::of(Kind::RowScope(RowScopeFrame {
key,
template,
body,
phase: RowPhase::Acquire,
read_slots: Vec::new(),
scale_cursor: 0,
}))
}
fn read_row(key: InstanceKey, end: RowEnd, position: Option<usize>) -> Self {
let read = rows::ReadRow {
key: key.clone(),
position,
};
Self::of(Kind::ReadRow(ReadRowFrame {
read,
key,
end,
rule_root: None,
settling: None,
}))
}
fn list_op(
id: NormalFormId,
list: NormalFormId,
op: &'p NormalFormListOp,
args: &'p [NormalFormId],
row_level: Option<u32>,
result_type: &'p Arc<LemmaType>,
) -> Self {
Self::of(Kind::ListOp(ListOpFrame {
id,
list,
op,
args,
row_level,
result_type,
state: ListState::Start,
}))
}
}
struct CellFrame {
id: NormalFormId,
cursor: usize,
acc: Option<OperationResult>,
veto: Option<OperationResult>,
settled: Option<OperationResult>,
resume: Option<Resume>,
member_mark: Option<RowLogMark>,
}
enum Resume {
Plain,
RowLog(RowLogMark),
Member(RowLogMark),
}
struct RuleFrame {
index: RuleIndex,
depth: usize,
saved_rows: Option<Vec<CurrentRow>>,
scale_cursor: usize,
body_spawned: bool,
}
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub(crate) enum RowBody {
Nothing,
Materialize,
Rule(RuleIndex),
Leaf(NormalFormId),
Member(NormalFormId),
Settle(NormalFormId),
}
enum RowPhase {
Acquire,
Resolve(usize),
Children(Vec<InstanceKey>),
Body,
Await,
Open(usize),
OpenAwait,
AwaitSettle,
OpenAwaitSettle,
}
struct RowScopeFrame<'p> {
key: InstanceKey,
template: &'p ExecutionPlan,
body: RowBody,
phase: RowPhase,
read_slots: Vec<DataPath>,
scale_cursor: usize,
}
struct ReadRowFrame {
key: InstanceKey,
end: RowEnd,
read: rows::ReadRow,
rule_root: Option<NormalFormId>,
settling: Option<OperationResult>,
}
struct SettleFrame {
root: NormalFormId,
pending: Vec<LiveWork>,
forced: Option<LiveWork>,
}
struct ListData {
rows: ListValue,
unit: Option<Arc<str>>,
}
enum ListState {
Start,
AwaitList,
Args {
data: ListData,
values: Vec<OperationResult>,
count: usize,
key_fields: Option<Vec<KeyField>>,
},
PerRow {
data: ListData,
cursor: usize,
values: Vec<BoundValueKind>,
first_veto: Option<OperationResult>,
},
InlineDeferred {
data: ListData,
values: Vec<OperationResult>,
count: usize,
key_fields: Option<Vec<KeyField>>,
pending: std::vec::IntoIter<RowBody>,
},
Scan(KeyScan),
}
struct KeyScan {
rows: ListValue,
fields: Vec<KeyField>,
row: usize,
field: usize,
key: Vec<TypedLiteral>,
keyed: Vec<Vec<TypedLiteral>>,
then: ScanThen,
}
enum ScanThen {
List(Option<Arc<str>>),
Find(Vec<TypedLiteral>),
}
struct ListOpFrame<'p> {
id: NormalFormId,
list: NormalFormId,
op: &'p NormalFormListOp,
args: &'p [NormalFormId],
row_level: Option<u32>,
result_type: &'p Arc<LemmaType>,
state: ListState,
}
fn run<'p>(
root_plan: &'p ExecutionPlan,
root: &mut EvaluationContext,
first: Frame<'p>,
) -> Delivered {
let mut active_rules: HashSet<(usize, RuleIndex)> = HashSet::new();
let mut open_rows: HashSet<InstanceKey> = HashSet::new();
let mut active_cells: HashSet<(usize, NormalFormId)> = HashSet::new();
if let Kind::Rule(rule) = &first.kind {
active_rules.insert((rule.depth, rule.index));
}
#[cfg(test)]
let first = match &first.kind {
Kind::Rule(rule) if root.rule_values[rule.index.index()].is_none() => {
root.log_entry(
crate::evaluation::EntryRun::Rule(rule.index),
crate::evaluation::EntryAt::Top,
);
Frame {
entry: true,
..first
}
}
Kind::Settle(settle) => {
root.log_entry(
crate::evaluation::EntryRun::Settle(settle.root),
crate::evaluation::EntryAt::Top,
);
Frame {
entry: true,
..first
}
}
Kind::Cell(cell) => {
root.log_entry(
crate::evaluation::EntryRun::Leaf(cell.id),
crate::evaluation::EntryAt::Top,
);
Frame {
entry: true,
..first
}
}
_ => first,
};
let mut walks: Vec<WalkDone> = Vec::new();
let first = match &first.kind {
Kind::Cell(cell) => {
active_cells.insert((0, cell.id));
walks.push(WalkDone::new());
Frame {
walk: 0,
owns_walk: true,
depth: 0,
..first
}
}
_ => first,
};
#[cfg(feature = "call-graph-check")]
let first = {
let mut first = first;
if first.depth == SCOPE_INHERIT {
first.depth = 0;
}
place_piece(&mut first, None, root_plan, &mut *root, &mut []);
first
};
let mut frames = vec![first];
let mut scopes: Vec<Scope<'p>> = Vec::new();
loop {
let frame = frames
.last_mut()
.expect("BUG: evaluation machine ran out of frames");
if frame.depth == SCOPE_INHERIT {
frame.depth = 0;
}
#[cfg(test)]
{
root.frame_tops = frame_tops(&frames, scopes.len());
}
let frame = frames
.last_mut()
.expect("BUG: evaluation machine ran out of frames");
let outcome = step(frame, root_plan, &mut *root, &mut scopes, &walks);
if let Outcome::Spawn(child, WalkMode::New) = &outcome {
if let Kind::Cell(cell) = &child.kind {
let depth = if child.depth == SCOPE_INHERIT {
frame.depth
} else {
child.depth
};
let (plan, ctx) = layer(depth, root_plan, &mut *root, &mut scopes);
if let Some(cached) = ctx.values[cell.id.index()].clone() {
if !ctx.leaf_unsettled(cell.id.index()) {
let cell_def = plan.normal_form(cell.id);
if cell_def.origin.is_some() && ctx.exhaustive {
} else {
let per_row_unscaled = !ctx.row_stack.is_empty()
&& matches!(
&cell_def.kind,
NormalFormKind::Leaf(LeafKind::Literal(literal))
if literal.value.has_unscaled_measure()
);
if !per_row_unscaled {
#[cfg(test)]
if child.entry {
ctx.log_entry_end();
}
frame.inbox = Some(cached);
continue;
}
}
}
}
}
}
match outcome {
Outcome::Spawn(mut child, mode) => {
if child.depth == SCOPE_INHERIT {
child.depth = frame.depth;
}
if let (WalkMode::New, Kind::Cell(cell)) = (&mode, &child.kind) {
assert!(
active_cells.insert((child.depth, cell.id)),
"BUG: cell {:?} of scope {} started while it is being evaluated",
cell.id,
child.depth
);
}
match mode {
WalkMode::Same => child.walk = frame.walk,
WalkMode::New => {
walks.push(WalkDone::new());
child.walk = walks.len() - 1;
child.owns_walk = true;
}
}
#[cfg(test)]
{
let at = root.frame_tops[child.depth];
let (_, ctx) = layer(child.depth, root_plan, &mut *root, &mut scopes);
match &child.kind {
Kind::Rule(rule) if ctx.rule_values[rule.index.index()].is_none() => {
ctx.log_entry(crate::evaluation::EntryRun::Rule(rule.index), at);
child.entry = true;
}
Kind::Cell(cell) if child.forced => {
ctx.log_entry(crate::evaluation::EntryRun::Member(cell.id), at);
child.entry = true;
}
_ => {}
}
}
if let Kind::Rule(rule) = &mut child.kind {
rule.depth = child.depth;
if !active_rules.insert((rule.depth, rule.index)) {
let (plan, _) = layer(rule.depth, root_plan, &mut *root, &mut scopes);
panic!(
"BUG: cyclic rule reference while ensuring values for '{}'",
plan.rule_at(rule.index).path
);
}
}
#[cfg(feature = "call-graph-check")]
place_piece(
&mut child,
frames.last(),
root_plan,
&mut *root,
&mut scopes,
);
frames.push(child);
}
Outcome::Enter(scope) => {
let Kind::RowScope(row_scope) = &frame.kind else {
panic!("BUG: only a row scope frame enters a scope");
};
assert!(
open_rows.insert(row_scope.key.clone()),
"BUG: row scope '{}' entered while it is open",
row_scope.key
);
scopes.push(scope);
walks.push(WalkDone::new());
frame.walk = walks.len() - 1;
frame.owns_walk = true;
frame.depth = scopes.len();
}
Outcome::Finish(value) => {
let frame = frames.pop().expect("BUG: the stepped frame is on top");
#[cfg(test)]
{
let ended = frame.entry.then_some(frame.depth);
if let Some(depth) = ended {
layer(depth, root_plan, &mut *root, &mut scopes)
.1
.log_entry_end();
}
}
if let Kind::Rule(rule) = &frame.kind {
assert!(
active_rules.remove(&(rule.depth, rule.index)),
"BUG: finished rule frame was not active"
);
}
if let (true, Kind::Cell(cell)) = (frame.owns_walk, &frame.kind) {
assert!(
active_cells.remove(&(frame.depth, cell.id)),
"BUG: finished cell frame was not active"
);
}
let stored = match &frame.kind {
Kind::Cell(cell) => {
let depth = frame.depth;
let (_, ctx) = layer(depth, root_plan, &mut *root, &mut scopes);
ctx.values[cell.id.index()].is_some()
}
_ => false,
};
if let Some(result) = complete(frame, value, stored, &mut frames, &mut walks) {
return result;
}
}
Outcome::Exit(value, row) => {
let frame = frames.pop().expect("BUG: the stepped frame is on top");
assert!(
scopes.len() == frame.depth,
"BUG: row scope at depth {} exited above {} entered scopes",
frame.depth,
scopes.len()
);
let scope = scopes.pop().expect("BUG: scope left without being entered");
assert!(
open_rows.remove(&row),
"BUG: row scope '{row}' exited without being entered"
);
root.caches.row_contexts.borrow_mut().insert(row, scope.ctx);
if let Some(result) = complete(frame, value, false, &mut frames, &mut walks) {
return result;
}
}
}
}
}
#[cfg(test)]
fn frame_tops(frames: &[Frame<'_>], scopes: usize) -> Vec<crate::evaluation::EntryAt> {
use crate::evaluation::EntryAt;
let mut tops = vec![EntryAt::Top; scopes + 1];
for frame in frames {
if frame.depth == SCOPE_INHERIT {
continue;
}
let top = match &frame.kind {
Kind::Cell(cell) => EntryAt::Cell(cell.id),
Kind::ListOp(list) => EntryAt::Cell(list.id),
Kind::Rule(rule) => EntryAt::Rule(rule.index),
Kind::RowScope(_) | Kind::ReadRow(_) | Kind::Settle(_) => match tops[frame.depth] {
EntryAt::Top => EntryAt::Row,
other => other,
},
};
tops[frame.depth] = top;
}
tops
}
#[cfg(feature = "call-graph-check")]
fn call_at<'p>(
frame: &Frame<'p>,
root_plan: &'p ExecutionPlan,
root: &mut EvaluationContext,
scopes: &mut [Scope<'p>],
) -> Option<crate::evaluation::CallAt> {
use crate::evaluation::CallAt;
match &frame.kind {
Kind::Rule(rule) => {
let (plan, ctx) = layer(frame.depth, root_plan, root, scopes);
Some(CallAt::In(
ctx.owner_row.clone(),
RowEnd::Rule(plan.rule_at(rule.index).path.clone()),
))
}
Kind::RowScope(scope) => {
let rule_of = |root_cell: NormalFormId| {
scope
.template
.rules
.values()
.find(|rule| rule.normal_form == root_cell)
.unwrap_or_else(|| panic!("BUG: a row settle's root is no rule of the row"))
.path
.clone()
};
match &scope.body {
RowBody::Rule(index) => Some(CallAt::In(
Some(scope.key.clone()),
RowEnd::Rule(scope.template.rule_at(*index).path.clone()),
)),
RowBody::Leaf(cell) => {
let NormalFormKind::Leaf(LeafKind::DataPath(path)) =
&scope.template.normal_form(*cell).kind
else {
panic!("BUG: a row's leaf body is not a data leaf");
};
Some(CallAt::In(
Some(scope.key.clone()),
RowEnd::Data(path.clone()),
))
}
RowBody::Settle(root_cell) => {
Some(CallAt::Settle(scope.key.clone(), rule_of(*root_cell)))
}
RowBody::Materialize => Some(CallAt::Materialize(scope.key.clone())),
RowBody::Member(_) | RowBody::Nothing => None,
}
}
Kind::Cell(_) | Kind::ReadRow(_) | Kind::ListOp(_) | Kind::Settle(_) => None,
}
}
#[cfg(feature = "call-graph-check")]
fn place_piece<'p>(
child: &mut Frame<'p>,
spawner: Option<&Frame<'p>>,
root_plan: &'p ExecutionPlan,
root: &mut EvaluationContext,
scopes: &mut [Scope<'p>],
) {
let (caller, nesting) = match spawner {
Some(frame) => (frame.piece.clone(), frame.nesting),
None => (None, 0),
};
child.piece = caller.clone();
child.nesting = nesting;
if let Kind::Rule(rule) = &child.kind {
let (_, ctx) = layer(child.depth, root_plan, &mut *root, &mut *scopes);
if ctx.rule_values[rule.index.index()].is_some() {
return;
}
}
if let Kind::RowScope(RowScopeFrame {
key,
body: RowBody::Rule(index),
..
}) = &child.kind
{
let open = scopes
.iter()
.find(|scope| scope.ctx.owner_row.as_ref() == Some(key))
.map(|scope| scope.ctx.rule_values[index.index()].is_some());
let evaluated = open.unwrap_or_else(|| {
root.caches
.row_contexts
.borrow()
.get(key)
.is_some_and(|ctx| ctx.rule_values[index.index()].is_some())
});
if evaluated {
return;
}
}
let Some(started) = call_at(child, root_plan, &mut *root, &mut *scopes) else {
return;
};
if matches!(child.kind, Kind::Rule(_)) && caller.as_deref() == Some(&started) {
return;
}
if started.in_planned_rows() {
child.nesting += 1;
}
let started = std::rc::Rc::new(started);
root.caches
.call_log
.borrow_mut()
.push(crate::evaluation::CallStart {
caller,
started: std::rc::Rc::clone(&started),
nesting: child.nesting,
});
child.piece = Some(started);
}
fn layer<'a, 'p>(
depth: usize,
root_plan: &'p ExecutionPlan,
root: &'a mut EvaluationContext,
scopes: &'a mut [Scope<'p>],
) -> (&'p ExecutionPlan, &'a mut EvaluationContext) {
if depth == 0 {
return (root_plan, root);
}
let scope = scopes
.get_mut(depth - 1)
.expect("BUG: frame holds a scope that already left");
(scope.plan, &mut scope.ctx)
}
enum DeferredOwner {
Layer(usize),
Cached,
}
fn deferred_owner(
owner: Option<&InstanceKey>,
depth: usize,
root: &EvaluationContext,
scopes: &[Scope],
) -> DeferredOwner {
let Some(owner_row) = owner else {
return DeferredOwner::Layer(0);
};
let current = if depth == 0 {
&root.owner_row
} else {
&scopes
.get(depth - 1)
.expect("BUG: frame holds a scope that already left")
.ctx
.owner_row
};
if current.as_ref() == Some(owner_row) {
return DeferredOwner::Layer(depth);
}
if let Some(position) = scopes
.iter()
.position(|scope| scope.ctx.owner_row.as_ref() == Some(owner_row))
{
return DeferredOwner::Layer(position + 1);
}
DeferredOwner::Cached
}
fn complete<'p>(
frame: Frame<'p>,
value: Delivered,
stored: bool,
frames: &mut Vec<Frame<'p>>,
walks: &mut Vec<WalkDone>,
) -> Option<Delivered> {
if frame.owns_walk {
walks.pop().expect("BUG: owned walk memo missing");
}
let Some(parent) = frames.last_mut() else {
return Some(value);
};
match &frame.kind {
Kind::Cell(cell) if !frame.owns_walk => {
let result = value.expect("BUG: cell finished without a value");
if !stored {
walks[frame.walk].insert(cell.id, result);
}
}
_ => parent.inbox = value,
}
None
}
fn step<'p>(
frame: &mut Frame<'p>,
root_plan: &'p ExecutionPlan,
root: &mut EvaluationContext,
scopes: &mut Vec<Scope<'p>>,
walks: &[WalkDone],
) -> Outcome<'p> {
let inbox = frame.inbox.take();
let walk = frame.walk;
if let Kind::RowScope(scope) = &mut frame.kind {
return step_row_scope(scope, inbox, frame.depth, root_plan, root, scopes);
}
if let Kind::ReadRow(read) = &mut frame.kind {
return step_read_row(read, inbox, frame.depth, root_plan, root, scopes);
}
let (plan, ctx) = layer(frame.depth, root_plan, root, scopes);
match &mut frame.kind {
Kind::Cell(cell) => step_cell(cell, inbox, &walks[walk], plan, ctx),
Kind::Rule(rule) => step_rule(rule, inbox, plan, ctx),
Kind::ReadRow(_) => unreachable!("BUG: row read frame stepped outside its arm"),
Kind::ListOp(list) => step_list_op(list, inbox, plan, ctx),
Kind::Settle(settle) => step_settle(settle, plan, ctx),
Kind::RowScope(_) => unreachable!("BUG: row scope frame stepped outside its arm"),
}
}
fn step_rule<'p>(
frame: &mut RuleFrame,
inbox: Delivered,
plan: &'p ExecutionPlan,
ctx: &mut EvaluationContext,
) -> Outcome<'p> {
let index = frame.index;
let rule = plan.rule_at(index);
if frame.body_spawned {
let value = inbox.expect("BUG: rule body finished without a value");
if let Some(rows) = frame.saved_rows.take() {
ctx.row_stack = rows;
}
ctx.rule_values[index.index()] = Some(value.held_as(&rule.rule_type));
return Outcome::Finish(None);
}
if ctx.rule_values[index.index()].is_some() {
return Outcome::Finish(None);
}
if frame.saved_rows.is_none() {
frame.saved_rows = Some(std::mem::take(&mut ctx.row_stack));
}
while let Some(target) = rule.scale_dependencies.get(frame.scale_cursor) {
frame.scale_cursor += 1;
if let Some(force) = unforced_target(target, plan, ctx) {
let (child, mode) = force_frame(force, plan, ctx);
return spawn(child, mode);
}
}
frame.body_spawned = true;
spawn(Frame::cell(rule.normal_form), WalkMode::New)
}
fn step_settle<'p>(
frame: &mut SettleFrame,
plan: &'p ExecutionPlan,
ctx: &mut EvaluationContext,
) -> Outcome<'p> {
let filled = |work: LiveWork, ctx: &EvaluationContext| match work {
LiveWork::Cell(id) => ctx.values[id.index()].is_some(),
LiveWork::Rule(index) => ctx.rule_values[index.index()].is_some(),
};
if let Some(work) = frame.forced.take() {
assert!(
filled(work, ctx),
"BUG: settled live work {work:?} left its slot empty"
);
}
loop {
while let Some(work) = frame.pending.pop() {
if filled(work, ctx) {
continue;
}
frame.forced = Some(work);
return match work {
LiveWork::Cell(id) => spawn(Frame::cell(id), WalkMode::New),
LiveWork::Rule(index) => spawn(Frame::rule(index), WalkMode::Same),
};
}
let mut round = unsettled_live_work(plan, frame.root, &ctx.values);
if round.is_empty() {
return Outcome::Finish(None);
}
round.reverse();
frame.pending = round;
}
}
fn row_scope_read_slots(frame: &RowScopeFrame, caches: &RequestCaches) -> Vec<DataPath> {
let template = frame.template;
match &frame.body {
RowBody::Nothing | RowBody::Settle(_) => Vec::new(),
RowBody::Materialize => {
let mut slots: Vec<DataPath> = Vec::new();
let mut push = |slot: DataPath| {
if !slots.contains(&slot) {
slots.push(slot);
}
};
for slot in 0..frame.key.row.bindings.len() {
if caches.binding(&frame.key, template, slot).is_some() {
let (path, _) = template
.data
.get_index(slot)
.expect("BUG: row binding slot is template data");
push(path.clone());
}
}
let mut index = 0;
while let Some(target) = row_body_scale_target(template, &frame.body, index) {
index += 1;
let end = match &target.target {
ReferenceTarget::Data(path) if path.segments.is_empty() => {
RowEnd::Data(path.clone())
}
ReferenceTarget::Rule(rule) if rule.segments.is_empty() => {
RowEnd::Rule(rule.clone())
}
ReferenceTarget::Data(_) | ReferenceTarget::Rule(_) => continue,
};
for read in template.row_end_reads(&end) {
push(read.slot);
}
}
slots
}
RowBody::Rule(index) => {
template.row_read_slots(&RowEnd::Rule(template.rule_at(*index).path.clone()))
}
RowBody::Leaf(id) => {
template.row_read_slots(&RowEnd::Data(row_leaf_path(template, *id).clone()))
}
RowBody::Member(id) => {
assert!(
matches!(
template.normal_form(*id).kind,
NormalFormKind::SpecMember { .. }
),
"BUG: a row member body is a member read"
);
Vec::new()
}
}
}
fn row_leaf_path(template: &ExecutionPlan, id: NormalFormId) -> &DataPath {
match &template.normal_form(id).kind {
NormalFormKind::Leaf(LeafKind::DataPath(path)) => path,
other => panic!("BUG: a row leaf body is a data leaf, got {other:?}"),
}
}
fn row_body_scale_target<'t>(
template: &'t ExecutionPlan,
body: &RowBody,
index: usize,
) -> Option<&'t ScaleTarget> {
match body {
RowBody::Nothing | RowBody::Settle(_) => None,
RowBody::Materialize => template.slot_scale_targets.iter().flatten().nth(index),
RowBody::Rule(rule) => template.rule_at(*rule).scale_dependencies.get(index),
RowBody::Leaf(id) => template
.data_scale_targets(row_leaf_path(template, *id))
.get(index),
RowBody::Member(_) => None,
}
}
fn force_frame<'p>(
force: RowBody,
plan: &'p ExecutionPlan,
ctx: &EvaluationContext,
) -> (Frame<'p>, WalkMode) {
match force {
RowBody::Member(cell) => (Frame::cell(cell), WalkMode::New),
RowBody::Rule(index) if ctx.owner_row.is_none() => (Frame::rule(index), WalkMode::Same),
body => {
let row = ctx
.owner_row
.clone()
.expect("BUG: only a row has a slot a read of it resolves");
(Frame::row_scope(row, plan, body), WalkMode::Same)
}
}
}
fn unforced_deferred_in_values(
values: &[OperationResult],
plan: &ExecutionPlan,
ctx: &EvaluationContext,
) -> Vec<RowBody> {
let rows = values
.iter()
.filter_map(OperationResult::value)
.flat_map(|bound| value_rows(&bound.value))
.collect();
unforced_deferred_targets(rows, true, plan, ctx)
.into_iter()
.map(|(_, force)| force)
.collect()
}
#[derive(Clone, PartialEq, Eq)]
enum ForceAt {
Here,
Row(InstanceKey),
}
fn unforced_deferred_targets(
rows: Vec<InstanceKey>,
owned_only: bool,
plan: &ExecutionPlan,
ctx: &EvaluationContext,
) -> Vec<(ForceAt, RowBody)> {
let mut pending = Vec::new();
let mut stack = rows;
stack.reverse();
while let Some(key) = stack.pop() {
let mut held = Vec::new();
let template = plan.row_template(&key.row.identity);
for field in
(0..key.row.bindings.len()).filter_map(|slot| ctx.caches.field(&key, template, slot))
{
match &*field.binding {
RowBinding::Deferred { target } => {
let owner = field.resolves_in.as_deref();
let unforced = if owner == ctx.owner_row.as_ref() {
unforced_reference(target, plan, ctx).map(|force| (ForceAt::Here, force))
} else if owned_only {
None
} else {
owner.and_then(|owner| {
let contexts = ctx.caches.row_contexts.borrow();
let owner_ctx = contexts.get(owner)?;
let owner_plan = plan.row_template(&owner.row.identity);
unforced_reference(target, owner_plan, owner_ctx)
.map(|force| (ForceAt::Row(owner.clone()), force))
})
};
if let Some(force) = unforced {
if !pending.contains(&force) {
pending.push(force);
}
}
}
RowBinding::Bound(value) => {
if let OperationResult::Value(bound) = value.clone() {
held.extend(value_rows(&bound.value));
}
}
}
}
stack.extend(held.into_iter().rev());
}
pending
}
fn copied_in(
target: &ReferenceTarget,
plan: &ExecutionPlan,
ctx: &EvaluationContext,
template: &ExecutionPlan,
path: &DataPath,
holder: &InstanceKey,
) -> OperationResult {
let value = copied_value(target, plan, ctx, template, path);
match template.instance_lists.get(path) {
Some(list) => lookup::rows_copied_into(value, holder, path, list, template, &ctx.caches),
None => value,
}
}
fn copied_value(
target: &ReferenceTarget,
plan: &ExecutionPlan,
ctx: &EvaluationContext,
template: &ExecutionPlan,
path: &DataPath,
) -> OperationResult {
let receiving = template
.data
.get(path)
.and_then(|definition| definition.schema_type())
.expect("BUG: a bound row field is typed template data");
if let ReferenceTarget::Data(path) = target {
if let Some((held, bound)) = crate::evaluation::compute::bounded_unscaled(path, plan, ctx) {
let held_type = plan
.data
.get(held)
.and_then(|definition| definition.schema_type())
.expect("BUG: data holding a value in a unit is typed");
if let veto @ OperationResult::Veto(_) =
crate::evaluation::compute::settle_stored(bound.clone(), held_type, plan, ctx)
{
return veto;
}
}
}
lookup::as_written(
resolve_stored_target(target, plan, ctx),
receiving,
|bound, unit| {
let source_type: &LemmaType = match target {
ReferenceTarget::Data(path) => plan.data.get(path)?.schema_type()?,
ReferenceTarget::Rule(rule) => plan.rules.get(rule)?.rule_type.as_ref(),
};
crate::evaluation::compute::display_scale_factors(Some(bound), source_type, plan, ctx)
.get(unit)
.cloned()
},
)
}
fn value_rows(value: &ValueKind) -> Vec<InstanceKey> {
fn row(value: &ValueKind) -> Option<InstanceKey> {
match value {
ValueKind::Spec(SpecValue::Row(key)) => Some(key.clone()),
_ => None,
}
}
match value {
ValueKind::List(items) => match items.stored() {
Some(stored) => stored
.rows
.iter()
.map(|row| InstanceKey::new(Arc::clone(row), stored.owner.cloned()))
.collect(),
None => items
.values()
.iter()
.filter_map(|item| row(&item.value))
.collect(),
},
other => row(other).into_iter().collect(),
}
}
fn step_row_scope<'p>(
frame: &mut RowScopeFrame<'p>,
mut inbox: Delivered,
depth: usize,
root_plan: &'p ExecutionPlan,
root: &mut EvaluationContext,
scopes: &mut Vec<Scope<'p>>,
) -> Outcome<'p> {
loop {
match &mut frame.phase {
RowPhase::Acquire => {
frame.read_slots = row_scope_read_slots(frame, &root.caches);
frame.phase = RowPhase::Resolve(0);
}
RowPhase::Resolve(cursor) => {
let caches = std::rc::Rc::clone(&root.caches);
while let Some(slot) = frame.read_slots.get(*cursor) {
let field = frame
.template
.data
.get_index_of(slot)
.and_then(|index| caches.field(&frame.key, frame.template, index));
let Some(field) = field else {
*cursor += 1;
continue;
};
let RowBinding::Deferred { target } = &*field.binding else {
*cursor += 1;
continue;
};
let owner_key = field.resolves_in.as_deref();
match deferred_owner(owner_key, depth, root, scopes) {
DeferredOwner::Layer(owner_depth) => {
let (oplan, octx) =
layer(owner_depth, root_plan, &mut *root, &mut *scopes);
if let Some(force) = unforced_reference(target, oplan, octx) {
#[cfg(test)]
let forced = matches!(force, RowBody::Member(_));
let (mut child, mode) = force_frame(force, oplan, octx);
child.depth = owner_depth;
#[cfg(test)]
{
child.forced = forced;
}
return spawn(child, mode);
}
}
DeferredOwner::Cached => {
let owner_key =
owner_key.expect("BUG: cached deferred owner without a row");
let oplan = root_plan.row_template(&owner_key.row.identity);
let force = {
let contexts = root.caches.row_contexts.borrow();
let octx = contexts.get(owner_key).expect(
"BUG: deferred owner row's context missing from the cache",
);
unforced_reference(target, oplan, octx)
};
if let Some(force) = force {
return spawn(
Frame::row_scope(owner_key.clone(), oplan, force),
WalkMode::Same,
);
}
}
}
*cursor += 1;
}
let mut resolved: Vec<(DataPath, OperationResult)> = Vec::new();
let caches = std::rc::Rc::clone(&root.caches);
for slot_idx in 0..frame.key.row.bindings.len() {
let Some(field) = caches.field(&frame.key, frame.template, slot_idx) else {
continue;
};
let RowBinding::Deferred { target } = &*field.binding else {
continue;
};
let owner_key = field.resolves_in.as_deref();
let (path, _) = frame
.template
.data
.get_index(slot_idx)
.expect("BUG: row binding slot is template data");
match deferred_owner(owner_key, depth, root, scopes) {
DeferredOwner::Layer(owner_depth) => {
let (oplan, octx) =
layer(owner_depth, root_plan, &mut *root, &mut *scopes);
if frame.read_slots.contains(path)
|| unforced_reference(target, oplan, octx).is_none()
{
resolved.push((
path.clone(),
rows::checked_deferred_field(
&frame.key,
frame.template,
path,
rows::owner_result(
copied_in(
target,
oplan,
octx,
frame.template,
path,
&frame.key,
),
owner_key,
oplan,
&caches,
),
),
));
}
}
DeferredOwner::Cached => {
let owner_key =
owner_key.expect("BUG: cached deferred owner without a row");
let oplan = root_plan.row_template(&owner_key.row.identity);
let contexts = root.caches.row_contexts.borrow();
let octx = contexts
.get(owner_key)
.expect("BUG: deferred owner row's context missing from the cache");
if frame.read_slots.contains(path)
|| unforced_reference(target, oplan, octx).is_none()
{
resolved.push((
path.clone(),
rows::checked_deferred_field(
&frame.key,
frame.template,
path,
rows::owner_result(
copied_in(
target,
oplan,
octx,
frame.template,
path,
&frame.key,
),
Some(owner_key),
oplan,
&caches,
),
),
));
}
}
}
}
let template = frame.template;
if let Some(open) = open_row_depth(&frame.key, scopes) {
let (_, octx) = layer(open, root_plan, &mut *root, &mut *scopes);
let key = &frame.key;
octx.bind_resolved_slots(template, resolved, |slot| {
caches.binding(key, template, slot).is_some()
});
frame.phase = RowPhase::Open(open);
continue;
}
let (_, ctx) = layer(depth, root_plan, &mut *root, &mut *scopes);
if let Some(mut cached) =
ctx.caches.row_contexts.borrow_mut().swap_remove(&frame.key)
{
let key = &frame.key;
cached.bind_resolved_slots(template, resolved, |slot| {
caches.binding(key, template, slot).is_some()
});
cached.owner_row = Some(frame.key.clone());
frame.phase = RowPhase::Body;
return Outcome::Enter(Scope {
plan: template,
ctx: cached,
});
}
let bindings: Vec<(usize, OperationResult)> = (0..frame.key.row.bindings.len())
.filter_map(|slot_idx| {
let binding = ctx.caches.binding(&frame.key, template, slot_idx)?;
let value = match &*binding {
RowBinding::Bound(value) => lookup::owned_by(value, &frame.key),
RowBinding::Deferred { .. } => {
let (path, _) = template
.data
.get_index(slot_idx)
.expect("BUG: row binding slot is template data");
resolved
.iter()
.find(|(slot, _)| slot == path)
.map(|(_, value)| value.clone())?
}
};
Some((slot_idx, value))
})
.collect();
let unbound: Vec<usize> = (0..frame.key.row.bindings.len())
.filter(|slot_idx| {
caches.binding(&frame.key, template, *slot_idx).is_some()
&& bindings
.binary_search_by_key(slot_idx, |(bound, _)| *bound)
.is_err()
})
.collect();
let children = rows::self_rows(&frame.key, template, &frame.read_slots, &bindings);
let mut fresh = ctx.child_row(template, &bindings, &unbound);
fresh.owner_row = Some(frame.key.clone());
frame.phase = if children.is_empty() {
RowPhase::Body
} else {
RowPhase::Children(children)
};
return Outcome::Enter(Scope {
plan: template,
ctx: fresh,
});
}
RowPhase::Children(children) => {
let Some(child) = children.pop() else {
frame.phase = RowPhase::Body;
continue;
};
let (_, ctx) = layer(depth, root_plan, &mut *root, &mut *scopes);
if ctx.caches.row_contexts.borrow().contains_key(&child) {
continue;
}
return spawn(
Frame::row_scope(child, frame.template, RowBody::Nothing),
WalkMode::Same,
);
}
RowPhase::Body => {
#[cfg(test)]
let at = root.frame_tops[depth];
let (_, ctx) = layer(depth, root_plan, &mut *root, &mut *scopes);
let template = frame.template;
#[cfg(test)]
if frame.scale_cursor == 0 {
ctx.log_body(&frame.body, at);
}
while let Some(target) =
row_body_scale_target(template, &frame.body, frame.scale_cursor)
{
frame.scale_cursor += 1;
if let Some(force) = unforced_target(target, template, ctx) {
let (child, mode) = force_frame(force, template, ctx);
return spawn(child, mode);
}
}
match &frame.body {
RowBody::Nothing => return Outcome::Exit(None, frame.key.clone()),
RowBody::Materialize => {
#[cfg(test)]
ctx.log_entry_end();
return Outcome::Exit(None, frame.key.clone());
}
RowBody::Rule(index) => match &ctx.rule_values[index.index()] {
Some(value) => {
return Outcome::Exit(Some(value.clone()), frame.key.clone());
}
None => return spawn(Frame::rule(*index), WalkMode::Same),
},
RowBody::Leaf(id) | RowBody::Member(id) => {
frame.phase = RowPhase::Await;
let child = Frame::cell(*id);
#[cfg(test)]
let child = Frame {
entry: true,
..child
};
return spawn(child, WalkMode::New);
}
RowBody::Settle(root) => {
frame.phase = RowPhase::AwaitSettle;
let child = Frame::settle(*root);
#[cfg(test)]
let child = Frame {
entry: true,
..child
};
return spawn(child, WalkMode::Same);
}
}
}
RowPhase::AwaitSettle => return Outcome::Exit(None, frame.key.clone()),
RowPhase::Await => {
let result = inbox
.take()
.expect("BUG: row scope resumed without its field value");
return Outcome::Exit(Some(result), frame.key.clone());
}
RowPhase::Open(open) => {
let open = *open;
#[cfg(test)]
let at = root.frame_tops[open];
let (_, octx) = layer(open, root_plan, &mut *root, &mut *scopes);
let template = frame.template;
#[cfg(test)]
if frame.scale_cursor == 0 {
octx.log_body(&frame.body, at);
}
while let Some(target) =
row_body_scale_target(template, &frame.body, frame.scale_cursor)
{
frame.scale_cursor += 1;
if let Some(force) = unforced_target(target, template, octx) {
let (mut child, mode) = force_frame(force, template, octx);
child.depth = open;
return spawn(child, mode);
}
}
match &frame.body {
RowBody::Nothing => return Outcome::Finish(None),
RowBody::Materialize => {
panic!(
"BUG: row '{}' materialized while its scope is open",
frame.key
)
}
RowBody::Rule(index) => match &octx.rule_values[index.index()] {
Some(value) => return Outcome::Finish(Some(value.clone())),
None => {
let mut child = Frame::rule(*index);
child.depth = open;
return spawn(child, WalkMode::Same);
}
},
RowBody::Leaf(id) | RowBody::Member(id) => {
frame.phase = RowPhase::OpenAwait;
let mut child = Frame::cell(*id);
child.depth = open;
#[cfg(test)]
{
child.entry = true;
}
return spawn(child, WalkMode::New);
}
RowBody::Settle(root) => {
frame.phase = RowPhase::OpenAwaitSettle;
let mut child = Frame::settle(*root);
child.depth = open;
#[cfg(test)]
{
child.entry = true;
}
return spawn(child, WalkMode::Same);
}
}
}
RowPhase::OpenAwaitSettle => return Outcome::Finish(None),
RowPhase::OpenAwait => {
let result = inbox
.take()
.expect("BUG: open row read resumed without its field value");
return Outcome::Finish(Some(result));
}
}
}
}
fn data_row_body(template: &ExecutionPlan, path: &DataPath) -> (RowBody, Option<NormalFormId>) {
match template.reference_ends.get(path) {
Some(ReferenceEnd::Rule(rule)) => {
let executable = template
.rules
.get(rule)
.expect("BUG: row reference rule missing from its template");
(
RowBody::Rule(template.rule_index(rule)),
Some(executable.normal_form),
)
}
Some(ReferenceEnd::Promptable(_)) | None => (
RowBody::Leaf(
*template
.data_leaf
.get(path)
.expect("BUG: row data end has no data_leaf entry in its template"),
),
None,
),
}
}
fn step_read_row<'p>(
frame: &mut ReadRowFrame,
inbox: Delivered,
depth: usize,
root_plan: &'p ExecutionPlan,
root: &mut EvaluationContext,
scopes: &mut [Scope<'p>],
) -> Outcome<'p> {
let (plan, _) = layer(depth, root_plan, &mut *root, &mut *scopes);
let template = plan.row_template(&frame.key.row.identity);
let (inbox, settled) = match frame.settling.take() {
Some(raw) => {
assert!(inbox.is_none(), "BUG: a row settle delivered a value");
(Some(raw), true)
}
None => (inbox, false),
};
let Some(raw) = inbox else {
let (body, rule_root) = match &frame.end {
RowEnd::Rule(rule) => {
let executable = template
.rules
.get(rule)
.expect("BUG: row rule end missing from its template");
(
RowBody::Rule(template.rule_index(rule)),
Some(executable.normal_form),
)
}
RowEnd::Data(path) => {
let slot = template
.data
.get_index_of(path)
.expect("BUG: row data end is template data");
let bound = match root.caches.binding(&frame.key, template, slot).as_deref() {
Some(RowBinding::Bound(value)) => Some(lookup::owned_by(value, &frame.key)),
Some(RowBinding::Deferred { .. }) | None => None,
};
if let Some(value) = bound {
let needs_options = template
.data
.get(path)
.and_then(|definition| definition.schema_type())
.is_some_and(|schema| schema.needs_runtime_option_check());
let unscaled = value
.value()
.is_some_and(|bound| bound.value.has_unscaled_measure());
let result_type = row_end_type(template, &frame.end);
let factors = with_row_context(&frame.key, root, scopes, |row_ctx| {
template
.data_scale_targets(path)
.iter()
.all(|target| unforced_target(target, template, row_ctx).is_none())
.then(|| instance_factors(&result_type, template, row_ctx))
})
.flatten();
if let (false, false, Some(factors)) = (needs_options, unscaled, factors) {
let (_, ctx) = layer(depth, root_plan, &mut *root, &mut *scopes);
let result = with_instance_factors(
rows::from_row(value, &frame.key, template, ctx),
factors,
);
if ctx.exhaustive {
ctx.row_reads_log.push(RowRead {
row: frame.read.clone(),
end: frame.end.clone(),
result: result.clone(),
result_type,
});
}
return Outcome::Finish(Some(result));
}
}
data_row_body(template, path)
}
};
frame.rule_root = rule_root;
return spawn(
Frame::row_scope(frame.key.clone(), template, body),
WalkMode::Same,
);
};
if let (Some(rule_root), false, true) = (frame.rule_root, settled, raw.is_missing_data()) {
frame.settling = Some(raw);
return spawn(
Frame::row_scope(frame.key.clone(), template, RowBody::Settle(rule_root)),
WalkMode::Same,
);
}
let result_type = row_end_type(template, &frame.end);
let (missing, factors) = with_row_context(&frame.key, root, scopes, |row_ctx| {
let missing = match frame.rule_root {
Some(rule_root) if raw.is_missing_data() => {
row_ctx.missing_data_for_rule(template, rule_root, Some(&frame.key))
}
_ => Vec::new(),
};
(missing, instance_factors(&result_type, template, row_ctx))
})
.unwrap_or_else(|| panic!("BUG: row context missing after its read ({})", frame.key));
let (_, ctx) = layer(depth, root_plan, &mut *root, &mut *scopes);
ctx.missing_row_keys.extend(missing);
let result = with_instance_factors(rows::from_row(raw, &frame.key, template, ctx), factors);
if ctx.exhaustive {
ctx.row_reads_log.push(RowRead {
row: frame.read.clone(),
end: frame.end.clone(),
result: result.clone(),
result_type,
});
}
Outcome::Finish(Some(result))
}
fn instance_factors(
result_type: &LemmaType,
template: &ExecutionPlan,
row_ctx: &EvaluationContext,
) -> Option<Arc<InstanceFactors>> {
if !result_type.is_measure() && !result_type.is_measure_range() {
return None;
}
let (factors, unsettled) = runtime_scales_for(result_type, template, row_ctx);
if factors.is_empty() && unsettled.is_empty() {
return None;
}
Some(Arc::new(InstanceFactors::new(
factors.into_iter().collect(),
unsettled,
)))
}
fn with_instance_factors(
result: OperationResult,
factors: Option<Arc<InstanceFactors>>,
) -> OperationResult {
let OperationResult::Value(mut bound) = result else {
return result;
};
bound.instance_factors = match (factors, bound.instance_factors.take()) {
(Some(row), Some(carried)) => Some(Arc::new(row.over(&carried))),
(row, carried) => row.or(carried),
};
OperationResult::from_bound(bound)
}
fn open_row_depth(key: &InstanceKey, scopes: &[Scope]) -> Option<usize> {
scopes
.iter()
.position(|scope| scope.ctx.owner_row.as_ref() == Some(key))
.map(|position| position + 1)
}
fn with_row_context<R>(
key: &InstanceKey,
root: &EvaluationContext,
scopes: &[Scope],
read: impl FnOnce(&EvaluationContext) -> R,
) -> Option<R> {
if let Some(depth) = open_row_depth(key, scopes) {
return Some(read(&scopes[depth - 1].ctx));
}
let contexts = root.caches.row_contexts.borrow();
contexts.get(key).map(read)
}
fn unforced_row_scale<'p>(
id: NormalFormId,
plan: &'p ExecutionPlan,
ctx: &mut EvaluationContext,
) -> Option<Outcome<'p>> {
if ctx.row_stack.is_empty() {
return None;
}
for target in plan.written_scale_targets(id) {
let Some((key, template)) = bare_target_row(&target, plan, ctx) else {
continue;
};
if ctx.owner_row.as_ref() == Some(key) {
if let Some(force) = unforced_target(&target, template, ctx) {
#[cfg(test)]
let forced = matches!(force, RowBody::Member(_));
let (child, mode) = force_frame(force, template, ctx);
#[cfg(test)]
let child = Frame { forced, ..child };
return Some(spawn(child, mode));
}
continue;
}
let force = {
let caches = ctx.caches.row_contexts.borrow();
let row_ctx = caches.get(key).unwrap_or_else(|| {
panic!(
"BUG: bare scale target '{target}' of a per-row literal before the row context was built; list per-row paths must spawn an empty RowScope first"
)
});
unforced_target(&target, template, row_ctx)
};
if let Some(force) = force {
return Some(spawn(
Frame::row_scope(key.clone(), template, force),
WalkMode::Same,
));
}
}
None
}
fn empty_sum_scale_veto(
result_type: &LemmaType,
plan: &ExecutionPlan,
ctx: &EvaluationContext,
) -> Option<OperationResult> {
if !result_type.is_measure() {
return None;
}
let unit = result_type
.measure_fallback_unit()
.filter(|unit| unit.is_dynamic())?;
let factors = result_type.unit_scale_factors(&unit.name);
if factors.is_empty() {
panic!(
"BUG: dynamic unit '{}' on '{}' has no scale factors",
unit.name,
result_type.name()
);
}
for (target, _) in factors {
assert!(
unforced_target(target, plan, ctx).is_none(),
"BUG: scale of unit '{}' on '{}' read before its scale dependency was evaluated",
unit.name,
result_type.name()
);
}
composed_unit_scale_factor(unit, plan, ctx).err()
}
fn inline_row_binding(
key: &InstanceKey,
position: Option<usize>,
end: &RowEnd,
plan: &ExecutionPlan,
ctx: &mut EvaluationContext,
) -> Option<OperationResult> {
let row = &key.row;
if !row.origin.is_inline() {
return None;
}
let RowEnd::Data(path) = end else {
return None;
};
let template = plan.row_template(&row.identity);
let value = match row.get_binding(template, path)? {
RowBinding::Bound(value) => value,
RowBinding::Deferred { .. } => {
unreachable!("BUG: an inline `-> with` row binds command values")
}
};
if !template.data_scale_targets(path).is_empty() {
return None;
}
if ctx.exhaustive {
ctx.row_reads_log.push(RowRead {
row: rows::ReadRow {
key: key.clone(),
position,
},
end: end.clone(),
result: value.clone(),
result_type: row_end_type(template, end),
});
}
Some(value.clone())
}
fn current_instance_row(row: &TypedLiteral, position: usize) -> CurrentRow {
match &row.value {
ValueKind::Spec(SpecValue::Row(key)) => CurrentRow::Instance {
key: key.clone(),
position,
},
other => panic!("BUG: instance list row is {other:?}, not a row"),
}
}
fn key_field_read(
plan: &ExecutionPlan,
row: &TypedLiteral,
key_field: &KeyField,
) -> (InstanceKey, RowEnd, Arc<LemmaType>) {
match &row.value {
ValueKind::Spec(SpecValue::Row(key)) => {
let (end, field_type) = list_ops::key_field_type(plan, &key.row, key_field);
(key.clone(), end, field_type)
}
other => panic!("BUG: instance list row is {other:?}, not a row"),
}
}
fn step_list_op<'p>(
frame: &mut ListOpFrame<'p>,
mut inbox: Delivered,
plan: &'p ExecutionPlan,
ctx: &mut EvaluationContext,
) -> Outcome<'p> {
let op = frame.op;
let result_type = frame.result_type;
loop {
match std::mem::replace(&mut frame.state, ListState::Start) {
ListState::Start => {
frame.state = ListState::AwaitList;
return spawn(Frame::cell(frame.list), WalkMode::New);
}
ListState::AwaitList => {
let list_value = inbox
.take()
.expect("BUG: list command resumed without its list value");
let bound = match list_value {
OperationResult::Value(bound) => bound,
veto => return Outcome::Finish(Some(veto)),
};
let ValueKind::List(rows) = &bound.value else {
panic!(
"BUG: list command operand is not a list (type {})",
plan.normal_form(frame.list).result_type.name()
);
};
let data = ListData {
rows: rows.clone(),
unit: bound.unit.clone(),
};
let key_fields = match frame.row_level {
Some(_) => match list_ops::list_key(plan.result_type(frame.list)) {
ListKey::Fields(fields) => Some(fields.clone()),
ListKey::Numbered => None,
},
None => None,
};
match (frame.row_level, op) {
(_, NormalFormListOp::Count) => {
return Outcome::Finish(Some(list_ops::count_rows(&data.rows)));
}
(_, NormalFormListOp::First) => {
return Outcome::Finish(Some(list_ops::first_or_last(&data.rows, true)));
}
(_, NormalFormListOp::Last) => {
return Outcome::Finish(Some(list_ops::first_or_last(&data.rows, false)));
}
(None, NormalFormListOp::Sum) => {
if data.rows.is_empty() {
if let Some(veto) = empty_sum_scale_veto(result_type, plan, ctx) {
return Outcome::Finish(Some(veto));
}
}
return Outcome::Finish(Some(list_ops::reduce_typed(
data.rows.values(),
ListFold::Sum,
result_type,
plan,
)));
}
(None, NormalFormListOp::Product) => {
return Outcome::Finish(Some(list_ops::reduce_typed(
data.rows.values(),
ListFold::Product,
result_type,
plan,
)));
}
(None, NormalFormListOp::Avg) => {
return Outcome::Finish(Some(list_ops::reduce_typed(
data.rows.values(),
ListFold::Avg,
result_type,
plan,
)));
}
(None, NormalFormListOp::Min) => {
return Outcome::Finish(Some(list_ops::extrema(
data.rows.values(),
Ordering::Less,
)));
}
(None, NormalFormListOp::Max) => {
return Outcome::Finish(Some(list_ops::extrema(
data.rows.values(),
Ordering::Greater,
)));
}
(None, NormalFormListOp::Sort { descending }) => {
return Outcome::Finish(Some(list_ops::sort_rows(
data.rows.values(),
*descending,
data.unit.clone(),
)));
}
(Some(_), NormalFormListOp::Key { .. }) => {
let ListKey::Fields(fields) =
list_ops::list_key(plan.result_type(frame.id))
else {
unreachable!("BUG: `-> key` result type is keyed by fields");
};
frame.state = ListState::Scan(KeyScan {
rows: data.rows,
fields: fields.clone(),
row: 0,
field: 0,
key: Vec::new(),
keyed: Vec::new(),
then: ScanThen::List(data.unit),
});
}
(None, NormalFormListOp::Key { .. }) => {
unreachable!("BUG: planning rejects `-> key` on value lists")
}
(None, NormalFormListOp::With) | (Some(_), NormalFormListOp::With) => {
let count = frame.args.len();
frame.state = ListState::Args {
data,
values: Vec::new(),
count,
key_fields,
};
}
(None, NormalFormListOp::Find)
| (None, NormalFormListOp::Top)
| (Some(_), NormalFormListOp::Top) => {
frame.state = ListState::Args {
data,
values: Vec::new(),
count: 1,
key_fields: None,
};
}
(Some(_), NormalFormListOp::Find) => {
let count = if key_fields.is_some() {
frame.args.len()
} else {
1
};
frame.state = ListState::Args {
data,
values: Vec::new(),
count,
key_fields,
};
}
(Some(_), NormalFormListOp::WithRow { .. }) => {
let count = frame.args.len();
frame.state = ListState::Args {
data,
values: Vec::new(),
count,
key_fields,
};
}
(Some(_), NormalFormListOp::Sum)
| (Some(_), NormalFormListOp::Product)
| (Some(_), NormalFormListOp::Avg)
| (Some(_), NormalFormListOp::Min)
| (Some(_), NormalFormListOp::Max)
| (Some(_), NormalFormListOp::Sort { .. })
| (Some(_), NormalFormListOp::Predicate { .. }) => {
frame.state = ListState::PerRow {
data,
cursor: 0,
values: Vec::new(),
first_veto: None,
};
}
(None, NormalFormListOp::Predicate { .. })
| (None, NormalFormListOp::WithRow { .. }) => {
unreachable!("BUG: row command {op:?} has no row level")
}
}
}
ListState::Args {
data,
mut values,
count,
key_fields,
} => {
if let Some(value) = inbox.take() {
if !matches!(value, OperationResult::Value(_)) {
return Outcome::Finish(Some(value));
}
values.push(value);
}
if values.len() < count {
let arg = frame.args[values.len()];
frame.state = ListState::Args {
data,
values,
count,
key_fields,
};
return spawn(Frame::cell(arg), WalkMode::New);
}
match (frame.row_level, op) {
(_, NormalFormListOp::Top) => {
return Outcome::Finish(Some(list_ops::top_rows(
&data.rows,
first_operand(&values),
data.unit.clone(),
)));
}
(None, NormalFormListOp::Find) => {
return Outcome::Finish(Some(list_ops::find_numbered(
&data.rows,
first_operand(&values),
)));
}
(Some(_), NormalFormListOp::Find) => match key_fields {
None => {
return Outcome::Finish(Some(list_ops::find_numbered(
&data.rows,
first_operand(&values),
)));
}
Some(fields) => {
let wanted: Vec<TypedLiteral> = values
.into_iter()
.zip(frame.args)
.map(|(value, arg)| {
list_ops::typed_operand(value, plan.result_type(*arg))
})
.collect();
if let Some(index) = data.rows.index().filter(|index| {
index
.fields
.iter()
.eq(fields.iter().map(|field| &field.name))
}) {
return Outcome::Finish(Some(find_keyed(
&data.rows, index, &fields, &wanted,
)));
}
frame.state = ListState::Scan(KeyScan {
rows: data.rows,
fields,
row: 0,
field: 0,
key: Vec::new(),
keyed: Vec::new(),
then: ScanThen::Find(wanted),
});
}
},
(None, NormalFormListOp::With) => {
return Outcome::Finish(Some(list_ops::append_values(
data.rows.values(),
values,
frame.args,
plan,
data.unit.clone(),
)));
}
(Some(_), NormalFormListOp::With) => {
let appended = list_ops::append_instance_operands(
&data.rows,
values,
plan.result_type(frame.list),
data.unit.clone(),
);
match key_fields {
None => return Outcome::Finish(Some(appended)),
Some(fields) => {
let OperationResult::Value(bound) = appended else {
return Outcome::Finish(Some(appended));
};
let ValueKind::List(rows) = bound.value else {
unreachable!("BUG: append_instance_operands returned non-list");
};
frame.state = ListState::Scan(KeyScan {
rows,
fields,
row: 0,
field: 0,
key: Vec::new(),
keyed: Vec::new(),
then: ScanThen::List(bound.unit),
});
}
}
}
(
Some(_),
NormalFormListOp::WithRow {
identity,
fields: append_fields,
},
) => {
let pending = unforced_deferred_in_values(&values, plan, ctx);
if !pending.is_empty() {
frame.state = ListState::InlineDeferred {
data,
values,
count,
key_fields,
pending: pending.into_iter(),
};
continue;
}
let inline = list_ops::inline_row(
plan,
identity,
append_fields,
values,
RowOrigin::Inline {
node: frame.id,
position: data.rows.len() + 1,
},
);
let mut rows = data.rows.to_vec();
rows.push(inline);
match key_fields {
None => {
return Outcome::Finish(Some(list_ops::list_result(
rows, data.unit,
)));
}
Some(fields) => {
frame.state = ListState::Scan(KeyScan {
rows: rows.into(),
fields,
row: 0,
field: 0,
key: Vec::new(),
keyed: Vec::new(),
then: ScanThen::List(data.unit),
});
}
}
}
(_, other) => unreachable!("BUG: {other:?} does not take operands here"),
}
}
ListState::InlineDeferred {
data,
values,
count,
key_fields,
mut pending,
} => {
inbox = None;
let Some(force) = pending.next() else {
frame.state = ListState::Args {
data,
values,
count,
key_fields,
};
continue;
};
frame.state = ListState::InlineDeferred {
data,
values,
count,
key_fields,
pending,
};
#[cfg(test)]
let forced = matches!(force, RowBody::Member(_));
let (child, mode) = force_frame(force, plan, ctx);
#[cfg(test)]
let child = Frame { forced, ..child };
return spawn(child, mode);
}
ListState::PerRow {
data,
mut cursor,
mut values,
mut first_veto,
} => {
let level = usize::try_from(
frame
.row_level
.expect("BUG: per-row command without a row level"),
)
.expect("BUG: row level fits usize");
let argument = *frame
.args
.first()
.expect("BUG: row reduction must have a row argument");
if let Some(value) = inbox.take() {
ctx.row_stack.truncate(level);
match value {
OperationResult::Value(bound) => {
values.push(bound);
}
veto => {
first_veto.get_or_insert(veto);
}
}
cursor += 1;
}
if cursor < data.rows.len() {
assert_eq!(
ctx.row_stack.len(),
level,
"BUG: list command entered at the wrong row depth"
);
let row = data
.rows
.get(cursor)
.expect("BUG: cursor below the list length");
let current = match op {
NormalFormListOp::Predicate {
form: crate::parsing::ast::ListPredicateForm::Value,
..
} => CurrentRow::Value(row.into_owned()),
NormalFormListOp::Predicate {
form: crate::parsing::ast::ListPredicateForm::Instance,
..
}
| NormalFormListOp::Sum
| NormalFormListOp::Product
| NormalFormListOp::Avg
| NormalFormListOp::Min
| NormalFormListOp::Max
| NormalFormListOp::Sort { .. } => current_instance_row(&row, cursor),
other => unreachable!("BUG: {other:?} is not a per-row operation"),
};
if let CurrentRow::Instance { key, .. } = ¤t {
if !ctx.caches.row_contexts.borrow().contains_key(key) {
let template = plan.row_template(&key.row.identity);
let child = Frame::row_scope(key.clone(), template, RowBody::Nothing);
frame.state = ListState::PerRow {
data,
cursor,
values,
first_veto,
};
return spawn(child, WalkMode::Same);
}
}
ctx.row_stack.push(current);
frame.state = ListState::PerRow {
data,
cursor,
values,
first_veto,
};
return spawn(Frame::cell(argument), WalkMode::New);
}
let empty_sum_veto = match op {
NormalFormListOp::Sum if data.rows.is_empty() => {
empty_sum_scale_veto(result_type, plan, ctx)
}
_ => None,
};
return Outcome::Finish(Some(match first_veto.or(empty_sum_veto) {
Some(veto) => veto,
None => list_ops::per_row_result(
op,
&data.rows,
&values,
data.unit.clone(),
plan.result_type(argument),
result_type,
plan,
),
}));
}
ListState::Scan(mut scan) => {
if let Some(value) = inbox.take() {
#[cfg(test)]
ctx.log_scan(frame.id, scan.row, scan.field, &value);
match value {
OperationResult::Value(bound) => {
let row = scan
.rows
.get(scan.row)
.expect("BUG: scanned row below the list length");
let (_, _, field_type) =
key_field_read(plan, &row, &scan.fields[scan.field]);
scan.key.push(typed_from_bound(&bound, &field_type));
}
veto => return Outcome::Finish(Some(veto)),
}
scan.field += 1;
}
loop {
if scan.row == scan.rows.len() {
let names: Vec<String> =
scan.fields.iter().map(|field| field.name.clone()).collect();
let index = match KeyIndex::build_numbered(names, &scan.keyed) {
Ok(index) => Arc::new(index),
Err(conflict) => {
return Outcome::Finish(Some(OperationResult::Veto(
VetoType::computation(conflict),
)));
}
};
return Outcome::Finish(Some(match scan.then {
ScanThen::List(unit) => {
list_ops::list_result(scan.rows.with_index(index), unit)
}
ScanThen::Find(wanted) => {
find_keyed(&scan.rows, &index, &scan.fields, &wanted)
}
}));
}
if scan.field == scan.fields.len() {
let key = std::mem::take(&mut scan.key);
scan.keyed.push(key);
scan.row += 1;
scan.field = 0;
continue;
}
let (row, end, _) = key_field_read(
plan,
&scan
.rows
.get(scan.row)
.expect("BUG: scanned row below the list length"),
&scan.fields[scan.field],
);
let read = rows::ReadRow::listed(row.clone(), scan.row);
frame.state = ListState::Scan(scan);
return spawn(Frame::read_row(row, end, read.position), WalkMode::Same);
}
}
}
}
}
fn step_cell<'p>(
cell: &mut CellFrame,
mut inbox: Delivered,
walk: &WalkDone,
plan: &'p ExecutionPlan,
ctx: &mut EvaluationContext,
) -> Outcome<'p> {
let id = cell.id;
if let Some(resume) = cell.resume.take() {
let value = inbox.take().expect("BUG: resumed cell has no child value");
match resume {
Resume::Plain => return cell_done(cell, walk, value, plan, ctx),
Resume::RowLog(mark) => {
ctx.record_row_log(id, mark);
return cell_done(cell, walk, value, plan, ctx);
}
Resume::Member(mark) => {
let NormalFormKind::SpecMember { row, .. } = &plan.normal_form(id).kind else {
unreachable!("BUG: a member hop resumed a cell that is not a member read");
};
if cell.cursor + 1 == row.ends.len() || value.vetoed() {
ctx.record_row_log(id, mark);
return cell_done(cell, walk, value, plan, ctx);
}
cell.cursor += 1;
cell.acc = Some(value);
cell.member_mark = Some(mark);
}
}
}
if let Some(settled) = cell.settled.take() {
return Outcome::Finish(Some(finish(id, settled, plan, ctx)));
}
macro_rules! need {
($child:expr) => {{
let child: NormalFormId = $child;
match ready(child, ctx, walk) {
Some(value) => value,
None => return spawn(Frame::cell(child), WalkMode::Same),
}
}};
}
macro_rules! settle {
($outcome:expr) => {
match $outcome {
Ok(value) => return cell_done(cell, walk, value, plan, ctx),
Err(child) => return spawn(Frame::cell(child), WalkMode::Same),
}
};
}
macro_rules! done {
($value:expr) => {
return cell_done(cell, walk, $value, plan, ctx)
};
}
let cell_def = plan.normal_form(id);
if let Some(index) = plan.rule_ref_indexes[id.index()] {
return match &ctx.rule_values[index.index()] {
None => spawn(Frame::rule(index), WalkMode::Same),
Some(result) => {
let result = result.clone();
#[cfg(test)]
ctx.log_store(plan, id, &result);
ctx.values[id.index()] = Some(result.clone());
Outcome::Finish(Some(result))
}
};
}
if matches!(
cell_def.kind,
NormalFormKind::Leaf(LeafKind::Literal(_)) | NormalFormKind::UnitConversion(..)
) {
if let Some(force) = unforced_row_scale(id, plan, ctx) {
return force;
}
}
match &cell_def.kind {
NormalFormKind::Leaf(LeafKind::Literal(_)) => {
cell_done(cell, walk, compute::literal(id, plan, ctx), plan, ctx)
}
NormalFormKind::Leaf(LeafKind::DataPath(path)) => {
if let Some(DataDefinition::Import { pin, .. }) = plan.data.get(path) {
let mut selected = None;
if let Some(pin) = pin {
let body = match ctx.caches.body(ctx.owner_row.as_ref(), path) {
Some(body) => body,
None => {
match pin {
crate::planning::semantics::ImportEffectivePin::Data(pin_path) => {
let leaf = *plan.data_leaf.get(pin_path).unwrap_or_else(|| {
panic!("BUG: effective pin data '{pin_path}' has no leaf")
});
if ctx.leaf_unsettled(leaf.index()) {
return spawn(Frame::cell(leaf), WalkMode::Same);
}
}
crate::planning::semantics::ImportEffectivePin::Rule(pin_rule) => {
let index = plan.rule_index(pin_rule);
if ctx.rule_values[index.index()].is_none() {
return spawn(Frame::rule(index), WalkMode::Same);
}
}
}
let body = crate::evaluation::select_dynamic_body(plan, ctx, path, pin);
ctx.caches.select_body(
ctx.owner_row.clone(),
path.clone(),
body.clone(),
);
body
}
};
match body {
Ok(body) => selected = Some(body),
Err(failure) => done!(failure),
}
}
let key = plan.import_key(
ctx.owner_row.as_ref(),
path,
selected.as_ref(),
&ctx.caches.globals,
);
done!(OperationResult::from_literal(LiteralValue::new(
ValueKind::Spec(SpecValue::Row(key))
)))
}
let lemma_type = plan
.data
.get(path)
.and_then(|definition| definition.schema_type());
let needs_options =
lemma_type.is_some_and(|schema| schema.needs_runtime_option_check());
if needs_options {
if let Some(rule_path) = plan.options_rule_of(path) {
let index = plan.rule_index(&rule_path);
if ctx.rule_values[index.index()].is_none() {
return spawn(Frame::rule(index), WalkMode::Same);
}
}
}
if let Some(slot) = ctx.data_slot(plan, path).cloned() {
let result = compute::stored_data_leaf(id, slot, plan, ctx);
ctx.settle_leaf(id.index());
done!(result)
}
let list_path = match plan.reference_ends.get(path) {
Some(ReferenceEnd::Promptable(target)) => target,
Some(ReferenceEnd::Rule(rule)) => {
let index = plan.rule_index(rule);
if ctx.rule_values[index.index()].is_none() {
return spawn(Frame::rule(index), WalkMode::Same);
}
let value = resolve_data_path_value(path, plan, ctx);
#[cfg(test)]
ctx.log_store(plan, id, &value);
ctx.values[id.index()] = Some(value.clone());
return Outcome::Finish(Some(value));
}
None => path,
};
if let Some(blocked) = options_rule_blocker(plan, ctx, path) {
done!(blocked);
}
if let Some(source) = plan.instance_lists.get(list_path) {
if list_path == path {
done!(stored_list(path, source, ctx))
}
let leaf = *plan
.data_leaf
.get(list_path)
.expect("BUG: instance list has no data_leaf entry");
cell.resume = Some(Resume::Plain);
return spawn(Frame::cell(leaf), WalkMode::New);
}
done!(resolve_data_path_value(path, plan, ctx))
}
NormalFormKind::RowField { level, end, .. } => {
let level = usize::try_from(*level).expect("BUG: row level fits usize");
let (key, position) = match ctx
.row_stack
.get(level)
.expect("BUG: row field evaluated outside its list command")
{
CurrentRow::Instance { key, position } => (key.clone(), *position),
CurrentRow::Value(_) => {
panic!("BUG: row field evaluated against a value-list row")
}
};
let read = rows::ReadRow::listed(key, position);
if let Some(written) = inline_row_binding(&read.key, read.position, end, plan, ctx) {
done!(written)
}
cell.resume = Some(Resume::Plain);
spawn(
Frame::read_row(read.key, end.clone(), read.position),
WalkMode::Same,
)
}
NormalFormKind::Leaf(LeafKind::RowValue { level }) => {
let level = usize::try_from(*level).expect("BUG: row level fits usize");
let row = match ctx
.row_stack
.get(level)
.expect("BUG: row value evaluated outside its list command")
{
CurrentRow::Value(row) => row,
CurrentRow::Instance { .. } => {
panic!("BUG: RowValue evaluated against an instance-list row")
}
};
done!(OperationResult::from_literal(row.to_literal()))
}
NormalFormKind::Now => done!(OperationResult::from_literal(ctx.now().clone())),
NormalFormKind::SpecMember { base, row, .. } => {
let instance = match cell.acc.take() {
Some(instance) => instance,
None => {
let base_result = need!(*base);
if base_result.vetoed() {
done!(base_result)
}
base_result
}
};
let key = match &borrow_value(&instance, "spec member").value {
ValueKind::Spec(SpecValue::Row(key)) => key.clone(),
other => panic!("BUG: spec member base was {other}, not a spec value"),
};
let end = row
.ends
.get(cell.cursor)
.expect("BUG: member read past its last hop");
let mark = match cell.member_mark.take() {
Some(mark) => mark,
None => ctx.row_log_mark(),
};
if cell.cursor + 1 == row.ends.len() {
if let Some(written) = inline_row_binding(&key, None, end, plan, ctx) {
ctx.record_row_log(id, mark);
done!(written)
}
}
cell.resume = Some(Resume::Member(mark));
spawn(Frame::read_row(key, end.clone(), None), WalkMode::Same)
}
NormalFormKind::ListCommand {
list,
op,
args,
row_level,
} => {
if row_level.is_some() {
if let OperationResult::Value(_) = need!(*list) {
let scoped: Vec<NormalFormId> = args
.iter()
.copied()
.filter(|arg| plan.row_mask[arg.index()] == 0)
.collect();
while cell.cursor < scoped.len() {
need!(scoped[cell.cursor]);
cell.cursor += 1;
}
}
}
cell.resume = Some(match row_level {
Some(_) => Resume::RowLog(ctx.row_log_mark()),
None => Resume::Plain,
});
spawn(
Frame::list_op(id, *list, op, args, *row_level, plan.result_type(id)),
WalkMode::Same,
)
}
NormalFormKind::Veto(veto) => done!(OperationResult::Veto(VetoType::UserDefined {
message: veto.message.clone().filter(|m| !m.is_empty()),
})),
NormalFormKind::Sum(terms) | NormalFormKind::Product(terms) => {
settle!(fold_step(cell, terms, plan, ctx, walk))
}
NormalFormKind::Negate(inner)
| NormalFormKind::Reciprocal(inner)
| NormalFormKind::Not(inner)
| NormalFormKind::MathOp(_, inner)
| NormalFormKind::StepRounding(_, inner, None)
| NormalFormKind::UnitConversion(inner, _)
| NormalFormKind::DateRelative(_, inner)
| NormalFormKind::DateCalendar(_, _, inner)
| NormalFormKind::RangeBound(_, inner)
| NormalFormKind::PastFutureRange(_, inner)
| NormalFormKind::ResultIsVeto(inner) => {
let value = need!(*inner);
done!(compute::unary(id, value, plan, ctx))
}
NormalFormKind::Logical(connective, children) => {
settle!(logical_step(cell, *connective, children, ctx, walk))
}
NormalFormKind::StepRounding(_, operand, Some(step)) => {
settle!(binary_operands(*operand, *step, ctx, walk)
.map(|(left, right)| compute::binary(id, &left, right.as_ref(), plan)))
}
NormalFormKind::RangeLiteral(left, right)
| NormalFormKind::RangeContainment(left, right)
| NormalFormKind::Subtract(left, right)
| NormalFormKind::Power(left, right)
| NormalFormKind::Divide(left, right)
| NormalFormKind::Modulo(left, right)
| NormalFormKind::Comparison(left, _, right) => {
settle!(
binary_operands(*left, *right, ctx, walk).map(|(l, r)| compute::binary(
id,
&l,
r.as_ref(),
plan
))
)
}
NormalFormKind::Piecewise(arms) => {
assert!(!arms.is_empty(), "BUG: empty piecewise");
while cell.cursor + 1 < arms.len() {
let (condition, body) = arms[arms.len() - 1 - cell.cursor];
match condition_outcome(&need!(condition)) {
BranchOutcome::Propagate(result) => done!(result),
BranchOutcome::Taken => {
let value = need!(body);
done!(value)
}
BranchOutcome::NotTaken => cell.cursor += 1,
}
}
let value = need!(arms[0].1);
done!(value)
}
NormalFormKind::OrderedDispatch {
scrutinee,
boundaries,
regions,
} => {
assert_eq!(
regions.len(),
region_count(boundaries.len()),
"BUG: OrderedDispatch region table does not match its boundary list"
);
let scrutinee_result = need!(*scrutinee);
if scrutinee_result.vetoed() {
if !regions.iter().any(DispatchRegion::is_conjunctive) {
done!(scrutinee_result)
}
let value = need!(plan.normal_form(id).dispatched_rule());
done!(value)
}
let value = borrow_value(&scrutinee_result, "dispatch scrutinee");
let region = match region_of_scrutinee(boundaries, &value.value) {
Ok(region) => region,
Err(veto) => done!(OperationResult::Veto(veto)),
};
let value = need!(regions[region].cell());
done!(value)
}
}
}
fn cell_done<'p>(
cell: &mut CellFrame,
walk: &WalkDone,
value: OperationResult,
plan: &'p ExecutionPlan,
ctx: &mut EvaluationContext,
) -> Outcome<'p> {
let id = cell.id;
let origin = if ctx.exhaustive {
plan.normal_form(id).origin
} else {
None
};
if let Some(origin) = origin {
if ready(origin, ctx, walk).is_none() {
cell.settled = Some(value);
return spawn(Frame::cell(origin), WalkMode::Same);
}
}
Outcome::Finish(Some(finish(id, value, plan, ctx)))
}
fn fold_step(
cell: &mut CellFrame,
terms: &[ArithmeticTerm],
plan: &ExecutionPlan,
ctx: &EvaluationContext,
walk: &WalkDone,
) -> Result<OperationResult, NormalFormId> {
assert!(!terms.is_empty(), "BUG: empty n-ary arithmetic");
while cell.cursor < terms.len() {
if compute::fold_settled(cell.veto.as_ref()) && !ctx.exhaustive {
break;
}
let index = cell.cursor;
let child = terms[index].operand;
let Some(result) = ready(child, ctx, walk) else {
return Err(child);
};
cell.cursor += 1;
compute::fold_term(&mut cell.acc, &mut cell.veto, cell.id, index, result, plan);
}
Ok(compute::fold_result(cell.acc.take(), cell.veto.take()))
}
fn logical_step(
cell: &mut CellFrame,
connective: LogicalConnective,
children: &[NormalFormId],
ctx: &EvaluationContext,
walk: &WalkDone,
) -> Result<OperationResult, NormalFormId> {
assert!(
children.len() >= 2,
"BUG: Logical has at least two operands"
);
loop {
let child = children[cell.cursor];
let result = ready(child, ctx, walk).ok_or(child)?;
if let Some(decided) = compute::logical_operand(connective, &mut cell.veto, result) {
return Ok(decided);
}
cell.cursor += 1;
if cell.cursor == children.len() {
return Ok(compute::logical_result(connective, cell.veto.take()));
}
}
}
fn binary_operands(
left: NormalFormId,
right: NormalFormId,
ctx: &EvaluationContext,
walk: &WalkDone,
) -> Result<(OperationResult, Option<OperationResult>), NormalFormId> {
let left_result = ready(left, ctx, walk).ok_or(left)?;
if left_result.vetoed() && !left_result.is_missing_data() {
if ctx.exhaustive {
ready(right, ctx, walk).ok_or(right)?;
}
return Ok((left_result, None));
}
let right_result = ready(right, ctx, walk).ok_or(right)?;
Ok((left_result, Some(right_result)))
}