forked from HaxeFoundation/haxe
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gencpp.ml
3744 lines (3309 loc) · 138 KB
/
gencpp.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 Ast
open Type
open Common
let unsupported p = error "This expression cannot be generated to Cpp" p
(*
Code for generating source files.
It manages creating diretories, indents, blocks and only modifying files
when the content changes.
*)
(*
A class_path is made from a package (array of strings) and a class name.
Join these together, inclding a separator. eg, "/" for includes : pack1/pack2/Name or "::"
for namespace "pack1::pack2::Name"
*)
let join_class_path path separator =
let result = match fst path, snd path with
| [], s -> s
| el, s -> String.concat separator el ^ separator ^ s in
if (String.contains result '+') then begin
let idx = String.index result '+' in
(String.sub result 0 idx) ^ (String.sub result (idx+1) ((String.length result) - idx -1 ) )
end else
result;;
class source_writer write_func close_func=
object(this)
val indent_str = "\t"
val mutable indent = ""
val mutable indents = []
val mutable just_finished_block = false
method close = close_func(); ()
method write x = write_func x; just_finished_block <- false
method indent_one = this#write indent_str
method push_indent = indents <- indent_str::indents; indent <- String.concat "" indents
method pop_indent = match indents with
| h::tail -> indents <- tail; indent <- String.concat "" indents
| [] -> indent <- "/*?*/";
method write_i x = this#write (indent ^ x)
method get_indent = indent
method begin_block = this#write ("{\n"); this#push_indent
method end_block = this#pop_indent; this#write_i "}\n"; just_finished_block <- true
method end_block_line = this#pop_indent; this#write_i "}"; just_finished_block <- true
method terminate_line = this#write (if just_finished_block then "" else ";\n")
method add_include class_path =
this#write ("#ifndef INCLUDED_" ^ (join_class_path class_path "_") ^ "\n");
this#write ("#include <" ^ (join_class_path class_path "/") ^ ".h>\n");
this#write ("#endif\n")
end;;
let file_source_writer filename =
let out_file = open_out filename in
new source_writer (output_string out_file) (fun ()-> close_out out_file);;
let read_whole_file chan =
Std.input_all chan;;
(* The cached_source_writer will not write to the file if it has not changed,
thus allowing the makefile dependencies to work correctly *)
let cached_source_writer filename =
try
let in_file = open_in filename in
let old_contents = read_whole_file in_file in
close_in in_file;
let buffer = Buffer.create 0 in
let add_buf str = Buffer.add_string buffer str in
let close = fun () ->
let contents = Buffer.contents buffer in
if (not (contents=old_contents) ) then begin
let out_file = open_out filename in
output_string out_file contents;
close_out out_file;
end;
in
new source_writer (add_buf) (close);
with _ ->
file_source_writer filename;;
let rec make_class_directories base dir_list =
( match dir_list with
| [] -> ()
| dir :: remaining ->
let path = match base with
| "" -> dir
| "/" -> "/" ^ dir
| _ -> base ^ "/" ^ dir in
if ( not ( (path="") ||
( ((String.length path)=2) && ((String.sub path 1 1)=":") ) ) ) then
if not (Sys.file_exists path) then
Unix.mkdir path 0o755;
make_class_directories (if (path="") then "/" else path) remaining
);;
let new_source_file base_dir sub_dir extension class_path =
make_class_directories base_dir ( sub_dir :: (fst class_path));
cached_source_writer
( base_dir ^ "/" ^ sub_dir ^ "/" ^ ( String.concat "/" (fst class_path) ) ^ "/" ^
(snd class_path) ^ extension);;
let new_cpp_file base_dir = new_source_file base_dir "src" ".cpp";;
let new_header_file base_dir = new_source_file base_dir "include" ".h";;
let make_base_directory file =
make_class_directories "" ( ( Str.split_delim (Str.regexp "[\\/]+") file ) );
(* CPP code generation context *)
type context =
{
mutable ctx_common : Common.context;
mutable ctx_output : string -> unit;
mutable ctx_dbgout : string -> unit;
mutable ctx_writer : source_writer;
mutable ctx_calling : bool;
mutable ctx_assigning : bool;
mutable ctx_return_from_block : bool;
mutable ctx_tcall_expand_args : bool;
(* This is for returning from the child nodes of TMatch, TSwitch && TTry *)
mutable ctx_return_from_internal_node : bool;
mutable ctx_debug : bool;
mutable ctx_debug_type : bool;
mutable ctx_real_this_ptr : bool;
mutable ctx_dynamic_this_ptr : bool;
mutable ctx_dump_src_pos : unit -> unit;
mutable ctx_dump_stack_line : bool;
mutable ctx_static_id_curr : int;
mutable ctx_static_id_used : int;
mutable ctx_static_id_depth : int;
mutable ctx_switch_id : int;
mutable ctx_class_name : string;
mutable ctx_class_super_name : string;
mutable ctx_local_function_args : (string,string) Hashtbl.t;
mutable ctx_local_return_block_args : (string,string) Hashtbl.t;
mutable ctx_class_member_types : (string,string) Hashtbl.t;
mutable ctx_file_info : (string,string) PMap.t ref;
mutable ctx_for_extern : bool;
}
let new_context common_ctx writer debug file_info =
{
ctx_common = common_ctx;
ctx_writer = writer;
ctx_output = (writer#write);
ctx_dbgout = if debug then (writer#write) else (fun _ -> ());
ctx_calling = false;
ctx_assigning = false;
ctx_debug = debug;
ctx_debug_type = debug;
ctx_dump_src_pos = (fun() -> ());
ctx_dump_stack_line = true;
ctx_return_from_block = false;
ctx_tcall_expand_args = false;
ctx_return_from_internal_node = false;
ctx_real_this_ptr = true;
ctx_dynamic_this_ptr = false;
ctx_static_id_curr = 0;
ctx_static_id_used = 0;
ctx_static_id_depth = 0;
ctx_switch_id = 0;
ctx_class_name = "";
ctx_class_super_name = "";
ctx_local_function_args = Hashtbl.create 0;
ctx_local_return_block_args = Hashtbl.create 0;
ctx_class_member_types = Hashtbl.create 0;
ctx_file_info = file_info;
ctx_for_extern = false;
}
let new_extern_context common_ctx writer debug file_info =
let ctx = new_context common_ctx writer debug file_info in
ctx.ctx_for_extern <- true;
ctx
;;
(* The internal classes are implemented by the core hxcpp system, so the cpp
classes should not be generated *)
let is_internal_class = function
| ([],"Int") | ([],"Void") | ([],"String") | ([], "Null") | ([], "Float")
| ([],"Array") | ([], "Class") | ([], "Enum") | ([], "Bool")
| ([], "Dynamic") | ([], "ArrayAccess") | (["cpp"], "FastIterator")-> true
| (["cpp"], "CppInt32__") | ([],"Math") | (["haxe";"io"], "Unsigned_char__") -> true
| _ -> false
(* The internal header files are also defined in the hx/Object.h file, so you do
#include them separately. However, the Int32 and Math classes do have their
own header files (these are under the hxcpp tree) so these should be included *)
let include_class_header = function
| ([],"@Main") -> false
| (["cpp"], "CppInt32__") | ([],"Math") -> true
| path -> not ( is_internal_class path )
let is_cpp_class = function
| ("cpp"::_ , _) -> true
| ( [] , "Xml" ) -> true
| ( [] , "EReg" ) -> true
| ( ["haxe"] , "Log" ) -> true
| _ -> false;;
let is_scalar typename = match typename with
| "int" | "unsigned int" | "signed int"
| "char" | "unsigned char"
| "short" | "unsigned short"
| "float" | "double"
| "bool" -> true
| _ -> false
;;
let is_block exp = match exp.eexpr with | TBlock _ -> true | _ -> false ;;
let to_block expression =
if is_block expression then expression else (mk_block expression);;
(* todo - is this how it's done? *)
let hash_keys hash =
let key_list = ref [] in
Hashtbl.iter (fun key value -> key_list := key :: !key_list ) hash;
!key_list;;
let pmap_keys pmap =
let key_list = ref [] in
PMap.iter (fun key value -> key_list := key :: !key_list ) pmap;
!key_list;;
(* The Hashtbl structure seems a little odd - but here is a helper function *)
let hash_iterate hash visitor =
let result = ref [] in
Hashtbl.iter (fun key value -> result := (visitor key value) :: !result ) hash;
!result
(* Convert function names that can't be written in c++ ... *)
let keyword_remap name =
match name with
| "int"
| "auto" | "char" | "const" | "delete" | "double" | "Float" | "enum"
| "extern" | "float" | "friend" | "goto" | "long" | "operator" | "protected"
| "register" | "short" | "signed" | "sizeof" | "template" | "typedef"
| "union" | "unsigned" | "void" | "volatile" | "or" | "and" | "xor" | "or_eq" | "not"
| "and_eq" | "xor_eq" | "typeof" | "stdin" | "stdout" | "stderr"
| "BIG_ENDIAN" | "LITTLE_ENDIAN" | "assert" | "NULL" | "wchar_t" | "EOF"
| "bool" | "const_cast" | "dynamic_cast" | "explicit" | "export" | "mutable" | "namespace"
| "reinterpret_cast" | "static_cast" | "typeid" | "typename" | "virtual"
| "_Complex"
| "struct" -> "_" ^ name
| "asm" -> "_asm_"
| x -> x
;;
let remap_class_path class_path =
(List.map keyword_remap (fst class_path)) , (snd class_path)
;;
let join_class_path_remap path separator =
join_class_path (remap_class_path path) separator
;;
let get_meta_string meta key =
let rec loop = function
| [] -> ""
| (k,[Ast.EConst (Ast.String name),_],_) :: _ when k=key-> name
| _ :: l -> loop l
in
loop meta
;;
let has_meta_key meta key =
List.exists (fun m -> match m with | (k,_,_) when k=key-> true | _ -> false ) meta
;;
let get_code meta key =
let code = get_meta_string meta key in
if (code<>"") then code ^ "\n" else code
;;
(* Add include to source code *)
let add_include writer class_path =
writer#add_include class_path;;
(* This gets the class include order correct. In the header files, we forward declare
the class types so the header file does not have any undefined variables.
In the cpp files, we include all the required header files, providing the actual
types for everything. This way there is no problem with circular class references.
*)
let gen_forward_decl writer class_path =
if ( class_path = (["cpp"],"CppInt32__")) then
writer#add_include class_path
else begin
let output = writer#write in
let name = fst (remap_class_path class_path) in
output ("HX_DECLARE_CLASS" ^ (string_of_int (List.length name ) ) ^ "(");
List.iter (fun package_part -> output (package_part ^ ",") ) name;
output ( (snd class_path) ^ ")\n")
end;;
let real_interfaces =
List.filter (function (t,pl) ->
match t, pl with
| { cl_path = ["cpp";"rtti"],_ },[] -> false
| _ -> true
);;
let rec is_function_expr expr =
match expr.eexpr with
| TParenthesis expr -> is_function_expr expr
| TCast (e,None) -> is_function_expr e
| TFunction _ -> true
| _ -> false;;
let is_var_field field =
match field.cf_kind with
| Var _ -> true
| Method MethDynamic -> true
| _ -> false
;;
let rec has_rtti_interface c interface =
List.exists (function (t,pl) ->
(snd t.cl_path) = interface && (match fst t.cl_path with | ["cpp";"rtti"] -> true | _ -> false )
) c.cl_implements ||
(match c.cl_super with None -> false | Some (c,_) -> has_rtti_interface c interface);;
let has_field_integer_lookup class_def =
has_rtti_interface class_def "FieldIntegerLookup";;
let has_field_integer_numeric_lookup class_def =
has_rtti_interface class_def "FieldNumericIntegerLookup";;
(* Output required code to place contents in required namespace *)
let gen_open_namespace output class_path =
List.iter (fun namespace -> output ("namespace " ^ namespace ^ "{\n")) (List.map keyword_remap (fst class_path));;
let gen_close_namespace output class_path =
List.iter
(fun namespace -> output ( "}" ^ " // end namespace " ^ namespace ^"\n"))
(fst class_path);;
(* The basic types can have default values and are passesby value *)
let is_numeric = function
| "Int" | "Bool" | "Float" | "::haxe::io::Unsigned_char__" | "unsigned char" -> true
| "int" | "bool" | "double" | "float" -> true
| _ -> false
let cant_be_null type_string =
is_numeric type_string
;;
let is_object type_string =
not (is_numeric type_string || type_string="::String");
;;
(* Get a string to represent a type.
The "suffix" will be nothing or "_obj", depending if we want the name of the
pointer class or the pointee (_obj class *)
let rec class_string klass suffix params =
(match klass.cl_path with
(* Array class *)
| ([],"Array") when is_dynamic_array_param (List.hd params) -> "Dynamic"
| ([],"Array") -> (snd klass.cl_path) ^ suffix ^ "< " ^ (String.concat ","
(List.map array_element_type params) ) ^ " >"
(* FastIterator class *)
| (["cpp"],"FastIterator") -> "::cpp::FastIterator" ^ suffix ^ "< " ^ (String.concat ","
(List.map type_string params) ) ^ " >"
| _ when (match klass.cl_kind with KTypeParameter _ -> true | _ -> false) -> "Dynamic"
| ([],"#Int") -> "/* # */int"
| (["haxe";"io"],"Unsigned_char__") -> "unsigned char"
| ([],"Class") -> "::Class"
| ([],"EnumValue") -> "Dynamic"
| ([],"Null") -> (match params with
| [t] ->
(match follow t with
| TAbstract ({ a_path = [],"Int" },_)
| TAbstract ({ a_path = [],"Float" },_)
| TAbstract ({ a_path = [],"Bool" },_)
| TInst ({ cl_path = [],"Int" },_)
| TInst ({ cl_path = [],"Float" },_)
| TEnum ({ e_path = [],"Bool" },_) -> "Dynamic"
| _ -> "/*NULL*/" ^ (type_string t) )
| _ -> assert false);
(* Normal class *)
| path when klass.cl_extern && (not (is_internal_class path) )->
(join_class_path_remap klass.cl_path "::") ^ suffix
| _ -> "::" ^ (join_class_path_remap klass.cl_path "::") ^ suffix
)
and type_string_suff suffix haxe_type =
(match haxe_type with
| TMono r -> (match !r with None -> "Dynamic" ^ suffix | Some t -> type_string_suff suffix t)
| TAbstract ({ a_path = ([],"Void") },[]) -> "Void"
| TAbstract ({ a_path = ([],"Bool") },[]) -> "bool"
| TAbstract ({ a_path = ([],"Float") },[]) -> "Float"
| TAbstract ({ a_path = ([],"Int") },[]) -> "int"
| TAbstract( { a_path = ([], "EnumValue") }, _ ) -> "Dynamic"
| TEnum ({ e_path = ([],"Void") },[]) -> "Void"
| TEnum ({ e_path = ([],"Bool") },[]) -> "bool"
| TInst ({ cl_path = ([],"Float") },[]) -> "Float"
| TInst ({ cl_path = ([],"Int") },[]) -> "int"
| TEnum (enum,params) -> "::" ^ (join_class_path_remap enum.e_path "::") ^ suffix
| TInst (klass,params) -> (class_string klass suffix params)
| TType (type_def,params) ->
(match type_def.t_path with
| [] , "Null" ->
(match params with
| [t] ->
(match follow t with
| TAbstract ({ a_path = [],"Int" },_)
| TAbstract ({ a_path = [],"Float" },_)
| TAbstract ({ a_path = [],"Bool" },_)
| TInst ({ cl_path = [],"Int" },_)
| TInst ({ cl_path = [],"Float" },_)
| TEnum ({ e_path = [],"Bool" },_) -> "Dynamic" ^ suffix
| _ -> type_string_suff suffix t)
| _ -> assert false);
| [] , "Array" ->
(match params with
| [t] when (type_string (follow t)) = "Dynamic" -> "Dynamic"
| [t] -> "Array< " ^ (type_string (follow t) ) ^ " >"
| _ -> assert false)
| ["cpp"] , "FastIterator" ->
(match params with
| [t] -> "::cpp::FastIterator< " ^ (type_string (follow t) ) ^ " >"
| _ -> assert false)
| _ -> type_string_suff suffix (apply_params type_def.t_types params type_def.t_type)
)
| TFun (args,haxe_type) -> "Dynamic" ^ suffix
| TAnon a -> "Dynamic"
(*
(match !(a.a_status) with
| Statics c -> type_string_suff suffix (TInst (c,List.map snd c.cl_types))
| EnumStatics e -> type_string_suff suffix (TEnum (e,List.map snd e.e_types))
| _ -> "Dynamic" ^ suffix )
*)
| TDynamic haxe_type -> "Dynamic" ^ suffix
| TLazy func -> type_string_suff suffix ((!func)())
| TAbstract (abs,pl) when abs.a_impl <> None ->
type_string_suff suffix (Codegen.Abstract.get_underlying_type abs pl)
| TAbstract (abs,pl) ->
"::" ^ (join_class_path_remap abs.a_path "::") ^ suffix
)
and type_string haxe_type =
type_string_suff "" haxe_type
and array_element_type haxe_type =
match type_string haxe_type with
| x when cant_be_null x -> x
| "::String" -> "::String"
| _ -> "::Dynamic"
and is_dynamic_array_param haxe_type =
if (type_string (follow haxe_type)) = "Dynamic" then true
else (match follow haxe_type with
| TInst (klass,params) ->
(match klass.cl_path with
| ([],"Array") | ([],"Class") | (["cpp"],"FastIterator") -> false
| _ -> (match klass.cl_kind with KTypeParameter _ -> true | _ -> false)
)
| _ -> false
)
;;
let is_array haxe_type =
match follow haxe_type with
| TInst (klass,params) ->
(match klass.cl_path with
| [] , "Array" -> not (is_dynamic_array_param (List.hd params))
| _ -> false )
| TType (type_def,params) ->
(match type_def.t_path with
| [] , "Array" -> not (is_dynamic_array_param (List.hd params))
| _ -> false )
| _ -> false
;;
let is_array_implementer haxe_type =
match follow haxe_type with
| TInst (klass,params) ->
(match klass.cl_array_access with
| Some _ -> true
| _ -> false )
| _ -> false
;;
let is_numeric_field field =
match field.cf_kind with
| Var _ -> is_numeric (type_string field.cf_type)
| _ -> false;
;;
(* Get the type and output it to the stream *)
let gen_type ctx haxe_type =
ctx.ctx_output (type_string haxe_type)
;;
(* Get the type and output it to the stream *)
let gen_type_suff ctx haxe_type suff =
ctx.ctx_output (type_string_suff suff haxe_type);;
let member_type ctx field_object member =
let name = (if (is_array field_object.etype) then "::Array"
else (type_string field_object.etype)) ^ "." ^ member in
try ( Hashtbl.find ctx.ctx_class_member_types name )
with Not_found -> "?";;
let is_interface_type t =
match follow t with
| TInst (klass,params) -> klass.cl_interface
| _ -> false
;;
let is_interface obj = is_interface_type obj.etype;;
let should_implement_field x = not (is_extern_field x);;
let is_function_member expression =
match (follow expression.etype) with | TFun (_,_) -> true | _ -> false;;
let is_internal_member member =
match member with
| "__Field" | "__IField" | "__Run" | "__Is" | "__GetClass" | "__GetType" | "__ToString"
| "__s" | "__GetPtr" | "__SetField" | "__length" | "__IsArray" | "__SetThis" | "__Internal"
| "__EnumParams" | "__Index" | "__Tag" | "__GetFields" | "toString" | "__HasField"
-> true
| _ -> false;;
let rec is_dynamic_accessor name acc field class_def =
( ( acc ^ "_" ^ field.cf_name) = name ) &&
( not (List.exists (fun f -> f.cf_name=name) class_def.cl_ordered_fields) )
&& (match class_def.cl_super with None -> true | Some (parent,_) -> is_dynamic_accessor name acc field parent )
;;
let gen_arg_type_name name default_val arg_type prefix =
let remap_name = keyword_remap name in
let type_str = (type_string arg_type) in
match default_val with
| Some TNull -> (type_str,remap_name)
| Some constant when (cant_be_null type_str) -> ("hx::Null< " ^ type_str ^ " > ",prefix ^ remap_name)
| Some constant -> (type_str,prefix ^ remap_name)
| _ -> (type_str,remap_name);;
let gen_interface_arg_type_name name opt typ =
let type_str = (type_string typ) in
(if (opt && (cant_be_null type_str) ) then
"hx::Null< " ^ type_str ^ " > "
else
type_str )
^ " " ^ (keyword_remap name)
;;
let gen_tfun_interface_arg_list args =
String.concat "," (List.map (fun (name,opt,typ) -> gen_interface_arg_type_name name opt typ) args)
;;
(* Generate prototype text, including allowing default values to be null *)
let gen_arg name default_val arg_type prefix =
let pair = gen_arg_type_name name default_val arg_type prefix in
(fst pair) ^ " " ^ (snd pair);;
let rec gen_arg_list arg_list prefix =
String.concat "," (List.map (fun (v,o) -> (gen_arg v.v_name o v.v_type prefix) ) arg_list)
let rec gen_tfun_arg_list arg_list =
match arg_list with
| [] -> ""
| [(name,o,arg_type)] -> gen_arg name None arg_type ""
| (name,o,arg_type) :: remaining ->
(gen_arg name None arg_type "") ^ "," ^ (gen_tfun_arg_list remaining)
(* Check to see if we are the first object in the parent tree to implement a dynamic interface *)
let implement_dynamic_here class_def =
let implements_dynamic c = match c.cl_dynamic with None -> false | _ -> true in
let rec super_implements_dynamic c = match c.cl_super with
| None -> false
| Some (csup, _) -> if (implements_dynamic csup) then true else
super_implements_dynamic csup;
in
( (implements_dynamic class_def) && (not (super_implements_dynamic class_def) ) );;
(* Make string printable for c++ code *)
(* Here we know there are no utf8 characters, so use the L"" notation to avoid conversion *)
let escape_stringw s l =
let b = Buffer.create 0 in
Buffer.add_char b 'L';
Buffer.add_char b '"';
let skip = ref 0 in
for i = 0 to String.length s - 1 do
if (!skip>0) then begin
skip := !skip -1;
l := !l-1;
end else
match Char.code (String.unsafe_get s i) with
| c when (c>127) ->
let encoded = ((c land 0x3F) lsl 6) lor ( Char.code ((String.unsafe_get s (i+1))) land 0x7F) in
skip := 1;
Buffer.add_string b (Printf.sprintf "\\x%X\"L\"" encoded)
| c when (c < 32) -> Buffer.add_string b (Printf.sprintf "\\x%X\"L\"" c)
| c -> Buffer.add_char b (Char.chr c)
done;
Buffer.add_char b '"';
Buffer.contents b;;
let special_to_hex s =
let l = String.length s in
let b = Buffer.create 0 in
for i = 0 to l - 1 do
match Char.code (String.unsafe_get s i) with
| c when (c>127) || (c<32) ->
Buffer.add_string b (Printf.sprintf "\\x%02x\"\"" c)
| c -> Buffer.add_char b (Char.chr c)
done;
Buffer.contents b;;
let escape_extern s =
let l = String.length s in
let b = Buffer.create 0 in
for i = 0 to l - 1 do
match Char.code (String.unsafe_get s i) with
| c when (c>127) || (c<32) || (c=34) || (c=92) ->
Buffer.add_string b (Printf.sprintf "\\x%02x" c)
| c -> Buffer.add_char b (Char.chr c)
done;
Buffer.contents b;;
let has_utf8_chars s =
let result = ref false in
for i = 0 to String.length s - 1 do
result := !result || ( Char.code (String.unsafe_get s i) > 127 )
done;
!result;;
let escape_command s =
let b = Buffer.create 0 in
String.iter (fun ch -> if (ch=='"' || ch=='\\' ) then Buffer.add_string b "\\"; Buffer.add_char b ch ) s;
Buffer.contents b;;
let str s =
let escaped = Ast.s_escape s in
("HX_CSTRING(\"" ^ (special_to_hex escaped) ^ "\")")
;;
(* When we are in a "real" object, we refer to ourselves as "this", but
if we are in a local class that is used to generate return values,
we use the fake "__this" pointer.
If we are in an "Anon" object, then the "this" refers to the anon object (eg List iterator) *)
let clear_real_this_ptr ctx dynamic_this =
let old_flag = ctx.ctx_real_this_ptr in
let old_dynamic = ctx.ctx_dynamic_this_ptr in
ctx.ctx_real_this_ptr <- false;
ctx.ctx_dynamic_this_ptr <- dynamic_this;
fun () -> ( ctx.ctx_real_this_ptr <- old_flag; ctx.ctx_dynamic_this_ptr <- old_dynamic; );;
(* Generate temp variable names *)
let next_anon_function_name ctx =
ctx.ctx_static_id_curr <- ctx.ctx_static_id_curr + 1;
"_Function_" ^ (string_of_int ctx.ctx_static_id_depth) ^"_"^ (string_of_int ctx.ctx_static_id_curr);;
let use_anon_function_name ctx =
ctx.ctx_static_id_used <- ctx.ctx_static_id_used + 1;
"_Function_" ^ (string_of_int ctx.ctx_static_id_depth) ^"_"^ (string_of_int ctx.ctx_static_id_used);;
let push_anon_names ctx =
let old_used = ctx.ctx_static_id_used in
let old_curr = ctx.ctx_static_id_curr in
let old_depth = ctx.ctx_static_id_depth in
ctx.ctx_static_id_used <- 0;
ctx.ctx_static_id_curr <- 0;
ctx.ctx_static_id_depth <- ctx.ctx_static_id_depth + 1;
( function () -> (
ctx.ctx_static_id_used <- old_used;
ctx.ctx_static_id_curr <- old_curr;
ctx.ctx_static_id_depth <- old_depth; ) )
;;
let get_switch_var ctx =
ctx.ctx_switch_id <- ctx.ctx_switch_id + 1;
"_switch_" ^ (string_of_int ctx.ctx_switch_id)
(* If you put on the "-debug" flag, you get extra comments in the source code *)
let debug_expression expression type_too =
"/* " ^ Type.s_expr_kind expression ^ (if (type_too) then " = " ^ (type_string expression.etype) else "") ^ " */";;
(* This is like the Type.iter, but also keeps the "retval" flag up to date *)
let rec iter_retval f retval e =
match e.eexpr with
| TConst _
| TLocal _
| TBreak
| TContinue
| TTypeExpr _ ->
()
| TArray (e1,e2)
| TBinop (_,e1,e2) ->
f true e1;
f true e2;
| TWhile (e1,e2,_) ->
f true e1;
f false e2;
| TFor (_,e1,e2) ->
f true e1;
f false e2;
| TThrow e
| TField (e,_)
| TUnop (_,_,e) ->
f true e
| TParenthesis e ->
f retval e
| TBlock expr_list when retval ->
let rec return_last = function
| [] -> ()
| expr :: [] -> f true expr
| expr :: exprs -> f false expr; return_last exprs in
return_last expr_list
| TArrayDecl el
| TNew (_,_,el) ->
List.iter (f true ) el
| TBlock el ->
List.iter (f false ) el
| TObjectDecl fl ->
List.iter (fun (_,e) -> f true e) fl
| TCall (e,el) ->
f true e;
List.iter (f true) el
| TVars vl ->
List.iter (fun (_,e) -> match e with None -> () | Some e -> f true e) vl
| TFunction fu ->
f false fu.tf_expr
| TIf (e,e1,e2) ->
f true e;
f retval e1;
(match e2 with None -> () | Some e -> f retval e)
| TSwitch (e,cases,def) ->
f true e;
List.iter (fun (el,e2) -> List.iter (f true) el; f retval e2) cases;
(match def with None -> () | Some e -> f retval e)
| TMatch (e,_,cases,def) ->
f true e;
List.iter (fun (_,_,e) -> f false e) cases;
(match def with None -> () | Some e -> f false e)
| TTry (e,catches) ->
f retval e;
List.iter (fun (_,e) -> f false e) catches
| TReturn eo ->
(match eo with None -> () | Some e -> f true e)
| TCast (e,None) ->
f retval e
| TCast (e,_) ->
f true e
;;
(* Convert an array to a comma separated list of values *)
let array_arg_list inList =
let i = ref (0-1) in
String.concat "," (List.map (fun _ -> incr i; "inArgs[" ^ (string_of_int !i) ^ "]" ) inList)
let list_num l = string_of_int (List.length l);;
let only_int_cases cases =
match cases with
| [] -> false
| _ ->
not (List.exists (fun (cases,expression) ->
List.exists (fun case -> match case.eexpr with TConst (TInt _) -> false | _ -> true ) cases
) cases );;
(* See if there is a haxe break statement that will be swollowed by c++ break *)
exception BreakFound;;
let contains_break expression =
try (
let rec check_all expression =
Type.iter (fun expr -> match expr.eexpr with
| TBreak -> raise BreakFound
| TFor _
| TFunction _
| TWhile (_,_,_) -> ()
| _ -> check_all expr;
) expression in
check_all expression;
false;
) with BreakFound -> true;;
(* Decide is we should look the field up by name *)
let dynamic_internal = function | "__Is" -> true | _ -> false
(* Get a list of variables to extract from a enum tmatch *)
let tmatch_params_to_args params =
(match params with
| None | Some [] -> []
| Some l ->
let n = ref (-1) in
List.fold_left
(fun acc v -> incr n; match v with None -> acc | Some v -> (v.v_name,v.v_type,!n) :: acc) [] l)
let rec is_null expr =
match expr.eexpr with
| TConst TNull -> true
| TParenthesis expr -> is_null expr
| TCast (e,None) -> is_null e
| _ -> false
;;
let find_undeclared_variables_ctx ctx undeclared declarations this_suffix allow_this expression =
let output = ctx.ctx_output in
let rec find_undeclared_variables undeclared declarations this_suffix allow_this expression =
match expression.eexpr with
| TVars var_list ->
List.iter (fun (tvar, optional_init) ->
Hashtbl.add declarations (keyword_remap tvar.v_name) ();
if (ctx.ctx_debug) then
output ("/* found var " ^ tvar.v_name ^ "*/ ");
match optional_init with
| Some expression -> find_undeclared_variables undeclared declarations this_suffix allow_this expression
| _ -> ()
) var_list
| TFunction func -> List.iter ( fun (tvar, opt_val) ->
if (ctx.ctx_debug) then
output ("/* found arg " ^ tvar.v_name ^ " = " ^ (type_string tvar.v_type) ^ " */ ");
Hashtbl.add declarations (keyword_remap tvar.v_name) () ) func.tf_args;
find_undeclared_variables undeclared declarations this_suffix false func.tf_expr
| TTry (try_block,catches) ->
find_undeclared_variables undeclared declarations this_suffix allow_this try_block;
List.iter (fun (tvar,catch_expt) ->
let old_decs = Hashtbl.copy declarations in
Hashtbl.add declarations (keyword_remap tvar.v_name) ();
find_undeclared_variables undeclared declarations this_suffix allow_this catch_expt;
Hashtbl.clear declarations;
Hashtbl.iter ( Hashtbl.add declarations ) old_decs
) catches;
| TLocal tvar ->
let name = keyword_remap tvar.v_name in
if not (Hashtbl.mem declarations name) then
Hashtbl.replace undeclared name (type_string expression.etype)
| TMatch (condition, enum, cases, default) ->
find_undeclared_variables undeclared declarations this_suffix allow_this condition;
List.iter (fun (case_ids,params,expression) ->
let old_decs = Hashtbl.copy declarations in
(match params with
| None -> ()
| Some l -> List.iter (fun (opt_var) ->
match opt_var with | Some v -> Hashtbl.add declarations (keyword_remap v.v_name) () | _ -> () )
l );
find_undeclared_variables undeclared declarations this_suffix allow_this expression;
Hashtbl.clear declarations;
Hashtbl.iter ( Hashtbl.add declarations ) old_decs
) cases;
(match default with | None -> ()
| Some expr ->
find_undeclared_variables undeclared declarations this_suffix allow_this expr;
);
| TFor (tvar, init, loop) ->
let old_decs = Hashtbl.copy declarations in
Hashtbl.add declarations (keyword_remap tvar.v_name) ();
find_undeclared_variables undeclared declarations this_suffix allow_this init;
find_undeclared_variables undeclared declarations this_suffix allow_this loop;
Hashtbl.clear declarations;
Hashtbl.iter ( Hashtbl.add declarations ) old_decs
| TConst TSuper
| TConst TThis ->
if ((not (Hashtbl.mem declarations "this")) && allow_this) then
Hashtbl.replace undeclared "this" (type_string_suff this_suffix expression.etype)
| TBlock expr_list ->
let old_decs = Hashtbl.copy declarations in
List.iter (find_undeclared_variables undeclared declarations this_suffix allow_this ) expr_list;
(* what is the best way for this ? *)
Hashtbl.clear declarations;
Hashtbl.iter ( Hashtbl.add declarations ) old_decs
| _ -> Type.iter (find_undeclared_variables undeclared declarations this_suffix allow_this) expression
in
find_undeclared_variables undeclared declarations this_suffix allow_this expression
;;
let rec is_dynamic_in_cpp ctx expr =
let expr_type = type_string ( match follow expr.etype with TFun (args,ret) -> ret | _ -> expr.etype) in
ctx.ctx_dbgout ( "/* idic: " ^ expr_type ^ " */" );
if ( expr_type="Dynamic" ) then
true
else begin
let result = (
match expr.eexpr with
| TField( obj, field ) ->
let name = field_name field in
ctx.ctx_dbgout ("/* ?tfield "^name^" */");
if (is_dynamic_member_lookup_in_cpp ctx obj name) then
(
ctx.ctx_dbgout "/* tf=dynobj */";
true
)
else if (is_dynamic_member_return_in_cpp ctx obj name) then
(
ctx.ctx_dbgout "/* tf=dynret */";
true
)
else
(
ctx.ctx_dbgout "/* tf=notdyn */";
false
)
| TConst TThis when ((not ctx.ctx_real_this_ptr) && ctx.ctx_dynamic_this_ptr) ->
ctx.ctx_dbgout ("/* dthis */"); true
| TArray (obj,index) -> let dyn = is_dynamic_in_cpp ctx obj in
ctx.ctx_dbgout ("/* aidr:" ^ (if dyn then "Dyn" else "Not") ^ " */");
dyn;
| TTypeExpr _ -> false
| TCall(func,args) ->
(match follow func.etype with
| TFun (args,ret) -> ctx.ctx_dbgout ("/* ret = "^ (type_string ret) ^" */");
is_dynamic_in_cpp ctx func
| _ -> ctx.ctx_dbgout "/* not TFun */"; true
);
| TParenthesis(expr) -> is_dynamic_in_cpp ctx expr
| TCast (e,None) -> is_dynamic_in_cpp ctx e
| TLocal { v_name = "__global__" } -> false
| TConst TNull -> true
| _ -> ctx.ctx_dbgout "/* other */"; false (* others ? *) )
in
ctx.ctx_dbgout (if result then "/* Y */" else "/* N */" );
result
end
and is_dynamic_member_lookup_in_cpp ctx field_object member =
ctx.ctx_dbgout ("/*mem."^member^".*/");
if (is_internal_member member) then false else
if (match field_object.eexpr with | TTypeExpr _ -> ctx.ctx_dbgout "/*!TTypeExpr*/"; true | _ -> false) then false else
if (is_dynamic_in_cpp ctx field_object) then true else
if (is_array field_object.etype) then false else (
let tstr = type_string field_object.etype in
ctx.ctx_dbgout ("/* ts:"^tstr^"*/");
match tstr with
(* Internal classes have no dynamic members *)
| "::String" | "Null" | "::Class" | "::Enum" | "::Math" | "::ArrayAccess" -> ctx.ctx_dbgout ("/* ok:" ^ (type_string field_object.etype) ^ " */"); false
| "Dynamic" -> true
| name ->
let full_name = name ^ "." ^ member in
ctx.ctx_dbgout ("/* t:" ^ full_name ^ " */");
try ( let mem_type = (Hashtbl.find ctx.ctx_class_member_types full_name) in
ctx.ctx_dbgout ("/* =" ^ mem_type ^ "*/");