Debian Codegraph @

vernac/comFixpoint.ml

raw symbols SCIP
1 (************************************************************************)
2 (* * The Rocq Prover / The Rocq Development Team *)
3 (* v * Copyright INRIA, CNRS and contributors *)
4 (* <O___,, * (see version control and CREDITS file for authors & dates) *)
5 (* \VV/ **************************************************************)
6 (* // * This file is distributed under the terms of the *)
7 (* * GNU Lesser General Public License Version 2.1 *)
8 (* * (see LICENSE file for the text of the license) *)
9 (************************************************************************)
10
11 module CVars = Vars
12
13 open Pp
14 open Util
15 open Names
16 open Context
17 open EConstr
18 open Constrexpr
19 open Constrintern
20 open Vernacexpr
21
22 module RelDecl = Context.Rel.Declaration
23 module NamedDecl = Context.Named.Declaration
24
25 (* 3c| Fixpoints and co-fixpoints *)
26
27 let check_duplicate fixlnames =
28 let rec first_dup eq prefix = function
29 | [] -> None
30 | x :: l ->
31 if List.mem_f eq x prefix then
32 Some x
33 else
34 first_dup eq (x :: prefix) l
35 in
36 match first_dup lident_eq [] fixlnames with
37 | None -> ()
38 | Some CAst.{ v=na; loc } ->
39 CErrors.user_err ?loc (str "An entry of name " ++ Id.print na ++
40 str " already exists in the mutual block.")
41
42 (* An (unoptimized) function that maps preorders to partial orders...
43
44 Input: a list of associations (x,[y1;...;yn]), all yi distincts
45 and different of x, meaning x<=y1, ..., x<=yn
46
47 Output: a list of associations (x,Inr [y1;...;yn]), collecting all
48 distincts yi greater than x, _or_, (x, Inl y) meaning that
49 x is in the same class as y (in which case, x occurs
50 nowhere else in the association map)
51
52 partial_order : ('a * 'a list) list -> ('a * ('a,'a list) union) list
53 *)
54
55 let rec partial_order cmp = function
56 | [] -> []
57 | (x,xge)::rest ->
58 let rec browse res xge' = function
59 | [] ->
60 let res = List.map (function
61 | (z, Inr zge) when List.mem_f cmp x zge ->
62 (z, Inr (List.union cmp zge xge'))
63 | r -> r) res in
64 (x,Inr xge')::res
65 | y::xge ->
66 let rec link y =
67 try match List.assoc_f cmp y res with
68 | Inl z -> link z
69 | Inr yge ->
70 if List.mem_f cmp x yge then
71 let res = List.remove_assoc_f cmp y res in
72 let res = List.map (function
73 | (z, Inl t) ->
74 if cmp t y then (z, Inl x) else (z, Inl t)
75 | (z, Inr zge) ->
76 if List.mem_f cmp y zge then
77 (z, Inr (List.add_set cmp x (List.remove cmp y zge)))
78 else
79 (z, Inr zge)) res in
80 browse ((y,Inl x)::res) xge' (List.union cmp xge yge)
81 else
82 browse res (List.add_set cmp y (List.union cmp xge' yge)) xge
83 with Not_found -> browse res (List.add_set cmp y xge') xge
84 in link y
85 in browse (partial_order cmp rest) [] xge
86
87 let string_of_kind = function
88 | Decls.IsDefinition Fixpoint -> "fixpoint"
89 | IsDefinition CoFixpoint -> "cofixpoint"
90 | _ -> "declaration"
91
92 let non_full_mutual_message x xge y yge kind rest =
93 let reason =
94 if Id.List.mem x yge then
95 Id.print y ++ str " depends on " ++ Id.print x ++ strbrk " but not conversely"
96 else if Id.List.mem y xge then
97 Id.print x ++ str " depends on " ++ Id.print y ++ strbrk " but not conversely"
98 else
99 Id.print y ++ str " and " ++ Id.print x ++ strbrk " are not mutually dependent" in
100 let e = if List.is_empty rest then reason else strbrk "e.g., " ++ reason in
101 let w =
102 if kind <> Decls.IsDefinition CoFixpoint
103 then strbrk "Well-foundedness check may fail unexpectedly." ++ fnl()
104 else mt () in
105 strbrk "Not a fully mutually defined " ++ str (string_of_kind kind) ++ fnl () ++
106 str "(" ++ e ++ str ")." ++ fnl () ++ w
107
108 let warn_non_full_mutual =
109 CWarnings.create ~name:"non-full-mutual" ~category:CWarnings.CoreCategories.fixpoints
110 (fun (x,xge,y,yge,kind,rest) ->
111 non_full_mutual_message x xge y yge kind rest)
112
113 let warn_non_recursive =
114 CWarnings.create ~name:"non-recursive" ~category:CWarnings.CoreCategories.fixpoints
115 (fun (x,kind) ->
116 strbrk "Not a truly recursive " ++ str (string_of_kind kind) ++ str ".")
117
118 let check_true_recursivity env evd ~kind fixl =
119 let names = List.map fst fixl in
120 let preorder =
121 List.map (fun (id,def) ->
122 (id.CAst.v, List.filter_map (fun {CAst.v=id'} -> if Termops.occur_var env evd id' def then Some id' else None) names))
123 fixl in
124 let po = partial_order Id.equal preorder in
125 match List.filter (function (_,Inr _) -> true | _ -> false) po with
126 | (x,Inr xge)::(y,Inr yge)::rest ->
127 warn_non_full_mutual (x,xge,y,yge,kind,rest)
128 | _ ->
129 match po with
130 | [x,Inr []] -> warn_non_recursive (x,kind)
131 | _ -> ()
132
133 (*****************************************************)
134 (* Utilities for Program Fixpoint with wf or measure *)
135
136 open Rocqlib
137 let init_constant sigma rf = Evd.fresh_global sigma rf
138 let fix_sub_ref () = lib_ref "program.wf.fix_sub"
139 let measure_on_R_ref () = lib_ref "program.wf.mr"
140 let well_founded sigma = init_constant (Global.env ()) sigma (lib_ref "core.wf.well_founded")
141 let mkSubset sigma name typ prop =
142 let open EConstr in
143 let sigma, app_h = Evd.fresh_global (Global.env ()) sigma (delayed_force build_sigma).typ in
144 sigma, mkApp (app_h, [| typ; mkLambda (make_annot name ERelevance.relevant, typ, prop) |])
145
146 let ensure_program () =
147 try fix_sub_ref (), measure_on_R_ref ()
148 with NotFoundRef r ->
149 CErrors.user_err
150 Pp.(str r ++ spc() ++ str "not registered," ++ spc() ++
151 str "you should try requiring library Corelib.Program.Wf.")
152
153 let recproofid = Id.of_string "recproof"
154 let argname = Id.of_string "recarg"
155
156 let encapsulate_Fix_sub env sigma recname ctx body ccl (extradecl, rel, relargty, measure_body) =
157 let len = Context.Rel.length ctx in
158 let fix_sub_ref, measure_on_R_ref = ensure_program () in
159 (* We curry the binders [x1:A1;...;xn:An] into [x:{x1&...&xn};x1:=x.1;...;xn:=x.2...2] *)
160 (* argtyp is [{x1&...&xn}], letbinders is [x1:=x.1;...;xn:=x.2...2], argvalue is [(x.1,...,x.2...2)] *)
161 let open Combinators in
162 let sigma, letbinders, {telescope_type = tuple_type; telescope_value = tuple_value} =
163 telescope env sigma ctx in
164 let tupled_ctx = letbinders @ [LocalAssum (make_annot (Name argname) ERelevance.relevant, tuple_type)] in
165 (* The function measure has type [tuple_type -> relargty] *)
166 let measure = it_mkLambda_or_LetIn measure_body tupled_ctx in
167 (* The relation wf_rel_measure is [fun x y => rel (measure x) (measure y)] *)
168 let sigma, comb = Evd.fresh_global (Global.env ()) sigma measure_on_R_ref in
169 let rel_measure = mkApp (comb, [| tuple_type; relargty; rel; measure |]) in
170 (* The statement that rel_measure is well-founded *)
171 let sigma, wf_term = well_founded sigma in
172 let wf_type = mkApp (wf_term, [| tuple_type ; rel_measure |]) in
173 (* A combinator building [rel (measure x) (measure y)] *)
174 let tupled_measure_body = it_mkLambda_or_LetIn measure_body letbinders in
175 let make_applied_rel x y =
176 mkApp (rel, [| Vars.subst1 x tupled_measure_body; Vars.subst1 y tupled_measure_body |]) in
177 (* Conclusion of fixpoint in currified context *)
178 let tupled_ccl = it_mkLambda_or_LetIn ccl letbinders in
179 (* Making Fix_sub ready to take the extended body as argument *)
180 let sigma, fix_sub =
181 let sigma, fix_sub_term = Evd.fresh_global (Global.env ()) sigma fix_sub_ref in
182 let typeclass_candidate = Typeclasses.is_maybe_class_type env sigma wf_type in
183 let sigma, wf_proof = Evarutil.new_evar ~typeclass_candidate env sigma
184 ~src:(Loc.tag @@ Evar_kinds.QuestionMark {
185 Evar_kinds.default_question_mark with Evar_kinds.qm_obligation=Evar_kinds.Define false;
186 }) wf_type in
187 let sigma = Evd.set_obligation_evar sigma (fst (destEvar sigma wf_proof)) in
188 let ccl_pred = mkLambda (make_annot (Name argname) ERelevance.relevant, tuple_type, tupled_ccl) in
189 let def = mkApp (fix_sub_term, [| tuple_type ; rel_measure ; wf_proof ; ccl_pred |]) in
190 Typing.solve_evars env sigma def in
191 let arg = RelDecl.LocalAssum (make_annot (Name argname) ERelevance.relevant, tuple_type) in
192 let argid' = Id.of_string (Id.to_string argname ^ "'") in
193 let sigma, wfa =
194 let sigma, ss_term = mkSubset sigma (Name argid') tuple_type (make_applied_rel (mkRel 1) (mkRel 2)) in
195 sigma, RelDecl.LocalAssum (make_annot (Name argid') ERelevance.relevant, ss_term) in
196 let sigma, fix_sub_F_sub_ctx =
197 let sigma, proj = Evd.fresh_global (Global.env ()) sigma (delayed_force build_sigma).Rocqlib.proj1 in
198 let wfargpred = mkLambda (make_annot (Name argid') ERelevance.relevant, tuple_type, make_applied_rel (mkRel 1) (mkRel 3)) in
199 let projection = (* in wfarg :: arg :: before *)
200 mkApp (proj, [| tuple_type ; wfargpred ; mkRel 1 |])
201 in
202 let ccl_on_smaller_arg = Vars.substl [projection] (it_mkLambda_or_LetIn ccl letbinders) in
203 (* substitute the projection of wfarg for something,
204 now ccl_let is in wfarg :: arg *)
205 let ccl_on_smaller_arg = it_mkProd_or_LetIn ccl_on_smaller_arg [wfa] in
206 let recname' = Nameops.add_suffix recname "'" in
207 let smaller_arg = RelDecl.LocalAssum (make_annot (Name recname') ERelevance.relevant,
208 ccl_on_smaller_arg) in
209 sigma, Vars.lift_rel_context 1 letbinders @ smaller_arg :: [arg] in
210 let sigma, curryfier_body, curryfier_ty =
211 (* In tupled_context where the function argument of Fix_sub (argid'), is inserted,
212 that is, all expanded: [recarg;argid';letbinders], build the curryfying combinator
213 [fun ctx (recproof : rel (measure ctx) (measure tupled_context)) => argid' (tuple_value,recproof)]
214 of type
215 [forall ctx (recproof : rel (measure ctx) (measure tupled_context)) => ccl] *)
216 let sigma, intro = Evd.fresh_global (Global.env ()) sigma (delayed_force build_sigma).Rocqlib.intro in
217 let app =
218 let wfpred = mkLambda (make_annot (Name argid') ERelevance.relevant, tuple_type, make_applied_rel (mkRel 1) (mkRel (2 * len + 4))) in
219 (* Build the sig pair [exist _ tuple_value recproof] *)
220 let arg = mkApp (intro, [| tuple_type; wfpred; Vars.lift 1 tuple_value; mkRel 1 |]) in
221 (* Build the body of combinator *)
222 mkApp (mkRel (2 * len + 2 (* recproof + orig binders + current binders *)), [| arg |]) in
223 let extended_ctx = extradecl :: ctx in
224 let body = it_mkLambda_or_LetIn app extended_ctx in
225 let ty = it_mkProd_or_LetIn (Vars.lift 1 ccl) extended_ctx in
226 sigma, body, ty in
227 (* Rephrase the body of the fixpoint as dependent in the telescope *)
228 let body_ctx = RelDecl.LocalDef (make_annot (Name recname) ERelevance.relevant, curryfier_body, curryfier_ty) :: fix_sub_F_sub_ctx in
229 let intern_body_lam = it_mkLambda_or_LetIn body body_ctx in
230 (* Instantiate the argument Fix_sub_F of Fix_sub with the body of the fixpoint *)
231 let sigma, fix_sub = Typing.solve_evars env sigma fix_sub in
232 sigma, tupled_ctx, tuple_value, mkApp (fix_sub, [|intern_body_lam|])
233
234 let build_wellfounded env sigma poly udecl {CAst.v=recname; loc} ctx body ccl impls rel_measure =
235 let len = Context.Rel.length ctx in
236 (* Restore body in the context of binders + extradecl *)
237 let _, body = decompose_lambda_n_decls sigma (len + 1) body in
238 (* Restore ccl in the context of binders *)
239 let ccl = Vars.subst1 (mkRel 1) (snd (decompose_prod_n_decls sigma (len + 1) ccl)) in
240 (* Apply the body to Program.Wf.Fix_sub *)
241 let sigma, tupled_ctx, tuple_value, def = encapsulate_Fix_sub env sigma recname ctx body ccl rel_measure in
242 (* Turn everything to constr *)
243 let ctx = Evarutil.nf_rel_context_evar sigma ctx in
244 let tupled_ctx = Evarutil.nf_rel_context_evar sigma tupled_ctx in
245 let ccl = Evarutil.nf_evar sigma ccl in
246 let tuple_value = Evarutil.nf_evar sigma tuple_value in
247 (* Decide if using a curryfied indirection via recname_func *)
248 let recname_func, typ =
249 if len > 1 then
250 Nameops.add_suffix recname "_func", it_mkProd_or_LetIn ccl tupled_ctx
251 else
252 recname, it_mkProd_or_LetIn ccl ctx in
253 let body, typ, _uctx, evmap, obls =
254 Declare.Obls.prepare_obligations ~name:recname_func poly ~body:def ~types:typ env sigma in
255 let hook, impls =
256 if len > 1 then
257 let hook { Declare.Hook.S.dref; uctx; obls; _ } =
258 let update c = CVars.replace_vars obls (evmap mkVar (Evarutil.nf_evar (Evd.from_ctx uctx) c)) in
259 let tuple_value = update tuple_value in
260 let ccl = update ccl in
261 let ctx = Context.Rel.map_het (ERelevance.kind sigma) update ctx in
262 let univs = UState.check_univ_decl ~poly uctx udecl in
263 let h_body =
264 let inst = UState.(match fst univs with
265 | Polymorphic_entry uctx -> UVars.UContext.instance uctx
266 | Monomorphic_entry _ -> UVars.Instance.empty) in
267 Constr.mkRef (dref, inst) in
268 let body = Term.it_mkLambda_or_LetIn (Constr.mkApp (h_body, [|tuple_value|])) ctx in
269 let ty = Term.it_mkProd_or_LetIn ccl ctx in
270 let ce = Declare.definition_entry ~types:ty ~univs body in
271 (* FIXME: include locality *)
272 let c = Declare.declare_constant ?loc ~name:recname ~kind:Decls.(IsDefinition Definition) (DefinitionEntry ce) in
273 let gr = GlobRef.ConstRef c in
274 if Impargs.is_implicit_args () || not (List.is_empty impls) then
275 Impargs.declare_manual_implicits false gr impls
276 in
277 Some (Declare.Hook.make hook), []
278 else
279 None, impls
280 in
281 sigma, CAst.make ?loc recname_func, body, typ, impls, obls, hook
282
283 (*********************************)
284 (* Interpretation of Co/Fixpoint *)
285
286 let make_qref s = Libnames.qualid_of_string s
287 let lt_ref = make_qref "Init.Peano.lt"
288
289 let position_of_argument ctx binders na =
290 let exception Found of int in
291 let name = Name na.CAst.v in
292 try
293 Context.Rel.fold_outside (fun decl n ->
294 match Context.Rel.Declaration.(get_value decl, Name.equal (get_name decl) name) with
295 | None, true -> raise (Found n)
296 | Some _, true ->
297 let loc = List.find_map (fun id -> if Name.equal name id.CAst.v then Some id.CAst.loc else None) (Constrexpr_ops.names_of_local_binders binders) in
298 let loc = Option.default na.CAst.loc loc in
299 CErrors.user_err ?loc
300 (Name.print name ++ str" must be a proper parameter and not a local definition.")
301 | None, false -> n + 1
302 | Some _, false -> n (* let-ins don't count *))
303 ~init:0 ctx |> ignore;
304 CErrors.user_err ?loc:na.loc
305 (str "No parameter named " ++ Id.print na.v ++ str".");
306 with
307 Found k -> k
308
309 (* Interpret the index of a recursion order annotation *)
310 let find_rec_annot ~program_mode ~function_mode env sigma Vernacexpr.{fname={CAst.loc}; binders} ctx typ = function
311 | None ->
312 let ctx', _ = Reductionops.whd_decompose_prod_decls (push_rel_context ctx env) sigma typ in
313 let n = Context.Rel.nhyps ctx + Context.Rel.nhyps ctx' in
314 if Int.equal n 0 then CErrors.user_err ?loc Pp.(str "A fixpoint needs at least one parameter.");
315 None, List.interval 0 (n - 1)
316 | Some CAst.{v=rec_order;loc} ->
317 let default_order r = Option.default (CAst.make @@ CRef (lt_ref,None)) r in
318 match rec_order with
319 | CStructRec na -> None, [position_of_argument ctx binders na]
320 | CWfRec (na,r) ->
321 if function_mode then None, []
322 else Some (r, Constrexpr_ops.mkIdentC na.CAst.v), [] (* useless for Program: will use Fix_sub *)
323 | CMeasureRec (na, mes, rfel) ->
324 if function_mode then
325 let _ = match binders, na with
326 | [CLocalDef({ CAst.v = Name id },_,_,_) | CLocalAssum([{ CAst.v = Name id }],_,_,_)], None -> ()
327 | _, None -> CErrors.user_err ?loc Pp.(str "Decreasing argument must be specified in measure clause.")
328 | _, Some na -> (* check that the name exists *) ignore (position_of_argument ctx binders na) in
329 (* Dummy *) None, []
330 else
331 let r = match na, rfel with
332 | Some id, None ->
333 let loc = id.CAst.loc in
334 CAst.make ?loc @@ CRef (Libnames.qualid_of_ident ?loc id.CAst.v,None)
335 | Some _, Some _ -> CErrors.user_err ?loc Pp.(str"Measure takes three arguments only in Function.")
336 | None, rfel -> default_order rfel in
337 Some (r, mes), [] (* useless: will use Fix_sub *)
338
339 let interp_rec_annot ~program_mode ~function_mode env sigma fixl ctxl ccll rec_order =
340 let open Pretyping in
341 let nowf () = List.map (fun _ -> None) fixl in
342 match rec_order with
343 (* If recursive argument was not given by user, we try all args.
344 An earlier approach was to look only for inductive arguments,
345 but doing it properly involves delta-reduction, and it finally
346 doesn't seem to worth the effort (except for huge mutual
347 fixpoints ?) *)
348 | CFixRecOrder fix_orders ->
349 let fixwf, possible_guard = List.split (List.map4 (find_rec_annot ~program_mode ~function_mode env sigma) fixl ctxl ccll fix_orders) in
350 fixwf, {possibly_cofix = false; possible_fix_indices = possible_guard}
351 | CCoFixRecOrder -> nowf (), {possibly_cofix = true; possible_fix_indices = List.map (fun _ -> []) fixl}
352 | CUnknownRecOrder -> nowf (), RecLemmas.find_mutually_recursive_statements sigma ctxl ccll
353
354 let interp_fix_context ~program_mode ~poly env sigma {Vernacexpr.binders} =
355 let sigma, (impl_env, ((env', ctx), imps, _locs)) = interp_context_evars ~program_mode env sigma binders in
356 sigma, (env', ctx, impl_env, imps)
357
358 let interp_fix_ccl ~program_mode ~poly sigma impls env fix =
359 let flags = Pretyping.{ all_no_fail_flags with program_mode ; poly } in
360 let sigma, (c, impl) = interp_type_evars_impls ~flags ~impls env sigma fix.Vernacexpr.rtype in
361 let r = Retyping.relevance_of_type env sigma c in
362 sigma, (c, r, impl)
363
364 let interp_fix_body ~program_mode env_rec ctx sigma impls fix ccl =
365 Option.cata (fun body ->
366 let env_rec_ctx = push_rel_context ctx env_rec in
367 let sigma, body = interp_casted_constr_evars ~program_mode env_rec_ctx sigma ~impls body ccl in
368 sigma, Some (it_mkLambda_or_LetIn body ctx)) (sigma, None) fix.Vernacexpr.body_def
369
370 let build_fix_type sigma ctx ccl (_, extradecl) =
371 let ccl = it_mkProd_or_LetIn (Vars.lift (Context.Rel.length extradecl) ccl) extradecl in
372 Evarutil.nf_evar sigma (it_mkProd_or_LetIn ccl ctx)
373
374 let build_dummy_fix_type sigma ctx ccl (_, extradecl) =
375 (* Hack: the extra declarations are smashed to a dummy non-dependent
376 so as not to contribute to the computation of implicit arguments *)
377 let ccl = it_mkProd_or_LetIn (Vars.lift (Context.Rel.length extradecl) ccl) (List.map (RelDecl.map_type (fun _ -> mkProp)) extradecl) in
378 Evarutil.nf_evar sigma (it_mkProd_or_LetIn ccl ctx)
379
380 (* Wellfounded definition *)
381
382 let encapsulate env sigma r t =
383 (* Would probably be overkill to use a specific fix_proto in SProp when in SProp?? *)
384 let fix_proto sigma =
385 Evd.fresh_global (Global.env ()) sigma (Rocqlib.lib_ref "program.tactic.fix_proto") in
386 let fix_proto_relevance = EConstr.ERelevance.relevant in
387 let sigma, sort = Typing.type_of ~refresh:true env sigma t in
388 try
389 let sigma, h_term = fix_proto sigma in
390 let app = EConstr.mkApp (h_term, [|sort; t|]) in
391 let sigma, app = Typing.solve_evars env sigma app in
392 sigma, fix_proto_relevance, app
393 with e when CErrors.noncritical e -> sigma, r, t
394
395 type ('constr, 'relevance) fix_data = {
396 fixnames : Names.lident list;
397 fixrs : 'relevance list;
398 fixdefs : 'constr option list;
399 fixtypes : 'constr list;
400 fixctxs : EConstr.rel_context list;
401 fiximps : (Names.Name.t * bool) option CAst.t list list;
402 fixntns : Metasyntax.notation_interpretation_decl list;
403 fixwfs : (rel_declaration * EConstr.t * EConstr.t * EConstr.t) option list;
404 }
405
406 let interp_wf ~program_mode env sigma recname ctx ccl = function
407 | None -> sigma, ((false, []), None, [])
408 | Some (r, measure) ->
409 (* We have to insert an argument for the measure/wellfoundedness *)
410 (* The extra implicit argument *)
411 let impl = CAst.make (Some (Name recproofid, true)) in
412 (* The well-founded relation *)
413 let env_ctx = push_rel_context ctx env in
414 let sigma, (rel, _) = interp_constr_evars_impls ~program_mode env sigma r in
415 let relargty = Hipattern.is_homogeneous_relation ?loc:(Constrexpr_ops.constr_loc r) env_ctx sigma rel in
416 (* The measure *)
417 let sigma, measure = interp_casted_constr_evars ~program_mode env_ctx sigma measure relargty in
418 let sigma, after, extradecl =
419 if program_mode then
420 let len = Context.Rel.length ctx in
421 let applied_rel_measure = mkApp (rel, [| measure; Vars.lift len measure |]) in
422 let extradecl = RelDecl.LocalAssum (make_annot (Name recproofid) ERelevance.relevant, applied_rel_measure) in
423 sigma, true, extradecl
424 else
425 let sigma, wf_term = well_founded sigma in
426 let applied_wf = mkApp (wf_term, [| relargty; rel |]) in
427 let extradecl = RelDecl.LocalAssum (make_annot (Name recproofid) ERelevance.relevant, applied_wf) in
428 sigma, false, extradecl
429 in
430 sigma, ((after, [extradecl]), Some (extradecl, rel, relargty, measure), [impl])
431
432 let interp_mutual_definition env ~program_mode ~poly ~function_mode rec_order fixl =
433 let open Context.Named.Declaration in
434 let open EConstr in
435 let fixlnames = List.map (fun fix -> fix.Vernacexpr.fname) fixl in
436 let fixnames = List.map (fun na -> na.CAst.v) fixlnames in
437 check_duplicate fixlnames;
438
439 (* Interp arities allowing for unresolved types *)
440 let sigma, decl = interp_mutual_univ_decl_opt env (List.map (fun Vernacexpr.{univs} -> univs) fixl) in
441 let sigma, (fixenv, fixctxs, fixctximpenvs, fixctximps) =
442 on_snd List.split4 @@
443 List.fold_left_map (fun sigma -> interp_fix_context ~program_mode ~poly env sigma) sigma fixl in
444 let sigma, (fixccls,fixrs,fixcclimps) =
445 on_snd List.split3 @@
446 List.fold_left3_map (interp_fix_ccl ~program_mode ~poly) sigma fixctximpenvs fixenv fixl in
447 let fixwfs, possible_guard = interp_rec_annot ~program_mode ~function_mode env sigma fixl fixctxs fixccls rec_order in
448 let sigma, (fixextras, fixwfs, fixwfimps) =
449 on_snd List.split3 @@ (List.fold_left4_map (interp_wf ~program_mode env) sigma fixnames fixctxs fixccls fixwfs) in
450 let fixtypes = List.map3 (build_fix_type sigma) fixctxs fixccls fixextras in
451 let sigma, rec_sign =
452 List.fold_left4
453 (fun (sigma, rec_sign) id r t (_,extradecl) ->
454 let sigma, r, t = if program_mode && List.is_empty extradecl then encapsulate env sigma r t else sigma, r, t in
455 sigma, LocalAssum (Context.make_annot id r, t) :: rec_sign)
456 (sigma, []) fixnames fixrs fixtypes fixextras
457 in
458 let fixrecimps = List.map3 (fun ctximps wfimps cclimps -> ctximps @ wfimps @ cclimps) fixctximps fixwfimps fixcclimps in
459 let fiximps = List.map2 (fun ctximps cclimps -> ctximps @ cclimps) fixctximps fixcclimps in
460
461 (* Interp bodies with rollback because temp use of notations/implicit *)
462 let fixntns = List.map_append (fun { Vernacexpr.notations } -> List.map Metasyntax.prepare_where_notation notations ) fixl in
463 let sigma, fixdefs =
464 let force = List.map (fun (_,extra) -> Id.Set.of_list (List.map_filter (fun d -> Nameops.Name.to_option (RelDecl.get_name d)) extra)) fixextras in
465 let dummy_fixtypes = List.map3 (build_dummy_fix_type sigma) fixctxs fixccls fixextras in
466 let impls = compute_internalization_env env sigma ~force Recursive fixnames dummy_fixtypes fixrecimps in
467 Metasyntax.with_syntax_protection (fun () ->
468 List.iter (Metasyntax.set_notation_for_interpretation env impls) fixntns;
469 List.fold_left5_map
470 (fun sigma fixctximpenv (after,extradecl) ctx body ccl ->
471 let impls = Id.Map.fold Id.Map.add fixctximpenv impls in
472 let env', ctx =
473 if after then env, List.map NamedDecl.to_rel_decl rec_sign @ ctx
474 else push_named_context rec_sign env, extradecl@ctx in
475 interp_fix_body ~program_mode env' ctx sigma impls body (Vars.lift (Context.Rel.length extradecl) ccl))
476 sigma fixctximpenvs fixextras fixctxs fixl fixccls)
477 () in
478
479 (* Build the fix declaration block *)
480 let fix = {fixnames=fixlnames;fixrs;fixdefs;fixtypes;fixctxs;fiximps;fixntns;fixwfs} in
481 (env, rec_sign, sigma), (fix, possible_guard, decl)
482
483 let check_recursive ~kind env evd {fixnames;fixdefs;fixwfs} =
484 (* TO MOVE AT FINAL DEFINITION TIME? *)
485 if List.for_all Option.has_some fixdefs && List.for_all Option.is_empty fixwfs then begin
486 let fixdefs = List.map Option.get fixdefs in
487 check_true_recursivity env evd ~kind (List.combine fixnames fixdefs)
488 end
489
490 let ground_fixpoint env evd {fixnames;fixrs;fixdefs;fixtypes;fixctxs;fiximps;fixntns;fixwfs} =
491 Pretyping.check_evars_are_solved ~program_mode:false env evd;
492 let fixrs = List.map (fun r -> EConstr.ERelevance.kind evd r) fixrs in
493 let fixdefs = List.map (fun c -> Option.map EConstr.(to_constr evd) c) fixdefs in
494 let fixtypes = List.map EConstr.(to_constr evd) fixtypes in
495 {fixnames;fixrs;fixdefs;fixtypes;fixctxs;fiximps;fixntns;fixwfs}
496
497 (** For Funind *)
498
499 let interp_fixpoint_short rec_order fixpoint_exprl =
500 let env = Global.env () in
501 let poly = PolyFlags.default in
502 let (_, _, sigma),(fix, _, _) = interp_mutual_definition ~program_mode:false ~poly ~function_mode:true env (CFixRecOrder rec_order) fixpoint_exprl in
503 (* Instantiate evars and check all are resolved *)
504 let sigma = Evarconv.solve_unif_constraints_with_heuristics env sigma in
505 let sigma = Evd.minimize_universes sigma in
506 let sigma = Pretyping.(solve_remaining_evars all_no_fail_flags env sigma) in
507 let typel = (ground_fixpoint env sigma fix).fixtypes in
508 typel, sigma
509
510 let build_recthms {fixnames;fixtypes;fixctxs;fiximps} =
511 List.map4 (fun {CAst.v=name; loc} typ ctx impargs ->
512 let args = List.map Context.Rel.Declaration.get_name ctx in
513 Declare.CInfo.make ?loc ~name ~typ ~args ~impargs ()
514 ) fixnames fixtypes fixctxs fiximps
515
516 let collect_evars_of_term evd c ty =
517 Evar.Set.union (Evd.evars_of_term evd c) (Evd.evars_of_term evd ty)
518
519 let collect_evars env sigma rec_sign recname def typ =
520 (* Generalize by the recursive prototypes *)
521 let deps = collect_evars_of_term sigma def typ in
522 let evars, _, def, typ =
523 RetrieveObl.retrieve_obligations env recname.CAst.v sigma
524 (List.length rec_sign) ~deps def typ in
525 (Some def, typ, evars)
526
527 let out_def = function
528 | Some def -> def
529 | None -> CErrors.user_err Pp.(str "Program Fixpoint needs defined bodies.")
530
531 let build_program_fixpoint env sigma rec_sign possible_guard fixnames fixrs fixdefs fixtypes fixwfs =
532 let () = if not @@ List.for_all Option.is_empty fixwfs then
533 CErrors.user_err Pp.(str "Well-founded fixpoints not allowed in mutually recursive blocks.")
534 in
535 (* Get the interesting evars, those that were not instantiated *)
536 let sigma = Typeclasses.resolve_typeclasses ~filter:Typeclasses.no_goals ~fail:true env sigma in
537 (* Solve remaining evars *)
538 let sigma = Evarutil.nf_evar_map_undefined sigma in
539 let fixdefs = List.map out_def fixdefs in
540 (* An early check of guardedness before working on the obligations *)
541 let () =
542 let fixdecls =
543 Array.of_list (List.map2 (fun x r -> Context.make_annot (Name x.CAst.v) r) fixnames fixrs),
544 Array.of_list fixtypes,
545 Array.of_list fixdefs
546 in
547 ignore (Pretyping.esearch_guard env sigma possible_guard fixdecls) in
548 List.split3 (List.map3 (collect_evars env sigma rec_sign) fixnames fixdefs fixtypes)
549
550 let finish_obligations env sigma rec_sign possible_guard poly udecl = function
551 | {fixnames=[recname];fixrs;fixdefs=[body];fixtypes=[ccl];fixctxs=[ctx];fiximps=[imps];fixntns;fixwfs=[Some wf]} ->
552 let sigma = Evarutil.nf_evar_map sigma in (* use nf_evar_map_undefined?? *)
553 let sigma, recname, body, ccl, impls, obls, hook = build_wellfounded env sigma poly udecl recname ctx (Option.get body) ccl imps wf in
554 let fixrs = List.map (EConstr.ERelevance.kind sigma) fixrs in
555 sigma, {fixnames=[recname];fixrs;fixdefs=[Some body];fixtypes=[ccl];fixctxs=[ctx];fiximps=[impls];fixntns;fixwfs=[Some wf]}, [obls], hook
556 | {fixnames;fixrs;fixdefs;fixtypes;fixctxs;fiximps;fixntns;fixwfs} ->
557 let fixdefs, fixtypes, obls = build_program_fixpoint env sigma rec_sign possible_guard fixnames fixrs fixdefs fixtypes fixwfs in
558 let fixrs = List.map (EConstr.ERelevance.kind sigma) fixrs in
559 sigma, {fixnames;fixrs;fixdefs;fixtypes;fixctxs;fiximps;fixntns;fixwfs}, obls, None
560
561 let finish_regular env sigma use_inference_hook fix =
562 let inference_hook = if use_inference_hook then Some Declare.Obls.program_inference_hook else None in
563 let sigma = Pretyping.(solve_remaining_evars ?hook:inference_hook all_no_fail_flags env sigma) in
564 sigma, ground_fixpoint env sigma fix, [], None
565
566 let do_mutually_recursive ?pm ~refine ~program_mode ?(use_inference_hook=false) ?scope ?clearbody ~kind ~poly ?typing_flags ?user_warns ?using (rec_order, fixl)
567 : Declare.OblState.t option * Declare.Proof.t option =
568 let env = Global.env () in
569 let env = Environ.update_typing_flags ?typing_flags env in
570 let (env,rec_sign,sigma),(fix,possible_guard,udecl) = interp_mutual_definition env ~program_mode ~poly ~function_mode:false rec_order fixl in
571 check_recursive ~kind env sigma fix;
572
573 if refine then
574 let info = Declare.Info.make ?scope ?clearbody ~kind ~poly ~udecl ?typing_flags ?user_warns ~ntns:fix.fixntns () in
575 let cinfo = build_recthms fix in
576 let possible_guard = (possible_guard, fix.fixrs) in
577 let lemma = Declare.Proof.start_mutual_definitions_refine ~info ~cinfo ~bodies:fix.fixdefs ~possible_guard ?using sigma in
578 None, Some lemma
579 else
580
581 (* Instantiate evars and check all are resolved *)
582 let sigma = Evarconv.solve_unif_constraints_with_heuristics env sigma in
583 let sigma = Evd.minimize_universes sigma in
584
585 let sigma, ({fixdefs=bodies;fixrs;fixtypes;fixwfs} as fix), obls, hook =
586 match pm with
587 | Some pm -> finish_obligations env sigma rec_sign possible_guard poly udecl fix
588 | None -> finish_regular env sigma use_inference_hook fix in
589 let info = Declare.Info.make ?scope ?clearbody ~kind ~poly ~udecl ?hook ?typing_flags ?user_warns ~ntns:fix.fixntns () in
590 let cinfo = build_recthms fix in
591 match pm with
592 | Some pm ->
593 (* Program Fixpoint struct *)
594 let bodies = List.map Option.get bodies in
595 Evd.check_univ_decl_early ~poly ~with_obls:true sigma udecl (bodies @ fixtypes);
596 let sigma = if PolyFlags.univ_poly poly then sigma else Evd.fix_undefined_variables sigma in
597 let uctx = Evd.ustate sigma in
598 (* FIXME? something should probably be done with sigma's side-effects here *)
599 (match fixwfs, bodies, cinfo, obls with
600 | [Some _], [body], [cinfo], [obls] ->
601 (* Program Fixpoint wf/measure *)
602 let pm = Declare.Obls.add_definition ~pm ~cinfo ~info ~opaque:false ~body ~uctx ?using obls in
603 Some pm, None
604 | _ ->
605 let possible_guard = (possible_guard, fixrs) in
606 Some (Declare.Obls.add_mutual_definitions ~pm ~cinfo ~info ~opaque:false ~uctx ~bodies ~possible_guard ?using obls), None)
607 | None ->
608 match Option.List.map (fun x -> x) bodies with
609 | Some bodies ->
610 let uctx = Evd.ustate sigma in
611 let eff = Evd.eval_side_effects sigma in
612 (* All bodies are defined *)
613 let possible_guard = (possible_guard, fixrs) in
614 let _ : GlobRef.t list =
615 Declare.declare_mutual_definitions ~cinfo ~info ~opaque:false ~eff ~uctx ~possible_guard ~bodies ?using ()
616 in
617 None, None
618 | None ->
619 (* At least one undefined body *)
620 Evd.check_univ_decl_early ~poly ~with_obls:false sigma udecl (Option.List.flatten bodies @ fixtypes);
621 let possible_guard = (possible_guard, fixrs) in
622 let lemma = Declare.Proof.start_mutual_definitions ~info ~cinfo ~bodies ~possible_guard ?using sigma in
623 None, Some lemma