-
Notifications
You must be signed in to change notification settings - Fork 1
/
interp.ml
3829 lines (3670 loc) · 111 KB
/
interp.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
(*
* Haxe Compiler
* Copyright (c)2005-2010 Nicolas Cannasse
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*)
open Nast
open Unix
open Type
(* ---------------------------------------------------------------------- *)
(* TYPES *)
type value =
| VNull
| VBool of bool
| VInt of int
| VFloat of float
| VString of string
| VObject of vobject
| VArray of value array
| VAbstract of vabstract
| VFunction of vfunction
| VClosure of value list * (value list -> value list -> value)
and vobject = {
mutable ofields : (int * value) array;
mutable oproto : vobject option;
}
and vabstract =
| AKind of vabstract
| AInt32 of int32
| AHash of (value, value) Hashtbl.t
| ARandom of Random.State.t ref
| ABuffer of Buffer.t
| APos of Ast.pos
| AFRead of in_channel
| AFWrite of out_channel
| AReg of regexp
| AZipI of zlib
| AZipD of zlib
| AUtf8 of UTF8.Buf.buf
| ASocket of Unix.file_descr
| ATExpr of texpr
| ATDecl of module_type
| AUnsafe of Obj.t
| ALazyType of (unit -> Type.t) ref
and vfunction =
| Fun0 of (unit -> value)
| Fun1 of (value -> value)
| Fun2 of (value -> value -> value)
| Fun3 of (value -> value -> value -> value)
| Fun4 of (value -> value -> value -> value -> value)
| Fun5 of (value -> value -> value -> value -> value -> value)
| FunVar of (value list -> value)
and regexp = {
r : Str.regexp;
mutable r_string : string;
mutable r_groups : (int * int) option array;
}
and zlib = {
z : Extc.zstream;
mutable z_flush : Extc.zflush;
}
type cmp =
| CEq
| CSup
| CInf
| CUndef
type extern_api = {
pos : Ast.pos;
on_error : string -> Ast.pos -> bool -> unit;
define : string -> unit;
defined : string -> bool;
get_type : string -> Type.t option;
get_module : string -> Type.t list;
on_generate : (Type.t list -> unit) -> unit;
print : string -> unit;
parse_string : string -> Ast.pos -> Ast.expr;
typeof : Ast.expr -> Type.t;
type_patch : string -> string -> bool -> string option -> unit;
meta_patch : string -> string -> string option -> bool -> unit;
set_js_generator : (value -> unit) -> unit;
get_local_type : unit -> t option;
get_build_fields : unit -> value;
define_type : value -> unit;
}
type callstack = {
cpos : pos;
cthis : value;
cstack : int;
cenv : value array;
}
type context = {
com : Common.context;
gen : Genneko.context;
types : (Type.path,bool) Hashtbl.t;
prototypes : (string list, vobject) Hashtbl.t;
fields_cache : (int,string) Hashtbl.t;
mutable error : bool;
mutable error_proto : vobject;
mutable enums : (value * string) array array;
mutable do_call : value -> value -> value list -> pos -> value;
mutable do_string : value -> string;
mutable do_loadprim : value -> value -> value;
mutable do_compare : value -> value -> cmp;
(* runtime *)
mutable stack : value DynArray.t;
mutable callstack : callstack list;
mutable exc : pos list;
mutable vthis : value;
mutable venv : value array;
(* context *)
mutable curapi : extern_api;
mutable delayed : (unit -> (unit -> value)) DynArray.t;
(* eval *)
mutable locals_map : (string, int) PMap.t;
mutable locals_count : int;
mutable locals_barrier : int;
mutable locals_env : string DynArray.t;
mutable globals : (string, value ref) PMap.t;
}
type access =
| AccThis
| AccLocal of int
| AccGlobal of value ref
| AccEnv of int
| AccField of (unit -> value) * string
| AccArray of (unit -> value) * (unit -> value)
exception Runtime of value
exception Builtin_error
exception Error of string * Ast.pos list
exception Abort
exception Continue
exception Break of value
exception Return of value
(* ---------------------------------------------------------------------- *)
(* UTILS *)
let get_ctx_ref = ref (fun() -> assert false)
let encode_type_ref = ref (fun t -> assert false)
let decode_type_ref = ref (fun t -> assert false)
let encode_expr_ref = ref (fun e -> assert false)
let decode_expr_ref = ref (fun e -> assert false)
let enc_array_ref = ref (fun l -> assert false)
let get_ctx() = (!get_ctx_ref)()
let enc_array (l:value list) : value = (!enc_array_ref) l
let encode_type (t:Type.t) : value = (!encode_type_ref) t
let decode_type (v:value) : Type.t = (!decode_type_ref) v
let encode_expr (e:Ast.expr) : value = (!encode_expr_ref) e
let decode_expr (e:value) : Ast.expr = (!decode_expr_ref) e
let to_int f = int_of_float (mod_float f 2147483648.0)
let make_pos p =
{
Ast.pfile = p.psource;
Ast.pmin = if p.pline < 0 then 0 else p.pline land 0xFFFF;
Ast.pmax = if p.pline < 0 then 0 else p.pline lsr 16;
}
let warn ctx msg p =
ctx.com.Common.warning msg (make_pos p)
let rec pop ctx n =
if n > 0 then begin
DynArray.delete_last ctx.stack;
pop ctx (n - 1);
end
let pop_ret ctx f n =
let v = f() in
pop ctx n;
v
let push ctx v =
DynArray.add ctx.stack v
let hash f =
let h = ref 0 in
for i = 0 to String.length f - 1 do
h := !h * 223 + int_of_char (String.unsafe_get f i);
done;
!h
let h_get = hash "__get" and h_set = hash "__set"
and h_add = hash "__add" and h_radd = hash "__radd"
and h_sub = hash "__sub" and h_rsub = hash "__rsub"
and h_mult = hash "__mult" and h_rmult = hash "__rmult"
and h_div = hash "__div" and h_rdiv = hash "__rdiv"
and h_mod = hash "__mod" and h_rmod = hash "__rmod"
and h_string = hash "__string" and h_compare = hash "__compare"
and h_constructs = hash "__constructs__" and h_a = hash "__a" and h_s = hash "__s"
and h_class = hash "__class__"
let exc v =
raise (Runtime v)
let hash_field ctx f =
let h = hash f in
(try
let f2 = Hashtbl.find ctx.fields_cache h in
if f <> f2 then exc (VString ("Field conflict between " ^ f ^ " and " ^ f2));
with Not_found ->
Hashtbl.add ctx.fields_cache h f);
h
let field_name ctx fid =
try
Hashtbl.find ctx.fields_cache fid
with Not_found ->
"???"
let obj hash fields =
let fields = Array.of_list (List.map (fun (k,v) -> hash k, v) fields) in
Array.sort (fun (k1,_) (k2,_) -> compare k1 k2) fields;
{
ofields = fields;
oproto = None;
}
let parse_int s =
let rec loop_hex i =
if i = String.length s then s else
match String.unsafe_get s i with
| '0'..'9' | 'a'..'f' | 'A'..'F' -> loop_hex (i + 1)
| _ -> String.sub s 0 i
in
let rec loop sp i =
if i = String.length s then (if sp = 0 then s else String.sub s sp (i - sp)) else
match String.unsafe_get s i with
| '0'..'9' -> loop sp (i + 1)
| ' ' when sp = i -> loop (sp + 1) (i + 1)
| '-' when i = 0 -> loop sp (i + 1)
| 'x' when i = 1 && String.get s 0 = '0' -> loop_hex (i + 1)
| _ -> String.sub s sp (i - sp)
in
int_of_string (loop 0 0)
let parse_float s =
let rec loop sp i =
if i = String.length s then (if sp = 0 then s else String.sub s sp (i - sp)) else
match String.unsafe_get s i with
| ' ' when sp = i -> loop (sp + 1) (i + 1)
| '0'..'9' | '-' | 'e' | 'E' | '.' -> loop sp (i + 1)
| _ -> String.sub s sp (i - sp)
in
float_of_string (loop 0 0)
let find_sub str sub start =
let sublen = String.length sub in
if sublen = 0 then
0
else
let found = ref 0 in
let len = String.length str in
try
for i = start to len - sublen do
let j = ref 0 in
while String.unsafe_get str (i + !j) = String.unsafe_get sub !j do
incr j;
if !j = sublen then begin found := i; raise Exit; end;
done;
done;
raise Not_found
with
Exit -> !found
let nargs = function
| Fun0 _ -> 0
| Fun1 _ -> 1
| Fun2 _ -> 2
| Fun3 _ -> 3
| Fun4 _ -> 4
| Fun5 _ -> 5
| FunVar _ -> -1
let rec get_field o fid =
let rec loop min max =
if min < max then begin
let mid = (min + max) lsr 1 in
let cid, v = Array.unsafe_get o.ofields mid in
if cid < fid then
loop (mid + 1) max
else if cid > fid then
loop min mid
else
v
end else
match o.oproto with
| None -> VNull
| Some p -> get_field p fid
in
loop 0 (Array.length o.ofields)
let set_field o fid v =
let rec loop min max =
let mid = (min + max) lsr 1 in
if min < max then begin
let cid, _ = Array.unsafe_get o.ofields mid in
if cid < fid then
loop (mid + 1) max
else if cid > fid then
loop min mid
else
Array.unsafe_set o.ofields mid (cid,v)
end else
let fields = Array.make (Array.length o.ofields + 1) (fid,v) in
Array.blit o.ofields 0 fields 0 mid;
Array.blit o.ofields mid fields (mid + 1) (Array.length o.ofields - mid);
o.ofields <- fields
in
loop 0 (Array.length o.ofields)
let rec remove_field o fid =
let rec loop min max =
let mid = (min + max) lsr 1 in
if min < max then begin
let cid, v = Array.unsafe_get o.ofields mid in
if cid < fid then
loop (mid + 1) max
else if cid > fid then
loop min mid
else begin
let fields = Array.make (Array.length o.ofields - 1) (fid,VNull) in
Array.blit o.ofields 0 fields 0 mid;
Array.blit o.ofields (mid + 1) fields mid (Array.length o.ofields - mid - 1);
o.ofields <- fields;
true
end
end else
false
in
loop 0 (Array.length o.ofields)
let rec get_field_opt o fid =
let rec loop min max =
if min < max then begin
let mid = (min + max) lsr 1 in
let cid, v = Array.unsafe_get o.ofields mid in
if cid < fid then
loop (mid + 1) max
else if cid > fid then
loop min mid
else
Some v
end else
match o.oproto with
| None -> None
| Some p -> get_field_opt p fid
in
loop 0 (Array.length o.ofields)
let catch_errors ctx ?(final=(fun() -> ())) f =
let n = DynArray.length ctx.stack in
try
let v = f() in
final();
Some v
with Runtime v ->
pop ctx (DynArray.length ctx.stack - n);
final();
let rec loop o =
if o == ctx.error_proto then true else match o.oproto with None -> false | Some p -> loop p
in
(match v with
| VObject o when loop o ->
(match get_field o (hash "message"), get_field o (hash "pos") with
| VObject msg, VAbstract (APos pos) ->
(match get_field msg h_s with
| VString msg -> raise (Typecore.Error (Typecore.Custom msg,pos))
| _ -> ());
| _ -> ());
| _ -> ());
raise (Error (ctx.do_string v,List.map (fun s -> make_pos s.cpos) ctx.callstack))
| Abort ->
pop ctx (DynArray.length ctx.stack - n);
final();
None
let make_library fl =
let h = Hashtbl.create 0 in
List.iter (fun (n,f) -> Hashtbl.add h n f) fl;
h
(* ---------------------------------------------------------------------- *)
(* BUILTINS *)
let builtins =
let p = { psource = "<builtin>"; pline = 0 } in
let error() =
raise Builtin_error
in
let vint = function
| VInt n -> n
| _ -> error()
in
let varray = function
| VArray a -> a
| _ -> error()
in
let vstring = function
| VString s -> s
| _ -> error()
in
let vobj = function
| VObject o -> o
| _ -> error()
in
let vfun = function
| VFunction f -> f
| VClosure (cl,f) -> FunVar (f cl)
| _ -> error()
in
let vhash = function
| VAbstract (AHash h) -> h
| _ -> error()
in
let build_stack sl =
let make p =
let p = make_pos p in
VArray [|VString p.Ast.pfile;VInt (Lexer.get_error_line p)|]
in
VArray (Array.of_list (List.map make sl))
in
let do_closure args args2 =
match args with
| f :: obj :: args ->
(get_ctx()).do_call obj f (args @ args2) p
| _ ->
assert false
in
let funcs = [
(* array *)
"array", FunVar (fun vl -> VArray (Array.of_list vl));
"amake", Fun1 (fun v -> VArray (Array.create (vint v) VNull));
"acopy", Fun1 (fun a -> VArray (Array.copy (varray a)));
"asize", Fun1 (fun a -> VInt (Array.length (varray a)));
"asub", Fun3 (fun a p l -> VArray (Array.sub (varray a) (vint p) (vint l)));
"ablit", Fun5 (fun dst dstp src p l ->
Array.blit (varray src) (vint p) (varray dst) (vint dstp) (vint l);
VNull
);
"aconcat", Fun1 (fun arr ->
let arr = Array.map varray (varray arr) in
VArray (Array.concat (Array.to_list arr))
);
(* string *)
"string", Fun1 (fun v -> VString ((get_ctx()).do_string v));
"smake", Fun1 (fun l -> VString (String.make (vint l) '\000'));
"ssize", Fun1 (fun s -> VInt (String.length (vstring s)));
"scopy", Fun1 (fun s -> VString (String.copy (vstring s)));
"ssub", Fun3 (fun s p l -> VString (String.sub (vstring s) (vint p) (vint l)));
"sget", Fun2 (fun s p ->
try VInt (int_of_char (String.get (vstring s) (vint p))) with Invalid_argument _ -> VNull
);
"sset", Fun3 (fun s p c ->
let c = char_of_int ((vint c) land 0xFF) in
try
String.set (vstring s) (vint p) c;
VInt (int_of_char c)
with Invalid_argument _ -> VNull);
"sblit", Fun5 (fun dst dstp src p l ->
String.blit (vstring src) (vint p) (vstring dst) (vint dstp) (vint l);
VNull
);
"sfind", Fun3 (fun src pos pat ->
try VInt (find_sub (vstring src) (vstring pat) (vint pos)) with Not_found -> VNull
);
(* object *)
"new", Fun1 (fun o ->
match o with
| VNull -> VObject { ofields = [||]; oproto = None }
| VObject o -> VObject { ofields = Array.copy o.ofields; oproto = o.oproto }
| _ -> error()
);
"objget", Fun2 (fun o f ->
match o with
| VObject o -> get_field o (vint f)
| _ -> VNull
);
"objset", Fun3 (fun o f v ->
match o with
| VObject o -> set_field o (vint f) v; v
| _ -> VNull
);
"objcall", Fun3 (fun o f pl ->
match o with
| VObject oo ->
(get_ctx()).do_call o (get_field oo (vint f)) (Array.to_list (varray pl)) p
| _ -> VNull
);
"objfield", Fun2 (fun o f ->
match o with
| VObject o ->
let p = o.oproto in
o.oproto <- None;
let v = get_field_opt o (vint f) in
o.oproto <- p;
VBool (v <> None)
| _ -> VBool false
);
"objremove", Fun2 (fun o f ->
VBool (remove_field (vobj o) (vint f))
);
"objfields", Fun1 (fun o ->
VArray (Array.map (fun (fid,_) -> VInt fid) (vobj o).ofields)
);
"hash", Fun1 (fun v -> VInt (hash_field (get_ctx()) (vstring v)));
"field", Fun1 (fun v ->
try VString (Hashtbl.find (get_ctx()).fields_cache (vint v)) with Not_found -> VNull
);
"objsetproto", Fun2 (fun o p ->
let o = vobj o in
(match p with
| VNull -> o.oproto <- None
| VObject p -> o.oproto <- Some p
| _ -> error());
VNull;
);
"objgetproto", Fun1 (fun o ->
match (vobj o).oproto with
| None -> VNull
| Some p -> VObject p
);
(* function *)
"nargs", Fun1 (fun f ->
VInt (nargs (vfun f))
);
"call", Fun3 (fun f o args ->
(get_ctx()).do_call o f (Array.to_list (varray args)) p
);
"closure", FunVar (fun vl ->
match vl with
| VFunction f :: _ :: _ ->
VClosure (vl, do_closure)
| _ -> exc (VString "Can't create closure : value is not a function")
);
"apply", FunVar (fun vl ->
match vl with
| f :: args ->
let f = vfun f in
VFunction (FunVar (fun args2 -> (get_ctx()).do_call VNull (VFunction f) (args @ args2) p))
| _ -> exc (VString "Invalid closure arguments number")
);
"varargs", Fun1 (fun f ->
match f with
| VFunction (FunVar _) | VFunction (Fun1 _) | VClosure _ ->
VFunction (FunVar (fun vl -> (get_ctx()).do_call VNull f [VArray (Array.of_list vl)] p))
| _ ->
error()
);
(* numbers *)
(* skip iadd, isub, idiv, imult *)
"isnan", Fun1 (fun f ->
match f with
| VFloat f -> VBool (f <> f)
| _ -> VBool false
);
"isinfinite", Fun1 (fun f ->
match f with
| VFloat f -> VBool (f = infinity || f = neg_infinity)
| _ -> VBool false
);
"int", Fun1 (fun v ->
match v with
| VInt i -> v
| VFloat f -> VInt (to_int f)
| VString s -> (try VInt (parse_int s) with _ -> VNull)
| _ -> VNull
);
"float", Fun1 (fun v ->
match v with
| VInt i -> VFloat (float_of_int i)
| VFloat _ -> v
| VString s -> (try VFloat (parse_float s) with _ -> VNull)
| _ -> VNull
);
(* abstract *)
"getkind", Fun1 (fun v ->
match v with
| VAbstract a -> VAbstract (AKind a)
| _ -> error()
);
"iskind", Fun2 (fun v k ->
match v, k with
| VAbstract a, VAbstract (AKind k) -> VBool (Obj.tag (Obj.repr a) = Obj.tag (Obj.repr k))
| _, VAbstract (AKind _) -> VBool false
| _ -> error()
);
(* hash *)
"hkey", Fun1 (fun v -> VInt (Hashtbl.hash v));
"hnew", Fun1 (fun v ->
VAbstract (AHash (match v with
| VNull -> Hashtbl.create 0
| VInt n -> Hashtbl.create n
| _ -> error()))
);
"hresize", Fun1 (fun v -> VNull);
"hget", Fun3 (fun h k cmp ->
if cmp <> VNull then assert false;
(try Hashtbl.find (vhash h) k with Not_found -> VNull)
);
"hmem", Fun3 (fun h k cmp ->
if cmp <> VNull then assert false;
VBool (Hashtbl.mem (vhash h) k)
);
"hremove", Fun3 (fun h k cmp ->
if cmp <> VNull then assert false;
let h = vhash h in
let old = Hashtbl.mem h k in
if old then Hashtbl.remove h k;
VBool old
);
"hset", Fun4 (fun h k v cmp ->
if cmp <> VNull then assert false;
let h = vhash h in
let old = Hashtbl.mem h k in
Hashtbl.replace h k v;
VBool (not old);
);
"hadd", Fun4 (fun h k v cmp ->
if cmp <> VNull then assert false;
let h = vhash h in
let old = Hashtbl.mem h k in
Hashtbl.add h k v;
VBool (not old);
);
"hiter", Fun2 (fun h f -> Hashtbl.iter (fun k v -> ignore ((get_ctx()).do_call VNull f [k;v] p)) (vhash h); VNull);
"hcount", Fun1 (fun h -> VInt (Hashtbl.length (vhash h)));
"hsize", Fun1 (fun h -> VInt (Hashtbl.length (vhash h)));
(* misc *)
"print", FunVar (fun vl -> List.iter (fun v ->
let ctx = get_ctx() in
ctx.curapi.print (ctx.do_string v)
) vl; VNull);
"throw", Fun1 (fun v -> exc v);
"rethrow", Fun1 (fun v ->
let ctx = get_ctx() in
ctx.callstack <- List.rev (List.map (fun p -> { cpos = p; cthis = ctx.vthis; cstack = DynArray.length ctx.stack; cenv = ctx.venv }) ctx.exc) @ ctx.callstack;
exc v
);
"istrue", Fun1 (fun v ->
match v with
| VNull | VInt 0 | VBool false -> VBool false
| _ -> VBool true
);
"not", Fun1 (fun v ->
match v with
| VNull | VInt 0 | VBool false -> VBool true
| _ -> VBool false
);
"typeof", Fun1 (fun v ->
VInt (match v with
| VNull -> 0
| VInt _ -> 1
| VFloat _ -> 2
| VBool _ -> 3
| VString _ -> 4
| VObject _ -> 5
| VArray _ -> 6
| VFunction _ | VClosure _ -> 7
| VAbstract _ -> 8)
);
"compare", Fun2 (fun a b ->
match (get_ctx()).do_compare a b with
| CUndef -> VNull
| CEq -> VInt 0
| CSup -> VInt 1
| CInf -> VInt (-1)
);
"pcompare", Fun2 (fun a b ->
assert false
);
"excstack", Fun0 (fun() ->
build_stack (get_ctx()).exc
);
"callstack", Fun0 (fun() ->
build_stack (List.map (fun s -> s.cpos) (get_ctx()).callstack)
);
"version", Fun0 (fun() ->
VInt 0
);
] in
let vals = [
"tnull", VInt 0;
"tint", VInt 1;
"tfloat", VInt 2;
"tbool", VInt 3;
"tstring", VInt 4;
"tobject", VInt 5;
"tarray", VInt 6;
"tfunction", VInt 7;
"tabstract", VInt 8;
] in
let h = Hashtbl.create 0 in
List.iter (fun (n,f) -> Hashtbl.add h n (VFunction f)) funcs;
List.iter (fun (n,v) -> Hashtbl.add h n v) vals;
let loader = obj hash [
"args",VArray [||];
"loadprim",VFunction (Fun2 (fun a b -> (get_ctx()).do_loadprim a b));
"loadmodule",VFunction (Fun2 (fun a b -> assert false));
] in
Hashtbl.add h "loader" (VObject loader);
Hashtbl.add h "exports" (VObject { ofields = [||]; oproto = None });
h
(* ---------------------------------------------------------------------- *)
(* STD LIBRARY *)
let std_lib =
let p = { psource = "<stdlib>"; pline = 0 } in
let error() =
raise Builtin_error
in
let make_list l =
let rec loop acc = function
| [] -> acc
| x :: l -> loop (VArray [|x;acc|]) l
in
loop VNull (List.rev l)
in
let num = function
| VInt i -> float_of_int i
| VFloat f -> f
| _ -> error()
in
let make_date f =
VAbstract (AInt32 (Int32.of_float f))
in
let date = function
| VAbstract (AInt32 i) -> Int32.to_float i
| VInt i -> float_of_int i
| _ -> error()
in
let make_i32 i =
VAbstract (AInt32 i)
in
let int32 = function
| VInt i -> Int32.of_int i
| VAbstract (AInt32 i) -> i
| _ -> error()
in
let vint = function
| VInt n -> n
| _ -> error()
in
let vstring = function
| VString s -> s
| _ -> error()
in
let int32_addr h =
let base = Int32.to_int (Int32.logand h 0xFFFFFFl) in
let str = Printf.sprintf "%ld.%d.%d.%d" (Int32.shift_right_logical h 24) (base lsr 16) ((base lsr 8) land 0xFF) (base land 0xFF) in
Unix.inet_addr_of_string str
in
let int32_op op = Fun2 (fun a b -> make_i32 (op (int32 a) (int32 b))) in
make_library [
(* math *)
"math_atan2", Fun2 (fun a b -> VFloat (atan2 (num a) (num b)));
"math_pow", Fun2 (fun a b -> VFloat ((num a) ** (num b)));
"math_abs", Fun1 (fun v ->
match v with
| VInt i -> VInt (abs i)
| VFloat f -> VFloat (abs_float f)
| _ -> error()
);
"math_ceil", Fun1 (fun v -> VInt (to_int (ceil (num v))));
"math_floor", Fun1 (fun v -> VInt (to_int (floor (num v))));
"math_round", Fun1 (fun v -> VInt (to_int (floor (num v +. 0.5))));
"math_pi", Fun0 (fun() -> VFloat (4.0 *. atan 1.0));
"math_sqrt", Fun1 (fun v -> VFloat (sqrt (num v)));
"math_atan", Fun1 (fun v -> VFloat (atan (num v)));
"math_cos", Fun1 (fun v -> VFloat (cos (num v)));
"math_sin", Fun1 (fun v -> VFloat (sin (num v)));
"math_tan", Fun1 (fun v -> VFloat (tan (num v)));
"math_log", Fun1 (fun v -> VFloat (log (num v)));
"math_exp", Fun1 (fun v -> VFloat (exp (num v)));
"math_acos", Fun1 (fun v -> VFloat (acos (num v)));
"math_asin", Fun1 (fun v -> VFloat (asin (num v)));
"math_fceil", Fun1 (fun v -> VFloat (ceil (num v)));
"math_ffloor", Fun1 (fun v -> VFloat (floor (num v)));
"math_fround", Fun1 (fun v -> VFloat (floor (num v +. 0.5)));
"math_int", Fun1 (fun v ->
match v with
| VInt n -> v
| VFloat f -> VInt (to_int (if f < 0. then ceil f else floor f))
| _ -> error()
);
(* buffer *)
"buffer_new", Fun0 (fun() ->
VAbstract (ABuffer (Buffer.create 0))
);
"buffer_add", Fun2 (fun b v ->
match b with
| VAbstract (ABuffer b) -> Buffer.add_string b ((get_ctx()).do_string v); VNull
| _ -> error()
);
"buffer_add_char", Fun2 (fun b v ->
match b, v with
| VAbstract (ABuffer b), VInt n when n >= 0 && n < 256 -> Buffer.add_char b (char_of_int n); VNull
| _ -> error()
);
"buffer_add_sub", Fun4 (fun b s p l ->
match b, s, p, l with
| VAbstract (ABuffer b), VString s, VInt p, VInt l -> (try Buffer.add_substring b s p l; VNull with _ -> error())
| _ -> error()
);
"buffer_string", Fun1 (fun b ->
match b with
| VAbstract (ABuffer b) -> VString (Buffer.contents b)
| _ -> error()
);
"buffer_reset", Fun1 (fun b ->
match b with
| VAbstract (ABuffer b) -> Buffer.reset b; VNull;
| _ -> error()
);
(* date *)
"date_now", Fun0 (fun () ->
make_date (Unix.time())
);
"date_new", Fun1 (fun v ->
make_date (match v with
| VNull -> Unix.time()
| VString s ->
(match String.length s with
| 19 ->
let r = Str.regexp "^\\([0-9][0-9][0-9][0-9]\\)-\\([0-9][0-9]\\)-\\([0-9][0-9]\\) \\([0-9][0-9]\\):\\([0-9][0-9]\\):\\([0-9][0-9]\\)$" in
if not (Str.string_match r s 0) then exc (VString ("Invalid date format : " ^ s));
let t = Unix.localtime (Unix.time()) in
let t = { t with
tm_year = int_of_string (Str.matched_group 1 s) - 1900;
tm_mon = int_of_string (Str.matched_group 2 s) - 1;
tm_mday = int_of_string (Str.matched_group 3 s);
tm_hour = int_of_string (Str.matched_group 4 s);
tm_min = int_of_string (Str.matched_group 5 s);
tm_sec = int_of_string (Str.matched_group 6 s);
} in
fst (Unix.mktime t)
| 10 ->
assert false
| 8 ->
assert false
| _ ->
exc (VString ("Invalid date format : " ^ s)));
| _ -> error())
);
"date_set_hour", Fun4 (fun d h m s ->
let d = date d in
let t = Unix.localtime d in
make_date (fst (Unix.mktime { t with tm_hour = vint h; tm_min = vint m; tm_sec = vint s }))
);
"date_set_day", Fun4 (fun d y m da ->
let d = date d in
let t = Unix.localtime d in
make_date (fst (Unix.mktime { t with tm_year = vint y - 1900; tm_mon = vint m - 1; tm_mday = vint da }))
);
"date_format", Fun2 (fun d fmt ->
match fmt with
| VNull ->
let t = Unix.localtime (date d) in
VString (Printf.sprintf "%.4d-%.2d-%.2d %.2d:%.2d:%.2d" (t.tm_year + 1900) (t.tm_mon + 1) t.tm_mday t.tm_hour t.tm_min t.tm_sec)
| VString _ ->
exc (VString "Custom date format is not supported") (* use native haXe implementation *)
| _ ->
error()
);
"date_get_hour", Fun1 (fun d ->
let t = Unix.localtime (date d) in
let o = obj (hash_field (get_ctx())) [
"h", VInt t.tm_hour;
"m", VInt t.tm_min;
"s", VInt t.tm_sec;
] in
VObject o
);
"date_get_day", Fun1 (fun d ->
let t = Unix.localtime (date d) in
let o = obj (hash_field (get_ctx())) [
"d", VInt t.tm_mday;
"m", VInt (t.tm_mon + 1);
"y", VInt (t.tm_year + 1900);
] in
VObject o
);
(* string *)
"string_split", Fun2 (fun s d ->
make_list (match s, d with
| VString "", VString _ -> [VString ""]
| VString s, VString "" -> Array.to_list (Array.init (String.length s) (fun i -> VString (String.make 1 (String.get s i))))
| VString s, VString d -> List.map (fun s -> VString s) (ExtString.String.nsplit s d)
| _ -> error())
);
"url_encode", Fun1 (fun s ->
let s = vstring s in
let b = Buffer.create 0 in
let hex = "0123456789ABCDEF" in
for i = 0 to String.length s - 1 do
let c = String.unsafe_get s i in
match c with
| 'A'..'Z' | 'a'..'z' | '0'..'9' | '_' | '-' | '.' ->
Buffer.add_char b c
| _ ->
Buffer.add_char b '%';
Buffer.add_char b (String.unsafe_get hex (int_of_char c lsr 4));
Buffer.add_char b (String.unsafe_get hex (int_of_char c land 0xF));
done;
VString (Buffer.contents b)
);
"url_decode", Fun1 (fun s ->
let s = vstring s in
let b = Buffer.create 0 in
let len = String.length s in
let decode c =
match c with
| '0'..'9' -> Some (int_of_char c - int_of_char '0')
| 'a'..'f' -> Some (int_of_char c - int_of_char 'a' + 10)
| 'A'..'F' -> Some (int_of_char c - int_of_char 'A' + 10)
| _ -> None
in
let rec loop i =
if i = len then () else
let c = String.unsafe_get s i in
match c with
| '%' ->
let p1 = (try decode (String.get s (i + 1)) with _ -> None) in
let p2 = (try decode (String.get s (i + 2)) with _ -> None) in
(match p1, p2 with
| Some c1, Some c2 ->
Buffer.add_char b (char_of_int ((c1 lsl 4) lor c2));
loop (i + 3)
| _ ->
loop (i + 1));
| '+' ->
Buffer.add_char b ' ';
loop (i + 1)
| c ->
Buffer.add_char b c;
loop (i + 1)
in
loop 0;
VString (Buffer.contents b)
);
"base_encode", Fun2 (fun s b ->
match s, b with
| VString s, VString "0123456789abcdef" when String.length s = 16 ->
VString (Digest.to_hex s)
| VString s, VString b ->
if String.length b <> 64 then assert false;
let tbl = Array.init 64 (String.unsafe_get b) in
VString (Base64.str_encode ~tbl s)
| _ -> error()
);
"base_decode", Fun2 (fun s b ->
let s = vstring s in
let b = vstring b in
if String.length b <> 64 then assert false;
let tbl = Array.init 64 (String.unsafe_get b) in
VString (Base64.str_decode ~tbl:(Base64.make_decoding_table tbl) s)
);
"make_md5", Fun1 (fun s ->
VString (Digest.string (vstring s))
);
(* sprintf *)
(* int32 *)
"int32_new", Fun1 (fun v ->
match v with
| VAbstract (AInt32 i) -> v
| VInt i -> make_i32 (Int32.of_int i)
| VFloat f -> make_i32 (Int32.of_float f)
| _ -> error()
);
"int32_to_int", Fun1 (fun v ->