1use crate::ast::*;
9use crate::registry::OpMeta;
10use crate::surface_ast::*;
11use winnow::ascii::multispace0;
12use winnow::combinator::cut_err;
13use winnow::error::{ContextError, ErrMode, StrContext, StrContextValue};
14use winnow::token::take_while;
15use winnow::{ModalResult, Parser};
16
17pub type ParseError = String;
18
19fn span_of(base: usize, start_ptr: usize, input: &mut &str) -> Span {
22 let end_ptr = input.as_ptr() as usize;
23 Span::new((start_ptr - base) as u32, (end_ptr - base) as u32)
24}
25
26fn ws(input: &mut &str) -> ModalResult<()> {
29 loop {
30 multispace0.parse_next(input)?;
31 if input.starts_with(';') {
32 let _ = take_while(0.., |c: char| c != '\n').parse_next(input)?;
33 } else {
34 break;
35 }
36 }
37 Ok(())
38}
39
40fn ident<'s>(input: &mut &'s str) -> ModalResult<&'s str> {
41 ws(input)?;
42 let s = *input;
43 if s.is_empty() || !s.starts_with(|c: char| c.is_alphabetic() || c == '_') {
44 let mut e = ContextError::new();
45 e.push(StrContext::Expected(StrContextValue::Description(
46 "identifier",
47 )));
48 return Err(ErrMode::Backtrack(e));
49 }
50 let len = s
51 .find(|c: char| !(c.is_alphanumeric() || c == '_'))
52 .unwrap_or(s.len());
53 let tok = &s[..len];
54 *input = &s[len..];
55 Ok(tok)
56}
57
58const SYMBOLS: &[&str] = &[
59 "<<", ">>", "<=", ">=", "!=", "==", "=>", "+", "-", "*", "/", "%", "<", ">", "&", "|", "^", "~",
60];
61
62fn symbol<'s>(input: &mut &'s str) -> ModalResult<&'s str> {
63 for &sym in SYMBOLS {
64 if input.starts_with(sym) {
65 let tok = &input[..sym.len()];
66 *input = &input[sym.len()..];
67 return Ok(tok);
68 }
69 }
70 let mut e = ContextError::new();
71 e.push(StrContext::Expected(StrContextValue::Description("symbol")));
72 Err(ErrMode::Backtrack(e))
73}
74
75fn op_name<'s>(input: &mut &'s str) -> ModalResult<&'s str> {
76 if input.starts_with(|c: char| c.is_alphabetic() || c == '_') {
77 return ident(input);
78 }
79 symbol(input)
80}
81
82fn op_token<'s>(input: &mut &'s str) -> ModalResult<&'s str> {
83 ws(input)?;
84 let s = *input;
85 let len = s
86 .find(|c: char| {
87 c.is_whitespace() || matches!(c, '(' | ')' | '[' | ']' | '{' | '}' | ';' | '"')
88 })
89 .unwrap_or(s.len());
90 if len == 0 {
91 let mut e = ContextError::new();
92 e.push(StrContext::Expected(StrContextValue::Description(
93 "operator",
94 )));
95 return Err(ErrMode::Backtrack(e));
96 }
97 let tok = &s[..len];
98 *input = &s[len..];
99 Ok(tok)
100}
101
102fn kw_token<'s>(input: &mut &'s str) -> ModalResult<&'s str> {
105 ws(input)?;
106 let s = *input;
107 if s.is_empty() || !s.starts_with(|c: char| c.is_alphabetic() || c == '_') {
108 let mut e = ContextError::new();
109 e.push(StrContext::Expected(StrContextValue::Description(
110 "command keyword",
111 )));
112 return Err(ErrMode::Backtrack(e));
113 }
114 let len = s
115 .find(|c: char| !(c.is_alphanumeric() || c == '_' || c == '-'))
116 .unwrap_or(s.len());
117 let tok = &s[..len];
118 *input = &s[len..];
119 Ok(tok)
120}
121
122fn op_expr(input: &mut &str) -> ModalResult<String> {
123 ws(input)?;
124 if input.starts_with(|c: char| c.is_alphabetic() || c == '_') {
125 let saved = *input;
126 let name = ident(input)?;
127 if input.starts_with("::") {
128 *input = &input[2..];
129 let method = op_name(input)?;
130 return Ok(format!("{name}::{method}"));
131 }
132 *input = saved;
133 }
134 let tok = op_token(input)?;
135 Ok(tok.to_owned())
136}
137
138fn num_token<'s>(input: &mut &'s str) -> ModalResult<&'s str> {
139 ws(input)?;
140 let s = *input;
141 let starts_numeric = s.starts_with(|c: char| c.is_ascii_digit())
142 || (s.starts_with('-') && s.len() > 1 && s.as_bytes()[1].is_ascii_digit());
143 if !starts_numeric {
144 let mut e = ContextError::new();
145 e.push(StrContext::Expected(StrContextValue::Description("number")));
146 return Err(ErrMode::Backtrack(e));
147 }
148 let len = s
149 .find(|c: char| {
150 c.is_whitespace() || matches!(c, '(' | ')' | '[' | ']' | '{' | '}' | ';' | '"')
151 })
152 .unwrap_or(s.len());
153 let tok = &s[..len];
154 *input = &s[len..];
155 Ok(tok)
156}
157
158fn number(input: &mut &str) -> ModalResult<u64> {
159 let tok = num_token(input)?;
160 tok.parse::<u64>().map_err(|_| {
161 let mut e = ContextError::new();
162 e.push(StrContext::Expected(StrContextValue::Description("number")));
163 ErrMode::Cut(e)
164 })
165}
166
167fn expect_char(input: &mut &str, c: char) -> ModalResult<()> {
168 ws(input)?;
169 if input.starts_with(c) {
170 *input = &input[c.len_utf8()..];
171 Ok(())
172 } else {
173 Err(ErrMode::Backtrack(ContextError::new()))
174 }
175}
176
177fn cut_char(input: &mut &str, c: char) -> ModalResult<()> {
178 ws(input)?;
179 if input.starts_with(c) {
180 *input = &input[c.len_utf8()..];
181 Ok(())
182 } else {
183 let mut e = ContextError::new();
184 e.push(StrContext::Expected(StrContextValue::CharLiteral(c)));
185 Err(ErrMode::Cut(e))
186 }
187}
188
189fn is_literal(s: &str) -> bool {
190 s.starts_with(|c: char| c.is_ascii_digit())
191 || (s.starts_with('-') && s.len() > 1)
192 || s == "true"
193 || s == "false"
194}
195
196fn parse_quoted_string(input: &mut &str) -> ModalResult<String> {
197 ws(input)?;
198 if !input.starts_with('"') {
199 return Err(ErrMode::Backtrack(ContextError::new()));
200 }
201 *input = &input[1..];
202 let mut buf = String::from('"');
203 loop {
204 let Some(c) = input.chars().next() else {
205 let mut e = ContextError::new();
206 e.push(StrContext::Expected(StrContextValue::Description(
207 "closing \"",
208 )));
209 return Err(ErrMode::Cut(e));
210 };
211 *input = &input[c.len_utf8()..];
212 match c {
213 '"' => {
214 buf.push('"');
215 return Ok(buf);
216 }
217 '\\' => {
218 let esc = input.chars().next().ok_or_else(|| {
219 let mut e = ContextError::new();
220 e.push(StrContext::Expected(StrContextValue::Description(
221 "escape character",
222 )));
223 ErrMode::Cut(e)
224 })?;
225 *input = &input[esc.len_utf8()..];
226 match esc {
227 '"' => buf.push('"'),
228 '\\' => buf.push('\\'),
229 'n' => buf.push('\n'),
230 't' => buf.push('\t'),
231 _ => {
232 buf.push('\\');
233 buf.push(esc);
234 }
235 }
236 }
237 _ => buf.push(c),
238 }
239 }
240}
241
242fn parse_term_inner(input: &mut &str, base: usize) -> ModalResult<Term> {
245 ws(input)?;
246 let start = input.as_ptr() as usize;
247 if input.starts_with('(') {
248 expect_char(input, '(')?;
249 let op = cut_err(op_expr)
250 .context(StrContext::Label("operator name"))
251 .parse_next(input)?;
252 let mut children = Vec::new();
253 loop {
254 ws(input)?;
255 if input.starts_with(')') {
256 break;
257 }
258 children.push(parse_term_inner(input, base)?);
259 }
260 cut_char(input, ')')?;
261 Ok(Term::App {
262 op,
263 children,
264 span: span_of(base, start, input),
265 })
266 } else if input.starts_with('"') {
267 let s = parse_quoted_string(input)?;
268 Ok(Term::Lit(s, span_of(base, start, input)))
269 } else if let Ok(tok) = num_token(input) {
270 Ok(Term::Lit(tok.to_owned(), span_of(base, start, input)))
271 } else {
272 let tok = ident(input)?;
273 Ok(Term::Lit(tok.to_owned(), span_of(base, start, input)))
274 }
275}
276
277#[allow(dead_code)]
278fn parse_term(input: &mut &str) -> ModalResult<Term> {
279 let base = input.as_ptr() as usize;
280 parse_term_inner(input, base)
281}
282
283fn parse_pattern(input: &mut &str, base: usize) -> ModalResult<SurfacePattern> {
286 ws(input)?;
287 let start = input.as_ptr() as usize;
288 if input.starts_with('(') {
289 expect_char(input, '(')?;
290 let op = cut_err(op_expr)
291 .context(StrContext::Label("operator name"))
292 .parse_next(input)?;
293
294 ws(input)?;
296 let prefix = if input.starts_with("..") {
297 let rstart = input.as_ptr() as usize;
298 *input = &input[2..];
299 let name = ident(input)?;
300 let sp = span_of(base, rstart, input);
301 Some((name.to_owned(), sp))
302 } else {
303 None
304 };
305
306 let mut children = Vec::new();
308 loop {
309 ws(input)?;
310 if input.starts_with(')') {
311 break;
312 }
313 if input.starts_with("..") {
314 break; }
316 children.push(parse_pat_child(input, base)?);
317 }
318
319 ws(input)?;
321 let suffix = if input.starts_with("..") {
322 let rstart = input.as_ptr() as usize;
323 *input = &input[2..];
324 let name = ident(input)?;
325 let sp = span_of(base, rstart, input);
326 Some((name.to_owned(), sp))
327 } else {
328 None
329 };
330
331 cut_char(input, ')')?;
332 let (prefix, suffix) = if prefix.is_some() && children.is_empty() && suffix.is_none() {
335 (None, prefix)
336 } else {
337 (prefix, suffix)
338 };
339 Ok(SurfacePattern::App {
340 op,
341 prefix,
342 children,
343 suffix,
344 span: span_of(base, start, input),
345 })
346 } else if input.starts_with('"') {
347 let s = parse_quoted_string(input)?;
348 let sp = span_of(base, start, input);
349 Ok(SurfacePattern::Lit(s, sp))
350 } else if let Ok(tok) = num_token(input) {
351 let sp = span_of(base, start, input);
352 Ok(SurfacePattern::Lit(tok.to_owned(), sp))
353 } else {
354 let tok = ident(input)?;
355 let sp = span_of(base, start, input);
356 if is_literal(tok) {
357 Ok(SurfacePattern::Lit(tok.to_owned(), sp))
358 } else {
359 Ok(SurfacePattern::Var(tok.to_owned(), sp))
360 }
361 }
362}
363
364fn parse_pat_child(input: &mut &str, base: usize) -> ModalResult<SurfacePatChild> {
365 ws(input)?;
366 let pat = parse_pattern(input, base)?;
367 ws(input)?;
369 if input.starts_with(':') {
370 *input = &input[1..];
371 let mult = parse_mult_spec(input)?;
372 Ok(SurfacePatChild::ElemMult(pat, mult))
373 } else {
374 Ok(SurfacePatChild::Elem(pat))
375 }
376}
377
378fn parse_mult_spec(input: &mut &str) -> ModalResult<MultSpec> {
379 ws(input)?;
380 if input.starts_with(|c: char| c.is_ascii_digit()) {
381 let n = number(input)?;
382 Ok(MultSpec::Exact(n))
383 } else {
384 let name = ident(input)?;
385 ws(input)?;
386 let constraint = parse_cmp_constraint(input)?;
387 Ok(MultSpec::Var {
388 name: name.to_owned(),
389 constraint,
390 })
391 }
392}
393
394fn parse_cmp_constraint(input: &mut &str) -> ModalResult<Option<(CmpOp, u64)>> {
395 ws(input)?;
396 let op = if input.starts_with(">=") {
397 *input = &input[2..];
398 Some(CmpOp::Ge)
399 } else if input.starts_with("<=") {
400 *input = &input[2..];
401 Some(CmpOp::Le)
402 } else if input.starts_with("==") {
403 *input = &input[2..];
404 Some(CmpOp::Eq)
405 } else if input.starts_with("!=") {
406 *input = &input[2..];
407 Some(CmpOp::Ne)
408 } else if input.starts_with('>') {
409 *input = &input[1..];
410 Some(CmpOp::Gt)
411 } else if input.starts_with('<') {
412 *input = &input[1..];
413 Some(CmpOp::Lt)
414 } else {
415 None
416 };
417 match op {
418 Some(cmp) => {
419 let n = number(input)?;
420 Ok(Some((cmp, n)))
421 }
422 None => Ok(None),
423 }
424}
425
426fn parse_rhs(input: &mut &str, base: usize) -> ModalResult<RhsTerm> {
429 ws(input)?;
430 let start = input.as_ptr() as usize;
431 if input.starts_with('(') {
432 expect_char(input, '(')?;
433 let op = cut_err(op_expr)
434 .context(StrContext::Label("operator name"))
435 .parse_next(input)?;
436 let mut children = Vec::new();
437 loop {
438 ws(input)?;
439 if input.starts_with(')') {
440 break;
441 }
442 if input.starts_with("..") {
443 children.push(parse_rhs_dotdot(input, base)?);
444 } else {
445 let child_start = input.as_ptr() as usize;
446 let t = parse_rhs(input, base)?;
447 ws(input)?;
448 if input.starts_with(':') {
450 *input = &input[1..];
451 let mult = parse_mult_expr(input)?;
452 children.push(RhsChild::TermMult {
453 term: t,
454 mult,
455 span: span_of(base, child_start, input),
456 });
457 } else {
458 children.push(RhsChild::Term(t));
459 }
460 }
461 }
462 cut_char(input, ')')?;
463 Ok(RhsTerm::App {
464 op,
465 children,
466 span: span_of(base, start, input),
467 })
468 } else if input.starts_with('"') {
469 let s = parse_quoted_string(input)?;
470 let sp = span_of(base, start, input);
471 Ok(RhsTerm::Lit(s, sp))
472 } else if let Ok(tok) = num_token(input) {
473 let sp = span_of(base, start, input);
474 Ok(RhsTerm::Lit(tok.to_owned(), sp))
475 } else {
476 let tok = ident(input)?;
477 let sp = span_of(base, start, input);
478 if is_literal(tok) {
479 Ok(RhsTerm::Lit(tok.to_owned(), sp))
480 } else {
481 Ok(RhsTerm::Var(tok.to_owned(), sp))
482 }
483 }
484}
485
486fn parse_rhs_dotdot(input: &mut &str, base: usize) -> ModalResult<RhsChild> {
487 let start = input.as_ptr() as usize;
488 assert!(input.starts_with(".."));
489 *input = &input[2..];
490 ws(input)?;
491
492 if input.starts_with('{') {
493 expect_char(input, '{')?;
494 let body = parse_rhs(input, base)?;
495 ws(input)?;
496 let mult = if input.starts_with(':') {
497 *input = &input[1..];
498 Some(parse_mult_expr(input)?)
499 } else {
500 None
501 };
502 ws(input)?;
503 expect_kw(input, "for")?;
504 let var = ident(input)?.to_owned();
505 ws(input)?;
506 let mult_var = if input.starts_with(':') {
507 *input = &input[1..];
508 Some(ident(input)?.to_owned())
509 } else {
510 None
511 };
512 ws(input)?;
513 expect_kw(input, "in")?;
514 let source = ident(input)?.to_owned();
515 let filter = parse_optional_if(input, base)?;
516 cut_char(input, '}')?;
517 match (mult, mult_var) {
518 (Some(m), Some(k)) => Ok(RhsChild::MsetComp {
519 body: Box::new(body),
520 mult: m,
521 var,
522 mult_var: k,
523 source,
524 filter,
525 span: span_of(base, start, input),
526 }),
527 (None, None) => Ok(RhsChild::SetComp {
528 body: Box::new(body),
529 var,
530 source,
531 filter,
532 span: span_of(base, start, input),
533 }),
534 _ => {
535 let mut e = ContextError::new();
536 e.push(StrContext::Label(
537 "multiset comp needs both :mult on body and :k on var",
538 ));
539 Err(ErrMode::Cut(e))
540 }
541 }
542 } else if input.starts_with('[') {
543 expect_char(input, '[')?;
544 let body = parse_rhs(input, base)?;
545 ws(input)?;
546 expect_kw(input, "for")?;
547 let var = ident(input)?.to_owned();
548 ws(input)?;
549 expect_kw(input, "in")?;
550 let source = ident(input)?.to_owned();
551 let filter = parse_optional_if(input, base)?;
552 cut_char(input, ']')?;
553 Ok(RhsChild::SeqComp {
554 body: Box::new(body),
555 var,
556 source,
557 filter,
558 span: span_of(base, start, input),
559 })
560 } else {
561 let name = ident(input)?;
562 Ok(RhsChild::Splice(
563 name.to_owned(),
564 span_of(base, start, input),
565 ))
566 }
567}
568
569fn expect_kw(input: &mut &str, kw: &'static str) -> ModalResult<()> {
570 let tok = ident(input)?;
571 if tok != kw {
572 let mut e = ContextError::new();
573 e.push(StrContext::Expected(StrContextValue::StringLiteral(kw)));
574 return Err(ErrMode::Cut(e));
575 }
576 Ok(())
577}
578
579fn parse_optional_if(input: &mut &str, base: usize) -> ModalResult<Option<Box<RhsTerm>>> {
580 ws(input)?;
581 if input.starts_with("if") && input[2..].starts_with(|c: char| c.is_whitespace() || c == '(') {
582 *input = &input[2..];
583 let guard = parse_rhs(input, base)?;
584 Ok(Some(Box::new(guard)))
585 } else {
586 Ok(None)
587 }
588}
589
590fn parse_mult_expr(input: &mut &str) -> ModalResult<MultExpr> {
591 ws(input)?;
592 if input.starts_with('(') {
593 expect_char(input, '(')?;
594 let op = op_expr(input)?;
595 let mut args = Vec::new();
596 loop {
597 ws(input)?;
598 if input.starts_with(')') {
599 break;
600 }
601 args.push(parse_mult_expr(input)?);
602 }
603 cut_char(input, ')')?;
604 Ok(MultExpr::Prim { op, args })
605 } else if input.starts_with(|c: char| c.is_ascii_digit()) {
606 let n = number(input)?;
607 Ok(MultExpr::Lit(n))
608 } else {
609 let name = ident(input)?;
610 Ok(MultExpr::Var(name.to_owned()))
611 }
612}
613
614fn parse_action(input: &mut &str, base: usize) -> ModalResult<Action> {
617 let start = input.as_ptr() as usize;
618 expect_char(input, '(')?;
619 let kw = op_expr(input)?;
620 let action = match kw.as_str() {
621 "union" => {
622 let a = parse_rhs(input, base)?;
623 let b = parse_rhs(input, base)?;
624 Action::Union(a, b)
625 }
626 "set" => {
627 cut_char(input, '(')?;
628 let func = ident(input)?.to_owned();
629 let mut args = Vec::new();
630 loop {
631 ws(input)?;
632 if input.starts_with(')') {
633 break;
634 }
635 args.push(parse_rhs(input, base)?);
636 }
637 cut_char(input, ')')?;
638 let value = parse_rhs(input, base)?;
639 Action::Set { func, args, value }
640 }
641 _ => {
642 let mut children = Vec::new();
643 loop {
644 ws(input)?;
645 if input.starts_with(')') {
646 break;
647 }
648 if input.starts_with("..") {
649 children.push(parse_rhs_dotdot(input, base)?);
650 } else {
651 children.push(RhsChild::Term(parse_rhs(input, base)?));
652 }
653 }
654 let action = Action::Insert(RhsTerm::App {
655 op: kw,
656 children,
657 span: span_of(base, start, input),
658 });
659 cut_char(input, ')')?;
660 return Ok(action);
661 }
662 };
663 cut_char(input, ')')?;
664 Ok(action)
665}
666
667struct RuleTags {
672 when: Vec<SurfacePattern>,
673 subsume: bool,
674 ruleset: Option<String>,
675}
676
677fn parse_rule_tags(input: &mut &str, base: usize) -> ModalResult<RuleTags> {
678 let mut t = RuleTags {
679 when: Vec::new(),
680 subsume: false,
681 ruleset: None,
682 };
683 loop {
684 ws(input)?;
685 if input.starts_with(":when") {
686 *input = &input[":when".len()..];
687 cut_char(input, '(')?;
688 loop {
689 ws(input)?;
690 if input.starts_with(')') {
691 break;
692 }
693 t.when.push(parse_pattern(input, base)?);
694 }
695 cut_char(input, ')')?;
696 } else if input.starts_with(":subsume") {
697 *input = &input[":subsume".len()..];
698 t.subsume = true;
699 } else if input.starts_with(":ruleset") {
700 *input = &input[":ruleset".len()..];
701 t.ruleset = Some(ident(input)?.to_owned());
702 } else {
703 break;
704 }
705 }
706 Ok(t)
707}
708
709fn pattern_as_rhs(p: &SurfacePattern) -> ModalResult<RhsTerm> {
713 match p {
714 SurfacePattern::Var(n, s) => Ok(RhsTerm::Var(n.clone(), *s)),
715 SurfacePattern::Lit(v, s) => Ok(RhsTerm::Lit(v.clone(), *s)),
716 SurfacePattern::App {
717 op,
718 prefix,
719 children,
720 suffix,
721 span,
722 } => {
723 let mut cs = Vec::with_capacity(children.len() + 2);
724 if let Some((n, s)) = prefix {
725 cs.push(RhsChild::Splice(n.clone(), *s));
726 }
727 for c in children {
728 match c {
729 SurfacePatChild::Elem(p) => cs.push(RhsChild::Term(pattern_as_rhs(p)?)),
730 SurfacePatChild::ElemMult(..) => {
731 let mut e = ContextError::new();
732 e.push(StrContext::Label(
733 "birewrite side cannot carry a :mult annotation",
734 ));
735 return Err(ErrMode::Cut(e));
736 }
737 }
738 }
739 if let Some((n, s)) = suffix {
740 cs.push(RhsChild::Splice(n.clone(), *s));
741 }
742 Ok(RhsTerm::App {
743 op: op.clone(),
744 children: cs,
745 span: *span,
746 })
747 }
748 }
749}
750
751fn parse_run_goal(input: &mut &str, base: usize) -> ModalResult<RunGoal> {
753 cut_char(input, '(')?;
754 ws(input)?;
755 let equal = if input.starts_with("!=") {
756 *input = &input[2..];
757 false
758 } else if input.starts_with('=') {
759 *input = &input[1..];
760 true
761 } else {
762 let mut e = ContextError::new();
763 e.push(StrContext::Expected(StrContextValue::Description(
764 ":until goal must be (= a b) or (!= a b)",
765 )));
766 return Err(ErrMode::Cut(e));
767 };
768 let left = parse_term_inner(input, base)?;
769 let right = parse_term_inner(input, base)?;
770 cut_char(input, ')')?;
771 Ok(RunGoal { left, right, equal })
772}
773
774fn parse_command(
778 input: &mut &str,
779 base: usize,
780 desugared: &mut Vec<SurfaceCommand>,
781) -> ModalResult<SurfaceCommand> {
782 ws(input)?;
783 let start = input.as_ptr() as usize;
784 expect_char(input, '(')?;
785 let kw = cut_err(kw_token).parse_next(input)?;
786 let cmd = match kw {
787 "rewrite" => {
788 let lhs = parse_pattern(input, base)?;
789 let rhs = parse_rhs(input, base)?;
790 let t = parse_rule_tags(input, base)?;
791 SurfaceCommand::Rewrite {
792 lhs,
793 rhs,
794 when: t.when,
795 subsume: t.subsume,
796 ruleset: t.ruleset,
797 }
798 }
799 "birewrite" => {
803 let lhs = parse_pattern(input, base)?;
804 let rhs = parse_pattern(input, base)?;
805 let t = parse_rule_tags(input, base)?;
806 if t.subsume {
807 let mut e = ContextError::new();
808 e.push(StrContext::Label(
809 "birewrite cannot be :subsume (it would subsume the node the reverse \
810 direction has to match)",
811 ));
812 return Err(ErrMode::Cut(e));
813 }
814 desugared.push(SurfaceCommand::Rewrite {
815 lhs: rhs.clone(),
816 rhs: pattern_as_rhs(&lhs)?,
817 when: t.when.clone(),
818 subsume: false,
819 ruleset: t.ruleset.clone(),
820 });
821 SurfaceCommand::Rewrite {
822 rhs: pattern_as_rhs(&rhs)?,
823 lhs,
824 when: t.when,
825 subsume: false,
826 ruleset: t.ruleset,
827 }
828 }
829 "rule" => {
830 cut_char(input, '(')?;
831 let mut body = Vec::new();
832 loop {
833 ws(input)?;
834 if input.starts_with(')') {
835 break;
836 }
837 body.push(parse_pattern(input, base)?);
838 }
839 cut_char(input, ')')?;
840 cut_char(input, '(')?;
841 let mut head = Vec::new();
842 loop {
843 ws(input)?;
844 if input.starts_with(')') {
845 break;
846 }
847 head.push(parse_action(input, base)?);
848 }
849 cut_char(input, ')')?;
850 let t = parse_rule_tags(input, base)?;
851 if !t.when.is_empty() {
852 let mut e = ContextError::new();
853 e.push(StrContext::Label(
854 "rule cannot use :when; put guard patterns in the rule body",
855 ));
856 return Err(ErrMode::Cut(e));
857 }
858 if t.subsume {
859 let mut e = ContextError::new();
860 e.push(StrContext::Label(
861 "rule cannot use :subsume; :subsume applies only to rewrite",
862 ));
863 return Err(ErrMode::Cut(e));
864 }
865 SurfaceCommand::Rule {
866 body,
867 head,
868 ruleset: t.ruleset,
869 }
870 }
871 "sort" => {
872 let name = ident(input)?.to_owned();
873 SurfaceCommand::Pass(Command::Sort(name))
874 }
875 "function" | "constructor" => {
879 let name = ident(input)?.to_owned();
880 cut_char(input, '(')?;
881 let mut arg_sorts = Vec::new();
882 loop {
883 ws(input)?;
884 if input.starts_with(')') {
885 break;
886 }
887 arg_sorts.push(ident(input)?.to_owned());
888 }
889 cut_char(input, ')')?;
890 let ret_sort = ident(input)?.to_owned();
891 let (tags, mut meta) = parse_decl_tags(input, base)?;
892 meta.is_constructor = kw == "constructor";
893 SurfaceCommand::Pass(Command::Function {
894 name,
895 arg_sorts,
896 ret_sort,
897 tags,
898 meta,
899 })
900 }
901 "datatype" => {
902 let name = ident(input)?.to_owned();
903 let mut variants = Vec::new();
904 loop {
905 ws(input)?;
906 if input.starts_with(')') {
907 break;
908 }
909 cut_char(input, '(')?;
910 let ctor = ident(input)?.to_owned();
911 let mut args = Vec::new();
912 loop {
913 ws(input)?;
914 if input.starts_with(')') || input.starts_with(':') {
915 break;
916 }
917 args.push(ident(input)?.to_owned());
918 }
919 let (tags, mut meta) = parse_decl_tags(input, base)?;
920 meta.is_constructor = true;
922 cut_char(input, ')')?;
923 variants.push(Variant {
924 name: ctor,
925 arg_sorts: args,
926 tags,
927 meta,
928 });
929 }
930 SurfaceCommand::Pass(Command::Datatype { name, variants })
931 }
932 "union" => {
933 let a = parse_term_inner(input, base)?;
934 let b = parse_term_inner(input, base)?;
935 SurfaceCommand::Pass(Command::Union(a, b))
936 }
937 "let" => {
938 let name = ident(input)?.to_owned();
939 let t = parse_term_inner(input, base)?;
940 SurfaceCommand::Pass(Command::Let(name, t))
941 }
942 "ruleset" => {
943 let name = ident(input)?.to_owned();
944 SurfaceCommand::Pass(Command::Ruleset(name))
945 }
946 "run" => {
947 ws(input)?;
950 let ruleset = if input.starts_with(|c: char| c.is_alphabetic() || c == '_') {
951 Some(ident(input)?.to_owned())
952 } else {
953 None
954 };
955 let limit = number(input)?;
956 ws(input)?;
957 let until = if input.starts_with(":until") {
958 *input = &input[":until".len()..];
959 Some(parse_run_goal(input, base)?)
960 } else {
961 None
962 };
963 SurfaceCommand::Pass(Command::Run {
964 ruleset,
965 limit,
966 until,
967 })
968 }
969 "print-size" => {
970 ws(input)?;
971 let op = if input.starts_with(')') {
972 None
973 } else {
974 Some(op_expr(input)?)
975 };
976 SurfaceCommand::Pass(Command::PrintSize(op))
977 }
978 "print-stats" => {
979 ws(input)?;
980 let file = if input.starts_with(":file") {
981 *input = &input[":file".len()..];
982 let quoted = parse_quoted_string(input)?;
983 Some(quoted[1..quoted.len() - 1].to_owned())
985 } else {
986 None
987 };
988 SurfaceCommand::Pass(Command::PrintStats(file))
989 }
990 "check" => {
991 ws(input)?;
992 let cmd = if input.starts_with("(!=") || input.starts_with("( !=") {
993 cut_char(input, '(')?;
994 ws(input)?;
995 *input = &input[2..];
996 let a = parse_term_inner(input, base)?;
997 let b = parse_term_inner(input, base)?;
998 cut_char(input, ')')?;
999 Command::CheckNeq(a, b)
1000 } else if input.starts_with("(=") || input.starts_with("( =") {
1001 cut_char(input, '(')?;
1002 ws(input)?;
1003 if !input.starts_with('=') {
1004 let mut e = ContextError::new();
1005 e.push(StrContext::Expected(StrContextValue::CharLiteral('=')));
1006 return Err(ErrMode::Cut(e));
1007 }
1008 *input = &input[1..];
1009 let a = parse_term_inner(input, base)?;
1010 let b = parse_term_inner(input, base)?;
1011 cut_char(input, ')')?;
1012 Command::CheckEq(a, b)
1013 } else {
1014 let t = parse_term_inner(input, base)?;
1015 Command::Check(t)
1016 };
1017 SurfaceCommand::Pass(cmd)
1018 }
1019 "push" => {
1020 ws.parse_next(input).ok();
1021 let shrink = input.starts_with(":shrink");
1022 if shrink {
1023 *input = &input[7..];
1024 }
1025 SurfaceCommand::Pass(Command::Push(shrink))
1026 }
1027 "pop" => SurfaceCommand::Pass(Command::Pop),
1028 "extract" => {
1029 let t = parse_term_inner(input, base)?;
1030 SurfaceCommand::Pass(Command::Extract(t))
1031 }
1032 "checkau" => {
1033 ws(input)?;
1034 let left = parse_term_inner(input, base)?;
1035 ws(input)?;
1036 let right = parse_term_inner(input, base)?;
1037 let mut max_size = u32::MAX;
1038 let mut playouts = 1000u64;
1039 let mut algorithm = "uct".to_string();
1040 let mut cycle_mode = "sides".to_string();
1041 loop {
1042 ws(input)?;
1043 if input.starts_with(')') {
1044 break;
1045 }
1046 if input.starts_with(":max_size") {
1047 *input = &input[":max_size".len()..];
1048 let n = number(input)?;
1049 max_size = u32::try_from(n).map_err(|_| {
1050 let mut e = ContextError::new();
1051 e.push(StrContext::Expected(StrContextValue::Description(
1052 "checkau :max_size fitting in u32",
1053 )));
1054 ErrMode::Cut(e)
1055 })?;
1056 } else if input.starts_with(":playouts") {
1057 *input = &input[":playouts".len()..];
1058 playouts = number(input)?;
1059 } else if input.starts_with(":algorithm") {
1060 *input = &input[":algorithm".len()..];
1061 algorithm = ident(input)?.to_string();
1062 } else if input.starts_with(":cycles") {
1063 *input = &input[":cycles".len()..];
1064 cycle_mode = kw_token(input)?.to_string();
1065 } else {
1066 break;
1067 }
1068 }
1069 SurfaceCommand::Pass(Command::CheckAu {
1070 left,
1071 right,
1072 max_size,
1073 playouts,
1074 algorithm,
1075 cycle_mode,
1076 })
1077 }
1078 "antiunify" => {
1079 ws(input)?;
1080 let left = parse_term_inner(input, base)?;
1081 ws(input)?;
1082 let right = parse_term_inner(input, base)?;
1083 let mut playouts = 1000u64;
1084 let mut algorithm = "uct".to_string();
1085 let mut cycle_mode = "sides".to_string();
1086 loop {
1087 ws(input)?;
1088 if input.starts_with(')') {
1089 break;
1090 }
1091 if input.starts_with(":playouts") {
1092 *input = &input[":playouts".len()..];
1093 playouts = number(input)?;
1094 } else if input.starts_with(":algorithm") {
1095 *input = &input[":algorithm".len()..];
1096 algorithm = ident(input)?.to_string();
1097 } else if input.starts_with(":cycles") {
1098 *input = &input[":cycles".len()..];
1099 cycle_mode = kw_token(input)?.to_string();
1100 } else {
1101 break;
1102 }
1103 }
1104 SurfaceCommand::Pass(Command::AntiUnify {
1105 left,
1106 right,
1107 playouts,
1108 algorithm,
1109 cycle_mode,
1110 })
1111 }
1112 _ => {
1113 let mut children = Vec::new();
1115 loop {
1116 ws(input)?;
1117 if input.starts_with(')') {
1118 break;
1119 }
1120 children.push(parse_term_inner(input, base)?);
1121 }
1122 let cmd = SurfaceCommand::Pass(Command::Insert(Term::App {
1123 op: kw.to_owned(),
1124 children,
1125 span: span_of(base, start, input),
1126 }));
1127 cut_char(input, ')')?;
1128 return Ok(cmd);
1129 }
1130 };
1131 cut_char(input, ')')?;
1132 Ok(cmd)
1133}
1134
1135fn parse_decl_tags(input: &mut &str, base: usize) -> ModalResult<(Vec<AlgTag>, OpMeta)> {
1145 let mut tags = Vec::new();
1146 let mut meta = OpMeta::default();
1147 loop {
1148 ws_inner(input);
1149 if input.starts_with(":cost") {
1151 *input = &input[":cost".len()..];
1152 let n = number(input)?;
1153 meta.cost = u32::try_from(n).map_err(|_| {
1154 let mut e = ContextError::new();
1155 e.push(StrContext::Expected(StrContextValue::Description(
1156 ":cost must fit in u32",
1157 )));
1158 ErrMode::Cut(e)
1159 })?;
1160 continue;
1161 }
1162 if input.starts_with(":unextractable") {
1163 *input = &input[":unextractable".len()..];
1164 meta.unextractable = true;
1165 continue;
1166 }
1167 if input.starts_with(":assoc-comm-idem") {
1169 *input = &input[":assoc-comm-idem".len()..];
1170 tags.push(AlgTag::Assoc);
1171 tags.push(AlgTag::Comm);
1172 tags.push(AlgTag::Idempotent);
1173 } else if input.starts_with(":assoc-comm") {
1174 *input = &input[":assoc-comm".len()..];
1175 tags.push(AlgTag::Assoc);
1176 tags.push(AlgTag::Comm);
1177 } else if input.starts_with(":assoc-left") {
1178 *input = &input[":assoc-left".len()..];
1179 tags.push(AlgTag::AssocLeft);
1180 } else if input.starts_with(":assoc-right") {
1181 *input = &input[":assoc-right".len()..];
1182 tags.push(AlgTag::AssocRight);
1183 } else if input.starts_with(":assoc") {
1184 *input = &input[":assoc".len()..];
1185 tags.push(AlgTag::Assoc);
1186 } else if input.starts_with(":comm") {
1187 *input = &input[":comm".len()..];
1188 tags.push(AlgTag::Comm);
1189 } else if input.starts_with(":idempotent") {
1190 *input = &input[":idempotent".len()..];
1191 tags.push(AlgTag::Idempotent);
1192 } else if input.starts_with(":nilpotent") {
1193 *input = &input[":nilpotent".len()..];
1194 ws_inner(input);
1196 let order = if input.starts_with(|c: char| c.is_ascii_digit()) {
1197 let n = number(input)?;
1198 if !(2..=255).contains(&n) {
1199 let mut e = ContextError::new();
1200 e.push(StrContext::Expected(StrContextValue::Description(
1201 ":nilpotent order must be 2..=255",
1202 )));
1203 return Err(ErrMode::Cut(e));
1204 }
1205 Some(n as u8)
1206 } else {
1207 None
1208 };
1209 tags.push(AlgTag::Nilpotent(order));
1214 } else if input.starts_with(":identity") {
1215 *input = &input[":identity".len()..];
1216 let term = parse_term_inner(input, base)?;
1218 tags.push(AlgTag::Identity(term));
1219 } else if input.starts_with(":cancellative") {
1220 *input = &input[":cancellative".len()..];
1221 tags.push(AlgTag::Cancellative);
1222 } else if input.starts_with(":inverse") {
1223 *input = &input[":inverse".len()..];
1224 let name = ident(input)?.to_owned();
1225 tags.push(AlgTag::Inverse(name));
1226 } else {
1227 break;
1228 }
1229 }
1230 Ok((tags, meta))
1231}
1232
1233fn ws_inner(input: &mut &str) {
1234 while let Some(pos) = input.find(|c: char| !c.is_whitespace()) {
1235 if input.as_bytes()[pos] == b';' {
1236 *input = &input[pos..];
1237 if let Some(nl) = input.find('\n') {
1238 *input = &input[nl..];
1239 } else {
1240 *input = "";
1241 return;
1242 }
1243 } else {
1244 *input = &input[pos..];
1245 return;
1246 }
1247 }
1248 *input = "";
1249}
1250
1251pub fn parse_program_v2(input: &str) -> Result<Vec<SurfaceCommand>, ParseError> {
1254 let base = input.as_ptr() as usize;
1255 let mut rest = input;
1256 let mut cmds = Vec::new();
1257 let mut desugared = Vec::new();
1258 loop {
1259 ws(&mut rest).map_err(|e| format!("{e}"))?;
1260 if rest.is_empty() {
1261 break;
1262 }
1263 desugared.clear();
1264 let cmd = parse_command(&mut rest, base, &mut desugared).map_err(|e| format!("{e}"))?;
1265 cmds.push(cmd);
1266 cmds.append(&mut desugared);
1267 }
1268 Ok(cmds)
1269}
1270
1271pub fn parse_patterns(input: &str) -> Result<Vec<SurfacePattern>, ParseError> {
1273 let base = input.as_ptr() as usize;
1274 let mut rest = input;
1275 let mut pats = Vec::new();
1276 loop {
1277 ws(&mut rest).map_err(|e| format!("{e}"))?;
1278 if rest.is_empty() {
1279 break;
1280 }
1281 pats.push(parse_pattern(&mut rest, base).map_err(|e| format!("{e}"))?);
1282 }
1283 Ok(pats)
1284}
1285
1286#[cfg(test)]
1287mod alg_tag_tests {
1288 use super::*;
1289
1290 fn tags_of(src: &str) -> Vec<AlgTag> {
1292 let cmds = parse_program_v2(src).expect("parse");
1293 match &cmds[0] {
1294 SurfaceCommand::Pass(Command::Function { tags, .. }) => tags.clone(),
1295 other => panic!("expected function decl, got {other:?}"),
1296 }
1297 }
1298
1299 #[test]
1300 fn no_tags() {
1301 assert_eq!(tags_of("(function f (E E) E)"), vec![]);
1302 }
1303
1304 #[test]
1305 fn basic_tags_compose() {
1306 assert_eq!(
1307 tags_of("(function add (E) E :assoc :comm)"),
1308 vec![AlgTag::Assoc, AlgTag::Comm]
1309 );
1310 assert_eq!(
1311 tags_of("(function and (E) E :assoc :comm :idempotent)"),
1312 vec![AlgTag::Assoc, AlgTag::Comm, AlgTag::Idempotent]
1313 );
1314 }
1315
1316 #[test]
1317 fn aliases_expand_to_basic_tags() {
1318 assert_eq!(
1319 tags_of("(function add (E) E :assoc-comm)"),
1320 vec![AlgTag::Assoc, AlgTag::Comm]
1321 );
1322 assert_eq!(
1323 tags_of("(function and (E) E :assoc-comm-idem)"),
1324 vec![AlgTag::Assoc, AlgTag::Comm, AlgTag::Idempotent]
1325 );
1326 }
1327
1328 #[test]
1329 fn assoc_direction() {
1330 assert_eq!(
1331 tags_of("(function sub (E) E :assoc-left)"),
1332 vec![AlgTag::AssocLeft]
1333 );
1334 assert_eq!(
1335 tags_of("(function sub (E) E :assoc-right)"),
1336 vec![AlgTag::AssocRight]
1337 );
1338 }
1339
1340 #[test]
1341 fn nilpotent_optional_order() {
1342 assert_eq!(
1343 tags_of("(function xor (E) E :assoc :comm :nilpotent)"),
1344 vec![AlgTag::Assoc, AlgTag::Comm, AlgTag::Nilpotent(None)]
1345 );
1346 assert_eq!(
1347 tags_of("(function x3 (E) E :assoc :comm :nilpotent 3)"),
1348 vec![AlgTag::Assoc, AlgTag::Comm, AlgTag::Nilpotent(Some(3))]
1349 );
1350 }
1351
1352 #[test]
1353 fn identity_literal_and_ctor() {
1354 match &tags_of("(function add (E) E :assoc :comm :identity 0)")[2] {
1356 AlgTag::Identity(Term::Lit(tok, _)) => assert_eq!(tok, "0"),
1357 other => panic!("expected Identity(Lit), got {other:?}"),
1358 }
1359 match &tags_of("(function add (E) E :assoc :comm :identity (zero))")[2] {
1361 AlgTag::Identity(Term::App { op, .. }) => assert_eq!(op, "zero"),
1362 other => panic!("expected Identity(App), got {other:?}"),
1363 }
1364 }
1365
1366 fn meta_of(src: &str) -> OpMeta {
1368 let cmds = parse_program_v2(src).expect("parse");
1369 match &cmds[0] {
1370 SurfaceCommand::Pass(Command::Function { meta, .. }) => *meta,
1371 other => panic!("expected function/constructor decl, got {other:?}"),
1372 }
1373 }
1374
1375 #[test]
1376 fn function_is_not_a_constructor() {
1377 assert_eq!(meta_of("(function f (E E) E)"), OpMeta::default());
1378 }
1379
1380 #[test]
1381 fn constructor_sets_the_flag() {
1382 let m = meta_of("(constructor f (E E) E)");
1383 assert!(m.is_constructor);
1384 assert_eq!(m.cost, 1);
1385 assert!(!m.unextractable);
1386 }
1387
1388 #[test]
1389 fn extraction_tags_parse_and_mix_with_algebra_tags() {
1390 let m = meta_of("(constructor add (E) E :cost 7 :assoc :comm :unextractable)");
1391 assert!(m.is_constructor);
1392 assert_eq!(m.cost, 7);
1393 assert!(m.unextractable);
1394 assert_eq!(
1395 tags_of("(constructor add (E) E :cost 7 :assoc :comm :unextractable)"),
1396 vec![AlgTag::Assoc, AlgTag::Comm]
1397 );
1398 }
1399
1400 #[test]
1401 fn datatype_variants_are_constructors() {
1402 let cmds = parse_program_v2("(datatype M (Num) (Add M M :cost 4))").expect("parse");
1403 let SurfaceCommand::Pass(Command::Datatype { variants, .. }) = &cmds[0] else {
1404 panic!("expected datatype");
1405 };
1406 assert!(variants.iter().all(|v| v.meta.is_constructor));
1407 assert_eq!(variants[0].meta.cost, 1);
1408 assert_eq!(variants[1].meta.cost, 4);
1409 }
1410
1411 #[test]
1412 fn birewrite_expands_to_two_rewrites() {
1413 let cmds = parse_program_v2("(birewrite (f x) (g x) :ruleset r)").expect("parse");
1414 assert_eq!(cmds.len(), 2);
1415 let ops = |c: &SurfaceCommand| match c {
1416 SurfaceCommand::Rewrite {
1417 lhs, rhs, ruleset, ..
1418 } => {
1419 let l = match lhs {
1420 SurfacePattern::App { op, .. } => op.clone(),
1421 other => panic!("expected app lhs, got {other:?}"),
1422 };
1423 let r = match rhs {
1424 RhsTerm::App { op, .. } => op.clone(),
1425 other => panic!("expected app rhs, got {other:?}"),
1426 };
1427 (l, r, ruleset.clone())
1428 }
1429 other => panic!("expected rewrite, got {other:?}"),
1430 };
1431 assert_eq!(
1432 ops(&cmds[0]),
1433 ("f".into(), "g".into(), Some("r".to_string()))
1434 );
1435 assert_eq!(
1436 ops(&cmds[1]),
1437 ("g".into(), "f".into(), Some("r".to_string()))
1438 );
1439 }
1440
1441 #[test]
1442 fn run_forms() {
1443 let one = |src: &str| match &parse_program_v2(src).expect("parse")[0] {
1444 SurfaceCommand::Pass(Command::Run {
1445 ruleset,
1446 limit,
1447 until,
1448 }) => (ruleset.clone(), *limit, until.clone()),
1449 other => panic!("expected run, got {other:?}"),
1450 };
1451 assert_eq!(one("(run 12)"), (None, 12, None));
1452 assert_eq!(one("(run fast 3)"), (Some("fast".to_string()), 3, None));
1453 let (rs, limit, until) = one("(run fast 3 :until (!= a b))");
1454 assert_eq!((rs, limit), (Some("fast".to_string()), 3));
1455 assert!(!until.expect("goal").equal);
1456 assert!(one("(run 5 :until (= a b))").2.expect("goal").equal);
1457 }
1458
1459 #[test]
1460 fn stats_commands_lex_their_hyphenated_keywords() {
1461 let cmds = parse_program_v2(
1462 "(print-size) (print-size Add) (print-stats) (print-stats :file \"x.json\")",
1463 )
1464 .expect("parse");
1465 assert!(matches!(
1466 &cmds[0],
1467 SurfaceCommand::Pass(Command::PrintSize(None))
1468 ));
1469 assert!(
1470 matches!(&cmds[1], SurfaceCommand::Pass(Command::PrintSize(Some(op))) if op == "Add")
1471 );
1472 assert!(matches!(
1473 &cmds[2],
1474 SurfaceCommand::Pass(Command::PrintStats(None))
1475 ));
1476 assert!(
1477 matches!(&cmds[3], SurfaceCommand::Pass(Command::PrintStats(Some(p))) if p == "x.json")
1478 );
1479 }
1480
1481 #[test]
1482 fn inverse_names_op() {
1483 assert_eq!(
1484 tags_of("(function add (E) E :assoc :comm :identity 0 :inverse neg)")
1485 .into_iter()
1486 .filter(|t| matches!(t, AlgTag::Inverse(_)))
1487 .collect::<Vec<_>>(),
1488 vec![AlgTag::Inverse("neg".to_string())]
1489 );
1490 }
1491}