Debian Codegraph @

pretyping/cases.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 Util
14 open Names
15 open Nameops
16 open Constr
17 open Context
18 open Termops
19 open Environ
20 open EConstr
21 open Vars
22 open Namegen
23 open Declarations
24 open Inductiveops
25 open Reductionops
26 open Type_errors
27 open Glob_term
28 open Glob_ops
29 open Retyping
30 open Pretype_errors
31 open Evarutil
32 open Evardefine
33 open Evarsolve
34 open Evarconv
35 open Evd
36 open Context.Rel.Declaration
37 open GlobEnv
38
39 module RelDecl = Context.Rel.Declaration
40 module NamedDecl = Context.Named.Declaration
41
42 (* Pattern-matching errors *)
43
44 type pattern_matching_error =
45 | BadPattern of constructor * constr
46 | BadConstructor of constructor * inductive
47 | WrongNumargConstructor of
48 {cstr:constructor; expanded:bool; nargs:int; expected_nassums:int; expected_ndecls:int}
49 | WrongNumargInductive of
50 {ind:inductive; expanded:bool; nargs:int; expected_nassums:int; expected_ndecls:int}
51 | UnusedClause of cases_pattern list
52 | NonExhaustive of cases_pattern list
53 | CannotInferPredicate of (constr * types) array
54
55 exception PatternMatchingError of env * evar_map * pattern_matching_error
56
57 let raise_pattern_matching_error ?loc (env,sigma,te) =
58 Loc.raise ?loc (PatternMatchingError(env,sigma,te))
59
60 let error_bad_pattern ?loc env sigma cstr ind =
61 raise_pattern_matching_error ?loc
62 (env, sigma, BadPattern (cstr,ind))
63
64 let error_bad_constructor ?loc env cstr ind =
65 raise_pattern_matching_error ?loc
66 (env, Evd.empty, BadConstructor (cstr,ind))
67
68 let error_wrong_numarg_constructor ?loc env ~cstr ~expanded ~nargs ~expected_nassums ~expected_ndecls =
69 raise_pattern_matching_error ?loc (env, Evd.empty,
70 WrongNumargConstructor {cstr; expanded; nargs; expected_nassums; expected_ndecls})
71
72 let error_wrong_numarg_inductive ?loc env ~ind ~expanded ~nargs ~expected_nassums ~expected_ndecls =
73 raise_pattern_matching_error ?loc (env, Evd.empty,
74 WrongNumargInductive {ind; expanded; nargs; expected_nassums; expected_ndecls})
75
76 let list_try_compile f l =
77 let rec aux errors = function
78 | [] -> if errors = [] then anomaly (str "try_find_f.") else Exninfo.iraise (List.last errors)
79 | h::t ->
80 try f h
81 with UserError _ | TypeError _ | PretypeError _ | PatternMatchingError _ as e ->
82 let e = Exninfo.capture e in
83 aux (e::errors) t in
84 aux [] l
85
86 let force_name =
87 let nx = Name default_dependent_ident in function Anonymous -> nx | na -> na
88
89 (************************************************************************)
90 (* Pattern-matching compilation (Cases) *)
91 (************************************************************************)
92
93 (************************************************************************)
94 (* Configuration, errors and warnings *)
95
96 open Pp
97
98 let msg_may_need_inversion () =
99 strbrk "Found a matching with no clauses on a term unknown to have an empty inductive type."
100
101 (* Utils *)
102 let make_anonymous_patvars n =
103 List.make n (DAst.make @@ PatVar Anonymous)
104
105 (* We have x1:t1...xn:tn,xi':ti,y1..yk |- c and re-generalize
106 over xi:ti to get x1:t1...xn:tn,xi':ti,y1..yk |- c[xi:=xi'] *)
107
108 let relocate_rel n1 n2 k j = if Int.equal j (n1 + k) then n2+k else j
109
110 let rec relocate_index sigma n1 n2 k t =
111 match EConstr.kind sigma t with
112 | Rel j when Int.equal j (n1 + k) -> mkRel (n2+k)
113 | Rel j when j < n1+k -> t
114 | Rel j when j > n1+k -> t
115 | _ -> EConstr.map_with_binders sigma succ (relocate_index sigma n1 n2) k t
116
117 (**********************************************************************)
118 (* Structures used in compiling pattern-matching *)
119
120 let (!!) env = GlobEnv.env env
121
122 type 'a rhs =
123 { rhs_env : GlobEnv.t;
124 rhs_vars : Id.Set.t;
125 avoid_ids : Id.Set.t;
126 it : 'a option}
127
128 type 'a equation =
129 { patterns : cases_pattern list;
130 rhs : 'a rhs;
131 alias_stack : Name.t list;
132 eqn_loc : Loc.t option;
133 orig : int option;
134 catch_all_vars : Id.t CAst.t list }
135
136 type 'a matrix = 'a equation list
137
138 (* 1st argument of IsInd is the original ind before extracting the summary *)
139 type tomatch_type =
140 | IsInd of types * inductive_type * Name.t list
141 | NotInd of constr option * types
142
143 (* spiwack: The first argument of [Pushed] is [true] for initial
144 Pushed and [false] otherwise. Used to decide whether the term being
145 matched on must be aliased in the variable case (only initial
146 Pushed need to be aliased). The first argument of [Alias] is [true]
147 if the alias was introduced by an initial pushed and [false]
148 otherwise.*)
149 type tomatch_status =
150 | Pushed of (bool*((constr * tomatch_type) * int list * Name.t))
151 | Alias of (bool*(Name.t * constr * (constr * types)))
152 | NonDepAlias
153 | Abstract of int * rel_declaration
154
155 type tomatch_stack = tomatch_status list
156
157 (* We keep a constr for aliases and a cases_pattern for error message *)
158
159 type pattern_history =
160 | Top
161 | MakeConstructor of constructor * pattern_continuation
162
163 and pattern_continuation =
164 | Continuation of int * cases_pattern list * pattern_history
165 | Result of cases_pattern list
166
167 let start_history n = Continuation (n, [], Top)
168
169 let feed_history arg = function
170 | Continuation (n, l, h) when n>=1 ->
171 Continuation (n-1, arg :: l, h)
172 | Continuation (n, _, _) ->
173 anomaly (str "Bad number of expected remaining patterns: " ++ int n ++ str ".")
174 | Result _ ->
175 anomaly (Pp.str "Exhausted pattern history.")
176
177 (* This is for non exhaustive error message *)
178
179 let rec glob_pattern_of_partial_history args2 = function
180 | Continuation (n, args1, h) ->
181 let args3 = make_anonymous_patvars (n - (List.length args2)) in
182 build_glob_pattern (List.rev_append args1 (args2@args3)) h
183 | Result pl -> pl
184
185 and build_glob_pattern args = function
186 | Top -> args
187 | MakeConstructor (pci, rh) ->
188 glob_pattern_of_partial_history
189 [DAst.make @@ PatCstr (pci, args, Anonymous)] rh
190
191 let complete_history = glob_pattern_of_partial_history []
192
193 (* This is to build glued pattern-matching history and alias bodies *)
194
195 let pop_history_pattern = function
196 | Continuation (0, l, Top) ->
197 Result (List.rev l)
198 | Continuation (0, l, MakeConstructor (pci, rh)) ->
199 feed_history (DAst.make @@ PatCstr (pci,List.rev l,Anonymous)) rh
200 | _ ->
201 anomaly (Pp.str "Constructor not yet filled with its arguments.")
202
203 let pop_history h =
204 feed_history (DAst.make @@ PatVar Anonymous) h
205
206 (* Builds a continuation expecting [n] arguments and building [ci] applied
207 to this [n] arguments *)
208
209 let push_history_pattern n pci cont =
210 Continuation (n, [], MakeConstructor (pci, cont))
211
212 (* A pattern-matching problem has the following form:
213
214 env, evd |- match terms_to_tomatch return pred with mat end
215
216 where terms_to_match is some sequence of "instructions" (t1 ... tp)
217
218 and mat is some matrix
219
220 (p11 ... p1n -> rhs1)
221 ( ... )
222 (pm1 ... pmn -> rhsm)
223
224 Terms to match: there are 3 kinds of instructions
225
226 - "Pushed" terms to match are typed in [env]; these are usually just
227 Rel(n) except for the initial terms given by user; in Pushed ((c,tm),deps,na),
228 [c] is the reference to the term (which is a Rel or an initial term), [tm] is
229 its type (telling whether we know if it is an inductive type or not),
230 [deps] is the list of terms to abstract before matching on [c] (these are
231 rels too)
232 - "Abstract" instructions mean that an abstraction has to be inserted in the
233 current branch to build (this means a pattern has been detected dependent
234 in another one and a generalization is necessary to ensure well-typing)
235 Abstract instructions extend the [env] in which the other instructions
236 are typed
237 - "Alias" instructions mean an alias has to be inserted (this alias
238 is usually removed at the end, except when its type is not the
239 same as the type of the matched term from which it comes -
240 typically because the inductive types are "real" parameters)
241 - "NonDepAlias" instructions mean the completion of a matching over
242 a term to match as for Alias but without inserting this alias
243 because there is no dependency in it
244
245 Right-hand sides:
246
247 They consist of a raw term to type in an environment specific to the
248 clause they belong to: the names of declarations are those of the
249 variables present in the patterns. Therefore, they come with their
250 own [rhs_env] (actually it is the same as [env] except for the names
251 of variables).
252
253 *)
254
255 type 'a pattern_matching_problem =
256 { env : GlobEnv.t;
257 pred : constr;
258 tomatch : tomatch_stack;
259 history : pattern_continuation;
260 mat : 'a matrix;
261 caseloc : Loc.t option;
262 casestyle : case_style;
263 typing_function: type_constraint -> GlobEnv.t -> evar_map -> 'a option -> evar_map * unsafe_judgment }
264
265 (*--------------------------------------------------------------------------*
266 * A few functions to infer the inductive type from the patterns instead of *
267 * checking that the patterns correspond to the ind. type of the *
268 * destructurated object. Allows type inference of examples like *
269 * match n with O => true | _ => false end *
270 * match x in I with C => true | _ => false end *
271 *--------------------------------------------------------------------------*)
272
273 (* Computing the inductive type from the matrix of patterns *)
274
275 (* We use the "in I" clause to coerce the terms to match and otherwise
276 use the constructor to know in which type is the matching problem
277
278 Note that insertion of coercions inside nested patterns is done
279 each time the matrix is expanded *)
280
281 let rec find_row_ind = function
282 [] -> None
283 | p :: l ->
284 match DAst.get p with
285 | PatVar _ -> find_row_ind l
286 | PatCstr(c,_,_) -> Some (p.CAst.loc,c)
287
288 let inductive_template env sigma tmloc ind =
289 (* XXX if ind is template poly we should be using fresh universes
290 instead of the global default universes
291 (and in the future fresh qualities?) *)
292 let sigma, indu = Evd.fresh_inductive_instance env sigma ind in
293 let templ =
294 match (Environ.lookup_mind (fst (fst indu)) env).mind_template with
295 | None -> []
296 | Some t -> t.template_param_arguments
297 in
298 let arsign = inductive_alldecls env indu in
299 let hole_source i = match tmloc with
300 | Some loc -> Loc.tag ~loc @@ Evar_kinds.TomatchTypeParameter (ind,i)
301 | None -> Loc.tag @@ Evar_kinds.TomatchTypeParameter (ind,i) in
302 let rec aux (sigma, subst, evarl, n) templ arsign = match arsign with
303 | [] -> sigma, evarl
304 | LocalDef (na,b,ty) :: arsign ->
305 aux (sigma, substl subst b::subst,evarl,n+1) templ arsign
306 | LocalAssum (na,ty) :: arsign ->
307 let this_templ, templ = match templ with
308 | b :: templ -> b, templ
309 | [] -> None, []
310 in
311 let ty = substl subst ty in
312 let sigma, ty = match this_templ with
313 | None -> sigma, ty
314 | Some _ ->
315 (* XXX qvar? *)
316 let sigma, u = Evd.new_univ_level_variable UState.univ_flexible_alg sigma in
317 let s = ESorts.make (Sorts.sort_of_univ (Univ.Universe.make u)) in
318 let ctx, _ = destArity sigma ty in
319 sigma, mkArity (ctx, s)
320 in
321 let typeclass_candidate = Typeclasses.is_maybe_class_type env sigma ty in
322 let sigma, e =
323 Evarutil.new_evar ~typeclass_candidate env ~src:(hole_source n) sigma ty
324 in
325 aux (sigma, e::subst,e::evarl,n+1) templ arsign
326 in
327 let (sigma, evarl) = aux (sigma, [], [], 1) templ (List.rev arsign) in
328 sigma, applist (mkIndU indu,List.rev evarl)
329
330 let try_find_ind env sigma typ realnames =
331 let (IndType(indf,realargs) as ind) = find_rectype env sigma typ in
332 let () =
333 let (ind, _), _ = Inductiveops.dest_ind_family indf in
334 let specif = Inductive.lookup_mind_specif env ind in
335 if Inductive.is_private specif then raise Not_found
336 in
337 let names =
338 match realnames with
339 | Some names -> names
340 | None ->
341 let ind = fst (fst (dest_ind_family indf)) in
342 List.make (inductive_nrealdecls env ind) Anonymous in
343 IsInd (typ,ind,names)
344
345 let inh_coerce_to_ind env sigma0 loc ty tyi =
346 let sigma, expected_typ = inductive_template env sigma0 loc tyi in
347 (* Try to refine the type with inductive information coming from the
348 constructor and renounce if not able to give more information *)
349 (* devrait être indifférent d'exiger leq ou pas puisque pour
350 un inductif cela doit être égal *)
351 match Evarconv.unify_leq_delay env sigma expected_typ ty with
352 | sigma -> sigma
353 | exception Evarconv.UnableToUnify _ -> sigma0
354
355 let binding_vars_of_inductive sigma = function
356 | NotInd _ -> []
357 | IsInd (_,IndType(_,realargs),_) -> List.filter (isRel sigma) realargs
358
359 let set_tomatch_realnames names = function
360 | NotInd _ as t -> t
361 | IsInd (typ,ind,_) -> IsInd (typ,ind,names)
362
363 let extract_inductive_data env sigma decl =
364 match decl with
365 | LocalAssum (_,t) ->
366 let tmtyp =
367 try try_find_ind env sigma t None
368 with Not_found -> NotInd (None,t) in
369 let tmtypvars = binding_vars_of_inductive sigma tmtyp in
370 (tmtyp,tmtypvars)
371 | LocalDef (_,_,t) ->
372 (NotInd (None, t), [])
373
374 let unify_tomatch_with_patterns env sigma loc typ pats realnames =
375 match find_row_ind pats with
376 | None -> sigma, NotInd (None,typ)
377 | Some (_,(ind,_)) ->
378 let sigma = inh_coerce_to_ind env sigma loc typ ind in
379 try sigma, try_find_ind env sigma typ realnames
380 with Not_found -> sigma, NotInd (None,typ)
381
382 let find_tomatch_tycon env sigma loc = function
383 (* Try if some 'in I ...' is present and can be used as a constraint *)
384 | Some {CAst.v=(ind,realnal)} ->
385 let sigma, tycon = inductive_template env sigma loc ind in
386 sigma, mk_tycon tycon, Some (List.rev realnal)
387 | None ->
388 sigma, empty_tycon, None
389
390 let make_return_predicate_ltac_lvar env sigma na tm c =
391 (* If we have an [x as x return ...] clause and [x] expands to [c],
392 we have to update the status of [x] in the substitution:
393 - if [c] is a variable [id'], then [x] should now become [id']
394 - otherwise, [x] should be hidden *)
395 match na, DAst.get tm with
396 | Name id, (GVar id' | GRef (GlobRef.VarRef id', _)) when Id.equal id id' ->
397 begin match kind sigma c with
398 | Var id' ->
399 (* We are typically in a situation [match id return P with ... end]
400 which we interpret as [match id' as id' return P with ... end],
401 with [P] interpreted in an environment where [id] is bound to [id'].
402 The variable is already bound to [id'], so nothing to do *)
403 env
404 | _ ->
405 GlobEnv.hide_variable env id
406 end
407 | _ -> env
408
409 let is_patvar pat =
410 match DAst.get pat with
411 | PatVar _ -> true
412 | _ -> false
413
414 let coerce_row ~program_mode typing_fun env sigma pats (tomatch,(na,indopt)) =
415 let loc = loc_of_glob_constr tomatch in
416 let sigma, tycon, realnames = find_tomatch_tycon !!env sigma loc indopt in
417 let sigma, j = typing_fun tycon env sigma tomatch in
418 let sigma, j = Coercion.inh_coerce_to_base ?loc:(loc_of_glob_constr tomatch) ~program_mode !!env sigma j in
419 let typ = nf_evar sigma j.uj_type in
420 let env = make_return_predicate_ltac_lvar env sigma na tomatch j.uj_val in
421 let sigma, t =
422 if realnames = None && pats <> [] && List.for_all is_patvar pats then
423 sigma, NotInd (None,typ)
424 else
425 try sigma, try_find_ind !!env sigma typ realnames
426 with Not_found ->
427 unify_tomatch_with_patterns !!env sigma loc typ pats realnames
428 in
429 ((env, sigma), (j.uj_val,t))
430
431 let coerce_to_indtype ~program_mode typing_fun env sigma matx tomatchl =
432 let pats = List.map (fun r -> r.patterns) matx in
433 let matx' = match matrix_transpose pats with
434 | [] -> List.map (fun _ -> []) tomatchl (* no patterns at all *)
435 | m -> m in
436 let (env, sigma), tms = List.fold_left2_map (fun (env, sigma) -> coerce_row ~program_mode typing_fun env sigma) (env, sigma) matx' tomatchl in
437 env, sigma, tms
438
439 (************************************************************************)
440 (* Utils *)
441
442 let mkExistential ?(src=(Loc.tag Evar_kinds.InternalHole)) env sigma =
443 let sigma, (e, u) = Evarutil.new_type_evar env sigma ~src:src univ_flexible_alg in
444 sigma, e
445
446 let adjust_tomatch_to_pattern ~program_mode sigma pb ((current,typ),deps,dep) =
447 (* Ideally, we could find a common inductive type to which both the
448 term to match and the patterns coerce *)
449 (* In practice, we coerce the term to match if it is not already an
450 inductive type and it is not dependent; moreover, we use only
451 the first pattern type and forget about the others *)
452 let typ,names =
453 match typ with IsInd(t,_,names) -> t,Some names | NotInd(_,t) -> t,None in
454 let tmtyp =
455 try try_find_ind !!(pb.env) sigma typ names
456 with Not_found -> NotInd (None,typ) in
457 match tmtyp with
458 | NotInd (None,typ) ->
459 let tm1 = List.map (fun eqn -> List.hd eqn.patterns) pb.mat in
460 (match find_row_ind tm1 with
461 | None -> sigma, (current, tmtyp)
462 | Some (loc,(ind,_)) ->
463 let () = Tacred.check_privacy !!(pb.env) ind in
464 let sigma, indt = inductive_template !!(pb.env) sigma None ind in
465 let sigma, current =
466 if List.is_empty deps && isEvar sigma typ then
467 (* Don't insert coercions if dependent; only solve evars *)
468 match Evarconv.unify_leq_delay !!(pb.env) sigma indt typ with
469 | exception Evarconv.UnableToUnify (sigma,e) ->
470 raise (PretypeError (!!(pb.env), sigma, CannotUnify (indt, typ, Some e)))
471 | sigma -> sigma, current
472 else
473 let sigma, j, _trace = Coercion.inh_conv_coerce_to ?loc ~program_mode ~resolve_tc:true !!(pb.env) sigma (make_judge current typ) indt in
474 sigma, j.uj_val
475 in
476 sigma, (current, try_find_ind !!(pb.env) sigma indt names))
477 | _ -> sigma, (current, tmtyp)
478
479 let type_of_tomatch = function
480 | IsInd (t,_,_) -> t
481 | NotInd (_,t) -> t
482
483 let map_tomatch_type f = function
484 | IsInd (t,ind,names) -> IsInd (f t,map_inductive_type f ind,names)
485 | NotInd (c,t) -> NotInd (Option.map f c, f t)
486
487 let liftn_tomatch_type n depth = map_tomatch_type (Vars.liftn n depth)
488 let lift_tomatch_type n = liftn_tomatch_type n 1
489
490 (**********************************************************************)
491 (* Utilities on patterns *)
492
493 let current_pattern eqn =
494 match eqn.patterns with
495 | pat::_ -> pat
496 | [] -> anomaly (Pp.str "Empty list of patterns.")
497
498 let remove_current_pattern eqn =
499 match eqn.patterns with
500 | pat::pats ->
501 { eqn with
502 patterns = pats;
503 alias_stack = alias_of_pat pat :: eqn.alias_stack }
504 | [] -> anomaly (Pp.str "Empty list of patterns.")
505
506 let push_current_pattern ~program_mode sigma (cur,ty) eqn =
507 let hypnaming = VarSet.variables (Global.env ()) in
508 match eqn.patterns with
509 | pat::pats ->
510 let r = ERelevance.relevant in (* TODO relevance *)
511 let _,rhs_env = push_rel ~hypnaming sigma (LocalDef (make_annot (alias_of_pat pat) r,cur,ty)) eqn.rhs.rhs_env in
512 { eqn with
513 rhs = { eqn.rhs with rhs_env = rhs_env };
514 patterns = pats }
515 | [] -> anomaly (Pp.str "Empty list of patterns.")
516
517 (* spiwack: like [push_current_pattern] but does not introduce an
518 alias in rhs_env. Aliasing binders are only useful for variables at
519 the root of a pattern matching problem (initial push), so we
520 distinguish the cases. *)
521 let push_noalias_current_pattern eqn =
522 match eqn.patterns with
523 | _::pats ->
524 { eqn with patterns = pats }
525 | [] -> anomaly (Pp.str "push_noalias_current_pattern: Empty list of patterns.")
526
527
528
529 let prepend_pattern tms eqn = {eqn with patterns = tms@eqn.patterns }
530
531 (**********************************************************************)
532 (* Well-formedness tests *)
533 (* Partial check on patterns *)
534
535 exception NotAdjustable
536
537 let rec adjust_local_defs ?loc = function
538 | (pat :: pats, LocalAssum _ :: decls) ->
539 pat :: adjust_local_defs ?loc (pats,decls)
540 | (pats, LocalDef _ :: decls) ->
541 (DAst.make ?loc @@ PatVar Anonymous) :: adjust_local_defs ?loc (pats,decls)
542 | [], [] -> []
543 | _ -> raise NotAdjustable
544
545 let check_and_adjust_constructor env ind cstrs pat = match DAst.get pat with
546 | PatVar _ -> pat
547 | PatCstr (((_,i) as cstr),args,alias) ->
548 let loc = pat.CAst.loc in
549 (* Check it is constructor of the right type *)
550 let ind' = inductive_of_constructor cstr in
551 if QInd.equal env ind' ind then
552 (* Check the constructor has the right number of args *)
553 let ci = cstrs.(i-1) in
554 let nb_args_constr = ci.cs_nargs in
555 let nargs = List.length args in
556 if Int.equal nargs nb_args_constr then pat
557 else
558 try
559 let args' = adjust_local_defs ?loc (args, List.rev ci.cs_args)
560 in DAst.make ?loc @@ PatCstr (cstr, args', alias)
561 with NotAdjustable ->
562 let nlet = List.count (function LocalDef _ -> true | _ -> false) ci.cs_args in
563 (* In practice, this is already checked at interning *)
564 error_wrong_numarg_constructor ?loc env ~cstr
565 (* as if not expanded: *) ~expanded:false ~nargs ~expected_nassums:nb_args_constr
566 ~expected_ndecls:(nb_args_constr + nlet)
567 else
568 (* Try to insert a coercion *)
569 try
570 Coercion.inh_pattern_coerce_to ?loc env pat ind' ind
571 with Not_found ->
572 error_bad_constructor ?loc env cstr ind
573
574 let check_all_variables env sigma typ mat =
575 List.iter
576 (fun eqn ->
577 let pat = current_pattern eqn in
578 match DAst.get pat with
579 | PatVar id -> ()
580 | PatCstr (cstr_sp,_,_) ->
581 let loc = pat.CAst.loc in
582 error_bad_pattern ?loc env sigma cstr_sp typ)
583 mat
584
585 let set_pattern_catch_all_var ?loc eqn = function
586 | Name id when not (Id.Set.mem id eqn.rhs.rhs_vars) ->
587 { eqn with catch_all_vars = CAst.make ?loc id :: eqn.catch_all_vars }
588 | _ ->
589 eqn
590
591 let warn_named_multi_catch_all =
592 CWarnings.create ~name:"unused-pattern-matching-variable"
593 (fun id ->
594 strbrk "Unused variable " ++ Id.print id
595 ++ strbrk " might be a misspelled constructor. Use _ or _"
596 ++ Id.print id ++ strbrk " to silence this warning.")
597
598 let wildcard_id = Id.of_string "wildcard'"
599
600 let is_wildcard id =
601 Id.equal (Id.of_string (Nameops.atompart_of_id id)) wildcard_id
602
603 let check_unused_pattern_eqn env vars eqn =
604 match vars with
605 | [] -> raise_pattern_matching_error ?loc:eqn.eqn_loc (env, Evd.empty, UnusedClause eqn.patterns)
606 | _ ->
607 let warn {CAst.v = id; loc} =
608 (* Convention: Names starting with `_` and derivatives of Program's
609 "wildcard'" internal name deactivate the warning *)
610 if (Id.to_string id).[0] <> '_' && not (is_wildcard id)
611 then warn_named_multi_catch_all ?loc id in
612 List.iter warn (List.uniquize (List.flatten vars))
613
614 let check_unused_pattern env used matx =
615 let result = Array.init (List.length matx) (fun _ -> []) in
616 List.iter (function (Some n,vars) -> result.(n) <- vars :: result.(n) | _ -> ()) used;
617 List.iter2 (check_unused_pattern_eqn env) (Array.to_list result) matx
618
619 let extract_rhs pb =
620 match pb.mat with
621 | [] -> user_err (msg_may_need_inversion())
622 | eqn::_ -> ([eqn.orig,eqn.catch_all_vars], eqn.rhs)
623
624 (**********************************************************************)
625 (* Functions to deal with matrix factorization *)
626
627 let occur_in_rhs na rhs =
628 match na with
629 | Anonymous -> false
630 | Name id -> Id.Set.mem id rhs.rhs_vars
631
632 let is_dep_patt_in eqn pat = match DAst.get pat with
633 | PatVar name -> occur_in_rhs name eqn.rhs
634 | PatCstr _ -> true
635
636 let mk_dep_patt_row ~program_mode (pats,_,eqn) =
637 if program_mode then List.map (fun _ -> true) pats
638 else List.map (is_dep_patt_in eqn) pats
639
640 let dependencies_in_pure_rhs ~program_mode nargs eqns =
641 if List.is_empty eqns then
642 List.make nargs (not program_mode) (* Only "_" patts *) else
643 let deps_rows = List.map (mk_dep_patt_row ~program_mode) eqns in
644 let deps_columns = matrix_transpose deps_rows in
645 List.map (List.exists (fun x -> x)) deps_columns
646
647 let dependent_decl sigma a =
648 function
649 | LocalAssum (na,t) -> dependent sigma a t
650 | LocalDef (na,c,t) -> dependent sigma a t || dependent sigma a c
651
652 let rec dep_in_tomatch sigma n = function
653 | (Pushed _ | Alias _ | NonDepAlias) :: l -> dep_in_tomatch sigma n l
654 | Abstract (_,d) :: l -> RelDecl.exists (fun c -> not (noccurn sigma n c)) d || dep_in_tomatch sigma (n+1) l
655 | [] -> false
656
657 let dependencies_in_rhs ~program_mode sigma nargs current tms eqns =
658 match EConstr.kind sigma current with
659 | Rel n when dep_in_tomatch sigma n tms -> List.make nargs true
660 | _ -> dependencies_in_pure_rhs ~program_mode nargs eqns
661
662 (* Computing the matrix of dependencies *)
663
664 (* [find_dependency_list tmi [d(i+1);...;dn]] computes in which
665 declarations [d(i+1);...;dn] the term [tmi] is dependent in.
666
667 [find_dependencies_signature (used1,...,usedn) ((tm1,d1),...,(tmn,dn))]
668 returns [(deps1,...,depsn)] where [depsi] is a subset of tm(i+1),..,tmn
669 denoting in which of the d(i+1)...dn, the term tmi is dependent.
670 *)
671
672 let rec find_dependency_list sigma tmblock = function
673 | [] -> []
674 | (used,tdeps,tm,d)::rest ->
675 let deps = find_dependency_list sigma tmblock rest in
676 if used && List.exists (fun x -> dependent_decl sigma x d) tmblock
677 then
678 match EConstr.kind sigma tm with
679 | Rel n -> List.add_set Int.equal n (List.union Int.equal deps tdeps)
680 | _ -> List.union Int.equal deps tdeps
681 else deps
682
683 let find_dependencies sigma is_dep_or_cstr_in_rhs (tm,(_,tmtypleaves),d) nextlist =
684 let deps = find_dependency_list sigma (tm::tmtypleaves) nextlist in
685 if is_dep_or_cstr_in_rhs || not (List.is_empty deps)
686 then ((true ,deps,tm,d)::nextlist)
687 else ((false,[] ,tm,d)::nextlist)
688
689 let find_dependencies_signature sigma deps_in_rhs typs =
690 let l = List.fold_right2 (find_dependencies sigma) deps_in_rhs typs [] in
691 List.map (fun (_,deps,_,_) -> deps) l
692
693 (* Assume we had terms t1..tq to match in a context xp:Tp,...,x1:T1 |-
694 and xn:Tn has just been regeneralized into x:Tn so that the terms
695 to match are now to be considered in the context xp:Tp,...,x1:T1,x:Tn |-.
696
697 [relocate_index_tomatch n 1 tomatch] updates t1..tq so that
698 former references to xn1 are now references to x. Note that t1..tq
699 are already adjusted to the context xp:Tp,...,x1:T1,x:Tn |-.
700
701 [relocate_index_tomatch 1 n tomatch] will go the way back.
702 *)
703
704 let relocate_index_tomatch sigma n1 n2 =
705 let rec genrec depth = function
706 | [] ->
707 []
708 | Pushed (b,((c,tm),l,na)) :: rest ->
709 let c = relocate_index sigma n1 n2 depth c in
710 let tm = map_tomatch_type (relocate_index sigma n1 n2 depth) tm in
711 let l = List.map (relocate_rel n1 n2 depth) l in
712 Pushed (b,((c,tm),l,na)) :: genrec depth rest
713 | Alias (initial,(na,c,d)) :: rest ->
714 (* [c] is out of relocation scope *)
715 Alias (initial,(na,c,map_pair (relocate_index sigma n1 n2 depth) d)) :: genrec depth rest
716 | NonDepAlias :: rest ->
717 NonDepAlias :: genrec depth rest
718 | Abstract (i,d) :: rest ->
719 let i = relocate_rel n1 n2 depth i in
720 Abstract (i, RelDecl.map_constr (fun c -> relocate_index sigma n1 n2 depth c) d)
721 :: genrec (depth+1) rest in
722 genrec 0
723
724 (* [replace_tomatch n c tomatch] replaces [Rel n] by [c] in [tomatch] *)
725
726 let rec replace_term sigma n c k t =
727 if isRel sigma t && Int.equal (destRel sigma t) (n + k) then Vars.lift k c
728 else EConstr.map_with_binders sigma succ (replace_term sigma n c) k t
729
730 let length_of_tomatch_type_sign na t =
731 let l = match na with
732 | Anonymous -> 0
733 | Name _ -> 1
734 in
735 match t with
736 | NotInd _ -> l
737 | IsInd (_, _, names) -> List.length names + l
738
739 let replace_tomatch sigma n c =
740 let rec replrec depth = function
741 | [] -> []
742 | Pushed (initial,((b,tm),l,na)) :: rest ->
743 let b = replace_term sigma n c depth b in
744 let tm = map_tomatch_type (replace_term sigma n c depth) tm in
745 List.iter (fun i -> if Int.equal i (n + depth) then anomaly (Pp.str "replace_tomatch.")) l;
746 Pushed (initial,((b,tm),l,na)) :: replrec depth rest
747 | Alias (initial,(na,b,d)) :: rest ->
748 (* [b] is out of replacement scope *)
749 Alias (initial,(na,b,map_pair (replace_term sigma n c depth) d)) :: replrec depth rest
750 | NonDepAlias :: rest ->
751 NonDepAlias :: replrec depth rest
752 | Abstract (i,d) :: rest ->
753 Abstract (i, RelDecl.map_constr (fun t -> replace_term sigma n c depth t) d)
754 :: replrec (depth+1) rest in
755 replrec 0
756
757 (* [liftn_tomatch_stack]: a term to match has just been substituted by
758 some constructor t = (ci x1...xn) and the terms x1 ... xn have been
759 added to match; all pushed terms to match must be lifted by n
760 (knowing that [Abstract] introduces a binder in the list of pushed
761 terms to match).
762 *)
763
764 let rec liftn_tomatch_stack n depth = function
765 | [] -> []
766 | Pushed (initial,((c,tm),l,na))::rest ->
767 let c = liftn n depth c in
768 let tm = liftn_tomatch_type n depth tm in
769 let l = List.map (fun i -> if i<depth then i else i+n) l in
770 Pushed (initial,((c,tm),l,na))::(liftn_tomatch_stack n depth rest)
771 | Alias (initial,(na,c,d))::rest ->
772 Alias (initial,(na,liftn n depth c,map_pair (liftn n depth) d))
773 ::(liftn_tomatch_stack n depth rest)
774 | NonDepAlias :: rest ->
775 NonDepAlias :: liftn_tomatch_stack n depth rest
776 | Abstract (i,d)::rest ->
777 let i = if i<depth then i else i+n in
778 Abstract (i, RelDecl.map_constr (liftn n depth) d)
779 ::(liftn_tomatch_stack n (depth+1) rest)
780
781 let lift_tomatch_stack n = liftn_tomatch_stack n 1
782
783 (* if [current] has type [I(p1...pn u1...um)] and we consider the case
784 of constructor [ci] of type [I(p1...pn u'1...u'm)], then the
785 default variable [name] is expected to have which type?
786 Rem: [current] is [(Rel i)] except perhaps for initial terms to match *)
787
788 (************************************************************************)
789 (* Some heuristics to get names for variables pushed in pb environment *)
790 (* Typical requirement:
791
792 [match y with (S (S x)) => x | x => x end] should be compiled into
793 [match y with O => y | (S n) => match n with O => y | (S x) => x end end]
794
795 and [match y with (S (S n)) => n | n => n end] into
796 [match y with O => y | (S n0) => match n0 with O => y | (S n) => n end end]
797
798 i.e. user names should be preserved and created names should not
799 interfere with user names
800
801 The exact names here are not important for typing (because they are
802 put in pb.env and not in the rhs.rhs_env of branches. However,
803 whether a name is Anonymous or not may have an effect on whether a
804 generalization is done or not.
805 *)
806
807 let merge_name get_name obj = function
808 | Anonymous -> get_name obj
809 | na -> na
810
811 let merge_names get_name = List.map2 (merge_name get_name)
812
813 let get_names avoid env sigma sign eqns =
814 let names1 = List.make (Context.Rel.length sign) Anonymous in
815 (* If any, we prefer names used in pats, from top to bottom *)
816 let names2,aliasname =
817 List.fold_right
818 (fun (pats,pat_alias,eqn) (names,aliasname) ->
819 (merge_names alias_of_pat pats names,
820 merge_name (fun x -> x) pat_alias aliasname))
821 eqns (names1,Anonymous) in
822 (* Otherwise, we take names from the parameters of the constructor but
823 avoiding conflicts with user ids *)
824 let allvars =
825 List.fold_left (fun l (_,_,eqn) -> Id.Set.union l eqn.rhs.avoid_ids)
826 avoid eqns in
827 let names3,_ =
828 List.fold_left2
829 (fun (l,avoid) d na ->
830 let na =
831 merge_name
832 (fun decl ->
833 let na = get_name decl in
834 let t = get_type decl in
835 Name (next_name_away (named_hd env sigma t na) avoid))
836 d na
837 in
838 (na::l,Id.Set.add (Name.get_id na) avoid))
839 ([],allvars) (List.rev sign) names2 in
840 names3,aliasname
841
842 (*****************************************************************)
843 (* Recovering names for variables pushed to the rhs' environment *)
844 (* We just factorized a match over a matrix of equations *)
845 (* "C xi1 .. xin as xi" as a single match over "C y1 .. yn as y" *)
846 (* We now replace the names y1 .. yn y by the actual names *)
847 (* xi1 .. xin xi to be found in the i-th clause of the matrix *)
848
849 let recover_initial_subpattern_names = List.map2 RelDecl.set_name
850
851 let recover_and_adjust_alias_names (_,avoid) names sign =
852 let rec aux = function
853 | [],[] ->
854 []
855 | x::names, LocalAssum (x',t)::sign ->
856 (x, LocalAssum ({x' with binder_name=alias_of_pat x},t)) :: aux (names,sign)
857 | names, (LocalDef (na,_,_) as decl)::sign ->
858 (DAst.make @@ PatVar na.binder_name, decl) :: aux (names,sign)
859 | _ -> assert false
860 in
861 List.split (aux (names,sign))
862
863 let push_rels_eqn ~hypnaming sigma sign eqn =
864 {eqn with
865 rhs = {eqn.rhs with rhs_env = snd (push_rel_context ~hypnaming sigma sign eqn.rhs.rhs_env) } }
866
867 let push_rels_eqn_with_names sigma sign eqn =
868 let subpats = List.rev (List.firstn (List.length sign) eqn.patterns) in
869 let subpatnames = List.map alias_of_pat subpats in
870 let sign = recover_initial_subpattern_names subpatnames sign in
871 push_rels_eqn sigma sign eqn
872
873 let push_generalized_decl_eqn ~hypnaming env sigma n decl eqn =
874 match RelDecl.get_name decl with
875 | Anonymous ->
876 push_rels_eqn ~hypnaming sigma [decl] eqn
877 | Name _ ->
878 push_rels_eqn ~hypnaming sigma [RelDecl.set_name (RelDecl.get_name (Environ.lookup_rel n !!(eqn.rhs.rhs_env))) decl] eqn
879
880 let drop_alias_eqn eqn =
881 { eqn with alias_stack = List.tl eqn.alias_stack }
882
883 let push_alias_eqn sigma alias eqn =
884 let aliasname = List.hd eqn.alias_stack in
885 let eqn = drop_alias_eqn eqn in
886 let alias = RelDecl.set_name aliasname alias in
887 push_rels_eqn sigma [alias] eqn
888
889 (**********************************************************************)
890 (* Functions to deal with elimination predicate *)
891
892 (* Inferring the predicate *)
893 (*
894 The problem to solve is the following:
895
896 We match Gamma |- t : I(u01..u0q) against the following constructors:
897
898 Gamma, x11...x1p1 |- C1(x11..x1p1) : I(u11..u1q)
899 ...
900 Gamma, xn1...xnpn |- Cn(xn1..xnp1) : I(un1..unq)
901
902 Assume the types in the branches are the following
903
904 Gamma, x11...x1p1 |- branch1 : T1
905 ...
906 Gamma, xn1...xnpn |- branchn : Tn
907
908 Assume the type of the global case expression is Gamma |- T
909
910 The predicate has the form phi = [y1..yq][z:I(y1..yq)]psi and it has to
911 satisfy the following n+1 equations:
912
913 Gamma, x11...x1p1 |- (phi u11..u1q (C1 x11..x1p1)) = T1
914 ...
915 Gamma, xn1...xnpn |- (phi un1..unq (Cn xn1..xnpn)) = Tn
916 Gamma |- (phi u01..u0q t) = T
917
918 Some hints:
919
920 - Clearly, if xij occurs in Ti, then, a "match z with (Ci xi1..xipi)
921 => ... end" or a "psi(yk)", with psi extracting xij from uik, should be
922 inserted somewhere in Ti.
923
924 - If T is undefined, an easy solution is to insert a "match z with
925 (Ci xi1..xipi) => ... end" in front of each Ti
926
927 - Otherwise, T1..Tn and T must be step by step unified, if some of them
928 diverge, then try to replace the diverging subterm by one of y1..yq or z.
929
930 - The main problem is what to do when an existential variables is encountered
931
932 *)
933
934 (* Propagation of user-provided predicate through compilation steps *)
935
936 let rec map_predicate f k ccl = function
937 | [] -> f k ccl
938 | Pushed (_,((_,tm),_,na)) :: rest ->
939 let k' = length_of_tomatch_type_sign na tm in
940 map_predicate f (k+k') ccl rest
941 | (Alias _ | NonDepAlias) :: rest ->
942 map_predicate f k ccl rest
943 | Abstract _ :: rest ->
944 map_predicate f (k+1) ccl rest
945
946 let noccur_predicate_between sigma n = map_predicate (noccur_between sigma n)
947
948 let liftn_predicate n = map_predicate (liftn n)
949
950 let lift_predicate n = liftn_predicate n 1
951
952 let regeneralize_index_predicate sigma n = map_predicate (relocate_index sigma n 1) 0
953
954 let substnl_predicate sigma = map_predicate (substnl sigma)
955
956 (* This is parallel bindings *)
957 let subst_predicate (subst,copt) ccl tms =
958 let sigma = match copt with
959 | None -> subst
960 | Some c -> c::subst in
961 substnl_predicate sigma 0 ccl tms
962
963 let specialize_predicate_var (cur,typ,dep) env tms ccl =
964 let c = match dep with
965 | Anonymous -> None
966 | Name _ -> Some cur
967 in
968 let l =
969 match typ with
970 | IsInd (_, IndType (_, _), []) -> []
971 | IsInd (_, IndType (indf, realargs), names) ->
972 let arsign = get_arity env indf in
973 subst_of_rel_context_instance_list arsign realargs
974 | NotInd _ -> [] in
975 subst_predicate (l,c) ccl tms
976
977 (*****************************************************************************)
978 (* We have pred = [X:=realargs;x:=c]P typed in Gamma1, x:I(realargs), Gamma2 *)
979 (* and we want to abstract P over y:t(x) typed in the same context to get *)
980 (* *)
981 (* pred' = [X:=realargs;x':=c](y':t(x'))P[y:=y'] *)
982 (* *)
983 (* We first need to lift t(x) s.t. it is typed in Gamma, X:=rargs, x' *)
984 (* then we have to replace x by x' in t(x) and y by y' in P *)
985 (*****************************************************************************)
986 let generalize_predicate sigma (names,na) ny d tms ccl =
987 let () = match na with
988 | Anonymous -> anomaly (Pp.str "Undetected dependency.")
989 | _ -> () in
990 let p = List.length names + 1 in
991 let ccl = lift_predicate 1 ccl tms in
992 regeneralize_index_predicate sigma (ny+p+1) ccl tms
993
994 (*****************************************************************************)
995 (* We just matched over cur:ind(realargs) in the following matching problem *)
996 (* *)
997 (* env |- match cur tms return ccl with ... end *)
998 (* *)
999 (* and we want to build the predicate corresponding to the individual *)
1000 (* matching over cur *)
1001 (* *)
1002 (* pred = fun X:realargstyps x:ind(X)] PI tms.ccl *)
1003 (* *)
1004 (* where pred is computed by abstract_predicate and PI tms.ccl by *)
1005 (* extract_predicate *)
1006 (*****************************************************************************)
1007 let rec extract_predicate ccl = function
1008 | (Alias _ | NonDepAlias)::tms ->
1009 (* substitution already done in build_branch *)
1010 extract_predicate ccl tms
1011 | Abstract (i,d)::tms ->
1012 mkProd_wo_LetIn d (extract_predicate ccl tms)
1013 | Pushed (_,((cur,NotInd _),_,na))::tms ->
1014 begin match na with
1015 | Anonymous -> extract_predicate ccl tms
1016 | Name _ ->
1017 let tms = lift_tomatch_stack 1 tms in
1018 let pred = extract_predicate ccl tms in
1019 subst1 cur pred
1020 end
1021 | Pushed (_,((cur,IsInd (_,IndType(_,realargs),_)),_,na))::tms ->
1022 let realargs = List.rev realargs in
1023 let k, nrealargs = match na with
1024 | Anonymous -> 0, realargs
1025 | Name _ -> 1, (cur :: realargs)
1026 in
1027 let tms = lift_tomatch_stack (List.length realargs + k) tms in
1028 let pred = extract_predicate ccl tms in
1029 substl nrealargs pred
1030 | [] ->
1031 ccl
1032
1033 let abstract_predicate env sigma indf cur realargs (names,na) tms ccl =
1034 let sign = make_arity_signature !!env sigma true indf in
1035 (* n is the number of real args + 1 (+ possible let-ins in sign) *)
1036 let n = List.length sign in
1037 (* Before abstracting we generalize over cur and on those realargs *)
1038 (* that are rels, consistently with the specialization made in *)
1039 (* build_branch *)
1040 let tms = List.fold_right2 (fun par arg tomatch ->
1041 match EConstr.kind sigma par with
1042 | Rel i -> relocate_index_tomatch sigma (i+n) (destRel sigma arg) tomatch
1043 | _ -> tomatch) (realargs@[cur]) (Context.Rel.instance_list EConstr.mkRel 0 sign)
1044 (lift_tomatch_stack n tms) in
1045 (* Pred is already dependent in the current term to match (if *)
1046 (* (na<>Anonymous) and its realargs; we just need to adjust it to *)
1047 (* full sign if dep in cur is not taken into account *)
1048 let ccl = match na with
1049 | Anonymous -> lift_predicate 1 ccl tms
1050 | Name _ -> ccl
1051 in
1052 let pred = extract_predicate ccl tms in
1053 (* Build the predicate properly speaking *)
1054 let sign = List.map2 set_name (na::names) sign in
1055 it_mkLambda_or_LetIn_name !!env sigma pred sign
1056
1057 (* [expand_arg] is used by [specialize_predicate]
1058 if Yk denotes [Xk;xk] or [Xk],
1059 it replaces gamma, x1...xn, x1...xk Yk+1...Yn |- pred
1060 by gamma, x1...xn, x1...xk-1 [Xk;xk] Yk+1...Yn |- pred (if dep) or
1061 by gamma, x1...xn, x1...xk-1 [Xk] Yk+1...Yn |- pred (if not dep) *)
1062
1063 let expand_arg tms (p,ccl) ((_,t),_,na) =
1064 let k = length_of_tomatch_type_sign na t in
1065 (p+k,liftn_predicate (k-1) (p+1) ccl tms)
1066
1067 let add_assert_false_case pb tomatch =
1068 let pats = List.map (fun _ -> DAst.make @@ PatVar Anonymous) tomatch in
1069 let aliasnames =
1070 List.map_filter (function Alias _ | NonDepAlias -> Some Anonymous | _ -> None) tomatch
1071 in
1072 [ { patterns = pats;
1073 rhs = { rhs_env = pb.env;
1074 rhs_vars = Id.Set.empty;
1075 avoid_ids = Id.Set.empty;
1076 it = None };
1077 alias_stack = Anonymous::aliasnames;
1078 eqn_loc = None;
1079 orig = None;
1080 catch_all_vars = [] } ]
1081
1082 let adjust_impossible_cases sigma pb pred tomatch submat =
1083 match submat with
1084 | [] ->
1085 begin match EConstr.kind sigma pred with
1086 | Evar (evk, _) ->
1087 let evi = Evd.find_undefined sigma evk in
1088 if snd (Evd.evar_source evi) == Evar_kinds.ImpossibleCase then
1089 let sigma, default = coq_unit_judge !!(pb.env) sigma in
1090 let sigma = Evd.define evk default.uj_type sigma in
1091 sigma, add_assert_false_case pb tomatch
1092 else
1093 sigma, submat
1094 | _ ->
1095 let sigma', default = coq_unit_judge !!(pb.env) sigma in
1096 if EConstr.eq_constr_nounivs sigma' pred default.uj_type
1097 then sigma, add_assert_false_case pb tomatch
1098 else sigma, submat
1099 end
1100 | _ ->
1101 sigma, submat
1102
1103 (*****************************************************************************)
1104 (* Let pred = PI [X;x:I(X)]. PI tms. P be a typing predicate for the *)
1105 (* following pattern-matching problem: *)
1106 (* *)
1107 (* Gamma |- match Pushed(c:I(V)) as x in I(X), tms return pred with...end *)
1108 (* *)
1109 (* where the branch with constructor Ci:(x1:T1)...(xn:Tn)->I(realargsi) *)
1110 (* is considered. Assume each Ti is some Ii(argsi) with Ti:PI Ui. sort_i *)
1111 (* We let subst = X:=realargsi;x:=Ci(x1,...,xn) and replace pred by *)
1112 (* *)
1113 (* pred' = PI [X1:Ui;x1:I1(X1)]...[Xn:Un;xn:In(Xn)]. (PI tms. P)[subst] *)
1114 (* *)
1115 (* s.t. the following well-typed sub-pattern-matching problem is obtained *)
1116 (* *)
1117 (* Gamma,x'1..x'n |- *)
1118 (* match *)
1119 (* Pushed(x'1) as x1 in I(X1), *)
1120 (* .., *)
1121 (* Pushed(x'n) as xn in I(Xn), *)
1122 (* tms *)
1123 (* return pred' *)
1124 (* with .. end *)
1125 (* *)
1126 (*****************************************************************************)
1127 let specialize_predicate env sigma newtomatchs (names,depna) arsign cs tms ccl =
1128 (* Assume some gamma st: gamma |- PI [X,x:I(X)]. PI tms. ccl *)
1129 let nrealargs = List.length names in
1130 let l = match depna with Anonymous -> 0 | Name _ -> 1 in
1131 let k = nrealargs + l in
1132 (* We adjust pred st: gamma, x1..xn |- PI [X,x:I(X)]. PI tms. ccl' *)
1133 (* so that x can later be instantiated by Ci(x1..xn) *)
1134 (* and X by the realargs for Ci *)
1135 let n = cs.cs_nargs in
1136 let ccl' = liftn_predicate n (k+1) ccl tms in
1137 (* We prepare the substitution of X and x:I(X) *)
1138 let realargsi =
1139 if not (Int.equal nrealargs 0) then
1140 Vars.subst_of_rel_context_instance arsign cs.cs_concl_realargs
1141 else
1142 [] in
1143 let copti = match depna with
1144 | Anonymous -> None
1145 | Name _ -> Some (build_dependent_constructor cs)
1146 in
1147 (* The substituends realargsi, copti are all defined in gamma, x1...xn *)
1148 (* We need _parallel_ bindings to get gamma, x1...xn |- PI tms. ccl'' *)
1149 (* Note: applying the substitution in tms is not important (is it sure?) *)
1150 let ccl'' =
1151 whd_betaiota env sigma (subst_predicate (realargsi, copti) ccl' tms) in
1152 (* We adjust ccl st: gamma, x'1..x'n, x1..xn, tms |- ccl'' *)
1153 let ccl''' = liftn_predicate n (n+1) ccl'' tms in
1154 (* We finally get gamma,x'1..x'n,x |- [X1;x1:I(X1)]..[Xn;xn:I(Xn)]pred'''*)
1155 snd (List.fold_left (expand_arg tms) (1,ccl''') newtomatchs)
1156
1157 let find_predicate loc env sigma p current (IndType (indf,realargs)) dep tms =
1158 let pred = abstract_predicate env sigma indf current realargs dep tms p in
1159 (pred, whd_betaiota !!env sigma
1160 (applist (pred, realargs@[current])))
1161
1162 (* Take into account that a type has been discovered to be inductive, leading
1163 to more dependencies in the predicate if the type has indices *)
1164 let adjust_predicate_from_tomatch tomatch (current,typ as ct) pb =
1165 let ((_,oldtyp),deps,na) = tomatch in
1166 match typ, oldtyp with
1167 | IsInd (_,_,names), NotInd _ ->
1168 let k = match na with
1169 | Anonymous -> 1
1170 | Name _ -> 2
1171 in
1172 let n = List.length names in
1173 { pb with pred = liftn_predicate n k pb.pred pb.tomatch },
1174 (ct,List.map (fun i -> if i >= k then i+n else i) deps,na)
1175 | _ ->
1176 pb, (ct,deps,na)
1177
1178 (* Remove commutative cuts that turn out to be non-dependent after
1179 some evars have been instantiated *)
1180
1181 let rec ungeneralize sigma n ng body =
1182 match EConstr.kind sigma body with
1183 | Lambda (_,_,c) when Int.equal ng 0 ->
1184 subst1 (mkRel n) c
1185 | Lambda (na,t,c) ->
1186 (* We traverse an inner generalization *)
1187 mkLambda (na,t,ungeneralize sigma (n+1) (ng-1) c)
1188 | LetIn (na,b,t,c) ->
1189 (* We traverse an alias *)
1190 mkLetIn (na,b,t,ungeneralize sigma (n+1) ng c)
1191 | Case (ci,u,pms,(p,rp),iv,c,brs) ->
1192 (* We traverse a split *)
1193 let p =
1194 let (nas, p) = p in
1195 let sign2,p = decompose_prod_n_decls sigma ng p in
1196 let p = prod_applist sigma p [mkRel (n+Array.length nas+ng)] in
1197 nas, it_mkProd_or_LetIn p sign2
1198 in
1199 let map (nas, br) = nas, ungeneralize sigma (n + Array.length nas) ng br in
1200 mkCase (ci, u, pms, (p,rp), iv, c, Array.map map brs)
1201 | App (f,args) ->
1202 (* We traverse an inner generalization *)
1203 assert (isCase sigma f);
1204 mkApp (ungeneralize sigma n (ng+Array.length args) f,args)
1205 | _ -> assert false
1206
1207 let ungeneralize_branch sigma n k (sign,body) cs =
1208 (sign,ungeneralize sigma (n+cs.cs_nargs) k body)
1209
1210 let rec is_dependent_generalization sigma ng body =
1211 match EConstr.kind sigma body with
1212 | Lambda (_,_,c) when Int.equal ng 0 ->
1213 not (noccurn sigma 1 c)
1214 | Lambda (na,t,c) ->
1215 (* We traverse an inner generalization *)
1216 is_dependent_generalization sigma (ng-1) c
1217 | LetIn (na,b,t,c) ->
1218 (* We traverse an alias *)
1219 is_dependent_generalization sigma ng c
1220 | Case (ci,u,pms,p,iv,c,brs) ->
1221 (* We traverse a split *)
1222 Array.exists (fun (_, b) -> is_dependent_generalization sigma ng b) brs
1223 | App (g,args) ->
1224 (* We traverse an inner generalization *)
1225 assert (isCase sigma g);
1226 is_dependent_generalization sigma (ng+Array.length args) g
1227 | _ -> assert false
1228
1229 let is_dependent_branch sigma k (_,br) =
1230 is_dependent_generalization sigma k br
1231
1232 let postprocess_dependencies evd tocheck brs tomatch pred deps cs =
1233 let rec aux k brs tomatch pred tocheck deps = match deps, tomatch with
1234 | [], _ -> brs,tomatch,pred,[]
1235 | n::deps, Abstract (i,d) :: tomatch ->
1236 let d = map_constr (fun c -> nf_evar evd c) d in
1237 let is_d = match d with LocalAssum _ -> false | LocalDef _ -> true in
1238 if is_d || List.exists (fun c -> dependent_decl evd (lift k c) d) tocheck
1239 && Array.exists (is_dependent_branch evd k) brs then
1240 (* Dependency in the current term to match and its dependencies is real *)
1241 let brs,tomatch,pred,inst = aux (k+1) brs tomatch pred (mkRel n::tocheck) deps in
1242 let inst = match d with
1243 | LocalAssum _ -> mkRel n :: inst
1244 | _ -> inst
1245 in
1246 brs, Abstract (i,d) :: tomatch, pred, inst
1247 else
1248 (* Finally, no dependency remains, so, we can replace the generalized *)
1249 (* terms by its actual value in both the remaining terms to match and *)
1250 (* the bodies of the Case *)
1251 let pred = lift_predicate (-1) pred tomatch in
1252 let tomatch = relocate_index_tomatch evd 1 (n+1) tomatch in
1253 let tomatch = lift_tomatch_stack (-1) tomatch in
1254 let brs = Array.map2 (ungeneralize_branch evd n k) brs cs in
1255 aux k brs tomatch pred tocheck deps
1256 | _ -> assert false
1257 in aux 0 brs tomatch pred tocheck deps
1258
1259 (************************************************************************)
1260 (* Sorting equations by constructor *)
1261
1262 let rec irrefutable env pat = match DAst.get pat with
1263 | PatVar name -> true
1264 | PatCstr (cstr,args,_) ->
1265 let ind = inductive_of_constructor cstr in
1266 let (_,mip) = Inductive.lookup_mind_specif env ind in
1267 let one_constr = Int.equal (Array.length mip.mind_user_lc) 1 in
1268 one_constr && List.for_all (irrefutable env) args
1269
1270 let first_clause_irrefutable env = function
1271 | {patterns=pat::patl}::mat -> (match DAst.get pat with PatVar _ -> List.for_all (irrefutable env) patl | _ -> false)
1272 | _ -> false
1273
1274 let group_equations pb ind current cstrs mat =
1275 let mat =
1276 if first_clause_irrefutable !!(pb.env) mat then [List.hd mat] else mat in
1277 let brs = Array.make (Array.length cstrs) [] in
1278 let only_default = ref None in
1279 let _ =
1280 List.fold_right (* To be sure it's from bottom to top *)
1281 (fun eqn () ->
1282 let rest = remove_current_pattern eqn in
1283 let pat = current_pattern eqn in
1284 match DAst.get (check_and_adjust_constructor !!(pb.env) ind cstrs pat) with
1285 | PatVar name ->
1286 (* This is a default clause that we expand *)
1287 let rest = set_pattern_catch_all_var ?loc:pat.CAst.loc rest name in
1288 for i=1 to Array.length cstrs do
1289 let args = make_anonymous_patvars cstrs.(i-1).cs_nargs in
1290 brs.(i-1) <- (args, name, rest) :: brs.(i-1)
1291 done;
1292 if !only_default == None then only_default := Some true
1293 | PatCstr (((_,i)),args,name) ->
1294 (* This is a regular clause *)
1295 only_default := Some false;
1296 brs.(i-1) <- (args, name, rest) :: brs.(i-1)) mat () in
1297 (brs,Option.default false !only_default)
1298
1299 (************************************************************************)
1300 (* Here starts the pattern-matching compilation algorithm *)
1301
1302 (* Abstracting over dependent subterms to match *)
1303 let rec generalize_problem names sigma pb = function
1304 | [] -> pb, []
1305 | i::l ->
1306 let pb',deps = generalize_problem names sigma pb l in
1307 let d = map_constr (lift i) (lookup_rel i !!(pb.env)) in
1308 begin match d with
1309 | LocalDef ({binder_name=Anonymous},_,_) -> pb', deps
1310 | _ ->
1311 (* for better rendering *)
1312 let d = RelDecl.map_type (fun c -> whd_betaiota !!(pb.env) sigma c) d in
1313 let tomatch = lift_tomatch_stack 1 pb'.tomatch in
1314 let tomatch = relocate_index_tomatch sigma (i+1) 1 tomatch in
1315 { pb' with
1316 tomatch = Abstract (i,d) :: tomatch;
1317 pred = generalize_predicate sigma names i d pb'.tomatch pb'.pred },
1318 i::deps
1319 end
1320
1321 (* No more patterns: typing the right-hand side of equations *)
1322 let build_leaf sigma pb =
1323 let used, rhs = extract_rhs pb in
1324 let sigma, j = pb.typing_function (mk_tycon pb.pred) rhs.rhs_env sigma rhs.it in
1325 used, sigma, j_nf_evar sigma j
1326
1327 (* Build the sub-pattern-matching problem for a given branch "C x1..xn as x" *)
1328 (* spiwack: the [initial] argument keeps track whether the branch is a
1329 toplevel branch ([true]) or a deep one ([false]). *)
1330 let build_branch ~program_mode initial current realargs deps (realnames,curname) sigma pb arsign eqns const_info =
1331 (* We remember that we descend through constructor C *)
1332 let history =
1333 push_history_pattern const_info.cs_nargs (fst const_info.cs_cstr) pb.history in
1334
1335 (* We prepare the matching on x1:T1 .. xn:Tn using some heuristic to *)
1336 (* build the name x1..xn from the names present in the equations *)
1337 (* that had matched constructor C *)
1338 let cs_args = const_info.cs_args in
1339 let names,aliasname = get_names (GlobEnv.vars_of_env pb.env) !!(pb.env) sigma cs_args eqns in
1340 let typs = List.map2 RelDecl.set_name names cs_args
1341 in
1342
1343 (* Beta-iota-normalize types to better compatibility of refine with 8.4 behavior *)
1344 (* This is a bit too strong I think, in the sense that what we would *)
1345 (* really like is to have beta-iota reduction only at the positions where *)
1346 (* parameters are substituted *)
1347 let typs = List.map (map_type (nf_betaiota !!(pb.env) sigma)) typs in
1348
1349 (* We build the matrix obtained by expanding the matching on *)
1350 (* "C x1..xn as x" followed by a residual matching on eqn into *)
1351 (* a matching on "x1 .. xn eqn" *)
1352 let submat = List.map (fun (tms,_,eqn) -> prepend_pattern tms eqn) eqns in
1353
1354 (* We adjust the terms to match in the context they will be once the *)
1355 (* context [x1:T1,..,xn:Tn] will have been pushed on the current env *)
1356 let typs' =
1357 List.map_i (fun i d -> (mkRel i, map_constr (lift i) d)) 1 typs in
1358
1359 let hypnaming = VarSet.variables (Global.env ()) in
1360 let typs,extenv = push_rel_context ~hypnaming sigma typs pb.env in
1361
1362 let typs' =
1363 List.map (fun (c,d) ->
1364 (c,extract_inductive_data !!extenv sigma d,d)) typs' in
1365
1366 (* We compute over which of x(i+1)..xn and x matching on xi will need a *)
1367 (* generalization *)
1368 let dep_sign =
1369 find_dependencies_signature sigma
1370 (dependencies_in_rhs ~program_mode sigma const_info.cs_nargs current pb.tomatch eqns)
1371 (List.rev typs') in
1372
1373 (* The dependent term to subst in the types of the remaining UnPushed
1374 terms is relative to the current context enriched by topushs *)
1375 let ci = build_dependent_constructor const_info in
1376
1377 (* Current context Gamma has the form Gamma1;cur:I(realargs);Gamma2 *)
1378 (* We go from Gamma |- PI tms. pred to *)
1379 (* Gamma;x1..xn;curalias:I(x1..xn) |- PI tms'. pred' *)
1380 (* where, in tms and pred, those realargs that are vars are *)
1381 (* replaced by the corresponding xi and cur replaced by curalias *)
1382 let cirealargs = Array.to_list const_info.cs_concl_realargs in
1383
1384 (* Do the specialization for terms to match *)
1385 let tomatch = List.fold_right2 (fun par arg tomatch ->
1386 match EConstr.kind sigma par with
1387 | Rel i -> replace_tomatch sigma (i+const_info.cs_nargs) arg tomatch
1388 | _ -> tomatch) (current::realargs) (ci::cirealargs)
1389 (lift_tomatch_stack const_info.cs_nargs pb.tomatch) in
1390
1391 let pred_is_not_dep =
1392 noccur_predicate_between sigma 1 (List.length realnames + 1) pb.pred tomatch in
1393
1394 let typs' =
1395 List.map2
1396 (fun (tm, (tmtyp,_), decl) deps ->
1397 let na = RelDecl.get_name decl in
1398 let na = match curname, na with
1399 | Name _, Anonymous -> curname
1400 | Name _, Name _ -> na
1401 | Anonymous, _ ->
1402 if List.is_empty deps && pred_is_not_dep then Anonymous else force_name na in
1403 ((tm,tmtyp),deps,na))
1404 typs' (List.rev dep_sign) in
1405
1406 (* Do the specialization for the predicate *)
1407 let pred =
1408 specialize_predicate !!(pb.env) sigma typs' (realnames,curname) arsign const_info tomatch pb.pred in
1409
1410 let currents = List.map (fun x -> Pushed (false,x)) typs' in
1411
1412 let alias = match aliasname with
1413 | Anonymous ->
1414 NonDepAlias
1415 | Name _ ->
1416 let cur_alias = lift const_info.cs_nargs current in
1417 let ind =
1418 mkApp (
1419 applist (mkIndU (inductive_of_constructor (fst const_info.cs_cstr), snd const_info.cs_cstr),
1420 List.map (lift const_info.cs_nargs) const_info.cs_params),
1421 const_info.cs_concl_realargs) in
1422 Alias (initial,(aliasname,cur_alias,(ci,ind))) in
1423
1424 let tomatch = List.rev_append (alias :: currents) tomatch in
1425
1426 let sigma, submat = adjust_impossible_cases sigma pb pred tomatch submat in
1427 let () = match submat with
1428 | [] ->
1429 raise_pattern_matching_error (!!(pb.env), Evd.empty, NonExhaustive (complete_history history))
1430 | _ -> ()
1431 in
1432
1433 sigma, typs,
1434 { pb with
1435 env = extenv;
1436 tomatch = tomatch;
1437 pred = pred;
1438 history = history;
1439 mat = List.map (push_rels_eqn_with_names ~hypnaming sigma typs) submat }
1440
1441 (**********************************************************************
1442 INVARIANT:
1443
1444 pb = { env, pred, tomatch, mat, ...}
1445 tomatch = list of Pushed (c:T), Abstract (na:T), Alias (c:T) or NonDepAlias
1446
1447 all terms and types in Pushed, Abstract and Alias are relative to env
1448 enriched by the Abstract coming before
1449
1450 *)
1451
1452 (**********************************************************************)
1453 (* Main compiling descent *)
1454 let compile ~program_mode sigma pb =
1455 let hypnaming = VarSet.variables (Global.env ()) in
1456 let rec compile sigma pb =
1457 match pb.tomatch with
1458 | Pushed cur :: rest -> match_current sigma { pb with tomatch = rest } cur
1459 | Alias (initial,x) :: rest -> compile_alias initial sigma pb x rest
1460 | NonDepAlias :: rest -> compile_non_dep_alias sigma pb rest
1461 | Abstract (i,d) :: rest -> compile_generalization sigma pb i d rest
1462 | [] -> build_leaf sigma pb
1463
1464 (* Case splitting *)
1465 and match_current sigma pb (initial,tomatch) =
1466 let sigma, tm = adjust_tomatch_to_pattern ~program_mode sigma pb tomatch in
1467 let pb,tomatch = adjust_predicate_from_tomatch tomatch tm pb in
1468 let ((current,typ),deps,dep) = tomatch in
1469 match typ with
1470 | NotInd (_,typ) ->
1471 check_all_variables !!(pb.env) sigma typ pb.mat;
1472 compile_all_variables initial tomatch sigma pb
1473 | IsInd (_,(IndType(indf,realargs) as indt),names) ->
1474 let mind,_ = dest_ind_family indf in
1475 let cstrs = get_constructors !!(pb.env) indf in
1476 let arsign = get_arity !!(pb.env) indf in
1477 let eqns,onlydflt = group_equations pb (fst mind) current cstrs pb.mat in
1478 let no_cstr = Int.equal (Array.length cstrs) 0 in
1479 if (not no_cstr || not (List.is_empty pb.mat)) && onlydflt then
1480 compile_all_variables initial tomatch sigma pb
1481 else
1482 (* We generalize over terms depending on current term to match *)
1483 let pb,deps = generalize_problem (names,dep) sigma pb deps in
1484
1485 (* We compile branches *)
1486 let fold_br sigma eqn cstr =
1487 let used, sigma, j = compile_branch initial current realargs (names,dep) deps sigma pb arsign eqn cstr in
1488 sigma, (used, j)
1489 in
1490 let sigma, brvals = Array.fold_left2_map fold_br sigma eqns cstrs in
1491 let used, brvals = Array.split brvals in
1492 (* We build the (elementary) case analysis *)
1493 let depstocheck = current::binding_vars_of_inductive sigma typ in
1494 let brvals,tomatch,pred,inst =
1495 postprocess_dependencies sigma depstocheck
1496 brvals pb.tomatch pb.pred deps cstrs in
1497 let brvals = Array.map (fun (sign,body) ->
1498 it_mkLambda_or_LetIn body sign) brvals in
1499 let (pred,typ) =
1500 find_predicate pb.caseloc pb.env sigma
1501 pred current indt (names,dep) tomatch
1502 in
1503 let sigma, rci = Typing.check_allowed_sort !!(pb.env) sigma mind current pred in
1504 let ci = make_case_info !!(pb.env) (fst mind) pb.casestyle in
1505 let pred = nf_betaiota !!(pb.env) sigma pred in
1506 let case = make_case_or_project !!(pb.env) sigma indt ci (pred,rci) current brvals in
1507 let sigma, _ = Typing.type_of !!(pb.env) sigma pred in
1508 let used = List.flatten (Array.to_list used) in
1509 used, sigma, { uj_val = applist (case, inst);
1510 uj_type = prod_applist sigma typ inst }
1511
1512
1513 (* Building the sub-problem when all patterns are variables. Case
1514 where [current] is an initially pushed term. *)
1515 and shift_problem ((current,t),_,na) sigma pb =
1516 let ty = type_of_tomatch t in
1517 let tomatch = lift_tomatch_stack 1 pb.tomatch in
1518 let pred = specialize_predicate_var (current,t,na) !!(pb.env) pb.tomatch pb.pred in
1519 let env = Name.fold_left (fun env id -> hide_variable env id) pb.env na in
1520 let pb =
1521 { pb with
1522 env = snd (push_rel ~hypnaming sigma (LocalDef (annotR na,current,ty)) env);
1523 tomatch = tomatch;
1524 pred = lift_predicate 1 pred tomatch;
1525 history = pop_history pb.history;
1526 mat = List.map (push_current_pattern ~program_mode sigma (current,ty)) pb.mat } in
1527 let used, sigma, j = compile sigma pb in
1528 used, sigma, { uj_val = subst1 current j.uj_val;
1529 uj_type = subst1 current j.uj_type }
1530
1531 (* Building the sub-problem when all patterns are variables,
1532 non-initial case. Variables which appear as subterms of constructor
1533 are already introduced in the context, we avoid creating aliases to
1534 themselves by treating this case specially. *)
1535 and pop_problem ((current,t),_,na) sigma pb =
1536 let pred = specialize_predicate_var (current,t,na) !!(pb.env) pb.tomatch pb.pred in
1537 let pb =
1538 { pb with
1539 pred = pred;
1540 history = pop_history pb.history;
1541 mat = List.map push_noalias_current_pattern pb.mat } in
1542 compile sigma pb
1543
1544 (* Building the sub-problem when all patterns are variables. *)
1545 and compile_all_variables initial cur sigma pb =
1546 if initial then shift_problem cur sigma pb
1547 else pop_problem cur sigma pb
1548
1549 (* Building the sub-problem when all patterns are variables *)
1550 and compile_branch initial current realargs names deps sigma pb arsign eqns cstr =
1551 let sigma, sign, pb = build_branch ~program_mode initial current realargs deps names sigma pb arsign eqns cstr in
1552 let used, sigma, j = compile sigma pb in
1553 used, sigma, (sign, j.uj_val)
1554
1555 (* Abstract over a declaration before continuing splitting *)
1556 and compile_generalization sigma pb i d rest =
1557 let pb =
1558 { pb with
1559 env = snd (push_rel ~hypnaming sigma d pb.env);
1560 tomatch = rest;
1561 mat = List.map (push_generalized_decl_eqn ~hypnaming pb.env sigma i d) pb.mat } in
1562 let used, sigma, j = compile sigma pb in
1563 used, sigma, { uj_val = mkLambda_or_LetIn d j.uj_val;
1564 uj_type = mkProd_wo_LetIn d j.uj_type }
1565
1566 (* spiwack: the [initial] argument keeps track whether the alias has
1567 been introduced by a toplevel branch ([true]) or a deep one
1568 ([false]). *)
1569 and compile_alias initial sigma pb (na,orig,(expanded,expanded_typ)) rest =
1570 let f c t =
1571 let r = Retyping.relevance_of_type !!(pb.env) sigma t in
1572 let alias = LocalDef (make_annot na r,c,t) in
1573 let pb =
1574 { pb with
1575 env = snd (push_rel ~hypnaming sigma alias pb.env);
1576 tomatch = lift_tomatch_stack 1 rest;
1577 pred = lift_predicate 1 pb.pred pb.tomatch;
1578 history = pop_history_pattern pb.history;
1579 mat = List.map (push_alias_eqn ~hypnaming sigma alias) pb.mat } in
1580 let used, sigma, j = compile sigma pb in
1581 used, sigma, { uj_val =
1582 if isRel sigma c || isVar sigma c || count_occurrences sigma (mkRel 1) j.uj_val <= 1 then
1583 subst1 c j.uj_val
1584 else
1585 mkLetIn (make_annot na r,c,t,j.uj_val);
1586 uj_type = subst1 c j.uj_type } in
1587 (* spiwack: when an alias appears on a deep branch, its non-expanded
1588 form is automatically a variable of the same name. We avoid
1589 introducing such superfluous aliases so that refines are elegant. *)
1590 let just_pop sigma =
1591 let pb =
1592 { pb with
1593 tomatch = rest;
1594 history = pop_history_pattern pb.history;
1595 mat = List.map drop_alias_eqn pb.mat } in
1596 compile sigma pb
1597 in
1598 (* If the "match" was originally over a variable, as in "match x with
1599 O => true | n => n end", we give preference to non-expansion in
1600 the default clause (i.e. "match x with O => true | n => n end"
1601 rather than "match x with O => true | S p => S p end";
1602 computationally, this avoids reallocating constructors in cbv
1603 evaluation; the drawback is that it might duplicate the instances
1604 of the term to match when the corresponding variable is
1605 substituted by a non-evaluated expression *)
1606 if not program_mode && (isRel sigma orig || isVar sigma orig) then
1607 (* Try to compile first using non expanded alias *)
1608 try
1609 if initial then f orig (Retyping.get_type_of !!(pb.env) sigma orig)
1610 else just_pop sigma
1611 with e when precatchable_exception e ->
1612 (* Try then to compile using expanded alias *)
1613 (* Could be needed in case of dependent return clause *)
1614 f expanded expanded_typ
1615 else
1616 (* Try to compile first using expanded alias *)
1617 try f expanded expanded_typ
1618 with e when precatchable_exception e ->
1619 (* Try then to compile using non expanded alias *)
1620 (* Could be needed in case of a recursive call which requires to
1621 be on a variable for size reasons *)
1622 if initial then f orig (Retyping.get_type_of !!(pb.env) sigma orig)
1623 else just_pop sigma
1624
1625
1626 (* Remember that a non-trivial pattern has been consumed *)
1627 and compile_non_dep_alias sigma pb rest =
1628 let pb =
1629 { pb with
1630 tomatch = rest;
1631 history = pop_history_pattern pb.history;
1632 mat = List.map drop_alias_eqn pb.mat } in
1633 compile sigma pb
1634 in
1635 compile sigma pb
1636
1637 (* pour les alias des initiaux, enrichir les env de ce qu'il faut et
1638 substituer après par les initiaux *)
1639
1640 (**************************************************************************)
1641 (* Preparation of the pattern-matching problem *)
1642
1643 (* builds the matrix of equations testing that each eqn has n patterns
1644 * and linearizing the _ patterns.
1645 * Syntactic correctness has already been done in constrintern *)
1646 let matx_of_eqns env eqns =
1647 let build_eqn i {CAst.loc;v=(ids,initial_lpat,initial_rhs)} =
1648 let avoid = ids_of_named_context_val (named_context_val !!env) in
1649 let avoid = List.fold_left (fun accu id -> Id.Set.add id accu) avoid ids in
1650 let rhs =
1651 { rhs_env = env;
1652 rhs_vars = free_glob_vars initial_rhs;
1653 avoid_ids = avoid;
1654 it = Some initial_rhs } in
1655 { patterns = initial_lpat;
1656 alias_stack = [];
1657 eqn_loc = loc;
1658 orig = Some i;
1659 catch_all_vars = [];
1660 rhs = rhs }
1661 in List.map_i build_eqn 0 eqns
1662
1663 (***************** Building an inversion predicate ************************)
1664
1665 (* Let "match t1 in I1 u11..u1n_1 ... tm in Im um1..umn_m with ... end : T"
1666 be a pattern-matching problem. We assume that each uij can be
1667 decomposed under the form pij(vij1..vijq_ij) where pij(aij1..aijq_ij)
1668 is a pattern depending on some variables aijk and the vijk are
1669 instances of these variables. We also assume that each ti has the
1670 form of a pattern qi(wi1..wiq_i) where qi(bi1..biq_i) is a pattern
1671 depending on some variables bik and the wik are instances of these
1672 variables (in practice, there is no reason that ti is already
1673 constructed and the qi will be degenerated).
1674
1675 We then look for a type U(..a1jk..b1 .. ..amjk..bm) so that
1676 T = U(..v1jk..t1 .. ..vmjk..tm). This a higher-order matching
1677 problem with a priori different solutions (one of them if T itself!).
1678
1679 We finally invert the uij and the ti and build the return clause
1680
1681 phi(x11..x1n_1y1..xm1..xmn_mym) =
1682 match x11..x1n_1 y1 .. xm1..xmn_m ym with
1683 | p11..p1n_1 q1 .. pm1..pmn_m qm => U(..a1jk..b1 .. ..amjk..bm)
1684 | _ .. _ _ .. _ .. _ _ => True
1685 end
1686
1687 so that "phi(u11..u1n_1t1..um1..umn_mtm) = T" (note that the clause
1688 returning True never happens and any inhabited type can be put instead).
1689 *)
1690
1691 let adjust_to_extended_env_and_remove_deps env extenv sigma subst t =
1692 let n = Context.Rel.length (rel_context !!env) in
1693 let n' = Context.Rel.length (rel_context !!extenv) in
1694 (* We first remove the bindings that are dependently typed (they are
1695 difficult to manage and it is not sure these are so useful in practice);
1696 Notes:
1697 - [subst] is made of pairs [(id,u)] where id is a name in [extenv] and
1698 [u] a term typed in [env];
1699 - [subst0] is made of items [(p,u,(u,ty))] where [ty] is the type of [u]
1700 and both are adjusted to [extenv] while [p] is the index of [id] in
1701 [extenv] (after expansion of the aliases) *)
1702 let map (x, u) =
1703 (* d1 ... dn dn+1 ... dn'-p+1 ... dn' *)
1704 (* \--env-/ (= x:ty) *)
1705 (* \--------------extenv------------/ *)
1706 let (p, _, _) = lookup_rel_id x (rel_context !!extenv) in
1707 let rec traverse_local_defs p =
1708 match lookup_rel p !!extenv with
1709 | LocalDef (_,c,_) -> assert (isRel sigma c); traverse_local_defs (p + destRel sigma c)
1710 | LocalAssum _ -> p in
1711 let p = traverse_local_defs p in
1712 let u = lift (n' - n) u in
1713 try Some (p, u, expand_vars_in_term !!extenv sigma u)
1714 (* pedrot: does this really happen to raise [Failure _]? *)
1715 with Failure _ -> None in
1716 let subst0 = List.map_filter map subst in
1717 let t0 = lift (n' - n) t in
1718 (subst0, t0)
1719
1720 let push_binder sigma d (k,env,subst) =
1721 let hypnaming = VarSet.variables (Global.env ()) in
1722 (k+1,snd (push_rel ~hypnaming sigma d env),List.map (fun (na,u,d) -> (na,lift 1 u,d)) subst)
1723
1724 let rec list_assoc_in_triple x = function
1725 [] -> raise Not_found
1726 | (a, b, _)::l -> if Int.equal a x then b else list_assoc_in_triple x l
1727
1728 (* Let vijk and ti be a set of dependent terms and T a type, all
1729 * defined in some environment env. The vijk and ti are supposed to be
1730 * instances for variables aijk and bi.
1731 *
1732 * [abstract_tycon Gamma0 Sigma subst T Gamma] looks for U(..v1jk..t1 .. ..vmjk..tm)
1733 * defined in some extended context
1734 * "Gamma0, ..a1jk:V1jk.. b1:W1 .. ..amjk:Vmjk.. bm:Wm"
1735 * such that env |- T = U(..v1jk..t1 .. ..vmjk..tm). To not commit to
1736 * a particular solution, we replace each subterm t in T that unifies with
1737 * a subset u1..ul of the vijk and ti by a special evar
1738 * ?id(x=t;c1:=c1,..,cl=cl) defined in context Gamma0,x,c1,...,cl |- ?id
1739 * (where the c1..cl are the aijk and bi matching the u1..ul), and
1740 * similarly for each ti.
1741 *)
1742
1743 let abstract_tycon ?loc env sigma subst tycon extenv t =
1744 let t = nf_betaiota !!env sigma t in (* it helps in some cases to remove K-redex*)
1745 let src = match EConstr.kind sigma t with
1746 | Evar (evk,_) -> (Loc.tag ?loc @@ Evar_kinds.SubEvar (None,evk))
1747 | _ -> (Loc.tag ?loc @@ Evar_kinds.CasesType true) in
1748 let subst0,t0 = adjust_to_extended_env_and_remove_deps env extenv sigma subst t in
1749 (* We traverse the type T of the original problem Xi looking for subterms
1750 that match the non-constructor part of the constraints (this part
1751 is in subst); these subterms are the "good" subterms and we replace them
1752 by an evar that may depend (and only depend) on the corresponding
1753 convertible subterms of the substitution *)
1754 let evdref = ref sigma in
1755 let rec aux (k,env,subst as x) t =
1756 (* Use a reference because the [map_constr_with_full_binders] does not
1757 allow threading a state. *)
1758 let sigma = !evdref in
1759 match EConstr.kind sigma t with
1760 | Rel n when is_local_def (lookup_rel n !!env) -> t
1761 | Evar ev ->
1762 let ty = get_type_of !!env sigma t in
1763 let sigma, ty = refresh_universes (Some false) !!env sigma ty in
1764 let inst =
1765 List.map_i
1766 (fun i _ ->
1767 try list_assoc_in_triple i subst0 with Not_found -> mkRel i)
1768 1 (rel_context !!env) in
1769 let sigma, ev' = Evarutil.new_evar ~src ~typeclass_candidate:false !!env sigma ty in
1770 begin
1771 let flags = (default_flags_of TransparentState.full) in
1772 match solve_simple_eqn evar_unify flags !!env sigma (None,ev,substl inst ev') with
1773 | Success evd -> evdref := evd
1774 | UnifFailure _ -> evdref := add_conv_pb (Conversion.CONV,!!env,substl inst ev',t) sigma
1775 end;
1776 ev'
1777 | _ ->
1778 let good = List.filter (fun (_,u,_) -> is_conv_leq !!env sigma t u) subst in
1779 match good with
1780 | [] ->
1781 map_constr_with_full_binders !!env sigma (push_binder sigma) aux x t
1782 | (_, _, u) :: _ -> (* u is in extenv *)
1783 let vl = List.map pi1 good in
1784 let ty =
1785 let ty = get_type_of !!env sigma t in
1786 let sigma, res = refresh_universes (Some false) !!env !evdref ty in
1787 evdref := sigma; res
1788 in
1789 let dummy_subst = List.init k (fun _ -> mkProp) in
1790 let ty = substl dummy_subst (aux x ty) in
1791 let sigma = !evdref in
1792 let depvl = free_rels sigma ty in
1793 let inst =
1794 List.map_i
1795 (fun i _ -> if Int.List.mem i vl then u else mkRel i) 1
1796 (rel_context !!extenv) in
1797 let map a = match EConstr.kind sigma a with
1798 | Rel n -> not (noccurn sigma n u) || Int.Set.mem n depvl
1799 | _ -> true
1800 in
1801 let rel_filter = List.map map inst in
1802 let named_filter =
1803 List.map (fun d -> local_occur_var sigma (NamedDecl.get_id d) u)
1804 (named_context !!extenv) in
1805 let filter = Filter.make (rel_filter @ named_filter) in
1806 let candidates = List.rev (u :: List.map mkRel vl) in
1807 let sigma, ev = Evarutil.new_evar !!extenv ~src ~filter ~candidates ~typeclass_candidate:false sigma ty in
1808 let () = evdref := sigma in
1809 lift k ev
1810 in
1811 let ans = aux (0,extenv,subst0) t0 in
1812 !evdref, ans
1813
1814 let build_tycon ?loc env tycon_env s subst tycon extenv sigma t =
1815 let s = mkSort s in
1816 match t with
1817 | None ->
1818 (* This is the situation we are building a return predicate and
1819 we are in an impossible branch *)
1820 let n = Context.Rel.length (rel_context !!env) in
1821 let n' = Context.Rel.length (rel_context !!tycon_env) in
1822 let src = Loc.tag ?loc Evar_kinds.ImpossibleCase in
1823 let sigma, impossible_case_type =
1824 Evarutil.new_evar (reset_context !!env) sigma ~src ~typeclass_candidate:false s in
1825 (sigma, { uj_val = lift (n'-n) impossible_case_type; uj_type = s })
1826 | Some t ->
1827 let sigma, t = abstract_tycon ?loc tycon_env sigma subst tycon extenv t in
1828 let sigma, tt = Typing.type_of !!extenv sigma t in
1829 match unify_leq_delay !!env sigma tt s with
1830 | exception Evarconv.UnableToUnify _ -> anomaly (Pp.str "Build_tycon: should be a type.");
1831 | sigma -> (sigma, { uj_val = t; uj_type = tt })
1832
1833
1834 (* For a multiple pattern-matching problem Xi on t1..tn with return
1835 * type T, [build_inversion_problem Gamma Sigma (t1..tn) T] builds a return
1836 * predicate for Xi that is itself made by an auxiliary
1837 * pattern-matching problem of which the first clause reveals the
1838 * pattern structure of the constraints on the inductive types of the t1..tn,
1839 * and the second clause is a wildcard clause for catching the
1840 * impossible cases. See above "Building an inversion predicate" for
1841 * further explanations
1842 *)
1843
1844 let build_inversion_problem ~program_mode loc env sigma tms t =
1845 let hypnaming = VarSet.variables (Global.env ()) in
1846 let make_patvar t (subst,avoid) =
1847 let id = next_name_away (named_hd !!env sigma t Anonymous) avoid in
1848 DAst.make @@ PatVar (Name id), ((id,t)::subst, Id.Set.add id avoid) in
1849 let rec reveal_pattern t (subst,avoid as acc) =
1850 match EConstr.kind sigma (whd_all !!env sigma t) with
1851 | Construct (cstr,u) -> DAst.make (PatCstr (cstr,[],Anonymous)), acc
1852 | App (f,v) when isConstruct sigma f ->
1853 let cstr,u = destConstruct sigma f in
1854 let n = constructor_nrealargs !!env cstr in
1855 let l = List.lastn n (Array.to_list v) in
1856 let l,acc = List.fold_right_map reveal_pattern l acc in
1857 DAst.make (PatCstr (cstr,l,Anonymous)), acc
1858 | _ -> make_patvar t acc in
1859 let rec aux n env acc_sign tms acc =
1860 match tms with
1861 | [] -> [], acc_sign, acc
1862 | (t, IsInd (_,IndType(indf,realargs),_)) :: tms ->
1863 let patl,acc = List.fold_right_map reveal_pattern realargs acc in
1864 let pat,acc = make_patvar t acc in
1865 let indf' = lift_inductive_family n indf in
1866 let sign = make_arity_signature !!env sigma true indf' in
1867 let patl = pat :: List.rev patl in
1868 let patl,sign = recover_and_adjust_alias_names acc patl sign in
1869 let p = List.length patl in
1870 let _,env' = push_rel_context ~hypnaming sigma sign env in
1871 let patl',acc_sign,acc = aux (n+p) env' (sign@acc_sign) tms acc in
1872 List.rev_append patl patl',acc_sign,acc
1873 | (t, NotInd (bo,typ)) :: tms ->
1874 let pat,acc = make_patvar t acc in
1875 let typ = lift n typ in
1876 let d = LocalAssum (annotR (alias_of_pat pat),typ) in
1877 let patl,acc_sign,acc = aux (n+1) (snd (push_rel ~hypnaming sigma d env)) (d::acc_sign) tms acc in
1878 pat::patl,acc_sign,acc in
1879 let avoid0 = GlobEnv.vars_of_env env in
1880 (* [patl] is a list of patterns revealing the substructure of
1881 constructors present in the constraints on the type of the
1882 multiple terms t1..tn that are matched in the original problem;
1883 [subst] is the substitution of the free pattern variables in
1884 [patl] that returns the non-constructor parts of the constraints.
1885 Especially, if the ti has type I ui1..uin_i, and the patterns associated
1886 to ti are pi1..pin_i, then subst(pij) is uij; the substitution is
1887 useful to recognize which subterms of the whole type T of the original
1888 problem have to be abstracted *)
1889 let patl,sign,(subst,avoid) = aux 0 env [] tms ([],avoid0) in
1890 let n = List.length sign in
1891
1892 let decls =
1893 List.map_i (fun i d -> (mkRel i, map_constr (lift i) d)) 1 sign in
1894
1895 let _,pb_env = push_rel_context ~hypnaming sigma sign env in
1896 let decls =
1897 List.map (fun (c,d) -> (c,extract_inductive_data !!(pb_env) sigma d,d)) decls in
1898
1899 let decls = List.rev decls in
1900 let dep_sign = find_dependencies_signature sigma (List.make n true) decls in
1901
1902 let sub_tms =
1903 List.map2 (fun deps (tm, (tmtyp,_), decl) ->
1904 let na = if List.is_empty deps then Anonymous else force_name (RelDecl.get_name decl) in
1905 Pushed (true,((tm,tmtyp),deps,na)))
1906 dep_sign decls in
1907 let subst = List.map (fun (na,t) -> (na,lift n t)) subst in
1908 (* [main_eqn] is the main clause of the auxiliary pattern-matching that
1909 serves as skeleton for the return type: [patl] is the
1910 substructure of constructors extracted from the list of
1911 constraints on the inductive types of the multiple terms matched
1912 in the original pattern-matching problem Xi *)
1913 let main_eqn =
1914 { patterns = patl;
1915 alias_stack = [];
1916 eqn_loc = None;
1917 orig = None;
1918 catch_all_vars = [];
1919 rhs = { rhs_env = pb_env;
1920 (* we assume all vars are used; in practice we discard dependent
1921 vars so that the field rhs_vars is normally not used *)
1922 rhs_vars = List.fold_left (fun accu (id, _) -> Id.Set.add id accu) Id.Set.empty subst;
1923 avoid_ids = avoid;
1924 it = Some (lift n t) } } in
1925 (* [catch_all] is a catch-all default clause of the auxiliary
1926 pattern-matching, if needed: it will catch the clauses
1927 of the original pattern-matching problem Xi whose type
1928 constraints are incompatible with the constraints on the
1929 inductive types of the multiple terms matched in Xi *)
1930 let catch_all_eqn =
1931 if List.for_all (irrefutable !!env) patl then
1932 (* No need for a catch all clause *)
1933 []
1934 else
1935 [ { patterns = List.map (fun _ -> DAst.make @@ PatVar Anonymous) patl;
1936 alias_stack = [];
1937 eqn_loc = None;
1938 orig = None;
1939 catch_all_vars = [];
1940 rhs = { rhs_env = pb_env;
1941 rhs_vars = Id.Set.empty;
1942 avoid_ids = avoid0;
1943 it = None } } ] in
1944 (* [pb] is the auxiliary pattern-matching serving as skeleton for the
1945 return type of the original problem Xi *)
1946 let s = Retyping.get_sort_of !!env sigma t in
1947 let sigma, s = Sorts.(match ESorts.kind sigma s with
1948 | SProp | Prop | Set ->
1949 (* To anticipate a possible restriction on an elimination from
1950 SProp, Prop or (impredicative) Set we preserve the sort of the
1951 main branch, knowing that the default impossible case shall
1952 always be coercible to one of those *)
1953 sigma, s
1954 | Type _ | QSort _ ->
1955 (* If the sort has algebraic universes, we cannot use this sort a
1956 type constraint for the impossible case; especially if the
1957 default case is not the canonical one provided in Prop by Rocq
1958 but one given by the user, which may be in either sort (an
1959 example is in Vector.caseS', even if this one can probably be
1960 put in Prop too with some care) *)
1961 let sigma, s' = Evd.new_sort_variable univ_flexible sigma in
1962 let sigma = Evd.set_leq_sort sigma s s' in
1963 sigma, s') in
1964 let pb =
1965 { env = pb_env;
1966 pred = (*ty *) mkSort s;
1967 tomatch = sub_tms;
1968 history = start_history n;
1969 mat = main_eqn :: catch_all_eqn;
1970 caseloc = loc;
1971 casestyle = RegularStyle;
1972 typing_function = build_tycon ?loc env pb_env s subst} in
1973 let _used, sigma, j = compile ~program_mode sigma pb in
1974 (sigma, j.uj_val)
1975
1976 (* Here, [pred] is assumed to be in the context built from all *)
1977 (* realargs and terms to match *)
1978 let build_initial_predicate arsign pred =
1979 let rec buildrec pred tmnames = function
1980 | [] -> List.rev tmnames,pred
1981 | (decl::realdecls)::lnames ->
1982 let na = RelDecl.get_name decl in
1983 let realnames = List.map RelDecl.get_name realdecls in
1984 buildrec pred ((force_name na,realnames)::tmnames) lnames
1985 | _ -> assert false
1986 in buildrec pred [] (List.rev arsign)
1987
1988 let extract_arity_signature ?(dolift=true) env0 tomatchl tmsign =
1989 let lift = if dolift then lift else fun n t -> t in
1990 let get_one_sign n tm (na,t) =
1991 match tm with
1992 | NotInd (bo,typ) ->
1993 (match t with
1994 | None ->
1995 let r = ERelevance.relevant in (* TODO relevance *)
1996 let sign = match bo with
1997 | None -> [LocalAssum (make_annot na r, lift n typ)]
1998 | Some b -> [LocalDef (make_annot na r, lift n b, lift n typ)] in sign
1999 | Some {CAst.loc} ->
2000 user_err ?loc
2001 (str"Unexpected type annotation for a term of non inductive type."))
2002 | IsInd (term,IndType(indf,realargs),_) ->
2003 let indf' = if dolift then lift_inductive_family n indf else indf in
2004 let ((ind,_ as indu),_) = dest_ind_family indf' in
2005 let nrealargs_ctxt = inductive_nrealdecls env0 ind in
2006 let arsign = get_arity env0 indf' in
2007 let realnal =
2008 match t with
2009 | Some {CAst.loc;v=(ind',realnal)} ->
2010 if not (QInd.equal env0 ind ind') then
2011 user_err ?loc (str "Wrong inductive type.");
2012 if not (Int.equal nrealargs_ctxt (List.length realnal)) then
2013 anomaly (Pp.str "Ill-formed 'in' clause in cases.");
2014 List.rev realnal
2015 | None ->
2016 List.make nrealargs_ctxt Anonymous in
2017 let r = Inductiveops.relevance_of_inductive env0 indu in
2018 let t = build_dependent_inductive env0 indf' in
2019 LocalAssum (make_annot na r, t) :: List.map2 RelDecl.set_name realnal arsign in
2020 let rec buildrec n = function
2021 | [],[] -> []
2022 | (_,tm)::ltm, (_,x)::tmsign ->
2023 let l = get_one_sign n tm x in
2024 l :: buildrec (n + List.length l) (ltm,tmsign)
2025 | _ -> assert false
2026 in List.rev (buildrec 0 (tomatchl,tmsign))
2027
2028 let inh_conv_coerce_to_tycon ?loc ~program_mode env sigma j tycon =
2029 match tycon with
2030 | Some p ->
2031 let (evd,v,_trace) =
2032 Coercion.inh_conv_coerce_to ?loc ~program_mode ~resolve_tc:true env sigma
2033 ~flags:(default_flags_of TransparentState.full) j p
2034 in
2035 (evd,v)
2036 | None -> sigma, j
2037
2038 (* We put the tycon inside the arity signature, possibly discovering dependencies. *)
2039
2040 let add_subst sigma c len (rel_subst,var_subst) =
2041 match EConstr.kind sigma c with
2042 | Rel n -> (n,len) :: rel_subst, var_subst
2043 | Var id -> rel_subst, (id,len) :: var_subst
2044 | _ -> assert false
2045
2046 let dependent_rel_or_var sigma tm c =
2047 match EConstr.kind sigma tm with
2048 | Rel n -> not (noccurn sigma n c)
2049 | Var id -> Termops.local_occur_var sigma id c
2050 | _ -> assert false
2051
2052 let prepare_predicate_from_arsign_tycon ~program_mode env sigma loc tomatchs arsign c =
2053 let nar = List.fold_left (fun n sign -> Context.Rel.nhyps sign + n) 0 arsign in
2054 let (rel_subst,var_subst), len =
2055 List.fold_right2 (fun (tm, tmtype) sign (subst, len) ->
2056 let signlen = Context.Rel.nhyps sign in
2057 match EConstr.kind sigma tm with
2058 | Rel _ | Var _ when Int.equal signlen 1 && dependent_rel_or_var sigma tm c
2059 (* The term to match is not of a dependent type itself *) ->
2060 (add_subst sigma tm len subst, len - signlen)
2061 | Rel _ | Var _ when signlen > 1 (* The term is of a dependent type,
2062 maybe some variable in its type appears in the tycon. *) ->
2063 (match tmtype with
2064 NotInd _ -> (subst, len - signlen)
2065 | IsInd (_, IndType(indf,realargs),_) ->
2066 let subst, len =
2067 List.fold_left
2068 (fun (subst, len) arg ->
2069 match EConstr.kind sigma arg with
2070 | Rel _ | Var _ when dependent_rel_or_var sigma arg c ->
2071 (add_subst sigma arg len subst, pred len)
2072 | _ -> (subst, pred len))
2073 (subst, len) realargs
2074 in
2075 let subst =
2076 if dependent_rel_or_var sigma tm c && List.for_all (fun c -> isRel sigma c || isVar sigma c) realargs
2077 then add_subst sigma tm len subst else subst
2078 in (subst, pred len))
2079 | _ -> (subst, len - signlen))
2080 (List.rev tomatchs) arsign (([],[]), nar)
2081 in
2082 let rec predicate lift c =
2083 match EConstr.kind sigma c with
2084 | Rel n when n > lift ->
2085 (try
2086 (* Make the predicate dependent on the matched variable *)
2087 let idx = Int.List.assoc (n - lift) rel_subst in
2088 mkRel (idx + lift)
2089 with Not_found ->
2090 (* A variable that is not matched, lift over the arsign *)
2091 mkRel (n + nar))
2092 | Var id ->
2093 (try
2094 (* Make the predicate dependent on the matched variable *)
2095 let idx = Id.List.assoc id var_subst in
2096 mkRel (idx + lift)
2097 with Not_found ->
2098 (* A variable that is not matched *)
2099 c)
2100 | _ ->
2101 EConstr.map_with_binders sigma succ predicate lift c
2102 in
2103 assert (len == 0);
2104 let p = predicate 0 c in
2105 let hypnaming = VarSet.variables (Global.env ()) in
2106 let arsign,env' = List.fold_right_map (push_rel_context ~hypnaming sigma) arsign env in
2107 try let sigma' = fst (Typing.type_of !!env' sigma p) in
2108 Some (sigma', p, arsign)
2109 with e when precatchable_exception e -> None
2110
2111 let expected_elimination_sorts env sigma tomatchl =
2112 List.map_filter (fun (_,tm) -> match tm with
2113 | NotInd _ -> None
2114 | IsInd (_,IndType(indf,_),_) ->
2115 let (ind, u), _ = dest_ind_family indf in
2116 Inductiveops.is_squashed sigma (Inductive.lookup_mind_specif env ind, u))
2117 tomatchl
2118
2119 (* Builds the predicate. If the predicate is dependent, its context is
2120 * made of 1+nrealargs assumptions for each matched term in an inductive
2121 * type and 1 assumption for each term not _syntactically_ in an
2122 * inductive type.
2123
2124 * Each matched term is independently considered dependent or not.
2125 *)
2126
2127 let prepare_predicate ?loc ~program_mode typing_fun env sigma tomatchs arsign tycon pred =
2128 let refresh_tycon sigma t =
2129 (* If we put the typing constraint in the term, it has to be
2130 refreshed to preserve the invariant that no algebraic universe
2131 can appear in the term. *)
2132 refresh_universes ~status:Evd.univ_flexible ~onlyalg:true (Some true)
2133 !!env sigma t
2134 in
2135 let preds =
2136 match pred with
2137 (* No return clause *)
2138 | None ->
2139 let sigma,t =
2140 match tycon with
2141 | Some t -> refresh_tycon sigma t
2142 | None ->
2143 (* No type constraint: we first create a generic evar type constraint *)
2144 let src = (loc, Evar_kinds.CasesType false) in
2145 let sigma, (t, _) = Evarutil.new_type_evar !!env sigma univ_flexible ~src in
2146 sigma, t in
2147 (* First strategy: we build an "inversion" predicate, also replacing the *)
2148 (* dependencies with existential variables *)
2149 let sigma1,pred1 = build_inversion_problem loc ~program_mode env sigma tomatchs t in
2150 (* Optional second strategy: we abstract the tycon wrt to the dependencies *)
2151 let p2 =
2152 prepare_predicate_from_arsign_tycon ~program_mode env sigma loc tomatchs arsign t in
2153 (* Third strategy: we take the type constraint as it is; of course we could *)
2154 (* need something in between, abstracting some but not all of the dependencies *)
2155 (* the "inversion" strategy deals with that but unification may not be *)
2156 (* powerful enough so strategy 2 and 3 helps; moreover, inverting does not *)
2157 (* work (yet) when a constructor has a type not precise enough for the inversion *)
2158 (* see log message for details *)
2159 let pred3 = lift (List.length (List.flatten arsign)) t in
2160 (match p2 with
2161 | Some (sigma2,pred2,arsign) when not (EConstr.eq_constr sigma pred2 pred3) ->
2162 [sigma1, pred1, arsign; sigma2, pred2, arsign; sigma, pred3, arsign]
2163 | _ ->
2164 [sigma1, pred1, arsign; sigma, pred3, arsign])
2165 (* Some type annotation *)
2166 | Some rtntyp ->
2167 (* We extract the signature of the arity *)
2168 let hypnaming = VarSet.variables (Global.env ()) in
2169 let building_arsign,envar = List.fold_right_map (push_rel_context ~hypnaming sigma) arsign env in
2170 let sigma, rtnsort = Evd.new_sort_variable univ_flexible sigma in
2171 let sigma, predcclj = typing_fun (Some (mkSort rtnsort)) envar sigma rtntyp in
2172 let check_elim_sort sigma squash =
2173 try Inductiveops.squash_elim_sort sigma squash rtnsort
2174 with QGraph.EliminationError _ | UGraph.UniverseInconsistency _ ->
2175 (* Incompatible constraints are ignored and handled later
2176 when typing the pattern-matching. *)
2177 sigma
2178 in
2179 let sigma = List.fold_left check_elim_sort sigma
2180 (expected_elimination_sorts !!env sigma tomatchs)
2181 in
2182 let predccl = nf_evar sigma predcclj.uj_val in
2183 [sigma, predccl, building_arsign]
2184 in
2185 List.map
2186 (fun (sigma,pred,arsign) ->
2187 let (nal,pred) = build_initial_predicate arsign pred in
2188 sigma,nal,pred)
2189 preds
2190
2191 (** Program cases *)
2192
2193 open Program
2194
2195 let ($) f x = f x
2196
2197 let string_of_name name =
2198 match name with
2199 | Anonymous -> "anonymous"
2200 | Name n -> Id.to_string n
2201
2202 let make_prime_id name =
2203 let str = string_of_name name in
2204 Id.of_string str, Id.of_string (str ^ "'")
2205
2206 let prime avoid name =
2207 let previd, id = make_prime_id name in
2208 previd, next_ident_away id avoid
2209
2210 let make_prime avoid prevname =
2211 let previd, id = prime !avoid prevname in
2212 avoid := Id.Set.add id !avoid;
2213 previd, id
2214
2215 let eq_id avoid id =
2216 let hid = Id.of_string ("Heq_" ^ Id.to_string id) in
2217 let hid' = next_ident_away hid avoid in
2218 hid'
2219
2220 let mk_eq env sigma typ x y = papp env sigma coq_eq_ind [| typ; x ; y |]
2221 let mk_eq_refl env sigma typ x = papp env sigma coq_eq_refl [| typ; x |]
2222 let mk_JMeq env sigma typ x typ' y =
2223 papp env sigma coq_JMeq_ind [| typ; x ; typ'; y |]
2224 let mk_JMeq_refl env sigma typ x =
2225 papp env sigma coq_JMeq_refl [| typ; x |]
2226
2227 let hole na = DAst.make @@
2228 GHole (GQuestionMark {
2229 Evar_kinds.qm_obligation= Evar_kinds.Define false;
2230 Evar_kinds.qm_name=na;
2231 Evar_kinds.qm_record_field=None})
2232
2233 let constr_of_pat env sigma arsign pat avoid =
2234 let rec typ env sigma decl realdecls pat avoid =
2235 let loc = pat.CAst.loc in
2236 let ty = RelDecl.get_type decl in
2237 match DAst.get pat with
2238 | PatVar name ->
2239 let name, avoid = match name with
2240 Name n -> name, avoid
2241 | Anonymous ->
2242 let id = next_ident_away wildcard_id avoid in
2243 Name id, Id.Set.add id avoid
2244 in
2245 let realargs = List.map (map_name (fun _ -> Anonymous)) realdecls in (* Hack to force their instantiation as evars *)
2246 (sigma, (DAst.make ?loc @@ PatVar name), [Rel.Declaration.set_name name decl] @ realargs, mkRel 1, lift 1 ty,
2247 List.rev (rel_list 1 (List.length realargs)), 1, avoid)
2248 | PatCstr (((_, i) as cstr),patargs,alias) ->
2249 let cind = inductive_of_constructor cstr in
2250 let IndType (indf, _) =
2251 try find_rectype env sigma (lift (-(List.length realdecls)) ty)
2252 with Not_found -> error_case_not_inductive env sigma
2253 {uj_val = ty; uj_type = Retyping.get_type_of env sigma ty}
2254 in
2255 let (ind,u), params = dest_ind_family indf in
2256 if not (QInd.equal env ind cind) then error_bad_constructor ?loc env cstr ind;
2257 let cstrs = get_constructors env indf in
2258 let ci = cstrs.(i-1) in
2259 let nb_args_constr = ci.cs_nargs in
2260 assert (Int.equal nb_args_constr (List.length patargs));
2261 let sigma, patargs, args, _, sign, env, n, m, avoid =
2262 List.fold_right2
2263 (fun decl pat (sigma, patargs, args, pats_c, sign, env, n, m, avoid) ->
2264 let sigma, patarg', sign', pat_c', typ', argtypargs, n', avoid =
2265 let decl = Rel.Declaration.map_constr (fun c -> substl pats_c (liftn (List.length sign) (succ (List.length pats_c)) c)) decl in
2266 typ env sigma decl [] pat avoid
2267 in
2268 let args = match decl with
2269 | LocalAssum _ -> pat_c' :: List.map (lift n') args
2270 | LocalDef _ -> List.map (lift n') args in
2271 let pats_c = pat_c' :: List.map (lift n') pats_c in
2272 let env' = EConstr.push_rel_context sign' env in
2273 (sigma, patarg' :: patargs, args, pats_c, sign' @ sign, env', n' + n, succ m, avoid))
2274 ci.cs_args (List.rev patargs) (sigma, [], [], [], [], env, 0, 0, avoid)
2275 in
2276 let args = List.rev args in
2277 let patargs = List.rev patargs in
2278 let pat' = DAst.make ?loc @@ PatCstr (cstr, patargs, alias) in
2279 let cstr = mkConstructU ci.cs_cstr in
2280 let app = applist (cstr, List.map (lift (List.length sign)) params) in
2281 let app = applist (app, args) in
2282 let apptype = Retyping.get_type_of env sigma app in
2283 let IndType (indf, realargs) as ind = find_rectype env sigma apptype in
2284 let subst = Vars.subst_of_rel_context_instance_list realdecls realargs in
2285 let apptype = mkAppliedInd ind (* this absorbs trailing let-ins *) in
2286 match alias with
2287 Anonymous ->
2288 sigma, pat', sign, app, apptype, subst, n, avoid
2289 | Name id ->
2290 let r = Inductiveops.relevance_of_inductive_family env indf in
2291 let sign = LocalAssum (make_annot alias r, lift m ty) :: sign in
2292 let avoid = Id.Set.add id avoid in
2293 let sigma, sign, i, avoid =
2294 try
2295 let env = EConstr.push_rel_context sign env in
2296 let sigma = unify_leq_delay (EConstr.push_rel_context sign env) sigma
2297 (lift (succ m) ty) (lift 1 apptype) in
2298 let sigma, eq_t = mk_eq env sigma (lift (succ m) ty)
2299 (mkRel 1) (* alias *)
2300 (lift 1 app) (* aliased term *)
2301 in
2302 let neq = eq_id avoid id in
2303 (* if we ever allow using a SProp-typed coq_eq_ind this relevance will be wrong *)
2304 sigma, LocalDef (nameR neq, mkRel 0, eq_t) :: sign, 2, Id.Set.add neq avoid
2305 with Evarconv.UnableToUnify _ -> sigma, sign, 1, avoid
2306 in
2307 (* Mark the equality as a hole *)
2308 sigma, pat', sign, lift i app, lift i apptype, subst, n + i, avoid
2309 in
2310 let sigma, pat', sign, patc, patty, args, z, avoid = typ env sigma (List.hd arsign) (List.tl arsign) pat avoid in
2311 sigma, pat', (sign, patc, (patty, args), pat'), avoid
2312
2313
2314 (* shadows functional version *)
2315 let eq_id avoid id =
2316 let hid = Id.of_string ("Heq_" ^ Id.to_string id) in
2317 let hid' = next_ident_away hid !avoid in
2318 avoid := Id.Set.add hid' !avoid;
2319 hid'
2320
2321 let is_topvar sigma t =
2322 match EConstr.kind sigma t with
2323 | Rel 0 -> true
2324 | _ -> false
2325
2326 let rels_of_patsign sigma =
2327 List.map (fun decl ->
2328 match decl with
2329 | LocalDef (na,t',t) when is_topvar sigma t' -> LocalAssum (na,t)
2330 | _ -> decl)
2331
2332 let vars_of_ctx sigma ctx =
2333 let _, y =
2334 List.fold_right (fun decl (prev, vars) ->
2335 match decl with
2336 | LocalDef (na,t',t) when is_topvar sigma t' ->
2337 prev,
2338 (DAst.make @@ GApp (
2339 (DAst.make @@ GRef (delayed_force coq_eq_refl_ref, None)),
2340 [hole na.binder_name; DAst.make @@ GVar prev])) :: vars
2341 | LocalDef _ -> prev, vars
2342 | LocalAssum _ ->
2343 match RelDecl.get_name decl with
2344 Anonymous -> prev, (DAst.make @@ GHole GInternalHole) :: vars (* Hack, see constr_of_pat *)
2345 | Name n -> n, (DAst.make @@ GVar n) :: vars)
2346 ctx (Id.of_string "vars_of_ctx_error", [])
2347 in List.rev y
2348
2349 let rec is_included x y =
2350 match DAst.get x, DAst.get y with
2351 | PatVar _, _ -> true
2352 | _, PatVar _ -> true
2353 | PatCstr ((_, i), args, alias), PatCstr ((_, i'), args', alias') ->
2354 if Int.equal i i' then List.for_all2 is_included args args'
2355 else false
2356
2357 (* curpat_sign_len is the current pattern's complete signature length.
2358 Hence pats is already typed in its
2359 full signature. However prevpatterns are in the original one signature per pattern form.
2360 *)
2361 let build_ineqs env sigma prevpatterns curpats curpat_sign_len =
2362 let sigma, ineqs =
2363 List.fold_left
2364 (fun (sigma, ineqs) ppats ->
2365 let sigma, acc = List.fold_left2
2366 (* ppat is the pattern we are discriminating against, curpat is the current one. *)
2367 (fun (sigma, acc) (ppat_sign, ppat_c, (ppat_ty, ppat_tyargs), ppat)
2368 (curpat_sign, curpat_c, (curpat_ty, curpat_tyargs), curpat) ->
2369 match acc with
2370 None -> sigma, None
2371 | Some (old_ppat_sign, old_ppats_len, old_eqs) -> (* FixMe: do not work with ppat_args *)
2372 (try
2373 if is_included curpat ppat then
2374 (* Length of previous pattern's signature *)
2375 let ppat_len = List.length ppat_sign in
2376 (* Accumulated length of previous pattern's signatures *)
2377 let new_ppats_len = ppat_len + old_ppats_len in
2378 let sigma, this_eq =
2379 (* We have [env, curpat_sign |- curpat_c : curpat_ty] and
2380 want [env, curpat_sign, old_sign, ppat_sign |- curpat_c : curpat_ty] *)
2381 let ppat_ty = liftn (old_ppats_len + curpat_sign_len) (succ ppat_len) ppat_ty in
2382 let ppat_c = liftn (old_ppats_len + curpat_sign_len) (succ ppat_len) ppat_c in
2383 let cur_ty = lift new_ppats_len curpat_ty in
2384 let cur_c = lift new_ppats_len curpat_c in
2385 if Reductionops.is_conv env sigma cur_ty ppat_ty then
2386 mk_eq env sigma
2387 cur_ty
2388 ppat_c
2389 cur_c
2390 else
2391 let can_we_make_sense_of_JMeq = false in
2392 if can_we_make_sense_of_JMeq then
2393 mk_JMeq env sigma
2394 ppat_ty
2395 ppat_c
2396 cur_ty
2397 cur_c
2398 else
2399 raise Exit
2400 in
2401 let acc =
2402 ((* Jump over previous prevpat signs *)
2403 lift_rel_context old_ppats_len ppat_sign @ old_ppat_sign,
2404 new_ppats_len,
2405 this_eq :: List.map (lift ppat_len (* Jump over this prevpat signature *)) old_eqs)
2406 in sigma, Some acc
2407 else sigma, None
2408 with Exit -> sigma, None))
2409 (sigma, Some ([], 0, [])) ppats curpats
2410 in match acc with
2411 None -> sigma, ineqs
2412 | Some (sign, len, eqs) ->
2413 let sigma, conj = mk_coq_and env sigma eqs in
2414 let sigma, neg = mk_coq_not env sigma conj in
2415 let ineq = it_mkProd_or_LetIn neg (lift_rel_context curpat_sign_len sign) in
2416 sigma, ineq :: ineqs)
2417 (sigma, []) prevpatterns
2418 in match ineqs with [] -> sigma, None
2419 | _ -> let sigma, conj = mk_coq_and env sigma ineqs in sigma, Some conj
2420
2421 let constrs_of_pats typing_fun env sigma eqns tomatchs sign neqs arity =
2422 let i = ref 0 in
2423 let hypnaming = VarSet.variables (Global.env ()) in
2424 let (sigma, x, y, z) =
2425 List.fold_left
2426 (fun (sigma, branches, eqns, prevpatterns) eqn ->
2427 let sigma, _, newpatterns, pats =
2428 List.fold_left2
2429 (fun (sigma, idents, newpatterns, pats) pat arsign ->
2430 let sigma, pat', cpat, idents = constr_of_pat !!env sigma arsign pat idents in
2431 (sigma, idents, pat' :: newpatterns, cpat :: pats))
2432 (sigma, Id.Set.empty, [], []) eqn.patterns (List.rev sign)
2433 in
2434 (* Below, [opats] is a list of [(sign, pat_c, (ty, args), pat)];
2435 each of [sign], [pat_c], [ty] and [args] is typed in [env] *)
2436 let newpatterns = List.rev newpatterns and opats = List.rev pats in
2437 (* Below, [pats] is a list of [(sign, pat_c, (ty, args), pat)];
2438 each of [sign], [pat_c] and [args] is typed in [env]
2439 extended with the previous [pats]; [ty] is typed in
2440 [env] extended with the type of realargs *)
2441 let rhs_rels, pats, signlen =
2442 List.fold_left
2443 (fun (renv, pats, n) (sign, pat_c, (ty, subst), pat) ->
2444 (* Recombine signatures and terms of all of the row's patterns *)
2445 let sign' = lift_rel_context n sign in
2446 let len = List.length sign' in
2447 (sign' @ renv,
2448 (* lift to get outside of previous pattern's signatures. *)
2449 (sign', liftn n (succ len) pat_c,
2450 (liftn n (succ len) ty, List.map (liftn n (succ len)) subst), pat) :: pats,
2451 len + n))
2452 ([], [], 0) opats in
2453 (* Below, [pats] is a list of [(sign, pat_c, (ty, args), pat)];
2454 each of [sign] is typed in [env] extended with the previous [sign]
2455 but [ty], [args] and [pat_c] are typed in the common context made
2456 of [env] extended with all [sign] *)
2457 let pats, _ = List.fold_left
2458 (* lift to get outside of past patterns to get terms in the combined environment. *)
2459 (fun (pats, n) (sign, pat_c, (ty, subst), pat) ->
2460 let len = List.length sign in
2461 ((rels_of_patsign sigma sign, lift n pat_c,
2462 (lift n ty, List.map (lift n) subst), pat) :: pats, len + n))
2463 ([], 0) pats
2464 in
2465 let sigma, ineqs = build_ineqs !!env sigma prevpatterns pats signlen in
2466 let rhs_rels' = rels_of_patsign sigma rhs_rels in
2467 let arity =
2468 let subst, nsubst =
2469 List.fold_right (fun (sign, pat_c, (_, subst), _) (allsubst,n) ->
2470 (allsubst @ pat_c :: subst, List.length subst + succ n))
2471 pats ([], 0)
2472 in
2473 substl subst (liftn signlen (succ nsubst) arity)
2474 in
2475 let r = ERelevance.relevant in (* TODO relevance *)
2476 let rhs_rels', tycon =
2477 let neqs_rels, arity =
2478 match ineqs with
2479 | None -> [], arity
2480 | Some ineqs ->
2481 [LocalAssum (make_annot Anonymous r, ineqs)], lift 1 arity
2482 in
2483 let eqs_rels, arity = decompose_prod_n_decls sigma neqs arity in
2484 eqs_rels @ neqs_rels @ rhs_rels', arity
2485 in
2486 let _,rhs_env = push_rel_context ~hypnaming sigma rhs_rels' env in
2487 let sigma, j = typing_fun (mk_tycon tycon) rhs_env sigma eqn.rhs.it in
2488 let bbody = it_mkLambda_or_LetIn j.uj_val rhs_rels'
2489 and btype = it_mkProd_or_LetIn j.uj_type rhs_rels' in
2490 let sigma, _btype = Typing.type_of !!env sigma bbody in
2491 let branch_name = Id.of_string ("program_branch_" ^ (string_of_int !i)) in
2492 let branch_decl = LocalDef (make_annot (Name branch_name) r, lift !i bbody, lift !i btype) in
2493 let branch =
2494 let bref = DAst.make @@ GVar branch_name in
2495 match vars_of_ctx sigma rhs_rels with
2496 [] -> bref
2497 | l -> DAst.make @@ GApp (bref, l)
2498 in
2499 let branch = match ineqs with
2500 Some _ -> DAst.make @@ GApp (branch, [ hole Anonymous ])
2501 | None -> branch
2502 in
2503 incr i;
2504 let rhs = { eqn.rhs with it = Some branch } in
2505 (sigma, branch_decl :: branches,
2506 { eqn with patterns = newpatterns; rhs = rhs } :: eqns,
2507 opats :: prevpatterns))
2508 (sigma, [], [], []) eqns
2509 in
2510 sigma, x, y
2511
2512 (* Builds the predicate. If the predicate is dependent, its context is
2513 * made of 1+nrealargs assumptions for each matched term in an inductive
2514 * type and 1 assumption for each term not _syntactically_ in an
2515 * inductive type.
2516
2517 * Each matched terms are independently considered dependent or not.
2518
2519 * A type constraint but no annotation case: it is assumed non dependent.
2520 *)
2521
2522 let lift_ctx n ctx =
2523 let ctx', _ =
2524 List.fold_right (fun (c, t) (ctx, n') ->
2525 (liftn n n' c, liftn_tomatch_type n n' t) :: ctx, succ n')
2526 ctx ([], 0)
2527 in ctx'
2528
2529 (* Turn matched terms into variables. *)
2530 let abstract_tomatch env sigma tomatchs tycon =
2531 let prev, ctx, names, tycon =
2532 List.fold_left
2533 (fun (prev, ctx, names, tycon) (c, t) ->
2534 let lenctx = List.length ctx in
2535 match EConstr.kind sigma c with
2536 Rel n -> (lift lenctx c, lift_tomatch_type lenctx t) :: prev, ctx, names, tycon
2537 | _ ->
2538 let tycon = Option.map
2539 (fun t -> subst_term sigma (lift 1 c) (lift 1 t)) tycon in
2540 let name = next_ident_away (Id.of_string "filtered_var") names in
2541 let r = ERelevance.relevant in (* TODO relevance *)
2542 (mkRel 1, lift_tomatch_type (succ lenctx) t) :: lift_ctx 1 prev,
2543 LocalDef (make_annot (Name name) r, lift lenctx c, lift lenctx $ type_of_tomatch t) :: ctx,
2544 Id.Set.add name names, tycon)
2545 ([], [], Id.Set.empty, tycon) tomatchs
2546 in List.rev prev, ctx, tycon
2547
2548 (* [build_dependent_inductive] takes:
2549 - a list [arsign] of contexts of the form [realvars:realtypes,arg:ind realvars]
2550 all typed in context [env]
2551 - a list [tomatchs] of terms instantiating [arsign], all typed in [env]
2552 It returns [sign,signlen,eqs,neqs,args] where
2553 - [eqs] is the list of contexts of equalities between
2554 [(realvars,arg)] and their instance in [tomatchs]
2555 - [sign] is the same as [arsign] where variables have been renamed using a prime
2556 - [signlen] is the common length of [sign] and [eqs] *)
2557
2558 let build_dependent_signature env sigma avoid tomatchs arsign =
2559 let avoid = ref avoid in
2560 let arsign = List.rev arsign in
2561 let allnames = List.rev_map (List.map RelDecl.get_name) arsign in
2562 let nar = List.fold_left (fun n names -> List.length names + n) 0 allnames in
2563 let sigma, eqs, neqs, refls, slift, arsign' =
2564 List.fold_left2
2565 (fun (sigma, eqs, neqs, refls, slift, arsigns) (tm, ty) arsign ->
2566 (* The accumulator:
2567 previous eqs,
2568 number of previous eqs,
2569 lift to get outside eqs and in the introduced variables ('as' and 'in'),
2570 new arity signatures
2571 *)
2572 match ty with
2573 | IsInd (ty, IndType (indf, realargs), _) when List.length realargs > 0 ->
2574 (* Build the arity signature following the names in matched terms
2575 as much as possible *)
2576 let argsign = List.tl arsign in (* arguments in inverse application order *)
2577 let app_decl = List.hd arsign in (* The matched argument *)
2578 (* We are working on the i-th inductive type of the arity. It satisfies
2579 [env |- tm_i : indf_i args_i : Type] with [args_i:argts_i] and we want to build
2580 [env, arsign |- eqs_i : ((names_i,appn_i : argsign_i,appt_i) = (args_i,tm_i : argts_i,indf args_i))]
2581 (there are |args|+1 such equations that we see as a context)
2582 where [arsign], with appropriate lift on each [ts_i] and [indf_i], is itself
2583 [names1:ts1,appn1:indf1 names1,...,names_n:ts_n,appn_n:indf_n names_n]
2584 where [indf_i names_i], written [appt],
2585 satisfies [env |- names_i:ts_i, appn_i:indf_i names_i]
2586 (that is a context in [env] rather than in [env] extended
2587 with the arity up to [i]);
2588 also [nar] is the length of [arsign]
2589 and [neqs] is the length of [arsign] up to before [i];
2590 Regarding the decls of [arsign] we have [env |- (names_i:argsign_i),(appn_i:appt_i)] as a context,
2591 that is [env, name_i1 ... name_i_{j-1} |- name_ij : argsign_i_j]
2592 and [env, names_i |- appn_i:appt_i]
2593 and we need [env, arsign, name'_i1 ... name'_i_{j-1} |- name_ij:argsign_i_j] and
2594 [env, arsign, names'_i |- appn_i:appt_i] as terms, where the [names_i] refer to
2595 the [names_i] in [argsign]; we obtain it by first lifting the whole context
2596 [(names_i:argsign_i),(appn_i:appt_i)] (argsign') *)
2597 let subst = Vars.subst_of_rel_context_instance_list argsign realargs in
2598 let sigma, env', nargeqs, argeqs, refl_args, slift, argsign' =
2599 List.fold_right2
2600 (fun arg decl (sigma, env, nargeqs, argeqs, refl_args, slift, argsign') ->
2601 let name = RelDecl.get_name decl in
2602 let t = liftn neqs (succ nargeqs) (RelDecl.get_type decl) in
2603 let argt = Retyping.get_type_of env sigma arg in
2604 assert (neqs + nargeqs + slift = nar);
2605
2606 let sigma, eq, refl_arg =
2607 let t' = lift (nargeqs + slift) t in
2608 let argt' = lift (nargeqs + nar) argt in
2609 if Reductionops.is_conv env sigma argt' t' then
2610 let sigma, eq =
2611 mk_eq env sigma argt'
2612 (mkRel (nargeqs + slift))
2613 (lift (nargeqs + nar) arg)
2614 in
2615 let sigma, refl = mk_eq_refl env sigma argt arg in
2616 sigma, eq, refl
2617 else
2618 let sigma, eq =
2619 mk_JMeq env sigma
2620 t'
2621 (mkRel (nargeqs + slift))
2622 argt'
2623 (lift (nargeqs + nar) arg)
2624 in
2625 let sigma, refl = mk_JMeq_refl env sigma argt arg in
2626 (sigma, eq, refl)
2627 in
2628 let previd, id =
2629 let name =
2630 match EConstr.kind sigma arg with
2631 Rel n -> RelDecl.get_name (lookup_rel n env)
2632 | _ -> name
2633 in
2634 make_prime avoid name
2635 in
2636 (sigma, env, succ nargeqs,
2637 (LocalAssum (make_annot (Name (eq_id avoid previd)) ERelevance.relevant, eq)) :: argeqs,
2638 refl_arg :: refl_args,
2639 pred slift,
2640 RelDecl.set_name (Name id) decl :: argsign'))
2641 subst argsign (sigma, env, 0, [], [], slift, [])
2642 in
2643 assert (neqs + nargeqs + slift = nar);
2644 let appn = RelDecl.get_name app_decl in
2645 let appt = liftn neqs (succ nargeqs) (RelDecl.get_type app_decl) in
2646 let sigma, eq =
2647 mk_JMeq env sigma
2648 (lift (nargeqs + slift) appt)
2649 (mkRel (nargeqs + slift))
2650 (lift (nargeqs + nar) ty)
2651 (lift (nargeqs + nar) tm)
2652 in
2653 let sigma, refl_eq = mk_JMeq_refl env sigma ty tm in
2654 let previd, id = make_prime avoid appn in
2655 (sigma, (LocalAssum (make_annot (Name (eq_id avoid previd)) ERelevance.relevant, eq) :: argeqs) :: eqs,
2656 succ (nargeqs + neqs),
2657 refl_eq :: refl_args @ refls,
2658 pred slift,
2659 ((RelDecl.set_name (Name id) app_decl :: argsign') :: arsigns))
2660
2661 | _ -> (* Non dependent inductive or not inductive, just use a regular equality *)
2662 let decl = List.hd arsign in (* The matched argument *)
2663 let argsign = List.tl arsign in (* rest of signature (necessarily only letins) *)
2664 let name = RelDecl.get_name decl in
2665 let previd, id = make_prime avoid name in
2666 let arsign' = RelDecl.set_name (Name id) decl :: argsign in
2667 let tomatch_ty = type_of_tomatch ty in
2668 assert (neqs + slift = nar);
2669 let slift = slift - List.length argsign in
2670 let sigma, eq =
2671 mk_eq env sigma
2672 (lift nar tomatch_ty)
2673 (mkRel slift)
2674 (lift nar tm)
2675 in
2676 let sigma, refl = mk_eq_refl env sigma tomatch_ty tm in
2677 let na = make_annot (Name (eq_id avoid previd)) ERelevance.relevant in
2678 let nar' = List.length arsign' in
2679 (sigma,
2680 [LocalAssum (na, eq)] :: eqs, neqs + nar',
2681 refl :: refls,
2682 pred slift, arsign' :: arsigns))
2683 (sigma, [], 0, [], nar, []) tomatchs arsign
2684 in
2685 assert (Int.equal slift 0); (* we must have folded over all elements of the arity signature *)
2686 assert (neqs = nar);
2687 sigma, arsign', nar, eqs, refls
2688
2689 let context_of_arsign l =
2690 (* From a family of [env, arsign |- ctx_i]] to [env, arsign |- ctx_1, ..., ctx_n] *)
2691 let (x, _) = List.fold_right
2692 (fun ctx (prev_ctx, n) ->
2693 (* From [env, arsign |- ctx_i] to [env, arsign, ctx1, ..., ctx_{i-1} |- ctx_i] *)
2694 (lift_rel_context n ctx @ prev_ctx, List.length ctx + n))
2695 l ([], 0)
2696 in x
2697
2698 let compile_program_cases ?loc style (typing_function, sigma) tycon env
2699 (predopt, tomatchl, eqns) =
2700 let hypnaming = VarSet.variables (Global.env ()) in
2701 let typing_fun tycon env sigma = function
2702 | Some t -> typing_function tycon env sigma t
2703 | None -> coq_unit_judge !!env sigma in
2704
2705 (* We build the matrix of patterns and right-hand side *)
2706 let matx = matx_of_eqns env eqns in
2707
2708 (* We build the vector of terms to match consistently with the *)
2709 (* constructors found in patterns *)
2710 let env, sigma, tomatchs = coerce_to_indtype ~program_mode:true typing_function env sigma matx tomatchl in
2711 let tycon = valcon_of_tycon tycon in
2712 let tomatchs, tomatchs_lets, tycon' = abstract_tomatch env sigma tomatchs tycon in
2713 let _,env = push_rel_context ~hypnaming sigma tomatchs_lets env in
2714 let len = List.length eqns in
2715 let sigma, sign, signlen, eqs, args =
2716 (* The arity signature *)
2717 let arsign = extract_arity_signature ~dolift:false !!env tomatchs tomatchl in
2718 (* Build the dependent arity signature, the equalities which makes
2719 the first part of the predicate and their instantiations. *)
2720 let avoid = Id.Set.empty in
2721 build_dependent_signature !!env sigma avoid tomatchs arsign
2722
2723 in
2724 let sigma, tycon, arity =
2725 let nar = List.fold_left (fun n sign -> List.length sign + n) 0 sign in
2726 match tycon' with
2727 | None ->
2728 let sigma, ev = mkExistential !!env sigma in
2729 sigma, ev, lift nar ev
2730 | Some t ->
2731 let sigma, pred =
2732 match prepare_predicate_from_arsign_tycon ~program_mode:true env sigma loc tomatchs sign t with
2733 | Some (evd, pred, arsign) -> evd, pred
2734 | None -> sigma, lift nar t
2735 in
2736 sigma, lift (List.length tomatchs_lets) (Option.get tycon), pred
2737 in
2738 let neqs, arity =
2739 let ctx = context_of_arsign eqs in
2740 let neqs = List.length ctx in
2741 neqs, it_mkProd_or_LetIn (lift neqs arity) ctx
2742 in
2743 let sigma, lets, matx =
2744 (* Type the rhs under the assumption of equations *)
2745 constrs_of_pats typing_fun env sigma matx tomatchs sign neqs arity
2746 in
2747 let matx = List.rev matx in
2748 let _ = assert (Int.equal len (List.length lets)) in
2749 let _,env = push_rel_context ~hypnaming sigma lets env in
2750 let matx = List.map (fun eqn -> { eqn with rhs = { eqn.rhs with rhs_env = env } }) matx in
2751 let tomatchs = List.map (fun (x, y) -> lift len x, lift_tomatch_type len y) tomatchs in
2752 let args = List.rev_map (lift len) args in
2753 let pred = liftn len (succ signlen) arity in
2754 let nal, pred = build_initial_predicate sign pred in
2755
2756 (* We push the initial terms to match and push their alias to rhs' envs *)
2757 (* names of aliases will be recovered from patterns (hence Anonymous here) *)
2758
2759 (* TODO relevance *)
2760 let out_tmt na = function NotInd (None,t) -> LocalAssum (make_annot na ERelevance.relevant,t)
2761 | NotInd (Some b, t) -> LocalDef (make_annot na ERelevance.relevant,b,t)
2762 | IsInd (typ,_,_) -> LocalAssum (make_annot na ERelevance.relevant,typ) in
2763 let typs = List.map2 (fun (na,_) (tm,tmt) -> (tm,out_tmt na tmt)) nal tomatchs in
2764
2765 let typs =
2766 List.map (fun (c,d) -> (c,extract_inductive_data !!env sigma d,d)) typs in
2767
2768 let dep_sign =
2769 find_dependencies_signature sigma
2770 (List.make (List.length typs) true)
2771 typs in
2772
2773 let typs' =
2774 List.map3
2775 (fun (tm,tmt) deps (na,realnames) ->
2776 let deps = if not (isRel sigma tm) then [] else deps in
2777 let tmt = set_tomatch_realnames realnames tmt in
2778 ((tm,tmt),deps,na))
2779 tomatchs dep_sign nal in
2780
2781 let initial_pushed = List.map (fun x -> Pushed (true,x)) typs' in
2782
2783 let typing_function tycon env sigma = function
2784 | Some t -> typing_function tycon env sigma t
2785 | None -> coq_unit_judge !!env sigma in
2786
2787 let pb =
2788 { env = env;
2789 pred = pred;
2790 tomatch = initial_pushed;
2791 history = start_history (List.length initial_pushed);
2792 mat = matx;
2793 caseloc = loc;
2794 casestyle= style;
2795 typing_function = typing_function } in
2796
2797 let used, sigma, j = compile ~program_mode:true sigma pb in
2798 (* We check for unused patterns *)
2799 check_unused_pattern !!env used matx;
2800 let body = it_mkLambda_or_LetIn (applist (j.uj_val, args)) lets in
2801 let tycon = it_mkProd_wo_LetIn tycon tomatchs_lets in
2802 let j =
2803 { uj_val = it_mkLambda_or_LetIn body tomatchs_lets;
2804 (* XXX: is this normalization needed? *)
2805 uj_type = Evarutil.nf_evar sigma tycon; }
2806 in sigma, j
2807
2808 (**************************************************************************)
2809 (* Main entry of the matching compilation *)
2810
2811 let compile_cases ?loc ~program_mode style (typing_fun, sigma) tycon env (predopt, tomatchl, eqns) =
2812 if predopt == None && program_mode && Program.is_program_cases () then
2813 compile_program_cases ?loc style (typing_fun, sigma)
2814 tycon env (predopt, tomatchl, eqns)
2815 else
2816
2817 (* We build the matrix of patterns and right-hand side *)
2818 let matx = matx_of_eqns env eqns in
2819
2820 (* We build the vector of terms to match consistently with the *)
2821 (* constructors found in patterns *)
2822 let predenv, sigma, tomatchs = coerce_to_indtype ~program_mode typing_fun env sigma matx tomatchl in
2823
2824 (* If an elimination predicate is provided, we check it is compatible
2825 with the type of arguments to match; if none is provided, we
2826 build alternative possible predicates *)
2827 let arsign = extract_arity_signature !!env tomatchs tomatchl in
2828 let preds = prepare_predicate ?loc ~program_mode typing_fun predenv sigma tomatchs arsign tycon predopt in
2829
2830 let compile_for_one_predicate (sigma,nal,pred) =
2831 (* We push the initial terms to match and push their alias to rhs' envs *)
2832 (* names of aliases will be recovered from patterns (hence Anonymous *)
2833 (* here) *)
2834
2835 (* TODO relevance *)
2836 let out_tmt na = function NotInd (None,t) -> LocalAssum (na,t)
2837 | NotInd (Some b,t) -> LocalDef (na,b,t)
2838 | IsInd (typ,_,_) -> LocalAssum (na,typ) in
2839 let typs = List.map2 (fun (na,_) (tm,tmt) -> (tm,out_tmt (make_annot na ERelevance.relevant) tmt)) nal tomatchs in
2840
2841 let typs =
2842 List.map (fun (c,d) -> (c,extract_inductive_data !!env sigma d,d)) typs in
2843
2844 let dep_sign =
2845 find_dependencies_signature sigma
2846 (List.make (List.length typs) true)
2847 typs in
2848
2849 let typs' =
2850 List.map3
2851 (fun (tm,tmt) deps (na,realnames) ->
2852 let deps = if not (isRel sigma tm) then [] else deps in
2853 let tmt = set_tomatch_realnames realnames tmt in
2854 ((tm,tmt),deps,na))
2855 tomatchs dep_sign nal in
2856
2857 let initial_pushed = List.map (fun x -> Pushed (true,x)) typs' in
2858
2859 (* A typing function that provides with a canonical term for absurd cases*)
2860 let typing_fun tycon env sigma = function
2861 | Some t -> typing_fun tycon env sigma t
2862 | None -> coq_unit_judge !!env sigma in
2863
2864 let pb =
2865 { env = env;
2866 pred = pred;
2867 tomatch = initial_pushed;
2868 history = start_history (List.length initial_pushed);
2869 mat = matx;
2870 caseloc = loc;
2871 casestyle = style;
2872 typing_function = typing_fun } in
2873
2874 let used, sigma, j = compile ~program_mode sigma pb in
2875
2876 (* We coerce to the tycon (if an elim predicate was provided) *)
2877 let sigma, j = inh_conv_coerce_to_tycon ?loc ~program_mode !!env sigma j tycon in
2878 used, sigma, j
2879 in
2880
2881 (* Return the term compiled with the first possible elimination *)
2882 (* predicate for which the compilation succeeds *)
2883 let used, sigma, j = list_try_compile compile_for_one_predicate preds in
2884
2885 (* We check for unused patterns *)
2886 check_unused_pattern !!env used matx;
2887
2888 sigma, j