Debian Codegraph @

vernac/auto_ind_decl.ml

raw symbols SCIP
1 (************************************************************************)
2 (* * The Rocq Prover / The Rocq Development Team *)
3 (* v * Copyright INRIA, CNRS and contributors *)
4 (* <O___,, * (see version control and CREDITS file for authors & dates) *)
5 (* \VV/ **************************************************************)
6 (* // * This file is distributed under the terms of the *)
7 (* * GNU Lesser General Public License Version 2.1 *)
8 (* * (see LICENSE file for the text of the license) *)
9 (************************************************************************)
10
11 (* This file is about the automatic generation of schemes about
12 decidable equality, created by Vincent Siles, Oct 2007 *)
13
14 open Util
15 open Constr
16 open Vars
17 open Declarations
18 open Names
19
20 module RelDecl = Context.Rel.Declaration
21
22 (**********************************************************************)
23 (* Generic synthesis of boolean equality *)
24
25 exception EqNotFound of inductive
26 exception EqUnknown of string
27 exception UndefinedCst of string
28 exception InductiveWithProduct
29 exception InductiveWithSort
30 exception ParameterWithoutEquality of GlobRef.t
31 exception NonSingletonProp of inductive
32 exception DecidabilityMutualNotSupported
33 exception NoDecidabilityCoInductive
34 exception ConstructorWithNonParametricInductiveType of inductive
35 exception DecidabilityIndicesNotSupported
36 exception InternalDependencies
37
38 let named_hd env t na = Namegen.named_hd env (Evd.from_env env) (EConstr.of_constr t) na
39 let name_assumption env = function
40 | RelDecl.LocalAssum (na,t) -> RelDecl.LocalAssum (Context.map_annot (named_hd env t) na, t)
41 | RelDecl.LocalDef (na,c,t) -> RelDecl.LocalDef (Context.map_annot (named_hd env c) na, c, t)
42 let name_context env ctxt =
43 snd
44 (List.fold_left
45 (fun (env,hyps) d ->
46 let d' = name_assumption env d in (Environ.push_rel d' env, d' :: hyps))
47 (env,[]) (List.rev ctxt))
48
49 (* Some pre declaration of constant we are going to use *)
50 let andb_prop = fun _ -> UnivGen.constr_of_monomorphic_global (Global.env ()) (Rocqlib.lib_ref "core.bool.andb_prop")
51
52 let andb_true_intro = fun _ ->
53 UnivGen.constr_of_monomorphic_global (Global.env ())
54 (Rocqlib.lib_ref "core.bool.andb_true_intro")
55
56 (* We avoid to use lazy as the binding of constants can change *)
57 let bb () = UnivGen.constr_of_monomorphic_global (Global.env ()) (Rocqlib.lib_ref "core.bool.type")
58 let tt () = UnivGen.constr_of_monomorphic_global (Global.env ()) (Rocqlib.lib_ref "core.bool.true")
59 let ff () = UnivGen.constr_of_monomorphic_global (Global.env ()) (Rocqlib.lib_ref "core.bool.false")
60 let eq () = UnivGen.constr_of_monomorphic_global (Global.env ()) (Rocqlib.lib_ref "core.eq.type")
61 let int63_eqb () = UnivGen.constr_of_monomorphic_global (Global.env ()) (Rocqlib.lib_ref "num.int63.eqb")
62 let float64_eqb () = UnivGen.constr_of_monomorphic_global (Global.env ()) (Rocqlib.lib_ref "num.float.leibniz.eqb")
63
64 let sumbool () = UnivGen.constr_of_monomorphic_global (Global.env ()) (Rocqlib.lib_ref "core.sumbool.type")
65 let andb = fun _ -> UnivGen.constr_of_monomorphic_global (Global.env ()) (Rocqlib.lib_ref "core.bool.andb")
66
67 let induct_on c = Induction.induction false None c None None
68 let destruct_on c = Induction.destruct false None c None None
69
70 let destruct_on_using c id =
71 let open Tactypes in
72 Induction.destruct false None c
73 (Some (CAst.make @@ IntroOrPattern [[CAst.make @@ IntroNaming IntroAnonymous];
74 [CAst.make @@ IntroNaming (IntroIdentifier id)]]))
75 None
76
77 let destruct_on_as c l =
78 Induction.destruct false None c (Some (CAst.make l)) None
79
80 let inj_flags = Some {
81 Equality.keep_proof_equalities = true; (* necessary *)
82 Equality.injection_pattern_l2r_order = true; (* does not matter here *)
83 }
84
85 let my_discr_tac = Equality.discr_tac false None
86 let my_inj_tac x = Equality.inj inj_flags None false None (EConstr.mkVar x,NoBindings)
87
88 (* reconstruct the inductive with the correct de Bruijn indexes *)
89 let mkFullInd env (ind,u) n =
90 let mib = Environ.lookup_mind (fst ind) env in
91 mkApp (mkIndU (ind,u), Context.Rel.instance mkRel n mib.mind_params_ctxt)
92
93 let mkPartialInd env (ind,u) n =
94 let mib = Environ.lookup_mind (fst ind) env in
95 let _, recparams_ctx = Inductive.inductive_nonrec_rec_paramdecls (mib,u) in
96 mkApp (mkIndU (ind,u), Context.Rel.instance mkRel n recparams_ctx)
97
98 let name_X = Context.make_annot (Name (Id.of_string "X")) Sorts.Relevant
99 let name_Y = Context.make_annot (Name (Id.of_string "Y")) Sorts.Relevant
100 let mk_eqb_over u = mkProd (name_X, u, (mkProd (name_Y, lift 1 u, bb ())))
101
102 let check_bool_is_defined () =
103 if not (Rocqlib.has_ref "core.bool.type")
104 then raise (UndefinedCst "bool")
105
106 let check_no_indices mib =
107 if Array.exists (fun mip -> mip.mind_nrealargs <> 0) mib.mind_packets then
108 raise DecidabilityIndicesNotSupported
109
110 let is_irrelevant env c =
111 match kind (EConstr.Unsafe.to_constr (Retyping.get_type_of env (Evd.from_env env) (EConstr.of_constr c))) with
112 | Sort SProp -> true
113 | _ -> false
114
115 let get_scheme handle k ind = match Ind_tables.local_lookup_scheme handle k ind with
116 | None -> assert false
117 | Some c -> c
118
119 let beq_scheme_kind_aux = ref (fun _ -> failwith "Undefined")
120
121 let get_inductive_deps ~noprop env kn =
122 (* fetching the mutual inductive body *)
123 let mib = Environ.lookup_mind kn env in
124 (* number of params in the type *)
125 check_no_indices mib;
126 let env = Environ.push_rel_context mib.mind_params_ctxt env in
127 let sigma = Evd.from_env env in
128 let get_deps_one accu i mip =
129 (* This function is only trying to recursively compute the inductive types
130 appearing as arguments of the constructors. This is done to support
131 equality decision over hereditarily first-order types. It could be
132 performed in a much cleaner way, e.g. using the kernel normal form of
133 constructor types and kernel whd_all for the argument types. *)
134 let rec aux env accu c =
135 let (c,a) = Reductionops.whd_all_stack env sigma c in
136 match EConstr.kind sigma c with
137 | Cast (x,_,_) -> aux env accu (EConstr.applist (x,a))
138 | App _ -> assert false
139 | Ind ((kn', _ as ind), _) ->
140 if Environ.QMutInd.equal env kn kn' then
141 (* Example: Inductive T A := C : T (option A) -> T A. *)
142 List.fold_left (aux env) accu a
143 else
144 let _,mip = Inductive.lookup_mind_specif env ind in
145 (* Types in SProp have trivial equality and are skipped
146 XXX should be substituting polymorphic universes *)
147 if Sorts.is_sprop mip.mind_sort then
148 List.fold_left (aux env) accu a
149 else
150 List.fold_left (aux env) (kn' :: accu) a
151 | Const (kn, u) ->
152 (match Environ.constant_opt_value_in env (kn, EConstr.EInstance.kind sigma u) with
153 | Some c -> aux env accu (EConstr.applist (EConstr.of_constr c,a))
154 | None -> accu)
155 | Rel _ | Var _ | Sort _ | Prod _ | Lambda _ | LetIn _ | Proj _
156 | Construct _ | Case _ | CoFix _ | Fix _ | Meta _ | Evar _ | Int _
157 | Float _ | String _ | Array _ -> Termops.fold_constr_with_full_binders env sigma EConstr.push_rel aux env (List.fold_left (aux env) accu a) c
158 in
159 let fold i accu (constr_ctx,_) =
160 let constr_ctx, _ = List.chop mip.mind_consnrealdecls.(i) constr_ctx in
161 let rec fold env accu = function
162 | [] -> env, accu
163 | decl::ctx ->
164 let env, accu = fold env accu ctx in
165 let t = Context.Rel.Declaration.get_type decl in
166 Environ.push_rel decl env,
167 (if noprop && is_irrelevant env t then accu else aux env accu (EConstr.of_constr t))
168 in
169 snd (fold env accu constr_ctx)
170 in
171 Array.fold_left_i fold accu mip.mind_nf_lc
172 in
173 Array.fold_left_i (fun i accu mip -> get_deps_one accu i mip) [] mib.mind_packets
174
175 (** A compact data structure to remember for each declaration of the
176 context if it is a type and comes with a Boolean equality; if it
177 comes with an equality we remember the integer to subtract to the
178 de Bruijn indices of the binder to get the equality *)
179
180 type eq_status =
181 | End
182 (* int is the number of consecutive declarations without an equality *)
183 | WithoutEq of int * eq_status
184 (* list is the list of shifts for consecutive declarations with an equality *)
185 | WithEq of int list * eq_status
186
187 let add_eq_status_no = function
188 | WithEq _ | End as s -> WithoutEq (1, s)
189 | WithoutEq (n, s) -> WithoutEq (n+1, s)
190
191 let set_eq_status_yes n q s =
192 let rec aux n = function
193 | WithoutEq (p,End) when Int.equal n p -> WithoutEq (p-1, WithEq ([q],End))
194 | WithoutEq (p,WithEq (l,s)) when Int.equal n p -> WithoutEq (p-1, WithEq (q::l,s))
195 | WithoutEq (p,s) when n < p -> WithoutEq (n-1, WithEq ([q], WithoutEq (p-n, s)))
196 | WithoutEq (p,s) when Int.equal n 1 -> WithEq ([q], WithoutEq (p-1, s))
197 | WithoutEq (p,s) -> WithoutEq (p, aux (n-p) s)
198 | WithEq (l,s) -> WithEq (l,aux (n-List.length l) s)
199 | End -> assert false in
200 aux n s
201
202 let rec has_decl_equality n status =
203 match n, status with
204 | p, WithEq (l,s) when p <= List.length l -> Some (List.nth l (p-1))
205 | p, WithEq (l,s) -> has_decl_equality (p-List.length l) s
206 | p, WithoutEq (n,s) when p <= n -> None
207 | p, WithoutEq (n,s) -> has_decl_equality (p-n) s
208 | _, End -> assert false
209
210 (** The reallocation of variables to be done during the translation:
211 [env] is the current env at the corresponding step of the translation
212 [lift] is the lift for the original variables
213 [eq_status] tells how to get the equality associated with a variable if any
214 [ind_pos] tells the position of recursive calls (it could have
215 been avoided by replacing the recursive occurrences of ind in an
216 inductive definition by variables *)
217
218 type env_lift = {
219 env : Environ.env; (* Gamma *)
220 lift : Esubst.lift; (* lift : Gamma + Gamma_eq |- Gamma *)
221 eq_status : eq_status;
222 ind_pos : ((MutInd.t * int * rel_context * int) * int) option;
223 }
224
225 let lift_ind_pos n =
226 Option.map (fun (ind,k) -> (ind,k+n))
227
228 let empty_env_lift env = {
229 env = env;
230 lift = Esubst.el_id;
231 eq_status = End;
232 ind_pos = None;
233 }
234
235 let push_env_lift decl env_lift = {
236 env = Environ.push_rel decl env_lift.env;
237 lift = Esubst.el_lift env_lift.lift;
238 eq_status = add_eq_status_no env_lift.eq_status;
239 ind_pos = lift_ind_pos 1 env_lift.ind_pos;
240 }
241
242 let set_replicate n q env_lift = {
243 env = env_lift.env;
244 lift = env_lift.lift;
245 eq_status = set_eq_status_yes n q env_lift.eq_status;
246 ind_pos = env_lift.ind_pos;
247 }
248
249 let shiftn_env_lift n env_lift =
250 { env_lift with lift = Esubst.el_shft n (Esubst.el_liftn n env_lift.lift);
251 ind_pos = lift_ind_pos n env_lift.ind_pos; }
252
253 let find_ind_env_lift env_lift (mind,i) =
254 match env_lift.ind_pos with
255 | Some ((mind',nrecparams,recparamsctx,nb_ind),n) when Environ.QMutInd.equal env_lift.env mind mind' ->
256 Some (nrecparams,recparamsctx,n+nb_ind-i)
257 | _ -> None
258
259 let shift_fix_env_lift ind nrecparams recparamsctx nb_ind env_lift = {
260 env = env_lift.env;
261 lift = Esubst.el_shft nb_ind env_lift.lift;
262 eq_status = env_lift.eq_status;
263 ind_pos = Some ((ind,nrecparams,recparamsctx,nb_ind),0)
264 }
265
266 let push_rec_env_lift recdef env_lift =
267 let n = Array.length (pi1 recdef) in {
268 env = Environ.push_rec_types recdef env_lift.env;
269 lift = Esubst.el_liftn n env_lift.lift;
270 eq_status = add_eq_status_no env_lift.eq_status;
271 ind_pos = lift_ind_pos n env_lift.ind_pos;
272 }
273
274 let dest_lam_assum_expand env c =
275 let ctx, c = Reduction.whd_decompose_lambda_decls env c in
276 if List.is_empty ctx then ctx, c
277 else
278 let t = EConstr.Unsafe.to_constr (Retyping.get_type_of (Environ.push_rel_context ctx env) (Evd.from_env env) (EConstr.of_constr c)) in
279 let ctx', _ = Reduction.whd_decompose_prod_decls env t in
280 ctx'@ctx, mkApp (lift (Context.Rel.length ctx') c, Context.Rel.instance mkRel 0 ctx')
281
282 let pred_context env ci params u nas =
283 let mib, mip = Inductive.lookup_mind_specif env ci.ci_ind in
284 let paramdecl = Vars.subst_instance_context u mib.mind_params_ctxt in
285 let paramsubst = Vars.subst_of_rel_context_instance paramdecl params in
286 let realdecls, _ = List.chop mip.mind_nrealdecls mip.mind_arity_ctxt in
287 let self =
288 let args = Context.Rel.instance mkRel 0 mip.mind_arity_ctxt in
289 let inst = UVars.Instance.(abstract_instance (length u)) in
290 mkApp (mkIndU (ci.ci_ind, inst), args)
291 in
292 let na = Context.make_annot Anonymous mip.mind_relevance in
293 let realdecls = RelDecl.LocalAssum (na, self) :: realdecls in
294 Inductive.instantiate_context u paramsubst nas realdecls
295
296 let branch_context env ci params u nas i =
297 let mib, mip = Inductive.lookup_mind_specif env ci.ci_ind in
298 let paramdecl = Vars.subst_instance_context u mib.mind_params_ctxt in
299 let paramsubst = Vars.subst_of_rel_context_instance paramdecl params in
300 let ctx, _ = List.chop mip.mind_consnrealdecls.(i) (fst mip.mind_nf_lc.(i)) in
301 Inductive.instantiate_context u paramsubst nas ctx
302
303 let build_beq_scheme_deps env kn =
304 let inds = get_inductive_deps ~noprop:true env kn in
305 List.map (fun ind -> Ind_tables.SchemeMutualDep (ind, !beq_scheme_kind_aux ())) inds
306
307 let build_beq_scheme env handle kn =
308 check_bool_is_defined ();
309 (* predef coq's boolean type *)
310 (* here I leave the Naming thingy so that the type of
311 the function is more readable for the user *)
312 let eqName = Context.map_annot (function
313 | Name s -> Name (Id.of_string ("eq_"^(Id.to_string s)))
314 | Anonymous -> Name (Id.of_string "eq_A"))
315 in
316
317 (* The Boolean equality translation is a parametricity translation
318 where each type T is interpreted as the pair of:
319 - a (possibly degenerate) predicate T_R in Type over T (i.e. T_R : T->Type)
320 - when T is decidable, a Boolean equality T_E over (i.e. T_E :
321 option (T->T->bool) where None means not decidable, that is, at
322 worst, unknown to be decidable)
323
324 This generalizes into an interpretation of each term M:T as:
325 - an inhabitant [|M|] of T_R M
326 by setting for sort s:
327 - s_R := \T:s.{R:T->s ; E:option (T->T->bool)} and
328 - s_E := None
329 so that types T:s are indeed interpreted as a pair, namely by:
330 - [|T|] := {R:=T_R; E:=T_E} : s_R T
331 and, in particular:
332 - [|Type(n)|] := {R:=Type(n)_R; E:=Type(n)_E) : Type(n+1)_R Type(n)
333
334 In practice, to have simpler schemes, we won't support here the
335 full hierarchy of sorts. That is, we assume that type parameters
336 of a type will be instantiated only by small types (i.e. not
337 containing sorts). This makes sense since equality on large types
338 is anyway not decidable in the general case [*].
339
340 Now, it happens that several parts of the translation are
341 degenerate. For instance, if T is a small type (not containing
342 sorts), then T_R M, which expresses that M realizes T, is a
343 singleton for all M (we assume functional extensionality to treat
344 the case of dependent product types). Therefore, M_T does not
345 need to be defined in this case. Conversely, if T is not small,
346 it is not decidable and T_E will be None.
347
348 This means that at least T_R is degenerate or T_E is None and
349 this also means that for M:T with degenerate T_R, we don't need
350 to compute [|M|].R
351
352 This further means that when translating a variable x:T with T
353 small, it can just be translated to x:T without requiring the
354 trivial information that T_R x is inhabited.
355
356 Similarly for types T of the form [forall X, (forall Y ...) ... Y args]
357 based on the assumption [*] that Y is instantiated only by small
358 functorial types for which (Y args)_R would be degenerate.
359
360 Similarly, based on the restriction above [*] that parameters are
361 instantiated by small types, when translating a variable x:T with
362 T an arity, i.e. of the form [... -> Type] (or at worst
363 [... -> Type*Type] etc.), we can assume x to be instantiated by a
364 small functorial type whose R translation is degenerate.
365
366 It remains the declarations of the form X:T for T of the form
367 [forall X, ... X args] where X is in negative position of a
368 dependent product. If such X is instantiated by a large type in
369 the definition, as in
370 [Inductive I (F:forall X:Type, X->X) (B:F Type nat) := C : B -> I F B],
371 we give up. Otherwise said, we support only the case when `X`is
372 instantiated by a small type.
373
374 Eventually, we thus need two translations:
375 - T_R when T is large and it does not need to go under
376 applicative subterms since subterms [X args] are considered
377 small by assumption [*]
378 - T_E when T is small which needs to go under subterms and which
379 thus needs to be generalized into a translation M_E : T_R.E
380 whenever T is detected as decidable (in which case, T_R.E is
381 typically of the form T->T->bool or of the form
382 (T.1->T.1->bool)*(T.2->T.2->bool), etc.)
383
384 Below, the first translation is called [translate_type_eq] and
385 the second [translate_term_eq]. Additionally, there is a copy-cat
386 translation called "translate_term" that lifts M in the typing context
387 of M_R.
388
389 The function [translate_type_eq] takes as input a type T and a
390 term M of type T and it returns T_R M.
391
392 For M of type T, the function [translate_term_eq M] returns an
393 object of type term T_R M, that is, when M is itself some type U,
394 an object of type U->U->bool.
395
396 Note that we don't use an option type for non-decidable types but
397 instead raises an exception whenever a type is not detected as
398 decidable.
399
400 Future work might support:
401 - exotic types such as
402 [Inductive I (F:forall X:Type, X->X) (B:F Type nat) := C : B -> I F B]
403 - types with invertible indices like listn
404 - dependent products over finite types (e.g. over bool->bool), and
405 more generally compact types whose equality is decidable (see Escardo-Oliva)
406 *)
407
408 let rec translate_type_eq env_lift na c t =
409 let ctx, t = Reduction.whd_decompose_prod_decls env t in
410 let env_lift', ctx_eq = translate_context_eq env_lift ctx in
411 let inst = Array.map (translate_term env_lift') (Context.Rel.instance mkRel 0 ctx) in
412 let env_lift'' = shiftn_env_lift (Context.Rel.length ctx_eq) env_lift in
413 let c = mkApp (translate_term env_lift'' c, inst) in
414 let c = match kind t with
415 | Sort _ -> Some (mk_eqb_over c)
416
417 | Prod _ | LetIn _ -> assert false
418
419 (* [s] is necessaritly a sort *)
420 | Cast (t,k,s) ->
421 begin
422 match translate_type_eq env_lift' na c t with
423 | None -> None
424 | Some t -> Some (mkCast (t, k, mkProd (na, t, c)))
425 end
426
427 (* TODO: take into account situations like (P:Type * Type) which
428 could be translated into (fst P->fst P>bool)*(snd P->snd
429 P->bool); to be done in parallel with preserving the types in
430 Proj/Construct/CoFix *)
431 | Ind _ -> None
432 | Array _ -> None
433
434 (* We assume references to be references to small types and thus
435 to types with singleton realizability predicate; to support
436 references to large types, see comments above for the full
437 translation *)
438 | App _ | Rel _ | Var _ | Const _ -> None
439
440 (* The restricted translation translates only types *)
441 | Lambda _ | Construct _ -> assert false
442
443 | Case (ci, u, pms, ((pnames,p),r), iv, tm, lbr) ->
444 let env_lift_pred = shiftn_env_lift (Array.length pnames) env_lift in
445 let t =
446 mkCase (ci, u,
447 Array.map (translate_term env_lift_pred) pms,
448 (translate_term_with_binders env_lift_pred (pnames,p), r),
449 Constr.map_invert (translate_term env_lift_pred) iv,
450 mkRel 1,
451 Array.map (translate_term_with_binders env_lift_pred) lbr) in
452 (* in the restricted translation, only types are translated and
453 the return predicate is necessarily a type *)
454 let p = mkProd (Context.anonR, t, p) in
455 let lbr = Array.mapi (fun i (names, t) ->
456 let ctx = branch_context env ci pms u names i in
457 let env_lift' = List.fold_right push_env_lift ctx env_lift in
458 match translate_type_eq env_lift' na (mkRel 1) t with
459 | None -> None
460 | Some t_eq -> Some (names, mkLambda (na, t, t_eq))) lbr in
461 if Array.for_all Option.has_some lbr then
462 let lbr = Array.map Option.get lbr in
463 let case = mkCase (ci, u, pms, ((pnames, p), r), iv, translate_term env_lift tm, lbr) in
464 Some (mkApp (case, [|c|]))
465 else
466 None
467
468 (* TODO: in parallel with traversing Fix in translate_term_eq to
469 look for types, traverse Fix to look for Type here *)
470 | Fix _ -> None
471
472 (* Not building a type *)
473 | Proj _ | CoFix _ | Int _ | Float _ | String _ -> None
474
475 | Meta _ | Evar _ -> assert false (* kernel terms *)
476 in
477 Option.map (fun c -> Term.it_mkProd_or_LetIn c ctx_eq) c
478
479 and translate_term_eq env_lift c =
480 let ctx, c = dest_lam_assum_expand env_lift.env c in
481 let env_lift, ctx = translate_context_eq env_lift ctx in
482 let c = match Constr.kind c with
483 | Rel x ->
484 (match has_decl_equality x env_lift.eq_status with
485 | Some n -> Some (mkRel (Esubst.reloc_rel x env_lift.lift - n))
486 | None -> None)
487 | Var x ->
488 if Reduction.is_arity env (Typeops.type_of_variable env x) then
489 (* Support for working in a context with "eq_x : x -> x -> bool" *)
490 let eid = Id.of_string ("eq_"^(Id.to_string x)) in
491 let () =
492 try ignore (Environ.lookup_named eid env)
493 with Not_found -> raise (ParameterWithoutEquality (GlobRef.VarRef x))
494 in
495 Some (mkVar eid)
496 else
497 None
498 | Cast (c,k,t) ->
499 begin
500 match translate_term_eq env_lift c, translate_type_eq env_lift Context.anonR c t with
501 | Some c, Some t -> Some (mkCast (c,k,t))
502 | None, None -> None
503 | (None | Some _), _ -> assert false
504 end
505 | Lambda _ | LetIn _ -> assert false
506 | App (f,args) ->
507 begin
508 let f, args =
509 match kind f with
510 | Ind (ind',_) ->
511 (match find_ind_env_lift env_lift ind' with
512 | Some (nrecparams,_,n) when Array.length args >= nrecparams ->
513 Some (mkRel n), Array.sub args nrecparams (Array.length args - nrecparams)
514 | _ -> translate_term_eq env_lift f, args)
515 | Const (kn,u) ->
516 (match Environ.constant_opt_value_in env (kn, u) with
517 | Some c -> translate_term_eq env_lift (mkApp (c,args)), [||]
518 | None -> translate_term_eq env_lift f, args)
519 | _ -> translate_term_eq env_lift f, args
520 in
521 match f with
522 | Some f -> Some (mkApp (f, translate_arguments_eq env_lift args))
523 | None -> None
524 end
525 | Ind (ind',u) ->
526 begin
527 match find_ind_env_lift env_lift ind' with
528 | Some (_,recparamsctx,n) -> Some (Term.it_mkLambda_or_LetIn (mkRel n) (translate_context env_lift recparamsctx))
529 | None ->
530 try Some (Constr.mkRef (get_scheme handle (!beq_scheme_kind_aux()) ind',u))
531 with Not_found -> raise(EqNotFound ind')
532 end
533 | Const (kn,u as cst) ->
534 if Environ.is_int63_type env kn then Some (int63_eqb ()) else
535 if Environ.is_float64_type env kn then Some (float64_eqb ()) else
536 if Environ.is_array_type env kn then (* TODO *) raise (ParameterWithoutEquality (GlobRef.ConstRef kn)) else
537 (match Environ.constant_opt_value_in env (kn, u) with
538 | Some c -> translate_term_eq env_lift c
539 | None ->
540 if Reduction.is_arity env (Typeops.type_of_constant_in env cst) then
541 (* Support for working in a context with "eq_x : x -> x -> bool" *)
542 (* Needs Hints, see test suite *)
543 let eq_lbl = Id.of_string ("eq_" ^ Id.to_string (Constant.label kn)) in
544 let kneq = Constant.change_label kn eq_lbl in
545 if Environ.mem_constant kneq env then
546 let _ = Environ.constant_opt_value_in env (kneq, u) in
547 Some (mkConstU (kneq,u))
548 else raise (ParameterWithoutEquality (GlobRef.ConstRef kn))
549 else None)
550
551 (* TODO: in parallel with preserving Type for Ind in
552 translate_type_eq, preserve the types in Construct/CoFix *)
553 | Proj _ | Construct _ | CoFix _ -> None
554
555 | Case (ci, u, pms, ((pnames,p), r), iv, tm, lbr) ->
556 let pctx = pred_context env ci pms u pnames in
557 let env_lift_pred = List.fold_right push_env_lift pctx env_lift in
558 let n = Array.length pnames in
559 let c =
560 mkCase (ci, u,
561 Array.map (lift n) pms,
562 ((pnames, liftn n (n+1) p), r),
563 Constr.map_invert (lift n) iv,
564 mkRel 1,
565 Array.map (fun (names, br) -> (names, let q = Array.length names in liftn n (n+q+1) br)) lbr) in
566 let p = translate_type_eq env_lift_pred Context.anonR c p in
567 let lbr = Array.mapi (fun i (names, t) ->
568 let ctx = branch_context env ci pms u names i in
569 let env_lift' = List.fold_right push_env_lift ctx env_lift in
570 match translate_term_eq env_lift' t with
571 | None -> None
572 | Some t_eq -> Some (names, t_eq)) lbr in
573 if Array.for_all Option.has_some lbr && Option.has_some p then
574 let lbr = Array.map Option.get lbr in
575 Some (mkCase (ci, u, pms, ((pnames, Option.get p), r), iv, translate_term env_lift tm, lbr))
576 else
577 None
578
579 | Fix ((recindxs,i),(names,typarray,bodies as recdef)) ->
580 let _ =
581 (* Almost work: would need:
582 1. that the generated fix has an eq_status registration
583 telling that an original recursive call should be
584 interpreted as the pair of the whole fix and of the
585 translated recursive call building the equality
586 2. something to do around either packaging the type with
587 its equality, or begin able for a match to have a return
588 predicate different though convertible to itself, namely
589 here a fix of match (see test-suite) *)
590 let mkfix j = mkFix ((recindxs,j),recdef) in
591 let typarray = Array.mapi (fun i -> translate_type_eq env_lift Context.anonR (mkfix i)) typarray in
592 let env_lift_types = push_rec_env_lift recdef env_lift in
593 let bodies = Array.map (translate_term_eq env_lift_types) bodies in
594 if Array.for_all Option.has_some bodies && Array.for_all Option.has_some typarray then
595 let bodies = Array.map Option.get bodies in
596 let typarray = Array.map Option.get typarray in
597 Some (mkFix ((recindxs,i),(names,typarray,bodies)))
598 else
599 None
600 in None
601
602 | Sort _ -> raise InductiveWithSort (* would require a more sophisticated translation *)
603 | Prod _ -> raise InductiveWithProduct (* loss of decidable if uncountable domain *)
604
605 | Meta _ | Evar _ -> None (* assert false! *)
606 | Int _ | Float _ | String _ | Array _ -> None
607 in
608 Option.map (fun c -> Term.it_mkLambda_or_LetIn c ctx) c
609
610 (* Translate context by adding a context of Boolean equalities for each type argument
611
612 Example of translated context:
613 (F : (U -> U) -> nat -> U)
614 (eq_F : forall G, (forall A, eq A -> eq (G A)) -> nat -> eq (F G)) *)
615
616 and translate_context_eq env_lift ctx =
617 let ctx = name_context env_lift.env ctx in
618 let (env_lift_ctx,nctx_eq,ctx_with_eq) =
619 List.fold_right (fun decl (env_lift,n,ctx) ->
620 let env_lift = push_env_lift decl env_lift in
621 let env_lift' = shiftn_env_lift (n-1) env_lift in
622 match decl with
623 | RelDecl.LocalDef (na,c,t) ->
624 (match translate_term_eq env_lift' (lift 1 c), translate_type_eq env_lift' na (mkRel 1) (lift 1 t) with
625 | Some eq_c, Some eq_typ ->
626 (set_replicate 1 n env_lift, n, RelDecl.LocalDef (eqName na,eq_c,eq_typ) :: ctx)
627 | None, None -> (env_lift, n-1, ctx)
628 | (None | Some _), _ -> assert false)
629 | RelDecl.LocalAssum (na,t) ->
630 match translate_type_eq env_lift' na (mkRel 1) (lift 1 t) with
631 | Some eq_typ -> (set_replicate 1 n env_lift, n, RelDecl.LocalAssum (eqName na,eq_typ) :: ctx)
632 | None -> (env_lift, n-1, ctx)
633 ) ctx (env_lift, Context.Rel.length ctx, ctx)
634 in
635 shiftn_env_lift nctx_eq env_lift_ctx, ctx_with_eq
636
637 (* Translate arguments by adding Boolean equality when relevant
638
639 Examples of translated applications:
640 F (fun A => A) 0
641 eq_F (fun A => A) (fun A eq_A => eq_A) 0
642
643 F (fun A => list A) 0
644 eq_F (fun A => list A) (fun A eq_A => eq_list A eq_A) 0 *)
645
646 and translate_arguments_eq env_lift args =
647 let args' = Array.map (translate_term env_lift) args in
648 let eq_args = Array.of_list (List.map_filter (translate_term_eq env_lift) (Array.to_list args)) in
649 Array.append args' eq_args
650
651 (* Copy-cat translation with relocation *)
652
653 and translate_term env_lift c =
654 exliftn env_lift.lift c
655
656 and translate_context env_lift ctx =
657 Context.Rel.map_with_binders (fun i -> translate_term (shiftn_env_lift i env_lift)) ctx
658
659 and translate_term_with_binders env_lift (names,c) =
660 (names, translate_term (shiftn_env_lift (Array.length names) env_lift) c)
661
662 in
663 (* Starting translating the inductive block to Boolean equalities;
664 Morally corresponds to the Ind case of translate_term_eq *)
665
666 (* fetching the mutual inductive body *)
667 let mib = Environ.lookup_mind kn env in
668
669 (* Setting universes *)
670 let auctx = Declareops.universes_context mib.mind_universes in
671 let u, ctx = UnivGen.fresh_instance_from auctx None in
672 let uctx = UState.from_env env in
673 let uctx = UState.merge_sort_context ~sideff:false UState.univ_rigid ~src:UState.Internal uctx ctx in
674
675 (* number of inductives in the mutual *)
676 let nb_ind = Array.length mib.mind_packets in
677 let truly_recursive =
678 let open Declarations in
679 let is_rec ra = match Declareops.dest_recarg ra with Mrec _ -> true | Norec -> false in
680 Array.exists
681 (fun mip -> Array.exists (List.exists is_rec) (Declareops.dest_subterms mip.mind_recargs))
682 mib.mind_packets in
683 (* params context divided *)
684 let nonrecparams_ctx,recparams_ctx = Inductive.inductive_nonrec_rec_paramdecls (mib,u) in
685 let params_ctx = nonrecparams_ctx @ recparams_ctx in
686 let nparamsdecls = Context.Rel.length params_ctx in
687 check_no_indices mib;
688
689 let env_lift_recparams, recparams_ctx_with_eqs =
690 translate_context_eq (empty_env_lift env) recparams_ctx in
691 let env_lift_recparams_fix, fix_ctx, names, types =
692 match mib.mind_finite with
693 | CoFinite ->
694 raise NoDecidabilityCoInductive
695 | Finite when truly_recursive || nb_ind > 1 (* Hum, there exist non-recursive mutual types... *) ->
696 (* rec name *)
697 let rec_name i =
698 (Id.to_string (Array.get mib.mind_packets i).mind_typename)^"_eqrec"
699 in
700 let names = Array.init nb_ind (fun i -> Context.make_annot (Name (Id.of_string (rec_name i))) Sorts.Relevant) in
701 let types = Array.init nb_ind (fun i -> Option.get (translate_type_eq env_lift_recparams Context.anonR (mkPartialInd env ((kn,i),u) 0) (Term.it_mkProd_or_LetIn (*any sort:*) mkSet nonrecparams_ctx))) in
702 let fix_ctx = List.rev (Array.to_list (Array.map2 (fun na t -> RelDecl.LocalAssum (na,t)) names types)) in
703 shift_fix_env_lift kn mib.mind_nparams_rec recparams_ctx nb_ind env_lift_recparams, fix_ctx, names, types
704 | Finite | BiFinite ->
705 env_lift_recparams, [], [||], [||]
706 in
707 let env_lift_recparams_fix_nonrecparams, nonrecparams_ctx_with_eqs =
708 translate_context_eq env_lift_recparams_fix nonrecparams_ctx in
709 let make_one_eq cur =
710 (* construct the "fun A B ... N, eqA eqB eqC ... N => fixpoint" part *)
711 let ind = (kn,cur) in
712 let indu = (ind,u) in
713 let tomatch_ctx = RelDecl.[
714 LocalAssum (name_Y,
715 translate_term (shiftn_env_lift 1 env_lift_recparams_fix_nonrecparams) (mkFullInd env indu 0));
716 LocalAssum (name_X,
717 translate_term env_lift_recparams_fix_nonrecparams (mkFullInd env indu 0))
718 ] in
719 let env_lift_recparams_fix_nonrecparams_tomatch =
720 shiftn_env_lift 2 env_lift_recparams_fix_nonrecparams in
721 (* current inductive we are working on *)
722 let open Term in
723 let pred =
724 let cur_packet = mib.mind_packets.(cur) in
725 (* Inductive toto : [rettyp] := *)
726 let rettyp = Inductive.type_of_inductive ((mib,cur_packet),u) in
727 (* split rettyp in a list without the non rec params and the last ->
728 e.g. Inductive vec (A:Set) : nat -> Set := ... will do [nat] *)
729 let _, rettyp = decompose_prod_n_decls nparamsdecls rettyp in
730 let rettyp_l, _ = decompose_prod_decls rettyp in
731 (* construct the predicate for the Case part*)
732 Term.it_mkLambda_or_LetIn
733 (mkLambda (Context.make_annot Anonymous Sorts.Relevant,
734 mkFullInd env indu (List.length rettyp_l),
735 (bb ())))
736 rettyp_l in
737 (* make_one_eq *)
738 (* do the [| C1 ... => match Y with ... end
739 ...
740 Cn => match Y with ... end |] part *)
741 let rci = EConstr.ERelevance.relevant in (* returning a boolean, hence relevant *)
742 let open Inductiveops in
743 let constrs =
744 let params = Context.Rel.instance_list EConstr.mkRel 0 params_ctx in
745 get_constructors env (make_ind_family (on_snd EConstr.EInstance.make indu, params))
746 in
747 let make_andb_list = function
748 | [] -> tt ()
749 | eq :: eqs -> List.fold_left (fun eqs eq -> mkApp (andb(),[|eq;eqs|])) eq eqs
750 in
751 let body =
752 match Environ.get_projections env ind with
753 | Some projs ->
754 (* A primitive record *)
755 let nb_cstr_args = List.length constrs.(0).cs_args in
756 let _,_,eqs = List.fold_right (fun decl (ndx,env_lift,l) ->
757 let decl = EConstr.Unsafe.to_rel_decl decl in
758 let env_lift' = push_env_lift decl env_lift in
759 match decl with
760 | RelDecl.LocalDef (na,b,t) -> (ndx-1,env_lift',l)
761 | RelDecl.LocalAssum (na,cc) ->
762 if is_irrelevant env_lift.env cc then (ndx-1,env_lift',l)
763 else
764 if Vars.noccur_between 1 (nb_cstr_args-ndx) cc then
765 let cc = lift (ndx-nb_cstr_args) cc in
766 match translate_term_eq env_lift_recparams_fix_nonrecparams_tomatch cc with
767 | None -> raise (EqUnknown "type") (* A supported type should have an eq *)
768 | Some eqA ->
769 let proj, relevance = projs.(nb_cstr_args-ndx) in
770 let proj = Projection.make proj true in
771 (ndx-1,env_lift',mkApp (eqA, [|mkProj (proj, relevance, mkRel 2);
772 mkProj (proj, relevance, mkRel 1)|])::l)
773 else
774 raise InternalDependencies)
775 constrs.(0).cs_args (nb_cstr_args,env_lift_recparams_fix_nonrecparams_tomatch,[])
776 in
777 make_andb_list eqs
778 | None ->
779 (* An inductive type *)
780 let ci = make_case_info env ind MatchStyle in
781 let nconstr = Array.length constrs in
782 let ar =
783 Array.init nconstr (fun i ->
784 let nb_cstr_args = List.length constrs.(i).cs_args in
785 let env_lift_recparams_fix_nonrecparams_tomatch_csargsi = shiftn_env_lift nb_cstr_args env_lift_recparams_fix_nonrecparams_tomatch in
786 let ar2 = Array.init nconstr (fun j ->
787 let env_lift_recparams_fix_nonrecparams_tomatch_csargsij = shiftn_env_lift nb_cstr_args env_lift_recparams_fix_nonrecparams_tomatch_csargsi in
788 let cc =
789 if Int.equal i j then
790 let _,_,eqs = List.fold_right (fun decl (ndx,env_lift,l) ->
791 let decl = EConstr.Unsafe.to_rel_decl decl in
792 let env_lift' = push_env_lift decl env_lift in
793 match decl with
794 | RelDecl.LocalDef (na,b,t) -> (ndx-1,env_lift',l)
795 | RelDecl.LocalAssum (na,cc) ->
796 if is_irrelevant env_lift.env cc then (ndx-1,env_lift',l)
797 else
798 if Vars.noccur_between 1 (nb_cstr_args-ndx) cc then
799 let cc = lift (ndx-nb_cstr_args) cc in
800 match translate_term_eq env_lift_recparams_fix_nonrecparams_tomatch_csargsij cc with
801 | None -> raise (EqUnknown "type") (* A supported type should have an eq *)
802 | Some eqA ->
803 (ndx-1,env_lift',mkApp (eqA, [|mkRel (ndx+nb_cstr_args);mkRel ndx|])::l)
804 else
805 raise InternalDependencies)
806 constrs.(j).cs_args (nb_cstr_args,env_lift_recparams_fix_nonrecparams_tomatch_csargsij,[])
807 in
808 make_andb_list eqs
809 else
810 ff ()
811 in
812 let cs_argsj = translate_context env_lift_recparams_fix_nonrecparams_tomatch_csargsi (EConstr.Unsafe.to_rel_context constrs.(j).cs_args) in
813 Term.it_mkLambda_or_LetIn cc cs_argsj)
814 in
815 let predj = EConstr.of_constr (translate_term env_lift_recparams_fix_nonrecparams_tomatch_csargsi pred) in
816 let case =
817 simple_make_case_or_project env (Evd.from_env env)
818 ci (predj,rci) NoInvert (EConstr.mkRel (nb_cstr_args + 1))
819 (EConstr.of_constr_array ar2)
820 in
821 let cs_argsi = translate_context env_lift_recparams_fix_nonrecparams_tomatch (EConstr.Unsafe.to_rel_context constrs.(i).cs_args) in
822 Term.it_mkLambda_or_LetIn (EConstr.Unsafe.to_constr case) cs_argsi)
823 in
824 let predi = EConstr.of_constr (translate_term env_lift_recparams_fix_nonrecparams_tomatch pred) in
825 let case =
826 simple_make_case_or_project env (Evd.from_env env)
827 ci (predi,rci) NoInvert (EConstr.mkRel 2)
828 (EConstr.of_constr_array ar) in
829 EConstr.Unsafe.to_constr case
830 in
831 Term.it_mkLambda_or_LetIn
832 (Term.it_mkLambda_or_LetIn body tomatch_ctx)
833 nonrecparams_ctx_with_eqs
834 in (* build_beq_scheme *)
835
836 let res =
837 match mib.mind_finite with
838 | CoFinite ->
839 raise NoDecidabilityCoInductive
840 | Finite when truly_recursive || nb_ind > 1 (* Hum... *) ->
841 let cores = Array.init nb_ind make_one_eq in
842 Array.init nb_ind (fun i ->
843 let kelim = Inductiveops.elim_sort (mib,mib.mind_packets.(i)) in
844 if not (Inductive.eliminates_to (Environ.qualities env) kelim Sorts.Quality.qtype) then
845 raise (NonSingletonProp (kn,i));
846 let decrArg = Context.Rel.length nonrecparams_ctx_with_eqs in
847 let fix = mkFix (((Array.make nb_ind decrArg),i),(names,types,cores)) in
848 Term.it_mkLambda_or_LetIn fix recparams_ctx_with_eqs)
849 | Finite | BiFinite ->
850 assert (Int.equal nb_ind 1);
851 (* If the inductive type is not recursive, the fixpoint is
852 not used, so let's replace it with garbage *)
853 let kelim = Inductiveops.elim_sort (mib,mib.mind_packets.(0)) in
854 if not (Inductive.eliminates_to (Environ.qualities env) kelim Sorts.Quality.qtype)
855 then raise (NonSingletonProp (kn,0));
856 [|Term.it_mkLambda_or_LetIn (make_one_eq 0) recparams_ctx_with_eqs|]
857 in
858
859 let uctx =
860 (* infer univ constraints
861 For instance template poly inductive produces a univ monomorphic scheme
862 which when applied needs to constrain the universe of its argument
863 *)
864 let sigma = Evd.from_ctx uctx in
865 let sigma = Array.fold_left (fun sigma c ->
866 fst @@ Typing.type_of env sigma (EConstr.of_constr c))
867 sigma
868 res
869 in
870 Evd.ustate sigma
871 in
872
873 res, uctx
874
875 let beq_scheme_kind =
876 Ind_tables.declare_mutual_scheme_object "beq"
877 ~deps:build_beq_scheme_deps
878 build_beq_scheme
879
880 let _ = beq_scheme_kind_aux := fun () -> beq_scheme_kind
881
882 (* This function tryies to get the [inductive] between a constr
883 the constr should be Ind i or App(Ind i,[|args|])
884 *)
885 let destruct_ind env sigma c =
886 let open EConstr in
887 let (c,v) = Reductionops.whd_all_stack env sigma c in
888 destInd sigma c, Array.of_list v
889
890 let bl_scheme_kind_aux = ref (fun () -> failwith "Undefined")
891 let lb_scheme_kind_aux = ref (fun () -> failwith "Undefined")
892
893 (*
894 In the following, avoid is the list of names to avoid.
895 If the args of the Inductive type are A1 ... An
896 then avoid should be
897 [| lb_An ... lb _A1 (resp. bl_An ... bl_A1)
898 eq_An .... eq_A1 An ... A1 |]
899 so from Ai we can find the correct eq_Ai bl_ai or lb_ai
900 *)
901 (* used in the leib -> bool side*)
902 let do_replace_lb handle aavoid narg p q =
903 let open EConstr in
904 let avoid = Array.of_list aavoid in
905 let do_arg env sigma hd v offset =
906 match kind sigma v with
907 | Var s ->
908 let x = narg*offset in
909 let n = Array.length avoid in
910 let rec find i =
911 if Id.equal avoid.(n-i) s then avoid.(n-i-x)
912 else (if i<n then find (i+1)
913 else CErrors.user_err
914 Pp.(str "Var " ++ Id.print s ++ str " seems unknown.")
915 )
916 in mkVar (find 1)
917 | Const (cst,u) ->
918 (* Works in specific situations where the args have to be already declared as a
919 Parameter (see example "J" in test file SchemeEquality.v);
920 We assume the parameter to have the same polymorphic arity as cst *)
921 let lbl = Id.to_string (Constant.label cst) in
922 let newlbl = if Int.equal offset 1 then ("eq_" ^ lbl) else (lbl ^ "_lb") in
923 let newcst = Constant.change_label cst (Id.of_string newlbl) in
924 if Environ.mem_constant newcst env then mkConstU (newcst,u)
925 else raise (ConstructorWithNonParametricInductiveType (fst hd))
926 | _ -> raise (ConstructorWithNonParametricInductiveType (fst hd))
927
928 in
929 Proofview.Goal.enter begin fun gl ->
930 let sigma = Proofview.Goal.sigma gl in
931 let env = Proofview.Goal.env gl in
932 let type_of_pq = Retyping.get_type_of env sigma p in
933 let (ind,u as indu),v = destruct_ind env sigma type_of_pq in
934 let c = get_scheme handle (!lb_scheme_kind_aux ()) ind in
935 let sigma , lb_type_of_p = Evd.fresh_global env sigma c in
936 let lb_args = Array.append (Array.append
937 v
938 (Array.Smart.map (fun x -> do_arg env sigma indu x 1) v))
939 (Array.Smart.map (fun x -> do_arg env sigma indu x 2) v)
940 in let app = if Array.is_empty lb_args
941 then lb_type_of_p else mkApp (lb_type_of_p,lb_args)
942 in
943 Tacticals.tclTHENLIST [
944 Proofview.Unsafe.tclEVARS sigma;
945 Equality.replace p q ; Tactics.apply app ; Auto.default_auto]
946 end
947
948 (* used in the bool -> leb side *)
949 let do_replace_bl handle (ind,u as indu) aavoid narg lft rgt =
950 let open EConstr in
951 let avoid = Array.of_list aavoid in
952 let do_arg env sigma hd v offset =
953 match kind sigma v with
954 | Var s ->
955 let x = narg*offset in
956 let n = Array.length avoid in
957 let rec find i =
958 if Id.equal avoid.(n-i) s then avoid.(n-i-x)
959 else (if i<n then find (i+1)
960 else CErrors.user_err
961 Pp.(str "Var " ++ Id.print s ++ str " seems unknown.")
962 )
963 in mkVar (find 1)
964 | Const (cst,u) ->
965 (* Works in specific situations where the args have to be already declared as a
966 Parameter (see example "J" in test file SchemeEquality.v)
967 We assume the parameter to have the same polymorphic arith as cst *)
968 let lbl = Id.to_string (Constant.label cst) in
969 let newlbl = if Int.equal offset 1 then ("eq_" ^ lbl) else (lbl ^ "_bl") in
970 let newcst = Constant.change_label cst (Id.of_string newlbl) in
971 if Environ.mem_constant newcst env then mkConstU (newcst,u)
972 else raise (ConstructorWithNonParametricInductiveType (fst hd))
973 | _ -> raise (ConstructorWithNonParametricInductiveType (fst hd))
974 in
975
976 let rec aux l1 l2 =
977 match (l1,l2) with
978 | (t1::q1,t2::q2) ->
979 Proofview.Goal.enter begin fun gl ->
980 let env = Proofview.Goal.env gl in
981 let sigma = Proofview.Goal.sigma gl in
982 if EConstr.eq_constr sigma t1 t2 then aux q1 q2
983 else (
984 let tt1 = Retyping.get_type_of env sigma t1 in
985 let (ind',u as indu),v = try destruct_ind env sigma tt1
986 (* trick so that the good sequence is returned*)
987 with e when CErrors.noncritical e -> indu,[||]
988 in if Environ.QInd.equal env ind' ind
989 then Tacticals.tclTHENLIST [Equality.replace t1 t2; Auto.default_auto ; aux q1 q2 ]
990 else (
991 let c = get_scheme handle (!bl_scheme_kind_aux ()) ind' in
992 let sigma , bl_t1 = Evd.fresh_global env sigma c in
993 let bl_args =
994 Array.append (Array.append
995 v
996 (Array.Smart.map (fun x -> do_arg env sigma indu x 1) v))
997 (Array.Smart.map (fun x -> do_arg env sigma indu x 2) v )
998 in
999 let app = if Array.is_empty bl_args
1000 then bl_t1 else mkApp (bl_t1,bl_args)
1001 in
1002 Tacticals.tclTHENLIST [
1003 Proofview.Unsafe.tclEVARS sigma;
1004 Equality.replace_by t1 t2
1005 (Tacticals.tclTHEN (Tactics.apply app) (Auto.default_auto)) ;
1006 aux q1 q2 ]
1007 )
1008 )
1009 end
1010 | ([],[]) -> Proofview.tclUNIT ()
1011 | _ -> Tacticals.tclZEROMSG Pp.(str "Both side of the equality must have the same arity.")
1012 in
1013 let open Proofview.Notations in
1014 Proofview.tclEVARMAP >>= fun sigma ->
1015 begin try Proofview.tclUNIT (destApp sigma lft)
1016 with DestKO -> Tacticals.tclZEROMSG Pp.(str "replace failed.")
1017 end >>= fun (ind1,ca1) ->
1018 begin try Proofview.tclUNIT (destApp sigma rgt)
1019 with DestKO -> Tacticals.tclZEROMSG Pp.(str "replace failed.")
1020 end >>= fun (ind2,ca2) ->
1021 begin try Proofview.tclUNIT (fst (destInd sigma ind1))
1022 with DestKO ->
1023 begin try Proofview.tclUNIT (fst (fst (destConstruct sigma ind1)))
1024 with DestKO -> Tacticals.tclZEROMSG Pp.(str "The expected type is an inductive one.")
1025 end
1026 end >>= fun (sp1,i1) ->
1027 begin try Proofview.tclUNIT (fst (destInd sigma ind2))
1028 with DestKO ->
1029 begin try Proofview.tclUNIT (fst (fst (destConstruct sigma ind2)))
1030 with DestKO -> Tacticals.tclZEROMSG Pp.(str "The expected type is an inductive one.")
1031 end
1032 end >>= fun (sp2,i2) ->
1033 Proofview.tclENV >>= fun env ->
1034 if not (Environ.QMutInd.equal env sp1 sp2) || not (Int.equal i1 i2)
1035 then Tacticals.tclZEROMSG Pp.(str "Eq should be on the same type")
1036 else aux (Array.to_list ca1) (Array.to_list ca2)
1037
1038 (*
1039 create, from a list of ids [i1,i2,...,in] the list
1040 [(in,eq_in,in_bl,in_al),,...,(i1,eq_i1,i1_bl_i1_al )]
1041 *)
1042 let list_id l = List.fold_left ( fun a decl -> let s' =
1043 match RelDecl.get_name decl with
1044 Name s -> Id.to_string s
1045 | Anonymous -> "A" in
1046 (Id.of_string s',Id.of_string ("eq_"^s'),
1047 Id.of_string (s'^"_bl"),
1048 Id.of_string (s'^"_lb"))
1049 ::a
1050 ) [] l
1051
1052 let avoid_of_list_id list_id =
1053 List.fold_left (fun avoid (s,seq,sbl,slb) ->
1054 List.fold_left (fun avoid id -> Id.Set.add id avoid)
1055 avoid [s;seq;sbl;slb])
1056 Id.Set.empty list_id
1057
1058 (*
1059 build the right eq_I A B.. N eq_A .. eq_N
1060 *)
1061 let eqI handle (ind,u) list_id =
1062 let eA = Array.of_list((List.map (fun (s,_,_,_) -> mkVar s) list_id)@
1063 (List.map (fun (_,seq,_,_)-> mkVar seq) list_id ))
1064 and e = Constr.mkRef (get_scheme handle beq_scheme_kind ind,u)
1065 in mkApp(e,eA)
1066
1067 (**********************************************************************)
1068 (* Boolean->Leibniz *)
1069
1070 open Namegen
1071
1072 let compute_bl_goal env handle (ind,u) lnamesparrec nparrec =
1073 let list_id = list_id lnamesparrec in
1074 let eqI = eqI handle (ind,u) list_id in
1075 let avoid = avoid_of_list_id list_id in
1076 let x = next_ident_away (Id.of_string "x") avoid in
1077 let y = next_ident_away (Id.of_string "y") (Id.Set.add x avoid) in
1078 let open Term in
1079 let create_input c =
1080 let bl_typ = List.map (fun (s,seq,_,_) ->
1081 mkNamedProd (Context.make_annot x Sorts.Relevant) (mkVar s) (
1082 mkNamedProd (Context.make_annot y Sorts.Relevant) (mkVar s) (
1083 mkArrow
1084 ( mkApp(eq (),[|bb (); mkApp(mkVar seq,[|mkVar x;mkVar y|]);tt () |]))
1085 Sorts.Relevant
1086 ( mkApp(eq (),[|mkVar s;mkVar x;mkVar y|]))
1087 ))
1088 ) list_id in
1089 let bl_input = List.fold_left2 ( fun a (s,_,sbl,_) b ->
1090 mkNamedProd (Context.make_annot sbl Sorts.Relevant) b a
1091 ) c (List.rev list_id) (List.rev bl_typ) in
1092 let eqs_typ = List.map (fun (s,_,_,_) ->
1093 mkProd(Context.make_annot Anonymous Sorts.Relevant,mkVar s,mkProd(Context.make_annot Anonymous Sorts.Relevant,mkVar s,(bb ())))
1094 ) list_id in
1095 let eq_input = List.fold_left2 ( fun a (s,seq,_,_) b ->
1096 mkNamedProd (Context.make_annot seq Sorts.Relevant) b a
1097 ) bl_input (List.rev list_id) (List.rev eqs_typ) in
1098 List.fold_left (fun a decl ->
1099 let x = Context.map_annot
1100 (function Name s -> s | Anonymous -> next_ident_away (Id.of_string "A") avoid)
1101 (RelDecl.get_annot decl)
1102 in
1103 mkNamedProd x (RelDecl.get_type decl) a) eq_input lnamesparrec
1104 in
1105 create_input (
1106 mkNamedProd (Context.make_annot x Sorts.Relevant) (mkFullInd env (ind,u) (2*nparrec)) (
1107 mkNamedProd (Context.make_annot y Sorts.Relevant) (mkFullInd env (ind,u) (2*nparrec+1)) (
1108 mkArrow
1109 (mkApp(eq (),[|bb ();mkApp(eqI,[|mkVar x;mkVar y|]);tt ()|]))
1110 Sorts.Relevant
1111 (mkApp(eq (),[|mkFullInd env (ind,u) (2*nparrec+3);mkVar x;mkVar y|]))
1112 )))
1113
1114 let compute_bl_tact handle ind lnamesparrec nparrec =
1115 let list_id = list_id lnamesparrec in
1116 let first_intros =
1117 ( List.map (fun (s,_,_,_) -> s ) list_id )
1118 @ ( List.map (fun (_,seq,_,_ ) -> seq) list_id )
1119 @ ( List.map (fun (_,_,sbl,_ ) -> sbl) list_id )
1120 in
1121 let open Tactics in
1122 let open Proofview.Notations in
1123 Ind_tables.push_handle handle <*>
1124 intros_using_then first_intros begin fun fresh_first_intros ->
1125 Tacticals.tclTHENLIST [
1126 intro_using_then (Id.of_string "x") (fun freshn -> induct_on (EConstr.mkVar freshn));
1127 intro_using_then (Id.of_string "y") (fun freshm -> destruct_on (EConstr.mkVar freshm));
1128 intro_using_then (Id.of_string "Z") begin fun freshz ->
1129 Tacticals.tclTHENLIST [
1130 intros;
1131 Tacticals.tclTRY (
1132 Tacticals.tclORELSE reflexivity my_discr_tac
1133 );
1134 simpl_in_hyp (freshz,Locus.InHyp);
1135 (*
1136 repeat ( apply andb_prop in z;let z1:= fresh "Z" in destruct z as [z1 z]).
1137 *)
1138 Tacticals.tclREPEAT (
1139 Tacticals.tclTHENLIST [
1140 Simple.apply_in freshz (EConstr.of_constr (andb_prop()));
1141 let open Tactypes in
1142 destruct_on_as (EConstr.mkVar freshz)
1143 (IntroOrPattern [[CAst.make @@ IntroNaming (IntroFresh (Id.of_string "Z"));
1144 CAst.make @@ IntroNaming (IntroIdentifier freshz)]])
1145 ]);
1146 (*
1147 Ci a1 ... an = Ci b1 ... bn
1148 replace bi with ai; auto || replace bi with ai by apply typeofbi_prod ; auto
1149 *)
1150 Proofview.Goal.enter begin fun gl ->
1151 let env = Proofview.Goal.env gl in
1152 let concl = Proofview.Goal.concl gl in
1153 let sigma = Proofview.Goal.sigma gl in
1154 match EConstr.kind sigma concl with
1155 | App (c,ca) -> (
1156 match EConstr.kind sigma c with
1157 | Ind (indeq, u) ->
1158 if Environ.QGlobRef.equal env (GlobRef.IndRef indeq) Rocqlib.(lib_ref "core.eq.type")
1159 then
1160 Tacticals.tclTHEN
1161 (do_replace_bl handle ind
1162 (List.rev fresh_first_intros)
1163 nparrec (ca.(2))
1164 (ca.(1)))
1165 Auto.default_auto
1166 else
1167 Tacticals.tclZEROMSG Pp.(str "Failure while solving Boolean->Leibniz.")
1168 | _ -> Tacticals.tclZEROMSG Pp.(str" Failure while solving Boolean->Leibniz.")
1169 )
1170 | _ -> Tacticals.tclZEROMSG Pp.(str "Failure while solving Boolean->Leibniz.")
1171 end
1172
1173 ]
1174 end
1175 ]
1176 end
1177
1178 let make_bl_scheme env handle mind =
1179 let mib = Environ.lookup_mind mind env in
1180 if not (Int.equal (Array.length mib.mind_packets) 1) then
1181 CErrors.user_err
1182 Pp.(str "Automatic building of boolean->Leibniz lemmas not supported");
1183
1184 (* Setting universes *)
1185 let auctx = Declareops.universes_context mib.mind_universes in
1186 let u, uctx = UnivGen.fresh_instance_from auctx None in
1187 let uctx = UState.merge_sort_context ~sideff:false UState.univ_rigid ~src:UState.Internal (UState.from_env env) uctx in
1188
1189 let ind = (mind,0) in
1190 let nparrec = mib.mind_nparams_rec in
1191 let lnonparrec,lnamesparrec =
1192 Inductive.inductive_nonrec_rec_paramdecls (mib,u) in
1193 let bl_goal = compute_bl_goal env handle (ind,u) lnamesparrec nparrec in
1194 let bl_goal = EConstr.of_constr bl_goal in
1195 let univ_poly = Declareops.inductive_is_polymorphic mib in
1196 let poly = PolyFlags.of_univ_poly univ_poly in (* FIXME cumulativity not handled *)
1197 let uctx = if univ_poly then Evd.ustate (fst (Typing.sort_of env (Evd.from_ctx uctx) bl_goal)) else uctx in
1198 let (ans, _, _, _, uctx) = Subproof.build_by_tactic ~poly env ~uctx ~typ:bl_goal
1199 (compute_bl_tact handle (ind, EConstr.EInstance.make u) lnamesparrec nparrec)
1200 in
1201 ([|ans|], uctx)
1202
1203 let make_bl_scheme_deps env ind =
1204 let inds = get_inductive_deps ~noprop:false env ind in
1205 let map ind = Ind_tables.SchemeMutualDep (ind, !bl_scheme_kind_aux ()) in
1206 Ind_tables.SchemeMutualDep (ind, beq_scheme_kind) :: List.map map inds
1207
1208 let bl_scheme_kind =
1209 Ind_tables.declare_mutual_scheme_object "dec_bl"
1210 ~deps:make_bl_scheme_deps
1211 make_bl_scheme
1212
1213 let _ = bl_scheme_kind_aux := fun () -> bl_scheme_kind
1214
1215 (**********************************************************************)
1216 (* Leibniz->Boolean *)
1217
1218 let compute_lb_goal env handle (ind,u) lnamesparrec nparrec =
1219 let list_id = list_id lnamesparrec in
1220 let eq = eq () and tt = tt () and bb = bb () in
1221 let avoid = avoid_of_list_id list_id in
1222 let eqI = eqI handle (ind,u) list_id in
1223 let x = next_ident_away (Id.of_string "x") avoid in
1224 let y = next_ident_away (Id.of_string "y") (Id.Set.add x avoid) in
1225 let open Term in
1226 let create_input c =
1227 let lb_typ = List.map (fun (s,seq,_,_) ->
1228 mkNamedProd (Context.make_annot x Sorts.Relevant) (mkVar s) (
1229 mkNamedProd (Context.make_annot y Sorts.Relevant) (mkVar s) (
1230 mkArrow
1231 ( mkApp(eq,[|mkVar s;mkVar x;mkVar y|]))
1232 Sorts.Relevant
1233 ( mkApp(eq,[|bb;mkApp(mkVar seq,[|mkVar x;mkVar y|]);tt|]))
1234 ))
1235 ) list_id in
1236 let lb_input = List.fold_left2 ( fun a (s,_,_,slb) b ->
1237 mkNamedProd (Context.make_annot slb Sorts.Relevant) b a
1238 ) c (List.rev list_id) (List.rev lb_typ) in
1239 let eqs_typ = List.map (fun (s,_,_,_) ->
1240 mkProd(Context.make_annot Anonymous Sorts.Relevant,mkVar s,
1241 mkProd(Context.make_annot Anonymous Sorts.Relevant,mkVar s,bb))
1242 ) list_id in
1243 let eq_input = List.fold_left2 ( fun a (s,seq,_,_) b ->
1244 mkNamedProd (Context.make_annot seq Sorts.Relevant) b a
1245 ) lb_input (List.rev list_id) (List.rev eqs_typ) in
1246 List.fold_left (fun a decl ->
1247 let x = Context.map_annot
1248 (function Name s -> s | Anonymous -> Id.of_string "A")
1249 (RelDecl.get_annot decl)
1250 in
1251 mkNamedProd x (RelDecl.get_type decl) a) eq_input lnamesparrec
1252 in
1253 create_input (
1254 mkNamedProd (Context.make_annot x Sorts.Relevant) (mkFullInd env (ind,u) (2*nparrec)) (
1255 mkNamedProd (Context.make_annot y Sorts.Relevant) (mkFullInd env (ind,u) (2*nparrec+1)) (
1256 mkArrow
1257 (mkApp(eq,[|mkFullInd env (ind,u) (2*nparrec+2);mkVar x;mkVar y|]))
1258 Sorts.Relevant
1259 (mkApp(eq,[|bb;mkApp(eqI,[|mkVar x;mkVar y|]);tt|]))
1260 )))
1261
1262 let compute_lb_tact handle ind lnamesparrec nparrec =
1263 let list_id = list_id lnamesparrec in
1264 let first_intros =
1265 ( List.map (fun (s,_,_,_) -> s ) list_id )
1266 @ ( List.map (fun (_,seq,_,_) -> seq) list_id )
1267 @ ( List.map (fun (_,_,_,slb) -> slb) list_id )
1268 in
1269 let open Tactics in
1270 let open Proofview.Notations in
1271 Ind_tables.push_handle handle <*>
1272 intros_using_then first_intros begin fun fresh_first_intros ->
1273 Tacticals.tclTHENLIST [
1274 intro_using_then (Id.of_string "x") (fun freshn -> induct_on (EConstr.mkVar freshn));
1275 intro_using_then (Id.of_string "y") (fun freshm -> destruct_on (EConstr.mkVar freshm));
1276 intro_using_then (Id.of_string "Z") begin fun freshz ->
1277 Tacticals.tclTHENLIST [
1278 intros;
1279 Tacticals.tclTRY (
1280 Tacticals.tclORELSE reflexivity my_discr_tac
1281 );
1282 my_inj_tac freshz;
1283 intros; simpl_in_concl;
1284 Auto.default_auto;
1285 Tacticals.tclREPEAT (
1286 Tacticals.tclTHENLIST [apply (EConstr.of_constr (andb_true_intro()));
1287 simplest_split ;Auto.default_auto ]
1288 );
1289 Proofview.Goal.enter begin fun gls ->
1290 let concl = Proofview.Goal.concl gls in
1291 let sigma = Proofview.Goal.sigma gls in
1292 (* assume the goal to be eq (eq_type ...) = true *)
1293 match EConstr.kind sigma concl with
1294 | App(c,ca) -> (match (EConstr.kind sigma ca.(1)) with
1295 | App(c',ca') ->
1296 let n = Array.length ca' in
1297 do_replace_lb handle
1298 (List.rev fresh_first_intros)
1299 nparrec
1300 ca'.(n-2) ca'.(n-1)
1301 | _ ->
1302 Tacticals.tclZEROMSG Pp.(str "Failure while solving Leibniz->Boolean.")
1303 )
1304 | _ ->
1305 Tacticals.tclZEROMSG Pp.(str "Failure while solving Leibniz->Boolean.")
1306 end
1307 ]
1308 end
1309 ]
1310 end
1311
1312 let make_lb_scheme env handle mind =
1313 let mib = Environ.lookup_mind mind env in
1314 if not (Int.equal (Array.length mib.mind_packets) 1) then
1315 CErrors.user_err
1316 Pp.(str "Automatic building of Leibniz->boolean lemmas not supported");
1317 let ind = (mind,0) in
1318
1319 (* Setting universes *)
1320 let auctx = Declareops.universes_context mib.mind_universes in
1321 let u, uctx = UnivGen.fresh_instance_from auctx None in
1322 let uctx = UState.merge_sort_context ~sideff:false UState.univ_rigid ~src:UState.Internal (UState.from_env env) uctx in
1323
1324 let nparrec = mib.mind_nparams_rec in
1325 let lnonparrec,lnamesparrec =
1326 Inductive.inductive_nonrec_rec_paramdecls (mib,u) in
1327 let lb_goal = compute_lb_goal env handle (ind,u) lnamesparrec nparrec in
1328 let lb_goal = EConstr.of_constr lb_goal in
1329 let poly = Declareops.inductive_is_polymorphic mib in
1330 let uctx = if poly then Evd.ustate (fst (Typing.sort_of env (Evd.from_ctx uctx) lb_goal)) else uctx in
1331 let poly = PolyFlags.of_univ_poly poly (* FIXME cumulativity not handled *) in
1332 let (ans, _, _, _, ctx) = Subproof.build_by_tactic ~poly env ~uctx ~typ:lb_goal
1333 (compute_lb_tact handle ind lnamesparrec nparrec)
1334 in
1335 ([|ans|], ctx)
1336
1337 let make_lb_scheme_deps env ind =
1338 let inds = get_inductive_deps ~noprop:false env ind in
1339 let map ind = Ind_tables.SchemeMutualDep (ind, !lb_scheme_kind_aux ()) in
1340 Ind_tables.SchemeMutualDep (ind, beq_scheme_kind) :: List.map map inds
1341
1342 let lb_scheme_kind =
1343 Ind_tables.declare_mutual_scheme_object "dec_lb"
1344 ~deps:make_lb_scheme_deps
1345 make_lb_scheme
1346
1347 let _ = lb_scheme_kind_aux := fun () -> lb_scheme_kind
1348
1349 (**********************************************************************)
1350 (* Decidable equality *)
1351
1352 let check_not_is_defined () =
1353 if not (Rocqlib.has_ref "core.not.type")
1354 then raise (UndefinedCst "not")
1355
1356 (* {n=m}+{n<>m} part *)
1357 let compute_dec_goal env ind lnamesparrec nparrec =
1358 check_not_is_defined ();
1359 let eq = eq () and tt = tt () and bb = bb () in
1360 let list_id = list_id lnamesparrec in
1361 let avoid = avoid_of_list_id list_id in
1362 let x = next_ident_away (Id.of_string "x") avoid in
1363 let y = next_ident_away (Id.of_string "y") (Id.Set.add x avoid) in
1364 let open Term in
1365 let create_input c =
1366 let lb_typ = List.map (fun (s,seq,_,_) ->
1367 mkNamedProd (Context.make_annot x Sorts.Relevant) (mkVar s) (
1368 mkNamedProd (Context.make_annot y Sorts.Relevant) (mkVar s) (
1369 mkArrow
1370 ( mkApp(eq,[|mkVar s;mkVar x;mkVar y|]))
1371 Sorts.Relevant
1372 ( mkApp(eq,[|bb;mkApp(mkVar seq,[|mkVar x;mkVar y|]);tt|]))
1373 ))
1374 ) list_id in
1375 let bl_typ = List.map (fun (s,seq,_,_) ->
1376 mkNamedProd (Context.make_annot x Sorts.Relevant) (mkVar s) (
1377 mkNamedProd (Context.make_annot y Sorts.Relevant) (mkVar s) (
1378 mkArrow
1379 ( mkApp(eq,[|bb;mkApp(mkVar seq,[|mkVar x;mkVar y|]);tt|]))
1380 Sorts.Relevant
1381 ( mkApp(eq,[|mkVar s;mkVar x;mkVar y|]))
1382 ))
1383 ) list_id in
1384
1385 let lb_input = List.fold_left2 ( fun a (s,_,_,slb) b ->
1386 mkNamedProd (Context.make_annot slb Sorts.Relevant) b a
1387 ) c (List.rev list_id) (List.rev lb_typ) in
1388 let bl_input = List.fold_left2 ( fun a (s,_,sbl,_) b ->
1389 mkNamedProd (Context.make_annot sbl Sorts.Relevant) b a
1390 ) lb_input (List.rev list_id) (List.rev bl_typ) in
1391
1392 let eqs_typ = List.map (fun (s,_,_,_) ->
1393 mkProd(Context.make_annot Anonymous Sorts.Relevant,mkVar s,
1394 mkProd(Context.make_annot Anonymous Sorts.Relevant,mkVar s,bb))
1395 ) list_id in
1396 let eq_input = List.fold_left2 ( fun a (s,seq,_,_) b ->
1397 mkNamedProd (Context.make_annot seq Sorts.Relevant) b a
1398 ) bl_input (List.rev list_id) (List.rev eqs_typ) in
1399 List.fold_left (fun a decl ->
1400 let x = Context.map_annot
1401 (function Name s -> s | Anonymous -> Id.of_string "A")
1402 (RelDecl.get_annot decl)
1403 in
1404 mkNamedProd x (RelDecl.get_type decl) a) eq_input lnamesparrec
1405 in
1406 let eqnm = mkApp(eq,[|mkFullInd env ind (3*nparrec+2);mkVar x;mkVar y|]) in
1407 create_input (
1408 mkNamedProd (Context.make_annot x Sorts.Relevant) (mkFullInd env ind (3*nparrec)) (
1409 mkNamedProd (Context.make_annot y Sorts.Relevant) (mkFullInd env ind (3*nparrec+1)) (
1410 mkApp(sumbool(),[|eqnm;mkApp (UnivGen.constr_of_monomorphic_global (Global.env ()) @@ Rocqlib.lib_ref "core.not.type",[|eqnm|])|])
1411 )
1412 )
1413 )
1414
1415 let compute_dec_tact handle (ind,u) lnamesparrec nparrec =
1416 let eq = eq () and tt = tt ()
1417 and ff = ff () and bb = bb () in
1418 let list_id = list_id lnamesparrec in
1419 let _ = get_scheme handle beq_scheme_kind ind in (* This is just an assertion? *)
1420 let _non_fresh_eqI = eqI handle (ind,u) list_id in
1421 let eqtrue x = mkApp(eq,[|bb;x;tt|]) in
1422 let eqfalse x = mkApp(eq,[|bb;x;ff|]) in
1423 let first_intros =
1424 ( List.map (fun (s,_,_,_) -> s ) list_id )
1425 @ ( List.map (fun (_,seq,_,_) -> seq) list_id )
1426 @ ( List.map (fun (_,_,sbl,_) -> sbl) list_id )
1427 @ ( List.map (fun (_,_,_,slb) -> slb) list_id )
1428 in
1429 let open Tactics in
1430 let fresh_id s gl = fresh_id_in_env (Id.Set.empty) s (Proofview.Goal.env gl) in
1431 let open Proofview.Notations in
1432 Ind_tables.push_handle handle <*>
1433 intros_using_then first_intros begin fun fresh_first_intros ->
1434 let eqI =
1435 let a = Array.of_list fresh_first_intros in
1436 let n = List.length list_id in
1437 assert (Int.equal (Array.length a) (4 * n));
1438 let fresh_list_id =
1439 List.init n (fun i -> (Array.get a i, Array.get a (i+n),
1440 Array.get a (i+2*n), Array.get a (i+3*n))) in
1441 eqI handle (ind,u) fresh_list_id
1442 in
1443 intro_using_then (Id.of_string "x") begin fun freshn ->
1444 intro_using_then (Id.of_string "y") begin fun freshm ->
1445 Proofview.Goal.enter begin fun gl ->
1446 let freshH = fresh_id (Id.of_string "H") gl in
1447 let eqbnm = mkApp(eqI,[|mkVar freshn;mkVar freshm|]) in
1448 let arfresh = Array.of_list fresh_first_intros in
1449 let xargs = Array.sub arfresh 0 (2*nparrec) in
1450 (* univ polymorphic schemes may have extra constraints
1451 from using univ monomorphic f_equal and the like *)
1452 let env, sigma = Proofview.Goal.(env gl, sigma gl) in
1453 let c = get_scheme handle bl_scheme_kind ind in
1454 let sigma , blI = Evd.fresh_global env sigma c in
1455 let c = get_scheme handle lb_scheme_kind ind in
1456 let sigma , lbI = Evd.fresh_global env sigma c in
1457 Tacticals.tclTHENLIST [
1458 Proofview.Unsafe.tclEVARS sigma;
1459
1460 (*we do this so we don't have to prove the same goal twice *)
1461 assert_by (Name freshH) (EConstr.of_constr (
1462 mkApp(sumbool(),[|eqtrue eqbnm; eqfalse eqbnm|])
1463 ))
1464 (Tacticals.tclTHEN (destruct_on (EConstr.of_constr eqbnm)) Auto.default_auto);
1465
1466 Proofview.Goal.enter begin fun gl ->
1467 let freshH2 = fresh_id (Id.of_string "H") gl in
1468 Tacticals.tclTHENS (destruct_on_using (EConstr.mkVar freshH) freshH2) [
1469 (* left *)
1470 Tacticals.tclTHENLIST [
1471 simplest_left;
1472 apply (EConstr.mkApp(blI,Array.map EConstr.mkVar xargs));
1473 Auto.default_auto
1474 ]
1475 ;
1476
1477 (*right *)
1478 Proofview.Goal.enter begin fun gl ->
1479 let freshH3 = fresh_id (Id.of_string "H") gl in
1480 Tacticals.tclTHENLIST [
1481 simplest_right ;
1482 unfold_constr (Rocqlib.lib_ref "core.not.type");
1483 intro;
1484 Equality.subst_all ();
1485 assert_by (Name freshH3)
1486 (EConstr.of_constr (mkApp(eq,[|bb;mkApp(eqI,[|mkVar freshm;mkVar freshm|]);tt|])))
1487 (Tacticals.tclTHENLIST [
1488 apply (EConstr.mkApp(lbI,Array.map EConstr.mkVar xargs));
1489 Auto.default_auto
1490 ]);
1491 Equality.general_rewrite ~where:(Some freshH3) ~l2r:true
1492 Locus.AllOccurrences ~freeze:true ~dep:false ~with_evars:true
1493 ((EConstr.mkVar freshH2),
1494 NoBindings
1495 )
1496 ;
1497 my_discr_tac
1498 ]
1499 end
1500 ]
1501 end
1502 ]
1503 end
1504 end
1505 end
1506 end
1507
1508 let make_eq_decidability env handle mind =
1509 let mib = Environ.lookup_mind mind env in
1510 if not (Int.equal (Array.length mib.mind_packets) 1) then
1511 raise DecidabilityMutualNotSupported;
1512 let ind = (mind,0) in
1513 let nparrec = mib.mind_nparams_rec in
1514
1515 (* Setting universes *)
1516 let auctx = Declareops.universes_context mib.mind_universes in
1517 let u, uctx = UnivGen.fresh_instance_from auctx None in
1518 let uctx = UState.merge_sort_context ~sideff:false UState.univ_rigid ~src:UState.Internal (UState.from_env env) uctx in
1519
1520 let lnonparrec,lnamesparrec =
1521 Inductive.inductive_nonrec_rec_paramdecls (mib,u) in
1522 let dec_goal = EConstr.of_constr (compute_dec_goal env (ind,u) lnamesparrec nparrec) in
1523 let univ_poly = Declareops.inductive_is_polymorphic mib in
1524 (* FIXME: cumulativity not handled *)
1525 let poly = PolyFlags.of_univ_poly univ_poly in
1526 let uctx = if univ_poly then Evd.ustate (fst (Typing.sort_of env (Evd.from_ctx uctx) dec_goal)) else uctx in
1527 let (ans, _, _, _, ctx) = Subproof.build_by_tactic ~poly env ~uctx
1528 ~typ:dec_goal (compute_dec_tact handle (ind,u) lnamesparrec nparrec)
1529 in
1530 ([|ans|], ctx)
1531
1532 let eq_dec_scheme_kind =
1533 Ind_tables.declare_mutual_scheme_object "eq_dec"
1534 ~deps:(fun _ ind -> [SchemeMutualDep (ind, beq_scheme_kind); SchemeMutualDep (ind, bl_scheme_kind); SchemeMutualDep (ind, lb_scheme_kind)])
1535 make_eq_decidability
1536
1537 (* The eq_dec_scheme proofs depend on the equality and discr tactics
1538 but the inj tactics, that comes with discr, depends on the
1539 eq_dec_scheme... *)
1540
1541 let _ = Equality.set_eq_dec_scheme_kind eq_dec_scheme_kind