1use crate::api::types::LemmaType;
5use crate::api::value::RuleResultValue;
6use crate::parsing::ast::{
7 ArithmeticComputation, CalendarPeriodUnit, ComparisonComputation, ConversionTypeKind,
8 DateCalendarKind, DateRelativeKind, MathematicalComputation, RangeBound, RoundingMode,
9};
10use crate::planning::execution_plan::{
11 ExecutionPlan, ListWrites, Show as DomainShow, ShowBranch as DomainShowBranch,
12 ShowConversionTarget as DomainConversionTarget, ShowData as DomainShowData,
13 ShowExpression as DomainShowExpression, ShowRule as DomainShowRule,
14};
15pub use crate::planning::execution_plan::{ShowListCommand, SortDirection};
16use crate::planning::semantics::{
17 LemmaType as DomainLemmaType, PathSegment as DomainPathSegment, SpecIdentity,
18 TypeSpecification as DomainTypeSpecification,
19};
20use crate::planning::show_expression::take_operand;
21use crate::result_value::{
22 type_scoped_result_value_from_literal, RuleResultValue as DomainRuleResultValue,
23};
24use crate::Engine;
25use indexmap::IndexMap;
26use serde::{Deserialize, Serialize};
27use serde_json::{json, Map, Value as JsonValue};
28use std::collections::{BTreeMap, BTreeSet};
29use std::sync::Arc;
30
31#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
34pub struct PathSegment {
35 pub uses: String,
36 #[serde(skip_serializing_if = "Option::is_none", default)]
38 pub row: Option<usize>,
39 #[serde(skip_serializing_if = "Option::is_none", default)]
40 pub repository: Option<String>,
41 pub spec: String,
42}
43
44impl From<&DomainPathSegment> for PathSegment {
45 fn from(segment: &DomainPathSegment) -> Self {
46 Self {
47 uses: segment.uses.to_string(),
48 row: segment.row,
49 repository: segment.repository.as_ref().map(|arc| arc.to_string()),
50 spec: segment.spec.to_string(),
51 }
52 }
53}
54
55#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
56#[serde(rename_all = "snake_case")]
57pub enum ShowConversionTarget {
58 Type(ConversionTypeKind),
59 Unit { unit_name: String },
60}
61
62impl From<&DomainConversionTarget> for ShowConversionTarget {
63 fn from(target: &DomainConversionTarget) -> Self {
64 match target {
65 DomainConversionTarget::Type(kind) => Self::Type(*kind),
66 DomainConversionTarget::Unit { unit_name } => Self::Unit {
67 unit_name: unit_name.clone(),
68 },
69 }
70 }
71}
72
73#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
75#[serde(tag = "type", rename_all = "snake_case")]
76pub enum ShowExpression {
77 Literal {
78 #[serde(flatten)]
79 value: Box<RuleResultValue>,
80 },
81 Data {
82 name: String,
83 },
84 Rule {
85 name: String,
86 },
87 And {
88 operands: Vec<ShowExpression>,
89 },
90 Or {
91 operands: Vec<ShowExpression>,
92 },
93 Not {
94 operand: Box<ShowExpression>,
95 },
96 Arithmetic {
97 first: Box<ShowExpression>,
98 steps: Vec<ShowArithmeticStep>,
99 },
100 Comparison {
101 op: ComparisonComputation,
102 left: Box<ShowExpression>,
103 right: Box<ShowExpression>,
104 },
105 UnitConversion {
106 operand: Box<ShowExpression>,
107 targets: Vec<ShowConversionTarget>,
108 },
109 Math {
110 op: MathematicalComputation,
111 operand: Box<ShowExpression>,
112 },
113 StepRounding {
114 mode: RoundingMode,
115 operand: Box<ShowExpression>,
116 #[serde(skip_serializing_if = "Option::is_none", default)]
117 step: Option<Box<ShowExpression>>,
118 },
119 Veto {
120 #[serde(skip_serializing_if = "Option::is_none", default)]
121 message: Option<String>,
122 },
123 Now,
124 DateRelative {
125 kind: DateRelativeKind,
126 operand: Box<ShowExpression>,
127 },
128 DateCalendar {
129 kind: DateCalendarKind,
130 unit: CalendarPeriodUnit,
131 operand: Box<ShowExpression>,
132 },
133 RangeLiteral {
134 from: Box<ShowExpression>,
135 to: Box<ShowExpression>,
136 },
137 PastFutureRange {
138 kind: DateRelativeKind,
139 operand: Box<ShowExpression>,
140 },
141 RangeContainment {
142 value: Box<ShowExpression>,
143 range: Box<ShowExpression>,
144 },
145 RangeBound {
146 bound: RangeBound,
147 operand: Box<ShowExpression>,
148 },
149 IsVeto {
150 operand: Box<ShowExpression>,
151 },
152 SpecMember {
153 base: String,
154 member: String,
155 },
156 Member {
157 base: Box<ShowExpression>,
158 member: String,
159 },
160 RowField {
161 field: String,
162 #[serde(default, skip_serializing_if = "Option::is_none")]
163 qualifier: Option<Vec<String>>,
164 },
165 RowValue,
166 RowFieldValue {
167 field: String,
168 value: Box<ShowExpression>,
169 },
170 ListCommand {
171 list: Box<ShowExpression>,
172 command: ShowListCommand,
173 #[serde(skip_serializing_if = "Option::is_none", default)]
174 direction: Option<SortDirection>,
175 args: Vec<ShowExpression>,
176 },
177}
178
179#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
181pub struct ShowArithmeticStep {
182 pub op: ArithmeticComputation,
183 pub operand: ShowExpression,
184}
185
186impl From<&DomainShowExpression> for ShowExpression {
187 fn from(expression: &DomainShowExpression) -> Self {
188 expression.fold(convert_show_node)
189 }
190}
191
192fn convert_show_node(node: &DomainShowExpression, operands: Vec<ShowExpression>) -> ShowExpression {
195 let mut operands = operands.into_iter();
196 match node {
197 DomainShowExpression::Literal(typed) => {
198 let domain_value = type_scoped_result_value_from_literal(
199 &typed.to_literal(),
200 typed.lemma_type.as_ref(),
201 )
202 .unwrap_or_else(|failure| {
203 panic!(
204 "BUG: show branch literal failed type_scoped_result_value_from_literal: {}",
205 crate::result_value::rule_result_value_failure_message(failure)
206 )
207 });
208 ShowExpression::Literal {
209 value: Box::new(RuleResultValue::from(&domain_value)),
210 }
211 }
212 DomainShowExpression::Data { name } => ShowExpression::Data { name: name.clone() },
213 DomainShowExpression::Rule { name } => ShowExpression::Rule { name: name.clone() },
214 DomainShowExpression::And { .. } => ShowExpression::And {
215 operands: operands.collect(),
216 },
217 DomainShowExpression::Or { .. } => ShowExpression::Or {
218 operands: operands.collect(),
219 },
220 DomainShowExpression::Not { .. } => ShowExpression::Not {
221 operand: Box::new(take_operand(&mut operands)),
222 },
223 DomainShowExpression::Arithmetic { steps, .. } => {
224 let first = Box::new(take_operand(&mut operands));
225 let steps = steps
226 .iter()
227 .map(|step| ShowArithmeticStep {
228 op: step.op.clone(),
229 operand: take_operand(&mut operands),
230 })
231 .collect();
232 ShowExpression::Arithmetic { first, steps }
233 }
234 DomainShowExpression::Comparison { op, .. } => {
235 let left = Box::new(take_operand(&mut operands));
236 let right = Box::new(take_operand(&mut operands));
237 ShowExpression::Comparison {
238 op: op.clone(),
239 left,
240 right,
241 }
242 }
243 DomainShowExpression::UnitConversion { targets, .. } => ShowExpression::UnitConversion {
244 operand: Box::new(take_operand(&mut operands)),
245 targets: targets.iter().map(ShowConversionTarget::from).collect(),
246 },
247 DomainShowExpression::Math { op, .. } => ShowExpression::Math {
248 op: op.clone(),
249 operand: Box::new(take_operand(&mut operands)),
250 },
251 DomainShowExpression::StepRounding { mode, step, .. } => {
252 let operand = Box::new(take_operand(&mut operands));
253 ShowExpression::StepRounding {
254 mode: *mode,
255 operand,
256 step: step.as_ref().map(|_| Box::new(take_operand(&mut operands))),
257 }
258 }
259 DomainShowExpression::Veto { message } => ShowExpression::Veto {
260 message: message.clone(),
261 },
262 DomainShowExpression::Now => ShowExpression::Now,
263 DomainShowExpression::DateRelative { kind, .. } => ShowExpression::DateRelative {
264 kind: *kind,
265 operand: Box::new(take_operand(&mut operands)),
266 },
267 DomainShowExpression::DateCalendar { kind, unit, .. } => ShowExpression::DateCalendar {
268 kind: *kind,
269 unit: *unit,
270 operand: Box::new(take_operand(&mut operands)),
271 },
272 DomainShowExpression::RangeLiteral { .. } => {
273 let from = Box::new(take_operand(&mut operands));
274 let to = Box::new(take_operand(&mut operands));
275 ShowExpression::RangeLiteral { from, to }
276 }
277 DomainShowExpression::PastFutureRange { kind, .. } => ShowExpression::PastFutureRange {
278 kind: *kind,
279 operand: Box::new(take_operand(&mut operands)),
280 },
281 DomainShowExpression::RangeContainment { .. } => {
282 let value = Box::new(take_operand(&mut operands));
283 let range = Box::new(take_operand(&mut operands));
284 ShowExpression::RangeContainment { value, range }
285 }
286 DomainShowExpression::RangeBound { bound, .. } => ShowExpression::RangeBound {
287 bound: *bound,
288 operand: Box::new(take_operand(&mut operands)),
289 },
290 DomainShowExpression::IsVeto { .. } => ShowExpression::IsVeto {
291 operand: Box::new(take_operand(&mut operands)),
292 },
293 DomainShowExpression::SpecMember { base, member } => ShowExpression::SpecMember {
294 base: base.clone(),
295 member: member.clone(),
296 },
297 DomainShowExpression::Member { member, .. } => ShowExpression::Member {
298 base: Box::new(take_operand(&mut operands)),
299 member: member.clone(),
300 },
301 DomainShowExpression::RowField { field, qualifier } => ShowExpression::RowField {
302 field: field.clone(),
303 qualifier: qualifier.clone(),
304 },
305 DomainShowExpression::RowValue => ShowExpression::RowValue,
306 DomainShowExpression::RowFieldValue { field, .. } => ShowExpression::RowFieldValue {
307 field: field.clone(),
308 value: Box::new(take_operand(&mut operands)),
309 },
310 DomainShowExpression::ListCommand {
311 command, direction, ..
312 } => {
313 let list = Box::new(take_operand(&mut operands));
314 ShowExpression::ListCommand {
315 list,
316 command: *command,
317 direction: *direction,
318 args: operands.collect(),
319 }
320 }
321 }
322}
323
324#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
325pub struct ShowBranch {
326 #[serde(skip_serializing_if = "Option::is_none", default)]
327 pub condition: Option<ShowExpression>,
328 pub result: ShowExpression,
329}
330
331impl From<&DomainShowBranch> for ShowBranch {
332 fn from(branch: &DomainShowBranch) -> Self {
333 Self {
334 condition: branch.condition.as_ref().map(ShowExpression::from),
335 result: ShowExpression::from(&branch.result),
336 }
337 }
338}
339
340#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
341pub struct ShowRule {
342 #[serde(rename = "type")]
343 pub lemma_type: LemmaType,
344 pub path: Vec<PathSegment>,
345 pub branches: Vec<ShowBranch>,
346 pub depends_on_rules: Vec<String>,
347}
348
349impl From<&DomainShowRule> for ShowRule {
350 fn from(rule: &DomainShowRule) -> Self {
351 Self {
352 lemma_type: LemmaType::from(&rule.lemma_type),
353 path: rule.path.iter().map(PathSegment::from).collect(),
354 branches: rule.branches.iter().map(ShowBranch::from).collect(),
355 depends_on_rules: rule
356 .depends_on_rules
357 .iter()
358 .map(|path| path.input_key())
359 .collect(),
360 }
361 }
362}
363
364const JSON_SCHEMA_DIALECT: &str = "https://json-schema.org/draft/2020-12/schema";
365
366const BOOLEAN_TEXT_PATTERN: &str =
368 r"^\s*(?:[Tt][Rr][Uu][Ee]|[Ff][Aa][Ll][Ss][Ee]|[Yy][Ee][Ss]|[Nn][Oo])\s*$";
369
370pub fn show_document(engine: &Engine, show: &DomainShow) -> JsonValue {
380 let consumer = match engine.plan_matching_show(show) {
381 Some(plan) => Some(plan),
382 None if !show_has_instance_list(show) => None,
383 None => panic!(
384 "BUG: Show '{}' has instance-list inputs but no matching execution plan",
385 show.spec
386 ),
387 };
388 let mut rows = RowSchemas::new(engine, consumer);
389 let mut document = Map::new();
390 document.insert("$schema".to_string(), json!(JSON_SCHEMA_DIALECT));
391 document.insert("title".to_string(), json!(show.spec));
392 if let Some(commentary) = &show.commentary {
393 document.insert("description".to_string(), json!(commentary));
394 }
395 document.extend(input_object_schema(show, &mut rows));
396 let (defs, row_field_needed_by_rules) = rows.into_defs();
397 if !defs.is_empty() {
398 document.insert("$defs".to_string(), JsonValue::Object(defs));
399 }
400 if !row_field_needed_by_rules.is_empty() {
401 document.insert(
405 "x-lemma-row-field-needed-by-rules".to_string(),
406 JsonValue::Object(row_field_needed_by_rules),
407 );
408 }
409 if let Some(repository) = &show.repository {
410 document.insert("x-lemma-repository".to_string(), json!(repository));
411 }
412 if let Some(from) = &show.effective_from {
413 document.insert("x-lemma-effective-from".to_string(), to_json(from));
414 }
415 if let Some(to) = &show.effective_to {
416 document.insert("x-lemma-effective-to".to_string(), to_json(to));
417 }
418 document.insert("x-lemma-start-line".to_string(), json!(show.start_line));
419 if let Some(source_type) = &show.source_type {
420 document.insert("x-lemma-source-type".to_string(), to_json(source_type));
421 }
422 document.insert("x-lemma-meta".to_string(), to_json(&show.meta));
423 let types: IndexMap<&String, LemmaType> = show
424 .types
425 .iter()
426 .map(|(name, lemma_type)| (name, LemmaType::from(lemma_type)))
427 .collect();
428 document.insert("x-lemma-types".to_string(), to_json(&types));
429 let rules: IndexMap<&String, ShowRule> = show
430 .rules
431 .iter()
432 .map(|(name, rule)| (name, ShowRule::from(rule)))
433 .collect();
434 document.insert("x-lemma-rules".to_string(), to_json(&rules));
435 JsonValue::Object(document)
436}
437
438fn to_json<T: Serialize>(value: &T) -> JsonValue {
439 serde_json::to_value(value).expect("BUG: Show document parts serialize to JSON")
440}
441
442fn show_has_instance_list(show: &DomainShow) -> bool {
443 show.data.values().any(|data| {
444 matches!(
445 &data.lemma_type.specifications,
446 DomainTypeSpecification::List { element, .. }
447 if matches!(&element.specifications, DomainTypeSpecification::Spec { .. })
448 )
449 })
450}
451
452fn input_object_schema(show: &DomainShow, rows: &mut RowSchemas) -> Map<String, JsonValue> {
456 let mut properties = Map::new();
457 let mut required = Vec::new();
458 for (name, data) in &show.data {
459 properties.insert(
460 name.clone(),
461 property_schema(data, rows, &data.needed_by_rules),
462 );
463 let is_list = matches!(
464 data.lemma_type.specifications,
465 DomainTypeSpecification::List { .. }
466 );
467 if data.value.is_none() && !data.needed_by_rules.is_empty() && !is_list {
468 required.push(name.clone());
469 }
470 }
471 required.sort();
472 let mut schema = Map::new();
473 schema.insert("type".to_string(), json!("object"));
474 schema.insert("additionalProperties".to_string(), json!(true));
475 schema.insert("properties".to_string(), JsonValue::Object(properties));
476 if !required.is_empty() {
477 schema.insert("required".to_string(), json!(required));
478 }
479 schema
480}
481
482fn row_object_schema(
490 show: &DomainShow,
491 list_writes: Option<&ListWrites>,
492 rows: &mut RowSchemas,
493) -> Map<String, JsonValue> {
494 let is_written_by_list =
495 |name: &String| list_writes.is_some_and(|rows| rows.fields.contains(name));
496 let mut properties = Map::new();
497 let mut required = Vec::new();
498 for (name, lemma_type) in &show.types {
499 if is_written_by_list(name) {
500 continue;
501 }
502 let stub;
503 let entry = match show.data.get(name) {
504 Some(data) => data,
505 None => {
506 stub = DomainShowData {
507 lemma_type: lemma_type.clone(),
508 path: Vec::new(),
509 value: None,
510 suggestion: None,
511 needed_by_rules: Vec::new(),
512 list_writes: None,
513 };
514 &stub
515 }
516 };
517 let is_list = matches!(
518 entry.lemma_type.specifications,
519 DomainTypeSpecification::List { .. }
520 );
521 if entry.value.is_none() && !is_list {
522 required.push(name.clone());
523 }
524 properties.insert(name.clone(), property_schema(entry, rows, &[]));
525 }
526 for (name, data) in row_data(show) {
527 if properties.contains_key(name) || is_written_by_list(name) {
528 continue;
529 }
530 let is_list = matches!(
531 data.lemma_type.specifications,
532 DomainTypeSpecification::List { .. }
533 );
534 if data.value.is_none() && !is_list {
535 required.push(name.clone());
536 }
537 properties.insert(name.clone(), property_schema(data, rows, &[]));
538 }
539 required.sort();
540 let mut schema = Map::new();
541 schema.insert("type".to_string(), json!("object"));
542 schema.insert("additionalProperties".to_string(), json!(true));
543 schema.insert("properties".to_string(), JsonValue::Object(properties));
544 if !required.is_empty() {
545 schema.insert("required".to_string(), json!(required));
546 }
547 schema
548}
549
550fn row_data(show: &DomainShow) -> impl Iterator<Item = (&String, &DomainShowData)> {
553 show.data.iter().filter(|(_, data)| !data.is_global())
554}
555
556fn row_property_names(show: &DomainShow) -> BTreeSet<String> {
557 let mut names: BTreeSet<String> = show.types.keys().cloned().collect();
558 names.extend(row_data(show).map(|(name, _)| name.clone()));
559 names
560}
561
562fn property_schema(
563 data: &DomainShowData,
564 rows: &mut RowSchemas,
565 needed_by_rules: &[String],
566) -> JsonValue {
567 let mut schema = type_schema(&data.lemma_type, data.list_writes.as_ref(), rows);
568 let help = specification_help(&data.lemma_type.specifications);
569 if !help.is_empty() {
570 schema.insert("description".to_string(), json!(help));
571 }
572 if let Some(value) = &data.value {
573 if !rule_result_value_has_reference(value) {
576 schema.insert(
577 "default".to_string(),
578 input_literal(value, &data.lemma_type, rows),
579 );
580 }
581 }
582 if let Some(suggestion) = &data.suggestion {
583 schema.insert(
584 "examples".to_string(),
585 json!([input_literal(suggestion, &data.lemma_type, rows)]),
586 );
587 }
588 schema.insert(
589 "x-lemma-type".to_string(),
590 lemma_type_without_standard_keywords(&data.lemma_type),
591 );
592 let path: Vec<PathSegment> = data.path.iter().map(PathSegment::from).collect();
593 schema.insert("x-lemma-path".to_string(), to_json(&path));
594 schema.insert(
595 "x-lemma-needed-by-rules".to_string(),
596 json!(needed_by_rules),
597 );
598 if let Some(value) = &data.value {
599 schema.insert(
600 "x-lemma-value".to_string(),
601 to_json(&RuleResultValue::from(value)),
602 );
603 }
604 if let Some(suggestion) = &data.suggestion {
605 schema.insert(
606 "x-lemma-suggestion".to_string(),
607 to_json(&RuleResultValue::from(suggestion)),
608 );
609 }
610 JsonValue::Object(schema)
611}
612
613fn type_schema(
616 lemma_type: &DomainLemmaType,
617 list_writes: Option<&ListWrites>,
618 rows: &mut RowSchemas,
619) -> Map<String, JsonValue> {
620 let DomainTypeSpecification::List { element, .. } = &lemma_type.specifications else {
621 return scalar_data_schema(lemma_type);
622 };
623 let mut schema = Map::new();
624 let items = match &element.specifications {
625 DomainTypeSpecification::Spec { spec } => rows.reference(spec, list_writes),
626 DomainTypeSpecification::List { .. } => {
627 unreachable!("BUG: lists do not nest; planning rejects a list element list")
628 }
629 _ => JsonValue::Object(scalar_data_schema(element)),
630 };
631 schema.insert("type".to_string(), json!("array"));
632 schema.insert("items".to_string(), items);
633 schema.insert(
634 "maxItems".to_string(),
635 json!(rows.engine.limits().max_list_rows),
636 );
637 schema
638}
639
640fn scalar_data_schema(lemma_type: &DomainLemmaType) -> Map<String, JsonValue> {
642 let specification = &lemma_type.specifications;
643 let names: Vec<&str> = match specification {
644 DomainTypeSpecification::Measure { units, .. } => {
645 units.iter().map(|unit| unit.name.as_str()).collect()
646 }
647 DomainTypeSpecification::Ratio { units, .. } => {
648 units.iter().map(|unit| unit.name.as_str()).collect()
649 }
650 _ => return scalar_type_schema(lemma_type),
651 };
652 let unit_map = json!({
653 "type": "object",
654 "minProperties": 1,
655 "maxProperties": 1,
656 "propertyNames": {"enum": names},
657 "additionalProperties": {"type": "string"}
658 });
659 let mut schema = Map::new();
660 schema.insert(
661 "oneOf".to_string(),
662 json!([JsonValue::Object(scalar_type_schema(lemma_type)), unit_map]),
663 );
664 publish_option_enum(&mut schema, lemma_type);
665 schema
666}
667
668fn scalar_type_schema(lemma_type: &DomainLemmaType) -> Map<String, JsonValue> {
669 let specification = &lemma_type.specifications;
670 let mut schema = Map::new();
671 match specification {
672 DomainTypeSpecification::Boolean { .. } => {
673 schema.insert(
674 "oneOf".to_string(),
675 json!([
676 {"type": "boolean"},
677 {"type": "string", "pattern": BOOLEAN_TEXT_PATTERN}
678 ]),
679 );
680 }
681 DomainTypeSpecification::Text { length, .. } => {
682 schema.insert("type".to_string(), json!("string"));
683 if let Some(length) = length {
684 schema.insert("minLength".to_string(), json!(length));
685 schema.insert("maxLength".to_string(), json!(length));
686 }
687 }
688 DomainTypeSpecification::Number { .. }
689 | DomainTypeSpecification::Measure { .. }
690 | DomainTypeSpecification::Ratio { .. }
691 | DomainTypeSpecification::NumberRange { .. }
692 | DomainTypeSpecification::MeasureRange { .. }
693 | DomainTypeSpecification::RatioRange { .. }
694 | DomainTypeSpecification::DateRange { .. }
695 | DomainTypeSpecification::TimeRange { .. } => {
696 schema.insert("type".to_string(), json!("string"));
697 }
698 DomainTypeSpecification::Date { .. } => {
699 schema.insert(
700 "oneOf".to_string(),
701 json!([
702 {"type": "string", "format": "date"},
703 {"type": "string", "format": "date-time"}
704 ]),
705 );
706 }
707 DomainTypeSpecification::Time { .. } => {
708 schema.insert("type".to_string(), json!("string"));
709 schema.insert("format".to_string(), json!("time"));
710 }
711 DomainTypeSpecification::List { .. } => {
712 unreachable!("BUG: list schemas are built by type_schema")
713 }
714 DomainTypeSpecification::Spec { spec } => {
715 unreachable!("BUG: spec '{spec}' is a uses alias, never a Show data entry")
716 }
717 DomainTypeSpecification::Veto { .. } => {
718 unreachable!("BUG: veto sentinel type on a Show data entry")
719 }
720 DomainTypeSpecification::Undetermined => {
721 unreachable!("BUG: undetermined sentinel type on a Show data entry")
722 }
723 }
724 publish_option_enum(&mut schema, lemma_type);
725 schema
726}
727
728fn publish_option_enum(schema: &mut Map<String, JsonValue>, lemma_type: &DomainLemmaType) {
729 if lemma_type.options.values.is_empty() {
730 return;
731 }
732 schema.insert(
733 "enum".to_string(),
734 json!(lemma_type
735 .options
736 .values
737 .iter()
738 .map(|option| lemma_type.display_bound(&option.value))
739 .collect::<Vec<_>>()),
740 );
741}
742
743fn specification_help(specification: &DomainTypeSpecification) -> String {
744 let mut leaf = specification;
745 while let DomainTypeSpecification::List { element, .. } = leaf {
746 leaf = &element.specifications;
747 }
748 match leaf {
749 DomainTypeSpecification::Boolean { help }
750 | DomainTypeSpecification::Measure { help, .. }
751 | DomainTypeSpecification::MeasureRange { help, .. }
752 | DomainTypeSpecification::Number { help, .. }
753 | DomainTypeSpecification::NumberRange { help, .. }
754 | DomainTypeSpecification::Ratio { help, .. }
755 | DomainTypeSpecification::RatioRange { help, .. }
756 | DomainTypeSpecification::Text { help, .. }
757 | DomainTypeSpecification::Date { help, .. }
758 | DomainTypeSpecification::DateRange { help, .. }
759 | DomainTypeSpecification::Time { help, .. }
760 | DomainTypeSpecification::TimeRange { help, .. } => help.clone(),
761 DomainTypeSpecification::Spec { spec } => spec.to_string(),
762 DomainTypeSpecification::List { .. } => {
763 unreachable!("BUG: list chain is unwound before the leaf match")
764 }
765 DomainTypeSpecification::Veto { .. } | DomainTypeSpecification::Undetermined => {
766 unreachable!("BUG: sentinel type on a Show data entry")
767 }
768 }
769}
770
771fn rule_result_value_has_reference(value: &DomainRuleResultValue) -> bool {
775 if value.reference.is_some() {
776 return true;
777 }
778 if let Some(fields) = &value.fields {
779 if fields.values().any(rule_result_value_has_reference) {
780 return true;
781 }
782 }
783 if let Some(list) = &value.list {
784 if list.iter().any(rule_result_value_has_reference) {
785 return true;
786 }
787 }
788 false
789}
790
791enum InputLiteralTask<'a> {
792 Visit {
793 value: &'a DomainRuleResultValue,
794 lemma_type: Arc<DomainLemmaType>,
795 },
796 CollectArray {
797 len: usize,
798 },
799 CollectObject {
800 keys: Vec<String>,
801 },
802}
803
804fn input_literal(
805 value: &DomainRuleResultValue,
806 lemma_type: &DomainLemmaType,
807 rows: &RowSchemas,
808) -> JsonValue {
809 let mut tasks = vec![InputLiteralTask::Visit {
810 value,
811 lemma_type: Arc::new(lemma_type.clone()),
812 }];
813 let mut converted: Vec<JsonValue> = Vec::new();
814 while let Some(task) = tasks.pop() {
815 match task {
816 InputLiteralTask::Visit { value, lemma_type } => match &lemma_type.specifications {
817 DomainTypeSpecification::Boolean { .. } => converted.push(JsonValue::Bool(
818 value
819 .boolean
820 .expect("BUG: boolean-typed Show value without boolean"),
821 )),
822 DomainTypeSpecification::List { element, .. } => {
823 let items = value
824 .list
825 .as_ref()
826 .expect("BUG: list-typed Show value without list");
827 tasks.push(InputLiteralTask::CollectArray { len: items.len() });
828 match &element.specifications {
829 DomainTypeSpecification::Spec { spec } => {
830 let row_show = rows.engine.show_spec(spec);
831 for row in items.iter().rev() {
832 let fields = row
833 .fields
834 .as_ref()
835 .expect("BUG: instance list Show row without fields");
836 let mut keys = Vec::with_capacity(fields.len());
837 let mut children = Vec::with_capacity(fields.len());
838 for (name, field) in fields {
839 assert!(
840 field.reference.is_none(),
841 "BUG: input_literal on Show value with reference field '{name}'"
842 );
843 let field_type = row_show
844 .types
845 .get(name)
846 .or_else(|| row_show.data.get(name).map(|d| &d.lemma_type))
847 .unwrap_or_else(|| {
848 panic!("BUG: row field '{name}' missing from Show of '{spec}'")
849 });
850 keys.push(name.clone());
851 children.push((field, Arc::new(field_type.clone())));
852 }
853 tasks.push(InputLiteralTask::CollectObject { keys });
854 for (field, field_type) in children.into_iter().rev() {
855 tasks.push(InputLiteralTask::Visit {
856 value: field,
857 lemma_type: field_type,
858 });
859 }
860 }
861 }
862 _ => {
863 for item in items.iter().rev() {
864 tasks.push(InputLiteralTask::Visit {
865 value: item,
866 lemma_type: Arc::clone(element),
867 });
868 }
869 }
870 }
871 }
872 _ => converted.push(JsonValue::String(
873 value
874 .result
875 .clone()
876 .expect("BUG: scalar Show value without result"),
877 )),
878 },
879 InputLiteralTask::CollectArray { len } => {
880 let items = converted.split_off(converted.len() - len);
881 converted.push(JsonValue::Array(items));
882 }
883 InputLiteralTask::CollectObject { keys } => {
884 let children = converted.split_off(converted.len() - keys.len());
885 converted.push(JsonValue::Object(keys.into_iter().zip(children).collect()));
886 }
887 }
888 }
889 converted
890 .pop()
891 .expect("BUG: Show value conversion yields exactly one JSON value")
892}
893
894fn lemma_type_without_standard_keywords(lemma_type: &DomainLemmaType) -> JsonValue {
897 let mut value = to_json(&LemmaType::from(lemma_type));
898 strip_standard_keywords(&mut value);
899 value
900}
901
902fn strip_standard_keywords(value: &mut JsonValue) {
903 let mut pending = vec![value];
904 while let Some(value) = pending.pop() {
905 let object = value
906 .as_object_mut()
907 .expect("BUG: LemmaType serializes to a JSON object");
908 object.remove("help");
909 if object.get("kind") == Some(&json!("text")) {
910 object.remove("options");
911 object.remove("length");
912 }
913 if let Some(element) = object.get_mut("element") {
914 pending.push(element);
915 }
916 }
917}
918
919struct RowSchemas<'a> {
922 engine: &'a Engine,
923 consumer: Option<&'a ExecutionPlan>,
926 started: BTreeSet<String>,
927 pending: Vec<(String, SpecIdentity, Option<ListWrites>)>,
928 defs: BTreeMap<String, JsonValue>,
929}
930
931impl<'a> RowSchemas<'a> {
932 fn new(engine: &'a Engine, consumer: Option<&'a ExecutionPlan>) -> Self {
933 Self {
934 engine,
935 consumer,
936 started: BTreeSet::new(),
937 pending: Vec::new(),
938 defs: BTreeMap::new(),
939 }
940 }
941
942 fn into_defs(mut self) -> (Map<String, JsonValue>, Map<String, JsonValue>) {
946 let mut row_field_needed_by_rules = Map::new();
947 while let Some((def_name, identity, list_writes)) = self.pending.pop() {
948 let show = self.engine.show_spec(&identity);
949 let mut schema = Map::new();
950 schema.insert("title".to_string(), json!(format!("{identity} row")));
951 schema.extend(row_object_schema(&show, list_writes.as_ref(), &mut self));
952 let mut field_map = Map::new();
953 for field in row_property_names(&show) {
954 if list_writes
955 .as_ref()
956 .is_some_and(|rows| rows.fields.contains(&field))
957 {
958 continue;
959 }
960 let needed = self.row_field_needed_by_rules(&identity, &field);
961 if !needed.is_empty() {
962 field_map.insert(field, json!(needed));
963 }
964 }
965 if !field_map.is_empty() {
966 row_field_needed_by_rules.insert(def_name.clone(), JsonValue::Object(field_map));
967 }
968 self.defs.insert(def_name, JsonValue::Object(schema));
969 }
970 (self.defs.into_iter().collect(), row_field_needed_by_rules)
971 }
972
973 fn row_field_needed_by_rules(&self, identity: &SpecIdentity, field: &str) -> Vec<String> {
975 let Some(consumer) = self.consumer else {
976 return Vec::new();
977 };
978 consumer
979 .row_field_needed_by_rules(identity, field)
980 .into_iter()
981 .map(|rule_position| {
982 &consumer
983 .rules
984 .get_index(rule_position as usize)
985 .expect("BUG: needed_by_rules field consumer out of consumer.rules range")
986 .1
987 .path
988 })
989 .filter(|rule_path| consumer.show_rules.contains_key(*rule_path))
990 .map(|rule_path| rule_path.input_key())
991 .collect()
992 }
993
994 fn reference(
997 &mut self,
998 identity: &SpecIdentity,
999 list_writes: Option<&ListWrites>,
1000 ) -> JsonValue {
1001 let name = match list_writes {
1002 Some(rows) => def_name_of(&rows.list),
1003 None => row_def_name(identity),
1004 };
1005 if self.started.insert(name.clone()) {
1006 self.pending
1007 .push((name.clone(), identity.clone(), list_writes.cloned()));
1008 }
1009 json!({ "$ref": format!("#/$defs/{name}") })
1010 }
1011}
1012
1013pub fn row_def_name(identity: &SpecIdentity) -> String {
1017 def_name_of(&identity.to_string())
1018}
1019
1020fn def_name_of(text: &str) -> String {
1022 let mut name = String::from("LemmaRow_");
1023 for c in text.chars() {
1024 if c.is_ascii_alphanumeric() || c == '-' {
1025 name.push(c);
1026 } else if c == '_' {
1027 name.push_str("__");
1028 } else {
1029 name.push_str(&format!("_{:x}_", c as u32));
1030 }
1031 }
1032 name
1033}
1034
1035#[cfg(test)]
1036mod tests {
1037 use super::*;
1038 use crate::parsing::ast::Span;
1039 use crate::parsing::source::{Source, SourceType};
1040 use crate::planning::semantics::parse_value_from_string;
1041
1042 const INPUTS: &str = r#"
1043spec inputs
1044data money: measure -> unit eur: 1 -> unit cent: 0.01
1045data price: money -> suggest 10 eur
1046data deposit: 250 cent
1047data rate: ratio -> suggest 21%
1048data bps: ratio -> unit basis_points: 10000 -> unit percent: 100 -> suggest 500 basis_points
1049data fee: 3%
1050data quantity: number -> suggest 12.5
1051data offset: -3
1052data express: boolean -> suggest true
1053data code: text -> option "A" -> option "B" -> suggest "B"
1054data label: text -> length 3
1055data start: date -> suggest 2026-01-01
1056data at: time -> suggest 09:30:00
1057data window: number range -> suggest 1...5
1058data tags: number list
1059 -> with 5, 10
1060rule r_price: price + deposit
1061rule r_rate: rate
1062rule r_bps: bps
1063rule r_fee: fee
1064rule r_quantity: quantity + offset
1065rule r_express: express
1066rule r_code: code
1067rule r_label: label
1068rule r_start: start
1069rule r_at: at
1070rule r_window: window
1071rule r_tags: tags -> sum
1072"#;
1073
1074 fn engine() -> Engine {
1075 let mut engine = Engine::new();
1076 engine
1077 .load([(SourceType::Volatile, INPUTS.to_string())])
1078 .expect("load inputs");
1079 engine
1080 }
1081
1082 fn document() -> (Engine, DomainShow, JsonValue) {
1083 let engine = engine();
1084 let show = engine.show(None, "inputs", None).expect("show inputs");
1085 let document = show_document(&engine, &show);
1086 (engine, show, document)
1087 }
1088
1089 fn source() -> Source {
1090 Source::new(
1091 SourceType::Volatile,
1092 Span {
1093 start: 0,
1094 end: 0,
1095 line: 1,
1096 col: 1,
1097 },
1098 )
1099 }
1100
1101 fn decimal(text: &JsonValue) -> rust_decimal::Decimal {
1102 text.as_str()
1103 .expect("API decimal is a string")
1104 .parse()
1105 .expect("API decimal parses")
1106 }
1107
1108 fn assert_literal_denotes(
1110 name: &str,
1111 literal: &str,
1112 value: &JsonValue,
1113 specification: &DomainTypeSpecification,
1114 ) {
1115 let parsed = parse_value_from_string(literal, specification, &source())
1116 .unwrap_or_else(|error| panic!("{name}: '{literal}' must parse: {error}"));
1117 assert_parsed_denotes(name, literal, &parsed, value);
1118 }
1119
1120 fn assert_parsed_denotes(
1121 name: &str,
1122 literal: &str,
1123 parsed: &crate::parsing::ast::Value,
1124 value: &JsonValue,
1125 ) {
1126 use crate::parsing::ast::Value;
1127 match parsed {
1128 Value::Number(magnitude) => {
1129 assert_eq!(*magnitude, decimal(&value["number"]), "{name}: '{literal}'");
1130 }
1131 Value::NumberWithUnit(magnitude, unit) => {
1132 let units = value
1133 .get("measure")
1134 .or_else(|| value.get("ratio"))
1135 .unwrap_or_else(|| panic!("{name}: unit map in {value}"));
1136 assert_eq!(
1137 *magnitude,
1138 decimal(&units[unit]),
1139 "{name}: '{literal}' vs {value}"
1140 );
1141 }
1142 Value::Range(left, right) => {
1143 assert_parsed_denotes(name, literal, left, &value["range"]["from"]);
1144 assert_parsed_denotes(name, literal, right, &value["range"]["to"]);
1145 }
1146 other => panic!("{name}: '{literal}' parsed to unexpected {other:?}"),
1147 }
1148 }
1149
1150 #[test]
1151 fn spec_level_keywords() {
1152 let (_, _, document) = document();
1153 assert_eq!(document["$schema"], JSON_SCHEMA_DIALECT);
1154 assert_eq!(document["title"], "inputs");
1155 assert_eq!(document["type"], "object");
1156 assert_eq!(document["additionalProperties"], true);
1157 assert!(document.get("$defs").is_none());
1158 assert_eq!(document["x-lemma-start-line"], 2);
1159 assert!(document["x-lemma-rules"]["r_price"].is_object());
1160 }
1161
1162 #[test]
1163 fn required_is_sorted_needed_inputs_without_committed_value() {
1164 let (_, _, document) = document();
1165 assert_eq!(
1166 document["required"],
1167 json!([
1168 "at", "bps", "code", "express", "label", "price", "quantity", "rate", "start",
1169 "window"
1170 ])
1171 );
1172 }
1173
1174 #[test]
1175 fn standard_keywords_per_type() {
1176 let (_, _, document) = document();
1177 let properties = &document["properties"];
1178 assert_eq!(properties["express"]["oneOf"][0]["type"], "boolean");
1179 assert_eq!(properties["express"]["examples"], json!([true]));
1180 assert_eq!(properties["code"]["type"], "string");
1181 assert_eq!(properties["code"]["enum"], json!(["A", "B"]));
1182 assert_eq!(properties["label"]["minLength"], 3);
1183 assert_eq!(properties["label"]["maxLength"], 3);
1184 assert_eq!(properties["quantity"]["type"], "string");
1185 assert!(properties["quantity"].get("pattern").is_none());
1186 assert_eq!(
1187 properties["price"]["oneOf"][1]["propertyNames"]["enum"],
1188 json!(["eur", "cent"])
1189 );
1190 assert_eq!(
1191 properties["price"]["oneOf"][1]["additionalProperties"],
1192 json!({ "type": "string" })
1193 );
1194 assert!(properties["price"]["oneOf"][0].get("pattern").is_none());
1195 assert_eq!(
1196 properties["rate"]["oneOf"][1]["propertyNames"]["enum"],
1197 json!(["percent", "permille"])
1198 );
1199 assert_eq!(
1200 properties["bps"]["oneOf"][1]["propertyNames"]["enum"],
1201 json!(["percent", "permille", "basis_points"])
1202 );
1203 assert_eq!(
1204 properties["start"]["oneOf"],
1205 json!([
1206 {"type": "string", "format": "date"},
1207 {"type": "string", "format": "date-time"}
1208 ])
1209 );
1210 assert_eq!(properties["at"]["type"], "string");
1211 assert_eq!(properties["at"]["format"], "time");
1212 assert_eq!(properties["window"]["type"], "string");
1213 assert!(properties["window"].get("pattern").is_none());
1214 assert!(properties["window"].get("format").is_none());
1215 let tags = &properties["tags"];
1216 assert_eq!(tags["type"], "array");
1217 assert_eq!(tags["items"], json!({ "type": "string" }));
1218 assert_eq!(
1219 tags["maxItems"],
1220 crate::ResourceLimits::default().max_list_rows
1221 );
1222 assert_eq!(tags["default"], json!(["5", "10"]));
1223 }
1224
1225 #[test]
1226 fn x_lemma_type_omits_what_standard_keywords_state() {
1227 let (_, _, document) = document();
1228 for (name, property) in document["properties"].as_object().expect("properties") {
1229 let lemma_type = &property["x-lemma-type"];
1230 assert!(lemma_type.get("help").is_none(), "{name}: {lemma_type}");
1231 assert!(lemma_type.get("options").is_none(), "{name}: {lemma_type}");
1232 assert!(lemma_type.get("length").is_none(), "{name}: {lemma_type}");
1233 if let Some(element) = lemma_type.get("element") {
1234 assert!(element.get("help").is_none(), "{name}: {element}");
1235 }
1236 assert!(property.get("x-lemma-path").is_some(), "{name}");
1237 assert!(property.get("x-lemma-needed-by-rules").is_some(), "{name}");
1238 }
1239 assert_eq!(
1240 document["properties"]["price"]["x-lemma-type"]["kind"],
1241 "measure"
1242 );
1243 assert!(document["properties"]["price"]["x-lemma-type"]["units"].is_array());
1244 }
1245
1246 fn value_json_has_reference(value: &JsonValue) -> bool {
1247 if value.get("reference").is_some() {
1248 return true;
1249 }
1250 if let Some(fields) = value.get("fields").and_then(|v| v.as_object()) {
1251 if fields.values().any(value_json_has_reference) {
1252 return true;
1253 }
1254 }
1255 if let Some(list) = value.get("list").and_then(|v| v.as_array()) {
1256 if list.iter().any(value_json_has_reference) {
1257 return true;
1258 }
1259 }
1260 false
1261 }
1262
1263 fn evaluate_data_json_of(value: &JsonValue) -> JsonValue {
1265 if let Some(boolean) = value.get("boolean") {
1266 return boolean.clone();
1267 }
1268 if let Some(items) = value.get("list") {
1269 return JsonValue::Array(
1270 items
1271 .as_array()
1272 .expect("list")
1273 .iter()
1274 .map(evaluate_data_json_of)
1275 .collect(),
1276 );
1277 }
1278 if let Some(fields) = value.get("fields") {
1279 return JsonValue::Object(
1280 fields
1281 .as_object()
1282 .expect("fields")
1283 .iter()
1284 .filter(|(_, field)| field.get("reference").is_none())
1285 .map(|(name, field)| (name.clone(), evaluate_data_json_of(field)))
1286 .collect(),
1287 );
1288 }
1289 if value.get("reference").is_some() {
1290 panic!("BUG: reference field is not a run-data literal");
1291 }
1292 value["result"].clone()
1293 }
1294
1295 #[test]
1296 fn instance_list_with_references_has_value_but_no_default() {
1297 let mut engine = Engine::new();
1298 engine
1299 .load([(
1300 SourceType::Volatile,
1301 r#"
1302spec processing
1303data type: text
1304data weight: number
1305data enabled: boolean
1306spec line_item
1307data weight: number
1308data finish_a: boolean
1309uses step: processing
1310data processing: step list
1311 -> with weight: weight, type: "finish_a", enabled: finish_a
1312rule cost: processing -> where enabled -> count
1313"#
1314 .to_string(),
1315 )])
1316 .expect("load");
1317 let show = engine.show(None, "line_item", None).expect("show");
1318 let processing = show.data.get("processing").expect("processing");
1319 let value = processing.value.as_ref().expect("value");
1320 assert!(
1321 rule_result_value_has_reference(value),
1322 "expected reference in value: {value:?}"
1323 );
1324 let document = show_document(&engine, &show);
1325 let property = &document["properties"]["processing"];
1326 assert!(property.get("x-lemma-value").is_some(), "{property}");
1327 assert!(
1328 property.get("default").is_none(),
1329 "default must be omitted when fields reference data: {property}"
1330 );
1331 }
1332
1333 #[test]
1334 fn default_and_examples_agree_with_typed_value_and_suggestion() {
1335 let (_, _, document) = document();
1336 let mut checked = 0;
1337 for (name, property) in document["properties"].as_object().expect("properties") {
1338 match (property.get("default"), property.get("x-lemma-value")) {
1339 (Some(default), Some(value)) => {
1340 assert_eq!(default, &evaluate_data_json_of(value), "{name}");
1341 checked += 1;
1342 }
1343 (None, Some(value)) => {
1344 assert!(
1345 value_json_has_reference(value),
1346 "{name}: value without default must carry a reference field"
1347 );
1348 }
1349 (None, None) => {}
1350 other => {
1351 panic!("{name}: default and x-lemma-value disagree on presence: {other:?}")
1352 }
1353 }
1354 match (property.get("examples"), property.get("x-lemma-suggestion")) {
1355 (Some(examples), Some(suggestion)) => {
1356 assert_eq!(
1357 examples,
1358 &json!([evaluate_data_json_of(suggestion)]),
1359 "{name}"
1360 );
1361 checked += 1;
1362 }
1363 (None, None) => {}
1364 other => panic!(
1365 "{name}: examples and x-lemma-suggestion disagree on presence: {other:?}"
1366 ),
1367 }
1368 }
1369 assert_eq!(checked, 13);
1370 }
1371
1372 fn is_numeric_literal_specification(specification: &DomainTypeSpecification) -> bool {
1373 matches!(
1374 specification,
1375 DomainTypeSpecification::Number { .. }
1376 | DomainTypeSpecification::Measure { .. }
1377 | DomainTypeSpecification::Ratio { .. }
1378 | DomainTypeSpecification::NumberRange { .. }
1379 | DomainTypeSpecification::MeasureRange { .. }
1380 | DomainTypeSpecification::RatioRange { .. }
1381 )
1382 }
1383
1384 #[test]
1385 fn emitted_string_literals_denote_their_value() {
1386 let (_, show, document) = document();
1387 let mut checked = 0;
1388 for (name, property) in document["properties"].as_object().expect("properties") {
1389 let specification = &show.data[name].lemma_type.specifications;
1390 if !is_numeric_literal_specification(specification) {
1391 continue;
1392 }
1393 let mut literals: Vec<(&str, &JsonValue)> = Vec::new();
1394 if let Some(literal) = property.get("default").and_then(|value| value.as_str()) {
1395 literals.push((literal, &property["x-lemma-value"]));
1396 }
1397 if let Some(literal) = property
1398 .get("examples")
1399 .and_then(|examples| examples[0].as_str())
1400 {
1401 literals.push((literal, &property["x-lemma-suggestion"]));
1402 }
1403 for (literal, value) in literals {
1404 assert_literal_denotes(name, literal, value, specification);
1405 checked += 1;
1406 }
1407 }
1408 assert_eq!(checked, 8);
1409 }
1410
1411 fn identity(repository: Option<&str>, spec: &str) -> SpecIdentity {
1412 SpecIdentity {
1413 repository: repository.map(str::to_string),
1414 spec: spec.to_string(),
1415 effective: crate::parsing::ast::EffectiveDate::Origin,
1416 slice: crate::parsing::ast::EffectiveDate::Origin,
1417 }
1418 }
1419
1420 #[test]
1421 fn row_def_name_is_injective_and_component_safe() {
1422 assert_eq!(row_def_name(&identity(None, "line")), "LemmaRow_line");
1423 assert_eq!(
1424 row_def_name(&identity(None, "tax_bracket")),
1425 "LemmaRow_tax__bracket"
1426 );
1427 let names = [
1428 row_def_name(&identity(Some("@org/repo"), "line")),
1429 row_def_name(&identity(None, "_org_repo_line")),
1430 row_def_name(&identity(None, "line")),
1431 ];
1432 for name in &names {
1433 assert!(
1434 name.chars()
1435 .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-'),
1436 "{name}"
1437 );
1438 }
1439 assert_ne!(names[0], names[1]);
1440 assert_ne!(names[0], names[2]);
1441 }
1442}