Debian Codegraph @

tactics/equality.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 module CVars = Vars
12 open Pp
13 open CErrors
14 open Util
15 open Names
16 open Constr
17 open Context
18 open Termops
19 open EConstr
20 open Vars
21 open Namegen
22 open Inductive
23 open Inductiveops
24 open Libnames
25 open Globnames
26 open Reductionops
27 open Retyping
28 open Logic
29 open Hipattern
30 open Tacticals
31 open Tactics
32 open Tacred
33 open Rocqlib
34 open Declarations
35 open Ind_tables
36 open Eqschemes
37 open Locus
38 open Locusops
39 open Tactypes
40 open Proofview.Notations
41 open Unification
42 open Context.Named.Declaration
43 open Combinators
44
45 module NamedDecl = Context.Named.Declaration
46
47 (* Options *)
48
49 type inj_flags = {
50 keep_proof_equalities : bool;
51 injection_pattern_l2r_order : bool;
52 }
53
54 open Goptions
55
56 let use_injection_pattern_l2r_order = function
57 | None -> true
58 | Some flags -> flags.injection_pattern_l2r_order
59
60 let { Goptions.get = injection_in_context_flag } =
61 declare_bool_option_and_ref
62 ~key:["Structural";"Injection"]
63 ~value:false
64 ()
65
66 (* Rewriting tactics *)
67
68 type dep_proof_flag = bool (* true = support rewriting dependent proofs *)
69 type freeze_evars_flag = bool (* true = don't instantiate existing evars *)
70
71 type orientation = bool
72
73 type conditions =
74 | Naive (* Only try the first occurrence of the lemma (default) *)
75 | FirstSolved (* Use the first match whose side-conditions are solved *)
76 | AllMatches (* Rewrite all matches whose side-conditions are solved *)
77
78 (* Warning : rewriting from left to right only works
79 if there exists in the context a theorem named <eqname>_<suffsort>_r
80 with type (A:<sort>)(x:A)(P:A->Prop)(P x)->(y:A)(eqname A y x)->(P y).
81 If another equality myeq is introduced, then corresponding theorems
82 myeq_ind_r, myeq_rec_r and myeq_rect_r have to be proven. See below.
83 -- Eduardo (19/8/97)
84 *)
85
86 let rewrite_core_unif_flags = {
87 modulo_conv_on_closed_terms = None;
88 use_metas_eagerly_in_conv_on_closed_terms = true;
89 use_evars_eagerly_in_conv_on_closed_terms = false;
90 modulo_delta = TransparentState.empty;
91 modulo_delta_types = TransparentState.empty;
92 check_applied_meta_types = true;
93 use_pattern_unification = true;
94 use_meta_bound_pattern_unification = true;
95 allowed_evars = Evarsolve.AllowedEvars.all;
96 restrict_conv_on_strict_subterms = false;
97 modulo_betaiota = false;
98 modulo_eta = true;
99 }
100
101 let rewrite_unif_flags = {
102 core_unify_flags = rewrite_core_unif_flags;
103 merge_unify_flags = rewrite_core_unif_flags;
104 subterm_unify_flags = rewrite_core_unif_flags;
105 allow_K_in_toplevel_higher_order_unification = false;
106 (* allow_K does not matter in practice because calls w_typed_unify *)
107 resolve_evars = true
108 }
109
110 let freeze_initial_evars sigma flags newevars =
111 let initial = Evd.undefined_map sigma in
112 let allowed evk =
113 if Evar.Map.mem evk initial then false
114 else Evar.Set.mem evk (Lazy.force newevars)
115 in
116 let allowed_evars = Evarsolve.AllowedEvars.from_pred allowed in
117 {flags with
118 core_unify_flags = {flags.core_unify_flags with allowed_evars};
119 merge_unify_flags = {flags.merge_unify_flags with allowed_evars};
120 subterm_unify_flags = {flags.subterm_unify_flags with allowed_evars}}
121
122 let make_flags frzevars sigma flags newevars =
123 if frzevars then freeze_initial_evars sigma flags newevars else flags
124
125 let side_tac tac sidetac =
126 match sidetac with
127 | None -> tac
128 | Some sidetac -> tclTHENSFIRSTn tac [|Proofview.tclUNIT ()|] sidetac
129
130 let instantiate_lemma_all env flags eqclause l2r concl =
131 let (_, args) = decompose_app (Clenv.clenv_evd eqclause) (Clenv.clenv_type eqclause) in
132 let arglen = Array.length args in
133 let () = if arglen < 2 then user_err Pp.(str "The term provided is not an applied relation.") in
134 let c1 = args.(arglen - 2) in
135 let c2 = args.(arglen - 1) in
136 let metas = Clenv.clenv_meta_list eqclause in
137 w_unify_to_subterm_all ~metas ~flags env (Clenv.clenv_evd eqclause)
138 ((if l2r then c1 else c2),concl)
139
140 let rewrite_conv_closed_core_unif_flags = {
141 modulo_conv_on_closed_terms = Some TransparentState.full;
142 (* We have this flag for historical reasons, it has e.g. the consequence *)
143 (* to rewrite "?x+2" in "y+(1+1)=0" or to rewrite "?x+?x" in "2+(1+1)=0" *)
144
145 use_metas_eagerly_in_conv_on_closed_terms = true;
146 use_evars_eagerly_in_conv_on_closed_terms = false;
147 (* Combined with modulo_conv_on_closed_terms, this flag allows since 8.2 *)
148 (* to rewrite e.g. "?x+(2+?x)" in "1+(1+2)=0" *)
149
150 modulo_delta = TransparentState.empty;
151 modulo_delta_types = TransparentState.full;
152 check_applied_meta_types = true;
153 use_pattern_unification = true;
154 (* To rewrite "?n x y" in "y+x=0" when ?n is *)
155 (* a preexisting evar of the goal*)
156
157 use_meta_bound_pattern_unification = true;
158
159 allowed_evars = Evarsolve.AllowedEvars.all;
160
161 restrict_conv_on_strict_subterms = false;
162 modulo_betaiota = false;
163 modulo_eta = true;
164 }
165
166 let rewrite_conv_closed_unif_flags = {
167 core_unify_flags = rewrite_conv_closed_core_unif_flags;
168 merge_unify_flags = rewrite_conv_closed_core_unif_flags;
169 subterm_unify_flags = rewrite_conv_closed_core_unif_flags;
170 allow_K_in_toplevel_higher_order_unification = false;
171 resolve_evars = false
172 }
173
174 let rewrite_keyed_core_unif_flags = {
175 modulo_conv_on_closed_terms = Some TransparentState.full;
176 (* We have this flag for historical reasons, it has e.g. the consequence *)
177 (* to rewrite "?x+2" in "y+(1+1)=0" or to rewrite "?x+?x" in "2+(1+1)=0" *)
178
179 use_metas_eagerly_in_conv_on_closed_terms = true;
180 use_evars_eagerly_in_conv_on_closed_terms = false;
181 (* Combined with modulo_conv_on_closed_terms, this flag allows since 8.2 *)
182 (* to rewrite e.g. "?x+(2+?x)" in "1+(1+2)=0" *)
183
184 modulo_delta = TransparentState.full;
185 modulo_delta_types = TransparentState.full;
186 check_applied_meta_types = true;
187 use_pattern_unification = true;
188 (* To rewrite "?n x y" in "y+x=0" when ?n is *)
189 (* a preexisting evar of the goal*)
190
191 use_meta_bound_pattern_unification = true;
192
193 allowed_evars = Evarsolve.AllowedEvars.all;
194
195 restrict_conv_on_strict_subterms = false;
196 modulo_betaiota = true;
197
198 modulo_eta = true;
199 }
200
201 let rewrite_keyed_unif_flags = {
202 core_unify_flags = rewrite_keyed_core_unif_flags;
203 merge_unify_flags = rewrite_keyed_core_unif_flags;
204 subterm_unify_flags = rewrite_keyed_core_unif_flags;
205 allow_K_in_toplevel_higher_order_unification = false;
206 resolve_evars = false
207 }
208
209 let rewrite_db = "rewrite_instances"
210
211 let tclNOTSAMEGOAL tac =
212 let goal gl = Proofview.Goal.goal gl in
213 Proofview.Goal.enter begin fun gl ->
214 let sigma = Proofview.Goal.sigma gl in
215 let ev = goal gl in
216 tac >>= fun () ->
217 Proofview.Goal.goals >>= fun gls ->
218 let check accu gl' =
219 gl' >>= fun gl' ->
220 let accu = accu || Proofview.Progress.goal_equal
221 ~evd:sigma ~extended_evd:(Proofview.Goal.sigma gl') ev (goal gl')
222 in
223 Proofview.tclUNIT accu
224 in
225 Proofview.Monad.List.fold_left check false gls >>= fun has_same ->
226 if has_same then
227 tclZEROMSG (str"Tactic generated a subgoal identical to the original goal.")
228 else
229 Proofview.tclUNIT ()
230 end
231
232 let elim_wrapper cls rwtac =
233 let open Pretype_errors in
234 Proofview.tclORELSE
235 begin match cls with
236 | None ->
237 (* was tclWEAK_PROGRESS which only fails for tactics generating one
238 subgoal and did not fail for useless conditional rewritings generating
239 an extra condition *)
240 tclNOTSAMEGOAL rwtac
241 | Some _ -> rwtac
242 end
243 begin function (e, info) -> match e with
244 | PretypeError (env, evd, NoOccurrenceFound (c', _)) ->
245 Proofview.tclZERO ~info (PretypeError (env, evd, NoOccurrenceFound (c', cls)))
246 | e ->
247 Proofview.tclZERO ~info e
248 end
249
250 let general_elim_clause with_evars frzevars tac cls c (ctx, eqn, args) l l2r elim indargs =
251 (* Ad hoc asymmetric general_elim_clause *)
252 let general_elim_clause0 rew =
253 let rewrite_elim =
254 Proofview.Goal.enter begin fun gl ->
255 let sigma = Proofview.Goal.sigma gl in
256 let flags = if Unification.is_keyed_unification ()
257 then rewrite_keyed_unif_flags else rewrite_conv_closed_unif_flags in
258 (* We take evars of the type: this may include old evars! For excluding *)
259 (* all old evars, including the ones occurring in the rewriting lemma, *)
260 (* we would have to take the clenv_value *)
261 let newevars = lazy (Evarutil.undefined_evars_of_term sigma (Clenv.clenv_type rew)) in
262 let flags = make_flags frzevars sigma flags newevars in
263 let metas = Clenv.clenv_meta_list rew in
264 let submetas = (Clenv.clenv_arguments rew, metas) in
265 general_elim_clause with_evars flags cls (submetas, c, Clenv.clenv_type rew) elim indargs
266 end
267 in
268 Proofview.Unsafe.tclEVARS (Clenv.clenv_evd rew) <*>
269 elim_wrapper cls rewrite_elim
270 in
271 let strat, tac =
272 match tac with
273 | None -> Naive, None
274 | Some (tac, Naive) -> Naive, Some tac
275 | Some (tac, FirstSolved) -> FirstSolved, Some (tclCOMPLETE tac)
276 | Some (tac, AllMatches) -> AllMatches, Some (tclCOMPLETE tac)
277 in
278 Proofview.Goal.enter begin fun gl ->
279 let env = Proofview.Goal.env gl in
280 let sigma = Proofview.Goal.sigma gl in
281 let concl = Proofview.Goal.concl gl in
282 let typ = match cls with
283 | None -> concl
284 | Some id -> Tacmach.pf_get_hyp_typ id gl
285 in
286 let ty = it_mkProd_or_LetIn (applist (eqn, args)) ctx in
287 let eqclause = Clenv.make_clenv_binding env sigma (c, ty) l in
288 let try_clause (metas, evd') =
289 let clenv = Clenv.update_clenv_evd eqclause evd' metas in
290 let clenv = Clenv.clenv_pose_dependent_evars ~with_evars:true clenv in
291 side_tac (general_elim_clause0 clenv) tac
292 in
293 match strat with
294 | Naive ->
295 side_tac (general_elim_clause0 eqclause) tac
296 | FirstSolved ->
297 let flags = make_flags frzevars sigma rewrite_unif_flags (lazy Evar.Set.empty) in
298 let cs = instantiate_lemma_all env flags eqclause l2r typ in
299 tclFIRST (List.map try_clause cs)
300 | AllMatches ->
301 let flags = make_flags frzevars sigma rewrite_unif_flags (lazy Evar.Set.empty) in
302 let cs = instantiate_lemma_all env flags eqclause l2r typ in
303 tclMAP (fun x -> tclTRY (try_clause x)) cs
304 end
305
306 (* The next function decides in particular whether to try a regular
307 rewrite or a generalized rewrite.
308 Approach is to break everything, if [eq] appears in head position
309 then regular rewrite else try general rewrite.
310 If occurrences are set, use general rewrite.
311 *)
312
313 let (forward_general_setoid_rewrite_clause, general_setoid_rewrite_clause) = Hook.make ()
314
315 (* scheme_name returns the generic elimination principle to be used, dependending on dep(endency), in conclusion or not and left-to-right *)
316 let scheme_name dep lft2rgt inccl =
317 match dep, lft2rgt, inccl with
318 (* Non dependent case *)
319 | false, Some true, true -> rew_l2r_scheme_kind
320 | false, Some true, false -> rew_r2l_scheme_kind
321 | false, _, false -> rew_l2r_scheme_kind
322 | false, _, true -> rew_r2l_scheme_kind
323 (* Dependent case *)
324 | true, Some true, true -> rew_l2r_dep_scheme_kind
325 | true, Some true, false -> rew_l2r_forward_dep_scheme_kind
326 | true, _, true -> rew_r2l_dep_scheme_kind
327 | true, _, false -> rew_r2l_forward_dep_scheme_kind
328
329 let lib_ref_opt_pos name pos =
330 match Rocqlib.lib_ref_opt name with
331 | None -> None
332 | Some x -> Some (x , pos)
333
334 (* eq_scheme_name returns the elimination principle to be used, dependending on dep(endency), in conclusion or not and left-to-right *)
335 (* this could be handled by has_J_ref as well, but is more efficient has it bypasses the typeclass search *)
336 let eq_scheme_pattern dep lft2rgt inccl target is_set = let open Sorts.Quality in
337 match dep, lft2rgt, inccl, target , is_set with
338 (* Non dependent case *)
339 | false, Some true, true , QConstant QType , false -> Some ("rect_r")
340 | false, Some true, true , QConstant QType , true -> Some ("rec_r")
341 | false, Some true, true , QConstant QProp , _ -> Some ("ind_r")
342 | false, Some true, true , QConstant QSProp , _ -> Some ("sind_r")
343 | false, Some true, false , QConstant QType , false -> Some ("rect")
344 | false, Some true, false , QConstant QType , true -> Some ("rec")
345 | false, Some true, false , QConstant QProp , _ -> Some ("ind")
346 | false, Some true, false , QConstant QSProp , _ -> Some ("sind")
347 | false, _ , false , QConstant QType , false -> Some ("rect_r")
348 | false, _ , false , QConstant QType , true -> Some ("rec_r")
349 | false, _ , false , QConstant QProp , _ -> Some ("ind_r")
350 | false, _ , false , QConstant QSProp , _ -> Some ("sind_r")
351 | false, _ , true , QConstant QProp , _ -> Some ("ind")
352 | false, _ , true , QConstant QSProp , _ -> Some ("sind")
353 | false, _ , true , QConstant QType , false -> Some ("rect")
354 | false, _ , true , QConstant QType , true -> Some ("rec")
355 (* Dependent case *)
356 | true, Some true, true , QConstant QType , _ -> Some ("rect_r_dep")
357 | true, Some true, true , QConstant QProp , _ -> Some ("ind_r_dep")
358 | true, _ , true , QConstant QType , _ -> Some ("rect_dep")
359 | true, _ , true , QConstant QProp , _ -> Some ("ind_dep")
360 | _ , _, _ , _ , _ -> None
361
362 let eq_scheme_name name dep lft2rgt inccl target is_set =
363 Option.bind (eq_scheme_pattern dep lft2rgt inccl target is_set)
364 (fun recursor -> lib_ref_opt_pos ("core." ^ name ^ "." ^ recursor) (AtPosition 5))
365
366 (* has_J_ref returns the name of the class to be used, dependending on dep(endency), in conclusion or not and left-to-right *)
367 (* The integer encodes the position of the equality argument in the elimination principle, starting from 0 *)
368 let has_J_ref dep lft2rgt inccl =
369 match dep, lft2rgt, inccl with
370 (* Non dependent case *)
371 | false, Some true, true -> Rocqlib.lib_ref "core.Has_Leibniz_r" , AtPosition 5
372 | false, Some true, false -> Rocqlib.lib_ref "core.Has_Leibniz" , AtPosition 5
373 | false, _, false -> Rocqlib.lib_ref "core.Has_Leibniz_r" , AtPosition 5
374 | false, _, true -> Rocqlib.lib_ref "core.Has_Leibniz" , AtPosition 5
375 (* Dependent case *)
376 | true, Some true, true -> Rocqlib.lib_ref "core.Has_J_r" , AtPosition 5
377 | true, Some true, false -> Rocqlib.lib_ref "core.Has_J_r_forward" , AtPosition 4
378 | true, _, true -> Rocqlib.lib_ref "core.Has_J" , AtPosition 5
379 | true, _, false -> Rocqlib.lib_ref "core.Has_J_forward" , AtPosition 4
380
381 let level_init l sigma =
382 let rec aux l sigma =
383 match l with
384 | [] -> sigma , []
385 | levels :: ls ->
386 let sigma , new_level = Evd.new_univ_level_variable UState.univ_flexible sigma in
387 let sigma , r = aux ls sigma in
388 sigma , new_level :: r
389 in aux l sigma
390
391 let lookup_eq_eliminator env sigma eq het_eq ~dep ~inccl ~l2r ~e_sort ~c_sort ~p_sort =
392 let has_elim_ref , indarg = has_J_ref dep l2r inccl in
393 let has_refl_ref = Rocqlib.lib_ref "core.Has_refl" in
394 let c_quality = ESorts.quality sigma c_sort in
395 let e_quality = ESorts.quality sigma e_sort in
396 let p_quality = ESorts.quality sigma p_sort in
397 let qs = [ c_quality; e_quality; p_quality ] in
398 let c_level = Sorts.univ_of_sort (ESorts.kind sigma c_sort) in
399 let e_level = Sorts.univ_of_sort (ESorts.kind sigma e_sort) in
400 let p_level = Sorts.univ_of_sort (ESorts.kind sigma p_sort) in
401 let sigma , univs = level_init [ c_level; e_level; p_level ] sigma in
402 let names = EInstance.make @@ UVars.Instance.of_array (Array.of_list qs, Array.of_list univs) in
403 (* eta-expansion for equality fun A => eq A *)
404 let eta_expand name typ f =
405 let body = EConstr.mkApp (Vars.lift 1 f , [| mkRel 1 |] ) in
406 EConstr.mkLambda (EConstr.nameR name, typ , body) in
407 (* Special eta-expansion for heterogeneous equality fun A x => JMeq A x A *)
408 let eta_expand_het_eq name namevar typ f =
409 let body = EConstr.mkApp (Vars.lift 2 f , [| mkRel 2 |] ) in
410 let body = EConstr.mkApp (body , [| mkRel 1 |] ) in
411 let body = EConstr.mkApp (body , [| mkRel 2 |] ) in
412 let body = EConstr.mkLambda (EConstr.nameR namevar, mkRel 1 , body) in
413 EConstr.mkLambda (EConstr.nameR name, typ , body) in
414 (* This patch is to handle template poly equality with carrier in Prop, because of cumulatitivty of Prop into Type *)
415 let c_type = EConstr.mkSort (ESorts.make (Sorts.make c_quality (Univ.Universe.make (List.hd univs)))) in
416 let eq = if het_eq
417 then eta_expand_het_eq (Id.of_string "A") (Id.of_string "x") c_type eq
418 else eta_expand (Id.of_string "A") c_type eq in
419 let sigma , has_J_class = Evd.fresh_global ~names env sigma has_elim_ref in
420 if dep then
421 let has_refl_names =
422 EInstance.make @@ UVars.Instance.of_array (Array.of_list (List.firstn 2 qs), Array.of_list (List.firstn 2 univs)) in
423 let sigma , has_refl_class = Evd.fresh_global ~names:has_refl_names env sigma has_refl_ref in
424 let sigma , apprefl = Typing.checked_appvect env sigma has_refl_class [| eq |] in
425 let sigma , has_refl = Evarutil.new_evar ~typeclass_candidate:true env sigma apprefl in
426 let sigma , app = Typing.checked_appvect env sigma has_J_class [| eq; has_refl |] in
427 (sigma, (app, indarg))
428 else
429 let sigma , app = Typing.checked_appvect env sigma has_J_class [| eq |] in
430 (sigma , (app, indarg))
431
432 let lookup_eq_eliminator_tc env sigma eq het_eq ~dep ~inccl ~l2r ~c_sort ~e_sort ~p_sort =
433 let sigma, (query,indarg) = lookup_eq_eliminator env sigma eq het_eq
434 ~dep ~inccl ~l2r ~c_sort ~e_sort ~p_sort in
435 let db = Hints.searchtable_map rewrite_db in
436 let (sigma , c) = Class_tactics.resolve_one_typeclass ~db env sigma query in
437 let hd , _ = EConstr.decompose_app sigma c in
438 let c_name , _ = Constr.destConst (EConstr.to_constr sigma hd) in
439 let c = Reductionops.whd_const c_name env sigma c in
440 (sigma , c), indarg
441
442 let which_equality_opt env sigma c =
443 let find_eq env sigma c name = match Rocqlib.lib_ref_opt ("core."^name^".type") with
444 | Some gr -> if isRefX env sigma gr c then Some name else None
445 | None -> None in
446 Option.List.flatten @@ List.map (find_eq env sigma c) ["eq";"identity"]
447
448 let lookup_eq_eliminator_with_error ?(het_eq=false) env sigma eq ~dep ~inccl ~l2r ~c_sort ~e_sort ~p_sort =
449 let which_eq = which_equality_opt env sigma eq in
450 let eq_scheme = Option.List.flatten @@ List.map (fun name -> eq_scheme_name name dep l2r inccl (ESorts.quality sigma p_sort) (ESorts.is_set sigma p_sort)) which_eq in
451 match eq_scheme with
452 | (r , indarg) :: _ ->
453 let elim = destConstRef r in
454 let (sigma, (c,u)) = Evd.fresh_constant_instance env sigma elim in
455 (sigma , mkConstU (c,u)), indarg
456 | _ ->
457 try
458 lookup_eq_eliminator_tc env sigma eq het_eq ~dep ~inccl ~l2r ~c_sort ~e_sort ~p_sort
459 with Not_found -> user_err Pp.(
460 str "Eliminator not found for query for equality carrier: " ++ Sorts.raw_pr (ESorts.kind sigma e_sort) ++
461 str " carrier quality: " ++ Sorts.raw_pr (ESorts.kind sigma c_sort) ++
462 str " target quality: " ++ Sorts.raw_pr (ESorts.kind sigma p_sort))
463
464 let lookup_eq_eliminator_opt env sigma eq ~dep het_eq ~inccl l2r ~c_sort ~e_sort ~p_sort =
465 try Some (lookup_eq_eliminator_with_error ~het_eq env sigma eq ~dep ~inccl ~l2r ~e_sort ~c_sort ~p_sort)
466 with _ -> None
467
468 type eq_scheme_kind = Minimality of UnivGen.QualityOrSet.t | Rewriting | Equality
469
470 let warn_missing_scheme = CWarnings.create ~name:"missing-scheme" ~category:Deprecation.Version.v9_2
471 Pp.(fun (kind,name,ind) ->
472 let ind = Nametab.pr_global_env Id.Set.empty (IndRef ind) in
473 let cmd () = match kind with
474 | Minimality s ->
475 fmt "Scheme Minimality for %t Sort %t"
476 (const ind) (fun () -> UnivGen.QualityOrSet.raw_pr s)
477 | Rewriting -> fmt "Scheme Rewriting for %t" (const ind)
478 | Equality -> fmt "Scheme Equality for %t" (const ind)
479 in
480 hv 0 @@ fmt "Autogenerated \"%s\" scheme for %t.@ Use \"%t\" to explicitly generate it.@ This will become an error in the future."
481 name (const ind) cmd)
482
483 (* find_elim determines which elimination principle is necessary to
484 eliminate lbeq on sort_of_gl. *)
485 let find_scheme kind scheme_name ind =
486 find_scheme scheme_name ind >>= function
487 | Some s -> Proofview.tclUNIT s
488 | None ->
489 match warn_missing_scheme (kind, Ind_tables.scheme_kind_name scheme_name, ind) with
490 | () -> force_find_scheme scheme_name ind
491 | exception e when CErrors.noncritical e ->
492 let e, info = Exninfo.capture e in
493 Proofview.tclZERO ~info e
494
495 let find_elim lft2rgt dep inccl type_of_cls (ctx, hdcncl, args) =
496 Proofview.Goal.enter_one begin fun gl ->
497 let env = Proofview.Goal.env gl in
498 let sigma = Proofview.Goal.sigma gl in
499 let gen_elim () =
500 match EConstr.kind sigma hdcncl with
501 | Ind (ind,u) ->
502 find_scheme Rewriting (scheme_name dep lft2rgt inccl) ind >>= fun elim ->
503 Proofview.tclEVARMAP >>= fun sigma ->
504 let (sigma, gref) = Evd.fresh_global env sigma elim in
505 Proofview.Unsafe.tclEVARS sigma <*> Proofview.tclUNIT (gref, UnknownPosition)
506 | _ -> assert false
507 in
508 let nb_args = List.length args in
509 let maybe_eq = nb_args == 3 in
510 let maybe_het_eq = nb_args == 4 in
511 if maybe_eq || maybe_het_eq
512 then
513 let env' = EConstr.push_rel_context ctx env in
514 let args = Array.of_list args in
515 let e_sort = Retyping.get_sort_of env' sigma (mkApp (hdcncl, args)) in
516 let c_sort = Retyping.get_sort_of env' sigma args.(0) in
517 let p_sort = Retyping.get_sort_of env sigma type_of_cls in
518 match lookup_eq_eliminator_opt env sigma hdcncl maybe_het_eq ~dep ~inccl lft2rgt ~c_sort ~e_sort ~p_sort with
519 | Some ((sigma, c),indarg) ->
520 Proofview.Unsafe.tclEVARS sigma <*> Proofview.tclUNIT (c,indarg)
521 | None -> gen_elim ()
522 else
523 gen_elim ()
524 end
525
526 let leibniz_rewrite_ebindings_clause cls lft2rgt tac c ((_, hdcncl, _) as t) l with_evars frzevars dep_proof_ok =
527 Proofview.Goal.enter begin fun gl ->
528 let evd = Proofview.Goal.sigma gl in
529 let type_of_cls = match cls with
530 | None -> Proofview.Goal.concl gl
531 | Some id -> Tacmach.pf_get_hyp_typ id gl in
532 let dep = dep_proof_ok && dependent_no_evar evd c type_of_cls in
533 let inccl = Option.is_empty cls in
534 find_elim lft2rgt dep inccl type_of_cls t >>= fun (elim, indarg) ->
535 general_elim_clause with_evars frzevars tac cls c t l
536 (match lft2rgt with None -> false | Some b -> b) elim indarg
537 end
538
539 let adjust_rewriting_direction args lft2rgt =
540 match args with
541 | [_] ->
542 (* equality to a constant, like in eq_true *)
543 (* more natural to see -> as the rewriting to the constant *)
544 if not lft2rgt then
545 user_err Pp.(str "Rewriting non-symmetric equality not allowed from right-to-left.");
546 None
547 | _ ->
548 (* other equality *)
549 Some lft2rgt
550
551 let rewrite_side_tac tac sidetac = side_tac tac (Option.map fst sidetac)
552
553 (* Main function for dispatching which kind of rewriting it is about *)
554
555 let general_rewrite ~where:cls ~l2r:lft2rgt occs ~freeze:frzevars ~dep:dep_proof_ok ~with_evars ?tac
556 ((c,l) : constr with_bindings) =
557 if not (Locusops.is_all_occurrences occs) then (
558 rewrite_side_tac (Hook.get forward_general_setoid_rewrite_clause cls lft2rgt occs (c,l) ~new_goals:[]) tac)
559 else
560 Proofview.Goal.enter begin fun gl ->
561 let sigma = Proofview.Goal.sigma gl in
562 let env = Proofview.Goal.env gl in
563 let ctype = get_type_of env sigma c in
564 let rels, t = decompose_prod_decls sigma (whd_betaiotazeta env sigma ctype) in
565 match match_with_equality_type env sigma t with
566 | Some (hdcncl,args) -> (* Fast path: direct leibniz-like rewrite *)
567 let lft2rgt = adjust_rewriting_direction args lft2rgt in
568 leibniz_rewrite_ebindings_clause cls lft2rgt tac c (rels, hdcncl, args)
569 l with_evars frzevars dep_proof_ok
570 | None ->
571 Proofview.tclORELSE
572 begin
573 rewrite_side_tac (Hook.get forward_general_setoid_rewrite_clause cls
574 lft2rgt occs (c,l) ~new_goals:[]) tac
575 end
576 begin function
577 | (e, info) ->
578 Proofview.tclEVARMAP >>= fun sigma ->
579 let env' = push_rel_context rels env in
580 let rels',t' = whd_decompose_prod_decls env' sigma t in (* Search for underlying eq *)
581 match match_with_equality_type env' sigma t' with
582 | Some (hdcncl,args) ->
583 let lft2rgt = adjust_rewriting_direction args lft2rgt in
584 leibniz_rewrite_ebindings_clause cls lft2rgt tac c
585 (rels' @ rels, hdcncl, args) l with_evars frzevars dep_proof_ok
586 | None -> Proofview.tclZERO ~info e
587 (* error "The provided term does not end with an equality or a declared rewrite relation." *)
588 end
589 end
590
591 let clear_for_rewrite_in_hyps ids c =
592 let ids = Id.Set.of_list ids in
593 Proofview.Goal.enter begin fun gl ->
594 let env = Proofview.Goal.env gl in
595 let sigma = Proofview.Goal.sigma gl in
596 (* Is this the right err? *)
597 let err = (Evarutil.OccurHypInSimpleClause None) in
598 let sigma =
599 try Evarutil.check_and_clear_in_constr env sigma err ids c
600 with Evarutil.ClearDependencyError (id,err,inglobal) ->
601 CErrors.user_err Pp.(str "Cannot rewrite due to dependency on " ++ Id.print id ++ str ".")
602 in
603 Proofview.Unsafe.tclEVARS sigma
604 end
605
606 let general_rewrite_clause l2r with_evars ?tac c cl =
607 let occs_of = occurrences_map (List.fold_left
608 (fun acc ->
609 function ArgArg x -> x :: acc | ArgVar _ -> acc)
610 [])
611 in
612 match cl.onhyps with
613 | Some l ->
614 (* If a precise list of locations is given, success is mandatory for
615 each of these locations. *)
616 let rec do_hyps = function
617 | [] -> Proofview.tclUNIT ()
618 | ((occs,id),_) :: l ->
619 tclTHENFIRST
620 (general_rewrite ~where:(Some id) ~l2r (occs_of occs) ~freeze:false ~dep:true ~with_evars ?tac c)
621 (do_hyps l)
622 in
623 let tac =
624 if cl.concl_occs == NoOccurrences then do_hyps l
625 else
626 tclTHENFIRST
627 (general_rewrite ~where:None ~l2r (occs_of cl.concl_occs) ~freeze:false ~dep:true ~with_evars ?tac c)
628 (do_hyps l)
629 in
630 begin match l with
631 | [] | [_] ->
632 (* don't clear when rewriting in 1 hyp *)
633 tac
634 | _ ->
635 tclTHEN (clear_for_rewrite_in_hyps (List.map (fun ((_,id),_) -> id) l) (fst c)) tac
636 end
637 | None ->
638 (* Otherwise, if we are told to rewrite in all hypothesis via the
639 syntax "* |-", we fail iff all the different rewrites fail *)
640 let rec do_hyps_atleastonce = function
641 | [] -> tclZEROMSG (Pp.str"Nothing to rewrite.")
642 | id :: l ->
643 tclIFTHENFIRSTTRYELSEMUST
644 (tclTHEN (clear_for_rewrite_in_hyps [id] (fst c))
645 (general_rewrite ~where:(Some id) ~l2r AllOccurrences ~freeze:false ~dep:true ~with_evars ?tac c))
646 (do_hyps_atleastonce l)
647 in
648 let do_hyps =
649 Proofview.Goal.enter begin fun gl ->
650 do_hyps_atleastonce (Tacmach.pf_ids_of_hyps gl)
651 end
652 in
653 if cl.concl_occs == NoOccurrences then do_hyps else
654 tclIFTHENFIRSTTRYELSEMUST
655 (general_rewrite ~where:None ~l2r (occs_of cl.concl_occs) ~freeze:false ~dep:true ~with_evars ?tac c)
656 do_hyps
657
658 let apply_special_clear_request clear_flag f =
659 Proofview.Goal.enter begin fun gl ->
660 let sigma = Proofview.Goal.sigma gl in
661 let env = Proofview.Goal.env gl in
662 try
663 let (sigma, (c, bl)) = f env sigma in
664 let c = try Some (destVar sigma c) with DestKO -> None in
665 apply_clear_request clear_flag (use_clear_hyp_by_default ()) c
666 with
667 e when noncritical e -> tclIDTAC
668 end
669
670 type multi =
671 | Precisely of int
672 | UpTo of int
673 | RepeatStar
674 | RepeatPlus
675
676 let general_multi_rewrite with_evars l cl tac =
677 let do1 l2r f =
678 Proofview.Goal.enter begin fun gl ->
679 let sigma = Proofview.Goal.sigma gl in
680 let env = Proofview.Goal.env gl in
681 let (sigma, c) = f env sigma in
682 tclWITHHOLES with_evars
683 (general_rewrite_clause l2r with_evars ?tac c cl) sigma
684 end
685 in
686 let rec doN l2r c = function
687 | Precisely n when n <= 0 -> Proofview.tclUNIT ()
688 | Precisely 1 -> do1 l2r c
689 | Precisely n -> tclTHENFIRST (do1 l2r c) (doN l2r c (Precisely (n-1)))
690 | RepeatStar -> tclREPEAT_MAIN (do1 l2r c)
691 | RepeatPlus -> tclTHENFIRST (do1 l2r c) (doN l2r c RepeatStar)
692 | UpTo n when n<=0 -> Proofview.tclUNIT ()
693 | UpTo n -> tclTHENFIRST (tclTRY (do1 l2r c)) (doN l2r c (UpTo (n-1)))
694 in
695 let rec loop = function
696 | [] -> Proofview.tclUNIT ()
697 | (l2r,m,clear_flag,c)::l ->
698 tclTHENFIRST
699 (tclTHEN (doN l2r c m) (apply_special_clear_request clear_flag c)) (loop l)
700 in loop l
701
702 let rewriteLR c =
703 general_rewrite ~where:None ~l2r:true AllOccurrences ~freeze:true ~dep:true ~with_evars:false (c, NoBindings)
704 let rewriteRL c =
705 general_rewrite ~where:None ~l2r:false AllOccurrences ~freeze:true ~dep:true ~with_evars:false (c, NoBindings)
706
707 (* Replacing tactics *)
708
709 let classes_dirpath =
710 DirPath.make (List.map Id.of_string ["Classes";"Corelib"])
711
712 let init_setoid () =
713 if is_dirpath_prefix_of classes_dirpath (Libnames.dirpath_of_path @@ Lib.cwd ()) then ()
714 else check_required_library ["Corelib";"Setoids";"Setoid"]
715
716 let check_setoid cl =
717 let concloccs = Locusops.occurrences_map (fun x -> x) cl.concl_occs in
718 Option.fold_left
719 (List.fold_left
720 (fun b ((occ,_),_) ->
721 b||(not (Locusops.is_all_occurrences (Locusops.occurrences_map (fun x -> x) occ)))
722 )
723 )
724 (not (Locusops.is_all_occurrences concloccs) &&
725 (concloccs <> NoOccurrences))
726 cl.onhyps
727
728 let replace_core clause l2r eq =
729 if check_setoid clause
730 then init_setoid ();
731 tclTHENFIRST
732 (assert_after Anonymous eq)
733 (onLastHypId (fun id ->
734 tclTHEN
735 (tclTRY (general_rewrite_clause l2r false (mkVar id,NoBindings) clause))
736 (clear [id])))
737
738 (* eq,sym_eq : equality on Type and its symmetry theorem
739 c1 c2 : c1 is to be replaced by c2
740 unsafe : If true, do not check that c1 and c2 are convertible
741 tac : Used to prove the equality c1 = c2
742 gl : goal *)
743
744 let replace_using_leibniz clause c1 c2 l2r unsafe try_prove_eq_opt =
745 Proofview.Goal.enter begin fun gl ->
746 let env = Proofview.Goal.env gl in
747 let sigma = Proofview.Goal.sigma gl in
748 let t1 = get_type_of env sigma c1 in
749 let t2 = get_type_of env sigma c2 in
750 let evd =
751 if unsafe then Some sigma
752 else
753 try Some (Evarconv.unify_delay env sigma t1 t2)
754 with Evarconv.UnableToUnify _ -> None
755 in
756 match evd with
757 | None ->
758 tclFAIL (str"Terms do not have convertible types")
759 | Some evd ->
760 let e,sym =
761 try lib_ref "core.eq.type", lib_ref "core.eq.sym"
762 with NotFoundRef _ ->
763 try lib_ref "core.identity.type", lib_ref "core.identity.sym"
764 with NotFoundRef _ ->
765 user_err (strbrk "Need a registration for either core.eq.type and core.eq.sym or core.identity.type and core.identity.sym.") in
766 Proofview.Unsafe.tclEVARS evd >>= fun () ->
767 Tacticals.pf_constr_of_global sym >>= fun sym ->
768 Tacticals.pf_constr_of_global e >>= fun e ->
769 let eq = applist (e, [t1;c1;c2]) in
770 let solve_tac = match try_prove_eq_opt with
771 | None ->
772 tclFIRST
773 [ assumption;
774 tclTHEN (apply sym) assumption;
775 Proofview.tclUNIT () ]
776 | Some tac -> tclCOMPLETE tac
777 in
778 tclTHENLAST
779 (replace_core clause l2r eq)
780 solve_tac
781 end
782
783 let replace c1 c2 =
784 replace_using_leibniz onConcl c2 c1 false false None
785
786 let replace_by c1 c2 tac =
787 replace_using_leibniz onConcl c2 c1 false false (Some tac)
788
789 let replace_in_clause_maybe_by dir_opt c1 c2 cl tac_opt =
790 let c1, c2, dir = match dir_opt with
791 | None | Some false -> c1, c2, false
792 | Some true -> c2, c1, true
793 in
794 replace_using_leibniz cl c2 c1 dir false tac_opt
795
796 (* End of Eduardo's code. The rest of this file could be improved
797 using the functions match_with_equation, etc that I defined
798 in Pattern.ml.
799 -- Eduardo (19/8/97)
800 *)
801
802 (* Tactics for equality reasoning with the "eq" relation. This code
803 will work with any equivalence relation which is substitutive *)
804
805 (* [find_positions t1 t2]
806
807 will find the positions in the two terms which are suitable for
808 discrimination, or for injection. Obviously, if there is a
809 position which is suitable for discrimination, then we want to
810 exploit it, and not bother with injection. So when we find a
811 position which is suitable for discrimination, we will just raise
812 an exception with that position.
813
814 So the algorithm goes like this:
815
816 if [t1] and [t2] start with the same constructor, then we can
817 continue to try to find positions in the arguments of [t1] and
818 [t2].
819
820 if [t1] and [t2] do not start with the same constructor, then we
821 have found a discrimination position
822
823 if one [t1] or [t2] do not start with a constructor and the two
824 terms are not already convertible, then we have found an injection
825 position.
826
827 A discriminating position consists of a constructor-path and a pair
828 of operators. The constructor-path tells us how to get down to the
829 place where the two operators, which must differ, can be found.
830
831 An injecting position has two terms instead of the two operators,
832 since these terms are different, but not manifestly so.
833
834 A constructor-path is a list of pairs of (operator * int), where
835 the int (based at 0) tells us which argument of the operator we
836 descended into.
837
838 *)
839
840 type discriminator =
841 | DConstruct of constructor * constructor
842 | DInt of Uint63.t * Uint63.t
843 | DFloat of Float64.t * Float64.t
844 | DString of Pstring.t * Pstring.t
845
846 exception DiscrFound of
847 (constructor * int) list * discriminator
848
849 let keep_proof_equalities_for_injection = ref false
850
851 let () =
852 declare_bool_option
853 { optstage = Summary.Stage.Interp;
854 optdepr = None;
855 optkey = ["Keep";"Proof";"Equalities"];
856 optread = (fun () -> !keep_proof_equalities_for_injection) ;
857 optwrite = (fun b -> keep_proof_equalities_for_injection := b) }
858
859 let keep_proof_equalities = function
860 | None -> !keep_proof_equalities_for_injection
861 | Some flags -> flags.keep_proof_equalities
862
863 module KeepEqualities =
864 struct
865 type t = inductive
866 module Set = Indset_env
867 let encode _env r = Nametab.global_inductive r
868 let subst subst obj = Mod_subst.subst_ind subst obj
869 let check_local _ _ = ()
870 let discharge (i:t) = i
871 let printer ind = Nametab.pr_global_env Id.Set.empty (GlobRef.IndRef ind)
872 let key = ["Keep"; "Equalities"]
873 let title = "Prop-valued inductive types for which injection keeps equality proofs"
874 let member_message ind b =
875 let b = if b then mt () else str "not " in
876 str "Equality proofs over " ++ (printer ind) ++
877 str " are " ++ b ++ str "kept by injection"
878 end
879
880 module KeepEqualitiesTable = Goptions.MakeRefTable(KeepEqualities)
881
882 let set_keep_equality = KeepEqualitiesTable.set
883
884 (* [keep_proofs] is relevant for types in Prop with elimination in Type *)
885 (* In particular, it is relevant for injection but not for discriminate *)
886
887 let keep_head_inductive sigma c =
888 (* Note that we do not weak-head normalize c before checking it is an
889 applied inductive, because [get_sort_of] did not use to either.
890 As a matter of fact, if it reduces to an applied template inductive
891 type but is not syntactically equal to it, it will fail to project. *)
892 let _, hd = EConstr.decompose_prod sigma c in
893 let hd, _ = EConstr.decompose_app sigma hd in
894 match EConstr.kind sigma hd with
895 | Ind (ind, _) -> KeepEqualitiesTable.active ind
896 | _ -> false
897
898 let find_positions env sigma ~keep_proofs ~no_discr ~eqsort ~goalsort t1 t2 =
899 let project env posn allowed_elim t1 t2 =
900 let ty1 = get_type_of env sigma t1 in
901 let keep =
902 if keep_head_inductive sigma ty1 then true
903 else
904 let s = get_sort_quality_of env sigma ty1 in
905 (keep_proofs || not (UnivGen.QualityOrSet.equal s UnivGen.QualityOrSet.prop)) &&
906 not (UnivGen.QualityOrSet.equal s UnivGen.QualityOrSet.sprop) &&
907 allowed_elim
908 in
909 if keep then [(List.rev posn,t1,t2)] else []
910 in
911 let false_ref = destIndRef (lib_ref "core.False.type") in
912 let eqqual = Sorts.quality (ESorts.kind sigma eqsort) in
913 let goalsort = ESorts.kind sigma goalsort in
914 let false_inst = UVars.Instance.(of_array ([|eqqual|], [||])) in
915 let rec findrec posn s t1 t2 =
916 let hd1,args1 = whd_all_stack env sigma t1 in
917 let hd2,args2 = whd_all_stack env sigma t2 in
918 let ty1 = get_type_of env sigma t1 in
919 let s1 = UnivGen.QualityOrSet.quality @@ get_sort_quality_of env sigma ty1 in
920 let g = Environ.qualities env in
921 let allowed_elim_on_sort = eliminates_to g s s1 in
922 match (EConstr.kind sigma hd1, EConstr.kind sigma hd2) with
923 | Construct ((ind1,i1 as sp1),u1), Construct (sp2,_)
924 when Int.equal (List.length args1) (constructor_nallargs env sp1)
925 ->
926 let (mib,mip) as mind_specif = lookup_mind_specif env ind1 in
927 let false_mind_specif = lookup_mind_specif env false_ref in
928 let ind_allowed_elim = Inductive.is_allowed_elimination env (mind_specif, EInstance.kind sigma u1) Sorts.type1 in
929 let eq_allowed_elim = Inductive.is_allowed_elimination env (false_mind_specif, false_inst) goalsort in
930 (* both sides are fully applied constructors, so either we descend,
931 or we can discriminate here. *)
932 if Environ.QConstruct.equal env sp1 sp2 && allowed_elim_on_sort then
933 let nparams = inductive_nparams env ind1 in
934 let params1,rargs1 = List.chop nparams args1 in
935 let _,rargs2 = List.chop nparams args2 in
936 let ctxt = (get_constructor ((ind1,u1),mib,mip,params1) i1).cs_args in
937 let adjust i = CVars.adjust_rel_to_rel_context ctxt (i+1) - 1 in
938 List.flatten
939 (List.map2_i (fun i -> findrec ((sp1,adjust i)::posn) s1)
940 0 rargs1 rargs2)
941 else if (ind_allowed_elim && eq_allowed_elim && allowed_elim_on_sort) && not no_discr
942 then (* see build_discriminator *)
943 raise (DiscrFound (List.rev posn, DConstruct (sp1, sp2)))
944 else
945 (* if we cannot eliminate to Type, we cannot discriminate but we
946 may still try to project *)
947 project env posn allowed_elim_on_sort (applist (hd1,args1)) (applist (hd2,args2))
948 | Int i1, Int i2 ->
949 if Uint63.equal i1 i2 then []
950 else raise (DiscrFound (List.rev posn, DInt (i1, i2)))
951 | Float f1, Float f2 ->
952 if Float64.equal f1 f2 then []
953 else raise (DiscrFound (List.rev posn, DFloat (f1, f2)))
954 | String s1, String s2 ->
955 if Pstring.equal s1 s2 then []
956 else raise (DiscrFound (List.rev posn, DString (s1, s2)))
957 | _ ->
958 let t1_0 = applist (hd1,args1)
959 and t2_0 = applist (hd2,args2) in
960 if is_conv env sigma t1_0 t2_0 then
961 []
962 else
963 project env posn allowed_elim_on_sort t1_0 t2_0
964 in
965 try
966 let ty1 = get_type_of env sigma t1 in
967 let s = UnivGen.QualityOrSet.quality @@ get_sort_quality_of env sigma ty1 in
968 Inr (findrec [] s t1 t2)
969 with DiscrFound (path, d) ->
970 Inl (path, d)
971
972 let use_keep_proofs = function
973 | None -> !keep_proof_equalities_for_injection
974 | Some b -> b
975
976 (* Once we have found a position, we need to project down to it. If
977 we are discriminating, then we need to produce False on one of the
978 branches of the discriminator, and True on the other one. So the
979 result type of the case-expressions is always Prop.
980
981 If we are injecting, then we need to discover the result-type.
982 This can be difficult, since the type of the two terms at the
983 injection-position can be different, and we need to find a
984 dependent sigma-type which generalizes them both.
985
986 We can get an approximation to the right type to choose by:
987
988 (0) Before beginning, we reserve a patvar for the default
989 value of the match, to be used in all the bogus branches.
990
991 (1) perform the case-splits, down to the site of the injection. At
992 each step, we have a term which is the "head" of the next
993 case-split. At the point when we actually reach the end of our
994 path, the "head" is the term to return. We compute its type, and
995 then, backwards, make a sigma-type with every free debruijn
996 reference in that type. We can be finer, and first do a S(TRONG)NF
997 on the type, so that we get the fewest number of references
998 possible.
999
1000 (2) This gives us a closed type for the head, which we use for the
1001 types of all the case-splits.
1002
1003 (3) Now, we can compute the type of one of T1, T2, and then unify
1004 it with the type of the last component of the result-type, and this
1005 will give us the bindings for the other arguments of the tuple.
1006
1007 *)
1008
1009 (* The algorithm, then is to perform successive case-splits. We have
1010 the result-type of the case-split, and also the type of that
1011 result-type. We have a "direction" we want to follow, i.e. a
1012 constructor-number, and in all other "directions", we want to juse
1013 use the default-value.
1014
1015 After doing the case-split, we call the afterfun, with the updated
1016 environment, to produce the term for the desired "direction".
1017
1018 The assumption is made here that the result-type is not manifestly
1019 functional, so we can just use the length of the branch-type to
1020 know how many lambda's to stick in.
1021
1022 *)
1023
1024 (* [descend_then env sigma head dirn]
1025
1026 returns the number of products introduced, and the environment
1027 which is active, in the body of the case-branch given by [dirn],
1028 along with a continuation, which expects to be fed:
1029
1030 (1) the value of the body of the branch given by [dirn]
1031 (2) the default-value
1032
1033 (3) the type of the default-value, which must also be the type of
1034 the body of the [dirn] branch
1035
1036 the continuation then constructs the case-split.
1037 *)
1038
1039 let descend_then env sigma head dirn =
1040 let IndType (indf,_) as indt =
1041 try find_rectype env sigma (get_type_of env sigma head)
1042 with Not_found ->
1043 user_err Pp.(str "Cannot project on an inductive type derived from a dependency.")
1044 in
1045 let (ind, _),_ = (dest_ind_family indf) in
1046 let () = check_privacy env ind in
1047 let (mib,mip) = lookup_mind_specif env ind in
1048 let cstr = get_constructors env indf in
1049 let dirn_nlams = cstr.(dirn-1).cs_nargs in
1050 let dirn_env = EConstr.push_rel_context cstr.(dirn-1).cs_args env in
1051 (dirn_nlams,
1052 dirn_env,
1053 (fun sigma dirnval (dfltval,resty) ->
1054 let deparsign = make_arity_signature env sigma true indf in
1055 let p =
1056 it_mkLambda_or_LetIn (lift (mip.mind_nrealargs+1) resty) deparsign in
1057 let build_branch i =
1058 let result = if Int.equal i dirn then dirnval else dfltval in
1059 let cs_args = cstr.(i-1).cs_args in
1060 let args = name_context env sigma cs_args in
1061 it_mkLambda_or_LetIn result args in
1062 let brl =
1063 List.map build_branch
1064 (List.interval 1 (Array.length mip.mind_consnames)) in
1065 let rci = ERelevance.relevant in (* TODO relevance *)
1066 let ci = make_case_info env ind RegularStyle in
1067 Inductiveops.make_case_or_project env sigma indt ci (p, rci) head (Array.of_list brl)))
1068
1069 (* Now we need to construct the discriminator, given a discriminable
1070 position. This boils down to:
1071
1072 (1) If the position is directly beneath us, then we need to do a
1073 case-split, with result-type Prop, and stick True and False into
1074 the branches, as is convenient.
1075
1076 (2) If the position is not directly beneath us, then we need to
1077 call descend_then, to descend one step, and then recursively
1078 construct the discriminator.
1079
1080 *)
1081
1082 let build_rocq_False () = pf_constr_of_global (lib_ref "core.False.type")
1083 let build_rocq_True () = pf_constr_of_global (lib_ref "core.True.type")
1084 let build_rocq_I () = pf_constr_of_global (lib_ref "core.True.I")
1085
1086 let rec build_discriminator env sigma true_0 false_0 pos c = function
1087 | [] ->
1088 begin match pos with
1089 | DConstruct ((_, dirn), _) ->
1090 let cty = get_type_of env sigma c in
1091 make_selector env sigma ~pos:dirn ~special:true_0 ~default:(fst false_0) c cty
1092 | DInt (i, _) ->
1093 let inteq = Rocqlib.lib_ref "num.int63.eqb" in
1094 let inteq = mkRef (inteq, EInstance.empty) in (* ints ought to be monomorphic *)
1095 let c = mkApp (inteq, [|mkInt i; c|]) in
1096 let cty = get_type_of env sigma c in
1097 make_selector env sigma ~pos:1 ~special:true_0 ~default:(fst false_0) c cty
1098 | DFloat (f, _) ->
1099 let floateq = Rocqlib.lib_ref "num.float.leibniz.eqb" in
1100 let floateq = mkRef (floateq, EInstance.empty) in (* ints ought to be monomorphic *)
1101 let c = mkApp (floateq, [|mkFloat f; c|]) in
1102 let cty = get_type_of env sigma c in
1103 make_selector env sigma ~pos:1 ~special:true_0 ~default:(fst false_0) c cty
1104 | DString (s, _) ->
1105 let streq = Rocqlib.lib_ref "strings.pstring.eqb" in
1106 let streq = mkRef (streq, EInstance.empty) in (* strings ought to be monomorphic *)
1107 let c = mkApp (streq, [|mkString s; c|]) in
1108 let cty = get_type_of env sigma c in
1109 make_selector env sigma ~pos:1 ~special:true_0 ~default:(fst false_0) c cty
1110 end
1111 | ((sp,cnum),argnum)::l ->
1112 let (cnum_nlams,cnum_env,kont) = descend_then env sigma c cnum in
1113 let newc = mkRel(cnum_nlams-argnum) in
1114 let subval = build_discriminator cnum_env sigma true_0 false_0 pos newc l in
1115 kont sigma subval false_0
1116
1117
1118 (* Note: discrimination could be more clever: if some elimination is
1119 not allowed because of a large impredicative constructor in the
1120 path (see allowed_sorts in find_positions), the positions could
1121 still be discrimated by projecting first instead of putting the
1122 discrimination combinator inside the projecting combinator. Example
1123 of relevant situation:
1124
1125 Inductive t:Set := c : forall A:Set, A -> nat -> t.
1126 Goal ~ c _ 0 0 = c _ 0 1. intro. discriminate H.
1127 *)
1128
1129 let gen_absurdity id =
1130 Proofview.Goal.enter begin fun gl ->
1131 let env = Proofview.Goal.env gl in
1132 let sigma = Proofview.Goal.sigma gl in
1133 let hyp_typ = Tacmach.pf_get_hyp_typ id gl in
1134 if is_empty_type env sigma hyp_typ
1135 then
1136 simplest_elim (mkVar id)
1137 else
1138 tclZEROMSG (str "Not the negation of an equality.")
1139 end
1140
1141 (* Precondition: eq is leibniz equality
1142
1143 returns ((eq_elim t t1 P i t2), absurd_term)
1144 where P=[e:t]discriminator
1145 absurd_term=False
1146 *)
1147 let _ind_scheme_of_eq lbeq to_kind =
1148 (* use ind rather than case by compatibility *)
1149 let kind = Elimschemes.elim_scheme ~dep:false ~to_kind in
1150 find_scheme (Minimality to_kind) kind (destIndRef lbeq.eq) >>= fun c ->
1151 Proofview.tclUNIT c
1152
1153 let discrimination_pf e (eq,_,s,(t,t1,t2)) discriminator p_sort =
1154 build_rocq_I () >>= fun i ->
1155 Proofview.Goal.enter_one begin fun gl ->
1156 let env = Proofview.Goal.env gl in
1157 let sigma = Proofview.Goal.sigma gl in
1158 let ((sigma, c),_) = lookup_eq_eliminator_with_error env sigma eq
1159 ~dep:false ~inccl:true ~l2r:(Some false)
1160 ~e_sort:s
1161 ~c_sort:(Retyping.get_sort_of env sigma t)
1162 ~p_sort in
1163 Proofview.Unsafe.tclEVARS sigma <*> Proofview.tclUNIT c >>= fun eq_elim ->
1164 Proofview.tclEVARMAP >>= fun sigma ->
1165 let term =
1166 (applist (eq_elim, [t;t1;mkNamedLambda sigma (make_annot e ERelevance.relevant) t discriminator;i;t2]))
1167 in
1168 let sigma, _ = Typing.solve_evars env sigma term in
1169 Proofview.Unsafe.tclEVARS sigma >>= fun _ -> Proofview.tclUNIT term
1170 end
1171
1172 type equality = {
1173 eq_data : ( EConstr.constr * GlobRef.t * ESorts.t * (EConstr.t * EConstr.t * EConstr.t));
1174 (* equality data + A : Type, t1 : A, t2 : A *)
1175 eq_term : EConstr.t;
1176 (* term [M : R A t1 t2] where [R] is the equality from above *)
1177 eq_evar : Proofview_monad.goal_with_state list;
1178 (* List of implicit hypotheses on which the data above depends. *)
1179 }
1180
1181 let eq_baseid = Id.of_string "e"
1182
1183 let discr_positions env sigma { eq_data = (_, _ , s, (t, _, _)) as eq_data; eq_term = v; eq_evar = evs } cpath dirn =
1184 build_rocq_True () >>= fun true_0 ->
1185 build_rocq_False () >>= fun false_0 ->
1186 let false_ty = Retyping.get_type_of env sigma false_0 in
1187 let false_kind = Retyping.get_sort_of env sigma false_0 in
1188 let e = next_ident_away eq_baseid (vars_of_env env) in
1189 let e_env = push_named (Context.Named.Declaration.LocalAssum (make_annot e ERelevance.relevant,t)) env in
1190
1191 let discriminator =
1192 try
1193 Proofview.tclUNIT
1194 (build_discriminator e_env sigma true_0 (false_0,false_ty) dirn (mkVar e) cpath)
1195 with
1196 UserError _ as ex ->
1197 let _, info = Exninfo.capture ex in
1198 Proofview.tclZERO ~info ex
1199 in
1200 discriminator >>= fun discriminator ->
1201 discrimination_pf e eq_data discriminator false_kind >>= fun pf ->
1202 let pf = EConstr.mkApp (pf, [|v|]) in
1203 tclTHENS (assert_after Anonymous false_0)
1204 [onLastHypId gen_absurdity; Tactics.exact_check pf <*> Proofview.Unsafe.tclNEWGOALS evs]
1205
1206 let discrEq eq =
1207 let { eq_data = (_, _ , s, (_, t1, t2)) } = eq in
1208 Proofview.Goal.enter begin fun gl ->
1209 let env = Proofview.Goal.env gl in
1210 let sigma = Proofview.Goal.sigma gl in
1211 let goalsort = Retyping.get_sort_of env sigma (Proofview.Goal.concl gl) in
1212 match find_positions env sigma ~keep_proofs:false ~no_discr:false ~eqsort:s ~goalsort t1 t2 with
1213 | Inr _ ->
1214 let info = Exninfo.reify () in
1215 tclZEROMSG ~info (str"Not a discriminable equality.")
1216 | Inl (cpath, discr) ->
1217 discr_positions env sigma eq cpath discr
1218 end
1219
1220 let make_clause with_evars env sigma t lbindc =
1221 let sigma', eq_clause = EClause.make_evar_clause env sigma t in
1222 let sigma' = EClause.solve_evar_clause env sigma' false eq_clause lbindc in
1223 let () = if not with_evars then EClause.check_evar_clause env sigma sigma' eq_clause in
1224 sigma', eq_clause
1225
1226 let onEquality with_evars tac (c,lbindc) =
1227 Proofview.Goal.enter begin fun gl ->
1228 let env = Proofview.Goal.env gl in
1229 let sigma = Proofview.Goal.sigma gl in
1230 let state = Proofview.Goal.state gl in
1231 let t = Retyping.get_type_of env sigma c in
1232 let s = Retyping.get_sort_of env sigma t in
1233 let t' = try snd (Tacred.reduce_to_quantified_ind env sigma t) with UserError _ -> t in
1234 let sigma, eq_clause = make_clause with_evars env sigma t' lbindc in
1235 let filter h =
1236 if h.EClause.hole_deps then None
1237 else
1238 try Some (Proofview_monad.goal_with_state (fst @@ destEvar sigma h.EClause.hole_evar) state)
1239 with DestKO -> None
1240 in
1241 let goals = List.map_filter filter eq_clause.EClause.cl_holes in
1242 let cl_args = Array.map_of_list (fun h -> h.EClause.hole_evar) eq_clause.EClause.cl_holes in
1243 let (eq,u,eq_args) = find_this_eq_data_decompose env sigma eq_clause.cl_concl in
1244 let eq = { eq_data = (EConstr.mkIndU (Globnames.destIndRef eq.eq, u), eq.congr, s, eq_args); eq_term = mkApp (c, cl_args); eq_evar = goals } in
1245 Proofview.Unsafe.tclEVARS sigma <*> tac eq
1246 end
1247
1248 let onNegatedEquality with_evars tac =
1249 Proofview.Goal.enter begin fun gl ->
1250 let sigma = Proofview.Goal.sigma gl in
1251 let ccl = Proofview.Goal.concl gl in
1252 let env = Proofview.Goal.env gl in
1253 match EConstr.kind sigma (hnf_constr0 env sigma ccl) with
1254 | Prod (na,t,u) ->
1255 let u = nf_betaiota (push_rel_assum (na, t) env) sigma u in
1256 if is_empty_type env sigma u then
1257 tclTHEN introf
1258 (onLastHypId (fun id ->
1259 onEquality with_evars tac (mkVar id,NoBindings)))
1260 else tclZEROMSG (str "Not a negated primitive equality.")
1261 | _ ->
1262 let info = Exninfo.reify () in
1263 tclZEROMSG ~info (str "Not a negated primitive equality.")
1264 end
1265
1266 let discrSimpleClause with_evars = function
1267 | None -> onNegatedEquality with_evars discrEq
1268 | Some id -> onEquality with_evars discrEq (mkVar id,NoBindings)
1269
1270 let discr with_evars = onEquality with_evars discrEq
1271
1272 let discrClause with_evars = onClause (discrSimpleClause with_evars)
1273
1274 let discrEverywhere with_evars =
1275 tclTHEN (Proofview.tclUNIT ())
1276 (* Delay the interpretation of side-effect *)
1277 (tclTHEN
1278 (tclREPEAT introf)
1279 (tryAllHyps
1280 (fun id -> tclCOMPLETE (discr with_evars (mkVar id,NoBindings)))))
1281
1282 let discr_tac with_evars = function
1283 | None -> discrEverywhere with_evars
1284 | Some c -> onInductionArg (fun clear_flag -> discr with_evars) c
1285
1286 let discrConcl = discrClause false onConcl
1287 let discrHyp id = discrClause false (onHyp id)
1288
1289 (* The problem is to build a destructor (a generalization of the
1290 predecessor) which, when applied to a term made of constructors
1291 (say [Ci(e1,Cj(e2,Ck(...,term,...),...),...)]), returns a given
1292 subterm of the term (say [term]).
1293
1294 Let [typ] be the type of [term]. If [term] has no dependencies in
1295 the [e1], [e2], etc, then all is simple. If not, then we need to
1296 encapsulated the dependencies into a dependent tuple in such a way
1297 that the destructor has not a dependent type and rewriting can then
1298 be applied. The destructor has the form
1299
1300 [e]Cases e of
1301 | ...
1302 | Ci (x1,x2,...) =>
1303 Cases x2 of
1304 | ...
1305 | Cj (y1,y2,...) =>
1306 Cases y2 of
1307 | ...
1308 | Ck (...,z,...) => z
1309 | ... end
1310 | ... end
1311 | ... end
1312
1313 and the dependencies is expressed by the fact that [z] has a type
1314 dependent in the x1, y1, ...
1315
1316 Assume [z] is typed as follows: env |- z:zty
1317
1318 If [zty] has no dependencies, this is simple. Otherwise, assume
1319 [zty] has free (de Bruijn) variables in,...i1 then the role of
1320 [make_iterated_tuple env sigma (term,typ) (z,zty)] is to build the
1321 tuple
1322
1323 [existT [xn]Pn Rel(in) .. (existT [x2]P2 Rel(i2) (existT [x1]P1 Rel(i1) z))]
1324
1325 where P1 is zty[i1/x1], P2 is {x1 | P1[i2/x2]} etc.
1326 *)
1327
1328 let rec build_injrec env sigma default c = function
1329 | [] ->
1330 let cty = get_type_of env sigma c in
1331 let sigma, { telescope_type; telescope_value }, dfltval = make_iterated_tuple env sigma ~default c cty in
1332 sigma, (telescope_value, telescope_type, dfltval)
1333 | ((sp,cnum),argnum)::l ->
1334 try
1335 let (cnum_nlams,cnum_env,kont) = descend_then env sigma c cnum in
1336 let newc = mkRel(cnum_nlams-argnum) in
1337 let sigma, (subval,tuplety,dfltval) = build_injrec cnum_env sigma default newc l in
1338 let res = kont sigma subval (dfltval,tuplety) in
1339 sigma, (res, tuplety,dfltval)
1340 with
1341 UserError _ -> failwith "caught"
1342
1343 let build_injector env sigma dflt c cpath =
1344 let sigma, (injcode,resty,_) = build_injrec env sigma dflt c cpath in
1345 sigma, (injcode,resty)
1346
1347 let eq_dec_scheme_kind_name = ref (fun _ -> failwith "eq_dec_scheme undefined")
1348 let set_eq_dec_scheme_kind k = eq_dec_scheme_kind_name := (fun _ -> k)
1349
1350 let warn_inject_no_eqdep_dec =
1351 CWarnings.create ~name:"injection-missing-eqdep-dec" ~category:CWarnings.CoreCategories.tactics
1352 Pp.(fun (env,ind) ->
1353 str "The equality scheme for" ++ spc() ++ Printer.pr_inductive env ind ++ spc() ++
1354 str "could not be used as Stdlib.Logic.Eqdep_dec has not been required.")
1355
1356 let inject_if_homogenous_dependent_pair ty =
1357 Proofview.Goal.enter begin fun gl ->
1358 try
1359 let env = Proofview.Goal.env gl in
1360 let sigma = Proofview.Goal.sigma gl in
1361 let eq,u,(t,t1,t2) = find_this_eq_data_decompose env sigma ty in
1362 (* fetch the informations of the pair *)
1363 let sigTconstr = Rocqlib.(lib_ref "core.sigT.type") in
1364 let existTconstr = Rocqlib.lib_ref "core.sigT.intro" in
1365 (* check whether the equality deals with dep pairs or not *)
1366 let eqTypeDest = fst (decompose_app sigma t) in
1367 if not (isRefX env sigma sigTconstr eqTypeDest) then raise_notrace Exit;
1368 let hd1,ar1 = decompose_app sigma t1 and
1369 hd2,ar2 = decompose_app sigma t2 in
1370 if not (isRefX env sigma existTconstr hd1) then raise_notrace Exit;
1371 if not (isRefX env sigma existTconstr hd2) then raise_notrace Exit;
1372 let (ind, _), _ = try find_mrectype env sigma ar1.(0) with Not_found -> raise_notrace Exit in
1373 (* check if the user has declared the dec principle *)
1374 (* and compare the fst arguments of the dep pair *)
1375 (* Note: should work even if not an inductive type, but the table only *)
1376 (* knows inductive types *)
1377 if not (Option.has_some (Ind_tables.lookup_scheme (!eq_dec_scheme_kind_name()) ind) &&
1378 is_conv env sigma ar1.(2) ar2.(2)) then raise_notrace Exit;
1379 let inj2 = match lib_ref_opt "core.eqdep_dec.inj_pair2" with
1380 | None ->
1381 warn_inject_no_eqdep_dec (env,ind);
1382 raise_notrace Exit
1383 | Some v -> v
1384 in
1385 let new_eq_args = [|Retyping.get_type_of env sigma ar1.(3);ar1.(3);ar2.(3)|] in
1386 find_scheme Equality (!eq_dec_scheme_kind_name()) ind >>= fun c ->
1387 let sigma, c = fresh_global env sigma c in
1388 (* cut with the good equality and prove the requested goal *)
1389 tclTHENLIST
1390 [
1391 intro;
1392 onLastHyp (fun hyp ->
1393 Tacticals.pf_constr_of_global Rocqlib.(lib_ref "core.eq.type") >>= fun ceq ->
1394 tclTHENS (cut (mkApp (ceq,new_eq_args)))
1395 [clear [destVar sigma hyp];
1396 Tacticals.pf_constr_of_global inj2 >>= fun inj2 ->
1397 Tactics.exact_check
1398 (mkApp(inj2,[|ar1.(0);c;ar1.(1);ar1.(2);ar1.(3);ar2.(3);hyp|]))
1399 ])]
1400 with Exit ->
1401 Proofview.tclUNIT ()
1402 end
1403
1404 (* Given t1=t2 Inj calculates the whd normal forms of t1 and t2 and it
1405 expands then only when the whdnf has a constructor of an inductive type
1406 in hd position, otherwise delta expansion is not done *)
1407
1408 let simplify_args env sigma t =
1409 (* Quick hack to reduce in arguments of eq only *)
1410 match decompose_app sigma t with
1411 | eq, [|t;c1;c2|] -> applist (eq,[t;simpl env sigma c1;simpl env sigma c2])
1412 | eq, [|t1;c1;t2;c2|] -> applist (eq,[t1;simpl env sigma c1;t2;simpl env sigma c2])
1413 | _ -> t
1414
1415 let inject_at_positions env sigma l2r eq posns tac =
1416 let { eq_data = (eq, congr, s, (t,t1,t2)); eq_term = v; eq_evar = evs } = eq in
1417 let e = next_ident_away eq_baseid (vars_of_env env) in
1418 let e_env = push_named (LocalAssum (make_annot e ERelevance.relevant,t)) env in
1419 let evdref = ref sigma in
1420 let filter (cpath, t1', t2') =
1421 try
1422 (* arbitrarily take t1' as the injector default value *)
1423 let sigma, (injbody,resty) = build_injector e_env !evdref t1' (mkVar e) cpath in
1424 let injfun = mkNamedLambda sigma (make_annot e ERelevance.relevant) t injbody in
1425 let sigma,congr = Evd.fresh_global env sigma congr in
1426 (* pf : eq t t1 t2 -> eq resty (injfun t1) (injfun t2) *)
1427 let mk c = Retyping.get_judgment_of env sigma c in
1428 let args = Array.map mk [|t; resty; injfun; t1; t2|] in
1429 let sigma, pf = Typing.judge_of_apply env sigma (mk congr) args in
1430 let { Environ.uj_val = pf; Environ.uj_type = pf_typ } = pf in
1431 let pf_typ = Vars.subst1 mkProp (pi3 @@ destProd sigma pf_typ) in
1432 let pf = mkApp (pf, [| v |]) in
1433 let ty = simplify_args env sigma pf_typ in
1434 evdref := sigma;
1435 Some (pf, ty)
1436 with Failure _ -> None
1437 in
1438 let injectors = List.map_filter filter posns in
1439 if List.is_empty injectors then
1440 tclZEROMSG (str "Failed to decompose the equality.")
1441 else
1442 let map (pf, ty) =
1443 tclTHENS (cut ty) [
1444 inject_if_homogenous_dependent_pair ty;
1445 Tactics.exact_check pf <*> Proofview.Unsafe.tclNEWGOALS evs;
1446 ] in
1447 Proofview.Unsafe.tclEVARS !evdref <*>
1448 Tacticals.tclTHENFIRST
1449 (Tacticals.tclMAP map (if l2r then List.rev injectors else injectors))
1450 (tac (List.length injectors))
1451
1452 exception NothingToInject
1453 let () = CErrors.register_handler (function
1454 | NothingToInject -> Some (Pp.str "Nothing to inject.")
1455 | _ -> None)
1456
1457
1458 let injEqThen keep_proofs tac l2r eql =
1459 Proofview.Goal.enter begin fun gl ->
1460 let { eq_data = (eq, _ , s, (t,t1,t2)) } = eql in
1461 let sigma = Proofview.Goal.sigma gl in
1462 let env = Proofview.Goal.env gl in
1463 let goalsort = Retyping.get_sort_of env sigma (Proofview.Goal.concl gl) in
1464 let id = try Some (destVar sigma eql.eq_term) with DestKO -> None in
1465 match find_positions env sigma ~keep_proofs ~no_discr:true ~eqsort:s ~goalsort t1 t2 with
1466 | Inl _ ->
1467 assert false
1468 | Inr [] ->
1469 let suggestion =
1470 if keep_proofs then
1471 "" else
1472 " You can try to use option Set Keep Proof Equalities." in
1473 tclZEROMSG (strbrk("No information can be deduced from this equality and the injectivity of constructors. This may be because the terms are convertible, or due to pattern matching restrictions in the sort Prop." ^ suggestion))
1474 | Inr [([],_,_)] ->
1475 Proofview.tclZERO NothingToInject
1476 | Inr posns ->
1477 inject_at_positions env sigma l2r eql posns
1478 (tac id)
1479 end
1480
1481 let get_previous_hyp_position id gl =
1482 let env, sigma = Proofview.Goal.(env gl, sigma gl) in
1483 let rec aux dest = function
1484 | [] -> raise (RefinerError (env, sigma, NoSuchHyp id))
1485 | d :: right ->
1486 let hyp = Context.Named.Declaration.get_id d in
1487 if Id.equal hyp id then dest else aux (MoveAfter hyp) right
1488 in
1489 aux MoveLast (Proofview.Goal.hyps gl)
1490
1491 let injEq flags ?(injection_in_context = injection_in_context_flag ()) with_evars clear_flag ipats =
1492 (* Decide which compatibility mode to use *)
1493 let ipats_style, l2r, dft_clear_flag, bounded_intro = match ipats with
1494 | None when injection_in_context -> Some [], true, true, true
1495 | None -> None, false, false, false
1496 | _ -> let b = use_injection_pattern_l2r_order flags in ipats, b, b, b in
1497 (* Built the post tactic depending on compatibility mode *)
1498 let post_tac id n =
1499 match ipats_style with
1500 | Some ipats ->
1501 Proofview.Goal.enter begin fun gl ->
1502 let destopt = match id with
1503 | Some id -> get_previous_hyp_position id gl
1504 | None -> MoveLast in
1505 let clear_tac =
1506 tclTRY (apply_clear_request clear_flag dft_clear_flag id) in
1507 (* Try should be removal if dependency were treated *)
1508 let intro_tac =
1509 if bounded_intro
1510 then intro_patterns_bound_to with_evars n destopt ipats
1511 else intro_patterns_to with_evars destopt ipats in
1512 tclTHEN clear_tac intro_tac
1513 end
1514 | None -> tclIDTAC in
1515 injEqThen (keep_proof_equalities flags) post_tac l2r
1516
1517 let inj flags ?injection_in_context ipats with_evars clear_flag =
1518 onEquality with_evars (injEq flags ?injection_in_context with_evars clear_flag ipats)
1519
1520 let injClause flags ?injection_in_context ipats with_evars = function
1521 | None -> onNegatedEquality with_evars (injEq flags ?injection_in_context with_evars None ipats)
1522 | Some c -> onInductionArg (inj flags ?injection_in_context ipats with_evars) c
1523
1524 let simpleInjClause flags with_evars = function
1525 | None -> onNegatedEquality with_evars (injEq flags ~injection_in_context:false with_evars None None)
1526 | Some c -> onInductionArg (fun clear_flag -> onEquality with_evars (injEq flags ~injection_in_context:false with_evars clear_flag None)) c
1527
1528 let injConcl flags ?injection_in_context () = injClause flags ?injection_in_context None false None
1529 let injHyp flags ?injection_in_context clear_flag id = injClause flags ?injection_in_context None false (Some (clear_flag,ElimOnIdent CAst.(make id)))
1530
1531 let decompEqThen keep_proofs ntac eq =
1532 let { eq_data = (_, _ , eqsort, (_,t1,t2)) } = eq in
1533 Proofview.Goal.enter begin fun gl ->
1534 let env = Proofview.Goal.env gl in
1535 let sigma = Proofview.Goal.sigma gl in
1536 let goalsort = Retyping.get_sort_of env sigma (Proofview.Goal.concl gl) in
1537 let ido = try Some (destVar sigma eq.eq_term) with DestKO -> None in
1538 match find_positions env sigma ~keep_proofs ~no_discr:false ~eqsort ~goalsort t1 t2 with
1539 | Inl (cpath, discr) ->
1540 discr_positions env sigma eq cpath discr
1541 | Inr [] -> (* Change: do not fail, simplify clear this trivial hyp *)
1542 ntac ido 0
1543 | Inr posns ->
1544 inject_at_positions env sigma true eq posns (ntac ido)
1545 end
1546
1547 let dEqThen0 ~keep_proofs with_evars ntac = function
1548 | None -> onNegatedEquality with_evars (decompEqThen (use_keep_proofs keep_proofs) (ntac None))
1549 | Some c -> onInductionArg (fun clear_flag -> onEquality with_evars (decompEqThen (use_keep_proofs keep_proofs) (ntac clear_flag))) c
1550
1551 let dEq ~keep_proofs with_evars =
1552 dEqThen0 ~keep_proofs with_evars (fun clear_flag ido x ->
1553 (apply_clear_request clear_flag (use_clear_hyp_by_default ()) ido))
1554
1555 let dEqThen ~keep_proofs with_evars ntac where =
1556 dEqThen0 ~keep_proofs with_evars (fun _ _ n -> ntac n) where
1557
1558 let intro_decomp_eq tac (eq, congr, _, data) (c, t) =
1559 Proofview.Goal.enter begin fun gl ->
1560 let env = Proofview.Goal.env gl in
1561 let sigma = Proofview.Goal.sigma gl in
1562 let s = Retyping.get_sort_of env sigma t in
1563 let eq = { eq_data = (eq, congr , s, data); eq_term = c; eq_evar = [] } in
1564 decompEqThen !keep_proof_equalities_for_injection (fun _ -> tac) eq
1565 end
1566
1567 let () = Tactics.declare_intro_decomp_eq intro_decomp_eq
1568
1569 (* [subst_tuple_term dep_pair B]
1570
1571 Given that dep_pair looks like:
1572
1573 (existT e1 (existT e2 ... (existT en en+1) ... ))
1574
1575 of type {x1:T1 & {x2:T2(x1) & ... {xn:Tn(x1..xn-1) & en+1 } } }
1576
1577 and B might contain instances of the ei, we will return the term:
1578
1579 ([x1:ty1]...[xn+1:tyn+1]B
1580 (projT1 (mkRel 1))
1581 (projT1 (projT2 (mkRel 1)))
1582 ...
1583 (projT1 (projT2^n (mkRel 1)))
1584 (projT2 (projT2^n (mkRel 1)))
1585
1586 That is, we will abstract out the terms e1...en+1 of types
1587 t1 (=_beta T1), ..., tn+1 (=_beta Tn+1(e1..en)) as usual, but
1588 will then produce a term in which the abstraction is on a single
1589 term - the debruijn index [mkRel 1], which will be of the same type
1590 as dep_pair (note that the abstracted body may not be typable!).
1591
1592 ALGORITHM for abstraction:
1593
1594 We have a list of terms, [e1]...[en+1], which we want to abstract
1595 out of [B]. For each term [ei], going backwards from [n+1], we
1596 just do a [subst_term], and then do a lambda-abstraction to the
1597 type of the [ei].
1598
1599 *)
1600
1601 let decomp_tuple env sigma c =
1602 let rec decomprec accu ex = match find_sigma_data_decompose env sigma ex with
1603 | ({ proj1; proj2 }), (u, a, b, car, cdr) ->
1604 decomprec ((proj1, proj2, u, a, b, car, cdr) :: accu) cdr
1605 | exception Constr_matching.PatternMatchingFailure -> List.rev accu
1606 in
1607 decomprec [] c
1608
1609 let make_tuple_projs data =
1610 let fold accu (p1, p2, u, a, b, _, _) =
1611 let proj = applist (mkConstU (destConstRef p1, u), [a; b; accu]) in
1612 let accu = applist (mkConstU (destConstRef p2, u), [a; b; accu]) in
1613 accu, proj
1614 in
1615 let last, projs = List.fold_left_map fold (mkRel 1) data in
1616 projs @ [last]
1617
1618 let make_tuple_args sigma arg typ data =
1619 let fold _ (_, _, _, a, b, car, cdr) =
1620 let typ = beta_applist sigma (b, [car]) in
1621 (cdr, typ), (car, a)
1622 in
1623 let last, args = List.fold_left_map fold (arg, typ) data in
1624 args @ [last]
1625
1626 let subst_tuple_term env sigma dep_pair1 dep_pair2 body =
1627 let typ = get_type_of env sigma dep_pair1 in
1628 (* We find all possible decompositions *)
1629 let data1 = decomp_tuple env sigma dep_pair1 in
1630 let data2 = decomp_tuple env sigma dep_pair2 in
1631 (* We adjust to the shortest decomposition *)
1632 let n = min (List.length data1) (List.length data2) in
1633 let data1 = List.firstn n data1 in
1634 let data2 = List.firstn n data2 in
1635 (* We rewrite dep_pair1 ... *)
1636 let proj_list = make_tuple_projs data1 in
1637 let e1_list = make_tuple_args sigma dep_pair1 typ data1 in
1638 (* ... and use dep_pair2 to compute the expected goal *)
1639 let e2_list = make_tuple_args sigma dep_pair2 typ data2 in
1640 (* We build the expected goal *)
1641 let fold (e, t) body = lambda_create env sigma (ERelevance.relevant, t, subst_term sigma e body) in
1642 let abst_B = List.fold_right fold e1_list body in
1643 let ctx, abst_B = decompose_lambda_n_assum sigma (List.length e1_list) abst_B in
1644 (* Retype the body, it might be ill-typed if it depends on the abstracted subterms *)
1645 let sigma, _ = Typing.type_of (push_rel_context ctx env) sigma abst_B in
1646 let sigma =
1647 (* FIXME: this should be enforced before. We only have to check the last
1648 projection, since all previous ones mention a prefix of the subtypes. *)
1649 let env = push_rel (Rel.Declaration.LocalAssum (anonR, typ)) env in
1650 let sigma, _ = Typing.type_of env sigma (List.last proj_list) in
1651 sigma
1652 in
1653 let pred_body = Vars.substl (List.rev proj_list) abst_B in
1654 let body = mkApp (lambda_create env sigma (ERelevance.relevant,typ,pred_body),[|dep_pair1|]) in
1655 let expected_goal = Vars.substl (List.rev_map fst e2_list) abst_B in
1656 (* Simulate now the normalisation treatment made by Logic.mk_refgoals *)
1657 let expected_goal = nf_betaiota env sigma expected_goal in
1658 (sigma, (body, expected_goal))
1659
1660 (* Like "replace" but decompose dependent equalities *)
1661 (* i.e. if equality is "exists t v = exists u w", and goal is "phi(t,u)", *)
1662 (* then it uses the predicate "\x.phi(proj1_sig x,proj2_sig x)", and so *)
1663 (* on for further iterated sigma-tuples *)
1664
1665 let cutSubstInConcl l2r eqn =
1666 Proofview.Goal.enter begin fun gl ->
1667 let env = Proofview.Goal.env gl in
1668 let sigma = Proofview.Goal.sigma gl in
1669 let concl = Proofview.Goal.concl gl in
1670 let (lbeq,u,(t,e1,e2)) = find_eq_data_decompose env sigma eqn in
1671 let (e1,e2) = if l2r then (e1,e2) else (e2,e1) in
1672 let (sigma, (typ, expected)) = subst_tuple_term env sigma e1 e2 concl in
1673 tclTHEN (Proofview.Unsafe.tclEVARS sigma)
1674 (tclTHENFIRST
1675 (tclTHENLIST [
1676 (change_concl typ); (* Put in pattern form *)
1677 (replace_core onConcl l2r eqn)
1678 ])
1679 (change_concl expected)) (* Put in normalized form *)
1680 end
1681
1682 let cutSubstInHyp l2r eqn id =
1683 Proofview.Goal.enter begin fun gl ->
1684 let env = Proofview.Goal.env gl in
1685 let sigma = Proofview.Goal.sigma gl in
1686 let (lbeq,u,(t,e1,e2)) = find_eq_data_decompose env sigma eqn in
1687 let typ = Tacmach.pf_get_hyp_typ id gl in
1688 let (e1,e2) = if l2r then (e1,e2) else (e2,e1) in
1689 let (sigma, (typ, expected)) = subst_tuple_term env sigma e1 e2 typ in
1690 tclTHEN (Proofview.Unsafe.tclEVARS sigma)
1691 (tclTHENFIRST
1692 (tclTHENLIST [
1693 (change_in_hyp ~check:true None (make_change_arg typ) (id,InHypTypeOnly));
1694 (replace_core (onHyp id) l2r eqn)
1695 ])
1696 (change_in_hyp ~check:true None (make_change_arg expected) (id,InHypTypeOnly)))
1697 end
1698
1699 let try_rewrite tac =
1700 Proofview.tclORELSE tac begin function (e, info) -> match e with
1701 | Constr_matching.PatternMatchingFailure ->
1702 tclZEROMSG ~info (str "Not a primitive equality here.")
1703 | e ->
1704 (* XXX: absorbing anomalies?? *)
1705 tclZEROMSG ~info
1706 (strbrk "Cannot find a well-typed generalization of the goal that makes the proof progress.")
1707 end
1708
1709 let cutSubstClause l2r eqn cls =
1710 match cls with
1711 | None -> cutSubstInConcl l2r eqn
1712 | Some id -> cutSubstInHyp l2r eqn id
1713
1714 let substClause l2r c cls =
1715 Proofview.Goal.enter begin fun gl ->
1716 let env = Proofview.Goal.env gl in
1717 let sigma = Proofview.Goal.sigma gl in
1718 let eq = get_type_of env sigma c in
1719 tclTHENS (cutSubstClause l2r eq cls)
1720 [Proofview.tclUNIT (); exact_no_check c]
1721 end
1722
1723 let rewriteClause l2r c cls = try_rewrite (substClause l2r c cls)
1724 let rewriteInHyp l2r c id = rewriteClause l2r c (Some id)
1725 let rewriteInConcl l2r c = rewriteClause l2r c None
1726
1727 (* Naming scheme for rewrite tactics
1728
1729 give equality give proof of equality
1730
1731 / cutSubstClause substClause
1732 raw | cutSubstInHyp substInHyp
1733 \ cutSubstInConcl substInConcl
1734
1735 raw = raise typing error or PatternMatchingFailure
1736 user = raise user error specific to rewrite
1737 *)
1738
1739 (**********************************************************************)
1740 (* Substitutions tactics (JCF) *)
1741
1742 let restrict_to_eq_and_identity env eq = (* compatibility *)
1743 let is_ref b = match Rocqlib.lib_ref_opt b with
1744 | None -> false
1745 | Some b -> Environ.QGlobRef.equal env eq b
1746 in
1747 if not (List.exists is_ref ["core.eq.type"; "core.identity.type"])
1748 then raise Constr_matching.PatternMatchingFailure
1749
1750 exception FoundHyp of (Id.t * constr * bool)
1751
1752 (* tests whether hyp [c] is [x = t] or [t = x], [x] not occurring in [t] *)
1753 let is_eq_x env sigma x d =
1754 let id = NamedDecl.get_id d in
1755 try
1756 let is_var id c = match EConstr.kind sigma c with
1757 | Var id' -> Id.equal id id'
1758 | _ -> false
1759 in
1760 let c = nf_evar sigma (NamedDecl.get_type d) in
1761 let (_,lhs,rhs) = pi3 (find_eq_data_decompose env sigma c) in
1762 if (is_var x lhs) && not (local_occur_var sigma x rhs) then raise (FoundHyp (id,rhs,true));
1763 if (is_var x rhs) && not (local_occur_var sigma x lhs) then raise (FoundHyp (id,lhs,false))
1764 with Constr_matching.PatternMatchingFailure ->
1765 ()
1766
1767 exception FoundDepInGlobal of Id.t option * GlobRef.t
1768
1769 let test_non_indirectly_dependent_section_variable gl x =
1770 let env = Proofview.Goal.env gl in
1771 let sigma = Proofview.Goal.sigma gl in
1772 let hyps = Proofview.Goal.hyps gl in
1773 let concl = Proofview.Goal.concl gl in
1774 List.iter (fun decl ->
1775 NamedDecl.iter_constr (fun c ->
1776 match occur_var_indirectly env sigma x c with
1777 | Some gr -> raise (FoundDepInGlobal (Some (NamedDecl.get_id decl), gr))
1778 | None -> ()) decl) hyps;
1779 match occur_var_indirectly env sigma x concl with
1780 | Some gr -> raise (FoundDepInGlobal (None, gr))
1781 | None -> ()
1782
1783 let check_non_indirectly_dependent_section_variable gl x =
1784 try test_non_indirectly_dependent_section_variable gl x
1785 with FoundDepInGlobal (pos,gr) ->
1786 let where = match pos with
1787 | Some id -> str "hypothesis " ++ Id.print id
1788 | None -> str "the conclusion of the goal" in
1789 user_err
1790 (strbrk "Section variable " ++ Id.print x ++
1791 strbrk " occurs implicitly in global declaration " ++ Printer.pr_global gr ++
1792 strbrk " present in " ++ where ++ strbrk ".")
1793
1794 let is_non_indirectly_dependent_section_variable gl z =
1795 try test_non_indirectly_dependent_section_variable gl z; true
1796 with FoundDepInGlobal (pos,gr) -> false
1797
1798 (* Rewrite "hyp:x=rhs" or "hyp:rhs=x" (if dir=false) everywhere and
1799 erase hyp and x; proceed by generalizing all dep hyps *)
1800
1801 let subst_one dep_proof_ok x (hyp,rhs,dir) =
1802 Proofview.Goal.enter begin fun gl ->
1803 let sigma = Proofview.Goal.sigma gl in
1804 let hyps = Proofview.Goal.hyps gl in
1805 let concl = Proofview.Goal.concl gl in
1806 (* The set of hypotheses using x *)
1807 let dephyps =
1808 List.rev (pi3 (List.fold_right (fun dcl (dest,deps,allhyps) ->
1809 let id = NamedDecl.get_id dcl in
1810 if not (Id.equal id hyp)
1811 && List.exists (fun y -> local_occur_var_in_decl sigma y dcl) deps
1812 then
1813 (dest,id::deps,(dest,id)::allhyps)
1814 else
1815 (MoveBefore id,deps,allhyps))
1816 hyps
1817 (MoveBefore x,[x],[]))) in (* In practice, no dep hyps before x, so MoveBefore x is good enough *)
1818 (* Decides if x appears in conclusion *)
1819 let depconcl = local_occur_var sigma x concl in
1820 let need_rewrite = not (List.is_empty dephyps) || depconcl in
1821 tclTHENLIST
1822 ((if need_rewrite then
1823 [Generalize.revert (List.map snd dephyps);
1824 general_rewrite ~where:None ~l2r:dir AtLeastOneOccurrence ~freeze:true ~dep:dep_proof_ok ~with_evars:false (mkVar hyp, NoBindings);
1825 (tclMAP (fun (dest,id) -> intro_move (Some id) dest) dephyps)]
1826 else
1827 [Proofview.tclUNIT ()]) @
1828 [tclTRY (clear [x; hyp])])
1829 end
1830
1831 (* Look for an hypothesis hyp of the form "x=rhs" or "rhs=x", rewrite
1832 it everywhere, and erase hyp and x; proceed by generalizing all dep hyps *)
1833
1834 let subst_one_var dep_proof_ok x =
1835 Proofview.Goal.enter begin fun gl ->
1836 let env = Proofview.Goal.env gl in
1837 let sigma = Proofview.Goal.sigma gl in
1838 let decl = Tacmach.pf_get_hyp x gl in
1839 (* If x has a body, simply replace x with body and clear x *)
1840 if is_local_def decl then tclTHEN (unfold_body x) (clear [x]) else
1841 (* Find a non-recursive definition for x *)
1842 let res =
1843 try
1844 (* [is_eq_x] ensures nf_evar on its side *)
1845 let hyps = Proofview.Goal.hyps gl in
1846 let test hyp _ = is_eq_x env sigma x hyp in
1847 Context.Named.fold_outside test ~init:() hyps;
1848 user_err
1849 (str "Cannot find any non-recursive equality over " ++ Id.print x ++
1850 str".")
1851 with FoundHyp res -> res in
1852 if is_section_variable (Global.env ()) x then
1853 check_non_indirectly_dependent_section_variable gl x;
1854 subst_one dep_proof_ok x res
1855 end
1856
1857 let subst_gen dep_proof_ok ids =
1858 tclMAP (subst_one_var dep_proof_ok) ids
1859
1860 (* For every x, look for an hypothesis hyp of the form "x=rhs" or "rhs=x",
1861 rewrite it everywhere, and erase hyp and x; proceed by generalizing
1862 all dep hyps *)
1863
1864 let subst = subst_gen true
1865
1866 type subst_tactic_flags = {
1867 only_leibniz : bool;
1868 rewrite_dependent_proof : bool
1869 }
1870
1871 let default_subst_tactic_flags =
1872 { only_leibniz = false; rewrite_dependent_proof = true }
1873
1874 let warn_deprecated_simple_subst =
1875 CWarnings.create ~name:"deprecated-simple-subst" ~category:Deprecation.Version.v8_8
1876 (fun () -> strbrk"\"simple subst\" is deprecated")
1877
1878 let subst_all ?(flags=default_subst_tactic_flags) () =
1879
1880 let () =
1881 if flags.only_leibniz || not flags.rewrite_dependent_proof then
1882 warn_deprecated_simple_subst ()
1883 in
1884
1885 (* Find hypotheses to treat in linear time *)
1886 let process hyp =
1887 Proofview.Goal.enter begin fun gl ->
1888 let env = Proofview.Goal.env gl in
1889 let sigma = Proofview.Goal.sigma gl in
1890 let c = Tacmach.pf_get_hyp hyp gl |> NamedDecl.get_type in
1891 try
1892 let lbeq,u,(_,x,y) = find_eq_data_decompose env sigma c in
1893 if flags.only_leibniz then restrict_to_eq_and_identity env lbeq.eq;
1894 match EConstr.kind sigma x, EConstr.kind sigma y with
1895 | Var x, Var y when Id.equal x y ->
1896 Proofview.tclUNIT ()
1897 | Var x', _ when not (Termops.local_occur_var sigma x' y) &&
1898 not (is_evaluable env sigma (EvalVarRef x')) &&
1899 is_non_indirectly_dependent_section_variable gl x' ->
1900 subst_one flags.rewrite_dependent_proof x' (hyp,y,true)
1901 | _, Var y' when not (Termops.local_occur_var sigma y' x) &&
1902 not (is_evaluable env sigma (EvalVarRef y')) &&
1903 is_non_indirectly_dependent_section_variable gl y' ->
1904 subst_one flags.rewrite_dependent_proof y' (hyp,x,false)
1905 | _ ->
1906 Proofview.tclUNIT ()
1907 with Constr_matching.PatternMatchingFailure ->
1908 Proofview.tclUNIT ()
1909 end
1910 in
1911 Proofview.Goal.enter begin fun gl ->
1912 tclMAP process (List.rev (List.map NamedDecl.get_id (Proofview.Goal.hyps gl)))
1913 end
1914
1915 (* Rewrite the first assumption for which a condition holds
1916 and gives the direction of the rewrite *)
1917
1918 let cond_eq_term_left env sigma c t =
1919 try
1920 let (_,x,_) = pi3 (find_eq_data_decompose env sigma t) in
1921 if Reductionops.is_conv env sigma c x then true else failwith "not convertible"
1922 with Constr_matching.PatternMatchingFailure -> failwith "not an equality"
1923
1924 let cond_eq_term_right env sigma c t =
1925 try
1926 let (_,_,x) = pi3 (find_eq_data_decompose env sigma t) in
1927 if Reductionops.is_conv env sigma c x then false else failwith "not convertible"
1928 with Constr_matching.PatternMatchingFailure -> failwith "not an equality"
1929
1930 let cond_eq_term env sigma c t =
1931 try
1932 let (_,x,y) = pi3 (find_eq_data_decompose env sigma t) in
1933 if Reductionops.is_conv env sigma c x then true
1934 else if Reductionops.is_conv env sigma c y then false
1935 else failwith "not convertible"
1936 with Constr_matching.PatternMatchingFailure -> failwith "not an equality"
1937
1938 let rewrite_assumption_cond cond_eq_term cl =
1939 let rec arec env sigma hyps = match hyps with
1940 | [] -> user_err Pp.(str "No such assumption.")
1941 | hyp ::rest ->
1942 let id = NamedDecl.get_id hyp in
1943 begin
1944 try
1945 let dir = cond_eq_term env sigma (NamedDecl.get_type hyp) in
1946 general_rewrite_clause dir false (mkVar id,NoBindings) cl
1947 with | Failure _ | UserError _ -> (* XXX: use options *)
1948 arec env sigma rest
1949 end
1950 in
1951 Proofview.Goal.enter begin fun gl ->
1952 let env = Proofview.Goal.env gl in
1953 let sigma = Proofview.Goal.sigma gl in
1954 let hyps = Proofview.Goal.hyps gl in
1955 arec env sigma hyps
1956 end
1957
1958 (* Generalize "subst x" to substitution of subterm appearing as an
1959 equation in the context, but not clearing the hypothesis *)
1960
1961 let replace_term dir_opt c =
1962 let cond_eq_fun env sigma t =
1963 match dir_opt with
1964 | None -> cond_eq_term env sigma c t
1965 | Some true -> cond_eq_term_left env sigma c t
1966 | Some false -> cond_eq_term_right env sigma c t
1967 in
1968 rewrite_assumption_cond cond_eq_fun
1969
1970 (* Declare rewriting tactic for intro patterns "<-" and "->" *)
1971
1972 let () =
1973 let gmr l2r with_evars tac c = general_rewrite_clause l2r with_evars tac c in
1974 Hook.set Tactics.general_rewrite_clause gmr
1975
1976 let () = Hook.set Tactics.subst_one subst_one