Debian Codegraph @

tactics/rewrite.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 Constr
16 open Context
17 open EConstr
18 open Vars
19 open Tacticals
20 open Tactics
21 open Pretype_errors
22 open Evd
23 open Tactypes
24 open Locus
25 open Locusops
26 open Elimschemes
27 open Environ
28 open Termops
29 open EConstr
30 open Proofview.Notations
31 open Context.Named.Declaration
32
33 module TC = Typeclasses
34
35 let { Goptions.get = do_rewrite_output_constraints } =
36 Goptions.declare_bool_option_and_ref ~key:["Rewrite"; "Output"; "Constraints"] ~value:false ()
37
38 (** Typeclass-based generalized rewriting. *)
39
40 (** Constants used by the tactic. *)
41
42 let bind_global_ref lib s =
43 let gr = lazy (Rocqlib.lib_ref (lib ^ "." ^ s)) in
44 fun () -> Lazy.force gr
45
46 type evars = evar_map * Evar.Set.t (* goal evars, constraint evars *)
47
48 let bind_global lib s =
49 let gr = lazy (Rocqlib.lib_ref (lib ^ "." ^ s)) in
50 fun env (evd,cstrs) ->
51 let (evd, c) = Evd.fresh_global env evd (Lazy.force gr) in
52 (evd, cstrs), c
53
54 (** Utility for dealing with polymorphic applications *)
55
56 (** Global constants. *)
57
58 let rocq_eq_ref () = Rocqlib.lib_ref "core.eq.type"
59 let rocq_eq = bind_global "core.eq" "type"
60 let rocq_f_equal = bind_global "core.eq" "congr"
61 let rocq_all = bind_global "core" "all"
62 let impl = bind_global "core" "impl"
63
64 let default_relation = bind_global "rewrite" "DefaultRelation"
65
66 (** Bookkeeping which evars are constraints so that we can
67 remove them at the end of the tactic. *)
68
69 let goalevars evars = fst evars
70 let cstrevars evars = snd evars
71
72 let new_cstr_evar (evd,cstrs) env t =
73 (* We handle the typeclass resolution of constraints ourselves *)
74 let (evd', t) = Evarutil.new_evar env evd ~typeclass_candidate:false t in
75 let ev, _ = destEvar evd' t in
76 (evd', Evar.Set.add ev cstrs), t
77
78 (** Building or looking up instances. *)
79
80 let extends_undefined evars evars' =
81 let f ev evi found = found || not (Evd.mem evars ev)
82 in fold_undefined f evars' false
83
84 let app_poly_check env evars f args =
85 let (evars, cstrs), fc = f env evars in
86 let evars, t = Typing.checked_appvect env evars fc args in
87 (evars, cstrs), t
88
89 let app_poly_nocheck env evars f args =
90 let evars, fc = f env evars in
91 evars, mkApp (fc, args)
92
93 let app_poly_sort b =
94 if b then app_poly_nocheck
95 else app_poly_check
96
97 let find_class_proof proof_type proof_method env evars carrier relation =
98 try
99 let evars, goal = app_poly_check env evars proof_type [| carrier ; relation |] in
100 let evars', c = Class_tactics.resolve_one_typeclass env (goalevars evars) goal in
101 if extends_undefined (goalevars evars) evars' then raise Not_found
102 else app_poly_check env (evars',cstrevars evars) proof_method [| carrier; relation; c |]
103 with e when CErrors.noncritical e -> raise Not_found
104
105 let eq_pb (ty, env, x, y as pb) (ty', env', x', y' as pb') =
106 let equal x y = Constr.equal (EConstr.Unsafe.to_constr x) (EConstr.Unsafe.to_constr y) in
107 pb == pb' || (ty == ty' && equal x x' && equal y y')
108
109 let problem_inclusion x y =
110 List.for_all (fun pb -> List.exists (fun pb' -> eq_pb pb pb') y) x
111
112 let evd_convertible env evd x y =
113 try
114 (* Unfortunately, the_conv_x might say they are unifiable even if some
115 unsolvable constraints remain, so we check that this unification
116 does not introduce any new problem. *)
117 let _, pbs = Evd.extract_all_conv_pbs evd in
118 let evd' = Evarconv.unify_delay env evd x y in
119 let _, pbs' = Evd.extract_all_conv_pbs evd' in
120 if evd' == evd || problem_inclusion pbs' pbs then Some evd'
121 else None
122 with e when CErrors.noncritical e -> None
123
124 type hypinfo = {
125 prf : constr;
126 car : constr;
127 rel : constr;
128 sort : bool; (* true = Prop; false = Type *)
129 c1 : constr;
130 c2 : constr;
131 holes : EClause.hole list;
132 }
133
134 let error_no_relation () = user_err Pp.(str "Cannot find a relation to rewrite.")
135
136 let rec decompose_app_rel env evd t =
137 (* Head normalize for compatibility with the old meta mechanism *)
138 let t = Reductionops.whd_betaiota env evd t in
139 match EConstr.kind evd t with
140 | App (f, [||]) -> assert false
141 | App (f, [|arg|]) ->
142 (* This treats the special case `g (R x y)`, turning it into
143 the relation `(fun x y => g (R x y))`. Useful when g is negation in particular. *)
144 let (f', argl, argr) = decompose_app_rel env evd arg in
145 let ty = Retyping.get_type_of env evd argl in
146 let ty' = Retyping.get_type_of env evd argr in
147 let r = Retyping.relevance_of_type env evd ty in
148 let r' = Retyping.relevance_of_type env evd ty' in
149 let f'' = mkLambda (make_annot (Name Namegen.default_dependent_ident) r, ty,
150 mkLambda (make_annot (Name (Id.of_string "y")) r', lift 1 ty',
151 mkApp (lift 2 f, [| mkApp (lift 2 f', [| mkRel 2; mkRel 1 |]) |])))
152 in (f'', argl, argr)
153 | App (f, args) ->
154 let len = Array.length args in
155 let fargs = Array.sub args 0 (Array.length args - 2) in
156 let rel = mkApp (f, fargs) in
157 rel, args.(len - 2), args.(len - 1)
158 | _ -> error_no_relation ()
159
160 let decompose_app_rel env evd t =
161 let (rel, t1, t2) = decompose_app_rel env evd t in
162 let ty = try Retyping.get_type_of ~lax:true env evd rel with Retyping.RetypeError _ -> error_no_relation () in
163 if not (Reductionops.is_arity env evd ty) then None else
164 match Reductionops.splay_arity env evd ty with
165 | [_, ty2; _, ty1], concl ->
166 if noccurn evd 1 ty2 then
167 Some (rel, ty1, subst1 mkProp ty2, concl, t1, t2)
168 else None
169 | _ -> assert false
170
171 let decompose_app_rel_error env evd t =
172 match decompose_app_rel env evd t with
173 | Some e -> e
174 | None -> error_no_relation ()
175
176 let decompose_applied_relation env sigma (c,l) =
177 let open Context.Rel.Declaration in
178 let ctype = Retyping.get_type_of env sigma c in
179 let find_rel ty =
180 let sigma, cl = EClause.make_evar_clause env sigma ty in
181 let sigma = EClause.solve_evar_clause env sigma true cl l in
182 let { EClause.cl_holes = holes; EClause.cl_concl = t } = cl in
183 match decompose_app_rel env sigma t with
184 | None -> None
185 | Some (equiv, ty1, ty2, concl, c1, c2) ->
186 match evd_convertible env sigma ty1 ty2 with
187 | None -> None
188 | Some sigma ->
189 let args = Array.map_of_list (fun h -> h.EClause.hole_evar) holes in
190 let value = mkApp (c, args) in
191 Some (sigma, { prf=value;
192 car=ty1; rel = equiv; sort = Sorts.is_prop (ESorts.kind sigma concl);
193 c1=c1; c2=c2; holes })
194 in
195 match find_rel ctype with
196 | Some c -> c
197 | None ->
198 let ctx,t' = Reductionops.whd_decompose_prod env sigma ctype in (* Search for underlying eq *)
199 let t' = it_mkProd_or_LetIn t' (List.map (fun (n,t) -> LocalAssum (n, t)) ctx) in
200 match find_rel t' with
201 | Some c -> c
202 | None -> user_err Pp.(str "Cannot find a homogeneous relation to rewrite.")
203
204 (** Utility functions *)
205
206 module GlobalBindings (M : sig
207 val prefix : string
208 val app_poly : env -> evars -> (env -> evars -> evars * constr) -> constr array -> evars * constr
209 val arrow : env -> evars -> evars * constr
210 end) = struct
211 open M
212 open Context.Rel.Declaration
213
214 let bind_rewrite s = bind_global prefix s
215 let bind_rewrite_ref s = bind_global_ref prefix s
216
217 let relation : env -> evars -> evars * constr =
218 bind_rewrite "relation"
219
220 let reflexive_type = bind_rewrite "Reflexive"
221 let reflexive_proof = bind_rewrite "reflexivity"
222
223 let symmetric_type = bind_rewrite "Symmetric"
224 let symmetric_proof = bind_rewrite "symmetry"
225
226 let transitive_type = bind_rewrite "Transitive"
227 let transitive_proof = bind_rewrite "transitivity"
228
229 let forall_relation = bind_rewrite "forall_relation"
230 let pointwise_relation = bind_rewrite "pointwise_relation"
231
232 let forall_relation_ref = bind_global_ref prefix "forall_relation"
233 let pointwise_relation_ref = bind_global_ref prefix "pointwise_relation"
234
235 let respectful = bind_rewrite "respectful"
236
237 let rocq_forall = bind_rewrite "forall_def"
238
239 let subrelation = bind_rewrite "subrelation"
240 let do_subrelation = bind_rewrite "do_subrelation"
241 let apply_subrelation = bind_rewrite "apply_subrelation"
242
243 let rewrite_relation_class = bind_rewrite "RewriteRelation"
244
245 let proper_class =
246 let r = lazy (bind_rewrite_ref "Proper" ()) in
247 fun () -> Option.get (TC.class_info (Global.env ()) (Lazy.force r))
248
249 let proper_proxy_class =
250 let r = lazy (bind_rewrite_ref "ProperProxy" ()) in
251 fun () -> Option.get (TC.class_info (Global.env ()) (Lazy.force r))
252
253 let proper_proj () = bind_rewrite_ref "proper_prf" ()
254
255 let proper_type env (sigma,cstrs) =
256 let l = (proper_class ()).TC.cl_impl in
257 let (sigma, c) = Evd.fresh_global env sigma l in
258 (sigma, cstrs), c
259
260 let proper_proxy_type env (sigma,cstrs) =
261 let l = (proper_proxy_class ()).TC.cl_impl in
262 let (sigma, c) = Evd.fresh_global env sigma l in
263 (sigma, cstrs), c
264
265 let proper_proof env evars carrier relation x =
266 let evars, goal = app_poly env evars proper_proxy_type [| carrier ; relation; x |] in
267 new_cstr_evar evars env goal
268
269 let get_reflexive_proof env = find_class_proof reflexive_type reflexive_proof env
270 let get_symmetric_proof env = find_class_proof symmetric_type symmetric_proof env
271 let get_transitive_proof env = find_class_proof transitive_type transitive_proof env
272
273 let mk_relation env evars ty =
274 let evars', ty = Evarsolve.refresh_universes ~onlyalg:true ~status:(Evd.UnivFlexible false)
275 (Some false) env (fst evars) ty in
276 app_poly env (evars', snd evars) relation [| ty |]
277
278 (** Build an inferred signature from constraints on the arguments and expected output
279 relation *)
280
281 let build_signature evars env m (cstrs : (types * types option) option list)
282 (finalcstr : (types * types option) option) =
283 let mk_relty evars newenv ty obj =
284 match obj with
285 | None | Some (_, None) ->
286 let evars, relty = mk_relation newenv evars ty in
287 if closed0 (goalevars evars) ty then
288 let env' = Environ.reset_with_named_context (Environ.named_context_val env) env in
289 new_cstr_evar evars env' relty
290 else new_cstr_evar evars newenv relty
291 | Some (x, Some rel) -> evars, rel
292 in
293 let rec aux env evars ty l =
294 let t = Reductionops.whd_all env (goalevars evars) ty in
295 match EConstr.kind (goalevars evars) t, l with
296 | Prod (na, ty, b), obj :: cstrs ->
297 let b = Reductionops.nf_betaiota env (goalevars evars) b in
298 if noccurn (goalevars evars) 1 b (* non-dependent product *) then
299 let ty = Reductionops.nf_betaiota env (goalevars evars) ty in
300 let (evars, b', arg, cstrs) = aux env evars (subst1 mkProp b) cstrs in
301 let evars, relty = mk_relty evars env ty obj in
302 let evars', b' = Evarsolve.refresh_universes ~onlyalg:true ~status:(Evd.UnivFlexible false)
303 (Some false) env (fst evars) b' in
304 let evars, newarg = app_poly env (evars', snd evars) respectful [| ty ; b' ; relty ; arg |] in
305 evars, mkProd(na, ty, b), newarg, (ty, Some relty) :: cstrs
306 else
307 let (evars, b, arg, cstrs) =
308 aux (push_rel (LocalAssum (na, ty)) env) evars b cstrs
309 in
310 let ty = Reductionops.nf_betaiota env (goalevars evars) ty in
311 let pred = mkLambda (na, ty, b) in
312 let liftarg = mkLambda (na, ty, arg) in
313 let evars, arg' = app_poly env evars forall_relation [| ty ; pred ; liftarg |] in
314 if Option.is_empty obj then evars, mkProd(na, ty, b), arg', (ty, None) :: cstrs
315 else user_err Pp.(str "build_signature: no constraint can apply on a dependent argument")
316 | _, obj :: _ -> anomaly ~label:"build_signature" (Pp.str "not enough products.")
317 | _, [] ->
318 (match finalcstr with
319 | None | Some (_, None) ->
320 let t = Reductionops.nf_betaiota env (fst evars) ty in
321 let evars, rel = mk_relty evars env t None in
322 evars, t, rel, [t, Some rel]
323 | Some (t, Some rel) -> evars, t, rel, [t, Some rel])
324 in aux env evars m cstrs
325
326 (** Folding/unfolding of the tactic constants. *)
327
328 let unfold_impl n sigma t =
329 match EConstr.kind sigma t with
330 | App (arrow, [| a; b |])(* when eq_constr arrow (Lazy.force impl) *) ->
331 mkProd (make_annot n ERelevance.relevant, a, lift 1 b)
332 | _ -> assert false
333
334 let unfold_all sigma t =
335 match EConstr.kind sigma t with
336 | App (id, [| a; b |]) (* when eq_constr id (Lazy.force rocq_all) *) ->
337 (match EConstr.kind sigma b with
338 | Lambda (n, ty, b) -> mkProd (n, ty, b)
339 | _ -> assert false)
340 | _ -> assert false
341
342 let unfold_forall sigma t =
343 match EConstr.kind sigma t with
344 | App (id, [| a; b |]) (* when eq_constr id (Lazy.force rocq_all) *) ->
345 (match EConstr.kind sigma b with
346 | Lambda (n, ty, b) -> mkProd (n, ty, b)
347 | _ -> assert false)
348 | _ -> assert false
349
350 let arrow_morphism env evd n ta tb a b =
351 let ap = is_Prop (goalevars evd) ta and bp = is_Prop (goalevars evd) tb in
352 if ap && bp then app_poly env evd impl [| a; b |], unfold_impl n
353 else if ap then (* Domain in Prop, CoDomain in Type *)
354 (app_poly env evd arrow [| a; b |]), unfold_impl n
355 (* (evd, mkProd (Anonymous, a, b)), (fun x -> x) *)
356 else if bp then (* Dummy forall *)
357 (app_poly env evd rocq_all [| a; mkLambda (make_annot n ERelevance.relevant, a, lift 1 b) |]), unfold_forall
358 else (* None in Prop, use arrow *)
359 (app_poly env evd arrow [| a; b |]), unfold_impl n
360
361 let rec decomp_pointwise env sigma n c =
362 if Int.equal n 0 then Some c
363 else
364 match EConstr.kind sigma c with
365 | App (f, [| a; b; relb |]) when isRefX env sigma (pointwise_relation_ref ()) f ->
366 decomp_pointwise env sigma (pred n) relb
367 | App (f, [| a; b; arelb |]) when isRefX env sigma (forall_relation_ref ()) f ->
368 decomp_pointwise env sigma (pred n) (Reductionops.beta_applist sigma (arelb, [mkRel 1]))
369 | _ ->
370 (* cf #11347: when rewriting a commutative cut, we
371 decomp_pointwise on "c := eq (Prop -> Prop)"
372 Maybe if funext is available it's possible to do something? *)
373 None
374
375 let rec apply_pointwise env sigma rel = function
376 | arg :: args ->
377 (match EConstr.kind sigma rel with
378 | App (f, [| a; b; relb |]) when isRefX env sigma (pointwise_relation_ref ()) f ->
379 apply_pointwise env sigma relb args
380 | App (f, [| a; b; arelb |]) when isRefX env sigma (forall_relation_ref ()) f ->
381 apply_pointwise env sigma (Reductionops.beta_applist sigma (arelb, [arg])) args
382 | _ -> invalid_arg "apply_pointwise")
383 | [] -> rel
384
385 let refresh_univs env evars ty =
386 let evars', ty = Evarsolve.refresh_universes ~onlyalg:true ~status:(Evd.UnivFlexible false)
387 (Some false) env (fst evars) ty in
388 (evars', snd evars), ty
389
390 let pointwise_or_dep_relation env evars n t car rel =
391 let evars, car = refresh_univs env evars car in
392 if noccurn (goalevars evars) 1 car && noccurn (goalevars evars) 1 rel then
393 app_poly env evars pointwise_relation [| t; lift (-1) car; lift (-1) rel |]
394 else
395 app_poly env evars forall_relation
396 [| t; mkLambda (make_annot n ERelevance.relevant, t, car);
397 mkLambda (make_annot n ERelevance.relevant, t, rel) |]
398
399 let lift_cstr env evars (args : constr list) c ty cstr =
400 let start evars env car =
401 match cstr with
402 | None | Some (_, None) ->
403 let evars, rel = mk_relation env evars car in
404 new_cstr_evar evars env rel
405 | Some (ty, Some rel) -> evars, rel
406 in
407 let rec aux evars env prod n =
408 if Int.equal n 0 then start evars env prod
409 else
410 let sigma = goalevars evars in
411 match EConstr.kind sigma (Reductionops.whd_all env sigma prod) with
412 | Prod (na, ty, b) ->
413 if noccurn sigma 1 b then
414 let b' = lift (-1) b in
415 let evars, rb = aux evars env b' (pred n) in
416 app_poly env evars pointwise_relation [| ty; b'; rb |]
417 else
418 let evars, rb = aux evars (push_rel (LocalAssum (na, ty)) env) b (pred n) in
419 app_poly env evars forall_relation
420 [| ty; mkLambda (na, ty, b); mkLambda (na, ty, rb) |]
421 | _ -> raise Not_found
422 in
423 let rec find env c ty = function
424 | [] -> None
425 | arg :: args ->
426 try let evars, found = aux evars env ty (succ (List.length args)) in
427 Some (evars, found, c, ty, arg :: args)
428 with Not_found ->
429 let sigma = goalevars evars in
430 let ty = Reductionops.whd_all env sigma ty in
431 find env (mkApp (c, [| arg |])) (prod_applist sigma ty [arg]) args
432 in find env c ty args
433
434 let unlift_cstr env sigma = function
435 | None -> None
436 | Some codom -> decomp_pointwise env (goalevars sigma) 1 codom
437
438 (** Looking up declared rewrite relations (instances of [RewriteRelation]) *)
439 let is_applied_rewrite_relation env sigma rels t =
440 match EConstr.kind sigma t with
441 | App (c, args) when Array.length args >= 2 ->
442 let head = if isApp sigma c then fst (destApp sigma c) else c in
443 if isRefX env sigma (rocq_eq_ref ()) head then None
444 else
445 (try
446 let env' = push_rel_context rels env in
447 match decompose_app_rel env' sigma t with
448 | None -> None
449 | Some (equiv, ty1, ty2, concl, c1, c2) ->
450 let (evars, evset), inst =
451 app_poly env' (sigma,Evar.Set.empty)
452 rewrite_relation_class [| ty1; equiv |] in
453 let sigma, _ = Class_tactics.resolve_one_typeclass env' evars inst in
454 (* We check that the relation is homogeneous *after* launching resolution,
455 as this convertibility test might be expensive in general (e.g. this
456 slows down mathcomp-odd-order). *)
457 match evd_convertible env sigma ty1 ty2 with
458 | None -> None
459 | Some sigma -> Some (it_mkProd_or_LetIn t rels)
460 with e when CErrors.noncritical e -> None)
461 | _ -> None
462
463 end
464
465 let type_app_poly env env evd f args =
466 let evars, c = app_poly_nocheck env evd f args in
467 let evd', t = Typing.type_of env (goalevars evars) c in
468 (evd', cstrevars evars), c
469
470 module PropGlobal = struct
471 module Consts =
472 struct
473 let prefix = "rewrite.prop"
474 let app_poly = app_poly_nocheck
475 let arrow = bind_global "core" "arrow"
476 let rocq_inverse = bind_global "core" "flip"
477 end
478
479 module G = GlobalBindings(Consts)
480
481 include G
482 include Consts
483 let inverse env evd car rel =
484 type_app_poly env env evd rocq_inverse [| car ; car; mkProp; rel |]
485 (* app_poly env evd rocq_inverse [| car ; car; mkProp; rel |] *)
486
487 end
488
489 module TypeGlobal = struct
490 module Consts =
491 struct
492 let prefix = "rewrite.type"
493 let app_poly = app_poly_check
494 let arrow = bind_global prefix "arrow"
495 let rocq_inverse = bind_global prefix "flip"
496 end
497
498 module G = GlobalBindings(Consts)
499 include G
500 include Consts
501
502
503 let inverse env (evd,cstrs) car rel =
504 let evd, car = Evarsolve.refresh_universes ~onlyalg:true (Some false) env evd car in
505 let (evd, sort) = Evarutil.new_Type ~rigid:Evd.univ_flexible evd in
506 app_poly_check env (evd,cstrs) rocq_inverse [| car ; car; sort; rel |]
507
508 end
509
510 (* Check that relation constants have been registered *)
511 let init_relation_classes () =
512 if Rocqlib.has_ref "rewrite.prop.relation" || Rocqlib.has_ref "rewrite.type.relation" then ()
513 else CErrors.user_err
514 (Pp.str "No bindings have been registered for relation classes in Prop or Type, maybe you need to require Corelib.Classes.(C)RelationClasses.")
515
516 let init_rewrite () =
517 if Rocqlib.has_ref "rewrite.prop.Proper" || Rocqlib.has_ref "rewrite.type.Proper" then ()
518 else CErrors.user_err
519 (Pp.str "No bindings have been registered for morphisms in Prop or Type, maybe you need to require Corelib.Classes.(C)Morphisms.")
520
521 let get_type_of_refresh env evars t =
522 let evars', tty = Evarsolve.get_type_of_refresh env (fst evars) t in
523 (evars', snd evars), tty
524
525 let sort_of_rel env evm rel =
526 ESorts.kind evm (Reductionops.sort_of_arity env evm (Retyping.get_type_of env evm rel))
527
528 let is_applied_rewrite_relation = PropGlobal.is_applied_rewrite_relation
529
530 (* let _ = *)
531 (* Hook.set Equality.is_applied_rewrite_relation is_applied_rewrite_relation *)
532
533 let split_head = function
534 hd :: tl -> hd, tl
535 | [] -> assert(false)
536
537 let get_symmetric_proof b =
538 if b then PropGlobal.get_symmetric_proof else TypeGlobal.get_symmetric_proof
539
540 let rewrite_db = "rewrite"
541
542 let conv_transparent_state =
543 let open TransparentState in
544 { tr_var = Id.Pred.empty; tr_cst = Cpred.full; tr_prj = PRpred.full }
545
546 let rewrite_transparent_state () =
547 Hints.Hint_db.transparent_state (Hints.searchtable_map rewrite_db)
548
549 let rewrite_core_unif_flags = {
550 Unification.modulo_conv_on_closed_terms = None;
551 Unification.use_metas_eagerly_in_conv_on_closed_terms = true;
552 Unification.use_evars_eagerly_in_conv_on_closed_terms = true;
553 Unification.modulo_delta = TransparentState.empty;
554 Unification.modulo_delta_types = TransparentState.full;
555 Unification.check_applied_meta_types = true;
556 Unification.use_pattern_unification = true;
557 Unification.use_meta_bound_pattern_unification = true;
558 Unification.allowed_evars = Evarsolve.AllowedEvars.all;
559 Unification.restrict_conv_on_strict_subterms = false;
560 Unification.modulo_betaiota = false;
561 Unification.modulo_eta = true;
562 }
563
564 (* Flags used for the setoid variant of "rewrite" and for the strategies
565 "hints"/"old_hints"/"terms" of "rewrite_strat", and for solving pre-existing
566 evars in "rewrite" (see unify_abs) *)
567 let rewrite_unif_flags =
568 let flags = rewrite_core_unif_flags in {
569 Unification.core_unify_flags = flags;
570 Unification.merge_unify_flags = flags;
571 Unification.subterm_unify_flags = flags;
572 Unification.allow_K_in_toplevel_higher_order_unification = true;
573 Unification.resolve_evars = true
574 }
575
576 let rewrite_core_conv_unif_flags = {
577 rewrite_core_unif_flags with
578 Unification.modulo_conv_on_closed_terms = Some conv_transparent_state;
579 Unification.modulo_delta_types = conv_transparent_state;
580 Unification.modulo_betaiota = true
581 }
582
583 (* Fallback flags for the setoid variant of "rewrite" *)
584 let rewrite_conv_unif_flags =
585 let flags = rewrite_core_conv_unif_flags in {
586 Unification.core_unify_flags = flags;
587 Unification.merge_unify_flags = flags;
588 Unification.subterm_unify_flags = flags;
589 Unification.allow_K_in_toplevel_higher_order_unification = true;
590 Unification.resolve_evars = true
591 }
592
593 (* Flags for "setoid_rewrite c"/"rewrite_strat -> c" *)
594 let general_rewrite_unif_flags () =
595 let ts = rewrite_transparent_state () in
596 let core_flags =
597 { rewrite_core_unif_flags with
598 Unification.modulo_conv_on_closed_terms = Some ts;
599 Unification.use_evars_eagerly_in_conv_on_closed_terms = true;
600 Unification.modulo_delta = ts;
601 Unification.modulo_delta_types = TransparentState.full;
602 Unification.modulo_betaiota = true }
603 in {
604 Unification.core_unify_flags = core_flags;
605 Unification.merge_unify_flags = core_flags;
606 Unification.subterm_unify_flags = { core_flags with Unification.modulo_delta = TransparentState.empty };
607 Unification.allow_K_in_toplevel_higher_order_unification = true;
608 Unification.resolve_evars = true
609 }
610
611 (** FIXME: write this in the new monad interface *)
612 let solve_remaining_by env sigma holes by =
613 match by with
614 | None -> sigma
615 | Some tac ->
616 let map h =
617 if h.EClause.hole_deps then None
618 else match EConstr.kind sigma h.EClause.hole_evar with
619 | Evar (evk, _) ->
620 Some evk
621 | _ -> None
622 in
623 (* Only solve independent holes *)
624 let indep = List.map_filter map holes in
625 let solve_tac = tclCOMPLETE (Gentactic.interp tac) in
626 let solve sigma evk =
627 let evi =
628 try Some (Evd.find_undefined sigma evk)
629 with Not_found -> None
630 in
631 match evi with
632 | None -> sigma
633 (* Evar should not be defined, but just in case *)
634 | Some evi ->
635 let env = Evd.evar_env env evi in
636 let ty = Evd.evar_concl evi in
637 let name, poly = Id.of_string "rewrite", PolyFlags.default in
638 let c, sigma = Subproof.refine_by_tactic ~name ~poly env sigma ty solve_tac in
639 Evd.define evk c sigma
640 in
641 List.fold_left solve sigma indep
642
643 let no_constraints cstrs =
644 fun ev _ -> not (Evar.Set.mem ev cstrs)
645
646 let poly_inverse sort =
647 if sort then PropGlobal.inverse else TypeGlobal.inverse
648
649 type rewrite_proof =
650 | RewPrf of constr * constr
651 (** A Relation (R : rew_car -> rew_car -> Prop) and a proof of R rew_from rew_to *)
652
653 | RewCast of cast_kind
654 (** A proof of convertibility (with casts) *)
655
656 type rewrite_result_info = {
657 rew_car : constr ;
658 (** A type *)
659 rew_from : constr ;
660 (** A term of type rew_car *)
661 rew_to : constr ;
662 (** A term of type rew_car *)
663 rew_prf : rewrite_proof ;
664 (** A proof of rew_from == rew_to *)
665 rew_evars : evars;
666 }
667
668 type rewrite_result =
669 | Fail
670 | Identity
671 | Success of rewrite_result_info
672
673 type 'a strategy_input = { state : 'a ; (* a parameter: for instance, a state *)
674 env : Environ.env ;
675 unfresh : Id.Set.t; (* Unfresh names *)
676 term1 : constr ;
677 ty1 : types ; (* first term and its type (convertible to rew_from) *)
678 cstr : (bool (* prop *) * constr option) ;
679 evars : evars }
680
681 type 'a pure_strategy = { strategy :
682 'a strategy_input ->
683 'a * rewrite_result (* the updated state and the "result" *) }
684
685 type strategy = unit pure_strategy
686
687 let symmetry env sort rew =
688 let { rew_evars = evars; rew_car = car; } = rew in
689 let (rew_evars, rew_prf) = match rew.rew_prf with
690 | RewCast _ -> (rew.rew_evars, rew.rew_prf)
691 | RewPrf (rel, prf) ->
692 try
693 let evars, symprf = get_symmetric_proof sort env evars car rel in
694 let prf = mkApp (symprf, [| rew.rew_from ; rew.rew_to ; prf |]) in
695 (evars, RewPrf (rel, prf))
696 with Not_found ->
697 let evars, rel = poly_inverse sort env evars car rel in
698 (evars, RewPrf (rel, prf))
699 in
700 { rew with rew_from = rew.rew_to; rew_to = rew.rew_from; rew_prf; rew_evars; }
701
702 (* Matching/unifying the rewriting rule against [t] *)
703 let unify_eqn { car; rel; prf; c1; c2; holes; sort } l2r flags env (sigma, cstrs) by t =
704 try
705 let left = if l2r then c1 else c2 in
706 let _, sigma = Unification.w_unify ~flags env sigma CONV left t in
707 let sigma = TC.resolve_typeclasses ~filter:(no_constraints cstrs)
708 ~fail:true env sigma in
709 let sigma = solve_remaining_by env sigma holes by in
710 let nf c = Reductionops.nf_evar sigma c in
711 let c1 = nf c1 and c2 = nf c2
712 and rew_car = nf car and rel = nf rel
713 and prf = nf prf in
714 let ty1 = Retyping.get_type_of env sigma c1 in
715 let ty2 = Retyping.get_type_of env sigma c2 in
716 begin match Reductionops.infer_conv ~pb:CUMUL env sigma ty2 ty1 with
717 | None -> None
718 | Some sigma ->
719 let rew_evars = sigma, cstrs in
720 let rew_prf = RewPrf (rel, prf) in
721 let rew = { rew_evars; rew_prf; rew_car; rew_from = c1; rew_to = c2; } in
722 let rew = if l2r then rew else symmetry env sort rew in
723 Some rew
724 end
725 with
726 | e when noncritical e -> None
727
728 let unify_abs (car, rel, prf, c1, c2) l2r sort env (sigma, cstrs) t =
729 try
730 let left = if l2r then c1 else c2 in
731 (* The pattern is already instantiated, so the next w_unify is
732 basically an eq_constr, except when preexisting evars occur in
733 either the lemma or the goal, in which case the eq_constr also
734 solved this evars *)
735 let _, sigma = Unification.w_unify ~flags:rewrite_unif_flags env sigma CONV left t in
736 let rew_evars = sigma, cstrs in
737 let rew_prf = RewPrf (rel, prf) in
738 let rew = { rew_car = car; rew_from = c1; rew_to = c2; rew_prf; rew_evars; } in
739 let rew = if l2r then rew else symmetry env sort rew in
740 Some rew
741 with
742 | e when noncritical e -> None
743
744 type rewrite_flags = { under_lambdas : bool; on_morphisms : bool }
745
746 let default_flags = { under_lambdas = true; on_morphisms = true; }
747
748 let get_opt_rew_rel = function RewPrf (rel, prf) -> Some rel | _ -> None
749
750 let new_global env (evars, cstrs) gr =
751 let (sigma,c) = Evd.fresh_global env evars gr in
752 (sigma, cstrs), c
753
754 let make_eq env sigma =
755 new_global env sigma Rocqlib.(lib_ref "core.eq.type")
756 let make_eq_refl env sigma =
757 new_global env sigma Rocqlib.(lib_ref "core.eq.refl")
758
759 let get_rew_prf env evars r = match r.rew_prf with
760 | RewPrf (rel, prf) -> evars, (rel, prf)
761 | RewCast c ->
762 let evars, eq = make_eq env evars in
763 let evars, eq_refl = make_eq_refl env evars in
764 let rel = mkApp (eq, [| r.rew_car |]) in
765 evars, (rel, mkCast (mkApp (eq_refl, [| r.rew_car; r.rew_from |]),
766 c, mkApp (rel, [| r.rew_from; r.rew_to |])))
767
768 let poly_subrelation sort =
769 if sort then PropGlobal.subrelation else TypeGlobal.subrelation
770
771 let resolve_subrelation env car rel sort prf rel' res =
772 if Termops.eq_constr env (fst res.rew_evars) rel rel' then res
773 else
774 let evars, app = app_poly_check env res.rew_evars (poly_subrelation sort) [|car; rel; rel'|] in
775 let evars, subrel = new_cstr_evar evars env app in
776 let appsub = mkApp (subrel, [| res.rew_from ; res.rew_to ; prf |]) in
777 { res with
778 rew_prf = RewPrf (rel', appsub);
779 rew_evars = evars }
780
781 let resolve_morphism env m args args' (b,cstr) evars =
782 let evars, proj, sigargs, m', args, args' =
783 let first = match (Array.findi (fun _ b -> not (Option.is_empty b)) args') with
784 | Some i -> i
785 | None -> invalid_arg "resolve_morphism" in
786 let morphargs, morphobjs = Array.chop first args in
787 let morphargs', morphobjs' = Array.chop first args' in
788 let appm = mkApp(m, morphargs) in
789 let evd, appmtype = Typing.type_of env (goalevars evars) appm in
790 let evars = evd, snd evars in
791 let cstrs = List.map
792 (Option.map (fun r -> r.rew_car, get_opt_rew_rel r.rew_prf))
793 (Array.to_list morphobjs')
794 in
795 (* Desired signature *)
796 let evars, appmtype', signature, sigargs =
797 if b then PropGlobal.build_signature evars env appmtype cstrs cstr
798 else TypeGlobal.build_signature evars env appmtype cstrs cstr
799 in
800 (* Actual signature found *)
801 let evars', appmtype' = Evarsolve.refresh_universes ~status:(Evd.UnivFlexible false) ~onlyalg:true
802 (Some false) env (fst evars) appmtype' in
803 let cl_args = [| appmtype' ; signature ; appm |] in
804 let evars, app = app_poly_sort b env (evars', snd evars) (if b then PropGlobal.proper_type else TypeGlobal.proper_type)
805 cl_args in
806 let dosub, appsub =
807 if b then PropGlobal.do_subrelation, PropGlobal.apply_subrelation
808 else TypeGlobal.do_subrelation, TypeGlobal.apply_subrelation
809 in
810 let _, dosub = app_poly_sort b env evars dosub [||] in
811 let _, appsub = app_poly_nocheck env evars appsub [||] in
812 let dosub_id = Id.of_string "do_subrelation" in
813 let env' = EConstr.push_named (LocalDef (make_annot dosub_id ERelevance.relevant, dosub, appsub)) env in
814 let evars, morph = new_cstr_evar evars env' app in
815 (* Replace the free [dosub_id] in the evar by the global reference *)
816 let morph = Vars.replace_vars (fst evars) [dosub_id , dosub] morph in
817 evars, morph, sigargs, appm, morphobjs, morphobjs'
818 in
819 let projargs, subst, evars, respars, typeargs =
820 Array.fold_left2
821 (fun (acc, subst, evars, sigargs, typeargs') x y ->
822 let (carrier, relation), sigargs = split_head sigargs in
823 match relation with
824 | Some relation ->
825 let carrier = substl subst carrier
826 and relation = substl subst relation in
827 (match y with
828 | None ->
829 let evars, proof =
830 (if b then PropGlobal.proper_proof else TypeGlobal.proper_proof)
831 env evars carrier relation x in
832 [ proof ; x ; x ] @ acc, subst, evars, sigargs, x :: typeargs'
833 | Some r ->
834 let evars, proof = get_rew_prf env evars r in
835 [ snd proof; r.rew_to; x ] @ acc, subst, evars,
836 sigargs, r.rew_to :: typeargs')
837 | None ->
838 if not (Option.is_empty y) then
839 user_err Pp.(str "Cannot rewrite inside dependent arguments of a function");
840 x :: acc, x :: subst, evars, sigargs, x :: typeargs')
841 ([], [], evars, sigargs, []) args args'
842 in
843 let proof = applist (proj, List.rev projargs) in
844 let newt = applist (m', List.rev typeargs) in
845 match respars with
846 [ a, Some r ] -> evars, proof, substl subst a, substl subst r, newt
847 | _ -> assert(false)
848
849 let apply_constraint env car rel prf cstr res =
850 match snd cstr with
851 | None -> res
852 | Some r -> resolve_subrelation env car rel (fst cstr) prf r res
853
854 let coerce env cstr res =
855 let evars, (rel, prf) = get_rew_prf env res.rew_evars res in
856 let res = { res with rew_evars = evars } in
857 apply_constraint env res.rew_car rel prf cstr res
858
859 let apply_rule unify : occurrences_count pure_strategy =
860 { strategy = fun { state = occs ; env ;
861 term1 = t ; ty1 = ty ; cstr ; evars } ->
862 let unif = if isEvar (goalevars evars) t then None else unify env evars t in
863 match unif with
864 | None -> (occs, Fail)
865 | Some rew ->
866 let b, occs = update_occurrence_counter occs in
867 if not b then (occs, Fail)
868 else if Termops.eq_constr env (fst rew.rew_evars) t rew.rew_to then (occs, Identity)
869 else
870 let res = { rew with rew_car = ty } in
871 let res = Success (coerce env cstr res) in
872 (occs, res)
873 }
874
875 let with_no_bindings (c : delayed_open_constr) : delayed_open_constr_with_bindings =
876 (); fun env sigma ->
877 let (sigma, c) = c env sigma in
878 (sigma, (c, NoBindings))
879
880 let apply_lemma l2r flags oc by loccs : strategy =
881 let oc = with_no_bindings oc in
882 let strategy ({ state = () ; env ; term1 = t ; evars = (sigma, cstrs) } as input) =
883 let sigma, c = oc env sigma in
884 let sigma, rew = decompose_applied_relation env sigma c in
885 let evars = (sigma, cstrs) in
886 let unify env evars t =
887 let rew = unify_eqn rew l2r flags env evars by t in
888 match rew with
889 | None -> None
890 | Some rew -> Some rew
891 in
892 let loccs, res = (apply_rule unify).strategy {
893 input with
894 state = initialize_occurrence_counter loccs ;
895 evars
896 }
897 in
898 check_used_occurrences loccs;
899 (), res
900
901 in {strategy}
902
903 let e_app_poly env evars f args =
904 let evars', c = app_poly_nocheck env !evars f args in
905 evars := evars';
906 c
907
908 let make_leibniz_proof env c ty r =
909 let evars = ref r.rew_evars in
910 let prf =
911 match r.rew_prf with
912 | RewPrf (rel, prf) ->
913 let rel = e_app_poly env evars rocq_eq [| ty |] in
914 let prf =
915 e_app_poly env evars rocq_f_equal
916 [| r.rew_car; ty;
917 mkLambda (make_annot Anonymous ERelevance.relevant, r.rew_car, c);
918 r.rew_from; r.rew_to; prf |]
919 in RewPrf (rel, prf)
920 | RewCast k -> r.rew_prf
921 in
922 { rew_car = ty; rew_evars = !evars;
923 rew_from = subst1 r.rew_from c; rew_to = subst1 r.rew_to c; rew_prf = prf }
924
925 let fold_match ?(force=false) env sigma c =
926 let case = destCase sigma c in
927 let (ci, (p,_), iv, c, brs) = EConstr.expand_case env sigma case in
928 let cty = Retyping.get_type_of env sigma c in
929 let dep, pred, sk =
930 let env', ctx, body =
931 let ctx, pred = decompose_lambda_decls sigma p in
932 let env' = push_rel_context ctx env in
933 env', ctx, pred
934 in
935 let sortp = Retyping.get_sort_quality_of env' sigma body in
936 let sortc = Retyping.get_sort_quality_of env sigma cty in
937 let dep = not (noccurn sigma 1 body) in
938 let pred = if dep then p else
939 it_mkProd_or_LetIn (subst1 mkProp body) (List.tl ctx)
940 in
941 let sk =
942 (* not sure how correct this is *)
943 if UnivGen.QualityOrSet.is_prop sortp then
944 if UnivGen.QualityOrSet.is_prop sortc then
945 if dep then case_dep
946 else case_nodep
947 else (
948 if dep
949 then casep_dep
950 else case_nodep (* should this be casep_nodep? *))
951 else ((* sortc <> InProp by typing *)
952 if dep
953 then case_dep
954 else case_nodep)
955 in
956 match Ind_tables.lookup_scheme sk ci.ci_ind with
957 | Some (ConstRef cst) -> dep, pred, cst
958 | None | Some _ -> raise Not_found
959 in
960 let app =
961 let sk = if Global.is_polymorphic (ConstRef sk)
962 then CErrors.anomaly Pp.(str "Unexpected univ poly in Rewrite.fold_match")
963 else UnsafeMonomorphic.mkConst sk
964 in
965 let ind, args = Inductiveops.find_mrectype env sigma cty in
966 let pars, args = List.chop ci.ci_npar args in
967 let meths = Array.to_list brs in
968 applist (sk, pars @ [pred] @ meths @ args @ [c])
969 in
970 sk, app
971
972 let unfold_match env sigma sk app =
973 match EConstr.kind sigma app with
974 | App (f', args) when QConstant.equal env (fst (destConst sigma f')) sk ->
975 let v = Environ.constant_value_in env (sk,UVars.Instance.empty)(*FIXME*) in
976 let v = EConstr.of_constr v in
977 Reductionops.whd_beta env sigma (mkApp (v, args))
978 | _ -> app
979
980 let is_rew_cast = function RewCast _ -> true | _ -> false
981
982 let subterm all flags (s : 'a pure_strategy) : 'a pure_strategy =
983 let aux { state ; env ; unfresh ;
984 term1 = t ; ty1 = ty ; cstr = (prop, cstr) ; evars } =
985 let cstr' = Option.map (fun c -> (ty, Some c)) cstr in
986 match EConstr.kind (goalevars evars) t with
987 | App (m, args) ->
988 let rewrite_args state success =
989 let state, (args', evars', progress) =
990 Array.fold_left
991 (fun (state, (acc, evars, progress)) arg ->
992 if not (Option.is_empty progress) && not all then
993 state, (None :: acc, evars, progress)
994 else
995 let evars, argty = get_type_of_refresh env evars arg in
996 let state, res = s.strategy { state ; env ;
997 unfresh ;
998 term1 = arg ; ty1 = argty ;
999 cstr = (prop,None) ;
1000 evars } in
1001 let res' =
1002 match res with
1003 | Identity ->
1004 let progress = if Option.is_empty progress then Some false else progress in
1005 (None :: acc, evars, progress)
1006 | Success r ->
1007 (Some r :: acc, r.rew_evars, Some true)
1008 | Fail -> (None :: acc, evars, progress)
1009 in state, res')
1010 (state, ([], evars, success)) args
1011 in
1012 let res =
1013 match progress with
1014 | None -> Fail
1015 | Some false -> Identity
1016 | Some true ->
1017 let args' = Array.of_list (List.rev args') in
1018 if Array.exists
1019 (function
1020 | None -> false
1021 | Some r -> not (is_rew_cast r.rew_prf)) args'
1022 then
1023 let evars', prf, car, rel, c2 =
1024 resolve_morphism env m args args' (prop, cstr') evars'
1025 in
1026 let res = { rew_car = ty; rew_from = t;
1027 rew_to = c2; rew_prf = RewPrf (rel, prf);
1028 rew_evars = evars' }
1029 in Success res
1030 else
1031 let args' = Array.map2
1032 (fun aorig anew ->
1033 match anew with None -> aorig
1034 | Some r -> r.rew_to) args args'
1035 in
1036 let res = { rew_car = ty; rew_from = t;
1037 rew_to = mkApp (m, args'); rew_prf = RewCast DEFAULTcast;
1038 rew_evars = evars' }
1039 in Success res
1040 in state, res
1041 in
1042 if flags.on_morphisms then
1043 let evars, mty = get_type_of_refresh env evars m in
1044 let evars, cstr', m, mty, argsl, args =
1045 let argsl = Array.to_list args in
1046 let lift = if prop then PropGlobal.lift_cstr else TypeGlobal.lift_cstr in
1047 match lift env evars argsl m mty None with
1048 | Some (evars, cstr', m, mty, args) ->
1049 evars, Some cstr', m, mty, args, Array.of_list args
1050 | None -> evars, None, m, mty, argsl, args
1051 in
1052 let state, m' = s.strategy { state ; env ; unfresh ;
1053 term1 = m ; ty1 = mty ;
1054 cstr = (prop, cstr') ; evars } in
1055 match m' with
1056 | Fail -> rewrite_args state None (* Standard path, try rewrite on arguments *)
1057 | Identity -> rewrite_args state (Some false)
1058 | Success r ->
1059 (* We rewrote the function and get a proof of pointwise rel for the arguments.
1060 We just apply it. *)
1061 let prf = match r.rew_prf with
1062 | RewPrf (rel, prf) ->
1063 let app = if prop then PropGlobal.apply_pointwise
1064 else TypeGlobal.apply_pointwise
1065 in
1066 RewPrf (app env (goalevars evars) rel argsl, mkApp (prf, args))
1067 | x -> x
1068 in
1069 let res =
1070 { rew_car = Reductionops.hnf_prod_appvect env (goalevars evars) r.rew_car args;
1071 rew_from = mkApp(r.rew_from, args); rew_to = mkApp(r.rew_to, args);
1072 rew_prf = prf; rew_evars = r.rew_evars }
1073 in
1074 let res =
1075 match prf with
1076 | RewPrf (rel, prf) ->
1077 Success (apply_constraint env res.rew_car
1078 rel prf (prop,cstr) res)
1079 | _ -> Success res
1080 in state, res
1081 else rewrite_args state None
1082
1083 | Proj (p, r, arg) ->
1084 let expanded = Retyping.expand_projection env (fst evars) p arg [] in
1085 let hd, args = EConstr.destApp (fst evars) expanded in
1086 let arg = Array.last args in
1087 let evars, argty = get_type_of_refresh env evars arg in
1088 let input = {
1089 state; env; unfresh;
1090 term1 = arg; ty1 = argty;
1091 cstr = (prop, None); evars }
1092 in
1093 let state, res = s.strategy input in
1094 let res = match res with
1095 | Fail -> Fail
1096 | Identity -> Identity
1097 | Success res ->
1098 let evars = res.rew_evars in
1099 if is_rew_cast res.rew_prf then
1100 Success { rew_car = ty; rew_from = t;
1101 rew_to = mkProj (p, r, res.rew_to); rew_prf = RewCast DEFAULTcast;
1102 rew_evars = evars }
1103 else
1104 let args' = Array.make (Array.length args) None in
1105 let () = args'.(Array.length args - 1) <- Some res in
1106 let evars, prf, _, rel, c2 =
1107 resolve_morphism env hd args args' (prop, cstr') evars
1108 in
1109 let (_, args) = EConstr.destApp (goalevars evars) c2 in
1110 Success { rew_car = ty; rew_from = t;
1111 rew_to = mkProj (p, r, Array.last args); rew_prf = RewPrf (rel, prf);
1112 rew_evars = evars }
1113 in
1114 state, res
1115
1116 | Prod (n, x, b) when noccurn (goalevars evars) 1 b ->
1117 let b = subst1 mkProp b in
1118 let evars, tx = get_type_of_refresh env evars x in
1119 let evars, tb = get_type_of_refresh env evars b in
1120 let arr = if prop then PropGlobal.arrow_morphism
1121 else TypeGlobal.arrow_morphism
1122 in
1123 let (evars', mor), unfold = arr env evars n.binder_name tx tb x b in
1124 let state, res = s.strategy { state ; env ; unfresh ;
1125 term1 = mor ; ty1 = ty ;
1126 cstr = (prop,cstr) ; evars = evars' } in
1127 let res =
1128 match res with
1129 | Success r -> Success { r with rew_to = unfold (goalevars r.rew_evars) r.rew_to }
1130 | Fail | Identity -> res
1131 in state, res
1132
1133 | Prod (n, dom, codom) ->
1134 let lam = mkLambda (n, dom, codom) in
1135 let (evars', app), unfold =
1136 if eq_constr (fst evars) ty mkProp then
1137 (app_poly_sort prop env evars rocq_all [| dom; lam |]), TypeGlobal.unfold_all
1138 else
1139 let forall = if prop then PropGlobal.rocq_forall else TypeGlobal.rocq_forall in
1140 (app_poly_sort prop env evars forall [| dom; lam |]), TypeGlobal.unfold_forall
1141 in
1142 let state, res = s.strategy { state ; env ; unfresh ;
1143 term1 = app ; ty1 = ty ;
1144 cstr = (prop,cstr) ; evars = evars' } in
1145 let res =
1146 match res with
1147 | Success r -> Success { r with rew_to = unfold (goalevars r.rew_evars) r.rew_to }
1148 | Fail | Identity -> res
1149 in state, res
1150
1151 (* TODO: real rewriting under binders: introduce x x' (H : R x x') and rewrite with
1152 H at any occurrence of x. Ask for (R ==> R') for the lambda. Formalize this.
1153 B. Barras' idea is to have a context of relations, of length 1, with Σ for gluing
1154 dependent relations and using projections to get them out.
1155 *)
1156
1157 | Lambda (n, t, b) when flags.under_lambdas ->
1158 let unfresh, n' =
1159 let id = match n.binder_name with
1160 | Anonymous -> Namegen.default_dependent_ident
1161 | Name id -> id
1162 in
1163 let id = Tactics.fresh_id_in_env unfresh id env in
1164 Id.Set.add id unfresh, {n with binder_name = Name id}
1165 in
1166 let unfresh = match n'.binder_name with
1167 | Anonymous -> unfresh
1168 | Name id -> Id.Set.add id unfresh
1169 in
1170 let open Context.Rel.Declaration in
1171 let env' = EConstr.push_rel (LocalAssum (n', t)) env in
1172 let bty = Retyping.get_type_of env' (goalevars evars) b in
1173 let unlift = if prop then PropGlobal.unlift_cstr else TypeGlobal.unlift_cstr in
1174 let state, b' = s.strategy { state ; env = env' ; unfresh ;
1175 term1 = b ; ty1 = bty ;
1176 cstr = (prop, unlift env evars cstr) ;
1177 evars } in
1178 let res =
1179 match b' with
1180 | Success r ->
1181 let r = match r.rew_prf with
1182 | RewPrf (rel, prf) ->
1183 let point = if prop then PropGlobal.pointwise_or_dep_relation else
1184 TypeGlobal.pointwise_or_dep_relation
1185 in
1186 let evars, rel = point env r.rew_evars n'.binder_name t r.rew_car rel in
1187 let prf = mkLambda (n', t, prf) in
1188 { r with rew_prf = RewPrf (rel, prf); rew_evars = evars }
1189 | x -> r
1190 in
1191 Success { r with
1192 rew_car = mkProd (n, t, r.rew_car);
1193 rew_from = mkLambda(n, t, r.rew_from);
1194 rew_to = mkLambda (n, t, r.rew_to) }
1195 | Fail | Identity -> b'
1196 in state, res
1197
1198 | Case (ci, u, pms, p, iv, c, brs) ->
1199 let (ci, (p,rp), iv, c, brs) = EConstr.expand_case env (goalevars evars) (ci, u, pms, p, iv, c, brs) in
1200 let cty = Retyping.get_type_of env (goalevars evars) c in
1201 let evars', eqty = app_poly_sort prop env evars rocq_eq [| cty |] in
1202 let cstr' = Some eqty in
1203 let state, c' = s.strategy { state ; env ; unfresh ;
1204 term1 = c ; ty1 = cty ;
1205 cstr = (prop, cstr') ; evars = evars' } in
1206 let state, res =
1207 match c' with
1208 | Success r ->
1209 let case = mkCase (EConstr.contract_case env (goalevars evars) (ci, (lift 1 p,rp), map_invert (lift 1) iv, mkRel 1, Array.map (lift 1) brs)) in
1210 let res = make_leibniz_proof env case ty r in
1211 state, Success (coerce env (prop,cstr) res)
1212 | Fail | Identity ->
1213 if Array.for_all (Int.equal 0) ci.ci_cstr_ndecls then
1214 let evars', eqty = app_poly_sort prop env evars rocq_eq [| ty |] in
1215 let cstr = Some eqty in
1216 let state, found, brs' = Array.fold_left
1217 (fun (state, found, acc) br ->
1218 if not (Option.is_empty found) then
1219 (state, found, fun x -> lift 1 br :: acc x)
1220 else
1221 let state, res = s.strategy { state ; env ; unfresh ;
1222 term1 = br ; ty1 = ty ;
1223 cstr = (prop,cstr) ; evars } in
1224 match res with
1225 | Success r -> (state, Some r, fun x -> mkRel 1 :: acc x)
1226 | Fail | Identity -> (state, None, fun x -> lift 1 br :: acc x))
1227 (state, None, fun x -> []) brs
1228 in
1229 match found with
1230 | Some r ->
1231 let ctxc = mkCase (EConstr.contract_case env (goalevars evars) (ci, (lift 1 p, rp), map_invert (lift 1) iv, lift 1 c, Array.of_list (List.rev (brs' c')))) in
1232 state, Success (make_leibniz_proof env ctxc ty r)
1233 | None -> state, c'
1234 else
1235 match try Some (fold_match env (goalevars evars) t) with Not_found -> None with
1236 | None -> state, c'
1237 | Some (cst, t') ->
1238 let state, res = s.strategy { state ; env ; unfresh ;
1239 term1 = t' ; ty1 = ty ;
1240 cstr = (prop,cstr) ; evars } in
1241 let res =
1242 match res with
1243 | Success prf ->
1244 Success { prf with
1245 rew_from = t;
1246 rew_to = unfold_match env (goalevars evars) cst prf.rew_to }
1247 | x' -> c'
1248 in state, res
1249 in
1250 let res =
1251 match res with
1252 | Success r -> Success (coerce env (prop,cstr) r)
1253 | Fail | Identity -> res
1254 in state, res
1255 | _ -> state, Fail
1256 in { strategy = aux }
1257
1258 (** Requires transitivity of the rewrite step, if not a reduction.
1259 Not tail-recursive. *)
1260
1261 let transitivity state env unfresh cstr (res : rewrite_result_info) (next : 'a pure_strategy) :
1262 'a * rewrite_result =
1263 let cstr = match cstr with
1264 | _, Some _ -> cstr
1265 | prop, None -> prop, get_opt_rew_rel res.rew_prf
1266 in
1267 let state, nextres =
1268 next.strategy { state; env; unfresh; cstr;
1269 term1 = res.rew_to;
1270 ty1 = res.rew_car;
1271 evars = res.rew_evars; }
1272 in
1273 let res =
1274 match nextres with
1275 | Fail -> Fail
1276 | Identity -> Success res
1277 | Success res' ->
1278 match res.rew_prf with
1279 | RewCast c -> Success { res' with rew_from = res.rew_from }
1280 | RewPrf (rew_rel, rew_prf) ->
1281 match res'.rew_prf with
1282 | RewCast _ -> Success { res with rew_to = res'.rew_to }
1283 | RewPrf (res'_rel, res'_prf) ->
1284 let trans =
1285 if fst cstr then PropGlobal.transitive_type
1286 else TypeGlobal.transitive_type
1287 in
1288 let evars, prfty =
1289 app_poly_sort (fst cstr) env res'.rew_evars trans [| res.rew_car; rew_rel |]
1290 in
1291 let evars, prf = new_cstr_evar evars env prfty in
1292 let prf = mkApp (prf, [|res.rew_from; res'.rew_from; res'.rew_to;
1293 rew_prf; res'_prf |])
1294 in Success { res' with rew_from = res.rew_from;
1295 rew_evars = evars; rew_prf = RewPrf (res'_rel, prf) }
1296 in state, res
1297
1298 (** Rewriting strategies.
1299
1300 Inspired by ELAN's rewriting strategies:
1301 http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.21.4049
1302 *)
1303
1304 module Strategies =
1305 struct
1306
1307 let fail : 'a pure_strategy =
1308 { strategy = fun { state } -> state, Fail }
1309
1310 let id : 'a pure_strategy =
1311 { strategy = fun { state } -> state, Identity }
1312
1313 let refl : 'a pure_strategy =
1314 { strategy =
1315 fun { state ; env ;
1316 term1 = t ; ty1 = ty ;
1317 cstr = (prop,cstr) ; evars } ->
1318 let evars, rel = match cstr with
1319 | None ->
1320 let mkr = if prop then PropGlobal.mk_relation else TypeGlobal.mk_relation in
1321 let evars, rty = mkr env evars ty in
1322 new_cstr_evar evars env rty
1323 | Some r -> evars, r
1324 in
1325 let evars, proof =
1326 let proxy =
1327 if prop then PropGlobal.proper_proxy_type
1328 else TypeGlobal.proper_proxy_type
1329 in
1330 let evars, mty = app_poly_sort prop env evars proxy [| ty ; rel; t |] in
1331 new_cstr_evar evars env mty
1332 in
1333 let res = Success { rew_car = ty; rew_from = t; rew_to = t;
1334 rew_prf = RewPrf (rel, proof); rew_evars = evars }
1335 in state, res
1336 }
1337
1338 let progress (s : 'a pure_strategy) : 'a pure_strategy = { strategy =
1339 fun input ->
1340 let state, res = s.strategy input in
1341 match res with
1342 | Fail -> state, Fail
1343 | Identity -> state, Fail
1344 | Success r -> state, Success r
1345 }
1346
1347 let seq first snd : 'a pure_strategy = { strategy =
1348 fun ({ env ; unfresh ; cstr } as input) ->
1349 let state, res = first.strategy input in
1350 match res with
1351 | Fail -> state, Fail
1352 | Identity -> snd.strategy { input with state }
1353 | Success res -> transitivity state env unfresh cstr res snd
1354 }
1355
1356 let seqs strs = List.fold_left seq id strs
1357
1358 let choice fst snd : 'a pure_strategy = { strategy =
1359 fun input ->
1360 let state, res = fst.strategy input in
1361 match res with
1362 | Fail -> snd.strategy { input with state }
1363 | Identity | Success _ -> state, res
1364 }
1365
1366 let choices strs = List.fold_left choice fail strs
1367
1368 let try_ str : 'a pure_strategy = choice str id
1369
1370 let check_interrupt str input =
1371 Control.check_for_interrupt ();
1372 str input
1373
1374 let fix (f : 'a pure_strategy -> 'a pure_strategy) : 'a pure_strategy =
1375 let rec aux input = (f { strategy = fun input -> check_interrupt aux input }).strategy input in
1376 { strategy = aux }
1377
1378 let fix_tac (f : 'a pure_strategy -> 'a pure_strategy Proofview.tactic) : 'a pure_strategy Proofview.tactic =
1379 let forward_def =
1380 (* The error below happens if you do
1381 [rewrite_strat (fix (fun s => rewrite_strat s None; s)) None]
1382 *)
1383 let err_msg = Pp.str "Rewrite strategy fixed-point variables cannot be executed by \"rewrite_strat\" inside of fix." in
1384 ref (fun _ -> user_err err_msg)
1385 in
1386 f {strategy = fun input -> check_interrupt !forward_def input} >>= fun f ->
1387 forward_def := f.strategy;
1388 Proofview.tclUNIT f
1389
1390 let all_subterms (s : 'a pure_strategy) : 'a pure_strategy = subterm true default_flags s
1391
1392 let one_subterm (s : 'a pure_strategy) : 'a pure_strategy = subterm false default_flags s
1393
1394 let any (s : 'a pure_strategy) : 'a pure_strategy =
1395 fix (fun any -> try_ (seq s any))
1396
1397 let repeat (s : 'a pure_strategy) : 'a pure_strategy =
1398 seq s (any s)
1399
1400 let bottomup (s : 'a pure_strategy) : 'a pure_strategy =
1401 fix (fun s' -> seq (choice (progress (all_subterms s')) s) (try_ s'))
1402
1403 let topdown (s : 'a pure_strategy) : 'a pure_strategy =
1404 fix (fun s' -> seq (choice s (progress (all_subterms s'))) (try_ s'))
1405
1406 let innermost (s : 'a pure_strategy) : 'a pure_strategy =
1407 fix (fun ins -> choice (one_subterm ins) s)
1408
1409 let outermost (s : 'a pure_strategy) : 'a pure_strategy =
1410 fix (fun out -> choice s (one_subterm out))
1411
1412 let one_lemma c l2r by occs : strategy =
1413 apply_lemma l2r (general_rewrite_unif_flags ()) c by occs
1414
1415 let lemmas cs : strategy =
1416 List.fold_left (fun tac (c, l2r, by) ->
1417 choice tac (apply_lemma l2r rewrite_unif_flags c by AllOccurrences)
1418 ) fail cs
1419
1420 let inj_open hint = (); fun _env sigma ->
1421 let (ctx, lemma) = Autorewrite.RewRule.rew_lemma hint in
1422 let subst, ctx = UnivGen.fresh_sort_context_instance ctx in
1423 let lemma = Vars.subst_univs_level_constr subst (EConstr.of_constr lemma) in
1424 let sigma = Evd.merge_sort_context_set UnivRigid ~src:UState.Internal sigma ctx in
1425 (sigma, lemma)
1426
1427 let old_hints (db : string) : strategy =
1428 let rules = Autorewrite.find_rewrites db in
1429 lemmas
1430 (List.map (fun hint -> (inj_open hint,
1431 Autorewrite.RewRule.rew_l2r hint,
1432 Autorewrite.RewRule.rew_tac hint
1433 )
1434 ) rules)
1435
1436 let hints (db : string) : strategy = { strategy =
1437 fun ({ term1 = t; env } as input) ->
1438 let t = EConstr.Unsafe.to_constr t in
1439 let rules = Autorewrite.find_matches env db t in
1440 let lemma hint = (inj_open hint,
1441 Autorewrite.RewRule.rew_l2r hint,
1442 Autorewrite.RewRule.rew_tac hint
1443 ) in
1444 let lems = List.map lemma rules in
1445 (lemmas lems).strategy input
1446 }
1447
1448 let reduce (r : Redexpr.red_expr) : 'a pure_strategy = { strategy =
1449 fun { state = state ; env = env ; term1 = t ; ty1 = ty ; cstr = cstr ; evars = evars } ->
1450 let rfn, ckind = Redexpr.reduction_of_red_expr env r in
1451 let sigma = goalevars evars in
1452 let (sigma, t') = rfn env sigma t in
1453 if Termops.eq_constr env sigma t' t then
1454 state, Identity
1455 else
1456 state, Success { rew_car = ty; rew_from = t; rew_to = t';
1457 rew_prf = RewCast ckind;
1458 rew_evars = sigma, cstrevars evars }
1459 }
1460
1461 let run_fold_in env evars c term typ : rewrite_result =
1462 let unfolded = match Tacred.red_product env (goalevars evars) c with
1463 | None -> user_err Pp.(str "fold: the term is not unfoldable!")
1464 | Some c -> c
1465 in try
1466 let _, sigma = Unification.w_unify env (goalevars evars) CONV ~flags:(Unification.elim_flags ()) unfolded term in
1467 let c' = Reductionops.nf_evar sigma c in
1468 Success { rew_car = typ; rew_from = term; rew_to = c';
1469 rew_prf = RewCast DEFAULTcast;
1470 rew_evars = (sigma, cstrevars evars) }
1471 with e when CErrors.noncritical e -> Fail
1472
1473 let fold (c : Evd.econstr) : 'a pure_strategy =
1474 { strategy = fun { state ; env ; term1 = t ; ty1 = ty ; cstr ; evars } ->
1475 state, run_fold_in env evars c t ty
1476 }
1477
1478 let fold_glob c : 'a pure_strategy =
1479 { strategy = fun { state ; env ; term1 = t ; ty1 = ty ; cstr ; evars } ->
1480 let sigma, c = Pretyping.understand_tcc env (goalevars evars) c in
1481 state, run_fold_in env (sigma, cstrevars evars) c t ty
1482 }
1483 end
1484
1485 (** The strategy for a single rewrite, dealing with occurrences. *)
1486
1487 (** A dummy initial clauseenv to avoid generating initial evars before
1488 even finding a first application of the rewriting lemma, in setoid_rewrite
1489 mode *)
1490
1491 let rewrite_with l2r flags c occs : strategy = { strategy =
1492 fun ({ state = () } as input) ->
1493 let unify env evars t =
1494 let (sigma, cstrs) = evars in
1495 let sigma, cbl = c env sigma in
1496 let sigma, rew = decompose_applied_relation env sigma cbl in
1497 unify_eqn rew l2r flags env (sigma, cstrs) None t
1498 in
1499 let app = apply_rule unify in
1500 let strat =
1501 Strategies.fix (fun aux ->
1502 Strategies.choice (Strategies.progress app) (subterm true default_flags aux))
1503 in
1504 let occs, res = strat.strategy { input with state = initialize_occurrence_counter occs } in
1505 check_used_occurrences occs;
1506 ((), res)
1507 }
1508
1509 let apply_strategy (s : strategy) env unfresh concl (prop, cstr) evars =
1510 let evars, ty = get_type_of_refresh env evars concl in
1511 let _, res = s.strategy { state = () ; env ; unfresh ;
1512 term1 = concl ; ty1 = ty ;
1513 cstr = (prop, Some cstr) ; evars } in
1514 res
1515
1516 let solve_constraints env (evars,cstrs) =
1517 let oldtcs = Evd.get_typeclass_evars evars in
1518 let evars' = Evd.set_typeclass_evars evars cstrs in
1519 let evars' = TC.resolve_typeclasses env ~filter:TC.all_evars ~fail:true evars' in
1520 Evd.set_typeclass_evars evars' oldtcs
1521
1522 let nf_zeta =
1523 Reductionops.clos_norm_flags (RedFlags.mkflags [RedFlags.fZETA])
1524
1525 exception RewriteFailure of Environ.env * Evd.evar_map * pretype_error
1526
1527 type result = (evar_map * constr option * types) option option
1528
1529 exception UnsolvedConstraints of Environ.env * evar_map * Evar.t
1530
1531 let () = CErrors.register_handler begin function
1532 | UnsolvedConstraints (env, evars, ev) ->
1533 Some (str "Unsolved constraint remaining: " ++ spc () ++
1534 Termops.pr_evar_info env evars (Evd.find_undefined evars ev) ++ str ".")
1535 | _ -> None
1536 end
1537
1538 let cl_rewrite_clause_aux ?(abs=None) strat env avoid sigma concl is_hyp : result =
1539 let sigma, sort = Typing.sort_of env sigma concl in
1540 let evdref = ref sigma in
1541 let evars = (!evdref, Evar.Set.empty) in
1542 let evars, cstr =
1543 let prop, (evars, arrow) =
1544 if ESorts.is_prop sigma sort then true, app_poly_sort true env evars impl [||]
1545 else false, app_poly_sort false env evars TypeGlobal.arrow [||]
1546 in
1547 match is_hyp with
1548 | None ->
1549 let evars, t = poly_inverse prop env evars (mkSort sort) arrow in
1550 evars, (prop, t)
1551 | Some _ -> evars, (prop, arrow)
1552 in
1553 let eq = apply_strategy strat env avoid concl cstr evars in
1554 match eq with
1555 | Fail -> None
1556 | Identity -> Some None
1557 | Success res ->
1558 let (_, cstrs) = res.rew_evars in
1559 let evars = solve_constraints env res.rew_evars in
1560 let iter ev = if not (Evd.is_defined evars ev) then raise (UnsolvedConstraints (env, evars, ev)) in
1561 let () = Evar.Set.iter iter cstrs in
1562 let newt = res.rew_to in
1563 let res = match res.rew_prf with
1564 | RewCast c -> None
1565 | RewPrf (rel, p) ->
1566 let p = nf_zeta env evars p in
1567 let term =
1568 match abs with
1569 | None -> p
1570 | Some (t, ty) ->
1571 mkApp (mkLambda (make_annot (Name (Id.of_string "lemma")) ERelevance.relevant, ty, p), [| t |])
1572 in
1573 let proof = match is_hyp with
1574 | None -> term
1575 | Some id -> mkApp (term, [| mkVar id |])
1576 in
1577 Some proof
1578 in
1579 Some (Some (evars, res, newt))
1580
1581 let assert_replacing id newt tac =
1582 let prf = Tactics.assert_after_replacing id newt in
1583 Proofview.tclTHEN prf (Proofview.tclFOCUS 2 2 tac)
1584
1585 let newfail n s =
1586 let info = Exninfo.reify () in
1587 Proofview.tclZERO ~info (Tacticals.FailError (n, lazy s))
1588
1589 let cl_rewrite_clause_newtac ?abs ?origsigma ~progress strat clause =
1590 let open Proofview.Notations in
1591 (* For compatibility *)
1592 let beta = Tactics.reduct_in_concl ~cast:false ~check:false
1593 (Reductionops.nf_betaiota, DEFAULTcast)
1594 in
1595 let beta_hyp id = Tactics.reduct_in_hyp ~check:false ~reorder:false Reductionops.nf_betaiota (id, InHyp) in
1596 let treat sigma res state =
1597 match res with
1598 | None -> newfail 0 (str "Nothing to rewrite")
1599 | Some None ->
1600 if progress
1601 then newfail 0 (str"Failed to progress")
1602 else Proofview.tclUNIT ()
1603 | Some (Some res) ->
1604 let (undef, prf, newt) = res in
1605 let fold ev _ accu = if Evd.mem sigma ev then accu else ev :: accu in
1606 let gls = List.rev (Evd.fold_undefined fold undef []) in
1607 let gls = List.map (fun gl -> Proofview.goal_with_state gl state) gls in
1608 match clause, prf with
1609 | Some id, Some p ->
1610 let tac = tclTHENLIST [
1611 Refine.refine ~typecheck:true (fun h -> (h,p));
1612 Proofview.Unsafe.tclNEWGOALS gls;
1613 ] in
1614 Proofview.Unsafe.tclEVARS undef <*>
1615 tclTHENFIRST (assert_replacing id newt tac) (beta_hyp id)
1616 | Some id, None ->
1617 Proofview.Unsafe.tclEVARS undef <*>
1618 convert_hyp ~check:false ~reorder:false (LocalAssum (make_annot id ERelevance.relevant, newt)) <*>
1619 beta_hyp id
1620 | None, Some p ->
1621 Proofview.Unsafe.tclEVARS undef <*>
1622 Proofview.Goal.enter begin fun gl ->
1623 let env = Proofview.Goal.env gl in
1624 let make = begin fun sigma ->
1625 let (sigma, ev) = Evarutil.new_evar env sigma newt in
1626 (sigma, mkApp (p, [| ev |]))
1627 end in
1628 Refine.refine ~typecheck:true make <*> Proofview.Unsafe.tclNEWGOALS gls
1629 end
1630 | None, None ->
1631 Proofview.Unsafe.tclEVARS undef <*>
1632 convert_concl ~cast:false ~check:false newt DEFAULTcast
1633 in
1634 Proofview.Goal.enter begin fun gl ->
1635 let concl = Proofview.Goal.concl gl in
1636 let env = Proofview.Goal.env gl in
1637 let state = Proofview.Goal.state gl in
1638 let sigma = Proofview.Goal.sigma gl in
1639 let ty = match clause with
1640 | None -> concl
1641 | Some id -> EConstr.of_constr (Environ.named_type id env)
1642 in
1643 let env = match clause with
1644 | None -> env
1645 | Some id ->
1646 (* Only consider variables not depending on [id] *)
1647 let ctx = named_context env in
1648 let filter decl = not (occur_var_in_decl env sigma id decl) in
1649 let nctx = List.filter filter ctx in
1650 Environ.reset_with_named_context (val_of_named_context nctx) env
1651 in
1652 try
1653 let res =
1654 cl_rewrite_clause_aux ?abs strat env Id.Set.empty sigma ty clause
1655 in
1656 let sigma = match origsigma with None -> sigma | Some sigma -> sigma in
1657 treat sigma res state <*>
1658 (* For compatibility *)
1659 beta <*> Proofview.shelve_unifiable
1660 with
1661 | PretypeError (env, evd, (UnsatisfiableConstraints _ as e)) ->
1662 if do_rewrite_output_constraints () then
1663 let fold ev _ accu = ev :: accu in
1664 let gls = List.rev (Evd.fold_undefined fold evd []) in
1665 let gls = List.map (fun gl -> Proofview.goal_with_state gl state) gls in
1666 Proofview.Unsafe.tclEVARS evd <*> Proofview.Unsafe.tclNEWGOALS gls
1667 else raise (RewriteFailure (env, evd, e))
1668 end
1669
1670 let tactic_init_rewrite () =
1671 try init_rewrite (); Proofview.tclUNIT ()
1672 with e when CErrors.noncritical e ->
1673 let _, info = Exninfo.capture e in
1674 Tacticals.tclFAIL ~info (str"Setoid library not loaded")
1675
1676 let cl_rewrite_clause_strat progress strat clause =
1677 tactic_init_rewrite () <*>
1678 (if progress then Proofview.tclPROGRESS else fun x -> x)
1679 (Proofview.tclOR
1680 (cl_rewrite_clause_newtac ~progress strat clause)
1681 (fun (e, info) -> match e with
1682 | Tacticals.FailError (n, pp) ->
1683 tclFAILn ~info n (str"setoid rewrite failed: " ++ Lazy.force pp)
1684 | e ->
1685 Proofview.tclZERO ~info e))
1686
1687 (** Setoid rewriting when called with "setoid_rewrite" *)
1688 let cl_rewrite_clause l left2right occs clause =
1689 let strat = rewrite_with left2right (general_rewrite_unif_flags ()) l occs in
1690 cl_rewrite_clause_strat true strat clause
1691
1692 (** Setoid rewriting when called with "rewrite_strat" *)
1693 let cl_rewrite_clause_strat strat clause =
1694 cl_rewrite_clause_strat false strat clause
1695
1696 (* Syntax for rewriting with strategies *)
1697
1698 type unary_strategy =
1699 Subterms | Subterm | Innermost | Outermost
1700 | Bottomup | Topdown | Progress | Try | Any | Repeat
1701
1702 type binary_strategy =
1703 | Compose
1704
1705 type nary_strategy = Choice
1706
1707 type ('constr,'redexpr,'id) strategy_ast =
1708 | StratId | StratFail | StratRefl
1709 | StratUnary of unary_strategy * ('constr,'redexpr,'id) strategy_ast
1710 | StratBinary of
1711 binary_strategy * ('constr,'redexpr,'id) strategy_ast * ('constr,'redexpr,'id) strategy_ast
1712 | StratNAry of nary_strategy * ('constr,'redexpr,'id) strategy_ast list
1713 | StratConstr of 'constr * bool
1714 | StratTerms of 'constr list
1715 | StratHints of bool * string
1716 | StratEval of 'redexpr
1717 | StratFold of 'constr
1718 | StratVar of 'id
1719 | StratFix of 'id * ('constr,'redexpr,'id) strategy_ast
1720
1721 let rec map_strategy f g h = function
1722 | StratId | StratFail | StratRefl as s -> s
1723 | StratUnary (s, str) -> StratUnary (s, map_strategy f g h str)
1724 | StratBinary (s, str, str') -> StratBinary (s, map_strategy f g h str, map_strategy f g h str')
1725 | StratNAry (s, strs) -> StratNAry (s, List.map (map_strategy f g h) strs)
1726 | StratConstr (c, b) -> StratConstr (f c, b)
1727 | StratTerms l -> StratTerms (List.map f l)
1728 | StratHints (b, id) -> StratHints (b, id)
1729 | StratEval r -> StratEval (g r)
1730 | StratFold c -> StratFold (f c)
1731 | StratVar id -> StratVar (h id)
1732 | StratFix (id, s) -> StratFix (h id, map_strategy f g h s)
1733
1734 let pr_ustrategy = function
1735 | Subterms -> str "subterms"
1736 | Subterm -> str "subterm"
1737 | Innermost -> str "innermost"
1738 | Outermost -> str "outermost"
1739 | Bottomup -> str "bottomup"
1740 | Topdown -> str "topdown"
1741 | Progress -> str "progress"
1742 | Try -> str "try"
1743 | Any -> str "any"
1744 | Repeat -> str "repeat"
1745
1746 let paren p = str "(" ++ p ++ str ")"
1747
1748 let rec pr_strategy0 prc prr prid = function
1749 | StratId -> str "id"
1750 | StratFail -> str "fail"
1751 | StratRefl -> str "refl"
1752 | str -> paren (pr_strategy prc prr prid str)
1753
1754 and pr_strategy1 prc prr prid = function
1755 | StratUnary (s, str) ->
1756 pr_ustrategy s ++ spc () ++ pr_strategy1 prc prr prid str
1757 | StratNAry (Choice, strs) ->
1758 str "choice" ++ brk (1,2) ++ prlist_with_sep spc (fun str -> hov 0 (pr_strategy0 prc prr prid str)) strs
1759 | StratConstr (c, true) -> prc c
1760 | StratConstr (c, false) -> str "<-" ++ spc () ++ prc c
1761 | StratVar id -> prid id
1762 | StratTerms cl -> str "terms" ++ spc () ++ pr_sequence prc cl
1763 | StratHints (old, id) ->
1764 let cmd = if old then "old_hints" else "hints" in
1765 str cmd ++ spc () ++ str id
1766 | StratEval r -> str "eval" ++ spc () ++ prr r
1767 | StratFold c -> str "fold" ++ spc () ++ prc c
1768 | str -> pr_strategy0 prc prr prid str
1769
1770 and pr_strategy2 prc prr prid = function
1771 | StratBinary (Compose, str1, str2) ->
1772 pr_strategy2 prc prr prid str1 ++ str ";" ++ spc () ++ hov 0 (pr_strategy1 prc prr prid str2)
1773 | str -> hov 0 (pr_strategy1 prc prr prid str)
1774
1775 and pr_strategy prc prr prid = function
1776 | StratFix (id,s) -> str "fix" ++ spc() ++ prid id ++ spc() ++ str ":=" ++ spc() ++ hov 0 (pr_strategy1 prc prr prid s)
1777 | str -> pr_strategy2 prc prr prid str
1778
1779 let rec strategy_of_ast bindings = function
1780 | StratId -> Strategies.id
1781 | StratFail -> Strategies.fail
1782 | StratRefl -> Strategies.refl
1783 | StratUnary (f, s) ->
1784 let s' = strategy_of_ast bindings s in
1785 let f' = match f with
1786 | Subterms -> Strategies.all_subterms
1787 | Subterm -> Strategies.one_subterm
1788 | Innermost -> Strategies.innermost
1789 | Outermost -> Strategies.outermost
1790 | Bottomup -> Strategies.bottomup
1791 | Topdown -> Strategies.topdown
1792 | Progress -> Strategies.progress
1793 | Try -> Strategies.try_
1794 | Any -> Strategies.any
1795 | Repeat -> Strategies.repeat
1796 in f' s'
1797 | StratBinary (f, s, t) ->
1798 let s' = strategy_of_ast bindings s in
1799 let t' = strategy_of_ast bindings t in
1800 let f' = match f with
1801 | Compose -> Strategies.seq
1802 in f' s' t'
1803 | StratNAry (Choice, strs) ->
1804 let strs = List.map (strategy_of_ast bindings) strs in
1805 begin match strs with
1806 | [] -> assert false
1807 | s::strs -> List.fold_left Strategies.choice s strs
1808 end
1809 | StratConstr ((_, c), b) -> Strategies.one_lemma c b None AllOccurrences
1810 | StratHints (old, id) -> if old then Strategies.old_hints id else Strategies.hints id
1811 | StratTerms l -> Strategies.lemmas (List.map (fun (_, c) -> (c, true, None)) l)
1812 | StratEval r -> { strategy =
1813 (fun ({ state = () ; env ; evars } as input) ->
1814 let (sigma, r_interp) = r env (goalevars evars) in
1815 (Strategies.reduce r_interp).strategy { input with
1816 evars = (sigma,cstrevars evars) }) }
1817 | StratFold c -> Strategies.fold_glob (fst c)
1818
1819 | StratVar id -> Id.Map.get id bindings
1820
1821 | StratFix (id, s) -> Strategies.fix (fun self -> strategy_of_ast (Id.Map.add id self bindings) s)
1822
1823 let strategy_of_ast s = strategy_of_ast Id.Map.empty s
1824
1825 let proper_projection env sigma r ty =
1826 let rel_vect n m = Array.init m (fun i -> mkRel(n+m-i)) in
1827 let ctx, inst = decompose_prod_decls sigma ty in
1828 let mor, args = destApp sigma inst in
1829 let instarg = mkApp (r, rel_vect 0 (List.length ctx)) in
1830 let sigma, proj = Evd.fresh_global env sigma (PropGlobal.proper_proj ()) in
1831 let app = mkApp (proj,
1832 Array.append args [| instarg |]) in
1833 sigma, it_mkLambda_or_LetIn app ctx
1834
1835 let build_morphism_signature env sigma m =
1836 let m,ctx = Constrintern.interp_constr env sigma m in
1837 let sigma = Evd.from_ctx ctx in
1838 let t = Retyping.get_type_of env sigma m in
1839 let cstrs =
1840 let rec aux t =
1841 match EConstr.kind sigma t with
1842 | Prod (na, a, b) ->
1843 None :: aux b
1844 | _ -> []
1845 in aux t
1846 in
1847 let evars, t', sig_, cstrs =
1848 PropGlobal.build_signature (sigma, Evar.Set.empty) env t cstrs None in
1849 let evd = ref evars in
1850 let _ = List.iter
1851 (fun (ty, rel) ->
1852 Option.iter (fun rel ->
1853 let default = e_app_poly env evd default_relation [| ty; rel |] in
1854 let evd', t = new_cstr_evar !evd env default in
1855 evd := evd')
1856 rel)
1857 cstrs
1858 in
1859 let morph = e_app_poly env evd PropGlobal.proper_type [| t; sig_; m |] in
1860 let evd = solve_constraints env !evd in
1861 evd, morph
1862
1863 let default_morphism env sigma sign m =
1864 let t = Retyping.get_type_of env sigma m in
1865 let sigma, _, sign, cstrs =
1866 PropGlobal.build_signature (sigma, Evar.Set.empty) env t (fst sign) (snd sign)
1867 in
1868 let sigma, morph = app_poly_check env sigma PropGlobal.proper_type [| t; sign; m |] in
1869 let sigma, mor = Class_tactics.resolve_one_typeclass env (goalevars sigma) morph in
1870 let sigma, proj = proper_projection env sigma mor morph in
1871 sigma, mor, proj
1872
1873 (** Bind to "rewrite" too *)
1874
1875 (* Find a subterm which matches the pattern to rewrite for "rewrite" *)
1876 let unification_rewrite l2r c1 c2 sigma prf car rel but env =
1877 let ((_, sigma), c') =
1878 try
1879 (* ~flags:(false,true) to allow to mark occurrences that must not be
1880 rewritten simply by replacing them with let-defined definitions
1881 in the context *)
1882 Unification.w_unify_to_subterm
1883 ~flags:rewrite_unif_flags
1884 env sigma ((if l2r then c1 else c2),but)
1885 with
1886 | ex when Pretype_errors.precatchable_exception ex ->
1887 (* ~flags:(true,true) to make Ring work (since it really
1888 exploits conversion) *)
1889 Unification.w_unify_to_subterm
1890 ~flags:rewrite_conv_unif_flags
1891 env sigma ((if l2r then c1 else c2),but)
1892 in
1893 let nf c = Reductionops.nf_evar sigma c in
1894 let c1 = if l2r then nf c' else nf c1
1895 and c2 = if l2r then nf c2 else nf c'
1896 and car = nf car and rel = nf rel in
1897 let prf = nf prf in
1898 let prfty = nf (Retyping.get_type_of env sigma prf) in
1899 let sort = sort_of_rel env sigma but in
1900 let abs = prf, prfty in
1901 let prf = mkRel 1 in
1902 let res = (car, rel, prf, c1, c2) in
1903 abs, sigma, res, Sorts.is_prop sort
1904
1905 let get_hyp gl (c,l) clause l2r =
1906 let env = Proofview.Goal.env gl in
1907 let sigma = Proofview.Goal.sigma gl in
1908 let concl = Proofview.Goal.concl gl in
1909 let sigma, hi = decompose_applied_relation env sigma (c, l) in
1910 let but = match clause with
1911 | Some id -> Tacmach.pf_get_hyp_typ id gl
1912 | None -> Reductionops.nf_evar sigma concl
1913 in
1914 unification_rewrite l2r hi.c1 hi.c2 sigma hi.prf hi.car hi.rel but env
1915
1916 let general_rewrite_flags = { under_lambdas = false; on_morphisms = true }
1917
1918 (** Setoid rewriting when called with "rewrite" *)
1919 let general_s_rewrite cl l2r occs (c,l) ~new_goals =
1920 Proofview.Goal.enter begin fun gl ->
1921 let abs, evd, res, sort = get_hyp gl (c,l) cl l2r in
1922 let unify env evars t = unify_abs res l2r sort env evars t in
1923 let app = apply_rule unify in
1924 let recstrat aux = Strategies.choice app (subterm true general_rewrite_flags aux) in
1925 let substrat = Strategies.fix recstrat in
1926 let strat = { strategy = fun ({ state = () } as input) ->
1927 let occs, res = substrat.strategy { input with state = initialize_occurrence_counter occs } in
1928 check_used_occurrences occs;
1929 (), res
1930 }
1931 in
1932 let origsigma = Proofview.Goal.sigma gl in
1933 tactic_init_rewrite () <*>
1934 Proofview.tclOR
1935 (tclPROGRESS
1936 (tclTHEN
1937 (Proofview.Unsafe.tclEVARS evd)
1938 (cl_rewrite_clause_newtac ~progress:true ~abs:(Some abs) ~origsigma strat cl)))
1939 (fun (e, info) -> match e with
1940 | e -> Proofview.tclZERO ~info e)
1941 end
1942
1943 let _ = Hook.set Equality.general_setoid_rewrite_clause general_s_rewrite
1944
1945 (** [setoid_]{reflexivity,symmetry,transitivity} tactics *)
1946
1947 exception RelationNotDeclared of Environ.env * Evd.evar_map * string * EConstr.types
1948
1949 let () = CErrors.register_handler begin function
1950 | RelationNotDeclared (env, sigma, ty, concl) ->
1951 let rel, _, _, _, _, _ = decompose_app_rel_error env sigma concl in
1952 Some (str" The relation " ++ Printer.pr_econstr_env env sigma rel ++ str" is not a declared " ++
1953 str ty ++ str" relation. Maybe you need to require the Corelib.Classes.RelationClasses library")
1954 | _ -> None
1955 end
1956
1957 let not_declared ~info env sigma ty concl =
1958 Proofview.tclZERO ~info (RelationNotDeclared (env, sigma, ty, concl))
1959
1960 let setoid_proof ty fn fallback =
1961 Proofview.Goal.enter begin fun gl ->
1962 let env = Proofview.Goal.env gl in
1963 let sigma = Proofview.Goal.sigma gl in
1964 let concl = Proofview.Goal.concl gl in
1965 Proofview.tclORELSE
1966 begin
1967 try
1968 let rel, ty1, ty2, concl, _, _ = decompose_app_rel_error env sigma concl in
1969 let (sigma, t) = Typing.type_of env sigma rel in
1970 let car = snd (List.hd (fst (Reductionops.whd_decompose_prod env sigma t))) in
1971 (try init_relation_classes () with e when CErrors.noncritical e -> raise Not_found);
1972 fn env sigma car rel
1973 with e when CErrors.noncritical e ->
1974 (* XXX what is the right test here as to whether e can be converted ? *)
1975 let e, info = Exninfo.capture e in
1976 Proofview.tclZERO ~info e
1977 end
1978 begin function
1979 | e ->
1980 Proofview.tclORELSE
1981 fallback
1982 begin function (e', info) -> match e' with
1983 | Hipattern.NoEquationFound ->
1984 begin match e with
1985 | (Not_found, _) -> not_declared ~info env sigma ty concl
1986 | (e, info) ->
1987 Proofview.tclZERO ~info e
1988 end
1989 | e' -> Proofview.tclZERO ~info e'
1990 end
1991 end
1992 end
1993
1994 let tac_open ((evm,_), c) tac =
1995 (tclTHEN (Proofview.Unsafe.tclEVARS evm) (tac c))
1996
1997 let poly_proof getp gett env evm car rel =
1998 if Sorts.is_prop (sort_of_rel env evm rel) then
1999 getp env (evm,Evar.Set.empty) car rel
2000 else gett env (evm,Evar.Set.empty) car rel
2001
2002 let setoid_reflexivity =
2003 setoid_proof "reflexive"
2004 (fun env evm car rel ->
2005 tac_open (poly_proof PropGlobal.get_reflexive_proof
2006 TypeGlobal.get_reflexive_proof
2007 env evm car rel)
2008 (fun c -> tclCOMPLETE (apply c)))
2009 (reflexivity_red true)
2010
2011 let setoid_symmetry =
2012 setoid_proof "symmetric"
2013 (fun env evm car rel ->
2014 tac_open
2015 (poly_proof PropGlobal.get_symmetric_proof TypeGlobal.get_symmetric_proof
2016 env evm car rel)
2017 (fun c -> apply c))
2018 (symmetry_red true)
2019
2020 let setoid_transitivity c =
2021 setoid_proof "transitive"
2022 (fun env evm car rel ->
2023 tac_open (poly_proof PropGlobal.get_transitive_proof TypeGlobal.get_transitive_proof
2024 env evm car rel)
2025 (fun proof -> match c with
2026 | None -> eapply proof
2027 | Some c -> apply_with_bindings (proof,ImplicitBindings [ c ])))
2028 (transitivity_red true c)
2029
2030 let setoid_symmetry_in id =
2031 Proofview.Goal.enter begin fun gl ->
2032 let env = Proofview.Goal.env gl in
2033 let sigma = Proofview.Goal.sigma gl in
2034 let ctype = Retyping.get_type_of env sigma (mkVar id) in
2035 let binders,concl = decompose_prod_decls sigma ctype in
2036 let (equiv, args) = decompose_app_list sigma concl in
2037 let rec split_last_two = function
2038 | [c1;c2] -> [],(c1, c2)
2039 | x::y::z -> let l,res = split_last_two (y::z) in x::l, res
2040 | _ -> user_err Pp.(str "Cannot find an equivalence relation to rewrite.")
2041 in
2042 let others,(c1,c2) = split_last_two args in
2043 let he,c1,c2 = mkApp (equiv, Array.of_list others),c1,c2 in
2044 let new_hyp' = mkApp (he, [| c2 ; c1 |]) in
2045 let new_hyp = it_mkProd_or_LetIn new_hyp' binders in
2046 (tclTHENLAST
2047 (Tactics.assert_after_replacing id new_hyp)
2048 (tclTHENLIST [ intros; setoid_symmetry; apply (mkVar id); Tactics.assumption ]))
2049 end
2050
2051 let _ = Hook.set Tactics.setoid_reflexivity setoid_reflexivity
2052 let _ = Hook.set Tactics.setoid_symmetry setoid_symmetry
2053 let _ = Hook.set Tactics.setoid_symmetry_in setoid_symmetry_in
2054 let _ = Hook.set Tactics.setoid_transitivity setoid_transitivity
2055
2056 let get_lemma_proof f env evm x y =
2057 let (evm, _), c = f env (evm,Evar.Set.empty) x y in
2058 evm, c
2059
2060 let get_reflexive_proof =
2061 get_lemma_proof PropGlobal.get_reflexive_proof
2062
2063 let get_symmetric_proof =
2064 get_lemma_proof PropGlobal.get_symmetric_proof
2065
2066 let get_transitive_proof =
2067 get_lemma_proof PropGlobal.get_transitive_proof
2068
2069 module Internal =
2070 struct
2071
2072 let build_signature env sigma m cstr finalcstr =
2073 let evars = (sigma, Evar.Set.empty) in
2074 let ((sigma, _), _, sig_, cstr) = PropGlobal.build_signature evars env m cstr finalcstr in
2075 sigma, sig_, cstr
2076
2077 let build_morphism_signature = build_morphism_signature
2078
2079 let default_morphism = default_morphism
2080
2081 end