1use crate::comprehension::cardinality::{Interval, MeasureName, ProductMeasure};
34use crate::comprehension::source::{LiteralValue, Source};
35
36pub fn parse_source(text: &str) -> Result<Source, SourceParseError> {
38 let trimmed = text.trim();
39
40 if let Some(name) = strip_curly(trimmed) {
46 return Ok(Source::WorkloadParamList {
47 name,
48 len_hint: None,
49 });
50 }
51 if let Some(dyn_text) = strip_dynamic_curly(trimmed) {
52 return Ok(Source::WorkloadParamList {
53 name: dyn_text,
54 len_hint: None,
55 });
56 }
57
58 if quoted_with_placeholder(trimmed) {
72 return Ok(Source::Generator {
73 expr: trimmed.to_string(),
74 cardinality_hint: None,
75 });
76 }
77 if trimmed.len() >= 2 && trimmed.starts_with('"') && trimmed.ends_with('"') {
78 let inner = &trimmed[1..trimmed.len() - 1];
79 let values = super::super::source::split_string_comprehension(inner)
80 .into_iter()
81 .map(parse_literal_value)
82 .collect();
83 return Ok(Source::Literal { values });
84 }
85 if trimmed.len() >= 2 && trimmed.starts_with('\'') && trimmed.ends_with('\'') {
86 let inner = &trimmed[1..trimmed.len() - 1];
87 return Ok(Source::Literal {
88 values: vec![LiteralValue::String(inner.to_string())],
89 });
90 }
91
92 if trimmed.starts_with('[') && trimmed.ends_with(']') {
103 let inner = &trimmed[1..trimmed.len() - 1];
104 if bracket_is_pure_literal(inner) {
105 return parse_literal_list(inner);
106 }
107 return Ok(Source::Generator {
108 expr: trimmed.to_string(),
109 cardinality_hint: None,
110 });
111 }
112
113 if let Some(result) = parse_distribution(trimmed) {
119 return result;
120 }
121
122 if let Some(idx) = find_top_level(trimmed, "..") {
124 return parse_range(trimmed, idx);
125 }
126
127 if looks_like_function_call(trimmed) {
129 return Ok(Source::Generator {
130 expr: trimmed.to_string(),
131 cardinality_hint: None,
132 });
133 }
134
135 if let Some(value) = try_parse_bare_scalar(trimmed) {
139 return Ok(Source::Literal {
140 values: vec![value],
141 });
142 }
143
144 if trimmed.contains(',') && looks_like_bare_value_list(trimmed) {
151 return parse_literal_list(trimmed);
152 }
153
154 Ok(Source::Generator {
160 expr: trimmed.to_string(),
161 cardinality_hint: None,
162 })
163}
164
165fn quoted_with_placeholder(text: &str) -> bool {
169 let Some(quote) = text.chars().next().filter(|c| matches!(c, '"' | '\'')) else {
170 return false;
171 };
172 if text.len() < 2 || !text.ends_with(quote) {
173 return false;
174 }
175 let inner = &text[1..text.len() - 1];
176 if inner.contains(quote) {
177 return false;
178 }
179 let bytes = inner.as_bytes();
180 (0..bytes.len()).any(|i| {
181 let escaped = i > 0 && bytes[i - 1] == b'\\';
182 (bytes[i] == b'{' && !escaped) || (matches!(bytes[i], b'{' | b'}') && escaped)
183 })
184}
185
186fn parse_distribution(text: &str) -> Option<Result<Source, SourceParseError>> {
197 let (call, support_text) = match split_on_keyword(text, " on ") {
198 Some((call, rest)) => (call, Some(rest)),
199 None => (text, None),
200 };
201 let (name, args) = split_call(call)?;
202 let measure = MeasureName::from_text(name)?;
203 Some(build_distribution(text, measure, args, support_text))
204}
205
206fn build_distribution(
209 text: &str,
210 measure: MeasureName,
211 args: &str,
212 support_text: Option<&str>,
213) -> Result<Source, SourceParseError> {
214 let invalid = || SourceParseError::InvalidRange(text.to_string());
215 let mut params = Vec::new();
216 for arg in args.split(',') {
217 let arg = arg.trim();
218 if arg.is_empty() {
219 if params.is_empty() && args.trim().is_empty() {
220 break;
221 }
222 return Err(invalid());
223 }
224 params.push(arg.parse::<f64>().map_err(|_| invalid())?);
225 }
226 let params = measure.resolve_params(¶ms).map_err(|_| invalid())?;
227 let support = match support_text {
228 None => measure.support(¶ms),
229 Some(interval_text) => match parse_range_text(interval_text)? {
230 Source::ContinuousInterval { interval, .. } => interval,
231 _ => return Err(invalid()),
232 },
233 };
234 Ok(Source::Distribution {
235 distribution: measure,
236 support,
237 params,
238 })
239}
240
241fn split_call(text: &str) -> Option<(&str, &str)> {
244 let text = text.trim();
245 let open = text.find('(')?;
246 let inner = text.strip_suffix(')')?;
247 let name = text[..open].trim();
248 if name.is_empty() || !name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') {
249 return None;
250 }
251 Some((name, &inner[open + 1..]))
252}
253
254fn split_on_keyword<'a>(text: &'a str, keyword: &str) -> Option<(&'a str, &'a str)> {
257 let bytes = text.as_bytes();
258 let mut depth = 0i32;
259 let mut quote: Option<u8> = None;
260 for i in 0..bytes.len() {
261 let c = bytes[i];
262 match quote {
263 Some(q) => {
264 if c == q {
265 quote = None;
266 }
267 }
268 None => match c {
269 b'"' | b'\'' => quote = Some(c),
270 b'(' | b'[' | b'{' => depth += 1,
271 b')' | b']' | b'}' => depth -= 1,
272 _ => {
273 if depth == 0 && text[i..].starts_with(keyword) {
274 return Some((&text[..i], &text[i + keyword.len()..]));
275 }
276 }
277 },
278 }
279 }
280 None
281}
282
283fn looks_like_bare_value_list(text: &str) -> bool {
289 !text.chars().any(|c| {
290 matches!(
291 c,
292 '(' | ')'
293 | '['
294 | ']'
295 | '{'
296 | '}'
297 | '\''
298 | '"'
299 | '+'
300 | '*'
301 | '/'
302 | '%'
303 | '='
304 | '<'
305 | '>'
306 | '!'
307 | '&'
308 | '|'
309 | '~'
310 | '^'
311 | '?'
312 )
313 })
314}
315
316fn strip_dynamic_curly(s: &str) -> Option<String> {
320 let s = s.trim();
321 if !s.starts_with('{') || !s.ends_with('}') {
322 return None;
323 }
324 let inner = &s[1..s.len() - 1];
325 if !inner.contains('{') {
329 return None;
330 }
331 Some(inner.to_string())
332}
333
334fn parse_literal_list(inner: &str) -> Result<Source, SourceParseError> {
338 let parts: Vec<&str> = inner
339 .split(',')
340 .map(|s| s.trim())
341 .filter(|s| !s.is_empty())
342 .collect();
343
344 if parts.is_empty() {
345 return Ok(Source::Literal { values: Vec::new() });
346 }
347
348 let values: Vec<LiteralValue> = parts.iter().map(|s| parse_literal_value(s)).collect();
349
350 Ok(Source::Literal { values })
351}
352
353fn bracket_is_pure_literal(inner: &str) -> bool {
360 let elems: Vec<&str> = inner
361 .split(',')
362 .map(str::trim)
363 .filter(|s| !s.is_empty())
364 .collect();
365 if elems.is_empty() {
366 return true; }
368 elems.iter().all(|e| {
369 if e.ends_with('…') || e.ends_with("...") {
370 return false; }
372 e.eq_ignore_ascii_case("true")
373 || e.eq_ignore_ascii_case("false")
374 || ((e.starts_with('"') && e.ends_with('"'))
375 || (e.starts_with('\'') && e.ends_with('\'')))
376 || e.parse::<i64>().is_ok()
377 || e.parse::<f64>().is_ok()
378 })
379}
380
381fn parse_literal_value(s: &str) -> LiteralValue {
382 let s = s.trim();
383 if s.eq_ignore_ascii_case("true") {
384 return LiteralValue::Bool(true);
385 }
386 if s.eq_ignore_ascii_case("false") {
387 return LiteralValue::Bool(false);
388 }
389 if (s.starts_with('"') && s.ends_with('"')) || (s.starts_with('\'') && s.ends_with('\'')) {
391 let inner = &s[1..s.len() - 1];
392 return LiteralValue::String(inner.to_string());
393 }
394 if let Ok(n) = s.parse::<i64>() {
396 return LiteralValue::Int(n);
397 }
398 if let Ok(n) = s.parse::<u64>() {
399 return LiteralValue::UInt(n);
400 }
401 if let Ok(f) = s.parse::<f64>() {
403 return LiteralValue::Float(f);
404 }
405 LiteralValue::String(s.to_string())
407}
408
409fn parse_range_text(text: &str) -> Result<Source, SourceParseError> {
412 let text = text.trim();
413 match find_top_level(text, "..") {
414 Some(idx) => parse_range(text, idx),
415 None => Err(SourceParseError::InvalidRange(text.to_string())),
416 }
417}
418
419fn parse_range(text: &str, dotdot_idx: usize) -> Result<Source, SourceParseError> {
420 let lo_str = text[..dotdot_idx].trim();
421 let after = &text[dotdot_idx + 2..];
422
423 let (inclusive_end, after) = if let Some(rest) = after.strip_prefix('=') {
425 (true, rest)
426 } else {
427 (false, after)
428 };
429
430 let (rhs, step) = if let Some(step_pos) = after.find(" step ") {
435 let rhs = after[..step_pos].trim();
436 let step_str = after[step_pos + 6..].trim();
437 let step: i64 = step_str
438 .parse()
439 .map_err(|_| SourceParseError::InvalidRange(text.to_string()))?;
440 (rhs, step)
441 } else if let Some(step_pos) = after.find("..") {
442 let rhs = after[..step_pos].trim();
445 let step_str = after[step_pos + 2..].trim();
446 let step: i64 = step_str
447 .parse()
448 .map_err(|_| SourceParseError::InvalidRange(text.to_string()))?;
449 (rhs, step)
450 } else {
451 (after.trim(), 1)
452 };
453
454 if let (Ok(lo_i), Ok(hi_i)) = (lo_str.parse::<i64>(), rhs.parse::<i64>()) {
456 let hi = if inclusive_end { hi_i + 1 } else { hi_i };
457 return Ok(Source::IntRange { lo: lo_i, hi, step });
458 }
459 if let (Ok(lo_f), Ok(hi_f)) = (lo_str.parse::<f64>(), rhs.parse::<f64>()) {
461 let interval = Interval {
462 lo: lo_f,
463 hi: hi_f,
464 lo_open: false,
465 hi_open: !inclusive_end,
466 };
467 return Ok(Source::ContinuousInterval {
468 interval,
469 measure: ProductMeasure::Uniform,
470 });
471 }
472
473 Err(SourceParseError::InvalidRange(text.to_string()))
474}
475
476fn strip_curly(s: &str) -> Option<String> {
477 let s = s.trim();
478 if s.starts_with('{') && s.ends_with('}') {
479 let inner = &s[1..s.len() - 1];
480 let trimmed = inner.trim();
481 if !trimmed.is_empty() && trimmed.chars().all(|c| c.is_alphanumeric() || c == '_') {
482 return Some(trimmed.to_string());
483 }
484 }
485 None
486}
487
488fn try_parse_bare_scalar(s: &str) -> Option<LiteralValue> {
494 if s.eq_ignore_ascii_case("true") {
495 return Some(LiteralValue::Bool(true));
496 }
497 if s.eq_ignore_ascii_case("false") {
498 return Some(LiteralValue::Bool(false));
499 }
500 if (s.starts_with('"') && s.ends_with('"')) || (s.starts_with('\'') && s.ends_with('\'')) {
501 let inner = &s[1..s.len() - 1];
502 return Some(LiteralValue::String(inner.to_string()));
503 }
504 if let Ok(n) = s.parse::<i64>() {
505 return Some(LiteralValue::Int(n));
506 }
507 if let Ok(n) = s.parse::<u64>() {
508 return Some(LiteralValue::UInt(n));
509 }
510 if let Ok(f) = s.parse::<f64>() {
511 return Some(LiteralValue::Float(f));
512 }
513 None
514}
515
516fn looks_like_function_call(s: &str) -> bool {
517 let Some(open) = s.find('(') else {
518 return false;
519 };
520 if !s.ends_with(')') {
521 return false;
522 }
523 let name = &s[..open];
524 !name.is_empty() && name.chars().all(|c| c.is_alphanumeric() || c == '_')
525}
526
527fn find_top_level(s: &str, needle: &str) -> Option<usize> {
530 let bytes = s.as_bytes();
531 let needle_bytes = needle.as_bytes();
532 let mut depth = 0i64;
533 let mut i = 0;
534 while i + needle_bytes.len() <= bytes.len() {
535 match bytes[i] {
536 b'(' | b'[' | b'{' => depth += 1,
537 b')' | b']' | b'}' => depth -= 1,
538 _ => {}
539 }
540 if depth == 0 && &bytes[i..i + needle_bytes.len()] == needle_bytes {
541 return Some(i);
542 }
543 i += 1;
544 }
545 None
546}
547
548#[derive(Debug, Clone, PartialEq)]
550pub enum SourceParseError {
551 Unrecognized(String),
553 InvalidRange(String),
556}
557
558impl std::fmt::Display for SourceParseError {
559 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
560 match self {
561 SourceParseError::Unrecognized(s) => {
562 write!(f, "unrecognized source expression: {s:?}")
563 }
564 SourceParseError::InvalidRange(s) => {
565 write!(f, "invalid range expression: {s:?}")
566 }
567 }
568 }
569}
570
571impl std::error::Error for SourceParseError {}
572
573#[cfg(test)]
574mod tests {
575 use super::*;
576
577 #[test]
578 fn int_range_exclusive() {
579 let s = parse_source("1..10").unwrap();
580 assert!(matches!(
581 s,
582 Source::IntRange {
583 lo: 1,
584 hi: 10,
585 step: 1
586 }
587 ));
588 }
589
590 #[test]
591 fn double_quoted_source_is_string_comprehension_striped() {
592 let s = parse_source(r#""rerank_def, rerank_1x, rerank_2x""#).unwrap();
594 match s {
595 Source::Literal { values } => {
596 assert_eq!(
597 values,
598 vec![
599 LiteralValue::String("rerank_def".into()),
600 LiteralValue::String("rerank_1x".into()),
601 LiteralValue::String("rerank_2x".into()),
602 ]
603 );
604 }
605 other => panic!("expected striped Literal, got {other:?}"),
606 }
607 }
608
609 #[test]
610 fn single_quoted_source_is_atomic() {
611 let s = parse_source("'rerank_def, rerank_1x'").unwrap();
613 match s {
614 Source::Literal { values } => {
615 assert_eq!(
616 values,
617 vec![LiteralValue::String("rerank_def, rerank_1x".into())]
618 );
619 }
620 other => panic!("expected atomic Literal, got {other:?}"),
621 }
622 }
623
624 #[test]
625 fn int_range_inclusive() {
626 let s = parse_source("1..=10").unwrap();
627 assert!(matches!(
628 s,
629 Source::IntRange {
630 lo: 1,
631 hi: 11,
632 step: 1
633 }
634 ));
635 }
636
637 #[test]
638 fn int_range_with_step() {
639 let s = parse_source("0..100 step 10").unwrap();
640 assert!(matches!(
641 s,
642 Source::IntRange {
643 lo: 0,
644 hi: 100,
645 step: 10
646 }
647 ));
648 }
649
650 #[test]
651 fn literal_int_list() {
652 let s = parse_source("[1, 2, 3]").unwrap();
653 match s {
654 Source::Literal { values } => {
655 assert_eq!(values.len(), 3);
656 assert_eq!(values[0], LiteralValue::Int(1));
657 assert_eq!(values[2], LiteralValue::Int(3));
658 }
659 other => panic!("expected Literal, got {other:?}"),
660 }
661 }
662
663 #[test]
664 fn bracket_bare_words_are_references_not_strings() {
665 let s = parse_source("[a, b, c]").unwrap();
671 match s {
672 Source::Generator { expr, .. } => assert_eq!(expr, "[a, b, c]"),
673 other => panic!("expected deferred Generator, got {other:?}"),
674 }
675 }
676
677 #[test]
678 fn bracket_with_spread_defers_to_generator() {
679 let s = parse_source("[xs…]").unwrap();
680 assert!(
681 matches!(s, Source::Generator { .. }),
682 "spread list must defer: {s:?}"
683 );
684 }
685
686 #[test]
687 fn literal_quoted_strings() {
688 let s = parse_source(r#"["hello", "world"]"#).unwrap();
689 match s {
690 Source::Literal { values } => {
691 assert_eq!(values[0], LiteralValue::String("hello".into()));
692 assert_eq!(values[1], LiteralValue::String("world".into()));
693 }
694 other => panic!("expected Literal, got {other:?}"),
695 }
696 }
697
698 #[test]
699 fn literal_float_list() {
700 let s = parse_source("[1.5, 2.5, 3.5]").unwrap();
701 match s {
702 Source::Literal { values } => {
703 assert_eq!(values[0], LiteralValue::Float(1.5));
704 }
705 other => panic!("expected Literal, got {other:?}"),
706 }
707 }
708
709 #[test]
710 fn workload_param_ref() {
711 let s = parse_source("{profiles}").unwrap();
712 match s {
713 Source::WorkloadParamList { name, .. } => assert_eq!(name, "profiles"),
714 other => panic!("expected WorkloadParamList, got {other:?}"),
715 }
716 }
717
718 #[test]
719 fn generator_function_call() {
720 let s = parse_source("fib(8)").unwrap();
721 match s {
722 Source::Generator { expr, .. } => assert_eq!(expr, "fib(8)"),
723 other => panic!("expected Generator, got {other:?}"),
724 }
725 }
726
727 #[test]
728 fn continuous_interval_via_floats() {
729 let s = parse_source("0.0..1.0").unwrap();
730 match s {
731 Source::ContinuousInterval { interval, measure } => {
732 assert_eq!(interval.lo, 0.0);
733 assert_eq!(interval.hi, 1.0);
734 assert!(matches!(measure, ProductMeasure::Uniform));
735 }
736 other => panic!("expected ContinuousInterval, got {other:?}"),
737 }
738 }
739
740 #[test]
741 fn continuous_interval_inclusive() {
742 let s = parse_source("0.0..=1.0").unwrap();
743 match s {
744 Source::ContinuousInterval { interval, .. } => {
745 assert!(!interval.hi_open);
746 }
747 other => panic!("expected ContinuousInterval, got {other:?}"),
748 }
749 }
750
751 #[test]
752 fn unrecognized_source_falls_back_to_generator() {
753 let s = parse_source("totally nonsense").unwrap();
758 match s {
759 Source::Generator { expr, .. } => assert_eq!(expr, "totally nonsense"),
760 other => panic!("expected Generator, got {other:?}"),
761 }
762 }
763
764 #[test]
765 fn empty_literal_list() {
766 let s = parse_source("[]").unwrap();
767 match s {
768 Source::Literal { values } => assert!(values.is_empty()),
769 other => panic!("expected empty Literal, got {other:?}"),
770 }
771 }
772
773 #[test]
776 fn a_named_measure_parses_as_a_distribution() {
777 match parse_source("normal(0, 1)").unwrap() {
778 Source::Distribution {
779 distribution: MeasureName::Normal,
780 support,
781 params,
782 } => {
783 assert_eq!(params, vec![0.0, 1.0]);
784 assert!(support.lo.is_infinite() && support.hi.is_infinite());
785 }
786 other => panic!("expected a normal distribution, got {other:?}"),
787 }
788 match parse_source("exponential(2) on 0.0..1.0").unwrap() {
789 Source::Distribution {
790 distribution: MeasureName::Exponential,
791 support,
792 params,
793 } => {
794 assert_eq!(params, vec![2.0]);
795 assert_eq!(support, Interval::half_open(0.0, 1.0));
796 }
797 other => panic!("expected a restricted exponential, got {other:?}"),
798 }
799 match parse_source("pareto(3, 2)").unwrap() {
802 Source::Distribution {
803 support, params, ..
804 } => {
805 assert_eq!(params, vec![3.0, 2.0]);
806 assert_eq!(support.lo, 3.0);
807 }
808 other => panic!("{other:?}"),
809 }
810 assert!(matches!(
811 parse_source("uniform01()").unwrap(),
812 Source::Distribution {
813 distribution: MeasureName::Uniform01,
814 ..
815 }
816 ));
817 }
818
819 #[test]
822 fn a_call_that_names_no_measure_is_still_a_generator() {
823 for text in ["fib(8)", "partitions(\"*/4\", 100)", "range(0, 10)"] {
824 assert!(
825 matches!(parse_source(text).unwrap(), Source::Generator { .. }),
826 "{text}"
827 );
828 }
829 assert!(matches!(
831 parse_source("0.0..1.0").unwrap(),
832 Source::ContinuousInterval { .. }
833 ));
834 }
835
836 #[test]
839 fn a_measure_with_the_wrong_arguments_is_an_error() {
840 for text in ["normal(1)", "normal(0, 1, 2)", "beta(a, b)", "gamma(1,)"] {
841 assert!(parse_source(text).is_err(), "{text}");
842 }
843 }
844}