1use crate::parsing::arena::{ExprId, ExprKind, ExprRef};
7use crate::parsing::ast::{
8 ArithmeticComputation, CalendarPeriodUnit, ComparisonComputation, ConversionTypeKind,
9 DateCalendarKind, DateRelativeKind, LogicalConnective, MathematicalComputation, RangeBound,
10 RoundingMode, VetoExpression,
11};
12use crate::planning::execution_plan::ExecutionPlan;
13use crate::planning::instance_list::{row_end_chain, RowEndView};
14use crate::planning::semantics::{
15 is_global_slot_name, DataDefinition, DataPath, Expression, ExpressionKind, GlobalKey, ListOp,
16 PathSegment, RowEnd, RulePath, SemanticConversionTarget, SpecIdentity, TypedLiteral,
17};
18use indexmap::IndexMap;
19use serde::{Deserialize, Serialize};
20use std::collections::{BTreeMap, HashSet};
21use std::sync::Arc;
22
23pub(crate) struct ShowScope<'a> {
26 pub(crate) show_keys: &'a HashSet<RulePath>,
27 pub(crate) data: &'a IndexMap<DataPath, DataDefinition>,
28 pub(crate) templates: &'a BTreeMap<SpecIdentity, Arc<ExecutionPlan>>,
29}
30
31enum ImportMember {
34 Rule(RulePath),
35 Data(DataPath),
36}
37
38impl ShowScope<'_> {
39 fn global_slot_name(&self, key: &GlobalKey) -> &str {
41 self.data
42 .iter()
43 .find_map(|(path, definition)| match definition {
44 DataDefinition::Import {
45 global: Some(slot_key),
46 ..
47 } if slot_key == key && is_global_slot_name(&path.data) => Some(path.data.as_str()),
48 _ => None,
49 })
50 .unwrap_or_else(|| panic!("BUG: plan reaches global '{key}' without its slot"))
51 }
52
53 fn import_member(
55 &self,
56 base: &ExpressionKind,
57 path: &[String],
58 name: &str,
59 ) -> Option<ImportMember> {
60 let ExpressionKind::DataPath(slot) = base else {
61 return None;
62 };
63 let Some(DataDefinition::Import { row, .. }) = self.data.get(slot) else {
64 return None;
65 };
66 let template = self.templates.get(&row.identity).unwrap_or_else(|| {
67 panic!(
68 "BUG: `uses` slot '{slot}' has no template of '{}'",
69 row.identity
70 )
71 });
72 let parts: Vec<&str> = path
73 .iter()
74 .map(String::as_str)
75 .chain(std::iter::once(name))
76 .collect();
77 let chain = row_end_chain(
78 &row.identity,
79 RowEndView::Plan(template),
80 self.templates,
81 &parts,
82 )
83 .unwrap_or_else(|| {
84 panic!(
85 "BUG: member '{}' of `uses` slot '{slot}' planned but unresolved",
86 parts.join(".")
87 )
88 });
89 let first = match self.data.get(slot) {
90 Some(DataDefinition::Import {
91 global: Some(key), ..
92 }) => self.global_slot_name(key),
93 _ => slot.data.as_str(),
94 };
95 let mut segments = vec![PathSegment::import(first, &row.identity)];
96 for (hop, next) in chain.iter().zip(chain.iter().skip(1)) {
97 let RowEnd::Data(alias) = &hop.end else {
98 panic!(
99 "BUG: a member chain hop is a `uses` slot, got {:?}",
100 hop.end
101 );
102 };
103 let hop_template = self.templates.get(&hop.identity).unwrap_or_else(|| {
104 panic!(
105 "BUG: member chain hop of '{}' has no template",
106 hop.identity
107 )
108 });
109 if let Some(DataDefinition::Import {
111 global: Some(key), ..
112 }) = hop_template.data.get(alias)
113 {
114 segments = vec![PathSegment::import(
115 self.global_slot_name(key),
116 &next.identity,
117 )];
118 continue;
119 }
120 segments.push(PathSegment::import(&alias.data, &next.identity));
121 }
122 let last = chain.last().expect("BUG: a member chain has a last end");
123 Some(match &last.end {
124 RowEnd::Rule(rule) => ImportMember::Rule(RulePath::new(segments, rule.rule.clone())),
125 RowEnd::Data(data) => ImportMember::Data(DataPath {
126 segments,
127 data: data.data.clone(),
128 }),
129 })
130 }
131}
132
133#[derive(Debug, Clone, PartialEq, Eq)]
135pub struct ShowBranch {
136 pub condition: Option<ShowExpression>,
138 pub result: ShowExpression,
139}
140
141#[derive(Debug, Clone, PartialEq, Eq)]
143pub struct ShowRule {
144 pub lemma_type: crate::planning::semantics::LemmaType,
145 pub path: Vec<crate::planning::semantics::PathSegment>,
147 pub branches: Vec<ShowBranch>,
148 pub depends_on_rules: Vec<RulePath>,
151}
152
153#[derive(Debug, Clone, PartialEq, Eq)]
155pub enum ShowConversionTarget {
156 Type(ConversionTypeKind),
157 Unit { unit_name: String },
158}
159
160#[derive(Debug, Clone, PartialEq, Eq)]
165pub enum ShowExpression {
166 Literal(Box<TypedLiteral>),
167 Data {
168 name: String,
169 },
170 Rule {
171 name: String,
172 },
173 And {
175 operands: Vec<ShowExpression>,
176 },
177 Or {
178 operands: Vec<ShowExpression>,
179 },
180 Not {
181 operand: Box<ShowExpression>,
182 },
183 Arithmetic {
185 first: Box<ShowExpression>,
186 steps: Vec<ShowArithmeticStep>,
187 },
188 Comparison {
189 op: ComparisonComputation,
190 left: Box<ShowExpression>,
191 right: Box<ShowExpression>,
192 },
193 UnitConversion {
195 operand: Box<ShowExpression>,
196 targets: Vec<ShowConversionTarget>,
197 },
198 Math {
199 op: MathematicalComputation,
200 operand: Box<ShowExpression>,
201 },
202 StepRounding {
204 mode: RoundingMode,
205 operand: Box<ShowExpression>,
206 step: Option<Box<ShowExpression>>,
207 },
208 Veto {
209 message: Option<String>,
210 },
211 Now,
212 DateRelative {
213 kind: DateRelativeKind,
214 operand: Box<ShowExpression>,
215 },
216 DateCalendar {
217 kind: DateCalendarKind,
218 unit: CalendarPeriodUnit,
219 operand: Box<ShowExpression>,
220 },
221 RangeLiteral {
222 from: Box<ShowExpression>,
223 to: Box<ShowExpression>,
224 },
225 PastFutureRange {
226 kind: DateRelativeKind,
227 operand: Box<ShowExpression>,
228 },
229 RangeContainment {
230 value: Box<ShowExpression>,
231 range: Box<ShowExpression>,
232 },
233 RangeBound {
234 bound: RangeBound,
235 operand: Box<ShowExpression>,
236 },
237 IsVeto {
238 operand: Box<ShowExpression>,
239 },
240 SpecMember {
242 base: String,
243 member: String,
244 },
245 Member {
247 base: Box<ShowExpression>,
248 member: String,
249 },
250 RowField {
252 field: String,
253 qualifier: Option<Vec<String>>,
255 },
256 RowValue,
258 RowFieldValue {
260 field: String,
261 value: Box<ShowExpression>,
262 },
263 ListCommand {
265 list: Box<ShowExpression>,
266 command: ShowListCommand,
267 direction: Option<SortDirection>,
268 args: Vec<ShowExpression>,
269 },
270}
271
272#[derive(Debug, Clone, PartialEq, Eq)]
274pub struct ShowArithmeticStep {
275 pub op: ArithmeticComputation,
276 pub operand: ShowExpression,
277}
278
279#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
281#[serde(rename_all = "snake_case")]
282pub enum ShowListCommand {
283 Find,
284 First,
285 Last,
286 Count,
287 Sum,
288 Avg,
289 Product,
290 Min,
291 Max,
292 Any,
293 All,
294 Where,
295 Sort,
296 Top,
297 With,
298 Key,
299}
300
301#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
302#[serde(rename_all = "snake_case")]
303pub enum SortDirection {
304 Asc,
305 Desc,
306}
307
308impl ShowExpression {
309 pub(crate) fn operands(&self) -> Vec<&ShowExpression> {
311 match self {
312 Self::Literal(_)
313 | Self::Data { .. }
314 | Self::Rule { .. }
315 | Self::Veto { .. }
316 | Self::Now
317 | Self::SpecMember { .. }
318 | Self::RowField { .. }
319 | Self::RowValue => Vec::new(),
320 Self::And { operands } | Self::Or { operands } => operands.iter().collect(),
321 Self::Not { operand }
322 | Self::UnitConversion { operand, .. }
323 | Self::Math { operand, .. }
324 | Self::DateRelative { operand, .. }
325 | Self::DateCalendar { operand, .. }
326 | Self::PastFutureRange { operand, .. }
327 | Self::RangeBound { operand, .. }
328 | Self::IsVeto { operand } => vec![operand.as_ref()],
329 Self::Arithmetic { first, steps } => {
330 let mut out = vec![first.as_ref()];
331 out.extend(steps.iter().map(|step| &step.operand));
332 out
333 }
334 Self::Comparison { left, right, .. }
335 | Self::RangeLiteral {
336 from: left,
337 to: right,
338 }
339 | Self::RangeContainment {
340 value: left,
341 range: right,
342 } => vec![left.as_ref(), right.as_ref()],
343 Self::StepRounding { operand, step, .. } => {
344 let mut out = vec![operand.as_ref()];
345 if let Some(step) = step {
346 out.push(step.as_ref());
347 }
348 out
349 }
350 Self::Member { base, .. } => vec![base.as_ref()],
351 Self::RowFieldValue { value, .. } => vec![value.as_ref()],
352 Self::ListCommand { list, args, .. } => {
353 let mut out = vec![list.as_ref()];
354 out.extend(args.iter());
355 out
356 }
357 }
358 }
359
360 pub(crate) fn fold<U>(&self, mut step: impl FnMut(&ShowExpression, Vec<U>) -> U) -> U {
363 let mut values: Vec<U> = Vec::new();
364 let mut stack: Vec<(&ShowExpression, bool)> = vec![(self, false)];
365 while let Some((node, expanded)) = stack.pop() {
366 let operands = node.operands();
367 if !expanded {
368 stack.push((node, true));
369 stack.extend(operands.iter().rev().map(|&operand| (operand, false)));
370 continue;
371 }
372 let split = values
373 .len()
374 .checked_sub(operands.len())
375 .expect("BUG: operand folded before its parent");
376 let args = values.split_off(split);
377 values.push(step(node, args));
378 }
379 values
380 .pop()
381 .expect("BUG: fold produced no value for its root")
382 }
383}
384
385pub(crate) fn take_operand<T, I: Iterator<Item = T>>(operands: &mut I) -> T {
387 operands
388 .next()
389 .expect("BUG: operand missing for its parent node")
390}
391
392fn project(
399 root: ExprRef<'_, ExpressionKind>,
400 scope: &ShowScope<'_>,
401 scratch: &mut ProjectScratch,
402) -> ShowExpression {
403 let ProjectScratch { values, stack } = scratch;
404 stack.push((root.id, false));
405 while let Some((id, expanded)) = stack.pop() {
406 let node = root.child(id);
407 if !expanded {
408 stack.push((id, true));
409 let start = stack.len();
410 for_each_projection_operand(node, scope, |operand| stack.push((operand, false)));
411 stack[start..].reverse();
412 continue;
413 }
414 let mut arity = 0;
415 for_each_projection_operand(node, scope, |_| arity += 1);
416 let split = values
417 .len()
418 .checked_sub(arity)
419 .expect("BUG: operand projected before its parent");
420 let shown = project_node(node, values.drain(split..), scope);
421 values.push(shown);
422 }
423 let shown = values
424 .pop()
425 .expect("BUG: projection produced no value for its root");
426 assert!(
427 values.is_empty(),
428 "BUG: projection left operands without a parent"
429 );
430 shown
431}
432
433#[derive(Default)]
435struct ProjectScratch {
436 values: Vec<ShowExpression>,
437 stack: Vec<(ExprId, bool)>,
438}
439
440fn for_each_projection_operand(
444 node: ExprRef<'_, ExpressionKind>,
445 scope: &ShowScope<'_>,
446 mut f: impl FnMut(ExprId),
447) {
448 match node.kind() {
449 ExpressionKind::Piecewise(_) => {}
450 ExpressionKind::SpecMember { base, path, name } => {
451 let base_kind = node.child(*base).kind();
452 if !matches!(base_kind, ExpressionKind::RulePath(_))
453 && scope.import_member(base_kind, path, name).is_none()
454 {
455 f(*base);
456 }
457 }
458 ExpressionKind::UnitConversion(_, _) => f(conversion_operand(node)),
459 other => other.for_each_child(f),
460 }
461}
462
463fn conversion_operand(node: ExprRef<'_, ExpressionKind>) -> ExprId {
465 let mut current = node;
466 while let ExpressionKind::UnitConversion(operand, _) = current.kind() {
467 current = current.child(*operand);
468 }
469 current.id
470}
471
472fn conversion_run(node: ExprRef<'_, ExpressionKind>) -> (ExprId, Vec<ShowConversionTarget>) {
474 let mut current = node;
475 let mut targets = Vec::new();
476 while let ExpressionKind::UnitConversion(operand, target) = current.kind() {
477 targets.push(conversion_target_from(target));
478 current = current.child(*operand);
479 }
480 targets.reverse();
481 (current.id, targets)
482}
483
484fn project_node(
486 node: ExprRef<'_, ExpressionKind>,
487 mut operands: std::vec::Drain<'_, ShowExpression>,
488 scope: &ShowScope<'_>,
489) -> ShowExpression {
490 let show_keys = scope.show_keys;
491 match node.kind() {
492 ExpressionKind::Literal(typed) => ShowExpression::Literal(Box::new(typed.as_ref().clone())),
493 ExpressionKind::DataPath(path) => ShowExpression::Data {
494 name: path.input_key(),
495 },
496 ExpressionKind::RulePath(path) => {
497 if !show_keys.contains(path) {
498 panic!(
499 "BUG: rule leaf '{}' not in Show.rules keys",
500 path.input_key()
501 );
502 }
503 ShowExpression::Rule {
504 name: path.input_key(),
505 }
506 }
507 ExpressionKind::Logical { connective, .. } => match connective {
508 LogicalConnective::And => ShowExpression::And {
509 operands: operands.collect(),
510 },
511 LogicalConnective::Or => ShowExpression::Or {
512 operands: operands.collect(),
513 },
514 },
515 ExpressionKind::LogicalNegation(_, _) => ShowExpression::Not {
516 operand: Box::new(take_operand(&mut operands)),
517 },
518 ExpressionKind::Arithmetic { steps, .. } => {
519 let first = Box::new(take_operand(&mut operands));
520 let steps = steps
521 .iter()
522 .map(|step| ShowArithmeticStep {
523 op: step.op.clone(),
524 operand: take_operand(&mut operands),
525 })
526 .collect();
527 ShowExpression::Arithmetic { first, steps }
528 }
529 ExpressionKind::Comparison(_, op, _) => {
530 let left = Box::new(take_operand(&mut operands));
531 let right = Box::new(take_operand(&mut operands));
532 ShowExpression::Comparison {
533 op: op.clone(),
534 left,
535 right,
536 }
537 }
538 ExpressionKind::UnitConversion(_, _) => {
539 let (_, targets) = conversion_run(node);
540 ShowExpression::UnitConversion {
541 operand: Box::new(take_operand(&mut operands)),
542 targets,
543 }
544 }
545 ExpressionKind::MathematicalComputation(op, _) => ShowExpression::Math {
546 op: op.clone(),
547 operand: Box::new(take_operand(&mut operands)),
548 },
549 ExpressionKind::StepRounding { mode, step, .. } => {
550 let operand = Box::new(take_operand(&mut operands));
551 ShowExpression::StepRounding {
552 mode: *mode,
553 operand,
554 step: step.map(|_| Box::new(take_operand(&mut operands))),
555 }
556 }
557 ExpressionKind::Veto(VetoExpression { message }) => ShowExpression::Veto {
558 message: message.clone(),
559 },
560 ExpressionKind::Now => ShowExpression::Now,
561 ExpressionKind::DateRelative(kind, _) => ShowExpression::DateRelative {
562 kind: *kind,
563 operand: Box::new(take_operand(&mut operands)),
564 },
565 ExpressionKind::DateCalendar(kind, unit, _) => ShowExpression::DateCalendar {
566 kind: *kind,
567 unit: *unit,
568 operand: Box::new(take_operand(&mut operands)),
569 },
570 ExpressionKind::RangeLiteral(_, _) => {
571 let from = Box::new(take_operand(&mut operands));
572 let to = Box::new(take_operand(&mut operands));
573 ShowExpression::RangeLiteral { from, to }
574 }
575 ExpressionKind::PastFutureRange(kind, _) => ShowExpression::PastFutureRange {
576 kind: *kind,
577 operand: Box::new(take_operand(&mut operands)),
578 },
579 ExpressionKind::RangeContainment(_, _) => {
580 let value = Box::new(take_operand(&mut operands));
581 let range = Box::new(take_operand(&mut operands));
582 ShowExpression::RangeContainment { value, range }
583 }
584 ExpressionKind::RangeBound(bound, _) => ShowExpression::RangeBound {
585 bound: *bound,
586 operand: Box::new(take_operand(&mut operands)),
587 },
588 ExpressionKind::ResultIsVeto(_) => ShowExpression::IsVeto {
589 operand: Box::new(take_operand(&mut operands)),
590 },
591 ExpressionKind::Piecewise(_) => {
592 panic!("BUG: piecewise inside a rule branch")
593 }
594 ExpressionKind::SpecMember { base, path, name } => {
595 match scope.import_member(node.child(*base).kind(), path, name) {
596 Some(ImportMember::Rule(rule)) => {
597 if !show_keys.contains(&rule) {
598 panic!(
599 "BUG: `uses` member rule '{}' not in Show.rules keys",
600 rule.input_key()
601 );
602 }
603 return ShowExpression::Rule {
604 name: rule.input_key(),
605 };
606 }
607 Some(ImportMember::Data(data)) => {
608 return ShowExpression::Data {
609 name: data.input_key(),
610 };
611 }
612 None => {}
613 }
614 let mut member = String::new();
615 for segment in path {
616 member.push_str(segment);
617 member.push('.');
618 }
619 member.push_str(name);
620 match node.child(*base).kind() {
621 ExpressionKind::RulePath(rule) => {
622 if !show_keys.contains(rule) {
623 panic!(
624 "BUG: spec member base '{}' not in Show.rules keys",
625 rule.input_key()
626 );
627 }
628 ShowExpression::SpecMember {
629 base: rule.input_key(),
630 member,
631 }
632 }
633 _ => ShowExpression::Member {
634 base: Box::new(take_operand(&mut operands)),
635 member,
636 },
637 }
638 }
639 ExpressionKind::RowField { end, qualifier, .. } => ShowExpression::RowField {
640 field: end.to_string(),
641 qualifier: qualifier.clone(),
642 },
643 ExpressionKind::RowValue { .. } => ShowExpression::RowValue,
644 ExpressionKind::ListCommand { op, .. } => {
645 let list = Box::new(take_operand(&mut operands));
646 let (command, direction, args) = show_list_op(op, &mut operands);
647 ShowExpression::ListCommand {
648 list,
649 command,
650 direction,
651 args,
652 }
653 }
654 }
655}
656
657fn show_list_op(
659 op: &ListOp,
660 operands: &mut std::vec::Drain<'_, ShowExpression>,
661) -> (ShowListCommand, Option<SortDirection>, Vec<ShowExpression>) {
662 use crate::planning::semantics::{ListPredKind, ListReduce};
663 let predicate = |kind: &ListPredKind| match kind {
664 ListPredKind::Any => ShowListCommand::Any,
665 ListPredKind::All => ShowListCommand::All,
666 ListPredKind::Where => ShowListCommand::Where,
667 };
668 match op {
669 ListOp::Find { keys } => (
670 ShowListCommand::Find,
671 None,
672 operands.by_ref().take(keys.len()).collect(),
673 ),
674 ListOp::First => (ShowListCommand::First, None, Vec::new()),
675 ListOp::Last => (ShowListCommand::Last, None, Vec::new()),
676 ListOp::Count => (ShowListCommand::Count, None, Vec::new()),
677 ListOp::Reduce { kind, argument } => {
678 let command = match kind {
679 ListReduce::Sum => ShowListCommand::Sum,
680 ListReduce::Avg => ShowListCommand::Avg,
681 ListReduce::Product => ShowListCommand::Product,
682 ListReduce::Min => ShowListCommand::Min,
683 ListReduce::Max => ShowListCommand::Max,
684 };
685 let args = if argument.is_some() {
686 vec![take_operand(operands)]
687 } else {
688 Vec::new()
689 };
690 (command, None, args)
691 }
692 ListOp::Predicate { kind, .. } => (predicate(kind), None, vec![take_operand(operands)]),
693 ListOp::Sort {
694 descending,
695 argument,
696 } => {
697 let direction = if *descending {
698 SortDirection::Desc
699 } else {
700 SortDirection::Asc
701 };
702 let args = if argument.is_some() {
703 vec![take_operand(operands)]
704 } else {
705 Vec::new()
706 };
707 (ShowListCommand::Sort, Some(direction), args)
708 }
709 ListOp::Top { .. } => (ShowListCommand::Top, None, vec![take_operand(operands)]),
710 ListOp::With { rows } => (
711 ShowListCommand::With,
712 None,
713 operands.by_ref().take(rows.len()).collect(),
714 ),
715 ListOp::WithRow { fields, .. } => (
716 ShowListCommand::With,
717 None,
718 fields
719 .iter()
720 .map(|(path, _)| ShowExpression::RowFieldValue {
721 field: path.input_key(),
722 value: Box::new(take_operand(operands)),
723 })
724 .collect(),
725 ),
726 ListOp::Key { fields } => (
727 ShowListCommand::Key,
728 None,
729 fields
730 .iter()
731 .map(|path| ShowExpression::Data {
732 name: path.input_key(),
733 })
734 .collect(),
735 ),
736 }
737}
738
739pub(crate) fn show_branches_from(
741 expression: &Expression,
742 branches: &[(Option<ExprId>, ExprId)],
743 scope: &ShowScope<'_>,
744) -> Vec<ShowBranch> {
745 let mut scratch = ProjectScratch::default();
746 branches
747 .iter()
748 .map(|(condition, result)| ShowBranch {
749 condition: condition
750 .map(|condition| project(expression.at(condition), scope, &mut scratch)),
751 result: project(expression.at(*result), scope, &mut scratch),
752 })
753 .collect()
754}
755
756pub fn project_depends_on_rules(
761 deps: &std::collections::BTreeSet<RulePath>,
762 catalog_keys: &HashSet<RulePath>,
763) -> Vec<RulePath> {
764 let mut out = Vec::new();
765 for path in deps {
766 if catalog_keys.contains(path) {
767 out.push(path.clone());
768 } else if path.segments.is_empty() {
769 panic!(
770 "BUG: local depends_on_rules entry '{}' missing from Show.rules keys",
771 path.input_key()
772 );
773 }
774 }
775 out
776}
777
778fn conversion_target_from(target: &SemanticConversionTarget) -> ShowConversionTarget {
779 match target {
780 SemanticConversionTarget::Type(kind) => ShowConversionTarget::Type(*kind),
781 SemanticConversionTarget::Unit { unit_name, .. } => ShowConversionTarget::Unit {
782 unit_name: unit_name.clone(),
783 },
784 }
785}