Debian Codegraph @

plugins/funind/gen_principle.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 Util
12 open Names
13 open Indfun_common
14 module RelDecl = Context.Rel.Declaration
15 module ERelevance = EConstr.ERelevance
16
17 let observe_tac s =
18 observe_tac ~header:(Pp.str "observation") (fun _ _ -> Pp.str s)
19
20 (*
21 Construct a fixpoint as a Glob_term
22 and not as a constr
23 *)
24 let rec abstract_glob_constr c = function
25 | [] -> c
26 | Constrexpr.CLocalDef (x, _, b, t) :: bl ->
27 Constrexpr_ops.mkLetInC (x, b, t, abstract_glob_constr c bl)
28 | Constrexpr.CLocalAssum (idl, _, k, t) :: bl ->
29 List.fold_right
30 (fun x b -> Constrexpr_ops.mkLambdaC ([x], k, t, b))
31 idl
32 (abstract_glob_constr c bl)
33 | Constrexpr.CLocalPattern _ :: bl -> assert false
34
35 let interp_casted_constr_with_implicits env sigma impls c =
36 Constrintern.intern_gen Pretyping.WithoutTypeConstraint env sigma ~impls c
37
38 let build_newrecursive lnameargsardef =
39 let env0 = Global.env () in
40 let sigma = Evd.from_env env0 in
41 let rec_sign, rec_impls =
42 List.fold_left
43 (fun (env, impls) {Vernacexpr.fname = {CAst.v = recname}; binders; rtype} ->
44 let arityc = Constrexpr_ops.mkCProdN binders rtype in
45 let arity, _ctx = Constrintern.interp_type env0 sigma arityc in
46 let evd = Evd.from_env env0 in
47 let evd, (_, (_, impls', _locs)) =
48 Constrintern.interp_context_evars ~program_mode:false env evd binders
49 in
50 let impl =
51 Constrintern.compute_internalization_data env0 evd recname
52 Constrintern.Recursive arity impls'
53 in
54 let open Context.Named.Declaration in
55 let r = ERelevance.relevant in
56 (* TODO relevance *)
57 ( EConstr.push_named
58 (LocalAssum (Context.make_annot recname r, arity))
59 env
60 , Id.Map.add recname impl impls ))
61 (env0, Constrintern.empty_internalization_env)
62 lnameargsardef
63 in
64 let recdef =
65 (* Declare local notations *)
66 let f {Vernacexpr.binders; body_def} =
67 match body_def with
68 | Some body_def ->
69 let def = abstract_glob_constr body_def binders in
70 interp_casted_constr_with_implicits rec_sign sigma rec_impls def
71 | None ->
72 CErrors.user_err
73 (Pp.str "Body of Function must be given.")
74 in
75 Vernacstate.System.protect (List.map f) lnameargsardef
76 in
77 (recdef, rec_impls)
78
79 (* Checks whether or not the mutual bloc is recursive *)
80 let is_rec names =
81 let open Glob_term in
82 let names = List.fold_right Id.Set.add names Id.Set.empty in
83 let check_id id names = Id.Set.mem id names in
84 let rec lookup names gt =
85 match DAst.get gt with
86 | GVar id -> check_id id names
87 | GRef _ | GEvar _ | GPatVar _ | GSort _ | GHole _ | GGenarg _
88 | GInt _ | GFloat _ | GString _ ->
89 false
90 | GCast (b, _, _) -> lookup names b
91 | GRec _ -> CErrors.user_err (Pp.str "GRec not handled")
92 | GIf (b, _, lhs, rhs) ->
93 lookup names b || lookup names lhs || lookup names rhs
94 | GProd (na, _, _, t, b) | GLambda (na, _, _, t, b) ->
95 lookup names t
96 || lookup (Nameops.Name.fold_right Id.Set.remove na names) b
97 | GLetIn (na, _, b, t, c) ->
98 lookup names b
99 || Option.cata (lookup names) true t
100 || lookup (Nameops.Name.fold_right Id.Set.remove na names) c
101 | GLetTuple (nal, _, t, b) ->
102 lookup names t
103 || lookup
104 (List.fold_left
105 (fun acc na -> Nameops.Name.fold_right Id.Set.remove na acc)
106 names nal)
107 b
108 | GApp (c, args) | GProj (_, args, c) -> List.exists (lookup names) (c :: args)
109 | GArray (_u, t, def, ty) ->
110 Array.exists (lookup names) t || lookup names def || lookup names ty
111 | GCases (_, _, el, brl) ->
112 List.exists (fun (e, _) -> lookup names e) el
113 || List.exists (lookup_br names) brl
114 and lookup_br names {CAst.v = idl, _, rt} =
115 let new_names = List.fold_right Id.Set.remove idl names in
116 lookup new_names rt
117 in
118 lookup names
119
120 let rec rebuild_bl aux bl typ =
121 let open Constrexpr in
122 match (bl, typ) with
123 | [], _ -> (List.rev aux, typ)
124 | CLocalAssum (nal, _, bk, _) :: bl', typ -> rebuild_nal aux bk bl' nal typ
125 | CLocalDef (na, _, _, _) :: bl', {CAst.v = CLetIn (_, nat, ty, typ')} ->
126 rebuild_bl (Constrexpr.CLocalDef (na, None, nat, ty) :: aux) bl' typ'
127 | _ -> assert false
128
129 and rebuild_nal aux bk bl' nal typ =
130 let open Constrexpr in
131 match (nal, typ) with
132 | _, {CAst.v = CProdN ([], typ)} -> rebuild_nal aux bk bl' nal typ
133 | [], _ -> rebuild_bl aux bl' typ
134 | ( na :: nal
135 , {CAst.v = CProdN (CLocalAssum (na' :: nal', _, bk', nal't) :: rest, typ')} )
136 ->
137 if Name.equal na.CAst.v na'.CAst.v || Name.is_anonymous na'.CAst.v then
138 let assum = CLocalAssum ([na], None, bk, nal't) in
139 let new_rest =
140 if nal' = [] then rest else CLocalAssum (nal', None, bk', nal't) :: rest
141 in
142 rebuild_nal (assum :: aux) bk bl' nal
143 (CAst.make @@ CProdN (new_rest, typ'))
144 else
145 let assum = CLocalAssum ([na'], None, bk, nal't) in
146 let new_rest =
147 if nal' = [] then rest else CLocalAssum (nal', None, bk', nal't) :: rest
148 in
149 rebuild_nal (assum :: aux) bk bl' (na :: nal)
150 (CAst.make @@ CProdN (new_rest, typ'))
151 | _ -> assert false
152
153 let rebuild_bl aux bl typ = rebuild_bl aux bl typ
154
155 let recompute_binder_list (rec_order, fixpoint_exprl) =
156 let typel, sigma = ComFixpoint.interp_fixpoint_short rec_order fixpoint_exprl in
157 let constr_expr_typel =
158 let flags = full_printing_flags() in
159 (List.map (fun c ->
160 Constrextern.extern_constr ~flags (Global.env ()) sigma
161 (EConstr.of_constr c)))
162 typel
163 in
164 let fixpoint_exprl_with_new_bl =
165 List.map2
166 (fun ({Vernacexpr.binders} as fp) fix_typ ->
167 let binders, rtype = rebuild_bl [] binders fix_typ in
168 {fp with Vernacexpr.binders; rtype})
169 fixpoint_exprl constr_expr_typel
170 in
171 fixpoint_exprl_with_new_bl
172
173 let rec local_binders_length = function
174 (* Assume that no `{ ... } contexts occur *)
175 | [] -> 0
176 | Constrexpr.CLocalDef _ :: bl -> 1 + local_binders_length bl
177 | Constrexpr.CLocalAssum (idl, _, _, _) :: bl ->
178 List.length idl + local_binders_length bl
179 | Constrexpr.CLocalPattern _ :: bl -> assert false
180
181 let prepare_body {Vernacexpr.binders} rt =
182 let n = local_binders_length binders in
183 (* Pp.msgnl (str "nb lambda to chop : " ++ str (string_of_int n) ++ fnl () ++Printer.pr_glob_constr rt); *)
184 let fun_args, rt' = chop_rlambda_n n rt in
185 (fun_args, rt')
186
187 let build_functional_principle env (sigma : Evd.evar_map) old_princ_type sorts funs
188 _i proof_tac hook =
189 (* First we get the type of the old graph principle *)
190 let mutr_nparams =
191 (Induction.compute_elim_sig sigma (EConstr.of_constr old_princ_type))
192 .Induction.nparams
193 in
194 let funs = Array.map EConstr.mkConstU funs in
195 let new_principle_type =
196 Functional_principles_types.compute_new_princ_type_from_rel (Global.env ())
197 (Array.map (EConstr.to_constr sigma) funs)
198 (Array.map (fun s -> EConstr.ESorts.kind sigma s) sorts) old_princ_type
199 in
200 let sigma, _ =
201 Typing.type_of ~refresh:true env sigma
202 (EConstr.of_constr new_principle_type)
203 in
204 let ftac = proof_tac funs mutr_nparams in
205 let uctx = Evd.ustate sigma in
206 let typ = EConstr.of_constr new_principle_type in
207 let body, typ, univs, _safe, _uctx =
208 Subproof.build_by_tactic env ~uctx ~poly:PolyFlags.default ~typ ftac
209 in
210 (* uctx was ignored before *)
211 let hook = Declare.Hook.make (hook new_principle_type) in
212 (body, typ, univs, hook, sigma)
213
214 let change_property_sort evd toSort princ princName =
215 let open Context.Rel.Declaration in
216 let toSort = EConstr.ESorts.kind evd toSort in
217 let princ = EConstr.of_constr princ in
218 let princ_info = Induction.compute_elim_sig evd princ in
219 let change_sort_in_predicate evd decl =
220 let args, ty =
221 Term.decompose_prod (EConstr.Unsafe.to_constr (get_type decl))
222 in
223 let s = Constr.destSort ty in
224 let evd = Evd.set_leq_sort evd (EConstr.ESorts.make toSort) (EConstr.ESorts.make s) in
225 let ty = Term.compose_prod args (Constr.mkSort toSort) in
226 evd, LocalAssum (EConstr.Unsafe.to_binder_annot @@ get_annot decl, ty)
227 in
228 let evd, princName_as_constr =
229 Evd.fresh_global (Global.env ()) evd
230 (Option.get (Constrintern.locate_reference (Libnames.qualid_of_ident princName)))
231 in
232 let init =
233 let nargs =
234 princ_info.Induction.nparams + List.length princ_info.Induction.predicates
235 in
236 Constr.mkApp
237 ( EConstr.Unsafe.to_constr princName_as_constr
238 , Array.init nargs (fun i -> Constr.mkRel (nargs - i)) )
239 in
240 let evd, predicates =
241 List.fold_left_map change_sort_in_predicate evd princ_info.Induction.predicates
242 in
243 ( evd
244 , Term.it_mkLambda_or_LetIn
245 (Term.it_mkLambda_or_LetIn init predicates)
246 (EConstr.Unsafe.to_rel_context princ_info.Induction.params) )
247
248 let generate_functional_principle (evd : Evd.evar_map ref) old_princ_type sorts
249 new_princ_name funs i proof_tac =
250 try
251 let f = funs.(i) in
252 let sigma, type_sort = Evd.fresh_sort_in_quality !evd UnivGen.QualityOrSet.qtype in
253 evd := sigma;
254 let new_sorts =
255 match sorts with
256 | None -> Array.make (Array.length funs) type_sort
257 | Some a -> a
258 in
259 let base_new_princ_name, new_princ_name, loc =
260 match new_princ_name with
261 | Some {CAst.v=id; loc} -> (id, id, loc)
262 | None ->
263 let id_of_f = Constant.label (fst f) in
264 (id_of_f, Elimschemes.make_elimination_ident id_of_f (EConstr.ESorts.quality_or_set !evd type_sort), None)
265 in
266 let names = ref [new_princ_name] in
267 let hook new_principle_type _ =
268 if Option.is_empty sorts then (
269 (* let id_of_f = Label.to_id (con_label f) in *)
270 let register_with_sort sort =
271 let evd' = Evd.from_env (Global.env ()) in
272 let evd', s = Evd.fresh_sort_in_quality evd' sort in
273 let name =
274 Elimschemes.make_elimination_ident base_new_princ_name sort
275 in
276 let evd', value =
277 change_property_sort evd' s new_principle_type new_princ_name
278 in
279 let evd' =
280 fst
281 (Typing.type_of ~refresh:true (Global.env ()) evd'
282 (EConstr.of_constr value))
283 in
284 (* Pp.msgnl (str "new principle := " ++ pr_lconstr value); *)
285 let univs = Evd.univ_entry ~poly:PolyFlags.default evd' in
286 let ce = Declare.definition_entry ~univs value in
287 ignore
288 (Declare.declare_constant ?loc ~name
289 ~kind:Decls.(IsDefinition Scheme)
290 (Declare.DefinitionEntry ce));
291 Declare.definition_message name;
292 names := name :: !names
293 in
294 register_with_sort UnivGen.QualityOrSet.prop;
295 register_with_sort UnivGen.QualityOrSet.set )
296 in
297 let body, types, univs, hook, sigma0 =
298 build_functional_principle (Global.env ()) !evd old_princ_type new_sorts funs i proof_tac
299 hook
300 in
301 evd := sigma0;
302 (* Pr 1278 :
303 Don't forget to close the goal if an error is raised !!!!
304 *)
305 let uctx = Evd.ustate sigma in
306 let entry = Declare.definition_entry ~univs ~types body in
307 let (_ : Names.GlobRef.t) =
308 Declare.declare_entry ~name:new_princ_name ~hook
309 ~kind:Decls.(IsProof Theorem)
310 ~impargs:[] ~uctx entry
311 in
312 ()
313 with e when CErrors.noncritical e -> raise (Defining_principle e)
314
315 let generate_principle (evd : Evd.evar_map ref) pconstants on_error is_general
316 do_built fix_rec_l recdefs
317 (continue_proof :
318 int
319 -> Names.Constant.t array
320 -> EConstr.constr array
321 -> int
322 -> unit Proofview.tactic) : unit =
323 let names =
324 List.map (function {Vernacexpr.fname = {CAst.v = name}} -> name) fix_rec_l
325 in
326 let fun_bodies = List.map2 prepare_body fix_rec_l recdefs in
327 let funs_args = List.map fst fun_bodies in
328 let funs_types =
329 List.map (function {Vernacexpr.rtype} -> rtype) fix_rec_l
330 in
331 try
332 (* We then register the Inductive graphs of the functions *)
333 Glob_term_to_relation.build_inductive !evd pconstants funs_args funs_types
334 recdefs;
335 if do_built then begin
336 (*i The next call to mk_rel_id is valid since we have just construct the graph
337 Ensures by : do_built
338 i*)
339 let f_R_mut = Libnames.qualid_of_ident @@ mk_rel_id (List.nth names 0) in
340 let ind_kn =
341 fst
342 (locate_with_msg
343 Pp.(Libnames.pr_qualid f_R_mut ++ str ": Not an inductive type!")
344 locate_ind f_R_mut)
345 in
346 let fname_kn {Vernacexpr.fname} =
347 let f_ref = Libnames.qualid_of_ident ?loc:fname.CAst.loc fname.CAst.v in
348 locate_with_msg
349 Pp.(Libnames.pr_qualid f_ref ++ str ": Not an inductive type!")
350 locate_constant f_ref
351 in
352 let funs_kn = Array.of_list (List.map fname_kn fix_rec_l) in
353 let _ =
354 List.map_i
355 (fun i _x ->
356 let env = Global.env () in
357 let princ = Elimschemes.lookup_eliminator env (ind_kn, i) UnivGen.QualityOrSet.prop in
358 let evd = ref (Evd.from_env env) in
359 let evd', uprinc = Evd.fresh_global env !evd princ in
360 let _ = evd := evd' in
361 let sigma, princ_type =
362 Typing.type_of ~refresh:true env !evd uprinc
363 in
364 evd := sigma;
365 let princ_type = EConstr.Unsafe.to_constr princ_type in
366 generate_functional_principle evd princ_type None None
367 (Array.map_of_list (fun (c, u) -> c, EConstr.EInstance.make u ) pconstants) (* funs_kn *)
368 i
369 (continue_proof 0 [|funs_kn.(i)|]))
370 0 fix_rec_l
371 in
372 Array.iter (add_Function is_general) funs_kn;
373 ()
374 end
375 with e when CErrors.noncritical e -> on_error names e
376
377 let register_struct is_rec (rec_order, fixpoint_exprl) =
378 let open EConstr in
379 match fixpoint_exprl with
380 | [{Vernacexpr.fname; univs; binders; rtype; body_def}] when not is_rec ->
381 let body =
382 match body_def with
383 | Some body -> body
384 | None ->
385 CErrors.user_err
386 Pp.(str "Body of Function must be given.")
387 in
388 ComDefinition.do_definition ?loc:fname.CAst.loc ~name:fname.CAst.v
389 ~poly:PolyFlags.default
390 ~kind:Decls.Definition univs binders None body (Some rtype);
391 let evd, rev_pconstants =
392 List.fold_left
393 (fun (evd, l) {Vernacexpr.fname} ->
394 let evd, c =
395 Evd.fresh_global (Global.env ()) evd
396 (Option.get (Constrintern.locate_reference
397 (Libnames.qualid_of_ident fname.CAst.v)))
398 in
399 let cst, u = destConst evd c in
400 let u = EInstance.kind evd u in
401 (evd, (cst, u) :: l))
402 (Evd.from_env (Global.env ()), [])
403 fixpoint_exprl
404 in
405 (None, evd, List.rev rev_pconstants)
406 | _ ->
407 let pm, p = ComFixpoint.do_mutually_recursive ~refine:false ~program_mode:false
408 ~poly:PolyFlags.default ~kind:(IsDefinition Fixpoint) (CFixRecOrder rec_order, fixpoint_exprl) in
409 assert (Option.is_empty pm && Option.is_empty p);
410 let evd, rev_pconstants =
411 List.fold_left
412 (fun (evd, l) {Vernacexpr.fname} ->
413 let evd, c =
414 Evd.fresh_global (Global.env ()) evd
415 (Option.get (Constrintern.locate_reference
416 (Libnames.qualid_of_ident fname.CAst.v)))
417 in
418 let cst, u = destConst evd c in
419 let u = EInstance.kind evd u in
420 (evd, (cst, u) :: l))
421 (Evd.from_env (Global.env ()), [])
422 fixpoint_exprl
423 in
424 (None, evd, List.rev rev_pconstants)
425
426 let generate_correction_proof_wf f_ref tcc_lemma_ref is_mes functional_ref
427 eq_ref rec_arg_num rec_arg_type relation (_ : int)
428 (_ : Names.Constant.t array) (_ : EConstr.constr array) (_ : int) :
429 unit Proofview.tactic =
430 Functional_principles_proofs.prove_principle_for_gen
431 (f_ref, functional_ref, eq_ref)
432 tcc_lemma_ref is_mes rec_arg_num rec_arg_type relation
433
434 (* [generate_type g_to_f f graph i] build the completeness (resp. correctness) lemma type if [g_to_f = true]
435 (resp. g_to_f = false) where [graph] is the graph of [f] and is the [i]th function in the block.
436
437 [generate_type true f i] returns
438 \[\forall (x_1:t_1)\ldots(x_n:t_n), let fv := f x_1\ldots x_n in, forall res,
439 graph\ x_1\ldots x_n\ res \rightarrow res = fv \] decomposed as the context and the conclusion
440
441 [generate_type false f i] returns
442 \[\forall (x_1:t_1)\ldots(x_n:t_n), let fv := f x_1\ldots x_n in, forall res,
443 res = fv \rightarrow graph\ x_1\ldots x_n\ res\] decomposed as the context and the conclusion
444 *)
445
446 let generate_type env evd g_to_f f graph =
447 let open Context.Rel.Declaration in
448 let open EConstr in
449 let open EConstr.Vars in
450 (*i we deduce the number of arguments of the function and its returned type from the graph i*)
451 let evd', graph =
452 Evd.fresh_global env !evd
453 (GlobRef.IndRef (fst (destInd !evd graph)))
454 in
455 evd := evd';
456 let sigma, graph_arity = Typing.type_of env !evd graph in
457 evd := sigma;
458 let ctxt, _ = decompose_prod_decls !evd graph_arity in
459 let fun_ctxt, res_type =
460 match ctxt with
461 | [] | [_] -> CErrors.anomaly (Pp.str "Not a valid context.")
462 | decl :: fun_ctxt -> (fun_ctxt, RelDecl.get_type decl)
463 in
464 let rec args_from_decl i accu = function
465 | [] -> accu
466 | LocalDef _ :: l -> args_from_decl (succ i) accu l
467 | _ :: l ->
468 let t = mkRel i in
469 args_from_decl (succ i) (t :: accu) l
470 in
471 (*i We need to name the vars [res] and [fv] i*)
472 let filter decl =
473 match RelDecl.get_name decl with Name id -> Some id | Anonymous -> None
474 in
475 let named_ctxt = Id.Set.of_list (List.map_filter filter fun_ctxt) in
476 let res_id =
477 Namegen.next_ident_away_in_goal env (Id.of_string "_res") named_ctxt
478 in
479 let fv_id =
480 Namegen.next_ident_away_in_goal env (Id.of_string "fv")
481 (Id.Set.add res_id named_ctxt)
482 in
483 (*i we can then type the argument to be applied to the function [f] i*)
484 let args_as_rels = Array.of_list (args_from_decl 1 [] fun_ctxt) in
485 (*i
486 the hypothesis [res = fv] can then be computed
487 We will need to lift it by one in order to use it as a conclusion
488 i*)
489 let make_eq = make_eq () in
490 let res_eq_f_of_args =
491 mkApp (make_eq, [|lift 2 res_type; mkRel 1; mkRel 2|])
492 in
493 (*i
494 The hypothesis [graph\ x_1\ldots x_n\ res] can then be computed
495 We will need to lift it by one in order to use it as a conclusion
496 i*)
497 let args_and_res_as_rels = Array.of_list (args_from_decl 3 [] fun_ctxt) in
498 let args_and_res_as_rels = Array.append args_and_res_as_rels [|mkRel 1|] in
499 let graph_applied = mkApp (graph, args_and_res_as_rels) in
500 (*i The [pre_context] is the defined to be the context corresponding to
501 \[\forall (x_1:t_1)\ldots(x_n:t_n), let fv := f x_1\ldots x_n in, forall res, \]
502 i*)
503 let pre_ctxt =
504 LocalAssum (Context.make_annot (Name res_id) ERelevance.relevant, lift 1 res_type)
505 :: LocalDef
506 ( Context.make_annot (Name fv_id) ERelevance.relevant
507 , mkApp (f, args_as_rels)
508 , res_type )
509 :: fun_ctxt
510 in
511 (*i and we can return the solution depending on which lemma type we are defining i*)
512 if g_to_f then
513 ( LocalAssum (Context.make_annot Anonymous ERelevance.relevant, graph_applied)
514 :: pre_ctxt
515 , lift 1 res_eq_f_of_args
516 , graph )
517 else
518 ( LocalAssum (Context.make_annot Anonymous ERelevance.relevant, res_eq_f_of_args)
519 :: pre_ctxt
520 , lift 1 graph_applied
521 , graph )
522
523 (**
524 [find_induction_principle f] searches and returns the [body] and the [type] of [f_rect]
525
526 WARNING: while convertible, [type_of body] and [type] can be non equal
527 *)
528 let find_induction_principle env evd f =
529 let f_as_constant, _u =
530 match EConstr.kind !evd f with
531 | Constr.Const c' -> c'
532 | _ -> CErrors.user_err Pp.(str "Must be used with a function")
533 in
534 match find_Function_infos f_as_constant with
535 | None -> raise Not_found
536 | Some infos -> (
537 match infos.rect_lemma with
538 | None -> raise Not_found
539 | Some rect_lemma ->
540 let evd', rect_lemma =
541 Evd.fresh_global env !evd (GlobRef.ConstRef rect_lemma)
542 in
543 let evd', typ =
544 Typing.type_of ~refresh:true env evd' rect_lemma
545 in
546 evd := evd';
547 (rect_lemma, typ) )
548
549 (* [prove_fun_correct funs_constr graphs_constr schemes lemmas_types_infos i ]
550 is the tactic used to prove correctness lemma.
551
552 [funs_constr], [graphs_constr] [schemes] [lemmas_types_infos] are the mutually recursive functions
553 (resp. graphs of the functions and principles and correctness lemma types) to prove correct.
554
555 [i] is the indice of the function to prove correct
556
557 The lemma to prove if suppose to have been generated by [generate_type] (in $\zeta$ normal form that is
558 it looks like~:
559 [\forall (x_1:t_1)\ldots(x_n:t_n), forall res,
560 res = f x_1\ldots x_n in, \rightarrow graph\ x_1\ldots x_n\ res]
561
562
563 The sketch of the proof is the following one~:
564 \begin{enumerate}
565 \item intros until $x_n$
566 \item $functional\ induction\ (f.(i)\ x_1\ldots x_n)$ using schemes.(i)
567 \item for each generated branch intro [res] and [hres :res = f x_1\ldots x_n], rewrite [hres] and the
568 apply the corresponding constructor of the corresponding graph inductive.
569 \end{enumerate}
570
571 *)
572
573 let rec generate_fresh_id x avoid i =
574 if i == 0 then []
575 else
576 let id = Namegen.next_ident_away_in_goal (Global.env ()) x (Id.Set.of_list avoid) in
577 id :: generate_fresh_id x (id :: avoid) (pred i)
578
579 let prove_fun_correct evd graphs_constr schemes lemmas_types_infos i :
580 unit Proofview.tactic =
581 let open Constr in
582 let open EConstr in
583 let open Context.Rel.Declaration in
584 let open Tactics in
585 let open Tacticals in
586 Proofview.Goal.enter (fun g ->
587 (* first of all we recreate the lemmas types to be used as predicates of the induction principle
588 that is~:
589 \[fun (x_1:t_1)\ldots(x_n:t_n)=> fun fv => fun res => res = fv \rightarrow graph\ x_1\ldots x_n\ res\]
590 *)
591 (* we the get the definition of the graphs block *)
592 let graph_ind, u = destInd evd graphs_constr.(i) in
593 let kn = fst graph_ind in
594 let mib, _ = Global.lookup_inductive graph_ind in
595 (* and the principle to use in this lemma in $\zeta$ normal form *)
596 let f_principle, princ_type = schemes.(i) in
597 let princ_type = Reductionops.nf_zeta (Global.env ()) evd princ_type in
598 let princ_infos = Induction.compute_elim_sig evd princ_type in
599 (* The number of args of the function is then easily computable *)
600 let nb_fun_args =
601 Termops.nb_prod (Proofview.Goal.sigma g) (Proofview.Goal.concl g) - 2
602 in
603 let args_names = generate_fresh_id (Id.of_string "x") [] nb_fun_args in
604 let ids = args_names @ Tacmach.pf_ids_of_hyps g in
605 (* Since we cannot ensure that the functional principle is defined in the
606 environment and due to the bug #1174, we will need to pose the principle
607 using a name
608 *)
609 let principle_id =
610 Namegen.next_ident_away_in_goal (Global.env ()) (Id.of_string "princ")
611 (Id.Set.of_list ids)
612 in
613 let ids = principle_id :: ids in
614 (* We get the branches of the principle *)
615 let branches = List.rev princ_infos.Induction.branches in
616 (* and built the intro pattern for each of them *)
617 let intro_pats =
618 List.map
619 (fun decl ->
620 List.map
621 (fun id ->
622 CAst.make @@ Tactypes.IntroNaming (Namegen.IntroIdentifier id))
623 (generate_fresh_id (Id.of_string "y") ids
624 (List.length
625 (fst (decompose_prod_decls evd (RelDecl.get_type decl))))))
626 branches
627 in
628 (* before building the full intro pattern for the principle *)
629 let eq_ind = make_eq () in
630 let eq_construct = mkConstructUi (destInd evd eq_ind, 1) in
631 (* The next to referencies will be used to find out which constructor to apply in each branch *)
632 let ind_number = ref 0 and min_constr_number = ref 0 in
633 (* The tactic to prove the ith branch of the principle *)
634 let prove_branch i pat =
635 (* We get the identifiers of this branch *)
636 let pre_args =
637 List.fold_right
638 (fun {CAst.v = pat} acc ->
639 match pat with
640 | Tactypes.IntroNaming (Namegen.IntroIdentifier id) -> id :: acc
641 | _ -> CErrors.anomaly (Pp.str "Not an identifier."))
642 pat []
643 in
644 (* and get the real args of the branch by unfolding the defined constant *)
645 (*
646 We can then recompute the arguments of the constructor.
647 For each [hid] introduced by this branch, if [hid] has type
648 $forall res, res=fv -> graph.(j)\ x_1\ x_n res$ the corresponding arguments of the constructor are
649 [ fv (hid fv (refl_equal fv)) ].
650 If [hid] has another type the corresponding argument of the constructor is [hid]
651 *)
652 let constructor_args g =
653 List.fold_right
654 (fun hid acc ->
655 let type_of_hid = Tacmach.pf_get_hyp_typ hid g in
656 let sigma = Proofview.Goal.sigma g in
657 match EConstr.kind sigma type_of_hid with
658 | Prod (_, _, t') -> (
659 match EConstr.kind sigma t' with
660 | Prod (_, t'', t''') -> (
661 match (EConstr.kind sigma t'', EConstr.kind sigma t''') with
662 | App (eq, args), App (graph', _)
663 when EConstr.eq_constr sigma eq eq_ind
664 && Array.exists
665 (EConstr.eq_constr_nounivs sigma graph')
666 graphs_constr ->
667 args.(2)
668 :: mkApp
669 ( mkVar hid
670 , [| args.(2)
671 ; mkApp (eq_construct, [|args.(0); args.(2)|]) |] )
672 :: acc
673 | _ -> mkVar hid :: acc )
674 | _ -> mkVar hid :: acc )
675 | _ -> mkVar hid :: acc)
676 pre_args []
677 in
678 (* in fact we must also add the parameters to the constructor args *)
679 let constructor_args g =
680 let params_id =
681 fst (List.chop princ_infos.Induction.nparams args_names)
682 in
683 List.map mkVar params_id @ constructor_args g
684 in
685 (* We then get the constructor corresponding to this branch and
686 modifies the references has needed i.e.
687 if the constructor is the last one of the current inductive then
688 add one the number of the inductive to take and add the number of constructor of the previous
689 graph to the minimal constructor number
690 *)
691 let constructor =
692 let constructor_num = i - !min_constr_number in
693 let length =
694 Array.length
695 mib.Declarations.mind_packets.(!ind_number)
696 .Declarations.mind_consnames
697 in
698 if constructor_num <= length then ((kn, !ind_number), constructor_num)
699 else begin
700 incr ind_number;
701 min_constr_number := !min_constr_number + length;
702 ((kn, !ind_number), 1)
703 end
704 in
705 (* we can then build the final proof term *)
706 let app_constructor g =
707 applist (mkConstructU (constructor, u), constructor_args g)
708 in
709 (* an apply the tactic *)
710 let res, hres =
711 match
712 generate_fresh_id (Id.of_string "z") ids (* @this_branche_ids *) 2
713 with
714 | [res; hres] -> (res, hres)
715 | _ -> assert false
716 in
717 (* observe (str "constructor := " ++ Printer.pr_lconstr_env (pf_env g) app_constructor); *)
718 tclTHENLIST
719 [ observe_tac "h_intro_patterns "
720 (match pat with [] -> tclIDTAC | _ -> intro_patterns false pat)
721 ; (* unfolding of all the defined variables introduced by this branch *)
722 (* observe_tac "unfolding" pre_tac; *)
723 (* $zeta$ normalizing of the conclusion *)
724 reduce
725 (Genredexpr.Cbv
726 { Redops.all_flags with
727 Genredexpr.rDelta = false
728 ; Genredexpr.rConst = [] })
729 Locusops.onConcl
730 ; observe_tac "toto " (Proofview.tclUNIT ())
731 ; (* introducing the result of the graph and the equality hypothesis *)
732 observe_tac "introducing" (tclMAP Simple.intro [res; hres])
733 ; (* replacing [res] with its value *)
734 observe_tac "rewriting res value" (Equality.rewriteLR (mkVar hres))
735 ; (* Conclusion *)
736 observe_tac "exact"
737 (Proofview.Goal.enter (fun g -> exact_check (app_constructor g)))
738 ]
739 in
740 (* end of branche proof *)
741 let lemmas =
742 Array.map
743 (fun (_, (ctxt, concl)) ->
744 match ctxt with
745 | [] | [_] | [_; _] -> CErrors.anomaly (Pp.str "bad context.")
746 | hres :: res :: decl :: ctxt ->
747 let res =
748 EConstr.it_mkLambda_or_LetIn
749 (EConstr.it_mkProd_or_LetIn concl [hres; res])
750 ( LocalAssum (RelDecl.get_annot decl, RelDecl.get_type decl)
751 :: ctxt )
752 in
753 res)
754 lemmas_types_infos
755 in
756 let param_names = fst (List.chop princ_infos.nparams args_names) in
757 let params = List.map mkVar param_names in
758 let lemmas =
759 Array.to_list (Array.map (fun c -> applist (c, params)) lemmas)
760 in
761 (* The bindings of the principle
762 that is the params of the principle and the different lemma types
763 *)
764 let bindings =
765 let params_bindings, avoid =
766 List.fold_left2
767 (fun (bindings, avoid) decl p ->
768 let id =
769 Namegen.next_ident_away
770 (Nameops.Name.get_id (RelDecl.get_name decl))
771 (Id.Set.of_list avoid)
772 in
773 (p :: bindings, id :: avoid))
774 ([], Tacmach.pf_ids_of_hyps g)
775 princ_infos.params (List.rev params)
776 in
777 let lemmas_bindings =
778 List.rev
779 (fst
780 (List.fold_left2
781 (fun (bindings, avoid) decl p ->
782 let id =
783 Namegen.next_ident_away
784 (Nameops.Name.get_id (RelDecl.get_name decl))
785 (Id.Set.of_list avoid)
786 in
787 ( Reductionops.nf_zeta (Proofview.Goal.env g)
788 (Proofview.Goal.sigma g) p
789 :: bindings
790 , id :: avoid ))
791 ([], avoid) princ_infos.predicates lemmas))
792 in
793 params_bindings @ lemmas_bindings
794 in
795 tclTHENLIST
796 [ observe_tac "principle"
797 (assert_by (Name principle_id) princ_type (exact_check f_principle))
798 ; observe_tac "intro args_names" (tclMAP Simple.intro args_names)
799 ; (* observe_tac "titi" (pose_proof (Name (Id.of_string "__")) (Reductionops.nf_beta Evd.empty ((mkApp (mkVar principle_id,Array.of_list bindings))))); *)
800 observe_tac "idtac" tclIDTAC
801 ; tclTHENS
802 (observe_tac "functional_induction"
803 (Proofview.Goal.enter (fun gl ->
804 let term =
805 mkApp (mkVar principle_id, Array.of_list bindings)
806 in
807 tclTYPEOFTHEN ~refresh:true term (fun _ _ -> apply term))))
808 (List.map_i
809 (fun i pat ->
810 observe_tac
811 ("proving branch " ^ string_of_int i)
812 (prove_branch i pat))
813 1 intro_pats) ])
814
815 (* [prove_fun_complete funs graphs schemes lemmas_types_infos i]
816 is the tactic used to prove completeness lemma.
817
818 [funcs], [graphs] [schemes] [lemmas_types_infos] are the mutually recursive functions
819 (resp. definitions of the graphs of the functions, principles and correctness lemma types) to prove correct.
820
821 [i] is the indice of the function to prove complete
822
823 The lemma to prove if suppose to have been generated by [generate_type] (in $\zeta$ normal form that is
824 it looks like~:
825 [\forall (x_1:t_1)\ldots(x_n:t_n), forall res,
826 graph\ x_1\ldots x_n\ res, \rightarrow res = f x_1\ldots x_n in]
827
828
829 The sketch of the proof is the following one~:
830 \begin{enumerate}
831 \item intros until $H:graph\ x_1\ldots x_n\ res$
832 \item $elim\ H$ using schemes.(i)
833 \item for each generated branch, intro the news hyptohesis, for each such hyptohesis [h], if [h] has
834 type [x=?] with [x] a variable, then subst [x],
835 if [h] has type [t=?] with [t] not a variable then rewrite [t] in the subterms, else
836 if [h] is a match then destruct it, else do just introduce it,
837 after all intros, the conclusion should be a reflexive equality.
838 \end{enumerate}
839
840 *)
841
842 let thin = Tactics.clear
843
844 (* [intros_with_rewrite] do the intros in each branch and treat each new hypothesis
845 (unfolding, substituting, destructing cases \ldots)
846 *)
847 let tauto =
848 let open Ltac_plugin in
849 let dp = List.map Id.of_string ["Tauto"; "Init"; "Corelib"] in
850 let mp = ModPath.MPfile (DirPath.make dp) in
851 let kn = KerName.make mp (Id.of_string "tauto") in
852 Proofview.tclBIND (Proofview.tclUNIT ()) (fun () ->
853 let body = Tacenv.interp_ltac kn in
854 Tacinterp.eval_tactic body)
855
856 (* [generalize_dependent_of x hyp g]
857 generalize every hypothesis which depends of [x] but [hyp]
858 *)
859 let generalize_dependent_of x hyp =
860 let open Context.Named.Declaration in
861 let open Tacticals in
862 Proofview.Goal.enter (fun g ->
863 tclMAP
864 (function
865 | LocalAssum ({Context.binder_name = id}, t)
866 when (not (Id.equal id hyp))
867 && Termops.occur_var (Proofview.Goal.env g)
868 (Proofview.Goal.sigma g) x t ->
869 tclTHEN (Generalize.generalize [EConstr.mkVar id]) (thin [id])
870 | _ -> Proofview.tclUNIT ())
871 (Proofview.Goal.hyps g))
872
873 let rec intros_with_rewrite () =
874 observe_tac "intros_with_rewrite" (intros_with_rewrite_aux ())
875
876 and intros_with_rewrite_aux () : unit Proofview.tactic =
877 let open Constr in
878 let open EConstr in
879 let open Tactics in
880 let open Tacticals in
881 Proofview.Goal.enter (fun g ->
882 let eq_ind = make_eq () in
883 let sigma = Proofview.Goal.sigma g in
884 match EConstr.kind sigma (Proofview.Goal.concl g) with
885 | Prod (_, t, t') -> (
886 match EConstr.kind sigma t with
887 | App (eq, args) when EConstr.eq_constr sigma eq eq_ind ->
888 if
889 Reductionops.is_conv (Proofview.Goal.env g) (Proofview.Goal.sigma g)
890 args.(1) args.(2)
891 then
892 let id = Tacmach.pf_get_new_id (Id.of_string "y") g in
893 tclTHENLIST [Simple.intro id; thin [id]; intros_with_rewrite ()]
894 else if
895 isVar sigma args.(1)
896 && Environ.evaluable_named
897 (destVar sigma args.(1))
898 (Proofview.Goal.env g)
899 then
900 tclTHENLIST
901 [ unfold_in_concl
902 [ ( Locus.AllOccurrences
903 , Evaluable.EvalVarRef (destVar sigma args.(1)) ) ]
904 ; tclMAP
905 (fun id ->
906 tclTRY
907 (unfold_in_hyp
908 [ ( Locus.AllOccurrences
909 , Evaluable.EvalVarRef (destVar sigma args.(1)) ) ]
910 (destVar sigma args.(1), Locus.InHyp)))
911 (Tacmach.pf_ids_of_hyps g)
912 ; intros_with_rewrite () ]
913 else if
914 isVar sigma args.(2)
915 && Environ.evaluable_named
916 (destVar sigma args.(2))
917 (Proofview.Goal.env g)
918 then
919 tclTHENLIST
920 [ unfold_in_concl
921 [ ( Locus.AllOccurrences
922 , Evaluable.EvalVarRef (destVar sigma args.(2)) ) ]
923 ; tclMAP
924 (fun id ->
925 tclTRY
926 (unfold_in_hyp
927 [ ( Locus.AllOccurrences
928 , Evaluable.EvalVarRef (destVar sigma args.(2)) ) ]
929 (destVar sigma args.(2), Locus.InHyp)))
930 (Tacmach.pf_ids_of_hyps g)
931 ; intros_with_rewrite () ]
932 else if isVar sigma args.(1) then
933 let id = Tacmach.pf_get_new_id (Id.of_string "y") g in
934 tclTHENLIST
935 [ Simple.intro id
936 ; generalize_dependent_of (destVar sigma args.(1)) id
937 ; tclTRY (Equality.rewriteLR (mkVar id))
938 ; intros_with_rewrite () ]
939 else if isVar sigma args.(2) then
940 let id = Tacmach.pf_get_new_id (Id.of_string "y") g in
941 tclTHENLIST
942 [ Simple.intro id
943 ; generalize_dependent_of (destVar sigma args.(2)) id
944 ; tclTRY (Equality.rewriteRL (mkVar id))
945 ; intros_with_rewrite () ]
946 else
947 let id = Tacmach.pf_get_new_id (Id.of_string "y") g in
948 tclTHENLIST
949 [ Simple.intro id
950 ; tclTRY (Equality.rewriteLR (mkVar id))
951 ; intros_with_rewrite () ]
952 | Ind _
953 when EConstr.eq_constr sigma t
954 (EConstr.of_constr
955 ( UnivGen.constr_of_monomorphic_global (Global.env ())
956 @@ Rocqlib.lib_ref "core.False.type" )) ->
957 tauto
958 | Case (_, _, _, _, _, v, _) ->
959 tclTHENLIST [simplest_case v; intros_with_rewrite ()]
960 | LetIn _ ->
961 tclTHENLIST
962 [ reduce
963 (Genredexpr.Cbv {Redops.all_flags with Genredexpr.rDelta = false})
964 Locusops.onConcl
965 ; intros_with_rewrite () ]
966 | _ ->
967 let id = Tacmach.pf_get_new_id (Id.of_string "y") g in
968 tclTHENLIST [Simple.intro id; intros_with_rewrite ()] )
969 | LetIn _ ->
970 tclTHENLIST
971 [ reduce
972 (Genredexpr.Cbv {Redops.all_flags with Genredexpr.rDelta = false})
973 Locusops.onConcl
974 ; intros_with_rewrite () ]
975 | _ -> Proofview.tclUNIT ())
976
977 let rec reflexivity_with_destruct_cases () =
978 let open Constr in
979 let open EConstr in
980 let open Tactics in
981 let open Tacticals in
982 Proofview.Goal.enter (fun g ->
983 let destruct_case () =
984 try
985 match
986 EConstr.kind (Proofview.Goal.sigma g)
987 (snd (destApp (Proofview.Goal.sigma g) (Proofview.Goal.concl g))).(
988 2)
989 with
990 | Case (_, _, _, _, _, v, _) ->
991 tclTHENLIST
992 [ simplest_case v
993 ; intros
994 ; observe_tac "reflexivity_with_destruct_cases"
995 (reflexivity_with_destruct_cases ()) ]
996 | _ -> reflexivity
997 with e when CErrors.noncritical e -> reflexivity
998 in
999 let eq_ind = make_eq () in
1000 let my_inj_flags =
1001 Some
1002 { Equality.keep_proof_equalities = false
1003 ; injection_pattern_l2r_order = false
1004 (* probably does not matter; except maybe with dependent hyps *)
1005 }
1006 in
1007 let discr_inject =
1008 onAllHypsAndConcl (fun sc ->
1009 match sc with
1010 | None -> Proofview.tclUNIT ()
1011 | Some id ->
1012 Proofview.Goal.enter (fun g ->
1013 match
1014 EConstr.kind (Proofview.Goal.sigma g) (Tacmach.pf_get_hyp_typ id g)
1015 with
1016 | App (eq, [|_; t1; t2|])
1017 when EConstr.eq_constr (Proofview.Goal.sigma g) eq eq_ind ->
1018 tclFIRST [
1019 Equality.discrHyp id;
1020 tclTHENLIST
1021 [ Equality.injHyp my_inj_flags ~injection_in_context:false None id
1022 ; thin [id]
1023 ; intros_with_rewrite () ];
1024 Proofview.tclUNIT ()
1025 ]
1026 | _ -> Proofview.tclUNIT ()))
1027 in
1028 tclFIRST
1029 [ observe_tac "reflexivity_with_destruct_cases : reflexivity" reflexivity
1030 ; observe_tac "reflexivity_with_destruct_cases : destruct_case"
1031 (destruct_case ())
1032 ; (* We reach this point ONLY if
1033 the same value is matched (at least) two times
1034 along binding path.
1035 In this case, either we have a discriminable hypothesis and we are done,
1036 either at least an injectable one and we do the injection before continuing
1037 *)
1038 observe_tac "reflexivity_with_destruct_cases : others"
1039 (tclTHEN (tclPROGRESS discr_inject)
1040 (reflexivity_with_destruct_cases ())) ])
1041
1042 let prove_fun_complete funcs graphs schemes lemmas_types_infos i :
1043 unit Proofview.tactic =
1044 let open EConstr in
1045 let open Tactics in
1046 let open Tacticals in
1047 Proofview.Goal.enter (fun g ->
1048 (* We compute the types of the different mutually recursive lemmas
1049 in $\zeta$ normal form
1050 *)
1051 let lemmas =
1052 Array.map
1053 (fun (_, (ctxt, concl)) ->
1054 Reductionops.nf_zeta (Proofview.Goal.env g) (Proofview.Goal.sigma g)
1055 (EConstr.it_mkLambda_or_LetIn concl ctxt))
1056 lemmas_types_infos
1057 in
1058 (* We get the constant and the principle corresponding to this lemma *)
1059 let f = funcs.(i) in
1060 let graph_principle =
1061 Reductionops.nf_zeta (Proofview.Goal.env g) (Proofview.Goal.sigma g)
1062 (EConstr.of_constr schemes.(i))
1063 in
1064 tclTYPEOFTHEN graph_principle (fun sigma princ_type ->
1065 let princ_infos = Induction.compute_elim_sig sigma princ_type in
1066 (* Then we get the number of argument of the function
1067 and compute a fresh name for each of them
1068 *)
1069 let nb_fun_args =
1070 Termops.nb_prod sigma (Proofview.Goal.concl g) - 2
1071 in
1072 let args_names =
1073 generate_fresh_id (Id.of_string "x") [] nb_fun_args
1074 in
1075 let ids = args_names @ Tacmach.pf_ids_of_hyps g in
1076 (* and fresh names for res H and the principle (cf bug bug #1174) *)
1077 let res, hres, graph_principle_id =
1078 match generate_fresh_id (Id.of_string "z") ids 3 with
1079 | [res; hres; graph_principle_id] -> (res, hres, graph_principle_id)
1080 | _ -> assert false
1081 in
1082 let ids = res :: hres :: graph_principle_id :: ids in
1083 (* we also compute fresh names for each hyptohesis of each branch
1084 of the principle *)
1085 let branches = List.rev princ_infos.branches in
1086 let intro_pats =
1087 List.map
1088 (fun decl ->
1089 List.map
1090 (fun id -> id)
1091 (generate_fresh_id (Id.of_string "y") ids
1092 (Termops.nb_prod (Proofview.Goal.sigma g)
1093 (RelDecl.get_type decl))))
1094 branches
1095 in
1096 (* We will need to change the function by its body
1097 using [f_equation] if it is recursive (that is the graph is infinite
1098 or unfold if the graph is finite
1099 *)
1100 let rewrite_tac j ids : unit Proofview.tactic =
1101 let graph_def = graphs.(j) in
1102 let infos =
1103 match
1104 find_Function_infos
1105 (fst (destConst (Proofview.Goal.sigma g) funcs.(j)))
1106 with
1107 | None -> CErrors.user_err Pp.(str "No graph found")
1108 | Some infos -> infos
1109 in
1110 if
1111 infos.is_general
1112 || Rtree.is_infinite Declareops.eq_recarg
1113 graph_def.Declarations.mind_recargs
1114 then
1115 let eq_lemma = match infos.equation_lemma with
1116 | None -> CErrors.anomaly (Pp.str "Cannot find equation lemma.")
1117 | Some lemma -> lemma
1118 in
1119 tclTHENLIST
1120 [ tclMAP Simple.intro ids
1121 ; Equality.rewriteLR (UnsafeMonomorphic.mkConst eq_lemma)
1122 ; (* Don't forget to $\zeta$ normlize the term since the principles
1123 have been $\zeta$-normalized *)
1124 reduce
1125 (Genredexpr.Cbv
1126 {Redops.all_flags with Genredexpr.rDelta = false})
1127 Locusops.onConcl
1128 ; Generalize.generalize (List.map mkVar ids)
1129 ; thin ids ]
1130 else
1131 unfold_in_concl
1132 [ ( Locus.AllOccurrences
1133 , Evaluable.EvalConstRef
1134 (fst (destConst (Proofview.Goal.sigma g) f)) ) ]
1135 in
1136 (* The proof of each branche itself *)
1137 let ind_number = ref 0 in
1138 let min_constr_number = ref 0 in
1139 let prove_branch i this_branche_ids =
1140 (* we fist compute the inductive corresponding to the branch *)
1141 let this_ind_number =
1142 let constructor_num = i - !min_constr_number in
1143 let length =
1144 Array.length graphs.(!ind_number).Declarations.mind_consnames
1145 in
1146 if constructor_num <= length then !ind_number
1147 else begin
1148 incr ind_number;
1149 min_constr_number := !min_constr_number + length;
1150 !ind_number
1151 end
1152 in
1153 tclTHENLIST
1154 [ (* we expand the definition of the function *)
1155 observe_tac "rewrite_tac"
1156 (rewrite_tac this_ind_number this_branche_ids)
1157 ; (* introduce hypothesis with some rewrite *)
1158 observe_tac "intros_with_rewrite (all)" (intros_with_rewrite ())
1159 ; (* The proof is (almost) complete *)
1160 observe_tac "reflexivity" (reflexivity_with_destruct_cases ())
1161 ]
1162 in
1163 let params_names = fst (List.chop princ_infos.nparams args_names) in
1164 let open EConstr in
1165 let params = List.map mkVar params_names in
1166 tclTHENLIST
1167 [ tclMAP Simple.intro (args_names @ [res; hres])
1168 ; observe_tac "h_generalize"
1169 (Generalize.generalize
1170 [ mkApp
1171 ( applist (graph_principle, params)
1172 , Array.map (fun c -> applist (c, params)) lemmas ) ])
1173 ; Simple.intro graph_principle_id
1174 ; observe_tac ""
1175 (tclTHENS
1176 (observe_tac "elim"
1177 (elim false None
1178 (mkVar hres, Tactypes.NoBindings)
1179 (Some (mkVar graph_principle_id, Tactypes.NoBindings))))
1180 (List.map_i
1181 (fun i pat ->
1182 observe_tac "prove_branch" (prove_branch i pat))
1183 1 intro_pats)) ]))
1184
1185 exception No_graph_found
1186
1187 let get_funs_constant mp =
1188 let open Constr in
1189 let exception Not_Rec in
1190 let get_funs_constant const e : (Names.Constant.t * int) array =
1191 match Constr.kind (Term.strip_lam e) with
1192 | Fix (_, (na, _, _)) ->
1193 Array.mapi
1194 (fun i na ->
1195 match na.Context.binder_name with
1196 | Name id ->
1197 let const = Constant.make2 mp id in
1198 (const, i)
1199 | Anonymous -> CErrors.anomaly (Pp.str "Anonymous fix."))
1200 na
1201 | _ -> [|(const, 0)|]
1202 in
1203 function
1204 | const ->
1205 let find_constant_body const =
1206 let env = Global.env () in
1207 let body = Environ.lookup_constant const env in
1208 match body.Declarations.const_body with
1209 | Def body ->
1210 let body =
1211 Tacred.cbv_norm_flags ~strong:true
1212 (RedFlags.mkflags [RedFlags.fZETA])
1213 env
1214 (Evd.from_env env)
1215 (EConstr.of_constr body)
1216 in
1217 let body = EConstr.Unsafe.to_constr body in
1218 body
1219 | Undef _ | OpaqueDef _ | Primitive _ | Symbol _ ->
1220 CErrors.user_err Pp.(str "Cannot define a principle over an axiom ")
1221 in
1222 let f = find_constant_body const in
1223 let l_const = get_funs_constant const f in
1224 (*
1225 We need to check that all the functions found are in the same block
1226 to prevent Reset strange thing
1227 *)
1228 let l_bodies =
1229 List.map find_constant_body (Array.to_list (Array.map fst l_const))
1230 in
1231 let l_params, _l_fixes =
1232 List.split (List.map Term.decompose_lambda l_bodies)
1233 in
1234 (* all the parameters must be equal*)
1235 let _check_params =
1236 let first_params = List.hd l_params in
1237 List.iter
1238 (fun params ->
1239 if
1240 not
1241 (List.equal
1242 (fun (n1, c1) (n2, c2) ->
1243 Context.eq_annot Name.equal Sorts.relevance_equal n1 n2 && Constr.equal c1 c2)
1244 first_params params)
1245 then CErrors.user_err Pp.(str "Not a mutal recursive block"))
1246 l_params
1247 in
1248 (* The bodies has to be very similar *)
1249 let _check_bodies =
1250 try
1251 let extract_info is_first body =
1252 match Constr.kind body with
1253 | Fix ((idxs, _), (na, ta, ca)) -> (idxs, na, ta, ca)
1254 | _ ->
1255 if is_first && Int.equal (List.length l_bodies) 1 then raise Not_Rec
1256 else CErrors.user_err Pp.(str "Not a mutal recursive block")
1257 in
1258 let first_infos = extract_info true (List.hd l_bodies) in
1259 let check body =
1260 (* Hope this is correct *)
1261 let eq_infos (ia1, na1, ta1, ca1) (ia2, na2, ta2, ca2) =
1262 Array.equal Int.equal ia1 ia2
1263 && Array.equal (Context.eq_annot Name.equal Sorts.relevance_equal) na1 na2
1264 && Array.equal Constr.equal ta1 ta2
1265 && Array.equal Constr.equal ca1 ca2
1266 in
1267 if not (eq_infos first_infos (extract_info false body)) then
1268 CErrors.user_err Pp.(str "Not a mutal recursive block")
1269 in
1270 List.iter check l_bodies
1271 with Not_Rec -> ()
1272 in
1273 l_const
1274
1275 let make_scheme evd (fas : (Constant.t EConstr.puniverses * UnivGen.QualityOrSet.t) list) : _ list =
1276 let exception Found_type of int in
1277 let env = Global.env () in
1278 let funs = List.map fst fas in
1279 let first_fun = List.hd funs in
1280 let funs_mp = KerName.modpath (Constant.canonical (fst first_fun)) in
1281 let first_fun_kn =
1282 match find_Function_infos (fst first_fun) with
1283 | None -> raise No_graph_found
1284 | Some finfos -> fst finfos.graph_ind
1285 in
1286 let this_block_funs_indexes = get_funs_constant funs_mp (fst first_fun) in
1287 let this_block_funs =
1288 Array.map (fun (c, _) -> (c, snd first_fun)) this_block_funs_indexes
1289 in
1290 let funs_indexes =
1291 let this_block_funs_indexes = Array.to_list this_block_funs_indexes in
1292 let eq c1 c2 = Environ.QConstant.equal env c1 c2 in
1293 List.map
1294 (function cst -> List.assoc_f eq (fst cst) this_block_funs_indexes)
1295 funs
1296 in
1297 let ind_list =
1298 List.map
1299 (fun idx ->
1300 let ind = (first_fun_kn, idx) in
1301 (ind, true, EConstr.ESorts.prop))
1302 funs_indexes
1303 in
1304 let sigma, schemes = Indrec.build_mutual_induction_scheme env !evd ind_list (snd first_fun) in
1305 let _ = evd := sigma in
1306 let l_schemes =
1307 List.map
1308 (Retyping.get_type_of env sigma
1309 %> EConstr.Unsafe.to_constr )
1310 schemes
1311 in
1312 let i = ref (-1) in
1313 let sorts =
1314 List.rev_map
1315 (fun (_, x) ->
1316 let sigma, fs = Evd.fresh_sort_in_quality !evd x in
1317 evd := sigma;
1318 fs)
1319 fas
1320 in
1321 (* We create the first principle by tactic *)
1322 let first_type, other_princ_types =
1323 match l_schemes with
1324 | s :: l_schemes -> (s, l_schemes)
1325 | _ -> CErrors.anomaly (Pp.str "")
1326 in
1327 let opaque =
1328 let finfos =
1329 match find_Function_infos (fst first_fun) with
1330 | None -> raise Not_found
1331 | Some finfos -> finfos
1332 in
1333 match finfos.equation_lemma with
1334 | None -> Vernacexpr.Transparent (* non recursive definition *)
1335 | Some equation ->
1336 if Declareops.is_opaque (Global.lookup_constant equation) then
1337 Vernacexpr.Opaque
1338 else Vernacexpr.Transparent
1339 in
1340 let body, typ, univs, _hook, sigma0 =
1341 try
1342 build_functional_principle (Global.env ()) !evd first_type (Array.of_list sorts)
1343 this_block_funs 0
1344 (Functional_principles_proofs.prove_princ_for_struct evd false 0
1345 (Array.of_list (List.map fst funs)))
1346 (fun _ _ -> ())
1347 with e when CErrors.noncritical e -> raise (Defining_principle e)
1348 in
1349 evd := sigma0;
1350 incr i;
1351 (* The others are just deduced *)
1352 if List.is_empty other_princ_types then [(body, typ, univs, opaque)]
1353 else
1354 let other_fun_princ_types =
1355 let funs = Array.map EConstr.(mkConstU %> to_constr sigma) this_block_funs in
1356 let sorts = Array.of_list sorts in
1357 let sorts = Array.map (fun s -> EConstr.ESorts.kind sigma s) sorts in
1358 List.map
1359 (Functional_principles_types.compute_new_princ_type_from_rel (Global.env ()) funs sorts)
1360 other_princ_types
1361 in
1362 let first_princ_body = body in
1363 let ctxt, fix = Term.decompose_lambda_decls first_princ_body in
1364 (* the principle has for forall ...., fix .*)
1365 let (idxs, _), ((_, ta, _) as decl) = Constr.destFix fix in
1366 let other_result =
1367 List.map (* we can now compute the other principles *)
1368 (fun scheme_type ->
1369 incr i;
1370 observe (fun () -> Printer.pr_lconstr_env env sigma scheme_type);
1371 let type_concl = Term.strip_prod_decls scheme_type in
1372 let applied_f =
1373 List.hd (List.rev (snd (Constr.decompose_app_list type_concl)))
1374 in
1375 let f = fst (Constr.decompose_app applied_f) in
1376 try
1377 (* we search the number of the function in the fix block (name of the function) *)
1378 Array.iteri
1379 (fun j t ->
1380 let t = Term.strip_prod_decls t in
1381 let applied_g =
1382 List.hd (List.rev (snd (Constr.decompose_app_list t)))
1383 in
1384 let g = fst (Constr.decompose_app applied_g) in
1385 if Constr.equal f g then raise (Found_type j);
1386 observe
1387 Pp.(fun () ->
1388 Printer.pr_lconstr_env env sigma f
1389 ++ str " <> "
1390 ++ Printer.pr_lconstr_env env sigma g))
1391 ta;
1392 (* If we reach this point, the two principle are not mutually recursive
1393 We fall back to the previous method
1394 *)
1395 let body, typ, univs, _hook, sigma0 =
1396 build_functional_principle (Global.env ()) !evd
1397 (List.nth other_princ_types (!i - 1))
1398 (Array.of_list sorts) this_block_funs !i
1399 (Functional_principles_proofs.prove_princ_for_struct evd false
1400 !i
1401 (Array.of_list (List.map fst funs)))
1402 (fun _ _ -> ())
1403 in
1404 evd := sigma0;
1405 (body, typ, univs, opaque)
1406 with Found_type i ->
1407 let princ_body =
1408 Term.it_mkLambda_or_LetIn (Constr.mkFix ((idxs, i), decl)) ctxt
1409 in
1410 (princ_body, scheme_type, univs, opaque))
1411 other_fun_princ_types
1412 in
1413 (body, typ, univs, opaque) :: other_result
1414
1415 (* [derive_correctness funs graphs] create correctness and completeness
1416 lemmas for each function in [funs] w.r.t. [graphs]
1417 *)
1418
1419 let derive_correctness (funs : Constant.t EConstr.puniverses list) (graphs : inductive list)
1420 =
1421 let open EConstr in
1422 assert (funs <> []);
1423 assert (graphs <> []);
1424 let funs = Array.of_list funs and graphs = Array.of_list graphs in
1425 let funs_constr = Array.map mkConstU funs in
1426 (* XXX STATE Why do we need this... why is the toplevel protection not enough *)
1427 funind_purify
1428 (fun () ->
1429 let env = Global.env () in
1430 let evd = ref (Evd.from_env env) in
1431 let graphs_constr = Array.map UnsafeMonomorphic.mkInd graphs in
1432 let lemmas_types_infos =
1433 Util.Array.map2_i
1434 (fun i f_constr graph ->
1435 let type_of_lemma_ctxt, type_of_lemma_concl, graph =
1436 generate_type env evd false f_constr graph
1437 in
1438 let type_info = (type_of_lemma_ctxt, type_of_lemma_concl) in
1439 graphs_constr.(i) <- graph;
1440 let type_of_lemma =
1441 EConstr.it_mkProd_or_LetIn type_of_lemma_concl type_of_lemma_ctxt
1442 in
1443 let sigma, _ = Typing.type_of env !evd type_of_lemma in
1444 evd := sigma;
1445 let type_of_lemma =
1446 Reductionops.nf_zeta env !evd type_of_lemma
1447 in
1448 observe
1449 Pp.(fun () ->
1450 str "type_of_lemma := "
1451 ++ Printer.pr_leconstr_env env !evd type_of_lemma);
1452 (type_of_lemma, type_info))
1453 funs_constr graphs_constr
1454 in
1455 let schemes =
1456 (* The functional induction schemes are computed and not saved if there is more that one function
1457 if the block contains only one function we can safely reuse [f_rect]
1458 *)
1459 try
1460 if not (Int.equal (Array.length funs_constr) 1) then raise Not_found;
1461 [|find_induction_principle env evd funs_constr.(0)|]
1462 with Not_found ->
1463 Array.of_list
1464 (List.map
1465 (fun (body, typ, _opaque, _univs) ->
1466 (EConstr.of_constr body, EConstr.of_constr typ))
1467 (make_scheme evd
1468 (Array.map_to_list (fun const -> (const, UnivGen.QualityOrSet.qtype)) funs)))
1469 in
1470 let proving_tac =
1471 prove_fun_correct !evd graphs_constr schemes lemmas_types_infos
1472 in
1473 Array.iteri
1474 (fun i f_as_constant ->
1475 let f_id = Constant.label (fst f_as_constant) in
1476 (*i The next call to mk_correct_id is valid since we are constructing the lemma
1477 Ensures by: obvious
1478 i*)
1479 let lem_id = mk_correct_id f_id in
1480 let typ, _ = lemmas_types_infos.(i) in
1481 let info = Declare.Info.make () in
1482 let cinfo = Declare.CInfo.make ~name:lem_id ~typ () in
1483 let lemma = Declare.Proof.start ~cinfo ~info !evd in
1484 let lemma = fst @@ Declare.Proof.by (Global.env ()) (proving_tac i) lemma in
1485 let (_ : _ list) =
1486 Declare.Proof.save_regular ~proof:lemma
1487 ~opaque:Vernacexpr.Transparent ~idopt:None
1488 in
1489 let finfo =
1490 match find_Function_infos (fst f_as_constant) with
1491 | None -> raise Not_found
1492 | Some finfo -> finfo
1493 in
1494 (* let lem_cst = fst (destConst (Constrintern.global_reference lem_id)) in *)
1495 let _, lem_cst_constr =
1496 Evd.fresh_global (Global.env ()) !evd
1497 (Option.get (Constrintern.locate_reference (Libnames.qualid_of_ident lem_id)))
1498 in
1499 let lem_cst, _ = EConstr.destConst !evd lem_cst_constr in
1500 update_Function {finfo with correctness_lemma = Some lem_cst})
1501 funs;
1502 let env = Global.env () in
1503 let lemmas_types_infos =
1504 Util.Array.map2_i
1505 (fun i f_constr graph ->
1506 let type_of_lemma_ctxt, type_of_lemma_concl, graph =
1507 generate_type env evd true f_constr graph
1508 in
1509 let type_info = (type_of_lemma_ctxt, type_of_lemma_concl) in
1510 graphs_constr.(i) <- graph;
1511 let type_of_lemma =
1512 EConstr.it_mkProd_or_LetIn type_of_lemma_concl type_of_lemma_ctxt
1513 in
1514 let type_of_lemma = Reductionops.nf_zeta env !evd type_of_lemma in
1515 observe
1516 Pp.(fun () ->
1517 str "type_of_lemma := "
1518 ++ Printer.pr_leconstr_env env !evd type_of_lemma);
1519 (type_of_lemma, type_info))
1520 funs_constr graphs_constr
1521 in
1522 let ((kn, _) as graph_ind), u = destInd !evd graphs_constr.(0) in
1523 let mib, _mip = Inductive.lookup_mind_specif env graph_ind in
1524 let sigma, scheme =
1525 let sigma, inds = CArray.fold_left_map_i (fun i sigma _ ->
1526 let sigma, s = Evd.fresh_sort_in_quality ~rigid:UnivRigid sigma UnivGen.QualityOrSet.qtype in
1527 sigma, ((kn, i), true, s))
1528 !evd
1529 mib.mind_packets
1530 in
1531 Indrec.build_mutual_induction_scheme env sigma (Array.to_list inds) u
1532 in
1533 let schemes = Array.map_of_list EConstr.Unsafe.to_constr scheme in
1534 let proving_tac =
1535 prove_fun_complete funs_constr mib.Declarations.mind_packets schemes
1536 lemmas_types_infos
1537 in
1538 Array.iteri
1539 (fun i f_as_constant ->
1540 let f_id = Constant.label (fst f_as_constant) in
1541 (*i The next call to mk_complete_id is valid since we are constructing the lemma
1542 Ensures by: obvious
1543 i*)
1544 let lem_id = mk_complete_id f_id in
1545 let info = Declare.Info.make () in
1546 let cinfo =
1547 Declare.CInfo.make ~name:lem_id ~typ:(fst lemmas_types_infos.(i)) ()
1548 in
1549 let lemma = Declare.Proof.start ~cinfo sigma ~info in
1550 let lemma =
1551 fst
1552 (Declare.Proof.by (Global.env ())
1553 (observe_tac
1554 ("prove completeness (" ^ Id.to_string f_id ^ ")")
1555 (proving_tac i))
1556 lemma)
1557 in
1558 let (_ : _ list) =
1559 Declare.Proof.save_regular ~proof:lemma
1560 ~opaque:Vernacexpr.Transparent ~idopt:None
1561 in
1562 let finfo =
1563 match find_Function_infos (fst f_as_constant) with
1564 | None -> raise Not_found
1565 | Some finfo -> finfo
1566 in
1567 let _, lem_cst_constr =
1568 Evd.fresh_global (Global.env ()) !evd
1569 (Option.get (Constrintern.locate_reference (Libnames.qualid_of_ident lem_id)))
1570 in
1571 let lem_cst, _ = destConst !evd lem_cst_constr in
1572 update_Function {finfo with completeness_lemma = Some lem_cst})
1573 funs)
1574 ()
1575
1576 let warn_funind_cannot_build_inversion =
1577 CWarnings.create ~name:"funind-cannot-build-inversion" ~category:CWarnings.CoreCategories.funind
1578 Pp.(
1579 fun e' ->
1580 strbrk "Cannot build inversion information"
1581 ++ if do_observe () then fnl () ++ CErrors.print e' else mt ())
1582
1583 let derive_inversion env fix_names =
1584 try
1585 let evd' = Evd.from_env env in
1586 (* we first transform the fix_names identifier into their corresponding constant *)
1587 let evd', fix_names_as_constant =
1588 List.fold_right
1589 (fun id (evd, l) ->
1590 let evd, c =
1591 Evd.fresh_global env evd
1592 (Option.get (Constrintern.locate_reference (Libnames.qualid_of_ident id)))
1593 in
1594 (evd, EConstr.destConst evd c :: l))
1595 fix_names (evd', [])
1596 in
1597 (*
1598 Then we check that the graphs have been defined
1599 If one of the graphs haven't been defined
1600 we do nothing
1601 *)
1602 List.iter
1603 (fun c -> ignore (find_Function_infos (fst c)))
1604 fix_names_as_constant;
1605 try
1606 let _evd', lind =
1607 List.fold_right
1608 (fun id (evd, l) ->
1609 let evd, id =
1610 Evd.fresh_global env evd
1611 (Option.get (Constrintern.locate_reference
1612 (Libnames.qualid_of_ident (mk_rel_id id))))
1613 in
1614 (evd, fst (EConstr.destInd evd id) :: l))
1615 fix_names (evd', [])
1616 in
1617 derive_correctness fix_names_as_constant lind
1618 with e when CErrors.noncritical e -> warn_funind_cannot_build_inversion e
1619 with e when CErrors.noncritical e -> warn_funind_cannot_build_inversion e
1620
1621 let register_wf interactive_proof ?(is_mes = false) fname rec_impls wf_rel_expr
1622 wf_arg using_lemmas args ret_type body pre_hook =
1623 let type_of_f = Constrexpr_ops.mkCProdN args ret_type in
1624 let rec_arg_num =
1625 let names =
1626 List.map
1627 CAst.(with_val (fun x -> x))
1628 (Constrexpr_ops.names_of_local_assums args)
1629 in
1630 List.index Name.equal (Name wf_arg) names
1631 in
1632 let unbounded_eq =
1633 let f_app_args =
1634 CAst.make
1635 @@ Constrexpr.CAppExpl
1636 ( (Libnames.qualid_of_ident fname, None)
1637 , List.map
1638 (function
1639 | {CAst.v = Anonymous} -> assert false
1640 | {CAst.v = Name e} -> Constrexpr_ops.mkIdentC e)
1641 (Constrexpr_ops.names_of_local_assums args) )
1642 in
1643 CAst.make
1644 @@ Constrexpr.CApp
1645 ( Constrexpr_ops.mkRefC (Libnames.qualid_of_string "Logic.eq")
1646 , [(f_app_args, None); (body, None)] )
1647 in
1648 let eq = Constrexpr_ops.mkCProdN args unbounded_eq in
1649 let hook ((f_ref, _) as fconst) tcc_lemma_ref (functional_ref, _) (eq_ref, _)
1650 rec_arg_num rec_arg_type _nb_args relation =
1651 try
1652 pre_hook [fconst]
1653 (generate_correction_proof_wf f_ref tcc_lemma_ref is_mes functional_ref
1654 eq_ref rec_arg_num rec_arg_type relation);
1655 derive_inversion (Global.env ()) [fname]
1656 with e when CErrors.noncritical e -> (* No proof done *)
1657 ()
1658 in
1659 Recdef.recursive_definition ~interactive_proof ~is_mes fname rec_impls
1660 type_of_f wf_rel_expr rec_arg_num eq hook using_lemmas
1661
1662 let register_mes interactive_proof fname rec_impls wf_mes_expr wf_rel_expr_opt
1663 wf_arg using_lemmas args ret_type body =
1664 let wf_arg_type, wf_arg =
1665 match wf_arg with
1666 | None -> (
1667 match args with
1668 | [Constrexpr.CLocalAssum ([{CAst.v = Name x}], _, _k, t)] -> (t, x)
1669 | _ -> CErrors.user_err (Pp.str "Recursive argument must be specified") )
1670 | Some wf_args -> (
1671 try
1672 match
1673 List.find
1674 (function
1675 | Constrexpr.CLocalAssum (l, _, _k, t) ->
1676 List.exists
1677 (function
1678 | {CAst.v = Name id} -> Id.equal id wf_args | _ -> false)
1679 l
1680 | _ -> false)
1681 args
1682 with
1683 | Constrexpr.CLocalAssum (_, _, _k, t) -> (t, wf_args)
1684 | _ -> assert false
1685 with Not_found -> assert false )
1686 in
1687 let wf_rel_from_mes, is_mes =
1688 match wf_rel_expr_opt with
1689 | None ->
1690 let ltof =
1691 let make_dir l = DirPath.make (List.rev_map Id.of_string l) in
1692 Libnames.make_qualid
1693 (make_dir ["Arith"; "Wf_nat"])
1694 (Id.of_string "ltof")
1695 in
1696 let fun_from_mes =
1697 let applied_mes =
1698 Constrexpr_ops.mkAppC (wf_mes_expr, [Constrexpr_ops.mkIdentC wf_arg])
1699 in
1700 Constrexpr_ops.mkLambdaC
1701 ( [CAst.make @@ Name wf_arg]
1702 , Constrexpr_ops.default_binder_kind
1703 , wf_arg_type
1704 , applied_mes )
1705 in
1706 let wf_rel_from_mes =
1707 Constrexpr_ops.mkAppC
1708 (Constrexpr_ops.mkRefC ltof, [wf_arg_type; fun_from_mes])
1709 in
1710 (wf_rel_from_mes, true)
1711 | Some wf_rel_expr ->
1712 let wf_rel_with_mes =
1713 let a = Names.Id.of_string "___a" in
1714 let b = Names.Id.of_string "___b" in
1715 Constrexpr_ops.mkLambdaC
1716 ( [CAst.make @@ Name a; CAst.make @@ Name b]
1717 , Constrexpr.Default Glob_term.Explicit
1718 , wf_arg_type
1719 , Constrexpr_ops.mkAppC
1720 ( wf_rel_expr
1721 , [ Constrexpr_ops.mkAppC
1722 (wf_mes_expr, [Constrexpr_ops.mkIdentC a])
1723 ; Constrexpr_ops.mkAppC
1724 (wf_mes_expr, [Constrexpr_ops.mkIdentC b]) ] ) )
1725 in
1726 (wf_rel_with_mes, false)
1727 in
1728 register_wf interactive_proof ~is_mes fname rec_impls wf_rel_from_mes wf_arg
1729 using_lemmas args ret_type body
1730
1731 let do_generate_principle_aux pconstants on_error register_built
1732 interactive_proof (rec_order, fixpoint_exprl as fix) : Declare.Proof.t option =
1733 List.iter
1734 (fun {Vernacexpr.notations} ->
1735 if not (List.is_empty notations) then
1736 CErrors.user_err (Pp.str "Function does not support notations for now"))
1737 fixpoint_exprl;
1738 let lemma, _is_struct =
1739 match rec_order with
1740 | [ Some { CAst.v = Constrexpr.CWfRec (wf_x, wf_rel) } ] ->
1741 let ( {Vernacexpr.fname; univs = _; binders; rtype; body_def} as
1742 fixpoint_expr ) =
1743 match recompute_binder_list fix with
1744 | [e] -> e
1745 | _ -> assert false
1746 in
1747 let fixpoint_exprl = [fixpoint_expr] in
1748 let body =
1749 match body_def with
1750 | Some body -> body
1751 | None ->
1752 CErrors.user_err
1753 (Pp.str "Body of Function must be given.")
1754 in
1755 let recdefs, rec_impls = build_newrecursive fixpoint_exprl in
1756 let using_lemmas = [] in
1757 let pre_hook pconstants =
1758 generate_principle
1759 (ref (Evd.from_env (Global.env ())))
1760 pconstants on_error true register_built fixpoint_exprl recdefs
1761 in
1762 if register_built then
1763 ( register_wf interactive_proof fname.CAst.v rec_impls wf_rel
1764 wf_x.CAst.v using_lemmas binders rtype body pre_hook
1765 , false )
1766 else (None, false)
1767 | [ Some { CAst.v = Constrexpr.CMeasureRec (wf_x, wf_mes, wf_rel_opt) } ] ->
1768 let ( {Vernacexpr.fname; univs = _; binders; rtype; body_def} as
1769 fixpoint_expr ) =
1770 match recompute_binder_list fix with
1771 | [e] -> e
1772 | _ -> assert false
1773 in
1774 let fixpoint_exprl = [fixpoint_expr] in
1775 let recdefs, rec_impls = build_newrecursive fixpoint_exprl in
1776 let using_lemmas = [] in
1777 let body =
1778 match body_def with
1779 | Some body -> body
1780 | None ->
1781 CErrors.user_err
1782 Pp.(str "Body of Function must be given.")
1783 in
1784 let pre_hook pconstants =
1785 generate_principle
1786 (ref (Evd.from_env (Global.env ())))
1787 pconstants on_error true register_built fixpoint_exprl recdefs
1788 in
1789 if register_built then
1790 ( register_mes interactive_proof fname.CAst.v rec_impls wf_mes wf_rel_opt
1791 (Option.map (fun x -> x.CAst.v) wf_x)
1792 using_lemmas binders rtype body pre_hook
1793 , true )
1794 else (None, true)
1795 | _ ->
1796 List.iter
1797 (function
1798 | Some { CAst.v = (Constrexpr.CMeasureRec _ | Constrexpr.CWfRec _) } ->
1799 CErrors.user_err
1800 (Pp.str
1801 "Cannot use mutual definition with well-founded recursion \
1802 or measure")
1803 | _ -> () )
1804 rec_order;
1805 let fixpoint_exprl = recompute_binder_list fix in
1806 let fix_names =
1807 List.map (function {Vernacexpr.fname} -> fname.CAst.v) fixpoint_exprl
1808 in
1809 (* ok all the expressions are structural *)
1810 let recdefs, _rec_impls = build_newrecursive fixpoint_exprl in
1811 let is_rec = List.exists (is_rec fix_names) recdefs in
1812 let lemma, evd, pconstants =
1813 if register_built then register_struct is_rec (rec_order, fixpoint_exprl)
1814 else (None, Evd.from_env (Global.env ()), pconstants)
1815 in
1816 let evd = ref evd in
1817 generate_principle (ref !evd) pconstants on_error false register_built
1818 fixpoint_exprl recdefs
1819 (Functional_principles_proofs.prove_princ_for_struct evd
1820 interactive_proof);
1821 if register_built then derive_inversion (Global.env ()) fix_names;
1822 (lemma, true)
1823 in
1824 lemma
1825
1826 let warn_cannot_define_graph =
1827 CWarnings.create ~name:"funind-cannot-define-graph" ~category:CWarnings.CoreCategories.funind
1828 (fun (names, error) ->
1829 Pp.(strbrk "Cannot define graph(s) for " ++ hv 1 names ++ error))
1830
1831 let warn_cannot_define_principle =
1832 CWarnings.create ~name:"funind-cannot-define-principle" ~category:CWarnings.CoreCategories.funind
1833 (fun (names, error) ->
1834 Pp.(
1835 strbrk "Cannot define induction principle(s) for " ++ hv 1 names ++ error))
1836
1837 let warning_error names e =
1838 let e_explain e =
1839 match e with
1840 | ToShow e -> Pp.(spc () ++ CErrors.print e)
1841 | _ -> if do_observe () then Pp.(spc () ++ CErrors.print e) else Pp.mt ()
1842 in
1843 match e with
1844 | Building_graph e ->
1845 let names =
1846 Pp.(prlist_with_sep (fun _ -> str "," ++ spc ()) Ppconstr.pr_id names)
1847 in
1848 warn_cannot_define_graph (names, e_explain e)
1849 | Defining_principle e ->
1850 let names =
1851 Pp.(prlist_with_sep (fun _ -> str "," ++ spc ()) Ppconstr.pr_id names)
1852 in
1853 warn_cannot_define_principle (names, e_explain e)
1854 | _ -> raise e
1855
1856 let error_error names e =
1857 let e_explain e =
1858 match e with
1859 | ToShow e -> Pp.(spc () ++ CErrors.print e)
1860 | _ -> if do_observe () then Pp.(spc () ++ CErrors.print e) else Pp.mt ()
1861 in
1862 match e with
1863 | Building_graph e ->
1864 CErrors.user_err
1865 Pp.(
1866 str "Cannot define graph(s) for "
1867 ++ hv 1
1868 (prlist_with_sep (fun _ -> str "," ++ spc ()) Ppconstr.pr_id names)
1869 ++ e_explain e)
1870 | _ -> raise e
1871
1872 (* [chop_n_arrow n t] chops the [n] first arrows in [t]
1873 Acts on Constrexpr.constr_expr
1874 *)
1875 let rec chop_n_arrow n t =
1876 let exception Stop of Constrexpr.constr_expr in
1877 let open Constrexpr in
1878 if n <= 0 then t
1879 (* If we have already removed all the arrows then return the type *)
1880 else
1881 (* If not we check the form of [t] *)
1882 match t.CAst.v with
1883 | Constrexpr.CProdN (nal_ta', t') -> (
1884 try
1885 (* If we have a forall, two results are possible :
1886 either we need to discard more than the number of arrows contained
1887 in this product declaration then we just recall [chop_n_arrow] on
1888 the remaining number of arrow to chop and [t'] we discard it and
1889 recall [chop_n_arrow], either this product contains more arrows
1890 than the number we need to chop and then we return the new type
1891 *)
1892 let new_n =
1893 let rec aux (n : int) = function
1894 | [] -> n
1895 | CLocalAssum (nal, _, k, t'') :: nal_ta' ->
1896 let nal_l = List.length nal in
1897 if n >= nal_l then aux (n - nal_l) nal_ta'
1898 else
1899 let new_t' =
1900 CAst.make
1901 @@ Constrexpr.CProdN
1902 ( CLocalAssum (snd (List.chop n nal), None, k, t'') :: nal_ta'
1903 , t' )
1904 in
1905 raise (Stop new_t')
1906 | _ -> CErrors.anomaly (Pp.str "Not enough products.")
1907 in
1908 aux n nal_ta'
1909 in
1910 chop_n_arrow new_n t'
1911 with Stop t -> t )
1912 | _ -> CErrors.anomaly (Pp.str "Not enough products.")
1913
1914 let rec add_args id new_args =
1915 let open Libnames in
1916 let open Constrexpr in
1917 CAst.map (function
1918 | CRef (qid, _) as b ->
1919 if qualid_is_ident qid && Id.equal (qualid_basename qid) id then
1920 CAppExpl ((qid, None), new_args)
1921 else b
1922 | CFix _ | CCoFix _ -> CErrors.anomaly ~label:"add_args " (Pp.str "todo.")
1923 | CProdN (nal, b1) ->
1924 CProdN
1925 ( List.map
1926 (function
1927 | CLocalAssum (nal, r, k, b2) ->
1928 CLocalAssum (nal, r, k, add_args id new_args b2)
1929 | CLocalDef (na, r, b1, t) ->
1930 CLocalDef
1931 ( na, r
1932 , add_args id new_args b1
1933 , Option.map (add_args id new_args) t )
1934 | CLocalPattern _ ->
1935 CErrors.user_err (Pp.str "pattern with quote not allowed here."))
1936 nal
1937 , add_args id new_args b1 )
1938 | CLambdaN (nal, b1) ->
1939 CLambdaN
1940 ( List.map
1941 (function
1942 | CLocalAssum (nal, r, k, b2) ->
1943 CLocalAssum (nal, r, k, add_args id new_args b2)
1944 | CLocalDef (na, r, b1, t) ->
1945 CLocalDef
1946 ( na, r
1947 , add_args id new_args b1
1948 , Option.map (add_args id new_args) t )
1949 | CLocalPattern _ ->
1950 CErrors.user_err (Pp.str "pattern with quote not allowed here."))
1951 nal
1952 , add_args id new_args b1 )
1953 | CLetIn (na, b1, t, b2) ->
1954 CLetIn
1955 ( na
1956 , add_args id new_args b1
1957 , Option.map (add_args id new_args) t
1958 , add_args id new_args b2 )
1959 | CAppExpl ((qid, us), exprl) ->
1960 if qualid_is_ident qid && Id.equal (qualid_basename qid) id then
1961 CAppExpl
1962 ((qid, us), new_args @ List.map (add_args id new_args) exprl)
1963 else CAppExpl ((qid, us), List.map (add_args id new_args) exprl)
1964 | CApp (b, bl) ->
1965 CApp
1966 ( add_args id new_args b
1967 , List.map (fun (e, o) -> (add_args id new_args e, o)) bl )
1968 | CProj (expl, f, bl, b) ->
1969 CProj
1970 (expl, f
1971 , List.map (fun (e, o) -> (add_args id new_args e, o)) bl
1972 , add_args id new_args b)
1973 | CCases (sty, b_option, cel, cal) ->
1974 CCases
1975 ( sty
1976 , Option.map (add_args id new_args) b_option
1977 , List.map
1978 (fun (b, na, b_option) -> (add_args id new_args b, na, b_option))
1979 cel
1980 , List.map
1981 CAst.(map (fun (cpl, e) -> (cpl, add_args id new_args e)))
1982 cal )
1983 | CLetTuple (nal, (na, b_option), b1, b2) ->
1984 CLetTuple
1985 ( nal
1986 , (na, Option.map (add_args id new_args) b_option)
1987 , add_args id new_args b1
1988 , add_args id new_args b2 )
1989 | CIf (b1, (na, b_option), b2, b3) ->
1990 CIf
1991 ( add_args id new_args b1
1992 , (na, Option.map (add_args id new_args) b_option)
1993 , add_args id new_args b2
1994 , add_args id new_args b3 )
1995 | (CHole _ | CGenarg _ | CGenargGlob _ | CPatVar _ | CEvar _ | CPrim _ | CSort _) as b -> b
1996 | CCast (b1, k, b2) ->
1997 CCast (add_args id new_args b1, k, add_args id new_args b2)
1998 | CRecord pars ->
1999 CRecord (List.map (fun (e, o) -> (e, add_args id new_args o)) pars)
2000 | CNotation _ -> CErrors.anomaly ~label:"add_args " (Pp.str "CNotation.")
2001 | CGeneralization _ ->
2002 CErrors.anomaly ~label:"add_args " (Pp.str "CGeneralization.")
2003 | CDelimiters _ ->
2004 CErrors.anomaly ~label:"add_args " (Pp.str "CDelimiters.")
2005 | CArray _ -> CErrors.anomaly ~label:"add_args " (Pp.str "CArray."))
2006
2007 let rec get_args b t :
2008 Constrexpr.local_binder_expr list
2009 * Constrexpr.constr_expr
2010 * Constrexpr.constr_expr =
2011 let open Constrexpr in
2012 match b.CAst.v with
2013 | Constrexpr.CLambdaN ((CLocalAssum (nal, _, k, ta) as d) :: rest, b') ->
2014 let n = List.length nal in
2015 let nal_tas, b'', t'' =
2016 get_args
2017 (CAst.make ?loc:b.CAst.loc @@ Constrexpr.CLambdaN (rest, b'))
2018 (chop_n_arrow n t)
2019 in
2020 (d :: nal_tas, b'', t'')
2021 | Constrexpr.CLambdaN ([], b) -> ([], b, t)
2022 | _ -> ([], b, t)
2023
2024 let make_graph (f_ref : GlobRef.t) =
2025 let open Constrexpr in
2026 let env = Global.env () in
2027 let sigma = Evd.from_env env in
2028 let c, c_body =
2029 match f_ref with
2030 | GlobRef.ConstRef c ->
2031 if Environ.mem_constant c env then (c, Environ.lookup_constant c env) else
2032 CErrors.user_err
2033 Pp.(
2034 str "Cannot find "
2035 ++ Termops.pr_global_env env (ConstRef c))
2036 | _ -> CErrors.user_err Pp.(str "Not a function reference")
2037 in
2038 match c_body.Declarations.const_body with
2039 | Undef _ | Primitive _ | Symbol _ | OpaqueDef _ -> CErrors.user_err (Pp.str "Cannot build a graph over an axiom!")
2040 | Def body ->
2041 let extern_body, extern_type =
2042 let flags = full_printing_flags() in
2043 ( Constrextern.extern_constr env sigma ~flags (EConstr.of_constr body)
2044 , Constrextern.extern_type env sigma ~flags
2045 (EConstr.of_constr (*FIXME*) c_body.Declarations.const_type) )
2046 in
2047 let nal_tas, b, t = get_args extern_body extern_type in
2048 let expr_list =
2049 match b.CAst.v with
2050 | Constrexpr.CFix (l_id, fixexprl) ->
2051 let l =
2052 List.map
2053 (fun (id, _, recexp, bl, t, b) ->
2054 let {CAst.loc; v = rec_id} =
2055 match Option.get recexp with
2056 | {CAst.v = CStructRec id} -> id
2057 | {CAst.v = CWfRec (id, _)} -> id
2058 | {CAst.v = CMeasureRec (oid, _, _)} -> Option.get oid
2059 in
2060 let new_args =
2061 List.flatten
2062 (List.map
2063 (function
2064 | Constrexpr.CLocalDef (na, _, _, _) -> []
2065 | Constrexpr.CLocalAssum (nal, _, _, _) ->
2066 List.map
2067 (fun {CAst.loc; v = n} ->
2068 CAst.make ?loc
2069 @@ CRef
2070 ( Libnames.qualid_of_ident ?loc
2071 @@ Nameops.Name.get_id n
2072 , None ))
2073 nal
2074 | Constrexpr.CLocalPattern _ -> assert false)
2075 nal_tas)
2076 in
2077 let b' = add_args id.CAst.v new_args b in
2078 Some (CAst.make (CStructRec (CAst.make rec_id))),
2079 { Vernacexpr.fname = id
2080 ; univs = None
2081 ; binders = nal_tas @ bl
2082 ; rtype = t
2083 ; body_def = Some b'
2084 ; notations = [] })
2085 fixexprl
2086 in
2087 l
2088 | _ ->
2089 let fname = CAst.make (Constant.label c) in
2090 [ None, { Vernacexpr.fname
2091 ; univs = None
2092 ; binders = nal_tas
2093 ; rtype = t
2094 ; body_def = Some b
2095 ; notations = [] } ]
2096 in
2097 let mp = Constant.modpath c in
2098 let expr_list = List.split expr_list in
2099 let pstate =
2100 do_generate_principle_aux [(c, UVars.Instance.empty)] error_error false
2101 false expr_list
2102 in
2103 assert (Option.is_empty pstate);
2104 (* We register the infos *)
2105 List.iter
2106 (fun {Vernacexpr.fname = {CAst.v = id}} ->
2107 add_Function false (Constant.make2 mp id))
2108 (snd expr_list)
2109
2110 (* *************** statically typed entrypoints ************************* *)
2111
2112 let do_generate_principle_interactive fixl : Declare.Proof.t =
2113 match do_generate_principle_aux [] warning_error true true fixl with
2114 | Some lemma -> lemma
2115 | None ->
2116 CErrors.anomaly (Pp.str "indfun: leaving no open proof in interactive mode")
2117
2118 let do_generate_principle fixl : unit =
2119 match do_generate_principle_aux [] warning_error true false fixl with
2120 | Some _lemma ->
2121 CErrors.anomaly
2122 (Pp.str "indfun: leaving a goal open in non-interactive mode")
2123 | None -> ()
2124
2125 let build_scheme fas =
2126 let env = Global.env () in
2127 let evd = ref (Evd.from_env env) in
2128 let pconstants =
2129 List.map
2130 (fun (_, f, sort) ->
2131 let f_as_constant =
2132 try Smartlocate.global_with_alias f
2133 with Not_found ->
2134 CErrors.user_err
2135 Pp.(str "Cannot find " ++ Libnames.pr_qualid f ++ str ".")
2136 in
2137 let evd', f = Evd.fresh_global env !evd f_as_constant in
2138 let _ = evd := evd' in
2139 let sigma, _ = Typing.type_of ~refresh:true env !evd f in
2140 evd := sigma;
2141 let c, u =
2142 try EConstr.destConst !evd f
2143 with Constr.DestKO ->
2144 CErrors.user_err
2145 Pp.(
2146 Printer.pr_econstr_env env !evd f
2147 ++ spc ()
2148 ++ str "should be the named of a globally defined function")
2149 in
2150 ((c, u), sort))
2151 fas
2152 in
2153 let bodies_types = make_scheme evd pconstants in
2154 List.iter2
2155 (fun (princ_id, _, _) (body, types, univs, opaque) ->
2156 let (_ : Constant.t) =
2157 let opaque = if opaque = Vernacexpr.Opaque then true else false in
2158 let def_entry = Declare.definition_entry ~univs ~opaque ~types body in
2159 Declare.declare_constant ?loc:princ_id.CAst.loc ~name:princ_id.CAst.v
2160 ~kind:Decls.(IsProof Theorem)
2161 (Declare.DefinitionEntry def_entry)
2162 in
2163 Declare.definition_message princ_id.v)
2164 fas bodies_types
2165
2166 let build_case_scheme fa =
2167 let env = Global.env () in
2168 let sigma = Evd.from_env env in
2169 (* let id_to_constr id = *)
2170 (* Constrintern.global_reference id *)
2171 (* in *)
2172 let funs =
2173 let _, f, _ = fa in
2174 try
2175 let open GlobRef in
2176 match Smartlocate.global_with_alias f with
2177 | ConstRef c -> c
2178 | IndRef _ | ConstructRef _ | VarRef _ -> assert false
2179 with Not_found ->
2180 CErrors.user_err
2181 Pp.(str "Cannot find " ++ Libnames.pr_qualid f ++ str ".")
2182 in
2183 let sigma, (_, u) = Evd.fresh_constant_instance env sigma funs in
2184 let first_fun = funs in
2185 let funs_mp = Constant.modpath first_fun in
2186 let first_fun_kn =
2187 match find_Function_infos first_fun with
2188 | None -> raise No_graph_found
2189 | Some finfos -> fst finfos.graph_ind
2190 in
2191 let this_block_funs_indexes = get_funs_constant funs_mp first_fun in
2192 let this_block_funs =
2193 Array.map (fun (c, _) -> (c, u)) this_block_funs_indexes
2194 in
2195 let funs_indexes =
2196 let this_block_funs_indexes = Array.to_list this_block_funs_indexes in
2197 let eq c1 c2 = Environ.QConstant.equal env c1 c2 in
2198 List.assoc_f eq funs this_block_funs_indexes
2199 in
2200 let ind, sf =
2201 let ind = (first_fun_kn, funs_indexes) in
2202 ((ind, EConstr.EInstance.empty) (*FIXME*), EConstr.ESorts.prop)
2203 in
2204 let dep = Elimschemes.default_case_analysis_dependence env (fst ind) in
2205 let sigma, scheme, scheme_type = Indrec.build_case_analysis_scheme env sigma ind dep sf in
2206 let sorts = (fun (_, _, x) ->
2207 EConstr.ESorts.make @@ fst @@ UnivGen.fresh_sort_in_quality x) fa in
2208 let princ_name = (fun (x, _, _) -> x) fa in
2209 let (_ : unit) =
2210 (* Pp.msgnl (str "Generating " ++ Ppconstr.pr_id princ_name ++str " with " ++
2211 pr_lconstr scheme_type ++ str " and " ++ (fun a -> prlist_with_sep spc (fun c -> pr_lconstr (mkConst c)) (Array.to_list a)) this_block_funs
2212 );
2213 *)
2214 generate_functional_principle
2215 (ref (Evd.from_env (Global.env ())))
2216 (EConstr.Unsafe.to_constr scheme_type)
2217 (Some [|sorts|])
2218 (Some princ_name) this_block_funs 0
2219 (Functional_principles_proofs.prove_princ_for_struct
2220 (ref (Evd.from_env (Global.env ())))
2221 false 0 [|funs|])
2222 in
2223 ()