1use crate::context::Context;
27use crate::error::{KernelError, KernelResult};
28use crate::reduction::normalize;
29use crate::term::{Literal, Term, Universe};
30
31pub(crate) const MAX_TERM_DEPTH: usize = 1600;
64
65thread_local! {
66 static INSIDE_KERNEL: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
70}
71
72pub(crate) struct DoorGuard(bool);
75
76impl Drop for DoorGuard {
77 fn drop(&mut self) {
78 if self.0 {
79 INSIDE_KERNEL.with(|f| f.set(false));
80 }
81 }
82}
83
84pub(crate) fn depth_exceeds(t: &Term, limit: usize) -> bool {
90 let mut work: Vec<(&Term, usize)> = vec![(t, 0)];
91 while let Some((node, d)) = work.pop() {
92 if d > limit {
93 return true;
94 }
95 let deeper = d + 1;
96 match node {
97 Term::Sort(_)
98 | Term::Var(_)
99 | Term::Global(_)
100 | Term::Const { .. }
101 | Term::Lit(_)
102 | Term::Hole => {}
103 Term::App(f, a) => {
104 work.push((f, deeper));
105 work.push((a, deeper));
106 }
107 Term::Pi {
108 param_type,
109 body_type,
110 ..
111 } => {
112 work.push((param_type, deeper));
113 work.push((body_type, deeper));
114 }
115 Term::Lambda {
116 param_type, body, ..
117 } => {
118 work.push((param_type, deeper));
119 work.push((body, deeper));
120 }
121 Term::Let {
122 ty, value, body, ..
123 } => {
124 work.push((ty, deeper));
125 work.push((value, deeper));
126 work.push((body, deeper));
127 }
128 Term::Match {
129 discriminant,
130 motive,
131 cases,
132 } => {
133 work.push((discriminant, deeper));
134 work.push((motive, deeper));
135 for c in cases {
136 work.push((c, deeper));
137 }
138 }
139 Term::Fix { body, .. } => work.push((body, deeper)),
140 Term::MutualFix { defs, .. } => {
141 for (_, b) in defs {
142 work.push((b, deeper));
143 }
144 }
145 Term::Annotated { term, .. } => work.push((term, deeper)),
146 }
147 }
148 false
149}
150
151pub(crate) fn enter_kernel(term: &Term, what: &str) -> KernelResult<DoorGuard> {
154 if INSIDE_KERNEL.with(|f| f.get()) {
155 return Ok(DoorGuard(false));
156 }
157 if depth_exceeds(term, MAX_TERM_DEPTH) {
158 crate::reduction::record_resource_stop(crate::reduction::Unreduced::TooDeep);
159 return Err(KernelError::CertificationError(format!(
160 "term nests deeper than the kernel's limit of {MAX_TERM_DEPTH} while running {what}: this is a REFUSAL, not a verdict — the term is neither accepted nor rejected, because descending it would exhaust the native stack"
161 )));
162 }
163 INSIDE_KERNEL.with(|f| f.set(true));
164 Ok(DoorGuard(true))
165}
166
167pub(crate) fn enter_kernel_or_refuse(term: &Term) -> Option<DoorGuard> {
169 enter_kernel(term, "reduction").ok()
170}
171
172pub(crate) fn inside_kernel() -> bool {
179 INSIDE_KERNEL.with(|f| f.get())
180}
181
182#[derive(Clone, Copy)]
186pub(crate) enum TypeHead {
187 Function,
188 Inductive,
189}
190
191#[cfg(test)]
192thread_local! {
193 static TYPE_HEAD_FULL_NORMALIZATIONS: std::cell::Cell<[usize; 2]> =
194 const { std::cell::Cell::new([0; 2]) };
195}
196
197pub(crate) fn demanded_type_head(ctx: &Context, ty: Term, requested: TypeHead) -> Term {
198 probe_type_head(ctx, ty, requested).unwrap_or_else(|ty| {
199 #[cfg(test)]
200 TYPE_HEAD_FULL_NORMALIZATIONS.with(|count| {
201 let mut values = count.get();
202 values[match requested {
203 TypeHead::Function => 0,
204 TypeHead::Inductive => 1,
205 }] += 1;
206 count.set(values);
207 });
208 normalize(ctx, &ty)
209 })
210}
211
212fn probe_type_head(ctx: &Context, ty: Term, requested: TypeHead) -> Result<Term, Term> {
215 if matches!(requested, TypeHead::Function) && matches!(ty, Term::Pi { .. }) {
217 return Ok(ty);
218 }
219 let has_requested_head = |candidate: &Term| match requested {
220 TypeHead::Function => matches!(candidate, Term::Pi { .. }),
221 TypeHead::Inductive => extract_inductive_name(ctx, candidate).is_some(),
222 };
223 if ctx.simp_rules().is_empty() {
226 if has_requested_head(&ty) {
227 return Ok(ty);
228 }
229 if let Some(exposed) = crate::reduction::bounded_conversion_head(ctx, &ty) {
230 if has_requested_head(&exposed) {
231 return Ok(exposed);
232 }
233 }
234 }
235 Err(ty)
236}
237
238pub(crate) fn exposed_inductive_type(ctx: &Context, ty: Term) -> Result<Term, Term> {
244 probe_type_head(ctx, ty, TypeHead::Inductive)
245}
246
247pub(crate) fn exposed_function_type(ctx: &Context, ty: Term) -> Result<Term, Term> {
252 probe_type_head(ctx, ty, TypeHead::Function)
253}
254
255fn infer_canonical_peano(ctx: &Context, term: &Term) -> Option<KernelResult<Term>> {
259 let Term::App(head, _) = term else {
260 return None;
261 };
262 if !matches!(head.as_ref(), Term::Global(name) if name == "Succ")
263 || !ctx.simp_rules().is_empty()
264 || !crate::int_inductive::canonical_nat_environment(ctx)
265 {
266 return None;
267 }
268 let mut tail = term;
269 let mut prefix = 0usize;
270 while let Term::App(head, argument) = tail {
271 if !matches!(head.as_ref(), Term::Global(name) if name == "Succ") {
272 break;
273 }
274 prefix += 1;
275 if prefix > MAX_TERM_DEPTH {
276 return Some(Err(KernelError::CertificationError(
277 "computed Peano term exceeds the kernel term-depth limit".into(),
278 )));
279 }
280 tail = argument;
281 }
282 if depth_exceeds(tail, MAX_TERM_DEPTH - prefix) {
285 return Some(Err(KernelError::CertificationError(
286 "computed Peano term exceeds the kernel term-depth limit".into(),
287 )));
288 }
289 let natural = Term::Global("Nat".into());
290 Some(check_type(ctx, tail, &natural).map(|()| natural))
291}
292
293#[cfg(test)]
294thread_local! {
295 static PEANO_INFERENCE_ENTRIES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
296}
297
298pub fn infer_type(ctx: &Context, term: &Term) -> KernelResult<Term> {
319 if let Some(r) = crate::annotation::erased(term, |term| infer_type(ctx, term)) {
320 return r;
321 }
322 if !inside_kernel() {
332 if let Some(r) = crate::term_store::deepen_stack(term, || infer_type(ctx, term)) {
333 return r;
334 }
335 }
336 let _door = enter_kernel(term, "infer_type")?;
337 #[cfg(test)]
338 PEANO_INFERENCE_ENTRIES.with(|count| count.set(count.get() + 1));
339 if let Some(result) = infer_canonical_peano(ctx, term) {
340 return result;
341 }
342 match term {
343 Term::Sort(u) => Ok(Term::Sort(u.succ())),
345
346 Term::Var(name) => ctx.get(name).cloned().ok_or_else(|| classify_unbound(name)),
350
351 Term::Global(name) => match ctx.get_global(name) {
359 Some(ty) => Ok(ty.clone()),
360 None => Err(classify_unbound(name)),
361 },
362
363 Term::Const { name, levels } => {
368 let (declared, ty) = lookup_const(ctx, name).ok_or_else(|| classify_unbound(name))?;
369 let subst = crate::term::resolve_const_levels(name, declared.as_deref(), &ty, levels)
370 .map_err(|e| KernelError::CertificationError(e.to_string()))?;
371 Ok(crate::term::instantiate_universes(&ty, &subst))
372 }
373
374 Term::Pi {
376 param,
377 param_type,
378 body_type,
379 } => {
380 let a_sort = infer_sort(ctx, param_type)?;
382
383 let (param, body_type) = open_context_binder(ctx, param, param_type, body_type);
385 let extended_ctx = ctx.extend(¶m, (**param_type).clone());
386 let b_sort = infer_sort(&extended_ctx, &body_type)?;
387
388 let pi_sort = a_sort.imax(&b_sort);
397 Ok(Term::Sort(pi_sort))
398 }
399
400 Term::Lambda {
402 param,
403 param_type,
404 body,
405 } => {
406 let _ = infer_sort(ctx, param_type)?;
408
409 let (param, body) = open_context_binder(ctx, param, param_type, body);
411 let extended_ctx = ctx.extend(¶m, (**param_type).clone());
412 let body_type = infer_type(&extended_ctx, &body)?;
413
414 Ok(Term::Pi {
416 param: param.into_owned(),
417 param_type: param_type.clone(),
418 body_type: Box::new(body_type),
419 })
420 }
421
422 Term::Let {
428 name,
429 ty,
430 value,
431 body,
432 } => {
433 let _ = infer_sort(ctx, ty)?;
434 check_type(ctx, value, ty)?;
435 if !ctx.local_name_in_use(name) {
439 std::thread_local! { static LET_PROBE: std::cell::Cell<bool> = const { std::cell::Cell::new(false) }; }
440 struct Probe(bool);
441 impl Drop for Probe {
442 fn drop(&mut self) {
443 LET_PROBE.with(|flag| flag.set(self.0));
444 }
445 }
446 let probe = Probe(LET_PROBE.with(|flag| flag.replace(true)));
447 let nested = probe.0;
448 let result = infer_type(&ctx.extend(name, (**ty).clone()), body);
449 drop(probe);
450 match result {
451 Ok(body_type) => return Ok(instantiate_codomain(name, ty, &body_type, value)),
452 Err(error) if nested => return Err(error),
455 Err(_) => {}
456 }
457 }
458 let unfolded = substitute(body, name, value);
459 infer_type(ctx, &unfolded)
460 }
461
462 Term::App(func, arg) => {
464 let func_type = infer_type(ctx, func)?;
465 let func_type = demanded_type_head(ctx, func_type, TypeHead::Function);
469 let func_type = implicit_levels_for_head(func, func_type);
473
474 match func_type {
475 Term::Pi {
476 param,
477 param_type,
478 body_type,
479 } => {
480 let (param_type, body_type) =
491 match solve_domain_levels(ctx, ¶m_type, &body_type, arg) {
492 Some(solved) => solved,
493 None => (*param_type, *body_type),
494 };
495
496 check_type(ctx, arg, ¶m_type)?;
498
499 Ok(expose_head(substitute_shared(
502 &body_type,
503 ¶m,
504 ¶m_type,
505 arg,
506 )))
507 }
508 _ => Err(KernelError::NotAFunction(format!("{}", func))),
509 }
510 }
511
512 Term::Match {
514 discriminant,
515 motive,
516 cases,
517 } => {
518 let disc_type =
522 demanded_type_head(ctx, infer_type(ctx, discriminant)?, TypeHead::Inductive);
523 let inductive_name = extract_inductive_name(ctx, &disc_type)
524 .ok_or_else(|| KernelError::NotAnInductive(format!("{}", disc_type)))?;
525
526 if empty_match_would_be_a_lie(ctx, &inductive_name) {
529 return Err(KernelError::InvalidMotive(format!(
530 "'{inductive_name}' is registered with no constructors, but the kernel's \
531 literal rule produces values of it — so a `match` on one is not `ex falso`: \
532 it would prove its motive from a value that demonstrably exists. Give \
533 '{inductive_name}' its constructors"
534 )));
535 }
536
537 let disc_args = extract_type_args(&disc_type);
543 let num_params = ctx
544 .inductive_num_params(&inductive_name)
545 .min(disc_args.len());
546 if disc_args.len() > num_params {
547 return infer_indexed_match(
548 ctx,
549 discriminant,
550 motive,
551 cases,
552 &disc_type,
553 &inductive_name,
554 num_params,
555 &disc_args,
556 );
557 }
558
559 let motive_type = infer_type(ctx, motive)?;
564 let effective_motive = match &motive_type {
565 Term::Pi {
566 param,
567 param_type,
568 body_type,
569 } => {
570 if !def_eq(ctx, param_type, &disc_type) {
574 return Err(KernelError::InvalidMotive(format!(
575 "motive parameter {} doesn't match discriminant type {}",
576 param_type, disc_type
577 )));
578 }
579 let (param, body_type) = open_context_binder(ctx, param, param_type, body_type);
583 let motive_context = ctx.extend(¶m, (**param_type).clone());
584 let codomain = crate::reduction::normalize_checked(&motive_context, &body_type)
585 .map_err(|reason| {
586 KernelError::CertificationError(format!(
587 "motive codomain normalization unfinished: {reason:?}"
588 ))
589 })?;
590 if !matches!(codomain, Term::Sort(_)) {
591 return Err(KernelError::InvalidMotive(format!(
592 "motive type codomain {} is not a sort",
593 body_type
594 )));
595 }
596 (**motive).clone()
598 }
599 Term::Sort(_) => {
600 Term::Lambda {
603 param: "_".to_string(),
604 param_type: Box::new(disc_type.clone()),
605 body: motive.clone(),
606 }
607 }
608 _ => {
609 return Err(KernelError::InvalidMotive(format!(
610 "motive {} is not a function or type",
611 motive
612 )));
613 }
614 };
615
616 let constructors = ctx.get_constructors(&inductive_name);
618 if cases.len() != constructors.len() {
619 return Err(KernelError::WrongNumberOfCases {
620 expected: constructors.len(),
621 found: cases.len(),
622 });
623 }
624
625 for (case, (ctor_name, _)) in cases.iter().zip(constructors.iter()) {
627 let (ctor_head, ctor_type) =
628 constructor_at_discriminant(ctx, ctor_name, &disc_type)?;
629 let expected_case_type =
630 compute_case_type(&effective_motive, &ctor_head, &ctor_type, &disc_type);
631 check_type(ctx, case, &expected_case_type)?;
632 }
633
634 let return_type =
638 beta_reduce(&Term::App(Box::new(effective_motive), discriminant.clone()));
639
640 let disc_sort = sort_of_type(ctx, &disc_type)?;
642 check_elimination(ctx, &inductive_name, &disc_sort, || {
643 sort_of_type(ctx, &return_type)
644 })?;
645
646 Ok(return_type)
647 }
648
649 Term::Lit(lit) => match lit {
651 Literal::Int(_) | Literal::BigInt(_) => Ok(Term::Global("Int".to_string())),
652 Literal::Nat(n) if *n < logicaffeine_base::BigInt::from_i64(0) => Err(
653 KernelError::CertificationError("a `Nat` literal must be non-negative".to_string()),
654 ),
655 Literal::Nat(_) => Ok(Term::Global("Nat".to_string())),
656 Literal::Float(_) => Ok(Term::Global("Float".to_string())),
657 Literal::Text(_) => Ok(Term::Global("Text".to_string())),
658 Literal::Duration(_) => Ok(Term::Global("Duration".to_string())),
659 Literal::Date(_) => Ok(Term::Global("Date".to_string())),
660 Literal::Moment(_) => Ok(Term::Global("Moment".to_string())),
661 },
662
663 Term::Hole => Err(KernelError::CannotInferHole),
666
667 Term::Fix { name, body } => {
674 let (name, body) = open_context_binder(ctx, name, body, body);
675 let structural_type = infer_fix_type_structurally(ctx, &body)
685 .map_err(|e| name_the_unreadable_fixpoint(&name, e))?;
686 if occurs_free(&structural_type, &name) {
687 return Err(KernelError::CertificationError(format!(
688 "the fixpoint `{name}`'s type mentions `{name}` itself"
689 )));
690 }
691
692 crate::termination::check_termination(ctx, &name, &body)?;
696
697 let extended = ctx.extend(&name, structural_type.clone());
699 let _ = infer_type(&extended, &body)?;
700
701 Ok(structural_type)
702 }
703
704 Term::MutualFix { defs, index } => {
709 if defs.is_empty() || *index >= defs.len() {
710 return Err(KernelError::CertificationError(
711 "mutual fixpoint with an empty block or out-of-range index".to_string(),
712 ));
713 }
714
715 let opened_defs = open_context_mutual(ctx, defs);
716 let defs = opened_defs.as_ref();
717 let mut types = Vec::with_capacity(defs.len());
719 for (name, body) in defs {
720 let ty = infer_fix_type_structurally(ctx, body)
721 .map_err(|e| name_the_unreadable_fixpoint(name, e))?;
722 if let Some((member, _)) = defs.iter().find(|(member, _)| occurs_free(&ty, member))
723 {
724 return Err(KernelError::CertificationError(format!(
725 "the mutual fixpoint `{name}`'s type mentions the block's `{member}`"
726 )));
727 }
728 types.push(ty);
729 }
730
731 crate::termination::check_termination_mutual(ctx, defs)?;
733
734 let mut extended = ctx.clone();
737 for ((name, _), ty) in defs.iter().zip(types.iter()) {
738 extended = extended.extend(name, ty.clone());
739 }
740 for (_, body) in defs {
741 let _ = infer_type(&extended, body)?;
742 }
743
744 Ok(types[*index].clone())
745 }
746
747 Term::Annotated { term, .. } => infer_type(ctx, term),
748 }
749}
750
751fn name_the_unreadable_fixpoint(name: &str, e: KernelError) -> KernelError {
766 match &e {
767 KernelError::UnboundVariable(v) if v == name => KernelError::CertificationError(format!(
768 "the fixpoint `{name}`'s result type cannot be read off its body: every route to it \
769 passes through the recursive call, whose type is the very thing being inferred. \
770 Give the recursion a `match` whose motive states the result type — that is the \
771 route this kernel reads a fixpoint's type by."
772 )),
773 _ => e,
774 }
775}
776
777fn infer_fix_type_structurally(ctx: &Context, term: &Term) -> KernelResult<Term> {
786 match term {
787 Term::Lambda {
788 param,
789 param_type,
790 body,
791 } => {
792 let _ = infer_sort(ctx, param_type)?;
794
795 let (param, body) = open_context_binder(ctx, param, param_type, body);
797 let extended = ctx.extend(¶m, (**param_type).clone());
798 let body_type = infer_fix_type_structurally(&extended, &body)?;
799
800 Ok(Term::Pi {
802 param: param.into_owned(),
803 param_type: param_type.clone(),
804 body_type: Box::new(body_type),
805 })
806 }
807 Term::Match {
816 discriminant,
817 motive,
818 ..
819 } => {
820 if let Ok(mt) = infer_type(ctx, motive) {
827 if matches!(normalize(ctx, &mt), Term::Sort(_)) {
828 return Ok(normalize(ctx, motive));
829 }
830 }
831 let mut applied = (**motive).clone();
832 if let Ok(dt) = infer_type(ctx, discriminant) {
833 let dt = normalize(ctx, &dt);
834 if let Some(ind) = extract_inductive_name(ctx, &dt) {
835 let args = extract_type_args(&dt);
836 let p = ctx.inductive_num_params(&ind).min(args.len());
837 for idx in &args[p..] {
838 applied = Term::App(Box::new(applied), Box::new(idx.clone()));
839 }
840 }
841 }
842 applied = Term::App(Box::new(applied), discriminant.clone());
843 Ok(normalize(ctx, &applied))
844 }
845 Term::App(..) if matches!(spine_of(term).0, Term::Match { .. }) => {
848 let (head, args) = spine_of(term);
849 let mut ty = infer_fix_type_structurally(ctx, head)?;
850 for arg in args {
851 match demanded_type_head(ctx, ty, TypeHead::Function) {
852 Term::Pi {
853 param, body_type, ..
854 } => ty = substitute(&body_type, ¶m, arg),
855 other => return Err(KernelError::NotAFunction(format!("{other}"))),
856 }
857 }
858 Ok(normalize(ctx, &ty))
859 }
860 _ => infer_type(ctx, term),
862 }
863}
864
865pub(crate) fn check_type(ctx: &Context, term: &Term, expected: &Term) -> KernelResult<()> {
871 if let Term::Fix { name, body } = term {
884 let (name, body) = open_context_binder(ctx, name, body, body);
885 if crate::termination::check_termination(ctx, &name, &body).is_ok() {
886 let scoped = ctx.extend(&name, expected.clone());
887 if matches!(infer_type(&scoped, &body), Ok(got) if is_subtype(&scoped, &got, expected))
888 {
889 return Ok(());
890 }
891 }
892 }
893
894 if let Term::Lambda {
897 param,
898 param_type,
899 body,
900 } = term
901 {
902 if let Term::Global(name) = param_type.as_ref() {
904 if name == "_" {
905 if let Term::Pi {
907 param_type: expected_param_type,
908 body_type: expected_body_type,
909 param: expected_param,
910 } = expected
911 {
912 let fresh = fresh_context_name(
914 ctx,
915 param,
916 &[expected_param_type, expected_body_type, body],
917 );
918 let body = rename_var(body, param, &fresh);
919 let extended_ctx = ctx.extend(&fresh, (**expected_param_type).clone());
920 let body_expected =
921 substitute(expected_body_type, expected_param, &Term::Var(fresh));
922 return check_type(&extended_ctx, &body, &body_expected);
923 }
924 }
925 }
926 }
927
928 let inferred = infer_type(ctx, term)?;
929 if is_subtype(ctx, &inferred, expected) {
930 Ok(())
931 } else {
932 Err(KernelError::TypeMismatch {
933 expected: format!("{}", expected),
934 found: format!("{}", inferred),
935 })
936 }
937}
938
939fn normalized_inferred_sort(ctx: &Context, term: &Term, inferred: &Term) -> KernelResult<Universe> {
941 let normalized = crate::reduction::normalize_checked(ctx, inferred).map_err(|reason| {
942 KernelError::CertificationError(format!(
943 "sort inference did not finish normalization: {reason:?}"
944 ))
945 })?;
946 match normalized {
947 Term::Sort(universe) => Ok(universe),
948 _ => Err(KernelError::NotAType(format!("{}", term))),
949 }
950}
951
952pub(crate) fn infer_type_as_type(ctx: &Context, term: &Term) -> KernelResult<Term> {
955 let inferred = infer_type(ctx, term)?;
956 if !matches!(&inferred, Term::Sort(_)) {
957 normalized_inferred_sort(ctx, term, &inferred)?;
958 }
959 Ok(inferred)
960}
961
962pub(crate) fn infer_sort(ctx: &Context, term: &Term) -> KernelResult<Universe> {
966 let inferred = infer_type(ctx, term)?;
967 match inferred {
968 Term::Sort(universe) => Ok(universe),
969 other => normalized_inferred_sort(ctx, term, &other),
970 }
971}
972
973fn result_sort_universe(t: &Term) -> Option<Universe> {
975 let mut cur = t;
976 while let Term::Pi { body_type, .. } = cur {
977 cur = body_type;
978 }
979 match cur {
980 Term::Sort(u) => Some(u.clone()),
981 _ => None,
982 }
983}
984
985pub(crate) fn constructor_target_universe(
987 ind: &str,
988 normalized_arity: &Term,
989) -> KernelResult<Universe> {
990 result_sort_universe(normalized_arity).ok_or_else(|| {
991 KernelError::InvalidDeclaration(format!(
992 "inductive '{ind}' must have a telescope ending in Sort"
993 ))
994 })
995}
996
997fn stores_any_sort(target: &Universe) -> bool {
1002 *target == Universe::SProp || target.equiv(&Universe::Prop)
1003}
1004
1005pub(crate) fn check_constructor_field_universe(
1007 ctx: &Context,
1008 ind: &str,
1009 ctor: &str,
1010 field: &Term,
1011 target: &Universe,
1012) -> KernelResult<()> {
1013 if stores_any_sort(target) {
1014 return Ok(());
1015 }
1016 let sort = infer_sort(ctx, field)?;
1017 if !sort.is_subtype_of(target) {
1018 return Err(KernelError::InvalidDeclaration(format!(
1019 "universe inconsistency: constructor '{ctor}' stores an argument in sort \
1020 {sort}, which exceeds the sort {target} of its inductive '{ind}'"
1021 )));
1022 }
1023 Ok(())
1024}
1025
1026pub fn check_constructor_universes(
1033 ctx: &Context,
1034 ind: &str,
1035 ctor: &str,
1036 ty: &Term,
1037) -> KernelResult<()> {
1038 let Some(ind_ty) = ctx.get_global(ind) else {
1039 return Ok(());
1040 };
1041 let normal = |term: &Term| {
1042 crate::reduction::normalize_checked(ctx, term).map_err(|error|
1043 KernelError::CertificationError(format!(
1044 "constructor '{ctor}' of '{ind}': universe telescope normalization unfinished: {error:?}"
1045 )))
1046 };
1047 let target = constructor_target_universe(ind, &normal(ind_ty)?)?;
1048 if stores_any_sort(&target) {
1049 return Ok(());
1050 }
1051 let mut cur = normal(ty)?;
1052 let num_params = ctx.inductive_num_params(ind);
1053 let mut ext = ctx.clone();
1054 let mut i = 0usize;
1055 while let Term::Pi {
1056 param,
1057 param_type,
1058 body_type,
1059 } = cur
1060 {
1061 if i >= num_params {
1062 check_constructor_field_universe(&ext, ind, ctor, ¶m_type, &target)?;
1063 }
1064 let mut fresh = format!("__constructor_universe_local_{i}");
1065 while ext.local_name_in_use(&fresh) {
1066 fresh.push('_');
1067 }
1068 cur = substitute(&body_type, ¶m, &Term::Var(fresh.clone()));
1069 ext = ext.extend(&fresh, *param_type);
1070 i += 1;
1071 }
1072 Ok(())
1073}
1074
1075fn beta_reduce(term: &Term) -> Term {
1079 match term {
1080 Term::App(func, arg) => {
1081 match func.as_ref() {
1082 Term::Lambda { param, body, .. } => {
1083 substitute(body, param, arg)
1085 }
1086 _ => term.clone(),
1087 }
1088 }
1089 _ => term.clone(),
1090 }
1091}
1092
1093fn constructor_at_discriminant(
1095 ctx: &Context,
1096 name: &str,
1097 disc_type: &Term,
1098) -> KernelResult<(Term, Term)> {
1099 let mut head = disc_type;
1100 while let Term::App(f, _) = head {
1101 head = f;
1102 }
1103 let constructor = match head {
1104 Term::Const { levels, .. } if ctx.poly_declaration(name).is_some() => Term::Const {
1105 name: name.to_string(),
1106 levels: levels.clone(),
1107 },
1108 _ => Term::Global(name.to_string()),
1109 };
1110 let ty = infer_type(ctx, &constructor)?;
1111 Ok((constructor, ty))
1112}
1113
1114fn validate_indexed_motive(
1119 ctx: &Context,
1120 motive: &Term,
1121 disc_type: &Term,
1122 num_params: usize,
1123 disc_args: &[Term],
1124) -> KernelResult<()> {
1125 fn head(ctx: &Context, ty: Term) -> KernelResult<Term> {
1126 if matches!(ty, Term::Pi { .. } | Term::Sort(_)) {
1127 return Ok(ty);
1128 }
1129 crate::reduction::normalize_checked(ctx, &ty).map_err(|reason| {
1130 KernelError::CertificationError(format!(
1131 "indexed motive telescope normalization unfinished: {reason:?}"
1132 ))
1133 })
1134 }
1135 let error = |message: &str| KernelError::InvalidMotive(message.to_string());
1136 let (family_head, _) = spine_of(disc_type);
1137 let mut family = family_head.clone();
1138 let mut arity = infer_type(ctx, family_head)?;
1139 for parameter in &disc_args[..num_params] {
1140 let Term::Pi {
1141 param, body_type, ..
1142 } = head(ctx, arity)?
1143 else {
1144 return Err(error(
1145 "inductive has fewer parameters than its discriminant",
1146 ));
1147 };
1148 arity = substitute(&body_type, ¶m, parameter);
1149 family = Term::App(Box::new(family), Box::new(parameter.clone()));
1150 }
1151 let mut motive_type = infer_type(ctx, motive)?;
1152 let mut inner = ctx.clone();
1153 let mut avoid = free_vars(motive);
1154 avoid.extend(free_vars(disc_type));
1155 for index in 0..disc_args.len() - num_params {
1156 let Term::Pi {
1157 param,
1158 param_type,
1159 body_type,
1160 } = head(&inner, arity)?
1161 else {
1162 return Err(error(
1163 "inductive index telescope is shorter than its discriminant",
1164 ));
1165 };
1166 let Term::Pi {
1167 param: actual_param,
1168 param_type: actual_domain,
1169 body_type: actual_body,
1170 } = head(&inner, motive_type)?
1171 else {
1172 return Err(error("indexed motive lacks an index binder"));
1173 };
1174 if !def_eq(&inner, &actual_domain, ¶m_type) {
1175 return Err(error(
1176 "indexed motive index domain differs from the inductive telescope",
1177 ));
1178 }
1179 let mut name = fresh_name(&format!("__motive_index{index}"), &avoid);
1180 while inner.local_name_in_use(&name) {
1181 name.push('_');
1182 }
1183 avoid.insert(name.clone());
1184 let variable = Term::Var(name.clone());
1185 arity = substitute(&body_type, ¶m, &variable);
1186 motive_type = substitute(&actual_body, &actual_param, &variable);
1187 family = Term::App(Box::new(family), Box::new(variable));
1188 inner = inner.extend(&name, *param_type);
1189 }
1190 if !matches!(head(&inner, arity)?, Term::Sort(_)) {
1191 return Err(error(
1192 "discriminant does not instantiate the full inductive index telescope",
1193 ));
1194 }
1195 let Term::Pi {
1196 param,
1197 param_type,
1198 body_type,
1199 } = head(&inner, motive_type)?
1200 else {
1201 return Err(error("indexed motive lacks its major-premise binder"));
1202 };
1203 if !def_eq(&inner, ¶m_type, &family) {
1204 return Err(error(
1205 "indexed motive major domain differs from the generic indexed family",
1206 ));
1207 }
1208 let mut major = fresh_name("__motive_major", &avoid);
1209 while inner.local_name_in_use(&major) {
1210 major.push('_');
1211 }
1212 let codomain = substitute(&body_type, ¶m, &Term::Var(major.clone()));
1213 inner = inner.extend(&major, family);
1214 if !matches!(head(&inner, codomain)?, Term::Sort(_)) {
1215 return Err(error(
1216 "indexed motive must return a sort after its major-premise binder",
1217 ));
1218 }
1219 Ok(())
1220}
1221
1222#[allow(clippy::too_many_arguments)]
1227fn infer_indexed_match(
1228 ctx: &Context,
1229 discriminant: &Term,
1230 motive: &Term,
1231 cases: &[Term],
1232 disc_type: &Term,
1233 inductive_name: &str,
1234 num_params: usize,
1235 disc_args: &[Term],
1236) -> KernelResult<Term> {
1237 let disc_params = &disc_args[0..num_params];
1240 let disc_indices = &disc_args[num_params..];
1241
1242 validate_indexed_motive(ctx, motive, disc_type, num_params, disc_args)?;
1246
1247 let constructors = ctx.get_constructors(inductive_name);
1253 let owed: Vec<(&str, &Term)> = if cases.len() == constructors.len() {
1254 constructors.iter().map(|(n, t)| (*n, *t)).collect()
1255 } else {
1256 let allowed = constructors_the_indices_allow(ctx, inductive_name, num_params, disc_args);
1257 if cases.len() != allowed.len() {
1258 return Err(KernelError::WrongNumberOfCases {
1259 expected: allowed.len(),
1260 found: cases.len(),
1261 });
1262 }
1263 allowed
1264 .iter()
1265 .map(|&i| (constructors[i].0, constructors[i].1))
1266 .collect()
1267 };
1268
1269 for (case, (ctor_name, _)) in cases.iter().zip(owed.iter()) {
1271 let (ctor_head, ctor_type) = constructor_at_discriminant(ctx, ctor_name, disc_type)?;
1272 let expected =
1273 compute_indexed_case_type(motive, &ctor_head, &ctor_type, num_params, disc_params);
1274 check_type(ctx, case, &expected)?;
1275 }
1276
1277 let mut ret = motive.clone();
1279 for idx in disc_indices {
1280 ret = Term::App(Box::new(ret), Box::new(idx.clone()));
1281 }
1282 ret = Term::App(Box::new(ret), Box::new(discriminant.clone()));
1283 let ret = normalize(ctx, &ret);
1284
1285 match normalize(ctx, &infer_type(ctx, &ret)?) {
1288 Term::Sort(_) => {}
1289 other => {
1290 return Err(KernelError::InvalidMotive(format!(
1291 "indexed match on '{}' has non-type result {} — the motive is not a family into a sort",
1292 inductive_name, other
1293 )));
1294 }
1295 }
1296
1297 let disc_sort = sort_of_type(ctx, disc_type)?;
1298 check_elimination(ctx, inductive_name, &disc_sort, || sort_of_type(ctx, &ret))?;
1299
1300 Ok(ret)
1301}
1302
1303fn sort_of_type(ctx: &Context, ty: &Term) -> KernelResult<Universe> {
1305 match normalize(ctx, &infer_type(ctx, ty)?) {
1306 Term::Sort(u) => Ok(u),
1307 other => Err(KernelError::InvalidMotive(format!(
1308 "{ty} is not a type: its type is {other}"
1309 ))),
1310 }
1311}
1312
1313fn check_elimination(
1331 ctx: &Context,
1332 inductive_name: &str,
1333 disc: &Universe,
1334 ret: impl FnOnce() -> KernelResult<Universe>,
1335) -> KernelResult<()> {
1336 if disc.is_never_prop() {
1337 return Ok(());
1338 }
1339 let ret = &ret()?;
1340 if matches!(disc, Universe::SProp) && !matches!(ret, Universe::SProp) {
1341 return Err(KernelError::InvalidMotive(format!(
1342 "elimination of the definitionally-irrelevant proposition '{inductive_name}' \
1343 into a relevant sort is not allowed: every inhabitant of an SProp is \
1344 definitionally equal, so a match on one would equate its branches"
1345 )));
1346 }
1347 let (large, instance) = if disc.equiv(&Universe::Prop) {
1348 (!ret.equiv(&Universe::Prop), "")
1349 } else {
1350 (
1351 !ret.is_subtype_of(disc),
1352 " (a proposition at some instance of its universe levels)",
1353 )
1354 };
1355 if large && !is_subsingleton_prop(ctx, inductive_name)? {
1356 return Err(KernelError::InvalidMotive(format!(
1357 "large elimination of proposition '{inductive_name}'{instance} into a larger sort is not \
1358 allowed: only subsingleton propositions (empty, or one constructor with propositional \
1359 arguments — e.g. False, And, eq) may be eliminated into Type"
1360 )));
1361 }
1362 Ok(())
1363}
1364
1365fn compute_indexed_case_type(
1371 motive: &Term,
1372 ctor_head: &Term,
1373 ctor_type: &Term,
1374 num_params: usize,
1375 disc_params: &[Term],
1376) -> Term {
1377 let mut current = ctor_type.clone();
1381 for arg in disc_params.iter().take(num_params) {
1382 if let Term::Pi {
1383 param, body_type, ..
1384 } = current
1385 {
1386 current = substitute(&body_type, ¶m, arg);
1387 } else {
1388 break;
1389 }
1390 }
1391 let mut avoid = free_vars(motive);
1392 avoid.extend(free_vars(¤t));
1393 for arg in disc_params {
1394 avoid.extend(free_vars(arg));
1395 }
1396 let mut fields = Vec::new();
1397 while let Term::Pi {
1398 param,
1399 param_type,
1400 body_type,
1401 } = current
1402 {
1403 let fresh = fresh_name(&format!("__arg{}", fields.len()), &avoid);
1404 avoid.insert(fresh.clone());
1405 current = substitute(&body_type, ¶m, &Term::Var(fresh.clone()));
1406 fields.push((fresh, *param_type));
1407 }
1408 let mut ctor_applied = ctor_head.clone();
1409 for arg in disc_params {
1410 ctor_applied = Term::App(Box::new(ctor_applied), Box::new(arg.clone()));
1411 }
1412 for (field, _) in &fields {
1413 ctor_applied = Term::App(Box::new(ctor_applied), Box::new(Term::Var(field.clone())));
1414 }
1415 let mut result = motive.clone();
1416 for index in extract_type_args(¤t).into_iter().skip(num_params) {
1417 result = Term::App(Box::new(result), Box::new(index));
1418 }
1419 result = beta_reduce(&Term::App(Box::new(result), Box::new(ctor_applied)));
1420 for (param, domain) in fields.into_iter().rev() {
1421 result = Term::Pi {
1422 param,
1423 param_type: Box::new(beta_reduce(&domain)),
1424 body_type: Box::new(result),
1425 };
1426 }
1427 result
1428}
1429
1430fn compute_case_type(motive: &Term, ctor_head: &Term, ctor_type: &Term, disc_type: &Term) -> Term {
1432 let parameters = extract_type_args(disc_type);
1433 compute_indexed_case_type(motive, ctor_head, ctor_type, parameters.len(), ¶meters)
1434}
1435
1436fn extract_type_args(ty: &Term) -> Vec<Term> {
1442 let mut args = Vec::new();
1443 let mut current = ty;
1444
1445 while let Term::App(func, arg) = current {
1446 args.push((**arg).clone());
1447 current = func;
1448 }
1449
1450 args.reverse();
1451 args
1452}
1453
1454pub fn substitute(body: &Term, var: &str, replacement: &Term) -> Term {
1472 if !occurs_free(body, var) {
1479 return body.clone();
1480 }
1481 let replacement_fvs = free_vars(replacement);
1484 substitute_avoiding(body, var, replacement, &replacement_fvs)
1485}
1486
1487const UNTRUSTED_AXIOMS: &[&str] = &[
1503 "Classical_choice",
1504 "propext",
1505 "Quot_sound",
1506 "sorryAx",
1507 "em",
1508 "choice",
1509];
1510
1511pub(crate) fn unbound_diagnosis(name: &str) -> Option<String> {
1515 if crate::elaborate::is_meta(name) {
1516 return Some(format!(
1517 "E_UNINSTANTIATED_METAVARIABLE: the metavariable '{name}' reached the kernel \
1518 without a solution. Elaboration must instantiate every metavariable before the \
1519 term is checked; a `?`-named variable is not a name the kernel can look up, and \
1520 guessing one is a soundness decision disguised as a convenience",
1521 ));
1522 }
1523 if UNTRUSTED_AXIOMS.contains(&name) {
1524 let admission = matches!(name, "sorryAx");
1525 return Some(format!(
1526 "{}: '{name}' is not in LOGOS's trusted base. {}",
1527 if admission {
1528 "E_INCOMPLETE_PROOF"
1529 } else {
1530 "E_UNTRUSTED_AXIOM"
1531 },
1532 if admission {
1533 "This proof is INCOMPLETE — it rests on an admission (`sorry`), which is an \
1534 axiom that proves everything. Adding the axiom to the prelude would make the \
1535 admission invisible to every certificate minted afterwards"
1536 } else {
1537 "Checking this term would enlarge the trusted base. Adding the axiom to \
1538 `StandardLibrary::register` is the one repair that must not be made: the \
1539 prelude version would still describe the axiom set the certificate was NOT \
1540 checked against"
1541 },
1542 ));
1543 }
1544 None
1545}
1546
1547fn classify_unbound(name: &str) -> KernelError {
1549 match unbound_diagnosis(name) {
1550 Some(msg) => KernelError::CertificationError(msg),
1551 None => KernelError::UnboundVariable(name.to_string()),
1552 }
1553}
1554
1555fn lookup_const(ctx: &Context, name: &str) -> Option<(Option<Vec<String>>, Term)> {
1578 if let Some((params, ty)) = ctx.poly_declaration(name) {
1579 return Some((Some(params.to_vec()), ty.clone()));
1580 }
1581 let ty = ctx.get_global(name)?;
1582 if !crate::term::mentions_level_var(ty) {
1591 return None;
1592 }
1593 Some((None, ty.clone()))
1594}
1595
1596pub(crate) fn implicit_levels_for_head(func: &Term, func_type: Term) -> Term {
1612 let Term::Global(name) = func else {
1613 return func_type;
1614 };
1615 if !crate::term::mentions_level_var(&func_type) {
1619 return func_type;
1620 }
1621 let params = crate::term::free_level_vars(&func_type);
1622 if params.is_empty() {
1623 return func_type;
1624 }
1625 let subst = crate::term::fresh_level_metas(name, ¶ms);
1626 crate::term::instantiate_universes(&func_type, &subst)
1627}
1628
1629fn solve_domain_levels(
1637 ctx: &Context,
1638 param_type: &Term,
1639 body_type: &Term,
1640 arg: &Term,
1641) -> Option<(Term, Term)> {
1642 let subst = domain_level_solution(ctx, param_type, arg)?;
1643 Some((
1644 crate::term::instantiate_universes(param_type, &subst),
1645 crate::term::instantiate_universes(body_type, &subst),
1646 ))
1647}
1648
1649fn domain_level_solution(
1654 ctx: &Context,
1655 param_type: &Term,
1656 arg: &Term,
1657) -> Option<std::collections::HashMap<String, Universe>> {
1658 if !crate::term::mentions_level_meta(param_type) {
1659 return None;
1660 }
1661 let arg_type = infer_type(ctx, arg).ok()?;
1665 let arg_type = match arg_type {
1666 Term::Sort(_) => arg_type,
1667 other => normalize(ctx, &other),
1668 };
1669 let mut subst = std::collections::HashMap::new();
1670 crate::term::unify_levels(param_type, &arg_type, &mut subst);
1671 (!subst.is_empty()).then_some(subst)
1672}
1673
1674fn is_atomic(t: &Term) -> bool {
1676 matches!(
1677 t,
1678 Term::Var(_)
1679 | Term::Global(_)
1680 | Term::Sort(_)
1681 | Term::Lit(_)
1682 | Term::Const { .. }
1683 | Term::Hole
1684 )
1685}
1686
1687const SHARE_MIN_ARGUMENT_NODES: usize = 16;
1693
1694fn size_exceeds(t: &Term, limit: usize) -> bool {
1701 fn walk(t: &Term, left: &mut usize) -> bool {
1702 if *left == 0 {
1703 return true;
1704 }
1705 *left -= 1;
1706 match t {
1707 Term::Var(_) | Term::Global(_) | Term::Sort(_) | Term::Lit(_) | Term::Hole => false,
1708 Term::Const { .. } => false,
1709 Term::App(f, a) => walk(f, left) || walk(a, left),
1710 Term::Pi {
1711 param_type,
1712 body_type,
1713 ..
1714 } => walk(param_type, left) || walk(body_type, left),
1715 Term::Lambda {
1716 param_type, body, ..
1717 } => walk(param_type, left) || walk(body, left),
1718 Term::Fix { body, .. } => walk(body, left),
1719 Term::MutualFix { defs, .. } => defs.iter().any(|(_, b)| walk(b, left)),
1720 Term::Let {
1721 ty, value, body, ..
1722 } => walk(ty, left) || walk(value, left) || walk(body, left),
1723 Term::Match {
1724 discriminant,
1725 motive,
1726 cases,
1727 } => {
1728 walk(discriminant, left)
1729 || walk(motive, left)
1730 || cases.iter().any(|c| walk(c, left))
1731 }
1732 Term::Annotated { term, .. } => {
1733 *left += 1;
1734 walk(term, left)
1735 }
1736 }
1737 }
1738 let mut left = limit;
1739 walk(t, &mut left)
1740}
1741
1742fn node_count(t: &Term) -> usize {
1744 match t {
1745 Term::Var(_) | Term::Global(_) | Term::Sort(_) | Term::Lit(_) | Term::Hole => 1,
1746 Term::Const { .. } => 1,
1747 Term::App(f, a) => 1 + node_count(f) + node_count(a),
1748 Term::Pi {
1749 param_type,
1750 body_type,
1751 ..
1752 } => 1 + node_count(param_type) + node_count(body_type),
1753 Term::Lambda {
1754 param_type, body, ..
1755 } => 1 + node_count(param_type) + node_count(body),
1756 Term::Fix { body, .. } => 1 + node_count(body),
1757 Term::MutualFix { defs, .. } => 1 + defs.iter().map(|(_, b)| node_count(b)).sum::<usize>(),
1758 Term::Let {
1759 ty, value, body, ..
1760 } => 1 + node_count(ty) + node_count(value) + node_count(body),
1761 Term::Match {
1762 discriminant,
1763 motive,
1764 cases,
1765 } => {
1766 1 + node_count(discriminant)
1767 + node_count(motive)
1768 + cases.iter().map(node_count).sum::<usize>()
1769 }
1770 Term::Annotated { term, .. } => node_count(term),
1771 }
1772}
1773
1774fn body_stats(term: &Term, var: &str) -> (usize, usize) {
1777 match term {
1778 Term::Var(name) => (usize::from(name == var), 1),
1779 Term::Global(_) | Term::Sort(_) | Term::Lit(_) | Term::Hole | Term::Const { .. } => (0, 1),
1780 Term::App(f, a) => {
1781 let (o1, s1) = body_stats(f, var);
1782 let (o2, s2) = body_stats(a, var);
1783 (o1 + o2, 1 + s1 + s2)
1784 }
1785 Term::Pi {
1786 param,
1787 param_type,
1788 body_type,
1789 } => {
1790 let (o1, s1) = body_stats(param_type, var);
1791 let (o2, s2) = body_stats(body_type, var);
1792 (o1 + if param == var { 0 } else { o2 }, 1 + s1 + s2)
1793 }
1794 Term::Lambda {
1795 param,
1796 param_type,
1797 body,
1798 } => {
1799 let (o1, s1) = body_stats(param_type, var);
1800 let (o2, s2) = body_stats(body, var);
1801 (o1 + if param == var { 0 } else { o2 }, 1 + s1 + s2)
1802 }
1803 Term::Fix { name, body } => {
1804 let (o, s) = body_stats(body, var);
1805 (if name == var { 0 } else { o }, 1 + s)
1806 }
1807 Term::MutualFix { defs, .. } => {
1808 let shadowed = defs.iter().any(|(n, _)| n == var);
1809 let mut occ = 0;
1810 let mut size = 1;
1811 for (_, b) in defs {
1812 let (o, s) = body_stats(b, var);
1813 if !shadowed {
1814 occ += o;
1815 }
1816 size += s;
1817 }
1818 (occ, size)
1819 }
1820 Term::Let {
1821 name,
1822 ty,
1823 value,
1824 body,
1825 } => {
1826 let (o1, s1) = body_stats(ty, var);
1827 let (o2, s2) = body_stats(value, var);
1828 let (o3, s3) = body_stats(body, var);
1829 (o1 + o2 + if name == var { 0 } else { o3 }, 1 + s1 + s2 + s3)
1830 }
1831 Term::Match {
1832 discriminant,
1833 motive,
1834 cases,
1835 } => {
1836 let (o1, s1) = body_stats(discriminant, var);
1837 let (o2, s2) = body_stats(motive, var);
1838 let mut occ = o1 + o2;
1839 let mut size = 1 + s1 + s2;
1840 for c in cases {
1841 let (o, s) = body_stats(c, var);
1842 occ += o;
1843 size += s;
1844 }
1845 (occ, size)
1846 }
1847 Term::Annotated { term, .. } => body_stats(term, var),
1848 }
1849}
1850
1851pub fn instantiate_codomain(param: &str, domain: &Term, body: &Term, argument: &Term) -> Term {
1869 expose_head(substitute_shared(body, param, domain, argument))
1870}
1871
1872fn substitute_shared(body: &Term, var: &str, var_type: &Term, replacement: &Term) -> Term {
1873 if is_atomic(replacement) {
1880 return substitute(body, var, replacement);
1881 }
1882 if !occurs_free(body, var) {
1883 return body.clone();
1884 }
1885 if !size_exceeds(replacement, SHARE_MIN_ARGUMENT_NODES) {
1886 return substitute(body, var, replacement);
1887 }
1888 let (occurrences, body_size) = body_stats(body, var);
1889 let repl_size = node_count(replacement);
1890 if (occurrences - 1) * repl_size <= body_size + repl_size {
1891 return substitute(body, var, replacement);
1892 }
1893 Term::Let {
1894 name: var.to_string(),
1895 ty: Box::new(var_type.clone()),
1896 value: Box::new(replacement.clone()),
1897 body: Box::new(body.clone()),
1898 }
1899}
1900
1901fn expose_head(t: Term) -> Term {
1919 let Term::Let {
1920 name,
1921 ty,
1922 value,
1923 body,
1924 } = t
1925 else {
1926 return head_beta(t);
1929 };
1930 match expose_head(*body) {
1931 Term::Pi {
1932 param,
1933 param_type,
1934 body_type,
1935 } => {
1936 let mut value_fvs = free_vars(&value);
1939 value_fvs.insert(name.clone());
1942 let (param, body_type) = if param == name || value_fvs.contains(¶m) {
1943 let fresh = fresh_name(¶m, &value_fvs);
1944 let renamed = substitute(&body_type, ¶m, &Term::Var(fresh.clone()));
1945 (fresh, renamed)
1946 } else {
1947 (param, *body_type)
1948 };
1949 let new_domain = substitute(¶m_type, &name, &value);
1950 let new_codomain = if occurs_free(&body_type, &name) {
1951 Term::Let {
1952 name,
1953 ty,
1954 value,
1955 body: Box::new(body_type),
1956 }
1957 } else {
1958 body_type
1959 };
1960 Term::Pi {
1961 param,
1962 param_type: Box::new(new_domain),
1963 body_type: Box::new(new_codomain),
1964 }
1965 }
1966 other => head_beta(substitute(&other, &name, &value)),
1967 }
1968}
1969
1970const MAX_HEAD_BETA_STEPS: usize = 4096;
1975
1976fn head_beta(t: Term) -> Term {
1980 fn head_is_lambda(mut t: &Term) -> bool {
1981 while let Term::App(f, _) = t {
1982 t = f;
1983 }
1984 matches!(t, Term::Lambda { .. })
1985 }
1986 if !matches!(t, Term::App(..)) || !head_is_lambda(&t) {
1987 return t;
1988 }
1989 let mut pending: Vec<Term> = Vec::new();
1991 let mut head = t;
1992 while let Term::App(f, a) = head {
1993 pending.push(*a);
1994 head = *f;
1995 }
1996 for _ in 0..MAX_HEAD_BETA_STEPS {
1997 let Term::Lambda {
1998 param,
1999 param_type,
2000 body,
2001 } = head
2002 else {
2003 break;
2004 };
2005 let Some(argument) = pending.pop() else {
2006 head = Term::Lambda {
2007 param,
2008 param_type,
2009 body,
2010 };
2011 break;
2012 };
2013 head = substitute(&body, ¶m, &argument);
2014 while let Term::App(f, a) = head {
2015 pending.push(*a);
2016 head = *f;
2017 }
2018 }
2019 pending
2020 .into_iter()
2021 .rev()
2022 .fold(head, |f, a| Term::App(Box::new(f), Box::new(a)))
2023}
2024
2025pub(crate) fn occurs_free(term: &Term, var: &str) -> bool {
2027 match term {
2028 Term::Var(name) => name == var,
2029 Term::Sort(_) | Term::Lit(_) | Term::Hole | Term::Global(_) | Term::Const { .. } => false,
2030 Term::App(func, arg) => occurs_free(func, var) || occurs_free(arg, var),
2031 Term::Pi {
2032 param,
2033 param_type,
2034 body_type,
2035 } => occurs_free(param_type, var) || (param != var && occurs_free(body_type, var)),
2036 Term::Lambda {
2037 param,
2038 param_type,
2039 body,
2040 } => occurs_free(param_type, var) || (param != var && occurs_free(body, var)),
2041 Term::Fix { name, body } => name != var && occurs_free(body, var),
2042 Term::MutualFix { defs, .. } => {
2043 !defs.iter().any(|(n, _)| n == var) && defs.iter().any(|(_, b)| occurs_free(b, var))
2046 }
2047 Term::Let {
2048 name,
2049 ty,
2050 value,
2051 body,
2052 } => {
2053 occurs_free(ty, var)
2054 || occurs_free(value, var)
2055 || (name != var && occurs_free(body, var))
2056 }
2057 Term::Match {
2058 discriminant,
2059 motive,
2060 cases,
2061 } => {
2062 occurs_free(discriminant, var)
2063 || occurs_free(motive, var)
2064 || cases.iter().any(|c| occurs_free(c, var))
2065 }
2066 Term::Annotated { term, .. } => occurs_free(term, var),
2067 }
2068}
2069
2070pub(crate) fn free_vars(term: &Term) -> std::collections::HashSet<String> {
2072 fn go(term: &Term, bound: &mut Vec<String>, acc: &mut std::collections::HashSet<String>) {
2073 match term {
2074 Term::Var(name) => {
2075 if !bound.iter().any(|b| b == name) {
2076 acc.insert(name.clone());
2077 }
2078 }
2079 Term::Sort(_) | Term::Lit(_) | Term::Hole | Term::Global(_) | Term::Const { .. } => {}
2080 Term::App(func, arg) => {
2081 go(func, bound, acc);
2082 go(arg, bound, acc);
2083 }
2084 Term::Pi {
2085 param,
2086 param_type,
2087 body_type,
2088 } => {
2089 go(param_type, bound, acc);
2090 bound.push(param.clone());
2091 go(body_type, bound, acc);
2092 bound.pop();
2093 }
2094 Term::Lambda {
2095 param,
2096 param_type,
2097 body,
2098 } => {
2099 go(param_type, bound, acc);
2100 bound.push(param.clone());
2101 go(body, bound, acc);
2102 bound.pop();
2103 }
2104 Term::Fix { name, body } => {
2105 bound.push(name.clone());
2106 go(body, bound, acc);
2107 bound.pop();
2108 }
2109 Term::MutualFix { defs, .. } => {
2110 for (n, _) in defs {
2111 bound.push(n.clone());
2112 }
2113 for (_, b) in defs {
2114 go(b, bound, acc);
2115 }
2116 for _ in defs {
2117 bound.pop();
2118 }
2119 }
2120 Term::Let {
2121 name,
2122 ty,
2123 value,
2124 body,
2125 } => {
2126 go(ty, bound, acc);
2127 go(value, bound, acc);
2128 bound.push(name.clone());
2129 go(body, bound, acc);
2130 bound.pop();
2131 }
2132 Term::Match {
2133 discriminant,
2134 motive,
2135 cases,
2136 } => {
2137 go(discriminant, bound, acc);
2138 go(motive, bound, acc);
2139 for c in cases {
2140 go(c, bound, acc);
2141 }
2142 }
2143 Term::Annotated { term, .. } => go(term, bound, acc),
2144 }
2145 }
2146 let mut acc = std::collections::HashSet::new();
2147 let mut bound = Vec::new();
2148 go(term, &mut bound, &mut acc);
2149 acc
2150}
2151
2152fn all_var_names(term: &Term, acc: &mut std::collections::HashSet<String>) {
2154 match term {
2155 Term::Var(name) => {
2156 acc.insert(name.clone());
2157 }
2158 Term::Sort(_) | Term::Lit(_) | Term::Hole | Term::Global(_) | Term::Const { .. } => {}
2159 Term::App(func, arg) => {
2160 all_var_names(func, acc);
2161 all_var_names(arg, acc);
2162 }
2163 Term::Pi {
2164 param,
2165 param_type,
2166 body_type,
2167 } => {
2168 acc.insert(param.clone());
2169 all_var_names(param_type, acc);
2170 all_var_names(body_type, acc);
2171 }
2172 Term::Lambda {
2173 param,
2174 param_type,
2175 body,
2176 } => {
2177 acc.insert(param.clone());
2178 all_var_names(param_type, acc);
2179 all_var_names(body, acc);
2180 }
2181 Term::Fix { name, body } => {
2182 acc.insert(name.clone());
2183 all_var_names(body, acc);
2184 }
2185 Term::MutualFix { defs, .. } => {
2186 for (n, b) in defs {
2187 acc.insert(n.clone());
2188 all_var_names(b, acc);
2189 }
2190 }
2191 Term::Let {
2192 name,
2193 ty,
2194 value,
2195 body,
2196 } => {
2197 acc.insert(name.clone());
2198 all_var_names(ty, acc);
2199 all_var_names(value, acc);
2200 all_var_names(body, acc);
2201 }
2202 Term::Match {
2203 discriminant,
2204 motive,
2205 cases,
2206 } => {
2207 all_var_names(discriminant, acc);
2208 all_var_names(motive, acc);
2209 for c in cases {
2210 all_var_names(c, acc);
2211 }
2212 }
2213 Term::Annotated { term, .. } => all_var_names(term, acc),
2214 }
2215}
2216
2217fn fresh_name(base: &str, avoid: &std::collections::HashSet<String>) -> String {
2219 let mut candidate = format!("{}'", base);
2220 let mut counter: u32 = 0;
2221 while avoid.contains(&candidate) {
2222 counter += 1;
2223 candidate = format!("{}'{}", base, counter);
2224 }
2225 candidate
2226}
2227
2228fn fresh_context_name(ctx: &Context, base: &str, terms: &[&Term]) -> String {
2230 let mut avoid = std::collections::HashSet::new();
2231 for term in terms {
2232 all_var_names(term, &mut avoid);
2233 }
2234 let mut name = fresh_name(base, &avoid);
2235 while avoid.contains(&name) || ctx.local_name_in_use(&name) {
2236 name.push('_');
2237 }
2238 name
2239}
2240
2241fn open_context_binder<'a>(
2244 ctx: &Context,
2245 name: &'a str,
2246 domain: &Term,
2247 body: &'a Term,
2248) -> (std::borrow::Cow<'a, str>, std::borrow::Cow<'a, Term>) {
2249 use std::borrow::Cow;
2250 if !binder_would_capture(ctx, name, domain) {
2251 return (Cow::Borrowed(name), Cow::Borrowed(body));
2252 }
2253 let fresh = fresh_context_name(ctx, name, &[domain, body]);
2254 let opened = rename_var(body, name, &fresh);
2255 (Cow::Owned(fresh), Cow::Owned(opened))
2256}
2257
2258fn binder_would_capture(ctx: &Context, name: &str, domain: &Term) -> bool {
2267 ctx.local_types_mention(name) || (ctx.has_local(name) && occurs_free(domain, name))
2268}
2269
2270fn open_context_mutual<'a>(
2272 ctx: &Context,
2273 defs: &'a [(String, Term)],
2274) -> std::borrow::Cow<'a, [(String, Term)]> {
2275 use std::borrow::Cow;
2276 if !defs.iter().any(|(name, _)| ctx.local_name_in_use(name)) {
2277 return Cow::Borrowed(defs);
2278 }
2279 let mut avoid = std::collections::HashSet::new();
2280 for (name, body) in defs {
2281 avoid.insert(name.clone());
2282 all_var_names(body, &mut avoid);
2283 }
2284 let mut replacements = Vec::new();
2285 for (name, _) in defs {
2286 if ctx.local_name_in_use(name) && !replacements.iter().any(|(old, _)| old == name) {
2287 let mut fresh = fresh_name(name, &avoid);
2288 while avoid.contains(&fresh) || ctx.local_name_in_use(&fresh) {
2289 fresh.push('_');
2290 }
2291 avoid.insert(fresh.clone());
2292 replacements.push((name.clone(), fresh));
2293 }
2294 }
2295 Cow::Owned(
2296 defs.iter()
2297 .map(|(name, body)| {
2298 let mut opened = body.clone();
2299 for (old, fresh) in &replacements {
2300 opened = rename_var(&opened, old, fresh);
2301 }
2302 let name = replacements
2303 .iter()
2304 .find(|(old, _)| old == name)
2305 .map_or_else(|| name.clone(), |(_, fresh)| fresh.clone());
2306 (name, opened)
2307 })
2308 .collect(),
2309 )
2310}
2311
2312fn freshen(
2315 param: &str,
2316 body: &Term,
2317 replacement_fvs: &std::collections::HashSet<String>,
2318 var: &str,
2319) -> String {
2320 let mut avoid = replacement_fvs.clone();
2321 all_var_names(body, &mut avoid);
2322 avoid.insert(var.to_string());
2323 fresh_name(param, &avoid)
2324}
2325
2326fn rename_var(term: &Term, from: &str, to: &str) -> Term {
2329 let repl = Term::Var(to.to_string());
2330 let mut fvs = std::collections::HashSet::new();
2331 fvs.insert(to.to_string());
2332 substitute_avoiding(term, from, &repl, &fvs)
2333}
2334
2335pub(crate) fn substitute_owned_value_counted(
2345 body: Term,
2346 var: &str,
2347 replacement: Term,
2348 occurrences: usize,
2349) -> Term {
2350 if occurrences == 0 {
2351 return body;
2352 }
2353 let free = free_vars(&replacement);
2354 let mut value = SubstitutionValue::Owned {
2355 term: Some(replacement),
2356 remaining: occurrences,
2357 };
2358 let result = substitute_input(SubstitutionInput::Owned(body), var, &mut value, &free);
2359 debug_assert!(matches!(
2360 value,
2361 SubstitutionValue::Owned { remaining: 0, .. }
2362 ));
2363 result
2364}
2365
2366pub(crate) fn substitute_owned_closed_value_counted(
2370 body: Term,
2371 var: &str,
2372 replacement: Term,
2373 occurrences: usize,
2374) -> Term {
2375 let remaining = occurrences;
2376 let mut value = SubstitutionValue::Owned {
2377 term: Some(replacement),
2378 remaining,
2379 };
2380 let result = substitute_input(
2381 SubstitutionInput::Owned(body),
2382 var,
2383 &mut value,
2384 &std::collections::HashSet::new(),
2385 );
2386 debug_assert!(matches!(
2387 value,
2388 SubstitutionValue::Owned { remaining: 0, .. }
2389 ));
2390 result
2391}
2392
2393enum SubstitutionValue<'a> {
2394 Borrowed(&'a Term),
2395 Owned {
2396 term: Option<Term>,
2397 remaining: usize,
2398 },
2399}
2400impl SubstitutionValue<'_> {
2401 fn materialize(&mut self) -> Term {
2402 match self {
2403 Self::Borrowed(term) => {
2404 #[cfg(test)]
2405 record_substitution_tree(term);
2406 (*term).clone()
2407 }
2408 Self::Owned { term, remaining } => {
2409 assert!(
2410 *remaining > 0,
2411 "lexical occurrence count must cover substitution"
2412 );
2413 *remaining -= 1;
2414 if *remaining == 0 {
2415 term.take().expect("owned replacement available")
2416 } else {
2417 let term = term.as_ref().expect("owned replacement retained");
2418 #[cfg(test)]
2419 record_substitution_tree(term);
2420 term.clone()
2421 }
2422 }
2423 }
2424 }
2425}
2426fn substitute_avoiding(
2427 body: &Term,
2428 var: &str,
2429 replacement: &Term,
2430 replacement_fvs: &std::collections::HashSet<String>,
2431) -> Term {
2432 substitute_input(
2433 SubstitutionInput::Borrowed(body),
2434 var,
2435 &mut SubstitutionValue::Borrowed(replacement),
2436 replacement_fvs,
2437 )
2438}
2439
2440pub(crate) fn substitute_owned(body: Term, var: &str, replacement: &Term) -> Term {
2444 if !occurs_free(&body, var) {
2445 return body;
2446 }
2447 let free = free_vars(replacement);
2448 substitute_input(
2449 SubstitutionInput::Owned(body),
2450 var,
2451 &mut SubstitutionValue::Borrowed(replacement),
2452 &free,
2453 )
2454}
2455
2456pub(crate) fn substitute_owned_closed(body: Term, var: &str, replacement: &Term) -> Term {
2459 substitute_input(
2460 SubstitutionInput::Owned(body),
2461 var,
2462 &mut SubstitutionValue::Borrowed(replacement),
2463 &std::collections::HashSet::new(),
2464 )
2465}
2466
2467enum SubstitutionInput<'a> {
2468 Borrowed(&'a Term),
2469 Owned(Term),
2470}
2471
2472enum SubstitutionChild<'a> {
2473 Borrowed(&'a Term),
2474 Owned(Box<Term>),
2475}
2476
2477enum SubstitutionCases<'a> {
2478 Borrowed(&'a [Term]),
2479 Owned(Vec<Term>),
2480}
2481
2482enum SubstitutionDefinitions<'a> {
2483 Borrowed(&'a [(String, Term)]),
2484 Owned(Vec<(String, Term)>),
2485}
2486
2487enum SubstitutionView<'a> {
2489 Atom(SubstitutionInput<'a>),
2490 Binder {
2491 pi: bool,
2492 name: std::borrow::Cow<'a, str>,
2493 domain: SubstitutionChild<'a>,
2494 body: SubstitutionChild<'a>,
2495 },
2496 App(SubstitutionChild<'a>, SubstitutionChild<'a>),
2497 Match {
2498 discriminant: SubstitutionChild<'a>,
2499 motive: SubstitutionChild<'a>,
2500 cases: SubstitutionCases<'a>,
2501 },
2502 Fix {
2503 name: std::borrow::Cow<'a, str>,
2504 body: SubstitutionChild<'a>,
2505 },
2506 MutualFix {
2507 defs: SubstitutionDefinitions<'a>,
2508 index: usize,
2509 },
2510 Let {
2511 name: std::borrow::Cow<'a, str>,
2512 ty: SubstitutionChild<'a>,
2513 value: SubstitutionChild<'a>,
2514 body: SubstitutionChild<'a>,
2515 },
2516 Annotated {
2517 annotation: std::borrow::Cow<'a, crate::Annotation>,
2518 term: SubstitutionChild<'a>,
2519 },
2520}
2521
2522impl<'a> SubstitutionInput<'a> {
2523 fn view(self) -> SubstitutionView<'a> {
2524 use std::borrow::Cow;
2525 use SubstitutionChild::{Borrowed as B, Owned as O};
2526 match self {
2527 Self::Borrowed(term) => match term {
2528 Term::Pi {
2529 param,
2530 param_type,
2531 body_type,
2532 } => SubstitutionView::Binder {
2533 pi: true,
2534 name: Cow::Borrowed(param),
2535 domain: B(param_type),
2536 body: B(body_type),
2537 },
2538 Term::Lambda {
2539 param,
2540 param_type,
2541 body,
2542 } => SubstitutionView::Binder {
2543 pi: false,
2544 name: Cow::Borrowed(param),
2545 domain: B(param_type),
2546 body: B(body),
2547 },
2548 Term::App(f, a) => SubstitutionView::App(B(f), B(a)),
2549 Term::Match {
2550 discriminant,
2551 motive,
2552 cases,
2553 } => SubstitutionView::Match {
2554 discriminant: B(discriminant),
2555 motive: B(motive),
2556 cases: SubstitutionCases::Borrowed(cases),
2557 },
2558 Term::Fix { name, body } => SubstitutionView::Fix {
2559 name: Cow::Borrowed(name),
2560 body: B(body),
2561 },
2562 Term::MutualFix { defs, index } => SubstitutionView::MutualFix {
2563 defs: SubstitutionDefinitions::Borrowed(defs),
2564 index: *index,
2565 },
2566 Term::Let {
2567 name,
2568 ty,
2569 value,
2570 body,
2571 } => SubstitutionView::Let {
2572 name: Cow::Borrowed(name),
2573 ty: B(ty),
2574 value: B(value),
2575 body: B(body),
2576 },
2577 Term::Annotated { annotation, term } => SubstitutionView::Annotated {
2578 annotation: Cow::Borrowed(annotation),
2579 term: B(term),
2580 },
2581 _ => SubstitutionView::Atom(Self::Borrowed(term)),
2582 },
2583 Self::Owned(term) => match term {
2584 Term::Pi {
2585 param,
2586 param_type,
2587 body_type,
2588 } => SubstitutionView::Binder {
2589 pi: true,
2590 name: Cow::Owned(param),
2591 domain: O(param_type),
2592 body: O(body_type),
2593 },
2594 Term::Lambda {
2595 param,
2596 param_type,
2597 body,
2598 } => SubstitutionView::Binder {
2599 pi: false,
2600 name: Cow::Owned(param),
2601 domain: O(param_type),
2602 body: O(body),
2603 },
2604 Term::App(f, a) => SubstitutionView::App(O(f), O(a)),
2605 Term::Match {
2606 discriminant,
2607 motive,
2608 cases,
2609 } => SubstitutionView::Match {
2610 discriminant: O(discriminant),
2611 motive: O(motive),
2612 cases: SubstitutionCases::Owned(cases),
2613 },
2614 Term::Fix { name, body } => SubstitutionView::Fix {
2615 name: Cow::Owned(name),
2616 body: O(body),
2617 },
2618 Term::MutualFix { defs, index } => SubstitutionView::MutualFix {
2619 defs: SubstitutionDefinitions::Owned(defs),
2620 index,
2621 },
2622 Term::Let {
2623 name,
2624 ty,
2625 value,
2626 body,
2627 } => SubstitutionView::Let {
2628 name: Cow::Owned(name),
2629 ty: O(ty),
2630 value: O(value),
2631 body: O(body),
2632 },
2633 Term::Annotated { annotation, term } => SubstitutionView::Annotated {
2634 annotation: Cow::Owned(annotation),
2635 term: O(term),
2636 },
2637 _ => SubstitutionView::Atom(Self::Owned(term)),
2638 },
2639 }
2640 }
2641}
2642
2643impl<'a> SubstitutionChild<'a> {
2644 fn as_term(&self) -> &Term {
2645 match self {
2646 Self::Borrowed(t) => t,
2647 Self::Owned(t) => t,
2648 }
2649 }
2650
2651 fn keep(self) -> Box<Term> {
2652 match self {
2653 Self::Borrowed(t) => {
2654 #[cfg(test)]
2655 record_substitution_tree(t);
2656 Box::new(t.clone())
2657 }
2658 Self::Owned(t) => t,
2659 }
2660 }
2661
2662 fn apply(
2663 self,
2664 var: &str,
2665 value: &mut SubstitutionValue<'_>,
2666 fvs: &std::collections::HashSet<String>,
2667 ) -> Box<Term> {
2668 match self {
2669 Self::Borrowed(t) => Box::new(substitute_input(
2670 SubstitutionInput::Borrowed(t),
2671 var,
2672 value,
2673 fvs,
2674 )),
2675 Self::Owned(mut t) => {
2676 let input = std::mem::replace(t.as_mut(), Term::Hole);
2677 *t = substitute_input(SubstitutionInput::Owned(input), var, value, fvs);
2678 t
2679 }
2680 }
2681 }
2682
2683 fn rename(self, old: &str, new: &str) -> Self {
2684 match self {
2685 Self::Borrowed(t) => Self::Owned(Box::new(rename_var(t, old, new))),
2686 Self::Owned(mut t) => {
2687 *t = rename_var(&t, old, new);
2688 Self::Owned(t)
2689 }
2690 }
2691 }
2692}
2693
2694fn substitute_binder<'a>(
2695 mut name: std::borrow::Cow<'a, str>,
2696 mut body: SubstitutionChild<'a>,
2697 var: &str,
2698 value: &mut SubstitutionValue<'_>,
2699 fvs: &std::collections::HashSet<String>,
2700) -> (String, Box<Term>) {
2701 if name.as_ref() == var {
2702 return (name.into_owned(), body.keep());
2703 }
2704 if fvs.contains(name.as_ref()) {
2705 let fresh = freshen(&name, body.as_term(), fvs, var);
2706 body = body.rename(&name, &fresh);
2707 name = std::borrow::Cow::Owned(fresh);
2708 }
2709 (name.into_owned(), body.apply(var, value, fvs))
2710}
2711
2712#[cfg(test)]
2713thread_local! {
2714 static SUBSTITUTION_COPY_WORK: std::cell::Cell<(usize, usize)> =
2715 const { std::cell::Cell::new((0, 0)) };
2716}
2717
2718#[cfg(test)]
2719pub(crate) fn take_substitution_copy_work() -> (usize, usize) {
2720 SUBSTITUTION_COPY_WORK.with(|work| work.replace((0, 0)))
2721}
2722
2723#[cfg(test)]
2724fn record_substitution_node(term: &Term) {
2725 let bytes = match term {
2726 Term::Var(name)
2727 | Term::Global(name)
2728 | Term::Const { name, .. }
2729 | Term::Fix { name, .. }
2730 | Term::Let { name, .. } => name.len(),
2731 Term::Pi { param, .. } | Term::Lambda { param, .. } => param.len(),
2732 Term::MutualFix { defs, .. } => defs.iter().map(|(name, _)| name.len()).sum(),
2733 _ => 0,
2734 };
2735 SUBSTITUTION_COPY_WORK.with(|work| {
2736 let (nodes, names) = work.get();
2737 work.set((nodes + 1, names + bytes));
2738 });
2739}
2740
2741#[cfg(test)]
2742fn record_substitution_tree(term: &Term) {
2743 record_substitution_node(term);
2744 match term {
2745 Term::Pi {
2746 param_type,
2747 body_type,
2748 ..
2749 } => {
2750 record_substitution_tree(param_type);
2751 record_substitution_tree(body_type);
2752 }
2753 Term::Lambda {
2754 param_type, body, ..
2755 } => {
2756 record_substitution_tree(param_type);
2757 record_substitution_tree(body);
2758 }
2759 Term::App(f, a) => {
2760 record_substitution_tree(f);
2761 record_substitution_tree(a);
2762 }
2763 Term::Match {
2764 discriminant,
2765 motive,
2766 cases,
2767 } => {
2768 record_substitution_tree(discriminant);
2769 record_substitution_tree(motive);
2770 for case in cases {
2771 record_substitution_tree(case);
2772 }
2773 }
2774 Term::Fix { body, .. } => record_substitution_tree(body),
2775 Term::MutualFix { defs, .. } => {
2776 for (_, body) in defs {
2777 record_substitution_tree(body);
2778 }
2779 }
2780 Term::Let {
2781 ty, value, body, ..
2782 } => {
2783 record_substitution_tree(ty);
2784 record_substitution_tree(value);
2785 record_substitution_tree(body);
2786 }
2787 Term::Annotated { term, .. } => record_substitution_tree(term),
2788 Term::Sort(_)
2789 | Term::Var(_)
2790 | Term::Global(_)
2791 | Term::Const { .. }
2792 | Term::Lit(_)
2793 | Term::Hole => {}
2794 }
2795}
2796
2797fn substitute_input(
2798 input: SubstitutionInput<'_>,
2799 var: &str,
2800 value: &mut SubstitutionValue<'_>,
2801 fvs: &std::collections::HashSet<String>,
2802) -> Term {
2803 #[cfg(test)]
2806 if let SubstitutionInput::Borrowed(term) = &input {
2807 if !matches!(term, Term::Var(name) if name == var) {
2808 record_substitution_node(term);
2809 }
2810 }
2811 match input.view() {
2812 SubstitutionView::Atom(input) => {
2813 let term = match &input {
2814 SubstitutionInput::Borrowed(t) => *t,
2815 SubstitutionInput::Owned(t) => t,
2816 };
2817 if matches!(term, Term::Var(name) if name == var) {
2818 value.materialize()
2819 } else {
2820 match input {
2821 SubstitutionInput::Borrowed(t) => t.clone(),
2822 SubstitutionInput::Owned(t) => t,
2823 }
2824 }
2825 }
2826 SubstitutionView::Binder {
2827 pi,
2828 name,
2829 domain,
2830 body,
2831 } => {
2832 let param_type = domain.apply(var, value, fvs);
2833 let (param, body) = substitute_binder(name, body, var, value, fvs);
2834 if pi {
2835 Term::Pi {
2836 param,
2837 param_type,
2838 body_type: body,
2839 }
2840 } else {
2841 Term::Lambda {
2842 param,
2843 param_type,
2844 body,
2845 }
2846 }
2847 }
2848 SubstitutionView::App(f, a) => {
2849 Term::App(f.apply(var, value, fvs), a.apply(var, value, fvs))
2850 }
2851 SubstitutionView::Match {
2852 discriminant,
2853 motive,
2854 cases,
2855 } => {
2856 let discriminant = discriminant.apply(var, value, fvs);
2857 let motive = motive.apply(var, value, fvs);
2858 let cases = match cases {
2859 SubstitutionCases::Borrowed(cases) => cases
2860 .iter()
2861 .map(|case| {
2862 substitute_input(SubstitutionInput::Borrowed(case), var, value, fvs)
2863 })
2864 .collect(),
2865 SubstitutionCases::Owned(mut cases) => {
2866 for case in &mut cases {
2867 let input = std::mem::replace(case, Term::Hole);
2868 *case = substitute_input(SubstitutionInput::Owned(input), var, value, fvs);
2869 }
2870 cases
2871 }
2872 };
2873 Term::Match {
2874 discriminant,
2875 motive,
2876 cases,
2877 }
2878 }
2879 SubstitutionView::Fix { name, body } => {
2880 let (name, body) = substitute_binder(name, body, var, value, fvs);
2881 Term::Fix { name, body }
2882 }
2883 SubstitutionView::MutualFix { defs, index } => {
2884 let mut defs = match defs {
2885 SubstitutionDefinitions::Borrowed(defs) => {
2886 #[cfg(test)]
2887 for (_, body) in defs {
2888 record_substitution_tree(body);
2889 }
2890 defs.to_vec()
2891 }
2892 SubstitutionDefinitions::Owned(defs) => defs,
2893 };
2894 if defs.iter().any(|(name, _)| name == var) {
2895 return Term::MutualFix { defs, index };
2896 }
2897 for i in 0..defs.len() {
2900 if fvs.contains(&defs[i].0) {
2901 let mut avoid = fvs.clone();
2902 for (name, body) in &defs {
2903 all_var_names(body, &mut avoid);
2904 avoid.insert(name.clone());
2905 }
2906 avoid.insert(var.to_string());
2907 let fresh = fresh_name(&defs[i].0, &avoid);
2908 for j in 0..defs.len() {
2909 defs[j].1 = rename_var(&defs[j].1, &defs[i].0, &fresh);
2910 }
2911 defs[i].0 = fresh;
2912 }
2913 }
2914 for (_, body) in &mut defs {
2915 let input = std::mem::replace(body, Term::Hole);
2916 *body = substitute_input(SubstitutionInput::Owned(input), var, value, fvs);
2917 }
2918 Term::MutualFix { defs, index }
2919 }
2920 SubstitutionView::Let {
2921 name,
2922 ty,
2923 value: binding,
2924 body,
2925 } => {
2926 let ty = ty.apply(var, value, fvs);
2927 let binding = binding.apply(var, value, fvs);
2928 let (name, body) = substitute_binder(name, body, var, value, fvs);
2929 Term::Let {
2930 name,
2931 ty,
2932 value: binding,
2933 body,
2934 }
2935 }
2936 SubstitutionView::Annotated { annotation, term } => Term::Annotated {
2937 annotation: annotation.into_owned(),
2938 term: term.apply(var, value, fvs),
2939 },
2940 }
2941}
2942
2943pub fn is_subtype(ctx: &Context, a: &Term, b: &Term) -> bool {
2965 if let Some(r) = crate::annotation::erased_pair(a, b, |a, b| is_subtype(ctx, a, b)) {
2966 return r;
2967 }
2968 if !inside_kernel() {
2973 if let Some(r) = crate::term_store::deepen_stack_all(&[a, b], || is_subtype(ctx, a, b)) {
2974 return r;
2975 }
2976 }
2977 if alpha_eq(a, b) {
2982 return true;
2983 }
2984 if enter_kernel(a, "is_subtype").is_err() || enter_kernel(b, "is_subtype").is_err() {
2987 return false;
2988 }
2989 if crate::conversion_session::known(ctx, a, b) {
2990 return true;
2991 }
2992 if let Some(equal) = rigid_conversion(ctx, a, b) {
2993 return equal;
2994 }
2995 if conversion_by_congruence(ctx, a, b) {
2996 return true;
2997 }
2998 if conversion_by_unfolded_head(ctx, a, b) {
2999 return true;
3000 }
3001 if crate::term_store::beta_zeta_equivalent(ctx, a, b, 1 << 16) {
3004 return true;
3005 }
3006 if crate::term_store::beta_delta_equivalent(ctx, a, b, 1 << 16) {
3007 return true;
3008 }
3009 let a_norm = normalize(ctx, a);
3010 let b_norm = normalize(ctx, b);
3011
3012 is_subtype_normalized(ctx, &a_norm, &b_norm)
3013}
3014
3015fn is_subtype_normalized(ctx: &Context, a: &Term, b: &Term) -> bool {
3021 if let Some(expanded) = crate::term_store::zeta_expand_head_term(a) {
3030 return is_subtype_normalized(ctx, &normalize(ctx, &expanded), b);
3031 }
3032 if let Some(expanded) = crate::term_store::zeta_expand_head_term(b) {
3033 return is_subtype_normalized(ctx, a, &normalize(ctx, &expanded));
3034 }
3035 match (a, b) {
3036 (Term::Sort(u1), Term::Sort(u2)) => u1.is_subtype_of(u2),
3038
3039 (
3041 Term::Pi {
3042 param: p1,
3043 param_type: t1,
3044 body_type: b1,
3045 },
3046 Term::Pi {
3047 param: p2,
3048 param_type: t2,
3049 body_type: b2,
3050 },
3051 ) => {
3052 is_subtype_normalized(ctx, t2, t1) && {
3054 let (name, lhs, rhs) = open_conversion_binders(Some(ctx), p1, b1, p2, b2);
3056 let ext = ctx.extend(&name, (**t1).clone());
3057 is_subtype_normalized(&ext, &lhs, &rhs)
3058 }
3059 }
3060
3061 _ => def_eq_normalized(ctx, a, b),
3063 }
3064}
3065
3066#[cfg(test)]
3067thread_local! {
3068 static CONVERSION_FULL_NORMALIZATIONS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3069 static CONVERSION_PROOF_TYPE_PROBES: std::cell::Cell<Option<usize>> = const { std::cell::Cell::new(None) };
3070}
3071
3072#[cfg(test)]
3076static PROCESS_FULL_NORMALIZATIONS: std::sync::atomic::AtomicUsize =
3077 std::sync::atomic::AtomicUsize::new(0);
3078
3079pub(crate) fn def_eq(ctx: &Context, a: &Term, b: &Term) -> bool {
3083 if let Some(r) = crate::annotation::erased_pair(a, b, |a, b| def_eq(ctx, a, b)) {
3084 return r;
3085 }
3086 within_conversion_rungs(|| {
3087 crate::conversion_session::convert(ctx, a, b, || def_eq_uncached(ctx, a, b))
3088 })
3089}
3090
3091thread_local! {
3092 static CONVERSION_NESTING: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3094}
3095
3096pub(crate) fn conversion_nesting() -> usize {
3098 CONVERSION_NESTING.with(|n| n.get())
3099}
3100
3101struct ConversionRung(usize);
3103
3104impl Drop for ConversionRung {
3105 fn drop(&mut self) {
3106 CONVERSION_NESTING.with(|n| n.set(self.0));
3107 }
3108}
3109
3110pub(crate) fn within_conversion_rungs(f: impl FnOnce() -> bool + Send) -> bool {
3119 let taken = conversion_nesting();
3120 if taken >= MAX_TERM_DEPTH {
3121 crate::reduction::record_resource_stop(crate::Unreduced::TooDeep);
3122 return false;
3123 }
3124 let rungs = crate::term_store::kernel_stack_rungs();
3125 if taken + 1 >= rungs && rungs < MAX_TERM_DEPTH {
3126 return crate::term_store::grow_stack_for_depth(
3127 (rungs * 2).min(MAX_TERM_DEPTH),
3128 move || {
3129 CONVERSION_NESTING.with(|n| n.set(taken));
3130 within_conversion_rungs(f)
3131 },
3132 );
3133 }
3134 let _rung = ConversionRung(taken);
3135 CONVERSION_NESTING.with(|n| n.set(taken + 1));
3136 f()
3137}
3138
3139fn def_eq_uncached(ctx: &Context, a: &Term, b: &Term) -> bool {
3140 if alpha_eq(a, b) {
3141 return true;
3142 }
3143 if enter_kernel(a, "def_eq").is_err() || enter_kernel(b, "def_eq").is_err() {
3144 return false;
3145 }
3146 let matching_binders = matches!(
3150 (a, b),
3151 (Term::Pi { .. }, Term::Pi { .. }) | (Term::Lambda { .. }, Term::Lambda { .. })
3152 );
3153 if matching_binders && conversion_by_congruence(ctx, a, b) {
3154 return true;
3155 }
3156 if let Some(equal) = rigid_conversion(ctx, a, b) {
3157 return equal;
3158 }
3159 if let Some(equal) = crate::reduction::natural_literal_conversion(ctx, a, b, 1 << 18) {
3160 return equal;
3161 }
3162 if crate::reduction::constructor_equivalent(ctx, a, b, 1 << 26) {
3163 return true;
3164 }
3165 if crate::term_store::beta_zeta_equivalent(ctx, a, b, 1 << 16) {
3166 return true;
3167 }
3168 if crate::term_store::beta_delta_equivalent(ctx, a, b, 1 << 16) {
3169 return true;
3170 }
3171 if !matching_binders && conversion_by_congruence(ctx, a, b) {
3172 return true;
3173 }
3174 let bounded_head = bounded_head_conversion(ctx, a, b);
3179 if bounded_head == Some(true) {
3180 return true;
3181 }
3182 if let Some(equal) = proof_irrelevance(ctx, a, b) {
3186 return equal;
3187 }
3188 if bounded_head == Some(false) && conversion_by_exposed_heads(ctx, a, b) {
3189 return true;
3190 }
3191 if crate::reduction::constructors_disagree(ctx, a, b, 1 << 26) {
3194 return false;
3195 }
3196 if let Some(answer) = lazy_delta::lazy_delta_after_the_probes(ctx, a, b) {
3200 #[cfg(debug_assertions)]
3201 lazy_delta::differential(ctx, a, b, answer);
3202 return answer;
3203 }
3204 #[cfg(test)]
3214 {
3215 CONVERSION_FULL_NORMALIZATIONS.with(|count| count.set(count.get() + 1));
3216 PROCESS_FULL_NORMALIZATIONS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3217 }
3218 let folded = |name: &str| is_transparent_theorem(ctx, name);
3219 let a_folded =
3220 crate::reduction::normalize_at(ctx, a, crate::reduction::Transparency::Excluding(&folded));
3221 let b_folded =
3222 crate::reduction::normalize_at(ctx, b, crate::reduction::Transparency::Excluding(&folded));
3223 if def_eq_normalized(ctx, &a_folded, &b_folded) {
3224 return true;
3225 }
3226 let a_norm = normalize(ctx, &a_folded);
3227 let b_norm = normalize(ctx, &b_folded);
3228 def_eq_normalized(ctx, &a_norm, &b_norm)
3229}
3230
3231pub(crate) fn is_transparent_theorem(ctx: &Context, name: &str) -> bool {
3233 ctx.checked_opaque_dependencies(name).is_some() && ctx.get_definition_body(name).is_some()
3234}
3235
3236fn conversion_by_unfolded_head(ctx: &Context, a: &Term, b: &Term) -> bool {
3240 match bounded_head_conversion(ctx, a, b) {
3241 Some(true) => true,
3242 Some(false) => conversion_by_exposed_heads(ctx, a, b),
3243 None => false,
3244 }
3245}
3246
3247fn bounded_head_conversion(ctx: &Context, a: &Term, b: &Term) -> Option<bool> {
3250 if !ctx.simp_rules().is_empty() || mentions_hole(a) || mentions_hole(b) {
3253 return None;
3254 }
3255 let mut budget = 256;
3259 Some(bounded_conversion(ctx, a, b, &mut budget))
3260}
3261
3262fn conversion_by_exposed_heads(ctx: &Context, a: &Term, b: &Term) -> bool {
3266 let Some(lhs) = crate::reduction::bounded_conversion_head(ctx, a) else {
3267 return false;
3268 };
3269 let Some(rhs) = crate::reduction::bounded_conversion_head(ctx, b) else {
3270 return false;
3271 };
3272 if alpha_eq(a, &lhs) && alpha_eq(b, &rhs) {
3273 return false;
3274 }
3275 alpha_eq(&lhs, &rhs)
3276 || rigid_conversion(ctx, &lhs, &rhs) == Some(true)
3277 || conversion_by_congruence(ctx, &lhs, &rhs)
3278}
3279
3280fn conversion_by_congruence(ctx: &Context, a: &Term, b: &Term) -> bool {
3285 let binders = match (a, b) {
3286 (
3287 Term::Lambda {
3288 param: p,
3289 param_type: pt,
3290 body: pb,
3291 },
3292 Term::Lambda {
3293 param: q,
3294 param_type: qt,
3295 body: qb,
3296 },
3297 )
3298 | (
3299 Term::Pi {
3300 param: p,
3301 param_type: pt,
3302 body_type: pb,
3303 },
3304 Term::Pi {
3305 param: q,
3306 param_type: qt,
3307 body_type: qb,
3308 },
3309 ) => Some((p, pt, pb, q, qt, qb)),
3310 _ => None,
3311 };
3312 if let Some((p, pt, pb, q, qt, qb)) = binders {
3313 if !def_eq(ctx, pt, qt) {
3314 return false;
3315 }
3316 let name = fresh_context_name(ctx, "__conversion", &[pb, qb, pt, qt]);
3317 let variable = Term::Var(name.clone());
3318 let lhs = substitute(pb, p, &variable);
3319 let rhs = substitute(qb, q, &variable);
3320 return def_eq(&ctx.extend(&name, (**pt).clone()), &lhs, &rhs);
3321 }
3322 let (ah, aa) = spine_of(a);
3326 let (bh, ba) = spine_of(b);
3327 if !aa.is_empty() && aa.len() == ba.len() && alpha_eq(ah, bh) {
3328 let mut budget = 256;
3329 return aa
3330 .iter()
3331 .zip(ba)
3332 .all(|(x, y)| bounded_conversion(ctx, x, y, &mut budget));
3333 }
3334 false
3335}
3336
3337#[cfg(test)]
3342fn delta_exposes_head(candidate: &Term, other: &Term, budget: &mut usize) -> bool {
3343 delta_exposes_head_through(None, candidate, other, budget)
3344}
3345
3346fn delta_exposes_head_through<'a>(
3347 ctx: Option<&'a Context>,
3348 candidate: &'a Term,
3349 other: &Term,
3350 budget: &mut usize,
3351) -> bool {
3352 let mut target = other;
3353 loop {
3354 if *budget == 0 {
3355 return false;
3356 }
3357 *budget -= 1;
3358 match target {
3359 Term::App(f, _) => target = f,
3360 Term::Global(_) | Term::Const { .. } => break,
3361 _ => return false,
3362 }
3363 }
3364 let mut term = candidate;
3365 let mut applied = 0usize;
3366 loop {
3367 if *budget == 0 {
3368 return false;
3369 }
3370 *budget -= 1;
3371 match term {
3372 Term::App(f, _) => {
3373 applied += 1;
3374 term = f;
3375 }
3376 Term::Lambda { body, .. } if applied > 0 => {
3377 applied -= 1;
3378 term = body;
3379 }
3380 Term::Let { body, .. } => term = body,
3381 Term::Global(name) => {
3382 if alpha_eq(term, target) {
3383 return true;
3384 }
3385 let Some(body) = ctx.and_then(|ctx| ctx.get_definition_body(name)) else {
3390 return false;
3391 };
3392 term = body;
3393 }
3394 Term::Const { .. } => return alpha_eq(term, target),
3397 _ => return false,
3398 }
3399 }
3400}
3401
3402fn bounded_closed_head_identity(ctx: &Context, a: &Term, b: &Term, budget: &mut usize) -> bool {
3407 if !matches!(
3408 (a, b),
3409 (Term::Global(_), Term::Global(_) | Term::Lambda { .. })
3410 | (Term::Lambda { .. }, Term::Global(_))
3411 ) {
3412 return false;
3413 }
3414 fn observe<'a>(ctx: &'a Context, term: &'a Term, budget: &mut usize) -> Option<&'a Term> {
3415 let body = match term {
3416 Term::Global(name) => ctx.get_definition_body(name)?,
3417 Term::Lambda { .. } => term,
3418 _ => return None,
3419 };
3420 if *budget == 0 {
3421 return None;
3422 }
3423 *budget -= 1;
3424 crate::reduction::bounded_closed_conversion_size(body)?;
3425 Some(body)
3426 }
3427 let Some(a) = observe(ctx, a, budget) else {
3428 return false;
3429 };
3430 let Some(b) = observe(ctx, b, budget) else {
3431 return false;
3432 };
3433 alpha_eq(a, b)
3436}
3437
3438struct BorrowedCongruence {
3439 equal: bool,
3440 fixed_heads: (bool, bool),
3441}
3442
3443#[cfg(test)]
3446thread_local! {
3447 static BORROWED_STRUCTURAL_VISITS: std::cell::Cell<Option<usize>> =
3448 const {std::cell::Cell::new(None)};
3449}
3450
3451fn bounded_structural_congruence(
3452 ctx: &Context,
3453 a: &Term,
3454 b: &Term,
3455 budget: &mut usize,
3456) -> BorrowedCongruence {
3457 #[cfg(test)]
3458 BORROWED_STRUCTURAL_VISITS.with(|count| {
3459 if let Some(n) = count.get() {
3460 count.set(Some(n + 1));
3461 }
3462 });
3463 let fixed = |head: &Term| matches!(head, Term::Global(_) | Term::Const { .. });
3467 let mut fixed_heads = (fixed(a), fixed(b));
3468 let equal = match (a, b) {
3469 (Term::App(..), Term::App(..)) => {
3470 let (ah, aa) = spine_of(a);
3471 let (bh, ba) = spine_of(b);
3472 fixed_heads = (fixed(ah), fixed(bh));
3473 aa.len() == ba.len()
3474 && (alpha_eq(ah, bh) || bounded_closed_head_identity(ctx, ah, bh, budget))
3475 && aa
3476 .iter()
3477 .zip(ba)
3478 .all(|(x, y)| bounded_conversion(ctx, x, y, budget))
3479 }
3480 (
3481 Term::Lambda {
3482 param: p,
3483 param_type: pt,
3484 body: pb,
3485 },
3486 Term::Lambda {
3487 param: q,
3488 param_type: qt,
3489 body: qb,
3490 },
3491 )
3492 | (
3493 Term::Pi {
3494 param: p,
3495 param_type: pt,
3496 body_type: pb,
3497 },
3498 Term::Pi {
3499 param: q,
3500 param_type: qt,
3501 body_type: qb,
3502 },
3503 ) => {
3504 if bounded_conversion(ctx, pt, qt, budget) {
3505 let (name, lhs, rhs) = open_conversion_binders(Some(ctx), p, pb, q, qb);
3506 bounded_conversion(&ctx.extend(&name, (**pt).clone()), &lhs, &rhs, budget)
3507 } else {
3508 false
3509 }
3510 }
3511 _ => bounded_closed_head_identity(ctx, a, b, budget),
3512 };
3513 BorrowedCongruence { equal, fixed_heads }
3514}
3515
3516pub(crate) fn bounded_conversion(ctx: &Context, a: &Term, b: &Term, budget: &mut usize) -> bool {
3520 if *budget == 0 {
3521 return false;
3522 }
3523 *budget -= 1;
3524 if alpha_eq(a, b) {
3525 return true;
3526 }
3527 let observed = bounded_structural_congruence(ctx, a, b, budget);
3528 if observed.equal {
3529 return true;
3530 }
3531 fn expose<'a>(
3535 ctx: &Context,
3536 term: &'a Term,
3537 fixed: bool,
3538 budget: &mut usize,
3539 ) -> Option<std::borrow::Cow<'a, Term>> {
3540 if fixed {
3541 crate::reduction::bounded_conversion_size(term)?;
3542 Some(std::borrow::Cow::Borrowed(term))
3543 } else {
3544 crate::reduction::beta_iota_zeta_head(ctx, term, budget).map(std::borrow::Cow::Owned)
3545 }
3546 }
3547 let Some(a) = expose(ctx, a, observed.fixed_heads.0, budget) else {
3548 return false;
3549 };
3550 let Some(b) = expose(ctx, b, observed.fixed_heads.1, budget) else {
3551 return false;
3552 };
3553 if !matches!(
3557 (&a, &b),
3558 (std::borrow::Cow::Borrowed(_), std::borrow::Cow::Borrowed(_))
3559 ) {
3560 if alpha_eq(&a, &b) {
3561 return true;
3562 }
3563 if bounded_structural_congruence(ctx, &a, &b, budget).equal {
3564 return true;
3565 }
3566 }
3567 if *budget == 0 {
3568 return false;
3569 }
3570 match (
3571 crate::reduction::bounded_delta_head(ctx, &a),
3572 crate::reduction::bounded_delta_head(ctx, &b),
3573 ) {
3574 (Some((ac, ua)), Some((bc, ub))) => {
3575 if ac <= bc {
3579 if delta_exposes_head_through(Some(ctx), &ub, &a, budget) {
3580 bounded_conversion(ctx, &a, &ub, budget)
3581 } else {
3582 bounded_conversion(ctx, &ua, &b, budget)
3583 }
3584 } else if delta_exposes_head_through(Some(ctx), &ua, &b, budget) {
3585 bounded_conversion(ctx, &ua, &b, budget)
3586 } else {
3587 bounded_conversion(ctx, &a, &ub, budget)
3588 }
3589 }
3590 (Some((_, unfolded)), None) => bounded_conversion(ctx, &unfolded, &b, budget),
3591 (None, Some((_, unfolded))) => bounded_conversion(ctx, &a, &unfolded, budget),
3592 (None, None) => false,
3593 }
3594}
3595
3596fn rigid_conversion(ctx: &Context, a: &Term, b: &Term) -> Option<bool> {
3600 let (ah, aa) = spine_of(a);
3601 let (bh, ba) = spine_of(b);
3602 if aa.is_empty() || aa.len() != ba.len() || !alpha_eq(ah, bh) {
3603 return None;
3604 }
3605 let name = match ah {
3606 Term::Global(n) | Term::Const { name: n, .. } => n,
3607 _ => return None,
3608 };
3609 if !ctx.is_inductive(name) && !ctx.is_constructor(name) {
3610 return None;
3611 }
3612 if ctx.is_constructor(name) && proof_irrelevant(ctx, a, b) {
3613 return Some(true);
3614 }
3615 let mut order: Vec<usize> = (0..aa.len()).collect();
3616 order.sort_by_key(|&i| {
3617 crate::term_store::term_depth(aa[i]) + crate::term_store::term_depth(ba[i])
3618 });
3619 Some(order.into_iter().all(|i| def_eq(ctx, aa[i], ba[i])))
3620}
3621
3622fn spine_of(t: &Term) -> (&Term, Vec<&Term>) {
3624 let mut args = Vec::new();
3625 let mut head = t;
3626 while let Term::App(f, a) = head {
3627 args.push(a.as_ref());
3628 head = f;
3629 }
3630 args.reverse();
3631 (head, args)
3632}
3633
3634fn try_structure_eta(ctx: &Context, mk_term: &Term, other: &Term) -> Option<bool> {
3640 let (head, args) = spine_of(mk_term);
3641 let (hname, levels) = match head {
3642 Term::Global(n) => (n, None),
3643 Term::Const { name, levels } => (name, Some(levels)),
3644 _ => return None,
3645 };
3646 let (_sname, info) = ctx.struct_of_constructor(hname)?;
3647 let nfields = info.projections.len();
3648 if args.len() != info.num_params + nfields {
3650 return None;
3651 }
3652 let (ohead, _) = spine_of(other);
3655 if matches!(ohead, Term::Global(n) | Term::Const {name:n, ..} if n == hname) {
3656 return None;
3657 }
3658 let params = &args[..info.num_params];
3659 let field_args = &args[info.num_params..];
3660 Some(info.projections.iter().enumerate().all(|(i, proj)| {
3662 let mut proj_applied = match levels {
3663 Some(levels) => Term::Const {
3664 name: proj.clone(),
3665 levels: levels.clone(),
3666 },
3667 None => Term::Global(proj.clone()),
3668 };
3669 for p in params {
3670 proj_applied = Term::App(Box::new(proj_applied), Box::new((*p).clone()));
3671 }
3672 proj_applied = Term::App(Box::new(proj_applied), Box::new(other.clone()));
3673 def_eq(ctx, field_args[i], &proj_applied)
3674 }))
3675}
3676
3677fn implicit_instance_conversion(ctx: &Context, a: &Term, b: &Term) -> bool {
3687 if !bare_against_explicit(a, b) {
3688 return false;
3689 }
3690 let (ah, aa) = spine_of(a);
3691 let (bh, ba) = spine_of(b);
3692 if aa.len() != ba.len() {
3693 return false;
3694 }
3695 let (name, levels, bare_args) = match (ah, bh) {
3696 (Term::Global(n), Term::Const { name, levels }) if n == name => (name, levels, &aa),
3697 (Term::Const { name, levels }, Term::Global(n)) if n == name => (name, levels, &ba),
3698 _ => return false,
3699 };
3700 if bare_args.is_empty() {
3701 return lookup_const(ctx, name).is_some_and(|(declared, const_type)| {
3702 let own = crate::term::level_telescope(declared.as_deref(), &const_type);
3703 own.len() == levels.len()
3704 && own
3705 .iter()
3706 .zip(levels)
3707 .all(|(p, l)| l.equiv(&Universe::Var(p.clone())))
3708 });
3709 }
3710 implicit_instance_levels(ctx, name, bare_args).is_some_and(|solved| {
3711 solved.len() == levels.len() && solved.iter().zip(levels).all(|(x, y)| x.equiv(y))
3712 }) && aa.iter().zip(ba.iter()).all(|(x, y)| def_eq(ctx, x, y))
3713}
3714
3715fn bare_against_explicit(a: &Term, b: &Term) -> bool {
3719 fn head(t: &Term) -> &Term {
3720 let mut h = t;
3721 while let Term::App(f, _) = h {
3722 h = f;
3723 }
3724 h
3725 }
3726 matches!(
3727 (head(a), head(b)),
3728 (Term::Global(n), Term::Const { name, .. }) | (Term::Const { name, .. }, Term::Global(n))
3729 if n == name
3730 )
3731}
3732
3733fn implicit_instance_levels(ctx: &Context, name: &str, args: &[&Term]) -> Option<Vec<Universe>> {
3742 let (declared, const_type) = lookup_const(ctx, name)?;
3743 let positional = crate::term::level_telescope(declared.as_deref(), &const_type);
3744 let head = Term::Global(name.to_string());
3745 let mut current = infer_type(ctx, &head).ok()?;
3746 let mut solution = std::collections::HashMap::new();
3747 for (i, arg) in args.iter().enumerate() {
3748 let exposed = demanded_type_head(ctx, current, TypeHead::Function);
3749 let exposed = if i == 0 {
3750 implicit_levels_for_head(&head, exposed)
3751 } else {
3752 exposed
3753 };
3754 let Term::Pi {
3755 param,
3756 param_type,
3757 body_type,
3758 } = exposed
3759 else {
3760 return None;
3761 };
3762 let body_type = match domain_level_solution(ctx, ¶m_type, arg) {
3763 Some(subst) => {
3764 let body_type = crate::term::instantiate_universes(&body_type, &subst);
3765 solution.extend(subst);
3766 body_type
3767 }
3768 None => *body_type,
3769 };
3770 current = substitute(&body_type, ¶m, arg);
3771 }
3772 let metas = crate::term::fresh_level_metas(name, &positional);
3773 positional
3774 .iter()
3775 .map(|p| {
3776 let solved = metas.get(p)?.substitute(&solution);
3777 (!crate::term::universe_mentions(&solved, &crate::term::is_level_meta))
3778 .then_some(solved)
3779 })
3780 .collect()
3781}
3782
3783fn is_nat_peano_headed(t: &Term) -> bool {
3786 match t {
3787 Term::Global(n) => n == "Zero",
3788 Term::App(f, _) => matches!(f.as_ref(), Term::Global(n) if n == "Succ"),
3789 _ => false,
3790 }
3791}
3792
3793fn nat_peano_step(t: &Term) -> Term {
3795 match t {
3796 Term::Lit(Literal::Nat(n)) if *n <= logicaffeine_base::BigInt::from_i64(0) => {
3799 Term::Global("Zero".to_string())
3800 }
3801 Term::Lit(Literal::Nat(n)) => Term::App(
3802 Box::new(Term::Global("Succ".to_string())),
3803 Box::new(Term::Lit(Literal::Nat(
3804 n.sub(&logicaffeine_base::BigInt::from_i64(1)),
3805 ))),
3806 ),
3807 other => other.clone(),
3808 }
3809}
3810
3811fn nat_bridge(ctx: &Context, number: &logicaffeine_base::BigInt, other: &Term) -> Option<bool> {
3817 let numerals = ctx.canonical_numerals();
3818 if numerals.succ {
3819 return Some(nat_peano_equal(ctx, number, other));
3820 }
3821 (numerals.zero
3822 && *number <= logicaffeine_base::BigInt::from_i64(0)
3823 && matches!(other, Term::Global(zero) if zero == "Zero"))
3824 .then_some(true)
3825}
3826
3827fn nat_peano_equal(ctx: &Context, number: &logicaffeine_base::BigInt, mut term: &Term) -> bool {
3828 let zero = logicaffeine_base::BigInt::from_i64(0);
3829 let one = logicaffeine_base::BigInt::from_i64(1);
3830 let mut remaining = number.clone();
3831 loop {
3832 match term {
3833 Term::Global(name) if name == "Zero" => return remaining == zero,
3834 Term::Lit(Literal::Nat(other)) => return remaining == *other,
3835 Term::App(head, predecessor) if matches!(head.as_ref(), Term::Global(name) if name == "Succ") =>
3836 {
3837 if remaining <= zero {
3838 return false;
3839 }
3840 remaining = remaining.sub(&one);
3841 term = predecessor;
3842 }
3843 _ => {
3844 return def_eq_normalized(ctx, &Term::Lit(Literal::Nat(remaining)), term);
3845 }
3846 }
3847 }
3848}
3849
3850fn def_eq_normalized(ctx: &Context, a: &Term, b: &Term) -> bool {
3852 if alpha_eq(a, b) {
3853 return true;
3854 }
3855
3856 if let Some(a_ctor) = crate::int_inductive::literal_constructor(ctx, a) {
3858 let b_ctor = crate::int_inductive::literal_constructor(ctx, b);
3859 return def_eq_normalized(ctx, &a_ctor, b_ctor.as_ref().unwrap_or(b));
3860 }
3861 if let Some(b_ctor) = crate::int_inductive::literal_constructor(ctx, b) {
3862 return def_eq_normalized(ctx, a, &b_ctor);
3863 }
3864
3865 if let Some(expanded) = crate::term_store::zeta_expand_head_term(a) {
3874 return def_eq_normalized(ctx, &normalize(ctx, &expanded), b);
3875 }
3876 if let Some(expanded) = crate::term_store::zeta_expand_head_term(b) {
3877 return def_eq_normalized(ctx, a, &normalize(ctx, &expanded));
3878 }
3879
3880 if let Term::Lambda {
3883 param,
3884 param_type,
3885 body,
3886 } = a
3887 {
3888 if !matches!(b, Term::Lambda { .. }) {
3889 let name = fresh_conversion_name(Some(ctx), &[body, b, param_type]);
3890 let variable = Term::Var(name.clone());
3891 let body = substitute(body, param, &variable);
3892 let ext = ctx.extend(&name, (**param_type).clone());
3893 let bx = normalize(&ext, &Term::App(Box::new(b.clone()), Box::new(variable)));
3894 return def_eq_normalized(&ext, &body, &bx);
3895 }
3896 }
3897 if let Term::Lambda {
3898 param,
3899 param_type,
3900 body,
3901 } = b
3902 {
3903 if !matches!(a, Term::Lambda { .. }) {
3904 let name = fresh_conversion_name(Some(ctx), &[body, a, param_type]);
3905 let variable = Term::Var(name.clone());
3906 let body = substitute(body, param, &variable);
3907 let ext = ctx.extend(&name, (**param_type).clone());
3908 let ax = normalize(&ext, &Term::App(Box::new(a.clone()), Box::new(variable)));
3909 return def_eq_normalized(&ext, &ax, &body);
3910 }
3911 }
3912
3913 if let Some(eq) = try_structure_eta(ctx, a, b) {
3919 return eq;
3920 }
3921 if let Some(eq) = try_structure_eta(ctx, b, a) {
3922 return eq;
3923 }
3924
3925 if implicit_instance_conversion(ctx, a, b) {
3930 return true;
3931 }
3932
3933 match (a, b) {
3938 (Term::Lit(Literal::Nat(x)), Term::Lit(Literal::Nat(y))) => return x == y,
3939 (Term::Lit(Literal::Nat(n)), _) if is_nat_peano_headed(b) => {
3940 if let Some(equal) = nat_bridge(ctx, n, b) {
3941 return equal;
3942 }
3943 }
3944 (_, Term::Lit(Literal::Nat(n))) if is_nat_peano_headed(a) => {
3945 if let Some(equal) = nat_bridge(ctx, n, a) {
3946 return equal;
3947 }
3948 }
3949 _ => {}
3950 }
3951
3952 let congruent = match (a, b) {
3953 (Term::Sort(u1), Term::Sort(u2)) => u1.equiv(u2),
3954 (
3955 Term::Pi {
3956 param: p1,
3957 param_type: t1,
3958 body_type: b1,
3959 },
3960 Term::Pi {
3961 param: p2,
3962 param_type: t2,
3963 body_type: b2,
3964 },
3965 ) => {
3966 def_eq_normalized(ctx, t1, t2) && {
3967 let (name, lhs, rhs) = open_conversion_binders(Some(ctx), p1, b1, p2, b2);
3968 let ext = ctx.extend(&name, (**t1).clone());
3969 def_eq_normalized(&ext, &lhs, &rhs)
3970 }
3971 }
3972 (
3973 Term::Lambda {
3974 param: p1,
3975 param_type: t1,
3976 body: b1,
3977 },
3978 Term::Lambda {
3979 param: p2,
3980 param_type: t2,
3981 body: b2,
3982 },
3983 ) => {
3984 def_eq_normalized(ctx, t1, t2) && {
3985 let (name, lhs, rhs) = open_conversion_binders(Some(ctx), p1, b1, p2, b2);
3986 let ext = ctx.extend(&name, (**t1).clone());
3987 def_eq_normalized(&ext, &lhs, &rhs)
3988 }
3989 }
3990 (Term::App(f1, a1), Term::App(f2, a2)) => {
3991 !bare_against_explicit(a, b)
3992 && def_eq_normalized(ctx, f1, f2)
3993 && def_eq_normalized(ctx, a1, a2)
3994 }
3995 (
3996 Term::Match {
3997 discriminant: d1,
3998 motive: m1,
3999 cases: c1,
4000 },
4001 Term::Match {
4002 discriminant: d2,
4003 motive: m2,
4004 cases: c2,
4005 },
4006 ) => {
4007 def_eq_normalized(ctx, d1, d2)
4011 && def_eq(ctx, m1, m2)
4012 && c1.len() == c2.len()
4013 && c1.iter().zip(c2.iter()).all(|(x, y)| def_eq(ctx, x, y))
4014 }
4015 (Term::Fix { name: n1, body: b1 }, Term::Fix { name: n2, body: b2 }) => {
4016 let (_, lhs, rhs) = open_conversion_binders(Some(ctx), n1, b1, n2, b2);
4017 def_eq(ctx, &lhs, &rhs)
4021 }
4022 _ => false,
4023 };
4024 if congruent {
4025 return true;
4026 }
4027
4028 if can_have_unit_type(ctx, a) && can_have_unit_type(ctx, b) {
4032 if let Ok(a_type) = infer_type(ctx, a) {
4033 let a_type = normalize(ctx, &a_type);
4034 let (head, _) = spine_of(&a_type);
4035 let name = match head {
4036 Term::Global(n) | Term::Const { name: n, .. } => Some(n),
4037 _ => None,
4038 };
4039 if name.is_some_and(|n| ctx.unit_constructor(n).is_some()) {
4040 if let Ok(b_type) = infer_type(ctx, b) {
4041 if def_eq(ctx, &a_type, &b_type) {
4042 return true;
4043 }
4044 }
4045 }
4046 }
4047 }
4048
4049 proof_irrelevant(ctx, a, b)
4052}
4053
4054fn monomorphic_constructor_parent<'a>(ctx: &'a Context, term: &Term) -> Option<&'a str> {
4057 if !ctx.simp_rules().is_empty() {
4060 return None;
4061 }
4062 let mut remaining = 256usize;
4063 let mut tick = || {
4064 remaining = remaining.checked_sub(1)?;
4065 Some(())
4066 };
4067 let mut head = term;
4068 let mut supplied = 0usize;
4069 while let Term::App(function, _) = head {
4070 tick()?;
4071 supplied += 1;
4072 head = function;
4073 }
4074 let Term::Global(name) = head else {
4075 return None;
4076 };
4077 let parent = ctx.constructor_inductive(name)?;
4078 if !ctx.is_inductive(parent)
4079 || ctx.is_inductive(name)
4080 || ctx.is_constructor(parent)
4081 || ctx.is_definition(name)
4082 || ctx.is_definition(parent)
4083 || ctx.poly_declaration(name).is_some()
4084 || ctx.poly_declaration(parent).is_some()
4085 {
4086 return None;
4087 }
4088 let mut result = ctx.get_global(name)?;
4092 let mut arity = 0usize;
4093 while let Term::Pi { body_type, .. } = result {
4094 tick()?;
4095 arity += 1;
4096 result = body_type;
4097 }
4098 if arity != supplied {
4099 return None;
4100 }
4101 let mut result_arguments = 0usize;
4102 while let Term::App(function, _) = result {
4103 tick()?;
4104 result_arguments += 1;
4105 result = function;
4106 }
4107 if !matches!(result, Term::Global(family) if family == parent) {
4108 return None;
4109 }
4110 let mut family_type = ctx.get_global(parent)?;
4111 let mut family_arity = 0usize;
4112 while let Term::Pi { body_type, .. } = family_type {
4113 tick()?;
4114 family_arity += 1;
4115 family_type = body_type;
4116 }
4117 if family_arity != result_arguments || !matches!(family_type, Term::Sort(_)) {
4118 return None;
4119 }
4120 Some(parent)
4121}
4122
4123fn is_monomorphic_data_constructor(ctx: &Context, term: &Term) -> bool {
4124 let Some(parent) = monomorphic_constructor_parent(ctx, term) else {
4125 return false;
4126 };
4127 matches!(
4128 ctx.get_global(parent).and_then(result_sort_universe),
4129 Some(Universe::Type(_))
4130 )
4131}
4132
4133fn fixed_applied_match_result_family<'a>(ctx: &Context, term: &'a Term) -> Option<&'a str> {
4137 if !ctx.simp_rules().is_empty() {
4138 return None;
4139 }
4140 let mut steps = 256usize;
4141 let mut tick = || {
4142 steps = steps.checked_sub(1)?;
4143 Some(())
4144 };
4145 let mut head = term;
4146 while let Term::Lambda { body, .. } = head {
4149 tick()?;
4150 head = body;
4151 }
4152 let mut supplied = 0usize;
4153 while let Term::App(function, _) = head {
4154 tick()?;
4155 supplied += 1;
4156 head = function;
4157 }
4158 let Term::Fix { body, .. } = head else {
4159 return None;
4160 };
4161 let mut inner = body.as_ref();
4162 let mut binders = Vec::new();
4163 while let Term::Lambda {
4164 param,
4165 param_type,
4166 body,
4167 } = inner
4168 {
4169 tick()?;
4170 binders.push((param.as_str(), param_type.as_ref()));
4171 inner = body;
4172 }
4173 if supplied == 0 || supplied != binders.len() {
4174 return None;
4175 }
4176 let Term::Match {
4177 discriminant,
4178 motive,
4179 ..
4180 } = inner
4181 else {
4182 return None;
4183 };
4184 tick()?;
4185 let Term::Var(variable) = discriminant.as_ref() else {
4188 return None;
4189 };
4190 let mut found_domain = None;
4191 for (name, domain) in binders.iter().rev() {
4192 tick()?;
4193 if *name == variable {
4194 found_domain = Some(*domain);
4195 break;
4196 }
4197 }
4198 let domain = found_domain?;
4199 let Term::Global(domain_name) = domain else {
4200 return None;
4201 };
4202 let rigid_sort = |name: &str| {
4203 if !ctx.is_inductive(name)
4204 || ctx.is_definition(name)
4205 || ctx.is_constructor(name)
4206 || ctx.poly_declaration(name).is_some()
4207 {
4208 return None;
4209 }
4210 match ctx.get_global(name) {
4211 Some(Term::Sort(level)) => Some(level),
4212 _ => None,
4213 }
4214 };
4215 rigid_sort(domain_name)?;
4216 let result = match motive.as_ref() {
4217 Term::Lambda {
4218 param_type, body, ..
4219 } if matches!(param_type.as_ref(), Term::Global(name) if name == domain_name) => {
4220 tick()?;
4221 body.as_ref()
4222 }
4223 other => other,
4224 };
4225 let Term::Global(result_name) = result else {
4226 return None;
4227 };
4228 if !matches!(rigid_sort(result_name), Some(Universe::Type(_))) {
4229 return None;
4230 }
4231 Some(result_name.as_str())
4232}
4233
4234fn can_have_unit_type(ctx: &Context, term: &Term) -> bool {
4235 if ctx.simp_rules().is_empty() && matches!(term, Term::Lambda { .. }) {
4238 return false;
4239 }
4240 match monomorphic_constructor_parent(ctx, term)
4241 .or_else(|| fixed_applied_match_result_family(ctx, term))
4242 {
4243 Some(parent) => ctx.unit_constructor(parent).is_some(),
4244 None => true,
4245 }
4246}
4247
4248fn proof_irrelevant(ctx: &Context, a: &Term, b: &Term) -> bool {
4259 proof_irrelevance(ctx, a, b) == Some(true)
4260}
4261
4262fn proof_irrelevance(ctx: &Context, a: &Term, b: &Term) -> Option<bool> {
4266 if is_monomorphic_data_constructor(ctx, a)
4267 || is_monomorphic_data_constructor(ctx, b)
4268 || fixed_applied_match_result_family(ctx, a).is_some()
4269 || fixed_applied_match_result_family(ctx, b).is_some()
4270 {
4271 return None;
4272 }
4273 #[cfg(test)]
4274 CONVERSION_PROOF_TYPE_PROBES.with(|count| {
4275 if let Some(n) = count.get() {
4276 count.set(Some(n + 1));
4277 }
4278 });
4279 let (Ok(ta), Ok(tb)) = (infer_type(ctx, a), infer_type(ctx, b)) else {
4280 return None;
4281 };
4282 let is_propositional = |t: &Term| {
4283 matches!(
4284 infer_type(ctx, t).map(|s| normalize(ctx, &s)),
4285 Ok(Term::Sort(level)) if level == Universe::SProp || level.equiv(&Universe::Prop)
4286 )
4287 };
4288 if !is_propositional(&ta) && !is_propositional(&tb) {
4289 return None;
4290 }
4291 Some(def_eq(ctx, &ta, &tb))
4292}
4293
4294fn extract_inductive_name(ctx: &Context, ty: &Term) -> Option<String> {
4302 match ty {
4303 Term::Global(name) | Term::Const { name, .. } if ctx.is_inductive(name) => {
4305 Some(name.clone())
4306 }
4307
4308 Term::App(func, _) => extract_inductive_name(ctx, func),
4311
4312 _ => None,
4313 }
4314}
4315
4316pub(crate) fn mentions_hole(t: &Term) -> bool {
4318 match t {
4319 Term::Hole => true,
4320 Term::Sort(_) | Term::Var(_) | Term::Global(_) | Term::Const { .. } | Term::Lit(_) => false,
4321 Term::App(f, a) => mentions_hole(f) || mentions_hole(a),
4322 Term::Pi {
4323 param_type,
4324 body_type,
4325 ..
4326 } => mentions_hole(param_type) || mentions_hole(body_type),
4327 Term::Lambda {
4328 param_type, body, ..
4329 } => mentions_hole(param_type) || mentions_hole(body),
4330 Term::Let {
4331 ty, value, body, ..
4332 } => mentions_hole(ty) || mentions_hole(value) || mentions_hole(body),
4333 Term::Match {
4334 discriminant,
4335 motive,
4336 cases,
4337 } => {
4338 mentions_hole(discriminant) || mentions_hole(motive) || cases.iter().any(mentions_hole)
4339 }
4340 Term::Fix { body, .. } => mentions_hole(body),
4341 Term::MutualFix { defs, .. } => defs.iter().any(|(_, b)| mentions_hole(b)),
4342 Term::Annotated { term, .. } => mentions_hole(term),
4343 }
4344}
4345
4346#[cfg(test)]
4359pub(crate) fn bounded_probe_alpha_eq_for_test(a: &Term, b: &Term) -> bool {
4360 alpha_eq(a, b)
4361}
4362
4363fn alpha_eq(a: &Term, b: &Term) -> bool {
4364 types_equal(a, b) && !mentions_hole(a) && !mentions_hole(b)
4365}
4366
4367pub(crate) fn alpha_equivalent(a: &Term, b: &Term) -> bool {
4370 alpha_eq(a, b)
4371}
4372
4373#[inline(never)]
4374fn fresh_conversion_name(ctx: Option<&Context>, terms: &[&Term]) -> String {
4375 let mut avoid = std::collections::HashSet::new();
4376 for term in terms {
4377 avoid.extend(free_vars(term));
4378 }
4379 let mut name = fresh_name("__conversion", &avoid);
4380 while avoid.contains(&name) || ctx.is_some_and(|c| c.local_name_in_use(&name)) {
4381 name.push('_');
4382 }
4383 name
4384}
4385
4386#[inline(never)]
4387fn open_conversion_binders(
4388 ctx: Option<&Context>,
4389 p: &str,
4390 a: &Term,
4391 q: &str,
4392 b: &Term,
4393) -> (String, Term, Term) {
4394 let name = fresh_conversion_name(ctx, &[a, b]);
4395 let variable = Term::Var(name.clone());
4396 (
4397 name,
4398 substitute(a, p, &variable),
4399 substitute(b, q, &variable),
4400 )
4401}
4402
4403#[inline(never)]
4404fn bound_types_equal(p: &str, a: &Term, q: &str, b: &Term) -> bool {
4405 if p == q {
4406 return types_equal(a, b);
4407 }
4408 let (_, a, b) = open_conversion_binders(None, p, a, q, b);
4409 types_equal(&a, &b)
4410}
4411
4412fn types_equal(a: &Term, b: &Term) -> bool {
4418 if matches!(a, Term::Hole) || matches!(b, Term::Hole) {
4420 return true;
4421 }
4422
4423 match (a, b) {
4424 (Term::Sort(u1), Term::Sort(u2)) => u1.equiv(u2),
4425
4426 (Term::Lit(l1), Term::Lit(l2)) => l1 == l2,
4427
4428 (Term::Var(n1), Term::Var(n2)) => n1 == n2,
4429
4430 (Term::Global(n1), Term::Global(n2)) => n1 == n2,
4431 (
4432 Term::Const {
4433 name: n1,
4434 levels: l1,
4435 },
4436 Term::Const {
4437 name: n2,
4438 levels: l2,
4439 },
4440 ) => n1 == n2 && l1.len() == l2.len() && l1.iter().zip(l2).all(|(a, b)| a.equiv(b)),
4441
4442 (
4443 Term::Pi {
4444 param: p1,
4445 param_type: t1,
4446 body_type: b1,
4447 },
4448 Term::Pi {
4449 param: p2,
4450 param_type: t2,
4451 body_type: b2,
4452 },
4453 ) => types_equal(t1, t2) && { bound_types_equal(p1, b1, p2, b2) },
4454
4455 (
4456 Term::Lambda {
4457 param: p1,
4458 param_type: t1,
4459 body: b1,
4460 },
4461 Term::Lambda {
4462 param: p2,
4463 param_type: t2,
4464 body: b2,
4465 },
4466 ) => types_equal(t1, t2) && { bound_types_equal(p1, b1, p2, b2) },
4467
4468 (Term::App(f1, a1), Term::App(f2, a2)) => types_equal(f1, f2) && types_equal(a1, a2),
4469
4470 (
4471 Term::Match {
4472 discriminant: d1,
4473 motive: m1,
4474 cases: c1,
4475 },
4476 Term::Match {
4477 discriminant: d2,
4478 motive: m2,
4479 cases: c2,
4480 },
4481 ) => {
4482 types_equal(d1, d2)
4483 && types_equal(m1, m2)
4484 && c1.len() == c2.len()
4485 && c1.iter().zip(c2.iter()).all(|(a, b)| types_equal(a, b))
4486 }
4487
4488 (Term::Fix { name: n1, body: b1 }, Term::Fix { name: n2, body: b2 }) => {
4489 bound_types_equal(n1, b1, n2, b2)
4490 }
4491
4492 (Term::Let { .. }, Term::Let { .. }) => let_types_equal(a, b),
4503
4504 (Term::MutualFix { .. }, Term::MutualFix { .. }) => mutual_types_equal(a, b),
4507
4508 _ => false,
4509 }
4510}
4511
4512#[inline(never)]
4514fn mutual_types_equal(a: &Term, b: &Term) -> bool {
4515 let mut store = crate::term_store::TermStore::new();
4516 let lhs = store.intern(a);
4517 let rhs = store.intern(b);
4518 store.alpha_same(lhs, rhs)
4519}
4520
4521#[inline(never)]
4524fn let_types_equal(a: &Term, b: &Term) -> bool {
4525 let (
4526 Term::Let {
4527 name: n1,
4528 ty: t1,
4529 value: v1,
4530 body: b1,
4531 },
4532 Term::Let {
4533 name: n2,
4534 ty: t2,
4535 value: v2,
4536 body: b2,
4537 },
4538 ) = (a, b)
4539 else {
4540 return false;
4541 };
4542 types_equal(t1, t2) && types_equal(v1, v2) && { bound_types_equal(n1, b1, n2, b2) }
4543}
4544
4545fn is_inhabited_by_a_literal(name: &str) -> bool {
4560 matches!(
4561 name,
4562 "Int" | "Nat" | "Float" | "Text" | "Duration" | "Date" | "Moment"
4563 )
4564}
4565
4566fn empty_match_would_be_a_lie(ctx: &Context, inductive_name: &str) -> bool {
4570 ctx.get_constructors(inductive_name).is_empty() && is_inhabited_by_a_literal(inductive_name)
4571}
4572
4573fn constructor_head(ctx: &Context, t: &Term) -> Option<(String, Vec<Term>)> {
4577 if let Some(constructor) = crate::int_inductive::literal_constructor(ctx, t) {
4578 return constructor_head(ctx, &constructor);
4579 }
4580 if let Term::Lit(Literal::Nat(value)) = t {
4581 if !crate::int_inductive::reads_nat_literal(ctx, value) {
4582 return None;
4583 }
4584 return match nat_peano_step(t) {
4585 Term::Global(z) => Some((z, Vec::new())),
4586 Term::App(s, pred) => match *s {
4587 Term::Global(succ) => Some((succ, vec![*pred])),
4588 _ => None,
4589 },
4590 _ => None,
4591 };
4592 }
4593 let mut args = Vec::new();
4594 let mut head = t;
4595 while let Term::App(f, a) = head {
4596 args.push((**a).clone());
4597 head = f;
4598 }
4599 args.reverse();
4600 match head {
4601 Term::Global(name) | Term::Const { name, .. } if ctx.is_constructor(name) => {
4602 Some((name.clone(), args))
4603 }
4604 _ => None,
4605 }
4606}
4607
4608pub(crate) fn demanded_index_constructor_head(
4612 ctx: &Context,
4613 t: &Term,
4614) -> Option<(String, Vec<Term>)> {
4615 if let Some(head) = constructor_head(ctx, t) {
4616 return Some(head);
4617 }
4618 if let Some(exposed) = crate::reduction::bounded_conversion_head(ctx, t) {
4619 if let Some(head) = constructor_head(ctx, &exposed) {
4620 return Some(head);
4621 }
4622 }
4623 let exposed = crate::reduction::normalize_checked(ctx, t).ok()?;
4627 constructor_head(ctx, &exposed)
4628}
4629
4630fn disjointness_available(ctx: &Context, ctor: &str) -> bool {
4640 let Some(ind) = ctx.constructor_inductive(ctor) else {
4641 return false;
4642 };
4643 let Some(ind_ty) = ctx.get_global(&ind) else {
4644 return false;
4645 };
4646 let mut cur = ind_ty;
4647 while let Term::Pi { body_type, .. } = cur {
4648 cur = body_type;
4649 }
4650 matches!(cur, Term::Sort(level) if level.is_never_prop())
4651}
4652
4653fn indices_clash(ctx: &Context, scrutinee: &Term, declared: &Term, flexible: &[String]) -> bool {
4665 if let Term::Var(v) = declared {
4666 if flexible.iter().any(|f| f == v) {
4667 return false;
4668 }
4669 }
4670 let Some((cd, args_d)) = constructor_head(ctx, declared) else {
4673 return false;
4674 };
4675 let Some((cs, args_s)) = demanded_index_constructor_head(ctx, scrutinee) else {
4676 return false;
4677 };
4678 if !disjointness_available(ctx, &cs) || !disjointness_available(ctx, &cd) {
4679 return false;
4680 }
4681 if cs != cd {
4682 return ctx.constructor_inductive(&cs) == ctx.constructor_inductive(&cd);
4683 }
4684 args_s
4685 .iter()
4686 .zip(args_d.iter())
4687 .any(|(a, b)| indices_clash(ctx, a, b, flexible))
4688}
4689
4690pub(crate) fn constructors_the_indices_allow(
4706 ctx: &Context,
4707 inductive_name: &str,
4708 num_params: usize,
4709 disc_args: &[Term],
4710) -> Vec<usize> {
4711 let (params, disc_indices) = disc_args.split_at(num_params.min(disc_args.len()));
4712 ctx.get_constructors(inductive_name)
4713 .iter()
4714 .enumerate()
4715 .filter(|(_, (_, ctor_type))| {
4716 let mut opened: Term = (*ctor_type).clone();
4717 for value in params {
4718 match opened {
4719 Term::Pi {
4720 param, body_type, ..
4721 } => opened = substitute(&body_type, ¶m, value),
4722 _ => return true,
4723 }
4724 }
4725 let mut flexible: Vec<String> = Vec::new();
4726 let mut cur = &opened;
4727 while let Term::Pi {
4728 param, body_type, ..
4729 } = cur
4730 {
4731 flexible.push(param.clone());
4732 cur = body_type;
4733 }
4734 let result_args = extract_type_args(cur);
4735 let declared: &[Term] = if result_args.len() > num_params {
4736 &result_args[num_params..]
4737 } else {
4738 &[]
4739 };
4740 !disc_indices
4741 .iter()
4742 .zip(declared.iter())
4743 .any(|(s, d)| indices_clash(ctx, s, d, &flexible))
4744 })
4745 .map(|(i, _)| i)
4746 .collect()
4747}
4748
4749pub(crate) fn is_subsingleton_prop(ctx: &Context, inductive_name: &str) -> KernelResult<bool> {
4773 let ctors = ctx.get_constructors(inductive_name);
4774 match ctors.len() {
4775 0 => Ok(true),
4776 1 => {
4777 let num_params = ctx.inductive_num_params(inductive_name);
4778 let mut local = ctx.clone();
4779 let mut t = ctors[0].1.clone();
4780 let mut i = 0usize;
4781 let mut owed: Vec<(String, usize)> = Vec::new();
4784 let mut bound: Vec<(String, String)> = Vec::new();
4788 while let Term::Pi {
4789 param,
4790 param_type,
4791 body_type,
4792 } = t
4793 {
4794 if i >= num_params && !infer_sort(&local, ¶m_type)?.equiv(&Universe::Prop) {
4795 owed.push((param.clone(), bound.len()));
4796 }
4797 let original = param.clone();
4798 let (param, body_type) =
4799 open_context_binder(&local, ¶m, ¶m_type, &body_type);
4800 let opened = param.to_string();
4801 t = body_type.into_owned();
4802 local = local.extend(&opened, (*param_type).clone());
4803 bound.push((original, opened));
4804 i += 1;
4805 }
4806 if owed.is_empty() {
4807 return Ok(true);
4808 }
4809 let args = extract_type_args(&t);
4812 let indices: &[Term] = if args.len() > num_params {
4813 &args[num_params..]
4814 } else {
4815 &[]
4816 };
4817 Ok(owed.iter().all(|(original, position)| {
4818 let name = &bound[*position].1;
4819 bound.iter().filter(|(old, _)| old == original).count() == 1
4820 && indices
4821 .iter()
4822 .any(|ix| matches!(ix, Term::Var(v) if v == name))
4823 }))
4824 }
4825 _ => Ok(false),
4826 }
4827}
4828
4829#[cfg(test)]
4830#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/type_checker/def_eq_and_freshness_mutation_kills.rs"]
4831mod def_eq_and_freshness_mutation_kills;
4832
4833#[cfg(test)]
4834#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/type_checker/large_elim_tests.rs"]
4835mod large_elim_tests;
4836
4837#[cfg(test)]
4838#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/type_checker/constructor_universe_controls.rs"]
4839mod constructor_universe_controls;
4840
4841#[cfg(test)]
4842#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/type_checker/native_mutual_alpha_regressions.rs"]
4843mod native_mutual_alpha_regressions;
4844
4845#[cfg(test)]
4846#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/type_checker/early_binder_conversion_controls.rs"]
4847mod early_binder_conversion_controls;
4848
4849#[cfg(test)]
4850#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/type_checker/type_head_work_controls.rs"]
4851mod type_head_work_controls;
4852
4853#[cfg(test)]
4854#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/type_checker/head_alignment_conversion_controls.rs"]
4855mod head_alignment_conversion_controls;
4856
4857#[cfg(test)]
4858#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/type_checker/head_alignment_exactness_controls.rs"]
4859mod head_alignment_exactness_controls;
4860
4861#[cfg(test)]
4862#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/type_checker/head_alignment_float_contract_controls.rs"]
4863mod head_alignment_float_contract_controls;
4864
4865#[cfg(test)]
4866#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/type_checker/delta_head_alignment_controls.rs"]
4867mod delta_head_alignment_controls;
4868
4869#[cfg(test)]
4870#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/type_checker/delta_head_hint_boundaries.rs"]
4871mod delta_head_hint_boundaries;
4872
4873#[cfg(test)]
4874#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/type_checker/delta_head_chain_controls.rs"]
4875mod delta_head_chain_controls;
4876
4877#[cfg(test)]
4878#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/type_checker/borrowed_common_head_work.rs"]
4879mod borrowed_common_head_work;
4880
4881#[cfg(test)]
4882#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/type_checker/closed_helper_body_controls.rs"]
4883mod closed_helper_body_controls;
4884
4885#[cfg(test)]
4886#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/type_checker/closed_helper_body_admission_controls.rs"]
4887mod closed_helper_body_admission_controls;
4888
4889#[cfg(test)]
4890#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/type_checker/borrowed_fixed_head_controls.rs"]
4891mod borrowed_fixed_head_controls;
4892
4893#[cfg(test)]
4894#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/type_checker/constructor_probe_guard_controls.rs"]
4895mod constructor_probe_guard_controls;
4896
4897#[cfg(test)]
4898#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/type_checker/fix_result_eligibility_controls.rs"]
4899mod fix_result_eligibility_controls;
4900
4901#[cfg(test)]
4902#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/type_checker/fix_lambda_probe_controls.rs"]
4903mod fix_lambda_probe_controls;
4904
4905#[cfg(test)]
4906#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/type_checker/peano_inference_controls.rs"]
4907mod peano_inference_controls;
4908
4909#[cfg(test)]
4910#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/type_checker/peano_inference_boundary_controls.rs"]
4911mod peano_inference_boundary_controls;
4912
4913#[cfg(test)]
4914#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/type_checker/peano_explicit_poly_control.rs"]
4915mod peano_explicit_poly_control;
4916
4917#[cfg(test)]
4918#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/type_checker/opaque_sort_reuse_controls.rs"]
4919mod opaque_sort_reuse_controls;
4920
4921#[cfg(test)]
4922#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/type_checker/binder_entry_scope_controls.rs"]
4923mod binder_entry_scope_controls;
4924
4925#[cfg(test)]
4926#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/type_checker/owned_substitution_controls.rs"]
4927mod owned_substitution_controls;
4928
4929#[cfg(test)]
4930#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/type_checker/owned_replacement_controls.rs"]
4931mod owned_replacement_controls;
4932
4933#[cfg(test)]
4934#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/type_checker/bounded_conversion_controls.rs"]
4935mod bounded_conversion_controls;
4936
4937#[cfg(test)]
4938#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/type_checker/borrowed_retry_controls.rs"]
4939mod borrowed_retry_controls;
4940
4941#[cfg(test)]
4942#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/type_checker/probe_scheduling_controls.rs"]
4943mod probe_scheduling_controls;
4944
4945#[cfg(test)]
4946#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/type_checker/constructor_refutation_controls.rs"]
4947mod constructor_refutation_controls;
4948
4949#[path = "lazy_delta.rs"]
4950mod lazy_delta;
4951
4952#[cfg(test)]
4953#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/type_checker/lazy_delta_controls.rs"]
4954mod lazy_delta_controls;
4955
4956#[cfg(test)]
4957#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/type_checker/recursor_probe_scheduling_controls.rs"]
4958mod recursor_probe_scheduling_controls;