Debian Codegraph @

kernel/genlambda.ml

raw symbols SCIP
1 (************************************************************************)
2 (* * The Rocq Prover / The Rocq Development Team *)
3 (* v * Copyright INRIA, CNRS and contributors *)
4 (* <O___,, * (see version control and CREDITS file for authors & dates) *)
5 (* \VV/ **************************************************************)
6 (* // * This file is distributed under the terms of the *)
7 (* * GNU Lesser General Public License Version 2.1 *)
8 (* * (see LICENSE file for the text of the license) *)
9 (************************************************************************)
10
11 open Pp
12 open Util
13 open Esubst
14 open Names
15 open Environ
16 open Declarations
17 open Constr
18
19 type reloc_table = (int * int) array
20
21 type case_annot = case_info * reloc_table * Declarations.recursivity_kind
22
23 type 'v node =
24 | Lrel of Name.t * int
25 | Lvar of Id.t
26 | Levar of Evar.t * 'v lambda array (* arguments *)
27 | Lprod of 'v lambda * 'v lambda
28 | Llam of Name.t binder_annot array * 'v lambda
29 | Llet of Name.t binder_annot * 'v lambda * 'v lambda
30 | Lapp of 'v lambda * 'v lambda array
31 | Lconst of pconstant
32 | Lproj of Projection.Repr.t * 'v lambda
33 | Lprim of pconstant * CPrimitives.t * 'v lambda array
34 | Lcase of case_annot * 'v lambda * 'v lambda * 'v lam_branches
35 (* annotations, term being matched, accu, branches *)
36 | Lfix of (int array * inductive array * int) * 'v fix_decl
37 | Lcofix of int * 'v fix_decl
38 | Lint of int
39 | Lparray of 'v lambda array * 'v lambda
40 | Lmakeblock of inductive * int * 'v lambda array
41 (* inductive name, constructor tag, arguments *)
42 | Luint of Uint63.t
43 | Lfloat of Float64.t
44 | Lstring of Pstring.t
45 | Lval of 'v
46 | Lsort of Sorts.t
47 | Lind of pinductive
48
49 and 'v lam_branches =
50 { constant_branches : 'v lambda array;
51 nonconstant_branches : (Name.t binder_annot array * 'v lambda) array }
52
53 and 'v fix_decl = Name.t binder_annot array * 'v lambda array * 'v lambda array
54
55 and 'v lambda = { node : 'v node }
56
57 type evars =
58 { evars_val : CClosure.evar_handler }
59
60 let empty_evars env =
61 { evars_val = CClosure.default_evar_handler env }
62
63 (** Printing **)
64
65 let pr_annot x = Name.print x.Context.binder_name
66
67 let pp_names ids =
68 prlist_with_sep (fun _ -> brk(1,1)) pr_annot (Array.to_list ids)
69
70 let pp_rel name n =
71 Name.print name ++ str "##" ++ int n
72
73 let pp_sort s =
74 match s with
75 | Sorts.Set -> str "Set"
76 | Sorts.Prop -> str "Prop"
77 | Sorts.SProp -> str "SProp"
78 | Sorts.Type _ | Sorts.QSort _ -> str "Type"
79
80 let pr_con sp = str(Names.Id.to_string (Constant.label sp))
81
82 let rec pp_lam lam =
83 match lam.node with
84 | Lrel (id,n) -> pp_rel id n
85 | Lvar id -> Id.print id
86 | Levar (evk, args) ->
87 hov 1 (str "evar(" ++ Evar.print evk ++ str "," ++ spc () ++
88 prlist_with_sep spc pp_lam (Array.to_list args) ++ str ")")
89 | Lprod(dom,codom) -> hov 1
90 (str "forall(" ++
91 pp_lam dom ++
92 str "," ++ spc() ++
93 pp_lam codom ++
94 str ")")
95 | Llam(ids,body) -> hov 1
96 (str "(fun " ++
97 pp_names ids ++
98 str " =>" ++
99 spc() ++
100 pp_lam body ++
101 str ")")
102 | Llet(id,def,body) -> hov 0
103 (str "let " ++
104 pr_annot id ++
105 str ":=" ++
106 pp_lam def ++
107 str " in" ++
108 spc() ++
109 pp_lam body)
110 | Lapp(f, args) -> hov 1
111 (str "(" ++ pp_lam f ++ spc() ++
112 prlist_with_sep spc pp_lam (Array.to_list args) ++
113 str")")
114 | Lconst (kn,_) -> pr_con kn
115 | Lcase(_annot, t, a, branches) ->
116 let ic = ref (-1) in
117 let ib = ref 0 in
118 v 0 (str"<" ++ pp_lam t ++ str">" ++ cut() ++
119 str "Case" ++ spc () ++ pp_lam a ++ spc() ++ str "of" ++ cut() ++
120 v 0
121 ((prlist_with_sep (fun _ -> str "")
122 (fun c ->
123 cut () ++ str "| " ++
124 int (incr ic; !ic) ++ str " => " ++ pp_lam c)
125 (Array.to_list branches.constant_branches)) ++
126 (prlist_with_sep (fun _ -> str "")
127 (fun (ids,c) ->
128 cut () ++ str "| " ++
129 int (incr ib; !ib) ++ str " " ++
130 pp_names ids ++ str " => " ++ pp_lam c)
131 (Array.to_list branches.nonconstant_branches)))
132 ++ cut() ++ str "end")
133 | Lfix ((t, _, i), (lna, tl, bl)) ->
134 let fixl = Array.mapi (fun i id -> (id,t.(i),tl.(i),bl.(i))) lna in
135 hov 1
136 (str"fix " ++ int i ++ spc() ++ str"{" ++
137 v 0
138 (prlist_with_sep spc
139 (fun (na,i,ty,bd) ->
140 pr_annot na ++ str"/" ++ int i ++ str":" ++
141 pp_lam ty ++ cut() ++ str":=" ++
142 pp_lam bd) (Array.to_list fixl)) ++
143 str"}")
144
145 | Lcofix (i,(lna,tl,bl)) ->
146 let fixl = Array.mapi (fun i na -> (na,tl.(i),bl.(i))) lna in
147 hov 1
148 (str"cofix " ++ int i ++ spc() ++ str"{" ++
149 v 0
150 (prlist_with_sep spc
151 (fun (na,ty,bd) ->
152 pr_annot na ++ str":" ++ pp_lam ty ++
153 cut() ++ str":=" ++ pp_lam bd) (Array.to_list fixl)) ++
154 str"}")
155 | Lparray (args, def) ->
156 hov 1
157 (str "(array " ++ spc() ++
158 prlist_with_sep spc pp_lam (Array.to_list args) ++
159 spc () ++ str "|" ++ spc () ++ pp_lam def ++ str")")
160 | Lmakeblock(_, tag, args) ->
161 hov 1
162 (str "(makeblock " ++ int tag ++ spc() ++
163 prlist_with_sep spc pp_lam (Array.to_list args) ++
164 str")")
165 | Luint i -> str (Uint63.to_string i)
166 | Lfloat f -> str (Float64.to_string f)
167 | Lstring s -> str (Printf.sprintf "%S" (Pstring.to_string s))
168 | Lval _ -> str "values"
169 | Lsort s -> pp_sort s
170 | Lind ((mind,i), _) -> MutInd.print mind ++ str"#" ++ int i
171 | Lprim ((kn,_u),_op,args) ->
172 hov 1
173 (str "(PRIM " ++ pr_con kn ++ spc() ++
174 prlist_with_sep spc pp_lam (Array.to_list args) ++
175 str")")
176 | Lproj(p,arg) ->
177 hov 1
178 (str "(proj " ++ str "{" ++ Projection.Repr.print p ++ str "}" ++ spc () ++ pp_lam arg
179 ++ str ")")
180 | Lint i ->
181 Pp.(str "(int:" ++ int i ++ str ")")
182
183 (*s Constructors *)
184
185 let mknode t = { node = t }
186
187 let node t = t.node
188
189 let mkLapp f args =
190 if Array.is_empty args then f
191 else
192 match f.node with
193 | Lapp(f', args') -> mknode @@ Lapp (f', Array.append args' args)
194 | _ -> mknode @@ Lapp(f, args)
195
196 let mkLlam ids body =
197 if Array.is_empty ids then body
198 else
199 match body.node with
200 | Llam(ids', body) -> mknode @@ Llam(Array.append ids ids', body)
201 | _ -> mknode @@ Llam(ids, body)
202
203 (* Hack: brutally pierce through the abstraction of PArray *)
204 let unsafe_mkPArray args def =
205 let dummy = KerName.make (ModPath.MPfile DirPath.empty) (Id.of_string "dummy") in
206 let dummy = (MutInd.make1 dummy, 0) in
207 let ar = mknode @@ Lmakeblock (dummy, 0, args) in
208 let kind = mknode @@ Lmakeblock (dummy, 0, [|ar; def|]) in (* Parray.Array *)
209 mknode @@ Lmakeblock (dummy, 0, [|kind|]) (* the reference *)
210
211 (* Same as above but with a blob instead of a block *)
212 let unsafe_mkPArray_val v def =
213 let dummy = KerName.make (ModPath.MPfile DirPath.empty) (Id.of_string "dummy") in
214 let dummy = (MutInd.make1 dummy, 0) in
215 let ar = mknode @@ Lval v in
216 let kind = mknode @@ Lmakeblock (dummy, 0, [|ar; def|]) in (* Parray.Array *)
217 mknode @@ Lmakeblock (dummy, 0, [|kind|]) (* the reference *)
218
219 let decompose_Llam lam =
220 match lam.node with
221 | Llam(ids,body) -> ids, body
222 | _ -> [||], lam
223
224 let rec decompose_Llam_Llet lam =
225 match lam.node with
226 | Llam(ids,body) ->
227 let vars, body = decompose_Llam_Llet body in
228 Array.fold_right (fun x l -> (x, None) :: l) ids vars, body
229 | Llet(id,def,body) ->
230 let vars, body = decompose_Llam_Llet body in
231 (id,Some def) :: vars, body
232 | _ -> [], lam
233
234 let decompose_Llam_Llet lam =
235 let vars, body = decompose_Llam_Llet lam in
236 Array.of_list vars, body
237
238 (* A generic map function *)
239
240 let map_lam_with_binders g f n lam =
241 match lam.node with
242 | Lrel _ | Lvar _ | Lconst _ | Lval _ | Lsort _ | Lind _ | Lint _ | Luint _
243 | Lfloat _ | Lstring _ -> lam
244 | Levar (evk, args) ->
245 let args' = Array.Smart.map (f n) args in
246 if args == args' then lam else mknode @@ Levar (evk, args')
247 | Lprod(dom,codom) ->
248 let dom' = f n dom in
249 let codom' = f n codom in
250 if dom == dom' && codom == codom' then lam else mknode @@ Lprod(dom',codom')
251 | Llam(ids,body) ->
252 let body' = f (g (Array.length ids) n) body in
253 if body == body' then lam else mkLlam ids body'
254 | Llet(id,def,body) ->
255 let def' = f n def in
256 let body' = f (g 1 n) body in
257 if body == body' && def == def' then lam else mknode @@ Llet(id,def',body')
258 | Lapp(fct,args) ->
259 let fct' = f n fct in
260 let args' = Array.Smart.map (f n) args in
261 if fct == fct' && args == args' then lam else mkLapp fct' args'
262 | Lcase (annot, t, a, branches) ->
263 let const = branches.constant_branches in
264 let nonconst = branches.nonconstant_branches in
265 let t' = f n t in
266 let a' = f n a in
267 let const' = Array.Smart.map (f n) const in
268 let on_b b =
269 let (ids,body) = b in
270 let body' = f (g (Array.length ids) n) body in
271 if body == body' then b else (ids,body') in
272 let nonconst' = Array.Smart.map on_b nonconst in
273 let branches' =
274 if const == const' && nonconst == nonconst' then
275 branches
276 else
277 { constant_branches = const';
278 nonconstant_branches = nonconst' }
279 in
280 if t == t' && a == a' && branches == branches' then lam else
281 mknode @@ Lcase(annot, t', a', branches')
282 | Lfix(init,(ids,ltypes,lbodies)) ->
283 let ltypes' = Array.Smart.map (f n) ltypes in
284 let lbodies' = Array.Smart.map (f (g (Array.length ids) n)) lbodies in
285 if ltypes == ltypes' && lbodies == lbodies' then lam
286 else mknode @@ Lfix(init,(ids,ltypes',lbodies'))
287 | Lcofix(init,(ids,ltypes,lbodies)) ->
288 let ltypes' = Array.Smart.map (f n) ltypes in
289 let lbodies' = Array.Smart.map (f (g (Array.length ids) n)) lbodies in
290 if ltypes == ltypes' && lbodies == lbodies' then lam
291 else mknode @@ Lcofix(init,(ids,ltypes',lbodies'))
292 | Lparray (args, def) ->
293 let args' = Array.Smart.map (f n) args in
294 let def' = f n def in
295 if args == args' && def == def' then lam else mknode @@ Lparray (args', def')
296 | Lmakeblock (inds, tag, args) ->
297 let args' = Array.Smart.map (f n) args in
298 if args == args' then lam else mknode @@ Lmakeblock (inds, tag,args')
299 | Lprim(kn,op,args) ->
300 let args' = Array.Smart.map (f n) args in
301 if args == args' then lam else mknode @@ Lprim(kn,op,args')
302 | Lproj(p,arg) ->
303 let arg' = f n arg in
304 if arg == arg' then lam else mknode @@ Lproj(p,arg')
305
306 (* Free rels *)
307
308 let free_rels lam =
309 let rec aux k accu lam = match node lam with
310 | Lrel (_, n) -> if n >= k then Int.Set.add (n - k + 1) accu else accu
311 | Lvar _ | Lconst _ | Lval _ | Lsort _ | Lind _ | Lint _ | Luint _
312 | Lfloat _ | Lstring _ -> accu
313 | Levar (_, args) ->
314 Array.fold_left (fun accu lam -> aux k accu lam) accu args
315 | Lprod (dom, codom) ->
316 aux k (aux k accu dom) codom
317 | Llam (ids, body) ->
318 aux (k + Array.length ids) accu body
319 | Llet (_, def, body) ->
320 aux (k + 1) (aux k accu def) body
321 | Lapp (fct, args) ->
322 let accu = aux k accu fct in
323 Array.fold_left (fun accu lam -> aux k accu lam) accu args
324 | Lcase (_, t, a, branches) ->
325 let const = branches.constant_branches in
326 let nonconst = branches.nonconstant_branches in
327 let accu = aux k accu t in
328 let accu = aux k accu a in
329 let accu = Array.fold_left (fun accu lam -> aux k accu lam) accu const in
330 let accu = Array.fold_left (fun accu (ids, lam) -> aux (k + Array.length ids) accu lam) accu nonconst in
331 accu
332 | Lfix (_, (ids, ltypes, lbodies)) | Lcofix (_, (ids, ltypes, lbodies)) ->
333 let accu = Array.fold_left (fun accu lam -> aux k accu lam) accu ltypes in
334 let accu = Array.fold_left (fun accu lam -> aux (k + Array.length ids) accu lam) accu lbodies in
335 accu
336 | Lparray (args, def) ->
337 let accu = Array.fold_left (fun accu lam -> aux k accu lam) accu args in
338 aux k accu def
339 | Lmakeblock (_, _, args) ->
340 Array.fold_left (fun accu lam -> aux k accu lam) accu args
341 | Lprim (_, _, args) ->
342 Array.fold_left (fun accu lam -> aux k accu lam) accu args
343 | Lproj (_, arg) ->
344 aux k accu arg
345 in
346 aux 1 Int.Set.empty lam
347
348 (*s Operators on substitution *)
349 let lift = subs_lift
350 let liftn = subs_liftn
351 let cons v subst = subs_cons v subst
352 let shift subst = subs_shft (1, subst)
353
354 (*s Lift and substitution *)
355
356 let rec lam_exlift el lam =
357 match lam.node with
358 | Lrel(id,i) ->
359 let i' = reloc_rel i el in
360 if i == i' then lam else mknode @@ Lrel(id,i')
361 | _ -> map_lam_with_binders el_liftn lam_exlift el lam
362
363 let lam_lift k lam =
364 if Int.equal k 0 then lam
365 else lam_exlift (el_shft k el_id) lam
366
367 let lam_subst_rel lam id n subst =
368 match expand_rel n subst with
369 | Inl(k,v) -> lam_lift k v
370 | Inr(n',_) ->
371 if n == n' then lam
372 else mknode @@ Lrel(id, n')
373
374 let rec lam_exsubst subst lam =
375 match lam.node with
376 | Lrel(id,i) -> lam_subst_rel lam id i subst
377 | _ -> map_lam_with_binders liftn lam_exsubst subst lam
378
379 let lam_subst_args subst args =
380 if is_subs_id subst then args
381 else Array.Smart.map (lam_exsubst subst) args
382
383 (* [simplify subst lam] simplifies the expression [lam_subst subst lam] by: *)
384 (* - Reducing [let] is the definition can be substituted *)
385 (* - Transforming beta redex into [let] expression *)
386 (* - Moving arguments under [let] *)
387 (* Invariant: Terms in [subst] are already simplified and can be substituted *)
388
389 let can_subst lam = match node lam with
390 | Lrel _ | Lvar _ | Lconst _ | Luint _
391 | Lval _ | Lsort _ | Lind _ -> true
392 | Levar _ | Lprod _ | Llam _ | Llet _ | Lapp _ | Lcase _ | Lfix _ | Lcofix _
393 | Lparray _ | Lmakeblock _ | Lfloat _ | Lstring _ | Lprim _ | Lproj _ -> false
394 | Lint _ -> false (* TODO: allow substitution of integers *)
395
396 let simplify lam =
397 let rec simplify subst lam =
398 match lam.node with
399 | Lrel(id,i) -> lam_subst_rel lam id i subst
400
401 | Llet(id,def,body) ->
402 let def' = simplify subst def in
403 if can_subst def' then simplify (cons def' subst) body
404 else
405 let body' = simplify (lift subst) body in
406 if def == def' && body == body' then lam
407 else mknode @@ Llet(id,def',body')
408
409 | Lapp(f,args) ->
410 begin match simplify_app subst f subst args with
411 | { node = Lapp(f',args') } when f == f' && args == args' -> lam
412 | lam' -> lam'
413 end
414
415 | _ -> map_lam_with_binders liftn simplify subst lam
416
417 and simplify_app substf f substa args =
418 match f.node with
419 | Lrel(id, i) ->
420 begin match lam_subst_rel f id i substf with
421 | { node = Llam(ids, body) } ->
422 reduce_lapp
423 (subs_id 0) (Array.to_list ids) body
424 substa (Array.to_list args)
425 | f' -> mkLapp f' (simplify_args substa args)
426 end
427 | Llam(ids, body) ->
428 reduce_lapp substf (Array.to_list ids) body substa (Array.to_list args)
429 | Llet(id, def, body) ->
430 let def' = simplify substf def in
431 if can_subst def' then
432 simplify_app (cons def' substf) body substa args
433 else
434 mknode @@ Llet(id, def', simplify_app (lift substf) body (shift substa) args)
435 | Lapp(f, args') ->
436 let args = Array.append
437 (lam_subst_args substf args') (lam_subst_args substa args) in
438 simplify_app substf f (subs_id 0) args
439 | _ -> mkLapp (simplify substf f) (simplify_args substa args)
440
441 and simplify_args subst args = Array.Smart.map (fun c -> simplify subst c) args
442
443 and reduce_lapp substf lids body substa largs =
444 match lids, largs with
445 | id::lids, a::largs ->
446 let a = simplify substa a in
447 if can_subst a then
448 reduce_lapp (subs_cons a substf) lids body substa largs
449 else
450 let body = reduce_lapp (lift substf) lids body (shift substa) largs in
451 mknode @@ Llet(id, a, body)
452 | [], [] -> simplify substf body
453 | _::_, _ ->
454 mknode @@ Llam(Array.of_list lids, simplify (liftn (List.length lids) substf) body)
455 | [], _ -> simplify_app substf body substa (Array.of_list largs)
456 in
457 simplify (subs_id 0) lam
458
459 (* [occurrence kind k lam]:
460 If [kind] is [true] return [true] if the variable [k] does not appear in
461 [lam], return [false] if the variable appear one time and not
462 under a lambda, a fixpoint, a cofixpoint; else raise Not_found.
463 If [kind] is [false] return [false] if the variable does not appear in [lam]
464 else raise [Not_found]
465 *)
466
467 let rec occurrence k kind lam =
468 match lam.node with
469 | Lrel (_,n) ->
470 if n = k then
471 if kind then false else raise Not_found
472 else kind
473 | Lvar _ | Lconst _ | Lval _ | Lsort _ | Lind _ | Lint _ | Luint _
474 | Lfloat _ | Lstring _ -> kind
475 | Levar (_, args) ->
476 occurrence_args k kind args
477 | Lprod(dom, codom) ->
478 occurrence k (occurrence k kind dom) codom
479 | Llam(ids,body) ->
480 let _ = occurrence (k+Array.length ids) false body in kind
481 | Llet(_,def,body) ->
482 occurrence (k+1) (occurrence k kind def) body
483 | Lapp(f, args) ->
484 occurrence_args k (occurrence k kind f) args
485 | Lparray (args, def) ->
486 occurrence_args k (occurrence k kind def) args
487 | Lprim(_,_,args) | Lmakeblock(_, _,args) ->
488 occurrence_args k kind args
489 | Lcase(_, t, a, branches) ->
490 let kind = occurrence k (occurrence k kind t) a in
491 let r = ref kind in
492 Array.iter (fun c -> r := occurrence k kind c && !r) branches.constant_branches;
493 let on_b (ids,c) =
494 r := occurrence (k+Array.length ids) kind c && !r
495 in
496 Array.iter on_b branches.nonconstant_branches;
497 !r
498 | Lfix(_,(ids,ltypes,lbodies))
499 | Lcofix(_,(ids,ltypes,lbodies)) ->
500 let kind = occurrence_args k kind ltypes in
501 let _ = occurrence_args (k+Array.length ids) false lbodies in
502 kind
503 | Lproj(_,arg) ->
504 occurrence k kind arg
505
506 and occurrence_args k kind args =
507 Array.fold_left (occurrence k) kind args
508
509 let occur_once lam =
510 try let _ = occurrence 1 true lam in true
511 with Not_found -> false
512
513 (* [remove_let lam] remove let expression in [lam] if the variable is *)
514 (* used at most once time in the body, and does not appear under *)
515 (* a lambda or a fix or a cofix *)
516
517 let is_value lam = match node lam with
518 | Lrel _ | Lvar _ | Lconst _ | Luint _
519 | Lval _ | Lsort _ | Lind _ | Lint _ | Llam _ | Lfix _ | Lcofix _ | Lfloat _ | Lstring _ -> true
520 | Levar _ | Lprod _ | Llet _ | Lapp _ | Lcase _
521 | Lparray _ | Lmakeblock _ | Lprim _ | Lproj _ -> false
522
523 let rec remove_let subst lam =
524 match lam.node with
525 | Lrel(id,i) -> lam_subst_rel lam id i subst
526 | Llet(id,def,body) ->
527 let def' = remove_let subst def in
528 if occur_once body && is_value body then remove_let (cons def' subst) body
529 else
530 let body' = remove_let (lift subst) body in
531 if def == def' && body == body' then lam else mknode @@ Llet(id,def',body')
532 | _ -> map_lam_with_binders liftn remove_let subst lam
533
534 let optimize lam =
535 let lam = simplify lam in
536 let lam = remove_let (subs_id 0) lam in
537 lam
538
539 (* Compiling constants *)
540
541 let rec get_alias env sigma kn =
542 let cb = CClosure.lookup_constant_handler env sigma.evars_val kn in
543 let tps = cb.const_body_code in
544 match tps with
545 | Vmemitcodes.BCalias kn' -> get_alias env sigma kn'
546 | Vmemitcodes.BCconstant -> kn, [||]
547 | Vmemitcodes.BCdefined (mask, _, _) -> kn, mask
548
549 (* Translation of constructors *)
550
551 let make_args start _end =
552 Array.init (start - _end + 1) (fun i -> mknode @@ Lrel (Anonymous, start - i))
553
554 let expand_constructor ind tag nparams arity =
555 let anon = Context.make_annot Anonymous Sorts.Relevant in (* TODO relevance *)
556 let ids = Array.make (nparams + arity) anon in
557 if Int.equal arity 0 then mkLlam ids (mknode @@ (Lint tag))
558 else
559 let args = make_args arity 1 in
560 mknode @@ Llam(ids, mknode @@ Lmakeblock (ind, tag, args))
561
562 let makeblock as_val ind tag nparams arity args =
563 let nargs = Array.length args in
564 if nparams > 0 || nargs < arity then
565 mkLapp (expand_constructor ind tag nparams arity) args
566 else
567 (* The constructor is fully applied *)
568 if arity = 0 then mknode @@ Lint tag
569 else match as_val tag args with
570 | Some v -> mknode @@ Lval v
571 | None -> mknode @@ Lmakeblock (ind, tag, args)
572
573 (* Compilation of primitive *)
574
575 let prim _env kn p args =
576 mknode @@ Lprim (kn, p, args)
577
578 let expand_prim env kn op arity =
579 (* primitives are always Relevant *)
580 let ids = Array.make arity Context.anonR in
581 let args = make_args arity 1 in
582 mknode @@ Llam(ids, prim env kn op args)
583
584 let lambda_of_prim env kn op args =
585 let arity = CPrimitives.arity op in
586 match Int.compare (Array.length args) arity with
587 | 0 -> prim env kn op args
588 | x when x > 0 ->
589 let prim_args = Array.sub args 0 arity in
590 let extra_args = Array.sub args arity (Array.length args - arity) in
591 mkLapp(prim env kn op prim_args) extra_args
592 | _ -> mkLapp (expand_prim env kn op arity) args
593
594 module RelDecl = Context.Rel.Declaration
595
596 type tag = int
597
598 module type S =
599 sig
600 type value
601 val as_value : int -> value lambda array -> value option
602 val check_inductive : inductive -> mutual_inductive_body -> unit
603 end
604
605 module Make (Val : S) =
606 struct
607
608 (* [nparams] is the number of parameters still expected *)
609 let makeblock _env ind tag nparams arity args =
610 makeblock Val.as_value ind tag nparams arity args
611
612 (*i Global environment *)
613
614 let get_names decl =
615 let decl = Array.of_list decl in
616 Array.map fst decl
617
618 let empty_args = [||]
619
620 module Cache =
621 struct
622
623 module ConstrTable = Hashtbl.Make(Construct.UserOrd)
624
625 type constructor_info = tag * int * int (* nparam nrealargs *)
626
627 let get_construct_info cache env c : constructor_info =
628 try ConstrTable.find cache c
629 with Not_found ->
630 let ((mind,j), i) = c in
631 let oib = lookup_mind mind env in
632 let oip = oib.mind_packets.(j) in
633 let () = Val.check_inductive (mind, j) oib in
634 let tag,arity = oip.mind_reloc_tbl.(i-1) in
635 let nparams = oib.mind_nparams in
636 let r = (tag, nparams, arity) in
637 ConstrTable.add cache c r;
638 r
639 end
640
641 let evar_value sigma ev = sigma.evars_val.CClosure.evar_expand ev
642
643 (** Extract the inductive type over which a fixpoint is decreasing *)
644 let rec get_fix_struct env i t = match kind (Reduction.whd_all env t) with
645 | Prod (na, dom, t) ->
646 if Int.equal i 0 then
647 let dom = Reduction.whd_all env dom in
648 let (dom, _) = decompose_app dom in
649 match kind dom with
650 | Ind (ind, _) -> ind
651 | _ -> assert false
652 else
653 let env = Environ.push_rel (RelDecl.LocalAssum (na, dom)) env in
654 get_fix_struct env (i - 1) t
655 | _ -> assert false
656
657 let rec lambda_of_constr cache env sigma c =
658 match kind c with
659 | Meta _ ->
660 raise (Invalid_argument "lambda_of_constr: Meta")
661
662 | Evar ev ->
663 (match evar_value sigma ev with
664 | CClosure.EvarUndefined (evk, args) ->
665 let args = Array.map_of_list (fun c -> lambda_of_constr cache env sigma c) args in
666 mknode @@ Levar(evk, args)
667 | CClosure.EvarDefined t -> lambda_of_constr cache env sigma t)
668
669 | Cast (c, _, _) -> lambda_of_constr cache env sigma c
670
671 | Rel i -> mknode @@ Lrel (RelDecl.get_name (Environ.lookup_rel i env), i)
672
673 | Var id -> mknode @@ Lvar id
674
675 | Sort s -> mknode @@ Lsort s
676
677 | Ind pind -> mknode @@ Lind pind
678
679 | Prod(id, dom, codom) ->
680 let ld = lambda_of_constr cache env sigma dom in
681 let env = Environ.push_rel (RelDecl.LocalAssum (id, dom)) env in
682 let lc = lambda_of_constr cache env sigma codom in
683 mknode @@ Lprod(ld, mknode @@ Llam([|id|], lc))
684
685 | Lambda _ ->
686 let params, body = Term.decompose_lambda c in
687 let fold (na, t) env = Environ.push_rel (RelDecl.LocalAssum (na, t)) env in
688 let env = List.fold_right fold params env in
689 let lb = lambda_of_constr cache env sigma body in
690 let ids = get_names (List.rev params) in
691 mkLlam ids lb
692
693 | LetIn(id, def, t, body) ->
694 let ld = lambda_of_constr cache env sigma def in
695 let env = Environ.push_rel (RelDecl.LocalDef (id, def, t)) env in
696 let lb = lambda_of_constr cache env sigma body in
697 mknode @@ Llet(id, ld, lb)
698
699 | App(f, args) -> lambda_of_app cache env sigma f args
700
701 | Const _ -> lambda_of_app cache env sigma c empty_args
702
703 | Construct _ -> lambda_of_app cache env sigma c empty_args
704
705 | Proj (p, _, c) ->
706 let c = lambda_of_constr cache env sigma c in
707 mknode @@ Lproj (Projection.repr p, c)
708
709 | Case (ci, u, pms, t, iv, a, br) -> (* XXX handle iv *)
710 let (ci, (t,_), _iv, a, branches) = Inductive.expand_case env (ci, u, pms, t, iv, a, br) in
711 let (mind, i) = ci.ci_ind in
712 let mib = lookup_mind mind env in
713 let oib = mib.mind_packets.(i) in
714 let tbl = oib.mind_reloc_tbl in
715 (* Building info *)
716 let annot_sw = (ci, tbl, mib.mind_finite) in
717 (* translation of the argument *)
718 let la = lambda_of_constr cache env sigma a in
719 (* translation of the type *)
720 let lt = lambda_of_constr cache env sigma t in
721 (* translation of branches *)
722 let dummy = mknode @@ Lrel(Anonymous,0) in
723 let consts = Array.make oib.mind_nb_constant dummy in
724 let blocks = Array.make oib.mind_nb_args ([||],dummy) in
725 let rtbl = oib.mind_reloc_tbl in
726 for i = 0 to Array.length rtbl - 1 do
727 let tag, arity = rtbl.(i) in
728 let b = lambda_of_constr cache env sigma branches.(i) in
729 if arity = 0 then consts.(tag) <- b
730 else
731 let b =
732 match b.node with
733 | Llam (ids, body) when arity <= Array.length ids ->
734 let ids, rem = Array.chop arity ids in
735 (ids, mkLlam rem body)
736 | _ ->
737 (* happens when the branch contains let-bindings *)
738 let anon = Context.make_annot Anonymous Sorts.Relevant in (* TODO relevance *)
739 let ids = Array.make arity anon in
740 let args = make_args arity 1 in
741 let ll = lam_lift arity b in
742 (ids, mkLapp ll args)
743 in blocks.(tag-1) <- b
744 done;
745 let branches =
746 { constant_branches = consts;
747 nonconstant_branches = blocks }
748 in
749 mknode @@ Lcase(annot_sw, lt, la, branches)
750
751 | Fix((pos, i), (names,type_bodies,rec_bodies)) ->
752 let ltypes = lambda_of_args cache env sigma 0 type_bodies in
753 let map i t = get_fix_struct env i t in
754 let inds = Array.map2 map pos type_bodies in
755 let env = Environ.push_rec_types (names, type_bodies, rec_bodies) env in
756 let lbodies = lambda_of_args cache env sigma 0 rec_bodies in
757 mknode @@ Lfix((pos, inds, i), (names, ltypes, lbodies))
758
759 | CoFix(init,(names,type_bodies,rec_bodies)) ->
760 let ltypes = lambda_of_args cache env sigma 0 type_bodies in
761 let env = Environ.push_rec_types (names, type_bodies, rec_bodies) env in
762 let map c ty = Reduction.eta_expand env c (Vars.lift (Array.length type_bodies) ty) in
763 let rec_bodies = Array.map2 map rec_bodies type_bodies in
764 let lbodies = lambda_of_args cache env sigma 0 rec_bodies in
765 mknode @@ Lcofix(init, (names, ltypes, lbodies))
766
767 | Int i -> mknode @@ Luint i
768
769 | Float f -> mknode @@ Lfloat f
770
771 | String s -> mknode @@ (Lstring s)
772
773 | Array (_u, t, def, _ty) ->
774 let def = lambda_of_constr cache env sigma def in
775 mknode @@ Lparray (lambda_of_args cache env sigma 0 t, def)
776
777 and lambda_of_app cache env sigma f args =
778 match kind f with
779 | Const (kn, u as c) ->
780 let kn, mask = get_alias env sigma kn in
781 let cb = CClosure.lookup_constant_handler env sigma.evars_val kn in
782 begin match cb.const_body with
783 | Primitive op -> lambda_of_prim env c op (lambda_of_args cache env sigma 0 args)
784 | Def csubst -> (* TODO optimize if f is a proj and argument is known *)
785 if cb.const_inline_code then
786 let csubst = Vars.subst_instance_constr u csubst in
787 lambda_of_app cache env sigma csubst args
788 else
789 (* Erase unused arguments *)
790 let mapi i arg =
791 let keep = if i < Array.length mask then mask.(i) else true in
792 if keep then lambda_of_constr cache env sigma arg
793 else mknode (Lint 0) (* dummy *)
794 in
795 let args = Array.mapi mapi args in
796 mkLapp (mknode @@ Lconst (kn, u)) args
797 | OpaqueDef _ | Undef _ | Symbol _ ->
798 mkLapp (mknode @@ Lconst (kn, u)) (lambda_of_args cache env sigma 0 args)
799 end
800 | Construct ((ind,_ as c),_) ->
801 let tag, nparams, arity = Cache.get_construct_info cache env c in
802 let nargs = Array.length args in
803 if nparams < nargs then (* got all parameters *)
804 let args = lambda_of_args cache env sigma nparams args in
805 makeblock env ind tag 0 arity args
806 else makeblock env ind tag (nparams - nargs) arity empty_args
807 | _ ->
808 let f = lambda_of_constr cache env sigma f in
809 let args = lambda_of_args cache env sigma 0 args in
810 mkLapp f args
811
812 and lambda_of_args cache env sigma start args =
813 let nargs = Array.length args in
814 if start < nargs then
815 Array.init (nargs - start)
816 (fun i -> lambda_of_constr cache env sigma args.(start + i))
817 else empty_args
818
819 let lambda_of_constr env sigma c =
820 let cache = Cache.ConstrTable.create 91 in
821 lambda_of_constr cache env sigma c
822
823 end