use crate::computation::arithmetic::divisive_operation_results;
use crate::computation::bigint::BigInt;
use crate::computation::datetime::{
compute_date_calendar, compute_date_relative, evaluate_past_future_range,
};
use crate::computation::measure_math::{integer_rounding, step_rounding};
use crate::computation::range::{check_containment, ordered_endpoints};
use crate::computation::rational::{
checked_mul, checked_pow_integer, rational_one, rational_zero, RationalInteger,
};
use crate::computation::{
arithmetic_operation, comparison_operation, convert_unit_operand, OperationResult, VetoType,
};
use crate::evaluation::branch_semantics::{condition_outcome, BranchOutcome};
use crate::evaluation::expression::{evaluate_mathematical_operator, resolve_data_path_value};
use crate::evaluation::list_ops;
use crate::evaluation::tree::RowBody;
use crate::evaluation::{CurrentRow, EvaluationContext};
use crate::parsing::ast::{ConversionTypeKind, LogicalConnective};
use crate::planning::execution_plan::{validate_value_against_type, ExecutionPlan, TargetForce};
use crate::planning::instance_list::InstanceListSource;
use crate::planning::instance_list::KeyIndex;
use crate::planning::normalize::{LeafKind, NormalFormId, NormalFormKind};
use crate::planning::semantics::{
primitive_boolean_arc, primitive_number_arc, typed_literal_from_bound, ArithmeticComputation,
BoundValueKind, ComparisonComputation, DataPath, InstanceKey, LemmaType, LiteralValue,
RangeBound, ReferenceEnd, ReferenceTarget, RowBinding, ScaleTarget, SemanticConversionTarget,
SemanticDateTime, TypedLiteral, ValueKind,
};
use crate::planning::semantics::{KeyField, ListValue};
use std::collections::HashMap;
use std::sync::Arc;
fn resolved_scale_factor(
scale: &ScaleTarget,
plan: &ExecutionPlan,
ctx: &EvaluationContext,
) -> Result<RationalInteger, OperationResult> {
assert!(
plan.holds_scale_target(scale),
"BUG: scale target '{scale}' resolved on a plan of '{}', which does not hold it",
plan.spec_name
);
match resolve_stored_target(&scale.target, plan, ctx) {
OperationResult::Veto(veto) => Err(OperationResult::Veto(veto)),
OperationResult::Value(bound) => {
let ValueKind::Number(factor) = &bound.value else {
panic!(
"BUG: unit scale target resolved to {} after planning required number",
bound.value
);
};
if !factor.numer_is_positive() {
return Err(OperationResult::Veto(VetoType::computation(
"unit conversion factor must be greater than zero",
)));
}
Ok(factor.clone())
}
}
}
pub(crate) fn composed_unit_scale_factor(
unit: &crate::literals::MeasureUnit,
plan: &ExecutionPlan,
ctx: &EvaluationContext,
) -> Result<RationalInteger, OperationResult> {
let factors = unit.resolved_scale_factors();
if factors.is_empty() {
panic!(
"BUG: composed_unit_scale_factor on unit '{}' with no scale factors",
unit.name
);
}
let mut product = unit.scale_coefficient();
for (target, exponent) in factors {
let settled = resolved_scale_factor(target, plan, ctx)?;
let raised = if *exponent == 1 {
settled
} else {
checked_pow_integer(&settled, &BigInt::from_i64(i64::from(*exponent))).map_err(
|failure| OperationResult::Veto(VetoType::computation(failure.to_string())),
)?
};
product = checked_mul(&product, &raised)
.map_err(|failure| OperationResult::Veto(VetoType::computation(failure.to_string())))?;
}
Ok(product)
}
fn measure_unit_on_type<'a>(
lemma_type: &'a LemmaType,
unit_name: &str,
) -> &'a crate::literals::MeasureUnit {
let units = lemma_type.measure_units_table().unwrap_or_else(|| {
panic!(
"BUG: measure unit lookup on non-measure type '{}'",
lemma_type.name()
)
});
units.get(unit_name).unwrap_or_else(|_| {
panic!(
"BUG: unknown unit '{unit_name}' on measure type '{}'",
lemma_type.name()
)
})
}
enum ScaleNodeType<'a> {
Borrowed(&'a LemmaType),
Shared(Arc<LemmaType>),
}
impl ScaleNodeType<'_> {
fn get(&self) -> &LemmaType {
match self {
Self::Borrowed(lemma_type) => lemma_type,
Self::Shared(lemma_type) => lemma_type.as_ref(),
}
}
fn into_arc(self) -> Arc<LemmaType> {
match self {
Self::Borrowed(lemma_type) => Arc::new(lemma_type.clone()),
Self::Shared(lemma_type) => lemma_type,
}
}
}
enum ScaleTask<'a> {
Visit {
value: ValueKind,
lemma_type: ScaleNodeType<'a>,
binding: Option<Arc<str>>,
},
AssembleRange {
lemma_type: Arc<LemmaType>,
binding: Option<Arc<str>>,
},
AssembleList {
lemma_type: Arc<LemmaType>,
binding: Option<Arc<str>>,
rows: usize,
},
}
fn scale_value(
value: ValueKind,
lemma_type: &LemmaType,
binding: Option<Arc<str>>,
plan: &ExecutionPlan,
ctx: &EvaluationContext,
) -> OperationResult {
let mut tasks = vec![ScaleTask::Visit {
value,
lemma_type: ScaleNodeType::Borrowed(lemma_type),
binding: binding.clone(),
}];
let mut done: Vec<TypedLiteral> = Vec::new();
let mut root_unit = binding;
while let Some(task) = tasks.pop() {
match task {
ScaleTask::Visit {
value,
lemma_type,
binding,
} => match value {
ValueKind::UnscaledMeasure { magnitude, unit } => {
let holding = lemma_type.get();
if holding.unit_scale_factors(&unit).is_empty() {
panic!(
"BUG: unscaled measure unit '{unit}' on '{}' has no scale factors",
holding.name()
);
}
if tasks.is_empty() && done.is_empty() {
root_unit = Some(Arc::clone(&unit));
}
let measure_unit = measure_unit_on_type(holding, &unit);
match composed_unit_scale_factor_for_settle(
measure_unit,
&unit,
holding,
plan,
ctx,
) {
Err(veto) => return veto,
Ok(factor) => match checked_mul(&magnitude, &factor) {
Ok(canonical) => done.push(TypedLiteral {
value: ValueKind::Measure(canonical),
lemma_type: lemma_type.into_arc(),
}),
Err(failure) => {
return OperationResult::Veto(VetoType::computation(
failure.to_string(),
));
}
},
}
}
ValueKind::Range(left, right) => {
let lemma_type = lemma_type.into_arc();
tasks.push(ScaleTask::AssembleRange {
lemma_type: Arc::clone(&lemma_type),
binding,
});
let right = *right;
let left = *left;
tasks.push(ScaleTask::Visit {
value: right.value,
lemma_type: ScaleNodeType::Shared(right.lemma_type),
binding: None,
});
tasks.push(ScaleTask::Visit {
value: left.value,
lemma_type: ScaleNodeType::Shared(left.lemma_type),
binding: None,
});
}
ValueKind::List(rows) => {
let lemma_type = lemma_type.into_arc();
let count = rows.len();
tasks.push(ScaleTask::AssembleList {
lemma_type,
binding,
rows: count,
});
for row in rows.iter().rev() {
let row = row.into_owned();
tasks.push(ScaleTask::Visit {
value: row.value,
lemma_type: ScaleNodeType::Shared(row.lemma_type),
binding: None,
});
}
}
other => done.push(TypedLiteral {
value: other,
lemma_type: lemma_type.into_arc(),
}),
},
ScaleTask::AssembleRange {
lemma_type,
binding,
} => {
let right = done
.pop()
.expect("BUG: scaled range missing right endpoint");
let left = done.pop().expect("BUG: scaled range missing left endpoint");
if tasks.is_empty() && done.is_empty() {
root_unit = binding;
}
done.push(TypedLiteral {
value: ValueKind::Range(Box::new(left), Box::new(right)),
lemma_type,
});
}
ScaleTask::AssembleList {
lemma_type,
binding,
rows,
} => {
let mut scaled = Vec::with_capacity(rows);
for _ in 0..rows {
scaled.push(done.pop().expect("BUG: scaled list missing a row"));
}
scaled.reverse();
if tasks.is_empty() && done.is_empty() {
root_unit = binding;
}
done.push(TypedLiteral {
value: ValueKind::List(scaled.into()),
lemma_type,
});
}
}
}
let result = done.pop().expect("BUG: scale walk leaves one result");
OperationResult::from_bound(BoundValueKind {
value: result.value,
unit: root_unit,
instance_factors: None,
})
}
pub(crate) fn settle_stored(
bound: BoundValueKind,
lemma_type: &LemmaType,
plan: &ExecutionPlan,
ctx: &EvaluationContext,
) -> OperationResult {
if !bound.value.has_unscaled_measure() {
return OperationResult::from_bound(bound);
}
let carried = bound.instance_factors.clone();
match scale_value(bound.value, lemma_type, bound.unit, plan, ctx) {
OperationResult::Value(mut settled) => {
if settled.instance_factors.is_none() {
settled.instance_factors = carried;
}
OperationResult::from_bound(settled)
}
other => other,
}
}
pub(crate) fn conversion_dynamic_unit<'a>(
target: &'a SemanticConversionTarget,
source_type: &'a LemmaType,
) -> Option<(String, &'a LemmaType)> {
match target {
SemanticConversionTarget::Unit {
unit_name,
owning_type,
} if owning_type.unit_is_dynamic(unit_name) => {
if owning_type.unit_scale_factors(unit_name).is_empty() {
panic!(
"BUG: dynamic unit '{unit_name}' on '{}' has no scale factors",
owning_type.name()
);
}
Some((unit_name.clone(), owning_type.as_ref()))
}
SemanticConversionTarget::Type(ConversionTypeKind::Number) if source_type.is_measure() => {
let unit = source_type.measure_runtime_signature().into_iter().next()?;
if source_type.unit_is_dynamic(&unit.0) {
if source_type.unit_scale_factors(&unit.0).is_empty() {
panic!(
"BUG: dynamic unit '{}' on '{}' has no scale factors",
unit.0,
source_type.name()
);
}
Some((unit.0, source_type))
} else {
None
}
}
_ => None,
}
}
fn converted_at(
converted: OperationResult,
unit: &str,
factor: &RationalInteger,
) -> OperationResult {
let OperationResult::Value(mut bound) = converted else {
return converted;
};
if let Some(carried) = &bound.instance_factors {
if carried.get(unit) != Some(factor) {
bound.instance_factors = Some(Arc::new(carried.with_factor(unit, factor)));
}
}
OperationResult::from_bound(bound)
}
pub(crate) fn conversion_dynamic_factor(
bound: &BoundValueKind,
unit_name: &str,
holding: &LemmaType,
plan: &ExecutionPlan,
ctx: &EvaluationContext,
) -> Result<RationalInteger, OperationResult> {
let measure_unit = measure_unit_on_type(holding, unit_name);
let factors = measure_unit.resolved_scale_factors();
if factors.is_empty() {
panic!("BUG: conversion_dynamic_factor on unit '{unit_name}' with no scale factors");
}
let all_in_plan = factors
.iter()
.all(|(target, _)| plan.holds_scale_target(target));
if all_in_plan {
for (target, _) in factors {
assert!(
unforced_target(target, plan, ctx).is_none(),
"BUG: conversion scale {target:?} read before its scale dependency was evaluated"
);
}
return composed_unit_scale_factor(measure_unit, plan, ctx);
}
if let Some(factors) = bound.instance_factors.as_ref() {
if let Some(factor) = factors.get(unit_name) {
return Ok(factor.clone());
}
if let Some(veto) = factors.unsettled(unit_name) {
return Err(OperationResult::Veto(veto.clone()));
}
}
let all_bare = factors.iter().all(|(scale, _)| match &scale.target {
ReferenceTarget::Data(path) => path.segments.is_empty(),
ReferenceTarget::Rule(path) => path.segments.is_empty(),
});
let in_rows = factors
.iter()
.all(|(target, _)| bare_target_row(target, plan, ctx).is_some());
let all_settle = factors.iter().all(|(target, _)| {
plan.holds_scale_target(target) || bare_target_row(target, plan, ctx).is_some()
});
if (all_bare && all_settle) || in_rows {
return composed_unit_scale_factor_for_settle(measure_unit, unit_name, holding, plan, ctx);
}
Err(OperationResult::Veto(VetoType::computation(format!(
"no conversion factor is known for unit '{unit_name}'"
))))
}
pub(crate) fn runtime_scale_factors_for(
lemma_type: &LemmaType,
plan: &ExecutionPlan,
ctx: &EvaluationContext,
) -> HashMap<String, RationalInteger> {
runtime_scales_for(lemma_type, plan, ctx).0
}
pub(crate) fn runtime_scales_for(
lemma_type: &LemmaType,
plan: &ExecutionPlan,
ctx: &EvaluationContext,
) -> (
HashMap<String, RationalInteger>,
std::collections::BTreeMap<String, VetoType>,
) {
let mut out = HashMap::new();
let mut unsettled = std::collections::BTreeMap::new();
let Some(units) = lemma_type.measure_units_table() else {
return (out, unsettled);
};
let family_declared_here = lemma_type.held_measure_family().is_some_and(|family| {
family.spec == plan.spec_name
&& family.repository.as_deref() == plan.identity.repository.as_deref()
});
for unit in units.iter() {
match &unit.scale {
crate::literals::UnitScale::Literal(factor) => {
out.insert(unit.name.clone(), factor.clone());
}
crate::literals::UnitScale::Reference { factors, .. } => {
if factors.is_empty() {
panic!(
"BUG: dynamic unit '{}' on '{}' has empty scale factors after planning",
unit.name,
lemma_type.name()
);
}
let all_forcible = factors.iter().all(|(target, _)| {
let bare = match &target.target {
ReferenceTarget::Data(path) => path.segments.is_empty(),
ReferenceTarget::Rule(path) => path.segments.is_empty(),
};
if bare && !family_declared_here && !plan.holds_scale_target(target) {
return false;
}
plan.holds_scale_target(target) && unforced_target(target, plan, ctx).is_none()
});
if !all_forcible {
continue;
}
match composed_unit_scale_factor(unit, plan, ctx) {
Ok(factor) => {
out.insert(unit.name.clone(), factor);
}
Err(OperationResult::Veto(veto)) => {
unsettled.insert(unit.name.clone(), veto);
}
Err(OperationResult::Value(_)) => {
unreachable!("BUG: a unit scale failure is a veto")
}
}
}
crate::literals::UnitScale::Compound { .. }
| crate::literals::UnitScale::Unresolved { .. } => {
panic!(
"BUG: unit '{}' on '{}' never went through scale resolution",
unit.name,
lemma_type.name()
);
}
}
}
(out, unsettled)
}
fn composed_unit_scale_factor_for_settle(
unit: &crate::literals::MeasureUnit,
unit_name: &str,
holding: &LemmaType,
plan: &ExecutionPlan,
ctx: &EvaluationContext,
) -> Result<RationalInteger, OperationResult> {
let factors = unit.resolved_scale_factors();
if factors.is_empty() {
panic!(
"BUG: composed_unit_scale_factor_for_settle on unit '{unit_name}' with no scale factors"
);
}
let mut product = unit.scale_coefficient();
for (target, exponent) in factors {
let settled = settled_scale_factor_for_target(target, unit_name, holding, plan, ctx)?;
let raised = if *exponent == 1 {
settled
} else {
checked_pow_integer(&settled, &BigInt::from_i64(i64::from(*exponent))).map_err(
|failure| OperationResult::Veto(VetoType::computation(failure.to_string())),
)?
};
product = checked_mul(&product, &raised)
.map_err(|failure| OperationResult::Veto(VetoType::computation(failure.to_string())))?;
}
Ok(product)
}
fn settled_scale_factor_for_target(
target: &ScaleTarget,
unit_name: &str,
holding: &LemmaType,
plan: &ExecutionPlan,
ctx: &EvaluationContext,
) -> Result<RationalInteger, OperationResult> {
if plan.holds_scale_target(target) {
assert!(
unforced_target(target, plan, ctx).is_none(),
"BUG: scale of unit '{unit_name}' on '{}' read before its scale dependency was evaluated",
holding.name()
);
return resolved_scale_factor(target, plan, ctx);
}
if let Some((key, template)) = bare_target_row(target, plan, ctx) {
if ctx.owner_row.as_ref() == Some(key) {
assert!(
unforced_target(target, template, ctx).is_none(),
"BUG: scale of unit '{unit_name}' on '{}' read before its scale dependency was evaluated",
holding.name()
);
return resolved_scale_factor(target, template, ctx);
}
let caches = ctx.caches.row_contexts.borrow();
let row_ctx = caches.get(key).unwrap_or_else(|| {
panic!(
"BUG: bare scale target '{target}' of a row-typed value settled before the row context was built; list per-row paths must spawn an empty RowScope first"
)
});
assert!(
unforced_target(target, template, row_ctx).is_none(),
"BUG: scale of unit '{unit_name}' on '{}' read before its scale dependency was evaluated",
holding.name()
);
return resolved_scale_factor(target, template, row_ctx);
}
assert!(
unforced_target(target, plan, ctx).is_none(),
"BUG: scale of unit '{unit_name}' on '{}' read before its scale dependency was evaluated",
holding.name()
);
resolved_scale_factor(target, plan, ctx)
}
pub(crate) fn bare_target_row<'p, 'c>(
target: &ScaleTarget,
plan: &'p ExecutionPlan,
ctx: &'c EvaluationContext,
) -> Option<(&'c InstanceKey, &'p ExecutionPlan)> {
if plan.holds_scale_target(target) {
return None;
}
ctx.row_stack.iter().rev().find_map(|row| {
let CurrentRow::Instance { key, .. } = row else {
return None;
};
let template = plan.row_template(&key.row.identity);
template
.holds_scale_target(target)
.then_some((key, template))
})
}
pub(crate) fn display_scale_factors(
bound: Option<&BoundValueKind>,
lemma_type: &LemmaType,
plan: &ExecutionPlan,
ctx: &EvaluationContext,
) -> HashMap<String, RationalInteger> {
let mut factors = runtime_scale_factors_for(lemma_type, plan, ctx);
if let Some(instance) = bound.and_then(|bound| bound.instance_factors.as_ref()) {
for (unit, factor) in instance.iter() {
factors.insert(unit.clone(), factor.clone());
}
}
factors
}
pub(crate) fn unforced_target(
scale: &ScaleTarget,
plan: &ExecutionPlan,
ctx: &EvaluationContext,
) -> Option<RowBody> {
unforced_reference(&scale.target, plan, ctx)
}
pub(crate) fn unforced_reference(
target: &ReferenceTarget,
plan: &ExecutionPlan,
ctx: &EvaluationContext,
) -> Option<RowBody> {
if let ReferenceTarget::Data(path) = target {
if let Some((held, _)) = bounded_unscaled(path, plan, ctx) {
for scale in plan.data_scale_targets(held) {
if let Some(force) = unevaluated(&scale.target, plan, ctx) {
return Some(force);
}
}
}
}
unevaluated(target, plan, ctx)
}
fn unevaluated(
target: &ReferenceTarget,
plan: &ExecutionPlan,
ctx: &EvaluationContext,
) -> Option<RowBody> {
match plan.target_force(target) {
Some(TargetForce::Member(cell)) => ctx.values[cell.index()]
.is_none()
.then_some(RowBody::Member(cell)),
Some(TargetForce::Rule(index)) => ctx.rule_values[index.index()]
.is_none()
.then_some(RowBody::Rule(index)),
None => {
let ReferenceTarget::Data(path) = target else {
return None;
};
let row = ctx.owner_row.as_ref()?;
let slot = plan.data.get_index_of(path)?;
if !matches!(
ctx.caches.binding(row, plan, slot).as_deref(),
Some(RowBinding::Deferred { .. })
) {
return None;
}
let leaf = *plan.data_leaf.get(path)?;
ctx.values[leaf.index()]
.is_none()
.then_some(RowBody::Leaf(leaf))
}
}
}
pub(crate) fn bounded_unscaled<'a>(
path: &'a DataPath,
plan: &'a ExecutionPlan,
ctx: &'a EvaluationContext,
) -> Option<(&'a DataPath, &'a BoundValueKind)> {
let held = match plan.reference_ends.get(path) {
Some(ReferenceEnd::Promptable(end)) => end,
Some(ReferenceEnd::Rule(_)) | None => path,
};
let leaf = plan.data_leaf.get(held)?;
let bound = ctx.values[leaf.index()].as_ref()?.value()?;
if !bound.value.has_unscaled_measure() {
return None;
}
let held_type = plan.data.get(held)?.schema_type()?;
crate::planning::fill::bounded_at_other_than_zero(held_type).then_some((held, bound))
}
pub(crate) fn resolve_stored_target(
target: &ReferenceTarget,
plan: &ExecutionPlan,
ctx: &EvaluationContext,
) -> OperationResult {
if let Some(&cell) = plan.member_targets.get(target) {
return ctx.values[cell.index()]
.clone()
.expect("BUG: member target resolved before its cell was evaluated");
}
match target {
ReferenceTarget::Rule(rule) => ctx.rule_value(plan, rule).clone(),
ReferenceTarget::Data(path) => resolve_stored_data_target(path, plan, ctx),
}
}
pub(crate) fn resolve_stored_data_target(
path: &DataPath,
plan: &ExecutionPlan,
ctx: &EvaluationContext,
) -> OperationResult {
if let Some(slot) = ctx.data_slot(plan, path) {
return slot.clone();
}
match plan.reference_ends.get(path) {
Some(ReferenceEnd::Rule(_)) => resolve_data_path_value(path, plan, ctx),
Some(ReferenceEnd::Promptable(end)) => {
if let Some(slot) = ctx.data_slot(plan, end) {
return slot.clone();
}
if let Some(nested_source) = plan.instance_lists.get(end) {
return stored_list(end, nested_source, ctx);
}
resolve_data_path_value(path, plan, ctx)
}
None => {
if let Some(nested_source) = plan.instance_lists.get(path) {
return stored_list(path, nested_source, ctx);
}
resolve_data_path_value(path, plan, ctx)
}
}
}
pub(crate) fn stored_list(
path: &DataPath,
source: &InstanceListSource,
ctx: &EvaluationContext,
) -> OperationResult {
let mut list = match ctx.caches.list_above(ctx.owner_row.as_ref(), path) {
Some(rows) => {
ListValue::stored_rows(rows, ctx.owner_row.clone(), Arc::clone(&source.row_type))
}
None => source.list(ctx.owner_row.clone()),
};
if ctx.caches.supplied.is_key_supplied(&ctx.owner_row, path)
|| ctx.caches.is_rekeyed_above(ctx.owner_row.as_ref(), path)
{
list = list.unindexed();
}
OperationResult::from_literal(LiteralValue {
value: ValueKind::List(list),
})
}
pub(crate) fn binary_arithmetic_result(
left: &OperationResult,
left_type: &Arc<LemmaType>,
right: &OperationResult,
right_type: &Arc<LemmaType>,
op: ArithmeticComputation,
plan: &ExecutionPlan,
) -> OperationResult {
arithmetic_operation(
borrow_value(left, "left operand"),
left_type,
&op,
borrow_value(right, "right operand"),
right_type,
&plan.signature_index,
)
}
pub(crate) fn unary(
id: NormalFormId,
value: OperationResult,
plan: &ExecutionPlan,
ctx: &EvaluationContext,
) -> OperationResult {
let kind = &plan.normal_form(id).kind;
if let NormalFormKind::ResultIsVeto(_) = kind {
return OperationResult::from_literal(LiteralValue::from_bool(value.vetoed()));
}
if value.vetoed() {
return value;
}
match kind {
NormalFormKind::Negate(inner) => {
let zero = OperationResult::from_literal(LiteralValue::number(rational_zero()));
binary_arithmetic_result(
&zero,
primitive_number_arc(),
&value,
plan.result_type(*inner),
ArithmeticComputation::Subtract,
plan,
)
}
NormalFormKind::Reciprocal(inner) => {
let one = OperationResult::from_literal(LiteralValue::number(rational_one()));
binary_arithmetic_result(
&one,
primitive_number_arc(),
&value,
plan.result_type(*inner),
ArithmeticComputation::Divide,
plan,
)
}
NormalFormKind::Not(inner) => {
let false_lit = OperationResult::from_literal(LiteralValue::from_bool(false));
comparison_operation(
&borrow_value(&value, "not operand").value,
plan.result_type(*inner),
&ComparisonComputation::Is,
&borrow_value(&false_lit, "not operand").value,
primitive_boolean_arc(),
)
}
NormalFormKind::MathOp(op, _) => evaluate_mathematical_operator(
op,
borrow_value(&value, "operand"),
plan.result_type(id),
),
NormalFormKind::StepRounding(mode, _, None) => {
integer_rounding(*mode, borrow_value(&value, "rounded operand"))
}
NormalFormKind::UnitConversion(inner, target) => {
let source_type = plan.result_type(*inner).as_ref();
let value = match value {
OperationResult::Value(bound) if bound.value.has_unscaled_measure() => {
settle_stored(bound, source_type, plan, ctx)
}
other => other,
};
if value.vetoed() {
return value;
}
let bound = borrow_value(&value, "conversion operand");
match conversion_dynamic_unit(target, source_type) {
Some((unit_name, holding)) => {
match conversion_dynamic_factor(bound, &unit_name, holding, plan, ctx) {
Err(veto) => veto,
Ok(factor) => {
let converted =
convert_unit_operand(bound, source_type, target, Some(&factor));
converted_at(converted, &unit_name, &factor)
}
}
}
None => convert_unit_operand(bound, source_type, target, None),
}
}
NormalFormKind::DateRelative(kind, _) => {
let date = match &borrow_value(&value, "date operand").value {
ValueKind::Date(dt) => dt,
other => panic!("BUG: date-relative operand expected date, got {other:?}"),
};
compute_date_relative(kind, date, now_date(ctx))
}
NormalFormKind::DateCalendar(kind, unit, _) => {
let date = match &borrow_value(&value, "date operand").value {
ValueKind::Date(dt) => dt,
other => panic!("BUG: date-calendar operand expected date, got {other:?}"),
};
compute_date_calendar(kind, unit, date, now_date(ctx))
}
NormalFormKind::RangeBound(bound, inner) => {
let range_literal = borrow_value(&value, "range operand");
let ValueKind::Range(left, right) = &range_literal.value else {
panic!(
"BUG: lower/upper expected a range value, got {:?}",
range_literal.value
)
};
let endpoint_type = plan
.result_type(*inner)
.specifications
.element_from_range()
.map(|element| Arc::new(LemmaType::primitive(element)))
.expect("BUG: lower/upper requires a range result type");
match ordered_endpoints(&left.value, &right.value, &endpoint_type) {
Ok((lo, hi)) => {
let picked = match bound {
RangeBound::Lower => lo,
RangeBound::Upper => hi,
};
let chosen = if std::ptr::eq(picked, &left.value) {
left.as_ref()
} else {
right.as_ref()
};
let unit = chosen.lemma_type.unit().map(Arc::<str>::from);
OperationResult::from_bound(BoundValueKind::with_binding(
chosen.value.clone(),
unit,
))
}
Err(veto) => OperationResult::Veto(veto),
}
}
NormalFormKind::PastFutureRange(kind, inner) => evaluate_past_future_range(
kind,
&borrow_value(&value, "offset operand").to_literal(),
plan.result_type(*inner),
now_date(ctx),
),
other => panic!("BUG: {other:?} is not a one-operand cell"),
}
}
pub(crate) fn binary(
id: NormalFormId,
left: &OperationResult,
right: Option<&OperationResult>,
plan: &ExecutionPlan,
) -> OperationResult {
let Some(right) = right else {
assert!(
left.vetoed() && !left.is_missing_data(),
"BUG: a binary cell skips its right operand only after a definitive left veto"
);
return left.clone();
};
let kind = &plan.normal_form(id).kind;
let (left_id, right_id) = match kind {
NormalFormKind::Subtract(l, r)
| NormalFormKind::Power(l, r)
| NormalFormKind::Divide(l, r)
| NormalFormKind::Modulo(l, r)
| NormalFormKind::Comparison(l, _, r)
| NormalFormKind::StepRounding(_, l, Some(r))
| NormalFormKind::RangeLiteral(l, r)
| NormalFormKind::RangeContainment(l, r) => (*l, *r),
other => panic!("BUG: {other:?} is not a two-operand cell"),
};
let (left_type, right_type) = (plan.result_type(left_id), plan.result_type(right_id));
if let NormalFormKind::Divide(..) | NormalFormKind::Modulo(..) = kind {
if right.vetoed() && !right.is_missing_data() {
return right.clone();
}
if right.is_missing_data() {
return if left.is_missing_data() {
left.clone()
} else {
right.clone()
};
}
let op = match kind {
NormalFormKind::Divide(..) => ArithmeticComputation::Divide,
_ => ArithmeticComputation::Modulo,
};
return divisive_operation_results(
left,
left_type,
&op,
right,
right_type,
&plan.signature_index,
);
}
if left.vetoed() {
if right.vetoed() && !right.is_missing_data() {
return right.clone();
}
return left.clone();
}
if right.vetoed() {
return right.clone();
}
match kind {
NormalFormKind::Subtract(..) => binary_arithmetic_result(
left,
left_type,
right,
right_type,
ArithmeticComputation::Subtract,
plan,
),
NormalFormKind::Power(..) => binary_arithmetic_result(
left,
left_type,
right,
right_type,
ArithmeticComputation::Power,
plan,
),
NormalFormKind::Comparison(_, op, _) => comparison_operation(
&borrow_value(left, "left operand").value,
left_type,
op,
&borrow_value(right, "right operand").value,
right_type,
),
NormalFormKind::StepRounding(mode, ..) => step_rounding(
*mode,
borrow_value(left, "rounded operand"),
borrow_value(right, "rounding step"),
plan.result_type(id),
),
NormalFormKind::RangeLiteral(..) => {
let left_typed =
typed_literal_from_bound(borrow_value(left, "left endpoint"), left_type);
let right_typed =
typed_literal_from_bound(borrow_value(right, "right endpoint"), right_type);
OperationResult::from_literal(LiteralValue::range(left_typed, right_typed))
}
NormalFormKind::RangeContainment(..) => {
let range_literal = borrow_value(right, "range operand");
let ValueKind::Range(range_left, range_right) = &range_literal.value else {
panic!(
"BUG: range containment expected range operand, got {:?}",
range_literal.value
)
};
let endpoint_type = right_type
.specifications
.element_from_range()
.map(|element| Arc::new(LemmaType::primitive(element)))
.expect("BUG: range containment requires a range result type");
check_containment(
&borrow_value(left, "value operand").value,
left_type,
&range_left.value,
&range_right.value,
&endpoint_type,
)
}
_ => unreachable!("BUG: two-operand kinds are matched above"),
}
}
pub(crate) fn borrow_value<'a>(result: &'a OperationResult, operand: &str) -> &'a BoundValueKind {
match result {
OperationResult::Value(v) => v,
OperationResult::Veto(_) => panic!("BUG: {operand} passed veto check but has no value"),
}
}
pub(crate) fn now_date(ctx: &EvaluationContext) -> &SemanticDateTime {
match &ctx.now().value {
ValueKind::Date(dt) => dt,
other => panic!("BUG: context.now() must be a date, got {other:?}"),
}
}
pub(crate) fn fold_settled(veto: Option<&OperationResult>) -> bool {
veto.is_some_and(|veto| !veto.is_missing_data())
}
pub(crate) fn fold_term(
acc: &mut Option<OperationResult>,
veto: &mut Option<OperationResult>,
id: NormalFormId,
index: usize,
result: OperationResult,
plan: &ExecutionPlan,
) {
let cell = plan.normal_form(id);
let (terms, direct_op, inverse_op) = match &cell.kind {
NormalFormKind::Sum(terms) => (
terms,
ArithmeticComputation::Add,
ArithmeticComputation::Subtract,
),
NormalFormKind::Product(terms) => (
terms,
ArithmeticComputation::Multiply,
ArithmeticComputation::Divide,
),
other => panic!("BUG: {other:?} is not an n-ary fold"),
};
let fold_types = &cell.fold_types;
assert_eq!(
fold_types.len(),
terms.len(),
"BUG: Sum/Product fold_types length must match terms"
);
let term = terms[index];
let child = term.operand;
if let Some(settled) = veto.as_ref() {
if settled.is_missing_data() && !result.vetoed() && term.inverse {
let combined = divisive_operation_results(
settled,
&fold_types[index - 1],
&inverse_op,
&result,
plan.result_type(child),
&plan.signature_index,
);
if combined.vetoed() && !combined.is_missing_data() {
*veto = Some(combined);
}
return;
}
if settled.is_missing_data() && result.vetoed() && !result.is_missing_data() {
*veto = Some(result);
}
return;
}
if result.vetoed() {
*veto = Some(result);
return;
}
*acc = Some(match acc.take() {
None => result,
Some(left) => {
let op = if term.inverse { inverse_op } else { direct_op };
let combined = if matches!(
op,
ArithmeticComputation::Divide | ArithmeticComputation::Modulo
) {
divisive_operation_results(
&left,
&fold_types[index - 1],
&op,
&result,
plan.result_type(child),
&plan.signature_index,
)
} else {
binary_arithmetic_result(
&left,
&fold_types[index - 1],
&result,
plan.result_type(child),
op,
plan,
)
};
if combined.vetoed() {
*veto = Some(combined);
return;
}
combined
}
});
}
pub(crate) fn fold_result(
acc: Option<OperationResult>,
veto: Option<OperationResult>,
) -> OperationResult {
veto.or(acc)
.expect("BUG: n-ary arithmetic produced neither value nor veto after evaluating children")
}
pub(crate) fn logical_operand(
connective: LogicalConnective,
veto: &mut Option<OperationResult>,
result: OperationResult,
) -> Option<OperationResult> {
let absorbing = connective.absorbing_operand();
match condition_outcome(&result) {
BranchOutcome::Taken if absorbing => {
Some(OperationResult::from_literal(LiteralValue::from_bool(true)))
}
BranchOutcome::NotTaken if !absorbing => Some(OperationResult::from_literal(
LiteralValue::from_bool(false),
)),
BranchOutcome::Propagate(propagated) => {
veto.get_or_insert(propagated);
None
}
BranchOutcome::Taken | BranchOutcome::NotTaken => None,
}
}
pub(crate) fn logical_result(
connective: LogicalConnective,
veto: Option<OperationResult>,
) -> OperationResult {
veto.unwrap_or_else(|| {
OperationResult::from_literal(LiteralValue::from_bool(!connective.absorbing_operand()))
})
}
pub(crate) fn find_keyed(
rows: &ListValue,
index: &KeyIndex,
fields: &[KeyField],
wanted: &[TypedLiteral],
) -> OperationResult {
match index.probe(wanted) {
Ok(Some(position)) => OperationResult::from_literal(
rows.get(position)
.expect("BUG: index position is a row of the list")
.to_literal(),
),
Ok(None) => list_ops::no_row_with_key(fields, wanted),
Err(veto) => veto,
}
}
pub(crate) fn first_operand(values: &[OperationResult]) -> OperationResult {
values
.first()
.cloned()
.expect("BUG: command operand collected before use")
}
pub(crate) fn options_rule_blocker(
plan: &ExecutionPlan,
ctx: &EvaluationContext,
path: &DataPath,
) -> Option<OperationResult> {
let rule_path = plan.options_rule_of(path)?;
let index = plan.rule_index(&rule_path);
let result = ctx.rule_values.get(index.index())?.as_ref()?;
match result.value().map(|bound| &bound.value) {
Some(crate::planning::semantics::ValueKind::List(_)) => None,
_ => Some(result.clone()),
}
}
fn check_data_options(
id: NormalFormId,
slot: OperationResult,
plan: &ExecutionPlan,
ctx: &EvaluationContext,
) -> OperationResult {
if slot.vetoed() || slot.is_missing_data() {
return slot;
}
let path = match &plan.normal_form(id).kind {
NormalFormKind::Leaf(LeafKind::DataPath(path)) => path,
other => panic!("BUG: options check on {other:?}"),
};
let lemma_type = plan
.data
.get(path)
.and_then(|definition| definition.schema_type())
.expect("BUG: options check on data without a type");
let rule_index = plan
.options_rule_of(path)
.map(|rule_path| plan.rule_index(&rule_path));
let rule_result = rule_index.map(|index| {
ctx.rule_values[index.index()]
.as_ref()
.expect("BUG: options rule checked before it was evaluated")
});
if let Some(rule_result) = rule_result {
if rule_result.vetoed() || rule_result.is_missing_data() {
return rule_result.clone();
}
}
let Some(slot_bound) = slot.value() else {
return slot;
};
let rule_rows = match rule_result {
Some(rule_result) => match rule_result.value().map(|bound| &bound.value) {
Some(ValueKind::List(rows)) => Some(rows),
_ => {
return OperationResult::Veto(VetoType::computation(
"options rule did not return a list".to_string(),
));
}
},
None => None,
};
let scales = display_scale_factors(Some(slot_bound), lemma_type, plan, ctx);
match lemma_type.explain_disallowed(&slot_bound.value, rule_rows, Some(&scales)) {
None => slot,
Some(message) => OperationResult::Veto(VetoType::computation(message)),
}
}
pub(crate) fn literal(
id: NormalFormId,
plan: &ExecutionPlan,
ctx: &EvaluationContext,
) -> OperationResult {
let NormalFormKind::Leaf(LeafKind::Literal(literal)) = &plan.normal_form(id).kind else {
panic!("BUG: cell {} is not a literal", id.index());
};
let lemma_type = plan.result_type(id).as_ref();
let unit = lemma_type.unit().map(Arc::<str>::from);
let bound = BoundValueKind::with_binding(literal.value.clone(), unit);
settle_stored(bound, lemma_type, plan, ctx)
}
pub(crate) fn stored_data_leaf(
id: NormalFormId,
slot: OperationResult,
plan: &ExecutionPlan,
ctx: &EvaluationContext,
) -> OperationResult {
let NormalFormKind::Leaf(LeafKind::DataPath(path)) = &plan.normal_form(id).kind else {
panic!("BUG: cell {} is not a data leaf", id.index());
};
let lemma_type = plan
.data
.get(path)
.and_then(|definition| definition.schema_type());
let slot = match (slot, lemma_type) {
(OperationResult::Value(bound), Some(lemma_type)) => {
settle_stored(bound, lemma_type, plan, ctx)
}
(slot, _) => slot,
};
if slot.vetoed() || slot.is_missing_data() {
return slot;
}
if let (Some(lemma_type), Some(bound)) = (lemma_type, slot.value()) {
let scales = display_scale_factors(Some(bound), lemma_type, plan, ctx);
if let Err(msg) = validate_value_against_type(
lemma_type,
&bound.to_literal(),
&plan.resolved_types.unit_index,
Some(&scales),
) {
return OperationResult::Veto(VetoType::computation(msg));
}
}
if lemma_type.is_some_and(|schema| schema.needs_runtime_option_check()) {
return check_data_options(id, slot, plan, ctx);
}
slot
}