8000 Option to internalize a qualid passed to an Ltac as a constr with its impargs by SkySkimmer · Pull Request #20682 · rocq-prover/rocq · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

Option to internalize a qualid passed to an Ltac as a constr with its impargs #20682

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

SkySkimmer
Copy link
Contributor

This was the case in non-strict mode (via interpretation at runtime), but, in strict mode, it was instead the reference without its maximal implicit arguments.

Also deprecate the old strict mode internalization.

For compat with enabling the option, the main impact is on "class_apply" which we reformulate as a tactic notation to ensure that its argument is always interpreted as a term.

Replaces #17084 in a more backward compatible way.

@coqbot-app coqbot-app bot added the needs: full CI The latest GitLab pipeline that ran was a light CI. Say "@coqbot run full ci" to get a full CI. label May 26, 2025
@SkySkimmer SkySkimmer added the request: full CI Use this label when you want your next push to trigger a full CI. label May 26, 2025
@SkySkimmer SkySkimmer force-pushed the ltac1-depr-noninserted-implicits branch from 5181e99 to 7031535 Compare May 26, 2025 11:52
@coqbot-app coqbot-app bot removed request: full CI Use this label when you want your next push to trigger a full CI. needs: full CI The latest GitLab pipeline that ran was a light CI. Say "@coqbot run full ci" to get a full CI. labels May 26, 2025
@SkySkimmer SkySkimmer marked this pull request as ready for review May 26, 2025 11:58
@SkySkimmer SkySkimmer requested review from a team as code owners May 26, 2025 11:58
@SkySkimmer SkySkimmer added part: ltac Issues and PRs related to the Ltac tactic language. kind: enhancement Enhancement to an existing user-facing feature, tactic, etc. labels May 26, 2025
@SkySkimmer SkySkimmer added this to the 9.1+rc1 milestone May 26, 2025
Copy link
Contributor
coqbot-app bot commented May 26, 2025

🔴 CI failures at commit 7031535 without any failure in the test-suite

✔️ Corresponding jobs for the base commit f38be3d succeeded

❔ Ask me to try to extract minimal test cases that can be added to the test-suite

🏃 @coqbot ci minimize will minimize the following targets: ci-compcert, ci-metarocq
  • You can also pass me a specific list of targets to minimize as arguments.

@SkySkimmer
Copy link
Contributor Author

@coqbot ci minimize

Copy link
Contributor
coqbot-app bot commented May 26, 2025

I have initiated minimization at commit 7031535 for the suggested targets ci-compcert, ci-metarocq as requested.

Copy link
Contributor
coqbot-app bot commented May 26, 2025

🔴 CI failures at commit 7031535 without any failure in the test-suite

✔️ Corresponding jobs for the base commit f38be3d succeeded

❔ Ask me to try to extract minimal test cases that can be added to the test-suite

🏃 @coqbot ci minimize will minimize the following targets: ci-compcert, ci-metarocq
  • You can also pass me a specific list of targets to minimize as arguments.

Copy link
Contributor
coqbot-app bot commented May 26, 2025

Minimized File /home/runner/work/run-coq-bug-minimizer/run-coq-bug-minimizer/builds/coq/coq-failing/_build_ci/compcert/backend/Unusedglobproof.v in 4h 11m 28s (from ci-compcert) (full log on GitHub Actions - verbose log)

We are collecting data on the user experience of the Coq Bug Minimizer.
If you haven't already filled the survey for this PR, please fill out our short survey!

🌟 Minimized Coq File (consider adding this file to the test-suite)
(* -*- mode: coq; coq-prog-args: ("-emacs" "-q" "-native-compiler" "no" "-w" "-undeclared-scope" "-w" "-omega-is-deprecated" "-coqlib" "/github/workspace/builds/coq/coq-failing/_install_ci/lib/coq//" "-R" "/github/workspace/builds/coq/coq-failing/_build_ci/compcert/lib" "compcert.lib" "-R" "/github/workspace/builds/coq/coq-failing/_build_ci/compcert/common" "compcert.common" "-R" "/github/workspace/builds/coq/coq-failing/_build_ci/compcert/x86_32" "compcert.x86_32" "-R" "/github/workspace/builds/coq/coq-failing/_build_ci/compcert/x86" "compcert.x86" "-R" "/github/workspace/builds/coq/coq-failing/_build_ci/compcert/backend" "compcert.backend" "-R" "/github/workspace/builds/coq/coq-failing/_build_ci/compcert/cfrontend" "compcert.cfrontend" "-R" "/github/workspace/builds/coq/coq-failing/_build_ci/compcert/driver" "compcert.driver" "-R" "/github/workspace/builds/coq/coq-failing/
8000
_build_ci/compcert/cparser" "compcert.cparser" "-R" "/github/workspace/builds/coq/coq-failing/_build_ci/compcert/export" "compcert.export" "-Q" "/github/workspace/cwd" "Top" "-Q" "/github/workspace/builds/coq/coq-failing/_install_ci/lib/coq///user-contrib/Flocq" "Flocq" "-Q" "/github/workspace/builds/coq/coq-failing/_install_ci/lib/coq///user-contrib/Ltac2" "Ltac2" "-Q" "/github/workspace/builds/coq/coq-failing/_install_ci/lib/coq///user-contrib/MenhirLib" "MenhirLib" "-Q" "/github/workspace/builds/coq/coq-failing/_install_ci/lib/coq///user-contrib/Stdlib" "Stdlib" "-top" "compcert.backend.Unusedglobproof") -*- *)
(* File reduced by coq-bug-minimizer from original input, then from 1454 lines to 35 lines, then from 48 lines to 1082 lines, then from 1087 lines to 63 lines, then from 76 lines to 569 lines, then from 574 lines to 63 lines, then from 76 lines to 327 lines, then from 332 lines to 64 lines, then from 77 lines to 676 lines, then from 681 lines to 68 lines, then from 81 lines to 1377 lines, then from 1380 lines to 168 lines, then from 181 lines to 1338 lines, then from 1343 lines to 281 lines, then from 294 lines to 2110 lines, then from 2115 lines to 285 lines, then from 298 lines to 5637 lines, then from 5640 lines to 314 lines, then from 327 lines to 721 lines, then from 726 lines to 314 lines, then from 327 lines to 1394 lines, then from 1399 lines to 319 lines, then from 332 lines to 4481 lines, then from 4486 lines to 333 lines, then from 346 lines to 1946 lines, then from 1951 lines to 340 lines, then from 353 lines to 596 lines, then from 601 lines to 340 lines, then from 353 lines to 1406 lines, then from 1408 lines to 340 lines, then from 353 lines to 1041 lines, then from 1046 lines to 345 lines, then from 358 lines to 2323 lines, then from 2324 lines to 348 lines, then from 361 lines to 759 lines, then from 759 lines to 384 lines, then from 397 lines to 778 lines, then from 783 lines to 385 lines, then from 398 lines to 2673 lines, then from 2676 lines to 448 lines, then from 461 lines to 958 lines, then from 958 lines to 509 lines, then from 522 lines to 917 lines, then from 920 lines to 603 lines, then from 616 lines to 922 lines, then from 923 lines to 698 lines, then from 711 lines to 1788 lines, then from 1791 lines to 711 lines, then from 724 lines to 739 lines, then from 744 lines to 710 lines, then from 723 lines to 738 lines, then from 743 lines to 709 lines, then from 722 lines to 1122 lines, then from 1127 lines to 762 lines, then from 775 lines to 790 lines, then from 795 lines to 761 lines, then from 766 lines to 763 lines *)
(* coqc version 9.1+alpha compiled with OCaml 4.14.2
   coqtop version runner-t7b1znuaq-project-4504-concurrent-2:/builds/coq/coq/_build/default,(HEAD detached at cdd06d0a2f356e) (cdd06d0a2f356e0c02e2d20356562b7deae4cf15)
   Expected coqc runtime on this file: 0.291 sec *)

Require Corelib.Classes.RelationClasses.
Require Corelib.Floats.SpecFloat.

Export Corelib.BinNums.PosDef.
Module Export BinPosDef.

Local Open Scope positive_scope.

Module Export Pos.

Include BinNums.PosDef.Pos.

Definition t := positive.

Infix "?=" := compare (at level 70, no associativity) : positive_scope.

Local Notation ten := 1~0~1~0.

Fixpoint of_uint_acc (d:Decimal.uint)(acc:positive) :=
  match d with
  | Decimal.Nil => acc
  | Decimal.D0 l => of_uint_acc l (mul ten acc)
  | Decimal.D1 l => of_uint_acc l (add 1 (mul ten acc))
  | Decimal.D2 l => of_uint_acc l (add 1~0 (mul ten acc))
  | Decimal.D3 l => of_uint_acc l (add 1~1 (mul ten acc))
  | Decimal.D4 l => of_uint_acc l (add 1~0~0 (mul ten acc))
  | Decimal.D5 l => of_uint_acc l (add 1~0~1 (mul ten acc))
  | Decimal.D6 l => of_uint_acc l (add 1~1~0 (mul ten acc))
  | Decimal.D7 l => of_uint_acc l (add 1~1~1 (mul ten acc))
  | Decimal.D8 l => of_uint_acc l (add 1~0~0~0 (mul ten acc))
  | Decimal.D9 l => of_uint_acc l (add 1~0~0~1 (mul ten acc))
  end.
Fixpoint of_uint (d:Decimal.uint) : N.
exact (match d with
  | Decimal.Nil => N0
  | Decimal.D0 l => of_uint l
  | Decimal.D1 l => Npos (of_uint_acc l 1)
  | Decimal.D2 l => Npos (of_uint_acc l 1~0)
  | Decimal.D3 l => Npos (of_uint_acc l 1~1)
  | Decimal.D4 l => Npos (of_uint_acc l 1~0~0)
  | Decimal.D5 l => Npos (of_uint_acc l 1~0~1)
  | Decimal.D6 l => Npos (of_uint_acc l 1~1~0)
  | Decimal.D7 l => Npos (of_uint_acc l 1~1~1)
  | Decimal.D8 l => Npos (of_uint_acc l 1~0~0~0)
  | Decimal.D9 l => Npos (of_uint_acc l 1~0~0~1)
  end).
Defined.
Fixpoint of_hex_uint (d:Hexadecimal.uint) : N.
Admitted.

Fixpoint to_little_uint p :=
  match p with
  | 1 => Decimal.D1 Decimal.Nil
  | p~1 => Decimal.Little.succ_double (to_little_uint p)
  | p~0 => Decimal.Little.double (to_little_uint p)
  end.

Definition to_uint p := Decimal.rev (to_little_uint p).

End Pos.
Export Corelib.Program.Basics.
Export Corelib.Classes.RelationClasses.

Module Export Stdlib_DOT_Bool_DOT_Bool_WRAPPED.
Module Export Bool.
Definition eqb (b1 b2:bool) : bool.
Admitted.

Open Scope bool_scope.

End Bool.
Module Export Stdlib.
Module Export Bool.
Module Export Bool.
Include Stdlib_DOT_Bool_DOT_Bool_WRAPPED.Bool.
End Bool.

Module Type Typ.
  Parameter Inline(10) t : Type.
End Typ.

Module Type HasEq (Import T:Typ).
  Parameter Inline(30) eq : t -> t -> Prop.
End HasEq.

Module Type Eq := Typ <+ HasEq.

Module Type EqNotation (Import E:Eq).
  Infix "==" := eq (at level 70, no associativity).
End EqNotation.

Module Type Eq' := Eq <+ EqNotation.

Module Type IsEq (Import E:Eq).
#[global]
  Declare Instance eq_equiv : Equivalence eq.
End IsEq.

Module Type IsEqOrig (Import E:Eq').
End IsEqOrig.

Module Type HasEqDec (Import E:Eq').
  Parameter eq_dec : forall x y : t, { x==y } + { ~ x==y }.
End HasEqDec.

Module Type HasEqb (Import T:Typ).
End HasEqb.

Module Type EqbSpec (T:Typ)(X:HasEq T)(Y:HasEqb T).
End EqbSpec.

Module Type EqbNotation (T:Typ)(E:HasEqb T).
End EqbNotation.

Module Type HasEqBool (E:Eq) := HasEqb E <+ EqbSpec E E.

Module Type EqualityType := Eq <+ IsEq.

Module Type EqualityTypeOrig := Eq <+ IsEqOrig.

Module Type EqualityTypeBoth <: EqualityType <: EqualityTypeOrig
 := Eq <+ IsEq <+ IsEqOrig.

Module Type DecidableType <: EqualityType
 := Eq <+ IsEq <+ HasEqDec.

Module Type DecidableTypeOrig <: EqualityTypeOrig
 := Eq <+ IsEqOrig <+ HasEqDec.

Module Type DecidableTypeBoth <: DecidableType <: DecidableTypeOrig
 := EqualityTypeBoth <+ HasEqDec.

Module Type BooleanEqualityType <: EqualityType
 := Eq <+ IsEq <+ HasEqBool.

Module Type BooleanDecidableType <: DecidableType <: BooleanEqualityType
 := Eq <+ IsEq <+ HasEqDec <+ HasEqBool.

Module Type DecidableTypeFull <: DecidableTypeBoth <: BooleanDecidableType
 := Eq <+ IsEq <+ IsEqOrig <+ HasEqDec <+ HasEqBool.
Module Type BooleanEqualityType' :=
 BooleanEqualityType <+ EqNotation <+ EqbNotation.

Module BackportEq (E:Eq)(F:IsEq E) <: IsEqOrig E.
End BackportEq.

Module UpdateEq (E:Eq)(F:IsEqOrig E) <: IsEq E.
#[global]
 Instance eq_equiv : Equivalence E.eq.
Admitted.
End UpdateEq.

Module HasEqDec2Bool (E:Eq)(F:HasEqDec E) <: HasEqBool E.
End HasEqDec2Bool.

Module HasEqBool2Dec (E:Eq)(F:HasEqBool E) <: HasEqDec E.
 Lemma eq_dec : forall x y, {E.eq x y}+{~E.eq x y}.
Admitted.
End HasEqBool2Dec.

Module BoolEqualityFacts (Import E : BooleanEqualityType').

End BoolEqualityFacts.

Module Type HasUsualEq (Import T:Typ) <: HasEq T.
 Definition eq := @Logic.eq t.
End HasUsualEq.

Module Type UsualEq <: Eq := Typ <+ HasUsualEq.

Module Type UsualIsEq (E:UsualEq) <: IsEq E.
Definition eq_equiv : Equivalence E.eq.
Admitted.
End UsualIsEq.

Module Type UsualIsEqOrig (E:UsualEq) <: IsEqOrig E.
End UsualIsEqOrig.

Module Type UsualEqualityType <: EqualityType
 := UsualEq <+ UsualIsEq.

Module Type UsualDecidableType <: DecidableType
 := UsualEq <+ UsualIsEq <+ HasEqDec.

Module Type UsualDecidableTypeFull <: DecidableTypeFull
 := UsualEq <+ UsualIsEq <+ UsualIsEqOrig <+ HasEqDec <+ HasEqBool.

Module Type HasLt (Import T:Typ).
  Parameter Inline(40) lt : t -> t -> Prop.
End HasLt.

Module Type HasLe (Import T:Typ).
  Parameter Inline(40) le : t -> t -> Prop.
End HasLe.

Module Type EqLt := Typ <+ HasEq <+ HasLt.
Module Type EqLe := Typ <+ HasEq <+ HasLe.
Module Type EqLtLe := Typ <+ HasEq <+ HasLt <+ HasLe.

Module Type LtNotation (E:EqLt).
  Infix "<" := E.lt.
End LtNotation.

Module Type LeNotation (E:EqLe).
End LeNotation.

Module Type LtLeNotation (E:EqLtLe).
End LtLeNotation.

Module Type EqLtNotation (E:EqLt) := EqNotation E <+ LtNotation E.
Module Type EqLtLeNotation (E:EqLtLe) := EqNotation E <+ LtLeNotation E.

Module Type EqLt' := EqLt <+ EqLtNotation.
Module Type EqLtLe' := EqLtLe <+ EqLtLeNotation.

Module Type IsStrOrder (Import E:EqLt).
End IsStrOrder.

Module Type LeIsLtEq (Import E:EqLtLe').
End LeIsLtEq.

Module Type StrOrder := EqualityType <+ HasLt <+ IsStrOrder.

Module Type HasCmp (Import T:Typ).
  Parameter Inline compare : t -> t -> comparison.
End HasCmp.

Module Type CmpNotation (T:Typ)(C:HasCmp T).
End CmpNotation.

Module Type CmpSpec (Import E:EqLt')(Import C:HasCmp E).
End CmpSpec.

Module Type HasCompare (E:EqLt) := HasCmp E <+ CmpSpec E.

Module Type DecStrOrder := StrOrder <+ HasCompare.
Module Type DecStrOrder' := DecStrOrder <+ EqLtNotation <+ CmpNotation.

Module Type OrderedType <: DecidableType := DecStrOrder <+ HasEqDec.
Module Type OrderedType' := OrderedType <+ EqLtNotation <+ CmpNotation.

Module Type OrderedTypeFull := OrderedType <+ HasLe <+ LeIsLtEq.
Module Type OrderedTypeFull' :=
 OrderedTypeFull <+ EqLtLeNotation <+ CmpNotation.

Module Type UsualStrOrder := UsualEqualityType <+ HasLt <+ IsStrOrder.
Module Type UsualDecStrOrder := UsualStrOrder <+ HasCompare.
Module Type UsualOrderedType <: UsualDecidableType <: OrderedType
 := UsualDecStrOrder <+ HasEqDec.
Module Type UsualOrderedTypeFull := UsualOrderedType <+ HasLe <+ LeIsLtEq.

Module Type LtIsTotal (Import E:EqLt').
End LtIsTotal.

Module Type TotalOrder := StrOrder <+ HasLe <+ LeIsLtEq <+ LtIsTotal.

Module Compare2EqBool (Import O:DecStrOrder') <: HasEqBool O.

End Compare2EqBool.

Module OT_to_Full (O:OrderedType') <: OrderedTypeFull.
 Include O.
 Definition le x y := x<y \/ x==y.
End OT_to_Full.

Module OTF_LtIsTotal (Import O:OrderedTypeFull') <: LtIsTotal O.
End OTF_LtIsTotal.

Local Coercion is_true : bool >-> Sortclass.

Module Type HasLeb (Import T:Typ).
 Parameter Inline leb : t -> t -> bool.
End HasLeb.

Module Type HasLtb (Import T:Typ).
End HasLtb.

Module Type LebNotation (T:Typ)(E:HasLeb T).
 Infix "<=?" := E.leb (at level 70, no associativity).
End LebNotation.

Module Type LtbNotation (T:Typ)(E:HasLtb T).
End LtbNotation.

Module Type LebSpec (T:Typ)(X:HasLe T)(Y:HasLeb T).
End LebSpec.

Module Type LtbSpec (T:Typ)(X:HasLt T)(Y:HasLtb T).
End LtbSpec.

Module Type LeBool := Typ <+ HasLeb.
Module Type LeBool' := LeBool <+ LebNotation.

Module Type LebIsTotal (Import X:LeBool').
End LebIsTotal.

Module Type TotalLeBool := LeBool <+ LebIsTotal.
Module Type TotalLeBool' := LeBool' <+ LebIsTotal.

Module Type LebIsTransitive (Import X:LeBool').
End LebIsTransitive.

Module Type TotalTransitiveLeBool := TotalLeBool <+ LebIsTransitive.
Module Type TotalTransitiveLeBool' := TotalLeBool' <+ LebIsTransitive.

Module OTF_to_TTLB (Import O : OrderedTypeFull') <: TotalTransitiveLeBool.

 Definition leb x y :=
  match compare x y with Gt => false | _ => true end.

 Definition t := t.

End OTF_to_TTLB.

Module TTLB_to_OTF (Import O : TotalTransitiveLeBool') <: OrderedTypeFull.

 Definition t := t.

 Definition le x y : Prop := x <=? y.
 Definition eq x y : Prop := le x y /\ le y x.
 Definition lt x y : Prop := le x y /\ ~le y x.

 Definition compare x y :=
  if x <=? y then (if y <=? x then Eq else Lt) else Gt.

 Include HasEqBool2Dec.

#[global]
 Instance eq_equiv : Equivalence eq.
Admitted.

End TTLB_to_OTF.

Module Type CompareFacts (Import O:DecStrOrder').

End CompareFacts.

Module OrderedTypeFullFacts (Import O:OrderedTypeFull').

End OrderedTypeFullFacts.

Module OrderedTypeFacts (Import O: OrderedType').

End OrderedTypeFacts.

Module OrderedTypeTest (Import O:OrderedType').
End OrderedTypeTest.

Module OrderedTypeRev (O:OrderedTypeFull) <: OrderedTypeFull.

Definition t := O.t.
Definition eq := O.eq.
#[global]
Program Instance eq_equiv : Equivalence eq.
Definition eq_dec := O.eq_dec.

Definition lt := flip O.lt.
Definition le := flip O.le.

Definition compare := flip O.compare.

End OrderedTypeRev.

Module Pos
 <: UsualOrderedTypeFull
 <: UsualDecidableTypeFull
 <: TotalOrder.

Include BinPosDef.Pos.

Definition eq := @Logic.eq positive.
Definition eq_equiv := @eq_equivalence positive.

Definition lt x y := (x ?= y) = Lt.
Definition le x y := (x ?= y) <> Gt.

Lemma eq_dec : forall x y:positive, {x = y} + {x <> y}.
Admitted.

End Pos.

Inductive ascii : Set := Ascii (_ _ _ _ _ _ _ _ : bool).

Local Notation "0" := Z0.

Include BinNums.IntDef.Z.

Notation pos := Zpos.
Notation neg := Zneg.

Definition of_uint (d:Decimal.uint) := of_N (Pos.of_uint d).

Definition of_hex_uint (d:Hexadecimal.uint) := of_N (Pos.of_hex_uint d).

Definition of_int (d:Decimal.int) :=
  match d with
  | Decimal.Pos d => of_uint d
  | Decimal.Neg d => opp (of_uint d)
  end.

Definition of_hex_int (d:Hexadecimal.int) :=
  match d with
  | Hexadecimal.Pos d => of_hex_uint d
  | Hexadecimal.Neg d => opp (of_hex_uint d)
  end.

Definition of_num_int (d:Number.int) :=
  match d with
  | Number.IntDecimal d => of_int d
  | Number.IntHexadecimal d => of_hex_int d
  end.

Definition to_int n :=
  match n with
  | 0 => Decimal.Pos Decimal.zero
  | pos p => Decimal.Pos (Pos.to_uint p)
  | neg p => Decimal.Neg (Pos.to_uint p)
  end.

Definition to_num_int n := Number.IntDecimal (to_int n).
Number Notation Z of_num_int to_num_int : Z_scope.

Local Open Scope Z_scope.
Notation "x < y < z" := (x < y /\ y < z) : Z_scope.

Inductive string : Set :=
  | EmptyString : string
  | String : ascii -> string -> string.
Export Stdlib.Bool.Bool.

Ltac inv H := inversion H; clear H; subst.
Definition zeq: forall (x y: Z), {x = y} + {x <> y}.
Admitted.

Section Binary.

Variable prec emax : Z.

Notation bounded := (SpecFloat.bounded prec emax).

Inductive binary_float :=
  | B754_zero (s : bool)
  | B754_infinity (s : bool)
  | B754_nan : binary_float
  | B754_finite (s : bool) (m : positive) (e : Z) :
    bounded m e = true -> binary_float.

End Binary.

Definition binary32 := binary_float 24 128.

Definition binary64 := binary_float 53 1024.

Module Type WORDSIZE.
End WORDSIZE.

Module Make(WS: WORDSIZE).
Definition modulus : Z.
Admitted.

Record int: Type := mkint { intval: Z; intrange: -1 < intval < modulus }.

End Make.

Module Export Wordsize_64.
End Wordsize_64.

Module Export Int64.

Include Make(Wordsize_64).

Notation int64 := Int64.int.

Module Export Wordsize_Ptrofs.
End Wordsize_Ptrofs.

Module Export Ptrofs.

Include Make(Wordsize_Ptrofs).

Notation ptrofs := Ptrofs.int.

Definition float := binary64.

Definition float32 := binary32.
Module Export AST.

Set Implicit Arguments.

Definition ident := positive.

Inductive typ : Type :=
  | Tint
  | Tfloat
  | Tlong
  | Tsingle
  | Tany32
  | Tany64.

Inductive xtype : Type :=
  | Xbool
  | Xint8signed
  | Xint8unsigned
  | Xint16signed
  | Xint16unsigned
  | Xint
  | Xfloat
  | Xlong
  | Xsingle
  | Xptr
  | Xany32
  | Xany64
  | Xvoid.

Record calling_convention : Type := mkcallconv {
  cc_vararg: option Z;
  cc_unproto: bool;
  cc_structret: bool
}.

Record signature : Type := mksignature {
  sig_args: list xtype;
  sig_res: xtype;
  sig_cc: calling_convention
}.

Inductive memory_chunk : Type :=
  | Mbool
  | Mint8signed
  | Mint8unsigned
  | Mint16signed
  | Mint16unsigned
  | Mint32
  | Mint64
  | Mfloat32
  | Mfloat64
  | Many32
  | Many64.

Inductive init_data: Type :=
  | Init_int8: int -> init_data
  | Init_int16: int -> init_data
  | Init_int32: int -> init_data
  | Init_int64: int64 -> init_data
  | Init_float32: float32 -> init_data
  | Init_float64: float -> init_data
  | Init_space: Z -> init_data
  | Init_addrof: ident -> ptrofs -> init_data.
Fixpoint init_data_list_size (il: list init_data) {struct il} : Z.
Admitted.

Record globvar (V: Type) : Type := mkglobvar {
  gvar_info: V;
  gvar_init: list init_data;
  gvar_readonly: bool;
  gvar_volatile: bool
}.

Inductive globdef (F V: Type) : Type :=
  | Gfun (f: F)
  | Gvar (v: globvar V).

Arguments Gfun [F V].
Arguments Gvar [F V].

Inductive external_function : Type :=
  | EF_external (name: string) (sg: signature)

  | EF_builtin (name: string) (sg: signature)

  | EF_runtime (name: string) (sg: signature)

  | EF_vload (chunk: memory_chunk)

  | EF_vstore (chunk: memory_chunk)

  | EF_malloc

  | EF_free

  | EF_memcpy (sz: Z) (al: Z)

  | EF_annot (kind: positive) (text: string) (targs: list typ)

  | EF_annot_val (kind: positive) (text: string) (targ: typ)

  | EF_inline_asm (text: string) (sg: signature) (clobbers: list string)

  | EF_debug (kind: positive) (text: ident) (targs: list typ).

Definition external_function_eq: forall (ef1 ef2: external_function), {ef1=ef2} + {ef1<>ef2}.
Admitted.

Inductive fundef (F: Type): Type :=
  | Internal: F -> fundef F
  | External: external_function -> fundef F.

Arguments External [F].

Class Linker (A: Type) := {
  link: A -> A -> option A;
  linkorder: A -> A -> Prop;
  linkorder_refl: forall x, linkorder x x;
  linkorder_trans: forall x y z, linkorder x y -> linkorder y z -> linkorder x z;
  link_linkorder: forall x y z, link x y = Some z -> linkorder x z /\ linkorder y z
}.

Definition link_fundef {F: Type} (fd1 fd2: fundef F) :=
  match fd1, fd2 with
  | Internal _, Internal _ => None
  | External ef1, External ef2 =>
      if external_function_eq ef1 ef2 then Some (External ef1) else None
  | Internal f, External ef =>
      match ef with EF_external id sg => Some (Internal f) | _ => None end
  | External ef, Internal f =>
      match ef with EF_external id sg => Some (Internal f) | _ => None end
  end.

Inductive linkorder_fundef {F: Type}: fundef F -> fundef F -> Prop :=
  | linkorder_fundef_refl: forall fd, linkorder_fundef fd fd
  | linkorder_fundef_ext_int: forall f id sg, linkorder_fundef (External (EF_external id sg)) (Internal f).

Global Program Instance Linker_fundef (F: Type): Linker (fundef F) := {
  link := link_fundef;
  linkorder := linkorder_fundef
}.

Inductive init_class : list init_data -> Type :=
  | Init_extern: init_class nil
  | Init_common: forall sz, init_class (Init_space sz :: nil)
  | Init_definitive: forall il, init_class il.
Definition classify_init (i: list init_data) : init_class i.
Admitted.

Definition link_varinit (i1 i2: list init_data) :=
  match classify_init i1, classify_init i2 with
  | Init_extern, _ => Some i2
  | _, Init_extern => Some i1
  | Init_common sz1, _ => if zeq sz1 (init_data_list_size i2) then Some i2 else None
  | _, Init_common sz2 => if zeq sz2 (init_data_list_size i1) then Some i1 else None
  | _, _ => None
  end.

Inductive linkorder_varinit: list init_data -> list init_data -> Prop :=
  |
8000
 linkorder_varinit_refl: forall il, linkorder_varinit il il
  | linkorder_varinit_extern: forall il, linkorder_varinit nil il
  | linkorder_varinit_common: forall sz il,
      il <> nil -> init_data_list_size il = sz ->
      linkorder_varinit (Init_space sz :: nil) il.

Global Program Instance Linker_varinit : Linker (list init_data) := {
  link := link_varinit;
  linkorder := linkorder_varinit
}.
Admit Obligations.

Definition link_vardef {V: Type} {LV: Linker V} (v1 v2: globvar V) :=
  match link v1.(gvar_info) v2.(gvar_info) with
  | None => None
  | Some info =>
      match link v1.(gvar_init) v2.(gvar_init) with
      | None => None
      | Some init =>
          if eqb v1.(gvar_readonly) v2.(gvar_readonly)
          && eqb v1.(gvar_volatile) v2.(gvar_volatile)
          then Some {| gvar_info := info; gvar_init := init;
                       gvar_readonly := v1.(gvar_readonly);
                       gvar_volatile := v1.(gvar_volatile) |}
          else None
      end
  end.

Inductive linkorder_vardef {V: Type} {LV: Linker V}: globvar V -> globvar V -> Prop :=
  | linkorder_vardef_intro: forall info1 info2 i1 i2 ro vo,
      linkorder info1 info2 ->
      linkorder i1 i2 ->
      linkorder_vardef (mkglobvar info1 i1 ro vo) (mkglobvar info2 i2 ro vo).

Global Program Instance Linker_vardef (V: Type) {LV: Linker V}: Linker (globvar V) := {
  link := link_vardef;
  linkorder := linkorder_vardef
}.
Admit Obligations.

Global Program Instance Linker_unit: Linker unit := {
  link := fun x y => Some tt;
  linkorder := fun x y => True
}.

Definition link_def {F V: Type} {LF: Linker F} {LV: Linker V} (gd1 gd2: globdef F V) :=
  match gd1, gd2 with
  | Gfun f1, Gfun f2 =>
      match link f1 f2 with Some f => Some (Gfun f) | None => None end
  | Gvar v1, Gvar v2 =>
      match link v1 v2 with Some v => Some (Gvar v) | None => None end
  | _, _ => None
  end.

Inductive linkorder_def {F V: Type} {LF: Linker F} {LV: Linker V}: globdef F V -> globdef F V -> Prop :=
  | linkorder_def_fun: forall fd1 fd2,
      linkorder fd1 fd2 ->
      linkorder_def (Gfun fd1) (Gfun fd2)
  | linkorder_def_var: forall v1 v2,
      linkorder v1 v2 ->
      linkorder_def (Gvar v1) (Gvar v2).

Global Program Instance Linker_def (F V: Type) {LF: Linker F} {LV: Linker V}: Linker (globdef F V) := {
  link := link_def;
  linkorder := linkorder_def
}.
Admit Obligations.
Module Export OrderedType.

Inductive Compare (X : Type) (lt eq : X -> X -> Prop) (x y : X) : Type :=
  | LT : lt x y -> Compare lt eq x y
  | EQ : eq x y -> Compare lt eq x y
  | GT : lt y x -> Compare lt eq x y.
Definition reg: Type.
Admitted.

Definition node := positive.
Definition code: Type.
Admitted.

Record function: Type := mkfunction {
  fn_sig: signature;
  fn_params: list reg;
  fn_stacksize: Z;
  fn_code: code;
  fn_entrypoint: node
}.

Definition fundef := AST.fundef function.

Remark link_def_either:
  forall (gd1 gd2 gd: globdef fundef unit),
  link_def gd1 gd2 = Some gd -> gd = gd1 \/ gd = gd2.
Proof with (try discriminate).
  intros until gd.
Local Transparent Linker_def Linker_fundef Linker_varinit Linker_vardef Linker_unit.
  destruct gd1 as [f1|v1], gd2 as [f2|v2]...

  destruct f1 as [f1|ef1], f2 as [f2|ef2]; simpl...
  destruct ef2; intuition congruence.
  destruct ef1; intuition congruence.
  destruct (external_function_eq ef1 ef2); intuition congruence.

  simpl.
unfold link_vardef.
destruct v1 as [info1 init1 ro1 vo1], v2 as [info2 init2 ro2 vo2]; simpl.
  destruct (link_varinit init1 init2) as [init|] eqn:LI...
  destruct (eqb ro1 ro2) eqn:RO...
  destruct (eqb vo1 vo2) eqn:VO...
  simpl.
  destruct info1, info2.
  assert (EITHER: init = init1 \/ init = init2).
  {
 revert LI.
unfold link_varinit.
    destruct (classify_init init1), (classify_init init2); intro EQ; inv EQ; auto.
🛠️ Intermediate Coq File (useful for debugging if minimization did not go as far as you wanted)
🛠️ 📜 Intermediate Coq File log (useful for debugging if minimization did not go as far as you wanted)
📜 Build Log (contains the Coq error message) (truncated to last 8.0KiB; full 6.1MiB file on GitHub Actions Artifacts under build.log)
ble COQCORELIB, use ROCQRUNTIMELIB instead.
Warning: Deprecated environment variable COQLIB, use ROCQLIB instead.
[deprecated-coq-env-var,deprecated-since-9.0,deprecated,default]
Warning: Deprecated environment variable COQCORELIB,
use ROCQRUNTIMELIB instead.
[deprecated-coq-env-var,deprecated-since-9.0,deprecated,default]
COQC backend/Unusedglobproof.v
MINIMIZER_DEBUG_EXTRA: coqc: /github/workspace/builds/coq/coq-failing/_install_ci/bin/coqc
MINIMIZER_DEBUG_EXTRA: original invocation: -q -R lib compcert.lib -R common compcert.common -R x86_32 compcert.x86_32 -R x86 compcert.x86 -R backend compcert.backend -R cfrontend compcert.cfrontend -R driver compcert.driver -R cparser compcert.cparser -R export compcert.export -native-compiler no -w -undeclared-scope -w -omega-is-deprecated backend/Unusedglobproof.v 
MINIMIZER_DEBUG_EXTRA: new invocation: /github/workspace/builds/coq/coq-failing/_install_ci/bin/coqc.orig -q -R /github/workspace/builds/coq/coq-failing/_build_ci/compcert/lib compcert.lib -R /github/workspace/builds/coq/coq-failing/_build_ci/compcert/common compcert.common -R /github/workspace/builds/coq/coq-failing/_build_ci/compcert/x86_32 compcert.x86_32 -R /github/workspace/builds/coq/coq-failing/_build_ci/compcert/x86 compcert.x86 -R /github/workspace/builds/coq/coq-failing/_build_ci/compcert/backend compcert.backend -R /github/workspace/builds/coq/coq-failing/_build_ci/compcert/cfrontend compcert.cfrontend -R /github/workspace/builds/coq/coq-failing/_build_ci/compcert/driver compcert.driver -R /github/workspace/builds/coq/coq-failing/_build_ci/compcert/cparser compcert.cparser -R /github/workspace/builds/coq/coq-failing/_build_ci/compcert/export compcert.export -native-compiler no -w -undeclared-scope -w -omega-is-deprecated backend/Unusedglobproof.v 
MINIMIZER_DEBUG_EXTRA: coqpath: 
MINIMIZER_DEBUG_EXTRA: ocamlpath: /github/workspace/builds/coq/coq-failing/_install_ci/lib:
MINIMIZER_DEBUG_EXTRA: pwd: PWD=/github/workspace/builds/coq/coq-failing/_build_ci/compcert
MINIMIZER_DEBUG_EXTRA: exec: /github/workspace/builds/coq/coq-failing/_install_ci/bin/coqc.orig -q -R /github/workspace/builds/coq/coq-failing/_build_ci/compcert/lib compcert.lib -R /github/workspace/builds/coq/coq-failing/_build_ci/compcert/common compcert.common -R /github/workspace/builds/coq/coq-failing/_build_ci/compcert/x86_32 compcert.x86_32 -R /github/workspace/builds/coq/coq-failing/_build_ci/compcert/x86 compcert.x86 -R /github/workspace/builds/coq/coq-failing/_build_ci/compcert/backend compcert.backend -R /github/workspace/builds/coq/coq-failing/_build_ci/compcert/cfrontend compcert.cfrontend -R /github/workspace/builds/coq/coq-failing/_build_ci/compcert/driver compcert.driver -R /github/workspace/builds/coq/coq-failing/_build_ci/compcert/cparser compcert.cparser -R /github/workspace/builds/coq/coq-failing/_build_ci/compcert/export compcert.export -native-compiler no -w -undeclared-scope -w -omega-is-deprecated backend/Unusedglobproof.v 
MINIMIZER_DEBUG_EXTRA: coqlib: Deprecated environment variable COQLIB, use ROCQLIB instead.
/github/workspace/builds/coq/coq-failing/_install_ci/lib/coq//
MINIMIZER_DEBUG: info: /tmp/tmp-coqbot-minimizer.8rIlnoeYhC
MINIMIZER_DEBUG: files:  backend/Unusedglobproof.v /github/workspace/builds/coq/coq-failing/_build_ci/compcert/backend/Unusedglobproof.v
Deprecated environment variable COQLIB, use ROCQLIB instead.
Deprecated environment variable COQCORELIB, use ROCQRUNTIMELIB instead.
Warning: Deprecated environment variable COQLIB, use ROCQLIB instead.
[deprecated-coq-env-var,deprecated-since-9.0,deprecated,default]
Warning: Deprecated environment variable COQCORELIB,
use ROCQRUNTIMELIB instead.
[deprecated-coq-env-var,deprecated-since-9.0,deprecated,default]
File "./backend/Unusedglobproof.v", line 15, characters 0-30:
Warning: "From Coq" has been replaced by "From Stdlib".
[deprecated-from-Coq,deprecated-since-9.0,deprecated,default]
COQC backend/LTL.v
MINIMIZER_DEBUG_EXTRA: coqc: /github/workspace/builds/coq/coq-failing/_install_ci/bin/coqc
MINIMIZER_DEBUG_EXTRA: original invocation: -q -R lib compcert.lib -R common compcert.common -R x86_32 compcert.x86_32 -R x86 compcert.x86 -R backend compcert.backend -R cfrontend compcert.cfrontend -R driver compcert.driver -R cparser compcert.cparser -R export compcert.export -native-compiler no -w -undeclared-scope -w -omega-is-deprecated backend/LTL.v 
MINIMIZER_DEBUG_EXTRA: new invocation: /github/workspace/builds/coq/coq-failing/_install_ci/bin/coqc.orig -q -R /github/workspace/builds/coq/coq-failing/_build_ci/compcert/lib compcert.lib -R /github/workspace/builds/coq/coq-failing/_build_ci/compcert/common compcert.common -R /github/workspace/builds/coq/coq-failing/_build_ci/compcert/x86_32 compcert.x86_32 -R /github/workspace/builds/coq/coq-failing/_build_ci/compcert/x86 compcert.x86 -R /github/workspace/builds/coq/coq-failing/_build_ci/compcert/backend compcert.backend -R /github/workspace/builds/coq/coq-failing/_build_ci/compcert/cfrontend compcert.cfrontend -R /github/workspace/builds/coq/coq-failing/_build_ci/compcert/driver compcert.driver -R /github/workspace/builds/coq/coq-failing/_build_ci/compcert/cparser compcert.cparser -R /github/workspace/builds/coq/coq-failing/_build_ci/compcert/export compcert.export -native-compiler no -w -undeclared-scope -w -omega-is-deprecated backend/LTL.v 
MINIMIZER_DEBUG_EXTRA: coqpath: 
MINIMIZER_DEBUG_EXTRA: ocamlpath: /github/workspace/builds/coq/coq-failing/_install_ci/lib:
MINIMIZER_DEBUG_EXTRA: pwd: PWD=/github/workspace/builds/coq/coq-failing/_build_ci/compcert
MINIMIZER_DEBUG_EXTRA: exec: /github/workspace/builds/coq/coq-failing/_install_ci/bin/coqc.orig -q -R /github/workspace/builds/coq/coq-failing/_build_ci/compcert/lib compcert.lib -R /github/workspace/builds/coq/coq-failing/_build_ci/compcert/common compcert.common -R /github/workspace/builds/coq/coq-failing/_build_ci/compcert/x86_32 compcert.x86_32 -R /github/workspace/builds/coq/coq-failing/_build_ci/compcert/x86 compcert.x86 -R /github/workspace/builds/coq/coq-failing/_build_ci/compcert/backend compcert.backend -R /github/workspace/builds/coq/coq-failing/_build_ci/compcert/cfrontend compcert.cfrontend -R /github/workspace/builds/coq/coq-failing/_build_ci/compcert/driver compcert.driver -R /github/workspace/builds/coq/coq-failing/_build_ci/compcert/cparser compcert.cparser -R /github/workspace/builds/coq/coq-failing/_build_ci/compcert/export compcert.export -native-compiler no -w -undeclared-scope -w -omega-is-deprecated backend/LTL.v 
MINIMIZER_DEBUG_EXTRA: coqlib: Deprecated environment variable COQLIB, use ROCQLIB instead.
/github/workspace/builds/coq/coq-failing/_install_ci/lib/coq//
MINIMIZER_DEBUG: info: /tmp/tmp-coqbot-minimizer.cODYiieODH
MINIMIZER_DEBUG: files:  backend/LTL.v /github/workspace/builds/coq/coq-failing/_build_ci/compcert/backend/LTL.v
Deprecated environment variable COQLIB, use ROCQLIB instead.
Deprecated environment variable COQCORELIB, use ROCQRUNTIMELIB instead.
Warning: Deprecated environment variable COQLIB, use ROCQLIB instead.
[deprecated-coq-env-var,deprecated-since-9.0,deprecated,default]
Warning: Deprecated environment variable COQCORELIB,
use ROCQRUNTIMELIB instead.
[deprecated-coq-env-var,deprecated-since-9.0,deprecated,default]
File "./backend/Unusedglobproof.v", line 1298, characters 69-75:
Error: Ltac variable H is bound to OrderedType.EQ of type constr which cannot
be coerced to a declared or quantified hypothesis.

make[1]: *** [Makefile:308: backend/Unusedglobproof.vo] Error 1
make[1]: *** Waiting for unfinished jobs....
File "./backend/LTL.v", line 321, characters 4-9:
Warning: Unused variable instr might be a misspelled constructor. Use _ or
_instr to silence this warning. [unused-pattern-matching-variable,default]
make[1]: Leaving directory '/github/workspace/builds/coq/coq-failing/_build_ci/compcert'
make: *** [Makefile:234: all] Error 2
+ code=2
+ printf '\n%s exit code: %s\n' compcert 2
+ '[' compcert '!=' stdlib_test ']'
+ echo 'Aggregating timing log...'
Aggregating timing log...
+ echo

+ tools/make-one-time-file.py --real compcert.log
No timing data
+ '[' '' ']'
+ exit 2
/github/workspace/builds/coq /github/workspace
::endgroup::
📜 🔎 Minimization Log (truncated to last 8.0KiB; full 3.9MiB file on GitHub Actions Artifacts under bug.log)
d) goals).
If this is really what you want to do, use Admitted in place of Qed.


�[93mIntermediate code not saved.�[0m
Failed to do everything at once; trying one at a time.
Admi
8000
tting definitions unsuccessful.
No successful changes.

I will now attempt to admit lemmas with Admitted with Proof using

Non-fatal error: Failed to admit lemmas and preserve the error.  
The new error was:
Deprecated environment variable COQCORELIB, use ROCQRUNTIMELIB instead.
Warning: Deprecated environment variable COQCORELIB,
use ROCQRUNTIMELIB instead.
[deprecated-coq-env-var,deprecated-since-9.0,deprecated,default]
Error: The module OrderedType, module AST, module Ptrofs, module Int64,
module Bool, module Stdlib, module Stdlib_DOT_Bool_DOT_Bool_WRAPPED and
module BinPosDef need to be closed.


�[93mIntermediate code not saved.�[0m
Failed to do everything at once; trying one at a time.
Admitting lemmas unsuccessful.
No successful changes.

I will now attempt to admit definitions with Admitted with Proof using

Non-fatal error: Failed to admit definitions and preserve the error.  
The new error was:
Deprecated environment variable COQCORELIB, use ROCQRUNTIMELIB instead.
Warning: Deprecated environment variable COQCORELIB,
use ROCQRUNTIMELIB instead.
[deprecated-coq-env-var,deprecated-since-9.0,deprecated,default]
File "/tmp/tmpq548p4eg/compcert/backend/Unusedglobproof.v", line 446, characters 39-42:
Error: Unexpected term
match
  BinPosDef.Pos.of_uint (Decimal.D1 (Decimal.D2 (Decimal.D8 Decimal.Nil)))
with
| N0 => 0
| Npos p => pos p
end while parsing a number notation.


�[93mIntermediate code not saved.�[0m
Failed to do everything at once; trying one at a time.
Admitting definitions unsuccessful.
No successful changes.

I will now attempt to admit lemmas with admit. Defined with Proof using

Non-fatal error: Failed to admit lemmas and preserve the error.  
The new error was:
Deprecated environment variable COQCORELIB, use ROCQRUNTIMELIB instead.
Warning: Deprecated environment variable COQCORELIB,
use ROCQRUNTIMELIB instead.
[deprecated-coq-env-var,deprecated-since-9.0,deprecated,default]
File "/tmp/tmp_eytc5q9/compcert/backend/Unusedglobproof.v", line 748, characters 0-8:
Error:  (in proof link_def_either): Attempt to save an incomplete proof
(the proof term is not complete because of given up (admitted) goals).
If this is really what you want to do, use Admitted in place of Qed.


�[93mIntermediate code not saved.�[0m
Failed to do everything at once; trying one at a time.
Admitting lemmas unsuccessful.
No successful changes.

I will now attempt to admit definitions with admit. Defined with Proof using

Non-fatal error: Failed to admit definitions and preserve the error.  
The new error was:
Deprecated environment variable COQCORELIB, use ROCQRUNTIMELIB instead.
Warning: Deprecated environment variable COQCORELIB,
use ROCQRUNTIMELIB instead.
[deprecated-coq-env-var,deprecated-since-9.0,deprecated,default]
File "/tmp/tmpgqaas5am/compcert/backend/Unusedglobproof.v", line 44, characters 0-8:
Error:  (in proof of_uint): Attempt to save an incomplete proof
(the proof term is not complete because of given up (admitted) goals).
If this is really what you want to do, use Admitted in place of Qed.


�[93mIntermediate code not saved.�[0m
Failed to do everything at once; trying one at a time.
Admitting definitions unsuccessful.
No successful changes.

I will now attempt to add Proof using lines
�[92m
Adding Proof using lines successful.�[0m
Failed to do everything at once; trying one at a time.
Adding Proof using lines unsuccessful.
No successful changes.

I will now attempt to export modules
Module exportation unsuccessful.

I will now attempt to split imports and exports
Import/Export splitting unsuccessful.

I will now attempt to split := definitions
One-line definition splitting unsuccessful.

I will now attempt to remove all lines, one at a time
Line removal unsuccessful.

I will now attempt to remove goals ending in [Abort.]
�[92m
Aborted removal successful.�[0m

I will now attempt to remove unused Ltacs
�[92m
Ltac removal successful.�[0m

I will now attempt to remove unused definitions

Non-fatal error: Failed to remove definitions and preserve the error.  
The new error was:
Deprecated environment variable COQCORELIB, use ROCQRUNTIMELIB instead.
Warning: Deprecated environment variable COQCORELIB,
use ROCQRUNTIMELIB instead.
[deprecated-coq-env-var,deprecated-since-9.0,deprecated,default]
File "/tmp/tmphgqxn1hz/compcert/backend/Unusedglobproof.v", line 156, characters 0-13:
Error:
The field eq_equiv is missing in compcert.backend.Unusedglobproof.BinPosDef.Stdlib_DOT_Bool_DOT_Bool_WRAPPED.Stdlib.Bool.UpdateEq.


�[93mIntermediate code not saved.�[0m

I will now attempt to remove unused non-instance, non-canonical structure definitions

Non-fatal error: Failed to remove non-instance definitions and preserve the error.  
The new error was:
Deprecated environment variable COQCORELIB, use ROCQRUNTIMELIB instead.
Warning: Deprecated environment variable COQCORELIB,
use ROCQRUNTIMELIB instead.
[deprecated-coq-env-var,deprecated-since-9.0,deprecated,default]
File "/tmp/tmp0ix6hiv6/compcert/backend/Unusedglobproof.v", line 313, characters 0-16:
Error:
The field t is missing in compcert.backend.Unusedglobproof.BinPosDef.Stdlib_DOT_Bool_DOT_Bool_WRAPPED.Stdlib.Bool.OTF_to_TTLB.


�[93mIntermediate code not saved.�[0m

I will now attempt to remove unused variables

Non-fatal error: Failed to remove variables and preserve the error.  
The new error was:
Deprecated environment variable COQCORELIB, use ROCQRUNTIMELIB instead.
Warning: Deprecated environment variable COQCORELIB,
use ROCQRUNTIMELIB instead.
[deprecated-coq-env-var,deprecated-since-9.0,deprecated,default]
File "/tmp/tmp5_rx7rfv/compcert/backend/Unusedglobproof.v", line 103, characters 30-41:
Error: Cannot infer the implicit parameter A of Equivalence whose type is
"Type".


�[93mIntermediate code not saved.�[0m

I will now attempt to remove unused contexts
�[92m
Context removal successful.�[0m

I will now attempt to remove modules

Non-fatal error: Failed to remove Modules and preserve the error.  
The new error was:
Deprecated environment variable COQCORELIB, use ROCQRUNTIMELIB instead.
Warning: Deprecated environment variable COQCORELIB,
use ROCQRUNTIMELIB instead.
[deprecated-coq-env-var,deprecated-since-9.0,deprecated,default]
File "/tmp/tmpciwr7uri/compcert/backend/Unusedglobproof.v", line 76, characters 8-45:
Error: Stdlib_DOT_Bool_DOT_Bool_WRAPPED.Bool is not a module or module type.


�[93mIntermediate code not saved.�[0m
Failed to do everything at once; trying one at a time.
Module removal unsuccessful.
No successful changes.

I will now attempt to remove sections

Non-fatal error: Failed to remove Sections and preserve the error.  
The new error was:
Deprecated environment variable COQCORELIB, use ROCQRUNTIMELIB instead.
Warning: Deprecated environment variable COQCORELIB,
use ROCQRUNTIMELIB instead.
[deprecated-coq-env-var,deprecated-since-9.0,deprecated,default]
File "/tmp/tmpc5b0k4fn/compcert/backend/Unusedglobproof.v", line 444, characters 0-23:
Error: Use of "Variable" or "Hypothesis" outside sections behaves as
"#[local] Parameter" or "#[local] Axiom".
[declaration-outside-section,vernacular,default]


�[93mIntermediate code not saved.�[0m
Failed to do everything at once; trying one at a time.
Section removal unsuccessful.
No successful changes.

I will now attempt to remove empty sections

Non-fatal error: Failed to remove empty sections and preserve the error.  
The new error was:
Deprecated environment variable COQCORELIB, use ROCQRUNTIMELIB instead.
Warning: Deprecated environment variable COQCORELIB,
use ROCQRUNTIMELIB instead.
[deprecated-coq-env-var,deprecated-since-9.0,deprecated,default]
File "/tmp/tmpiv00qlqn/compcert/backend/Unusedglobproof.v", line 481, characters 13-24:
Error: Wordsize_64 is not a module or module type.


�[93mChanged file not saved.�[0m

I will now attempt to remove the admit tactic header

No admit tactic header to remove

Now, I will attempt to strip repeated newlines and trailing spaces from this file...
�[92m
Succeeded in stripping newlines and spaces.�[0m

If you have any comments on your experience of the minimizer, please share them in a reply (possibly tagging @JasonGross).
If you believe there's a bug in the bug minimizer, please report it on the bug minimizer issue tracker.

Copy link
Contributor
coqbot-app bot commented May 26, 2025
Minimization interrupted by timeout, being automatically continued. Partially Minimized File /home/runner/work/run-coq-bug-minimizer/run-coq-bug-minimizer/builds/coq/coq-failing/_build_ci/metarocq/pcuic/theories/PCUICConfluence.v in 5h 15m 6s (from ci-metarocq) (interrupted by timeout, being automatically continued) (full log on GitHub Actions - verbose log)
⭐ ⏱️ Partially Minimized Coq File (timeout) (truncated to first and last 32KiB; full 35KiB file on GitHub Actions Artifacts under bug.v)
(* -*- mode: coq; coq-prog-args: ("-emacs" "-q" "-w" "-deprecated-native-compiler-option" "-native-compiler" "no" "-coqlib" "/github/workspace/builds/coq/coq-failing/_install_ci/lib/coq//" "-R" "/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/utils/theories" "MetaRocq.Utils" "-R" "/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/common/theories" "MetaRocq.Common" "-R" "/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/pcuic/theories" "MetaRocq.PCUIC" "-Q" "/github/workspace/cwd" "Top" "-Q" "/github/workspace/builds/coq/coq-failing/_install_ci/lib/coq///user-contrib/Equations" "Equations" "-Q" "/github/workspace/builds/coq/coq-failing/_install_ci/lib/coq///user-contrib/Ltac2" "Ltac2" "-Q" "/github/workspace/builds/coq/coq-failing/_install_ci/lib/coq///user-contrib/Stdlib" "Stdlib" "-top" "MetaRocq.PCUIC.PCUICConfluence") -*- *)
(* File reduced by coq-bug-minimizer from original input, then from 3959 lines to 98 lines, then from 111 lines to 3187 lines, then from 3191 lines to 96 lines, then from 107 lines to 1813 lines, then from 1818 lines to 359 lines, then from 369 lines to 1502 lines, then from 1506 lines to 524 lines, then from 535 lines to 3221 lines, then from 3222 lines to 656 lines, then from 667 lines to 2894 lines, then from 2900 lines to 656 lines, then from 667 lines to 1321 lines, then from 1327 lines to 874 lines *)
(* coqc version 9.1+alpha compiled with OCaml 4.14.2
   coqtop version runner-t7b1znuaq-project-4504-concurrent-2:/builds/coq/coq/_build/default,(HEAD detached at cdd06d0a2f356e) (cdd06d0a2f356e0c02e2d20356562b7deae4cf15)
   Modules that could not be inlined: MetaRocq.PCUIC.Syntax.PCUICOnFreeVars
   Expected coqc runtime on this file: 1.605 sec *)









Require Corelib.Init.Ltac.
Require Corelib.BinNums.IntDef.
Require Corelib.BinNums.NatDef.
Require Corelib.BinNums.PosDef.
Require Corelib.Classes.CMorphisms.
Require Corelib.Classes.CRelationClasses.
Require Corelib.Classes.Morphisms.
Require Corelib.Classes.Morphisms_Prop.
Require Corelib.Classes.RelationClasses.
Require Corelib.Floats.FloatAxioms.
Require Corelib.Floats.FloatOps.
Require Corelib.Floats.PrimFloat.
Require Corelib.Floats.SpecFloat.
Require Corelib.Init.Byte.
Require Corelib.Init.Decimal.
Require Corelib.Init.Hexadecimal.
Require Corelib.Init.Nat.
Require Corelib.Init.Sumbool.
Require Corelib.Init.Wf.
Require Corelib.Lists.ListDef.
Require Corelib.Numbers.BinNums.
Require Corelib.Numbers.Cyclic.Int63.CarryType.
Require Corelib.Numbers.Cyclic.Int63.PrimInt63.
Require Corelib.Numbers.Cyclic.Int63.Sint63Axioms.
Require Corelib.Numbers.Cyclic.Int63.Uint63Axioms.
Require Corelib.Program.Basics.
Require Corelib.Program.Tactics.
Require Corelib.Program.Utils.
Require Corelib.Program.Wf.
Require Corelib.Relations.Relation_Definitions.
Require Corelib.Setoids.Setoid.
Require Corelib.Strings.PrimString.
Require Corelib.Strings.PrimStringAxioms.
Require Corelib.extraction.Extraction.
Require Corelib.ssr.ssrbool.
Require Corelib.ssr.ssreflect.
Require Corelib.ssr.ssrfun.
Require MetaRocq.Utils.MREquality.
Require MetaRocq.Utils.MRSquash.
Require MetaRocq.Utils.MRTactics.DestructHyps.
Require MetaRocq.Utils.MRTactics.FindHyp.
Require MetaRocq.Utils.MRTactics.Head.
Require MetaRocq.Utils.MRTactics.SpecializeBy.
Require MetaRocq.Utils.MRTactics.SplitInContext.
Require MetaRocq.Utils.MRTactics.Zeta1.
Require Stdlib.Classes.DecidableClass.
Require Stdlib.Logic.Decidable.
Require Stdlib.Logic.EqdepFacts.
Require Stdlib.Logic.FunctionalExtensionality.
Require Stdlib.Logic.HLevelsBase.
Require Stdlib.Program.Syntax.
Require Stdlib.Sets.Relations_1.
Require Stdlib.Unicode.Utf8_core.
Require Stdlib.Wellfounded.Inverse_Image.
Require Stdlib.micromega.ZifyClasses.
Require Stdlib.setoid_ring.Algebra_syntax.
Require Ltac2.Init.
Require MetaRocq.Utils.MRTactics.UniquePose.
Require Stdlib.BinNums.IntDef.
Require Stdlib.BinNums.NatDef.
Require Stdlib.BinNums.PosDef.
Require Stdlib.Classes.CMorphisms.
Require Stdlib.Classes.CRelationClasses.
Require Stdlib.Classes.Morphisms.
Require Stdlib.Classes.Morphisms_Prop.
Require Stdlib.Classes.RelationClasses.
Require Stdlib.Floats.FloatAxioms.
Require Stdlib.Floats.FloatOps.
Require Stdlib.Floats.PrimFloat.
Require Stdlib.Floats.SpecFloat.
Require Stdlib.Init.Byte.
Require Stdlib.Init.Decimal.
Require Stdlib.Init.Hexadecimal.
Require Stdlib.Init.Nat.
Require Stdlib.Init.Sumbool.
Require Stdlib.Init.Wf.
Require Stdlib.Lists.ListDef.
Require Stdlib.Logic.Eqdep.
Require Stdlib.Logic.Eqdep_dec.
Require Stdlib.Logic.ProofIrrelevanceFacts.
Require Stdlib.Numbers.BinNums.
Require Stdlib.Numbers.Cyclic.Int63.CarryType.
Require Stdlib.Numbers.Cyclic.Int63.PrimInt63.
Require Stdlib.Numbers.Cyclic.Int63.Sint63Axioms.
Require Stdlib.Numbers.Cyclic.Int63.Uint63Axioms.
Require Stdlib.Program.Basics.
Require Stdlib.Program.Tactics.
Require Stdlib.Program.Utils.
Require Stdlib.Program.Wf.
Require Stdlib.Relations.Relation_Definitions.
Require Stdlib.Setoids.Setoid.
Require Stdlib.Strings.PrimString.
Require Stdlib.Strings.PrimStringAxioms.
Require Stdlib.Unicode.Utf8.
Requ
9E88
ire Stdlib.Wellfounded.Well_Ordering.
Require Stdlib.extraction.Extraction.
Require Stdlib.ssr.ssrbool.
Require Stdlib.ssr.ssreflect.
Require Stdlib.ssr.ssrfun.
Require Equations.Init.
Require Ltac2.Message.
Require Ltac2.Std.
Require MetaRocq.Utils.MRTactics.DestructHead.
Require MetaRocq.Utils.MRTactics.SpecializeAllWays.
Require Stdlib.Bool.Bool.
Require Stdlib.Logic.JMeq.
Require Stdlib.Logic.ProofIrrelevance.
Require Stdlib.Relations.Relation_Operators.
Require Stdlib.Wellfounded.Inclusion.
Require Equations.Prop.SigmaNotations.
Require Equations.Signature.
Require Ltac2.Control.
Require MetaRocq.Utils.MRTactics.GeneralizeOverHoles.
Require Stdlib.Program.Combinators.
Require Stdlib.Relations.Operators_Properties.
Require Stdlib.Wellfounded.Disjoint_Union.
Require Stdlib.Wellfounded.Transitive_Closure.
Require Equations.CoreTactics.
Require Stdlib.PArith.BinPosDef.
Require Stdlib.Relations.Relations.
Require Stdlib.Wellfounded.Union.
Require Ltac2.Ltac1.
Require Stdlib.Program.Equality.
Require Equations.Type.Logic.
Require Stdlib.Numbers.NumPrelude.
Require Equations.Prop.Logic.
Require Equations.Type.Relation.
Require MetaRocq.Utils.MRTactics.InHypUnderBindersDo.
Require MetaRocq.Utils.MRTactics.SpecializeUnderBindersBy.
Require Stdlib.Classes.RelationPairs.
Require Stdlib.Program.WfExtensionality.
Require Stdlib.Wellfounded.Lexicographic_Product.
Require Equations.Type.Relation_Properties.
Require MetaRocq.Utils.MRProd.
Require Stdlib.Structures.Equalities.
Require Equations.Prop.Classes.
Require Stdlib.Program.Subset.
Require Equations.Prop.EqDec.
Require MetaRocq.Utils.MRRelations.
Require Equations.Prop.DepElim.
Require Equations.Prop.FunctionalInduction.
Require Stdlib.Structures.Orders.
Require Equations.Prop.Constants.
Require Stdlib.Structures.OrdersTac.
Require Stdlib.Structures.OrdersFacts.
Require Stdlib.Structures.GenericMinMax.
Require Stdlib.Program.Program.
Require Stdlib.Numbers.NatInt.NZAxioms.
Require Stdlib.Numbers.NatInt.NZBase.
Require Stdlib.Numbers.NatInt.NZAdd.
Require Stdlib.Numbers.NatInt.NZMul.
Require Stdlib.Numbers.NatInt.NZOrder.
Require Stdlib.Numbers.NatInt.NZAddOrder.
Require Stdlib.Numbers.NatInt.NZMulOrder.
Require Stdlib.Numbers.NatInt.NZDiv.
Require Stdlib.Numbers.NatInt.NZGcd.
Require Stdlib.Numbers.NatInt.NZParity.
Require Stdlib.Numbers.NatInt.NZPow.
Require Stdlib.Numbers.NatInt.NZSqrt.
Require Stdlib.Numbers.NatInt.NZLog.
Require Stdlib.Numbers.NatInt.NZBits.
Require Stdlib.Numbers.Integer.Abstract.ZAxioms.
Require Stdlib.Numbers.Natural.Abstract.NAxioms.
Require Stdlib.Numbers.Integer.Abstract.ZBase.
Require Stdlib.Numbers.Natural.Abstract.NBase.
Require Stdlib.Numbers.Integer.Abstract.ZAdd.
Require Stdlib.Numbers.Natural.Abstract.NAdd.
Require Stdlib.Numbers.Integer.Abstract.ZMul.
Require Stdlib.Numbers.Natural.Abstract.NOrder.
Require Stdlib.Numbers.Integer.Abstract.ZLt.
Require Stdlib.Numbers.Natural.Abstract.NAddOrder.
Require MetaRocq.PCUIC.Syntax.PCUICOnFreeVars.
Axiom proof_admitted : False.
Tactic Notation "admit" := abstract case proof_admitted.
Module Export PCUICOnOne.

Import MetaRocq.Utils.utils.
Import MetaRocq.PCUIC.PCUICAst.
Definition set_preturn (p : predicate term) (pret' : term) : predicate term. exact ({| pparams := p.(pparams);
      puinst := p.(puinst);
      pcontext := p.(pcontext);
      preturn := pret' |}). Defined.
Definition set_pparams (p : predicate term) (pars' : list term) : predicate term. exact ({| pparams := pars';
     puinst := p.(puinst);
     pcontext := p.(pcontext);
     preturn := p.(preturn) |}). Defined.
Definition on_one_decl (P : term -> term -> Type)
  (d : context_decl) (d' : context_decl) : Type. exact (match d, d' with
  | {| decl_name := na; decl_body := None; decl_type := ty |},
    {| decl_name := na'; decl_body := None; decl_type := ty' |} =>
      na = na' × P ty ty'
  | {| decl_name := na; decl_body := Some b; decl_type := ty |},
    {| decl_name := na'; decl_body := Some b'; decl_type := ty' |} =>
      na = na' ×
      ((P ty ty' × b = b') +
        (P b b' × ty = ty'))
  | _, _ => False
  end). Defined.

Section OnOne_local_2.
  Context (P : forall (Γ : context), context_decl -> context_decl -> Type).

  Inductive OnOne2_local_env : context -> context -> Type :=
  | onone2_localenv_cons_abs Γ na na' t t' :
      P Γ (vass na t) (vass na' t') ->
      OnOne2_local_env (Γ ,, vass na t) (Γ ,, vass na' t')
  | onone2_localenv_def Γ na na' b b' t t' :
      P Γ (vdef na b t) (vdef na' b' t') ->
      OnOne2_local_env (Γ ,, vdef na b t) (Γ ,, vdef na' b' t')
  | onone2_localenv_cons_tl Γ Γ' d :
      OnOne2_local_env Γ Γ' ->
      OnOne2_local_env (Γ ,, d) (Γ' ,, d).
End OnOne_local_2.

End PCUICOnOne.
Arguments exist {_ _} _ _.
Import MetaRocq.Utils.utils.
Import MetaRocq.PCUIC.PCUICAst.
Import MetaRocq.PCUIC.Syntax.PCUICCases.
Import Equations.Type.Relation.

Reserved Notation " Σ ;;; Γ |- t ⇝ u " (at level 50, Γ, t, u at next level).

Definition set_array_default (ar : array_model term) (v : term) :=
  {| array_level := ar.(array_level);
     array_default := v;
     array_type := ar.(array_type);
     array_value := ar.(array_value) |}.

Definition set_array_type (ar : array_model term) (v : term) :=
  {| array_level := ar.(array_level);
     array_default := ar.(array_default);
     array_type := v;
     array_value := ar.(array_value) |}.

Definition set_array_value (ar : array_model term) (v : list term) :=
  {| array_level := ar.(array_level);
     array_default := ar.(array_default);
     array_type := ar.(array_type);
     array_value := v |}.

Inductive red1 (Σ : global_env) (Γ : context) : term -> term -> Type :=

| red_beta na t b a :
  Σ ;;; Γ |- tApp (tLambda na t b) a ⇝ b {0 := a}

| red_zeta na b t b' :
  Σ ;;; Γ |- tLetIn na b t b' ⇝ b' {0 := b}

| red_rel i body :
    option_map decl_body (nth_error Γ i) = Some (Some body) ->
    Σ ;;; Γ |- tRel i ⇝ lift0 (S i) body

| red_iota ci c u args p brs br :
    nth_error brs c = Some br ->
    #|args| = (ci.(ci_npar) + context_assumptions br.(bcontext))%nat ->
    Σ ;;; Γ |- tCase ci p (mkApps (tConstruct ci.(ci_ind) c u) args) brs
        ⇝ iota_red ci.(ci_npar) p args br

| red_fix mfix idx args narg fn :
    unfold_fix mfix idx = Some (narg, fn) ->
    is_constructor narg args = true ->
    Σ ;;; Γ |- mkApps (tFix mfix idx) args ⇝ mkApps fn args

| red_cofix_case ip p mfix idx args narg fn brs :
    unfold_cofix mfix idx = Some (narg, fn) ->
    Σ ;;; Γ |- tCase ip p (mkApps (tCoFix mfix idx) args) brs ⇝
         tCase ip p (mkApps fn args) brs

| red_cofix_proj p mfix idx args narg fn :
    unfold_cofix mfix idx = Some (narg, fn) ->
    Σ ;;; Γ |- tProj p (mkApps (tCoFix mfix idx) args) ⇝ tProj p (mkApps fn args)

| red_delta c decl body (isdecl : declared_constant Σ c decl) u :
    decl.(cst_body) = Some body ->
    Σ ;;; Γ |- tConst c u ⇝ subst_instance u body

| red_proj p args u arg:
    nth_error args (p.(proj_npars) + p.(proj_arg)) = Some arg ->
    Σ ;;; Γ |- tProj p (mkApps (tConstruct p.(proj_ind) 0 u) args) ⇝ arg

| abs_red_l na M M' N : Σ ;;; Γ |- M ⇝ M' -> Σ ;;; Γ |- tLambda na M N ⇝ tLambda na M' N
| abs_red_r na M M' N : Σ ;;; Γ ,, vass na N |- M ⇝ M' -> Σ ;;; Γ |- tLambda na N M ⇝ tLambda na N M'

| letin_red_def na b t b' r : Σ ;;; Γ |- b ⇝ r -> Σ ;;; Γ |- tLetIn na b t b' ⇝ tLetIn na r t b'
| letin_red_ty na b t b' r : Σ ;;; Γ |- t ⇝ r -> Σ ;;; Γ |- tLetIn na b t b' ⇝ tLetIn na b r b'
| letin_red_body na b t b' r : Σ ;;; Γ ,, vdef na b t |- b' ⇝ r -> Σ ;;; Γ |- tLetIn na b t b' ⇝ tLetIn na b t r

| case_red_param ci p params' c brs :
    OnOne2 (fun t u => Σ ;;; Γ |- t ⇝ u) p.(pparams) params' ->
    Σ ;;; Γ |- tCase ci p c brs ⇝ tCase ci (set_pparams p params') c brs

| case_red_return ci p preturn' c brs :
  Σ ;;; Γ ,,, inst_case_predicate_context p |- p.(preturn) ⇝ preturn' ->
  Σ ;;; Γ |- tCase ci p c brs ⇝ tCase ci (set_preturn p preturn') c brs

| case_red_discr ci p c c' brs :
  Σ ;;; Γ |- c ⇝ c' -> Σ ;;; Γ |- tCase ci p c brs ⇝ tCase ci p c' brs

| case_red_brs ci p c brs brs' :
    OnOne2 (fun br br' =>
      on_Trel_eq (fun t u => Σ ;;; Γ ,,, inst_case_branch_context p br |- t ⇝ u) bbody bcontext br br')
      brs brs' ->
    Σ ;;; Γ |- tCase ci p c brs ⇝ tCase ci p c brs'

| proj_red p c c' : Σ ;;; Γ |- c ⇝ c' -> Σ ;;; Γ |- tProj p c ⇝ tProj p c'

| app_red_l M1 N1 M2 : Σ ;;; Γ |- M1 ⇝ N1 -> Σ ;;; Γ |- tApp M1 M2 ⇝ tApp N1 M2
| app_red_r M2 N2 M1 : Σ ;;; Γ |- M2 ⇝ N2 -> Σ ;;; Γ |- tApp M1 M2 ⇝ tApp M1 N2

| prod_red_l na M1 M2 N1 : Σ ;;; Γ |- M1 ⇝ N1 -> Σ ;;; Γ |- tProd na M1 M2 ⇝ tProd na N1 M2
| prod_red_r na M2 N2 M1 : Σ ;;; Γ ,, vass na M1 |- M2 ⇝ N2 ->
                           Σ ;;; Γ |- tProd na M1 M2 ⇝ tProd na M1 N2

| evar_red ev l l' : OnOne2 (fun t u => Σ ;;; Γ |- t ⇝ u) l l' -> Σ ;;; Γ |- tEvar ev l ⇝ tEvar ev l'

| fix_red_ty mfix0 mfix1 idx :
    OnOne2 (on_Trel_eq (fun t u => Σ ;;; Γ |- t ⇝ u) dtype (fun x => (dname x, dbody x, rarg x))) mfix0 mfix1 ->
    Σ ;;; Γ |- tFix mfix0 idx ⇝ tFix mfix1 idx

| fix_red_body mfix0 mfix1 idx :
    OnOne2 (on_Trel_eq (fun t u => Σ ;;; Γ ,,, fix_context mfix0 |- t ⇝ u) dbody (fun x => (dname x, dtype x, rarg x)))
           mfix0 mfix1 ->
    Σ ;;; Γ |- tFix mfix0 idx ⇝ tFix mfix1 idx

| cofix_red_ty mfix0 mfix1 idx :
    OnOne2 (on_Trel_eq (fun t u => Σ ;;; Γ |- t ⇝ u) dtype (fun x => (dname x, dbody x, rarg x))) mfix0 mfix1 ->
    Σ ;;; Γ |- tCoFix mfix0 idx ⇝ tCoFix mfix1 idx

| cofix_red_body mfix0 mfix1 idx :
    OnOne2 (on_Trel_eq (fun t u => Σ ;;; Γ ,,, fix_context mfix0 |- t ⇝ u) dbody (fun x => (dname x, dtype x, rarg x))) mfix0 mfix1 ->
    Σ ;;; Γ |- tCoFix mfix0 idx ⇝ tCoFix mfix1 idx

| array_red_val arr value :
    OnOne2 (fun t u => Σ ;;; Γ |- t ⇝ u) arr.(array_value) value ->
    Σ ;;; Γ |- tPrim (primArray; primArrayModel arr) ⇝
               tPrim (primArray; primArrayModel (set_array_value arr value))

| array_red_def arr def :
    Σ ;;; Γ |- arr.(array_default) ⇝ def ->
    Σ ;;; Γ |- tPrim (primArray; primArrayModel arr) ⇝
               tPrim (primArray; primArrayModel (set_array_default arr def))

| array_red_type arr ty :
    Σ ;;; Γ |- arr.(array_type) ⇝ ty ->
    Σ ;;; Γ |- tPrim (primArray; primArrayModel arr) ⇝
          tPrim (primArray; primArrayModel (set_array_type arr ty))

where " Σ ;;; Γ |- t ⇝ u " := (red1 Σ Γ t u).

Definition red1_ctx Σ := (OnOne2_local_env (fun Δ => on_one_decl (fun t t' => red1 Σ Δ t t'))).

Definition red Σ Γ := clos_refl_trans (fun t u : term => Σ;;; Γ |- t ⇝ u).
Module Export PCUICCumulativitySpec.
Import MetaRocq.Common.config.
Import MetaRocq.PCUIC.PCUICEquality.
Import MetaRocq.PCUIC.Syntax.PCUICOnFreeVars.

Implicit Types (cf : checker_flags).

Definition cumul_predicate (cumul : context -> term -> term -> Type) cumul_universe Γ p p' :=
  All2 (cumul Γ) p.(pparams) p'.(pparams) ×
  cmp_universe_instance cumul_universe p.(puinst) p'.(puinst) ×
  eq_context_upto_names p.(pcontext) p'.(pcontext) ×
  cumul (Γ ,,, inst_case_predicate_context p) p.(preturn) p'.(preturn).

Definition cumul_branch (cumul_term : context -> term -> term -> Type) Γ p br br' :=
  eq_context_upto_names br.(bcontext) br'.(bcontext) ×
  cumul_term (Γ ,,, inst_case_branch_context p br) br.(bbody) br'.(bbody).

Definition cumul_branches cumul_term Γ p brs brs' := All2 (cumul_branch cumul_term Γ p) brs brs'.

Definition cumul_mfixpoint (cumul_term : context -> term -> term -> Type) Γ mfix mfix' :=
  All2 (fun d d' =>
    cumul_term Γ d.(dtype) d'.(dtype) ×
    cumul_term (Γ ,,, fix_context mfix) d.(dbody) d'.(dbody) ×
    d.(rarg) = d'.(rarg) ×
    eq_binder_annot d.(dname) d'.(dname)
  ) mfix mfix'.

Reserved Notation " Σ ;;; Γ ⊢ t ≤s[ pb ] u" (at level 50, Γ, t, u at next level,
  format "Σ  ;;;  Γ  ⊢  t  ≤s[ pb ]  u").

Definition cumul_Ind_univ {cf} (Σ : global_env_ext) pb i napp :=
  cmp_global_instance Σ (compare_universe Σ) pb (IndRef i) napp.

Definition cumul_Construct_univ {cf} (Σ : global_env_ext) pb  i k napp :=
  cmp_global_instance Σ (compare_universe Σ) pb (ConstructRef i k) napp.
Inductive cumulSpec0 {cf : checker_flags} (Σ : global_env_ext) Γ (pb : conv_pb) : term -> term -> Type :=

| cumul_Trans : forall t u v,
    is_closed_context Γ -> is_open_term Γ u ->
    Σ ;;; Γ ⊢ t ≤s[pb] u ->
    Σ ;;; Γ ⊢ u ≤s[pb] v ->
    Σ ;;; Γ ⊢ t ≤s[pb] v

| cumul_Sym : forall t u,
    Σ ;;; Γ ⊢ t ≤s[Conv] u ->
    Σ ;;; Γ ⊢ u ≤s[pb] t

| cumul_Refl : forall t,
    Σ ;;; Γ ⊢ t ≤s[pb] t

| cumul_Ind : forall i u u' args args',
    cumul_Ind_univ Σ pb i #|args| u u' ->
    All2 (fun t u => Σ ;;; Γ ⊢ t ≤s[Conv] u) args args' ->
    Σ ;;; Γ ⊢ mkApps (tInd i u) args ≤s[pb] mkApps (tInd i u') args'

| cumul_Construct : forall i k u u' args args',
    cumul_Construct_univ Σ pb i k #|args| u u' ->
    All2 (fun t u => Σ ;;; Γ ⊢ t ≤s[Conv] u) args args' ->
    Σ ;;; Γ ⊢ mkApps (tConstruct i k u) args ≤s[pb] mkApps (tConstruct i k u') args'

| cumul_Sort : forall s s',
    compare_sort Σ pb s s' ->
    Σ ;;; Γ ⊢ tSort s ≤s[pb] tSort s'

| cumul_Const : forall c u u',
    cmp_universe_instance (compare_universe Σ Conv) u u' ->
    Σ ;;; Γ ⊢ tConst c u ≤s[pb] tConst c u'

| cumul_Evar : forall e args args',
    All2 (fun t u => Σ ;;; Γ ⊢ t ≤s[Conv] u) args args' ->
    Σ ;;; Γ ⊢ tEvar e args ≤s[pb] tEvar e args'

| cumul_App : forall t t' u u',
    Σ ;;; Γ ⊢ t ≤s[pb] t' ->
    Σ ;;; Γ ⊢ u ≤s[Conv] u' ->
    Σ ;;; Γ ⊢ tApp t u ≤s[pb] tApp t' u'

| cumul_Lambda : forall na na' ty ty' t t',
    eq_binder_annot na na' ->
    Σ ;;; Γ ⊢ ty ≤s[Conv] ty' ->
    Σ ;;; Γ ,, vass na ty ⊢ t ≤s[Conv] t' ->
    Σ ;;; Γ ⊢ tLambda na ty t ≤s[pb] tLambda na' ty' t'

| cumul_Prod : forall na na' a a' b b',
    eq_binder_annot na na' ->
    Σ ;;; Γ ⊢ a ≤s[Conv] a' ->
    Σ ;;; Γ ,, vass na a ⊢ b ≤s[pb] b' ->
    Σ ;;; Γ ⊢ tProd na a b ≤s[pb] tProd na' a' b'

| cumul_LetIn : forall na na' t t' ty ty' u u',
    eq_binder_annot na na' ->
    Σ ;;; Γ ⊢ t ≤s[Conv] t' ->
    Σ ;;; Γ ⊢ ty ≤s[Conv] ty' ->
    Σ ;;; Γ ,, vdef na t ty ⊢ u ≤s[Conv] u' ->
    Σ ;;; Γ ⊢ tLetIn na t ty u ≤s[pb] tLetIn na' t' ty' u'

| cumul_Case indn : forall p p' c c' brs brs',
    cumul_predicate (fun Γ t u => Σ ;;; Γ ⊢ t ≤s[Conv] u) (compare_universe Σ Conv) Γ p p' ->
    Σ ;;; Γ ⊢ c ≤s[Conv] c' ->
    cumul_branches (fun Γ t u => Σ ;;; Γ ⊢ t ≤s[Conv] u) Γ p brs brs' ->
    Σ ;;; Γ ⊢ tCase indn p c brs ≤s[pb] tCase indn p' c' brs'

| cumul_Proj : forall p c c',
    Σ ;;; Γ ⊢ c ≤s[Conv] c' ->
    Σ ;;; Γ ⊢ tProj p c ≤s[pb] tProj p c'

| cumul_Fix : forall mfix mfix' idx,
    cumul_mfixpoint (fun Γ t u => Σ ;;; Γ ⊢ t ≤s[Conv] u) Γ mfix mfix' ->
    Σ ;;; Γ ⊢ tFix mfix idx ≤s[pb] tFix mfix' idx

| cumul_CoFix : forall mfix mfix' idx,
    cumul_mfixpoint (fun Γ t u => Σ ;;; Γ ⊢ t ≤s[Conv] u) Γ mfix mfix' ->
    Σ ;;; Γ ⊢ tCoFix mfix idx ≤s[pb] tCoFix mfix' idx

| cumul_Prim p p' :
  onPrims (fun x y => Σ ;;; Γ ⊢ x ≤s[Conv] y) (compare_universe Σ Conv) p p' ->
  Σ ;;; Γ ⊢ tPrim p ≤s[pb] tPrim p'

| cumul_beta : forall na t b a,
    Σ ;;; Γ ⊢ tApp (tLambda na t b) a ≤s[pb] b {0 := a}

| cumul_zeta : forall na b t b',
    Σ ;;; Γ ⊢ tLetIn na b t b' ≤s[pb] b' {0 := b}

| cumul_rel i body :
    option_map decl_body (nth_error Γ i) = Some (Some body) ->
    Σ ;;; Γ ⊢ tRel i ≤s[pb] lift0 (S i) body

| cumul_iota : forall ci c u args p brs br,
    nth_error brs c = Some br ->
    #|args| = (ci.(ci_npar) + context_assumptions br.(bcontext))%nat ->
    Σ ;;; Γ ⊢ tCase ci p (mkApps (tConstruct ci.(ci_ind) c u) args) brs  ≤s[pb] iota_red ci.(ci_npar) p args br

| cumul_fix : forall mfix idx args narg fn,
    unfold_fix mfix idx = Some (narg, fn) ->
    is_constructor narg args = true ->
    Σ ;;; Γ ⊢ mkApps (tFix mfix idx) args ≤s[pb] mkApps fn args

| cumul_cofix_case : forall ip p mfix idx args narg fn brs,
    unfold_cofix mfix idx = Some (narg, fn) ->
    Σ ;;; Γ ⊢ tCase ip p (mkApps (tCoFix mfix idx) args) brs ≤s[pb] tCase ip p (mkApps fn args) brs

| cumul_cofix_proj : forall p mfix idx args narg fn,
    unfold_cofix mfix idx = Some (narg, fn) ->
    Σ ;;; Γ ⊢ tProj p (mkApps (tCoFix mfix idx) args) ≤s[pb] tProj p (mkApps fn args)

| cumul_delta : forall c decl body (isdecl : declared_constant Σ c decl) u,
    decl.(cst_body) = Some body ->
    Σ ;;; Γ ⊢ tConst c u ≤s[pb] body@[u]

| cumul_proj : forall p args u arg,
    nth_error args (p.(proj_npars) + p.(proj_arg)) = Some arg ->
    Σ ;;; Γ ⊢ tProj p (mkApps (tConstruct p.(proj_ind) 0 u) args) ≤s[pb] arg

where " Σ ;;; Γ ⊢ t ≤s[ pb ] u " := (@cumulSpec0 _ Σ Γ pb t u) : type_scope.
Definition cumulSpec `{checker_flags} (Σ : global_env_ext) Γ := cumulSpec0 Σ Γ Cumul.

Notation " Σ ;;; Γ |- t <=s u " := (@cumulSpec _ Σ Γ t u) (at level 50, Γ, t, u at next level).

Module PCUICConversionParSpec <: EnvironmentTyping.ConversionParSig PCUICTerm PCUICEnvironment PCUICTermUtils PCUICEnvTyping.
  Definition cumul_gen := @cumulSpec0.
End PCUICConversionParSpec.

End PCUICCumulativitySpec.
Import MetaRocq.Common.config.
Import MetaRocq.PCUIC.utils.PCUICAstUtils.
Import MetaRocq.PCUIC.utils.PCUICPrimitive.
Import MetaRocq.PCUIC.PCUICEquality.

Implicit Types (cf : checker_flags) (Σ : global_env_ext).

Definition type_of_constructor mdecl (cdecl : constructor_body) (c : inductive * nat) (u : list Level.t) :=
  let mind := inductive_mind (fst c) in
  subst0 (inds mind u mdecl.(ind_bodies)) (subst_instance u (cstr_type cdecl)).

Include PCUICEnvTyping.

Inductive FixCoFix : Type := Fix | CoFix.

Class GuardChecker :=
{
  guard : FixCoFix -> global_env_ext -> context -> mfixpoint term -> Prop ;
}.

Axiom guard_checking : GuardChecker.
#[global]
Existing Instance guard_checking.

Definition fix_guard := guard Fix.
Definition cofix_guard := guard CoFix.

Definition destInd (t : term) :=
  match t with
  | tInd ind u => Some (ind, u)
  | _ => None
  end.

Definition isCoFinite (r : recursivity_kind) :=
  match r with
  | CoFinite => true
  | _ => false
  end.

Definition check_recursivity_kind
  (lookup: kername -> option global_decl) ind r :=
  match lookup ind with
  | Some (InductiveDecl mib) => ReflectEq.eqb mib.(ind_finite) r
  | _ => false
  end.

Definition check_one_fix d :=
  let '{| dname := na;
         dtype := ty;
         dbody := b;
         rarg := arg |} := d in
  let '(ctx, ty) := decompose_prod_assum [] ty in
  match nth_error (List.rev (smash_context [] ctx)) arg with
  | Some argd =>
    let (hd, args) := decompose_app argd.(decl_type) in
    match destInd hd with
    | Some (mkInd mind _, u) => Some mind
    | None => None
    end
  | None => None
  end.

Definition wf_fixpoint_gen
  (lookup: kername -> option global_decl) mfix :=
  forallb (isLambda ∘ dbody) mfix &&
  let checks := map check_one_fix mfix in
  match map_option_out checks with
  | Some (ind :: inds) =>

    forallb (eqb ind) inds &&
    check_recursivity_kind lookup ind Finite
  | _ => false
  end.

Definition wf_fixpoint (Σ : global_env) := wf_fixpoint_gen (lookup_env Σ).

Definition check_one_cofix d :=
  let '{| dname := na;
         dtype := ty;
         dbody := b;
         rarg := arg |} := d in
  let '(ctx, ty) := decompose_prod_assum [] ty in
  let (hd, args) := decompose_app ty in
  match destInd hd with
  | Some (mkInd ind _, u) => Some ind
  | None => None
  end.

Definition wf_cofixpoint_gen
  (lookup: kername -> option global_decl) mfix :=
  let checks := map check_one_cofix mfix in
  match map_option_out checks with
  | Some (ind :: inds) =>

    forallb (eqb ind) inds &&
    check_recursivity_kind lookup ind CoFinite
  | _ => false
  end.

Definition wf_cofixpoint (Σ : global_env) := wf_cofixpoint_gen (lookup_env Σ).

Reserved Notation "'wf_local' Σ Γ " (at level 9, Σ, Γ at next level).

Reserved Notation " Σ ;;; Γ |- t : T " (at level 50, Γ, t, T at next level).

Variant case_side_conditions `{checker_flags} wf_local_fun typing Σ Γ ci p ps mdecl idecl indices predctx :=
| case_side_info
    (eq_npars : mdecl.(ind_npars) = ci.(ci_npar))
    (wf_pred : wf_predicate mdecl idecl p)
    (cons : consistent_instance_ext Σ (ind_universes mdecl) p.(puinst))
    (wf_pctx : wf_local_fun Σ (Γ ,,, predctx))

    (conv_pctx : eq_context_upto_names p.(pcontext) (ind_predicate_context ci.(ci_ind) mdecl idecl))
    (allowed_elim : is_allowed_elimination Σ idecl.(ind_kelim) ps)
    (elim_relevance : isSortRel ps ci.(ci_relevance))
    (ind_inst : ctx_inst (typing Σ) Γ (p.(pparams) ++ indices)
                         (List.rev (subst_instance p.(puinst)
                                                   (ind_params mdecl ,,, ind_indices idecl : context))))
    (not_cofinite : isCoFinite mdecl.(ind_finite) = false).

Variant case_branch_typing `{checker_flags} wf_local_fun typing Σ Γ (ci:case_info) p ps mdecl idecl ptm  brs :=
| case_branch_info
    (wf_brs : wf_branches idecl brs)
    (brs_ty :
       All2i (fun i cdecl br =>

                eq_context_upto_names br.(bcontext) (cstr_branch_context ci mdecl cdecl) ×
                let brctxty := case_branch_type ci.(ci_ind) mdecl idecl p br ptm i cdecl in
                (wf_local_fun Σ (Γ ,,, brctxty.1) ×
                ((typing Σ (Γ ,,, brctxty.1) br.(bbody) (brctxty.2)) ×
                (typing Σ (Γ ,,, brctxty.1) brctxty.2 (tSort ps)))))
             0 idecl.(ind_ctors) brs).

Variant primitive_typing_hyps `{checker_flags}
  (typing : forall (Σ : global_env_ext) (Γ : context), term -> term -> Type)
  Σ Γ : prim_val term -> Type :=
| prim_int_hyps i : primitive_typing_hyps typing Σ Γ (primInt; primIntModel i)
| prim_float_hyps f : primitive_typing_hyps typing Σ Γ (primFloat; primFloatModel f)
| prim_string_hyps s : primitive_typing_hyps typing Σ Γ (primString; primStringModel s)
| prim_array_hyps a
  (wfl : wf_universe Σ (Universe.make' a.(array_level)))
  (hty : typing Σ Γ a.(array_type) (tSort (sType (Universe.make' a.(array_level)))))
  (hdef : typing Σ Γ a.(array_default) a.(array_type))
  (hvalue : All (fun x => typing Σ Γ x a.(array_type)) a.(array_value)) :
  primitive_typing_hyps typing Σ Γ (primArray; primArrayModel a).

Equations prim_type (p : prim_val term) (cst : kername) : term :=
prim_type (primInt; _) cst := tConst cst [];
prim_type (primFloat; _) cst := tConst cst [];
prim_type (primString; _) cst := tConst cst [];
prim_type (primArray; primArrayModel a) cst := tApp (tConst cst [a.(array_level)]) a.(array_type).

Inductive typing `{checker_flags} (Σ : global_env_ext) (Γ : context) : term -> term -> Type :=
| type_Rel : forall n decl,
    wf_local Σ Γ ->
    nth_error Γ n = Some decl ->
    Σ ;;; Γ |- tRel n : lift0 (S n) decl.(decl_type)

| type_Sort : forall s,
    wf_local Σ Γ ->
    wf_sort Σ s ->
    Σ ;;; Γ |- tSort s : tSort (Sort.super s)

| type_Prod : forall na A B s1 s2,
    lift_typing typing Σ Γ (j_vass_s na A s1) ->
    Σ ;;; Γ ,, vass na A |- B : tSort s2 ->
    Σ ;;; Γ |- tProd na A B : tSort (Sort.sort_of_product s1 s2)

| type_Lambda : forall na A t B,
    lift_typing typing Σ Γ (j_vass na A) ->
    Σ ;;; Γ ,, vass na A |- t : B ->
    Σ ;;; Γ |- tLambda na A t : tProd na A B

| type_LetIn : forall na b B t A,
    lift_typing typing Σ Γ (j_vdef na b B) ->
    Σ ;;; Γ ,, vdef na b B |- t : A ->
    Σ ;;; Γ |- tLetIn na b B t : tLetIn na b B A

| type_App : forall t na A B s u,

    Σ ;;; Γ |- tProd na A B : tSort s ->
    Σ ;;; Γ |- t : tProd na A B ->
    Σ ;;; Γ |- u : A ->
    Σ ;;; Γ |- tApp t u : B{0 := u}

| type_Const : forall cst u decl,
    wf_local Σ Γ ->
    declared_constant Σ cst decl ->
    consistent_instance_ext Σ decl.(cst_universes) u ->
    Σ ;;; Γ |- tConst cst u : decl.(cst_type)@[u]

| type_Ind : forall ind u mdecl idecl,
    wf_local Σ Γ ->
    declared_inductive Σ ind mdecl idecl ->
    consistent_instance_ext Σ mdecl.(ind_universes) u ->
    Σ ;;; Γ |- tInd ind u : idecl.(ind_type)@[u]

| type_Construct : forall ind i u mdecl idecl cdecl,
    wf_local Σ Γ ->
    declared_constructor Σ (ind, i) mdecl idecl cdecl ->
    consistent_instance_ext Σ mdecl.(ind_universes) u ->
    Σ ;;; Γ |- tConstruct ind i u : type_of_constructor mdecl cdecl (ind, i) u

| type_Case : forall ci p c brs indices ps mdecl idecl,
    let predctx := case_predicate_context ci.(ci_ind) mdecl idecl p in
    let ptm := it_mkLambda_or_LetIn predctx p.(preturn) in
    declared_inductive Σ ci.(ci_ind) mdecl idecl ->
    Σ ;;; Γ ,,, predctx |- p.(preturn) : tSort ps ->
    Σ ;;; Γ |- c : mkApps (tInd ci.(ci_ind) p.(puinst)) (p.(pparams) ++ indices) ->
    case_side_conditions (fun Σ Γ => wf_local Σ Γ) typing Σ Γ ci p ps
                         mdecl idecl indices predctx  ->
    case_branch_typing (fun Σ Γ => wf_local Σ Γ) typing Σ Γ ci p ps
                        mdecl idecl ptm brs ->
    Σ ;;; Γ |- tCase ci p c brs : mkApps ptm (indices ++ [c])

| type_Proj : forall p c u mdecl idecl cdecl pdecl args,
    declared_projection Σ p mdecl idecl cdecl pdecl ->
    Σ ;;; Γ |- c : mkApps (tInd p.(proj_ind) u) args ->
    #|args| = ind_npars mdecl ->
    Σ ;;; Γ |- tProj p c : subst0 (c :: List.rev args) pdecl.(proj_type)@[u]

| type_Fix : forall mfix n decl,
    wf_local Σ Γ ->
    fix_guard Σ Γ mfix ->
    nth_error mfix n = Some decl ->
    All (on_def_type (lift_typing1 (typing Σ)) Γ) mfix ->
    All (on_def_body (lift_typing1 (typing Σ)) (fix_context mfix) Γ) mfix ->
    wf_fixpoint Σ mfix ->
    Σ ;;; Γ |- tFix mfix n : decl.(dtype)

| type_CoFix : forall mfix n decl,
    wf_local Σ Γ ->
    cofix_guard Σ Γ mfix ->
    nth_error mfix n = Some decl ->
    All (on_def_type (lift_typing1 (typing Σ)) Γ) mfix ->
    All (on_def_body (lift_typing1 (typing Σ)) (fix_context mfix) Γ) mfix ->
    wf_cofixpoint Σ mfix ->
    Σ ;;; Γ |- tCoFix mfix n : decl.(dtype)

| type_Prim p prim_ty cdecl :
    wf_local Σ Γ ->
    primitive_constant Σ (prim_val_tag p) = Some prim_ty ->
    declared_constant Σ prim_ty cdecl ->
    primitive_invariants (prim_val_tag p) cdecl ->
    primitive_typing_hyps typing Σ Γ p ->
    Σ ;;; Γ |- tPrim p : prim_type p prim_ty

| type_Cumul : forall t A B s,
    Σ ;;; Γ |- t : A ->
    Σ ;;; Γ |- B : tSort s ->
    Σ ;;; Γ |- A <=s B ->
    Σ ;;; Γ |- t : B

where " Σ ;;; Γ |- t : T " := (typing Σ Γ t T)
and "'wf_local' Σ Γ " := (All_local_env (lift_typing1 (typing Σ)) Γ).

Module PCUICTypingDef <: EnvironmentTyping.Typing PCUICTerm PCUICEnvironment PCUICTermUtils PCUICEnvTyping PCUICConversion PCUICConversionParSpec.

  Definition typing := @typing.

End PCUICTypingDef.

Definition wf `{checker_flags} := on_global_env cumulSpec0 (lift_typing typing).
Notation on_contexts_length := All2_fold_length.
Import MetaRocq.PCUIC.Syntax.PCUICOnFreeVars.
Import Stdlib.ssr.ssreflect.
Import Stdlib.ssr.ssrbool.
Import Equations.Prop.Equations.
Import Stdlib.Classes.CRelationClasses.
Import Equations.Type.Relation_Properties.

Definition ws_term P := { t : term | on_free_vars P t }.
Definition ws_term_proj {P} (t : ws_term P) : term.
admit.
Defined.
Coercion ws_term_proj : ws_term >-> term.

Definition ws_context P := { t : context | on_free_vars_ctx 

[...]

xadecimal.
Require Corelib.Init.Nat.
Require Corelib.Init.Sumbool.
Require Corelib.Init.Wf.
Require Corelib.Lists.ListDef.
Require Corelib.Numbers.BinNums.
Require Corelib.Numbers.Cyclic.Int63.CarryType.
Require Corelib.Numbers.Cyclic.Int63.PrimInt63.
Require Corelib.Numbers.Cyclic.Int63.Sint63Axioms.
Require Corelib.Numbers.Cyclic.Int63.Uint63Axioms.
Require Corelib.Program.Basics.
Require Corelib.Program.Tactics.
Require Corelib.Program.Utils.
Require Corelib.Program.Wf.
Require Corelib.Relations.Relation_Definitions.
Require Corelib.Setoids.Setoid.
Require Corelib.Strings.PrimString.
Require Corelib.Strings.PrimStringAxioms.
Require Corelib.extraction.Extraction.
Require Corelib.ssr.ssrbool.
Require Corelib.ssr.ssreflect.
Require Corelib.ssr.ssrfun.
Require MetaRocq.Utils.MREquality.
Require MetaRocq.Utils.MRSquash.
Require MetaRocq.Utils.MRTactics.DestructHyps.
Require MetaRocq.Utils.MRTactics.FindHyp.
Require MetaRocq.Utils.MRTactics.Head.
Require MetaRocq.Utils.MRTactics.SpecializeBy.
Require MetaRocq.Utils.MRTactics.SplitInContext.
Require MetaRocq.Utils.MRTactics.Zeta1.
Require Stdlib.Classes.DecidableClass.
Require Stdlib.Logic.Decidable.
Require Stdlib.Logic.EqdepFacts.
Require Stdlib.Logic.FunctionalExtensionality.
Require Stdlib.Logic.HLevelsBase.
Require Stdlib.Program.Syntax.
Require Stdlib.Sets.Relations_1.
Require Stdlib.Unicode.Utf8_core.
Require Stdlib.Wellfounded.Inverse_Image.
Require Stdlib.micromega.ZifyClasses.
Require Stdlib.setoid_ring.Algebra_syntax.
Require Ltac2.Init.
Require MetaRocq.Utils.MRTactics.UniquePose.
Require Stdlib.BinNums.IntDef.
Require Stdlib.BinNums.NatDef.
Require Stdlib.BinNums.PosDef.
Require Stdlib.Classes.CMorphisms.
Require Stdlib.Classes.CRelationClasses.
Require Stdlib.Classes.Morphisms.
Require Stdlib.Classes.Morphisms_Prop.
Require Stdlib.Classes.RelationClasses.
Require Stdlib.Floats.FloatAxioms.
Require Stdlib.Floats.FloatOps.
Require Stdlib.Floats.PrimFloat.
Require Stdlib.Floats.SpecFloat.
Require Stdlib.Init.Byte.
Require Stdlib.Init.Decimal.
Require Stdlib.Init.Hexadecimal.
Require Stdlib.Init.Nat.
Require Stdlib.Init.Sumbool.
Require Stdlib.Init.Wf.
Require Stdlib.Lists.ListDef.
Require Stdlib.Logic.Eqdep.
Require Stdlib.Logic.Eqdep_dec.
Require Stdlib.Logic.ProofIrrelevanceFacts.
Require Stdlib.Numbers.BinNums.
Require Stdlib.Numbers.Cyclic.Int63.CarryType.
Require<
F438
/span> Stdlib.Numbers.Cyclic.Int63.PrimInt63.
Require Stdlib.Numbers.Cyclic.Int63.Sint63Axioms.
Require Stdlib.Numbers.Cyclic.Int63.Uint63Axioms.
Require Stdlib.Program.Basics.
Require Stdlib.Program.Tactics.
Require Stdlib.Program.Utils.
Require Stdlib.Program.Wf.
Require Stdlib.Relations.Relation_Definitions.
Require Stdlib.Setoids.Setoid.
Require Stdlib.Strings.PrimString.
Require Stdlib.Strings.PrimStringAxioms.
Require Stdlib.Unicode.Utf8.
Require Stdlib.Wellfounded.Well_Ordering.
Require Stdlib.extraction.Extraction.
Require Stdlib.ssr.ssrbool.
Require Stdlib.ssr.ssreflect.
Require Stdlib.ssr.ssrfun.
Require Equations.Init.
Require Ltac2.Message.
Require Ltac2.Std.
Require MetaRocq.Utils.MRTactics.DestructHead.
Require MetaRocq.Utils.MRTactics.SpecializeAllWays.
Require Stdlib.Bool.Bool.
Require Stdlib.Logic.JMeq.
Require Stdlib.Logic.ProofIrrelevance.
Require Stdlib.Relations.Relation_Operators.
Require Stdlib.Wellfounded.Inclusion.
Require Equations.Prop.SigmaNotations.
Require Equations.Signature.
Require Ltac2.Control.
Require MetaRocq.Utils.MRTactics.GeneralizeOverHoles.
Require Stdlib.Program.Combinators.
Require Stdlib.Relations.Operators_Properties.
Require Stdlib.Wellfounded.Disjoint_Union.
Require Stdlib.Wellfounded.Transitive_Closure.
Require Equations.CoreTactics.
Require Stdlib.PArith.BinPosDef.
Require Stdlib.Relations.Relations.
Require Stdlib.Wellfounded.Union.
Require Ltac2.Ltac1.
Require Stdlib.Program.Equality.
Require Equations.Type.Logic.
Require Stdlib.Numbers.NumPrelude.
Require Equations.Prop.Logic.
Require Equations.Type.Relation.
Require MetaRocq.Utils.MRTactics.InHypUnderBindersDo.
Require MetaRocq.Utils.MRTactics.SpecializeUnderBindersBy.
Require Stdlib.Classes.RelationPairs.
Require Stdlib.Program.WfExtensionality.
Require Stdlib.Wellfounded.Lexicographic_Product.
Require Equations.Type.Relation_Properties.
Require MetaRocq.Utils.MRProd.
Require Stdlib.Structures.Equalities.
Require Equations.Prop.Classes.
Require Stdlib.Program.Subset.
Require Equations.Prop.EqDec.
Require MetaRocq.Utils.MRRelations.
Require Equations.Prop.DepElim.
Require Equations.Prop.FunctionalInduction.
Require Stdlib.Structures.Orders.
Require Equations.Prop.Constants.
Require Stdlib.Structures.OrdersTac.
Require Stdlib.Structures.OrdersFacts.
Require Stdlib.Structures.GenericMinMax.
Require Stdlib.Program.Program.
Require Stdlib.Numbers.NatInt.NZAxioms.
Require Stdlib.Numbers.NatInt.NZBase.
Require Stdlib.Numbers.NatInt.NZAdd.
Require Stdlib.Numbers.NatInt.NZMul.
Require Stdlib.Numbers.NatInt.NZOrder.
Require Stdlib.Numbers.NatInt.NZAddOrder.
Require Stdlib.Numbers.NatInt.NZMulOrder.
Require Stdlib.Numbers.NatInt.NZDiv.
Require Stdlib.Numbers.NatInt.NZGcd.
Require Stdlib.Numbers.NatInt.NZParity.
Require Stdlib.Numbers.NatInt.NZPow.
Require Stdlib.Numbers.NatInt.NZSqrt.
Require Stdlib.Numbers.NatInt.NZLog.
Require Stdlib.Numbers.NatInt.NZBits.
Require Stdlib.Numbers.Integer.Abstract.ZAxioms.
Require Stdlib.Numbers.Natural.Abstract.NAxioms.
Require Stdlib.Numbers.Integer.Abstract.ZBase.
Require Stdlib.Numbers.Natural.Abstract.NBase.
Require Stdlib.Numbers.Integer.Abstract.ZAdd.
Require Stdlib.Numbers.Natural.Abstract.NAdd.
Require Stdlib.Numbers.Integer.Abstract.ZMul.
Require Stdlib.Numbers.Natural.Abstract.NOrder.
Require Stdlib.Numbers.Integer.Abstract.ZLt.
Require Stdlib.Numbers.Natural.Abstract.NAddOrder.
Require MetaRocq.PCUIC.Syntax.PCUICOnFreeVars.
Axiom proof_admitted : False.
Tactic Notation "admit" := abstract case proof_admitted.
Module Export PCUICOnOne.

Import MetaRocq.Utils.utils.
Import MetaRocq.PCUIC.PCUICAst.
Definition set_preturn (p : predicate term) (pret' : term) : predicate term. exact ({| pparams := p.(pparams);
      puinst := p.(puinst);
      pcontext := p.(pcontext);
      preturn := pret' |}). Defined.
Definition set_pparams (p : predicate term) (pars' : list term) : predicate term. exact ({| pparams := pars';
     puinst := p.(puinst);
     pcontext := p.(pcontext);
     preturn := p.(preturn) |}). Defined.
Definition on_one_decl (P : term -> term -> Type)
  (d : context_decl) (d' : context_decl) : Type. exact (match d, d' with
  | {| decl_name := na; decl_body := None; decl_type := ty |},
    {| decl_name := na'; decl_body := None; decl_type := ty' |} =>
      na = na' × P ty ty'
  | {| decl_name := na; decl_body := Some b; decl_type := ty |},
    {| decl_name := na'; decl_body := Some b'; decl_type := ty' |} =>
      na = na' ×
      ((P ty ty' × b = b') +
        (P b b' × ty = ty'))
  | _, _ => False
  end). Defined.

Section OnOne_local_2.
  Context (P : forall (Γ : context), context_decl -> context_decl -> Type).

  Inductive OnOne2_local_env : context -> context -> Type :=
  | onone2_localenv_cons_abs Γ na na' t t' :
      P Γ (vass na t) (vass na' t') ->
      OnOne2_local_env (Γ ,, vass na t) (Γ ,, vass na' t')
  | onone2_localenv_def Γ na na' b b' t t' :
      P Γ (vdef na b t) (vdef na' b' t') ->
      OnOne2_local_env (Γ ,, vdef na b t) (Γ ,, vdef na' b' t')
  | onone2_localenv_cons_tl Γ Γ' d :
      OnOne2_local_env Γ Γ' ->
      OnOne2_local_env (Γ ,, d) (Γ' ,, d).
End OnOne_local_2.

End PCUICOnOne.
Arguments exist {_ _} _ _.
Import MetaRocq.Utils.utils.
Import MetaRocq.PCUIC.PCUICAst.
Import MetaRocq.PCUIC.Syntax.PCUICCases.
Import Equations.Type.Relation.

Reserved Notation " Σ ;;; Γ |- t ⇝ u " (at level 50, Γ, t, u at next level).

Definition set_array_default (ar : array_model term) (v : term) :=
  {| array_level := ar.(array_level);
     array_default := v;
     array_type := ar.(array_type);
     array_value := ar.(array_value) |}.

Definition set_array_type (ar : array_model term) (v : term) :=
  {| array_level := ar.(array_level);
     array_default := ar.(array_default);
     array_type := v;
     array_value := ar.(array_value) |}.

Definition set_array_value (ar : array_model term) (v : list term) :=
  {| array_level := ar.(array_level);
     array_default := ar.(array_default);
     array_type := ar.(array_type);
     array_value := v |}.

Inductive red1 (Σ : global_env) (Γ : context) : term -> term -> Type :=

| red_beta na t b a :
  Σ ;;; Γ |- tApp (tLambda na t b) a ⇝ b {0 := a}

| red_zeta na b t b' :
  Σ ;;; Γ |- tLetIn na b t b' ⇝ b' {0 := b}

| red_rel i body :
    option_map decl_body (nth_error Γ i) = Some (Some body) ->
    Σ ;;; Γ |- tRel i ⇝ lift0 (S i) body

| red_iota ci c u args p brs br :
    nth_error brs c = Some br ->
    #|args| = (ci.(ci_npar) + context_assumptions br.(bcontext))%nat ->
    Σ ;;; Γ |- tCase ci p (mkApps (tConstruct ci.(ci_ind) c u) args) brs
        ⇝ iota_red ci.(ci_npar) p args br

| red_fix mfix idx args narg fn :
    unfold_fix mfix idx = Some (narg, fn) ->
    is_constructor narg args = true ->
    Σ ;;; Γ |- mkApps (tFix mfix idx) args ⇝ mkApps fn args

| red_cofix_case ip p mfix idx args narg fn brs :
    unfold_cofix mfix idx = Some (narg, fn) ->
    Σ ;;; Γ |- tCase ip p (mkApps (tCoFix mfix idx) args) brs ⇝
         tCase ip p (mkApps fn args) brs

| red_cofix_proj p mfix idx args narg fn :
    unfold_cofix mfix idx = Some (narg, fn) ->
    Σ ;;; Γ |- tProj p (mkApps (tCoFix mfix idx) args) ⇝ tProj p (mkApps fn args)

| red_delta c decl body (isdecl : declared_constant Σ c decl) u :
    decl.(cst_body) = Some body ->
    Σ ;;; Γ |- tConst c u ⇝ subst_instance u body

| red_proj p args u arg:
    nth_error args (p.(proj_npars) + p.(proj_arg)) = Some arg ->
    Σ ;;; Γ |- tProj p (mkApps (tConstruct p.(proj_ind) 0 u) args) ⇝ arg

| abs_red_l na M M' N : Σ ;;; Γ |- M ⇝ M' -> Σ ;;; Γ |- tLambda na M N ⇝ tLambda na M' N
| abs_red_r na M M' N : Σ ;;; Γ ,, vass na N |- M ⇝ M' -> Σ ;;; Γ |- tLambda na N M ⇝ tLambda na N M'

| letin_red_def na b t b' r : Σ ;;; Γ |- b ⇝ r -> Σ ;;; Γ |- tLetIn na b t b' ⇝ tLetIn na r t b'
| letin_red_ty na b t b' r : Σ ;;; Γ |- t ⇝ r -> Σ ;;; Γ |- tLetIn na b t b' ⇝ tLetIn na b r b'
| letin_red_body na b t b' r : Σ ;;; Γ ,, vdef na b t |- b' ⇝ r -> Σ ;;; Γ |- tLetIn na b t b' ⇝ tLetIn na b t r

| case_red_param ci p params' c brs :
    OnOne2 (fun t u => Σ ;;; Γ |- t ⇝ u) p.(pparams) params' ->
    Σ ;;; Γ |- tCase ci p c brs ⇝ tCase ci (set_pparams p params') c brs

| case_red_return ci p preturn' c brs :
  Σ ;;; Γ ,,, inst_case_predicate_context p |- p.(preturn) ⇝ preturn' ->
  Σ ;;; Γ |- tCase ci p c brs ⇝ tCase ci (set_preturn p preturn') c brs

| case_red_discr ci p c c' brs :
  Σ ;;; Γ |- c ⇝ c' -> Σ ;;; Γ |- tCase ci p c brs ⇝ tCase ci p c' brs

| case_red_brs ci p c brs brs' :
    OnOne2 (fun br br' =>
      on_Trel_eq (fun t u => Σ ;;; Γ ,,, inst_case_branch_context p br |- t ⇝ u) bbody bcontext br br')
      brs brs' ->
    Σ ;;; Γ |- tCase ci p c brs ⇝ tCase ci p c brs'

| proj_red p c c' : Σ ;;; Γ |- c ⇝ c' -> Σ ;;; Γ |- tProj p c ⇝ tProj p c'

| app_red_l M1 N1 M2 : Σ ;;; Γ |- M1 ⇝ N1 -> Σ ;;; Γ |- tApp M1 M2 ⇝ tApp N1 M2
| app_red_r M2 N2 M1 : Σ ;;; Γ |- M2 ⇝ N2 -> Σ ;;; Γ |- tApp M1 M2 ⇝ tApp M1 N2

| prod_red_l na M1 M2 N1 : Σ ;;; Γ |- M1 ⇝ N1 -> Σ ;;; Γ |- tProd na M1 M2 ⇝ tProd na N1 M2
| prod_red_r na M2 N2 M1 : Σ ;;; Γ ,, vass na M1 |- M2 ⇝ N2 ->
                           Σ ;;; Γ |- tProd na M1 M2 ⇝ tProd na M1 N2

| evar_red ev l l' : OnOne2 (fun t u => Σ ;;; Γ |- t ⇝ u) l l' -> Σ ;;; Γ |- tEvar ev l ⇝ tEvar ev l'

| fix_red_ty mfix0 mfix1 idx :
    OnOne2 (on_Trel_eq (fun t u => Σ ;;; Γ |- t ⇝ u) dtype (fun x => (dname x, dbody x, rarg x))) mfix0 mfix1 ->
    Σ ;;; Γ |- tFix mfix0 idx ⇝ tFix mfix1 idx

| fix_red_body mfix0 mfix1 idx :
    OnOne2 (on_Trel_eq (fun t u => Σ ;;; Γ ,,, fix_context mfix0 |- t ⇝ u) dbody (fun x => (dname x, dtype x, rarg x)))
           mfix0 mfix1 ->
    Σ ;;; Γ |- tFix mfix0 idx ⇝ tFix mfix1 idx

| cofix_red_ty mfix0 mfix1 idx :
    OnOne2 (on_Trel_eq (fun t u => Σ ;;; Γ |- t ⇝ u) dtype (fun x => (dname x, dbody x, rarg x))) mfix0 mfix1 ->
    Σ ;;; Γ |- tCoFix mfix0 idx ⇝ tCoFix mfix1 idx

| cofix_red_body mfix0 mfix1 idx :
    OnOne2 (on_Trel_eq (fun t u => Σ ;;; Γ ,,, fix_context mfix0 |- t ⇝ u) dbody (fun x => (dname x, dtype x, rarg x))) mfix0 mfix1 ->
    Σ ;;; Γ |- tCoFix mfix0 idx ⇝ tCoFix mfix1 idx

| array_red_val arr value :
    OnOne2 (fun t u => Σ ;;; Γ |- t ⇝ u) arr.(array_value) value ->
    Σ ;;; Γ |- tPrim (primArray; primArrayModel arr) ⇝
               tPrim (primArray; primArrayModel (set_array_value arr value))

| array_red_def arr def :
    Σ ;;; Γ |- arr.(array_default) ⇝ def ->
    Σ ;;; Γ |- tPrim (primArray; primArrayModel arr) ⇝
               tPrim (primArray; primArrayModel (set_array_default arr def))

| array_red_type arr ty :
    Σ ;;; Γ |- arr.(array_type) ⇝ ty ->
    Σ ;;; Γ |- tPrim (primArray; primArrayModel arr) ⇝
          tPrim (primArray; primArrayModel (set_array_type arr ty))

where " Σ ;;; Γ |- t ⇝ u " := (red1 Σ Γ t u).

Definition red1_ctx Σ := (OnOne2_local_env (fun Δ => on_one_decl (fun t t' => red1 Σ Δ t t'))).

Definition red Σ Γ := clos_refl_trans (fun t u : term => Σ;;; Γ |- t ⇝ u).
Module Export PCUICCumulativitySpec.
Import MetaRocq.Common.config.
Import MetaRocq.PCUIC.PCUICEquality.
Import MetaRocq.PCUIC.Syntax.PCUICOnFreeVars.

Implicit Types (cf : checker_flags).

Definition cumul_predicate (cumul : context -> term -> term -> Type) cumul_universe Γ p p' :=
  All2 (cumul Γ) p.(pparams) p'.(pparams) ×
  cmp_universe_instance cumul_universe p.(puinst) p'.(puinst) ×
  eq_context_upto_names p.(pcontext) p'.(pcontext) ×
  cumul (Γ ,,, inst_case_predicate_context p) p.(preturn) p'.(preturn).

Definition cumul_branch (cumul_term : context -> term -> term -> Type) Γ p br br' :=
  eq_context_upto_names br.(bcontext) br'.(bcontext) ×
  cumul_term (Γ ,,, inst_case_branch_context p br) br.(bbody) br'.(bbody).

Definition cumul_branches cumul_term Γ p brs brs' := All2 (cumul_branch cumul_term Γ p) brs brs'.

Definition cumul_mfixpoint (cumul_term : context -> term -> term -> Type) Γ mfix mfix' :=
  All2 (fun d d' =>
    cumul_term Γ d.(dtype) d'.(dtype) ×
    cumul_term (Γ ,,, fix_context mfix) d.(dbody) d'.(dbody) ×
    d.(rarg) = d'.(rarg) ×
    eq_binder_annot d.(dname) d'.(dname)
  ) mfix mfix'.

Reserved Notation " Σ ;;; Γ ⊢ t ≤s[ pb ] u" (at level 50, Γ, t, u at next level,
  format "Σ  ;;;  Γ  ⊢  t  ≤s[ pb ]  u").

Definition cumul_Ind_univ {cf} (Σ : global_env_ext) pb i napp :=
  cmp_global_instance Σ (compare_universe Σ) pb (IndRef i) napp.

Definition cumul_Construct_univ {cf} (Σ : global_env_ext) pb  i k napp :=
  cmp_global_instance Σ (compare_universe Σ) pb (ConstructRef i k) napp.
Inductive cumulSpec0 {cf : checker_flags} (Σ : global_env_ext) Γ (pb : conv_pb) : term -> term -> Type :=

| cumul_Trans : forall t u v,
    is_closed_context Γ -> is_open_term Γ u ->
    Σ ;;; Γ ⊢ t ≤s[pb] u ->
    Σ ;;; Γ ⊢ u ≤s[pb] v ->
    Σ ;;; Γ ⊢ t ≤s[pb] v

| cumul_Sym : forall t u,
    Σ ;;; Γ ⊢ t ≤s[Conv] u ->
    Σ ;;; Γ ⊢ u ≤s[pb] t

| cumul_Refl : forall t,
    Σ ;;; Γ ⊢ t ≤s[pb] t

| cumul_Ind : forall i u u' args args',
    cumul_Ind_univ Σ pb i #|args| u u' ->
    All2 (fun t u => Σ ;;; Γ ⊢ t ≤s[Conv] u) args args' ->
    Σ ;;; Γ ⊢ mkApps (tInd i u) args ≤s[pb] mkApps (tInd i u') args'

| cumul_Construct : forall i k u u' args args',
    cumul_Construct_univ Σ pb i k #|args| u u' ->
    All2 (fun t u => Σ ;;; Γ ⊢ t ≤s[Conv] u) args args' ->
    Σ ;;; Γ ⊢ mkApps (tConstruct i k u) args ≤s[pb] mkApps (tConstruct i k u') args'

| cumul_Sort : forall s s',
    compare_sort Σ pb s s' ->
    Σ ;;; Γ ⊢ tSort s ≤s[pb] tSort s'

| cumul_Const : forall c u u',
    cmp_universe_instance (compare_universe Σ Conv) u u' ->
    Σ ;;; Γ ⊢ tConst c u ≤s[pb] tConst c u'

| cumul_Evar : forall e args args',
    All2 (fun t u => Σ ;;; Γ ⊢ t ≤s[Conv] u) args args' ->
    Σ ;;; Γ ⊢ tEvar e args ≤s[pb] tEvar e args'

| cumul_App : forall t t' u u',
    Σ ;;; Γ ⊢ t ≤s[pb] t' ->
    Σ ;;; Γ ⊢ u ≤s[Conv] u' ->
    Σ ;;; Γ ⊢ tApp t u ≤s[pb] tApp t' u'

| cumul_Lambda : forall na na' ty ty' t t',
    eq_binder_annot na na' ->
    Σ ;;; Γ ⊢ ty ≤s[Conv] ty' ->
    Σ ;;; Γ ,, vass na ty ⊢ t ≤s[Conv] t' ->
    Σ ;;; Γ ⊢ tLambda na ty t ≤s[pb] tLambda na' ty' t'

| cumul_Prod : forall na na' a a' b b',
    eq_binder_annot na na' ->
    Σ ;;; Γ ⊢ a ≤s[Conv] a' ->
    Σ ;;; Γ ,, vass na a ⊢ b ≤s[pb] b' ->
    Σ ;;; Γ ⊢ tProd na a b ≤s[pb] tProd na' a' b'

| cumul_LetIn : forall na na' t t' ty ty' u u',
    eq_binder_annot na na' ->
    Σ ;;; Γ ⊢ t ≤s[Conv] t' ->
    Σ ;;; Γ ⊢ ty ≤s[Conv] ty' ->
    Σ ;;; Γ ,, vdef na t ty ⊢ u ≤s[Conv] u' ->
    Σ ;;; Γ ⊢ tLetIn na t ty u ≤s[pb] tLetIn na' t' ty' u'

| cumul_Case indn : forall p p' c c' brs brs',
    cumul_predicate (fun Γ t u => Σ ;;; Γ ⊢ t ≤s[Conv] u) (compare_universe Σ Conv) Γ p p' ->
    Σ ;;; Γ ⊢ c ≤s[Conv] c' ->
    cumul_branches (fun Γ t u => Σ ;;; Γ ⊢ t ≤s[Conv] u) Γ p brs brs' ->
    Σ ;;; Γ ⊢ tCase indn p c brs ≤s[pb] tCase indn p' c' brs'

| cumul_Proj : forall p c c',
    Σ ;;; Γ ⊢ c ≤s[Conv] c' ->
    Σ ;;; Γ ⊢ tProj p c ≤s[pb] tProj p c'

| cumul_Fix : forall mfix mfix' idx,
    cumul_mfixpoint (fun Γ t u => Σ ;;; Γ ⊢ t ≤s[Conv] u) Γ mfix mfix' ->
    Σ ;;; Γ ⊢ tFix mfix idx ≤s[pb] tFix mfix' idx

| cumul_CoFix : forall mfix mfix' idx,
    cumul_mfixpoint (fun Γ t u => Σ ;;; Γ ⊢ t ≤s[Conv] u) Γ mfix mfix' ->
    Σ ;;; Γ ⊢ tCoFix mfix idx ≤s[pb] tCoFix mfix' idx

| cumul_Prim p p' :
  onPrims (fun x y => Σ ;;; Γ ⊢ x ≤s[Conv] y) (compare_universe Σ Conv) p p' ->
  Σ ;;; Γ ⊢ tPrim p ≤s[pb] tPrim p'

| cumul_beta : forall na t b a,
    Σ ;;; Γ ⊢ tApp (tLambda na t b) a ≤s[pb] b {0 := a}

| cumul_zeta : forall na b t b',
    Σ ;;; Γ ⊢ tLetIn na b t b' ≤s[pb] b' {0 := b}

| cumul_rel i body :
    option_map decl_body (nth_error Γ i) = Some (Some body) ->
    Σ ;;; Γ ⊢ tRel i ≤s[pb] lift0 (S i) body

| cumul_iota : forall ci c u args p brs br,
    nth_error brs c = Some br ->
    #|args| = (ci.(ci_npar) + context_assumptions br.(bcontext))%nat ->
    Σ ;;; Γ ⊢ tCase ci p (mkApps (tConstruct ci.(ci_ind) c u) args) brs  ≤s[pb] iota_red ci.(ci_npar) p args br

| cumul_fix : forall mfix idx args narg fn,
    unfold_fix mfix idx = Some (narg, fn) ->
    is_constructor narg args = true ->
    Σ ;;; Γ ⊢ mkApps (tFix mfix idx) args ≤s[pb] mkApps fn args

| cumul_cofix_case : forall ip p mfix idx args narg fn brs,
    unfold_cofix mfix idx = Some (narg, fn) ->
    Σ ;;; Γ ⊢ tCase ip p (mkApps (tCoFix mfix idx) args) brs ≤s[pb] tCase ip p (mkApps fn args) brs

| cumul_cofix_proj : forall p mfix idx args narg fn,
    unfold_cofix mfix idx = Some (narg, fn) ->
    Σ ;;; Γ ⊢ tProj p (mkApps (tCoFix mfix idx) args) ≤s[pb] tProj p (mkApps fn args)

| cumul_delta : forall c decl body (isdecl : declared_constant Σ c decl) u,
    decl.(cst_body) = Some body ->
    Σ ;;; Γ ⊢ tConst c u ≤s[pb] body@[u]

| cumul_proj : forall p args u arg,
    nth_error args (p.(proj_npars) + p.(proj_arg)) = Some arg ->
    Σ ;;; Γ ⊢ tProj p (mkApps (tConstruct p.(proj_ind) 0 u) args) ≤s[pb] arg

where " Σ ;;; Γ ⊢ t ≤s[ pb ] u " := (@cumulSpec0 _ Σ Γ pb t u) : type_scope.
Definition cumulSpec `{checker_flags} (Σ : global_env_ext) Γ := cumulSpec0 Σ Γ Cumul.

Notation " Σ ;;; Γ |- t <=s u " := (@cumulSpec _ Σ Γ t u) (at level 50, Γ, t, u at next level).

Module PCUICConversionParSpec <: EnvironmentTyping.ConversionParSig PCUICTerm PCUICEnvironment PCUICTermUtils PCUICEnvTyping.
  Definition cumul_gen := @cumulSpec0.
End PCUICConversionParSpec.

End PCUICCumulativitySpec.
Import MetaRocq.Common.config.
Import MetaRocq.PCUIC.utils.PCUICAstUtils.
Import MetaRocq.PCUIC.utils.PCUICPrimitive.
Import MetaRocq.PCUIC.PCUICEquality.

Implicit Types (cf : checker_flags) (Σ : global_env_ext).

Definition type_of_constructor mdecl (cdecl : constructor_body) (c : inductive * nat) (u : list Level.t) :=
  let mind := inductive_mind (fst c) in
  subst0 (inds mind u mdecl.(ind_bodies)) (subst_instance u (cstr_type cdecl)).

Include PCUICEnvTyping.

Inductive FixCoFix : Type := Fix | CoFix.

Class GuardChecker :=
{
  guard : FixCoFix -> global_env_ext -> context -> mfixpoint term -> Prop ;
}.

Axiom guard_checking : GuardChecker.
#[global]
Existing Instance guard_checking.

Definition fix_guard := guard Fix.
Definition cofix_guard := guard CoFix.

Definition destInd (t : term) :=
  match t with
  | tInd ind u => Some (ind, u)
  | _ => None
  end.

Definition isCoFinite (r : recursivity_kind) :=
  match r with
  | CoFinite => true
  | _ => false
  end.

Definition check_recursivity_kind
  (lookup: kername -> option global_decl) ind r :=
  match lookup ind with
  | Some (InductiveDecl mib) => ReflectEq.eqb mib.(ind_finite) r
  | _ => false
  end.

Definition check_one_fix d :=
  let '{| dname := na;
         dtype := ty;
         dbody := b;
         rarg := arg |} := d in
  let '(ctx, ty) := decompose_prod_assum [] ty in
  match nth_error (List.rev (smash_context [] ctx)) arg with
  | Some argd =>
    let (hd, args) := decompose_app argd.(decl_type) in
    match destInd hd with
    | Some (mkInd mind _, u) => Some mind
    | None => None
    end
  | None => None
  end.

Definition wf_fixpoint_gen
  (lookup: kername -> option global_decl) mfix :=
  forallb (isLambda ∘ dbody) mfix &&
  let checks := map check_one_fix mfix in
  match map_option_out checks with
  | Some (ind :: inds) =>

    forallb (eqb ind) inds &&
    check_recursivity_kind lookup ind Finite
  | _ => false
  end.

Definition wf_fixpoint (Σ : global_env) := wf_fixpoint_gen (lookup_env Σ).

Definition check_one_cofix d :=
  let '{| dname := na;
         dtype := ty;
         dbody := b;
         rarg := arg |} := d in
  let '(ctx, ty) := decompose_prod_assum [] ty in
  let (hd, args) := decompose_app ty in
  match destInd hd with
  | Some (mkInd ind _, u) => Some ind
  | None => None
  end.

Definition wf_cofixpoint_gen
  (lookup: kername -> option global_decl) mfix :=
  let checks := map check_one_cofix mfix in
  match map_option_out checks with
  | Some (ind :: inds) =>

    forallb (eqb ind) inds &&
    check_recursivity_kind lookup ind CoFinite
  | _ => false
  end.

Definition wf_cofixpoint (Σ : global_env) := wf_cofixpoint_gen (lookup_env Σ).

Reserved Notation "'wf_local' Σ Γ " (at level 9, Σ, Γ at next level).

Reserved Notation " Σ ;;; Γ |- t : T " (at level 50, Γ, t, T at next level).

Variant case_side_conditions `{checker_flags} wf_local_fun typing Σ Γ ci p ps mdecl idecl indices predctx :=
| case_side_info
    (eq_npars : mdecl.(ind_npars) = ci.(ci_npar))
    (wf_pred : wf_predicate mdecl idecl p)
    (cons : consistent_instance_ext Σ (ind_universes mdecl) p.(puinst))
    (wf_pctx : wf_local_fun Σ (Γ ,,, predctx))

    (conv_pctx : eq_context_upto_names p.(pcontext) (ind_predicate_context ci.(ci_ind) mdecl idecl))
    (allowed_elim : is_allowed_elimination Σ idecl.(ind_kelim) ps)
    (elim_relevance : isSortRel ps ci.(ci_relevance))
    (ind_inst : ctx_inst (typing Σ) Γ (p.(pparams) ++ indices)
                         (List.rev (subst_instance p.(puinst)
                                                   (ind_params mdecl ,,, ind_indices idecl : context))))
    (not_cofinite : isCoFinite mdecl.(ind_finite) = false).

Variant case_branch_typing `{checker_flags} wf_local_fun typing Σ Γ (ci:case_info) p ps mdecl idecl ptm  brs :=
| case_branch_info
    (wf_brs : wf_branches idecl brs)
    (brs_ty :
       All2i (fun i cdecl br =>

                eq_context_upto_names br.(bcontext) (cstr_branch_context ci mdecl cdecl) ×
                let brctxty := case_branch_type ci.(ci_ind) mdecl idecl p br ptm i cdecl in
                (wf_local_fun Σ (Γ ,,, brctxty.1) ×
                ((typing Σ (Γ ,,, brctxty.1) br.(bbody) (brctxty.2)) ×
                (typing Σ (Γ ,,, brctxty.1) brctxty.2 (tSort ps)))))
             0 idecl.(ind_ctors) brs).

Variant primitive_typing_hyps `{checker_flags}
  (typing : forall (Σ : global_env_ext) (Γ : context), term -> term -> Type)
  Σ Γ : prim_val term -> Type :=
| prim_int_hyps i : primitive_typing_hyps typing Σ Γ (primInt; primIntModel i)
| prim_float_hyps f : primitive_typing_hyps typing Σ Γ (primFloat; primFloatModel f)
| prim_string_hyps s : primitive_typing_hyps typing Σ Γ (primString; primStringModel s)
| prim_array_hyps a
  (wfl : wf_universe Σ (Universe.make' a.(array_level)))
  (hty : typing Σ Γ a.(array_type) (tSort (sType (Universe.make' a.(array_level)))))
  (hdef : typing Σ Γ a.(array_default) a.(array_type))
  (hvalue : All (fun x => typing Σ Γ x a.(array_type)) a.(array_value)) :
  primitive_typing_hyps typing Σ Γ (primArray; primArrayModel a).

Equations prim_type (p : prim_val term) (cst : kername) : term :=
prim_type (primInt; _) cst := tConst cst [];
prim_type (primFloat; _) cst := tConst cst [];
prim_type (primString; _) cst := tConst cst [];
prim_type (primArray; primArrayModel a) cst := tApp (tConst cst [a.(array_level)]) a.(array_type).

Inductive typing `{checker_flags} (Σ : global_env_ext) (Γ : context) : term -> term -> Type :=
| type_Rel : forall n decl,
    wf_local Σ Γ ->
    nth_error Γ n = Some decl ->
    Σ ;;; Γ |- tRel n : lift0 (S n) decl.(decl_type)

| type_Sort : forall s,
    wf_local Σ Γ ->
    wf_sort Σ s ->
    Σ ;;; Γ |- tSort s : tSort (Sort.super s)

| type_Prod : forall na A B s1 s2,
    lift_typing typing Σ Γ (j_vass_s na A s1) ->
    Σ ;;; Γ ,, vass na A |- B : tSort s2 ->
    Σ ;;; Γ |- tProd na A B : tSort (Sort.sort_of_product s1 s2)

| type_Lambda : forall na A t B,
    lift_typing typing Σ Γ (j_vass na A) ->
    Σ ;;; Γ ,, vass na A |- t : B ->
    Σ ;;; Γ |- tLambda na A t : tProd na A B

| type_LetIn : forall na b B t A,
    lift_typing typing Σ Γ (j_vdef na b B) ->
    Σ ;;; Γ ,, vdef na b B |- t : A ->
    Σ ;;; Γ |- tLetIn na b B t : tLetIn na b B A

| type_App : forall t na A B s u,

    Σ ;;; Γ |- tProd na A B : tSort s ->
    Σ ;;; Γ |- t : tProd na A B ->
    Σ ;;; Γ |- u : A ->
    Σ ;;; Γ |- tApp t u : B{0 := u}

| type_Const : forall cst u decl,
    wf_local Σ Γ ->
    declared_constant Σ cst decl ->
    consistent_instance_ext Σ decl.(cst_universes) u ->
    Σ ;;; Γ |- tConst cst u : decl.(cst_type)@[u]

| type_Ind : forall ind u mdecl idecl,
    wf_local Σ Γ ->
    declared_inductive Σ ind mdecl idecl ->
    consistent_instance_ext Σ mdecl.(ind_universes) u ->
    Σ ;;; Γ |- tInd ind u : idecl.(ind_type)@[u]

| type_Construct : forall ind i u mdecl idecl cdecl,
    wf_local Σ Γ ->
    declared_constructor Σ (ind, i) mdecl idecl cdecl ->
    consistent_instance_ext Σ mdecl.(ind_universes) u ->
    Σ ;;; Γ |- tConstruct ind i u : type_of_constructor mdecl cdecl (ind, i) u

| type_Case : forall ci p c brs indices ps mdecl idecl,
    let predctx := case_predicate_context ci.(ci_ind) mdecl idecl p in
    let ptm := it_mkLambda_or_LetIn predctx p.(preturn) in
    declared_inductive Σ ci.(ci_ind) mdecl idecl ->
    Σ ;;; Γ ,,, predctx |- p.(preturn) : tSort ps ->
    Σ ;;; Γ |- c : mkApps (tInd ci.(ci_ind) p.(puinst)) (p.(pparams) ++ indices) ->
    case_side_conditions (fun Σ Γ => wf_local Σ Γ) typing Σ Γ ci p ps
                         mdecl idecl indices predctx  ->
    case_branch_typing (fun Σ Γ => wf_local Σ Γ) typing Σ Γ ci p ps
                        mdecl idecl ptm brs ->
    Σ ;;; Γ |- tCase ci p c brs : mkApps ptm (indices ++ [c])

| type_Proj : forall p c u mdecl idecl cdecl pdecl args,
    declared_projection Σ p mdecl idecl cdecl pdecl ->
    Σ ;;; Γ |- c : mkApps (tInd p.(proj_ind) u) args ->
    #|args| = ind_npars mdecl ->
    Σ ;;; Γ |- tProj p c : subst0 (c :: List.rev args) pdecl.(proj_type)@[u]

| type_Fix : forall mfix n decl,
    wf_local Σ Γ ->
    fix_guard Σ Γ mfix ->
    nth_error mfix n = Some decl ->
    All (on_def_type (lift_typing1 (typing Σ)) Γ) mfix ->
    All (on_def_body (lift_typing1 (typing Σ)) (fix_context mfix) Γ) mfix ->
    wf_fixpoint Σ mfix ->
    Σ ;;; Γ |- tFix mfix n : decl.(dtype)

| type_CoFix : forall mfix n decl,
    wf_local Σ Γ ->
    cofix_guard Σ Γ mfix ->
    nth_error mfix n = Some decl ->
    All (on_def_type (lift_typing1 (typing Σ)) Γ) mfix ->
    All (on_def_body (lift_typing1 (typing Σ)) (fix_context mfix) Γ) mfix ->
    wf_cofixpoint Σ mfix ->
    Σ ;;; Γ |- tCoFix mfix n : decl.(dtype)

| type_Prim p prim_ty cdecl :
    wf_local Σ Γ ->
    primitive_constant Σ (prim_val_tag p) = Some prim_ty ->
    declared_constant Σ prim_ty cdecl ->
    primitive_invariants (prim_val_tag p) cdecl ->
    primitive_typing_hyps typing Σ Γ p ->
    Σ ;;; Γ |- tPrim p : prim_type p prim_ty

| type_Cumul : forall t A B s,
    Σ ;;; Γ |- t : A ->
    Σ ;;; Γ |- B : tSort s ->
    Σ ;;; Γ |- A <=s B ->
    Σ ;;; Γ |- t : B

where " Σ ;;; Γ |- t : T " := (typing Σ Γ t T)
and "'wf_local' Σ Γ " := (All_local_env (lift_typing1 (typing Σ)) Γ).

Module PCUICTypingDef <: EnvironmentTyping.Typing PCUICTerm PCUICEnvironment PCUICTermUtils PCUICEnvTyping PCUICConversion PCUICConversionParSpec.

  Definition typing := @typing.

End PCUICTypingDef.

Definition wf `{checker_flags} := on_global_env cumulSpec0 (lift_typing typing).
Notation on_contexts_length := All2_fold_length.
Import MetaRocq.PCUIC.Syntax.PCUICOnFreeVars.
Import Stdlib.ssr.ssreflect.
Import Stdlib.ssr.ssrbool.
Import Equations.Prop.Equations.
Import Stdlib.Classes.CRelationClasses.
Import Equations.Type.Relation_Properties.

Definition ws_term P := { t : term | on_free_vars P t }.
Definition ws_term_proj {P} (t : ws_term P) : term.
admit.
Defined.
Coercion ws_term_proj : ws_term >-> term.

Definition ws_context P := { t : context | on_free_vars_ctx P t }.

Notation closed_context := (ws_context xpred0).
Notation open_term Γ := (ws_term (shiftnP #|Γ| xpred0)).
Definition ws_context_proj' {P} (t : ws_context P) : list context_decl.
Admitted.
Coercion ws_context_proj' : ws_context >-> list.

Definition ws_red1 Σ P (Γ : ws_context P) (t u : ws_term (shiftnP #|Γ| P)) :=
  red1 Σ Γ t u.

Definition ws_red Σ P (Γ : ws_context P) := clos_refl_trans (ws_red1 Σ P Γ).

Definition ws_pair :=
  ∑ Γ : ws_context xpred0, ws_term (shiftnP #|Γ| xpred0).

Section RedConfluence.
  Context {cf : checker_flags}.
  Context {Σ : global_env_ext} (wfΣ : wf Σ).
Definition red1_rel_alpha : relation ws_pair.
exact (relation_disjunction (A:=ws_pair) (fun '(Γ; t) '(Δ; u) => (red1 Σ Γ t u * (Γ = Δ)))%type
     (relation_disjunction (A:=ws_pair)
        (fun '(Γ; t) '(Δ; u) => ((red1_ctx Σ Γ Δ * (t = u :> term))))
        (fun '(Γ; t) '(Δ; u) => ((eq_context_upto_names Γ Δ * (t = u :> term)))))%type).
Defined.

  Lemma red_ws_red (Γ : closed_context) (x y : ws_term (shiftnP #|Γ| xpred0)) :
    red Σ Γ x y -> ws_red Σ xpred0 Γ x y.
Admitted.
Definition transport_ws_term {n m : nat} (t : ws_term (shiftnP n xpred0)) (eq : n = m) : ws_term (shiftnP m xpred0).
Admitted.
Definition red_ctx_alpha : relation context.
exact (All2_fold (fun Γ _ => All_decls_alpha (red Σ Γ))).
Defined.

  Instance red_ctx_alpha_refl : Reflexive red_ctx_alpha.
Admitted.

  Lemma ws_red_refl_irrel P (Γ : ws_context P) (x y : ws_term (shiftnP #|Γ| P)) :
    x = y :> term ->
    ws_red Σ P Γ x y.
Admitted.

  Lemma clos_rt_red1_alpha_out x y :
    clos_refl_trans red1_rel_alpha x y ->
    ∑ redctx : red_ctx_alpha x.π1 y.π1,
      ws_red Σ xpred0 x.π1 x.π2 (transport_ws_term y.π2 (symmetry (All2_fold_length redctx))).
  Proof using wfΣ.
    intros H.
    eapply clos_rt_rt1n_iff in H.
    induction H.
    -
 unshelve eexists.
reflexivity.
eapply ws_red_refl_irrel => //.
    -
 destruct x as [Γ t], y as [Δ u], z as [Δ' u']; simpl in *.
      destruct IHclos_refl_trans_1n.
      red in r.
destruct r.
      *
 destruct p.
subst.
exists x.
        transitivity u; auto.
        now eapply red_ws_red.
      *
 destruct t as [t ht], u as [u hu];
        move: r; case; move => [] r eq; noconf eq.
🛠️ Intermediate Coq File (useful for debugging if minimization did not go as far as you wanted) (truncated to 6.0KiB; full 90KiB file on GitHub Actions Artifacts under tmp.v)
(* -*- mode: coq; coq-prog-args: ("-emacs" "-q" "-w" "-deprecated-native-compiler-option" "-native-compiler" "no" "-coqlib" "/github/workspace/builds/coq/coq-failing/_install_ci/lib/coq//" "-R" "/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/utils/theories" "MetaRocq.Utils" "-R" "/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/common/theories" "MetaRocq.Common" "-R" "/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/pcuic/theories" "MetaRocq.PCUIC" "-Q" "/github/workspace/cwd" "Top" "-Q" "/github/workspace/builds/coq/coq-failing/_install_ci/lib/coq///user-contrib/Equations" "Equations" "-Q" "/github/workspace/builds/coq/coq-failing/_install_ci/lib/coq///user-contrib/Ltac2" "Ltac2" "-Q" "/github/workspace/builds/coq/coq-failing/_install_ci/lib/coq///user-contrib/Stdlib" "Stdlib" "-top" "MetaRocq.PCUIC.PCUICConfluence") -*- *)
(* File reduced by coq-bug-minimizer from original input, then from 3959 lines to 98 lines, then from 111 lines to 3187 lines, then from 3191 lines to 96 lines, then from 107 lines to 1813 lines, then from 1818 lines to 359 lines, then from 369 lines to 1502 lines, then from 1506 lines to 524 lines, then from 535 lines to 2595 lines *)
(* coqc version 9.1+alpha compiled with OCaml 4.14.2
   coqtop version runner-t7b1znuaq-project-4504-concurrent-2:/builds/coq/coq/_build/default,(HEAD detached at cdd06d0a2f356e) (cdd06d0a2f356e0c02e2d20356562b7deae4cf15)
   Expected coqc runtime on this file: 0.000 sec *)
Require Coq.Init.Ltac.
Module Export AdmitTactic.
Module Import LocalFalse.
Inductive False : Prop := .
End LocalFalse.
Axiom proof_admitted : False.
Import Coq.Init.Ltac.
Tactic Notation "admit" := abstract case proof_admitted.
End AdmitTactic.
Require MetaRocq.PCUIC.PCUICReduction.
Require Corelib.BinNums.IntDef.
Require Corelib.BinNums.NatDef.
Require Corelib.BinNums.PosDef.
Require Corelib.Classes.CMorphisms.
Require Corelib.Classes.CRelationClasses.
Require Corelib.Classes.Morphisms.
Require Corelib.Classes.Morphisms_Prop.
Require Corelib.Classes.RelationClasses.
Require Corelib.Classes.SetoidTactics.
Require Corelib.Floats.FloatAxioms.
Require Corelib.Floats.FloatOps.
Require Corelib.Floats.PrimFloat.
Require Corelib.Floats.SpecFloat.
Require Corelib.Init.Byte.
Require Corelib.Init.Decimal.
Require Corelib.Init.Hexadecimal.
Require Corelib.Init.Ltac.
Require Corelib.Init.Nat.
Require Corelib.Init.Sumbool.
Require Corelib.Init.Wf.
Require Corelib.Lists.ListDef.
Require Corelib.Numbers.BinNums.
Require Corelib.Numbers.Cyclic.Int63.CarryType.
Require Corelib.Numbers.Cyclic.Int63.PrimInt63.
Require Corelib.Numbers.Cyclic.Int63.Sint63Axioms.
Require Corelib.Numbers.Cyclic.Int63.Uint63Axioms.
Require Corelib.Program.Basics.
Require Corelib.Program.Tactics.
Require Corelib.Program.Utils.
Require Corelib.Program.Wf.
Require Corelib.Relations.Relation_Definitions.
Require Corelib.Setoids.Setoid.
Require Corelib.Strings.PrimString.
Require Corelib.Strings.PrimStringAxioms.
Require Corelib.extraction.Extraction.
Require Corelib.ssr.ssrbool.
Require Corelib.ssr.ssreflect.
Require Corelib.ssr.ssrfun.
Require MetaRocq.Utils.MREquality.
Require MetaRocq.Utils.MRSquash.
Require MetaRocq.Utils.MRTactics.DestructHyps.
Require MetaRocq.Utils.MRTactics.FindHyp.
Require MetaRocq.Utils.MRTactics.Head.
Require MetaRocq.Utils.MRTactics.SpecializeBy.
Require MetaRocq.Utils.MRTactics.SplitInContext.
Require MetaRocq.Utils.MRTactics.Zeta1.
Require Stdlib.Classes.DecidableClass.
Require Stdlib.Logic.Decidable.
Require Stdlib.Logic.EqdepFacts.
Require Stdlib.Logic.FunctionalExtensionality.
Require Stdlib.Logic.HLevelsBase.
Require Stdlib.Program.Syntax.
Require Stdlib.Sets.Relations_1.
Require Stdlib.Unicode.Utf8_core.
Require Stdlib.Wellfounded.Inverse_Image.
Require Stdlib.micromega.ZifyClasses.
Require Stdlib.setoid_ring.Algebra_syntax.
Require Ltac2.Init.
Require MetaRocq.Utils.MRTactics.UniquePose.
Require Stdlib.BinNums.IntDef.
Require Stdlib.BinNums.NatDef.
Require Stdlib.BinNums.PosDef.
Require Stdlib.Classes.CMorphisms.
Require Stdlib.Classes.CRelationClasses.
Require Stdlib.Classes.Morphisms.
Require Stdlib.Classes.Morphisms_Prop.
Require Stdlib.Classes.RelationClasses.
Require Stdlib.Classes.SetoidTactics.
Require Stdlib.Floats.FloatAxioms.
Require Stdlib.Floats.FloatOps.
Require Stdlib.Floats.PrimFloat.
Require Stdlib.Floats.SpecFloat.
Require Stdlib.Init.Byte.
Require Stdlib.Init.Decimal.
Require Stdlib.Init.Hexadecimal.
Require Stdlib.Init.Nat.
Require Stdlib.Init.Sumbool.
Require Stdlib.Init.Wf.
Require Stdlib.Lists.ListDef.
Require Stdlib.Logic.Eqdep.
Require Stdlib.Logic.Eqdep_dec.
Require Stdlib.Logic.ProofIrrelevanceFacts.
Require Stdlib.Numbers.BinNums.
Require Stdlib.Numbers.Cyclic.Int63.CarryType.
Require Stdlib.Numbers.Cyclic.Int63.PrimInt63.
Require Stdlib.Numbers.Cyclic.Int63.Sint63Axioms.
Require Stdlib.Numbers.Cyclic.Int63.Uint63Axioms.
Require Stdlib.Program.Basics.
Require Stdlib.Program.Tactics.
Require Stdlib.Program.Utils.
Require Stdlib.Program.Wf.
Require Stdlib.Relations.Relation_Definitions.
Require Stdlib.Setoids.Setoid.
Require Stdlib.Strings.PrimString.
Require Stdlib.Strings.PrimStringAxioms.
Require Stdlib.Unicode.Utf8.
Require Stdlib.Wellfounded.Well_Ordering.
Require Stdlib.extraction.Extraction.
Require Stdlib.ssr.ssrbool.
Require Stdlib.ssr.ssreflect.
Require Stdlib.ssr.ssrfun.
Require Equations.Init.
Require Ltac2.Message.
Require Ltac2.Std.
Require MetaRocq.Utils.MRTactics.DestructHead.
Require MetaRocq.Utils.MRTactics.SpecializeAllWays.
Require Stdlib.Bool.Bool.
Require Stdlib.Logic.JMeq.
Require Stdlib.Logic.ProofIrrelevance.
Require Stdlib.Relations.Relation_Operators.
Require Stdlib.Wellfounded.Inclusion.
Require Equations.Prop.SigmaNotations.
Require Equations.Signature.
Require Ltac2.Control.
Require MetaRocq.Utils.MRTactics.GeneralizeOverHoles.
Require Stdlib.Program.Combinators.
Require Stdlib.Relations.Operators_Properties.
Require Stdlib.Wellfounded.Disjoint_Union.
Require Stdlib.Wellfounded.Transitive_Closure.
Require Equations.CoreTactics.
Require Stdlib.PArith.BinPosDef.
Require Stdlib.Relations.Relations.
Require Stdlib.Wellfounded.Unio
🛠️ 📜 Intermediate Coq File log (useful for debugging if minimization did not go as far as you wanted) (truncated to last 2.0KiB; full 3.4KiB file on GitHub Actions Artifacts under tmp.log)
see
<https://github.com/coq/stdlib/blob/master/theories/Vectors/Vector.v>.
[warn-library-file-stdlib-vector,stdlib-vector,warn-library-file,user-warn,default]
File "/tmp/tmp5ddyed5q/MetaRocq/PCUIC/PCUICConfluence.v", line 258, characters 0-32:
Warning: Using Vector.t is known to be technically difficult, see
<https://github.com/coq/stdlib/blob/master/theories/Vectors/Vector.v>.
[warn-library-file-stdlib-vector,stdlib-vector,warn-library-file,user-warn,default]
File "/tmp/tmp5ddyed5q/MetaRocq/PCUIC/PCUICConfluence.v", line 259, characters 0-30:
Warning: Using Vector.t is known to be technically difficult, see
<https://github.com/coq/stdlib/blob/master/theories/Vectors/Vector.v>.
[warn-library-file-stdlib-vector,stdlib-vector,warn-library-file,user-warn,default]
File "/tmp/tmp5ddyed5q/MetaRocq/PCUIC/PCUICConfluence.v", line 265, characters 0-31:
Warning: Library File Stdlib.Vectors.Bvector is deprecated since 8.20.
Consider [list bool] instead. See <https://github.com/coq/stdlib/blob/master/theories/Vectors/Vector.v> for details. Please open an issue if you would like to keep using Bvector.
[deprecated-library-file-since-8.20,deprecated-since-8.20,deprecated-library-file,deprecated,default]
File "/tmp/tmp5ddyed5q/MetaRocq/PCUIC/PCUICConfluence.v", line 313, characters 0-34:
Warning: Library File Stdlib
10000
.ZArith.ZArith_base is deprecated since 9.0.
use ZArith instead
[deprecated-library-file-since-9.0,deprecated-since-9.0,deprecated-library-file,deprecated,default]
File "/tmp/tmp5ddyed5q/MetaRocq/PCUIC/PCUICConfluence.v", line 405, characters 0-50:
Warning: Notation "_ =1 _" was already used in scope type_scope.
[notation-overridden,parsing,default]
File "/tmp/tmp5ddyed5q/MetaRocq/PCUIC/PCUICConfluence.v", line 405, characters 0-50:
Warning: Notation "_ =2 _" was already used in scope type_scope.
[notation-overridden,parsing,default]
File "/tmp/tmp5ddyed5q/MetaRocq/PCUIC/PCUICConfluence.v", line 1378, characters 42-73:
Error: The LHS of addnP_shiftnP
    (addnP _ (shiftnP _ _))
does not match any subterm of the goal
📜 Build Log (contains the Coq error message) (truncated to last 8.0KiB; full 7.0MiB file on GitHub Actions Artifacts under build.log)
t-minimizer.3BOBeHtupa
MINIMIZER_DEBUG: files: 
make[2]: Leaving directory '/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/template-rocq'
# Ensure the cmxs is built before the loader file 
make -f Makefile.plugin gen-src/metarocq_template_plugin.cmxs
make[2]: Entering directory '/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/template-rocq'
MINIMIZER_DEBUG_EXTRA: coqc: /github/workspace/builds/coq/coq-failing/_install_ci/bin///rocq
MINIMIZER_DEBUG_EXTRA: original invocation: c --print-version 
MINIMIZER_DEBUG_EXTRA: new invocation: /github/workspace/builds/coq/coq-failing/_install_ci/bin/rocq.orig c --print-version 
MINIMIZER_DEBUG_EXTRA: coqpath: 
MINIMIZER_DEBUG_EXTRA: ocamlpath: /github/workspace/builds/coq/coq-failing/_build_ci/metarocq/template-rocq/:/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/safechecker-plugin/src:/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/erasure-plugin/src:/github/workspace/builds/coq/coq-failing/_install_ci/lib:
MINIMIZER_DEBUG_EXTRA: pwd: PWD=/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/template-rocq
MINIMIZER_DEBUG_EXTRA: exec: /github/workspace/builds/coq/coq-failing/_install_ci/bin/rocq.orig c --print-version 
MINIMIZER_DEBUG_EXTRA: coqlib: Warning: Deprecated environment variable COQLIB, use ROCQLIB instead.
/github/workspace/builds/coq/coq-failing/_install_ci/lib/coq//
MINIMIZER_DEBUG: info: /tmp/tmp-coqbot-minimizer.v4rXB91qMQ
MINIMIZER_DEBUG: files: 
make[2]: 'gen-src/metarocq_template_plugin.cmxs' is up to date.
make[2]: Leaving directory '/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/template-rocq'
make -f Makefile.plugin
make[2]: Entering directory '/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/template-rocq'
MINIMIZER_DEBUG_EXTRA: coqc: /github/workspace/builds/coq/coq-failing/_install_ci/bin///rocq
MINIMIZER_DEBUG_EXTRA: original invocation: c --print-version 
MINIMIZER_DEBUG_EXTRA: new invocation: /github/workspace/builds/coq/coq-failing/_install_ci/bin/rocq.orig c --print-version 
MINIMIZER_DEBUG_EXTRA: coqpath: 
MINIMIZER_DEBUG_EXTRA: ocamlpath: /github/workspace/builds/coq/coq-failing/_build_ci/metarocq/template-rocq/:/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/safechecker-plugin/src:/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/erasure-plugin/src:/github/workspace/builds/coq/coq-failing/_install_ci/lib:
MINIMIZER_DEBUG_EXTRA: pwd: PWD=/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/template-rocq
MINIMIZER_DEBUG_EXTRA: exec: /github/workspace/builds/coq/coq-failing/_install_ci/bin/rocq.orig c --print-version 
MINIMIZER_DEBUG_EXTRA: coqlib: Warning: Deprecated environment variable COQLIB, use ROCQLIB instead.
/github/workspace/builds/coq/coq-failing/_install_ci/lib/coq//
MINIMIZER_DEBUG: info: /tmp/tmp-coqbot-minimizer.pvnFRJJ81I
MINIMIZER_DEBUG: files: 
MINIMIZER_DEBUG_EXTRA: coqc: /github/workspace/builds/coq/coq-failing/_install_ci/bin/////rocq
MINIMIZER_DEBUG_EXTRA: original invocation: c --print-version 
MINIMIZER_DEBUG_EXTRA: new invocation: /github/workspace/builds/coq/coq-failing/_install_ci/bin/rocq.orig c --print-version 
MINIMIZER_DEBUG_EXTRA: coqpath: 
MINIMIZER_DEBUG_EXTRA: ocamlpath: /github/workspace/builds/coq/coq-failing/_build_ci/metarocq/template-rocq/:/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/safechecker-plugin/src:/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/erasure-plugin/src:/github/workspace/builds/coq/coq-failing/_install_ci/lib:
MINIMIZER_DEBUG_EXTRA: pwd: PWD=/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/template-rocq
MINIMIZER_DEBUG_EXTRA: exec: /github/workspace/builds/coq/coq-failing/_install_ci/bin/rocq.orig c --print-version 
MINIMIZER_DEBUG_EXTRA: coqlib: Warning: Deprecated environment variable COQLIB, use ROCQLIB instead.
/github/workspace/builds/coq/coq-failing/_install_ci/lib/coq//
MINIMIZER_DEBUG: info: /tmp/tmp-coqbot-minimizer.YlqT44BYza
MINIMIZER_DEBUG: files: 
MINIMIZER_DEBUG_EXTRA: coqc: /github/workspace/builds/coq/coq-failing/_install_ci/bin/////rocq
MINIMIZER_DEBUG_EXTRA: original invocation: c --print-version 
MINIMIZER_DEBUG_EXTRA: new invocation: /github/workspace/builds/coq/coq-failing/_install_ci/bin/rocq.orig c --print-version 
MINIMIZER_DEBUG_EXTRA: coqpath: 
MINIMIZER_DEBUG_EXTRA: ocamlpath: /github/workspace/builds/coq/coq-failing/_build_ci/metarocq/template-rocq/:/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/safechecker-plugin/src:/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/erasure-plugin/src:/github/workspace/builds/coq/coq-failing/_install_ci/lib:
MINIMIZER_DEBUG_EXTRA: pwd: PWD=/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/template-rocq
MINIMIZER_DEBUG_EXTRA: exec: /github/workspace/builds/coq/coq-failing/_install_ci/bin/rocq.orig c --print-version 
MINIMIZER_DEBUG_EXTRA: coqlib: Warning: Deprecated environment variable COQLIB, use ROCQLIB instead.
/github/workspace/builds/coq/coq-failing/_install_ci/lib/coq//
MINIMIZER_DEBUG: info: /tmp/tmp-coqbot-minimizer.FTU8Xtcgr5
MINIMIZER_DEBUG: files: 
make[3]: Nothing to be done for 'real-all'.
MINIMIZER_DEBUG_EXTRA: coqc: /github/workspace/builds/coq/coq-failing/_install_ci/bin/////rocq
MINIMIZER_DEBUG_EXTRA: original invocation: c --print-version 
MINIMIZER_DEBUG_EXTRA: new invocation: /github/workspace/builds/coq/coq-failing/_install_ci/bin/rocq.orig c --print-version 
MINIMIZER_DEBUG_EXTRA: coqpath: 
MINIMIZER_DEBUG_EXTRA: ocamlpath: /github/workspace/builds/coq/coq-failing/_build_ci/metarocq/template-rocq/:/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/safechecker-plugin/src:/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/erasure-plugin/src:/github/workspace/builds/coq/coq-failing/_install_ci/lib:
MINIMIZER_DEBUG_EXTRA: pwd: PWD=/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/template-rocq
MINIMIZER_DEBUG_EXTRA: exec: /github/workspace/builds/coq/coq-failing/_install_ci/bin/rocq.orig c --print-version 
MINIMIZER_DEBUG_EXTRA: coqlib: Warning: Deprecated environment variable COQLIB, use ROCQLIB instead.
/github/workspace/builds/coq/coq-failing/_install_ci/lib/coq//
MINIMIZER_DEBUG: info: /tmp/tmp-coqbot-minimizer.Pj5oe5wksg
MINIMIZER_DEBUG: files: 
make[2]: Leaving directory '/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/template-rocq'
make[1]: Leaving directory '/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/template-rocq'
File "./theories/PCUICConfluence.v", line 3649, characters 47-49:
Error: Cannot infer the implicit parameter A of eq whose type is 
"Type" in
environment:
cf : checker_flags
Σ : global_env_ext
wfΣ : wf Σ
Γ : closed_context
t : term
ht : is_open_term Γ t
Δ : closed_context
u : term
hu : is_open_term Δ u
Δ' : closed_context
u' : open_term Δ'
H : clos_refl_trans_1n red1_rel_alpha (Δ; exist u hu) (Δ'; u')
x : red_ctx_alpha Δ Δ'
w :
  ws_red Σ xpred0 Δ (exist u hu)
    (transport_ws_term u' (symmetry (on_contexts_length x)))
r : red1_ctx Σ Γ Δ
eq : exist t ht = exist u hu

Command exited with non-zero status 1
theories/PCUICConfluence.vo (real: 46.54, user: 46.12, sys: 0.41, mem: 2429588 ko)
make[3]: *** [Makefile.rocq:814: theories/PCUICConfluence.vo] Error 1
make[3]: *** [theories/PCUICConfluence.vo] Deleting file 'theories/PCUICConfluence.glob'
make[2]: *** [Makefile.rocq:412: all] Error 2
make[2]: Leaving directory '/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/pcuic'
make[1]: *** [Makefile:11: coq] Error 2
make[1]: Leaving directory '/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/pcuic'
make: *** [Makefile:149: pcuic] Error 2
+ code=2
+ printf '\n%s exit code: %s\n' metarocq 2
+ '[' metarocq '!=' stdlib_test ']'
+ echo 'Aggregating timing log...'
Aggregating timing log...
+ echo

+ tools/make-one-time-file.py --real metarocq.log
    Time |   Peak Mem | File Name            
---------------------------------------------
0m46.54s | 2429588 ko | Total Time / Peak Mem
---------------------------------------------
0m46.54s | 2429588 ko | PCUICConfluence.vo   
+ '[' '' ']'
+ exit 2
/github/workspace/builds/coq /github/workspace
::endgroup::
📜 🔎 Minimization Log (truncated to last 8.0KiB; full 4.5MiB file on GitHub Actions Artifacts under bug.log)
v", line 257, characters 0-31:
Warning: Library File Stdlib.Vectors.Bvector is deprecated since 8.20.
Consider [list bool] instead. See <https://github.com/coq/stdlib/blob/master/theories/Vectors/Vector.v> for details. Please open an issue if you would like to keep using Bvector.
[deprecated-library-file-since-8.20,deprecated-since-8.20,deprecated-library-file,deprecated,default]
File "/tmp/tmpthoq41e7/MetaRocq/PCUIC/PCUICConfluence.v", line 305, characters 0-34:
Warning: Library File Stdlib.ZArith.ZArith_base is deprecated since 9.0.
use ZArith instead
[deprecated-library-file-since-9.0,deprecated-since-9.0,deprecated-library-file,deprecated,default]
File "/tmp/tmpthoq41e7/MetaRocq/PCUIC/PCUICConfluence.v", line 400, characters 7-20:
Warning: Coq.Init.Ltac has been replaced by Corelib.Init.Ltac.
[deprecated-dirpath-Coq,deprecated-since-9.0,deprecated,default]
File "/tmp/tmpthoq41e7/MetaRocq/PCUIC/PCUICConfluence.v", line 1238, characters 88-94:
Error:
In environment
cf : checker_flags
Σ : global_env_ext
wfΣ : wf Σ
x : ws_pair
y : ws_pair
redctx : red_ctx_alpha x.π1 y.π1
The term "redctx" has type "red_ctx_alpha x.π1 y.π1"
while it is expected to have type "All2_fold ?P ?Γ ?Γ'".


�[93mIntermediate code not saved.�[0m
Failed to do everything at once; trying one at a time.
Admitting definitions unsuccessful.
No successful changes.

I will now attempt to admit lemmas with admit. Defined with Proof using

Non-fatal error: Failed to admit lemmas and preserve the error.  
The new error was:
Deprecated environment variable COQCORELIB, use ROCQRUNTIMELIB instead.
Warning: Deprecated environment variable COQCORELIB,
use ROCQRUNTIMELIB instead.
[deprecated-coq-env-var,deprecated-since-9.0,deprecated,default]
File "/tmp/tmpy_plq2hi/MetaRocq/PCUIC/PCUICConfluence.v", line 235, characters 0-27:
Warning: Alternatives to Fin.t are available, see
<https://github.com/coq/stdlib/blob/master/theories/Vectors/Fin.v>.
[warn-library-file-stdlib-vector,stdlib-vector,warn-library-file,user-warn,default]
File "/tmp/tmpy_plq2hi/MetaRocq/PCUIC/PCUICConfluence.v", line 238, characters 0-33:
Warning: Using Vector.t is known to be technically difficult, see
<https://github.com/coq/stdlib/blob/master/theories/Vectors/Vector.v>.
[warn-library-file-stdlib-vector,stdlib-vector,warn-library-file,user-warn,default]
File "/tmp/tmpy_plq2hi/MetaRocq/PCUIC/PCUICConfluence.v", line 248, characters 0-34:
Warning: Using Vector.t is known to be technically difficult, see
<https://github.com/coq/stdlib/blob/master/theories/Vectors/Vector.v>.
[warn-library-file-stdlib-vector,stdlib-vector,warn-library-file,user-warn,default]
File "/tmp/tmpy_plq2hi/MetaRocq/PCUIC/PCUICConfluence.v", line 250, characters 0-32:
Warning: Using Vector.t is known to be technically difficult, see
<https://github.com/coq/stdlib/blob/master/theories/Vectors/Vector.v>.
[warn-library-file-stdlib-vector,stdlib-vector,warn-library-file,user-warn,default]
File "/tmp/tmpy_plq2hi/MetaRocq/PCUIC/PCUICConfluence.v", line 251, characters 0-30:
Warning: Using Vector.t is known to be technically difficult, see
<https://github.com/coq/stdlib/blob/master/theories/Vectors/Vector.v>.
[warn-library-file-stdlib-vector,stdlib-vector,warn-library-file,user-warn,default]
File "/tmp/tmpy_plq2hi/MetaRocq/PCUIC/PCUICConfluence.v", line 257, characters 0-31:
Warning: Library File Stdlib.Vectors.Bvector is deprecated since 8.20.
Consider [list bool] instead. See <https://github.com/coq/stdlib/blob/master/theories/Vectors/Vector.v> for details. Please open an issue if you would like to keep using Bvector.
[deprecated-library-file-since-8.20,deprecated-since-8.20,deprecated-library-file,deprecated,default]
File "/tmp/tmpy_plq2hi/MetaRocq/PCUIC/PCUICConfluence.v", line 305, characters 0-34:
Warning: Library File Stdlib.ZArith.ZArith_base is deprecated since 9.0.
use ZArith instead
[deprecated-library-file-since-9.0,deprecated-since-9.0,deprecated-library-file,deprecated,default]
File "/tmp/tmpy_plq2hi/MetaRocq/PCUIC/PCUICConfluence.v", line 400, characters 7-20:
Warning: Coq.Init.Ltac has been replaced by Corelib.Init.Ltac.
[deprecated-dirpath-Coq,deprecated-since-9.0,deprecated,default]
Error: The section RedConfluence needs to be closed.


�[93mIntermediate code not saved.�[0m
Failed to do everything at once; trying one at a time.
Admitting lemmas unsuccessful.
No successful changes.

I will now attempt to admit definitions with admit. Defined with Proof using

Non-fatal error: Failed to admit definitions and preserve the error.  
The new error was:
Deprecated environment variable COQCORELIB, use ROCQRUNTIMELIB instead.
Warning: Deprecated environment variable COQCORELIB,
use ROCQRUNTIMELIB instead.
[deprecated-coq-env-var,deprecated-since-9.0,deprecated,default]
File "/tmp/tmpugym0z2f/MetaRocq/PCUIC/PCUICConfluence.v", line 235, characters 0-27:
Warning: Alternatives to Fin.t are available, see
<https://github.com/coq/stdlib/blob/master/theories/Vectors/Fin.v>.
[warn-library-file-stdlib-vector,stdlib-vector,warn-library-file,user-warn,default]
File "/tmp/tmpugym0z2f/MetaRocq/PCUIC/PCUICConfluence.v", line 238, characters 0-33:
Warning: Using Vector.t is known to be technically difficult, see
<https://github.com/coq/stdlib/blob/master/theories/Vectors/Vector.v>.
[warn-library-file-stdlib-vector,stdlib-vector,warn-library-file,user-warn,default]
File "/tmp/tmpugym0z2f/MetaRocq/PCUIC/PCUICConfluence.v", line 248, characters 0-34:
Warning: Using Vector.t is known to be technically difficult, see
<https://github.com/coq/stdlib/blob/master/theories/Vectors/Vector.v>.
[warn-library-file-stdlib-vector,stdlib-vector,warn-library-file,user-warn,default]
File "/tmp/tmpugym0z2f/MetaRocq/PCUIC/PCUICConfluence.v", line 250, characters 0-32:
Warning: Using Vector.t is known to be technically difficult, see
<https://github.com/coq/stdlib/blob/master/theories/Vectors/Vector.v>.
[warn-library-file-stdlib-vector,stdlib-vector,warn-library-file,user-warn,default]
File "/tmp/tmpugym0z2f/MetaRocq/PCUIC/PCUICConfluence.v", line 251, characters 0-30:
Warning: Using Vector.t is known to be technically difficult, see
<https://github.com/coq/stdlib/blob/master/theories/Vectors/Vector.v>.
[warn-library-file-stdlib-vector,stdlib-vector,warn-library-file,user-warn,default]
File "/tmp/tmpugym0z2f/MetaRocq/PCUIC/PCUICConfluence.v", line 257, characters 0-31:
Warning: Library File Stdlib.Vectors.Bvector is deprecated since 8.20.
Consider [list bool] instead. See <https://github.com/coq/stdlib/blob/master/theories/Vectors/Vector.v> for details. Please open an issue if you would like to keep using Bvector.
[deprecated-library-file-since-8.20,deprecated-since-8.20,deprecated-library-file,deprecated,default]
File "/tmp/tmpugym0z2f/MetaRocq/PCUIC/PCUICConfluence.v", line 305, characters 0-34:
Warning: Library File Stdlib.ZArith.ZArith_base is deprecated since 9.0.
use ZArith instead
[deprecated-library-file-since-9.0,deprecated-since-9.0,deprecated-library-file,deprecated,default]
File "/tmp/tmpugym0z2f/MetaRocq/PCUIC/PCUICConfluence.v", line 400, characters 7-20:
Warning: Coq.Init.Ltac has been replaced by Corelib.Init.Ltac.
[deprecated-dirpath-Coq,deprecated-since-9.0,deprecated,default]
File "/tmp/tmpugym0z2f/MetaRocq/PCUIC/PCUICConfluence.v", line 1240, characters 88-94:
Error:
In environment
cf : checker_flags
Σ : global_env_ext
wfΣ : wf Σ
x : ws_pair
y : ws_pair
redctx : red_ctx_alpha x.π1 y.π1
The term "redctx" has type "red_ctx_alpha x.π1 y.π1"
while it is expected to have type "All2_fold ?P ?Γ ?Γ'".


�[93mIntermediate code not saved.�[0m
Failed to do everything at once; trying one at a time.
Admitting definitions unsuccessful.
No successful changes.

I will now attempt to add Proof using lines
�[92m
Adding Proof using lines successful.�[0m
Failed to do everything at once; trying one at a time.
Adding Proof using lines unsuccessful.
No successful changes.

I will now attempt to export modules
Module exportation successful

I will now attempt to split imports and exports
Import/Export splitting successful

I will now attempt to split := definitions
One-line definition splitting successful

I will now attempt to remove all lines, one at a time

If you have any comments on your experience of the minimizer, please share them in a reply (possibly tagging @JasonGross).
If you believe there's a bug in the bug minimizer, please report it on the bug minimizer issue tracker.

cc @JasonGross

Copy link
Contributor
coqbot-app bot commented May 27, 2025
Minimization interrupted by timeout, being automatically continued. Partially Minimized File /home/runner/work/run-coq-bug-minimizer/run-coq-bug-minimizer/builds/coq/coq-failing/_build_ci/metarocq/pcuic/theories/PCUICConfluence.v in 5h 15m 6s (from ci-metarocq) (interrupted by timeout, being automatically continued) (full log on GitHub Actions - verbose log)
⭐ ⏱️ Partially Minimized Coq File (timeout) (truncated to first and last 32KiB; full 44KiB file on GitHub Actions Artifacts under bug.v)
(* -*- mode: coq; coq-prog-args: ("-emacs" "-q" "-w" "-deprecated-native-compiler-option" "-native-compiler" "no" "-coqlib" "/github/workspace/builds/coq/coq-failing/_install_ci/lib/coq//" "-R" "/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/utils/theories" "MetaRocq.Utils" "-R" "/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/common/theories" "MetaRocq.Common" "-R" "/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/pcuic/theories" "MetaRocq.PCUIC" "-Q" "/github/workspace/cwd" "Top" "-Q" "/github/workspace/builds/coq/coq-failing/_install_ci/lib/coq///user-contrib/Equations" "Equations" "-Q" "/github/workspace/builds/coq/coq-failing/_install_ci/lib/coq///user-contrib/Ltac2" "Ltac2" "-Q" "/github/workspace/builds/coq/coq-failing/_install_ci/lib/coq///user-contrib/Stdlib" "Stdlib" "-top" "Top.bug_01") -*- *)
(* File reduced by coq-bug-minimizer from original input, then from 3959 lines to 98 lines, then from 111 lines to 3187 lines, then from 3191 lines to 96 lines, then from 107 lines to 1813 lines, then from 1818 lines to 359 lines, then from 369 lines to 1502 lines, then from 1506 lines to 524 lines, then from 535 lines to 3221 lines, then from 3222 lines to 656 lines, then from 667 lines to 2894 lines, then from 2900 lines to 656 lines, then from 667 lines to 1321 lines, then from 1327 lines to 874 lines, then from 883 lines to 675 lines, then from 686 lines to 2746 lines, then from 2745 lines to 687 lines, then from 698 lines to 3155 lines, then from 3155 lines to 745 lines, then from 756 lines to 1586 lines, then from 1589 lines to 869 lines, then from 880 lines to 2395 lines, then from 2394 lines to 885 lines, then from 895 lines to 2754 lines, then from 2755 lines to 1157 lines *)
(* coqc version 9.1+alpha compiled with OCaml 4.14.2
   coqtop version runner-t7b1znuaq-project-4504-concurrent-2:/builds/coq/coq/_build/default,(HEAD detached at cdd06d0a2f356e) (cdd06d0a2f356e0c02e2d20356562b7deae4cf15)
   Expected coqc runtime on this file: 2.016 sec *)
Require MetaRocq.PCUIC.utils.PCUICPrimitive.
Axiom proof_admitted : False.
Tactic Notation "admit" := abstract case proof_admitted.
Import MetaRocq.Utils.utils.
Export MetaRocq.Common.Primitive.
Export MetaRocq.Common.Universes.
Export MetaRocq.Common.BasicAst.
Export MetaRocq.Common.Environment.
Export MetaRocq.PCUIC.utils.PCUICPrimitive.


Record predicate {term} := mk_predicate {
  pparams : list term; 
  puinst : Instance.t; 
  pcontext : list (context_decl term);
    
  preturn : term;  }.
Arguments predicate : clear implicits.

Section map_predicate_k.
  Context {term : Type}.
  Context (uf : Instance.t -> Instance.t).
  Context (f : nat -> term -> term).

  Definition map_predicate_k k (p : predicate term) :=
    {| pparams := map (f k) p.(pparams);
        puinst := uf p.(puinst);
        pcontext := p.(pcontext);
        preturn := f (#|p.(pcontext)| + k) p.(preturn) |}.

  Definition test_predicate_k (instp : Instance.t -> bool)
    (p : nat -> term -> bool) k (pred : predicate term) :=
    instp pred.(puinst) && forallb (p k) pred.(pparams) &&
    test_context_k p #|pred.(pparams)| pred.(pcontext) &&
    p (#|pred.(pcontext)| + k) pred.(preturn).

End map_predicate_k.

Section Branch.
  Context {term : Type}.
  
  Record branch := mk_branch {
    bcontext : list (context_decl term);
    
    bbody : term;  }.

  Definition test_branch_k (pred : predicate term) (p : nat -> term -> bool) k (b : branch) :=
    test_context_k p #|pred.(pparams)| b.(bcontext) && p (#|b.(bcontext)| + k) b.(bbody).

End Branch.
Arguments branch : clear implicits.

Section map_branch_k.
  Context {term term' : Type}.
  Context (f : nat -> term -> term').
  Context (g : list (BasicAst.context_decl term) -> list (BasicAst.context_decl term')).
  Definition map_branch_k k (b : branch term) :=
  {| bcontext := g b.(bcontext);
     bbody := f (#|b.(bcontext)| + k) b.(bbody) |}.
End map_branch_k.

Notation map_branches_k f h k brs :=
  (List.map (map_branch_k f h k) brs).

Notation test_branches_k p test k brs :=
  (List.forallb (test_branch_k p test k) brs).

Inductive term :=
| tRel (n : nat)
| tVar (i : ident) 
| tEvar (n : nat) (l : list term)
| tSort (u : sort)
| tProd (na : aname) (A B : term)
| tLambda (na : aname) (A t : term)
| tLetIn (na : aname) (b B t : term) 
| tApp (u v : term)
| tConst (k : kername) (ui : Instance.t)
| tInd (ind : induc
3D11
tive) (ui : Instance.t)
| tConstruct (ind : inductive) (n : nat) (ui : Instance.t)
| tCase (indn : case_info) (p : predicate term) (c : term) (brs : list (branch term))
| tProj (p : projection) (c : term)
| tFix (mfix : mfixpoint term) (idx : nat)
| tCoFix (mfix : mfixpoint term) (idx : nat)
| tPrim (prim : prim_val term).

Fixpoint mkApps t us :=
  match us with
  | nil => t
  | u :: us => mkApps (tApp t u) us
  end.

Definition isLambda t :=
  match t with
  | tLambda _ _ _ => true
  | _ => false
  end.



Fixpoint lift n k t : term :=
  match t with
  | tRel i => tRel (if Nat.leb k i then (n + i) else i)
  | tEvar ev args => tEvar ev (List.map (lift n k) args)
  | tLambda na T M => tLambda na (lift n k T) (lift n (S k) M)
  | tApp u v => tApp (lift n k u) (lift n k v)
  | tProd na A B => tProd na (lift n k A) (lift n (S k) B)
  | tLetIn na b t b' => tLetIn na (lift n k b) (lift n k t) (lift n (S k) b')
  | tCase ind p c brs =>
    let p' := map_predicate_k id (lift n) k p in
    let brs' := map_branches_k (lift n) id k brs in
    tCase ind p' (lift n k c) brs'
  | tProj p c => tProj p (lift n k c)
  | tFix mfix idx =>
    let k' := List.length mfix + k in
    let mfix' := List.map (map_def (lift n k) (lift n k')) mfix in
    tFix mfix' idx
  | tCoFix mfix idx =>
    let k' := List.length mfix + k in
    let mfix' := List.map (map_def (lift n k) (lift n k')) mfix in
    tCoFix mfix' idx
  | tPrim p => tPrim (map_prim (lift n k) p)
  | x => x
  end.

Notation lift0 n := (lift n 0).



Fixpoint subst s k u :=
  match u with
  | tRel n =>
    if Nat.leb k n then
      match nth_error s (n - k) with
      | Some b => lift0 k b
      | None => tRel (n - List.length s)
      end
    else tRel n
  | tEvar ev args => tEvar ev (List.map (subst s k) args)
  | tLambda na T M => tLambda na (subst s k T) (subst s (S k) M)
  | tApp u v => tApp (subst s k u) (subst s k v)
  | tProd na A B => tProd na (subst s k A) (subst s (S k) B)
  | tLetIn na b ty b' => tLetIn na (subst s k b) (subst s k ty) (subst s (S k) b')
  | tCase ind p c brs =>
    let p' := map_predicate_k id (subst s) k p in
    let brs' := map_branches_k (subst s) id k brs in
    tCase ind p' (subst s k c) brs'
  | tProj p c => tProj p (subst s k c)
  | tFix mfix idx =>
    let k' := List.length mfix + k in
    let mfix' := List.map (map_def (subst s k) (subst s k')) mfix in
    tFix mfix' idx
  | tCoFix mfix idx =>
    let k' := List.length mfix + k in
    let mfix' := List.map (map_def (subst s k) (subst s k')) mfix in
    tCoFix mfix' idx
  | tPrim p => tPrim (map_prim (subst s k) p)
  | x => x
  end.


Notation subst0 t := (subst t 0).
Definition subst1 t k u := subst [t] k u.
Notation "M { j := N }" := (subst1 N j M) (at level 10, right associativity).

Fixpoint closedn k (t : term) : bool :=
  match t with
  | tRel i => Nat.ltb i k
  | tEvar ev args => List.forallb (closedn k) args
  | tLambda _ T M | tProd _ T M => closedn k T && closedn (S k) M
  | tApp u v => closedn k u && closedn k v
  | tLetIn na b t b' => closedn k b && closedn k t && closedn (S k) b'
  | tCase ind p c brs =>
    let p' := test_predicate_k (fun _ => true) closedn k p in
    let brs' := test_branches_k p closedn k brs in
    p' && closedn k c && brs'
  | tProj p c => closedn k c
  | tFix mfix idx =>
    let k' := List.length mfix + k in
    List.forallb (test_def (closedn k) (closedn k')) mfix
  | tCoFix mfix idx =>
    let k' := List.length mfix + k in
    List.forallb (test_def (closedn k) (closedn k')) mfix
  | tPrim p => test_prim (closedn k) p
  | _ => true
  end.

Fixpoint noccur_between k n (t : term) : bool :=
  match t with
  | tRel i => Nat.ltb i k || Nat.leb (k + n) i
  | tEvar ev args => List.forallb (noccur_between k n) args
  | tLambda _ T M | tProd _ T M => noccur_between k n T && noccur_between (S k) n M
  | tApp u v => noccur_between k n u && noccur_between k n v
  | tLetIn na b t b' => noccur_between k n b && noccur_between k n t && noccur_between (S k) n b'
  | tCase ind p c brs =>
    let p' := test_predicate_k (fun _ => true) (fun k' => noccur_between k' n) k p in
    let brs' := test_branches_k p (fun k => noccur_between k n) k brs in
    p' && noccur_between k n c && brs'
  | tProj p c => noccur_between k n c
  | tFix mfix idx =>
    let k' := List.length mfix + k in
    List.forallb (test_def (noccur_between k n) (noccur_between k' n)) mfix
  | tCoFix mfix idx =>
    let k' := List.length mfix + k in
    List.forallb (test_def (noccur_between k n) (noccur_between k' n)) mfix
  | tPrim p => test_prim (noccur_between k n) p
  | _ => true
  end.
#[global]
Instance subst_instance_constr : UnivSubst term.
Admitted.

Module PCUICTerm <: Term.

  Definition term := term.

  Definition tRel := tRel.
  Definition tSort := tSort.
  Definition tProd := tProd.
  Definition tLambda := tLambda.
  Definition tLetIn := tLetIn.
  Definition tInd := tInd.
  Definition tProj := tProj.
  Definition mkApps := mkApps.

  Definition lift := lift.
  Definition subst := subst.
  Definition closedn := closedn.
  Definition noccur_between := noccur_between.
  Definition subst_instance_constr := subst_instance.
End PCUICTerm.


Module PCUICEnvironment := Environment PCUICTerm.
Export PCUICEnvironment.




Fixpoint destArity Γ (t : term) :=
  match t with
  | tProd na t b => destArity (Γ ,, vass na t) b
  | tLetIn na b b_ty b' => destArity (Γ ,, vdef na b b_ty) b'
  | tSort s => Some (Γ, s)
  | _ => None
  end.


Definition inds ind u (l : list one_inductive_body) :=
  let fix aux n :=
      match n with
      | 0 => []
      | S n => tInd (mkInd ind n) u :: aux n
      end
  in aux (List.length l).

Module PCUICTermUtils <: TermUtils PCUICTerm PCUICEnvironment.

Definition destArity := destArity.
Definition inds := inds.

End PCUICTermUtils.

Module PCUICEnvTyping := EnvironmentTyping.EnvTyping PCUICTerm PCUICEnvironment PCUICTermUtils.


Module PCUICConversion := EnvironmentTyping.Conversion PCUICTerm PCUICEnvironment PCUICTermUtils PCUICEnvTyping.

Module PCUICLookup := EnvironmentTyping.Lookup PCUICTerm PCUICEnvironment.
Include PCUICLookup.

Module PCUICGlobalMaps := EnvironmentTyping.GlobalMaps
  PCUICTerm
  PCUICEnvironment
  PCUICTermUtils
  PCUICEnvTyping
  PCUICConversion
  PCUICLookup
.
Include PCUICGlobalMaps.

Fixpoint decompose_app_rec (t : term) l :=
  match t with
  | tApp f a => decompose_app_rec f (a :: l)
  | _ => (t, l)
  end.

Definition decompose_app t := decompose_app_rec t [].

Definition isConstruct_app t :=
  match fst (decompose_app t) with
  | tConstruct _ _ _ => true
  | _ => false
  end.
Fixpoint decompose_prod_assum (Γ : context) (t : term) : context * term.
Admitted.

Coercion ci_ind : case_info >-> inductive.

Definition ind_predicate_context ind mdecl idecl : context :=
  let ictx := (expand_lets_ctx mdecl.(ind_params) idecl.(ind_indices)) in
  let indty := mkApps (tInd ind (abstract_instance mdecl.(ind_universes)))
    (to_extended_list (smash_context [] mdecl.(ind_params) ,,, ictx)) in
  let inddecl :=
    {| decl_name :=
      {| binder_name := nNamed (ind_name idecl); binder_relevance := idecl.(ind_relevance) |};
       decl_body := None;
       decl_type := indty |}
  in (inddecl :: ictx).

Definition inst_case_context params puinst (pctx : context) :=
  subst_context (List.rev params) 0 (subst_instance puinst pctx).

Definition inst_case_predicate_context (p : predicate term) :=
  inst_case_context p.(pparams) p.(puinst) p.(pcontext).

Definition inst_case_branch_context (p : predicate term) (br : branch term) :=
  inst_case_context p.(pparams) p.(puinst) br.(bcontext).

Definition iota_red npar p args br :=
  subst (List.rev (List.skipn npar args)) 0
    (expand_lets (inst_case_branch_context p br) (bbody br)).

Definition pre_case_predicate_context_gen ind mdecl idecl params puinst : context :=
  inst_case_context params puinst (ind_predicate_context ind mdecl idecl).

Definition case_predicate_context_gen ind mdecl idecl params puinst pctx :=
  map2 set_binder_name pctx (pre_case_predicate_context_gen ind mdecl idecl params puinst).

Definition case_predicate_context ind mdecl idecl p : context :=
  case_predicate_context_gen ind mdecl idecl p.(pparams) p.(puinst) (forget_types p.(pcontext)).

Definition cstr_branch_context ind mdecl cdecl : context :=
  expand_lets_ctx mdecl.(ind_params)
    (subst_context (inds (inductive_mind ind) (abstract_instance mdecl.(ind_universes))
       mdecl.(ind_bodies)) #|mdecl.(ind_params)|
      cdecl.(cstr_args)).

Definition pre_case_branch_context_gen ind mdecl cdecl params puinst : context :=
  inst_case_context params puinst (cstr_branch_context ind mdecl cdecl).

Definition case_branch_context_gen ind mdecl params puinst pctx cdecl :=
  map2 set_binder_name pctx (pre_case_branch_context_gen ind mdecl cdecl params puinst).

Definition case_branch_type_gen ind mdecl (idecl : one_inductive_body) params puinst bctx ptm i cdecl : context * term :=
  let cstr := tConstruct ind i puinst in
  let args := to_extended_list cdecl.(cstr_args) in
  let cstrapp := mkApps cstr (map (lift0 #|cdecl.(cstr_args)|) params ++ args) in
  let brctx := case_branch_context_gen ind mdecl params puinst bctx cdecl in
  let upars := subst_instance puinst mdecl.(ind_params) in
  let indices :=
    (map (subst (List.rev params) #|cdecl.(cstr_args)|)
      (map (expand_lets_k upars #|cdecl.(cstr_args)|)
        (map (subst (inds (inductive_mind ind) puinst mdecl.(ind_bodies))
                    (#|mdecl.(ind_params)| + #|cdecl.(cstr_args)|))
          (map (subst_instance puinst) cdecl.(cstr_indices))))) in
  let ty := mkApps (lift0 #|cdecl.(cstr_args)| ptm) (indices ++ [cstrapp]) in
  (brctx, ty).

Definition case_branch_type ind mdecl idecl p (b : branch term) ptm i cdecl : context * term :=
  case_branch_type_gen ind mdecl idecl p.(pparams) p.(puinst) (forget_types b.(bcontext)) ptm i cdecl.

Definition idecl_binder idecl :=
  {| decl_name :=
    {| binder_name := nNamed idecl.(ind_name);
        binder_relevance := idecl.(ind_relevance) |};
     decl_body := None;
     decl_type := idecl.(ind_type) |}.

Definition wf_predicate_gen mdecl idecl (pparams : list term) (pcontext : list aname) : Prop :=
  let decl := idecl_binder idecl in
  (#|pparams| = mdecl.(ind_npars)) /\
  (Forall2 (fun na decl => eq_binder_annot na decl.(decl_name))
    pcontext (decl :: idecl.(ind_indices))).

Definition wf_predicate mdecl idecl (p : predicate term) : Prop :=
  wf_predicate_gen mdecl idecl p.(pparams) (forget_types p.(pcontext)).

Definition wf_branch_gen cdecl (bctx : list aname) : Prop :=
  (Forall2 (fun na decl => eq_binder_annot na decl.(decl_name))
    bctx cdecl.(cstr_args)).

Definition w
F438
f_branch cdecl (b : branch term) : Prop :=
  wf_branch_gen cdecl (forget_types b.(bcontext)).

Definition wf_branches idecl (brs : list (branch term)) : Prop :=
  Forall2 wf_branch idecl.(ind_ctors) brs.

Definition fix_subst (l : mfixpoint term) :=
  let fix aux n :=
      match n with
      | 0 => []
      | S n => tFix l n :: aux n
      end
  in aux (List.length l).

Definition unfold_fix (mfix : mfixpoint term) (idx : nat) :=
  match List.nth_error mfix idx with
  | Some d => Some (d.(rarg), subst0 (fix_subst mfix) d.(dbody))
  | None => None
  end.

Definition cofix_subst (l : mfixpoint term) :=
  let fix aux n :=
      match n with
      | 0 => []
      | S n => tCoFix l n :: aux n
      end
  in aux (List.length l).

Definition unfold_cofix (mfix : mfixpoint term) (idx : nat) :=
  match List.nth_error mfix idx with
  | Some d => Some (d.(rarg), subst0 (cofix_subst mfix) d.(dbody))
  | None => None
  end.

Definition is_constructor n ts :=
  match List.nth_error ts n with
  | Some a => isConstruct_app a
  | None => false
  end.
Definition cmp_universe_instance (cmp_univ : Universe.t -> Universe.t -> Prop) : Instance.t -> Instance.t -> Prop.
Admitted.

Definition cmp_universe_variance (cmp_univ : conv_pb -> Universe.t -> Universe.t -> Prop) pb v u u' :=
  match v with
  | Variance.Irrelevant => True
  | Variance.Covariant => on_rel (cmp_univ pb) Universe.make' u u'
  | Variance.Invariant => on_rel (cmp_univ Conv) Universe.make' u u'
  end.

Definition cmp_universe_instance_variance cmp_univ pb v u u' :=
  Forall3 (cmp_universe_variance cmp_univ pb) v u u'.

Definition global_variance_gen lookup gr napp :=
  match gr with
  | IndRef ind =>
    match lookup_inductive_gen lookup ind with
    | Some (mdecl, idecl) =>
      match destArity [] idecl.(ind_type) with
      | Some (ctx, _) => if (context_assumptions ctx) <=? napp then
          match mdecl.(ind_variance) with
          | Some var => Variance var
          | None => AllEqual
          end
        else AllEqual
      | None => AllEqual
      end
    | None => AllEqual
    end
  | ConstructRef ind k =>
    match lookup_constructor_gen lookup ind k with
    | Some (mdecl, idecl, cdecl) =>
      if (cdecl.(cstr_arity) + mdecl.(ind_npars))%nat <=? napp then

        AllIrrelevant
      else AllEqual
    | _ => AllEqual
    end
  | _ => AllEqual
  end.

Definition cmp_opt_variance cmp_univ pb v :=
  match v with
  | AllEqual => cmp_universe_instance (cmp_univ Conv)
  | AllIrrelevant => fun l l' => #|l| = #|l'|
  | Variance v => fun u u' => cmp_universe_instance (cmp_univ Conv) u u' \/ cmp_universe_instance_variance cmp_univ pb v u u'
  end.

Definition cmp_global_instance_gen Σ cmp_universe pb gr napp :=
  cmp_opt_variance cmp_universe pb (global_variance_gen Σ gr napp).

Notation cmp_global_instance Σ := (cmp_global_instance_gen (lookup_env Σ)).

Inductive eq_decl_upto_names : context_decl -> context_decl -> Type :=
  | compare_vass {na na' T} :
    eq_binder_annot na na' -> eq_decl_upto_names (vass na T) (vass na' T)
  | compare_vdef {na na' b T} :
    eq_binder_annot na na' -> eq_decl_upto_names (vdef na b T) (vdef na' b T).

Notation eq_context_upto_names := (All2 eq_decl_upto_names).
Import Stdlib.ssr.ssrbool.

Definition shiftnP k p i :=
  (i <? k) || p (i - k).
Fixpoint on_free_vars (p : nat -> bool) (t : term) : bool.
Admitted.

Definition on_free_vars_decl P d :=
  test_decl (on_free_vars P) d.

Definition on_free_vars_ctx P ctx :=
  alli (fun k => (on_free_vars_decl (shiftnP k P))) 0 (List.rev ctx).

Notation is_open_term Γ := (on_free_vars (shiftnP #|Γ| xpred0)).
Notation is_closed_context := (on_free_vars_ctx xpred0).
Definition set_preturn (p : predicate term) (pret' : term) : predicate term.
Admitted.
Definition set_pparams (p : predicate term) (pars' : list term) : predicate term.
Admitted.
Definition on_one_decl (P : term -> term -> Type)
  (d : context_decl) (d' : context_decl) : Type.
Admitted.

Section OnOne_local_2.
  Context (P : forall (Γ : context), context_decl -> context_decl -> Type).

  Inductive OnOne2_local_env : context -> context -> Type :=
  | onone2_localenv_cons_abs Γ na na' t t' :
      P Γ (vass na t) (vass na' t') ->
      OnOne2_local_env (Γ ,, vass na t) (Γ ,, vass na' t')
  | onone2_localenv_def Γ na na' b b' t t' :
      P Γ (vdef na b t) (vdef na' b' t') ->
      OnOne2_local_env (Γ ,, vdef na b t) (Γ ,, vdef na' b' t')
  | onone2_localenv_cons_tl Γ Γ' d :
      OnOne2_local_env Γ Γ' ->
      OnOne2_local_env (Γ ,, d) (Γ' ,, d).
End OnOne_local_2.
Arguments exist {_ _} _ _.
Import Equations.Type.Relation.

Reserved Notation " Σ ;;; Γ |- t ⇝ u " (at level 50, Γ, t, u at next level).

Definition set_array_default (ar : array_model term) (v : term) :=
  {| array_level := ar.(array_level);
     array_default := v;
     array_type := ar.(array_type);
     array_value := ar.(array_value) |}.

Definition set_array_type (ar : array_model term) (v : term) :=
  {| array_level := ar.(array_level);
     array_default := ar.(array_default);
     array_type := v;
     array_value := ar.(array_value) |}.

Definition set_array_value (ar : array_model term) (v : list term) :=
  {| array_level := ar.(array_level);
     array_default := ar.(array_default);
     array_type := ar.(array_type);
     array_value := v |}.

Inductive red1 (Σ : global_env) (Γ : context) : term -> term -> Type :=

| red_beta na t b a :
  Σ ;;; Γ |- tApp (tLambda na t b) a ⇝ b {0 := a}

| red_zeta na b t b' :
  Σ ;;; Γ |- tLetIn na b t b' ⇝ b' {0 := b}

| red_rel i body :
    option_map decl_body (nth_error Γ i) = Some (Some body) ->
    Σ ;;; Γ |- tRel i ⇝ lift0 (S i) body

| red_iota ci c u args p brs br :
    nth_error brs c = Some br ->
    #|args| = (ci.(ci_npar) + context_assumptions br.(bcontext))%nat ->
    Σ ;;; Γ |- tCase ci p (mkApps (tConstruct ci.(ci_ind) c u) args) brs
        ⇝ iota_red ci.(ci_npar) p args br

| red_fix mfix idx args narg fn :
    unfold_fix mfix idx = Some (narg, fn) ->
    is_constructor narg args = true ->
    Σ ;;; Γ |- mkApps (tFix mfix idx) args ⇝ mkApps fn args

| red_cofix_case ip p mfix idx args narg fn brs :
    unfold_cofix mfix idx = Some (narg, fn) ->
    Σ ;;; Γ |- tCase ip p (mkApps (tCoFix mfix idx) args) brs ⇝
         tCase ip p (mkApps fn args) brs

| red_cofix_proj p mfix idx args narg fn :
    unfold_cofix mfix idx = Some (narg, fn) ->
    Σ ;;; Γ |- tProj p (mkApps (tCoFix mfix idx) args) ⇝ tProj p (mkApps fn args)

| red_delta c decl body (isdecl : declared_constant Σ c decl) u :
    decl.(cst_body) = Some body ->
    Σ ;;; Γ |- tConst c u ⇝ subst_instance u body

| red_proj p args u arg:
    nth_error args (p.(proj_npars) + p.(proj_arg)) = Some arg ->
    Σ ;;; Γ |- tProj p (mkApps (tConstruct p.(proj_ind) 0 u) args) ⇝ arg

| abs_red_l na M M' N : Σ ;;; Γ |- M ⇝ M' -> Σ ;;; Γ |- tLambda na M N ⇝ tLambda na M' N
| abs_red_r na M M' N : Σ ;;; Γ ,, vass na N |- M ⇝ M' -> Σ ;;; Γ |- tLambda na N M ⇝ tLambda na N M'

| letin_red_def na b t b' r : Σ ;;; Γ |- b ⇝ r -> Σ ;;; Γ |- tLetIn na b t b' ⇝ tLetIn na r t b'
| letin_red_ty na b t b' r : Σ ;;; Γ |- t ⇝ r -> Σ ;;; Γ |- tLetIn na b t b' ⇝ tLetIn na b r b'
| letin_red_body na b t b' r : Σ ;;; Γ ,, vdef na b t |- b' ⇝ r -> Σ ;;; Γ |- tLetIn na b t b' ⇝ tLetIn na b t r

| case_red_param ci p params' c brs :
    OnOne2 (fun t u => Σ ;;; Γ |- t ⇝ u) p.(pparams) params' ->
    Σ ;;; Γ |- tCase ci p c brs ⇝ tCase ci (set_pparams p params') c brs

| case_red_return ci p preturn' c brs :
  Σ ;;; Γ ,,, inst_case_predicate_context p |- p.(preturn) ⇝ preturn' ->
  Σ ;;; Γ |- tCase ci p c brs ⇝ tCase ci (set_preturn p preturn') c brs

| case_red_discr ci p c c' brs :
  Σ ;;; Γ |- c ⇝ c' -> Σ ;;; Γ |- tCase ci p c brs ⇝ tCase ci p c' brs

| case_red_brs ci p c brs brs' :
    OnOne2 (fun br br' =>
      on_Trel_eq (fun t u => Σ ;;; Γ ,,, inst_case_branch_context p br |- t ⇝ u) bbody bcontext br br')
      brs brs' ->
    Σ ;;; Γ |- tCase ci p c brs ⇝ tCase ci p c brs'

| proj_red p c c' : Σ ;;; Γ |- c ⇝ c' -> Σ ;;; Γ |- tProj p c ⇝ tProj p c'

| app_red_l M1 N1 M2 : Σ ;;; Γ |- M1 ⇝ N1 -> Σ ;;; Γ |- tApp M1 M2 ⇝ tApp N1 M2
| app_red_r M2 N2 M1 : Σ ;;; Γ |- M2 ⇝ N2 -> Σ ;;; Γ |- tApp M1 M2 ⇝ tApp M1 N2

| prod_red_l na M1 M2 N1 : Σ ;;; Γ |- M1 ⇝ N1 -> Σ ;;; Γ |- tProd na M1 M2 ⇝ tProd na N1 M2
| prod_red_r na M2 N2 M1 : Σ ;;; Γ ,, vass na M1 |- M2 ⇝ N2 ->
                           Σ ;;; Γ |- tProd na M1 M2 ⇝ tProd na M1 N2

| evar_red ev l l' : OnOne2 (fun t u => Σ ;;; Γ |- t ⇝ u) l l' -> Σ ;;; Γ |- tEvar ev l ⇝ tEvar ev l'

| fix_red_ty mfix0 mfix1 idx :
    OnOne2 (on_Trel_eq (fun t u => Σ ;;; Γ |- t ⇝ u) dtype (fun x => (dname x, dbody x, rarg x))) mfix0 mfix1 ->
    Σ ;;; Γ |- tFix mfix0 idx ⇝ tFix mfix1 idx

| fix_red_body mfix0 mfix1 idx :
    OnOne2 (on_Trel_eq (fun t u => Σ ;;; Γ ,,, fix_context mfix0 |- t ⇝ u) dbody (fun x => (dname x, dtype x, rarg x)))
           mfix0 mfix1 ->
    Σ ;;; Γ |- tFix mfix0 idx ⇝ tFix mfix1 idx

| cofix_red_ty mfix0 mfix1 idx :
    OnOne2 (on_Trel_eq (fun t u => Σ ;;; Γ |- t ⇝ u) dtype (fun x => (dname x, dbody x, rarg x))) mfix0 mfix1 ->
    Σ ;;; Γ |- tCoFix mfix0 idx ⇝ tCoFix mfix1 idx

| cofix_red_body mfix0 mfix1 idx :
    OnOne2 (on_Trel_eq (fun t u => Σ ;;; Γ ,,, fix_context mfix0 |- t ⇝ u) dbody (fun x => (dname x, dtype x, rarg x))) mfix0 mfix1 ->
    Σ ;;; Γ |- tCoFix mfix0 idx ⇝ tCoFix mfix1 idx

| array_red_val arr value :
    OnOne2 (fun t u => Σ ;;; Γ |- t ⇝ u) arr.(array_value) value ->
    Σ ;;; Γ |- tPrim (primArray; primArrayModel arr) ⇝
               tPrim (primArray; primArrayModel (set_array_value arr value))

| array_red_def arr def :
    Σ ;;; Γ |- arr.(array_default) ⇝ def ->
    Σ ;;; Γ |- tPrim (primArray; primArrayModel arr) ⇝
               tPrim (primArray; primArrayModel (set_array_default arr def))

| array_red_type arr ty :
    Σ ;;; Γ |- arr.(array_type) ⇝ ty ->
    Σ ;;; Γ |- tPrim (primArray; primArrayModel arr) ⇝
          tPrim (primArray; primArrayModel (set_array_type arr ty))

where " Σ ;;; Γ |- t ⇝ u " := (red1 Σ Γ t u).

Definition red1_ctx Σ := (OnOne2_local_env (fun Δ => on_one_decl (fun t t' => red1 Σ Δ t t'))).

Definition red Σ Γ := clos_refl_trans (fun t u : term => Σ;;; Γ |- t ⇝ u).
Module Export PCUICCumulativitySpec.
Import MetaRocq.Common.config.

Implicit Types (cf : checker_flags).

Definition cumul_predicate (cumul : context -> term -> term -> Type) cumul_universe Γ p p' :=
  All2 (cumul Γ) p.(pparams) p'.(pparams) ×
  cmp_universe_instance cumul_universe p.(puinst) p'.(puinst) ×
  eq_context_upto_names p.(pcontext) p'.(pcontext) ×
  cumul (Γ ,,, inst_case_predicate_context p) p.(preturn) p'.(preturn).

Definition cumul_branch (cumul_term : context -> term -> term -> Type) Γ p br br' :=
  eq_context_upto_names br.(bcontext) br'.(bcontext) ×
  cumul_term (Γ ,,, inst_case_branch_context p br) br.(bbody) br'.(bbody).

Definition cumul_branches cumul_term Γ p brs brs' := All2 (cumul_branch cumul_term Γ p) brs brs'.

Definition cumul_mfixpoint (cumul_term : context -> term -> term -> Type) Γ mfix mfix' :=
  All2 (fun d d' =>
    cumul_term Γ d.(dtype) d'.(dtype) ×
    cumul_term (Γ ,,, fix_context mfix) d.(dbody) d'.(dbody) ×
    d.(rarg) = d'.(rarg) ×
    eq_binder_annot d.(dname) d'.(dname)
  ) mfix mfix'.

Reserved Notation " Σ ;;; Γ ⊢ t ≤s[ pb ] u" (at level 50, Γ, t, u at next level,
  format "Σ  ;;;  Γ  ⊢  t  ≤s[ pb ]  u").

Definition cumul_Ind_univ {cf} (Σ : global_env_ext) pb i napp :=
  cmp_global_instance Σ (compare_universe Σ) pb (IndRef i) napp.

Definition cumul_Construct_univ {cf} (Σ : global_env_ext) pb  i k napp :=
  cmp_global_instance Σ (compare_universe Σ) pb (ConstructRef i k) napp.
Inductive cumulSpec0 {cf : checker_flags} (Σ : global_env_ext) Γ (pb : conv_pb) : term -> term -> Type :=

| cumul_Trans : forall t u v,
    is_closed_context Γ -> is_open_term Γ u ->
    Σ ;;; Γ ⊢ t ≤s[pb] u ->
    Σ ;;; Γ ⊢ u ≤s[pb] v ->
    Σ ;;; Γ ⊢ t ≤s[pb] v

| cumul_Sym : forall t u,
    Σ ;;; Γ ⊢ t ≤s[Conv] u ->
    Σ ;;; Γ ⊢ u ≤s[pb] t

| cumul_Refl : forall t,
    Σ ;;; Γ ⊢ t ≤s[pb] t

| cumul_Ind : forall i u u' args args',
    cumul_Ind_univ Σ pb i #|args| u u' ->
    All2 (fun t u => Σ ;;; Γ ⊢ t ≤s[Conv] u) args args' ->
    Σ ;;; Γ ⊢ mkApps (tInd i u) args ≤s[pb] mkApps (tInd i u') args'

| cumul_Construct : forall i k u u' args args',
    cumul_Construct_univ Σ pb i k #|args| u u' ->
    All2 (fun t u => Σ ;;; Γ ⊢ t ≤s[Conv] u) args args' ->
    Σ ;;; Γ ⊢ mkApps (tConstruct i k u) args ≤s[pb] mkApps (tConstruct i k u') args'

| cumul_Sort : forall s s',
    compare_sort Σ pb s s' ->
    Σ ;;; Γ ⊢ tSort s ≤s[pb] tSort s'

| cumul_Const : forall c u u',
    cmp_universe_instance (compare_universe Σ Conv) u u' ->
    Σ ;;; Γ ⊢ tConst c u ≤s[pb] tConst c u'

| cumul_Evar : forall e args args',
    All2 (fun t u => Σ ;;; Γ ⊢ t ≤s[Conv] u) args args' ->
    Σ ;;; Γ ⊢ tEvar e args ≤s[pb] tEvar e args'

| cumul_App : forall t t' u u',
    Σ ;;; Γ ⊢ t ≤s[pb] t' ->
    Σ ;;; Γ ⊢ u ≤s[Conv] u' ->
    Σ ;;; Γ ⊢ tApp t u ≤s[pb] tApp t' u'

| cumul_Lambda : forall na na' ty ty' t t',
    eq_binder_annot na na' ->
    Σ ;;; Γ ⊢ ty ≤s[Conv] ty' ->
    Σ ;;; Γ ,, vass na ty ⊢ t ≤s[Conv] t' ->
    Σ ;;; Γ ⊢ tLambda na ty t ≤s[pb] tLambda na' ty' t'

| cumul_Prod : forall na na' a a' b b',
    eq_binder_annot na na' ->
    Σ ;;; Γ ⊢ a ≤s[Conv] a' ->
    Σ ;;; Γ ,, vass na a ⊢ b ≤s[pb] b' ->
    Σ ;;; Γ ⊢ tProd na a b ≤s[pb] tProd na' a' b'

| cumul_LetIn : forall na na' t t' ty ty' u u',
    eq_binder_annot na na' ->
    Σ ;;; Γ ⊢ t ≤s[Conv] t' ->
    Σ ;;; Γ ⊢ ty ≤s[Conv] ty' ->
    Σ ;;; Γ ,, vdef na t ty ⊢ u ≤s[Conv] u' ->
    Σ ;;; Γ ⊢ tLetIn na t ty u ≤s[pb] tLetIn na' t' ty' u'

| cumul_Case indn : forall p p' c c' brs brs',
    cumul_predicate (fun Γ t u => Σ ;;; Γ ⊢ t ≤s[Conv] u) (compare_universe Σ Conv) Γ p p' ->
    Σ ;;; Γ ⊢ c ≤s[Conv] c' ->
    cumul_branches (fun Γ t u => Σ ;;; Γ ⊢ t ≤s[Conv] u) Γ p brs brs' ->
    Σ ;;; Γ ⊢ tCase indn p c brs ≤s[pb] tCase indn p' c' brs'

| cumul_Proj : forall p c c',
    Σ ;;; Γ ⊢ c ≤s[Conv] c' ->
    Σ ;;; Γ ⊢ tProj p c ≤s[pb] tProj p c'

| cumul_Fix : forall mfix mfix' idx,
    cumul_mfixpoint (fun Γ t u => Σ ;;; Γ ⊢ t ≤s[Conv] u) Γ mfix mfix' ->
    Σ ;;; Γ ⊢ tFix mfix idx ≤s[pb] tFix mfix' idx

| cumul_CoFix : forall mfix mfix' idx,
    cumul_mfixpoint (fun Γ t u => Σ ;;; Γ ⊢ t ≤s[Conv] u) Γ mfix mfix' ->
    Σ ;;; Γ ⊢ tCoFix mfix idx ≤s[pb] tCoFix mfix' idx

| cumul_Prim p p' :
  onPrims (fun x y => Σ ;;; Γ ⊢ x ≤s[Conv] y) (compare_universe Σ Conv) p p' ->
  Σ ;;; Γ ⊢ tPrim p ≤s[pb] tPrim p'

| cumul_beta : forall na t b a,
    Σ ;;; Γ ⊢ tApp (tLambda na t b) a ≤s[pb] b {0 := a}

| cumul_zeta : forall na b t b',
    Σ ;;; Γ ⊢ tLetIn na b t b' ≤s[pb] b' {0 := b}

| cumul_rel i body :
    option_map decl_body (nth_error Γ i) = Some (Some body) ->
    Σ ;;; Γ ⊢ tRel i ≤s[pb] lift0 (S i) body

| cumul_iota : forall ci c u args p brs br,
    nth_error brs c = Some br ->
    #|args| = (ci.(ci_npar) + context_assumptions br.(bcontext))%nat ->
    Σ ;;; Γ ⊢ tCase ci p (mkApps (tConstruct ci.(ci_ind) c u) args) brs  ≤s[pb] iota_red ci.(ci_npar) p args br

| cumul_fix : forall mfix idx args narg fn,
    unfold_fix mfix idx = Some (narg, fn) ->
    is_constructor narg args = true ->
    Σ ;;; Γ ⊢ mkApps (tFix mfix idx) args ≤s[pb] mkApps fn args

| cumul_cofix_case : forall ip p mfix idx args narg fn brs,
    unfold_cofix mfix idx = Some (narg, fn) ->
    Σ ;;; Γ ⊢ tCase ip p (mkApps (tCoFix mfix idx) args) brs ≤s[pb] tCase ip p (mkApps fn args) brs

| cumul_cofix_proj : forall p mfix idx args narg fn,
    unfold_cofix mfix idx = Some (narg, fn) ->
    Σ ;;; Γ ⊢ tProj p (mkApps (tCoFix mfix idx) args) ≤s[pb] tProj p (mkApps fn args)

| cumul_delta : forall c decl body (isdecl : declared_constant Σ c decl) u,
    decl.(cst_body) = Some body ->
    Σ ;;; Γ ⊢ tConst c u ≤s[pb] body@[u]

| cumul_proj : forall p args u arg,
    nth_error args (p.(proj_npars) + p.(proj_arg)) = Some arg ->
    Σ ;;; Γ ⊢ tProj p (mkApps (tConstruct p.(proj_ind) 0 u) args) ≤s[pb] arg

where " Σ ;;; Γ ⊢ t ≤s[ pb ] u " := (@cumulSpec0 _ Σ Γ pb t u) : type_scope.
Definition cumulSpec `{checker_flags} (Σ : global_env_ext) Γ := cumulSpec0 Σ Γ Cumul.

Notation " Σ ;;; Γ |- t <=s u " := (@cumulSpec _ Σ Γ t u) (at level 50, Γ, t, u at next level).

Module PCUICConversionParSpec <: EnvironmentTyping.ConversionParSig PCUICTerm PCUICEnvironment PCUICTermUtils PCUICEnvTyping.
  Definition cumul_gen := @cumulSpec0.
End PCUICConversionParSpec.

End PCUICCumulativitySpec.
Import MetaRocq.Common.config.

Implicit Types (cf : checker_flags) (Σ : global_env_ext).

Definition type_of_constructor mdecl (cdecl : constructor_body) (c : inductive * nat) (u : list Level.t) :=
  let mind := inductive_mind (fst c) in
  subst0 (inds mind u mdecl.(ind_bodies)) (subst_instance u (cstr_type cdecl)).

Include PCUICEnvTyping.

Inductive FixCoFix : Type := Fix | CoFix.

Class GuardChecker :=
{
  guard : FixCoFix -> global_env_ext -> context -> mfixpoint term -> Prop ;
}.

Axiom guard_checking : GuardChecker.
#[global]
Existing Instance guard_ch

[...]

puinst pctx).

Definition inst_case_predicate_context (p : predicate term) :=
  inst_case_context p.(pparams) p.(puinst) p.(pcontext).

Definition inst_case_branch_context (p : predicate term) (br : branch term) :=
  inst_case_context p.(pparams) p.(puinst) br.(bcontext).

Definition iota_red npar p args br :=
  subst (List.rev (List.skipn npar args)) 0
    (expand_lets (inst_case_branch_context p br) (bbody br)).

Definition pre_case_predicate_context_gen ind mdecl idecl params puinst : context :=
  inst_case_context params puinst (ind_predicate_context ind mdecl idecl).

Definition case_predicate_context_gen ind mdecl idecl params puinst pctx :=
  map2 set_binder_name pctx (pre_case_predicate_context_gen ind mdecl idecl params puinst).

Definition case_predicate_context ind mdecl idecl p : context :=
  case_predicate_context_gen ind mdecl idecl p.(pparams) p.(puinst) (forget_types p.(pcontext)).

Definition cstr_branch_context ind mdecl cdecl : context :=
  expand_lets_ctx mdecl.(ind_params)
    (subst_context (inds (inductive_mind ind) (abstract_instance mdecl.(ind_universes))
       mdecl.(ind_bodies)) #|mdecl.(ind_params)|
      cdecl.(cstr_args)).

Definition pre_case_branch_context_gen ind mdecl cdecl params puinst : context :=
  inst_case_context params puinst (cstr_branch_context ind mdecl cdecl).

Definition case_branch_context_gen ind mdecl params puinst pctx cdecl :=
  map2 set_binder_name pctx (pre_case_branch_context_gen ind mdecl cdecl params puinst).

Definition case_branch_type_gen ind mdecl (idecl : one_inductive_body) params puinst bctx ptm i cdecl : context * term :=
  let cstr := tConstruct ind i puinst in
  let args := to_extended_list cdecl.(cstr_args) in
  let cstrapp := mkApps cstr (map (lift0 #|cdecl.(cstr_args)|) params ++ args) in
  let brctx := case_branch_context_gen ind mdecl params puinst bctx cdecl in
  let upars := subst_instance puinst mdecl.(ind_params) in
  let indices :=
    (map (subst (List.rev params) #|cdecl.(cstr_args)|)
      (map (expand_lets_k upars #|cdecl.(cstr_args)|)
        (map (subst (inds (inductive_mind ind) puinst mdecl.(ind_bodies))
                    (#|mdecl.(ind_params)| + #|cdecl.(cstr_args)|))
          (map (subst_instance puinst) cdecl.(cstr_indices))))) in
  let ty := mkApps (lift0 #|cdecl.(cstr_args)| ptm) (indices ++ [cstrapp]) in
  (brctx, ty).

Definition case_branch_type ind mdecl idecl p (b : branch term) ptm i cdecl : context * term :=
  case_branch_type_gen ind mdecl idecl p.(pparams) p.(puinst) (forget_types b.(bcontext)) ptm i cdecl.

Definition idecl_binder idecl :=
  {| decl_name :=
    {| binder_name := nNamed idecl.(ind_name);
        binder_relevance := idecl.(ind_relevance) |};
     decl_body := None;
     decl_type := idecl.(ind_type) |}.

Definition wf_predicate_gen mdecl idecl (pparams : list term) (pcontext : list aname) : Prop :=
  let decl := idecl_binder idecl in
  (#|pparams| = mdecl.(ind_npars)) /\
  (Forall2 (fun na decl => eq_binder_annot na decl.(decl_name))
    pcontext (decl :: idecl.(ind_indices))).

Definition wf_predicate mdecl idecl (p : predicate term) : Prop :=
  wf_predicate_gen mdecl idecl p.(pparams) (forget_types p.(pcontext)).

Definition wf_branch_gen cdecl (bctx : list aname) : Prop :=
  (Forall2 (fun na decl => eq_binder_annot na decl.(decl_name))
    bctx cdecl.(cstr_args)).

Definition wf_branch cdecl (b : branch term) : Prop :=
  wf_branch_gen cdecl (forget_types b.(bcontext)).

Definition wf_branches idecl (brs : list (branch term)) : Prop :=
  Forall2 wf_branch idecl.(ind_ctors) brs.

Definition fix_subst (l : mfixpoint term) :=
  let fix aux n :=
      match n with
      | 0 => []
      | S n => tFix l n :: aux n
      end
  in aux (List.length l).

Definition unfold_fix (mfix : mfixpoint term) (idx : nat) :=
  match List.nth_error mfix idx with
  | Some d => Some (d.(rarg), subst0 (fix_subst mfix) d.(dbody))
  | None => None
  end.

Definition cofix_subst (l : mfixpoint term) :=
  let fix aux n :=
      match n with
      | 0 => []
      | S n => tCoFix l n :: aux n
      end
  in aux (List.length l).

Definition unfold_cofix (mfix : mfixpoint term) (idx : nat) :=
  match List.nth_error mfix idx with
  | Some d => Some (d.(rarg), subst0 (cofix_subst mfix) d.(dbody))
  | None => None
  end.

Definition is_constructor n ts :=
  match List.nth_error ts n with
  | Some a => isConstruct_app a
  | None => false
  end.
Definition cmp_universe_instance (cmp_univ : Universe.t -> Universe.t -> Prop) : Instance.t -> Instance.t -> Prop.
Admitted.

Definition cmp_universe_variance (cmp_univ : conv_pb -> Universe.t -> Universe.t -> Prop) pb v u u' :=
  match v with
  | Variance.Irrelevant => True
  | Variance.Covariant => on_rel (cmp_univ pb) Universe.make' u u'
  | Variance.Invariant => on_rel (cmp_univ Conv) Universe.make' u u'
  end.

Definition cmp_universe_instance_variance cmp_univ pb v u u' :=
  Forall3 (cmp_universe_variance cmp_univ pb) v u u'.

Definition global_variance_gen lookup gr napp :=
  match gr with
  | IndRef ind =>
    match lookup_inductive_gen lookup ind with
    | Some (mdecl, idecl) =>
      match destArity [] idecl.(ind_type) with
      | Some (ctx, _) => if (context_assumptions ctx) <=? napp then
          match mdecl.(ind_variance) with
          | Some var => Variance var
          | None => AllEqual
          end
        else AllEqual
      | None => AllEqual
      end
    | None => AllEqual
    end
  | ConstructRef ind k =>
    match lookup_constructor_gen lookup ind k with
    | Some (mdecl, idecl, cdecl) =>
      if (cdecl.(cstr_arity) + mdecl.(ind_npars))%nat <=? napp then

        AllIrrelevant
      else AllEqual
    | _ => AllEqual
    end
  | _ => AllEqual
  end.

Definition cmp_opt_variance cmp_univ pb v :=
  match v with
  | AllEqual => cmp_universe_instance (cmp_univ Conv)
  | AllIrrelevant => fun l l' => #|l| = #|l'|
  | Variance v => fun u u' => cmp_universe_instance (cmp_univ Conv) u u' \/ cmp_universe_instance_variance cmp_univ pb v u u'
  end.

Definition cmp_global_instance_gen Σ cmp_universe pb gr napp :=
  cmp_opt_variance cmp_universe pb (global_variance_gen Σ gr napp).

Notation cmp_global_instance Σ := (cmp_global_instance_gen (lookup_env Σ)).

Inductive eq_decl_upto_names : context_decl -> context_decl -> Type :=
  | compare_vass {na na' T} :
    eq_binder_annot na na' -> eq_decl_upto_names (vass na T) (vass na' T)
  | compare_vdef {na na' b T} :
    eq_binder_annot na na' -> eq_decl_upto_names (vdef na b T) (vdef na' b T).

Notation eq_context_upto_names := (All2 eq_decl_upto_names).
Import Stdlib.ssr.ssrbool.

Definition shiftnP k p i :=
  (i <? k) || p (i - k).
Fixpoint on_free_vars (p : nat -> bool) (t : term) : bool.
Admitted.

Definition on_free_vars_decl P d :=
  test_decl (on_free_vars P) d.

Definition on_free_vars_ctx P ctx :=
  alli (fun k => (on_free_vars_decl (shiftnP k P))) 0 (List.rev ctx).

Notation is_open_term Γ := (on_free_vars (shiftnP #|Γ| xpred0)).
Notation is_closed_context := (on_free_vars_ctx xpred0).
Definition set_preturn (p : predicate term) (pret' : term) : predicate term.
Admitted.
Definition set_pparams (p : predicate term) (pars' : list term) : predicate term.
Admitted.
Definition on_one_decl (P : term -> term -> Type)
  (d : context_decl) (d' : context_decl) : Type.
Admitted.

Section OnOne_local_2.
  Context (P : forall (Γ : context), context_decl -> context_decl -> Type).

  Inductive OnOne2_local_env : context -> context -> Type :=
  | onone2_localenv_cons_abs Γ na na' t t' :
      P Γ (vass na t) (vass na' t') ->
      OnOne2_local_env (Γ ,, vass na t) (Γ ,, vass na' t')
  | onone2_localenv_def Γ na na' b b' t t' :
      P Γ (vdef na b t) (vdef na' b' t') ->
      OnOne2_local_env (Γ ,, vdef na b t) (Γ ,, vdef na' b' t')
  | onone2_localenv_cons_tl Γ Γ' d :
      OnOne2_local_env Γ Γ' ->
      OnOne2_local_env (Γ ,, d) (Γ' ,, d).
End OnOne_local_2.
Arguments exist {_ _} _ _.
Import Equations.Type.Relation.

Reserved Notation " Σ ;;; Γ |- t ⇝ u " (at level 50, Γ, t, u at next level).

Definition set_array_default (ar : array_model term) (v : term) :=
  {| array_level := ar.(array_level);
     array_default := v;
     array_type := ar.(array_type);
     array_value := ar.(array_value) |}.

Definition set_array_type (ar : array_model term) (v : term) :=
  {| array_level := ar.(array_level);
     array_default := ar.(array_default);
     array_type := v;
     array_value := ar.(array_value) |}.

Definition set_array_value (ar : array_model term) (v : list term) :=
  {| array_level := ar.(array_level);
     array_default := ar.(array_default);
     array_type := ar.(array_type);
     array_value := v |}.

Inductive red1 (Σ : global_env) (Γ : context) : term -> term -> Type :=

| red_beta na t b a :
  Σ ;;; Γ |- tApp (tLambda na t b) a ⇝ b {0 := a}

| red_zeta na b t b' :
  Σ ;;; Γ |- tLetIn na b t b' ⇝ b' {0 := b}

| red_rel i body :
    option_map decl_body (nth_error Γ i) = Some (Some body) ->
    Σ ;;; Γ |- tRel i ⇝ lift0 (S i) body

| red_iota ci c u args p brs br :
    nth_error brs c = Some br ->
    #|args| = (ci.(ci_npar) + context_assumptions br.(bcontext))%nat ->
    Σ ;;; Γ |- tCase ci p (mkApps (tConstruct ci.(ci_ind) c u) args) brs
        ⇝ iota_red ci.(ci_npar) p args br

| red_fix mfix idx args narg fn :
    unfold_fix mfix idx = Some (narg, fn) ->
    is_constructor narg args = true ->
    Σ ;;; Γ |- mkApps (tFix mfix idx) args ⇝ mkApps fn args

| red_cofix_case ip p mfix idx args narg fn brs :
    unfold_cofix mfix idx = Some (narg, fn) ->
    Σ ;;; Γ |- tCase ip p (mkApps (tCoFix mfix idx) args) brs ⇝
         tCase ip p (mkApps fn args) brs

| red_cofix_proj p mfix idx args narg fn :
    unfold_cofix mfix idx = Some (narg, fn) ->
    Σ ;;; Γ |- tProj p (mkApps (tCoFix mfix idx) args) ⇝ tProj p (mkApps fn args)

| red_delta c decl body (isdecl : declared_constant Σ c decl) u :
    decl.(cst_body) = Some body ->
    Σ ;;; Γ |- tConst c u ⇝ subst_instance u body

| red_proj p args u arg:
    nth_error args (p.(proj_npars) + p.(proj_arg)) = Some arg ->
    Σ ;;; Γ |- tProj p (mkApps (tConstruct p.(proj_ind) 0 u) args) ⇝ arg

| abs_red_l na M M' N : Σ ;;; Γ |- M ⇝ M' -> Σ ;;; Γ |- tLambda na M N ⇝ tLambda na M' N
| abs_red_r na M M' N : Σ ;;; Γ ,, vass na N |- M ⇝ M' -> Σ ;;; Γ |- tLambda na N M ⇝ tLambda na N M'

| letin_red_def na b t b' r : Σ ;;; Γ |- b ⇝ r -> Σ ;;; Γ |- tLetIn na b t b' ⇝ tLetIn na r t b'
| letin_red_ty na b t b' r : Σ ;;; Γ |- t ⇝ r -> Σ ;;; Γ |- tLetIn na b t b' ⇝ tLetIn na b r b'
| letin_red_body na b t b' r : Σ ;;; Γ ,, vdef na b t |- b' ⇝ r -> Σ ;;; Γ |- tLetIn na b t b' ⇝ tLetIn na b t r

| case_red_param ci p params' c brs :
    OnOne2 (fun t u => Σ ;;; Γ |- t ⇝ u) p.(pparams) params' ->
    Σ ;;; Γ |- tCase ci p c brs ⇝ tCase ci (set_pparams p params') c brs

| case_red_return ci p preturn' c brs :
  Σ ;;; Γ ,,, inst_case_predicate_context p |- p.(preturn) ⇝ preturn' ->
  Σ ;;; Γ |- tCase ci p c brs ⇝ tCase ci (set_preturn p preturn') c brs

| case_red_discr ci p c c' brs :
  Σ ;;; Γ |- c ⇝ c' -> Σ ;;; Γ |- tCase ci p c brs ⇝ tCase ci p c' brs

| case_red_brs ci p c brs brs' :
    OnOne2 (fun br br' =>
      on_Trel_eq (fun t u => Σ ;;; Γ ,,, inst_case_branch_context p br |- t ⇝ u) bbody bcontext br br')
      brs brs' ->
    Σ ;;; Γ |- tCase ci p c brs ⇝ tCase ci p c brs'

| proj_red p c c' : Σ ;;; Γ |- c ⇝ c' -> Σ ;;; Γ |- tProj p c ⇝ tProj p c'

| app_red_l M1 N1 M2 : Σ ;;; Γ |- M1 ⇝ N1 -> Σ ;;; Γ |- tApp M1 M2 ⇝ tApp N1 M2
| app_red_r M2 N2 M1 : Σ ;;; Γ |- M2 ⇝ N2 -> Σ ;;; Γ |- tApp M1 M2 ⇝ tApp M1 N2

| prod_red_l na M1 M2 N1 : Σ ;;; Γ |- M1 ⇝ N1 -> Σ ;;; Γ |- tProd na M1 M2 ⇝ tProd na N1 M2
| prod_red_r na M2 N2 M1 : Σ ;;; Γ ,, vass na M1 |- M2 ⇝ N2 ->
                           Σ ;;; Γ |- tProd na M1 M2 ⇝ tProd na M1 N2

| evar_red ev l l' : OnOne2 (fun t u => Σ ;;; Γ |- t ⇝ u) l l' -> Σ ;;; Γ |- tEvar ev l ⇝ tEvar ev l'

| fix_red_ty mfix0 mfix1 idx :
    OnOne2 (on_Trel_eq (fun t u => Σ ;;; Γ |- t ⇝ u) dtype (fun x => (dname x, dbody x, rarg x))) mfix0 mfix1 ->
    Σ ;;; Γ |- tFix mfix0 idx ⇝ tFix mfix1 idx

| fix_red_body mfix0 mfix1 idx :
    OnOne2 (on_Trel_eq (fun t u => Σ ;;; Γ ,,, fix_context mfix0 |- t ⇝ u) dbody (fun x => (dname x, dtype x, rarg x)))
           mfix0 mfix1 ->
    Σ ;;; Γ |- tFix mfix0 idx ⇝ tFix mfix1 idx

| cofix_red_ty mfix0 mfix1 idx :
    OnOne2 (on_Trel_eq (fun t u => Σ ;;; Γ |- t ⇝ u) dtype (fun x => (dname x, dbody x, rarg x))) mfix0 mfix1 ->
    Σ ;;; Γ |- tCoFix mfix0 idx ⇝ tCoFix mfix1 idx

| cofix_red_body mfix0 mfix1 idx :
    OnOne2 (on_Trel_eq (fun t u => Σ ;;; Γ ,,, fix_context mfix0 |- t ⇝ u) dbody (fun x => (dname x, dtype x, rarg x))) mfix0 mfix1 ->
    Σ ;;; Γ |- tCoFix mfix0 idx ⇝ tCoFix mfix1 idx

| array_red_val arr value :
    OnOne2 (fun t u => Σ ;;; Γ |- t ⇝ u) arr.(array_value) value ->
    Σ ;;; Γ |- tPrim (primArray; primArrayModel arr) ⇝
               tPrim (primArray; primArrayModel (set_array_value arr value))

| array_red_def arr def :
    Σ ;;; Γ |- arr.(array_default) ⇝ def ->
    Σ ;;; Γ |- tPrim (primArray; primArrayModel arr) ⇝
               tPrim (primArray; primArrayModel (set_array_default arr def))

| array_red_type arr ty :
    Σ ;;; Γ |- arr.(array_type) ⇝ ty ->
    Σ ;;; Γ |- tPrim (primArray; primArrayModel arr) ⇝
          tPrim (primArray; primArrayModel (set_array_type arr ty))

where " Σ ;;; Γ |- t ⇝ u " := (red1 Σ Γ t u).

Definition red1_ctx Σ := (OnOne2_local_env (fun Δ => on_one_decl (fun t t' => red1 Σ Δ t t'))).

Definition red Σ Γ := clos_refl_trans (fun t u : term => Σ;;; Γ |- t ⇝ u).
Module Export PCUICCumulativitySpec.
Import MetaRocq.Common.config.

Implicit Types (cf : checker_flags).

Definition cumul_predicate (cumul : context -> term -> term -> Type) cumul_universe Γ p p' :=
  All2 (cumul Γ) p.(pparams) p'.(pparams) ×
  cmp_universe_instance cumul_universe p.(puinst) p'.(puinst) ×
  eq_context_upto_names p.(pcontext) p'.(pcontext) ×
  cumul (Γ ,,, inst_case_predicate_context p) p.(preturn) p'.(preturn).

Definition cumul_branch (cumul_term : context -> term -> term -> Type) Γ p br br' :=
  eq_context_upto_names br.(bcontext) br'.(bcontext) ×
  cumul_term (Γ ,,, inst_case_branch_context p br) br.(bbody) br'.(bbody).

Definition cumul_branches cumul_term Γ p brs brs' := All2 (cumul_branch cumul_term Γ p) brs brs'.

Definition cumul_mfixpoint (cumul_term : context -> term -> term -> Type) Γ mfix mfix' :=
  All2 (fun d d' =>
    cumul_term Γ d.(dtype) d'.(dtype) ×
    cumul_term (Γ ,,, fix_context mfix) d.(dbody) d'.(dbody) ×
    d.(rarg) = d'.(rarg) ×
    eq_binder_annot d.(dname) d'.(dname)
  ) mfix mfix'.

Reserved Notation " Σ ;;; Γ ⊢ t ≤s[ pb ] u" (at level 50, Γ, t, u at next level,
  format "Σ  ;;;  Γ  ⊢  t  ≤s[ pb ]  u").

Definition cumul_Ind_univ {cf} (Σ : global_env_ext) pb i napp :=
  cmp_global_instance Σ (compare_universe Σ) pb (IndRef i) napp.

Definition cumul_Construct_univ {cf} (Σ : global_env_ext) pb  i k napp :=
  cmp_global_instance Σ (compare_universe Σ) pb (ConstructRef i k) napp.
Inductive cumulSpec0 {cf : checker_flags} (Σ : global_env_ext) Γ (pb : conv_pb) : term -> term -> Type :=

| cumul_Trans : forall t u v,
    is_closed_context Γ -> is_open_term Γ u ->
    Σ ;;; Γ ⊢ t ≤s[pb] u ->
    Σ ;;; Γ ⊢ u ≤s[pb] v ->
    Σ ;;; Γ ⊢ t ≤s[pb] v

| cumul_Sym : forall t u,
    Σ ;;; Γ ⊢ t ≤s[Conv] u ->
    Σ ;;; Γ ⊢ u ≤s[pb] t

| cumul_Refl : forall t,
    Σ ;;; Γ ⊢ t ≤s[pb] t

| cumul_Ind : forall i u u' args args',
    cumul_Ind_univ Σ pb i #|args| u u' ->
    All2 (fun t u => Σ ;;; Γ ⊢ t ≤s[Conv] u) args args' ->
    Σ ;;; Γ ⊢ mkApps (tInd i u) args ≤s[pb] mkApps (tInd i u') args'

| cumul_Construct : forall i k u u' args args',
    cumul_Construct_univ Σ pb i k #|args| u u' ->
    All2 (fun t u => Σ ;;; Γ ⊢ t ≤s[Conv] u) args args' ->
    Σ ;;; Γ ⊢ mkApps (tConstruct i k u) args ≤s[pb] mkApps (tConstruct i k u') args'

| cumul_Sort : forall s s',
    compare_sort Σ pb s s' ->
    Σ ;;; Γ ⊢ tSort s ≤s[pb] tSort s'

| cumul_Const : forall c u u',
    cmp_universe_instance (compare_universe Σ Conv) u u' ->
    Σ ;;; Γ ⊢ tConst c u ≤s[pb] tConst c u'

| cumul_Evar : forall e args args',
    All2 (fun t u => Σ ;;; Γ ⊢ t ≤s[Conv] u) args args' ->
    Σ ;;; Γ ⊢ tEvar e args ≤s[pb] tEvar e args'

| cumul_App : forall t t' u u',
    Σ ;;; Γ ⊢ t ≤s[pb] t' ->
    Σ ;;; Γ ⊢ u ≤s[Conv] u' ->
    Σ ;;; Γ ⊢ tApp t u ≤s[pb] tApp t' u'

| cumul_Lambda : forall na na' ty ty' t t',
    eq_binder_annot na na' ->
    Σ ;;; Γ ⊢ ty ≤s[Conv] ty' ->
    Σ ;;; Γ ,, vass na ty ⊢ t ≤s[Conv] t' ->
    Σ ;;; Γ ⊢ tLambda na ty t ≤s[pb] tLambda na' ty' t'

| cumul_Prod : forall na na' a a' b b',
    eq_binder_annot na na' ->
    Σ ;;; Γ ⊢ a ≤s[Conv] a' ->
    Σ ;;; Γ ,, vass na a ⊢ b ≤s[pb] b' ->
    Σ ;;; Γ ⊢ tProd na a b ≤s[pb] tProd na' a' b'

| cumul_LetIn : forall na na' t t' ty ty' u u',
    eq_binder_annot na na' ->
    Σ ;;; Γ ⊢ t ≤s[Conv] t' ->
    Σ ;;; Γ ⊢ ty ≤s[Conv] ty' ->
    Σ ;;; Γ ,, vdef na t ty ⊢ u ≤s[Conv] u' ->
    Σ ;;; Γ ⊢ tLetIn na t ty u ≤s[pb] tLetIn na' t' ty' u'

| cumul_Case indn : forall p p' c c' brs brs',
    cumul_predicate (fun Γ t u => Σ ;;; Γ ⊢ t ≤s[Conv] u) (compare_universe Σ Conv) Γ p p' ->
    Σ ;;; Γ ⊢ c ≤s[Conv] c' ->
    cumul_branches (fun Γ t u => Σ ;;; Γ ⊢ t ≤s[Conv] u) Γ p brs brs' ->
    Σ ;;; Γ ⊢ tCase indn p c brs ≤s[pb] tCase indn p' c' brs'

| cumul_Proj : forall p c c',
    Σ ;;; Γ ⊢ c ≤s[Conv] c' ->
    Σ ;;; Γ ⊢ tProj p c ≤s[pb] tProj p c'

| cumul_Fix : forall mfix mfix' idx,
    cumul_mfixpoint (fun Γ t u => Σ ;;; Γ ⊢ t ≤s[Conv] u) Γ mfix mfix' ->
    Σ ;;; Γ ⊢ tFix mfix idx ≤s[pb] tFix mfix' idx

| cumul_CoFix : forall mfix mfix' idx,
    cumul_mfixpoint (fun Γ t u => Σ ;;; Γ ⊢ t ≤s[Conv] u) Γ mfix mfix' ->
    Σ ;;; Γ ⊢ tCoFix mfix idx ≤s[pb] tCoFix mfix' idx

| cumul_Prim p p' :
  onPrims (fun x y => Σ ;;; Γ ⊢ x ≤s[Conv] y) (compare_universe Σ Conv) p p' ->
  Σ ;;; Γ ⊢ tPrim p ≤s[pb] tPrim p'

| cumul_beta : forall na t b a,
    Σ ;;; Γ ⊢ tApp (tLambda na t b) a ≤s[pb] b {0 := a}

| cumul_zeta : forall na b t b',
    Σ ;;; Γ ⊢ tLetIn na b t b' ≤s[pb] b' {0 := b}

| cumul_rel i body :
    option_map decl_body (nth_error Γ i) = Some (Some body) ->
    Σ ;;; Γ ⊢ tRel i ≤s[pb] lift0 (S i) body

| cumul_iota : forall ci c u args p brs br,
    nth_error brs c = Some br ->
    #|args| = (ci.(ci_npar) + context_assumptions br.(bcontext))%nat ->
    Σ ;;; Γ ⊢ tCase ci p (mkApps (tConstruct ci.(ci_ind) c u) args) brs  ≤s[pb] iota_red ci.(ci_npar) p args br

| cumul_fix : forall mfix idx args narg fn,
    unfold_fix mfix idx = Some (narg, fn) ->
    is_constructor narg args = true ->
    Σ ;;; Γ ⊢ mkApps (tFix mfix idx) args ≤s[pb] mkApps fn args

| cumul_cofix_case : forall ip p mfix idx args narg fn brs,
    unfold_cofix mfix idx = Some (narg, fn) ->
    Σ ;;; Γ ⊢ tCase ip p (mkApps (tCoFix mfix idx) args) brs ≤s[pb] tCase ip p (mkApps fn args) brs

| cumul_cofix_proj : forall p mfix idx args narg fn,
    unfold_cofix mfix idx = Some (narg, fn) ->
    Σ ;;; Γ ⊢ tProj p (mkApps (tCoFix mfix idx) args) ≤s[pb] tProj p (mkApps fn args)

| cumul_delta : forall c decl body (isdecl : declared_constant Σ c decl) u,
    decl.(cst_body) = Some body ->
    Σ ;;; Γ ⊢ tConst c u ≤s[pb] body@[u]

| cumul_proj : forall p args u arg,
    nth_error args (p.(proj_npars) + p.(proj_arg)) = Some arg ->
    Σ ;;; Γ ⊢ tProj p (mkApps (tConstruct p.(proj_ind) 0 u) args) ≤s[pb] arg

where " Σ ;;; Γ ⊢ t ≤s[ pb ] u " := (@cumulSpec0 _ Σ Γ pb t u) : type_scope.
Definition cumulSpec `{checker_flags} (Σ : global_env_ext) Γ := cumulSpec0 Σ Γ Cumul.

Notation " Σ ;;; Γ |- t <=s u " := (@cumulSpec _ Σ Γ t u) (at level 50, Γ, t, u at next level).

Module PCUICConversionParSpec <: EnvironmentTyping.ConversionParSig PCUICTerm PCUICEnvironment PCUICTermUtils PCUICEnvTyping.
  Definition cumul_gen := @cumulSpec0.
End PCUICConversionParSpec.

End PCUICCumulativitySpec.
Import MetaRocq.Common.config.

Implicit Types (cf : checker_flags) (Σ : global_env_ext).

Definition type_of_constructor mdecl (cdecl : constructor_body) (c : inductive * nat) (u : list Level.t) :=
  let mind := inductive_mind (fst c) in
  subst0 (inds mind u mdecl.(ind_bodies)) (subst_instance u (cstr_type cdecl)).

Include PCUICEnvTyping.

Inductive FixCoFix : Type := Fix | CoFix.

Class GuardChecker :=
{
  guard : FixCoFix -> global_env_ext -> context -> mfixpoint term -> Prop ;
}.

Axiom guard_checking : GuardChecker.
#[global]
Existing Instance guard_checking.

Definition fix_guard := guard Fix.
Definition cofix_guard := guard CoFix.

Definition destInd (t : term) :=
  match t with
  | tInd ind u => Some (ind, u)
  | _ => None
  end.

Definition isCoFinite (r : recursivity_kind) :=
  match r with
  | CoFinite => true
  | _ => false
  end.

Definition check_recursivity_kind
  (lookup: kername -> option global_decl) ind r :=
  match lookup ind with
  | Some (InductiveDecl mib) => ReflectEq.eqb mib.(ind_finite) r
  | _ => false
  end.

Definition check_one_fix d :=
  let '{| dname := na;
         dtype := ty;
         dbody := b;
         rarg := arg |} := d in
  let '(ctx, ty) := decompose_prod_assum [] ty in
  match nth_error (List.rev (smash_context [] ctx)) arg with
  | Some argd =>
    let (hd, args) := decompose_app argd.(decl_type) in
    match destInd hd with
    | Some (mkInd mind _, u) => Some mind
    | None => None
    end
  | None => None
  end.

Definition wf_fixpoint_gen
  (lookup: kername -> option global_decl) mfix :=
  forallb (isLambda ∘ dbody) mfix &&
  let checks := map check_one_fix mfix in
  match map_option_out checks with
  | Some (ind :: inds) =>

    forallb (eqb ind) inds &&
    check_recursivity_kind lookup ind Finite
  | _ => false
  end.

Definition wf_fixpoint (Σ : global_env) := wf_fixpoint_gen (lookup_env Σ).

Definition check_one_cofix d :=
  let '{| dname := na;
         dtype := ty;
         dbody := b;
         rarg := arg |} := d in
  let '(ctx, ty) := decompose_prod_assum [] ty in
  let (hd, args) := decompose_app ty in
  match destInd hd with
  | Some (mkInd ind _, u) => Some ind
  | None => None
  end.

Definition wf_cofixpoint_gen
  (lookup: kername -> option global_decl) mfix :=
  let checks := map check_one_cofix mfix in
  match map_option_out checks with
  | Some (ind :: inds) =>

    forallb (eqb ind) inds &&
    check_recursivity_kind lookup ind CoFinite
  | _ => false
  end.

Definition wf_cofixpoint (Σ : global_env) := wf_cofixpoint_gen (lookup_env Σ).

Reserved Notation "'wf_local' Σ Γ " (at level 9, Σ, Γ at next level).

Reserved Notation " Σ ;;; Γ |- t : T " (at level 50, Γ, t, T at next level).

Variant case_side_conditions `{checker_flags} wf_local_fun typing Σ Γ ci p ps mdecl idecl indices predctx :=
| case_side_info
    (eq_npars : mdecl.(ind_npars) = ci.(ci_npar))
    (wf_pred : wf_predicate mdecl idecl p)
    (cons : consistent_instance_ext Σ (ind_universes mdecl) p.(puinst))
    (wf_pctx : wf_local_fun Σ (Γ ,,, predctx))

    (conv_pctx : eq_context_upto_names p.(pcontext) (ind_predicate_context ci.(ci_ind) mdecl idecl))
    (allowed_elim : is_allowed_elimination Σ idecl.(ind_kelim) ps)
    (elim_relevance : isSortRel ps ci.(ci_relevance))
    (ind_inst : ctx_inst (typing Σ) Γ (p.(pparams) ++ indices)
                         (List.rev (subst_instance p.(puinst)
                                                   (ind_params mdecl ,,, ind_indices idecl : context))))
    (not_cofinite : isCoFinite mdecl.(ind_finite) = false).

Variant case_branch_typing `{checker_flags} wf_local_fun typing Σ Γ (ci:case_info) p ps mdecl idecl ptm  brs :=
| case_branch_info
    (wf_brs : wf_branches idecl brs)
    (brs_ty :
       All2i (fun i cdecl br =>

                eq_context_upto_names br.(bcontext) (cstr_branch_context ci mdecl cdecl) ×
                let brctxty := case_branch_type ci.(ci_ind) mdecl idecl p br ptm i cdecl in
                (wf_local_fun Σ (Γ ,,, brctxty.1) ×
                ((typing Σ (Γ ,,, brctxty.1) br.(bbody) (brctxty.2)) ×
                (typing Σ (Γ ,,, brctxty.1) brctxty.2 (tSort ps)))))
             0 idecl.(ind_ctors) brs).

Variant primitive_typing_hyps `{checker_flags}
  (typing : forall (Σ : global_env_ext) (Γ : context), term -> term -> Type)
  Σ Γ : prim_val term -> Type :=
| prim_int_hyps i : primitive_typing_hyps typing Σ Γ (primInt; primIntModel i)
| prim_float_hyps f : primitive_typing_hyps typing Σ Γ (primFloat; primFloatModel f)
| prim_string_hyps s : primitive_typing_hyps typing Σ Γ (primString; primStringModel s)
| prim_array_hyps a
  (wfl : wf_universe Σ (Universe.make' a.(array_level)))
  (hty : typing Σ Γ a.(array_type) (tSort (sType (Universe.make' a.(array_level)))))
  (hdef : typing Σ Γ a.(array_default) a.(array_type))
  (hvalue : All (fun x => typing Σ Γ x a.(array_type)) a.(array_value)) :
  primitive_typing_hyps typing Σ Γ (primArray; primArrayModel a).

Equations prim_type (p : prim_val term) (cst : kername) : term :=
prim_type (primInt; _) cst := tConst cst [];
prim_type (primFloat; _) cst := tConst cst [];
prim_type (primString; _) cst := tConst cst [];
prim_type (primArray; primArrayModel a) cst := tApp (tConst cst [a.(array_level)]) a.(array_type).

Inductive typing `{checker_flags} (Σ : global_env_ext) (Γ : context) : term -> term -> Type :=
| type_Rel : forall n decl,
    wf_local Σ Γ ->
    nth_error Γ n = Some decl ->
    Σ ;;; Γ |- tRel n : lift0 (S n) decl.(decl_type)

| type_Sort : forall s,
    wf_local Σ Γ ->
    wf_sort Σ s ->
    Σ ;;; Γ |- tSort s : tSort (Sort.super s)

| type_Prod : forall na A B s1 s2,
    lift_typing typing Σ Γ (j_vass_s na A s1) ->
    Σ ;;; Γ ,, vass na A |- B : tSort s2 ->
    Σ ;;; Γ |- tProd na A B : tSort (Sort.sort_of_product s1 s2)

| type_Lambda : forall na A t B,
    lift_typing typing Σ Γ (j_vass na A) ->
    Σ ;;; Γ ,, vass na A |- t : B ->
    Σ ;;; Γ |- tLambda na A t : tProd na A B

| type_LetIn : forall na b B t A,
    lift_typing typing Σ Γ (j_vdef na b B) ->
    Σ ;;; Γ ,, vdef na b B |- t : A ->
    Σ ;;; Γ |- tLetIn na b B t : tLetIn na b B A

| type_App : forall t na A B s u,

    Σ ;;; Γ |- tProd na A B : tSort s ->
    Σ ;;; Γ |- t : tProd na A B ->
    Σ ;;; Γ |- u : A ->
    Σ ;;; Γ |- tApp t u : B{0 := u}

| type_Const : forall cst u decl,
    wf_local Σ Γ ->
    declared_constant Σ cst decl ->
    consistent_instance_ext Σ decl.(cst_universes) u ->
    Σ ;;; Γ |- tConst cst u : decl.(cst_type)@[u]

| type_Ind : forall ind u mdecl idecl,
    wf_local Σ Γ ->
    declared_inductive Σ ind mdecl idecl ->
    consistent_instance_ext Σ mdecl.(ind_universes) u ->
    Σ ;;; Γ |- tInd ind u : idecl.(ind_type)@[u]

| type_Construct : forall ind i u mdecl idecl cdecl,
    wf_local Σ Γ ->
    declared_constructor Σ (ind, i) mdecl idecl cdecl ->
    consistent_instance_ext Σ mdecl.(ind_universes) u ->
    Σ ;;; Γ |- tConstruct ind i u : type_of_constructor mdecl cdecl (ind, i) u

| type_Case : forall ci p c brs indices ps mdecl idecl,
    let predctx := case_predicate_context ci.(ci_ind) mdecl idecl p in
    let ptm := it_mkLambda_or_LetIn predctx p.(preturn) in
    declared_inductive Σ ci.(ci_ind) mdecl idecl ->
    Σ ;;; Γ ,,, predctx |- p.(preturn) : tSort ps ->
    Σ ;;; Γ |- c : mkApps (tInd ci.(ci_ind) p.(puinst)) (p.(pparams) ++ indices) ->
    case_side_conditions (fun Σ Γ => wf_local Σ Γ) typing Σ Γ ci p ps
                         mdecl idecl indices predctx  ->
    case_branch_typing (fun Σ Γ => wf_local Σ Γ) typing Σ Γ ci p ps
                        mdecl idecl ptm brs ->
    Σ ;;; Γ |- tCase ci p c brs : mkApps ptm (indices ++ [c])

| type_Proj : forall p c u mdecl idecl cdecl pdecl args,
    declared_projection Σ p mdecl idecl cdecl pdecl ->
    Σ ;;; Γ |- c : mkApps (tInd p.(proj_ind) u) args ->
    #|args| = ind_npars mdecl ->
    Σ ;;; Γ |- tProj p c : subst0 (c :: List.rev args) pdecl.(proj_type)@[u]

| type_Fix : forall mfix n decl,
    wf_local Σ Γ ->
    fix_guard Σ Γ mfix ->
    nth_error mfix n = Some decl ->
    All (on_def_type (lift_typing1 (typing Σ)) Γ) mfix ->
    All (on_def_body (lift_typing1 (typing Σ)) (fix_context mfix) Γ) mfix ->
    wf_fixpoint Σ mfix ->
    Σ ;;; Γ |- tFix mfix n : decl.(dtype)

| type_CoFix : forall mfix n decl,
    wf_local Σ Γ ->
    cofix_guard Σ Γ mfix ->
    nth_error mfix n = Some decl ->
    All (on_def_type (lift_typing1 (typing Σ)) Γ) mfix ->
    All (on_def_body (lift_typing1 (typing Σ)) (fix_context mfix) Γ) mfix ->
    wf_cofixpoint Σ mfix ->
    Σ ;;; Γ |- tCoFix mfix n : decl.(dtype)

| type_Prim p prim_ty cdecl :
    wf_local Σ Γ ->
    primitive_constant Σ (prim_val_tag p) = Some prim_ty ->
    declared_constant Σ prim_ty cdecl ->
    primitive_invariants (prim_val_tag p) cdecl ->
    primitive_typing_hyps typing Σ Γ p ->
    Σ ;;; Γ |- tPrim p : prim_type p prim_ty

| type_Cumul : forall t A B s,
    Σ ;;; Γ |- t : A ->
    Σ ;;; Γ |- B : tSort s ->
    Σ ;;; Γ |- A <=s B ->
    Σ ;;; Γ |- t : B

where " Σ ;;; Γ |- t : T " := (typing Σ Γ t T)
and "'wf_local' Σ Γ " := (All_local_env (lift_typing1 (typing Σ)) Γ).

Module PCUICTypingDef <: EnvironmentTyping.Typing PCUICTerm PCUICEnvironment PCUICTermUtils PCUICEnvTyping PCUICConversion PCUICConversionParSpec.

  Definition typing := @typing.

End PCUICTypingDef.

Definition wf `{checker_flags} := on_global_env cumulSpec0 (lift_typing typing).
Notation on_contexts_length := All2_fold_length.
Import Stdlib.ssr.ssreflect.
Import Equations.Prop.Equations.
Import Stdlib.Classes.CRelationClasses.
Import Equations.Type.Relation_Properties.

Definition ws_term P := { t : term | on_free_vars P t }.
Definition ws_term_proj {P} (t : ws_term P) : term.
admit.
Defined.
Coercion ws_term_proj : ws_term >-> term.

Definition ws_context P := { t : context | on_free_vars_ctx P t }.

Notation closed_context := (ws_context xpred0).
Notation open_term Γ := (ws_term (shiftnP #|Γ| xpred0)).
Definition ws_context_proj' {P} (t : ws_context P) : list context_decl.
Admitted.
Coercion ws_context_proj' : ws_context >-> list.

Definition ws_red1 Σ P (Γ : ws_context P) (t u : ws_term (shiftnP #|Γ| P)) :=
  red1 Σ Γ t u.

Definition ws_red Σ P (Γ : ws_context P) := clos_refl_trans (ws_red1 Σ P Γ).

Definition ws_pair :=
  ∑ Γ : ws_context xpred0, ws_term (shiftnP #|Γ| xpred0).

Section RedConfluence.
  Context {cf : checker_flags}.
  Context {Σ : global_env_ext} (wfΣ : wf Σ).
Definition red1_rel_alpha : relation ws_pair.
exact (relation_disjunction (A:=ws_pair) (fun '(Γ; t) '(Δ; u) => (red1 Σ Γ t u * (Γ = Δ)))%type
     (relation_disjunction (A:=ws_pair)
        (fun '(Γ; t) '(Δ; u) => ((red1_ctx Σ Γ Δ * (t = u :> term))))
        (fun '(Γ; t) '(Δ; u) => ((eq_context_upto_names Γ Δ * (t = u :> term)))))%type).
Defined.

  Lemma red_ws_red (Γ : closed_context) (x y : ws_term (shiftnP #|Γ| xpred0)) :
    red Σ Γ x y -> ws_red Σ xpred0 Γ x y.
Admitted.
Definition transport_ws_term {n m : nat} (t : ws_term (shiftnP n xpred0)) (eq : n = m) : ws_term (shiftnP m xpred0).
Admitted.
Definition red_ctx_alpha : relation context.
exact (All2_fold (fun Γ _ => All_decls_alpha (red Σ Γ))).
Defined.

  Instance red_ctx_alpha_refl : Reflexive red_ctx_alpha.
Admitted.

  Lemma ws_red_refl_irrel P (Γ : ws_context P) (x y : ws_term (shiftnP #|Γ| P)) :
    x = y :> term ->
    ws_red Σ P Γ x y.
Admitted.

  Lemma clos_rt_red1_alpha_out x y :
    clos_refl_trans red1_rel_alpha x y ->
    ∑ redctx : red_ctx_alpha x.π1 y.π1,
      ws_red Σ xpred0 x.π1 x.π2 (transport_ws_term y.π2 (symmetry (All2_fold_length redctx))).
  Proof using wfΣ.
    intros H.
    eapply clos_rt_rt1n_iff in H.
    induction H.
    -
 unshelve eexists.
reflexivity.
eapply ws_red_refl_irrel => //.
    -
 destruct x as [Γ t], y as [Δ u], z as [Δ' u']; simpl in *.
      destruct IHclos_refl_trans_1n.
      red in r.
destruct r.
      *
 destruct p.
subst.
exists x.
        transitivity u; auto.
        now eapply red_ws_red.
      *
 destruct t as [t ht], u as [u hu];
        move: r; case; move => [] r eq; noconf eq.
🛠️ Intermediate Coq File (useful for debugging if minimization did not go as far as you wanted)
🛠️ 📜 Intermediate Coq File log (useful for debugging if minimization did not go as far as you wanted)
📜 Build Log (contains the Coq error message) (truncated to last 8.0KiB; full 7.0MiB file on GitHub Actions Artifacts under build.log)
t-minimizer.Dw8n1fO7h0
MINIMIZER_DEBUG: files: 
make[2]: Leaving directory '/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/template-rocq'
# Ensure the cmxs is built before the loader file 
make -f Makefile.plugin gen-src/metarocq_template_plugin.cmxs
make[2]: Entering directory '/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/template-rocq'
MINIMIZER_DEBUG_EXTRA: coqc: /github/workspace/builds/coq/coq-failing/_install_ci/bin///rocq
MINIMIZER_DEBUG_EXTRA: original invocation: c --print-version 
MINIMIZER_DEBUG_EXTRA: new invocation: /github/workspace/builds/coq/coq-failing/_install_ci/bin/rocq.orig c --print-version 
MINIMIZER_DEBUG_EXTRA: coqpath: 
MINIMIZER_DEBUG_EXTRA: ocamlpath: /github/workspace/builds/coq/coq-failing/_build_ci/metarocq/template-rocq/:/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/safechecker-plugin/src:/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/erasure-plugin/src:/github/workspace/builds/coq/coq-failing/_install_ci/lib:
MINIMIZER_DEBUG_EXTRA: pwd: PWD=/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/template-rocq
MINIMIZER_DEBUG_EXTRA: exec: /github/workspace/builds/coq/coq-failing/_install_ci/bin/rocq.orig c --print-version 
MINIMIZER_DEBUG_EXTRA: coqlib: Warning: Deprecated environment variable COQLIB, use ROCQLIB instead.
/github/workspace/builds/coq/coq-failing/_install_ci/lib/coq//
MINIMIZER_DEBUG: info: /tmp/tmp-coqbot-minimizer.kvgeo2fG7T
MINIMIZER_DEBUG: files: 
make[2]: 'gen-src/metarocq_template_plugin.cmxs' is up to date.
make[2]: Leaving directory '/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/template-rocq'
make -f Makefile.plugin
make[2]: Entering directory '/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/template-rocq'
MINIMIZER_DEBUG_EXTRA: coqc: /github/workspace/builds/coq/coq-failing/_install_ci/bin///rocq
MINIMIZER_DEBUG_EXTRA: original invocation: c --print-version 
MINIMIZER_DEBUG_EXTRA: new invocation: /github/workspace/builds/coq/coq-failing/_install_ci/bin/rocq.orig c --print-version 
MINIMIZER_DEBUG_EXTRA: coqpath: 
MINIMIZER_DEBUG_EXTRA: ocamlpath: /github/workspace/builds/coq/coq-failing/_build_ci/metarocq/template-rocq/:/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/safechecker-plugin/src:/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/erasure-plugin/src:/github/workspace/builds/coq/coq-failing/_install_ci/lib:
MINIMIZER_DEBUG_EXTRA: pwd: PWD=/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/template-rocq
MINIMIZER_DEBUG_EXTRA: exec: /github/workspace/builds/coq/coq-failing/_install_ci/bin/rocq.orig c --print-version 
MINIMIZER_DEBUG_EXTRA: coqlib: Warning: Deprecated environment variable COQLIB, use ROCQLIB instead.
/github/workspace/builds/coq/coq-failing/_install_ci/lib/coq//
MINIMIZER_DEBUG: info: /tmp/tmp-coqbot-minimizer.f0OxQBxANN
MINIMIZER_DEBUG: files: 
MINIMIZER_DEBUG_EXTRA: coqc: /github/workspace/builds/coq/coq-failing/_install_ci/bin/////rocq
MINIMIZER_DEBUG_EXTRA: original invocation: c --print-version 
MINIMIZER_DEBUG_EXTRA: new invocation: /github/workspace/builds/coq/coq-failing/_install_ci/bin/rocq.orig c --print-version 
MINIMIZER_DEBUG_EXTRA: coqpath: 
MINIMIZER_DEBUG_EXTRA: ocamlpath: /github/workspace/builds/coq/coq-failing/_build_ci/metarocq/template-rocq/:/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/safechecker-plugin/src:/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/erasure-plugin/src:/github/workspace/builds/coq/coq-failing/_install_ci/lib:
MINIMIZER_DEBUG_EXTRA: pwd: PWD=/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/template-rocq
MINIMIZER_DEBUG_EXTRA: exec: /github/workspace/builds/coq/coq-failing/_install_ci/bin/rocq.orig c --print-version 
MINIMIZER_DEBUG_EXTRA: coqlib: Warning: Deprecated environment variable COQLIB, use ROCQLIB instead.
/github/workspace/builds/coq/coq-failing/_install_ci/lib/coq//
MINIMIZER_DEBUG: info: /tmp/tmp-coqbot-minimizer.DUEj7eDNEq
MINIMIZER_DEBUG: files: 
MINIMIZER_DEBUG_EXTRA: coqc: /github/workspace/builds/coq/coq-failing/_install_ci/bin/////rocq
MINIMIZER_DEBUG_EXTRA: original invocation: c --print-version 
MINIMIZER_DEBUG_EXTRA: new invocation: /github/workspace/builds/coq/coq-failing/_install_ci/bin/rocq.orig c --print-version 
MINIMIZER_DEBUG_EXTRA: coqpath: 
MINIMIZER_DEBUG_EXTRA: ocamlpath: /github/workspace/builds/coq/coq-failing/_build_ci/metarocq/template-rocq/:/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/safechecker-plugin/src:/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/erasure-plugin/src:/github/workspace/builds/coq/coq-failing/_install_ci/lib:
MINIMIZER_DEBUG_EXTRA: pwd: PWD=/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/template-rocq
MINIMIZER_DEBUG_EXTRA: exec: /github/workspace/builds/coq/coq-failing/_install_ci/bin/rocq.orig c --print-version 
MINIMIZER_DEBUG_EXTRA: coqlib: Warning: Deprecated environment variable COQLIB, use ROCQLIB instead.
/github/workspace/builds/coq/coq-failing/_install_ci/lib/coq//
MINIMIZER_DEBUG: info: /tmp/tmp-coqbot-minimizer.BqG3VKzIwJ
MINIMIZER_DEBUG: files: 
make[3]: Nothing to be done for 'real-all'.
MINIMIZER_DEBUG_EXTRA: coqc: /github/workspace/builds/coq/coq-failing/_install_ci/bin/////rocq
MINIMIZER_DEBUG_EXTRA: original invocation: c --print-version 
MINIMIZER_DEBUG_EXTRA: new invocation: /github/workspace/builds/coq/coq-failing/_install_ci/bin/rocq.orig c --print-version 
MINIMIZER_DEBUG_EXTRA: coqpath: 
MINIMIZER_DEBUG_EXTRA: ocamlpath: /github/workspace/builds/coq/coq-failing/_build_ci/metarocq/template-rocq/:/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/safechecker-plugin/src:/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/erasure-plugin/src:/github/workspace/builds/coq/coq-failing/_install_ci/lib:
MINIMIZER_DEBUG_EXTRA: pwd: PWD=/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/template-rocq
MINIMIZER_DEBUG_EXTRA: exec: /github/workspace/builds/coq/coq-failing/_install_ci/bin/rocq.orig c --print-version 
MINIMIZER_DEBUG_EXTRA: coqlib: Warning: Deprecated environment variable COQLIB, use ROCQLIB instead.
/github/workspace/builds/coq/coq-failing/_install_ci/lib/coq//
MINIMIZER_DEBUG: info: /tmp/tmp-coqbot-minimizer.jBdYkWRDc4
MINIMIZER_DEBUG: files: 
make[2]: Leaving directory '/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/template-rocq'
make[1]: Leaving directory '/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/template-rocq'
File "./theories/PCUICConfluence.v", line 3649, characters 47-49:
Error: Cannot infer the implicit parameter A of eq whose type is 
"Type" in
environment:
cf : checker_flags
Σ : global_env_ext
wfΣ : wf Σ
Γ : closed_context
t : term
ht : is_open_term Γ t
Δ : closed_context
u : term
hu : is_open_term Δ u
Δ' : closed_context
u' : open_term Δ'
H : clos_refl_trans_1n red1_rel_alpha (Δ; exist u hu) (Δ'; u')
x : red_ctx_alpha Δ Δ'
w :
  ws_red Σ xpred0 Δ (exist u hu)
    (transport_ws_term u' (symmetry (on_contexts_length x)))
r : red1_ctx Σ Γ Δ
eq : exist t ht = exist u hu

Command exited with non-zero status 1
theories/PCUICConfluence.vo (real: 46.54, user: 46.10, sys: 0.43, mem: 2430472 ko)
make[3]: *** [Makefile.rocq:814: theories/PCUICConfluence.vo] Error 1
make[3]: *** [theories/PCUICConfluence.vo] Deleting file 'theories/PCUICConfluence.glob'
make[2]: *** [Makefile.rocq:412: all] Error 2
make[2]: Leaving directory '/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/pcuic'
make[1]: *** [Makefile:11: coq] Error 2
make[1]: Leaving directory '/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/pcuic'
make: *** [Makefile:149: pcuic] Error 2
+ code=2
+ printf '\n%s exit code: %s\n' metarocq 2
+ '[' metarocq '!=' stdlib_test ']'
+ echo 'Aggregating timing log...'
Aggregating timing log...
+ echo

+ tools/make-one-time-file.py --real metarocq.log
    Time |   Peak Mem | File Name            
---------------------------------------------
0m46.54s | 2430472 ko | Total Time / Peak Mem
---------------------------------------------
0m46.54s | 2430472 ko | PCUICConfluence.vo   
+ '[' '' ']'
+ exit 2
/github/workspace/builds/coq /github/workspace
::endgroup::
📜 🔎 Minimization Log (truncated to last 8.0KiB; full 1.3MiB file on GitHub Actions Artifacts under bug.log)
now attempt to remove unused variables
�[92m
Variable removal successful.�[0m

I will now attempt to remove unused contexts
�[92m
Context removal successful.�[0m

I will now attempt to admit [abstract ...]s
�[92m
Admitting [abstract ...] successful.�[0m
�[92m
Admitting [abstract ...] successful.�[0m
Admitting [abstract ...] unsuccessful.
Admitting [abstract ...] unsuccessful.

I will now attempt to remove goals ending in [Abort.]
�[92m
Aborted removal successful.�[0m

I will now attempt to remove unused Ltacs
�[92m
Ltac removal successful.�[0m

I will now attempt to remove unused definitions

Non-fatal error: Failed to remove definitions and preserve the error.  
The new error was:
Deprecated environment variable COQCORELIB, use ROCQRUNTIMELIB instead.
Warning: Deprecated environment variable COQCORELIB,
use ROCQRUNTIMELIB instead.
[deprecated-coq-env-var,deprecated-since-9.0,deprecated,default]
File "/tmp/tmpinfbwz_j/Top/bug_01.v", line 172, characters 0-14:
Error: The field lift is missing in Top.bug_01.PCUICTerm.


�[93mIntermediate code not saved.�[0m

I will now attempt to remove unused non-instance, non-canonical structure definitions

Non-fatal error: Failed to remove non-instance definitions and preserve the error.  
The new error was:
Deprecated environment variable COQCORELIB, use ROCQRUNTIMELIB instead.
Warning: Deprecated environment variable COQCORELIB,
use ROCQRUNTIMELIB instead.
[deprecated-coq-env-var,deprecated-since-9.0,deprecated,default]
File "/tmp/tmp3c8i01l4/Top/bug_01.v", line 175, characters 0-14:
Error: The field lift is missing in Top.bug_01.PCUICTerm.


�[93mIntermediate code not saved.�[0m

I will now attempt to remove unused variables
�[92m
Variable removal successful.�[0m

I will now attempt to remove unused contexts
�[92m
Context removal successful.�[0m

I will now attempt to replace Obligation with Admit Obligations
�[92m
Admitting Obligations successful.�[0m
Failed to do everything at once; trying one at a time.
Admitting Obligations unsuccessful.
No successful changes.

I will now attempt to admit lemmas with Admitted

Non-fatal error: Failed to admit lemmas and preserve the error.  
The new error was:
Deprecated environment variable COQCORELIB, use ROCQRUNTIMELIB instead.
Warning: Deprecated environment variable COQCORELIB,
use ROCQRUNTIMELIB instead.
[deprecated-coq-env-var,deprecated-since-9.0,deprecated,default]
Error: The section RedConfluence needs to be closed.


�[93mIntermediate code not saved.�[0m
Failed to do everything at once; trying one at a time.
Admitting lemmas unsuccessful.
No successful changes.

I will now attempt to admit definitions with Admitted

Non-fatal error: Failed to admit definitions and preserve the error.  
The new error was:
Deprecated environment variable COQCORELIB, use ROCQRUNTIMELIB instead.
Warning: Deprecated environment variable COQCORELIB,
use ROCQRUNTIMELIB instead.
[deprecated-coq-env-var,deprecated-since-9.0,deprecated,default]
File "/tmp/tmpcirensht/Top/bug_01.v", line 1128, characters 88-94:
Error:
In environment
cf : checker_flags
Σ : global_env_ext
wfΣ : wf Σ
x : ws_pair
y : ws_pair
redctx : red_ctx_alpha x.π1 y.π1
The term "redctx" has type "red_ctx_alpha x.π1 y.π1"
while it is expected to have type "All2_fold ?P ?Γ ?Γ'".


�[93mIntermediate code not saved.�[0m
Failed to do everything at once; trying one at a time.
Admitting definitions unsuccessful.
No successful changes.

I will now attempt to admit lemmas with admit. Defined

Non-fatal error: Failed to admit lemmas and preserve the error.  
The new error was:
Deprecated environment variable COQCORELIB, use ROCQRUNTIMELIB instead.
Warning: Deprecated environment variable COQCORELIB,
use ROCQRUNTIMELIB instead.
[deprecated-coq-env-var,deprecated-since-9.0,deprecated,default]
Error: The section RedConfluence needs to be closed.


�[93mIntermediate code not saved.�[0m
Failed to do everything at once; trying one at a time.
Admitting lemmas unsuccessful.
No successful changes.

I will now attempt to admit definitions with admit. Defined

Non-fatal error: Failed to admit definitions and preserve the error.  
The new error was:
Deprecated environment variable COQCORELIB, use ROCQRUNTIMELIB instead.
Warning: Deprecated environment variable COQCORELIB,
use ROCQRUNTIMELIB instead.
[deprecated-coq-env-var,deprecated-since-9.0,deprecated,default]
File "/tmp/tmp6n0x855k/Top/bug_01.v", line 1130, characters 88-94:
Error:
In environment
cf : checker_flags
Σ : global_env_ext
wfΣ : wf Σ
x : ws_pair
y : ws_pair
redctx : red_ctx_alpha x.π1 y.π1
The term "redctx" has type "red_ctx_alpha x.π1 y.π1"
while it is expected to have type "All2_fold ?P ?Γ ?Γ'".


�[93mIntermediate code not saved.�[0m
Failed to do everything at once; trying one at a time.
Admitting definitions unsuccessful.
No successful changes.

I will now attempt to admit lemmas with Admitted with Proof using

Non-fatal error: Failed to admit lemmas and preserve the error.  
The new error was:
Deprecated environment variable COQCORELIB, use ROCQRUNTIMELIB instead.
Warning: Deprecated environment variable COQCORELIB,
use ROCQRUNTIMELIB instead.
[deprecated-coq-env-var,deprecated-since-9.0,deprecated,default]
Error: The section RedConfluence needs to be closed.


�[93mIntermediate code not saved.�[0m
Failed to do everything at once; trying one at a time.
Admitting lemmas unsuccessful.
No successful changes.

I will now attempt to admit definitions with Admitted with Proof using

Non-fatal error: Failed to admit definitions and preserve the error.  
The new error was:
Deprecated environment variable COQCORELIB, use ROCQRUNTIMELIB instead.
Warning: Deprecated environment variable COQCORELIB,
use ROCQRUNTIMELIB instead.
[deprecated-coq-env-var,deprecated-since-9.0,deprecated,default]
File "/tmp/tmpkrdr7zl1/Top/bug_01.v", line 1128, characters 88-94:
Error:
In environment
cf : checker_flags
Σ : global_env_ext
wfΣ : wf Σ
x : ws_pair
y : ws_pair
redctx : red_ctx_alpha x.π1 y.π1
The term "redctx" has type "red_ctx_alpha x.π1 y.π1"
while it is expected to have type "All2_fold ?P ?Γ ?Γ'".


�[93mIntermediate code not saved.�[0m
Failed to do everything at once; trying one at a time.
Admitting definitions unsuccessful.
No successful changes.

I will now attempt to admit lemmas with admit. Defined with Proof using

Non-fatal error: Failed to admit lemmas and preserve the error.  
The new error was:
Deprecated environment variable COQCORELIB, use ROCQRUNTIMELIB instead.
Warning: Deprecated environment variable COQCORELIB,
use ROCQRUNTIMELIB instead.
[deprecated-coq-env-var,deprecated-since-9.0,deprecated,default]
Error: The section RedConfluence needs to be closed.


�[93mIntermediate code not saved.�[0m
Failed to do everything at once; trying one at a time.
Admitting lemmas unsuccessful.
No successful changes.

I will now attempt to admit definitions with admit. Defined with Proof using

Non-fatal error: Failed to admit definitions and preserve the error.  
The new error was:
Deprecated environment variable COQCORELIB, use ROCQRUNTIMELIB instead.
Warning: Deprecated environment variable COQCORELIB,
use ROCQRUNTIMELIB instead.
[deprecated-coq-env-var,deprecated-since-9.0,deprecated,default]
File "/tmp/tmpqhcfve5d/Top/bug_01.v", line 1130, characters 88-94:
Error:
In environment
cf : checker_flags
Σ : global_env_ext
wfΣ : wf Σ
x : ws_pair
y : ws_pair
redctx : red_ctx_alpha x.π1 y.π1
The term "redctx" has type "red_ctx_alpha x.π1 y.π1"
while it is expected to have type "All2_fold ?P ?Γ ?Γ'".


�[93mIntermediate code not saved.�[0m
Failed to do everything at once; trying one at a time.
Admitting definitions unsuccessful.
No successful changes.

I will now attempt to add Proof using lines
�[92m
Adding Proof using lines successful.�[0m
Failed to do everything at once; trying one at a time.
Adding Proof using lines unsuccessful.
No successful changes.

I will now attempt to export modules
Module exportation unsuccessful.

I will now attempt to split imports and exports
Import/Export splitting unsuccessful.

I will now attempt to split := definitions
One-line definition splitting unsuccessful.

I will now attempt to remove all lines, one at a time

If you have any comments on your experience of the minimizer, please share them in a reply (possibly tagging @JasonGross).
If you believe there's a bug in the bug minimizer, please report it on the bug minimizer issue tracker.

Copy link
Contributor
coqbot-app bot commented May 27, 2025
Minimization interrupted by timeout, being automatically continued. Partially Minimized File /home/runner/work/run-coq-bug-minimizer/run-coq-bug-minimizer/builds/coq/coq-failing/_build_ci/metarocq/pcuic/theories/PCUICConfluence.v in 5h 15m 7s (from ci-metarocq) (interrupted by timeout, being automatically continued) (full log on GitHub Actions - verbose log)
⭐ ⏱️ Partially Minimized Coq File (timeout) (truncated to first and last 32KiB; full 71KiB file on GitHub Actions Artifacts under bug.v)
(* -*- mode: coq; coq-prog-args: ("-emacs" "-q" "-w" "-deprecated-native-compiler-option" "-native-compiler" "no" "-coqlib" "/github/workspace/builds/coq/coq-failing/_install_ci/lib/coq//" "-R" "/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/utils/theories" "MetaRocq.Utils" "-R" "/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/common/theories" "MetaRocq.Common" "-R" "/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/pcuic/theories" "MetaRocq.PCUIC" "-Q" "/github/workspace/cwd" "Top" "-Q" "/github/workspace/builds/coq/coq-failing/_install_ci/lib/coq///user-contrib/Equations" "Equations" "-Q" "/github/workspace/builds/coq/coq-failing/_install_ci/lib/coq///user-contrib/Ltac2" "Ltac2" "-Q" "/github/workspace/builds/coq/coq-failing/_install_ci/lib/coq///user-contrib/Stdlib" "Stdlib" "-top" "Top.bug_01") -*- *)
(* File reduced by coq-bug-minimizer from original input, then from 3959 lines to 98 lines, then from 111 lines to 3187 lines, then from 3191 lines to 96 lines, then from 107 lines to 1813 lines, then from 1818 lines to 359 lines, then from 369 lines to 1502 lines, then from 1506 lines to 524 lines, then from 535 lines to 3221 lines, then from 3222 lines to 656 lines, then from 667 lines to 2894 lines, then from 2900 lines to 656 lines, then from 667 lines to 1321 lines, then from 1327 lines to 874 lines, then from 883 lines to 675 lines, then from 686 lines to 2746 lines, then from 2745 lines to 687 lines, then from 698 lines to 3155 lines, then from 3155 lines to 745 lines, then from 756 lines to 1586 lines, then from 1589 lines to 869 lines, then from 880 lines to 2395 lines, then from 2394 lines to 885 lines, then from 895 lines to 2754 lines, then from 2755 lines to 1157 lines, then from 1161 lines to 1145 lines, then from 1156 lines to 1809 lines, then from 1813 lines to 1200 lines, then from 1211 lines to 4024 lines, then from 4021 lines to 1355 lines, then from 1366 lines to 3048 lines, then from 3051 lines to 1938 lines *)
(* coqc version 9.1+alpha compiled with OCaml 4.14.2
   coqtop version runner-t7b1znuaq-project-4504-concurrent-2:/builds/coq/coq/_build/default,(HEAD detached at cdd06d0a2f356e) (cdd06d0a2f356e0c02e2d20356562b7deae4cf15)
   Expected coqc runtime on this file: 1.560 sec *)









Require Corelib.Init.Ltac.
Require Stdlib.Unicode.Utf8_core.
Require Stdlib.Unicode.Utf8.
Require Corelib.Numbers.BinNums.
Require Stdlib.Numbers.BinNums.
Require Stdlib.Logic.EqdepFacts.
Require Stdlib.Logic.Eqdep_dec.
Require Corelib.Classes.RelationClasses.
Require Stdlib.Classes.RelationClasses.
Require Corelib.Classes.Morphisms.
Require Stdlib.Classes.Morphisms.
Require Corelib.Setoids.Setoid.
Require Stdlib.Setoids.Setoid.
Require Stdlib.Classes.DecidableClass.
Require Stdlib.Logic.HLevelsBase.
Require Stdlib.Bool.Bool.
Require Stdlib.Structures.Equalities.
Require Corelib.Relations.Relation_Definitions.
Require Stdlib.Relations.Relation_Definitions.
Require Stdlib.Relations.Relation_Operators.
Require Stdlib.Relations.Operators_Properties.
Require Stdlib.Relations.Relations.
Require Stdlib.Structures.Orders.
Require Corelib.Program.Basics.
Require Stdlib.Program.Basics.
Require Stdlib.Structures.OrdersTac.
Require Stdlib.Structures.OrdersFacts.
Require Stdlib.Structures.GenericMinMax.
Require Corelib.Classes.Morphisms_Prop.
Require Stdlib.Classes.Morphisms_Prop.
Require Stdlib.Numbers.NumPrelude.
Require Stdlib.Numbers.NatInt.NZAxioms.
Require Stdlib.Numbers.NatInt.NZBase.
Require Stdlib.Numbers.NatInt.NZAdd.
Require Stdlib.Numbers.NatInt.NZMul.
Require Stdlib.Logic.Decidable.
Require Stdlib.Numbers.NatInt.NZOrder.
Require Stdlib.Numbers.NatInt.NZAddOrder.
Require Stdlib.Numbers.NatInt.NZMulOrder.
Require Stdlib.Numbers.NatInt.NZParity.
Require Stdlib.Numbers.NatInt.NZPow.
Require Stdlib.Numbers.NatInt.NZSqrt.
Require Stdlib.Numbers.NatInt.NZLog.
Require Stdlib.Numbers.NatInt.NZDiv.
Require Stdlib.Numbers.NatInt.NZGcd.
Require Stdlib.Numbers.NatInt.NZBits.
Require Stdlib.Numbers.Natural.Abstract.NAxioms.
Require Stdlib.Numbers.Natural.Abstract.NBase.
Require Stdlib.Numbers.Natural.Abstract.NAdd.
Require Stdlib.Numbers.Natural.Abstract.NOrder.
Require Stdlib.Numbers.Natural.Abstract.NAddOrder.
Require Stdlib.Numbers.Natural.Abstract.NMulOrder.
Require Stdlib.Numbers.Natural.Abstract.NSub.
Require Stdlib.Numbers.Natural.Abstract.NMaxMin.
Require Stdlib.Numbers.Natural.Abstract.NParity.
Require Stdlib.Numbers.Natural.Abstract.NPow.
Require Stdlib.Numbers.Natural.Abstract.NSqrt.
Require Stdlib.Numbers.Natural.Abstract.NLog.
Require Stdlib.Numbers.Natural.Abstract.NDiv.
Require Stdlib.Numbers.Natural.Abstract.NDiv0.
Require Stdlib.Numbers.Natural.Abstract.NGcd.
Require Stdlib.Numbers.Natural.Abstract.NLcm.
Require Stdlib.Numbers.Natural.Abstract.NLcm0.
Require Stdlib.Numbers.Natural.Abstract.NBits.
Require Stdlib.Numbers.Natural.Abstract.NProperties.
Require Stdlib.Arith.PeanoNat.
Require Corelib.BinNums.PosDef.
Require Stdlib.BinNums.PosDef.
Require Stdlib.PArith.BinPosDef.
Require Stdlib.PArith.BinPos.
Require Stdlib.PArith.Pnat.
Require Corelib.BinNums.NatDef.
Require Stdlib.BinNums.NatDef.
Require Stdlib.NArith.BinNatDef.
Require Stdlib.NArith.BinNat.
Require Stdlib.Numbers.Integer.Abstract.ZAxioms.
Require Stdlib.Numbers.Integer.Abstract.ZBase.
Require Stdlib.Numbers.Integer.Abstract.ZAdd.
Require Stdlib.Numbers.Integer.Abstract.ZMul.
Require Stdlib.Numbers.Integer.Abstract.ZLt.
Require Stdlib.Numbers.Integer.Abstract.ZAddOrder.
Require Stdlib.Numbers.Integer.Abstract.ZMulOrder.
Require Stdlib.Numbers.Integer.Abstract.ZMaxMin.
Require Stdlib.Numbers.Integer.Abstract.ZSgnAbs.
Require Stdlib.Numbers.Integer.Abstract.ZParity.
Require Stdlib.Numbers.Integer.Abstract.ZPow.
Require Stdlib.Numbers.Integer.Abstract.ZDivTrunc.
Require Stdlib.Numbers.Integer.Abstract.ZDivFloor.
Require Stdlib.Numbers.Integer.Abstract.ZGcd.
Require Stdlib.Numbers.Integer.Abstract.ZLcm.
Require Stdlib.Numbers.Integer.Abstract.ZBits.
Require Stdlib.Numbers.Integer.Abstract.ZProperties.
Require Corelib.BinNums.IntDef.
Require Stdlib.BinNums.IntDef.
Require Stdlib.ZArith.BinIntDef.
Require Stdlib.ZArith.BinInt.
Require Corelib.Numbers.Cyclic.Int63.CarryType.
Require Stdlib.Numbers.Cyclic.Int63.CarryType.
Require Stdlib.Numbers.Cyclic.Abstract.DoubleType.
Require Stdlib.Arith.Factorial.
Require Stdlib.Arith.Between.
Require Stdlib.Arith.Peano_dec.
Require Stdlib.Arith.Compare_dec.
Require Stdlib.Arith.EqNat.
Require Stdlib.Arith.Wf_nat.
Require Stdlib.Arith.Arith_base.
Require Stdlib.NArith.Nnat.
Require Stdlib.setoid_ring.Ring_theory.
Require Corelib.Lists.ListDef.
Require Stdlib.Lists.ListDef.
Require Stdlib.Lists.List.
Require Stdlib.setoid_ring.BinList.
Require Stdlib.setoid_ring.Ring_polynom.
Require Stdlib.Lists.ListTactics.
Require Stdlib.setoid_ring.InitialRing.
Require Stdlib.setoid_ring.Ring_tac.
Require Stdlib.setoid_ring.Ring_base.
Require Stdlib.setoid_ring.Ring.
Require Stdlib.setoid_ring.ArithRing.
Require Stdlib.Arith.Arith.
Require Stdlib.ZArith.Znat.
Require Stdlib.micromega.ZifyClasses.
Require Stdlib.ZArith.Zeven.
Require Stdlib.micromega.ZifyInst.
Require Stdlib.micromega.Zify.
Require Stdlib.omega.PreOmega.
Require Stdlib.micromega.OrderedRing.
Require Stdlib.NArith.Ndiv_def.
Require Stdlib.NArith.Nsqrt_def.
Require Stdlib.NArith.Ngcd_def.
Require Stdlib.NArith.NArith_base.
Require Stdlib.setoid_ring.NArithRing.
Require Stdlib.NArith.NArith.
Require Stdlib.micromega.Env.
Require Stdlib.micromega.EnvRing.
Require Stdlib.micromega.Refl.
Require Stdlib.micromega.Tauto.
Require Stdlib.micromega.RingMicromega.
Require Stdlib.ZArith.Zpow_def.
Require Stdlib.setoid_ring.ZArithRing.
Require Stdlib.micromega.ZCoeff.
Require Stdlib.ZArith.Zcompare.
Require Stdlib.ZArith.Zorder.
Require Stdlib.ZArith.Zmisc.
Require Stdlib.ZArith.Wf_Z.
Require Corelib.Init.Sumbool.
Require Stdlib.Init.Sumbool.
Require Stdlib.ZArith.ZArith_dec.
Require Stdlib.ZArith.Zbool.
Require Stdlib.ZArith.Zabs.
Require Stdlib.ZArith.Zcomplements.
Require Stdlib.ZArith.Zdiv.
Require Stdlib.micromega.VarMap.
Require Stdlib.micromega.ZMicromega.
Require Stdlib.micromega.DeclConstantZ.
Require Stdlib.micromega.Lia.
Require Stdlib.ZArith.Zdivisibility.
Require Stdlib.ZArith.Zpower.
Require Stdlib.ZArith.Zminmax.
Require Stdlib.ZArith.Zmin.
Require Stdlib.ZArith.Zmax.
Require Stdlib.ZArith.auxiliary.
Require Stdlib.ZArith.Zhints.
Require Stdlib.ZArith.ZArith_base.
Require Stdlib.setoid_ring.Algebra_syntax.
Require Stdlib.setoid_ring.Ncring.
Require Stdlib.setoid_ring.Ncring_polynom.
Require Stdlib.setoid_ring.Ncring_initial.
Require Stdlib.setoid_ring.Ncring_tac.
Require Stdlib.setoid_ring.Cring.
Require Stdlib.ZArith.Znumtheory.
Require Stdlib.ZArith.Zpow_facts.
Require Stdlib.ZArith.Zgcd_alt.
Require Stdlib.omega.OmegaLemmas.
Require Stdlib.micromega.ZArith_hints.
Require Stdlib.ZArith.Zcong.
Require Stdlib.ZArith.Zdiv_facts.
Require Stdlib.PArith.POrderedType.
Require Stdlib.PArith.PArith.
Require Stdlib.btauto.Algebra.
Require Stdlib.btauto.Reflect.
Require Stdlib.btauto.Btauto.
Require Stdlib.ZArith.Zbitwise.
Require Stdlib.ZArith.ZModOffset.
Require Stdlib.ZArith.ZArith.
Require Corelib.Numbers.Cyclic.Int63.PrimInt63.
Require Stdlib.Numbers.Cyclic.Int63.PrimInt63.
Require Corelib.Numbers.Cyclic.Int63.Uint63Axioms.
Require Stdlib.Numbers.Cyclic.Int63.Uint63Axioms.
Require Stdlib.Numbers.Cyclic.Int63.Uint63.
Require Corelib.Floats.PrimFloat.
Require Stdlib.Floats.PrimFloat.
Require Corelib.Floats.FloatAxioms.
Require Stdlib.Floats.FloatAxioms.
Require Corelib.Init.Nat.
Require Stdlib.Init.Nat.
Require Corelib.Init.Byte.
Require Stdlib.Init.Byte.
Require Stdlib.Strings.Byte.
Require Stdlib.Strings.Ascii.
Require Stdlib.Strings.String.
Require Corelib.extraction.Extraction.
Require Stdlib.extraction.Extraction.
Require Equations.Init.
Require Equations.Signature.
Require Equations.CoreTactics.
Require Equations.Prop.SigmaNotations.
Require Equations.Prop.Logic.
Require Equations.Prop.Classes.
Require Corelib.Program.Tactics.
Require Stdlib.Program.Tactics.
Require Equations.Prop.EqDec.
Require Equations.Prop.DepElim.
Require Equations.Prop.Constants.
Require Stdlib.Vectors.Fin.
Require 
10000
Stdlib.Vectors.VectorDef.
Require Stdlib.Vectors.VectorSpec.
Require Stdlib.Vectors.VectorEq.
Require Stdlib.Vectors.Vector.
Require Stdlib.Vectors.Bvector.
Require Stdlib.Wellfounded.Disjoint_Union.
Require Stdlib.Wellfounded.Inclusion.
Require Stdlib.Wellfounded.Inverse_Image.
Require Stdlib.Wellfounded.Transitive_Closure.
Require Stdlib.Wellfounded.List_Extension.
Require Stdlib.Wellfounded.Lexicographic_Exponentiation.
Require Stdlib.Wellfounded.Lexicographic_Product.
Require Stdlib.Wellfounded.Union.
Require Stdlib.Wellfounded.Well_Ordering.
Require Stdlib.Wellfounded.Wellfounded.
Require Corelib.Program.Wf.
Require Stdlib.Program.Wf.
Require Stdlib.Logic.FunctionalExtensionality.
Require Equations.Prop.Subterm.
Require Equations.Prop.FunctionalInduction.
Require Equations.Prop.Tactics.
Require Equations.Prop.NoConfusion.
Require Equations.Prop.EqDecInstances.
Require Equations.Prop.Loader.
Require Equations.Prop.Telescopes.
Require Equations.Prop.Equations.
Require MetaRocq.Utils.MRPrelude.
Require Corelib.ssr.ssreflect.
Require Stdlib.ssr.ssreflect.
Require MetaRocq.Utils.MRReflect.
Require Corelib.ssr.ssrbool.
Require Stdlib.ssr.ssrbool.
Require Stdlib.Sets.Relations_1.
Require Stdlib.Sorting.Sorted.
Require Stdlib.Sorting.SetoidList.
Require Corelib.Classes.CRelationClasses.
Require Stdlib.Classes.CRelationClasses.
Require Equations.Type.Logic.
Require Equations.Type.Relation.
Require Equations.Type.Relation_Properties.
Require MetaRocq.Utils.MRRelations.
Require MetaRocq.Utils.ReflectEq.
Require MetaRocq.Utils.MRList.
Require MetaRocq.Utils.MRProd.
Require MetaRocq.Utils.MROption.
Require MetaRocq.Utils.MRSquash.
Require MetaRocq.Utils.All_Forall.
Require MetaRocq.Utils.MRArith.
Require Stdlib.Structures.OrderedType.
Require MetaRocq.Utils.MRCompare.
Require MetaRocq.Utils.MREquality.
Require Corelib.Init.Decimal.
Require Stdlib.Init.Decimal.
Require Stdlib.Numbers.DecimalString.
Require MetaRocq.Utils.ByteCompare.
Require MetaRocq.Utils.ByteCompareSpec.
Require Stdlib.Structures.OrdersAlt.
Require MetaRocq.Utils.bytestring.
Require MetaRocq.Utils.MRString.
Require MetaRocq.Utils.MRTactics.SpecializeBy.
Require MetaRocq.Utils.MRTactics.Zeta1.
Require MetaRocq.Utils.MRTactics.GeneralizeOverHoles.
Require MetaRocq.Utils.MRTactics.FindHyp.
Require MetaRocq.Utils.MRTactics.UniquePose.
Require MetaRocq.Utils.MRTactics.InHypUnderBindersDo.
Require MetaRocq.Utils.MRTactics.SpecializeUnderBindersBy.
Require MetaRocq.Utils.MRTactics.Head.
Require MetaRocq.Utils.MRTactics.DestructHyps.
Require MetaRocq.Utils.MRTactics.DestructHead.
Require MetaRocq.Utils.MRTactics.SpecializeAllWays.
Require MetaRocq.Utils.MRTactics.SplitInContext.
Require Corelib.Numbers.Cyclic.Int63.Sint63Axioms.
Require Stdlib.Numbers.Cyclic.Int63.Sint63Axioms.
Require Stdlib.Numbers.Cyclic.Int63.Sint63.
Require Corelib.Floats.SpecFloat.
Require Stdlib.Floats.SpecFloat.
Require Corelib.Floats.FloatOps.
Require Stdlib.Floats.FloatOps.
Require Corelib.Strings.PrimString.
Require Stdlib.Strings.PrimString.
Require Corelib.Strings.PrimStringAxioms.
Require Stdlib.Strings.PrimStringAxioms.
Require Stdlib.micromega.ZifyBool.
Require MetaRocq.Common.Reflect.
Require MetaRocq.Common.Primitive.
Axiom proof_admitted : False.
Tactic Notation "admit" := abstract case proof_admitted.
Import Stdlib.ssr.ssrbool.
Import MetaRocq.Utils.utils.
Import MetaRocq.Common.BasicAst.
Import MetaRocq.Common.Primitive.
Import MetaRocq.Common.Universes.

Module Type Term.

  Parameter Inline term : Type.

  Parameter Inline tRel : nat -> term.
  Parameter Inline tSort : Sort.t -> term.
  Parameter Inline tProd : aname -> term -> term -> term.
  Parameter Inline tLambda : aname -> term -> term -> term.
  Parameter Inline tLetIn : aname -> term -> term -> term -> term.

  Parameter Inline lift : nat -> nat -> term -> term.
  Parameter Inline subst : list term -> nat -> term -> term.
  Parameter Inline subst_instance_constr : UnivSubst term.

  Notation lift0 n := (lift n 0).
End Term.

Module Type TermDecide (Import T : Term).
End TermDecide.

Module TermDecideReflectInstances (Import T : Term) (Import TDec : TermDecide T).
End TermDecideReflectInstances.

Module Export Retroknowledge.

  Record t := mk_retroknowledge {
    retro_int63 : option kername;
    retro_float64 : option kername;
    retro_string : option kername;
    retro_array : option kername;
  }.

Module Environment (T : Term).

  Import T.
  #[global] Existing Instance subst_instance_constr.

  Definition judgment := judgment_ Sort.t term.

  
  Notation context_decl := (context_decl term).

  

  Definition vass x A : context_decl :=
    {| decl_name := x ; decl_body := None ; decl_type := A |}.

  

  Definition vdef x t A : context_decl :=
    {| decl_name := x ; decl_body := Some t ; decl_type := A |}.

  

  Definition context := list context_decl.

  Definition lift_context n k (Γ : context) : context :=
    fold_context_k (fun k' => lift n (k' + k)) Γ.

  Definition subst_context s k (Γ : context) : context :=
    fold_context_k (fun k' => subst s (k' + k)) Γ.

  Definition subst_telescope s k (Γ : context) : context :=
    mapi (fun k' decl => map_decl (subst s (k' + k)) decl) Γ.
Global Instance subst_instance_context : UnivSubst context. exact (map_context ∘ subst_instance). Defined.
Definition set_binder_name (na : aname) (x : context_decl) : context_decl. exact ({| decl_name := na;
       decl_body := decl_body x;
       decl_type := decl_type x |}). Defined.
Fixpoint context_assumptions (Γ : context) : nat. exact (match Γ with
    | [] => 0
    | d :: Γ =>
      match d.(decl_body) with
      | Some _ => context_assumptions Γ
      | None => S (context_assumptions Γ)
      end
    end). Defined.
Fixpoint smash_context (Γ Γ' : context) : context. exact (match Γ' with
    | {| decl_body := Some b |} :: Γ' => smash_context (subst_context [b] 0 Γ) Γ'
    | {| decl_body := None |} as d :: Γ' => smash_context (Γ ++ [d]) Γ'
    | [] => Γ
    end). Defined.

  Fixpoint extended_subst (Γ : context) (n : nat)
   :=
  match Γ with
  | nil => nil
  | cons d vs =>
    match decl_body d with
    | Some b =>
      
      let s := extended_subst vs n in
      
      let b' := lift (context_assumptions vs + n) #|s| b in
      
      let b' := subst s 0 b' in
      
      b' :: s
    | None => tRel n :: extended_subst vs (S n)
    end
  end.

  Definition expand_lets_k Γ k t :=
    (subst (extended_subst Γ 0) k (lift (context_assumptions Γ) (k + #|Γ|) t)).

  Definition expand_lets Γ t := expand_lets_k Γ 0 t.

  Definition expand_lets_k_ctx Γ k Δ :=
    (subst_context (extended_subst Γ 0) k (lift_context (context_assumptions Γ) (k + #|Γ|) Δ)).

  Definition expand_lets_ctx Γ Δ := expand_lets_k_ctx Γ 0 Δ.
Definition fix_context (m : mfixpoint term) : context. exact (List.rev (mapi (fun i d => vass d.(dname) (lift i 0 d.(dtype))) m)). Defined.

  

  
  Record constructor_body := {
    
    cstr_name : ident;
    
    cstr_args : context;
    
    cstr_indices : list term;
    
    cstr_type : term;
    
    cstr_arity : nat;
  }.

  
  Record projection_body := {
    
    proj_name : ident;
    
    proj_relevance : relevance;
    
    proj_type : term;
  }.

  
  Record one_inductive_body := {
    
    ind_name : ident;
    
    ind_indices : context;
    
    ind_sort : Sort.t;
    
    ind_type : term;
    
    ind_kelim : allowed_eliminations;
    
    ind_ctors : list constructor_body;
    
    ind_projs : list projection_body;
    
    ind_relevance : relevance }.

  
  Record mutual_inductive_body := {
    
    ind_finite : recursivity_kind;
    
    ind_npars : nat;
    
    ind_params : context;
    
    ind_bodies : list one_inductive_body ;
    
    ind_universes : universes_decl;
    
    ind_variance : option (list Universes.Variance.t) }.

  
  Record constant_body := {
    
    cst_type : term;
    
    cst_body : option term;
    
    cst_universes : universes_decl;
    
    cst_relevance : relevance }.

  
  Inductive global_decl :=
  | ConstantDecl : constant_body -> global_decl
  | InductiveDecl : mutual_inductive_body -> global_decl.

  Definition global_declarations := list (kername * global_decl).

  Record global_env := mk_global_env
    { universes : ContextSet.t;
      declarations : global_declarations;
      retroknowledge : Retroknowledge.t }.
Fixpoint lookup_global (Σ : global_declarations) (kn : kername) : option global_decl. exact (match Σ with
    | nil => None
    | d :: tl =>
      if kn == d.1 then Some d.2
      else lookup_global tl kn
    end). Defined.

  Definition lookup_env (Σ : global_env) (kn : kername) := lookup_global Σ.(declarations) kn.
Definition primitive_constant (Σ : global_env) (p : prim_tag) : option kername. exact (match p with
    | primInt => Σ.(retroknowledge).(Retroknowledge.retro_int63)
    | primFloat => Σ.(retroknowledge).(Retroknowledge.retro_float64)
    | primString => Σ.(retroknowledge).(Retroknowledge.retro_string)
    | primArray => Σ.(retroknowledge).(Retroknowledge.retro_array)
    end). Defined.
Definition tImpl (dom codom : term) : term. exact (tProd {| binder_name := nAnon; binder_relevance := rel_of_Type |}
      dom (lift 1 0 codom)). Defined.

  Definition array_uctx := ([nAnon], ConstraintSet.empty).

  Definition primitive_invariants (p : prim_tag) (cdecl : constant_body) :=
    match p with
    | primInt | primFloat | primString =>
     [/\ cdecl.(cst_type) = tSort Sort.type0, cdecl.(cst_body) = None &
          cdecl.(cst_universes) = Monomorphic_ctx]
    | primArray =>
      let s := sType (Universe.make' (Level.lvar 0)) in
      [/\ cdecl.(cst_type) = tImpl (tSort s) (tSort s), cdecl.(cst_body) = None &
        cdecl.(cst_universes) = Polymorphic_ctx array_uctx]
    end.
Definition global_env_ext : Type. exact (global_env * universes_decl). Defined.
Definition fst_ctx : global_env_ext -> global_env. exact (fst). Defined.
  Coercion fst_ctx : global_env_ext >-> global_env.

  

  Definition mkLambda_or_LetIn d t :=
    match d.(decl_body) with
    | None => tLambda d.(decl_name) d.(decl_type) t
    | Some b => tLetIn d.(decl_name) b d.(decl_type) t
    end.

  Definition it_mkLambda_or_LetIn (l : context) (t : term) :=
    List.fold_left (fun acc d => mkLambda_or_LetIn d acc) l t.
Fixpoint reln (l : list term) (p : nat) (Γ0 : list context_decl) {struct Γ0} : list term. exact (match Γ0 with
    | [] => l
    | {| decl_body := Some _ |} :: hyps => reln l (p + 1) hyps
    | {| decl_body := None |} :: hyps => reln (tRel p :: l) (p + 1) hyps
    end). Defined.

  Definition to_extended_list_k Γ k := reln [] k Γ.
  Definition to_extended_list Γ := to_extended_list_k Γ 0.

  
  Inductive All_decls_alpha (P : term -> term -> Type) : context_decl -> context_decl -> Type :=
  | on_vass_alpha na na' t t' :
    eq_binder_annot na na' ->
    P t t' ->
    All_decls_alpha P (vass na t) (vass na' t')

  | on_vdef_alpha na na' b t b' t' :
    eq_binder_annot na na' ->
    P b b' ->
    P t t' ->
    All_decls_alpha P (vdef na b t) (vdef na' b' t').

End Environment.

Module Type EnvironmentSig (T : Term).
 Include Environment T.
End EnvironmentSig.

Module Type EnvironmentDecide (T : Term) (Import E : EnvironmentSig T).
End EnvironmentDecide.

Module EnvironmentDecideReflectInstances (T : Term) (Import E : EnvironmentSig T) (Import EDec : EnvironmentDecide T E).
End EnvironmentDecideReflectInstances.

Module Type TermUtils (T: Term) (E: EnvironmentSig T).

End TermUtils.
Module Export EnvironmentTyping.
Import Stdlib.ssr.ssrbool.
Import MetaRocq.Utils.utils.
Import MetaRocq.Common.config.
Import MetaRocq.Common.BasicAst.
Import MetaRocq.Common.Universes.

Module Lookup (T : Term) (E : EnvironmentSig T).
Import E.

  Definition declared_constant (Σ : global_env) id decl := In (id,ConstantDecl decl) (declarations Σ).

  Definition declared_minductive Σ mind decl := In (mind,InductiveDecl decl) (declarations Σ).

  Definition declared_inductive Σ ind mdecl decl :=
    declared_minductive Σ (inductive_mind ind) mdecl /\
    List.nth_error mdecl.(ind_bodies) (inductive_ind ind) = Some decl.

  Definition declared_constructor Σ cstr mdecl idecl cdecl :=
    declared_inductive Σ (fst cstr) mdecl idecl /\
    List.nth_error idecl.(ind_ctors) (snd cstr) = Some cdecl.

  Definition declared_projection Σ (proj : projection) mdecl idecl cdecl pdecl
  : Prop :=
    declared_constructor Σ (proj.(proj_ind), 0) mdecl idecl cdecl /\
    List.nth_error idecl.(ind_projs) proj.(proj_arg) = Some pdecl /\
    mdecl.(ind_npars) = proj.(proj_npars).

  Definition lookup_minductive_gen (lookup : kername -> option global_decl) mind :=
    match lookup mind with
    | Some (InductiveDecl decl) => Some decl
    | _ => None
    end.

  Definition lookup_inductive_gen lookup ind :=
    match lookup_minductive_gen lookup (inductive_mind ind) with
    | Some mdecl =>
      match nth_error mdecl.(ind_bodies) (inductive_ind ind) with
      | Some idecl => Some (mdecl, idecl)
      | None => None
      end
    | None => None
    end.

  Definition lookup_constructor_gen lookup ind k :=
    match lookup_inductive_gen lookup ind with
    | Some (mdecl, idecl) =>
      match nth_error idecl.(ind_ctors) k with
      | Some cdecl => Some (mdecl, idecl, cdecl)
      | None => None
      end
    | _ => None
    end.
Definition global_ext_levels (Σ : global_env_ext) : LevelSet.t.
Admitted.
Definition global_ext_constraints (Σ : global_env_ext) : ConstraintSet.t.
Admitted.

  Coercion global_ext_constraints : global_env_ext >-> ConstraintSet.t.

  Definition consistent_instance `{checker_flags} (lvs : LevelSet.t) (φ : ConstraintSet.t) uctx (u : Instance.t) :=
    match uctx with
    | Monomorphic_ctx => List.length u = 0
    | Polymorphic_ctx c =>

      forallb (fun l => LevelSet.mem l lvs) u /\
      List.length u = List.length c.1 /\
      valid_constraints φ (subst_instance_cstrs u c.2)
    end.

  Definition consistent_instance_ext `{checker_flags} Σ :=
    consistent_instance (global_ext_levels Σ) (global_ext_constraints Σ).

  Definition wf_universe Σ (u : Universe.t) : Prop :=
    forall l, LevelExprSet.In l u -> LevelSet.In (LevelExpr.get_level l) (global_ext_levels Σ).

  Definition wf_sort Σ (s : sort) : Prop :=
    Sort.on_sort (wf_universe Σ) True s.

End Lookup.

Module Type LookupSig (T : Term) (E : EnvironmentSig T).
End LookupSig.

Module EnvTyping (T : Term) (E : EnvironmentSig T) (TU : TermUtils T E).
Import T.
Import E.

  Definition on_def_type (P : context -> judgment -> Type) Γ d :=
    P Γ (TypRel d.(dtype) d.(dname).(binder_relevance)).

  Definition on_def_body (P : context -> judgment -> Type) types Γ d :=
    P (Γ ,,, types) (TermTypRel d.(dbody) (lift0 #|types| d.(dtype)) d.(dname).(binder_relevance)).

  Definition lift_sorting checking sorting : judgment -> Type :=
    fun j => option_default (fun tm => checking tm (j_typ j)) (j_term j) (unit : Type) ×
                                ∑ s, sorting (j_typ j) s ×
                                  option_default (fun u => u = s) (j_univ j) True /\
                                  isSortRelOpt s (j_rel j).

  Notation typing_sort typing := (fun T s => typing T (tSort s)).

  Definition lift_typing0 typing := lift_sorting typing (typing_sort typing).
  Notation lift_typing1 typing := (fun Γ => lift_typing0 (typing Γ)).
  Notation lift_typing typing := (fun Σ Γ => lift_typing0 (typing Σ Γ)).

  Section TypeLocal.
    Context (typing : forall (Γ : context), judgment -> Type).

    Inductive All_local_env : context -> Type :=
    | localenv_nil :
        All_local_env []

    | localenv_cons_abs Γ na t :
        All_local_env Γ ->
        typing Γ (j_vass na t) ->
        All_local_env (Γ ,, vass na t)

    | localenv_cons_def Γ na b t :
        All_local_env Γ ->
        typing Γ (j_vdef na b t) ->
        All_local_env (Γ ,, vdef na b t).
  End TypeLocal.

  Section TypeCtxInst.
    Context (typing : forall (Γ : context), term -> term -> Type).

    Inductive ctx_inst (Γ : context) : list term -> context -> Type :=
    | ctx_inst_nil : ctx_inst Γ [] []
    | ctx_inst_ass na t i inst Δ :
        typing Γ i t ->
        ctx_inst Γ inst (subst_telescope [i] 0 Δ) ->
        ctx_inst Γ (i :: inst) (vass na t :: Δ)
    | ctx_inst_def na b t inst Δ :
        ctx_inst Γ inst (subst_telescope [b] 0 Δ) ->
        ctx_inst Γ inst (vdef na b t :: Δ).
  End TypeCtxInst.

End EnvTyping.

Module Type EnvTypingSig (T : Term) (E : EnvironmentSig T) (TU : TermUtils T E).
End EnvTypingSig.

Module Conversion (T : Term) (E : EnvironmentSig T) (TU : TermUtils T E) (ET : EnvTypingSig T E TU).
End Conversion.

Module Type ConversionSig (T : Term) (E : EnvironmentSig T) (TU : TermUtils T E) (ET : EnvTypingSig T E TU).
End ConversionSig.

Module GlobalMaps (T: Term) (E: EnvironmentSig T) (TU : TermUtils T E) (ET: EnvTypingSig T E TU) (C: ConversionSig T E TU ET) (L: LookupSig T E).
Import T.
Import E.

  Section GlobalMaps.
    Context (Pcmp: global_env_ext -> context -> conv_pb -> term -> term -> Type).
    Context (P : global_env_ext -> context -> judgment -> Type).
Definition on_global_env (g : global_env) : Type.
Admitted.

  End GlobalMaps.

End GlobalMaps.

Module Type GlobalMapsSig (T: Term) (E: EnvironmentSig T) (TU : TermUtils T E) (ET: EnvTypingSig T E TU) (C: ConversionSig T E TU ET) (L: LookupSig T E).
End GlobalMapsSig.

Module Type ConversionParSig (T : Term) (E : EnvironmentSig T) (TU : TermUtils T E) (ET : EnvTypingSig T E TU).

End ConversionParSig.
Module Export PCUICPrimitive.
Import MetaRocq.Common.Primitive.

Record array_model {term : Type} :=
  { array_level : Level.t;
    array_type : term;
    array_default : term;
    array_value : list term }.

Arguments array_model : clear implicits.

Inductive prim_model (term : Type) : prim_tag -> Type :=
| primIntModel (i : PrimInt63.int) : prim_model term primInt
| primFloatModel (f : PrimFloat.float) : prim_model term primFloat
| primStringModel (s : PrimString.string) : prim_model term primString
| primArrayModel (a : array_model term) : prim_model term primArray.

Arguments primIntModel {term}.
Arguments primFloatModel {term}.
Arguments primStringModel {term}.
Arguments primArrayModel {term}.

Definition prim_val term := ∑ t : prim_tag, prim_model term t.
Definition prim_val_tag {term} (s : prim_val term) := s.π1.

Inductive onPrims {term} (eq_term : term -> term -> Type) Re : prim_val term -> prim_val term -> Type :=
  | onPrimsInt i : onPrims eq_term Re (primInt; primIntModel i) (primInt; primIntModel i)
  | onPrimsFloat f : onPrims eq_term Re (primFloat; primFloatModel f) (primFloat; primFloatModel f)
  | onPrimsString s : onPrims eq_term Re (primString; primStringModel s) (primString; primStringModel s)
  | onPrimsArray a a' :
    Re (Universe.make' a.(array_level)) (Universe.make' a'.(array_level)) ->
    eq_term a.(array_default) a'.(array_default) ->
    eq_term a.(array_type) a'.(array_type) ->
    All2 eq_term a.(array_value) a'.(array_value) ->
    onPrims eq_term Re (primArray; primArrayModel a) (primArray; primArrayModel a').
Definition mapu_array_model {term term'} (fl : Level.t -> Level.t) (f : term -> term')
  (ar : array_model term) : array_model term'.
admit.
Defined.

Equations mapu_prim {term term'} (f : Level.t -> Level.t) (g : term -> term')
  (p : PCUICPrimitive.prim_val term) : PCUICPrimitive.prim_val term' :=
| _, _, (primInt; primIntModel i) => (primInt; primIntModel i)
| _, _, (primFloat; primFloatModel fl) => (primFloat; primFloatModel fl)
| _, _, (primString; primStringModel s) => (primString; primStringModel s)
| f, g, (primArray; primArrayModel ar) =>
  (primArray; primArrayModel (mapu_array_model f g ar)).
Notation map_prim := (mapu_prim id).

Equations test_prim {term} (p : term -> bool) (p : prim_val term) : bool :=
| p, (primInt; _) => true
| p, (primFloat; _) => true
| p, (primString; _) => true
| p, (primArray; primArrayModel ar) =>
  List.forallb p ar.(array_value) && p ar.(array_default) && p ar.(array_type).

Record predicate {term} := mk_predicate {
  pparams : list term;
  puinst : Instance.t;
  pcontext : list (context_decl term);

  preturn : term;  }.
Arguments predicate : clear implicits.

Section map_predicate_k.
  Context {term : Type}.
  Context (uf : Instance.t -> Instance.t).
  Context (f : nat -> term -> term).

  Definition map_predicate_k k (p : predicate term) :=
    {| pparams := map (f k) p.(pparams);
        puinst := uf p.(puinst);
        pcontext := p.(pcontext);
        preturn := f (#|p.(pcontext)| + k) p.(preturn) |}.

  Definition test_predicate_k (instp : Instance.t -> bool)
    (p : nat -> term -> bool) k (pred : predicate term) :=
    instp pred.(puinst) && forallb (p k) pred.(pparams) &&
    test_context_k p #|pred.(pparams)| pred.(pcontext) &&
    p (#|pred.(pcontext)| + k) pred.(preturn).

End map_predicate_k.

Section Branch.
  Context {term : Type}.

  Record branch := mk_branch {
    bcontext : list (context_decl term);

    bbody : term;  }.

  Definition test_branch_k (pred : predicate term) (p : nat -> term -> bool) k (b : branch) :=
    test_context_k p #|pred.(pparams)| b.(bcontext) && p (#|b.(bcontext)| + k) b.(bbody).

End Branch.
Arguments branch : clear implicits.

Section map_branch_k.
  Context {term term' : Type}.
  Context (f : nat -> term -> term').
  Context (g : list (BasicAst.context_decl term) -> list (BasicAst.context_decl term')).
  Definition map_branch_k k (b : branch term) :=
  {| bcontext := g b.(bcontext);
     bbody := f (#|b.(bcontext)| + k) b.(bbody) |}.
End map_branch_k.

Notation map_branches_k f h k brs :=
  (List.map (map_branch_k f h k) brs).

Notation test_branches_k p test k brs :=
  (List.forallb (test_branch_k p test k) brs).

Inductive term :=
| tRel (n : nat)
| tVar (i : ident)
| tEvar (n : nat) (l : list term)
| tSort (u : sort)
| tProd (na : aname) (A B : term)
| tLambda (na : aname) (A t : term)
| tLetIn (na : aname) (b B t : term)
| tApp (u v : term)
| tConst (k : kername) (ui : Instance.t)
| tInd (ind : inductive) (ui : Instance.t)
| tConstruct (ind : inductive) (n : nat) (ui : Instance.t)
| tCase (indn : case_info) (p : predicate term) (c : term) (brs : list (branch term))
| tProj (p : projection) (c : term)
| tFix (mfix : mfixpoint term) (idx : nat)
| tCoFix (mfix : mfixpoint term) (idx : nat)
| tPrim (prim : prim_val term).

Fixpoint mkApps t us :=
  match us with
  | nil => t
  | u :: us => mkApps (tApp t u) us
  end.

Definition isLambda t :=
  match t with
  | tLambda _ _ _ => true
  |

[...]

in
  let inddecl :=
    {| decl_name :=
      {| binder_name := nNamed (ind_name idecl); binder_relevance := idecl.(ind_relevance) |};
       decl_body := None;
       decl_type := indty |}
  in (inddecl :: ictx).

Definition inst_case_context params puinst (pctx : context) :=
  subst_context (List.rev params) 0 (subst_instance puinst pctx).

Definition inst_case_predicate_context (p : predicate term) :=
  inst_case_context p.(pparams) p.(puinst) p.(pcontext).

Definition inst_case_branch_context (p : predicate term) (br : branch term) :=
  inst_case_context p.(pparams) p.(puinst) br.(bcontext).

Definition iota_red npar p args br :=
  subst (List.rev (List.skipn npar args)) 0
    (expand_lets (inst_case_branch_context p br) (bbody br)).

Definition pre_case_predicate_context_gen ind mdecl idecl params puinst : context :=
  inst_case_context params puinst (ind_predicate_context ind mdecl idecl).

Definition case_predicate_context_gen ind mdecl idecl params puinst pctx :=
  map2 set_binder_name pctx (pre_case_predicate_context_gen ind mdecl idecl params puinst).

Definition case_predicate_context ind mdecl idecl p : context :=
  case_predicate_context_gen ind mdecl idecl p.(pparams) p.(puinst) (forget_types p.(pcontext)).

Definition cstr_branch_context ind mdecl cdecl : context :=
  expand_lets_ctx mdecl.(ind_params)
    (subst_context (inds (inductive_mind ind) (abstract_instance mdecl.(ind_universes))
       mdecl.(ind_bodies)) #|mdecl.(ind_params)|
      cdecl.(cstr_args)).

Definition pre_case_branch_context_gen ind mdecl cdecl params puinst : context :=
  inst_case_context params puinst (cstr_branch_context ind mdecl cdecl).

Definition case_branch_context_gen ind mdecl params puinst pctx cdecl :=
  map2 set_binder_name pctx (pre_case_branch_context_gen ind mdecl cdecl params puinst).

Definition case_branch_type_gen ind mdecl (idecl : one_inductive_body) params puinst bctx ptm i cdecl : context * term :=
  let cstr := tConstruct ind i puinst in
  let args := to_extended_list cdecl.(cstr_args) in
  let cstrapp := mkApps cstr (map (lift0 #|cdecl.(cstr_args)|) params ++ args) in
  let brctx := case_branch_context_gen ind mdecl params puinst bctx cdecl in
  let upars := subst_instance puinst mdecl.(ind_params) in
  let indices :=
    (map (subst (List.rev params) #|cdecl.(cstr_args)|)
      (map (expand_lets_k upars #|cdecl.(cstr_args)|)
        (map (subst (inds (inductive_mind ind) puinst mdecl.(ind_bodies))
                    (#|mdecl.(ind_params)| + #|cdecl.(cstr_args)|))
          (map (subst_instance puinst) cdecl.(cstr_indices))))) in
  let ty := mkApps (lift0 #|cdecl.(cstr_args)| ptm) (indices ++ [cstrapp]) in
  (brctx, ty).

Definition case_branch_type ind mdecl idecl p (b : branch term) ptm i cdecl : context * term :=
  case_branch_type_gen ind mdecl idecl p.(pparams) p.(puinst) (forget_types b.(bcontext)) ptm i cdecl.

Definition idecl_binder idecl :=
  {| decl_name :=
    {| binder_name := nNamed idecl.(ind_name);
        binder_relevance := idecl.(ind_relevance) |};
     decl_body := None;
     decl_type := idecl.(ind_type) |}.

Definition wf_predicate_gen mdecl idecl (pparams : list term) (pcontext : list aname) : Prop :=
  let decl := idecl_binder idecl in
  (#|pparams| = mdecl.(ind_npars)) /\
  (Forall2 (fun na decl => eq_binder_annot na decl.(decl_name))
    pcontext (decl :: idecl.(ind_indices))).

Definition wf_predicate mdecl idecl (p : predicate term) : Prop :=
  wf_predicate_gen mdecl idecl p.(pparams) (forget_types p.(pcontext)).

Definition wf_branch_gen cdecl (bctx : list aname) : Prop :=
  (Forall2 (fun na decl => eq_binder_annot na decl.(decl_name))
    bctx cdecl.(cstr_args)).

Definition wf_branch cdecl (b : branch term) : Prop :=
  wf_branch_gen cdecl (forget_types b.(bcontext)).

Definition wf_branches idecl (brs : list (branch term)) : Prop :=
  Forall2 wf_branch idecl.(ind_ctors) brs.

Definition fix_subst (l : mfixpoint term) :=
  let fix aux n :=
      match n with
      | 0 => []
      | S n => tFix l n :: aux n
      end
  in aux (List.length l).

Definition unfold_fix (mfix : mfixpoint term) (idx : nat) :=
  match List.nth_error mfix idx with
  | Some d => Some (d.(rarg), subst0 (fix_subst mfix) d.(dbody))
  | None => None
  end.

Definition cofix_subst (l : mfixpoint term) :=
  let fix aux n :=
      match n with
      | 0 => []
      | S n => tCoFix l n :: aux n
      end
  in aux (List.length l).

Definition unfold_cofix (mfix : mfixpoint term) (idx : nat) :=
  match List.nth_error mfix idx with
  | Some d => Some (d.(rarg), subst0 (cofix_subst mfix) d.(dbody))
  | None => None
  end.

Definition is_constructor n ts :=
  match List.nth_error ts n with
  | Some a => isConstruct_app a
  | None => false
  end.
Definition cmp_universe_instance (cmp_univ : Universe.t -> Universe.t -> Prop) : Instance.t -> Instance.t -> Prop.
Admitted.

Definition cmp_universe_variance (cmp_univ : conv_pb -> Universe.t -> Universe.t -> Prop) pb v u u' :=
  match v with
  | Variance.Irrelevant => True
  | Variance.Covariant => on_rel (cmp_univ pb) Universe.make' u u'
  | Variance.Invariant => on_rel (cmp_univ Conv) Universe.make' u u'
  end.

Definition cmp_universe_instance_variance cmp_univ pb v u u' :=
  Forall3 (cmp_universe_variance cmp_univ pb) v u u'.

Definition global_variance_gen lookup gr napp :=
  match gr with
  | IndRef ind =>
    match lookup_inductive_gen lookup ind with
    | Some (mdecl, idecl) =>
      match destArity [] idecl.(ind_type) with
      | Some (ctx, _) => if (context_assumptions ctx) <=? napp then
          match mdecl.(ind_variance) with
          | Some var => Variance var
          | None => AllEqual
          end
        else AllEqual
      | None => AllEqual
      end
    | None => AllEqual
    end
  | ConstructRef ind k =>
    match lookup_constructor_gen lookup ind k with
    | Some (mdecl, idecl, cdecl) =>
      if (cdecl.(cstr_arity) + mdecl.(ind_npars))%nat <=? napp then

        AllIrrelevant
      else AllEqual
    | _ => AllEqual
    end
  | _ => AllEqual
  end.

Definition cmp_opt_variance cmp_univ pb v :=
  match v with
  | AllEqual => cmp_universe_instance (cmp_univ Conv)
  | AllIrrelevant => fun l l' => #|l| = #|l'|
  | Variance v => fun u u' => cmp_universe_instance (cmp_univ Conv) u u' \/ cmp_universe_instance_variance cmp_univ pb v u u'
  end.

Definition cmp_global_instance_gen Σ cmp_universe pb gr napp :=
  cmp_opt_variance cmp_universe pb (global_variance_gen Σ gr napp).

Notation cmp_global_instance Σ := (cmp_global_instance_gen (lookup_env Σ)).

Inductive eq_decl_upto_names : context_decl -> context_decl -> Type :=
  | compare_vass {na na' T} :
    eq_binder_annot na na' -> eq_decl_upto_names (vass na T) (vass na' T)
  | compare_vdef {na na' b T} :
    eq_binder_annot na na' -> eq_decl_upto_names (vdef na b T) (vdef na' b T).

Notation eq_context_upto_names := (All2 eq_decl_upto_names).

Definition shiftnP k p i :=
  (i <? k) || p (i - k).
Fixpoint on_free_vars (p : nat -> bool) (t : term) : bool.
Admitted.

Definition on_free_vars_decl P d :=
  test_decl (on_free_vars P) d.

Definition on_free_vars_ctx P ctx :=
  alli (fun k => (on_free_vars_decl (shiftnP k P))) 0 (List.rev ctx).

Notation is_open_term Γ := (on_free_vars (shiftnP #|Γ| xpred0)).
Notation is_closed_context := (on_free_vars_ctx xpred0).
Definition set_preturn (p : predicate term) (pret' : term) : predicate term.
Admitted.
Definition set_pparams (p : predicate term) (pars' : list term) : predicate term.
Admitted.
Definition on_one_decl (P : term -> term -> Type)
  (d : context_decl) (d' : context_decl) : Type.
Admitted.

Section OnOne_local_2.
  Context (P : forall (Γ : context), context_decl -> context_decl -> Type).

  Inductive OnOne2_local_env : context -> context -> Type :=
  | onone2_localenv_cons_abs Γ na na' t t' :
      P Γ (vass na t) (vass na' t') ->
      OnOne2_local_env (Γ ,, vass na t) (Γ ,, vass na' t')
  | onone2_localenv_def Γ na na' b b' t t' :
      P Γ (vdef na b t) (vdef na' b' t') ->
      OnOne2_local_env (Γ ,, vdef na b t) (Γ ,, vdef na' b' t')
  | onone2_localenv_cons_tl Γ Γ' d :
      OnOne2_local_env Γ Γ' ->
      OnOne2_local_env (Γ ,, d) (Γ' ,, d).
End OnOne_local_2.
Arguments exist {_ _} _ _.
Import Equations.Type.Relation.

Reserved Notation " Σ ;;; Γ |- t ⇝ u " (at level 50, Γ, t, u at next level).

Definition set_array_default (ar : array_model term) (v : term) :=
  {| array_level := ar.(array_level);
     array_default := v;
     array_type := ar.(array_type);
     array_value := ar.(array_value) |}.

Definition set_array_type (ar : array_model term) (v : term) :=
  {| array_level := ar.(array_level);
     array_default := ar.(array_default);
     array_type := v;
     array_value := ar.(array_value) |}.

Definition set_array_value (ar : array_model term) (v : list term) :=
  {| array_level := ar.(array_level);
     array_default := ar.(array_default);
     array_type := ar.(array_type);
     array_value := v |}.

Inductive red1 (Σ : global_env) (Γ : context) : term -> term -> Type :=

| red_beta na t b a :
  Σ ;;; Γ |- tApp (tLambda na t b) a ⇝ b {0 := a}

| red_zeta na b t b' :
  Σ ;;; Γ |- tLetIn na b t b' ⇝ b' {0 := b}

| red_rel i body :
    option_map decl_body (nth_error Γ i) = Some (Some body) ->
    Σ ;;; Γ |- tRel i ⇝ lift0 (S i) body

| red_iota ci c u args p brs br :
    nth_error brs c = Some br ->
    #|args| = (ci.(ci_npar) + context_assumptions br.(bcontext))%nat ->
    Σ ;;; Γ |- tCase ci p (mkApps (tConstruct ci.(ci_ind) c u) args) brs
        ⇝ iota_red ci.(ci_npar) p args br

| red_fix mfix idx args narg fn :
    unfold_fix mfix idx = Some (narg, fn) ->
    is_constructor narg args = true ->
    Σ ;;; Γ |- mkApps (tFix mfix idx) args ⇝ mkApps fn args

| red_cofix_case ip p mfix idx args narg fn brs :
    unfold_cofix mfix idx = Some (narg, fn) ->
    Σ ;;; Γ |- tCase ip p (mkApps (tCoFix mfix idx) args) brs ⇝
         tCase ip p (mkApps fn args) brs

| red_cofix_proj p mfix idx args narg fn :
    unfold_cofix mfix idx = Some (narg, fn) ->
    Σ ;;; Γ |- tProj p (mkApps (tCoFix mfix idx) args) ⇝ tProj p (mkApps fn args)

| red_delta c decl body (isdecl : declared_constant Σ c decl) u :
    decl.(cst_body) = Some body ->
    Σ ;;; Γ |- tConst c u ⇝ subst_instance u body

| red_proj p args u arg:
    nth_error args (p.(proj_npars) + p.(proj_arg)) = Some arg ->
    Σ ;;; Γ |- tProj p (mkApps (tConstruct p.(proj_ind) 0 u) args) ⇝ arg

| abs_red_l na M M' N : Σ ;;; Γ |- M ⇝ M' -> Σ ;;; Γ |- tLambda na M N ⇝ tLambda na M' N
| abs_red_r na M M' N : Σ ;;; Γ ,, vass na N |- M ⇝ M' -> Σ ;;; Γ |- tLambda na N M ⇝ tLambda na N M'

| letin_red_def na b t b' r : Σ ;;; Γ |- b ⇝ r -> Σ ;;; Γ |- tLetIn na b t b' ⇝ tLetIn na r t b'
| letin_red_ty na b t b' r : Σ ;;; Γ |- t ⇝ r -> Σ ;;; Γ |- tLetIn na b t b' ⇝ tLetIn na b r b'
| letin_red_body na b t b' r : Σ ;;; Γ ,, vdef na b t |- b' ⇝ r -> Σ ;;; Γ |- tLetIn na b t b' ⇝ tLetIn na b t r

| case_red_param ci p params' c brs :
    OnOne2 (fun t u => Σ ;;; Γ |- t ⇝ u) p.(pparams) params' ->
    Σ ;;; Γ |- tCase ci p c brs ⇝ tCase ci (set_pparams p params') c brs

| case_red_return ci p preturn' c brs :
  Σ ;;; Γ ,,, inst_case_predicate_context p |- p.(preturn) ⇝ preturn' ->
  Σ ;;; Γ |- tCase ci p c brs ⇝ tCase ci (set_preturn p preturn') c brs

| case_red_discr ci p c c' brs :
  Σ ;;; Γ |- c ⇝ c' -> Σ ;;; Γ |- tCase ci p c brs ⇝ tCase ci p c' brs

| case_red_brs ci p c brs brs' :
    OnOne2 (fun br br' =>
      on_Trel_eq (fun t u => Σ ;;; Γ ,,, inst_case_branch_context p br |- t ⇝ u) bbody bcontext br br')
      brs brs' ->
    Σ ;;; Γ |- tCase ci p c brs ⇝ tCase ci p c brs'

| proj_red p c c' : Σ ;;; Γ |- c ⇝ c' -> Σ ;;; Γ |- tProj p c ⇝ tProj p c'

| app_red_l M1 N1 M2 : Σ ;;; Γ |- M1 ⇝ N1 -> Σ ;;; Γ |- tApp M1 M2 ⇝ tApp N1 M2
| app_red_r M2 N2 M1 : Σ ;;; Γ |- M2 ⇝ N2 -> Σ ;;; Γ |- tApp M1 M2 ⇝ tApp M1 N2

| prod_red_l na M1 M2 N1 : Σ ;;; Γ |- M1 ⇝ N1 -> Σ ;;; Γ |- tProd na M1 M2 ⇝ tProd na N1 M2
| prod_red_r na M2 N2 M1 : Σ ;;; Γ ,, vass na M1 |- M2 ⇝ N2 ->
                           Σ ;;; Γ |- tProd na M1 M2 ⇝ tProd na M1 N2

| evar_red ev l l' : OnOne2 (fun t u => Σ ;;; Γ |- t ⇝ u) l l' -> Σ ;;; Γ |- tEvar ev l ⇝ tEvar ev l'

| fix_red_ty mfix0 mfix1 idx :
    OnOne2 (on_Trel_eq (fun t u => Σ ;;; Γ |- t ⇝ u) dtype (fun x => (dname x, dbody x, rarg x))) mfix0 mfix1 ->
    Σ ;;; Γ |- tFix mfix0 idx ⇝ tFix mfix1 idx

| fix_red_body mfix0 mfix1 idx :
    OnOne2 (on_Trel_eq (fun t u => Σ ;;; Γ ,,, fix_context mfix0 |- t ⇝ u) dbody (fun x => (dname x, dtype x, rarg x)))
           mfix0 mfix1 ->
    Σ ;;; Γ |- tFix mfix0 idx ⇝ tFix mfix1 idx

| cofix_red_ty mfix0 mfix1 idx :
    OnOne2 (on_Trel_eq (fun t u => Σ ;;; Γ |- t ⇝ u) dtype (fun x => (dname x, dbody x, rarg x))) mfix0 mfix1 ->
    Σ ;;; Γ |- tCoFix mfix0 idx ⇝ tCoFix mfix1 idx

| cofix_red_body mfix0 mfix1 idx :
    OnOne2 (on_Trel_eq (fun t u => Σ ;;; Γ ,,, fix_context mfix0 |- t ⇝ u) dbody (fun x => (dname x, dtype x, rarg x))) mfix0 mfix1 ->
    Σ ;;; Γ |- tCoFix mfix0 idx ⇝ tCoFix mfix1 idx

| array_red_val arr value :
    OnOne2 (fun t u => Σ ;;; Γ |- t ⇝ u) arr.(array_value) value ->
    Σ ;;; Γ |- tPrim (primArray; primArrayModel arr) ⇝
               tPrim (primArray; primArrayModel (set_array_value arr value))

| array_red_def arr def :
    Σ ;;; Γ |- arr.(array_default) ⇝ def ->
    Σ ;;; Γ |- tPrim (primArray; primArrayModel arr) ⇝
               tPrim (primArray; primArrayModel (set_array_default arr def))

| array_red_type arr ty :
    Σ ;;; Γ |- arr.(array_type) ⇝ ty ->
    Σ ;;; Γ |- tPrim (primArray; primArrayModel arr) ⇝
          tPrim (primArray; primArrayModel (set_array_type arr ty))

where " Σ ;;; Γ |- t ⇝ u " := (red1 Σ Γ t u).

Definition red1_ctx Σ := (OnOne2_local_env (fun Δ => on_one_decl (fun t t' => red1 Σ Δ t t'))).

Definition red Σ Γ := clos_refl_trans (fun t u : term => Σ;;; Γ |- t ⇝ u).
Module Export PCUICCumulativitySpec.

Implicit Types (cf : checker_flags).

Definition cumul_predicate (cumul : context -> term -> term -> Type) cumul_universe Γ p p' :=
  All2 (cumul Γ) p.(pparams) p'.(pparams) ×
  cmp_universe_instance cumul_universe p.(puinst) p'.(puinst) ×
  eq_context_upto_names p.(pcontext) p'.(pcontext) ×
  cumul (Γ ,,, inst_case_predicate_context p) p.(preturn) p'.(preturn).

Definition cumul_branch (cumul_term : context -> term -> term -> Type) Γ p br br' :=
  eq_context_upto_names br.(bcontext) br'.(bcontext) ×
  cumul_term (Γ ,,, inst_case_branch_context p br) br.(bbody) br'.(bbody).

Definition cumul_branches cumul_term Γ p brs brs' := All2 (cumul_branch cumul_term Γ p) brs brs'.

Definition cumul_mfixpoint (cumul_term : context -> term -> term -> Type) Γ mfix mfix' :=
  All2 (fun d d' =>
    cumul_term Γ d.(dtype) d'.(dtype) ×
    cumul_term (Γ ,,, fix_context mfix) d.(dbody) d'.(dbody) ×
    d.(rarg) = d'.(rarg) ×
    eq_binder_annot d.(dname) d'.(dname)
  ) mfix mfix'.

Reserved Notation " Σ ;;; Γ ⊢ t ≤s[ pb ] u" (at level 50, Γ, t, u at next level,
  format "Σ  ;;;  Γ  ⊢  t  ≤s[ pb ]  u").

Definition cumul_Ind_univ {cf} (Σ : global_env_ext) pb i napp :=
  cmp_global_instance Σ (compare_universe Σ) pb (IndRef i) napp.

Definition cumul_Construct_univ {cf} (Σ : global_env_ext) pb  i k napp :=
  cmp_global_instance Σ (compare_universe Σ) pb (ConstructRef i k) napp.
Inductive cumulSpec0 {cf : checker_flags} (Σ : global_env_ext) Γ (pb : conv_pb) : term -> term -> Type :=

| cumul_Trans : forall t u v,
    is_closed_context Γ -> is_open_term Γ u ->
    Σ ;;; Γ ⊢ t ≤s[pb] u ->
    Σ ;;; Γ ⊢ u ≤s[pb] v ->
    Σ ;;; Γ ⊢ t ≤s[pb] v

| cumul_Sym : forall t u,
    Σ ;;; Γ ⊢ t ≤s[Conv] u ->
    Σ ;;; Γ ⊢ u ≤s[pb] t

| cumul_Refl : forall t,
    Σ ;;; Γ ⊢ t ≤s[pb] t

| cumul_Ind : forall i u u' args args',
    cumul_Ind_univ Σ pb i #|args| u u' ->
    All2 (fun t u => Σ ;;; Γ ⊢ t ≤s[Conv] u) args args' ->
    Σ ;;; Γ ⊢ mkApps (tInd i u) args ≤s[pb] mkApps (tInd i u') args'

| cumul_Construct : forall i k u u' args args',
    cumul_Construct_univ Σ pb i k #|args| u u' ->
    All2 (fun t u => Σ ;;; Γ ⊢ t ≤s[Conv] u) args args' ->
    Σ ;;; Γ ⊢ mkApps (tConstruct i k u) args ≤s[pb] mkApps (tConstruct i k u') args'

| cumul_Sort : forall s s',
    compare_sort Σ pb s s' ->
    Σ ;;; Γ ⊢ tSort s ≤s[pb] tSort s'

| cumul_Const : forall c u u',
    cmp_universe_instance (compare_universe Σ Conv) u u' ->
    Σ ;;; Γ ⊢ tConst c u ≤s[pb] tConst c u'

| cumul_Evar : forall e args args',
    All2 (fun t u => Σ ;;; Γ ⊢ t ≤s[Conv] u) args args' ->
    Σ ;;; Γ ⊢ tEvar e args ≤s[pb] tEvar e args'

| cumul_App : forall t t' u u',
    Σ ;;; Γ ⊢ t ≤s[pb] t' ->
    Σ ;;; Γ ⊢ u ≤s[Conv] u' ->
    Σ ;;; Γ ⊢ tApp t u ≤s[pb] tApp t' u'

| cumul_Lambda : forall na na' ty ty' t t',
    eq_binder_annot na na' ->
    Σ ;;; Γ ⊢ ty ≤s[Conv] ty' ->
    Σ ;;; Γ ,, vass na ty ⊢ t ≤s[Conv] t' ->
    Σ ;;; Γ ⊢ tLambda na ty t ≤s[pb] tLambda na' ty' t'

| cumul_Prod : forall na na' a a' b b',
    eq_binder_annot na na' ->
    Σ ;;; Γ ⊢ a ≤s[Conv] a' ->
    Σ ;;; Γ ,, vass na a ⊢ b ≤s[pb] b' ->
    Σ ;;; Γ ⊢ tProd na a b ≤s[pb] tProd na' a' b'

| cumul_LetIn : forall na na' t t' ty ty' u u',
    eq_binder_annot na na' ->
    Σ ;;; Γ ⊢ t ≤s[Conv] t' ->
    Σ ;;; Γ ⊢ ty ≤s[Conv] ty' ->
    Σ ;;; Γ ,, vdef na t ty ⊢ u ≤s[Conv] u' ->
    Σ ;;; Γ ⊢ tLetIn na t ty u ≤s[pb] tLetIn na' t' ty' u'

| cumul_Case indn : forall p p' c c' brs brs',
    cumul_predicate (fun Γ t u => Σ ;;; Γ ⊢ t ≤s[Conv] u) (compare_universe Σ Conv) Γ p p' ->
    Σ ;;; Γ ⊢ c ≤s[Conv] c' ->
    cumul_branches (fun Γ t u => Σ ;;; Γ ⊢ t ≤s[Conv] u) Γ p brs brs' ->
    Σ ;;; Γ ⊢ tCase indn p c brs ≤s[pb] tCase indn p' c' brs'

| cumul_Proj : forall p c c',
    Σ ;;; Γ ⊢ c ≤s[Conv] c' ->
    Σ ;;; Γ ⊢ tProj p c ≤s[pb] tProj p c'

| cumul_Fix : forall mfix mfix' idx,
    cumul_mfixpoint (fun Γ t u => Σ ;;; Γ ⊢ t ≤s[Conv] u) Γ mfix mfix' ->
    Σ ;;; Γ ⊢ tFix mfix idx ≤s[pb] tFix mfix' idx

| cumul_CoFix : forall mfix mfix' idx,
    cumul_mfixpoint (fun Γ t u => Σ ;;; Γ ⊢ t ≤s[Conv] u) Γ mfix mfix' ->
    Σ ;;; Γ ⊢ tCoFix mfix idx ≤s[pb] tCoFix mfix' idx

| cumul_Prim p p' :
  onPrims (fun x y => Σ ;;; Γ ⊢ x ≤s[Conv] y) (compare_universe Σ Conv) p p' ->
  Σ ;;; Γ ⊢ tPrim p ≤s[pb] tPrim p'

| cumul_beta : forall na t b a,
    Σ ;;; Γ ⊢ tApp (tLambda na t b) a ≤s[pb] b {0 := a}

| cumul_zeta : forall na b t b',
    Σ ;;; Γ ⊢ tLetIn na b t b' ≤s[pb] b' {0 := b}

| cumul_rel i body :
    option_map decl_body (nth_error Γ i) = Some (Some body) ->
    Σ ;;; Γ ⊢ tRel i ≤s[pb] lift0 (S i) body

| cumul_iota : forall ci c u args p brs br,
    nth_error brs c = Some br ->
    #|args| = (ci.(ci_npar) + context_assumptions br.(bcontext))%nat ->
    Σ ;;; Γ ⊢ tCase ci p (mkApps (tConstruct ci.(ci_ind) c u) args) brs  ≤s[pb] iota_red ci.(ci_npar) p args br

| cumul_fix : forall mfix idx args narg fn,
    unfold_fix mfix idx = Some (narg, fn) ->
    is_constructor narg args = true ->
    Σ ;;; Γ ⊢ mkApps (tFix mfix idx) args ≤s[pb] mkApps fn args

| cumul_cofix_case : forall ip p mfix idx args narg fn brs,
    unfold_cofix mfix idx = Some (narg, fn) ->
    Σ ;;; Γ ⊢ tCase ip p (mkApps (tCoFix mfix idx) args) brs ≤s[pb] tCase ip p (mkApps fn args) brs

| cumul_cofix_proj : forall p mfix idx args narg fn,
    unfold_cofix mfix idx = Some (narg, fn) ->
    Σ ;;; Γ ⊢ tProj p (mkApps (tCoFix mfix idx) args) ≤s[pb] tProj p (mkApps fn args)

| cumul_delta : forall c decl body (isdecl : declared_constant Σ c decl) u,
    decl.(cst_body) = Some body ->
    Σ ;;; Γ ⊢ tConst c u ≤s[pb] body@[u]

| cumul_proj : forall p args u arg,
    nth_error args (p.(proj_npars) + p.(proj_arg)) = Some arg ->
    Σ ;;; Γ ⊢ tProj p (mkApps (tConstruct p.(proj_ind) 0 u) args) ≤s[pb] arg

where " Σ ;;; Γ ⊢ t ≤s[ pb ] u " := (@cumulSpec0 _ Σ Γ pb t u) : type_scope.
Definition cumulSpec `{checker_flags} (Σ : global_env_ext) Γ := cumulSpec0 Σ Γ Cumul.

Notation " Σ ;;; Γ |- t <=s u " := (@cumulSpec _ Σ Γ t u) (at level 50, Γ, t, u at next level).

Module PCUICConversionParSpec <: EnvironmentTyping.ConversionParSig PCUICTerm PCUICEnvironment PCUICTermUtils PCUICEnvTyping.
End PCUICConversionParSpec.

End PCUICCumulativitySpec.

Implicit Types (cf : checker_flags) (Σ : global_env_ext).

Definition type_of_constructor mdecl (cdecl : constructor_body) (c : inductive * nat) (u : list Level.t) :=
  let mind := inductive_mind (fst c) in
  subst0 (inds mind u mdecl.(ind_bodies)) (subst_instance u (cstr_type cdecl)).

Include PCUICEnvTyping.

Inductive FixCoFix : Type := Fix | CoFix.

Class GuardChecker :=
{
  guard : FixCoFix -> global_env_ext -> context -> mfixpoint term -> Prop ;
}.

Axiom guard_checking : GuardChecker.
#[global]
Existing Instance guard_checking.

Definition fix_guard := guard Fix.
Definition cofix_guard := guard CoFix.

Definition destInd (t : term) :=
  match t with
  | tInd ind u => Some (ind, u)
  | _ => None
  end.

Definition isCoFinite (r : recursivity_kind) :=
  match r with
  | CoFinite => true
  | _ => false
  end.

Definition check_recursivity_kind
  (lookup: kername -> option global_decl) ind r :=
  match lookup ind with
  | Some (InductiveDecl mib) => ReflectEq.eqb mib.(ind_finite) r
  | _ => false
  end.

Definition check_one_fix d :=
  let '{| dname := na;
         dtype := ty;
         dbody := b;
         rarg := arg |} := d in
  let '(ctx, ty) := decompose_prod_assum [] ty in
  match nth_error (List.rev (smash_context [] ctx)) arg with
  | Some argd =>
    let (hd, args) := decompose_app argd.(decl_type) in
    match destInd hd with
    | Some (mkInd mind _, u) => Some mind
    | None => None
    end
  | None => None
  end.

Definition wf_fixpoint_gen
  (lookup: kername -> option global_decl) mfix :=
  forallb (isLambda ∘ dbody) mfix &&
  let checks := map check_one_fix mfix in
  match map_option_out checks with
  | Some (ind :: inds) =>

    forallb (eqb ind) inds &&
    check_recursivity_kind lookup ind Finite
  | _ => false
  end.

Definition wf_fixpoint (Σ : global_env) := wf_fixpoint_gen (lookup_env Σ).

Definition check_one_cofix d :=
  let '{| dname := na;
         dtype := ty;
         dbody := b;
         rarg := arg |} := d in
  let '(ctx, ty) := decompose_prod_assum [] ty in
  let (hd, args) := decompose_app ty in
  match destInd hd with
  | Some (mkInd ind _, u) => Some ind
  | None => None
  end.

Definition wf_cofixpoint_gen
  (lookup: kername -> option global_decl) mfix :=
  let checks := map check_one_cofix mfix in
  match map_option_out checks with
  | Some (ind :: inds) =>

    forallb (eqb ind) inds &&
    check_recursivity_kind lookup ind CoFinite
  | _ => false
  end.

Definition wf_cofixpoint (Σ : global_env) := wf_cofixpoint_gen (lookup_env Σ).

Reserved Notation "'wf_local' Σ Γ " (at level 9, Σ, Γ at next level).

Reserved Notation " Σ ;;; Γ |- t : T " (at level 50, Γ, t, T at next level).

Variant case_side_conditions `{checker_flags} wf_local_fun typing Σ Γ ci p ps mdecl idecl indices predctx :=
| case_side_info
    (eq_npars : mdecl.(ind_npars) = ci.(ci_npar))
    (wf_pred : wf_predicate mdecl idecl p)
    (cons : consistent_instance_ext Σ (ind_universes mdecl) p.(puinst))
    (wf_pctx : wf_local_fun Σ (Γ ,,, predctx))

    (conv_pctx : eq_context_upto_names p.(pcontext) (ind_predicate_context ci.(ci_ind) mdecl ide
10000
cl))
    (allowed_elim : is_allowed_elimination Σ idecl.(ind_kelim) ps)
    (elim_relevance : isSortRel ps ci.(ci_relevance))
    (ind_inst : ctx_inst (typing Σ) Γ (p.(pparams) ++ indices)
                         (List.rev (subst_instance p.(puinst)
                                                   (ind_params mdecl ,,, ind_indices idecl : context))))
    (not_cofinite : isCoFinite mdecl.(ind_finite) = false).

Variant case_branch_typing `{checker_flags} wf_local_fun typing Σ Γ (ci:case_info) p ps mdecl idecl ptm  brs :=
| case_branch_info
    (wf_brs : wf_branches idecl brs)
    (brs_ty :
       All2i (fun i cdecl br =>

                eq_context_upto_names br.(bcontext) (cstr_branch_context ci mdecl cdecl) ×
                let brctxty := case_branch_type ci.(ci_ind) mdecl idecl p br ptm i cdecl in
                (wf_local_fun Σ (Γ ,,, brctxty.1) ×
                ((typing Σ (Γ ,,, brctxty.1) br.(bbody) (brctxty.2)) ×
                (typing Σ (Γ ,,, brctxty.1) brctxty.2 (tSort ps)))))
             0 idecl.(ind_ctors) brs).

Variant primitive_typing_hyps `{checker_flags}
  (typing : forall (Σ : global_env_ext) (Γ : context), term -> term -> Type)
  Σ Γ : prim_val term -> Type :=
| prim_int_hyps i : primitive_typing_hyps typing Σ Γ (primInt; primIntModel i)
| prim_float_hyps f : primitive_typing_hyps typing Σ Γ (primFloat; primFloatModel f)
| prim_string_hyps s : primitive_typing_hyps typing Σ Γ (primString; primStringModel s)
| prim_array_hyps a
  (wfl : wf_universe Σ (Universe.make' a.(array_level)))
  (hty : typing Σ Γ a.(array_type) (tSort (sType (Universe.make' a.(array_level)))))
  (hdef : typing Σ Γ a.(array_default) a.(array_type))
  (hvalue : All (fun x => typing Σ Γ x a.(array_type)) a.(array_value)) :
  primitive_typing_hyps typing Σ Γ (primArray; primArrayModel a).

Equations prim_type (p : prim_val term) (cst : kername) : term :=
prim_type (primInt; _) cst := tConst cst [];
prim_type (primFloat; _) cst := tConst cst [];
prim_type (primString; _) cst := tConst cst [];
prim_type (primArray; primArrayModel a) cst := tApp (tConst cst [a.(array_level)]) a.(array_type).

Inductive typing `{checker_flags} (Σ : global_env_ext) (Γ : context) : term -> term -> Type :=
| type_Rel : forall n decl,
    wf_local Σ Γ ->
    nth_error Γ n = Some decl ->
    Σ ;;; Γ |- tRel n : lift0 (S n) decl.(decl_type)

| type_Sort : forall s,
    wf_local Σ Γ ->
    wf_sort Σ s ->
    Σ ;;; Γ |- tSort s : tSort (Sort.super s)

| type_Prod : forall na A B s1 s2,
    lift_typing typing Σ Γ (j_vass_s na A s1) ->
    Σ ;;; Γ ,, vass na A |- B : tSort s2 ->
    Σ ;;; Γ |- tProd na A B : tSort (Sort.sort_of_product s1 s2)

| type_Lambda : forall na A t B,
    lift_typing typing Σ Γ (j_vass na A) ->
    Σ ;;; Γ ,, vass na A |- t : B ->
    Σ ;;; Γ |- tLambda na A t : tProd na A B

| type_LetIn : forall na b B t A,
    lift_typing typing Σ Γ (j_vdef na b B) ->
    Σ ;;; Γ ,, vdef na b B |- t : A ->
    Σ ;;; Γ |- tLetIn na b B t : tLetIn na b B A

| type_App : forall t na A B s u,

    Σ ;;; Γ |- tProd na A B : tSort s ->
    Σ ;;; Γ |- t : tProd na A B ->
    Σ ;;; Γ |- u : A ->
    Σ ;;; Γ |- tApp t u : B{0 := u}

| type_Const : forall cst u decl,
    wf_local Σ Γ ->
    declared_constant Σ cst decl ->
    consistent_instance_ext Σ decl.(cst_universes) u ->
    Σ ;;; Γ |- tConst cst u : decl.(cst_type)@[u]

| type_Ind : forall ind u mdecl idecl,
    wf_local Σ Γ ->
    declared_inductive Σ ind mdecl idecl ->
    consistent_instance_ext Σ mdecl.(ind_universes) u ->
    Σ ;;; Γ |- tInd ind u : idecl.(ind_type)@[u]

| type_Construct : forall ind i u mdecl idecl cdecl,
    wf_local Σ Γ ->
    declared_constructor Σ (ind, i) mdecl idecl cdecl ->
    consistent_instance_ext Σ mdecl.(ind_universes) u ->
    Σ ;;; Γ |- tConstruct ind i u : type_of_constructor mdecl cdecl (ind, i) u

| type_Case : forall ci p c brs indices ps mdecl idecl,
    let predctx := case_predicate_context ci.(ci_ind) mdecl idecl p in
    let ptm := it_mkLambda_or_LetIn predctx p.(preturn) in
    declared_inductive Σ ci.(ci_ind) mdecl idecl ->
    Σ ;;; Γ ,,, predctx |- p.(preturn) : tSort ps ->
    Σ ;;; Γ |- c : mkApps (tInd ci.(ci_ind) p.(puinst)) (p.(pparams) ++ indices) ->
    case_side_conditions (fun Σ Γ => wf_local Σ Γ) typing Σ Γ ci p ps
                         mdecl idecl indices predctx  ->
    case_branch_typing (fun Σ Γ => wf_local Σ Γ) typing Σ Γ ci p ps
                        mdecl idecl ptm brs ->
    Σ ;;; Γ |- tCase ci p c brs : mkApps ptm (indices ++ [c])

| type_Proj : forall p c u mdecl idecl cdecl pdecl args,
    declared_projection Σ p mdecl idecl cdecl pdecl ->
    Σ ;;; Γ |- c : mkApps (tInd p.(proj_ind) u) args ->
    #|args| = ind_npars mdecl ->
    Σ ;;; Γ |- tProj p c : subst0 (c :: List.rev args) pdecl.(proj_type)@[u]

| type_Fix : forall mfix n decl,
    wf_local Σ Γ ->
    fix_guard Σ Γ mfix ->
    nth_error mfix n = Some decl ->
    All (on_def_type (lift_typing1 (typing Σ)) Γ) mfix ->
    All (on_def_body (lift_typing1 (typing Σ)) (fix_context mfix) Γ) mfix ->
    wf_fixpoint Σ mfix ->
    Σ ;;; Γ |- tFix mfix n : decl.(dtype)

| type_CoFix : forall mfix n decl,
    wf_local Σ Γ ->
    cofix_guard Σ Γ mfix ->
    nth_error mfix n = Some decl ->
    All (on_def_type (lift_typing1 (typing Σ)) Γ) mfix ->
    All (on_def_body (lift_typing1 (typing Σ)) (fix_context mfix) Γ) mfix ->
    wf_cofixpoint Σ mfix ->
    Σ ;;; Γ |- tCoFix mfix n : decl.(dtype)

| type_Prim p prim_ty cdecl :
    wf_local Σ Γ ->
    primitive_constant Σ (prim_val_tag p) = Some prim_ty ->
    declared_constant Σ prim_ty cdecl ->
    primitive_invariants (prim_val_tag p) cdecl ->
    primitive_typing_hyps typing Σ Γ p ->
    Σ ;;; Γ |- tPrim p : prim_type p prim_ty

| type_Cumul : forall t A B s,
    Σ ;;; Γ |- t : A ->
    Σ ;;; Γ |- B : tSort s ->
    Σ ;;; Γ |- A <=s B ->
    Σ ;;; Γ |- t : B

where " Σ ;;; Γ |- t : T " := (typing Σ Γ t T)
and "'wf_local' Σ Γ " := (All_local_env (lift_typing1 (typing Σ)) Γ).

Definition wf `{checker_flags} := on_global_env cumulSpec0 (lift_typing typing).
Notation on_contexts_length := All2_fold_length.
Import Stdlib.ssr.ssreflect.
Import Equations.Prop.Equations.
Import Stdlib.Classes.CRelationClasses.
Import Equations.Type.Relation_Properties.

Definition ws_term P := { t : term | on_free_vars P t }.
Definition ws_term_proj {P} (t : ws_term P) : term.
admit.
Defined.
Coercion ws_term_proj : ws_term >-> term.

Definition ws_context P := { t : context | on_free_vars_ctx P t }.

Notation closed_context := (ws_context xpred0).
Notation open_term Γ := (ws_term (shiftnP #|Γ| xpred0)).
Definition ws_context_proj' {P} (t : ws_context P) : list context_decl.
Admitted.
Coercion ws_context_proj' : ws_context >-> list.

Definition ws_red1 Σ P (Γ : ws_context P) (t u : ws_term (shiftnP #|Γ| P)) :=
  red1 Σ Γ t u.

Definition ws_red Σ P (Γ : ws_context P) := clos_refl_trans (ws_red1 Σ P Γ).

Definition ws_pair :=
  ∑ Γ : ws_context xpred0, ws_term (shiftnP #|Γ| xpred0).

Section RedConfluence.
  Context {cf : checker_flags}.
  Context {Σ : global_env_ext} (wfΣ : wf Σ).
Definition red1_rel_alpha : relation ws_pair.
exact (relation_disjunction (A:=ws_pair) (fun '(Γ; t) '(Δ; u) => (red1 Σ Γ t u * (Γ = Δ)))%type
     (relation_disjunction (A:=ws_pair)
        (fun '(Γ; t) '(Δ; u) => ((red1_ctx Σ Γ Δ * (t = u :> term))))
        (fun '(Γ; t) '(Δ; u) => ((eq_context_upto_names Γ Δ * (t = u :> term)))))%type).
Defined.

  Lemma red_ws_red (Γ : closed_context) (x y : ws_term (shiftnP #|Γ| xpred0)) :
    red Σ Γ x y -> ws_red Σ xpred0 Γ x y.
Admitted.
Definition transport_ws_term {n m : nat} (t : ws_term (shiftnP n xpred0)) (eq : n = m) : ws_term (shiftnP m xpred0).
Admitted.
Definition red_ctx_alpha : relation context.
exact (All2_fold (fun Γ _ => All_decls_alpha (red Σ Γ))).
Defined.

  Instance red_ctx_alpha_refl : Reflexive red_ctx_alpha.
Admitted.

  Lemma ws_red_refl_irrel P (Γ : ws_context P) (x y : ws_term (shiftnP #|Γ| P)) :
    x = y :> term ->
    ws_red Σ P Γ x y.
Admitted.

  Lemma clos_rt_red1_alpha_out x y :
    clos_refl_trans red1_rel_alpha x y ->
    ∑ redctx : red_ctx_alpha x.π1 y.π1,
      ws_red Σ xpred0 x.π1 x.π2 (transport_ws_term y.π2 (symmetry (All2_fold_length redctx))).
  Proof using wfΣ.
    intros H.
    eapply clos_rt_rt1n_iff in H.
    induction H.
    -
 unshelve eexists.
reflexivity.
eapply ws_red_refl_irrel => //.
    -
 destruct x as [Γ t], y as [Δ u], z as [Δ' u']; simpl in *.
      destruct IHclos_refl_trans_1n.
      red in r.
destruct r.
      *
 destruct p.
subst.
exists x.
        transitivity u; auto.
        now eapply red_ws_red.
      *
 destruct t as [t ht], u as [u hu];
        move: r; case; move => [] r eq; noconf eq.
🛠️ Intermediate Coq File (useful for debugging if minimization did not go as far as you wanted)
🛠️ 📜 Intermediate Coq File log (useful for debugging if minimization did not go as far as you wanted)
📜 Build Log (contains the Coq error message) (truncated to last 8.0KiB; full 7.0MiB file on GitHub Actions Artifacts under build.log)
t-minimizer.yOazJ6YAgU
MINIMIZER_DEBUG: files: 
make[2]: Leaving directory '/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/template-rocq'
# Ensure the cmxs is built before the loader file 
make -f Makefile.plugin gen-src/metarocq_template_plugin.cmxs
make[2]: Entering directory '/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/template-rocq'
MINIMIZER_DEBUG_EXTRA: coqc: /github/workspace/builds/coq/coq-failing/_install_ci/bin///rocq
MINIMIZER_DEBUG_EXTRA: original invocation: c --print-version 
MINIMIZER_DEBUG_EXTRA: new invocation: /github/workspace/builds/coq/coq-failing/_install_ci/bin/rocq.orig c --print-version 
MINIMIZER_DEBUG_EXTRA: coqpath: 
MINIMIZER_DEBUG_EXTRA: ocamlpath: /github/workspace/builds/coq/coq-failing/_build_ci/metarocq/template-rocq/:/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/safechecker-plugin/src:/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/erasure-plugin/src:/github/workspace/builds/coq/coq-failing/_install_ci/lib:
MINIMIZER_DEBUG_EXTRA: pwd: PWD=/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/template-rocq
MINIMIZER_DEBUG_EXTRA: exec: /github/workspace/builds/coq/coq-failing/_install_ci/bin/rocq.orig c --print-version 
MINIMIZER_DEBUG_EXTRA: coqlib: Warning: Deprecated environment variable COQLIB, use ROCQLIB instead.
/github/workspace/builds/coq/coq-failing/_install_ci/lib/coq//
MINIMIZER_DEBUG: info: /tmp/tmp-coqbot-minimizer.alkVktnDKl
MINIMIZER_DEBUG: files: 
make[2]: 'gen-src/metarocq_template_plugin.cmxs' is up to date.
make[2]: Leaving directory '/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/template-rocq'
make -f Makefile.plugin
make[2]: Entering directory '/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/template-rocq'
MINIMIZER_DEBUG_EXTRA: coqc: /github/workspace/builds/coq/coq-failing/_install_ci/bin///rocq
MINIMIZER_DEBUG_EXTRA: original invocation: c --print-version 
MINIMIZER_DEBUG_EXTRA: new invocation: /github/workspace/builds/coq/coq-failing/_install_ci/bin/rocq.orig c --print-version 
MINIMIZER_DEBUG_EXTRA: coqpath: 
MINIMIZER_DEBUG_EXTRA: ocamlpath: /github/workspace/builds/coq/coq-failing/_build_ci/metarocq/template-rocq/:/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/safechecker-plugin/src:/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/erasure-plugin/src:/github/workspace/builds/coq/coq-failing/_install_ci/lib:
MINIMIZER_DEBUG_EXTRA: pwd: PWD=/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/template-rocq
MINIMIZER_DEBUG_EXTRA: exec: /github/workspace/builds/coq/coq-failing/_install_ci/bin/rocq.orig c --print-version 
MINIMIZER_DEBUG_EXTRA: coqlib: Warning: Deprecated environment variable COQLIB, use ROCQLIB instead.
/github/workspace/builds/coq/coq-failing/_install_ci/lib/coq//
MINIMIZER_DEBUG: info: /tmp/tmp-coqbot-minimizer.xUxNu2iPD2
MINIMIZER_DEBUG: files: 
MINIMIZER_DEBUG_EXTRA: coqc: /github/workspace/builds/coq/coq-failing/_install_ci/bin/////rocq
MINIMIZER_DEBUG_EXTRA: original invocation: c --print-version 
MINIMIZER_DEBUG_EXTRA: new invocation: /github/workspace/builds/coq/coq-failing/_install_ci/bin/rocq.orig c --print-version 
MINIMIZER_DEBUG_EXTRA: coqpath: 
MINIMIZER_DEBUG_EXTRA: ocamlpath: /github/workspace/builds/coq/coq-failing/_build_ci/metarocq/template-rocq/:/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/safechecker-plugin/src:/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/erasure-plugin/src:/github/workspace/builds/coq/coq-failing/_install_ci/lib:
MINIMIZER_DEBUG_EXTRA: pwd: PWD=/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/template-rocq
MINIMIZER_DEBUG_EXTRA: exec: /github/workspace/builds/coq/coq-failing/_install_ci/bin/rocq.orig c --print-version 
MINIMIZER_DEBUG_EXTRA: coqlib: Warning: Deprecated environment variable COQLIB, use ROCQLIB instead.
/github/workspace/builds/coq/coq-failing/_install_ci/lib/coq//
MINIMIZER_DEBUG: info: /tmp/tmp-coqbot-minimizer.ppF3d5xr5f
MINIMIZER_DEBUG: files: 
MINIMIZER_DEBUG_EXTRA: coqc: /github/workspace/builds/coq/coq-failing/_install_ci/bin/////rocq
MINIMIZER_DEBUG_EXTRA: original invocation: c --print-version 
MINIMIZER_DEBUG_EXTRA: new invocation: /github/workspace/builds/coq/coq-failing/_install_ci/bin/rocq.orig c --print-version 
MINIMIZER_DEBUG_EXTRA: coqpath: 
MINIMIZER_DEBUG_EXTRA: ocamlpath: /github/workspace/builds/coq/coq-failing/_build_ci/metarocq/template-rocq/:/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/safechecker-plugin/src:/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/erasure-plugin/src:/github/workspace/builds/coq/coq-failing/_install_ci/lib:
MINIMIZER_DEBUG_EXTRA: pwd: PWD=/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/template-rocq
MINIMIZER_DEBUG_EXTRA: exec: /github/workspace/builds/coq/coq-failing/_install_ci/bin/rocq.orig c --print-version 
MINIMIZER_DEBUG_EXTRA: coqlib: Warning: Deprecated environment variable COQLIB, use ROCQLIB instead.
/github/workspace/builds/coq/coq-failing/_install_ci/lib/coq//
MINIMIZER_DEBUG: info: /tmp/tmp-coqbot-minimizer.9NaetHeTok
MINIMIZER_DEBUG: files: 
make[3]: Nothing to be done for 'real-all'.
MINIMIZER_DEBUG_EXTRA: coqc: /github/workspace/builds/coq/coq-failing/_install_ci/bin/////rocq
MINIMIZER_DEBUG_EXTRA: original invocation: c --print-version 
MINIMIZER_DEBUG_EXTRA: new invocation: /github/workspace/builds/coq/coq-failing/_install_ci/bin/rocq.orig c --print-version 
MINIMIZER_DEBUG_EXTRA: coqpath: 
MINIMIZER_DEBUG_EXTRA: ocamlpath: /github/workspace/builds/coq/coq-failing/_build_ci/metarocq/template-rocq/:/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/safechecker-plugin/src:/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/erasure-plugin/src:/github/workspace/builds/coq/coq-failing/_install_ci/lib:
MINIMIZER_DEBUG_EXTRA: pwd: PWD=/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/template-rocq
MINIMIZER_DEBUG_EXTRA: exec: /github/workspace/builds/coq/coq-failing/_install_ci/bin/rocq.orig c --print-version 
MINIMIZER_DEBUG_EXTRA: coqlib: Warning: Deprecated environment variable COQLIB, use ROCQLIB instead.
/github/workspace/builds/coq/coq-failing/_install_ci/lib/coq//
MINIMIZER_DEBUG: info: /tmp/tmp-coqbot-minimizer.k6TXOlCd0o
MINIMIZER_DEBUG: files: 
make[2]: Leaving directory '/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/template-rocq'
make[1]: Leaving directory '/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/template-rocq'
File "./theories/PCUICConfluence.v", line 3649, characters 47-49:
Error: Cannot infer the implicit parameter A of eq whose type is 
"Type" in
environment:
cf : checker_flags
Σ : global_env_ext
wfΣ : wf Σ
Γ : closed_context
t : term
ht : is_open_term Γ t
Δ : closed_context
u : term
hu : is_open_term Δ u
Δ' : closed_context
u' : open_term Δ'
H : clos_refl_trans_1n red1_rel_alpha (Δ; exist u hu) (Δ'; u')
x : red_ctx_alpha Δ Δ'
w :
  ws_red Σ xpred0 Δ (exist u hu)
    (transport_ws_term u' (symmetry (on_contexts_length x)))
r : red1_ctx Σ Γ Δ
eq : exist t ht = exist u hu

Command exited with non-zero status 1
theories/PCUICConfluence.vo (real: 46.74, user: 46.28, sys: 0.40, mem: 2432516 ko)
make[3]: *** [Makefile.rocq:814: theories/PCUICConfluence.vo] Error 1
make[3]: *** [theories/PCUICConfluence.vo] Deleting file 'theories/PCUICConfluence.glob'
make[2]: *** [Makefile.rocq:412: all] Error 2
make[2]: Leaving directory '/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/pcuic'
make[1]: *** [Makefile:11: coq] Error 2
make[1]: Leaving directory '/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/pcuic'
make: *** [Makefile:149: pcuic] Error 2
+ code=2
+ printf '\n%s exit code: %s\n' metarocq 2
+ '[' metarocq '!=' stdlib_test ']'
+ echo 'Aggregating timing log...'
Aggregating timing log...
+ echo

+ tools/make-one-time-file.py --real metarocq.log
    Time |   Peak Mem | File Name            
---------------------------------------------
0m46.74s | 2432516 ko | Total Time / Peak Mem
---------------------------------------------
0m46.74s | 2432516 ko | PCUICConfluence.vo   
+ '[' '' ']'
+ exit 2
/github/workspace/builds/coq /github/workspace
::endgroup::
📜 🔎 Minimization Log (truncated to last 8.0KiB; full 1.1MiB file on GitHub Actions Artifacts under bug.log)
738/Top/bug_01.v", line 376, characters 7-20:
Warning: Coq.Init.Ltac has been replaced by Corelib.Init.Ltac.
[deprecated-dirpath-Coq,deprecated-since-9.0,deprecated,default]
File "/tmp/tmpx2gxl738/Top/bug_01.v", line 384, characters 0-28:
Warning: Notation "_ =1 _" was already used in scope type_scope.
[notation-overridden,parsing,default]
File "/tmp/tmpx2gxl738/Top/bug_01.v", line 384, characters 0-28:
Warning: Notation "_ =2 _" was already used in scope type_scope.
[notation-overridden,parsing,default]
File "/tmp/tmpx2gxl738/Top/bug_01.v", line 2706, characters 88-94:
Error:
In environment
cf : checker_flags
Σ : global_env_ext
wfΣ : wf Σ
x : ws_pair
y : ws_pair
redctx : red_ctx_alpha x.π1 y.π1
The term "redctx" has type "red_ctx_alpha x.π1 y.π1"
while it is expected to have type "All2_fold ?P ?Γ ?Γ'".


�[93mIntermediate code not saved.�[0m
Failed to do everything at once; trying one at a time.
Admitting definitions unsuccessful.
No successful changes.

I will now attempt to admit lemmas with admit. Defined with Proof using

Non-fatal error: Failed to admit lemmas and preserve the error.  
The new error was:
Deprecated environment variable COQCORELIB, use ROCQRUNTIMELIB instead.
Warning: Deprecated environment variable COQCORELIB,
use ROCQRUNTIMELIB instead.
[deprecated-coq-env-var,deprecated-since-9.0,deprecated,default]
File "/tmp/tmp5q6u7s2c/Top/bug_01.v", line 173, characters 0-34:
Warning: Library File Stdlib.ZArith.ZArith_base is deprecated since 9.0.
use ZArith instead
[deprecated-library-file-since-9.0,deprecated-since-9.0,deprecated-library-file,deprecated,default]
File "/tmp/tmp5q6u7s2c/Top/bug_01.v", line 224, characters 0-27:
Warning: Alternatives to Fin.t are available, see
<https://github.com/coq/stdlib/blob/master/theories/Vectors/Fin.v>.
[warn-library-file-stdlib-vector,stdlib-vector,warn-library-file,user-warn,default]
File "/tmp/tmp5q6u7s2c/Top/bug_01.v", line 225, characters 0-33:
Warning: Using Vector.t is known to be technically difficult, see
<https://github.com/coq/stdlib/blob/master/theories/Vectors/Vector.v>.
[warn-library-file-stdlib-vector,stdlib-vector,warn-library-file,user-warn,default]
File "/tmp/tmp5q6u7s2c/Top/bug_01.v", line 226, characters 0-34:
Warning: Using Vector.t is known to be technically difficult, see
<https://github.com/coq/stdlib/blob/master/theories/Vectors/Vector.v>.
[warn-library-file-stdlib-vector,stdlib-vector,warn-library-file,user-warn,default]
File "/tmp/tmp5q6u7s2c/Top/bug_01.v", line 227, characters 0-32:
Warning: Using Vector.t is known to be technically difficult, see
<https://github.com/coq/stdlib/blob/master/theories/Vectors/Vector.v>.
[warn-library-file-stdlib-vector,stdlib-vector,warn-library-file,user-warn,default]
File "/tmp/tmp5q6u7s2c/Top/bug_01.v", line 228, characters 0-30:
Warning: Using Vector.t is known to be technically difficult, see
<https://github.com/coq/stdlib/blob/master/theories/Vectors/Vector.v>.
[warn-library-file-stdlib-vector,stdlib-vector,warn-library-file,user-warn,default]
File "/tmp/tmp5q6u7s2c/Top/bug_01.v", line 229, characters 0-31:
Warning: Library File Stdlib.Vectors.Bvector is deprecated since 8.20.
Consider [list bool] instead. See <https://github.com/coq/stdlib/blob/master/theories/Vectors/Vector.v> for details. Please open an issue if you would like to keep using Bvector.
[deprecated-library-file-since-8.20,deprecated-since-8.20,deprecated-library-file,deprecated,default]
File "/tmp/tmp5q6u7s2c/Top/bug_01.v", line 376, characters 7-20:
Warning: Coq.Init.Ltac has been replaced by Corelib.Init.Ltac.
[deprecated-dirpath-Coq,deprecated-since-9.0,deprecated,default]
File "/tmp/tmp5q6u7s2c/Top/bug_01.v", line 384, characters 0-28:
Warning: Notation "_ =1 _" was already used in scope type_scope.
[notation-overridden,parsing,default]
File "/tmp/tmp5q6u7s2c/Top/bug_01.v", line 384, characters 0-28:
Warning: Notation "_ =2 _" was already used in scope type_scope.
[notation-overridden,parsing,default]
Error: The section RedConfluence, module PCUICPrimitive and module
EnvironmentTyping need to be closed.


�[93mIntermediate code not saved.�[0m
Failed to do everything at once; trying one at a time.
Admitting lemmas unsuccessful.
No successful changes.

I will now attempt to admit definitions with admit. Defined with Proof using

Non-fatal error: Failed to admit definitions and preserve the error.  
The new error was:
Deprecated environment variable COQCORELIB, use ROCQRUNTIMELIB instead.
Warning: Deprecated environment variable COQCORELIB,
use ROCQRUNTIMELIB instead.
[deprecated-coq-env-var,deprecated-since-9.0,deprecated,default]
File "/tmp/tmp69i63neo/Top/bug_01.v", line 173, characters 0-34:
Warning: Library File Stdlib.ZArith.ZArith_base is deprecated since 9.0.
use ZArith instead
[deprecated-library-file-since-9.0,deprecated-since-9.0,deprecated-library-file,deprecated,default]
File "/tmp/tmp69i63neo/Top/bug_01.v", line 224, characters 0-27:
Warning: Alternatives to Fin.t are available, see
<https://github.com/coq/stdlib/blob/master/theories/Vectors/Fin.v>.
[warn-library-file-stdlib-vector,stdlib-vector,warn-library-file,user-warn,default]
File "/tmp/tmp69i63neo/Top/bug_01.v", line 225, characters 0-33:
Warning: Using Vector.t is known to be technically difficult, see
<https://github.com/coq/stdlib/blob/master/theories/Vectors/Vector.v>.
[warn-library-file-stdlib-vector,stdlib-vector,warn-library-file,user-warn,default]
File "/tmp/tmp69i63neo/Top/bug_01.v", line 226, characters 0-34:
Warning: Using Vector.t is known to be technically difficult, see
<https://github.com/coq/stdlib/blob/master/theories/Vectors/Vector.v>.
[warn-library-file-stdlib-vector,stdlib-vector,warn-library-file,user-warn,default]
File "/tmp/tmp69i63neo/Top/bug_01.v", line 227, characters 0-32:
Warning: Using Vector.t is known to be technically difficult, see
<https://github.com/coq/stdlib/blob/master/theories/Vectors/Vector.v>.
[warn-library-file-stdlib-vector,stdlib-vector,warn-library-file,user-warn,default]
File "/tmp/tmp69i63neo/Top/bug_01.v", line 228, characters 0-30:
Warning: Using Vector.t is known to be technically difficult, see
<https://github.com/coq/stdlib/blob/master/theories/Vectors/Vector.v>.
[warn-library-file-stdlib-vector,stdlib-vector,warn-library-file,user-warn,default]
File "/tmp/tmp69i63neo/Top/bug_01.v", line 229, characters 0-31:
Warning: Library File Stdlib.Vectors.Bvector is deprecated since 8.20.
Consider [list bool] instead. See <https://github.com/coq/stdlib/blob/master/theories/Vectors/Vector.v> for details. Please open an issue if you would like to keep using Bvector.
[deprecated-library-file-since-8.20,deprecated-since-8.20,deprecated-library-file,deprecated,default]
File "/tmp/tmp69i63neo/Top/bug_01.v", line 376, characters 7-20:
Warning: Coq.Init.Ltac has been replaced by Corelib.Init.Ltac.
[deprecated-dirpath-Coq,deprecated-since-9.0,deprecated,default]
File "/tmp/tmp69i63neo/Top/bug_01.v", line 384, characters 0-28:
Warning: Notation "_ =1 _" was already used in scope type_scope.
[notation-overridden,parsing,default]
File "/tmp/tmp69i63neo/Top/bug_01.v", line 384, characters 0-28:
Warning: Notation "_ =2 _" was already used in scope type_scope.
[notation-overridden,parsing,default]
File "/tmp/tmp69i63neo/Top/bug_01.v", line 2708, characters 88-94:
Error:
In environment
cf : checker_flags
Σ : global_env_ext
wfΣ : wf Σ
x : ws_pair
y : ws_pair
redctx : red_ctx_alpha x.π1 y.π1
The term "redctx" has type "red_ctx_alpha x.π1 y.π1"
while it is expected to have type "All2_fold ?P ?Γ ?Γ'".


�[93mIntermediate code not saved.�[0m
Failed to do everything at once; trying one at a time.
Admitting definitions unsuccessful.
No successful changes.

I will now attempt to add Proof using lines
�[92m
Adding Proof using lines successful.�[0m
Failed to do everything at once; trying one at a time.
Adding Proof using lines unsuccessful.
No successful changes.

I will now attempt to export modules
Module exportation successful

I will now attempt to split imports and exports
Import/Export splitting successful

I will now attempt to split := definitions
One-line definition splitting successful

I will now attempt to remove all lines, one at a time

If you have any comments on your experience of the minimizer, please share them in a reply (possibly tagging @JasonGross).
If you believe there's a bug in the bug minimizer, please report it on the bug minimizer issue tracker.

Copy link
Contributor
coqbot-app bot commented May 27, 2025
Minimization interrupted by timeout, being automatically continued. Partially Minimized File /home/runner/work/run-coq-bug-minimizer/run-coq-bug-minimizer/builds/coq/coq-failing/_build_ci/metarocq/pcuic/theories/PCUICConfluence.v in 5h 15m 7s (from ci-metarocq) (interrupted by timeout, being automatically continued) (full log on GitHub Actions - verbose log)
⭐ ⏱️ Partially Minimized Coq File (timeout) (truncated to first and last 32KiB; full 95KiB file on GitHub Actions Artifacts under bug.v)
(* -*- mode: coq; coq-prog-args: ("-emacs" "-q" "-w" "-deprecated-native-compiler-option" "-native-compiler" "no" "-coqlib" "/github/workspace/builds/coq/coq-failing/_install_ci/lib/coq//" "-R" "/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/utils/theories" "MetaRocq.Utils" "-R" "/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/common/theories" "MetaRocq.Common" "-R" "/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/pcuic/theories" "MetaRocq.PCUIC" "-Q" "/github/workspace/cwd" "Top" "-Q" "/github/workspace/builds/coq/coq-failing/_install_ci/lib/coq///user-contrib/Equations" "Equations" "-Q" "/github/workspace/builds/coq/coq-failing/_install_ci/lib/coq///user-contrib/Ltac2" "Ltac2" "-Q" "/github/workspace/builds/coq/coq-failing/_install_ci/lib/coq///user-contrib/Stdlib" "Stdlib" "-top" "Top.bug_01") -*- *)
(* File reduced by coq-bug-minimizer from original input, then from 3959 lines to 98 lines, then from 111 lines to 3187 lines, then from 3191 lines to 96 lines, then from 107 lines to 1813 lines, then from 1818 lines to 359 lines, then from 369 lines to 1502 lines, then from 1506 lines to 524 lines, then from 535 lines to 3221 lines, then from 3222 lines to 656 lines, then from 667 lines to 2894 lines, then from 2900 lines to 656 lines, then from 667 lines to 1321 lines, then from 1327 lines to 874 lines, then from 883 lines to 675 lines, then from 686 lines to 2746 lines, then from 2745 lines to 687 lines, then from 698 lines to 3155 lines, then from 3155 lines to 745 lines, then from 756 lines to 1586 lines, then from 1589 lines to 869 lines, then from 880 lines to 2395 lines, then from 2394 lines to 885 lines, then from 895 lines to 2754 lines, then from 2755 lines to 1157 lines, then from 1161 lines to 1145 lines, then from 1156 lines to 1809 lines, then from 1813 lines to 1200 lines, then from 1211 lines to 4024 lines, then from 4021 lines to 1355 lines, then from 1366 lines to 3048 lines, then from 3051 lines to 1938 lines, then from 1928 lines to 1518 lines, then from 1529 lines to 1814 lines, then from 1819 lines to 1523 lines, then from 1533 lines to 2340 lines, then from 2342 lines to 1526 lines, then from 1536 lines to 4638 lines, then from 4602 lines to 1892 lines, then from 1903 lines to 3075 lines, then from 3076 lines to 2771 lines *)
(* coqc version 9.1+alpha compiled with OCaml 4.14.2
   coqtop version runner-t7b1znuaq-project-4504-concurrent-2:/builds/coq/coq/_build/default,(HEAD detached at cdd06d0a2f356e) (cdd06d0a2f356e0c02e2d20356562b7deae4cf15)
   Expected coqc runtime on this file: 1.847 sec *)









Require Corelib.Init.Ltac.
Require Corelib.Classes.CRelationClasses.
Require Stdlib.Classes.CRelationClasses.
Require Stdlib.Classes.DecidableClass.
Require Stdlib.Logic.HLevelsBase.
Require Stdlib.Bool.Bool.
Require Corelib.Classes.RelationClasses.
Require Stdlib.Classes.RelationClasses.
Require Corelib.Numbers.BinNums.
Require Stdlib.Numbers.BinNums.
Require Stdlib.Logic.EqdepFacts.
Require Stdlib.Logic.Eqdep_dec.
Require Corelib.Classes.Morphisms.
Require Stdlib.Classes.Morphisms.
Require Corelib.Setoids.Setoid.
Require Stdlib.Setoids.Setoid.
Require Stdlib.Structures.Equalities.
Require Corelib.Relations.Relation_Definitions.
Require Stdlib.Relations.Relation_Definitions.
Require Stdlib.Relations.Relation_Operators.
Require Stdlib.Relations.Operators_Properties.
Require Stdlib.Relations.Relations.
Require Stdlib.Structures.Orders.
Require Corelib.Program.Basics.
Require Stdlib.Program.Basics.
Require Stdlib.Structures.OrdersTac.
Require Stdlib.Structures.OrdersFacts.
Require Stdlib.Structures.GenericMinMax.
Require Corelib.Classes.Morphisms_Prop.
Require Stdlib.Classes.Morphisms_Prop.
Require Stdlib.Numbers.NumPrelude.
Require Stdlib.Numbers.NatInt.NZAxioms.
Require Stdlib.Numbers.NatInt.NZBase.
Require Stdlib.Numbers.NatInt.NZAdd.
Require Stdlib.Numbers.NatInt.NZMul.
Require Stdlib.Logic.Decidable.
Require Stdlib.Numbers.NatInt.NZOrder.
Require Stdlib.Numbers.NatInt.NZAddOrder.
Require Stdlib.Numbers.NatInt.NZMulOrder.
Require Stdlib.Numbers.NatInt.NZParity.
Require Stdlib.Numbers.NatInt.NZPow.
Require Stdlib.Numbers.NatInt.NZSqrt.
Require Stdlib.Numbers.NatInt.NZLog.
Require Stdlib.Numbers.NatInt.NZDiv.
Require Stdlib.Numbers.NatInt.NZGcd.
Require Stdlib.Numbers.NatInt.NZBits.
Require Stdlib.Numbers.Natural.Abstract.NAxioms.
Require Stdlib.Numbers.Natural.Abstract.NBase.
Require Stdlib.Numbers.Natural.Abstract.NAdd.
Require Stdlib.Numbers.Natural.Abstract.NOrder.
Require Stdlib.Numbers.Natural.Abstract.NAddOrder.
Require Stdlib.Numbers.Natural.Abstract.NMulOrder.
Require Stdlib.Numbers.Natural.Abstract.NSub.
Require Stdlib.Numbers.Natural.Abstract.NMaxMin.
Require Stdlib.Numbers.Natural.Abstract.NParity.
Require Stdlib.Numbers.Natural.Abstract.NPow.
Require Stdlib.Numbers.Natural.Abstract.NSqrt.
Require Stdlib.Numbers.Natural.Abstract.NLog.
Require Stdlib.Numbers.Natural.Abstract.NDiv.
Require Stdlib.Numbers.Natural.Abstract.NDiv0.
Require Stdlib.Numbers.Natural.Abstract.NGcd.
Require Stdlib.Numbers.Natural.Abstract.NLcm.
Require Stdlib.Numbers.Natural.Abstract.NLcm0.
Require Stdlib.Numbers.Natural.Abstract.NBits.
Require Stdlib.Numbers.Natural.Abstract.NProperties.
Require Stdlib.Arith.PeanoNat.
Require Corelib.BinNums.PosDef.
Require Stdlib.BinNums.PosDef.
Require Stdlib.PArith.BinPosDef.
Require Stdlib.PArith.BinPos.
Require Stdlib.PArith.Pnat.
Require Stdlib.PArith.POrderedType.
Require Stdlib.PArith.PArith.
Require Corelib.BinNums.NatDef.
Require Stdlib.BinNums.NatDef.
Require Stdlib.NArith.BinNatDef.
Require Stdlib.NArith.BinNat.
Require Stdlib.setoid_ring.Ring_theory.
Require Corelib.Lists.ListDef.
Require Stdlib.Lists.ListDef.
Require Stdlib.Lists.List.
Require Stdlib.setoid_ring.BinList.
Require Stdlib.Numbers.Integer.Abstract.ZAxioms.
Require Stdlib.Numbers.Integer.Abstract.ZBase.
Require Stdlib.Numbers.Integer.Abstract.ZAdd.
Require Stdlib.Numbers.Integer.Abstract.ZMul.
Require Stdlib.Numbers.Integer.Abstract.ZLt.
Require Stdlib.Numbers.Integer.Abstract.ZAddOrder.
Require Stdlib.Numbers.Integer.Abstract.ZMulOrder.
Require Stdlib.Numbers.Integer.Abstract.ZMaxMin.
Require Stdlib.Numbers.Integer.Abstract.ZSgnAbs.
Require Stdlib.Numbers.Integer.Abstract.ZParity.
Require Stdlib.Numbers.Integer.Abstract.ZPow.
Require Stdlib.Numbers.Integer.Abstract.ZDivTrunc.
Require Stdlib.Numbers.Integer.Abstract.ZDivFloor.
Require Stdlib.Numbers.Integer.Abstract.ZGcd.
Require Stdlib.Numbers.Integer.Abstract.ZLcm.
Require Stdlib.Numbers.Integer.Abstract.ZBits.
Require Stdlib.Numbers.Integer.Abstract.ZProperties.
Require Corelib.BinNums.IntDef.
Require Stdlib.BinNums.IntDef.
Require Stdlib.ZArith.BinIntDef.
Require Stdlib.ZArith.BinInt.
Require Stdlib.setoid_ring.Ring_polynom.
Require Stdlib.Lists.ListTactics.
Require Stdlib.setoid_ring.InitialRing.
Require Stdlib.setoid_ring.Ring_tac.
Require Stdlib.setoid_ring.Ring_base.
Require Stdlib.setoid_ring.Ring.
Require Stdlib.Arith.Factorial.
Require Stdlib.Arith.Between.
Require Stdlib.Arith.Peano_dec.
Require Stdlib.Arith.Compare_dec.
Require Stdlib.Arith.EqNat.
Require Stdlib.Arith.Wf_nat.
Require Stdlib.Arith.Arith_base.
Require Stdlib.NArith.Nnat.
Require Stdlib.setoid_ring.ArithRing.
Require Stdlib.Arith.Arith.
Require Stdlib.ZArith.Znat.
Require Stdlib.micromega.ZifyClasses.
Require Stdlib.ZArith.Zeven.
Require Stdlib.micromega.ZifyInst.
Require Stdlib.micromega.Zify.
Require Stdlib.omega.PreOmega.
Require Stdlib.micromega.OrderedRing.
Require Stdlib.NArith.Ndiv_def.
Require Stdlib.NArith.Nsqrt_def.
Require Stdlib.NArith.Ngcd_def.
Require Stdlib.NArith.NArith_base.
Require Stdlib.setoid_ring.NArithRing.
Require Stdlib.NArith.NArith.
Require Stdlib.micromega.Env.
Require Stdlib.micromega.EnvRing.
Require Stdlib.micromega.Refl.
Require Stdlib.micromega.Tauto.
Require Stdlib.micromega.RingMicromega.
Require Stdlib.ZArith.Zpow_def.
Require Stdlib.setoid_ring.ZArithRing.
Require Stdlib.micromega.ZCoeff.
Require Stdlib.ZArith.Zcompare.
Require Stdlib.ZArith.Zorder.
Require Stdlib.ZArith.Zmisc.
Require Stdlib.ZArith.Wf_Z.
Require Corelib.Init.Sumbool.
Require Stdlib.Init.Sumbool.
Require Stdlib.ZArith.ZArith_dec.
Require Stdlib.ZArith.Zbool.
Require Stdlib.ZArith.Zabs.
Require Stdlib.ZArith.Zcomplements.
Require Stdlib.ZArith.Zdiv.
Require Stdlib.micromega.VarMap.
Require Stdlib.micromega.ZMicromega.
Require Stdlib.micromega.DeclConstantZ.
Require Stdlib.micromega.Lia.
Require Stdlib.btauto.Algebra.
Require Stdlib.btauto.Reflect.
Require Stdlib.btauto.Btauto.
Require Corelib.ssr.ssreflect.
Require Stdlib.ssr.ssreflect.
Require Corelib.ssr.ssrbool.
Require Stdlib.ssr.ssrbool.
Require MetaRocq.Common.config.
Require Corelib.Floats.FloatOps.
Require Corelib.Floats.PrimFloat.
Require Corelib.Floats.SpecFloat.
Require Corelib.Init.Byte.
Require Corelib.Init.Decimal.
Require Corelib.Init.Nat.
Require Corelib.Init.Wf.
Require Corelib.Numbers.Cyclic.Int63.CarryType.
Require Corelib.Numbers.Cyclic.Int63.PrimInt63.
Require Corelib.Numbers.Cyclic.Int63.Sint63Axioms.
Require Corelib.Numbers.Cyclic.Int63.Uint63Axioms.
Require Corelib.Program.Tactics.
Require Corelib.Program.Utils.
Require Corelib.Program.Wf.
Require Corelib.Strings.PrimString.
Require Corelib.Strings.PrimStringAxioms.
Require Corelib.extraction.Extraction.
Require MetaRocq.Utils.MREquality.
Require MetaRocq.Utils.MRSquash.
Require MetaRocq.Utils.MRTactics.DestructHyps.
Require MetaRocq.Utils.MRTactics.FindHyp.
Require MetaRocq.Utils.MRTactics.Head.
Require MetaRocq.Utils.MRTactics.SpecializeBy.
Require MetaRocq.Utils.MRTactics.SplitInContext.
Require MetaRocq.Utils.MRTactics.Zeta1.
Require Stdlib.Logic.FunctionalExtensionality.
Require Stdlib.Program.Syntax.
Require Stdlib.Sets.Relations_1.
Require Stdlib.Unicode.Utf8_core.
Require Stdlib.Wellfounded.Inverse_Image.
Require Stdlib.setoid_ring.Algebra_syntax.
Require Ltac2.Init.
Require MetaRocq.Utils.MRTactics.UniquePose.
Require Stdlib.Floats.FloatOps.
Require Stdlib.Floats.PrimFloat.
Require Stdlib.Floats.SpecFloat.
Require Stdlib.Init.Byte.
Require Stdlib.Init.Decimal.
Require Stdlib.Init.Nat.
Require Stdlib.Init.Wf.
Require Stdlib.Logic.Eqdep.
Require Stdlib.Logic.ProofIrrelevanceFacts.
Require Stdlib.Numbers.Cyclic.Int63.CarryType.
Require Stdlib.Numbers.Cyclic.Int63.PrimInt63.
Require Stdlib.Numbers.Cyclic.Int63.Sint63Axioms.
Require Stdlib.Numbers.Cyclic.Int63.Uint63Axioms.
Require Stdlib.Program.Tactics.
Require Stdlib.Program.Utils.
Require Stdlib.Program.Wf.
Require Stdlib.Strings.PrimString.
Require Stdlib.Strings.PrimStringAxioms.
Require Stdlib.Unicode.Utf8.
Require Stdlib.Wellfounded.Well_Ordering.
Require Stdlib.extraction.Extraction.
Require Equations.Init.
Require Ltac2.Message.
Require Ltac2.Std.
Require MetaRocq.Utils.MRTactics.DestructHead.
Require MetaRocq.Utils.MRTactics.SpecializeAllWays.
Require Stdlib.Logic.JMeq.
Require Stdlib.Logic.ProofIrrelevance.
Require Stdlib.Wellfounded.Inclusion.
Require Equations.Prop.SigmaNotations.
Require Equations.Signature.
Require Ltac2.Control.
Require MetaRocq.Utils.MRTactics.GeneralizeOverHoles.
Require Stdlib.Program.Combinators.
Require Stdlib.Wellfounded.Disjoint_Union.
Require Stdlib.Wellfounded.Transitive_Closure.
Require Equations.CoreTactics.
Require Stdlib.Wellfounded.Union.
Require Ltac2.Ltac1.
Require Stdlib.Program.Equality.
Require Equations.Type.Logic.
Require Equations.Prop.Logic.
Require Equations.Type.Relation.
Require MetaRocq.Utils.MRTactics.InHypUnderBindersDo.
Require MetaRocq.Utils.MRTactics.SpecializeUnderBindersBy.
Require Stdlib.Classes.RelationPairs.
Require Stdlib.Program.WfExtensionality.
Require Stdlib.Wellfounded.Lexicographic_Product.
Require Equations.Type.Relation_Properties.
Require MetaRocq.Utils.MRProd.
Require Equations.Prop.Classes.
Require Stdlib.Program.Subset.
Require Equations.Prop.EqDec.
Require MetaRocq.Utils.MRRelations.
Require Equations.Prop.DepElim.
Require Equations.Prop.FunctionalInduction.
Require Equations.Prop.Constants.
Require Stdlib.Program.Program.
Require Stdlib.Wellfounded.List_Extension.
Require Stdlib.Sorting.Sorted.
Require Stdlib.Sorting.SetoidList.
Require Stdlib.Structures.DecidableType.
Require Stdlib.Structures.OrderedType.
Require Stdlib.Wellfounded.Lexicographic_Exponentiation.
Require Stdlib.MSets.MSetInterface.
Require Stdlib.Structures.EqualitiesFacts.
Require Stdlib.Structures.OrderedTypeAlt.
Require Stdlib.Structures.OrdersAlt.
Require Stdlib.FSets.FMapInterface.
Require Stdlib.Structures.OrdersLists.
Require Stdlib.FSets.FMapList.
Require Stdlib.Vectors.Fin.
Require Stdlib.Vectors.VectorDef.
Require Stdlib.MSets.MSetList.
Require Stdlib.Wellfounded.Wellfounded.
Require Stdlib.Vectors.VectorSpec.
Require Stdlib.Vectors.VectorEq.
Require Stdlib.Vectors.Vector.
Require Stdlib.Strings.Byte.
Require MetaRocq.Utils.ByteCompare.
Require Stdlib.Strings.Ascii.
Require Stdlib.Vectors.Bvector.
Require Stdlib.NArith.Ndec.
Require Equations.Prop.Subterm.
Require Stdlib.ZArith.Int.
Require Equations.Prop.Tactics.
Require Stdlib.setoid_ring.Ncring.
Require Stdlib.Numbers.Cyclic.Abstract.DoubleType.
Require Stdlib.setoid_ring.Ncring_polynom.
Require Stdlib.ZArith.Zmax.
Require Stdlib.ZArith.Zmin.
Require Stdlib.ZArith.Zminmax.
Require Stdlib.ZArith.auxiliary.
Require Stdlib.omega.OmegaLemmas.
Require Stdlib.setoid_ring.Ncring_initial.
Require Stdlib.setoid_ring.Ncring_tac.
Require Stdlib.setoid_ring.Cring.
Require Equations.Prop.NoConfusion.
Require Equations.Prop.EqDecInstances.
Require Equations.Prop.Loader.
Require Equations.Prop.Telescopes.
Require Stdlib.ZArith.Zhints.
Require Equations.Prop.Equations.
Require Stdlib.ZArith.ZArith_base.
Require MetaRocq.Utils.ReflectEq.
Require Stdlib.Strings.String.
Require Stdlib.MSets.MSetGenTree.
Require Stdlib.micromega.ZifyBool.
Require MetaRocq.Utils.MRCompare.
Require Stdlib.MSets.MSetAVL.
Require Stdlib.Numbers.DecimalString.
Require Stdlib.ZArith.Zpower.
Require Stdlib.Structures.OrderedTypeEx.
Require Stdlib.Structures.DecidableTypeEx.
Require Stdlib.FSets.FMapFacts.
Require Stdlib.MSets.MSetFacts.
Require Stdlib.MSets.MSetDecide.
Require Stdlib.MSets.MSetProperties.
Require Stdlib.ZArith.Zdiv_facts.
Require Stdlib.ZArith.Zdivisibility.
Require Stdlib.ZArith.ZModOffset.
Require Stdlib.ZArith.Zcong.
Require Stdlib.micromega.ZArith_hints.
Require Stdlib.ZArith.Zbitwise.
Require Stdlib.ZArith.Znumtheory.
Require Stdlib.ZArith.Zgcd_alt.
Require Stdlib.ZArith.Zpow_facts.
Require Stdlib.ZArith.ZArith.
Require MetaRocq.Utils.MRArith.
Require Stdlib.Numbers.Cyclic.Abstract.CyclicAxioms.
Require Stdlib.FSets.FMapAVL.
Require Stdlib.Numbers.Cyclic.Int63.Uint63.
Require Stdlib.Numbers.Cyclic.Int63.Cyclic63.
Require Stdlib.micromega.ZifyUint63.
Require Stdlib.Numbers.Cyclic.Int63.Ring63.
Require Stdlib.Numbers.Cyclic.Int63.Sint63.
Require Stdlib.Strings.PString.
Require MetaRocq.Utils.ByteCompareSpec.
Require Stdlib.FSets.FMapFullAVL.
Require MetaRocq.Utils.bytestring.
Require MetaRocq.Utils.MRPrelude.
Require MetaRocq.Utils.MRReflect.
Require MetaRocq.Utils.MRList.
Require MetaRocq.Utils.MRString.
Require MetaRocq.Utils.MROption.
Require MetaRocq.Utils.All_Forall.
Require MetaRocq.Utils.monad_utils.
Require MetaRocq.Utils.MRMSets.
Require MetaRocq.Utils.Show.
Require MetaRocq.Utils.MRUtils.
Require MetaRocq.Utils.utils.
Require MetaRocq.Utils.MRFSets.
Require MetaRocq.Common.Kernames.

Module Export AdmitTactic.
Module Import LocalFalse.
Inductive False : Prop := .
End LocalFalse.
Axiom proof_admitted : False.
Import Coq.Init.Ltac.
Tactic Notation "admit" := abstract case proof_admitted.
End AdmitTactic.

Module Export MetaRocq_DOT_Common_DOT_BasicAst_WRAPPED.
Module Export BasicAst.
Import Stdlib.ssr.ssreflect.
Import Stdlib.Classes.Morphisms.
Import Stdlib.Structures.Orders.
Import Stdlib.Setoids.Setoid.
Import MetaRocq.Utils.utils.
Export MetaRocq.Common.Kernames.
Import Equations.Prop.Equations.


Inductive name : Set :=
| nAnon
| nNamed (_ : ident).
Derive NoConfusion EqDec for name.

Inductive relevance : Set := Relevant | Irrelevant.
Derive NoConfusion EqDec for relevance.


Record binder_annot (A : Type) := mkBindAnn { binder_name : A; binder_relevance : relevance }.

Arguments mkBindAnn {_}.
Arguments binder_name {_}.
Arguments binder_relevance {_}.

Derive NoConfusion for binder_annot.

#[global] Instance eqdec_binder_annot (A : Type) (e : Classes.EqDec A) : Classes.EqDec (binder_annot A).
Admitted.
Definition map_binder_annot {A B} (f : A -> B) (b : binder_annot A) : binder_annot B. exact ({| binder_name := f b.(binder_name); binder_relevance := b.(binder_relevance) |}). Defined.
Definition eq_binder_annot {A B} (b : binder_annot A) (b' : binder_annot B) : Prop. exact (b.(binder_relevance) = b'.(binder_relevance)). Defined.


Definition aname := binder_annot name.
#[global] Instance anqme_eqdec : Classes.EqDec aname. exact (_). Defined.
Definition eqb_binder_annot {A} (b b' : binder_annot A) : bool. exact (match Classes.eq_dec b.(binder_relevance) b'.(binder_relevance) with
  | left _ => true
  | right _ => false
  end). Defined.

Definition string_of_name (na : name) :=
  match na with
  | nAnon => "_"
  | nNamed n => n
  end.

Definition string_of_relevance (r : relevance) :=
  match r with
  | Relevant => "Relevant"
  | Irrelevant => "Irrelevant"
  end.


Inductive cast_kind : Set :=
| VmCast
| NativeCast
| Cast.
Derive NoConfusion EqDec for cast_kind.

Record case_info := mk_case_info {
  ci_ind : inductive;
  ci_npar : nat;
  
  ci_relevance : relevance }.
Derive NoConfusion EqDec for case_info.

Definition string_of_case_info ci :=
  "(" ^ string_of_inductive ci.(ci_ind) ^ "," ^
  string_of_nat ci.(ci_npar) ^ "," ^
  
  string_of_relevance ci.(ci_relevance) ^ ")".

Inductive recursivity_kind :=
  | Finite 
  | CoFinite 
  | BiFinite .
Derive NoConfusion EqDec for recursivity_kind.


Inductive conv_pb :=
  | Conv
  | Cumul.
Derive NoConfusion EqDec for conv_pb.
Definition conv_pb_leqb (pb1 pb2 : conv_pb) : bool. exact (match pb1, pb2 with
     | Cumul, Conv => false
     | _, _ => true
     end). Defined.


Definition fresh_evar_id : nat.
Admitted.


Record def term := mkdef {
  dname : aname; 
  dtype : term;
  dbody : term; 
  rarg  : nat   }.

Arguments dname {term} _.
Arguments dtype {term} _.
Arguments dbody {term} _.
Arguments rarg {term} _.

Derive NoConfusion for def.
#[global] Instance def_eq_dec {A} : Classes.EqDec A -> Classes.EqDec (def A).
Admitted.

Definition string_of_def {A} (f : A -> string) (def : def A) :=
  "(" ^ string_of_name (binder_name (dname def))
      ^ "," ^ string_of_relevance (binder_relevance (dname def))
      ^ "," ^ f (dtype def)
      ^ "," ^ f (dbody def)
      ^ "," ^ string_of_nat (rarg def) ^ ")".

Definition print_def {A} (f : A -> string) (g : A -> string) (def : def A) :=
  string_of_name (binder_name (dname def)) ^ " { struct " ^ string_of_nat (rarg def) ^ " }" ^
                 " : " ^ f (dtype def) ^ " := " ^ nl ^ g (dbody def).

Definition map_def {A B} (tyf bodyf : A -> B) (d : def A) :=
  {| dname := d.(dname); dtype := tyf d.(dtype); dbody := bodyf d.(dbody); rarg := d.(rarg) |}.

Lemma map_dtype {A B} (f : A -> B) (g : A -> B) (d : def A) :
  f (dtype d) = dtype (map_def f g d).
Admitted.

Lemma map_dbody {A B} (f : A -> B) (g : A -> B) (d : def A) :
  g (dbody d) = dbody (map_def f g d).
Admitted.

Lemma map_dname {A B} (f : A -> B) (g : A -> B) (d : def A) :
  dname d = dname (map_def f g d).
Admitted.

Definition mfixpoint term := list (def term).

Definition test_def {A} (tyf bodyf : A -> bool) (d : def A) :=
  tyf d.(dtype) && bodyf d.(dbody).

Definition tFixProp {A} (P P' : A -> Type) (m : mfixpoint A) :=
  All (fun x : def A => P x.(dtype) * P' x.(dbody))%type m.

Lemma map_def_map_def {A B C} (f f' : B -> C) (g g' : A -> B) (d : def A) :
  map_def f f' (map_def g g' d) = map_def (f ∘ g) (f' ∘ g') d.
Admitted.

Lemma compose_map_def {A B C} (f f' : B -> C) (g g' : A -> B) :
  (map_def f f') ∘ (map_def g g') = map_def (f ∘ g) (f' ∘ g').
Admitted.

Lemma map_def_id {t} x : map_def (@id t) (@id t) x = id x.
Admitted.
#[global] Hint Rewrite @map_def_id @map_id : map.

Lemma map_def_spec {A B} (P P' : A -> Type) (f f' g g' : A -> B) (x : def A) :
  P' x.(dbody) -> P x.(dtype) -> (forall x, P x -> f x = g x) ->
  (forall x, P' x -> f' x = g' x) ->
  map_def f f' x = map_def g g' x.
Admitted.

#[global] Hint Extern 10 (_ < _)%nat => lia : all.
#[global] Hint Extern 10 (_ <= _)%nat => lia : all.
#[global] Hint Extern 10 (@eq nat _ _) => lia : all.
#[global] Hint Extern 0 (_ = _) => progress f_equal : all.
#[global] Hint Unfold on_snd snd : all.

Lemma on_snd_eq_id_spec {A B} (f : B -> B) (x : A * B) :
  f (snd x) = snd x <->
  on_snd f x = x.
Admitted.
#[global] Hint Resolve -> on_snd_eq_id_spec : all.
#[global] Hint Resolve -> on_snd_eq_spec : all.

Lemma map_def_eq_spec {A B} (f f' g g' : A -> B) (x : def A) :
  f (dtype x) = g (dtype x) ->
  f' (dbody x) = g' (dbody x) ->
  map_def f f' x = map_def g g' x.
Admitted.
#[global] Hint Resolve map_def_eq_spec : all.

Lemma map_def_id_spec {A} (f f' : A -> A) (x : def A) :
  f (dtype x) = (dtype x) ->
  f' (dbody x) = (dbody x) ->
  map_def f f' x = x.
Admitted.
#[global] Hint Resolve map_def_id_spec : all.

Lemma tfix_map_spec {A B} {P P' : A -> Type} {l} {f f' g g' : A -> B} :
  tFixProp P P' l -> (forall x, P x -> f x = g x) ->
  (forall x, P' x -> f' x = g' x) ->
  map (map_def f f') l = map (map_def g g') l.
Admitted.

Record judgment_ {universe Term} := Judge {
  j_term : option Term;
  j_typ : Term;
  j_univ : option universe;
  j_rel : option relevance;
}.
Arguments judgment_ : clear implicits.
Arguments Judge {universe Term} _ _ _.

Definition judgment_map {univ T A} (f: T -> A) (j : judgment_ univ T) :=
  Judge (option_map f (j_term j)) (f (j_typ j)) (j_univ j) (j_rel j).

Section Contexts.
  Context {term : Type}.
  

  Record context_decl := mkdecl {
    decl_name : aname ;
    decl_body : option term ;
    decl_type : term
  }.
  Derive NoConfusion for context_decl.
End Contexts.

Arguments context_decl : clear implicits.

Notation Typ typ := (Judge None typ None None).
Notation TypRel typ rel := (Judge None typ None (Some rel)).
Notation TermTyp tm ty := (Judge (Some tm) ty None None).
Notation TermTypRel tm ty rel := (Judge (Some tm) ty None (Some rel)).
Notation TermoptTyp tm typ := (Judge tm typ None None).
Notation TermoptTypRel tm typ rel := (Judge tm typ None (Some rel)).
Notation TypUniv ty u := (Judge None ty (Some u) None).
Notation TypUnivRel ty u rel := (Judge None ty (Some u) (Some rel)).
Notation TermTypUniv tm ty u := (Judge (Some tm) ty (Some u) None).

Notation j_vass na ty := (TypRel ty na.(binder_relevance)).
Notation j_vass_s na ty s := (TypUnivRel ty s na.(binder_relevance)).
Notation j_vdef na b ty := (TermTypRel b ty na.(binder_relevance)).
Notation j_decl d := (TermoptTypRel (decl_body d) (decl_type d) (decl_name d).(binder_relevance)).
Notation j_decl_s d s := (Judge (decl_body d) (decl_type d) s (Some (decl_name d).(binder_relevance))).
Definition map_decl {term term'} (f : term -> term') (d : context_decl term) : context_decl term'. exact ({| decl_name := d.(decl_name);
     decl_body := option_map f d.(decl_body);
     decl_type := f d.(decl_type) |}). Defined.

Lemma compose_map_decl {term term' term''} (g : term -> term') (f : term' -> term'') x :
  map_decl f (map_decl g x) = map_decl (f ∘ g) x.
Admitted.

Lemma map_decl_ext {term term'} (f g : term -> term') x : (forall x, f x = g x) -> map_decl f x = map_decl g x.
Admitted.

#[global] Instance map_decl_proper {term term'} : Proper (`=1` ==> Logic.eq ==> Logic.eq) (@map_decl term term').
Admitted.

#[global] Instance map_decl_pointwise {term term'} : Proper (`=1` ==> `=1`) (@map_decl term term').
Admitted.


Definition map_context {term term'} (f : term -> term') (c : list (context_decl term)) :=
  List.map (map_decl f) c.

#[global] Instance map_context_proper {term term'} : Proper (`=1` ==> Logic.eq ==> Logic.eq) (@map_context term term').
Admitted.

Lemma map_context_length {term term'} (f : term -> term') l : #|map_context f l| = #|l|.
Admitted.
#[global] Hint Rewrite @map_context_length : len.
Definition test_decl {term} (f : term -> bool) (d : context_decl term) : bool. exact (option_default f d.(decl_body) true && f d.(decl_type)). Defined.

#[global] Instance test_decl_proper {term} : Proper (`=1` ==> Logic.eq ==> Logic.eq) (@test_decl term).
Admitted.

Definition snoc {A} (Γ : list A) (d : A) := d :: Γ.

Notation " Γ ,, d " := (snoc Γ d) (at level 20, d at next level).

Definition app_context {A} (Γ Γ': list A) := Γ' ++ Γ.

Notation "Γ ,,, Γ'" := (app_context Γ Γ') (at level 25, Γ' at next level, left associativity).

Lemma app_context_nil_l {T} Γ : [] ,,, Γ = Γ :> list T.
Admitted.

Lemma app_context_assoc {T} Γ Γ' Γ'' : Γ ,,, (Γ' ,,, Γ'') = Γ ,,, Γ' ,,, Γ'' :> list T.
Admitted.

Lemma app_context_cons {T} Γ Γ' A : Γ ,,, (Γ' ,, A) = (Γ ,,, Γ') ,, A :> list T.
Admitted.

Lemma app_context_push {T} Γ Δ Δ' d : (Γ ,,, Δ ,,, Δ') ,, d = (Γ ,,, Δ ,,, (Δ' ,, d)) :> list T.
Admitted.

Lemma snoc_app_context {T Γ Δ d} : (Γ ,,, (d :: Δ)) =  (Γ ,,, Δ) ,,, [d] :> list T.
Admitted.

Lemma app_context_length {T} (Γ Γ' : list T) : #|Γ ,,, Γ'| = #|Γ'| + #|Γ|.
Admitted.
#[global] Hint Rewrite @app_context_length : len.

Lemma nth_error_app_context_ge {T} v Γ Γ' :
  #|Γ'| <= v -> nth_error (Γ ,,, Γ') v = nth_error Γ (v - #|Γ'|) :> option T.
Admitted.

Lemma nth_error_app_context_lt {T} v Γ Γ' :
  v < #|Γ'| -> nth_error (Γ ,,, Γ') v = nth_error Γ' v :> option T.
Admitted.

Definition ondecl {A} (P : A -> Type) (d : context_decl A) :=
  option_default P d.(decl_body) unit × P d.(decl_type).

Notation onctx P := (All (ondecl P)).

Section ContextMap.
  Context {term term' : Type} (f : nat -> term -> term').
Fixpoint mapi_context (c : list (context_decl term)) : list (context_decl term'). exact (match c with
    | d :: Γ => map_decl (f #|Γ|) d :: mapi_context Γ
    | [] => []
  end). Defined.
End ContextMap.

#[global] Instance mapi_context_proper {term term'} : Proper (`=2` ==> Logic.eq ==> Logic.eq) (@mapi_context term term').
Admitted.

Lemma mapi_context_length {term} (f : nat -> term -> term) l : #|mapi_context f l| = #|l|.
Admitted.
#[global] Hint Rewrite @mapi_context_length : len.

Section ContextTest.
  Context {term : Type} (f : term -> bool).
Fixpoint test_context (c : list (context_decl term)) : bool. exact (match c with
    | d :: Γ => test_context Γ && test_decl f d
    | [] => true
    end). Defined.
End ContextTest.

#[global] Instance test_context_proper {term} : Proper (`=1` ==> Logic.eq ==> Logic.eq) (@test_context term).
Admitted.

Section ContextTestK.
  Context {term : Type} (f : nat -> term -> bool) (k : nat).
Fixpoint test_context_k (c : list (context_decl term)) : bool. exact (match c with
    | d :: Γ => test_context_k Γ && test_decl (f (#|Γ| + k)) d
    | [] => true
    end). Defined.
End ContextTestK.

#[global] Instance test_context_k_proper {term} : Proper (`=1` ==> Logic.eq ==> Logic.eq ==> Logic.eq) (@test_context_k term).
Admitted.

Section Contexts.
  Context {term term' term'' : Type}.
  Notation context term := (list (context_decl term)).

  Lemma test_decl_impl (f g : term -> bool) x : (forall x, f x -> g x) ->
    test_decl f x -> test_decl g x.
Admitted.

  Definition onctx_k (P : nat -> term -> Type) k (ctx : context term) :=
    Alli (fun i d => ondecl (P (Nat.pred #|ctx| - i + k)) d) 0 ctx.

  Lemma ondeclP {P : term -> Type} {p : term -> bool} {d : context_decl term} :
    (forall x, reflectT (P x) (p x)) ->
    reflectT (ondecl P d) (test_decl p d).
Admitted.

  Lemma onctxP {p : term -> bool} {ctx : context term} :
    reflectT (onctx p ctx) (test_context p ctx).
Admitted.

  Lemma map_decl_type (f : term -> term') decl : f (decl_type decl) = decl_type (map_decl f decl).
Admitted.

  Lemma map_decl_body (f : term -> term') decl : option_map f (decl_body decl) = decl_body (map_decl f decl).
Admitted.

  Lemma map_decl_id : @map_decl term term id =1 id.
Admitted.

  Lemma option_map_decl_body_map_decl (f : term -> term') x :
    option_map decl_body (option_map (map_decl f) x) =
    option_map (option_map f) (option_map decl_body x).
Admitted.

  Lemma option_map_decl_type_map_decl (f : term -> term') x :
    option_map decl_type (option_map (map_decl f) x) =
    option_map f (option_map decl_type x).
Admitted.

  Definition fold_context_k (f : nat -> term -> term') Γ :=
    List.rev (mapi (fun k' decl => map_decl (f k') decl) (List.rev Γ)).

  Arguments fold_context_k f Γ%_list_scope.

  Lemma fold_context_k_alt f Γ :
    fold_context_k f Γ =
    mapi (fun k' d => map_decl (f (Nat.pred (length Γ) - k')) d) Γ.
Admitted.

  Lemma mapi_context_fold f Γ :
    mapi_context f Γ = fold_context_k f Γ.
Admitted.

  Lemma fold_context_k_tip f d : fold_context_k f [d] = [map_decl (f 0) d].
Admitted.

  Lemma fold_context_k_length f Γ : length (fold_context_k f Γ) = length Γ.
Admitted.

  Lemma fold_context_k_snoc0 f Γ d :
    fold_context_k f (d :: Γ) = fold_context_k f Γ ,, map_decl (f (length Γ)) d.
Admitted.

  Lemma fold_context_k_app f Γ Δ :
    fold_context_k f (Δ ++ Γ)
    = fold_context_k (fun k => f (length Γ + k)) Δ ++ fold_context_k f Γ.
Admitted.

  Local Set Keyed Unification.

  Equations mapi_context_In (ctx : context term) (f : nat -> forall (x : context_decl term), In x ctx -> context_decl term) : context term :=
  mapi_context_In nil _ := nil;
  mapi_context_In (cons x xs) f := cons (f #|xs| x _) (mapi_context_In xs (fun n x H => f n x _)).

  Lemma mapi_context_In_spec (f : nat -> term -> term) (ctx : context term) :
    mapi_context_In ctx (fun n (x : context_decl term) (_ : In x ctx) => map_decl (f n) x) =
    mapi_context f ctx.
Admitted.

  Equations fold_context_In (ctx : context term) (f : context term -> forall (x : context_decl term), In x ctx -> context_decl term) : context term :=
  fold_context_In nil _ := nil;
  fold_context_In (cons x xs) f :=
    let xs' := fold_context_In xs (fun n x H => f n x _) in
    cons (f xs' x _) xs'.

  Equations fold_context (f : context term -> context_decl term -> context_decl term) (ctx : context term) : context term :=
    fold_context f nil := nil;
    fold_context f (cons x xs) :=
      let xs' := fold_context f xs in
      cons (f xs' x ) xs'.

  Lemma fold_context_length f Γ : #|fold_context f Γ| = #|Γ|.
Admitted.

  Lemma fold_context_In_spec (f : context term -> context_decl term -> context_decl term) (ctx : context term) :
    fold_context_In ctx (fun n (x : context_decl term) (_ : In x ctx) => f n x) =
    fold_context f ctx.
Admitted.

  #[global]
  Instance fold_context_Proper : Proper (`=2` ==> `=1`) fold_context.
Admitted.
Definition forget_types (c : list (BasicAst.context_decl term)) : list aname. exact (map decl_name c). Defined.

End Contexts.
#[global] Hint Rewrite @fold_context_length @fold_context_k_length : len.

Section Contexts.
  Context {term term' term'' : Type}.
  Notation context term := (list (context_decl term)).

  Lemma fold_context_k_id (x : context term) : fold_context_k (fun i x => x) x = x.
Admitted.

  Lemma fold_context_k_compose (f : nat -> term' -> term) (g : nat -> term'' -> term') Γ :
    fold_context_k f (fold_context_k g Γ) =
    fold_context_k (fun i => f i ∘ g i) Γ.
Admitted.

  Lemma fold_context_k_ext (f g : nat -> term' -> term) Γ :
    f =2 g ->
    fold_context_k f Γ = fold_context_k g Γ.
Admitted.

  #[global] Instance fold_context_k_proper : Proper (pointwise_relation nat (pointwise_relation _ Logic.eq) ==> Logic.eq ==> Logic.eq)
    (@fold_context_k term' term).
Admitted.

  Lemma alli_fold_context_k_prop (f : nat -> context_decl term -> bool) (g : nat -> term' -> term) ctx :
    alli f 0 (fold_context_k g ctx) =
    alli (fun i x => f i (map_decl (g (Nat.pred #|ctx| - i)) x)) 0 ctx.
Admitted.

  Lemma test_decl_map_decl f g x : (@test_decl term) f (map_decl g x) = @test_decl term (f ∘ g) x.
Admitted.

  Lemma map_fold_context_k (f : term' -> term) (g : nat -> term'' -> term') ctx :
    map (map_decl f) (fold_context_k g ctx) = fold_context_k (fun i => f ∘ g i) ctx.
Admitted.

  Lemma map_context_mapi_context (f : term' -> term) (g : nat -> term'' -> term') (ctx : list (BasicAst.context_decl term'')) :
    map_context f (mapi_context g ctx) =
    mapi_context (fun i => f ∘ g i) ctx.
Admitted.

  Lemma mapi_context_map (f : nat -> term' -> term) (g : context_decl term'' -> context_decl term') ctx :
    mapi_context f (map g ctx) = mapi (fun i => map_decl (f (Nat.pred #|ctx| - i)) ∘ g) ctx.
Admitted.

  Lemma map_context_map (f : term' -> term) (g : context_decl term'' -> context_decl term') ctx :
    map_c

[...]

in
  let inddecl :=
    {| decl_name :=
      {| binder_name := nNamed (ind_name idecl); binder_relevance := idecl.(ind_relevance) |};
       decl_body := None;
       decl_type := indty |}
  in (inddecl :: ictx).

Definition inst_case_context params puinst (pctx : context) :=
  subst_context (List.rev params) 0 (subst_instance puinst pctx).

Definition inst_case_predicate_context (p : predicate term) :=
  inst_case_context p.(pparams) p.(puinst) p.(pcontext).

Definition inst_case_branch_context (p : predicate term) (br : branch term) :=
  inst_case_context p.(pparams) p.(puinst) br.(bcontext).

Definition iota_red npar p args br :=
  subst (List.rev (List.skipn npar args)) 0
    (expand_lets (inst_case_branch_context p br) (bbody br)).

Definition pre_case_predicate_context_gen ind mdecl idecl params puinst : context :=
  inst_case_context params puinst (ind_predicate_context ind mdecl idecl).

Definition case_predicate_context_gen ind mdecl idecl params puinst pctx :=
  map2 set_binder_name pctx (pre_case_predicate_context_gen ind mdecl idecl params puinst).

Definition case_predicate_context ind mdecl idecl p : context :=
  case_predicate_context_gen ind mdecl idecl p.(pparams) p.(puinst) (forget_types p.(pcontext)).

Definition cstr_branch_context ind mdecl cdecl : context :=
  expand_lets_ctx mdecl.(ind_params)
    (subst_context (inds (inductive_mind ind) (abstract_instance mdecl.(ind_universes))
       mdecl.(ind_bodies)) #|mdecl.(ind_params)|
      cdecl.(cstr_args)).

Definition pre_case_branch_context_gen ind mdecl cdecl params puinst : context :=
  inst_case_context params puinst (cstr_branch_context ind mdecl cdecl).

Definition case_branch_context_gen ind mdecl params puinst pctx cdecl :=
  map2 set_binder_name pctx (pre_case_branch_context_gen ind mdecl cdecl params puinst).

Definition case_branch_type_gen ind mdecl (idecl : one_inductive_body) params puinst bctx ptm i cdecl : context * term :=
  let cstr := tConstruct ind i puinst in
  let args := to_extended_list cdecl.(cstr_args) in
  let cstrapp := mkApps cstr (map (lift0 #|cdecl.(cstr_args)|) params ++ args) in
  let brctx := case_branch_context_gen ind mdecl params puinst bctx cdecl in
  let upars := subst_instance puinst mdecl.(ind_params) in
  let indices :=
    (map (subst (List.rev params) #|cdecl.(cstr_args)|)
      (map (expand_lets_k upars #|cdecl.(cstr_args)|)
        (map (subst (inds (inductive_mind ind) puinst mdecl.(ind_bodies))
                    (#|mdecl.(ind_params)| + #|cdecl.(cstr_args)|))
          (map (subst_instance puinst) cdecl.(cstr_indices))))) in
  let ty := mkApps (lift0 #|cdecl.(cstr_args)| ptm) (indices ++ [cstrapp]) in
  (brctx, ty).

Definition case_branch_type ind mdecl idecl p (b : branch term) ptm i cdecl : context * term :=
  case_branch_type_gen ind mdecl idecl p.(pparams) p.(puinst) (forget_types b.(bcontext)) ptm i cdecl.

Definition idecl_binder idecl :=
  {| decl_name :=
    {| binder_name := nNamed idecl.(ind_name);
        binder_relevance := idecl.(ind_relevance) |};
     decl_body := None;
     decl_type := idecl.(ind_type) |}.

Definition wf_predicate_gen mdecl idecl (pparams : list term) (pcontext : list aname) : Prop :=
  let decl := idecl_binder idecl in
  (#|pparams| = mdecl.(ind_npars)) /\
  (Forall2 (fun na decl => eq_binder_annot na decl.(decl_name))
    pcontext (decl :: idecl.(ind_indices))).

Definition wf_predicate mdecl idecl (p : predicate term) : Prop :=
  wf_predicate_gen mdecl idecl p.(pparams) (forget_types p.(pcontext)).

Definition wf_branch_gen cdecl (bctx : list aname) : Prop :=
  (Forall2 (fun na decl => eq_binder_annot na decl.(decl_name))
    bctx cdecl.(cstr_args)).

Definition wf_branch cdecl (b : branch term) : Prop :=
  wf_branch_gen cdecl (forget_types b.(bcontext)).

Definition wf_branches idecl (brs : list (branch term)) : Prop :=
  Forall2 wf_branch idecl.(ind_ctors) brs.

Definition fix_subst (l : mfixpoint term) :=
  let fix aux n :=
      match n with
      | 0 => []
      | S n => tFix l n :: aux n
      end
  in aux (List.length l).

Definition unfold_fix (mfix : mfixpoint term) (idx : nat) :=
  match List.nth_error mfix idx with
  | Some d => Some (d.(rarg), subst0 (fix_subst mfix) d.(dbody))
  | None => None
  end.

Definition cofix_subst (l : mfixpoint term) :=
  let fix aux n :=
      match n with
      | 0 => []
      | S n => tCoFix l n :: aux n
      end
  in aux (List.length l).

Definition unfold_cofix (mfix : mfixpoint term) (idx : nat) :=
  match List.nth_error mfix idx with
  | Some d => Some (d.(rarg), subst0 (cofix_subst mfix) d.(dbody))
  | None => None
  end.

Definition is_constructor n ts :=
  match List.nth_error ts n with
  | Some a => isConstruct_app a
  | None => false
  end.
Definition cmp_universe_instance (cmp_univ : Universe.t -> Universe.t -> Prop) : Instance.t -> Instance.t -> Prop.
Admitted.

Definition cmp_universe_variance (cmp_univ : conv_pb -> Universe.t -> Universe.t -> Prop) pb v u u' :=
  match v with
  | Variance.Irrelevant => True
  | Variance.Covariant => on_rel (cmp_univ pb) Universe.make' u u'
  | Variance.Invariant => on_rel (cmp_univ Conv) Universe.make' u u'
  end.

Definition cmp_universe_instance_variance cmp_univ pb v u u' :=
  Forall3 (cmp_universe_variance cmp_univ pb) v u u'.

Definition global_variance_gen lookup gr napp :=
  match gr with
  | IndRef ind =>
    match lookup_inductive_gen lookup ind with
    | Some (mdecl, idecl) =>
      match destArity [] idecl.(ind_type) with
      | Some (ctx, _) => if (context_assumptions ctx) <=? napp then
          match mdecl.(ind_variance) with
          | Some var => Variance var
          | None => AllEqual
          end
        else AllEqual
      | None => AllEqual
      end
    | None => AllEqual
    end
  | ConstructRef ind k =>
    match lookup_constructor_gen lookup ind k with
    | Some (mdecl, idecl, cdecl) =>
      if (cdecl.(cstr_arity) + mdecl.(ind_npars))%nat <=? napp then

        AllIrrelevant
      else AllEqual
    | _ => AllEqual
    end
  | _ => AllEqual
  end.

Definition cmp_opt_variance cmp_univ pb v :=
  match v with
  | AllEqual => cmp_universe_instance (cmp_univ Conv)
  | AllIrrelevant => fun l l' => #|l| = #|l'|
  | Variance v => fun u u' => cmp_universe_instance (cmp_univ Conv) u u' \/ cmp_universe_instance_variance cmp_univ pb v u u'
  end.

Definition cmp_global_instance_gen Σ cmp_universe pb gr napp :=
  cmp_opt_variance cmp_universe pb (global_variance_gen Σ gr napp).

Notation cmp_global_instance Σ := (cmp_global_instance_gen (lookup_env Σ)).

Inductive eq_decl_upto_names : context_decl -> context_decl -> Type :=
  | compare_vass {na na' T} :
    eq_binder_annot na na' -> eq_decl_upto_names (vass na T) (vass na' T)
  | compare_vdef {na na' b T} :
    eq_binder_annot na na' -> eq_decl_upto_names (vdef na b T) (vdef na' b T).

Notation eq_context_upto_names := (All2 eq_decl_upto_names).

Definition shiftnP k p i :=
  (i <? k) || p (i - k).
Fixpoint on_free_vars (p : nat -> bool) (t : term) : bool.
Admitted.

Definition on_free_vars_decl P d :=
  test_decl (on_free_vars P) d.

Definition on_free_vars_ctx P ctx :=
  alli (fun k => (on_free_vars_decl (shiftnP k P))) 0 (List.rev ctx).

Notation is_open_term Γ := (on_free_vars (shiftnP #|Γ| xpred0)).
Notation is_closed_context := (on_free_vars_ctx xpred0).
Definition set_preturn (p : predicate term) (pret' : term) : predicate term.
Admitted.
Definition set_pparams (p : predicate term) (pars' : list term) : predicate term.
Admitted.
Definition on_one_decl (P : term -> term -> Type)
  (d : context_decl) (d' : context_decl) : Type.
Admitted.

Section OnOne_local_2.
  Context (P : forall (Γ : context), context_decl -> context_decl -> Type).

  Inductive OnOne2_local_env : context -> context -> Type :=
  | onone2_localenv_cons_abs Γ na na' t t' :
      P Γ (vass na t) (vass na' t') ->
      OnOne2_local_env (Γ ,, vass na t) (Γ ,, vass na' t')
  | onone2_localenv_def Γ na na' b b' t t' :
      P Γ (vdef na b t) (vdef na' b' t') ->
      OnOne2_local_env (Γ ,, vdef na b t) (Γ ,, vdef na' b' t')
  | onone2_localenv_cons_tl Γ Γ' d :
      OnOne2_local_env Γ Γ' ->
      OnOne2_local_env (Γ ,, d) (Γ' ,, d).
End OnOne_local_2.
Arguments exist {_ _} _ _.
Import Equations.Type.Relation.

Reserved Notation " Σ ;;; Γ |- t ⇝ u " (at level 50, Γ, t, u at next level).

Definition set_array_default (ar : array_model term) (v : term) :=
  {| array_level := ar.(array_level);
     array_default := v;
     array_type := ar.(array_type);
     array_value := ar.(array_value) |}.

Definition set_array_type (ar : array_model term) (v : term) :=
  {| array_level := ar.(array_level);
     array_default := ar.(array_default);
     array_type := v;
     array_value := ar.(array_value) |}.

Definition set_array_value (ar : array_model term) (v : list term) :=
  {| array_level := ar.(array_level);
     array_default := ar.(array_default);
     array_type := ar.(array_type);
     array_value := v |}.

Inductive red1 (Σ : global_env) (Γ : context) : term -> term -> Type :=

| red_beta na t b a :
  Σ ;;; Γ |- tApp (tLambda na t b) a ⇝ b {0 := a}

| red_zeta na b t b' :
  Σ ;;; Γ |- tLetIn na b t b' ⇝ b' {0 := b}

| red_rel i body :
    option_map decl_body (nth_error Γ i) = Some (Some body) ->
    Σ ;;; Γ |- tRel i ⇝ lift0 (S i) body

| red_iota ci c u args p brs br :
    nth_error brs c = Some br ->
    #|args| = (ci.(ci_npar) + context_assumptions br.(bcontext))%nat ->
    Σ ;;; Γ |- tCase ci p (mkApps (tConstruct ci.(ci_ind) c u) args) brs
        ⇝ iota_red ci.(ci_npar) p args br

| red_fix mfix idx args narg fn :
    unfold_fix mfix idx = Some (narg, fn) ->
    is_constructor narg args = true ->
    Σ ;;; Γ |- mkApps (tFix mfix idx) args ⇝ mkApps fn args

| red_cofix_case ip p mfix idx args narg fn brs :
    unfold_cofix mfix idx = Some (narg, fn) ->
    Σ ;;; Γ |- tCase ip p (mkApps (tCoFix mfix idx) args) brs ⇝
         tCase ip p (mkApps fn args) brs

| red_cofix_proj p mfix idx args narg fn :
    unfold_cofix mfix idx = Some (narg, fn) ->
    Σ ;;; Γ |- tProj p (mkApps (tCoFix mfix idx) args) ⇝ tProj p (mkApps fn args)

| red_delta c decl body (isdecl : declared_constant Σ c decl) u :
    decl.(cst_body) = Some body ->
    Σ ;;; Γ |- tConst c u ⇝ subst_instance u body

| red_proj p args u arg:
    nth_error args (p.(proj_npars) + p.(proj_arg)) = Some arg ->
    Σ ;;; Γ |- tProj p (mkApps (tConstruct p.(proj_ind) 0 u) args) ⇝ arg

| abs_red_l na M M' N : Σ ;;; Γ |- M ⇝ M' -> Σ ;;; Γ |- tLambda na M N ⇝ tLambda na M' N
| abs_red_r na M M' N : Σ ;;; Γ ,, vass na N |- M ⇝ M' -> Σ ;;; Γ |- tLambda na N M ⇝ tLambda na N M'

| letin_red_def na b t b' r : Σ ;;; Γ |- b ⇝ r -> Σ ;;; Γ |- tLetIn na b t b' ⇝ tLetIn na r t b'
| letin_red_ty na b t b' r : Σ ;;; Γ |- t ⇝ r -> Σ ;;; Γ |- tLetIn na b t b' ⇝ tLetIn na b r b'
| letin_red_body na b t b' r : Σ ;;; Γ ,, vdef na b t |- b' ⇝ r -> Σ ;;; Γ |- tLetIn na b t b' ⇝ tLetIn na b t r

| case_red_param ci p params' c brs :
    OnOne2 (fun t u => Σ ;;; Γ |- t ⇝ u) p.(pparams) params' ->
    Σ ;;; Γ |- tCase ci p c brs ⇝ tCase ci (set_pparams p params') c brs

| case_red_return ci p preturn' c brs :
  Σ ;;; Γ ,,, inst_case_predicate_context p |- p.(preturn) ⇝ preturn' ->
  Σ ;;; Γ |- tCase ci p c brs ⇝ tCase ci (set_preturn p preturn') c brs

| case_red_discr ci p c c' brs :
  Σ ;;; Γ |- c ⇝ c' -> Σ ;;; Γ |- tCase ci p c brs ⇝ tCase ci p c' brs

| case_red_brs ci p c brs brs' :
    OnOne2 (fun br br' =>
      on_Trel_eq (fun t u => Σ ;;; Γ ,,, inst_case_branch_context p br |- t ⇝ u) bbody bcontext br br')
      brs brs' ->
    Σ ;;; Γ |- tCase ci p c brs ⇝ tCase ci p c brs'

| proj_red p c c' : Σ ;;; Γ |- c ⇝ c' -> Σ ;;; Γ |- tProj p c ⇝ tProj p c'

| app_red_l M1 N1 M2 : Σ ;;; Γ |- M1 ⇝ N1 -> Σ ;;; Γ |- tApp M1 M2 ⇝ tApp N1 M2
| app_red_r M2 N2 M1 : Σ ;;; Γ |- M2 ⇝ N2 -> Σ ;;; Γ |- tApp M1 M2 ⇝ tApp M1 N2

| prod_red_l na M1 M2 N1 : Σ ;;; Γ |- M1 ⇝ N1 -> Σ ;;; Γ |- tProd na M1 M2 ⇝ tProd na N1 M2
| prod_red_r na M2 N2 M1 : Σ ;;; Γ ,, vass na M1 |- M2 ⇝ N2 ->
                           Σ ;;; Γ |- tProd na M1 M2 ⇝ tProd na M1 N2

| evar_red ev l l' : OnOne2 (fun t u => Σ ;;; Γ |- t ⇝ u) l l' -> Σ ;;; Γ |- tEvar ev l ⇝ tEvar ev l'

| fix_red_ty mfix0 mfix1 idx :
    OnOne2 (on_Trel_eq (fun t u => Σ ;;; Γ |- t ⇝ u) dtype (fun x => (dname x, dbody x, rarg x))) mfix0 mfix1 ->
    Σ ;;; Γ |- tFix mfix0 idx ⇝ tFix mfix1 idx

| fix_red_body mfix0 mfix1 idx :
    OnOne2 (on_Trel_eq (fun t u => Σ ;;; Γ ,,, fix_context mfix0 |- t ⇝ u) dbody (fun x => (dname x, dtype x, rarg x)))
           mfix0 mfix1 ->
    Σ ;;; Γ |- tFix mfix0 idx ⇝ tFix mfix1 idx

| cofix_red_ty mfix0 mfix1 idx :
    OnOne2 (on_Trel_eq (fun t u => Σ ;;; Γ |- t ⇝ u) dtype (fun x => (dname x, dbody x, rarg x))) mfix0 mfix1 ->
    Σ ;;; Γ |- tCoFix mfix0 idx ⇝ tCoFix mfix1 idx

| cofix_red_body mfix0 mfix1 idx :
    OnOne2 (on_Trel_eq (fun t u => Σ ;;; Γ ,,, fix_context mfix0 |- t ⇝ u) dbody (fun x => (dname x, dtype x, rarg x))) mfix0 mfix1 ->
    Σ ;;; Γ |- tCoFix mfix0 idx ⇝ tCoFix mfix1 idx

| array_red_val arr value :
    OnOne2 (fun t u => Σ ;;; Γ |- t ⇝ u) arr.(array_value) value ->
    Σ ;;; Γ |- tPrim (primArray; primArrayModel arr) ⇝
               tPrim (primArray; primArrayModel (set_array_value arr value))

| array_red_def arr def :
    Σ ;;; Γ |- arr.(array_default) ⇝ def ->
    Σ ;;; Γ |- tPrim (primArray; primArrayModel arr) ⇝
               tPrim (primArray; primArrayModel (set_array_default arr def))

| array_red_type arr ty :
    Σ ;;; Γ |- arr.(array_type) ⇝ ty ->
    Σ ;;; Γ |- tPrim (primArray; primArrayModel arr) ⇝
          tPrim (primArray; primArrayModel (set_array_type arr ty))

where " Σ ;;; Γ |- t ⇝ u " := (red1 Σ Γ t u).

Definition red1_ctx Σ := (OnOne2_local_env (fun Δ => on_one_decl (fun t t' => red1 Σ Δ t t'))).

Definition red Σ Γ := clos_refl_trans (fun t u : term => Σ;;; Γ |- t ⇝ u).
Module Export PCUICCumulativitySpec.

Implicit Types (cf : checker_flags).

Definition cumul_predicate (cumul : context -> term -> term -> Type) cumul_universe Γ p p' :=
  All2 (cumul Γ) p.(pparams) p'.(pparams) ×
  cmp_universe_instance cumul_universe p.(puinst) p'.(puinst) ×
  eq_context_upto_names p.(pcontext) p'.(pcontext) ×
  cumul (Γ ,,, inst_case_predicate_context p) p.(preturn) p'.(preturn).

Definition cumul_branch (cumul_term : context -> term -> term -> Type) Γ p br br' :=
  eq_context_upto_names br.(bcontext) br'.(bcontext) ×
  cumul_term (Γ ,,, inst_case_branch_context p br) br.(bbody) br'.(bbody).

Definition cumul_branches cumul_term Γ p brs brs' := All2 (cumul_branch cumul_term Γ p) brs brs'.

Definition cumul_mfixpoint (cumul_term : context -> term -> term -> Type) Γ mfix mfix' :=
  All2 (fun d d' =>
    cumul_term Γ d.(dtype) d'.(dtype) ×
    cumul_term (Γ ,,, fix_context mfix) d.(dbody) d'.(dbody) ×
    d.(rarg) = d'.(rarg) ×
    eq_binder_annot d.(dname) d'.(dname)
  ) mfix mfix'.

Reserved Notation " Σ ;;; Γ ⊢ t ≤s[ pb ] u" (at level 50, Γ, t, u at next le
10000
vel,
  format "Σ  ;;;  Γ  ⊢  t  ≤s[ pb ]  u").

Definition cumul_Ind_univ {cf} (Σ : global_env_ext) pb i napp :=
  cmp_global_instance Σ (compare_universe Σ) pb (IndRef i) napp.

Definition cumul_Construct_univ {cf} (Σ : global_env_ext) pb  i k napp :=
  cmp_global_instance Σ (compare_universe Σ) pb (ConstructRef i k) napp.
Inductive cumulSpec0 {cf : checker_flags} (Σ : global_env_ext) Γ (pb : conv_pb) : term -> term -> Type :=

| cumul_Trans : forall t u v,
    is_closed_context Γ -> is_open_term Γ u ->
    Σ ;;; Γ ⊢ t ≤s[pb] u ->
    Σ ;;; Γ ⊢ u ≤s[pb] v ->
    Σ ;;; Γ ⊢ t ≤s[pb] v

| cumul_Sym : forall t u,
    Σ ;;; Γ ⊢ t ≤s[Conv] u ->
    Σ ;;; Γ ⊢ u ≤s[pb] t

| cumul_Refl : forall t,
    Σ ;;; Γ ⊢ t ≤s[pb] t

| cumul_Ind : forall i u u' args args',
    cumul_Ind_univ Σ pb i #|args| u u' ->
    All2 (fun t u => Σ ;;; Γ ⊢ t ≤s[Conv] u) args args' ->
    Σ ;;; Γ ⊢ mkApps (tInd i u) args ≤s[pb] mkApps (tInd i u') args'

| cumul_Construct : forall i k u u' args args',
    cumul_Construct_univ Σ pb i k #|args| u u' ->
    All2 (fun t u => Σ ;;; Γ ⊢ t ≤s[Conv] u) args args' ->
    Σ ;;; Γ ⊢ mkApps (tConstruct i k u) args ≤s[pb] mkApps (tConstruct i k u') args'

| cumul_Sort : forall s s',
    compare_sort Σ pb s s' ->
    Σ ;;; Γ ⊢ tSort s ≤s[pb] tSort s'

| cumul_Const : forall c u u',
    cmp_universe_instance (compare_universe Σ Conv) u u' ->
    Σ ;;; Γ ⊢ tConst c u ≤s[pb] tConst c u'

| cumul_Evar : forall e args args',
    All2 (fun t u => Σ ;;; Γ ⊢ t ≤s[Conv] u) args args' ->
    Σ ;;; Γ ⊢ tEvar e args ≤s[pb] tEvar e args'

| cumul_App : forall t t' u u',
    Σ ;;; Γ ⊢ t ≤s[pb] t' ->
    Σ ;;; Γ ⊢ u ≤s[Conv] u' ->
    Σ ;;; Γ ⊢ tApp t u ≤s[pb] tApp t' u'

| cumul_Lambda : forall na na' ty ty' t t',
    eq_binder_annot na na' ->
    Σ ;;; Γ ⊢ ty ≤s[Conv] ty' ->
    Σ ;;; Γ ,, vass na ty ⊢ t ≤s[Conv] t' ->
    Σ ;;; Γ ⊢ tLambda na ty t ≤s[pb] tLambda na' ty' t'

| cumul_Prod : forall na na' a a' b b',
    eq_binder_annot na na' ->
    Σ ;;; Γ ⊢ a ≤s[Conv] a' ->
    Σ ;;; Γ ,, vass na a ⊢ b ≤s[pb] b' ->
    Σ ;;; Γ ⊢ tProd na a b ≤s[pb] tProd na' a' b'

| cumul_LetIn : forall na na' t t' ty ty' u u',
    eq_binder_annot na na' ->
    Σ ;;; Γ ⊢ t ≤s[Conv] t' ->
    Σ ;;; Γ ⊢ ty ≤s[Conv] ty' ->
    Σ ;;; Γ ,, vdef na t ty ⊢ u ≤s[Conv] u' ->
    Σ ;;; Γ ⊢ tLetIn na t ty u ≤s[pb] tLetIn na' t' ty' u'

| cumul_Case indn : forall p p' c c' brs brs',
    cumul_predicate (fun Γ t u => Σ ;;; Γ ⊢ t ≤s[Conv] u) (compare_universe Σ Conv) Γ p p' ->
    Σ ;;; Γ ⊢ c ≤s[Conv] c' ->
    cumul_branches (fun Γ t u => Σ ;;; Γ ⊢ t ≤s[Conv] u) Γ p brs brs' ->
    Σ ;;; Γ ⊢ tCase indn p c brs ≤s[pb] tCase indn p' c' brs'

| cumul_Proj : forall p c c',
    Σ ;;; Γ ⊢ c ≤s[Conv] c' ->
    Σ ;;; Γ ⊢ tProj p c ≤s[pb] tProj p c'

| cumul_Fix : forall mfix mfix' idx,
    cumul_mfixpoint (fun Γ t u => Σ ;;; Γ ⊢ t ≤s[Conv] u) Γ mfix mfix' ->
    Σ ;;; Γ ⊢ tFix mfix idx ≤s[pb] tFix mfix' idx

| cumul_CoFix : forall mfix mfix' idx,
    cumul_mfixpoint (fun Γ t u => Σ ;;; Γ ⊢ t ≤s[Conv] u) Γ mfix mfix' ->
    Σ ;;; Γ ⊢ tCoFix mfix idx ≤s[pb] tCoFix mfix' idx

| cumul_Prim p p' :
  onPrims (fun x y => Σ ;;; Γ ⊢ x ≤s[Conv] y) (compare_universe Σ Conv) p p' ->
  Σ ;;; Γ ⊢ tPrim p ≤s[pb] tPrim p'

| cumul_beta : forall na t b a,
    Σ ;;; Γ ⊢ tApp (tLambda na t b) a ≤s[pb] b {0 := a}

| cumul_zeta : forall na b t b',
    Σ ;;; Γ ⊢ tLetIn na b t b' ≤s[pb] b' {0 := b}

| cumul_rel i body :
    option_map decl_body (nth_error Γ i) = Some (Some body) ->
    Σ ;;; Γ ⊢ tRel i ≤s[pb] lift0 (S i) body

| cumul_iota : forall ci c u args p brs br,
    nth_error brs c = Some br ->
    #|args| = (ci.(ci_npar) + context_assumptions br.(bcontext))%nat ->
    Σ ;;; Γ ⊢ tCase ci p (mkApps (tConstruct ci.(ci_ind) c u) args) brs  ≤s[pb] iota_red ci.(ci_npar) p args br

| cumul_fix : forall mfix idx args narg fn,
    unfold_fix mfix idx = Some (narg, fn) ->
    is_constructor narg args = true ->
    Σ ;;; Γ ⊢ mkApps (tFix mfix idx) args ≤s[pb] mkApps fn args

| cumul_cofix_case : forall ip p mfix idx args narg fn brs,
    unfold_cofix mfix idx = Some (narg, fn) ->
    Σ ;;; Γ ⊢ tCase ip p (mkApps (tCoFix mfix idx) args) brs ≤s[pb] tCase ip p (mkApps fn args) brs

| cumul_cofix_proj : forall p mfix idx args narg fn,
    unfold_cofix mfix idx = Some (narg, fn) ->
    Σ ;;; Γ ⊢ tProj p (mkApps (tCoFix mfix idx) args) ≤s[pb] tProj p (mkApps fn args)

| cumul_delta : forall c decl body (isdecl : declared_constant Σ c decl) u,
    decl.(cst_body) = Some body ->
    Σ ;;; Γ ⊢ tConst c u ≤s[pb] body@[u]

| cumul_proj : forall p args u arg,
    nth_error args (p.(proj_npars) + p.(proj_arg)) = Some arg ->
    Σ ;;; Γ ⊢ tProj p (mkApps (tConstruct p.(proj_ind) 0 u) args) ≤s[pb] arg

where " Σ ;;; Γ ⊢ t ≤s[ pb ] u " := (@cumulSpec0 _ Σ Γ pb t u) : type_scope.
Definition cumulSpec `{checker_flags} (Σ : global_env_ext) Γ := cumulSpec0 Σ Γ Cumul.

Notation " Σ ;;; Γ |- t <=s u " := (@cumulSpec _ Σ Γ t u) (at level 50, Γ, t, u at next level).

Module PCUICConversionParSpec <: EnvironmentTyping.ConversionParSig PCUICTerm PCUICEnvironment PCUICTermUtils PCUICEnvTyping.
End PCUICConversionParSpec.

End PCUICCumulativitySpec.

Implicit Types (cf : checker_flags) (Σ : global_env_ext).

Definition type_of_constructor mdecl (cdecl : constructor_body) (c : inductive * nat) (u : list Level.t) :=
  let mind := inductive_mind (fst c) in
  subst0 (inds mind u mdecl.(ind_bodies)) (subst_instance u (cstr_type cdecl)).

Include PCUICEnvTyping.

Inductive FixCoFix : Type := Fix | CoFix.

Class GuardChecker :=
{
  guard : FixCoFix -> global_env_ext -> context -> mfixpoint term -> Prop ;
}.

Axiom guard_checking : GuardChecker.
#[global]
Existing Instance guard_checking.

Definition fix_guard := guard Fix.
Definition cofix_guard := guard CoFix.

Definition destInd (t : term) :=
  match t with
  | tInd ind u => Some (ind, u)
  | _ => None
  end.

Definition isCoFinite (r : recursivity_kind) :=
  match r with
  | CoFinite => true
  | _ => false
  end.

Definition check_recursivity_kind
  (lookup: kername -> option global_decl) ind r :=
  match lookup ind with
  | Some (InductiveDecl mib) => ReflectEq.eqb mib.(ind_finite) r
  | _ => false
  end.

Definition check_one_fix d :=
  let '{| dname := na;
         dtype := ty;
         dbody := b;
         rarg := arg |} := d in
  let '(ctx, ty) := decompose_prod_assum [] ty in
  match nth_error (List.rev (smash_context [] ctx)) arg with
  | Some argd =>
    let (hd, args) := decompose_app argd.(decl_type) in
    match destInd hd with
    | Some (mkInd mind _, u) => Some mind
    | None => None
    end
  | None => None
  end.

Definition wf_fixpoint_gen
  (lookup: kername -> option global_decl) mfix :=
  forallb (isLambda ∘ dbody) mfix &&
  let checks := map check_one_fix mfix in
  match map_option_out checks with
  | Some (ind :: inds) =>

    forallb (eqb ind) inds &&
    check_recursivity_kind lookup ind Finite
  | _ => false
  end.

Definition wf_fixpoint (Σ : global_env) := wf_fixpoint_gen (lookup_env Σ).

Definition check_one_cofix d :=
  let '{| dname := na;
         dtype := ty;
         dbody := b;
         rarg := arg |} := d in
  let '(ctx, ty) := decompose_prod_assum [] ty in
  let (hd, args) := decompose_app ty in
  match destInd hd with
  | Some (mkInd ind _, u) => Some ind
  | None => None
  end.

Definition wf_cofixpoint_gen
  (lookup: kername -> option global_decl) mfix :=
  let checks := map check_one_cofix mfix in
  match map_option_out checks with
  | Some (ind :: inds) =>

    forallb (eqb ind) inds &&
    check_recursivity_kind lookup ind CoFinite
  | _ => false
  end.

Definition wf_cofixpoint (Σ : global_env) := wf_cofixpoint_gen (lookup_env Σ).

Reserved Notation "'wf_local' Σ Γ " (at level 9, Σ, Γ at next level).

Reserved Notation " Σ ;;; Γ |- t : T " (at level 50, Γ, t, T at next level).

Variant case_side_conditions `{checker_flags} wf_local_fun typing Σ Γ ci p ps mdecl idecl indices predctx :=
| case_side_info
    (eq_npars : mdecl.(ind_npars) = ci.(ci_npar))
    (wf_pred : wf_predicate mdecl idecl p)
    (cons : consistent_instance_ext Σ (ind_universes mdecl) p.(puinst))
    (wf_pctx : wf_local_fun Σ (Γ ,,, predctx))

    (conv_pctx : eq_context_upto_names p.(pcontext) (ind_predicate_context ci.(ci_ind) mdecl idecl))
    (allowed_elim : is_allowed_elimination Σ idecl.(ind_kelim) ps)
    (elim_relevance : isSortRel ps ci.(ci_relevance))
    (ind_inst : ctx_inst (typing Σ) Γ (p.(pparams) ++ indices)
                         (List.rev (subst_instance p.(puinst)
                                                   (ind_params mdecl ,,, ind_indices idecl : context))))
    (not_cofinite : isCoFinite mdecl.(ind_finite) = false).

Variant case_branch_typing `{checker_flags} wf_local_fun typing Σ Γ (ci:case_info) p ps mdecl idecl ptm  brs :=
| case_branch_info
    (wf_brs : wf_branches idecl brs)
    (brs_ty :
       All2i (fun i cdecl br =>

                eq_context_upto_names br.(bcontext) (cstr_branch_context ci mdecl cdecl) ×
                let brctxty := case_branch_type ci.(ci_ind) mdecl idecl p br ptm i cdecl in
                (wf_local_fun Σ (Γ ,,, brctxty.1) ×
                ((typing Σ (Γ ,,, brctxty.1) br.(bbody) (brctxty.2)) ×
                (typing Σ (Γ ,,, brctxty.1) brctxty.2 (tSort ps)))))
             0 idecl.(ind_ctors) brs).

Variant primitive_typing_hyps `{checker_flags}
  (typing : forall (Σ : global_env_ext) (Γ : context), term -> term -> Type)
  Σ Γ : prim_val term -> Type :=
| prim_int_hyps i : primitive_typing_hyps typing Σ Γ (primInt; primIntModel i)
| prim_float_hyps f : primitive_typing_hyps typing Σ Γ (primFloat; primFloatModel f)
| prim_string_hyps s : primitive_typing_hyps typing Σ Γ (primString; primStringModel s)
| prim_array_hyps a
  (wfl : wf_universe Σ (Universe.make' a.(array_level)))
  (hty : typing Σ Γ a.(array_type) (tSort (sType (Universe.make' a.(array_level)))))
  (hdef : typing Σ Γ a.(array_default) a.(array_type))
  (hvalue : All (fun x => typing Σ Γ x a.(array_type)) a.(array_value)) :
  primitive_typing_hyps typing Σ Γ (primArray; primArrayModel a).

Equations prim_type (p : prim_val term) (cst : kername) : term :=
prim_type (primInt; _) cst := tConst cst [];
prim_type (primFloat; _) cst := tConst cst [];
prim_type (primString; _) cst := tConst cst [];
prim_type (primArray; primArrayModel a) cst := tApp (tConst cst [a.(array_level)]) a.(array_type).

Inductive typing `{checker_flags} (Σ : global_env_ext) (Γ : context) : term -> term -> Type :=
| type_Rel : forall n decl,
    wf_local Σ Γ ->
    nth_error Γ n = Some decl ->
    Σ ;;; Γ |- tRel n : lift0 (S n) decl.(decl_type)

| type_Sort : forall s,
    wf_local Σ Γ ->
    wf_sort Σ s ->
    Σ ;;; Γ |- tSort s : tSort (Sort.super s)

| type_Prod : forall na A B s1 s2,
    lift_typing typing Σ Γ (j_vass_s na A s1) ->
    Σ ;;; Γ ,, vass na A |- B : tSort s2 ->
    Σ ;;; Γ |- tProd na A B : tSort (Sort.sort_of_product s1 s2)

| type_Lambda : forall na A t B,
    lift_typing typing Σ Γ (j_vass na A) ->
    Σ ;;; Γ ,, vass na A |- t : B ->
    Σ ;;; Γ |- tLambda na A t : tProd na A B

| type_LetIn : forall na b B t A,
    lift_typing typing Σ Γ (j_vdef na b B) ->
    Σ ;;; Γ ,, vdef na b B |- t : A ->
    Σ ;;; Γ |- tLetIn na b B t : tLetIn na b B A

| type_App : forall t na A B s u,

    Σ ;;; Γ |- tProd na A B : tSort s ->
    Σ ;;; Γ |- t : tProd na A B ->
    Σ ;;; Γ |- u : A ->
    Σ ;;; Γ |- tApp t u : B{0 := u}

| type_Const : forall cst u decl,
    wf_local Σ Γ ->
    declared_constant Σ cst decl ->
    consistent_instance_ext Σ decl.(cst_universes) u ->
    Σ ;;; Γ |- tConst cst u : decl.(cst_type)@[u]

| type_Ind : forall ind u mdecl idecl,
    wf_local Σ Γ ->
    declared_inductive Σ ind mdecl idecl ->
    consistent_instance_ext Σ mdecl.(ind_universes) u ->
    Σ ;;; Γ |- tInd ind u : idecl.(ind_type)@[u]

| type_Construct : forall ind i u mdecl idecl cdecl,
    wf_local Σ Γ ->
    declared_constructor Σ (ind, i) mdecl idecl cdecl ->
    consistent_instance_ext Σ mdecl.(ind_universes) u ->
    Σ ;;; Γ |- tConstruct ind i u : type_of_constructor mdecl cdecl (ind, i) u

| type_Case : forall ci p c brs indices ps mdecl idecl,
    let predctx := case_predicate_context ci.(ci_ind) mdecl idecl p in
    let ptm := it_mkLambda_or_LetIn predctx p.(preturn) in
    declared_inductive Σ ci.(ci_ind) mdecl idecl ->
    Σ ;;; Γ ,,, predctx |- p.(preturn) : tSort ps ->
    Σ ;;; Γ |- c : mkApps (tInd ci.(ci_ind) p.(puinst)) (p.(pparams) ++ indices) ->
    case_side_conditions (fun Σ Γ => wf_local Σ Γ) typing Σ Γ ci p ps
                         mdecl idecl indices predctx  ->
    case_branch_typing (fun Σ Γ => wf_local Σ Γ) typing Σ Γ ci p ps
                        mdecl idecl ptm brs ->
    Σ ;;; Γ |- tCase ci p c brs : mkApps ptm (indices ++ [c])

| type_Proj : forall p c u mdecl idecl cdecl pdecl args,
    declared_projection Σ p mdecl idecl cdecl pdecl ->
    Σ ;;; Γ |- c : mkApps (tInd p.(proj_ind) u) args ->
    #|args| = ind_npars mdecl ->
    Σ ;;; Γ |- tProj p c : subst0 (c :: List.rev args) pdecl.(proj_type)@[u]

| type_Fix : forall mfix n decl,
    wf_local Σ Γ ->
    fix_guard Σ Γ mfix ->
    nth_error mfix n = Some decl ->
    All (on_def_type (lift_typing1 (typing Σ)) Γ) mfix ->
    All (on_def_body (lift_typing1 (typing Σ)) (fix_context mfix) Γ) mfix ->
    wf_fixpoint Σ mfix ->
    Σ ;;; Γ |- tFix mfix n : decl.(dtype)

| type_CoFix : forall mfix n decl,
    wf_local Σ Γ ->
    cofix_guard Σ Γ mfix ->
    nth_error mfix n = Some decl ->
    All (on_def_type (lift_typing1 (typing Σ)) Γ) mfix ->
    All (on_def_body (lift_typing1 (typing Σ)) (fix_context mfix) Γ) mfix ->
    wf_cofixpoint Σ mfix ->
    Σ ;;; Γ |- tCoFix mfix n : decl.(dtype)

| type_Prim p prim_ty cdecl :
    wf_local Σ Γ ->
    primitive_constant Σ (prim_val_tag p) = Some prim_ty ->
    declared_constant Σ prim_ty cdecl ->
    primitive_invariants (prim_val_tag p) cdecl ->
    primitive_typing_hyps typing Σ Γ p ->
    Σ ;;; Γ |- tPrim p : prim_type p prim_ty

| type_Cumul : forall t A B s,
    Σ ;;; Γ |- t : A ->
    Σ ;;; Γ |- B : tSort s ->
    Σ ;;; Γ |- A <=s B ->
    Σ ;;; Γ |- t : B

where " Σ ;;; Γ |- t : T " := (typing Σ Γ t T)
and "'wf_local' Σ Γ " := (All_local_env (lift_typing1 (typing Σ)) Γ).

Definition wf `{checker_flags} := on_global_env cumulSpec0 (lift_typing typing).
Notation on_contexts_length := All2_fold_length.
Import Stdlib.ssr.ssreflect.
Import Equations.Prop.Equations.
Import Stdlib.Classes.CRelationClasses.
Import Equations.Type.Relation_Properties.

Definition ws_term P := { t : term | on_free_vars P t }.
Definition ws_term_proj {P} (t : ws_term P) : term.
admit.
Defined.
Coercion ws_term_proj : ws_term >-> term.

Definition ws_context P := { t : context | on_free_vars_ctx P t }.

Notation closed_context := (ws_context xpred0).
Notation open_term Γ := (ws_term (shiftnP #|Γ| xpred0)).
Definition ws_context_proj' {P} (t : ws_context P) : list context_decl.
Admitted.
Coercion ws_context_proj' : ws_context >-> list.

Definition ws_red1 Σ P (Γ : ws_context P) (t u : ws_term (shiftnP #|Γ| P)) :=
  red1 Σ Γ t u.

Definition ws_red Σ P (Γ : ws_context P) := clos_refl_trans (ws_red1 Σ P Γ).

Definition ws_pair :=
  ∑ Γ : ws_context xpred0, ws_term (shiftnP #|Γ| xpred0).

Section RedConfluence.
  Context {cf : checker_flags}.
  Context {Σ : global_env_ext} (wfΣ : wf Σ).
Definition red1_rel_alpha : relation ws_pair.
exact (relation_disjunction (A:=ws_pair) (fun '(Γ; t) '(Δ; u) => (red1 Σ Γ t u * (Γ = Δ)))%type
     (relation_disjunction (A:=ws_pair)
        (fun '(Γ; t) '(Δ; u) => ((red1_ctx Σ Γ Δ * (t = u :> term))))
        (fun '(Γ; t) '(Δ; u) => ((eq_context_upto_names Γ Δ * (t = u :> term)))))%type).
Defined.

  Lemma red_ws_red (Γ : closed_context) (x y : ws_term (shiftnP #|Γ| xpred0)) :
    red Σ Γ x y -> ws_red Σ xpred0 Γ x y.
Admitted.
Definition transport_ws_term {n m : nat} (t : ws_term (shiftnP n xpred0)) (eq : n = m) : ws_term (shiftnP m xpred0).
Admitted.
Definition red_ctx_alpha : relation context.
exact (All2_fold (fun Γ _ => All_decls_alpha (red Σ Γ))).
Defined.

  Instance red_ctx_alpha_refl : Reflexive red_ctx_alpha.
Admitted.

  Lemma ws_red_refl_irrel P (Γ : ws_context P) (x y : ws_term (shiftnP #|Γ| P)) :
    x = y :> term ->
    ws_red Σ P Γ x y.
Admitted.

  Lemma clos_rt_red1_alpha_out x y :
    clos_refl_trans red1_rel_alpha x y ->
    ∑ redctx : red_ctx_alpha x.π1 y.π1,
      ws_red Σ xpred0 x.π1 x.π2 (transport_ws_term y.π2 (symmetry (All2_fold_length redctx))).
  Proof using wfΣ.
    intros H.
    eapply clos_rt_rt1n_iff in H.
    induction H.
    -
 unshelve eexists.
reflexivity.
eapply ws_red_refl_irrel => //.
    -
 destruct x as [Γ t], y as [Δ u], z as [Δ' u']; simpl in *.
      destruct IHclos_refl_trans_1n.
      red in r.
destruct r.
      *
 destruct p.
subst.
exists x.
        transitivity u; auto.
        now eapply red_ws_red.
      *
 destruct t as [t ht], u as [u hu];
        move: r; case; move => [] r eq; noconf eq.
🛠️ Intermediate Coq File (useful for debugging if minimization did not go as far as you wanted)
🛠️ 📜 Intermediate Coq File log (useful for debugging if minimization did not go as far as you wanted)
📜 Build Log (contains the Coq error message) (truncated to last 8.0KiB; full 7.0MiB file on GitHub Actions Artifacts under build.log)
t-minimizer.WuFprGYhYy
MINIMIZER_DEBUG: files: 
make[2]: Leaving directory '/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/template-rocq'
# Ensure the cmxs is built before the loader file 
make -f Makefile.plugin gen-src/metarocq_template_plugin.cmxs
make[2]: Entering directory '/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/template-rocq'
MINIMIZER_DEBUG_EXTRA: coqc: /github/workspace/builds/coq/coq-failing/_install_ci/bin///rocq
MINIMIZER_DEBUG_EXTRA: original invocation: c --print-version 
MINIMIZER_DEBUG_EXTRA: new invocation: /github/workspace/builds/coq/coq-failing/_install_ci/bin/rocq.orig c --print-version 
MINIMIZER_DEBUG_EXTRA: coqpath: 
MINIMIZER_DEBUG_EXTRA: ocamlpath: /github/workspace/builds/coq/coq-failing/_build_ci/metarocq/template-rocq/:/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/safechecker-plugin/src:/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/erasure-plugin/src:/github/workspace/builds/coq/coq-failing/_install_ci/lib:
MINIMIZER_DEBUG_EXTRA: pwd: PWD=/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/template-rocq
MINIMIZER_DEBUG_EXTRA: exec: /github/workspace/builds/coq/coq-failing/_install_ci/bin/rocq.orig c --print-version 
MINIMIZER_DEBUG_EXTRA: coqlib: Warning: Deprecated environment variable COQLIB, use ROCQLIB instead.
/github/workspace/builds/coq/coq-failing/_install_ci/lib/coq//
MINIMIZER_DEBUG: info: /tmp/tmp-coqbot-minimizer.ZQTtmlFnBb
MINIMIZER_DEBUG: files: 
make[2]: 'gen-src/metarocq_template_plugin.cmxs' is up to date.
make[2]: Leaving directory '/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/template-rocq'
make -f Makefile.plugin
make[2]: Entering directory '/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/template-rocq'
MINIMIZER_DEBUG_EXTRA: coqc: /github/workspace/builds/coq/coq-failing/_install_ci/bin///rocq
MINIMIZER_DEBUG_EXTRA: original invocation: c --print-version 
MINIMIZER_DEBUG_EXTRA: new invocation: /github/workspace/builds/coq/coq-failing/_install_ci/bin/rocq.orig c --print-version 
MINIMIZER_DEBUG_EXTRA: coqpath: 
MINIMIZER_DEBUG_EXTRA: ocamlpath: /github/workspace/builds/coq/coq-failing/_build_ci/metarocq/template-rocq/:/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/safechecker-plugin/src:/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/erasure-plugin/src:/github/workspace/builds/coq/coq-failing/_install_ci/lib:
MINIMIZER_DEBUG_EXTRA: pwd: PWD=/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/template-rocq
MINIMIZER_DEBUG_EXTRA: exec: /github/workspace/builds/coq/coq-failing/_install_ci/bin/rocq.orig c --print-version 
MINIMIZER_DEBUG_EXTRA: coqlib: Warning: Deprecated environment variable COQLIB, use ROCQLIB instead.
/github/workspace/builds/coq/coq-failing/_install_ci/lib/coq//
MINIMIZER_DEBUG: info: /tmp/tmp-coqbot-minimizer.lv52Erhq4U
MINIMIZER_DEBUG: files: 
MINIMIZER_DEBUG_EXTRA: coqc: /github/workspace/builds/coq/coq-failing/_install_ci/bin/////rocq
MINIMIZER_DEBUG_EXTRA: original invocation: c --print-version 
MINIMIZER_DEBUG_EXTRA: new invocation: /github/workspace/builds/coq/coq-failing/_install_ci/bin/rocq.orig c --print-version 
MINIMIZER_DEBUG_EXTRA: coqpath: 
MINIMIZER_DEBUG_EXTRA: ocamlpath: /github/workspace/builds/coq/coq-failing/_build_ci/metarocq/template-rocq/:/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/safechecker-plugin/src:/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/erasure-plugin/src:/github/workspace/builds/coq/coq-failing/_install_ci/lib:
MINIMIZER_DEBUG_EXTRA: pwd: PWD=/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/template-rocq
MINIMIZER_DEBUG_EXTRA: exec: /github/workspace/builds/coq/coq-failing/_install_ci/bin/rocq.orig c --print-version 
MINIMIZER_DEBUG_EXTRA: coqlib: Warning: Deprecated environment variable COQLIB, use ROCQLIB instead.
/github/workspace/builds/coq/coq-failing/_install_ci/lib/coq//
MINIMIZER_DEBUG: info: /tmp/tmp-coqbot-minimizer.InZOjWVYhv
MINIMIZER_DEBUG: files: 
MINIMIZER_DEBUG_EXTRA: coqc: /github/workspace/builds/coq/coq-failing/_install_ci/bin/////rocq
MINIMIZER_DEBUG_EXTRA: original invocation: c --print-version 
MINIMIZER_DEBUG_EXTRA: new invocation: /github/workspace/builds/coq/coq-failing/_install_ci/bin/rocq.orig c --print-version 
MINIMIZER_DEBUG_EXTRA: coqpath: 
MINIMIZER_DEBUG_EXTRA: ocamlpath: /github/workspace/builds/coq/coq-failing/_build_ci/metarocq/template-rocq/:/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/safechecker-plugin/src:/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/erasure-plugin/src:/github/workspace/builds/coq/coq-failing/_install_ci/lib:
MINIMIZER_DEBUG_EXTRA: pwd: PWD=/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/template-rocq
MINIMIZER_DEBUG_EXTRA: exec: /github/workspace/builds/coq/coq-failing/_install_ci/bin/rocq.orig c --print-version 
MINIMIZER_DEBUG_EXTRA: coqlib: Warning: Deprecated environment variable COQLIB, use ROCQLIB instead.
/github/workspace/builds/coq/coq-failing/_install_ci/lib/coq//
MINIMIZER_DEBUG: info: /tmp/tmp-coqbot-minimizer.qifoYhPmc9
MINIMIZER_DEBUG: files: 
make[3]: Nothing to be done for 'real-all'.
MINIMIZER_DEBUG_EXTRA: coqc: /github/workspace/builds/coq/coq-failing/_install_ci/bin/////rocq
MINIMIZER_DEBUG_EXTRA: original invocation: c --print-version 
MINIMIZER_DEBUG_EXTRA: new invocation: /github/workspace/builds/coq/coq-failing/_install_ci/bin/rocq.orig c --print-version 
MINIMIZER_DEBUG_EXTRA: coqpath: 
MINIMIZER_DEBUG_EXTRA: ocamlpath: /github/workspace/builds/coq/coq-failing/_build_ci/metarocq/template-rocq/:/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/safechecker-plugin/src:/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/erasure-plugin/src:/github/workspace/builds/coq/coq-failing/_install_ci/lib:
MINIMIZER_DEBUG_EXTRA: pwd: PWD=/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/template-rocq
MINIMIZER_DEBUG_EXTRA: exec: /github/workspace/builds/coq/coq-failing/_install_ci/bin/rocq.orig c --print-version 
MINIMIZER_DEBUG_EXTRA: coqlib: Warning: Deprecated environment variable COQLIB, use ROCQLIB instead.
/github/workspace/builds/coq/coq-failing/_install_ci/lib/coq//
MINIMIZER_DEBUG: info: /tmp/tmp-coqbot-minimizer.wBaeUigk9s
MINIMIZER_DEBUG: files: 
make[2]: Leaving directory '/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/template-rocq'
make[1]: Leaving directory '/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/template-rocq'
File "./theories/PCUICConfluence.v", line 3649, characters 47-49:
Error: Cannot infer the implicit parameter A of eq whose type is 
"Type" in
environment:
cf : checker_flags
Σ : global_env_ext
wfΣ : wf Σ
Γ : closed_context
t : term
ht : is_open_term Γ t
Δ : closed_context
u : term
hu : is_open_term Δ u
Δ' : closed_context
u' : open_term Δ'
H : clos_refl_trans_1n red1_rel_alpha (Δ; exist u hu) (Δ'; u')
x : red_ctx_alpha Δ Δ'
w :
  ws_red Σ xpred0 Δ (exist u hu)
    (transport_ws_term u' (symmetry (on_contexts_length x)))
r : red1_ctx Σ Γ Δ
eq : exist t ht = exist u hu

Command exited with non-zero status 1
theories/PCUICConfluence.vo (real: 46.13, user: 45.77, sys: 0.36, mem: 2429952 ko)
make[3]: *** [Makefile.rocq:814: theories/PCUICConfluence.vo] Error 1
make[3]: *** [theories/PCUICConfluence.vo] Deleting file 'theories/PCUICConfluence.glob'
make[2]: *** [Makefile.rocq:412: all] Error 2
make[2]: Leaving directory '/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/pcuic'
make[1]: *** [Makefile:11: coq] Error 2
make[1]: Leaving directory '/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/pcuic'
make: *** [Makefile:149: pcuic] Error 2
+ code=2
+ printf '\n%s exit code: %s\n' metarocq 2
+ '[' metarocq '!=' stdlib_test ']'
+ echo 'Aggregating timing log...'
Aggregating timing log...
+ echo

+ tools/make-one-time-file.py --real metarocq.log
    Time |   Peak Mem | File Name            
---------------------------------------------
0m46.13s | 2429952 ko | Total Time / Peak Mem
---------------------------------------------
0m46.13s | 2429952 ko | PCUICConfluence.vo   
+ '[' '' ']'
+ exit 2
/github/workspace/builds/coq /github/workspace
::endgroup::
📜 🔎 Minimization Log (truncated to last 8.0KiB; full 1.1MiB file on GitHub Actions Artifacts under bug.log)
ctor.t is known to be technically difficult, see
<https://github.com/coq/stdlib/blob/master/theories/Vectors/Vector.v>.
[warn-library-file-stdlib-vector,stdlib-vector,warn-library-file,user-warn,default]
File "/tmp/tmp_ixcidxp/Top/bug_01.v", line 287, characters 0-31:
Warning: Library File Stdlib.Vectors.Bvector is deprecated since 8.20.
Consider [list bool] instead. See <https://github.com/coq/stdlib/blob/master/theories/Vectors/Vector.v> for details. Please open an issue if you would like to keep using Bvector.
[deprecated-library-file-since-8.20,deprecated-since-8.20,deprecated-library-file,deprecated,default]
File "/tmp/tmp_ixcidxp/Top/bug_01.v", line 309, characters 0-34:
Warning: Library File Stdlib.ZArith.ZArith_base is deprecated since 9.0.
use ZArith instead
[deprecated-library-file-since-9.0,deprecated-since-9.0,deprecated-library-file,deprecated,default]
File "/tmp/tmp_ixcidxp/Top/bug_01.v", line 365, characters 7-20:
Warning: Coq.Init.Ltac has been replaced by Corelib.Init.Ltac.
[deprecated-dirpath-Coq,deprecated-since-9.0,deprecated,default]
File "/tmp/tmp_ixcidxp/Top/bug_01.v", line 1042, characters 0-38:
Error: Signature components for field compare_spec do not match:
expected type
"forall x y : Level.t,
 CompareSpec (Level.eq x y) (Level.lt x y) (Level.lt y x) (Level.compare x y)"
but found type
"forall x y : Level.t,
 CompareSpec (x = y) (Level.lt x y) (Level.lt y x) (Level.compare x y)".


�[93mIntermediate code not saved.�[0m
Failed to do everything at once; trying one at a time.
Admitting definitions unsuccessful.
No successful changes.

I will now attempt to admit lemmas with admit. Defined with Proof using

Non-fatal error: Failed to admit lemmas and preserve the error.  
The new error was:
Deprecated environment variable COQCORELIB, use ROCQRUNTIMELIB instead.
Warning: Deprecated environment variable COQCORELIB,
use ROCQRUNTIMELIB instead.
[deprecated-coq-env-var,deprecated-since-9.0,deprecated,default]
File "/tmp/tmplq1lcvr9/Top/bug_01.v", line 277, characters 0-27:
Warning: Alternatives to Fin.t are available, see
<https://github.com/coq/stdlib/blob/master/theories/Vectors/Fin.v>.
[warn-library-file-stdlib-vector,stdlib-vector,warn-library-file,user-warn,default]
File "/tmp/tmplq1lcvr9/Top/bug_01.v", line 278, characters 0-33:
Warning: Using Vector.t is known to be technically difficult, see
<https://github.com/coq/stdlib/blob/master/theories/Vectors/Vector.v>.
[warn-library-file-stdlib-vector,stdlib-vector,warn-library-file,user-warn,default]
File "/tmp/tmplq1lcvr9/Top/bug_01.v", line 281, characters 0-34:
Warning: Using Vector.t is known to be technically difficult, see
<https://github.com/coq/stdlib/blob/master/theories/Vectors/Vector.v>.
[warn-library-file-stdlib-vector,stdlib-vector,warn-library-file,user-warn,default]
File "/tmp/tmplq1lcvr9/Top/bug_01.v", line 282, characters 0-32:
Warning: Using Vector.t is known to be technically difficult, see
<https://github.com/coq/stdlib/blob/master/theories/Vectors/Vector.v>.
[warn-library-file-stdlib-vector,stdlib-vector,warn-library-file,user-warn,default]
File "/tmp/tmplq1lcvr9/Top/bug_01.v", line 283, characters 0-30:
Warning: Using Vector.t is known to be technically difficult, see
<https://github.com/coq/stdlib/blob/master/theories/Vectors/Vector.v>.
[warn-library-file-stdlib-vector,stdlib-vector,warn-library-file,user-warn,default]
File "/tmp/tmplq1lcvr9/Top/bug_01.v", line 287, characters 0-31:
Warning: Library File Stdlib.Vectors.Bvector is deprecated since 8.20.
Consider [list bool] instead. See <https://github.com/coq/stdlib/blob/master/theories/Vectors/Vector.v> for details. Please open an issue if you would like to keep using Bvector.
[deprecated-library-file-since-8.20,deprecated-since-8.20,deprecated-library-file,deprecated,default]
File "/tmp/tmplq1lcvr9/Top/bug_01.v", line 309, characters 0-34:
Warning: Library File Stdlib.ZArith.ZArith_base is deprecated since 9.0.
use ZArith instead
[deprecated-library-file-since-9.0,deprecated-since-9.0,deprecated-library-file,deprecated,default]
File "/tmp/tmplq1lcvr9/Top/bug_01.v", line 365, characters 7-20:
Warning: Coq.Init.Ltac has been replaced by Corelib.Init.Ltac.
[deprecated-dirpath-Coq,deprecated-since-9.0,deprecated,default]
Error: The section RedConfluence, module PCUICPrimitive, module
EnvironmentTyping and module Retroknowledge need to be closed.


�[93mIntermediate code not saved.�[0m
Failed to do everything at once; trying one at a time.
Admitting lemmas unsuccessful.
No successful changes.

I will now attempt to admit definitions with admit. Defined with Proof using

Non-fatal error: Failed to admit definitions and preserve the error.  
The new error was:
Deprecated environment variable COQCORELIB, use ROCQRUNTIMELIB instead.
Warning: Deprecated environment variable COQCORELIB,
use ROCQRUNTIMELIB instead.
[deprecated-coq-env-var,deprecated-since-9.0,deprecated,default]
File "/tmp/tmpqftq6dz_/Top/bug_01.v", line 277, characters 0-27:
Warning: Alternatives to Fin.t are available, see
<https://github.com/coq/stdlib/blob/master/theories/Vectors/Fin.v>.
[warn-library-file-stdlib-vector,stdlib-vector,warn-library-file,user-warn,default]
File "/tmp/tmpqftq6dz_/Top/bug_01.v", line 278, characters 0-33:
Warning: Using Vector.t is known to be technically difficult, see
<https://github.com/coq/stdlib/blob/master/theories/Vectors/Vector.v>.
[warn-library-file-stdlib-vector,stdlib-vector,warn-library-file,user-warn,default]
File "/tmp/tmpqftq6dz_/Top/bug_01.v", line 281, characters 0-34:
Warning: Using Vector.t is known to be technically difficult, see
<https://github.com/coq/stdlib/blob/master/theories/Vectors/Vector.v>.
[warn-library-file-stdlib-vector,stdlib-vector,warn-library-file,user-warn,default]
File "/tmp/tmpqftq6dz_/Top/bug_01.v", line 282, characters 0-32:
Warning: Using Vector.t is known to be technically difficult, see
<https://github.com/coq/stdlib/blob/master/theories/Vectors/Vector.v>.
[warn-library-file-stdlib-vector,stdlib-vector,warn-library-file,user-warn,default]
File "/tmp/tmpqftq6dz_/Top/bug_01.v", line 283, characters 0-30:
Warning: Using Vector.t is known to be technically difficult, see
<https://github.com/coq/stdlib/blob/master/theories/Vectors/Vector.v>.
[warn-library-file-stdlib-vector,stdlib-vector,warn-library-file,user-warn,default]
File "/tmp/tmpqftq6dz_/Top/bug_01.v", line 287, characters 0-31:
Warning: Library File Stdlib.Vectors.Bvector is deprecated since 8.20.
Consider [list bool] instead. See <https://github.com/coq/stdlib/blob/master/theories/Vectors/Vector.v> for details. Please open an issue if you would like to keep using Bvector.
[deprecated-library-file-since-8.20,deprecated-since-8.20,deprecated-library-file,deprecated,default]
File "/tmp/tmpqftq6dz_/Top/bug_01.v", line 309, characters 0-34:
Warning: Library File Stdlib.ZArith.ZArith_base is deprecated since 9.0.
use ZArith instead
[deprecated-library-file-since-9.0,deprecated-since-9.0,deprecated-library-file,deprecated,default]
File "/tmp/tmpqftq6dz_/Top/bug_01.v", line 365, characters 7-20:
Warning: Coq.Init.Ltac has been replaced by Corelib.Init.Ltac.
[deprecated-dirpath-Coq,deprecated-since-9.0,deprecated,default]
File "/tmp/tmpqftq6dz_/Top/bug_01.v", line 1043, characters 0-38:
Error: Signature components for field compare_spec do not match:
expected type
"forall x y : Level.t,
 CompareSpec (Level.eq x y) (Level.lt x y) (Level.lt y x) (Level.compare x y)"
but found type
"forall x y : Level.t,
 CompareSpec (x = y) (Level.lt x y) (Level.lt y x) (Level.compare x y)".


�[93mIntermediate code not saved.�[0m
Failed to do everything at once; trying one at a time.
Admitting definitions unsuccessful.
No successful changes.

I will now attempt to add Proof using lines
�[92m
Adding Proof using lines successful.�[0m
Failed to do everything at once; trying one at a time.
Adding Proof using lines unsuccessful.
No successful changes.

I will now attempt to export modules
Module exportation successful

I will now attempt to split imports and exports
Import/Export splitting successful

I will now attempt to split := definitions
One-line definition splitting successful

I will now attempt to remove all lines, one at a time

If you have any comments on your experience of the minimizer, please share them in a reply (possibly tagging @JasonGross).
If you believe there's a bug in the bug minimizer, please report it on the bug minimizer issue tracker.

Copy link
Contributor
coqbot-app bot commented May 27, 2025
Minimization interrupted by timeout, being automatically continued. Partially Minimized File /home/runner/work/run-coq-bug-minimizer/run-coq-bug-minimizer/builds/coq/coq-failing/_build_ci/metarocq/pcuic/theories/PCUICConfluence.v in 5h 15m 6s (from ci-metarocq) (interrupted by timeout, being automatically continued) (full log on GitHub Actions - verbose log)
⭐ ⏱️ Partially Minimized Coq File (timeout) (truncated to first and last 32KiB; full 154KiB file on GitHub Actions Artifacts under bug.v)
(* -*- mode: coq; coq-prog-args: ("-emacs" "-q" "-w" "-deprecated-native-compiler-option" "-native-compiler" "no" "-coqlib" "/github/workspace/builds/coq/coq-failing/_install_ci/lib/coq//" "-R" "/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/utils/theories" "MetaRocq.Utils" "-R" "/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/common/theories" "MetaRocq.Common" "-R" "/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/pcuic/theories" "MetaRocq.PCUIC" "-Q" "/github/workspace/cwd" "Top" "-Q" "/github/workspace/builds/coq/coq-failing/_install_ci/lib/coq///user-contrib/Equations" "Equations" "-Q" "/github/workspace/builds/coq/coq-failing/_install_ci/lib/coq///user-contrib/Ltac2" "Ltac2" "-Q" "/github/workspace/builds/coq/coq-failing/_install_ci/lib/coq///user-contrib/Stdlib" "Stdlib" "-top" "Top.bug_01") -*- *)
(* File reduced by coq-bug-minimizer from original input, then from 3959 lines to 98 lines, then from 111 lines to 3187 lines, then from 3191 lines to 96 lines, then from 107 lines to 1813 lines, then from 1818 lines to 359 lines, then from 369 lines to 1502 lines, then from 1506 lines to 524 lines, then from 535 lines to 3221 lines, then from 3222 lines to 656 lines, then from 667 lines to 2894 lines, then from 2900 lines to 656 lines, then from 667 lines to 1321 lines, then from 1327 lines to 874 lines, then from 883 lines to 675 lines, then from 686 lines to 2746 lines, then from 2745 lines to 687 lines, then from 698 lines to 3155 lines, then from 3155 lines to 745 lines, then from 756 lines to 1586 lines, then from 1589 lines to 869 lines, then from 880 lines to 2395 lines, then from 2394 lines to 885 lines, then from 895 lines to 2754 lines, then from 2755 lines to 1157 lines, then from 1161 lines to 1145 lines, then from 1156 lines to 1809 lines, then from 1813 lines to 1200 lines, then from 1211 lines to 4024 lines, then from 4021 lines to 1355 lines, then from 1366 lines to 3048 lines, then from 3051 lines to 1938 lines, then from 1928 lines to 1518 lines, then from 1529 lines to 1814 lines, then from 1819 lines to 1523 lines, then from 1533 lines to 2340 lines, then from 2342 lines to 1526 lines, then from 1536 lines to 4638 lines, then from 4602 lines to 1892 lines, then from 1903 lines to 3075 lines, then from 3076 lines to 2771 lines, then from 2762 lines to 1985 lines, then from 1996 lines to 2830 lines, then from 2835 lines to 2048 lines, then from 2059 lines to 2413 lines, then from 2418 lines to 2052 lines, then from 2063 lines to 2597 lines, then from 2601 lines to 2063 lines, then from 2074 lines to 6642 lines, then from 6641 lines to 4802 lines *)
(* coqc version 9.1+alpha compiled with OCaml 4.14.2
   coqtop version runner-t7b1znuaq-project-4504-concurrent-2:/builds/coq/coq/_build/default,(HEAD detached at cdd06d0a2f356e) (cdd06d0a2f356e0c02e2d20356562b7deae4cf15)
   Expected coqc runtime on this file: 3.393 sec *)









Require Corelib.Init.Ltac.
Require Corelib.Classes.CRelationClasses.
Require Stdlib.Classes.CRelationClasses.
Require Stdlib.Classes.DecidableClass.
Require Stdlib.Logic.HLevelsBase.
Require Stdlib.Bool.Bool.
Require Corelib.Classes.RelationClasses.
Require Stdlib.Classes.RelationClasses.
Require Corelib.Numbers.BinNums.
Require Stdlib.Numbers.BinNums.
Require Stdlib.Logic.EqdepFacts.
Require Stdlib.Logic.Eqdep_dec.
Require Corelib.Classes.Morphisms.
Require Stdlib.Classes.Morphisms.
Require Corelib.Setoids.Setoid.
Require Stdlib.Setoids.Setoid.
Require Stdlib.Structures.Equalities.
Require Corelib.Relations.Relation_Definitions.
Require Stdlib.Relations.Relation_Definitions.
Require Stdlib.Relations.Relation_Operators.
Require Stdlib.Relations.Operators_Properties.
Require Stdlib.Relations.Relations.
Require Stdlib.Structures.Orders.
Require Corelib.Program.Basics.
Require Stdlib.Program.Basics.
Require Stdlib.Structures.OrdersTac.
Require Stdlib.Structures.OrdersFacts.
Require Stdlib.Structures.GenericMinMax.
Require Corelib.Classes.Morphisms_Prop.
Require Stdlib.Classes.Morphisms_Prop.
Require Stdlib.Numbers.NumPrelude.
Require Stdlib.Numbers.NatInt.NZAxioms.
Require Stdlib.Numbers.NatInt.NZBase.
Require Stdlib.Numbers.NatInt.NZAdd.
Require Stdlib.Numbers.NatInt.NZMul.
Require Stdlib.Logic.Decidable.
Require Stdlib.Numbers.NatInt.NZOrder.
Require Stdlib.Numbers.NatInt.NZAddOrder.
Require Stdlib.Numbers.NatInt.NZMulOrder.
Require Stdlib.Numbers.NatInt.NZParity.
Require Stdlib.Numbers.NatInt.NZPow.
Require Stdlib.Numbers.NatInt.NZSqrt.
Require Stdlib.Numbers.NatInt.NZLog.
Require Stdlib.Numbers.NatInt.NZDiv.
Require Stdlib.Numbers.NatInt.NZGcd.
Require Stdlib.Numbers.NatInt.NZBits.
Require Stdlib.Numbers.Natural.Abstract.NAxioms.
Require Stdlib.Numbers.Natural.Abstract.NBase.
Require Stdlib.Numbers.Natural.Abstract.NAdd.
Require Stdlib.Numbers.Natural.Abstract.NOrder.
Require Stdlib.Numbers.Natural.Abstract.NAddOrder.
Require Stdlib.Numbers.Natural.Abstract.NMulOrder.
Require Stdlib.Numbers.Natural.Abstract.NSub.
Require Stdlib.Numbers.Natural.Abstract.NMaxMin.
Require Stdlib.Numbers.Natural.Abstract.NParity.
Require Stdlib.Numbers.Natural.Abstract.NPow.
Require Stdlib.Numbers.Natural.Abstract.NSqrt.
Require Stdlib.Numbers.Natural.Abstract.NLog.
Require Stdlib.Numbers.Natural.Abstract.NDiv.
Require Stdlib.Numbers.Natural.Abstract.NDiv0.
Require Stdlib.Numbers.Natural.Abstract.NGcd.
Require Stdlib.Numbers.Natural.Abstract.NLcm.
Require Stdlib.Numbers.Natural.Abstract.NLcm0.
Require Stdlib.Numbers.Natural.Abstract.NBits.
Require Stdlib.Numbers.Natural.Abstract.NProperties.
Require Stdlib.Arith.PeanoNat.
Require Corelib.BinNums.PosDef.
Require Stdlib.BinNums.PosDef.
Require Stdlib.PArith.BinPosDef.
Require Stdlib.PArith.BinPos.
Require Stdlib.PArith.Pnat.
Require Stdlib.PArith.POrderedType.
Require Stdlib.PArith.PArith.
Require Corelib.BinNums.NatDef.
Require Stdlib.BinNums.NatDef.
Require Stdlib.NArith.BinNatDef.
Require Stdlib.NArith.BinNat.
Require Stdlib.setoid_ring.Ring_theory.
Require Corelib.Lists.ListDef.
Require Stdlib.Lists.ListDef.
Require Stdlib.Lists.List.
Require Stdlib.setoid_ring.BinList.
Require Stdlib.Numbers.Integer.Abstract.ZAxioms.
Require Stdlib.Numbers.Integer.Abstract.ZBase.
Require Stdlib.Numbers.Integer.Abstract.ZAdd.
Require Stdlib.Numbers.Integer.Abstract.ZMul.
Require Stdlib.Numbers.Integer.Abstract.ZLt.
Require Stdlib.Numbers.Integer.Abstract.ZAddOrder.
Require Stdlib.Numbers.Integer.Abstract.ZMulOrder.
Require Stdlib.Numbers.Integer.Abstract.ZMaxMin.
Require Stdlib.Numbers.Integer.Abstract.ZSgnAbs.
Require Stdlib.Numbers.Integer.Abstract.ZParity.
Require Stdlib.Numbers.Integer.Abstract.ZPow.
Require Stdlib.Numbers.Integer.Abstract.ZDivTrunc.
Require Stdlib.Numbers.Integer.Abstract.ZDivFloor.
Require Stdlib.Numbers.Integer.Abstract.ZGcd.
Require Stdlib.Numbers.Integer.Abstract.ZLcm.
Require Stdlib.Numbers.Integer.Abstract.ZBits.
Require Stdlib.Numbers.Integer.Abstract.ZProperties.
Require Corelib.BinNums.IntDef.
Require Stdlib.BinNums.IntDef.
Require Stdlib.ZArith.BinIntDef.
Require Stdlib.ZArith.BinInt.
Require Stdlib.setoid_ring.Ring_polynom.
Require Stdlib.Lists.ListTactics.
Require Stdlib.setoid_ring.InitialRing.
Require Stdlib.setoid_ring.Ring_tac.
Require Stdlib.setoid_ring.Ring_base.
Require Stdlib.setoid_ring.Ring.
Require Stdlib.Arith.Factorial.
Require Stdlib.Arith.Between.
Require Stdlib.Arith.Peano_dec.
Require Stdlib.Arith.Compare_dec.
Require Stdlib.Arith.EqNat.
Require Stdlib.Arith.Wf_nat.
Require Stdlib.Arith.Arith_base.
Require Stdlib.NArith.Nnat.
Require Stdlib.setoid_ring.ArithRing.
Require Stdlib.Arith.Arith.
Require Stdlib.ZArith.Znat.
Require Stdlib.micromega.ZifyClasses.
Require Stdlib.ZArith.Zeven.
Require Stdlib.micromega.ZifyInst.
Require Stdlib.micromega.Zify.
Require Stdlib.omega.PreOmega.
Require Stdlib.micromega.OrderedRing.
Require Stdlib.NArith.Ndiv_def.
Require Stdlib.NArith.Nsqrt_def.
Require Stdlib.NArith.Ngcd_def.
Require Stdlib.NArith.NArith_base.
Require Stdlib.setoid_ring.NArithRing.
Require Stdlib.NArith.NArith.
Require Stdlib.micromega.Env.
Require Stdlib.micromega.EnvRing.
Require Stdlib.micromega.Refl.
Require Stdlib.micromega.Tauto.
Require Stdlib.micromega.RingMicromega.
Require Stdlib.ZArith.Zpow_def.
Require Stdlib.setoid_ring.ZArithRing.
Require Stdlib.micromega.ZCoeff.
Require Stdlib.ZArith.Zcompare.
Require Stdlib.ZArith.Zorder.
Require Stdlib.ZArith.Zmisc.
Require Stdlib.ZArith.Wf_Z.
Require Corelib.Init.Sumbool.
Require Stdlib.Init.Sumbool.
Require Stdlib.ZArith.ZArith_dec.
Require Stdlib.ZArith.Zbool.
Require Stdlib.ZArith.Zabs.
Require Stdlib.ZArith.Zcomplements.
Require Stdlib.ZArith.Zdiv.
Require Stdlib.micromega.VarMap.
Require Stdlib.micromega.ZMicromega.
Require Stdlib.micromega.DeclConstantZ.
Require Stdlib.micromega.Lia.
Require Stdlib.btauto.Algebra.
Require Stdlib.btauto.Reflect.
Require Stdlib.btauto.Btauto.
Require Corelib.ssr.ssreflect.
Require Stdlib.ssr.ssreflect.
Require Corelib.ssr.ssrbool.
Require Stdlib.ssr.ssrbool.
Require MetaRocq.Common.config.
Require Stdlib.Sets.Relations_1.
Require Stdlib.Sorting.Sorted.
Require Stdlib.Sorting.SetoidList.
Require Stdlib.Classes.RelationPairs.
Require Stdlib.MSets.MSetInterface.
Require Stdlib.Structures.EqualitiesFacts.
Require Stdlib.Structures.OrdersLists.
Require Stdlib.MSets.MSetList.
Require Stdlib.MSets.MSetGenTree.
Require Stdlib.ZArith.Int.
Require Stdlib.MSets.MSetAVL.
Require Corelib.Floats.FloatOps.
Require Corelib.Strings.PrimString.
Require Corelib.Init.Byte.
Require Stdlib.Init.Byte.
Require Stdlib.Strings.Byte.
Require Stdlib.Strings.Ascii.
Require Stdlib.Strings.String.
Require Corelib.extraction.Extraction.
Require Stdlib.extraction.Extraction.
Require Stdlib.Unicode.Utf8_core.
Require Equations.Init.
Require Equations.Signature.
Require Equations.CoreTactics.
Require Equations.Prop.SigmaNotations.
Require Equations.Prop.Logic.
Require Equations.Prop.Classes.
Require Corelib.Program.Tactics.
Require Stdlib.Program.Tactics.
Require Equations.Prop.EqDec.
Require Equations.Prop.DepElim.
Require Equations.Prop.Constants.
Require Stdlib.Vectors.Fin.
Require Stdlib.Vectors.VectorDef.
Require Stdlib.Vectors.VectorSpec.
Require Stdlib.Vectors.VectorEq.
Require Stdlib.Vectors.Vector.
Require Stdlib.Vectors.Bvector.
Require Stdlib.Wellfounded.Disjoint_Union.
Require Stdlib.Wellfounded.Inclusion.
Require Stdlib.Wellfounded.Inverse_Image.
Require Stdlib.Wellfounded.Transitive_Closure.
Require Stdlib.Wellfounded.List_Extension.
Require Stdlib.Wellfounded.Lexicographic_Exponentiation.
Require Stdlib.Wellfounded.Lexicographic_Product.
Require Stdlib.Wellfounded.Union.
Require Stdlib.Wellfounded.Well_Ordering.
Require Stdlib.Wellfounded.Wellfounded.
Require Corelib.Program.Wf.
Require Stdlib.Program.Wf.
Require Stdlib.Logic.FunctionalExtensionality.
Require Equations.Prop.Subterm.
Require Equations.Prop.FunctionalInduction.
Require Equations.Prop.Tactics.
Require Equations.Prop.NoConfusion.
Require Equations.Prop.EqDecInstances.
Require Equations.Prop.Loader.
Require Equations.Prop.Telescopes.
Require Equations.Prop.Equations.
Require Stdlib.Structures.OrderedType.
Require MetaRocq.Utils.MRCompare.
Require MetaRocq.Utils.ReflectEq.
Require MetaRocq.Utils.ByteCompare.
Require MetaRocq.Utils.ByteCompareSpec.
Require Stdlib.Structures.OrdersAlt.
Require MetaRocq.Utils.bytestring.
Require MetaRocq.Utils.MRSquash.
Require Stdlib.setoid_ring.Algebra_syntax.
Require Stdlib.Unicode.Utf8.
Require Equations.Type.Logic.
Require Equations.Type.Relation.
Require Equations.Type.Relation_Properties.
Require MetaRocq.Utils.MRProd.
Require MetaRocq.Utils.MRRelations.
Require Stdlib.setoid_ring.Ncring.
Require Stdlib.setoid_ring.Ncring_polynom.
Require Stdlib.ZArith.Zmax.
Require Stdlib.ZArith.Zmin.
Require Stdlib.ZArith.Zminmax.
Require Stdlib.ZArith.auxiliary.
Require Stdlib.omega.OmegaLemmas.
Require Stdlib.setoid_ring.Ncring_initial.
Require Stdlib.setoid_ring.Ncring_tac.
Require Stdlib.setoid_ring.Cring.
Require Stdlib.ZArith.Zhints.
Require Stdlib.ZArith.ZArith_base.
Require Stdlib.ZArith.Zpower.
Require Stdlib.ZArith.Zdiv_facts.
Require Stdlib.ZArith.Zdivisibility.
Require Stdlib.ZArith.ZModOffset.
Require Stdlib.ZArith.Zcong.
Require Stdlib.micromega.ZArith_hints.
Require Stdlib.ZArith.Zbitwise.
Require Stdlib.ZArith.Znumtheory.
Require Stdlib.ZArith.ZArith.
Require MetaRocq.Utils.MRPrelude.
Require MetaRocq.Utils.MRReflect.
Require MetaRocq.Utils.MRList.
Require MetaRocq.Utils.MROption.

Module Export AdmitTactic.
Module Import LocalFalse.
Inductive False : Prop := .
End LocalFalse.
Axiom proof_admitted : False.
Import Coq.Init.Ltac.
Tactic Notation "admit" := abstract case proof_admitted.
End AdmitTactic.

Module Export MetaRocq_DOT_Utils_DOT_All_Forall_WRAPPED.
Module Export All_Forall.
Import Stdlib.Lists.List.
Import Stdlib.Bool.Bool.
Import Stdlib.Arith.Arith.
Import Stdlib.ssr.ssreflect.
Import Stdlib.ssr.ssrbool.
Import Stdlib.Classes.Morphisms.
Import Stdlib.micromega.Lia.
Import Stdlib.Unicode.Utf8.
Import MetaRocq.Utils.MRPrelude.
Import MetaRocq.Utils.MRReflect.
Import MetaRocq.Utils.MRList.
Import MetaRocq.Utils.MRRelations.
Import MetaRocq.Utils.MRProd.
Import MetaRocq.Utils.MROption.
Import Equations.Prop.Equations.

Import ListNotations.

Derive Signature for Forall Forall2.




Inductive All {A} (P : A -> Type) : list A -> Type :=
    All_nil : All P []
  | All_cons : forall (x : A) (l : list A),
                  P x -> All P l -> All P (x :: l).
Arguments All {A} P%_type _.
Arguments All_nil {_ _}.
Arguments All_cons {_ _ _ _}.
Derive Signature NoConfusion for All.
#[global] Hint Constructors All : core.

Inductive Alli {A} (P : nat -> A -> Type) (n : nat) : list A -> Type :=
| Alli_nil : Alli P n []
| Alli_cons hd tl : P n hd -> Alli P (S n) tl -> Alli P n (hd :: tl).
Arguments Alli_nil {_ _ _}.
Arguments Alli_cons {_ _ _ _ _}.
Derive Signature for Alli.
Derive NoConfusionHom for Alli.

Inductive All2 {A B : Type} (R : A -> B -> Type) : list A -> list B -> Type :=
  All2_nil : All2 R [] []
| All2_cons : forall (x : A) (y : B) (l : list A) (l' : list B),
    R x y -> All2 R l l' -> All2 R (x :: l) (y :: l').
Arguments All2_nil {_ _ _}.
Arguments All2_cons {_ _ _ _ _ _ _}.
Derive Signature for All2.
Derive NoConfusionHom for All2.
#[global] Hint Constructors All2 : core.

Lemma All2_tip {A} {P} (t u : A) : P t u -> All2 P [t] [u].
Admitted.
#[global] Hint Resolve All2_tip : core.

Inductive All2_dep {A B : Type} {R : A -> B -> Type} (R' : forall a b, R a b -> Type) : forall {xs ys}, All2 R xs ys -> Type :=
| All2_dep_nil : All2_dep R' All2_nil
| All2_dep_cons : forall (x : A) (y : B) (l : list A) (l' : list B) (r : R x y) (rs : All2 R l l'),
    R' x y r -> All2_dep R' rs -> All2_dep R' (All2_cons r rs).
Arguments All2_dep_nil {_ _ _ _}.
Arguments All2_dep_cons {_ _ _ _ _ _ _ _ _ _} _ _.
Derive Signature for All2_dep.
Derive NoConfusionHom for All2_dep.
#[global] Hint Constructors All2_dep : core.

Inductive Forall2_dep {A B : Type} {R : A -> B -> Prop} (R' : forall a b, R a b -> Prop) : forall {xs ys}, Forall2 R xs ys -> Prop :=
| Forall2_dep_nil : Forall2_dep R' (@Forall2_nil _ _ _)
| Forall2_dep_cons : forall (x : A) (y : B) (l : list A) (l' : list B) (r : R x y) (rs : Forall2 R l l'),
    R' x y r -> Forall2_dep R' rs -> Forall2_dep R' (@Forall2_cons _ _ _ _ _ _ _ r rs).
Arguments Forall2_dep_nil {_ _ _ _}.
Arguments Forall2_dep_cons {_ _ _ _ _ _ _ _ _ _} _ _.
Derive Signature for Forall2_dep.
#[global] Hint Constructors Forall2_dep : core.

Inductive All2i {A B : Type} (R : nat -> A -> B -> Type) (n : nat)
  : list A -> list B -> Type :=
| All2i_nil : All2i R n [] []
| All2i_cons :
    forall x y l r,
      R n x y ->
      All2i R (S n) l r ->
      All2i R n (x :: l) (y :: r).
Arguments All2i_nil {_ _ _ _}.
Arguments All2i_cons {_ _ _ _ _ _ _ _}.

Derive Signature NoConfusionHom for All2i.

Inductive All3 {A B C : Type} (R : A -> B -> C -> Type) : list A -> list B -> list C -> Type :=
  All3_nil : All3 R [] [] []
| All3_cons : forall (x : A) (y : B) (z : C) (l : list A) (l' : list B) (l'' : list C),
    R x y z -> All3 R l l' l'' -> All3 R (x :: l) (y :: l') (z :: l'').
Arguments All3_nil {_ _ _ _}.
Arguments All3_cons {_ _ _ _ _ _ _ _ _ _}.

Inductive Forall3 {A B C : Type} (R : A -> B -> C -> Type) : list A -> list B -> list C -> Prop :=
  Forall3_nil : Forall3 R [] [] []
| Forall3_cons : forall (x : A) (y : B) (z : C) (l : list A) (l' : list B) (l'' : list C),
    R x y z -> Forall3 R l l' l'' -> Forall3 R (x :: l) (y :: l') (z :: l'').
Arguments Forall3_nil {_ _ _ _}.
Arguments Forall3_cons {_ _ _ _ _ _ _ _ _ _}.

#[global] Hint Constructors All3 Forall3 : core.
Derive Signature for All3 Forall3.
Derive NoConfusionHom for All3.

Definition invert_Forall2 {A B R l l'} (a : @Forall2 A B R l l')
  := match a in Forall2 _ l l'
           return
           match l, l' return @Forall2 A B R l l' -> Prop with
           | [], [] => fun a => Forall2_nil _ = a
           | [], _ | _, [] => fun _ => False
           | x :: xs, y :: ys
             => fun a => sigP (fun v => Forall2_cons _ _ (proj1 v) (proj2 v) = a)
           end a
     with
     | Forall2_nil _ => eq_refl
     | Forall2_cons _ _ r a => existP _ (conj r a) eq_refl
     end.
Import EqNotations.
Definition invert_Forall2_dep {A B R R' l l' a} (a' : @Forall2_dep A B R R' l l' a)
  := match a' in @Forall2_dep _ _ _ _ l l' a
           return
           match l, l' return forall a, @Forall2_dep A B R R' l l' a -> Prop with
           | [], [] => fun a a' => (rew [Forall2_dep _] invert_Forall2 a in Forall2_dep_nil) = a'
           | [], _ | _, [] => fun _ _ => False
           | x :: xs, y :: ys
             => fun a a' => sigP (fun v => (rew projP2 (invert_Forall2 a) in Forall2_dep_cons (proj1 v) (proj2 v)) = a')
           end a a'
     with
     | Forall2_dep_nil => eq_refl
     | Forall2_dep_cons r a => existP _ (conj r a) eq_refl
     end.

Definition Forall2_rect A B R (P : forall x y, Forall2 R x y -> Type)
  (Hn : P [] [] (@Forall2_nil _ _ _))
  (Hc : forall x y l l' r (a : Forall2 R l l'),
      P l l' a -> P (x :: l) (y :: l') (Forall2_cons _ _ r a))
  : forall l l' (a : @Forall2 A B R l l'), P l l' a.
Admitted.

Definition Forall2_rec A B R (P : forall x y, Forall2 R x y -> Set)
  (Hn : P [] [] (@Forall2_nil _ _ _))
  (Hc : forall x y l l' r (a : Forall2 R l l'),
      P l l' a -> P (x :: l) (y :: l') (Forall2_cons _ _ r a))
  : forall l l' (a : @Forall2 A B R l l'), P l l' a
  := @Forall2_rect A B R P Hn Hc.

Definition Forall2_dep_rect A B R R' (P : forall x y a, @Forall2_dep A B R R' x y a -> Type)
  (Hn : P [] [] (@Forall2_nil _ _ _) Forall2_dep_nil)
  (Hc : forall x y l l' r rs r' (a : Forall2_dep R' rs),
      P l l' rs a -> P (x :: l) (y :: l') (Forall2_cons _ _ r rs) (Forall2_dep_cons r' a))
  : forall l l' a (a' : @Forall2_dep A B R R' l l' a), P l l' a a'.
Admitted.

Definition Forall2_dep_rec A B R R' (P : forall x y a, @Forall2_dep A B R R' x y a -> Set)
  (Hn : P [] [] (@Forall2_nil _ _ _) Forall2_dep_nil)
  (Hc : forall x y l l' r rs r' (a : Forall2_dep R' rs),
      P l l' rs a -> P (x :: l) (y :: l') (Forall2_cons _ _ r rs) (Forall2_dep_cons r' a))
  : forall l l' a (a' : @Forall2_dep A B R R' l l' a), P l l' a a'
  := @Forall2_dep_rect A B R R' P Hn Hc.

Section alli.
  Context {A} (p : nat -> A -> bool).
  Fixpoint alli (n : nat) (l : list A) : bool :=
  match l with
  | [] => true
  | hd :: tl => p n hd && alli (S n) tl
  end.
End alli.

Lemma alli_ext {A} (p q : nat -> A -> bool) n (l : list A) :
  (forall i, p i =1 q i) ->
  alli p n l = alli q n l.
Admitted.

#[global] Instance alli_proper {A} :
   Proper ((pointwise_relation nat (pointwise_relation A eq)) ==> eq ==> eq ==> eq) alli.
Admitted.

Lemma alli_impl {A} (p q : nat -> A -> bool) n (l : list A) :
  (forall i x, p i x -> q i x) ->
  alli p n l -> alli q n l.
Admitted.

Lemma allbiP {A} (P : nat -> A -> Type) (p : nat -> A -> bool) n l :
  (forall i x, reflectT (P i x) (p i x)) ->
  reflectT (Alli P n l) (alli p n l).
Admitted.

Lemma alli_Alli {A} (p : nat -> A -> bool) n l :
  alli p n l <~> Alli p n l.
Admitted.

Lemma alli_shiftn {A} n k p (l : list A) :
  alli p (n + k) l = alli (fun i => p (n + i)) k l.
Admitted.

Section alli.
  Context {A} (p q : nat -> A -> bool) (l l' : list A).

  Lemma alli_app n :
    alli p n (l ++ l') =
    alli p n l && alli p (#|l| + n) l'.
Admitted.

  Lemma alli_shift n :
    alli p n l = alli (fun i => p (n + i)) 0 l.
Admitted.

  Lemma alli_map {B} (f : B -> A) n bs : alli p n (map f bs) = alli (fun i => p i ∘ f) n bs.
Admitted.
End alli.

Lemma alli_mapi {A B} (f : nat -> A -> bool) (g : nat -> B -> A) n l :
  alli f n (mapi_rec g l n) = alli (fun i x => f i (g i x)) n l.
Admitted.

Section Forallb2.
  Context {A B} (f : A -> B -> bool).

  Fixpoint forallb2 l l' :=
    match l, l' with
    | hd :: tl, hd' :: tl' => f hd hd' && forallb2 tl tl'
    | [], [] => true
    | _, _ => false
    end.

End Forallb2.

Section Forallb3.
  Context {A B C} (f : A -> B -> C -> bool).

  Fixpoint forallb3 l l' l'' :=
    match l, l', l'' with
    | hd :: tl, hd' :: tl', hd'' :: tl'' => f hd hd' hd'' && forallb3 tl tl' tl''
    | [], [], [] => true
    | _, _, _ => false
    end.

End Forallb3.

Lemma forallb2_refl :
  forall A (R : A -> A -> bool),
    (forall x, R x x) ->
    forall l, forallb2 R l l.
Admitted.

Lemma forallb2_map :
  forall A B C D (R : A -> B -> bool) f g (l : list C) (l' : list D),
    forallb2 R (map f l) (map g l') =
    forallb2 (fun x y => R (f x) (g y)) l l'.
Admitted.

Lemma forall_map_spec {A B} {l} {f g : A -> B} :
  Forall (fun x => f x = g x) l <->
  map f l = map g l.
Admitted.

Lemma forall_map_id_spec {A} {l} {f : A -> A} :
  Forall (fun x => f x = x) l <-> map f l = l.
Admitted.

Lemma forallb_Forall {A} (p : A -> bool) l
  : Forall p l <-> is_true (forallb p l).
Admitted.

Lemma forallbP {A} (P : A -> Prop) (p : A -> bool) l :
  (forall x, reflect (P x) (p x)) ->
  reflect (Forall P l) (forallb p l).
Admitted.

Lemma forallb_ext {A} (p q : A -> bool) : p =1 q -> forallb p =1 forallb q.
Admitted.

#[global] Instance forallb_proper {A} : Proper (`=1` ==> eq ==> eq) (@forallb A).
Admitted.

Lemma forallbP_cond {A} (P Q : A -> Prop) (p : A -> bool) l :
  Forall Q l ->
  (forall x, Q x -> reflect (P x) (p x)) -> reflect (Forall P l) (forallb p l).
Admitted.

Lemma nth_error_forallb {A} {p : A -> bool} {l : list A} {n x} :
  nth_error l n = Some x -> forallb p l -> p x.
Admitted.

Lemma forallb_nth_error {A} P l n :
  @forallb A P l -> on_Some_or_None P (nth_error l n).
Admitted.

Lemma map_eq_inj {A B} (f g : A -> B) l: map f l = map g l ->
                                         All (fun x => f x = g x) l.
Admitted.



Lemma Forall_mix {A} (P Q : A -> Prop) : forall l, Forall P l -> Forall Q l -> Forall (fun x => P x /\ Q x) l.
Admitted.

Lemma Forall_skipn {A} (P : A -> Prop) n l : Forall P l -> Forall P (skipn n l).
Admitted.

Lemma Forall_firstn {A} (P : A -> Prop) n l : Forall P l -> Forall P (firstn n l).
Admitted.

Lemma forallb2_All2 {A B : Type} {p : A -> B -> bool}
      {l : list A} {l' : list B}:
  is_true (forallb2 p l l') -> All2 (fun x y => is_true (p x y)) l l'.
Admitted.

Lemma All2_forallb2 {A B : Type} {p : A -> B -> bool}
      {l : list A} {l' : list B} :
  All2 (fun x y => is_true (p x y)) l l' -> is_true (forallb2 p l l').
Admitted.

Lemma forallb3_All3 {A B C : Type} {p : A -> B -> C -> bool}
      {l : list A} {l' : list B} {l'' : list C}:
  is_true (forallb3 p l l' l'') -> All3 (fun x y z => is_true (p x y z)) l l' l''.
Admitted.

Lemma All3_forallb3 {A B C : Type} {p : A -> B -> C -> bool}
      {l : list A} {l' : list B} {l'' : list C} :
  All3 (fun x y z => is_true (p x y z)) l l' l'' -> is_true (forallb3 p l l' l'').
Admitted.

Lemma All3P {A B C : Type} {p : A -> B -> C -> bool} {l l' l''} :
  reflectT (All3 p l l' l'') (forallb3 p l l' l'').
Admitted.

Lemma All2_refl {A} {P : A -> A -> Type} l :
  (forall x, P x x) ->
  All2 P l l.
Admitted.

Lemma forallb2_app {A B} (p : A -> B -> bool) l l' q q' :
  is_true (forallb2 p l l' && forallb2 p q q')
  -> is_true (forallb2 p (l ++ q) (l' ++ q')).
Admitted.

Lemma All2_map_equiv {A B C D} {R : C -> D -> Type} {f : A -> C} {g : B -> D} {l l'} :
  All2 (fun x y => R (f x) (g y)) l l' <~> All2 R (map f l) (map g l').
Admitted.

Lemma All2_map {A B C D} {R : C -> D -> Type} {f : A -> C} {g : B -> D} {l l'} :
  All2 (fun x y => R (f x) (g y)) l l' -> All2 R (map f l) (map g l').
Admitted.

Lemma All2_map_inv {A B C D} {R : C -> D -> Type} {f : A -> C} {g : B -> D} {l l'} :
  All2 R (map f l) (map g l') -> All2 (fun x y => R (f x) (g y)) l l'.
Admitted.

Lemma All2_tip_l {A B} {R : A -> B -> Type} x y : All2 R [x] y -> ∑ y', (y = [y']) * R x y'.
Admitted.

Lemma All2i_All2i_mix {A B} {P Q : nat -> A -> B -> Type}
      {n} {l : list A} {l' : list B} :
  All2i P n l l' -> All2i Q n l l' -> All2i (fun i x y => (P i x y * Q i x y)%type) n l l'.
Admitted.

Lemma All2i_nth_error {A B} {P : nat -> A -> B -> Type} {l l' n x c k} :
  All2i P k l l' ->
  nth_error l n = Some x ->
  nth_error l' n = Some c ->
  P (k + n)%nat x c.
Admitted.



















Lemma All2_All_mix_left {A B} {P : A -> Type} {Q : A -> B -> Type}
      {l : list A} {l' : list B} :
  All P l -> All2 Q l l' -> All2 (fun x y => (P x * Q x y)%type) l l'.
Admitted.

Lemma All2_All_mix_right {A B} {P : B -> Type} {Q : A -> B -> Type}
      {l : list A} {l' : list B} :
  All P l' -> All2 Q l l' -> All2 (fun x y => (Q x y * P y)%type) l l'.
Admitted.

Lemma All2i_All_mix_left {A B} {P : A -> Type} {Q : nat -> A -> B -> Type}
      {n} {l : list A} {l' : list B} :
  All P l -> All2i Q n l l' -> All2i (fun i x y => (P x * Q i x y)%type) n l l'.
Admitted.

Lemma All2i_All_mix_right {A B} {P : B -> Type} {Q : nat -> A -> B -> Type}
      {n} {l : list A} {l' : list B} :
  All P l' -> All2i Q n l l' -> All2i (fun i x y => (Q i x y * P y)%type) n l l'.
Admitted.

Lemma All2i_All2_mix_left {A B} {P : A -> B -> Type} {Q : nat -> A -> B -> Type}
      {n} {l : list A} {l' : list B} :
  All2 P l l' -> All2i Q n l l' -> All2i (fun i x y => (P x y * Q i x y)%type) n l l'.
Admitted.

Lemma All2_All2_All2 {A B C} {P Q R} (l : list A) (l' : list B) (l'' : list C) :
  All2 P l l' -> All2 Q l' l'' ->
  (forall x y z, P x y -> Q y z -> R x z) ->
  All2 R l l''.
Admitted.

Lemma Forall_All {A : Type} (P : A -> Prop) l :
  Forall P l -> All P l.
Admitted.

Lemma All_Forall {A : Type} (P : A -> Prop) l :
  All P l -> Forall P l.
Admitted.

Lemma forallb_All {A} (p : A -> bool) l : is_true (forallb p l) -> All p l.
Admitted.

Lemma All_forallb {A} (p : A -> bool) l : All p l -> is_true (forallb p l).
Admitted.

Lemma All_firstn {A} {P : A -> Type} {l} {n} : All P l -> All P (firstn n l).
Admitted.

Lemma All_skipn {A} {P : A -> Type} {l} {n} : All P l -> All P (skipn n l).
Admitted.

Lemma All_app {A} {P : A -> Type} {l l'} : All P (l ++ l') -> All P l * All P l'.
Admitted.

Lemma All_app_inv {A} (P : A -> Type) l l' : All P l -> All P l' -> All P (l ++ l').
Admitted.

Lemma All_True {A} l : All (fun x : A => True) l.
Admitted.

Lemma All_tip {A} {P : A -> Type} {a : A} : P a <~> All P [a].
Admitted.

Lemma All_mix {A} {P : A -> Type} {Q : A -> Type} {l} :
  All P l -> All Q l -> All (fun x => (P x * Q x)%type) l.
Admitted.

Lemma All2_All_left {A B} {P : A -> B -> Type} {Q : A -> Type} {l l'} :
  All2 P l l' ->
  (forall x y, P x y -> Q x) ->
  All Q l.
Admitted.

Lemma All2_All_right {A B} {P : A -> B -> Type} {Q : B -> Type} {l l'} :
  All2 P l l' ->
  (forall x y, P x y -> Q y) ->
  All Q l'.
Admitted.

Lemma All2_right {A B} {P : B -> Type} {l : list A} {l'} :
  All2 (fun x y => P y) l l' -> All P l'.
Admitted.

Lemma All2_impl_All2 {A B} {P Q : A -> B -> Type} {l l'} :
    All2 P l l' ->
    All2 (fun x y => P x y -> Q x y) l l' ->
    All2 Q l l'.
Admitted.

Lemma All2_impl {A B} {P Q : A -> B -> Type} {l l'} :
    All2 P l l' ->
    (forall x y, P x y -> Q x y) ->
    All2 Q l l'.
Admitted.

Lemma All2_eq_eq {A} (l l' : list A) : l = l' -> All2 (fun x y => x = y) l l'.
Admitted.

Lemma All2_reflexivity {A} {P : A -> A -> Type} :
  CRelationClasses.Reflexive P -> CRelationClasses.Reflexive (All2 P).
Admitted.

Lemma All2_symmetry {A} (R : A -> A -> Type) :
  CRelationClasses.Symmetric R ->
  CRelationClasses.Symmetric (All2 R).
Admitted.

Lemma All2_transitivity {A} (R : A -> A -> Type) :
  CRelationClasses.Transitive R ->
  CRelationClasses.Transitive (All2 R).
Admitted.

Lemma All2_apply {A B C} {D : A -> B -> C -> Type} {l : list B} {l' : list C} :
  forall (a : A),
    All2 (fun x y => forall a : A, D a x y) l l' ->
    All2 (fun x y => D a x y) l l'.
Admitted.

Lemma All2_apply_arrow {A B C} {D : B -> C -> Type} {l : list B} {l' : list C} :
  A -> All2 (fun x y => A -> D x y) l l' ->
  All2 (fun x y => D x y) l l'.
Admitted.

Lemma All2_apply_dep_arrow {B C} {A} {D : B -> C -> Type} {l : list B} {l' : list C} :
  All A l ->
  All2 (fun x y => A x -> D x y) l l' ->
  All2 D l l'.
Admitted.

Lemma All2_apply_dep_All {B C} {A} {D : C -> Type} {l : list B} {l' : list C} :
  All A l ->
  All2 (fun x y => A x -> D y) l l' ->
  All D l'.
Admitted.

Lemma All2P {A B : Type} {P : A -> B -> Type} {p : A -> B -> bool} {l l'} :
  (forall x y, reflectT (P x y) (p x y)) ->
  reflectT (All2 P l l') (forallb2 p l l').
Admitted.

Lemma All2i_All_left {A B} {P : nat -> A -> B -> Type} {Q : A -> Type} {n l l'} :
  All2i P n l l' ->
  (forall i x y, P i x y -> Q x) ->
  All Q l.
Admitted.

Lemma All2i_All_right {A B} {P : nat -> A -> B -> Type} {Q : B -> Type} {n l l'} :
  All2i P n l l' ->
  (forall i x y, P i x y -> Q y) ->
  All Q l'.
Admitted.

Lemma All2_dep_impl {A B} {P : A -> B -> Type} {P' Q' : forall a b, P a b -> Type} {l l'} {a : All2 P l l'} :
    All2_dep P' a ->
    (forall x y r, P' x y r -> Q' x y r) ->
    All2_dep Q' a.
Admitted.

Lemma All_refl {A} (P : A -> Type) l : (forall x, P x) -> All P l.
Admitted.

Lemma All_rev_map {A B} (P : A -> Type) f (l : list B) : All (fun x => P (f x)) l -> All P (rev_map f l).
Admitted.

Lemma All_rev (A : Type) (P : A -> Type) (l : list A) : All P l -> All P (List.rev l).
Admitted.

Lemma All_rev_inv {A} (P : A -> Type) (l : list A) : All P (List.rev l) -> All P l.
Admitted.

Lemma All_impl_All {A} {P Q} {l : list A} : All P l -> All (fun x => P x -> Q x) l -> All Q l.
Admitted.

Lemma Alli_impl_Alli {A} {P Q} (l : list A) {n} : Alli P n l -> Alli (fun n x => P n x -> Q n x) n l -> Alli Q n l.
Admitted.

Lemma All_impl {A} {P Q} {l : list A} : All P l -> (forall x, P x -> Q x) -> All Q l.
Admitted.

Lemma Alli_impl {A} {P Q} (l : list A) {n} : Alli P n l -> (forall n x, P n x -> Q n x) -> Alli Q n l.
Admitted.

Lemma All_map {A B} {P : B -> Type} {f : A -> B} {l : list A} :
  All (fun x => P (f x)) l -> All P (map f l).
Admitted.

Lemma All_map_inv {A B} (P : B -> Type) (f : A -> B) l : All P (map f l) -> All (fun x => P (f x)) l.
Admitted.

Lemma In_All {A} {P : A -> Type} l :
    (∀ x : A, In x l -> P x) -> All P l.
Admitted.

Lemma All_nth_error :
  forall A P l i x,
    @All A P l ->
    nth_error l i = Some x ->
    P x.
Admitted.

Lemma Alli_mix {A} {P : nat -> A -> Type} {Q : nat -> A -> Type} {n l} :
  Alli P n l -> Alli Q n l -> Alli (fun n x => (P n x * Q n x)%type) n l.
Admitted.

Lemma Alli_All {A} {P : nat -> A -> Type} {Q : A -> Type} {l n} :
  Alli P n l ->
  (forall n x, P n x -> Q x) ->
  All Q l.
Admitted.

Lemma Alli_app {A} (P : nat -> A -> Type) n l l' : Alli P n (l ++ l') -> Alli P n l * Alli P (length l + n) l'.
Admitted.

Lemma Alli_nth_error :
  forall A P k l i x,
    @Alli A P k l ->
    nth_error l i = Some x ->
    P (k + i) x.
Admitted.

Lemma forall_nth_error_All :
  forall {A} (P : A -> Type) l,
    (forall i x, nth_error l i = Some x -> P x) ->
    All P l.
Admitted.

Lemma forall_nth_error_Alli :
  forall {A} (P : nat -> A -> Type) k l,
    (forall i x, nth_error l i = Some x -> P (k + i) x) ->
    Alli P k l.
Admitted.

Lemma Alli_mapi {A B} {P : nat -> B -> Type} (f : nat -> A -> B) k l :
  Alli (fun n a => P n (f n a)) k l <~> Alli P k (mapi_rec f l k).
Admitted.

Lemma Alli_shift {A} {P : nat -> A -> Type} k l :
  Alli (fun x => P (S x)) k l ->
  Alli P (S k) l.
Admitted.

Lemma Alli_refl {A} (P : nat -> A -> Type) n (l : list A) :
  (forall n x, P n x) -> Alli P n l.
Admitted.

Lemma Alli_rev {A} {P : nat -> A -> Type} k l :
  Alli P k l ->
  Alli (fun k' => P (Nat.pred #|l| - k' + k)) 0 (List.rev l).
Admitted.

Lemma Alli_rev_inv {A: Type} (P : nat -> A -> Type) (k : nat) (l : list A) :
  Alli P k (List.rev l) ->
  Alli (fun k' : nat => P (Nat.pred #|l| - k' + k)) 0 l.
Admitted.

Lemma Alli_app_inv {A} {P} {l l' : list A} {n} : Alli P n l -> Alli P (n + #|l|) l' -> Alli P n (l ++ l').
Admitted.

Lemma A

[...]

extended_list (smash_context [] mdecl.(ind_params) ,,, ictx)) in
  let inddecl :=
    {| decl_name :=
      {| binder_name := nNamed (ind_name idecl); binder_relevance := idecl.(ind_relevance) |};
       decl_body := None;
       decl_type := indty |}
  in (inddecl :: ictx).

Definition inst_case_context params puinst (pctx : context) :=
  subst_context (List.rev params) 0 (subst_instance puinst pctx).

Definition inst_case_predicate_context (p : predicate term) :=
  inst_case_context p.(pparams) p.(puinst) p.(pcontext).

Definition inst_case_branch_context (p : predicate term) (br : branch term) :=
  inst_case_context p.(pparams) p.(puinst) br.(bcontext).

Definition iota_red npar p args br :=
  subst (List.rev (List.skipn npar args)) 0
    (expand_lets (inst_case_branch_context p br) (bbody br)).

Definition pre_case_predicate_context_gen ind mdecl idecl params puinst : context :=
  inst_case_context params puinst (ind_predicate_context ind mdecl idecl).

Definition case_predicate_context_gen ind mdecl idecl params puinst pctx :=
  map2 set_binder_name pctx (pre_case_predicate_context_gen ind mdecl idecl params puinst).

Definition case_predicate_context ind mdecl idecl p : context :=
  case_predicate_context_gen ind mdecl idecl p.(pparams) p.(puinst) (forget_types p.(pcontext)).

Definition cstr_branch_context ind mdecl cdecl : context :=
  expand_lets_ctx mdecl.(ind_params)
    (subst_context (inds (inductive_mind ind) (abstract_instance mdecl.(ind_universes))
       mdecl.(ind_bodies)) #|mdecl.(ind_params)|
      cdecl.(cstr_args)).

Definition pre_case_branch_context_gen ind mdecl cdecl params puinst : context :=
  inst_case_context params puinst (cstr_branch_context ind mdecl cdecl).

Definition case_branch_context_gen ind mdecl params puinst pctx cdecl :=
  map2 set_binder_name pctx (pre_case_branch_context_gen ind mdecl cdecl params puinst).

Definition case_branch_type_gen ind mdecl (idecl : one_inductive_body) params puinst bctx ptm i cdecl : context * term :=
  let cstr := tConstruct ind i puinst in
  let args := to_extended_list cdecl.(cstr_args) in
  let cstrapp := mkApps cstr (map (lift0 #|cdecl.(cstr_args)|) params ++ args) in
  let brctx := case_branch_context_gen ind mdecl params puinst bctx cdecl in
  let upars := subst_instance puinst mdecl.(ind_params) in
  let indices :=
    (map (subst (List.rev params) #|cdecl.(cstr_args)|)
      (map (expand_lets_k upars #|cdecl.(cstr_args)|)
        (map (subst (inds (inductive_mind ind) puinst mdecl.(ind_bodies))
                    (#|mdecl.(ind_params)| + #|cdecl.(cstr_args)|))
          (map (subst_instance puinst) cdecl.(cstr_indices))))) in
  let ty := mkApps (lift0 #|cdecl.(cstr_args)| ptm) (indices ++ [cstrapp]) in
  (brctx, ty).

Definition case_branch_type ind mdecl idecl p (b : branch term) ptm i cdecl : context * term :=
  case_branch_type_gen ind mdecl idecl p.(pparams) p.(puinst) (forget_types b.(bcontext)) ptm i cdecl.

Definition idecl_binder idecl :=
  {| decl_name :=
    {| binder_name := nNamed idecl.(ind_name);
        binder_relevance := idecl.(ind_relevance) |};
     decl_body := None;
     decl_type := idecl.(ind_type) |}.

Definition wf_predicate_gen mdecl idecl (pparams : list term) (pcontext : list aname) : Prop :=
  let decl := idecl_binder idecl in
  (#|pparams| = mdecl.(ind_npars)) /\
  (Forall2 (fun na decl => eq_binder_annot na decl.(decl_name))
    pcontext (decl :: idecl.(ind_indices))).

Definition wf_predicate mdecl idecl (p : predicate term) : Prop :=
  wf_predicate_gen mdecl idecl p.(pparams) (forget_types p.(pcontext)).

Definition wf_branch_gen cdecl (bctx : list aname) : Prop :=
  (Forall2 (fun na decl => eq_binder_annot na decl.(decl_name))
    bctx cdecl.(cstr_args)).

Definition wf_branch cdecl (b : branch term) : Prop :=
  wf_branch_gen cdecl (forget_types b.(bcontext)).

Definition wf_branches idecl (brs : list (branch term)) : Prop :=
  Forall2 wf_branch idecl.(ind_ctors) brs.

Definition fix_subst (l : mfixpoint term) :=
  let fix aux n :=
      match n with
      | 0 => []
      | S n => tFix l n :: aux n
      end
  in aux (List.length l).

Definition unfold_fix (mfix : mfixpoint term) (idx : nat) :=
  match List.nth_error mfix idx with
  | Some d => Some (d.(rarg), subst0 (fix_subst mfix) d.(dbody))
  | None => None
  end.

Definition cofix_subst (l : mfixpoint term) :=
  let fix aux n :=
      match n with
      | 0 => []
      | S n => tCoFix l n :: aux n
      end
  in aux (List.length l).

Definition unfold_cofix (mfix : mfixpoint term) (idx : nat) :=
  match List.nth_error mfix idx with
  | Some d => Some (d.(rarg), subst0 (cofix_subst mfix) d.(dbody))
  | None => None
  end.

Definition is_constructor n ts :=
  match List.nth_error ts n with
  | Some a => isConstruct_app a
  | None => false
  end.
Definition cmp_universe_instance (cmp_univ : Universe.t -> Universe.t -> Prop) : Instance.t -> Instance.t -> Prop.
Admitted.

Definition cmp_universe_variance (cmp_univ : conv_pb -> Universe.t -> Universe.t -> Prop) pb v u u' :=
  match v with
  | Variance.Irrelevant => True
  | Variance.Covariant => on_rel (cmp_univ pb) Universe.make' u u'
  | Variance.Invariant => on_rel (cmp_univ Conv) Universe.make' u u'
  end.

Definition cmp_universe_instance_variance cmp_univ pb v u u' :=
  Forall3 (cmp_universe_variance cmp_univ pb) v u u'.

Definition global_variance_gen lookup gr napp :=
  match gr with
  | IndRef ind =>
    match lookup_inductive_gen lookup ind with
    | Some (mdecl, idecl) =>
      match destArity [] idecl.(ind_type) with
      | Some (ctx, _) => if (context_assumptions ctx) <=? napp then
          match mdecl.(ind_variance) with
          | Some var => Variance var
          | None => AllEqual
          end
        else AllEqual
      | None => AllEqual
      end
    | None => AllEqual
    end
  | ConstructRef ind k =>
    match lookup_constructor_gen lookup ind k with
    | Some (mdecl, idecl, cdecl) =>
      if (cdecl.(cstr_arity) + mdecl.(ind_npars))%nat <=? napp then

        AllIrrelevant
      else AllEqual
    | _ => AllEqual
    end
  | _ => AllEqual
  end.

Definition cmp_opt_variance cmp_univ pb v :=
  match v with
  | AllEqual => cmp_universe_instance (cmp_univ Conv)
  | AllIrrelevant => fun l l' => #|l| = #|l'|
  | Variance v => fun u u' => cmp_universe_instance (cmp_univ Conv) u u' \/ cmp_universe_instance_variance cmp_univ pb v u u'
  end.

Definition cmp_global_instance_gen Σ cmp_universe pb gr napp :=
  cmp_opt_variance cmp_universe pb (global_variance_gen Σ gr napp).

Notation cmp_global_instance Σ := (cmp_global_instance_gen (lookup_env Σ)).

Inductive eq_decl_upto_names : context_decl -> context_decl -> Type :=
  | compare_vass {na na' T} :
    eq_binder_annot na na' -> eq_decl_upto_names (vass na T) (vass na' T)
  | compare_vdef {na na' b T} :
    eq_binder_annot na na' -> eq_decl_upto_names (vdef na b T) (vdef na' b T).

Notation eq_context_upto_names := (All2 eq_decl_upto_names).

Definition shiftnP k p i :=
  (i <? k) || p (i - k).
Fixpoint on_free_vars (p : nat -> bool) (t : term) : bool.
Admitted.

Definition on_free_vars_decl P d :=
  test_decl (on_free_vars P) d.

Definition on_free_vars_ctx P ctx :=
  alli (fun k => (on_free_vars_decl (shiftnP k P))) 0 (List.rev ctx).

Notation is_open_term Γ := (on_free_vars (shiftnP #|Γ| xpred0)).
Notation is_closed_context := (on_free_vars_ctx xpred0).
Definition set_preturn (p : predicate term) (pret' : term) : predicate term.
Admitted.
Definition set_pparams (p : predicate term) (pars' : list term) : predicate term.
Admitted.
Definition on_one_decl (P : term -> term -> Type)
  (d : context_decl) (d' : context_decl) : Type.
Admitted.

Section OnOne_local_2.
  Context (P : forall (Γ : context), context_decl -> context_decl -> Type).

  Inductive OnOne2_local_env : context -> context -> Type :=
  | onone2_localenv_cons_abs Γ na na' t t' :
      P Γ (vass na t) (vass na' t') ->
      OnOne2_local_env (Γ ,, vass na t) (Γ ,, vass na' t')
  | onone2_localenv_def Γ na na' b b' t t' :
      P Γ (vdef na b t) (vdef na' b' t') ->
      OnOne2_local_env (Γ ,, vdef na b t) (Γ ,, vdef na' b' t')
  | onone2_localenv_cons_tl Γ Γ' d :
      OnOne2_local_env Γ Γ' ->
      OnOne2_local_env (Γ ,, d) (Γ' ,, d).
End OnOne_local_2.
Arguments exist {_ _} _ _.
Import Equations.Type.Relation.

Reserved Notation " Σ ;;; Γ |- t ⇝ u " (at level 50, Γ, t, u at next level).

Definition set_array_default (ar : array_model term) (v : term) :=
  {| array_level := ar.(array_level);
     array_default := v;
     array_type := ar.(array_type);
     array_value := ar.(array_value) |}.

Definition set_array_type (ar : array_model term) (v : term) :=
  {| array_level := ar.(array_level);
     array_default := ar.(array_default);
     array_type := v;
     array_value := ar.(array_value) |}.

Definition set_array_value (ar : array_model term) (v : list term) :=
  {| array_level := ar.(array_level);
     array_default := ar.(array_default);
     array_type := ar.(array_type);
     array_value := v |}.

Inductive red1 (Σ : global_env) (Γ : context) : term -> term -> Type :=

| red_beta na t b a :
  Σ ;;; Γ |- tApp (tLambda na t b) a ⇝ b {0 := a}

| red_zeta na b t b' :
  Σ ;;; Γ |- tLetIn na b t b' ⇝ b' {0 := b}

| red_rel i body :
    option_map decl_body (nth_error Γ i) = Some (Some body) ->
    Σ ;;; Γ |- tRel i ⇝ lift0 (S i) body

| red_iota ci c u args p brs br :
    nth_error brs c = Some br ->
    #|args| = (ci.(ci_npar) + context_assumptions br.(bcontext))%nat ->
    Σ ;;; Γ |- tCase ci p (mkApps (tConstruct ci.(ci_ind) c u) args) brs
        ⇝ iota_red ci.(ci_npar) p args br

| red_fix mfix idx args narg fn :
    unfold_fix mfix idx = Some (narg, fn) ->
    is_constructor narg args = true ->
    Σ ;;; Γ |- mkApps (tFix mfix idx) args ⇝ mkApps fn args

| red_cofix_case ip p mfix idx args narg fn brs :
    unfold_cofix mfix idx = Some (narg, fn) ->
    Σ ;;; Γ |- tCase ip p (mkApps (tCoFix mfix idx) args) brs ⇝
         tCase ip p (mkApps fn args) brs

| red_cofix_proj p mfix idx args narg fn :
    unfold_cofix mfix idx = Some (narg, fn) ->
    Σ ;;; Γ |- tProj p (mkApps (tCoFix mfix idx) args) ⇝ tProj p (mkApps fn args)

| red_delta c decl body (isdecl : declared_constant Σ c decl) u :
    decl.(cst_body) = Some body ->
    Σ ;;; Γ |- tConst c u ⇝ subst_instance u body

| red_proj p args u arg:
    nth_error args (p.(proj_npars) + p.(proj_arg)) = Some arg ->
    Σ ;;; Γ |- tProj p (mkApps (tConstruct p.(proj_ind) 0 u) args) ⇝ arg

| abs_red_l na M M' N : Σ ;;; Γ |- M ⇝ M' -> Σ ;;; Γ |- tLambda na M N ⇝ tLambda na M' N
| abs_red_r na M M' N : Σ ;;; Γ ,, vass na N |- M ⇝ M' -> Σ ;;; Γ |- tLambda na N M ⇝ tLambda na N M'

| letin_red_def na b t b' r : Σ ;;; Γ |- b ⇝ r -> Σ ;;; Γ |- tLetIn na b t b' ⇝ tLetIn na r t b'
| letin_red_ty na b t b' r : Σ ;;; Γ |- t ⇝ r -> Σ ;;; Γ |- tLetIn na b t b' ⇝ tLetIn na b r b'
| letin_red_body na b t b' r : Σ ;;; Γ ,, vdef na b t |- b' ⇝ r -> Σ ;;; Γ |- tLetIn na b t b' ⇝ tLetIn na b t r

| case_red_param ci p params' c brs :
    OnOne2 (fun t u => Σ ;;; Γ |- t ⇝ u) p.(pparams) params' ->
    Σ ;;; Γ |- tCase ci p c brs ⇝ tCase ci (set_pparams p params') c brs

| case_red_return ci p preturn' c brs :
  Σ ;;; Γ ,,, inst_case_predicate_context p |- p.(preturn) ⇝ preturn' ->
  Σ ;;; Γ |- tCase ci p c brs ⇝ tCase ci (set_preturn p preturn') c brs

| case_red_discr ci p c c' brs :
  Σ ;;; Γ |- c ⇝ c' -> Σ ;;; Γ |- tCase ci p c brs ⇝ tCase ci p c' brs

| case_red_brs ci p c brs brs' :
    OnOne2 (fun br br' =>
      on_Trel_eq (fun t u => Σ ;;; Γ ,,, inst_case_branch_context p br |- t ⇝ u) bbody bcontext br br')
      brs brs' ->
    Σ ;;; Γ |- tCase ci p c brs ⇝ tCase ci p c brs'

| proj_red p c c' : Σ ;;; Γ |- c ⇝ c' -> Σ ;;; Γ |- tProj p c ⇝ tProj p c'

| app_red_l M1 N1 M2 : Σ ;;; Γ |- M1 ⇝ N1 -> Σ ;;; Γ |- tApp M1 M2 ⇝ tApp N1 M2
| app_red_r M2 N2 M1 : Σ ;;; Γ |- M2 ⇝ N2 -> Σ ;;; Γ |- tApp M1 M2 ⇝ tApp M1 N2

| prod_red_l na M1 M2 N1 : Σ ;;; Γ |- M1 ⇝ N1 -> Σ ;;; Γ |- tProd na M1 M2 ⇝ tProd na N1 M2
| prod_red_r na M2 N2 M1 : Σ ;;; Γ ,, vass na M1 |- M2 ⇝ N2 ->
                           Σ ;;; Γ |- tProd na M1 M2 ⇝ tProd na M1 N2

| evar_red ev l l' : OnOne2 (fun t u => Σ ;;; Γ |- t ⇝ u) l l' -> Σ ;;; Γ |- tEvar ev l ⇝ tEvar ev l'

| fix_red_ty mfix0 mfix1 idx :
    OnOne2 (on_Trel_eq (fun t u => Σ ;;; Γ |- t ⇝ u) dtype (fun x => (dname x, dbody x, rarg x))) mfix0 mfix1 ->
    Σ ;;; Γ |- tFix mfix0 idx ⇝ tFix mfix1 idx

| fix_red_body mfix0 mfix1 idx :
    OnOne2 (on_Trel_eq (fun t u => Σ ;;; Γ ,,, fix_context mfix0 |- t ⇝ u) dbody (fun x => (dname x, dtype x, rarg x)))
           mfix0 mfix1 ->
    Σ ;;; Γ |- tFix mfix0 idx ⇝ tFix mfix1 idx

| cofix_red_ty mfix0 mfix1 idx :
    OnOne2 (on_Trel_eq (fun t u => Σ ;;; Γ |- t ⇝ u) dtype (fun x => (dname x, dbody x, rarg x))) mfix0 mfix1 ->
    Σ ;;; Γ |- tCoFix mfix0 idx ⇝ tCoFix mfix1 idx

| cofix_red_body mfix0 mfix1 idx :
    OnOne2 (on_Trel_eq (fun t u => Σ ;;; Γ ,,, fix_context mfix0 |- t ⇝ u) dbody (fun x => (dname x, dtype x, rarg x))) mfix0 mfix1 ->
    Σ ;;; Γ |- tCoFix mfix0 idx ⇝ tCoFix mfix1 idx

| array_red_val arr value :
    OnOne2 (fun t u => Σ ;;; Γ |- t ⇝ u) arr.(array_value) value ->
    Σ ;;; Γ |- tPrim (primArray; primArrayModel arr) ⇝
               tPrim (primArray; primArrayModel (set_array_value arr value))

| array_red_def arr def :
    Σ ;;; Γ |- arr.(array_default) ⇝ def ->
    Σ ;;; Γ |- tPrim (primArray; primArrayModel arr) ⇝
               tPrim (primArray; primArrayModel (set_array_default arr def))

| array_red_type arr ty :
    Σ ;;; Γ |- arr.(array_type) ⇝ ty ->
    Σ ;;; Γ |- tPrim (primArray; primArrayModel arr) ⇝
          tPrim (primArray; primArrayModel (set_array_type arr ty))

where " Σ ;;; Γ |- t ⇝ u " := (red1 Σ Γ t u).

Definition red1_ctx Σ := (OnOne2_local_env (fun Δ => on_one_decl (fun t t' => red1 Σ Δ t t'))).

Definition red Σ Γ := clos_refl_trans (fun t u : term => Σ;;; Γ |- t ⇝ u).
Module Export PCUICCumulativitySpec.

Implicit Types (cf : checker_flags).

Definition cumul_predicate (cumul : context -> term -> term -> Type) cumul_universe Γ p p' :=
  All2 (cumul Γ) p.(pparams) p'.(pparams) ×
  cmp_universe_instance cumul_universe p.(puinst) p'.(puinst) ×
  eq_context_upto_names p.(pcontext) p'.(pcontext) ×
  cumul (Γ ,,, inst_case_predicate_context p) p.(preturn) p'.(preturn).

Definition cumul_branch (cumul_term : context -> term -> term -> Type) Γ p br br' :=
  eq_context_upto_names br.(bcontext) br'.(bcontext) ×
  cumul_term (Γ ,,, inst_case_branch_context p br) br.(bbody) br'.(bbody).

Definition cumul_branches cumul_term Γ p brs brs' := All2 (cumul_branch cumul_term Γ p) brs brs'.

Definition cumul_mfixpoint (cumul_term : context -> term -> term -> Type) Γ mfix mfix' :=
  All2 (fun d d' =>
    cumul_term Γ d.(dtype) d'.(dtype) ×
    cumul_term (Γ ,,, fix_context mfix) d.(dbody) d'.(dbody) ×
    d.(rarg) = d'.(rarg) ×
    eq_binder_annot d.(dname) d'.(dname)
  ) mfix mfix'.

Reserved Notation " Σ ;;; Γ ⊢ t ≤s[ pb ] u" (at level 50, Γ, t, u at next level,
  format "Σ  ;;;  Γ  ⊢  t  ≤s[ pb ]  u").

Definition cumul_Ind_univ {cf} (Σ : global_env_ext) pb i napp :=
  cmp_global_instance Σ (compare_universe Σ) pb (IndRef i) napp.

Definition cumul_Construct_univ {cf} (Σ : global_env_ext) pb  i k napp :=
  cmp_global_instance Σ (compare_universe Σ) pb (ConstructRef i k) napp.
Inductive cumulSpec0 {cf : checker_flags} (Σ : global_env_ext) Γ (pb : conv_pb) : term -> term -> Type :=

| cumul_Trans : forall t u v,
    is_closed_context Γ -> is_open_term Γ u ->
    Σ ;;; Γ ⊢ t ≤s[pb] u ->
    Σ ;;; Γ ⊢ u ≤s[pb] v ->
    Σ ;;; Γ ⊢ t ≤s[pb] v

| cumul_Sym : forall t u,
    Σ ;;; Γ ⊢ t ≤s[Conv] u ->
    Σ ;;; Γ ⊢ u ≤s[pb] t

| cumul_Refl : forall t,
    Σ ;;; Γ ⊢ t ≤s[pb] t

| cumul_Ind : forall i u u' args args',
    cumul_Ind_univ Σ pb i #|args| u u' ->
    All2 (fun t u => Σ ;;; Γ ⊢ t ≤s[Conv] u) args args' ->
    Σ ;;; Γ ⊢ mkApps (tInd i u) args ≤s[pb] mkApps (tInd i u') args'

| cumul_Construct : forall i k u u' args args',
    cumul_Construct_univ Σ pb i k #|args| u u' ->
    All2 (fun t u => Σ ;;; Γ ⊢ t ≤s[Conv] u) args args' ->
    Σ ;;; Γ ⊢ mkApps (tConstruct i k u) args ≤s[pb] mkApps (tConstruct i k u') args'

| cumul_Sort : forall s s',
    compare_sort Σ pb s s' ->
    Σ ;;; Γ ⊢ tSort s ≤s[pb] tSort s'

| cumul_Const : forall c u u',
    cmp_universe_instance (compare_universe Σ Conv) u u' ->
    Σ ;;; Γ ⊢ tConst c u ≤s[pb] tConst c u'

| cumul_Evar : forall e args args',
    All2 (fun t u => Σ ;;; Γ ⊢ t ≤s[Conv] u) args args' ->
    Σ ;;; Γ ⊢ tEvar e args ≤s[pb] tEvar e args'

| cumul_App : forall t t' u u',
    Σ ;;; Γ ⊢ t ≤s[pb] t' ->
    Σ ;;; Γ ⊢ u ≤s[Conv] u' ->
    Σ ;;; Γ ⊢ tApp t u ≤s[pb] tApp t' u'

| cumul_Lambda : forall na na' ty ty' t t',
    eq_binder_annot na na' ->
    Σ ;;; Γ ⊢ ty ≤s[Conv] ty' ->
    Σ ;;; Γ ,, vass na ty ⊢ t ≤s[Conv] t' ->
    Σ ;;; Γ ⊢ tLambda na ty t ≤s[pb] tLambda na' ty' t'

| cumul_Prod : forall na na' a a' b b',
    eq_binder_annot na na' ->
    Σ ;;; Γ ⊢ a ≤s[Conv] a' ->
    Σ ;;; Γ ,, vass na a ⊢ b ≤s[pb] b' ->
    Σ ;;; Γ ⊢ tProd na a b ≤s[pb] tProd na' a' b'

| cumul_LetIn : forall na na' t t' ty ty' u u',
    eq_binder_annot na na' ->
    Σ ;;; Γ ⊢ t ≤s[Conv] t' ->
    Σ ;;; Γ ⊢ ty ≤s[Conv] ty' ->
    Σ ;;; Γ ,, vdef na t ty ⊢ u ≤s[Conv] u' ->
    Σ ;;; Γ ⊢ tLetIn na t ty u ≤s[pb] tLetIn na' t' ty' u'

| cumul_Case indn : forall p p' c c' brs brs',
    cumul_predicate (fun Γ t u => Σ ;;; Γ ⊢ t ≤s[Conv] u) (compare_universe Σ Conv) Γ p p' ->
    Σ ;;; Γ ⊢ c ≤s[Conv] c' ->
    cumul_branches (fun Γ t u => Σ ;;; Γ ⊢ t ≤s[Conv] u) Γ p brs brs' ->
    Σ ;;; Γ ⊢ tCase indn p c brs ≤s[pb] tCase indn p' c' brs'

| cumul_Proj : forall p c c',
    Σ ;;; Γ ⊢ c ≤s[Conv] c' ->
    Σ ;;; Γ ⊢ tProj p c ≤s[pb] tProj p c'

| cumul_Fix : forall mfix mfix' idx,
    cumul_mfixpoint (fun Γ t u => Σ ;;; Γ ⊢ t ≤s[Conv] u) Γ mfix mfix' ->
    Σ ;;; Γ ⊢ tFix mfix idx ≤s[pb] tFix mfix' idx

| cumul_CoFix : forall mfix mfix' idx,
    cumul_mfixpoint (fun Γ t u => Σ ;;; Γ ⊢ t ≤s[Conv] u) Γ mfix mfix' ->
    Σ ;;; Γ ⊢ tCoFix mfix idx ≤s[pb] tCoFix mfix' idx

| cumul_Prim p p' :
  onPrims (fun x y => Σ ;;; Γ ⊢ x ≤s[Conv] y) (compare_universe Σ Conv) p p' ->
  Σ ;;; Γ ⊢ tPrim p ≤s[pb] tPrim p'

| cumul_beta : forall na t b a,
    Σ ;;; Γ ⊢ tApp (tLambda na t b) a ≤s[pb] b {0 := a}

| cumul_zeta : forall na b t b',
    Σ ;;; Γ ⊢ tLetIn na b t b' ≤s[pb] b' {0 := b}

| cumul_rel i body :
    option_map decl_body (nth_error Γ i) = Some (Some body) ->
    Σ ;;; Γ ⊢ tRel i ≤s[pb] lift0 (S i) body

| cumul_iota : forall ci c u args p brs br,
    nth_error brs c = Some br ->
    #|args| = (ci.(ci_npar) + context_assumptions br.(bcontext))%nat ->
    Σ ;;; Γ ⊢ tCase ci p (mkApps (tConstruct ci.(ci_ind) c u) args) brs  ≤s[pb] iota_red ci.(ci_npar) p args br

| cumul_fix : forall mfix idx args narg fn,
    unfold_fix mfix idx = Some (narg, fn) ->
    is_constructor narg args = true ->
    Σ ;;; Γ ⊢ mkApps (tFix mfix idx) args ≤s[pb] mkApps fn args

| cumul_cofix_case : forall ip p mfix idx args narg fn brs,
    unfold_cofix mfix idx = Some (narg, fn) ->
    Σ ;;; Γ ⊢ tCase ip p (mkApps (tCoFix mfix idx) args) brs ≤s[pb] tCase ip p (mkApps fn args) brs

| cumul_cofix_proj : forall p mfix idx args narg fn,
    unfold_cofix mfix idx = Some (narg, fn) ->
    Σ ;;; Γ ⊢ tProj p (mkApps (tCoFix mfix idx) args) ≤s[pb] tProj p (mkApps fn args)

| cumul_delta : forall c decl body (isdecl : declared_constant Σ c decl) u,
    decl.(cst_body) = Some body ->
    Σ ;;; Γ ⊢ tConst c u ≤s[pb] body@[u]

| cumul_proj : forall p args u arg,
    nth_error args (p.(proj_npars) + p.(proj_arg)) = Some arg ->
    Σ ;;; Γ ⊢ tProj p (mkApps (tConstruct p.(proj_ind) 0 u) args) ≤s[pb] arg

where " Σ ;;; Γ ⊢ t ≤s[ pb ] u " := (@cumulSpec0 _ Σ Γ pb t u) : type_scope.
Definition cumulSpec `{checker_flags} (Σ : global_env_ext) Γ := cumulSpec0 Σ Γ Cumul.

Notation " Σ ;;; Γ |- t <=s u " := (@cumulSpec _ Σ Γ t u) (at level 50, Γ, t, u at next level).

Module PCUICConversionParSpec <: EnvironmentTyping.ConversionParSig PCUICTerm PCUICEnvironment PCUICTermUtils PCUICEnvTyping.
End PCUICConversionParSpec.

End PCUICCumulativitySpec.

Implicit Types (cf : checker_flags) (Σ : global_env_ext).

Definition type_of_constructor mdecl (cdecl : constructor_body) (c : inductive * nat) (u : list Level.t) :=
  let mind := inductive_mind (fst c) in
  subst0 (inds mind u mdecl.(ind_bodies)) (subst_instance u (cstr_type cdecl)).

Include PCUICEnvTyping.

Inductive FixCoFix : Type := Fix | CoFix.

Class GuardChecker :=
{
  guard : FixCoFix -> global_env_ext -> context -> mfixpoint term -> Prop ;
}.

Axiom guard_checking : GuardChecker.
#[global]
Existing Instance guard_checking.

Definition fix_guard := guard Fix.
Definition cofix_guard := guard CoFix.

Definition destInd (t : term) :=
  match t with
  | tInd ind u => Some (ind, u)
  | _ => None
  end.

Definition isCoFinite (r : recursivity_kind) :=
  match r with
  | CoFinite => true
  | _ => false
  end.

Definition check_recursivity_kind
  (lookup: kername -> option global_decl) ind r :=
  match lookup ind with
  | Some (InductiveDecl mib) => ReflectEq.eqb mib.(ind_finite) r
  | _ => false
  end.

Definition check_one_fix d :=
  let '{| dname := na;
         dtype := ty;
         dbody := b;
         rarg := arg |} := d in
  let '(ctx, ty) := decompose_prod_assum [] ty in
  match nth_error (List.rev (smash_context [] ctx)) arg with
  | Some argd =>
    let (hd, args) := decompose_app argd.(decl_type) in
    match destInd hd with
    | Some (mkInd mind _, u) => Some mind
    | None => None
    end
  | None => None
  end.

Definition wf_fixpoint_gen
  (lookup: kername -> option global_decl) mfix :=
  forallb (isLambda ∘ dbody) mfix &&
  let checks := map check_one_fix mfix in
  match map_option_out checks with
  | Some (ind :: inds) =>

    forallb (eqb ind) inds &&
    check_recursivity_kind lookup ind Finite
  | _ => false
  end.

Definition wf_fixpoint (Σ : global_env) := wf_fixpoint_gen (lookup_env Σ).

Definition check_one_cofix d :=
  let '{| dname := na;
         dtype := ty;
         dbody := b;
         rarg := arg |} := d in
  let '(ctx, ty) := decompose_prod_assum [] ty in
  let (hd, args) := decompose_app ty in
  match destInd hd with
  | Some (mkInd ind _, u) => Some ind
  | None => None
  end.

Definition wf_cofixpoint_gen
  (lookup: kername -> option global_decl) mfix :=
  let checks := map check_one_cofix mfix in
  match map_option_out checks with
  | Some (ind :: inds) =>

    forallb (eqb ind) inds &&
    check_recursivity_kind lookup ind CoFinite
  | _ => false
  end.

Definition wf_cofixpoint (Σ : global_env) := wf_cofixpoint_gen (lookup_env Σ).

Reserved Notation "'wf_local' Σ Γ " (at level 9, Σ, Γ at next level).

Reserved Notation " Σ ;;; Γ |- t : T " (at level 50, Γ, t, T at next level).

Variant case_side_conditions `{checker_flags} wf_local_fun typing Σ Γ ci p ps mdecl idecl indices predctx :=
| case_side_info
    (eq_npars : mdecl.(ind_npars) = ci.(ci_npar))
    (wf_pred : wf_predicate mdecl idecl p)
    (cons : consistent_instance_ext Σ (ind_universes mdecl) p.(puinst))
    (wf_pctx : wf_local_fun Σ (Γ ,,, predctx))

    (conv_pctx : eq_context_upto_names p.(pcontext) (ind_predicate_context ci.(ci_ind) mdecl idecl))
    (allowed_elim : is_allowed_elimination Σ idecl.(ind_kelim) ps)
    (elim_relevance : isSortRel ps ci.(ci_relevance))
    (ind_inst : ctx_inst (typing Σ) Γ (p.(pparams) ++ indices)
                         (List.rev (subst_instance p.(puinst)
                                                   (ind_params mdecl ,,, ind_indices idecl : context))))
    (not_cofinite : isCoFinite mdecl.(ind_finite) = false).

Variant case_branch_typing `{checker_flags} wf_local_fun typing Σ Γ (ci:case_info) p ps mdecl idecl ptm  brs :=
| case_branch_info
    (wf_brs : wf_branches idecl brs)
    (brs_ty :
       All2i (fun i cdecl br =>

                eq_context_upto_names br.(bcontext) (cstr_branch_context ci mdecl cdecl) ×
                let brctxty := case_branch_type ci.(ci_ind) mdecl idecl p br ptm i cdecl in
                (wf_local_fun Σ (Γ ,,, brctxty.1) ×
                ((typing Σ (Γ ,,, brctxty.1) br.(bbody) (brctxty.2)) ×
                (typing Σ (Γ ,,, brctxty.1) brctxty.2 (tSort ps)))))
             0 idecl.(ind_ctors) brs).

Variant primitive_typing_hyps `{checker_flags}
  (typing : forall (Σ : global_env_ext) (Γ : context), term -> term -> Type)
  Σ Γ : prim_val term -> Type :=
| prim_int_hyps i : primitive_typing_hyps typing Σ Γ (primInt; primIntModel i)
| prim_float_hyps f : primitive_typing_hyps typing Σ Γ (primFloat; primFloatModel f)
| prim_string_hyps s : primitive_typing_hyps typing Σ Γ (primString; primStringModel s)
| prim_array_hyps a
  (wfl : wf_universe Σ (Universe.make' a.(array_level)))
  (hty : typing Σ Γ a.(array_type) (tSort (sType (Universe.make' a.(array_level)))))
  (hdef : typing Σ Γ a.(array_default) a.(array_type))
  (hvalue : All (fun x => typing Σ Γ x a.(array_type)) a.(array_value)) :
  primitive_typing_hyps typing Σ Γ (primArray; primArrayModel a).

Equations prim_type (p : prim_val term) (cst : kername) : term :=
prim_type (primInt; _) cst := tConst cst [];
prim_type (primFloat; _) cst := tConst cst [];
prim_type (primString; _) cst := tConst cst [];
prim_type (primArray; primArrayModel a) cst := tApp (tConst cst [a.(array_level)]) a.(array_type).

Inductive typing `{checker_flags} (Σ : global_env_ext) (Γ : context) : term -> term -> Type :=
| type_Rel : forall n decl,
    wf_local Σ Γ ->
    nth_error Γ n = Some decl ->
    Σ ;;; Γ |- tRel n : lift0 (S n) decl.(decl_type)

| type_Sort : forall s,
    wf_local Σ Γ ->
    wf_sort Σ s ->
    Σ ;;; Γ |- tSort s : tSort (Sort.super s)

| type_Prod : forall na A B s1 s2,
    lift_typing typing Σ Γ (j_vass_s na A s1) ->
    Σ ;;; Γ ,, vass na A |- B : tSort s2 ->
    Σ ;;; Γ |- tProd na A B : tSort (Sort.sort_of_product s1 s2)

| type_Lambda : forall na A t B,
    lift_typing typing Σ Γ (j_vass na A) ->
    Σ ;;; Γ ,, vass na A |- t : B ->
    Σ ;;; Γ |- tLambda na A t : tProd na A B

| type_LetIn : forall na b B t A,
    lift_typing typing Σ Γ (j_vdef na b B) ->
    Σ ;;; Γ ,, vdef na b B |- t : A ->
    Σ ;;; Γ |- tLetIn na b B t : tLetIn na b B A

| type_App : forall t na A B s u,

    Σ ;;; Γ |- tProd na A B : tSort s ->
    Σ ;;; Γ |- t : tProd na A B ->
    Σ ;;; Γ |- u : A ->
    Σ ;;; Γ |- tApp t u : B{0 := u}

| type_Const : forall cst u decl,
    wf_local Σ Γ ->
    declared_constant Σ cst decl ->
    consistent_instance_ext Σ decl.(cst_universes) u ->
    Σ ;;; Γ |- tConst cst u : decl.(cst_type)@[u]

| type_Ind : forall ind u mdecl idecl,
    wf_local Σ Γ ->
    declared_inductive Σ ind mdecl idecl ->
    consistent_instance_ext Σ mdecl.(ind_universes) u ->
    Σ ;;; Γ |- tInd ind u : idecl.(ind_type)@[u]

| type_Construct : forall ind i u mdecl idecl cdecl,
    wf_local Σ Γ ->
    declared_constructor Σ (ind, i) mdecl idecl cdecl ->
    consistent_instance_ext Σ mdecl.(ind_universes) u ->
    Σ ;;; Γ |- tConstruct ind i u : type_of_constructor mdecl cdecl (ind, i) u

| type_Case : forall ci p c brs indices ps mdecl idecl,
    let predctx := case_predicate_context ci.(ci_ind) mdecl idecl p in
    let ptm := it_mkLambda_or_LetIn predctx p.(preturn) in
    declared_inductive Σ ci.(ci_ind) mdecl idecl ->
    Σ ;;; Γ ,,, predctx |- p.(preturn) : tSort ps ->
    Σ ;;; Γ |- c : mkApps (tInd ci.(ci_ind) p.(puinst)) (p.(pparams) ++ indices) ->
    case_side_conditions (fun Σ Γ => wf_local Σ Γ) typing Σ Γ ci p ps
                         mdecl idecl indices predctx  ->
    case_branch_typing (fun Σ Γ => wf_local Σ Γ) typing Σ Γ ci p ps
                        mdecl idecl ptm brs ->
    Σ ;;; Γ |- tCase ci p c brs : mkApps ptm (indices ++ [c])

| type_Proj : forall p c u mdecl idecl cdecl pdecl args,
    declared_projection Σ p mdecl idecl cdecl pdecl ->
    Σ ;;; Γ |- c : mkApps (tInd p.(proj_ind) u) args ->
    #|args| = ind_npars mdecl ->
    Σ ;;; Γ |- tProj p c : subst0 (c :: List.rev args) pdecl.(proj_type)@[u]

| type_Fix : forall mfix n decl,
    wf_local Σ Γ ->
    fix_guard Σ Γ mfix ->
    nth_error mfix n = Some decl ->
    All (on_def_type (lift_typing1 (typing Σ)) Γ) mfix ->
    All (on_def_body (lift_typing1 (typing Σ)) (fix_context mfix) Γ) mfix ->
    wf_fixpoint Σ mfix ->
    Σ ;;; Γ |- tFix mfix n : decl.(dtype)

| type_CoFix : forall mfix n decl,
    wf_local Σ Γ ->
    cofix_guard Σ Γ mfix ->
    nth_error mfix n = Some decl ->
    All (on_def_type (lift_typing1 (typing Σ)) Γ) mfix ->
    All (on_def_body (lift_typing1 (typing Σ)) (fix_context mfix) Γ) mfix ->
    wf_cofixpoint Σ mfix ->
    Σ ;;; Γ |- tCoFix mfix n : decl.(dtype)

| type_Prim p prim_ty cdecl :
    wf_local Σ Γ ->
    primitive_constant Σ (prim_val_tag p) = Some prim_ty ->
    declared_constant Σ prim_ty cdecl ->
    primitive_invariants (prim_val_tag p) cdecl ->
    primitive_typing_hyps typing Σ Γ p ->
    Σ ;;; Γ |- tPrim p : prim_type p prim_ty

| type_Cumul : forall t A B s,
    Σ ;;; Γ |- t : A ->
    Σ ;;; Γ |- B : tSort s ->
    Σ ;;; Γ |- A <=s B ->
    Σ ;;; Γ |- t : B

where " Σ ;;; Γ |- t : T " := (typing Σ Γ t T)
and "'wf_local' Σ Γ " := (All_local_env (lift_typing1 (typing Σ)) Γ).

Definition wf `{checker_flags} := on_global_env cumulSpec0 (lift_typing typing).
Notation on_contexts_length := All2_fold_length.
Import Stdlib.Classes.CRelationClasses.
Import Equations.Type.Relation_Properties.

Definition ws_term P := { t : term | on_free_vars P t }.
Definition ws_term_proj {P} (t : ws_term P) : term.
admit.
Defined.
Coercion ws_term_proj : ws_term >-> term.

Definition ws_context P := { t : context | on_free_vars_ctx P t }.

Notation closed_context := (ws_context xpred0).
Notation open_term Γ := (ws_term (shiftnP #|Γ| xpred0)).
Definition ws_context_proj' {P} (t : ws_context P) : list context_decl.
Admitted.
Coercion ws_context_proj' : ws_context >-> list.

Definition ws_red1 Σ P (Γ : ws_context P) (t u : ws_term (shiftnP #|Γ| P)) :=
  red1 Σ Γ t u.

Definition ws_red Σ P (Γ : ws_context P) := clos_refl_trans (ws_red1 Σ P Γ).

Definition ws_pair :=
  ∑ Γ : ws_context xpred0, ws_term (shiftnP #|Γ| xpred0).

Section RedConfluence.
  Context {cf : checker_flags}.
  Context {Σ : global_env_ext} (wfΣ : wf Σ).
Definition red1_rel_alpha : relation ws_pair.
exact (relation_disjunction (A:=ws_pair) (fun '(Γ; t) '(Δ; u) => (red1 Σ Γ t u * (Γ = Δ)))%type
     (relation_disjunction (A:=ws_pair)
        (fun '(Γ; t) '(Δ; u) => ((red1_ctx Σ Γ Δ * (t = u :> term))))
        (fun '(Γ; t) '(Δ; u) => ((eq_context_upto_names Γ Δ * (t = u :> term)))))%type).
Defined.

  Lemma red_ws_red (Γ : closed_context) (x y : ws_term (shiftnP #|Γ| xpred0)) :
    red Σ Γ x y -> ws_red Σ xpred0 Γ x y.
Admitted.
Definition transport_ws_term {n m : nat} (t : ws_term (shiftnP n xpred0)) (eq : n = m) : ws_term (shiftnP m xpred0).
Admitted.
Definition red_ctx_alpha : relation context.
exact (All2_fold (fun Γ _ => All_decls_alpha (red Σ Γ))).
Defined.

  Instance red_ctx_alpha_refl : Reflexive red_ctx_alpha.
Admitted.

  Lemma ws_red_refl_irrel P (Γ : ws_context P) (x y : ws_term (shiftnP #|Γ| P)) :
    x = y :> term ->
    ws_red Σ P Γ x y.
Admitted.

  Lemma clos_rt_red1_alpha_out x y :
    clos_refl_trans red1_rel_alpha x y ->
    ∑ redctx : red_ctx_alpha x.π1 y.π1,
      ws_red Σ xpred0 x.π1 x.π2 (transport_ws_term y.π2 (symmetry (All2_fold_length redctx))).
  Proof using wfΣ.
    intros H.
    eapply clos_rt_rt1n_iff in H.
    induction H.
    -
 unshelve eexists.
reflexivity.
eapply ws_red_refl_irrel => //.
    -
 destruct x as [Γ t], y as [Δ u], z as [Δ' u']; simpl in *.
      destruct IHclos_refl_trans_1n.
      red in r.
destruct r.
      *
 destruct p.
subst.
exists x.
        transitivity u; auto.
        now eapply red_ws_red.
      *
 destruct t as [t ht], u as [u hu];
        move: r; case; move => [] r eq; noconf eq.
🛠️ Intermediate Coq File (useful for debugging if minimization did not go as far as you wanted)
🛠️ 📜 Intermediate Coq File log (useful for debugging if minimization did not go as far as you wanted)
📜 Build Log (contains the Coq error message) (truncated to last 8.0KiB; full 7.0MiB file on GitHub Actions Artifacts under build.log)
t-minimizer.KwQ86BCSh4
MINIMIZER_DEBUG: files: 
make[2]: Leaving directory '/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/template-rocq'
# Ensure the cmxs is built before the loader file 
make -f Makefile.plugin gen-src/metarocq_template_plugin.cmxs
make[2]: Entering directory '/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/template-rocq'
MINIMIZER_DEBUG_EXTRA: coqc: /github/workspace/builds/coq/coq-failing/_install_ci/bin///rocq
MINIMIZER_DEBUG_EXTRA: original invocation: c --print-version 
MINIMIZER_DEBUG_EXTRA: new invocation: /github/workspace/builds/coq/coq-failing/_install_ci/bin/rocq.orig c --print-version 
MINIMIZER_DEBUG_EXTRA: coqpath: 
MINIMIZER_DEBUG_EXTRA: ocamlpath: /github/workspace/builds/coq/coq-failing/_build_ci/metarocq/template-rocq/:/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/safechecker-plugin/src:/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/erasure-plugin/src:/github/workspace/builds/coq/coq-failing/_install_ci/lib:
MINIMIZER_DEBUG_EXTRA: pwd: PWD=/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/template-rocq
MINIMIZER_DEBUG_EXTRA: exec: /github/workspace/builds/coq/coq-failing/_install_ci/bin/rocq.orig c --print-version 
MINIMIZER_DEBUG_EXTRA: coqlib: Warning: Deprecated environment variable COQLIB, use ROCQLIB instead.
/github/workspace/builds/coq/coq-failing/_install_ci/lib/coq//
MINIMIZER_DEBUG: info: /tmp/tmp-coqbot-minimizer.PTXVIDigOb
MINIMIZER_DEBUG: files: 
make[2]: 'gen-src/metarocq_template_plugin.cmxs' is up to date.
make[2]: Leaving directory '/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/template-rocq'
make -f Makefile.plugin
make[2]: Entering directory '/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/template-rocq'
MINIMIZER_DEBUG_EXTRA: coqc: /github/workspace/builds/coq/coq-failing/_install_ci/bin///rocq
MINIMIZER_DEBUG_EXTRA: original invocation: c --print-version 
MINIMIZER_DEBUG_EXTRA: new invocation: /github/workspace/builds/coq/coq-failing/_install_ci/bin/rocq.orig c --print-version 
MINIMIZER_DEBUG_EXTRA: coqpath: 
MINIMIZER_DEBUG_EXTRA: ocamlpath: /github/workspace/builds/coq/coq-failing/_build_ci/metarocq/template-rocq/:/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/safechecker-plugin/src:/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/erasure-plugin/src:/github/workspace/builds/coq/coq-failing/_install_ci/lib:
MINIMIZER_DEBUG_EXTRA: pwd: PWD=/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/template-rocq
MINIMIZER_DEBUG_EXTRA: exec: /github/workspace/builds/coq/coq-failing/_install_ci/bin/rocq.orig c --print-version 
MINIMIZER_DEBUG_EXTRA: coqlib: Warning: Deprecated environment variable COQLIB, use ROCQLIB instead.
/github/workspace/builds/coq/coq-failing/_install_ci/lib/coq//
MINIMIZER_DEBUG: info: /tmp/tmp-coqbot-minimizer.vsoVkZVKHS
MINIMIZER_DEBUG: files: 
MINIMIZER_DEBUG_EXTRA: coqc: /github/workspace/builds/coq/coq-failing/_install_ci/bin/////rocq
MINIMIZER_DEBUG_EXTRA: original invocation: c --print-version 
MINIMIZER_DEBUG_EXTRA: new invocation: /github/workspace/builds/coq/coq-failing/_install_ci/bin/rocq.orig c --print-version 
MINIMIZER_DEBUG_EXTRA: coqpath: 
MINIMIZER_DEBUG_EXTRA: ocamlpath: /github/workspace/builds/coq/coq-failing/_build_ci/metarocq/template-rocq/:/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/safechecker-plugin/src:/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/erasure-plugin/src:/github/workspace/builds/coq/coq-failing/_install_ci/lib:
MINIMIZER_DEBUG_EXTRA: pwd: PWD=/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/template-rocq
MINIMIZER_DEBUG_EXTRA: exec: /github/workspace/builds/coq/coq-failing/_install_ci/bin/rocq.orig c --print-version 
MINIMIZER_DEBUG_EXTRA: coqlib: Warning: Deprecated environment variable COQLIB, use ROCQLIB instead.
/github/workspace/builds/coq/coq-failing/_install_ci/lib/coq//
MINIMIZER_DEBUG: info: /tmp/tmp-coqbot-minimizer.JDeudoUguL
MINIMIZER_DEBUG: files: 
MINIMIZER_DEBUG_EXTRA: coqc: /github/workspace/builds/coq/coq-failing/_install_ci/bin/////rocq
MINIMIZER_DEBUG_EXTRA: original invocation: c --print-version 
MINIMIZER_DEBUG_EXTRA: new invocation: /github/workspace/builds/coq/coq-failing/_install_ci/bin/rocq.orig c --print-version 
MINIMIZER_DEBUG_EXTRA: coqpath: 
MINIMIZER_DEBUG_EXTRA: ocamlpath: /github/workspace/builds/coq/coq-failing/_build_ci/metarocq/template-rocq/:/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/safechecker-plugin/src:/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/erasure-plugin/src:/github/workspace/builds/coq/coq-failing/_install_ci/lib:
MINIMIZER_DEBUG_EXTRA: pwd: PWD=/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/template-rocq
MINIMIZER_DEBUG_EXTRA: exec: /github/workspace/builds/coq/coq-failing/_install_ci/bin/rocq.orig c --print-version 
MINIMIZER_DEBUG_EXTRA: coqlib: Warning: Deprecated environment variable COQLIB, use ROCQLIB instead.
/github/workspace/builds/coq/coq-failing/_install_ci/lib/coq//
MINIMIZER_DEBUG: info: /tmp/tmp-coqbot-minimizer.oXyYEAMG9d
MINIMIZER_DEBUG: files: 
make[3]: Nothing to be done for 'real-all'.
MINIMIZER_DEBUG_EXTRA: coqc: /github/workspace/builds/coq/coq-failing/_install_ci/bin/////rocq
MINIMIZER_DEBUG_EXTRA: original invocation: c --print-version 
MINIMIZER_DEBUG_EXTRA: new invocation: /github/workspace/builds/coq/coq-failing/_install_ci/bin/rocq.orig c --print-version 
MINIMIZER_DEBUG_EXTRA: coqpath: 
MINIMIZER_DEBUG_EXTRA: ocamlpath: /github/workspace/builds/coq/coq-failing/_build_ci/metarocq/template-rocq/:/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/safechecker-plugin/src:/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/erasure-plugin/src:/github/workspace/builds/coq/coq-failing/_install_ci/lib:
MINIMIZER_DEBUG_EXTRA: pwd: PWD=/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/template-rocq
MINIMIZER_DEBUG_EXTRA: exec: /github/workspace/builds/coq/coq-failing/_install_ci/bin/rocq.orig c --print-version 
MINIMIZER_DEBUG_EXTRA: coqlib: Warning: Deprecated environment variable COQLIB, use ROCQLIB instead.
/github/workspace/builds/coq/coq-failing/_install_ci/lib/coq//
MINIMIZER_DEBUG: info: /tmp/tmp-coqbot-minimizer.7rFWE3Xj3Y
MINIMIZER_DEBUG: files: 
make[2]: Leaving directory '/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/template-rocq'
make[1]: Leaving directory '/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/template-rocq'
File "./theories/PCUICConfluence.v", line 3649, characters 47-49:
Error: Cannot infer the implicit parameter A of eq whose type is 
"Type" in
environment:
cf : checker_flags
Σ : global_env_ext
wfΣ : wf Σ
Γ : closed_context
t : term
ht : is_open_term Γ t
Δ : closed_context
u : term
hu : is_open_term Δ u
Δ' : closed_context
u' : open_term Δ'
H : clos_refl_trans_1n red1_rel_alpha (Δ; exist u hu) (Δ'; u')
x : red_ctx_alpha Δ Δ'
w :
  ws_red Σ xpred0 Δ (exist u hu)
    (transport_ws_term u' (symmetry (on_contexts_length x)))
r : red1_ctx Σ Γ Δ
eq : exist t ht = exist u hu

Command exited with non-zero status 1
theories/PCUICConfluence.vo (real: 46.31, user: 45.91, sys: 0.36, mem: 2430084 ko)
make[3]: *** [Makefile.rocq:814: theories/PCUICConfluence.vo] Error 1
make[3]: *** [theories/PCUICConfluence.vo] Deleting file 'theories/PCUICConfluence.glob'
make[2]: *** [Makefile.rocq:412: all] Error 2
make[2]: Leaving directory '/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/pcuic'
make[1]: *** [Makefile:11: coq] Error 2
make[1]: Leaving directory '/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/pcuic'
make: *** [Makefile:149: pcuic] Error 2
+ code=2
+ printf '\n%s exit code: %s\n' metarocq 2
+ '[' metarocq '!=' stdlib_test ']'
+ echo 'Aggregating timing log...'
Aggregating timing log...
+ echo

+ tools/make-one-time-file.py --real metarocq.log
    Time |   Peak Mem | File Name            
---------------------------------------------
0m46.31s | 2430084 ko | Total Time / Peak Mem
---------------------------------------------
0m46.31s | 2430084 ko | PCUICConfluence.vo   
+ '[' '' ']'
+ exit 2
/github/workspace/builds/coq /github/workspace
::endgroup::
📜 🔎 Minimization Log (truncated to last 8.0KiB; full 1.2MiB file on GitHub Actions Artifacts under bug.log)
dlib/blob/master/theories/Vectors/Vector.v>.
[warn-library-file-stdlib-vector,stdlib-vector,warn-library-file,user-warn,default]
File "/tmp/tmpuagosknn/Top/bug_01.v", line 209, characters 0-30:
Warning: Using Vector.t is known to be technically difficult, see
<https://github.com/coq/stdlib/blob/master/theories/Vectors/Vector.v>.
[warn-library-file-stdlib-vector,stdlib-vector,warn-library-file,user-warn,default]
File "/tmp/tmpuagosknn/Top/bug_01.v", line 210, characters 0-31:
Warning: Library File Stdlib.Vectors.Bvector is deprecated since 8.20.
Consider [list bool] instead. See <https://github.com/coq/stdlib/blob/master/theories/Vectors/Vector.v> for details. Please open an issue if you would like to keep using Bvector.
[deprecated-library-file-since-8.20,deprecated-since-8.20,deprecated-library-file,deprecated,default]
File "/tmp/tmpuagosknn/Top/bug_01.v", line 258, characters 0-34:
Warning: Library File Stdlib.ZArith.ZArith_base is deprecated since 9.0.
use ZArith instead
[deprecated-library-file-since-9.0,deprecated-since-9.0,deprecated-library-file,deprecated,default]
File "/tmp/tmpuagosknn/Top/bug_01.v", line 278, characters 7-20:
Warning: Coq.Init.Ltac has been replaced by Corelib.Init.Ltac.
[deprecated-dirpath-Coq,deprecated-since-9.0,deprecated,default]
File "/tmp/tmpuagosknn/Top/bug_01.v", line 2514, characters 0-9:
Error: Anomaly "Uncaught exception Invalid_argument("List.fold_left2")."
Please report at http://rocq-prover.org/bugs/.


�[93mIntermediate code not saved.�[0m
Failed to do everything at once; trying one at a time.
Admitting definitions unsuccessful.
No successful changes.

I will now attempt to admit lemmas with admit. Defined with
10000
 Proof using

Non-fatal error: Failed to admit lemmas and preserve the error.  
The new error was:
Deprecated environment variable COQCORELIB, use ROCQRUNTIMELIB instead.
Warning: Deprecated environment variable COQCORELIB,
use ROCQRUNTIMELIB instead.
[deprecated-coq-env-var,deprecated-since-9.0,deprecated,default]
File "/tmp/tmp4xuzxjfv/Top/bug_01.v", line 205, characters 0-27:
Warning: Alternatives to Fin.t are available, see
<https://github.com/coq/stdlib/blob/master/theories/Vectors/Fin.v>.
[warn-library-file-stdlib-vector,stdlib-vector,warn-library-file,user-warn,default]
File "/tmp/tmp4xuzxjfv/Top/bug_01.v", line 206, characters 0-33:
Warning: Using Vector.t is known to be technically difficult, see
<https://github.com/coq/stdlib/blob/master/theories/Vectors/Vector.v>.
[warn-library-file-stdlib-vector,stdlib-vector,warn-library-file,user-warn,default]
File "/tmp/tmp4xuzxjfv/Top/bug_01.v", line 207, characters 0-34:
Warning: Using Vector.t is known to be technically difficult, see
<https://github.com/coq/stdlib/blob/master/theories/Vectors/Vector.v>.
[warn-library-file-stdlib-vector,stdlib-vector,warn-library-file,user-warn,default]
File "/tmp/tmp4xuzxjfv/Top/bug_01.v", line 208, characters 0-32:
Warning: Using Vector.t is known to be technically difficult, see
<https://github.com/coq/stdlib/blob/master/theories/Vectors/Vector.v>.
[warn-library-file-stdlib-vector,stdlib-vector,warn-library-file,user-warn,default]
File "/tmp/tmp4xuzxjfv/Top/bug_01.v", line 209, characters 0-30:
Warning: Using Vector.t is known to be technically difficult, see
<https://github.com/coq/stdlib/blob/master/theories/Vectors/Vector.v>.
[warn-library-file-stdlib-vector,stdlib-vector,warn-library-file,user-warn,default]
File "/tmp/tmp4xuzxjfv/Top/bug_01.v", line 210, characters 0-31:
Warning: Library File Stdlib.Vectors.Bvector is deprecated since 8.20.
Consider [list bool] instead. See <https://github.com/coq/stdlib/blob/master/theories/Vectors/Vector.v> for details. Please open an issue if you would like to keep using Bvector.
[deprecated-library-file-since-8.20,deprecated-since-8.20,deprecated-library-file,deprecated,default]
File "/tmp/tmp4xuzxjfv/Top/bug_01.v", line 258, characters 0-34:
Warning: Library File Stdlib.ZArith.ZArith_base is deprecated since 9.0.
use ZArith instead
[deprecated-library-file-since-9.0,deprecated-since-9.0,deprecated-library-file,deprecated,default]
File "/tmp/tmp4xuzxjfv/Top/bug_01.v", line 278, characters 7-20:
Warning: Coq.Init.Ltac has been replaced by Corelib.Init.Ltac.
[deprecated-dirpath-Coq,deprecated-since-9.0,deprecated,default]
File "/tmp/tmp4xuzxjfv/Top/bug_01.v", line 2748, characters 0-45:
Warning: Declaring a scope implicitly is deprecated; use in advance an
explicit "Declare Scope type_scope2.".
[undeclared-scope,deprecated-since-8.10,deprecated,default]
Error: The section RedConfluence, module PCUICPrimitive, module
EnvironmentTyping, module Retroknowledge and module BasicAst
need to be closed.


�[93mIntermediate code not saved.�[0m
Failed to do everything at once; trying one at a time.
Admitting lemmas unsuccessful.
No successful changes.

I will now attempt to admit definitions with admit. Defined with Proof using

Non-fatal error: Failed to admit definitions and preserve the error.  
The new error was:
Deprecated environment variable COQCORELIB, use ROCQRUNTIMELIB instead.
Warning: Deprecated environment variable COQCORELIB,
use ROCQRUNTIMELIB instead.
[deprecated-coq-env-var,deprecated-since-9.0,deprecated,default]
File "/tmp/tmp6pevrre9/Top/bug_01.v", line 205, characters 0-27:
Warning: Alternatives to Fin.t are available, see
<https://github.com/coq/stdlib/blob/master/theories/Vectors/Fin.v>.
[warn-library-file-stdlib-vector,stdlib-vector,warn-library-file,user-warn,default]
File "/tmp/tmp6pevrre9/Top/bug_01.v", line 206, characters 0-33:
Warning: Using Vector.t is known to be technically difficult, see
<https://github.com/coq/stdlib/blob/master/theories/Vectors/Vector.v>.
[warn-library-file-stdlib-vector,stdlib-vector,warn-library-file,user-warn,default]
File "/tmp/tmp6pevrre9/Top/bug_01.v", line 207, characters 0-34:
Warning: Using Vector.t is known to be technically difficult, see
<https://github.com/coq/stdlib/blob/master/theories/Vectors/Vector.v>.
[warn-library-file-stdlib-vector,stdlib-vector,warn-library-file,user-warn,default]
File "/tmp/tmp6pevrre9/Top/bug_01.v", line 208, characters 0-32:
Warning: Using Vector.t is known to be technically difficult, see
<https://github.com/coq/stdlib/blob/master/theories/Vectors/Vector.v>.
[warn-library-file-stdlib-vector,stdlib-vector,warn-library-file,user-warn,default]
File "/tmp/tmp6pevrre9/Top/bug_01.v", line 209, characters 0-30:
Warning: Using Vector.t is known to be technically difficult, see
<https://github.com/coq/stdlib/blob/master/theories/Vectors/Vector.v>.
[warn-library-file-stdlib-vector,stdlib-vector,warn-library-file,user-warn,default]
File "/tmp/tmp6pevrre9/Top/bug_01.v", line 210, characters 0-31:
Warning: Library File Stdlib.Vectors.Bvector is deprecated since 8.20.
Consider [list bool] instead. See <https://github.com/coq/stdlib/blob/master/theories/Vectors/Vector.v> for details. Please open an issue if you would like to keep using Bvector.
[deprecated-library-file-since-8.20,deprecated-since-8.20,deprecated-library-file,deprecated,default]
File "/tmp/tmp6pevrre9/Top/bug_01.v", line 258, characters 0-34:
Warning: Library File Stdlib.ZArith.ZArith_base is deprecated since 9.0.
use ZArith instead
[deprecated-library-file-since-9.0,deprecated-since-9.0,deprecated-library-file,deprecated,default]
File "/tmp/tmp6pevrre9/Top/bug_01.v", line 278, characters 7-20:
Warning: Coq.Init.Ltac has been replaced by Corelib.Init.Ltac.
[deprecated-dirpath-Coq,deprecated-since-9.0,deprecated,default]
File "/tmp/tmp6pevrre9/Top/bug_01.v", line 2515, characters 0-8:
Error:  (in proof map_All): Attempt to save an incomplete proof
(there are remaining open goals).


�[93mIntermediate code not saved.�[0m
Failed to do everything at once; trying one at a time.
Admitting definitions unsuccessful.
No successful changes.

I will now attempt to add Proof using lines
�[92m
Adding Proof using lines successful.�[0m
Failed to do everything at once; trying one at a time.
Adding Proof using lines unsuccessful.
No successful changes.

I will now attempt to export modules
Module exportation successful

I will now attempt to split imports and exports
Import/Export splitting successful

I will now attempt to split := definitions

If you have any comments on your experience of the minimizer, please share them in a reply (possibly tagging @JasonGross).
If you believe there's a bug in the bug minimizer, please report it on the bug minimizer issue tracker.

Copy link
Contributor
coqbot-app bot commented May 27, 2025
Minimization interrupted by timeout, being automatically continued. Partially Minimized File /home/runner/work/run-coq-bug-minimizer/run-coq-bug-minimizer/builds/coq/coq-failing/_build_ci/metarocq/pcuic/theories/PCUICConfluence.v in 5h 15m 8s (from ci-metarocq) (interrupted by timeout, being automatically continued) (full log on GitHub Actions - verbose log)
⭐ ⏱️ Partially Minimized Coq File (timeout) (truncated to first and last 32KiB; full 74KiB file on GitHub Actions Artifacts under bug.v)
(* -*- mode: coq; coq-prog-args: ("-emacs" "-q" "-w" "-deprecated-native-compiler-option" "-native-compiler" "no" "-coqlib" "/github/workspace/builds/coq/coq-failing/_install_ci/lib/coq//" "-R" "/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/utils/theories" "MetaRocq.Utils" "-R" "/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/common/theories" "MetaRocq.Common" "-R" "/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/pcuic/theories" "MetaRocq.PCUIC" "-Q" "/github/workspace/cwd" "Top" "-Q" "/github/workspace/builds/coq/coq-failing/_install_ci/lib/coq///user-contrib/Equations" "Equations" "-Q" "/github/workspace/builds/coq/coq-failing/_install_ci/lib/coq///user-contrib/Ltac2" "Ltac2" "-Q" "/github/workspace/builds/coq/coq-failing/_install_ci/lib/coq///user-contrib/Stdlib" "Stdlib" "-top" "Top.bug_01") -*- *)
(* File reduced by coq-bug-minimizer from original input, then from 3959 lines to 98 lines, then from 111 lines to 3187 lines, then from 3191 lines to 96 lines, then from 107 lines to 1813 lines, then from 1818 lines to 359 lines, then from 369 lines to 1502 lines, then from 1506 lines to 524 lines, then from 535 lines to 3221 lines, then from 3222 lines to 656 lines, then from 667 lines to 2894 lines, then from 2900 lines to 656 lines, then from 667 lines to 1321 lines, then from 1327 lines to 874 lines, then from 883 lines to 675 lines, then from 686 lines to 2746 lines, then from 2745 lines to 687 lines, then from 698 lines to 3155 lines, then from 3155 lines to 745 lines, then from 756 lines to 1586 lines, then from 1589 lines to 869 lines, then from 880 lines to 2395 lines, then from 2394 lines to 885 lines, then from 895 lines to 2754 lines, then from 2755 lines to 1157 lines, then from 1161 lines to 1145 lines, then from 1156 lines to 1809 lines, then from 1813 lines to 1200 lines, then from 1211 lines to 4024 lines, then from 4021 lines to 1355 lines, then from 1366 lines to 3048 lines, then from 3051 lines to 1938 lines, then from 1928 lines to 1518 lines, then from 1529 lines to 1814 lines, then from 1819 lines to 1523 lines, then from 1533 lines to 2340 lines, then from 2342 lines to 1526 lines, then from 1536 lines to 4638 lines, then from 4602 lines to 1892 lines, then from 1903 lines to 3075 lines, then from 3076 lines to 2771 lines, then from 2762 lines to 1985 lines, then from 1996 lines to 2830 lines, then from 2835 lines to 2048 lines, then from 2059 lines to 2413 lines, then from 2418 lines to 2052 lines, then from 2063 lines to 2597 lines, then from 2601 lines to 2063 lines, then from 2074 lines to 6642 lines, then from 6641 lines to 4802 lines, then from 4761 lines to 2105 lines, then from 2116 lines to 2604 lines, then from 2606 lines to 2117 lines, then from 2128 lines to 3899 lines, then from 3897 lines to 2137 lines, then from 2148 lines to 2516 lines, then from 2521 lines to 2151 lines, then from 2161 lines to 2404 lines, then from 2409 lines to 2150 lines, then from 2161 lines to 2447 lines, then from 2449 lines to 2162 lines *)
(* coqc version 9.1+alpha compiled with OCaml 4.14.2
   coqtop version runner-t7b1znuaq-project-4504-concurrent-2:/builds/coq/coq/_build/default,(HEAD detached at cdd06d0a2f356e) (cdd06d0a2f356e0c02e2d20356562b7deae4cf15)
   Expected coqc runtime on this file: 1.081 sec *)
Require MetaRocq.Common.config.
Require Stdlib.MSets.MSetList.
Require Stdlib.MSets.MSetAVL.
Require Corelib.Floats.FloatOps.
Require Corelib.Strings.PrimString.
Require MetaRocq.Utils.bytestring.
Require MetaRocq.Utils.MRProd.
Require Equations.Type.Relation_Properties.
Axiom proof_admitted : False.
Tactic Notation "admit" := abstract case proof_admitted.
Import Equations.Type.Relation.
Import Stdlib.Classes.CRelationClasses.
Definition on_rel {A B} (R : A -> A -> Prop) (f : B -> A) : B -> B -> Prop.
Admitted.

Notation on_Trel_eq R f g :=
  (fun x y => (R (f x) (f y) * (g x = g y)))%type.

Global Instance clos_rt_trans A R : Transitive (@clos_refl_trans A R).
Admitted.

Global Instance clos_rt_refl A R : Reflexive (@clos_refl_trans A R).
Admitted.
Export Stdlib.ZArith.BinInt.
Export Stdlib.ZArith.Znat.
Coercion is_true : bool >-> Sortclass.

Notation "'eta_compose'" := (fun g f x => g (f x)).

Notation "g ∘ f" := (eta_compose g f) (at level 40, left associativity).

Notation "'∑' x .. y , p" := (sigT (fun x => .. (sigT (fun y => p%type)) ..))
  (at level 200, x binder, right associativity,
   format "'[' '∑'  '/  ' x  ..  y ,  '/  ' p ']'")
  : type_scope.

Notation "( x ; y )" := (@existT _ _ x y).
Notation "x .π1" := (@projT1 _ _ x) (at level 3, format "x '.π1'").
Notation "x .π2" := (@projT2 _ _ x) (at level 3, format "x '.π2'").
Import Stdlib.Sorting.SetoidList.

Export ListNotations.

Notation "#| l |" := (List.length l) (at level 0, l at level 99, format "#| l |").

Fixpoint mapi_rec {A B} (f : nat -> A -> B) (l : list A) (n : nat) : list B :=
  match l with
  | [] => []
  | hd :: tl => f n hd :: mapi_rec f tl (S n)
  end.

Definition mapi {A B} (f : nat -> A -> B) (l : list A) := mapi_rec f l 0.

Section map2.

  Context {A B C} (f : A -> B -> C).
Fixpoint map2 (l : list A) (l' : list B) : list C.
Admitted.

End map2.

Definition option_default {A B} (f : A -> B) (o : option A) (b : B) :=
  match o with Some x => f x | None => b end.

Fixpoint map_option_out {A} (l : list (option A)) : option (list A) :=
  match l with
  | nil => Some nil
  | hd :: tl => match hd, map_option_out tl with
                | Some hd, Some tl => Some (hd :: tl)
                | _, _ => None
                end
  end.

Inductive All {A} (P : A -> Type) : list A -> Type :=
    All_nil : All P []
  | All_cons : forall (x : A) (l : list A),
                  P x -> All P l -> All P (x :: l).

Inductive All2 {A B : Type} (R : A -> B -> Type) : list A -> list B -> Type :=
  All2_nil : All2 R [] []
| All2_cons : forall (x : A) (y : B) (l : list A) (l' : list B),
    R x y -> All2 R l l' -> All2 R (x :: l) (y :: l').

Inductive All2i {A B : Type} (R : nat -> A -> B -> Type) (n : nat)
  : list A -> list B -> Type :=
| All2i_nil : All2i R n [] []
| All2i_cons :
    forall x y l r,
      R n x y ->
      All2i R (S n) l r ->
      All2i R n (x :: l) (y :: r).

Inductive Forall3 {A B C : Type} (R : A -> B -> C -> Type) : list A -> list B -> list C -> Prop :=
  Forall3_nil : Forall3 R [] [] []
| Forall3_cons : forall (x : A) (y : B) (z : C) (l : list A) (l' : list B) (l'' : list C),
    R x y z -> Forall3 R l l' l'' -> Forall3 R (x :: l) (y :: l') (z :: l'').

Section alli.
  Context {A} (p : nat -> A -> bool).
Fixpoint alli (n : nat) (l : list A) : bool.
Admitted.
End alli.

Inductive OnOne2 {A : Type} (P : A -> A -> Type) : list A -> list A -> Type :=
| OnOne2_hd hd hd' tl : P hd hd' -> OnOne2 P (hd :: tl) (hd' :: tl)
| OnOne2_tl hd tl tl' : OnOne2 P tl tl' -> OnOne2 P (hd :: tl) (hd :: tl').

Inductive All2_fold {A} (P : list A -> list A -> A -> A -> Type)
            : list A -> list A -> Type :=
| All2_fold_nil : All2_fold P nil nil
| All2_fold_cons {d d' Γ Γ'} : All2_fold P Γ Γ' -> P Γ Γ' d d' -> All2_fold P (d :: Γ) (d' :: Γ').

Lemma All2_fold_length {A P} {Γ Γ' : list A} :
  All2_fold P Γ Γ' -> #|Γ| = #|Γ'|.
Admitted.
Export MetaRocq.Utils.MRCompare.
Export MetaRocq.Utils.MRProd.
Export MetaRocq.Utils.ReflectEq.
Export MetaRocq.Utils.bytestring.
Notation "A * B" := (prod A B) : type_scope2.
Global Open Scope type_scope2.

Definition ident   := string.

Definition dirpath := list ident.

Module IdentOT := StringOT.

Module DirPathOT := ListOrderedType IdentOT.

Inductive modpath :=
| MPfile  (dp : dirpath)
| MPbound (dp : dirpath) (id : ident) (i : nat)
| MPdot   (mp : modpath) (id : ident).

Definition kername := modpath × ident.

Module Export ModPathComp.

  Definition mpbound_compare dp id k dp' id' k' :=
    compare_cont (DirPathOT.compare dp dp')
      (compare_cont (IdentOT.compare id id') (Nat.compare k k')).

  Fixpoint compare mp mp' :=
    match mp, mp' with
    | MPfile dp, MPfile dp' => DirPathOT.compare dp dp'
    | MPbound dp id k, MPbound dp' id' k' =>
      mpbound_compare dp id k dp' id' k'
    | MPdot mp id, MPdot mp' id' =>
      compare_cont (compare mp mp') (IdentOT.compare id id')
    | MPfile _, _ => Gt
    | _, MPfile _ => Lt
    | MPbound _ _ _, _ => Gt
    | _, MPbound _ _ _ => Lt
    end.

End ModPathComp.

  Definition compare kn kn' :=
    match kn, kn' with
    | (mp, id), (mp', id') =>
      compare_cont (ModPathComp.compare mp mp') (IdentOT.compare id id')
    end.

  Definition eqb kn kn' :=
    match compare kn kn' with
    | Eq => true
    | _ => false
    end.

Record inductive : Set := mkInd { inductive_mind : kername ;
                                  inductive_ind : nat }.

Record projection := mkProjection
  { proj_ind : inductive;
    proj_npars : nat;
    proj_arg : nat  }.

Inductive global_reference :=
| VarRef : ident -> global_reference
| ConstRef : kername -> global_reference
| IndRef : inductive -> global_reference
| ConstructRef : inductive -> nat -> global_reference.
Module Export BasicAst.
Import Stdlib.ssr.ssreflect.
Import Stdlib.Structures.Orders.
Import Equations.Prop.Equations.

Inductive name : Set :=
| nAnon
| nNamed (_ : ident).

Inductive relevance : Set := Relevant | Irrelevant.

Record binder_annot (A : Type) := mkBindAnn { binder_name : A; binder_relevance : relevance }.
Arguments binder_relevance {_}.
Definition eq_binder_annot {A B} (b : binder_annot A) (b' : binder_annot B) : Prop.
Admitted.

Definition aname := binder_annot name.

Record case_info := mk_case_info {
  ci_ind : inductive;
  ci_npar : nat;

  ci_relevance : relevance }.

Inductive recursivity_kind :=
  | Finite
  | CoFinite
  | BiFinite .

Inductive conv_pb :=
  | Conv
  | Cumul.

Record def term := mkdef {
  dname : aname;
  dtype : term;
  dbody : term;
  rarg  : nat   }.

Arguments dname {term} _.
Arguments dtype {term} _.
Arguments dbody {term} _.
Arguments rarg {term} _.

Definition map_def {A B} (tyf bodyf : A -> B) (d : def A) :=
  {| dname := d.(dname); dtype := tyf d.(dtype); dbody := bodyf d.(dbody); rarg := d.(rarg) |}.

Definition mfixpoint term := list (def term).

Record judgment_ {universe Term} := Judge {
  j_term : option Term;
  j_typ : Term;
  j_univ : option universe;
  j_rel : option relevance;
}.
Arguments judgment_ : clear implicits.
Arguments Judge {universe Term} _ _ _.

Section Contexts.
  Context {term : Type}.

  Record context_decl := mkdecl {
    decl_name : aname ;
    decl_body : option term ;
    decl_type : term
  }.
End Contexts.

Arguments context_decl : clear implicits.
Notation TypRel typ rel := (Judge None typ None (Some rel)).
Notation TermTypRel tm ty rel := (Judge (Some tm) ty None (Some rel)).
Notation TypUnivRel ty u rel := (Judge None ty (Some u) (Some rel)).

Notation j_vass na ty := (TypRel ty na.(binder_relevance)).
Notation j_vass_s na ty s := (TypUnivRel ty s na.(binder_relevance)).
Notation j_vdef na b ty := (TermTypRel b ty na.(binder_relevance)).
Definition map_decl {term term'} (f : term -> term') (d : context_decl term) : context_decl term'.
Admitted.
Definition test_decl {term} (f : term -> bool) (d : context_decl term) : bool.
Admitted.

Definition snoc {A} (Γ : list A) (d : A) := d :: Γ.

Notation " Γ ,, d " := (snoc Γ d) (at level 20, d at next level).

Definition app_context {A} (Γ Γ': list A) := Γ' ++ Γ.

Notation "Γ ,,, Γ'" := (app_context Γ Γ') (at level 25, Γ' at next level, left associativity).

Section Contexts.
  Context {term term' term'' : Type}.

  Definition fold_context_k (f : nat -> term -> term') Γ :=
    List.rev (mapi (fun k' decl => map_decl (f k') decl) (List.rev Γ)).
Definition forget_types (c : list (BasicAst.context_decl term)) : list aname.
admit.
Defined.

End Contexts.
Module Export Universes.
Import MetaRocq.Common.config.

Implicit Types (cf : checker_flags).

Record valuation :=
  { valuation_mono : string -> positive ;
    valuation_poly : nat -> nat }.

Class Evaluable (A : Type) := val : valuation -> A -> nat.

Module Level.
  Inductive t_ : Set :=
  | lzero
  | level (_ : string)
  | lvar (_ : nat) .

  Definition t := t_.
Global Instance Evaluable : Evaluable t.
Admitted.
Definition compare (l1 l2 : t) : comparison.
Admitted.
Definition eq : t -> t -> Prop.
exact (eq).
Defined.
Definition eq_equiv : Equivalence eq.
Admitted.

  Inductive lt_ : t -> t -> Prop :=
  | ltSetLevel s : lt_ lzero (level s)
  | ltSetlvar n : lt_ lzero (lvar n)
  | ltLevelLevel s s' : StringOT.lt s s' -> lt_ (level s) (level s')
  | ltLevellvar s n : lt_ (level s) (lvar n)
  | ltlvarlvar n n' : Nat.lt n n' -> lt_ (lvar n) (lvar n').

  Definition lt := lt_.

  Definition lt_strorder : StrictOrder lt.
Admitted.

  Definition lt_compat : Proper (eq ==> eq ==> iff) lt.
Admitted.

  Definition compare_spec :
    forall x y : t, CompareSpec (x = y) (lt x y) (lt y x) (compare x y).
Admitted.
Definition eq_dec : forall (l1 l2 : t), {l1 = l2}+{l1 <> l2}.
Admitted.

End Level.

Module LevelSet := MSetAVL.Make Level.

Module LevelExpr.
  Definition t := (Level.t * nat)%type.
Definition get_level (e : t) : Level.t.
Admitted.
Definition eq : t -> t -> Prop.
exact (eq).
Defined.
Definition eq_equiv : Equivalence eq.
Admitted.

  Inductive lt_ : t -> t -> Prop :=
  | ltLevelExpr1 l n n' : (n < n')%nat -> lt_ (l, n) (l, n')
  | ltLevelExpr2 l l' b b' : Level.lt l l' -> lt_ (l, b) (l', b').

  Definition lt := lt_.

  Global Instance lt_strorder : StrictOrder lt.
Admitted.

  Definition lt_compat : Proper (Logic.eq ==> Logic.eq ==> iff) lt.
Admitted.
Definition compare (x y : t) : comparison.
Admitted.

  Definition compare_spec :
    forall x y : t, CompareSpec (x = y) (lt x y) (lt y x) (compare x y).
Admitted.
Definition eq_dec : forall (l1 l2 : t), {l1 = l2} + {l1 <> l2}.
Admitted.
Definition eq_leibniz (x y : t) : eq x y -> x = y.
Admitted.

End LevelExpr.

Module LevelExprSet := MSetList.MakeWithLeibniz LevelExpr.

Record nonEmptyLevelExprSet
  := { t_set : LevelExprSet.t ;
       t_ne  : LevelExprSet.is_empty t_set = false }.

Coercion t_set : nonEmptyLevelExprSet >-> LevelExprSet.t.

Module Export Universe.

  Definition t := nonEmptyLevelExprSet.
Definition make' (l: Level.t) : t.
Admitted.
Global Instance Evaluable : Evaluable Universe.t.
Admitted.
Definition lt : t -> t -> Prop.
Admitted.
End Universe.

Module Export ConstraintType.
  Inductive t_ : Set := Le (z : Z) | Eq.

  Definition t := t_.

  Inductive lt_ : t -> t -> Prop :=
  | LeLe n m : (n < m)%Z -> lt_ (Le n) (Le m)
  | LeEq n : lt_ (Le n) Eq.
  Definition lt := lt_.
End ConstraintType.

Module UnivConstraint.
Definition t : Set.
exact (Level.t * ConstraintType.t * Level.t).
Defined.
Definition eq : t -> t -> Prop.
Admitted.
Definition eq_equiv : Equivalence eq.
Admitted.

  Inductive lt_ : t -> t -> Prop :=
  | lt_Level2 l1 t l2 l2' : Level.lt l2 l2' -> lt_ (l1, t, l2) (l1, t, l2')
  | lt_Cstr l1 t t' l2 l2' : ConstraintType.lt t t' -> lt_ (l1, t, l2) (l1, t', l2')
  | lt_Level1 l1 l1' t t' l2 l2' : Level.lt l1 l1' -> lt_ (l1, t, l2) (l1', t', l2').
  Definition lt := lt_.

  Lemma lt_strorder : StrictOrder lt.
Admitted.

  Lemma lt_compat : Proper (eq ==> eq ==> iff) lt.
Admitted.
Definition compare : t -> t -> comparison.
Admitted.

  Lemma compare_spec x y
    : CompareSpec (eq x y) (lt x y) (lt y x) (compare x y).
Admitted.

  Lemma eq_dec x y : {eq x y} + {~ eq x y}.
Admitted.
End UnivConstraint.

Module ConstraintSet := MSetAVL.Make UnivConstraint.

Module Export Instance.
Definition t : Set.
exact (list Level.t).
Defined.
Definition empty : t.
Admitted.
End Instance.

Module Export UContext.
  Definition t := list name × (Instance.t × ConstraintSet.t).
Definition instance : t -> Instance.t.
Admitted.
End UContext.

Module Export AUContext.
  Definition t := list name × ConstraintSet.t.
Definition repr (x : t) : UContext.t.
Admitted.
End AUContext.

Module Export ContextSet.
  Definition t := LevelSet.t × ConstraintSet.t.
End ContextSet.

Module Variance.

  Inductive t :=
  | Irrelevant : t
  | Covariant : t
  | Invariant : t.

End Variance.

Variant opt_variance :=
  AllEqual | AllIrrelevant | Variance of list Variance.t.

Inductive universes_decl : Type :=
| Monomorphic_ctx
| Polymorphic_ctx (cst : AUContext.t).

Inductive satisfies0 (v : valuation) : UnivConstraint.t -> Prop :=
| satisfies0_Lt (l l' : Level.t) (z : Z) : (Z.of_nat (val v l) <= Z.of_nat (val v l') - z)%Z
                        -> satisfies0 v (l, ConstraintType.Le z, l')
| satisfies0_Eq (l l' : Level.t) : val v l = val v l'
                        -> satisfies0 v (l, ConstraintType.Eq, l').

Definition satisfies v : ConstraintSet.t -> Prop :=
  ConstraintSet.For_all (satisfies0 v).

Definition leq0_universe_n n φ (u u' : Universe.t) :=
  forall v, satisfies v φ -> (Z.of_nat (val v u) <= Z.of_nat (val v u') - n)%Z.

Definition leq_universe_n {cf} n φ (u u' : Universe.t) :=
  if check_univs then leq0_universe_n n φ u u' else True.
Definition leq_universe {cf} := leq_universe_n 0.

Definition eq0_universe φ (u u' : Universe.t) :=
  forall v, satisfies v φ -> val v u = val v u'.

Definition eq_universe {cf} φ (u u' : Universe.t) :=
  if check_univs then eq0_universe φ u u' else True.

Definition valid_constraints0 φ ctrs
  := forall v, satisfies v φ -> satisfies v ctrs.

Definition valid_constraints {cf} φ ctrs
  := if check_univs then valid_constraints0 φ ctrs else True.

Definition compare_universe {cf} φ (pb : conv_pb) :=
  match pb with
  | Conv => eq_universe φ
  | Cumul => leq_universe φ
  end.

Module Export Sort.
  Inductive t_ {univ} :=
    sProp | sSProp | sType (_ : univ).
  Arguments t_ : clear implicits.

  Definition t := t_ Universe.t.

  Inductive family : Set :=
  | fSProp
  | fProp
  | fType.

  Definition on_sort {univ} {T} (P: univ -> T) (def: T) (s : t_ univ) :=
    match s with
    | sProp | sSProp => def
    | sType l => P l
    end.
Definition is_sprop {univ} (s : t_ univ) : bool.
Admitted.
Definition is_propositional {univ} (s : t_ univ) : bool.
Admitted.
Definition type0 : t.
Admitted.
Definition super : t -> t.
Admitted.
Definition sort_of_product : t -> t -> t.
Admitted.

  Definition to_family {univ} (s : t_ univ) :=
    match s with
    | sSProp => fSProp
    | sProp => fProp
    | sType _ => fType
    end.

  Inductive lt_ {univ univ_lt} : t_ univ -> t_ univ -> Prop :=
  | ltPropSProp : lt_ sProp sSProp
  | ltPropType s : lt_ sProp (sType s)
  | ltSPropType s : lt_ sSProp (sType s)
  | ltTypeType s1 s2 : univ_lt s1 s2 -> lt_ (sType s1) (sType s2).
  Arguments lt_ {univ} univ_lt.

  Definition lt := lt_ Universe.lt.

  Module OT <: OrderedType.
    Definition t := t.
#[local] Definition eq : t -> t -> Prop.
exact (eq).
Defined.
#[local] Definition eq_equiv : Equivalence eq.
Admitted.
    Definition lt := lt.
    #[local] Instance lt_strorder : StrictOrder lt.
Admitted.

    Definition lt_compat : Proper (eq ==> eq ==> iff) lt.
Admitted.
Definition compare (x y : t) : comparison.
Admitted.
    Lemma compare_spec x y : CompareSpec (eq x y) (lt x y) (lt y x) (compare x y).
Admitted.
    Definition eq_dec (x y : t) : {x = y} + {x <> y}.
Admitted.
  End OT.
End Sort.
Notation sort := Sort.t.

Section SortCompare.
  Context {cf}.
  Definition leq_sort_n_ {univ} (leq_universe_n : Z -> univ -> univ -> Prop) n s s' : Prop :=
    match s, s' with
    | sProp,   sProp
    | sSProp,  sSProp => (n = 0)%Z
    | sType u, sType u' => leq_universe_n n u u'
    | sProp,   sType u => prop_sub_type
    | _, _ => False
    end.

  Definition leq_sort_n n φ := leq_sort_n_ (fun n => leq_universe_n n φ) n.
  Definition leq_sort := leq_sort_n 0.

  Definition eq_sort_ {univ} (eq_universe : univ -> univ -> Prop) s s' : Prop :=
    match s, s' with
    | sProp,   sProp
    | sSProp,  sSProp => True
    | sType u, sType u' => eq_universe u u'
    | _, _ => False
    end.

  Definition eq_sort φ := eq_sort_ (eq_universe φ).

  Definition compare_sort φ (pb : conv_pb) :=
    match pb with
    | Conv => eq_sort φ
    | Cumul => leq_sort φ
    end.
End SortCompare.

Definition relevance_of_family (s : Sort.family) :=
  match s with
  | Sort.fSProp => Irrelevant
  | _ => Relevant
  end.
Notation relevance_of_sort s := (relevance_of_family (Sort.to_family s)).

Notation isSortRel s rel := (relevance_of_sort s = rel).
Notation isSortRelOpt s relopt :=
  (option_default (fun rel => isSortRel s rel) relopt True).

Inductive allowed_eliminations : Set :=
  | IntoSProp
  | IntoPropSProp
  | IntoSetPropSProp
  | IntoAny.

Definition is_lSet {cf} φ s := eq_sort φ s Sort.type0.

Definition is_allowed_elimination {cf} φ allowed : Sort.t -> Prop :=
  match allowed with
  | IntoSProp => Sort.is_sprop
  | IntoPropSProp => Sort.is_propositional
  | IntoSetPropSProp => fun s => Sort.is_propositional s \/ is_lSet φ s
  | IntoAny => fun s => true
  end.

Class UnivSubst A := subst_instance : Instance.t -> A -> A.

Notation "x @[ u ]" := (subst_instance u x) (at level 3,
  format "x @[ u ]").
#[global] Instance subst_instance_cstrs : UnivSubst ConstraintSet.t.
Admitted.

Definition abstract_instance decl :=
  match decl with
  | Monomorphic_ctx => Instance.empty
  | Polymorphic_ctx auctx => UContext.instance (AUContext.repr auctx)
  end.

End Universes.

#[global] Instance reflect_recursivity_kind : ReflectEq recursivity_kind.
Admitted.
Variant prim_tag :=
  | primInt
  | primFloat
  | primString
  | primArray.
Derive NoConfusion EqDec for prim_tag.
Import Stdlib.ssr.ssrbool.

Module Type Term.

  Parameter Inline term : Type.

  Parameter Inline tRel : nat -> term.
  Parameter Inline tSort : Sort.t -> term.
  Parameter Inline tLambda : aname -> term -> term -> term.
  Parameter Inline tLetIn : aname -> term -> term -> term -> term.

  Parameter Inline lift : nat -> nat -> term -> term.
  Parameter Inline subst : list term -> nat -> term -> term.

  Notation lift0 n := (lift n 0).
End Term.

Module Type TermDecide (Import T : Term).
End TermDecide.

Module TermDecideReflectInstances (Import T : Term) (Import TDec : TermDecide T).
End TermDecideReflectInstances.

Module Export Retroknowledge.

  Record t := mk_retroknowledge {
    retro_int63 : option kername;
    retro_float64 : option kername;
    retro_string : option kername;
    retro_array : option kername;
  }.

Module Environment (T : Term).

  Import T.

  Definition judgment := judgment_ Sort.t term.

  Notation context_decl := (context_decl term).

  Definition vass x A : context_decl :=
    {| decl_name := x ; decl_body := None ; decl_type := A |}.

  Definition vdef x t A : context_decl :=
    {| decl_name := x ; decl_body := Some t ; decl_type := A |}.

  Definition context := list context_decl.

  Definition lift_context n k (Γ : context) : context :=
    fold_context_k (fun k' => lift n (k' + k)) Γ.

  Definition subst_context s k (Γ : context) : context :=
    fold_context_k (fun k' => subst s (k' + k)) Γ.

  Definition subst_telescope s k (Γ : context) : context :=
    mapi (fun k' decl => map_decl (subst s (k' + k)) decl) Γ.
Global Instance subst_instance_context : UnivSubst context.
Admitted.
Definition set_binder_name (na : aname) (x : context_decl) : context_decl.
Admitted.
Fixpoint context_assumptions (Γ : context) : nat.
Admitted.
Fixpoint smash_context (Γ Γ' : context) : context.
Admitted.

  Fixpoint extended_subst (Γ : context) (n : nat)
   :=
  match Γ with
  | nil => nil
  | cons d vs =>
    match decl_body d with
    | Some b =>

      let s := extended_subst vs n in

      let b' := lift (context_assumptions vs + n) #|s| b in

      let b' := subst s 0 b' in

      b' :: s
    | None => tRel n :: extended_subst vs (S n)
    end
  end.

  Definition expand_lets_k Γ k t :=
    (subst (extended_subst Γ 0) k (lift (context_assumptions Γ) (k + #|Γ|) t)).

  Definition expand_lets Γ t := expand_lets_k Γ 0 t.

  Definition expand_lets_k_ctx Γ k Δ :=
    (subst_context (extended_subst Γ 0) k (lift_context (context_assumptions Γ) (k + #|Γ|) Δ)).

  Definition expand_lets_ctx Γ Δ := expand_lets_k_ctx Γ 0 Δ.
Definition fix_context (m : mfixpoint term) : context.
Admitted.

  Record constructor_body := {

    cstr_name : ident;

    cstr_args : context;

    cstr_indices : list term;

    cstr_type : term;

    cstr_arity : nat;
  }.

  Record projection_body := {

    proj_name : ident;

    proj_relevance : relevance;

    proj_type : term;
  }.

  Record one_inductive_body := {

    ind_name : ident;

    ind_indices : context;

    ind_sort : Sort.t;

    ind_type : term;

    ind_kelim : allowed_eliminations;

    ind_ctors : list constructor_body;

    ind_projs : list projection_body;

    ind_relevance : relevance }.

  Record mutual_inductive_body := {

    ind_finite : recursivity_kind;

    ind_npars : nat;

    ind_params : context;

    ind_bodies : list one_inductive_body ;

    ind_universes : universes_decl;

    ind_variance : option (list Universes.Variance.t) }.

  Record constant_body := {

    cst_type : term;

    cst_body : option term;

    cst_universes : universes_decl;

    cst_relevance : relevance }.

  Inductive global_decl :=
  | ConstantDecl : constant_body -> global_decl
  | InductiveDecl : mutual_inductive_body -> global_decl.

  Definition global_declarations := list (kername * global_decl).

  Record global_env := mk_global_env
    { universes : ContextSet.t;
      declarations : global_declarations;
      retroknowledge : Retroknowledge.t }.
Fixpoint lookup_global (Σ : global_declarations) (kn : kername) : option global_decl.
Admitted.

  Definition lookup_env (Σ : global_env) (kn : kername) := lookup_global Σ.(declarations) kn.
Definition primitive_constant (Σ : global_env) (p : prim_tag) : option kername.
Admitted.
Definition tImpl (dom codom : term) : term.
Admitted.

  Definition array_uctx := ([nAnon], ConstraintSet.empty).

  Definition primitive_invariants (p : prim_tag) (cdecl : constant_body) :=
    match p with
    | primInt | primFloat | primString =>
     [/\ cdecl.(cst_type) = tSort Sort.type0, cdecl.(cst_body) = None &
          cdecl.(cst_universes) = Monomorphic_ctx]
    | primArray =>
      let s := sType (Universe.make' (Level.lvar 0)) in
      [/\ cdecl.(cst_type) = tImpl (tSort s) (tSort s), cdecl.(cst_body) = None &
        cdecl.(cst_universes) = Polymorphic_ctx array_uctx]
    end.
Definition global_env_ext : Type.
Admitted.
Definition fst_ctx : global_env_ext -> global_env.
Admitted.
  Coercion fst_ctx : global_env_ext >-> global_env.

  Definition mkLambda_or_LetIn d t :=
    match d.(decl_body) with
    | None => tLambda d.(decl_name) d.(decl_type) t
    | Some b => tLetIn d.(decl_name) b d.(decl_type) t
    end.

  Definition it_mkLambda_or_LetIn (l : context) (t : term) :=
    List.fold_left (fun acc d => mkLambda_or_LetIn d acc) l t.
Fixpoint reln (l : list term) (p : nat) (Γ0 : list context_decl) {struct Γ0} : list term.
Admitted.

  Definition to_extended_list_k Γ k := reln [] k Γ.
  Definition to_extended_list Γ := to_extended_list_k Γ 0.

  Inductive All_decls_alpha (P : term -> term -> Type) : context_decl -> context_decl -> Type :=
  | on_vass_alpha na na' t t' :
    eq_binder_annot na na' ->
    P t t' ->
    All_decls_alpha P (vass na t) (vass na' t')

  | on_vdef_alpha na na' b t b' t' :
    eq_binder_annot na na' ->
    P b b' ->
    P t t' ->
    All_decls_alpha P (vdef na b t) (vdef na' b' t').

End Environment.

Module Type EnvironmentSig (T : Term).
 Include Environment T.
End EnvironmentSig.

Module Type EnvironmentDecide (T : Term) (Import E : EnvironmentSig T).
End EnvironmentDecide.

Module EnvironmentDecideReflectInstances (T : Term) (Import E : EnvironmentSig T) (Import EDec : EnvironmentDecide T E).
End EnvironmentDecideReflectInstances.

Module Type TermUtils (T: Term) (E: EnvironmentSig T).

End TermUtils.
Module Export EnvironmentTyping.
Import MetaRocq.Common.config.

Module Lookup (T : Term) (E : EnvironmentSig T).
Import E.

  Definition declared_constant (Σ : global_env) id decl := In (id,ConstantDecl decl) (declarations Σ).

  Definition declared_minductive Σ mind decl := In (mind,InductiveDecl decl) (declarations Σ).

  Definition declared_inductive Σ ind mdecl decl :=
    declared_minductive Σ (inductive_mind ind) mdecl /\
    List.nth_error mdecl.(ind_bodies) (inductive_ind ind) = Some decl.

  Definition declared_constructor Σ cstr mdecl idecl cdecl :=
    declared_inductive Σ (fst cstr) mdecl idecl /\
    List.nth_error idecl.(ind_ctors) (snd cstr) = Some cdecl.

  Definition declared_projection Σ (proj : projection) mdecl idecl cdecl pdecl
  : Prop :=
    declared_constructor Σ (proj.(proj_ind), 0) mdecl idecl cdecl /\
    List.nth_error idecl.(ind_projs) proj.(proj_arg) = Some pdecl /\
    mdecl.(ind_npars) = proj.(proj_npars).

  Definition lookup_minductive_gen (lookup : kername -> option global_decl) mind :=
    match lookup mind with
    | Some (InductiveDecl decl) => Some decl
    | _ => None
    end.

  Definition lookup_inductive_gen lookup ind :=
    match lookup_minductive_gen lookup (inductive_mind ind) with
    | Some mdecl =>
      match nth_error mdecl.(ind_bodies) (inductive_ind ind) with
      | Some idecl => Some (mdecl, idecl)
      | None => None
      end
    | None => None
    end.

  Definition lookup_constructor_gen lookup ind k :=
    match lookup_inductive_gen lookup ind with
    | Some (mdecl, idecl) =>
      match nth_error idecl.(ind_ctors) k with
      | Some cdecl => Some (mdecl, idecl, cdecl)
      | None => None
      end
    | _ => None
    end.
Definition global_ext_levels (Σ : global_env_ext) : LevelSet.t.
Admitted.
Definition global_ext_constraints (Σ : global_env_ext) : ConstraintSet.t.
Admitted.

  Coercion global_ext_constraints : global_env_ext >-> ConstraintSet.t.

  Definition consistent_instance `{checker_flags} (lvs : LevelSet.t) (φ : ConstraintSet.t) uctx (u : Instance.t) :=
    match uctx with
    | Monomorphic_ctx => List.length u = 0
    | Polymorphic_ctx c =>

      forallb (fun l => LevelSet.mem l lvs) u /\
      List.length u = List.length c.1 /\
      valid_constraints φ (subst_instance_cstrs u c.2)
    end.

  Definition consistent_instance_ext `{checker_flags} Σ :=
    consistent_instance (global_ext_levels Σ) (global_ext_constraints Σ).

  Definition wf_universe Σ (u : Universe.t) : Prop :=
    forall l, LevelExprSet.In l u -> LevelSet.In (LevelExpr.get_level l) (global_ext_levels Σ).

  Definition wf_sort Σ (s : sort) : Prop :=
    Sort.on_sort (wf_universe Σ) True s.

End Lookup.

Module Type LookupSig (T : Term) (E : EnvironmentSig T).
End LookupSig.

Module EnvTyping (T : Term) (E : EnvironmentSig T) (TU : TermUtils T E).
Import T.
Import E.

  Definition on_def_type (P : context -> judgment -> Type) Γ d :=
    P Γ (TypRel d.(dtype) d.(dname).(binder_relevance)).

  Definition on_def_body (P : context -> judgment -> Type) types Γ d :=
    P (Γ ,,, types) (TermTypRel d.(dbody) (lift0 #|types| d.(dtype)) d.(dname).(binder_relevance)).

  Definition lift_sorting checking sorting : judgment -> Type :=
    fun j => option_default (fun tm => checking tm (j_typ j)) (j_term j) (unit : Type) ×
                                ∑ s, sorting (j_typ j) s ×
                                  option_default (fun u => u = s) (j_univ j) True /\
                                  isSortRelOpt s (j_rel j).

  Notation typing_sort typing := (fun T s => typing T (tSort s)).

  Definition lift_typing0 typing := lift_sorting typing (typing_sort typing).
  Notation lift_typing1 typing := (fun Γ => lift_typing0 (typing Γ)).
  Notation lift_typing typing := (fun Σ Γ => lift_typing0 (typing Σ Γ)).

  Section TypeLocal.
    Context (typing : forall (Γ : context), judgment -> Type).

    Inductive All_local_env : context -> Type :=
    | localenv_nil :
        All_local_env []

    | localenv_cons_abs Γ na t :
        All_local_env Γ ->
        typing Γ (j_vass na t) ->
        All_local_env (Γ ,, vass na t)

    | localenv_cons_def Γ na b t :
        All_local_env Γ ->
        typing Γ (j_vdef na b t) ->
        All_local_env (Γ ,, vdef na b t).
  End TypeLocal.

  Section TypeCtxInst.
    Context (typing : forall (Γ : context), term -> term -> Type).

    Inductive ctx_inst (Γ : context) : list term -> context -> Type :=
    | ctx_inst_nil : ctx_inst Γ [] []
    | ctx_inst_ass na t i inst Δ :
        typing Γ i t ->
        ctx_inst Γ inst (subst_telescope [i] 0 Δ) ->
        ctx_inst Γ (i :: inst) (vass na t :: Δ)
    | ctx_inst_def na b t inst Δ :
        ctx_inst Γ inst (subst_telescope [b] 0 Δ) ->
        ctx_inst Γ inst (vdef na b t :: Δ).
  End TypeCtxInst.

End EnvTyping.

Module Type EnvTypingSig (T : Term) (E : EnvironmentS

[...]

extended_list (smash_context [] mdecl.(ind_params) ,,, ictx)) in
  let inddecl :=
    {| decl_name :=
      {| binder_name := nNamed (ind_name idecl); binder_relevance := idecl.(ind_relevance) |};
       decl_body := None;
       decl_type := indty |}
  in (inddecl :: ictx).

Definition inst_case_context params puinst (pctx : context) :=
  subst_context (List.rev params) 0 (subst_instance puinst pctx).

Definition inst_case_predicate_context (p : predicate term) :=
  inst_case_context p.(pparams) p.(puinst) p.(pcontext).

Definition inst_case_branch_context (p : predicate term) (br : branch term) :=
  inst_case_context p.(pparams) p.(puinst) br.(bcontext).

Definition iota_red npar p args br :=
  subst (List.rev (List.skipn npar args)) 0
    (expand_lets (inst_case_branch_context p br) (bbody br)).

Definition pre_case_predicate_context_gen ind mdecl idecl params puinst : context :=
  inst_case_context params puinst (ind_predicate_context ind mdecl idecl).

Definition case_predicate_context_gen ind mdecl idecl params puinst pctx :=
  map2 set_binder_name pctx (pre_case_predicate_context_gen ind mdecl idecl params puinst).

Definition case_predicate_context ind mdecl idecl p : context :=
  case_predicate_context_gen ind mdecl idecl p.(pparams) p.(puinst) (forget_types p.(pcontext)).

Definition cstr_branch_context ind mdecl cdecl : context :=
  expand_lets_ctx mdecl.(ind_params)
    (subst_context (inds (inductive_mind ind) (abstract_instance mdecl.(ind_universes))
       mdecl.(ind_bodies)) #|mdecl.(ind_params)|
      cdecl.(cstr_args)).

Definition pre_case_branch_context_gen ind mdecl cdecl params puinst : context :=
  inst_case_context params puinst (cstr_branch_context ind mdecl cdecl).

Definition case_branch_context_gen ind mdecl params puinst pctx cdecl :=
  map2 set_binder_name pctx (pre_case_branch_context_gen ind mdecl cdecl params puinst).

Definition case_branch_type_gen ind mdecl (idecl : one_inductive_body) params puinst bctx ptm i cdecl : context * term :=
  let cstr := tConstruct ind i puinst in
  let args := to_extended_list cdecl.(cstr_args) in
  let cstrapp := mkApps cstr (map (lift0 #|cdecl.(cstr_args)|) params ++ args) in
  let brctx := case_branch_context_gen ind mdecl params puinst bctx cdecl in
  let upars := subst_instance puinst mdecl.(ind_params) in
  let indices :=
    (map (subst (List.rev params) #|cdecl.(cstr_args)|)
      (map (expand_lets_k upars #|cdecl.(cstr_args)|)
        (map (subst (inds (inductive_mind ind) puinst mdecl.(ind_bodies))
                    (#|mdecl.(ind_params)| + #|cdecl.(cstr_args)|))
          (map (subst_instance puinst) cdecl.(cstr_indices))))) in
  let ty := mkApps (lift0 #|cdecl.(cstr_args)| ptm) (indices ++ [cstrapp]) in
  (brctx, ty).

Definition case_branch_type ind mdecl idecl p (b : branch term) ptm i cdecl : context * term :=
  case_branch_type_gen ind mdecl idecl p.(pparams) p.(puinst) (forget_types b.(bcontext)) ptm i cdecl.

Definition idecl_binder idecl :=
  {| decl_name :=
    {| binder_name := nNamed idecl.(ind_name);
        binder_relevance := idecl.(ind_relevance) |};
     decl_body := None;
     decl_type := idecl.(ind_type) |}.

Definition wf_predicate_gen mdecl idecl (pparams : list term) (pcontext : list aname) : Prop :=
  let decl := idecl_binder idecl in
  (#|pparams| = mdecl.(ind_npars)) /\
  (Forall2 (fun na decl => eq_binder_annot na decl.(decl_name))
    pcontext (decl :: idecl.(ind_indices))).

Definition wf_predicate mdecl idecl (p : predicate term) : Prop :=
  wf_predicate_gen mdecl idecl p.(pparams) (forget_types p.(pcontext)).

Definition wf_branch_gen cdecl (bctx : list aname) : Prop :=
  (Forall2 (fun na decl => eq_binder_annot na decl.(decl_name))
    bctx cdecl.(cstr_args)).

Definition wf_branch cdecl (b : branch term) : Prop :=
  wf_branch_gen cdecl (forget_types b.(bcontext)).

Definition wf_branches idecl (brs : list (branch term)) : Prop :=
  Forall2 wf_branch idecl.(ind_ctors) brs.

Definition fix_subst (l : mfixpoint term) :=
  let fix aux n :=
      match n with
      | 0 => []
      | S n => tFix l n :: aux n
      end
  in aux (List.length l).

Definition unfold_fix (mfix : mfixpoint term) (idx : nat) :=
  match List.nth_error mfix idx with
  | Some d => Some (d.(rarg), subst0 (fix_subst mfix) d.(dbody))
  | None => None
  end.

Definition cofix_subst (l : mfixpoint term) :=
  let fix aux n :=
      match n with
      | 0 => []
      | S n => tCoFix l n :: aux n
      end
  in aux (List.length l).

Definition unfold_cofix (mfix : mfixpoint term) (idx : nat) :=
  match List.nth_error mfix idx with
  | Some d => Some (d.(rarg), subst0 (cofix_subst mfix) d.(dbody))
  | None => None
  end.

Definition is_constructor n ts :=
  match List.nth_error ts n with
  | Some a => isConstruct_app a
  | None => false
  end.
Definition cmp_universe_instance (cmp_univ : Universe.t -> Universe.t -> Prop) : Instance.t -> Instance.t -> Prop.
Admitted.

Definition cmp_universe_variance (cmp_univ : conv_pb -> Universe.t -> Universe.t -> Prop) pb v u u' :=
  match v with
  | Variance.Irrelevant => True
  | Variance.Covariant => on_rel (cmp_univ pb) Universe.make' u u'
  | Variance.Invariant => on_rel (cmp_univ Conv) Universe.make' u u'
  end.

Definition cmp_universe_instance_variance cmp_univ pb v u u' :=
  Forall3 (cmp_universe_variance cmp_univ pb) v u u'.

Definition global_variance_gen lookup gr napp :=
  match gr with
  | IndRef ind =>
    match lookup_inductive_gen lookup ind with
    | Some (mdecl, idecl) =>
      match destArity [] idecl.(ind_type) with
      | Some (ctx, _) => if (context_assumptions ctx) <=? napp then
          match mdecl.(ind_variance) with
          | Some var => Variance var
          | None => AllEqual
          end
        else AllEqual
      | None => AllEqual
      end
    | None => AllEqual
    end
  | ConstructRef ind k =>
    match lookup_constructor_gen lookup ind k with
    | Some (mdecl, idecl, cdecl) =>
      if (cdecl.(cstr_arity) + mdecl.(ind_npars))%nat <=? napp then

        AllIrrelevant
      else AllEqual
    | _ => AllEqual
    end
  | _ => AllEqual
  end.

Definition cmp_opt_variance cmp_univ pb v :=
  match v with
  | AllEqual => cmp_universe_instance (cmp_univ Conv)
  | AllIrrelevant => fun l l' => #|l| = #|l'|
  | Variance v => fun u u' => cmp_universe_instance (cmp_univ Conv) u u' \/ cmp_universe_instance_variance cmp_univ pb v u u'
  end.

Definition cmp_global_instance_gen Σ cmp_universe pb gr napp :=
  cmp_opt_variance cmp_universe pb (global_variance_gen Σ gr napp).

Notation cmp_global_instance Σ := (cmp_global_instance_gen (lookup_env Σ)).

Inductive eq_decl_upto_names : context_decl -> context_decl -> Type :=
  | compare_vass {na na' T} :
    eq_binder_annot na na' -> eq_decl_upto_names (vass na T) (vass na' T)
  | compare_vdef {na na' b T} :
    eq_binder_annot na na' -> eq_decl_upto_names (vdef na b T) (vdef na' b T).

Notation eq_context_upto_names := (All2 eq_decl_upto_names).

Definition shiftnP k p i :=
  (i <? k) || p (i - k).
Fixpoint on_free_vars (p : nat -> bool) (t : term) : bool.
Admitted.

Definition on_free_vars_decl P d :=
  test_decl (on_free_vars P) d.

Definition on_free_vars_ctx P ctx :=
  alli (fun k => (on_free_vars_decl (shiftnP k P))) 0 (List.rev ctx).

Notation is_open_term Γ := (on_free_vars (shiftnP #|Γ| xpred0)).
Notation is_closed_context := (on_free_vars_ctx xpred0).
Definition set_preturn (p : predicate term) (pret' : term) : predicate term.
Admitted.
Definition set_pparams (p : predicate term) (pars' : list term) : predicate term.
Admitted.
Definition on_one_decl (P : term -> term -> Type)
  (d : context_decl) (d' : context_decl) : Type.
Admitted.

Section OnOne_local_2.
  Context (P : forall (Γ : context), context_decl -> context_decl -> Type).

  Inductive OnOne2_local_env : context -> context -> Type :=
  | onone2_localenv_cons_abs Γ na na' t t' :
      P Γ (vass na t) (vass na' t') ->
      OnOne2_local_env (Γ ,, vass na t) (Γ ,, vass na' t')
  | onone2_localenv_def Γ na na' b b' t t' :
      P Γ (vdef na b t) (vdef na' b' t') ->
      OnOne2_local_env (Γ ,, vdef na b t) (Γ ,, vdef na' b' t')
  | onone2_localenv_cons_tl Γ Γ' d :
      OnOne2_local_env Γ Γ' ->
      OnOne2_local_env (Γ ,, d) (Γ' ,, d).
End OnOne_local_2.
Arguments exist {_ _} _ _.
Import Equations.Type.Relation.

Reserved Notation " Σ ;;; Γ |- t ⇝ u " (at level 50, Γ, t, u at next level).

Definition set_array_default (ar : array_model term) (v : term) :=
  {| array_level := ar.(array_level);
     array_default := v;
     array_type := ar.(array_type);
     array_value := ar.(array_value) |}.

Definition set_array_type (ar : array_model term) (v : term) :=
  {| array_level := ar.(array_level);
     array_default := ar.(array_default);
     array_type := v;
     array_value := ar.(array_value) |}.

Definition set_array_value (ar : array_model term) (v : list term) :=
  {| array_level := ar.(array_level);
     array_default := ar.(array_default);
     array_type := ar.(array_type);
     array_value := v |}.

Inductive red1 (Σ : global_env) (Γ : context) : term -> term -> Type :=

| red_beta na t b a :
  Σ ;;; Γ |- tApp (tLambda na t b) a ⇝ b {0 := a}

| red_zeta na b t b' :
  Σ ;;; Γ |- tLetIn na b t b' ⇝ b' {0 := b}

| red_rel i body :
    option_map decl_body (nth_error Γ i) = Some (Some body) ->
    Σ ;;; Γ |- tRel i ⇝ lift0 (S i) body

| red_iota ci c u args p brs br :
    nth_error brs c = Some br ->
    #|args| = (ci.(ci_npar) + context_assumptions br.(bcontext))%nat ->
    Σ ;;; Γ |- tCase ci p (mkApps (tConstruct ci.(ci_ind) c u) args) brs
        ⇝ iota_red ci.(ci_npar) p args br

| red_fix mfix idx args narg fn :
    unfold_fix mfix idx = Some (narg, fn) ->
    is_constructor narg args = true ->
    Σ ;;; Γ |- mkApps (tFix mfix idx) args ⇝ mkApps fn args

| red_cofix_case ip p mfix idx args narg fn brs :
    unfold_cofix mfix idx = Some (narg, fn) ->
    Σ ;;; Γ |- tCase ip p (mkApps (tCoFix mfix idx) args) brs ⇝
         tCase ip p (mkApps fn args) brs

| red_cofix_proj p mfix idx args narg fn :
    unfold_cofix mfix idx = Some (narg, fn) ->
    Σ ;;; Γ |- tProj p (mkApps (tCoFix mfix idx) args) ⇝ tProj p (mkApps fn args)

| red_delta c decl body (isdecl : declared_constant Σ c decl) u :
    decl.(cst_body) = Some body ->
    Σ ;;; Γ |- tConst c u ⇝ subst_instance u body

| red_proj p args u arg:
    nth_error args (p.(proj_npars) + p.(proj_arg)) = Some arg ->
    Σ ;;; Γ |- tProj p (mkApps (tConstruct p.(proj_ind) 0 u) args) ⇝ arg

| abs_red_l na M M' N : Σ ;;; Γ |- M ⇝ M' -> Σ ;;; Γ |- tLambda na M N ⇝ tLambda na M' N
| abs_red_r na M M' N : Σ ;;; Γ ,, vass na N |- M ⇝ M' -> Σ ;;; Γ |- tLambda na N M ⇝ tLambda na N M'

| letin_red_def na b t b' r : Σ ;;; Γ |- b ⇝ r -> Σ ;;; Γ |- tLetIn na b t b' ⇝ tLetIn na r t b'
| letin_red_ty na b t b' r : Σ ;;; Γ |- t ⇝ r -> Σ ;;; Γ |- tLetIn na b t b' ⇝ tLetIn na b r b'
| letin_red_body na b t b' r : Σ ;;; Γ ,, vdef na b t |- b' ⇝ r -> Σ ;;; Γ |- tLetIn na b t b' ⇝ tLetIn na b t r

| case_red_param ci p params' c brs :
    OnOne2 (fun t u => Σ ;;; Γ |- t ⇝ u) p.(pparams) params' ->
    Σ ;;; Γ |- tCase ci p c brs ⇝ tCase ci (set_pparams p params') c brs

| case_red_return ci p preturn' c brs :
  Σ ;;; Γ ,,, inst_case_predicate_context p |- p.(preturn) ⇝ preturn' ->
  Σ ;;; Γ |- tCase ci p c brs ⇝ tCase ci (set_preturn p preturn') c brs

| case_red_discr ci p c c' brs :
  Σ ;;; Γ |- c ⇝ c' -> Σ ;;; Γ |- tCase ci p c brs ⇝ tCase ci p c' brs

| case_red_brs ci p c brs brs' :
    OnOne2 (fun br br' =>
      on_Trel_eq (fun t u => Σ ;;; Γ ,,, inst_case_branch_context p br |- t ⇝ u) bbody bcontext br br')
      brs brs' ->
    Σ ;;; Γ |- tCase ci p c brs ⇝ tCase ci p c brs'

| proj_red p c c' : Σ ;;; Γ |- c ⇝ c' -> Σ ;;; Γ |- tProj p c ⇝ tProj p c'

| app_red_l M1 N1 M2 : Σ ;;; Γ |- M1 ⇝ N1 -> Σ ;;; Γ |- tApp M1 M2 ⇝ tApp N1 M2
| app_red_r M2 N2 M1 : Σ ;;; Γ |- M2 ⇝ N2 -> Σ ;;; Γ |- tApp M1 M2 ⇝ tApp M1 N2

| prod_red_l na M1 M2 N1 : Σ ;;; Γ |- M1 ⇝ N1 -> Σ ;;; Γ |- tProd na M1 M2 ⇝ tProd na N1 M2
| prod_red_r na M2 N2 M1 : Σ ;;; Γ ,, vass na M1 |- M2 ⇝ N2 ->
                           Σ ;;; Γ |- tProd na M1 M2 ⇝ tProd na M1 N2

| evar_red ev l l' : OnOne2 (fun t u => Σ ;;; Γ |- t ⇝ u) l l' -> Σ ;;; Γ |- tEvar ev l ⇝ tEvar ev l'

| fix_red_ty mfix0 mfix1 idx :
    OnOne2 (on_Trel_eq (fun t u => Σ ;;; Γ |- t ⇝ u) dtype (fun x => (dname x, dbody x, rarg x))) mfix0 mfix1 ->
    Σ ;;; Γ |- tFix mfix0 idx ⇝ tFix mfix1 idx

| fix_red_body mfix0 mfix1 idx :
    OnOne2 (on_Trel_eq (fun t u => Σ ;;; Γ ,,, fix_context mfix0 |- t ⇝ u) dbody (fun x => (dname x, dtype x, rarg x)))
           mfix0 mfix1 ->
    Σ ;;; Γ |- tFix mfix0 idx ⇝ tFix mfix1 idx

| cofix_red_ty mfix0 mfix1 idx :
    OnOne2 (on_Trel_eq (fun t u => Σ ;;; Γ |- t ⇝ u) dtype (fun x => (dname x, dbody x, rarg x))) mfix0 mfix1 ->
    Σ ;;; Γ |- tCoFix mfix0 idx ⇝ tCoFix mfix1 idx

| cofix_red_body mfix0 mfix1 idx :
    OnOne2 (on_Trel_eq (fun t u => Σ ;;; Γ ,,, fix_context mfix0 |- t ⇝ u) dbody (fun x => (dname x, dtype x, rarg x))) mfix0 mfix1 ->
    Σ ;;; Γ |- tCoFix mfix0 idx ⇝ tCoFix mfix1 idx

| array_red_val arr value :
    OnOne2 (fun t u => Σ ;;; Γ |- t ⇝ u) arr.(array_value) value ->
    Σ ;;; Γ |- tPrim (primArray; primArrayModel arr) ⇝
               tPrim (primArray; primArrayModel (set_array_value arr value))

| array_red_def arr def :
    Σ ;;; Γ |- arr.(array_default) ⇝ def ->
    Σ ;;; Γ |- tPrim (primArray; primArrayModel arr) ⇝
               tPrim (primArray; primArrayModel (set_array_default arr def))

| array_red_type arr ty :
    Σ ;;; Γ |- arr.(array_type) ⇝ ty ->
    Σ ;;; Γ |- tPrim (primArray; primArrayModel arr) ⇝
          tPrim (primArray; primArrayModel (set_array_type arr ty))

where " Σ ;;; Γ |- t ⇝ u " := (red1 Σ Γ t u).

Definition red1_ctx Σ := (OnOne2_local_env (fun Δ => on_one_decl (fun t t' => red1 Σ Δ t t'))).

Definition red Σ Γ := clos_refl_trans (fun t u : term => Σ;;; Γ |- t ⇝ u).
Module Export PCUICCumulativitySpec.

Implicit Types (cf : checker_flags).

Definition cumul_predicate (cumul : context -> term -> term -> Type) cumul_universe Γ p p' :=
  All2 (cumul Γ) p.(pparams) p'.(pparams) ×
  cmp_universe_instance cumul_universe p.(puinst) p'.(puinst) ×
  eq_context_upto_names p.(pcontext) p'.(pcontext) ×
  cumul (Γ ,,, inst_case_predicate_context p) p.(preturn) p'.(preturn).

Definition cumul_branch (cumul_term : context -> term -> term -> Type) Γ p br br' :=
  eq_context_upto_names br.(bcontext) br'.(bcontext) ×
  cumul_term (Γ ,,, inst_case_branch_context p br) br.(bbody) br'.(bbody).

Definition cumul_branches cumul_term Γ p brs brs' := All2 (cumul_branch cumul_term Γ p) brs brs'.

Definition cumul_mfixpoint (cumul_term : context -> term -> term -> Type) Γ mfix mfix' :=
  All2 (fun d d' =>
    cumul_term Γ d.(dtype) d'.(dtype) ×
    cumul_term (Γ ,,, fix_context mfix) d.(dbody) d'.(dbody) ×
    d.(rarg) = d'.(rarg) ×
    eq_binder_annot d.(dname) d'.(dname)
  ) mfix mfix'.

Reserved Notation " Σ ;;; Γ ⊢ t ≤s[ pb ] u" (at level 50, Γ, t, u at next level,
  format "Σ  ;;;  Γ  ⊢  t  ≤s[ pb ]  u").

Definition cumul_Ind_univ {cf} (Σ : global_env_ext) pb i napp :=
  cmp_global_instance Σ (compare_universe Σ) pb (IndRef i) napp.

Definition cumul_Construct_univ {cf} (Σ : global_env_ext) pb  i k napp :=
  cmp_global_instance Σ (compare_universe Σ) pb (ConstructRef i k) napp.
Inductive cumulSpec0 {cf : checker_flags} (Σ : global_env_ext) Γ (pb : conv_pb) : term -> term -> Type :=

| cumul_Trans : forall t u v,
    is_closed_context Γ -> is_open_term Γ u ->
    Σ ;;; Γ ⊢ t ≤s[pb] u ->
    Σ ;;; Γ ⊢ u ≤s[pb] v ->
    Σ ;;; Γ ⊢ t ≤s[pb] v

| cumul_Sym : forall t u,
    Σ ;;; Γ ⊢ t ≤s[Conv] u ->
    Σ ;;; Γ ⊢ u ≤s[pb] t

| cumul_Refl : forall t,
    Σ ;;; Γ ⊢ t ≤s[pb] t

| cumul_Ind : forall i u u' args args',
    cumul_Ind_univ Σ pb i #|args| u u' ->
    All2 (fun t u => Σ ;;; Γ ⊢ t ≤s[Conv] u) args args' ->
    Σ ;;; Γ ⊢ mkApps (tInd i u) args ≤s[pb] mkApps (tInd i u') args'

| cumul_Construct : forall i k u u' args args',
    cumul_Construct_univ Σ pb i k #|args| u u' ->
    All2 (fun t u => Σ ;;; Γ ⊢ t ≤s[Conv] u) args args' ->
    Σ ;;; Γ ⊢ mkApps (tConstruct i k u) args ≤s[pb] mkApps (tConstruct i k u') args'

| cumul_Sort : forall s s',
    compare_sort Σ pb s s' ->
    Σ ;;; Γ ⊢ tSort s ≤s[pb] tSort s'

| cumul_Const : forall c u u',
    cmp_universe_instance (compare_universe Σ Conv) u u' ->
    Σ ;;; Γ ⊢ tConst c u ≤s[pb] tConst c u'

| cumul_Evar : forall e args args',
    All2 (fun t u => Σ ;;; Γ ⊢ t ≤s[Conv] u) args args' ->
    Σ ;;; Γ ⊢ tEvar e args ≤s[pb] tEvar e args'

| cumul_App : forall t t' u u',
    Σ ;;; Γ ⊢ t ≤s[pb] t' ->
    Σ ;;; Γ ⊢ u ≤s[Conv] u' ->
    Σ ;;; Γ ⊢ tApp t u ≤s[pb] tApp t' u'

| cumul_Lambda : forall na na' ty ty' t t',
    eq_binder_annot na na' ->
    Σ ;;; Γ ⊢ ty ≤s[Conv] ty' ->
    Σ ;;; Γ ,, vass na ty ⊢ t ≤s[Conv] t' ->
    Σ ;;; Γ ⊢ tLambda na ty t ≤s[pb] tLambda na' ty' t'

| cumul_Prod : forall na na' a a' b b',
    eq_binder_annot na na' ->
    Σ ;;; Γ ⊢ a ≤s[Conv] a' ->
    Σ ;;; Γ ,, vass na a ⊢ b ≤s[pb] b' ->
    Σ ;;; Γ ⊢ tProd na a b ≤s[pb] tProd na' a' b'

| cumul_LetIn : forall na na' t t' ty ty' u u',
    eq_binder_annot na na' ->
    Σ ;;; Γ ⊢ t ≤s[Conv] t' ->
    Σ ;;; Γ ⊢ ty ≤s[Conv] ty' ->
    Σ ;;; Γ ,, vdef na t ty ⊢ u ≤s[Conv] u' ->
    Σ ;;; Γ ⊢ tLetIn na t ty u ≤s[pb] tLetIn na' t' ty' u'

| cumul_Case indn : forall p p' c c' brs brs',
    cumul_predicate (fun Γ t u => Σ ;;; Γ ⊢ t ≤s[Conv] u) (compare_universe Σ Conv) Γ p p' ->
    Σ ;;; Γ ⊢ c ≤s[Conv] c' ->
    cumul_branches (fun Γ t u => Σ ;;; Γ ⊢ t ≤s[Conv] u) Γ p brs brs' ->
    Σ ;;; Γ ⊢ tCase indn p c brs ≤s[pb] tCase indn p' c' brs'

| cumul_Proj : forall p c c',
    Σ ;;; Γ ⊢ c ≤s[Conv] c' ->
    Σ ;;; Γ ⊢ tProj p c ≤s[pb] tProj p c'

| cumul_Fix : forall mfix mfix' idx,
    cumul_mfixpoint (fun Γ t u => Σ ;;; Γ ⊢ t ≤s[Conv] u) Γ mfix mfix' ->
    Σ ;;; Γ ⊢ tFix mfix idx ≤s[pb] tFix mfix' idx

| cumul_CoFix : forall mfix mfix' idx,
    cumul_mfixpoint (fun Γ t u => Σ ;;; Γ ⊢ t ≤s[Conv] u) Γ mfix mfix' ->
    Σ ;;; Γ ⊢ tCoFix mfix idx ≤s[pb] tCoFix mfix' idx

| cumul_Prim p p' :
  onPrims (fun x y => Σ ;;; Γ ⊢ x ≤s[Conv] y) (compare_universe Σ Conv) p p' ->
  Σ ;;; Γ ⊢ tPrim p ≤s[pb] tPrim p'

| cumul_beta : forall na t b a,
    Σ ;;; Γ ⊢ tApp (tLambda na t b) a ≤s[pb] b {0 := a}

| cumul_zeta : forall na b t b',
    Σ ;;; Γ ⊢ tLetIn na b t b' ≤s[pb] b' {0 := b}

| cumul_rel i body :
    option_map decl_body (nth_error Γ i) = Some (Some body) ->
    Σ ;;; Γ ⊢ tRel i ≤s[pb] lift0 (S i) body

| cumul_iota : forall ci c u args p brs br,
    nth_error brs c = Some br ->
    #|args| = (ci.(ci_npar) + context_assumptions br.(bcontext))%nat ->
    Σ ;;; Γ ⊢ tCase ci p (mkApps (tConstruct ci.(ci_ind) c u) args) brs  ≤s[pb] iota_red ci.(ci_npar) p args br

| cumul_fix : forall mfix idx args narg fn,
    unfold_fix mfix idx = Some (narg, fn) ->
    is_constructor narg args = true ->
    Σ ;;; Γ ⊢ mkApps (tFix mfix idx) args ≤s[pb] mkApps fn args

| cumul_cofix_case : forall ip p mfix idx args narg fn brs,
    unfold_cofix mfix idx = Some (narg, fn) ->
    Σ ;;; Γ ⊢ tCase ip p (mkApps (tCoFix mfix idx) args) brs ≤s[pb] tCase ip p (mkApps fn args) brs

| cumul_cofix_proj : forall p mfix idx args narg fn,
    unfold_cofix mfix idx = Some (narg, fn) ->
    Σ ;;; Γ ⊢ tProj p (mkApps (tCoFix mfix idx) args) ≤s[pb] tProj p (mkApps fn args)

| cumul_delta : forall c decl body (isdecl : declared_constant Σ c decl) u,
    decl.(cst_body) = Some body ->
    Σ ;;; Γ ⊢ tConst c u ≤s[pb] body@[u]

| cumul_proj : forall p args u arg,
    nth_error args (p.(proj_npars) + p.(proj_arg)) = Some arg ->
    Σ ;;; Γ ⊢ tProj p (mkApps (tConstruct p.(proj_ind) 0 u) args) ≤s[pb] arg

where " Σ ;;; Γ ⊢ t ≤s[ pb ] u " := (@cumulSpec0 _ Σ Γ pb t u) : type_scope.
Definition cumulSpec `{checker_flags} (Σ : global_env_ext) Γ := cumulSpec0 Σ Γ Cumul.

Notation " Σ ;;; Γ |- t <=s u " := (@cumulSpec _ Σ Γ t u) (at level 50, Γ, t, u at next level).

Module PCUICConversionParSpec <: EnvironmentTyping.ConversionParSig PCUICTerm PCUICEnvironment PCUICTermUtils PCUICEnvTyping.
End PCUICConversionParSpec.

End PCUICCumulativitySpec.

Implicit Types (cf : checker_flags) (Σ : global_env_ext).

Definition type_of_constructor mdecl (cdecl : constructor_body) (c : inductive * nat) (u : list Level.t) :=
  let mind := inductive_mind (fst c) in
  subst0 (inds mind u mdecl.(ind_bodies)) (subst_instance u (cstr_type cdecl)).

Include PCUICEnvTyping.

Inductive FixCoFix : Type := Fix | CoFix.

Class GuardChecker :=
{
  guard : FixCoFix -> global_env_ext -> context -> mfixpoint term -> Prop ;
}.

Axiom guard_checking : GuardChecker.
#[global]
Existing Instance guard_checking.

Definition fix_guard := guard Fix.
Definition cofix_guard := guard CoFix.

Definition destInd (t : term) :=
  match t with
  | tInd ind u => Some (ind, u)
  | _ => None
  end.

Definition isCoFinite (r : recursivity_kind) :=
  match r with
  | CoFinite => true
  | _ => false
  end.

Definition check_recursivity_kind
  (lookup: kername -> option global_decl) ind r :=
  match lookup ind with
  | Some (InductiveDecl mib) => ReflectEq.eqb mib.(ind_finite) r
  | _ => false
  end.

Definition check_one_fix d :=
  let '{| dname := na;
         dtype := ty;
         dbody := b;
         rarg := arg |} := d in
  let '(ctx, ty) := decompose_prod_assum [] ty in
  match nth_error (List.rev (smash_context [] ctx)) arg with
  | Some argd =>
    let (hd, args) := decompose_app argd.(decl_type) in
    match destInd hd with
    | Some (mkInd mind _, u) => Some mind
    | None => None
    end
  | None => None
  end.

Definition wf_fixpoint_gen
  (lookup: kername -> option global_decl) mfix :=
  forallb (isLambda ∘ dbody) mfix &&
  let checks := map check_one_fix mfix in
  match map_option_out checks with
  | Some (ind :: inds) =>

    forallb (eqb ind) inds &&
    check_recursivity_kind lookup ind Finite
  | _ => false
  end.

Definition wf_fixpoint (Σ : global_env) := wf_fixpoint_gen (lookup_env Σ).

Definition check_one_cofix d :=
  let '{| dname := na;
         dtype := ty;
         dbody := b;
         rarg := arg |} := d in
  let '(ctx, ty) := decompose_prod_assum [] ty in
  let (hd, args) := decompose_app ty in
  match destInd hd with
  | Some (mkInd ind _, u) => Some ind
  | None => None
  end.

Definition wf_cofixpoint_gen
  (lookup: kername -> option global_decl) mfix :=
  let checks := map check_one_cofix mfix in
  match map_option_out checks with
  | Some (ind :: inds) =>

    forallb (eqb ind) inds &&
    check_recursivity_kind lookup ind CoFinite
  | _ => false
  end.

Definition wf_cofixpoint (Σ : global_env) := wf_cofixpoint_gen (lookup_env Σ).

Reserved Notation "'wf_local' Σ Γ " (at level 9, Σ, Γ at next level).

Reserved Notation " Σ ;;; Γ |- t : T " (at level 50, Γ, t, T at next level).

Variant case_side_conditions `{checker_flags} wf_local_fun typing Σ Γ ci p ps mdecl idecl indices predctx :=
| case_side_info
    (eq_npars : mdecl.(ind_npars) = ci.(ci_npar))
    (wf_pred : wf_predicate mdecl idecl p)
    (cons : consistent_instance_ext Σ (ind_universes mdecl) p.(puinst))
    (wf_pctx : wf_local_fun Σ (Γ ,,, predctx))

    (conv_pctx : eq_context_upto_names p.(pcontext) (ind_predicate_context ci.(ci_ind) mdecl idecl))
    (allowed_elim : is_allowed_elimination Σ idecl.(ind_kelim) ps)
    (elim_relevance : isSortRel ps ci.(ci_relevance))
    (ind_inst : ctx_inst (typing Σ) Γ (p.(pparams) ++ indices)
                         (List.rev (subst_instance p.(puinst)
                                                   (ind_params mdecl ,,, ind_indices idecl : context))))
    (not_cofinite : isCoFinite mdecl.(ind_finite) = false).

Variant case_branch_typing `{checker_flags} wf_local_fun typing Σ Γ (ci:case_info) p ps mdecl idecl ptm  brs :=
| case_branch_info
    (wf_brs : wf_branches idecl brs)
    (brs_ty :
       All2i (fun i cdecl br =>

                eq_context_upto_names br.(bcontext) (cstr_branch_context ci mdecl cdecl) ×
                let brctxty := case_branch_type ci.(ci_ind) mdecl idecl p br ptm i cdecl in
                (wf_local_fun Σ (Γ ,,, brctxty.1) ×
                ((typing Σ (Γ ,,, brctxty.1) br.(bbody) (brctxty.2)) ×
                (typing Σ (Γ ,,, brctxty.1) brctxty.2 (tSort ps)))))
             0 idecl.(ind_ctors) brs).

Variant primitive_typing_hyps `{checker_flags}
  (typing : forall (Σ : global_env_ext) (Γ : context), term -> term -> Type)
  Σ Γ : prim_val term -> Type :=
| prim_int_hyps i : primitive_typing_hyps typing Σ Γ (primInt; primIntModel i)
| prim_float_hyps f : primitive_typing_hyps typing Σ Γ (primFloat; primFloatModel f)
| prim_string_hyps s : primitive_typing_hyps typing Σ Γ (primString; primStringModel s)
| prim_array_hyps a
  (wfl : wf_universe Σ (Universe.make' a.(array_level)))
  (hty : typing Σ Γ a.(array_type) (tSort (sType (Universe.make' a.(array_level)))))
  (hdef : typing Σ Γ a.(array_default) a.(array_type))
  (hvalue : All (fun x => typing Σ Γ x a.(array_type)) a.(array_value)) :
  primitive_typing_hyps typing Σ Γ (primArray; primArrayModel a).

Equations prim_type (p : prim_val term) (cst : kername) : term :=
prim_type (primInt; _) cst := tConst cst [];
prim_type (primFloat; _) cst := tConst cst [];
prim_type (primString; _) cst := tConst cst [];
prim_type (primArray; primArrayModel a) cst := tApp (tConst cst [a.(array_level)]) a.(array_type).

Inductive typing `{checker_flags} (Σ : global_env_ext) (Γ : context) : term -> term -> Type :=
| type_Rel : forall n decl,
    wf_local Σ Γ ->
    nth_error Γ n = Some decl ->
    Σ ;;; Γ |- tRel n : lift0 (S n) decl.(decl_type)

| type_Sort : forall s,
    wf_local Σ Γ ->
    wf_sort Σ s ->
    Σ ;;; Γ |- tSort s : tSort (Sort.super s)

| type_Prod : forall na A B s1 s2,
    lift_typing typing Σ Γ (j_vass_s na A s1) ->
    Σ ;;; Γ ,, vass na A |- B : tSort s2 ->
    Σ ;;; Γ |- tProd na A B : tSort (Sort.sort_of_product s1 s2)

| type_Lambda : forall na A t B,
    lift_typing typing Σ Γ (j_vass na A) ->
    Σ ;;; Γ ,, vass na A |- t : B ->
    Σ ;;; Γ |- tLambda na A t : tProd na A B

| type_LetIn : forall na b B t A,
    lift_typing typing Σ Γ (j_vdef na b B) ->
    Σ ;;; Γ ,, vdef na b B |- t : A ->
    Σ ;;; Γ |- tLetIn na b B t : tLetIn na b B A

| type_App : forall t na A B s u,

    Σ ;;; Γ |- tProd na A B : tSort s ->
    Σ ;;; Γ |- t : tProd na A B ->
    Σ ;;; Γ |- u : A ->
    Σ ;;; Γ |- tApp t u : B{0 := u}

| type_Const : forall cst u decl,
    wf_local Σ Γ ->
    declared_constant Σ cst decl ->
    consistent_instance_ext Σ decl.(cst_universes) u ->
    Σ ;;; Γ |- tConst cst u : decl.(cst_type)@[u]

| type_Ind : forall ind u mdecl idecl,
    wf_local Σ Γ ->
    declared_inductive Σ ind mdecl idecl ->
    consistent_instance_ext Σ mdecl.(ind_universes) u ->
    Σ ;;; Γ |- tInd ind u : idecl.(ind_type)@[u]

| type_Construct : forall ind i u mdecl idecl cdecl,
    wf_local Σ Γ ->
    declared_constructor Σ (ind, i) mdecl idecl cdecl ->
    consistent_instance_ext Σ mdecl.(ind_universes) u ->
    Σ ;;; Γ |- tConstruct ind i u : type_of_constructor mdecl cdecl (ind, i) u

| type_Case : forall ci p c brs indices ps mdecl idecl,
    let predctx := case_predicate_context ci.(ci_ind) mdecl idecl p in
    let ptm := it_mkLambda_or_LetIn predctx p.(preturn) in
    declared_inductive Σ ci.(ci_ind) mdecl idecl ->
    Σ ;;; Γ ,,, predctx |- p.(preturn) : tSort ps ->
    Σ ;;; Γ |- c : mkApps (tInd ci.(ci_ind) p.(puinst)) (p.(pparams) ++ indices) ->
    case_side_conditions (fun Σ Γ => wf_local Σ Γ) typing Σ Γ ci p ps
                         mdecl idecl indices predctx  ->
    case_branch_typing (fun Σ Γ => wf_local Σ Γ) typing Σ Γ ci p ps
                        mdecl idecl ptm brs ->
    Σ ;;; Γ |- tCase ci p c brs : mkApps ptm (indices ++ [c])

| type_Proj : forall p c u mdecl idecl cdecl pdecl args,
    declared_projection Σ p mdecl idecl cdecl pdecl ->
    Σ ;;; Γ |- c : mkApps (tInd p.(proj_ind) u) args ->
    #|args| = ind_npars mdecl ->
    Σ ;;; Γ |- tProj p c : subst0 (c :: List.rev args) pdecl.(proj_type)@[u]

| type_Fix : forall mfix n decl,
    wf_local Σ Γ ->
    fix_guard Σ Γ mfix ->
    nth_error mfix n = Some decl ->
    All (on_def_type (lift_typing1 (typing Σ)) Γ) mfix ->
    All (on_def_body (lift_typing1 (typing Σ)) (fix_context mfix) Γ) mfix ->
    wf_fixpoint Σ mfix ->
    Σ ;;; Γ |- tFix mfix n : decl.(dtype)

| type_CoFix : forall mfix n decl,
    wf_local Σ Γ ->
    cofix_guard Σ Γ mfix ->
    nth_error mfix n = Some decl ->
    All (on_def_type (lift_typing1 (typing Σ)) Γ) mfix ->
    All (on_def_body (lift_typing1 (typing Σ)) (fix_context mfix) Γ) mfix ->
    wf_cofixpoint Σ mfix ->
    Σ ;;; Γ |- tCoFix mfix n : decl.(dtype)

| type_Prim p prim_ty cdecl :
    wf_local Σ Γ ->
    primitive_constant Σ (prim_val_tag p) = Some prim_ty ->
    declared_constant Σ prim_ty cdecl ->
    primitive_invariants (prim_val_tag p) cdecl ->
    primitive_typing_hyps typing Σ Γ p ->
    Σ ;;; Γ |- tPrim p : prim_type p prim_ty

| type_Cumul : forall t A B s,
    Σ ;;; Γ |- t : A ->
    Σ ;;; Γ |- B : tSort s ->
    Σ ;;; Γ |- A <=s B ->
    Σ ;;; Γ |- t : B

where " Σ ;;; Γ |- t : T " := (typing Σ Γ t T)
and "'wf_local' Σ Γ " := (All_local_env (lift_typing1 (typing Σ)) Γ).

Definition wf `{checker_flags} := on_global_env cumulSpec0 (lift_typing typing).
Notation on_contexts_length := All2_fold_length.
Import Stdlib.Classes.CRelationClasses.
Import Equations.Type.Relation_Properties.

Definition ws_term P := { t : term | on_free_vars P t }.
Definition ws_term_proj {P} (t : ws_term P) : term.
admit.
Defined.
Coercion ws_term_proj : ws_term >-> term.

Definition ws_context P := { t : context | on_free_vars_ctx P t }.

Notation closed_context := (ws_context xpred0).
Notation open_term Γ := (ws_term (shiftnP #|Γ| xpred0)).
Definition ws_context_proj' {P} (t : ws_context P) : list context_decl.
Admitted.
Coercion ws_context_proj' : ws_context >-> list.

Definition ws_red1 Σ P (Γ : ws_context P) (t u : ws_term (shiftnP #|Γ| P)) :=
  red1 Σ Γ t u.

Definition ws_red Σ P (Γ : ws_context P) := clos_refl_trans (ws_red1 Σ P Γ).

Definition ws_pair :=
  ∑ Γ : ws_context xpred0, ws_term (shiftnP #|Γ| xpred0).

Section RedConfluence.
  Context {cf : checker_flags}.
  Context {Σ : global_env_ext} (wfΣ : wf Σ).
Definition red1_rel_alpha : relation ws_pair.
exact (relation_disjunction (A:=ws_pair) (fun '(Γ; t) '(Δ; u) => (red1 Σ Γ t u * (Γ = Δ)))%type
     (relation_disjunction (A:=ws_pair)
        (fun '(Γ; t) '(Δ; u) => ((red1_ctx Σ Γ Δ * (t = u :> term))))
        (fun '(Γ; t) '(Δ; u) => ((eq_context_upto_names Γ Δ * (t = u :> term)))))%type).
Defined.

  Lemma red_ws_red (Γ : closed_context) (x y : ws_term (shiftnP #|Γ| xpred0)) :
    red Σ Γ x y -> ws_red Σ xpred0 Γ x y.
Admitted.
Definition transport_ws_term {n m : nat} (t : ws_term (shiftnP n xpred0)) (eq : n = m) : ws_term (shiftnP m xpred0).
Admitted.
Definition red_ctx_alpha : relation context.
exact (All2_fold (fun Γ _ => All_decls_alpha (red Σ Γ))).
Defined.

  Instance red_ctx_alpha_refl : Reflexive red_ctx_alpha.
Admitted.

  Lemma ws_red_refl_irrel P (Γ : ws_context P) (x y : ws_term (shiftnP #|Γ| P)) :
    x = y :> term ->
    ws_red Σ P Γ x y.
Admitted.

  Lemma clos_rt_red1_alpha_out x y :
    clos_refl_trans red1_rel_alpha x y ->
    ∑ redctx : red_ctx_alpha x.π1 y.π1,
      ws_red Σ xpred0 x.π1 x.π2 (transport_ws_term y.π2 (symmetry (All2_fold_length redctx))).
  Proof using wfΣ.
    intros H.
    eapply clos_rt_rt1n_iff in H.
    induction H.
    -
 unshelve eexists.
reflexivity.
eapply ws_red_refl_irrel => //.
    -
 destruct x as [Γ t], y as [Δ u], z as [Δ' u']; simpl in *.
      destruct IHclos_refl_trans_1n.
      red in r.
destruct r.
      *
 destruct p.
subst.
exists x.
        transitivity u; auto.
        now eapply red_ws_red.
      *
 destruct t as [t ht], u as [u hu];
        move: r; case; move => [] r eq; noconf eq.
🛠️ Intermediate Coq File (useful for debugging if minimization did not go as far as you wanted)
🛠️ 📜 Intermediate Coq File log (useful for debugging if minimization did not go as far as you wanted)
📜 Build Log (contains the Coq error message) (truncated to last 8.0KiB; full 7.0MiB file on GitHub Actions Artifacts under build.log)
t-minimizer.OvTqaFJ361
MINIMIZER_DEBUG: files: 
make[2]: Leaving directory '/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/template-rocq'
# Ensure the cmxs is built before the loader file 
make -f Makefile.plugin gen-src/metarocq_template_plugin.cmxs
make[2]: Entering directory '/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/template-rocq'
MINIMIZER_DEBUG_EXTRA: coqc: /github/workspace/builds/coq/coq-failing/_install_ci/bin///rocq
MINIMIZER_DEBUG_EXTRA: original invocation: c --print-version 
MINIMIZER_DEBUG_EXTRA: new invocation: /github/workspace/builds/coq/coq-failing/_install_ci/bin/rocq.orig c --print-version 
MINIMIZER_DEBUG_EXTRA: coqpath: 
MINIMIZER_DEBUG_EXTRA: ocamlpath: /github/workspace/builds/coq/coq-failing/_build_ci/metarocq/template-rocq/:/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/safechecker-plugin/src:/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/erasure-plugin/src:/github/workspace/builds/coq/coq-failing/_install_ci/lib:
MINIMIZER_DEBUG_EXTRA: pwd: PWD=/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/template-rocq
MINIMIZER_DEBUG_EXTRA: exec: /github/workspace/builds/coq/coq-failing/_install_ci/bin/rocq.orig c --print-version 
MINIMIZER_DEBUG_EXTRA: coqlib: Warning: Deprecated environment variable COQLIB, use ROCQLIB instead.
/github/workspace/builds/coq/coq-failing/_install_ci/lib/coq//
MINIMIZER_DEBUG: info: /tmp/tmp-coqbot-minimizer.Prl4RTBcdH
MINIMIZER_DEBUG: files: 
make[2]: 'gen-src/metarocq_template_plugin.cmxs' is up to date.
make[2]: Leaving directory '/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/template-rocq'
make -f Makefile.plugin
make[2]: Entering directory '/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/template-rocq'
MINIMIZER_DEBUG_EXTRA: coqc: /github/workspace/builds/coq/coq-failing/_install_ci/bin///rocq
MINIMIZER_DEBUG_EXTRA: original invocation: c --print-version 
MINIMIZER_DEBUG_EXTRA: new invocation: /github/workspace/builds/coq/coq-failing/_install_ci/bin/rocq.orig c --print-version 
MINIMIZER_DEBUG_EXTRA: coqpath: 
MINIMIZER_DEBUG_EXTRA: ocamlpath: /github/workspace/builds/coq/coq-failing/_build_ci/metarocq/template-rocq/:/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/safechecker-plugin/src:/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/erasure-plugin/src:/github/workspace/builds/coq/coq-failing/_install_ci/lib:
MINIMIZER_DEBUG_EXTRA: pwd: PWD=/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/template-rocq
MINIMIZER_DEBUG_EXTRA: exec: /github/workspace/builds/coq/coq-failing/_install_ci/bin/rocq.orig c --print-version 
MINIMIZER_DEBUG_EXTRA: coqlib: Warning: Deprecated environment variable COQLIB, use ROCQLIB instead.
/github/workspace/builds/coq/coq-failing/_install_ci/lib/coq//
MINIMIZER_DEBUG: info: /tmp/tmp-coqbot-minimizer.0IDepJcLZM
MINIMIZER_DEBUG: files: 
MINIMIZER_DEBUG_EXTRA: coqc: /github/workspace/builds/coq/coq-failing/_install_ci/bin/////rocq
MINIMIZER_DEBUG_EXTRA: original invocation: c --print-version 
MINIMIZER_DEBUG_EXTRA: new invocation: /github/workspace/builds/coq/coq-failing/_install_ci/bin/rocq.orig c --print-version 
MINIMIZER_DEBUG_EXTRA: coqpath: 
MINIMIZER_DEBUG_EXTRA: ocamlpath: /github/workspace/builds/coq/coq-failing/_build_ci/metarocq/template-rocq/:/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/safechecker-plugin/src:/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/erasure-plugin/src:/github/workspace/builds/coq/coq-failing/_install_ci/lib:
MINIMIZER_DEBUG_EXTRA: pwd: PWD=/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/template-rocq
MINIMIZER_DEBUG_EXTRA: exec: /github/workspace/builds/coq/coq-failing/_install_ci/bin/rocq.orig c --print-version 
MINIMIZER_DEBUG_EXTRA: coqlib: Warning: Deprecated environment variable COQLIB, use ROCQLIB instead.
/github/workspace/builds/coq/coq-failing/_install_ci/lib/coq//
MINIMIZER_DEBUG: info: /tmp/tmp-coqbot-minimizer.m0kcLYnr7g
MINIMIZER_DEBUG: files: 
MINIMIZER_DEBUG_EXTRA: coqc: /github/workspace/builds/coq/coq-failing/_install_ci/bin/////rocq
MINIMIZER_DEBUG_EXTRA: original invocation: c --print-version 
MINIMIZER_DEBUG_EXTRA: new invocation: /github/workspace/builds/coq/coq-failing/_install_ci/bin/rocq.orig c --print-version 
MINIMIZER_DEBUG_EXTRA: coqpath: 
MINIMIZER_DEBUG_EXTRA: ocamlpath: /github/workspace/builds/coq/coq-failing/_build_ci/metarocq/template-rocq/:/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/safechecker-plugin/src:/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/erasure-plugin/src:/github/workspace/builds/coq/coq-failing/_install_ci/lib:
MINIMIZER_DEBUG_EXTRA: pwd: PWD=/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/template-rocq
MINIMIZER_DEBUG_EXTRA: exec: /github/workspace/builds/coq/coq-failing/_install_ci/bin/rocq.orig c --print-version 
MINIMIZER_DEBUG_EXTRA: coqlib: Warning: Deprecated environment variable COQLIB, use ROCQLIB instead.
/github/workspace/builds/coq/coq-failing/_install_ci/lib/coq//
MINIMIZER_DEBUG: info: /tmp/tmp-coqbot-minimizer.BeHeMWoDkM
MINIMIZER_DEBUG: files: 
make[3]: Nothing to be done for 'real-all'.
MINIMIZER_DEBUG_EXTRA: coqc: /github/workspace/builds/coq/coq-failing/_install_ci/bin/////rocq
MINIMIZER_DEBUG_EXTRA: original invocation: c --print-version 
MINIMIZER_DEBUG_EXTRA: new invocation: /github/workspace/builds/coq/coq-failing/_install_ci/bin/rocq.orig c --print-version 
MINIMIZER_DEBUG_EXTRA: coqpath: 
MINIMIZER_DEBUG_EXTRA: ocamlpath: /github/workspace/builds/coq/coq-failing/_build_ci/metarocq/template-rocq/:/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/safechecker-plugin/src:/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/erasure-plugin/src:/github/workspace/builds/coq/coq-failing/_install_ci/lib:
MINIMIZER_DEBUG_EXTRA: pwd: PWD=/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/template-rocq
MINIMIZER_DEBUG_EXTRA: exec: /github/workspace/builds/coq/coq-failing/_install_ci/bin/rocq.orig c --print-version 
MINIMIZER_DEBUG_EXTRA: coqlib: Warning: Deprecated environment variable COQLIB, use ROCQLIB instead.
/github/workspace/builds/coq/coq-failing/_install_ci/lib/coq//
MINIMIZER_DEBUG: info: /tmp/tmp-coqbot-minimizer.dqRdOG81lq
MINIMIZER_DEBUG: files: 
make[2]: Leaving directory '/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/template-rocq'
make[1]: Leaving directory '/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/template-rocq'
File "./theories/PCUICConfluence.v", line 3649, characters 47-49:
Error: Cannot infer the implicit parameter A of eq whose type is 
"Type" in
environment:
cf : checker_flags
Σ : global_env_ext
wfΣ : wf Σ
Γ : closed_context
t : term
ht : is_open_term Γ t
Δ : closed_context
u : term
hu : is_open_term Δ u
Δ' : closed_context
u' : open_term Δ'
H : clos_refl_trans_1n red1_rel_alpha (Δ; exist u hu) (Δ'; u')
x : red_ctx_alpha Δ Δ'
w :
  ws_red Σ xpred0 Δ (exist u hu)
    (transport_ws_term u' (symmetry (on_contexts_length x)))
r : red1_ctx Σ Γ Δ
eq : exist t ht = exist u hu

Command exited with non-zero status 1
theories/PCUICConfluence.vo (real: 46.89, user: 46.50, sys: 0.38, mem: 2432820 ko)
make[3]: *** [Makefile.rocq:814: theories/PCUICConfluence.vo] Error 1
make[3]: *** [theories/PCUICConfluence.vo] Deleting file 'theories/PCUICConfluence.glob'
make[2]: *** [Makefile.rocq:412: all] Error 2
make[2]: Leaving directory '/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/pcuic'
make[1]: *** [Makefile:11: coq] Error 2
make[1]: Leaving directory '/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/pcuic'
make: *** [Makefile:149: pcuic] Error 2
+ code=2
+ printf '\n%s exit code: %s\n' metarocq 2
+ '[' metarocq '!=' stdlib_test ']'
+ echo 'Aggregating timing log...'
Aggregating timing log...
+ echo

+ tools/make-one-time-file.py --real metarocq.log
    Time |   Peak Mem | File Name            
---------------------------------------------
0m46.89s | 2432820 ko | Total Time / Peak Mem
---------------------------------------------
0m46.89s | 2432820 ko | PCUICConfluence.vo   
+ '[' '' ']'
+ exit 2
/github/workspace/builds/coq /github/workspace
::endgroup::
📜 🔎 Minimization Log (truncated to last 8.0KiB; full 1.2MiB file on GitHub Actions Artifacts under bug.log)
tmp/tmpy4oyhyvr/Top/bug_01.v", line 121, characters 0-45:
Warning: Declaring a scope implicitly is deprecated; use in advance an
explicit "Declare Scope type_scope2.".
[undeclared-scope,deprecated-since-8.10,deprecated,default]
Error: The section RedConfluence, module PCUICPrimitive, module
EnvironmentTyping, module Retroknowledge and module BasicAst
need to be closed.


�[93mIntermediate code not saved.�[0m
Failed to do everything at once; trying one at a time.
Admitting lemmas unsuccessful.
No successful changes.

I will now attempt to admit definitions with Admitted

Non-fatal error: Failed to admit definitions and preserve the error.  
The new error was:
Deprecated environment variable COQCORELIB, use ROCQRUNTIMELIB instead.
Warning: Deprecated environment variable COQCORELIB,
use ROCQRUNTIMELIB instead.
[deprecated-coq-env-var,deprecated-since-9.0,deprecated,default]
File "/tmp/tmpyt9mnb1l/Top/bug_01.v", line 120, characters 0-45:
Warning: Declaring a scope implicitly is deprecated; use in advance an
explicit "Declare Scope type_scope2.".
[undeclared-scope,deprecated-since-8.10,deprecated,default]
File "/tmp/tmpyt9mnb1l/Top/bug_01.v", line 333, characters 0-38:
Error: Signature components for field compare_spec do not match:
expected type
"forall x y : Level.t,
 CompareSpec (Level.eq x y) (Level.lt x y) (Level.lt y x) (Level.compare x y)"
but found type
"forall x y : Level.t,
 CompareSpec (x = y) (Level.lt x y) (Level.lt y x) (Level.compare x y)".


�[93mIntermediate code not saved.�[0m
Failed to do everything at once; trying one at a time.
Admitting definitions successful
Success!

I will now attempt to admit lemmas with admit. Defined

Non-fatal error: Failed to admit lemmas and preserve the error.  
The new error was:
Deprecated environment variable COQCORELIB, use ROCQRUNTIMELIB instead.
Warning: Deprecated environment variable COQCORELIB,
use ROCQRUNTIMELIB instead.
[deprecated-coq-env-var,deprecated-since-9.0,deprecated,default]
File "/tmp/tmp4gm082dg/Top/bug_01.v", line 120, characters 0-45:
Warning: Declaring a scope implicitly is deprecated; use in advance an
explicit "Declare Scope type_scope2.".
[undeclared-scope,deprecated-since-8.10,deprecated,default]
Error: The section RedConfluence, module PCUICPrimitive, module
EnvironmentTyping, module Retroknowledge and module BasicAst
need to be closed.


�[93mIntermediate code not saved.�[0m
Failed to do everything at once; trying one at a time.
Admitting lemmas unsuccessful.
No successful changes.

I will now attempt to admit definitions with admit. Defined

Non-fatal error: Failed to admit definitions and preserve the error.  
The new error was:
Deprecated environment variable COQCORELIB, use ROCQRUNTIMELIB instead.
Warning: Deprecated environment variable COQCORELIB,
use ROCQRUNTIMELIB instead.
[deprecated-coq-env-var,deprecated-since-9.0,deprecated,default]
File "/tmp/tmp7b_5zeu0/Top/bug_01.v", line 120, characters 0-45:
Warning: Declaring a scope implicitly is deprecated; use in advance an
explicit "Declare Scope type_scope2.".
[undeclared-scope,deprecated-since-8.10,deprecated,default]
File "/tmp/tmp7b_5zeu0/Top/bug_01.v", line 334, characters 0-38:
Error: Signature components for field compare_spec do not match:
expected type
"forall x y : Level.t,
 CompareSpec (Level.eq x y) (Level.lt x y) (Level.lt y x) (Level.compare x y)"
but found type
"forall x y : Level.t,
 CompareSpec (x = y) (Level.lt x y) (Level.lt y x) (Level.compare x y)".


�[93mIntermediate code not saved.�[0m
Failed to do everything at once; trying one at a time.
Admitting definitions unsuccessful.
No successful changes.

I will now attempt to admit lemmas with Admitted with Proof using

Non-fatal error: Failed to admit lemmas and preserve the error.  
The new error was:
Deprecated environment variable COQCORELIB, use ROCQRUNTIMELIB instead.
Warning: Deprecated environment variable COQCORELIB,
use ROCQRUNTIMELIB instead.
[deprecated-coq-env-var,deprecated-since-9.0,deprecated,default]
File "/tmp/tmppf0j4p8t/Top/bug_01.v", line 120, characters 0-45:
Warning: Declaring a scope implicitly is deprecated; use in advance an
explicit "Declare Scope type_scope2.".
[undeclared-scope,deprecated-since-8.10,deprecated,default]
Error: The section RedConfluence, module PCUICPrimitive, module
EnvironmentTyping, module Retroknowledge and module BasicAst
need to be closed.


�[93mIntermediate code not saved.�[0m
Failed to do everything at once; trying one at a time.
Admitting lemmas unsuccessful.
No successful changes.

I will now attempt to admit definitions with Admitted with Proof using

Non-fatal error: Failed to admit definitions and preserve the error.  
The new error was:
Deprecated environment variable COQCORELIB, use ROCQRUNTIMELIB instead.
Warning: Deprecated environment variable COQCORELIB,
use ROCQRUNTIMELIB instead.
[deprecated-coq-env-var,deprecated-since-9.0,deprecated,default]
File "/tmp/tmpb3a6wf5x/Top/bug_01.v", line 120, characters 0-45:
Warning: Declaring a scope implicitly is deprecated; use in advance an
explicit "Declare Scope type_scope2.".
[undeclared-scope,deprecated-since-8.10,deprecated,default]
File "/tmp/tmpb3a6wf5x/Top/bug_01.v", line 333, characters 0-38:
Error: Signature components for field compare_spec do not match:
expected type
"forall x y : Level.t,
 CompareSpec (Level.eq x y) (Level.lt x y) (Level.lt y x) (Level.compare x y)"
but found type
"forall x y : Level.t,
 CompareSpec (x = y) (Level.lt x y) (Level.lt y x) (Level.compare x y)".


�[93mIntermediate code not saved.�[0m
Failed to do everything at once; trying one at a time.
Admitting definitions unsuccessful.
No successful changes.

I will now attempt to admit lemmas with admit. Defined with Proof using

Non-fatal error: Failed to admit lemmas and preserve the error.  
The new error was:
Deprecated environment variable COQCORELIB, use ROCQRUNTIMELIB instead.
Warning: Deprecated environment variable COQCORELIB,
use ROCQRUNTIMELIB instead.
[deprecated-coq-env-var,deprecated-since-9.0,deprecated,default]
File "/tmp/tmpxj4q8ih2/Top/bug_01.v", line 120, characters 0-45:
Warning: Declaring a scope implicitly is deprecated; use in advance an
explicit "Declare Scope type_scope2.".
[undeclared-scope,deprecated-since-8.10,deprecated,default]
Error: The section RedConfluence, module PCUICPrimitive, module
EnvironmentTyping, module Retroknowledge and module BasicAst
need to be closed.


�[93mIntermediate code not saved.�[0m
Failed to do everything at once; trying one at a time.
Admitting lemmas unsuccessful.
No successful changes.

I will now attempt to admit definitions with admit. Defined with Proof using

Non-fatal error: Failed to admit definitions and preserve the error.  
The new error was:
Deprecated environment variable COQCORELIB, use ROCQRUNTIMELIB instead.
Warning: Deprecated environment variable COQCORELIB,
use ROCQRUNTIMELIB instead.
[deprecated-coq-env-var,deprecated-since-9.0,deprecated,default]
File "/tmp/tmpsqzyt5d5/Top/bug_01.v", line 120, characters 0-45:
Warning: Declaring a scope implicitly is deprecated; use in advance an
explicit "Declare Scope type_scope2.".
[undeclared-scope,deprecated-since-8.10,deprecated,default]
File "/tmp/tmpsqzyt5d5/Top/bug_01.v", line 334, characters 0-38:
Error: Signature components for field compare_spec do not match:
expected type
"forall x y : Level.t,
 CompareSpec (Level.eq x y) (Level.lt x y) (Level.lt y x) (Level.compare x y)"
but found type
"forall x y : Level.t,
 CompareSpec (x = y) (Level.lt x y) (Level.lt y x) (Level.compare x y)".


�[93mIntermediate code not saved.�[0m
Failed to do everything at once; trying one at a time.
Admitting definitions unsuccessful.
No successful changes.

I will now attempt to add Proof using lines
�[92m
Adding Proof using lines successful.�[0m
Failed to do everything at once; trying one at a time.
Adding Proof using lines unsuccessful.
No successful changes.

I will now attempt to export modules
Module exportation unsuccessful.

I will now attempt to split imports and exports
Import/Export splitting unsuccessful.

I will now attempt to split := definitions
One-line definition splitting unsuccessful.

I will now attempt to remove all lines, one at a time

If you have any comments on your experience of the minimizer, please share them in a reply (possibly tagging @JasonGross).
If you believe there's a bug in the bug minimizer, please report it on the bug minimizer issue tracker.

Copy link
Contributor
coqbot-app bot commented May 28, 2025
Minimization interrupted by timeout, being automatically continued. Partially Minimized File /home/runner/work/run-coq-bug-minimizer/run-coq-bug-minimizer/builds/coq/coq-failing/_build_ci/metarocq/pcuic/theories/PCUICConfluence.v in 5h 15m 7s (from ci-metarocq) (interrupted by timeout, being automatically continued) (full log on GitHub Actions - verbose log)
⭐ ⏱️ Partially Minimized Coq File (timeout) (truncated to first and last 32KiB; full 89KiB file on GitHub Actions Artifacts under bug.v)
(* -*- mode: coq; coq-prog-args: ("-emacs" "-q" "-w" "-deprecated-native-compiler-option" "-native-compiler" "no" "-coqlib" "/github/workspace/builds/coq/coq-failing/_install_ci/lib/coq//" "-R" "/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/utils/theories" "MetaRocq.Utils" "-R" "/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/common/theories" "MetaRocq.Common" "-R" "/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/pcuic/theories" "MetaRocq.PCUIC" "-Q" "/github/workspace/cwd" "Top" "-Q" "/github/workspace/builds/coq/coq-failing/_install_ci/lib/coq///user-contrib/Equations" "Equations" "-Q" "/github/workspace/builds/coq/coq-failing/_install_ci/lib/coq///user-contrib/Ltac2" "Ltac2" "-Q" "/github/workspace/builds/coq/coq-failing/_install_ci/lib/coq///user-contrib/Stdlib" "Stdlib" "-top" "Top.bug_01") -*- *)
(* File reduced by coq-bug-minimizer from original input, then from 3959 lines to 98 lines, then from 111 lines to 3187 lines, then from 3191 lines to 96 lines, then from 107 lines to 1813 lines, then from 1818 lines to 359 lines, then from 369 lines to 1502 lines, then from 1506 lines to 524 lines, then from 535 lines to 3221 lines, then from 3222 lines to 656 lines, then from 667 lines to 2894 lines, then from 2900 lines to 656 lines, then from 667 lines to 1321 lines, then from 1327 lines to 874 lines, then from 883 lines to 675 lines, then from 686 lines to 2746 lines, then from 2745 lines to 687 lines, then from 698 lines to 3155 lines, then from 3155 lines to 745 lines, then from 756 lines to 1586 lines, then from 1589 lines to 869 lines, then from 880 lines to 2395 lines, then from 2394 lines to 885 lines, then from 895 lines to 2754 lines, then from 2755 lines to 1157 lines, then from 1161 lines to 1145 lines, then from 1156 lines to 1809 lines, then from 1813 lines to 1200 lines, then from 1211 lines to 4024 lines, then from 4021 lines to 1355 lines, then from 1366 lines to 3048 lines, then from 3051 lines to 1938 lines, then from 1928 lines to 1518 lines, then from 1529 lines to 1814 lines, then from 1819 lines to 1523 lines, then from 1533 lines to 2340 lines, then from 2342 lines to 1526 lines, then from 1536 lines to 4638 lines, then from 4602 lines to 1892 lines, then from 1903 lines to 3075 lines, then from 3076 lines to 2771 lines, then from 2762 lines to 1985 lines, then from 1996 lines to 2830 lines, then from 2835 lines to 2048 lines, then from 2059 lines to 2413 lines, then from 2418 lines to 2052 lines, then from 2063 lines to 2597 lines, then from 2601 lines to 2063 lines, then from 2074 lines to 6642 lines, then from 6641 lines to 4802 lines, then from 4761 lines to 2105 lines, then from 2116 lines to 2604 lines, then from 2606 lines to 2117 lines, then from 2128 lines to 3899 lines, then from 3897 lines to 2137 lines, then from 2148 lines to 2516 lines, then from 2521 lines to 2151 lines, then from 2161 lines to 2404 lines, then from 2409 lines to 2150 lines, then from 2161 lines to 2447 lines, then from 2449 lines to 2162 lines, then from 2178 lines to 2162 lines, then from 2173 lines to 2602 lines, then from 2607 lines to 2180 lines, then from 2190 lines to 2437 lines, then from 2442 lines to 2200 lines, then from 2210 lines to 2368 lines, then from 2373 lines to 2201 lines, then from 2211 lines to 2367 lines, then from 2371 lines to 2204 lines, then from 2214 lines to 2934 lines, then from 2939 lines to 2250 lines, then from 2261 lines to 2593 lines, then from 2598 lines to 2252 lines, then from 2263 lines to 2633 lines, then from 2637 lines to 2623 lines *)
(* coqc version 9.1+alpha compiled with OCaml 4.14.2
   coqtop version runner-t7b1znuaq-project-4504-concurrent-2:/builds/coq/coq/_build/default,(HEAD detached at cdd06d0a2f356e) (cdd06d0a2f356e0c02e2d20356562b7deae4cf15)
   Expected coqc runtime on this file: 1.290 sec *)









Require Corelib.Init.Ltac.
Require Corelib.Classes.CRelationClasses.
Require Stdlib.Classes.CRelationClasses.
Require Stdlib.Classes.DecidableClass.
Require Stdlib.Logic.HLevelsBase.
Require Stdlib.Bool.Bool.
Require Corelib.Classes.RelationClasses.
Require Stdlib.Classes.RelationClasses.
Require Corelib.Numbers.BinNums.
Require Stdlib.Numbers.BinNums.
Require Stdlib.Logic.EqdepFacts.
Require Stdlib.Logic.Eqdep_dec.
Require Corelib.Classes.Morphisms.
Require Stdlib.Classes.Morphisms.
Require Corelib.Setoids.Setoid.
Require Stdlib.Setoids.Setoid.
Require Stdlib.Structures.Equalities.
Require Corelib.Relations.Relation_Definitions.
Require Stdlib.Relations.Relation_Definitions.
Require Stdlib.Relations.Relation_Operators.
Require Stdlib.Relations.Operators_Properties.
Require Stdlib.Relations.Relations.
Require Stdlib.Structures.Orders.
Require Corelib.Program.Basics.
Require Stdlib.Program.Basics.
Require Stdlib.Structures.OrdersTac.
Require Stdlib.Structures.OrdersFacts.
Require Stdlib.Structures.GenericMinMax.
Require Corelib.Classes.Morphisms_Prop.
Require Stdlib.Classes.Morphisms_Prop.
Require Stdlib.Numbers.NumPrelude.
Require Stdlib.Numbers.NatInt.NZAxioms.
Require Stdlib.Numbers.NatInt.NZBase.
Require Stdlib.Numbers.NatInt.NZAdd.
Require Stdlib.Numbers.NatInt.NZMul.
Require Stdlib.Logic.Decidable.
Require Stdlib.Numbers.NatInt.NZOrder.
Require Stdlib.Numbers.NatInt.NZAddOrder.
Require Stdlib.Numbers.NatInt.NZMulOrder.
Require Stdlib.Numbers.NatInt.NZParity.
Require Stdlib.Numbers.NatInt.NZPow.
Require Stdlib.Numbers.NatInt.NZSqrt.
Require Stdlib.Numbers.NatInt.NZLog.
Require Stdlib.Numbers.NatInt.NZDiv.
Require Stdlib.Numbers.NatInt.NZGcd.
Require Stdlib.Numbers.NatInt.NZBits.
Require Stdlib.Numbers.Natural.Abstract.NAxioms.
Require Stdlib.Numbers.Natural.Abstract.NBase.
Require Stdlib.Numbers.Natural.Abstract.NAdd.
Require Stdlib.Numbers.Natural.Abstract.NOrder.
Require Stdlib.Numbers.Natural.Abstract.NAddOrder.
Require Stdlib.Numbers.Natural.Abstract.NMulOrder.
Require Stdlib.Numbers.Natural.Abstract.NSub.
Require Stdlib.Numbers.Natural.Abstract.NMaxMin.
Require Stdlib.Numbers.Natural.Abstract.NParity.
Require Stdlib.Numbers.Natural.Abstract.NPow.
Require Stdlib.Numbers.Natural.Abstract.NSqrt.
Require Stdlib.Numbers.Natural.Abstract.NLog.
Require Stdlib.Numbers.Natural.Abstract.NDiv.
Require Stdlib.Numbers.Natural.Abstract.NDiv0.
Require Stdlib.Numbers.Natural.Abstract.NGcd.
Require Stdlib.Numbers.Natural.Abstract.NLcm.
Require Stdlib.Numbers.Natural.Abstract.NLcm0.
Require Stdlib.Numbers.Natural.Abstract.NBits.
Require Stdlib.Numbers.Natural.Abstract.NProperties.
Require Stdlib.Arith.PeanoNat.
Require Corelib.BinNums.PosDef.
Require Stdlib.BinNums.PosDef.
Require Stdlib.PArith.BinPosDef.
Require Stdlib.PArith.BinPos.
Require Stdlib.PArith.Pnat.
Require Stdlib.PArith.POrderedType.
Require Stdlib.PArith.PArith.
Require Corelib.BinNums.NatDef.
Require Stdlib.BinNums.NatDef.
Require Stdlib.NArith.BinNatDef.
Require Stdlib.NArith.BinNat.
Require Stdlib.setoid_ring.Ring_theory.
Require Corelib.Lists.ListDef.
Require Stdlib.Lists.ListDef.
Require Stdlib.Lists.List.
Require Stdlib.setoid_ring.BinList.
Require Stdlib.Numbers.Integer.Abstract.ZAxioms.
Require Stdlib.Numbers.Integer.Abstract.ZBase.
Require Stdlib.Numbers.Integer.Abstract.ZAdd.
Require Stdlib.Numbers.Integer.Abstract.ZMul.
Require Stdlib.Numbers.Integer.Abstract.ZLt.
Require Stdlib.Numbers.Integer.Abstract.ZAddOrder.
Require Stdlib.Numbers.Integer.Abstract.ZMulOrder.
Require Stdlib.Numbers.Integer.Abstract.ZMaxMin.
Require Stdlib.Numbers.Integer.Abstract.ZSgnAbs.
Require Stdlib.Numbers.Integer.Abstract.ZParity.
Require Stdlib.Numbers.Integer.Abstract.ZPow.
Require Stdlib.Numbers.Integer.Abstract.ZDivTrunc.
Require Stdlib.Numbers.Integer.Abstract.ZDivFloor.
Require Stdlib.Numbers.Integer.Abstract.ZGcd.
Require Stdlib.Numbers.Integer.Abstract.ZLcm.
Require Stdlib.Numbers.Integer.Abstract.ZBits.
Require Stdlib.Numbers.Integer.Abstract.ZProperties.
Require Corelib.BinNums.IntDef.
Require Stdlib.BinNums.IntDef.
Require Stdlib.ZArith.BinIntDef.
Require Stdlib.ZArith.BinInt.
Require Stdlib.setoid_ring.Ring_polynom.
Require Stdlib.Lists.ListTactics.
Require Stdlib.setoid_ring.InitialRing.
Require Stdlib.setoid_ring.Ring_tac.
Require Stdlib.setoid_ring.Ring_base.
Require Stdlib.setoid_ring.Ring.
Require Stdlib.Arith.Factorial.
Require Stdlib.Arith.Between.
Require Stdlib.Arith.Peano_dec.
Require Stdlib.Arith.Compare_dec.
Require Stdlib.Arith.EqNat.
Require Stdlib.Arith.Wf_nat.
Require Stdlib.Arith.Arith_base.
Require Stdlib.NArith.Nnat.
Require Stdlib.setoid_ring.ArithRing.
Require Stdlib.Arith.Arith.
Require Stdlib.ZArith.Znat.
Require Stdlib.micromega.ZifyClasses.
Require Stdlib.ZArith.Zeven.
Require Stdlib.micromega.ZifyInst.
Require Stdlib.micromega.Zify.
Require Stdlib.omega.PreOmega.
Require Stdlib.micromega.OrderedRing.
Require Stdlib.NArith.Ndiv_def.
Require Stdlib.NArith.Nsqrt_def.
Require Stdlib.NArith.Ngcd_def.
Require Stdlib.NArith.NArith_base.
Require Stdlib.setoid_ring.NArithRing.
Require Stdlib.NArith.NArith.
Require Stdlib.micromega.Env.
Require Stdlib.micromega.EnvRing.
Require Stdlib.micromega.Refl.
Require Stdlib.micromega.Tauto.
Require Stdlib.micromega.RingMicromega.
Require Stdlib.ZArith.Zpow_def.
Require Stdlib.setoid_ring.ZArithRing.
Require Stdlib.micromega.ZCoeff.
Require Stdlib.ZArith.Zcompare.
Require Stdlib.ZArith.Zorder.
Require Stdlib.ZArith.Zmisc.
Require Stdlib.ZArith.Wf_Z.
Require Corelib.Init.Sumbool.
Require Stdlib.Init.Sumbool.
Require Stdlib.ZArith.ZArith_dec.
Require Stdlib.ZArith.Zbool.
Require Stdlib.ZArith.Zabs.
Require Stdlib.ZArith.Zcomplements.
Require Stdlib.ZArith.Zdiv.
Require Stdlib.micromega.VarMap.
Require Stdlib.micromega.ZMicromega.
Require Stdlib.micromega.DeclConstantZ.
Require Stdlib.micromega.Lia.
Require Stdlib.btauto.Algebra.
Require Stdlib.btauto.Reflect.
Require Stdlib.btauto.Btauto.
Require Corelib.ssr.ssreflect.
Require Stdlib.ssr.ssreflect.
Require Corelib.ssr.ssrbool.
Require Stdlib.ssr.ssrbool.
Require MetaRocq.Common.config.
Require Stdlib.Sets.Relations_1.
Require Stdlib.Sorting.Sorted.
Require Stdlib.Sorting.SetoidList.
Require Stdlib.Classes.RelationPairs.
Require Stdlib.MSets.MSetInterface.
Require Stdlib.Structures.EqualitiesFacts.
Require Stdlib.Structures.OrdersLists.
Require Stdlib.MSets.MSetList.
Require Stdlib.MSets.MSetGenTree.
Require Stdlib.ZArith.Int.
Require Stdlib.MSets.MSetAVL.
Require Corelib.Floats.FloatOps.
Require Corelib.Strings.PrimString.
Require Corelib.Init.Byte.
Require Stdlib.Init.Byte.
Require Stdlib.Strings.Byte.
Require MetaRocq.Utils.ByteCompare.
Require Corelib.extraction.Extraction.
Require Stdlib.extraction.Extraction.
Require Stdlib.Unicode.Utf8_core.
Require Equations.Init.
Require Equations.Signature.
Require Equations.CoreTactics.
Require Equations.Prop.SigmaNotations.
Require Equations.Prop.Logic.
Require Equations.Prop.Classes.
Require Corelib.Program.Tactics.
Require Stdlib.Program.Tactics.
Require Equations.Prop.EqDec.
Require Equations.Prop.DepElim.
Require Equations.Prop.Constants.
Require Stdlib.Vectors.Fin.
Require Stdlib.Vectors.VectorDef.
Require Stdlib.Vectors.VectorSpec.
Require Stdlib.Vectors.VectorEq.
Require Stdlib.Vectors.Vector.
Require Stdlib.Vectors.Bvector.
Require Stdlib.Wellfounded.Disjoint_Union.
Require Stdlib.Wellfounded.Inclusion.
Require Stdlib.Wellfounded.Inverse_Image.
Require Stdlib.Wellfounded.Transitive_Closure.
Require Stdlib.Wellfounded.List_Extension.
Require Stdlib.Wellfounded.Lexicographic_Exponentiation.
Require Stdlib.Wellfounded.Lexicographic_Product.
Require Stdlib.Wellfounded.Union.
Require Stdlib.Wellfounded.Well_Ordering.
Require Stdlib.Wellfounded.Wellfounded.
Require Corelib.Program.Wf.
Require Stdlib.Program.Wf.
Require Stdlib.Logic.FunctionalExtensionality.
Require Equations.Prop.Subterm.
Require Equations.Prop.FunctionalInduction.
Require Equations.Prop.Tactics.
Require Equations.Prop.NoConfusion.
Require Equations.Prop.EqDecInstances.
Require Equations.Prop.Loader.
Require Equations.Prop.Telescopes.
Require Equations.Prop.Equations.
Require MetaRocq.Utils.ReflectEq.
Require Stdlib.Structures.OrderedType.

Module Export AdmitTactic.
Module Import LocalFalse.
Inductive False : Prop := .
End LocalFalse.
Axiom proof_admitted : False.
Import Coq.Init.Ltac.
Tactic Notation "admit" := abstract case proof_admitted.
End AdmitTactic.

Module Export MetaRocq_DOT_Utils_DOT_MRCompare_WRAPPED.
Module Export MRCompare.
Import Stdlib.ssr.ssreflect.
Import Stdlib.extraction.Extraction.
Import Stdlib.Structures.OrderedType.
Import Stdlib.Structures.Orders.
Import Equations.Prop.Equations.

Lemma CompareSpec_Proper : Proper (iff ==> iff ==> iff ==> Logic.eq ==> iff) CompareSpec.
Admitted.
Definition compare_cont (c : comparison) (d : comparison) : comparison. exact (match c with
  | Datatypes.Lt => Datatypes.Lt
  | Datatypes.Eq => d
  | Datatypes.Gt => Datatypes.Gt
  end). Defined.
Extraction Inline compare_cont.

Local Notation " c ?? y " := (compare_cont c y) (at level 100).

Lemma compare_cont_CompOpp p q : CompOpp (compare_cont p q) = compare_cont (CompOpp p) (CompOpp q).
Admitted.

Definition comparison_trans p q :=
  match p, q with
  | Datatypes.Eq, c => Some c
  | c, Datatypes.Eq => Some c
  | Datatypes.Lt, Datatypes.Gt => None
  | Datatypes.Gt, Datatypes.Lt => None
  | c, _ => Some c
  end.

Lemma compare_cont_trans {A} (cmp : A -> A -> comparison) :
  (forall c x y z, cmp x y = c -> cmp y z = c -> cmp x z = c) ->
  (forall x y, cmp x y = Datatypes.Eq -> x = y) ->
  forall c x y z q q' q'',
  (forall c, q = c -> q' = c -> q'' = c) ->
  compare_cont (cmp x y) q = c -> compare_cont (cmp y z) q' = c -> compare_cont (cmp x z) q'' = c.
Admitted.



Module BoolOT <: UsualOrderedType.
  Definition t := bool.
Definition compare (x y : bool) : comparison. exact (if x then if y then Eq else Gt else if y then Lt else Eq). Defined.

  Definition lt (x y : bool) :=
    if x then False else y = true.

  Definition compare_spec (x y : bool) : CompareSpec (x = y) (lt x y) (lt y x) (compare x y).
Admitted.
Definition eq : t -> t -> Prop. exact (eq). Defined.
Definition eq_equiv : Equivalence eq. exact (_). Defined.

  Definition eq_dec (l1 l2 : t) : {l1 = l2}+{l1 <> l2}.
Admitted.

  Definition lt_strorder : StrictOrder lt.
Admitted.

  Definition lt_compat : Proper (eq ==> eq ==> iff) lt.
Admitted.
Definition eqb (l1 l2 : t) : bool. exact (match compare l1 l2 with Eq => true | _ => false end). Defined.
Definition eq_leibniz (x y : t) : eq x y -> x = y. exact (id). Defined.

End BoolOT.

Notation bool_compare := BoolOT.compare.

Module ListOrderedType (A : UsualOrderedType) <: UsualOrderedType.
  Definition t := list A.t.
  Import Stdlib.Lists.List.
Import ListNotations.
Fixpoint compare (l1 l2 : t) : comparison. exact (match l1, l2 with
    | [], [] => Eq
    | hd :: tl, hd' :: tl' => compare_cont (A.compare hd hd') (compare tl tl')
    | [], _ :: _ => Lt
    | _, [] => Gt
    end). Defined.
Definition eq : t -> t -> Prop. exact (eq). Defined.
Definition eq_equiv : Equivalence eq. exact (_). Defined.

  Inductive lt_ : t -> t -> Prop :=
  | lt_nil_cons hd tl : lt_ [] (hd :: tl)
  | lt_cons_cons_hd hd tl hd' tl' : A.lt hd hd' -> lt_ (hd :: tl) (hd' :: tl')
  | lt_cons_cons_tl hd tl tl' : lt_ tl tl' -> lt_ (hd :: tl) (hd :: tl').
  Derive Signature for lt_.
  Local Hint Constructors lt_ : core.

  Definition lt := lt_.

  Global Instance lt_strorder : StrictOrder lt.
Admitted.

  Global Instance lt_compat : Proper (eq ==> eq ==> iff) lt.
Admitted.

  Definition compare_spec :
    forall x y : t, CompareSpec (x = y) (lt x y) (lt y x) (compare x y).
Admitted.

  Lemma compare_eq x y : compare x y = Eq -> x = y.
Admitted.

  Lemma compare_refl x : compare x x = Eq.
Admitted.

  Lemma compare_sym x y : compare x y = CompOpp (compare y x).
Admitted.

  Lemma compare_lt_lt x y : compare x y = Lt <-> lt x y.
Admitted.

  Lemma compare_trans x y z c : compare x y = c -> compare y z = c -> compare x z = c.
Admitted.
Definition eqb (l1 l2 : t) : bool. exact (match compare l1 l2 with Eq => true | _ => false end). Defined.
Definition eq_leibniz (x y : t) : eq x y -> x = y. exact (id). Defined.

  Program Definition eqb_dec (x y : t) : { x = y } + { x <> y } :=
    match eqb x y with
    | true => left _
    | false => right _
    end.
Admit Obligations.
Admit Obligations.

  Global Instance eq_dec : EqDec t := { eq_dec := eqb_dec }.

End ListOrderedType.

End MRCompare.

End MetaRocq_DOT_Utils_DOT_MRCompare_WRAPPED.
Module Export MetaRocq_DOT_Utils_DOT_MRCompare.
Module Export MetaRocq.
Module Export Utils.
Module Export MRCompare.
Include MetaRocq_DOT_Utils_DOT_MRCompare_WRAPPED.MRCompare.
End MRCompare.

End Utils.
Import MetaRocq.Utils.ReflectEq.

Module Export String.
  Inductive t : Set :=
  | EmptyString
  | String (_ : Byte.byte) (_ : t).
Fixpoint compare (xs ys : t) : comparison.
Admitted.
Notation string := String.t.
Import Stdlib.Structures.Orders.

Module OT_byte <: OrderedType.OrderedType with Definition t := Byte.byte.
  Definition t := Byte.byte.
  Definition eq := @Logic.eq t.
  Definition lt := fun l r => ByteCompare.compare l r = Lt.
  Theorem eq_refl : forall x : t, eq x x.
Admitted.
  Theorem eq_sym : forall x y : t, eq x y -> eq y x.
Admitted.
  Theorem eq_trans : forall x y z : t, eq x y -> eq y z -> eq x z.
Admitted.
  Theorem lt_trans : forall x y z : t, lt x y -> lt y z -> lt x z.
Admitted.
  Theorem lt_not_eq : forall x y : t, lt x y -> not (eq x y).
Admitted.
  Definition compare (x y : t) : OrderedType.Compare lt eq x y.
Admitted.
Definition eq_dec : forall x y : t, {eq x y} + {not (eq x y)}.
Admitted.
End OT_byte.

Module StringOT <: UsualOrderedType.
  Definition t := string.
Definition eq : t -> t -> Prop.
exact (eq).
Defined.
Definition eq_equiv : Equivalence eq.
exact (_).
Defined.

  Definition compare := String.compare.
  Definition lt x y : Prop := compare x y = Lt.

  Theorem compare_spec : forall x y, CompareSpec (x = y) (lt x y) (lt y x) (compare x y).
Admitted.
Definition eq_dec : forall x y : t, {eq x y} + {not (eq x y)}.
Admitted.

  Global Instance lt_strorder : StrictOrder lt.
Admitted.

  Definition lt_compat : Proper (eq ==> eq ==> iff) lt.
Admitted.

End StringOT.
Notation "p .1" := (fst p) : pair_scope.
Notation "p .2" := (snd p) : pair_scope.
Open Scope pair_scope.

Notation "x × y" := (prod x y ) (at level 80, right associativity).
Definition BiImpl (A B : Type) : Type := (A -> B) * (B -> A).

Notation "A <-> B" := (BiImpl A B) (at level 95) : type_scope.
Module Export Equations_DOT_Type_DOT_Relation_WRAPPED.
Module Export Relation.

Definition relation (A : Type) := A -> A -> Type.

Section Reflexive_Transitive_Closure.
  Context {A : Type} (R : relation A).

  Inductive clos_refl_trans (x:A) : A -> Type :=
    | rt_step (y:A) : R x y -> clos_refl_trans x y
    | rt_refl : clos_refl_trans x x
    | rt_trans (y z:A) :
          clos_refl_trans x y -> clos_refl_trans y z -> clos_refl_trans x z.

  Inductive clos_refl_trans_1n (x: A) : A -> Type :=
    | rt1n_refl : clos_refl_trans_1n x x
    | rt1n_trans (y z:A) :
         R x y -> clos_refl_trans_1n y z -> clos_refl_trans_1n x z.

End Reflexive_Transitive_Closure.

End Relation.

Section Properties.

  Context{A : Type}.
  Variable R : relation A.

    Lemma clos_rt_rt1n_iff : forall x y,
      clos_refl_trans R x y <-> clos_refl_trans_1n R x y.
Admitted.

End Properties.
Import Stdlib.Classes.CRelationClasses.
Definition on_rel {A B} (R : A -> A -> Prop) (f : B -> A) : B -> B -> Prop.
Admitted.

Notation on_Trel_eq R f g :=
  (fun x y => (R (f x) (f y) * (g x = g y)))%type.

Global Instance clos_rt_trans A R : Transitive (@clos_refl_trans A R).
Admitted.

Global Instance clos_rt_refl A R : Reflexive (@clos_refl_trans A R).
Admitted.
Export Stdlib.ZArith.BinInt.
Export Stdlib.ZArith.Znat.
Coercion is_true : bool >-> Sortclass.

Notation "'eta_compose'" := (fun g f x => g (f x)).

Notation "g ∘ f" := (eta_compose g f) (at level 40, left associativity).

Notation "'∑' x .. y , p" := (sigT (fun x => .. (sigT (fun y => p%type)) ..))
  (at level 200, x binder, right associativity,
   format "'[' '∑'  '/  ' x  ..  y ,  '/  ' p ']'")
  : type_scope.

Notation "( x ; y )" := (@existT _ _ x y).
Notation "x .π1" := (@projT1 _ _ x) (at level 3, format "x '.π1'").
Notation "x .π2" := (@projT2 _ _ x) (at level 3, format "x '.π2'").
Import Stdlib.Sorting.SetoidList.

Export ListNotations.

Notation "#| l |" := (List.length l) (at level 0, l at level 99, format "#| l |").

Fixpoint mapi_rec {A B} (f : nat -> A -> B) (l : list A) (n : nat) : list B :=
  match l with
  | [] => []
  | hd :: tl => f n hd :: mapi_rec f tl (S n)
  end.

Definition mapi {A B} (f : nat -> A -> B) (l : list A) := mapi_rec f l 0.

Section map2.

  Context {A B C} (f : A -> B -> C).
Fixpoint map2 (l : list A) (l' : list B) : list C.
Admitted.

End map2.

Definition option_default {A B} (f : A -> B) (o : option A) (b : B) :=
  match o with Some x => f x | None => b end.

Fixpoint map_option_out {A} (l : list (option A)) : option (list A) :=
  match l with
  | nil => Some nil
  | hd :: tl => match hd, map_option_out tl with
                | Some hd, Some tl => Some (hd :: tl)
                | _, _ => None
                end
  end.

Inductive All {A} (P : A -> Type) : list A -> Type :=
    All_nil : All P []
  | All_cons : forall (x : A) (l : list A),
                  P x -> All P l -> All P (x :: l).

Inductive All2 {A B : Type} (R : A -> B -> Type) : list A -> list B -> Type :=
  All2_nil : All2 R [] []
| All2_cons : forall (x : A) (y : B) (l : list A) (l' : list B),
    R x y -> All2 R l l' -> All2 R (x :: l) (y :: l').

Inductive All2i {A B : Type} (R : nat -> A -> B -> Type) (n : nat)
  : list A -> list B -> Type :=
| All2i_nil : All2i R n [] []
| All2i_cons :
    forall x y l r,
      R n x y ->
      All2i R (S n) l r ->
      All2i R n (x :: l) (y :: r).

Inductive Forall3 {A B C : Type} (R : A -> B -> C -> Type) : list A -> list B -> list C -> Prop :=
  Forall3_nil : Forall3 R [] [] []
| Forall3_cons : forall (x : A) (y : B) (z : C) (l : list A) (l' : list B) (l'' : list C),
    R x y z -> Forall3 R l l' l'' -> Forall3 R (x :: l) (y :: l') (z :: l'').

Section alli.
  Context {A} (p : nat -> A -> bool).
Fixpoint alli (n : nat) (l : list A) : bool.
Admitted.
End alli.

Inductive OnOne2 {A : Type} (P : A -> A -> Type) : list A -> list A -> Type :=
| OnOne2_hd hd hd' tl : P hd hd' -> OnOne2 P (hd :: tl) (hd' :: tl)
| OnOne2_tl hd tl tl' : OnOne2 P tl tl' -> OnOne2 P (hd :: tl) (hd :: tl').

Inductive All2_fold {A} (P : list A -> list A -> A -> A -> Type)
            : list A -> list A -> Type :=
| All2_fold_nil : All2_fold P nil nil
| All2_fold_cons {d d' Γ Γ'} : All2_fold P Γ Γ' -> P Γ Γ' d d' -> All2_fold P (d :: Γ) (d' :: Γ').

Lemma All2_fold_length {A P} {Γ Γ' : list A} :
  All2_fold P Γ Γ' -> #|Γ| = #|Γ'|.
Admitted.
Notation "A * B" := (prod A B) : type_scope2.
Global Open Scope type_scope2.

Definition ident   := string.

Definition dirpath := list ident.

Module IdentOT := StringOT.

Module DirPathOT := ListOrderedType IdentOT.

Inductive modpath :=
| MPfile  (dp : dirpath)
| MPbound (dp : dirpath) (id : ident) (i : nat)
| MPdot   (mp : modpath) (id : ident).

Definition kername := modpath × ident.

Module Export ModPathComp.

  Definition mpbound_compare dp id k dp' id' k' :=
    compare_cont (DirPathOT.compare dp dp')
      (compare_cont (IdentOT.compare id id') (Nat.compare k k')).

  Fixpoint compare mp mp' :=
    match mp, mp' with
    | MPfile dp, MPfile dp' => DirPathOT.compare dp dp'
    | MPbound dp id k, MPbound dp' id' k' =>
      mpbound_compare dp id k dp' id' k'
    | MPdot mp id, MPdot mp' id' =>
      compare_cont (compare mp mp') (IdentOT.compare id id')
    | MPfile _, _ => Gt
    | _, MPfile _ => Lt
    | MPbound _ _ _, _ => Gt
    | _, MPbound _ _ _ => Lt
    end.

End ModPathComp.

  Definition compare kn kn' :=
    match kn, kn' with
    | (mp, id), (mp', id') =>
      compare_cont (ModPathComp.compare mp mp') (IdentOT.compare id id')
    end.

  Definition eqb kn kn' :=
    match compare kn kn' with
    | Eq => true
    | _ => false
    end.

Record inductive : Set := mkInd { inductive_mind : kername ;
                                  inductive_ind : nat }.

Record projection := mkProjection
  { proj_ind : inductive;
    proj_npars : nat;
    proj_arg : nat  }.

Inductive global_reference :=
| VarRef : ident -> global_reference
| ConstRef : kername -> global_reference
| IndRef : inductive -> global_reference
| ConstructRef : inductive -> nat -> global_reference.
Module Export BasicAst.
Import Stdlib.ssr.ssreflect.
Import Equations.Prop.Equations.

Inductive name : Set :=
| nAnon
| nNamed (_ : ident).

Inductive relevance : Set := Relevant | Irrelevant.

Record binder_annot (A : Type) := mkBindAnn { binder_n
F438
ame : A; binder_relevance : relevance }.
Arguments binder_relevance {_}.
Definition eq_binder_annot {A B} (b : binder_annot A) (b' : binder_annot B) : Prop.
Admitted.

Definition aname := binder_annot name.

Record case_info := mk_case_info {
  ci_ind : inductive;
  ci_npar : nat;

  ci_relevance : relevance }.

Inductive recursivity_kind :=
  | Finite
  | CoFinite
  | BiFinite .

Inductive conv_pb :=
  | Conv
  | Cumul.

Record def term := mkdef {
  dname : aname;
  dtype : term;
  dbody : term;
  rarg  : nat   }.

Arguments dname {term} _.
Arguments dtype {term} _.
Arguments dbody {term} _.
Arguments rarg {term} _.

Definition map_def {A B} (tyf bodyf : A -> B) (d : def A) :=
  {| dname := d.(dname); dtype := tyf d.(dtype); dbody := bodyf d.(dbody); rarg := d.(rarg) |}.

Definition mfixpoint term := list (def term).

Record judgment_ {universe Term} := Judge {
  j_term : option Term;
  j_typ : Term;
  j_univ : option universe;
  j_rel : option relevance;
}.
Arguments judgment_ : clear implicits.
Arguments Judge {universe Term} _ _ _.

Section Contexts.
  Context {term : Type}.

  Record context_decl := mkdecl {
    decl_name : aname ;
    decl_body : option term ;
    decl_type : term
  }.
End Contexts.

Arguments context_decl : clear implicits.
Notation TypRel typ rel := (Judge None typ None (Some rel)).
Notation TermTypRel tm ty rel := (Judge (Some tm) ty None (Some rel)).
Notation TypUnivRel ty u rel := (Judge None ty (Some u) (Some rel)).

Notation j_vass na ty := (TypRel ty na.(binder_relevance)).
Notation j_vass_s na ty s := (TypUnivRel ty s na.(binder_relevance)).
Notation j_vdef na b ty := (TermTypRel b ty na.(binder_relevance)).
Definition map_decl {term term'} (f : term -> term') (d : context_decl term) : context_decl term'.
Admitted.
Definition test_decl {term} (f : term -> bool) (d : context_decl term) : bool.
Admitted.

Definition snoc {A} (Γ : list A) (d : A) := d :: Γ.

Notation " Γ ,, d " := (snoc Γ d) (at level 20, d at next level).

Definition app_context {A} (Γ Γ': list A) := Γ' ++ Γ.

Notation "Γ ,,, Γ'" := (app_context Γ Γ') (at level 25, Γ' at next level, left associativity).

Section Contexts.
  Context {term term' term'' : Type}.

  Definition fold_context_k (f : nat -> term -> term') Γ :=
    List.rev (mapi (fun k' decl => map_decl (f k') decl) (List.rev Γ)).
Definition forget_types (c : list (BasicAst.context_decl term)) : list aname.
admit.
Defined.

End Contexts.
Module Export Universes.
Import MetaRocq.Common.config.

Implicit Types (cf : checker_flags).

Record valuation :=
  { valuation_mono : string -> positive ;
    valuation_poly : nat -> nat }.

Class Evaluable (A : Type) := val : valuation -> A -> nat.

Module Level.
  Inductive t_ : Set :=
  | lzero
  | level (_ : string)
  | lvar (_ : nat) .

  Definition t := t_.
Global Instance Evaluable : Evaluable t.
Admitted.
Definition compare (l1 l2 : t) : comparison.
Admitted.
Definition eq : t -> t -> Prop.
exact (eq).
Defined.
Definition eq_equiv : Equivalence eq.
Admitted.

  Inductive lt_ : t -> t -> Prop :=
  | ltSetLevel s : lt_ lzero (level s)
  | ltSetlvar n : lt_ lzero (lvar n)
  | ltLevelLevel s s' : StringOT.lt s s' -> lt_ (level s) (level s')
  | ltLevellvar s n : lt_ (level s) (lvar n)
  | ltlvarlvar n n' : Nat.lt n n' -> lt_ (lvar n) (lvar n').

  Definition lt := lt_.

  Definition lt_strorder : StrictOrder lt.
Admitted.

  Definition lt_compat : Proper (eq ==> eq ==> iff) lt.
Admitted.

  Definition compare_spec :
    forall x y : t, CompareSpec (x = y) (lt x y) (lt y x) (compare x y).
Admitted.
Definition eq_dec : forall (l1 l2 : t), {l1 = l2}+{l1 <> l2}.
Admitted.

End Level.

Module LevelSet := MSetAVL.Make Level.

Module LevelExpr.
  Definition t := (Level.t * nat)%type.
Definition get_level (e : t) : Level.t.
Admitted.
Definition eq : t -> t -> Prop.
exact (eq).
Defined.
Definition eq_equiv : Equivalence eq.
Admitted.

  Inductive lt_ : t -> t -> Prop :=
  | ltLevelExpr1 l n n' : (n < n')%nat -> lt_ (l, n) (l, n')
  | ltLevelExpr2 l l' b b' : Level.lt l l' -> lt_ (l, b) (l', b').

  Definition lt := lt_.

  Global Instance lt_strorder : StrictOrder lt.
Admitted.

  Definition lt_compat : Proper (Logic.eq ==> Logic.eq ==> iff) lt.
Admitted.
Definition compare (x y : t) : comparison.
Admitted.

  Definition compare_spec :
    forall x y : t, CompareSpec (x = y) (lt x y) (lt y x) (compare x y).
Admitted.
Definition eq_dec : forall (l1 l2 : t), {l1 = l2} + {l1 <> l2}.
Admitted.
Definition eq_leibniz (x y : t) : eq x y -> x = y.
Admitted.

End LevelExpr.

Module LevelExprSet := MSetList.MakeWithLeibniz LevelExpr.

Record nonEmptyLevelExprSet
  := { t_set : LevelExprSet.t ;
       t_ne  : LevelExprSet.is_empty t_set = false }.

Coercion t_set : nonEmptyLevelExprSet >-> LevelExprSet.t.

Module Export Universe.

  Definition t := nonEmptyLevelExprSet.
Definition make' (l: Level.t) : t.
Admitted.
Global Instance Evaluable : Evaluable Universe.t.
Admitted.
Definition lt : t -> t -> Prop.
Admitted.
End Universe.

Module Export ConstraintType.
  Inductive t_ : Set := Le (z : Z) | Eq.

  Definition t := t_.

  Inductive lt_ : t -> t -> Prop :=
  | LeLe n m : (n < m)%Z -> lt_ (Le n) (Le m)
  | LeEq n : lt_ (Le n) Eq.
  Definition lt := lt_.
End ConstraintType.

Module UnivConstraint.
Definition t : Set.
exact (Level.t * ConstraintType.t * Level.t).
Defined.
Definition eq : t -> t -> Prop.
Admitted.
Definition eq_equiv : Equivalence eq.
Admitted.

  Inductive lt_ : t -> t -> Prop :=
  | lt_Level2 l1 t l2 l2' : Level.lt l2 l2' -> lt_ (l1, t, l2) (l1, t, l2')
  | lt_Cstr l1 t t' l2 l2' : ConstraintType.lt t t' -> lt_ (l1, t, l2) (l1, t', l2')
  | lt_Level1 l1 l1' t t' l2 l2' : Level.lt l1 l1' -> lt_ (l1, t, l2) (l1', t', l2').
  Definition lt := lt_.

  Lemma lt_strorder : StrictOrder lt.
Admitted.

  Lemma lt_compat : Proper (eq ==> eq ==> iff) lt.
Admitted.
Definition compare : t -> t -> comparison.
Admitted.

  Lemma compare_spec x y
    : CompareSpec (eq x y) (lt x y) (lt y x) (compare x y).
Admitted.

  Lemma eq_dec x y : {eq x y} + {~ eq x y}.
Admitted.
End UnivConstraint.

Module ConstraintSet := MSetAVL.Make UnivConstraint.

Module Export Instance.
Definition t : Set.
exact (list Level.t).
Defined.
Definition empty : t.
Admitted.
End Instance.

Module Export UContext.
  Definition t := list name × (Instance.t × ConstraintSet.t).
Definition instance : t -> Instance.t.
Admitted.
End UContext.

Module Export AUContext.
  Definition t := list name × ConstraintSet.t.
Definition repr (x : t) : UContext.t.
Admitted.
End AUContext.

Module Export ContextSet.
  Definition t := LevelSet.t × ConstraintSet.t.
End ContextSet.

Module Variance.

  Inductive t :=
  | Irrelevant : t
  | Covariant : t
  | Invariant : t.

End Variance.

Variant opt_variance :=
  AllEqual | AllIrrelevant | Variance of list Variance.t.

Inductive universes_decl : Type :=
| Monomorphic_ctx
| Polymorphic_ctx (cst : AUContext.t).

Inductive satisfies0 (v : valuation) : UnivConstraint.t -> Prop :=
| satisfies0_Lt (l l' : Level.t) (z : Z) : (Z.of_nat (val v l) <= Z.of_nat (val v l') - z)%Z
                        -> satisfies0 v (l, ConstraintType.Le z, l')
| satisfies0_Eq (l l' : Level.t) : val v l = val v l'
                        -> satisfies0 v (l, ConstraintType.Eq, l').

Definition satisfies v : ConstraintSet.t -> Prop :=
  ConstraintSet.For_all (satisfies0 v).

Definition leq0_universe_n n φ (u u' : Universe.t) :=
  forall v, satisfies v φ -> (Z.of_nat (val v u) <= Z.of_nat (val v u') - n)%Z.

Definition leq_universe_n {cf} n φ (u u' : Universe.t) :=
  if check_univs then leq0_universe_n n φ u u' else True.
Definition leq_universe {cf} := leq_universe_n 0.

Definition eq0_universe φ (u u' : Universe.t) :=
  forall v, satisfies v φ -> val v u = val v u'.

Definition eq_universe {cf} φ (u u' : Universe.t) :=
  if check_univs then eq0_universe φ u u' else True.

Definition valid_constraints0 φ ctrs
  := forall v, satisfies v φ -> satisfies v ctrs.

Definition val

[...]

verses)))
    (to_extended_list (smash_context [] mdecl.(ind_params) ,,, ictx)) in
  let inddecl :=
    {| decl_name :=
      {| binder_name := nNamed (ind_name idecl); binder_relevance := idecl.(ind_relevance) |};
       decl_body := None;
       decl_type := indty |}
  in (inddecl :: ictx).

Definition inst_case_context params puinst (pctx : context) :=
  subst_context (List.rev params) 0 (subst_instance puinst pctx).

Definition inst_case_predicate_context (p : predicate term) :=
  inst_case_context p.(pparams) p.(puinst) p.(pcontext).

Definition inst_case_branch_context (p : predicate term) (br : branch term) :=
  inst_case_context p.(pparams) p.(puinst) br.(bcontext).

Definition iota_red npar p args br :=
  subst (List.rev (List.skipn npar args)) 0
    (expand_lets (inst_case_branch_context p br) (bbody br)).

Definition pre_case_predicate_context_gen ind mdecl idecl params puinst : context :=
  inst_case_context params puinst (ind_predicate_context ind mdecl idecl).

Definition case_predicate_context_gen ind mdecl idecl params puinst pctx :=
  map2 set_binder_name pctx (pre_case_predicate_context_gen ind mdecl idecl params puinst).

Definition case_predicate_context ind mdecl idecl p : context :=
  case_predicate_context_gen ind mdecl idecl p.(pparams) p.(puinst) (forget_types p.(pcontext)).

Definition cstr_branch_context ind mdecl cdecl : context :=
  expand_lets_ctx mdecl.(ind_params)
    (subst_context (inds (inductive_mind ind) (abstract_instance mdecl.(ind_universes))
       mdecl.(ind_bodies)) #|mdecl.(ind_params)|
      cdecl.(cstr_args)).

Definition pre_case_branch_context_gen ind mdecl cdecl params puinst : context :=
  inst_case_context params puinst (cstr_branch_context ind mdecl cdecl).

Definition case_branch_context_gen ind mdecl params puinst pctx cdecl :=
  map2 set_binder_name pctx (pre_case_branch_context_gen ind mdecl cdecl params puinst).

Definition case_branch_type_gen ind mdecl (idecl : one_inductive_body) params puinst bctx ptm i cdecl : context * term :=
  let cstr := tConstruct ind i puinst in
  let args := to_extended_list cdecl.(cstr_args) in
  let cstrapp := mkApps cstr (map (lift0 #|cdecl.(cstr_args)|) params ++ args) in
  let brctx := case_branch_context_gen ind mdecl params puinst bctx cdecl in
  let upars := subst_instance puinst mdecl.(ind_params) in
  let indices :=
    (map (subst (List.rev params) #|cdecl.(cstr_args)|)
      (map (expand_lets_k upars #|cdecl.(cstr_args)|)
        (map (subst (inds (inductive_mind ind) puinst mdecl.(ind_bodies))
                    (#|mdecl.(ind_params)| + #|cdecl.(cstr_args)|))
          (map (subst_instance puinst) cdecl.(cstr_indices))))) in
  let ty := mkApps (lift0 #|cdecl.(cstr_args)| ptm) (indices ++ [cstrapp]) in
  (brctx, ty).

Definition case_branch_type ind mdecl idecl p (b : branch term) ptm i cdecl : context * term :=
  case_branch_type_gen ind mdecl idecl p.(pparams) p.(puinst) (forget_types b.(bcontext)) ptm i cdecl.

Definition idecl_binder idecl :=
  {| decl_name :=
    {| binder_name := nNamed idecl.(ind_name);
        binder_relevance := idecl.(ind_relevance) |};
     decl_body := None;
     decl_type := idecl.(ind_type) |}.

Definition wf_predicate_gen mdecl idecl (pparams : list term) (pcontext : list aname) : Prop :=
  let decl := idecl_binder idecl in
  (#|pparams| = mdecl.(ind_npars)) /\
  (Forall2 (fun na decl => eq_binder_annot na decl.(decl_name))
    pcontext (decl :: idecl.(ind_indices))).

Definition wf_predicate mdecl idecl (p : predicate term) : Prop :=
  wf_predicate_gen mdecl idecl p.(pparams) (forget_types p.(pcontext)).

Definition wf_branch_gen cdecl (bctx : list aname) : Prop :=
  (Forall2 (fun na decl => eq_binder_annot na decl.(decl_name))
    bctx cdecl.(cstr_args)).

Definition wf_branch cdecl (b : branch term) : Prop :=
  wf_branch_gen cdecl (forget_types b.(bcontext)).

Definition wf_branches idecl (brs : list (branch term)) : Prop :=
  Forall2 wf_branch idecl.(ind_ctors) brs.

Definition fix_subst (l : mfixpoint term) :=
  let fix aux n :=
      match n with
      | 0 => []
      | S n => tFix l n :: aux n
      end
  in aux (List.length l).

Definition unfold_fix (mfix : mfixpoint term) (idx : nat) :=
  match List.nth_error mfix idx with
  | Some d => Some (d.(rarg), subst0 (fix_subst mfix) d.(dbody))
  | None => None
  end.

Definition cofix_subst (l : mfixpoint term) :=
  let fix aux n :=
      match n with
      | 0 => []
      | S n => tCoFix l n :: aux n
      end
  in aux (List.length l).

Definition unfold_cofix (mfix : mfixpoint term) (idx : nat) :=
  match List.nth_error mfix idx with
  | Some d => Some (d.(rarg), subst0 (cofix_subst mfix) d.(dbody))
  | None => None
  end.

Definition is_constructor n ts :=
  match List.nth_error ts n with
  | Some a => isConstruct_app a
  | None => false
  end.
Definition cmp_universe_instance (cmp_univ : Universe.t -> Universe.t -> Prop) : Instance.t -> Instance.t -> Prop.
Admitted.

Definition cmp_universe_variance (cmp_univ : conv_pb -> Universe.t -> Universe.t -> Prop) pb v u u' :=
  match v with
  | Variance.Irrelevant => True
  | Variance.Covariant => on_rel (cmp_univ pb) Universe.make' u u'
  | Variance.Invariant => on_rel (cmp_univ Conv) Universe.make' u u'
  end.

Definition cmp_universe_instance_variance cmp_univ pb v u u' :=
  Forall3 (cmp_universe_variance cmp_univ pb) v u u'.

Definition global_variance_gen lookup gr napp :=
  match gr with
  | IndRef ind =>
    match lookup_inductive_gen lookup ind with
    | Some (mdecl, idecl) =>
      match destArity [] idecl.(ind_type) with
      | Some (ctx, _) => if (context_assumptions ctx) <=? napp then
          match mdecl.(ind_variance) with
          | Some var => Variance var
          | None => AllEqual
          end
        else AllEqual
      | None => AllEqual
      end
    | None => AllEqual
    end
  | ConstructRef ind k =>
    match lookup_constructor_gen lookup ind k with
    | Some (mdecl, idecl, cdecl) =>
      if (cdecl.(cstr_arity) + mdecl.(ind_npars))%nat <=? napp then

        AllIrrelevant
      else AllEqual
    | _ => AllEqual
    end
  | _ => AllEqual
  end.

Definition cmp_opt_variance cmp_univ pb v :=
  match v with
  | AllEqual => cmp_universe_instance (cmp_univ Conv)
  | AllIrrelevant => fun l l' => #|l| = #|l'|
  | Variance v => fun u u' => cmp_universe_instance (cmp_univ Conv) u u' \/ cmp_universe_instance_variance cmp_univ pb v u u'
  end.

Definition cmp_global_instance_gen Σ cmp_universe pb gr napp :=
  cmp_opt_variance cmp_universe pb (global_variance_gen Σ gr napp).

Notation cmp_global_instance Σ := (cmp_global_instance_gen (lookup_env Σ)).

Inductive eq_decl_upto_names : context_decl -> context_decl -> Type :=
  | compare_vass {na na' T} :
    eq_binder_annot na na' -> eq_decl_upto_names (vass na T) (vass na' T)
  | compare_vdef {na na' b T} :
    eq_binder_annot na na' -> eq_decl_upto_names (vdef na b T) (vdef na' b T).

Notation eq_context_upto_names := (All2 eq_decl_upto_names).

Definition shiftnP k p i :=
  (i <? k) || p (i - k).
Fixpoint on_free_vars (p : nat -> bool) (t : term) : bool.
Admitted.

Definition on_free_vars_decl P d :=
  test_decl (on_free_vars P) d.

Definition on_free_vars_ctx P ctx :=
  alli (fun k => (on_free_vars_decl (shiftnP k P))) 0 (List.rev ctx).

Notation is_open_term Γ := (on_free_vars (shiftnP #|Γ| xpred0)).
Notation is_closed_context := (on_free_vars_ctx xpred0).
Definition set_preturn (p : predicate term) (pret' : term) : predicate term.
Admitted.
Definition set_pparams (p : predicate term) (pars' : list term) : predicate term.
Admitted.
Definition on_one_decl (P : term -> term -> Type)
  (d : context_decl) (d' : context_decl) : Type.
Admitted.

Section OnOne_local_2.
  Context (P : forall (Γ : context), context_decl -> context_decl -> Type).

  Inductive OnOne2_local_env : context -> context -> Type :=
  | onone2_localenv_cons_abs Γ na na' t t' :
      P Γ (vass na t) (vass na' t') ->
      OnOne2_local_env (Γ ,, vass na t) (Γ ,, vass na' t')
  | onone2_localenv_def Γ na na' b b' t t' :
      P Γ (vdef na b t) (vdef na' b' t') ->
      OnOne2_local_env (Γ ,, vdef na b t) (Γ ,, vdef na' b' t')
  | onone2_localenv_cons_tl Γ Γ' d :
      OnOne2_local_env Γ Γ' ->
      OnOne2_local_env (Γ ,, d) (Γ' ,, d).
End OnOne_local_2.
Arguments exist {_ _} _ _.
Import Equations_DOT_Type_DOT_Relation_WRAPPED.Relation.

Reserved Notation " Σ ;;; Γ |- t ⇝ u " (at level 50, Γ, t, u at next level).

Definition set_array_default (ar : array_model term) (v : term) :=
  {| array_level := ar.(array_level);
     array_default := v;
     array_type := ar.(array_type);
     array_value := ar.(array_value) |}.

Definition set_array_type (ar : array_model term) (v : term) :=
  {| array_level := ar.(array_level);
     array_default := ar.(array_default);
     array_type := v;
     array_value := ar.(array_value) |}.

Definition set_array_value (ar : array_model term) (v : list term) :=
  {| array_level := ar.(array_level);
     array_default := ar.(array_default);
     array_type := ar.(array_type);
     array_value := v |}.

Inductive red1 (Σ : global_env) (Γ : context) : term -> term -> Type :=

| red_beta na t b a :
  Σ ;;; Γ |- tApp (tLambda na t b) a ⇝ b {0 := a}

| red_zeta na b t b' :
  Σ ;;; Γ |- tLetIn na b t b' ⇝ b' {0 := b}

| red_rel i body :
    option_map decl_body (nth_error Γ i) = Some (Some body) ->
    Σ ;;; Γ |- tRel i ⇝ lift0 (S i) body

| red_iota ci c u args p brs br :
    nth_error brs c = Some br ->
    #|args| = (ci.(ci_npar) + context_assumptions br.(bcontext))%nat ->
    Σ ;;; Γ |- tCase ci p (mkApps (tConstruct ci.(ci_ind) c u) args) brs
        ⇝ iota_red ci.(ci_npar) p args br

| red_fix mfix idx args narg fn :
    unfold_fix mfix idx = Some (narg, fn) ->
    is_constructor narg args = true ->
    Σ ;;; Γ |- mkApps (tFix mfix idx) args ⇝ mkApps fn args

| red_cofix_case ip p mfix idx args narg fn brs :
    unfold_cofix mfix idx = Some (narg, fn) ->
    Σ ;;; Γ |- tCase ip p (mkApps (tCoFix mfix idx) args) brs ⇝
         tCase ip p (mkApps fn args) brs

| red_cofix_proj p mfix idx args narg fn :
    unfold_cofix mfix idx = Some (narg, fn) ->
    Σ ;;; Γ |- tProj p (mkApps (tCoFix mfix idx) args) ⇝ tProj p (mkApps fn args)

| red_delta c decl body (isdecl : declared_constant Σ c decl) u :
    decl.(cst_body) = Some body ->
    Σ ;;; Γ |- tConst c u ⇝ subst_instance u body

| red_proj p args u arg:
    nth_error args (p.(proj_npars) + p.(proj_arg)) = Some arg ->
    Σ ;;; Γ |- tProj p (mkApps (tConstruct p.(proj_ind) 0 u) args) ⇝ arg

| abs_red_l na M M' N : Σ ;;; Γ |- M ⇝ M' -> Σ ;;; Γ |- tLambda na M N ⇝ tLambda na M' N
| abs_red_r na M M' N : Σ ;;; Γ ,, vass na N |- M ⇝ M' -> Σ ;;; Γ |- tLambda na N M ⇝ tLambda na N M'

| letin_red_def na b t b' r : Σ ;;; Γ |- b ⇝ r -> Σ ;;; Γ |- tLetIn na b t b' ⇝ tLetIn na r t b'
| letin_red_ty na b t b' r : Σ ;;; Γ |- t ⇝ r -> Σ ;;; Γ |- tLetIn na b t b' ⇝ tLetIn na b r b'
| letin_red_body na b t b' r : Σ ;;; Γ ,, vdef na b t |- b' ⇝ r -> Σ ;;; Γ |- tLetIn na b t b' ⇝ tLetIn na b t r

| case_red_param ci p params' c brs :
    OnOne2 (fun t u => Σ ;;; Γ |- t ⇝ u) p.(pparams) params' ->
    Σ ;;; Γ |- tCase ci p c brs ⇝ tCase ci (set_pparams p params') c brs

| case_red_return ci p preturn' c brs :
  Σ ;;; Γ ,,, inst_case_predicate_context p |- p.(preturn) ⇝ preturn' ->
  Σ ;;; Γ |- tCase ci p c brs ⇝ tCase ci (set_preturn p preturn') c brs

| case_red_discr ci p c c' brs :
  Σ ;;; Γ |- c ⇝ c' -> Σ ;;; Γ |- tCase ci p c brs ⇝ tCase ci p c' brs

| case_red_brs ci p c brs brs' :
    OnOne2 (fun br br' =>
      on_Trel_eq (fun t u => Σ ;;; Γ ,,, inst_case_branch_context p br |- t ⇝ u) bbody bcontext br br')
      brs brs' ->
    Σ ;;; Γ |- tCase ci p c brs ⇝ tCase ci p c brs'

| proj_red p c c' : Σ ;;; Γ |- c ⇝ c' -> Σ ;;; Γ |- tProj p c ⇝ tProj p c'

| app_red_l M1 N1 M2 : Σ ;;; Γ |- M1 ⇝ N1 -> Σ ;;; Γ |- tApp M1 M2 ⇝ tApp N1 M2
| app_red_r M2 N2 M1 : Σ ;;; Γ |- M2 ⇝ N2 -> Σ ;;; Γ |- tApp M1 M2 ⇝ tApp M1 N2

| prod_red_l na M1 M2 N1 : Σ ;;; Γ |- M1 ⇝ N1 -> Σ ;;; Γ |- tProd na M1 M2 ⇝ tProd na N1 M2
| prod_red_r na M2 N2 M1 : Σ ;;; Γ ,, vass na M1 |- M2 ⇝ N2 ->
                           Σ ;;; Γ |- tProd na M1 M2 ⇝ tProd na M1 N2

| evar_red ev l l' : OnOne2 (fun t u => Σ ;;; Γ |- t ⇝ u) l l' -> Σ ;;; Γ |- tEvar ev l ⇝ tEvar ev l'

| fix_red_ty mfix0 mfix1 idx :
    OnOne2 (on_Trel_eq (fun t u => Σ ;;; Γ |- t ⇝ u) dtype (fun x => (dname x, dbody x, rarg x))) mfix0 mfix1 ->
    Σ ;;; Γ |- tFix mfix0 idx ⇝ tFix mfix1 idx

| fix_red_body mfix0 mfix1 idx :
    OnOne2 (on_Trel_eq (fun t u => Σ ;;; Γ ,,, fix_context mfix0 |- t ⇝ u) dbody (fun x => (dname x, dtype x, rarg x)))
           mfix0 mfix1 ->
    Σ ;;; Γ |- tFix mfix0 idx ⇝ tFix mfix1 idx

| cofix_red_ty mfix0 mfix1 idx :
    OnOne2 (on_Trel_eq (fun t u => Σ ;;; Γ |- t ⇝ u) dtype (fun x => (dname x, dbody x, rarg x))) mfix0 mfix1 ->
    Σ ;;; Γ |- tCoFix mfix0 idx ⇝ tCoFix mfix1 idx

| cofix_red_body mfix0 mfix1 idx :
    OnOne2 (on_Trel_eq (fun t u => Σ ;;; Γ ,,, fix_context mfix0 |- t ⇝ u) dbody (fun x => (dname x, dtype x, rarg x))) mfix0 mfix1 ->
    Σ ;;; Γ |- tCoFix mfix0 idx ⇝ tCoFix mfix1 idx

| array_red_val arr value :
    OnOne2 (fun t u => Σ ;;; Γ |- t ⇝ u) arr.(array_value) value ->
    Σ ;;; Γ |- tPrim (primArray; primArrayModel arr) ⇝
               tPrim (primArray; primArrayModel (set_array_value arr value))

| array_red_def arr def :
    Σ ;;; Γ |- arr.(array_default) ⇝ def ->
    Σ ;;; Γ |- tPrim (primArray; primArrayModel arr) ⇝
               tPrim (primArray; primArrayModel (set_array_default arr def))

| array_red_type arr ty :
    Σ ;;; Γ |- arr.(array_type) ⇝ ty ->
    Σ ;;; Γ |- tPrim (primArray; primArrayModel arr) ⇝
          tPrim (primArray; primArrayModel (set_array_type arr ty))

where " Σ ;;; Γ |- t ⇝ u " := (red1 Σ Γ t u).

Definition red1_ctx Σ := (OnOne2_local_env (fun Δ => on_one_decl (fun t t' => red1 Σ Δ t t'))).

Definition red Σ Γ := clos_refl_trans (fun t u : term => Σ;;; Γ |- t ⇝ u).
Module Export PCUICCumulativitySpec.

Implicit Types (cf : checker_flags).

Definition cumul_predicate (cumul : context -> term -> term -> Type) cumul_universe Γ p p' :=
  All2 (cumul Γ) p.(pparams) p'.(pparams) ×
  cmp_universe_instance cumul_universe p.(puinst) p'.(puinst) ×
  eq_context_upto_names p.(pcontext) p'.(pcontext) ×
  cumul (Γ ,,, inst_case_predicate_context p) p.(preturn) p'.(preturn).

Definition cumul_branch (cumul_term : context -> term -> term -> Type) Γ p br br' :=
  eq_context_upto_names br.(bcontext) br'.(bcontext) ×
  cumul_term (Γ ,,, inst_case_branch_context p br) br.(bbody) br'.(bbody).

Definition cumul_branches cumul_term Γ p brs brs' := All2 (cumul_branch cumul_term Γ p) brs brs'.

Definition cumul_mfixpoint (cumul_term : context -> term -> term -> Type) Γ mfix mfix' :=
  All2 (fun d d' =>
    cumul_term Γ d.(dtype) d'.(dtype) ×
    cumul_term (Γ ,,, fix_context mfix) d.(dbody) d'.(dbody) ×
    d.(rarg) = d'.(rarg) ×
    eq_binder_annot d.(dname) d'.(dname)
  ) mfix mfix'.

Reserved Notation " Σ ;;; Γ ⊢ t ≤s[ pb ] u" (at level 50, Γ, t, u at next level,
  format "Σ  ;;;  Γ  ⊢  t  ≤s[ pb ]  u").

Definition cumul_Ind_univ {cf} (Σ : global_env_ext) pb i napp :=
  cmp_global_instance Σ (compare_universe Σ) pb (IndRef i) napp.

Definition cumul_Construct_univ {cf} (Σ : global_env_ext) pb  i k napp :=
  cmp_global_instance Σ (compare_universe Σ) pb (ConstructRef i k) napp.
Inductive cumulSpec0 {cf : checker_flags} (Σ : global_env_ext) Γ (pb : conv_pb) : term -> term -> Type :=

| cumul_Trans : forall t u v,
    is_closed_context Γ -> is_open_term Γ u ->
    Σ ;;; Γ ⊢ t ≤s[pb] u ->
    Σ ;;; Γ ⊢ u ≤s[pb] v ->
    Σ ;;; Γ ⊢ t ≤s[pb] v

| cumul_Sym : forall t u,
    Σ ;;; Γ ⊢ t ≤s[Conv] u ->
    Σ ;;; Γ ⊢ u ≤s[pb] t

| cumul_Refl : forall t,
    Σ ;;; Γ ⊢ t ≤s[pb] t

| cumul_Ind : forall i u u' args args',
    cumul_Ind_univ Σ pb i #|args| u u' ->
    All2 (fun t u => Σ ;;; Γ ⊢ t ≤s[Conv] u) args args' ->
    Σ ;;; Γ ⊢ mkApps (tInd i u) args ≤s[pb] mkApps (tInd i u') args'

| cumul_Construct : forall i k u u' args args',
    cumul_Construct_univ Σ pb i k #|args| u u' ->
    All2 (fun t u => Σ ;;; Γ ⊢ t ≤s[Conv] u) args args' ->
    Σ ;;; Γ ⊢ mkApps (tConstruct i k u) args ≤s[pb] mkApps (tConstruct i k u') args'

| cumul_Sort : forall s s',
    compare_sort Σ pb s s' ->
    Σ ;;; Γ ⊢ tSort s ≤s[pb] tSort s'

| cumul_Const : forall c u u',
    cmp_universe_instance (compare_universe Σ Conv) u u' ->
    Σ ;;; Γ ⊢ tConst c u ≤s[pb] tConst c u'

| cumul_Evar : forall e args args',
    All2 (fun t u => Σ ;;; Γ ⊢ t ≤s[Conv] u) args args' ->
    Σ ;;; Γ ⊢ tEvar e args ≤s[pb] tEvar e args'

| cumul_App : forall t t' u u',
    Σ ;;; Γ ⊢ t ≤s[pb] t' ->
    Σ ;;; Γ ⊢ u ≤s[Conv] u' ->
    Σ ;;; Γ ⊢ tApp t u ≤s[pb] tApp t' u'

| cumul_Lambda : forall na na' ty ty' t t',
    eq_binder_annot na na' ->
    Σ ;;; Γ ⊢ ty ≤s[Conv] ty' ->
    Σ ;;; Γ ,, vass na ty ⊢ t ≤s[Conv] t' ->
    Σ ;;; Γ ⊢ tLambda na ty t ≤s[pb] tLambda na' ty' t'

| cumul_Prod : forall na na' a a' b b',
    eq_binder_annot na na' ->
    Σ ;;; Γ ⊢ a ≤s[Conv] a' ->
    Σ ;;; Γ ,, vass na a ⊢ b ≤s[pb] b' ->
    Σ ;;; Γ ⊢ tProd na a b ≤s[pb] tProd na' a' b'

| cumul_LetIn : forall na na' t t' ty ty' u u',
    eq_binder_annot na na' ->
    Σ ;;; Γ ⊢ t ≤s[Conv] t' ->
    Σ ;;; Γ ⊢ ty ≤s[Conv] ty' ->
    Σ ;;; Γ ,, vdef na t ty ⊢ u ≤s[Conv] u' ->
    Σ ;;; Γ ⊢ tLetIn na t ty u ≤s[pb] tLetIn na' t' ty' u'

| cumul_Case indn : forall p p' c c' brs brs',
    cumul_predicate (fun Γ t u => Σ ;;; Γ ⊢ t ≤s[Conv] u) (compare_universe Σ Conv) Γ p p' ->
    Σ ;;; Γ ⊢ c ≤s[Conv] c' ->
    cumul_branches (fun Γ t u => Σ ;;; Γ ⊢ t ≤s[Conv] u) Γ p brs brs' ->
    Σ ;;; Γ ⊢ tCase indn p c brs ≤s[pb] tCase indn p' c' brs'

| cumul_Proj : forall p c c',
    Σ ;;; Γ ⊢ c ≤s[Conv] c' ->
    Σ ;;; Γ ⊢ tProj p c ≤s[pb] tProj p c'

| cumul_Fix : forall mfix mfix' idx,
    cumul_mfixpoint (fun Γ t u => Σ ;;; Γ ⊢ t ≤s[Conv] u) Γ mfix mfix' ->
    Σ ;;; Γ ⊢ tFix mfix idx ≤s[pb] tFix mfix' idx

| cumul_CoFix : forall mfix mfix' idx,
    cumul_mfixpoint (fun Γ t u => Σ ;;; Γ ⊢ t ≤s[Conv] u) Γ mfix mfix' ->
    Σ ;;; Γ ⊢ tCoFix mfix idx ≤s[pb] tCoFix mfix' idx

| cumul_Prim p p' :
  onPrims (fun x y => Σ ;;; Γ ⊢ x ≤s[Conv] y) (compare_universe Σ Conv) p p' ->
  Σ ;;; Γ ⊢ tPrim p ≤s[pb] tPrim p'

| cumul_beta : forall na t b a,
    Σ ;;; Γ ⊢ tApp (tLambda na t b) a ≤s[pb] b {0 := a}

| cumul_zeta : forall na b t b',
    Σ ;;; Γ ⊢ tLetIn na b t b' ≤s[pb] b' {0 := b}

| cumul_rel i body :
    option_map decl_body (nth_error Γ i) = Some (Some body) ->
    Σ ;;; Γ ⊢ tRel i ≤s[pb] lift0 (S i) body

| cumul_iota : forall ci c u args p brs br,
    nth_error brs c = Some br ->
    #|args| = (ci.(ci_npar) + context_assumptions br.(bcontext))%nat ->
    Σ ;;; Γ ⊢ tCase ci p (mkApps (tConstruct ci.(ci_ind) c u) args) brs  ≤s[pb] iota_red ci.(ci_npar) p args br

| cumul_fix : forall mfix idx args narg fn,
    unfold_fix mfix idx = Some (narg, fn) ->
    is_constructor narg args = true ->
    Σ ;;; Γ ⊢ mkApps (tFix mfix idx) args ≤s[pb] mkApps fn args

| cumul_cofix_case : forall ip p mfix idx args narg fn brs,
    unfold_cofix mfix idx = Some (narg, fn) ->
    Σ ;;; Γ ⊢ tCase ip p (mkApps (tCoFix mfix idx) args) brs ≤s[pb] tCase ip p (mkApps fn args) brs

| cumul_cofix_proj : forall p mfix idx args narg fn,
    unfold_cofix mfix idx = Some (narg, fn) ->
    Σ ;;; Γ ⊢ tProj p (mkApps (tCoFix mfix idx) args) ≤s[pb] tProj p (mkApps fn args)

| cumul_delta : forall c decl body (isdecl : declared_constant Σ c decl) u,
    decl.(cst_body) = Some body ->
    Σ ;;; Γ ⊢ tConst c u ≤s[pb] body@[u]

| cumul_proj : forall p args u arg,
    nth_error args (p.(proj_npars) + p.(proj_arg)) = Some arg ->
    Σ ;;; Γ ⊢ tProj p (mkApps (tConstruct p.(proj_ind) 0 u) args) ≤s[pb] arg

where " Σ ;;; Γ ⊢ t ≤s[ pb ] u " := (@cumulSpec0 _ Σ Γ pb t u) : type_scope.
Definition cumulSpec `{checker_flags} (Σ : global_env_ext) Γ := cumulSpec0 Σ Γ Cumul.

Notation " Σ ;;; Γ |- t <=s u " := (@cumulSpec _ Σ Γ t u) (at level 50, Γ, t, u at next level).

Module PCUICConversionParSpec <: EnvironmentTyping.ConversionParSig PCUICTerm PCUICEnvironment PCUICTermUtils PCUICEnvTyping.
End PCUICConversionParSpec.

End PCUICCumulativitySpec.

Implicit Types (cf : checker_flags) (Σ : global_env_ext).

Definition type_of_constructor mdecl (cdecl : constructor_body) (c : inductive * nat) (u : list Level.t) :=
  let mind := inductive_mind (fst c) in
  subst0 (inds mind u mdecl.(ind_bodies)) (subst_instance u (cstr_type cdecl)).

Include PCUICEnvTyping.

Inductive FixCoFix : Type := Fix | CoFix.

Class GuardChecker :=
{
  guard : FixCoFix -> global_env_ext -> context -> mfixpoint term -> Prop ;
}.

Axiom guard_checking : GuardChecker.
#[global]
Existing Instance guard_checking.

Definition fix_guard := guard Fix.
Definition cofix_guard := guard CoFix.

Definition destInd (t : term) :=
  match t with
  | tInd ind u => Some (ind, u)
  | _ => None
  end.

Definition isCoFinite (r : recursivity_kind) :=
  match r with
  | CoFinite => true
  | _ => false
  end.

Definition check_recursivity_kind
  (lookup: kername -> option global_decl) ind r :=
  match lookup ind with
  | Some (InductiveDecl mib) => ReflectEq.eqb mib.(ind_finite) r
  | _ => false
  end.

Definition check_one_fix d :=
  let '{| dname := na;
         dtype := ty;
         dbody := b;
         rarg := arg |} := d in
  let '(ctx, ty) := decompose_prod_assum [] ty in
  match nth_error (List.rev (smash_context [] ctx)) arg with
  | Some argd =>
    let (hd, args) := decompose_app argd.(decl_type) in
    match destInd hd with
    | Some (mkInd mind _, u) => Some mind
    | None => None
    end
  | None => None
  end.

Definition wf_fixpoint_gen
  (lookup: kername -> option global_decl) mfix :=
  forallb (isLambda ∘ dbody) mfix &&
  let checks := map check_one_fix mfix in
  match map_option_out checks with
  | Some (ind :: inds) =>

    forallb (eqb ind) inds &&
    check_recursivity_kind lookup ind Finite
  | _ => false
  end.

Definition wf_fixpoint (Σ : global_env) := wf_fixpoint_gen (lookup_env Σ).

Definition check_one_cofix d :=
  let '{| dname := na;
         dtype := ty;
         dbody := b;
         rarg := arg |} := d in
  let '(ctx, ty) := decompose_prod_assum [] ty in
  let (hd, args) := decompose_app ty in
  match destInd hd with
  | Some (mkInd ind _, u) => Some ind
  | None => None
  end.

Definition wf_cofixpoint_gen
  (lookup: kername -> option global_decl) mfix :=
  let checks := map check_one_cofix mfix in
  match map_option_out checks with
  | Some (ind :: inds) =>

    forallb (eqb ind) inds &&
    check_recursivity_kind lookup ind CoFinite
  | _ => false
  end.

Definition wf_cofixpoint (Σ : global_env) := wf_cofixpoint_gen (lookup_env Σ).

Reserved Notation "'wf_local' Σ Γ " (at level 9, Σ, Γ at next level).

Reserved Notation " Σ ;;; Γ |- t : T " (at level 50, Γ, t, T at next level).

Variant case_side_conditions `{checker_flags} wf_local_fun typing Σ Γ ci p ps mdecl idecl indices predctx :=
| case_side_info
    (eq_npars : mdecl.(ind_npars) = ci.(ci_npar))
    (wf_pred : wf_predicate mdecl idecl p)
    (cons : consistent_instance_ext Σ (ind_universes mdecl) p.(puinst))
    (wf_pctx : wf_local_fun Σ (Γ ,,, predctx))

    (conv_pctx : eq_context_upto_names p.(pcontext) (ind_predicate_context ci.(ci_ind) mdecl idecl))
    (allowed_elim : is_allowed_elimination Σ idecl.(ind_kelim) ps)
    (elim_relevance : isSortRel ps ci.(ci_relevance))
    (ind_inst : ctx_inst (typing Σ) Γ (p.(pparams) ++ indices)
                         (List.rev (subst_instance p.(puinst)
                                                   (ind_params mdecl ,,, ind_indices idecl : context))))
    (not_cofinite : isCoFinite mdecl.(ind_finite) = false).

Variant case_branch_typing `{checker_flags} wf_local_fun typing Σ Γ (ci:case_info) p ps mdecl idecl ptm  brs :=
| case_branch_info
    (wf_brs : wf_branches idecl brs)
    (brs_ty :
       All2i (fun i cdecl br =>

                eq_context_upto_names br.(bcontext) (cstr_branch_context ci mdecl cdecl) ×
                let brctxty := case_branch_type ci.(ci_ind) mdecl idecl p br ptm i cdecl in
                (wf_local_fun Σ (Γ ,,, brctxty.1) ×
                ((typing Σ (Γ ,,, brctxty.1) br.(bbody) (brctxty.2)) ×
                (typing Σ (Γ ,,, brctxty.1) brctxty.2 (tSort ps)))))
             0 idecl.(ind_ctors) brs).

Variant primitive_typing_hyps `{checker_flags}
  (typing : forall (Σ : global_env_ext) (Γ : context), term -> term -> Type)
  Σ Γ : prim_val term -> Type :=
| prim_int_hyps i : primitive_typing_hyps typing Σ Γ (primInt; primIntModel i)
| prim_float_hyps f : primitive_typing_hyps typing Σ Γ (primFloat; primFloatModel f)
| prim_string_hyps s : primitive_typing_hyps typing Σ Γ (primString; primStringModel s)
| prim_array_hyps a
  (wfl : wf_universe Σ (Universe.make' a.(array_level)))
  (hty : typing Σ Γ a.(array_type) (tSort (sType (Universe.make' a.(array_level)))))
  (hdef : typing Σ Γ a.(array_default) a.(array_type))
  (hvalue : All (fun x => typing Σ Γ x a.(array_type)) a.(array_value)) :
  primitive_typing_hyps typing Σ Γ (primArray; primArrayModel a).

Equations prim_type (p : prim_val term) (cst : kername) : term :=
prim_type (primInt; _) cst := tConst cst [];
prim_type (primFloat; _) cst := tConst cst [];
prim_type (primString; _) cst := tConst cst [];
prim_type (primArray; primArrayModel a) cst := tApp (tConst cst [a.(array_level)]) a.(array_type).

Inductive typing `{checker_flags} (Σ : global_env_ext) (Γ : context) : term -> term -> Type :=
| type_Rel : forall n decl,
    wf_local Σ Γ ->
    nth_error Γ n = Some decl ->
    Σ ;;; Γ |- tRel n : lift0 (S n) decl.(decl_type)

| type_Sort : forall s,
    wf_local Σ Γ ->
    wf_sort Σ s ->
    Σ ;;; Γ |- tSort s : tSort (Sort.super s)

| type_Prod : forall na A B s1 s2,
    lift_typing typing Σ Γ (j_vass_s na A s1) ->
    Σ ;;; Γ ,, vass na A |- B : tSort s2 ->
    Σ ;;; Γ |- tProd na A B : tSort (Sort.sort_of_product s1 s2)

| type_Lambda : forall na A t B,
    lift_typing typing Σ Γ (j_vass na A) ->
    Σ ;;; Γ ,, vass na A |- t : B ->
    Σ ;;; Γ |- tLambda na A t : tProd na A B

| type_LetIn : forall na b B t A,
    lift_typing typing Σ Γ (j_vdef na b B) ->
    Σ ;;; Γ ,, vdef na b B |- t : A ->
    Σ ;;; Γ |- tLetIn na b B t : tLetIn na b B A

| type_App : forall t na A B s u,

    Σ ;;; Γ |- tProd na A B : tSort s ->
    Σ ;;; Γ |- t : tProd na A B ->
    Σ ;;; Γ |- u : A ->
    Σ ;;; Γ |- tApp t u : B{0 := u}

| type_Const : forall cst u decl,
    wf_local Σ Γ ->
    declared_constant Σ cst decl ->
    consistent_instance_ext Σ decl.(cst_universes) u ->
    Σ ;;; Γ |- tConst cst u : decl.(cst_type)@[u]

| type_Ind : forall ind u mdecl idecl,
    wf_local Σ Γ ->
    declared_inductive Σ ind mdecl idecl ->
    consistent_instance_ext Σ mdecl.(ind_universes) u ->
    Σ ;;; Γ |- tInd ind u : idecl.(ind_type)@[u]

| type_Construct : forall ind i u mdecl idecl cdecl,
    wf_local Σ Γ ->
    declared_constructor Σ (ind, i) mdecl idecl cdecl ->
    consistent_instance_ext Σ mdecl.(ind_universes) u ->
    Σ ;;; Γ |- tConstruct ind i u : type_of_constructor mdecl cdecl (ind, i) u

| type_Case : forall ci p c brs indices ps mdecl idecl,
    let predctx := case_predicate_context ci.(ci_ind) mdecl idecl p in
    let ptm := it_mkLambda_or_LetIn predctx p.(preturn) in
    declared_inductive Σ ci.(ci_ind) mdecl idecl ->
    Σ ;;; Γ ,,, predctx |- p.(preturn) : tSort ps ->
    Σ ;;; Γ |- c : mkApps (tInd ci.(ci_ind) p.(puinst)) (p.(pparams) ++ indices) ->
    case_side_conditions (fun Σ Γ => wf_local Σ Γ) typing Σ Γ ci p ps
                         mdecl idecl indices predctx  ->
    case_branch_typing (fun Σ Γ => wf_local Σ Γ) typing Σ Γ ci p ps
                        mdecl idecl ptm brs ->
    Σ ;;; Γ |- tCase ci p c brs : mkApps ptm (indices ++ [c])

| type_Proj : forall p c u mdecl idecl cdecl pdecl args,
    declared_projection Σ p mdecl idecl cdecl pdecl ->
    Σ ;;; Γ |- c : mkApps (tInd p.(proj_ind) u) args ->
    #|args| = ind_npars mdecl ->
    Σ ;;; Γ |- tProj p c : subst0 (c :: List.rev args) pdecl.(proj_type)@[u]

| type_Fix : forall mfix n decl,
    wf_local Σ Γ ->
    fix_guard Σ Γ mfix ->
    nth_error mfix n = Some decl ->
    All (on_def_type (lift_typing1 (typing Σ)) Γ) mfix ->
    All (on_def_body (lift_typing1 (typing Σ)) (fix_context mfix) Γ) mfix ->
    wf_fixpoint Σ mfix ->
    Σ ;;; Γ |- tFix mfix n : decl.(dtype)

| type_CoFix : forall mfix n decl,
    wf_local Σ Γ ->
    cofix_guard Σ Γ mfix ->
    nth_error mfix n = Some decl ->
    All (on_def_type (lift_typing1 (typing Σ)) Γ) mfix ->
    All (on_def_body (lift_typing1 (typing Σ)) (fix_context mfix) Γ) mfix ->
    wf_cofixpoint Σ mfix ->
    Σ ;;; Γ |- tCoFix mfix n : decl.(dtype)

| type_Prim p prim_ty cdecl :
    wf_local Σ Γ ->
    primitive_constant Σ (prim_val_tag p) = Some prim_ty ->
    declared_constant Σ prim_ty cdecl ->
    primitive_invariants (prim_val_tag p) cdecl ->
    primitive_typing_hyps typing Σ Γ p ->
    Σ ;;; Γ |- tPrim p : prim_type p prim_ty

| type_Cumul : forall t A B s,
    Σ ;;; Γ |- t : A ->
    Σ ;;; Γ |- B : tSort s ->
    Σ ;;; Γ |- A <=s B ->
    Σ ;;; Γ |- t : B

where " Σ ;;; Γ |- t : T " := (typing Σ Γ t T)
and "'wf_local' Σ Γ " := (All_local_env (lift_typing1 (typing Σ)) Γ).

Definition wf `{checker_flags} := on_global_env cumulSpec0 (lift_typing typing).
Notation on_contexts_length := All2_fold_length.
Import Stdlib.Classes.CRelationClasses.

Definition ws_term P := { t : term | on_free_vars P t }.
Definition ws_term_proj {P} (t : ws_term P) : term.
admit.
Defined.
Coercion ws_term_proj : ws_term >-> term.

Definition ws_context P := { t : context | on_free_vars_ctx P t }.

Notation closed_context := (ws_context xpred0).
Notation open_term Γ := (ws_term (shiftnP #|Γ| xpred0)).
Definition ws_context_proj' {P} (t : ws_context P) : list context_decl.
Admitted.
Coercion ws_context_proj' : ws_context >-> list.

Definition ws_red1 Σ P (Γ : ws_context P) (t u : ws_term (shiftnP #|Γ| P)) :=
  red1 Σ Γ t u.

Definition ws_red Σ P (Γ : ws_context P) := clos_refl_trans (ws_red1 Σ P Γ).

Definition ws_pair :=
  ∑ Γ : ws_context xpred0, ws_term (shiftnP #|Γ| xpred0).

Section RedConfluence.
  Context {cf : checker_flags}.
  Context {Σ : global_env_ext} (wfΣ : wf Σ).
Definition red1_rel_alpha : relation ws_pair.
exact (relation_disjunction (A:=ws_pair) (fun '(Γ; t) '(Δ; u) => (red1 Σ Γ t u * (Γ = Δ)))%type
     (relation_disjunction (A:=ws_pair)
        (fun '(Γ; t) '(Δ; u) => ((red1_ctx Σ Γ Δ * (t = u :> term))))
        (fun '(Γ; t) '(Δ; u) => ((eq_context_upto_names Γ Δ * (t = u :> term)))))%type).
Defined.

  Lemma red_ws_red (Γ : closed_context) (x y : ws_term (shiftnP #|Γ| xpred0)) :
    red Σ Γ x y -> ws_red Σ xpred0 Γ x y.
Admitted.
Definition transport_ws_term {n m : nat} (t : ws_term (shiftnP n xpred0)) (eq : n = m) : ws_term (shiftnP m xpred0).
Admitted.
Definition red_ctx_alpha : relation context.
exact (All2_fold (fun Γ _ => All_decls_alpha (red Σ Γ))).
Defined.

  Instance red_ctx_alpha_refl : Reflexive red_ctx_alpha.
Admitted.

  Lemma ws_red_refl_irrel P (Γ : ws_context P) (x y : ws_term (shiftnP #|Γ| P)) :
    x = y :> term ->
    ws_red Σ P Γ x y.
Admitted.

  Lemma clos_rt_red1_alpha_out x y :
    clos_refl_trans red1_rel_alpha x y ->
    ∑ redctx : red_ctx_alpha x.π1 y.π1,
      ws_red Σ xpred0 x.π1 x.π2 (transport_ws_term y.π2 (symmetry (All2_fold_length redctx))).
  Proof using wfΣ.
    intros H.
    eapply clos_rt_rt1n_iff in H.
    induction H.
    -
 unshelve eexists.
reflexivity.
eapply ws_red_refl_irrel => //.
    -
 destruct x as [Γ t], y as [Δ u], z as [Δ' u']; simpl in *.
      destruct IHclos_refl_trans_1n.
      red in r.
destruct r.
      *
 destruct p.
subst.
exists x.
        transitivity u; auto.
        now eapply red_ws_red.
      *
 destruct t as [t ht], u as [u hu];
        move: r; case; move => [] r eq; noconf eq.
🛠️ Intermediate Coq File (useful for debugging if minimization did not go as far as you wanted)
🛠️ 📜 Intermediate Coq File log (useful for debugging if minimization did not go as far as you wanted)
📜 Build Log (contains the Coq error message) (truncated to last 8.0KiB; full 7.0MiB file on GitHub Actions Artifacts under build.log)
t-minimizer.vWHQ3xyoaN
MINIMIZER_DEBUG: files: 
make[2]: Leaving directory '/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/template-rocq'
# Ensure the cmxs is built before the loader file 
make -f Makefile.plugin gen-src/metarocq_template_plugin.cmxs
make[2]: Entering directory '/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/template-rocq'
MINIMIZER_DEBUG_EXTRA: coqc: /github/workspace/builds/coq/coq-failing/_install_ci/bin///rocq
MINIMIZER_DEBUG_EXTRA: original invocation: c --print-version 
MINIMIZER_DEBUG_EXTRA: new invocation: /github/workspace/builds/coq/coq-failing/_install_ci/bin/rocq.orig c --print-version 
MINIMIZER_DEBUG_EXTRA: coqpath: 
MINIMIZER_DEBUG_EXTRA: ocamlpath: /github/workspace/builds/coq/coq-failing/_build_ci/metarocq/template-rocq/:/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/safechecker-plugin/src:/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/erasure-plugin/src:/github/workspace/builds/coq/coq-failing/_install_ci/lib:
MINIMIZER_DEBUG_EXTRA: pwd: PWD=/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/template-rocq
MINIMIZER_DEBUG_EXTRA: exec: /github/workspace/builds/coq/coq-failing/_install_ci/bin/rocq.orig c --print-version 
MINIMIZER_DEBUG_EXTRA: coqlib: Warning: Deprecated environment variable COQLIB, use ROCQLIB instead.
/github/workspace/builds/coq/coq-failing/_install_ci/lib/coq//
MINIMIZER_DEBUG: info: /tmp/tmp-coqbot-minimizer.xOHuAT6TY6
MINIMIZER_DEBUG: files: 
make[2]: 'gen-src/metarocq_template_plugin.cmxs' is up to date.
make[2]: Leaving directory '/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/template-rocq'
make -f Makefile.plugin
make[2]: Entering directory '/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/template-rocq'
MINIMIZER_DEBUG_EXTRA: coqc: /github/workspace/builds/coq/coq-failing/_install_ci/bin///rocq
MINIMIZER_DEBUG_EXTRA: original invocation: c --print-version 
MINIMIZER_DEBUG_EXTRA: new invocation: /github/workspace/builds/coq/coq-failing/_install_ci/bin/rocq.orig c --print-version 
MINIMIZER_DEBUG_EXTRA: coqpath: 
MINIMIZER_DEBUG_EXTRA: ocamlpath: /github/workspace/builds/coq/coq-failing/_build_ci/metarocq/template-rocq/:/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/safechecker-plugin/src:/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/erasure-plugin/src:/github/workspace/builds/coq/coq-failing/_install_ci/lib:
MINIMIZER_DEBUG_EXTRA: pwd: PWD=/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/template-rocq
MINIMIZER_DEBUG_EXTRA: exec: /github/workspace/builds/coq/coq-failing/_install_ci/bin/rocq.orig c --print-version 
MINIMIZER_DEBUG_EXTRA: coqlib: Warning: Deprecated environment variable COQLIB, use ROCQLIB instead.
/github/workspace/builds/coq/coq-failing/_install_ci/lib/coq//
MINIMIZER_DEBUG: info: /tmp/tmp-coqbot-minimizer.DGZJIKvvh5
MINIMIZER_DEBUG: files: 
MINIMIZER_DEBUG_EXTRA: coqc: /github/workspace/builds/coq/coq-failing/_install_ci/bin/////rocq
MINIMIZER_DEBUG_EXTRA: original invocation: c --print-version 
MINIMIZER_DEBUG_EXTRA: new invocation: /github/workspace/builds/coq/coq-failing/_install_ci/bin/rocq.orig c --print-version 
MINIMIZER_DEBUG_EXTRA: coqpath: 
MINIMIZER_DEBUG_EXTRA: ocamlpath: /github/workspace/builds/coq/coq-failing/_build_ci/metarocq/template-rocq/:/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/safechecker-plugin/src:/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/erasure-plugin/src:/github/workspace/builds/coq/coq-failing/_install_ci/lib:
MINIMIZER_DEBUG_EXTRA: pwd: PWD=/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/template-rocq
MINIMIZER_DEBUG_EXTRA: exec: /github/workspace/builds/coq/coq-failing/_install_ci/bin/rocq.orig c --print-version 
MINIMIZER_DEBUG_EXTRA: coqlib: Warning: Deprecated environment variable COQLIB, use ROCQLIB instead.
/github/workspace/builds/coq/coq-failing/_install_ci/lib/coq//
MINIMIZER_DEBUG: info: /tmp/tmp-coqbot-minimizer.jXkzyKao3D
MINIMIZER_DEBUG: files: 
MINIMIZER_DEBUG_EXTRA: coqc: /github/workspace/builds/coq/coq-failing/_install_ci/bin/////rocq
MINIMIZER_DEBUG_EXTRA: original invocation: c --print-version 
MINIMIZER_DEBUG_EXTRA: new invocation: /github/workspace/builds/coq/coq-failing/_install_ci/bin/rocq.orig c --print-version 
MINIMIZER_DEBUG_EXTRA: coqpath: 
MINIMIZER_DEBUG_EXTRA: ocamlpath: /github/workspace/builds/coq/coq-failing/_build_ci/metarocq/template-rocq/:/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/safechecker-plugin/src:/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/erasure-plugin/src:/github/workspace/builds/coq/coq-failing/_install_ci/lib:
MINIMIZER_DEBUG_EXTRA: pwd: PWD=/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/template-rocq
MINIMIZER_DEBUG_EXTRA: exec: /github/workspace/builds/coq/coq-failing/_install_ci/bin/rocq.orig c --print-version 
MINIMIZER_DEBUG_EXTRA: coqlib: Warning: Deprecated environment variable COQLIB, use ROCQLIB instead.
/github/workspace/builds/coq/coq-failing/_install_ci/lib/coq//
MINIMIZER_DEBUG: info: /tmp/tmp-coqbot-minimizer.fpJ0htN5X2
MINIMIZER_DEBUG: files: 
make[3]: Nothing to be done for 'real-all'.
MINIMIZER_DEBUG_EXTRA: coqc: /github/workspace/builds/coq/coq-failing/_install_ci/bin/////rocq
MINIMIZER_DEBUG_EXTRA: original invocation: c --print-version 
MINIMIZER_DEBUG_EXTRA: new invocation: /github/workspace/builds/coq/coq-failing/_install_ci/bin/rocq.orig c --print-version 
MINIMIZER_DEBUG_EXTRA: coqpath: 
MINIMIZER_DEBUG_EXTRA: ocamlpath: /github/workspace/builds/coq/coq-failing/_build_ci/metarocq/template-rocq/:/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/safechecker-plugin/src:/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/erasure-plugin/src:/github/workspace/builds/coq/coq-failing/_install_ci/lib:
MINIMIZER_DEBUG_EXTRA: pwd: PWD=/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/template-rocq
MINIMIZER_DEBUG_EXTRA: exec: /github/workspace/builds/coq/coq-failing/_install_ci/bin/rocq.orig c --print-version 
MINIMIZER_DEBUG_EXTRA: coqlib: Warning: Deprecated environment variable COQLIB, use ROCQLIB instead.
/github/workspace/builds/coq/coq-failing/_install_ci/lib/coq//
MINIMIZER_DEBUG: info: /tmp/tmp-coqbot-minimizer.g7XENOftSc
MINIMIZER_DEBUG: files: 
make[2]: Leaving directory '/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/template-rocq'
make[1]: Leaving directory '/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/template-rocq'
File "./theories/PCUICConfluence.v", line 3649, characters 47-49:
Error: Cannot infer the implicit parameter A of eq whose type is 
"Type" in
environment:
cf : checker_flags
Σ : global_env_ext
wfΣ : wf Σ
Γ : closed_context
t : term
ht : is_open_term Γ t
Δ : closed_context
u : term
hu : is_open_term Δ u
Δ' : closed_context
u' : open_term Δ'
H : clos_refl_trans_1n red1_rel_alpha (Δ; exist u hu) (Δ'; u')
x : red_ctx_alpha Δ Δ'
w :
  ws_red Σ xpred0 Δ (exist u hu)
    (transport_ws_term u' (symmetry (on_contexts_length x)))
r : red1_ctx Σ Γ Δ
eq : exist t ht = exist u hu

Command exited with non-zero status 1
theories/PCUICConfluence.vo (real: 47.15, user: 46.75, sys: 0.39, mem: 2429600 ko)
make[3]: *** [Makefile.rocq:814: theories/PCUICConfluence.vo] Error 1
make[3]: *** [theories/PCUICConfluence.vo] Deleting file 'theories/PCUICConfluence.glob'
make[2]: *** [Makefile.rocq:412: all] Error 2
make[2]: Leaving directory '/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/pcuic'
make[1]: *** [Makefile:11: coq] Error 2
make[1]: Leaving directory '/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/pcuic'
make: *** [Makefile:149: pcuic] Error 2
+ code=2
+ printf '\n%s exit code: %s\n' metarocq 2
+ '[' metarocq '!=' stdlib_test ']'
+ echo 'Aggregating timing log...'
Aggregating timing log...
+ echo

+ tools/make-one-time-file.py --real metarocq.log
    Time |   Peak Mem | File Name            
---------------------------------------------
0m47.15s | 2429600 ko | Total Time / Peak Mem
---------------------------------------------
0m47.15s | 2429600 ko | PCUICConfluence.vo   
+ '[' '' ']'
+ exit 2
/github/workspace/builds/coq /github/workspace
::endgroup::
📜 🔎 Minimization Log (truncated to last 8.0KiB; full 5.2MiB file on GitHub Actions Artifacts under bug.log)
ector,warn-library-file,user-warn,default]
File "/tmp/tmpathbuqz5/Top/bug_01.v", line 206, characters 0-34:
Warning: Using Vector.t is known to be technically difficult, see
<https://github.com/coq/stdlib/blob/master/theories/Vectors/Vector.v>.
[warn-library-file-stdlib-vector,stdlib-vector,warn-library-file,user-warn,default]
File "/tmp/tmpathbuqz5/Top/bug_01.v", line 207, characters 0-32:
Warning: Using Vector.t is known to be technically difficult, see
<https://github.com/coq/stdlib/blob/master/theories/Vectors/Vector.v>.
[warn-library-file-stdlib-vector,stdlib-vector,warn-library-file,user-warn,default]
File "/tmp/tmpathbuqz5/Top/bug_01.v", line 208, characters 0-30:
Warning: Using Vector.t is known to be technically difficult, see
<https://github.com/coq/stdlib/blob/master/theories/Vectors/Vector.v>.
[warn-library-file-stdlib-vector,stdlib-vector,warn-library-file,user-warn,default]
File "/tmp/tmpathbuqz5/Top/bug_01.v", line 209, characters 0-31:
Warning: Library File Stdlib.Vectors.Bvector is deprecated since 8.20.
Consider [list bool] instead. See <https://github.com/coq/stdlib/blob/master/theories/Vectors/Vector.v> for details. Please open an issue if you would like to keep using Bvector.
[deprecated-library-file-since-8.20,deprecated-since-8.20,deprecated-library-file,deprecated,default]
File "/tmp/tmpathbuqz5/Top/bug_01.v", line 239, characters 7-20:
Warning: Coq.Init.Ltac has been replaced by Corelib.Init.Ltac.
[deprecated-dirpath-Coq,deprecated-since-9.0,deprecated,default]
File "/tmp/tmpathbuqz5/Top/bug_01.v", line 452, characters 0-13:
Error: Signature components for field eq do not match:
the body of definitions differs.


�[93mIntermediate code not saved.�[0m
Failed to do everything at once; trying one at a time.
Admitting definitions unsuccessful.
No successful changes.

I will now attempt to admit lemmas with admit. Defined with Proof using

Non-fatal error: Failed to admit lemmas and preserve the error.  
The new error was:
Deprecated environment variable COQCORELIB, use ROCQRUNTIMELIB instead.
Warning: Deprecated environment variable COQCORELIB,
use ROCQRUNTIMELIB instead.
[deprecated-coq-env-var,deprecated-since-9.0,deprecated,default]
File "/tmp/tmp2tzzlmz5/Top/bug_01.v", line 204, characters 0-27:
Warning: Alternatives to Fin.t are available, see
<https://github.com/coq/stdlib/blob/master/theories/Vectors/Fin.v>.
[warn-library-file-stdlib-vector,stdlib-vector,warn-library-file,user-warn,default]
File "/tmp/tmp2tzzlmz5/Top/bug_01.v", line 205, characters 0-33:
Warning: Using Vector.t is known to be technically difficult, see
<https://github.com/coq/stdlib/blob/master/theories/Vectors/Vector.v>.
[warn-library-file-stdlib-vector,stdlib-vector,warn-library-file,user-warn,default]
File "/tmp/tmp2tzzlmz5/Top/bug_01.v", line 206, characters 0-34:
Warning: Using Vector.t is known to be technically difficult, see
<https://github.com/coq/stdlib/blob/master/theories/Vectors/Vector.v>.
[warn-library-file-stdlib-vector,stdlib-vector,warn-library-file,user-warn,default]
File "/tmp/tmp2tzzlmz5/Top/bug_01.v", line 207, characters 0-32:
Warning: Using Vector.t is known to be technically difficult, see
<https://github.com/coq/stdlib/blob/master/theories/Vectors/Vector.v>.
[warn-library-file-stdlib-vector,stdlib-vector,warn-library-file,user-warn,default]
File "/tmp/tmp2tzzlmz5/Top/bug_01.v", line 208, characters 0-30:
Warning: Using Vector.t is known to be technically difficult, see
<https://github.com/coq/stdlib/blob/master/theories/Vectors/Vector.v>.
[warn-library-file-stdlib-vector,stdlib-vector,warn-library-file,user-warn,default]
File "/tmp/tmp2tzzlmz5/Top/bug_01.v", line 209, characters 0-31:
Warning: Library File Stdlib.Vectors.Bvector is deprecated since 8.20.
Consider [list bool] instead. See <https://github.com/coq/stdlib/blob/master/theories/Vectors/Vector.v> for details. Please open an issue if you would like to keep using Bvector.
[deprecated-library-file-since-8.20,deprecated-since-8.20,deprecated-library-file,deprecated,default]
File "/tmp/tmp2tzzlmz5/Top/bug_01.v", line 239, characters 7-20:
Warning: Coq.Init.Ltac has been replaced by Corelib.Init.Ltac.
[deprecated-dirpath-Coq,deprecated-since-9.0,deprecated,default]
File "/tmp/tmp2tzzlmz5/Top/bug_01.v", line 462, characters 0-62:
Warning: Notation "_ <-> _" was already used in scope type_scope.
[notation-overridden,parsing,default]
File "/tmp/tmp2tzzlmz5/Top/bug_01.v", line 601, characters 0-45:
Warning: Declaring a scope implicitly is deprecated; use in advance an
explicit "Declare Scope type_scope2.".
[undeclared-scope,deprecated-since-8.10,deprecated,default]
Error: The section RedConfluence, module PCUICPrimitive, module
EnvironmentTyping, module Retroknowledge, module BasicAst, module
Equations_DOT_Type_DOT_Relation_WRAPPED and module String need to be closed.


�[93mIntermediate code not saved.�[0m
Failed to do everything at once; trying one at a time.
Admitting lemmas unsuccessful.
No successful changes.

I will now attempt to admit definitions with admit. Defined with Proof using

Non-fatal error: Failed to admit definitions and preserve the error.  
The new error was:
Deprecated environment variable COQCORELIB, use ROCQRUNTIMELIB instead.
Warning: Deprecated environment variable COQCORELIB,
use ROCQRUNTIMELIB instead.
[deprecated-coq-env-var,deprecated-since-9.0,deprecated,default]
File "/tmp/tmpfnoh8wu6/Top/bug_01.v", line 204, characters 0-27:
Warning: Alternatives to Fin.t are available, see
<https://github.com/coq/stdlib/blob/master/theories/Vectors/Fin.v>.
[warn-library-file-stdlib-vector,stdlib-vector,warn-library-file,user-warn,default]
File "/tmp/tmpfnoh8wu6/Top/bug_01.v", line 205, characters 0-33:
Warning: Using Vector.t is known to be technically difficult, see
<https://github.com/coq/stdlib/blob/master/theories/Vectors/Vector.v>.
[warn-library-file-stdlib-vector,stdlib-vector,warn-library-file,user-warn,default]
File "/tmp/tmpfnoh8wu6/Top/bug_01.v", line 206, characters 0-34:
Warning: Using Vector.t is known to be technically difficult, see
<https://github.com/coq/stdlib/blob/master/theories/Vectors/Vector.v>.
[warn-library-file-stdlib-vector,stdlib-vector,warn-library-file,user-warn,default]
File "/tmp/tmpfnoh8wu6/Top/bug_01.v", line 207, characters 0-32:
Warning: Using Vector.t is known to be technically difficult, see
<https://github.com/coq/stdlib/blob/master/theories/Vectors/Vector.v>.
[warn-library-file-stdlib-vector,stdlib-vector,warn-library-file,user-warn,default]
File "/tmp/tmpfnoh8wu6/Top/bug_01.v", line 208, characters 0-30:
Warning: Using Vector.t is known to be technically difficult, see
<https://github.com/coq/stdlib/blob/master/theories/Vectors/Vector.v>.
[warn-library-file-stdlib-vector,stdlib-vector,warn-library-file,user-warn,default]
File "/tmp/tmpfnoh8wu6/Top/bug_01.v", line 209, characters 0-31:
Warning: Library File Stdlib.Vectors.Bvector is deprecated since 8.20.
Consider [list bool] instead. See <https://github.com/coq/stdlib/blob/master/theories/Vectors/Vector.v> for details. Please open an issue if you would like to keep using Bvector.
[deprecated-library-file-since-8.20,deprecated-since-8.20,deprecated-library-file,deprecated,default]
File "/tmp/tmpfnoh8wu6/Top/bug_01.v", line 239, characters 7-20:
Warning: Coq.Init.Ltac has been replaced by Corelib.Init.Ltac.
[deprecated-dirpath-Coq,deprecated-since-9.0,deprecated,default]
File "/tmp/tmpfnoh8wu6/Top/bug_01.v", line 454, characters 0-13:
Error: Signature components for field eq do not match:
the body of definitions differs.


�[93mIntermediate code not saved.�[0m
Failed to do everything at once; trying one at a time.
Admitting definitions unsuccessful.
No successful changes.

I will now attempt to add Proof using lines
�[92m
Adding Proof using lines successful.�[0m
Failed to do everything at once; trying one at a time.
Adding Proof using lines unsuccessful.
No successful changes.

I will now attempt to export modules
Module exportation successful

I will now attempt to split imports and exports
Import/Export splitting successful

I will now attempt to split := definitions
One-line definition splitting successful

I will now attempt to remove all lines, one at a time

If you have any comments on your experience of the minimizer, please share them in a reply (possibly tagging @JasonGross).
If you believe there's a bug in the bug minimizer, please report it on the bug minimizer issue tracker.

Copy link
Contributor
coqbot-app bot commented May 28, 2025
Minimization interrupted by timeout, being automatically continued. Partially Minimized File /home/runner/work/run-coq-bug-minimizer/run-coq-bug-minimizer/builds/coq/coq-failing/_build_ci/metarocq/pcuic/theories/PCUICConfluence.v in 5h 15m 7s (from ci-metarocq) (interrupted by timeout, being automatically continued) (full log on GitHub Actions - verbose log)
⭐ ⏱️ Partially Minimized Coq File (timeout) (truncated to first and last 32KiB; full 106KiB file on GitHub Actions Artifacts under bug.v)
(* -*- mode: coq; coq-prog-args: ("-emacs" "-q" "-w" "-deprecated-native-compiler-option" "-native-compiler" "no" "-coqlib" "/github/workspace/builds/coq/coq-failing/_install_ci/lib/coq//" "-R" "/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/utils/theories" "MetaRocq.Utils" "-R" "/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/common/theories" "MetaRocq.Common" "-R" "/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/pcuic/theories" "MetaRocq.PCUIC" "-Q" "/github/workspace/cwd" "Top" "-Q" "/github/workspace/builds/coq/coq-failing/_install_ci/lib/coq///user-contrib/Equations" "Equations" "-Q" "/github/workspace/builds/coq/coq-failing/_install_ci/lib/coq///user-contrib/Ltac2" "Ltac2" "-Q" "/github/workspace/builds/coq/coq-failing/_install_ci/lib/coq///user-contrib/Stdlib" "Stdlib" "-top" "Top.bug_01") -*- *)
(* File reduced by coq-bug-minimizer from original input, then from 3959 lines to 98 lines, then from 111 lines to 3187 lines, then from 3191 lines to 96 lines, then from 107 lines to 1813 lines, then from 1818 lines to 359 lines, then from 369 lines to 1502 lines, then from 1506 lines to 524 lines, then from 535 lines to 3221 lines, then from 3222 lines to 656 lines, then from 667 lines to 2894 lines, then from 2900 lines to 656 lines, then from 667 lines to 1321 lines, then from 1327 lines to 874 lines, then from 883 lines to 675 lines, then from 686 lines to 2746 lines, then from 2745 lines to 687 lines, then from 698 lines to 3155 lines, then from 3155 lines to 745 lines, then from 756 lines to 1586 lines, then from 1589 lines to 869 lines, then from 880 lines to 2395 lines, then from 2394 lines to 885 lines, then from 895 lines to 2754 lines, then from 2755 lines to 1157 lines, then from 1161 lines to 1145 lines, then from 1156 lines to 1809 lines, then from 1813 lines to 1200 lines, then from 1211 lines to 4024 lines, then from 4021 lines to 1355 lines, then from 1366 lines to 3048 lines, then from 3051 lines to 1938 lines, then from 1928 lines to 1518 lines, then from 1529 lines to 1814 lines, then from 1819 lines to 1523 lines, then from 1533 lines to 2340 lines, then from 2342 lines to 1526 lines, then from 1536 lines to 4638 lines, then from 4602 lines to 1892 lines, then from 1903 lines to 3075 lines, then from 3076 lines to 2771 lines, then from 2762 lines to 1985 lines, then from 1996 lines to 2830 lines, then from 2835 lines to 2048 lines, then from 2059 lines to 2413 lines, then from 2418 lines to 2052 lines, then from 2063 lines to 2597 lines, then from 2601 lines to 2063 lines, then from 2074 lines to 6642 lines, then from 6641 lines to 4802 lines, then from 4761 lines to 2105 lines, then from 2116 lines to 2604 lines, then from 2606 lines to 2117 lines, then from 2128 lines to 3899 lines, then from 3897 lines to 2137 lines, then from 2148 lines to 2516 lines, then from 2521 lines to 2151 lines, then from 2161 lines to 2404 lines, then from 2409 lines to 2150 lines, then from 2161 lines to 2447 lines, then from 2449 lines to 2162 lines, then from 2178 lines to 2162 lines, then from 2173 lines to 2602 lines, then from 2607 lines to 2180 lines, then from 2190 lines to 2437 lines, then from 2442 lines to 2200 lines, then from 2210 lines to 2368 lines, then from 2373 lines to 2201 lines, then from 2211 lines to 2367 lines, then from 2371 lines to 2204 lines, then from 2214 lines to 2934 lines, then from 2939 lines to 2250 lines, then from 2261 lines to 2593 lines, then from 2598 lines to 2252 lines, then from 2263 lines to 2633 lines, then from 2637 lines to 2623 lines, then from 2621 lines to 2324 lines, then from 2335 lines to 2934 lines, then from 2939 lines to 2302 lines, then from 2313 lines to 2654 lines, then from 2656 lines to 2311 lines, then from 2322 lines to 2473 lines, then from 2478 lines to 2312 lines, then from 2322 lines to 2470 lines, then from 2475 lines to 2312 lines, then from 2323 lines to 2571 lines, then from 2576 lines to 2353 lines, then from 2363 lines to 2478 lines, then from 2483 lines to 2368 lines, then from 2379 lines to 3551 lines, then from 3541 lines to 3278 lines *)
(* coqc version 9.1+alpha compiled with OCaml 4.14.2
   coqtop version runner-t7b1znuaq-project-4504-concurrent-2:/builds/coq/coq/_build/default,(HEAD detached at cdd06d0a2f356e) (cdd06d0a2f356e0c02e2d20356562b7deae4cf15)
   Modules that could not be inlined: Equations.Prop.DepElim
   Expected coqc runtime on this file: 1.301 sec *)









Require Corelib.Init.Ltac.
Require Corelib.Classes.CRelationClasses.
Require Stdlib.Classes.CRelationClasses.
Require Stdlib.Classes.DecidableClass.
Require Stdlib.Logic.HLevelsBase.
Require Stdlib.Bool.Bool.
Require Corelib.Classes.RelationClasses.
Require Stdlib.Classes.RelationClasses.
Require Corelib.Numbers.BinNums.
Require Stdlib.Numbers.BinNums.
Require Stdlib.Logic.EqdepFacts.
Require Stdlib.Logic.Eqdep_dec.
Require Corelib.Classes.Morphisms.
Require Stdlib.Classes.Morphisms.
Require Corelib.Setoids.Setoid.
Require Stdlib.Setoids.Setoid.
Require Stdlib.Structures.Equalities.
Require Corelib.Relations.Relation_Definitions.
Require Stdlib.Relations.Relation_Definitions.
Require Stdlib.Relations.Relation_Operators.
Require Stdlib.Relations.Operators_Properties.
Require Stdlib.Relations.Relations.
Require Stdlib.Structures.Orders.
Require Corelib.Program.Basics.
Require Stdlib.Program.Basics.
Require Stdlib.Structures.OrdersTac.
Require Stdlib.Structures.OrdersFacts.
Require Stdlib.Structures.GenericMinMax.
Require Corelib.Classes.Morphisms_Prop.
Require Stdlib.Classes.Morphisms_Prop.
Require Stdlib.Numbers.NumPrelude.
Require Stdlib.Numbers.NatInt.NZAxioms.
Require Stdlib.Numbers.NatInt.NZBase.
Require Stdlib.Numbers.NatInt.NZAdd.
Require Stdlib.Numbers.NatInt.NZMul.
Require Stdlib.Logic.Decidable.
Require Stdlib.Numbers.NatInt.NZOrder.
Require Stdlib.Numbers.NatInt.NZAddOrder.
Require Stdlib.Numbers.NatInt.NZMulOrder.
Require Stdlib.Numbers.NatInt.NZParity.
Require Stdlib.Numbers.NatInt.NZPow.
Require Stdlib.Numbers.NatInt.NZSqrt.
Require Stdlib.Numbers.NatInt.NZLog.
Require Stdlib.Numbers.NatInt.NZDiv.
Require Stdlib.Numbers.NatInt.NZGcd.
Require Stdlib.Numbers.NatInt.NZBits.
Require Stdlib.Numbers.Natural.Abstract.NAxioms.
Require Stdlib.Numbers.Natural.Abstract.NBase.
Require Stdlib.Numbers.Natural.Abstract.NAdd.
Require Stdlib.Numbers.Natural.Abstract.NOrder.
Require Stdlib.Numbers.Natural.Abstract.NAddOrder.
Require Stdlib.Numbers.Natural.Abstract.NMulOrder.
Require Stdlib.Numbers.Natural.Abstract.NSub.
Require Stdlib.Numbers.Natural.Abstract.NMaxMin.
Require Stdlib.Numbers.Natural.Abstract.NParity.
Require Stdlib.Numbers.Natural.Abstract.NPow.
Require Stdlib.Numbers.Natural.Abstract.NSqrt.
Require Stdlib.Numbers.Natural.Abstract.NLog.
Require Stdlib.Numbers.Natural.Abstract.NDiv.
Require Stdlib.Numbers.Natural.Abstract.NDiv0.
Require Stdlib.Numbers.Natural.Abstract.NGcd.
Require Stdlib.Numbers.Natural.Abstract.NLcm.
Require Stdlib.Numbers.Natural.Abstract.NLcm0.
Require Stdlib.Numbers.Natural.Abstract.NBits.
Require Stdlib.Numbers.Natural.Abstract.NProperties.
Require Stdlib.Arith.PeanoNat.
Require Corelib.BinNums.PosDef.
Require Stdlib.BinNums.PosDef.
Require Stdlib.PArith.BinPosDef.
Require Stdlib.PArith.BinPos.
Require Stdlib.PArith.Pnat.
Require Stdlib.PArith.POrderedType.
Require Stdlib.PArith.PArith.
Require Corelib.BinNums.NatDef.
Require Stdlib.BinNums.NatDef.
Require Stdlib.NArith.BinNatDef.
Require Stdlib.NArith.BinNat.
Require Stdlib.setoid_ring.Ring_theory.
Require Corelib.Lists.ListDef.
Require Stdlib.Lists.ListDef.
Require Stdlib.Lists.List.
Require Stdlib.setoid_ring.BinList.
Require Stdlib.Numbers.Integer.Abstract.ZAxioms.
Require Stdlib.Numbers.Integer.Abstract.ZBase.
Require Stdlib.Numbers.Integer.Abstract.ZAdd.
Require Stdlib.Numbers.Integer.Abstract.ZMul.
Require Stdlib.Numbers.Integer.Abstract.ZLt.
Require Stdlib.Numbers.Integer.Abstract.ZAddOrder.
Require Stdlib.Numbers.Integer.Abstract.ZMulOrder.
Require Stdlib.Numbers.Integer.Abstract.ZMaxMin.
Require Stdlib.Numbers.Integer.Abstract.ZSgnAbs.
Require Stdlib.Numbers.Integer.Abstract.ZParity.
Require Stdlib.Numbers.Integer.Abstract.ZPow.
Require Stdlib.Numbers.Integer.Abstract.ZDivTrunc.
Require Stdlib.Numbers.Integer.Abstract.ZDivFloor.
Require Stdlib.Numbers.Integer.Abstract.ZGcd.
Require Stdlib.Numbers.Integer.Abstract.ZLcm.
Require Stdlib.Numbers.Integer.Abstract.ZBits.
Require Stdlib.Numbers.Integer.Abstract.ZProperties.
Require Corelib.BinNums.IntDef.
Require Stdlib.BinNums.IntDef.
Require Stdlib.ZArith.BinIntDef.
Require Stdlib.ZArith.BinInt.
Require Stdlib.setoid_ring.Ring_polynom.
Require Stdlib.Lists.ListTactics.
Require Stdlib.setoid_ring.InitialRing.
Require Stdlib.setoid_ring.Ring_tac.
Require Stdlib.setoid_ring.Ring_base.
Require Stdlib.setoid_ring.Ring.
Require Stdlib.Arith.Factorial.
Require Stdlib.Arith.Between.
Require Stdlib.Arith.Peano_dec.
Require Stdlib.Arith.Compare_dec.
Require Stdlib.Arith.EqNat.
Require Stdlib.Arith.Wf_nat.
Require Stdlib.Arith.Arith_base.
Require Stdlib.NArith.Nnat.
Require Stdlib.setoid_ring.ArithRing.
Require Stdlib.Arith.Arith.
Require Stdlib.ZArith.Znat.
Require Stdlib.micromega.ZifyClasses.
Require Stdlib.ZArith.Zeven.
Require Stdlib.micromega.ZifyInst.
Require Stdlib.micromega.Zify.
Require Stdlib.omega.PreOmega.
Require Stdlib.micromega.OrderedRing.
Require Stdlib.NArith.Ndiv_def.
Require Stdlib.NArith.Nsqrt_def.
Require Stdlib.NArith.Ngcd_def.
Require Stdlib.NArith.NArith_base.
Require Stdlib.setoid_ring.NArithRing.
Require Stdlib.NArith.NArith.
Require Stdlib.micromega.Env.
Require Stdlib.micromega.EnvRing.
Require Stdlib.micromega.Refl.
Require Stdlib.micromega.Tauto.
Require Stdlib.micromega.RingMicromega.
Require Stdlib.ZArith.Zpow_def.
Require Stdlib.setoid_ring.ZArithRing.
Require Stdlib.micromega.ZCoeff.
Require Stdlib.ZArith.Zcompare.
Require Stdlib.ZArith.Zorder.
Require Stdlib.ZArith.Zmisc.
Require Stdlib.ZArith.Wf_Z.
Require Corelib.Init.Sumbool.
Require Stdlib.Init.Sumbool.
Require Stdlib.ZArith.ZArith_dec.
Require Stdlib.ZArith.Zbool.
Require Stdlib.ZArith.Zabs.
Require Stdlib.ZArith.Zcomplements.
Require Stdlib.ZArith.Zdiv.
Require Stdlib.micromega.VarMap.
Require Stdlib.micromega.ZMicromega.
Require Stdlib.micromega.DeclConstantZ.
Require Stdlib.micromega.Lia.
Require Stdlib.btauto.Algebra.
Require Stdlib.btauto.Reflect.
Require Stdlib.btauto.Btauto.
Require Corelib.ssr.ssreflect.
Require Stdlib.ssr.ssreflect.
Require Corelib.ssr.ssrbool.
Require Stdlib.ssr.ssrbool.
Require MetaRocq.Common.config.
Require Stdlib.Sets.Relations_1.
Require Stdlib.Sorting.Sorted.
Require Stdlib.Sorting.SetoidList.
Require Stdlib.Classes.RelationPairs.
Require Stdlib.MSets.MSetInterface.
Require Stdlib.Structures.EqualitiesFacts.
Require Stdlib.Structures.OrdersLists.
Require Stdlib.MSets.MSetList.
Require Stdlib.ZArith.Int.
Require Stdlib.MSets.MSetGenTree.
Require Corelib.Floats.FloatOps.
Require Corelib.Strings.PrimString.
Require Corelib.Program.Tactics.
Require Stdlib.Program.Tactics.
Require Corelib.extraction.Extraction.
Require Stdlib.Unicode.Utf8_core.
Require Equations.Init.
Require Equations.Signature.
Require Equations.CoreTactics.
Require Equations.Prop.SigmaNotations.
Require Stdlib.extraction.Extraction.
Require Equations.Prop.Logic.
Require Equations.Prop.Classes.
Require Equations.Prop.EqDec.
Require Equations.Prop.DepElim.

Module Export AdmitTactic.
Module Import LocalFalse.
Inductive False : Prop := .
End LocalFalse.
Axiom proof_admitted : False.
Import Coq.Init.Ltac.
Tactic Notation "admit" := abstract case proof_admitted.
End AdmitTactic.

Module Export Stdlib_DOT_MSets_DOT_MSetAVL_WRAPPED.
Module Export MSetAVL.
Import Stdlib.MSets.MSetInterface.
Import Stdlib.MSets.MSetGenTree.
Import Stdlib.ZArith.BinInt.
Import Stdlib.ZArith.Int.

Set Implicit Arguments.
Unset Strict Implicit.

Local Unset Elimination Schemes.



Module Ops (Import I:Int)(X:OrderedType) <: MSetInterface.Ops X.
Local Open Scope Int_scope.
Local Notation int := I.t.





Include MSetGenTree.Ops X I.

Definition t := tree.
Definition height (s : t) : int. exact (match s with
  | Leaf => 0
  | Node h _ _ _ => h
  end). Defined.



Definition singleton x := Node 1 Leaf x Leaf.





Definition create l x r :=
   Node (max (height l) (height r) + 1) l x r.



Definition assert_false := create.

Definition bal l x r :=
  let hl := height l in
  let hr := height r in
  if (hr+2) <? hl then
    match l with
     | Leaf => assert_false l x r
     | Node _ ll lx lr =>
       if (height lr) <=? (height ll) then
         create ll lx (create lr x r)
       else
         match lr with
          | Leaf => assert_false l x r
          | Node _ lrl lrx lrr =>
              create (create ll lx lrl) lrx (create lrr x r)
         end
    end
  else
    if (hl+2) <? hr then
      match r with
       | Leaf => assert_false l x r
       | Node _ rl rx rr =>
         if (height rl) <=? (height rr) then
            create (create l x rl) rx rr
         else
           match rl with
            | Leaf => assert_false l x r
            | Node _ rll rlx rlr =>
                create (create l x rll) rlx (create rlr rx rr)
           end
      end
    else
      create l x r.



Fixpoint add x s := match s with
   | Leaf => Node 1 Leaf x Leaf
   | Node h l y r =>
      match X.compare x y with
         | Lt => bal (add x l) y r
         | Eq => Node h l y r
         | Gt => bal l y (add x r)
      end
  end.



Fixpoint join l : elt -> t -> t :=
  match l with
    | Leaf => add
    | Node lh ll lx lr => fun x =>
       fix join_aux (r:t) : t := match r with
          | Leaf => add x l
          | Node rh rl rx rr =>
               if (rh+2) <? lh then bal ll lx (join lr x r)
               else if (lh+2) <? rh then bal (join_aux rl) rx rr
               else create l x r
          end
  end.



Fixpoint remove_min l x r : t*elt :=
  match l with
    | Leaf => (r,x)
    | Node lh ll lx lr =>
       let (l',m) := remove_min ll lx lr in (bal l' x r, m)
  end.



Definition merge s1 s2 :=  match s1,s2 with
  | Leaf, _ => s2
  | _, Leaf => s1
  | _, Node _ l2 x2 r2 =>
        let (s2',m) := remove_min l2 x2 r2 in bal s1 m s2'
end.



Fixpoint remove x s := match s with
  | Leaf => Leaf
  | Node _ l y r =>
      match X.compare x y with
         | Lt => bal (remove x l) y r
         | Eq => merge l r
         | Gt => bal l y (remove x r)
      end
   end.



Definition concat s1 s2 :=
   match s1, s2 with
      | Leaf, _ => s2
      | _, Leaf => s1
      | _, Node _ l2 x2 r2 =>
            let (s2',m) := remove_min l2 x2 r2 in
            join s1 m s2'
   end.



Record triple := mktriple { t_left:t; t_in:bool; t_right:t }.
Notation "<< l , b , r >>" := (mktriple l b r) (at level 9).

Fixpoint split x s : triple := match s with
  | Leaf => << Leaf, false, Leaf >>
  | Node _ l y r =>
     match X.compare x y with
      | Lt => let (ll,b,rl) := split x l in << ll, b, join rl y r >>
      | Eq => << l, true, r >>
      | Gt => let (rl,b,rr) := split x r in << join l y rl, b, rr >>
     end
 end.



Fixpoint inter s1 s2 := match s1, s2 with
    | Leaf, _ => Leaf
    | _, Leaf => Leaf
    | Node _ l1 x1 r1, _ =>
            let (l2',pres,r2') := split x1 s2 in
            if pres then join (inter l1 l2') x1 (inter r1 r2')
            else concat (inter l1 l2') (inter r1 r2')
    end.



Fixpoint diff s1 s2 := match s1, s2 with
 | Leaf, _ => Leaf
 | _, Leaf => s1
 | Node _ l1 x1 r1, _ =>
    let (l2',pres,r2') := split x1 s2 in
    if pres then concat (d
10000
iff l1 l2') (diff r1 r2')
    else join (diff l1 l2') x1 (diff r1 r2')
end.





Fixpoint union s1 s2 :=
 match s1, s2 with
  | Leaf, _ => s2
  | _, Leaf => s1
  | Node _ l1 x1 r1, _ =>
     let (l2',_,r2') := split x1 s2 in
     join (union l1 l2') x1 (union r1 r2')
 end.



Fixpoint filter (f:elt->bool) s := match s with
  | Leaf => Leaf
  | Node _ l x r =>
    let l' := filter f l in
    let r' := filter f r in
    if f x then join l' x r' else concat l' r'
 end.
Fixpoint partition (f:elt->bool)(s : t) : t*t. exact (match s with
   | Leaf => (Leaf, Leaf)
   | Node _ l x r =>
      let (l1,l2) := partition f l in
      let (r1,r2) := partition f r in
      if f x then (join l1 x r1, concat l2 r2)
      else (concat l1 r1, join l2 x r2)
  end). Defined.

End Ops.



Module MakeRaw (Import I:Int)(X:OrderedType) <: RawSets X.
Include Ops I X.



Include MSetGenTree.Props X I.



Local Hint Immediate MX.eq_sym : core.
Local Hint Unfold In lt_tree gt_tree Ok : core.
Local Hint Constructors InT bst : core.
Local Hint Resolve MX.eq_refl MX.eq_trans MX.lt_trans ok : core.
Local Hint Resolve lt_leaf gt_leaf lt_tree_node gt_tree_node : core.
Local Hint Resolve lt_tree_not_in lt_tree_trans gt_tree_not_in gt_tree_trans : core.
Local Hint Resolve elements_spec2 : core.





Tactic Notation "factornode" ident(s) :=
 try clear s;
 match goal with
   | |- context [Node ?l ?x ?r ?h] =>
       set (s:=Node l x r h) in *; clearbody s; clear l x r h
   | _ : context [Node ?l ?x ?r ?h] |- _ =>
       set (s:=Node l x r h) in *; clearbody s; clear l x r h
 end.



#[local] Ltac caseq :=
match goal with [ |- context [match ?t with _ => _ end] ] =>
  let cmp := fresh in
  let H := fresh in
  remember t as cmp eqn:H; symmetry in H; destruct cmp
end.

Lemma bal_ind  [P : t -> X.t -> t -> tree -> Prop] :
  (forall (l : t) (x : X.t) (r : t),
   let hl := height l in
   let hr := height r in (hr + 2 <? hl) = true -> l = Leaf -> P Leaf x r (assert_false l x r)) ->
  (forall (l : t) (x : X.t) (r : t),
   let hl := height l in
   let hr := height r in
   (hr + 2 <? hl) = true ->
   forall (_x : I.t) (ll : tree) (lx : X.t) (lr : tree),
   l = Node _x ll lx lr ->
   (height lr <=? height ll) = true -> P (Node _x ll lx lr) x r (create ll lx (create lr x r))) ->
  (forall (l : t) (x : X.t) (r : t),
   let hl := height l in
   let hr := height r in
   (hr + 2 <? hl) = true ->
   forall (_x : I.t) (ll : tree) (lx : X.t) (lr : tree),
   l = Node _x ll lx lr ->
   (height lr <=? height ll) = false ->
   lr = Leaf -> P (Node _x ll lx Leaf) x r (assert_false l x r)) ->
  (forall (l : t) (x : X.t) (r : t),
   let hl := height l in
   let hr := height r in
   (hr + 2 <? hl) = true ->
   forall (_x : I.t) (ll : tree) (lx : X.t) (lr : tree),
   l = Node _x ll lx lr ->
   (height lr <=? height ll) = false ->
   forall (_x0 : I.t) (lrl : tree) (lrx : X.t) (lrr : tree),
   lr = Node _x0 lrl lrx lrr ->
   P (Node _x ll lx (Node _x0 lrl lrx lrr)) x r (create (create ll lx lrl) lrx (create lrr x r))) ->
  (forall (l : t) (x : X.t) (r : t),
   let hl := height l in
   let hr := height r in
   (hr + 2 <? hl) = false ->
   (hl + 2 <? hr) = true -> r = Leaf -> P l x Leaf (assert_false l x r)) ->
  (forall (l : t) (x : X.t) (r : t),
   let hl := height l in
   let hr := height r in
   (hr + 2 <? hl) = false ->
   (hl + 2 <? hr) = true ->
   forall (_x : I.t) (rl : tree) (rx : X.t) (rr : tree),
   r = Node _x rl rx rr ->
   (height rl <=? height rr) = true -> P l x (Node _x rl rx rr) (create (create l x rl) rx rr)) ->
  (forall (l : t) (x : X.t) (r : t),
   let hl := height l in
   let hr := height r in
   (hr + 2 <? hl) = false ->
   (hl + 2 <? hr) = true ->
   forall (_x : I.t) (rl : tree) (rx : X.t) (rr : tree),
   r = Node _x rl rx rr ->
   (height rl <=? height rr) = false ->
   rl = Leaf -> P l x (Node _x Leaf rx rr) (assert_false l x r)) ->
  (forall (l : t) (x : X.t) (r : t),
   let hl := height l in
   let hr := height r in
   (hr + 2 <? hl) = false ->
   (hl + 2 <? hr) = true ->
   forall (_x : I.t) (rl : tree) (rx : X.t) (rr : tree),
   r = Node _x rl rx rr ->
   (height rl <=? height rr) = false ->
   forall (_x0 : I.t) (rll : tree) (rlx : X.t) (rlr : tree),
   rl = Node _x0 rll rlx rlr ->
   P l x (Node _x (Node _x0 rll rlx rlr) rx rr) (create (create l x rll) rlx (create rlr rx rr))) ->
  (forall (l : t) (x : X.t) (r : t),
   let hl := height l in
   let hr := height r in
   (hr + 2 <? hl) = false -> (hl + 2 <? hr) = false -> P l x r (create l x r)) ->
  forall (l : t) (x : X.t) (r : t), P l x r (bal l x r).
Admitted.

Lemma remove_min_ind [P : tree -> elt -> t -> t * elt -> Prop] :
  (forall (l : tree) (x : elt) (r : t), l = Leaf -> P Leaf x r (r, x)) ->
  (forall (l : tree) (x : elt) (r : t) (_x : I.t) (ll : tree) (lx : X.t) (lr : tree),
   l = Node _x ll lx lr ->
   P ll lx lr (remove_min ll lx lr) ->
   forall (l' : t) (m : elt),
   remove_min ll lx lr = (l', m) -> P (Node _x ll lx lr) x r (bal l' x r, m)) ->
  forall (l : tree) (x : elt) (r : t), P l x r (remove_min l x r).
Admitted.

Lemma merge_ind [P : tree -> tree -> tree -> Prop] :
  (forall s1 s2 : tree, s1 = Leaf -> P Leaf s2 s2) ->
  (forall (s1 s2 : tree) (_x : I.t) (_x0 : tree) (_x1 : X.t) (_x2 : tree),
   s1 = Node _x _x0 _x1 _x2 -> s2 = Leaf -> P (Node _x _x0 _x1 _x2) Leaf s1) ->
  (forall (s1 s2 : tree) (_x : I.t) (_x0 : tree) (_x1 : X.t) (_x2 : tree),
   s1 = Node _x _x0 _x1 _x2 ->
   forall (_x3 : I.t) (l2 : tree) (x2 : X.t) (r2 : tree),
   s2 = Node _x3 l2 x2 r2 ->
   forall (s2' : t) (m : elt),
   remove_min l2 x2 r2 = (s2', m) -> P (Node _x _x0 _x1 _x2) (Node _x3 l2 x2 r2) (bal s1 m s2')) ->
  forall s1 s2 : tree, P s1 s2 (merge s1 s2).
Admitted.

Lemma concat_ind [P : tree -> tree -> tree -> Prop] :
  (forall s1 s2 : tree, s1 = Leaf -> P Leaf s2 s2) ->
  (forall (s1 s2 : tree) (_x : I.t) (_x0 : tree) (_x1 : X.t) (_x2 : tree),
   s1 = Node _x _x0 _x1 _x2 -> s2 = Leaf -> P (Node _x _x0 _x1 _x2) Leaf s1) ->
  (forall (s1 s2 : tree) (_x : I.t) (_x0 : tree) (_x1 : X.t) (_x2 : tree),
   s1 = Node _x _x0 _x1 _x2 ->
   forall (_x3 : I.t) (l2 : tree) (x2 : X.t) (r2 : tree),
   s2 = Node _x3 l2 x2 r2 ->
   forall (s2' : t) (m : elt),
   remove_min l2 x2 r2 = (s2', m) -> P (Node _x _x0 _x1 _x2) (Node _x3 l2 x2 r2) (join s1 m s2')) ->
  forall s1 s2 : tree, P s1 s2 (concat s1 s2).
Admitted.

Lemma inter_ind [P : tree -> tree -> tree -> Prop] :
  (forall s1 s2 : tree, s1 = Leaf -> P Leaf s2 Leaf) ->
  (forall (s1 s2 : tree) (_x : I.t) (l1 : tree) (x1 : X.t) (r1 : tree),
   s1 = Node _x l1 x1 r1 -> s2 = Leaf -> P (Node _x l1 x1 r1) Leaf Leaf) ->
  (forall (s1 s2 : tree) (_x : I.t) (l1 : tree) (x1 : X.t) (r1 : tree),
   s1 = Node _x l1 x1 r1 ->
   forall (_x0 : I.t) (_x1 : tree) (_x2 : X.t) (_x3 : tree),
   s2 = Node _x0 _x1 _x2 _x3 ->
   forall (l2' : t) (pres : bool) (r2' : t),
   split x1 s2 = << l2', pres, r2' >> ->
   pres = true ->
   P l1 l2' (inter l1 l2') ->
   P r1 r2' (inter r1 r2') ->
   P (Node _x l1 x1 r1) (Node _x0 _x1 _x2 _x3) (join (inter l1 l2') x1 (inter r1 r2'))) ->
  (forall (s1 s2 : tree) (_x : I.t) (l1 : tree) (x1 : X.t) (r1 : tree),
   s1 = Node _x l1 x1 r1 ->
   forall (_x0 : I.t) (_x1 : tree) (_x2 : X.t) (_x3 : tree),
   s2 = Node _x0 _x1 _x2 _x3 ->
   forall (l2' : t) (pres : bool) (r2' : t),
   split x1 s2 = << l2', pres, r2' >> ->
   pres = false ->
   P l1 l2' (inter l1 l2') ->
   P r1 r2' (inter r1 r2') ->
   P (Node _x l1 x1 r1) (Node _x0 _x1 _x2 _x3) (concat (inter l1 l2') (inter r1 r2'))) ->
  forall s1 s2 : tree, P s1 s2 (inter s1 s2).
Admitted.

Lemma diff_ind [P : tree -> tree -> tree -> Prop] :
  (forall s1 s2 : tree, s1 = Leaf -> P Leaf s2 Leaf) ->
  (forall (s1 s2 : tree) (_x : I.t) (l1 : tree) (x1 : X.t) (r1 : tree),
   s1 = Node _x l1 x1 r1 -> s2 = Leaf -> P (Node _x l1 x1 r1) Leaf s1) ->
  (forall (s1 s2 : tree) (_x : I.t) (l1 : tree) (x1 : X.t) (r1 : tree),
   s1 = Node _x l1 x1 r1 ->
   forall (_x0 : I.t) (_x1 : tree) (_x2 : X.t) (_x3 : tree),
   s2 = Node _x0 _x1 _x2 _x3 ->
   forall (l2' : t) (pres : bool) (r2' : t),
   split x1 s2 = << l2', pres, r2' >> ->
   pres = true ->
   P l1 l2' (diff l1 l2') ->
   P r1 r2' (diff r1 r2') ->
   P (Node _x l1 x1 r1) (Node _x0 _x1 _x2 _x3) (concat (diff l1 l2') (diff r1 r2'))) ->
  (forall (s1 s2 : tree) (_x : I.t) (l1 : tree) (x1 : X.t) (r1 : tree),
   s1 = Node _x l1 x1 r1 ->
   forall (_x0 : I.t) (_x1 : tree) (_x2 : X.t) (_x3 : tree),
   s2 = Node _x0 _x1 _x2 _x3 ->
   forall (l2' : t) (pres : bool) (r2' : t),
   split x1 s2 = << l2', pres, r2' >> ->
   pres = false ->
   P l1 l2' (diff l1 l2') ->
   P r1 r2' (diff r1 r2') ->
   P (Node _x l1 x1 r1) (Node _x0 _x1 _x2 _x3) (join (diff l1 l2') x1 (diff r1 r2'))) ->
  forall s1 s2 : tree, P s1 s2 (diff s1 s2).
Admitted.

Lemma union_ind [P : tree -> tree -> tree -> Prop] :
  (forall s1 s2 : tree, s1 = Leaf -> P Leaf s2 s2) ->
  (forall (s1 s2 : tree) (_x : I.t) (l1 : tree) (x1 : X.t) (r1 : tree),
   s1 = Node _x l1 x1 r1 -> s2 = Leaf -> P (Node _x l1 x1 r1) Leaf s1) ->
  (forall (s1 s2 : tree) (_x : I.t) (l1 : tree) (x1 : X.t) (r1 : tree),
   s1 = Node _x l1 x1 r1 ->
   forall (_x0 : I.t) (_x1 : tree) (_x2 : X.t) (_x3 : tree),
   s2 = Node _x0 _x1 _x2 _x3 ->
   forall (l2' : t) (_x4 : bool) (r2' : t),
   split x1 s2 = << l2', _x4, r2' >> ->
   P l1 l2' (union l1 l2') ->
   P r1 r2' (union r1 r2') ->
   P (Node _x l1 x1 r1) (Node _x0 _x1 _x2 _x3) (join (union l1 l2') x1 (union r1 r2'))) ->
  forall s1 s2 : tree, P s1 s2 (union s1 s2).
Admitted.



Declare Scope pair_scope.

Notation "s #1" := (fst s) (at level 9, format "s '#1'") : pair_scope.
Notation "s #2" := (snd s) (at level 9, format "s '#2'") : pair_scope.
Notation "t #l" := (t_left t) (at level 9, format "t '#l'") : pair_scope.
Notation "t #b" := (t_in t) (at level 9, format "t '#b'") : pair_scope.
Notation "t #r" := (t_right t) (at level 9, format "t '#r'") : pair_scope.

Local Open Scope pair_scope.



Lemma singleton_spec : forall x y, InT y (singleton x) <-> X.eq y x.
Admitted.

#[global]
Instance singleton_ok x : Ok (singleton x).
Admitted.



Lemma create_spec :
 forall l x r y,  InT y (create l x r) <-> X.eq y x \/ InT y l \/ InT y r.
Admitted.

#[global]
Instance create_ok l x r `(Ok l, Ok r, lt_tree x l, gt_tree x r) :
 Ok (create l x r).
Admitted.

Lemma bal_spec : forall l x r y,
 InT y (bal l x r) <-> X.eq y x \/ InT y l \/ InT y r.
Admitted.

#[global]
Instance bal_ok l x r `(Ok l, Ok r, lt_tree x l, gt_tree x r) :
 Ok (bal l x r).
Admitted.



Lemma add_spec' : forall s x y,
 InT y (add x s) <-> X.eq y x \/ InT y s.
Admitted.

Lemma add_spec : forall s x y `{Ok s},
 InT y (add x s) <-> X.eq y x \/ InT y s.
Admitted.

#[global]
Instance add_ok s x `(Ok s) : Ok (add x s).
Admitted.

Local Open Scope Int_scope.





Ltac join_tac :=
 let l := fresh "l" in
 intro l; induction l as [| lh ll _ lx lr Hlr];
   [ | intros x r; induction r as [| rh rl Hrl rx rr _]; unfold join;
     [ | destruct ((rh+2) <? lh) eqn:LT;
       [ match goal with |- context b [ bal ?a ?b ?c] =>
           replace (bal a b c)
           with (bal ll lx (join lr x (Node rh rl rx rr))); [ | auto]
         end
       | destruct ((lh+2) <? rh) eqn:LT';
         [ match goal with |- context b [ bal ?a ?b ?c] =>
             replace (bal a b c)
             with (bal (join (Node lh ll lx lr) x rl) rx rr); [ | auto]
           end
         | ] ] ] ]; intros.

Lemma join_spec : forall l x r y,
 InT y (join l x r) <-> X.eq y x \/ InT y l \/ InT y r.
Admitted.

#[global]
Instance join_ok : forall l x r `(Ok l, Ok r, lt_tree x l, gt_tree x r),
 Ok (join l x r).
Admitted.



Lemma remove_min_spec : forall l x r y h,
 InT y (Node h l x r) <->
  X.eq y (remove_min l x r)#2 \/ InT y (remove_min l x r)#1.
Admitted.

#[global]
Instance remove_min_ok l x r : forall h `(Ok (Node h l x r)),
 Ok (remove_min l x r)#1.
Admitted.

Lemma remove_min_gt_tree : forall l x r h `{Ok (Node h l x r)},
 gt_tree (remove_min l x r)#2 (remove_min l x r)#1.
Admitted.
Local Hint Resolve remove_min_gt_tree : core.



Lemma merge_spec : forall s1 s2 y,
 InT y (merge s1 s2) <-> InT y s1 \/ InT y s2.
Admitted.

#[global]
Instance merge_ok s1 s2 : forall `(Ok s1, Ok s2)
 `(forall y1 y2 : elt, InT y1 s1 -> InT y2 s2 -> X.lt y1 y2),
 Ok (merge s1 s2).
Admitted.



Lemma remove_spec : forall s x y `{Ok s},
 (InT y (remove x s) <-> InT y s /\ ~ X.eq y x).
Admitted.

#[global]
Instance remove_ok s x `(Ok s) : Ok (remove x s).
Admitted.



Lemma concat_spec : forall s1 s2 y,
 InT y (concat s1 s2) <-> InT y s1 \/ InT y s2.
Admitted.

#[global]
Instance concat_ok s1 s2 : forall `(Ok s1, Ok s2)
 `(forall y1 y2 : elt, InT y1 s1 -> InT y2 s2 -> X.lt y1 y2),
 Ok (concat s1 s2).
Admitted.



Lemma split_spec1 : forall s x y `{Ok s},
 (InT y (split x s)#l <-> InT y s /\ X.lt y x).
Admitted.

Lemma split_spec2 : forall s x y `{Ok s},
 (InT y (split x s)#r <-> InT y s /\ X.lt x y).
Admitted.

Lemma split_spec3 : forall s x `{Ok s},
 ((split x s)#b = true <-> InT x s).
Admitted.

Lemma split_ok : forall s x `{Ok s}, Ok (split x s)#l /\ Ok (split x s)#r.
Admitted.

#[global]
Instance split_ok1 s x `(Ok s) : Ok (split x s)#l.
Admitted.

#[global]
Instance split_ok2 s x `(Ok s) : Ok (split x s)#r.
Admitted.



Ltac destruct_split := match goal with
 | H : split ?x ?s = << ?u, ?v, ?w >> |- _ =>
   assert ((split x s)#l = u) by (rewrite H; auto);
   assert ((split x s)#b = v) by (rewrite H; auto);
   assert ((split x s)#r = w) by (rewrite H; auto);
   clear H; subst u w
 end.

Lemma inter_spec_ok : forall s1 s2 `{Ok s1, Ok s2},
 Ok (inter s1 s2) /\ (forall y, InT y (inter s1 s2) <-> InT y s1 /\ InT y s2).
Admitted.

Lemma inter_spec : forall s1 s2 y `{Ok s1, Ok s2},
 (InT y (inter s1 s2) <-> InT y s1 /\ InT y s2).
Admitted.

#[global]
Instance inter_ok s1 s2 `(Ok s1, Ok s2) : Ok (inter s1 s2).
Admitted.



Lemma diff_spec_ok : forall s1 s2 `{Ok s1, Ok s2},
 Ok (diff s1 s2) /\ (forall y, InT y (diff s1 s2) <-> InT y s1 /\ ~InT y s2).
Admitted.

Lemma diff_spec : forall s1 s2 y `{Ok s1, Ok s2},
 (InT y (diff s1 s2) <-> InT y s1 /\ ~InT y s2).
Admitted.

#[global]
Instance diff_ok s1 s2 `(Ok s1, Ok s2) : Ok (diff s1 s2).
Admitted.



Lemma union_spec : forall s1 s2 y `{Ok s1, Ok s2},
 (InT y (union s1 s2) <-> InT y s1 \/ InT y s2).
Admitted.

#[global]
Instance union_ok s1 s2 : forall `(Ok s1, Ok s2), Ok (union s1 s2).
Admitted.



Lemma filter_spec : forall s x f,
 Proper (X.eq==>Logic.eq) f ->
 (InT x (filter f s) <-> InT x s /\ f x = true).
Admitted.

Lemma filter_weak_spec : forall s x f,
 InT x (filter f s) -> InT x s.
Admitted.

#[global]
Instance filter_ok s f `(H : Ok s) : Ok (filter f s).
Admitted.



Lemma partition_spec1' s f : (partition f s)#1 = filter f s.
Admitted.

Lemma partition_spec2' s f :
 (partition f s)#2 = filter (fun x => negb (f x)) s.
Admitted.

Lemma partition_spec1 s f :
 Proper (X.eq==>Logic.eq) f ->
 Equal (partition f s)#1 (filter f s).
Admitted.

Lemma partition_spec2 s f :
 Proper (X.eq==>Logic.eq) f ->
 Equal (partition f s)#2 (filter (fun x => negb (f x)) s).
Admitted.

#[global]
Instance partition_ok1 s f `(Ok s) : Ok (partition f s)#1.
Admitted.

#[global]
Instance partition_ok2 s f `(Ok s) : Ok (partition f s)#2.
Admitted.

End MakeRaw.



Module IntMake (I:Int)(X: OrderedType) <: S with Module E := X.
 Module Raw := MakeRaw I X.
 Include Raw2Sets X Raw.
End IntMake.



Module Make (X: OrderedType) <: S with Module E := X
 :=IntMake(Z_as_Int)(X).

End MSetAVL.

End Stdlib_DOT_MSets_DOT_MSetAVL_WRAPPED.
Module Export Stdlib_DOT_MSets_DOT_MSetAVL.
Module Export Stdlib.
Module Export MSets.
Module Export MSetAVL.
Include Stdlib_DOT_MSets_DOT_MSetAVL_WRAPPED.MSetAVL.
End MSetAVL.

End MSets.

End Stdlib.

End Stdlib_DOT_MSets_DOT_MSetAVL.
Register Equations.Init.sigmaI as equations.sigma.intro.

Register Init.Logic.eq as equations.equality.type.
Register Init.Logic.eq_refl as equations.equality.refl.

Register Classes.EqDec as equations.eqdec.class.
Register Classes.dec_eq as equations.eqdec.dec_eq.

Register Init.Logic.False as equations.bottom.type.
Register Init.Logic.False_rect as equations.bottom.case.

Register Init.Logic.True as equations.top.type.

Register Equations.Prop.Classes.NoConfusionPackage as equations.noconfusion.class.
Register Equations.Prop.Classes.apply_noConfusion as equations.depelim.apply_noConfusion.
Register Equations.Prop.DepElim.opaque_ind_pack_eq_inv as equations.depelim.opaque_ind_pack_eq_inv.
Import Equations.CoreTactics.
Import Equations.Prop.DepElim.

Ltac solve_noconf_prf := intros;
  on_last_hyp ltac:(fun id => destruct id) ;
  on_last_hyp ltac:(fun id =>
                      destruct_sigma id;
                      destruct id) ;
  constructor.

Ltac solve_noconf_inv_eq a b :=
  destruct_sigma a; destruct_sigma b;
  destruct a ; depelim b; simpl in * |-;
  on_last_hyp ltac:(fun id => hnf in id; destruct_tele_eq id || destruct id);
  solve [constructor].

Ltac solve_noconf_inv := intros;
  match goal with
    |- ?R ?a ?b => destruct_sigma a; destruct_sigma b;
                   destruct a ; depelim b; simpl in * |-;
                 on_last_hyp ltac:(fun id => hnf in id; destruct_tele_eq id || destruct id);
                 solve [constructor]
  | |- @eq _ (?f ?a ?b _) _ => solve_noconf_inv_eq a b
  end.

Ltac solve_noconf_i

[...]

verses)))
    (to_extended_list (smash_context [] mdecl.(ind_params) ,,, ictx)) in
  let inddecl :=
    {| decl_name :=
      {| binder_name := nNamed (ind_name idecl); binder_relevance := idecl.(ind_relevance) |};
       decl_body := None;
       decl_type := indty |}
  in (inddecl :: ictx).

Definition inst_case_context params puinst (pctx : context) :=
  subst_context (List.rev params) 0 (subst_instance puinst pctx).

Definition inst_case_predicate_context (p : predicate term) :=
  inst_case_context p.(pparams) p.(puinst) p.(pcontext).

Definition inst_case_branch_context (p : predicate term) (br : branch term) :=
  inst_case_context p.(pparams) p.(puinst) br.(bcontext).

Definition iota_red npar p args br :=
  subst (List.rev (List.skipn npar args)) 0
    (expand_lets (inst_case_branch_context p br) (bbody br)).

Definition pre_case_predicate_context_gen ind mdecl idecl params puinst : context :=
  inst_case_context params puinst (ind_predicate_context ind mdecl idecl).

Definition case_predicate_context_gen ind mdecl idecl params puinst pctx :=
  map2 set_binder_name pctx (pre_case_predicate_context_gen ind mdecl idecl params puinst).

Definition case_predicate_context ind mdecl idecl p : context :=
  case_predicate_context_gen ind mdecl idecl p.(pparams) p.(puinst) (forget_types p.(pcontext)).

Definition cstr_branch_context ind mdecl cdecl : context :=
  expand_lets_ctx mdecl.(ind_params)
    (subst_context (inds (inductive_mind ind) (abstract_instance mdecl.(ind_universes))
       mdecl.(ind_bodies)) #|mdecl.(ind_params)|
      cdecl.(cstr_args)).

Definition pre_case_branch_context_gen ind mdecl cdecl params puinst : context :=
  inst_case_context params puinst (cstr_branch_context ind mdecl cdecl).

Definition case_branch_context_gen ind mdecl params puinst pctx cdecl :=
  map2 set_binder_name pctx (pre_case_branch_context_gen ind mdecl cdecl params puinst).

Definition case_branch_type_gen ind mdecl (idecl : one_inductive_body) params puinst bctx ptm i cdecl : context * term :=
  let cstr := tConstruct ind i puinst in
  let args := to_extended_list cdecl.(cstr_args) in
  let cstrapp := mkApps cstr (map (lift0 #|cdecl.(cstr_args)|) params ++ args) in
  let brctx := case_branch_context_gen ind mdecl params puinst bctx cdecl in
  let upars := subst_instance puinst mdecl.(ind_params) in
  let indices :=
    (map (subst (List.rev params) #|cdecl.(cstr_args)|)
      (map (expand_lets_k upars #|cdecl.(cstr_args)|)
        (map (subst (inds (inductive_mind ind) puinst mdecl.(ind_bodies))
                    (#|mdecl.(ind_params)| + #|cdecl.(cstr_args)|))
          (map (subst_instance puinst) cdecl.(cstr_indices))))) in
  let ty := mkApps (lift0 #|cdecl.(cstr_args)| ptm) (indices ++ [cstrapp]) in
  (brctx, ty).

Definition case_branch_type ind mdecl idecl p (b : branch term) ptm i cdecl : context * term :=
  case_branch_type_gen ind mdecl idecl p.(pparams) p.(puinst) (forget_types b.(bcontext)) ptm i cdecl.

Definition idecl_binder idecl :=
  {| decl_name :=
    {| binder_name := nNamed idecl.(ind_name);
        binder_relevance := idecl.(ind_relevance) |};
     decl_body := None;
     decl_type := idecl.(ind_type) |}.

Definition wf_predicate_gen mdecl idecl (pparams : list term) (pcontext : list aname) : Prop :=
  let decl := idecl_binder idecl in
  (#|pparams| = mdecl.(ind_npars)) /\
  (Forall2 (fun na decl => eq_binder_annot na decl.(decl_name))
    pcontext (decl :: idecl.(ind_indices))).

Definition wf_predicate mdecl idecl (p : predicate term) : Prop :=
  wf_predicate_gen mdecl idecl p.(pparams) (forget_types p.(pcontext)).

Definition wf_branch_gen cdecl (bctx : list aname) : Prop :=
  (Forall2 (fun na decl => eq_binder_annot na decl.(decl_name))
    bctx cdecl.(cstr_args)).

Definition wf_branch cdecl (b : branch term) : Prop :=
  wf_branch_gen cdecl (forget_types b.(bcontext)).

Definition wf_branches idecl (brs : list (branch term)) : Prop :=
  Forall2 wf_branch idecl.(ind_ctors) brs.

Definition fix_subst (l : mfixpoint term) :=
  let fix aux n :=
      match n with
      | 0 => []
      | S n => tFix l n :: aux n
      end
  in aux (List.length l).

Definition unfold_fix (mfix : mfixpoint term) (idx : nat) :=
  match List.nth_error mfix idx with
  | Some d => Some (d.(rarg), subst0 (fix_subst mfix) d.(dbody))
  | None => None
  end.

Definition cofix_subst (l : mfixpoint term) :=
  let fix aux n :=
      match n with
      | 0 => []
      | S n => tCoFix l n :: aux n
      end
  in aux (List.length l).

Definition unfold_cofix (mfix : mfixpoint term) (idx : nat) :=
  match List.nth_error mfix idx with
  | Some d => Some (d.(rarg), subst0 (cofix_subst mfix) d.(dbody))
  | None => None
  end.

Definition is_constructor n ts :=
  match List.nth_error ts n with
  | Some a => isConstruct_app a
  | None => false
  end.
Definition cmp_universe_instance (cmp_univ : Universe.t -> Universe.t -> Prop) : Instance.t -> Instance.t -> Prop.
Admitted.

Definition cmp_universe_variance (cmp_univ : conv_pb -> Universe.t -> Universe.t -> Prop) pb v u u' :=
  match v with
  | Variance.Irrelevant => True
  | Variance.Covariant => on_rel (cmp_univ pb) Universe.make' u u'
  | Variance.Invariant => on_rel (cmp_univ Conv) Universe.make' u u'
  end.

Definition cmp_universe_instance_variance cmp_univ pb v u u' :=
  Forall3 (cmp_universe_variance cmp_univ pb) v u u'.

Definition global_variance_gen lookup gr napp :=
  match gr with
  | IndRef ind =>
    match lookup_inductive_gen lookup ind with
    | Some (mdecl, idecl) =>
      match destArity [] idecl.(ind_type) with
      | Some (ctx, _) => if (context_assumptions ctx) <=? napp then
          match mdecl.(ind_variance) with
          | Some var => Variance var
          | None => AllEqual
          end
        else AllEqual
      | None => AllEqual
      end
    | None => AllEqual
    end
  | ConstructRef ind k =>
    match lookup_constructor_gen lookup ind k with
    | Some (mdecl, idecl, cdecl) =>
      if (cdecl.(cstr_arity) + mdecl.(ind_npars))%nat <=? napp then

        AllIrrelevant
      else AllEqual
    | _ => AllEqual
    end
  | _ => AllEqual
  end.

Definition cmp_opt_variance cmp_univ pb v :=
  match v with
  | AllEqual => cmp_universe_instance (cmp_univ Conv)
  | AllIrrelevant => fun l l' => #|l| = #|l'|
  | Variance v => fun u u' => cmp_universe_instance (cmp_univ Conv) u u' \/ cmp_universe_instance_variance cmp_univ pb v u u'
  end.

Definition cmp_global_instance_gen Σ cmp_universe pb gr napp :=
  cmp_opt_variance cmp_universe pb (global_variance_gen Σ gr napp).

Notation cmp_global_instance Σ := (cmp_global_instance_gen (lookup_env Σ)).

Inductive eq_decl_upto_names : context_decl -> context_decl -> Type :=
  | compare_vass {na na' T} :
    eq_binder_annot na na' -> eq_decl_upto_names (vass na T) (vass na' T)
  | compare_vdef {na na' b T} :
    eq_binder_annot na na' -> eq_decl_upto_names (vdef na b T) (vdef na' b T).

Notation eq_context_upto_names := (All2 eq_decl_upto_names).

Definition shiftnP k p i :=
  (i <? k) || p (i - k).
Fixpoint on_free_vars (p : nat -> bool) (t : term) : bool.
Admitted.

Definition on_free_vars_decl P d :=
  test_decl (on_free_vars P) d.

Definition on_free_vars_ctx P ctx :=
  alli (fun k => (on_free_vars_decl (shiftnP k P))) 0 (List.rev ctx).

Notation is_open_term Γ := (on_free_vars (shiftnP #|Γ| xpred0)).
Notation is_closed_context := (on_free_vars_ctx xpred0).
Definition set_preturn (p : predicate term) (pret' : term) : predicate term.
Admitted.
Definition set_pparams (p : predicate term) (pars' : list term) : predicate term.
Admitted.
Definition on_one_decl (P : term -> term -> Type)
  (d : context_decl) (d' : context_decl) : Type.
Admitted.

Section OnOne_local_2.
  Context (P : forall (Γ : context), context_decl -> context_decl -> Type).

  Inductive OnOne2_local_env : context -> context -> Type :=
  | onone2_localenv_cons_abs Γ na na' t t' :
      P Γ (vass na t) (vass na' t') ->
      OnOne2_local_env (Γ ,, vass na t) (Γ ,, vass na' t')
  | onone2_localenv_def Γ na na' b b' t t' :
      P Γ (vdef na b t) (vdef na' b' t') ->
      OnOne2_local_env (Γ ,, vdef na b t) (Γ ,, vdef na' b' t')
  | onone2_localenv_cons_tl Γ Γ' d :
      OnOne2_local_env Γ Γ' ->
      OnOne2_local_env (Γ ,, d) (Γ' ,, d).
End OnOne_local_2.
Arguments exist {_ _} _ _.
Import Equations_DOT_Type_DOT_Relation_WRAPPED.Relation.

Reserved Notation " Σ ;;; Γ |- t ⇝ u " (at level 50, Γ, t, u at next level).

Definition set_array_default (ar : array_model term) (v : term) :=
  {| array_level := ar.(array_level);
     array_default := v;
     array_type := ar.(array_type);
     array_value := ar.(array_value) |}.

Definition set_array_type (ar : array_model term) (v : term) :=
  {| array_level := ar.(array_level);
     array_default := ar.(array_default);
     array_type := v;
     array_value := ar.(array_value) |}.

Definition set_array_value (ar : array_model term) (v : list term) :=
  {| array_level := ar.(array_level);
     array_default := ar.(array_default);
     array_type := ar.(array_type);
     array_value := v |}.

Inductive red1 (Σ : global_env) (Γ : context) : term -> term -> Type :=

| red_beta na t b a :
  Σ ;;; Γ |- tApp (tLambda na t b) a ⇝ b {0 := a}

| red_zeta na b t b' :
  Σ ;;; Γ |- tLetIn na b t b' ⇝ b' {0 := b}

| red_rel i body :
    option_map decl_body (nth_error Γ i) = Some (Some body) ->
    Σ ;;; Γ |- tRel i ⇝ lift0 (S i) body

| red_iota ci c u args p brs br :
    nth_error brs c = Some br ->
    #|args| = (ci.(ci_npar) + context_assumptions br.(bcontext))%nat ->
    Σ ;;; Γ |- tCase ci p (mkApps (tConstruct ci.(ci_ind) c u) args) brs
        ⇝ iota_red ci.(ci_npar) p args br

| red_fix mfix idx args narg fn :
    unfold_fix mfix idx = Some (narg, fn) ->
    is_constructor narg args = true ->
    Σ ;;; Γ |- mkApps (tFix mfix idx) args ⇝ mkApps fn args

| red_cofix_case ip p mfix idx args narg fn brs :
    unfold_cofix mfix idx = Some (narg, fn) ->
    Σ ;;; Γ |- tCase ip p (mkApps (tCoFix mfix idx) args) brs ⇝
         tCase ip p (mkApps fn args) brs

| red_cofix_proj p mfix idx args narg fn :
    unfold_cofix mfix idx = Some (narg, fn) ->
    Σ ;;; Γ |- tProj p (mkApps (tCoFix mfix idx) args) ⇝ tProj p (mkApps fn args)

| red_delta c decl body (isdecl : declared_constant Σ c decl) u :
    decl.(cst_body) = Some body ->
    Σ ;;; Γ |- tConst c u ⇝ subst_instance u body

| red_proj p args u arg:
    nth_error args (p.(proj_npars) + p.(proj_arg)) = Some arg ->
    Σ ;;; Γ |- tProj p (mkApps (tConstruct p.(proj_ind) 0 u) args) ⇝ arg

| abs_red_l na M M' N : Σ ;;; Γ |- M ⇝ M' -> Σ ;;; Γ |- tLambda na M N ⇝ tLambda na M' N
| abs_red_r na M M' N : Σ ;;; Γ ,, vass na N |- M ⇝ M' -> Σ ;;; Γ |- tLambda na N M ⇝ tLambda na N M'

| letin_red_def na b t b' r : Σ ;;; Γ |- b ⇝ r -> Σ ;;; Γ |- tLetIn na b t b' ⇝ tLetIn na r t b'
| letin_red_ty na b t b' r : Σ ;;; Γ |- t ⇝ r -> Σ ;;; Γ |- tLetIn na b t b' ⇝ tLetIn na b r b'
| letin_red_body na b t b' r : Σ ;;; Γ ,, vdef na b t |- b' ⇝ r -> Σ ;;; Γ |- tLetIn na b t b' ⇝ tLetIn na b t r

| case_red_param ci p params' c brs :
    OnOne2 (fun t u => Σ ;;; Γ |- t ⇝ u) p.(pparams) params' ->
    Σ ;;; Γ |- tCase ci p c brs ⇝ tCase ci (set_pparams p params') c brs

| case_red_return ci p preturn' c brs :
  Σ ;;; Γ ,,, inst_case_predicate_context p |- p.(preturn) ⇝ preturn' ->
  Σ ;;; Γ |- tCase ci p c brs ⇝ tCase ci (set_preturn p preturn') c brs

| case_red_discr ci p c c' brs :
  Σ ;;; Γ |- c ⇝ c' -> Σ ;;; Γ |- tCase ci p c brs ⇝ tCase ci p c' brs

| case_red_brs ci p c brs brs' :
    OnOne2 (fun br br' =>
      on_Trel_eq (fun t u => Σ ;;; Γ ,,, inst_case_branch_context p br |- t ⇝ u) bbody bcontext br br')
      brs brs' ->
    Σ ;;; Γ |- tCase ci p c brs ⇝ tCase ci p c brs'

| proj_red p c c' : Σ ;;; Γ |- c ⇝ c' -> Σ ;;; Γ |- tProj p c ⇝ tProj p c'

| app_red_l M1 N1 M2 : Σ ;;; Γ |- M1 ⇝ N1 -> Σ ;;; Γ |- tApp M1 M2 ⇝ tApp N1 M2
| app_red_r M2 N2 M1 : Σ ;;; Γ |- M2 ⇝ N2 -> Σ ;;; Γ |- tApp M1 M2 ⇝ tApp M1 N2

| prod_red_l na M1 M2 N1 : Σ ;;; Γ |- M1 ⇝ N1 -> Σ ;;; Γ |- tProd na M1 M2 ⇝ tProd na N1 M2
| prod_red_r na M2 N2 M1 : Σ ;;; Γ ,, vass na M1 |- M2 ⇝ N2 ->
                           Σ ;;; Γ |- tProd na M1 M2 ⇝ tProd na M1 N2

| evar_red ev l l' : OnOne2 (fun t u => Σ ;;; Γ |- t ⇝ u) l l' -> Σ ;;; Γ |- tEvar ev l ⇝ tEvar ev l'

| fix_red_ty mfix0 mfix1 idx :
    OnOne2 (on_Trel_eq (fun t u => Σ ;;; Γ |- t ⇝ u) dtype (fun x => (dname x, dbody x, rarg x))) mfix0 mfix1 ->
    Σ ;;; Γ |- tFix mfix0 idx ⇝ tFix mfix1 idx

| fix_red_body mfix0 mfix1 idx :
    OnOne2 (on_Trel_eq (fun t u => Σ ;;; Γ ,,, fix_context mfix0 |- t ⇝ u) dbody (fun x => (dname x, dtype x, rarg x)))
           mfix0 mfix1 ->
    Σ ;;; Γ |- tFix mfix0 idx ⇝ tFix mfix1 idx

| cofix_red_ty mfix0 mfix1 idx :
    OnOne2 (on_Trel_eq (fun t u => Σ ;;; Γ |- t ⇝ u) dtype (fun x => (dname x, dbody x, rarg x))) mfix0 mfix1 ->
    Σ ;;; Γ |- tCoFix mfix0 idx ⇝ tCoFix mfix1 idx

| cofix_red_body mfix0 mfix1 idx :
    OnOne2 (on_Trel_eq (fun t u => Σ ;;; Γ ,,, fix_context mfix0 |- t ⇝ u) dbody (fun x => (dname x, dtype x, rarg x))) mfix0 mfix1 ->
    Σ ;;; Γ |- tCoFix mfix0 idx ⇝ tCoFix mfix1 idx

| array_red_val arr value :
    OnOne2 (fun t u => Σ ;;; Γ |- t ⇝ u) arr.(array_value) value ->
    Σ ;;; Γ |- tPrim (primArray; primArrayModel arr) ⇝
               tPrim (primArray; primArrayModel (set_array_value arr value))

| array_red_def arr def :
    Σ ;;; Γ |- arr.(array_default) ⇝ def ->
    Σ ;;; Γ |- tPrim (primArray; primArrayModel arr) ⇝
               tPrim (primArray; primArrayModel (set_array_default arr def))

| array_red_type arr ty :
    Σ ;;; Γ |- arr.(array_type) ⇝ ty ->
    Σ ;;; Γ |- tPrim (primArray; primArrayModel arr) ⇝
          tPrim (primArray; primArrayModel (set_array_type arr ty))

where " Σ ;;; Γ |- t ⇝ u " := (red1 Σ Γ t u).

Definition red1_ctx Σ := (OnOne2_local_env (fun Δ => on_one_decl (fun t t' => red1 Σ Δ t t'))).

Definition red Σ Γ := clos_refl_trans (fun t u : term => Σ;;; Γ |- t ⇝ u).
Module Export PCUICCumulativitySpec.

Implicit Types (cf : checker_flags).

Definition cumul_predicate (cumul : context -> term -> term -> Type) cumul_universe Γ p p' :=
  All2 (cumul Γ) p.(pparams) p'.(pparams) ×
  cmp_universe_instance cumul_universe p.(puinst) p'.(puinst) ×
  eq_context_upto_names p.(pcontext) p'.(pcontext) ×
  cumul (Γ ,,, inst_case_predicate_context p) p.(preturn) p'.(preturn).

Definition cumul_branch (cumul_term : context -> term -> term -> Type) Γ p br br' :=
  eq_context_upto_names br.(bcontext) br'.(bcontext) ×
  cumul_term (Γ ,,, inst_case_branch_context p br) br.(bbody) br'.(bbody).

Definition cumul_branches cumul_term Γ p brs brs' := All2 (cumul_branch cumul_term Γ p) brs brs'.

Definition cumul_mfixpoint (cumul_term : context -> term -> term -> Type) Γ mfix mfix' :=
  All2 (fun d d' =>
    cumul_term Γ d.(dtype) d'.(dtype) ×
    cumul_term (Γ ,,, fix_context mfix) d.(dbody) d'.(dbody) ×
    d.(rarg) = d'.(rarg) ×
    eq_binder_annot d.(dname) d'.(dname)
  ) mfix mfix'.

Reserved Notation " Σ ;;; Γ ⊢ t ≤s[ pb ] u" (at level 50, Γ, t, u at next level,
  format "Σ  ;;;  Γ  ⊢  t  ≤s[ pb ]  u").

Definition cumul_Ind_univ {cf} (Σ : global_env_ext) pb i napp :=
  cmp_global_instance Σ (compare_universe Σ) pb (IndRef i) napp.

Definition cumul_Construct_univ {cf} (Σ : global_env_ext) pb  i k napp :=
  cmp_global_instance Σ (compare_universe Σ) pb (ConstructRef i k) napp.
Inductive cumulSpec0 {cf : checker_flags} (Σ : global_env_ext) Γ (pb : conv_pb) : term -> term -> Type :=

| cumul_Trans : forall t u v,
    is_closed_context Γ -> is_open_term Γ u ->
    Σ ;;; Γ ⊢ t ≤s[pb] u ->
    Σ ;;; Γ ⊢ u ≤s[pb] v ->
    Σ ;;; Γ ⊢ t ≤s[pb] v

| cumul_Sym : forall t u,
    Σ ;;; Γ ⊢ t ≤s[Conv] u ->
    Σ ;;; Γ ⊢ u ≤s[pb] t

| cumul_Refl : forall t,
    Σ ;;; Γ ⊢ t ≤s[pb] t

| cumul_Ind : forall i u u' args args',
    cumul_Ind_univ Σ pb i #|args| u u' ->
    All2 (fun t u => Σ ;;; Γ ⊢ t ≤s[Conv] u) args args' ->
    Σ ;;; Γ ⊢ mkApps (tInd i u) args ≤s[pb] mkApps (tInd i u') args'

| cumul_Construct : forall i k u u' args args',
    cumul_Construct_univ Σ pb i k #|args| u u' ->
    All2 (fun t u => Σ ;;; Γ ⊢ t ≤s[Conv] u) args args' ->
    Σ ;;; Γ ⊢ mkApps (tConstruct i k u) args ≤s[pb] mkApps (tConstruct i k u') args'

| cumul_Sort : forall s s',
    compare_sort Σ pb s s' ->
    Σ ;;; Γ ⊢ tSort s ≤s[pb] tSort s'

| cumul_Const : forall c u u',
    cmp_universe_instance (compare_universe Σ Conv) u u' ->
    Σ ;;; Γ ⊢ tConst c u ≤s[pb] tConst c u'

| cumul_Evar : forall e args args',
    All2 (fun t u => Σ ;;; Γ ⊢ t ≤s[Conv] u) args args' ->
    Σ ;;; Γ ⊢ tEvar e args ≤s[pb] tEvar e args'

| cumul_App : forall t t' u u',
    Σ ;;; Γ ⊢ t ≤s[pb] t' ->
    Σ ;;; Γ ⊢ u ≤s[Conv] u' ->
    Σ ;;; Γ ⊢ tApp t u ≤s[pb] tApp t' u'

| cumul_Lambda : forall na na' ty ty' t t',
    eq_binder_annot na na' ->
    Σ ;;; Γ ⊢ ty ≤s[Conv] ty' ->
    Σ ;;; Γ ,, vass na ty ⊢ t ≤s[Conv] t' ->
    Σ ;;; Γ ⊢ tLambda na ty t ≤s[pb] tLambda na' ty' t'

| cumul_Prod : forall na na' a a' b b',
    eq_binder_annot na na' ->
    Σ ;;; Γ ⊢ a ≤s[Conv] a' ->
    Σ ;;; Γ ,, vass na a ⊢ b ≤s[pb] b' ->
    Σ ;;; Γ ⊢ tProd na a b ≤s[pb] tProd na' a' b'

| cumul_LetIn : forall na na' t t' ty ty' u u',
    eq_binder_annot na na' ->
    Σ ;;; Γ ⊢ t ≤s[Conv] t' ->
    Σ ;;; Γ ⊢ ty ≤s[Conv] ty' ->
    Σ ;;; Γ ,, vdef na t ty ⊢ u ≤s[Conv] u' ->
    Σ ;;; Γ ⊢ tLetIn na t ty u ≤s[pb] tLetIn na' t' ty' u'

| cumul_Case indn : forall p p' c c' brs brs',
    cumul_predicate (fun Γ t u => Σ ;;; Γ ⊢ t ≤s[Conv] u) (compare_universe Σ Conv) Γ p p' ->
    Σ ;;; Γ ⊢ c ≤s[Conv] c' ->
    cumul_branches (fun Γ t u => Σ ;;; Γ ⊢ t ≤s[Conv] u) Γ p brs brs' ->
    Σ ;;; Γ ⊢ tCase indn p c brs ≤s[pb] tCase indn p' c' brs'

| cumul_Proj : forall p c c',
    Σ ;;; Γ ⊢ c ≤s[Conv] c' ->
    Σ ;;; Γ ⊢ tProj p c ≤s[pb] tProj p c'

| cumul_Fix : forall mfix mfix' idx,
    cumul_mfixpoint (fun Γ t u => Σ ;;; Γ ⊢ t ≤s[Conv] u) Γ mfix mfix' ->
    Σ ;;; Γ ⊢ tFix mfix idx ≤s[pb] tFix mfix' idx

| cumul_CoFix : forall mfix mfix' idx,
    cumul_mfixpoint (fun Γ t u => Σ ;;; Γ ⊢ t ≤s[Conv] u) Γ mfix mfix' ->
    Σ ;;; Γ ⊢ tCoFix mfix idx ≤s[pb] tCoFix mfix' idx

| cumul_Prim p p' :
  onPrims (fun x y => Σ ;;; Γ ⊢ x ≤s[Conv] y) (compare_universe Σ Conv) p p' ->
  Σ ;;; Γ ⊢ tPrim p ≤s[pb] tPrim p'

| cumul_beta : forall na t b a,
    Σ ;;; Γ ⊢ tApp (tLambda na t b) a ≤s[pb] b {0 := a}

| cumul_zeta : forall na b t b',
    Σ ;;; Γ ⊢ tLetIn na b t b' ≤s[pb] b' {0 := b}

| cumul_rel i body :
    option_map decl_body (nth_error Γ i) = Some (Some body) ->
    Σ ;;; Γ ⊢ tRel i ≤s[pb] lift0 (S i) body

| cumul_iota : forall ci c u args p brs br,
    nth_error brs c = Some br ->
    #|args| = (ci.(ci_npar) + context_assumptions br.(bcontext))%nat ->
    Σ ;;; Γ ⊢ tCase ci p (mkApps (tConstruct ci.(ci_ind) c u) args) brs  ≤s[pb] iota_red ci.(ci_npar) p args br

| cumul_fix : forall mfix idx args narg fn,
    unfold_fix mfix idx = Some (narg, fn) ->
    is_constructor narg args = true ->
    Σ ;;; Γ ⊢ mkApps (tFix mfix idx) args ≤s[pb] mkApps fn args

| cumul_cofix_case : forall ip p mfix idx args narg fn brs,
    unfold_cofix mfix idx = Some (narg, fn) ->
    Σ ;;; Γ ⊢ tCase ip p (mkApps (tCoFix mfix idx) args) brs ≤s[pb] tCase ip p (mkApps fn args) brs

| cumul_cofix_proj : forall p mfix idx args narg fn,
    unfold_cofix mfix idx = Some (narg, fn) ->
    Σ ;;; Γ ⊢ tProj p (mkApps (tCoFix mfix idx) args) ≤s[pb] tProj p (mkApps fn args)

| cumul_delta : forall c decl body (isdecl : declared_constant Σ c decl) u,
    decl.(cst_body) = Some body ->
    Σ ;;; Γ ⊢ tConst c u ≤s[pb] body@[u]

| cumul_proj : forall p args u arg,
    nth_error args (p.(proj_npars) + p.(proj_arg)) = Some arg ->
    Σ ;;; Γ ⊢ tProj p (mkApps (tConstruct p.(proj_ind) 0 u) args) ≤s[pb] arg

where " Σ ;;; Γ ⊢ t ≤s[ pb ] u " := (@cumulSpec0 _ Σ Γ pb t u) : type_scope.
Definition cumulSpec `{checker_flags} (Σ : global_env_ext) Γ := cumulSpec0 Σ Γ Cumul.

Notation " Σ ;;; Γ |- t <=s u " := (@cumulSpec _ Σ Γ t u) (at level 50, Γ, t, u at next level).

Module PCUICConversionParSpec <: EnvironmentTyping.ConversionParSig PCUICTerm PCUICEnvironment PCUICTermUtils PCUICEnvTyping.
End PCUICConversionParSpec.

End PCUICCumulativitySpec.

Implicit Types (cf : checker_flags) (Σ : global_env_ext).

Definition type_of_constructor mdecl (cdecl : constructor_body) (c : inductive * nat) (u : list Level.t) :=
  let mind := inductive_mind (fst c) in
  subst0 (inds mind u mdecl.(ind_bodies)) (subst_instance u (cstr_type cdecl)).

Include PCUICEnvTyping.

Inductive FixCoFix : Type := Fix | CoFix.

Class GuardChecker :=
{
  guard : FixCoFix -> global_env_ext -> context -> mfixpoint term -> Prop ;
}.

Axiom guard_checking : GuardChecker.
#[global]
Existing Instance guard_checking.

Definition fix_guard := guard Fix.
Definition cofix_guard := guard CoFix.

Definition destInd (t : term) :=
  match t with
  | tInd ind u => Some (ind, u)
  | _ => None
  end.

Definition isCoFinite (r : recursivity_kind) :=
  match r with
  | CoFinite => true
  | _ => false
  end.

Definition check_recursivity_kind
  (lookup: kername -> option global_decl) ind r :=
  match lookup ind with
  | Some (InductiveDecl mib) => ReflectEq.eqb mib.(ind_finite) r
  | _ => false
  end.

Definition check_one_fix d :=
  let '{| dname := na;
         dtype := ty;
         dbody := b;
         rarg := arg |} := d in
  let '(ctx, ty) := decompose_prod_assum [] ty in
  match nth_error (List.rev (smash_context [] ctx)) arg with
  | Some argd =>
    let (hd, args) := decompose_app argd.(decl_type) in
    match destInd hd with
    | Some (mkInd mind _, u) => Some mind
    | None => None
    end
  | None => None
  end.

Definition wf_fixpoint_gen
  (lookup: kername -> option global_decl) mfix :=
  forallb (isLambda ∘ dbody) mfix &&
  let checks := map check_one_fix mfix in
  match map_option_out checks with
  | Some (ind :: inds) =>

    forallb (eqb ind) inds &&
    check_recursivity_kind lookup ind Finite
  | _ => false
  end.

Definition wf_fixpoint (Σ : global_env) := wf_fixpoint_gen (lookup_env Σ).

Definition check_one_cofix d :=
  let '{| dname := na;
         dtype := ty;
         dbody := b;
         rarg := arg |} := d in
  let '(ctx, ty) := decompose_prod_assum [] ty in
  let (hd, args) := decompose_app ty in
  match destInd hd with
  | Some (mkInd ind _, u) => Some ind
  | None => None
  end.

Definition wf_cofixpoint_gen
  (lookup: kername -> option global_decl) mfix :=
  let checks := map check_one_cofix mfix in
  match map_option_out checks with
  | Some (ind :: inds) =>

    forallb (eqb ind) inds &&
    check_recursivity_kind lookup ind CoFinite
  | _ => false
  end.

Definition wf_cofixpoint (Σ : global_env) := wf_cofixpoint_gen (lookup_env Σ).

Reserved Notation "'wf_local' Σ Γ " (at level 9, Σ, Γ at next level).

Reserved Notation " Σ ;;; Γ |- t : T " (at level 50, Γ, t, T at next level).

Variant case_side_conditions `{checker_flags} wf_local_fun typing Σ Γ ci p ps mdecl idecl indices predctx :=
| case_side_info
    (eq_npars : mdecl.(ind_npars) = ci.(ci_npar))
    (wf_pred : wf_predicate mdecl idecl p)
    (cons : consistent_instance_ext Σ (ind_universes mdecl) p.(puinst))
    (wf_pctx : wf_local_fun Σ (Γ ,,, predctx))

    (conv_pctx : eq_context_upto_names p.(pcontext) (ind_predicate_context ci.(ci_ind) mdecl idecl))
    (allowed_elim : is_allowed_elimination Σ idecl.(ind_kelim) ps)
    (elim_relevance : isSortRel ps ci.(ci_relevance))
    (ind_inst : ctx_inst (typing Σ) Γ (p.(pparams) ++ indices)
                         (List.rev (subst_instance p.(puinst)
                                                   (ind_params mdecl ,,, ind_indices idecl : context))))
    (not_cofinite : isCoFinite mdecl.(ind_finite) = false).

Variant case_branch_typing `{checker_flags} wf_local_fun typing Σ Γ (ci:case_info) p ps mdecl idecl ptm  brs :=
| case_branch_info
    (wf_brs : wf_branches idecl brs)
    (brs_ty :
       All2i (fun i cdecl br =>

                eq_context_upto_names br.(bcontext) (cstr_branch_context ci mdecl cdecl) ×
                let brctxty := case_branch_type ci.(ci_ind) mdecl idecl p br ptm i cdecl in
                (wf_local_fun Σ (Γ ,,, brctxty.1) ×
                ((typing Σ (Γ ,,, brctxty.1) br.(bbody) (brctxty.2)) ×
                (typing Σ (Γ ,,, brctxty.1) brctxty.2 (tSort ps)))))
             0 idecl.(ind_ctors) brs).

Variant primitive_typing_hyps `{checker_flags}
  (typing : forall (Σ : global_env_ext) (Γ : context), term -> term -> Type)
  Σ Γ : prim_val term -> Type :=
| prim_int_hyps i : primitive_typing_hyps typing Σ Γ (primInt; primIntModel i)
| prim_float_hyps f : primitive_typing_hyps typing Σ Γ (primFloat; primFloatModel f)
| prim_string_hyps s : primitive_typing_hyps typing Σ Γ (primString; primStringModel s)
| prim_array_hyps a
  (wfl : wf_universe Σ (Universe.make' a.(array_level)))
  (hty : typing Σ Γ a.(array_type) (tSort (sType (Universe.make' a.(array_level)))))
  (hdef : typing Σ Γ a.(array_default) a.(array_type))
  (hvalue : All (fun x => typing Σ Γ x a.(array_type)) a.(array_value)) :
  primitive_typing_hyps typing Σ Γ (primArray; primArrayModel a).

Equations prim_type (p : prim_val term) (cst : kername) : term :=
prim_type (primInt; _) cst := tConst cst [];
prim_type (primFloat; _) cst := tConst cst [];
prim_type (primString; _) cst := tConst cst [];
prim_type (primArray; primArrayModel a) cst := tApp (tConst cst [a.(array_level)]) a.(array_type).

Inductive typing `{checker_flags} (Σ : global_env_ext) (Γ : context) : term -> term -> Type :=
| type_Rel : forall n decl,
    wf_local Σ Γ ->
    nth_error Γ n = Some decl ->
    Σ ;;; Γ |- tRel n : lift0 (S n) decl.(decl_type)

| type_Sort : forall s,
    wf_local Σ Γ ->
    wf_sort Σ s ->
    Σ ;;; Γ |- tSort s : tSort (Sort.super s)

| type_Prod : forall na A B s1 s2,
    lift_typing typing Σ Γ (j_vass_s na A s1) ->
    Σ ;;; Γ ,, vass na A |- B : tSort s2 ->
    Σ ;;; Γ |- tProd na A B : tSort (Sort.sort_of_product s1 s2)

| type_Lambda : forall na A t B,
    lift_typing typing Σ Γ (j_vass na A) ->
    Σ ;;; Γ ,, vass na A |- t : B ->
    Σ ;;; Γ |- tLambda na A t : tProd na A B

| type_LetIn : forall na b B t A,
    lift_typing typing Σ Γ (j_vdef na b B) ->
    Σ ;;; Γ ,, vdef na b B |- t : A ->
    Σ ;;; Γ |- tLetIn na b B t : tLetIn na b B A

| type_App : forall t na A B s u,

    Σ ;;; Γ |- tProd na A B : tSort s ->
    Σ ;;; Γ |- t : tProd na A B ->
    Σ ;;; Γ |- u : A ->
    Σ ;;; Γ |- tApp t u : B{0 := u}

| type_Const : forall cst u decl,
    wf_local Σ Γ ->
    declared_constant Σ cst decl ->
    consistent_instance_ext Σ decl.(cst_universes) u ->
    Σ ;;; Γ |- tConst cst u : decl.(cst_type)@[u]

| type_Ind : forall ind u mdecl idecl,
    wf_local Σ Γ ->
    declared_inductive Σ ind mdecl idecl ->
    consistent_instance_ext Σ mdecl.(ind_universes) u ->
    Σ ;;; Γ |- tInd ind u : idecl.(ind_type)@[u]

| type_Construct : forall ind i u mdecl idecl cdecl,
    wf_local Σ Γ ->
    declared_constructor Σ (ind, i) mdecl idecl cdecl ->
    consistent_instance_ext Σ mdecl.(ind_universes) u ->
    Σ ;;; Γ |- tConstruct ind i u : type_of_constructor mdecl cdecl (ind, i) u

| type_Case : forall ci p c brs indices ps mdecl idecl,
    let predctx := case_predicate_context ci.(ci_ind) mdecl idecl p in
    let ptm := it_mkLambda_or_LetIn predctx p.(preturn) in
    declared_inductive Σ ci.(ci_ind) mdecl idecl ->
    Σ ;;; Γ ,,, predctx |- p.(preturn) : tSort ps ->
    Σ ;;; Γ |- c : mkApps (tInd ci.(ci_ind) p.(puinst)) (p.(pparams) ++ indices) ->
    case_side_conditions (fun Σ Γ => wf_local Σ Γ) typing Σ Γ ci p ps
                         mdecl idecl indices predctx  ->
    case_branch_typing (fun Σ Γ => wf_local Σ Γ) typing Σ Γ ci p ps
                        mdecl idecl ptm brs ->
    Σ ;;; Γ |- tCase ci p c brs : mkApps ptm (indices ++ [c])

| type_Proj : forall p c u mdecl idecl cdecl pdecl args,
    declared_projection Σ p mdecl idecl cdecl pdecl ->
    Σ ;;; Γ |- c : mkApps (tInd p.(proj_ind) u) args ->
    #|args| = ind_npars mdecl ->
    Σ ;;; Γ |- tProj p c : subst0 (c :: List.rev args) pdecl.(proj_type)@[u]

| type_Fix : forall mfix n decl,
    wf_local Σ Γ ->
    fix_guard Σ Γ mfix ->
    nth_error mfix n = Some decl ->
    All (on_def_type (lift_typing1 (typing Σ)) Γ) mfix ->
    All (on_def_body (lift_typing1 (typing Σ)) (fix_context mfix) Γ) mfix ->
    wf_fixpoint Σ mfix ->
    Σ ;;; Γ |- tFix mfix n : decl.(dtype)

| type_CoFix : forall mfix n decl,
    wf_local Σ Γ ->
    cofix_guard Σ Γ mfix ->
    nth_error mfix n = Some decl ->
    All (on_def_type (lift_typing1 (typing Σ)) Γ) mfix ->
    All (on_def_body (lift_typing1 (typing Σ)) (fix_context mfix) Γ) mfix ->
    wf_cofixpoint Σ mfix ->
    Σ ;;; Γ |- tCoFix mfix n : decl.(dtype)

| type_Prim 
10000
p prim_ty cdecl :
    wf_local Σ Γ ->
    primitive_constant Σ (prim_val_tag p) = Some prim_ty ->
    declared_constant Σ prim_ty cdecl ->
    primitive_invariants (prim_val_tag p) cdecl ->
    primitive_typing_hyps typing Σ Γ p ->
    Σ ;;; Γ |- tPrim p : prim_type p prim_ty

| type_Cumul : forall t A B s,
    Σ ;;; Γ |- t : A ->
    Σ ;;; Γ |- B : tSort s ->
    Σ ;;; Γ |- A <=s B ->
    Σ ;;; Γ |- t : B

where " Σ ;;; Γ |- t : T " := (typing Σ Γ t T)
and "'wf_local' Σ Γ " := (All_local_env (lift_typing1 (typing Σ)) Γ).

Definition wf `{checker_flags} := on_global_env cumulSpec0 (lift_typing typing).
Notation on_contexts_length := All2_fold_length.
Import Stdlib.Classes.CRelationClasses.

Definition ws_term P := { t : term | on_free_vars P t }.
Definition ws_term_proj {P} (t : ws_term P) : term.
admit.
Defined.
Coercion ws_term_proj : ws_term >-> term.

Definition ws_context P := { t : context | on_free_vars_ctx P t }.

Notation closed_context := (ws_context xpred0).
Notation open_term Γ := (ws_term (shiftnP #|Γ| xpred0)).
Definition ws_context_proj' {P} (t : ws_context P) : list context_decl.
Admitted.
Coercion ws_context_proj' : ws_context >-> list.

Definition ws_red1 Σ P (Γ : ws_context P) (t u : ws_term (shiftnP #|Γ| P)) :=
  red1 Σ Γ t u.

Definition ws_red Σ P (Γ : ws_context P) := clos_refl_trans (ws_red1 Σ P Γ).

Definition ws_pair :=
  ∑ Γ : ws_context xpred0, ws_term (shiftnP #|Γ| xpred0).

Section RedConfluence.
  Context {cf : checker_flags}.
  Context {Σ : global_env_ext} (wfΣ : wf Σ).
Definition red1_rel_alpha : relation ws_pair.
exact (relation_disjunction (A:=ws_pair) (fun '(Γ; t) '(Δ; u) => (red1 Σ Γ t u * (Γ = Δ)))%type
     (relation_disjunction (A:=ws_pair)
        (fun '(Γ; t) '(Δ; u) => ((red1_ctx Σ Γ Δ * (t = u :> term))))
        (fun '(Γ; t) '(Δ; u) => ((eq_context_upto_names Γ Δ * (t = u :> term)))))%type).
Defined.

  Lemma red_ws_red (Γ : closed_context) (x y : ws_term (shiftnP #|Γ| xpred0)) :
    red Σ Γ x y -> ws_red Σ xpred0 Γ x y.
Admitted.
Definition transport_ws_term {n m : nat} (t : ws_term (shiftnP n xpred0)) (eq : n = m) : ws_term (shiftnP m xpred0).
Admitted.
Definition red_ctx_alpha : relation context.
exact (All2_fold (fun Γ _ => All_decls_alpha (red Σ Γ))).
Defined.

  Instance red_ctx_alpha_refl : Reflexive red_ctx_alpha.
Admitted.

  Lemma ws_red_refl_irrel P (Γ : ws_context P) (x y : ws_term (shiftnP #|Γ| P)) :
    x = y :> term ->
    ws_red Σ P Γ x y.
Admitted.

  Lemma clos_rt_red1_alpha_out x y :
    clos_refl_trans red1_rel_alpha x y ->
    ∑ redctx : red_ctx_alpha x.π1 y.π1,
      ws_red Σ xpred0 x.π1 x.π2 (transport_ws_term y.π2 (symmetry (All2_fold_length redctx))).
  Proof using wfΣ.
    intros H.
    eapply clos_rt_rt1n_iff in H.
    induction H.
    -
 unshelve eexists.
reflexivity.
eapply ws_red_refl_irrel => //.
    -
 destruct x as [Γ t], y as [Δ u], z as [Δ' u']; simpl in *.
      destruct IHclos_refl_trans_1n.
      red in r.
destruct r.
      *
 destruct p.
subst.
exists x.
        transitivity u; auto.
        now eapply red_ws_red.
      *
 destruct t as [t ht], u as [u hu];
        move: r; case; move => [] r eq; noconf eq.
🛠️ Intermediate Coq File (useful for debugging if minimization did not go as far as you wanted) (truncated to 6.0KiB; full 109KiB file on GitHub Actions Artifacts under tmp.v)
(* -*- mode: coq; coq-prog-args: ("-emacs" "-q" "-w" "-deprecated-native-compiler-option" "-native-compiler" "no" "-coqlib" "/github/workspace/builds/coq/coq-failing/_install_ci/lib/coq//" "-R" "/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/utils/theories" "MetaRocq.Utils" "-R" "/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/common/theories" "MetaRocq.Common" "-R" "/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/pcuic/theories" "MetaRocq.PCUIC" "-Q" "/github/workspace/cwd" "Top" "-Q" "/github/workspace/builds/coq/coq-failing/_install_ci/lib/coq///user-contrib/Equations" "Equations" "-Q" "/github/workspace/builds/coq/coq-failing/_install_ci/lib/coq///user-contrib/Ltac2" "Ltac2" "-Q" "/github/workspace/builds/coq/coq-failing/_install_ci/lib/coq///user-contrib/Stdlib" "Stdlib" "-top" "Top.bug_01") -*- *)
(* File reduced by coq-bug-minimizer from original input, then from 3959 lines to 98 lines, then from 111 lines to 3187 lines, then from 3191 lines to 96 lines, then from 107 lines to 1813 lines, then from 1818 lines to 359 lines, then from 369 lines to 1502 lines, then from 1506 lines to 524 lines, then from 535 lines to 3221 lines, then from 3222 lines to 656 lines, then from 667 lines to 2894 lines, then from 2900 lines to 656 lines, then from 667 lines to 1321 lines, then from 1327 lines to 874 lines, then from 883 lines to 675 lines, then from 686 lines to 2746 lines, then from 2745 lines to 687 lines, then from 698 lines to 3155 lines, then from 3155 lines to 745 lines, then from 756 lines to 1586 lines, then from 1589 lines to 869 lines, then from 880 lines to 2395 lines, then from 2394 lines to 885 lines, then from 895 lines to 2754 lines, then from 2755 lines to 1157 lines, then from 1161 lines to 1145 lines, then from 1156 lines to 1809 lines, then from 1813 lines to 1200 lines, then from 1211 lines to 4024 lines, then from 4021 lines to 1355 lines, then from 1366 lines to 3048 lines, then from 3051 lines to 1938 lines, then from 1928 lines to 1518 lines, then from 1529 lines to 1814 lines, then from 1819 lines to 1523 lines, then from 1533 lines to 2340 lines, then from 2342 lines to 1526 lines, then from 1536 lines to 4638 lines, then from 4602 lines to 1892 lines, then from 1903 lines to 3075 lines, then from 3076 lines to 2771 lines, then from 2762 lines to 1985 lines, then from 1996 lines to 2830 lines, then from 2835 lines to 2048 lines, then from 2059 lines to 2413 lines, then from 2418 lines to 2052 lines, then from 2063 lines to 2597 lines, then from 2601 lines to 2063 lines, then from 2074 lines to 6642 lines, then from 6641 lines to 4802 lines, then from 4761 lines to 2105 lines, then from 2116 lines to 2604 lines, then from 2606 lines to 2117 lines, then from 2128 lines to 3899 lines, then from 3897 lines to 2137 lines, then from 2148 lines to 2516 lines, then from 2521 lines to 2151 lines, then from 2161 lines to 2404 lines, then from 2409 lines to 2150 lines, then from 2161 lines to 2447 lines, then from 2449 lines to 2162 lines, then from 2178 lines to 2162 lines, then from 2173 lines to 2602 lines, then from 2607 lines to 2180 lines, then from 2190 lines to 2437 lines, then from 2442 lines to 2200 lines, then from 2210 lines to 2368 lines, then from 2373 lines to 2201 lines, then from 2211 lines to 2367 lines, then from 2371 lines to 2204 lines, then from 2214 lines to 2934 lines, then from 2939 lines to 2250 lines, then from 2261 lines to 2593 lines, then from 2598 lines to 2252 lines, then from 2263 lines to 2633 lines, then from 2637 lines to 2623 lines, then from 2621 lines to 2324 lines, then from 2335 lines to 2934 lines, then from 2939 lines to 2302 lines, then from 2313 lines to 2654 lines, then from 2656 lines to 2311 lines, then from 2322 lines to 2473 lines, then from 2478 lines to 2312 lines, then from 2322 lines to 2470 lines, then from 2475 lines to 2312 lines, then from 2323 lines to 2571 lines, then from 2576 lines to 2353 lines, then from 2363 lines to 2478 lines, then from 2483 lines to 2368 lines, then from 2379 lines to 3181 lines *)
(* coqc version 9.1+alpha compiled with OCaml 4.14.2
   coqtop version runner-t7b1znuaq-project-4504-concurrent-2:/builds/coq/coq/_build/default,(HEAD detached at cdd06d0a2f356e) (cdd06d0a2f356e0c02e2d20356562b7deae4cf15)
   Expected coqc runtime on this file: 0.000 sec *)
Require Coq.Init.Ltac.
Module Export AdmitTactic.
Module Import LocalFalse.
Inductive False : Prop := .
End LocalFalse.
Axiom proof_admitted : False.
Import Coq.Init.Ltac.
Tactic Notation "admit" := abstract case proof_admitted.
End AdmitTactic.
Require MetaRocq.Common.config.
Require Stdlib.MSets.MSetList.
Require Stdlib.MSets.MSetAVL.
Require Corelib.Floats.FloatOps.
Require Corelib.Strings.PrimString.
Require Corelib.Program.Tactics.
Require Corelib.Relations.Relation_Definitions.
Require Corelib.extraction.Extraction.
Require Stdlib.Unicode.Utf8_core.
Require Stdlib.Program.Tactics.
Require Stdlib.Relations.Relation_Definitions.
Require Stdlib.extraction.Extraction.
Require Equations.Init.
Require Equations.Prop.SigmaNotations.
Require Equations.Signature.
Require Equations.CoreTactics.
Require Equations.Prop.Logic.
Require Equations.Prop.Classes.
Require Equations.Prop.EqDec.

Module Equations_DOT_Prop_DOT_DepElim_WRAPPED.
Module DepElim.
(**********************************************************************)
(* Equations                                                          *)
(* Copyright (c) 2009-2020 Matthieu Sozeau <matthieu.sozeau@inria.fr> *)
(**********************************************************************)
(* This file is distributed under the terms of the                    *)
(* GNU Lesser General Public License Version 2.1                      *)
(**********************************************************************)

(** Tactics related to (dependent) equality and proof irrelevance. *)
Import Stdlib.Program.Tactics.
Export Equations.Init.
Import Equations.CoreTactics.
Import Equations.Signature.
Import Equations.Prop.Logic.
Import Equations.Prop.Classes.
Import Equations.Prop.EqDec.

Import Sigma_Notations.
Local Open Sco
🛠️ 📜 Intermediate Coq File log (useful for debugging if minimization did not go as far as you wanted)
📜 Build Log (contains the Coq error message) (truncated to last 8.0KiB; full 7.0MiB file on GitHub Actions Artifacts under build.log)
t-minimizer.vT6FTBjRlc
MINIMIZER_DEBUG: files: 
make[2]: Leaving directory '/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/template-rocq'
# Ensure the cmxs is built before the loader file 
make -f Makefile.plugin gen-src/metarocq_template_plugin.cmxs
make[2]: Entering directory '/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/template-rocq'
MINIMIZER_DEBUG_EXTRA: coqc: /github/workspace/builds/coq/coq-failing/_install_ci/bin///rocq
MINIMIZER_DEBUG_EXTRA: original invocation: c --print-version 
MINIMIZER_DEBUG_EXTRA: new invocation: /github/workspace/builds/coq/coq-failing/_install_ci/bin/rocq.orig c --print-version 
MINIMIZER_DEBUG_EXTRA: coqpath: 
MINIMIZER_DEBUG_EXTRA: ocamlpath: /github/workspace/builds/coq/coq-failing/_build_ci/metarocq/template-rocq/:/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/safechecker-plugin/src:/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/erasure-plugin/src:/github/workspace/builds/coq/coq-failing/_install_ci/lib:
MINIMIZER_DEBUG_EXTRA: pwd: PWD=/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/template-rocq
MINIMIZER_DEBUG_EXTRA: exec: /github/workspace/builds/coq/coq-failing/_install_ci/bin/rocq.orig c --print-version 
MINIMIZER_DEBUG_EXTRA: coqlib: Warning: Deprecated environment variable COQLIB, use ROCQLIB instead.
/github/workspace/builds/coq/coq-failing/_install_ci/lib/coq//
MINIMIZER_DEBUG: info: /tmp/tmp-coqbot-minimizer.7ZZaIVRN7D
MINIMIZER_DEBUG: files: 
make[2]: 'gen-src/metarocq_template_plugin.cmxs' is up to date.
make[2]: Leaving directory '/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/template-rocq'
make -f Makefile.plugin
make[2]: Entering directory '/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/template-rocq'
MINIMIZER_DEBUG_EXTRA: coqc: /github/workspace/builds/coq/coq-failing/_install_ci/bin///rocq
MINIMIZER_DEBUG_EXTRA: original invocation: c --print-version 
MINIMIZER_DEBUG_EXTRA: new invocation: /github/workspace/builds/coq/coq-failing/_install_ci/bin/rocq.orig c --print-version 
MINIMIZER_DEBUG_EXTRA: coqpath: 
MINIMIZER_DEBUG_EXTRA: ocamlpath: /github/workspace/builds/coq/coq-failing/_build_ci/metarocq/template-rocq/:/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/safechecker-plugin/src:/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/erasure-plugin/src:/github/workspace/builds/coq/coq-failing/_install_ci/lib:
MINIMIZER_DEBUG_EXTRA: pwd: PWD=/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/template-rocq
MINIMIZER_DEBUG_EXTRA: exec: /github/workspace/builds/coq/coq-failing/_install_ci/bin/rocq.orig c --print-version 
MINIMIZER_DEBUG_EXTRA: coqlib: Warning: Deprecated environment variable COQLIB, use ROCQLIB instead.
/github/workspace/builds/coq/coq-failing/_install_ci/lib/coq//
MINIMIZER_DEBUG: info: /tmp/tmp-coqbot-minimizer.QkzxGj8xqZ
MINIMIZER_DEBUG: files: 
MINIMIZER_DEBUG_EXTRA: coqc: /github/workspace/builds/coq/coq-failing/_install_ci/bin/////rocq
MINIMIZER_DEBUG_EXTRA: original invocation: c --print-version 
MINIMIZER_DEBUG_EXTRA: new invocation: /github/workspace/builds/coq/coq-failing/_install_ci/bin/rocq.orig c --print-version 
MINIMIZER_DEBUG_EXTRA: coqpath: 
MINIMIZER_DEBUG_EXTRA: ocamlpath: /github/workspace/builds/coq/coq-failing/_build_ci/metarocq/template-rocq/:/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/safechecker-plugin/src:/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/erasure-plugin/src:/github/workspace/builds/coq/coq-failing/_install_ci/lib:
MINIMIZER_DEBUG_EXTRA: pwd: PWD=/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/template-rocq
MINIMIZER_DEBUG_EXTRA: exec: /github/workspace/builds/coq/coq-failing/_install_ci/bin/rocq.orig c --print-version 
MINIMIZER_DEBUG_EXTRA: coqlib: Warning: Deprecated environment variable COQLIB, use ROCQLIB instead.
/github/workspace/builds/coq/coq-failing/_install_ci/lib/coq//
MINIMIZER_DEBUG: info: /tmp/tmp-coqbot-minimizer.oUqH2hdUXG
MINIMIZER_DEBUG: files: 
MINIMIZER_DEBUG_EXTRA: coqc: /github/workspace/builds/coq/coq-failing/_install_ci/bin/////rocq
MINIMIZER_DEBUG_EXTRA: original invocation: c --print-version 
MINIMIZER_DEBUG_EXTRA: new invocation: /github/workspace/builds/coq/coq-failing/_install_ci/bin/rocq.orig c --print-version 
MINIMIZER_DEBUG_EXTRA: coqpath: 
MINIMIZER_DEBUG_EXTRA: ocamlpath: /github/workspace/builds/coq/coq-failing/_build_ci/metarocq/template-rocq/:/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/safechecker-plugin/src:/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/erasure-plugin/src:/github/workspace/builds/coq/coq-failing/_install_ci/lib:
MINIMIZER_DEBUG_EXTRA: pwd: PWD=/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/template-rocq
MINIMIZER_DEBUG_EXTRA: exec: /github/workspace/builds/coq/coq-failing/_install_ci/bin/rocq.orig c --print-version 
MINIMIZER_DEBUG_EXTRA: coqlib: Warning: Deprecated environment variable COQLIB, use ROCQLIB instead.
/github/workspace/builds/coq/coq-failing/_install_ci/lib/coq//
MINIMIZER_DEBUG: info: /tmp/tmp-coqbot-minimizer.p4gZhGKVHm
MINIMIZER_DEBUG: files: 
make[3]: Nothing to be done for 'real-all'.
MINIMIZER_DEBUG_EXTRA: coqc: /github/workspace/builds/coq/coq-failing/_install_ci/bin/////rocq
MINIMIZER_DEBUG_EXTRA: original invocation: c --print-version 
MINIMIZER_DEBUG_EXTRA: new invocation: /github/workspace/builds/coq/coq-failing/_install_ci/bin/rocq.orig c --print-version 
MINIMIZER_DEBUG_EXTRA: coqpath: 
MINIMIZER_DEBUG_EXTRA: ocamlpath: /github/workspace/builds/coq/coq-failing/_build_ci/metarocq/template-rocq/:/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/safechecker-plugin/src:/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/erasure-plugin/src:/github/workspace/builds/coq/coq-failing/_install_ci/lib:
MINIMIZER_DEBUG_EXTRA: pwd: PWD=/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/template-rocq
MINIMIZER_DEBUG_EXTRA: exec: /github/workspace/builds/coq/coq-failing/_install_ci/bin/rocq.orig c --print-version 
MINIMIZER_DEBUG_EXTRA: coqlib: Warning: Deprecated environment variable COQLIB, use ROCQLIB instead.
/github/workspace/builds/coq/coq-failing/_install_ci/lib/coq//
MINIMIZER_DEBUG: info: /tmp/tmp-coqbot-minimizer.bqm0Xjxjhu
MINIMIZER_DEBUG: files: 
make[2]: Leaving directory '/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/template-rocq'
make[1]: Leaving directory '/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/template-rocq'
File "./theories/PCUICConfluence.v", line 3649, characters 47-49:
Error: Cannot infer the implicit parameter A of eq whose type is 
"Type" in
environment:
cf : checker_flags
Σ : global_env_ext
wfΣ : wf Σ
Γ : closed_context
t : term
ht : is_open_term Γ t
Δ : closed_context
u : term
hu : is_open_term Δ u
Δ' : closed_context
u' : open_term Δ'
H : clos_refl_trans_1n red1_rel_alpha (Δ; exist u hu) (Δ'; u')
x : red_ctx_alpha Δ Δ'
w :
  ws_red Σ xpred0 Δ (exist u hu)
    (transport_ws_term u' (symmetry (on_contexts_length x)))
r : red1_ctx Σ Γ Δ
eq : exist t ht = exist u hu

Command exited with non-zero status 1
theories/PCUICConfluence.vo (real: 46.44, user: 46.01, sys: 0.39, mem: 2429940 ko)
make[3]: *** [Makefile.rocq:814: theories/PCUICConfluence.vo] Error 1
make[3]: *** [theories/PCUICConfluence.vo] Deleting file 'theories/PCUICConfluence.glob'
make[2]: *** [Makefile.rocq:412: all] Error 2
make[2]: Leaving directory '/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/pcuic'
make[1]: *** [Makefile:11: coq] Error 2
make[1]: Leaving directory '/github/workspace/builds/coq/coq-failing/_build_ci/metarocq/pcuic'
make: *** [Makefile:149: pcuic] Error 2
+ code=2
+ printf '\n%s exit code: %s\n' metarocq 2
+ '[' metarocq '!=' stdlib_test ']'
+ echo 'Aggregating timing log...'
Aggregating timing log...
+ echo

+ tools/make-one-time-file.py --real metarocq.log
    Time |   Peak Mem | File Name            
---------------------------------------------
0m46.44s | 2429940 ko | Total Time / Peak Mem
---------------------------------------------
0m46.44s | 2429940 ko | PCUICConfluence.vo   
+ '[' '' ']'
+ exit 2
/github/workspace/builds/coq /github/workspace
::endgroup::
📜 🔎 Minimization Log (truncated to last 8.0KiB; full 4.0MiB file on GitHub Actions Artifacts under bug.log)
ons.


�[93mIntermediate code not saved.�[0m
Failed to do everything at once; trying one at a time.
Admitting lemmas unsuccessful.
No successful changes.

I will now attempt to admit definitions with admit. Defined

Non-fatal error: Failed to admit definitions and preserve the error.  
The new error was:
Deprecated environment variable COQCORELIB, use ROCQRUNTIMELIB instead.
Warning: Deprecated environment variable COQCORELIB,
use ROCQRUNTIMELIB instead.
[deprecated-coq-env-var,deprecated-since-9.0,deprecated,default]
File "/tmp/tmpq8gokyvv/Top/bug_01.v", line 204, characters 7-20:
Warning: Coq.Init.Ltac has been replaced by Corelib.Init.Ltac.
[deprecated-dirpath-Coq,deprecated-since-9.0,deprecated,default]
File "/tmp/tmpq8gokyvv/Top/bug_01.v", line 1036, characters 0-11:
Error: Signature components for field eq do not match:
the body of definitions differs.


�[93mIntermediate code not saved.�[0m
Failed to do everything at once; trying one at a time.
Admitting definitions unsuccessful.
No successful changes.

I will now attempt to admit lemmas with Admitted with Proof using

Non-fatal error: Failed to admit lemmas and preserve the error.  
The new error was:
Deprecated environment variable COQCORELIB, use ROCQRUNTIMELIB instead.
Warning: Deprecated environment variable COQCORELIB,
use ROCQRUNTIMELIB instead.
[deprecated-coq-env-var,deprecated-since-9.0,deprecated,default]
File "/tmp/tmpreme6k51/Top/bug_01.v", line 204, characters 7-20:
Warning: Coq.Init.Ltac has been replaced by Corelib.Init.Ltac.
[deprecated-dirpath-Coq,deprecated-since-9.0,deprecated,default]
File "/tmp/tmpreme6k51/Top/bug_01.v", line 1119, characters 0-62:
Warning: Notation "_ <-> _" was already used in scope type_scope.
[notation-overridden,parsing,default]
File "/tmp/tmpreme6k51/Top/bug_01.v", line 1257, characters 0-45:
Warning: Declaring a scope implicitly is deprecated; use in advance an
explicit "Declare Scope type_scope2.".
[undeclared-scope,deprecated-since-8.10,deprecated,default]
File "/tmp/tmpreme6k51/Top/bug_01.v", line 1789, characters 0-38:
Warning:
Solve Obligations tactic returned error: Tactic failure: Equations.Init.solve_eqdec has not been bound yet.
This will become an error in the future
[solve_obligation_error,tactics,default]
File "/tmp/tmpreme6k51/Top/bug_01.v", line 2232, characters 0-459:
Warning:
Solve Obligations tactic returned error: not found in table: equations.sigma.type
This will become an error in the future
[solve_obligation_error,tactics,default]
File "/tmp/tmpreme6k51/Top/bug_01.v", line 2232, characters 0-459:
Warning:
Functional induction/elimination principle could not be proved automatically: it is left as an obligation.
[functional-induction-derivation-failure,equations,default]
File "/tmp/tmpreme6k51/Top/bug_01.v", line 3106, characters 0-304:
Warning:
Functional induction/elimination principle could not be proved automatically: 
Couldn't rewrite [functional-induction-derivation-failure,equations,default]
File "/tmp/tmpreme6k51/Top/bug_01.v", line 3106, characters 0-304:
Warning:
Functional induction/elimination principle could not be proved automatically: it is left as an obligation.
[functional-induction-derivation-failure,equations,default]
Error: Unsolved obligations when closing file /tmp/tmpreme6k51/Top/bug_01.v:
 have unsolved obligations.


�[93mIntermediate code not saved.�[0m
Failed to do everything at once; trying one at a time.
Admitting lemmas unsuccessful.
No successful changes.

I will now attempt to admit definitions with Admitted with Proof using

Non-fatal error: Failed to admit definitions and preserve the error.  
The new error was:
Deprecated environment variable COQCORELIB, use ROCQRUNTIMELIB instead.
Warning: Deprecated environment variable COQCORELIB,
use ROCQRUNTIMELIB instead.
[deprecated-coq-env-var,deprecated-since-9.0,deprecated,default]
File "/tmp/tmpotsvzxxd/Top/bug_01.v", line 204, characters 7-20:
Warning: Coq.Init.Ltac has been replaced by Corelib.Init.Ltac.
[deprecated-dirpath-Coq,deprecated-since-9.0,deprecated,default]
File "/tmp/tmpotsvzxxd/Top/bug_01.v", line 1034, characters 0-11:
Error: Signature components for field eq do not match:
the body of definitions differs.


�[93mIntermediate code not saved.�[0m
Failed to do everything at once; trying one at a time.
Admitting definitions unsuccessful.
No successful changes.

I will now attempt to admit lemmas with admit. Defined with Proof using

Non-fatal error: Failed to admit lemmas and preserve the error.  
The new error was:
Deprecated environment variable COQCORELIB, use ROCQRUNTIMELIB instead.
Warning: Deprecated environment variable COQCORELIB,
use ROCQRUNTIMELIB instead.
[deprecated-coq-env-var,deprecated-since-9.0,deprecated,default]
File "/tmp/tmpa4tqbht2/Top/bug_01.v", line 204, characters 7-20:
Warning: Coq.Init.Ltac has been replaced by Corelib.Init.Ltac.
[deprecated-dirpath-Coq,deprecated-since-9.0,deprecated,default]
File "/tmp/tmpa4tqbht2/Top/bug_01.v", line 1119, characters 0-62:
Warning: Notation "_ <-> _" was already used in scope type_scope.
[notation-overridden,parsing,default]
File "/tmp/tmpa4tqbht2/Top/bug_01.v", line 1257, characters 0-45:
Warning: Declaring a scope implicitly is deprecated; use in advance an
explicit "Declare Scope type_scope2.".
[undeclared-scope,deprecated-since-8.10,deprecated,default]
File "/tmp/tmpa4tqbht2/Top/bug_01.v", line 1789, characters 0-38:
Warning:
Solve Obligations tactic returned error: Tactic failure: Equations.Init.solve_eqdec has not been bound yet.
This will become an error in the future
[solve_obligation_error,tactics,default]
File "/tmp/tmpa4tqbht2/Top/bug_01.v", line 2232, characters 0-459:
Warning:
Solve Obligations tactic returned error: not found in table: equations.sigma.type
This will become an error in the future
[solve_obligation_error,tactics,default]
File "/tmp/tmpa4tqbht2/Top/bug_01.v", line 2232, characters 0-459:
Warning:
Functional induction/elimination principle could not be proved automatically: it is left as an obligation.
[functional-induction-derivation-failure,equations,default]
File "/tmp/tmpa4tqbht2/Top/bug_01.v", line 3106, characters 0-304:
Warning:
Functional induction/elimination principle could not be proved automatically: 
Couldn't rewrite [functional-induction-derivation-failure,equations,default]
File "/tmp/tmpa4tqbht2/Top/bug_01.v", line 3106, characters 0-304:
Warning:
Functional induction/elimination principle could not be proved automatically: it is left as an obligation.
[functional-induction-derivation-failure,equations,default]
Error: Unsolved obligations when closing file /tmp/tmpa4tqbht2/Top/bug_01.v:
 have unsolved obligations.


�[93mIntermediate code not saved.�[0m
Failed to do everything at once; trying one at a time.
Admitting lemmas unsuccessful.
No successful changes.

I will now attempt to admit definitions with admit. Defined with Proof using

Non-fatal error: Failed to admit definitions and preserve the error.  
The new error was:
Deprecated environment variable COQCORELIB, use ROCQRUNTIMELIB instead.
Warning: Deprecated environment variable COQCORELIB,
use ROCQRUNTIMELIB instead.
[deprecated-coq-env-var,deprecated-since-9.0,deprecated,default]
File "/tmp/tmpbcmryn0m/Top/bug_01.v", line 204, characters 7-20:
Warning: Coq.Init.Ltac has been replaced by Corelib.Init.Ltac.
[deprecated-dirpath-Coq,deprecated-since-9.0,deprecated,default]
File "/tmp/tmpbcmryn0m/Top/bug_01.v", line 1036, characters 0-11:
Error: Signature components for field eq do not match:
the body of definitions differs.


�[93mIntermediate code not saved.�[0m
Failed to do everything at once; trying one at a time.
Admitting definitions unsuccessful.
No successful changes.

I will now attempt to add Proof using lines
�[92m
Adding Proof using lines successful.�[0m
Failed to do everything at once; trying one at a time.
Adding Proof using lines unsuccessful.
No successful changes.

I will now attempt to export modules
Module exportation successful

I will now attempt to split imports and exports
Import/Export splitting successful

I will now attempt to split := definitions
One-line definition splitting successful

I will now attempt to remove all lines, one at a time

If you have any comments on your experience of the minimizer, please share them in a reply (possibly tagging @JasonGross).
If you believe there's a bug in the bug minimizer, please report it on the bug minimizer issue tracker.

cc @JasonGross

@SkySkimmer
Copy link
Contributor Author

interrupted manually

@SkySkimmer
Copy link
Contributor Author

Reduced compcert example:

Module M.
  Axiom foo : bool.
End M.
Import M.

Ltac bli H := inversion H.

Goal forall n m:nat, Some n = Some m -> True /\ True.
  intros n m.
  intro foo; split; bli foo.

(very important to get the bug: use intro foo not intros foo)

thanks ltac

let intern_constr_reference strict ist qid =
let id = qualid_basename qid in
if qualid_is_ident qid && not strict && find_hyp (qualid_basename qid) ist then
(DAst.make @@ GVar id), Some (make @@ CRef (qid,None))
else if qualid_is_ident qid && find_var (qualid_basename qid) ist then
(DAst.make @@ GVar id), if strict then None else Some (make @@ CRef (qid,None))
else
DAst.make @@ GRef (locate_global_with_alias qid,None),
if strict then None else Some (make @@ CRef (qid,None))
match intern_constr {ist with strict_check=true} (CAst.make (CRef (qid,None))) with
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

the problem is strict_check=true here when strict=false
#17084 had strict_check=true but then did some adhoc stuff with the returned value:

      let c,_ = intern_constr {ist with strict_check=true} (CAst.make (CRef (qid,None))) in
      c, if strict then None else Some (make @@ CRef (qid,None))

unless someone (@herbelin?) knows a reason to keep strict_check constant true I'll do strict_check=strict

@SkySkimmer SkySkimmer added the request: full CI Use this label when you want your next push to trigger a full CI. label May 28, 2025
@SkySkimmer SkySkimmer force-pushed the ltac1-depr-noninserted-implicits branch from 7031535 to d999a8c Compare May 28, 2025 13:54
@coqbot-app coqbot-app bot removed the request: full CI Use this label when you want your next push to trigger a full CI. label May 28, 2025
@github-actions github-actions bot added the needs: rebase Should be rebased on the latest master to solve conflicts or have a newer CI run. label Jun 3, 2025
… impargs.

This was the case in non-strict mode (via interpretation at runtime),
but, in strict mode, it was instead the reference without its maximal
implicit arguments.

Also deprecate the old strict mode internalization.

For compat with enabling the option, the main impact is on
"class_apply" which we reformulate as a tactic notation to ensure that
its argument is always interpreted as a term.

Replaces rocq-prover#17084 in a more
backward compatible way.

Co-authored-by: Hugo Herbelin <herbelin@users.noreply.github.com>
@SkySkimmer SkySkimmer force-pushed the ltac1-depr-noninserted-implicits branch from d999a8c to 20a6687 Compare June 3, 2025 13:19
@SkySkimmer SkySkimmer requested a review from a team as a code owner June 3, 2025 13:19
@coqbot-app coqbot-app bot added needs: full CI The latest GitLab pipeline that ran was a light CI. Say "@coqbot run full ci" to get a full CI. and removed needs: rebase Should be rebased on the latest master to solve conflicts or have a newer CI run. labels Jun 3, 2025
@SkySkimmer SkySkimmer added the needs: fixing The proposed code change is broken. label Jun 3, 2025
Copy link
Contributor 10000
@Villetaneuse Villetaneuse left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Some suggestions for doc.
The change seems reasonable (more consistency), but I leave the review of the OCaml code to more expert reviewers.

Comment on lines +2 to +3
flag :flag:`Ltac Always Insert Implicits` to interprete a :n:`@qualid` argument to a ltac as a term (with insertion of any implicit arguments, unfolding notations, etc)
in a toplevel :cmd:`Ltac` definition instead of interpreting it as the reference without implicit arguments.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
flag :flag:`Ltac Always Insert Implicits` to interprete a :n:`@qualid` argument to a ltac as a term (with insertion of any implicit arguments, unfolding notations, etc)
in a toplevel :cmd:`Ltac` definition instead of interpreting it as the reference without implicit arguments.
flag :flag:`Ltac Always Insert Implicits` to interpret :n:`@qualid` arguments as terms (with insertion of any implicit arguments, unfolding notations, etc)
in further toplevel :cmd:`Ltac` definitions instead of interpreting them as references without implicit arguments.

Comment on lines +2 to +3
interpreting a :n:`@qualid` argument to a ltac as a term (with insertion of any implicit arguments, unfolding notations, etc)
in a toplevel :cmd:`Ltac` definition instead of interpreting it as the reference without implicit arguments.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
interpreting a :n:`@qualid` argument to a ltac as a term (with insertion of any implicit arguments, unfolding notations, etc)
in a toplevel :cmd:`Ltac` definition instead of interpreting it as the reference without implicit arguments.
Interpreting :n:`@qualid` arguments as terms (with insertion of any implicit arguments, unfolding notations, etc)
in toplevel :cmd:`Ltac` definitions instead of interpreting them as references without implicit arguments.

By default, ltac applications to a :n:`@qualid` inside a toplevel
:cmd:`Ltac`'s body can behave differently from the same application in
proof scripts: in proof scripts the :n:`@qualid` is interpreted as
a term, but in toplevel :cmd:`Ltac` it is interpreted as a
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
a term, but in toplevel :cmd:`Ltac` it is interpreted as a
a term, but in a toplevel :cmd:`Ltac` definition, it is interpreted as a

@SkySkimmer
Copy link
Contributor Author

Doesn't seem like it will be ready for 9.1.

@SkySkimmer SkySkimmer removed this from the 9.1+rc1 milestone Jun 6, 2025
(* XXX enable printing implicits while printing?
currently we get "got @foo but in proof scripts foo would be produced" *)
let warn_noninserted_impls =
CWarnings.create ~name:"ltac-non-inserted-implicits" ~category:Deprecation.Version.v9_1
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

TODO change the version since this won't be 9.1

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
kind: enhancement Enhancement to an existing user-facing feature, tactic, etc. needs: fixing The proposed code change is broken. needs: full CI The latest GitLab pipeline that ran was a light CI. Say "@coqbot run full ci" to get a full CI. part: ltac Issues and PRs related to the Ltac tactic language.
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants
0