Debian Codegraph @

plugins/extraction/extraction.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 (*i*)
12 open Util
13 open Names
14 open Term
15 open Constr
16 open Context
17 open Declarations
18 open Declareops
19 open Environ
20 open Reductionops
21 open Retyping
22 open Inductiveops
23 open Namegen
24 open Miniml
25 open Table
26 open Mlutil
27 open Context.Rel.Declaration
28 (*i*)
29
30 exception I of inductive_kind
31
32 (* A set of all fixpoint functions currently being extracted *)
33 let current_fixpoints = ref ([] : Constant.t list)
34
35 (* NB: In OCaml, [type_of] and [get_of] might raise
36 [SingletonInductiveBecomeProp]. This exception will be caught
37 in late wrappers around the exported functions of this file,
38 in order to display the location of the issue. *)
39
40 let type_of env sg c =
41 let polyprop = (lang() == Haskell) in
42 Retyping.get_type_of ~polyprop env sg (Termops.strip_outer_cast sg c)
43
44 let sort_of env sg c =
45 let polyprop = (lang() == Haskell) in
46 Retyping.get_sort_quality_of ~polyprop env sg (Termops.strip_outer_cast sg c)
47
48 (*S Generation of flags and signatures. *)
49
50 (* The type [flag] gives us information about any Rocq term:
51 \begin{itemize}
52 \item [TypeScheme] denotes a type scheme, that is
53 something that will become a type after enough applications.
54 More formally, a type scheme has type $(x_1:X_1)\ldots(x_n:X_n)s$ with
55 [s = Set], [Prop] or [Type]
56 \item [Default] denotes the other cases. It may be inexact after
57 instantiation. For example [(X:Type)X] is [Default] and may give [Set]
58 after instantiation, which is rather [TypeScheme]
59 \item [Logic] denotes a term of sort [Prop], or a type scheme on sort [Prop]
60 \item [Info] is the opposite. The same example [(X:Type)X] shows
61 that an [Info] term might in fact be [Logic] later on.
62 \end{itemize} *)
63
64 type info = Logic | Info
65
66 type scheme = TypeScheme | Default
67
68 type flag = info * scheme
69
70 (*s [flag_of_type] transforms a type [t] into a [flag].
71 Really important function. *)
72
73 let info_of_quality = let open UnivGen.QualityOrSet in function
74 | Qual (QConstant QSProp | QConstant QProp) -> Logic
75 | Set | Qual (QConstant QType | QVar _) -> Info
76
77 let info_of_sort s = info_of_quality (UnivGen.QualityOrSet.of_sort s)
78
79 let rec flag_of_type env sg t : flag =
80 let t = whd_all env sg t in
81 match EConstr.kind sg t with
82 | Prod (x,t,c) -> flag_of_type (EConstr.push_rel (LocalAssum (x,t)) env) sg c
83 | Sort s -> (info_of_sort (EConstr.ESorts.kind sg s),TypeScheme)
84 | _ -> (info_of_quality (sort_of env sg t),Default)
85
86 (*s Two particular cases of [flag_of_type]. *)
87
88 let is_default env sg t = match flag_of_type env sg t with
89 | (Info, Default) -> true
90 | _ -> false
91
92 exception NotDefault of kill_reason
93
94 let check_default env sg t =
95 match flag_of_type env sg t with
96 | _,TypeScheme -> raise (NotDefault Ktype)
97 | Logic,_ -> raise (NotDefault Kprop)
98 | _ -> ()
99
100 let is_info_scheme env sg t = match flag_of_type env sg t with
101 | (Info, TypeScheme) -> true
102 | _ -> false
103
104 let push_rel_assum (n, t) env =
105 EConstr.push_rel (LocalAssum (n, t)) env
106
107 let push_rels_assum assums =
108 EConstr.push_rel_context (List.map (fun (x,t) -> LocalAssum (x,t)) assums)
109
110 let qmono uctx inst lconstr = match uctx with
111 | Monomorphic -> EConstr.of_constr lconstr
112 | Polymorphic uctx ->
113 let inst = InfvInst.instantiate uctx inst in
114 let lconstr = Vars.subst_instance_constr inst lconstr in
115 EConstr.of_constr lconstr
116
117 let get_opaque access env c =
118 EConstr.of_constr
119 (fst (Global.force_proof access c))
120
121 let applistc c args = EConstr.mkApp (c, Array.of_list args)
122
123 (* Same as [Environ.push_rec_types], but for [EConstr.t] *)
124 let push_rec_types (lna,typarray,_) env =
125 let ctxt =
126 Array.map2_i
127 (fun i na t -> LocalAssum (na, EConstr.Vars.lift i t)) lna typarray
128 in
129 Array.fold_left (fun e assum -> EConstr.push_rel assum e) env ctxt
130
131 (* Same as [Termops.nb_lam], but for [EConstr.t] *)
132 let nb_lam sg c = List.length (fst (EConstr.decompose_lambda sg c))
133
134 (* Same as [Term.decompose_lambda_n] but for [EConstr.t] *)
135 let decompose_lambda_n sg n =
136 let rec lamdec_rec l n c =
137 if n <= 0 then l,c
138 else match EConstr.kind sg c with
139 | Lambda (x,t,c) -> lamdec_rec ((x,t)::l) (n-1) c
140 | Cast (c,_,_) -> lamdec_rec l n c
141 | _ -> raise Not_found
142 in
143 lamdec_rec [] n
144
145 (*s [type_sign] gernerates a signature aimed at treating a type application. *)
146
147 let rec type_sign env sg c =
148 match EConstr.kind sg (whd_all env sg c) with
149 | Prod (n,t,d) ->
150 (if is_info_scheme env sg t then Keep else Kill Kprop)
151 :: (type_sign (push_rel_assum (n,t) env) sg d)
152 | _ -> []
153
154 let rec type_scheme_nb_args env sg c =
155 match EConstr.kind sg (whd_all env sg c) with
156 | Prod (n,t,d) ->
157 let n = type_scheme_nb_args (push_rel_assum (n,t) env) sg d in
158 if is_info_scheme env sg t then n+1 else n
159 | _ -> 0
160
161 let type_scheme_nb_args' env c =
162 type_scheme_nb_args env (Evd.from_env env) (EConstr.of_constr c)
163
164 let _ = Hook.set type_scheme_nb_args_hook type_scheme_nb_args'
165
166 (*s [type_sign_vl] does the same, plus a type var list. *)
167
168 (* When generating type variables, we avoid any ' in their names
169 (otherwise this may cause a lexer conflict in ocaml with 'a').
170 We also get rid of unicode characters. Anyway, since type variables
171 are local, the created name is just a matter of taste...
172 See also Bug #3227 *)
173
174 let make_typvar n vl =
175 let id = id_of_name n in
176 let id' =
177 let s = Id.to_string id in
178 if not (String.contains s '\'') && Unicode.is_basic_ascii s then id
179 else id_of_name Anonymous
180 in
181 let vl = Id.Set.of_list vl in
182 next_ident_away id' vl
183
184 let rec type_sign_vl env sg c =
185 match EConstr.kind sg (whd_all env sg c) with
186 | Prod (n,t,d) ->
187 let s,vl = type_sign_vl (push_rel_assum (n,t) env) sg d in
188 if not (is_info_scheme env sg t) then Kill Kprop::s, vl
189 else Keep::s, (make_typvar n.binder_name vl) :: vl
190 | _ -> [],[]
191
192 let rec nb_default_params env sg c =
193 match EConstr.kind sg (whd_all env sg c) with
194 | Prod (n,t,d) ->
195 let n = nb_default_params (push_rel_assum (n,t) env) sg d in
196 if is_default env sg t then n+1 else n
197 | _ -> 0
198
199 (* Enriching a signature with implicit information *)
200
201 let sign_with_implicits r s nb_params =
202 let implicits = implicits_of_global r in
203 let rec add_impl i = function
204 | [] -> []
205 | Keep::s when Int.Set.mem i implicits ->
206 Kill (Kimplicit (r,i)) :: add_impl (i+1) s
207 | sign::s -> sign :: add_impl (i+1) s
208 in
209 add_impl (1+nb_params) s
210
211 (*S Management of type variable contexts. *)
212
213 (* A De Bruijn variable context (db) is a context for translating Rocq [Rel]
214 into ML type [Tvar]. *)
215
216 (*s From a type signature toward a type variable context (db). *)
217
218 let db_from_sign s =
219 let rec make i acc = function
220 | [] -> acc
221 | Keep :: l -> make (i+1) (i::acc) l
222 | Kill _ :: l -> make i (0::acc) l
223 in make 1 [] s
224
225 (*s Create a type variable context from indications taken from
226 an inductive type (see just below). *)
227
228 let rec db_from_ind dbmap i =
229 if Int.equal i 0 then []
230 else (try Int.Map.find i dbmap with Not_found -> 0)::(db_from_ind dbmap (i-1))
231
232 (*s [parse_ind_args] builds a map: [i->j] iff the i-th Rocq argument
233 of a constructor corresponds to the j-th type var of the ML inductive. *)
234
235 (* \begin{itemize}
236 \item [si] : signature of the inductive
237 \item [i] : counter of Rocq args for [(I args)]
238 \item [j] : counter of ML type vars
239 \item [relmax] : total args number of the constructor
240 \end{itemize} *)
241
242 let parse_ind_args si args relmax =
243 let rec parse i j = function
244 | [] -> Int.Map.empty
245 | Kill _ :: s -> parse (i+1) j s
246 | Keep :: s ->
247 (match Constr.kind args.(i-1) with
248 | Rel k -> Int.Map.add (relmax+1-k) j (parse (i+1) (j+1) s)
249 | _ -> parse (i+1) (j+1) s)
250 in parse 1 1 si
251
252 let relevance_of_projection_repr mip p =
253 match mip.mind_record with
254 | NotRecord | FakeRecord ->
255 CErrors.anomaly ~label:"relevance_of_projection" Pp.(str "not a projection")
256 | PrimRecord { relevances; _ } ->
257 relevances.(Names.Projection.Repr.arg p)
258
259 (** Because of automatic unboxing the easy way [mk_def c] on the
260 constant body of primitive projections doesn't work. We pretend
261 that they are implemented by matches until someone figures out how
262 to clean it up (test with #4710 when working on this). *)
263 let fake_match_projection env p =
264 let ind = Projection.Repr.inductive p in
265 let proj_arg = Projection.Repr.arg p in
266 let mib, mip = Inductive.lookup_mind_specif env ind in
267 let u = UVars.make_abstract_instance (Declareops.inductive_polymorphic_context mib) in
268 let indu = mkIndU (ind,u) in
269 let ctx, paramslet =
270 let ntypes = Declareops.mind_ntypes mib in
271 let subst = List.init ntypes (fun i -> mkIndU ((fst ind, ntypes - i - 1), u)) in
272 let (ctx, cty) = mip.mind_nf_lc.(0) in
273 let cty = Term.it_mkProd_or_LetIn cty ctx in
274 let rctx, _ = decompose_prod_decls (Vars.substl subst cty) in
275 List.chop mip.mind_consnrealdecls.(0) rctx
276 in
277 let ci_pp_info = { style = LetStyle } in
278 let ci = {
279 ci_ind = ind;
280 ci_npar = mib.mind_nparams;
281 ci_cstr_ndecls = mip.mind_consnrealdecls;
282 ci_cstr_nargs = mip.mind_consnrealargs;
283 ci_pp_info;
284 }
285 in
286 let relevance = relevance_of_projection_repr mip p in
287 let x = match mip.mind_record with
288 | NotRecord | FakeRecord -> assert false
289 | PrimRecord { id; _ } ->
290 make_annot (Name id) mip.mind_relevance
291 in
292 let indty = mkApp (indu, Context.Rel.instance mkRel 0 paramslet) in
293 let rec fold arg j subst = function
294 | [] -> assert false
295 | LocalAssum (na,ty) :: rem ->
296 let ty = Vars.substl subst (liftn 1 j ty) in
297 if arg != proj_arg then
298 let lab = match na.binder_name with Name id -> id | Anonymous -> assert false in
299 let kn = Projection.Repr.make ind ~proj_npars:mib.mind_nparams ~proj_arg:arg lab in
300 fold (arg+1) (j+1) (mkProj (Projection.make kn false, na.binder_relevance, mkRel 1)::subst) rem
301 else
302 let p = ([|x|], liftn 1 2 ty) in
303 let branch =
304 let nas = Array.of_list (List.rev_map Context.Rel.Declaration.get_annot ctx) in
305 (nas, mkRel (List.length ctx - (j - 1)))
306 in
307 let params = Context.Rel.instance mkRel 1 paramslet in
308 let body = mkCase (ci, u, params, (p,relevance), NoInvert, mkRel 1, [|branch|]) in
309 it_mkLambda_or_LetIn (mkLambda (x,indty,body)) mib.mind_params_ctxt
310 | LocalDef (_,c,t) :: rem ->
311 let c = liftn 1 j c in
312 let c1 = Vars.substl subst c in
313 fold arg (j+1) (c1::subst) rem
314 in
315 fold 0 1 [] (List.rev ctx)
316
317 (*S Extraction of a type. *)
318
319 (* [extract_type env db c args] is used to produce an ML type from the
320 coq term [(c args)], which is supposed to be a Rocq type. *)
321
322 (* [db] is a context for translating Rocq [Rel] into ML type [Tvar]. *)
323
324 (* [j] stands for the next ML type var. [j=0] means we do not
325 generate ML type var anymore (in subterms for example). *)
326
327
328 let rec extract_type (table : Common.State.t) env sg db j c args =
329 match EConstr.kind sg (whd_betaiotazeta env sg c) with
330 | App (d, args') ->
331 (* We just accumulate the arguments. *)
332 extract_type table env sg db j d (Array.to_list args' @ args)
333 | Lambda (_,_,d) ->
334 (match args with
335 | [] -> assert false (* A lambda cannot be a type. *)
336 | a :: args -> extract_type table env sg db j (EConstr.Vars.subst1 a d) args)
337 | Prod (n,t,d) ->
338 assert (List.is_empty args);
339 let env' = push_rel_assum (n,t) env in
340 (match flag_of_type env sg t with
341 | (Info, Default) ->
342 (* Standard case: two [extract_type] ... *)
343 let mld = extract_type table env' sg (0::db) j d [] in
344 (match expand table env mld with
345 | Tdummy d -> Tdummy d
346 | _ -> Tarr (extract_type table env sg db 0 t [], mld))
347 | (Info, TypeScheme) when j > 0 ->
348 (* A new type var. *)
349 let mld = extract_type table env' sg (j::db) (j+1) d [] in
350 (match expand table env mld with
351 | Tdummy d -> Tdummy d
352 | _ -> Tarr (Tdummy Ktype, mld))
353 | _,lvl ->
354 let mld = extract_type table env' sg (0::db) j d [] in
355 (match expand table env mld with
356 | Tdummy d -> Tdummy d
357 | _ ->
358 let reason = if lvl == TypeScheme then Ktype else Kprop in
359 Tarr (Tdummy reason, mld)))
360 | Sort _ -> Tdummy Ktype (* The two logical cases. *)
361 | _ when info_of_quality (sort_of env sg (applistc c args)) == Logic -> Tdummy Kprop
362 | Rel n ->
363 (match EConstr.lookup_rel n env with
364 | LocalDef (_,t,_) ->
365 extract_type table env sg db j (EConstr.Vars.lift n t) args
366 | _ ->
367 (* Asks [db] a translation for [n]. *)
368 if n > List.length db then Tunknown
369 else let n' = List.nth db (n-1) in
370 if Int.equal n' 0 then Tunknown else Tvar n')
371 | Const (kn,u) ->
372 let inst = InfvInst.ground (EConstr.EInstance.kind sg u) in
373 let r = { glob = GlobRef.ConstRef kn; inst } in
374 let typ = type_of env sg (EConstr.mkConstU (kn,u)) in
375 (match flag_of_type env sg typ with
376 | (Logic,_) -> assert false (* Cf. logical cases above *)
377 | (Info, TypeScheme) ->
378 let mlt = extract_type_app table env sg db (r, type_sign env sg typ) args in
379 mlt
380 | (Info, Default) ->
381 (* Not an ML type, for example [(c:forall X, X->X) Type nat] *)
382 let cb = lookup_constant kn env in
383 (match cb.const_body with
384 | Undef _ | OpaqueDef _ | Primitive _ | Symbol _ -> Tunknown (* Brutal approx ... *)
385 | Def lbody ->
386 (* We try to reduce. *)
387 let newc = applistc (qmono cb.const_universes inst lbody) args in
388 extract_type table env sg db j newc []))
389 | Ind ((kn, i), u) ->
390 let inst = InfvInst.ground (EConstr.EInstance.kind sg u) in
391 let r = { glob = GlobRef.IndRef (kn, i); inst } in
392 let s = (extract_ind table env kn inst).ind_packets.(i).ip_sign in
393 extract_type_app table env sg db (r, s) args
394 | Proj (p,r,t) ->
395 (* Let's try to reduce, if it hasn't already been done. *)
396 if Projection.unfolded p then Tunknown
397 else
398 extract_type table env sg db j (EConstr.mkProj (Projection.unfold p, r, t)) args
399 | Case _ | Fix _ | CoFix _ -> Tunknown
400 | Evar _ | Meta _ -> Taxiom (* only possible during Show Extraction *)
401 | Var v ->
402 (* For Show Extraction *)
403 let open Context.Named.Declaration in
404 (match EConstr.lookup_named v env with
405 | LocalDef (_,body,_) ->
406 extract_type table env sg db j (EConstr.applist (body,args)) []
407 | LocalAssum (_,ty) ->
408 let r = { glob = GlobRef.VarRef v; inst = InfvInst.empty } in
409 (match flag_of_type env sg ty with
410 | (Logic,_) -> assert false (* Cf. logical cases above *)
411 | (Info, TypeScheme) ->
412 extract_type_app table env sg db (r, type_sign env sg ty) args
413 | (Info, Default) -> Tunknown))
414 | Cast _ | LetIn _ | Construct _ | Int _ | Float _ | String _ | Array _ -> assert false
415
416 (*s Auxiliary function dealing with type application.
417 Precondition: [r] is a type scheme represented by the signature [s],
418 and is completely applied: [List.length args = List.length s]. *)
419
420 and extract_type_app table env sg db (r,s) args =
421 let ml_args =
422 List.fold_right
423 (fun (b,c) a -> if b == Keep then
424 let p = List.length (fst (whd_decompose_prod env sg (type_of env sg c))) in
425 let db = iterate (fun l -> 0 :: l) p db in
426 (extract_type_scheme table env sg db c p) :: a
427 else a)
428 (List.combine s args) []
429 in Tglob (r, ml_args)
430
431 (*S Extraction of a type scheme. *)
432
433 (* [extract_type_scheme env db c p] works on a Rocq term [c] which is
434 an informative type scheme. It means that [c] is not a Rocq type, but will
435 be when applied to sufficiently many arguments ([p] in fact).
436 This function decomposes p lambdas, with eta-expansion if needed. *)
437
438 (* [db] is a context for translating Rocq [Rel] into ML type [Tvar]. *)
439
440 and extract_type_scheme table env sg db c p =
441 if Int.equal p 0 then extract_type table env sg db 0 c []
442 else
443 let c = whd_betaiotazeta env sg c in
444 match EConstr.kind sg c with
445 | Lambda (n,t,d) ->
446 extract_type_scheme table (push_rel_assum (n,t) env) sg db d (p-1)
447 | _ ->
448 let rels = fst (whd_decompose_prod env sg (type_of env sg c)) in
449 let env = push_rels_assum rels env in
450 let eta_args = List.rev_map EConstr.mkRel (List.interval 1 p) in
451 extract_type table env sg db 0 (EConstr.Vars.lift p c) eta_args
452
453
454 (*S Extraction of an inductive type. *)
455
456 (* First, a version with cache *)
457
458 and extract_ind table env kn inst = (* kn is supposed to be in long form *)
459 let mib = Environ.lookup_mind kn env in
460 match lookup_ind (Common.State.get_table table) kn inst mib with
461 | Some ml_ind -> ml_ind
462 | None ->
463 try
464 extract_really_ind table env kn inst mib
465 with SingletonInductiveBecomesProp ind ->
466 error_singleton_become_prop ind
467
468 (* Then the real function *)
469
470 and extract_really_ind table env kn inst mib =
471 (* First, if this inductive is aliased via a Module,
472 we process the original inductive if possible.
473 When at toplevel of the monolithic case, we cannot do much
474 (cf Vector and bug #2570) *)
475 let equiv =
476 if lang () != Ocaml ||
477 (not (Common.State.get_modular table) && at_toplevel (MutInd.modpath kn)) ||
478 KerName.equal (MutInd.canonical kn) (MutInd.user kn)
479 then
480 NoEquiv
481 else
482 begin
483 ignore (extract_ind table env (MutInd.make1 (MutInd.canonical kn)) inst);
484 Equiv (MutInd.canonical kn)
485 end
486 in
487 let env, u = match mib.mind_universes with
488 | Monomorphic -> env, UVars.Instance.empty
489 | Polymorphic uctx ->
490 (* FIXME: we should probably push the levels *)
491 env, InfvInst.instantiate uctx inst
492 in
493 (* Everything concerning parameters. *)
494 (* We do that first, since they are common to all the [mib]. *)
495 let mip0 = mib.mind_packets.(0) in
496 let ndecls = List.length mib.mind_params_ctxt in
497 let npar = mib.mind_nparams in
498 let epar = push_rel_context (Vars.subst_instance_context u mib.mind_params_ctxt) env in
499 let sg = Evd.from_env env in
500 (* First pass: we store inductive signatures together with *)
501 (* their type var list. *)
502 let packets =
503 Array.mapi
504 (fun i mip ->
505 let ar = Inductive.type_of_inductive ((mib,mip),u) in
506 let ar = EConstr.of_constr ar in
507 let info = (fst (flag_of_type env sg ar) = Info) in
508 let s,v = if info then type_sign_vl env sg ar else [],[] in
509 let ncons = Array.length mip.mind_nf_lc in
510 let t = Array.make ncons [] in
511 { ip_typename = mip.mind_typename;
512 ip_typename_ref = { glob = GlobRef.IndRef (kn, i); inst };
513 ip_consnames = mip.mind_consnames;
514 ip_consnames_ref = Array.init ncons (fun j -> { glob = GlobRef.ConstructRef ((kn, i), j + 1); inst });
515 ip_logical = not info;
516 ip_sign = s;
517 ip_vars = v;
518 ip_types = t }, u)
519 mib.mind_packets
520 in
521
522 add_ind (Common.State.get_table table) kn inst mib
523 {ind_kind = Standard;
524 ind_nparams = npar;
525 ind_packets = Array.map fst packets;
526 ind_equiv = equiv
527 };
528 (* Second pass: we extract constructors *)
529 let () = packets |> Array.iteri @@ fun i (p,u) ->
530 if not p.ip_logical then
531 let types = Inductive.arities_of_constructors ((kn,i),u) (mib, mib.mind_packets.(i)) in
532 for j = 0 to Array.length types - 1 do
533 let t = snd (decompose_prod_n_decls ndecls types.(j)) in
534 let prods,head = Reduction.whd_decompose_prod epar t in
535 let nprods = List.length prods in
536 let args = match Constr.kind head with
537 | App (f,args) -> args (* [Constr.kind f = Ind ip] *)
538 | _ -> [||]
539 in
540 let dbmap = parse_ind_args p.ip_sign args (nprods + ndecls) in
541 let db = db_from_ind dbmap ndecls in
542 p.ip_types.(j) <-
543 extract_type_cons table epar sg db dbmap (EConstr.of_constr t) (ndecls+1)
544 done
545 in
546 (* Third pass: we determine special cases. *)
547 let ind_info =
548 try
549 let ip = (kn, 0) in
550 let r = { glob = GlobRef.IndRef ip; inst } in
551 if is_custom r then raise (I Standard);
552 if mib.mind_finite == CoFinite then raise (I Coinductive);
553 if not (Int.equal (Declareops.mind_ntypes mib) 1) then raise (I Standard);
554 let p,u = packets.(0) in
555 if p.ip_logical then raise (I Standard);
556 if not (Int.equal (Array.length p.ip_types) 1) then raise (I Standard);
557 let typ = p.ip_types.(0) in
558 let l = if conservative_types () then [] else List.filter (fun t -> not (isTdummy (expand table env t))) typ in
559 if List.is_empty l then raise (I Standard);
560 if mip0.mind_record == Declarations.NotRecord then
561 if not (keep_singleton ()) && Int.equal (List.length l) 1 && not (type_mem_kn kn (List.hd l))
562 then raise (I Singleton)
563 else raise (I Standard);
564 (* Now we're sure it's a record. *)
565 (* First, we find its field names. *)
566 let rec names_prod t = match Constr.kind t with
567 | Prod(n,_,t) -> n::(names_prod t)
568 | LetIn(_,_,_,t) -> names_prod t
569 | Cast(t,_,_) -> names_prod t
570 | _ -> []
571 in
572 let field_names =
573 List.skipn mib.mind_nparams (names_prod mip0.mind_user_lc.(0)) in
574 assert (Int.equal (List.length field_names) (List.length typ));
575 let mp = MutInd.modpath kn in
576 let implicits = implicits_of_global { glob = (GlobRef.ConstructRef (ip,1)); inst } in
577 let ty = Inductive.type_of_inductive ((mib,mip0),u) in
578 let nparams = nb_default_params env sg (EConstr.of_constr ty) in
579 let rec select_fields i l typs = match l,typs with
580 | [],[] -> []
581 | _::l, typ::typs when isTdummy (expand table env typ) || Int.Set.mem i implicits ->
582 select_fields (i+1) l typs
583 | {binder_name=Anonymous}::l, typ::typs ->
584 None :: (select_fields (i+1) l typs)
585 | {binder_name=Name id}::l, typ::typs ->
586 let knp = Constant.make2 mp id in
587 (* Is it safe to use [id] for projections [foo.id] ? *)
588 if List.for_all ((==) Keep) (type2signature table env typ)
589 then (* for OCaml inlining: *) add_projection (Common.State.get_table table) nparams knp ip;
590 Some { glob = GlobRef.ConstRef knp; inst } :: (select_fields (i+1) l typs)
591 | _ -> assert false
592 in
593 let field_glob = select_fields (1+npar) field_names typ in
594 if not (keep_singleton ()) && Int.equal (List.length l) 1 && not (type_mem_kn kn (List.hd l))
595 then Singleton (* in passing, we registered the (identity) projection *)
596 else Record field_glob
597 with (I info) -> info
598 in
599 let i = {ind_kind = ind_info;
600 ind_nparams = npar;
601 ind_packets = Array.map fst packets;
602 ind_equiv = equiv }
603 in
604 add_ind (Common.State.get_table table) kn inst mib i;
605 add_inductive_kind (Common.State.get_table table) kn inst i.ind_kind;
606 i
607
608 (*s [extract_type_cons] extracts the type of an inductive
609 constructor toward the corresponding list of ML types.
610
611 - [db] is a context for translating Rocq [Rel] into ML type [Tvar]
612 - [dbmap] is a translation map (produced by a call to [parse_in_args])
613 - [i] is the rank of the current product (initially [params_nb+1])
614 *)
615
616 and extract_type_cons table env sg db dbmap c i =
617 match EConstr.kind sg (whd_all env sg c) with
618 | Prod (n,t,d) ->
619 let env' = push_rel_assum (n,t) env in
620 let db' = (try Int.Map.find i dbmap with Not_found -> 0) :: db in
621 let l = extract_type_cons table env' sg db' dbmap d (i+1) in
622 (extract_type table env sg db 0 t []) :: l
623 | _ -> []
624
625 (*s Recording the ML type abbreviation of a Rocq type scheme constant. *)
626
627 and mlt_env table env r = let open GlobRef in match r.glob with
628 | IndRef _ | ConstructRef _ | VarRef _ -> None
629 | ConstRef kn ->
630 let cb = Environ.lookup_constant kn env in
631 match cb.const_body with
632 | Undef _ | OpaqueDef _ | Primitive _ | Symbol _ -> None
633 | Def l_body ->
634 match lookup_typedef (Common.State.get_table table) kn r.inst cb with
635 | Some _ as o -> o
636 | None ->
637 let sg = Evd.from_env env in
638 let typ = EConstr.of_constr cb.const_type
639 (* FIXME not sure if we should instantiate univs here *) in
640 match flag_of_type env sg typ with
641 | Info,TypeScheme ->
642 let body = qmono cb.const_universes r.inst l_body in
643 let s = type_sign env sg typ in
644 let db = db_from_sign s in
645 let t = extract_type_scheme table env sg db body (List.length s)
646 in add_typedef (Common.State.get_table table) kn r.inst cb t; Some t
647 | _ -> None
648
649 and expand table env = type_expand (mlt_env table env)
650 and type2signature table env = type_to_signature (mlt_env table env)
651 let type2sign table env = type_to_sign (mlt_env table env)
652 let type_expunge table env = type_expunge (mlt_env table env)
653 let type_expunge_from_sign table env = type_expunge_from_sign (mlt_env table env)
654
655 (*s Extraction of the type of a constant. *)
656
657 let record_constant_type table env sg kn inst opt_typ =
658 let cb = lookup_constant kn env in
659 match lookup_cst_type (Common.State.get_table table) kn inst cb with
660 | Some schema -> schema
661 | None ->
662 let typ = match opt_typ with
663 | None -> qmono cb.const_universes inst cb.const_type
664 | Some typ -> typ
665 in
666 let mlt = extract_type table env sg [] 1 typ [] in
667 let schema = (type_maxvar mlt, mlt) in
668 let () = add_cst_type (Common.State.get_table table) kn inst cb schema in
669 schema
670
671 (*S Extraction of a term. *)
672
673 (* Precondition: [(c args)] is not a type scheme, and is informative. *)
674
675 (* [mle] is a ML environment [Mlenv.t]. *)
676 (* [mlt] is the ML type we want our extraction of [(c args)] to have. *)
677
678 let rec extract_term table env sg mle mlt c args =
679 match EConstr.kind sg c with
680 | App (f,a) ->
681 extract_term table env sg mle mlt f (Array.to_list a @ args)
682 | Lambda (n, t, d) ->
683 let id = map_annot id_of_name n in
684 let idna = map_annot Name.mk_name id in
685 (match args with
686 | a :: l ->
687 (* We make as many [LetIn] as possible. *)
688 let l' = List.map (EConstr.Vars.lift 1) l in
689 let d' = EConstr.mkLetIn (idna,a,t,applistc d l') in
690 extract_term table env sg mle mlt d' []
691 | [] ->
692 let env' = push_rel_assum (idna, t) env in
693 let id, a =
694 try check_default env sg t; Id id.binder_name, new_meta()
695 with NotDefault d -> Dummy, Tdummy d
696 in
697 let b = new_meta () in
698 (* If [mlt] cannot be unified with an arrow type, then magic! *)
699 let magic = needs_magic (mlt, Tarr (a, b)) in
700 let d' = extract_term table env' sg (Mlenv.push_type mle a) b d [] in
701 put_magic_if magic (MLlam (id, d')))
702 | LetIn (n, c1, t1, c2) ->
703 let id = map_annot id_of_name n in
704 let env' = EConstr.push_rel (LocalDef (map_annot Name.mk_name id, c1, t1)) env in
705 (* We directly push the args inside the [LetIn].
706 TODO: the opt_let_app flag is supposed to prevent that *)
707 let args' = List.map (EConstr.Vars.lift 1) args in
708 (try
709 check_default env sg t1;
710 let a = new_meta () in
711 let c1' = extract_term table env sg mle a c1 [] in
712 (* The type of [c1'] is generalized and stored in [mle]. *)
713 let mle' =
714 if generalizable c1'
715 then Mlenv.push_gen mle a
716 else Mlenv.push_type mle a
717 in
718 MLletin (Id id.binder_name, c1', extract_term table env' sg mle' mlt c2 args')
719 with NotDefault d ->
720 let mle' = Mlenv.push_std_type mle (Tdummy d) in
721 ast_pop (extract_term table env' sg mle' mlt c2 args'))
722 | Const (kn,u) ->
723 extract_cst_app table env sg mle mlt (kn, u) args
724 | Construct (cp,u) ->
725 extract_cons_app table env sg mle mlt (cp, u) args
726 | Proj (p, _, c) ->
727 let p = Projection.repr p in
728 let term = fake_match_projection env p in
729 let ind = Inductiveops.find_rectype env sg (Retyping.get_type_of env sg c) in
730 let indf,_ = Inductiveops.dest_ind_type ind in
731 let _,indargs = Inductiveops.dest_ind_family indf in
732 extract_term table env sg mle mlt (beta_applist sg (EConstr.of_constr term,indargs@[c])) args
733 | Rel n ->
734 (* As soon as the expected [mlt] for the head is known, *)
735 (* we unify it with an fresh copy of the stored type of [Rel n]. *)
736 let extract_rel mlt = put_magic (mlt, Mlenv.get mle n) (MLrel n)
737 in extract_app table env sg mle mlt extract_rel args
738 | Case (ci, u, pms, r, iv, c0, br) ->
739 (* If invert_case then this is a match that will get erased later, but right now we don't care. *)
740 let (ip, r, iv, c0, br) = EConstr.expand_case env sg (ci, u, pms, r, iv, c0, br) in
741 let ip = ci.ci_ind in
742 extract_app table env sg mle mlt (extract_case table env sg mle (ip, u, c0, br)) args
743 | Fix ((_,i),recd) ->
744 extract_app table env sg mle mlt (extract_fix table env sg mle i recd) args
745 | CoFix (i,recd) ->
746 extract_app table env sg mle mlt (extract_fix table env sg mle i recd) args
747 | Cast (c,_,_) -> extract_term table env sg mle mlt c args
748 | Evar _ | Meta _ -> MLaxiom "evar"
749 | Var v ->
750 (* Only during Show Extraction *)
751 let open Context.Named.Declaration in
752 let ty = match EConstr.lookup_named v env with
753 | LocalAssum (_,ty) -> ty
754 | LocalDef (_,_,ty) -> ty
755 in
756 let vty = extract_type table env sg [] 0 ty [] in
757 let r = { glob = GlobRef.VarRef v; inst = InfvInst.empty } in
758 let extract_var mlt = put_magic (mlt,vty) (MLglob r) in
759 extract_app table env sg mle mlt extract_var args
760 | Int i -> assert (args = []); MLuint i
761 | Float f -> assert (args = []); MLfloat f
762 | String s -> assert (args = []); MLstring s
763 | Array (_u,t,def,_ty) ->
764 assert (args = []);
765 let a = new_meta () in
766 let ml_arr = Array.map (fun c -> extract_term table env sg mle a c []) t in
767 let def = extract_term table env sg mle a def [] in
768 MLparray(ml_arr, def)
769 | Ind _ | Prod _ | Sort _ -> assert false
770
771 (*s [extract_maybe_term] is [extract_term] for usual terms, else [MLdummy] *)
772
773 and extract_maybe_term table env sg mle mlt c =
774 try check_default env sg (type_of env sg c);
775 extract_term table env sg mle mlt c []
776 with NotDefault d ->
777 put_magic (mlt, Tdummy d) (MLdummy d)
778
779 (*s Generic way to deal with an application. *)
780
781 (* We first type all arguments starting with unknown meta types.
782 This gives us the expected type of the head. Then we use the
783 [mk_head] to produce the ML head from this type. *)
784
785 and extract_app table env sg mle mlt mk_head args =
786 let metas = List.map new_meta args in
787 let type_head = type_recomp (metas, mlt) in
788 let mlargs = List.map2 (extract_maybe_term table env sg mle) metas args in
789 mlapp (mk_head type_head) mlargs
790
791 (*s Auxiliary function used to extract arguments of constant or constructor. *)
792
793 and make_mlargs table env sg e s args typs =
794 let rec f = function
795 | [], [], _ -> []
796 | a::la, t::lt, [] -> extract_maybe_term table env sg e t a :: (f (la,lt,[]))
797 | a::la, t::lt, Keep::s -> extract_maybe_term table env sg e t a :: (f (la,lt,s))
798 | _::la, _::lt, _::s -> f (la,lt,s)
799 | _ -> assert false
800 in f (args,typs,s)
801
802 (*s Extraction of a constant applied to arguments. *)
803
804 and extract_cst_app table env sg mle mlt (kn, u) args =
805 let inst = InfvInst.ground (EConstr.EInstance.kind sg u) in
806 (* First, the [ml_schema] of the constant, in expanded version. *)
807 let nb, t = record_constant_type table env sg kn inst None in
808 let schema = nb, expand table env t in
809 (* Can we instantiate types variables for this constant ? *)
810 (* In Ocaml, inside the definition of this constant, the answer is no. *)
811 let instantiated =
812 if lang () == Ocaml && List.exists (fun c -> Constant.UserOrd.equal kn c) !current_fixpoints
813 then var2var' (snd schema)
814 else instantiation schema
815 in
816 (* Then the expected type of this constant. *)
817 let a = new_meta () in
818 (* We compare stored and expected types in two steps. *)
819 (* First, can [kn] be applied to all args ? *)
820 let metas = List.map new_meta args in
821 let magic1 = needs_magic (type_recomp (metas, a), instantiated) in
822 (* Second, is the resulting type compatible with the expected type [mlt] ? *)
823 let magic2 = needs_magic (a, mlt) in
824 (* The internal head receives a magic if [magic1] *)
825 let r = { glob = GlobRef.ConstRef kn; inst } in
826 let head = put_magic_if magic1 (MLglob r) in
827 (* Now, the extraction of the arguments. *)
828 let s_full = type2signature table env (snd schema) in
829 let s_full = sign_with_implicits r s_full 0 in
830 let s = sign_no_final_keeps s_full in
831 let ls = List.length s in
832 let la = List.length args in
833 (* The ml arguments, already expunged from known logical ones *)
834 let mla = make_mlargs table env sg mle s args metas in
835 (* For strict languages, purely logical signatures lead to a dummy lam
836 (except when [Kill Ktype] everywhere). So a [MLdummy] is left
837 accordingly. *)
838 let optdummy = match sign_kind s_full with
839 | UnsafeLogicalSig when lang () != Haskell -> [MLdummy Kprop]
840 | _ -> []
841 in
842 (* Different situations depending of the number of arguments: *)
843 if la >= ls
844 then
845 (* Enough args, cleanup already done in [mla], we only add the
846 additional dummy if needed. *)
847 put_magic_if (magic2 && not magic1) (mlapp head (optdummy @ mla))
848 else
849 (* Partially applied function with some logical arg missing.
850 We complete via eta and expunge logical args. *)
851 let ls' = ls-la in
852 let s' = List.skipn la s in
853 let mla = (List.map (ast_lift ls') mla) @ (eta_args_sign ls' s') in
854 let e = anonym_or_dummy_lams (mlapp head mla) s' in
855 put_magic_if magic2 (remove_n_lams (List.length optdummy) e)
856
857 (*s Extraction of an inductive constructor applied to arguments. *)
858
859 (* \begin{itemize}
860 \item In ML, constructor arguments are uncurryfied.
861 \item We managed to suppress logical parts inside inductive definitions,
862 but they must appears outside (for partial applications for instance)
863 \item We also suppressed all Rocq parameters to the inductives, since
864 they are fixed, and thus are not used for the computation.
865 \end{itemize} *)
866
867 and extract_cons_app table env sg mle mlt (cp, u) args =
868 let ((kn, i) as ip, j) = cp in
869 (* First, we build the type of the constructor, stored in small pieces. *)
870 let inst = InfvInst.ground (EConstr.EInstance.kind sg u) in
871 let mi = extract_ind table env kn inst in
872 let params_nb = mi.ind_nparams in
873 let oi = mi.ind_packets.(i) in
874 let nb_tvars = List.length oi.ip_vars
875 and types = List.map (expand table env) oi.ip_types.(j-1) in
876 let list_tvar = List.map (fun i -> Tvar i) (List.interval 1 nb_tvars) in
877 let gind = { glob = GlobRef.IndRef ip; inst } in
878 let gcstr = { glob = GlobRef.ConstructRef cp; inst } in
879 let type_cons = type_recomp (types, Tglob (gind, list_tvar)) in
880 let type_cons = instantiation (nb_tvars, type_cons) in
881 (* Then, the usual variables [s], [ls], [la], ... *)
882 let s = List.map (type2sign table env) types in
883 let s = sign_with_implicits gcstr s params_nb in
884 let ls = List.length s in
885 let la = List.length args in
886 assert (la <= ls + params_nb);
887 let la' = max 0 (la - params_nb) in
888 let args' = List.lastn la' args in
889 (* Now, we build the expected type of the constructor *)
890 let metas = List.map new_meta args' in
891 (* If stored and expected types differ, then magic! *)
892 let a = new_meta () in
893 let magic1 = needs_magic (type_cons, type_recomp (metas, a)) in
894 let magic2 = needs_magic (a, mlt) in
895 let head mla =
896 if mi.ind_kind == Singleton then
897 put_magic_if magic1 (List.hd mla) (* assert (List.length mla = 1) *)
898 else
899 let typeargs = match snd (type_decomp type_cons) with
900 | Tglob (_,l) -> List.map type_simpl l
901 | _ -> assert false
902 in
903 let typ = Tglob (gind, typeargs) in
904 put_magic_if magic1 (MLcons (typ, gcstr, mla))
905 in
906 (* Different situations depending of the number of arguments: *)
907 if la < params_nb then
908 let head' = head (eta_args_sign ls s) in
909 put_magic_if magic2
910 (dummy_lams (anonym_or_dummy_lams head' s) (params_nb - la))
911 else
912 let mla = make_mlargs table env sg mle s args' metas in
913 if Int.equal la (ls + params_nb)
914 then put_magic_if (magic2 && not magic1) (head mla)
915 else (* [ params_nb <= la <= ls + params_nb ] *)
916 let ls' = params_nb + ls - la in
917 let s' = List.lastn ls' s in
918 let mla = (List.map (ast_lift ls') mla) @ (eta_args_sign ls' s') in
919 put_magic_if magic2 (anonym_or_dummy_lams (head mla) s')
920
921 (*S Extraction of a case. *)
922
923 and extract_case table env sg mle ((kn,i) as ip, u, c, br) mlt =
924 (* [br]: bodies of each branch (in functional form) *)
925 (* [ni]: number of arguments without parameters in each branch *)
926 let ni = constructors_nrealargs env ip in
927 let br_size = Array.length br in
928 let inst = InfvInst.ground (EConstr.EInstance.kind sg u) in
929 let gind = { glob = GlobRef.IndRef ip; inst } in
930 assert (Int.equal (Array.length ni) br_size);
931 if Int.equal br_size 0 then begin
932 add_recursors (Common.State.get_table table) env kn; (* May have passed unseen if logical ... *)
933 MLexn "absurd case"
934 end else
935 (* [c] has an inductive type, and is not a type scheme type. *)
936 let t = type_of env sg c in
937 (* The only non-informative case: [c] is of sort [Prop]/[SProp] *)
938 if info_of_quality (sort_of env sg t) == Logic then
939 begin
940 add_recursors (Common.State.get_table table) env kn; (* May have passed unseen if logical ... *)
941 (* Logical singleton case: *)
942 (* [match c with C i j k -> t] becomes [t'] *)
943 assert (Int.equal br_size 1);
944 let s = iterate (fun l -> Kill Kprop :: l) ni.(0) [] in
945 let mlt = iterate (fun t -> Tarr (Tdummy Kprop, t)) ni.(0) mlt in
946 let e = extract_maybe_term table env sg mle mlt br.(0) in
947 snd (case_expunge s e)
948 end
949 else
950 let mi = extract_ind table env kn inst in
951 let oi = mi.ind_packets.(i) in
952 let metas = Array.init (List.length oi.ip_vars) new_meta in
953 (* The extraction of the head. *)
954 let type_head = Tglob (gind, Array.to_list metas) in
955 let a = extract_term table env sg mle type_head c [] in
956 (* The extraction of each branch. *)
957 let extract_branch i =
958 let r = { glob = GlobRef.ConstructRef (ip, i + 1); inst } in
959 (* The types of the arguments of the corresponding constructor. *)
960 let f t = type_subst_vect metas (expand table env t) in
961 let l = List.map f oi.ip_types.(i) in
962 (* the corresponding signature *)
963 let s = List.map (type2sign table env) oi.ip_types.(i) in
964 let s = sign_with_implicits r s mi.ind_nparams in
965 (* Extraction of the branch (in functional form). *)
966 let e = extract_maybe_term table env sg mle (type_recomp (l,mlt)) br.(i) in
967 (* We suppress dummy arguments according to signature. *)
968 let ids,e = case_expunge s e in
969 (List.rev ids, Pusual r, e)
970 in
971 if mi.ind_kind == Singleton then
972 begin
973 (* Informative singleton case: *)
974 (* [match c with C i -> t] becomes [let i = c' in t'] *)
975 assert (Int.equal br_size 1);
976 let (ids,_,e') = extract_branch 0 in
977 assert (Int.equal (List.length ids) 1);
978 MLletin (tmp_id (List.hd ids),a,e')
979 end
980 else
981 (* Standard case: we apply [extract_branch]. *)
982 let typs = List.map type_simpl (Array.to_list metas) in
983 let typ = Tglob (gind, typs) in
984 MLcase (typ, a, Array.init br_size extract_branch)
985
986 (*s Extraction of a (co)-fixpoint. *)
987
988 and extract_fix table env sg mle i (fi,ti,ci as recd) mlt =
989 let env = push_rec_types recd env in
990 let metas = Array.map new_meta fi in
991 metas.(i) <- mlt;
992 let mle = Array.fold_left Mlenv.push_type mle metas in
993 let ei = Array.map2 (extract_maybe_term table env sg mle) metas ci in
994 MLfix (i, Array.map (fun x -> id_of_name x.binder_name) fi, ei)
995
996 (*S ML declarations. *)
997
998 (* [decomp_lams_eta env c t] finds the number [n] of products in the type [t],
999 and decompose the term [c] in [n] lambdas, with eta-expansion if needed. *)
1000
1001 let decomp_lams_eta_n n m env sg c t =
1002 let rels = fst (whd_decompose_prod_n env sg n t) in
1003 let rels',c = EConstr.decompose_lambda sg c in
1004 let d = n - m in
1005 (* we'd better keep rels' as long as possible. *)
1006 let rels = (List.firstn d rels) @ rels' in
1007 let eta_args = List.rev_map EConstr.mkRel (List.interval 1 d) in
1008 rels, applistc (EConstr.Vars.lift d c) eta_args
1009
1010 (* Let's try to identify some situation where extracted code
1011 will allow generalisation of type variables *)
1012
1013 let rec gentypvar_ok sg c = match EConstr.kind sg c with
1014 | Lambda _ | Const _ -> true
1015 | App (c,v) ->
1016 (* if all arguments are variables, these variables will
1017 disappear after extraction (see [empty_s] below) *)
1018 Array.for_all (EConstr.isRel sg) v && gentypvar_ok sg c
1019 | Cast (c,_,_) -> gentypvar_ok sg c
1020 | _ -> false
1021
1022 (*s From a constant to a ML declaration. *)
1023
1024 let extract_std_constant table env sg kn inst body typ =
1025 (* expects body and typ to be already substituted w.r.t. inst *)
1026 reset_meta_count ();
1027 (* The short type [t] (i.e. possibly with abbreviations). *)
1028 let t = snd (record_constant_type table env sg kn inst (Some typ)) in
1029 (* The real type [t']: without head products, expanded, *)
1030 (* and with [Tvar] translated to [Tvar'] (not instantiable). *)
1031 let l,t' = type_decomp (expand table env (var2var' t)) in
1032 let s = List.map (type2sign table env) l in
1033 (* Check for user-declared implicit information *)
1034 let s = sign_with_implicits { glob = GlobRef.ConstRef kn; inst } s 0 in
1035 (* Decomposing the top level lambdas of [body].
1036 If there isn't enough, it's ok, as long as remaining args
1037 aren't to be pruned (and initial lambdas aren't to be all
1038 removed if the target language is strict). In other situations,
1039 eta-expansions create artificially enough lams (but that may
1040 break user's clever let-ins and partial applications). *)
1041 let rels, c =
1042 let n = List.length s
1043 and m = nb_lam sg body in
1044 if n <= m then decompose_lambda_n sg n body
1045 else
1046 let s,s' = List.chop m s in
1047 if List.for_all ((==) Keep) s' &&
1048 (lang () == Haskell || sign_kind s != UnsafeLogicalSig)
1049 then decompose_lambda_n sg m body
1050 else decomp_lams_eta_n n m env sg body typ
1051 in
1052 (* Should we do one eta-expansion to avoid non-generalizable '_a ? *)
1053 let rels, c =
1054 let n = List.length rels in
1055 let s,s' = List.chop n s in
1056 let k = sign_kind s in
1057 let empty_s = (k == EmptySig || k == SafeLogicalSig) in
1058 if lang () == Ocaml && empty_s && not (gentypvar_ok sg c)
1059 && not (List.is_empty s') && not (Int.equal (type_maxvar t) 0)
1060 then decomp_lams_eta_n (n+1) n env sg body typ
1061 else rels,c
1062 in
1063 let n = List.length rels in
1064 let s = List.firstn n s in
1065 let l,l' = List.chop n l in
1066 let t' = type_recomp (l',t') in
1067 (* The initial ML environment. *)
1068 let mle = List.fold_left Mlenv.push_std_type Mlenv.empty l in
1069 (* The lambdas names. *)
1070 let ids = List.map (fun (n,_) -> Id (id_of_name n.binder_name)) rels in
1071 (* The according Rocq environment. *)
1072 let env = push_rels_assum rels env in
1073 (* The real extraction: *)
1074 let e = extract_term table env sg mle t' c [] in
1075 (* Expunging term and type from dummy lambdas. *)
1076 let trm = term_expunge s (ids,e) in
1077 trm, type_expunge_from_sign table env s t
1078
1079 (* Extracts the type of an axiom, honors the Extraction Implicit declaration. *)
1080 let extract_axiom table env sg kn inst typ =
1081 reset_meta_count ();
1082 (* The short type [t] (i.e. possibly with abbreviations). *)
1083 let t = snd (record_constant_type table env sg kn inst (Some typ)) in
1084 (* The real type [t']: without head products, expanded, *)
1085 (* and with [Tvar] translated to [Tvar'] (not instantiable). *)
1086 let l,_ = type_decomp (expand table env (var2var' t)) in
1087 let s = List.map (type2sign table env) l in
1088 (* Check for user-declared implicit information *)
1089 let s = sign_with_implicits { glob = GlobRef.ConstRef kn; inst } s 0 in
1090 type_expunge_from_sign table env s t
1091
1092 let extract_fixpoint table env sg vkn inst (fi,ti,ci) =
1093 let n = Array.length vkn in
1094 let types = Array.make n (Tdummy Kprop)
1095 and terms = Array.make n (MLdummy Kprop) in
1096 let kns = Array.to_list vkn in
1097 current_fixpoints := kns;
1098 (* for replacing recursive calls [Rel ..] by the corresponding [Const]: *)
1099 let sg, sub = CList.fold_left_map (fun sg con ->
1100 Evd.fresh_global env sg (ConstRef con))
1101 sg
1102 (List.rev kns)
1103 in
1104 for i = 0 to n-1 do
1105 if info_of_quality (sort_of env sg ti.(i)) != Logic then
1106 try
1107 let e,t = extract_std_constant table env sg vkn.(i) inst
1108 (EConstr.Vars.substl sub ci.(i)) ti.(i) in
1109 terms.(i) <- e;
1110 types.(i) <- t;
1111 with SingletonInductiveBecomesProp ind ->
1112 error_singleton_become_prop ind
1113 done;
1114 current_fixpoints := [];
1115 Dfix (Array.map (fun kn -> { glob = GlobRef.ConstRef kn; inst }) vkn, terms, types)
1116
1117 let extract_constant table access env kn inst cb =
1118 let sg = Evd.from_env env in
1119 let r = { glob = GlobRef.ConstRef kn; inst } in
1120 let typ = qmono cb.const_universes inst cb.const_type in
1121 let warn_info () = if not (is_custom r) then add_info_axiom (Common.State.get_table table) r in
1122 let warn_log () = if not (constant_has_body cb) then add_log_axiom (Common.State.get_table table) r
1123 in
1124 let mk_typ_ax () =
1125 let n = type_scheme_nb_args env sg typ in
1126 let ids = iterate (fun l -> anonymous_name::l) n [] in
1127 Dtype (r, ids, Taxiom)
1128 in
1129 let mk_typ c =
1130 let s,vl = type_sign_vl env sg typ in
1131 let db = db_from_sign s in
1132 let t = extract_type_scheme table env sg db c (List.length s)
1133 in Dtype (r, vl, t)
1134 in
1135 let mk_ax () =
1136 let t = extract_axiom table env sg kn inst typ in
1137 Dterm (r, MLaxiom (Constant.to_string kn), t)
1138 in
1139 let mk_def c =
1140 let e,t = extract_std_constant table env sg kn inst c typ in
1141 Dterm (r,e,t)
1142 in
1143 try
1144 match flag_of_type env sg typ with
1145 | (Logic,TypeScheme) -> warn_log ();
1146 let s,vl = type_sign_vl env sg typ in
1147 Dtype (r, vl, Tdummy Ktype)
1148 | (Logic,Default) -> warn_log (); Dterm (r, MLdummy Kprop, Tdummy Kprop)
1149 | (Info,TypeScheme) ->
1150 (match cb.const_body with
1151 | Symbol _ -> add_symbol (Common.State.get_table table) r; mk_typ_ax ()
1152 | Primitive _ | Undef _ -> warn_info (); mk_typ_ax ()
1153 | Def c ->
1154 (match Structures.PrimitiveProjections.find_opt kn with
1155 | None -> mk_typ (qmono cb.const_universes inst c)
1156 | Some p ->
1157 let body = fake_match_projection env p in
1158 let body = qmono cb.const_universes inst body in
1159 mk_typ body)
1160 | OpaqueDef c ->
1161 add_opaque (Common.State.get_table table) r;
1162 if access_opaque () then mk_typ (get_opaque access env c)
1163 else mk_typ_ax ())
1164 | (Info,Default) ->
1165 (match cb.const_body with
1166 | Symbol _ -> add_symbol (Common.State.get_table table) r; mk_ax ()
1167 | Primitive _ | Undef _ -> warn_info (); mk_ax ()
1168 | Def c ->
1169 (match Structures.PrimitiveProjections.find_opt kn with
1170 | None -> mk_def (qmono cb.const_universes inst c)
1171 | Some p ->
1172 let body = fake_match_projection env p in
1173 mk_def (qmono cb.const_universes inst body))
1174 | OpaqueDef c ->
1175 add_opaque (Common.State.get_table table) r;
1176 if access_opaque () then mk_def (get_opaque access env c)
1177 else mk_ax ())
1178 with SingletonInductiveBecomesProp ind ->
1179 error_singleton_become_prop ind
1180
1181 let extract_constant_spec table env kn inst cb =
1182 let sg = Evd.from_env env in
1183 let r = { glob = GlobRef.ConstRef kn; inst } in
1184 let typ = qmono cb.const_universes inst cb.const_type in
1185 try
1186 match flag_of_type env sg typ with
1187 | (Logic, TypeScheme) ->
1188 let s,vl = type_sign_vl env sg typ in
1189 Stype (r, vl, Some (Tdummy Ktype))
1190 | (Logic, Default) -> Sval (r, Tdummy Kprop)
1191 | (Info, TypeScheme) ->
1192 let s,vl = type_sign_vl env sg typ in
1193 (match cb.const_body with
1194 | Undef _ | OpaqueDef _ | Primitive _ | Symbol _ -> Stype (r, vl, None)
1195 | Def body ->
1196 let db = db_from_sign s in
1197 let body = qmono cb.const_universes inst body in
1198 let t = extract_type_scheme table env sg db body (List.length s)
1199 in Stype (r, vl, Some t))
1200 | (Info, Default) ->
1201 let t = snd (record_constant_type table env sg kn inst (Some typ)) in
1202 Sval (r, type_expunge table env t)
1203 with SingletonInductiveBecomesProp ind ->
1204 error_singleton_become_prop ind
1205
1206 let extract_with_type table env sg c =
1207 try
1208 let typ = type_of env sg c in
1209 match flag_of_type env sg typ with
1210 | (Info, TypeScheme) ->
1211 let s,vl = type_sign_vl env sg typ in
1212 let db = db_from_sign s in
1213 let t = extract_type_scheme table env sg db c (List.length s) in
1214 Some (vl, t)
1215 | _ -> None
1216 with SingletonInductiveBecomesProp ind ->
1217 error_singleton_become_prop ind
1218
1219 let extract_constr table env sg c =
1220 reset_meta_count ();
1221 try
1222 let typ = type_of env sg c in
1223 match flag_of_type env sg typ with
1224 | (_,TypeScheme) -> MLdummy Ktype, Tdummy Ktype
1225 | (Logic,_) -> MLdummy Kprop, Tdummy Kprop
1226 | (Info,Default) ->
1227 let mlt = extract_type table env sg [] 1 typ [] in
1228 extract_term table env sg Mlenv.empty mlt c [], mlt
1229 with SingletonInductiveBecomesProp ind ->
1230 error_singleton_become_prop ind
1231
1232 let extract_inductive table env kn inst =
1233 let ind = extract_ind table env kn inst in
1234 let () = add_recursors (Common.State.get_table table) env kn in
1235 let f i j l =
1236 let r = { glob = GlobRef.ConstructRef ((kn, i), j + 1); inst } in
1237 let implicits = implicits_of_global r in
1238 let rec filter i = function
1239 | [] -> []
1240 | t::l ->
1241 let l' = filter (succ i) l in
1242 if isTdummy (expand table env t) || Int.Set.mem i implicits then l'
1243 else t::l'
1244 in filter (1+ind.ind_nparams) l
1245 in
1246 let packets =
1247 Array.mapi (fun i p -> { p with ip_types = Array.mapi (f i) p.ip_types })
1248 ind.ind_packets
1249 in { ind with ind_packets = packets }
1250
1251 (*s Is a [ml_decl] logical ? *)
1252
1253 let logical_decl = function
1254 | Dterm (_,MLdummy _,Tdummy _) -> true
1255 | Dtype (_,_,Tdummy _) -> true
1256 | Dfix (_,av,tv) ->
1257 (Array.for_all isMLdummy av) &&
1258 (Array.for_all isTdummy tv)
1259 | Dind i -> Array.for_all (fun ip -> ip.ip_logical) i.ind_packets
1260 | _ -> false
1261
1262 (*s Is a [ml_spec] logical ? *)
1263
1264 let logical_spec = function
1265 | Stype (_, _, Some (Tdummy _)) -> true
1266 | Sval (_,Tdummy _) -> true
1267 | Sind i -> Array.for_all (fun ip -> ip.ip_logical) i.ind_packets
1268 | _ -> false