-
-
Notifications
You must be signed in to change notification settings - Fork 653
/
gencpp.ml
2667 lines (2349 loc) · 91.6 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
(*
* haXe/CPP Compiler
* Copyright (c)2008 Hugh Sanderson
* based on and including code by (c)2005-2008 Nicolas Cannasse
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*)
open Type
open Common
(*
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 = base ^ "/" ^ dir in
if not (Sys.file_exists path) then
Unix.mkdir path 0o755;
make_class_directories 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 "." (file :: []);;
(* CPP code generation context *)
type context =
{
mutable ctx_output : string -> unit;
mutable ctx_writer : source_writer;
mutable ctx_calling : bool;
mutable ctx_assigning : bool;
mutable ctx_return_from_block : 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_static_id_curr : int;
mutable ctx_static_id_used : int;
mutable ctx_switch_id : int;
mutable ctx_class_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;
}
let new_context writer debug =
{
ctx_writer = writer;
ctx_output = (writer#write);
ctx_calling = false;
ctx_assigning = false;
ctx_debug = debug;
ctx_debug_type = debug;
ctx_return_from_block = 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_switch_id = 0;
ctx_class_name = "";
ctx_local_function_args = Hashtbl.create 0;
ctx_local_return_block_args = Hashtbl.create 0;
ctx_class_member_types = Hashtbl.create 0;
}
(* 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") -> true
| (["cpp"], "CppInt32__") | ([],"Math") | (["haxe";"io"], "Unsigned_char__") -> true
| _ -> false
(* The internal header files are also defined in the hxObject.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 is_internal_header = function
| ([],"@Main") -> true
| (["cpp"], "CppInt32__") | ([],"Math") -> false
| path -> is_internal_class path
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 = function
| "int" -> "toInt"
| "or" -> "_or" (*problem with gcc *)
| "and" -> "_and" (*problem with gcc *)
| "xor" -> "_xor" (*problem with gcc *)
| "typeof" -> "_typeof"
| "float" -> "_float"
| "union" -> "_union"
| "template" -> "_template"
| "goto" -> "_goto"
| "stdin" -> "_stdin"
| "stdout" -> "_stdout"
| "stderr" -> "_stderr"
| "struct" -> "_struct"
| x -> x
(*
While #include "Math.h" sould be different from "#include <math.h>", and it may be possible
to use include paths to get this right, I think it is easier just to chnage the name *)
let include_remap = function | ([],"Math") -> ([],"hxMath") | x -> x;;
(* Add include to source code *)
let add_include writer class_path =
writer#add_include (include_remap 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
output ("DECLARE_CLASS" ^ (string_of_int (List.length (fst class_path) ) ) ^ "(");
List.iter (fun package_part -> output (package_part ^ ",") ) (fst class_path);
output ( (snd class_path) ^ ")\n")
end;;
(* Output required code to place contents in required namespace *)
let gen_open_namespace output class_path =
List.iter (fun namespace -> output ("namespace " ^ namespace ^ "{\n")) (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_basic_type = function
| "Int" | "Bool" | "Float" | "String" | "haxe::io::Unsigned_char__" -> true
| "int" | "bool" | "double" -> true
| _ -> false
(* 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") -> (snd klass.cl_path) ^ suffix ^ "<" ^ (String.concat ","
(List.map type_string params) ) ^ " >"
| _ when klass.cl_kind=KTypeParameter -> "Dynamic"
| ([],"#Int") -> "/* # */int"
| (["haxe";"io"],"Unsigned_char__") -> "unsigned char"
| ([],"Class") -> "Class"
| ([],"Null") -> (match params with
| [t] ->
(match follow t with
| TInst ({ cl_path = [],"Int" },_)
| TInst ({ cl_path = [],"Float" },_)
| TEnum ({ e_path = [],"Bool" },_) -> "Dynamic"
| _ -> "/*NULL*/" ^ (type_string t) )
| _ -> assert false);
(* Normal class *)
| _ -> (join_class_path klass.cl_path "::") ^ suffix
)
and type_string_suff suffix haxe_type =
(match haxe_type with
| TMono r -> (match !r with None -> "Dynamic" | Some t -> type_string_suff suffix t)
| TEnum ({ e_path = ([],"Void") },[]) -> "Void"
| TEnum ({ e_path = ([],"Bool") },[]) -> "bool"
| TInst ({ cl_path = ([],"Float") },[]) -> "double"
| TInst ({ cl_path = ([],"Int") },[]) -> "int"
| TEnum (enum,params) -> (join_class_path 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
| TInst ({ cl_path = [],"Int" },_)
| TInst ({ cl_path = [],"Float" },_)
| TEnum ({ e_path = [],"Bool" },_) -> "Dynamic"
| _ -> type_string_suff suffix t)
| _ -> assert false);
| [] , "Array" ->
(match params with
| [t] -> "Array<" ^ (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"
| TAnon anon -> "Dynamic"
| TDynamic haxe_type -> "Dynamic"
| TLazy func -> type_string_suff suffix ((!func)())
)
and type_string haxe_type =
type_string_suff "" haxe_type;;
let is_array haxe_type =
match follow haxe_type with
| TInst (klass,params) ->
(match klass.cl_path with
| [] , "Array" -> true
| _ -> false )
| TType (type_def,params) ->
(match type_def.t_path with
| [] , "Array" -> true
| _ -> false )
| _ -> false
;;
let is_dynamic haxe_type = type_string haxe_type ="Dynamic";;
(* 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 = (type_string field_object.etype) ^ "." ^ member in
try ( Hashtbl.find ctx.ctx_class_member_types name )
with Not_found -> "?";;
let is_interface obj =
match obj.etype with
| TInst (klass,params) -> klass.cl_interface
| _ -> false;;
let is_function_member expression =
match (follow expression.etype) with | TFun (_,_) -> true | _ -> false;;
(* Some fields of a dynamic object are internal and should be accessed directly,
rather than through the abstract interface. In haxe code, these will be written
as "untyped" values. *)
let dynamic_access ctx field_object member is_function =
match member with
| "__Field" | "__IField" | "__Run" | "__Is" | "__GetClass" | "__GetType" | "__ToString"
| "__s" | "__GetPtr" | "__SetField" | "__length" | "__IsArray"
| "__EnumParams" | "__Index" | "__Tag" | "__GetFields" | "toString" | "__HasField"
-> false
| _ ->
let could_be_dynamic_interface haxe_type =
if (is_array haxe_type) then false else
(match type_string haxe_type with
| "String" | "Null" | "Class" | "Enum" | "Math" | "ArrayAccess" -> false
| _ -> true ) in
if ( (could_be_dynamic_interface field_object.etype) &&
((member_type ctx field_object member)="?") ) then true else
if ( (is_interface field_object) && (not is_function) ) then true else
match field_object.eexpr with
| TConst TThis when ((not ctx.ctx_real_this_ptr) && ctx.ctx_dynamic_this_ptr) -> true
| _ -> (match follow field_object.etype with
| TMono mono -> true
| TAnon anon -> true
| TDynamic haxe_type -> true
| other -> (type_string other ) = "Dynamic");;
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 constant when (is_basic_type type_str) -> ("Dynamic",prefix ^ remap_name)
| _ -> (type_str,remap_name);;
(* 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 (name,o,arg_type) -> (gen_arg name o arg_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 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 quote s l =
l := String.length s;
escape_stringw (Ast.s_escape s) l;;
let str s =
let l = ref 0 in
let q = quote s l in
"STRING(" ^ q ^ "," ^ (string_of_int !l) ^ ")";;
(* 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_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_used)
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 =
"/* " ^
(match expression.eexpr with
| TConst _ -> "TConst"
| TLocal _ -> "TLocal"
| TEnumField _ -> "TEnumField"
| TArray (_,_) -> "TArray"
| TBinop (_,_,_) -> "TBinop"
| TField (_,_) -> "TField"
| TClosure _ -> "TClosure"
| TTypeExpr _ -> "TTypeExpr"
| TParenthesis _ -> "TParenthesis"
| TObjectDecl _ -> "TObjectDecl"
| TArrayDecl _ -> "TArrayDecl"
| TCall (_,_) -> "TCall"
| TNew (_,_,_) -> "TNew"
| TUnop (_,_,_) -> "TUnop"
| TFunction _ -> "TFunction"
| TVars _ -> "TVars"
| TBlock _ -> "TBlock"
| TFor (_,_,_,_) -> "TFor"
| TIf (_,_,_) -> "TIf"
| TWhile (_,_,_) -> "TWhile"
| TSwitch (_,_,_) -> "TSwitch"
| TMatch (_,_,_,_) -> "TMatch"
| TTry (_,_) -> "TTry"
| TReturn _ -> "TReturn"
| TBreak -> "TBreak"
| TContinue -> "TContinue"
| TThrow _ -> "TThrow" ) ^
(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 _
| TEnumField _
| 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,_)
| TClosure (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)
| 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 retval 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)
;;
(* 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 =
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,t) -> incr n; match v with None -> acc | Some v -> (v,t,!n) :: acc) [] l)
(*
This is the big one.
Once you get inside a function, all code is generated (recursively) as a "expression".
"retval" is tracked to determine whether the value on an expression is actually used.
eg, if the result of a block (ie, the last expression in the list) is used, then
we have to do some funky stuff to generate a local function.
Some things that change less often are stored in the context and are extracted
at the top for simplicity.
*)
let rec gen_expression ctx retval expression =
let output = ctx.ctx_output in
let writer = ctx.ctx_writer in
let output_i = writer#write_i in
let calling = ctx.ctx_calling in
ctx.ctx_calling <- false;
let assigning = ctx.ctx_assigning in
ctx.ctx_assigning <- false;
let return_from_block = ctx.ctx_return_from_block in
ctx.ctx_return_from_block <- false;
let return_from_internal_node = ctx.ctx_return_from_internal_node in
ctx.ctx_return_from_internal_node <- false;
(* Annotate source code with debug - can get a bit verbose. Mainly for debugging code gen,
rather than the run time *)
if (ctx.ctx_debug) then begin
if calling then output "/* Call */";
output (debug_expression expression ctx.ctx_debug_type);
end;
(* Write comma separated list of variables - useful for function args. *)
let rec gen_expression_list expressions =
(match expressions with
| [] -> ()
| [single] -> gen_expression ctx true single
| first :: remaining ->
gen_expression ctx true first;
output ",";
gen_expression_list remaining
) in
let check_this = function | "this" when not ctx.ctx_real_this_ptr -> "__this" | x -> x in
let rec find_undeclared_variables undeclared declarations this_suffix expression =
(
match expression.eexpr with
| TVars var_list ->
List.iter (fun (var_name, var_type, optional_init) ->
Hashtbl.add declarations var_name ();
if (ctx.ctx_debug) then
output ("/* found var " ^ var_name ^ "*/ ");
match optional_init with
| Some expression -> find_undeclared_variables undeclared declarations this_suffix expression
| _ -> ()
) var_list
| TFunction func -> List.iter ( fun (arg_name, opt_val, arg_type) ->
if (ctx.ctx_debug) then
output ("/* found arg " ^ arg_name ^ " = " ^ (type_string arg_type) ^ " */ ");
Hashtbl.add declarations arg_name () ) func.tf_args;
find_undeclared_variables undeclared declarations this_suffix func.tf_expr
| TTry (try_block,catches) ->
find_undeclared_variables undeclared declarations this_suffix try_block;
List.iter (fun (name,t,catch_expt) ->
let old_decs = Hashtbl.copy declarations in
Hashtbl.add declarations name ();
find_undeclared_variables undeclared declarations this_suffix catch_expt;
Hashtbl.clear declarations;
Hashtbl.iter ( Hashtbl.add declarations ) old_decs
) catches;
| TLocal local_name ->
if not (Hashtbl.mem declarations local_name) then
Hashtbl.replace undeclared local_name (type_string expression.etype)
| TMatch (condition, enum, cases, default) ->
Type.iter (find_undeclared_variables undeclared declarations this_suffix) 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_name,t) ->
match opt_name with | Some name -> Hashtbl.add declarations name () | _ -> () )
l );
Type.iter (find_undeclared_variables undeclared declarations this_suffix) expression;
Hashtbl.clear declarations;
Hashtbl.iter ( Hashtbl.add declarations ) old_decs
) cases;
(match default with | None -> ()
| Some expr ->
Type.iter (find_undeclared_variables undeclared declarations this_suffix) expr;
);
| TFor (var_name, var_type, init, loop) ->
let old_decs = Hashtbl.copy declarations in
Hashtbl.add declarations var_name ();
find_undeclared_variables undeclared declarations this_suffix init;
find_undeclared_variables undeclared declarations this_suffix loop;
Hashtbl.clear declarations;
Hashtbl.iter ( Hashtbl.add declarations ) old_decs
| TConst TSuper
| TConst TThis ->
if not (Hashtbl.mem declarations "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 ) 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) expression;
)
in
let remap_this = function | "this" -> "__this" | other -> other in
let reference = function | "this" -> " *__this" | name -> " &" ^name in
let rec define_local_function func_name func_def =
let declarations = Hashtbl.create 0 in
let undeclared = Hashtbl.create 0 in
(* Add args as defined variables *)
List.iter ( fun (arg_name, opt_val, arg_type) ->
if (ctx.ctx_debug) then
output ("/* found arg " ^ arg_name ^ " = " ^ (type_string arg_type) ^" */ ");
Hashtbl.add declarations arg_name () ) func_def.tf_args;
find_undeclared_variables undeclared declarations "" func_def.tf_expr;
let has_this = Hashtbl.mem undeclared "this" in
if (has_this) then Hashtbl.remove undeclared "this";
let typed_vars = hash_iterate undeclared (fun key value -> value ^ "," ^ key ) in
let func_name_sep = func_name ^ (if List.length typed_vars > 0 then "," else "") in
output_i ("BEGIN_LOCAL_FUNC" ^ (list_num typed_vars) ^ "(" ^ func_name_sep ^
(String.concat "," typed_vars) ^ ")\n" );
(* actual function, called "run" *)
let args_and_types = List.map
(fun (name,_,arg_type) -> (type_string arg_type) ^ " " ^ name ) func_def.tf_args in
let block = is_block func_def.tf_expr in
let func_type = type_string func_def.tf_type in
output_i (func_type ^ " run(" ^ (String.concat "," args_and_types) ^ ")");
let pop_real_this_ptr = clear_real_this_ptr ctx true in
if (block) then begin
writer#begin_block;
gen_expression ctx false func_def.tf_expr;
output_i "return null();\n";
writer#end_block;
end else begin
writer#begin_block;
(* Save old values, and equalize for new input ... *)
let old_used = ctx.ctx_static_id_used in
let old_curr = ctx.ctx_static_id_curr in
ctx.ctx_static_id_used <- old_curr;
find_local_functions func_def.tf_expr;
find_local_return_blocks false func_def.tf_expr;
(match func_def.tf_expr.eexpr with
| TReturn (Some return_expression) when (func_type<>"Void") ->
output_i "return ";
gen_expression ctx true return_expression;
| TReturn (Some return_expression) ->
output_i "";
gen_expression ctx false return_expression;
| _ ->
output_i "";
gen_expression ctx false func_def.tf_expr;
);
output ";\n";
output_i "return null();\n";
ctx.ctx_static_id_used <- old_used;
ctx.ctx_static_id_curr <- old_curr;
writer#end_block;
end;
pop_real_this_ptr();
if (has_this) then begin
output_i "Dynamic __this;\n";
output_i "void __SetThis(Dynamic inThis) { __this = inThis; }\n";
end;
let return = if (type_string func_def.tf_type ) = "Void" then "(void)" else "return" in
output_i ("END_LOCAL_FUNC" ^ (list_num args_and_types) ^ "(" ^ return ^ ")\n\n");
Hashtbl.replace ctx.ctx_local_function_args func_name
(if (ctx.ctx_real_this_ptr) then
String.concat "," (hash_keys undeclared)
else
String.concat "," (List.map remap_this (hash_keys undeclared)) )
and
define_local_return_block expression =
let declarations = Hashtbl.create 0 in
let undeclared = Hashtbl.create 0 in
find_undeclared_variables undeclared declarations "_obj" expression;
let name = next_anon_function_name ctx in
let vars = (hash_keys undeclared) in
let args = String.concat "," (List.map check_this (hash_keys undeclared)) in
Hashtbl.replace ctx.ctx_local_return_block_args name args;
output_i ("struct " ^ name);
writer#begin_block;
let ret_type = type_string expression.etype in
output_i ("static " ^ ret_type ^ " Block( ");
output (String.concat "," ( (List.map (fun var ->
(Hashtbl.find undeclared var) ^ (reference var)) ) vars));
output (")");
if (is_block expression) then begin
ctx.ctx_return_from_block <- true;
ctx.ctx_return_from_internal_node <- false;
output "/* DEF (ret block)(not intern) */";
end else begin
ctx.ctx_return_from_block <- false;
ctx.ctx_return_from_internal_node <- true;
output "/* DEF (not block)(ret intern) */";
end;
let pop_real_this_ptr = clear_real_this_ptr ctx false in
gen_expression ctx false (to_block expression);
pop_real_this_ptr();
(*
let block = is_block expression in
if (not block) then begin
writer#begin_block; output_i "";
iter_retval find_local_return_blocks false expression;
end;
ctx.ctx_return_from_block <- true;
let pop_real_this_ptr = clear_real_this_ptr ctx false in
gen_expression ctx false expression;
pop_real_this_ptr();
if (not block) then begin
output_i "return Dynamic();\n";
writer#end_block;
end;
*)
writer#end_block_line;
output ";\n";
and
find_local_functions expression =
match expression.eexpr with
| TBlock _ -> () (* stop at block - since that block will define the function *)
| TCall (e,el) -> (* visit the args first, then the function *)
List.iter find_local_functions el;
find_local_functions e
| TFunction func ->
let func_name = next_anon_function_name ctx in
output "\n";
define_local_function func_name func
| _ -> Type.iter find_local_functions expression
and
find_local_return_blocks retval expression =
match expression.eexpr with
| TBlock _ ->
if (retval) then begin
define_local_return_block expression;
end (* else we are done *)
| TFunction func -> ()
| TMatch (_, _, _, _)
| TTry (_, _)
| TSwitch (_, _, _) when retval ->
define_local_return_block expression;
| _ -> iter_retval find_local_return_blocks retval expression
in
let rec gen_bin_op_string expr1 op expr2 =
let cast = (match op with
| ">>" | "<<" | "&" | "|" | "^" -> "int("
| "&&" | "||" -> "bool("
| "/" -> "double("
| _ -> "") in
if ( cast <> "") then output cast;
gen_expression ctx true expr1;
if ( cast <> "") then output ")";
output (" " ^ op ^ " ");
if ( cast <> "") then output cast;
gen_expression ctx true expr2;
if ( cast <> "") then output ")"
in
let rec gen_bin_op op expr1 expr2 =
match op with
| Ast.OpAssign -> ctx.ctx_assigning <- true;
gen_bin_op_string expr1 "=" expr2
| Ast.OpUShr ->
output "hxUShr(";
gen_expression ctx true expr1;
output ",";
gen_expression ctx true expr2;
output ")";
| Ast.OpMod ->
output "hxMod(";
gen_expression ctx true expr1;
output ",";
gen_expression ctx true expr2;
output ")";
| Ast.OpAssignOp bin_op ->
output (match bin_op with
| Ast.OpAdd -> "hxAddEq("
| Ast.OpMult -> "hxMultEq("
| Ast.OpDiv -> "hxDivEq("
| Ast.OpSub -> "hxSubEq("
| Ast.OpAnd -> "hxAndEq("
| Ast.OpOr -> "hxOrEq("
| Ast.OpXor -> "hxXorEq("
| Ast.OpShl -> "hxShlEq("
| Ast.OpShr -> "hxShrEq("
| Ast.OpUShr -> "hxUShrEq("
| Ast.OpMod -> "hxModEq("
| _ -> error "Unknown OpAssignOp" expression.epos );
ctx.ctx_assigning <- true;
gen_expression ctx true expr1;
output ",";
gen_expression ctx true expr2;
output ")"
| Ast.OpNotEq -> gen_bin_op_string expr1 "!=" expr2
| Ast.OpEq -> gen_bin_op_string expr1 "==" expr2
| _ -> gen_bin_op_string expr1 (Ast.s_binop op) expr2
in
let gen_member_access field_object member is_function return_type =
let remap_name = keyword_remap member in
begin
let check_dynamic_member_access member = begin
(match (dynamic_access ctx field_object member is_function) with
| true when (not (dynamic_internal member)) ->
let access = (if assigning then ".FieldRef" else "->__Field") in
output ( access ^ "(" ^ (str member) ^ ")" );
if (not assigning) then begin
let return = type_string return_type in
if ( not (return="Dynamic") ) then
output (".Cast<" ^ return ^ " >()");
end
| _ ->
let member_name = remap_name ^
( if ( (not calling) && is_function && (not assigning)) then "_dyn()" else "" ) in
if ( (type_string field_object.etype)="String") then
output ( "." ^ member_name)
else begin
output ( "->" ^ member_name);
if (not assigning) then begin
let expr_type = type_string return_type in
let mem_type = member_type ctx field_object member in
if ( (mem_type="Dynamic") && expr_type<>"Dynamic") then
output (".Cast<" ^ expr_type ^ " >()");
end;
end )
end in
match field_object.eexpr with
(* static access ... *)
| TTypeExpr type_def ->
let class_name = (join_class_path (t_path type_def) "::" ) in
if (class_name="String") then
output ("String::" ^ remap_name)