logicaffeine_kernel/positivity.rs
1//! Strict positivity checking for inductive types.
2//!
3//! An inductive type must appear only in "strictly positive" positions in its constructors.
4//! Without this check, we could define paradoxical types like:
5//!
6//! ```text
7//! Inductive Bad := Cons : (Bad -> False) -> Bad
8//! ```
9//!
10//! This would allow encoding Russell's paradox and proving False.
11//!
12//! Strict Positivity Rules (from CIC):
13//!
14//! I is strictly positive in T iff:
15//! 1. I does not occur in T, OR
16//! 2. T = Π(x:A). B where:
17//! - If A = I exactly, it's a "recursive argument" (allowed)
18//! - Otherwise, I must NOT occur in A at all
19//! - AND I must be strictly positive in B
20//!
21//! Examples:
22//! - `I -> I` is valid: first I is a recursive argument, second is result
23//! - `(I -> X) -> I` is INVALID: I occurs inside the param type of another arrow
24//! - `X -> I -> I` is valid: X has no I, second param is recursive arg
25
26use crate::context::Context;
27use crate::error::{KernelError, KernelResult};
28use crate::term::Term;
29use std::cell::{Cell, RefCell};
30use std::collections::{HashMap, HashSet};
31
32/// Check strict positivity in a constructor type without unfolding definitions.
33///
34/// Use [`check_positivity_resolved`] at declaration boundaries, where a context is
35/// available. This syntactic variant supports callers whose input has already been
36/// expanded and provides an independent comparison for alias-free types.
37pub fn check_positivity(inductive: &str, constructor: &str, ty: &Term) -> KernelResult<()> {
38 check_strictly_positive(&Delta::blind(), &[inductive], constructor, ty)
39}
40
41/// Strict positivity with every REFERENCE resolved — the paradox fence that a definitional
42/// alias cannot walk around.
43///
44/// [`check_positivity`] reads the constructor type as written, so a name is an occurrence of
45/// the inductive only when it is SPELLED as the inductive. That is not a property of the type,
46/// it is a property of the spelling, and δ makes the two different things:
47///
48/// ```text
49/// Inductive Bad : Type 0 -- no constructors yet
50/// Definition Negate : Prop := Bad -> False
51/// Constructor cons : Negate -> Bad -- `Bad` does not literally occur in `Negate`
52/// ```
53///
54/// `Negate` is `Bad → False` up to δ, so `cons` is the Russell constructor
55/// `(Bad → False) → Bad` — and `λx. match x with | cons f => f (cons f)` then inhabits
56/// `Bad → False`, which applied to its own `cons` inhabits `False`. No fixpoint and no
57/// recursor are needed: a bare `Term::Match` does it, so no later gate can catch what this one
58/// lets past. The blind check accepts it because `occurs_in` asks whether the STRING "Bad"
59/// appears.
60///
61/// This entry point answers the same four questions about the same four shapes, but resolves a
62/// reference to a transparent definition (or a universe-polymorphic one) before deciding
63/// whether the inductive occurs in it and whether an occurrence is a legitimate recursive one.
64/// Both directions fail SAFE: a reference whose unfolding cannot be decided counts as an
65/// occurrence (so the constructor is refused), and never as a recursive one.
66pub fn check_positivity_resolved(
67 ctx: &Context,
68 inductive: &str,
69 constructor: &str,
70 ty: &Term,
71) -> KernelResult<()> {
72 check_strictly_positive(&Delta::over(ctx), &[inductive], constructor, ty)
73}
74
75/// [`check_positivity_resolved`] for a MUTUAL block — the same δ resolution, and a member
76/// hidden behind an alias is a member of the block for every question asked here.
77pub fn check_positivity_mutual_resolved(
78 ctx: &Context,
79 block: &[&str],
80 constructor: &str,
81 ty: &Term,
82) -> KernelResult<()> {
83 check_strictly_positive(&Delta::over(ctx), block, constructor, ty)
84}
85
86/// Dependencies whose meanings justified native container positivity. Empty for
87/// checks that did not use the native rule, preserving existing mutation behavior.
88pub(crate) fn native_positivity_dependencies(
89 ctx: &Context,
90 block: &[&str],
91 constructor: &str,
92 ty: &Term,
93) -> KernelResult<HashSet<String>> {
94 let delta = Delta::over(ctx);
95 check_strictly_positive(&delta, block, constructor, ty)?;
96 if !delta.used_nested.get() {
97 return Ok(HashSet::new());
98 }
99 let mut dependencies = delta.dependencies.into_inner();
100 dependencies.retain(|name| !block.contains(&name.as_str()));
101 Ok(dependencies)
102}
103
104/// Conservative occurrence query using the positivity checker's memoized
105/// definition graph. A false result means normalization cannot expose a
106/// recursive occurrence of this block; cycles conservatively answer true.
107pub(crate) fn mentions_inductive_block(ctx: &Context, block: &[&str], term: &Term) -> bool {
108 occurs_in(&Delta::over(ctx), block, term)
109}
110
111/// The δ oracle the fence consults: what a REFERENCE unfolds to, and whether that unfolding
112/// mentions the block at all.
113///
114/// `ctx: None` is the historical blind behaviour — every reference is opaque, so the answers
115/// are exactly the ones [`check_positivity`] always gave. With a context, a definition is
116/// transparent and a `Const` at explicit levels is transparent in the same way, because both
117/// are references and the paradox does not care which spelling carried it.
118///
119/// `mentions` is memoised per name: definition bodies are closed, so "does `n` mention a block
120/// member" does not depend on what `n` is applied to, and the same question is asked once per
121/// constructor rather than once per occurrence. `path` is the UNFOLDING STACK, not a global
122/// visited set: a name re-entered while it is still being unfolded is a cycle the kernel's
123/// acyclic definition graph should make impossible, and the honest answer to a question that
124/// does not terminate is the refusing one.
125struct Delta<'a> {
126 ctx: Option<&'a Context>,
127 path: RefCell<Vec<String>>,
128 mentions: RefCell<HashMap<String, bool>>,
129 nested_path: RefCell<Vec<Term>>,
130 dependencies: RefCell<HashSet<String>>,
131 used_nested: Cell<bool>,
132 // Diagnostic only: retain the innermost container field that failed the
133 // existing positivity predicate. Never used to admit or reject a term.
134 negative_container: RefCell<Option<String>>,
135 // Failure to justify a container is not evidence of negative occurrence.
136 inconclusive: Cell<bool>,
137 /// δ-unfoldings left in the HEAD position for one constructor. The definition graph is
138 /// acyclic, so this cannot be reached by a well-formed context; it is here because a fence
139 /// that loops on a malformed one is a fence that hangs the compiler instead of refusing.
140 /// Exhaustion answers in the refusing direction on both sides.
141 fuel: RefCell<u32>,
142}
143
144/// Generous by three orders of magnitude: the deepest alias chain in the standard prelude is
145/// two.
146const UNFOLD_BUDGET: u32 = 512;
147
148impl<'a> Delta<'a> {
149 fn blind() -> Self {
150 Delta {
151 ctx: None,
152 path: RefCell::new(Vec::new()),
153 mentions: RefCell::new(HashMap::new()),
154 nested_path: RefCell::new(Vec::new()),
155 dependencies: RefCell::new(HashSet::new()),
156 used_nested: Cell::new(false),
157 negative_container: RefCell::new(None),
158 inconclusive: Cell::new(false),
159 // Local beta/zeta exposure is bounded even when global delta is disabled.
160 fuel: RefCell::new(UNFOLD_BUDGET),
161 }
162 }
163
164 fn over(ctx: &'a Context) -> Self {
165 Delta {
166 ctx: Some(ctx),
167 path: RefCell::new(Vec::new()),
168 mentions: RefCell::new(HashMap::new()),
169 nested_path: RefCell::new(Vec::new()),
170 dependencies: RefCell::new(HashSet::new()),
171 used_nested: Cell::new(false),
172 negative_container: RefCell::new(None),
173 inconclusive: Cell::new(false),
174 fuel: RefCell::new(UNFOLD_BUDGET),
175 }
176 }
177
178 /// Spend one head unfolding, or report that the budget is gone.
179 fn spend(&self) -> bool {
180 let mut fuel = self.fuel.borrow_mut();
181 if *fuel == 0 {
182 return false;
183 }
184 *fuel -= 1;
185 true
186 }
187
188 /// The body `name` unfolds to, or `None` when it is opaque — an axiom, a constructor, an
189 /// inductive, an unknown name, or anything at all when this `Delta` is blind.
190 fn body(&self, name: &str) -> Option<Term> {
191 let ctx = self.ctx?;
192 self.dependencies.borrow_mut().insert(name.to_string());
193 if let Some(b) = ctx.get_definition_body(name) {
194 return Some(b.clone());
195 }
196 ctx.get_universe_poly(name).map(|(_, _, body)| body.clone())
197 }
198
199 /// Whether `name`'s unfolding mentions a member of `block`. `false` for every opaque name,
200 /// which is what makes the common case — a constructor field of some unrelated type —
201 /// cost one hash lookup.
202 fn mentions(&self, block: &[&str], name: &str) -> bool {
203 if self.ctx.is_none() {
204 return false;
205 }
206 if let Some(known) = self.mentions.borrow().get(name) {
207 return *known;
208 }
209 if self.path.borrow().iter().any(|n| n == name) {
210 return true;
211 }
212 let Some(body) = self.body(name) else {
213 self.mentions.borrow_mut().insert(name.to_string(), false);
214 return false;
215 };
216 self.path.borrow_mut().push(name.to_string());
217 let answer = occurs_in(self, block, &body);
218 self.path.borrow_mut().pop();
219 self.mentions.borrow_mut().insert(name.to_string(), answer);
220 answer
221 }
222}
223
224/// β-apply a CLOSED definition body to `args`, or `None` when it runs out of λs first.
225///
226/// Positivity in CIC is a property of the type UP TO CONVERSION, so `GTo GList` where
227/// `GTo := λX. Nat → X` has to be judged as the `Nat → GList` it is — a strictly-positive
228/// functional field — and `GNegOf GBad` where `GNegOf := λX. X → False` as the `GBad → False`
229/// it is. Judging the spelling instead refuses the first and admits the second.
230///
231/// The substitution is `type_checker::substitute`, which α-renames a binder that would capture
232/// a free variable of the argument. There is deliberately no second implementation of it here:
233/// a paradox fence that substitutes differently from the kernel is a fence around a different
234/// language.
235fn beta_apply(body: &Term, args: &[&Term]) -> Option<Term> {
236 let mut cur = body.clone();
237 for a in args {
238 match cur {
239 Term::Lambda { param, body, .. } => {
240 cur = crate::type_checker::substitute(&body, ¶m, a);
241 }
242 _ => return None,
243 }
244 }
245 Some(cur)
246}
247
248/// The name a reference carries, whether written monomorphically or at explicit levels.
249fn ref_name(t: &Term) -> Option<&str> {
250 match t {
251 Term::Global(n) | Term::Const { name: n, .. } => Some(n.as_str()),
252 _ => None,
253 }
254}
255
256/// Check strict positivity of a MUTUAL BLOCK of inductives in a constructor type.
257///
258/// A constructor of one block member may recursively reference ANY member — `Even`'s
259/// `even_succ : Π(n). Odd n → Even (Succ n)` places the sibling `Odd` in a
260/// strictly-positive recursive position. The block is treated as a single "inductive"
261/// for positivity: an occurrence of any member to the RIGHT of every arrow is a
262/// (recursive) occurrence and allowed; any member in a DOMAIN is a negative
263/// occurrence and rejected — so a cross-block paradox `(Even n → False) → Odd n` is
264/// caught exactly as a self-negative one is.
265pub fn check_positivity_mutual(block: &[&str], constructor: &str, ty: &Term) -> KernelResult<()> {
266 check_strictly_positive(&Delta::blind(), block, constructor, ty)
267}
268
269/// Check that the inductive appears only strictly positively.
270///
271/// At the top level of constructor type, we allow:
272/// - I as a direct parameter type (recursive argument)
273/// - I in the final result type
274/// - But NOT I nested inside function types within parameters
275fn check_strictly_positive(
276 delta: &Delta<'_>,
277 block: &[&str],
278 constructor: &str,
279 ty: &Term,
280) -> KernelResult<()> {
281 let negative = |where_: &str| {
282 if delta.inconclusive.get() {
283 return Err(KernelError::CertificationError(format!(
284 "native positivity check is inconclusive for constructor '{constructor}' ({where_})"
285 )));
286 }
287 let mut reason = format!(
288 "'{}' occurs in negative position ({where_})",
289 block.join("/")
290 );
291 if let Some(origin) = delta.negative_container.borrow().as_ref() {
292 reason.push_str(" through ");
293 reason.push_str(origin);
294 }
295 Err(KernelError::PositivityViolation {
296 inductive: block.join("/"),
297 constructor: constructor.to_string(),
298 reason,
299 })
300 };
301 match ty {
302 // Direct occurrence of a block member is always fine (either as recursive argument
303 // or result type), whether written monomorphically or at explicit levels.
304 Term::Global(name) | Term::Const { name, .. } if block.contains(&name.as_str()) => Ok(()),
305
306 // Pi type: Π(x:A). B
307 Term::Pi {
308 param_type,
309 body_type,
310 ..
311 } => {
312 // Check the parameter type A.
313 // If A is a recursive argument (a block member `I` applied to its
314 // parameters, with no block member occurring in the arguments — `I`,
315 // `I a`, `List A`, `Odd n`, …), it is a strictly-positive recursive
316 // occurrence (allowed). Otherwise no block member may occur in A at all.
317 if !is_recursive_arg(delta, block, param_type) && occurs_in(delta, block, param_type) {
318 return negative("inside parameter type");
319 }
320
321 // Recursively check the body type B
322 check_strictly_positive(delta, block, constructor, body_type)
323 }
324
325 // Application: check both parts, and — when the head is a REFERENCE that unfolds —
326 // the shape it unfolds to. `AliasI a` is `I a` and `Negate a` may be `a → False`;
327 // reading only the spelling is how the fence is walked around.
328 Term::App(func, arg) => {
329 let mut head = ty;
330 let mut args: Vec<&Term> = Vec::new();
331 while let Term::App(f, a) = head {
332 args.push(a.as_ref());
333 head = f.as_ref();
334 }
335 args.reverse();
336 if matches!(head, Term::Lambda { .. }) && !args.is_empty() {
337 // Reuse the same capture-safe beta exposure as recursive-field
338 // classification. The original constructor is typed separately.
339 if !delta.spend() {
340 delta.inconclusive.set(true);
341 return negative("inside an exhausted beta telescope");
342 }
343 let Some(mut reduced) = beta_apply(head, &args[..1]) else {
344 delta.inconclusive.set(true);
345 return negative("inside an unexposed beta telescope");
346 };
347 for argument in &args[1..] {
348 reduced = Term::App(Box::new(reduced), Box::new((*argument).clone()));
349 }
350 return check_strictly_positive(delta, block, constructor, &reduced);
351 }
352 // A head that UNFOLDS is resolved before it is judged; one that does not — an
353 // inductive, an axiom, a constructor, or any head at all when this fence is blind —
354 // falls through to the structural walk below, exactly as before.
355 if let Some(name) = ref_name(head).filter(|n| !block.contains(n)) {
356 let could_reach =
357 delta.mentions(block, name) || args.iter().any(|a| occurs_in(delta, block, a));
358 if let Some(body) = could_reach.then(|| delta.body(name)).flatten() {
359 let Some(reduced) = delta.spend().then(|| beta_apply(&body, &args)).flatten()
360 else {
361 delta.inconclusive.set(true);
362 return negative("inside a reference this fence cannot resolve");
363 };
364 return check_strictly_positive(delta, block, constructor, &reduced);
365 }
366 }
367 check_strictly_positive(delta, block, constructor, func)?;
368 check_strictly_positive(delta, block, constructor, arg)
369 }
370
371 // Lambda (unusual in types, but handle it)
372 Term::Lambda {
373 param_type, body, ..
374 } => {
375 // Same rule as Pi for param_type
376 if !is_recursive_arg(delta, block, param_type) && occurs_in(delta, block, param_type) {
377 return negative("inside lambda parameter");
378 }
379 check_strictly_positive(delta, block, constructor, body)
380 }
381
382 // Other terms: no occurrences of the inductive to worry about
383 Term::Sort(_) => Ok(()),
384 Term::Var(_) => Ok(()),
385 // Some other declaration, not a block member — monomorphic or universe-polymorphic.
386 // A TRANSPARENT one is a reference, not a leaf: if its unfolding mentions the block,
387 // the shape that matters is the unfolding's, and it is checked here rather than
388 // believed to be absent.
389 Term::Global(_) | Term::Const { .. } => {
390 let name = ref_name(ty).expect("a Global/Const carries a name");
391 if !delta.mentions(block, name) {
392 return Ok(());
393 }
394 match delta.body(name) {
395 Some(body) => check_strictly_positive(delta, block, constructor, &body),
396 None => {
397 delta.inconclusive.set(true);
398 negative("inside an unfoldable reference")
399 }
400 }
401 }
402 Term::Lit(_) => Ok(()), // Literals cannot contain inductives
403
404 // Match in types (unusual but possible)
405 Term::Match {
406 discriminant,
407 motive,
408 cases,
409 } => {
410 check_strictly_positive(delta, block, constructor, discriminant)?;
411 check_strictly_positive(delta, block, constructor, motive)?;
412 for case in cases {
413 check_strictly_positive(delta, block, constructor, case)?;
414 }
415 Ok(())
416 }
417
418 // Fix in types (very unusual)
419 Term::Fix { body, .. } => check_strictly_positive(delta, block, constructor, body),
420
421 // Mutual fix in types (very unusual): check every definition's body.
422 Term::MutualFix { defs, .. } => {
423 for (_, body) in defs {
424 check_strictly_positive(delta, block, constructor, body)?;
425 }
426 Ok(())
427 }
428
429 // Checked declaration paths type the ORIGINAL Let before accepting
430 // positivity. Its value's occurrences acquire polarity only after zeta.
431 Term::Let {
432 name, value, body, ..
433 } => {
434 if !delta.spend() {
435 delta.inconclusive.set(true);
436 return negative("inside an exhausted let telescope");
437 }
438 let exposed = crate::type_checker::substitute(body, name, value);
439 check_strictly_positive(delta, block, constructor, &exposed)
440 }
441
442 // Hole: type placeholder, no occurrences to check
443 Term::Hole => Ok(()),
444
445 // An annotation hides no occurrence: the term under it is checked in the same position.
446 Term::Annotated { term, .. } => check_strictly_positive(delta, block, constructor, term),
447 }
448}
449
450/// True if `term` is a strictly-positive recursive occurrence of `inductive` —
451/// possibly a FUNCTIONAL one. Two shapes:
452/// - a TELESCOPE `Π(z:B). rest` where `inductive` does not occur in the domain
453/// `B` (so it is not in a negative position) and `rest` is itself a recursive
454/// occurrence — e.g. `Acc_intro`'s field `Π(y:A). R y x → Acc A R y`, or a
455/// rose tree's `Nat → Tree`; and
456/// - the BASE `I e₁ … eₙ`: the inductive applied to arguments that do not mention
457/// it (`I`, `I a`, `List A`, an indexed `Acc A R y`).
458///
459/// This is exactly CIC strict positivity: the inductive may appear only to the
460/// RIGHT of every arrow. A negative occurrence (`Bad → …`, `(Bad → X) → …`) puts
461/// it in a domain, so `is_recursive_arg` returns `false` and the caller's
462/// `occurs_in` check then rejects the constructor.
463///
464/// A δ-TRANSPARENT reference is followed, in the one direction that cannot widen the fence:
465/// the arguments must already be free of the block (so unfolding cannot smuggle a member in
466/// through a substitution), the body is closed, and what it unfolds to has to satisfy this
467/// same predicate. An alias for a recursive occurrence is one; an alias for `Bad → False` is
468/// not, because its unfolding puts the block in a domain.
469fn is_recursive_arg(delta: &Delta<'_>, block: &[&str], term: &Term) -> bool {
470 match term {
471 Term::Pi {
472 param_type,
473 body_type,
474 ..
475 } => !occurs_in(delta, block, param_type) && is_recursive_arg(delta, block, body_type),
476 _ => {
477 let mut head = term;
478 let mut args: Vec<&Term> = Vec::new();
479 while let Term::App(func, arg) = head {
480 args.push(arg.as_ref());
481 head = func.as_ref();
482 }
483 args.reverse();
484 if matches!(head, Term::Lambda { .. }) && !args.is_empty() {
485 if !delta.spend() {
486 delta.inconclusive.set(true);
487 return false;
488 }
489 // Checked constructor entry points require original source
490 // typing as well as this positive result; no ill-typed erased
491 // argument is admitted. Reuse delta aliases' capture-safe beta.
492 let Some(mut reduced) = beta_apply(head, &args[..1]) else {
493 delta.inconclusive.set(true);
494 return false;
495 };
496 for argument in &args[1..] {
497 reduced = Term::App(Box::new(reduced), Box::new((*argument).clone()));
498 }
499 return is_recursive_arg(delta, block, &reduced);
500 }
501 if is_block_member(block, head) {
502 // `I e₁ … eₙ` — the BASE shape. The block may not occur in the index
503 // arguments: `I (I a)` is not a recursive occurrence of `I`, it is `I` applied
504 // to one.
505 return args.iter().all(|a| !occurs_in(delta, block, a));
506 }
507 let Some(name) = ref_name(head).filter(|n| !block.contains(n)) else {
508 return false;
509 };
510 // Unfold when the block could be in there AT ALL — either the definition's own body
511 // mentions it, or an ARGUMENT does. The second half is the one `GTo GList` needs:
512 // `GTo := λX. Nat → X` mentions nothing, and the recursive occurrence arrives
513 // through the argument, so gating on the body alone refuses an ordinary rose tree.
514 if !delta.mentions(block, name) && !args.iter().any(|a| occurs_in(delta, block, a)) {
515 return false;
516 }
517 let Some(body) = delta.body(name) else {
518 return nested_container_arg(delta, block, head, &args);
519 };
520 match delta.spend().then(|| beta_apply(&body, &args)).flatten() {
521 Some(reduced) => is_recursive_arg(delta, block, &reduced),
522 None => {
523 delta.inconclusive.set(true);
524 false
525 }
526 }
527 }
528 }
529}
530
531// A registered container is covariant only if every constructor preserves that
532// property after fixing its uniform parameters. This is a constructor check,
533// not a whitelist of names or a guess from the container's arity.
534//
535// An indexed container (`Vec α n`) is judged the same way: its parameters are fixed, its index
536// arguments must not mention the block, and each constructor may return the container at any
537// indices of its own — the parameters, never the indices, are what nesting instantiates.
538fn nested_container_arg(delta: &Delta<'_>, block: &[&str], head: &Term, args: &[&Term]) -> bool {
539 let unsupported = || {
540 delta.inconclusive.set(true);
541 false
542 };
543 let Some(ctx) = delta.ctx else {
544 return unsupported();
545 };
546 let Some(name) = ref_name(head) else {
547 return unsupported();
548 };
549 delta.dependencies.borrow_mut().insert(name.to_string());
550 let parameters = ctx.inductive_num_params(name);
551 if !ctx.is_inductive(name)
552 || parameters == 0
553 || parameters > ctx.inductive_arity(name)
554 || args.len() != ctx.inductive_arity(name)
555 {
556 return unsupported();
557 }
558 if args[parameters..]
559 .iter()
560 .any(|index| occurs_in(delta, block, index))
561 {
562 return unsupported();
563 }
564 let Ok(mut arity) = crate::infer_type(ctx, head) else {
565 return unsupported();
566 };
567 let mut domains = Vec::with_capacity(parameters);
568 for (position, argument) in args.iter().enumerate() {
569 let Term::Pi {
570 param,
571 param_type,
572 body_type,
573 } = arity
574 else {
575 return unsupported();
576 };
577 if position < parameters {
578 // Only a type parameter can carry the block into the container; a value
579 // parameter (`VBox 3 T`'s `3`) must not mention it at all.
580 if !matches!(param_type.as_ref(), Term::Sort(_)) && occurs_in(delta, block, argument) {
581 return unsupported();
582 }
583 domains.push(*param_type);
584 }
585 arity = crate::type_checker::substitute(&body_type, ¶m, argument);
586 }
587 if !matches!(arity, Term::Sort(_)) {
588 return unsupported();
589 }
590 delta.used_nested.set(true);
591 // The container at these parameters, whatever its indices: the unit nesting instantiates.
592 let instance = args[..parameters].iter().fold(head.clone(), |f, a| {
593 Term::App(Box::new(f), Box::new((*a).clone()))
594 });
595 // Revisiting this exact instantiated container closes only a positive
596 // constructor-field cycle. A function domain is rejected by is_recursive_arg
597 // before control can reach this assumption.
598 if delta
599 .nested_path
600 .borrow()
601 .iter()
602 .any(|active| *active == instance)
603 {
604 return true;
605 }
606 if !delta.spend() {
607 return unsupported();
608 }
609 delta.nested_path.borrow_mut().push(instance.clone());
610 let answer = (|| {
611 for (constructor, _) in ctx.get_constructors(name) {
612 delta
613 .dependencies
614 .borrow_mut()
615 .insert(constructor.to_string());
616 let reference = match head {
617 Term::Const { levels, .. } => Term::Const {
618 name: constructor.into(),
619 levels: levels.clone(),
620 },
621 _ => Term::Global(constructor.into()),
622 };
623 let Ok(mut ty) = crate::infer_type(ctx, &reference) else {
624 return unsupported();
625 };
626 for (argument, domain) in args[..parameters].iter().zip(&domains) {
627 let Term::Pi {
628 param,
629 param_type,
630 body_type,
631 } = ty
632 else {
633 return unsupported();
634 };
635 if *param_type != *domain {
636 return unsupported();
637 }
638 ty = crate::type_checker::substitute(&body_type, ¶m, argument);
639 }
640 while let Term::Pi {
641 param_type,
642 body_type,
643 ..
644 } = ty
645 {
646 if occurs_in(delta, block, ¶m_type)
647 && !is_recursive_arg(delta, block, ¶m_type)
648 {
649 if !delta.inconclusive.get() {
650 let mut origin = delta.negative_container.borrow_mut();
651 if origin.is_none() {
652 *origin =
653 Some(format!("container '{name}', constructor '{constructor}'"));
654 }
655 }
656 return false;
657 }
658 ty = *body_type;
659 }
660 // The constructor must return this instance at indices of its own, preserving
661 // every parameter. Dropping an unused parameter is not an admissible rewrite.
662 let mut result_head = &ty;
663 let mut result_args = Vec::new();
664 while let Term::App(f, a) = result_head {
665 result_args.push(a.as_ref());
666 result_head = f;
667 }
668 result_args.reverse();
669 if result_head != head
670 || result_args.len() != args.len()
671 || result_args[..parameters] != args[..parameters]
672 || result_args[parameters..]
673 .iter()
674 .any(|index| occurs_in(delta, block, index))
675 {
676 return unsupported();
677 }
678 }
679 true
680 })();
681 delta.nested_path.borrow_mut().pop();
682 answer
683}
684
685/// True if `term` REFERS to a member of the block — the head of a recursive occurrence.
686///
687/// A reference is a member whether it is written monomorphically (`Term::Global`) or at
688/// explicit universe levels (`Term::Const`). Treating `Const` as inert here would make a
689/// universe-polymorphic recursive occurrence invisible: `Π(_:Nat). Bad.{u}` would stop
690/// being recognised as a strictly-positive recursive argument and be REFUSED, while
691/// `occurs_in`'s matching blind spot would let the negative `(Bad.{u} → False) → Bad.{u}`
692/// through. The two halves must agree, so both read the name from the same place.
693fn is_block_member(block: &[&str], term: &Term) -> bool {
694 match term {
695 Term::Global(name) | Term::Const { name, .. } => block.contains(&name.as_str()),
696 _ => false,
697 }
698}
699
700/// Check if any block member's name occurs anywhere in the term, THROUGH δ.
701///
702/// `Term::Const` is a REFERENCE, not an inert leaf. The moment a `Const` can name an
703/// inductive — which is exactly what universe-polymorphic inductives require — skipping it
704/// here would hide a negative recursive occurrence from the paradox fence: `Bad.{u}` in a
705/// constructor domain would read as "the inductive does not occur", and
706/// `Cons : (Bad.{u} → False) → Bad.{u}` would be accepted. Universe levels cannot mention
707/// an inductive, so the `levels` carry nothing to descend into.
708///
709/// A TRANSPARENT definition is a reference for the same reason a `Const` is. `Negate` whose
710/// body is `Bad → False` mentions `Bad`, and a fence that answers "no" there is a fence with
711/// a δ-shaped hole in it — see [`check_positivity_resolved`] for the paradox it admits.
712/// [`Delta::blind`] restores the name-only answer for the historical entry points.
713fn occurs_in(delta: &Delta<'_>, block: &[&str], term: &Term) -> bool {
714 match term {
715 Term::Global(name) | Term::Const { name, .. } => {
716 block.contains(&name.as_str()) || delta.mentions(block, name)
717 }
718 Term::Sort(_) | Term::Var(_) | Term::Lit(_) => false,
719 Term::Pi {
720 param_type,
721 body_type,
722 ..
723 } => occurs_in(delta, block, param_type) || occurs_in(delta, block, body_type),
724 Term::Lambda {
725 param_type, body, ..
726 } => occurs_in(delta, block, param_type) || occurs_in(delta, block, body),
727 Term::App(func, arg) => occurs_in(delta, block, func) || occurs_in(delta, block, arg),
728 Term::Match {
729 discriminant,
730 motive,
731 cases,
732 } => {
733 occurs_in(delta, block, discriminant)
734 || occurs_in(delta, block, motive)
735 || cases.iter().any(|c| occurs_in(delta, block, c))
736 }
737 Term::Fix { body, .. } => occurs_in(delta, block, body),
738 Term::MutualFix { defs, .. } => defs.iter().any(|(_, b)| occurs_in(delta, block, b)),
739 Term::Let {
740 ty, value, body, ..
741 } => {
742 occurs_in(delta, block, ty)
743 || occurs_in(delta, block, value)
744 || occurs_in(delta, block, body)
745 }
746 Term::Hole => false, // Holes don't contain inductives
747 Term::Annotated { term, .. } => occurs_in(delta, block, term),
748 }
749}
750
751#[cfg(test)]
752#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/positivity/tests.rs"]
753mod tests;
754
755#[cfg(test)]
756#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/positivity/constructor_exposure_budget_controls.rs"]
757mod constructor_exposure_budget_controls;