Debian Codegraph @

plugins/funind/glob_term_to_relation.ml

raw symbols SCIP
1 open Printer
2 open Pp
3 open Names
4 open Constr
5 open Context
6 open Vars
7 open Glob_term
8 open Glob_ops
9 open Indfun_common
10 open CErrors
11 open Util
12 open Glob_termops
13 module RelDecl = Context.Rel.Declaration
14 module NamedDecl = Context.Named.Declaration
15 module ERelevance = EConstr.ERelevance
16
17 let observe strm = if do_observe () then Feedback.msg_debug strm else ()
18
19 (*let observennl strm =
20 if do_observe ()
21 then Pp.msg strm
22 else ()*)
23
24 type binder_type = Lambda of Name.t | Prod of Name.t | LetIn of Name.t
25 type glob_context = (binder_type * glob_constr) list
26
27 let rec solve_trivial_holes pat_as_term e =
28 match (DAst.get pat_as_term, DAst.get e) with
29 | GHole _, _ -> e
30 | GApp (fp, argsp), GApp (fe, argse) when glob_constr_eq fp fe ->
31 DAst.make
32 (GApp
33 (solve_trivial_holes fp fe, List.map2 solve_trivial_holes argsp argse))
34 | _, _ -> pat_as_term
35
36 (*
37 compose_glob_context [(bt_1,n_1,t_1);......] rt returns
38 b_1(n_1,t_1,.....,bn(n_k,t_k,rt)) where the b_i's are the
39 binders corresponding to the bt_i's
40 *)
41 let compose_glob_context =
42 let compose_binder (bt, t) acc =
43 match bt with
44 | Lambda n -> mkGLambda (n, t, acc)
45 | Prod n -> mkGProd (n, t, acc)
46 | LetIn n -> mkGLetIn (n, t, None, acc)
47 in
48 List.fold_right compose_binder
49
50 (*
51 The main part deals with building a list of globalized constructor expressions
52 from the rhs of a fixpoint equation.
53 *)
54
55 type 'a build_entry_pre_return =
56 { context : glob_context
57 ; (* the binding context of the result *)
58 value : 'a (* The value *) }
59
60 type 'a build_entry_return =
61 {result : 'a build_entry_pre_return list; to_avoid : Id.t list}
62
63 (*
64 [combine_results combine_fun res1 res2] combine two results [res1] and [res2]
65 w.r.t. [combine_fun].
66
67 Informally, both [res1] and [res2] are lists of "constructors" [res1_1;...]
68 and [res2_1,....] and we need to produce
69 [combine_fun res1_1 res2_1;combine_fun res1_1 res2_2;........]
70 *)
71
72 let combine_results
73 (combine_fun :
74 'a build_entry_pre_return
75 -> 'b build_entry_pre_return
76 -> 'c build_entry_pre_return) (res1 : 'a build_entry_return)
77 (res2 : 'b build_entry_return) : 'c build_entry_return =
78 let pre_result =
79 List.map
80 (fun res1 ->
81 (* for each result in arg_res *)
82 List.map (* we add it in each args_res *)
83 (fun res2 -> combine_fun res1 res2)
84 res2.result)
85 res1.result
86 in
87 (* and then we flatten the map *)
88 { result = List.concat pre_result
89 ; to_avoid = List.union Id.equal res1.to_avoid res2.to_avoid }
90
91 (*
92 The combination function for an argument with a list of argument
93 *)
94
95 let combine_args arg args =
96 { context = arg.context @ args.context
97 ; (* Note that the binding context of [arg] MUST be placed before the one of
98 [args] in order to preserve possible type dependencies
99 *)
100 value = arg.value :: args.value }
101
102 let ids_of_binder = function
103 | LetIn Anonymous | Prod Anonymous | Lambda Anonymous -> Id.Set.empty
104 | LetIn (Name id) | Prod (Name id) | Lambda (Name id) -> Id.Set.singleton id
105
106 let rec change_vars_in_binder mapping = function
107 | [] -> []
108 | (bt, t) :: l ->
109 let new_mapping = Id.Set.fold Id.Map.remove (ids_of_binder bt) mapping in
110 (bt, change_vars mapping t)
111 ::
112 ( if Id.Map.is_empty new_mapping then l
113 else change_vars_in_binder new_mapping l )
114
115 let rec replace_var_by_term_in_binder x_id term = function
116 | [] -> []
117 | (bt, t) :: l ->
118 (bt, replace_var_by_term x_id term t)
119 ::
120 ( if Id.Set.mem x_id (ids_of_binder bt) then l
121 else replace_var_by_term_in_binder x_id term l )
122
123 let add_bt_names bt = Id.Set.union (ids_of_binder bt)
124
125 let apply_args ctxt body args =
126 let need_convert_id avoid id =
127 List.exists (is_free_in id) args || Id.Set.mem id avoid
128 in
129 let need_convert avoid bt =
130 Id.Set.exists (need_convert_id avoid) (ids_of_binder bt)
131 in
132 let next_name_away (na : Name.t) (mapping : Id.t Id.Map.t) (avoid : Id.Set.t)
133 =
134 match na with
135 | Name id when Id.Set.mem id avoid ->
136 let new_id = Namegen.next_ident_away id avoid in
137 (Name new_id, Id.Map.add id new_id mapping, Id.Set.add new_id avoid)
138 | _ -> (na, mapping, avoid)
139 in
140 let next_bt_away bt (avoid : Id.Set.t) =
141 match bt with
142 | LetIn na ->
143 let new_na, mapping, new_avoid = next_name_away na Id.Map.empty avoid in
144 (LetIn new_na, mapping, new_avoid)
145 | Prod na ->
146 let new_na, mapping, new_avoid = next_name_away na Id.Map.empty avoid in
147 (Prod new_na, mapping, new_avoid)
148 | Lambda na ->
149 let new_na, mapping, new_avoid = next_name_away na Id.Map.empty avoid in
150 (Lambda new_na, mapping, new_avoid)
151 in
152 let rec do_apply avoid ctxt body args =
153 match (ctxt, args) with
154 | _, [] ->
155 (* No more args *)
156 (ctxt, body)
157 | [], _ ->
158 (* no more fun *)
159 let f, args' = glob_decompose_app body in
160 (ctxt, mkGApp (f, args' @ args))
161 | (Lambda Anonymous, t) :: ctxt', arg :: args' ->
162 do_apply avoid ctxt' body args'
163 | (Lambda (Name id), t) :: ctxt', arg :: args' ->
164 let new_avoid, new_ctxt', new_body, new_id =
165 if need_convert_id avoid id then
166 let new_avoid = Id.Set.add id avoid in
167 let new_id = Namegen.next_ident_away id new_avoid in
168 let new_avoid' = Id.Set.add new_id new_avoid in
169 let mapping = Id.Map.add id new_id Id.Map.empty in
170 let new_ctxt' = change_vars_in_binder mapping ctxt' in
171 let new_body = change_vars mapping body in
172 (new_avoid', new_ctxt', new_body, new_id)
173 else (Id.Set.add id avoid, ctxt', body, id)
174 in
175 let new_body = replace_var_by_term new_id arg new_body in
176 let new_ctxt' = replace_var_by_term_in_binder new_id arg new_ctxt' in
177 do_apply avoid new_ctxt' new_body args'
178 | (bt, t) :: ctxt', _ ->
179 let new_avoid, new_ctxt', new_body, new_bt =
180 let new_avoid = add_bt_names bt avoid in
181 if need_convert avoid bt then
182 let new_bt, mapping, new_avoid = next_bt_away bt new_avoid in
183 ( new_avoid
184 , change_vars_in_binder mapping ctxt'
185 , change_vars mapping body
186 , new_bt )
187 else (new_avoid, ctxt', body, bt)
188 in
189 let new_ctxt', new_body = do_apply new_avoid new_ctxt' new_body args in
190 ((new_bt, t) :: new_ctxt', new_body)
191 in
192 do_apply Id.Set.empty ctxt body args
193
194 let combine_app f args =
195 let new_ctxt, new_value = apply_args f.context f.value args.value in
196 { (* Note that the binding context of [args] MUST be placed before the one of
197 the applied value in order to preserve possible type dependencies
198 *)
199 context = args.context @ new_ctxt
200 ; value = new_value }
201
202 let combine_lam n t b =
203 { context = []
204 ; value =
205 mkGLambda
206 ( n
207 , compose_glob_context t.context t.value
208 , compose_glob_context b.context b.value ) }
209
210 let combine_prod2 n t b =
211 { context = []
212 ; value =
213 mkGProd
214 ( n
215 , compose_glob_context t.context t.value
216 , compose_glob_context b.context b.value ) }
217
218 let combine_prod n t b =
219 {context = t.context @ ((Prod n, t.value) :: b.context); value = b.value}
220
221 let combine_letin n t b =
222 {context = t.context @ ((LetIn n, t.value) :: b.context); value = b.value}
223
224 let mk_result ctxt value avoid =
225 {result = [{context = ctxt; value}]; to_avoid = avoid}
226
227 (*************************************************
228 Some functions to deal with overlapping patterns
229 **************************************************)
230
231 let rocq_True_ref = lazy (Rocqlib.lib_ref "core.True.type")
232 let rocq_False_ref = lazy (Rocqlib.lib_ref "core.False.type")
233
234 (*
235 [make_discr_match_el \[e1,...en\]] builds match e1,...,en with
236 (the list of expressions on which we will do the matching)
237 *)
238 let make_discr_match_el = List.map (fun e -> (e, (Anonymous, None)))
239
240 (*
241 [make_discr_match_brl i \[pat_1,...,pat_n\]] constructs a discrimination pattern matching on the ith expression.
242 that is.
243 match ?????? with \\
244 | pat_1 => False \\
245 | pat_{i-1} => False \\
246 | pat_i => True \\
247 | pat_{i+1} => False \\
248 \vdots
249 | pat_n => False
250 end
251 *)
252 let make_discr_match_brl i =
253 List.map_i
254 (fun j {CAst.v = idl, patl, _} ->
255 CAst.make
256 @@
257 if Int.equal j i then (idl, patl, mkGRef (Lazy.force rocq_True_ref))
258 else (idl, patl, mkGRef (Lazy.force rocq_False_ref)))
259 0
260
261 (*
262 [make_discr_match brl el i] generates an hypothesis such that it reduce to true iff
263 brl_{i} is the first branch matched by [el]
264
265 Used when we want to simulate the coq pattern matching algorithm
266 *)
267 let make_discr_match brl el i =
268 mkGCases (None, make_discr_match_el el, make_discr_match_brl i brl)
269
270 (**********************************************************************)
271 (* functions used to build case expression from lettuple and if ones *)
272 (**********************************************************************)
273
274 (* [build_constructors_of_type] construct the array of pattern of its inductive argument*)
275 let build_constructors_of_type env ind' argl =
276 let mib, ind = Inductive.lookup_mind_specif env ind' in
277 let npar = mib.Declarations.mind_nparams in
278 Array.mapi
279 (fun i _ ->
280 let construct = (ind', i + 1) in
281 let constructref = GlobRef.ConstructRef construct in
282 let _implicit_positions_of_cst =
283 Impargs.implicits_of_global constructref
284 in
285 let cst_narg =
286 Inductiveops.constructor_nallargs env construct
287 in
288 let argl =
289 if List.is_empty argl then List.make cst_narg (mkGHole ())
290 else List.make npar (mkGHole ()) @ argl
291 in
292 let pat_as_term =
293 mkGApp (mkGRef (GlobRef.ConstructRef (ind', i + 1)), argl)
294 in
295 cases_pattern_of_glob_constr env Anonymous pat_as_term)
296 ind.Declarations.mind_consnames
297
298 (******************)
299 (* Main functions *)
300 (******************)
301
302 let raw_push_named (na, raw_value, raw_typ) env =
303 match na with
304 | Anonymous -> env
305 | Name id -> (
306 let typ, _ =
307 Pretyping.understand env (Evd.from_env env)
308 ~expected_type:Pretyping.IsType raw_typ
309 in
310 let na = make_annot id ERelevance.relevant in
311 (* TODO relevance *)
312 match raw_value with
313 | None -> EConstr.push_named (NamedDecl.LocalAssum (na, typ)) env
314 | Some value -> EConstr.push_named (NamedDecl.LocalDef (na, value, typ)) env
315 )
316
317 let add_pat_variables sigma pat typ env : Environ.env =
318 let rec add_pat_variables env pat typ : Environ.env =
319 observe
320 (str "new rel env := " ++ Printer.pr_rel_context_of env (Evd.from_env env));
321 match DAst.get pat with
322 | PatVar na ->
323 EConstr.push_rel
324 (RelDecl.LocalAssum (make_annot na ERelevance.relevant, typ))
325 env
326 | PatCstr (c, patl, na) ->
327 let (Inductiveops.IndType (indf, indargs)) =
328 try
329 Inductiveops.find_rectype env (Evd.from_env env)
330 typ
331 with Not_found -> assert false
332 in
333 let constructors = Inductiveops.get_constructors env indf in
334 let constructor : Inductiveops.constructor_summary =
335 List.find
336 (fun cs -> Environ.QConstruct.equal env c (fst cs.Inductiveops.cs_cstr))
337 (Array.to_list constructors)
338 in
339 let cs_args_types : EConstr.types list =
340 List.map RelDecl.get_type constructor.Inductiveops.cs_args
341 in
342 List.fold_left2 add_pat_variables env patl (List.rev cs_args_types)
343 in
344 let new_env = add_pat_variables env pat typ in
345 let res =
346 fst
347 (Context.Rel.fold_outside
348 (fun decl (env, ctxt) ->
349 let open Context.Rel.Declaration in
350 match decl with
351 | LocalAssum ({binder_name = Anonymous}, _)
352 |LocalDef ({binder_name = Anonymous}, _, _) ->
353 assert false
354 | LocalAssum (({binder_name = Name id} as na), t) ->
355 let na = {na with binder_name = id} in
356 let new_t = substl ctxt t in
357 observe
358 ( str "for variable " ++ Ppconstr.pr_id id ++ fnl ()
359 ++ str "old type := "
360 ++ Printer.pr_lconstr_env env sigma t
361 ++ fnl () ++ str "new type := "
362 ++ Printer.pr_lconstr_env env sigma new_t
363 ++ fnl () );
364 let open Context.Named.Declaration in
365 (Environ.push_named (LocalAssum (na, new_t)) env, mkVar id :: ctxt)
366 | LocalDef (({binder_name = Name id} as na), v, t) ->
367 let na = {na with binder_name = id} in
368 let new_t = substl ctxt t in
369 let new_v = substl ctxt v in
370 observe
371 ( str "for variable " ++ Ppconstr.pr_id id ++ fnl ()
372 ++ str "old type := "
373 ++ Printer.pr_lconstr_env env sigma t
374 ++ fnl () ++ str "new type := "
375 ++ Printer.pr_lconstr_env env sigma new_t
376 ++ fnl () ++ str "old value := "
377 ++ Printer.pr_lconstr_env env sigma v
378 ++ fnl () ++ str "new value := "
379 ++ Printer.pr_lconstr_env env sigma new_v
380 ++ fnl () );
381 let open Context.Named.Declaration in
382 ( Environ.push_named (LocalDef (na, new_v, new_t)) env
383 , mkVar id :: ctxt ))
384 (Environ.rel_context new_env)
385 ~init:(env, []))
386 in
387 observe
388 (str "new var env := " ++ Printer.pr_named_context_of res (Evd.from_env env));
389 res
390
391 let rec pattern_to_term_and_type env typ =
392 DAst.with_val (function
393 | PatVar Anonymous -> assert false
394 | PatVar (Name id) -> mkGVar id
395 | PatCstr (constr, patternl, _) ->
396 let cst_narg = Inductiveops.constructor_nallargs env constr in
397 let (Inductiveops.IndType (indf, indargs)) =
398 try
399 Inductiveops.find_rectype env (Evd.from_env env)
400 typ
401 with Not_found -> assert false
402 in
403 let constructors = Inductiveops.get_constructors env indf in
404 let constructor =
405 List.find
406 (fun cs ->
407 Environ.QConstruct.equal env (fst cs.Inductiveops.cs_cstr) constr)
408 (Array.to_list constructors)
409 in
410 let cs_args_types : EConstr.types list =
411 List.map RelDecl.get_type constructor.Inductiveops.cs_args
412 in
413 let _, cstl = Inductiveops.dest_ind_family indf in
414 let csta = Array.of_list cstl in
415 let implicit_args =
416 Array.to_list
417 (Array.init
418 (cst_narg - List.length patternl)
419 (fun i ->
420 Detyping.detype Detyping.Now env
421 (* XXX should we use full printing flags? *)
422 ~flags:(PrintingFlags.Detype.current())
423 (Evd.from_env env)
424 csta.(i)))
425 in
426 let patl_as_term =
427 List.map2
428 (pattern_to_term_and_type env)
429 (List.rev cs_args_types) patternl
430 in
431 mkGApp (mkGRef (GlobRef.ConstructRef constr), implicit_args @ patl_as_term))
432
433 (* [build_entry_lc funnames avoid rt] construct the list (in fact a build_entry_return)
434 of constructors corresponding to [rt] when replacing calls to [funnames] by calls to the
435 corresponding graphs.
436
437
438 The idea to transform a term [t] into a list of constructors [lc] is the following:
439 \begin{itemize}
440 \item if the term is a binder (bind x, body) then first compute [lc'] the list corresponding
441 to [body] and add (bind x. _) to each elements of [lc]
442 \item if the term has the form (g t1 ... ... tn) where g does not appears in (fnames)
443 then compute [lc1] ... [lcn] the lists of constructors corresponding to [t1] ... [tn],
444 then combine those lists and [g] as follows~: for each element [c1,...,cn] of [lc1\times...\times lcn],
445 [g c1 ... cn] is an element of [lc]
446 \item if the term has the form (f t1 .... tn) where [f] appears in [fnames] then
447 compute [lc1] ... [lcn] the lists of constructors corresponding to [t1] ... [tn],
448 then compute those lists and [f] as follows~: for each element [c1,...,cn] of [lc1\times...\times lcn]
449 create a new variable [res] and [forall res, R_f c1 ... cn res] is in [lc]
450 \item if the term is a cast just treat its body part
451 \item
452 if the term is a match, an if or a lettuple then compute the lists corresponding to each branch of the case
453 and concatenate them (informally, each branch of a match produces a new constructor)
454 \end{itemize}
455
456 WARNING: The terms constructed here are only USING the glob_constr syntax but are highly bad formed.
457 We must wait to have complete all the current calculi to set the recursive calls.
458 At this point, each term [f t1 ... tn] (where f appears in [funnames]) is replaced by
459 a pseudo term [forall res, res t1 ... tn, res]. A reconstruction phase is done later.
460 We in fact not create a constructor list since then end of each constructor has not the expected form
461 but only the value of the function
462 *)
463
464 let pr_glob_constr_env env x = pr_glob_constr_env env (Evd.from_env env) x
465
466 let rec build_entry_lc env sigma funnames avoid rt :
467 glob_constr build_entry_return =
468 observe (str " Entering : " ++ pr_glob_constr_env env rt);
469 let open CAst in
470 match DAst.get rt with
471 | GRef _ | GVar _ | GEvar _ | GPatVar _ | GSort _ | GHole _ | GGenarg _ | GInt _
472 |GFloat _ | GString _ ->
473 (* do nothing (except changing type of course) *)
474 mk_result [] rt avoid
475 | GApp (_, _) -> (
476 let f, args = glob_decompose_app rt in
477 let args_res : glob_constr list build_entry_return =
478 List.fold_right
479 (* create the arguments lists of constructors and combine them *)
480 (fun arg ctxt_argsl ->
481 let arg_res =
482 build_entry_lc env sigma funnames ctxt_argsl.to_avoid arg
483 in
484 combine_results combine_args arg_res ctxt_argsl)
485 args (mk_result [] [] avoid)
486 in
487 match DAst.get f with
488 | GLambda _ ->
489 let rec aux t l =
490 match l with
491 | [] -> t
492 | u :: l -> (
493 DAst.make
494 @@
495 match DAst.get t with
496 | GLambda (na, _, _, nat, b) -> GLetIn (na, None, u, None, aux b l)
497 | _ -> GApp (t, l) )
498 in
499 build_entry_lc env sigma funnames avoid (aux f args)
500 | GVar id when Id.Set.mem id funnames ->
501 (* if we have [f t1 ... tn] with [f]$\in$[fnames]
502 then we create a fresh variable [res],
503 add [res] and its "value" (i.e. [res v1 ... vn]) to each
504 pseudo constructor build for the arguments (i.e. a pseudo context [ctxt] and
505 a pseudo value "v1 ... vn".
506 The "value" of this branch is then simply [res]
507 *)
508 (* XXX here and other [understand] calls drop the ctx *)
509 let rt_as_constr, ctx = Pretyping.understand env (Evd.from_env env) rt in
510 let rt_typ = Retyping.get_type_of env (Evd.from_env env) rt_as_constr in
511 let res_raw_type =
512 Detyping.detype Detyping.Now
513 (* XXX should we use full printing flags? *)
514 ~flags:(PrintingFlags.Detype.current())
515 env (Evd.from_env env) rt_typ
516 in
517 let res = fresh_id args_res.to_avoid "_res" in
518 let new_avoid = res :: args_res.to_avoid in
519 let res_rt = mkGVar res in
520 let new_result =
521 List.map
522 (fun arg_res ->
523 let new_hyps =
524 [ (Prod (Name res), res_raw_type)
525 ; (Prod Anonymous, mkGApp (res_rt, mkGVar id :: arg_res.value)) ]
526 in
527 {context = arg_res.context @ new_hyps; value = res_rt})
528 args_res.result
529 in
530 {result = new_result; to_avoid = new_avoid}
531 | GVar _ | GEvar _ | GPatVar _ | GHole _ | GGenarg _ | GSort _ | GRef _ ->
532 (* if have [g t1 ... tn] with [g] not appearing in [funnames]
533 then
534 foreach [ctxt,v1 ... vn] in [args_res] we return
535 [ctxt, g v1 .... vn]
536 *)
537 { args_res with
538 result =
539 List.map
540 (fun args_res -> {args_res with value = mkGApp (f, args_res.value)})
541 args_res.result }
542 | GApp _ ->
543 assert false (* we have collected all the app in [glob_decompose_app] *)
544 | GLetIn (n, _, v, t, b) ->
545 (* if we have [(let x := v in b) t1 ... tn] ,
546 we discard our work and compute the list of constructor for
547 [let x = v in (b t1 ... tn)] up to alpha conversion
548 *)
549 let new_n, new_b, new_avoid =
550 match n with
551 | Name id when List.exists (is_free_in id) args ->
552 (* need to alpha-convert the name *)
553 let new_id = Namegen.next_ident_away id (Id.Set.of_list avoid) in
554 let new_avoid = id :: avoid in
555 let new_b = replace_var_by_term id (DAst.make @@ GVar id) b in
556 (Name new_id, new_b, new_avoid)
557 | _ -> (n, b, avoid)
558 in
559 build_entry_lc env sigma funnames avoid
560 (mkGLetIn (new_n, v, t, mkGApp (new_b, args)))
561 | GCases _ | GIf _ | GLetTuple _ | GProj _ ->
562 (* we have [(match e1, ...., en with ..... end) t1 tn]
563 we first compute the result from the case and
564 then combine each of them with each of args one
565 *)
566 let f_res = build_entry_lc env sigma funnames args_res.to_avoid f in
567 combine_results combine_app f_res args_res
568 | GCast (b, _, _) ->
569 (* for an applied cast we just trash the cast part
570 and restart the work.
571
572 WARNING: We need to restart since [b] itself should be an application term
573 *)
574 build_entry_lc env sigma funnames avoid (mkGApp (b, args))
575 | GRec _ -> user_err Pp.(str "Not handled GRec")
576 | GProd _ -> user_err Pp.(str "Cannot apply a type")
577 | GInt _ -> user_err Pp.(str "Cannot apply an integer")
578 | GFloat _ -> user_err Pp.(str "Cannot apply a float")
579 | GString _ -> user_err Pp.(str "Cannot apply a string")
580 | GArray _ -> user_err Pp.(str "Cannot apply an array")
581 (* end of the application treatement *) )
582 | GProj (f, params, c) ->
583 let args_res : glob_constr list build_entry_return =
584 List.fold_right
585 (* create the arguments lists of constructors and combine them *)
586 (fun arg ctxt_argsl ->
587 let arg_res =
588 build_entry_lc env sigma funnames ctxt_argsl.to_avoid arg
589 in
590 combine_results combine_args arg_res ctxt_argsl)
591 (params@[c]) (mk_result [] [] avoid) in
592 { args_res with
593 result =
594 List.map
595 (fun args_res ->
596 let c, params = List.sep_last args_res.value in
597 {args_res with value = DAst.make (GProj (f, params, c))})
598 args_res.result }
599 | GLambda (n, _, _, t, b) ->
600 (* we first compute the list of constructor
601 corresponding to the body of the function,
602 then the one corresponding to the type
603 and combine the two result
604 *)
605 let t_res = build_entry_lc env sigma funnames avoid t in
606 let new_n =
607 match n with
608 | Name _ -> n
609 | Anonymous -> Name (Indfun_common.fresh_id [] "_x")
610 in
611 let new_env = raw_push_named (new_n, None, t) env in
612 let b_res = build_entry_lc new_env sigma funnames avoid b in
613 combine_results (combine_lam new_n) t_res b_res
614 | GProd (n, _, _, t, b) ->
615 (* we first compute the list of constructor
616 corresponding to the body of the function,
617 then the one corresponding to the type
618 and combine the two result
619 *)
620 let t_res = build_entry_lc env sigma funnames avoid t in
621 let new_env = raw_push_named (n, None, t) env in
622 let b_res = build_entry_lc new_env sigma funnames avoid b in
623 if List.length t_res.result = 1 && List.length b_res.result = 1 then
624 combine_results (combine_prod2 n) t_res b_res
625 else combine_results (combine_prod n) t_res b_res
626 | GLetIn (n, _, v, typ, b) ->
627 (* we first compute the list of constructor
628 corresponding to the body of the function,
629 then the one corresponding to the value [t]
630 and combine the two result
631 *)
632 let v =
633 match typ with
634 | None -> v
635 | Some t -> DAst.make ?loc:rt.loc @@ GCast (v, Some DEFAULTcast, t)
636 in
637 let v_res = build_entry_lc env sigma funnames avoid v in
638 let v_as_constr, ctx = Pretyping.understand env (Evd.from_env env) v in
639 let v_type = Retyping.get_type_of env (Evd.from_env env) v_as_constr in
640 let v_r = ERelevance.relevant in
641 (* TODO relevance *)
642 let new_env =
643 match n with
644 | Anonymous -> env
645 | Name id ->
646 EConstr.push_named
647 (NamedDecl.LocalDef (make_annot id v_r, v_as_constr, v_type))
648 env
649 in
650 let b_res = build_entry_lc new_env sigma funnames avoid b in
651 combine_results (combine_letin n) v_res b_res
652 | GCases (_, _, el, brl) ->
653 (* we create the discrimination function
654 and treat the case itself
655 *)
656 let make_discr = make_discr_match brl in
657 build_entry_lc_from_case env sigma funnames make_discr el brl avoid
658 | GIf (b, (na, e_option), lhs, rhs) ->
659 let b_as_constr, ctx = Pretyping.understand env (Evd.from_env env) b in
660 let b_typ = Retyping.get_type_of env (Evd.from_env env) b_as_constr in
661 let ind, _ =
662 try Inductiveops.find_inductive env (Evd.from_env env) b_typ
663 with Not_found ->
664 user_err
665 ( str "Cannot find the inductive associated to "
666 ++ pr_glob_constr_env env b ++ str " in " ++ pr_glob_constr_env env rt
667 ++ str ". try again with a cast" )
668 in
669 let case_pats = build_constructors_of_type env (fst ind) [] in
670 assert (Int.equal (Array.length case_pats) 2);
671 let brl =
672 List.map_i (fun i x -> CAst.make ([], [case_pats.(i)], x)) 0 [lhs; rhs]
673 in
674 let match_expr = mkGCases (None, [(b, (Anonymous, None))], brl) in
675 (* Pp.msgnl (str "new case := " ++ Printer.pr_glob_constr match_expr); *)
676 build_entry_lc env sigma funnames avoid match_expr
677 | GLetTuple (nal, _, b, e) ->
678 let nal_as_glob_constr =
679 List.map (function Name id -> mkGVar id | Anonymous -> mkGHole ()) nal
680 in
681 let b_as_constr, ctx = Pretyping.understand env (Evd.from_env env) b in
682 let b_typ = Retyping.get_type_of env (Evd.from_env env) b_as_constr in
683 let ind, _ =
684 try Inductiveops.find_inductive env (Evd.from_env env) b_typ
685 with Not_found ->
686 user_err
687 ( str "Cannot find the inductive associated to "
688 ++ pr_glob_constr_env env b ++ str " in " ++ pr_glob_constr_env env rt
689 ++ str ". try again with a cast" )
690 in
691 let case_pats = build_constructors_of_type env (fst ind) nal_as_glob_constr in
692 assert (Int.equal (Array.length case_pats) 1);
693 let br = CAst.make ([], [case_pats.(0)], e) in
694 let match_expr = mkGCases (None, [(b, (Anonymous, None))], [br]) in
695 build_entry_lc env sigma funnames avoid match_expr
696 | GRec _ -> user_err Pp.(str "Not handled GRec")
697 | GCast (b, _, _) -> build_entry_lc env sigma funnames avoid b
698 | GArray _ -> user_err Pp.(str "Not handled GArray")
699
700 and build_entry_lc_from_case env sigma funname make_discr (el : tomatch_tuples)
701 (brl : Glob_term.cases_clauses) avoid : glob_constr build_entry_return =
702 match el with
703 | [] -> assert false (* this case correspond to match <nothing> with .... !*)
704 | el ->
705 (* this case correspond to
706 match el with brl end
707 we first compute the list of lists corresponding to [el] and
708 combine them .
709 Then for each element of the combinations,
710 we compute the result we compute one list per branch in [brl] and
711 finally we just concatenate those list
712 *)
713 let case_resl =
714 List.fold_right
715 (fun (case_arg, _) ctxt_argsl ->
716 let arg_res =
717 build_entry_lc env sigma funname ctxt_argsl.to_avoid case_arg
718 in
719 combine_results combine_args arg_res ctxt_argsl)
720 el (mk_result [] [] avoid)
721 in
722 let types =
723 List.map
724 (fun (case_arg, _) ->
725 let case_arg_as_constr, ctx =
726 Pretyping.understand env (Evd.from_env env) case_arg
727 in
728 Retyping.get_type_of env (Evd.from_env env) case_arg_as_constr)
729 el
730 in
731 (****** The next works only if the match is not dependent ****)
732 let results =
733 List.map
734 (fun ca ->
735 let res =
736 build_entry_lc_from_case_term env sigma types funname make_discr []
737 brl case_resl.to_avoid ca
738 in
739 res)
740 case_resl.result
741 in
742 { result = List.concat (List.map (fun r -> r.result) results)
743 ; to_avoid =
744 List.fold_left
745 (fun acc r -> List.union Id.equal acc r.to_avoid)
746 [] results }
747
748 and build_entry_lc_from_case_term env sigma types funname make_discr
749 patterns_to_prevent brl avoid matched_expr =
750 match brl with
751 | [] -> (* computed_branches *) {result = []; to_avoid = avoid}
752 | br :: brl' ->
753 (* alpha conversion to prevent name clashes *)
754 let {CAst.v = idl, patl, return} = alpha_br avoid br in
755 let new_avoid = idl @ avoid in
756 (* for now we can no more use idl as an identifier *)
757 (* building a list of precondition stating that we are not in this branch
758 (will be used in the following recursive calls)
759 *)
760 let new_env = List.fold_right2 (add_pat_variables sigma) patl types env in
761 let not_those_patterns : (Id.t list -> glob_constr -> glob_constr) list =
762 List.map2
763 (fun pat typ avoid pat'_as_term ->
764 let renamed_pat, _, _ = alpha_pat avoid pat in
765 let pat_ids = get_pattern_id renamed_pat in
766 let env_with_pat_ids = add_pat_variables sigma pat typ new_env in
767 List.fold_right
768 (fun id acc ->
769 let typ_of_id = Typing.type_of_variable env_with_pat_ids id in
770 let raw_typ_of_id =
771 Detyping.detype Detyping.Now env_with_pat_ids
772 (* XXX should we use full printing flags? *)
773 ~flags:(PrintingFlags.Detype.current())
774 (Evd.from_env env) typ_of_id
775 in
776 mkGProd (Name id, raw_typ_of_id, acc))
777 pat_ids
778 (glob_make_neq pat'_as_term (pattern_to_term renamed_pat)))
779 patl types
780 in
781 (* Checking if we can be in this branch
782 (will be used in the following recursive calls)
783 *)
784 let unify_with_those_patterns : (cases_pattern -> bool * bool) list =
785 List.map
786 (fun pat pat' -> (are_unifiable env pat pat', eq_cases_pattern env pat pat'))
787 patl
788 in
789 (*
790 we first compute the other branch result (in ordrer to keep the order of the matching
791 as much as possible)
792 *)
793 let brl'_res =
794 build_entry_lc_from_case_term env sigma types funname make_discr
795 ((unify_with_those_patterns, not_those_patterns) :: patterns_to_prevent)
796 brl' avoid matched_expr
797 in
798 (* We now create the precondition of this branch i.e.
799 1- the list of variable appearing in the different patterns of this branch and
800 the list of equation stating than el = patl (List.flatten ...)
801 2- If there exists a previous branch which pattern unify with the one of this branch
802 then a discrimination precond stating that we are not in a previous branch (if List.exists ...)
803 *)
804 let those_pattern_preconds =
805 List.flatten
806 (List.map3
807 (fun pat e typ_as_constr ->
808 let this_pat_ids = ids_of_pat pat in
809 let typ =
810 Detyping.detype Detyping.Now new_env
811 (* XXX should we use full printing flags? *)
812 ~flags:(PrintingFlags.Detype.current())
813 (Evd.from_env env) typ_as_constr
814 in
815 let pat_as_term = pattern_to_term pat in
816 (* removing trivial holes *)
817 let pat_as_term = solve_trivial_holes pat_as_term e in
818 (* observe (str "those_pattern_preconds" ++ spc () ++ *)
819 (* str "pat" ++ spc () ++ pr_glob_constr pat_as_term ++ spc ()++ *)
820 (* str "e" ++ spc () ++ pr_glob_constr e ++spc ()++ *)
821 (* str "typ_as_constr" ++ spc () ++ pr_lconstr typ_as_constr); *)
822 List.fold_right
823 (fun id acc ->
824 if Id.Set.mem id this_pat_ids then
825 ( Prod (Name id)
826 , let typ_of_id = Typing.type_of_variable new_env id in
827 let raw_typ_of_id =
828 Detyping.detype Detyping.Now new_env
829 (* XXX should we use full printing flags? *)
830 ~flags:(PrintingFlags.Detype.current())
831 (Evd.from_env env) typ_of_id
832 in
833 raw_typ_of_id )
834 :: acc
835 else acc)
836 idl
837 [(Prod Anonymous, glob_make_eq ~typ pat_as_term e)])
838 patl matched_expr.value types)
839 @
840 if
841 List.exists
842 (function
843 | unifl, _ ->
844 let unif, _ =
845 List.split (List.map2 (fun x y -> x y) unifl patl)
846 in
847 List.for_all (fun x -> x) unif)
848 patterns_to_prevent
849 then
850 let i = List.length patterns_to_prevent in
851 let pats_as_constr =
852 List.map2 (pattern_to_term_and_type new_env) types patl
853 in
854 [(Prod Anonymous, make_discr pats_as_constr i)]
855 else []
856 in
857 (* We compute the result of the value returned by the branch*)
858 let return_res = build_entry_lc new_env sigma funname new_avoid return in
859 (* and combine it with the preconds computed for this branch *)
860 let this_branch_res =
861 List.map
862 (fun res ->
863 { context = matched_expr.context @ those_pattern_preconds @ res.context
864 ; value = res.value })
865 return_res.result
866 in
867 {brl'_res with result = this_branch_res @ brl'_res.result}
868
869 let is_res r =
870 match DAst.get r with
871 | GVar id -> (
872 try String.equal (String.sub (Id.to_string id) 0 4) "_res"
873 with Invalid_argument _ -> false )
874 | _ -> false
875
876 let is_gr env c gr =
877 match DAst.get c with GRef (r, _) -> Environ.QGlobRef.equal env r gr | _ -> false
878
879 let is_gvar c = match DAst.get c with GVar id -> true | _ -> false
880
881 let same_raw_term env rt1 rt2 =
882 match (DAst.get rt1, DAst.get rt2) with
883 | GRef (r1, _), GRef (r2, _) -> Environ.QGlobRef.equal env r1 r2
884 | GHole _, GHole _ -> true
885 | _ -> false
886
887 let decompose_raw_eq env lhs rhs =
888 let rec decompose_raw_eq lhs rhs acc =
889 observe
890 ( str "decomposing eq for " ++ pr_glob_constr_env env lhs ++ str " "
891 ++ pr_glob_constr_env env rhs );
892 let rhd, lrhs = glob_decompose_app rhs in
893 let lhd, llhs = glob_decompose_app lhs in
894 observe (str "lhd := " ++ pr_glob_constr_env env lhd);
895 observe (str "rhd := " ++ pr_glob_constr_env env rhd);
896 observe (str "llhs := " ++ int (List.length llhs));
897 observe (str "lrhs := " ++ int (List.length lrhs));
898 let sllhs = List.length llhs in
899 let slrhs = List.length lrhs in
900 if same_raw_term env lhd rhd && Int.equal sllhs slrhs then
901 (* let _ = assert false in *)
902 List.fold_right2 decompose_raw_eq llhs lrhs acc
903 else (lhs, rhs) :: acc
904 in
905 decompose_raw_eq lhs rhs []
906
907 exception Continue
908
909 (*
910 The second phase which reconstruct the real type of the constructor.
911 rebuild the globalized constructors expression.
912 eliminates some meaningless equalities, applies some rewrites......
913 *)
914 let rec rebuild_cons env nb_args relname args crossed_types depth rt =
915 observe (str "rebuilding : " ++ pr_glob_constr_env env rt);
916 let open Context.Rel.Declaration in
917 let open CAst in
918 match DAst.get rt with
919 | GProd (n, _, k, t, b) -> (
920 let not_free_in_t id = not (is_free_in id t) in
921 let new_crossed_types = t :: crossed_types in
922 match DAst.get t with
923 | GApp (res_rt, args') when is_res res_rt -> (
924 let arg = List.hd args' in
925 match DAst.get arg with
926 | GVar this_relname ->
927 (*i The next call to mk_rel_id is
928 valid since we are constructing the graph
929 Ensures by: obvious
930 i*)
931 let new_t =
932 mkGApp (mkGVar (mk_rel_id this_relname), List.tl args' @ [res_rt])
933 in
934 let t', ctx = Pretyping.understand env (Evd.from_env env) new_t in
935 let r = ERelevance.relevant in
936 (* TODO relevance *)
937 let new_env = EConstr.push_rel (LocalAssum (make_annot n r, t')) env in
938 let new_b, id_to_exclude =
939 rebuild_cons new_env nb_args relname args new_crossed_types
940 (depth + 1) b
941 in
942 (mkGProd (n, new_t, new_b), Id.Set.filter not_free_in_t id_to_exclude)
943 | _ ->
944 (* the first args is the name of the function! *)
945 assert false )
946 | GApp (eq_as_ref, [ty; id; rt])
947 when is_gvar id
948 && is_gr env eq_as_ref Rocqlib.(lib_ref "core.eq.type")
949 && n == Anonymous -> (
950 let loc1 = rt.CAst.loc in
951 let loc2 = eq_as_ref.CAst.loc in
952 let loc3 = id.CAst.loc in
953 let id = match DAst.get id with GVar id -> id | _ -> assert false in
954 try
955 observe (str "computing new type for eq : " ++ pr_glob_constr_env env rt);
956 let t' =
957 try fst (Pretyping.understand env (Evd.from_env env) t) (*FIXME*)
958 with e when CErrors.noncritical e -> raise Continue
959 in
960 let is_in_b = is_free_in id b in
961 let _keep_eq =
962 (not (List.exists (is_free_in id) args))
963 || is_in_b
964 || List.exists (is_free_in id) crossed_types
965 in
966 let new_args = List.map (replace_var_by_term id rt) args in
967 let subst_b = if is_in_b then b else replace_var_by_term id rt b in
968 let r = ERelevance.relevant in
969 (* TODO relevance *)
970 let new_env = EConstr.push_rel (LocalAssum (make_annot n r, t')) env in
971 let new_b, id_to_exclude =
972 rebuild_cons new_env nb_args relname new_args new_crossed_types
973 (depth + 1) subst_b
974 in
975 (mkGProd (n, t, new_b), id_to_exclude)
976 with Continue ->
977 let jmeq = GlobRef.IndRef (fst (EConstr.destInd Evd.empty (jmeq ()))) in
978 let ty', ctx = Pretyping.understand env (Evd.from_env env) ty in
979 let ind, args' =
980 Inductiveops.find_inductive env Evd.(from_env env) ty'
981 in
982 let mib, _ = Inductive.lookup_mind_specif env (fst ind) in
983 let nparam = mib.Declarations.mind_nparams in
984 let params, arg' = Util.List.chop nparam args' in
985 let rt_typ =
986 DAst.make
987 @@ GApp
988 ( DAst.make @@ GRef (GlobRef.IndRef (fst ind), None)
989 , List.map
990 (fun p ->
991 Detyping.detype Detyping.Now env
992 (* XXX should we use full printing flags? *)
993 ~flags:(PrintingFlags.Detype.current())
994 (Evd.from_env env) p)
995 params
996 @ Array.to_list
997 (Array.make (List.length args' - nparam) (mkGHole ())) )
998 in
999 let eq' =
1000 DAst.make ?loc:loc1
1001 @@ GApp
1002 ( DAst.make ?loc:loc2 @@ GRef (jmeq, None)
1003 , [ty; DAst.make ?loc:loc3 @@ GVar id; rt_typ; rt] )
1004 in
1005 observe
1006 (str "computing new type for jmeq : " ++ pr_glob_constr_env env eq');
1007 let eq'_as_constr, ctx =
1008 Pretyping.understand env (Evd.from_env env) eq'
1009 in
1010 observe (str " computing new type for jmeq : done");
1011 let sigma = Evd.(from_env env) in
1012 let new_args =
1013 match EConstr.kind sigma eq'_as_constr with
1014 | App (_, [|_; _; ty; _|]) ->
1015 let ty = Array.to_list (snd (EConstr.destApp sigma ty)) in
1016 let ty' = snd (Util.List.chop nparam ty) in
1017 List.fold_left2
1018 (fun acc var_as_constr arg ->
1019 if EConstr.isRel sigma var_as_constr then
1020 let na =
1021 RelDecl.get_name
1022 (Environ.lookup_rel (EConstr.destRel sigma var_as_constr) env)
1023 in
1024 match na with
1025 | Anonymous -> acc
1026 | Name id' ->
1027 ( id'
1028 , Detyping.detype Detyping.Now env
1029 (* XXX should we use full printing flags? *)
1030 ~flags:(PrintingFlags.Detype.current())
1031 (Evd.from_env env) arg )
1032 :: acc
1033 else if EConstr.isVar sigma var_as_constr then
1034 (EConstr.destVar sigma var_as_constr
1035 , Detyping.detype Detyping.Now env
1036 (* XXX should we use full printing flags? *)
1037 ~flags:(PrintingFlags.Detype.current())
1038 (Evd.from_env env) arg )
1039 :: acc
1040 else acc)
1041 [] arg' ty'
1042 | _ -> assert false
1043 in
1044 let is_in_b = is_free_in id b in
1045 let _keep_eq =
1046 (not (List.exists (is_free_in id) args))
1047 || is_in_b
1048 || List.exists (is_free_in id) crossed_types
1049 in
1050 let new_args =
1051 List.fold_left
1052 (fun args (id, rt) -> List.map (replace_var_by_term id rt) args)
1053 args ((id, rt) :: new_args)
1054 in
1055 let subst_b = if is_in_b then b else replace_var_by_term id rt b in
1056 let new_env =
1057 let t', ctx = Pretyping.understand env (Evd.from_env env) eq' in
1058 let r = ERelevance.relevant in
1059 (* TODO relevance *)
1060 EConstr.push_rel (LocalAssum (make_annot n r, t')) env
1061 in
1062 let new_b, id_to_exclude =
1063 rebuild_cons new_env nb_args relname new_args new_crossed_types
1064 (depth + 1) subst_b
1065 in
1066 (mkGProd (n, eq', new_b), id_to_exclude)
1067 (* J.F:. keep this comment it explain how to remove some meaningless equalities
1068 if keep_eq then
1069 mkGProd(n,t,new_b),id_to_exclude
1070 else new_b, Id.Set.add id id_to_exclude
1071 *) )
1072 | GApp (eq_as_ref, [ty; rt1; rt2])
1073 when is_gr env eq_as_ref Rocqlib.(lib_ref "core.eq.type") && n == Anonymous
1074 -> (
1075 try
1076 let l = decompose_raw_eq env rt1 rt2 in
1077 if List.length l > 1 then
1078 let new_rt =
1079 List.fold_left
1080 (fun acc (lhs, rhs) ->
1081 mkGProd
1082 ( Anonymous
1083 , mkGApp
1084 ( mkGRef Rocqlib.(lib_ref "core.eq.type")
1085 , [mkGHole (); lhs; rhs] )
1086 , acc ))
1087 b l
1088 in
1089 rebuild_cons env nb_args relname args crossed_types depth new_rt
1090 else raise Continue
1091 with Continue -> (
1092 observe
1093 (str "computing new type for prod : " ++ pr_glob_constr_env env rt);
1094 let t', ctx = Pretyping.understand env (Evd.from_env env) t in
1095 let r = ERelevance.relevant in
1096 (* TODO relevance *)
1097 let new_env = EConstr.push_rel (LocalAssum (make_annot n r, t')) env in
1098 let new_b, id_to_exclude =
1099 rebuild_cons new_env nb_args relname args new_crossed_types
1100 (depth + 1) b
1101 in
1102 match n with
1103 | Name id when Id.Set.mem id id_to_exclude && depth >= nb_args ->
1104 (new_b, Id.Set.remove id (Id.Set.filter not_free_in_t id_to_exclude))
1105 | _ -> (mkGProd (n, t, new_b), Id.Set.filter not_free_in_t id_to_exclude) )
1106 )
1107 | _ -> (
1108 observe (str "computing new type for prod : " ++ pr_glob_constr_env env rt);
1109 let t', ctx = Pretyping.understand env (Evd.from_env env) t in
1110 let r = ERelevance.relevant in
1111 (* TODO relevance *)
1112 let new_env = EConstr.push_rel (LocalAssum (make_annot n r, t')) env in
1113 let new_b, id_to_exclude =
1114 rebuild_cons new_env nb_args relname args new_crossed_types (depth + 1)
1115 b
1116 in
1117 match n with
1118 | Name id when Id.Set.mem id id_to_exclude && depth >= nb_args ->
1119 (new_b, Id.Set.remove id (Id.Set.filter not_free_in_t id_to_exclude))
1120 | _ -> (mkGProd (n, t, new_b), Id.Set.filter not_free_in_t id_to_exclude)
1121 ) )
1122 | GLambda (n, _, k, t, b) -> (
1123 let not_free_in_t id = not (is_free_in id t) in
1124 let new_crossed_types = t :: crossed_types in
1125 observe (str "computing new type for lambda : " ++ pr_glob_constr_env env rt);
1126 let t', ctx = Pretyping.understand env (Evd.from_env env) t in
1127 match n with
1128 | Name id ->
1129 let r = ERelevance.relevant in
1130 (* TODO relevance *)
1131 let new_env = EConstr.push_rel (LocalAssum (make_annot n r, t')) env in
1132 let new_b, id_to_exclude =
1133 rebuild_cons new_env nb_args relname
1134 (args @ [mkGVar id])
1135 new_crossed_types (depth + 1) b
1136 in
1137 if Id.Set.mem id id_to_exclude && depth >= nb_args then
1138 (new_b, Id.Set.remove id (Id.Set.filter not_free_in_t id_to_exclude))
1139 else
1140 ( DAst.make @@ GProd (n, None, k, t, new_b)
1141 , Id.Set.filter not_free_in_t id_to_exclude )
1142 | _ -> anomaly (Pp.str "Should not have an anonymous function here.")
1143 (* We have renamed all the anonymous functions during alpha_renaming phase *)
1144 )
1145 | GLetIn (n, _, v, t, b) -> (
1146 let t =
1147 match t with
1148 | None -> v
1149 | Some t -> DAst.make ?loc:rt.loc @@ GCast (v, Some DEFAULTcast, t)
1150 in
1151 let not_free_in_t id = not (is_free_in id t) in
1152 let evd = Evd.from_env env in
1153 let t', ctx = Pretyping.understand env evd t in
1154 let evd = Evd.from_ctx ctx in
1155 let type_t' = Retyping.get_type_of env evd t' in
1156 let new_env =
1157 EConstr.push_rel (LocalDef (make_annot n ERelevance.relevant, t', type_t')) env
1158 in
1159 let new_b, id_to_exclude =
1160 rebuild_cons new_env nb_args relname args (t :: crossed_types) (depth + 1)
1161 b
1162 in
1163 match n with
1164 | Name id when Id.Set.mem id id_to_exclude && depth >= nb_args ->
1165 (new_b, Id.Set.remove id (Id.Set.filter not_free_in_t id_to_exclude))
1166 | _ ->
1167 ( DAst.make @@ GLetIn (n, None, t, None, new_b)
1168 , (* HOPING IT WOULD WORK *)
1169 Id.Set.filter not_free_in_t id_to_exclude ) )
1170 | GLetTuple (nal, (na, rto), t, b) ->
1171 assert (Option.is_empty rto);
1172 let not_free_in_t id = not (is_free_in id t) in
1173 let new_t, id_to_exclude' =
1174 rebuild_cons env nb_args relname args crossed_types depth t
1175 in
1176 let t', ctx = Pretyping.understand env (Evd.from_env env) new_t in
1177 let r = ERelevance.relevant in
1178 (* TODO relevance *)
1179 let new_env = EConstr.push_rel (LocalAssum (make_annot na r, t')) env in
1180 let new_b, id_to_exclude =
1181 rebuild_cons new_env nb_args relname args (t :: crossed_types) (depth + 1)
1182 b
1183 in
1184 (* match n with *)
1185 (* | Name id when Id.Set.mem id id_to_exclude -> *)
1186 (* new_b,Id.Set.remove id (Id.Set.filter not_free_in_t id_to_exclude) *)
1187 (* | _ -> *)
1188 ( DAst.make @@ GLetTuple (nal, (na, None), t, new_b)
1189 , Id.Set.filter not_free_in_t (Id.Set.union id_to_exclude id_to_exclude') )
1190 | _ -> (mkGApp (mkGVar relname, args @ [rt]), Id.Set.empty)
1191
1192 (* debugging wrapper *)
1193 let rebuild_cons env nb_args relname args crossed_types rt =
1194 (* observennl (str "rebuild_cons : rt := "++ pr_glob_constr rt ++ *)
1195 (* str "nb_args := " ++ str (string_of_int nb_args)); *)
1196 let res = rebuild_cons env nb_args relname args crossed_types 0 rt in
1197 (* observe (str " leads to "++ pr_glob_constr (fst res)); *)
1198 res
1199
1200 (* naive implementation of parameter detection.
1201
1202 A parameter is an argument which is only preceded by parameters and whose
1203 calls are all syntactically equal.
1204
1205 TODO: Find a valid way to deal with implicit arguments here!
1206 *)
1207 let rec compute_cst_params relnames params gt =
1208 DAst.with_val
1209 (function
1210 | GRef _ | GVar _ | GEvar _ | GPatVar _
1211 | GInt _ | GFloat _ | GString _ -> params
1212 | GApp (f, args) -> (
1213 match DAst.get f with
1214 | GVar relname' when Id.Set.mem relname' relnames ->
1215 compute_cst_params_from_app [] (params, args)
1216 | _ -> List.fold_left (compute_cst_params relnames) params (f :: args) )
1217 | GProj (f, args, c) ->
1218 List.fold_left (compute_cst_params relnames) params (args @ [c])
1219 | GLambda (_, _, _, t, b) | GProd (_, _, _, t, b) | GLetTuple (_, _, t, b) ->
1220 let t_params = compute_cst_params relnames params t in
1221 compute_cst_params relnames t_params b
1222 | GLetIn (_, _, v, t, b) ->
1223 let v_params = compute_cst_params relnames params v in
1224 let t_params =
1225 Option.fold_left (compute_cst_params relnames) v_params t
1226 in
1227 compute_cst_params relnames t_params b
1228 | GCases _ ->
1229 params
1230 (* If there is still cases at this point they can only be
1231 discrimination ones *)
1232 | GSort _ -> params
1233 | GHole _ -> params
1234 | GGenarg _ -> params
1235 | GIf _ | GRec _ | GCast _ | GArray _ ->
1236 CErrors.user_err (str "Unhandled case."))
1237 gt
1238
1239 and compute_cst_params_from_app acc (params, rtl) =
1240 let is_gid id c =
1241 match DAst.get c with GVar id' -> Id.equal id id' | _ -> false
1242 in
1243 match (params, rtl) with
1244 | _ :: _, [] -> assert false (* the rel has at least nargs + 1 arguments ! *)
1245 | ((Name id, _, None) as param) :: params', c :: rtl' when is_gid id c ->
1246 compute_cst_params_from_app (param :: acc) (params', rtl')
1247 | _ -> List.rev acc
1248
1249 let compute_params_name relnames
1250 (args : (Name.t * Glob_term.glob_constr * glob_constr option) list array)
1251 csts =
1252 let rels_params =
1253 Array.mapi
1254 (fun i args ->
1255 List.fold_left
1256 (fun params (_, cst) -> compute_cst_params relnames params cst)
1257 args csts.(i))
1258 args
1259 in
1260 let l = ref [] in
1261 let _ =
1262 try
1263 List.iteri
1264 (fun i ((n, nt, typ) as param) ->
1265 if
1266 Array.for_all
1267 (fun l ->
1268 let n', nt', typ' = List.nth l i in
1269 Name.equal n n' && glob_constr_eq nt nt'
1270 && Option.equal glob_constr_eq typ typ')
1271 rels_params
1272 then l := param :: !l)
1273 rels_params.(0)
1274 with e when CErrors.noncritical e -> ()
1275 in
1276 List.rev !l
1277
1278 let rec rebuild_return_type rt =
1279 let loc = rt.CAst.loc in
1280 match rt.CAst.v with
1281 | Constrexpr.CProdN (n, t') ->
1282 CAst.make ?loc @@ Constrexpr.CProdN (n, rebuild_return_type t')
1283 | Constrexpr.CLetIn (na, v, t, t') ->
1284 CAst.make ?loc @@ Constrexpr.CLetIn (na, v, t, rebuild_return_type t')
1285 | _ ->
1286 CAst.make ?loc
1287 @@ Constrexpr.CProdN
1288 ( [ Constrexpr.CLocalAssum
1289 ([CAst.make Anonymous], None, Constrexpr.Default Explicit, rt) ]
1290 , CAst.make @@ Constrexpr.CSort Constrexpr_ops.expr_Type_sort )
1291
1292 let do_build_inductive evd (funconstants : pconstant list)
1293 (funsargs : (Name.t * glob_constr * glob_constr option) list list)
1294 returned_types (rtl : glob_constr list) =
1295 let funnames =
1296 List.map
1297 (fun c -> Constant.label (fst c))
1298 funconstants
1299 in
1300 (* Pp.msgnl (prlist_with_sep fnl Printer.pr_glob_constr rtl); *)
1301 let funnames_as_set = List.fold_right Id.Set.add funnames Id.Set.empty in
1302 let funnames = Array.of_list funnames in
1303 let funsargs = Array.of_list funsargs in
1304 let returned_types = Array.of_list returned_types in
1305 (* alpha_renaming of the body to prevent variable capture during manipulation *)
1306 let rtl_alpha = List.map (function rt -> expand_as (alpha_rt [] rt)) rtl in
1307 let rta = Array.of_list rtl_alpha in
1308 (*i The next call to mk_rel_id is valid since we are constructing the graph
1309 Ensures by: obvious
1310 i*)
1311 let relnames = Array.map mk_rel_id funnames in
1312 let relnames_as_set = Array.fold_right Id.Set.add relnames Id.Set.empty in
1313 (* Construction of the pseudo constructors *)
1314 let open Context.Named.Declaration in
1315 let evd, env =
1316 Array.fold_right2
1317 (fun id (c, u) (evd, env) ->
1318 let u = EConstr.EInstance.make u in
1319 let evd, t = Typing.type_of env evd (EConstr.mkConstU (c, u)) in
1320 ( evd
1321 , EConstr.push_named (LocalAssum (make_annot id ERelevance.relevant, t)) env
1322 ))
1323 funnames
1324 (Array.of_list funconstants)
1325 (evd, Global.env ())
1326 in
1327 (* we solve and replace the implicits *)
1328 let rta =
1329 Array.mapi
1330 (fun i rt ->
1331 let _, t =
1332 Typing.type_of env evd
1333 (EConstr.of_constr (mkConstU (Array.of_list funconstants).(i)))
1334 in
1335 resolve_and_replace_implicits t env
1336 evd rt)
1337 rta
1338 in
1339 let resa = Array.map (build_entry_lc env evd funnames_as_set []) rta in
1340 let env_with_graphs =
1341 let rel_arity i funargs =
1342 (* Rebuilding arities (with parameters) *)
1343 let rel_first_args :
1344 (Name.t * Glob_term.glob_constr * Glob_term.glob_constr option) list =
1345 funargs
1346 in
1347 List.fold_right
1348 (fun (n, t, typ) acc ->
1349 match typ with
1350 | Some typ ->
1351 CAst.make
1352 @@ Constrexpr.CLetIn
1353 ( CAst.make n
1354 , Constrextern.extern_glob_constr (extern_env_full_printing()) t
1355 , Some
1356 (Constrextern.extern_glob_constr (extern_env_full_printing()) typ)
1357 , acc )
1358 | None ->
1359 CAst.make
1360 @@ Constrexpr.CProdN
1361 ( [ Constrexpr.CLocalAssum
1362 ( [CAst.make n]
1363 , None
1364 , Constrexpr_ops.default_binder_kind
1365 , Constrextern.extern_glob_constr (extern_env_full_printing()) t ) ]
1366 , acc ))
1367 rel_first_args
1368 (rebuild_return_type returned_types.(i))
1369 in
1370 (* We need to lift back our work topconstr but only with all information
1371 We mimic a Set Printing All.
1372 Then save the graphs and reset Printing options to their primitive values
1373 *)
1374 let rel_arities = Array.mapi rel_arity funsargs in
1375 Util.Array.fold_left2
1376 (fun env rel_name rel_ar ->
1377 let rex =
1378 fst (Constrintern.interp_constr env evd rel_ar)
1379 in
1380 let r = ERelevance.relevant in
1381 (* TODO relevance *)
1382 EConstr.push_named (LocalAssum (make_annot rel_name r, rex)) env)
1383 env relnames rel_arities
1384 in
1385 (* and of the real constructors*)
1386 let constr i res =
1387 List.map
1388 (function
1389 | result (* (args',concl') *) ->
1390 let rt = compose_glob_context result.context result.value in
1391 let nb_args = List.length funsargs.(i) in
1392 (* with_full_print (fun rt -> Pp.msgnl (str "glob constr " ++ pr_glob_constr rt)) rt; *)
1393 fst (rebuild_cons env_with_graphs nb_args relnames.(i) [] [] rt))
1394 res.result
1395 in
1396 (* adding names to constructors *)
1397 let next_constructor_id = ref (-1) in
1398 let mk_constructor_id i =
1399 incr next_constructor_id;
1400 (*i The next call to mk_rel_id is valid since we are constructing the graph
1401 Ensures by: obvious
1402 i*)
1403 Id.of_string
1404 ( Id.to_string (mk_rel_id funnames.(i))
1405 ^ "_"
1406 ^ string_of_int !next_constructor_id )
1407 in
1408 let rel_constructors i rt : (Id.t * glob_constr) list =
1409 next_constructor_id := -1;
1410 List.map (fun constr -> (mk_constructor_id i, constr)) (constr i rt)
1411 in
1412 let rel_constructors = Array.mapi rel_constructors resa in
1413 (* Computing the set of parameters if asked *)
1414 let rels_params =
1415 compute_params_name relnames_as_set funsargs rel_constructors
1416 in
1417 let nrel_params = List.length rels_params in
1418 let rel_constructors =
1419 (* Taking into account the parameters in constructors *)
1420 Array.map
1421 (List.map (fun (id, rt) -> (id, snd (chop_rprod_n nrel_params rt))))
1422 rel_constructors
1423 in
1424 let rel_arity i funargs =
1425 (* Reduilding arities (with parameters) *)
1426 let rel_first_args :
1427 (Name.t * Glob_term.glob_constr * Glob_term.glob_constr option) list =
1428 snd (List.chop nrel_params funargs)
1429 in
1430 List.fold_right
1431 (fun (n, t, typ) acc ->
1432 match typ with
1433 | Some typ ->
1434 CAst.make
1435 @@ Constrexpr.CLetIn
1436 ( CAst.make n
1437 , Constrextern.extern_glob_constr (extern_env_full_printing()) t
1438 , Some
1439 (Constrextern.extern_glob_constr (extern_env_full_printing()) typ)
1440 , acc )
1441 | None ->
1442 CAst.make
1443 @@ Constrexpr.CProdN
1444 ( [ Constrexpr.CLocalAssum
1445 ( [CAst.make n]
1446 , None
1447 , Constrexpr_ops.default_binder_kind
1448 , Constrextern.extern_glob_constr (extern_env_full_printing()) t ) ]
1449 , acc ))
1450 rel_first_args
1451 (rebuild_return_type returned_types.(i))
1452 in
1453 (* We need to lift back our work topconstr but only with all information
1454 We mimic a Set Printing All.
1455 Then save the graphs and reset Printing options to their primitive values
1456 *)
1457 let rel_arities = Array.mapi rel_arity funsargs in
1458 let rel_params_ids =
1459 List.fold_left
1460 (fun acc (na, _, _) ->
1461 match na with Anonymous -> acc | Name id -> id :: acc)
1462 [] rels_params
1463 in
1464 let rel_params =
1465 List.map
1466 (fun (n, t, typ) ->
1467 match typ with
1468 | Some typ ->
1469 Constrexpr.CLocalDef
1470 ( CAst.make n
1471 , None
1472 , Constrextern.(extern_glob_constr (extern_env_full_printing())) t
1473 , Some
1474 (Constrextern.extern_glob_constr (extern_env_full_printing()) typ) )
1475 | None ->
1476 Constrexpr.CLocalAssum
1477 ( [CAst.make n]
1478 , None
1479 , Constrexpr_ops.default_binder_kind
1480 , Constrextern.(extern_glob_constr (extern_env_full_printing())) t ))
1481 rels_params
1482 in
1483 let ext_rels_constructors =
1484 Array.map
1485 (List.map (fun (id, t) ->
1486 ( Vernacexpr.([], NoCoercion, NoInstance)
1487 , ( CAst.make id
1488 , Constrextern.extern_glob_type (extern_env_full_printing())
1489 ((* zeta_normalize *) alpha_rt rel_params_ids t) ) )))
1490 rel_constructors
1491 in
1492 let rel_ind i ext_rel_constructors =
1493 ( ( CAst.make @@ relnames.(i)
1494 , (rel_params, None)
1495 , Some rel_arities.(i)
1496 , ext_rel_constructors )
1497 , [] )
1498 in
1499 let ext_rel_constructors = Array.mapi rel_ind ext_rels_constructors in
1500 let rel_inds = Array.to_list ext_rel_constructors in
1501 (* let _ = *)
1502 (* Pp.msgnl (\* observe *\) ( *)
1503 (* str "Inductive" ++ spc () ++ *)
1504 (* prlist_with_sep *)
1505 (* (fun () -> fnl ()++spc () ++ str "with" ++ spc ()) *)
1506 (* (function ((_,id),_,params,ar,constr) -> *)
1507 (* Ppconstr.pr_id id ++ spc () ++ *)
1508 (* Ppconstr.pr_binders params ++ spc () ++ *)
1509 (* str ":" ++ spc () ++ *)
1510 (* Ppconstr.pr_lconstr_expr ar ++ spc () ++ str ":=" ++ *)
1511 (* prlist_with_sep *)
1512 (* (fun _ -> fnl () ++ spc () ++ str "|" ++ spc ()) *)
1513 (* (function (_,((_,id),t)) -> *)
1514 (* Ppconstr.pr_id id ++ spc () ++ str ":" ++ spc () ++ *)
1515 (* Ppconstr.pr_lconstr_expr t) *)
1516 (* constr *)
1517 (* ) *)
1518 (* rel_inds *)
1519 (* ) *)
1520 (* in *)
1521 try
1522 let flags = {
1523 ComInductive.poly = PolyFlags.default;
1524 template = Some false;
1525 finite = Finite;
1526 mode = None;
1527 schemes = Default;
1528 }
1529 in
1530 without_implicit_declarations
1531 (Flags.silently
1532 (fun () ->
1533 ComInductive.do_mutual_inductive ~flags
1534 None rel_inds
1535 ~private_ind:false
1536 ~uniform:ComInductive.NonUniformParameters))
1537 ()
1538 with
1539 | UserError msg as e ->
1540 let repacked_rel_inds =
1541 List.map
1542 (fun ((a, b, c, l), ntn) ->
1543 (Vernacexpr.((NoCoercion, (a, None)), b, c, Constructors l), ntn))
1544 rel_inds
1545 in
1546 let msg =
1547 str "while trying to define"
1548 ++ spc ()
1549 ++ Ppvernac.pr_vernac
1550 (CAst.make
1551 Vernacexpr.
1552 { control = []
1553 ; attrs = []
1554 ; expr =
1555 VernacSynPure (VernacInductive (Vernacexpr.Inductive_kw, repacked_rel_inds))
1556 })
1557 ++ fnl () ++ msg
1558 in
1559 observe msg; raise e
1560 | reraise ->
1561 let repacked_rel_inds =
1562 List.map
1563 (fun ((a, b, c, l), ntn) ->
1564 (Vernacexpr.((NoCoercion, (a, None)), b, c, Constructors l), ntn))
1565 rel_inds
1566 in
1567 let msg =
1568 str "while trying to define"
1569 ++ spc ()
1570 ++ Ppvernac.pr_vernac
1571 ( CAst.make
1572 @@ Vernacexpr.
1573 { control = []
1574 ; attrs = []
1575 ; expr =
1576 VernacSynPure (VernacInductive (Vernacexpr.Inductive_kw, repacked_rel_inds))
1577 } )
1578 ++ fnl () ++ CErrors.print reraise
1579 in
1580 observe msg; raise reraise
1581
1582 let build_inductive evd funconstants funsargs returned_types rtl =
1583 (* XXX pass functionally (is it just the marked XXX near Detype.current calls?) *)
1584 let pu = !PrintingFlags.print_universes in
1585 try
1586 PrintingFlags.print_universes := true;
1587 do_build_inductive evd funconstants funsargs returned_types rtl;
1588 PrintingFlags.print_universes := pu;
1589 with e when CErrors.noncritical e ->
1590 PrintingFlags.print_universes := pu;
1591 raise (Building_graph e)