forked from ocaml/ocaml
-
Notifications
You must be signed in to change notification settings - Fork 0
/
value_rec_check.ml
1421 lines (1270 loc) · 46.9 KB
/
value_rec_check.ml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
(**************************************************************************)
(* *)
(* OCaml *)
(* *)
(* Jeremy Yallop, University of Cambridge *)
(* Gabriel Scherer, Project Parsifal, INRIA Saclay *)
(* Alban Reynaud, ENS Lyon *)
(* *)
(* Copyright 2017 Jeremy Yallop *)
(* Copyright 2018 Alban Reynaud *)
(* Copyright 2018 INRIA *)
(* *)
(* All rights reserved. This file is distributed under the terms of *)
(* the GNU Lesser General Public License version 2.1, with the *)
(* special exception on linking described in the file LICENSE. *)
(* *)
(**************************************************************************)
(** Static checking of recursive declarations, as described in
A practical mode system for recursive definitions
Alban Reynaud, Gabriel Scherer and Jeremy Yallop
POPL 2021
Some recursive definitions are meaningful
{[
let rec factorial = function 0 -> 1 | n -> n * factorial (n - 1)
let rec infinite_list = 0 :: infinite_list
]}
but some other are meaningless
{[
let rec x = x
let rec x = x+1
]}
Intuitively, a recursive definition makes sense when the body of the
definition can be evaluated without fully knowing what the recursive
name is yet.
In the [factorial] example, the name [factorial] refers to a function,
evaluating the function definition [function ...] can be done
immediately and will not force a recursive call to [factorial] -- this
will only happen later, when [factorial] is called with an argument.
In the [infinite_list] example, we can evaluate [0 :: infinite_list]
without knowing the full content of [infinite_list], but with just its
address. This is a case of productive/guarded recursion.
On the contrary, [let rec x = x] is unguarded recursion (the meaning
is undetermined), and [let rec x = x+1] would need the value of [x]
while evaluating its definition [x+1].
This file implements a static check to decide which definitions are
known to be meaningful, and which may be meaningless. In the general
case, we handle a set of mutually-recursive definitions
{[
let rec x1 = e1
and x2 = e2
...
and xn = en
]}
Our check (see function [is_valid_recursive_expression] is defined
using two criteria:
Usage of recursive variables: how does each of the [e1 .. en] use the
recursive variables [x1 .. xn]?
Static or dynamic size: for which of the [ei] can we compute the
in-memory size of the value without evaluating [ei] (so that we can
pre-allocate it, and thus know its final address before evaluation).
The "static or dynamic size" is decided by the classify_* functions below.
The "variable usage" question is decided by a static analysis looking
very much like a type system. The idea is to assign "access modes" to
variables, where an "access mode" [m] is defined as either
m ::= Ignore (* the value is not used at all *)
| Delay (* the value is not needed at definition time *)
| Guard (* the value is stored under a data constructor *)
| Return (* the value result is directly returned *)
| Dereference (* full access and inspection of the value *)
The access modes of an expression [e] are represented by a "context"
[G], which is simply a mapping from variables (the variables used in
[e]) to access modes.
The core notion of the static check is a type-system-like judgment of
the form [G |- e : m], which can be interpreted as meaning either of:
- If we are allowed to use the variables of [e] at the modes in [G]
(but not more), then it is safe to use [e] at the mode [m].
- If we want to use [e] at the mode [m], then its variables are
used at the modes in [G].
In practice, for a given expression [e], our implementation takes the
desired mode of use [m] as *input*, and returns a context [G] as
*output*, which is (uniquely determined as) the most permissive choice
of modes [G] for the variables of [e] such that [G |- e : m] holds.
*)
open Asttypes
open Typedtree
open Types
(** {1 Static or dynamic size} *)
type sd = Value_rec_types.recursive_binding_kind
let is_ref : Types.value_description -> bool = function
| { Types.val_kind =
Types.Val_prim { Primitive.prim_name = "%makemutable";
prim_arity = 1 } } ->
true
| _ -> false
(* See the note on abstracted arguments in the documentation for
Typedtree.Texp_apply *)
let is_abstracted_arg : arg_label * expression option -> bool = function
| (_, None) -> true
| (_, Some _) -> false
let classify_expression : Typedtree.expression -> sd =
(* We need to keep track of the size of expressions
bound by local declarations, to be able to predict
the size of variables. Compare:
let rec r =
let y = fun () -> r ()
in y
and
let rec r =
let y = if Random.bool () then ignore else fun () -> r ()
in y
In both cases the final address of `r` must be known before `y` is compiled,
and this is only possible if `r` has a statically-known size.
The first definition can be allowed (`y` has a statically-known
size) but the second one is unsound (`y` has no statically-known size).
*)
let rec classify_expression env e : sd =
match e.exp_desc with
(* binding and variable cases *)
| Texp_let (rec_flag, vb, e) ->
let env = classify_value_bindings rec_flag env vb in
classify_expression env e
| Texp_letmodule (Some mid, _, _, mexp, e) ->
(* Note on module presence:
For absent modules (i.e. module aliases), the module being bound
does not have a physical representation, but its size can still be
derived from the alias itself, so we can reuse the same code as
for modules that are present. *)
let size = classify_module_expression env mexp in
let env = Ident.add mid size env in
classify_expression env e
| Texp_ident (path, _, _) ->
classify_path env path
(* non-binding cases *)
| Texp_open (_, e)
| Texp_letmodule (None, _, _, _, e)
| Texp_sequence (_, e)
| Texp_letexception (_, e) ->
classify_expression env e
| Texp_construct (_, {cstr_tag = Cstr_unboxed}, [e]) ->
classify_expression env e
| Texp_construct _ ->
Static
| Texp_record { representation = Record_unboxed _;
fields = [| _, Overridden (_,e) |] } ->
classify_expression env e
| Texp_record _ ->
Static
| Texp_variant _
| Texp_tuple _
| Texp_extension_constructor _
| Texp_constant _ ->
Static
| Texp_for _
| Texp_setfield _
| Texp_while _
| Texp_setinstvar _ ->
(* Unit-returning expressions *)
Static
| Texp_unreachable ->
Static
| Texp_apply ({exp_desc = Texp_ident (_, _, vd)}, _)
when is_ref vd ->
Static
| Texp_apply (_,args)
when List.exists is_abstracted_arg args ->
Static
| Texp_apply _ ->
Dynamic
| Texp_array _ ->
Static
| Texp_pack mexp ->
classify_module_expression env mexp
| Texp_function _ ->
Static
| Texp_lazy e ->
(* The code below was copied (in part) from translcore.ml *)
begin match Typeopt.classify_lazy_argument e with
| `Constant_or_function ->
(* A constant expr (of type <> float if [Config.flat_float_array] is
true) gets compiled as itself. *)
classify_expression env e
| `Float_that_cannot_be_shortcut
| `Identifier `Forward_value ->
(* Forward blocks *)
Static
| `Identifier `Other ->
classify_expression env e
| `Other ->
(* other cases compile to a lazy block holding a function *)
Static
end
| Texp_new _
| Texp_instvar _
| Texp_object _
| Texp_match _
| Texp_ifthenelse _
| Texp_send _
| Texp_field _
| Texp_assert _
| Texp_try _
| Texp_override _
| Texp_letop _ ->
Dynamic
and classify_value_bindings rec_flag env bindings =
(* We use a non-recursive classification, classifying each
binding with respect to the old environment
(before all definitions), even if the bindings are recursive.
Note: computing a fixpoint in some way would be more
precise, as the following could be allowed:
let rec topdef =
let rec x = y and y = fun () -> topdef ()
in x
*)
ignore rec_flag;
let old_env = env in
let add_value_binding env vb =
match vb.vb_pat.pat_desc with
| Tpat_var (id, _loc, _uid) ->
let size = classify_expression old_env vb.vb_expr in
Ident.add id size env
| _ ->
(* Note: we don't try to compute any size for complex patterns *)
env
in
List.fold_left add_value_binding env bindings
and classify_path env : _ -> Value_rec_types.recursive_binding_kind = function
| Path.Pident x ->
begin
try Ident.find_same x env
with Not_found ->
(* an identifier will be missing from the map if either:
- it is a non-local identifier
(bound outside the letrec-binding we are analyzing)
- or it is bound by a complex (let p = e in ...) local binding
- or it is bound within a module (let module M = ... in ...)
that we are not traversing for size computation
For non-local identifiers it might be reasonable (although
not completely clear) to consider them Static (they have
already been evaluated), but for the others we must
under-approximate with Not_recursive.
This could be fixed by a more complete implementation.
*)
Dynamic
end
| Path.Pdot _ | Path.Papply _ | Path.Pextra_ty _ ->
(* local modules could have such paths to local definitions;
classify_expression could be extend to compute module
shapes more precisely *)
Dynamic
and classify_module_expression env mexp : sd =
match mexp.mod_desc with
| Tmod_ident (path, _) ->
classify_path env path
| Tmod_structure _ ->
Static
| Tmod_functor _ ->
Static
| Tmod_apply _ ->
Dynamic
| Tmod_apply_unit _ ->
Dynamic
| Tmod_constraint (mexp, _, _, coe) ->
begin match coe with
| Tcoerce_none ->
classify_module_expression env mexp
| Tcoerce_structure _ ->
Static
| Tcoerce_functor _ ->
Static
| Tcoerce_primitive _ ->
Misc.fatal_error "letrec: primitive coercion on a module"
| Tcoerce_alias _ ->
Misc.fatal_error "letrec: alias coercion on a module"
end
| Tmod_unpack (e, _) ->
classify_expression env e
in classify_expression Ident.empty
(** {1 Usage of recursive variables} *)
module Mode = struct
(** For an expression in a program, its "usage mode" represents
static information about how the value produced by the expression
will be used by the context around it. *)
type t =
| Ignore
(** [Ignore] is for subexpressions that are not used at all during
the evaluation of the whole program. This is the mode of
a variable in an expression in which it does not occur. *)
| Delay
(** A [Delay] context can be fully evaluated without evaluating its argument
, which will only be needed at a later point of program execution. For
example, [fun x -> ?] or [lazy ?] are [Delay] contexts. *)
| Guard
(** A [Guard] context returns the value as a member of a data structure,
for example a variant constructor or record. The value can safely be
defined mutually-recursively with their context, for example in
[let rec li = 1 :: li].
When these subexpressions participate in a cyclic definition,
this definition is productive/guarded.
The [Guard] mode is also used when a value is not dereferenced,
it is returned by a sub-expression, but the result of this
sub-expression is discarded instead of being returned.
For example, the subterm [?] is in a [Guard] context
in [let _ = ? in e] and in [?; e].
When these subexpressions participate in a cyclic definition,
they cannot create a self-loop.
*)
| Return
(** A [Return] context returns its value without further inspection.
This value cannot be defined mutually-recursively with its context,
as there is a risk of self-loop: in [let rec x = y and y = x], the
two definitions use a single variable in [Return] context. *)
| Dereference
(** A [Dereference] context consumes, inspects and uses the value
in arbitrary ways. Such a value must be fully defined at the point
of usage, it cannot be defined mutually-recursively with its context. *)
let equal = ((=) : t -> t -> bool)
(* Lower-ranked modes demand/use less of the variable/expression they qualify
-- so they allow more recursive definitions.
Ignore < Delay < Guard < Return < Dereference
*)
let rank = function
| Ignore -> 0
| Delay -> 1
| Guard -> 2
| Return -> 3
| Dereference -> 4
(* Returns the more conservative (highest-ranking) mode of the two
arguments.
In judgments we write (m + m') for (join m m').
*)
let join m m' =
if rank m >= rank m' then m else m'
(* If x is used with the mode m in e[x], and e[x] is used with mode
m' in e'[e[x]], then x is used with mode m'[m] (our notation for
"compose m' m") in e'[e[x]].
Return is neutral for composition: m[Return] = m = Return[m].
Composition is associative and [Ignore] is a zero/annihilator for
it: (compose Ignore m) and (compose m Ignore) are both Ignore. *)
let compose m' m = match m', m with
| Ignore, _ | _, Ignore -> Ignore
| Dereference, _ -> Dereference
| Delay, _ -> Delay
| Guard, Return -> Guard
| Guard, ((Dereference | Guard | Delay) as m) -> m
| Return, Return -> Return
| Return, ((Dereference | Guard | Delay) as m) -> m
end
type mode = Mode.t = Ignore | Delay | Guard | Return | Dereference
module Env :
sig
type t
val single : Ident.t -> Mode.t -> t
(** Create an environment with a single identifier used with a given mode.
*)
val empty : t
(** An environment with no used identifiers. *)
val find : Ident.t -> t -> Mode.t
(** Find the mode of an identifier in an environment. The default mode is
Ignore. *)
val unguarded : t -> Ident.t list -> Ident.t list
(** unguarded e l: the list of all identifiers in l that are dereferenced or
returned in the environment e. *)
val dependent : t -> Ident.t list -> Ident.t list
(** dependent e l: the list of all identifiers in l that are used in e
(not ignored). *)
val join : t -> t -> t
val join_list : t list -> t
(** Environments can be joined pointwise (variable per variable) *)
val compose : Mode.t -> t -> t
(** Environment composition m[G] extends mode composition m1[m2]
by composing each mode in G pointwise *)
val remove : Ident.t -> t -> t
(** Remove an identifier from an environment. *)
val take: Ident.t -> t -> Mode.t * t
(** Remove an identifier from an environment, and return its mode *)
val remove_list : Ident.t list -> t -> t
(** Remove all the identifiers of a list from an environment. *)
val equal : t -> t -> bool
end = struct
module M = Map.Make(Ident)
(** A "t" maps each rec-bound variable to an access status *)
type t = Mode.t M.t
let equal = M.equal Mode.equal
let find (id: Ident.t) (tbl: t) =
try M.find id tbl with Not_found -> Ignore
let empty = M.empty
let join (x: t) (y: t) =
M.fold
(fun (id: Ident.t) (v: Mode.t) (tbl: t) ->
let v' = find id tbl in
M.add id (Mode.join v v') tbl)
x y
let join_list li = List.fold_left join empty li
let compose m env =
M.map (Mode.compose m) env
let single id mode = M.add id mode empty
let unguarded env li =
List.filter (fun id -> Mode.rank (find id env) > Mode.rank Guard) li
let dependent env li =
List.filter (fun id -> Mode.rank (find id env) > Mode.rank Ignore) li
let remove = M.remove
let take id env = (find id env, remove id env)
let remove_list l env =
List.fold_left (fun env id -> M.remove id env) env l
end
let remove_pat pat env =
Env.remove_list (pat_bound_idents pat) env
let remove_patlist pats env =
List.fold_right remove_pat pats env
(* Usage mode judgments.
There are two main groups of judgment functions:
- Judgments of the form "G |- ... : m"
compute the environment G of a subterm ... from its mode m, so
the corresponding function has type [... -> Mode.t -> Env.t].
We write [... -> term_judg] in this case.
- Judgments of the form "G |- ... : m -| G'"
correspond to binding constructs (for example "let x = e" in the
term "let x = e in body") that have both an exterior environment
G (the environment of the whole term "let x = e in body") and an
interior environment G' (the environment at the "in", after the
binding construct has introduced new names in scope).
For example, let-binding could be given the following rule:
G |- e : m + m'
-----------------------------------
G+G' |- (let x = e) : m -| x:m', G'
Checking the whole term composes this judgment
with the "G |- e : m" form for the let body:
G |- (let x = e) : m -| G'
G' |- body : m
-------------------------------
G |- let x = e in body : m
To this judgment "G |- e : m -| G'" our implementation gives the
type [... -> Mode.t -> Env.t -> Env.t]: it takes the mode and
interior environment as inputs, and returns the exterior
environment.
We write [... -> bind_judg] in this case.
*)
type term_judg = Mode.t -> Env.t
type bind_judg = Mode.t -> Env.t -> Env.t
let option : 'a. ('a -> term_judg) -> 'a option -> term_judg =
fun f o m -> match o with
| None -> Env.empty
| Some v -> f v m
let list : 'a. ('a -> term_judg) -> 'a list -> term_judg =
fun f li m ->
List.fold_left (fun env item -> Env.join env (f item m)) Env.empty li
let array : 'a. ('a -> term_judg) -> 'a array -> term_judg =
fun f ar m ->
Array.fold_left (fun env item -> Env.join env (f item m)) Env.empty ar
let single : Ident.t -> term_judg = Env.single
let remove_id : Ident.t -> term_judg -> term_judg =
fun id f m -> Env.remove id (f m)
let remove_ids : Ident.t list -> term_judg -> term_judg =
fun ids f m -> Env.remove_list ids (f m)
let join : term_judg list -> term_judg =
fun li m -> Env.join_list (List.map (fun f -> f m) li)
let empty = fun _ -> Env.empty
(* A judgment [judg] takes a mode from the context as input, and
returns an environment. The judgment [judg << m], given a mode [m']
from the context, evaluates [judg] in the composed mode [m'[m]]. *)
let (<<) : term_judg -> Mode.t -> term_judg =
fun f inner_mode -> fun outer_mode -> f (Mode.compose outer_mode inner_mode)
(* A binding judgment [binder] expects a mode and an inner environment,
and returns an outer environment. [binder >> judg] computes
the inner environment as the environment returned by [judg]
in the ambient mode. *)
let (>>) : bind_judg -> term_judg -> term_judg =
fun binder term mode -> binder mode (term mode)
(* Expression judgment:
G |- e : m
where (m) is an input of the code and (G) is an output;
in the Prolog mode notation, this is (+G |- -e : -m).
*)
let rec expression : Typedtree.expression -> term_judg =
fun exp -> match exp.exp_desc with
| Texp_ident (pth, _, _) ->
path pth
| Texp_let (rec_flag, bindings, body) ->
(*
G |- <bindings> : m -| G'
G' |- body : m
-------------------------------
G |- let <bindings> in body : m
*)
value_bindings rec_flag bindings >> expression body
| Texp_letmodule (x, _, _, mexp, e) ->
module_binding (x, mexp) >> expression e
| Texp_match (e, cases, eff_cases, _) ->
(* TODO: update comment below for eff_cases
(Gi; mi |- pi -> ei : m)^i
G |- e : sum(mi)^i
----------------------------------------------
G + sum(Gi)^i |- match e with (pi -> ei)^i : m
*)
(fun mode ->
let pat_envs, pat_modes =
List.split (List.map (fun c -> case c mode) cases) in
let env_e = expression e (List.fold_left Mode.join Ignore pat_modes) in
let eff_envs, eff_modes =
List.split (List.map (fun c -> case c mode) eff_cases) in
let eff_e = expression e (List.fold_left Mode.join Ignore eff_modes) in
Env.join_list
((Env.join_list (env_e :: pat_envs)) :: (eff_e :: eff_envs)))
| Texp_for (_, _, low, high, _, body) ->
(*
G1 |- low: m[Dereference]
G2 |- high: m[Dereference]
G3 |- body: m[Guard]
---
G1 + G2 + G3 |- for _ = low to high do body done: m
*)
join [
expression low << Dereference;
expression high << Dereference;
expression body << Guard;
]
| Texp_constant _ ->
empty
| Texp_new (pth, _, _) ->
(*
G |- c: m[Dereference]
-----------------------
G |- new c: m
*)
path pth << Dereference
| Texp_instvar (self_path, pth, _inst_var) ->
join [path self_path << Dereference; path pth]
| Texp_apply ({exp_desc = Texp_ident (_, _, vd)}, [_, Some arg])
when is_ref vd ->
(*
G |- e: m[Guard]
------------------
G |- ref e: m
*)
expression arg << Guard
| Texp_apply (e, args) ->
(* [args] may contain omitted arguments, corresponding to labels in
the function's type that were not passed in the actual application.
The arguments before the first omitted argument are passed to the
function immediately, so they are dereferenced. The arguments after
the first omitted one are stored in a closure, so guarded.
The function itself is called immediately (dereferenced) if there
is at least one argument before the first omitted one.
On the other hand, if the first argument is omitted then the
function is stored in the closure without being called. *)
let rec split_args ~has_omitted_arg = function
| [] -> [], []
| (_, None) :: rest -> split_args ~has_omitted_arg:true rest
| (_, Some arg) :: rest ->
let applied, delayed = split_args ~has_omitted_arg rest in
if has_omitted_arg
then applied, arg :: delayed
else arg :: applied, delayed
in
let applied, delayed = split_args ~has_omitted_arg:false args in
let function_mode =
match applied with
| [] -> Guard
| _ :: _ -> Dereference
in
join [expression e << function_mode;
list expression applied << Dereference;
list expression delayed << Guard]
| Texp_tuple exprs ->
list expression exprs << Guard
| Texp_array exprs ->
let array_mode = match Typeopt.array_kind exp with
| Lambda.Pfloatarray ->
(* (flat) float arrays unbox their elements *)
Dereference
| Lambda.Pgenarray ->
(* This is counted as a use, because constructing a generic array
involves inspecting to decide whether to unbox (PR#6939). *)
Dereference
| Lambda.Paddrarray | Lambda.Pintarray ->
(* non-generic, non-float arrays act as constructors *)
Guard
in
list expression exprs << array_mode
| Texp_construct (_, desc, exprs) ->
let access_constructor =
match desc.cstr_tag with
| Cstr_extension (pth, _) ->
path pth << Dereference
| _ -> empty
in
let m' = match desc.cstr_tag with
| Cstr_unboxed ->
Return
| Cstr_constant _ | Cstr_block _ | Cstr_extension _ ->
Guard
in
join [
access_constructor;
list expression exprs << m'
]
| Texp_variant (_, eo) ->
(*
G |- e: m[Guard]
------------------ -----------
G |- `A e: m [] |- `A: m
*)
option expression eo << Guard
| Texp_record { fields = es; extended_expression = eo;
representation = rep } ->
let field_mode = match rep with
| Record_float -> Dereference
| Record_unboxed _ -> Return
| Record_regular | Record_inlined _
| Record_extension _ -> Guard
in
let field (_label, field_def) = match field_def with
Kept _ -> empty
| Overridden (_, e) -> expression e
in
join [
array field es << field_mode;
option expression eo << Dereference
]
| Texp_ifthenelse (cond, ifso, ifnot) ->
(*
Gc |- c: m[Dereference]
G1 |- e1: m
G2 |- e2: m
---
Gc + G1 + G2 |- if c then e1 else e2: m
Note: `if c then e1 else e2` is treated in the same way as
`match c with true -> e1 | false -> e2`
*)
join [
expression cond << Dereference;
expression ifso;
option expression ifnot;
]
| Texp_setfield (e1, _, _, e2) ->
(*
G1 |- e1: m[Dereference]
G2 |- e2: m[Dereference]
---
G1 + G2 |- e1.x <- e2: m
Note: e2 is dereferenced in the case of a field assignment to
a record of unboxed floats in that case, e2 evaluates to
a boxed float and it is unboxed on assignment.
*)
join [
expression e1 << Dereference;
expression e2 << Dereference;
]
| Texp_sequence (e1, e2) ->
(*
G1 |- e1: m[Guard]
G2 |- e2: m
--------------------
G1 + G2 |- e1; e2: m
Note: `e1; e2` is treated in the same way as `let _ = e1 in e2`
*)
join [
expression e1 << Guard;
expression e2;
]
| Texp_while (cond, body) ->
(*
G1 |- cond: m[Dereference]
G2 |- body: m[Guard]
---------------------------------
G1 + G2 |- while cond do body done: m
*)
join [
expression cond << Dereference;
expression body << Guard;
]
| Texp_send (e1, _) ->
(*
G |- e: m[Dereference]
---------------------- (plus weird 'eo' option)
G |- e#x: m
*)
join [
expression e1 << Dereference
]
| Texp_field (e, _, _) ->
(*
G |- e: m[Dereference]
-----------------------
G |- e.x: m
*)
expression e << Dereference
| Texp_setinstvar (pth,_,_,e) ->
(*
G |- e: m[Dereference]
----------------------
G |- x <- e: m
*)
join [
path pth << Dereference;
expression e << Dereference;
]
| Texp_letexception ({ext_id}, e) ->
(* G |- e: m
----------------------------
G |- let exception A in e: m
*)
remove_id ext_id (expression e)
| Texp_assert (e, _) ->
(*
G |- e: m[Dereference]
-----------------------
G |- assert e: m
Note: `assert e` is treated just as if `assert` was a function.
*)
expression e << Dereference
| Texp_pack mexp ->
(*
G |- M: m
----------------
G |- module M: m
*)
modexp mexp
| Texp_object (clsstrct, _) ->
class_structure clsstrct
| Texp_try (e, cases, eff_cases) ->
(*
G |- e: m (Gi; _ |- pi -> ei : m)^i
--------------------------------------------
G + sum(Gi)^i |- try e with (pi -> ei)^i : m
Contrarily to match, the patterns p do not inspect
the value of e, so their mode does not influence the
mode of e.
*)
let case_env c m = fst (case c m) in
join [
expression e;
list case_env cases;
list case_env eff_cases;
]
| Texp_override (pth, fields) ->
(*
G |- pth : m (Gi |- ei : m[Dereference])^i
----------------------------------------------------
G + sum(Gi)^i |- {< (xi = ei)^i >} (at path pth) : m
Note: {< .. >} is desugared to a function application, but
the function implementation might still use its arguments in
a guarded way only -- intuitively it should behave as a constructor.
We could possibly refine the arguments' Dereference into Guard here.
*)
let field (_, _, arg) = expression arg in
join [
path pth << Dereference;
list field fields << Dereference;
]
| Texp_function (params, body) ->
(*
G |-{body} b : m[Delay]
(Hj |-{def} Pj : m[Delay])^j
H := sum(Hj)^j
ps := sum(pat(Pj))^j
-----------------------------------
G + H - ps |- fun (Pj)^j -> b : m
*)
let param_pat param =
(* param P ::=
| ?(pat = expr)
| pat
Define pat(P) as
pat if P = ?(pat = expr)
pat if P = pat
*)
match param.fp_kind with
| Tparam_pat pat -> pat
| Tparam_optional_default (pat, _) -> pat
in
(* Optional argument defaults.
G |-{def} P : m
*)
let param_default param =
match param.fp_kind with
| Tparam_optional_default (_, default) ->
(*
G |- e : m
------------------
G |-{def} ?(p=e) : m
*)
expression default
| Tparam_pat _ ->
(*
------------------
. |-{def} p : m
*)
empty
in
let patterns = List.map param_pat params in
let defaults = List.map param_default params in
let body = function_body body in
let f = join (body :: defaults) << Delay in
(fun m ->
let env = f m in
remove_patlist patterns env)
| Texp_lazy e ->
(*
G |- e: m[Delay]
---------------- (modulo some subtle compiler optimizations)
G |- lazy e: m
*)
let lazy_mode = match Typeopt.classify_lazy_argument e with
| `Constant_or_function
| `Identifier _
| `Float_that_cannot_be_shortcut ->
Return
| `Other ->
Delay
in
expression e << lazy_mode
| Texp_letop{let_; ands; body; _} ->
let case_env c m = fst (case c m) in
join [
list binding_op (let_ :: ands) << Dereference;
case_env body << Delay
]
| Texp_unreachable ->
(*
----------
[] |- .: m
*)
empty
| Texp_extension_constructor (_lid, pth) ->
path pth << Dereference
| Texp_open (od, e) ->
open_declaration od >> expression e
(* Function bodies.
G |-{body} b : m
*)
and function_body body =
match body with
| Tfunction_body body ->
(*
G |- e : m
------------------
G |-{body} e : m (**)
(**) The "e" here stands for [Tfunction_body] as opposed to
[Tfunction_cases].
*)
expression body
| Tfunction_cases { cases; _ } ->
(*
(Gi; _ |- pi -> ei : m)^i (**)
------------------
sum(Gi)^i |-{body} function (pi -> ei)^i : m
(**) Contrarily to match, the values that are pattern-matched
are bound locally, so the pattern modes do not influence
the final environment.
*)
List.map (fun c mode -> fst (case c mode)) cases
|> join
and binding_op : Typedtree.binding_op -> term_judg =
fun bop ->
join [path bop.bop_op_path; expression bop.bop_exp]
and class_structure : Typedtree.class_structure -> term_judg =
fun cs -> list class_field cs.cstr_fields
and class_field : Typedtree.class_field -> term_judg =
fun cf -> match cf.cf_desc with
| Tcf_inherit (_, ce, _super, _inh_vars, _inh_meths) ->
class_expr ce << Dereference
| Tcf_val (_lab, _mut, _, cfk, _) ->
class_field_kind cfk
| Tcf_method (_, _, cfk) ->
class_field_kind cfk
| Tcf_constraint _ ->
empty
| Tcf_initializer e ->
expression e << Dereference
| Tcf_attribute _ ->
empty
and class_field_kind : Typedtree.class_field_kind -> term_judg =
fun cfk -> match cfk with
| Tcfk_virtual _ ->
empty
| Tcfk_concrete (_, e) ->