Debian Codegraph @

vernac/comInductive.ml

raw symbols SCIP
1 (************************************************************************)
2 (* * The Rocq Prover / The Rocq Development Team *)
3 (* v * Copyright INRIA, CNRS and contributors *)
4 (* <O___,, * (see version control and CREDITS file for authors & dates) *)
5 (* \VV/ **************************************************************)
6 (* // * This file is distributed under the terms of the *)
7 (* * GNU Lesser General Public License Version 2.1 *)
8 (* * (see LICENSE file for the text of the license) *)
9 (************************************************************************)
10
11 open Pp
12 open CErrors
13 open Sorts
14 open Util
15 open Context
16 open Environ
17 open Names
18 open Libnames
19 open Constrexpr
20 open Constrexpr_ops
21 open Constrintern
22 open Type_errors
23 open Pretyping
24 open Context.Rel.Declaration
25 open Entries
26 open EConstr
27
28 module RelDecl = Context.Rel.Declaration
29
30 type flags = {
31 poly : PolyFlags.t;
32 template : bool option;
33 finite : Declarations.recursivity_kind;
34 mode : Hints.hint_mode list option;
35 schemes : DeclareInd.declare_schemes;
36 }
37
38 (* 3b| Mutual inductive definitions *)
39
40 let warn_auto_template =
41 CWarnings.create ~name:"auto-template" ~default:CWarnings.Disabled
42 (fun id ->
43 Pp.(strbrk "Automatically declaring " ++ Id.print id ++
44 strbrk " as template polymorphic. Use attributes or " ++
45 strbrk "disable Auto Template Polymorphism to avoid this warning."))
46
47 let should_auto_template =
48 let open Goptions in
49 let auto = ref true in
50 let () = declare_bool_option
51 { optstage = Summary.Stage.Interp;
52 optdepr = None;
53 optkey = ["Auto";"Template";"Polymorphism"];
54 optread = (fun () -> !auto);
55 optwrite = (fun b -> auto := b); }
56 in
57 fun id would_auto ->
58 let b = !auto && would_auto in
59 if b then warn_auto_template id;
60 b
61
62 let push_types env idl rl tl =
63 List.fold_left3 (fun env id r t -> EConstr.push_rel (LocalAssum (make_annot (Name id) r,t)) env)
64 env idl rl tl
65
66 type structured_one_inductive_expr = {
67 ind_name : Id.t;
68 ind_arity_explicit : bool;
69 ind_arity : constr_expr;
70 ind_lc : (Id.t * constr_expr) list
71 }
72
73 exception Same of Id.t
74
75 let check_all_names_different env indl =
76 let rec elements = function
77 | [] -> Id.Set.empty
78 | id :: l ->
79 let s = elements l in
80 if Id.Set.mem id s then raise (Same id) else Id.Set.add id s
81 in
82 let ind_names = List.map (fun ind -> ind.ind_name) indl in
83 let cstr_names = List.map_append (fun ind -> List.map fst ind.ind_lc) indl in
84 let ind_names = match elements ind_names with
85 | s -> s
86 | exception (Same t) -> raise (InductiveError (env, SameNamesTypes t))
87 in
88 let cstr_names = match elements cstr_names with
89 | s -> s
90 | exception (Same c) -> raise (InductiveError (env, SameNamesConstructors c))
91 in
92 let l = Id.Set.inter ind_names cstr_names in
93 if not (Id.Set.is_empty l) then
94 raise (InductiveError (env, SameNamesOverlap (Id.Set.elements l)))
95
96 (** Make the arity conclusion flexible to avoid generating an upper bound universe now,
97 only if the universe does not appear anywhere else.
98 This is really a hack to stay compatible with the semantics of template polymorphic
99 inductives which are recognized when a "Type" appears at the end of the conlusion in
100 the source syntax. *)
101
102 let rec check_type_conclusion ind =
103 let open Glob_term in
104 match DAst.get ind with
105 | GSort s ->
106 (* not sure what this check is expected to be exactly *)
107 begin match s with
108 | (None, UAnonymous {rigid=UnivRigid}) ->
109 (* should have been made flexible *)
110 assert false
111 | (None, UAnonymous {rigid=UnivFlexible _}) -> false
112 | _ -> true
113 end
114 | GProd (_, _, _, _, e)
115 | GLetIn (_, _, _, _, e) ->
116 check_type_conclusion e
117 | _ -> false
118
119 let rec make_anonymous_conclusion_flexible ind =
120 let open Glob_term in
121 match DAst.get ind with
122 | GSort (None, UAnonymous {rigid=UnivRigid}) ->
123 Some (DAst.make ?loc:ind.loc (GSort (None, UAnonymous {rigid=UnivFlexible true})))
124 | GSort _ -> None
125 | GProd (a, b, c, d, e) -> begin match make_anonymous_conclusion_flexible e with
126 | None -> None
127 | Some e -> Some (DAst.make ?loc:ind.loc (GProd (a, b, c, d, e)))
128 end
129 | GLetIn (a, b, c, d, e) -> begin match make_anonymous_conclusion_flexible e with
130 | None -> None
131 | Some e -> Some (DAst.make ?loc:ind.loc (GLetIn (a, b, c, d, e)))
132 end
133 | _ -> None
134
135 type syntax_allows_template_poly = SyntaxAllowsTemplatePoly | SyntaxNoTemplatePoly
136
137 let intern_ind_arity env sigma ind =
138 let c = intern_gen IsType env sigma ind.ind_arity in
139 let impls = Implicit_quantifiers.implicits_of_glob_constr ~with_products:true c in
140 let pseudo_poly, c = match make_anonymous_conclusion_flexible c with
141 | None -> check_type_conclusion c, c
142 | Some c -> true, c
143 in
144 let template_syntax = if pseudo_poly then SyntaxAllowsTemplatePoly else SyntaxNoTemplatePoly in
145 (constr_loc ind.ind_arity, c, impls, template_syntax)
146
147 let pretype_ind_arity ~unconstrained_sorts ~poly env sigma (loc, c, impls, template_syntax) =
148 let flags = { Pretyping.all_no_fail_flags with unconstrained_sorts ; poly } in
149 let sigma,t = understand_tcc ~flags env sigma ~expected_type:IsType c in
150 match Reductionops.sort_of_arity env sigma t with
151 | exception Reduction.NotArity ->
152 user_err ?loc (str "Not an arity")
153 | s ->
154 sigma, (t, Retyping.relevance_of_sort s, template_syntax, impls)
155
156 (* ind_rel is the Rel for this inductive in the context without params.
157 n is how many arguments there are in the constructor. *)
158 let model_conclusion env sigma ind_rel params n arity_indices =
159 let model_head = EConstr.mkRel (n + Context.Rel.length params + ind_rel) in
160 let model_params = Context.Rel.instance EConstr.mkRel n params in
161 let sigma,model_indices =
162 List.fold_right
163 (fun (_,t) (sigma, subst) ->
164 let t = EConstr.Vars.substl subst (EConstr.Vars.liftn n (List.length subst + 1) t) in
165 let typeclass_candidate = Typeclasses.is_maybe_class_type env sigma t in
166 let sigma, c = Evarutil.new_evar ~typeclass_candidate env sigma t in
167 sigma, c::subst)
168 arity_indices (sigma, []) in
169 sigma, mkApp (mkApp (model_head, model_params), Array.of_list (List.rev model_indices))
170
171 let interp_cstrs env (sigma, ind_rel) impls params ind arity =
172 let cnames,ctyps = List.split ind.ind_lc in
173 let arity_indices, cstr_sort = Reductionops.splay_arity env sigma arity in
174 (* Interpret the constructor types *)
175 let interp_cstr sigma ctyp =
176 let flags =
177 Pretyping.{ all_no_fail_flags with
178 use_typeclasses = UseTCForConv;
179 solve_unification_constraints = false }
180 in
181 let sigma, (ctyp, cimpl) = interp_type_evars_impls ~flags env sigma ~impls ctyp in
182 let ctx, concl = Reductionops.whd_decompose_prod_decls env sigma ctyp in
183 let concl_env = EConstr.push_rel_context ctx env in
184 let sigma_with_model_evars, model =
185 model_conclusion concl_env sigma ind_rel params (Context.Rel.length ctx) arity_indices
186 in
187 (* unify the expected with the provided conclusion *)
188 let sigma =
189 try Evarconv.unify concl_env sigma_with_model_evars Conversion.CONV concl model
190 with Evarconv.UnableToUnify (sigma,e) ->
191 user_err (Himsg.explain_pretype_error concl_env sigma
192 (Pretype_errors.CannotUnify (concl, model, (Some e))))
193 in
194 sigma, (ctyp, cimpl)
195 in
196 let sigma, (ctyps, cimpls) =
197 on_snd List.split @@
198 List.fold_left_map interp_cstr sigma ctyps
199 in
200 (sigma, pred ind_rel), (cnames, ctyps, cimpls)
201
202 (***** Generate constraints from constructor arguments *****)
203
204 let compute_constructor_levels env evd sign =
205 fst (List.fold_right
206 (fun d (lev,env) ->
207 match d with
208 | LocalDef _ -> lev, EConstr.push_rel d env
209 | LocalAssum _ ->
210 let s = Retyping.get_sort_of env evd (RelDecl.get_type d) in
211 (s :: lev, EConstr.push_rel d env))
212 sign ([],env))
213
214 let is_flexible_sort evd s = match ESorts.kind evd s with
215 | Set | Prop | SProp -> false
216 | Type u | QSort (_, u) ->
217 match Univ.Universe.level u with
218 | Some l -> Evd.is_flexible_level evd l
219 | None -> false
220
221 let prop_lowering_candidates evd ~arities_explicit inds =
222 let less_than_2 = function [] | [_] -> true | _ :: _ :: _ -> false in
223
224 (* handle automatic lowering to Prop
225 We repeatedly add information about which inductives should not be Prop
226 until no more progress can be made
227 *)
228 let is_prop_candidate_arity (raw_arity,(_,s),indices,ctors) =
229 less_than_2 ctors
230 && EConstr.isArity evd raw_arity
231 && is_flexible_sort evd s
232 && not (Evd.check_leq evd ESorts.set s)
233 in
234 let candidates = List.filter_map (fun (explicit,(_,(_,s),_,_ as ind)) ->
235 if (not explicit) && is_prop_candidate_arity ind
236 then Some s else None)
237 (List.combine arities_explicit inds)
238 in
239
240 let in_candidates s candidates = List.mem_f (ESorts.equal evd) s candidates in
241 let is_prop_candidate_size candidates (_,_,indices,ctors) =
242 List.for_all
243 (List.for_all (fun s -> match ESorts.kind evd s with
244 | SProp | Prop -> true
245 | Set -> false
246 | Type _ | QSort _ ->
247 not (Evd.check_leq evd ESorts.set s)
248 && in_candidates s candidates))
249 (Option.List.cons indices ctors)
250 in
251 let rec spread_nonprop candidates =
252 let (changed, candidates) = List.fold_left
253 (fun (changed, candidates as acc) (raw_arity,(_,s),indices,ctors as ind) ->
254 if is_prop_candidate_size candidates ind
255 then acc (* still a Prop candidate *)
256 else if in_candidates s candidates
257 then (true, List.remove (ESorts.equal evd) s candidates)
258 else acc)
259 (false,candidates)
260 inds
261 in
262 if changed then spread_nonprop candidates
263 else candidates
264 in
265 let candidates = spread_nonprop candidates in
266 candidates
267
268 let include_constructor_argument evd ~poly ~ctor_sort ~inductive_sort =
269 if PolyFlags.univ_poly poly then
270 (* We ignore the quality when comparing the sorts: it has an impact
271 on squashing in the kernel but cannot cause a universe error. *)
272 let univ_of_sort s =
273 match ESorts.kind evd s with
274 | SProp | Prop -> None
275 | Set -> Some Univ.Universe.type0
276 | Type u | QSort (_,u) -> Some u
277 in
278 match univ_of_sort ctor_sort, univ_of_sort inductive_sort with
279 | _, None ->
280 (* This function is only called when [s] is not impredicative *)
281 assert false
282 | None, Some _ -> evd
283 | Some uctor, Some uind ->
284 let mk u = ESorts.make (Sorts.sort_of_univ u) in
285 Evd.set_leq_sort evd (mk uctor) (mk uind)
286 else
287 match ESorts.kind evd ctor_sort with
288 | SProp | Prop -> evd
289 | Set | Type _ | QSort _ ->
290 Evd.set_leq_sort evd ctor_sort inductive_sort
291
292 type default_dep_elim = DeclareInd.default_dep_elim = DefaultElim | PropButDepElim
293
294 let inductive_levels env evd ~poly ~indnames ~arities_explicit arities ctors =
295 let inds = List.map2 (fun x ctors ->
296 let ctx, s = Reductionops.dest_arity env evd x in
297 x, (ctx, s), List.map (compute_constructor_levels env evd) ctors)
298 arities ctors
299 in
300 (* Inductives explicitly put in an impredicative sort can be
301 squashed, so there are no constraints to get from them. *)
302 let is_impredicative_sort evd s = is_impredicative_sort env (ESorts.kind evd s) in
303 (* Inductives with >= 2 constructors are >= Set *)
304 let less_than_2 = function [] | [_] -> true | _ :: _ :: _ -> false in
305 let evd = List.fold_left (fun evd (raw_arity,(_,s),ctors) ->
306 if less_than_2 ctors || is_impredicative_sort evd s then evd
307 else (* >=2 constructors is like having a bool argument *)
308 include_constructor_argument evd ~poly ~ctor_sort:ESorts.set ~inductive_sort:s)
309 evd inds
310 in
311 (* If indices_matter, the index telescope acts like an extra
312 constructor except for constructor count checks. *)
313 let inds =
314 List.map (fun (raw_arity,(ctx,_ as arity),ctors) ->
315 let indices = if indices_matter env then
316 Some (compute_constructor_levels env evd ctx)
317 else None
318 in
319 (raw_arity,arity,indices,ctors))
320 inds
321 in
322
323 let candidates = prop_lowering_candidates evd ~arities_explicit inds in
324 (* Do the lowering. We forget about the generated universe for the
325 lowered inductive and rely on universe restriction to get rid of
326 it.
327
328 NB: it would probably be less hacky to use the sort polymorphism system
329 ie lowering to Prop by setting a qvar equal to prop.
330
331 However this means we wouldn't lower "Inductive foo : Type := ."
332 as "Type" doesn't produce a qvar.
333
334 Perhaps someday we can stop lowering these explicit ": Type". *)
335 let inds = List.map3 (fun na explicit (raw_arity,(ctx,s),indices,ctors) ->
336 if List.mem_f (ESorts.equal evd) s candidates then
337 (* NB: is_prop_candidate requires is_flexible_sort
338 so in this branch we know s <> Prop *)
339 ((PropButDepElim, mkArity (ctx, ESorts.prop)),ESorts.prop,indices,ctors)
340 else ((DefaultElim, raw_arity), s, indices, ctors))
341 indnames
342 arities_explicit
343 inds
344 in
345
346 (* Add constraints from constructor arguments and indices.
347 We must do this after Prop lowering as otherwise we risk unifying sorts
348 eg on "Box (A:Type)" we risk unifying the parameter sort and the output sort
349 then ESorts.equal would make us believe that the constructor argument is a lowering candidate.
350 *)
351 let evd = List.fold_left (fun evd (_,s,indices,ctors) ->
352 if is_impredicative_sort evd s then evd
353 else List.fold_left
354 (List.fold_left (fun evd ctor_sort ->
355 include_constructor_argument evd ~poly ~ctor_sort ~inductive_sort:s))
356 evd (Option.List.cons indices ctors))
357 evd inds
358 in
359 let arities = List.map (fun (arity,_,_,_) -> arity) inds in
360 evd, List.split arities
361
362 (** Template poly ***)
363
364 let check_named {CAst.loc;v=na} = match na with
365 | Name _ -> ()
366 | Anonymous ->
367 let msg = str "Parameters must be named." in
368 user_err ?loc msg
369
370 let get_template_binding_arity sigma c =
371 let decls, c = EConstr.decompose_prod_decls sigma c in
372 match EConstr.kind sigma c with
373 | Sort s ->
374 begin match ESorts.kind sigma s with
375 | Type u ->
376 begin match Univ.Universe.level u with
377 | Some l -> Some (decls, None, l)
378 | None -> None
379 end
380 | QSort (q,u) ->
381 begin match Univ.Universe.level u with
382 | Some l ->
383 if Univ.Level.is_set l then None else Some (decls, Some q, l)
384 | None -> None
385 end
386 | _ -> None
387 end
388 | _ -> None
389
390 let non_template_levels sigma ~params ~arity ~constructors =
391 let (let+) x f = Result.map f x in
392 let ctx, u = EConstr.destArity sigma arity in
393 (* locally making the conclusion qvar above_prop means its
394 appearances in relevance marks aren't counted *)
395 let+ sigma = match ESorts.kind sigma u with
396 | QSort (q, _) ->
397 if Sorts.QVar.is_unif q then Ok (Evd.set_above_prop sigma (QVar q))
398 else Error "Cannot handle template polymorphism when the conclusion is a global sort."
399 | _ -> Ok sigma
400 in
401 let add_levels c levels = EConstr.universes_of_constr sigma ~init:levels c in
402 let levels = Sorts.QVar.Set.empty, Univ.Level.Set.empty in
403 let fold_params levels = function
404 | LocalDef (_, b, t) -> add_levels b (add_levels t levels)
405 | LocalAssum (_, t) ->
406 match get_template_binding_arity sigma t with
407 | None -> add_levels t levels
408 | Some (decls, _, _) -> add_levels (EConstr.it_mkProd_or_LetIn EConstr.mkProp decls) levels
409 in
410 (* Levels in LocalDef params, on the left of the context in LocalAssum params,
411 in the indices and in the constructor types are not allowed to be template.
412 (partly to guarantee Irrelevant variance, and partly to simplify universe substitution code) *)
413 let levels = List.fold_left fold_params levels params in
414 let levels = add_levels (EConstr.mkArity (ctx,ESorts.prop)) levels in
415 let levels = List.fold_left (fun levels c -> add_levels c levels)
416 levels constructors
417 in
418 let qvars, ulevels = levels in
419 (* levels with nonzero increment in the conclusion may not be template
420 (until constraint checking can handle arbitrary +k, cf #19230) *)
421 let concl_univs = match ESorts.kind sigma u with
422 | QSort (_,u) | Sorts.Type u -> Univ.Universe.repr u
423 | SProp | Prop | Set -> []
424 in
425 let ulevels =
426 List.fold_left (fun ulevels (u,n) ->
427 if Int.equal n 0 then ulevels else Univ.Level.Set.add u ulevels)
428 ulevels
429 concl_univs
430 in
431 qvars, ulevels
432
433 type linearity = Linear of Sorts.QVar.t option | NonLinear
434
435 let pseudo_sort_poly ~non_template_qvars ~template_univs sigma params arity =
436 (* to be pseudo sort poly, every univ in the conclusion must be bound at a free quality *)
437 (* XXX maybe should be anomaly (ie directly call destArity) *)
438 if not @@ isArity sigma arity then None
439 else
440 let ctx, s = destArity sigma arity in
441 match ESorts.kind sigma s with
442 | SProp | Prop | Set -> None
443 | QSort (q,u) ->
444 if not (Sorts.QVar.Set.mem q non_template_qvars)
445 && Univ.Universe.for_all (fun (u,_) ->
446 match Univ.Level.Map.find_opt u template_univs with
447 | None | Some None -> false
448 | Some (Some q') -> QVar.equal q q')
449 u
450 then Some q
451 else None
452 | Type u -> None
453
454 let unbounded_from_below u cstrs =
455 let open Univ in
456 UnivConstraints.for_all (fun (l, d, r) ->
457 match d with
458 | UnivConstraint.Eq | UnivConstraint.Lt -> not (Level.equal l u) && not (Level.equal r u)
459 | UnivConstraint.Le -> not (Level.equal r u))
460 cstrs
461
462 (* Returns the list [x_1, ..., x_n] of levels contributing to template
463 polymorphism. The elements x_k is None if the k-th parameter
464 (starting from the most recent and ignoring let-definitions) is not
465 template or is Some u_k if its level is u_k and is template. *)
466 let template_polymorphic_univs sigma ~params ~arity ~constructors =
467 let (let+) x f = Result.map f x in
468 let+ non_template_qvars, non_template_levels =
469 non_template_levels sigma ~params ~arity ~constructors
470 in
471 let fold_params accu decl = match decl with
472 | LocalAssum (_, p) ->
473 begin match get_template_binding_arity sigma p with
474 | Some (_, qopt, l) ->
475 Univ.Level.Map.update l (function None -> Some (Linear qopt) | Some _ -> Some NonLinear) accu
476 | None -> accu
477 end
478 | LocalDef _ -> accu
479 in
480 let paramslevels = List.fold_left fold_params Univ.Level.Map.empty params in
481 let template_univs =
482 (* already minimized and restricted *)
483 let uctx = Evd.universe_context_set sigma in
484 Univ.Level.Map.filter (fun u -> function
485 | NonLinear -> false
486 | Linear _ ->
487 assert (not @@ Univ.Level.is_set u);
488 Univ.Level.Set.mem u (fst uctx) &&
489 unbounded_from_below u (snd uctx) &&
490 not (Univ.Level.Set.mem u non_template_levels))
491 paramslevels
492 in
493 let template_univs = Univ.Level.Map.map (function
494 | NonLinear -> assert false
495 | Linear qopt -> qopt)
496 template_univs
497 in
498 let pseudo_sort_poly =
499 pseudo_sort_poly ~non_template_qvars ~template_univs sigma params arity
500 in
501 let template_univs = Univ.Level.Map.domain template_univs in
502 pseudo_sort_poly, template_univs
503
504 let split_universe_context subset (univs, univ_csts) =
505 let rem = Univ.Level.Set.diff univs subset in
506 let subfilter (l, _, r) =
507 let () = assert (not @@ Univ.Level.Set.mem r subset) in
508 Univ.Level.Set.mem l subset
509 in
510 let subcst, remcst = Univ.UnivConstraints.partition subfilter univ_csts in
511 (subset, subcst), (rem, remcst)
512
513 let warn_no_template_universe =
514 CWarnings.create ~name:"no-template-universe"
515 (fun () -> Pp.str "This inductive type has no template universes.")
516
517 type should_template =
518 | MaybeTemplate of { force_template : bool; }
519 | NotTemplate
520
521 let nontemplate_univ_entry ~poly sigma udecl =
522 let sigma = Evd.collapse_sort_variables sigma in
523 let uentry, _ as ubinders = Evd.check_univ_decl ~poly sigma udecl in
524 let uentry, global = match uentry with
525 | UState.Polymorphic_entry uctx -> Polymorphic_ind_entry uctx, Univ.ContextSet.empty
526 | UState.Monomorphic_entry uctx -> Monomorphic_ind_entry, uctx
527 in
528 sigma, uentry, ubinders, global
529
530 let template_univ_entry sigma udecl ~template_univs pseudo_sort_poly =
531 let template_qvars = match pseudo_sort_poly with
532 | Some q -> QVar.Set.singleton q
533 | None -> QVar.Set.empty
534 in
535 let sigma = Evd.collapse_sort_variables ~except:template_qvars sigma in
536 let sigma = QVar.Set.fold (fun q sigma -> Evd.set_above_prop sigma (QVar q))
537 template_qvars sigma
538 in
539 let uctx =
540 UState.check_template_univ_decl (Evd.ustate sigma) ~template_qvars udecl
541 in
542 let ubinders = UState.Monomorphic_entry uctx, Evd.universe_binders sigma in
543 let template_univs, global = split_universe_context template_univs uctx in
544 let uctx =
545 UVars.UContext.of_context_set
546 (UState.compute_instance_binders @@ Evd.ustate sigma)
547 ((template_qvars, Sorts.ElimConstraints.empty), template_univs)
548 in
549 let default_univs =
550 let inst = UVars.UContext.instance uctx in
551 let qs, us = UVars.Instance.to_array inst in
552 UVars.Instance.of_array (Array.map (fun _ -> Quality.qtype) qs, us)
553 in
554 sigma, Template_ind_entry {uctx; default_univs}, ubinders, global
555
556 let should_template ~user_template ~poly =
557 match user_template, PolyFlags.univ_poly poly with
558 | Some true, true ->
559 user_err Pp.(strbrk "Template-polymorphism and universe polymorphism are not compatible.")
560 | Some false, _ | None, true ->
561 NotTemplate
562 | Some true, false ->
563 MaybeTemplate { force_template = true; }
564 | None, false ->
565 MaybeTemplate { force_template = false; }
566
567 let inductive_univs sigma ~user_template ~poly udecl ~indnames ~ctx_params ~arities ~constructors template_syntax =
568 match should_template ~user_template ~poly with
569 | NotTemplate -> nontemplate_univ_entry ~poly sigma udecl
570 | MaybeTemplate { force_template; } ->
571 let info = match List.combine3 arities constructors template_syntax with
572 | [arity, (_cnames, constructors), SyntaxAllowsTemplatePoly] ->
573 template_polymorphic_univs sigma ~params:ctx_params ~arity ~constructors
574 | [_, _, SyntaxNoTemplatePoly] ->
575 Error "Template polymorphism needs a syntactic sort for the inductive's conclusion."
576 | _ :: _ :: _ -> Error "Template-polymorphism not allowed with mutual inductives."
577 | [] -> assert false
578 in
579 match info, force_template with
580 | Error _, false ->
581 nontemplate_univ_entry ~poly sigma udecl
582 | Error msg, true -> CErrors.user_err Pp.(str msg)
583 | Ok (pseudo_sort_poly, template_univs), _ ->
584 let has_template = not @@ Univ.Level.Set.is_empty template_univs in
585 if force_template || should_auto_template (List.hd indnames) has_template then
586 let () = if not has_template then warn_no_template_universe () in
587 template_univ_entry sigma udecl ~template_univs pseudo_sort_poly
588 else nontemplate_univ_entry ~poly sigma udecl
589
590 let check_param = function
591 | CLocalDef (na, _, _, _) -> check_named na
592 | CLocalAssum (nas, _, Default _, _) -> List.iter check_named nas
593 | CLocalAssum (nas, _, Generalized _, _) -> ()
594 | CLocalPattern {CAst.loc} ->
595 Loc.raise ?loc (Gramlib.Grammar.ParseError "pattern with quote not allowed here")
596
597 let restrict_inductive_universes sigma ctx_params arities constructors =
598 let merge_universes_of_constr c acc =
599 Univ.Level.Set.union acc (snd (EConstr.universes_of_constr sigma c)) in
600 let uvars = Univ.Level.Set.empty in
601 let uvars = List.fold_left (fun acc d -> Context.Rel.Declaration.fold_constr merge_universes_of_constr d acc) uvars ctx_params in
602 let uvars = List.fold_right merge_universes_of_constr arities uvars in
603 let uvars = List.fold_right (fun (_,ctypes) -> List.fold_right merge_universes_of_constr ctypes) constructors uvars in
604 Evd.restrict_universe_context sigma uvars
605
606 let check_trivial_variances variances =
607 Array.iter (function
608 | None | Some UVars.Variance.Invariant -> ()
609 | Some _ ->
610 CErrors.user_err
611 Pp.(strbrk "Universe variance was specified but this inductive will not be cumulative."))
612 variances
613
614 let variance_of_entry ~cumulative ~variances uctx =
615 match uctx with
616 | Monomorphic_ind_entry | Template_ind_entry _ -> check_trivial_variances variances; None
617 | Polymorphic_ind_entry uctx ->
618 if not cumulative then begin check_trivial_variances variances; None end
619 else
620 let lvs = Array.length variances in
621 let _, lus = UVars.UContext.size uctx in
622 assert (lvs <= lus);
623 Some (Array.append variances (Array.make (lus - lvs) None))
624
625 let interp_mutual_inductive_constr ~sigma ~flags ~udecl ~variances ~ctx_params ~indnames ~arities_explicit ~arities ~template_syntax ~constructors ~env_ar ~private_ind =
626 let {
627 poly;
628 template;
629 finite;
630 } = flags in
631 let env_ar_params = EConstr.push_rel_context ctx_params env_ar in
632 (* Compute renewed arities *)
633 let ctor_args = List.map (fun (_,tys) ->
634 List.map (fun ty ->
635 let ctx = fst (Reductionops.whd_decompose_prod_decls env_ar_params sigma ty) in
636 ctx)
637 tys)
638 constructors
639 in
640 let sigma, (default_dep_elim, arities) = inductive_levels env_ar_params sigma ~poly ~indnames ~arities_explicit arities ctor_args in
641 (* we must minimize before inferring template info.
642 For instance before minimization "option" is "option : Type@{u} -> Type@{v}" with "u <= v".
643 We want to produce "Type@{u} -> Type@{u}" with "u" template poly.
644 Minimization is what gives us "u = v".
645
646 We also need to restrict to avoid seeing spurious bounds from below
647 (ie v <= template_u with v getting restricted away). *)
648 let sigma = Evd.minimize_universes ~collapse_sort_variables:false sigma in
649 let sigma = restrict_inductive_universes sigma ctx_params arities constructors in
650
651 let sigma, univ_entry, ubinders, global_univs =
652 inductive_univs sigma ~user_template:template ~poly udecl
653 ~indnames ~ctx_params ~arities ~constructors template_syntax
654 in
655
656 (* evar-normalize *)
657 let arities = List.map EConstr.(to_constr sigma) arities in
658 let constructors = List.map (on_snd (List.map (EConstr.to_constr sigma))) constructors in
659 let ctx_params = List.map (fun d -> EConstr.to_rel_decl sigma d) ctx_params in
660
661 (* Build the inductive entries *)
662 let entries = List.map3 (fun indname arity (cnames,ctypes) ->
663 { mind_entry_typename = indname;
664 mind_entry_arity = arity;
665 mind_entry_consnames = cnames;
666 mind_entry_lc = ctypes
667 })
668 indnames arities constructors
669 in
670 let variance = variance_of_entry ~cumulative:(PolyFlags.cumulative poly) ~variances univ_entry in
671 (* Build the mutual inductive entry *)
672 let mind_ent =
673 { mind_entry_params = ctx_params;
674 mind_entry_record = None;
675 mind_entry_finite = finite;
676 mind_entry_inds = entries;
677 mind_entry_private = if private_ind then Some false else None;
678 mind_entry_universes = univ_entry;
679 mind_entry_variance = variance;
680 }
681 in
682 default_dep_elim, mind_ent, ubinders, global_univs
683
684 let interp_params ~unconstrained_sorts env udecl uparamsl paramsl =
685 let sigma, udecl, variances = interp_cumul_univ_decl_opt env udecl in
686 let sigma, (uimpls, ((env_uparams, ctx_uparams), useruimpls, _locs)) =
687 interp_context_evars ~program_mode:false ~unconstrained_sorts env sigma uparamsl in
688 let sigma, (impls, ((env_params, ctx_params), userimpls, _locs)) =
689 interp_context_evars ~program_mode:false ~unconstrained_sorts ~impl_env:uimpls env_uparams sigma paramsl
690 in
691 (* Names of parameters as arguments of the inductive type (defs removed) *)
692 sigma, env_params, (ctx_params, env_uparams, ctx_uparams,
693 userimpls, useruimpls, impls, udecl, variances)
694
695 (* When a hole remains for a param, pretend the param is uniform and
696 do the unification.
697 [env_ar_par] is [uparams; inds; params]
698 *)
699 let maybe_unify_params_in env_ar_par sigma ~ninds ~nparams ~binders:k c =
700 let is_ind sigma k c = match EConstr.kind sigma c with
701 | Constr.Rel n ->
702 (* env is [uparams; inds; params; k other things] *)
703 n > k + nparams && n <= k + nparams + ninds
704 | _ -> false
705 in
706 let rec aux (env,k as envk) sigma c = match EConstr.kind sigma c with
707 | Constr.App (h,args) when is_ind sigma k h ->
708 Array.fold_left_i (fun i sigma arg ->
709 if i >= nparams || not (EConstr.isEvar sigma arg) then sigma
710 else begin try Evarconv.unify_delay env sigma arg (EConstr.mkRel (k+nparams-i))
711 with Evarconv.UnableToUnify _ ->
712 (* ignore errors, we will get a "Cannot infer ..." error instead *)
713 sigma
714 end)
715 sigma args
716 | _ -> Termops.fold_constr_with_full_binders
717 env sigma
718 (fun d (env,k) -> EConstr.push_rel d env, k+1)
719 aux envk sigma c
720 in
721 aux (env_ar_par,k) sigma c
722
723 let interp_mutual_inductive_gen env0 ~flags udecl (uparamsl,paramsl,indl) notations ~private_ind =
724 check_all_names_different env0 indl;
725 List.iter check_param paramsl;
726 if not (List.is_empty uparamsl) && not (List.is_empty notations)
727 then user_err (str "Inductives with uniform parameters may not have attached notations.");
728
729 let indnames = List.map (fun ind -> ind.ind_name) indl in
730 let ninds = List.length indl in
731
732 (* In case of template polymorphism, we need to compute more constraints *)
733 let unconstrained_sorts = not (PolyFlags.univ_poly flags.poly) in
734
735 let sigma, env_params, (ctx_params, env_uparams, ctx_uparams, userimpls, useruimpls, impls, udecl, variances) =
736 interp_params ~unconstrained_sorts env0 udecl uparamsl paramsl
737 in
738
739 (* Interpret the arities *)
740 let arities = List.map (intern_ind_arity env_params sigma) indl in
741
742 let sigma, arities = List.fold_left_map (pretype_ind_arity ~unconstrained_sorts ~poly:flags.poly env_params) sigma arities in
743 let arities, relevances, template_syntax, indimpls = List.split4 arities in
744
745 let lift_ctx n ctx =
746 let t = EConstr.it_mkProd_or_LetIn EConstr.mkProp ctx in
747 let t = EConstr.Vars.lift n t in
748 let ctx, _ = EConstr.decompose_prod_decls sigma t in
749 ctx
750 in
751 let ctx_params_lifted, fullarities =
752 lift_ctx ninds ctx_params,
753 CList.map_i
754 (fun i c -> EConstr.Vars.lift i (EConstr.it_mkProd_or_LetIn c ctx_params))
755 0 arities
756 in
757 let env_ar = push_types env_uparams indnames relevances fullarities in
758 let env_ar_params = EConstr.push_rel_context ctx_params_lifted env_ar in
759
760 (* Compute interpretation metadatas *)
761 let indimpls = List.map (fun impls -> userimpls @ impls) indimpls in
762 let impls = compute_internalization_env env_uparams sigma ~impls Inductive indnames fullarities indimpls in
763 let ntn_impls = compute_internalization_env env_uparams sigma Inductive indnames fullarities indimpls in
764
765 let (sigma, _), constructors =
766 Metasyntax.with_syntax_protection (fun () ->
767 (* Temporary declaration of notations and scopes *)
768 List.iter (Metasyntax.set_notation_for_interpretation env_params ntn_impls) notations;
769 (* Interpret the constructor types *)
770 List.fold_left2_map
771 (fun (sigma, ind_rel) ind arity ->
772 interp_cstrs env_ar_params (sigma, ind_rel) impls ctx_params_lifted
773 ind (EConstr.Vars.liftn ninds (Rel.length ctx_params + 1) arity))
774 (sigma, ninds) indl arities)
775 ()
776 in
777
778 let nparams = Context.Rel.length ctx_params in
779 let sigma =
780 List.fold_left (fun sigma (_,ctyps,_) ->
781 List.fold_left (fun sigma ctyp ->
782 maybe_unify_params_in env_ar_params sigma ~ninds ~nparams ~binders:0 ctyp)
783 sigma ctyps)
784 sigma constructors
785 in
786
787 (* generalize over the uniform parameters *)
788 let nuparams = Context.Rel.length ctx_uparams in
789 let uargs = Context.Rel.instance EConstr.mkRel 0 ctx_uparams in
790 let uparam_subst =
791 List.init ninds EConstr.(fun i -> mkApp (mkRel (i + 1 + nuparams), uargs))
792 @ List.init nuparams EConstr.(fun i -> mkRel (i + 1)) in
793 let generalize_constructor c = EConstr.Vars.substnl uparam_subst nparams c in
794 let cimpls = List.map pi3 constructors in
795 let constructors = List.map (fun (cnames,ctypes,cimpls) ->
796 (cnames,List.map generalize_constructor ctypes))
797 constructors
798 in
799 let ctx_params = ctx_params @ ctx_uparams in
800 let userimpls = useruimpls @ userimpls in
801 let indimpls = List.map (fun iimpl -> useruimpls @ iimpl) indimpls in
802 let fullarities = List.map (fun c -> EConstr.it_mkProd_or_LetIn c ctx_uparams) fullarities in
803 let env_ar = push_types env0 indnames relevances fullarities in
804 (* Try further to solve evars, and instantiate them *)
805 let sigma = solve_remaining_evars all_and_fail_flags env_params sigma in
806 let impls =
807 List.map2 (fun indimpls cimpls ->
808 indimpls, List.map (fun impls ->
809 userimpls @ impls) cimpls)
810 indimpls cimpls
811 in
812 let arities_explicit = List.map (fun ar -> ar.ind_arity_explicit) indl in
813 let default_dep_elim, mie, binders, ctx = interp_mutual_inductive_constr ~flags ~sigma ~ctx_params ~udecl ~variances ~arities_explicit ~arities ~template_syntax ~constructors ~env_ar ~private_ind ~indnames in
814 (default_dep_elim, mie, binders, impls, ctx)
815
816
817 (* Very syntactical equality *)
818 let eq_local_binders bl1 bl2 =
819 List.equal local_binder_eq bl1 bl2
820
821 let eq_params (up1,p1) (up2,p2) =
822 eq_local_binders up1 up2 && Option.equal eq_local_binders p1 p2
823
824 let extract_coercions indl =
825 let mkqid (_,({CAst.v=id},_)) = qualid_of_ident id in
826 let iscoe (_, coe, inst) = match inst with
827 | Vernacexpr.NoInstance -> coe = Vernacexpr.AddCoercion
828 | _ -> user_err (Pp.str "'::' not allowed in inductives.") in
829 let extract lc = List.filter (fun (coe,_) -> iscoe coe) lc in
830 List.map mkqid (List.flatten(List.map (fun (_,_,_,lc) -> extract lc) indl))
831
832 exception DifferingParams of
833 string (* inductive or record *)
834 * (Id.t * Vernacexpr.inductive_params_expr)
835 * (Id.t * Vernacexpr.inductive_params_expr)
836
837 let explain_differing_params kind (ind,p) (ind',p') =
838 let pr_params = function
839 | ([],None) -> str "no parameters"
840 | (up,p) ->
841 let env = Global.env() in
842 let sigma = Evd.from_env env in
843 let pr_binders = Ppconstr.pr_binders ~flags:(Ppconstr.current_flags()) env sigma in
844 str "parameters" ++ spc() ++ hov 1 (quote (pr_binders up ++ pr_opt (fun p -> str "|" ++ spc() ++ pr_binders p) p))
845 in
846 v 0
847 (str "Parameters should be syntactically the same for each " ++ str kind ++ str " type." ++ spc() ++
848 hov 0 (str "Type " ++ quote (Id.print ind) ++ str " has " ++ pr_params p) ++ spc() ++
849 hov 0 (str "but type " ++ quote (Id.print ind') ++ str " has " ++ pr_params p') ++ str ".")
850
851 let () = CErrors.register_handler (function
852 | DifferingParams (kind, a, b) -> Some (explain_differing_params kind a b)
853 | _ -> None)
854
855 let error_differing_params ~kind (ind,p) (ind',p') =
856 Loc.raise ?loc:ind'.CAst.loc (DifferingParams (kind, (ind.CAst.v,p), (ind'.CAst.v,p')))
857
858 let extract_params indl =
859 match indl with
860 | [] -> anomaly (Pp.str "empty list of inductive types.")
861 | (ind,params,_,_)::rest ->
862 match List.find_opt (fun (_,p',_,_) -> not @@ eq_params params p') rest with
863 | None -> params
864 | Some (ind',p',_,_) ->
865 error_differing_params ~kind:"inductive" (ind,params) (ind',p')
866
867 let extract_inductive indl =
868 List.map (fun ({CAst.v=indname},_,ar,lc) -> {
869 ind_name = indname;
870 ind_arity_explicit = Option.has_some ar;
871 ind_arity = Option.default (CAst.make @@ CSort Constrexpr_ops.expr_Type_sort) ar;
872 ind_lc = List.map (fun (_,({CAst.v=id},t)) -> (id,t)) lc
873 }) indl
874
875 let extract_mutual_inductive_declaration_components indl =
876 let indl,ntnl = List.split indl in
877 let params = extract_params indl in
878 let coes = extract_coercions indl in
879 let indl = extract_inductive indl in
880 (params,indl), coes, List.flatten ntnl
881
882 type uniform_inductive_flag =
883 | UniformParameters
884 | NonUniformParameters
885
886 module Mind_decl = struct
887
888 type t = {
889 mie : Entries.mutual_inductive_entry;
890 default_dep_elim : default_dep_elim list;
891 nuparams : int option;
892 univ_binders : UState.named_universes_entry;
893 implicits : DeclareInd.one_inductive_impls list;
894 uctx : Univ.ContextSet.t;
895 where_notations : Metasyntax.notation_interpretation_decl list;
896 coercions : Libnames.qualid list;
897 indlocs : DeclareInd.indlocs;
898 }
899
900 end
901
902 let rec count_binder_expr = function
903 | [] -> 0
904 | CLocalAssum(l,_,_,_) :: rest -> List.length l + count_binder_expr rest
905 | CLocalDef _ :: rest -> 1 + count_binder_expr rest
906 | CLocalPattern {CAst.loc} :: _ ->
907 Loc.raise ?loc (Gramlib.Grammar.ParseError "pattern with quote not allowed here")
908
909 let interp_mutual_inductive ~env ~flags ?typing_flags udecl indl ~private_ind ~uniform =
910 let indlocs = List.map (fun ((n,_,_,constructors),_) ->
911 let conslocs = List.map (fun (_,(c,_)) -> c.CAst.loc) constructors in
912 n.CAst.loc, conslocs)
913 indl
914 in
915 let (params,indl),coercions,ntns = extract_mutual_inductive_declaration_components indl in
916 let where_notations = List.map Metasyntax.prepare_where_notation ntns in
917 (* Interpret the types *)
918 let indl, nuparams = match params with
919 | uparams, Some params -> (uparams, params, indl), Some (count_binder_expr params)
920 | params, None -> match uniform with
921 | UniformParameters -> (params, [], indl), Some 0
922 | NonUniformParameters -> ([], params, indl), None
923 in
924 let env = Environ.update_typing_flags ?typing_flags env in
925 let default_dep_elim, mie, univ_binders, implicits, uctx = interp_mutual_inductive_gen ~flags env udecl indl where_notations ~private_ind in
926 let open Mind_decl in
927 { mie; default_dep_elim; nuparams; univ_binders; implicits; uctx; where_notations; coercions; indlocs }
928
929 let do_mutual_inductive ~flags ?typing_flags udecl indl ~private_ind ~uniform =
930 let open Mind_decl in
931 let env = Global.env () in
932 let { mie; default_dep_elim; univ_binders; implicits; uctx; where_notations; coercions; indlocs} =
933 interp_mutual_inductive ~flags ~env udecl indl ?typing_flags ~private_ind ~uniform in
934 (* Declare the global universes *)
935 let () = Global.push_context_set uctx in
936 (* Declare the mutual inductive block with its associated schemes *)
937 ignore (DeclareInd.declare_mutual_inductive_with_eliminations ~default_dep_elim ?typing_flags ~indlocs mie univ_binders implicits ~schemes:flags.schemes);
938 (* Declare the possible notations of inductive types *)
939 List.iter (Metasyntax.add_notation_interpretation ~local:false (Global.env ())) where_notations;
940 (* Declare the coercions *)
941 List.iter (fun qid -> ComCoercion.try_add_new_coercion (Nametab.locate qid) ~local:false ~reversible:true) coercions
942
943 (** Prepare a "match" template for a given inductive type.
944 For each branch of the match, we list the constructor name
945 followed by enough pattern variables.
946 [Not_found] is raised if the given string isn't the qualid of
947 a known inductive type. *)
948
949 (*
950
951 HH notes in PR #679:
952
953 The Show Match could also be made more robust, for instance in the
954 presence of let in the branch of a constructor. A
955 decompose_prod_decls would probably suffice for that, but then, it
956 is a Context.Rel.Declaration.t which needs to be matched and not
957 just a pair (name,type).
958
959 Otherwise, this is OK. After all, the API on inductive types is not
960 so canonical in general, and in this simple case, working at the
961 low-level of mind_nf_lc seems reasonable (compared to working at the
962 higher-level of Inductiveops).
963
964 *)
965
966 let make_cases ind =
967 let open Declarations in
968 let mib, mip = Global.lookup_inductive ind in
969 Util.Array.fold_right_i
970 (fun i (ctx, _) l ->
971 let al = Util.List.skipn (List.length mib.mind_params_ctxt) (List.rev ctx) in
972 let rec rename avoid = function
973 | [] -> []
974 | RelDecl.LocalDef _ :: l -> "_" :: rename avoid l
975 | RelDecl.LocalAssum (n, _)::l ->
976 let n' = Namegen.next_name_away_with_default (Id.to_string Namegen.default_dependent_ident) n.Context.binder_name avoid in
977 Id.to_string n' :: rename (Id.Set.add n' avoid) l in
978 let al' = rename Id.Set.empty al in
979 let consref = GlobRef.ConstructRef (ith_constructor_of_inductive ind (i + 1)) in
980 (Libnames.string_of_qualid (Nametab.shortest_qualid_of_global Id.Set.empty consref) :: al') :: l)
981 mip.mind_nf_lc []
982
983 module Internal =
984 struct
985
986 let error_differing_params = error_differing_params
987
988 end