1use crate::context::Context;
16use crate::term::{int_lit, lit_bigint, Literal, Term};
17use std::cell::RefCell;
18use std::collections::HashMap;
19use std::rc::Rc;
20
21enum Scope {
23 Empty,
24 Bind(String, Val, Rc<Scope>),
25}
26
27#[derive(Clone)]
28enum Val {
29 Ctor(String, Vec<Val>),
31 Clos(Rc<(String, Term)>, Rc<Scope>),
33 Fix(Rc<(String, Term)>, Rc<Scope>),
35 Lit(Literal),
37 Prim(&'static str, Vec<Val>),
41 Stuck,
45}
46
47#[derive(Clone, Copy)]
50struct LiteralRules {
51 nat: bool,
52 int: bool,
53}
54
55trait LiteralValue: Sized {
56 fn literal_ref(&self) -> Option<&Literal>;
57 fn constructor_ref(&self) -> Option<(&str, &[Self])>;
58 fn literal_value(literal: Literal) -> Self;
59 fn constructor_value(name: &str, fields: Vec<Self>) -> Self;
60}
61impl LiteralValue for Val {
62 fn literal_ref(&self) -> Option<&Literal> {
63 if let Self::Lit(l) = self {
64 Some(l)
65 } else {
66 None
67 }
68 }
69 fn constructor_ref(&self) -> Option<(&str, &[Self])> {
70 if let Self::Ctor(n, args) = self {
71 Some((n, args))
72 } else {
73 None
74 }
75 }
76 fn literal_value(literal: Literal) -> Self {
77 Self::Lit(literal)
78 }
79 fn constructor_value(name: &str, fields: Vec<Self>) -> Self {
80 Self::Ctor(name.into(), fields)
81 }
82}
83impl LiteralRules {
84 fn new(ctx: &Context) -> Self {
85 Self {
86 nat: crate::int_inductive::canonical_nat_environment(ctx),
87 int: crate::int_inductive::canonical_environment(ctx),
88 }
89 }
90 fn constructor_form<V: LiteralValue>(&self, value: &V) -> bool {
91 value.constructor_ref().is_some()
92 || match value.literal_ref() {
93 Some(Literal::Nat(n)) => self.nat && !n.is_negative(),
94 Some(Literal::Int(_) | Literal::BigInt(_)) => self.int,
95 _ => false,
96 }
97 }
98 fn constructor<V: LiteralValue>(&self, value: V) -> V {
99 let one = logicaffeine_base::BigInt::from_i64(1);
100 let view = match value.literal_ref() {
101 Some(Literal::Nat(n)) if self.nat && !n.is_negative() => {
102 if *n == logicaffeine_base::BigInt::from_i64(0) {
103 Some(("Zero", None))
104 } else {
105 Some(("Succ", Some(Literal::Nat(n.sub(&one)))))
106 }
107 }
108 Some(literal) if self.int => lit_bigint(literal).map(|n| {
109 if n.is_negative() {
110 ("Int_negSucc", Some(Literal::Nat(n.abs().sub(&one))))
111 } else {
112 ("Int_ofNat", Some(Literal::Nat(n)))
113 }
114 }),
115 _ => None,
116 };
117 if let Some((name, field)) = view {
118 V::constructor_value(name, field.into_iter().map(V::literal_value).collect())
119 } else {
120 value
121 }
122 }
123 fn literal<'a, V: LiteralValue>(&self, value: &'a V) -> Option<std::borrow::Cow<'a, Literal>> {
124 if let Some(l) = value.literal_ref() {
125 return Some(std::borrow::Cow::Borrowed(l));
126 }
127 if !self.int {
128 return None;
129 }
130 let (name, fields) = value.constructor_ref()?;
131 if fields.len() != 1 || !matches!(name, "Int_ofNat" | "Int_negSucc") {
132 return None;
133 }
134 let mut field = &fields[0];
135 let one = logicaffeine_base::BigInt::from_i64(1);
136 let mut n = logicaffeine_base::BigInt::from_i64(0);
137 loop {
138 if let Some(Literal::Nat(tail)) = field.literal_ref() {
139 if tail.is_negative() {
140 return None;
141 }
142 n = n.add(tail);
143 break;
144 }
145 match field.constructor_ref()? {
146 ("Zero", []) => break,
147 ("Succ", [tail]) => {
148 n = n.add(&one);
149 field = tail;
150 }
151 _ => return None,
152 }
153 }
154 if name == "Int_negSucc" {
155 n = n.add(&one).negated();
156 }
157 Some(std::borrow::Cow::Owned(int_lit(n)))
158 }
159}
160
161fn prim_name(n: &str) -> Option<&'static str> {
172 match n {
173 "add" => Some("add"),
174 "sub" => Some("sub"),
175 "mul" => Some("mul"),
176 "div" => Some("div"),
177 "mod" => Some("mod"),
178 "le" => Some("le"),
179 "lt" => Some("lt"),
180 "ge" => Some("ge"),
181 "gt" => Some("gt"),
182 "Text_append" => Some("Text_append"),
183 "Text_beq" => Some("Text_beq"),
184 "Text_isPrefixOf" => Some("Text_isPrefixOf"),
185 "Text_length" => Some("Text_length"),
186 _ => None,
187 }
188}
189
190fn prim_arity(name: &str) -> usize {
198 match name {
199 "Text_length" => 1,
200 _ => 2,
201 }
202}
203
204enum PrimResult {
206 Int(Literal),
209 Text(Literal),
211 Bool(bool),
212 Stuck,
213}
214
215fn nat_order(name: &str, al: &Literal, bl: &Literal) -> Option<bool> {
236 let (Literal::Nat(a), Literal::Nat(b)) = (al, bl) else {
237 return None;
238 };
239 let zero = logicaffeine_base::BigInt::from_i64(0);
240 let a = if a.is_negative() { &zero } else { a };
241 let b = if b.is_negative() { &zero } else { b };
242 match name {
243 "natLe" => Some(a <= b),
244 "natLt" => Some(a < b),
245 _ => None,
246 }
247}
248
249fn nat_order_name(n: &str) -> Option<&'static str> {
253 match n {
254 "natLe" => Some("natLe"),
255 "natLt" => Some("natLt"),
256 _ => None,
257 }
258}
259
260fn ediv_emod_i64(a: i64, b: i64) -> Option<(i64, i64)> {
272 if b == 0 {
273 return Some((0, a));
274 }
275 Some((a.checked_div_euclid(b)?, a.checked_rem_euclid(b)?))
276}
277
278fn ediv_emod_big(
283 a: &logicaffeine_base::BigInt,
284 b: &logicaffeine_base::BigInt,
285) -> (logicaffeine_base::BigInt, logicaffeine_base::BigInt) {
286 use logicaffeine_base::BigInt;
287 let Some((_, truncated)) = a.div_rem(b) else {
288 return (BigInt::from_i64(0), a.clone());
289 };
290 let r = if truncated.is_negative() {
291 truncated.add(&b.abs())
292 } else {
293 truncated
294 };
295 let q = a
296 .sub(&r)
297 .div_rem(b)
298 .map(|(q, _)| q)
299 .unwrap_or_else(|| BigInt::from_i64(0));
300 (q, r)
301}
302
303fn prim_arith(name: &str, al: &Literal, bl: &Literal) -> PrimResult {
309 if let Some(r) = text_prim(name, al, bl) {
310 return r;
311 }
312 if let (Literal::Int(x), Literal::Int(y)) = (al, bl) {
313 let fast = match name {
314 "add" => x.checked_add(*y),
315 "sub" => x.checked_sub(*y),
316 "mul" => x.checked_mul(*y),
317 "div" => ediv_emod_i64(*x, *y).map(|(q, _)| q),
318 "mod" => ediv_emod_i64(*x, *y).map(|(_, r)| r),
319 _ => None,
320 };
321 if let Some(r) = fast {
322 return PrimResult::Int(Literal::Int(r));
323 }
324 match name {
325 "le" => return PrimResult::Bool(x <= y),
326 "lt" => return PrimResult::Bool(x < y),
327 "ge" => return PrimResult::Bool(x >= y),
328 "gt" => return PrimResult::Bool(x > y),
329 _ => {}
330 }
331 }
332 let (Some(xb), Some(yb)) = (lit_bigint(al), lit_bigint(bl)) else {
333 return PrimResult::Stuck;
334 };
335 let big = match name {
336 "add" => Some(xb.add(&yb)),
337 "sub" => Some(xb.sub(&yb)),
338 "mul" => Some(xb.mul(&yb)),
339 "div" => Some(ediv_emod_big(&xb, &yb).0),
340 "mod" => Some(ediv_emod_big(&xb, &yb).1),
341 _ => None,
342 };
343 if let Some(r) = big {
344 return PrimResult::Int(int_lit(r));
345 }
346 match name {
347 "le" => PrimResult::Bool(xb <= yb),
348 "lt" => PrimResult::Bool(xb < yb),
349 "ge" => PrimResult::Bool(xb >= yb),
350 "gt" => PrimResult::Bool(xb > yb),
351 _ => PrimResult::Stuck,
352 }
353}
354
355fn text_prim(name: &str, al: &Literal, bl: &Literal) -> Option<PrimResult> {
368 let (Literal::Text(a), Literal::Text(b)) = (al, bl) else {
369 return None;
370 };
371 Some(match name {
372 "Text_append" => PrimResult::Text(Literal::Text(a.chars().chain(b.chars()).collect())),
373 "Text_beq" => PrimResult::Bool(a.chars().eq(b.chars())),
374 "Text_isPrefixOf" => PrimResult::Bool(
375 b.chars().count() >= a.chars().count() && b.chars().zip(a.chars()).all(|(x, y)| x == y),
376 ),
377 _ => return None,
378 })
379}
380
381fn prim_unary(name: &str, al: &Literal) -> PrimResult {
385 match (name, al) {
386 ("Text_length", Literal::Text(s)) => PrimResult::Int(Literal::Nat(
387 logicaffeine_base::BigInt::from_u64(s.chars().count() as u64),
388 )),
389 _ => PrimResult::Stuck,
390 }
391}
392
393fn prim_val(r: PrimResult) -> Val {
395 match r {
396 PrimResult::Int(l) | PrimResult::Text(l) => Val::Lit(l),
397 PrimResult::Bool(b) => Val::Ctor(if b { "true" } else { "false" }.to_string(), Vec::new()),
398 PrimResult::Stuck => Val::Stuck,
399 }
400}
401
402fn prim_compute(rules: LiteralRules, name: &str, args: &[Val]) -> Val {
407 let r = match args {
408 [a] => rules.literal(a).map(|a| prim_unary(name, &a)),
409 [a, b] => rules
410 .literal(a)
411 .zip(rules.literal(b))
412 .map(|(a, b)| prim_arith(name, &a, &b)),
413 _ => None,
414 };
415 prim_val(r.unwrap_or(PrimResult::Stuck))
416}
417
418thread_local! {
422 static EVAL_STACK_BASE: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
423}
424struct EvalFrame {
425 previous: usize,
426}
427impl Drop for EvalFrame {
428 fn drop(&mut self) {
429 EVAL_STACK_BASE.with(|base| base.set(self.previous));
430 }
431}
432#[inline(always)]
433fn eval_stack_mark() -> usize {
434 let probe = 0u8;
435 std::ptr::addr_of!(probe) as usize
436}
437fn enter_eval_frame(here: usize) -> Option<EvalFrame> {
438 let previous = EVAL_STACK_BASE.with(|base| base.get());
439 if previous != 0 && previous.abs_diff(here) > crate::term_store::kernel_stack_bytes() / 2 {
440 return None;
441 }
442 if previous == 0 {
443 EVAL_STACK_BASE.with(|base| base.set(here));
444 }
445 Some(EvalFrame { previous })
446}
447
448const FUEL: u64 = 50_000_000;
449
450pub fn eval_bool(ctx: &Context, term: &Term) -> Option<bool> {
461 if let Some(b) = native_compile_decide(ctx, term) {
462 return Some(b);
463 }
464 eval_bool_tree(ctx, term)
465}
466
467pub fn eval_bool_tree(ctx: &Context, term: &Term) -> Option<bool> {
470 let mut fuel = FUEL;
471 let rules = LiteralRules::new(ctx);
472 match eval(ctx, rules, &Rc::new(Scope::Empty), term, &mut fuel) {
473 Val::Ctor(c, _) if c == "true" => Some(true),
474 Val::Ctor(c, _) if c == "false" => Some(false),
475 _ => None,
476 }
477}
478
479pub fn native_decide(ctx: &Context, prop: &Term, inst: &Term) -> Option<Term> {
486 let g = |s: &str| Term::Global(s.to_string());
487 let ap = |f: Term, x: Term| Term::App(Box::new(f), Box::new(x));
488 let decide_app = ap(ap(g("decide"), prop.clone()), inst.clone());
489 if eval_bool(ctx, &decide_app) != Some(true) {
490 return None;
491 }
492 let refl_true = ap(ap(g("refl"), g("Bool")), g("true"));
493 let of_reduce = ap(ap(ap(g("ofReduceBool"), decide_app), g("true")), refl_true);
494 Some(ap(
495 ap(ap(g("of_decide_eq_true"), prop.clone()), inst.clone()),
496 of_reduce,
497 ))
498}
499
500fn lookup(scope: &Rc<Scope>, name: &str) -> Option<Val> {
501 let mut s = scope;
502 loop {
503 match s.as_ref() {
504 Scope::Empty => return None,
505 Scope::Bind(n, v, rest) => {
506 if n == name {
507 return Some(v.clone());
508 }
509 s = rest;
510 }
511 }
512 }
513}
514
515fn count_type_params(ty: &Term) -> usize {
518 let mut n = 0;
519 let mut cur = ty;
520 while let Term::Pi {
521 param_type,
522 body_type,
523 ..
524 } = cur
525 {
526 if matches!(param_type.as_ref(), Term::Sort(_)) {
527 n += 1;
528 cur = body_type;
529 } else {
530 break;
531 }
532 }
533 n
534}
535
536fn eval(ctx: &Context, rules: LiteralRules, scope: &Rc<Scope>, term: &Term, fuel: &mut u64) -> Val {
537 let Some(_frame) = enter_eval_frame(eval_stack_mark()) else {
538 return Val::Stuck;
539 };
540 if *fuel == 0 {
541 return Val::Stuck;
542 }
543 *fuel -= 1;
544 match term {
545 Term::Var(n) => lookup(scope, n).unwrap_or(Val::Stuck),
546 Term::Global(n) => {
547 if crate::int_inductive::accelerates_integer_alias(ctx, n) {
548 if let Some(p) = prim_name(n) {
549 return Val::Prim(p, Vec::new());
550 }
551 }
552 if let Some(body) = ctx.get_definition_body(n) {
553 eval(ctx, rules, &Rc::new(Scope::Empty), body, fuel)
555 } else if ctx.is_constructor(n) {
556 Val::Ctor(n.clone(), Vec::new())
557 } else if let Some(p) =
558 prim_name(n).filter(|_| crate::reduction::declaration_agrees_with_the_rule(ctx, n))
559 {
560 Val::Prim(p, Vec::new())
561 } else {
562 Val::Stuck }
564 }
565 Term::Lambda { param, body, .. } => {
566 Val::Clos(Rc::new((param.clone(), (**body).clone())), scope.clone())
567 }
568 Term::Fix { name, body } => {
569 Val::Fix(Rc::new((name.clone(), (**body).clone())), scope.clone())
570 }
571 Term::App(f, a) => {
572 if let Some(decided) = eval_nat_order(ctx, rules, scope, f, a, fuel) {
576 return decided;
577 }
578 let fv = eval(ctx, rules, scope, f, fuel);
579 let av = eval(ctx, rules, scope, a, fuel);
580 apply(ctx, rules, fv, av, fuel)
581 }
582 Term::Match {
583 discriminant,
584 cases,
585 ..
586 } => {
587 match rules.constructor(eval(ctx, rules, scope, discriminant, fuel)) {
588 Val::Ctor(c, args) => {
589 let ind = match ctx.constructor_inductive(&c) {
592 Some(i) => i,
593 None => return Val::Stuck,
594 };
595 let ctors = ctx.get_constructors(ind);
596 let (idx, ctor_ty) = match ctors.iter().position(|(cn, _)| *cn == c) {
597 Some(i) => (i, ctors[i].1.clone()),
598 None => return Val::Stuck,
599 };
600 if idx >= cases.len() {
601 return Val::Stuck;
602 }
603 let nparams = ctx
604 .inductive_declared_params(ind)
605 .unwrap_or_else(|| count_type_params(&ctor_ty));
606 let value_args: &[Val] = if nparams < args.len() {
607 &args[nparams..]
608 } else {
609 &[]
610 };
611 let mut sel = eval(ctx, rules, scope, &cases[idx], fuel);
612 for va in value_args {
613 sel = apply(ctx, rules, sel, va.clone(), fuel);
614 }
615 sel
616 }
617 _ => Val::Stuck,
618 }
619 }
620 Term::Lit(l) => Val::Lit(l.clone()),
621 _ => Val::Stuck,
623 }
624}
625
626fn eval_nat_order(
634 ctx: &Context,
635 rules: LiteralRules,
636 scope: &Rc<Scope>,
637 func: &Term,
638 arg: &Term,
639 fuel: &mut u64,
640) -> Option<Val> {
641 let Term::App(head, x) = func else {
642 return None;
643 };
644 let Term::Global(name) = head.as_ref() else {
645 return None;
646 };
647 let op = nat_order_name(name)?;
648 if !crate::reduction::accelerates_nat_order(ctx, op) {
649 return None;
650 }
651 let (Val::Lit(al), Val::Lit(bl)) = (
652 eval(ctx, rules, scope, x, fuel),
653 eval(ctx, rules, scope, arg, fuel),
654 ) else {
655 return None;
656 };
657 let decided = nat_order(op, &al, &bl)?;
658 Some(Val::Ctor(
659 if decided { "true" } else { "false" }.to_string(),
660 Vec::new(),
661 ))
662}
663
664fn apply(ctx: &Context, rules: LiteralRules, fv: Val, av: Val, fuel: &mut u64) -> Val {
665 if *fuel == 0 {
666 return Val::Stuck;
667 }
668 match fv {
669 Val::Clos(pb, cenv) => {
670 let ext = Rc::new(Scope::Bind(pb.0.clone(), av, cenv));
671 eval(ctx, rules, &ext, &pb.1, fuel)
672 }
673 Val::Ctor(c, mut args) => {
674 args.push(av);
675 Val::Ctor(c, args)
676 }
677 Val::Prim(name, mut args) => {
678 args.push(av);
679 if args.len() < prim_arity(name) {
680 Val::Prim(name, args)
681 } else {
682 prim_compute(rules, name, &args)
683 }
684 }
685 Val::Fix(rb, fenv) => {
686 if rules.constructor_form(&av) {
689 let ext = Rc::new(Scope::Bind(
690 rb.0.clone(),
691 Val::Fix(rb.clone(), fenv.clone()),
692 fenv,
693 ));
694 let unfolded = eval(ctx, rules, &ext, &rb.1, fuel);
695 apply(ctx, rules, unfolded, av, fuel)
696 } else {
697 Val::Stuck
698 }
699 }
700 Val::Lit(_) => Val::Stuck,
702 Val::Stuck => Val::Stuck,
703 }
704}
705
706type IntThunk = Box<dyn Fn() -> i128>;
716type BoolThunk = Box<dyn Fn() -> bool>;
717
718fn as_binop(term: &Term) -> Option<(&str, &Term, &Term)> {
719 if let Term::App(fx, y) = term {
720 if let Term::App(op, x) = fx.as_ref() {
721 if let Term::Global(name) = op.as_ref() {
722 return Some((name.as_str(), x.as_ref(), y.as_ref()));
723 }
724 }
725 }
726 None
727}
728
729fn compile_int(term: &Term) -> Option<IntThunk> {
732 match term {
733 Term::Lit(Literal::Int(n)) => {
734 let n = *n as i128;
735 Some(Box::new(move || n))
736 }
737 Term::Lit(Literal::BigInt(n)) => {
738 let n = n.to_i64().map(|v| v as i128)?;
739 Some(Box::new(move || n))
740 }
741 _ => {
742 let (op, x, y) = as_binop(term)?;
743 let cx = compile_int(x)?;
744 let cy = compile_int(y)?;
745 match op {
746 "add" => Some(Box::new(move || cx() + cy())),
747 "sub" => Some(Box::new(move || cx() - cy())),
748 "mul" => Some(Box::new(move || cx() * cy())),
749 _ => None,
750 }
751 }
752 }
753}
754
755fn compile_bool(term: &Term) -> Option<BoolThunk> {
758 match term {
759 Term::Global(n) if n == "true" => Some(Box::new(|| true)),
760 Term::Global(n) if n == "false" => Some(Box::new(|| false)),
761 _ => {
762 let (op, x, y) = as_binop(term)?;
763 match op {
764 "le" | "lt" | "ge" | "gt" => {
765 let cx = compile_int(x)?;
766 let cy = compile_int(y)?;
767 Some(match op {
768 "le" => Box::new(move || cx() <= cy()),
769 "lt" => Box::new(move || cx() < cy()),
770 "ge" => Box::new(move || cx() >= cy()),
771 _ => Box::new(move || cx() > cy()),
772 })
773 }
774 "and" | "or" => {
775 let cx = compile_bool(x)?;
776 let cy = compile_bool(y)?;
777 Some(if op == "and" {
778 Box::new(move || cx() && cy())
779 } else {
780 Box::new(move || cx() || cy())
781 })
782 }
783 _ => None,
784 }
785 }
786 }
787}
788
789pub fn native_compile_bool(term: &Term) -> Option<bool> {
794 compile_bool(term).map(|c| c())
795}
796
797enum CScope {
811 Empty,
812 Bind(Rc<str>, CVal, Rc<CScope>),
813}
814
815#[derive(Clone)]
818enum CVal {
819 Ctor(Rc<str>, Rc<Vec<CVal>>),
821 Fun(Rc<dyn Fn(CVal, &mut u64) -> CVal>),
823 Fix(Rc<FixClosure>),
825 Lit(Literal),
826 Prim(&'static str, Rc<Vec<CVal>>, LiteralRules),
828 Stuck,
829}
830
831impl LiteralValue for CVal {
832 fn literal_ref(&self) -> Option<&Literal> {
833 if let Self::Lit(l) = self {
834 Some(l)
835 } else {
836 None
837 }
838 }
839 fn constructor_ref(&self) -> Option<(&str, &[Self])> {
840 if let Self::Ctor(n, args) = self {
841 Some((n, args))
842 } else {
843 None
844 }
845 }
846 fn literal_value(literal: Literal) -> Self {
847 Self::Lit(literal)
848 }
849 fn constructor_value(name: &str, fields: Vec<Self>) -> Self {
850 Self::Ctor(Rc::from(name), Rc::new(fields))
851 }
852}
853
854struct FixClosure {
856 body: Code,
857 name: Rc<str>,
858 env: Rc<CScope>,
859 rules: LiteralRules,
860}
861
862type Code = Rc<dyn Fn(&Rc<CScope>, &mut u64) -> CVal>;
864
865fn clookup(scope: &Rc<CScope>, name: &str) -> CVal {
866 let mut s = scope;
867 loop {
868 match s.as_ref() {
869 CScope::Empty => return CVal::Stuck,
870 CScope::Bind(n, v, rest) => {
871 if n.as_ref() == name {
872 return v.clone();
873 }
874 s = rest;
875 }
876 }
877 }
878}
879
880fn cprim_compute(rules: LiteralRules, name: &str, args: &[CVal]) -> CVal {
883 let r = match args {
884 [a] => rules
885 .literal(a)
886 .map(|a| prim_unary(name, &a))
887 .unwrap_or(PrimResult::Stuck),
888 [a, b] => rules
889 .literal(a)
890 .zip(rules.literal(b))
891 .map(|(a, b)| prim_arith(name, &a, &b))
892 .unwrap_or(PrimResult::Stuck),
893 _ => PrimResult::Stuck,
894 };
895 match r {
896 PrimResult::Int(l) | PrimResult::Text(l) => CVal::Lit(l),
897 PrimResult::Bool(b) => CVal::Ctor(
898 Rc::from(if b { "true" } else { "false" }),
899 Rc::new(Vec::new()),
900 ),
901 PrimResult::Stuck => CVal::Stuck,
902 }
903}
904
905fn capply(f: CVal, arg: CVal, fuel: &mut u64) -> CVal {
910 let Some(_frame) = enter_eval_frame(eval_stack_mark()) else {
911 return CVal::Stuck;
912 };
913 if *fuel == 0 {
914 return CVal::Stuck;
915 }
916 *fuel -= 1;
917 match f {
918 CVal::Fun(func) => func(arg, fuel),
919 CVal::Ctor(c, args) => {
920 let mut v = (*args).clone();
921 v.push(arg);
922 CVal::Ctor(c, Rc::new(v))
923 }
924 CVal::Prim(name, args, rules) => {
925 let mut v = (*args).clone();
926 v.push(arg);
927 if v.len() < prim_arity(name) {
928 CVal::Prim(name, Rc::new(v), rules)
929 } else {
930 cprim_compute(rules, name, &v)
931 }
932 }
933 CVal::Fix(fx) => {
934 if fx.rules.constructor_form(&arg) {
935 let self_val = CVal::Fix(fx.clone());
936 let ext = Rc::new(CScope::Bind(fx.name.clone(), self_val, fx.env.clone()));
937 let unfolded = (fx.body)(&ext, fuel);
938 capply(unfolded, arg, fuel)
939 } else {
940 CVal::Stuck
941 }
942 }
943 CVal::Lit(_) | CVal::Stuck => CVal::Stuck,
944 }
945}
946
947struct Compiler<'c> {
952 ctx: &'c Context,
953 rules: LiteralRules,
954 ctor_map: Rc<HashMap<String, (usize, usize)>>,
955 slots: RefCell<HashMap<String, Rc<RefCell<Option<Code>>>>>,
956}
957
958impl<'c> Compiler<'c> {
959 fn new(ctx: &'c Context) -> Self {
960 let mut ctor_map = HashMap::new();
964 let inductives: Vec<String> = ctx.iter_inductives().map(|(n, _)| n.to_string()).collect();
965 for ind in &inductives {
966 let declared = ctx.inductive_declared_params(ind);
967 for (idx, (cname, cty)) in ctx.get_constructors(ind).iter().enumerate() {
968 let nparams = declared.unwrap_or_else(|| count_type_params(cty));
969 ctor_map.entry(cname.to_string()).or_insert((idx, nparams));
970 }
971 }
972 Compiler {
973 ctx,
974 rules: LiteralRules::new(ctx),
975 ctor_map: Rc::new(ctor_map),
976 slots: RefCell::new(HashMap::new()),
977 }
978 }
979
980 fn compile(&self, term: &Term) -> Code {
981 match term {
982 Term::Var(n) => {
983 let n: Rc<str> = Rc::from(n.as_str());
984 Rc::new(move |env, _| clookup(env, &n))
985 }
986 Term::Lit(l) => {
987 let l = l.clone();
988 Rc::new(move |_, _| CVal::Lit(l.clone()))
989 }
990 Term::Global(n) => self.compile_global(n),
991 Term::Lambda { param, body, .. } => {
992 let param: Rc<str> = Rc::from(param.as_str());
993 let cbody = self.compile(body);
994 Rc::new(move |env, _| {
995 let env = env.clone();
996 let cbody = cbody.clone();
997 let param = param.clone();
998 CVal::Fun(Rc::new(move |arg, fuel| {
999 let ext = Rc::new(CScope::Bind(param.clone(), arg, env.clone()));
1000 cbody(&ext, fuel)
1001 }))
1002 })
1003 }
1004 Term::Fix { name, body } => {
1005 let name: Rc<str> = Rc::from(name.as_str());
1006 let rules = self.rules;
1007 let cbody = self.compile(body);
1008 Rc::new(move |env, _| {
1009 CVal::Fix(Rc::new(FixClosure {
1010 body: cbody.clone(),
1011 name: name.clone(),
1012 env: env.clone(),
1013 rules,
1014 }))
1015 })
1016 }
1017 Term::App(f, a) => {
1018 if let Some(fast) = self.compile_nat_order(f, a) {
1019 return fast;
1020 }
1021 let cf = self.compile(f);
1022 let ca = self.compile(a);
1023 Rc::new(move |env, fuel| {
1024 let fv = cf(env, fuel);
1025 let av = ca(env, fuel);
1026 capply(fv, av, fuel)
1027 })
1028 }
1029 Term::Match {
1030 discriminant,
1031 cases,
1032 ..
1033 } => {
1034 let cd = self.compile(discriminant);
1035 let ccases: Vec<Code> = cases.iter().map(|c| self.compile(c)).collect();
1036 let ctor_map = self.ctor_map.clone();
1037 let rules = self.rules;
1038 Rc::new(move |env, fuel| match rules.constructor(cd(env, fuel)) {
1039 CVal::Ctor(c, args) => {
1040 let (idx, nparams) = match ctor_map.get(c.as_ref()) {
1041 Some(p) => *p,
1042 None => return CVal::Stuck,
1043 };
1044 if idx >= ccases.len() {
1045 return CVal::Stuck;
1046 }
1047 let mut sel = ccases[idx](env, fuel);
1050 let value_args: &[CVal] = if nparams < args.len() {
1051 &args[nparams..]
1052 } else {
1053 &[]
1054 };
1055 for va in value_args {
1056 sel = capply(sel, va.clone(), fuel);
1057 }
1058 sel
1059 }
1060 _ => CVal::Stuck,
1061 })
1062 }
1063 _ => Rc::new(|_, _| CVal::Stuck),
1067 }
1068 }
1069
1070 fn compile_nat_order(&self, func: &Term, arg: &Term) -> Option<Code> {
1075 let Term::App(head, x) = func else {
1076 return None;
1077 };
1078 let Term::Global(name) = head.as_ref() else {
1079 return None;
1080 };
1081 let op = nat_order_name(name)?;
1082 if !crate::reduction::accelerates_nat_order(self.ctx, op) {
1083 return None;
1084 }
1085 let chead = self.compile_global(name);
1086 let cx = self.compile(x);
1087 let cy = self.compile(arg);
1088 Some(Rc::new(move |env, fuel| {
1089 let xv = cx(env, fuel);
1090 let yv = cy(env, fuel);
1091 if let (CVal::Lit(al), CVal::Lit(bl)) = (&xv, &yv) {
1092 if let Some(decided) = nat_order(op, al, bl) {
1093 let name: Rc<str> = Rc::from(if decided { "true" } else { "false" });
1094 return CVal::Ctor(name, Rc::new(Vec::new()));
1095 }
1096 }
1097 capply(capply(chead(env, fuel), xv, fuel), yv, fuel)
1098 }))
1099 }
1100
1101 fn compile_global(&self, n: &str) -> Code {
1102 if crate::int_inductive::accelerates_integer_alias(self.ctx, n) {
1103 if let Some(p) = prim_name(n) {
1104 let rules = self.rules;
1105 return Rc::new(move |_, _| CVal::Prim(p, Rc::new(Vec::new()), rules));
1106 }
1107 }
1108 if self.ctx.get_definition_body(n).is_some() {
1109 let slot = self.def_slot(n);
1113 Rc::new(move |_env, fuel| match slot.borrow().clone() {
1114 Some(code) => code(&Rc::new(CScope::Empty), fuel),
1115 None => CVal::Stuck,
1116 })
1117 } else if self.ctx.is_constructor(n) {
1118 let n: Rc<str> = Rc::from(n);
1119 Rc::new(move |_, _| CVal::Ctor(n.clone(), Rc::new(Vec::new())))
1120 } else if let Some(p) =
1121 prim_name(n).filter(|_| crate::reduction::declaration_agrees_with_the_rule(self.ctx, n))
1122 {
1123 {
1124 let rules = self.rules;
1125 Rc::new(move |_, _| CVal::Prim(p, Rc::new(Vec::new()), rules))
1126 }
1127 } else {
1128 Rc::new(|_, _| CVal::Stuck)
1130 }
1131 }
1132
1133 fn def_slot(&self, n: &str) -> Rc<RefCell<Option<Code>>> {
1137 if let Some(s) = self.slots.borrow().get(n) {
1138 return s.clone();
1139 }
1140 let s = Rc::new(RefCell::new(None));
1141 self.slots.borrow_mut().insert(n.to_string(), s.clone());
1142 let body = self
1143 .ctx
1144 .get_definition_body(n)
1145 .expect("def_slot on a definition")
1146 .clone();
1147 let cbody = self.compile(&body);
1148 *s.borrow_mut() = Some(cbody);
1149 s
1150 }
1151}
1152
1153pub fn native_compile_decide(ctx: &Context, term: &Term) -> Option<bool> {
1159 let compiler = Compiler::new(ctx);
1160 let code = compiler.compile(term);
1161 let mut fuel = FUEL;
1162 match code(&Rc::new(CScope::Empty), &mut fuel) {
1163 CVal::Ctor(c, _) if c.as_ref() == "true" => Some(true),
1164 CVal::Ctor(c, _) if c.as_ref() == "false" => Some(false),
1165 _ => None,
1166 }
1167}
1168
1169#[cfg(test)]
1170#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/eval/prim_arith_tests.rs"]
1171mod prim_arith_tests;
1172
1173#[cfg(test)]
1174#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/eval/eval_tree_tests.rs"]
1175mod eval_tree_tests;