-
Notifications
You must be signed in to change notification settings - Fork 0
/
celeste_ocaml.ml
1728 lines (1603 loc) · 59.2 KB
/
celeste_ocaml.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
open Lua_parser.Ast
module T = Tqdm.Tqdm
module StringMap = Map.Make (String)
module StringSet = Set.Make (String)
(* TODO WARNING some of these pico_number functions probably have mistakes*)
type pico_number = Int32.t [@@deriving show, ord]
(*
Binary representation of PICO-8 numbers:
-1.0 0xffff_0000
-0.5 0xffff_8000
-0.1 0xffff_E667
-0.0 0x0000_0000
0.0 0x0000_0000
0.1 0x0000_1999
0.5 0x0000_8000
1.0 0x0001_0000
*)
let whole_int_of_pico_number (n : pico_number) : int =
Int32.shift_right n 16 |> Int32.to_int
let fraction_int_of_pico_number (n : pico_number) : int =
Int32.shift_right_logical (Int32.shift_left n 16) 16 |> Int32.to_int
let float_of_pico_number (n : pico_number) : float =
let whole = Float.of_int @@ whole_int_of_pico_number n in
let fraction = Float.of_int @@ fraction_int_of_pico_number n in
whole +. (fraction /. 65536.)
let pp_pico_number (f : Format.formatter) (n : pico_number) =
Format.fprintf f "(pico_number %d + (%d / 65536))"
(whole_int_of_pico_number n)
(fraction_int_of_pico_number n)
let pico_number_of_ints (whole_n : int) (fraction_n : int) : pico_number =
assert (whole_n >= -32768 && whole_n < 32768);
assert (fraction_n >= 0 && fraction_n < 65536);
let pico_n =
Int32.logor
(Int32.shift_left (Int32.of_int whole_n) 16)
(Int32.of_int fraction_n)
in
assert (whole_int_of_pico_number pico_n = whole_n);
assert (fraction_int_of_pico_number pico_n = fraction_n);
pico_n
let pico_number_of_int (n : int) : pico_number = pico_number_of_ints n 0
let rec pico_number_of_float (n : float) : pico_number =
if n < 0. then Int32.neg @@ pico_number_of_float (-.n)
else
pico_number_of_ints (int_of_float n)
(int_of_float ((n -. floor n) *. 65536.))
let pico_number_of_string n = n |> float_of_string |> pico_number_of_float
let int_of_pico_number (n : pico_number) : int =
assert (fraction_int_of_pico_number n = 0);
whole_int_of_pico_number n
let equal_pico_number = Int32.equal
let pico_number_below (v : pico_number) = Int32.sub v (Int32.of_int 1)
let pico_number_above (v : pico_number) = Int32.add v (Int32.of_int 1)
let pico_number_flr (n : pico_number) : pico_number =
pico_number_of_ints (whole_int_of_pico_number n) 0
let pico_number_ceil (n : pico_number) : pico_number =
pico_number_flr @@ Int32.add n @@ pico_number_below @@ pico_number_of_int 1
let pico_number_flr_bits (b : int) (n : pico_number) : pico_number =
assert (b >= 0 && b <= 16);
let result = Int32.logand n @@ Int32.shift_left Int32.minus_one b in
assert (result <= n);
result
let pico_number_ceil_bits (b : int) (n : pico_number) : pico_number =
assert (b >= 0 && b <= 16);
let mask = Int32.shift_left Int32.minus_one b in
let flr = Int32.logand n mask in
let ceil = Int32.logor flr @@ Int32.lognot mask in
assert (ceil >= n);
ceil
let pico_number_mul (a : pico_number) (b : pico_number) =
let result_high = Int64.mul (Int64.of_int32 a) (Int64.of_int32 b) in
let result_low = Int64.shift_right result_high 16 in
Int64.to_int32 result_low
let pico_number_div (a : pico_number) (b : pico_number) =
let a_high = Int64.shift_left (Int64.of_int32 a) 16 in
let result = Int64.div a_high (Int64.of_int32 b) in
Int64.to_int32 result
type concrete_value =
| ConcreteNumber of pico_number
| ConcreteBoolean of bool
| ConcreteReference of int
| ConcreteNil
| ConcreteString of string
[@@deriving show, eq, ord]
type abstract_value =
| AbstractOneOf of concrete_value list
| AbstractNumberRange of pico_number * pico_number
| AbstractUnknownNumber
| AbstractUnknownString
[@@deriving show, ord]
type any_value = Concrete of concrete_value | Abstract of abstract_value
[@@deriving show, ord]
type lhs_value =
| ArrayTableElement of int * int
| ObjectTableElement of int * string
[@@deriving show, ord]
module LhsValueMap = Map.Make (struct
type t = lhs_value
let compare = compare_lhs_value
end)
type array_table = any_value list [@@deriving show, ord]
type object_table = any_value StringMap.t [@@deriving ord]
let pp_object_table (f : Format.formatter) (_t : object_table) =
Format.fprintf f "{ %s }"
(Seq.fold_left
(fun a b -> a ^ "; " ^ b)
""
(Seq.map
(fun (k, v) -> k ^ " = " ^ show_any_value v)
(StringMap.to_seq _t)))
type scope = int * StringSet.t [@@deriving ord]
let pp_scope (f : Format.formatter) ((ref, values) : scope) =
Format.fprintf f "{ %d %s }" ref
(Seq.fold_left (fun a b -> a ^ "; " ^ b) "" (StringSet.to_seq values))
type identifier = Identifier of string [@@deriving show]
type heap_stats = {
gc_count : int ref;
old_writes : int ref;
old_write_size : int ref;
young_writes : int ref;
old_r_reads : int ref;
old_rw_reads : int ref;
young_reads : int ref;
young_slow_reads : int ref;
young_read_steps : int ref;
allocations : int ref;
transitions_to_old : int ref;
}
[@@deriving show]
let global_heap_stats =
{
gc_count = ref 0;
old_writes = ref 0;
old_write_size = ref 0;
young_writes = ref 0;
old_r_reads = ref 0;
old_rw_reads = ref 0;
young_reads = ref 0;
young_slow_reads = ref 0;
young_read_steps = ref 0;
allocations = ref 0;
transitions_to_old = ref 0;
}
let incr_mut r = r := !r + 1
type heap_value =
| ArrayTable of array_table
| ObjectTable of object_table
| UnknownTable
| Function of string list * int * scope list
| Builtin of int
[@@deriving show, ord]
type heap = {
old_r_values : heap_value array;
old_rw_values : heap_value array;
old_indices : (bool * int) array;
young_values : (int * heap_value) list;
size : int;
}
[@@deriving show, ord]
let heap_get (heap : heap) (i : int) : heap_value =
assert (i >= 0 && i < heap.size);
let old_count = Array.length heap.old_indices in
if i < old_count then (
match Array.get heap.old_indices i with
| false, j ->
incr_mut global_heap_stats.old_r_reads;
Array.get heap.old_r_values j
| true, j ->
incr_mut global_heap_stats.old_rw_reads;
Array.get heap.old_rw_values j)
else (
incr_mut global_heap_stats.young_reads;
let old_steps = !(global_heap_stats.young_read_steps) in
let value =
heap.young_values
|> List.find (fun (j, _v) ->
incr_mut global_heap_stats.young_read_steps;
i = j)
|> fun (_, v) -> v
in
if !(global_heap_stats.young_read_steps) > old_steps + 100 then
incr_mut global_heap_stats.young_slow_reads;
value)
let heap_update (heap : heap) (i : int) f : heap =
assert (i >= 0 && i < heap.size);
let old_count = Array.length heap.old_indices in
if i < old_count then (
incr_mut global_heap_stats.old_writes;
match Array.get heap.old_indices i with
| false, _j -> failwith "write to read-only part of heap"
| true, j ->
global_heap_stats.old_write_size :=
!(global_heap_stats.old_write_size) + Array.length heap.old_rw_values;
let values = Array.copy heap.old_rw_values in
Array.set values j (f @@ Array.get values j);
{ heap with old_rw_values = values })
else (
incr_mut global_heap_stats.young_writes;
{ heap with young_values = (i, f @@ heap_get heap i) :: heap.young_values })
let heap_set (heap : heap) (i : int) v : heap = heap_update heap i (fun _ -> v)
let heap_allocate (heap : heap) v : heap * int =
incr_mut global_heap_stats.allocations;
let i = heap.size in
( {
heap with
size = heap.size + 1;
young_values = (i, v) :: heap.young_values;
},
i )
let heap_of_seq (values : heap_value Seq.t) : heap =
let temp =
values
|> Seq.map (fun v ->
match v with
| ArrayTable _ | ObjectTable _ | UnknownTable -> (None, Some v)
| Function _ | Builtin _ -> (Some v, None))
|> Array.of_seq
in
{
old_r_values = temp |> BatArray.filter_map (fun (v, _) -> v);
old_rw_values = temp |> BatArray.filter_map (fun (_, v) -> v);
old_indices =
( temp
|> BatArray.fold_left_map
(fun (r_i, rw_i) v ->
match v with
| Some _v, None -> ((r_i + 1, rw_i), (false, r_i))
| None, Some _v -> ((r_i, rw_i + 1), (true, rw_i))
| _ -> failwith "unreachable")
(0, 0)
|> fun (_, v) -> v );
young_values = [];
size = Array.length temp;
}
let array_of_heap heap =
let values = Array.make heap.size None in
heap.old_indices
|> Array.iteri (fun i (rw, j) ->
let v =
Array.get (if rw then heap.old_rw_values else heap.old_r_values) j
in
Array.set values i (Some v));
heap.young_values
|> List.iter (fun (i, v) ->
if Array.get values i = None then Array.set values i (Some v));
Array.map Option.get values
type state = {
heap : heap;
scopes : scope list;
return : any_value option option;
break : bool;
}
[@@deriving show, ord]
module StateSet = Set.Make (struct
type t = state
let compare = compare_state
end)
type ast_numberer = (ast, int) Hashtbl.t * (int, ast) Hashtbl.t
let number_ast (tbl, rev_tbl) ast =
match Hashtbl.find_opt tbl ast with
| Some i -> i
| None ->
let i = Hashtbl.length tbl in
Hashtbl.add tbl ast i;
Hashtbl.add rev_tbl i ast;
i
let get_numbered_ast (_, rev_tbl) i = Hashtbl.find rev_tbl i
type builtin =
interpreter_context ->
state ->
(lhs_value option * any_value) list ->
state list
and interpreter_context = {
on_statement : ast -> unit;
on_mark : string * lhs_value -> unit;
print : bool;
builtins : builtin array;
ast_numberer : ast_numberer;
}
let resolve_scope (name : string) (scopes : scope list) : int option =
scopes
|> List.find_opt (fun (_, names) -> StringSet.mem name names)
|> Option.map (fun (ref, _) -> ref)
let map_ith i cb l =
assert (i >= 0 && i < List.length l);
List.mapi (fun j v -> if i = j then cb v else v) l
let get_by_scope (name : string) (state : state) : int * string * any_value =
let ref = Option.value (resolve_scope name state.scopes) ~default:0 in
let value =
match heap_get state.heap ref with
| ObjectTable scope -> StringMap.find_opt name scope
| _ -> failwith "scope references something that's not an ObjectTable"
in
let value = Option.value value ~default:(Concrete ConcreteNil) in
(ref, name, value)
let set_by_scope (name : string) (value : any_value) (state : state) : state =
let update_table = function
| ObjectTable o -> ObjectTable (StringMap.add name value o)
| _ -> failwith "scope references something that's not an ObjectTable"
in
let ref = Option.value (resolve_scope name state.scopes) ~default:0 in
{ state with heap = heap_update state.heap ref update_table }
let allocate o state =
let heap, i = heap_allocate state.heap o in
({ state with heap }, Concrete (ConcreteReference i))
let add_local (name : string) ((ref, names) : scope) : scope =
(ref, StringSet.add name names)
let is_in_call (state : state) : bool = List.length state.scopes != 0
let is_skipping (state : state) : bool =
Option.is_some state.return || state.break
let pad_or_drop p n l =
if List.length l > n then BatList.take n l
else l @ List.init (n - List.length l) (fun _ -> p)
let concrete_number_of_any_value v =
match v with
| Concrete (ConcreteNumber n) -> n
| _ -> failwith "not a concrete number"
let concat_fold_left f init list =
List.fold_left (fun xs y -> List.concat_map (fun x -> f x y) xs) init list
let concat_fold_left_map (f : 'a -> 'b -> ('a * 'c) list) (init : 'a list)
(list : 'b list) : ('a * 'c list) list =
list
|> List.fold_left
(fun (xs : ('a * 'c list) list) (y : 'b) ->
xs
|> List.concat_map (fun (old_acc, old_map_values) ->
f old_acc y
|> List.map (fun (acc, map_value) ->
(acc, map_value :: old_map_values))))
(List.map (fun init -> (init, [])) init)
|> List.map (fun (acc, map_values) -> (acc, List.rev map_values))
let concat_map_sort_uniq_states (f : state -> state list)
(old_states : state list) (on_old_state_processed : unit -> unit) :
state list * int =
let old_states = Array.of_list old_states in
(* HACK shuffle so that the progress bar advances more evenly *)
BatArray.shuffle old_states;
let count_with_duplicates = ref 0 in
let new_states =
Array.fold_left
(fun new_states state ->
StateSet.add_seq
(let states_with_duplicates = f state in
count_with_duplicates :=
!count_with_duplicates + List.length states_with_duplicates;
on_old_state_processed ();
states_with_duplicates |> List.sort_uniq compare_state |> List.to_seq)
new_states)
StateSet.empty old_states
in
(StateSet.elements new_states, !count_with_duplicates)
let only xs =
match xs with
| [ x ] -> x
| _ -> failwith "list does not contain exactly one element"
let rec bools_of_any_value (v : any_value) : (bool * any_value) list =
match v with
| Concrete (ConcreteBoolean b) -> [ (b, v) ]
| Concrete (ConcreteNumber _) -> [ (true, v) ]
| Concrete ConcreteNil -> [ (false, v) ]
| Abstract (AbstractNumberRange _) -> [ (true, v) ]
| Abstract (AbstractOneOf options) ->
List.concat_map (fun o -> bools_of_any_value (Concrete o)) options
| Abstract AbstractUnknownString -> [ (true, v) ]
| _ ->
failwith
"bools_from_any_value called on a value which could not be converted \
to a boolean"
let any_value_of_bools_direct (maybe_false : bool) (maybe_true : bool) :
any_value =
match (maybe_false, maybe_true) with
| false, false -> Abstract (AbstractOneOf [])
| false, true -> Concrete (ConcreteBoolean true)
| true, false -> Concrete (ConcreteBoolean false)
| true, true ->
Abstract (AbstractOneOf [ ConcreteBoolean false; ConcreteBoolean true ])
let any_value_of_bools (bools : bool list) : any_value =
let maybe_false, maybe_true =
List.fold_left
(fun (maybe_false, maybe_true) b ->
(maybe_false || not b, maybe_true || b))
(false, false) bools
in
any_value_of_bools_direct maybe_false maybe_true
let number_range_of_any_value (v : any_value) : pico_number * pico_number =
match v with
| Concrete (ConcreteNumber v) -> (v, v)
| Abstract (AbstractNumberRange (v_min, v_max)) ->
assert (v_min <= v_max);
(v_min, v_max)
| _ ->
failwith
"number_range_from_any_value called on a value which could not be \
converted to a number range"
let any_value_of_number_range (v_min : pico_number) (v_max : pico_number) :
any_value =
assert (v_min <= v_max);
if v_min = v_max then Concrete (ConcreteNumber v_min)
else Abstract (AbstractNumberRange (v_min, v_max))
let single_number_of_range (min, max) =
if min = max then min else failwith "range is not a single number"
let number_ranges_intersect (a_min, a_max) (b_min, b_max) =
assert (a_min <= a_max && b_min <= b_max);
(* TODO not sure if this is correct*)
not (a_max < b_min || b_max < a_min)
let rec interpret_expression (ctx : interpreter_context) (state : state)
(expr : ast) : (state * lhs_value option * any_value) list =
match expr with
| Number n ->
[ (state, None, Concrete (ConcreteNumber (pico_number_of_string n))) ]
| Bool "true" -> [ (state, None, Concrete (ConcreteBoolean true)) ]
| Bool "false" -> [ (state, None, Concrete (ConcreteBoolean false)) ]
| Bool "nil" -> [ (state, None, Concrete ConcreteNil) ]
| String s ->
assert (String.starts_with ~prefix:"\"" s);
assert (String.ends_with ~suffix:"\"" s);
let s = String.sub s 1 (String.length s - 2) in
assert (not (String.contains s '"'));
[ (state, None, Concrete (ConcreteString s)) ]
| Ident name ->
let lhs_ref, lhs_name, value = get_by_scope name state in
[ (state, Some (ObjectTableElement (lhs_ref, lhs_name)), value) ]
| Table (Elist []) ->
let state, value = allocate UnknownTable state in
[ (state, None, value) ]
| Table (Elist initializer_asts) ->
let initializers =
List.map
(function
| Assign (Ident name, expr) -> (name, expr)
| _ ->
Lua_parser.Pp_ast.pp_ast_show expr;
failwith "unsupported table initializer")
initializer_asts
in
let initializations =
concat_fold_left_map
(fun state (_, expr) -> interpret_rhs_expression ctx state expr)
[ state ] initializers
in
initializations
|> List.map (fun (state, initializer_values) ->
let value_map =
List.map2
(fun (name, _) value -> (name, value))
initializers initializer_values
|> List.to_seq |> StringMap.of_seq
in
let state, value = allocate (ObjectTable value_map) state in
(state, None, value))
| FunctionE (Fbody (Elist params, body)) ->
let params =
List.map
(function
| Ident name -> name | _ -> "unsupported function parameter")
params
in
let state, value =
allocate
(Function (params, number_ast ctx.ast_numberer body, state.scopes))
state
in
[ (state, None, value) ]
| Clist [ callee_expr; Args (Elist arg_exprs) ] ->
let state, callee_value =
only @@ interpret_rhs_expression ctx state callee_expr
in
let state, arg_values =
List.fold_left_map
(fun state expr ->
let state, lhs_value, value =
only @@ interpret_expression ctx state expr
in
(state, (lhs_value, value)))
state arg_exprs
in
interpret_call ctx state callee_value arg_values
|> List.map (fun (state, return_value) ->
(state, None, Option.get return_value))
| Clist [ lhs_expr; Key1 rhs_expr ] ->
let state, lhs_ref =
match interpret_expression ctx state lhs_expr with
| [ (state, _, Concrete (ConcreteReference ref)) ] -> (state, ref)
| _ ->
failwith "element access where left value is not ConcreteReference"
in
let state, rhs_index =
match interpret_expression ctx state rhs_expr with
| [ (state, _, Concrete (ConcreteNumber i)) ] ->
(state, int_of_pico_number i - 1)
| _ -> failwith "element access where right value is not ConcreteNumber"
in
let value =
match heap_get state.heap lhs_ref with
| ArrayTable values -> List.nth values rhs_index
| _ ->
failwith
"element access where left value references something that's not \
an ArrayTable"
in
[ (state, Some (ArrayTableElement (lhs_ref, rhs_index)), value) ]
| Clist [ lhs_expr; Key2 (Ident rhs_name) ] ->
let state, lhs_ref =
match interpret_expression ctx state lhs_expr with
| [ (state, _, Concrete (ConcreteReference ref)) ] -> (state, ref)
| _ ->
failwith "property access where left value is not ConcreteReference"
in
let value =
match heap_get state.heap lhs_ref with
| ObjectTable scope -> StringMap.find_opt rhs_name scope
| UnknownTable -> None
| _ ->
failwith
"property access where left value references something that's \
not an ObjectTable"
in
let value = Option.value value ~default:(Concrete ConcreteNil) in
[ (state, Some (ObjectTableElement (lhs_ref, rhs_name)), value) ]
| Unop (op, value) ->
let state, value = only @@ interpret_rhs_expression ctx state value in
[ (state, None, interpret_unop state op value) ]
| Binop (op, left, right) ->
interpret_rhs_expression ctx state left
|> List.concat_map (fun (state, left) ->
interpret_binop_maybe_short ctx state op left right
|> List.map (fun (state, value) -> (state, None, value)))
| Pexp expr -> interpret_expression ctx state expr
| _ ->
Lua_parser.Pp_ast.pp_ast_show expr;
failwith "unsupported expression"
and interpret_rhs_expression ctx state expr =
interpret_expression ctx state expr
|> List.map (fun (state, _, value) -> (state, value))
(* TODO WARNING some of these unop handlers probably have mistakes*)
and interpret_unop (_state : state) (op : string) (v : any_value) : any_value =
match (String.trim op, v) with
| "-", Concrete (ConcreteNumber v) -> Concrete (ConcreteNumber (Int32.neg v))
| "not", _ ->
v |> bools_of_any_value
|> List.map (fun (b, _) -> not b)
|> any_value_of_bools
| _ -> failwith (Printf.sprintf "unsupported op: %s %s" op (show_any_value v))
and interpret_binop_maybe_short (ctx : interpreter_context) (state : state)
(op : string) (left : any_value) (right : ast) : (state * any_value) list =
match (op, left) with
| "and", _ ->
bools_of_any_value left
|> List.concat_map (fun (left_bool, left) ->
match left_bool with
| true -> interpret_rhs_expression ctx state right
| false -> [ (state, left) ])
| "or", _ ->
bools_of_any_value left
|> List.concat_map (fun (left_bool, left) ->
match left_bool with
| true -> [ (state, left) ]
| false -> interpret_rhs_expression ctx state right)
| op, Abstract (AbstractOneOf left_options) ->
left_options
|> List.map (fun v -> Concrete v)
|> List.concat_map (fun left ->
interpret_binop_maybe_short ctx state op left right)
| _ ->
interpret_rhs_expression ctx state right
|> List.map (fun (state, right) ->
(state, interpret_binop_not_short state op left right))
(* TODO WARNING some of these binop handlers probably have mistakes*)
and interpret_binop_not_short (state : state) (op : string) (left : any_value)
(right : any_value) : any_value =
match (op, left, right) with
| "+", Concrete (ConcreteNumber left), Concrete (ConcreteNumber right) ->
Concrete (ConcreteNumber (Int32.add left right))
| ( "+",
Concrete (ConcreteNumber left),
Abstract (AbstractNumberRange (right_min, right_max)) ) ->
Abstract
(AbstractNumberRange (Int32.add left right_min, Int32.add left right_max))
| ( "+",
Abstract (AbstractNumberRange (left_min, left_max)),
Abstract (AbstractNumberRange (right_min, right_max)) ) ->
Abstract
(AbstractNumberRange
(Int32.add left_min right_min, Int32.add left_max right_max))
| "+", Abstract _, Concrete _ -> interpret_binop_not_short state op right left
| "+", Abstract AbstractUnknownNumber, _
| "+", _, Abstract AbstractUnknownNumber ->
Abstract AbstractUnknownNumber
| "-", Concrete (ConcreteNumber left), Concrete (ConcreteNumber right) ->
Concrete (ConcreteNumber (Int32.sub left right))
| ( "-",
Abstract (AbstractNumberRange (left_min, left_max)),
Concrete (ConcreteNumber right) ) ->
Abstract
(AbstractNumberRange (Int32.sub left_min right, Int32.sub left_max right))
| ( "-",
Abstract (AbstractNumberRange (left_min, left_max)),
Abstract (AbstractNumberRange (right_min, right_max)) ) ->
Abstract
(AbstractNumberRange
(Int32.sub left_min right_max, Int32.sub left_max right_min))
| "-", Abstract AbstractUnknownNumber, _
| "-", _, Abstract AbstractUnknownNumber ->
Abstract AbstractUnknownNumber
| "/", Concrete (ConcreteNumber left), Concrete (ConcreteNumber right) ->
Concrete (ConcreteNumber (pico_number_div left right))
| ( "/",
Abstract (AbstractNumberRange (left_min, left_max)),
Concrete (ConcreteNumber right) ) ->
assert (Int32.compare right (pico_number_of_int 0) > 0);
Abstract
(AbstractNumberRange
(pico_number_div left_min right, pico_number_div left_max right))
| "/", Abstract AbstractUnknownNumber, _
| "/", _, Abstract AbstractUnknownNumber ->
Abstract AbstractUnknownNumber
| "*", Concrete (ConcreteNumber left), Concrete (ConcreteNumber right) ->
Concrete (ConcreteNumber (pico_number_mul left right))
| "*", Abstract AbstractUnknownNumber, _
| "*", _, Abstract AbstractUnknownNumber ->
Abstract AbstractUnknownNumber
| "%", Concrete (ConcreteNumber left), Concrete (ConcreteNumber right) ->
let left_whole = whole_int_of_pico_number left in
assert (left_whole >= 0);
let left_fraction = fraction_int_of_pico_number left in
assert (left_fraction >= 0);
let right = int_of_pico_number right in
assert (right > 0);
Concrete
(ConcreteNumber
(pico_number_of_ints (left_whole mod right) left_fraction))
| "%", Abstract AbstractUnknownNumber, _
| "%", _, Abstract AbstractUnknownNumber ->
Abstract AbstractUnknownNumber
| "==", Concrete left, Concrete right ->
Concrete (ConcreteBoolean (equal_concrete_value left right))
| "==", Concrete (ConcreteNumber _), Abstract (AbstractNumberRange _)
| "==", Abstract (AbstractNumberRange _), Concrete (ConcreteNumber _)
| "==", Abstract (AbstractNumberRange _), Abstract (AbstractNumberRange _) ->
let left = number_range_of_any_value left in
let left_min, left_max = left in
let right = number_range_of_any_value right in
let right_min, right_max = left in
any_value_of_bools_direct
(left <> right || left_min <> left_max || right_min <> right_max)
(number_ranges_intersect left right)
| "~=", Concrete left, Concrete right ->
Concrete (ConcreteBoolean (not @@ equal_concrete_value left right))
| "~=", Concrete (ConcreteNumber _), Abstract (AbstractNumberRange _)
| "~=", Abstract (AbstractNumberRange _), Concrete (ConcreteNumber _)
| "~=", Abstract (AbstractNumberRange _), Abstract (AbstractNumberRange _) ->
let left = number_range_of_any_value left in
let left_min, left_max = left in
let right = number_range_of_any_value right in
let right_min, right_max = left in
any_value_of_bools_direct
(number_ranges_intersect left right)
(left <> right || left_min <> left_max || right_min <> right_max)
| "<", _, _ | "<=", _, _ | ">", _, _ | ">=", _, _ ->
let compare_concrete left right =
(match op with
| "<" -> ( < )
| "<=" -> ( <= )
| ">" -> ( > )
| ">=" -> ( >= )
| _ -> failwith "unreachable")
(Int32.compare left right) 0
in
let compare_range (left_min, left_max) (right_min, right_max) =
any_value_of_bools
[
compare_concrete left_min right_min;
compare_concrete left_min right_max;
compare_concrete left_max right_min;
compare_concrete left_max right_max;
]
in
compare_range
(number_range_of_any_value left)
(number_range_of_any_value right)
| "..", _, _ -> Abstract AbstractUnknownString
| _ ->
failwith
(Printf.sprintf "unsupported op: %s %s %s" (show_any_value left) op
(show_any_value right))
and interpret_statement (ctx : interpreter_context) (state : state) (stmt : ast)
: state list =
if not (is_skipping state) then ctx.on_statement stmt;
match (is_skipping state, stmt) with
| true, _ -> [ state ]
| _, Assign (Elist [ lhs_expr ], Elist [ expr ]) ->
let state, lhs =
match only @@ interpret_expression ctx state lhs_expr with
| state, Some lhs, _ -> (state, lhs)
| _, None, _ -> failwith "assignment to non-lhs expression"
in
interpret_rhs_expression ctx state expr
|> List.map (fun (state, value) ->
let update_array_table lhs_index = function
| ArrayTable values ->
ArrayTable (map_ith lhs_index (fun _ -> value) values)
| _ ->
failwith
"lhs of assignment references something that's not an \
ArrayTable"
in
let update_object_table lhs_name = function
| ObjectTable o -> ObjectTable (StringMap.add lhs_name value o)
| UnknownTable ->
ObjectTable (StringMap.singleton lhs_name value)
| _ ->
failwith
"lhs of assignment references something that's not an \
ObjectTable or UnknownTable"
in
let lhs_ref, update_table =
match lhs with
| ArrayTableElement (lhs_ref, lhs_index) ->
(lhs_ref, update_array_table lhs_index)
| ObjectTableElement (lhs_ref, lhs_name) ->
(lhs_ref, update_object_table lhs_name)
in
{ state with heap = heap_update state.heap lhs_ref update_table })
| _, Lassign (Elist [ Ident name ], expr) ->
let state =
only @@ interpret_statement ctx state (Lnames (Elist [ Ident name ]))
in
let state =
interpret_statement ctx state (Assign (Elist [ Ident name ], expr))
in
state
| _, Lnames (Elist [ Ident name ]) ->
[
{
state with
scopes = add_local name (List.hd state.scopes) :: List.tl state.scopes;
};
]
| _, Function (FNlist [ Ident name ], f) ->
interpret_statement ctx state
(Assign (Elist [ Ident name ], Elist [ FunctionE f ]))
| _, Clist [ callee_expr; Args (Elist arg_exprs) ] ->
let state, callee_value =
only @@ interpret_rhs_expression ctx state callee_expr
in
let state, arg_values =
List.fold_left_map
(fun state expr ->
let state, lhs_value, value =
only @@ interpret_expression ctx state expr
in
(state, (lhs_value, value)))
state arg_exprs
in
interpret_call ctx state callee_value arg_values
|> List.map (fun (state, _) -> state)
| _, Return (Elist [ expr ]) ->
assert (is_in_call state);
interpret_rhs_expression ctx state expr
|> List.map (fun (state, value) ->
{ state with return = Some (Some value) })
| _, Return (Elist []) ->
assert (is_in_call state);
[ { state with return = Some None } ]
| _, Break -> [ { state with break = true } ]
| _, For1 (Ident i_name, i_from, i_to, Slist body) ->
let state, i_from = only @@ interpret_rhs_expression ctx state i_from in
let i_from = concrete_number_of_any_value i_from in
let state, i_to = only @@ interpret_rhs_expression ctx state i_to in
let i_to = concrete_number_of_any_value i_to in
let i_values =
BatEnum.unfold i_from (fun i ->
if i <= i_to then
Some
(Concrete (ConcreteNumber i), Int32.add i (pico_number_of_int 1))
else None)
|> BatList.of_enum
in
let state =
List.fold_left
(fun state i_value ->
if is_skipping state then state
else
let old_scopes = state.scopes in
let heap, scope_ref =
heap_allocate state.heap
(ObjectTable (StringMap.singleton i_name i_value))
in
let state =
{
state with
scopes =
(scope_ref, StringSet.singleton i_name) :: state.scopes;
heap;
}
in
let state =
List.fold_left
(fun state ast -> only @@ interpret_statement ctx state ast)
state body
in
{ state with scopes = old_scopes })
state i_values
in
[ { state with break = false } ]
| _, If1 (cond, body) ->
interpret_statement ctx state (If3 (cond, body, Slist []))
| _, If2 (cond, then_body, else_body) ->
interpret_statement ctx state
(If3 (cond, then_body, Slist [ Elseif (Bool "true", else_body) ]))
| _, If3 (first_cond, first_body, Slist elseifs) ->
let branches =
List.map
(function
| Elseif (cond, Slist body) -> (cond, body)
| _ -> failwith "expected Elseif")
(Elseif (first_cond, first_body)
:: (elseifs @ [ Elseif (Bool "true", Slist []) ]))
in
let interpret_condition (state, already_matched) (cond, _) :
(state * bool) list =
if already_matched then [ (state, true) ]
else
interpret_rhs_expression ctx state cond
|> List.concat_map (fun (state, value) ->
bools_of_any_value value
|> List.map (fun (value, _) -> (state, value)))
in
concat_fold_left_map
(fun acc cond ->
interpret_condition acc cond |> List.map (fun v -> (v, v)))
[ (state, false) ]
branches
|> List.concat_map (fun (_, matches) ->
let state, _, body =
List.map2
(fun (state, did_match) (_, body) -> (state, did_match, body))
matches branches
|> List.find (fun (_, did_match, _) -> did_match)
in
if List.length body = 0 then [ state ]
else
let old_scopes = state.scopes in
let heap, scope_ref =
heap_allocate state.heap (ObjectTable StringMap.empty)
in
let state =
{
state with
scopes = (scope_ref, StringSet.empty) :: state.scopes;
heap;
}
in
concat_fold_left
(fun state ast -> interpret_statement ctx state ast)
[ state ] body
|> List.map (fun state -> { state with scopes = old_scopes }))
| _, If4 (first_cond, first_body, Slist elseifs, else_body) ->
interpret_statement ctx state
(If3
( first_cond,
first_body,
Slist (elseifs @ [ Elseif (Bool "true", else_body) ]) ))
| _, _ ->
Lua_parser.Pp_ast.pp_ast_show stmt;
failwith "unsupported statement"
and interpret_call (ctx : interpreter_context) (state : state)
(callee : any_value) (args : (lhs_value option * any_value) list) :
(state * any_value option) list =
assert (not (is_skipping state));
let ref =
match callee with
| Concrete (ConcreteReference ref) -> ref
| _ -> failwith "callee is not a concrete reference"
in
let old_scopes = state.scopes in
let heap, scope_ref =
heap_allocate state.heap (ObjectTable StringMap.empty)
in
let state = { state with heap } in
let states =
match heap_get state.heap ref with
| Function (params, body_i, scopes) ->
let args =
pad_or_drop (None, Concrete ConcreteNil) (List.length params) args
in
let state =
{
state with
scopes = (scope_ref, StringSet.of_list params) :: scopes;
}
in
let state =
List.fold_left2
(fun state name (_, value) -> set_by_scope name value state)
state params args
in
let body =
match get_numbered_ast ctx.ast_numberer body_i with
| Slist body -> body
| _ -> failwith "body is not Slist"
in
concat_fold_left
(fun state ast -> interpret_statement ctx state ast)
[ state ] body
| Builtin i ->
let f = Array.get ctx.builtins i in
f ctx state args
| _ -> failwith "callee is not a function"
in
List.map
(fun state ->
( { state with scopes = old_scopes; return = None },
Option.value state.return ~default:None ))
states
let rec gc_heap heap : heap_value Seq.t =
incr_mut global_heap_stats.gc_count;
let new_refs_by_old_ref = Array.make heap.size None in
let heap_array = array_of_heap heap in
let old_refs = Stack.create () in
let rec f_once (old_ref : int) : int =
let new_ref, first_visit =