Debian Codegraph @

vernac/declare.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 (** This module is about the low-level declaration of logical objects *)
12
13 open Pp
14 open Util
15 open Names
16 open Safe_typing
17 module NamedDecl = Context.Named.Declaration
18
19 (* Hooks naturally belong here as they apply to both definitions and lemmas *)
20 module Hook = struct
21 module S = struct
22 type t =
23 { uctx : UState.t
24 (** [ustate]: universe constraints obtained when the term was closed *)
25 ; obls : (Names.Id.t * Constr.t) list
26 (** [(n1,t1),...(nm,tm)]: association list between obligation
27 name and the corresponding defined term (might be a constant,
28 but also an arbitrary term in the Expand case of obligations) *)
29 ; scope : Locality.definition_scope
30 (** [locality]: Locality of the original declaration *)
31 ; dref : Names.GlobRef.t
32 (** [ref]: identifier of the original declaration *)
33 }
34 end
35
36 type 'a g = (S.t -> 'a -> 'a) CEphemeron.key
37 type t = unit g
38
39 let make_g hook = CEphemeron.create hook
40 let make (hook : S.t -> unit) : t = CEphemeron.create (fun x () -> hook x)
41
42 let hcall hook x s = CEphemeron.default hook (fun _ x -> x) x s
43
44 let call_g ?hook x s = Option.cata (fun hook -> hcall hook x s) s hook
45 let call ?hook x = Option.iter (fun hook -> hcall hook x ()) hook
46
47 end
48
49 let warn_using_fallback_loc = CWarnings.create ~name:"using-fallback-loc" ~category:CWarnings.CoreCategories.internal ~default:Disabled
50 Pp.(fun name -> str "Using fallback loc for " ++ Id.print name ++ str ".")
51
52 let fallback_loc ?(warn=true) name = function
53 | Some _ as loc -> loc
54 | None -> match Loc.get_current_command_loc () with
55 | None -> None
56 | Some _ as loc ->
57 let () = if warn then warn_using_fallback_loc name in
58 loc
59
60 module CInfo = struct
61
62 type 'constr t =
63 { name : Id.t
64 (** Name of theorem *)
65 ; typ : 'constr
66 (** Type of theorem *)
67 ; args : Name.t list
68 (** Names to pre-introduce *)
69 ; impargs : Impargs.manual_implicits
70 (** Explicitily declared implicit arguments *)
71 ; loc : Loc.t option
72 }
73
74
75 let make ?loc ~name ~typ ?(args=[]) ?(impargs=[]) () =
76 let loc = fallback_loc name loc in
77 { name; typ; args; impargs; loc }
78
79 let to_constr sigma thm = { thm with typ = EConstr.to_constr sigma thm.typ }
80
81 let get_typ { typ; _ } = typ
82 let get_name { name; _ } = name
83
84 end
85
86 (** Information for a declaration, interactive or not, includes
87 parameters shared by mutual constants *)
88 module Info = struct
89
90 type t =
91 { poly : PolyFlags.t
92 ; inline : bool
93 ; kind : Decls.logical_kind
94 ; udecl : UState.universe_decl
95 ; scope : Locality.definition_scope
96 ; clearbody : bool (* always false for non Discharge scope *)
97 ; hook : Hook.t option
98 ; typing_flags : Declarations.typing_flags option
99 ; user_warns : Globnames.extended_global_reference UserWarn.with_qf option
100 ; ntns : Metasyntax.notation_interpretation_decl list
101 }
102
103 (** Note that [opaque] doesn't appear here as it is not known at the
104 start of the proof in the interactive case. *)
105 let make ?(poly = PolyFlags.default) ?(inline=false) ?(kind=Decls.(IsDefinition Definition))
106 ?(udecl=UState.default_univ_decl) ?(scope=Locality.default_scope)
107 ?(clearbody=false) ?hook ?typing_flags ?user_warns ?(ntns=[]) () =
108 { poly; inline; kind; udecl; scope; hook; typing_flags; clearbody; user_warns; ntns }
109 end
110
111 module SideEff :
112 sig
113 type t
114 val empty : t
115 val make : Evd.side_effects -> t
116 val concat : t -> t -> t
117 val get : t -> Safe_typing.private_constants
118 val obj : t -> (Evd.side_effect_role option * UState.named_universes_entry option) Cmap_env.t
119 end =
120 struct
121
122 type t = {
123 priv : Safe_typing.private_constants;
124 data : (Evd.side_effect_role option * UState.named_universes_entry option) Cmap_env.t;
125 }
126
127 let empty = {
128 priv = Safe_typing.empty_private_constants;
129 data = Cmap_env.empty;
130 }
131
132 let make eff =
133 let fold accu c =
134 let role = try Some (Cmap_env.find c (Evd.seff_roles eff)) with Not_found -> None in
135 let univs = try Some (Cmap_env.find c (Evd.seff_univs eff)) with Not_found -> None in
136 Cmap_env.add c (role, univs) accu
137 in
138 let priv = Evd.seff_private eff in
139 let data = List.fold_left fold Cmap_env.empty (Safe_typing.constants_of_private priv) in
140 { priv; data }
141
142 let concat e1 e2 = {
143 priv = Safe_typing.concat_private e1.priv e2.priv;
144 data = Cmap_env.union (fun _ x y -> Some x) e1.data e2.data;
145 }
146
147 let get e = e.priv
148 let obj e = e.data
149
150 end
151
152 (** Declaration of constants and parameters *)
153
154 (* Deferred proofs: monomorphic, opaque, and udecl is for body+type *)
155 type 'eff deferred_opaque_proof_body = {
156 body : ((Constr.t * Univ.ContextSet.t) * 'eff) Future.computation;
157 feedback_id : Stateid.t option
158 (* State id on which the completion of type checking is reported *)
159 }
160
161 (* Opacity of default proofs, possibly with private universes *)
162 type default_body_opacity =
163 | Transparent
164 (* udecl is for body+type; all universes are in proof_entry_universes *)
165 | Opaque of Univ.ContextSet.t * SideEff.t
166 (* if poly, the private uctx, udecl excludes the private uctx *)
167 (* if mono, the body uctx *)
168
169 (* Default (non-deferred) proofs/definitions, possibly with effects *)
170 type default_proof_body = {
171 body : Constr.t;
172 opaque : default_body_opacity
173 }
174
175 (* A proof body is either immediate or deferred *)
176 type 'eff proof_body =
177 | DeferredOpaque of 'eff deferred_opaque_proof_body
178 | Default of default_proof_body
179
180 (* A proof entry, parameterized with its kind of proof body *)
181 type 'body pproof_entry = {
182 proof_entry_body : 'body;
183 proof_entry_secctx : Id.Set.t option;
184 (* List of section variables *)
185 proof_entry_type : Constr.types option;
186 (* the initial type if deferred *)
187 proof_entry_universes : UState.named_universes_entry;
188 (* refers to:
189 - the initial uctx if opaque deferred;
190 - the uctx of type only if opaque private;
191 - the full uctx otherwise *)
192 proof_entry_inline_code : bool;
193 }
194
195 (* The most general form of proof entry *)
196 type proof_entry = SideEff.t proof_body pproof_entry
197
198 type parameter_entry = {
199 parameter_entry_secctx : Id.Set.t option;
200 parameter_entry_type : Constr.types;
201 parameter_entry_universes : UState.named_universes_entry;
202 parameter_entry_inline_code : Entries.inline;
203 }
204
205 type primitive_entry = {
206 prim_entry_type : (Constr.types * UState.named_universes_entry) option;
207 prim_entry_content : CPrimitives.op_or_type;
208 }
209
210 type symbol_entry = {
211 symb_entry_type : Constr.types;
212 symb_entry_unfold_fix: bool;
213 symb_entry_universes : UState.named_universes_entry;
214 }
215
216 let default_univ_entry = UState.Monomorphic_entry Univ.ContextSet.empty
217 let default_named_univ_entry = default_univ_entry, UnivNames.empty_binders
218
219 let extract_monomorphic = function
220 | UState.Monomorphic_entry ctx ->
221 Entries.Monomorphic_entry, ctx
222 | UState.Polymorphic_entry uctx -> Entries.Polymorphic_entry uctx, Univ.ContextSet.empty
223
224 let instance_of_univs = function
225 | UState.Monomorphic_entry _, _ -> UVars.Instance.empty
226 | UState.Polymorphic_entry uctx, _ -> UVars.UContext.instance uctx
227
228 let add_mono_uctx uctx = function
229 | UState.Monomorphic_entry ctx, ubinders ->
230 let uctx = UState.check_mono_sort_constraints uctx in
231 UState.Monomorphic_entry (Univ.ContextSet.union uctx ctx), ubinders
232 | UState.Polymorphic_entry _, _ as x -> assert (UnivGen.is_empty_sort_context (UState.sort_context_set uctx)); x
233
234 let make_ubinders uctx (univs, ubinders as u) = match univs with
235 | UState.Monomorphic_entry _ -> (UState.Monomorphic_entry uctx, ubinders)
236 | UState.Polymorphic_entry _ -> u
237
238 let { Goptions.get = private_poly_univs } =
239 Goptions.declare_bool_option_and_ref
240 ~key:["Private";"Polymorphic";"Universes"]
241 ~value:true
242 ()
243
244 let universes_of_body_type ~used_univs body typ =
245 let used_univs_typ = Option.cata (Vars.universes_of_constr ~init:used_univs) used_univs typ in
246 let used_univs = Vars.universes_of_constr body ~init:used_univs_typ in
247 used_univs_typ, used_univs
248
249 let make_univs_deferred_private_mono ~initial_euctx ?feedback_id ~uctx ~udecl body typ =
250 let _, used_univs = universes_of_body_type ~used_univs:Univ.Level.Set.empty body typ in
251 let uctx = UState.constrain_variables (fst (UState.universe_context_set initial_euctx)) uctx in
252 (* For vi2vo compilation proofs are computed now but we need to
253 complement the univ constraints of the typ with the ones of
254 the body. So we keep the two sets distinct. *)
255 let uctx_body = UState.restrict uctx used_univs in
256 UState.check_mono_univ_decl uctx_body udecl
257
258 let make_univs_immediate_private_mono ~initial_euctx ~uctx ~udecl ~eff ~used_univs body typ =
259 let utyp = UState.univ_entry ~poly:PolyFlags.default initial_euctx in
260 let _, used_univs = universes_of_body_type ~used_univs body typ in
261 let ubody =
262 let uctx = UState.constrain_variables (fst (UState.universe_context_set initial_euctx)) uctx in
263 (* For vi2vo compilation proofs are computed now but we need to
264 complement the univ constraints of the typ with the ones of
265 the body. So we keep the two sets distinct. *)
266 let uctx_body = UState.restrict uctx used_univs in
267 UState.check_mono_univ_decl uctx_body udecl in
268 initial_euctx, utyp, used_univs, Default { body; opaque = Opaque (ubody, eff) }
269
270 let make_univs_immediate_private_poly ~poly ~uctx ~udecl ~eff ~used_univs body typ =
271 let used_univs_typ, used_univs = universes_of_body_type ~used_univs body typ in
272 let uctx' = UState.restrict uctx used_univs_typ in
273 let utyp = UState.check_univ_decl ~poly uctx' udecl in
274 let ubody =
275 let uctx = UState.restrict uctx used_univs in
276 (* XXX we don't check anything on sort variables *)
277 let (_qs, us), (qcst, ucst) = UState.sort_context_set uctx in
278 let (_qs', us'), (qcst', ucst') = UState.sort_context_set uctx' in
279 let uctx = Univ.ContextSet.diff (us, ucst) (us', ucst') in
280 (* XXX we should have a more principled check somewhere *)
281 let () = assert (Sorts.ElimConstraints.is_empty @@ Sorts.ElimConstraints.diff qcst qcst') in
282 uctx
283 in
284 uctx', utyp, used_univs, Default { body = body; opaque = Opaque (ubody, eff) }
285
286 let make_univs_immediate_default ~poly ~opaque ~uctx ~udecl ~eff ~used_univs body typ =
287 let _, used_univs = universes_of_body_type ~used_univs body typ in
288 (* Since the proof is computed now, we can simply have 1 set of
289 constraints in which we merge the ones for the body and the ones
290 for the typ. We recheck the declaration after restricting with
291 the actually used universes.
292 TODO: check if restrict is really necessary now. *)
293 let uctx = UState.restrict uctx used_univs in
294 let utyp = UState.check_univ_decl ~poly uctx udecl in
295 let utyp = match fst utyp with
296 | Polymorphic_entry _ -> utyp
297 | Monomorphic_entry uctx ->
298 (* the constraints from the body may depend on universes from
299 the side effects, so merge it all together.
300 Example failure if we don't is "l1" in test-suite/success/rewrite.v.
301
302 Not sure if it makes more sense to merge them in the ustate
303 before restrict/check_univ_decl or here. Since we only do it
304 when monomorphic it shouldn't really matter. *)
305 let puctx = Safe_typing.universes_of_private (SideEff.get eff) in
306 Monomorphic_entry (Univ.ContextSet.union uctx puctx), snd utyp
307 in
308 uctx, utyp, used_univs, Default { body; opaque = if opaque then Opaque (Univ.ContextSet.empty, eff) else Transparent }
309
310 let make_univs_immediate ~poly ?keep_body_ucst_separate ~opaque ~uctx ~udecl ~eff ~used_univs body typ =
311 (* allow_deferred case *)
312 match keep_body_ucst_separate with
313 | Some initial_euctx when not (PolyFlags.univ_poly poly) ->
314 make_univs_immediate_private_mono ~initial_euctx ~uctx ~udecl ~eff ~used_univs body typ
315 | _ ->
316 (* private_poly_univs case *)
317 if PolyFlags.univ_poly poly && opaque && private_poly_univs ()
318 then make_univs_immediate_private_poly ~poly ~uctx ~udecl ~eff ~used_univs body typ
319 else make_univs_immediate_default ~poly ~opaque ~uctx ~udecl ~eff ~used_univs body typ
320
321 (** [univsbody] are universe-constraints attached to the body-only,
322 used in vio-delayed opaque constants and private poly universes *)
323 let definition_entry_core ?using ?(inline=false) ?types
324 ?(univs=default_named_univ_entry) body =
325 { proof_entry_body = body;
326 proof_entry_secctx = using;
327 proof_entry_type = types;
328 proof_entry_universes = univs;
329 proof_entry_inline_code = inline}
330
331 let pure_definition_entry ?(opaque=Transparent) ?using ?inline ?types ?univs body =
332 definition_entry_core ?using ?inline ?types ?univs body
333
334 let definition_entry ?(opaque=false) ?using ?inline ?types ?univs body =
335 let opaque = if opaque then Opaque (Univ.ContextSet.empty, SideEff.empty) else Transparent in
336 definition_entry_core ?using ?inline ?types ?univs (Default { body; opaque })
337
338 let delayed_definition_entry ?feedback_id ?using ~univs ?types body =
339 definition_entry_core ?using ?types ~univs (DeferredOpaque { body; feedback_id })
340
341 let parameter_entry ?inline ?(univs=default_named_univ_entry) typ = {
342 parameter_entry_secctx = None;
343 parameter_entry_type = typ;
344 parameter_entry_universes = univs;
345 parameter_entry_inline_code = inline;
346 }
347
348 let primitive_entry ?types c = {
349 prim_entry_type = types;
350 prim_entry_content = c;
351 }
352
353 let symbol_entry ?(univs=default_named_univ_entry) ~unfold_fix symb_entry_type = {
354 symb_entry_universes = univs;
355 symb_entry_unfold_fix = unfold_fix;
356 symb_entry_type;
357 }
358
359 type constant_entry =
360 | DefinitionEntry of proof_entry
361 | ParameterEntry of parameter_entry
362 | PrimitiveEntry of primitive_entry
363 | SymbolEntry of symbol_entry
364
365 module ProofEntry = struct
366
367 let map_entry_body ~f = function
368 | Default { body = body; opaque } -> Default { body = f body; opaque }
369 | DeferredOpaque { body; feedback_id } ->
370 let body = Future.chain body (fun ((b,c),eff) -> ((f b, c), eff)) in
371 DeferredOpaque { body; feedback_id }
372
373 let map_entry ~f entry =
374 { entry with
375 proof_entry_body = map_entry_body ~f entry.proof_entry_body;
376 proof_entry_type = Option.map f entry.proof_entry_type }
377
378 let get_opacity entry =
379 match entry.proof_entry_body with
380 | Default { body; opaque = Transparent } -> false
381 | Default { body; opaque = Opaque _ } -> true
382 | DeferredOpaque _ -> true
383
384 let force_entry_body entry =
385 match entry.proof_entry_body with
386 | Default { body; opaque } -> body, opaque
387 | DeferredOpaque { body; feedback_id = Some _ } -> CErrors.anomaly (str "Forcing a proof with feedback")
388 | DeferredOpaque { body; feedback_id = None } ->
389 let (body, uctx), eff = Future.force body in
390 body, Opaque (uctx, eff)
391
392 let force_extract_body entry =
393 match entry.proof_entry_body with
394 | Default { body; opaque = Transparent } -> ((body, Univ.ContextSet.empty), SideEff.empty), false, None
395 | Default { body; opaque = Opaque (uctx, eff) } -> ((body, uctx), eff), true, None
396 | DeferredOpaque { body; feedback_id } -> Future.force body, true, feedback_id
397
398 end
399
400 let local_csts = Summary.ref ~name:"local-csts" Cset_env.empty
401
402 let is_local_constant c = Cset_env.mem c !local_csts
403
404 type constant_obj = {
405 cst_kind : Decls.logical_kind;
406 cst_locl : Locality.import_status;
407 cst_warn : Globnames.extended_global_reference UserWarn.with_qf option;
408 cst_loc : Loc.t option;
409 }
410
411 let load_constant i ((sp,kn), obj) =
412 if Nametab.exists_cci sp then
413 raise (DeclareUniv.AlreadyDeclared (None, Libnames.basename sp));
414 let con = Global.constant_of_delta_kn kn in
415 let gr = GlobRef.ConstRef con in
416 Nametab.push ?user_warns:obj.cst_warn (Nametab.Until i) sp gr;
417 Dumpglob.add_constant_kind con obj.cst_kind;
418 obj.cst_loc |> Option.iter (fun loc -> Nametab.set_cci_src_loc (TrueGlobal gr) loc);
419 begin match obj.cst_locl with
420 | Locality.ImportNeedQualified -> local_csts := Cset_env.add con !local_csts
421 | Locality.ImportDefaultBehavior -> ()
422 end
423
424 (* Opening means making the name without its module qualification available *)
425 let open_constant i ((sp,kn), obj) =
426 (* Never open a local definition *)
427 match obj.cst_locl with
428 | Locality.ImportNeedQualified -> ()
429 | Locality.ImportDefaultBehavior ->
430 let con = Global.constant_of_delta_kn kn in
431 Nametab.push (Nametab.Exactly i) sp (GlobRef.ConstRef con)
432
433 let exists_name id =
434 Decls.variable_exists id || Global.exists_objlabel id
435
436 let check_exists id =
437 if exists_name id then
438 raise (DeclareUniv.AlreadyDeclared (None, id))
439
440 let cache_constant ((sp,kn), obj) =
441 let kn = Global.constant_of_delta_kn kn in
442 let gr = GlobRef.ConstRef kn in
443 Nametab.push ?user_warns:obj.cst_warn (Nametab.Until 1) sp gr;
444 Dumpglob.add_constant_kind kn obj.cst_kind;
445 obj.cst_loc |> Option.iter (fun loc -> Nametab.set_cci_src_loc (TrueGlobal gr) loc)
446
447 let discharge_constant obj = Some obj
448
449 let classify_constant cst = Libobject.Substitute
450
451 let (objConstant : (Id.t * constant_obj) Libobject.Dyn.tag) =
452 let open Libobject in
453 declare_named_object_full { (default_object "CONSTANT") with
454 cache_function = cache_constant;
455 load_function = load_constant;
456 open_function = filtered_open open_constant;
457 classify_function = classify_constant;
458 subst_function = ident_subst_function;
459 discharge_function = discharge_constant }
460
461 let inConstant v = Libobject.Dyn.Easy.inj v objConstant
462
463 (* Register the libobjects attached to the constants *)
464 let register_constant loc cst kind ?user_warns local =
465 (* Register the declaration *)
466 let id = Constant.label cst in
467 let loc = fallback_loc id loc in
468 let o = inConstant (id, { cst_kind = kind; cst_locl = local; cst_warn = user_warns; cst_loc = loc; }) in
469 let () = Lib.add_leaf o in
470 (* Register associated data *)
471 Impargs.declare_constant_implicits cst;
472 Notation.declare_ref_arguments_scope (GlobRef.ConstRef cst)
473
474 let register_side_effect (c, body, role, univs) =
475 (* Register the body in the opaque table *)
476 let () = match body with
477 | None -> ()
478 | Some opaque -> Opaques.declare_private_opaque opaque
479 in
480 let id = Constant.label c in
481 let () = register_constant (fallback_loc ~warn:false id None) c Decls.(IsProof Theorem) Locality.ImportDefaultBehavior in
482 let () = match univs with
483 | None -> ()
484 | Some univs -> DeclareUniv.declare_univ_binders (ConstRef c) univs
485 in
486 match role with
487 | None -> ()
488 | Some (Evd.Schema (ind, kind)) -> DeclareScheme.declare_scheme SuperGlobal kind (ind, GlobRef.ConstRef c)
489
490 let get_roles export eff =
491 let eff = SideEff.obj eff in
492 let map (c, body) =
493 let role, univs = try (Cmap_env.find c eff) with Not_found -> None, None in
494 (c, body, role, univs)
495 in
496 List.map map export
497
498 (* This globally defines the side-effects in the environment and registers their
499 libobjects. *)
500 let export_side_effects eff =
501 let export = Global.export_private_constants (SideEff.get eff) in
502 let export = get_roles export eff in
503 List.iter register_side_effect export
504
505 (* This is different from [export_side_effects] as the former properly declares
506 the body of opaque constants whereas this function keeps them as axioms, see
507 below. *)
508 let register_side_effects pf =
509 let open Names in
510 let pf, eff = Proof.purge_side_effects pf in
511 let () = Global.Internal.reset_safe_env (Evd.get_senv_side_effects eff) in
512 (* We do not have to register the opaque proofs because opaque private constants
513 have no body in the environment, see {!Safe_typing.add_private_constant}. *)
514 let iter kn =
515 let gr = GlobRef.ConstRef kn in
516 let id = Constant.label kn in
517 let sp = Lib.make_path id in
518 Nametab.push (Nametab.Until 1) sp gr
519 in
520 let () = List.iter iter (Safe_typing.constants_of_private @@ Evd.seff_private eff) in
521 pf, SideEff.make eff
522
523 let record_aux env s_ty s_bo =
524 let open Environ in
525 let in_ty = keep_hyps env s_ty in
526 let v =
527 String.concat " "
528 (CList.map_filter (fun decl ->
529 let id = NamedDecl.get_id decl in
530 if List.exists (NamedDecl.get_id %> Id.equal id) in_ty then None
531 else Some (Id.to_string id))
532 (keep_hyps env s_bo)) in
533 Aux_file.record_in_aux "context_used" v
534
535 let cast_pure_proof_entry (e : Constr.constr pproof_entry) =
536 let univ_entry, ctx = extract_monomorphic (fst (e.proof_entry_universes)) in
537 { Entries.definition_entry_body = e.proof_entry_body;
538 definition_entry_secctx = e.proof_entry_secctx;
539 definition_entry_type = e.proof_entry_type;
540 definition_entry_universes = univ_entry;
541 definition_entry_inline_code = e.proof_entry_inline_code;
542 },
543 ctx
544
545 type ('a, 'b) effect_entry =
546 | ImmediateEffectEntry : (private_constants Entries.proof_output, unit) effect_entry
547 | DeferredEffectEntry : (private_constants Entries.proof_output Future.computation, unit) effect_entry
548 | PureEntry : (Constr.constr, Constr.constr) effect_entry
549
550 let section_context_of_opaque_proof_entry (type a b) (entry : (a, b) effect_entry) (body : a) typ =
551 let open Environ in
552 let env = Global.env () in
553 let hyp_typ, hyp_def =
554 if List.is_empty (Environ.named_context env) then
555 Id.Set.empty, Id.Set.empty
556 else
557 let ids_typ = global_vars_set env typ in
558 let (pf : Constr.constr), env = match entry with
559 | PureEntry -> body, env
560 | ImmediateEffectEntry ->
561 let (pf, _), eff = body in
562 let env = Safe_typing.push_private_constants env eff in
563 pf, env
564 | DeferredEffectEntry ->
565 let (pf, _), eff = Future.force body in
566 let env = Safe_typing.push_private_constants env eff in
567 pf, env
568 in
569 let vars = global_vars_set env pf in
570 ids_typ, vars
571 in
572 let () = if Aux_file.recording () then record_aux env hyp_typ hyp_def in
573 Environ.really_needed env (Id.Set.union hyp_typ hyp_def)
574
575 let cast_opaque_proof_entry (type a b) (entry : (a, b) effect_entry) (e : a pproof_entry) : b Entries.opaque_entry * _ =
576 let typ = match e.proof_entry_type with
577 | None -> assert false
578 | Some typ -> typ
579 in
580 let secctx = match e.proof_entry_secctx with
581 | None -> section_context_of_opaque_proof_entry entry e.proof_entry_body typ
582 | Some hyps -> hyps
583 in
584 let body : b = match entry with
585 | PureEntry -> e.proof_entry_body
586 | ImmediateEffectEntry -> ()
587 | DeferredEffectEntry -> ()
588 in
589 let univ_entry, ctx = extract_monomorphic (fst (e.proof_entry_universes)) in
590 { Entries.opaque_entry_body = body;
591 opaque_entry_secctx = secctx;
592 opaque_entry_type = typ;
593 opaque_entry_universes = univ_entry;
594 },
595 ctx
596
597 let feedback_axiom () = Feedback.(feedback AddedAxiom)
598
599 let is_unsafe_typing_flags flags =
600 let flags = Option.default (Global.typing_flags ()) flags in
601 let open Declarations in
602 not (flags.check_universes && flags.check_guarded && flags.check_positive)
603
604 let declare_constant ~loc ?(local = Locality.ImportDefaultBehavior) ~name ~kind ~typing_flags ?user_warns cd =
605 let before_univs = Global.universes () in
606 let make_constant = function
607 (* Logically define the constant and its subproofs, no libobject tampering *)
608 | DefinitionEntry de ->
609 (* We deal with side effects *)
610 begin match de.proof_entry_body with
611 | Default { body; opaque = Transparent } ->
612 let de = { de with proof_entry_body = body } in
613 let e, ctx = cast_pure_proof_entry de in
614 let ubinders = make_ubinders ctx de.proof_entry_universes in
615 Entries.DefinitionEntry e, false, ubinders, None, ctx
616 | Default { body; opaque = Opaque (body_uctx, eff) } ->
617 let body = ((body, body_uctx), SideEff.get eff) in
618 let de = { de with proof_entry_body = body } in
619 let cd, ctx = cast_opaque_proof_entry ImmediateEffectEntry de in
620 let ubinders = make_ubinders ctx de.proof_entry_universes in
621 Entries.OpaqueEntry cd, false, ubinders, Some (Future.from_val body, None), ctx
622 | DeferredOpaque { body; feedback_id } ->
623 let map (body, eff) = body, SideEff.get eff in
624 let body = Future.chain body map in
625 let de = { de with proof_entry_body = body } in
626 let cd, ctx = cast_opaque_proof_entry DeferredEffectEntry de in
627 let ubinders = make_ubinders ctx de.proof_entry_universes in
628 Entries.OpaqueEntry cd, false, ubinders, Some (body, feedback_id), ctx
629 end
630 | ParameterEntry e ->
631 let univ_entry, ctx = extract_monomorphic (fst e.parameter_entry_universes) in
632 let ubinders = make_ubinders ctx e.parameter_entry_universes in
633 let e = {
634 Entries.parameter_entry_secctx = e.parameter_entry_secctx;
635 Entries.parameter_entry_type = e.parameter_entry_type;
636 Entries.parameter_entry_universes = univ_entry;
637 Entries.parameter_entry_inline_code = e.parameter_entry_inline_code;
638 } in
639 Entries.ParameterEntry e, not (Lib.is_modtype_strict()), ubinders, None, ctx
640 | PrimitiveEntry e ->
641 let typ, univ_entry, ctx = match e.prim_entry_type with
642 | None ->
643 None, (UState.Monomorphic_entry Univ.ContextSet.empty, UnivNames.empty_binders), Univ.ContextSet.empty
644 | Some (typ, entry_univs) ->
645 let univ_entry, ctx = extract_monomorphic (fst entry_univs) in
646 Some (typ, univ_entry), entry_univs, ctx
647 in
648 let e = {
649 Entries.prim_entry_type = typ;
650 Entries.prim_entry_content = e.prim_entry_content;
651 } in
652 let ubinders = make_ubinders ctx univ_entry in
653 Entries.PrimitiveEntry e, false, ubinders, None, ctx
654 | SymbolEntry { symb_entry_type=typ; symb_entry_unfold_fix=un_fix; symb_entry_universes=entry_univs } ->
655 let univ_entry, ctx = extract_monomorphic (fst entry_univs) in
656 let e = {
657 Entries.symb_entry_type = typ;
658 Entries.symb_entry_unfold_fix = un_fix;
659 Entries.symb_entry_universes = univ_entry;
660 } in
661 let ubinders = make_ubinders ctx entry_univs in
662 Entries.SymbolEntry e, false, ubinders, None, ctx
663 in
664 let declare_opaque kn = function
665 | None -> ()
666 | Some (body, feedback_id) ->
667 let open Declarations in
668 match (Global.lookup_constant kn).const_body with
669 | OpaqueDef o ->
670 let (_, _, _, i) = Opaqueproof.repr o in
671 Opaques.declare_defined_opaque ?feedback_id i body
672 | Def _ | Undef _ | Primitive _ | Symbol _ -> assert false
673 in
674 let () = check_exists name in
675 let decl, unsafe, ubinders, delayed, ctx = make_constant cd in
676 let () = Global.push_context_set ctx in
677 let kn = Global.add_constant ?typing_flags name decl in
678 let () =
679 let is_new_constraint (u,_,v as c) =
680 match UGraph.check_declared_universes before_univs Univ.Level.Set.(add u (add v empty)) with
681 | Ok () -> not (UGraph.check_constraint before_univs c)
682 | Error _ -> true
683 in
684 let ctx = on_snd (Univ.UnivConstraints.filter is_new_constraint) ctx in
685 DeclareUniv.add_constraint_source (ConstRef kn) ctx
686 in
687 let () = DeclareUniv.declare_univ_binders (GlobRef.ConstRef kn) ubinders in
688 let () = declare_opaque kn delayed in
689 let () = register_constant loc kn kind local ?user_warns in
690 if unsafe || is_unsafe_typing_flags typing_flags then feedback_axiom();
691 kn
692
693 let declare_private_constant ?role ?ts ~name ~opaque de effs =
694 let de, ctx =
695 if not opaque then
696 let de, ctx = cast_pure_proof_entry de in
697 DefinitionEff de, ctx
698 else
699 let de, ctx = cast_opaque_proof_entry PureEntry de in
700 OpaqueEff de, ctx
701
702 in
703 Evd.push_side_effects ?role ?ts name de ctx effs
704
705 let inline_private_constants ~uctx env (body, eff) =
706 let body, ctx = Safe_typing.inline_private_constants env (body, SideEff.get eff) in
707 let uctx = UState.merge_universe_context ~sideff:true Evd.univ_rigid uctx ctx in
708 body, uctx
709
710 (** Declaration of section variables and local definitions *)
711 type variable_declaration =
712 | SectionLocalDef of {
713 clearbody : bool;
714 entry : proof_entry;
715 }
716 | SectionLocalAssum of {
717 typ : Constr.types;
718 impl : Glob_term.binding_kind;
719 univs : UState.named_universes_entry;
720 }
721
722 (* This object is only for things which iterate over objects to find
723 variables (only Prettyp.print_context AFAICT) *)
724 let objVariable : Id.t Libobject.Dyn.tag =
725 let open Libobject in
726 declare_object_full { (default_object "VARIABLE") with
727 classify_function = (fun _ -> Dispose)}
728
729 let inVariable v = Libobject.Dyn.Easy.inj v objVariable
730
731 let declare_variable ~name ~kind ~typing_flags d =
732 (* Variables are distinguished by only short names *)
733 if Decls.variable_exists name then
734 raise (DeclareUniv.AlreadyDeclared (None, name));
735
736 let impl,opaque = match d with (* Fails if not well-typed *)
737 | SectionLocalAssum {typ;impl;univs} ->
738 let () = match fst univs with
739 | UState.Monomorphic_entry uctx ->
740 (* XXX [snd univs] is ignored, should we use it? *)
741 let () = DeclareUniv.name_mono_section_univs (fst uctx) in
742 Global.push_context_set uctx
743 | UState.Polymorphic_entry uctx -> Global.push_section_context uctx
744 in
745 let () = Global.push_named_assum (name,typ) in
746 impl, true
747 | SectionLocalDef { clearbody; entry = de } ->
748 (* The body should already have been forced upstream because it is a
749 section-local definition, but it's not enforced by typing *)
750 let ((body, body_uctx), eff), opaque, feedback_id = ProofEntry.force_extract_body de in
751 let () = export_side_effects eff in
752 (* We must declare the universe constraints before type-checking the
753 term. *)
754 let univs = match fst de.proof_entry_universes with
755 | UState.Monomorphic_entry uctx ->
756 let () = DeclareUniv.name_mono_section_univs (fst uctx) in
757 let () = Global.push_context_set (Univ.ContextSet.union uctx body_uctx) in
758 UState.Monomorphic_entry Univ.ContextSet.empty, UnivNames.empty_binders
759 | UState.Polymorphic_entry uctx ->
760 Global.push_section_context uctx;
761 let mk_anon_names u =
762 let qs, us = UVars.Instance.to_array u in
763 {UVars.quals = Array.make (Array.length qs) Anonymous; UVars.univs = Array.make (Array.length us) Anonymous}
764 in
765 Global.push_section_context
766 (UVars.UContext.of_context_set mk_anon_names (Sorts.QContextSet.empty, body_uctx));
767 UState.Polymorphic_entry UVars.UContext.empty, UnivNames.empty_binders
768 in
769 let se = if opaque then
770 let cname = Id.of_string (Id.to_string name ^ "_subproof") in
771 let cname = Namegen.next_global_ident_away (Global.safe_env ()) cname Id.Set.empty in
772 let de = {
773 proof_entry_body = DeferredOpaque { body = Future.from_val ((body, Univ.ContextSet.empty), SideEff.empty); feedback_id };
774 proof_entry_secctx = None; (* de.proof_entry_secctx is NOT respected *)
775 proof_entry_type = de.proof_entry_type;
776 proof_entry_universes = univs;
777 proof_entry_inline_code = de.proof_entry_inline_code;
778 }
779 in
780 let kn = declare_constant ~name:cname ~loc:None
781 ~local:ImportNeedQualified ~kind:(IsProof Lemma) ~typing_flags
782 (DefinitionEntry de)
783 in
784 {
785 Entries.secdef_body = Constr.mkConstU (kn, UVars.Instance.empty);
786 secdef_type = None;
787 }
788 else {
789 Entries.secdef_body = body;
790 secdef_type = de.proof_entry_type;
791 } in
792 let () = Global.push_named_def (name, se) in
793 (* opaque implies clearbody, so we don't see useless "foo := foo_subproof" in the context *)
794 Glob_term.Explicit, opaque || clearbody
795 in
796 Nametab.push (Nametab.Until 1) (Libnames.make_path DirPath.empty name) (GlobRef.VarRef name);
797 Decls.(add_variable_data name {opaque;kind});
798 Lib.add_leaf (inVariable name);
799 Impargs.declare_var_implicits ~impl name;
800 Notation.declare_ref_arguments_scope (GlobRef.VarRef name)
801
802 (* Declaration messages *)
803
804 let pr_rank i = pr_nth (i+1)
805
806 let fixpoint_message indexes l =
807 Flags.if_verbose Feedback.msg_info (match l with
808 | [] -> CErrors.anomaly (Pp.str "no recursive definition.")
809 | [id] -> Id.print id ++ str " is recursively defined" ++
810 (match indexes with
811 | Some [|i|] -> str " (guarded on "++pr_rank i++str " argument)"
812 | _ -> mt ())
813 | l -> hov 0 (prlist_with_sep pr_comma Id.print l ++
814 spc () ++ str "are recursively defined" ++
815 match indexes with
816 | Some a -> spc () ++ str "(guarded respectively on " ++
817 prvect_with_sep pr_comma pr_rank a ++
818 str " arguments)"
819 | None -> mt ()))
820
821 let cofixpoint_message l =
822 Flags.if_verbose Feedback.msg_info (match l with
823 | [] -> CErrors.anomaly (Pp.str "No corecursive definition.")
824 | [id] -> Id.print id ++ str " is corecursively defined"
825 | l -> hov 0 (prlist_with_sep pr_comma Id.print l ++
826 spc () ++ str "are corecursively defined"))
827
828 let recursive_message indexes l =
829 match indexes with
830 | None -> cofixpoint_message l
831 | Some indexes -> fixpoint_message (Some indexes) l
832
833 let definition_message id =
834 Flags.if_verbose Feedback.msg_info (Id.print id ++ str " is defined")
835
836 let assumption_message id =
837 (* Changing "assumed" to "declared", "assuming" referring more to
838 the type of the object than to the name of the object (see
839 discussion on coqdev: "Chapter 4 of the Reference Manual", 8/10/2015) *)
840 Flags.if_verbose Feedback.msg_info (Id.print id ++ str " is declared")
841
842 (* The word [proof] is to be understood as [justification] *)
843 (* A possible alternatve would be [evidence]?? *)
844 type closed_proof_output = {
845 output_entries : (Constr.t * Constr.t option) list;
846 output_ustate : UState.t;
847 output_sideff : SideEff.t;
848 }
849
850 type proof_object =
851 | DefaultProof of
852 { proof : closed_proof_output
853 ; opaque : bool
854 ; using : Names.Id.Set.t option
855 ; keep_body_ucst_separate : UState.t option
856 }
857 | DeferredOpaqueProof of
858 { deferred_proof : closed_proof_output Future.computation
859 ; using : Names.Id.Set.t option
860 ; initial_proof_data : Proof.data
861 ; feedback_id : Stateid.t
862 ; initial_euctx : UState.t
863 }
864
865 let future_map2_pair_list_distribute p l f =
866 List.map_i (fun i c -> f (Future.chain p (fun p -> (List.nth p.output_entries i, p.output_ustate, p.output_sideff))) c) 0 l
867
868 let process_proof ~info:Info.({ udecl; poly }) ?(is_telescope=false) = function
869 | DefaultProof { proof; opaque; using; keep_body_ucst_separate } ->
870 let { output_entries = entries; output_ustate = uctx; output_sideff = eff } = proof in
871 (* Force transparency for Derive-like dependent statements *)
872 let opaques =
873 let n = List.length entries in
874 List.init n (fun i ->
875 if i < n-1 && is_telescope then (* waiting for addition of cinfo-based opacity in #19029 *) false
876 else opaque) in
877 (* Multiple entries mean either a recursive block of definitions
878 (as in Co/Fixpoint) or a sequence of dependent definitions (as
879 in "Derive"). In the second case, the dependency in the
880 previous entries requires to accumulate the universes from the
881 previous definitions *)
882 let exported_effects = if List.exists not opaques then eff else SideEff.empty in
883 exported_effects,
884 snd (List.fold_left2_map (fun used_univs (body, typ) opaque ->
885 let uctx, univs, used_univs, body =
886 make_univs_immediate ~poly ?keep_body_ucst_separate ~opaque ~uctx ~udecl ~eff ~used_univs body typ in
887 (used_univs, (definition_entry_core ?using ~univs ?types:typ body, uctx))) Univ.Level.Set.empty entries opaques)
888 | DeferredOpaqueProof { deferred_proof = bodies; using; initial_proof_data; feedback_id; initial_euctx } ->
889 let { Proof.poly; entry; sigma } = initial_proof_data in
890 (* Deferred multiple entries currently assume either a mutual
891 Co/Fixpoint or no dependency (thus no "Derive"); to support
892 "Derive"-like statements, we would need a combinator on futures
893 that fold used universes *)
894 SideEff.empty,
895 future_map2_pair_list_distribute bodies (Proofview.initial_goals entry)
896 (fun body_typ_uctx (_, _, initial_typ) ->
897 (* Testing if evar-closed? *)
898 let initial_typ = Evarutil.nf_evars_universes sigma (EConstr.Unsafe.to_constr initial_typ) in
899 (* The flags keep_body_ucst_separate, opaque, etc. should be consistent with evar-closedness? *)
900 let univs = UState.univ_entry ~poly:PolyFlags.default initial_euctx in
901 let body = Future.chain body_typ_uctx (fun ((body, _typ), uctx, eff) ->
902 let uctx = make_univs_deferred_private_mono ~initial_euctx ~uctx ~udecl body (Some initial_typ) in
903 ((body, uctx), eff)) in
904 (delayed_definition_entry ?using ~univs ~types:initial_typ ~feedback_id body, initial_euctx))
905
906 let declare_definition_scheme ~univs ~role ~name ~effs c =
907 let entry = pure_definition_entry ~univs c in
908 declare_private_constant ~role ~name ~opaque:false entry effs
909
910 let register_definition_scheme ~internal ~name ~const:kn ~univs ?loc () =
911 let kind = Decls.(IsDefinition Scheme) in
912 let () = register_constant (fallback_loc ~warn:false name None) kn kind Locality.ImportDefaultBehavior in
913 let () = DeclareUniv.declare_univ_binders (ConstRef kn) univs in
914 Dumpglob.dump_definition
915 (CAst.make ?loc (Constant.label kn)) false "scheme";
916 let () = if internal then () else definition_message name in
917 ()
918
919 (* Locality stuff *)
920 let declare_entry ~loc ~name ?(scope=Locality.default_scope) ?(clearbody=false) ~kind ~typing_flags ~user_warns ?hook ?(obls=[]) ~impargs ~uctx entry =
921 let should_suggest =
922 ProofEntry.get_opacity entry
923 && not (List.is_empty (Global.named_context()))
924 && Option.is_empty entry.proof_entry_secctx
925 in
926 let dref = match scope with
927 | Locality.Discharge ->
928 let () = declare_variable ~typing_flags ~name ~kind (SectionLocalDef {clearbody; entry}) in
929 if should_suggest then Proof_using.suggest_variable (Global.env ()) name;
930 Names.GlobRef.VarRef name
931 | Locality.Global local ->
932 assert (not clearbody);
933 let kn = declare_constant ~loc ~name ~local ~kind ~typing_flags ?user_warns (DefinitionEntry entry) in
934 let gr = Names.GlobRef.ConstRef kn in
935 if should_suggest then Proof_using.suggest_constant (Global.env ()) kn;
936 gr
937 in
938 let () = Impargs.maybe_declare_manual_implicits false dref impargs in
939 let () = definition_message name in
940 Hook.call ?hook { Hook.S.uctx; obls; scope; dref };
941 dref
942
943 let warn_let_as_axiom =
944 CWarnings.create ~name:"let-as-axiom" ~category:CWarnings.CoreCategories.vernacular
945 Pp.(fun id -> strbrk "Let definition" ++ spc () ++ Names.Id.print id ++
946 spc () ++ strbrk "declared as an axiom.")
947
948 (* Declare an assumption when not in a section: Parameter/Axiom but also
949 Variable/Hypothesis seen as Local Parameter/Axiom *)
950 let declare_parameter ~loc ~name ~scope ~hook ~impargs ~uctx pe =
951 let local = match scope with
952 | Locality.Discharge -> warn_let_as_axiom name; Locality.ImportNeedQualified
953 | Locality.Global local -> local
954 in
955 let kind = Decls.(IsAssumption Conjectural) in
956 let decl = ParameterEntry pe in
957 let cst = declare_constant ~loc ~name ~local ~kind ~typing_flags:None decl in
958 let dref = Names.GlobRef.ConstRef cst in
959 let () = Impargs.maybe_declare_manual_implicits false dref impargs in
960 let () = assumption_message name in
961 let () = Hook.(call ?hook { S.uctx; obls = []; scope; dref}) in
962 cst
963
964 (* Using processing *)
965 let interp_proof_using_gen f env evd cinfo using =
966 let cextract v (fixnames, terms) =
967 let name, new_terms = f v in
968 name :: fixnames, new_terms @ terms
969 in
970 let fixnames, terms = CList.fold_right cextract cinfo ([],[]) in
971 Proof_using.definition_using env evd ~fixnames ~terms ~using
972
973 let interp_proof_using_cinfo env evd cinfo using =
974 let f { CInfo.name; typ; _ } = name, [typ] in
975 interp_proof_using_gen f env evd cinfo using
976
977 let gather_mutual_using_data cinfo =
978 List.fold_left2 (fun acc CInfo.{name} (body, typ) ->
979 let l = Option.List.flatten EConstr.[Option.map of_constr typ; Some (of_constr body)] in
980 (name, l) :: acc) [] cinfo
981
982 let interp_mutual_using env cinfo bodies_types using =
983 let evd = Evd.from_env env in
984 Option.map (fun using ->
985 let cinfos = gather_mutual_using_data cinfo bodies_types in
986 let f x = x in
987 interp_proof_using_gen f env evd cinfos using)
988 using
989
990 let declare_possibly_mutual_definitions ~info ~cinfo ~obls ?(is_telescope=false) obj =
991 let eff, entries = process_proof ~info ~is_telescope obj in
992 let () = export_side_effects eff in
993 let { Info.hook; scope; clearbody; kind; typing_flags; user_warns; ntns; _ } = info in
994 let _, refs = List.fold_left2_map (fun subst CInfo.{name; impargs; loc} (entry, uctx) ->
995 (* replacing matters for Derive-like statement but it does not hurt otherwise *)
996 let entry = ProofEntry.map_entry entry ~f:(Vars.replace_vars subst) in
997 let gref = declare_entry ~loc ~name ~scope ~clearbody ~kind ?hook ~impargs ~typing_flags ~user_warns ~obls ~uctx entry in
998 let inst = instance_of_univs entry.proof_entry_universes in
999 let const = Constr.mkRef (gref, inst) in
1000 ((name, const) :: subst, gref)) [] cinfo entries in
1001 let () =
1002 (* For the recursive case, we override the temporary notations used while proving, now using the global names *)
1003 let local = info.scope=Locality.Discharge in
1004 if ntns <> [] then
1005 CWarnings.with_warn ("-"^Notation.warning_overridden_name)
1006 (List.iter (Metasyntax.add_notation_interpretation ~local (Global.env()))) ntns
1007 in
1008 refs
1009
1010 let declare_possibly_mutual_parameters ~info ~cinfo ?(mono_uctx_extra=UState.empty) ~sec_vars typs =
1011 (* Note, if an initial uctx, minimize and restrict have not been done *)
1012 (* if the uctx of an abandonned proof, minimize is redundant (see close_proof) *)
1013 let { Info.scope; poly; hook; udecl } = info in
1014 pi3 (List.fold_left2 (
1015 fun (i, subst, csts) { CInfo.name; loc; impargs } (typ, uctx) ->
1016 let uctx' = UState.restrict uctx (Vars.universes_of_constr typ) in
1017 let univs = UState.check_univ_decl ~poly uctx' udecl in
1018 let univs = if i = 0 then add_mono_uctx mono_uctx_extra univs else univs in
1019 let typ = Vars.replace_vars subst typ in
1020 let pe = {
1021 parameter_entry_secctx = sec_vars;
1022 parameter_entry_type = Evarutil.nf_evars_universes (Evd.from_ctx uctx) typ;
1023 parameter_entry_universes = univs;
1024 parameter_entry_inline_code = None;
1025 } in
1026 let cst = declare_parameter ~loc ~name ~scope ~hook ~impargs ~uctx pe in
1027 let inst = instance_of_univs univs in
1028 (i+1, (name, Constr.mkConstU (cst,inst))::subst, (cst, univs)::csts)
1029 ) (0, [], []) cinfo typs)
1030
1031 let make_recursive_bodies ?elim_to env ~typing_flags ~possible_guard ~rec_declaration =
1032 let env = Environ.update_typing_flags ?typing_flags env in
1033 let indexes = Pretyping.search_guard ?elim_to env possible_guard rec_declaration in
1034 let mkbody i = match indexes with
1035 | Some indexes -> Constr.mkFix ((indexes,i), rec_declaration)
1036 | None -> Constr.mkCoFix (i, rec_declaration) in
1037 List.map_i (fun i typ -> (mkbody i, typ)) 0 (Array.to_list (pi2 rec_declaration)), indexes
1038
1039 let prepare_recursive_declaration cinfo fixtypes fixrs fixdefs =
1040 let fixnames = List.map (fun CInfo.{name} -> name) cinfo in
1041 let names = List.map2 (fun name r -> Context.make_annot (Name name) r) fixnames fixrs in
1042 let defs = List.map (Vars.subst_vars (List.rev fixnames)) fixdefs in
1043 (Array.of_list names, Array.of_list fixtypes, Array.of_list defs)
1044
1045 let prepare_recursive_edeclaration sigma cinfo fixtypes fixrs fixdefs =
1046 let fixnames = List.map (fun CInfo.{name} -> name) cinfo in
1047 let names = List.map2 (fun name r -> Context.make_annot (Name name) r) fixnames fixrs in
1048 let defs = List.map (EConstr.Vars.subst_vars sigma (List.rev fixnames)) fixdefs in
1049 (Array.of_list names, Array.of_list fixtypes, Array.of_list defs)
1050
1051 let declare_mutual_definitions ~info ~cinfo ~opaque ~eff ~uctx ~bodies ~possible_guard ?using () =
1052 (* Note: uctx is supposed to be already minimized *)
1053 let { Info.typing_flags; _ } = info in
1054 let env = Global.env() in
1055 let possible_guard, fixrelevances = possible_guard in
1056 let fixtypes = List.map (fun CInfo.{typ} -> typ) cinfo in
1057 let rec_declaration = prepare_recursive_declaration cinfo fixtypes fixrelevances bodies in
1058 let elim_to = Inductive.eliminates_to @@ UState.elim_graph uctx in
1059 let bodies_types, indexes = make_recursive_bodies ~elim_to env ~typing_flags ~rec_declaration ~possible_guard in
1060 let entries = List.map (fun (body, typ) -> (body, Some typ)) bodies_types in
1061 let entries_for_using = List.map (fun (body, typ) -> (body, Some typ)) bodies_types in
1062 let using = interp_mutual_using env cinfo entries_for_using using in
1063 let proof = { output_entries = entries; output_ustate = uctx; output_sideff = SideEff.make eff } in
1064 let obj = DefaultProof { proof; opaque; using; keep_body_ucst_separate = None } in
1065 let refs = declare_possibly_mutual_definitions ~info ~cinfo ~obls:[] obj in
1066 let fixnames = List.map (fun { CInfo.name } -> name) cinfo in
1067 recursive_message indexes fixnames;
1068 refs
1069
1070 (* Preparing proof entries *)
1071 let error_unresolved_evars env sigma t evars =
1072 let pr_unresolved_evar e =
1073 hov 2 (str"- " ++ Printer.pr_existential_key env sigma e ++ str ": " ++
1074 Himsg.explain_pretype_error env sigma
1075 (Pretype_errors.UnsolvableImplicit (e,None)))
1076 in
1077 CErrors.user_err (hov 0 begin
1078 str "The following term contains unresolved implicit arguments:"++ fnl () ++
1079 str " " ++ Printer.pr_econstr_env env sigma t ++ fnl () ++
1080 str "More precisely: " ++ fnl () ++
1081 v 0 (prlist_with_sep cut pr_unresolved_evar (Evar.Set.elements evars))
1082 end)
1083
1084 let check_evars_are_solved env sigma t =
1085 let evars = Evarutil.undefined_evars_of_term sigma t in
1086 if not (Evar.Set.is_empty evars) then error_unresolved_evars env sigma t evars
1087
1088 let declare_definition ~info ~cinfo ~opaque ~obls ~body ?using sigma =
1089 let { CInfo.name; typ; _ } = cinfo in
1090 let env = Global.env () in
1091 Option.iter (check_evars_are_solved env sigma) typ;
1092 check_evars_are_solved env sigma body;
1093 let sigma = Evd.minimize_universes sigma in
1094 let body = EConstr.to_constr sigma body in
1095 let typ = Option.map (EConstr.to_constr sigma) typ in
1096 let uctx = Evd.ustate sigma in
1097 let eff = SideEff.make @@ Evd.eval_side_effects sigma in
1098 let using = interp_mutual_using env [cinfo] [body,typ] using in
1099 let proof = { output_entries = [(body, typ)]; output_ustate = uctx; output_sideff = eff } in
1100 let obj = DefaultProof { proof; opaque; using; keep_body_ucst_separate = None } in
1101 let gref = List.hd (declare_possibly_mutual_definitions ~info ~cinfo:[cinfo] ~obls obj) in
1102 gref, uctx
1103
1104 let prepare_obligations ~name poly ?types ~body env sigma =
1105 let env = Global.env () in
1106 let types = match types with
1107 | Some t -> t
1108 | None -> Retyping.get_type_of env sigma body
1109 in
1110 let sigma, (body, types) = Evarutil.finalize ~abort_on_undefined_evars:false
1111 sigma (fun nf -> nf body, nf types)
1112 in
1113 RetrieveObl.check_evars env sigma;
1114 let body, types = EConstr.(of_constr body, of_constr types) in
1115 let obls, (_, evmap), body, cty = RetrieveObl.retrieve_obligations env name sigma 0 body types in
1116 let uctx = Evd.ustate sigma in
1117 body, cty, uctx, evmap, obls
1118
1119 let prepare_parameter ~poly ~udecl ~types sigma =
1120 let env = Global.env () in
1121 Pretyping.check_evars_are_solved ~program_mode:false env sigma;
1122 let sigma, typ = Evarutil.finalize ~abort_on_undefined_evars:true
1123 sigma (fun nf -> nf types)
1124 in
1125 let univs = Evd.check_univ_decl ~poly sigma udecl in
1126 let pe = {
1127 parameter_entry_secctx = None;
1128 parameter_entry_type = typ;
1129 parameter_entry_universes = univs;
1130 parameter_entry_inline_code = None;
1131 } in
1132 sigma, pe
1133
1134 type progress = Remain | Dependent | Defined
1135
1136 module Obls_ = struct
1137
1138 open Constr
1139
1140 type 'a obligation_body = DefinedObl of 'a | TermObl of constr
1141
1142 module Obligation = struct
1143 type t =
1144 { obl_name : Id.t
1145 ; obl_type : types
1146 ; obl_location : Evar_kinds.t Loc.located
1147 ; obl_body : pconstant obligation_body option
1148 ; obl_status : bool * Evar_kinds.obligation_definition_status
1149 ; obl_deps : Int.Set.t
1150 ; obl_tac : unit Proofview.tactic option }
1151
1152 let set_type ~typ obl = {obl with obl_type = typ}
1153 end
1154
1155 type obligations = {obls : Obligation.t array; remaining : int}
1156 type fixpoint_kind = IsFixpoint of lident option list | IsCoFixpoint
1157
1158 module ProgramDecl = struct
1159
1160 type 'a t =
1161 { prg_cinfo : constr CInfo.t
1162 ; prg_info : Info.t
1163 ; prg_using : Vernacexpr.section_subset_expr option
1164 ; prg_opaque : bool
1165 ; prg_hook : 'a option
1166 ; prg_body : constr
1167 ; prg_uctx : UState.t
1168 ; prg_obligations : obligations
1169 ; prg_deps : Id.t list
1170 ; prg_possible_guard : (Pretyping.possible_guard * Sorts.relevance list) option (* None = not recursive *)
1171 ; prg_reduce : constr -> constr
1172 }
1173
1174 open Obligation
1175
1176 let make ~info ~cinfo ~opaque ~reduce ~deps ~uctx ~body ~possible_guard ?obl_hook ?using obls =
1177 let obls', body =
1178 match body with
1179 | None ->
1180 assert (Int.equal (Array.length obls) 0);
1181 let n = Nameops.add_suffix cinfo.CInfo.name "_obligation" in
1182 ( [| { obl_name = n
1183 ; obl_body = None
1184 ; obl_location = Loc.tag Evar_kinds.InternalHole
1185 ; obl_type = cinfo.CInfo.typ
1186 ; obl_status = (false, Evar_kinds.Expand)
1187 ; obl_deps = Int.Set.empty
1188 ; obl_tac = None } |]
1189 , mkVar n )
1190 | Some b ->
1191 ( Array.mapi
1192 (fun i (n, t, l, o, d, tac) ->
1193 { obl_name = n
1194 ; obl_body = None
1195 ; obl_location = l
1196 ; obl_type = t
1197 ; obl_status = o
1198 ; obl_deps = d
1199 ; obl_tac = tac })
1200 obls
1201 , b )
1202 in
1203 let prg_uctx =
1204 if PolyFlags.univ_poly info.Info.poly then uctx
1205 else
1206 (* declare global univs of the main constant before we do obligations *)
1207 let uctx = UState.collapse_sort_variables uctx in
1208 let ctx = UState.check_mono_sort_constraints uctx in
1209 let () = Global.push_context_set ctx in
1210 let cst = Constant.make2 (Lib.current_mp()) cinfo.CInfo.name in
1211 let () = DeclareUniv.declare_univ_binders (ConstRef cst)
1212 (UState.univ_entry ~poly:info.Info.poly uctx)
1213 in
1214 UState.Internal.reboot (Global.env()) uctx
1215 in
1216 { prg_cinfo = { cinfo with CInfo.typ = reduce cinfo.CInfo.typ }
1217 ; prg_info = info
1218 ; prg_using = using
1219 ; prg_hook = obl_hook
1220 ; prg_opaque = opaque
1221 ; prg_body = body
1222 ; prg_uctx
1223 ; prg_obligations = {obls = obls'; remaining = Array.length obls'}
1224 ; prg_deps = deps
1225 ; prg_possible_guard = possible_guard
1226 ; prg_reduce = reduce }
1227
1228 let show prg =
1229 let { CInfo.name; typ; _ } = prg.prg_cinfo in
1230 let env = Global.env () in
1231 let sigma = Evd.from_env env in
1232 Id.print name ++ spc () ++ str ":" ++ spc ()
1233 ++ Printer.pr_constr_env env sigma typ
1234 ++ spc () ++ str ":=" ++ fnl ()
1235 ++ Printer.pr_constr_env env sigma prg.prg_body
1236
1237 module Internal = struct
1238 let get_name prg = prg.prg_cinfo.CInfo.name
1239 let get_uctx prg = prg.prg_uctx
1240 let set_uctx ~uctx prg = {prg with prg_uctx = uctx}
1241 let get_poly prg = prg.prg_info.Info.poly
1242 let get_obligations prg = prg.prg_obligations
1243 let get_using prg = prg.prg_using
1244 end
1245 end
1246
1247 open Obligation
1248 open ProgramDecl
1249
1250 (* Saving an obligation *)
1251
1252 (* XXX: Is this the right place for this? *)
1253 let it_mkLambda_or_LetIn_or_clean t ctx =
1254 let open Context.Rel.Declaration in
1255 let fold t decl =
1256 if is_local_assum decl then Term.mkLambda_or_LetIn decl t
1257 else if Vars.noccurn 1 t then Vars.subst1 mkProp t
1258 else Term.mkLambda_or_LetIn decl t
1259 in
1260 Context.Rel.fold_inside fold ctx ~init:t
1261
1262 (* XXX: Is this the right place for this? *)
1263 let decompose_lam_prod c ty =
1264 let open Context.Rel.Declaration in
1265 let rec aux ctx c ty =
1266 match (Constr.kind c, Constr.kind ty) with
1267 | LetIn (x, b, t, c), LetIn (x', b', t', ty)
1268 when Constr.equal b b' && Constr.equal t t' ->
1269 let ctx' = Context.Rel.add (LocalDef (x, b', t')) ctx in
1270 aux ctx' c ty
1271 | _, LetIn (x', b', t', ty) ->
1272 let ctx' = Context.Rel.add (LocalDef (x', b', t')) ctx in
1273 aux ctx' (lift 1 c) ty
1274 | LetIn (x, b, t, c), _ ->
1275 let ctx' = Context.Rel.add (LocalDef (x, b, t)) ctx in
1276 aux ctx' c (lift 1 ty)
1277 | Lambda (x, b, t), Prod (x', b', t')
1278 (* By invariant, must be convertible *) ->
1279 let ctx' = Context.Rel.add (LocalAssum (x, b')) ctx in
1280 aux ctx' t t'
1281 | Cast (c, _, _), _ -> aux ctx c ty
1282 | _, _ -> (ctx, c, ty)
1283 in
1284 aux Context.Rel.empty c ty
1285
1286 (* XXX: What's the relation of this with Abstract.shrink ? *)
1287 let shrink_body c ty =
1288 let ctx, b, ty =
1289 match ty with
1290 | None ->
1291 let ctx, b = Term.decompose_lambda_decls c in
1292 (ctx, b, None)
1293 | Some ty ->
1294 let ctx, b, ty = decompose_lam_prod c ty in
1295 (ctx, b, Some ty)
1296 in
1297 let b', ty', n, args =
1298 List.fold_left
1299 (fun (b, ty, i, args) decl ->
1300 if Vars.noccurn 1 b && Option.cata (Vars.noccurn 1) true ty then
1301 (Vars.subst1 mkProp b, Option.map (Vars.subst1 mkProp) ty, succ i, args)
1302 else
1303 let open Context.Rel.Declaration in
1304 let args = if is_local_assum decl then mkRel i :: args else args in
1305 ( Term.mkLambda_or_LetIn decl b
1306 , Option.map (Term.mkProd_or_LetIn decl) ty
1307 , succ i
1308 , args ))
1309 (b, ty, 1, []) ctx
1310 in
1311 (ctx, b', ty', Array.of_list args)
1312
1313 (***********************************************************************)
1314 (* Saving an obligation *)
1315 (***********************************************************************)
1316
1317 let universes_of_decl body typ =
1318 let univs_typ = match typ with None -> Univ.Level.Set.empty | Some ty -> Vars.universes_of_constr ty in
1319 let univs_body = Vars.universes_of_constr body in
1320 Univ.Level.Set.union univs_body univs_typ
1321
1322 let update_global_obligation_uctx prg uctx =
1323 let uctx =
1324 if PolyFlags.univ_poly prg.prg_info.Info.poly then
1325 (* Accumulate the polymorphic constraints *)
1326 UState.union prg.prg_uctx uctx
1327 else
1328 (* The monomorphic universe context of the main constant has
1329 been declared by the first obligation; it is now in the
1330 global env and we now remove it for the further
1331 declarations *)
1332 UState.Internal.reboot (Global.env ()) uctx in
1333 ProgramDecl.Internal.set_uctx ~uctx prg
1334
1335 let declare_obligation prg obl ~uctx ~types ~body =
1336 let body = prg.prg_reduce body in
1337 let types = Option.map prg.prg_reduce types in
1338 match obl.obl_status with
1339 | _, Evar_kinds.Expand ->
1340 let prg_uctx = UState.union prg.prg_uctx uctx in
1341 let prg = ProgramDecl.Internal.set_uctx ~uctx:prg_uctx prg in
1342 (prg, {obl with obl_body = Some (TermObl body)}, [])
1343 | force, Evar_kinds.Define opaque ->
1344 let opaque = (not force) && opaque in
1345 let poly = prg.prg_info.Info.poly in
1346 let ctx, body, ty, args =
1347 if not (PolyFlags.univ_poly poly) then shrink_body body types
1348 else ([], body, types, [||])
1349 in
1350 let uctx' = UState.restrict uctx (universes_of_decl body types) in
1351 let univs = UState.univ_entry ~poly uctx' in
1352 let inst = instance_of_univs univs in
1353 let ce = definition_entry ?types:ty ~opaque ~univs body in
1354 (* ppedrot: seems legit to have obligations as local *)
1355 let constant =
1356 declare_constant ~loc:(fallback_loc ~warn:false obl.obl_name None) ~name:obl.obl_name
1357 ~typing_flags:prg.prg_info.Info.typing_flags
1358 ~local:Locality.ImportNeedQualified
1359 ~kind:Decls.(IsProof Property)
1360 (DefinitionEntry ce)
1361 in
1362 definition_message obl.obl_name;
1363 let prg = update_global_obligation_uctx prg uctx in
1364 let body =
1365 if PolyFlags.univ_poly poly then DefinedObl (constant, inst)
1366 else
1367 let const = mkConstU (constant, inst) in
1368 TermObl (it_mkLambda_or_LetIn_or_clean (mkApp (const, args)) ctx)
1369 in
1370 (prg, {obl with obl_body = Some body}, [GlobRef.ConstRef constant])
1371
1372 (* Updating the obligation meta-info on close *)
1373
1374 let not_transp_msg =
1375 Pp.(
1376 str "Obligation should be transparent but was declared opaque."
1377 ++ spc ()
1378 ++ str "Use 'Defined' instead.")
1379
1380 let err_not_transp () =
1381 CErrors.user_err not_transp_msg
1382
1383 module ProgMap = Id.Map
1384
1385 module State = struct
1386
1387 type t = prg_hook ProgramDecl.t CEphemeron.key ProgMap.t
1388 and prg_hook = PrgHook of t Hook.g
1389
1390 let call_prg_hook { prg_hook=hook } x pm =
1391 let hook = Option.map (fun (PrgHook h) -> h) hook in
1392 Hook.call_g ?hook x pm
1393
1394
1395 let empty = ProgMap.empty
1396
1397 let pending pm =
1398 ProgMap.filter
1399 (fun _ v -> (CEphemeron.get v).prg_obligations.remaining > 0)
1400 pm
1401
1402 let num_pending pm = pending pm |> ProgMap.cardinal
1403
1404 let first_pending pm =
1405 pending pm |> ProgMap.choose_opt
1406 |> Option.map (fun (_, v) -> CEphemeron.get v)
1407
1408 let get_unique_open_prog pm name : (_, Id.t list) result =
1409 match name with
1410 | Some n ->
1411 Option.cata
1412 (fun p -> Ok (CEphemeron.get p))
1413 (Error []) (ProgMap.find_opt n pm)
1414 | None -> (
1415 let n = num_pending pm in
1416 match n with
1417 | 0 -> Error []
1418 | 1 -> Option.cata (fun p -> Ok p) (Error []) (first_pending pm)
1419 | _ ->
1420 let progs = Id.Set.elements (ProgMap.domain pm) in
1421 Error progs )
1422
1423 let add t key prg = ProgMap.add key (CEphemeron.create prg) t
1424
1425 let fold t ~f ~init =
1426 let f k v acc = f k (CEphemeron.get v) acc in
1427 ProgMap.fold f t init
1428
1429 let all pm = ProgMap.bindings pm |> List.map (fun (_,v) -> CEphemeron.get v)
1430 let find m t = ProgMap.find_opt t m |> Option.map CEphemeron.get
1431
1432 module View = struct
1433 module Obl = struct
1434 type t =
1435 { name : Id.t
1436 ; loc : Loc.t option
1437 ; status : bool * Evar_kinds.obligation_definition_status
1438 ; solved : bool
1439 }
1440
1441 let make (o : Obligation.t) =
1442 let { obl_name; obl_location; obl_status; obl_body; _ } = o in
1443 { name = obl_name
1444 ; loc = fst obl_location
1445 ; status = obl_status
1446 ; solved = Option.has_some obl_body
1447 }
1448 end
1449
1450 type t =
1451 { opaque : bool
1452 ; remaining : int
1453 ; obligations : Obl.t array
1454 }
1455
1456 let make { prg_opaque; prg_obligations; _ } =
1457 { opaque = prg_opaque
1458 ; remaining = prg_obligations.remaining
1459 ; obligations = Array.map Obl.make prg_obligations.obls
1460 }
1461
1462 let make eph = CEphemeron.get eph |> make
1463 end
1464
1465 let view s = Id.Map.map View.make s
1466
1467 end
1468
1469 (* In all cases, the use of the map is read-only so we don't expose the ref *)
1470 let map_non_empty_keys is_empty m =
1471 ProgMap.fold (fun k prg l -> if is_empty prg then l else k :: l) m []
1472
1473 let check_solved_obligations is_empty ~pm ~what_for : unit =
1474 if not (ProgMap.is_empty pm) then
1475 let keys = map_non_empty_keys is_empty pm in
1476 let have_string = if Int.equal (List.length keys) 1 then " has " else " have " in
1477 CErrors.user_err
1478 Pp.(
1479 str "Unsolved obligations when closing "
1480 ++ what_for ++ str ":" ++ spc ()
1481 ++ prlist_with_sep spc (fun x -> Id.print x) keys
1482 ++ str have_string
1483 ++ str "unsolved obligations." )
1484
1485 let map_replace k v m = ProgMap.add k (CEphemeron.create v) (ProgMap.remove k m)
1486 let progmap_remove pm prg = ProgMap.remove prg.prg_cinfo.CInfo.name pm
1487 let progmap_replace prg' pm = map_replace prg'.prg_cinfo.CInfo.name prg' pm
1488 let obligations_solved prg = Int.equal prg.prg_obligations.remaining 0
1489
1490 let obligations_message rem =
1491 Format.asprintf "%s %s remaining"
1492 (if rem > 0 then string_of_int rem else "No more")
1493 (CString.plural rem "obligation")
1494 |> Pp.str |> Flags.if_verbose Feedback.msg_info
1495
1496 let get_obligation_body expand obl =
1497 match obl.obl_body with
1498 | None -> None
1499 | Some c -> (
1500 if expand && snd obl.obl_status == Evar_kinds.Expand then
1501 match c with
1502 | DefinedObl pc -> Some (Environ.constant_value_in (Global.env ()) pc)
1503 | TermObl c -> Some c
1504 else
1505 match c with DefinedObl pc -> Some (mkConstU pc) | TermObl c -> Some c )
1506
1507 let obl_substitution expand obls deps =
1508 Int.Set.fold
1509 (fun x acc ->
1510 let xobl = obls.(x) in
1511 match get_obligation_body expand xobl with
1512 | None -> acc
1513 | Some oblb -> (xobl.obl_name, (xobl.obl_type, oblb)) :: acc)
1514 deps []
1515
1516 let rec intset_to = function
1517 | -1 -> Int.Set.empty
1518 | n -> Int.Set.add n (intset_to (pred n))
1519
1520 let obligation_substitution expand prg =
1521 let obls = prg.prg_obligations.obls in
1522 let ints = intset_to (pred (Array.length obls)) in
1523 obl_substitution expand obls ints
1524
1525 let subst_prog subst prg =
1526 let subst' = List.map (fun (n, (_, b)) -> (n, b)) subst in
1527 ( Vars.replace_vars subst' prg.prg_body
1528 , Vars.replace_vars subst' (* Termops.refresh_universes *) prg.prg_cinfo.CInfo.typ )
1529
1530 let declare_definition ~pm prg =
1531 let varsubst = obligation_substitution true prg in
1532 let sigma = Evd.from_ctx prg.prg_uctx in
1533 let body, types = subst_prog varsubst prg in
1534 let body, types = EConstr.(of_constr body, of_constr types) in
1535 let cinfo = { prg.prg_cinfo with CInfo.typ = Some types } in
1536 let name, info, opaque, using = prg.prg_cinfo.CInfo.name, prg.prg_info, prg.prg_opaque, prg.prg_using in
1537 let obls = List.map (fun (id, (_, c)) -> (id, c)) varsubst in
1538 (* XXX: This is doing normalization twice *)
1539 let kn, uctx = declare_definition ~cinfo ~info ~obls ~body ~opaque ?using sigma in
1540 (* XXX: We call the obligation hook here, by consistency with the
1541 previous imperative behaviour, however I'm not sure this is right *)
1542 let pm = State.call_prg_hook prg
1543 { Hook.S.uctx; obls; scope = prg.prg_info.Info.scope; dref = kn} pm in
1544 let pm = progmap_remove pm prg in
1545 pm, kn
1546
1547 let declare_mutual_definitions ~pm l =
1548 let first = List.hd l in
1549 let defobl x =
1550 let oblsubst = obligation_substitution true x in
1551 let subs, typ = subst_prog oblsubst x in
1552 let sigma = Evd.from_ctx x.prg_uctx in
1553 let term = EConstr.of_constr subs in
1554 let typ = EConstr.of_constr typ in
1555 let term = EConstr.to_constr sigma term in
1556 let typ = EConstr.to_constr sigma typ in
1557 let def = (x.prg_reduce term, x.prg_reduce typ, x.prg_cinfo.CInfo.impargs) in
1558 let oblsubst = List.map (fun (id, (_, c)) -> (id, c)) oblsubst in
1559 (def, oblsubst)
1560 in
1561 let defs, obls = List.split (List.map defobl l) in
1562 let obls = List.flatten obls in
1563 let fixitems = List.map2 (fun (d, typ, impargs) name ->
1564 let loc = fallback_loc ~warn:false name None in
1565 CInfo.make ?loc ~name ~typ ~impargs ()) defs first.prg_deps in
1566 let fixdefs, fixtypes, _ = List.split3 defs in
1567 let possible_guard = Option.get first.prg_possible_guard in
1568 (* Declare the recursive definitions *)
1569 let kns =
1570 declare_mutual_definitions ~info:first.prg_info
1571 ~eff:Evd.empty_side_effects (* FIXME? *)
1572 ~uctx:first.prg_uctx ~bodies:fixdefs ~possible_guard ~opaque:first.prg_opaque
1573 ~cinfo:fixitems ?using:first.prg_using ()
1574 in
1575 (* Only for the first constant *)
1576 let dref = List.hd kns in
1577 let scope = first.prg_info.Info.scope in
1578 let s_hook = {Hook.S.uctx = first.prg_uctx; obls; scope; dref} in
1579 Hook.call ?hook:first.prg_info.Info.hook s_hook;
1580 (* XXX: We call the obligation hook here, by consistency with the
1581 previous imperative behaviour, however I'm not sure this is right *)
1582 let pm = State.call_prg_hook first s_hook pm in
1583 let pm = List.fold_left progmap_remove pm l in
1584 pm, dref
1585
1586 let update_obls ~pm prg obls rem =
1587 let prg_obligations = {obls; remaining = rem} in
1588 let prg' = {prg with prg_obligations} in
1589 let pm = progmap_replace prg' pm in
1590 obligations_message rem;
1591 if rem > 0 then pm, Remain
1592 else
1593 match prg'.prg_deps with
1594 | [] ->
1595 let pm, kn = declare_definition ~pm prg' in
1596 pm, Defined
1597 | l ->
1598 let progs =
1599 List.map (fun x -> CEphemeron.get (ProgMap.find x pm)) prg'.prg_deps
1600 in
1601 if List.for_all (fun x -> obligations_solved x) progs then
1602 let pm, kn = declare_mutual_definitions ~pm progs in
1603 pm, Defined
1604 else pm, Dependent
1605
1606 let dependencies obls n =
1607 let res = ref Int.Set.empty in
1608 Array.iteri
1609 (fun i obl ->
1610 if (not (Int.equal i n)) && Int.Set.mem n obl.obl_deps then
1611 res := Int.Set.add i !res)
1612 obls;
1613 !res
1614
1615 let update_program_decl_on_defined ~pm prg obls num obl rem ~auto =
1616 let obls = Array.copy obls in
1617 let () = obls.(num) <- obl in
1618 let pm, _progress = update_obls ~pm prg obls (pred rem) in
1619 let pm =
1620 if pred rem > 0 then
1621 let deps = dependencies obls num in
1622 if not (Int.Set.is_empty deps) then
1623 auto ~pm (Some prg.prg_cinfo.CInfo.name) deps None
1624 else pm
1625 else pm
1626 in
1627 pm
1628
1629 type obligation_resolver =
1630 pm:State.t
1631 -> Id.t option
1632 -> Int.Set.t
1633 -> unit Proofview.tactic option
1634 -> State.t
1635
1636 type obl_check_final = AllFinal | SpecificFinal of Id.t
1637
1638 type obligation_qed_info = {
1639 name : Id.t;
1640 num : int;
1641 auto : obligation_resolver;
1642 check_final : obl_check_final option;
1643 }
1644
1645 let not_final_obligation n =
1646 let msg = match n with
1647 | AllFinal -> str "This obligation is not final."
1648 | SpecificFinal n -> str "This obligation is not final for program " ++ Id.print n ++ str "."
1649 in
1650 CErrors.user_err msg
1651
1652 let do_check_final ~pm = function
1653 | None -> ()
1654 | Some check_final ->
1655 let final = match check_final with
1656 | AllFinal -> begin match State.first_pending pm with
1657 | Some _ -> false
1658 | None -> true
1659 end
1660 | SpecificFinal n -> begin match State.get_unique_open_prog pm (Some n) with
1661 | Error _ -> true
1662 | Ok _ -> false
1663 end
1664 in
1665 if not final then not_final_obligation check_final
1666
1667 let obligation_terminator ~pm ~entry ~eff ~uctx ~oinfo:{name; num; auto; check_final} =
1668 let env = Global.env () in
1669 let ty = entry.proof_entry_type in
1670 let body, opaque = ProofEntry.force_entry_body entry in
1671 let body, eff = match opaque with
1672 | Transparent -> (body, Univ.ContextSet.empty), eff
1673 | Opaque (uctx, eff) -> (body, uctx), eff
1674 in
1675 (* TODO: we always inline effects here, maybe we could export them when transparent? *)
1676 let body, uctx = inline_private_constants ~uctx env (body, eff) in
1677 let sigma = Evd.from_ctx uctx in
1678 Inductiveops.control_only_guard (Global.env ()) sigma
1679 (EConstr.of_constr body);
1680 (* Declare the obligation ourselves and drop the hook *)
1681 let prg = Option.get (State.find pm name) in
1682 let {obls; remaining = rem} = prg.prg_obligations in
1683 let obl = obls.(num) in
1684 let status =
1685 match (obl.obl_status, ProofEntry.get_opacity entry) with
1686 | (_, Evar_kinds.Expand), true -> err_not_transp ()
1687 | (true, _), true -> err_not_transp ()
1688 | (false, _), true -> Evar_kinds.Define true
1689 | (_, Evar_kinds.Define true), false -> Evar_kinds.Define false
1690 | (_, status), false -> status
1691 in
1692 let obl = {obl with obl_status = (false, status)} in
1693 let prg, obl, cst = declare_obligation prg obl ~body ~types:ty ~uctx in
1694 let pm = update_program_decl_on_defined ~pm prg obls num obl rem ~auto in
1695 let () = do_check_final ~pm check_final in
1696 pm, cst
1697
1698 (* Similar to the terminator but for the admitted path; this assumes
1699 the admitted constant was already declared.
1700
1701 FIXME: There is duplication of this code with obligation_terminator
1702 and Obligations.admit_obligations *)
1703 let obligation_admitted_terminator ~pm typ {name; num; auto; check_final} declare_fun sec_vars uctx =
1704 let prg = Option.get (State.find pm name) in
1705 let {obls; remaining = rem} = prg.prg_obligations in
1706 let obl = obls.(num) in
1707 let () =
1708 match obl.obl_status with
1709 | true, Evar_kinds.Expand | true, Evar_kinds.Define true -> err_not_transp ()
1710 | _ -> ()
1711 in
1712 let mono_uctx_extra = if PolyFlags.univ_poly prg.prg_info.Info.poly then UState.empty else prg.prg_uctx in
1713 let cst, univs = declare_fun ~uctx ~mono_uctx_extra typ in
1714 let inst = instance_of_univs univs in
1715 let obl = {obl with obl_body = Some (DefinedObl (cst, inst))} in
1716 let prg = update_global_obligation_uctx prg uctx in
1717 let pm = update_program_decl_on_defined ~pm prg obls num obl rem ~auto in
1718 let () = do_check_final ~pm check_final in
1719 pm
1720
1721 end
1722
1723 (************************************************************************)
1724 (* Handling of interactive proofs *)
1725 (************************************************************************)
1726
1727 module Proof_ending = struct
1728
1729 type t =
1730 | Regular
1731 | End_obligation of Obls_.obligation_qed_info
1732 | End_equations of
1733 { hook : pm:Obls_.State.t -> Constant.t list -> Evd.evar_map -> Obls_.State.t
1734 ; i : Id.t
1735 ; types : (Environ.env * Evar.t * Evd.undefined Evd.evar_info * EConstr.named_context * Evd.econstr) list
1736 ; sigma : Evd.evar_map
1737 }
1738
1739 end
1740
1741 module Proof_info = struct
1742
1743 type t =
1744 { cinfo : unit CInfo.t list
1745 (** cinfo contains each individual constant info in a mutual decl *)
1746 ; info : Info.t
1747 ; proof_ending : Proof_ending.t CEphemeron.key
1748 (* This could be improved and the CEphemeron removed *)
1749 ; possible_guard : (Pretyping.possible_guard * Evd.erelevance list) option (* None = not recursive *)
1750 (** thms and compute guard are specific only to
1751 start_definition + regular terminator, so we
1752 could make this per-proof kind *)
1753 }
1754
1755 let make ~cinfo ~info ?possible_guard ?(proof_ending=Proof_ending.Regular) () =
1756 { cinfo
1757 ; info
1758 ; possible_guard
1759 ; proof_ending = CEphemeron.create proof_ending
1760 }
1761
1762 end
1763
1764 module Proof_object = struct
1765
1766 type t =
1767 { proof_object : proof_object
1768 ; pinfo : Proof_info.t
1769 }
1770
1771 end
1772
1773 module Proof = struct
1774
1775 type nonrec closed_proof_output = closed_proof_output
1776 type proof_object = Proof_object.t
1777
1778 type t =
1779 { endline_tactic : Gentactic.glob_generic_tactic option
1780 ; using : Id.Set.t option
1781 ; proof : Proof.t
1782 ; initial_euctx : UState.t
1783 (** The initial universe context (for the statement) *)
1784 ; pinfo : Proof_info.t
1785 ; sideff : SideEff.t;
1786 (** Local constants to replay at the end of the proof. Invariant: the global
1787 environment already contains these constants, including non-logical data
1788 such as nametab and the like. Note that the evarmap within Proof.t may
1789 also contain side-effects, but these ones are not yet globally
1790 registered. *)
1791 }
1792
1793 (*** Proof Global manipulation ***)
1794
1795 let get ps = ps.proof
1796 let get_name ps = (Proof.data ps.proof).Proof.name
1797
1798 let fold ~f p = f p.proof
1799 let map ~f p = { p with proof = f p.proof }
1800 let map_fold ~f p = let proof, res = f p.proof in { p with proof }, res
1801
1802 let map_fold_endline ~f ps =
1803 let (newpr,ret) = f ps.endline_tactic ps.proof in
1804 let ps = { ps with proof = newpr } in
1805 ps, ret
1806
1807 let compact pf = map ~f:Proof.compact pf
1808
1809 (* Sets the tactic to be used when a tactic line is closed with [...] *)
1810 let set_endline_tactic tac ps =
1811 { ps with endline_tactic = Some tac }
1812
1813 let initialize_named_context_for_proof () =
1814 let sign = Global.named_context () in
1815 List.fold_right
1816 (fun d signv ->
1817 let id = NamedDecl.get_id d in
1818 let d = if Decls.variable_opacity id then NamedDecl.drop_body d else d in
1819 Environ.push_named_context_val d signv) sign Environ.empty_named_context_val
1820
1821 let start_proof_core ~name ~pinfo ?using sigma goals =
1822 (* In ?sign, we remove the bodies of variables in the named context
1823 marked "opaque", this is a hack tho, see #10446, and
1824 build_constant_by_tactic uses a different method that would break
1825 program_inference_hook *)
1826 let { Proof_info.info = { Info.poly; typing_flags; _ }; _ } = pinfo in
1827 let goals = List.map (fun (sign, typ) ->
1828 let sign = match sign with None -> initialize_named_context_for_proof () | Some sign -> sign in
1829 (Global.env_of_context sign, typ)) goals in
1830 let proof = Proof.start ~name ~poly ?typing_flags sigma goals in
1831 let initial_euctx = Evd.ustate Proof.((data proof).sigma) in
1832 { proof
1833 ; endline_tactic = None
1834 ; using
1835 ; initial_euctx
1836 ; pinfo
1837 ; sideff = SideEff.empty
1838 }
1839
1840 (** [start_proof ~info ~cinfo sigma] starts a proof of [cinfo].
1841 The proof is started in the evar map [sigma] (which
1842 can typically contain universe constraints) *)
1843 let start_core ~info ~cinfo ?proof_ending ?using sigma =
1844 let { CInfo.name; typ; _ } = cinfo in
1845 check_exists name;
1846 let cinfo = [{ cinfo with CInfo.typ = () }] in
1847 let pinfo = Proof_info.make ~cinfo ~info ?proof_ending () in
1848 start_proof_core ~name ~pinfo ?using sigma [None,typ]
1849
1850 let start = start_core ?proof_ending:None
1851
1852 let start_dependent ~info ~cinfo ~name ~proof_ending goals =
1853 let { Info.poly; typing_flags; _ } = info in
1854 let proof = Proof.dependent_start ~name ~poly ?typing_flags goals in
1855 let initial_euctx = Evd.ustate Proof.((data proof).sigma) in
1856 let pinfo = Proof_info.make ~info ~cinfo ~proof_ending () in
1857 { proof
1858 ; endline_tactic = None
1859 ; using = None
1860 ; initial_euctx
1861 ; pinfo
1862 ; sideff = SideEff.empty
1863 }
1864
1865 let start_derive ~name ~info ~cinfo goals =
1866 let proof_ending = Proof_ending.Regular in
1867 start_dependent ~info ~cinfo ~name ~proof_ending goals
1868
1869 let start_equations ~name ~info ~hook ~types sigma goals =
1870 let proof_ending = Proof_ending.End_equations {hook; i=name; types; sigma} in
1871 start_dependent ~name ~cinfo:[] ~info ~proof_ending goals
1872
1873 let start_definition ~info ~cinfo ?using sigma =
1874 let { CInfo.name; typ; args } = cinfo in
1875 let init_tac = Tactics.auto_intros_tac args in
1876 let pinfo = Proof_info.make ~cinfo:[{cinfo with typ = ()}] ~info () in
1877 let env = Global.env () in
1878 let using = Option.map (interp_proof_using_cinfo env sigma [cinfo]) using in
1879 let lemma = start_proof_core ~name ~pinfo ?using sigma [None, typ] in
1880 map lemma ~f:(fun p ->
1881 pi1 @@ Proof.run_tactic Global.(env ()) init_tac p)
1882
1883 let start_mutual_definitions ~info ~cinfo ~bodies ~possible_guard ?using sigma =
1884 let intro_tac { CInfo.args; _ } = Tactics.auto_intros_tac args in
1885 let (possible_guard, fixrs) = possible_guard in
1886 let fixrs = List.map EConstr.ERelevance.make fixrs in
1887 let cinfo' = List.map (fun cinfo -> { cinfo with CInfo.typ = EConstr.of_constr cinfo.CInfo.typ }) cinfo in
1888 let init_tac =
1889 (* This is the case for hybrid proof mode / definition
1890 fixpoint, where terms for some constants are given with := *)
1891 let tacl = List.map (Option.cata (EConstr.of_constr %> Tactics.exact_no_check) Tacticals.tclIDTAC) bodies in
1892 List.map2 (fun tac thm -> Tacticals.tclTHEN tac (intro_tac thm)) tacl cinfo'
1893 in
1894 match cinfo' with
1895 | [] -> CErrors.anomaly (Pp.str "No proof to start.")
1896 | { CInfo.name; _} :: _ as thms ->
1897 let pinfo = Proof_info.make ~cinfo:(List.map (fun cinfo -> {cinfo with CInfo.typ = ()}) cinfo) ~info ~possible_guard:(possible_guard, fixrs) () in
1898 (* start_lemma has the responsibility to add (name, impargs, typ)
1899 to thms, once Info.t is more refined this won't be necessary *)
1900 let env = Global.env () in
1901 let sign =
1902 List.fold_left2 (fun sign CInfo.{name;typ} r ->
1903 let decl = Context.Named.Declaration.LocalAssum (Context.make_annot name r, typ) in
1904 EConstr.push_named_context_val decl sign) (initialize_named_context_for_proof ()) cinfo' fixrs in
1905 let using = Option.map (interp_proof_using_cinfo env sigma cinfo') using in
1906 let goals = List.map (function CInfo.{typ} -> (Some sign, typ)) thms in
1907 let lemma = start_proof_core ~name ~pinfo ?using sigma goals in
1908 let lemma = map lemma ~f:(fun p ->
1909 pi1 @@ Proof.run_tactic Global.(env ()) (Proofview.tclFOCUS 1 (List.length thms) (Proofview.tclDISPATCH init_tac)) p) in
1910 let () =
1911 (* Temporary declaration of notations for the time of the proofs *)
1912 let ntn_env =
1913 (* We simulate the goal context in which the fixpoint bodies have to be proved (exact relevance does not matter) *)
1914 let make_decl CInfo.{name; typ} = Context.Named.Declaration.LocalAssum (Context.annotR name, typ) in
1915 Environ.push_named_context (List.map make_decl cinfo) (Global.env()) in
1916 List.iter (Metasyntax.add_notation_interpretation ~local:(info.scope=Locality.Discharge) ntn_env) info.ntns in
1917 lemma
1918
1919 let start_mutual_definitions_refine ~info ~cinfo ~bodies ~possible_guard ?using sigma =
1920 let future_goals, sigma = Evd.pop_future_goals sigma in
1921 let gls = List.rev (Evd.FutureGoals.comb future_goals) in
1922 let sigma = Evd.push_future_goals sigma in
1923
1924 let intro_tac { CInfo.args; _ } = Tactics.auto_intros_tac args in
1925 let fixrs = snd possible_guard in
1926 let init_tac =
1927 let tacl = List.map (Option.cata (fun body -> Refine.refine ~typecheck:false (fun sigma -> sigma, body)) Tacticals.tclIDTAC) bodies in
1928 List.map2 (fun tac thm -> Tacticals.tclTHEN tac (intro_tac thm)) tacl cinfo
1929 in
1930 match cinfo with
1931 | [] -> CErrors.anomaly (Pp.str "No proof to start.")
1932 | { CInfo.name; _} :: _ as thms ->
1933 let pinfo = Proof_info.make ~cinfo:(List.map (fun cinfo -> {cinfo with CInfo.typ = ()}) cinfo) ~info ~possible_guard () in
1934 (* start_lemma has the responsibility to add (name, impargs, typ)
1935 to thms, once Info.t is more refined this won't be necessary *)
1936 let env = Global.env () in
1937 let sign =
1938 List.fold_left2 (fun sign CInfo.{name;typ} r ->
1939 let decl = Context.Named.Declaration.LocalAssum (Context.make_annot name r, typ) in
1940 EConstr.push_named_context_val decl sign) (initialize_named_context_for_proof ()) cinfo fixrs in
1941 let using = Option.map (interp_proof_using_cinfo env sigma cinfo) using in
1942 let goals = List.map (function CInfo.{typ} -> (Some sign, typ)) thms in
1943 let lemma = start_proof_core ~name ~pinfo ?using sigma goals in
1944 let lemma = map lemma ~f:(fun p ->
1945 pi1 @@ Proof.run_tactic Global.(env ())
1946 (Tacticals.tclTHENLIST [
1947 Proofview.tclFOCUS 1 (List.length thms) (Proofview.tclDISPATCH init_tac);
1948 Proofview.Unsafe.tclNEWGOALS (CList.map Proofview.with_empty_state gls);
1949 Tactics.reduce_after_refine;
1950 ]) p) in
1951 let () =
1952 (* Temporary declaration of notations for the time of the proofs *)
1953 let ntn_env =
1954 (* We simulate the goal context in which the fixpoint bodies have to be proved (exact relevance does not matter) *)
1955 let make_decl CInfo.{name; typ} = Context.Named.Declaration.LocalAssum (Context.annotR name, EConstr.Unsafe.to_constr typ) in
1956 Environ.push_named_context (List.map make_decl cinfo) (Global.env()) in
1957 List.iter (Metasyntax.add_notation_interpretation ~local:(info.scope=Locality.Discharge) ntn_env) info.ntns in
1958 lemma
1959
1960 let get_used_variables pf = pf.using
1961
1962 let definition_scope ps = ps.pinfo.info.scope
1963
1964 let set_used_variables ps ~using =
1965 let open Context.Named.Declaration in
1966 let env = Global.env () in
1967 let ctx = Environ.keep_hyps env using in
1968 let ctx_set =
1969 List.fold_right Id.Set.add (List.map NamedDecl.get_id ctx) Id.Set.empty in
1970 let vars_of = Environ.global_vars_set in
1971 let aux env entry (ctx, all_safe as orig) =
1972 match entry with
1973 | LocalAssum ({Context.binder_name=x},_) ->
1974 if Id.Set.mem x all_safe then orig
1975 else (ctx, all_safe)
1976 | LocalDef ({Context.binder_name=x},bo, ty) as decl ->
1977 if Id.Set.mem x all_safe then orig else
1978 let vars = Id.Set.union (vars_of env bo) (vars_of env ty) in
1979 if Id.Set.subset vars all_safe
1980 then (decl :: ctx, Id.Set.add x all_safe)
1981 else (ctx, all_safe) in
1982 let ctx, _ =
1983 Environ.fold_named_context aux env ~init:(ctx,ctx_set) in
1984 if not (Option.is_empty ps.using) then
1985 CErrors.user_err Pp.(str "Used section variables can be declared only once");
1986 ctx, { ps with using = Some (Context.Named.to_vars ctx) }
1987
1988 (* Interprets the expression in the current proof context, from vernacentries *)
1989 let get_recnames pf =
1990 if Option.has_some pf.pinfo.Proof_info.possible_guard then
1991 List.map (fun c -> c.CInfo.name) pf.pinfo.Proof_info.cinfo
1992 else
1993 []
1994
1995 let interpret_proof_using pstate using =
1996 let env = Global.env () in
1997 let pf = get pstate in
1998 let sigma, _ = Proof.get_proof_context pf in
1999 let fixnames = get_recnames pstate in
2000 let initial_goals pf = Proofview.initial_goals Proof.((data pf).entry) in
2001 let terms = List.map pi3 (initial_goals (get pstate)) in
2002 Proof_using.definition_using env sigma ~fixnames ~using ~terms
2003
2004 let set_proof_using pstate using =
2005 let using = interpret_proof_using pstate using in
2006 set_used_variables pstate ~using
2007
2008 let get_open_goals ps =
2009 let Proof.{ goals; stack; sigma } = Proof.data ps.proof in
2010 List.length goals +
2011 List.fold_left (+) 0
2012 (List.map (fun (l1,l2) -> List.length l1 + List.length l2) stack) +
2013 List.length (Evd.shelf sigma)
2014
2015 let warn_remaining_shelved_goals =
2016 CWarnings.create ~name:"remaining-shelved-goals" ~category:CWarnings.CoreCategories.tactics
2017 (fun () -> Pp.str"The proof has remaining shelved goals.")
2018
2019 let warn_given_up =
2020 CWarnings.create ~name:"remaining-given-up" ~category:CWarnings.CoreCategories.tactics
2021 (fun () -> Pp.str"The proof has given up (admitted) goals." )
2022
2023 let warn_remaining_unresolved_evars =
2024 CWarnings.create ~name:"remaining-unresolved-evars" ~category:CWarnings.CoreCategories.tactics
2025 (fun () -> Pp.str"The proof has unresolved variables.")
2026
2027 type open_proof_kind =
2028 | OpenGoals
2029 | NonGroundResult of bool (* true = at least some of the evars in the proof term are given up *)
2030
2031 exception OpenProof of Names.Id.t * open_proof_kind
2032
2033 let () = CErrors.register_handler begin function
2034 | OpenProof (pid, reason) ->
2035 let open Pp in
2036 let ppreason = match reason with
2037 | OpenGoals -> str "(there are remaining open goals)"
2038 | NonGroundResult has_given_up ->
2039 str "(the proof term is not complete" ++
2040 (if has_given_up then str " because of given up (admitted) goals" else mt()) ++
2041 str ")"
2042 in
2043 let how_to_admit = match reason with
2044 | OpenGoals | NonGroundResult false -> mt()
2045 | NonGroundResult true ->
2046 fnl() ++ str "If this is really what you want to do, use Admitted in place of Qed."
2047 in
2048 Some (str " (in proof " ++ Names.Id.print pid ++ str "): " ++
2049 str "Attempt to save an incomplete proof" ++ spc() ++ ppreason ++ str "." ++
2050 how_to_admit)
2051 | _ -> None
2052 end
2053
2054 let raise_non_ground_proof evd pid c =
2055 let has_given_up =
2056 let exception Found in
2057 let rec aux c =
2058 let () = match EConstr.kind evd c with
2059 | Evar (e,_) -> if Evar.Set.mem e (Evd.given_up evd) then raise Found
2060 | _ -> ()
2061 in
2062 EConstr.iter evd aux c
2063 in
2064 try aux c; false with Found -> true
2065 in
2066 raise (OpenProof (pid, NonGroundResult has_given_up))
2067
2068 let check_incomplete_proof evd =
2069 if Evd.has_shelved evd then warn_remaining_shelved_goals ()
2070 else if Evd.has_given_up evd then warn_given_up ()
2071 else if Evd.has_undefined evd then warn_remaining_unresolved_evars ()
2072
2073 (* XXX: This is still separate from close_proof below due to drop_pt in the STM *)
2074 let prepare_proof ?(warn_incomplete=true) { proof; pinfo; sideff } =
2075 let Proof.{name=pid;entry;poly;sigma=evd} = Proof.data proof in
2076 let initial_goals = Proofview.initial_goals entry in
2077 let () = if not @@ Proof.is_done proof then raise (OpenProof (pid, OpenGoals)) in
2078 let _ : Proof.t =
2079 (* checks that we closed all brackets ("}") *)
2080 Proof.unfocus_all proof
2081 in
2082 let eff = SideEff.make @@ Evd.eval_side_effects evd in
2083 let evd = Evd.minimize_universes evd in
2084 let to_constr c =
2085 match EConstr.to_constr_opt evd c with
2086 | Some p -> p
2087 | None -> raise_non_ground_proof evd pid c
2088 in
2089 let proofs = List.map (fun (_, body, typ) -> (to_constr body, to_constr typ)) initial_goals in
2090 let proofs = match pinfo.possible_guard with
2091 | None -> proofs
2092 | Some (possible_guard, fixrelevances) ->
2093 let env = Safe_typing.push_private_constants (Global.env()) (SideEff.get eff) in
2094 let fixbodies, fixtypes = List.split proofs in
2095 let fixrelevances = List.map (EConstr.ERelevance.kind evd) fixrelevances in
2096 let rec_declaration = prepare_recursive_declaration pinfo.cinfo fixtypes fixrelevances fixbodies in
2097 let typing_flags = pinfo.info.typing_flags in
2098 fst (make_recursive_bodies ~elim_to:(Inductive.eliminates_to (Evd.elim_graph evd)) env ~typing_flags ~possible_guard ~rec_declaration) in
2099 let proofs = List.map (fun (body, typ) -> (body, Some typ)) proofs in
2100 let () = if warn_incomplete then check_incomplete_proof evd in
2101 { output_entries = proofs; output_ustate = Evd.ustate evd; output_sideff = SideEff.concat eff sideff }
2102
2103 exception NotGuarded of
2104 Environ.env * Evd.evar_map *
2105 (Environ.env * int * EConstr.t Type_errors.pcofix_guard_error) option *
2106 (Environ.env * int * int list * EConstr.t Type_errors.pfix_guard_error) list *
2107 EConstr.rec_declaration
2108
2109 let () = CErrors.register_handler (function
2110 | NotGuarded (env, sigma, cofix_err, fix_errs, rec_declaration) ->
2111 Some (Himsg.explain_not_guarded env sigma cofix_err fix_errs rec_declaration)
2112 | _ -> None)
2113
2114 let control_only_guard { proof; pinfo } =
2115 let { Proof.entry; Proof.sigma; } = Proof.data proof in
2116 let initial_goals = Proofview.initial_goals entry in
2117 let proofs = List.map (fun (_, body, typ) -> Evarutil.(nf_evar sigma body, nf_evar sigma typ)) initial_goals in
2118 let eff = Evd.eval_side_effects sigma in
2119 let env = Safe_typing.push_private_constants (Global.env()) (Evd.seff_private eff) in
2120 let open Proof_info in
2121 match pinfo.possible_guard with
2122 | None ->
2123 List.iter (fun (body, _) -> Inductiveops.control_only_guard env sigma body) proofs
2124 | Some (possible_guard, fixrelevances) ->
2125 let fixbodies, fixtypes = List.split proofs in
2126 let rec_declaration = prepare_recursive_edeclaration sigma pinfo.cinfo fixtypes fixrelevances fixbodies in
2127 try
2128 let cofix_error =
2129 if possible_guard.possibly_cofix then
2130 try
2131 Inductiveops.control_only_guard env sigma (EConstr.mkCoFix (0,rec_declaration));
2132 raise Exit
2133 with Pretype_errors.PretypeError (env, sigma, TypingError (IllFormedRecBody (CoFixGuardError why,lna,i,fixenv,vdefj))) ->
2134 Some (env,i,why)
2135 else None
2136 in
2137 let combinations = List.combinations possible_guard.possible_fix_indices in
2138 let fix_errors =
2139 List.map (fun lv ->
2140 try
2141 Inductiveops.control_only_guard env sigma (EConstr.mkFix ((Array.of_list lv,0),rec_declaration));
2142 raise Exit
2143 with Pretype_errors.PretypeError (env, sigma, TypingError (IllFormedRecBody (FixGuardError why,lna,i,fixenv,vdefj))) ->
2144 (env,i,lv,why))
2145 combinations
2146 in
2147 raise (NotGuarded (env, sigma, cofix_error, fix_errors, rec_declaration))
2148 with Exit -> ()
2149
2150 let return_proof p = (prepare_proof p : closed_proof_output)
2151
2152 let close_proof ?warn_incomplete ~opaque ~keep_body_ucst_separate (proof : t) : Proof_object.t =
2153 NewProfile.profile "close_proof" (fun () ->
2154 let opaque = match opaque with
2155 | Vernacexpr.Opaque -> true
2156 | Vernacexpr.Transparent -> false in
2157 let keep_body_ucst_separate = if keep_body_ucst_separate then Some proof.initial_euctx else None in
2158 { Proof_object.proof_object =
2159 DefaultProof { proof = prepare_proof ?warn_incomplete proof; opaque; using = proof.using; keep_body_ucst_separate }
2160 ; pinfo = proof.pinfo
2161 }) ()
2162
2163 let close_future_proof ~feedback_id proof (fpl : closed_proof_output Future.computation) : Proof_object.t =
2164 { Proof_object.proof_object =
2165 DeferredOpaqueProof { deferred_proof = fpl; using = proof.using; initial_proof_data = Proof.data proof.proof;
2166 feedback_id; initial_euctx = proof.initial_euctx }
2167 ; pinfo = proof.pinfo
2168 }
2169
2170 let update_sigma_univs ugraph p =
2171 map ~f:(Proof.update_sigma_univs ugraph) p
2172
2173 let by env tac pf =
2174 let pf, safe = map_fold ~f:(Proof.solve env (Goal_select.select_nth 1) None tac) pf in
2175 let proof, eff = register_side_effects pf.proof in
2176 let sideff = SideEff.concat eff pf.sideff in
2177 { pf with proof; sideff }, safe
2178
2179 let get_goal_context pf i =
2180 let p = get pf in
2181 Proof.get_goal_context_gen p i
2182
2183 let get_current_context pf =
2184 let p = get pf in
2185 Proof.get_proof_context p
2186
2187 (************************************************************************)
2188 (* Admitting a lemma-like constant *)
2189 (************************************************************************)
2190
2191 (* Admitted *)
2192 let { Goptions.get = get_keep_admitted_vars } =
2193 Goptions.declare_bool_option_and_ref
2194 ~key:["Keep"; "Admitted"; "Variables"]
2195 ~value:true
2196 ()
2197
2198 let compute_proof_using_for_admitted pinfo proof typs iproof =
2199 if not (get_keep_admitted_vars ()) || not (Lib.sections_are_opened()) then None
2200 else match get_used_variables proof with
2201 | Some _ as x -> x
2202 | None ->
2203 let pproofs = Proof.partial_proof iproof in
2204 let env = Global.env () in
2205 let sigma = (Proof.data iproof).Proof.sigma in
2206 let ids_def = Id.Set.List.union (List.map (Termops.global_vars_set env sigma) pproofs) in
2207 let ids_typ = Id.Set.List.union (List.map (Termops.global_vars_set env sigma) typs) in
2208 (* [pproof] is evar-normalized by [partial_proof]. We don't
2209 count variables appearing only in the type of evars. *)
2210 let vars = Id.Set.union ids_def ids_typ in
2211 let vars = match pinfo.Proof_info.possible_guard with
2212 | Some _ ->
2213 let recvars = Id.Set.of_list (List.map (fun CInfo.{name} -> name) pinfo.cinfo) in
2214 Id.Set.diff vars recvars
2215 | None -> vars
2216 in
2217 Some (Environ.really_needed env vars)
2218
2219 let check_type_evars_solved env sigma typ =
2220 let evars = Evar.Set.elements (Evarutil.undefined_evars_of_term sigma typ) in
2221 match evars with
2222 | [] -> ()
2223 | evk::_ -> CErrors.user_err (str "Cannot admit: the statement has unresolved existential variables.")
2224
2225 let finish_admitted ~pm ~pinfo ~sec_vars typs =
2226 (* If the constant was an obligation we need to update the program map *)
2227 let { Proof_info.info; cinfo } = pinfo in
2228 match CEphemeron.default pinfo.Proof_info.proof_ending Proof_ending.Regular with
2229 | Proof_ending.End_obligation oinfo ->
2230 let declare_fun ~uctx ~mono_uctx_extra typ =
2231 List.hd (declare_possibly_mutual_parameters ~info ~cinfo ~sec_vars ~mono_uctx_extra [typ, uctx]) in
2232 let typ, uctx = match typs with [typ, uctx] -> typ, uctx | _ -> assert false in
2233 Obls_.obligation_admitted_terminator ~pm typ oinfo declare_fun sec_vars uctx
2234 | _ ->
2235 let (_ : 'a list) = declare_possibly_mutual_parameters ~info ~cinfo ~sec_vars typs in
2236 pm
2237
2238 let save_admitted ~pm ~proof =
2239 let iproof = get proof in
2240 let Proof.{ entry } = Proof.data iproof in
2241 let typs = List.map pi3 (Proofview.initial_goals entry) in
2242 let sigma = Evd.from_ctx proof.initial_euctx in
2243 List.iter (check_type_evars_solved (Global.env()) sigma) typs;
2244 let sec_vars = compute_proof_using_for_admitted proof.pinfo proof typs iproof in
2245 let sigma = Evd.minimize_universes sigma in
2246 let uctx = Evd.ustate sigma in
2247 let typs = List.map (fun typ -> (EConstr.to_constr sigma typ, uctx)) typs in
2248 finish_admitted ~pm ~pinfo:proof.pinfo ~sec_vars typs
2249
2250 (************************************************************************)
2251 (* Saving a lemma-like constant *)
2252 (************************************************************************)
2253
2254 let finish_proved_equations ~pm ~kind ~hook i entries types sigma0 =
2255
2256 let obls = ref 1 in
2257 let sigma, recobls =
2258 CList.fold_left2_map (fun sigma (_evar_env, ev, _evi, local_context, _type) entry ->
2259 let id =
2260 match Evd.evar_ident ev sigma0 with
2261 | Some id -> Libnames.basename id (* XXX: should deambiguate somehow *)
2262 | None ->
2263 let n = !obls in
2264 let () = incr obls in
2265 let id = Nameops.add_suffix i ("_obligation_" ^ string_of_int n) in
2266 id
2267 in
2268 let body, opaque = match entry.proof_entry_body with Default { body; opaque } -> body, opaque | _ -> assert false in
2269 let typ = match entry.proof_entry_type with None -> assert false | Some typ -> typ in
2270 let body, typ, args = Subproof.shrink_entry local_context body typ in
2271 let entry = { entry with proof_entry_body = Default { body; opaque }; proof_entry_type = Some typ } in
2272 let cst = declare_constant ~loc:None ~name:id ~kind ~typing_flags:None (DefinitionEntry entry) in
2273 let sigma, app = Evd.fresh_global (Global.env ()) sigma (GlobRef.ConstRef cst) in
2274 let sigma = Evd.define ev (EConstr.applist (app, args)) sigma in
2275 sigma, cst) sigma0
2276 types entries
2277 in
2278 let pm = hook ~pm recobls sigma in
2279 pm, List.map (fun cst -> GlobRef.ConstRef cst) recobls
2280
2281 let check_single_entry entries label =
2282 match entries with
2283 | [entry, uctx] -> entry, uctx
2284 | _ ->
2285 CErrors.anomaly ~label Pp.(str "close_proof returned more than one proof term")
2286
2287 let finish_proof ~pm proof_obj proof_info =
2288 let open Proof_ending in
2289 let { Proof_info.info; cinfo; possible_guard } = proof_info in
2290 match CEphemeron.default proof_info.Proof_info.proof_ending Regular with
2291 | Regular ->
2292 (* Unless this is a block of mutual fixpoint, we assume the
2293 statements, if more than one, to form a telescope, as in Derive *)
2294 let is_telescope = Option.is_empty proof_info.possible_guard in
2295 pm, declare_possibly_mutual_definitions ~info ~cinfo ~obls:[] ~is_telescope proof_obj
2296 | End_obligation oinfo ->
2297 let eff, entries = process_proof ~info proof_obj in
2298 let entry, uctx = check_single_entry entries "Obligation.save" in
2299 Obls_.obligation_terminator ~pm ~entry ~eff ~uctx ~oinfo
2300 | End_equations { hook; i; types; sigma } ->
2301 let kind = info.Info.kind in
2302 let eff, entries = process_proof ~info proof_obj in
2303 (* FIXME: this is probably not the right place to declare effects *)
2304 let () = export_side_effects eff in
2305 let entries = List.map fst entries in
2306 finish_proved_equations ~pm ~kind ~hook i entries types sigma
2307
2308 let err_save_forbidden_in_place_of_qed () =
2309 CErrors.user_err (Pp.str "Cannot use Save with more than one constant or in this proof mode")
2310
2311 let process_idopt_for_save ~idopt info =
2312 match idopt with
2313 | None -> info
2314 | Some { CAst.v = save_name } ->
2315 (* Save foo was used; we override the info in the first theorem *)
2316 let cinfo =
2317 match info.Proof_info.cinfo, CEphemeron.default info.Proof_info.proof_ending Proof_ending.Regular with
2318 | [ { CInfo.name; _} as decl ], Proof_ending.Regular ->
2319 [ { decl with CInfo.name = save_name } ]
2320 | _ ->
2321 err_save_forbidden_in_place_of_qed ()
2322 in { info with Proof_info.cinfo }
2323
2324 let save ~pm ~proof ~opaque ~idopt =
2325 (* Env and sigma are just used for error printing in save_remaining_recthms *)
2326 let proof_obj = close_proof ~opaque ~keep_body_ucst_separate:false proof in
2327 let proof_info = process_idopt_for_save ~idopt proof.pinfo in
2328 finish_proof ~pm proof_obj.proof_object proof_info
2329
2330 let save_regular ~(proof : t) ~opaque ~idopt =
2331 let open Proof_ending in
2332 match CEphemeron.default proof.pinfo.Proof_info.proof_ending Regular with
2333 | Regular ->
2334 let (_, grs) : Obls_.State.t * _ = save ~pm:Obls_.State.empty ~proof ~opaque ~idopt in
2335 grs
2336 | _ -> CErrors.anomaly Pp.(str "save_regular: unexpected proof ending")
2337
2338 (***********************************************************************)
2339 (* Special case to close a lemma without forcing a proof *)
2340 (***********************************************************************)
2341 let save_lemma_admitted_delayed ~pm ~proof =
2342 let { Proof_object.proof_object; pinfo } = proof in
2343 (* Drop side-effects, they will not be used anyway *)
2344 let _eff, entries = process_proof ~info:pinfo.info proof_object in
2345 let typs = List.map (function { proof_entry_type }, uctx -> Option.get proof_entry_type, uctx) entries in
2346 (* Note: an alternative would be to compute sec_vars of the partial
2347 proof as a Future computation, as in compute_proof_using_for_admitted *)
2348 let sec_vars = if get_keep_admitted_vars () then (fst (List.hd entries)).proof_entry_secctx else None in
2349 (* If the proof is partial, do we want to take the (restriction on
2350 visible uvars of) uctx so far or (as done below) the initial ones
2351 that refers to only the types *)
2352 finish_admitted ~pm ~pinfo:proof.pinfo ~sec_vars typs
2353
2354 let save_lemma_proved_delayed ~pm ~proof ~idopt =
2355 (* vio2vo used to call this with invalid [pinfo], now it should work fine. *)
2356 let pinfo = process_idopt_for_save ~idopt proof.Proof_object.pinfo in
2357 let pm, _ = finish_proof ~pm proof.proof_object pinfo in
2358 pm
2359
2360 end (* Proof module *)
2361
2362 let _ = Ind_tables.declare_definition_scheme := declare_definition_scheme
2363 let _ = Ind_tables.register_definition_scheme := register_definition_scheme
2364
2365 module Internal = struct
2366
2367 module Constant = struct
2368 type t = constant_obj
2369 let tag = objConstant
2370 let kind obj = obj.cst_kind
2371 end
2372
2373 let objVariable = objVariable
2374
2375 let export_side_effects eff = export_side_effects (SideEff.make eff)
2376
2377 let register_side_effects pf =
2378 let proof, eff = register_side_effects pf.Proof.proof in
2379 let sideff = SideEff.concat eff pf.sideff in
2380 { pf with proof; sideff }
2381
2382 end
2383
2384 (* This module could be merged with Obl, and placed before [Proof],
2385 however there is a single dependency on [Proof.start] for the interactive case *)
2386 module Obls = struct
2387 (* For the records fields, opens should go away one these types are private *)
2388 open Obls_
2389 open Obls_.Obligation
2390 open Obls_.ProgramDecl
2391
2392 let reduce c =
2393 let env = Global.env () in
2394 let sigma = Evd.from_env env in
2395 EConstr.Unsafe.to_constr (Reductionops.clos_norm_flags RedFlags.betaiota env sigma (EConstr.of_constr c))
2396
2397 let explain_no_obligations = function
2398 Some ident -> str "No obligations for program " ++ Id.print ident
2399 | None -> str "No obligations remaining"
2400
2401 module Error = struct
2402
2403 let no_obligations n =
2404 CErrors.user_err (explain_no_obligations n)
2405
2406 let ambiguous_program id ids =
2407 CErrors.user_err
2408 Pp.(str "More than one program with unsolved obligations: " ++ prlist Id.print ids
2409 ++ str "; use the \"of\" clause to specify, as in \"Obligation 1 of " ++ Id.print id ++ str "\"")
2410
2411 let unknown_obligation num =
2412 CErrors.user_err (Pp.str (Printf.sprintf "Unknown obligation number %i" (succ num)))
2413
2414 let already_solved num =
2415 CErrors.user_err Pp.(str "Obligation " ++ int num ++ str " already solved." )
2416
2417 let depends num rem =
2418 CErrors.user_err
2419 ( str "Obligation " ++ int num
2420 ++ str " depends on obligation(s) "
2421 ++ pr_sequence (fun x -> int (succ x)) rem)
2422
2423 end
2424
2425 let default_tactic = ref (Proofview.tclUNIT ())
2426
2427 let subst_deps expand obls deps t =
2428 let osubst = Obls_.obl_substitution expand obls deps in
2429 (Vars.replace_vars (List.map (fun (n, (_, b)) -> n, b) osubst) t)
2430
2431 let subst_deps_obl obls obl =
2432 let t' = subst_deps true obls obl.obl_deps obl.obl_type in
2433 Obligation.set_type ~typ:t' obl
2434
2435 let is_defined obls x = not (Option.is_empty obls.(x).obl_body)
2436
2437 let deps_remaining obls deps =
2438 Int.Set.fold
2439 (fun x acc ->
2440 if is_defined obls x then acc
2441 else x :: acc)
2442 deps []
2443
2444 let goal_kind = Decls.(IsDefinition Definition)
2445 let goal_proof_kind = Decls.(IsProof Lemma)
2446
2447 let kind_of_obligation o =
2448 match o with
2449 | Evar_kinds.Define false
2450 | Evar_kinds.Expand -> goal_kind
2451 | _ -> goal_proof_kind
2452
2453 (* Solve an obligation using tactics, return the corresponding proof term *)
2454 let warn_solve_errored =
2455 CWarnings.create ~name:"solve_obligation_error" ~category:CWarnings.CoreCategories.tactics
2456 (fun err ->
2457 Pp.seq
2458 [ str "Solve Obligations tactic returned error: "
2459 ; err
2460 ; fnl ()
2461 ; str "This will become an error in the future" ])
2462
2463 let solve_by_tac prg obls i tac =
2464 let obl = obls.(i) in
2465 let obl = subst_deps_obl obls obl in
2466 let tac = Option.(default !default_tactic (append tac obl.obl_tac)) in
2467 let uctx = Internal.get_uctx prg in
2468 let uctx = UState.update_sigma_univs uctx (Global.universes ()) in
2469 let poly = Internal.get_poly prg in
2470 (* the status of [build_by_tactic] is dropped. *)
2471 try
2472 let env = Global.env () in
2473 let typ = EConstr.of_constr obl.obl_type in
2474 (* If the proof is open we absorb the error and leave the obligation open *)
2475 match Subproof.build_by_tactic_opt env ~uctx ~poly ~typ tac with
2476 | None -> None
2477 | Some (body, types, _univs, _, uctx) ->
2478 let () = Inductiveops.control_only_guard env (Evd.from_ctx uctx) (EConstr.of_constr body) in
2479 Some (body, types, uctx)
2480 with
2481 | Tacticals.FailError (_, s) as exn ->
2482 let _ = Exninfo.capture exn in
2483 let loc = fst obl.obl_location in
2484 CErrors.user_err ?loc (Lazy.force s)
2485 | e when CErrors.noncritical e ->
2486 let err = CErrors.print e in
2487 let loc = fst obl.obl_location in
2488 warn_solve_errored ?loc err;
2489 None
2490
2491 let solve_and_declare_by_tac prg obls i tac =
2492 match solve_by_tac prg obls i tac with
2493 | None -> None
2494 | Some (t, ty, uctx) ->
2495 let obl = obls.(i) in
2496 let prg, obl', _cst = declare_obligation prg obl ~body:t ~types:(Some ty) ~uctx in
2497 obls.(i) <- obl';
2498 Some prg
2499
2500 let solve_obligation_by_tac prg obls i tac =
2501 let obl = obls.(i) in
2502 match obl.obl_body with
2503 | Some _ -> None
2504 | None ->
2505 if List.is_empty (deps_remaining obls obl.obl_deps)
2506 then solve_and_declare_by_tac prg obls i tac
2507 else None
2508
2509 let get_unique_prog ~pm prg =
2510 match State.get_unique_open_prog pm prg with
2511 | Ok prg -> prg
2512 | Error [] ->
2513 Error.no_obligations None
2514 | Error ((id :: _) as ids) ->
2515 Error.ambiguous_program id ids
2516
2517 let solve_prg_obligations ~pm prg ?oblset tac =
2518 let { obls; remaining } = Internal.get_obligations prg in
2519 let rem = ref remaining in
2520 let obls' = Array.copy obls in
2521 let set = ref Int.Set.empty in
2522 let p = match oblset with
2523 | None -> (fun _ -> true)
2524 | Some s -> set := s;
2525 (fun i -> Int.Set.mem i !set)
2526 in
2527 let prg =
2528 Array.fold_left_i
2529 (fun i prg x ->
2530 if p i then (
2531 match solve_obligation_by_tac prg obls' i tac with
2532 | None -> prg
2533 | Some prg ->
2534 let deps = dependencies obls i in
2535 set := Int.Set.union !set deps;
2536 decr rem;
2537 prg)
2538 else prg)
2539 prg obls'
2540 in
2541 update_obls ~pm prg obls' !rem
2542
2543 let auto_solve_obligations ~pm n ?oblset tac : State.t * progress =
2544 Flags.if_verbose Feedback.msg_info
2545 (str "Solving obligations automatically...");
2546 let prg = get_unique_prog ~pm n in
2547 solve_prg_obligations ~pm prg ?oblset tac
2548
2549 let solve_obligation ?check_final prg num tac =
2550 let user_num = succ num in
2551 let { obls; remaining=rem } = Internal.get_obligations prg in
2552 let obl = obls.(num) in
2553 let remaining = deps_remaining obls obl.obl_deps in
2554 let () =
2555 if not (Option.is_empty obl.obl_body)
2556 then Error.already_solved user_num;
2557 if not (List.is_empty remaining)
2558 then Error.depends user_num remaining
2559 in
2560 let obl = subst_deps_obl obls obl in
2561 let kind = kind_of_obligation (snd obl.obl_status) in
2562 let evd = Evd.from_ctx (Internal.get_uctx prg) in
2563 let evd = Evd.update_sigma_univs (Global.universes ()) evd in
2564 let auto ~pm n oblset tac = fst (auto_solve_obligations ~pm n ~oblset tac) in
2565 let proof_ending =
2566 let name = Internal.get_name prg in
2567 Proof_ending.End_obligation {name; num; auto; check_final}
2568 in
2569 let cinfo = CInfo.make ?loc:(fallback_loc ~warn:false obl.obl_name None)
2570 ~name:obl.obl_name ~typ:(EConstr.of_constr obl.obl_type) ()
2571 in
2572 let using =
2573 let using = Internal.get_using prg in
2574 let env = Global.env () in
2575 let f {CInfo.name; typ; _} = name, [typ] in
2576 Option.map (interp_proof_using_gen f env evd [cinfo]) using
2577 in
2578 let poly = Internal.get_poly prg in
2579 let info = Info.make ~kind ~poly () in
2580 let lemma = Proof.start_core ~cinfo ~info ~proof_ending ?using evd in
2581 let lemma = fst @@ Proof.by (Global.env ()) !default_tactic lemma in
2582 let lemma = Option.cata (fun tac -> Proof.set_endline_tactic tac lemma) lemma tac in
2583 lemma
2584
2585 (** Implements [Solve Obligations of name with tac] *)
2586 let solve_obligations ~pm n tac =
2587 let prg = get_unique_prog ~pm n in
2588 fst (solve_prg_obligations ~pm prg tac)
2589
2590 (** Implements [Solve All Obligations with tac] *)
2591 let solve_all_obligations ~pm tac =
2592 State.fold pm ~init:pm ~f:(fun k v pm ->
2593 solve_prg_obligations ~pm v tac |> fst)
2594
2595 (** Implements [Obligation n of name with tac] *)
2596 let obligation (user_num, name) ~pm tac =
2597 let num = pred user_num in
2598 let prg = get_unique_prog ~pm name in
2599 let { obls; remaining } = Internal.get_obligations prg in
2600 if num >= 0 && num < Array.length obls then
2601 let obl = obls.(num) in
2602 match obl.obl_body with
2603 | None -> solve_obligation prg num tac
2604 | Some r -> Error.already_solved user_num
2605 else Error.unknown_obligation num
2606
2607 (** Implements [Obligations of name] *)
2608 let show_single_obligation i name obls x =
2609 let x = subst_deps_obl obls x in
2610 let env = Global.env () in
2611 let sigma = Evd.from_env env in
2612 let msg =
2613 str "Obligation" ++ spc ()
2614 ++ int (succ i)
2615 ++ spc () ++ str "of" ++ spc () ++ Id.print name ++ str ":" ++ spc ()
2616 ++ hov 1 (Printer.pr_constr_env env sigma x.obl_type
2617 ++ str "." ++ fnl ()) in
2618 Feedback.msg_info msg
2619
2620 let show_obligations_of_prg ?(msg = true) prg =
2621 let name = Internal.get_name prg in
2622 let {obls; remaining} = Internal.get_obligations prg in
2623 let showed = ref 5 in
2624 if msg then Feedback.msg_info (int remaining ++ str " obligation(s) remaining: ");
2625 Array.iteri
2626 (fun i x ->
2627 match x.obl_body with
2628 | None ->
2629 if !showed > 0 then begin
2630 decr showed;
2631 show_single_obligation i name obls x
2632 end
2633 | Some _ -> ())
2634 obls
2635
2636 let show_obligations ~pm ?(msg = true) name =
2637 let progs =
2638 match name with
2639 | None ->
2640 State.all pm
2641 | Some name ->
2642 (match State.find pm name with
2643 | Some prg -> [prg]
2644 | None -> Error.no_obligations (Some name))
2645 in
2646 List.iter (fun x -> show_obligations_of_prg ~msg x) progs
2647
2648 (** Implementation of the [Preterm of name] command *)
2649 let show_term ~pm name =
2650 let prg = get_unique_prog ~pm name in
2651 ProgramDecl.show prg
2652
2653 let msg_generating_obl name obls =
2654 let len = Array.length obls in
2655 let info = Id.print name ++ str " has type-checked" in
2656 Feedback.msg_info
2657 (if len = 0 then info ++ str "."
2658 else
2659 info ++ str ", generating " ++ int len ++
2660 str (String.plural len " obligation"))
2661
2662 let add_definition ~pm ~info ~cinfo ~opaque ~uctx ?body
2663 ?tactic ?(reduce = reduce) ?using ?obl_hook obls =
2664 let obl_hook = Option.map (fun h -> State.PrgHook h) obl_hook in
2665 let prg =
2666 ProgramDecl.make ~info ~cinfo ~body ~opaque ~uctx ~reduce ~deps:[] ~possible_guard:None ?obl_hook ?using obls
2667 in
2668 let name = CInfo.get_name cinfo in
2669 let {obls;_} = Internal.get_obligations prg in
2670 if Int.equal (Array.length obls) 0 then
2671 let () = Flags.if_verbose (msg_generating_obl name) obls in
2672 let pm, _cst = Obls_.declare_definition ~pm prg in
2673 pm
2674 else
2675 let () = Flags.if_verbose (msg_generating_obl name) obls in
2676 let pm = State.add pm name prg in
2677 let pm, res = auto_solve_obligations ~pm (Some name) tactic in
2678 let () = match res with
2679 | Remain -> Flags.if_verbose (show_obligations ~pm ~msg:false) (Some name)
2680 | Dependent | Defined -> ()
2681 in
2682 pm
2683
2684 let add_mutual_definitions ~pm ~info ~cinfo ~opaque ~uctx ~bodies ~possible_guard
2685 ?tactic ?(reduce = reduce) ?using ?obl_hook obls =
2686 let obl_hook = Option.map (fun h -> State.PrgHook h) obl_hook in
2687 let deps = List.map CInfo.get_name cinfo in
2688 let pm =
2689 List.fold_left3
2690 (fun pm cinfo body obls ->
2691 let prg =
2692 ProgramDecl.make ~info ~cinfo ~opaque ~body:(Some body) ~uctx ~deps
2693 ~possible_guard:(Some possible_guard) ~reduce ?obl_hook ?using obls
2694 in
2695 State.add pm (CInfo.get_name cinfo) prg)
2696 pm cinfo bodies obls
2697 in
2698 let pm, _defined =
2699 List.fold_left
2700 (fun (pm, finished) x ->
2701 if finished then (pm, finished)
2702 else
2703 let pm, res = auto_solve_obligations ~pm (Some x) tactic in
2704 match res with
2705 | Defined ->
2706 (* If one definition is turned into a constant,
2707 the whole block is defined. *)
2708 (pm, true)
2709 | Dependent | Remain -> (pm, false))
2710 (pm, false) deps
2711 in
2712 pm
2713
2714 (** [admit_obligations ~pm name] implements [Admit Obligations of name] *)
2715
2716 let rec admit_prog ~pm prg =
2717 let {obls} = Internal.get_obligations prg in
2718 let is_open _ x = Option.is_empty x.obl_body && List.is_empty (deps_remaining obls x.obl_deps) in
2719 let i = match Array.findi is_open obls with
2720 | Some i -> i
2721 | None -> CErrors.anomaly (Pp.str "Could not find a solvable obligation.")
2722 in
2723 let proof = solve_obligation prg i None in
2724 let pm = Proof.save_admitted ~pm ~proof in
2725 match ProgMap.find_opt (Internal.get_name prg) pm with
2726 | Some prg -> admit_prog ~pm (CEphemeron.get prg)
2727 | None -> pm
2728
2729 let rec admit_all_obligations ~pm =
2730 let prg = State.first_pending pm in
2731 match prg with
2732 | None -> pm
2733 | Some prg ->
2734 let pm = admit_prog ~pm prg in
2735 admit_all_obligations ~pm
2736
2737 let admit_obligations ~pm name =
2738 match name with
2739 | None -> admit_all_obligations ~pm
2740 | Some _ ->
2741 let prg = get_unique_prog ~pm name in
2742 let pm = admit_prog ~pm prg in
2743 pm
2744
2745 (** Implements [Next Obligation of name with tac] and [Final Obligation of name with tac] *)
2746 let next_obligation ~pm ?(final=false) name tac =
2747 let prg = match name with
2748 | None ->
2749 begin match State.first_pending pm with
2750 | Some prg -> prg
2751 | None ->
2752 Error.no_obligations None
2753 end
2754 | Some _ -> get_unique_prog ~pm name
2755 in
2756 let {obls; remaining} = Internal.get_obligations prg in
2757 let is_open _ x = Option.is_empty x.obl_body && List.is_empty (deps_remaining obls x.obl_deps) in
2758 let i = match Array.findi is_open obls with
2759 | Some i -> i
2760 | None ->
2761 match name with
2762 | None -> CErrors.anomaly (Pp.str "Could not find a solvable obligation.")
2763 | Some name -> CErrors.user_err (str "No more obligations for " ++ Id.print name ++ str ".")
2764 in
2765 let check_final = if not final then None
2766 else match name with
2767 | None -> Some AllFinal
2768 | Some name -> Some (SpecificFinal name)
2769 in
2770 solve_obligation ?check_final prg i tac
2771
2772 let check_program_libraries () =
2773 Rocqlib.check_required_library Rocqlib.datatypes_module_name;
2774 Rocqlib.check_required_library ["Corelib";"Init";"Specif"]
2775
2776 let program_inference_hook env sigma ev =
2777 let tac = !default_tactic in
2778 let evi = Evd.find_undefined sigma ev in
2779 let evi = Evarutil.nf_evar_info sigma evi in
2780 let env = Evd.evar_filtered_env env evi in
2781 try
2782 let concl = Evd.evar_concl evi in
2783 if not (Evarutil.is_ground_env sigma env &&
2784 Evarutil.is_ground_term sigma concl)
2785 then None
2786 else
2787 let c, sigma =
2788 Subproof.refine_by_tactic ~name:(Id.of_string "program_subproof")
2789 ~poly:PolyFlags.default env sigma concl (Tacticals.tclSOLVE [tac])
2790 in
2791 Some (sigma, c)
2792 with
2793 | (Proof.OpenProof _ as e | Logic_monad.TacticFailure e) when CErrors.noncritical e ->
2794 CErrors.user_err Pp.(str "The statement obligations could not be resolved \
2795 automatically, write a statement definition first.")
2796
2797 (* aliases *)
2798 let prepare_obligations = prepare_obligations
2799 let check_solved_obligations =
2800 let is_empty prg =
2801 let obls = (Internal.get_obligations (CEphemeron.get prg)).obls in
2802 let is_open x = Option.is_empty x.obl_body && List.is_empty (deps_remaining obls x.obl_deps) in
2803 Array.exists is_open obls in
2804 Obls_.check_solved_obligations is_empty
2805 type fixpoint_kind = Obls_.fixpoint_kind =
2806 | IsFixpoint of lident option list | IsCoFixpoint
2807
2808 end
2809
2810 module OblState = Obls_.State
2811
2812 let declare_constant ?loc ?local ~name ~kind ?typing_flags =
2813 declare_constant ~loc ?local ~name ~kind ~typing_flags
2814
2815 let declare_entry ?loc ~name ?scope ~kind ?user_warns ?hook ~impargs ~uctx entry =
2816 declare_entry ~loc ~name ?scope ~kind ~typing_flags:None ?clearbody:None ~user_warns ?hook ~impargs ~uctx entry
2817
2818 let declare_definition_full ~info ~cinfo ~opaque ~body ?using sigma =
2819 let c, uctx = declare_definition ~obls:[] ~info ~cinfo ~opaque ~body ?using sigma in
2820 c, if PolyFlags.univ_poly info.poly then Univ.ContextSet.empty else UState.universe_context_set uctx
2821
2822 let declare_definition ~info ~cinfo ~opaque ~body ?using sigma =
2823 declare_definition ~obls:[] ~info ~cinfo ~opaque ~body ?using sigma |> fst