forked from HaxeFoundation/haxe
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gencs.ml
3390 lines (3086 loc) · 128 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
(*
* 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 Gencommon.ReflectionCFs
open Ast
open Common
open Gencommon
open Gencommon.SourceWriter
open Type
open Printf
open Option
open ExtString
let is_cs_basic_type t =
match follow t with
| TInst( { cl_path = (["haxe"], "Int32") }, [] )
| TInst( { cl_path = (["haxe"], "Int64") }, [] )
| TInst( { cl_path = ([], "Int") }, [] )
| TAbstract ({ a_path = ([], "Int") },[])
| TInst( { cl_path = ([], "Float") }, [] )
| TAbstract ({ a_path = ([], "Float") },[])
| TEnum( { e_path = ([], "Bool") }, [] )
| TAbstract ({ a_path = ([], "Bool") },[]) ->
true
| TAbstract _ when like_float t ->
true
| TEnum(e, _) when not (Meta.has Meta.Class e.e_meta) -> true
| TInst(cl, _) when Meta.has Meta.Struct cl.cl_meta -> true
| _ -> false
(* see http://msdn.microsoft.com/en-us/library/2sk3x8a7(v=vs.71).aspx *)
let cs_binops =
[Ast.OpAdd, "op_Addition";
Ast.OpSub, "op_Subtraction";
Ast.OpMult, "op_Multiply";
Ast.OpDiv, "op_Division";
Ast.OpMod, "op_Modulus";
Ast.OpXor, "op_ExclusiveOr";
Ast.OpOr, "op_BitwiseOr";
Ast.OpAnd, "op_BitwiseAnd";
Ast.OpBoolAnd, "op_LogicalAnd";
Ast.OpBoolOr, "op_LogicalOr";
Ast.OpAssign, "op_Assign";
Ast.OpShl, "op_LeftShift";
Ast.OpShr, "op_RightShift";
Ast.OpShr, "op_SignedRightShift";
Ast.OpUShr, "op_UnsignedRightShift";
Ast.OpEq, "op_Equality";
Ast.OpGt, "op_GreaterThan";
Ast.OpLt, "op_LessThan";
Ast.OpNotEq, "op_Inequality";
Ast.OpGte, "op_GreaterThanOrEqual";
Ast.OpLte, "op_LessThanOrEqual";
Ast.OpAssignOp Ast.OpMult, "op_MultiplicationAssignment";
Ast.OpAssignOp Ast.OpSub, "op_SubtractionAssignment";
Ast.OpAssignOp Ast.OpXor, "op_ExclusiveOrAssignment";
Ast.OpAssignOp Ast.OpShl, "op_LeftShiftAssignment";
Ast.OpAssignOp Ast.OpMod, "op_ModulusAssignment";
Ast.OpAssignOp Ast.OpAdd, "op_AdditionAssignment";
Ast.OpAssignOp Ast.OpAnd, "op_BitwiseAndAssignment";
Ast.OpAssignOp Ast.OpOr, "op_BitwiseOrAssignment";
(* op_Comma *)
Ast.OpAssignOp Ast.OpDiv, "op_DivisionAssignment";]
let cs_unops =
[Ast.Decrement, "op_Decrement";
Ast.Increment, "op_Increment";
Ast.Not, "op_UnaryNegation";
Ast.Neg, "op_UnaryMinus";
Ast.NegBits, "op_OnesComplement"]
let binops_names = List.fold_left (fun acc (op,n) -> PMap.add n op acc) PMap.empty cs_binops
let unops_names = List.fold_left (fun acc (op,n) -> PMap.add n op acc) PMap.empty cs_unops
let get_item = "get_Item"
let set_item = "set_Item"
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") }, [] )
| TAbstract ({ a_path = ([], "Int") },[])
| TInst( { cl_path = ([], "Float") }, [] )
| TAbstract ({ a_path = ([], "Float") },[]) ->
true
| TAbstract _ when like_float t ->
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
(* ******************************************* *)
(* CSharpSpecificESynf *)
(* ******************************************* *)
(*
Some CSharp-specific syntax filters that must run before ExpressionUnwrap
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 CSharpSpecificESynf =
struct
let name = "csharp_specific_e"
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 get_ab_from_t t =
match follow t with
| TAbstract(ab,_) -> ab
| _ -> assert false
let traverse gen runtime_cl =
let basic = gen.gcon.basic in
let uint = match get_type gen ([], "UInt") with | TTypeDecl t -> TType(t, []) | TAbstractDecl a -> TAbstract(a, []) | _ -> assert false in
let is_var = alloc_var "__is__" t_dynamic in
let rec run e =
match e.eexpr with
(* Std.is() *)
| TCall(
{ eexpr = TField( _, FStatic({ cl_path = ([], "Std") }, { cf_name = "is" })) },
[ obj; { eexpr = TTypeExpr(TClassDecl { cl_path = [], "Dynamic" } | TAbstractDecl { a_path = [], "Dynamic" }) }]
) ->
Type.map_expr run e
| TCall(
{ eexpr = TField( _, FStatic({ cl_path = ([], "Std") }, { cf_name = "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 mk_or a b =
{
eexpr = TBinop(Ast.OpBoolOr, a, b);
etype = basic.tbool;
epos = e.epos
}
in
let wrap_if_needed obj f =
(* introduce temp variable for complex expressions *)
match obj.eexpr with
| TLocal(v) -> f obj
| _ ->
let var = mk_temp gen "is" obj.etype in
let added = { obj with eexpr = TVar(var, Some(obj)); etype = basic.tvoid } in
let local = mk_local var obj.epos in
{
eexpr = TBlock([ added; f local ]);
etype = basic.tbool;
epos = e.epos
}
in
let obj = run obj in
(match follow_module follow md with
| TAbstractDecl{ a_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 =
(* we check if it float or int or uint *)
let eisint = mk_is local (TAbstractDecl (get_ab_from_t basic.tint)) in
let eisuint = mk_is local (TAbstractDecl (get_ab_from_t uint)) in
let eisfloat = mk_is local md in
mk_paren (mk_or eisfloat (mk_or eisint eisuint))
in
wrap_if_needed obj mk_is
| TAbstractDecl{ a_path = ([], "Int") } ->
(* int can be stored in double variable because of anonymous functions, check that case *)
let mk_isint_call local =
{
eexpr = TCall(
mk_static_field_access_infer runtime_cl "isInt" e.epos [],
[ local ]
);
etype = basic.tbool;
epos = e.epos
}
in
let mk_is local =
let eisint = mk_is local (TAbstractDecl (get_ab_from_t basic.tint)) in
let eisuint = mk_is local (TAbstractDecl (get_ab_from_t uint)) in
mk_paren (mk_or (mk_or eisint eisuint) (mk_isint_call local))
in
wrap_if_needed obj mk_is
| TAbstractDecl{ a_path = ([], "UInt") } ->
(* uint can be stored in double variable because of anonymous functions, check that case *)
let mk_isuint_call local =
{
eexpr = TCall(
mk_static_field_access_infer runtime_cl "isUInt" e.epos [],
[ local ]
);
etype = basic.tbool;
epos = e.epos
}
in
let mk_is local =
let eisuint = mk_is local (TAbstractDecl (get_ab_from_t uint)) in
mk_paren (mk_or eisuint (mk_isuint_call local))
in
wrap_if_needed obj mk_is
| _ ->
mk_is obj md
)
(* end Std.is() *)
| TBinop( Ast.OpUShr, e1, e2 ) ->
mk_cast e.etype { e with eexpr = TBinop( Ast.OpShr, mk_cast 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 = TVar(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
| _ -> 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;;
(* ******************************************* *)
(* CSharpSpecificSynf *)
(* ******************************************* *)
(*
Some CSharp-specific syntax filters that can run after ExprUnwrap
dependencies:
Runs after ExprUnwrap
*)
module CSharpSpecificSynf =
struct
let name = "csharp_specific"
let priority = solve_deps name [ DAfter ExpressionUnwrap.priority; DAfter ObjectDeclMap.priority; DAfter ArrayDeclSynf.priority; DAfter HardNullableSynf.priority ]
let get_cl_from_t t =
match follow t with
| TInst(cl,_) -> cl
| _ -> assert false
let is_tparam t =
match follow t with
| TInst( { cl_kind = KTypeParameter _ }, _ ) -> true
| _ -> false
let traverse gen runtime_cl =
let basic = gen.gcon.basic in
let tchar = match ( get_type gen (["cs"], "Char16") ) with
| TTypeDecl t -> TType(t,[])
| TAbstractDecl a -> TAbstract(a,[])
| _ -> assert false
in
let string_ext = get_cl ( get_type gen (["haxe";"lang"], "StringExt")) 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 Meta.has Meta.Struct cl.cl_meta -> true
| _ -> false
in
let is_cl t = match gen.greal_type t with | TInst ( { cl_path = (["System"], "Type") }, [] ) -> true | _ -> false in
let rec run e =
match e.eexpr with
(* Std.int() *)
| TCall(
{ eexpr = TField( _, FStatic({ cl_path = ([], "Std") }, { cf_name = "int" }) ) },
[obj]
) ->
run (mk_cast basic.tint obj)
(* end Std.int() *)
(* TODO: change cf_name *)
| TField(ef, FInstance({ cl_path = [], "String" }, { cf_name = "length" })) ->
{ e with eexpr = TField(run ef, FDynamic "Length") }
| TField(ef, FInstance({ cl_path = [], "String" }, { cf_name = "toLowerCase" })) ->
{ e with eexpr = TField(run ef, FDynamic "ToLower") }
| TField(ef, FInstance({ cl_path = [], "String" }, { cf_name = "toUpperCase" })) ->
{ e with eexpr = TField(run ef, FDynamic "ToUpper") }
| TCall( { eexpr = TField(_, FStatic({ cl_path = [], "String" }, { cf_name = "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(ef, FInstance({ cl_path = [], "String" }, { cf_name = ("charAt" as field) })) }, args )
| TCall( { eexpr = TField(ef, FInstance({ cl_path = [], "String" }, { cf_name = ("charCodeAt" as field) })) }, args )
| TCall( { eexpr = TField(ef, FInstance({ cl_path = [], "String" }, { cf_name = ("indexOf" as field) })) }, args )
| TCall( { eexpr = TField(ef, FInstance({ cl_path = [], "String" }, { cf_name = ("lastIndexOf" as field) })) }, args )
| TCall( { eexpr = TField(ef, FInstance({ cl_path = [], "String" }, { cf_name = ("split" as field) })) }, args )
| TCall( { eexpr = TField(ef, FInstance({ cl_path = [], "String" }, { cf_name = ("substring" as field) })) }, args )
| TCall( { eexpr = TField(ef, FInstance({ cl_path = [], "String" }, { cf_name = ("substr" as field) })) }, args ) ->
{ e with eexpr = TCall(mk_static_field_access_infer string_ext field e.epos [], [run ef] @ (List.map run args)) }
| TCall( { eexpr = TField(ef, FInstance({ cl_path = [], "String" }, { cf_name = ("toString" as field) })) }, [] ) ->
run ef
| TNew( { cl_path = ([], "String") }, [], [p] ) -> run p (* new String(myString) -> myString *)
| 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 = if like_int e.etype then "toInt" else "toDouble" 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( mk_static_field_access_infer runtime_cl "toString" expr.epos [], [run expr] ) }
| 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, FDynamic "Equals");
etype = TFun(["obj1",false,basic.tstring; "obj2",false,basic.tstring], basic.tbool);
epos = e1.epos
}, [ run e1; run e2 ])
}
| TCast(expr, _) when is_tparam e.etype ->
let static = mk_static_field_access_infer (runtime_cl) "genericCast" e.epos [e.etype] in
{ e with eexpr = TCall(static, [mk_local (alloc_var "$type_param" e.etype) expr.epos; run expr]); }
| 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, FDynamic "Equals");
etype = TFun(["obj1",false,t_dynamic;], basic.tbool);
epos = e1.epos
}, [ run e2 ])
}
| TBinop ( (Ast.OpEq as op), e1, e2 )
| TBinop ( (Ast.OpNotEq as op), e1, e2 ) when is_cl e1.etype ->
let static = mk_static_field_access_infer (runtime_cl) "typeEq" e.epos [] in
let ret = { e with eexpr = TCall(static, [run e1; run e2]); } in
if op = Ast.OpNotEq then
{ ret with eexpr = TUnop(Ast.Not, Ast.Prefix, ret) }
else
ret
| _ -> 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 base_generic =
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 = mk_field_access gen e "Length" e.epos in
let obj_v = mk_temp gen "obj" t_dynamic in
let block = [
{
eexpr = TVar(
new_v, Some( {
eexpr = TNew(native_arr_cl, [new_param], [old_len] );
etype = to_t;
epos = e.epos
} )
);
etype = basic.tvoid;
epos = e.epos
};
{
eexpr = TVar(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 = TVar(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 base_generic
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 } )
let rec get_class_modifiers meta cl_type cl_access cl_modifiers =
match meta with
| [] -> cl_type,cl_access,cl_modifiers
| (Meta.Struct,[],_) :: meta -> get_class_modifiers meta "struct" cl_access cl_modifiers
| (Meta.Protected,[],_) :: meta -> get_class_modifiers meta cl_type "protected" cl_modifiers
| (Meta.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 *)
| (Meta.Final,[],_) :: meta -> get_class_modifiers meta cl_type cl_access ("sealed" :: cl_modifiers)
| (Meta.Unsafe,[],_) :: meta -> get_class_modifiers meta cl_type cl_access ("unsafe" :: 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
| (Meta.Protected,[],_) :: meta -> get_fun_modifiers meta "protected" modifiers
| (Meta.Internal,[],_) :: meta -> get_fun_modifiers meta "internal" modifiers
| (Meta.ReadOnly,[],_) :: meta -> get_fun_modifiers meta access ("readonly" :: modifiers)
| (Meta.Unsafe,[],_) :: meta -> get_fun_modifiers meta access ("unsafe" :: modifiers)
| (Meta.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 (get_type gen (["haxe";"lang"],"Function")) in
let null_t = (get_cl (get_type gen (["haxe";"lang"],"Null")) ) in
let runtime_cl = get_cl (get_type gen (["haxe";"lang"],"Runtime")) in
let no_root = Common.defined gen.gcon Define.NoRoot in
let change_clname n = n in
let change_id name = try
Hashtbl.find reserved name
with | Not_found ->
if String.starts_with name "get_" || String.starts_with name "set_" then
"_" ^ name
else
name
in
let change_ns md = if no_root then
function
| [] when is_hxgen md -> ["haxe";"root"]
| ns -> List.map change_id ns
else List.map change_id 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") }, [])
| TAbstract ({ a_path = ([], "Bool") },[])
| TEnum ({ e_path = ([], "Void") }, [])
| TAbstract ({ a_path = ([], "Void") },[])
| TInst ({ cl_path = ([],"Float") },[])
| TAbstract ({ a_path = ([],"Float") },[])
| TInst ({ cl_path = ([],"Int") },[])
| TAbstract ({ a_path = ([],"Int") },[])
| TType ({ t_path = [],"UInt" },[])
| TAbstract ({ a_path = [],"UInt" },[])
| TType ({ t_path = ["haxe";"_Int64"], "NativeInt64" },[])
| TAbstract ({ a_path = ["haxe";"_Int64"], "NativeInt64" },[])
| TType ({ t_path = ["haxe";"_Int64"], "NativeUInt64" },[])
| TAbstract ({ a_path = ["haxe";"_Int64"], "NativeUInt64" },[])
| TType ({ t_path = ["cs"],"UInt64" },[])
| TAbstract ({ a_path = ["cs"],"UInt64" },[])
| TType ({ t_path = ["cs"],"UInt8" },[])
| TAbstract ({ a_path = ["cs"],"UInt8" },[])
| TType ({ t_path = ["cs"],"Int8" },[])
| TAbstract ({ a_path = ["cs"],"Int8" },[])
| TType ({ t_path = ["cs"],"Int16" },[])
| TAbstract ({ a_path = ["cs"],"Int16" },[])
| TType ({ t_path = ["cs"],"UInt16" },[])
| TAbstract ({ a_path = ["cs"],"UInt16" },[])
| TType ({ t_path = ["cs"],"Char16" },[])
| TAbstract ({ a_path = ["cs"],"Char16" },[])
| TType ({ t_path = ["cs"],"Ref" },_)
| TAbstract ({ a_path = ["cs"],"Ref" },_)
| TType ({ t_path = ["cs"],"Out" },_)
| TAbstract ({ a_path = ["cs"],"Out" },_)
| TType ({ t_path = [],"Single" },[])
| TAbstract ({ a_path = [],"Single" },[]) -> Some t
| TType ({ t_path = [],"Null" },[_]) -> Some t
| TAbstract ({ a_impl = Some _ } as a, pl) ->
Some (gen.gfollow#run_f ( Codegen.Abstract.get_underlying_type a pl) )
| TAbstract( { a_path = ([], "EnumValue") }, _ )
| TInst( { cl_path = ([], "EnumValue") }, _ ) -> Some t_dynamic
| _ -> None);
let module_s md =
let path = (t_infos md).mt_path in
match path with
| ([], "String") -> "string"
| ([], "Null") -> path_s (change_ns md ["haxe"; "lang"], change_clname "Null")
| (ns,clname) -> path_s (change_ns md ns, change_clname clname)
in
let ifaces = Hashtbl.create 1 in
let ti64 = match ( get_type gen (["haxe";"_Int64"], "NativeInt64") ) with | TTypeDecl t -> TType(t,[]) | TAbstractDecl a -> TAbstract(a,[]) | _ -> assert false in
let ttype = get_cl ( get_type gen (["System"], "Type") ) in
let has_tdyn tl =
List.exists (fun t -> match follow t with
| TDynamic _ | TMono _ -> true
| _ -> false
) tl
in
let rec real_type t =
let t = gen.gfollow#run_f t in
let ret = match t with
| TAbstract ({ a_impl = Some _ } as a, pl) ->
real_type (Codegen.Abstract.get_underlying_type a pl)
| TInst( { cl_path = (["haxe"], "Int32") }, [] ) -> gen.gcon.basic.tint
| TInst( { cl_path = (["haxe"], "Int64") }, [] ) -> ti64
| TAbstract( { a_path = [],"Class" }, _ )
| TAbstract( { a_path = [],"Enum" }, _ )
| TInst( { cl_path = ([], "Class") }, _ )
| TInst( { cl_path = ([], "Enum") }, _ ) -> TInst(ttype,[])
| TEnum(_, [])
| TInst(_, []) -> t
| TInst(cl, params) when
has_tdyn params &&
Hashtbl.mem ifaces cl.cl_path ->
TInst(Hashtbl.find ifaces cl.cl_path, [])
| TEnum(e, params) ->
TEnum(e, List.map (fun _ -> t_dynamic) params)
| TInst(cl, params) when Meta.has Meta.Enum cl.cl_meta ->
TInst(cl, List.map (fun _ -> t_dynamic) params)
| TInst(cl, params) -> TInst(cl, change_param_type (TClassDecl cl) 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)
| TAbstract _
| TType _ -> t
| TAnon (anon) when (match !(anon.a_status) with | Statics _ | EnumStatics _ | AbstractStatics _ -> true | _ -> false) -> t
| TFun _ -> TInst(fn_cl,[])
| _ -> t_dynamic
in
ret
and
(*
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<{}>
*)
change_param_type md tl =
let is_hxgeneric = (TypeParams.RealTypeParams.is_hxgeneric md) in
let ret t = match is_hxgeneric, real_type t with
| false, _ -> t
(*
Because Null<> types need a special compiler treatment for many operations (e.g. boxing/unboxing),
Null<> type parameters will be transformed into Dynamic.
*)
| true, TInst ( { cl_path = (["haxe";"lang"], "Null") }, _ ) -> dynamic_anon
| true, TInst ( { cl_kind = KTypeParameter _ }, _ ) -> t
| true, TInst _
| true, TEnum _
| true, TAbstract _ 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
in
let is_dynamic t = match real_type t with
| TMono _ | TDynamic _
| TInst({ cl_kind = KTypeParameter _ }, _) -> 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") }, [])
| TAbstract ({ a_path = ([], "Bool") },[]) -> "bool"
| TEnum ({ e_path = ([], "Void") }, [])
| TAbstract ({ a_path = ([], "Void") },[]) -> "object"
| TInst ({ cl_path = ([],"Float") },[])
| TAbstract ({ a_path = ([],"Float") },[]) -> "double"
| TInst ({ cl_path = ([],"Int") },[])
| TAbstract ({ a_path = ([],"Int") },[]) -> "int"
| TType ({ t_path = [],"UInt" },[])
| TAbstract ({ a_path = [],"UInt" },[]) -> "uint"
| TType ({ t_path = ["haxe";"_Int64"], "NativeInt64" },[])
| TAbstract ({ a_path = ["haxe";"_Int64"], "NativeInt64" },[]) -> "long"
| TType ({ t_path = ["haxe";"_Int64"], "NativeUInt64" },[])
| TAbstract ({ a_path = ["haxe";"_Int64"], "NativeUInt64" },[]) -> "ulong"
| TType ({ t_path = ["cs"],"UInt64" },[])
| TAbstract ({ a_path = ["cs"],"UInt64" },[]) -> "ulong"
| TType ({ t_path = ["cs"],"UInt8" },[])
| TAbstract ({ a_path = ["cs"],"UInt8" },[]) -> "byte"
| TType ({ t_path = ["cs"],"Int8" },[])
| TAbstract ({ a_path = ["cs"],"Int8" },[]) -> "sbyte"
| TType ({ t_path = ["cs"],"Int16" },[])
| TAbstract ({ a_path = ["cs"],"Int16" },[]) -> "short"
| TType ({ t_path = ["cs"],"UInt16" },[])
| TAbstract ({ a_path = ["cs"],"UInt16" },[]) -> "ushort"
| TType ({ t_path = ["cs"],"Char16" },[])
| TAbstract ({ a_path = ["cs"],"Char16" },[]) -> "char"
| TType ({ t_path = [],"Single" },[])
| TAbstract ({ a_path = [],"Single" },[]) -> "float"
| TInst ({ cl_path = ["haxe"],"Int32" },[])
| TAbstract ({ a_path = ["haxe"],"Int32" },[]) -> "int"
| TInst ({ cl_path = ["haxe"],"Int64" },[])
| TAbstract ({ a_path = ["haxe"],"Int64" },[]) -> "long"
| TInst ({ cl_path = ([], "Dynamic") },_)
| TAbstract ({ a_path = ([], "Dynamic") },_) -> "object"
| TType ({ t_path = ["cs"],"Out" },[t])
| TAbstract ({ a_path = ["cs"],"Out" },[t])
| TType ({ t_path = ["cs"],"Ref" },[t])
| TAbstract ({ a_path = ["cs"],"Ref" },[t]) -> t_s t
| 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) ^ "[]"
| TInst({ cl_path = (["cs"], "Pointer") },[t])
| TAbstract({ a_path = (["cs"], "Pointer") },[t])->
t_s t ^ "*"
(* 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"
| TEnum (e, params) -> ("global::" ^ (module_s (TEnumDecl e)))
| TInst (cl, _ :: _) when Meta.has Meta.Enum cl.cl_meta ->
"global::" ^ module_s (TClassDecl cl)
| 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 _ -> "System.Type"
| _ -> "object")
| TDynamic _ -> "object"
| TAbstract(a,pl) when a.a_impl <> None ->
t_s (Codegen.Abstract.get_underlying_type a pl)
(* 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
| [] -> "global::" ^ module_s md
| _ -> sprintf "%s<%s>" ("global::" ^ module_s md) (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")}, [])
| TAbstract ({ a_path = ([], "Void") },[]) -> "void"
| _ -> t_s t
in
let argt_s t =
match t with
| TType ({ t_path = (["cs"], "Ref") }, [t])
| TAbstract ({ a_path = (["cs"], "Ref") },[t]) -> "ref " ^ t_s t
| TType ({ t_path = (["cs"], "Out") }, [t])
| TAbstract ({ a_path = (["cs"], "Out") },[t]) -> "out " ^ t_s t
| _ -> t_s t
in
let escape ichar b =
match ichar with
| 92 (* \ *) -> Buffer.add_string b "\\\\"
| 39 (* ' *) -> Buffer.add_string b "\\\'"
| 34 -> Buffer.add_string b "\\\""
| 13 (* \r *) -> Buffer.add_string b "\\r"
| 10 (* \n *) -> Buffer.add_string b "\\n"
| 9 (* \t *) -> Buffer.add_string b "\\t"
| c when c < 32 || (c >= 127 && c <= 0xFFFF) -> Buffer.add_string b (Printf.sprintf "\\u%.4x" c)
| c when c > 0xFFFF -> Buffer.add_string b (Printf.sprintf "\\U%.8x" c)
| c -> Buffer.add_char b (Char.chr c)
in
let escape s =
let b = Buffer.create 0 in
(try
UTF8.validate s;
UTF8.iter (fun c -> escape (UChar.code c) b) s
with
UTF8.Malformed_code ->
String.iter (fun c -> escape (Char.code c) b) s
);
Buffer.contents b
in
let has_semicolon e =
match e.eexpr with
| TBlock _ | TFor _ | TSwitch _ | TPatMatch _ | 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))
| TAbstractDecl a ->
t_s (TAbstract(a, List.map(fun t -> t_dynamic) a.a_types))
in
let rec ensure_local e explain =
match e.eexpr with
| TLocal _ -> e
| TCast(e,_)
| TParenthesis e | TMeta(_,e) -> ensure_local e explain
| _ -> gen.gcon.error ("This function argument " ^ explain ^ " must be a local variable.") e.epos; e
in
let is_pointer t = match follow t with
| TInst({ cl_path = (["cs"], "Pointer") }, _)
| TAbstract ({ a_path = (["cs"], "Pointer") },_) ->
true
| _ ->
false in
let last_line = ref (-1) in
let line_directive =
if Common.defined gen.gcon Define.RealPosition then
fun w p -> ()
else fun w 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 Common.get_full_path 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
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 is_extern_prop t name = match field_access gen t name with
| FClassField(_,_,decl,v,_,t,_) ->
Type.is_extern_field v && decl.cl_extern && not (is_hxgen (TClassDecl decl))
| _ -> false
in
let expr_s w e =
last_line := -1;
in_value := false;
let rec expr_s w e =
let was_in_value = !in_value in
in_value := true;
(match e.eexpr with
| TCall( ({ eexpr = TField(ef,f) } as e), [] ) when String.starts_with (field_name f) "get_" ->
let name = field_name f in
let propname = String.sub name 4 (String.length name - 4) in
if is_extern_prop (gen.greal_type ef.etype) propname then begin
expr_s w ef;
write w ".";
write_field w propname
end else
do_call w e []