diff --git a/CHANGELOG.md b/CHANGELOG.md index 1ee4f9a..dfca375 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,7 @@ All changes that a user can see are in this file. The format follows Keep a Chan - `scripts/arena-fetch.sh` downloads the Arena tests and results and keeps only the tests whose export has the hash of the results. - The `bench` workflow runs the official kernel of Lean v4.35.0 on the Arena tests each week and compares its instruction counts with the Arena numbers. - `docs/bench/baseline.md` records the first baseline run. The verdicts match the Arena on all 225 tests. The cachegrind counts are not within 2% of the Arena counts, so the 2% limit applies only to `perf`. +- `rulean-core` has the environment and the type checker of engine R, as a transcription of `type_checker.cpp`, `inductive_reduce_rec` and `quot_reduce_rec` of the official kernel v4.35.0. The checker infers types in the infer-only mode and in the check mode, reduces terms to weak head normal form in the official order (beta, zeta, projections, recursors, quotients, the `Nat` extension and delta), and decides definitional equality with lazy delta reduction, eta, structure eta, proof irrelevance, unit-like types and the `Nat` and `String` literal extensions. An error is a sticky fault, and a depth bound stops deep recursion. The `Nat` operations check the size bound of 128 MiB. ### Changed diff --git a/Cargo.lock b/Cargo.lock index 6218526..952e017 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -81,6 +81,7 @@ version = "0.0.2" name = "rulean-core" version = "0.0.2" dependencies = [ + "rulean-format", "rulean-nat", "rulean-store", ] diff --git a/crates/rulean-core/Cargo.toml b/crates/rulean-core/Cargo.toml index 62bf790..4bdcbe0 100644 --- a/crates/rulean-core/Cargo.toml +++ b/crates/rulean-core/Cargo.toml @@ -17,5 +17,6 @@ layer = "core" workspace = true [dependencies] +rulean-format = { path = "../rulean-format" } rulean-nat = { path = "../rulean-nat" } rulean-store = { path = "../rulean-store" } diff --git a/crates/rulean-core/src/defeq.rs b/crates/rulean-core/src/defeq.rs new file mode 100644 index 0000000..87afbf4 --- /dev/null +++ b/crates/rulean-core/src/defeq.rs @@ -0,0 +1,664 @@ +//! Engine R: definitional equality (spec 05.7). +//! +//! This module is a transcription of `is_def_eq_core` and its helpers in `type_checker.cpp` of the official kernel v4.35.0. The order of the steps is the same as the order in the official function, because the order changes which terms the checker unfolds. + +use alloc::vec::Vec; +use rulean_store::{Expr, ExprId, LevelListId, Literal, NameId}; + +use crate::env::{ConstKind, compare_hints}; +use crate::expr; +use crate::level; +use crate::tc::{Checker, LBool, to_lbool}; +use rulean_format::Hints; + +/// The result of one step of lazy delta reduction (`reduction_status`). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Status { + Continue, + Unknown, + Equal, + Diff, +} + +impl Checker { + // The caches. The key is the pair in the order of the hashes, as in the official kernel. + + fn pair_seen(&self, success: bool, t: ExprId, s: ExprId) -> bool { + let m = if success { + &self.c_success + } else { + &self.c_failure + }; + let ht = self.st.hash(t); + let hs = self.st.hash(s); + if ht < hs { + m.contains(t.0, s.0) + } else if ht > hs { + m.contains(s.0, t.0) + } else { + m.contains(t.0, s.0) || m.contains(s.0, t.0) + } + } + + fn pair_put(&mut self, success: bool, t: ExprId, s: ExprId) { + let (a, b) = if self.st.hash(t) <= self.st.hash(s) { + (t, s) + } else { + (s, t) + }; + if success { + self.c_success.put(a.0, b.0, 1); + } else { + self.c_failure.put(a.0, b.0, 1); + } + } + + // Levels. + + /// `is_def_eq` on two level lists: the same length and equivalent items. + fn is_def_eq_levels(&mut self, a: LevelListId, b: LevelListId) -> bool { + let la = self.st.level_list_vec(a); + let lb = self.st.level_list_vec(b); + level::is_equivalent_list(&mut self.st, &mut self.lc, &la, &lb) + } + + /// The level list of a constant. The caller has checked that `e` is a constant. + fn const_levels(&self, e: ExprId) -> LevelListId { + match self.st.node(e) { + Expr::Const(_, ls) => ls, + _ => self.st.level_list_empty(), + } + } + + // The easy cases. + + /// One binder of `is_def_eq_binding`. It checks the domains, pushes the free variable or the placeholder, and gives the bodies. The first value is false if the domains are not equal. + fn binding_step( + &mut self, + t: ExprId, + s: ExprId, + subst: &mut Vec, + ) -> (bool, ExprId, ExprId) { + let pair = match (self.st.node(t), self.st.node(s)) { + (Expr::Lam(a), Expr::Lam(b)) => (a, b), + (Expr::Pi(a), Expr::Pi(b)) => (a, b), + _ => return (false, t, s), + }; + let (tb, sb) = pair; + let mut var_s_type: Option = None; + if !self.eq(tb.dom, sb.dom) { + let vs = self.instantiate_rev(sb.dom, subst); + let vt = self.instantiate_rev(tb.dom, subst); + var_s_type = Some(vs); + if !self.is_def_eq(vt, vs) { + return (false, t, s); + } + } + if expr::has_loose_bvars(&self.st, tb.body) || expr::has_loose_bvars(&self.st, sb.body) { + let ty = match var_s_type { + Some(v) => v, + None => self.instantiate_rev(sb.dom, subst), + }; + let fv = self.mk_local(sb.name, sb.info, ty, None); + subst.push(fv); + } else { + subst.push(self.dummy); + } + (true, tb.body, sb.body) + } + + /// `is_def_eq_binding`: the domains and the bodies of two binders of the same kind, for all the binders of that kind at the head. + fn is_def_eq_binding(&mut self, t0: ExprId, s0: ExprId) -> bool { + let lam = self.is_lambda(t0); + let mut t = t0; + let mut s = s0; + let mut subst: Vec = Vec::new(); + let mut ok = true; + let mut walking = true; + while ok && walking && !self.bad() { + let (k, t1, s1) = self.binding_step(t, s, &mut subst); + ok = k; + t = t1; + s = s1; + walking = if lam { + self.is_lambda(t) && self.is_lambda(s) + } else { + self.is_pi(t) && self.is_pi(s) + }; + } + if !ok || self.bad() { + return false; + } + let ti = self.instantiate_rev(t, &subst); + let si = self.instantiate_rev(s, &subst); + self.is_def_eq(ti, si) + } + + /// `quick_is_def_eq`. + fn quick_is_def_eq(&mut self, t: ExprId, s: ExprId) -> LBool { + if self.eq(t, s) || self.pair_seen(true, t, s) { + return LBool::True; + } + match (self.st.node(t), self.st.node(s)) { + (Expr::Lam(_), Expr::Lam(_)) | (Expr::Pi(_), Expr::Pi(_)) => { + to_lbool(self.is_def_eq_binding(t, s)) + } + (Expr::Sort(a), Expr::Sort(b)) => { + to_lbool(level::is_equivalent(&mut self.st, &mut self.lc, a, b)) + } + (Expr::Lit(a), Expr::Lit(b)) => to_lbool(self.lit_eq(a, b)), + _ => LBool::Undef, + } + } + + fn lit_eq(&self, a: Literal, b: Literal) -> bool { + match (a, b) { + (Literal::Nat(x), Literal::Nat(y)) => x == y || self.st.nat(x).beq(self.st.nat(y)), + (Literal::Str(x), Literal::Str(y)) => { + x == y || self.st.str_bytes(x) == self.st.str_bytes(y) + } + _ => false, + } + } + + /// `is_def_eq_args`: the arguments from the last one to the first one. + fn is_def_eq_args(&mut self, t0: ExprId, s0: ExprId) -> bool { + let mut t = t0; + let mut s = s0; + let mut ok = true; + while ok && self.is_app(t) && self.is_app(s) { + let a = self.app_arg(t); + let b = self.app_arg(s); + if self.is_def_eq(a, b) { + t = self.app_fn1(t); + s = self.app_fn1(s); + } else { + ok = false; + } + } + ok && !self.is_app(t) && !self.is_app(s) + } + + // Eta. + + /// `try_eta_expansion_core`: `fun x => b =?= s` by `fun x => s x`. + fn try_eta_expansion_core(&mut self, t: ExprId, s: ExprId) -> bool { + if !self.is_lambda(t) || self.is_lambda(s) { + return false; + } + let ty = self.infer(s); + let s_type = self.whnf(ty); + if self.bad() { + return false; + } + let b = match self.st.node(s_type) { + Expr::Pi(b) => b, + _ => return false, + }; + let v = self.st.mk_bvar(0); + let sv = self.st.mk_app(s, v); + let new_s = self.st.mk_lam(b.name, b.info, b.dom, sv); + self.is_def_eq(t, new_s) + } + + fn try_eta_expansion(&mut self, t: ExprId, s: ExprId) -> bool { + self.try_eta_expansion_core(t, s) || self.try_eta_expansion_core(s, t) + } + + /// `try_eta_struct_core`: `t =?= mk t.1 ... t.n`. + fn try_eta_struct_core(&mut self, t: ExprId, s: ExprId) -> bool { + let f = expr::app_fn(&self.st, s); + let n = match self.st.node(f) { + Expr::Const(n, _) => n, + _ => return false, + }; + if self.get_const(n, s) == 0 { + return false; + } + let (induct, nparams, nfields) = match self.ctor_shape(n) { + Some(x) => x, + None => return false, + }; + let mut s_args: Vec = Vec::new(); + expr::app_args(&self.st, s, &mut s_args); + if s_args.len() != (nparams + nfields) as usize { + return false; + } + if !self.is_non_rec_structure(induct, s) { + return false; + } + let tt = self.infer(t); + let st = self.infer(s); + if self.bad() || !self.is_def_eq(tt, st) { + return false; + } + let mut ok = true; + let mut i = nparams as usize; + while ok && i < s_args.len() { + let p = self.st.mk_proj(induct, (i - nparams as usize) as u32, t); + ok = self.is_def_eq(p, s_args[i]); + i += 1; + } + ok + } + + fn try_eta_struct(&mut self, t: ExprId, s: ExprId) -> bool { + self.try_eta_struct_core(t, s) || self.try_eta_struct_core(s, t) + } + + /// `is_def_eq_app`: the same head and the same arguments. + fn is_def_eq_app(&mut self, t: ExprId, s: ExprId) -> bool { + if !self.is_app(t) || !self.is_app(s) { + return false; + } + let mut t_args: Vec = Vec::new(); + let mut s_args: Vec = Vec::new(); + let tf = expr::app_args(&self.st, t, &mut t_args); + let sf = expr::app_args(&self.st, s, &mut s_args); + if !self.is_def_eq(tf, sf) || t_args.len() != s_args.len() { + return false; + } + let mut ok = true; + let mut i = 0; + while ok && i < t_args.len() { + ok = self.is_def_eq(t_args[i], s_args[i]); + i += 1; + } + ok + } + + /// `is_def_eq_proof_irrel`: two proofs of the same proposition are equal. + fn is_def_eq_proof_irrel(&mut self, t: ExprId, s: ExprId) -> LBool { + let t_type = self.infer(t); + if self.bad() || !self.is_prop(t_type) { + return LBool::Undef; + } + let s_type = self.infer(s); + if self.bad() { + return LBool::Undef; + } + to_lbool(self.is_def_eq(t_type, s_type)) + } + + // Lazy delta reduction. + + /// `try_unfold_proj_app`. + fn try_unfold_proj_app(&mut self, e: ExprId) -> Option { + let f = expr::app_fn(&self.st, e); + match self.st.node(f) { + Expr::Proj(_) => { + let n = self.whnf_core(e, false, false); + if self.eq(n, e) { None } else { Some(n) } + } + _ => None, + } + } + + /// One delta step: `whnf_core(unfold_definition(e), false, true)`. + fn delta_step(&mut self, e: ExprId) -> ExprId { + match self.unfold_definition(e) { + Some(u) => self.whnf_core(u, false, true), + None => e, + } + } + + /// The unfold step of `lazy_delta_reduction_step` when both sides are delta terms. + fn lazy_delta_both( + &mut self, + t: ExprId, + s: ExprId, + dt: u32, + ds: u32, + ) -> (Status, ExprId, ExprId) { + let c = compare_hints(self.hints(dt), self.hints(ds)); + if c < 0 { + return (Status::Continue, self.delta_step(t), s); + } + if c > 0 { + return (Status::Continue, t, self.delta_step(s)); + } + let regular = matches!(self.hints(dt), Hints::Regular(_)); + if self.is_app(t) && self.is_app(s) && dt == ds && regular && !self.pair_seen(false, t, s) { + let tf = expr::app_fn(&self.st, t); + let sf = expr::app_fn(&self.st, s); + let tl = self.const_levels(tf); + let sl = self.const_levels(sf); + if self.is_def_eq_levels(tl, sl) && self.is_def_eq_args(t, s) { + return (Status::Equal, t, s); + } + self.pair_put(false, t, s); + } + let t1 = self.delta_step(t); + let s1 = self.delta_step(s); + (Status::Continue, t1, s1) + } + + /// `lazy_delta_reduction_step`. It returns the status and the new terms. + fn lazy_delta_reduction_step(&mut self, t0: ExprId, s0: ExprId) -> (Status, ExprId, ExprId) { + let dt = self.is_delta(t0); + let ds = self.is_delta(s0); + let (st, t, s) = if dt == 0 && ds == 0 { + (Status::Unknown, t0, s0) + } else if dt != 0 && ds == 0 { + match self.try_unfold_proj_app(s0) { + Some(s1) => (Status::Continue, t0, s1), + None => (Status::Continue, self.delta_step(t0), s0), + } + } else if dt == 0 { + match self.try_unfold_proj_app(t0) { + Some(t1) => (Status::Continue, t1, s0), + None => (Status::Continue, t0, self.delta_step(s0)), + } + } else { + self.lazy_delta_both(t0, s0, dt, ds) + }; + if st != Status::Continue || self.bad() { + return (st, t, s); + } + match self.quick_is_def_eq(t, s) { + LBool::True => (Status::Equal, t, s), + LBool::False => (Status::Diff, t, s), + LBool::Undef => (Status::Continue, t, s), + } + } + + /// `is_nat_zero`. + fn is_nat_zero(&self, t: ExprId) -> bool { + if t == self.b.e_nat_zero { + return true; + } + match self.st.node(t) { + Expr::Lit(Literal::Nat(n)) => self.st.nat(n).is_zero(), + _ => false, + } + } + + /// `is_nat_succ`: the predecessor of a non-zero literal or of `Nat.succ x`. + fn is_nat_succ(&mut self, t: ExprId) -> Option { + if let Expr::Lit(Literal::Nat(n)) = self.st.node(t) { + let v = self.st.nat(n).clone(); + if !v.is_zero() { + let p = v.sub(&rulean_nat::Nat::from_u64(1)); + let id = self.st.intern_nat(p); + return Some(self.st.mk_nat_lit(id)); + } + } + let f = expr::app_fn(&self.st, t); + if f == self.b.e_nat_succ && expr::app_num_args(&self.st, t) == 1 { + return Some(self.app_arg(t)); + } + None + } + + /// `is_def_eq_offset`. + fn is_def_eq_offset(&mut self, t: ExprId, s: ExprId) -> LBool { + if self.is_nat_zero(t) && self.is_nat_zero(s) { + return LBool::True; + } + let pt = self.is_nat_succ(t); + let ps = self.is_nat_succ(s); + match (pt, ps) { + (Some(a), Some(b)) => to_lbool(self.is_def_eq_core(a, b)), + _ => LBool::Undef, + } + } + + /// One round of `lazy_delta_reduction` before the delta step: the offsets and the `Nat` extension. `Undef` means that the loop goes on. + fn lazy_delta_nat(&mut self, t: ExprId, s: ExprId) -> LBool { + let r = self.is_def_eq_offset(t, s); + if r != LBool::Undef { + return r; + } + let no_fvar = !expr::has_fvar(&self.st, t) && !expr::has_fvar(&self.st, s); + if no_fvar || self.eager { + if let Some(tv) = self.reduce_nat(t) { + return to_lbool(self.is_def_eq_core(tv, s)); + } + if self.bad() { + return LBool::False; + } + if let Some(sv) = self.reduce_nat(s) { + return to_lbool(self.is_def_eq_core(t, sv)); + } + } + LBool::Undef + } + + /// `lazy_delta_reduction`. It returns the result and the last terms, because the caller uses them when the result is `Undef`. + fn lazy_delta_reduction(&mut self, t0: ExprId, s0: ExprId) -> (LBool, ExprId, ExprId) { + let mut t = t0; + let mut s = s0; + let mut r = LBool::Undef; + let mut done = false; + while !done && !self.bad() { + let n = self.lazy_delta_nat(t, s); + if n != LBool::Undef { + r = n; + done = true; + } else { + let (st, t1, s1) = self.lazy_delta_reduction_step(t, s); + t = t1; + s = s1; + match st { + Status::Continue => {} + Status::Unknown => done = true, + Status::Equal => { + r = LBool::True; + done = true; + } + Status::Diff => { + r = LBool::False; + done = true; + } + } + } + } + if self.bad() { + return (LBool::False, t, s); + } + (r, t, s) + } + + /// `lazy_delta_proj_reduction`: `t.i =?= s.i` by lazy unfolding of `t` and `s`. + fn lazy_delta_proj_reduction( + &mut self, + t0: ExprId, + s0: ExprId, + sname: NameId, + idx: u32, + ) -> bool { + let mut t = t0; + let mut s = s0; + let mut st = Status::Continue; + while st == Status::Continue && !self.bad() { + let (r, t1, s1) = self.lazy_delta_reduction_step(t, s); + st = r; + t = t1; + s = s1; + } + if self.bad() { + return false; + } + if st == Status::Equal { + return true; + } + let tp = self.reduce_proj_core(t, sname, idx); + let sp = match tp { + Some(_) => self.reduce_proj_core(s, sname, idx), + None => None, + }; + match (tp, sp) { + (Some(a), Some(b)) => self.is_def_eq_core(a, b), + _ => self.is_def_eq_core(t, s), + } + } + + // The other extensions. + + /// `try_string_lit_expansion_core`. + fn try_string_lit_expansion_core(&mut self, t: ExprId, s: ExprId) -> LBool { + let lit = match self.string_lit(t) { + Some(x) => x, + None => return LBool::Undef, + }; + if !self.is_app(s) || self.app_fn1(s) != self.b.e_string_of_list { + return LBool::Undef; + } + let c = self.string_lit_to_constructor(lit); + let w = self.whnf(c); + to_lbool(self.is_def_eq_core(w, s)) + } + + fn try_string_lit_expansion(&mut self, t: ExprId, s: ExprId) -> LBool { + let r = self.try_string_lit_expansion_core(t, s); + if r != LBool::Undef { + return r; + } + self.try_string_lit_expansion_core(s, t) + } + + /// `is_def_eq_unit_like`: two terms of a structure with one constructor and no fields. + fn is_def_eq_unit_like(&mut self, t: ExprId, s: ExprId) -> bool { + let ty = self.infer(t); + let t_type = self.whnf(ty); + if self.bad() { + return false; + } + let i = expr::app_fn(&self.st, t_type); + let n = match self.st.node(i) { + Expr::Const(n, _) => n, + _ => return false, + }; + if !self.is_non_rec_structure(n, t) { + return false; + } + let c = match self.first_ctor(n, t) { + Some(c) => c, + None => return false, + }; + let cs = self.get_const(c, t); + if cs == 0 { + return false; + } + let nfields = match &self.env.at(cs).kind { + ConstKind::Ctor(k) => k.nfields, + _ => return false, + }; + if nfields != 0 { + return false; + } + let s_type = self.infer(s); + if self.bad() { + return false; + } + self.is_def_eq_core(t_type, s_type) + } + + // The main function. + + /// `is_def_eq_core` with the depth guard. + pub(crate) fn is_def_eq_core(&mut self, t: ExprId, s: ExprId) -> bool { + if self.bad() { + return false; + } + if !self.enter(t) { + return false; + } + let r = self.is_def_eq_core_body(t, s); + self.leave(); + r && !self.bad() + } + + /// The steps of `is_def_eq_core` up to lazy delta reduction. + fn is_def_eq_core_body(&mut self, t: ExprId, s: ExprId) -> bool { + let r = self.quick_is_def_eq(t, s); + if r != LBool::Undef { + return r == LBool::True; + } + // Proofs by reflection: `t =?= Bool.true` with `t` closed. + if (!expr::has_fvar(&self.st, t) || self.eager) + && self.is_constant_named(s, self.b.bool_true) + { + let w = self.whnf(t); + if self.is_constant_named(w, self.b.bool_true) { + return true; + } + } + let t_n = self.whnf_core(t, false, true); + let s_n = self.whnf_core(s, false, true); + if self.bad() { + return false; + } + if t_n != t || s_n != s { + let r = self.quick_is_def_eq(t_n, s_n); + if r != LBool::Undef { + return r == LBool::True; + } + } + let r = self.is_def_eq_proof_irrel(t_n, s_n); + if r != LBool::Undef { + return r == LBool::True; + } + let (r, t_n, s_n) = self.lazy_delta_reduction(t_n, s_n); + if r != LBool::Undef { + return r == LBool::True; + } + self.is_def_eq_whnf(t_n, s_n) + } + + /// The steps of `is_def_eq_core` after lazy delta reduction. + fn is_def_eq_whnf(&mut self, t_n: ExprId, s_n: ExprId) -> bool { + match (self.st.node(t_n), self.st.node(s_n)) { + (Expr::Const(a, la), Expr::Const(b, lb)) => { + if a == b && self.is_def_eq_levels(la, lb) { + return true; + } + } + (Expr::FVar(a, _), Expr::FVar(b, _)) => { + if a == b { + return true; + } + } + (Expr::Proj(a), Expr::Proj(b)) => { + if a.struct_name == b.struct_name + && a.index == b.index + && self.lazy_delta_proj_reduction(a.expr, b.expr, a.struct_name, a.index) + { + return true; + } + } + _ => {} + } + if self.bad() { + return false; + } + let t_nn = self.whnf_core(t_n, false, false); + let s_nn = self.whnf_core(s_n, false, false); + if self.bad() { + return false; + } + if t_nn != t_n || s_nn != s_n { + return self.is_def_eq_core(t_nn, s_nn); + } + if self.is_def_eq_app(t_n, s_n) || self.try_eta_expansion(t_n, s_n) { + return true; + } + if self.try_eta_struct(t_n, s_n) { + return true; + } + let r = self.try_string_lit_expansion(t_n, s_n); + if r != LBool::Undef { + return r == LBool::True; + } + self.is_def_eq_unit_like(t_n, s_n) + } + + /// `is_def_eq`: definitional equality. A true result goes into the success cache. + pub fn is_def_eq(&mut self, t: ExprId, s: ExprId) -> bool { + let r = self.is_def_eq_core(t, s); + if r { + self.pair_put(true, t, s); + } + r + } +} diff --git a/crates/rulean-core/src/env.rs b/crates/rulean-core/src/env.rs new file mode 100644 index 0000000..2eaec12 --- /dev/null +++ b/crates/rulean-core/src/env.rs @@ -0,0 +1,218 @@ +//! The environment: the constants that the checker has added (spec 04.7 and 05.9). +//! +//! The environment is an array indexed by the name handle. The store interns names, so the handles are dense and a lookup is one array access. The fields follow `declaration.h` of the official kernel v4.35.0. + +use alloc::vec::Vec; +use rulean_format::{Hints, QuotKind, Safety}; +use rulean_store::{ExprId, NameId}; + +/// The data of an inductive type (`inductive_val`). +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct InductInfo { + pub nparams: u32, + pub nindices: u32, + /// The names of the types of the mutual block. + pub all: Vec, + pub ctors: Vec, + pub nnested: u32, + pub is_rec: bool, + pub is_reflexive: bool, +} + +/// The data of a constructor (`constructor_val`). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct CtorInfo { + pub induct: NameId, + pub cidx: u32, + pub nparams: u32, + pub nfields: u32, +} + +/// One rule of a recursor (`recursor_rule`). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct RuleInfo { + pub ctor: NameId, + pub nfields: u32, + pub rhs: ExprId, +} + +/// The data of a recursor (`recursor_val`). +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct RecInfo { + pub all: Vec, + pub nparams: u32, + pub nindices: u32, + pub nmotives: u32, + pub nminors: u32, + pub rules: Vec, + pub k: bool, +} + +impl RecInfo { + /// The position of the major premise (`get_major_idx`). + pub fn major_idx(&self) -> u32 { + self.nparams + self.nmotives + self.nminors + self.nindices + } +} + +/// The kind and the kind data of a constant. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum ConstKind { + Axiom, + Defn { value: ExprId, hints: Hints }, + Thm { value: ExprId }, + Opaque { value: ExprId }, + Quot { kind: QuotKind }, + Induct(InductInfo), + Ctor(CtorInfo), + Rec(RecInfo), +} + +/// A constant of the environment (`constant_info`). +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ConstInfo { + pub name: NameId, + pub lparams: Vec, + pub ty: ExprId, + /// The safety. A theorem and a quotient constant are always safe. + pub safety: Safety, + pub kind: ConstKind, +} + +impl ConstInfo { + /// True for an unsafe constant (`is_unsafe`). A partial definition is not unsafe. + pub fn is_unsafe(&self) -> bool { + self.safety == Safety::Unsafe + } + + /// True for a partial definition. + pub fn is_partial_defn(&self) -> bool { + match self.kind { + ConstKind::Defn { .. } => self.safety == Safety::Partial, + _ => false, + } + } + + /// The value of a definition or a theorem (`has_value` and `get_value`). Other constants have no value for reduction. + pub fn value(&self) -> Option { + match self.kind { + ConstKind::Defn { value, .. } => Some(value), + ConstKind::Thm { value } => Some(value), + _ => None, + } + } + + /// The reducibility hint (`get_hints`). A constant that is not a definition is opaque. + pub fn hints(&self) -> Hints { + match self.kind { + ConstKind::Defn { hints, .. } => hints, + _ => Hints::Opaque, + } + } + + /// True for an inductive type. + pub fn is_induct(&self) -> bool { + matches!(self.kind, ConstKind::Induct(_)) + } + + /// True for a constructor. + pub fn is_ctor(&self) -> bool { + matches!(self.kind, ConstKind::Ctor(_)) + } +} + +/// The relative priority of two hints for lazy delta reduction (`compare` of `declaration.cpp`). A negative value means: unfold the first. A positive value means: unfold the second. Zero means: unfold both. +pub fn compare_hints(h1: Hints, h2: Hints) -> i32 { + match (h1, h2) { + (Hints::Regular(a), Hints::Regular(b)) => { + if a == b { + 0 + } else if a > b { + -1 + } else { + 1 + } + } + (Hints::Opaque, Hints::Opaque) => 0, + (Hints::Abbrev, Hints::Abbrev) => 0, + (Hints::Opaque, _) => 1, + (_, Hints::Opaque) => -1, + (Hints::Abbrev, _) => -1, + (_, Hints::Abbrev) => 1, + } +} + +/// The constants of a run. +/// +/// `slot` maps a name handle to the position of its constant plus 1, or to 0. A lookup returns the slot, and `at` gives the constant of a slot. This keeps references out of the return types (subset rule S10). +#[derive(Clone, Debug, Default)] +pub struct Env { + consts: Vec, + slot: Vec, + quot_init: bool, +} + +impl Env { + /// An empty environment. + pub fn new() -> Env { + Env { + consts: Vec::new(), + slot: Vec::new(), + quot_init: false, + } + } + + /// The number of constants. + pub fn len(&self) -> usize { + self.consts.len() + } + + /// True if there is no constant. + pub fn is_empty(&self) -> bool { + self.consts.len() == 0 + } + + /// The slot of the constant with the name, or 0 if there is none (`find`). + pub fn find(&self, n: NameId) -> u32 { + let i = n.0 as usize; + if i < self.slot.len() { self.slot[i] } else { 0 } + } + + /// True if the environment has a constant with the name. + pub fn contains(&self, n: NameId) -> bool { + self.find(n) != 0 + } + + /// The constant of a slot that `find` returned. The slot must not be 0. + pub fn at(&self, s: u32) -> &ConstInfo { + let i = (s - 1) as usize; + &self.consts[i] + } + + /// Adds the constant. A constant with the same name is replaced (`add_core`). The callers check the name first. + pub fn add(&mut self, c: ConstInfo) { + let i = c.name.0 as usize; + while self.slot.len() <= i { + self.slot.push(0); + } + let s = self.slot[i]; + if s == 0 { + self.consts.push(c); + let n = self.consts.len() as u32; + self.slot[i] = n; + } else { + let k = (s - 1) as usize; + self.consts[k] = c; + } + } + + /// True if the quotient constants were added (`is_quot_initialized`). + pub fn quot_initialized(&self) -> bool { + self.quot_init + } + + /// Records that the quotient constants were added. + pub fn mark_quot_initialized(&mut self) { + self.quot_init = true; + } +} diff --git a/crates/rulean-core/src/lib.rs b/crates/rulean-core/src/lib.rs index e6e9e1d..780d8ce 100644 --- a/crates/rulean-core/src/lib.rs +++ b/crates/rulean-core/src/lib.rs @@ -9,6 +9,8 @@ #![allow(clippy::len_zero)] // `Option` combinators and `?` are outside the subset, so the code matches by hand. #![allow(clippy::collapsible_if)] +#![allow(clippy::collapsible_match)] +#![allow(clippy::question_mark)] #![allow(clippy::comparison_chain)] // `Vec::clear`, `slice::swap` and `checked_sub` are outside the modelled functions too. #![allow(clippy::manual_clear)] @@ -17,6 +19,10 @@ extern crate alloc; +pub mod defeq; +pub mod env; pub mod expr; pub mod level; pub mod memo; +pub mod tc; +pub mod whnf; diff --git a/crates/rulean-core/src/tc.rs b/crates/rulean-core/src/tc.rs new file mode 100644 index 0000000..f831e76 --- /dev/null +++ b/crates/rulean-core/src/tc.rs @@ -0,0 +1,1056 @@ +//! Engine R: the reference transcription of the type checker (spec 05.5). +//! +//! This module has the state of the checker, the local context and type inference. It is a transcription of `type_checker.cpp` and `local_ctx.cpp` of the official kernel v4.35.0. `whnf.rs` has the reduction functions and `defeq.rs` has definitional equality. Each function has the name of the official function. +//! +//! The official kernel throws a C++ exception on an error. Here an error sets a sticky fault: the first fault is kept, the functions return a dummy value after it, and each caller checks `bad` before it uses a result. So the first error is the error that the official kernel throws. +//! +//! A free variable is the store node `FVar(level, type)`. The level is a counter for each declaration, so a level is never used twice in a declaration. The caches are cleared for each declaration, as the official kernel makes a new `type_checker` for each declaration. + +use alloc::vec::Vec; +use rulean_format::Safety; +use rulean_nat::Nat; +use rulean_store::{BinderInfo, Expr, ExprId, LevelId, Literal, NameId, Store}; + +use crate::env::{ConstKind, Env}; +use crate::expr::{self, Scratch}; +use crate::level::{self, LevelCache}; +use crate::memo::Memo; + +/// The upper bound in bytes of a `Nat` literal (`LEAN_NAT_MAX_SIZE_DEFAULT`). This is semantics and not a resource limit (spec 05.11). +pub const NAT_MAX_BYTES: u64 = 128 * 1024 * 1024; + +/// The default bound of the call depth: 4 times 16 times the default `maxRecDepth` of 512 (spec 05.5 and 05.11). +pub const MAX_DEPTH: u32 = 4 * 16 * 512; + +/// The kind of an error. Each kind is one exception of `kernel_exception.h` or one message of `type_checker.cpp`. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ErrorKind { + /// "type checker does not support loose bound variables". + LooseBVar, + /// "unknown constant" (`environment::get`). + UnknownConst, + /// "unknown free variable". + UnknownFVar, + /// "incorrect number of universe levels parameters". + LevelCount, + /// "invalid declaration, it uses unsafe declaration". + UnsafeUse, + /// "safe declaration must not contain partial declaration". + PartialUse, + /// "invalid reference to undefined universe level parameter". + UndefLevelParam, + /// `type_expected_exception`. + TypeExpected, + /// `function_expected_exception`. + FunctionExpected, + /// `app_type_mismatch_exception`. + AppTypeMismatch, + /// `def_type_mismatch_exception` of a `let` or of a declaration. + DefTypeMismatch, + /// `invalid_proj_exception`. + InvalidProj, + /// "the kernel refused a `Nat` numeral because its size exceeds the maximum". + NatTooLarge, + /// "its second argument does not fit in a 32-bit unsigned integer". + CountTooLarge, + /// The call depth is above the bound. This is a resource failure and not a verdict (spec 05.11). + DeepRecursion, + /// A constant of the environment does not have the expected kind. The official kernel fails with an assertion here. + BadConst, +} + +/// The first error of a declaration. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Fault { + pub kind: ErrorKind, + /// The term where the error was found. + pub at: ExprId, +} + +/// The binary `Nat` operations of `reduce_nat`, in the order of the `nat_ops` table. +pub(crate) const NAT_ADD: usize = 0; +pub(crate) const NAT_SUB: usize = 1; +pub(crate) const NAT_MUL: usize = 2; +pub(crate) const NAT_POW: usize = 3; +pub(crate) const NAT_GCD: usize = 4; +pub(crate) const NAT_MOD: usize = 5; +pub(crate) const NAT_DIV: usize = 6; +pub(crate) const NAT_BEQ: usize = 7; +pub(crate) const NAT_BLE: usize = 8; +pub(crate) const NAT_LAND: usize = 9; +pub(crate) const NAT_LOR: usize = 10; +pub(crate) const NAT_XOR: usize = 11; +pub(crate) const NAT_SHL: usize = 12; +pub(crate) const NAT_SHR: usize = 13; + +/// The names and the constant terms that the kernel knows by name. +#[derive(Clone, Debug)] +pub struct Builtins { + pub nat: NameId, + pub nat_zero: NameId, + pub nat_succ: NameId, + pub string: NameId, + pub string_of_list: NameId, + pub char_: NameId, + pub char_of_nat: NameId, + pub list_nil: NameId, + pub list_cons: NameId, + pub bool_true: NameId, + pub bool_false: NameId, + pub eager_reduce: NameId, + pub quot: NameId, + pub quot_mk: NameId, + pub quot_lift: NameId, + pub quot_ind: NameId, + pub eq: NameId, + /// `Nat`, `String`, `Nat.zero`, `Nat.succ`, `Bool.true`, `Bool.false` and `String.ofList` as constants with no levels. + pub e_nat: ExprId, + pub e_string: ExprId, + pub e_nat_zero: ExprId, + pub e_nat_succ: ExprId, + pub e_bool_true: ExprId, + pub e_bool_false: ExprId, + pub e_string_of_list: ExprId, + /// `Char.ofNat`, `List.cons.{0} Char` and `List.nil.{0} Char`. + pub e_char_of_nat: ExprId, + pub e_list_cons_char: ExprId, + pub e_list_nil_char: ExprId, + /// The binary operations of `reduce_nat` as constants with no levels, in the order of the `NAT_*` indices. + pub nat_ops: Vec, +} + +fn name2(st: &mut Store, a: &[u8], b: &[u8]) -> NameId { + let r = st.anon(); + let p = st.name_str_bytes(r, a); + st.name_str_bytes(p, b) +} + +fn name1(st: &mut Store, a: &[u8]) -> NameId { + let r = st.anon(); + st.name_str_bytes(r, a) +} + +fn nat_op(st: &mut Store, out: &mut Vec, op: &[u8]) { + let n = name2(st, b"Nat", op); + let c = const0(st, n); + out.push(c); +} + +fn const0(st: &mut Store, n: NameId) -> ExprId { + let ls = st.level_list_empty(); + st.mk_const(n, ls) +} + +impl Builtins { + /// Interns the names and the terms. + pub fn new(st: &mut Store) -> Builtins { + let nat = name1(st, b"Nat"); + let nat_zero = name2(st, b"Nat", b"zero"); + let nat_succ = name2(st, b"Nat", b"succ"); + let string = name1(st, b"String"); + let string_of_list = name2(st, b"String", b"ofList"); + let char_ = name1(st, b"Char"); + let char_of_nat = name2(st, b"Char", b"ofNat"); + let list_nil = name2(st, b"List", b"nil"); + let list_cons = name2(st, b"List", b"cons"); + let bool_true = name2(st, b"Bool", b"true"); + let bool_false = name2(st, b"Bool", b"false"); + let eager_reduce = name1(st, b"eagerReduce"); + let quot = name1(st, b"Quot"); + let quot_mk = name2(st, b"Quot", b"mk"); + let quot_lift = name2(st, b"Quot", b"lift"); + let quot_ind = name2(st, b"Quot", b"ind"); + let eq = name1(st, b"Eq"); + let e_nat = const0(st, nat); + let e_string = const0(st, string); + let e_nat_zero = const0(st, nat_zero); + let e_nat_succ = const0(st, nat_succ); + let e_bool_true = const0(st, bool_true); + let e_bool_false = const0(st, bool_false); + let e_string_of_list = const0(st, string_of_list); + let e_char_of_nat = const0(st, char_of_nat); + let e_char = const0(st, char_); + let z = st.level_zero(); + let l0 = st.level_list(&[z]); + let cons = st.mk_const(list_cons, l0); + let e_list_cons_char = st.mk_app(cons, e_char); + let nil = st.mk_const(list_nil, l0); + let e_list_nil_char = st.mk_app(nil, e_char); + let mut nat_ops = Vec::with_capacity(14); + nat_op(st, &mut nat_ops, b"add"); + nat_op(st, &mut nat_ops, b"sub"); + nat_op(st, &mut nat_ops, b"mul"); + nat_op(st, &mut nat_ops, b"pow"); + nat_op(st, &mut nat_ops, b"gcd"); + nat_op(st, &mut nat_ops, b"mod"); + nat_op(st, &mut nat_ops, b"div"); + nat_op(st, &mut nat_ops, b"beq"); + nat_op(st, &mut nat_ops, b"ble"); + nat_op(st, &mut nat_ops, b"land"); + nat_op(st, &mut nat_ops, b"lor"); + nat_op(st, &mut nat_ops, b"xor"); + nat_op(st, &mut nat_ops, b"shiftLeft"); + nat_op(st, &mut nat_ops, b"shiftRight"); + Builtins { + nat, + nat_zero, + nat_succ, + string, + string_of_list, + char_, + char_of_nat, + list_nil, + list_cons, + bool_true, + bool_false, + eager_reduce, + quot, + quot_mk, + quot_lift, + quot_ind, + eq, + e_nat, + e_string, + e_nat_zero, + e_nat_succ, + e_bool_true, + e_bool_false, + e_string_of_list, + e_char_of_nat, + e_list_cons_char, + e_list_nil_char, + nat_ops, + } + } +} + +/// A three-valued result (`lbool`). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum LBool { + True, + False, + Undef, +} + +pub(crate) fn to_lbool(b: bool) -> LBool { + if b { LBool::True } else { LBool::False } +} + +/// The type checker of engine R. +#[derive(Debug)] +pub struct Checker { + pub st: Store, + pub env: Env, + pub b: Builtins, + pub(crate) lc: LevelCache, + pub(crate) x: Scratch, + /// The level parameters of the declaration (`m_lparams`). They are checked only if `check_lparams` is true. + pub(crate) lparams: Vec, + pub(crate) check_lparams: bool, + /// The safety of the declaration (`m_definition_safety`). + pub(crate) safety: Safety, + // The local context, indexed by the level of the free variable. + pub(crate) lctx_name: Vec, + pub(crate) lctx_info: Vec, + pub(crate) lctx_ty: Vec, + pub(crate) lctx_val: Vec>, + // The caches of `type_checker::state`. `infer` has the mode in the second key. + pub(crate) c_infer: Memo, + pub(crate) c_whnf_core: Memo, + pub(crate) c_whnf: Memo, + pub(crate) c_unfold: Memo, + pub(crate) c_success: Memo, + pub(crate) c_failure: Memo, + /// `m_eager_reduce`. + pub(crate) eager: bool, + pub(crate) depth: u32, + pub max_depth: u32, + pub(crate) fault: Option, + /// The value that a function returns after a fault. + pub(crate) dummy: ExprId, +} + +impl Checker { + /// A checker over the store, with an empty environment. + pub fn new(st: Store) -> Checker { + let mut st = st; + let b = Builtins::new(&mut st); + let dummy = b.e_nat_zero; + Checker { + st, + env: Env::new(), + b, + lc: LevelCache::new(), + x: Scratch::new(), + lparams: Vec::new(), + check_lparams: false, + safety: Safety::Safe, + lctx_name: Vec::new(), + lctx_info: Vec::new(), + lctx_ty: Vec::new(), + lctx_val: Vec::new(), + c_infer: Memo::new(), + c_whnf_core: Memo::new(), + c_whnf: Memo::new(), + c_unfold: Memo::new(), + c_success: Memo::new(), + c_failure: Memo::new(), + eager: false, + depth: 0, + max_depth: MAX_DEPTH, + fault: None, + dummy, + } + } + + /// Starts a declaration: clears the caches, the local context and the fault, and sets the level parameters and the safety (`type_checker(env, lctx, safety)`). + pub fn begin(&mut self, lparams: Vec, safety: Safety) { + self.lparams = lparams; + self.check_lparams = true; + self.safety = safety; + self.lctx_name.truncate(0); + self.lctx_info.truncate(0); + self.lctx_ty.truncate(0); + self.lctx_val.truncate(0); + self.c_infer.clear(); + self.c_whnf_core.clear(); + self.c_whnf.clear(); + self.c_unfold.clear(); + self.c_success.clear(); + self.c_failure.clear(); + self.eager = false; + self.depth = 0; + self.fault = None; + } + + /// The first error since `begin`, if any. + pub fn fault(&self) -> Option { + self.fault + } + + /// True if there is a fault. + pub fn bad(&self) -> bool { + self.fault.is_some() + } + + /// Records an error and returns the dummy value. Only the first error is kept. + pub(crate) fn fail(&mut self, kind: ErrorKind, at: ExprId) -> ExprId { + if self.fault.is_none() { + self.fault = Some(Fault { kind, at }); + } + self.dummy + } + + /// Counts one call level (`scope_rec_depth`). It gives false and records a fault if the depth is above the bound. + pub(crate) fn enter(&mut self, at: ExprId) -> bool { + if self.bad() { + return false; + } + if self.depth >= self.max_depth { + self.fail(ErrorKind::DeepRecursion, at); + return false; + } + self.depth += 1; + true + } + + pub(crate) fn leave(&mut self) { + if self.depth > 0 { + self.depth -= 1; + } + } + + // The local context. + + /// Adds a local declaration and returns its free variable (`mk_local_decl`). + pub(crate) fn mk_local( + &mut self, + name: NameId, + info: BinderInfo, + ty: ExprId, + val: Option, + ) -> ExprId { + let lvl = self.lctx_ty.len() as u32; + self.lctx_name.push(name); + self.lctx_info.push(info); + self.lctx_ty.push(ty); + self.lctx_val.push(val); + self.st.mk_fvar(lvl, ty) + } + + /// The value of a `let` free variable, if any. + pub(crate) fn fvar_value(&self, lvl: u32) -> Option { + let i = lvl as usize; + if i < self.lctx_val.len() { + self.lctx_val[i] + } else { + None + } + } + + /// True if `e` is a free variable with a value (`is_let_fvar`). + pub(crate) fn is_let_fvar(&self, e: ExprId) -> bool { + match self.st.node(e) { + Expr::FVar(lvl, _) => self.fvar_value(lvl).is_some(), + _ => false, + } + } + + /// Abstracts the free variables of `b` and binds them, from the last one to the first one (`local_ctx::mk_binding`). + pub(crate) fn mk_binding( + &mut self, + fvars: &[ExprId], + b: ExprId, + is_lambda: bool, + remove_dead_let: bool, + ) -> ExprId { + let mut r = expr::abstract_fvars(&mut self.st, &mut self.x, b, fvars); + let mut i = fvars.len(); + while i > 0 { + i -= 1; + let lvl = match self.st.node(fvars[i]) { + Expr::FVar(l, _) => l as usize, + _ => 0, + }; + let name = self.lctx_name[lvl]; + let info = self.lctx_info[lvl]; + let ty0 = self.lctx_ty[lvl]; + let ty = expr::abstract_fvars(&mut self.st, &mut self.x, ty0, &fvars[..i]); + match self.lctx_val[lvl] { + Some(v0) => { + if !remove_dead_let || expr::has_loose_bvar(&self.st, &mut self.x, r, 0) { + let v = expr::abstract_fvars(&mut self.st, &mut self.x, v0, &fvars[..i]); + r = self.st.mk_let(name, ty, v, r); + } else { + r = expr::lower_loose_bvars(&mut self.st, &mut self.x, r, 1, 1); + } + } + None => { + if is_lambda { + r = self.st.mk_lam(name, info, ty, r); + } else { + r = self.st.mk_pi(name, info, ty, r); + } + } + } + } + r + } + + // Helpers for terms. + + pub(crate) fn sort_level(&self, e: ExprId) -> LevelId { + match self.st.node(e) { + Expr::Sort(l) => l, + _ => self.st.level_zero(), + } + } + + pub(crate) fn is_sort(&self, e: ExprId) -> bool { + matches!(self.st.node(e), Expr::Sort(_)) + } + + pub(crate) fn is_pi(&self, e: ExprId) -> bool { + matches!(self.st.node(e), Expr::Pi(_)) + } + + pub(crate) fn is_lambda(&self, e: ExprId) -> bool { + matches!(self.st.node(e), Expr::Lam(_)) + } + + pub(crate) fn is_app(&self, e: ExprId) -> bool { + matches!(self.st.node(e), Expr::App(_, _)) + } + + /// The name of a constant, or the anonymous name. + pub(crate) fn const_name(&self, e: ExprId) -> NameId { + match self.st.node(e) { + Expr::Const(n, _) => n, + _ => self.st.anon(), + } + } + + pub(crate) fn is_constant(&self, e: ExprId) -> bool { + matches!(self.st.node(e), Expr::Const(_, _)) + } + + /// True if `e` is the constant `n` with any levels (`is_constant(e, n)`). + pub(crate) fn is_constant_named(&self, e: ExprId, n: NameId) -> bool { + match self.st.node(e) { + Expr::Const(m, _) => m == n, + _ => false, + } + } + + /// The argument of an application, or `e`. + pub(crate) fn app_arg(&self, e: ExprId) -> ExprId { + match self.st.node(e) { + Expr::App(_, a) => a, + _ => e, + } + } + + /// The function of an application, or `e`. + pub(crate) fn app_fn1(&self, e: ExprId) -> ExprId { + match self.st.node(e) { + Expr::App(f, _) => f, + _ => e, + } + } + + /// The domain and the body of a binder, or `e` twice. + pub(crate) fn binding(&self, e: ExprId) -> (ExprId, ExprId) { + match self.st.node(e) { + Expr::Pi(b) => (b.dom, b.body), + Expr::Lam(b) => (b.dom, b.body), + _ => (e, e), + } + } + + /// The alpha-equality of the official kernel (`operator==` on `expr`). + pub(crate) fn eq(&mut self, a: ExprId, b: ExprId) -> bool { + expr::expr_equal(&self.st, &mut self.x, a, b) + } + + pub(crate) fn instantiate1(&mut self, e: ExprId, v: ExprId) -> ExprId { + expr::instantiate1(&mut self.st, &mut self.x, e, v) + } + + pub(crate) fn instantiate_rev(&mut self, e: ExprId, subst: &[ExprId]) -> ExprId { + expr::instantiate_rev(&mut self.st, &mut self.x, e, subst) + } + + /// The level parameters of the constant of a slot, as a vector. + pub(crate) fn const_lparams(&self, slot: u32) -> Vec { + self.env.at(slot).lparams.clone() + } + + /// The type of the constant of the slot with the levels for its parameters (`instantiate_type_lparams`). + pub(crate) fn instantiate_type_lparams(&mut self, slot: u32, ls: &[LevelId]) -> ExprId { + let c = self.env.at(slot); + let ty = c.ty; + expr::instantiate_lparams(&mut self.st, &mut self.x, ty, &c.lparams, ls) + } + + /// The value of the constant of the slot with the levels for its parameters (`instantiate_value_lparams`). + pub(crate) fn instantiate_value_lparams(&mut self, slot: u32, ls: &[LevelId]) -> ExprId { + let c = self.env.at(slot); + let v = match c.value() { + Some(v) => v, + None => self.dummy, + }; + expr::instantiate_lparams(&mut self.st, &mut self.x, v, &c.lparams, ls) + } + + /// The slot of the constant, or a fault (`environment::get`). + pub(crate) fn get_const(&mut self, n: NameId, at: ExprId) -> u32 { + let s = self.env.find(n); + if s == 0 { + self.fail(ErrorKind::UnknownConst, at); + } + s + } + + /// The byte size of a `Nat` value for the size guard (`lean_nat_size_in_bytes`): 8 bytes for each 64-bit limb. + pub(crate) fn nat_size(v: &Nat) -> u64 { + let n = v.limb_count() as u64; + if n == 0 { 8 } else { n * 8 } + } + + /// Records a fault if the size is above the bound (`check_nat_size`). It gives true if the size is in the bound. + pub(crate) fn check_nat_size(&mut self, bytes: u64, at: ExprId) -> bool { + if bytes > NAT_MAX_BYTES { + self.fail(ErrorKind::NatTooLarge, at); + return false; + } + true + } + + // Inference. + + /// `ensure_sort_core`. + pub(crate) fn ensure_sort_core(&mut self, e: ExprId, s: ExprId) -> ExprId { + if self.bad() || self.is_sort(e) { + return e; + } + let new_e = self.whnf(e); + if self.bad() || self.is_sort(new_e) { + new_e + } else { + self.fail(ErrorKind::TypeExpected, s) + } + } + + /// `ensure_pi_core`. + pub(crate) fn ensure_pi_core(&mut self, e: ExprId, s: ExprId) -> ExprId { + if self.bad() || self.is_pi(e) { + return e; + } + let new_e = self.whnf(e); + if self.bad() || self.is_pi(new_e) { + new_e + } else { + self.fail(ErrorKind::FunctionExpected, s) + } + } + + /// `check_level`. + pub(crate) fn check_level(&mut self, l: LevelId, at: ExprId) { + if self.check_lparams && level::undef_param(&self.st, l, &self.lparams) != 0 { + self.fail(ErrorKind::UndefLevelParam, at); + } + } + + /// `infer_fvar`. + fn infer_fvar(&mut self, e: ExprId, lvl: u32, ty: ExprId) -> ExprId { + if (lvl as usize) < self.lctx_ty.len() { + ty + } else { + self.fail(ErrorKind::UnknownFVar, e) + } + } + + /// `infer_constant`. + fn infer_constant(&mut self, e: ExprId, infer_only: bool) -> ExprId { + let (n, list) = match self.st.node(e) { + Expr::Const(n, list) => (n, list), + _ => return self.fail(ErrorKind::BadConst, e), + }; + let slot = self.get_const(n, e); + if slot == 0 { + return self.dummy; + } + let ls = self.st.level_list_vec(list); + let c = self.env.at(slot); + if c.lparams.len() != ls.len() { + return self.fail(ErrorKind::LevelCount, e); + } + if !infer_only { + let c = self.env.at(slot); + if c.is_unsafe() && self.safety != Safety::Unsafe { + return self.fail(ErrorKind::UnsafeUse, e); + } + if c.is_partial_defn() && self.safety == Safety::Safe { + return self.fail(ErrorKind::PartialUse, e); + } + let mut i = 0; + while i < ls.len() { + self.check_level(ls[i], e); + i += 1; + } + if self.bad() { + return self.dummy; + } + } + self.instantiate_type_lparams(slot, &ls) + } + + /// `infer_lambda`. + fn infer_lambda(&mut self, e0: ExprId, infer_only: bool) -> ExprId { + let mut fvars: Vec = Vec::new(); + let mut e = e0; + let mut walking = true; + while walking && !self.bad() { + match self.st.node(e) { + Expr::Lam(b) => { + let d = self.instantiate_rev(b.dom, &fvars); + if !infer_only { + let t = self.infer_type_core(d, infer_only); + self.ensure_sort_core(t, d); + } + let fv = self.mk_local(b.name, b.info, d, None); + fvars.push(fv); + e = b.body; + } + _ => walking = false, + } + } + if self.bad() { + return self.dummy; + } + let body = self.instantiate_rev(e, &fvars); + let r = self.infer_type_core(body, infer_only); + if self.bad() { + return self.dummy; + } + let r = expr::cheap_beta_reduce(&mut self.st, r); + self.mk_binding(&fvars, r, false, false) + } + + /// `infer_pi`. + fn infer_pi(&mut self, e0: ExprId, infer_only: bool) -> ExprId { + let mut fvars: Vec = Vec::new(); + let mut us: Vec = Vec::new(); + let mut e = e0; + let mut walking = true; + while walking && !self.bad() { + match self.st.node(e) { + Expr::Pi(b) => { + let d = self.instantiate_rev(b.dom, &fvars); + let t = self.infer_type_core(d, infer_only); + let t1 = self.ensure_sort_core(t, d); + let u = self.sort_level(t1); + us.push(u); + let fv = self.mk_local(b.name, b.info, d, None); + fvars.push(fv); + e = b.body; + } + _ => walking = false, + } + } + if self.bad() { + return self.dummy; + } + let body = self.instantiate_rev(e, &fvars); + let t = self.infer_type_core(body, infer_only); + let s = self.ensure_sort_core(t, body); + if self.bad() { + return self.dummy; + } + let mut r = self.sort_level(s); + let mut i = us.len(); + while i > 0 { + i -= 1; + r = level::mk_imax(&mut self.st, us[i], r); + } + self.st.mk_sort(r) + } + + /// True if `e` is `eagerReduce _ _` (`is_eager_reduce`). + fn is_eager_reduce(&self, e: ExprId) -> bool { + let f = expr::app_fn(&self.st, e); + self.is_constant_named(f, self.b.eager_reduce) && expr::app_num_args(&self.st, e) == 2 + } + + /// `infer_app`. + fn infer_app(&mut self, e: ExprId, infer_only: bool) -> ExprId { + if !infer_only { + let (f, a) = match self.st.node(e) { + Expr::App(f, a) => (f, a), + _ => return self.fail(ErrorKind::BadConst, e), + }; + let ft0 = self.infer_type_core(f, infer_only); + let f_type = self.ensure_pi_core(ft0, e); + let a_type = self.infer_type_core(a, infer_only); + if self.bad() { + return self.dummy; + } + let (d_type, body) = self.binding(f_type); + let saved = self.eager; + if self.is_eager_reduce(a) { + self.eager = true; + } + let ok = self.is_def_eq(a_type, d_type); + self.eager = saved; + if self.bad() { + return self.dummy; + } + if !ok { + return self.fail(ErrorKind::AppTypeMismatch, e); + } + self.instantiate1(body, a) + } else { + self.infer_app_only(e) + } + } + + /// The infer-only branch of `infer_app`. It instantiates the arguments in chunks. + fn infer_app_only(&mut self, e: ExprId) -> ExprId { + let mut args: Vec = Vec::new(); + let f = expr::app_args(&self.st, e, &mut args); + let mut f_type = self.infer_type_core(f, true); + let mut j = 0; + let nargs = args.len(); + let mut i = 0; + while i < nargs && !self.bad() { + let (t, k) = self.app_only_step(e, f_type, &args, j, i); + f_type = t; + j = k; + i += 1; + } + if self.bad() { + return self.dummy; + } + self.instantiate_rev(f_type, &args[j..nargs]) + } + + /// One step of `infer_app_only`. It gives the new function type and the new start of the chunk. + fn app_only_step( + &mut self, + e: ExprId, + f_type: ExprId, + args: &[ExprId], + j: usize, + i: usize, + ) -> (ExprId, usize) { + match self.st.node(f_type) { + Expr::Pi(b) => (b.body, j), + _ => { + let t = self.instantiate_rev(f_type, &args[j..i]); + let t = self.ensure_pi_core(t, e); + let (_, body) = self.binding(t); + (body, i) + } + } + } + + /// `infer_let`. + fn infer_let(&mut self, e0: ExprId, infer_only: bool) -> ExprId { + let mut fvars: Vec = Vec::new(); + let mut e = e0; + let mut walking = true; + while walking && !self.bad() { + match self.st.node(e) { + Expr::Let(l) => { + let ty = self.instantiate_rev(l.ty, &fvars); + let val = self.instantiate_rev(l.value, &fvars); + if !infer_only { + let t = self.infer_type_core(ty, infer_only); + self.ensure_sort_core(t, ty); + let vt = self.infer_type_core(val, infer_only); + if !self.bad() && !self.is_def_eq(vt, ty) && !self.bad() { + self.fail(ErrorKind::DefTypeMismatch, e); + } + } + let fv = self.mk_local(l.name, BinderInfo::Default, ty, Some(val)); + fvars.push(fv); + e = l.body; + } + _ => walking = false, + } + } + if self.bad() { + return self.dummy; + } + let body = self.instantiate_rev(e, &fvars); + let r = self.infer_type_core(body, infer_only); + if self.bad() { + return self.dummy; + } + let r = expr::cheap_beta_reduce(&mut self.st, r); + self.mk_binding(&fvars, r, false, true) + } + + /// The data of the inductive type of a slot that `infer_proj` needs: the number of parameters, the number of indices, the number of constructors and the first constructor. + fn induct_shape(&self, slot: u32) -> Option<(u32, u32, usize, NameId)> { + let anon = self.st.anon(); + match &self.env.at(slot).kind { + ConstKind::Induct(i) => Some(induct_data(i, anon)), + _ => None, + } + } + + /// `infer_proj`. + fn infer_proj(&mut self, e: ExprId, infer_only: bool) -> ExprId { + let (sname, idx, c) = match self.st.node(e) { + Expr::Proj(p) => (p.struct_name, p.index, p.expr), + _ => return self.fail(ErrorKind::BadConst, e), + }; + let t0 = self.infer_type_core(c, infer_only); + let ty = self.whnf(t0); + if self.bad() { + return self.dummy; + } + let mut args: Vec = Vec::new(); + let i_fn = expr::app_args(&self.st, ty, &mut args); + let (i_name, i_levels) = match self.st.node(i_fn) { + Expr::Const(n, ls) => (n, ls), + _ => return self.fail(ErrorKind::InvalidProj, e), + }; + if i_name != sname { + return self.fail(ErrorKind::InvalidProj, e); + } + let i_slot = self.get_const(i_name, e); + if i_slot == 0 { + return self.dummy; + } + let (nparams, nindices, nctors, ctor) = match self.induct_shape(i_slot) { + Some(x) => x, + None => return self.fail(ErrorKind::InvalidProj, e), + }; + if nctors != 1 || args.len() != (nparams + nindices) as usize { + return self.fail(ErrorKind::InvalidProj, e); + } + let c_slot = self.get_const(ctor, e); + if c_slot == 0 { + return self.dummy; + } + let ls = self.st.level_list_vec(i_levels); + let mut r = self.instantiate_type_lparams(c_slot, &ls); + let mut i = 0; + while i < nparams as usize && !self.bad() { + r = self.whnf(r); + match self.st.node(r) { + Expr::Pi(b) => r = self.instantiate1(b.body, args[i]), + _ => { + self.fail(ErrorKind::InvalidProj, e); + } + } + i += 1; + } + if self.bad() { + return self.dummy; + } + let is_prop_type = self.is_prop(ty); + self.infer_proj_fields(e, i_name, idx, c, r, is_prop_type) + } + + /// The field loop of `infer_proj`. + fn infer_proj_fields( + &mut self, + e: ExprId, + i_name: NameId, + idx: u32, + c: ExprId, + r0: ExprId, + is_prop_type: bool, + ) -> ExprId { + let mut r = r0; + let mut i = 0; + while i < idx && !self.bad() { + r = self.whnf(r); + match self.st.node(r) { + Expr::Pi(b) => { + if expr::has_loose_bvars(&self.st, b.body) { + if is_prop_type && !self.is_prop(b.dom) && !self.bad() { + self.fail(ErrorKind::InvalidProj, e); + } + let p = self.st.mk_proj(i_name, i, c); + r = self.instantiate1(b.body, p); + } else { + r = b.body; + } + } + _ => { + self.fail(ErrorKind::InvalidProj, e); + } + } + i += 1; + } + if self.bad() { + return self.dummy; + } + r = self.whnf(r); + let d = match self.st.node(r) { + Expr::Pi(b) => b.dom, + _ => return self.fail(ErrorKind::InvalidProj, e), + }; + if is_prop_type && !self.is_prop(d) && !self.bad() { + return self.fail(ErrorKind::InvalidProj, e); + } + d + } + + /// `infer_lit`. + fn infer_lit(&mut self, e: ExprId, l: Literal) -> ExprId { + match l { + Literal::Nat(n) => { + let bytes = Checker::nat_size(self.st.nat(n)); + self.check_nat_size(bytes, e); + self.b.e_nat + } + Literal::Str(_) => self.b.e_string, + } + } + + /// `infer_type_core`. The result is cached with the mode. + pub(crate) fn infer_type_core(&mut self, e: ExprId, infer_only: bool) -> ExprId { + if self.bad() { + return self.dummy; + } + if expr::has_loose_bvars(&self.st, e) { + return self.fail(ErrorKind::LooseBVar, e); + } + if !self.enter(e) { + return self.dummy; + } + let mode = infer_only as u32; + let r = match self.c_infer.get(e.0, mode) { + Some(r) => ExprId(r), + None => { + let r = self.infer_type_node(e, infer_only); + if !self.bad() { + self.c_infer.put(e.0, mode, r.0); + } + r + } + }; + self.leave(); + r + } + + fn infer_type_node(&mut self, e: ExprId, infer_only: bool) -> ExprId { + match self.st.node(e) { + Expr::Lit(l) => self.infer_lit(e, l), + Expr::Proj(_) => self.infer_proj(e, infer_only), + Expr::FVar(lvl, ty) => self.infer_fvar(e, lvl, ty), + Expr::BVar(_) => self.fail(ErrorKind::LooseBVar, e), + Expr::Sort(l) => { + if !infer_only { + self.check_level(l, e); + } + let s = self.st.level_succ(l); + self.st.mk_sort(s) + } + Expr::Const(_, _) => self.infer_constant(e, infer_only), + Expr::Lam(_) => self.infer_lambda(e, infer_only), + Expr::Pi(_) => self.infer_pi(e, infer_only), + Expr::App(_, _) => self.infer_app(e, infer_only), + Expr::Let(_) => self.infer_let(e, infer_only), + } + } + + /// `infer_type`: inference without checks. + pub fn infer(&mut self, e: ExprId) -> ExprId { + self.infer_type_core(e, true) + } + + /// `check`: inference with all checks, with the level parameters of the declaration. + pub fn check(&mut self, e: ExprId) -> ExprId { + let saved = self.check_lparams; + self.check_lparams = true; + let r = self.infer_type_core(e, false); + self.check_lparams = saved; + r + } + + /// `check_ignore_undefined_universes`. + pub fn check_ignore_undefined_universes(&mut self, e: ExprId) -> ExprId { + let saved = self.check_lparams; + self.check_lparams = false; + let r = self.infer_type_core(e, false); + self.check_lparams = saved; + r + } + + /// `ensure_sort`. + pub fn ensure_sort(&mut self, e: ExprId, s: ExprId) -> ExprId { + self.ensure_sort_core(e, s) + } + + /// `ensure_pi`. + pub fn ensure_pi(&mut self, e: ExprId, s: ExprId) -> ExprId { + self.ensure_pi_core(e, s) + } + + /// `is_prop`: the type of `e` is a sort whose level normalizes to zero. + pub fn is_prop(&mut self, e: ExprId) -> bool { + let t = self.infer(e); + let s = self.ensure_sort(t, e); + if self.bad() { + return false; + } + let l = self.sort_level(s); + level::normalizes_to_zero(&self.st, l) + } +} + +/// The number of parameters, the number of indices, the number of constructors and the first constructor of an inductive type. If there is no constructor, the first constructor is `anon`. +fn induct_data(i: &crate::env::InductInfo, anon: NameId) -> (u32, u32, usize, NameId) { + let n = i.ctors.len(); + let mut first = anon; + if n > 0 { + first = i.ctors[0]; + } + (i.nparams, i.nindices, n, first) +} diff --git a/crates/rulean-core/src/whnf.rs b/crates/rulean-core/src/whnf.rs new file mode 100644 index 0000000..3021cb4 --- /dev/null +++ b/crates/rulean-core/src/whnf.rs @@ -0,0 +1,856 @@ +//! Engine R: weak head normal form (spec 05.5 and 05.8). +//! +//! This module is a transcription of the reduction part of `type_checker.cpp`, of `inductive_reduce_rec` and its helpers in `inductive.h` and `inductive.cpp`, and of `quot_reduce_rec` in `quot.h`, of the official kernel v4.35.0. + +use alloc::vec::Vec; +use rulean_format::Hints; +use rulean_nat::Nat; +use rulean_store::{Expr, ExprId, Literal, NameId}; + +use crate::env::{ConstKind, RuleInfo}; +use crate::expr; +use crate::tc::{ + Checker, ErrorKind, NAT_ADD, NAT_BEQ, NAT_BLE, NAT_DIV, NAT_GCD, NAT_LAND, NAT_LOR, NAT_MOD, + NAT_MUL, NAT_POW, NAT_SHL, NAT_SHR, NAT_SUB, NAT_XOR, +}; + +/// The data of a recursor that `inductive_reduce_rec` needs. +#[derive(Clone, Copy)] +struct RecShape { + major_idx: u32, + /// The number of parameters, motives and minor premises. + nprefix: u32, + nparams: u32, + k: bool, +} + +/// Decodes UTF-8 bytes into code points (`utf8_decode`). The parser has checked the bytes, so a bad sequence does not occur. A bad byte gives its own value. +pub fn utf8_decode(b: &[u8]) -> Vec { + let mut out: Vec = Vec::with_capacity(b.len()); + let mut i = 0; + while i < b.len() { + let c = b[i] as u32; + let (n, first) = if c < 0x80 { + (0, c) + } else if c >= 0xf0 { + (3, c & 0x07) + } else if c >= 0xe0 { + (2, c & 0x0f) + } else if c >= 0xc0 { + (1, c & 0x1f) + } else { + (0, c) + }; + let mut v = first; + let mut k = 0; + while k < n && i + 1 + k < b.len() { + v = (v << 6) | (b[i + 1 + k] as u32 & 0x3f); + k += 1; + } + out.push(v); + i += 1 + k; + } + out +} + +impl Checker { + // Literals as constructors. + + /// `nat_lit_to_constructor`: `0` is `Nat.zero` and `n+1` is `Nat.succ n`. + pub(crate) fn nat_lit_to_constructor(&mut self, v: &Nat) -> ExprId { + if v.is_zero() { + return self.b.e_nat_zero; + } + let p = v.sub(&Nat::from_u64(1)); + let id = self.st.intern_nat(p); + let lit = self.st.mk_nat_lit(id); + self.st.mk_app(self.b.e_nat_succ, lit) + } + + /// `string_lit_to_constructor`: `String.ofList [Char.ofNat c1, ..., Char.ofNat cn]`. + pub(crate) fn string_lit_to_constructor(&mut self, s: rulean_store::StrId) -> ExprId { + let cs = utf8_decode(self.st.str_bytes(s)); + let mut r = self.b.e_list_nil_char; + let mut i = cs.len(); + while i > 0 { + i -= 1; + let id = self.st.intern_nat(Nat::from_u64(cs[i] as u64)); + let lit = self.st.mk_nat_lit(id); + let ch = self.st.mk_app(self.b.e_char_of_nat, lit); + let cons = self.st.mk_app(self.b.e_list_cons_char, ch); + r = self.st.mk_app(cons, r); + } + self.st.mk_app(self.b.e_string_of_list, r) + } + + /// The string of a string literal, if `e` is one. + pub(crate) fn string_lit(&self, e: ExprId) -> Option { + match self.st.node(e) { + Expr::Lit(Literal::Str(s)) => Some(s), + _ => None, + } + } + + // Environment queries of `inductive.cpp`. + + /// `is_non_rec_structure`: an inductive type with one constructor, no indices and no recursion. An unknown name is a fault, as `environment::get` throws. + pub(crate) fn is_non_rec_structure(&mut self, n: NameId, at: ExprId) -> bool { + let s = self.get_const(n, at); + if s == 0 { + return false; + } + match &self.env.at(s).kind { + ConstKind::Induct(i) => i.ctors.len() == 1 && i.nindices == 0 && !i.is_rec, + _ => false, + } + } + + /// `get_first_cnstr`: the first constructor of an inductive type, if any. + pub(crate) fn first_ctor(&mut self, n: NameId, at: ExprId) -> Option { + let s = self.get_const(n, at); + if s == 0 { + return None; + } + match &self.env.at(s).kind { + ConstKind::Induct(i) => { + if i.ctors.len() > 0 { + Some(i.ctors[0]) + } else { + None + } + } + _ => None, + } + } + + /// The induct, the number of parameters and the number of fields of a constructor. A name that is not a constructor gives `None`. + pub(crate) fn ctor_shape(&self, n: NameId) -> Option<(NameId, u32, u32)> { + let s = self.env.find(n); + if s == 0 { + return None; + } + match &self.env.at(s).kind { + ConstKind::Ctor(c) => Some((c.induct, c.nparams, c.nfields)), + _ => None, + } + } + + /// `is_constructor_app`. + fn is_constructor_app(&self, e: ExprId) -> bool { + let f = expr::app_fn(&self.st, e); + match self.st.node(f) { + Expr::Const(n, _) => self.ctor_shape(n).is_some(), + _ => false, + } + } + + /// `mk_nullary_cnstr`: the first constructor of the head of `ty`, applied to the first `nparams` arguments of `ty`. + fn mk_nullary_cnstr(&mut self, ty: ExprId, nparams: u32) -> Option { + let mut args: Vec = Vec::new(); + let d = expr::app_args(&self.st, ty, &mut args); + let (dn, dls) = match self.st.node(d) { + Expr::Const(n, ls) => (n, ls), + _ => return None, + }; + let c = match self.first_ctor(dn, ty) { + Some(c) => c, + None => return None, + }; + args.truncate(nparams as usize); + let k = self.st.mk_const(c, dls); + Some(self.st.mk_apps(k, &args)) + } + + /// `expand_eta_struct`: `mk e.1 ... e.n` for a term `e` of type `e_type`. + fn expand_eta_struct(&mut self, e_type: ExprId, e: ExprId) -> ExprId { + let mut args: Vec = Vec::new(); + let i_fn = expr::app_args(&self.st, e_type, &mut args); + let (i_name, i_levels) = match self.st.node(i_fn) { + Expr::Const(n, ls) => (n, ls), + _ => return e, + }; + let c = match self.first_ctor(i_name, e) { + Some(c) => c, + None => return e, + }; + let (nparams, nfields) = match self.ctor_shape(c) { + Some((_, p, f)) => (p, f), + None => return self.fail(ErrorKind::BadConst, e), + }; + args.truncate(nparams as usize); + let k = self.st.mk_const(c, i_levels); + let mut r = self.st.mk_apps(k, &args); + let mut i = 0; + while i < nfields { + let p = self.st.mk_proj(i_name, i, e); + r = self.st.mk_app(r, p); + i += 1; + } + r + } + + /// The reduction that `inductive_reduce_rec` gets as its `whnf` argument. + fn rec_whnf(&mut self, e: ExprId, cheap_rec: bool, cheap_proj: bool) -> ExprId { + if cheap_rec { + self.whnf_core(e, cheap_rec, cheap_proj) + } else { + self.whnf(e) + } + } + + /// `to_cnstr_when_K` of the official kernel. + fn cnstr_when_k( + &mut self, + major_induct: NameId, + nparams: u32, + e: ExprId, + cheap_rec: bool, + cheap_proj: bool, + ) -> ExprId { + let t = self.infer(e); + let app_type = self.rec_whnf(t, cheap_rec, cheap_proj); + if self.bad() { + return e; + } + let i_fn = expr::app_fn(&self.st, app_type); + if !self.is_constant_named(i_fn, major_induct) { + return e; + } + let new_c = match self.mk_nullary_cnstr(app_type, nparams) { + Some(c) => c, + None => return e, + }; + let new_type = self.infer(new_c); + if self.bad() || !self.is_def_eq(app_type, new_type) { + return e; + } + new_c + } + + /// `to_cnstr_when_structure` of the official kernel. + fn cnstr_when_structure( + &mut self, + induct: NameId, + e: ExprId, + cheap_rec: bool, + cheap_proj: bool, + ) -> ExprId { + if !self.is_non_rec_structure(induct, e) || self.is_constructor_app(e) { + return e; + } + let t = self.infer(e); + let e_type = self.rec_whnf(t, cheap_rec, cheap_proj); + if self.bad() { + return e; + } + let f = expr::app_fn(&self.st, e_type); + if !self.is_constant_named(f, induct) { + return e; + } + if self.is_prop(e_type) || self.bad() { + return e; + } + self.expand_eta_struct(e_type, e) + } + + /// `recursor_val::get_major_induct`: the head of the domain of the major premise in the type of the recursor. + fn major_induct(&self, slot: u32, major_idx: u32) -> NameId { + let mut t = self.env.at(slot).ty; + let mut i = 0; + while i < major_idx { + let (_, body) = self.binding(t); + t = body; + i += 1; + } + let (dom, _) = self.binding(t); + let f = expr::app_fn(&self.st, dom); + self.const_name(f) + } + + /// The recursor data of a slot, if the constant is a recursor. + fn rec_shape(&self, slot: u32) -> Option { + match &self.env.at(slot).kind { + ConstKind::Rec(r) => Some(RecShape { + major_idx: r.major_idx(), + nprefix: r.nparams + r.nmotives + r.nminors, + nparams: r.nparams, + k: r.k, + }), + _ => None, + } + } + + /// `get_rec_rule_for`. + fn rec_rule_for(&self, slot: u32, major: ExprId) -> Option { + let f = expr::app_fn(&self.st, major); + let n = match self.st.node(f) { + Expr::Const(n, _) => n, + _ => return None, + }; + match &self.env.at(slot).kind { + ConstKind::Rec(r) => find_rule(&r.rules, n), + _ => None, + } + } + + /// `inductive_reduce_rec`. + fn inductive_reduce_rec( + &mut self, + e: ExprId, + cheap_rec: bool, + cheap_proj: bool, + ) -> Option { + let rec_fn = expr::app_fn(&self.st, e); + let (rn, rls) = match self.st.node(rec_fn) { + Expr::Const(n, ls) => (n, ls), + _ => return None, + }; + let slot = self.env.find(rn); + if slot == 0 { + return None; + } + let r = match self.rec_shape(slot) { + Some(r) => r, + None => return None, + }; + let mut rec_args: Vec = Vec::new(); + expr::app_args(&self.st, e, &mut rec_args); + let major_idx = r.major_idx as usize; + if major_idx >= rec_args.len() { + return None; + } + let induct = self.major_induct(slot, r.major_idx); + let mut major = rec_args[major_idx]; + if r.k { + major = self.cnstr_when_k(induct, r.nparams, major, cheap_rec, cheap_proj); + } + major = self.rec_whnf(major, cheap_rec, cheap_proj); + if self.bad() { + return None; + } + major = match self.st.node(major) { + Expr::Lit(Literal::Nat(n)) => { + let v = self.st.nat(n).clone(); + self.nat_lit_to_constructor(&v) + } + Expr::Lit(Literal::Str(s)) => { + let c = self.string_lit_to_constructor(s); + self.rec_whnf(c, cheap_rec, cheap_proj) + } + _ => self.cnstr_when_structure(induct, major, cheap_rec, cheap_proj), + }; + if self.bad() { + return None; + } + let rule = match self.rec_rule_for(slot, major) { + Some(x) => x, + None => return None, + }; + let mut major_args: Vec = Vec::new(); + expr::app_args(&self.st, major, &mut major_args); + let nfields = rule.nfields as usize; + if nfields > major_args.len() { + return None; + } + let ls = self.st.level_list_vec(rls); + let lps = self.const_lparams(slot); + if ls.len() != lps.len() { + return None; + } + let mut rhs = expr::instantiate_lparams(&mut self.st, &mut self.x, rule.rhs, &lps, &ls); + let np = r.nprefix as usize; + rhs = self.st.mk_apps(rhs, &rec_args[..np]); + let nparams = major_args.len() - nfields; + rhs = self.st.mk_apps(rhs, &major_args[nparams..]); + if rec_args.len() > major_idx + 1 { + rhs = self.st.mk_apps(rhs, &rec_args[major_idx + 1..]); + } + Some(rhs) + } + + /// `quot_reduce_rec`: `Quot.lift f h (Quot.mk r a)` is `f a`, and `Quot.ind h (Quot.mk r a)` is `h a`. + fn quot_reduce_rec(&mut self, e: ExprId) -> Option { + let f = expr::app_fn(&self.st, e); + let n = match self.st.node(f) { + Expr::Const(n, _) => n, + _ => return None, + }; + let mk_pos: usize = if n == self.b.quot_lift { + 5 + } else if n == self.b.quot_ind { + 4 + } else { + return None; + }; + let arg_pos: usize = 3; + let mut args: Vec = Vec::new(); + expr::app_args(&self.st, e, &mut args); + if args.len() <= mk_pos { + return None; + } + let mk = self.whnf(args[mk_pos]); + if self.bad() { + return None; + } + let mk_fn = expr::app_fn(&self.st, mk); + if !self.is_constant_named(mk_fn, self.b.quot_mk) || expr::app_num_args(&self.st, mk) != 3 { + return None; + } + let a = self.app_arg(mk); + let mut r = self.st.mk_app(args[arg_pos], a); + let elim_arity = mk_pos + 1; + if args.len() > elim_arity { + r = self.st.mk_apps(r, &args[elim_arity..]); + } + Some(r) + } + + /// `reduce_recursor`. + fn reduce_recursor(&mut self, e: ExprId, cheap_rec: bool, cheap_proj: bool) -> Option { + if self.env.quot_initialized() { + let r = self.quot_reduce_rec(e); + if r.is_some() || self.bad() { + return r; + } + } + self.inductive_reduce_rec(e, cheap_rec, cheap_proj) + } + + /// `whnf_fvar`: zeta-reduction of a `let` free variable. + fn whnf_fvar(&mut self, e: ExprId, lvl: u32, cheap_rec: bool, cheap_proj: bool) -> ExprId { + match self.fvar_value(lvl) { + Some(v) => self.whnf_core(v, cheap_rec, cheap_proj), + None => e, + } + } + + /// `reduce_proj_core`. + pub(crate) fn reduce_proj_core( + &mut self, + c0: ExprId, + sname: NameId, + idx: u32, + ) -> Option { + let mut c = c0; + if let Some(s) = self.string_lit(c) { + let k = self.string_lit_to_constructor(s); + c = self.whnf(k); + if self.bad() { + return None; + } + } + let mut args: Vec = Vec::new(); + let mk = expr::app_args(&self.st, c, &mut args); + let n = match self.st.node(mk) { + Expr::Const(n, _) => n, + _ => return None, + }; + if self.get_const(n, c) == 0 { + return None; + } + let (induct, nparams, _) = match self.ctor_shape(n) { + Some(x) => x, + None => return None, + }; + if induct != sname { + return None; + } + let i = nparams as usize + idx as usize; + if i < args.len() { Some(args[i]) } else { None } + } + + /// `reduce_proj`. + fn reduce_proj(&mut self, e: ExprId, cheap_rec: bool, cheap_proj: bool) -> Option { + let (sname, idx, s) = match self.st.node(e) { + Expr::Proj(p) => (p.struct_name, p.index, p.expr), + _ => return None, + }; + let c = if cheap_proj { + self.whnf_core(s, cheap_rec, cheap_proj) + } else { + self.whnf(s) + }; + if self.bad() { + return None; + } + self.reduce_proj_core(c, sname, idx) + } + + /// `whnf_core`: weak head normal form without delta reduction and without the `Nat` extension. The cache is used only when `cheap_rec` and `cheap_proj` are false. + pub fn whnf_core(&mut self, e: ExprId, cheap_rec: bool, cheap_proj: bool) -> ExprId { + if self.bad() { + return self.dummy; + } + match self.st.node(e) { + Expr::BVar(_) + | Expr::Sort(_) + | Expr::Pi(_) + | Expr::Const(_, _) + | Expr::Lam(_) + | Expr::Lit(_) => return e, + Expr::FVar(_, _) => { + if !self.is_let_fvar(e) { + return e; + } + } + Expr::App(_, _) | Expr::Let(_) | Expr::Proj(_) => {} + } + if let Some(r) = self.c_whnf_core.get(e.0, 0) { + return ExprId(r); + } + if !self.enter(e) { + return self.dummy; + } + let (r, cache) = self.whnf_core_node(e, cheap_rec, cheap_proj); + self.leave(); + if cache && !cheap_rec && !cheap_proj && !self.bad() { + self.c_whnf_core.put(e.0, 0, r.0); + } + r + } + + /// The work of `whnf_core`. The flag is false where the official function returns before it writes the cache. + fn whnf_core_node(&mut self, e: ExprId, cheap_rec: bool, cheap_proj: bool) -> (ExprId, bool) { + match self.st.node(e) { + Expr::FVar(lvl, _) => (self.whnf_fvar(e, lvl, cheap_rec, cheap_proj), false), + Expr::Proj(_) => match self.reduce_proj(e, cheap_rec, cheap_proj) { + Some(m) => (self.whnf_core(m, cheap_rec, cheap_proj), true), + None => (e, true), + }, + Expr::App(_, _) => self.whnf_core_app(e, cheap_rec, cheap_proj), + Expr::Let(l) => { + let b = self.instantiate1(l.body, l.value); + (self.whnf_core(b, cheap_rec, cheap_proj), true) + } + _ => (e, false), + } + } + + /// The application case of `whnf_core`: beta reduction, then the recursors. + fn whnf_core_app(&mut self, e: ExprId, cheap_rec: bool, cheap_proj: bool) -> (ExprId, bool) { + let mut rev: Vec = Vec::new(); + let f0 = expr::app_rev_args(&self.st, e, &mut rev); + let f = self.whnf_core(f0, cheap_rec, cheap_proj); + if self.bad() { + return (self.dummy, false); + } + if self.is_lambda(f) { + let num_args = rev.len(); + let mut g = f; + let mut m = 1; + let mut walking = true; + while walking && m < num_args { + let (_, body) = self.binding(g); + if self.is_lambda(body) { + g = body; + m += 1; + } else { + walking = false; + } + } + let (_, body) = self.binding(g); + let inst = expr::instantiate(&mut self.st, &mut self.x, body, &rev[num_args - m..]); + let r = expr::mk_rev_app(&mut self.st, inst, &rev[..num_args - m]); + (self.whnf_core(r, cheap_rec, cheap_proj), true) + } else if self.eq(f, f0) { + match self.reduce_recursor(e, cheap_rec, cheap_proj) { + Some(r) => (self.whnf_core(r, cheap_rec, cheap_proj), false), + None => (e, false), + } + } else { + let r = expr::mk_rev_app(&mut self.st, f, &rev); + (self.whnf_core(r, cheap_rec, cheap_proj), true) + } + } + + // Delta reduction. + + /// `is_delta`: the slot of the definition or theorem at the head of `e`, if its number of levels is right, or 0. + pub(crate) fn is_delta(&self, e: ExprId) -> u32 { + let f = expr::app_fn(&self.st, e); + let (n, ls) = match self.st.node(f) { + Expr::Const(n, ls) => (n, ls), + _ => return 0, + }; + let s = self.env.find(n); + if s == 0 { + return 0; + } + let c = self.env.at(s); + if c.value().is_some() && self.st.level_list_items(ls).len() == c.lparams.len() { + s + } else { + 0 + } + } + + /// The hint of the constant of a slot. + pub(crate) fn hints(&self, slot: u32) -> Hints { + self.env.at(slot).hints() + } + + /// `unfold_definition_core`. The cache is used only for a constant with levels. + fn unfold_definition_core(&mut self, e: ExprId) -> Option { + let list = match self.st.node(e) { + Expr::Const(_, list) => list, + _ => return None, + }; + let d = self.is_delta(e); + if d == 0 { + return None; + } + let ls = self.st.level_list_vec(list); + if ls.len() > 0 { + if let Some(r) = self.c_unfold.get(e.0, 0) { + return Some(ExprId(r)); + } + let r = self.instantiate_value_lparams(d, &ls); + self.c_unfold.put(e.0, 0, r.0); + Some(r) + } else { + Some(self.instantiate_value_lparams(d, &ls)) + } + } + + /// `unfold_definition`: unfolds the head constant and applies the result to the arguments. + pub(crate) fn unfold_definition(&mut self, e: ExprId) -> Option { + if self.is_app(e) { + let f0 = expr::app_fn(&self.st, e); + match self.unfold_definition_core(f0) { + Some(f) => { + let mut rev: Vec = Vec::new(); + expr::app_rev_args(&self.st, e, &mut rev); + Some(expr::mk_rev_app(&mut self.st, f, &rev)) + } + None => None, + } + } else { + self.unfold_definition_core(e) + } + } + + // The `Nat` extension. + + /// The value of a literal or of `Nat.zero` (`is_nat_lit_ext` and `get_nat_val`). + pub(crate) fn nat_lit_ext(&self, e: ExprId) -> Option { + if e == self.b.e_nat_zero { + return Some(Nat::zero()); + } + match self.st.node(e) { + Expr::Lit(Literal::Nat(n)) => Some(self.st.nat(n).clone()), + _ => None, + } + } + + fn mk_nat(&mut self, v: Nat) -> ExprId { + let id = self.st.intern_nat(v); + self.st.mk_nat_lit(id) + } + + fn mk_bool(&self, b: bool) -> ExprId { + if b { + self.b.e_bool_true + } else { + self.b.e_bool_false + } + } + + /// The two arguments of a binary `Nat` operation after `whnf`, if both are literals. + fn nat_args(&mut self, e: ExprId) -> Option<(Nat, Nat)> { + let f = self.app_fn1(e); + let a1 = self.app_arg(f); + let w1 = self.whnf(a1); + let v1 = match self.nat_lit_ext(w1) { + Some(v) => v, + None => return None, + }; + let a2 = self.app_arg(e); + let w2 = self.whnf(a2); + let v2 = match self.nat_lit_ext(w2) { + Some(v) => v, + None => return None, + }; + if self.bad() { + return None; + } + Some((v1, v2)) + } + + /// The second argument of `Nat.pow` or `Nat.shiftLeft` as a count (`get_count_arg`). + fn count_arg(&mut self, v: &Nat, e: ExprId) -> Option { + match v.to_u64() { + Some(k) if k <= u32::MAX as u64 => Some(k), + _ => { + self.fail(ErrorKind::CountTooLarge, e); + None + } + } + } + + /// `reduce_pow`. + fn reduce_pow(&mut self, e: ExprId, base: &Nat, exp: &Nat) -> Option { + let k = match self.count_arg(exp, e) { + Some(k) => k, + None => return None, + }; + let one = Nat::from_u64(1); + if base.compare(&one) == core::cmp::Ordering::Greater + && k != 0 + && Checker::nat_size(base) > crate::tc::NAT_MAX_BYTES / k + { + self.fail(ErrorKind::NatTooLarge, e); + return None; + } + let r = base.pow(k); + Some(self.mk_nat(r)) + } + + /// `reduce_shiftLeft`. + fn reduce_shift_left(&mut self, e: ExprId, v: &Nat, shift: &Nat) -> Option { + if v.is_zero() { + return Some(self.mk_nat(Nat::zero())); + } + let k = match self.count_arg(shift, e) { + Some(k) => k, + None => return None, + }; + if !self.check_nat_size(Checker::nat_size(v) + k / 8 + 1, e) { + return None; + } + let r = v.shift_left(k); + Some(self.mk_nat(r)) + } + + /// A binary operation that checks the size of its result (`reduce_bin_nat_op` with `check_size`). + fn sized(&mut self, e: ExprId, r: Nat) -> Option { + if !self.check_nat_size(Checker::nat_size(&r), e) { + return None; + } + Some(self.mk_nat(r)) + } + + /// The binary operation `op` of `reduce_nat` on the values. + fn nat_bin(&mut self, e: ExprId, op: usize, v1: &Nat, v2: &Nat) -> Option { + match op { + NAT_ADD => self.sized(e, v1.add(v2)), + NAT_SUB => self.sized(e, v1.sub(v2)), + NAT_MUL => self.sized(e, v1.mul(v2)), + NAT_POW => self.reduce_pow(e, v1, v2), + NAT_GCD => Some(self.mk_nat(v1.gcd(v2))), + NAT_MOD => Some(self.mk_nat(v1.rem(v2))), + NAT_DIV => Some(self.mk_nat(v1.div(v2))), + NAT_BEQ => Some(self.mk_bool(v1.beq(v2))), + NAT_BLE => Some(self.mk_bool(v1.ble(v2))), + NAT_LAND => Some(self.mk_nat(v1.land(v2))), + NAT_LOR => Some(self.mk_nat(v1.lor(v2))), + NAT_XOR => Some(self.mk_nat(v1.xor(v2))), + NAT_SHL => self.reduce_shift_left(e, v1, v2), + NAT_SHR => Some(self.mk_nat(v1.shift_right_nat(v2))), + _ => None, + } + } + + /// The index of the binary operation `f` in the `nat_ops` table, or the length of the table. + fn nat_op_index(&self, f: ExprId) -> usize { + let ops = &self.b.nat_ops; + let mut i = 0; + while i < ops.len() && ops[i] != f { + i += 1; + } + i + } + + /// `reduce_nat`: the 15 built-in operations on literals (spec 05.8). + pub(crate) fn reduce_nat(&mut self, e: ExprId) -> Option { + let nargs = expr::app_num_args(&self.st, e); + if nargs == 1 { + let f = self.app_fn1(e); + if f == self.b.e_nat_succ { + let a = self.app_arg(e); + let w = self.whnf(a); + let v = match self.nat_lit_ext(w) { + Some(v) => v, + None => return None, + }; + return self.sized(e, v.succ()); + } + } else if nargs == 2 { + let f1 = self.app_fn1(e); + let f = self.app_fn1(f1); + if !self.is_constant(f) { + return None; + } + let op = self.nat_op_index(f); + if op >= self.b.nat_ops.len() { + return None; + } + let (v1, v2) = match self.nat_args(e) { + Some(x) => x, + None => return None, + }; + return self.nat_bin(e, op, &v1, &v2); + } + None + } + + /// `whnf`: weak head normal form with delta reduction and the `Nat` extension. + pub fn whnf(&mut self, e: ExprId) -> ExprId { + if self.bad() { + return self.dummy; + } + match self.st.node(e) { + Expr::BVar(_) | Expr::Sort(_) | Expr::Pi(_) | Expr::Lit(_) => return e, + Expr::FVar(_, _) => { + if !self.is_let_fvar(e) { + return e; + } + } + _ => {} + } + if let Some(r) = self.c_whnf.get(e.0, 0) { + return ExprId(r); + } + let r = self.whnf_loop(e); + if !self.bad() { + self.c_whnf.put(e.0, 0, r.0); + } + r + } + + /// The loop of `whnf`: `whnf_core`, then the `Nat` extension, then one delta step. + fn whnf_loop(&mut self, e: ExprId) -> ExprId { + let mut t = e; + let mut r = e; + let mut done = false; + while !done && !self.bad() { + let t1 = self.whnf_core(t, false, false); + match self.reduce_nat(t1) { + Some(v) => { + r = v; + done = true; + } + None => match self.unfold_definition(t1) { + Some(n) => t = n, + None => { + r = t1; + done = true; + } + }, + } + } + r + } +} + +/// The rule of the constructor `n` in `rules`, if there is one. +fn find_rule(rules: &[RuleInfo], n: NameId) -> Option { + let mut i = 0; + while i < rules.len() && rules[i].ctor != n { + i += 1; + } + if i < rules.len() { + Some(rules[i]) + } else { + None + } +} diff --git a/crates/rulean-core/tests/tc.rs b/crates/rulean-core/tests/tc.rs new file mode 100644 index 0000000..c4d96e9 --- /dev/null +++ b/crates/rulean-core/tests/tc.rs @@ -0,0 +1,489 @@ +//! Tests of inference, reduction and definitional equality of engine R. Each test builds a small environment by hand. The expected values follow `type_checker.cpp` of the official kernel v4.35.0. + +use rulean_core::env::{ConstInfo, ConstKind, CtorInfo, InductInfo, RecInfo, RuleInfo}; +use rulean_core::tc::{Checker, ErrorKind}; +use rulean_format::{Hints, Safety}; +use rulean_nat::Nat; +use rulean_store::{BinderInfo, ExprId, LevelId, NameId, Store}; + +struct T { + c: Checker, +} + +impl T { + fn new() -> T { + let mut c = Checker::new(Store::new()); + c.begin(Vec::new(), Safety::Safe); + T { c } + } + fn name(&mut self, s: &str) -> NameId { + let mut n = self.c.st.anon(); + for part in s.split('.') { + n = self.c.st.name_str_bytes(n, part.as_bytes()); + } + n + } + fn sort(&mut self, k: u32) -> ExprId { + let mut l = self.c.st.level_zero(); + for _ in 0..k { + l = self.c.st.level_succ(l); + } + self.c.st.mk_sort(l) + } + fn k(&mut self, s: &str) -> ExprId { + let n = self.name(s); + let ls = self.c.st.level_list_empty(); + self.c.st.mk_const(n, ls) + } + fn kl(&mut self, s: &str, ls: &[LevelId]) -> ExprId { + let n = self.name(s); + let ls = self.c.st.level_list(ls); + self.c.st.mk_const(n, ls) + } + fn app(&mut self, f: ExprId, args: &[ExprId]) -> ExprId { + self.c.st.mk_apps(f, args) + } + fn bv(&mut self, i: u32) -> ExprId { + self.c.st.mk_bvar(i) + } + fn lam(&mut self, n: &str, ty: ExprId, body: ExprId) -> ExprId { + let n = self.name(n); + self.c.st.mk_lam(n, BinderInfo::Default, ty, body) + } + fn pi(&mut self, n: &str, ty: ExprId, body: ExprId) -> ExprId { + let n = self.name(n); + self.c.st.mk_pi(n, BinderInfo::Default, ty, body) + } + fn nat(&mut self, v: u64) -> ExprId { + let id = self.c.st.intern_nat(Nat::from_u64(v)); + self.c.st.mk_nat_lit(id) + } + fn add(&mut self, name: &str, lparams: &[&str], ty: ExprId, kind: ConstKind) { + let name = self.name(name); + let mut ls = Vec::new(); + for p in lparams { + ls.push(self.name(p)); + } + self.c.env.add(ConstInfo { + name, + lparams: ls, + ty, + safety: Safety::Safe, + kind, + }); + } + fn axiom(&mut self, name: &str, ty: ExprId) -> ExprId { + self.add(name, &[], ty, ConstKind::Axiom); + self.k(name) + } + fn def(&mut self, name: &str, ty: ExprId, value: ExprId, h: u32) -> ExprId { + self.add( + name, + &[], + ty, + ConstKind::Defn { + value, + hints: Hints::Regular(h), + }, + ); + self.k(name) + } + fn whnf(&mut self, e: ExprId) -> ExprId { + self.c.whnf(e) + } + fn defeq(&mut self, a: ExprId, b: ExprId) -> bool { + self.c.is_def_eq(a, b) + } +} + +#[test] +fn infer_sort_lambda_and_pi() { + let mut t = T::new(); + let s0 = t.sort(0); + let s1 = t.sort(1); + let s2 = t.sort(2); + assert_eq!(t.c.check(s0), s1); + assert_eq!(t.c.check(s1), s2); + // fun (A : Type) (x : A) => x has the type (A : Type) -> A -> A. + let b0 = t.bv(0); + let b1 = t.bv(1); + let inner = t.lam("x", b0, b0); + let id = t.lam("A", s1, inner); + let pinner = t.pi("x", b0, b1); + let want = t.pi("A", s1, pinner); + let got = t.c.check(id); + assert!(t.c.fault().is_none()); + assert!(t.defeq(got, want)); + // The type of a pi over a sort is the impredicative maximum. + let p = t.pi("A", s1, b0); + assert_eq!(t.c.check(p), s2); + let prop_pi = t.pi("p", s0, b0); + let ty = t.c.check(prop_pi); + assert_eq!(ty, s0); +} + +#[test] +fn unknown_constant_is_a_fault() { + let mut t = T::new(); + let c = t.k("nothing"); + t.c.check(c); + let f = t.c.fault().expect("fault"); + assert_eq!(f.kind, ErrorKind::UnknownConst); +} + +#[test] +fn application_type_mismatch() { + let mut t = T::new(); + let s1 = t.sort(1); + let a = t.axiom("A", s1); + let b = t.axiom("B", s1); + let x = t.axiom("x", b); + let b0 = t.bv(0); + let f = t.lam("y", a, b0); + let e = t.app(f, &[x]); + t.c.check(e); + assert_eq!( + t.c.fault().map(|f| f.kind), + Some(ErrorKind::AppTypeMismatch) + ); +} + +#[test] +fn beta_delta_and_zeta() { + let mut t = T::new(); + let s1 = t.sort(1); + let a = t.axiom("A", s1); + let c = t.axiom("c", a); + let b0 = t.bv(0); + let id = t.lam("x", a, b0); + let e = t.app(id, &[c]); + assert_eq!(t.whnf(e), c); + assert_eq!(t.c.whnf_core(e, false, false), c); + // A definition unfolds in whnf but not in whnf_core. + let d = t.def("d", a, c, 1); + assert_eq!(t.c.whnf_core(d, false, false), d); + assert_eq!(t.whnf(d), c); + // let x := c; x + let n = t.name("x"); + let l = t.c.st.mk_let(n, a, c, b0); + assert_eq!(t.whnf(l), c); + assert!(t.c.fault().is_none()); +} + +#[test] +fn nat_literal_extension() { + let mut t = T::new(); + let s1 = t.sort(1); + let nat = t.k("Nat"); + t.axiom("Nat", s1); + let (two, three, five) = (t.nat(2), t.nat(3), t.nat(5)); + let add = t.k("Nat.add"); + let e = t.app(add, &[two, three]); + assert_eq!(t.whnf(e), five); + let succ = t.k("Nat.succ"); + let four = t.nat(4); + let e = t.app(succ, &[four]); + assert_eq!(t.whnf(e), five); + let ble = t.k("Nat.ble"); + let e = t.app(ble, &[five, two]); + let f = t.k("Bool.false"); + assert_eq!(t.whnf(e), f); + // 5 =?= Nat.succ 4 by the offset rule. + let e = t.app(succ, &[four]); + assert!(t.defeq(five, e)); + let zero = t.axiom("Nat.zero", nat); + let z = t.nat(0); + assert!(t.defeq(zero, z)); + assert!(!t.defeq(five, four)); + let _ = nat; + assert!(t.c.fault().is_none()); +} + +#[test] +fn nat_pow_count_bound() { + let mut t = T::new(); + let pow = t.k("Nat.pow"); + let two = t.nat(2); + let big = t.nat(5_000_000_000); + let e = t.app(pow, &[two, big]); + t.whnf(e); + assert_eq!(t.c.fault().map(|f| f.kind), Some(ErrorKind::CountTooLarge)); +} + +#[test] +fn proof_irrelevance() { + let mut t = T::new(); + let s0 = t.sort(0); + let p = t.axiom("P", s0); + let h1 = t.axiom("h1", p); + let h2 = t.axiom("h2", p); + assert!(t.defeq(h1, h2)); + let s1 = t.sort(1); + let a = t.axiom("A", s1); + let x = t.axiom("x", a); + let y = t.axiom("y", a); + assert!(!t.defeq(x, y)); + assert!(t.c.fault().is_none()); +} + +#[test] +fn eta_expansion() { + let mut t = T::new(); + let s1 = t.sort(1); + let a = t.axiom("A", s1); + let fty = t.pi("x", a, a); + let f = t.axiom("f", fty); + let b0 = t.bv(0); + let body = t.app(f, &[b0]); + let l = t.lam("x", a, body); + assert!(t.defeq(l, f)); + assert!(t.defeq(f, l)); + assert!(t.c.fault().is_none()); +} + +/// A structure `Pr` with the constructor `Pr.mk : A -> A -> Pr`. +fn pair(t: &mut T) -> (ExprId, ExprId, NameId) { + let s1 = t.sort(1); + let a = t.axiom("A", s1); + let pr_n = t.name("Pr"); + let mk_n = t.name("Pr.mk"); + t.add( + "Pr", + &[], + s1, + ConstKind::Induct(InductInfo { + nparams: 0, + nindices: 0, + all: vec![pr_n], + ctors: vec![mk_n], + nnested: 0, + is_rec: false, + is_reflexive: false, + }), + ); + let pr = t.k("Pr"); + let inner = t.pi("b", a, pr); + let mk_ty = t.pi("a", a, inner); + t.add( + "Pr.mk", + &[], + mk_ty, + ConstKind::Ctor(CtorInfo { + induct: pr_n, + cidx: 0, + nparams: 0, + nfields: 2, + }), + ); + (a, pr, pr_n) +} + +#[test] +fn projections_and_structure_eta() { + let mut t = T::new(); + let (a, pr, pr_n) = pair(&mut t); + let x = t.axiom("x", a); + let y = t.axiom("y", a); + let mk = t.k("Pr.mk"); + let v = t.app(mk, &[x, y]); + let p1 = t.c.st.mk_proj(pr_n, 1, v); + assert_eq!(t.whnf(p1), y); + assert_eq!(t.c.infer(p1), a); + // p =?= Pr.mk p.1 p.2 + let p = t.axiom("p", pr); + let q0 = t.c.st.mk_proj(pr_n, 0, p); + let q1 = t.c.st.mk_proj(pr_n, 1, p); + let e = t.app(mk, &[q0, q1]); + assert!(t.defeq(p, e)); + assert!(t.defeq(e, p)); + let e = t.app(mk, &[q1, q0]); + assert!(!t.defeq(p, e)); + assert!(t.c.fault().is_none()); +} + +#[test] +fn unit_like_structure() { + let mut t = T::new(); + let s1 = t.sort(1); + let u_n = t.name("U"); + let star_n = t.name("U.star"); + t.add( + "U", + &[], + s1, + ConstKind::Induct(InductInfo { + nparams: 0, + nindices: 0, + all: vec![u_n], + ctors: vec![star_n], + nnested: 0, + is_rec: false, + is_reflexive: false, + }), + ); + let u = t.k("U"); + t.add( + "U.star", + &[], + u, + ConstKind::Ctor(CtorInfo { + induct: u_n, + cidx: 0, + nparams: 0, + nfields: 0, + }), + ); + let a = t.axiom("a", u); + let b = t.axiom("b", u); + assert!(t.defeq(a, b)); + assert!(t.c.fault().is_none()); +} + +#[test] +fn recursor_iota() { + let mut t = T::new(); + let s1 = t.sort(1); + let b_n = t.name("B"); + let bt_n = t.name("B.t"); + let bf_n = t.name("B.f"); + t.add( + "B", + &[], + s1, + ConstKind::Induct(InductInfo { + nparams: 0, + nindices: 0, + all: vec![b_n], + ctors: vec![bt_n, bf_n], + nnested: 0, + is_rec: false, + is_reflexive: false, + }), + ); + let bty = t.k("B"); + for (n, i) in [("B.t", 0), ("B.f", 1)] { + t.add( + n, + &[], + bty, + ConstKind::Ctor(CtorInfo { + induct: b_n, + cidx: i, + nparams: 0, + nfields: 0, + }), + ); + } + // B.rec.{u} : (motive : B -> Sort u) -> motive B.t -> motive B.f -> (b : B) -> motive b + let un = t.name("u"); + let u = t.c.st.level_param(un); + let su = t.c.st.mk_sort(u); + let motive_ty = t.pi("b", bty, su); + let (b0, b1, b2, b3) = (t.bv(0), t.bv(1), t.bv(2), t.bv(3)); + let btc = t.k("B.t"); + let bfc = t.k("B.f"); + let m_t = t.app(b0, &[btc]); + let m_f = t.app(b1, &[bfc]); + let m_b = t.app(b3, &[b0]); + let last = t.pi("b", bty, m_b); + let r3 = t.pi("f", m_f, last); + let r2 = t.pi("t", m_t, r3); + let rec_ty = t.pi("motive", motive_ty, r2); + // The rules: fun motive t f => t and fun motive t f => f. + let rt = { + let l3 = t.lam("f", m_f, b1); + let l2 = t.lam("t", m_t, l3); + t.lam("motive", motive_ty, l2) + }; + let rf = { + let l3 = t.lam("f", m_f, b0); + let l2 = t.lam("t", m_t, l3); + t.lam("motive", motive_ty, l2) + }; + let _ = b2; + t.add( + "B.rec", + &["u"], + rec_ty, + ConstKind::Rec(RecInfo { + all: vec![b_n], + nparams: 0, + nindices: 0, + nmotives: 1, + nminors: 2, + rules: vec![ + RuleInfo { + ctor: bt_n, + nfields: 0, + rhs: rt, + }, + RuleInfo { + ctor: bf_n, + nfields: 0, + rhs: rf, + }, + ], + k: false, + }), + ); + let z = t.c.st.level_zero(); + let one = t.c.st.level_succ(z); + let rec = t.kl("B.rec", &[one]); + let m = t.k("M"); + let x = t.k("x"); + let y = t.k("y"); + let e = t.app(rec, &[m, x, y, bfc]); + assert_eq!(t.whnf(e), y); + let e = t.app(rec, &[m, x, y, btc]); + assert_eq!(t.whnf(e), x); + // A major premise that is not a constructor stays. + let o = t.k("o"); + let e = t.app(rec, &[m, x, y, o]); + assert_eq!(t.whnf(e), e); + assert!(t.c.fault().is_none()); +} + +#[test] +fn quotient_lift() { + let mut t = T::new(); + t.c.env.mark_quot_initialized(); + let z = t.c.st.level_zero(); + let one = t.c.st.level_succ(z); + let lift = t.kl("Quot.lift", &[one, one]); + let mk = t.kl("Quot.mk", &[one]); + let (a, r, b, f, h, x) = (t.k("A"), t.k("r"), t.k("B"), t.k("f"), t.k("h"), t.k("x")); + let q = t.app(mk, &[a, r, x]); + let e = t.app(lift, &[a, r, b, f, h, q]); + let want = t.app(f, &[x]); + assert_eq!(t.whnf(e), want); +} + +#[test] +fn string_literal_expansion() { + let mut t = T::new(); + let s1 = t.sort(1); + t.axiom("String", s1); + t.axiom("String.ofList", s1); + let sid = t.c.st.intern_str(b"a"); + let lit = t.c.st.mk_str_lit(sid); + let z = t.c.st.level_zero(); + let ch = t.k("Char"); + let cons = t.kl("List.cons", &[z]); + let nil = t.kl("List.nil", &[z]); + let nil = t.app(nil, &[ch]); + let of_nat = t.k("Char.ofNat"); + let n97 = t.nat(97); + let c97 = t.app(of_nat, &[n97]); + let list = t.app(cons, &[ch, c97, nil]); + let of_list = t.k("String.ofList"); + let s = t.app(of_list, &[list]); + assert!(t.defeq(lit, s)); + assert!(t.c.fault().is_none()); +} + +#[test] +fn utf8_decode_matches_code_points() { + let s = "aé€😀"; + let want: Vec = s.chars().map(|c| c as u32).collect(); + assert_eq!(rulean_core::whnf::utf8_decode(s.as_bytes()), want); +}