Debian Codegraph @

pretyping/vnorm.ml

raw symbols SCIP
1 (************************************************************************)
2 (* * The Rocq Prover / The Rocq Development Team *)
3 (* v * Copyright INRIA, CNRS and contributors *)
4 (* <O___,, * (see version control and CREDITS file for authors & dates) *)
5 (* \VV/ **************************************************************)
6 (* // * This file is distributed under the terms of the *)
7 (* * GNU Lesser General Public License Version 2.1 *)
8 (* * (see LICENSE file for the text of the license) *)
9 (************************************************************************)
10
11 open Util
12 open Names
13 open Declarations
14 open Term
15 open Constr
16 open Context
17 open Vars
18 open Environ
19 open Inductive
20 open Vmvalues
21 open Vm
22 open Context.Rel.Declaration
23
24 module RelDecl = Context.Rel.Declaration
25 module NamedDecl = Context.Named.Declaration
26
27 (*******************************************)
28 (* Calcul de la forme normal d'un terme *)
29 (*******************************************)
30
31 let e_whd_all = Reductionops.clos_whd_flags RedFlags.all
32
33 let crazy_type = mkSet
34
35 let decompose_prod env sigma t =
36 let (name,dom,codom) = destProd (EConstr.Unsafe.to_constr (e_whd_all env sigma (EConstr.of_constr t))) in
37 let name = map_annot (function
38 | Anonymous -> Name (Id.of_string "x")
39 | Name _ as na -> na) name
40 in
41 (name,dom,codom)
42
43 exception Find_at of int
44
45 (* rend le numero du constructeur correspondant au tag [tag],
46 [cst] = true si c'est un constructeur constant *)
47
48 let invert_tag cst tag reloc_tbl =
49 try
50 for j = 0 to Array.length reloc_tbl - 1 do
51 let tagj,arity = reloc_tbl.(j) in
52 let no_arity = Int.equal arity 0 in
53 if Int.equal tag tagj && (cst && no_arity || not (cst || no_arity)) then
54 raise (Find_at j)
55 else ()
56 done;raise Not_found
57 with Find_at j -> (j+1)
58 (* Argggg, ces constructeurs de ... qui commencent a 1*)
59
60 let app_type env sigma c =
61 let t = e_whd_all env sigma c in
62 decompose_app (EConstr.Unsafe.to_constr t)
63
64 let find_rectype_a env sigma c =
65 let (t, l) = app_type env sigma c in
66 match kind t with
67 | Ind ind -> (ind, l)
68 | _ -> raise Not_found
69
70 (* Instantiate inductives and parameters in constructor type *)
71
72 let type_constructor mind mib u (ctx, typ) params =
73 let typ = it_mkProd_or_LetIn typ ctx in
74 let ctyp = subst_instance_constr u typ in
75 let ndecls = Context.Rel.length mib.mind_params_ctxt in
76 if Int.equal ndecls 0 then ctyp
77 else
78 let _,ctyp = decompose_prod_n_decls ndecls ctyp in
79 substl (subst_of_rel_context_instance mib.mind_params_ctxt params)
80 ctyp
81
82
83
84 let construct_of_constr const env sigma tag typ =
85 let t, allargs = app_type env sigma (EConstr.of_constr typ) in
86 match Constr.kind t with
87 | Ind ((mind,_ as ind), u as indu) ->
88 let mib,mip = lookup_mind_specif env ind in
89 let nparams = mib.mind_nparams in
90 let i = invert_tag const tag mip.mind_reloc_tbl in
91 let params = Array.sub allargs 0 nparams in
92 let ctyp = type_constructor mind mib u (mip.mind_nf_lc.(i-1)) params in
93 (mkApp(mkConstructUi(indu,i), params), ctyp)
94 | _ ->
95 assert (Constr.equal t (Typeops.type_of_int env));
96 (mkInt (Uint63.of_int tag), t)
97
98 let construct_of_constr_const env sigma tag typ =
99 fst (construct_of_constr true env sigma tag typ)
100
101 let construct_of_constr_block = construct_of_constr false
102
103 let type_of_ind env (ind, u) =
104 type_of_inductive (Inductive.lookup_mind_specif env ind, u)
105
106 let get_case_annot decls =
107 Array.map_of_list (fun decl -> get_annot decl) (List.rev decls)
108
109 let build_branches_type env sigma (mind,_ as _ind) mib mip u params (pctx, p) =
110 let rtbl = mip.mind_reloc_tbl in
111 (* [build_one_branch i cty] construit le type de la ieme branche (commence
112 a 0) et les lambda correspondant aux realargs *)
113 let p = it_mkLambda_or_LetIn p pctx in (* TODO: prevent useless cut? *)
114 let build_one_branch i cty =
115 let typi = type_constructor mind mib u cty params in
116 let decl,indapp = Reductionops.whd_decompose_prod env sigma (EConstr.of_constr typi) in
117 let decl = List.map EConstr.Unsafe.(fun (na,c) -> to_binder_annot na, to_constr c) decl in
118 let ((ind,u),cargs) = find_rectype_a env sigma indapp in
119 let nparams = Array.length params in
120 let carity = snd (rtbl.(i)) in
121 let crealargs = Array.sub cargs nparams (Array.length cargs - nparams) in
122 let codom =
123 let ndecl = List.length decl in
124 let papp = mkApp(lift ndecl p,crealargs) in
125 let cstr = ith_constructor_of_inductive ind (i+1) in
126 let relargs = Array.init carity (fun i -> mkRel (carity-i)) in
127 let params = Array.map (lift ndecl) params in
128 let dep_cstr = mkApp(mkApp(mkConstructU (cstr,u),params),relargs) in
129 mkApp(papp,[|dep_cstr|])
130 in
131 let decl_with_letin = List.firstn mip.mind_consnrealdecls.(i) (fst cty) in
132 let nas = get_case_annot decl_with_letin in
133 let rec get_lift decls = match decls with
134 | [] -> Esubst.el_id
135 | LocalDef _ :: decls -> Esubst.el_shft 1 (get_lift decls)
136 | LocalAssum _ :: decls -> Esubst.el_lift (get_lift decls)
137 in
138 decl, nas, get_lift decl_with_letin, codom
139 in Array.mapi build_one_branch mip.mind_nf_lc
140
141 let build_case_type (pctx, p) realargs c =
142 let p = it_mkLambda_or_LetIn p pctx in (* TODO: prevent useless cut? *)
143 mkApp(mkApp(p, realargs), [|c|])
144
145 (* La fonction de normalisation *)
146
147 let rec nf_val env sigma v t = nf_whd env sigma (Vmvalues.whd_val v) t
148
149 and nf_vtype env sigma v = nf_val env sigma v crazy_type
150
151 and nf_whd env sigma whd typ =
152 match whd with
153 | Vprod p ->
154 let dom = nf_vtype env sigma (dom p) in
155 let name = Name (Id.of_string "x") in
156 let vc = reduce_fun (nb_rel env) (codom p) in
157 let r = Retyping.relevance_of_type env sigma (EConstr.of_constr dom) in
158 let r = EConstr.Unsafe.to_relevance r in
159 let name = make_annot name r in
160 let codom = nf_vtype (push_rel (LocalAssum (name,dom)) env) sigma vc in
161 mkProd(name,dom,codom)
162 | Vfun f -> nf_fun env sigma f typ
163 | Vfix(f,None) -> nf_fix env sigma f
164 | Vfix(f,Some vargs) -> fst (nf_fix_app env sigma f vargs)
165 | Vcofix(cf,_,None) -> nf_cofix env sigma cf
166 | Vcofix(cf,_,Some vargs) ->
167 let cfd = nf_cofix env sigma cf in
168 let i,(_,ta,_) = destCoFix cfd in
169 let t = ta.(i) in
170 let _, args = nf_args env sigma vargs t in
171 mkApp(cfd,args)
172 | Vconst n ->
173 construct_of_constr_const env sigma n typ
174 | Vblock b ->
175 let tag = btag b in
176 let (tag,ofs) =
177 if tag = Obj.last_non_constant_constructor_tag then
178 match whd_val (bfield b 0) with
179 | Vconst tag -> (tag+Obj.last_non_constant_constructor_tag, 1)
180 | _ -> assert false
181 else (tag, 0) in
182 let capp,ctyp = construct_of_constr_block env sigma tag typ in
183 let args = nf_bargs env sigma b ofs ctyp in
184 mkApp(capp,args)
185 | Vint64 i -> i |> Uint63.of_int64 |> mkInt
186 | Vfloat64 f -> f |> Float64.of_float |> mkFloat
187 | Vstring s -> s |> mkString
188 | Varray t -> nf_array env sigma t typ
189 | Vaccu (Aid idkey, stk) ->
190 constr_type_of_idkey env sigma idkey stk
191 | Vaccu (Aind ((mi, i) as ind), stk) ->
192 let mib = Environ.lookup_mind mi env in
193 let nb_univs =
194 UVars.AbstractContext.size (Declareops.inductive_polymorphic_context mib)
195 in
196 let mk u =
197 let pind = (ind, u) in (mkIndU pind, type_of_ind env pind)
198 in
199 nf_univ_args ~nb_univs mk env sigma stk
200 | Vaccu (Asort s, stk) ->
201 assert (List.is_empty stk); mkSort s
202
203 and nf_univ_args ~nb_univs mk env sigma stk =
204 let u =
205 if UVars.eq_sizes nb_univs (0,0) then UVars.Instance.empty
206 else match stk with
207 | Zapp args :: _ ->
208 let inst = arg args 0 in
209 let inst = uni_instance inst in
210 let () = assert (UVars.eq_sizes (UVars.Instance.length inst) nb_univs) in
211 inst
212 | _ -> assert false
213 in
214 let (t,ty) = mk u in
215 let from = if UVars.Instance.is_empty u then 0 else 1 in
216 nf_stk ~from env sigma t ty stk
217
218 and nf_evar env sigma evk stk =
219 let evi = try Evd.find_undefined sigma evk with Not_found -> assert false in
220 let hyps = EConstr.named_context_of_val (Evd.evar_filtered_hyps evi) in
221 if List.is_empty hyps then
222 let concl = EConstr.to_constr ~abort_on_undefined_evars:false sigma @@ Evd.evar_concl evi in
223 nf_stk env sigma (mkEvar (evk, SList.empty)) concl stk
224 else match stk with
225 | Zapp args :: stk ->
226 (* We assume that there is no consecutive Zapp nodes in a VM stack. Is that
227 really an invariant? *)
228 (* Let-bound arguments are present in the evar arguments but not in the
229 type, so we turn the let into a product. *)
230 let concl = Evd.evar_concl evi in
231 let hyps = Context.Named.drop_bodies hyps in
232 let fold accu d = EConstr.mkNamedProd_or_LetIn sigma d accu in
233 let t = List.fold_left fold concl hyps in
234 let t = EConstr.to_constr ~abort_on_undefined_evars:false sigma t in
235 let t, args = nf_args env sigma args t in
236 let inst, args = Array.chop (List.length hyps) args in
237 (* Evar instances are reversed w.r.t. argument order *)
238 let inst = Array.to_list inst in
239 let ev = EConstr.(Unsafe.to_constr @@ mkLEvar sigma (evk, List.rev_map of_constr inst)) in
240 let c = mkApp (ev, args) in
241 nf_stk env sigma c t stk
242 | _ ->
243 CErrors.anomaly (Pp.str "Argument size mismatch when decompiling an evar")
244
245 and constr_type_of_idkey env sigma (idkey : Vmvalues.id_key) stk =
246 match idkey with
247 | ConstKey cst ->
248 let cbody = EConstr.lookup_constant env sigma cst in
249 let nb_univs =
250 UVars.AbstractContext.size (Declareops.constant_polymorphic_context cbody)
251 in
252 let mk u =
253 let ty = subst_instance_constr u cbody.const_type in
254 (mkConstU (cst, u), ty)
255 in
256 nf_univ_args ~nb_univs mk env sigma stk
257 | VarKey id ->
258 let ty = NamedDecl.get_type (lookup_named id env) in
259 nf_stk env sigma (mkVar id) ty stk
260 | RelKey i ->
261 let n = (nb_rel env - i) in
262 let ty = RelDecl.get_type (lookup_rel n env) in
263 nf_stk env sigma (mkRel n) (lift n ty) stk
264 | EvarKey evk ->
265 nf_evar env sigma evk stk
266
267 and nf_stk ?from:(from=0) env sigma c t stk =
268 match stk with
269 | [] -> c
270 | Zapp vargs :: stk ->
271 if nargs vargs >= from then
272 let t, args = nf_args ~from:from env sigma vargs t in
273 nf_stk env sigma (mkApp(c,args)) t stk
274 else
275 let rest = from - nargs vargs in
276 nf_stk ~from:rest env sigma c t stk
277 | Zfix (f,vargs) :: stk ->
278 assert (from = 0) ;
279 let fa, typ = nf_fix_app env sigma f vargs in
280 let _,_,codom = decompose_prod env sigma typ in
281 nf_stk env sigma (mkApp(fa,[|c|])) (subst1 c codom) stk
282 | Zswitch sw :: stk ->
283 assert (from = 0) ;
284 let ((mind,_ as ind), u), allargs = find_rectype_a env sigma (EConstr.of_constr t) in
285 let (mib,mip) = Inductive.lookup_mind_specif env ind in
286 let nparams = mib.mind_nparams in
287 let params,realargs = Util.Array.chop nparams allargs in
288 let pctx =
289 let realdecls, _ = List.chop mip.mind_nrealdecls mip.mind_arity_ctxt in
290 let nas = List.rev_map RelDecl.get_annot realdecls @ [nameR (Id.of_string "c")] in
291 expand_arity (mib, mip) (ind, u) params (Array.of_list nas)
292 in
293 let p, relevance = nf_predicate env sigma (ind,u) mip params (type_of_switch sw) pctx in
294 (* Calcul du type des branches *)
295 let btypes = build_branches_type env sigma ind mib mip u params (pctx, p) in
296 (* calcul des branches *)
297 let bsw = branch_of_switch (nb_rel env) sw in
298 let mkbranch i (n,v) =
299 let decl, nas, lft, codom = btypes.(i) in
300 let b = nf_val (Termops.push_rels_assum decl env) sigma v codom in
301 (* No let-ins in [codom], so we have to ignore the ones from the branch *)
302 let b = exliftn lft b in
303 (nas, b)
304 in
305 let branchs = Array.mapi mkbranch bsw in
306 let tcase = build_case_type (pctx, p) realargs c in
307 let p = (get_case_annot pctx, p) in
308 let ci = Inductiveops.make_case_info env ind RegularStyle in
309 let iv = if Inductiveops.Internal.should_invert_case env sigma relevance ci then
310 CaseInvert {indices=realargs}
311 else NoInvert
312 in
313 nf_stk env sigma (mkCase (ci, u, params, (p,relevance), iv, c, branchs)) tcase stk
314 | Zproj p :: stk ->
315 let () = assert (from = 0) in
316 let ((ind, u), args) = Inductiveops.find_mrectype env sigma (EConstr.of_constr t) in
317 let (mib, mip) = Inductive.lookup_mind_specif env ind in
318 let pars = List.firstn mib.mind_nparams args in
319 let ty = match mip.mind_record with
320 | NotRecord | FakeRecord -> assert false
321 | PrimRecord { tys; _ } ->
322 let ty = Vars.subst_instance_constr (EConstr.Unsafe.to_instance u) tys.(p) in
323 substl (c :: List.rev_map EConstr.Unsafe.to_constr pars) ty
324 in
325 let p, r = Declareops.inductive_make_projection ind mib ~proj_arg:p in
326 let p = Projection.make p true in
327 let r = UVars.subst_instance_relevance (EConstr.Unsafe.to_instance u) r in
328 nf_stk env sigma (mkProj (p, r, c)) ty stk
329
330 and nf_predicate env sigma ind mip params v pctx =
331 (* TODO: we should expose some variant of Vm.mkrel_vstack *)
332 let fold decl (k, v) = match decl with
333 | LocalDef _ -> (k + 1, v)
334 | LocalAssum _ ->
335 match whd_val v with
336 | Vfun f -> (k + 1, reduce_fun k f)
337 | _ -> assert false
338 in
339 let (_, v) = List.fold_right fold pctx (nb_rel env, v) in
340 let env = push_rel_context pctx env in
341 let body = nf_vtype env sigma v in
342 let rel = Retyping.relevance_of_type env sigma (EConstr.of_constr body) in
343 body, EConstr.Unsafe.to_relevance rel
344
345 and nf_telescope env sigma len f typ =
346 let open CClosure in
347 let t = ref (inject typ) in
348 let infos = Evarutil.create_clos_infos env sigma RedFlags.all in
349 let tab = create_tab () in
350 let init i =
351 let typ, stk = whd_stack infos tab !t [] in
352 let typ = zip typ stk in
353 match fterm_of typ with
354 | FProd (na, dom, codom, e) ->
355 let arg = f i in
356 let dom = term_of_fconstr dom in
357 let arg = nf_val env sigma arg dom in
358 let () = t := mk_clos (CClosure.usubs_cons (inject arg) e) codom in
359 arg
360 | _ -> assert false
361 in
362 let args = Array.init len init in
363 !t, args
364
365 and nf_args env sigma vargs ?from:(f=0) t =
366 let len = nargs vargs - f in
367 let fargs i = arg vargs (f + i) in
368 let typ, args = nf_telescope env sigma len fargs t in
369 CClosure.term_of_fconstr typ, args
370
371 and nf_bargs env sigma b ofs t =
372 let len = bsize b - ofs in
373 let fargs i = bfield b (i + ofs) in
374 snd @@ nf_telescope env sigma len fargs t
375
376 and nf_fun env sigma f typ =
377 let k = nb_rel env in
378 let vb = reduce_fun k f in
379 let name,dom,codom =
380 try decompose_prod env sigma typ
381 with DestKO ->
382 CErrors.anomaly
383 Pp.(strbrk "Returned a functional value in type " ++
384 Termops.Internal.print_constr_env env sigma (EConstr.of_constr typ))
385 in
386 let body = nf_val (push_rel (LocalAssum (name,dom)) env) sigma vb codom in
387 mkLambda(name,dom,body)
388
389 and nf_fix env sigma f =
390 let init = current_fix f in
391 let rec_args = rec_args f in
392 let k = nb_rel env in
393 let vb, vt = reduce_fix k f in
394 let ndef = Array.length vt in
395 let ft = Array.map (fun v -> nf_val env sigma v crazy_type) vt in
396 let name = Name (Id.of_string "Ffix") in
397 let names = Array.map (fun t ->
398 make_annot name @@
399 EConstr.Unsafe.to_relevance @@
400 Retyping.relevance_of_type env sigma (EConstr.of_constr t)) ft in
401 (* Body argument of the tuple is ignored by push_rec_types *)
402 let env = push_rec_types (names,ft,ft) env in
403 (* We lift here because the types of arguments (in tt) will be evaluated
404 in an environment where the fixpoints have been pushed *)
405 let norm_vb v t = nf_fun env sigma v (lift ndef t) in
406 let fb = Util.Array.map2 norm_vb vb ft in
407 mkFix ((rec_args,init),(names,ft,fb))
408
409 and nf_fix_app env sigma f vargs =
410 let fd = nf_fix env sigma f in
411 let (_,i),(_,ta,_) = destFix fd in
412 let t = ta.(i) in
413 let t, args = nf_args env sigma vargs t in
414 mkApp(fd,args),t
415
416 and nf_cofix env sigma cf =
417 let init = current_cofix cf in
418 let k = nb_rel env in
419 let vb,vt = reduce_cofix k cf in
420 let cft = Array.map (fun v -> nf_val env sigma v crazy_type) vt in
421 let name = Name (Id.of_string "Fcofix") in
422 let names = Array.map (fun t ->
423 make_annot name @@
424 EConstr.Unsafe.to_relevance @@
425 Retyping.relevance_of_type env sigma (EConstr.of_constr t)) cft in
426 let env = push_rec_types (names,cft,cft) env in
427 let cfb = Util.Array.map2 (fun v t -> nf_val env sigma v t) vb cft in
428 mkCoFix (init,(names,cft,cfb))
429
430 and nf_array env sigma t typ =
431 let ty, allargs = app_type env sigma (EConstr.of_constr typ) in
432 let typ_elem = allargs.(0) in
433 let vdef = Parray.default t in
434 (* Do not cast into an array out of fear that floats may sneak in *)
435 let init i = nf_val env sigma (Parray.get t (Uint63.of_int i)) typ_elem in
436 let t = Array.init (Parray.length_int t) init in
437 let u = snd (destConst ty) in
438 mkArray(u, t, nf_val env sigma vdef typ_elem, typ_elem)
439
440 let evars_of_evar_map sigma =
441 { Genlambda.evars_val = Evd.evar_handler sigma }
442
443 let cbv_vm env sigma c t =
444 if not (Environ.typing_flags env).enable_VM then
445 CErrors.user_err Pp.(str "vm_compute reduction has been disabled.");
446 if Termops.occur_meta sigma c then
447 CErrors.user_err Pp.(str "vm_compute does not support metas.");
448 (* This evar-normalizes terms beforehand *)
449 let c = EConstr.Unsafe.to_constr c in
450 let t = EConstr.Unsafe.to_constr t in
451 let v = Vmsymtable.val_of_constr env (evars_of_evar_map sigma) c in
452 EConstr.of_constr (nf_val env sigma v t)