Debian Codegraph @

plugins/ssr/ssripats.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 Ssrmatching_plugin
12
13 open Util
14 open Names
15 open Constr
16 open Context
17
18 open Proofview
19 open Proofview.Notations
20
21 open Ssrast
22
23 type ssriop =
24 | IOpId of Names.Id.t
25 | IOpDrop
26 | IOpTemporay
27 | IOpInaccessible of string option
28 | IOpInaccessibleAll
29 | IOpAbstractVars of Names.Id.t list
30 | IOpFastNondep
31
32 | IOpInj of ssriops list
33
34 | IOpDispatchBlock of id_block
35 | IOpDispatchBranches of ssriops list
36
37 | IOpCaseBlock of id_block
38 | IOpCaseBranches of ssriops list
39
40 | IOpRewrite of ssrocc * ssrdir
41 | IOpView of ssrclear option * ssrview (* extra clears to be performed *)
42
43 | IOpClear of ssrclear * ssrhyp option (* must clear, may clear *)
44 | IOpSimpl of ssrsimpl
45
46 | IOpEqGen of unit Proofview.tactic (* generation of eqn *)
47
48 | IOpNoop
49
50 and ssriops = ssriop list
51
52 let rec pr_ipatop = function
53 | IOpId id -> Names.Id.print id
54 | IOpDrop -> Pp.str "_"
55 | IOpTemporay -> Pp.str "+"
56 | IOpInaccessible None -> Pp.str "?"
57 | IOpInaccessible (Some s) -> Pp.str ("?«"^s^"»")
58 | IOpInaccessibleAll -> Pp.str "*"
59 | IOpAbstractVars l -> Pp.str ("[:"^String.concat " " (List.map Names.Id.to_string l)^"]")
60 | IOpFastNondep -> Pp.str ">"
61
62 | IOpInj l -> Pp.(str "[=" ++ ppl l ++ str "]")
63
64 | IOpDispatchBlock b -> Pp.(str"(" ++ Ssrprinters.pr_block b ++ str")")
65 | IOpDispatchBranches l -> Pp.(str "(" ++ ppl l ++ str ")")
66
67 | IOpCaseBlock b -> Pp.(str"[" ++ Ssrprinters.pr_block b ++ str"]")
68 | IOpCaseBranches l -> Pp.(str "[" ++ ppl l ++ str "]")
69
70 | IOpRewrite (occ,dir) -> Pp.(Ssrprinters.(pr_occ occ ++ pr_dir dir))
71 | IOpView (None,vs) -> Pp.(prlist_with_sep mt (fun c -> str "/" ++ Ssrprinters.pr_ast_closure_term c) vs)
72 | IOpView (Some cl,vs) -> Pp.(Ssrprinters.pr_clear Pp.spc cl ++ prlist_with_sep mt (fun c -> str "/" ++ Ssrprinters.pr_ast_closure_term c) vs)
73
74 | IOpClear (clmust,clmay) ->
75 Pp.(Ssrprinters.pr_clear spc clmust ++
76 match clmay with
77 | Some cl -> str "(try " ++ Ssrprinters.pr_clear spc [cl] ++ str")"
78 | None -> mt ())
79 | IOpSimpl s -> Ssrprinters.pr_simpl s
80
81 | IOpEqGen _ -> Pp.str "E:"
82 | IOpNoop -> Pp.str"-"
83 and ppl x = Pp.(prlist_with_sep (fun () -> str"|") (prlist_with_sep spc pr_ipatop)) x
84
85
86 module IpatMachine : sig
87
88 (* the => tactical. ?eqtac is a tactic to be eventually run
89 * after the first [..] block. first_case_is_dispatch is the
90 * ssr exception to elim: and case: *)
91 val main : ?eqtac:unit tactic -> first_case_is_dispatch:bool ->
92 ssriops -> unit tactic
93
94 val tclCompileIPats : ssripats -> ssriops
95
96 val tclSEED_SUBGOALS : Names.Name.t list array -> unit tactic -> unit tactic
97
98 end = struct (* {{{ *)
99
100 module State : sig
101
102 type delayed_gen = {
103 tmp_id : Id.t; (* Temporary name *)
104 orig_name : Name.t (* Old name *)
105 }
106
107 (* to_clear API *)
108 val isCLR_PUSH : Id.t -> unit tactic
109 val isCLR_PUSHL : Id.t list -> unit tactic
110 val isCLR_CONSUME : unit tactic
111
112 (* to_generalize API *)
113 val isGEN_PUSH : delayed_gen -> unit tactic
114 val isGEN_CONSUME : unit tactic
115
116 (* name_seed API *)
117 val isNSEED_SET : Names.Name.t list -> unit tactic
118 val isNSEED_CONSUME : (Names.Name.t list option -> unit tactic) -> unit tactic
119
120 (* Some data may expire *)
121 val isTICK : ssriop -> unit tactic
122
123 val isPRINT : Proofview.Goal.t -> Pp.t
124
125 end = struct (* {{{ *)
126
127 type istate = {
128
129 (* Delayed clear *)
130 to_clear : Id.t list;
131
132 (* Temporary intros, to be generalized back *)
133 to_generalize : delayed_gen list;
134
135 (* The type of the inductive constructor corresponding to the current proof
136 * branch: name seeds are taken from that in an intro block *)
137 name_seed : Names.Name.t list option;
138
139 }
140 and delayed_gen = {
141 tmp_id : Id.t; (* Temporary name *)
142 orig_name : Name.t (* Old name *)
143 }
144
145 let empty_state = {
146 to_clear = [];
147 to_generalize = [];
148 name_seed = None;
149 }
150
151 include Ssrcommon.MakeState(struct
152 type state = istate
153 let init = empty_state
154 let name = "ssripats"
155 end)
156
157 let print_name_seed env sigma = function
158 | None -> Pp.str "-"
159 | Some nl -> Pp.prlist Names.Name.print nl
160
161 let print_delayed_gen { tmp_id; orig_name } =
162 Pp.(Id.print tmp_id ++ str"->" ++ Name.print orig_name)
163
164 let isPRINT g =
165 let env, sigma = Goal.env g, Goal.sigma g in
166 let state = get g in
167 Pp.(str"{{ to_clear: " ++
168 prlist_with_sep spc Id.print state.to_clear ++ spc () ++
169 str"to_generalize: " ++
170 prlist_with_sep spc print_delayed_gen state.to_generalize ++ spc () ++
171 str"name_seed: " ++ print_name_seed env sigma state.name_seed ++ str" }}")
172
173
174 let isCLR_PUSH id =
175 tclGET (fun ({ to_clear = ids } as s) ->
176 tclSET { s with to_clear = id :: ids })
177
178 let isCLR_PUSHL more_ids =
179 tclGET (fun ({ to_clear = ids } as s) ->
180 tclSET { s with to_clear = more_ids @ ids })
181
182 let isCLR_CONSUME =
183 tclGET (fun ({ to_clear = ids } as s) ->
184 tclSET { s with to_clear = [] } <*>
185 Tactics.clear ids)
186
187
188 let isGEN_PUSH dg =
189 tclGET (fun s ->
190 tclSET { s with to_generalize = dg :: s.to_generalize })
191
192 (* generalize `id` as `new_name` *)
193 let gen_astac id new_name =
194 let gen = ((None,Some(false,[])),Ssrmatching.cpattern_of_id id) in
195 Ssrcommon.gentac gen
196 <*> Ssrcommon.tclRENAME_HD_PROD new_name
197
198 (* performs and resets all delayed generalizations *)
199 let isGEN_CONSUME =
200 tclGET (fun ({ to_generalize = dgs } as s) ->
201 tclSET { s with to_generalize = [] } <*>
202 Tacticals.tclTHENLIST
203 (List.map (fun { tmp_id; orig_name } ->
204 gen_astac tmp_id orig_name) dgs) <*>
205 Tactics.clear (List.map (fun gen -> gen.tmp_id) dgs))
206
207
208 let isNSEED_SET ty =
209 tclGET (fun s ->
210 tclSET { s with name_seed = Some ty })
211
212 let isNSEED_CONSUME k =
213 tclGET (fun ({ name_seed = x } as s) ->
214 tclSET { s with name_seed = None } <*>
215 k x)
216
217 let isTICK = function
218 | IOpSimpl _ | IOpClear _ -> tclUNIT ()
219 | _ -> tclGET (fun s -> tclSET { s with name_seed = None })
220
221 end (* }}} *************************************************************** *)
222
223 open State
224
225 (***[=> *] ****************************************************************)
226 (** [nb_assums] returns the number of dependent premises
227 Warning: unlike [nb_deps_assums], it does not perform reduction *)
228 let rec nb_assums cur env sigma t =
229 match EConstr.kind sigma t with
230 | Prod(name,ty,body) ->
231 nb_assums (cur+1) env sigma body
232 | LetIn(name,ty,t1,t2) ->
233 nb_assums (cur+1) env sigma t2
234 | Cast(t,_,_) ->
235 nb_assums cur env sigma t
236 | _ -> cur
237 let nb_assums = nb_assums 0
238
239 let intro_anon_all = Goal.enter begin fun gl ->
240 let env = Goal.env gl in
241 let sigma = Goal.sigma gl in
242 let g = Goal.concl gl in
243 let n = nb_assums env sigma g in
244 Tacticals.tclDO n (Ssrcommon.tclINTRO_ANON ())
245 end
246
247 (*** [=> >*] **************************************************************)
248 (** [nb_deps_assums] returns the number of dependent premises *)
249 let rec nb_deps_assums cur env sigma t =
250 let t' = Reductionops.whd_allnolet env sigma t in
251 match EConstr.kind sigma t' with
252 | Constr.Prod(name,ty,body) ->
253 if EConstr.Vars.noccurn sigma 1 body &&
254 not (Typeclasses.is_class_type env sigma ty) then cur
255 else nb_deps_assums (cur+1) env sigma body
256 | Constr.LetIn(name,ty,t1,t2) ->
257 nb_deps_assums (cur+1) env sigma t2
258 | Constr.Cast(t,_,_) ->
259 nb_deps_assums cur env sigma t
260 | _ -> cur
261 let nb_deps_assums = nb_deps_assums 0
262
263 let intro_anon_deps = Goal.enter begin fun gl ->
264 let env = Goal.env gl in
265 let sigma = Goal.sigma gl in
266 let g = Goal.concl gl in
267 let n = nb_deps_assums env sigma g in
268 Tacticals.tclDO n (Ssrcommon.tclINTRO_ANON ())
269 end
270
271 (** [intro_drop] behaves like [intro_anon] but registers the id of the
272 introduced assumption for a delayed clear. *)
273 let intro_drop =
274 Ssrcommon.tclINTRO ~id:Ssrcommon.Anon
275 ~conclusion:(fun ~orig_name:_ ~new_name -> isCLR_PUSH new_name)
276
277 (** [intro_temp] behaves like [intro_anon] but registers the id of the
278 introduced assumption for a regeneralization. *)
279 let intro_anon_temp =
280 Ssrcommon.tclINTRO ~id:Ssrcommon.Anon
281 ~conclusion:(fun ~orig_name ~new_name ->
282 isGEN_PUSH { tmp_id = new_name; orig_name })
283
284 (** [intro_end] performs the actions that have been delayed. *)
285 let intro_end =
286 Ssrcommon.tcl0G ~default:() (isCLR_CONSUME <*> isGEN_CONSUME)
287
288 (** [=> _] *****************************************************************)
289 let intro_clear ids =
290 Goal.enter begin fun gl ->
291 let env = Proofview.Goal.env gl in
292 let fold (used_ids, clear_ids, ren) id =
293 let new_id = Ssrcommon.mk_anon_id (Id.to_string id) used_ids in
294 let used_ids = Environ.push_named_context_val (LocalAssum (annotR new_id, mkProp)) used_ids in
295 (used_ids, new_id :: clear_ids, (id, new_id) :: ren)
296 in
297 let _, clear_ids, ren = List.fold_left fold (Environ.named_context_val env, [], []) ids in
298 Tactics.rename_hyp ren <*>
299 isCLR_PUSHL clear_ids
300 end
301
302 let tacCHECK_HYPS_EXIST hyps = Goal.enter begin fun gl ->
303 let ctx = Goal.hyps gl in
304 List.iter (Ssrcommon.check_hyp_exists ctx) hyps;
305 tclUNIT ()
306 end
307
308 let tacFILTER_HYP_EXIST hyps k = Goal.enter begin fun gl ->
309 let ctx = Goal.hyps gl in
310 k (Option.bind hyps (fun h ->
311 if Ssrcommon.test_hyp_exists ctx h &&
312 Ssrcommon.(not_section_id (hyp_id h)) then Some h else None))
313 end
314
315 (** [=> []] *****************************************************************)
316
317 (* calls t1 then t2 on each subgoal passing to t2 the index of the current
318 * subgoal (starting from 0) as well as the number of subgoals *)
319 let tclTHENin t1 t2 =
320 tclUNIT () >>= begin fun () -> let i = ref (-1) in
321 t1 <*> numgoals >>= fun n ->
322 Goal.enter begin fun g -> incr i; t2 !i n end
323 end
324
325 (* Attaches one element of `seeds` to each of the last k goals generated by
326 `tac`, where k is the size of `seeds` *)
327 let tclSEED_SUBGOALS seeds tac =
328 tclTHENin tac (fun i n ->
329 Ssrprinters.debug_ssr (fun () -> Pp.(str"seeding"));
330 (* eg [case: (H _ : nat)] generates 3 goals:
331 - 1 for _
332 - 2 for the nat constructors *)
333 let extra_goals = n - Array.length seeds in
334 if i < extra_goals then tclUNIT ()
335 else isNSEED_SET seeds.(i - extra_goals))
336
337 let tac_case t =
338 Goal.enter begin fun _ ->
339 Ssrcommon.tacTYPEOF t >>= fun ty ->
340 Ssrcommon.tacIS_INJECTION_CASE ~ty t >>= fun is_inj ->
341 if is_inj then
342 Ssrelim.perform_injection t
343 else
344 Goal.enter begin fun g ->
345 (Ssrelim.casetac t (fun ?seed k ->
346 match seed with
347 | None -> k
348 | Some seed -> tclSEED_SUBGOALS seed k))
349 end
350 end
351
352 (** [=> [^ seed ]] *********************************************************)
353 let tac_intro_seed interp_ipats fix = Goal.enter begin fun gl ->
354 isNSEED_CONSUME begin fun seeds ->
355 let seeds =
356 Ssrcommon.option_assert_get seeds Pp.(str"tac_intro_seed: no seed") in
357 let ipats = List.map (function
358 | Anonymous ->
359 let s = match fix with
360 | Prefix id -> Id.to_string id ^ "?"
361 | SuffixNum n -> "?" ^ string_of_int n
362 | SuffixId id -> "?" ^ Id.to_string id in
363 IOpInaccessible (Some s)
364 | Name id ->
365 let s = match fix with
366 | Prefix fix -> Id.to_string fix ^ Id.to_string id
367 | SuffixNum n -> Id.to_string id ^ string_of_int n
368 | SuffixId fix -> Id.to_string id ^ Id.to_string fix in
369 IOpId (Id.of_string s)) seeds in
370 interp_ipats ipats
371 end end
372
373 (*** [=> [: id]] ************************************************************)
374 let mk_abstract_id =
375 let open Rocqlib in
376 let ssr_abstract_id = Summary.ref ~name:"SSR:abstractid" 0 in
377 begin fun env sigma ->
378 let sigma, zero = EConstr.fresh_global env sigma (lib_ref "num.nat.O") in
379 let sigma, succ = EConstr.fresh_global env sigma (lib_ref "num.nat.S") in
380 let rec nat_of_n n =
381 if n = 0 then zero
382 else EConstr.mkApp (succ, [|nat_of_n (n-1)|]) in
383 incr ssr_abstract_id;
384 sigma, nat_of_n !ssr_abstract_id
385 end
386
387 let tclMK_ABSTRACT_VAR id = Goal.enter begin fun gl ->
388 let env, concl = Goal.(env gl, concl gl) in
389 let step ablock abstract = begin fun sigma ->
390 let (sigma, (abstract_proof, abstract_ty)) =
391 let (sigma, (ty, _)) =
392 Evarutil.new_type_evar env sigma Evd.univ_flexible_alg in
393 let (sigma, lock) = Evarutil.new_evar env sigma ablock in
394 let (sigma, abstract_id) = mk_abstract_id env sigma in
395 let abstract_ty = EConstr.mkApp(abstract, [|ty; abstract_id; lock|]) in
396 let sigma, m = Evarutil.new_evar env sigma abstract_ty in
397 sigma, (m, abstract_ty) in
398 let sigma, kont =
399 let rd = Context.Rel.Declaration.LocalAssum (make_annot (Name id) EConstr.ERelevance.relevant, abstract_ty) in
400 let sigma, ev = Evarutil.new_evar (EConstr.push_rel rd env) sigma concl in
401 sigma, ev
402 in
403 let term =
404 EConstr.(mkApp (mkLambda(make_annot (Name id) ERelevance.relevant,abstract_ty,kont),[|abstract_proof|])) in
405 let sigma, _ = Typing.type_of env sigma term in
406 sigma, term
407 end in
408 Ssrcommon.tacMK_SSR_CONST "abstract_lock" >>= fun ablock ->
409 Ssrcommon.tacMK_SSR_CONST "abstract" >>= fun abstract ->
410 Tactics.refine ~typecheck:false (step ablock abstract) <*>
411 tclFOCUS 1 3 Proofview.shelve
412 end
413
414 let tclMK_ABSTRACT_VARS ids =
415 List.fold_right (fun id tac ->
416 Tacticals.tclTHENFIRST (tclMK_ABSTRACT_VAR id) tac) ids (tclUNIT ())
417
418 (* Debugging *)
419 let tclLOG p t =
420 tclUNIT () >>= begin fun () ->
421 Ssrprinters.debug_ssr (fun () -> Pp.(str "exec: " ++ pr_ipatop p));
422 tclUNIT ()
423 end <*>
424 Goal.enter begin fun g ->
425 Ssrprinters.debug_ssr (fun () -> Pp.(str" on state:" ++ spc () ++
426 isPRINT g ++
427 str" goal:" ++ spc () ++ Printer.Debug.pr_goal g));
428 tclUNIT ()
429 end
430 <*>
431 t p
432 >>= fun ret ->
433 Goal.enter begin fun g ->
434 Ssrprinters.debug_ssr (fun () -> Pp.(str "done: " ++ isPRINT g));
435 tclUNIT ()
436 end
437 >>= fun () -> tclUNIT ret
438
439 let notTAC = tclUNIT false
440
441 let duplicate_clear =
442 CWarnings.create ~name:"duplicate-clear" ~category:CWarnings.CoreCategories.ssr
443 (fun id -> Pp.(
444 str "Duplicate clear of" ++ spc () ++ Id.print id ++ str "." ++ spc ()
445 ++ str "Use {}" ++ Id.print id ++ spc ()
446 ++ str "instead of {" ++ Id.print id ++ str "}" ++ Id.print id
447 ))
448
449 (* returns true if it was a tactic (eg /ltac:tactic) *)
450 let rec ipat_tac1 ipat : bool tactic =
451 match ipat with
452 | IOpView (glued_clear,l) ->
453 let clear_if_id, extra_clear =
454 match glued_clear with
455 | None -> false, []
456 | Some x -> true, List.map Ssrcommon.hyp_id x in
457 Ssrview.tclIPAT_VIEWS
458 ~views:l ~clear_if_id
459 ~conclusion:(fun ~to_clear:clr ->
460 let inter = CList.intersect Id.equal clr extra_clear in
461 List.iter duplicate_clear inter;
462 let cl = CList.union Id.equal clr extra_clear in
463 intro_clear cl) ()
464
465 | IOpDispatchBranches ipatss ->
466 tclDISPATCH (List.map ipat_tac ipatss) <*> notTAC
467 | IOpDispatchBlock id_block ->
468 tac_intro_seed ipat_tac id_block <*> notTAC
469 | IOpCaseBlock id_block ->
470 Ssrcommon.tclWITHTOP tac_case <*> tac_intro_seed ipat_tac id_block <*> notTAC
471
472 | IOpCaseBranches ipatss ->
473 tclIORPAT (Ssrcommon.tclWITHTOP tac_case) ipatss <*> notTAC
474
475 | IOpId id -> Ssrcommon.tclINTRO_ID id <*> notTAC
476 | IOpFastNondep -> intro_anon_deps <*> notTAC
477 | IOpDrop -> intro_drop <*> notTAC
478 | IOpInaccessible seed -> Ssrcommon.tclINTRO_ANON ?seed () <*> notTAC
479 | IOpInaccessibleAll -> intro_anon_all <*> notTAC
480 | IOpTemporay -> intro_anon_temp <*> notTAC
481
482 | IOpSimpl Nop -> assert false
483
484 | IOpInj ipatss ->
485 tclIORPAT (Ssrcommon.tclWITHTOP
486 (fun t -> Ssrelim.perform_injection t))
487 ipatss
488 <*> notTAC
489
490 | IOpClear (must,may) ->
491 tacCHECK_HYPS_EXIST must <*>
492 tacFILTER_HYP_EXIST may (fun may ->
493 let must = List.map Ssrcommon.hyp_id must in
494 let cl = Option.fold_left (fun cls (SsrHyp(_,id)) ->
495 if CList.mem_f Id.equal id cls then begin
496 duplicate_clear id;
497 cls
498 end else id :: cls) must may in
499 intro_clear cl) <*>
500 notTAC
501
502 | IOpSimpl x ->
503 Ssrequality.simpltac x <*> notTAC
504
505 | IOpRewrite (occ,dir) ->
506 Ssrcommon.tclWITHTOP
507 (fun x -> Ssrequality.ipat_rewrite occ dir x) <*> notTAC
508
509 | IOpAbstractVars ids -> tclMK_ABSTRACT_VARS ids <*> notTAC
510
511 | IOpEqGen t -> t <*> notTAC
512 | IOpNoop -> notTAC
513
514 and ipat_tac pl : unit tactic =
515 match pl with
516 | [] -> tclUNIT ()
517 | pat :: pl ->
518 Ssrcommon.tcl0G ~default:false (tclLOG pat ipat_tac1) >>= fun was_tac ->
519 isTICK pat (* drops expired seeds *) >>= fun () ->
520 if was_tac then (* exception *)
521 let ip_before, case, ip_after = split_at_first_case pl in
522 let case = ssr_exception true case in
523 let case = option_to_list case in
524 ipat_tac (ip_before @ case @ ip_after)
525 else ipat_tac pl
526
527 and tclIORPAT tac = function
528 | [[]] -> tac
529 | p -> Tacticals.tclTHENS tac (List.map ipat_tac p)
530
531 and ssr_exception is_on = function
532 | Some (IOpCaseBranches [[]]) when is_on -> Some IOpNoop
533 | Some (IOpCaseBranches l) when is_on ->
534 Some (IOpDispatchBranches l)
535 | Some (IOpCaseBlock s) when is_on ->
536 Some (IOpDispatchBlock s)
537 | x -> x
538
539 and option_to_list = function None -> [] | Some x -> [x]
540
541 and split_at_first_case ipats =
542 let rec loop acc = function
543 | (IOpSimpl _ | IOpClear _) as x :: rest -> loop (x :: acc) rest
544 | (IOpCaseBlock _ | IOpCaseBranches _
545 | IOpDispatchBlock _ | IOpDispatchBranches _) as x :: xs ->
546 CList.rev acc, Some x, xs
547 | pats -> CList.rev acc, None, pats
548 in
549 loop [] ipats
550 ;;
551
552 (* Simple pass doing {x}/v -> /v{x} *)
553 let tclCompileIPats l =
554 let rec elab = function
555
556 | (IPatClear cl) :: (IPatView v) :: rest ->
557 (IOpView(Some cl,v)) :: elab rest
558 | (IPatClear cl) :: (IPatId id) :: rest ->
559 (IOpClear (cl,Some (SsrHyp(None,id)))) :: IOpId id :: elab rest
560
561 (* boring code *)
562 | [] -> []
563
564 | IPatId id :: rest -> IOpId id :: elab rest
565 | IPatAnon (One hint) ::rest -> IOpInaccessible hint :: elab rest
566 | IPatAnon Drop :: rest -> IOpDrop :: elab rest
567 | IPatAnon All :: rest -> IOpInaccessibleAll :: elab rest
568 | IPatAnon Temporary :: rest -> IOpTemporay :: elab rest
569 | IPatAbstractVars vs :: rest -> IOpAbstractVars vs :: elab rest
570 | IPatFastNondep :: rest -> IOpFastNondep :: elab rest
571
572 | IPatInj pats :: rest -> IOpInj (List.map elab pats) :: elab rest
573 | IPatRewrite(occ,dir) :: rest -> IOpRewrite(occ,dir) :: elab rest
574 | IPatView vs :: rest -> IOpView (None,vs) :: elab rest
575 | IPatSimpl s :: rest -> IOpSimpl s :: elab rest
576 | IPatClear cl :: rest -> IOpClear (cl,None) :: elab rest
577
578 | IPatCase (Block seed) :: rest -> IOpCaseBlock seed :: elab rest
579 | IPatCase (Regular bs) :: rest -> IOpCaseBranches (List.map elab bs) :: elab rest
580 | IPatDispatch (Block seed) :: rest -> IOpDispatchBlock seed :: elab rest
581 | IPatDispatch (Regular bs) :: rest -> IOpDispatchBranches (List.map elab bs) :: elab rest
582 | IPatNoop :: rest -> IOpNoop :: elab rest
583
584 in
585 elab l
586 ;;
587 let tclCompileIPats l =
588 Ssrprinters.debug_ssr (fun () -> Pp.(str "tclCompileIPats input: " ++
589 prlist_with_sep spc Ssrprinters.pr_ipat l));
590 let ops = tclCompileIPats l in
591 Ssrprinters.debug_ssr (fun () -> Pp.(str "tclCompileIPats output: " ++
592 prlist_with_sep spc pr_ipatop ops));
593 ops
594
595 let main ?eqtac ~first_case_is_dispatch iops =
596 let ip_before, case, ip_after = split_at_first_case iops in
597 let case = ssr_exception first_case_is_dispatch case in
598 let case = option_to_list case in
599 let eqtac = option_to_list (Option.map (fun x -> IOpEqGen x) eqtac) in
600 let ipats = ip_before @ case @ eqtac @ ip_after in
601 Ssrcommon.tcl0G ~default:() (ipat_tac ipats <*> intro_end)
602
603 end (* }}} *)
604
605 let tclIPAT_EQ eqtac ip =
606 Ssrprinters.debug_ssr (fun () -> Pp.(str "ipat@run: " ++ Ssrprinters.pr_ipats ip));
607 IpatMachine.(main ~eqtac ~first_case_is_dispatch:true (tclCompileIPats ip))
608
609 let tclIPATssr ip =
610 Ssrprinters.debug_ssr (fun () -> Pp.(str "ipat@run: " ++ Ssrprinters.pr_ipats ip));
611 IpatMachine.(main ~first_case_is_dispatch:true (tclCompileIPats ip))
612
613 let tclCompileIPats = IpatMachine.tclCompileIPats
614
615 (* Common code to handle generalization lists along with the defective case *)
616 let with_defective maintac deps clr = Goal.enter begin fun g ->
617 let sigma, concl = Goal.(sigma g, concl g) in
618 let top_id =
619 let open EConstr in
620 match kind_of_type sigma concl with
621 | ProdType ({binder_name=Name id}, _, _)
622 when Ssrcommon.is_discharged_id id -> id
623 | _ -> Ssrcommon.top_id in
624 let top_gen = Ssrequality.mkclr clr, Ssrmatching.cpattern_of_id top_id in
625 Ssrcommon.tclINTRO_ID top_id <*> maintac deps top_gen
626 end
627
628 let with_dgens { dgens; gens; clr } maintac = match gens with
629 | [] -> with_defective maintac dgens clr
630 | gen :: gens ->
631 Ssrcommon.genstac (gens, clr) <*> maintac dgens gen
632
633 let mkCoqEq env sigma =
634 let eq = Rocqlib.((build_rocq_eq_data ()).eq) in
635 let sigma, eq = EConstr.fresh_global env sigma eq in
636 eq, sigma
637
638 let mkCoqRefl t c env sigma =
639 let refl = Rocqlib.((build_rocq_eq_data()).refl) in
640 let sigma, refl = EConstr.fresh_global env sigma refl in
641 EConstr.mkApp (refl, [|t; c|]), sigma
642
643 (** Intro patterns processing for elim tactic, in particular when used in
644 conjunction with equation generation as in [elim E: x] *)
645 let elim_intro_tac ipats ?seed what eqid ssrelim is_rec clr =
646 let intro_eq =
647 match eqid with
648 | Some (IPatId ipat) when not is_rec ->
649 let rec intro_eq () = Goal.enter begin fun g ->
650 let sigma, env, concl = Goal.(sigma g, env g, concl g) in
651 let open EConstr in
652 match kind_of_type sigma concl with
653 | ProdType (_, src, tgt) -> begin
654 match kind_of_type sigma src with
655 | AtomicType (hd, _) when Ssrcommon.is_protect hd env sigma ->
656 Ssrcommon.unprotecttac <*>
657 Ssrcommon.tclINTRO_ID ipat
658 | _ -> Ssrcommon.tclINTRO_ANON () <*> intro_eq ()
659 end
660 |_ -> Ssrcommon.errorstrm (Pp.str "Too many names in intro pattern")
661 end in
662 intro_eq ()
663 | Some (IPatId ipat) ->
664 let intro_lhs = Goal.enter begin fun g ->
665 let env = Proofview.Goal.env g in
666 let sigma = Goal.sigma g in
667 let elim_name = match clr, what with
668 | [SsrHyp(_, x)], _ -> x
669 | _, Ssrelim.EConstr(_,_,t) when EConstr.isVar sigma t ->
670 EConstr.destVar sigma t
671 | _ -> Ssrcommon.mk_anon_id "K" (Environ.named_context_val env) in
672 Tacticals.tclFIRST
673 [ Ssrcommon.tclINTRO_ID elim_name
674 ; Ssrcommon.tclINTRO_ANON ~seed:"K" ()]
675 end in
676 let rec gen_eq_tac () = Goal.enter begin fun g ->
677 let sigma, env, concl = Goal.(sigma g, env g, concl g) in
678 let sigma, eq =
679 EConstr.fresh_global env sigma (Rocqlib.lib_ref "core.eq.type") in
680 let ctx, last = EConstr.decompose_prod_decls sigma concl in
681 let open EConstr in
682 let args = match kind_of_type sigma last with
683 | AtomicType (hd, args) ->
684 if Ssrcommon.is_protect hd env sigma then args
685 else Ssrcommon.errorstrm
686 (Pp.str "Too many names in intro pattern")
687 | _ -> assert false in
688 let case = args.(Array.length args-1) in
689 if not(EConstr.Vars.closed0 sigma case)
690 then Ssrcommon.tclINTRO_ANON () <*> gen_eq_tac ()
691 else
692 Ssrcommon.tacTYPEOF case >>= fun case_ty ->
693 let open EConstr in
694 let refl =
695 mkApp (eq, [|Vars.lift 1 case_ty; mkRel 1; Vars.lift 1 case|]) in
696 let name = Ssrcommon.mk_anon_id "K" (Environ.named_context_val env) in
697
698 let new_concl =
699 mkProd (make_annot (Name name) ERelevance.relevant, case_ty, mkArrow refl ERelevance.relevant (Vars.lift 2 concl)) in
700 let erefl, sigma = mkCoqRefl case_ty case env sigma in
701 Proofview.Unsafe.tclEVARS sigma <*>
702 Tactics.apply_type ~typecheck:true new_concl [case;erefl]
703 end in
704 gen_eq_tac () <*>
705 intro_lhs <*>
706 Ssrcommon.tclINTRO_ID ipat
707 | _ -> tclUNIT () in
708 let unprotect =
709 if eqid <> None && is_rec
710 then Ssrcommon.unprotecttac else tclUNIT () in
711 begin match seed with
712 | None -> ssrelim
713 | Some s -> IpatMachine.tclSEED_SUBGOALS s ssrelim end <*>
714 tclIPAT_EQ (intro_eq <*> unprotect) ipats
715 ;;
716
717 let mkEq dir cl c t n env sigma =
718 let open EConstr in
719 let eqargs = [|t; c; c|] in
720 eqargs.(Ssrequality.dir_org dir) <- mkRel n;
721 let eq, sigma = mkCoqEq env sigma in
722 let refl, sigma = mkCoqRefl t c env sigma in
723 mkArrow (mkApp (eq, eqargs)) ERelevance.relevant (Vars.lift 1 cl), refl, sigma
724
725 (** in [tac/v: last gens..] the first (last to be run) generalization is
726 "special" in that is it also the main argument of [tac] and is eventually
727 to be processed forward with view [v]. The behavior implemented is
728 very close to [tac: (v last) gens..] but:
729 - [v last] may use a view adaptor
730 - eventually clear for [last] is taken into account
731 - [tac/v {clr}] is also supported, and [{clr}] is to be run later
732 The code here does not "grab" [v last] nor apply [v] to [last], see the
733 [tacVIEW_THEN_GRAB] combinator. *)
734 let tclLAST_GEN ~to_ind ((oclr, occ), t) conclusion = tclINDEPENDENTL begin
735 Goal.enter_one begin fun gl ->
736 let cl0, env, sigma, hyps = Goal.(concl gl, env gl, sigma gl, hyps gl) in
737 let sigma0 = sigma in
738 let pat = Ssrmatching.interp_cpattern env sigma t None in
739 let cl = Reductionops.nf_evar sigma cl0 in
740 let sigma, c, cl = Ssrmatching.fill_rel_occ_pattern env sigma cl pat occ in
741 let clr =
742 Ssrcommon.interp_clr sigma (oclr, (Ssrmatching.tag_of_cpattern t,c)) in
743 (* Historically in Rocq, and hence in ssr, [case t] accepts [t] of type
744 [A.. -> Ind] and opens new goals for [A..] as well as for the branches
745 of [Ind], see the [~to_ind] argument *)
746 if not(Termops.occur_existential sigma c) then
747 if Ssrmatching.tag_of_cpattern t = Ssrmatching.WithAt then
748 if not (EConstr.isVar sigma c) then
749 Ssrcommon.errorstrm Pp.(str "@ can be used with variables only")
750 else match Context.Named.lookup (EConstr.destVar sigma c) hyps with
751 | Context.Named.Declaration.LocalAssum _ ->
752 Ssrcommon.errorstrm Pp.(str "@ can be used with let-ins only")
753 | Context.Named.Declaration.LocalDef (name, b, ty) ->
754 Unsafe.tclEVARS sigma <*>
755 tclUNIT (true, EConstr.mkLetIn (map_annot Name.mk_name name,b,ty,cl), c, clr)
756 else
757 Unsafe.tclEVARS sigma <*>
758 Ssrcommon.tacMKPROD c cl >>= fun ccl ->
759 tclUNIT (false, ccl, c, clr)
760 else
761 if to_ind && occ = None then
762 let p, _, ucst' = Ssrcommon.abs_evars env sigma0 (pat.pat_sigma, c) in
763 let sigma = Evd.merge_universe_context sigma ucst' in
764 Unsafe.tclEVARS sigma <*>
765 Ssrcommon.tacTYPEOF p >>= fun pty ->
766 (* TODO: check bug: cl0 no lift? *)
767 let ccl = EConstr.mkProd (make_annot (Ssrcommon.constr_name sigma c) EConstr.ERelevance.relevant, pty, cl0) in
768 tclUNIT (false, ccl, p, clr)
769 else
770 Ssrcommon.errorstrm Pp.(str "generalized term didn't match")
771 end end >>= begin
772 fun infos -> tclDISPATCH (infos |> List.map conclusion)
773 end
774
775 (** a typical mate of [tclLAST_GEN] doing the job of applying the views [cs]
776 to [c] and generalizing the resulting term *)
777 let tacVIEW_THEN_GRAB ?(simple_types=true)
778 vs ~conclusion (is_letin, new_concl, c, clear)
779 =
780 Ssrview.tclWITH_FWD_VIEWS ~simple_types ~subject:c ~views:vs
781 ~conclusion:(fun t ->
782 Ssrcommon.tacCONSTR_NAME c >>= fun name ->
783 Goal.enter_one ~__LOC__ begin fun g ->
784 let sigma, env = Goal.sigma g, Goal.env g in
785 Ssrcommon.tacMKPROD t ~name
786 (Termops.subst_term sigma t (* NOTE: we grab t here *)
787 (Termops.prod_applist sigma new_concl [c])) >>=
788 conclusion is_letin t clear
789 end)
790
791 (* Elim views are elimination lemmas, so the eliminated term is not added *)
792 (* to the dependent terms as for "case", unless it actually occurs in the *)
793 (* goal, the "all occurrences" {+} switch is used, or the equation switch *)
794 (* is used and there are no dependents. *)
795
796 let ssrelimtac (view, (eqid, (dgens, ipats))) =
797 let ndefectelimtac view eqid ipats deps gen =
798 match view with
799 | [v] ->
800 Ssrcommon.tclINTERP_AST_CLOSURE_TERM_AS_CONSTR v >>= fun cs ->
801 tclDISPATCH (List.map (fun elim ->
802 (Ssrelim.ssrelim deps (Ssrelim.EGen gen) ~elim eqid (elim_intro_tac ipats)))
803 cs)
804 | [] ->
805 tclINDEPENDENT
806 (Ssrelim.ssrelim deps (Ssrelim.EGen gen) eqid (elim_intro_tac ipats))
807 | _ ->
808 Ssrcommon.errorstrm
809 Pp.(str "elim: only one elimination lemma can be provided")
810 in
811 with_dgens dgens (ndefectelimtac view eqid ipats)
812
813 let ssrcasetac (view, (eqid, (dgens, ipats))) =
814 let ndefectcasetac view eqid ipats deps ((_, occ), _ as gen) =
815 tclLAST_GEN ~to_ind:true gen (fun (_, cl, c, clear as info) ->
816 let conclusion _ vc _clear _cl =
817 Ssrcommon.tacIS_INJECTION_CASE vc >>= fun inj ->
818 let simple = (eqid = None && deps = [] && occ = None) in
819 if simple && inj then
820 Ssrelim.perform_injection vc <*>
821 Tactics.clear (List.map Ssrcommon.hyp_id clear) <*>
822 tclIPATssr ipats
823 else
824 (* macro for "case/v E: x" ---> "case E: x / (v x)" *)
825 let deps, clear, occ =
826 if view <> [] && eqid <> None && deps = []
827 then [gen], [], None
828 else deps, clear, occ in
829 Ssrelim.ssrelim ~is_case:true deps (Ssrelim.EConstr (clear, occ, vc))
830 eqid (elim_intro_tac ipats)
831 in
832 if view = [] then conclusion false c clear c
833 else tacVIEW_THEN_GRAB ~simple_types:false view ~conclusion info)
834 in
835 with_dgens dgens (ndefectcasetac view eqid ipats)
836
837 let ssrscasetoptac = Ssrcommon.tclWITHTOP Ssrelim.ssrscase_or_inj_tac
838 let ssrselimtoptac = Ssrcommon.tclWITHTOP Ssrelim.elimtac
839
840 (** [move] **************************************************************)
841 let pushmoveeqtac cl c = Goal.enter begin fun g ->
842 let env, sigma = Goal.(env g, sigma g) in
843 let x, t, cl1 = EConstr.destProd sigma cl in
844 let cl2, eqc, sigma = mkEq R2L cl1 c t 1 env sigma in
845 Unsafe.tclEVARS sigma <*>
846 Tactics.apply_type ~typecheck:true (EConstr.mkProd (x, t, cl2)) [c; eqc]
847 end
848
849 let eqmovetac _ gen =
850 Proofview.Goal.enter begin fun gl ->
851 let env = Proofview.Goal.env gl in
852 let sigma = Proofview.Goal.sigma gl in
853 let concl = Proofview.Goal.concl gl in
854 let (sigma, (cl, c, _)) = Ssrcommon.interp_gen env sigma ~concl false gen in
855 Proofview.Unsafe.tclEVARS sigma <*> pushmoveeqtac cl c
856 end
857
858 let rec eqmoveipats eqpat = function
859 | (IOpSimpl _ | IOpClear _ as ipat) :: ipats ->
860 ipat :: eqmoveipats eqpat ipats
861 | (IOpInaccessibleAll :: _ | []) as ipats ->
862 IOpInaccessible None :: eqpat @ ipats
863 | ipat :: ipats ->
864 ipat :: eqpat @ ipats
865
866 let ssrsmovetac = Goal.enter begin fun g ->
867 let sigma, concl = Goal.(sigma g, concl g) in
868 match EConstr.kind sigma concl with
869 | Prod _ | LetIn _ -> tclUNIT ()
870 | _ -> Tactics.hnf_in_concl
871 end
872
873 let tclIPAT ip =
874 IpatMachine.main ~first_case_is_dispatch:false ip
875
876 let ssrmovetac = function
877 | _::_ as view, (_, ({ gens = lastgen :: gens; clr }, ipats)) ->
878 let gentac = Ssrcommon.genstac (gens, []) in
879 let conclusion _ t clear ccl =
880 Tactics.apply_type ~typecheck:true ccl [t] <*>
881 Tactics.clear (List.map Ssrcommon.hyp_id clear) in
882 gentac <*>
883 tclLAST_GEN ~to_ind:false lastgen
884 (tacVIEW_THEN_GRAB view ~conclusion) <*>
885 tclIPAT (IOpClear (clr,None) :: IpatMachine.tclCompileIPats ipats)
886 | _::_ as view, (_, ({ gens = []; clr }, ipats)) ->
887 tclIPAT (IOpView (None,view) :: IOpClear (clr,None) :: IpatMachine.tclCompileIPats ipats)
888 | _, (Some pat, (dgens, ipats)) ->
889 let dgentac = with_dgens dgens eqmovetac in
890 dgentac <*> tclIPAT (eqmoveipats (IpatMachine.tclCompileIPats [pat]) (IpatMachine.tclCompileIPats ipats))
891 | _, (_, ({ gens = (_ :: _ as gens); dgens = []; clr}, ipats)) ->
892 let gentac = Ssrcommon.genstac (gens, clr) in
893 gentac <*> tclIPAT (IpatMachine.tclCompileIPats ipats)
894 | _, (_, ({ clr }, ipats)) ->
895 Tacticals.tclTHENLIST [ssrsmovetac; Tactics.clear (List.map Ssrcommon.hyp_id clr); tclIPAT (IpatMachine.tclCompileIPats ipats)]
896
897 (** [abstract: absvar gens] **************************************************)
898 let rec is_Evar_or_CastedMeta sigma x =
899 EConstr.isEvar sigma x ||
900 EConstr.isMeta sigma x ||
901 (EConstr.isCast sigma x &&
902 is_Evar_or_CastedMeta sigma (pi1 (EConstr.destCast sigma x)))
903
904 let occur_existential_or_casted_meta sigma c =
905 let rec occrec c = match EConstr.kind sigma c with
906 | Evar _ -> raise Not_found
907 | Cast (m,_,_) when EConstr.isMeta sigma m -> raise Not_found
908 | _ -> EConstr.iter sigma occrec c
909 in
910 try occrec c; false
911 with Not_found -> true
912
913 let examine_abstract env sigma id =
914 let (sigma, tid) = Typing.type_of env sigma id in
915 let abstract = Ssrcommon.mkSsrRef "abstract" in
916 let err () =
917 Ssrcommon.errorstrm
918 Pp.(strbrk"not a proper abstract constant: "++
919 Printer.pr_econstr_env env sigma id) in
920 if not (EConstr.isApp sigma tid) then err ();
921 let hd, args_id = EConstr.destApp sigma tid in
922 if not (EConstr.isRefX env sigma abstract hd) then err ();
923 if Array.length args_id <> 3 then err ();
924 if not (is_Evar_or_CastedMeta sigma args_id.(2)) then
925 Ssrcommon.errorstrm Pp.(strbrk"abstract constant "++
926 Printer.pr_econstr_env env sigma id++str" already used");
927 sigma, (tid, args_id)
928
929 let tacEXAMINE_ABSTRACT id =
930 Goal.enter_one ~__LOC__ begin fun g ->
931 let sigma, env = Goal.(sigma g, env g) in
932 let sigma, ans = examine_abstract env sigma id in
933 Proofview.Unsafe.tclEVARS sigma <*> Proofview.tclUNIT ans
934 end
935
936 let find_abstract_proof env sigma check_lock abstract_n =
937 let abstract = Ssrcommon.mkSsrRef "abstract" in
938 let l = Evd.fold_undefined (fun e ei l ->
939 match EConstr.kind sigma (Evd.evar_concl ei) with
940 | App(hd, [|ty; n; lock|])
941 when (not check_lock ||
942 (occur_existential_or_casted_meta sigma ty &&
943 is_Evar_or_CastedMeta sigma lock)) &&
944 EConstr.isRefX env sigma abstract hd &&
945 EConstr.eq_constr_nounivs sigma n abstract_n -> e :: l
946 | _ -> l) sigma [] in
947 match l with
948 | [e] -> e
949 | _ -> Ssrcommon.errorstrm
950 Pp.(strbrk"abstract constant "++
951 Printer.pr_econstr_env env sigma abstract_n ++
952 strbrk" not found in the evar map exactly once. "++
953 strbrk"Did you tamper with it?")
954
955 let tacFIND_ABSTRACT_PROOF check_lock abstract_n =
956 Goal.enter_one ~__LOC__ begin fun g ->
957 let sigma, env = Goal.(sigma g, env g) in
958 tclUNIT (find_abstract_proof env sigma check_lock abstract_n)
959 end
960
961 let ssrabstract dgens =
962 let main _ (_,cid) =
963 Ssrcommon.tacMK_SSR_CONST "abstract" >>= fun abstract ->
964 Ssrcommon.tacMK_SSR_CONST "abstract_key" >>= fun abstract_key ->
965 Ssrcommon.tacINTERP_CPATTERN cid >>= fun cid -> Goal.enter @@ fun g ->
966 let id =
967 match Ssrmatching.id_of_pattern (Goal.sigma g) cid with
968 | None -> Ssrcommon.errorstrm Pp.(strbrk "argument is not a hypothesis")
969 | Some id -> EConstr.mkVar id in
970 tacEXAMINE_ABSTRACT id >>= fun (idty, args_id) ->
971 let abstract_n = args_id.(1) in
972 tacFIND_ABSTRACT_PROOF true abstract_n >>= fun abstract_proof ->
973 let tacFIND_HOLE = Goal.enter_one ~__LOC__ begin fun g ->
974 let sigma, env, concl = Goal.(sigma g, env g, concl g) in
975 let t = args_id.(0) in
976 match EConstr.kind sigma t with
977 | (Evar _ | Meta _) -> Ssrcommon.tacUNIFY concl t <*> tclUNIT id
978 | Cast(m,_,_)
979 when EConstr.isEvar sigma m || EConstr.isMeta sigma m ->
980 Ssrcommon.tacUNIFY concl t <*> tclUNIT id
981 | _ ->
982 Ssrcommon.errorstrm
983 Pp.(strbrk"abstract constant "++
984 Printer.pr_econstr_env env sigma abstract_n ++
985 strbrk" has an unexpected shape. Did you tamper with it?")
986 end in
987 tacFIND_HOLE >>= fun proof ->
988 Ssrcommon.tacUNIFY abstract_key args_id.(2) <*>
989 Ssrcommon.tacTYPEOF idty >>= fun _ ->
990 Unsafe.tclGETGOALS >>= fun goals ->
991 (* Here we jump in the proof tree: we move from the current goal to
992 the evar that inhabits the abstract variable with the current goal *)
993 Unsafe.tclSETGOALS
994 (goals @ [Proofview_monad.with_empty_state abstract_proof]) <*>
995 tclDISPATCH [
996 Tacticals.tclSOLVE [Tactics.apply proof];
997 Ssrcommon.unfold[abstract;abstract_key]
998 ] in
999 let interp_gens { gens } ~conclusion = Goal.enter begin fun gl ->
1000 let sigma = Proofview.Goal.sigma gl in
1001 let env = Proofview.Goal.env gl in
1002 let open Ssrmatching in
1003 let ipats = List.map (fun (_,cp) ->
1004 match id_of_pattern sigma (interp_cpattern env sigma cp None) with
1005 | None -> IPatAnon (One None)
1006 | Some id -> IPatId id)
1007 (List.tl gens) in
1008 conclusion ipats
1009 end in
1010 interp_gens dgens ~conclusion:(fun ipats ->
1011 with_dgens dgens main <*>
1012 tclIPATssr ipats)
1013
1014 module Internal = struct
1015 let find_abstract_proof = find_abstract_proof
1016 let examine_abstract = examine_abstract
1017 end
1018
1019 (* vim: set filetype=ocaml foldmethod=marker: *)