-
Notifications
You must be signed in to change notification settings - Fork 2
/
interp.ml
5106 lines (4874 loc) · 151 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
(*
* Copyright (C)2005-2013 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*)
open Common
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)
| VInt32 of int32
and vobject = {
mutable ofields : (int * value) array;
mutable oproto : vobject option;
}
and vabstract =
| ADeallocated of int ref
| AKind of vabstract
| AHash of (value, value) Hashtbl.t
| ARandom of Random.State.t ref
| ABuffer of Buffer.t
| APos of Ast.pos
| AFRead of (in_channel * bool ref)
| AFWrite of out_channel
| AReg of regexp
| AZipI of zlib
| AZipD of zlib
| AUtf8 of UTF8.Buf.buf
| ASocket of Unix.file_descr
| ATDecl of module_type
| AUnsafe of Obj.t
| ALazyType of (unit -> Type.t) ref
| ANekoAbstract of Extc.value
| ANekoBuffer of value
| ACacheRef of value
| AInt32Kind
| ATls of value ref
| AProcess of Process.process
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;
get_com : unit -> Common.context;
get_type : string -> Type.t option;
get_module : string -> Type.t list;
on_generate : (Type.t list -> unit) -> unit;
after_generate : (unit -> unit) -> unit;
on_type_not_found : (string -> value) -> unit;
parse_string : string -> Ast.pos -> bool -> Ast.expr;
type_expr : Ast.expr -> Type.texpr;
store_typed_expr : Type.texpr -> Ast.expr;
get_display : string -> string;
allow_package : string -> unit;
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_expected_type : unit -> t option;
get_call_arguments : unit -> Ast.expr list option;
get_local_method : unit -> string;
get_local_using : unit -> tclass list;
get_local_vars : unit -> (string, Type.tvar) PMap.t;
get_build_fields : unit -> value;
get_pattern_locals : Ast.expr -> Type.t -> (string,Type.tvar * Ast.pos) PMap.t;
define_type : value -> unit;
define_module : string -> value list -> ((string * Ast.pos) list * Ast.import_mode) list -> Ast.type_path list -> unit;
module_dependency : string -> string -> bool -> unit;
current_module : unit -> module_def;
delayed_macro : int -> (unit -> (unit -> value));
use_cache : unit -> bool;
format_string : string -> Ast.pos -> Ast.expr;
cast_or_unify : Type.t -> texpr -> Ast.pos -> Type.texpr;
add_global_metadata : string -> string -> (bool * bool * bool) -> unit;
}
type callstack = {
cpos : pos;
cthis : value;
cstack : int;
cenv : value array;
}
type context = {
gen : Genneko.context;
types : (Type.path,int) 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;
mutable loader : value;
mutable exports : value;
(* runtime *)
mutable stack : value DynArray.t;
mutable callstack : callstack list;
mutable callsize : int;
mutable exc : pos list;
mutable vthis : value;
mutable venv : value array;
(* context *)
mutable curapi : extern_api;
mutable on_reused : (unit -> bool) list;
mutable is_reused : bool;
(* 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
exception Invalid_expr
exception Sys_exit of int
(* ---------------------------------------------------------------------- *)
(* UTILS *)
let get_ctx_ref = ref (fun() -> assert false)
let encode_complex_type_ref = ref (fun t -> 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 encode_texpr_ref = ref (fun e -> assert false)
let decode_texpr_ref = ref (fun e -> assert false)
let encode_clref_ref = ref (fun c -> assert false)
let enc_hash_ref = ref (fun h -> assert false)
let enc_array_ref = ref (fun l -> assert false)
let dec_array_ref = ref (fun v -> assert false)
let enc_string_ref = ref (fun s -> assert false)
let make_ast_ref = ref (fun _ -> assert false)
let make_complex_type_ref = ref (fun _ -> assert false)
let encode_tvar_ref = ref (fun _ -> assert false)
let decode_path_ref = ref (fun _ -> assert false)
let decode_import_ref = ref (fun _ -> assert false)
let get_ctx() = (!get_ctx_ref)()
let enc_array (l:value list) : value = (!enc_array_ref) l
let dec_array (l:value) : value list = (!dec_array_ref) l
let encode_complex_type (t:Ast.complex_type) : value = (!encode_complex_type_ref) t
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 encode_texpr (e:Type.texpr) : value = (!encode_texpr_ref) e
let decode_texpr (v:value) : Type.texpr = (!decode_texpr_ref) v
let encode_clref (c:tclass) : value = (!encode_clref_ref) c
let enc_hash (h:('a,'b) Hashtbl.t) : value = (!enc_hash_ref) h
let make_ast (e:texpr) : Ast.expr = (!make_ast_ref) e
let enc_string (s:string) : value = (!enc_string_ref) s
let make_complex_type (t:Type.t) : Ast.complex_type = (!make_complex_type_ref) t
let encode_tvar (v:tvar) : value = (!encode_tvar_ref) v
let decode_path (v:value) : Ast.type_path = (!decode_path_ref) v
let decode_import (v:value) : ((string * Ast.pos) list * Ast.import_mode) = (!decode_import_ref) v
let to_int f = Int32.of_float (mod_float f 2147483648.0)
let need_32_bits i = Int32.compare (Int32.logand (Int32.add i 0x40000000l) 0x80000000l) Int32.zero <> 0
let best_int i = if need_32_bits i then VInt32 i else VInt (Int32.to_int i)
let make_pos p =
let low = p.pline land 0xFFFFF in
{
Ast.pfile = p.psource;
Ast.pmin = low;
Ast.pmax = low + (p.pline lsr 20);
}
let warn ctx msg p =
(ctx.curapi.get_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;
if Sys.word_size = 64 then Int32.to_int (Int32.shift_right (Int32.shift_left (Int32.of_int !h) 1) 1) else !h
let constants =
let h = Hashtbl.create 0 in
List.iter (fun f -> Hashtbl.add h (hash f) f)
["done";"read";"write";"min";"max";"file";"args";"loadprim";"loadmodule";"__a";"__s";"h";
"tag";"index";"length";"message";"pack";"name";"params";"sub";"doc";"kind";"meta";"access";
"constraints";"opt";"type";"value";"ret";"expr";"field";"values";"get";"__string";"toString";
"$";"add";"remove";"has";"__t";"module";"isPrivate";"isPublic";"isExtern";"isInterface";"exclude";
"constructs";"names";"superClass";"interfaces";"fields";"statics";"constructor";"init";"t";
"gid";"uid";"atime";"mtime";"ctime";"dev";"ino";"nlink";"rdev";"size";"mode";"pos";"len";
"binops";"unops";"from";"to";"array";"op";"isPostfix";"impl";
"id";"capture";"extra";"v";"ids";"vars";"en";"overrides";"status"];
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' | 'X') when i = 1 && String.get s 0 = '0' -> loop_hex (i + 1)
| _ -> String.sub s sp (i - sp)
in
best_int (Int32.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
(* ---------------------------------------------------------------------- *)
(* NEKO INTEROP *)
type primitive = (string * Extc.value * int)
type neko_context = {
load : string -> int -> primitive;
call : primitive -> value list -> value;
}
let neko =
let is_win = Sys.os_type = "Win32" || Sys.os_type = "Cygwin" in
let neko = Extc.dlopen (if is_win then "neko.dll" else "libneko.so") in
let null = Extc.dlint 0 in
let neko = if Obj.magic neko == null && not is_win then Extc.dlopen "libneko.dylib" else neko in
if Obj.magic neko == null then
None
else
let load v =
let s = Extc.dlsym neko v in
if (Obj.magic s) == null then failwith ("Could not load neko." ^ v);
s
in
ignore(Extc.dlcall0 (load "neko_global_init"));
let vm = Extc.dlcall1 (load "neko_vm_alloc") null in
ignore(Extc.dlcall1 (load "neko_vm_select") vm);
let loader = Extc.dlcall2 (load "neko_default_loader") null null in
let loadprim =
let l1 = load "neko_val_field" in
let l2 = Extc.dlcall1 (load "neko_val_id") (Extc.dlstring "loadprim") in
Extc.dlcall2 (l1) loader (l2) in
let callN = load "neko_val_callN" in
let callEx = load "neko_val_callEx" in
let copy_string = load "neko_copy_string" in
let alloc_root = load "neko_alloc_root" in
let free_root = load "neko_free_root" in
let alloc_root v =
let r = Extc.dlcall1 alloc_root (Extc.dlint 1) in
Extc.dlsetptr r v;
r
in
let free_root r =
ignore(Extc.dlcall1 free_root r)
in
ignore(alloc_root vm);
ignore(alloc_root loader);
ignore(alloc_root loadprim);
let alloc_string s =
Extc.dlcall2 copy_string (Extc.dlstring s) (Extc.dlint (String.length s))
in
let alloc_int (i:int) : Extc.value =
Obj.magic i
in
let loadprim n args =
let exc = ref null in
let vargs = [|alloc_string n;alloc_int args|] in
let p = Extc.dlcall5 callEx loader loadprim (Obj.magic vargs) (Extc.dlint 2) (Obj.magic exc) in
if !exc != null then failwith ("Failed to load " ^ n ^ ":" ^ string_of_int args);
ignore(alloc_root p);
(n,p,args)
in
let call_raw_prim (_,p,nargs) (args:Extc.value array) =
Extc.dlcall3 callN p (Obj.magic args) (Extc.dlint nargs)
in
(* a bit tricky since load "val_true" does not work as expected on Windows *)
let unser = try loadprim "std@unserialize" 2 with _ -> ("",null,0) in
(* did we fail to load std.ndll ? *)
if (match unser with ("",_,_) -> true | _ -> false) then None else
let val_true = call_raw_prim unser [|alloc_string "T";loader|] in
let val_false = call_raw_prim unser [|alloc_string "F";loader|] in
let val_null = call_raw_prim unser [|alloc_string "N";loader|] in
let is_64 = call_raw_prim (loadprim "std@sys_is64" 0) [||] == val_true in
let alloc_i32, is_v2 = (try load "neko_alloc_int32", true with _ -> Obj.magic 0, false) in
let alloc_i32 = if is_v2 then
(fun i -> Extc.dlcall1 alloc_i32 (Extc.dlint32 i))
else
(fun i -> alloc_int (Int32.to_int (if Int32.compare i Int32.zero < 0 then Int32.logand i 0x7FFFFFFFl else Int32.logor i 0x80000000l)))
in
let tag_bits = if is_v2 then 4 else 3 in
let tag_mask = (1 lsl tag_bits) - 1 in
let ptr_size = if is_64 then 8 else 4 in
let val_field v i = Extc.dladdr v ((i + 1) * ptr_size) in
let val_str v = Extc.dladdr v 4 in
let val_fun_env v = Extc.dladdr v (8 + ptr_size) in
(* alloc support *)
let alloc_function = load "neko_alloc_function" in
let alloc_array = load "neko_alloc_array" in
let alloc_float = load "neko_alloc_float" in
let alloc_object = load "neko_alloc_object" in
let alloc_field = load "neko_alloc_field" in
let alloc_abstract = load "neko_alloc_abstract" in
let val_gc = load "neko_val_gc" in
let val_field_name = load "neko_val_field_name" in
let val_iter_fields = load "neko_val_iter_fields" in
let gen_callback = Extc.dlcaml_callback 2 in
(* roots *)
let on_abstract_gc = Extc.dlcaml_callback 1 in
let root_index = ref 0 in
let roots = Hashtbl.create 0 in
Callback.register "dlcallb1" (fun a ->
let index : int = Obj.magic (Extc.dlptr (val_field a 1)) in
Hashtbl.remove roots index;
null
);
(* wrapping *)
let copy_string v =
let head = Extc.dltoint (Extc.dlptr v) in
let size = head asr tag_bits in
let s = String.create size in
Extc.dlmemcpy (Extc.dlstring s) (val_str v) size;
s
in
let buffers = ref [] in
let rec value_neko ?(obj=VNull) = function
| VNull -> val_null
| VBool b -> if b then val_true else val_false
| VInt i -> alloc_int i
| VAbstract (ANekoAbstract a) -> a
| VAbstract (ANekoBuffer (VString buf)) ->
let v = value_neko (VString buf) in
buffers := (buf,v) :: !buffers;
v
| VString s ->
let v = alloc_string s in (* make a copy *)
ignore(copy_string v);
v
| VObject o as obj ->
let vo = Extc.dlcall1 alloc_object null in
Array.iter (fun (id,v) ->
ignore(Extc.dlcall3 alloc_field vo (Extc.dlint id) (value_neko ~obj v))
) o.ofields;
vo
| VClosure _ ->
failwith "Closure not supported"
| VFunction f ->
let callb = Extc.dlcall3 alloc_function gen_callback (Extc.dlint (-1)) (Obj.magic "<callback>") in
let index = !root_index in
incr root_index;
Hashtbl.add roots index (f,obj);
let a = Extc.dlcall2 alloc_abstract null (Obj.magic index) in
if Extc.dlptr (val_field a 1) != Obj.magic index then assert false;
ignore(Extc.dlcall2 val_gc a on_abstract_gc);
Extc.dlsetptr (val_fun_env callb) a;
callb
| VArray a ->
let va = Extc.dlcall1 alloc_array (Extc.dlint (Array.length a)) in
Array.iteri (fun i v ->
Extc.dlsetptr (val_field va i) (value_neko v)
) a;
va
| VFloat f ->
Extc.dlcall1 alloc_float (Obj.magic f)
| VAbstract _ ->
failwith "Abstract not supported"
| VInt32 i ->
alloc_i32 i
in
let obj_r = ref [] in
let obj_fun = (fun v id -> obj_r := (v,id) :: !obj_r; val_null) in
let rec neko_value (v:Extc.value) =
if Obj.is_int (Obj.magic v) then
VInt (Obj.magic v)
else
let head = Extc.dltoint (Extc.dlptr v) in
match head land tag_mask with
| 0 -> VNull
| 2 -> VBool (v == val_true)
| 3 -> VString (copy_string v)
| 4 ->
ignore(Extc.dlcall3 val_iter_fields v (Extc.dlcallback 2) (Obj.magic obj_fun));
let r = !obj_r in
obj_r := [];
let ctx = get_ctx() in
let fields = List.rev_map (fun (v,id) ->
let iid = Extc.dltoint id in
if not (Hashtbl.mem ctx.fields_cache iid) then begin
let name = copy_string (Extc.dlcall1 val_field_name id) in
ignore(hash_field ctx name);
end;
iid, neko_value v
) r in
VObject { ofields = Array.of_list fields; oproto = None }
| 5 ->
VArray (Array.init (head asr tag_bits) (fun i -> neko_value (Extc.dlptr (val_field v i))))
| 7 ->
let r = alloc_root v in
let a = ANekoAbstract v in
Gc.finalise (fun _ -> free_root r) a;
VAbstract a
| t ->
failwith ("Unsupported Neko value tag " ^ string_of_int t)
in
Callback.register "dlcallb2" (fun args nargs ->
(* get back the VM env, which was set in value_neko *)
let env = Extc.dlptr (Extc.dladdr vm (2 * ptr_size)) in
(* extract the index stored in abstract data *)
let index : int = Obj.magic (Extc.dlptr (val_field env 1)) in
let f, obj = (try Hashtbl.find roots index with Not_found -> assert false) in
let nargs = Extc.dltoint nargs in
let rec loop i =
if i = nargs then [] else neko_value (Extc.dlptr (Extc.dladdr args (i * ptr_size))) :: loop (i + 1)
in
let v = (get_ctx()).do_call obj (VFunction f) (loop 0) { psource = "<callback>"; pline = 0; } in
value_neko v
);
let callprim (n,p,nargs) args =
let arr = Array.of_list (List.map value_neko args) in
let exc = ref null in
if Array.length arr <> nargs then failwith n;
let ret = Extc.dlcall5 callEx val_null p (Obj.magic arr) (Extc.dlint nargs) (Obj.magic exc) in
if !exc != null then raise (Runtime (neko_value !exc));
(match !buffers with
| [] -> ()
| l ->
buffers := [];
(* copy back data *)
List.iter (fun (buf,v) ->
Extc.dlmemcpy (Extc.dlstring buf) (val_str v) (String.length buf);
) l);
neko_value ret
in
Some {
load = loadprim;
call = callprim;
}
(* ---------------------------------------------------------------------- *)
(* 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)));
"fasthash", Fun1 (fun v -> VInt (hash (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 _ | VInt32 _ -> v
| VFloat f -> best_int (to_int f)
| VString s -> (try parse_int s with _ -> VNull)
| _ -> VNull
);
"float", Fun1 (fun v ->
match v with
| VInt i -> VFloat (float_of_int i)
| VInt32 i -> VFloat (Int32.to_float 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)
| VInt32 _ -> VAbstract (AKind AInt32Kind)
| _ -> 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))
| VInt32 _, VAbstract (AKind AInt32Kind) -> VBool true
| _, 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
let com = ctx.curapi.get_com() in
com.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 | VInt32 0l -> VBool false
| _ -> VBool true
);
"not", Fun1 (fun v ->
match v with
| VNull | VInt 0 | VBool false | VInt32 0l -> VBool true
| _ -> VBool false
);