Debian Codegraph @

tactics/allScheme.ml

raw symbols SCIP
1 (************************************************************************)
2 (* * The Rocq Prover / The Rocq Development Team *)
3 (* v * Copyright INRIA, CNRS and contributors *)
4 (* <O___,, * (see version control and CREDITS file for authors & dates) *)
5 (* \VV/ **************************************************************)
6 (* // * This file is distributed under the terms of the *)
7 (* * GNU Lesser General Public License Version 2.1 *)
8 (* * (see LICENSE file for the text of the license) *)
9 (************************************************************************)
10
11 open Declarations
12 open Util
13 open Names
14 open Nameops
15 open Constr
16 open Vars
17 open Environ
18 open Reduction
19 open Context.Rel.Declaration
20
21 (** Generalize parameters for template and univ poly, and split uniform and non-uniform parameters *)
22 let split_uparans_nuparams mib params =
23 let (uparams, nuparams) = Context.Rel.chop_nhyps mib.mind_nparams_rec (List.rev params) in
24 (List.rev uparams, List.rev nuparams)
25
26 (** {6 Strictly Positive Uniform Parameters } *)
27
28 let dbg_strpos = CDebug.create ~name:"strpos" ()
29
30 let pp_strpos l = Pp.(str "[" ++ prlist_with_sep (fun () -> str ";" ++ spc()) bool l ++ str "]")
31
32 (** Iterate [&&] on [f x] for an array [ar] *)
33 let andl_array f default ar =
34 Array.fold_right (fun x acc -> (List.map2 (&&)) acc (f x)) ar default
35
36 (** Check which uniform parameters are arity, unfolding Let-ins, and returns
37 the updated environment and the initial value of strictly positivity *)
38 let init_value env uparams =
39 let rec aux env (tel : Constr.rel_context) =
40 match tel with
41 | [] -> (env, [])
42 | decl::tel ->
43 match get_value decl with
44 | Some _ ->
45 aux (push_rel decl env) tel
46 | None ->
47 let (env, init_value) = aux (push_rel decl env) tel in
48 (env, Reduction.is_arity env (get_type decl) :: init_value)
49 in
50 aux env (List.rev uparams)
51
52 (** Check if the uniform parameters appear in a term *)
53 let check_strpos env uparams t =
54 let nenv = List.length @@ Environ.rel_context env in
55 let rec aux i tel =
56 match tel with
57 | [] -> []
58 | decl::tel ->
59 match get_value decl with
60 | Some _ -> aux (i+1) tel
61 | None -> noccur_between (nenv - i) 1 t :: aux (i+1) tel
62 in
63 aux 0 (List.rev uparams)
64
65 (** Check if the uniform parameters appear in a context *)
66 let check_strpos_context env uparams default cxt =
67 let rec aux env strpos tel =
68 match tel with
69 | [] -> (env, strpos)
70 | decl::tel ->
71 if Option.has_some @@ get_value decl then
72 aux (push_rel decl env) strpos tel
73 else
74 let ty = whd_all env @@ get_type decl in
75 let strpos_decl = check_strpos env uparams ty in
76 aux (push_rel decl env) (List.map2 (&&) strpos_decl strpos) tel
77 in aux env default (List.rev cxt)
78
79 module Cache =
80 struct
81
82 type t = { mutable uniform : bool list Mindmap_env.t }
83
84 let empty () = { uniform = Mindmap_env.empty }
85
86 end
87
88 (** Computes which uniform parameters are strictly positive in an argument *)
89 let rec compute_params_rec_strpos_arg cache env kn uparams nparams_rec nparams init_value arg =
90 (* strictly positive uniform parameters do not appear on the left of an arrow *)
91 let (local_vars, hd) = Reduction.whd_decompose_prod_decls env arg in
92 let (env, strpos_local) = check_strpos_context env uparams init_value local_vars in
93 (* check the head *)
94 let (hd, inst_args) = decompose_app hd in
95 let srpos_hd =
96 match kind hd with
97 | Rel k ->
98 (* Check if it is the inductive *)
99 if List.length (Environ.rel_context env) < k then
100 (* If it is the inductive, then they should not appear in the instantiation
101 of the non-uniform parameters and indices of the inductive type being defined *)
102 let (_, iargs) = Array.chop nparams_rec inst_args in
103 andl_array (check_strpos env uparams) init_value iargs
104 (* Otherwise, they should not appear in the arguments *)
105 else
106 andl_array (check_strpos env uparams) init_value inst_args
107 | Ind ((kn_nested, _), _) ->
108 (* Check if it is the inductive or nested *)
109 if QMutInd.equal env kn kn_nested then
110 (* If it is the inductive, then they should not appear in the instantiation
111 of the non-uniform parameters and indices of the inductive type being defined *)
112 let (_, iargs) = Array.chop nparams_rec inst_args in
113 andl_array (check_strpos env uparams) init_value iargs
114 (* For nested arguments, they should: *)
115 else begin
116 let mib_nested = lookup_mind kn_nested env in
117 let mib_nested_strpos = compute_params_rec_strpos cache env kn_nested mib_nested in
118 let (inst_uparams, inst_nuparams_indices) = Array.chop mib_nested.mind_nparams_rec inst_args in
119 let uparams_nested = List.rev @@ fst @@
120 Context.Rel.chop_nhyps mib_nested.mind_nparams_rec @@
121 List.rev mib_nested.mind_params_ctxt in
122 let inst_uparams = Termops.eta_expand_instantiation env inst_uparams uparams_nested in
123 (* - appear strictly positively in the instantiation of the uniform parameters
124 that are strictly postive themselves
125 - not appear in uniform parameters that are not strictly postive *)
126 let strpos_inst_uparams = Array.fold_right_i (fun i x acc ->
127 if List.nth mib_nested_strpos i
128 then List.map2 (&&) acc @@ compute_params_rec_strpos_arg cache env kn uparams nparams_rec nparams init_value x
129 else List.map2 (&&) acc @@ check_strpos env uparams x
130 ) inst_uparams init_value in
131 (* - not appear in the instantiation of the non-uniform parameters and indices *)
132 let strpos_inst_nuparams_indices = andl_array (check_strpos env uparams) init_value inst_nuparams_indices in
133 List.map2 (&&) strpos_inst_uparams strpos_inst_nuparams_indices
134 end
135 | _ -> check_strpos env uparams hd
136 in
137 List.map2 (&&) strpos_local srpos_hd
138
139 (** Computes which uniform parameters are strictly positive in a constructor *)
140 and compute_params_rec_strpos_ctor cache env kn uparams nparams_rec nparams init_value (args, hd) =
141 (* They must not appear on the left of an arrow in each argument *)
142 let (env, strpos_args) =
143 List.fold_right (
144 fun arg (env, acc) ->
145 if Option.has_some @@ get_value arg then
146 push_rel arg env, acc
147 else
148 let strpos_arg = compute_params_rec_strpos_arg cache env kn uparams nparams_rec nparams init_value (get_type arg) in
149 (push_rel arg env, List.map2 (&&) acc strpos_arg)
150 ) args (env, init_value)
151 in
152 (* They must not appear in the instantiation of the indices *)
153 let (_, xs) = decompose_app hd in
154 let inst_indices = Array.sub xs nparams (Array.length xs - nparams) in
155 let str_inst_indices = andl_array (check_strpos env uparams) strpos_args inst_indices in
156 let res_ctor = List.map2 (&&) strpos_args str_inst_indices in
157 res_ctor
158
159 (** Computes which uniform parameters are strictly positive in an inductive block *)
160 and compute_params_rec_strpos_ind cache env kn uparams nparams_rec nparams init_value (indices, ctors) =
161 (* They must not appear in indices *)
162 let (_, strpos_indices) = check_strpos_context env uparams init_value indices in
163 (* They must be strictly positive in each constructor *)
164 let strpos_ctors = andl_array (compute_params_rec_strpos_ctor cache env kn uparams nparams_rec nparams init_value) init_value ctors in
165 let res_ind = List.map2 (&&) strpos_indices strpos_ctors in
166 res_ind
167
168 (** Computes which uniform parameters are strictly positive in a mutual inductive block.
169 [inds : (rel_context * (rel_declaration list * types) array) array] contains
170 the context of indices, then for each constructor the telescope of arguments, and the hd.
171 This function can be used whether the inductive is refered using [Rel] or [Ind].
172 This particular data representation is the one of indtypes.
173 *)
174 and compute_params_rec_strpos_aux cache env kn uparams nuparams nparams_rec nparams inds =
175 if nparams_rec = 0 then [] else
176 (* They must be arities [forall ..., sort X] *)
177 let (env, init_value) = init_value env uparams in
178 (* They must not appear in non-uniform parameters *)
179 let (env, strpos_nuparams) = check_strpos_context env uparams init_value nuparams in
180 (* They must be strictly positive in each inductive block *)
181 let strpos_inds = andl_array (compute_params_rec_strpos_ind cache env kn uparams nparams_rec nparams init_value) init_value inds in
182 let res = List.map2 (&&) strpos_nuparams strpos_inds in
183 dbg_strpos Pp.(fun () -> MutInd.print kn ++ str ": Final Result = " ++ pp_strpos res);
184 res
185
186 and compute_params_rec_strpos cache env kn mib = match Mindmap_env.find_opt kn cache.Cache.uniform with
187 | None ->
188 (* reset the context *)
189 let env = set_rel_context_val empty_rel_context_val env in
190 (* compute the data expected *)
191 let inds = Array.map (fun ind ->
192 let (indices, _) = List.chop (List.length ind.mind_arity_ctxt - mib.mind_nparams) ind.mind_arity_ctxt in
193 let ctors = Array.map (fun (args, hd) ->
194 let (args,_) = List.chop (List.length args - mib.mind_nparams) args in
195 (args, hd)
196 ) ind.mind_nf_lc
197 in
198 (indices, ctors)
199 ) mib.mind_packets
200 in
201 let (uparams, nuparams) = map_pair List.rev @@ Context.Rel.chop_nhyps mib.mind_nparams_rec @@
202 List.rev mib.mind_params_ctxt in
203 let ans = compute_params_rec_strpos_aux cache env kn uparams nuparams mib.mind_nparams_rec mib.mind_nparams inds in
204 let () = cache.Cache.uniform <- Mindmap_env.add kn ans cache.Cache.uniform in
205 ans
206 | Some unf -> unf
207
208 (** {6 Lookup All Predicate and its Theorem } *)
209
210 (** Suffix and register key for the [all] predicate and its theorem *)
211 let default_suffix = (("_all", "_all_forall"), ("All", "AllForall"))
212
213 let rec bool_list_to_string lb =
214 match lb with
215 | [] -> ""
216 | true::l -> "1" ^ bool_list_to_string l
217 | false::l -> "0" ^ bool_list_to_string l
218
219 (** Suffix and register key for partial version of the [all] predicate and its theorem *)
220 let partial_suffix strpos =
221 let ((a, b), (c, d)) = default_suffix in
222 let s = "_" ^ bool_list_to_string strpos in
223 ((a^s, b^s), (c^s, d^s))
224
225 let rec compute_user_strpos_aux user_names allowed_uparams strpos =
226 match user_names with
227 | [] -> strpos
228 | name::user_names ->
229 let i =
230 try CList.index0 (fun i n -> Name.equal i n) name allowed_uparams with
231 | Not_found ->
232 let allowed_uparams = List.filter Name.is_name allowed_uparams in
233 CErrors.user_err Pp.(
234 fmt "The variable %t is not included in the uniform parameters that are strictly positive and can be nested on"
235 (fun () -> Name.print name) ++
236 if List.is_empty allowed_uparams then
237 strbrk " because there are no such parameters."
238 else
239 fmt ".@ Allowed parameters are %t." (fun () -> pr_enum Name.print allowed_uparams)
240 )
241 in
242 dbg_strpos Pp.(fun () -> str "POSITION IS =" ++ int i);
243 compute_user_strpos_aux user_names allowed_uparams (List.assign strpos i true)
244
245 let compute_user_strpos mib user_id default_strpos =
246 let user_names = List.map (fun i -> Name i) user_id in
247 let uparams = fst @@ split_uparans_nuparams mib mib.mind_params_ctxt in
248 let uparams_decl = List.filter is_local_assum uparams in
249 let uparams_decl_name = List.map get_name uparams_decl in
250 let allowed_uparams = List.map (fun (name, i) -> if i then name else Anonymous)
251 @@ List.combine (List.rev uparams_decl_name) default_strpos in
252 let strpos = List.map (fun _ -> false) uparams_decl in
253 compute_user_strpos_aux user_names allowed_uparams strpos
254
255 let compute_params_rec_strpos env kn mib =
256 let cache = Cache.empty () in
257 compute_params_rec_strpos cache env kn mib
258
259 (** Compute the default positivity of the uniform parameters, and generates the suffix
260 for naming the [all] predicate, and its theorem, as well as the key for registering.
261 If a positivity specification is given by users [bool list option], it is
262 checked to be included in the default one, and the suffix are modified accordingly. *)
263 let compute_positive_uparams_and_suffix env kn mib user_id =
264 let default_strpos = compute_params_rec_strpos env kn mib in
265 match user_id with
266 | None ->
267 (default_strpos, fst default_suffix, snd default_suffix)
268 | Some user_id ->
269 let user_strpos = compute_user_strpos mib user_id default_strpos in
270 let partial_suffix = partial_suffix user_strpos in
271 (user_strpos, fst partial_suffix, snd partial_suffix)
272
273 (** Warning for looking up the [all] predicate and its theorem *)
274 let warn_lookup_not_found =
275 CWarnings.create ~name:"register-all" ~category:CWarnings.CoreCategories.automation
276 Pp.(fun (key, ind, ind_nested) ->
277 Nametab.XRefs.pr (TrueGlobal (IndRef ind))
278 ++ strbrk " is nested using "
279 ++ Nametab.XRefs.pr (TrueGlobal (IndRef ind_nested))
280 ++ strbrk ". "
281 ++ strbrk "No scheme for "
282 ++ Nametab.XRefs.pr (TrueGlobal (IndRef ind_nested))
283 ++ strbrk " is registered as "
284 ++ strbrk key ++ strbrk ". "
285 ++ strbrk "It can be generated using command \"Scheme All\" e.g. \"Scheme All for "
286 ++ Nametab.XRefs.pr (TrueGlobal (IndRef ind_nested))
287 ++ str ".\"."
288 )
289
290 (** Lookup the partial [all] predicate for [ind_nested] for [args_are_nested].
291 If they are not found, lookup the general [all] predicate.
292 Returns if the partial [all] was found, and the global references.
293 Raise a warning if none is found. *)
294 let lookup_all ind ind_nested args_are_nested =
295 let (_, (pred, _)) = partial_suffix args_are_nested in
296 match DeclareScheme.lookup_scheme_opt pred ind_nested with
297 | Some ref_pred ->
298 Some (true, ref_pred)
299 | None ->
300 let (_, (pred, _)) = default_suffix in
301 match DeclareScheme.lookup_scheme_opt pred ind_nested with
302 | Some ref_pred -> Some (false, ref_pred)
303 | None -> warn_lookup_not_found (pred, ind, ind_nested); None
304
305 (** Lookup the [all] predicate, and its theorem *)
306 let lookup_all_theorem_aux ind ind_nested =
307 let (_, (pred, thm)) = default_suffix in
308 match DeclareScheme.lookup_scheme_opt pred ind_nested with
309 | None -> warn_lookup_not_found (pred, ind, ind_nested); None
310 | Some ref_pred ->
311 match DeclareScheme.lookup_scheme_opt thm ind_nested with
312 | None -> warn_lookup_not_found (thm, ind, ind_nested); None
313 | Some ref_thm -> Some (false, ref_pred, ref_thm)
314
315 (** Lookup the partial [all] predicate and its theorem for [ind_nested] for [args_are_nested].
316 If they are not found, lookup the general [all] predicate and its theorem.
317 Returns if the partial [all] was found, and the global references.
318 Raise a warning if none is found. *)
319 let lookup_all_theorem ind ind_nested args_are_nested =
320 let (_, (pred, thm)) = partial_suffix args_are_nested in
321 match DeclareScheme.lookup_scheme_opt pred ind_nested with
322 | None -> lookup_all_theorem_aux ind ind_nested
323 | Some ref_pred ->
324 match DeclareScheme.lookup_scheme_opt thm ind_nested with
325 | Some ref_thm ->
326 Some (true, ref_pred, ref_thm)
327 | None ->
328 warn_lookup_not_found (thm, ind,ind_nested);
329 lookup_all_theorem_aux ind ind_nested
330
331
332 (** {6 Instantiate the All Predicate and its Theorem } *)
333
334 open EConstr
335 open Context
336 open Inductive
337 open LibBinding
338 open State
339 open Retyping
340 open Rel.Declaration
341
342 let (let@) x f = x f
343 let (let*) x f = State.bind x f
344 let dbg = CDebug.create ~name:"scheme-all" ()
345
346 let mkFunUnit x =
347 let@ _ = rebind fid Lambda Fresh naming_id x in
348 return @@ mkRef ((Rocqlib.lib_ref "core.unit.type"), EInstance.empty)
349
350 let instantiate_all_uparams ~partial_nesting strpos inst_uparams inst_preds =
351 let inst_preds = Array.to_list inst_preds in
352 let inst_uparams = Array.to_list inst_uparams in
353 let* s = get_state in
354 let* sigma = get_sigma in
355 let inst_sparam =
356 List.fold_right (fun (positive, inst_uparam, pred) acc ->
357 if not positive then
358 inst_uparam :: acc
359 else
360 match pred with
361 | Some pred ->
362 inst_uparam :: pred :: acc
363 | None ->
364 if partial_nesting
365 then inst_uparam :: acc
366 else inst_uparam :: (snd @@ run_state s sigma @@ mkFunUnit inst_uparam) :: acc
367 )
368 (List.combine3 strpos inst_uparams inst_preds) []
369 in
370 return @@ Array.of_list inst_sparam
371
372 (** Make the [all] predicate for a fresh instance and using [Typing.checked_appvect], given:
373 - whether the [all] predicate is the partial one, or the general one [partial_nesting:bool]
374 - the positivity of each uniform parameter [bool list]
375 - the instantiation of the uniform parameter of the inductive type [constr array]
376 - the instation of the fresh predicate [constr option array], using [fun ... => True]
377 if the values are none, and [all] is the general predicate
378 - the instantiation of the non-uniform parameters and indices
379 - the argument to apply it to
380 *)
381 let make_all_predicate ~partial_nesting ref_all strpos inst_uparams inst_preds inst_nuparams_indices arg =
382 let* ref_ind = fresh_global ref_all in
383 let* inst_uparams = instantiate_all_uparams ~partial_nesting strpos inst_uparams inst_preds in
384 typing_checked_appvect ref_ind @@ Array.concat [inst_uparams; inst_nuparams_indices; [|arg|]]
385
386 let mkFuntt x =
387 let@ _ = rebind fid Lambda Fresh naming_id x in
388 return @@ mkRef ((Rocqlib.lib_ref "core.unit.tt"), EInstance.empty)
389
390 let instantiate_all_theorem_uparams ~partial_nesting strpos inst_uparams preds preds_hold =
391 let inst_uparams = Array.to_list inst_uparams in
392 let preds = Array.to_list preds in
393 let preds_hold = Array.to_list preds_hold in
394 let* s = get_state in
395 let* sigma = get_sigma in
396 let inst_lfth =
397 List.fold_right (fun (positive, inst_uparam, (pred, pred_hold)) acc ->
398 if not positive then inst_uparam :: acc else
399 match pred, pred_hold with
400 | Some pred, Some pred_hold ->
401 inst_uparam :: pred :: pred_hold :: acc
402 | None, None ->
403 if partial_nesting
404 then inst_uparam :: acc
405 else inst_uparam :: (snd @@ run_state s sigma @@ mkFunUnit inst_uparam) ::
406 (snd @@ run_state s sigma @@ mkFuntt inst_uparam) :: acc
407 | _, _ -> assert false
408 )
409 (List.combine3 strpos inst_uparams @@ List.combine preds preds_hold) []
410 in
411 return @@ Array.of_list inst_lfth
412
413 (** Make the theorem for the [all] predicate for a fresh instance and using [Typing.checked_appvect], given:
414 - whether the [all] predicate is the partial one, or the general one [partial_nesting:bool]
415 - the positivity of each uniform parameter [bool list]
416 - the instantiation of the uniform parameter of the inductive type [constr array]
417 - the instation of the fresh predicate and the proofs they hold [constr option array],
418 using [fun ... => True] and [fun _ => I] if the values are none, and [all] is the general predicate
419 - the instantiation of the non-uniform parameters and indices
420 - the argument to apply it to
421 *)
422 let make_all_theorem ~partial_nesting ref_all_thm strpos inst_uparams inst_preds inst_preds_hold inst_nuparams_indices arg =
423 let* ref_ind = fresh_global ref_all_thm in
424 let* inst_uparams = instantiate_all_theorem_uparams ~partial_nesting strpos inst_uparams inst_preds inst_preds_hold in
425 typing_checked_appvect ref_ind @@ Array.concat [inst_uparams; inst_nuparams_indices; [|arg|]]
426
427
428 (** {6 View for Arguments } *)
429
430 type head_argument =
431 | ArgIsSPUparam of int * constr array
432 (** constant context, position of the uniform parameter, args *)
433 | ArgIsInd of int * constr array * constr array
434 (** constant context, position of the one_inductive body, inst_nuparams inst_indices *)
435 | ArgIsNested of MutInd.t * int * mutual_inductive_body * bool list
436 * one_inductive_body * constr array * constr array
437 (** constant context, ind_nested, mutual and one body, strictly positivity of its uniform parameters,
438 instantiation uniform paramerters, and of both non_uniform parameters and indices *)
439 | ArgIsCst
440
441 (** View to decompose arguments as [forall locs, X] where [X] is further decomposed
442 as a uniform parameter, the inductive, ainstantiate_all nested argument or a constant. *)
443 type argument = rel_context * head_argument
444
445 (** Decompose the argument in [it_Prod_or_LetIn local, X] where [X] is a uniform parameter, Ind, nested or a constant *)
446 let view_argument kn mib key_uparams strpos t =
447 let* (cxt, hd) = whd_decompose_prod_decls t in
448 let@ _ = add_context Old naming_id cxt in
449 let* (hd, iargs) = decompose_app hd in
450 let* sigma = get_sigma in
451 match kind sigma hd with
452 | Rel k ->
453 begin
454 (* Check if the debruijn variable corresponds to a strictly positive uniform parameter *)
455 let* pos_up = check_key_in k key_uparams in
456 match pos_up with
457 | None -> return @@ (cxt, ArgIsCst)
458 | Some i ->
459 if List.nth strpos i then
460 return @@ (cxt, ArgIsSPUparam (i, iargs))
461 else
462 return @@ (cxt, ArgIsCst)
463 end
464 | Ind ((kn_ind, pos_ind), _) ->
465 (* If it is the inductive *)
466 if kn = kn_ind then
467 let (_, local_nuparams_indices) = Array.chop mib.mind_nparams_rec iargs in
468 let nb_nuparams = mib.mind_nparams - mib.mind_nparams_rec in
469 let (local_nuparams, local_indices) = Array.chop nb_nuparams local_nuparams_indices in
470 return @@ (cxt, ArgIsInd (pos_ind, local_nuparams, local_indices))
471 (* if there is no argument, it cannot be nested *)
472 else if Array.length iargs = 0 then return @@ (cxt, ArgIsCst)
473 else
474 (* If it may be nested *)
475 let* env = get_env in
476 let (mib_nested, ind_nested) = lookup_mind_specif env (kn_ind, pos_ind) in
477 let mib_nested_strpos = compute_params_rec_strpos env kn_ind mib_nested in
478 (* Check if at least one parameter can be nested upon *)
479 if List.exists (fun a -> a) mib_nested_strpos then
480 let (inst_uparams, inst_nuparams_indices) = Array.chop mib_nested.mind_nparams_rec iargs in
481 return @@ (cxt, ArgIsNested (kn_ind, pos_ind, mib_nested, mib_nested_strpos,
482 ind_nested, inst_uparams, inst_nuparams_indices))
483 else
484 return @@ (cxt, ArgIsCst)
485 | _ -> return @@ (cxt, ArgIsCst)
486
487
488 (** {6 Generate All Predicate } *)
489
490 (* To build sparse parametricity:
491 - For each positive uniform parameter [A : Type] add a predicate [PA : A -> Type]
492 - For each argument [a : A] add [PA a], for each inductive a recursion hypothesis
493 - Replace [tInd] by the corresponding [rel]
494 *)
495
496 (** {7 Functions on Parameters } *)
497
498 let get_params_sep sigma mib u =
499 let (sigma, params, sub_temp) = Inductiveops.paramdecls_fresh_template sigma (mib, u) in
500 let (uparams, nuparams) = split_uparans_nuparams mib params in
501 (sigma, uparams, nuparams, sub_temp)
502
503 (** Closure of non-uniform parameters if [b], forgetting letins *)
504 let closure_nuparams m binder naming_scheme nuparams =
505 closure_context m binder Old naming_scheme nuparams
506
507 let add_context_nuparams naming_scheme nuparams =
508 add_context Old naming_scheme nuparams
509
510 (** Closure for indices. They are considered as [Fresh] as they are not in the context of the arguments *)
511 let closure_indices m binder freshness naming_scheme indb u f =
512 let* i = get_indices indb u in
513 closure_context m binder freshness naming_scheme i f
514
515 (** {7 Create Fresh Sorts } *)
516
517 (** Create a fresh quality and level for each positive uniform parameter *)
518 let create_fresh_sorts_ql strpos =
519 let nb_sorts = List.fold_right (fun a b -> a + b) (List.map Bool.to_int strpos) 0 in
520 let init = List.make nb_sorts 0 in
521 list_mapi (fun _ _ -> fresh_sort_ql ~sort_rigid:true UnivRigid) init
522
523 (** Create a fresh sort for each positive uniform parameter *)
524 let create_fresh_sorts strpos =
525 let nb_sorts = List.fold_right (fun a b -> a + b) (List.map Bool.to_int strpos) 0 in
526 let init = List.make nb_sorts 0 in
527 list_mapi (fun _ _ ->
528 let* (q,l) = fresh_sort_ql ~sort_rigid:true UnivRigid in
529 return @@ ESorts.make @@ Sorts.qsort q l
530 ) init
531
532
533 (** {7 Compute the Return Sort} *)
534
535 (* Compute if an inductive is nested including for positive parameters to
536 be able to create a fresh universe to handle the constrains created due to
537 the lack of algebraic universes. *)
538
539 let rec is_nested_arg_nested kn mib key_uparams strpos arg : bool t =
540 let* (locs, hd) = view_argument kn mib key_uparams strpos arg in
541 let@ _ = add_context Old naming_id locs in
542 match hd with
543 | ArgIsNested (_, _, mib_nested, _, _, inst_uparams, _) ->
544 let uparams_nested = of_rel_context @@ fst @@
545 split_uparans_nuparams mib_nested mib_nested.mind_params_ctxt in
546 let* inst_uparams = eta_expand_instantiation inst_uparams uparams_nested in
547 let is_nested_arg_nested arg =
548 let* (loc, hd) = decompose_lambda_decls arg in
549 let@ _ = add_context Old naming_hd loc in
550 is_nested_arg_nested kn mib key_uparams strpos hd
551 in
552 let* inst_uparams = array_mapi (fun _ -> is_nested_arg_nested) inst_uparams in
553 return @@ Array.exists (fun x -> x) inst_uparams
554 | ArgIsSPUparam _ | ArgIsInd _ -> return true
555 | _ -> return false
556
557 let is_nested_arg kn mib key_uparams strpos arg =
558 let* (locs, hd) = view_argument kn mib key_uparams strpos arg in
559 let@ _ = add_context Old naming_id locs in
560 match hd with
561 | ArgIsNested (kn_nested, _, mib_nested, _, _, inst_uparams, _) ->
562 let uparams_nested = of_rel_context @@ fst @@
563 split_uparans_nuparams mib_nested mib_nested.mind_params_ctxt in
564 let* inst_uparams = eta_expand_instantiation inst_uparams uparams_nested in
565 let is_nested_arg_nested arg =
566 let* (loc, hd) = decompose_lambda_decls arg in
567 let@ _ = add_context Old naming_hd loc in
568 is_nested_arg_nested kn mib key_uparams strpos hd
569 in
570 let* inst_uparams = array_mapi (fun _ -> is_nested_arg_nested) inst_uparams in
571 return @@ Array.exists (fun x -> x) inst_uparams
572 | _ -> return false
573
574 (** Compute if an inductive is nested including for positive uniform parameters *)
575 let is_nested_ind kn mib ind uparams nuparams strpos : bool t =
576 let@ key_uparams = add_context Old naming_id uparams in
577 let@ _ = add_context Old naming_id nuparams in
578 let* s = get_state in
579 let* sigma = get_sigma in
580 return @@
581 Array.exists (fun ctor ->
582 snd @@ run_state s sigma @@
583 let* (args, _) = get_args mib EInstance.empty ctor in
584 fold_left_state (fun a l -> a::l) args (fun _ arg cc ->
585 let* arg_is_nested = is_nested_arg kn mib key_uparams strpos (get_type arg) in
586 let@ key_arg = add_decl Old naming_id arg in
587 let* b = cc key_arg in
588 return (arg_is_nested || b)
589 ) (fun _ -> return false)
590 ) ind.mind_nf_lc
591
592 (** Compute the return sort of the [all] predicate by adding to the sort of the
593 original inductive type:
594 - the level of the fresh sort of each fresh predicate,
595 - if the inductive is nested including with a positive uniform parameter,
596 add a new universe level [ualg] to accumulates constrains coming from
597 the instantation of the [all] predicates for nested arguments.
598 This is needed due to the lack of algebraic universes.
599 *)
600 let compute_one_return_sort mib ind is_nested u sub_temp fresh_sorts_ql =
601 let open Sorts in
602 (* Recover the sort of the original inductive type *)
603 let* sigma = get_sigma in
604 let u = EInstance.kind sigma u in
605 let ind_sort = UVars.subst_instance_sort u ind.mind_sort in
606 let ind_sort =
607 match sub_temp, mib.mind_template with
608 | Some sub_temp, Some temp -> Template.template_subst_sort sub_temp temp.template_concl
609 | _, _ -> ind_sort
610 in
611 (* Sup of the original levels + a fresh universe if it is nested.
612 Returns the new universe, if there is one, and the return sort *)
613 let sort_if_nested is_nested make_sort u =
614 let mkSort u = mkSort @@ ESorts.make @@ make_sort u in
615 let fresh_sorts_levels = List.map snd fresh_sorts_ql in
616 let new_u = List.fold_right Univ.Universe.sup fresh_sorts_levels u in
617 if not is_nested then
618 return (None, mkSort new_u)
619 else
620 let* l_alg = new_univ_level_variable UnivRigid in
621 let u_alg = Univ.Universe.make l_alg in
622 let u_return_sort = Univ.Universe.sup new_u u_alg in
623 return (Some (mkSort u_alg), mkSort u_return_sort)
624 in
625 (* Compute the new sort, preserving impredicativity *)
626 match ind_sort with
627 | SProp -> return (None, mkSort @@ ESorts.make sprop)
628 | Prop -> return (None, mkSort @@ ESorts.make prop)
629 | Set -> sort_if_nested is_nested sort_of_univ Univ.Universe.type0
630 | Type u -> sort_if_nested is_nested sort_of_univ u
631 | QSort (q,u) -> sort_if_nested is_nested (qsort q) u
632
633 (** Compute the return sort of each [one_inductive_body], and a a fresh sort to
634 handle algebraic constrains if the [one_inductive_body] is nested *)
635 let compute_return_sort kn u sub_temp mib uparams nuparams strpos fresh_sorts_ql =
636 array_mapi (fun pos_ind ind ->
637 let* ind_is_nested = is_nested_ind kn mib ind uparams nuparams strpos in
638 compute_one_return_sort mib ind ind_is_nested u sub_temp fresh_sorts_ql
639 ) mib.mind_packets
640
641
642 (** {7 Generate the Type of All } *)
643
644 let rebind_applied_arity m naming_scheme key_arg cc =
645 (* decompose the arity *)
646 let* arg_ty = State.get_type key_arg in
647 let* (locs, hd) = whd_decompose_prod_decls arg_ty in
648 let@ key_locs = closure_context fid Prod Fresh naming_scheme locs in
649 (* make args *)
650 let* locs_tm = get_terms key_locs in
651 let* arg_tm = get_term key_arg in
652 let head = mkApp (arg_tm, locs_tm) in
653 (* rebind the arity apply to the local variables*)
654 let* sigma = get_sigma in
655 let head_rev = ESorts.relevance_of_sort @@ destSort sigma hd in
656 let head_name = make_annot Anonymous head_rev in
657 let@ key_head = build_binder fid Prod Fresh naming_scheme @@ LocalAssum (head_name, head) in
658 (* continuation *)
659 cc (key_locs, key_head)
660
661 (** Create a fresh predicate [PA : A -> Type] given a variable that is an arity *)
662 let mkPred key_arg sort =
663 let@ _ = rebind_applied_arity fid naming_hd key_arg in
664 return sort
665
666 (** Create the assumption that a predicate [PA : A -> Type] hold [forall a, PA a]
667 given a variable that is an arity *)
668 let mkPredHold key_arg key_pred =
669 let@ (key_locs, key_head) = rebind_applied_arity fid naming_hd key_arg in
670 (* Return PA x1 ... xn a *)
671 let* locs = get_terms key_locs in
672 let* head = get_term key_head in
673 let* pred = get_term key_pred in
674 return @@ mkApp (pred, Array.concat [locs; [|head|]])
675
676 (** Given the position of uniform parameter that is positive, return the
677 position among the positive uniform parameters *)
678 let pos_uparams_to_pos_spuparams j strpos =
679 let rec aux i n l =
680 match l with
681 | [] -> assert false
682 | x::_ when x && i = j -> n
683 | x::l when x -> aux (i+1) (n+1) l
684 | _ :: l -> aux (i+1) n l
685 in
686 aux 0 0 strpos
687
688 (** Take the closure of the uniform parameters adding fresh predicates for
689 strictly positive uniform parameters [PA : A -> Type], and that it holds
690 [forall a, PA a] if [pred_hold = true] *)
691 let closure_uparams_preds_hold_gen ~mk_pred_hold binder uparams strpos fresh_sorts cc =
692 (* let open Sorts in *)
693 let rec aux i key_uparams key_preds key_uparams_preds key_preds_hold tel cc =
694 match tel with
695 | [] -> cc (((List.rev key_uparams), (List.rev key_preds), (List.rev key_uparams_preds)), (List.rev key_preds_hold))
696 | decl :: tel ->
697 let@ key_up = binder Old naming_id decl in
698 if (Option.has_some @@ get_value decl) then
699 aux i key_uparams key_preds key_uparams_preds key_preds_hold tel cc
700 else if not (List.nth strpos i) then
701 aux (i+1) (key_up::key_uparams) key_preds (key_up::key_uparams_preds) key_preds_hold tel cc
702 else
703 let pred_sort = List.nth fresh_sorts @@ pos_uparams_to_pos_spuparams i strpos in
704 (* create (PA : A -> s) *)
705 let pred_id = Name.map (fun id -> Id.of_string @@ "P" ^ Id.to_string id) (get_name decl) in
706 let pred_name = make_annot pred_id ERelevance.relevant in
707 let* pred_type = mkPred key_up (mkSort pred_sort) in
708 let@ key_pred = binder Fresh naming_id @@ LocalAssum (pred_name, pred_type) in
709 (* create (HPA : forall a, PA a) *)
710 if not mk_pred_hold then
711 aux (i+1) (key_up::key_uparams) (key_pred::key_preds) (key_pred::key_up::key_uparams_preds) [] tel cc
712 else
713 let pred_hold_id = Name.map (fun id -> Id.of_string @@ "HP" ^ Id.to_string id) (get_name decl) in
714 let pred_hold_rev = ESorts.relevance_of_sort @@ pred_sort in
715 let pred_hold_name = make_annot pred_hold_id pred_hold_rev in
716 let* pred_hold_type = mkPredHold key_up key_pred in
717 let@ key_pred_hold = binder Fresh naming_id @@ LocalAssum (pred_hold_name, pred_hold_type) in
718 aux (i+1) (key_up::key_uparams) (key_pred::key_preds) (key_pred::key_up::key_uparams_preds)
719 (key_pred_hold::key_preds_hold) tel cc
720 in
721 aux 0 [] [] [] [] (List.rev uparams) cc
722
723 let closure_uparams_preds m binder uparams strpos fresh_sorts cc =
724 closure_uparams_preds_hold_gen ~mk_pred_hold:false (build_binder m binder) uparams strpos fresh_sorts
725 (fun (x,_) -> cc x)
726
727 let context_uparams_preds uparams strpos fresh_sorts cc =
728 closure_uparams_preds_hold_gen ~mk_pred_hold:false add_decl uparams strpos fresh_sorts
729 (fun (x,_) -> cc x)
730
731
732 (** {7 Generate the Type of the [all] predicate } *)
733
734 (** Generate the type of the [all] predicate provided the parameters have already been quantified *)
735 let gen_all_type_param kn pos_ind u mib key_uparams key_nuparams return_sort =
736 (* Closure uparams and predicates, nuparams and indices *)
737 let ind = mib.mind_packets.(pos_ind) in
738 let@ key_indices = closure_indices fid Prod Fresh naming_hd ind u in
739 (* Bind the inductive *)
740 let* ind_rev = ind_relevance ind u in
741 let ind_name = make_annot Anonymous ind_rev in
742 let* ind_term = make_ind ((kn, pos_ind), u) key_uparams key_nuparams key_indices in
743 let@ _ = make_binder fid Prod naming_hd_fresh ind_name ind_term in
744 return return_sort
745
746 (** Generate the type of the [all] predicate *)
747 let gen_all_type kn pos_ind u mib uparams strpos fresh_sorts nuparams return_sort =
748 let@ (key_uparams, _, _) = closure_uparams_preds fid Prod uparams strpos fresh_sorts in
749 let@ key_nuparams = closure_nuparams fid Prod naming_id nuparams in
750 gen_all_type_param kn pos_ind u mib key_uparams key_nuparams return_sort
751
752 (** Add the [one_inductive_body] of the [all] predicate in the context *)
753 let add_inductive kn u mib return_sorts uparams strpos fresh_sorts nuparams cc =
754 let* cxt = array_map2i (fun pos_ind ind return_sort ->
755 let* ind_rev = ind_relevance ind u in
756 let* ind_type = gen_all_type kn pos_ind u mib uparams strpos fresh_sorts nuparams return_sort in
757 return (LocalAssum (make_annot Anonymous ind_rev, ind_type))
758 ) mib.mind_packets return_sorts in
759 add_context Fresh naming_id (List.rev @@ Array.to_list cxt) cc
760
761
762 (** {7 Generate the Type of the New Constructors } *)
763
764 (** Recursively compute the predicate, returns [None] if it is not nested *)
765 let compute_pred to_compute f i x : (constr option) t =
766 if to_compute then
767 let* (locs, head) = decompose_lambda_decls x in
768 let@ key_loc = closure_context fopt Lambda Fresh naming_id locs in
769 (* create new variable *)
770 let* head_sort = retyping_sort_of head in
771 let arg_rev = relevance_of_sort head_sort in
772 let arg_name = make_annot Anonymous arg_rev in
773 (* let name_var = make_annot Anonymous ERelevance.relevant in *)
774 let@ key_arg = make_binder fopt Lambda naming_id arg_name head in
775 let* arg_type = State.get_type key_arg in
776 (* compute rec call *)
777 let* res = f key_arg arg_type in
778 return @@ res
779 else
780 return None
781
782 (** Recursively compute the predicate, returns [None] if it is not nested *)
783 let compute_pred_eta to_compute f i x =
784 let* res = compute_pred to_compute f i x in
785 let* sigma = get_sigma in
786 let res = Option.map (Reductionops.shrink_eta sigma) res in
787 return res
788
789 (** Internal type to be able to refer to inductive blocks either through
790 variables or through [MutInd.t] *)
791 type ('a, 'b) vars_or_kn = IndIsVars of 'a | IndIsKn of 'b
792
793 (** Compute the new argument *)
794 let rec make_rec_call_hyp kn pos_ind mib rep_inds ((key_uparams, key_preds, key_uparams_preds) as key_up) strpos ualg key_arg arg_type =
795 (* Decompose the argument, rebind local variables and compute the argument *)
796 let* (locs, head) = view_argument kn mib key_uparams strpos arg_type in
797 let@ key_locals = closure_context fopt Prod Fresh naming_id locs in
798 let* arg_term = get_term key_arg in
799 let* locs_term = get_terms key_locals in
800 let inst_arg = mkApp (arg_term, locs_term) in
801 (* Match head *)
802 match head with
803 | ArgIsSPUparam (pos_uparam, iargs) ->
804 let pos_in_keys = pos_uparams_to_pos_spuparams pos_uparam strpos in
805 let* pred_tm = geti_term key_preds pos_in_keys in
806 let pred = mkApp (pred_tm, Array.concat [ iargs; [|inst_arg|] ]) in
807 return @@ Some pred
808 | ArgIsInd (pos_ind_block, inst_nuparams, inst_indices) ->
809 begin
810 let* inst_uparams_preds = get_terms key_uparams_preds in
811 let ind_args = Array.concat [inst_uparams_preds; inst_nuparams; inst_indices; [|inst_arg|]] in
812 match rep_inds with
813 | IndIsVars key_inds ->
814 let* ind = geti_term key_inds pos_ind_block in
815 return @@ Some (mkApp (ind, ind_args))
816 | IndIsKn (kn_all, u_all) ->
817 return @@ Some (mkApp (mkIndU ((kn_all, pos_ind), u_all), ind_args))
818 end
819 | ArgIsNested (kn_nested, pos_nested, mib_nested, mib_nested_strpos, ind_nested,
820 inst_uparams, inst_nuparams_indices) ->
821 (* eta expand arguments *)
822 let uparams_nested = of_rel_context @@ fst @@
823 split_uparans_nuparams mib_nested mib_nested.mind_params_ctxt in
824 let* inst_uparams = eta_expand_instantiation inst_uparams uparams_nested in
825 (* Compute the recursive predicates *)
826 let compute_pred i x b = compute_pred_eta b
827 (make_rec_call_hyp kn pos_ind mib rep_inds key_up strpos ualg) i x in
828 let* rec_preds = array_map2i compute_pred inst_uparams (Array.of_list mib_nested_strpos) in
829 (* If at least one argument is nested, lookup the sparse parametricity *)
830 let args_are_nested = Array.map Option.has_some rec_preds in
831 if Array.for_all not args_are_nested then
832 return None
833 else begin
834 match lookup_all (kn, pos_ind) (kn_nested, pos_nested) (Array.to_list args_are_nested) with
835 | None ->
836 return None
837 | Some (partial_nesting, ref_pred) ->
838 (* Create: all A0 PA0 ... An PAn B0 ... Bm i0 ... il (arg a0 ... an) *)
839 let* rec_hyp = make_all_predicate ~partial_nesting ref_pred mib_nested_strpos
840 inst_uparams rec_preds inst_nuparams_indices inst_arg in
841 (* Add constrains with return sort *)
842 match ualg with
843 | None ->
844 return (Some rec_hyp)
845 | Some ualg ->
846 let* jud = retyping_judgment_of rec_hyp in
847 let* () = typing_check_actual_type jud ualg in
848 return (Some rec_hyp)
849 end
850 | _ -> return None
851
852 (** Create and bind the recursive call *)
853 let make_rec_call_cc kn pos_ind mib key_inds ((key_uparams, key_preds, key_uparams_preds) as key_up) strpos ualg _ key_arg cc =
854 let* arg_type = State.get_type key_arg in
855 let* rec_call = make_rec_call_hyp kn pos_ind mib (IndIsVars key_inds) key_up strpos ualg key_arg arg_type in
856 match rec_call with
857 | None ->
858 cc [key_arg]
859 | Some rec_hyp ->
860 (* Compute the relevance after the instantiation *)
861 let* rec_hyp_sort = retyping_sort_of rec_hyp in
862 let rec_hyp_rev = relevance_of_sort rec_hyp_sort in
863 let rec_hyp_name = make_annot Anonymous rec_hyp_rev in
864 let@ _ = make_binder fid Prod naming_id rec_hyp_name rec_hyp in
865 cc [key_arg]
866
867 (** Closure of the args, and of the rec call if [rec_hyp], and if any *)
868 let closure_args_and_rec_call kn pos_ind mib key_inds key_up strpos ualg args =
869 read_by_decl args
870 (build_binder fid Prod Old naming_hd)
871 (fun _ _ cc -> cc [])
872 (make_rec_call_cc kn pos_ind mib key_inds key_up strpos ualg)
873
874 (** Generate the type of the constructors of the [all] predicate supposing
875 parameters have already been quantified:
876 [ ∀ [args + rec], Indε (UP+PRED) NUP IND (cst up nup args) ] *)
877 let gen_all_type_ctor kn pos_ind u mib key_inds ((key_uparams, key_preds, key_uparams_preds) as key_up) strpos key_nuparams ualg pos_ctor ctor =
878 let* (args, indices) = get_args mib u ctor in
879 let@ key_args = closure_args_and_rec_call kn pos_ind mib key_inds key_up strpos ualg args in
880 (* Build the new inductive *)
881 let* ind = geti_term key_inds pos_ind in
882 let* inst_uparams_preds = get_terms key_uparams_preds in
883 let* inst_nuparams = get_terms key_nuparams in
884 let* inst_indices = array_mapi (fun _ -> weaken) indices in
885 let ind = mkApp (ind, Array.concat [inst_uparams_preds; inst_nuparams; inst_indices]) in
886 (* Builds the constructor *)
887 let* cst_args = get_terms key_args in
888 let* cst = make_cst ((kn, pos_ind), u) pos_ctor key_uparams key_nuparams cst_args in
889 (* Return *)
890 return @@ mkApp (ind, [|cst|])
891
892
893 (** {7 Make Entries } *)
894
895 open Entries
896
897 (** Generate the [one_inductive_entry] of the [all] predicate *)
898 let gen_all_one_ind suffix kn pos_ind ind u mib return_sorts key_inds key_up strpos key_nuparams : one_inductive_entry t =
899 let ulag, return_sort = return_sorts.(pos_ind) in
900 let ind_id = add_suffix ind.mind_typename suffix in
901 let* ind_type = gen_all_type_param kn pos_ind u mib ((fun (a,_,_) -> a) key_up) key_nuparams return_sort in
902 let ctors_id = Array.map (fun x -> add_suffix x suffix) ind.mind_consnames in
903 let* ctors_type = array_mapi (gen_all_type_ctor kn pos_ind u mib key_inds key_up strpos key_nuparams ulag) ind.mind_nf_lc in
904 let* sigma = get_sigma in
905 return {
906 mind_entry_typename = ind_id ;
907 mind_entry_arity = to_constr sigma ind_type ;
908 mind_entry_consnames = Array.to_list ctors_id;
909 mind_entry_lc = Array.to_list @@ Array.map (to_constr sigma) ctors_type;
910 }
911
912 let generate_all_aux suffix kn u sub_temp mib uparams strpos nuparams =
913 (* create fresh sorts, and return types *)
914 let* fresh_sorts_ql = create_fresh_sorts_ql strpos in
915 let* return_sorts = compute_return_sort kn u sub_temp mib uparams nuparams strpos fresh_sorts_ql in
916 let fresh_sorts = List.map (fun (a,b) -> ESorts.make @@ Sorts.qsort a b) fresh_sorts_ql in
917 (*uparams + preds, nuparams and recover the context of parameters *)
918 let@ key_inds = add_inductive kn u mib (Array.map snd return_sorts) uparams strpos fresh_sorts nuparams in
919 let@ key_up = context_uparams_preds uparams strpos fresh_sorts in
920 let@ key_nuparams = add_context_nuparams naming_id nuparams in
921 let* current_context = get_context in
922 let ctxt_params = fst @@ List.chop (List.length current_context - Array.length mib.mind_packets) current_context in
923 (* create the inductive body *)
924 let* ind_bodies = array_mapi (fun pos_ind ind ->
925 gen_all_one_ind suffix kn pos_ind ind u mib return_sorts key_inds key_up strpos key_nuparams
926 ) mib.mind_packets
927 in
928 (* universes *)
929 let* sigma = get_sigma in
930 let uctx = Evd.ustate sigma in
931 dbg Pp.(fun () -> str "Before Simpl, Ustate.t = " ++ UState.pr (Evd.ustate sigma) ++ str "\n");
932 let uctx = UState.collapse_above_prop_sort_variables ~to_prop:true uctx in
933 let uctx = UState.normalize_variables uctx in
934 let uctx = UState.minimize uctx in
935 dbg Pp.(fun () -> str "After Simpl, Ustate.t = " ++ UState.pr (Evd.ustate sigma) ++ str "\n");
936 let ind_bodies = Array.map (fun ind ->
937 { ind with
938 mind_entry_arity = UState.nf_universes uctx ind.mind_entry_arity;
939 mind_entry_lc = List.map (UState.nf_universes uctx) ind.mind_entry_lc
940 }
941 ) ind_bodies
942 in
943 (* build mentry *)
944 let mie =
945 let uctx = UState.context uctx in
946 let _qlen, ulen = UVars.UContext.size uctx in
947 {
948 mind_entry_record = None;
949 mind_entry_finite = mib.mind_finite;
950 mind_entry_params = EConstr.to_rel_context sigma ctxt_params ;
951 mind_entry_inds = Array.to_list ind_bodies;
952 mind_entry_universes = Polymorphic_ind_entry uctx;
953 mind_entry_variance = Some (Array.make ulen None);
954 mind_entry_private = mib.mind_private;
955 }
956 in
957 (* DEBUG FUNCTIONS *)
958 let* env = get_env in
959 let sigma = Evd.set_universe_context sigma uctx in
960 let () = dbg Pp.(fun () ->
961 let params = EConstr.of_rel_context mie.mind_entry_params in
962 let ind = List.hd @@ mie.mind_entry_inds in
963 let ind_ty = EConstr.of_constr @@ ind.mind_entry_arity in
964 let ctors_ty = List.map EConstr.of_constr ind.mind_entry_lc in
965 let open Termops.Internal in
966 str "Type Sparse Parametricity = "
967 ++ (print_constr_env env sigma (it_mkProd_or_LetIn ind_ty params))
968 ++ fnl ()
969 ++ prlist_with_sep (fun () -> fnl ()) (fun ty_cst ->
970 str "Type Constructor " ++ str " = "
971 ++ print_constr_env env sigma (it_mkProd_or_LetIn ty_cst params)
972 ++ fnl ()
973 ) ctors_ty
974 )
975 in
976 (* RETURN *)
977 return (uctx, mie)
978
979 let generate_all_predicate env sigma kn u mib strpos suffix =
980 let (sigma, uparams, nuparams, sub_temp) = get_params_sep sigma mib u in
981 dbg Pp.(fun () -> str "strpos = " ++ prlist_with_sep (fun () -> str ", ") bool strpos);
982 let (sigma, (uctx, mie)) = run env sigma @@ generate_all_aux suffix kn u sub_temp mib uparams strpos nuparams in
983 (uctx, mie)
984
985
986 (** {6 Generate the Theorem for the All Predicate } *)
987
988 let make_ind_typing (kn, pos_ind) u key_uparams key_nuparams key_indices =
989 let tInd = mkIndU ((kn, pos_ind), u) in
990 let* inst_ind = get_terms (key_uparams @ key_nuparams @ key_indices) in
991 let* ind = typing_checked_appvect tInd inst_ind in
992 return ind
993
994 let make_ccl kn_nested pos_ind u_all key_uparams_preds key_nuparams key_indices key_VarMatch =
995 make_ind_typing (kn_nested, pos_ind) u_all key_uparams_preds key_nuparams (key_indices @ [key_VarMatch])
996
997 let return_type kn kn_nested pos_ind u u_all mib key_uparams key_uparams_preds nuparams =
998 let@ key_nuparams = closure_nuparams fid Prod naming_id nuparams in
999 (* Closure uparams and predicates, nuparams and indices *)
1000 let ind = mib.mind_packets.(pos_ind) in
1001 let@ key_indices = closure_indices fid Prod Fresh naming_hd ind u in
1002 (* Bind the inductive *)
1003 let* ind_rev = ind_relevance ind u in
1004 let ind_name = make_annot Anonymous ind_rev in
1005 let* ind_term = make_ind ((kn, pos_ind), u) key_uparams key_nuparams key_indices in
1006 let@ key_VarMatch = make_binder fid Prod naming_hd_fresh ind_name ind_term in
1007 (* Return the sort of the inductive *)
1008 make_ccl kn_nested pos_ind u_all key_uparams_preds key_nuparams key_indices key_VarMatch
1009
1010 let rec make_rec_call_proof kn knu pos_ind mib ((key_uparams, _, _) as key_up) key_preds_hold key_fixs strpos key_arg arg_type =
1011 (* Decompose the argument, rebind local variables and compute the argument *)
1012 let* (locs, head) = view_argument kn mib key_uparams strpos arg_type in
1013 let@ key_locals = closure_context fopt Lambda Fresh naming_id locs in
1014 let* arg_term = get_term key_arg in
1015 let* locs_term = get_terms key_locals in
1016 let inst_arg = mkApp (arg_term, locs_term) in
1017 (* match head *)
1018 match head with
1019 | ArgIsSPUparam (pos_uparam, iargs) ->
1020 let pos_in_keys = pos_uparams_to_pos_spuparams pos_uparam strpos in
1021 let* pred_hold_tm = geti_term key_preds_hold pos_in_keys in
1022 let rec_hyp_proof = mkApp (pred_hold_tm, Array.concat [ iargs; [|inst_arg|] ]) in
1023 return @@ Some rec_hyp_proof
1024 | ArgIsInd (pos_ind_block, inst_nuparams, inst_indices) ->
1025 (* Fi B0 ... Bm i0 ... il (x a0 ... an) *)
1026 let* fix = geti_term key_fixs pos_ind_block in
1027 return @@ Some (mkApp (fix, Array.concat [inst_nuparams; inst_indices; [|inst_arg|]]))
1028 | ArgIsNested (kn_nested, pos_nested, mib_nested, mib_nested_strpos, ind_nested,
1029 inst_uparams, inst_nuparams_indices) ->
1030 (* eta expand arguments *)
1031 let uparams_nested = of_rel_context @@ fst @@
1032 split_uparans_nuparams mib_nested mib_nested.mind_params_ctxt in
1033 let* inst_uparams = eta_expand_instantiation inst_uparams uparams_nested in
1034 (* Compute the recursive predicates, and their proofs *)
1035 let compute_pred_preds i x b = compute_pred_eta b (make_rec_call_hyp kn pos_ind mib (IndIsKn knu) key_up strpos None) i x in
1036 let* rec_preds = array_map2i compute_pred_preds inst_uparams (Array.of_list mib_nested_strpos) in
1037 let compute_pred_holds i x b = compute_pred_eta b (make_rec_call_proof kn knu pos_ind mib key_up key_preds_hold key_fixs strpos) i x in
1038 let* rec_preds_hold = array_map2i compute_pred_holds inst_uparams (Array.of_list mib_nested_strpos) in
1039 (* If at least one argument is nested, lookup the local fundamental theorem *)
1040 let args_are_nested = Array.map Option.has_some rec_preds_hold in
1041 if Array.for_all not args_are_nested then
1042 return None
1043 else begin
1044 match lookup_all_theorem (kn, pos_ind) (kn_nested, pos_nested) (Array.to_list args_are_nested) with
1045 | None ->
1046 return None
1047 | Some (partial_nesting, _, ref_thm) ->
1048 let* rec_hyp_proof = make_all_theorem ~partial_nesting ref_thm mib_nested_strpos inst_uparams
1049 rec_preds rec_preds_hold inst_nuparams_indices inst_arg in
1050 return @@ Some rec_hyp_proof
1051 end
1052 | _ -> return None
1053
1054 let compute_args_fix kn knu pos_ind mib key_up key_preds_hold key_fixs strpos key_args =
1055 CList.fold_right_i (fun pos_arg key_arg acc ->
1056 let* acc = acc in
1057 let* arg_term = get_term key_arg in
1058 let* arg_type = State.get_type key_arg in
1059 let* rec_call_proof = make_rec_call_proof kn knu pos_ind mib key_up key_preds_hold key_fixs strpos key_arg arg_type in
1060 match rec_call_proof with
1061 | Some rec_call_proof -> return @@ arg_term :: rec_call_proof :: acc
1062 | None -> return @@ arg_term :: acc
1063 ) 0 key_args (return [])
1064
1065 let make_cst_typing ((kn, pos_ind), u) pos_ctor key_uparams key_nuparams args =
1066 let tCst = mkConstructU (((kn, pos_ind), 1+pos_ctor), u) in
1067 let* params = get_terms (key_uparams @ key_nuparams) in
1068 typing_checked_appvect tCst (Array.concat [params; args])
1069
1070 let generate_all_theorem_aux kn kn_nested focus u mib uparams strpos nuparams : constr t =
1071 (* 1. Create fresh sorts + new unfiform parameters *)
1072 let* fresh_sorts = create_fresh_sorts strpos in
1073 let@ ((key_uparams, key_preds, key_uparams_preds) as key_up, key_preds_hold) =
1074 closure_uparams_preds_hold_gen ~mk_pred_hold:true (build_binder fid Lambda) uparams strpos fresh_sorts in
1075 (* Evd.ustate 2. Fixpoint *)
1076 let* u_all = array_mapi (fun pos_ind _ -> fresh_inductive_instance (kn_nested, pos_ind)) mib.mind_packets in
1077 let relevance_ind ind = Vars.subst_instance_relevance u @@ relevance_of_sort @@ ESorts.make ind.mind_sort in
1078 let fix_name pos_ind ind = make_annot (Name (Id.of_string "F")) (relevance_ind ind) in
1079 let fix_type pos_ind ind = return_type kn kn_nested pos_ind u u_all.(pos_ind) mib key_uparams key_uparams_preds nuparams in
1080 let fix_rarg pos_ind ind = (mib.mind_nparams - mib.mind_nparams_rec) + ind.mind_nrealargs in
1081 let is_rec = Array.length mib.mind_packets > 1 || (Inductiveops.mis_is_recursive mib.mind_packets.(0)) in
1082 let@ (key_fixs, pos_ind, ind) =
1083 (* Doe not create a fix if it is not-recursive and only has one inductive body *)
1084 if is_rec then
1085 make_fix (Array.to_list mib.mind_packets) focus fix_rarg fix_name fix_type
1086 else
1087 fun cc -> cc ([], 0, mib.mind_packets.(0))
1088 in
1089 (* 3. Closure Nuparams / Indices / Var *)
1090 let@ key_nuparams = closure_nuparams fid Lambda naming_id nuparams in
1091 let ind = mib.mind_packets.(pos_ind) in
1092 let@ key_indices = closure_indices fid Lambda Fresh naming_hd ind u in
1093 let* ind_rev = ind_relevance ind u in
1094 let ind_name = make_annot Anonymous ind_rev in
1095 let* ind_term = make_ind ((kn, pos_ind), u) key_uparams key_nuparams key_indices in
1096 let@ key_VarMatch = make_binder fid Lambda naming_hd_fresh ind_name ind_term in
1097 (* 4 Match to prove P ... x *)
1098 let case_pred = make_ccl kn_nested pos_ind u_all.(pos_ind) key_uparams_preds key_nuparams in
1099 let* inst_params = get_terms (key_uparams @ key_nuparams )in
1100 let* var_match = get_term key_VarMatch in
1101 let* inst_indices = get_terms key_indices in
1102 let case_rev = relevance_ind ind in
1103 let@ (key_args, _, _, pos_ctor) =
1104 make_case_or_projections naming_hd_fresh mib (kn, pos_ind) ind u key_uparams key_nuparams inst_params
1105 inst_indices case_pred case_rev var_match in
1106 (* 5 Body of the branch *)
1107 let* args = compute_args_fix kn (kn_nested, u_all.(pos_ind)) pos_ind mib key_up key_preds_hold key_fixs strpos key_args in
1108 make_cst_typing ((kn_nested, pos_ind), u_all.(pos_ind)) pos_ctor key_uparams_preds key_nuparams (Array.of_list args)
1109
1110 let generate_all_theorem env sigma kn kn_nested focus u mib strpos =
1111 let (sigma, uparams, nuparams, _) = get_params_sep sigma mib u in
1112 dbg Pp.(fun () -> str "strpos = " ++ prlist_with_sep (fun () -> str ", ") bool strpos);
1113 let (sigma, tm) = run env sigma @@ generate_all_theorem_aux kn kn_nested focus u mib uparams strpos nuparams in
1114 dbg Pp.(fun () -> str "All Theorem = " ++ Termops.Internal.print_constr_env env sigma tm ++ fnl ());
1115 dbg Pp.(fun () -> str "UState = " ++ UState.pr (Evd.ustate sigma) ++ fnl ());
1116 (sigma, tm)