Debian Codegraph @

tactics/tactics.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 open Pp
12 open CErrors
13 open Util
14 open Names
15 open Nameops
16 open Constr
17 open Context
18 open Termops
19 open Environ
20 open EConstr
21 open Vars
22 open Namegen
23 open Declarations
24 open Inductiveops
25 open Reductionops
26 open Evd
27 open Tacred
28 open Genredexpr
29 open Logic
30 open Clenv
31 open Tacticals
32 open Hipattern
33 open Rocqlib
34 open Evarutil
35 open Elimschemes
36 open Pretype_errors
37 open Unification
38 open Locus
39 open Locusops
40 open Tactypes
41 open Proofview.Notations
42 open Context.Named.Declaration
43
44 module RelDecl = Context.Rel.Declaration
45 module NamedDecl = Context.Named.Declaration
46
47 let tclEVARS = Proofview.Unsafe.tclEVARS
48 let tclEVARSTHEN sigma t = Proofview.tclTHEN (tclEVARS sigma) t
49
50 let typ_of env sigma c =
51 let open Retyping in
52 try get_type_of ~lax:true env sigma c
53 with RetypeError e ->
54 user_err (print_retype_error e)
55
56 open Goptions
57
58 let clear_hyp_by_default = ref false
59
60 let use_clear_hyp_by_default () = !clear_hyp_by_default
61
62 let () =
63 declare_bool_option
64 { optstage = Summary.Stage.Interp;
65 optdepr = None;
66 optkey = ["Default";"Clearing";"Used";"Hypotheses"];
67 optread = (fun () -> !clear_hyp_by_default) ;
68 optwrite = (fun b -> clear_hyp_by_default := b) }
69
70
71 (*********************************************)
72 (* Tactics *)
73 (*********************************************)
74
75 (******************************************)
76 (* Primitive tactics *)
77 (******************************************)
78
79 (** This tactic creates a partial proof realizing the introduction rule, but
80 does not check anything. *)
81 let unsafe_intro env decl ~relevance b =
82 Refine.refine_with_principal ~typecheck:false begin fun sigma ->
83 let ctx = named_context_val env in
84 let nctx = push_named_context_val decl ctx in
85 let inst = EConstr.identity_subst_val (named_context_val env) in
86 let ninst = SList.cons (mkRel 1) inst in
87 let nb = subst1 (mkVar (NamedDecl.get_id decl)) b in
88 let (sigma, ev) = new_pure_evar nctx sigma ~relevance nb in
89 (sigma, mkLambda_or_LetIn (NamedDecl.to_rel_decl decl) (mkEvar (ev, ninst)),
90 Some ev)
91 end
92
93 let introduction id =
94 Proofview.Goal.enter begin fun gl ->
95 let concl = Proofview.Goal.concl gl in
96 let relevance = Proofview.Goal.relevance gl in
97 let sigma = Proofview.Goal.sigma gl in
98 let hyps = named_context_val (Proofview.Goal.env gl) in
99 let env = Proofview.Goal.env gl in
100 let () = if mem_named_context_val id hyps then
101 TacticErrors.intro_already_declared id
102 in
103 let open Context.Named.Declaration in
104 match EConstr.kind sigma concl with
105 | Prod (id0, t, b) -> unsafe_intro env (LocalAssum ({id0 with binder_name=id}, t)) ~relevance b
106 | LetIn (id0, c, t, b) -> unsafe_intro env (LocalDef ({id0 with binder_name=id}, c, t)) ~relevance b
107 | _ -> raise (RefinerError (env, sigma, IntroNeedsProduct))
108 end
109
110 (* Not sure if being able to disable [cast] is useful. Uses seem picked somewhat randomly. *)
111 let convert_concl ~cast ~check ty k =
112 Proofview.Goal.enter begin fun gl ->
113 let env = Proofview.Goal.env gl in
114 let conclty = Proofview.Goal.concl gl in
115 Refine.refine_with_principal ~typecheck:false begin fun sigma ->
116 let sigma =
117 if check then begin
118 let sigma, _ = Typing.type_of env sigma ty in
119 match Reductionops.infer_conv env sigma ty conclty with
120 | None -> TacticErrors.not_convertible ()
121 | Some sigma -> sigma
122 end else sigma
123 in
124 let (sigma, x) = Evarutil.new_evar env sigma ty in
125 let ans = if not cast then x else mkCast(x,k,conclty) in
126 (sigma, ans, Some (fst @@ destEvar sigma x))
127 end
128 end
129
130 let convert_hyp ~check ~reorder d =
131 Proofview.Goal.enter begin fun gl ->
132 let env = Proofview.Goal.env gl in
133 let sigma = Proofview.Goal.sigma gl in
134 let ty = Proofview.Goal.concl gl in
135 let sign = convert_hyp ~check ~reorder env sigma d in
136 let env = reset_with_named_context sign env in
137 Refine.refine_with_principal ~typecheck:false begin fun sigma ->
138 let sigma, ev = Evarutil.new_evar env sigma ty in
139 sigma, ev, Some (fst @@ destEvar sigma ev)
140 end
141 end
142
143 let convert_gen pb x y =
144 Proofview.Goal.enter begin fun gl ->
145 let env = Proofview.Goal.env gl in
146 let sigma = Proofview.Goal.sigma gl in
147 match Reductionops.infer_conv ~pb env sigma x y with
148 | Some sigma -> Proofview.Unsafe.tclEVARS sigma
149 | None -> TacticErrors.not_convertible ()
150 | exception e when CErrors.noncritical e ->
151 let _, info = Exninfo.capture e in
152 (* FIXME: Sometimes an anomaly is raised from conversion *)
153 TacticErrors.not_convertible ?loc:(Loc.get_loc info) ()
154 end
155
156 let convert x y = convert_gen Conversion.CONV x y
157 let convert_leq x y = convert_gen Conversion.CUMUL x y
158
159 let clear_gen fail = function
160 | [] -> Proofview.tclUNIT ()
161 | ids ->
162 Proofview.Goal.enter begin fun gl ->
163 let ids = List.fold_right Id.Set.add ids Id.Set.empty in
164 (* clear_hyps_in_evi does not require nf terms *)
165 let env = Proofview.Goal.env gl in
166 let sigma = Proofview.Goal.sigma gl in
167 let concl = Proofview.Goal.concl gl in
168 let (sigma, hyps, concl) =
169 try clear_hyps_in_evi env sigma (named_context_val env) concl ids
170 with Evarutil.ClearDependencyError (id,err,inglobal) -> fail env sigma id err inglobal
171 in
172 let env = reset_with_named_context hyps env in
173 Proofview.tclTHEN (Proofview.Unsafe.tclEVARS sigma)
174 (Refine.refine_with_principal ~typecheck:false begin fun sigma ->
175 let sigma, ev = Evarutil.new_evar env sigma concl in
176 sigma, ev, Some (fst @@ destEvar sigma ev)
177 end)
178 end
179
180 let clear ids =
181 let fail env sigma id err inglobal =
182 TacticErrors.clear_dependency env sigma (Some id) err inglobal
183 in
184 clear_gen fail ids
185
186 let clear_for_replacing ids =
187 let fail env sigma id err inglobal =
188 TacticErrors.replacing_dependency env sigma id err inglobal
189 in
190 clear_gen fail ids
191
192 let apply_clear_request clear_flag dft c =
193 let doclear = match clear_flag with
194 | None -> if dft then c else None
195 | Some true ->
196 begin match c with
197 | None -> TacticErrors.keep_and_clear_modifier_only_for_hypotheses ()
198 | Some id -> Some id
199 end
200 | Some false -> None
201 in
202 match doclear with
203 | None -> Proofview.tclUNIT ()
204 | Some id -> clear [id]
205
206 let move_hyp id dest =
207 Proofview.Goal.enter begin fun gl ->
208 let env = Proofview.Goal.env gl in
209 let sigma = Proofview.Goal.sigma gl in
210 let ty = Proofview.Goal.concl gl in
211 let sign = named_context_val env in
212 let sign' = move_hyp_in_named_context env sigma id dest sign in
213 let env = reset_with_named_context sign' env in
214 Refine.refine_with_principal ~typecheck:false begin fun sigma ->
215 let sigma, ev = Evarutil.new_evar env sigma ty in
216 sigma, ev, Some (fst @@ destEvar sigma ev)
217 end
218 end
219
220 let rename_hyp repl =
221 let fold accu (src, dst) = match accu with
222 | None -> None
223 | Some (srcs, dsts) ->
224 if Id.Set.mem src srcs then None
225 else if Id.Set.mem dst dsts then None
226 else
227 let srcs = Id.Set.add src srcs in
228 let dsts = Id.Set.add dst dsts in
229 Some (srcs, dsts)
230 in
231 let init = Some (Id.Set.empty, Id.Set.empty) in
232 let dom = List.fold_left fold init repl in
233 match dom with
234 | None ->
235 let info = Exninfo.reify () in
236 Tacticals.tclZEROMSG ~info (str "Not a one-to-one name mapping")
237 | Some (src, dst) ->
238 Proofview.Goal.enter begin fun gl ->
239 let concl = Proofview.Goal.concl gl in
240 let env = Proofview.Goal.env gl in
241 let sign = named_context_val env in
242 let sigma = Proofview.Goal.sigma gl in
243 let relevance = Proofview.Goal.relevance gl in
244 (* Check that we do not mess variables *)
245 let vars = ids_of_named_context_val sign in
246 let () =
247 if not (Id.Set.subset src vars) then
248 let hyp = Id.Set.choose (Id.Set.diff src vars) in
249 raise (RefinerError (env, sigma, NoSuchHyp hyp))
250 in
251 let mods = Id.Set.diff vars src in
252 let () =
253 try
254 let elt = Id.Set.choose (Id.Set.inter dst mods) in
255 TacticErrors.already_used elt
256 with Not_found -> ()
257 in
258 (* All is well *)
259 let make_subst (src, dst) = (src, mkVar dst) in
260 let subst = List.map make_subst repl in
261 let subst c = Vars.replace_vars sigma subst c in
262 let replace id = try List.assoc_f Id.equal id repl with Not_found -> id in
263 let map decl = decl |> NamedDecl.map_id replace |> NamedDecl.map_constr subst in
264 let ohyps = named_context_of_val sign in
265 let nhyps = List.map map ohyps in
266 let nconcl = subst concl in
267 let nctx = val_of_named_context nhyps in
268 let fold odecl ndecl accu =
269 if Id.equal (NamedDecl.get_id odecl) (NamedDecl.get_id ndecl) then
270 SList.default accu
271 else
272 SList.cons (mkVar @@ NamedDecl.get_id odecl) accu
273 in
274 let instance = List.fold_right2 fold ohyps nhyps SList.empty in
275 Refine.refine_with_principal ~typecheck:false begin fun sigma ->
276 let sigma, ev = Evarutil.new_pure_evar nctx sigma ~relevance nconcl in
277 sigma, mkEvar (ev, instance), Some ev
278 end
279 end
280
281 (**************************************************************)
282 (* Fresh names *)
283 (**************************************************************)
284
285 let fresh_id_in_env avoid id env =
286 let avoid' = ids_of_named_context_val (named_context_val env) in
287 let avoid = if Id.Set.is_empty avoid then avoid' else Id.Set.union avoid' avoid in
288 next_ident_away_in_goal (Global.env ()) id avoid
289
290 let new_fresh_id avoid id gl =
291 fresh_id_in_env avoid id (Proofview.Goal.env gl)
292
293 let id_of_name_with_default id = function
294 | Anonymous -> id
295 | Name id -> id
296
297 let default_id_of_sort sigma s =
298 if ESorts.is_small sigma s then default_small_ident else default_type_ident
299
300 let default_id env sigma decl =
301 let open Context.Rel.Declaration in
302 match decl with
303 | LocalAssum (name,t) ->
304 let dft = default_id_of_sort sigma (Retyping.get_sort_of env sigma t) in
305 id_of_name_with_default dft name.binder_name
306 | LocalDef (name,b,_) -> id_of_name_using_hdchar env sigma b name.binder_name
307
308 (* Non primitive introduction tactics are treated by intro_then_gen
309 There is possibly renaming, with possibly names to avoid and
310 possibly a move to do after the introduction *)
311
312 type name_flag =
313 | NamingAvoid of Id.Set.t
314 | NamingBasedOn of Id.t * Id.Set.t
315 | NamingMustBe of lident
316
317 let naming_of_name = function
318 | Anonymous -> NamingAvoid Id.Set.empty
319 | Name id -> NamingMustBe (CAst.make id)
320
321 let find_name mayrepl decl naming gl = match naming with
322 | NamingAvoid idl ->
323 (* This case must be compatible with [find_intro_names] below. *)
324 let env = Proofview.Goal.env gl in
325 let sigma = Proofview.Goal.sigma gl in
326 new_fresh_id idl (default_id env sigma decl) gl
327 | NamingBasedOn (id,idl) -> new_fresh_id idl id gl
328 | NamingMustBe {CAst.loc;v=id} ->
329 (* When name is given, we allow to hide a global name. *)
330 let ids_of_hyps = Tacmach.pf_ids_set_of_hyps gl in
331 if not mayrepl && Id.Set.mem id ids_of_hyps then
332 TacticErrors.already_used ?loc id;
333 id
334
335 (**************************************************************)
336 (* Computing position of hypotheses for replacing *)
337 (**************************************************************)
338
339 let get_next_hyp_position env sigma id =
340 let rec aux = function
341 | [] -> error_no_such_hypothesis env sigma id
342 | decl :: right ->
343 if Id.equal (NamedDecl.get_id decl) id then
344 match right with decl::_ -> MoveBefore (NamedDecl.get_id decl) | [] -> MoveFirst
345 else
346 aux right
347 in
348 aux
349
350 let get_previous_hyp_position env sigma id =
351 let rec aux dest = function
352 | [] -> error_no_such_hypothesis env sigma id
353 | decl :: right ->
354 let hyp = NamedDecl.get_id decl in
355 if Id.equal hyp id then dest else aux (MoveAfter hyp) right
356 in
357 aux MoveLast
358
359 (**************************************************************)
360 (* Cut rule *)
361 (**************************************************************)
362
363 let clear_hyps2 env sigma ids sign t cl =
364 try
365 Evarutil.clear_hyps2_in_evi env sigma sign t cl ids
366 with Evarutil.ClearDependencyError (id, err, inglobal) ->
367 TacticErrors.replacing_dependency env sigma id err inglobal
368
369 let internal_cut ?(check=true) replace id t =
370 Proofview.Goal.enter begin fun gl ->
371 let env = Proofview.Goal.env gl in
372 let sigma = Proofview.Goal.sigma gl in
373 let concl = Proofview.Goal.concl gl in
374 let sign = named_context_val env in
375 let r = Retyping.relevance_of_type env sigma t in
376 let env',t,concl,sigma =
377 if replace then
378 let nexthyp = get_next_hyp_position env sigma id (named_context_of_val sign) in
379 let sigma,sign',t,concl = clear_hyps2 env sigma (Id.Set.singleton id) sign t concl in
380 let sign' = insert_decl_in_named_context env sigma (LocalAssum (make_annot id r,t)) nexthyp sign' in
381 Environ.reset_with_named_context sign' env,t,concl,sigma
382 else
383 (if check && mem_named_context_val id sign then
384 TacticErrors.intro_already_declared id;
385 push_named (LocalAssum (make_annot id r,t)) env,t,concl,sigma) in
386 let nf_t = nf_betaiota env sigma t in
387 Proofview.tclTHEN
388 (Proofview.Unsafe.tclEVARS sigma)
389 (Refine.refine_with_principal ~typecheck:false begin fun sigma ->
390 let (sigma, ev) = Evarutil.new_evar env sigma nf_t in
391 let (sigma, ev') = Evarutil.new_evar env' sigma concl in
392 let term = mkLetIn (make_annot (Name id) r, ev, t, EConstr.Vars.subst_var sigma id ev') in
393 (sigma, term, Some (fst @@ destEvar sigma ev'))
394 end)
395 end
396
397 let assert_before_then_gen b naming t tac =
398 let open Context.Rel.Declaration in
399 Proofview.Goal.enter begin fun gl ->
400 let id = find_name b (LocalAssum (make_annot Anonymous Sorts.Relevant, t)) naming gl in
401 Tacticals.tclTHENLAST
402 (internal_cut b id t)
403 (tac id)
404 end
405
406 let assert_before_gen b naming t =
407 assert_before_then_gen b naming t (fun _ -> Proofview.tclUNIT ())
408
409 let assert_before na = assert_before_gen false (naming_of_name na)
410 let assert_before_replacing id = assert_before_gen true (NamingMustBe (CAst.make id))
411
412 let replace_error_option err tac =
413 match err with
414 | None -> tac
415 | Some (e, info) ->
416 Proofview.tclORELSE tac (fun _ -> Proofview.tclZERO ~info e)
417
418 let assert_after_then_gen b naming t tac =
419 let open Context.Rel.Declaration in
420 Proofview.Goal.enter begin fun gl ->
421 let id = find_name b (LocalAssum (make_annot Anonymous Sorts.Relevant,t)) naming gl in
422 Tacticals.tclTHENFIRST
423 (internal_cut b id t <*> Proofview.cycle 1)
424 (tac id)
425 end
426
427 let assert_after_gen b naming t =
428 assert_after_then_gen b naming t (fun _ -> (Proofview.tclUNIT ()))
429
430 let assert_after na = assert_after_gen false (naming_of_name na)
431 let assert_after_replacing id = assert_after_gen true (NamingMustBe (CAst.make id))
432
433 (**************************************************************)
434 (* Reduction and conversion tactics *)
435 (**************************************************************)
436
437 type tactic_reduction = Reductionops.reduction_function
438 type e_tactic_reduction = Reductionops.e_reduction_function
439
440 let[@ocaml.inline] (let*) m f = match m with
441 | NoChange -> NoChange
442 | Changed v -> f v
443
444 let e_pf_change_decl (redfun : bool -> Tacred.change_function) where env sigma decl =
445 let open Context.Named.Declaration in
446 match decl with
447 | LocalAssum (id,ty) ->
448 if where == InHypValueOnly then TacticErrors.variable_has_no_value id.binder_name;
449 let* (sigma, ty') = redfun false env sigma ty in
450 Changed (sigma, LocalAssum (id, ty'))
451 | LocalDef (id,b,ty) ->
452 let (sigma, b') =
453 if where != InHypTypeOnly then match redfun true env sigma b with
454 | NoChange -> (sigma, NoChange)
455 | Changed (sigma, b') -> (sigma, Changed b')
456 else (sigma, NoChange)
457 in
458 let (sigma, ty') =
459 if where != InHypValueOnly then match redfun false env sigma ty with
460 | NoChange -> (sigma, NoChange)
461 | Changed (sigma, ty') -> (sigma, Changed ty')
462 else (sigma, NoChange)
463 in
464 match b', ty' with
465 | NoChange, NoChange -> NoChange
466 | Changed b', NoChange -> Changed (sigma, LocalDef (id, b', ty))
467 | NoChange, Changed ty' -> Changed (sigma, LocalDef (id, b, ty'))
468 | Changed b', Changed ty' -> Changed (sigma, LocalDef (id, b', ty'))
469
470 let bind_change_occurrences occs = function
471 | None -> None
472 | Some c -> Some (Redexpr.out_with_occurrences (occs,c))
473
474 (* The following two tactics apply an arbitrary
475 reduction function either to the conclusion or to a
476 certain hypothesis *)
477
478 (** Tactic reduction modulo evars (for universes essentially) *)
479
480 let e_change_in_concl ~cast ~check (redfun, sty) =
481 Proofview.Goal.enter begin fun gl ->
482 let sigma = Proofview.Goal.sigma gl in
483 let env = Proofview.Goal.env gl in
484 let concl = Proofview.Goal.concl gl in
485 match redfun env sigma concl with
486 | NoChange -> Proofview.tclUNIT ()
487 | Changed (sigma, c') ->
488 Proofview.tclTHEN (Proofview.Unsafe.tclEVARS sigma)
489 (convert_concl ~cast ~check c' sty)
490 end
491
492 let e_change_in_hyp ~check ~reorder redfun (id,where) =
493 Proofview.Goal.enter begin fun gl ->
494 let sigma = Proofview.Goal.sigma gl in
495 let hyp = Tacmach.pf_get_hyp id gl in
496 match e_pf_change_decl redfun where (Proofview.Goal.env gl) sigma hyp with
497 | NoChange -> Proofview.tclUNIT ()
498 | Changed (sigma, c) ->
499 Proofview.tclTHEN (Proofview.Unsafe.tclEVARS sigma)
500 (convert_hyp ~check ~reorder c)
501 end
502
503 let e_change_option ~check ~reorder (redfun, sty) = function
504 | None ->
505 e_change_in_concl ~cast:true ~check (redfun, sty)
506 | Some id ->
507 let redfun _ env sigma c = redfun env sigma c in
508 e_change_in_hyp ~check ~reorder redfun id
509
510 type hyp_conversion =
511 | AnyHypConv (** Arbitrary conversion *)
512 | StableHypConv (** Does not introduce new dependencies on variables *)
513 | LocalHypConv (** Same as above plus no dependence on the named environment *)
514
515 let e_change_in_hyps ~check ~reorder f args = match args with
516 | [] -> Proofview.tclUNIT ()
517 | _ :: _ ->
518 Proofview.Goal.enter begin fun gl ->
519 let env = Proofview.Goal.env gl in
520 let sigma = Proofview.Goal.sigma gl in
521 let (env, sigma) = match reorder with
522 | LocalHypConv ->
523 (* If the reduction function is known not to depend on the named
524 context, then we can perform it in parallel. *)
525 let fold accu arg =
526 let (id, redfun) = f arg in
527 let old = try Id.Map.find id accu with Not_found -> [] in
528 Id.Map.add id (redfun :: old) accu
529 in
530 let reds = List.fold_left fold Id.Map.empty args in
531 let evdref = ref sigma in
532 let map d =
533 let id = NamedDecl.get_id d in
534 match Id.Map.find id reds with
535 | reds ->
536 let d = EConstr.of_named_decl d in
537 let fold redfun (sigma, d) = match redfun env sigma d with
538 | NoChange -> sigma, d
539 | Changed (sigma, d) -> sigma, d
540 in
541 let (sigma, d) = List.fold_right fold reds (sigma, d) in
542 let () = evdref := sigma in
543 EConstr.Unsafe.to_named_decl d
544 | exception Not_found -> d
545 in
546 let sign = Environ.map_named_val map (Environ.named_context_val env) in
547 let env = reset_with_named_context sign env in
548 (env, !evdref)
549 | StableHypConv | AnyHypConv ->
550 let reorder = reorder == AnyHypConv in
551 let fold (env, sigma) arg =
552 let (id, redfun) = f arg in
553 let hyp =
554 try lookup_named id env
555 with Not_found ->
556 raise (RefinerError (env, sigma, NoSuchHyp id))
557 in
558 match redfun env sigma hyp with
559 | NoChange -> (env, sigma)
560 | Changed (sigma, d) ->
561 let sign = Logic.convert_hyp ~check ~reorder env sigma d in
562 let env = reset_with_named_context sign env in
563 (env, sigma)
564 in
565 List.fold_left fold (env, sigma) args
566 in
567 let ty = Proofview.Goal.concl gl in
568 Proofview.Unsafe.tclEVARS sigma
569 <*>
570 Refine.refine_with_principal ~typecheck:false begin fun sigma ->
571 let sigma, ev = Evarutil.new_evar env sigma ty in
572 sigma, ev, Some (fst @@ destEvar sigma ev)
573 end
574 end
575
576 let e_reduct_in_concl ~cast ~check (redfun, sty) =
577 let redfun env sigma c = Changed (redfun env sigma c) in
578 e_change_in_concl ~cast ~check (redfun, sty)
579
580 let reduct_in_concl ~cast ~check (redfun, sty) =
581 let redfun env sigma c = Changed (sigma, redfun env sigma c) in
582 e_change_in_concl ~cast ~check (redfun, sty)
583
584 let e_reduct_in_hyp ~check ~reorder redfun (id, where) =
585 let redfun _ env sigma c = Changed (redfun env sigma c) in
586 e_change_in_hyp ~check ~reorder redfun (id, where)
587
588 let reduct_in_hyp ~check ~reorder redfun (id, where) =
589 let redfun _ env sigma c = Changed (sigma, redfun env sigma c) in
590 e_change_in_hyp ~check ~reorder redfun (id, where)
591
592 let e_reduct_option ~check redfun = function
593 | Some id -> e_reduct_in_hyp ~check ~reorder:check (fst redfun) id
594 | None -> e_reduct_in_concl ~cast:true ~check redfun
595
596 let reduct_option ~check (redfun, sty) where =
597 let redfun env sigma c = (sigma, redfun env sigma c) in
598 e_reduct_option ~check (redfun, sty) where
599
600 type change_arg = Ltac_pretype.patvar_map -> env -> evar_map -> (evar_map * EConstr.constr) Tacred.change
601
602 let make_change_arg c pats env sigma =
603 Changed (sigma, replace_vars sigma (Id.Map.bindings pats) c) (* TODO: fast-path *)
604
605 let is_partial_template_head env sigma c =
606 let (hd, args) = decompose_app sigma c in
607 match destRef sigma hd with
608 | (ConstructRef (ind, _) | IndRef ind), _ ->
609 let (mib, _) = Inductive.lookup_mind_specif env ind in
610 begin match mib.mind_template with
611 | None -> false
612 | Some _ -> Array.length args < mib.mind_nparams
613 end
614 | (VarRef _ | ConstRef _), _ -> false
615 | exception DestKO -> false
616
617 let check_types env sigma mayneedglobalcheck deep newc origc =
618 let t1 = Retyping.get_type_of env sigma newc in
619 if deep then begin
620 let () =
621 (* When changing a partially applied template term in a context, one must
622 be careful to resynthetize the constraints as the implicit levels from
623 the arguments are not written in the term. *)
624 if is_partial_template_head env sigma newc ||
625 is_partial_template_head env sigma origc then
626 mayneedglobalcheck := true
627 in
628 let t2 = Retyping.get_type_of env sigma origc in
629 let sigma, t2 = Evarsolve.refresh_universes
630 ~onlyalg:true (Some false) env sigma t2 in
631 match infer_conv ~pb:Conversion.CUMUL env sigma t1 t2 with
632 | None ->
633 if
634 isSort sigma (whd_all env sigma t1) &&
635 isSort sigma (whd_all env sigma t2)
636 then (mayneedglobalcheck := true; sigma)
637 else
638 TacticErrors.convert_incompatible_types env sigma t2 t1
639 | Some sigma -> sigma
640 end
641 else
642 if not (isSort sigma (whd_all env sigma t1)) then
643 TacticErrors.convert_not_a_type ()
644 else sigma
645
646 (* Now we introduce different instances of the previous tacticals *)
647 let change_and_check cv_pb mayneedglobalcheck deep t env sigma c = match t env sigma with
648 | NoChange -> NoChange
649 | Changed (sigma, t') ->
650 let sigma = check_types env sigma mayneedglobalcheck deep t' c in
651 match infer_conv ~pb:cv_pb env sigma t' c with
652 | None -> TacticErrors.not_convertible ()
653 | Some sigma -> Changed (sigma, t')
654
655 (* Use cumulativity only if changing the conclusion not a subterm *)
656 let change_on_subterm ~check cv_pb deep t where env sigma c =
657 let mayneedglobalcheck = ref false in
658 let ans = match where with
659 | None ->
660 if check then
661 change_and_check cv_pb mayneedglobalcheck deep (t Id.Map.empty) env sigma c
662 else
663 t Id.Map.empty env sigma
664 | Some occl ->
665 e_contextually false occl
666 (fun subst ->
667 if check then
668 change_and_check Conversion.CONV mayneedglobalcheck true (t subst)
669 else
670 fun env sigma _c -> t subst env sigma) env sigma c in
671 match ans with
672 | NoChange -> NoChange
673 | Changed (sigma, c) ->
674 let sigma = if !mayneedglobalcheck then
675 begin
676 try fst (Typing.type_of env sigma c)
677 with e when noncritical e ->
678 TacticErrors.replacement_ill_typed e
679 end else sigma
680 in
681 Changed (sigma, c)
682
683 let change_in_concl ~check occl t =
684 (* No need to check in e_change_in_concl, the check is done in change_on_subterm *)
685 e_change_in_concl ~cast:false ~check:false
686 ((change_on_subterm ~check Conversion.CUMUL false t occl),DEFAULTcast)
687
688 let change_in_hyp ~check occl t id =
689 (* Same as above *)
690 e_change_in_hyp ~check:false ~reorder:check (fun x -> change_on_subterm ~check Conversion.CONV x t occl) id
691
692 let concrete_clause_of enum_hyps cl = match cl.onhyps with
693 | None ->
694 let f id = (id, AllOccurrences, InHyp) in
695 List.map f (enum_hyps ())
696 | Some l ->
697 List.map (fun ((occs, id), w) -> (id, occs, w)) l
698
699 let change ~check chg c cls =
700 Proofview.Goal.enter begin fun gl ->
701 let hyps = concrete_clause_of (fun () -> Tacmach.pf_ids_of_hyps gl) cls in
702 begin match cls.concl_occs with
703 | NoOccurrences -> Proofview.tclUNIT ()
704 | occs -> change_in_concl ~check (bind_change_occurrences occs chg) c
705 end
706 <*>
707 let f (id, occs, where) =
708 let occl = bind_change_occurrences occs chg in
709 let redfun deep env sigma t = change_on_subterm ~check Conversion.CONV deep c occl env sigma t in
710 let redfun env sigma d = e_pf_change_decl redfun where env sigma d in
711 (id, redfun)
712 in
713 let reorder = if check then AnyHypConv else StableHypConv in
714 (* Don't check, we do it already in [change_on_subterm]. *)
715 e_change_in_hyps ~check:false ~reorder f hyps
716 end
717
718 let change_concl t =
719 change_in_concl ~check:true None (make_change_arg t)
720
721 let red_product_exn env sigma c = match red_product env sigma c with
722 | None -> user_err Pp.(str "No head constant to reduce.")
723 | Some c -> c
724
725 (* Pour usage interne (le niveau User est pris en compte par reduce) *)
726 let red_in_concl = reduct_in_concl ~cast:true ~check:false (red_product_exn,DEFAULTcast)
727 let red_in_hyp = reduct_in_hyp ~check:false ~reorder:false red_product_exn
728 let red_option = reduct_option ~check:false (red_product_exn,DEFAULTcast)
729 let hnf_in_concl = reduct_in_concl ~cast:true ~check:false (hnf_constr,DEFAULTcast)
730 let hnf_in_hyp = reduct_in_hyp ~check:false ~reorder:false hnf_constr
731 let hnf_option = reduct_option ~check:false (hnf_constr,DEFAULTcast)
732 let simpl_in_concl = reduct_in_concl ~cast:true ~check:false (simpl,DEFAULTcast)
733 let simpl_in_hyp = reduct_in_hyp ~check:false ~reorder:false simpl
734 let simpl_option = reduct_option ~check:false (simpl,DEFAULTcast)
735 let normalise_in_concl = reduct_in_concl ~cast:true ~check:false (compute,DEFAULTcast)
736 let normalise_in_hyp = reduct_in_hyp ~check:false ~reorder:false compute
737 let normalise_option = reduct_option ~check:false (compute,DEFAULTcast)
738 let normalise_vm_in_concl = reduct_in_concl ~cast:true ~check:false (Redexpr.cbv_vm,VMcast)
739 let unfold_in_concl loccname = reduct_in_concl ~cast:true ~check:false (unfoldn loccname,DEFAULTcast)
740 let unfold_in_hyp loccname = reduct_in_hyp ~check:false ~reorder:false (unfoldn loccname)
741 let unfold_option loccname = reduct_option ~check:false (unfoldn loccname,DEFAULTcast)
742 let pattern_option l = e_change_option ~check:false ~reorder:false (pattern_occs l,DEFAULTcast)
743
744 (* The main reduction function *)
745
746 let is_local_flag env flags =
747 if flags.rDelta then false
748 else
749 let check = function
750 | Evaluable.EvalVarRef _ -> false
751 | Evaluable.EvalConstRef c -> Id.Set.is_empty (Environ.vars_of_global env (GlobRef.ConstRef c))
752 | Evaluable.EvalProjectionRef c -> false (* FIXME *)
753 in
754 List.for_all check flags.rConst
755
756 let is_local_unfold env flags =
757 let check (_, c) = match c with
758 | Evaluable.EvalVarRef _ -> false
759 | Evaluable.EvalConstRef c -> Id.Set.is_empty (Environ.vars_of_global env (GlobRef.ConstRef c))
760 | Evaluable.EvalProjectionRef c -> false (* FIXME *)
761 in
762 List.for_all check flags
763
764 let change_of_red_expr_val ?occs redexp =
765 let (redfun, kind) = Redexpr.reduction_of_red_expr_val ?occs redexp in
766 let redfun env sigma c = Changed (redfun env sigma c) in (* TODO: fast-path *)
767 (redfun, kind)
768
769 let reduce redexp cl =
770 let trace env sigma =
771 let open Printer in
772 let pr = ((fun e -> pr_econstr_env e), (fun e -> pr_leconstr_env e), pr_evaluable_reference, (fun e -> pr_constr_pattern_env e), int, Redexpr.pr_glob_user_red_expr) in
773 Pp.(hov 2 (Ppred.pr_red_expr_env env sigma pr str redexp))
774 in
775 Proofview.Goal.enter begin fun gl ->
776 let env = Proofview.Goal.env gl in
777 let sigma = Proofview.Goal.sigma gl in
778 let hyps = concrete_clause_of (fun () -> Tacmach.pf_ids_of_hyps gl) cl in
779 let nbcl = (if cl.concl_occs = NoOccurrences then 0 else 1) + List.length hyps in
780 let check = match redexp with Fold _ | Pattern _ -> true | _ -> false in
781 let reorder = match redexp with
782 | Fold _ | Pattern _ -> AnyHypConv
783 | Simpl (flags, _) | Cbv flags | Cbn flags | Lazy flags ->
784 if is_local_flag env flags then LocalHypConv else StableHypConv
785 | Unfold flags ->
786 if is_local_unfold env flags then LocalHypConv else StableHypConv
787 | Red | Hnf | CbvVm _ | CbvNative _ -> StableHypConv
788 | ExtraRedExpr _ -> StableHypConv (* Should we be that lenient ?*)
789 | UserRed _ -> AnyHypConv (* TODO: ask it in the API *)
790 in
791 let redexp = Redexpr.eval_red_expr env redexp in
792 Proofview.Trace.name_tactic (fun () -> trace env sigma) begin
793 begin match cl.concl_occs with
794 | NoOccurrences -> Proofview.tclUNIT ()
795 | occs ->
796 let occs = Redexpr.out_occurrences occs in
797 let redfun = change_of_red_expr_val ~occs:(occs, nbcl) redexp in
798 e_change_in_concl ~cast:true ~check redfun
799 end
800 <*>
801 let f (id, occs, where) =
802 let occs = Redexpr.out_occurrences occs in
803 let (redfun, _) = change_of_red_expr_val ~occs:(occs, nbcl) redexp in
804 let redfun _ env sigma c = redfun env sigma c in
805 let redfun env sigma d = e_pf_change_decl redfun where env sigma d in
806 (id, redfun)
807 in
808 e_change_in_hyps ~check ~reorder f hyps
809 end
810 end
811
812 let unfold_constr = function
813 | GlobRef.ConstRef sp -> unfold_in_concl [(AllOccurrences, EvalConstRef sp)]
814 | GlobRef.VarRef id -> unfold_in_concl [(AllOccurrences, EvalVarRef id)]
815 | _ -> TacticErrors.not_unfoldable ()
816
817 (*******************************************)
818 (* Introduction tactics *)
819 (*******************************************)
820
821 (** This function is supposed to be compatible with an iteration of [find_name] above.
822 As [default_id] checks the sort of the type to build hyp names,
823 we maintain an environment to be able to type dependent hyps. *)
824 let find_intro_names env0 sigma ctxt =
825 let _, res, _ = List.fold_right
826 (fun decl acc ->
827 let env,idl,avoid = acc in
828 let name = fresh_id_in_env avoid (default_id env sigma decl) env0 in
829 let newenv = push_rel decl env in
830 (newenv, name :: idl, Id.Set.add name avoid))
831 ctxt (env0, [], Id.Set.empty) in
832 List.rev res
833
834 let build_intro_tac id dest tac = match dest with
835 | MoveLast -> Tacticals.tclTHEN (introduction id) (tac id)
836 | dest -> Tacticals.tclTHENLIST
837 [introduction id; move_hyp id dest; tac id]
838
839 let rec intro_then_gen name_flag move_flag ~force ~dep tac =
840 let open Context.Rel.Declaration in
841 Proofview.Goal.enter begin fun gl ->
842 let sigma = Proofview.Goal.sigma gl in
843 let env = Proofview.Goal.env gl in
844 let concl = Proofview.Goal.concl gl in
845 match EConstr.kind sigma concl with
846 | Prod (name,t,u) when not dep || not (noccurn sigma 1 u) ->
847 let name = find_name false (LocalAssum (name,t)) name_flag gl in
848 build_intro_tac name move_flag tac
849 | LetIn (name,b,t,u) when not dep || not (noccurn sigma 1 u) ->
850 let name = find_name false (LocalDef (name,b,t)) name_flag gl in
851 build_intro_tac name move_flag tac
852 | Evar ev when force ->
853 let name = find_name false (LocalAssum (anonR,concl)) name_flag gl in
854 let sigma, t = Evardefine.define_evar_as_product env sigma ~name ev in
855 Tacticals.tclTHEN
856 (Proofview.Unsafe.tclEVARS sigma)
857 (intro_then_gen name_flag move_flag ~force ~dep tac)
858 | _ ->
859 begin if not force
860 then
861 let info = Exninfo.reify () in
862 Proofview.tclZERO ~info (RefinerError (env, sigma, IntroNeedsProduct))
863 (* Note: red_in_concl includes betaiotazeta and this was like *)
864 (* this since at least V6.3 (a pity *)
865 (* that intro do betaiotazeta only when reduction is needed; and *)
866 (* probably also a pity that intro does zeta *)
867 else Proofview.tclUNIT ()
868 end <*>
869 Proofview.tclORELSE
870 (Tacticals.tclTHEN hnf_in_concl
871 (intro_then_gen name_flag move_flag ~force:false ~dep tac))
872 begin function (e, info) -> match e with
873 | RefinerError (env, sigma, IntroNeedsProduct) ->
874 Tacticals.tclZEROMSG ~info (str "No product even after head-reduction.")
875 | e -> Proofview.tclZERO ~info e
876 end
877 end
878
879 let drop_intro_name (_ : Id.t) = Proofview.tclUNIT ()
880
881 let intro_gen n m ~force ~dep = intro_then_gen n m ~force ~dep drop_intro_name
882 let intro_mustbe_force id = intro_gen (NamingMustBe (CAst.make id)) MoveLast ~force:true ~dep:false
883 let intro_using_then id = intro_then_gen (NamingBasedOn (id, Id.Set.empty)) MoveLast ~force:false ~dep:false
884 let intro_using id = intro_using_then id drop_intro_name
885
886 let intro_then = intro_then_gen (NamingAvoid Id.Set.empty) MoveLast ~force:false ~dep:false
887 let intro = intro_then drop_intro_name
888 let introf = intro_gen (NamingAvoid Id.Set.empty) MoveLast ~force:true ~dep:false
889 let intro_avoiding l = intro_gen (NamingAvoid l) MoveLast ~force:false ~dep:false
890
891 let intro_move_avoid idopt avoid hto = match idopt with
892 | None -> intro_gen (NamingAvoid avoid) hto ~force:true ~dep:false
893 | Some id -> intro_gen (NamingMustBe (CAst.make id)) hto ~force:true ~dep:false
894
895 let intro_move idopt hto = intro_move_avoid idopt Id.Set.empty hto
896
897 (**** Multiple introduction tactics ****)
898
899 let rec intros_mustbe_force = function
900 | [] -> Proofview.tclUNIT()
901 | str::l -> Tacticals.tclTHEN (intro_mustbe_force str) (intros_mustbe_force l)
902
903 let rec intros_using_then_helper tac acc = function
904 | [] -> tac (List.rev acc)
905 | str::l -> intro_using_then str (fun str' -> intros_using_then_helper tac (str'::acc) l)
906 let intros_using_then l tac = intros_using_then_helper tac [] l
907
908 let is_overbound bound n = match bound with None -> false | Some p -> n >= p
909
910 let intro_forthcoming_last_then_gen avoid dep_flag bound n tac =
911 let open RelDecl in
912 Proofview.Goal.enter begin fun gl ->
913 let env = Proofview.Goal.env gl in
914 let sigma = Proofview.Goal.sigma gl in
915 let concl = Proofview.Goal.concl gl in
916 let relevance = Proofview.Goal.relevance gl in
917 let avoid =
918 let avoid' = ids_of_named_context_val (named_context_val env) in
919 if Id.Set.is_empty avoid then avoid' else Id.Set.union avoid' avoid
920 in
921 let rec decompose env avoid n concl subst decls ndecls =
922 let decl =
923 if is_overbound bound n then None
924 else match EConstr.kind sigma concl with
925 | Prod (na, t, u) when not dep_flag || not (noccurn sigma 1 u) ->
926 Some (LocalAssum (na, t), u)
927 | LetIn (na, b, t, u) when not dep_flag || not (noccurn sigma 1 u) ->
928 Some (LocalDef (na, b, t), u)
929 | _ -> None
930 in
931 match decl with
932 | None -> ndecls, decls, Vars.esubst Vars.lift_substituend subst concl
933 | Some (decl, concl) ->
934 let id = default_id env sigma decl in
935 let id = next_ident_away_in_goal (Global.env ()) id avoid in
936 let avoid = Id.Set.add id avoid in
937 let env = EConstr.push_rel decl env in
938 let ndecl = NamedDecl.of_rel_decl (fun _ -> id) decl in
939 let ndecl = NamedDecl.map_constr (fun c -> Vars.esubst Vars.lift_substituend subst c) ndecl in
940 let subst = Esubst.subs_cons (make_substituend @@ mkVar id) subst in
941 decompose env avoid (n + 1) concl subst (decl :: decls) (ndecl :: ndecls)
942 in
943 let (ndecls, decls, nconcl) = decompose env avoid n concl (Esubst.subs_id 0) [] [] in
944 let ids = List.map NamedDecl.get_id ndecls in
945 if List.is_empty ids then tac []
946 else Refine.refine_with_principal ~typecheck:false begin fun sigma ->
947 let ctx = named_context_val env in
948 let nctx = List.fold_right push_named_context_val ndecls ctx in
949 let inst = SList.defaultn (List.length @@ Environ.named_context env) SList.empty in
950 let rels = List.init (List.length decls) (fun i -> mkRel (i + 1)) in
951 let ninst = List.fold_right (fun c accu -> SList.cons c accu) rels inst in
952 let (sigma, ev) = new_pure_evar nctx sigma ~relevance nconcl in
953 (sigma, it_mkLambda_or_LetIn (mkEvar (ev, ninst)) decls,
954 Some ev)
955 end <*> tac ids
956 end
957
958 let intros =
959 intro_forthcoming_last_then_gen Id.Set.empty false None 0 (fun _ -> tclIDTAC)
960
961 let intro_forthcoming_then_gen avoid move_flag ~dep bound n tac = match move_flag with
962 | MoveLast ->
963 (* Fast path *)
964 intro_forthcoming_last_then_gen avoid dep bound n tac
965 | MoveFirst | MoveAfter _ | MoveBefore _ ->
966 let rec aux n ids =
967 (* Note: we always use the bound when there is one for "*" and "**" *)
968 if not (is_overbound bound n) then
969 Proofview.tclORELSE
970 begin
971 intro_then_gen (NamingAvoid avoid) move_flag ~force:false ~dep
972 (fun id -> aux (n+1) (id::ids))
973 end
974 begin function (e, info) -> match e with
975 | RefinerError (env, sigma, IntroNeedsProduct) ->
976 tac ids
977 | e -> Proofview.tclZERO ~info e
978 end
979 else
980 tac ids
981 in
982 aux n []
983
984 let intro_replacing id =
985 Proofview.Goal.enter begin fun gl ->
986 let env, sigma = Proofview.Goal.(env gl, sigma gl) in
987 let hyps = Proofview.Goal.hyps gl in
988 let next_hyp = get_next_hyp_position env sigma id hyps in
989 Tacticals.tclTHENLIST [
990 clear_for_replacing [id];
991 introduction id;
992 move_hyp id next_hyp;
993 ]
994 end
995
996 (* We have e.g. [x, y, y', x', y'' |- forall y y' y'', G] and want to
997 reintroduce y, y,' y''. Note that we have to clear y, y' and y''
998 before introducing y because y' or y'' can e.g. depend on old y. *)
999
1000 (* This version assumes that replacement is actually possible *)
1001 (* (ids given in the introduction order) *)
1002 (* We keep a sub-optimality in cleaing for compatibility with *)
1003 (* the behavior of inversion *)
1004 let intros_possibly_replacing ids =
1005 let suboptimal = true in
1006 Proofview.Goal.enter begin fun gl ->
1007 let env, sigma = Proofview.Goal.(env gl, sigma gl) in
1008 let hyps = Proofview.Goal.hyps gl in
1009 let posl = List.map (fun id -> (id, get_next_hyp_position env sigma id hyps)) ids in
1010 Tacticals.tclTHEN
1011 (Tacticals.tclMAP (fun id ->
1012 Tacticals.tclTRY (clear_for_replacing [id]))
1013 (if suboptimal then ids else List.rev ids))
1014 (Tacticals.tclMAP (fun (id,pos) ->
1015 Tacticals.tclORELSE (intro_move (Some id) pos) (intro_using id))
1016 posl)
1017 end
1018
1019 (* This version assumes that replacement is actually possible *)
1020 let intros_replacing ids =
1021 Proofview.Goal.enter begin fun gl ->
1022 let hyps = Proofview.Goal.hyps gl in
1023 let env, sigma = Proofview.Goal.(env gl, sigma gl) in
1024 let posl = List.map (fun id -> (id, get_next_hyp_position env sigma id hyps)) ids in
1025 Tacticals.tclTHEN
1026 (clear_for_replacing ids)
1027 (Tacticals.tclMAP (fun (id,pos) -> intro_move (Some id) pos) posl)
1028 end
1029
1030 (* The standard for implementing Automatic Introduction *)
1031 let auto_intros_tac ids =
1032 let fold used = function
1033 | Name id -> Id.Set.add id used
1034 | Anonymous -> used
1035 in
1036 let avoid = NamingAvoid (List.fold_left fold Id.Set.empty ids) in
1037 let naming = function
1038 | Name id -> NamingMustBe CAst.(make id)
1039 | Anonymous -> avoid
1040 in
1041 Tacticals.tclMAP (fun name -> intro_gen (naming name) MoveLast ~force:true ~dep:false) (List.rev ids)
1042
1043 (* User-level introduction tactics *)
1044
1045 let lookup_hypothesis_as_renamed env sigma ccl = function
1046 | AnonHyp n -> Detyping.lookup_index_as_renamed env sigma ccl n
1047 | NamedHyp id -> Detyping.lookup_name_as_displayed env sigma ccl id.CAst.v
1048
1049 let lookup_hypothesis_as_renamed_gen red h gl =
1050 let env = Proofview.Goal.env gl in
1051 let rec aux ccl =
1052 match lookup_hypothesis_as_renamed env (Proofview.Goal.sigma gl) ccl h with
1053 | None when red ->
1054 begin match red_product env (Proofview.Goal.sigma gl) ccl with
1055 | None -> None
1056 | Some c -> aux c
1057 end
1058 | x -> x
1059 in
1060 aux (Proofview.Goal.concl gl)
1061
1062 let is_quantified_hypothesis id gl =
1063 match lookup_hypothesis_as_renamed_gen false (NamedHyp (CAst.make id)) gl with
1064 | Some _ -> true
1065 | None -> false
1066
1067 let warn_deprecated_intros_until_0 =
1068 CWarnings.create ~name:"deprecated-intros-until-0" ~category:CWarnings.CoreCategories.tactics
1069 (fun () ->
1070 strbrk"\"intros until 0\" is deprecated, use \"intros *\"; instead of \"induction 0\" and \"destruct 0\" use explicitly a name.\"")
1071
1072 let depth_of_quantified_hypothesis red h gl =
1073 if h = AnonHyp 0 then warn_deprecated_intros_until_0 ();
1074 match lookup_hypothesis_as_renamed_gen red h gl with
1075 | Some depth -> depth
1076 | None -> TacticErrors.no_quantified_hypothesis h red
1077
1078 let intros_until_gen red h =
1079 Proofview.Goal.enter begin fun gl ->
1080 let n = depth_of_quantified_hypothesis red h gl in
1081 Tacticals.tclDO n (if red then introf else intro)
1082 end
1083
1084 let intros_until_id id = intros_until_gen false (NamedHyp (CAst.make id))
1085 let intros_until_n_gen red n = intros_until_gen red (AnonHyp n)
1086
1087 let intros_until = intros_until_gen true
1088 let intros_until_n = intros_until_n_gen true
1089
1090 let tclCHECKVAR id =
1091 Proofview.Goal.enter begin fun gl ->
1092 let _ = Tacmach.pf_get_hyp id gl in
1093 Proofview.tclUNIT ()
1094 end
1095
1096 let try_intros_until_id_check id =
1097 Tacticals.tclORELSE (intros_until_id id) (tclCHECKVAR id)
1098
1099 let try_intros_until tac = function
1100 | NamedHyp {CAst.v=id} -> Tacticals.tclTHEN (try_intros_until_id_check id) (tac id)
1101 | AnonHyp n -> Tacticals.tclTHEN (intros_until_n n) (Tacticals.onLastHypId tac)
1102
1103 let rec intros_move = function
1104 | [] -> Proofview.tclUNIT ()
1105 | (hyp,destopt) :: rest ->
1106 Tacticals.tclTHEN (intro_gen (NamingMustBe (CAst.make hyp)) destopt ~force:false ~dep:false)
1107 (intros_move rest)
1108
1109 (* Apply a tactic on a quantified hypothesis, an hypothesis in context
1110 or a term with bindings *)
1111
1112 let tactic_infer_flags with_evar = Pretyping.{
1113 use_coercions = true;
1114 use_typeclasses = UseTC;
1115 solve_unification_constraints = true;
1116 fail_evar = not with_evar;
1117 expand_evars = true;
1118 program_mode = false;
1119 poly = PolyFlags.default;
1120 undeclared_evars_rr = false;
1121 unconstrained_sorts = false;
1122 }
1123
1124 type evars_flag = bool (* true = pose evars false = fail on evars *)
1125 type rec_flag = bool (* true = recursive false = not recursive *)
1126 type advanced_flag = bool (* true = advanced false = basic *)
1127 type clear_flag = bool option (* true = clear hyp, false = keep hyp, None = use default *)
1128
1129 type 'a core_destruction_arg =
1130 | ElimOnConstr of 'a
1131 | ElimOnIdent of lident
1132 | ElimOnAnonHyp of int
1133
1134 type equality_position_on_elim =
1135 | UnknownPosition
1136 | AtPosition of int
1137
1138 type 'a destruction_arg =
1139 clear_flag * 'a core_destruction_arg
1140
1141 let onInductionArg tac = function
1142 | clear_flag,ElimOnConstr cbl ->
1143 tac clear_flag cbl
1144 | clear_flag,ElimOnAnonHyp n ->
1145 Tacticals.tclTHEN
1146 (intros_until_n n)
1147 (Tacticals.onLastHyp (fun c -> tac clear_flag (c,NoBindings)))
1148 | clear_flag,ElimOnIdent {CAst.v=id} ->
1149 (* A quantified hypothesis *)
1150 Tacticals.tclTHEN
1151 (try_intros_until_id_check id)
1152 (tac clear_flag (mkVar id,NoBindings))
1153
1154 let map_destruction_arg f sigma = function
1155 | clear_flag,ElimOnConstr g -> let sigma,x = f sigma g in (sigma, (clear_flag,ElimOnConstr x))
1156 | clear_flag,ElimOnAnonHyp n as x -> (sigma,x)
1157 | clear_flag,ElimOnIdent id as x -> (sigma,x)
1158
1159
1160 let finish_evar_resolution ?(flags=Pretyping.all_and_fail_flags) env current_sigma (pending,c) =
1161 let sigma = Pretyping.solve_remaining_evars flags env current_sigma ?initial:pending in
1162 (sigma, nf_evar sigma c)
1163
1164 let finish_delayed_evar_resolution with_evars env sigma f =
1165 let (sigma', (c, lbind)) = f env sigma in
1166 let flags = tactic_infer_flags with_evars in
1167 let (sigma', c) = finish_evar_resolution ~flags env sigma' (Some sigma,c) in
1168 (sigma', (c, lbind))
1169
1170 let force_destruction_arg with_evars env sigma c =
1171 map_destruction_arg (finish_delayed_evar_resolution with_evars env) sigma c
1172
1173 (****************************************)
1174 (* tactic "cut" (actually modus ponens) *)
1175 (****************************************)
1176
1177 let cut c =
1178 Proofview.Goal.enter begin fun gl ->
1179 let env = Proofview.Goal.env gl in
1180 let sigma = Proofview.Goal.sigma gl in
1181 let concl = Proofview.Goal.concl gl in
1182 (* Backward compat: ensure that [c] is well-typed. Plus we need to
1183 know the relevance *)
1184 match Typing.sort_of env sigma c with
1185 | exception e when noncritical e ->
1186 let _, info = Exninfo.capture e in
1187 Tacticals.tclZEROMSG ~info (str "Not a proposition or a type.")
1188 | sigma, s ->
1189 let r = ESorts.relevance_of_sort s in
1190 let id = next_name_away_with_default "H" Anonymous (Tacmach.pf_ids_set_of_hyps gl) in
1191 Proofview.tclTHEN (Proofview.Unsafe.tclEVARS sigma)
1192 (Refine.refine_with_principal ~typecheck:false begin fun h ->
1193 let (h, f) = Evarutil.new_evar env h (mkArrow c r concl) in
1194 let ev = fst @@ destEvar h f in
1195 let (h, x) = Evarutil.new_evar env h c in
1196 let f = mkLetIn (make_annot (Name id) r, x, c, mkApp (f, [|mkRel 1|])) in
1197 (h, f, Some ev)
1198 end)
1199 end
1200
1201 let check_unresolved_evars_of_metas sigma clenv =
1202 (* This checks that Metas turned into Evars by *)
1203 (* Refiner.pose_all_metas_as_evars are resolved *)
1204 let metas = clenv_meta_list clenv in
1205 let iter mv () = match Unification.Meta.meta_opt_fvalue metas mv with
1206 | Some c ->
1207 begin match Constr.kind (EConstr.Unsafe.to_constr c.rebus) with
1208 | Evar (evk,_) when Evd.is_undefined (clenv_evd clenv) evk
1209 && not (Evd.mem sigma evk) ->
1210 let na = Unification.Meta.meta_name metas mv in
1211 let id = match na with Name id -> id | _ -> anomaly (Pp.str "unnamed dependent meta.") in
1212 TacticErrors.cannot_find_instance id
1213 | _ -> ()
1214 end
1215 | None -> ()
1216 in
1217 Unification.Meta.fold iter metas ()
1218
1219 let do_replace id = function
1220 | NamingMustBe {CAst.v=id'} when Option.equal Id.equal id (Some id') -> true
1221 | _ -> false
1222
1223 (* For a clenv expressing some lemma [C[?1:T1,...,?n:Tn] : P] and some
1224 goal [G], [clenv_refine_in] returns [n+1] subgoals, the [n] last
1225 ones (resp [n] first ones if [sidecond_first] is [true]) being the
1226 [Ti] and the first one (resp last one) being [G] whose hypothesis
1227 [id] is replaced by P using the proof given by [tac] *)
1228
1229 let clenv_refine_in with_evars targetid replace env sigma0 clenv =
1230 let clenv = Clenv.clenv_pose_dependent_evars ~with_evars clenv in
1231 let evd = Typeclasses.resolve_typeclasses ~fail:(not with_evars) env (clenv_evd clenv) in
1232 let clenv = Clenv.update_clenv_evd clenv evd (Clenv.clenv_meta_list clenv) in
1233 let new_hyp_typ = clenv_type clenv in
1234 if not with_evars then check_unresolved_evars_of_metas sigma0 clenv;
1235 let [@ocaml.warning "-3"] exact_tac = Clenv.Internal.refiner clenv in
1236 let naming = NamingMustBe (CAst.make targetid) in
1237 Proofview.Unsafe.tclEVARS evd <*>
1238 Proofview.Goal.enter begin fun gl ->
1239 let id = find_name replace (LocalAssum (make_annot Anonymous Sorts.Relevant, new_hyp_typ)) naming gl in
1240 Tacticals.tclTHENLAST (internal_cut replace id new_hyp_typ <*> Proofview.cycle 1) exact_tac
1241 end
1242
1243
1244 (********************************************)
1245 (* Elimination tactics *)
1246 (********************************************)
1247
1248 let nth_arg i c = match i with
1249 | None -> List.last c
1250 | Some i -> List.nth c i
1251
1252 let index_of_ind_arg sigma t =
1253 let rec aux i j t = match EConstr.kind sigma t with
1254 | LetIn (_, _, _, t) -> aux i j t
1255 | Prod (_,t,u) ->
1256 (* heuristic *)
1257 if isInd sigma (fst (decompose_app sigma t)) then aux (Some j) (j+1) u
1258 else aux i (j+1) u
1259 | _ -> match i with
1260 | Some i -> i
1261 | None -> TacticErrors.cannot_find_inductive_argument ()
1262 in aux None 0 t
1263
1264 (*
1265 * Elimination tactic with bindings and using an arbitrary
1266 * elimination constant called elimc. This constant should end
1267 * with a clause (x:I)(P .. ), where P is a bound variable.
1268 * The term c is of type t, which is a product ending with a type
1269 * matching I, lbindc are the expected terms for c arguments
1270 *)
1271
1272 type eliminator =
1273 | ElimConstant of EConstr.constr * equality_position_on_elim
1274 (* Constant generated by a scheme function *)
1275 | ElimClause of EConstr.constr with_bindings
1276 (* Arbitrary expression provided by the user *)
1277
1278 let general_elim_clause0 with_evars flags (submetas, c, ty) elim =
1279 Proofview.Goal.enter begin fun gl ->
1280 let env = Proofview.Goal.env gl in
1281 let sigma = Proofview.Goal.sigma gl in
1282 let clause, bindings, index = match elim with
1283 | ElimConstant (elimc, i) ->
1284 let elimt = Retyping.get_type_of env sigma elimc in
1285 let elimt = Reductionops.whd_all env sigma elimt in
1286 let i = match i with
1287 | AtPosition i -> i
1288 | UnknownPosition -> index_of_ind_arg sigma elimt
1289 in
1290 (elimc, elimt), NoBindings, Some i
1291 | ElimClause (elimc, lbindelimc) ->
1292 let elimt = Retyping.get_type_of env sigma elimc in
1293 (elimc, elimt), lbindelimc, None
1294 in
1295 let elimclause = make_clenv_binding env sigma clause bindings in
1296 let indmv =
1297 try nth_arg index (clenv_arguments elimclause)
1298 with Failure _ | Invalid_argument _ -> TacticErrors.ill_formed_elimination_type ()
1299 in
1300 let elimclause = clenv_instantiate ~flags ~submetas indmv elimclause (c, ty) in
1301 Clenv.res_pf elimclause ~with_evars ~with_classes:true ~flags
1302 end
1303
1304 let general_elim_clause_in0 with_evars flags id (submetas, c, ty) elimc indarg =
1305 Proofview.Goal.enter begin fun gl ->
1306 let env = Proofview.Goal.env gl in
1307 let sigma = Proofview.Goal.sigma gl in
1308 let elimt = Retyping.get_type_of env sigma elimc in
1309 let elimt = Reductionops.whd_all env sigma elimt in
1310 let i = match indarg with
1311 | AtPosition i -> i
1312 | UnknownPosition -> index_of_ind_arg sigma elimt
1313 in
1314 let elimclause = mk_clenv_from env sigma (elimc, elimt) in
1315 let indmv =
1316 try nth_arg (Some i) (clenv_arguments elimclause)
1317 with Failure _ | Invalid_argument _ -> TacticErrors.ill_formed_elimination_type ()
1318 in
1319 (* Assumes that the metas of [c] are part of [sigma] already *)
1320 let hypmv =
1321 match List.remove Int.equal indmv (clenv_independent elimclause) with
1322 | [a] -> a
1323 | _ -> TacticErrors.ill_formed_elimination_type ()
1324 in
1325 let elimclause = clenv_instantiate ~flags ~submetas indmv elimclause (c, ty) in
1326 let hyp = mkVar id in
1327 let hyp_typ = Retyping.get_type_of env sigma hyp in
1328 let elimclause =
1329 try clenv_instantiate ~flags hypmv elimclause (hyp, hyp_typ)
1330 with PretypeError (env,evd,NoOccurrenceFound (op,_)) ->
1331 (* Set the hypothesis name in the message *)
1332 raise (PretypeError (env,evd,NoOccurrenceFound (op,Some id)))
1333 in
1334 let new_hyp_typ = clenv_type elimclause in
1335 if EConstr.eq_constr sigma hyp_typ new_hyp_typ then
1336 TacticErrors.nothing_to_rewrite id;
1337 clenv_refine_in with_evars id true env sigma elimclause
1338 end
1339
1340 let general_elim with_evars clear_flag (c, lbindc) elim =
1341 Proofview.Goal.enter begin fun gl ->
1342 let env = Proofview.Goal.env gl in
1343 let sigma = Proofview.Goal.sigma gl in
1344 let ct = Retyping.get_type_of env sigma c in
1345 let id = try Some (destVar sigma c) with DestKO -> None in
1346 let t = try snd (reduce_to_quantified_ind env sigma ct) with UserError _ -> ct in
1347 let indclause = make_clenv_binding env sigma (c, t) lbindc in
1348 let flags = elim_flags () in
1349 let metas = clenv_meta_list indclause in
1350 let submetas = (clenv_arguments indclause, metas) in
1351 Proofview.Unsafe.tclEVARS (clenv_evd indclause) <*>
1352 Tacticals.tclTHEN
1353 (general_elim_clause0 with_evars flags (submetas, c, clenv_type indclause) elim)
1354 (apply_clear_request clear_flag (use_clear_hyp_by_default ()) id)
1355 end
1356
1357 let general_elim_clause with_evars flags where arg elim indarg =
1358 match where with
1359 | None -> general_elim_clause0 with_evars flags arg (ElimConstant (elim, indarg))
1360 | Some id -> general_elim_clause_in0 with_evars flags id arg elim indarg
1361
1362 (* Case analysis tactics *)
1363
1364 let general_case_analysis_in_context with_evars clear_flag (c,lbindc) =
1365 Proofview.Goal.enter begin fun gl ->
1366 let sigma = Proofview.Goal.sigma gl in
1367 let env = Proofview.Goal.env gl in
1368 let concl = Proofview.Goal.concl gl in
1369 let state = Proofview.Goal.state gl in
1370 let ct = Retyping.get_type_of env sigma c in
1371 let (mind, _), t = reduce_to_quantified_ind env sigma ct in
1372 let dep =
1373 if dependent sigma c concl then true
1374 else default_case_analysis_dependence env mind
1375 in
1376 let id = try Some (destVar sigma c) with DestKO -> None in
1377 let indclause = make_clenv_binding env sigma (c, t) lbindc in
1378 let indclause = Clenv.clenv_pose_dependent_evars ~with_evars:true indclause in
1379 let argtype = clenv_type indclause in (* Guaranteed to be meta-free *)
1380 let tac =
1381 Proofview.tclEVARMAP >>= fun sigma ->
1382 let sigma = Evd.push_future_goals sigma in
1383 let (sigma, ev) = Evarutil.new_evar env sigma argtype in
1384 let _, sigma = Evd.pop_future_goals sigma in
1385 let evk, _ = destEvar sigma ev in
1386 let indclause = Clenv.update_clenv_evd indclause sigma (Clenv.clenv_meta_list indclause) in
1387 Proofview.Unsafe.tclEVARS sigma <*>
1388 Proofview.Unsafe.tclNEWGOALS ~before:true [Proofview.goal_with_state evk state] <*>
1389 Proofview.tclDISPATCH [Clenv.res_pf ~with_evars:true indclause; tclIDTAC] <*>
1390 Proofview.tclEXTEND [] tclIDTAC [Clenv.case_pf ~with_evars ~dep (ev, argtype)]
1391 in
1392 let sigma = clenv_evd indclause in
1393 Tacticals.tclTHENLIST [
1394 Tacticals.tclWITHHOLES with_evars tac sigma;
1395 apply_clear_request clear_flag (use_clear_hyp_by_default ()) id;
1396 ]
1397 end
1398
1399 let general_case_analysis with_evars clear_flag (c,lbindc as cx) =
1400 Proofview.tclEVARMAP >>= fun sigma ->
1401 match EConstr.kind sigma c with
1402 | Var id when lbindc == NoBindings ->
1403 Tacticals.tclTHEN (try_intros_until_id_check id)
1404 (general_case_analysis_in_context with_evars clear_flag cx)
1405 | _ ->
1406 general_case_analysis_in_context with_evars clear_flag cx
1407
1408 let simplest_case c = general_case_analysis false None (c,NoBindings)
1409 let simplest_ecase c = general_case_analysis true None (c,NoBindings)
1410
1411 (* Elimination tactic with bindings but using the default elimination
1412 * constant associated with the type. *)
1413
1414 exception IsNonrec
1415
1416 let is_nonrec env mind = (Environ.lookup_mind (fst mind) env).mind_finite == Declarations.BiFinite
1417
1418 let find_ind_eliminator env sigma ind s =
1419 let c = Elimschemes.lookup_eliminator env ind s in
1420 let sigma, c = EConstr.fresh_global env sigma c in
1421 sigma, destConst sigma c
1422
1423 let default_elim with_evars clear_flag (c,_ as cx) =
1424 Proofview.tclORELSE
1425 (Proofview.Goal.enter begin fun gl ->
1426 let env = Proofview.Goal.env gl in
1427 let sigma = Proofview.Goal.sigma gl in
1428 let concl = Proofview.Goal.concl gl in
1429 let sigma, t = Typing.type_of env sigma c in
1430 let (ind,u) = eval_to_quantified_ind env sigma t in
1431 if is_nonrec env ind then raise IsNonrec;
1432 let sigma, elim = find_ind_eliminator env sigma ind
1433 (Retyping.get_sort_quality_of env sigma concl) in
1434 Proofview.tclTHEN (Proofview.Unsafe.tclEVARS sigma)
1435 (general_elim with_evars clear_flag cx (ElimConstant (mkConstU elim, UnknownPosition)))
1436 end)
1437 begin function (e, info) -> match e with
1438 | IsNonrec ->
1439 (* For records, induction principles aren't there by default
1440 anymore. Instead, we do a case analysis. *)
1441 general_case_analysis with_evars clear_flag cx
1442 | e -> Proofview.tclZERO ~info e
1443 end
1444
1445 let elim_in_context with_evars clear_flag c = function
1446 | Some elim ->
1447 general_elim with_evars clear_flag c (ElimClause elim)
1448 | None -> default_elim with_evars clear_flag c
1449
1450 let elim with_evars clear_flag (c,lbindc as cx) elim =
1451 Proofview.tclEVARMAP >>= fun sigma ->
1452 match EConstr.kind sigma c with
1453 | Var id when lbindc == NoBindings ->
1454 Tacticals.tclTHEN (try_intros_until_id_check id)
1455 (elim_in_context with_evars clear_flag cx elim)
1456 | _ ->
1457 elim_in_context with_evars clear_flag cx elim
1458
1459 (* The simplest elimination tactic, with no substitutions at all. *)
1460
1461 let simplest_elim c = default_elim false None (c,NoBindings)
1462
1463 (* Elimination in hypothesis *)
1464 (* Typically, elimclause := (eq_ind ?x ?P ?H ?y ?Heq : ?P ?y)
1465 indclause : forall ..., hyps -> a=b (to take place of ?Heq)
1466 id : phi(a) (to take place of ?H)
1467 and the result is to overwrite id with the proof of phi(b)
1468
1469 but this generalizes to any elimination scheme with one constructor
1470 (e.g. it could replace id:A->B->C by id:C, knowing A/\B)
1471 *)
1472
1473 (* Apply a tactic below the products of the conclusion of a lemma *)
1474
1475 type conjunction_status =
1476 | DefinedRecord of Constant.t option list
1477 | NotADefinedRecordUseScheme
1478
1479 let make_projection env sigma params cstr sign elim i n c (ind, u) =
1480 let open Context.Rel.Declaration in
1481 let elim = match elim with
1482 | NotADefinedRecordUseScheme ->
1483 (* bugs: goes from right to left when i increases! *)
1484 let cs_args = cstr.cs_args in
1485 let decl = List.nth cs_args i in
1486 let t = RelDecl.get_type decl in
1487 let b = match decl with LocalAssum _ -> mkRel (i+1) | LocalDef (_,b,_) -> b in
1488 if
1489 (* excludes dependent projection types *)
1490 noccur_between sigma 1 (n-i-1) t
1491 (* to avoid surprising unifications, excludes flexible
1492 projection types or lambda which will be instantiated by Meta/Evar *)
1493 && not (isEvar sigma (fst (whd_betaiota_stack env sigma t)))
1494 && (not (isRel sigma t))
1495 then
1496 let (_, mip) as specif = Inductive.lookup_mind_specif env ind in
1497 let t = lift (i + 1 - n) t in
1498 let ksort = Retyping.get_sort_quality_of (push_rel_context sign env) sigma t in
1499 if UnivGen.QualityOrSet.eliminates_to
1500 (UnivGen.QualityOrSet.of_quality @@ Inductiveops.elim_sort specif) ksort then
1501 let arity = List.firstn mip.mind_nrealdecls mip.mind_arity_ctxt in
1502 let mknas ctx = Array.of_list (List.rev_map get_annot ctx) in
1503 let ci = Inductiveops.make_case_info env ind RegularStyle in
1504 let br = [| mknas cs_args, b |] in
1505 let args = Context.Rel.instance mkRel 0 sign in
1506 let indr = ERelevance.make @@
1507 Inductive.relevance_of_ind_body mip (EConstr.Unsafe.to_instance u)
1508 in
1509 let pnas = Array.append (mknas (EConstr.of_rel_context arity)) [|make_annot Anonymous indr|] in
1510 let p = (pnas, lift (Array.length pnas) t) in
1511 let c = mkCase (ci, u, Array.of_list params, (p, get_relevance decl), NoInvert, mkApp (c, args), br) in
1512 Some (sigma, it_mkLambda_or_LetIn c sign, it_mkProd_or_LetIn t sign)
1513 else None
1514 else
1515 None
1516 | DefinedRecord l ->
1517 (* goes from left to right when i increases! *)
1518 match List.nth l i with
1519 | Some proj ->
1520 let args = Context.Rel.instance mkRel 0 sign in
1521 let sigma, proj =
1522 match Structures.PrimitiveProjections.find_opt_with_relevance (proj,u) with
1523 | Some (proj,r) ->
1524 sigma, mkProj (Projection.make proj false, r, mkApp (c, args))
1525 | None ->
1526 let env = EConstr.push_rel_context sign env in
1527 let args = Array.append (Array.of_list params) [|mkApp (c, args)|] in
1528 Typing.checked_appvect env sigma (mkConstU (proj, u)) args
1529 in
1530 let app = it_mkLambda_or_LetIn proj sign in
1531 let t = Retyping.get_type_of env sigma app in
1532 Some (sigma, app, t)
1533 | None -> None
1534 in elim
1535
1536 let descend_in_conjunctions avoid tac (err, info) c =
1537 Proofview.Goal.enter begin fun gl ->
1538 let env = Proofview.Goal.env gl in
1539 let sigma = Proofview.Goal.sigma gl in
1540 try
1541 let t = Retyping.get_type_of env sigma c in
1542 let ((ind,u),t) = reduce_to_quantified_ind env sigma t in
1543 let sign,ccl = EConstr.decompose_prod_decls sigma t in
1544 match match_with_tuple env sigma ccl with
1545 | Some (_,_,isrec) ->
1546 (* At this point, ind is known to be an index-free one-constructor
1547 inductive type, potentially recursive. *)
1548 let n = (constructors_nrealdecls env ind).(0) in
1549 let IndType (indf,_) = find_rectype env sigma ccl in
1550 let (_,inst), params = dest_ind_family indf in
1551 let cstr = (get_constructors env indf).(0) in
1552 let elim =
1553 try DefinedRecord (Structures.Structure.find_projections env ind)
1554 with Not_found -> NotADefinedRecordUseScheme
1555 in
1556 let or_tac t1 t2 e = Proofview.tclORELSE (t1 e) t2 in
1557 List.fold_right or_tac
1558 (List.init n (fun i (err, info) ->
1559 Proofview.Goal.enter begin fun gl ->
1560 let env = Proofview.Goal.env gl in
1561 let sigma = Proofview.Goal.sigma gl in
1562 match make_projection env sigma params cstr sign elim i n c (ind, u) with
1563 | None ->
1564 Proofview.tclZERO ~info err
1565 | Some (sigma, p, pt) ->
1566 Proofview.Unsafe.tclEVARS sigma <*>
1567 Tacticals.tclTHENS
1568 (Proofview.tclORELSE
1569 (assert_before_gen false (NamingAvoid avoid) pt)
1570 (fun _ -> Proofview.tclZERO ~info err))
1571 [Proofview.tclORELSE
1572 (Refine.refine ~typecheck:false (fun h -> (h, p)))
1573 (fun _ -> Proofview.tclZERO ~info err);
1574 (* Might be ill-typed due to forbidden elimination. *)
1575 Tacticals.onLastHypId (tac (err, info) (not isrec))]
1576 end))
1577 (fun (err, info) -> Proofview.tclZERO ~info err)
1578 (err, info)
1579 | None -> Proofview.tclZERO ~info err
1580 with RefinerError _|UserError _ -> Proofview.tclZERO ~info err
1581 end
1582
1583 (****************************************************)
1584 (* Resolution tactics *)
1585 (****************************************************)
1586
1587 let general_apply ?(with_classes=true) ?(respect_opaque=false) with_delta with_destruct with_evars
1588 clear_flag {CAst.loc;v=(c,lbind : EConstr.constr with_bindings)} =
1589 Proofview.Goal.enter begin fun gl ->
1590 let concl = Proofview.Goal.concl gl in
1591 let sigma = Proofview.Goal.sigma gl in
1592 let id = try Some (destVar sigma c) with DestKO -> None in
1593 let concl_nprod = nb_prod_modulo_zeta sigma concl in
1594 let rec try_main_apply with_destruct c =
1595 Proofview.Goal.enter begin fun gl ->
1596 let env = Proofview.Goal.env gl in
1597 let sigma = Proofview.Goal.sigma gl in
1598 let ts =
1599 if respect_opaque then Conv_oracle.get_transp_state (oracle env)
1600 else TransparentState.full
1601 in
1602 let flags =
1603 if with_delta then default_unify_flags () else default_no_delta_unify_flags ts in
1604 (* The actual type of the theorem. It will be matched against the goal.
1605 If this fails, then the head constant will be unfolded step by step. *)
1606 let thm_ty = nf_betaiota env sigma (Retyping.get_type_of env sigma c) in
1607 let sigma, thm_ty = Evarsolve.refresh_universes ~onlyalg:true None env sigma thm_ty in
1608 let try_apply thm_ty nprod =
1609 try
1610 let n = nb_prod_modulo_zeta sigma thm_ty - nprod in
1611 if n < 0 then TacticErrors.not_enough_premises ();
1612 let clause = make_clenv_binding_apply env sigma (Some n) (c,thm_ty) lbind in
1613 Clenv.res_pf clause ~with_classes ~with_evars ~flags
1614 with exn when noncritical exn ->
1615 let exn, info = Exninfo.capture exn in
1616 Proofview.tclZERO ~info exn
1617 in
1618 let rec try_red_apply thm_ty (exn0, info) = match red_product env sigma thm_ty with
1619 | Some red_thm ->
1620 (* Try to head-reduce the conclusion of the theorem *)
1621 Proofview.tclORELSE
1622 (try_apply red_thm concl_nprod)
1623 (fun _ -> try_red_apply red_thm (exn0, info))
1624 | None ->
1625 (* Last chance: if the head is a variable, apply may try
1626 second order unification *)
1627 let info = Option.cata (fun loc -> Loc.add_loc info loc) info loc in
1628 let tac =
1629 if with_destruct then
1630 Proofview.tclORELSE
1631 (descend_in_conjunctions Id.Set.empty
1632 (fun _ b id ->
1633 Tacticals.tclTHEN
1634 (try_main_apply b (mkVar id))
1635 (clear [id]))
1636 (exn0, info) c)
1637 (fun _ -> Proofview.tclZERO ~info exn0)
1638 else
1639 Proofview.tclZERO ~info exn0 in
1640 if not (Int.equal concl_nprod 0) then
1641 Tacticals.tclORELSE0 (try_apply thm_ty 0) tac
1642 else
1643 tac
1644 in
1645 Proofview.tclORELSE
1646 (try_apply thm_ty concl_nprod)
1647 (try_red_apply thm_ty)
1648 end
1649 in
1650 Tacticals.tclTHEN
1651 (try_main_apply with_destruct c)
1652 (apply_clear_request clear_flag (use_clear_hyp_by_default ()) id)
1653 end
1654
1655 let rec apply_with_bindings_gen ?with_classes b e = function
1656 | [] -> Proofview.tclUNIT ()
1657 | [k,cb] -> general_apply ?with_classes b b e k cb
1658 | (k,cb)::cbl ->
1659 Tacticals.tclTHENLAST
1660 (general_apply ?with_classes b b e k cb)
1661 (apply_with_bindings_gen ?with_classes b e cbl)
1662
1663 let apply_with_delayed_bindings_gen b e l =
1664 let one k {CAst.loc;v=cb} =
1665 Proofview.Goal.enter begin fun _ ->
1666 Tacticals.tclRUNWITHHOLES e cb
1667 (fun cb -> general_apply ~respect_opaque:(not b) b b e k CAst.(make ?loc cb))
1668 end
1669 in
1670 let rec aux = function
1671 | [] -> Proofview.tclUNIT ()
1672 | [k,f] -> one k f
1673 | (k,f)::cbl ->
1674 Tacticals.tclTHENLAST
1675 (one k f) (aux cbl)
1676 in aux l
1677
1678 let apply_with_bindings cb = apply_with_bindings_gen false false [None,(CAst.make cb)]
1679
1680 let eapply_with_bindings ?with_classes cb = apply_with_bindings_gen ?with_classes false true [None,(CAst.make cb)]
1681
1682 let apply c = apply_with_bindings_gen false false [None,(CAst.make (c,NoBindings))]
1683
1684 let eapply ?with_classes c =
1685 apply_with_bindings_gen ?with_classes false true [None,(CAst.make (c,NoBindings))]
1686
1687 let apply_list = function
1688 | c::l -> apply_with_bindings (c,ImplicitBindings l)
1689 | _ -> assert false
1690
1691 (* [apply_in hyp c] replaces
1692
1693 hyp : forall y1, ti -> t hyp : rho(u)
1694 ======================== with ============ and the =======
1695 goal goal rho(ti)
1696
1697 assuming that [c] has type [forall x1..xn -> t' -> u] for some [t]
1698 unifiable with [t'] with unifier [rho]
1699 *)
1700
1701 exception UnableToApply
1702
1703 let progress_with_clause env flags (id, t) clause mvs =
1704 let innerclause = mk_clenv_from_n env (clenv_evd clause) 0 (mkVar id, t) in
1705 if List.is_empty mvs then raise UnableToApply;
1706 let f mv =
1707 let rec find innerclause =
1708 let metas = clenv_meta_list innerclause in
1709 let submetas = (clenv_arguments innerclause, metas) in
1710 try
1711 Some (clenv_instantiate mv ~flags ~submetas clause (mkVar id, clenv_type innerclause))
1712 with e when noncritical e ->
1713 match clenv_push_prod innerclause with
1714 | Some (_, _, innerclause) -> find innerclause
1715 | None -> None
1716 in
1717 find innerclause
1718 in
1719 match List.find_map f mvs with
1720 | Some v -> v
1721 | None -> raise UnableToApply
1722
1723 let apply_in_once_main flags (id, t) env sigma (loc,d,lbind) =
1724 let thm = nf_betaiota env sigma (Retyping.get_type_of env sigma d) in
1725 let rec aux clause mvs =
1726 try progress_with_clause env flags (id, t) clause mvs
1727 with e when CErrors.noncritical e ->
1728 let e' = Exninfo.capture e in
1729 match clenv_push_prod clause with
1730 | Some (mv, dep, clause) -> aux clause (if dep then [] else [mv])
1731 | None ->
1732 match e with
1733 | UnableToApply -> TacticErrors.unable_to_apply_lemma ?loc env sigma thm t
1734 | _ -> Exninfo.iraise e'
1735 in
1736 let clenv = make_clenv_binding env sigma (d,thm) lbind in
1737 let mvs = List.rev (clenv_independent clenv) in
1738 aux clenv mvs
1739
1740 let apply_in_once ?(respect_opaque = false) with_delta
1741 with_destruct with_evars naming id (clear_flag,{ CAst.loc; v= d,lbind}) tac =
1742 let open Context.Rel.Declaration in
1743 Proofview.Goal.enter begin fun gl ->
1744 let t' = Tacmach.pf_get_hyp_typ id gl in
1745 let targetid = find_name true (LocalAssum (make_annot Anonymous Sorts.Relevant,t')) naming gl in
1746 let replace = Id.equal id targetid in
1747 let rec aux ?err idstoclear with_destruct c =
1748 Proofview.Goal.enter begin fun gl ->
1749 let env = Proofview.Goal.env gl in
1750 let sigma = Proofview.Goal.sigma gl in
1751 let idc = try Some (destVar (Proofview.Goal.sigma gl) c) with DestKO -> None in
1752 let ts =
1753 if respect_opaque then Conv_oracle.get_transp_state (oracle env)
1754 else TransparentState.full
1755 in
1756 let flags =
1757 if with_delta then default_unify_flags () else default_no_delta_unify_flags ts in
1758 try
1759 let clause = apply_in_once_main flags (id, t') env sigma (loc,c,lbind) in
1760 let cleartac = apply_clear_request clear_flag false idc <*> clear idstoclear in
1761 let refine = Tacticals.tclTHENFIRST (clenv_refine_in with_evars targetid replace env sigma clause) cleartac in
1762 Tacticals.tclTHENFIRST (replace_error_option err refine) (tac targetid)
1763 with e when with_destruct && CErrors.noncritical e ->
1764 let err = Option.default (Exninfo.capture e) err in
1765 (descend_in_conjunctions (Id.Set.singleton targetid)
1766 (fun err b id -> aux ~err (id::idstoclear) b (mkVar id))
1767 err c)
1768 end
1769 in
1770 aux [] with_destruct d
1771 end
1772
1773 let apply_in_delayed_once ?(respect_opaque = false) with_delta
1774 with_destruct with_evars naming id (clear_flag,{CAst.loc;v=f}) tac =
1775 Proofview.Goal.enter begin fun _ ->
1776 Tacticals.tclRUNWITHHOLES with_evars f
1777 (fun c -> apply_in_once ~respect_opaque with_delta with_destruct with_evars
1778 naming id (clear_flag,CAst.(make ?loc c)) tac)
1779 end
1780
1781 (* A useful resolution tactic which, if c:A->B, transforms |- C into
1782 |- B -> C and |- A
1783
1784 -------------------
1785 Gamma |- c : A -> B Gamma |- ?2 : A
1786 ----------------------------------------
1787 Gamma |- B Gamma |- ?1 : B -> C
1788 -----------------------------------------------------
1789 Gamma |- ? : C
1790
1791 Ltac lapply c :=
1792 let ty := check c in
1793 match eval hnf in ty with
1794 ?A -> ?B => cut B; [ idtac | apply c ]
1795 end.
1796 *)
1797
1798 let cut_and_apply c =
1799 Proofview.Goal.enter begin fun gl ->
1800 let env = Proofview.Goal.env gl in
1801 let sigma = Proofview.Goal.sigma gl in
1802 let concl = Proofview.Goal.concl gl in
1803 let sigma, t = Typing.type_of env sigma c in
1804 match EConstr.kind sigma (hnf_constr env sigma t) with
1805 | Prod (_,c1,c2) when Vars.noccurn sigma 1 c2 ->
1806 Proofview.tclTHEN (Proofview.Unsafe.tclEVARS sigma)
1807 (Refine.refine ~typecheck:false begin fun sigma ->
1808 let typ = mkProd (make_annot Anonymous ERelevance.relevant, c2, concl) in
1809 let (sigma, f) = Evarutil.new_evar env sigma typ in
1810 let (sigma, x) = Evarutil.new_evar env sigma c1 in
1811 (sigma, mkApp (f, [|mkApp (c, [|x|])|]))
1812 end)
1813 | _ -> TacticErrors.need_dependent_product ()
1814 end
1815
1816 (********************************************************************)
1817 (* Exact tactics *)
1818 (********************************************************************)
1819
1820 let exact_no_check c =
1821 Refine.refine ~typecheck:false (fun h -> (h,c))
1822
1823 let exact_check c =
1824 Proofview.Goal.enter begin fun gl ->
1825 let sigma = Proofview.Goal.sigma gl in
1826 (* We do not need to normalize the goal because we just check convertibility *)
1827 let concl = Proofview.Goal.concl gl in
1828 let env = Proofview.Goal.env gl in
1829 let sigma, ct = Typing.type_of env sigma c in
1830 Tacticals.tclTHEN (Proofview.Unsafe.tclEVARS sigma)
1831 (Tacticals.tclTHEN (convert_leq ct concl) (exact_no_check c))
1832 end
1833
1834 let cast_no_check cast c =
1835 Proofview.Goal.enter begin fun gl ->
1836 let concl = Proofview.Goal.concl gl in
1837 exact_no_check (mkCast (c, cast, concl))
1838 end
1839
1840 let vm_cast_no_check c = cast_no_check VMcast c
1841 let native_cast_no_check c = cast_no_check NATIVEcast c
1842
1843 let exact_proof c =
1844 Proofview.Goal.enter begin fun gl ->
1845 let env = Proofview.Goal.env gl in
1846 let concl = Proofview.Goal.concl gl in
1847 Refine.refine ~typecheck:false begin fun sigma ->
1848 Constrintern.interp_casted_constr_evars ~flags:Pretyping.all_and_fail_flags env sigma c concl
1849 end
1850 end
1851
1852 (** For efficiency reasons we first try to find a hypothesis whose type
1853 is syntactically equal to the goal. If this fails we retry with full conversion. *)
1854 let assumption =
1855 let rec arec gl only_eq = function
1856 | [] ->
1857 if only_eq then
1858 let hyps = Proofview.Goal.hyps gl in
1859 arec gl false hyps
1860 else
1861 let info = Exninfo.reify () in
1862 Tacticals.tclZEROMSG ~info (str "No such assumption.")
1863 | decl::rest ->
1864 let t = NamedDecl.get_type decl in
1865 let concl = Proofview.Goal.concl gl in
1866 let sigma = Proofview.Goal.sigma gl in
1867 let ans =
1868 if only_eq then
1869 if EConstr.eq_constr sigma t concl then Some sigma
1870 else None
1871 else
1872 let env = Proofview.Goal.env gl in
1873 infer_conv env sigma t concl
1874 in
1875 match ans with
1876 | Some sigma ->
1877 (Proofview.Unsafe.tclEVARS sigma) <*>
1878 exact_no_check (mkVar (NamedDecl.get_id decl))
1879 | None -> arec gl only_eq rest
1880 in
1881 let assumption_tac gl =
1882 let hyps = Proofview.Goal.hyps gl in
1883 arec gl true hyps
1884 in
1885 Proofview.Goal.enter assumption_tac
1886
1887 (*****************************************************************)
1888 (* Modification of a local context *)
1889 (*****************************************************************)
1890
1891 let check_is_type env sigma idl ids ty =
1892 try
1893 let sigma, _ = Typing.sort_of env sigma ty in
1894 sigma
1895 with e when CErrors.noncritical e ->
1896 TacticErrors.depends_on_body idl ids None
1897
1898 let check_decl env sigma idl ids decl =
1899 let open Context.Named.Declaration in
1900 let ty = NamedDecl.get_type decl in
1901 try
1902 let sigma, _ = Typing.sort_of env sigma ty in
1903 let sigma = match decl with
1904 | LocalAssum _ -> sigma
1905 | LocalDef (_,c,_) -> Typing.check env sigma c ty
1906 in
1907 sigma
1908 with e when CErrors.noncritical e ->
1909 let id = NamedDecl.get_id decl in
1910 TacticErrors.depends_on_body idl ids (Some id)
1911
1912 let clear_body idl =
1913 let open Context.Named.Declaration in
1914 Proofview.Goal.enter begin fun gl ->
1915 let env = Proofview.Goal.env gl in
1916 let concl = Proofview.Goal.concl gl in
1917 let sigma = Proofview.Goal.sigma gl in
1918 let ctx = named_context env in
1919 let ids = Id.Set.of_list idl in
1920 let () =
1921 match Id.Set.find_first_opt (fun v -> not (mem_named v env)) ids with
1922 | Some v -> TacticErrors.variable_has_no_value v
1923 | None -> ()
1924 in
1925 (* We assume the context to respect dependencies *)
1926 let rec fold ids ctx =
1927 if Id.Set.is_empty ids then
1928 let base_env = reset_context env in
1929 let env = push_named_context ctx base_env in
1930 env, sigma, Id.Set.empty
1931 else
1932 match ctx with
1933 | [] -> assert false
1934 | decl :: ctx ->
1935 let decl, ids, found =
1936 match decl with
1937 | LocalAssum (id,t) ->
1938 let () =
1939 if Id.Set.mem id.binder_name ids then
1940 TacticErrors.variable_has_no_value id.binder_name
1941 in
1942 decl, ids, false
1943 | LocalDef (id,_,t) as decl ->
1944 if Id.Set.mem id.binder_name ids
1945 then LocalAssum (id, t), Id.Set.remove id.binder_name ids, true
1946 else decl, ids, false
1947 in
1948 let env, sigma, ids = fold ids ctx in
1949 if Id.Set.exists (fun id -> occur_var_in_decl env sigma id decl) ids then
1950 let sigma = check_decl env sigma idl ids decl in (* can sigma really change? *)
1951 let ids = Id.Set.add (get_id decl) ids in
1952 push_named decl env, sigma, Id.Set.add (get_id decl) ids
1953 else
1954 push_named decl env, sigma, if found then Id.Set.add (get_id decl) ids else ids
1955 in
1956 try
1957 let env, sigma, ids = fold ids ctx in
1958 let sigma =
1959 if Id.Set.exists (fun id -> occur_var env sigma id concl) ids then
1960 check_is_type env sigma idl ids concl
1961 else sigma
1962 in
1963 Proofview.Unsafe.tclEVARS sigma <*>
1964 Refine.refine_with_principal ~typecheck:false begin fun sigma ->
1965 let sigma, ev = Evarutil.new_evar env sigma concl in
1966 sigma, ev, Some (fst @@ destEvar sigma ev)
1967 end
1968 with TacticErrors.DependsOnBody _ as exn ->
1969 let _, info = Exninfo.capture exn in
1970 Proofview.tclZERO ~info exn
1971 end
1972
1973 let clear_wildcards ids =
1974 let clear_wildcards_msg ?loc env sigma _id err inglobal =
1975 user_err ?loc (TacticErrors.clear_dependency_msg env sigma None err inglobal)
1976 in
1977 Tacticals.tclMAP (fun {CAst.loc;v=id} -> clear_gen (clear_wildcards_msg ?loc) [id]) ids
1978
1979 let rec intros_clearing = function
1980 | [] -> Proofview.tclUNIT ()
1981 | (false::tl) -> Tacticals.tclTHEN intro (intros_clearing tl)
1982 | (true::tl) ->
1983 Tacticals.tclTHENLIST
1984 [ intro; Tacticals.onLastHypId (fun id -> clear [id]); intros_clearing tl]
1985
1986 (* Keeping only a few hypotheses *)
1987
1988 let keep hyps =
1989 Proofview.Goal.enter begin fun gl ->
1990 Proofview.tclENV >>= fun env ->
1991 let ccl = Proofview.Goal.concl gl in
1992 let sigma = Proofview.Goal.sigma gl in
1993 let cl,_ =
1994 fold_named_context_reverse (fun (clear,keep) decl ->
1995 let decl = EConstr.of_named_decl decl in
1996 let hyp = NamedDecl.get_id decl in
1997 if Id.List.mem hyp hyps
1998 || List.exists (occur_var_in_decl env sigma hyp) keep
1999 || occur_var env sigma hyp ccl
2000 then (clear,decl::keep)
2001 else (hyp::clear,keep))
2002 ~init:([],[]) (Proofview.Goal.env gl)
2003 in
2004 clear cl
2005 end
2006
2007 (*********************************)
2008 (* Basic generalization tactics *)
2009 (*********************************)
2010
2011 (* Given a type [T] convertible to [forall x1..xn:A1..An(x1..xn-1), G(x1..xn)]
2012 and [a1..an:A1..An(a1..an-1)] such that the goal is [G(a1..an)],
2013 this generalizes [hyps |- goal] into [hyps |- T] *)
2014
2015 let apply_type ~typecheck newcl args =
2016 Proofview.Goal.enter begin fun gl ->
2017 let env = Proofview.Goal.env gl in
2018 Refine.refine_with_principal ~typecheck begin fun sigma ->
2019 let newcl = nf_betaiota env sigma newcl (* As in former Logic.refine *) in
2020 let (sigma, ev) = Evarutil.new_evar env sigma newcl in
2021 (sigma, applist (ev, args), Some (fst @@ destEvar sigma ev))
2022 end
2023 end
2024
2025 (************************)
2026 (* Introduction tactics *)
2027 (************************)
2028
2029 let check_number_of_constructors expctdnumopt i nconstr =
2030 if Int.equal i 0 then TacticErrors.constructors_numbered_from_one ();
2031 begin match expctdnumopt with
2032 | Some n when not (Int.equal n nconstr) ->
2033 TacticErrors.not_right_number_constructors n
2034 | _ -> ()
2035 end;
2036 if i > nconstr then TacticErrors.not_enough_constructors ()
2037
2038 let constructor_core with_evars cstr lbind =
2039 Proofview.Goal.enter begin fun gl ->
2040 let sigma = Proofview.Goal.sigma gl in
2041 let env = Proofview.Goal.env gl in
2042 let (sigma, cons) = Evd.fresh_constructor_instance env sigma cstr in
2043 let cons = mkConstructU cons in
2044 let apply_tac = general_apply true false with_evars None (CAst.make (cons,lbind)) in
2045 Tacticals.tclTHEN (Proofview.Unsafe.tclEVARS sigma) apply_tac
2046 end
2047
2048 let constructor_tac with_evars expctdnumopt i lbind =
2049 Proofview.Goal.enter begin fun gl ->
2050 let env = Proofview.Goal.env gl in
2051 let sigma = Proofview.Goal.sigma gl in
2052 let concl = Proofview.Goal.concl gl in
2053 let ((ind, _), redcl) = Tacred.reduce_to_quantified_ind env sigma concl in
2054 let nconstr = Array.length (snd (Inductive.lookup_mind_specif env ind)).mind_consnames in
2055 check_number_of_constructors expctdnumopt i nconstr;
2056 Tacticals.tclTHENLIST [
2057 convert_concl ~cast:false ~check:false redcl DEFAULTcast;
2058 intros;
2059 constructor_core with_evars (ind, i) lbind
2060 ]
2061 end
2062
2063 let one_constructor i lbind = constructor_tac false None i lbind
2064
2065 (* Try to apply the constructor of the inductive definition followed by
2066 a tactic t given as an argument.
2067 Should be generalize in Constructor (Fun c : I -> tactic)
2068 *)
2069
2070 let any_constructor with_evars tacopt =
2071 let one_constr =
2072 let tac cstr = constructor_core with_evars cstr NoBindings in
2073 match tacopt with
2074 | None -> tac
2075 | Some t -> fun cstr -> Tacticals.tclTHEN (tac cstr) t in
2076 let rec any_constr ind n i () =
2077 if Int.equal i n then one_constr (ind,i)
2078 else Tacticals.tclORD (one_constr (ind,i)) (any_constr ind n (i + 1)) in
2079 Proofview.Goal.enter begin fun gl ->
2080 let env = Proofview.Goal.env gl in
2081 let sigma = Proofview.Goal.sigma gl in
2082 let concl = Proofview.Goal.concl gl in
2083 let (ind, _), redcl = Tacred.reduce_to_quantified_ind env sigma concl in
2084 let nconstr =
2085 Array.length (snd (Inductive.lookup_mind_specif env ind)).mind_consnames in
2086 if Int.equal nconstr 0 then TacticErrors.no_constructors ();
2087 Tacticals.tclTHENLIST [
2088 convert_concl ~cast:false ~check:false redcl DEFAULTcast;
2089 intros;
2090 any_constr ind nconstr 1 ()
2091 ]
2092 end
2093
2094 let left_with_bindings with_evars = constructor_tac with_evars (Some 2) 1
2095 let right_with_bindings with_evars = constructor_tac with_evars (Some 2) 2
2096 let split_with_bindings with_evars l =
2097 Tacticals.tclMAP (constructor_tac with_evars (Some 1) 1) l
2098 let split_with_delayed_bindings with_evars bl =
2099 Tacticals.tclMAPDELAYEDWITHHOLES with_evars bl
2100 (constructor_tac with_evars (Some 1) 1)
2101
2102 let left = left_with_bindings false
2103 let simplest_left = left NoBindings
2104
2105 let right = right_with_bindings false
2106 let simplest_right = right NoBindings
2107
2108 let split = constructor_tac false (Some 1) 1
2109 let simplest_split = split NoBindings
2110
2111 (*****************************)
2112 (* Decomposing introductions *)
2113 (*****************************)
2114
2115 (* Rewriting function for rewriting one hypothesis at the time *)
2116 let (forward_general_rewrite_clause, general_rewrite_clause) = Hook.make ()
2117
2118 (* Rewriting function for substitution (x=t) everywhere at the same time *)
2119 let (forward_subst_one, subst_one) = Hook.make ()
2120
2121 let intro_decomp_eq_function = ref (fun _ -> failwith "Not implemented")
2122
2123 let declare_intro_decomp_eq f = intro_decomp_eq_function := f
2124
2125 let my_find_eq_data_decompose env sigma t =
2126 try Some (find_eq_data_decompose env sigma t)
2127 with Constr_matching.PatternMatchingFailure -> None
2128
2129 let intro_decomp_eq ?loc l thin tac id =
2130 Proofview.Goal.enter begin fun gl ->
2131 let c = mkVar id in
2132 let env = Proofview.Goal.env gl in
2133 let sigma = Proofview.Goal.sigma gl in
2134 let {uj_type=t} = Typing.judge_of_variable env id in
2135 let _,t = reduce_to_atomic_ind env sigma t in
2136 match my_find_eq_data_decompose env sigma t with
2137 | Some (eq,u,eq_args) ->
2138 !intro_decomp_eq_function
2139 (fun n -> tac ((CAst.make id)::thin) (Some n) l)
2140 (EConstr.mkIndU (Globnames.destIndRef eq.eq, u),eq.congr,t,eq_args) (c, t)
2141 | None ->
2142 let info = Exninfo.reify () in
2143 Tacticals.tclZEROMSG ~info (str "Not a primitive equality here.")
2144 end
2145
2146 let intro_or_and_pattern ?loc with_evars ll thin tac id =
2147 Proofview.Goal.enter begin fun gl ->
2148 let c = mkVar id in
2149 let env = Proofview.Goal.env gl in
2150 let sigma = Proofview.Goal.sigma gl in
2151 let {uj_type=t} = Typing.judge_of_variable env id in
2152 let ind = eval_to_quantified_ind env sigma t in
2153 let branchsigns = compute_constructor_signatures env ~rec_flag:false ind in
2154 let nv_with_let = Array.map List.length branchsigns in
2155 let ll = fix_empty_or_and_pattern (Array.length branchsigns) ll in
2156 let ll = get_and_check_or_and_pattern ?loc ll branchsigns in
2157 let case = if with_evars then simplest_ecase else simplest_case in
2158 Tacticals.tclTHENLASTn
2159 (Tacticals.tclTHEN (case c) (clear [id]))
2160 (Array.map2 (fun n l -> tac thin (Some n) l)
2161 nv_with_let ll)
2162 end
2163
2164 let rewrite_hyp_then with_evars thin l2r id tac =
2165 let rew_on l2r =
2166 Hook.get forward_general_rewrite_clause l2r with_evars (mkVar id,NoBindings) in
2167 let subst_on l2r x rhs =
2168 Hook.get forward_subst_one true x (id,rhs,l2r) in
2169 let clear_var_and_eq id' = clear [id';id] in
2170 let early_clear id' thin =
2171 List.filter (fun {CAst.v=id} -> not (Id.equal id id')) thin in
2172 Proofview.Goal.enter begin fun gl ->
2173 let env = Proofview.Goal.env gl in
2174 let sigma = Proofview.Goal.sigma gl in
2175 let {uj_type=t} = Typing.judge_of_variable env id in
2176 let t = whd_all env sigma t in
2177 let eqtac, thin = match match_with_equality_type env sigma t with
2178 | Some (hdcncl,[_;lhs;rhs]) ->
2179 if l2r && isVar sigma lhs && not (occur_var env sigma (destVar sigma lhs) rhs) then
2180 let id' = destVar sigma lhs in
2181 subst_on l2r id' rhs, early_clear id' thin
2182 else if not l2r && isVar sigma rhs && not (occur_var env sigma (destVar sigma rhs) lhs) then
2183 let id' = destVar sigma rhs in
2184 subst_on l2r id' lhs, early_clear id' thin
2185 else
2186 Tacticals.tclTHEN (rew_on l2r onConcl) (clear [id]),
2187 thin
2188 | Some (hdcncl,[c]) ->
2189 let l2r = not l2r in (* equality of the form eq_true *)
2190 if isVar sigma c then
2191 let id' = destVar sigma c in
2192 Tacticals.tclTHEN (rew_on l2r allHypsAndConcl)
2193 (clear_var_and_eq id'),
2194 early_clear id' thin
2195 else
2196 Tacticals.tclTHEN (rew_on l2r onConcl) (clear [id]),
2197 thin
2198 | _ ->
2199 Tacticals.tclTHEN (rew_on l2r onConcl) (clear [id]),
2200 thin in
2201 (* Skip the side conditions of the rewriting step *)
2202 Tacticals.tclTHENFIRST eqtac (tac thin)
2203 end
2204
2205 let rec collect_intro_names = let open CAst in function
2206 | {v=IntroForthcoming _} :: l -> collect_intro_names l
2207 | {v=IntroNaming (IntroIdentifier id)} :: l ->
2208 let ids1, ids2 = collect_intro_names l in Id.Set.add id ids1, ids2
2209 | {v=IntroAction (IntroOrAndPattern l)} :: l' ->
2210 let ll = match l with IntroAndPattern l -> [l] | IntroOrPattern ll -> ll in
2211 let fold (ids1',ids2') l =
2212 let ids1, ids2 = collect_intro_names (l@l') in
2213 Id.Set.union ids1 ids1', Id.Set.union ids2 ids2' in
2214 List.fold_left fold (Id.Set.empty,Id.Set.empty) ll
2215 | {v=IntroAction (IntroInjection l)} :: l' ->
2216 collect_intro_names (l@l')
2217 | {v=IntroAction (IntroApplyOn (c,pat))} :: l' ->
2218 collect_intro_names (pat::l')
2219 | {v=IntroNaming (IntroFresh id)} :: l ->
2220 let ids1, ids2 = collect_intro_names l in ids1, Id.Set.add id ids2
2221 | {v=(IntroNaming IntroAnonymous
2222 | IntroAction (IntroWildcard | IntroRewrite _))} :: l ->
2223 collect_intro_names l
2224 | [] -> Id.Set.empty, Id.Set.empty
2225
2226 let explicit_intro_names l = fst (collect_intro_names l)
2227
2228 let explicit_all_intro_names l =
2229 let ids1,ids2 = collect_intro_names l in Id.Set.union ids1 ids2
2230
2231 let rec check_name_unicity env ok seen = let open CAst in function
2232 | {v=IntroForthcoming _} :: l -> check_name_unicity env ok seen l
2233 | {loc;v=IntroNaming (IntroIdentifier id)} :: l ->
2234 (try
2235 ignore (if List.mem_f Id.equal id ok then raise Not_found else lookup_named id env);
2236 TacticErrors.already_used ?loc id
2237 with Not_found ->
2238 if List.mem_f Id.equal id seen then
2239 TacticErrors.used_twice ?loc id
2240 else
2241 check_name_unicity env ok (id::seen) l)
2242 | {v=IntroAction (IntroOrAndPattern l)} :: l' ->
2243 let ll = match l with IntroAndPattern l -> [l] | IntroOrPattern ll -> ll in
2244 List.iter (fun l -> check_name_unicity env ok seen (l@l')) ll
2245 | {v=IntroAction (IntroInjection l)} :: l' ->
2246 check_name_unicity env ok seen (l@l')
2247 | {v=IntroAction (IntroApplyOn (c,pat))} :: l' ->
2248 check_name_unicity env ok seen (pat::l')
2249 | {v=(IntroNaming (IntroAnonymous | IntroFresh _)
2250 | IntroAction (IntroWildcard | IntroRewrite _))} :: l ->
2251 check_name_unicity env ok seen l
2252 | [] -> ()
2253
2254 let make_naming ?loc avoid l = function
2255 | IntroIdentifier id -> NamingMustBe (CAst.make ?loc id)
2256 | IntroAnonymous -> NamingAvoid (Id.Set.union avoid (explicit_intro_names l))
2257 | IntroFresh id -> NamingBasedOn (id, Id.Set.union avoid (explicit_intro_names l))
2258
2259 let rec make_naming_action avoid l = function
2260 (* In theory, we could use a tmp id like "wild_id" for all actions
2261 but we prefer to avoid it to avoid this kind of "ugly" names *)
2262 | IntroWildcard ->
2263 NamingBasedOn (Id.of_string "_H", Id.Set.union avoid (explicit_all_intro_names l))
2264 | IntroApplyOn (_,{CAst.v=pat;loc}) -> make_naming_pattern avoid ?loc l pat
2265 | (IntroOrAndPattern _ | IntroInjection _ | IntroRewrite _) as pat ->
2266 NamingAvoid(Id.Set.union avoid (explicit_intro_names ((CAst.make @@ IntroAction pat)::l)))
2267
2268 and make_naming_pattern ?loc avoid l = function
2269 | IntroNaming pat -> make_naming ?loc avoid l pat
2270 | IntroAction pat -> make_naming_action avoid l pat
2271 | IntroForthcoming _ -> NamingAvoid (Id.Set.union avoid (explicit_intro_names l))
2272
2273 let prepare_naming ?loc pat = make_naming ?loc Id.Set.empty [] pat
2274
2275 let fit_bound n = function
2276 | None -> true
2277 | Some n' -> n = n'
2278
2279 let exceed_bound n = function
2280 | None -> false
2281 | Some n' -> n >= n'
2282
2283 (** We delay thinning until the completion of the whole intros tactic
2284 to ensure that dependent hypotheses are cleared in the right
2285 dependency order (see BZ#1000); we use fresh names, not used in
2286 the tactic, for the hyps to clear. *)
2287
2288 (** In [intro_patterns_core b avoid ids thin destopt bound n tac patl]:
2289 - [b]: compatibility flag, if false at toplevel, do not complete incomplete
2290 trailing toplevel or_and patterns (as in "intros []", see
2291 [bracketing_last_or_and_intro_pattern])
2292 - [avoid]: names to avoid when creating an internal name
2293 - [ids]: collect introduced names for possible use by the [tac] continuation
2294 - [thin]: collect names to erase at the end
2295 - [destopt]: position in the context where to introduce the hypotheses
2296 - [bound]: number of pending intros to do in the current or-and pattern,
2297 with remembering of [b] flag if at toplevel
2298 - [n]: number of introduction done in the current or-and pattern
2299 - [tac]: continuation tactic
2300 - [patl]: introduction patterns to interpret
2301 *)
2302 let rec intro_patterns_core with_evars avoid ids thin destopt bound n tac =
2303 function
2304 | [] when fit_bound n bound ->
2305 tac ids thin
2306 | [] ->
2307 (* Behave as IntroAnonymous *)
2308 intro_patterns_core with_evars avoid ids thin destopt bound n tac
2309 [CAst.make @@ IntroNaming IntroAnonymous]
2310 | {CAst.loc;v=pat} :: l ->
2311 if exceed_bound n bound then TacticErrors.unexpected_extra_pattern ?loc bound pat else
2312 match pat with
2313 | IntroForthcoming onlydeps ->
2314 let naming = Id.Set.union avoid (explicit_intro_names l) in
2315 intro_forthcoming_then_gen naming destopt ~dep:onlydeps bound n
2316 (fun ids -> intro_patterns_core with_evars avoid ids thin destopt bound
2317 (n+List.length ids) tac l)
2318 | IntroAction pat ->
2319 let naming = make_naming_action avoid l pat in
2320 intro_then_gen naming destopt ~force:true ~dep:false
2321 (intro_pattern_action ?loc with_evars pat thin destopt
2322 (fun thin bound' -> intro_patterns_core with_evars avoid ids thin destopt bound' 0
2323 (fun ids thin ->
2324 intro_patterns_core with_evars avoid ids thin destopt bound (n+1) tac l)))
2325 | IntroNaming pat ->
2326 let naming = make_naming avoid l pat in
2327 intro_then_gen naming destopt ~force:true ~dep:false
2328 (fun id -> intro_patterns_core with_evars avoid (id::ids) thin destopt bound (n+1) tac l)
2329
2330 and intro_pattern_action ?loc with_evars pat thin destopt tac id =
2331 match pat with
2332 | IntroWildcard ->
2333 tac (CAst.(make ?loc id)::thin) None []
2334 | IntroOrAndPattern ll ->
2335 intro_or_and_pattern ?loc with_evars ll thin tac id
2336 | IntroInjection l' ->
2337 intro_decomp_eq ?loc l' thin tac id
2338 | IntroRewrite l2r ->
2339 rewrite_hyp_then with_evars thin l2r id (fun thin -> tac thin None [])
2340 | IntroApplyOn ({CAst.loc=loc';v=f},{CAst.loc;v=pat}) ->
2341 let naming = NamingMustBe (CAst.make ?loc id) in
2342 let tac_ipat = prepare_action ?loc with_evars destopt pat in
2343 let f =
2344 tactic_of_delayed f >>= fun c ->
2345 Proofview.tclUNIT (c, NoBindings)
2346 in
2347 apply_in_delayed_once true true with_evars naming id (None,CAst.make ?loc:loc' f)
2348 (fun id -> Tacticals.tclTHENLIST [tac_ipat id; tac thin None []])
2349
2350 and prepare_action ?loc with_evars destopt = function
2351 | IntroNaming ipat ->
2352 (fun _ -> Proofview.tclUNIT ())
2353 | IntroAction ipat ->
2354 (let tac thin bound =
2355 intro_patterns_core with_evars Id.Set.empty [] thin destopt bound 0
2356 (fun _ l -> clear_wildcards l) in
2357 fun id ->
2358 intro_pattern_action ?loc with_evars ipat [] destopt tac id)
2359 | IntroForthcoming _ -> TacticErrors.one_intro_pattern_expected ?loc ()
2360
2361 let intro_patterns_head_core with_evars destopt bound pat =
2362 Proofview.Goal.enter begin fun gl ->
2363 let env = Proofview.Goal.env gl in
2364 check_name_unicity env [] [] pat;
2365 intro_patterns_core with_evars Id.Set.empty [] [] destopt
2366 bound 0 (fun _ l -> clear_wildcards l) pat
2367 end
2368
2369 let intro_patterns_bound_to with_evars n destopt =
2370 intro_patterns_head_core with_evars destopt (Some n)
2371
2372 let intro_patterns_to with_evars destopt =
2373 intro_patterns_head_core with_evars destopt None
2374
2375 let intro_pattern_to with_evars destopt pat =
2376 intro_patterns_to with_evars destopt [CAst.make pat]
2377
2378 let intro_patterns with_evars = intro_patterns_to with_evars MoveLast
2379
2380 (* Implements "intros" *)
2381 let intros_patterns with_evars = function
2382 | [] -> intros
2383 | l -> intro_patterns_to with_evars MoveLast l
2384
2385 (**************************)
2386 (* Forward reasoning *)
2387 (**************************)
2388
2389 let prepare_intros_opt with_evars dft destopt ipat =
2390 let naming, loc, ipat = match ipat with
2391 | None ->
2392 let pat = IntroNaming dft in make_naming_pattern Id.Set.empty [] pat, None, pat
2393 | Some {CAst.loc;v=(IntroNaming pat as ipat)} ->
2394 (* "apply ... in H as id" needs to use id and H is kept iff id<>H *)
2395 prepare_naming ?loc pat, loc, ipat
2396 | Some {CAst.loc;v=(IntroAction pat as ipat)} ->
2397 (* "apply ... in H as pat" reuses H so that old H is always cleared *)
2398 (match dft with IntroIdentifier _ -> prepare_naming ?loc dft | _ -> make_naming_action Id.Set.empty [] pat),
2399 loc, ipat
2400 | Some {CAst.loc;v=(IntroForthcoming _)} -> assert false in
2401 naming, prepare_action ?loc with_evars destopt ipat
2402
2403 let ipat_of_name = function
2404 | Anonymous -> None
2405 | Name id -> Some (CAst.make @@ IntroNaming (IntroIdentifier id))
2406
2407 let head_ident sigma c =
2408 let c = fst (decompose_app sigma (snd (decompose_lambda_decls sigma c))) in
2409 if isVar sigma c then Some (destVar sigma c) else None
2410
2411 (* apply in as *)
2412
2413 let general_apply_in ?(respect_opaque=false) with_delta
2414 with_destruct with_evars id lemmas ipat then_tac =
2415 let tac (naming,lemma) tac id =
2416 apply_in_delayed_once ~respect_opaque with_delta
2417 with_destruct with_evars naming id lemma tac in
2418 Proofview.Goal.enter begin fun gl ->
2419 let destopt =
2420 if with_evars then MoveLast (* evars would depend on the whole context *)
2421 else (
2422 let env, sigma = Proofview.Goal.(env gl, sigma gl) in
2423 get_previous_hyp_position env sigma id (Proofview.Goal.hyps gl)
2424 ) in
2425 let naming,ipat_tac =
2426 prepare_intros_opt with_evars (IntroIdentifier id) destopt ipat in
2427 let lemmas_target, last_lemma_target =
2428 let last,first = List.sep_last lemmas in
2429 List.map (fun lem -> (NamingMustBe (CAst.make id),lem)) first, (naming,last)
2430 in
2431 (* We chain apply_in_once, ending with an intro pattern *)
2432 List.fold_right tac lemmas_target
2433 (tac last_lemma_target (fun id -> Tacticals.tclTHEN (ipat_tac id) then_tac)) id
2434 end
2435
2436 (*
2437 if sidecond_first then
2438 (* Skip the side conditions of the applied lemma *)
2439 Tacticals.tclTHENLAST (tclMAPLAST tac lemmas_target) (ipat_tac id)
2440 else
2441 Tacticals.tclTHENFIRST (tclMAPFIRST tac lemmas_target) (ipat_tac id)
2442 *)
2443
2444 let apply_in simple with_evars id lemmas ipat =
2445 let lemmas = List.map (fun (k,{CAst.loc;v=l}) -> k, CAst.make ?loc (Proofview.tclUNIT l)) lemmas in
2446 general_apply_in simple simple with_evars id lemmas ipat Tacticals.tclIDTAC
2447
2448 let apply_delayed_in simple with_evars id lemmas ipat then_tac =
2449 general_apply_in ~respect_opaque:true simple simple with_evars id lemmas ipat then_tac
2450
2451 (*****************************)
2452 (* Tactics abstracting terms *)
2453 (*****************************)
2454
2455 (* Implementation without generalisation: abbrev will be lost in hyps in *)
2456 (* in the extracted proof *)
2457
2458 let decode_hyp = function
2459 | None -> MoveLast
2460 | Some id -> MoveAfter id
2461
2462 (* [letin_tac b (... abstract over c ...) gl] transforms
2463 [...x1:T1(c),...,x2:T2(c),... |- G(c)] into
2464 [...x:T;Heqx:(x=c);x1:T1(x),...,x2:T2(x),... |- G(x)] if [b] is false or
2465 [...x:=c:T;x1:T1(x),...,x2:T2(x),... |- G(x)] if [b] is true
2466 *)
2467
2468 let letin_tac_gen with_eq (id,depdecls,lastlhyp,ccl,c) ty =
2469 Proofview.Goal.enter begin fun gl ->
2470 let sigma = Proofview.Goal.sigma gl in
2471 let env = Proofview.Goal.env gl in
2472 let (sigma, t) = match ty with
2473 | Some t -> (sigma, t)
2474 | None ->
2475 let t = typ_of env sigma c in
2476 Evarsolve.refresh_universes ~onlyalg:true (Some false) env sigma t
2477 in
2478 let rel = Retyping.relevance_of_term env sigma c in
2479 let (sigma, (newcl, eq_tac)) = match with_eq with
2480 | Some (lr,{CAst.loc;v=ido}) ->
2481 let heq = match ido with
2482 | IntroAnonymous -> new_fresh_id (Id.Set.singleton id) (add_prefix "Heq" id) gl
2483 | IntroFresh heq_base -> new_fresh_id (Id.Set.singleton id) heq_base gl
2484 | IntroIdentifier id -> id in
2485 let eqdata = build_rocq_eq_data () in
2486 let args = if lr then [mkVar id;c] else [c;mkVar id]in
2487 let (sigma, eq) = Evd.fresh_global env sigma eqdata.eq in
2488 let refl = mkRef (eqdata.refl, snd @@ destRef sigma eq) in
2489 let sigma, eq = Typing.checked_applist env sigma eq [t] in
2490 let eq = applist (eq, args) in
2491 let refl = applist (refl, [t; mkVar id]) in
2492 let r = Retyping.relevance_of_term env sigma refl in
2493 let term = mkNamedLetIn sigma (make_annot id rel) c t
2494 (mkLetIn (make_annot (Name heq) r, refl, eq, ccl)) in
2495 let ans = term,
2496 Tacticals.tclTHENLIST
2497 [
2498 intro_gen (NamingMustBe CAst.(make ?loc heq)) (decode_hyp lastlhyp) ~force:true ~dep:false;
2499 clear_body [heq;id]]
2500 in
2501 (sigma, ans)
2502 | None ->
2503 (sigma, (mkNamedLetIn sigma (make_annot id rel) c t ccl, Proofview.tclUNIT ()))
2504 in
2505 Tacticals.tclTHENLIST
2506 [ Proofview.Unsafe.tclEVARS sigma;
2507 convert_concl ~cast:false ~check:false newcl DEFAULTcast;
2508 intro_gen (NamingMustBe (CAst.make id)) (decode_hyp lastlhyp) ~force:true ~dep:false;
2509 Tacticals.tclMAP (convert_hyp ~check:false ~reorder:false) depdecls;
2510 eq_tac ]
2511 end
2512
2513 let pose_tac na c =
2514 Proofview.Goal.enter begin fun gl ->
2515 let sigma = Proofview.Goal.sigma gl in
2516 let env = Proofview.Goal.env gl in
2517 let hyps = named_context_val env in
2518 let concl = Proofview.Goal.concl gl in
2519 let relevance = Proofview.Goal.relevance gl in
2520 let t = typ_of env sigma c in
2521 let rel = Retyping.relevance_of_term env sigma c in
2522 let (sigma, t) = Evarsolve.refresh_universes ~onlyalg:true (Some false) env sigma t in
2523 let id = match na with
2524 | Name id ->
2525 let () = if mem_named_context_val id hyps then
2526 TacticErrors.intro_already_declared id
2527 in
2528 id
2529 | Anonymous ->
2530 let id = id_of_name_using_hdchar env sigma t Anonymous in
2531 next_ident_away_in_goal (Global.env ()) id (ids_of_named_context_val hyps)
2532 in
2533 Proofview.Unsafe.tclEVARS sigma <*>
2534 Refine.refine ~typecheck:false begin fun sigma ->
2535 let id = make_annot id rel in
2536 let nhyps = EConstr.push_named_context_val (NamedDecl.LocalDef (id, c, t)) hyps in
2537 let (sigma, ev) = Evarutil.new_pure_evar nhyps sigma ~relevance concl in
2538 let inst = EConstr.identity_subst_val hyps in
2539 let body = mkEvar (ev, SList.cons (mkRel 1) inst) in
2540 (sigma, mkLetIn (map_annot Name.mk_name id, c, t, body))
2541 end
2542 end
2543
2544 let letin_tac with_eq id c ty occs =
2545 Proofview.Goal.enter begin fun gl ->
2546 let sigma = Proofview.Goal.sigma gl in
2547 let env = Proofview.Goal.env gl in
2548 let ccl = Proofview.Goal.concl gl in
2549 let abs = AbstractExact (id,c,ty,occs,true) in
2550 let (id,_,depdecls,lastlhyp,ccl,res) = make_abstraction env sigma ccl abs in
2551 (* We keep the original term to match but record the potential side-effects
2552 of unifying universes. *)
2553 let (sigma, c) = match res with
2554 | None -> (sigma, c)
2555 | Some (sigma, _) -> (sigma, c)
2556 in
2557 Proofview.tclTHEN (Proofview.Unsafe.tclEVARS sigma)
2558 (letin_tac_gen with_eq (id,depdecls,lastlhyp,ccl,c) ty)
2559 end
2560
2561 let letin_pat_tac with_evars with_eq id c occs =
2562 Proofview.Goal.enter begin fun gl ->
2563 let sigma = Proofview.Goal.sigma gl in
2564 let env = Proofview.Goal.env gl in
2565 let ccl = Proofview.Goal.concl gl in
2566 let check t = true in
2567 let abs = AbstractPattern (false,check,id,c,occs) in
2568 let (id,_,depdecls,lastlhyp,ccl,res) = make_abstraction env sigma ccl abs in
2569 let (sigma, c) = match res with
2570 | None -> finish_evar_resolution ~flags:(tactic_infer_flags with_evars) env sigma c
2571 | Some res -> res in
2572 Proofview.tclTHEN (Proofview.Unsafe.tclEVARS sigma)
2573 (letin_tac_gen with_eq (id,depdecls,lastlhyp,ccl,c) None)
2574 end
2575
2576 (* Tactics "pose proof" (usetac=None) and "assert"/"enough" (otherwise) *)
2577 let forward b usetac ipat c =
2578 match usetac with
2579 | None ->
2580 Proofview.Goal.enter begin fun gl ->
2581 let env = Proofview.Goal.env gl in
2582 let sigma = Proofview.Goal.sigma gl in
2583 let t = Retyping.get_type_of env sigma c in
2584 let hd = head_ident sigma c in
2585 let assert_as =
2586 let naming,tac = prepare_intros_opt false IntroAnonymous MoveLast ipat in
2587 let repl = do_replace hd naming in
2588 if repl then assert_before_gen true naming t
2589 else assert_before_then_gen false naming t tac
2590 in
2591 Tacticals.tclTHENFIRST assert_as (exact_no_check c)
2592 end
2593 | Some tac ->
2594 let tac = match tac with
2595 | None -> Tacticals.tclIDTAC
2596 | Some tac -> Tacticals.tclCOMPLETE tac in
2597 let naming, assert_tac = prepare_intros_opt false IntroAnonymous MoveLast ipat in
2598 if b then
2599 Tacticals.tclTHENFIRST (assert_before_then_gen false naming c assert_tac) tac
2600 else
2601 Tacticals.tclTHENS3PARTS
2602 (assert_after_then_gen false naming c assert_tac) [||] tac [|Tacticals.tclIDTAC|]
2603
2604 let pose_proof na c = forward true None (ipat_of_name na) c
2605 let assert_by na t tac = forward true (Some (Some tac)) (ipat_of_name na) t
2606 let enough_by na t tac = forward false (Some (Some tac)) (ipat_of_name na) t
2607
2608 (* Instantiating some arguments (whatever their position) of an hypothesis
2609 or any term, leaving other arguments quantified. If operating on an
2610 hypothesis of the goal, the new hypothesis replaces it.
2611
2612 (c,lbind) are supposed to be of the form
2613 ((H t1 t2 ... tm) , someBindings)
2614 whete t1..tn are user given args, to which someBinding must be combined.
2615
2616 The goal is to pose a proof with body
2617
2618 (fun y1...yp => H t1 t2 ... tm u1 ... uq)
2619
2620 where yi are the remaining arguments of H that lbind could not
2621 solve, ui are a mix of inferred args and yi. The overall effect
2622 is to remove from H as much quantification as possible given
2623 lbind. *)
2624
2625 module Specialize :
2626 sig
2627 val unify_bindings : evar_map -> (evar_map -> int -> 'a -> evar_map) ->
2628 types -> 'a bindings -> evar_map
2629 (* Unfortunate small code duplication with EClause *)
2630 end =
2631 struct
2632
2633 type hole = {
2634 hole_evar : int;
2635 hole_deps : bool;
2636 hole_name : Name.t;
2637 }
2638
2639 let make_evar_clause sigma t =
2640 let open EConstr in
2641 let open Vars in
2642 let rec clrec holes n t = match EConstr.kind sigma t with
2643 | Cast (t, _, _) -> clrec holes n t
2644 | Prod (na, t1, t2) ->
2645 let dep = not (noccurn sigma 1 t2) in
2646 let hole = { hole_evar = n; hole_deps = dep; hole_name = na.binder_name; } in
2647 clrec (hole :: holes) (n + 1) t2
2648 | LetIn (na, b, _, t) -> clrec holes n (subst1 b t)
2649 | _ -> holes
2650 in
2651 let holes = clrec [] 0 t in
2652 List.rev holes
2653
2654 let evar_with_name holes ({CAst.v=id} as lid) =
2655 let map h = match h.hole_name with
2656 | Anonymous -> None
2657 | Name id' -> if Id.equal id id' then Some h else None
2658 in
2659 let hole = List.map_filter map holes in
2660 match hole with
2661 | [] ->
2662 let fold h accu = match h.hole_name with
2663 | Anonymous -> accu
2664 | Name id -> id :: accu
2665 in
2666 let mvl = List.fold_right fold holes [] in
2667 EClause.explain_no_such_bound_variable mvl lid
2668 | h::_ -> h.hole_evar
2669
2670 let evar_of_binder holes = function
2671 | NamedHyp s -> evar_with_name holes s
2672 | AnonHyp n ->
2673 try
2674 let nondeps = List.filter (fun hole -> not hole.hole_deps) holes in
2675 let h = List.nth nondeps (pred n) in
2676 h.hole_evar
2677 with e when CErrors.noncritical e ->
2678 user_err Pp.(str "No such binder.")
2679
2680 let solve_evar_clause sigma unify holes = function
2681 | NoBindings -> sigma
2682 | ImplicitBindings largs ->
2683 let map h = if h.hole_deps then Some h.hole_evar else None in
2684 let evs = List.map_filter map holes in
2685 let len = List.length evs in
2686 if Int.equal len (List.length largs) then
2687 let fold sigma ev arg = unify sigma ev arg in
2688 let sigma = List.fold_left2 fold sigma evs largs in
2689 sigma
2690 else
2691 EClause.error_not_right_number_missing_arguments len
2692 | ExplicitBindings lbind ->
2693 let () = EClause.check_bindings lbind in
2694 let fold sigma {CAst.v=(binder, c)} =
2695 let ev = evar_of_binder holes binder in
2696 unify sigma ev c
2697 in
2698 let sigma = List.fold_left fold sigma lbind in
2699 sigma
2700
2701 let unify_bindings sigma unify ty =
2702 let holes = make_evar_clause sigma ty in
2703 solve_evar_clause sigma unify holes
2704
2705 end
2706
2707 let specialize (c,lbind) ipat =
2708 Proofview.Goal.enter begin fun gl ->
2709 let env = Proofview.Goal.env gl in
2710 let sigma = Proofview.Goal.sigma gl in
2711 let typ_of_c = Retyping.get_type_of env sigma c in
2712 let sigma, term, typ = match lbind with
2713 | NoBindings ->
2714 sigma, c, typ_of_c
2715 | ExplicitBindings _ | ImplicitBindings _ ->
2716 let ctx, ty = decompose_prod_decls sigma typ_of_c in
2717 (* Create a new context where variables mentioned further in the telescope
2718 are turned into evars that live in the telescope context. This allows
2719 instantiating each evar with the original variable as a default value.
2720
2721 For instance, on Γ := [x : A, y : B{x}, z : C{x, y}] it produces evars
2722 [x : A ⊢ ?X : A]
2723 [x : A, y : B{?X{x}} ⊢ ?Y : B{?X{x}}]
2724 [x : A, y : B{?X{x}}, z : C{?X{x}, ?Y{x, y}} ⊢ ?Z : C{?X{x}, ?Y{x, y}}]
2725 and returns the context
2726 Δ := [x : A, y : B{?X{x}}, z : C{?X{x}, ?Y{x, y}}]
2727 together with a substitution [?X, ?Y, ?Z] : Γ ⊢ Δ.
2728 *)
2729 let open RelDecl in
2730 let rec instantiate sigma env subst accu = function
2731 | [] -> sigma, subst, rel_context env, List.rev accu
2732 | LocalAssum (na, t) :: decls ->
2733 let t = Vars.esubst Vars.lift_substituend subst t in
2734 let env = push_rel (LocalAssum (na, t)) env in
2735 let typeclass_candidate = Typeclasses.is_maybe_class_type env sigma t in
2736 let sigma, ev = Evarutil.new_evar ~typeclass_candidate env sigma (lift 1 t) in
2737 let subst = Esubst.subs_cons (Vars.make_substituend ev) (Esubst.subs_shft (1, subst)) in
2738 instantiate sigma env subst ((env, ev) :: accu) decls
2739 | LocalDef (na, b, t) :: decls ->
2740 let b = Vars.esubst Vars.lift_substituend subst b in
2741 let t = Vars.esubst Vars.lift_substituend subst t in
2742 let env = push_rel (LocalDef (na, b, t)) env in
2743 let subst = Esubst.subs_lift subst in
2744 instantiate sigma env subst accu decls
2745 in
2746 let sigma, subst, nctx, holes = instantiate sigma env (Esubst.subs_id 0) [] (List.rev ctx) in
2747 let nty = Vars.esubst Vars.lift_substituend subst ty in
2748 (* Solve holes with the provided bindings *)
2749 let unify sigma n c =
2750 let env, ev = List.nth holes n in
2751 Evarconv.unify env sigma CONV ev c
2752 in
2753 let sigma = Specialize.unify_bindings sigma unify typ_of_c lbind in
2754 (* Instantiate unsolved holes with their default value *)
2755 let fold sigma (env, ev) =
2756 if isEvar sigma ev then Evarconv.unify env sigma CONV ev (mkRel 1)
2757 else sigma
2758 in
2759 let sigma = List.fold_left fold sigma holes in
2760 (* Requantify the proof term and its type *)
2761 let args = Context.Rel.instance_list mkRel 0 ctx in
2762 let nc = applist (c, List.map (fun c -> Vars.esubst Vars.lift_substituend subst c) args) in
2763 let rec rebuild rels ctx c ty = match ctx with
2764 | [] -> c, ty
2765 | decl :: ctx ->
2766 let lift s = Int.Set.fold (fun n accu -> Int.Set.add (n - 1) accu) s Int.Set.empty in
2767 let c, ty, rels =
2768 (* We always keep let bindings *)
2769 if RelDecl.is_local_def decl || Int.Set.mem 1 rels then
2770 let rels = lift (Int.Set.remove 1 rels) in
2771 let rels = RelDecl.fold_constr (fun c accu -> Int.Set.union accu (free_rels sigma c)) decl rels in
2772 mkLambda_or_LetIn decl c, mkProd_or_LetIn decl ty, rels
2773 else subst1 mkProp (* dummy *) c, subst1 mkProp ty, lift rels
2774 in
2775 rebuild rels ctx c ty
2776 in
2777 let rels = Int.Set.union (free_rels sigma nc) (free_rels sigma nty) in
2778 let nc, nty = rebuild rels nctx nc nty in
2779 sigma, nc, nty
2780 in
2781 let tac =
2782 match EConstr.kind sigma (fst(EConstr.decompose_app sigma (snd(EConstr.decompose_lambda_decls sigma c)))) with
2783 | Var id when Id.List.mem id (Tacmach.pf_ids_of_hyps gl) ->
2784 (* Like assert (id:=id args) but with the concept of specialization *)
2785 let ipat = match ipat with None -> Some (CAst.make (IntroNaming (IntroIdentifier id))) | _ -> ipat in
2786 let naming,tac = prepare_intros_opt false IntroAnonymous MoveLast ipat in
2787 let repl = do_replace (Some id) naming in
2788 (* "specialize H ... as H", "specialize H ...": do not clear (cleared implicitly at replacing time) *)
2789 (* "specialize H ... as H'", "specialize H ... as ?H": keep a copy by convention *)
2790 (* "specialize H ... as any_other_pattern": clear *)
2791 let doclear = match ipat with
2792 | Some {CAst.v=IntroNaming (IntroIdentifier _ | IntroFresh _)} -> false
2793 | _ -> true in
2794 let tac = if doclear then fun id' -> Tacticals.tclTHEN (clear [id]) (tac id') else tac in
2795 Tacticals.tclTHENFIRST
2796 (assert_before_then_gen repl naming typ tac)
2797 (exact_no_check term)
2798 | _ ->
2799 match ipat with
2800 | None ->
2801 (* Like generalize with extra support for "with" bindings *)
2802 (* even though the "with" bindings forces full application *)
2803 (* TODO: add intro to be more homogeneous. It will break
2804 scripts but will be easy to fix *)
2805 (Tacticals.tclTHENLAST (cut typ) (exact_no_check term))
2806 | Some _ as ipat ->
2807 (* Like pose proof with extra support for "with" bindings *)
2808 (* even though the "with" bindings forces full application *)
2809 let naming, tac = prepare_intros_opt false IntroAnonymous MoveLast ipat in
2810 Tacticals.tclTHENFIRST
2811 (assert_before_then_gen false naming typ tac)
2812 (exact_no_check term)
2813 in
2814 Tacticals.tclTHEN (Proofview.Unsafe.tclEVARS sigma) tac
2815 end
2816
2817 (*****************************)
2818 (* Ad hoc unfold *)
2819 (*****************************)
2820
2821 (* The two following functions should already exist, but found nowhere *)
2822 (* Unfolds x by its definition everywhere *)
2823 let unfold_body x =
2824 let open Context.Named.Declaration in
2825 Proofview.Goal.enter begin fun gl ->
2826 (* We normalize the given hypothesis immediately. *)
2827 let env = Proofview.Goal.env gl in
2828 let sigma = Proofview.Goal.sigma gl in
2829 let xval = match Environ.lookup_named x env with
2830 | LocalAssum _ -> TacticErrors.variable_has_no_value x
2831 | LocalDef (_,xval,_) -> xval
2832 in
2833 let xval = EConstr.of_constr xval in
2834 Tacticals.afterHyp x begin fun aft ->
2835 let hl = List.fold_right (fun decl cl -> (NamedDecl.get_id decl, InHyp) :: cl) aft [] in
2836 let rfun _ _ c = replace_vars sigma [x, xval] c in
2837 let reducth h = reduct_in_hyp ~check:false ~reorder:false rfun h in
2838 let reductc = reduct_in_concl ~cast:false ~check:false (rfun, DEFAULTcast) in
2839 Tacticals.tclTHENLIST [Tacticals.tclMAP reducth hl; reductc]
2840 end
2841 end
2842
2843 let dest_intro_patterns with_evars avoid thin dest pat tac =
2844 intro_patterns_core with_evars avoid [] thin dest None 0 tac pat
2845
2846 let rocq_heq_ref = lazy (Rocqlib.lib_ref "core.JMeq.type")
2847
2848 let compare_upto_variables sigma x y =
2849 let rec compare x y =
2850 if (isVar sigma x || isRel sigma x) && (isVar sigma y || isRel sigma y) then true
2851 else compare_constr sigma compare x y
2852 in
2853 compare x y
2854
2855 let specialize_eqs id =
2856 let open Context.Rel.Declaration in
2857 Proofview.Goal.enter begin fun gl ->
2858 let env = Proofview.Goal.env gl in
2859 let ty = Tacmach.pf_get_hyp_typ id gl in
2860 let evars = ref (Proofview.Goal.sigma gl) in
2861 let unif env evars c1 c2 =
2862 compare_upto_variables !evars c1 c2 &&
2863 (match Evarconv.unify_delay env !evars c1 c2 with
2864 | sigma -> evars := sigma; true
2865 | exception Evarconv.UnableToUnify _ -> false)
2866 in
2867 let rec aux in_eqs ctx acc ty =
2868 match EConstr.kind !evars ty with
2869 | Prod (na, t, b) ->
2870 (match EConstr.kind !evars t with
2871 | App (eq, [| eqty; x; y |]) when is_lib_ref env !evars "core.eq.type" eq ->
2872 let c = if noccur_between !evars 1 (List.length ctx) x then y else x in
2873 let pt = mkApp (eq, [| eqty; c; c |]) in
2874 let ind = destInd !evars eq in
2875 let p = mkApp (mkConstructUi (ind,0), [| eqty; c |]) in
2876 if unif (push_rel_context ctx env) evars pt t then
2877 aux true ctx (mkApp (acc, [| p |])) (subst1 p b)
2878 else acc, in_eqs, ctx, ty
2879 | App (heq, [| eqty; x; eqty'; y |]) when isRefX env !evars (Lazy.force rocq_heq_ref) heq ->
2880 let eqt, c = if noccur_between !evars 1 (List.length ctx) x then eqty', y else eqty, x in
2881 let pt = mkApp (heq, [| eqt; c; eqt; c |]) in
2882 let ind = destInd !evars heq in
2883 let p = mkApp (mkConstructUi (ind,0), [| eqt; c |]) in
2884 if unif (push_rel_context ctx env) evars pt t then
2885 aux true ctx (mkApp (acc, [| p |])) (subst1 p b)
2886 else acc, in_eqs, ctx, ty
2887 | _ ->
2888 if in_eqs then acc, in_eqs, ctx, ty
2889 else
2890 let typeclass_candidate = Typeclasses.is_maybe_class_type env !evars t in
2891 let sigma, e = Evarutil.new_evar ~typeclass_candidate (push_rel_context ctx env) !evars t in
2892 evars := sigma;
2893 aux false (LocalDef (na,e,t) :: ctx) (mkApp (lift 1 acc, [| mkRel 1 |])) b)
2894 | t -> acc, in_eqs, ctx, ty
2895 in
2896 let acc, worked, ctx, ty = aux false [] (mkVar id) ty in
2897 let ctx' = nf_rel_context_evar !evars ctx in
2898 let ctx'' = List.map (function
2899 | LocalDef (n,k,t) when isEvar !evars k -> LocalAssum (n,t)
2900 | decl -> decl) ctx'
2901 in
2902 let ty' = it_mkProd_or_LetIn ty ctx'' in
2903 let acc' = it_mkLambda_or_LetIn acc ctx'' in
2904 let ty' = Tacred.whd_simpl env !evars ty'
2905 and acc' = Tacred.whd_simpl env !evars acc' in
2906 let ty' = Evarutil.nf_evar !evars ty' in
2907 if worked then
2908 Tacticals.tclTHENFIRST
2909 (internal_cut true id ty')
2910 (exact_no_check ((* refresh_universes_strict *) acc'))
2911 else
2912 let info = Exninfo.reify () in
2913 Tacticals.tclFAIL ~info (str "Nothing to do in hypothesis " ++ Id.print id)
2914 end
2915
2916 let specialize_eqs id = Proofview.Goal.enter begin fun gl ->
2917 let msg = str "Specialization not allowed on dependent hypotheses" in
2918 Proofview.tclOR (clear [id])
2919 (fun (_,info) -> Tacticals.tclZEROMSG ~info msg) >>= fun () ->
2920 specialize_eqs id
2921 end
2922
2923 let exfalso =
2924 Proofview.Goal.enter begin fun gl ->
2925 let env = Proofview.Goal.env gl in
2926 let sigma = Proofview.Goal.sigma gl in
2927 let (sigma, f) = Evd.fresh_global env sigma (Rocqlib.lib_ref "core.False.type") in
2928 let (ind, _) = reduce_to_atomic_ind env sigma f in
2929 let s = Retyping.get_sort_quality_of env sigma (Proofview.Goal.concl gl) in
2930 let sigma, elimc = find_ind_eliminator env sigma (fst ind) s in
2931 let elimc = mkConstU elimc in
2932 let elimt = Retyping.get_type_of env sigma elimc in
2933 let clause = mk_clenv_from env sigma (elimc, elimt) in
2934 Proofview.tclTHEN (Proofview.Unsafe.tclEVARS sigma) (Clenv.res_pf clause ~flags:(elim_flags ()) ~with_evars:false)
2935 end
2936
2937 (************************************************)
2938 (* Tactics related with logic connectives *)
2939 (************************************************)
2940
2941 (* Reflexivity tactics *)
2942
2943 let (forward_setoid_reflexivity, setoid_reflexivity) = Hook.make ()
2944
2945 let maybe_betadeltaiota_concl allowred gl =
2946 let env = Proofview.Goal.env gl in
2947 let sigma = Proofview.Goal.sigma gl in
2948 let concl = Proofview.Goal.concl gl in
2949 if not allowred then concl
2950 else whd_all env sigma concl
2951
2952 let reflexivity_red allowred =
2953 Proofview.Goal.enter begin fun gl ->
2954 (* PL: usual reflexivity don't perform any reduction when searching
2955 for an equality, but we may need to do some when called back from
2956 inside setoid_reflexivity (see Optimize cases in setoid_replace.ml). *)
2957 let env = Proofview.Goal.env gl in
2958 let sigma = Proofview.Goal.sigma gl in
2959 let concl = maybe_betadeltaiota_concl allowred gl in
2960 match match_with_equality_type env sigma concl with
2961 | None ->
2962 let info = Exninfo.reify () in
2963 Proofview.tclZERO ~info NoEquationFound
2964 | Some _ -> one_constructor 1 NoBindings
2965 end
2966
2967 let reflexivity =
2968 Proofview.tclORELSE
2969 (reflexivity_red false)
2970 begin function (e, info) -> match e with
2971 | NoEquationFound -> Hook.get forward_setoid_reflexivity
2972 | e -> Proofview.tclZERO ~info e
2973 end
2974
2975 let intros_reflexivity = (Tacticals.tclTHEN intros reflexivity)
2976
2977 (* Symmetry tactics *)
2978
2979 (* This tactic first tries to apply a constant named sym_eq, where eq
2980 is the name of the equality predicate. If this constant is not
2981 defined and the conclusion is a=b, it solves the goal doing (Cut
2982 b=a;Intro H;Case H;Constructor 1) *)
2983
2984 let (forward_setoid_symmetry, setoid_symmetry) = Hook.make ()
2985
2986 (* This is probably not very useful any longer *)
2987 let prove_symmetry hdcncl eq_kind =
2988 let symc =
2989 match eq_kind with
2990 | MonomorphicLeibnizEq (c1,c2) -> mkApp(hdcncl,[|c2;c1|])
2991 | PolymorphicLeibnizEq (typ,c1,c2) -> mkApp(hdcncl,[|typ;c2;c1|])
2992 | HeterogenousEq (t1,c1,t2,c2) -> mkApp(hdcncl,[|t2;c2;t1;c1|]) in
2993 Tacticals.tclTHENFIRST (cut symc)
2994 (Tacticals.tclTHENLIST
2995 [ intro;
2996 Tacticals.onLastHyp simplest_case;
2997 one_constructor 1 NoBindings ])
2998
2999 let match_with_equation c =
3000 Proofview.tclEVARMAP >>= fun sigma ->
3001 Proofview.tclENV >>= fun env ->
3002 try
3003 let res = match_with_equation env sigma c in
3004 Proofview.tclUNIT res
3005 with NoEquationFound as exn ->
3006 let _, info = Exninfo.capture exn in
3007 Proofview.tclZERO ~info NoEquationFound
3008
3009 let symmetry_red allowred =
3010 Proofview.Goal.enter begin fun gl ->
3011 (* PL: usual symmetry don't perform any reduction when searching
3012 for an equality, but we may need to do some when called back from
3013 inside setoid_reflexivity (see Optimize cases in setoid_replace.ml). *)
3014 let concl = maybe_betadeltaiota_concl allowred gl in
3015 match_with_equation concl >>= fun with_eqn ->
3016 match with_eqn with
3017 | Some eq_data,_,_ ->
3018 Tacticals.tclTHEN
3019 (convert_concl ~cast:false ~check:false concl DEFAULTcast)
3020 (Tacticals.pf_constr_of_global eq_data.sym >>= apply)
3021 | None,eq,eq_kind -> prove_symmetry eq eq_kind
3022 end
3023
3024 let symmetry =
3025 Proofview.tclORELSE
3026 (symmetry_red false)
3027 begin function (e, info) -> match e with
3028 | NoEquationFound -> Hook.get forward_setoid_symmetry
3029 | e -> Proofview.tclZERO ~info e
3030 end
3031
3032 let (forward_setoid_symmetry_in, setoid_symmetry_in) = Hook.make ()
3033
3034
3035 let symmetry_in id =
3036 Proofview.Goal.enter begin fun gl ->
3037 let env = Proofview.Goal.env gl in
3038 let sigma = Proofview.Goal.sigma gl in
3039 let sigma, ctype = Typing.type_of env sigma (mkVar id) in
3040 let sign,t = decompose_prod_decls sigma ctype in
3041 tclEVARSTHEN sigma
3042 (Proofview.tclORELSE
3043 begin
3044 match_with_equation t >>= fun (_,hdcncl,eq) ->
3045 let symccl =
3046 match eq with
3047 | MonomorphicLeibnizEq (c1,c2) -> mkApp (hdcncl, [| c2; c1 |])
3048 | PolymorphicLeibnizEq (typ,c1,c2) -> mkApp (hdcncl, [| typ; c2; c1 |])
3049 | HeterogenousEq (t1,c1,t2,c2) -> mkApp (hdcncl, [| t2; c2; t1; c1 |]) in
3050 Tacticals.tclTHENS (cut (EConstr.it_mkProd_or_LetIn symccl sign))
3051 [ intro_replacing id;
3052 Tacticals.tclTHENLIST [ intros; symmetry; apply (mkVar id); assumption ] ]
3053 end
3054 begin function (e, info) -> match e with
3055 | NoEquationFound -> Hook.get forward_setoid_symmetry_in id
3056 | e -> Proofview.tclZERO ~info e
3057 end)
3058 end
3059
3060 let intros_symmetry =
3061 Tacticals.onClause
3062 (function
3063 | None -> Tacticals.tclTHEN intros symmetry
3064 | Some id -> symmetry_in id)
3065
3066 (* Transitivity tactics *)
3067
3068 (* This tactic first tries to apply a constant named eq_trans, where eq
3069 is the name of the equality predicate. If this constant is not
3070 defined and the conclusion is a=b, it solves the goal doing
3071 Cut x1=x2;
3072 [Cut x2=x3; [Intros e1 e2; Case e2;Assumption
3073 | Idtac]
3074 | Idtac]
3075 --Eduardo (19/8/97)
3076 *)
3077
3078 let (forward_setoid_transitivity, setoid_transitivity) = Hook.make ()
3079
3080
3081 (* This is probably not very useful any longer *)
3082 let prove_transitivity hdcncl eq_kind t =
3083 Proofview.Goal.enter begin fun gl ->
3084 let eq1, eq2 = match eq_kind with
3085 | MonomorphicLeibnizEq (c1,c2) ->
3086 mkApp (hdcncl, [| c1; t|]), mkApp (hdcncl, [| t; c2 |])
3087 | PolymorphicLeibnizEq (typ,c1,c2) ->
3088 mkApp (hdcncl, [| typ; c1; t |]), mkApp (hdcncl, [| typ; t; c2 |])
3089 | HeterogenousEq (typ1,c1,typ2,c2) ->
3090 let env = Proofview.Goal.env gl in
3091 let sigma = Proofview.Goal.sigma gl in
3092 let typt = Retyping.get_type_of env sigma t in
3093 mkApp(hdcncl, [| typ1; c1; typt ;t |]),
3094 mkApp(hdcncl, [| typt; t; typ2; c2 |])
3095 in
3096 Tacticals.tclTHENFIRST (cut eq2)
3097 (Tacticals.tclTHENFIRST (cut eq1)
3098 (Tacticals.tclTHENLIST
3099 [ Tacticals.tclDO 2 intro;
3100 Tacticals.onLastHyp simplest_case;
3101 assumption ]))
3102 end
3103
3104 let transitivity_red allowred t =
3105 Proofview.Goal.enter begin fun gl ->
3106 (* PL: usual transitivity don't perform any reduction when searching
3107 for an equality, but we may need to do some when called back from
3108 inside setoid_reflexivity (see Optimize cases in setoid_replace.ml). *)
3109 let concl = maybe_betadeltaiota_concl allowred gl in
3110 match_with_equation concl >>= fun with_eqn ->
3111 match with_eqn with
3112 | Some eq_data,_,_ ->
3113 Tacticals.tclTHEN
3114 (convert_concl ~cast:false ~check:false concl DEFAULTcast)
3115 (match t with
3116 | None -> Tacticals.pf_constr_of_global eq_data.trans >>= eapply
3117 | Some t -> Tacticals.pf_constr_of_global eq_data.trans >>= fun trans -> apply_list [trans; t])
3118 | None,eq,eq_kind ->
3119 match t with
3120 | None ->
3121 let info = Exninfo.reify () in
3122 Tacticals.tclZEROMSG ~info (str"etransitivity not supported for this relation.")
3123 | Some t -> prove_transitivity eq eq_kind t
3124 end
3125
3126 let transitivity_gen t =
3127 Proofview.tclORELSE
3128 (transitivity_red false t)
3129 begin function (e, info) -> match e with
3130 | NoEquationFound -> Hook.get forward_setoid_transitivity t
3131 | e -> Proofview.tclZERO ~info e
3132 end
3133
3134 let etransitivity = transitivity_gen None
3135 let transitivity t = transitivity_gen (Some t)
3136
3137 let intros_transitivity n = Tacticals.tclTHEN intros (transitivity_gen n)
3138
3139 let constr_eq ~strict x y =
3140 let fail ~info = Tacticals.tclFAIL ~info (str "Not equal") in
3141 let fail_universes ~info = Tacticals.tclFAIL ~info (str "Not equal (due to universes)") in
3142 Proofview.Goal.enter begin fun gl ->
3143 let env = Proofview.Goal.env gl in
3144 let evd = Proofview.Goal.sigma gl in
3145 match EConstr.eq_constr_universes env evd x y with
3146 | Some csts ->
3147 if strict then
3148 if UState.check_constraints (Evd.ustate evd) csts
3149 then Proofview.tclUNIT ()
3150 else
3151 let info = Exninfo.reify () in
3152 fail_universes ~info
3153 else
3154 let csts = UnivProblem.Set.force csts in
3155 begin match Evd.add_constraints evd csts with
3156 | evd -> Proofview.Unsafe.tclEVARS evd
3157 | exception (UGraph.UniverseInconsistency _ as e) ->
3158 let _, info = Exninfo.capture e in
3159 fail_universes ~info
3160 end
3161 | None ->
3162 let info = Exninfo.reify () in
3163 fail ~info
3164 end
3165
3166 let unify ?(state=TransparentState.full) x y =
3167 Proofview.Goal.enter begin fun gl ->
3168 let env = Proofview.Goal.env gl in
3169 let sigma = Proofview.Goal.sigma gl in
3170 try
3171 let core_flags =
3172 { (default_unify_flags ()).core_unify_flags with
3173 modulo_delta = state;
3174 modulo_conv_on_closed_terms = Some state} in
3175 (* What to do on merge and subterm flags?? *)
3176 let flags = { (default_unify_flags ()) with
3177 core_unify_flags = core_flags;
3178 merge_unify_flags = core_flags;
3179 subterm_unify_flags = { core_flags with modulo_delta = TransparentState.empty } }
3180 in
3181 let _, sigma = w_unify env sigma Conversion.CONV ~flags x y in
3182 Proofview.Unsafe.tclEVARS sigma
3183 with e when noncritical e ->
3184 let e, info = Exninfo.capture e in
3185 Proofview.tclZERO ~info (PretypeError (env, sigma, CannotUnify (x, y, None)))
3186 end
3187
3188 let evarconv_unify ?(state=TransparentState.full) ?(with_ho=true) x y =
3189 Proofview.Goal.enter begin fun gl ->
3190 let env = Proofview.Goal.env gl in
3191 let sigma = Proofview.Goal.sigma gl in
3192 try
3193 let flags = Evarconv.default_flags_of state in
3194 let sigma = Evarconv.unify ~flags ~with_ho env sigma Conversion.CONV x y in
3195 Proofview.Unsafe.tclEVARS sigma
3196 with e when noncritical e ->
3197 let e, info = Exninfo.capture e in
3198 Proofview.tclZERO ~info (PretypeError (env, sigma, CannotUnify (x, y, None)))
3199 end
3200
3201 (** [tclWRAPFINALLY before tac finally] runs [before] before each
3202 entry-point of [tac] and passes the result of [before] to
3203 [finally], which is then run at each exit-point of [tac],
3204 regardless of whether it succeeds or fails. Said another way, if
3205 [tac] succeeds, then it behaves as [before >>= fun v -> tac >>= fun
3206 ret -> finally v <*> tclUNIT ret]; otherwise, if [tac] fails with
3207 [e], it behaves as [before >>= fun v -> finally v <*> tclZERO
3208 e]. Note that if [tac] succeeds [n] times before finally failing,
3209 [before] and [finally] are both run [n+1] times (once around each
3210 succuess, and once more around the final failure). *)
3211 (* We should probably export this somewhere, but it's not clear
3212 where. As per
3213 https://github.com/rocq-prover/rocq/pull/12197#discussion_r418480525 and
3214 https://gitter.im/coq/coq?at=5ead5c35347bd616304e83ef, we don't
3215 export it from Proofview, because it seems somehow not primitive
3216 enough. We don't export it from this file because it is more of a
3217 tactical than a tactic. But we also don't export it from Tacticals
3218 because all of the non-New tacticals there operate on `tactic`, not
3219 `Proofview.tactic`, and all of the `New` tacticals that deal with
3220 multi-success things are focussing, i.e., apply their arguments on
3221 each goal separately (and it even says so in the comment on `New`),
3222 whereas it's important that `tclWRAPFINALLY` doesn't introduce
3223 extra focussing. *)
3224 let rec tclWRAPFINALLY before tac finally =
3225 let open Proofview in
3226 let open Proofview.Notations in
3227 before >>= fun v -> tclCASE tac >>= function
3228 | Fail (e, info) -> finally v >>= fun () -> tclZERO ~info e
3229 | Next (ret, tac') -> tclOR
3230 (finally v >>= fun () -> tclUNIT ret)
3231 (fun e -> tclWRAPFINALLY before (tac' e) finally)
3232
3233 let with_set_strategy lvl_ql k =
3234 let glob_key r =
3235 match r with
3236 | GlobRef.ConstRef sp ->
3237 begin
3238 match Structures.PrimitiveProjections.find_opt sp with
3239 | None -> Evaluable.EvalConstRef sp
3240 | Some p -> Evaluable.EvalProjectionRef p
3241 end
3242 | GlobRef.VarRef id -> Evaluable.EvalVarRef id
3243 | _ -> user_err Pp.(str
3244 "cannot set an inductive type or a constructor as transparent") in
3245 let get_strategy env kl =
3246 let ts = Environ.oracle env in
3247 let map (_, k) = (Conv_oracle.get_strategy ts (Evaluable.to_kevaluable k), k) in
3248 List.map map kl
3249 in
3250 let set_strategy env kl =
3251 let fold accu (lvl, k) = Conv_oracle.set_strategy accu (Evaluable.to_kevaluable k) lvl in
3252 let ts = List.fold_left fold (Environ.oracle env) kl in
3253 Environ.set_oracle env ts
3254 in
3255 let kl = List.concat (List.map (fun (lvl, ql) -> List.map (fun q -> (lvl, glob_key q)) ql) lvl_ql) in
3256 tclWRAPFINALLY
3257 (Proofview.tclENV >>= fun env ->
3258 let orig_kl = get_strategy env kl in
3259 let env = set_strategy env kl in
3260 Proofview.Unsafe.tclSETENV env <*>
3261 Proofview.tclUNIT orig_kl)
3262 k
3263 (fun orig_kl ->
3264 Proofview.tclENV >>= fun env ->
3265 let env = set_strategy env orig_kl in
3266 Proofview.Unsafe.tclSETENV env)
3267
3268 module Simple = struct
3269 (** Simplified version of some of the above tactics *)
3270
3271 let intro x = intro_move (Some x) MoveLast
3272
3273 let apply c =
3274 apply_with_bindings_gen false false [None,(CAst.make (c,NoBindings))]
3275 let eapply c =
3276 apply_with_bindings_gen false true [None,(CAst.make (c,NoBindings))]
3277 let elim c = elim false None (c,NoBindings) None
3278 let case c = general_case_analysis false None (c,NoBindings)
3279
3280 let apply_in id c =
3281 apply_in false false id [None,(CAst.make (c, NoBindings))] None
3282
3283 end
3284
3285
3286 (** Tacticals defined directly in term of Proofview *)
3287 let reduce_after_refine =
3288 (* For backward compatibility reasons, we do not contract let-ins, but we unfold them. *)
3289 let redfun env t =
3290 let flags = RedFlags.red_add_transparent RedFlags.allnolet TransparentState.empty in
3291 clos_norm_flags flags env t
3292 in
3293 reduct_in_concl ~cast:false ~check:false (redfun,DEFAULTcast)
3294
3295 let refine ~typecheck c =
3296 Refine.refine ~typecheck c <*>
3297 reduce_after_refine
3298
3299 module Internal =
3300 struct
3301
3302 let explicit_intro_names = explicit_intro_names
3303 let check_name_unicity = check_name_unicity
3304 let clear_gen = clear_gen
3305 let clear_wildcards = clear_wildcards
3306 let dest_intro_patterns = dest_intro_patterns
3307
3308 end
3309
3310 (**********************************************************)
3311 (** Moved functions. *)
3312 (**********************************************************)
3313
3314 exception NotConvertible = TacticErrors.NotConvertible
3315
3316 let fix = FixTactics.fix
3317
3318 let mutual_fix = FixTactics.mutual_fix
3319
3320 let cofix = FixTactics.cofix
3321
3322 let mutual_cofix = FixTactics.mutual_cofix