Debian Codegraph @

tactics/generalize.ml

raw symbols SCIP
1 (************************************************************************)
2 (* * The Rocq Prover / The Rocq Development Team *)
3 (* v * Copyright INRIA, CNRS and contributors *)
4 (* <O___,, * (see version control and CREDITS file for authors & dates) *)
5 (* \VV/ **************************************************************)
6 (* // * This file is distributed under the terms of the *)
7 (* * GNU Lesser General Public License Version 2.1 *)
8 (* * (see LICENSE file for the text of the license) *)
9 (************************************************************************)
10
11 (* module CVars = Vars *)
12
13 open Pp
14 open Util
15 open Names
16 open Constr
17 open Context
18 open Termops
19 open Environ
20 open EConstr
21 open Vars
22 open Find_subterm
23 open Namegen
24 open Locus
25 open Proofview.Notations
26 open Context.Named.Declaration
27
28 module NamedDecl = Context.Named.Declaration
29
30 (*********************************************)
31 (* Errors *)
32 (*********************************************)
33
34 exception AlreadyUsed of Id.t
35
36 let error ?loc e =
37 Loc.raise ?loc e
38
39 exception Unhandled
40
41 let wrap_unhandled f e =
42 try Some (f e)
43 with Unhandled -> None
44
45 let tactic_interp_error_handler = function
46 | AlreadyUsed id ->
47 Id.print id ++ str " is already used."
48 | _ -> raise Unhandled
49
50 let _ = CErrors.register_handler (wrap_unhandled tactic_interp_error_handler)
51
52 let fresh_id_in_env avoid id env =
53 let avoid' = ids_of_named_context_val (named_context_val env) in
54 let avoid = if Id.Set.is_empty avoid then avoid' else Id.Set.union avoid' avoid in
55 next_ident_away_in_goal (Global.env ()) id avoid
56
57 (*********************************)
58 (* Basic generalization tactics *)
59 (*********************************)
60
61 (* Given a type [T] convertible to [forall x1..xn:A1..An(x1..xn-1), G(x1..xn)]
62 and [a1..an:A1..An(a1..an-1)] such that the goal is [G(a1..an)],
63 this generalizes [hyps |- goal] into [hyps |- T] *)
64
65 (* Given a context [hyps] with domain [x1..xn], possibly with let-ins,
66 and well-typed in the current goal, [bring_hyps hyps] generalizes
67 [ctxt |- G(x1..xn] into [ctxt |- forall hyps, G(x1..xn)] *)
68
69 let bring_hyps hyps =
70 if List.is_empty hyps then Tacticals.tclIDTAC
71 else
72 let hyps = List.rev hyps in
73 Proofview.Goal.enter begin fun gl ->
74 let env = Proofview.Goal.env gl in
75 let sigma = Proofview.Goal.sigma gl in
76 let concl = Proofview.Goal.concl gl in
77 let newcl = it_mkNamedProd_or_LetIn sigma concl hyps in
78 let args = Context.Named.instance mkVar hyps in
79 Refine.refine_with_principal ~typecheck:false begin fun sigma ->
80 let (sigma, ev) =
81 Evarutil.new_evar env sigma newcl in
82 (sigma, mkApp (ev, args), Some (fst @@ destEvar sigma ev))
83 end
84 end
85
86 let revert hyps =
87 Proofview.Goal.enter begin fun gl ->
88 let ctx = List.map (fun id -> Tacmach.pf_get_hyp id gl) hyps in
89 (bring_hyps ctx) <*> (Tactics.clear hyps)
90 end
91
92 (***************************)
93 (* Generalization tactics *)
94 (***************************)
95
96 (* Compute a name for a generalization *)
97
98 let generalized_name env sigma c t ids cl = function
99 | Name id as na ->
100 if Id.Set.mem id ids then
101 error (AlreadyUsed id);
102 na
103 | Anonymous ->
104 match EConstr.kind sigma c with
105 | Var id ->
106 (* Keep the name even if not occurring: may be used by intros later *)
107 Name id
108 | _ ->
109 if noccurn sigma 1 cl then Anonymous else
110 (* On ne s'etait pas casse la tete : on avait pris pour nom de
111 variable la premiere lettre du type, meme si "c" avait ete une
112 constante dont on aurait pu prendre directement le nom *)
113 named_hd env sigma t Anonymous
114
115 (* Abstract over [c] in [forall x1:A1(c)..xi:Ai(c).T(c)] producing
116 [forall x, x1:A1(x1), .., xi:Ai(x). T(x)] with all [c] abtracted in [Ai]
117 but only those at [occs] in [T] *)
118
119 let generalize_goal_gen env sigma ids i ((occs,c,b),na) t cl =
120 let open Context.Rel.Declaration in
121 let decls,cl = decompose_prod_n_decls sigma i cl in
122 let dummy_prod = it_mkProd_or_LetIn mkProp decls in
123 let newdecls,_ =
124 let arity = Array.length (snd (EConstr.decompose_app sigma c)) in
125 let cache = ref Int.Map.empty in
126 let eq sigma k t =
127 let c =
128 try Int.Map.find k !cache
129 with Not_found ->
130 let c = EConstr.Vars.lift k c in
131 let () = cache := Int.Map.add k c !cache in
132 c
133 in
134 (* We use a nounivs equality because generalize morally takes a pattern as
135 argument, so we have to ignore freshly generated sorts. *)
136 EConstr.eq_constr_nounivs sigma c t
137 in
138 decompose_prod_n_decls sigma i (replace_term_gen sigma eq arity (mkRel 1) dummy_prod)
139 in
140 let cl',sigma' = subst_closed_term_occ env sigma (AtOccs occs) c (it_mkProd_or_LetIn cl newdecls) in
141 let na = generalized_name env sigma c t ids cl' na in
142 let r = Retyping.relevance_of_type env sigma t in
143 let decl = match b with
144 | None -> LocalAssum (make_annot na r,t)
145 | Some b -> LocalDef (make_annot na r,b,t)
146 in
147 sigma', mkProd_or_LetIn decl cl'
148
149 let generalize_goal env sigma i ((occs,c,b),na as o) cl =
150 let ids = Environ.ids_of_named_context_val @@ Environ.named_context_val env in
151 let sigma, t = Typing.type_of env sigma c in
152 generalize_goal_gen env sigma ids i o t cl
153
154 let generalize_dep ?(with_let=false) c =
155 let open Tacticals in
156 Proofview.Goal.enter begin fun gl ->
157 let env = Proofview.Goal.env gl in
158 let sigma = Proofview.Goal.sigma gl in
159 let concl = Proofview.Goal.concl gl in
160 let sign = named_context_val env in
161 let init_ids = ids_of_named_context (Global.named_context()) in
162 let seek (d:named_declaration) (toquant:named_context) =
163 if List.exists (fun d' -> occur_var_in_decl env sigma (NamedDecl.get_id d') d) toquant
164 || dependent_in_decl sigma c d then
165 d::toquant
166 else
167 toquant in
168 let to_quantify = Context.Named.fold_outside seek (named_context_of_val sign) ~init:[] in
169 let qhyps = List.map NamedDecl.get_id to_quantify in
170 let tothin = List.filter (fun id -> not (Id.List.mem id init_ids)) qhyps in
171 let tothin' =
172 match EConstr.kind sigma c with
173 | Var id when mem_named_context_val id sign && not (Id.List.mem id init_ids)
174 -> tothin@[id]
175 | _ -> tothin
176 in
177 let cl' = it_mkNamedProd_or_LetIn sigma concl to_quantify in
178 let is_var, body = match EConstr.kind sigma c with
179 | Var id ->
180 let body = NamedDecl.get_value (Tacmach.pf_get_hyp id gl) in
181 let is_var = Option.is_empty body && not (List.mem id init_ids) in
182 if with_let then is_var, body else is_var, None
183 | _ -> false, None
184 in
185 let evd, cl'' = generalize_goal env sigma 0 ((AllOccurrences, c, body), Anonymous) cl' in
186 (* Check that the generalization is indeed well-typed *)
187 let evd =
188 (* No need to retype for variables, term is statically well-typed *)
189 if is_var then evd
190 else fst (Typing.type_of env evd cl'')
191 in
192 let args = Array.to_list (Context.Named.instance mkVar to_quantify) in
193 tclTHENLIST
194 [ Proofview.Unsafe.tclEVARS evd;
195 Tactics.apply_type ~typecheck:false cl'' (if Option.is_empty body then c::args else args);
196 Tactics.clear tothin']
197 end
198
199 (** *)
200 let generalize_gen_let lconstr = Proofview.Goal.enter begin fun gl ->
201 let env = Proofview.Goal.env gl in
202 let sigma = Proofview.Goal.sigma gl in
203 let concl = Proofview.Goal.concl gl in
204 let fold i arg (sigma, c) = generalize_goal env sigma i arg c in
205 let evd, newcl = List.fold_right_i fold 0 lconstr (sigma, concl) in
206 let (evd, _) = Typing.type_of env evd newcl in
207 let map ((_, c, b),_) = if Option.is_empty b then Some c else None in
208 Proofview.tclTHEN (Proofview.Unsafe.tclEVARS evd)
209 (Tactics.apply_type ~typecheck:false newcl (List.map_filter map lconstr))
210 end
211
212 let new_generalize_gen_let lconstr =
213 Proofview.Goal.enter begin fun gl ->
214 let sigma = Proofview.Goal.sigma gl in
215 let concl = Proofview.Goal.concl gl in
216 let env = Proofview.Goal.env gl in
217 let ids = Environ.ids_of_named_context_val @@ Environ.named_context_val env in
218 let newcl, sigma, args =
219 List.fold_right_i
220 (fun i ((_,c,b),_ as o) (cl, sigma, args) ->
221 let sigma, t = Typing.type_of env sigma c in
222 let args = if Option.is_empty b then c :: args else args in
223 let sigma, cl = generalize_goal_gen env sigma ids i o t cl in
224 (cl, sigma, args))
225 0 lconstr (concl, sigma, [])
226 in
227 Proofview.tclTHEN (Proofview.Unsafe.tclEVARS sigma)
228 (Refine.refine_with_principal ~typecheck:false begin fun sigma ->
229 let (sigma, ev) = Evarutil.new_evar env sigma newcl in
230 (sigma, applist (ev, args), Some (fst @@ destEvar sigma ev))
231 end)
232 end
233
234 let generalize_gen lconstr =
235 generalize_gen_let (List.map (fun ((occs,c),na) ->
236 (occs,c,None),na) lconstr)
237
238 let new_generalize_gen lconstr =
239 new_generalize_gen_let (List.map (fun ((occs,c),na) ->
240 (occs,c,None),na) lconstr)
241
242 let generalize l =
243 new_generalize_gen_let (List.map (fun c -> ((AllOccurrences,c,None),Anonymous)) l)
244
245 (* Faudra-t-il une version avec plusieurs args de generalize_dep ?
246 Cela peut-être troublant de faire "Generalize Dependent H n" dans
247 "n:nat; H:n=n |- P(n)" et d'échouer parce que H a disparu après la
248 généralisation dépendante par n.
249
250 let quantify lconstr =
251 List.fold_right
252 (fun com tac -> tclTHEN tac (tactic_com generalize_dep c))
253 lconstr
254 tclIDTAC
255 *)
256
257 let rocq_eq env sigma = Evd.fresh_global env sigma Rocqlib.(lib_ref "core.eq.type")
258 let rocq_eq_refl env sigma = Evd.fresh_global env sigma Rocqlib.(lib_ref "core.eq.refl")
259
260 let rocq_heq_ref = lazy (Rocqlib.lib_ref "core.JMeq.type")
261 let rocq_heq env sigma = Evd.fresh_global env sigma (Lazy.force rocq_heq_ref)
262 let rocq_heq_refl env sigma = Evd.fresh_global env sigma (Rocqlib.lib_ref "core.JMeq.refl")
263 (* let rocq_heq_refl = lazy (glob (lib_ref "core.JMeq.refl")) *)
264
265 let mkEq env sigma t x y =
266 let sigma, eq = rocq_eq env sigma in
267 sigma, mkApp (eq, [| t; x; y |])
268
269 let mkRefl env sigma t x =
270 let sigma, refl = rocq_eq_refl env sigma in
271 sigma, mkApp (refl, [| t; x |])
272
273 let mkHEq env sigma t x u y =
274 let sigma, c = rocq_heq env sigma in
275 sigma, mkApp (c,[| t; x; u; y |])
276
277 let mkHRefl env sigma t x =
278 let sigma, c = rocq_heq_refl env sigma in
279 sigma, mkApp (c, [| t; x |])
280
281 let lift_togethern n l =
282 let l', _ =
283 List.fold_right
284 (fun x (acc, n) ->
285 (lift n x :: acc, succ n))
286 l ([], n)
287 in l'
288
289 let lift_list l = List.map (lift 1) l
290
291 let ids_of_constr env sigma ?(all=false) vars c =
292 let rec aux vars c =
293 match EConstr.kind sigma c with
294 | Var id -> Id.Set.add id vars
295 | App (f, args) ->
296 (match EConstr.kind sigma f with
297 | Construct ((ind,_),_)
298 | Ind (ind,_) ->
299 let (mib,mip) = Inductive.lookup_mind_specif env ind in
300 Array.fold_left_from
301 (if all then 0 else mib.Declarations.mind_nparams)
302 aux vars args
303 | _ -> EConstr.fold sigma aux vars c)
304 | _ -> EConstr.fold sigma aux vars c
305 in aux vars c
306
307 let decompose_indapp env sigma f args =
308 match EConstr.kind sigma f with
309 | Construct ((ind,_),_)
310 | Ind (ind,_) ->
311 let (mib,mip) = Inductive.lookup_mind_specif env ind in
312 let first = mib.Declarations.mind_nparams_rec in
313 let pars, args = Array.chop first args in
314 mkApp (f, pars), args
315 | _ -> f, args
316
317 let mk_term_eq homogeneous env sigma ty t ty' t' =
318 if homogeneous then
319 let sigma, eq = mkEq env sigma ty t t' in
320 let sigma, refl = mkRefl env sigma ty' t' in
321 sigma, (eq, refl)
322 else
323 let sigma, heq = mkHEq env sigma ty t ty' t' in
324 let sigma, hrefl = mkHRefl env sigma ty' t' in
325 sigma, (heq, hrefl)
326
327 let make_abstract_generalize env id typ concl dep ctx body c eqs args refls =
328 let open Context.Rel.Declaration in
329 Refine.refine_with_principal ~typecheck:true begin fun sigma ->
330 let eqslen = List.length eqs in
331 (* Abstract by the "generalized" hypothesis equality proof if necessary. *)
332 let sigma, abshypeq, abshypt =
333 if dep then
334 let ty = lift 1 c in
335 let homogeneous = Reductionops.is_conv env sigma ty typ in
336 let sigma, (eq, refl) =
337 mk_term_eq homogeneous (push_rel_context ctx env) sigma ty (mkRel 1) typ (mkVar id) in
338 sigma, mkProd (make_annot Anonymous ERelevance.relevant, eq, lift 1 concl), [| refl |]
339 else sigma, concl, [||]
340 in
341 (* Abstract by equalities *)
342 let eqs = lift_togethern 1 eqs in (* lift together and past genarg *)
343 let abseqs = it_mkProd_or_LetIn (lift eqslen abshypeq)
344 (List.map (fun x -> LocalAssum (make_annot Anonymous ERelevance.relevant, x)) eqs)
345 in
346 let r = ERelevance.relevant in (* TODO relevance *)
347 let decl = match body with
348 | None -> LocalAssum (make_annot (Name id) r, c)
349 | Some body -> LocalDef (make_annot (Name id) r, body, c)
350 in
351 (* Abstract by the "generalized" hypothesis. *)
352 let genarg = mkProd_or_LetIn decl abseqs in
353 (* Abstract by the extension of the context *)
354 let genctyp = it_mkProd_or_LetIn genarg ctx in
355 (* The goal will become this product. *)
356 let (sigma, genc) = Evarutil.new_evar env sigma genctyp in
357 (* Apply the old arguments giving the proper instantiation of the hyp *)
358 let instc = mkApp (genc, Array.of_list args) in
359 (* Then apply to the original instantiated hyp. *)
360 let instc = Option.cata (fun _ -> instc) (mkApp (instc, [| mkVar id |])) body in
361 (* Apply the reflexivity proofs on the indices. *)
362 let appeqs = mkApp (instc, Array.of_list refls) in
363 (* Finally, apply the reflexivity proof for the original hyp, to get a term of type gl again. *)
364 (sigma, mkApp (appeqs, abshypt), Some (fst @@ destEvar sigma genc))
365 end
366
367 let hyps_of_vars env sigma sign nogen hyps =
368 if Id.Set.is_empty hyps then []
369 else
370 let (_,lh) =
371 Context.Named.fold_inside
372 (fun (hs,hl) d ->
373 let x = NamedDecl.get_id d in
374 if Id.Set.mem x nogen then (hs,hl)
375 else if Id.Set.mem x hs then (hs,x::hl)
376 else
377 let xvars = global_vars_set_of_decl env sigma d in
378 if not (Id.Set.is_empty (Id.Set.diff xvars hs)) then
379 (Id.Set.add x hs, x :: hl)
380 else (hs, hl))
381 ~init:(hyps,[])
382 sign
383 in lh
384
385 exception Seen
386
387 let linear env sigma vars args =
388 let seen = ref vars in
389 try
390 Array.iter (fun i ->
391 let rels = ids_of_constr env sigma ~all:true Id.Set.empty i in
392 let seen' =
393 Id.Set.fold (fun id acc ->
394 if Id.Set.mem id acc then raise Seen
395 else Id.Set.add id acc)
396 rels !seen
397 in seen := seen')
398 args;
399 true
400 with Seen -> false
401
402 let is_defined_variable env id =
403 env |> lookup_named id |> is_local_def
404
405 let abstract_args gl generalize_vars dep id defined f args =
406 let open Context.Rel.Declaration in
407 let sigma = Proofview.Goal.sigma gl in
408 let env = Proofview.Goal.env gl in
409 let concl = Proofview.Goal.concl gl in
410 let hyps = Proofview.Goal.hyps gl in
411 let dep = dep || local_occur_var sigma id concl in
412 let avoid = ref Id.Set.empty in
413 let get_id name =
414 let id = fresh_id_in_env !avoid (match name with Name n -> n | Anonymous -> Id.of_string "gen_x") env in
415 avoid := Id.Set.add id !avoid; id
416 in
417 (* Build application generalized w.r.t. the argument plus the necessary eqs.
418 From env |- c : forall G, T and args : G we build
419 (T[G'], G' : ctx, env ; G' |- args' : G, eqs := G'_i = G_i, refls : G' = G, vars to generalize)
420
421 eqs are not lifted w.r.t. each other yet. (* will be needed when going to dependent indexes *)
422 *)
423 let aux (sigma, prod, ctx, ctxenv, c, args, eqs, refls, nongenvars, vars) arg =
424 let name, ty_relevance, ty, arity =
425 let rel, c = Reductionops.whd_decompose_prod_n env sigma 1 prod in
426 let ({binder_name=na;binder_relevance=r},t) = List.hd rel in
427 na, r, t, c
428 in
429 let argty = Retyping.get_type_of env sigma arg in
430 let sigma, ty = Evarsolve.refresh_universes (Some true) env sigma ty in
431 let lenctx = List.length ctx in
432 let liftargty = lift lenctx argty in
433 let leq = constr_cmp ctxenv sigma Conversion.CUMUL liftargty ty in
434 match EConstr.kind sigma arg with
435 | Var id when not (is_defined_variable env id) && leq && not (Id.Set.mem id nongenvars) ->
436 (sigma, subst1 arg arity, ctx, ctxenv, mkApp (c, [|arg|]), args, eqs, refls,
437 Id.Set.add id nongenvars, Id.Set.remove id vars)
438 | _ ->
439 let name = get_id name in
440 let decl = LocalAssum (make_annot (Name name) ty_relevance, ty) in
441 let ctx = decl :: ctx in
442 let c' = mkApp (lift 1 c, [|mkRel 1|]) in
443 let args = arg :: args in
444 let liftarg = lift (List.length ctx) arg in
445 let sigma, eq, refl =
446 if leq then
447 let sigma, eq = mkEq env sigma (lift 1 ty) (mkRel 1) liftarg in
448 let sigma, refl = mkRefl env sigma (lift (-lenctx) ty) arg in
449 sigma, eq, refl
450 else
451 let sigma, eq = mkHEq env sigma (lift 1 ty) (mkRel 1) liftargty liftarg in
452 let sigma, refl = mkHRefl env sigma argty arg in
453 sigma, eq, refl
454 in
455 let eqs = eq :: lift_list eqs in
456 let refls = refl :: refls in
457 let argvars = ids_of_constr env sigma vars arg in
458 (sigma, arity, ctx, push_rel decl ctxenv, c', args, eqs, refls,
459 nongenvars, Id.Set.union argvars vars)
460 in
461 let f', args' = decompose_indapp env sigma f args in
462 let dogen, f', args' =
463 let parvars = ids_of_constr env sigma ~all:true Id.Set.empty f' in
464 if not (linear env sigma parvars args') then true, f, args
465 else
466 match Array.findi (fun i x -> not (isVar sigma x) || is_defined_variable env (destVar sigma x)) args' with
467 | None -> false, f', args'
468 | Some nonvar ->
469 let before, after = Array.chop nonvar args' in
470 true, mkApp (f', before), after
471 in
472 if dogen then
473 let tyf' = Retyping.get_type_of env sigma f' in
474 let sigma, arity, ctx, ctxenv, c', args, eqs, refls, nogen, vars =
475 Array.fold_left aux (sigma, tyf',[],env,f',[],[],[],Id.Set.empty,Id.Set.empty) args'
476 in
477 let args, refls = List.rev args, List.rev refls in
478 let vars =
479 if generalize_vars then
480 let nogen = Id.Set.add id nogen in
481 hyps_of_vars env sigma hyps nogen vars
482 else []
483 in
484 let body, c' =
485 if defined then Some c', Retyping.get_type_of ctxenv sigma c'
486 else None, c'
487 in
488 let typ = Tacmach.pf_get_hyp_typ id gl in
489 let tac = make_abstract_generalize env id typ concl dep ctx body c' eqs args refls in
490 let tac = Proofview.Unsafe.tclEVARS sigma <*> tac in
491 Some (tac, dep, succ (List.length ctx), vars)
492 else None
493
494 let abstract_generalize ?(generalize_vars=true) ?(force_dep=false) id =
495 let open Context.Named.Declaration in
496 Proofview.Goal.enter begin fun gl ->
497 Rocqlib.(check_required_library jmeq_module_name);
498 let sigma = Proofview.Goal.sigma gl in
499 let (f, args, def, id, oldid) =
500 let oldid = Tacmach.pf_get_new_id id gl in
501 match Tacmach.pf_get_hyp id gl with
502 | LocalAssum (_,t) -> let f, args = decompose_app sigma t in
503 (f, args, false, id, oldid)
504 | LocalDef (_,t,_) ->
505 let f, args = decompose_app sigma t in
506 (f, args, true, id, oldid)
507 in
508 if Array.is_empty args then Proofview.tclUNIT ()
509 else
510 let newc = abstract_args gl generalize_vars force_dep id def f args in
511 match newc with
512 | None -> Proofview.tclUNIT ()
513 | Some (tac, dep, n, vars) ->
514 let tac =
515 if dep then
516 Tacticals.tclTHENLIST [
517 tac;
518 Tactics.rename_hyp [(id, oldid)]; Tacticals.tclDO n Tactics.intro;
519 generalize_dep ~with_let:true (mkVar oldid)]
520 else Tacticals.tclTHENLIST [
521 tac;
522 Tactics.clear [id];
523 Tacticals.tclDO n Tactics.intro]
524 in
525 if List.is_empty vars then tac
526 else Tacticals.tclTHEN tac
527 (Tacticals.tclFIRST
528 [revert vars ;
529 Tacticals.tclMAP (fun id ->
530 Tacticals.tclTRY (generalize_dep ~with_let:true (mkVar id))) vars])
531 end