Debian Codegraph @

plugins/extraction/mlutil.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 Libnames
15 open Table
16 open Miniml
17 (*i*)
18
19 (*s Exceptions. *)
20
21 exception Found
22 exception Impossible
23
24 (*S Names operations. *)
25
26 let eq_global g1 g2 = GlobRef.CanOrd.equal g1.glob g2.glob (* FIXME *)
27
28 let anonymous_name = Id.of_string "x"
29 let dummy_name = Id.of_string "_"
30
31 let anonymous = Id anonymous_name
32
33 let id_of_name = function
34 | Name.Anonymous -> anonymous_name
35 | Name.Name id when Id.equal id dummy_name -> anonymous_name
36 | Name.Name id -> id
37
38 let id_of_mlid = function
39 | Dummy -> dummy_name
40 | Id id -> id
41 | Tmp id -> id
42
43 let tmp_id = function
44 | Id id -> Tmp id
45 | a -> a
46
47 let is_tmp = function Tmp _ -> true | _ -> false
48
49 (*S Operations upon ML types (with meta). *)
50
51 let meta_count = ref 0
52
53 let reset_meta_count () = meta_count := 0
54
55 let new_meta _ =
56 incr meta_count;
57 Tmeta {id = !meta_count; contents = None}
58
59 let rec eq_ml_type t1 t2 = match t1, t2 with
60 | Tarr (tl1, tr1), Tarr (tl2, tr2) ->
61 eq_ml_type tl1 tl2 && eq_ml_type tr1 tr2
62 | Tglob (gr1, t1), Tglob (gr2, t2) ->
63 eq_global gr1 gr2 && List.equal eq_ml_type t1 t2
64 | Tvar i1, Tvar i2 -> Int.equal i1 i2
65 | Tvar' i1, Tvar' i2 -> Int.equal i1 i2
66 | Tmeta m1, Tmeta m2 -> eq_ml_meta m1 m2
67 | Tdummy k1, Tdummy k2 -> k1 == k2
68 | Tunknown, Tunknown -> true
69 | Taxiom, Taxiom -> true
70 | (Tarr _ | Tglob _ | Tvar _ | Tvar' _ | Tmeta _ | Tdummy _ | Tunknown | Taxiom), _
71 -> false
72
73 and eq_ml_meta m1 m2 =
74 Int.equal m1.id m2.id && Option.equal eq_ml_type m1.contents m2.contents
75
76 (* Simultaneous substitution of [[Tvar 1; ... ; Tvar n]] by [l] in a ML type. *)
77
78 let type_subst_list l t =
79 let rec subst t = match t with
80 | Tvar j -> List.nth l (j-1)
81 | Tmeta {contents=None} -> t
82 | Tmeta {contents=Some u} -> subst u
83 | Tarr (a,b) -> Tarr (subst a, subst b)
84 | Tglob (r, l) -> Tglob (r, List.map subst l)
85 | a -> a
86 in subst t
87
88 (* Simultaneous substitution of [[|Tvar 1; ... ; Tvar n|]] by [v] in a ML type. *)
89
90 let type_subst_vect v t =
91 let rec subst t = match t with
92 | Tvar j -> v.(j-1)
93 | Tmeta {contents=None} -> t
94 | Tmeta {contents=Some u} -> subst u
95 | Tarr (a,b) -> Tarr (subst a, subst b)
96 | Tglob (r, l) -> Tglob (r, List.map subst l)
97 | a -> a
98 in subst t
99
100 (*s From a type schema to a type. All [Tvar] become fresh [Tmeta]. *)
101
102 let instantiation (nb,t) = type_subst_vect (Array.init nb new_meta) t
103
104 (*s Occur-check of a free meta in a type *)
105
106 let rec type_occurs alpha t =
107 match t with
108 | Tmeta {id=beta; contents=None} -> Int.equal alpha beta
109 | Tmeta {contents=Some u} -> type_occurs alpha u
110 | Tarr (t1, t2) -> type_occurs alpha t1 || type_occurs alpha t2
111 | Tglob (r,l) -> List.exists (type_occurs alpha) l
112 | (Tdummy _ | Tvar _ | Tvar' _ | Taxiom | Tunknown) -> false
113
114 (*s Most General Unificator *)
115
116 let rec mgu = function
117 | Tmeta m, Tmeta m' when Int.equal m.id m'.id -> ()
118 | Tmeta m, t | t, Tmeta m ->
119 (match m.contents with
120 | Some u -> mgu (u, t)
121 | None when type_occurs m.id t -> raise Impossible
122 | None -> m.contents <- Some t)
123 | Tarr(a, b), Tarr(a', b') ->
124 mgu (a, a'); mgu (b, b')
125 | Tglob (r,l), Tglob (r',l') when eq_global r r' ->
126 List.iter mgu (List.combine l l')
127 | Tdummy _, Tdummy _ -> ()
128 | Tvar i, Tvar j when Int.equal i j -> ()
129 | Tvar' i, Tvar' j when Int.equal i j -> ()
130 | Tunknown, Tunknown -> ()
131 | Taxiom, Taxiom -> ()
132 | _ -> raise Impossible
133
134 let skip_typing () = lang () == Scheme
135
136 let needs_magic p =
137 if skip_typing () then false
138 else try mgu p; false with Impossible -> true
139
140 let put_magic_if b a = if b then MLmagic a else a
141
142 let put_magic p a = if needs_magic p then MLmagic a else a
143
144 let generalizable a =
145 lang () != Ocaml ||
146 match a with
147 | MLapp _ -> false
148 | _ -> true (* TODO, this is just an approximation for the moment *)
149
150 (*S ML type env. *)
151
152 module Mlenv = struct
153
154 let meta_cmp m m' = compare m.id m'.id
155 module Metaset = Set.Make(struct type t = ml_meta let compare = meta_cmp end)
156
157 (* Main MLenv type. [env] is the real environment, whereas [free]
158 (tries to) record the free meta variables occurring in [env]. *)
159
160 type t = { env : ml_schema list; mutable free : Metaset.t}
161
162 (* Empty environment. *)
163
164 let empty = { env = []; free = Metaset.empty }
165
166 (* [get] returns a instantiated copy of the n-th most recently added
167 type in the environment. *)
168
169 let get mle n =
170 assert (List.length mle.env >= n);
171 instantiation (List.nth mle.env (n-1))
172
173 (* [find_free] finds the free meta in a type. *)
174
175 let rec find_free set = function
176 | Tmeta m when Option.is_empty m.contents -> Metaset.add m set
177 | Tmeta {contents = Some t} -> find_free set t
178 | Tarr (a,b) -> find_free (find_free set a) b
179 | Tglob (_,l) -> List.fold_left find_free set l
180 | _ -> set
181
182 (* The [free] set of an environment can be outdate after
183 some unifications. [clean_free] takes care of that. *)
184
185 let clean_free mle =
186 let rem = ref Metaset.empty
187 and add = ref Metaset.empty in
188 let clean m = match m.contents with
189 | None -> ()
190 | Some u -> rem := Metaset.add m !rem; add := find_free !add u
191 in
192 Metaset.iter clean mle.free;
193 mle.free <- Metaset.union (Metaset.diff mle.free !rem) !add
194
195 (* From a type to a type schema. If a [Tmeta] is still uninstantiated
196 and does appears in the [mle], then it becomes a [Tvar]. *)
197
198 let generalization mle t =
199 let c = ref 0 in
200 let map = ref (Int.Map.empty : int Int.Map.t) in
201 let add_new i = incr c; map := Int.Map.add i !c !map; !c in
202 let rec meta2var t = match t with
203 | Tmeta {contents=Some u} -> meta2var u
204 | Tmeta ({id=i} as m) ->
205 (try Tvar (Int.Map.find i !map)
206 with Not_found ->
207 if Metaset.mem m mle.free then t
208 else Tvar (add_new i))
209 | Tarr (t1,t2) -> Tarr (meta2var t1, meta2var t2)
210 | Tglob (r,l) -> Tglob (r, List.map meta2var l)
211 | t -> t
212 in !c, meta2var t
213
214 (* Adding a type in an environment, after generalizing. *)
215
216 let push_gen mle t =
217 clean_free mle;
218 { env = generalization mle t :: mle.env; free = mle.free }
219
220 (* Adding a type with no [Tvar], hence no generalization needed. *)
221
222 let push_type mle t =
223 { env = (0,t) :: mle.env; free = find_free mle.free t}
224
225 (* Adding a type with no [Tvar] nor [Tmeta]. *)
226
227 let push_std_type mle t =
228 { env = (0,t) :: mle.env; free = mle.free}
229
230 end
231
232 (*S Operations upon ML types (without meta). *)
233
234 (*s Does a section path occur in a ML type ? *)
235
236 let rec type_mem_kn kn = function
237 | Tmeta {contents = Some t} -> type_mem_kn kn t
238 | Tglob (r,l) -> occur_kn_in_ref kn r || List.exists (type_mem_kn kn) l
239 | Tarr (a,b) -> (type_mem_kn kn a) || (type_mem_kn kn b)
240 | _ -> false
241
242 (*s Greatest variable occurring in [t]. *)
243
244 let type_maxvar t =
245 let rec parse n = function
246 | Tmeta {contents = Some t} -> parse n t
247 | Tvar i -> max i n
248 | Tarr (a,b) -> parse (parse n a) b
249 | Tglob (_,l) -> List.fold_left parse n l
250 | _ -> n
251 in parse 0 t
252
253 (*s From [a -> b -> c] to [[a;b],c]. *)
254
255 let rec type_decomp = function
256 | Tmeta {contents = Some t} -> type_decomp t
257 | Tarr (a,b) -> let l,h = type_decomp b in a::l, h
258 | a -> [],a
259
260 (*s The converse: From [[a;b],c] to [a -> b -> c]. *)
261
262 let rec type_recomp (l,t) = match l with
263 | [] -> t
264 | a::l -> Tarr (a, type_recomp (l,t))
265
266 (*s Translating [Tvar] to [Tvar'] to avoid clash. *)
267
268 let rec var2var' = function
269 | Tmeta {contents = Some t} -> var2var' t
270 | Tvar i -> Tvar' i
271 | Tarr (a,b) -> Tarr (var2var' a, var2var' b)
272 | Tglob (r,l) -> Tglob (r, List.map var2var' l)
273 | a -> a
274
275 type abbrev_map = global -> ml_type option
276
277 (*s Delta-reduction of type constants everywhere in a ML type [t].
278 [env] is a function of type [ml_type_env]. *)
279
280 let type_expand env t =
281 let rec expand = function
282 | Tmeta {contents = Some t} -> expand t
283 | Tglob (r,l) ->
284 (match env r with
285 | Some mlt -> expand (type_subst_list l mlt)
286 | None -> Tglob (r, List.map expand l))
287 | Tarr (a,b) -> Tarr (expand a, expand b)
288 | a -> a
289 in if Table.type_expand () then expand t else t
290
291 let type_simpl = type_expand (fun _ -> None)
292
293 (*s Generating a signature from a ML type. *)
294
295 let type_to_sign env t = match type_expand env t with
296 | Tdummy d when not (conservative_types ()) -> Kill d
297 | _ -> Keep
298
299 let type_to_signature env t =
300 let rec f = function
301 | Tmeta {contents = Some t} -> f t
302 | Tarr (Tdummy d, b) when not (conservative_types ()) -> Kill d :: f b
303 | Tarr (_, b) -> Keep :: f b
304 | _ -> []
305 in f (type_expand env t)
306
307 let isKill = function Kill _ -> true | _ -> false
308
309 let isTdummy = function Tdummy _ -> true | _ -> false
310
311 let isMLdummy = function MLdummy _ -> true | _ -> false
312
313 let sign_of_id = function
314 | Dummy -> Kill Kprop
315 | (Id _ | Tmp _) -> Keep
316
317 (* Classification of signatures *)
318
319 type sign_kind =
320 | EmptySig
321 | NonLogicalSig (* at least a [Keep] *)
322 | SafeLogicalSig (* only [Kill Ktype] *)
323 | UnsafeLogicalSig (* No [Keep], not all [Kill Ktype] *)
324
325 let rec sign_kind = function
326 | [] -> EmptySig
327 | Keep :: _ -> NonLogicalSig
328 | Kill k :: s ->
329 match k, sign_kind s with
330 | _, NonLogicalSig -> NonLogicalSig
331 | Ktype, (SafeLogicalSig | EmptySig) -> SafeLogicalSig
332 | _, _ -> UnsafeLogicalSig
333
334 (* Removing the final [Keep] in a signature *)
335
336 let rec sign_no_final_keeps = function
337 | [] -> []
338 | k :: s ->
339 match k, sign_no_final_keeps s with
340 | Keep, [] -> []
341 | k, l -> k::l
342
343 (*s Removing [Tdummy] from the top level of a ML type. *)
344
345 let type_expunge_from_sign env s t =
346 let rec expunge s t = match s, t with
347 | [], _ -> t
348 | Keep :: s, Tarr(a,b) -> Tarr (a, expunge s b)
349 | Kill _ :: s, Tarr(a,b) -> expunge s b
350 | _, Tmeta {contents = Some t} -> expunge s t
351 | _, Tglob (r,l) ->
352 (match env r with
353 | Some mlt -> expunge s (type_subst_list l mlt)
354 | None -> assert false)
355 | _ -> assert false
356 in
357 let t = expunge (sign_no_final_keeps s) t in
358 if lang () != Haskell && sign_kind s == UnsafeLogicalSig then
359 Tarr (Tdummy Kprop, t)
360 else t
361
362 let type_expunge env t =
363 type_expunge_from_sign env (type_to_signature env t) t
364
365 (*S Generic functions over ML ast terms. *)
366
367 let mlapp f a = if List.is_empty a then f else MLapp (f,a)
368
369 (** Equality *)
370
371 let eq_ml_ident i1 i2 = match i1, i2 with
372 | Dummy, Dummy -> true
373 | Id id1, Id id2 -> Id.equal id1 id2
374 | Tmp id1, Tmp id2 -> Id.equal id1 id2
375 | Dummy, (Id _ | Tmp _)
376 | Id _, (Dummy | Tmp _)
377 | Tmp _, (Dummy | Id _)
378 -> false
379
380 let rec eq_ml_ast t1 t2 = match t1, t2 with
381 | MLrel i1, MLrel i2 ->
382 Int.equal i1 i2
383 | MLapp (f1, t1), MLapp (f2, t2) ->
384 eq_ml_ast f1 f2 && List.equal eq_ml_ast t1 t2
385 | MLlam (na1, t1), MLlam (na2, t2) ->
386 eq_ml_ident na1 na2 && eq_ml_ast t1 t2
387 | MLletin (na1, c1, t1), MLletin (na2, c2, t2) ->
388 eq_ml_ident na1 na2 && eq_ml_ast c1 c2 && eq_ml_ast t1 t2
389 | MLglob gr1, MLglob gr2 -> eq_global gr1 gr2
390 | MLcons (t1, gr1, c1), MLcons (t2, gr2, c2) ->
391 eq_ml_type t1 t2 && eq_global gr1 gr2 && List.equal eq_ml_ast c1 c2
392 | MLtuple t1, MLtuple t2 ->
393 List.equal eq_ml_ast t1 t2
394 | MLcase (t1, c1, p1), MLcase (t2, c2, p2) ->
395 eq_ml_type t1 t2 && eq_ml_ast c1 c2 && Array.equal eq_ml_branch p1 p2
396 | MLfix (i1, id1, t1), MLfix (i2, id2, t2) ->
397 Int.equal i1 i2 && Array.equal Id.equal id1 id2 && Array.equal eq_ml_ast t1 t2
398 | MLexn e1, MLexn e2 -> String.equal e1 e2
399 | MLdummy k1, MLdummy k2 -> k1 == k2
400 | MLaxiom _, MLaxiom _ -> true (* ignore the name of the axiom *)
401 | MLmagic t1, MLmagic t2 -> eq_ml_ast t1 t2
402 | MLuint i1, MLuint i2 -> Uint63.equal i1 i2
403 | MLfloat f1, MLfloat f2 -> Float64.equal f1 f2
404 | MLstring s1, MLstring s2 -> Pstring.equal s1 s2
405 | MLparray (t1,def1), MLparray (t2, def2) -> Array.equal eq_ml_ast t1 t2 && eq_ml_ast def1 def2
406 | (MLrel _|MLapp _|MLlam _|MLletin _|MLglob _|MLcons _
407 |MLtuple _|MLcase _|MLfix _|MLexn _|MLdummy _|MLaxiom _
408 | MLmagic _| MLuint _| MLfloat _| MLstring _| MLparray _), _
409 -> false
410
411 and eq_ml_pattern p1 p2 = match p1, p2 with
412 | Pcons (gr1, p1), Pcons (gr2, p2) ->
413 eq_global gr1 gr2 && List.equal eq_ml_pattern p1 p2
414 | Ptuple p1, Ptuple p2 ->
415 List.equal eq_ml_pattern p1 p2
416 | Prel i1, Prel i2 ->
417 Int.equal i1 i2
418 | Pwild, Pwild -> true
419 | Pusual gr1, Pusual gr2 -> eq_global gr1 gr2
420 | _ -> false
421
422 and eq_ml_branch (id1, p1, t1) (id2, p2, t2) =
423 List.equal eq_ml_ident id1 id2 &&
424 eq_ml_pattern p1 p2 &&
425 eq_ml_ast t1 t2
426
427 (*s [ast_iter_rel f t] applies [f] on every [MLrel] in t. It takes care
428 of the number of bingings crossed before reaching the [MLrel]. *)
429
430 let ast_iter_rel f =
431 let rec iter n = function
432 | MLrel i -> f (i-n)
433 | MLlam (_,a) -> iter (n+1) a
434 | MLletin (_,a,b) -> iter n a; iter (n+1) b
435 | MLcase (_,a,v) ->
436 iter n a; Array.iter (fun (l,_,t) -> iter (n + (List.length l)) t) v
437 | MLfix (_,ids,v) -> let k = Array.length ids in Array.iter (iter (n+k)) v
438 | MLapp (a,l) -> iter n a; List.iter (iter n) l
439 | MLcons (_,_,l) | MLtuple l -> List.iter (iter n) l
440 | MLmagic a -> iter n a
441 | MLparray (t,def) -> Array.iter (iter n) t; iter n def
442 | MLglob _ | MLexn _ | MLdummy _ | MLaxiom _
443 | MLuint _ | MLfloat _ | MLstring _ -> ()
444 in iter 0
445
446 (*s Map over asts. *)
447
448 let ast_map_branch f (c,ids,a) = (c,ids,f a)
449
450 (* Warning: in [ast_map] we assume that [f] does not change the type
451 of [MLcons] and of [MLcase] heads *)
452
453 let ast_map f = function
454 | MLlam (i,a) -> MLlam (i, f a)
455 | MLletin (i,a,b) -> MLletin (i, f a, f b)
456 | MLcase (typ,a,v) -> MLcase (typ,f a, Array.map (ast_map_branch f) v)
457 | MLfix (i,ids,v) -> MLfix (i, ids, Array.map f v)
458 | MLapp (a,l) -> MLapp (f a, List.map f l)
459 | MLcons (typ,c,l) -> MLcons (typ,c, List.map f l)
460 | MLtuple l -> MLtuple (List.map f l)
461 | MLmagic a -> MLmagic (f a)
462 | MLparray (t,def) -> MLparray (Array.map f t, f def)
463 | MLrel _ | MLglob _ | MLexn _ | MLdummy _ | MLaxiom _
464 | MLuint _ | MLfloat _ | MLstring _ as a -> a
465
466 (*s Map over asts, with binding depth as parameter. *)
467
468 let ast_map_lift_branch f n (ids,p,a) = (ids,p, f (n+(List.length ids)) a)
469
470 (* Same warning as for [ast_map]... *)
471
472 let ast_map_lift f n = function
473 | MLlam (i,a) -> MLlam (i, f (n+1) a)
474 | MLletin (i,a,b) -> MLletin (i, f n a, f (n+1) b)
475 | MLcase (typ,a,v) -> MLcase (typ,f n a,Array.map (ast_map_lift_branch f n) v)
476 | MLfix (i,ids,v) ->
477 let k = Array.length ids in MLfix (i,ids,Array.map (f (k+n)) v)
478 | MLapp (a,l) -> MLapp (f n a, List.map (f n) l)
479 | MLcons (typ,c,l) -> MLcons (typ,c, List.map (f n) l)
480 | MLtuple l -> MLtuple (List.map (f n) l)
481 | MLmagic a -> MLmagic (f n a)
482 | MLparray (t,def) -> MLparray (Array.map (f n) t, f n def)
483 | MLrel _ | MLglob _ | MLexn _ | MLdummy _ | MLaxiom _
484 | MLuint _ | MLfloat _ | MLstring _ as a -> a
485
486 (*s Iter over asts. *)
487
488 let ast_iter_branch f (c,ids,a) = f a
489
490 let ast_iter f = function
491 | MLlam (i,a) -> f a
492 | MLletin (i,a,b) -> f a; f b
493 | MLcase (_,a,v) -> f a; Array.iter (ast_iter_branch f) v
494 | MLfix (i,ids,v) -> Array.iter f v
495 | MLapp (a,l) -> f a; List.iter f l
496 | MLcons (_,_,l) | MLtuple l -> List.iter f l
497 | MLmagic a -> f a
498 | MLparray (t,def) -> Array.iter f t; f def
499 | MLrel _ | MLglob _ | MLexn _ | MLdummy _ | MLaxiom _
500 | MLuint _ | MLfloat _ | MLstring _ -> ()
501
502 (*S Operations concerning De Bruijn indices. *)
503
504 (*s [ast_occurs k t] returns [true] if [(Rel k)] occurs in [t]. *)
505
506 let ast_occurs k t =
507 try
508 ast_iter_rel (fun i -> if Int.equal i k then raise Found) t; false
509 with Found -> true
510
511 (*s [occurs_itvl k k' t] returns [true] if there is a [(Rel i)]
512 in [t] with [k<=i<=k'] *)
513
514 let ast_occurs_itvl k k' t =
515 try
516 ast_iter_rel (fun i -> if (k <= i) && (i <= k') then raise Found) t; false
517 with Found -> true
518
519 (* Number of occurrences of [Rel 1] in [t], with special treatment of match:
520 occurrences in different branches aren't added, but we rather use max. *)
521
522 let nb_occur_match =
523 let rec nb k = function
524 | MLrel i -> if Int.equal i k then 1 else 0
525 | MLcase(_,a,v) ->
526 (nb k a) +
527 Array.fold_left
528 (fun r (ids,_,a) -> max r (nb (k+(List.length ids)) a)) 0 v
529 | MLletin (_,a,b) -> (nb k a) + (nb (k+1) b)
530 | MLfix (_,ids,v) -> let k = k+(Array.length ids) in
531 Array.fold_left (fun r a -> r+(nb k a)) 0 v
532 | MLlam (_,a) -> nb (k+1) a
533 | MLapp (a,l) -> List.fold_left (fun r a -> r+(nb k a)) (nb k a) l
534 | MLcons (_,_,l) | MLtuple l -> List.fold_left (fun r a -> r+(nb k a)) 0 l
535 | MLmagic a -> nb k a
536 | MLparray (t,def) -> Array.fold_left (fun r a -> r+(nb k a)) 0 t + nb k def
537 | MLglob _ | MLexn _ | MLdummy _ | MLaxiom _
538 | MLuint _ | MLfloat _ | MLstring _ -> 0
539 in nb 1
540
541 (* Replace unused variables by _ *)
542
543 let dump_unused_vars a =
544 let rec ren env a = match a with
545 | MLrel i ->
546 let () = (List.nth env (i-1)) := true in a
547
548 | MLlam (id,b) ->
549 let occ_id = ref false in
550 let b' = ren (occ_id::env) b in
551 if !occ_id then if b' == b then a else MLlam(id,b')
552 else MLlam(Dummy,b')
553
554 | MLletin (id,b,c) ->
555 let occ_id = ref false in
556 let b' = ren env b in
557 let c' = ren (occ_id::env) c in
558 if !occ_id then
559 if b' == b && c' == c then a else MLletin(id,b',c')
560 else
561 (* 'let' without occurrence: shouldn't happen after simpl *)
562 MLletin(Dummy,b',c')
563
564 | MLcase (t,e,br) ->
565 let e' = ren env e in
566 let br' = Array.Smart.map (ren_branch env) br in
567 if e' == e && br' == br then a else MLcase (t,e',br')
568
569 | MLfix (i,ids,v) ->
570 let env' = List.init (Array.length ids) (fun _ -> ref false) @ env in
571 let v' = Array.Smart.map (ren env') v in
572 if v' == v then a else MLfix (i,ids,v')
573
574 | MLapp (b,l) ->
575 let b' = ren env b and l' = List.Smart.map (ren env) l in
576 if b' == b && l' == l then a else MLapp (b',l')
577
578 | MLcons(t,r,l) ->
579 let l' = List.Smart.map (ren env) l in
580 if l' == l then a else MLcons (t,r,l')
581
582 | MLtuple l ->
583 let l' = List.Smart.map (ren env) l in
584 if l' == l then a else MLtuple l'
585
586 | MLmagic b ->
587 let b' = ren env b in
588 if b' == b then a else MLmagic b'
589
590 | MLparray(t,def) ->
591 let t' = Array.Smart.map (ren env) t in
592 let def' = ren env def in
593 if def' == def && t' == t then a else MLparray(t',def')
594
595 | MLglob _ | MLexn _ | MLdummy _ | MLaxiom _
596 | MLuint _ | MLfloat _ | MLstring _ -> a
597
598 and ren_branch env ((ids,p,b) as tr) =
599 let occs = List.map (fun _ -> ref false) ids in
600 let b' = ren (List.rev_append occs env) b in
601 let ids' =
602 List.map2
603 (fun id occ -> if !occ then id else Dummy)
604 ids occs
605 in
606 if b' == b && List.equal eq_ml_ident ids ids' then tr
607 else (ids',p,b')
608 in
609 ren [] a
610
611 (*s Lifting on terms.
612 [ast_lift k t] lifts the binding depth of [t] across [k] bindings. *)
613
614 let ast_lift k t =
615 let rec liftrec n = function
616 | MLrel i as a -> if i-n < 1 then a else MLrel (i+k)
617 | a -> ast_map_lift liftrec n a
618 in if Int.equal k 0 then t else liftrec 0 t
619
620 let ast_pop t = ast_lift (-1) t
621
622 (*s [permut_rels k k' c] translates [Rel 1 ... Rel k] to [Rel (k'+1) ...
623 Rel (k'+k)] and [Rel (k+1) ... Rel (k+k')] to [Rel 1 ... Rel k'] *)
624
625 let permut_rels k k' =
626 let rec permut n = function
627 | MLrel i as a ->
628 let i' = i-n in
629 if i'<1 || i'>k+k' then a
630 else if i'<=k then MLrel (i+k')
631 else MLrel (i-k)
632 | a -> ast_map_lift permut n a
633 in permut 0
634
635 (*s Substitution. [ml_subst e t] substitutes [e] for [Rel 1] in [t].
636 Lifting (of one binder) is done at the same time. *)
637
638 let ast_subst e =
639 let rec subst n = function
640 | MLrel i as a ->
641 let i' = i-n in
642 if Int.equal i' 1 then ast_lift n e
643 else if i'<1 then a
644 else MLrel (i-1)
645 | a -> ast_map_lift subst n a
646 in subst 0
647
648 (*s Generalized substitution.
649 [gen_subst v d t] applies to [t] the substitution coded in the
650 [v] array: [(Rel i)] becomes [v.(i-1)]. [d] is the correction applies
651 to [Rel] greater than [Array.length v]. *)
652
653 let gen_subst v d t =
654 let rec subst n = function
655 | MLrel i as a ->
656 let i'= i-n in
657 if i' < 1 then a
658 else if i' <= Array.length v then
659 match v.(i'-1) with
660 | None -> assert false
661 | Some u -> ast_lift n u
662 else MLrel (i+d)
663 | a -> ast_map_lift subst n a
664 in subst 0 t
665
666 (*S Operations concerning match patterns *)
667
668 let is_basic_pattern = function
669 | Prel _ | Pwild -> true
670 | Pusual _ | Pcons _ | Ptuple _ -> false
671
672 let has_deep_pattern br =
673 let deep = function
674 | Pcons (_,l) | Ptuple l -> not (List.for_all is_basic_pattern l)
675 | Pusual _ | Prel _ | Pwild -> false
676 in
677 Array.exists (function (_,pat,_) -> deep pat) br
678
679 let is_regular_match br =
680 if Array.is_empty br then false (* empty match becomes MLexn *)
681 else
682 try
683 let get_r (ids,pat,c) =
684 match pat with
685 | Pusual r -> r
686 | Pcons (r,l) ->
687 let is_rel i = function Prel j -> Int.equal i j | _ -> false in
688 if not (List.for_all_i is_rel 1 (List.rev l))
689 then raise Impossible;
690 r
691 | _ -> raise Impossible
692 in
693 let ind = match get_r br.(0) with
694 | { glob = GlobRef.ConstructRef (ind,_) } -> ind
695 | _ -> raise Impossible
696 in
697 let is_ref i tr = match get_r tr with
698 | { glob = GlobRef.ConstructRef (ind', j) } -> Ind.CanOrd.equal ind ind' && Int.equal j (i + 1)
699 | _ -> false
700 in
701 Array.for_all_i is_ref 0 br
702 with Impossible -> false
703
704 (*S Operations concerning lambdas. *)
705
706 (*s [collect_lams MLlam(id1,...MLlam(idn,t)...)] returns
707 [[idn;...;id1]] and the term [t]. *)
708
709 let collect_lams =
710 let rec collect acc = function
711 | MLlam(id,t) -> collect (id::acc) t
712 | x -> acc,x
713 in collect []
714
715 (*s [collect_n_lams] does the same for a precise number of [MLlam]. *)
716
717 let collect_n_lams =
718 let rec collect acc n t =
719 if Int.equal n 0 then acc,t
720 else match t with
721 | MLlam(id,t) -> collect (id::acc) (n-1) t
722 | _ -> assert false
723 in collect []
724
725 (*s [remove_n_lams] just removes some [MLlam]. *)
726
727 let rec remove_n_lams n t =
728 if Int.equal n 0 then t
729 else match t with
730 | MLlam(_,t) -> remove_n_lams (n-1) t
731 | _ -> assert false
732
733 (*s [nb_lams] gives the number of head [MLlam]. *)
734
735 let rec nb_lams = function
736 | MLlam(_,t) -> succ (nb_lams t)
737 | _ -> 0
738
739 (*s [named_lams] does the converse of [collect_lams]. *)
740
741 let rec named_lams ids a = match ids with
742 | [] -> a
743 | id :: ids -> named_lams ids (MLlam (id,a))
744
745 (*s The same for a specific identifier (resp. anonymous, dummy) *)
746
747 let rec many_lams id a = function
748 | 0 -> a
749 | n -> many_lams id (MLlam (id,a)) (pred n)
750
751 let anonym_tmp_lams a n = many_lams (Tmp anonymous_name) a n
752 let dummy_lams a n = many_lams Dummy a n
753
754 (*s mixed according to a signature. *)
755
756 let rec anonym_or_dummy_lams a = function
757 | [] -> a
758 | Keep :: s -> MLlam(anonymous, anonym_or_dummy_lams a s)
759 | Kill _ :: s -> MLlam(Dummy, anonym_or_dummy_lams a s)
760
761 (*S Operations concerning eta. *)
762
763 (*s The following function creates [MLrel n;...;MLrel 1] *)
764
765 let rec eta_args n =
766 if Int.equal n 0 then [] else (MLrel n)::(eta_args (pred n))
767
768 (*s Same, but filtered by a signature. *)
769
770 let rec eta_args_sign n = function
771 | [] -> []
772 | Keep :: s -> (MLrel n) :: (eta_args_sign (n-1) s)
773 | Kill _ :: s -> eta_args_sign (n-1) s
774
775 (*s This one tests [MLrel (n+k); ... ;MLrel (1+k)] *)
776
777 let rec test_eta_args_lift k n = function
778 | [] -> Int.equal n 0
779 | MLrel m :: q -> Int.equal (k+n) m && (test_eta_args_lift k (pred n) q)
780 | _ -> false
781
782 (*s Computes an eta-reduction. *)
783
784 let eta_red e =
785 let ids,t = collect_lams e in
786 let n = List.length ids in
787 if Int.equal n 0 then e
788 else match t with
789 | MLapp (f,a) ->
790 let m = List.length a in
791 let ids,body,args =
792 if Int.equal m n then
793 [], f, a
794 else if m < n then
795 List.skipn m ids, f, a
796 else (* m > n *)
797 let a1,a2 = List.chop (m-n) a in
798 [], MLapp (f,a1), a2
799 in
800 let p = List.length args in
801 if test_eta_args_lift 0 p args && not (ast_occurs_itvl 1 p body)
802 then named_lams ids (ast_lift (-p) body)
803 else e
804 | _ -> e
805
806 (* Performs an eta-reduction when the core is atomic and value,
807 or otherwise returns None *)
808
809 let atomic_eta_red e =
810 let ids,t = collect_lams e in
811 let n = List.length ids in
812 match t with
813 | MLapp (f,a) when test_eta_args_lift 0 n a ->
814 (match f with
815 | MLrel k when k>n -> Some (MLrel (k-n))
816 | MLglob _ | MLdummy _ -> Some f
817 | _ -> None)
818 | _ -> None
819
820 (*s Computes all head linear beta-reductions possible in [(t a)].
821 Non-linear head beta-redex become let-in. *)
822
823 let rec linear_beta_red a t = match a,t with
824 | [], _ -> t
825 | a0::a, MLlam (id,t) ->
826 (match nb_occur_match t with
827 | 0 -> linear_beta_red a (ast_pop t)
828 | 1 -> linear_beta_red a (ast_subst a0 t)
829 | _ ->
830 let a = List.map (ast_lift 1) a in
831 MLletin (id, a0, linear_beta_red a t))
832 | _ -> MLapp (t, a)
833
834 let rec tmp_head_lams = function
835 | MLlam (id, t) -> MLlam (tmp_id id, tmp_head_lams t)
836 | e -> e
837
838 (*s Applies a substitution [s] of constants by their body, plus
839 linear beta reductions at modified positions.
840 Moreover, we mark some lambdas as suitable for later linear
841 reduction (this helps the inlining of recursors).
842 *)
843
844 let is_constant g = match g.glob with
845 | GlobRef.ConstRef _ -> true
846 | _ -> false
847
848 let rec ast_glob_subst s t = match t with
849 | MLapp ((MLglob refe) as f, a) when is_constant refe ->
850 let a = List.map (fun e -> tmp_head_lams (ast_glob_subst s e)) a in
851 (try linear_beta_red a (Refmap'.find refe s)
852 with Not_found -> MLapp (f, a))
853 | MLglob refe when is_constant refe ->
854 (try Refmap'.find refe s with Not_found -> t)
855 | _ -> ast_map (ast_glob_subst s) t
856
857
858 (*S Auxiliary functions used in simplification of ML cases. *)
859
860 (* Factorisation of some match branches into a common "x -> f x"
861 branch may break types sometimes. Example: [type 'x a = A].
862 Then [let id = function A -> A] has type ['x a -> 'y a],
863 which is incompatible with the type of [let id x = x].
864 We now check that the type arguments of the inductive are
865 preserved by our transformation.
866
867 TODO: this verification should be done someday modulo
868 expansion of type definitions.
869 *)
870
871 (*s [branch_as_function b typ (l,p,c)] tries to see branch [c]
872 as a function [f] applied to [MLcons(r,l)]. For that it transforms
873 any [MLcons(r,l)] in [MLrel 1] and raises [Impossible]
874 if any variable in [l] occurs outside such a [MLcons] *)
875
876 let branch_as_fun typ (l,p,c) =
877 let nargs = List.length l in
878 let cons = match p with
879 | Pusual r -> MLcons (typ, r, eta_args nargs)
880 | Pcons (r,pl) ->
881 let pat2rel = function Prel i -> MLrel i | _ -> raise Impossible in
882 MLcons (typ, r, List.map pat2rel pl)
883 | _ -> raise Impossible
884 in
885 let rec genrec n = function
886 | MLrel i as c ->
887 let i' = i-n in
888 if i'<1 then c
889 else if i'>nargs then MLrel (i-nargs+1)
890 else raise Impossible
891 | MLcons _ as cons' when eq_ml_ast cons' (ast_lift n cons) -> MLrel (n+1)
892 | a -> ast_map_lift genrec n a
893 in genrec 0 c
894
895 (*s [branch_as_cst (l,p,c)] tries to see branch [c] as a constant
896 independent from the pattern [MLcons(r,l)]. For that is raises [Impossible]
897 if any variable in [l] occurs in [c], and otherwise returns [c] lifted to
898 appear like a function with one arg (for uniformity with [branch_as_fun]).
899 NB: [MLcons(r,l)] might occur nonetheless in [c], but only when [l] is
900 empty, i.e. when [r] is a constant constructor
901 *)
902
903 let branch_as_cst (l,_,c) =
904 let n = List.length l in
905 if ast_occurs_itvl 1 n c then raise Impossible;
906 ast_lift (1-n) c
907
908 (* A branch [MLcons(r,l)->c] can be seen at the same time as a function
909 branch and a constant branch, either because:
910 - [MLcons(r,l)] doesn't occur in [c]. For example : "A -> B"
911 - this constructor is constant (i.e. [l] is empty). For example "A -> A"
912 When searching for the best factorisation below, we'll try both.
913 *)
914
915 (* The following structure allows recording which element occurred
916 at what position, and then finally return the most frequent
917 element and its positions. *)
918
919 let census_add h k i =
920 let rec add k v = function
921 | [] -> raise Not_found
922 | (k', s) as p :: l ->
923 if eq_ml_ast k k' then (k', Int.Set.add v s) :: l
924 else p :: add k v l
925 in
926 try h := add k i !h
927 with Not_found -> h := (k, Int.Set.singleton i) :: !h
928
929 let census_max h =
930 let len = ref 0 and lst = ref Int.Set.empty and elm = ref (MLaxiom "should not appear") in
931 List.iter
932 (fun (e, s) ->
933 let n = Int.Set.cardinal s in
934 if n > !len then begin len := n; lst := s; elm := e end)
935 !h;
936 (!elm,!lst)
937
938 (* [factor_branches] return the longest possible list of branches
939 that have the same factorization, either as a function or as a
940 constant.
941 *)
942
943 let is_opt_pat (_,p,_) = match p with
944 | Prel _ | Pwild -> true
945 | _ -> false
946
947 let factor_branches o typ br =
948 if Array.exists is_opt_pat br then None (* already optimized *)
949 else begin
950 let h = ref [] in
951 for i = 0 to Array.length br - 1 do
952 if o.opt_case_idr then
953 (try census_add h (branch_as_fun typ br.(i)) i with Impossible -> ());
954 if o.opt_case_cst then
955 (try census_add h (branch_as_cst br.(i)) i with Impossible -> ());
956 done;
957 let br_factor, br_set = census_max h in
958 let n = Int.Set.cardinal br_set in
959 if Int.equal n 0 then None
960 else if Array.length br >= 2 && n < 2 then None
961 else Some (br_factor, br_set)
962 end
963
964 (*s If all branches are functions, try to permute the case and the functions. *)
965
966 let rec merge_ids ids ids' = match ids,ids' with
967 | [],l -> l
968 | l,[] -> l
969 | i::ids, i'::ids' ->
970 (if i == Dummy then i' else i) :: (merge_ids ids ids')
971
972 let is_exn = function MLexn _ -> true | _ -> false
973
974 let permut_case_fun br acc =
975 let nb = ref max_int in
976 Array.iter (fun (_,_,t) ->
977 let ids, c = collect_lams t in
978 let n = List.length ids in
979 if (n < !nb) && (not (is_exn c)) then nb := n) br;
980 if Int.equal !nb max_int || Int.equal !nb 0 then ([],br)
981 else begin
982 let br = Array.copy br in
983 let ids = ref [] in
984 for i = 0 to Array.length br - 1 do
985 let (l,p,t) = br.(i) in
986 let local_nb = nb_lams t in
987 if local_nb < !nb then (* t = MLexn ... *)
988 br.(i) <- (l,p,remove_n_lams local_nb t)
989 else begin
990 let local_ids,t = collect_n_lams !nb t in
991 ids := merge_ids !ids local_ids;
992 br.(i) <- (l,p,permut_rels !nb (List.length l) t)
993 end
994 done;
995 (!ids,br)
996 end
997
998 (*S Generalized iota-reduction. *)
999
1000 (* Definition of a generalized iota-redex: it's a [MLcase(e,br)]
1001 where the head [e] is a [MLcons] or made of [MLcase]'s with
1002 [MLcons] as leaf branches.
1003 A generalized iota-redex is transformed into beta-redexes. *)
1004
1005 (* In [iota_red], we try to simplify a [MLcase(_,MLcons(typ,r,a),br)].
1006 Argument [i] is the branch we consider, we should lift what
1007 comes from [br] by [lift] *)
1008
1009 let rec iota_red i lift br ((typ,r,a) as cons) =
1010 if i >= Array.length br then raise Impossible;
1011 let (ids,p,c) = br.(i) in
1012 match p with
1013 | Pusual r' | Pcons (r',_) when not (eq_global r' r) -> iota_red (i+1) lift br cons
1014 | Pusual r' ->
1015 let c = named_lams (List.rev ids) c in
1016 let c = ast_lift lift c
1017 in MLapp (c,a)
1018 | Prel 1 when Int.equal (List.length ids) 1 ->
1019 let c = MLlam (List.hd ids, c) in
1020 let c = ast_lift lift c
1021 in MLapp(c,[MLcons(typ,r,a)])
1022 | Pwild when List.is_empty ids -> ast_lift lift c
1023 | _ -> raise Impossible (* TODO: handle some more cases *)
1024
1025 (* [iota_gen] is an extension of [iota_red] where we allow to
1026 traverse matches in the head of the first match *)
1027
1028 let iota_gen br hd =
1029 let rec iota k = function
1030 | MLcons (typ,r,a) -> iota_red 0 k br (typ,r,a)
1031 | MLcase(typ,e,br') ->
1032 let new_br =
1033 Array.map (fun (i,p,c)->(i,p,iota (k+(List.length i)) c)) br'
1034 in MLcase(typ,e,new_br)
1035 | _ -> raise Impossible
1036 in iota 0 hd
1037
1038 let is_atomic = function
1039 | MLrel _ | MLglob _ | MLexn _ | MLdummy _ -> true
1040 | _ -> false
1041
1042 let is_imm_apply = function MLapp (MLrel 1, _) -> true | _ -> false
1043
1044 (** Program creates a let-in named "program_branch_NN" for each branch of match.
1045 Unfolding them leads to more natural code (and more dummy removal) *)
1046
1047 let is_program_branch = function
1048 | Tmp _ | Dummy -> false
1049 | Id id ->
1050 let s = Id.to_string id in
1051 try Scanf.sscanf s "program_branch_%d%!" (fun _ -> true)
1052 with Scanf.Scan_failure _ | End_of_file -> false
1053
1054 let expand_linear_let o id e =
1055 o.opt_lin_let || is_tmp id || is_program_branch id || is_imm_apply e
1056
1057 (*S The main simplification function. *)
1058
1059 (* Some beta-iota reductions + simplifications. *)
1060
1061 let rec unmagic = function MLmagic e -> unmagic e | e -> e
1062 let is_magic = function MLmagic _ -> true | _ -> false
1063 let magic_hd a = match a with
1064 | MLmagic _ :: _ -> a
1065 | e :: a -> MLmagic e :: a
1066 | [] -> assert false
1067
1068 let rec simpl o = function
1069 | MLapp (f, []) -> simpl o f
1070 | MLapp (MLapp(f,a),a') -> simpl o (MLapp(f,a@a'))
1071 | MLapp (f, a) ->
1072 (* When the head of the application is magic, no need for magic on args *)
1073 let a = if is_magic f then List.map unmagic a else a in
1074 simpl_app o (List.map (simpl o) a) (simpl o f)
1075 | MLcase (typ,e,br) ->
1076 let br = Array.map (fun (l,p,t) -> (l,p,simpl o t)) br in
1077 simpl_case o typ br (simpl o e)
1078 | MLletin(Dummy,_,e) -> simpl o (ast_pop e)
1079 | MLletin(id,c,e) ->
1080 let e = simpl o e in
1081 if
1082 (is_atomic c) || (is_atomic e) ||
1083 (let n = nb_occur_match e in
1084 (Int.equal n 0 || (Int.equal n 1 && expand_linear_let o id e)))
1085 then
1086 simpl o (ast_subst c e)
1087 else
1088 MLletin(id, simpl o c, e)
1089 | MLfix(i,ids,c) ->
1090 let n = Array.length ids in
1091 if ast_occurs_itvl 1 n c.(i) then
1092 MLfix (i, ids, Array.map (simpl o) c)
1093 else simpl o (ast_lift (-n) c.(i)) (* Dummy fixpoint *)
1094 | MLmagic(MLmagic _ as e) -> simpl o e
1095 | MLmagic(MLapp (f,l)) -> simpl o (MLapp (MLmagic f, l))
1096 | MLmagic(MLletin(id,c,e)) -> simpl o (MLletin(id,c,MLmagic e))
1097 | MLmagic(MLcase(typ,e,br)) ->
1098 let br' = Array.map (fun (ids,p,c) -> (ids,p,MLmagic c)) br in
1099 simpl o (MLcase(typ,e,br'))
1100 | MLmagic(MLdummy _ as e) when lang () == Haskell -> e
1101 | MLmagic(MLexn _ as e) -> e
1102 | MLlam _ as e ->
1103 (match atomic_eta_red e with
1104 | Some e' -> e'
1105 | None -> ast_map (simpl o) e)
1106 | a -> ast_map (simpl o) a
1107
1108 (* invariant : list [a] of arguments is non-empty *)
1109
1110 and simpl_app o a = function
1111 | MLlam (Dummy,t) ->
1112 simpl o (MLapp (ast_pop t, List.tl a))
1113 | MLlam (id,t) -> (* Beta redex *)
1114 (match nb_occur_match t with
1115 | 0 -> simpl o (MLapp (ast_pop t, List.tl a))
1116 | 1 when (is_tmp id || o.opt_lin_beta) ->
1117 simpl o (MLapp (ast_subst (List.hd a) t, List.tl a))
1118 | _ ->
1119 let a' = List.map (ast_lift 1) (List.tl a) in
1120 simpl o (MLletin (id, List.hd a, MLapp (t, a'))))
1121 | MLmagic (MLlam (id,t)) ->
1122 (* When we've at least one argument, we permute the magic
1123 and the lambda, to simplify things a bit (see #2795).
1124 Alas, the 1st argument must also be magic then. *)
1125 simpl_app o (magic_hd a) (MLlam (id,MLmagic t))
1126 | MLletin (id,e1,e2) when o.opt_let_app ->
1127 (* Application of a letin: we push arguments inside *)
1128 MLletin (id, e1, simpl o (MLapp (e2, List.map (ast_lift 1) a)))
1129 | MLcase (typ,e,br) when o.opt_case_app ->
1130 (* Application of a case: we push arguments inside *)
1131 let br' =
1132 Array.map
1133 (fun (l,p,t) ->
1134 let k = List.length l in
1135 let a' = List.map (ast_lift k) a in
1136 (l, p, simpl o (MLapp (t,a')))) br
1137 in simpl o (MLcase (typ,e,br'))
1138 | (MLdummy _ | MLexn _) as e -> e
1139 (* We just discard arguments in those cases. *)
1140 | f -> MLapp (f,a)
1141
1142 (* Invariant : all empty matches should now be [MLexn] *)
1143
1144 and simpl_case o typ br e =
1145 try
1146 (* Generalized iota-redex *)
1147 if not o.opt_case_iot then raise Impossible;
1148 simpl o (iota_gen br e)
1149 with Impossible ->
1150 (* Swap the case and the lam if possible *)
1151 let ids,br = if o.opt_case_fun then permut_case_fun br [] else [],br in
1152 let n = List.length ids in
1153 if not (Int.equal n 0) then
1154 simpl o (named_lams ids (MLcase (typ, ast_lift n e, br)))
1155 else
1156 (* Can we merge several branches as the same constant or function ? *)
1157 if lang() == Scheme || is_custom_match br
1158 then MLcase (typ, e, br)
1159 else match factor_branches o typ br with
1160 | Some (f,ints) when Int.equal (Int.Set.cardinal ints) (Array.length br) ->
1161 (* If all branches have been factorized, we remove the match *)
1162 simpl o (MLletin (Tmp anonymous_name, e, f))
1163 | Some (f,ints) ->
1164 let last_br =
1165 if ast_occurs 1 f then ([Tmp anonymous_name], Prel 1, f)
1166 else ([], Pwild, ast_pop f)
1167 in
1168 let brl = Array.to_list br in
1169 let brl_opt = List.filteri (fun i _ -> not (Int.Set.mem i ints)) brl in
1170 let brl_opt = brl_opt @ [last_br] in
1171 MLcase (typ, e, Array.of_list brl_opt)
1172 | None -> MLcase (typ, e, br)
1173
1174 (*S Local prop elimination. *)
1175 (* We try to eliminate as many [prop] as possible inside an [ml_ast]. *)
1176
1177 (*s In a list, it selects only the elements corresponding to a [Keep]
1178 in the boolean list [l]. *)
1179
1180 let rec select_via_bl l args = match l,args with
1181 | [],_ -> args
1182 | Keep::l,a::args -> a :: (select_via_bl l args)
1183 | Kill _::l,a::args -> select_via_bl l args
1184 | _ -> assert false
1185
1186 (*s [kill_some_lams] removes some head lambdas according to the signature [bl].
1187 This list is build on the identifier list model: outermost lambda
1188 is on the right.
1189 [Rels] corresponding to removed lambdas are not supposed to occur
1190 (except maybe in the case of Kimplicit), and
1191 the other [Rels] are made correct via a [gen_subst].
1192 Output is not directly a [ml_ast], compose with [named_lams] if needed. *)
1193
1194 let is_impl_kill = function Kill (Kimplicit _) -> true | _ -> false
1195
1196 let kill_some_lams bl (ids,c) =
1197 let n = List.length bl in
1198 let n' = List.fold_left (fun n b -> if b == Keep then (n+1) else n) 0 bl in
1199 if Int.equal n n' then ids,c
1200 else if Int.equal n' 0 && not (List.exists is_impl_kill bl)
1201 then [],ast_lift (-n) c
1202 else begin
1203 let v = Array.make n None in
1204 let rec parse_ids i j = function
1205 | [] -> ()
1206 | Keep :: l -> v.(i) <- Some (MLrel j); parse_ids (i+1) (j+1) l
1207 | Kill (Kimplicit _ as k) :: l ->
1208 v.(i) <- Some (MLdummy k); parse_ids (i+1) j l
1209 | Kill _ :: l -> parse_ids (i+1) j l
1210 in parse_ids 0 1 bl;
1211 select_via_bl bl ids, gen_subst v (n'-n) c
1212 end
1213
1214 (*s [kill_dummy_lams] uses the last function to kill the lambdas corresponding
1215 to a [dummy_name]. It can raise [Impossible] if there is nothing to do, or
1216 if there is no lambda left at all. In addition, it now accepts a signature
1217 that may mention some implicits. *)
1218
1219 let rec merge_implicits ids s = match ids, s with
1220 | [],_ -> []
1221 | _,[] -> List.map sign_of_id ids
1222 | Dummy::ids, _::s -> Kill Kprop :: merge_implicits ids s
1223 | _::ids, (Kill (Kimplicit _) as k)::s -> k :: merge_implicits ids s
1224 | _::ids, _::s -> Keep :: merge_implicits ids s
1225
1226 let kill_dummy_lams sign c =
1227 let ids,c = collect_lams c in
1228 let bl = merge_implicits ids (List.rev sign) in
1229 if not (List.memq Keep bl) then raise Impossible;
1230 let rec fst_kill n = function
1231 | [] -> raise Impossible
1232 | Kill _ :: bl -> n
1233 | Keep :: bl -> fst_kill (n+1) bl
1234 in
1235 let skip = max 0 ((fst_kill 0 bl) - 1) in
1236 let ids_skip, ids = List.chop skip ids in
1237 let _, bl = List.chop skip bl in
1238 let c = named_lams ids_skip c in
1239 let ids',c = kill_some_lams bl (ids,c) in
1240 (ids,bl), named_lams ids' c
1241
1242 (*s [eta_expansion_sign] takes a function [fun idn ... id1 -> c]
1243 and a signature [s] and builds a eta-long version. *)
1244
1245 (* For example, if [s = [Keep;Keep;Kill Prop;Keep]] then the output is :
1246 [fun idn ... id1 x x _ x -> (c' 4 3 __ 1)] with [c' = lift 4 c] *)
1247
1248 let eta_expansion_sign s (ids,c) =
1249 let rec abs ids rels i = function
1250 | [] ->
1251 let a = List.rev_map (function MLrel x -> MLrel (i-x) | a -> a) rels
1252 in ids, MLapp (ast_lift (i-1) c, a)
1253 | Keep :: l -> abs (anonymous :: ids) (MLrel i :: rels) (i+1) l
1254 | Kill k :: l -> abs (Dummy :: ids) (MLdummy k :: rels) (i+1) l
1255 in abs ids [] 1 s
1256
1257 (*s If [s = [b1; ... ; bn]] then [case_expunge] decomposes [e]
1258 in [n] lambdas (with eta-expansion if needed) and removes all dummy lambdas
1259 corresponding to [Kill _] in [s]. *)
1260
1261 let case_expunge s e =
1262 let m = List.length s in
1263 let n = nb_lams e in
1264 let p = if m <= n then collect_n_lams m e
1265 else eta_expansion_sign (List.skipn n s) (collect_lams e) in
1266 kill_some_lams (List.rev s) p
1267
1268 (*s [term_expunge] takes a function [fun idn ... id1 -> c]
1269 and a signature [s] and remove dummy lams. The difference
1270 with [case_expunge] is that we here leave one dummy lambda
1271 if all lambdas are logical dummy and the target language is strict. *)
1272
1273 let term_expunge s (ids,c) =
1274 if List.is_empty s then c
1275 else
1276 let ids,c = kill_some_lams (List.rev s) (ids,c) in
1277 if List.is_empty ids && lang () != Haskell &&
1278 sign_kind s == UnsafeLogicalSig
1279 then MLlam (Dummy, ast_lift 1 c)
1280 else named_lams ids c
1281
1282 (*s [kill_dummy_args (ids,bl) r t] looks for occurrences of [MLrel r] in [t]
1283 and purge the args of [MLrel r] corresponding to a [Kill] in [bl].
1284 It makes eta-expansion if needed. *)
1285
1286 let kill_dummy_args (ids,bl) r t =
1287 let m = List.length ids in
1288 let sign = List.rev bl in
1289 let rec found n = function
1290 | MLrel r' when Int.equal r' (r + n) -> true
1291 | MLmagic e -> found n e
1292 | _ -> false
1293 in
1294 let rec killrec n = function
1295 | MLapp(e, a) when found n e ->
1296 let k = max 0 (m - (List.length a)) in
1297 let a = List.map (killrec n) a in
1298 let a = List.map (ast_lift k) a in
1299 let a = select_via_bl sign (a @ (eta_args k)) in
1300 named_lams (List.firstn k ids) (MLapp (ast_lift k e, a))
1301 | e when found n e ->
1302 let a = select_via_bl sign (eta_args m) in
1303 named_lams ids (MLapp (ast_lift m e, a))
1304 | e -> ast_map_lift killrec n e
1305 in killrec 0 t
1306
1307 (*s The main function for local [dummy] elimination. *)
1308
1309 let sign_of_args a =
1310 List.map (function MLdummy k -> Kill k | _ -> Keep) a
1311
1312 let rec kill_dummy = function
1313 | MLfix(i,fi,c) ->
1314 begin match kill_dummy_fix i c [] with
1315 | k, c -> ast_subst (MLfix (i,fi,c)) (kill_dummy_args k 1 (MLrel 1))
1316 | exception Impossible -> MLfix (i,fi,Array.map kill_dummy c)
1317 end
1318 | MLapp (MLfix (i,fi,c),a) ->
1319 let a = List.map kill_dummy a in
1320 (* Heuristics: if some arguments are implicit args, we try to
1321 eliminate the corresponding arguments of the fixpoint *)
1322 begin match kill_dummy_fix i c (sign_of_args a) with
1323 | (k, c) ->
1324 let fake = MLapp (MLrel 1, List.map (ast_lift 1) a) in
1325 let fake' = kill_dummy_args k 1 fake in
1326 ast_subst (MLfix (i,fi,c)) fake'
1327 | exception Impossible -> MLapp(MLfix(i,fi,Array.map kill_dummy c),a)
1328 end
1329 | MLletin(id, MLfix (i,fi,c),e) ->
1330 begin match kill_dummy_fix i c [] with
1331 | (k, c) ->
1332 let e = kill_dummy (kill_dummy_args k 1 e) in
1333 MLletin(id, MLfix(i,fi,c),e)
1334 | exception Impossible -> MLletin(id, MLfix(i,fi,Array.map kill_dummy c),kill_dummy e)
1335 end
1336 | MLletin(id,c,e) ->
1337 let c = kill_dummy c in
1338 begin match kill_dummy_lams [] c with
1339 | (k, c) ->
1340 let e = kill_dummy (kill_dummy_args k 1 e) in
1341 if is_atomic c then ast_subst c e else MLletin (id, c, e)
1342 | exception Impossible -> MLletin(id, c, kill_dummy e)
1343 end
1344 | a -> ast_map kill_dummy a
1345
1346 (* Similar function, but acting only on head lambdas and let-ins *)
1347
1348 and kill_dummy_hd = function
1349 | MLlam(id,e) -> MLlam(id, kill_dummy_hd e)
1350 | MLletin(id,c,e) ->
1351 begin match kill_dummy_lams [] (kill_dummy_hd c) with
1352 | (k, c) ->
1353 let e = kill_dummy_hd (kill_dummy_args k 1 e) in
1354 let c = kill_dummy c in
1355 if is_atomic c then ast_subst c e else MLletin (id, c, e)
1356 | exception Impossible -> MLletin(id,kill_dummy c,kill_dummy_hd e)
1357 end
1358 | a -> a
1359
1360 and kill_dummy_fix i c s =
1361 let n = Array.length c in
1362 let k,ci = kill_dummy_lams s (kill_dummy_hd c.(i)) in
1363 let c = Array.copy c in c.(i) <- ci;
1364 for j = 0 to (n-1) do
1365 c.(j) <- kill_dummy (kill_dummy_args k (n-i) c.(j))
1366 done;
1367 k,c
1368
1369 (*s Putting things together. *)
1370
1371 let normalize a =
1372 let o = optims () in
1373 let rec norm a =
1374 let a' = if o.opt_kill_dum then kill_dummy (simpl o a) else simpl o a in
1375 if eq_ml_ast a a' then a else norm a'
1376 in norm a
1377
1378 (*S Special treatment of fixpoint for pretty-printing purpose. *)
1379
1380 let general_optimize_fix f ids n args m c =
1381 let v = Array.init n (fun i -> i) in
1382 let aux i = function
1383 | MLrel j when v.(j-1)>=0 ->
1384 if ast_occurs (j+1) c then raise Impossible else v.(j-1)<-(-i-1)
1385 | _ -> raise Impossible
1386 in List.iteri aux args;
1387 let args_f = List.rev_map (fun i -> MLrel (i+m+1)) (Array.to_list v) in
1388 let new_f = anonym_tmp_lams (MLapp (MLrel (n+m+1),args_f)) m in
1389 let new_c = named_lams ids (normalize (MLapp ((ast_subst new_f c),args))) in
1390 MLfix(0,[|f|],[|new_c|])
1391
1392 let optimize_fix a =
1393 if not (optims()).opt_fix_fun then a
1394 else
1395 let ids,a' = collect_lams a in
1396 let n = List.length ids in
1397 if Int.equal n 0 then a
1398 else match a' with
1399 | MLfix(_,[|f|],[|c|]) ->
1400 let new_f = MLapp (MLrel (n+1),eta_args n) in
1401 let new_c = named_lams ids (normalize (ast_subst new_f c))
1402 in MLfix(0,[|f|],[|new_c|])
1403 | MLapp(a',args) ->
1404 let m = List.length args in
1405 (match a' with
1406 | MLfix(_,_,_) when
1407 (test_eta_args_lift 0 n args) && not (ast_occurs_itvl 1 m a')
1408 -> a'
1409 | MLfix(_,[|f|],[|c|]) ->
1410 (try general_optimize_fix f ids n args m c
1411 with Impossible -> a)
1412 | _ -> a)
1413 | _ -> a
1414
1415 (*S Inlining. *)
1416
1417 (* Utility functions used in the decision of inlining. *)
1418
1419 let ml_size_branch size pv = Array.fold_left (fun a (_,_,t) -> a + size t) 0 pv
1420
1421 let rec ml_size = function
1422 | MLapp(t,l) -> List.length l + ml_size t + ml_size_list l
1423 | MLlam(_,t) -> 1 + ml_size t
1424 | MLcons(_,_,l) | MLtuple l -> ml_size_list l
1425 | MLcase(_,t,pv) -> 1 + ml_size t + ml_size_branch ml_size pv
1426 | MLfix(_,_,f) -> ml_size_array f
1427 | MLletin (_,_,t) -> ml_size t
1428 | MLmagic t -> ml_size t
1429 | MLparray(t,def) -> ml_size_array t + ml_size def
1430 | MLglob _ | MLrel _ | MLexn _ | MLdummy _ | MLaxiom _
1431 | MLuint _ | MLfloat _ | MLstring _ -> 0
1432
1433 and ml_size_list l = List.fold_left (fun a t -> a + ml_size t) 0 l
1434
1435 and ml_size_array a = Array.fold_left (fun a t -> a + ml_size t) 0 a
1436
1437 let is_fix = function MLfix _ -> true | _ -> false
1438
1439 (*s Strictness *)
1440
1441 (* A variable is strict if the evaluation of the whole term implies
1442 the evaluation of this variable. Non-strict variables can be found
1443 behind Match, for example. Expanding a term [t] is a good idea when
1444 it begins by at least one non-strict lambda, since the corresponding
1445 argument to [t] might be unevaluated in the expanded code. *)
1446
1447 exception Toplevel
1448
1449 let lift n l = List.map ((+) n) l
1450
1451 let pop n l = List.map (fun x -> if x<=n then raise Toplevel else x-n) l
1452
1453 (* This function returns a list of de Bruijn indices of non-strict variables,
1454 or raises [Toplevel] if it has an internal non-strict variable.
1455 In fact, not all variables are checked for strictness, only the ones which
1456 de Bruijn index is in the candidates list [cand]. The flag [add] controls
1457 the behaviour when going through a lambda: should we add the corresponding
1458 variable to the candidates? We use this flag to check only the external
1459 lambdas, those that will correspond to arguments. *)
1460
1461 let rec non_stricts add cand = function
1462 | MLlam (id,t) ->
1463 let cand = lift 1 cand in
1464 let cand = if add then 1::cand else cand in
1465 pop 1 (non_stricts add cand t)
1466 | MLrel n ->
1467 List.filter (fun m -> not (Int.equal m n)) cand
1468 | MLapp (t,l)->
1469 let cand = non_stricts false cand t in
1470 List.fold_left (non_stricts false) cand l
1471 | MLcons (_,_,l) ->
1472 List.fold_left (non_stricts false) cand l
1473 | MLletin (_,t1,t2) ->
1474 let cand = non_stricts false cand t1 in
1475 pop 1 (non_stricts add (lift 1 cand) t2)
1476 | MLfix (_,i,f)->
1477 let n = Array.length i in
1478 let cand = lift n cand in
1479 let cand = Array.fold_left (non_stricts false) cand f in
1480 pop n cand
1481 | MLcase (_,t,v) ->
1482 (* The only interesting case: for a variable to be non-strict, *)
1483 (* it is sufficient that it appears non-strict in at least one branch, *)
1484 (* so we make an union (in fact a merge). *)
1485 let cand = non_stricts false cand t in
1486 Array.fold_left
1487 (fun c (i,_,t)->
1488 let n = List.length i in
1489 let cand = lift n cand in
1490 let cand = pop n (non_stricts add cand t) in
1491 List.merge Int.compare cand c) [] v
1492 (* [merge] may duplicates some indices, but I don't mind. *)
1493 | MLmagic t ->
1494 non_stricts add cand t
1495 | _ ->
1496 cand
1497
1498 (* The real test: we are looking for internal non-strict variables, so we start
1499 with no candidates, and the only positive answer is via the [Toplevel]
1500 exception. *)
1501
1502 let is_not_strict t =
1503 try let _ = non_stricts true [] t in false
1504 with Toplevel -> true
1505
1506 (*s Inlining decision *)
1507
1508 (* [inline_test] answers the following question:
1509 If we could inline [t] (the user said nothing special),
1510 should we inline ?
1511
1512 We expand small terms with at least one non-strict
1513 variable (i.e. a variable that may not be evaluated).
1514
1515 Furthermore we don't expand fixpoints.
1516
1517 Moreover, as mentioned by X. Leroy (bug #2241),
1518 inlining a constant from inside an opaque module might
1519 break types. To avoid that, we require below that
1520 both [r] and its body are globally visible. This isn't
1521 fully satisfactory, since [r] might not be visible (functor),
1522 and anyway it might be interesting to inline [r] at least
1523 inside its own structure. But to be safe, we adopt this
1524 restriction for the moment.
1525 *)
1526
1527 open Declareops
1528
1529 let inline_test r t =
1530 if not (auto_inline ()) then false
1531 else
1532 let c = match r.glob with GlobRef.ConstRef c -> c | _ -> assert false in
1533 let has_body =
1534 Environ.mem_constant c (Global.env()) && constant_has_body (Global.lookup_constant c)
1535 in
1536 has_body &&
1537 (let t1 = eta_red t in
1538 let t2 = snd (collect_lams t1) in
1539 not (is_fix t2) && ml_size t < 12 && is_not_strict t)
1540
1541 let con_of_string s =
1542 let d, id = Libnames.split_dirpath (dirpath_of_string s) in
1543 Constant.make2 (ModPath.MPfile d) id
1544
1545 let manual_inline_set =
1546 List.fold_right (fun x -> Cset_env.add (con_of_string x))
1547 [ "Corelib.Init.Wf.well_founded_induction_type";
1548 "Corelib.Init.Wf.well_founded_induction";
1549 "Corelib.Init.Wf.Acc_iter";
1550 "Corelib.Init.Wf.Fix_F";
1551 "Corelib.Init.Wf.Fix";
1552 "Corelib.Init.Datatypes.andb";
1553 "Corelib.Init.Datatypes.orb";
1554 "Corelib.Init.Logic.eq_rec_r";
1555 "Corelib.Init.Logic.eq_rect_r";
1556 "Corelib.Init.Specif.proj1_sig";
1557 ]
1558 Cset_env.empty
1559
1560 let manual_inline g = match g.glob with
1561 | GlobRef.ConstRef c -> Cset_env.mem c manual_inline_set
1562 | _ -> false
1563
1564 (* If the user doesn't say he wants to keep [t], we inline in two cases:
1565 \begin{itemize}
1566 \item the user explicitly requests it
1567 \item [expansion_test] answers that the inlining is a good idea, and
1568 we are free to act (AutoInline is set)
1569 \end{itemize} *)
1570
1571 let inline table r t =
1572 not (to_keep r) (* The user DOES want to keep it *)
1573 && not (is_inline_custom r)
1574 && (to_inline r (* The user DOES want to inline it *)
1575 || (lang () != Haskell &&
1576 (is_projection table r || is_recursor table r ||
1577 manual_inline r || inline_test r t)))
1578