forked from HaxeFoundation/haxe
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgencs.ml
1673 lines (1489 loc) · 66.5 KB
/
gencs.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/C# & Java Compiler
* Copyright (c)2011 Cauê Waneck
* based on and including code by (c)2005-2008 Nicolas Cannasse, Hugh Sanderson and Franco Ponticelli
*
* 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 Gencommon.ReflectionCFs
open Ast
open Common
open Gencommon
open Gencommon.SourceWriter
open Type
open Printf
open Option
let is_cs_basic_type t =
match follow t with
| TInst( { cl_path = (["haxe"], "Int32") }, [] )
| TInst( { cl_path = (["haxe"], "Int64") }, [] )
| TInst( { cl_path = ([], "Int") }, [] )
| TInst( { cl_path = ([], "Float") }, [] )
| TEnum( { e_path = ([], "Bool") }, [] ) ->
true
| TEnum(e, _) when not (has_meta ":$class" e.e_meta) -> true
| TInst(cl, _) when has_meta ":struct" cl.cl_meta -> true
| _ -> false
let is_tparam t =
match follow t with
| TInst( { cl_kind = KTypeParameter }, [] ) -> true
| _ -> false
let rec is_int_float t =
match follow t with
| TInst( { cl_path = (["haxe"], "Int32") }, [] )
| TInst( { cl_path = (["haxe"], "Int64") }, [] )
| TInst( { cl_path = ([], "Int") }, [] )
| TInst( { cl_path = ([], "Float") }, [] ) ->
true
| TInst( { cl_path = (["haxe"; "lang"], "Null") }, [t] ) -> is_int_float t
| _ -> false
let rec is_null t =
match t with
| TInst( { cl_path = (["haxe"; "lang"], "Null") }, _ )
| TType( { t_path = ([], "Null") }, _ ) -> true
| TType( t, tl ) -> is_null (apply_params t.t_types tl t.t_type)
| TMono r ->
(match !r with
| Some t -> is_null t
| _ -> false)
| TLazy f ->
is_null (!f())
| _ -> false
let parse_explicit_iface =
let regex = Str.regexp "\\." in
let parse_explicit_iface str =
let split = Str.split regex str in
let rec get_iface split pack =
match split with
| clname :: fn_name :: [] -> fn_name, (List.rev pack, clname)
| pack_piece :: tl -> get_iface tl (pack_piece :: pack)
| _ -> assert false
in
get_iface split []
in parse_explicit_iface
let is_string t =
match follow t with
| TInst( { cl_path = ([], "String") }, [] ) -> true
| _ -> false
(* ******************************************* *)
(* CSharpSpecificSynf *)
(* ******************************************* *)
(*
Some CSharp-specific syntax filters
dependencies:
It must run before ExprUnwrap, as it may not return valid Expr/Statement expressions
It must run before ClassInstance, as it will detect expressions that need unchanged TTypeExpr
*)
module CSharpSpecificSynf =
struct
let name = "csharp_specific"
let priority = solve_deps name [DBefore ExpressionUnwrap.priority; DBefore ClassInstance.priority; DAfter TryCatchWrapper.priority]
let get_cl_from_t t =
match follow t with
| TInst(cl,_) -> cl
| _ -> assert false
let traverse gen runtime_cl =
let basic = gen.gcon.basic in
let uint = match ( get_type gen ([], "UInt") ) with | TTypeDecl t -> t | _ -> assert false in
let tchar = match ( get_type gen (["cs"], "Char16") ) with | TTypeDecl t -> t | _ -> assert false in
let tchar = TType(tchar,[]) in
let string_ext = get_cl ( get_type gen (["haxe";"lang"], "StringExt")) in
let is_var = alloc_var "__is__" t_dynamic in
let block = ref [] in
let is_string t = match follow t with | TInst({ cl_path = ([], "String") }, []) -> true | _ -> false in
let clstring = match basic.tstring with | TInst(cl,_) -> cl | _ -> assert false in
let is_struct t = (* not basic type *)
match follow t with
| TInst(cl, _) when has_meta ":struct" cl.cl_meta -> true
| _ -> false
in
let rec run e =
match e.eexpr with
| TBlock bl ->
let old_block = !block in
block := [];
List.iter (fun e -> let e = run e in block := e :: !block) bl;
let ret = List.rev !block in
block := old_block;
{ e with eexpr = TBlock(ret) }
(* Std.is() *)
| TCall(
{ eexpr = TField( { eexpr = TTypeExpr ( TClassDecl { cl_path = ([], "Std") } ) }, "is") },
[ obj; { eexpr = TTypeExpr(md) }]
) ->
let mk_is obj md =
{ e with eexpr = TCall( { eexpr = TLocal is_var; etype = t_dynamic; epos = e.epos }, [
obj;
{ eexpr = TTypeExpr md; etype = t_dynamic (* this is after all a syntax filter *); epos = e.epos }
] ) }
in
let obj = run obj in
(match follow_module follow md with
| TClassDecl({ cl_path = ([], "Float") }) ->
(* on the special case of seeing if it is a Float, we need to test if both it is a float and if it is an Int *)
let mk_is local =
mk_paren {
eexpr = TBinop(Ast.OpBoolOr, mk_is local md, mk_is local (TClassDecl (get_cl_from_t basic.tint)));
etype = basic.tbool;
epos = e.epos
}
in
let ret = match obj.eexpr with
| TLocal(v) -> mk_is obj
| _ ->
let var = mk_temp gen "is" obj.etype in
let added = { obj with eexpr = TVars([var, Some(obj)]); etype = basic.tvoid } in
let local = mk_local var obj.epos in
{
eexpr = TBlock([ added; mk_is local ]);
etype = basic.tbool;
epos = e.epos
}
in
ret
| _ ->
mk_is obj md
)
(* end Std.is() *)
(* Std.int() *)
| TCall(
{ eexpr = TField( { eexpr = TTypeExpr ( TClassDecl ({ cl_path = ([], "Std") }) ) }, "int") },
[obj]
) ->
run (mk_cast basic.tint obj)
(* end Std.int() *)
| TField(ef, "length") when is_string ef.etype ->
{ e with eexpr = TField(run ef, "Length") }
| TField(ef, ("toLowerCase")) when is_string ef.etype ->
{ e with eexpr = TField(run ef, "ToLower") }
| TField(ef, ("toUpperCase")) when is_string ef.etype ->
{ e with eexpr = TField(run ef, "ToUpper") }
| TCall( ( { eexpr = TField({ eexpr = TTypeExpr (TClassDecl cl) }, "fromCharCode") } ), [cc] ) ->
{ e with eexpr = TNew(get_cl_from_t basic.tstring, [], [mk_cast tchar (run cc); mk_int gen 1 cc.epos]) }
| TCall( ( { eexpr = TField({ eexpr = TTypeExpr (TTypeDecl t) }, "fromCharCode") } ), [cc] ) when is_string (follow (TType(t,List.map snd t.t_types))) ->
{ e with eexpr = TNew(get_cl_from_t basic.tstring, [], [mk_cast tchar (run cc); mk_int gen 1 cc.epos]) }
| TCall( ( { eexpr = TField(ef, ("charAt" as field)) } ), args )
| TCall( ( { eexpr = TField(ef, ("charCodeAt" as field)) } ), args )
| TCall( ( { eexpr = TField(ef, ("indexOf" as field)) } ), args )
| TCall( ( { eexpr = TField(ef, ("lastIndexOf" as field)) } ), args )
| TCall( ( { eexpr = TField(ef, ("split" as field)) } ), args )
| TCall( ( { eexpr = TField(ef, ("substr" as field)) } ), args ) when is_string ef.etype ->
{ e with eexpr = TCall(mk_static_field_access_infer string_ext field e.epos [], [run ef] @ (List.map run args)) }
| TCast(expr, _) when is_int_float e.etype && not (is_int_float expr.etype) && not (is_null e.etype) ->
let needs_cast = match gen.gfollow#run_f e.etype with
| TInst _ -> false
| _ -> true
in
let fun_name = match follow e.etype with
| TInst ({ cl_path = ([], "Float") },[]) -> "toDouble"
| _ -> "toInt"
in
let ret = {
eexpr = TCall(
mk_static_field_access_infer runtime_cl fun_name expr.epos [],
[ run expr ]
);
etype = basic.tint;
epos = expr.epos
} in
if needs_cast then mk_cast e.etype ret else ret
| TCast(expr, _) when is_string e.etype ->
(*{ e with eexpr = TCall( { expr with eexpr = TField(expr, "ToString"); etype = TFun([], basic.tstring) }, [] ) }*)
mk_paren { e with eexpr = TBinop(Ast.OpAdd, run expr, { e with eexpr = TConst(TString("")) }) }
| TBinop( Ast.OpUShr, e1, e2 ) ->
mk_cast e.etype { e with eexpr = TBinop( Ast.OpShr, mk_cast (TType(uint,[])) (run e1), run e2 ) }
| TBinop( Ast.OpAssignOp Ast.OpUShr, e1, e2 ) ->
let mk_ushr local =
{ e with eexpr = TBinop(Ast.OpAssign, local, run { e with eexpr = TBinop(Ast.OpUShr, local, run e2) }) }
in
let mk_local obj =
let var = mk_temp gen "opUshr" obj.etype in
let added = { obj with eexpr = TVars([var, Some(obj)]); etype = basic.tvoid } in
let local = mk_local var obj.epos in
local, added
in
let e1 = run e1 in
let ret = match e1.eexpr with
| TField({ eexpr = TLocal _ }, _)
| TField({ eexpr = TTypeExpr _ }, _)
| TArray({ eexpr = TLocal _ }, _)
| TLocal(_) ->
mk_ushr e1
| TField(fexpr, field) ->
let local, added = mk_local fexpr in
{ e with eexpr = TBlock([ added; mk_ushr { e1 with eexpr = TField(local, field) } ]); }
| TArray(ea1, ea2) ->
let local, added = mk_local ea1 in
{ e with eexpr = TBlock([ added; mk_ushr { e1 with eexpr = TArray(local, ea2) } ]); }
| _ -> (* invalid left-side expression *)
assert false
in
ret
| TBinop( (Ast.OpNotEq as op), e1, e2)
| TBinop( (Ast.OpEq as op), e1, e2) when is_string e1.etype || is_string e2.etype ->
let mk_ret e = match op with | Ast.OpNotEq -> { e with eexpr = TUnop(Ast.Not, Ast.Prefix, e) } | _ -> e in
mk_ret { e with
eexpr = TCall({
eexpr = TField(mk_classtype_access clstring e.epos, "Equals");
etype = TFun(["obj1",false,basic.tstring; "obj2",false,basic.tstring], basic.tbool);
epos = e1.epos
}, [ run e1; run e2 ])
}
| TBinop( (Ast.OpNotEq as op), e1, e2)
| TBinop( (Ast.OpEq as op), e1, e2) when is_struct e1.etype || is_struct e2.etype ->
let mk_ret e = match op with | Ast.OpNotEq -> { e with eexpr = TUnop(Ast.Not, Ast.Prefix, e) } | _ -> e in
mk_ret { e with
eexpr = TCall({
eexpr = TField(run e1, "Equals");
etype = TFun(["obj1",false,t_dynamic;], basic.tbool);
epos = e1.epos
}, [ run e2 ])
}
| _ -> Type.map_expr run e
in
run
let configure gen (mapping_func:texpr->texpr) =
let map e = Some(mapping_func e) in
gen.gsyntax_filters#add ~name:name ~priority:(PCustom priority) map
end;;
(* Type Parameters Handling *)
let handle_type_params gen ifaces =
let basic = gen.gcon.basic in
(*
starting to set gtparam_cast.
*)
(* NativeArray: the most important. *)
(*
var new_arr = new NativeArray<TO_T>(old_arr.Length);
var i = -1;
while( i < old_arr.Length )
{
new_arr[i] = (TO_T) old_arr[i];
}
*)
let native_arr_cl = get_cl ( get_type gen (["cs"], "NativeArray") ) in
let get_narr_param t = match follow t with
| TInst({ cl_path = (["cs"], "NativeArray") }, [param]) -> param
| _ -> assert false
in
let gtparam_cast_native_array e to_t =
let old_param = get_narr_param e.etype in
let new_param = get_narr_param to_t in
let new_v = mk_temp gen "new_arr" to_t in
let i = mk_temp gen "i" basic.tint in
let old_len = { eexpr = TField(e, "Length"); etype = basic.tint; epos = e.epos } in
let obj_v = mk_temp gen "obj" t_dynamic in
let block = [
{
eexpr = TVars(
[
new_v, Some( {
eexpr = TNew(native_arr_cl, [new_param], [old_len] );
etype = to_t;
epos = e.epos
} );
i, Some( mk_int gen (-1) e.epos )
]);
etype = basic.tvoid;
epos = e.epos };
{
eexpr = TWhile(
{
eexpr = TBinop(
Ast.OpLt,
{ eexpr = TUnop(Ast.Increment, Ast.Prefix, mk_local i e.epos); etype = basic.tint; epos = e.epos },
old_len
);
etype = basic.tbool;
epos = e.epos
},
{ eexpr = TBlock [
{
eexpr = TVars([obj_v, Some (mk_cast t_dynamic { eexpr = TArray(e, mk_local i e.epos); etype = old_param; epos = e.epos })]);
etype = basic.tvoid;
epos = e.epos
};
{
eexpr = TIf({
eexpr = TBinop(Ast.OpNotEq, mk_local obj_v e.epos, null e.etype e.epos);
etype = basic.tbool;
epos = e.epos
},
{
eexpr = TBinop(
Ast.OpAssign,
{ eexpr = TArray(mk_local new_v e.epos, mk_local i e.epos); etype = new_param; epos = e.epos },
mk_cast new_param (mk_local obj_v e.epos)
);
etype = new_param;
epos = e.epos
},
None);
etype = basic.tvoid;
epos = e.epos
}
]; etype = basic.tvoid; epos = e.epos },
Ast.NormalWhile
);
etype = basic.tvoid;
epos = e.epos;
};
mk_local new_v e.epos
] in
{ eexpr = TBlock(block); etype = to_t; epos = e.epos }
in
Hashtbl.add gen.gtparam_cast (["cs"], "NativeArray") gtparam_cast_native_array;
(* end set gtparam_cast *)
TypeParams.RealTypeParams.default_config gen (fun e t -> gen.gcon.warning ("Cannot cast to " ^ (debug_type t)) e.epos; mk_cast t e) ifaces
let connecting_string = "?" (* ? see list here http://www.fileformat.info/info/unicode/category/index.htm and here for C# http://msdn.microsoft.com/en-us/library/aa664670.aspx *)
let default_package = "cs" (* I'm having this separated as I'm still not happy with having a cs package. Maybe dotnet would be better? *)
let strict_mode = ref false (* strict mode is so we can check for unexpected information *)
(* reserved c# words *)
let reserved = let res = Hashtbl.create 120 in
List.iter (fun lst -> Hashtbl.add res lst ("@" ^ lst)) ["abstract"; "as"; "base"; "bool"; "break"; "byte"; "case"; "catch"; "char"; "checked"; "class";
"const"; "continue"; "decimal"; "default"; "delegate"; "do"; "double"; "else"; "enum"; "event"; "explicit";
"extern"; "false"; "finally"; "fixed"; "float"; "for"; "foreach"; "goto"; "if"; "implicit"; "in"; "int";
"interface"; "internal"; "is"; "lock"; "long"; "namespace"; "new"; "null"; "object"; "operator"; "out"; "override";
"params"; "private"; "protected"; "public"; "readonly"; "ref"; "return"; "sbyte"; "sealed"; "short"; "sizeof";
"stackalloc"; "static"; "string"; "struct"; "switch"; "this"; "throw"; "true"; "try"; "typeof"; "uint"; "ulong";
"unchecked"; "unsafe"; "ushort"; "using"; "virtual"; "volatile"; "void"; "while"; "add"; "ascending"; "by"; "descending";
"dynamic"; "equals"; "from"; "get"; "global"; "group"; "into"; "join"; "let"; "on"; "orderby"; "partial";
"remove"; "select"; "set"; "value"; "var"; "where"; "yield"];
res
let dynamic_anon = TAnon( { a_fields = PMap.empty; a_status = ref Closed } )
(*
On hxcs, the only type parameters allowed to be declared are the basic c# types.
That's made like this to avoid casting problems when type parameters in this case
add nothing to performance, since the memory layout is always the same.
To avoid confusion between Generic<Dynamic> (which has a different meaning in hxcs AST),
all those references are using dynamic_anon, which means Generic<{}>
*)
let change_param_type md tl =
let is_hxgeneric = (TypeParams.RealTypeParams.is_hxgeneric md) in
let ret t = match is_hxgeneric, follow t with
| false, _ -> t
| true, TInst ( { cl_kind = KTypeParameter }, _ ) -> t
| true, TInst _ | true, TEnum _ when is_cs_basic_type t -> t
| true, TDynamic _ -> t
| true, _ -> dynamic_anon
in
if is_hxgeneric && List.exists (fun t -> match follow t with | TDynamic _ -> true | _ -> false) tl then
List.map (fun _ -> t_dynamic) tl
else
List.map ret tl
let rec get_class_modifiers meta cl_type cl_access cl_modifiers =
match meta with
| [] -> cl_type,cl_access,cl_modifiers
| (":struct",[],_) :: meta -> get_class_modifiers meta "struct" cl_access cl_modifiers
| (":protected",[],_) :: meta -> get_class_modifiers meta cl_type "protected" cl_modifiers
| (":internal",[],_) :: meta -> get_class_modifiers meta cl_type "internal" cl_modifiers
(* no abstract for now | (":abstract",[],_) :: meta -> get_class_modifiers meta cl_type cl_access ("abstract" :: cl_modifiers)
| (":static",[],_) :: meta -> get_class_modifiers meta cl_type cl_access ("static" :: cl_modifiers) TODO: support those types *)
| (":final",[],_) :: meta -> get_class_modifiers meta cl_type cl_access ("sealed" :: cl_modifiers)
| _ :: meta -> get_class_modifiers meta cl_type cl_access cl_modifiers
let rec get_fun_modifiers meta access modifiers =
match meta with
| [] -> access,modifiers
| (":protected",[],_) :: meta -> get_fun_modifiers meta "protected" modifiers
| (":internal",[],_) :: meta -> get_fun_modifiers meta "internal" modifiers
| (":readonly",[],_) :: meta -> get_fun_modifiers meta access ("readonly" :: modifiers)
| (":unsafe",[],_) :: meta -> get_fun_modifiers meta access ("unsafe" :: modifiers)
| (":volatile",[],_) :: meta -> get_fun_modifiers meta access ("volatile" :: modifiers)
| _ :: meta -> get_fun_modifiers meta access modifiers
(* this was the way I found to pass the generator context to be accessible across all functions here *)
(* so 'configure' is almost 'top-level' and will have all functions needed to make this work *)
let configure gen =
let basic = gen.gcon.basic in
let fn_cl = get_cl (Hashtbl.find gen.gtypes (["haxe";"lang"],"Function")) in
let null_t = (get_cl (Hashtbl.find gen.gtypes (["haxe";"lang"],"Null")) ) in
let runtime_cl = get_cl (Hashtbl.find gen.gtypes (["haxe";"lang"],"Runtime")) in
let change_ns ns = ns in
let change_clname n = n in
let change_id name = try Hashtbl.find reserved name with | Not_found -> name in
let change_field = change_id in
let write_id w name = write w (change_id name) in
let write_field w name = write w (change_field name) in
gen.gfollow#add ~name:"follow_basic" (fun t -> match t with
| TEnum ({ e_path = ([], "Bool") }, [])
| TEnum ({ e_path = ([], "Void") }, [])
| TInst ({ cl_path = ([],"Float") },[])
| TInst ({ cl_path = ([],"Int") },[])
| TType ({ t_path = [],"UInt" },[])
| TType ({ t_path = [],"Int64" },[])
| TType ({ t_path = ["cs"],"UInt64" },[])
| TType ({ t_path = ["cs"],"UInt8" },[])
| TType ({ t_path = ["cs"],"Int8" },[])
| TType ({ t_path = ["cs"],"Int16" },[])
| TType ({ t_path = ["cs"],"UInt16" },[])
| TType ({ t_path = ["cs"],"Char16" },[])
| TType ({ t_path = [],"Single" },[]) -> Some t
| TInst( { cl_path = ([], "EnumValue") }, _ ) -> Some t_dynamic
| _ -> None);
let path_s path = match path with
| ([], "String") -> "string"
| ([], "Null") -> path_s (change_ns ["haxe"; "lang"], change_clname "Null")
| (ns,clname) -> path_s (change_ns ns, change_clname clname)
in
let ifaces = Hashtbl.create 1 in
let ti64 = match ( get_type gen ([], "Int64") ) with | TTypeDecl t -> TType(t,[]) | _ -> assert false in
let rec real_type t =
let t = gen.gfollow#run_f t in
match t with
| TInst( { cl_path = (["haxe"], "Int32") }, [] ) -> gen.gcon.basic.tint
| TInst( { cl_path = (["haxe"], "Int64") }, [] ) -> ti64
| TEnum(_, [])
| TInst(_, []) -> t
| TInst(cl, params) when
List.exists (fun t -> match follow t with | TDynamic _ -> true | _ -> false) params &&
Hashtbl.mem ifaces cl.cl_path ->
TInst(Hashtbl.find ifaces cl.cl_path, [])
| TEnum(e, params) when
List.exists (fun t -> match follow t with | TDynamic _ -> true | _ -> false) params &&
Hashtbl.mem ifaces e.e_path ->
TInst(Hashtbl.find ifaces e.e_path, [])
| TInst(cl, params) -> TInst(cl, change_param_type (TClassDecl cl) params)
| TEnum(e, params) -> TEnum(e, change_param_type (TEnumDecl e) params)
| TType({ t_path = ([], "Null") }, [t]) ->
(*
Null<> handling is a little tricky.
It will only change to haxe.lang.Null<> when the actual type is non-nullable or a type parameter
It works on cases such as Hash<T> returning Null<T> since cast_detect will invoke real_type at the original type,
Null<T>, which will then return the type haxe.lang.Null<>
*)
(match real_type t with
| TInst( { cl_kind = KTypeParameter }, _ ) -> TInst(null_t, [t])
| _ when is_cs_basic_type t -> TInst(null_t, [t])
| _ -> real_type t)
| TType _ -> t
| TAnon (anon) when (match !(anon.a_status) with | Statics _ | EnumStatics _ -> true | _ -> false) -> t
| TAnon _ -> dynamic_anon
| TFun _ -> TInst(fn_cl,[])
| _ -> t_dynamic
in
let is_dynamic t = match real_type t with
| TMono _ | TDynamic _ -> true
| TAnon anon ->
(match !(anon.a_status) with
| EnumStatics _ | Statics _ -> false
| _ -> true
)
| _ -> false
in
let rec t_s t =
match real_type t with
(* basic types *)
| TEnum ({ e_path = ([], "Bool") }, []) -> "bool"
| TEnum ({ e_path = ([], "Void") }, []) -> "object"
| TInst ({ cl_path = ([],"Float") },[]) -> "double"
| TInst ({ cl_path = ([],"Int") },[]) -> "int"
| TType ({ t_path = [],"UInt" },[]) -> "uint"
| TType ({ t_path = [],"Int64" },[]) -> "long"
| TType ({ t_path = ["cs"],"UInt64" },[]) -> "ulong"
| TType ({ t_path = ["cs"],"UInt8" },[]) -> "byte"
| TType ({ t_path = ["cs"],"Int8" },[]) -> "sbyte"
| TType ({ t_path = ["cs"],"Int16" },[]) -> "short"
| TType ({ t_path = ["cs"],"UInt16" },[]) -> "ushort"
| TType ({ t_path = ["cs"],"Char16" },[]) -> "char"
| TType ({ t_path = [],"Single" },[]) -> "float"
| TInst ({ cl_path = ["haxe"],"Int32" },[]) -> "int"
| TInst ({ cl_path = ["haxe"],"Int64" },[]) -> "long"
| TInst ({ cl_path = ([], "Dynamic") }, _) -> "object"
| TInst({ cl_path = (["cs"], "NativeArray") }, [param]) ->
let rec check_t_s t =
match real_type t with
| TInst({ cl_path = (["cs"], "NativeArray") }, [param]) ->
(check_t_s param) ^ "[]"
| _ -> t_s (run_follow gen t)
in
(check_t_s param) ^ "[]"
(* end of basic types *)
| TInst ({ cl_kind = KTypeParameter; cl_path=p }, []) -> snd p
| TMono r -> (match !r with | None -> "object" | Some t -> t_s (run_follow gen t))
| TInst ({ cl_path = [], "String" }, []) -> "string"
| TInst ({ cl_path = [], "Class" }, _) | TInst ({ cl_path = [], "Enum" }, _) -> "haxe.lang.Class"
| TEnum ({ e_path = p }, params) -> (path_s p)
| TInst (({ cl_path = p } as cl), params) -> (path_param_s (TClassDecl cl) p params)
| TType (({ t_path = p } as t), params) -> (path_param_s (TTypeDecl t) p params)
| TAnon (anon) ->
(match !(anon.a_status) with
| Statics _ | EnumStatics _ -> "haxe.lang.Class"
| _ -> "object")
| TDynamic _ -> "object"
(* No Lazy type nor Function type made. That's because function types will be at this point be converted into other types *)
| _ -> if !strict_mode then begin trace ("[ !TypeError " ^ (Type.s_type (Type.print_context()) t) ^ " ]"); assert false end else "[ !TypeError " ^ (Type.s_type (Type.print_context()) t) ^ " ]"
and path_param_s md path params =
match params with
| [] -> path_s path
| _ -> sprintf "%s<%s>" (path_s path) (String.concat ", " (List.map (fun t -> t_s t) (change_param_type md params)))
in
let rett_s t =
match t with
| TEnum ({e_path = ([], "Void")}, []) -> "void"
| _ -> t_s t
in
let escape s =
let b = Buffer.create 0 in
for i = 0 to String.length s - 1 do
match String.unsafe_get s i with
| '\\' -> Buffer.add_string b "\\\\"
| '\'' -> Buffer.add_string b "\\\'"
| '\"' -> Buffer.add_string b "\\\""
| c when (Char.code c) < 32 -> Buffer.add_string b (Printf.sprintf "\\x%.2X" (Char.code c))
| c -> Buffer.add_char b c
done;
Buffer.contents b
in
let has_semicolon e =
match e.eexpr with
| TBlock _ | TFor _ | TSwitch _ | TMatch _ | TTry _ | TIf _ -> false
| TWhile (_,_,flag) when flag = Ast.NormalWhile -> false
| _ -> true
in
let in_value = ref false in
let rec md_s md =
let md = follow_module (gen.gfollow#run_f) md in
match md with
| TClassDecl ({ cl_types = [] } as cl) ->
t_s (TInst(cl,[]))
| TClassDecl (cl) when not (is_hxgen md) ->
t_s (TInst(cl,List.map (fun t -> t_dynamic) cl.cl_types))
| TEnumDecl ({ e_types = [] } as e) ->
t_s (TEnum(e,[]))
| TEnumDecl (e) when not (is_hxgen md) ->
t_s (TEnum(e,List.map (fun t -> t_dynamic) e.e_types))
| TClassDecl cl ->
t_s (TInst(cl,[]))
| TEnumDecl e ->
t_s (TEnum(e,[]))
| TTypeDecl t ->
t_s (TType(t, List.map (fun t -> t_dynamic) t.t_types))
in
let expr_s w e =
in_value := false;
let rec expr_s w e =
let was_in_value = !in_value in
in_value := true;
match e.eexpr with
| TConst c ->
(match c with
| TInt i32 ->
print w "%ld" i32;
(match real_type e.etype with
| TType( { t_path = ([], "Int64") }, [] ) -> write w "L";
| _ -> ()
)
| TFloat s ->
write w s;
(match real_type e.etype with
| TType( { t_path = ([], "Single") }, [] ) -> write w "f"
| _ -> ()
)
| TString s -> print w "\"%s\"" (escape s)
| TBool b -> write w (if b then "true" else "false")
| TNull -> print w "default(%s)" (t_s e.etype)
| TThis -> write w "this"
| TSuper -> write w "base")
| TLocal { v_name = "__sbreak__" } -> write w "break"
| TLocal { v_name = "__undefined__" } ->
write w (t_s (TInst(runtime_cl, List.map (fun _ -> t_dynamic) runtime_cl.cl_types)));
write w ".undefined";
| TLocal { v_name = "__typeof__" } -> write w "typeof"
| TLocal var ->
write_id w var.v_name
| TEnumField (e, s) ->
print w "%s." (path_s e.e_path); write_field w s
| TArray (e1, e2) ->
expr_s w e1; write w "["; expr_s w e2; write w "]"
| TBinop (op, e1, e2) ->
expr_s w e1; write w ( " " ^ (Ast.s_binop op) ^ " " ); expr_s w e2
| TField (e, s) | TClosure (e, s) ->
expr_s w e; write w "."; write_field w s
| TTypeExpr mt ->
(match mt with
| TClassDecl { cl_path = (["haxe"], "Int64") } -> write w (path_s (["haxe"], "Int64"))
| TClassDecl { cl_path = (["haxe"], "Int32") } -> write w (path_s (["haxe"], "Int32"))
| TClassDecl cl -> write w (t_s (TInst(cl, List.map (fun _ -> t_empty) cl.cl_types)))
| TEnumDecl en -> write w (t_s (TEnum(en, List.map (fun _ -> t_empty) en.e_types)))
| TTypeDecl td -> write w (t_s (gen.gfollow#run_f (TType(td, List.map (fun _ -> t_empty) td.t_types)))) )
| TParenthesis e ->
write w "("; expr_s w e; write w ")"
| TArrayDecl el ->
print w "new %s" (t_s e.etype);
write w "{";
ignore (List.fold_left (fun acc e ->
(if acc <> 0 then write w ", ");
expr_s w e;
acc + 1
) 0 el);
write w "}"
| TCall ({ eexpr = TLocal( { v_name = "__is__" } ) }, [ expr; { eexpr = TTypeExpr(md) } ] ) ->
write w "( ";
expr_s w expr;
write w " is ";
write w (md_s md);
write w " )"
| TCall ({ eexpr = TLocal( { v_name = "__as__" } ) }, [ expr; { eexpr = TTypeExpr(md) } ] ) ->
write w "( ";
expr_s w expr;
write w " as ";
write w (md_s md);
write w " )"
| TCall ({ eexpr = TLocal( { v_name = "__cs__" } ) }, [ { eexpr = TConst(TString(s)) } ] ) ->
write w s
| TCall ({ eexpr = TLocal( { v_name = "__goto__" } ) }, [ { eexpr = TConst(TInt v) } ] ) ->
print w "goto label%ld" v
| TCall ({ eexpr = TLocal( { v_name = "__label__" } ) }, [ { eexpr = TConst(TInt v) } ] ) ->
print w "label%ld: {}" v
| TCall ({ eexpr = TLocal( { v_name = "__rethrow__" } ) }, _) ->
write w "throw"
| TCall (e, el) ->
let rec extract_tparams params el =
match el with
| ({ eexpr = TLocal({ v_name = "$type_param" }) } as tp) :: tl ->
extract_tparams (tp.etype :: params) tl
| _ -> (params, el)
in
let params, el = extract_tparams [] el in
let params = List.rev params in
expr_s w e;
(match params with
| [] -> ()
| params ->
let md = match e.eexpr with
| TField(ef, _) -> t_to_md (run_follow gen ef.etype)
| _ -> assert false
in
write w "<";
ignore (List.fold_left (fun acc t ->
(if acc <> 0 then write w ", ");
write w (t_s t);
acc + 1
) 0 (change_param_type md params));
write w ">"
);
write w "(";
ignore (List.fold_left (fun acc e ->
(if acc <> 0 then write w ", ");
expr_s w e;
acc + 1
) 0 el);
write w ")"
| TNew (({ cl_path = (["cs"], "NativeArray") } as cl), params, [ size ]) ->
let rec check_t_s t times =
match real_type t with
| TInst({ cl_path = (["cs"], "NativeArray") }, [param]) ->
(check_t_s param (times+1))
| _ ->
print w "new %s[" (t_s (run_follow gen t));
expr_s w size;
print w "]";
let rec loop i =
if i <= 0 then () else (write w "[]"; loop (i-1))
in
loop (times - 1)
in
check_t_s (TInst(cl, params)) 0
| TNew (cl, params, el) ->
write w "new ";
write w (path_param_s (TClassDecl cl) cl.cl_path params);
write w "(";
ignore (List.fold_left (fun acc e ->
(if acc <> 0 then write w ", ");
expr_s w e;
acc + 1
) 0 el);
write w ")"
| TUnop ((Ast.Increment as op), flag, e)
| TUnop ((Ast.Decrement as op), flag, e) ->
(match flag with
| Ast.Prefix -> write w ( " " ^ (Ast.s_unop op) ^ " " ); expr_s w e
| Ast.Postfix -> expr_s w e; write w (Ast.s_unop op))
| TUnop (op, flag, e) ->
(match flag with
| Ast.Prefix -> write w ( " " ^ (Ast.s_unop op) ^ " (" ); expr_s w e; write w ") "
| Ast.Postfix -> write w "("; expr_s w e; write w (") " ^ Ast.s_unop op))
| TVars (v_eop_l) ->
ignore (List.fold_left (fun acc (var, eopt) ->
(if acc <> 0 then write w ", ");
print w "%s " (t_s var.v_type);
write_id w var.v_name;
(match eopt with
| None -> ()
| Some e ->
write w " = ";
expr_s w e
);
acc + 1
) 0 v_eop_l);
| TBlock [e] when was_in_value ->
expr_s w e
| TBlock el ->
begin_block w;
let last_line = ref (-1) in
let line_directive p =
let cur_line = Lexer.get_error_line p in
let is_relative_path = (String.sub p.pfile 0 1) = "." in
let file = if is_relative_path then "../" ^ p.pfile else p.pfile in
if cur_line <> ((!last_line)+1) then begin print w "//#line %d \"%s\"" cur_line (Ast.s_escape file); newline w end;
last_line := cur_line in
List.iter (fun e ->
line_directive e.epos;
in_value := false;
expr_s w e;
(if has_semicolon e then write w ";");
newline w
) el;
end_block w
| TIf (econd, e1, Some(eelse)) when was_in_value ->
write w "( ";
expr_s w (mk_paren econd);
write w " ? ";
expr_s w (mk_paren e1);
write w " : ";
expr_s w (mk_paren eelse);
write w " )";
| TIf (econd, e1, eelse) ->
write w "if ";
expr_s w (mk_paren econd);
write w " ";
in_value := false;
expr_s w (mk_block e1);
(match eelse with
| None -> ()
| Some e ->
write w " else ";
in_value := false;
expr_s w (mk_block e)
)
| TWhile (econd, eblock, flag) ->
(match flag with
| Ast.NormalWhile ->
write w "while ";
expr_s w (mk_paren econd);
write w "";
in_value := false;
expr_s w (mk_block eblock)
| Ast.DoWhile ->
write w "do ";
in_value := false;
expr_s w (mk_block eblock);
write w "while ";
in_value := true;
expr_s w (mk_paren econd);
)
| TSwitch (econd, ele_l, default) ->
write w "switch ";
expr_s w (mk_paren econd);
begin_block w;
List.iter (fun (el, e) ->
List.iter (fun e ->
write w "case ";
in_value := true;
expr_s w e;
write w ":";
) el;
newline w;
in_value := false;
expr_s w (mk_block e);
newline w;
newline w
) ele_l;
if is_some default then begin
write w "default:";
newline w;
in_value := false;
expr_s w (get default);
newline w;
end;
end_block w
| TTry (tryexpr, ve_l) ->
write w "try ";
in_value := false;
expr_s w (mk_block tryexpr);
List.iter (fun (var, e) ->
print w "catch (%s %s)" (t_s var.v_type) (var.v_name);
in_value := false;
expr_s w (mk_block e);
newline w
) ve_l
| TReturn eopt ->
write w "return ";
if is_some eopt then expr_s w (get eopt)
| TBreak -> write w "break"
| TContinue -> write w "continue"
| TThrow e ->
write w "throw ";
expr_s w e
| TCast (e1,md_t) ->
((*match gen.gfollow#run_f e.etype with
| TType({ t_path = ([], "UInt") }, []) ->
write w "( unchecked ((uint) ";
expr_s w e1;
write w ") )"
| _ ->*)
(* FIXME I'm ignoring module type *)
print w "((%s) (" (t_s e.etype);
expr_s w e1;
write w ") )"
)
| TFor (_,_,content) ->
write w "[ for not supported ";
expr_s w content;
write w " ]";
if !strict_mode then assert false
| TObjectDecl _ -> write w "[ obj decl not supported ]"; if !strict_mode then assert false
| TFunction _ -> write w "[ func decl not supported ]"; if !strict_mode then assert false
| TMatch _ -> write w "[ match not supported ]"; if !strict_mode then assert false
in
expr_s w e
in
let get_string_params cl_types =
match cl_types with
| [] ->
("","")
| _ ->
let params = sprintf "<%s>" (String.concat ", " (List.map (fun (_, tcl) -> match follow tcl with | TInst(cl, _) -> snd cl.cl_path | _ -> assert false) cl_types)) in
let params_extends = List.fold_left (fun acc (name, t) ->
match run_follow gen t with
| TInst (cl, p) ->
(match cl.cl_implements with
| [] -> acc
| _ -> acc) (* TODO
| _ -> (sprintf " where %s : %s" name (String.concat ", " (List.map (fun (cl,p) -> path_param_s (TClassDecl cl) cl.cl_path p) cl.cl_implements))) :: acc ) *)
| _ -> trace (t_s t); assert false (* FIXME it seems that a cl_types will never be anything other than cl.cl_types. I'll take the risk and fail if not, just to see if that confirms *)
) [] cl_types in
(params, String.concat " " params_extends)
in
let gen_class_field w is_static cl is_final cf =
let is_interface = cl.cl_interface in
let name, is_new, is_explicit_iface = match cf.cf_name with
| "new" -> snd cl.cl_path, true, false
| name when String.contains name '.' ->
let fn_name, path = parse_explicit_iface name in
(path_s path) ^ "." ^ fn_name, false, true
| name -> name, false, false
in
(match cf.cf_kind with
| Var _
| Method (MethDynamic) ->
if not is_interface then begin
let access, modifiers = get_fun_modifiers cf.cf_meta "public" [] in
(match cf.cf_expr with
| Some e ->
print w "%s %s%s %s %s = " access (if is_static then "static " else "") (String.concat " " modifiers) (t_s (run_follow gen cf.cf_type)) (change_field name);
expr_s w e;
write w ";"
| None ->
print w "%s %s%s %s %s;" access (if is_static then "static " else "") (String.concat " " modifiers) (t_s (run_follow gen cf.cf_type)) (change_field name)
)
end (* TODO see how (get,set) variable handle when they are interfaces *)
| Method mkind ->
let is_virtual = not is_final && match mkind with | MethInline -> false | _ when not is_new -> true | _ -> false in
let is_override = List.mem cf.cf_name cl.cl_overrides in
let is_virtual = is_virtual && not (has_meta ":final" cl.cl_meta) && not (is_interface) in
let visibility = if is_interface then "" else "public" in
let visibility, modifiers = get_fun_modifiers cf.cf_meta visibility [] in
let visibility, is_virtual = if is_explicit_iface then "",false else visibility, is_virtual in
let v_n = if is_static then "static " else if is_override && not is_interface then "override " else if is_virtual then "virtual " else "" in
let ret_type, args = match cf.cf_type with | TFun (strbtl, t) -> (t, strbtl) | _ -> assert false in
(* public static void funcName *)
print w "%s %s %s %s %s" (visibility) v_n (String.concat " " modifiers) (if is_new then "" else rett_s (run_follow gen ret_type)) (change_field name);
let params, params_ext = get_string_params cf.cf_params in
(* <T>(string arg1, object arg2) with T : object *)
print w "%s(%s)%s" (params) (String.concat ", " (List.map (fun (name, _, t) -> sprintf "%s %s" (t_s (run_follow gen t)) (change_id name)) args)) (params_ext);
if is_interface then
write w ";"
else begin
let rec loop meta =
match meta with
| [] ->
let expr = match cf.cf_expr with
| None -> mk (TBlock([])) t_dynamic Ast.null_pos