1use crate::error::Error;
2use crate::limits::ResourceLimits;
3
4pub mod arena;
5pub mod ast;
6pub mod lexer;
7pub mod parser;
8pub mod source;
9
10pub use ast::*;
11pub use parser::{parse_repository_qualifier_str, ParseResult};
12
13pub fn parse(
14 content: &str,
15 source_type: source::SourceType,
16 limits: &ResourceLimits,
17) -> Result<ParseResult, Error> {
18 parser::parse(content, source_type, limits)
19}
20
21#[cfg(test)]
26mod tests {
27 use super::{
28 parse, ArithmeticComputation, CommandArg, Constraint, DataValue, Expression,
29 ExpressionKind, LemmaSpec, MathematicalComputation, RangeBound, Reference, RoundingMode,
30 TypeConstraintCommand, UnitArg, UnitFactor,
31 };
32 use crate::formatting::format_parse_result;
33 use crate::parsing::arena::ExprRef;
34 use crate::Error;
35 use crate::ResourceLimits;
36
37 fn binary_arithmetic(
39 node: ExprRef<'_, ExpressionKind>,
40 ) -> Option<(
41 ExprRef<'_, ExpressionKind>,
42 ArithmeticComputation,
43 ExprRef<'_, ExpressionKind>,
44 )> {
45 match node.kind() {
46 ExpressionKind::Arithmetic { first, steps } if steps.len() == 1 => Some((
47 node.child(*first),
48 steps[0].op.clone(),
49 node.child(steps[0].operand),
50 )),
51 _ => None,
52 }
53 }
54
55 #[test]
56 fn parse_empty_input_returns_no_specs() {
57 let result = parse(
58 "",
59 crate::parsing::source::SourceType::Volatile,
60 &ResourceLimits::default(),
61 )
62 .unwrap()
63 .into_flattened_specs();
64 assert_eq!(result.len(), 0);
65 }
66
67 #[test]
68 fn parse_workspace_file_yields_expected_spec_datas_and_rules() {
69 let input = r#"spec person
70data name: "John Doe"
71rule adult: true"#;
72 let result = parse(
73 input,
74 crate::parsing::source::SourceType::Volatile,
75 &ResourceLimits::default(),
76 )
77 .unwrap()
78 .into_flattened_specs();
79 assert_eq!(result.len(), 1);
80 assert_eq!(result[0].name, "person");
81 assert_eq!(result[0].data.len(), 1);
82 assert_eq!(result[0].rules.len(), 1);
83 assert_eq!(result[0].rules[0].name, "adult");
84 }
85
86 #[test]
87 fn mixing_data_and_rules_is_collected_into_spec() {
88 let input = r#"spec test
89data name: "John"
90rule is_adult: age >= 18
91data age: 25
92rule can_drink: age >= 21
93data status: "active"
94rule is_eligible: is_adult and status is "active""#;
95
96 let result = parse(
97 input,
98 crate::parsing::source::SourceType::Volatile,
99 &ResourceLimits::default(),
100 )
101 .unwrap()
102 .into_flattened_specs();
103 assert_eq!(result.len(), 1);
104 assert_eq!(result[0].data.len(), 3);
105 assert_eq!(result[0].rules.len(), 3);
106 }
107
108 #[test]
109 fn parse_simple_spec_collects_data() {
110 let input = r#"spec person
111data name: "John"
112data age: 25"#;
113 let result = parse(
114 input,
115 crate::parsing::source::SourceType::Volatile,
116 &ResourceLimits::default(),
117 )
118 .unwrap()
119 .into_flattened_specs();
120 assert_eq!(result.len(), 1);
121 assert_eq!(result[0].name, "person");
122 assert_eq!(result[0].data.len(), 2);
123 }
124
125 #[test]
126 fn parse_dotted_spec_name_is_rejected() {
127 let input = r#"spec contracts.employment.jack
128data name: "Jack""#;
129 let error = parse(
130 input,
131 crate::parsing::source::SourceType::Volatile,
132 &ResourceLimits::default(),
133 )
134 .expect_err("a spec name has no '.'");
135 assert!(
136 error
137 .to_string()
138 .contains("'.' is not allowed in spec names: 'contracts.employment.jack'"),
139 "got: {error}"
140 );
141 }
142
143 #[test]
144 fn parse_dotted_repository_name_is_rejected() {
145 for (input, name) in [
146 ("repo bieb.nl\n\nspec rates\ndata x: 1", "bieb.nl"),
147 (
148 "repo @bieb.nl/rekenen\n\nspec rates\ndata x: 1",
149 "@bieb.nl/rekenen",
150 ),
151 (
152 "spec factuur\nuses omrekening: @bieb.nl/rekenen omrekening",
153 "@bieb.nl/rekenen",
154 ),
155 ] {
156 let error = parse(
157 input,
158 crate::parsing::source::SourceType::Volatile,
159 &ResourceLimits::default(),
160 )
161 .expect_err("a repository name has no '.'");
162 assert!(
163 error
164 .to_string()
165 .contains(&format!("'.' is not allowed in repository names: '{name}'")),
166 "{input}: {error}"
167 );
168 }
169 }
170
171 #[test]
172 fn parse_dotted_uses_target_is_rejected() {
173 let input = "spec order
174uses brackets: nl.tax.brackets";
175 let error = parse(
176 input,
177 crate::parsing::source::SourceType::Volatile,
178 &ResourceLimits::default(),
179 )
180 .expect_err("a spec name has no '.'");
181 assert!(
182 error
183 .to_string()
184 .contains("'.' is not allowed in spec names: 'nl.tax.brackets'"),
185 "got: {error}"
186 );
187 }
188
189 #[test]
190 fn parse_slashed_spec_name() {
191 let input = "spec contracts/employment/jack\ndata x: 1";
192 let result = parse(
193 input,
194 crate::parsing::source::SourceType::Volatile,
195 &ResourceLimits::default(),
196 )
197 .unwrap()
198 .into_flattened_specs();
199 assert_eq!(result.len(), 1);
200 assert_eq!(result[0].name, "contracts/employment/jack");
201 }
202
203 #[test]
204 fn parse_spec_name_no_version_tag() {
205 let input = "spec myspec\nrule x: 1";
206 let result = parse(
207 input,
208 crate::parsing::source::SourceType::Volatile,
209 &ResourceLimits::default(),
210 )
211 .unwrap()
212 .into_flattened_specs();
213 assert_eq!(result.len(), 1);
214 assert_eq!(result[0].name, "myspec");
215 assert_eq!(result[0].effective_from(), None);
216 }
217
218 #[test]
219 fn parse_commentary_block_is_attached_to_spec() {
220 let input = r#"spec person
221"""
222This is a markdown comment
223uses **bold** text
224"""
225data name: "John""#;
226 let result = parse(
227 input,
228 crate::parsing::source::SourceType::Volatile,
229 &ResourceLimits::default(),
230 )
231 .unwrap()
232 .into_flattened_specs();
233 assert_eq!(result.len(), 1);
234 assert!(result[0].commentary.is_some());
235 assert!(result[0].commentary.as_ref().unwrap().contains("**bold**"));
236 }
237
238 #[test]
239 fn parse_spec_with_rule_collects_rule() {
240 let input = r#"spec person
241rule is_adult: age >= 18"#;
242 let result = parse(
243 input,
244 crate::parsing::source::SourceType::Volatile,
245 &ResourceLimits::default(),
246 )
247 .unwrap()
248 .into_flattened_specs();
249 assert_eq!(result.len(), 1);
250 assert_eq!(result[0].rules.len(), 1);
251 assert_eq!(result[0].rules[0].name, "is_adult");
252 }
253
254 #[test]
255 fn parse_multiple_specs_returns_all_specs() {
256 let input = r#"spec person
257data name: "John"
258
259spec company
260data name: "Acme Corp""#;
261 let result = parse(
262 input,
263 crate::parsing::source::SourceType::Volatile,
264 &ResourceLimits::default(),
265 )
266 .unwrap()
267 .into_flattened_specs();
268 assert_eq!(result.len(), 2);
269 assert_eq!(result[0].name, "person");
270 assert_eq!(result[1].name, "company");
271 }
272
273 #[test]
274 fn parse_allows_duplicate_data_names() {
275 let input = r#"spec person
276data name: "John"
277data name: "Jane""#;
278 let result = parse(
279 input,
280 crate::parsing::source::SourceType::Volatile,
281 &ResourceLimits::default(),
282 );
283 assert!(
284 result.is_ok(),
285 "Parser should succeed even with duplicate data"
286 );
287 }
288
289 #[test]
290 fn parse_allows_duplicate_rule_names() {
291 let input = r#"spec person
292rule is_adult: age >= 18
293rule is_adult: age >= 21"#;
294 let result = parse(
295 input,
296 crate::parsing::source::SourceType::Volatile,
297 &ResourceLimits::default(),
298 );
299 assert!(
300 result.is_ok(),
301 "Parser should succeed even with duplicate rules"
302 );
303 }
304
305 #[test]
306 fn parse_rejects_malformed_input() {
307 let input = "invalid syntax here";
308 let result = parse(
309 input,
310 crate::parsing::source::SourceType::Volatile,
311 &ResourceLimits::default(),
312 );
313 assert!(result.is_err());
314 }
315
316 #[test]
317 fn parse_handles_whitespace_variants_in_expressions() {
318 let test_cases = vec![
319 ("spec test\nrule test: 2+3", "no spaces in arithmetic"),
320 ("spec test\nrule test: age>=18", "no spaces in comparison"),
321 (
322 "spec test\nrule test: age >= 18 and salary>50000",
323 "spaces around and keyword",
324 ),
325 (
326 "spec test\nrule test: age >= 18 and salary > 50000",
327 "extra spaces",
328 ),
329 (
330 "spec test\nrule test: \n age >= 18 \n and \n salary > 50000",
331 "newlines in expression",
332 ),
333 ];
334
335 for (input, description) in test_cases {
336 let result = parse(
337 input,
338 crate::parsing::source::SourceType::Volatile,
339 &ResourceLimits::default(),
340 );
341 assert!(
342 result.is_ok(),
343 "Failed to parse {} ({}): {:?}",
344 input,
345 description,
346 result.err()
347 );
348 }
349 }
350
351 #[test]
352 fn parse_error_cases_are_rejected() {
353 let error_cases = vec![
354 (
355 "spec test\ndata name: \"unclosed string",
356 "unclosed string literal",
357 ),
358 ("spec test\nrule test: (2 + 3", "unclosed parenthesis"),
359 ("spec test\nrule test: 2 + 3)", "extra closing paren"),
360 ("spec test\ndata spec: 123", "reserved keyword as data name"),
361 (
362 "spec test\nrule rule: true",
363 "reserved keyword as rule name",
364 ),
365 ];
366
367 for (input, description) in error_cases {
368 let result = parse(
369 input,
370 crate::parsing::source::SourceType::Volatile,
371 &ResourceLimits::default(),
372 );
373 assert!(
374 result.is_err(),
375 "Expected error for {} but got success",
376 description
377 );
378 }
379 }
380
381 #[test]
382 fn parse_duration_literals_in_rules() {
383 let test_cases = vec![
384 ("2 year", "year"),
385 ("6 month", "month"),
386 ("52 week", "week"),
387 ("365 day", "day"),
388 ("24 hour", "hour"),
389 ("60 minute", "minute"),
390 ("3600 second", "second"),
391 ("1000 millisecond", "millisecond"),
392 ("500000 microsecond", "microsecond"),
393 ("50 percent", "percent"),
394 ];
395
396 for (expr, description) in test_cases {
397 let input = format!("spec test\nrule test: {}", expr);
398 let result = parse(
399 &input,
400 crate::parsing::source::SourceType::Volatile,
401 &ResourceLimits::default(),
402 );
403 assert!(
404 result.is_ok(),
405 "Failed to parse literal {} ({}): {:?}",
406 expr,
407 description,
408 result.err()
409 );
410 }
411 }
412
413 #[test]
414 fn parse_comparisons_with_duration_unit_conversions() {
415 let test_cases = vec![
416 (
417 "(duration as hour) > 2",
418 "duration conversion in comparison with parens",
419 ),
420 (
421 "(meeting_time as minute) >= 30",
422 "duration conversion with gte",
423 ),
424 (
425 "(project_length as day) < 100",
426 "duration conversion with lt",
427 ),
428 (
429 "(delay as second) is 60",
430 "duration conversion with equality",
431 ),
432 (
433 "(1 hour) > (30 minute)",
434 "duration conversions on both sides",
435 ),
436 ("duration as hour > 2", "duration conversion without parens"),
437 (
438 "meeting_time as second > 3600",
439 "variable duration conversion in comparison",
440 ),
441 (
442 "project_length as day > deadline_days",
443 "two variables with duration conversion",
444 ),
445 (
446 "duration as hour >= 1 and duration as hour <= 8",
447 "multiple duration comparisons",
448 ),
449 (
450 "(2024-06-01...2024-06-15) as day as number >= 7",
451 "chained as conversion before comparison",
452 ),
453 ("duration as hour as number > 2", "chained as on duration"),
454 ];
455
456 for (expr, description) in test_cases {
457 let input = format!("spec test\nrule test: {}", expr);
458 let result = parse(
459 &input,
460 crate::parsing::source::SourceType::Volatile,
461 &ResourceLimits::default(),
462 );
463 assert!(
464 result.is_ok(),
465 "Failed to parse {} ({}): {:?}",
466 expr,
467 description,
468 result.err()
469 );
470 }
471 }
472
473 #[test]
474 fn parse_rejects_token_after_unit_conversion() {
475 let result = parse(
476 "spec test\nuses lemma units\nrule ok: (2024-06-01...2024-06-15) as day foo",
477 crate::parsing::source::SourceType::Volatile,
478 &ResourceLimits::default(),
479 );
480 let err = result.expect_err("expected parse error");
481 let msg = err.to_string();
482 assert!(
483 msg.contains("Unexpected token") && msg.contains("foo"),
484 "expected error at 'foo', got: {}",
485 msg
486 );
487 assert!(
488 !msg.contains("Expected 'data'"),
489 "should not defer to spec-level error, got: {}",
490 msg
491 );
492 }
493
494 #[test]
495 fn parse_unit_conversion_before_next_spec() {
496 let result = parse(
497 r#"spec pricing
498rule hourly_rate: 150 eur
499 unless loyalty is "silver" then 140 eur
500 unless loyalty is "gold" then 125 usd as eur
501
502spec other
503rule x: 1"#,
504 crate::parsing::source::SourceType::Volatile,
505 &ResourceLimits::default(),
506 );
507 assert!(
508 result.is_ok(),
509 "unless branch ending with 'as' must parse before next spec: {:?}",
510 result.err()
511 );
512 }
513
514 #[test]
515 fn parse_unit_conversion_before_sibling_rule() {
516 let result = parse(
517 r#"spec s
518rule a: 100 usd as eur
519rule b: 1"#,
520 crate::parsing::source::SourceType::Volatile,
521 &ResourceLimits::default(),
522 );
523 assert!(
524 result.is_ok(),
525 "rule ending with 'as' must parse before sibling rule: {:?}",
526 result.err()
527 );
528 }
529
530 #[test]
531 fn parse_unit_conversion_before_uses() {
532 let result = parse(
533 r#"spec s
534rule rate: 10 usd as eur
535uses lemma units
536rule hour: 1 hour"#,
537 crate::parsing::source::SourceType::Volatile,
538 &ResourceLimits::default(),
539 );
540 assert!(
541 result.is_ok(),
542 "rule ending with 'as' must parse before uses: {:?}",
543 result.err()
544 );
545 }
546
547 #[test]
549 fn parse_unit_conversion_before_expression_boundaries() {
550 let cases: &[(&str, &str)] = &[
551 (
552 "sibling data",
553 r#"spec s
554rule rate: 10 usd as eur
555data price: 100 eur"#,
556 ),
557 (
558 "sibling uses",
559 r#"spec s
560rule rate: 10 usd as eur
561uses other"#,
562 ),
563 (
564 "sibling meta",
565 r#"spec s
566rule rate: 10 usd as eur
567meta version: 1"#,
568 ),
569 (
570 "another unless",
571 r#"spec s
572rule rate: 10 usd
573 unless active then 5 usd as eur
574 unless premium then 3 usd as eur"#,
575 ),
576 (
577 "eof",
578 r#"spec s
579rule rate: 10 usd as eur"#,
580 ),
581 (
582 "next repo",
583 r#"spec s
584rule rate: 10 usd as eur
585
586repo other
587spec t
588rule x: 1"#,
589 ),
590 (
591 "unless then before next unless",
592 r#"spec s
593rule rate: 10 usd
594 unless a then 1 usd as eur
595 unless b then 2"#,
596 ),
597 (
598 "chained as before sibling rule",
599 r#"spec s
600rule rate: (2024-01-01...2024-01-02) as day as number
601rule other: 1"#,
602 ),
603 ];
604
605 for (label, source) in cases {
606 let result = parse(
607 source,
608 crate::parsing::source::SourceType::Volatile,
609 &ResourceLimits::default(),
610 );
611 assert!(
612 result.is_ok(),
613 "unit conversion before {label} must parse: {:?}",
614 result.err()
615 );
616 }
617 }
618
619 #[test]
620 fn parse_rejects_plain_number_plus_converted_operand() {
621 let result = parse(
622 r#"spec test
623data c: measure
624 -> unit eur: 1
625 -> unit usd: 0.84
626rule z: 5 + c as usd"#,
627 crate::parsing::source::SourceType::Volatile,
628 &ResourceLimits::default(),
629 );
630 let err = result.expect_err("expected parse error for 5 + c as usd");
631 let msg = err.to_string();
632 assert!(
633 msg.contains("plain number") || msg.contains("each operand"),
634 "expected conversion-before-+ error, got: {msg}"
635 );
636 }
637
638 #[test]
639 fn parse_accepts_conversion_on_each_additive_operand() {
640 let cases: &[(&str, &str)] = &[
641 (
642 "money",
643 r#"spec test
644data c: measure
645 -> unit eur: 1
646 -> unit usd: 0.84
647rule z: 5 as usd + c as usd"#,
648 ),
649 (
650 "duration + literal",
651 r#"spec test
652uses lemma units
653rule z: duration as hour + 1"#,
654 ),
655 (
656 "duration + comparison",
657 r#"spec test
658uses lemma units
659data duration: units.duration
660 -> suggest 1 hour
661rule z: duration as hour + 1 > 0"#,
662 ),
663 (
664 "date range + ref",
665 r#"spec test
666uses lemma units
667data age: date range
668data c: measure
669 -> unit eur: 1
670rule z: age as day + c"#,
671 ),
672 ];
673 for (label, source) in cases {
674 let result = parse(
675 source,
676 crate::parsing::source::SourceType::Volatile,
677 &ResourceLimits::default(),
678 );
679 assert!(
680 result.is_ok(),
681 "expected {label} to parse, got: {:?}",
682 result.err()
683 );
684 }
685 }
686
687 fn decimal(value: &str) -> rust_decimal::Decimal {
688 value.parse().expect("decimal literal in test")
689 }
690
691 fn parse_single_spec(source: &str) -> LemmaSpec {
692 let specs = parse(
693 source,
694 crate::parsing::source::SourceType::Volatile,
695 &ResourceLimits::default(),
696 )
697 .expect("spec must parse")
698 .into_flattened_specs();
699 assert_eq!(specs.len(), 1, "expected one spec, got {}", specs.len());
700 specs[0].clone()
701 }
702
703 fn measure_unit_constraints(spec: &LemmaSpec) -> Vec<Constraint> {
704 let mut unit_rows = Vec::new();
705 for data in &spec.data {
706 let DataValue::Definition { constraints, .. } = &data.value else {
707 continue;
708 };
709 if let Some(rows) = constraints {
710 for row in rows {
711 if row.command == TypeConstraintCommand::Unit {
712 unit_rows.push(row.clone());
713 }
714 }
715 }
716 }
717 unit_rows
718 }
719
720 fn unit_name_and_arg(row: &Constraint) -> (String, UnitArg) {
721 let args = &row.args;
722 let name = match args.first() {
723 Some(CommandArg::Label(label)) => label.clone(),
724 other => panic!("unit constraint needs label name, got: {:?}", other),
725 };
726 let unit_arg = match args.get(1) {
727 Some(CommandArg::UnitExpr(unit_arg)) => unit_arg.clone(),
728 other => panic!("unit constraint needs UnitExpr payload, got: {:?}", other),
729 };
730 (name, unit_arg)
731 }
732
733 #[test]
736 fn parse_unit_colon_factor_payload() {
737 let spec = parse_single_spec(
738 r#"spec money_spec
739data money: measure
740 -> unit eur: 1.00
741"#,
742 );
743 let rows = measure_unit_constraints(&spec);
744 assert_eq!(rows.len(), 1);
745 let (name, unit_arg) = unit_name_and_arg(&rows[0]);
746 assert_eq!(name, "eur");
747 assert_eq!(unit_arg, UnitArg::Factor(decimal("1.00")));
748 assert!(!rows[0].deprecated_without_colon);
749 }
750
751 #[test]
752 fn parse_unit_colon_compound_only_payload() {
753 let spec = parse_single_spec(
754 r#"spec rates
755uses lemma units
756
757data money: measure
758 -> unit eur: 1.00
759
760data rate: measure
761 -> unit eur_per_hour: eur/hour
762"#,
763 );
764 let rows = measure_unit_constraints(&spec);
765 assert_eq!(rows.len(), 2);
766 let (name, unit_arg) = unit_name_and_arg(&rows[1]);
767 assert_eq!(name, "eur_per_hour");
768 assert_eq!(
769 unit_arg,
770 UnitArg::Expr(
771 rust_decimal::Decimal::ONE,
772 vec![
773 UnitFactor {
774 measure_ref: "eur".to_string(),
775 exp: 1,
776 },
777 UnitFactor {
778 measure_ref: "hour".to_string(),
779 exp: -1,
780 }
781 ],
782 )
783 );
784 assert!(!rows[1].deprecated_without_colon);
785 }
786
787 #[test]
788 fn parse_unit_colon_numeric_prefix_and_compound_payload() {
789 let spec = parse_single_spec(
790 r#"spec speed
791uses lemma units
792
793data velocity: measure
794 -> unit kmh: 3.6 meter/second
795"#,
796 );
797 let rows = measure_unit_constraints(&spec);
798 assert_eq!(rows.len(), 1);
799 let (name, unit_arg) = unit_name_and_arg(&rows[0]);
800 assert_eq!(name, "kmh");
801 assert_eq!(
802 unit_arg,
803 UnitArg::Expr(
804 decimal("3.6"),
805 vec![
806 UnitFactor {
807 measure_ref: "meter".to_string(),
808 exp: 1,
809 },
810 UnitFactor {
811 measure_ref: "second".to_string(),
812 exp: -1,
813 }
814 ],
815 )
816 );
817 assert!(!rows[0].deprecated_without_colon);
818 }
819
820 #[test]
823 fn parse_unit_colon_reference_payload() {
824 let spec = parse_single_spec(
825 r#"spec fx
826data rate: number
827data money: measure
828 -> unit gbp: rate
829"#,
830 );
831 let rows = measure_unit_constraints(&spec);
832 assert_eq!(rows.len(), 1);
833 let (name, unit_arg) = unit_name_and_arg(&rows[0]);
834 assert_eq!(name, "gbp");
835 assert_eq!(
836 unit_arg,
837 UnitArg::Reference(Reference::local("rate".to_string()))
838 );
839 assert!(!rows[0].deprecated_without_colon);
840 }
841
842 #[test]
843 fn parse_unit_colon_dotted_reference_payload() {
844 let specs = parse(
845 r#"spec rate_src
846data rate: number
847spec consumer
848uses rs: rate_src
849data money: measure
850 -> unit gbp: rs.rate
851"#,
852 crate::parsing::source::SourceType::Volatile,
853 &ResourceLimits::default(),
854 )
855 .expect("spec must parse")
856 .into_flattened_specs();
857 let consumer = specs
858 .iter()
859 .find(|s| s.name == "consumer")
860 .expect("consumer spec");
861 let rows = measure_unit_constraints(consumer);
862 assert_eq!(rows.len(), 1);
863 let (name, unit_arg) = unit_name_and_arg(&rows[0]);
864 assert_eq!(name, "gbp");
865 assert_eq!(
866 unit_arg,
867 UnitArg::Reference(Reference {
868 segments: vec!["rs".to_string()],
869 name: "rate".to_string(),
870 })
871 );
872 }
873
874 #[test]
875 fn parse_unit_colon_reference_display_roundtrips() {
876 let local = UnitArg::Reference(Reference::local("rate".to_string()));
877 assert_eq!(format!("{local}"), "rate");
878 let dotted = UnitArg::Reference(Reference {
879 segments: vec!["rs".to_string()],
880 name: "rate".to_string(),
881 });
882 assert_eq!(format!("{dotted}"), "rs.rate");
883 }
884
885 #[test]
886 fn parse_unit_colon_compound_still_parses_after_reference_support() {
887 let spec = parse_single_spec(
891 r#"spec rates
892uses lemma units
893
894data money: measure
895 -> unit eur_per_hour: eur/hour
896"#,
897 );
898 let rows = measure_unit_constraints(&spec);
899 assert_eq!(rows.len(), 1);
900 let (name, unit_arg) = unit_name_and_arg(&rows[0]);
901 assert_eq!(name, "eur_per_hour");
902 assert_eq!(
903 unit_arg,
904 UnitArg::Expr(
905 rust_decimal::Decimal::ONE,
906 vec![
907 UnitFactor {
908 measure_ref: "eur".to_string(),
909 exp: 1,
910 },
911 UnitFactor {
912 measure_ref: "hour".to_string(),
913 exp: -1,
914 }
915 ],
916 )
917 );
918 }
919
920 #[test]
923 fn parse_unit_deprecated_space_factor_payload() {
924 let spec = parse_single_spec(
925 r#"spec money_spec
926data money: measure
927 -> unit eur 1.00
928"#,
929 );
930 let rows = measure_unit_constraints(&spec);
931 assert_eq!(rows.len(), 1);
932 let (name, unit_arg) = unit_name_and_arg(&rows[0]);
933 assert_eq!(name, "eur");
934 assert_eq!(unit_arg, UnitArg::Factor(decimal("1.00")));
935 assert!(rows[0].deprecated_without_colon);
936 }
937
938 #[test]
939 fn parse_unit_deprecated_space_compound_only_payload() {
940 let spec = parse_single_spec(
941 r#"spec rates
942uses lemma units
943
944data money: measure
945 -> unit eur 1.00
946
947data rate: measure
948 -> unit eur_per_hour eur/hour
949"#,
950 );
951 let rows = measure_unit_constraints(&spec);
952 assert_eq!(rows.len(), 2);
953 let (name, unit_arg) = unit_name_and_arg(&rows[1]);
954 assert_eq!(name, "eur_per_hour");
955 assert_eq!(
956 unit_arg,
957 UnitArg::Expr(
958 rust_decimal::Decimal::ONE,
959 vec![
960 UnitFactor {
961 measure_ref: "eur".to_string(),
962 exp: 1,
963 },
964 UnitFactor {
965 measure_ref: "hour".to_string(),
966 exp: -1,
967 }
968 ],
969 )
970 );
971 assert!(rows[1].deprecated_without_colon);
972 }
973
974 #[test]
975 fn parse_unit_deprecated_space_numeric_prefix_and_compound_payload() {
976 let spec = parse_single_spec(
977 r#"spec speed
978uses lemma units
979
980data velocity: measure
981 -> unit kmh 3.6 meter/second
982"#,
983 );
984 let rows = measure_unit_constraints(&spec);
985 assert_eq!(rows.len(), 1);
986 let (name, unit_arg) = unit_name_and_arg(&rows[0]);
987 assert_eq!(name, "kmh");
988 assert_eq!(
989 unit_arg,
990 UnitArg::Expr(
991 decimal("3.6"),
992 vec![
993 UnitFactor {
994 measure_ref: "meter".to_string(),
995 exp: 1,
996 },
997 UnitFactor {
998 measure_ref: "second".to_string(),
999 exp: -1,
1000 }
1001 ],
1002 )
1003 );
1004 assert!(rows[0].deprecated_without_colon);
1005 }
1006
1007 #[test]
1008 fn parse_unit_deprecated_space_matches_colon_payload() {
1009 let canonical = parse_single_spec(
1010 r#"spec rates
1011uses lemma units
1012
1013data money: measure
1014 -> unit eur: 1.00
1015
1016data rate: measure
1017 -> unit eur_per_hour: eur/hour
1018"#,
1019 );
1020 let deprecated = parse_single_spec(
1021 r#"spec rates
1022uses lemma units
1023
1024data money: measure
1025 -> unit eur 1.00
1026
1027data rate: measure
1028 -> unit eur_per_hour eur/hour
1029"#,
1030 );
1031 let canonical_args: Vec<UnitArg> = measure_unit_constraints(&canonical)
1032 .iter()
1033 .map(|row| unit_name_and_arg(row).1)
1034 .collect();
1035 let deprecated_args: Vec<UnitArg> = measure_unit_constraints(&deprecated)
1036 .iter()
1037 .map(|row| unit_name_and_arg(row).1)
1038 .collect();
1039 assert_eq!(canonical_args, deprecated_args);
1040 }
1041
1042 #[test]
1043 fn parse_unit_colon_without_payload_errors() {
1044 let result = parse(
1045 r#"spec s
1046data money: measure
1047 -> unit eur:
1048"#,
1049 crate::parsing::source::SourceType::Volatile,
1050 &ResourceLimits::default(),
1051 );
1052 assert!(
1053 result.is_err(),
1054 "empty unit payload after colon must not parse"
1055 );
1056 }
1057
1058 fn rule_expression(source: &str, rule_name: &str) -> Expression {
1059 let parsed = parse(
1060 source,
1061 crate::parsing::source::SourceType::Volatile,
1062 &ResourceLimits::default(),
1063 )
1064 .expect("expected parse");
1065 let spec = parsed
1066 .flatten_specs()
1067 .into_iter()
1068 .next()
1069 .expect("expected one spec");
1070 spec.rules
1071 .iter()
1072 .find(|rule| rule.name == rule_name)
1073 .unwrap_or_else(|| panic!("rule '{rule_name}' not found"))
1074 .expression
1075 .clone()
1076 }
1077
1078 fn assert_multiply_range_side(
1079 root: ExprRef<'_, ExpressionKind>,
1080 range_on_left: bool,
1081 label: &str,
1082 ) {
1083 let Some((left, ArithmeticComputation::Multiply, right)) = binary_arithmetic(root) else {
1084 panic!("{label}: expected Multiply, got {:?}", root.kind());
1085 };
1086 let (range, other) = if range_on_left {
1087 (left, right)
1088 } else {
1089 (right, left)
1090 };
1091 assert!(
1092 matches!(range.kind(), ExpressionKind::RangeLiteral(..)),
1093 "{label}: expected RangeLiteral on {} of *, got {:?}",
1094 if range_on_left { "left" } else { "right" },
1095 range.kind()
1096 );
1097 assert!(
1098 !matches!(other.kind(), ExpressionKind::RangeLiteral(..)),
1099 "{label}: expected non-range on other side of *"
1100 );
1101 }
1102
1103 #[test]
1104 fn parse_range_binds_tighter_than_multiply() {
1105 let base = r#"spec test
1106uses lemma units
1107data rate: measure -> unit eur: 1
1108data period_start: 2026-01-01
1109data period_end: 2026-01-02
1110"#;
1111 let rhs = rule_expression(
1112 &format!("{base}rule rhs: rate * period_start...period_end"),
1113 "rhs",
1114 );
1115 assert_multiply_range_side(rhs.root(), false, "rate * period_start...period_end");
1116 let lhs = rule_expression(
1117 &format!("{base}rule lhs: period_start...period_end * rate"),
1118 "lhs",
1119 );
1120 assert_multiply_range_side(lhs.root(), true, "period_start...period_end * rate");
1121 }
1122
1123 #[test]
1124 fn parse_range_additive_right_endpoint_binds_inside_literal() {
1125 let expression = rule_expression(
1126 r#"spec test
1127uses lemma units
1128data start: date
1129data length: units.duration
1130rule valid: now in start...start + length"#,
1131 "valid",
1132 );
1133 let root = expression.root();
1134 let ExpressionKind::RangeContainment(value, range) = root.kind() else {
1135 panic!("expected RangeContainment, got {:?}", root.kind());
1136 };
1137 let value = root.child(*value);
1138 assert!(
1139 matches!(value.kind(), ExpressionKind::Now),
1140 "expected now as containment value, got {:?}",
1141 value.kind()
1142 );
1143 let range = root.child(*range);
1144 let ExpressionKind::RangeLiteral(left, right) = range.kind() else {
1145 panic!(
1146 "expected RangeLiteral as containment range, got {:?}",
1147 range.kind()
1148 );
1149 };
1150 let left = range.child(*left);
1151 assert!(
1152 matches!(left.kind(), ExpressionKind::Reference(..)),
1153 "expected start reference as left endpoint, got {:?}",
1154 left.kind()
1155 );
1156 let right = range.child(*right);
1157 let Some((add_left, ArithmeticComputation::Add, add_right)) = binary_arithmetic(right)
1158 else {
1159 panic!(
1160 "expected start + length as right endpoint, got {:?}",
1161 right.kind()
1162 );
1163 };
1164 assert!(
1165 matches!(add_left.kind(), ExpressionKind::Reference(..)),
1166 "expected start reference in right endpoint add, got {:?}",
1167 add_left.kind()
1168 );
1169 assert!(
1170 matches!(add_right.kind(), ExpressionKind::Reference(..)),
1171 "expected length reference in right endpoint add, got {:?}",
1172 add_right.kind()
1173 );
1174 }
1175
1176 #[test]
1177 fn parse_range_multiply_with_conversion_without_inner_parens() {
1178 let expression = rule_expression(
1179 r#"spec test
1180uses lemma units
1181data money: measure -> unit eur: 1
1182data rate: measure -> unit eur_per_hour: eur/hour
1183data hourly_rate: 50 eur_per_hour
1184data period_start: 2026-01-01
1185data period_end: 2026-01-02
1186rule pay: (hourly_rate * period_start...period_end) as eur"#,
1187 "pay",
1188 );
1189 let ExpressionKind::UnitConversion(inner, _) = expression.root_kind() else {
1190 panic!("expected UnitConversion, got {:?}", expression.root_kind());
1191 };
1192 assert_multiply_range_side(expression.at(*inner), false, "pay");
1193 }
1194
1195 #[test]
1196 fn parse_error_includes_attribute_and_parse_error_spec_name() {
1197 let result = parse(
1198 r#"
1199spec test
1200data name: "Unclosed string
1201data age: 25
1202"#,
1203 crate::parsing::source::SourceType::Volatile,
1204 &ResourceLimits::default(),
1205 );
1206
1207 match result {
1208 Err(Error::Parsing(details)) => {
1209 let src = details
1210 .source
1211 .as_ref()
1212 .expect("BUG: parsing errors always have source");
1213 assert_eq!(
1214 src.source_type,
1215 crate::parsing::source::SourceType::Volatile
1216 );
1217 }
1218 Err(e) => panic!("Expected Parse error, got: {e:?}"),
1219 Ok(_) => panic!("Expected parse error for unclosed string"),
1220 }
1221 }
1222
1223 #[test]
1224 fn parse_single_spec_file() {
1225 let input = r#"spec somespec
1226data name: "Alice""#;
1227 let parsed = parse(
1228 input,
1229 crate::parsing::source::SourceType::Volatile,
1230 &ResourceLimits::default(),
1231 )
1232 .unwrap();
1233 let specs = parsed.flatten_specs();
1234 assert_eq!(specs.len(), 1);
1235 assert_eq!(specs[0].name, "somespec");
1236 }
1237
1238 #[test]
1239 fn parse_uses_registry_spec_explicit_alias() {
1240 let input = r#"spec example
1241uses external: @user/workspace somespec"#;
1242 let specs = parse(
1243 input,
1244 crate::parsing::source::SourceType::Volatile,
1245 &ResourceLimits::default(),
1246 )
1247 .unwrap()
1248 .into_flattened_specs();
1249 assert_eq!(specs.len(), 1);
1250 assert_eq!(specs[0].data.len(), 1);
1251 match &specs[0].data[0].value {
1252 crate::parsing::ast::DataValue::Import { spec_ref, .. } => {
1253 assert_eq!(spec_ref.name, "somespec");
1254 let repository_hdr = spec_ref
1255 .repository
1256 .as_ref()
1257 .expect("expected repository qualifier");
1258 assert_eq!(repository_hdr.name, "@user/workspace");
1259 }
1260 other => panic!("Expected Import, got: {:?}", other),
1261 }
1262 }
1263
1264 #[test]
1265 fn parse_multiple_specs_cross_reference_in_file() {
1266 let input = r#"spec spec_a
1267data x: 10
1268
1269spec spec_b
1270data y: 20
1271uses a: spec_a"#;
1272 let parsed = parse(
1273 input,
1274 crate::parsing::source::SourceType::Volatile,
1275 &ResourceLimits::default(),
1276 )
1277 .unwrap();
1278 let specs = parsed.flatten_specs();
1279 assert_eq!(specs.len(), 2);
1280 assert_eq!(specs[0].name, "spec_a");
1281 assert_eq!(specs[1].name, "spec_b");
1282 }
1283
1284 #[test]
1285 fn parse_uses_registry_spec_default_alias() {
1286 let input = "spec example\nuses @owner/repo somespec";
1287 let specs = parse(
1288 input,
1289 crate::parsing::source::SourceType::Volatile,
1290 &ResourceLimits::default(),
1291 )
1292 .unwrap()
1293 .into_flattened_specs();
1294 match &specs[0].data[0].value {
1295 crate::parsing::ast::DataValue::Import { spec_ref, .. } => {
1296 assert_eq!(spec_ref.name, "somespec");
1297 let repository_hdr = spec_ref
1298 .repository
1299 .as_ref()
1300 .expect("expected repository qualifier");
1301 assert_eq!(repository_hdr.name, "@owner/repo");
1302 }
1303 other => panic!("Expected Import, got: {:?}", other),
1304 }
1305 }
1306
1307 #[test]
1308 fn parse_uses_local_spec_default_alias() {
1309 let input = "spec example\nuses myspec";
1310 let specs = parse(
1311 input,
1312 crate::parsing::source::SourceType::Volatile,
1313 &ResourceLimits::default(),
1314 )
1315 .unwrap()
1316 .into_flattened_specs();
1317 match &specs[0].data[0].value {
1318 crate::parsing::ast::DataValue::Import { spec_ref, .. } => {
1319 assert_eq!(spec_ref.name, "myspec");
1320 assert!(
1321 spec_ref.repository.is_none(),
1322 "same-repository reference must omit repository qualifier"
1323 );
1324 }
1325 other => panic!("Expected Import, got: {:?}", other),
1326 }
1327 }
1328
1329 #[test]
1330 fn parse_spec_name_with_trailing_dot_is_rejected() {
1331 let input = "spec myspec.\ndata x: 1";
1332 let error = parse(
1333 input,
1334 crate::parsing::source::SourceType::Volatile,
1335 &ResourceLimits::default(),
1336 )
1337 .expect_err("a spec name has no '.'");
1338 assert!(
1339 error
1340 .to_string()
1341 .contains("'.' is not allowed in spec names: 'myspec.'"),
1342 "got: {error}"
1343 );
1344 }
1345
1346 #[test]
1347 fn parse_multiple_specs_in_same_file() {
1348 let input = "spec myspec_a\nrule x: 1\n\nspec myspec_b\nrule x: 2";
1349 let result = parse(
1350 input,
1351 crate::parsing::source::SourceType::Volatile,
1352 &ResourceLimits::default(),
1353 )
1354 .unwrap()
1355 .into_flattened_specs();
1356 assert_eq!(result.len(), 2);
1357 assert_eq!(result[0].name, "myspec_a");
1358 assert_eq!(result[1].name, "myspec_b");
1359 }
1360
1361 #[test]
1362 fn parse_uses_accepts_name_only() {
1363 let input = "spec consumer\nuses other";
1364 let result = parse(
1365 input,
1366 crate::parsing::source::SourceType::Volatile,
1367 &ResourceLimits::default(),
1368 );
1369 assert!(result.is_ok(), "uses name should parse");
1370 let specs = result.unwrap().into_flattened_specs();
1371 let spec_ref = match &specs[0].data[0].value {
1372 crate::parsing::ast::DataValue::Import { spec_ref, .. } => spec_ref,
1373 _ => panic!("expected Import"),
1374 };
1375 assert_eq!(spec_ref.name, "other");
1376 }
1377
1378 #[test]
1379 fn parse_uses_bare_year_effective() {
1380 let input = "spec consumer\nuses other 2026";
1381 let result = parse(
1382 input,
1383 crate::parsing::source::SourceType::Volatile,
1384 &ResourceLimits::default(),
1385 )
1386 .unwrap();
1387 let specs = result.into_flattened_specs();
1388 let spec_ref = match &specs[0].data[0].value {
1389 crate::parsing::ast::DataValue::Import { spec_ref, .. } => spec_ref,
1390 _ => panic!("expected Import"),
1391 };
1392 assert_eq!(spec_ref.name, "other");
1393 let eff = spec_ref.effective.as_ref().expect("effective");
1394 assert_eq!(eff.year, 2026);
1395 assert_eq!(eff.month, 1);
1396 assert_eq!(eff.day, 1);
1397 }
1398
1399 #[test]
1400 fn parse_uses_registry_spec_ref_records_repository_and_target_spans() {
1401 let input = "spec consumer\nuses @iso/countries alpha2 2026";
1402 let result = parse(
1403 input,
1404 crate::parsing::source::SourceType::Volatile,
1405 &ResourceLimits::default(),
1406 )
1407 .unwrap();
1408 let spec = &result.flatten_specs()[0];
1409 let sr = match &spec.data[0].value {
1410 crate::parsing::ast::DataValue::Import { spec_ref, .. } => spec_ref,
1411 _ => panic!("expected Import"),
1412 };
1413 let rs = sr
1414 .repository_span
1415 .as_ref()
1416 .expect("repository_span should be set for @-qualified uses");
1417 let ts = sr
1418 .target_span
1419 .as_ref()
1420 .expect("target_span should cover spec name and effective");
1421 assert_eq!(&input[rs.start..rs.end], "@iso/countries");
1422 assert_eq!(&input[ts.start..ts.end], "alpha2 2026");
1423 }
1424
1425 #[test]
1426 fn parse_uses_alias_no_comma_continuation() {
1427 let input = "spec consumer\nuses alias: pricing retail\ndata x: 1";
1428 let result = parse(
1429 input,
1430 crate::parsing::source::SourceType::Volatile,
1431 &ResourceLimits::default(),
1432 )
1433 .unwrap();
1434 let data = &result.flatten_specs()[0].data;
1435 assert_eq!(data.len(), 2);
1436 assert_eq!(data[0].reference.name, "alias");
1437 let sr = match &data[0].value {
1438 crate::parsing::ast::DataValue::Import { spec_ref, .. } => spec_ref,
1439 _ => panic!("expected Import"),
1440 };
1441 assert_eq!(sr.name, "retail");
1442 let repository_hdr = sr
1443 .repository
1444 .as_ref()
1445 .expect("expected repository qualifier");
1446 assert_eq!(repository_hdr.name, "pricing");
1447 }
1448
1449 #[test]
1450 fn parse_data_qualified_type_with_effective_and_repository_on_uses() {
1451 let input = "spec consumer\nuses @iso/countries alpha2 2026-06-01\ndata country: alpha2.code -> option \"NL\"";
1452 let result = parse(
1453 input,
1454 crate::parsing::source::SourceType::Volatile,
1455 &ResourceLimits::default(),
1456 )
1457 .unwrap()
1458 .into_flattened_specs();
1459 let spec_ref = match &result[0].data[0].value {
1460 crate::parsing::ast::DataValue::Import { spec_ref: sr, .. } => sr,
1461 other => panic!("expected Import on uses row, got: {:?}", other),
1462 };
1463 assert_eq!(spec_ref.name, "alpha2");
1464
1465 let eff = spec_ref
1466 .effective
1467 .as_ref()
1468 .expect("expected effective datetime");
1469 assert_eq!(eff.year, 2026);
1470 assert_eq!(eff.month, 6);
1471
1472 let qualifier = spec_ref
1473 .repository
1474 .as_ref()
1475 .expect("expected repository qualifier");
1476 assert_eq!(qualifier.name, "@iso/countries");
1477
1478 match &result[0].data[1].value {
1479 crate::parsing::ast::DataValue::Definition {
1480 base,
1481 constraints,
1482 value,
1483 list: _,
1484 } => {
1485 assert!(value.is_none());
1486 assert_eq!(
1487 base.as_ref().expect("expected base"),
1488 &crate::parsing::ast::ParentType::Qualified {
1489 spec_alias: "alpha2".into(),
1490 inner: Box::new(crate::parsing::ast::ParentType::custom("code")),
1491 }
1492 );
1493
1494 let cs = constraints
1495 .as_ref()
1496 .expect("expected trailing constraint chain");
1497 assert_eq!(cs.len(), 1);
1498 }
1499 other => panic!("expected Definition, got: {:?}", other),
1500 }
1501 }
1502
1503 #[test]
1504 fn parse_qualified_type_with_slashed_opaque_spec_name() {
1505 let input = r#"
1506spec logistics/terms
1507data incoterm_type: text
1508
1509spec logistics/shipping
1510uses logistics/terms
1511data incoterm: logistics/terms.incoterm_type
1512"#;
1513 let result = parse(
1514 input,
1515 crate::parsing::source::SourceType::Volatile,
1516 &ResourceLimits::default(),
1517 )
1518 .unwrap()
1519 .into_flattened_specs();
1520 assert_eq!(result.len(), 2);
1521 assert_eq!(result[0].name, "logistics/terms");
1522 assert_eq!(result[1].name, "logistics/shipping");
1523 assert_eq!(result[1].data[0].reference.name, "logistics/terms");
1524 let import = match &result[1].data[0].value {
1525 crate::parsing::ast::DataValue::Import { spec_ref, .. } => spec_ref,
1526 other => panic!("expected Import, got: {other:?}"),
1527 };
1528 assert_eq!(import.name, "logistics/terms");
1529 assert!(import.repository.is_none());
1530 match &result[1].data[1].value {
1531 crate::parsing::ast::DataValue::Definition {
1532 base: Some(base), ..
1533 } => {
1534 assert_eq!(
1535 base,
1536 &crate::parsing::ast::ParentType::Qualified {
1537 spec_alias: "logistics/terms".into(),
1538 inner: Box::new(crate::parsing::ast::ParentType::custom("incoterm_type",)),
1539 }
1540 );
1541 }
1542 other => panic!("expected Definition with qualified base, got: {other:?}"),
1543 }
1544 }
1545
1546 #[test]
1547 fn parse_uses_slashed_name_alias_is_full_opaque_name() {
1548 let input = "spec consumer\nuses finance/units\ndata x: 1";
1549 let result = parse(
1550 input,
1551 crate::parsing::source::SourceType::Volatile,
1552 &ResourceLimits::default(),
1553 )
1554 .unwrap()
1555 .into_flattened_specs();
1556 assert_eq!(result[0].data[0].reference.name, "finance/units");
1557 let sr = match &result[0].data[0].value {
1558 crate::parsing::ast::DataValue::Import { spec_ref, .. } => spec_ref,
1559 other => panic!("expected Import, got: {other:?}"),
1560 };
1561 assert_eq!(sr.name, "finance/units");
1562 assert!(sr.repository.is_none());
1563 }
1564
1565 #[test]
1566 fn parse_uses_terms_is_spec_named_terms_not_sibling_of_logistics() {
1567 let input = "spec logistics/shipping\nuses terms\ndata x: 1";
1568 let result = parse(
1569 input,
1570 crate::parsing::source::SourceType::Volatile,
1571 &ResourceLimits::default(),
1572 )
1573 .unwrap()
1574 .into_flattened_specs();
1575 assert_eq!(result[0].data[0].reference.name, "terms");
1576 let sr = match &result[0].data[0].value {
1577 crate::parsing::ast::DataValue::Import { spec_ref, .. } => spec_ref,
1578 other => panic!("expected Import, got: {other:?}"),
1579 };
1580 assert_eq!(sr.name, "terms");
1581 assert!(sr.repository.is_none());
1582 }
1583
1584 #[test]
1585 fn parse_error_is_returned_for_garbage_input() {
1586 let result = parse(
1587 r#"
1588spec test
1589this is not valid lemma syntax @#$%
1590"#,
1591 crate::parsing::source::SourceType::Volatile,
1592 &ResourceLimits::default(),
1593 );
1594
1595 assert!(result.is_err(), "Should fail on malformed input");
1596 match result {
1597 Err(Error::Parsing { .. }) => {
1598 }
1600 Err(e) => panic!("Expected Parse error, got: {e:?}"),
1601 Ok(_) => panic!("Expected parse error"),
1602 }
1603 }
1604
1605 #[test]
1608 fn parse_local_with_literal_rejected() {
1609 let err = parse(
1610 r#"spec s
1611with x: 42"#,
1612 crate::parsing::source::SourceType::Volatile,
1613 &ResourceLimits::default(),
1614 )
1615 .unwrap_err();
1616 let msg = err.to_string();
1617 assert!(
1618 msg.contains("Standalone") || msg.contains("uses"),
1619 "expected standalone with rejection, got: {msg}"
1620 );
1621 }
1622
1623 #[test]
1624 fn parse_local_with_import_reference_rejected() {
1625 let err = parse(
1626 r#"spec s
1627uses i: inner
1628with copy: i.v"#,
1629 crate::parsing::source::SourceType::Volatile,
1630 &ResourceLimits::default(),
1631 )
1632 .unwrap_err();
1633 let msg = err.to_string();
1634 assert!(
1635 msg.contains("Standalone") || msg.contains("uses"),
1636 "expected standalone with rejection, got: {msg}"
1637 );
1638 }
1639
1640 #[test]
1641 fn parse_local_with_dotted_rhs_rejected() {
1642 let err = parse(
1643 r#"spec s
1644with x: a.something"#,
1645 crate::parsing::source::SourceType::Volatile,
1646 &ResourceLimits::default(),
1647 )
1648 .unwrap_err();
1649 let msg = err.to_string();
1650 assert!(
1651 msg.contains("Standalone") || msg.contains("uses"),
1652 "expected standalone with rejection, got: {msg}"
1653 );
1654 }
1655
1656 #[test]
1657 fn parse_local_with_multi_segment_rhs_rejected() {
1658 let err = parse(
1659 r#"spec s
1660with x: alpha.beta.gamma.delta"#,
1661 crate::parsing::source::SourceType::Volatile,
1662 &ResourceLimits::default(),
1663 )
1664 .unwrap_err();
1665 let msg = err.to_string();
1666 assert!(
1667 msg.contains("Standalone") || msg.contains("uses"),
1668 "expected standalone with rejection, got: {msg}"
1669 );
1670 }
1671
1672 #[test]
1675 fn parse_local_non_dotted_rhs_stays_definition_with_custom_base() {
1676 let input = r#"spec s
1677data x: myothertype"#;
1678 let result = parse(
1679 input,
1680 crate::parsing::source::SourceType::Volatile,
1681 &ResourceLimits::default(),
1682 )
1683 .unwrap()
1684 .into_flattened_specs();
1685 let value = &result[0].data[0].value;
1686 assert!(
1687 matches!(
1688 value,
1689 crate::parsing::ast::DataValue::Definition {
1690 base: Some(crate::parsing::ast::ParentType::Custom { .. }),
1691 ..
1692 }
1693 ),
1694 "non-dotted local RHS must stay Definition with custom base, got: {:?}",
1695 value
1696 );
1697 }
1698
1699 #[test]
1701 fn parse_uses_binding_non_dotted_rhs_is_reference() {
1702 let input = r#"spec s
1703uses child: other
1704 -> with slot: somename"#;
1705 let result = parse(
1706 input,
1707 crate::parsing::source::SourceType::Volatile,
1708 &ResourceLimits::default(),
1709 )
1710 .unwrap()
1711 .into_flattened_specs();
1712 let bindings = match &result[0].data[0].value {
1713 crate::parsing::ast::DataValue::Import { bindings, .. } => bindings,
1714 other => panic!("expected Import, got: {:?}", other),
1715 };
1716 assert_eq!(bindings.len(), 1);
1717 assert!(
1718 matches!(
1719 &bindings[0].rhs,
1720 crate::parsing::ast::UsesBindingRhs::References { targets }
1721 if targets.len() == 1
1722 ),
1723 "non-dotted RHS must yield Reference; got: {:?}",
1724 bindings[0].rhs
1725 );
1726 }
1727
1728 #[test]
1729 fn parse_uses_binding_keeps_ordered_aliases_in_one_binding() {
1730 let input = r#"spec s
1731uses tree: node
1732 -> with children: left, right"#;
1733 let result = parse(
1734 input,
1735 crate::parsing::source::SourceType::Volatile,
1736 &ResourceLimits::default(),
1737 )
1738 .unwrap()
1739 .into_flattened_specs();
1740 let bindings = match &result[0].data[0].value {
1741 crate::parsing::ast::DataValue::Import { bindings, .. } => bindings,
1742 other => panic!("expected Import, got: {other:?}"),
1743 };
1744 assert_eq!(bindings.len(), 1);
1745 assert_eq!(bindings[0].path.name, "children");
1746 let crate::parsing::ast::UsesBindingRhs::References { targets } = &bindings[0].rhs else {
1747 panic!("expected ordered references, got: {:?}", bindings[0].rhs);
1748 };
1749 assert_eq!(
1750 targets.iter().map(ToString::to_string).collect::<Vec<_>>(),
1751 ["left", "right"]
1752 );
1753 }
1754
1755 #[test]
1756 fn parse_uses_alias_sequence_can_precede_another_field_pair() {
1757 let input = r#"spec s
1758uses tree: node
1759 -> with children: left, right, weight: 2"#;
1760 let result = parse(
1761 input,
1762 crate::parsing::source::SourceType::Volatile,
1763 &ResourceLimits::default(),
1764 )
1765 .unwrap()
1766 .into_flattened_specs();
1767 let bindings = match &result[0].data[0].value {
1768 crate::parsing::ast::DataValue::Import { bindings, .. } => bindings,
1769 other => panic!("expected Import, got: {other:?}"),
1770 };
1771 assert_eq!(bindings.len(), 2);
1772 assert_eq!(bindings[0].path.name, "children");
1773 assert_eq!(bindings[1].path.name, "weight");
1774 }
1775
1776 #[test]
1777 fn parse_uses_alias_sequence_rejects_literal_member() {
1778 let err = parse(
1779 "spec s\nuses tree: node\n -> with children: left, 2",
1780 crate::parsing::source::SourceType::Volatile,
1781 &ResourceLimits::default(),
1782 )
1783 .expect_err("alias sequence containing a literal must fail");
1784 assert!(
1785 err.to_string().contains("cannot contain literals"),
1786 "unexpected error: {err}"
1787 );
1788 }
1789
1790 #[test]
1792 fn parse_data_colon_spec_rhs_is_rejected() {
1793 let result = parse(
1794 r#"
1795spec s
1796data x: spec other
1797"#,
1798 crate::parsing::source::SourceType::Volatile,
1799 &ResourceLimits::default(),
1800 );
1801 match result {
1802 Ok(_) => panic!("`data x: spec other` must fail to parse"),
1803 Err(err) => {
1804 let msg = err.to_string();
1805 assert!(
1806 msg.contains("uses") && msg.contains("spec"),
1807 "error must direct to `uses` for spec import, got: {msg}"
1808 );
1809 }
1810 }
1811 }
1812
1813 #[test]
1815 fn parse_uses_binding_with_dotted_rhs_preserves_both_sides() {
1816 let input = r#"spec s
1817uses outer: other
1818 -> with inner: target.field"#;
1819 let result = parse(
1820 input,
1821 crate::parsing::source::SourceType::Volatile,
1822 &ResourceLimits::default(),
1823 )
1824 .unwrap()
1825 .into_flattened_specs();
1826 let bindings = match &result[0].data[0].value {
1827 crate::parsing::ast::DataValue::Import { bindings, .. } => bindings,
1828 other => panic!("expected Import, got: {:?}", other),
1829 };
1830 assert_eq!(bindings.len(), 1);
1831 assert_eq!(bindings[0].path.segments, vec![] as Vec<String>);
1832 assert_eq!(bindings[0].path.name, "inner");
1833 match &bindings[0].rhs {
1834 crate::parsing::ast::UsesBindingRhs::References { targets } => {
1835 let [target] = targets.as_slice() else {
1836 panic!("expected one reference, got: {targets:?}");
1837 };
1838 assert_eq!(target.segments, vec!["target"]);
1839 assert_eq!(target.name, "field");
1840 }
1841 other => panic!("expected Reference rhs, got: {:?}", other),
1842 }
1843 }
1844
1845 #[test]
1846 fn parse_deprecated_standalone_with_is_error() {
1847 let input = r#"spec inner
1848data x: number
1849
1850spec outer
1851uses i: inner
1852with i.x: 42
1853rule r: i.x"#;
1854 let result = parse(
1855 input,
1856 crate::parsing::source::SourceType::Volatile,
1857 &ResourceLimits::default(),
1858 );
1859 match result {
1860 Ok(_) => panic!("standalone with after uses must not parse"),
1861 Err(err) => {
1862 let msg = err.to_string();
1863 assert!(
1864 msg.contains("with"),
1865 "error should mention with; got: {msg}"
1866 );
1867 }
1868 }
1869 }
1870
1871 #[test]
1872 fn parse_deprecated_standalone_with_before_uses_is_error() {
1873 let input = r#"spec inner
1874data slot: number
1875
1876spec outer
1877with i.slot: 99
1878uses i: inner
1879rule r: i.slot"#;
1880 let result = parse(
1881 input,
1882 crate::parsing::source::SourceType::Volatile,
1883 &ResourceLimits::default(),
1884 );
1885 match result {
1886 Ok(_) => panic!("standalone with before uses must not parse"),
1887 Err(err) => {
1888 let msg = err.to_string();
1889 assert!(
1890 msg.contains("with"),
1891 "error should mention with; got: {msg}"
1892 );
1893 }
1894 }
1895 }
1896
1897 #[test]
1898 fn parse_standalone_with_without_matching_uses_errors() {
1899 let result = parse(
1900 r#"spec s
1901with outer.inner: 1"#,
1902 crate::parsing::source::SourceType::Volatile,
1903 &ResourceLimits::default(),
1904 );
1905 match result {
1906 Ok(_) => panic!("standalone with without uses must not parse"),
1907 Err(err) => {
1908 let msg = err.to_string();
1909 assert!(
1910 msg.contains("with"),
1911 "error should mention with; got: {msg}"
1912 );
1913 }
1914 }
1915 }
1916
1917 #[test]
1918 fn parse_data_on_binding_path_is_rejected_with_with_hint() {
1919 let result = parse(
1920 r#"spec s
1921data outer.inner: 1"#,
1922 crate::parsing::source::SourceType::Volatile,
1923 &ResourceLimits::default(),
1924 );
1925 match result {
1926 Ok(_) => panic!("data with binding path must not parse"),
1927 Err(err) => {
1928 let msg = err.to_string();
1929 assert!(
1930 msg.contains("with"),
1931 "error should steer authors toward with; got: {msg}"
1932 );
1933 }
1934 }
1935 }
1936
1937 #[test]
1938 fn parse_bare_file_yields_single_anonymous_repository_group() {
1939 let input = "spec a\ndata x: 1\nspec b\ndata y: 2";
1940 let parsed = parse(
1941 input,
1942 crate::parsing::source::SourceType::Volatile,
1943 &ResourceLimits::default(),
1944 )
1945 .unwrap();
1946 assert_eq!(parsed.repositories.len(), 1);
1947 let (repo, specs) = parsed.repositories.iter().next().unwrap();
1948 assert!(repo.name.is_none());
1949 assert_eq!(specs.len(), 2);
1950 assert_eq!(specs[0].name, "a");
1951 assert_eq!(specs[1].name, "b");
1952 }
1953
1954 #[test]
1955 fn parse_repo_sections_preserve_order_and_names() {
1956 let input = r#"repo r1
1957
1958spec a
1959data x: 1
1960
1961repo r2
1962
1963spec b
1964data y: 2"#;
1965 let parsed = parse(
1966 input,
1967 crate::parsing::source::SourceType::Volatile,
1968 &ResourceLimits::default(),
1969 )
1970 .unwrap();
1971 assert_eq!(parsed.repositories.len(), 2);
1972 let keys: Vec<_> = parsed.repositories.keys().collect();
1973 assert_eq!(keys[0].name.as_deref(), Some("r1"));
1974 assert_eq!(keys[1].name.as_deref(), Some("r2"));
1975 }
1976
1977 #[test]
1978 fn parse_duplicate_repo_name_merges_spec_lists() {
1979 let input = r#"repo dup
1980
1981spec a
1982data x: 1
1983
1984repo dup
1985
1986spec b
1987data y: 2"#;
1988 let parsed = parse(
1989 input,
1990 crate::parsing::source::SourceType::Volatile,
1991 &ResourceLimits::default(),
1992 )
1993 .unwrap();
1994 assert_eq!(parsed.repositories.len(), 1);
1995 assert_eq!(parsed.flatten_specs().len(), 2);
1996 }
1997
1998 #[test]
1999 fn parse_repo_with_no_specs_then_eof_yields_empty_spec_vec_for_that_repo() {
2000 let input = "repo empty";
2001 let parsed = parse(
2002 input,
2003 crate::parsing::source::SourceType::Volatile,
2004 &ResourceLimits::default(),
2005 )
2006 .unwrap();
2007 assert_eq!(parsed.repositories.len(), 1);
2008 let (_, specs) = parsed.repositories.iter().next().unwrap();
2009 assert_eq!(specs.len(), 0);
2010 }
2011
2012 #[test]
2013 fn parse_repo_followed_by_repo_without_specs_first_repo_empty_second_has_spec() {
2014 let input = "repo a\n\nrepo b\n\nspec s\ndata x: 1";
2015 let parsed = parse(
2016 input,
2017 crate::parsing::source::SourceType::Volatile,
2018 &ResourceLimits::default(),
2019 )
2020 .unwrap();
2021 assert_eq!(parsed.repositories.len(), 2);
2022 let names: Vec<_> = parsed
2023 .repositories
2024 .keys()
2025 .map(|r| r.name.as_deref())
2026 .collect();
2027 assert_eq!(names, vec![Some("a"), Some("b")]);
2028 assert!(parsed.repositories.values().next().unwrap().is_empty());
2029 assert_eq!(parsed.repositories.values().nth(1).unwrap().len(), 1);
2030 }
2031
2032 #[test]
2033 fn parse_spec_named_repo_keyword_should_be_rejected() {
2034 assert!(
2035 parse(
2036 "spec repo\ndata x: 1",
2037 crate::parsing::source::SourceType::Volatile,
2038 &ResourceLimits::default(),
2039 )
2040 .is_err(),
2041 "spec must not be allowed to use reserved keyword `repo` as its name"
2042 );
2043 }
2044
2045 #[test]
2046 fn parse_repo_declaration_cannot_use_spec_keyword_as_repository_name() {
2047 assert!(
2048 parse(
2049 "repo spec\n\nspec z\ndata q: 1\nrule r: q",
2050 crate::parsing::source::SourceType::Volatile,
2051 &ResourceLimits::default(),
2052 )
2053 .is_err(),
2054 "repository name cannot be the token `spec`"
2055 );
2056 }
2057
2058 #[test]
2059 fn parse_repo_declaration_cannot_use_data_keyword_as_repository_name() {
2060 assert!(
2061 parse(
2062 "repo data\n\nspec z\ndata q: 1\nrule r: q",
2063 crate::parsing::source::SourceType::Volatile,
2064 &ResourceLimits::default(),
2065 )
2066 .is_err(),
2067 "repository name cannot be the token `data`"
2068 );
2069 }
2070
2071 #[test]
2072 fn parse_repo_declaration_cannot_use_rule_keyword_as_repository_name() {
2073 assert!(
2074 parse(
2075 "repo rule\n\nspec z\ndata q: 1\nrule r: q",
2076 crate::parsing::source::SourceType::Volatile,
2077 &ResourceLimits::default(),
2078 )
2079 .is_err(),
2080 "repository name cannot be the token `rule`"
2081 );
2082 }
2083
2084 #[test]
2085 fn parse_data_named_repo_keyword_is_rejected() {
2086 let err = parse(
2087 "spec s\ndata repo: 1",
2088 crate::parsing::source::SourceType::Volatile,
2089 &ResourceLimits::default(),
2090 )
2091 .unwrap_err();
2092 assert!(
2093 err.to_string().contains("repo"),
2094 "data named repo should not parse: {}",
2095 err
2096 );
2097 }
2098
2099 #[test]
2100 fn parse_rule_named_repo_keyword_is_rejected() {
2101 let err = parse(
2102 "spec s\ndata x: 1\nrule repo: x",
2103 crate::parsing::source::SourceType::Volatile,
2104 &ResourceLimits::default(),
2105 )
2106 .unwrap_err();
2107 let msg = err.to_string();
2108 assert!(
2109 msg.contains("repo") || msg.contains("reserved"),
2110 "rule named repo should not parse: {msg}"
2111 );
2112 }
2113
2114 #[test]
2115 fn parse_repo_declaration_accepts_non_keyword_repository_identifier() {
2116 let parsed = parse(
2117 "repo warehouse\n\nspec z\ndata q: 1\nrule r: q",
2118 crate::parsing::source::SourceType::Volatile,
2119 &ResourceLimits::default(),
2120 )
2121 .unwrap();
2122 assert_eq!(parsed.repositories.len(), 1);
2123 assert_eq!(
2124 parsed.repositories.keys().next().unwrap().name.as_deref(),
2125 Some("warehouse")
2126 );
2127 }
2128
2129 #[test]
2130 fn parse_repo_name_case_insensitive_same_repository_merged() {
2131 let input = "repo Foo\n\nspec a\ndata x: 1\n\nrepo foo\n\nspec b\ndata y: 2";
2132 let parsed = parse(
2133 input,
2134 crate::parsing::source::SourceType::Volatile,
2135 &ResourceLimits::default(),
2136 )
2137 .unwrap();
2138 assert_eq!(
2139 parsed.repositories.len(),
2140 1,
2141 "Foo and foo are the same repository after canonicalization"
2142 );
2143 let specs: Vec<_> = parsed.repositories.values().next().unwrap().clone();
2144 assert_eq!(specs.len(), 2);
2145 assert_eq!(specs[0].name, "a");
2146 assert_eq!(specs[1].name, "b");
2147 }
2148
2149 #[test]
2150 fn parse_repo_empty_name_errors() {
2151 let err = parse(
2152 "repo \nspec a\ndata x: 1",
2153 crate::parsing::source::SourceType::Volatile,
2154 &ResourceLimits::default(),
2155 )
2156 .unwrap_err();
2157 assert!(
2158 !err.to_string().is_empty(),
2159 "empty repo name should not parse quietly: {err}"
2160 );
2161 }
2162
2163 #[test]
2164 fn parse_repo_numeric_name_behavior() {
2165 let input = "repo 123\n\nspec a\ndata x: 1";
2166 let result = parse(
2167 input,
2168 crate::parsing::source::SourceType::Volatile,
2169 &ResourceLimits::default(),
2170 );
2171 match result {
2172 Ok(parsed) => {
2173 assert_eq!(
2174 parsed.repositories.keys().next().unwrap().name.as_deref(),
2175 Some("123"),
2176 "if numeric repo names parse, identity must be stable"
2177 );
2178 }
2179 Err(e) => {
2180 assert!(
2181 !e.to_string().is_empty(),
2182 "rejecting numeric repo name is ok if explicit: {e}"
2183 );
2184 }
2185 }
2186 }
2187
2188 #[test]
2189 fn parse_duplicate_repo_three_sections_preserves_spec_order_abc() {
2190 let input = r#"repo dup
2191
2192spec a
2193data x: 1
2194
2195repo dup
2196
2197spec b
2198data y: 2
2199
2200repo dup
2201
2202spec c
2203data z: 3"#;
2204 let parsed = parse(
2205 input,
2206 crate::parsing::source::SourceType::Volatile,
2207 &ResourceLimits::default(),
2208 )
2209 .unwrap();
2210 assert_eq!(parsed.repositories.len(), 1);
2211 let specs = parsed.repositories.values().next().unwrap();
2212 assert_eq!(
2213 specs.iter().map(|s| s.name.as_str()).collect::<Vec<_>>(),
2214 vec!["a", "b", "c"]
2215 );
2216 }
2217
2218 #[test]
2219 fn parse_repo_single_section_roundtrips_through_formatter() {
2220 let input = "repo r\n\nspec a\ndata x: 1";
2221 let parsed = parse(
2222 input,
2223 crate::parsing::source::SourceType::Volatile,
2224 &ResourceLimits::default(),
2225 )
2226 .unwrap();
2227 let formatted = format_parse_result(&parsed);
2228 let again = parse(
2229 &formatted,
2230 crate::parsing::source::SourceType::Volatile,
2231 &ResourceLimits::default(),
2232 )
2233 .unwrap();
2234 assert_eq!(again.repositories.len(), parsed.repositories.len());
2235 assert_eq!(again.flatten_specs().len(), parsed.flatten_specs().len());
2236 assert_eq!(
2237 again.flatten_specs()[0].name,
2238 parsed.flatten_specs()[0].name
2239 );
2240 }
2241
2242 #[test]
2243 fn parse_repo_two_sections_roundtrips_through_formatter() {
2244 let input = "repo r1\n\nspec a\ndata x: 1\n\nrepo r2\n\nspec b\ndata y: 2";
2245 let parsed = parse(
2246 input,
2247 crate::parsing::source::SourceType::Volatile,
2248 &ResourceLimits::default(),
2249 )
2250 .unwrap();
2251 let formatted = format_parse_result(&parsed);
2252 let again = parse(
2253 &formatted,
2254 crate::parsing::source::SourceType::Volatile,
2255 &ResourceLimits::default(),
2256 )
2257 .unwrap();
2258 assert_eq!(again.repositories.len(), 2);
2259 assert_eq!(again.flatten_specs().len(), 2);
2260 }
2261
2262 #[test]
2263 fn parse_repo_duplicate_merge_formatter_emits_single_repo_block_or_equivalent_parse() {
2264 let input = r#"repo dup
2265
2266spec a
2267data x: 1
2268
2269repo dup
2270
2271spec b
2272data y: 2"#;
2273 let parsed = parse(
2274 input,
2275 crate::parsing::source::SourceType::Volatile,
2276 &ResourceLimits::default(),
2277 )
2278 .unwrap();
2279 let formatted = format_parse_result(&parsed);
2280 let again = parse(
2281 &formatted,
2282 crate::parsing::source::SourceType::Volatile,
2283 &ResourceLimits::default(),
2284 )
2285 .unwrap();
2286 assert_eq!(
2287 again.repositories.len(),
2288 1,
2289 "formatted duplicate-repo file must still merge to one logical repo"
2290 );
2291 assert_eq!(again.flatten_specs().len(), 2);
2292 }
2293
2294 #[test]
2295 fn parse_rejects_data_named_that_in_any_case() {
2296 for name in ["that", "That", "THAT"] {
2297 let result = parse(
2298 &format!("spec s\ndata {name}: 1"),
2299 crate::parsing::source::SourceType::Volatile,
2300 &ResourceLimits::default(),
2301 );
2302 let err = result.expect_err("that is reserved");
2303 assert!(
2304 err.to_string().to_ascii_lowercase().contains("that"),
2305 "{name}: expected reserved-keyword error, got: {err}"
2306 );
2307 }
2308 }
2309
2310 #[test]
2311 fn parse_rejects_data_named_measure() {
2312 let result = parse(
2313 "spec s\ndata measure: 1",
2314 crate::parsing::source::SourceType::Volatile,
2315 &ResourceLimits::default(),
2316 );
2317 assert!(
2318 result.is_err(),
2319 "data named measure (type keyword) must be rejected"
2320 );
2321 }
2322
2323 #[test]
2324 fn parse_rejects_data_named_number() {
2325 let result = parse(
2326 "spec s\ndata number: 42",
2327 crate::parsing::source::SourceType::Volatile,
2328 &ResourceLimits::default(),
2329 );
2330 assert!(
2331 result.is_err(),
2332 "data named number (type keyword) must be rejected"
2333 );
2334 }
2335
2336 #[test]
2337 fn parse_rejects_data_named_text() {
2338 let result = parse(
2339 "spec s\ndata text: \"hello\"",
2340 crate::parsing::source::SourceType::Volatile,
2341 &ResourceLimits::default(),
2342 );
2343 assert!(
2344 result.is_err(),
2345 "data named text (type keyword) must be rejected"
2346 );
2347 }
2348
2349 #[test]
2350 fn parse_rejects_data_named_date() {
2351 let result = parse(
2352 "spec s\ndata date: 2024-01-01",
2353 crate::parsing::source::SourceType::Volatile,
2354 &ResourceLimits::default(),
2355 );
2356 assert!(
2357 result.is_err(),
2358 "data named date (type keyword) must be rejected"
2359 );
2360 }
2361
2362 #[test]
2363 fn parse_rejects_data_named_boolean() {
2364 let result = parse(
2365 "spec s\ndata boolean: true",
2366 crate::parsing::source::SourceType::Volatile,
2367 &ResourceLimits::default(),
2368 );
2369 assert!(
2370 result.is_err(),
2371 "data named boolean (type keyword) must be rejected"
2372 );
2373 }
2374
2375 #[test]
2376 fn parse_rejects_data_named_ratio() {
2377 let result = parse(
2378 "spec s\ndata ratio: 5%",
2379 crate::parsing::source::SourceType::Volatile,
2380 &ResourceLimits::default(),
2381 );
2382 assert!(
2383 result.is_err(),
2384 "data named ratio (type keyword) must be rejected"
2385 );
2386 }
2387
2388 #[test]
2389 fn parse_rejects_rule_named_measure() {
2390 let result = parse(
2391 "spec s\ndata x: 1\nrule measure: x",
2392 crate::parsing::source::SourceType::Volatile,
2393 &ResourceLimits::default(),
2394 );
2395 assert!(
2396 result.is_err(),
2397 "rule named measure (type keyword) must be rejected"
2398 );
2399 }
2400
2401 #[test]
2402 fn parse_rejects_rule_named_number() {
2403 let result = parse(
2404 "spec s\ndata x: 1\nrule number: x",
2405 crate::parsing::source::SourceType::Volatile,
2406 &ResourceLimits::default(),
2407 );
2408 assert!(
2409 result.is_err(),
2410 "rule named number (type keyword) must be rejected"
2411 );
2412 }
2413
2414 #[test]
2415 fn parse_rejects_rule_named_text() {
2416 let result = parse(
2417 "spec s\ndata x: 1\nrule text: x",
2418 crate::parsing::source::SourceType::Volatile,
2419 &ResourceLimits::default(),
2420 );
2421 assert!(
2422 result.is_err(),
2423 "rule named text (type keyword) must be rejected"
2424 );
2425 }
2426
2427 #[test]
2428 fn parse_rejects_rule_named_date() {
2429 let result = parse(
2430 "spec s\ndata x: 1\nrule date: x",
2431 crate::parsing::source::SourceType::Volatile,
2432 &ResourceLimits::default(),
2433 );
2434 assert!(
2435 result.is_err(),
2436 "rule named date (type keyword) must be rejected"
2437 );
2438 }
2439
2440 #[test]
2441 fn parse_rejects_rule_named_boolean() {
2442 let result = parse(
2443 "spec s\ndata x: 1\nrule boolean: x",
2444 crate::parsing::source::SourceType::Volatile,
2445 &ResourceLimits::default(),
2446 );
2447 assert!(
2448 result.is_err(),
2449 "rule named boolean (type keyword) must be rejected"
2450 );
2451 }
2452
2453 #[test]
2454 fn parse_rejects_rule_named_ratio() {
2455 let result = parse(
2456 "spec s\ndata x: 1\nrule ratio: x",
2457 crate::parsing::source::SourceType::Volatile,
2458 &ResourceLimits::default(),
2459 );
2460 assert!(
2461 result.is_err(),
2462 "rule named ratio (type keyword) must be rejected"
2463 );
2464 }
2465
2466 fn assert_reserved_name(source: &str) {
2467 let result = parse(
2468 source,
2469 crate::parsing::source::SourceType::Volatile,
2470 &ResourceLimits::default(),
2471 );
2472 let message = result
2473 .expect_err("reserved name must not parse")
2474 .to_string();
2475 assert!(
2476 message.contains("reserved keyword"),
2477 "expected reserved-keyword error, got: {message}"
2478 );
2479 }
2480
2481 #[test]
2482 fn parse_rejects_lower_and_upper_as_names() {
2483 assert_reserved_name("spec s\ndata lower: 1");
2484 assert_reserved_name("spec s\ndata upper: 1");
2485 assert_reserved_name("spec s\nrule lower: 1");
2486 assert_reserved_name("spec s\nrule upper: 1");
2487 }
2488
2489 #[test]
2490 fn parse_constraint_lower_and_upper_still_parse() {
2491 let parsed = parse(
2492 r#"spec window
2493data period: date range
2494 -> lower 2020-01-01
2495 -> upper 2030-12-31
2496"#,
2497 crate::parsing::source::SourceType::Volatile,
2498 &ResourceLimits::default(),
2499 )
2500 .expect("-> lower / -> upper are constraint commands");
2501 let spec = parsed.flatten_specs().into_iter().next().expect("one spec");
2502 let period = spec
2503 .data
2504 .iter()
2505 .find(|data| data.reference.name == "period")
2506 .expect("period");
2507 let DataValue::Definition {
2508 constraints: Some(rows),
2509 ..
2510 } = &period.value
2511 else {
2512 panic!("expected constraints, got {:?}", period.value);
2513 };
2514 let commands: Vec<_> = rows.iter().map(|row| row.command).collect();
2515 assert_eq!(
2516 commands,
2517 vec![TypeConstraintCommand::Lower, TypeConstraintCommand::Upper]
2518 );
2519 }
2520
2521 fn prefix_expression(source: &str) -> Expression {
2522 rule_expression(source, "out")
2523 }
2524
2525 fn prefix_parse_error(source: &str) -> String {
2526 match parse(
2527 source,
2528 crate::parsing::source::SourceType::Volatile,
2529 &ResourceLimits::default(),
2530 ) {
2531 Err(Error::Parsing(details)) => details.message,
2532 other => panic!("expected parse Error, got {other:?}"),
2533 }
2534 }
2535
2536 #[test]
2537 fn parse_prefix_operand_is_call_or_one_operand() {
2538 for (body, operator) in [
2539 ("abs x + 1", "+"),
2540 ("abs x as gram", "as"),
2541 ("sqrt x ^ 2", "^"),
2542 ("lower p + 1", "+"),
2543 ("not ok and ok", "and"),
2544 ("not x > 1", ">"),
2545 ] {
2546 let message = prefix_parse_error(&format!(
2547 "spec test\nuses lemma units\ndata x: 1\ndata p: number range\ndata ok: boolean\nrule out: {body}"
2548 ));
2549 assert!(
2550 message.contains(&format!("found '{operator}' after it")),
2551 "{body}: {message}"
2552 );
2553 }
2554 let message = prefix_parse_error("spec test\nrule out: abs -1");
2555 assert!(message.contains("`abs(...)`"), "{message}");
2556
2557 let abs_plus = prefix_expression(
2558 r#"spec test
2559data x: 1
2560rule out: abs(x) + 1"#,
2561 );
2562 let Some((left, ArithmeticComputation::Add, _)) = binary_arithmetic(abs_plus.root()) else {
2563 panic!("abs(x) + 1 must be add, got {abs_plus}");
2564 };
2565 assert!(matches!(
2566 left.kind(),
2567 ExpressionKind::MathematicalComputation(MathematicalComputation::Abs, _)
2568 ));
2569
2570 let abs_sum = prefix_expression(
2571 r#"spec test
2572data x: 1
2573rule out: abs (x + 1)"#,
2574 );
2575 let ExpressionKind::MathematicalComputation(MathematicalComputation::Abs, operand) =
2576 abs_sum.root_kind()
2577 else {
2578 panic!("abs (x + 1) must be abs of a sum, got {abs_sum}");
2579 };
2580 assert!(matches!(
2581 abs_sum.at(*operand).kind(),
2582 ExpressionKind::Arithmetic { .. }
2583 ));
2584
2585 let abs_sqrt = prefix_expression(
2586 r#"spec test
2587data x: 1
2588rule out: abs sqrt x"#,
2589 );
2590 let ExpressionKind::MathematicalComputation(MathematicalComputation::Abs, operand) =
2591 abs_sqrt.root_kind()
2592 else {
2593 panic!("abs sqrt x must be abs of sqrt, got {abs_sqrt}");
2594 };
2595 assert!(matches!(
2596 abs_sqrt.at(*operand).kind(),
2597 ExpressionKind::MathematicalComputation(MathematicalComputation::Sqrt, _)
2598 ));
2599
2600 let lower_range = prefix_expression(
2601 r#"spec test
2602rule out: lower 5...10"#,
2603 );
2604 let ExpressionKind::RangeBound(RangeBound::Lower, operand) = lower_range.root_kind() else {
2605 panic!("lower 5...10 must be lower of a range, got {lower_range}");
2606 };
2607 assert!(matches!(
2608 lower_range.at(*operand).kind(),
2609 ExpressionKind::RangeLiteral(..)
2610 ));
2611 assert_eq!(
2612 rule_expression(
2613 r#"spec test
2614rule out: lower 5...10"#,
2615 "out"
2616 )
2617 .to_string(),
2618 "lower 5...10"
2619 );
2620
2621 let lower_extended = prefix_expression(
2622 r#"spec test
2623data a: 1
2624data b: 2
2625rule out: lower a...b + 1"#,
2626 );
2627 let ExpressionKind::RangeBound(RangeBound::Lower, operand) = lower_extended.root_kind()
2628 else {
2629 panic!("expected lower of a range, got {lower_extended}");
2630 };
2631 let operand = lower_extended.at(*operand);
2632 let ExpressionKind::RangeLiteral(_, right) = operand.kind() else {
2633 panic!("+ must stay inside the range, got {:?}", operand.kind());
2634 };
2635 assert!(matches!(
2636 binary_arithmetic(operand.child(*right)),
2637 Some((_, ArithmeticComputation::Add, _))
2638 ));
2639
2640 let not_comparison = prefix_expression(
2641 r#"spec test
2642data x: 1
2643rule out: not (x > 1)"#,
2644 );
2645 let ExpressionKind::LogicalNegation(operand, _) = not_comparison.root_kind() else {
2646 panic!("not (x > 1) must negate the comparison, got {not_comparison}");
2647 };
2648 assert!(matches!(
2649 not_comparison.at(*operand).kind(),
2650 ExpressionKind::Comparison(..)
2651 ));
2652 }
2653
2654 fn arrow_expression(body: &str) -> Expression {
2655 rule_expression(&format!("spec test\nrule out: {body}"), "out")
2656 }
2657
2658 #[test]
2659 fn arrow_takes_the_whole_arithmetic_operand() {
2660 let sum = arrow_expression("a + b -> sum x");
2661 let ExpressionKind::ListCommand { list, .. } = sum.root_kind() else {
2662 panic!("a + b -> sum x must be a command on a + b, got {sum}");
2663 };
2664 assert!(matches!(
2665 binary_arithmetic(sum.at(*list)),
2666 Some((_, ArithmeticComputation::Add, _))
2667 ));
2668
2669 let quotient = arrow_expression("total / weight -> round 0.001 eur_per_kg");
2670 let ExpressionKind::StepRounding {
2671 operand,
2672 mode: RoundingMode::Round,
2673 step,
2674 } = quotient.root_kind()
2675 else {
2676 panic!("total / weight -> round step must round the quotient, got {quotient}");
2677 };
2678 assert!(matches!(
2679 binary_arithmetic(quotient.at(*operand)),
2680 Some((_, ArithmeticComputation::Divide, _))
2681 ));
2682 let Some(step) = step else {
2683 panic!("total / weight -> round step must carry a step");
2684 };
2685 assert!(matches!(
2686 quotient.at(*step).kind(),
2687 ExpressionKind::Literal(_)
2688 ));
2689
2690 let prefix = arrow_expression("abs saldo -> floor 1 eur");
2691 let ExpressionKind::StepRounding {
2692 operand,
2693 mode: RoundingMode::Floor,
2694 ..
2695 } = prefix.root_kind()
2696 else {
2697 panic!("abs saldo -> floor step must floor abs saldo, got {prefix}");
2698 };
2699 assert!(matches!(
2700 prefix.at(*operand).kind(),
2701 ExpressionKind::MathematicalComputation(MathematicalComputation::Abs, _)
2702 ));
2703
2704 let call = arrow_expression("eind - start -> ceil(15 minute)");
2705 assert!(matches!(
2706 call.root_kind(),
2707 ExpressionKind::StepRounding {
2708 mode: RoundingMode::Ceil,
2709 ..
2710 }
2711 ));
2712
2713 let bare = arrow_expression("x -> round");
2714 assert!(matches!(
2715 bare.root_kind(),
2716 ExpressionKind::StepRounding {
2717 mode: RoundingMode::Round,
2718 step: None,
2719 ..
2720 }
2721 ));
2722 }
2723
2724 #[test]
2725 fn arrow_binds_tighter_than_comparison_and_logic() {
2726 let count = arrow_expression("items -> count is 0");
2727 let ExpressionKind::Comparison(left, _, _) = count.root_kind() else {
2728 panic!("items -> count is 0 must compare the count, got {count}");
2729 };
2730 assert!(matches!(
2731 count.at(*left).kind(),
2732 ExpressionKind::ListCommand { .. }
2733 ));
2734
2735 let right = arrow_expression("limit > items -> sum cost");
2736 let ExpressionKind::Comparison(_, _, right_operand) = right.root_kind() else {
2737 panic!("limit > items -> sum cost must compare against the sum, got {right}");
2738 };
2739 assert!(matches!(
2740 right.at(*right_operand).kind(),
2741 ExpressionKind::ListCommand { .. }
2742 ));
2743
2744 let logic = arrow_expression("ok and items -> count > 0");
2745 let ExpressionKind::Logical { steps, .. } = logic.root_kind() else {
2746 panic!("ok and items -> count > 0 must be a conjunction, got {logic}");
2747 };
2748 let ExpressionKind::Comparison(left, _, _) = logic.at(steps[0].operand).kind() else {
2749 panic!("second operand must be a comparison, got {logic}");
2750 };
2751 assert!(matches!(
2752 logic.at(*left).kind(),
2753 ExpressionKind::ListCommand { .. }
2754 ));
2755
2756 let chain = arrow_expression("staff -> where paid -> sum bonus");
2757 let ExpressionKind::ListCommand { list, .. } = chain.root_kind() else {
2758 panic!("chained commands must nest left to right, got {chain}");
2759 };
2760 assert!(matches!(
2761 chain.at(*list).kind(),
2762 ExpressionKind::ListCommand { .. }
2763 ));
2764 }
2765
2766 #[test]
2767 fn operator_after_a_command_is_a_parse_error() {
2768 for (body, found, command) in [
2769 ("lines -> sum(qty) * 2", "*", "sum(qty)"),
2770 ("fares -> sum - 1", "-", "sum"),
2771 ("speeds -> max as mps", "as", "max"),
2772 ("fares -> count + 1", "+", "count"),
2773 ("x -> round(0.01) ^ 2", "^", "round(0.01)"),
2774 ] {
2775 let message = prefix_parse_error(&format!("spec test\nrule out: {body}"));
2776 assert!(
2777 message.contains(&format!("found '{found}' after `-> {command}`")),
2778 "{body}: {message}"
2779 );
2780 assert!(message.contains("parentheses"), "{body}: {message}");
2781 }
2782 }
2783
2784 #[test]
2785 fn arrow_after_bare_not_is_a_parse_error() {
2786 let message = prefix_parse_error("spec test\nrule out: not items -> any paid");
2787 assert!(
2788 message.contains("`not (items -> ...)`"),
2789 "not followed by -> must suggest parentheses: {message}"
2790 );
2791 }
2792
2793 #[test]
2794 fn arrow_after_in_range_suggests_parentheses_around_the_command() {
2795 let message = prefix_parse_error("spec test\nrule out: day in periods -> first");
2796 assert!(
2797 message.contains(
2798 "found '->' after `day in periods`; `in` takes one range operand, \
2799 so put parentheses around the command: `day in (periods -> ...)`"
2800 ),
2801 "{message}"
2802 );
2803 }
2804
2805 #[test]
2806 fn arrow_after_in_calendar_suggests_parentheses_around_the_check() {
2807 let message = prefix_parse_error("spec test\nrule out: day in past calendar year -> first");
2808 assert!(
2809 message.contains("found '->' after `day in past calendar year`"),
2810 "{message}"
2811 );
2812 assert!(
2813 message.contains("`(day in past calendar year) -> ...`"),
2814 "{message}"
2815 );
2816 }
2817
2818 #[test]
2819 fn prefix_rounding_suggests_the_arrow_form() {
2820 for (body, keyword, rewrite) in [
2821 ("round(x)", "round", "`x -> round`"),
2822 ("floor x", "floor", "`x -> floor`"),
2823 ("ceil (a / b)", "ceil", "`a / b -> ceil`"),
2824 ] {
2825 let message = prefix_parse_error(&format!(
2826 "spec test\ndata x: 1\ndata a: 1\ndata b: 1\nrule out: {body}"
2827 ));
2828 assert!(
2829 message.contains(&format!("`{keyword}` is written after `->`")),
2830 "{body}: {message}"
2831 );
2832 assert!(message.contains(rewrite), "{body}: {message}");
2833 }
2834 }
2835
2836 #[test]
2837 fn format_prefix_operand_round_trips() {
2838 let source = r#"spec test
2839data x: 1.00
2840rule tight: abs(x) + 1
2841rule wide: abs (x + 1)
2842rule ends: lower 5...10
2843rule edge: (lower x)...(upper x)
2844rule round_bare: x -> round
2845rule round_step: x -> round(0.05) > 1
2846"#;
2847 let formatted =
2848 crate::formatting::format_source(source, crate::parsing::source::SourceType::Volatile)
2849 .expect("format");
2850 let again = crate::formatting::format_source(
2851 &formatted,
2852 crate::parsing::source::SourceType::Volatile,
2853 )
2854 .expect("reformat");
2855 assert_eq!(formatted, again, "format must be stable");
2856
2857 for rule in ["tight", "wide", "ends", "edge", "round_bare", "round_step"] {
2858 let original = rule_expression(source, rule);
2859 let reparsed = rule_expression(&formatted, rule);
2860 assert_eq!(
2861 original.to_string(),
2862 reparsed.to_string(),
2863 "{rule} changed meaning across format/parse"
2864 );
2865 }
2866
2867 let tight = rule_expression(&formatted, "tight");
2868 let Some((left, ArithmeticComputation::Add, _)) = binary_arithmetic(tight.root()) else {
2869 panic!("abs(x) + 1 must stay an addition, got {}", tight);
2870 };
2871 assert!(
2872 matches!(
2873 left.kind(),
2874 ExpressionKind::MathematicalComputation(MathematicalComputation::Abs, _)
2875 ),
2876 "abs(x) + 1 must stay abs-then-add, got {tight}"
2877 );
2878 }
2879}