forked from HaxeFoundation/haxe
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gencpp.ml
5846 lines (5213 loc) · 233 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
(*
The Haxe Compiler
Copyright (C) 2005-2015 Haxe Foundation
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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*)
open Ast
open Type
open Common
let unsupported p = error "This expression cannot be generated to Cpp" p
(*
Generators do not care about non-core-type abstracts, so let us follow them
away by default.
*)
let follow = Abstract.follow_with_abstracts
(*
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;;
(* 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")
| (["cpp"],"Pointer") | (["cpp"],"ConstPointer")
| (["cpp"],"RawPointer") | (["cpp"],"RawConstPointer")
| (["cpp"],"Function") -> true
| ([],"Math") | (["haxe";"io"], "Unsigned_char__") -> true
| (["cpp"],"Int8") | (["cpp"],"UInt8") | (["cpp"],"Char")
| (["cpp"],"Int16") | (["cpp"],"UInt16")
| (["cpp"],"Int32") | (["cpp"],"UInt32")
| (["cpp"],"Int64") | (["cpp"],"UInt64")
| (["cpp"],"Float32") | (["cpp"],"Float64") -> true
| _ -> false;;
let get_include_prefix common_ctx with_slash =
try
(Common.defined_value common_ctx Define.IncludePrefix) ^ (if with_slash then "/" else "")
with
Not_found -> ""
;;
let should_prefix_include = function
| x when is_internal_class x -> false
| ([],"hxMath") -> true
| _ -> false;;
class source_writer common_ctx 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 =
( match class_path with
| (["@verbatim"],file) -> this#write ("#include \"" ^ file ^ "\"\n");
| _ ->
let prefix = if should_prefix_include class_path then "" else get_include_prefix common_ctx true in
this#write ("#ifndef INCLUDED_" ^ (join_class_path class_path "_") ^ "\n");
this#write ("#include <" ^ prefix ^ (join_class_path class_path "/") ^ ".h>\n");
this#write ("#endif\n")
)
end;;
let file_source_writer common_ctx filename =
let out_file = open_out filename in
new source_writer common_ctx (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 common_ctx 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 common_ctx (add_buf) (close);
with _ ->
file_source_writer common_ctx filename;;
let make_class_directories = Common.mkdir_recursive;;
let make_base_directory dir =
make_class_directories "" ( ( Str.split_delim (Str.regexp "[\\/]+") dir ) );;
let new_source_file common_ctx base_dir sub_dir extension class_path =
let include_prefix = get_include_prefix common_ctx true in
let full_dir =
if (sub_dir="include") && (include_prefix<>"") then begin
let dir = match fst class_path with
| [] -> base_dir ^ "/include/" ^ (get_include_prefix common_ctx false)
| path -> base_dir ^ "/include/" ^ include_prefix ^ ( String.concat "/" path )
in
make_base_directory dir;
dir
end else begin
make_class_directories base_dir ( sub_dir :: (fst class_path));
base_dir ^ "/" ^ sub_dir ^ "/" ^ ( String.concat "/" (fst class_path) )
end
in
cached_source_writer common_ctx (full_dir ^ "/" ^ ((snd class_path) ^ extension));;
let source_file_extension common_ctx =
(* no need to -D file_extension if -D objc is defined *)
if Common.defined common_ctx Define.Objc then
".mm"
else try
"." ^ (Common.defined_value common_ctx Define.FileExtension)
with
Not_found -> ".cpp"
;;
let new_cpp_file common_ctx base_dir = new_source_file common_ctx base_dir "src" (source_file_extension common_ctx);;
let new_header_file common_ctx base_dir =
new_source_file common_ctx base_dir "include" ".h";;
(* 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_level : int;
mutable ctx_real_this_ptr : bool;
mutable ctx_real_void : bool;
mutable ctx_dynamic_this_ptr : bool;
mutable ctx_dump_src_pos : unit -> unit;
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>1 then (writer#write) else (fun _ -> ());
ctx_calling = false;
ctx_assigning = false;
ctx_debug_level = debug;
ctx_dump_src_pos = (fun() -> ());
ctx_return_from_block = false;
ctx_tcall_expand_args = false;
ctx_return_from_internal_node = false;
ctx_real_this_ptr = true;
ctx_real_void = false;
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 header files are also defined in the hx/Object.h file, so you do
#include them separately. However, Math classes has its
own header file (under the hxcpp tree) so these should be included *)
let include_class_header = function
| ([],"@Main") -> false
| ([],"Math") -> true
| path -> not ( is_internal_class path )
let is_cpp_class = function
| ("cpp"::_ , _) -> 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 ;;
(* 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 _ -> key_list := key :: !key_list ) pmap;
!key_list;;
let pmap_values pmap =
let value_list = ref [] in
PMap.iter (fun _ value -> value_list := value :: !value_list ) pmap;
!value_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" | "system"
| "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" | "INFINITY" | "NAN"
| "INT_MIN" | "INT_MAX" | "INT8_MIN" | "INT8_MAX" | "UINT8_MAX" | "INT16_MIN"
| "INT16_MAX" | "UINT16_MAX" | "INT32_MIN" | "INT32_MAX" | "UINT32_MAX"
| "asm"
| "struct" -> "_hx_" ^ name
| 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 =
match join_class_path (remap_class_path path) separator with
| "Class" -> "hx::Class"
| x -> x
;;
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 get_meta_string_path meta key =
let rec loop = function
| [] -> ""
| (k,[Ast.EConst (Ast.String name),_], pos) :: _ when k=key->
(try
if (String.sub name 0 2) = "./" then begin
let base = if (Filename.is_relative pos.pfile) then
Filename.concat (Sys.getcwd()) pos.pfile
else
pos.pfile
in
Gencommon.normalize (Filename.concat (Filename.dirname base) (String.sub name 2 ((String.length name) -2) ))
end else
name
with Invalid_argument _ -> name)
| _ :: l -> loop l
in
loop meta
;;
let get_meta_string_full_filename meta key =
let rec loop = function
| [] -> ""
| (k,_, pos) :: _ when k=key->
if (Filename.is_relative pos.pfile) then
Gencommon.normalize (Filename.concat (Sys.getcwd()) pos.pfile)
else
pos.pfile
| _ :: l -> loop l
in
loop meta
;;
let get_meta_string_full_dirname meta key =
let name = get_meta_string_full_filename meta key in
try
Gencommon.normalize (Filename.dirname name)
with Invalid_argument _ -> ""
;;
let get_field_access_meta field_access key =
match field_access with
| FInstance(_,_,class_field)
| FStatic(_,class_field) -> get_meta_string class_field.cf_meta key
| _ -> ""
;;
let format_code code =
String.concat "\n" (ExtString.String.nsplit code "\r\n")
let get_code meta key =
let code = get_meta_string meta key in
let magic_var = "${GENCPP_SOURCE_DIRECTORY}" in
let code = if ExtString.String.exists code magic_var then begin
let source_directory = get_meta_string_full_dirname meta key in
let _,code = ExtString.String.replace code magic_var source_directory in
code
end else
code
in
if (code<>"") then format_code code ^ "\n" else code
;;
let has_meta_key meta key =
List.exists (fun m -> match m with | (k,_,_) when k=key-> true | _ -> false ) meta
;;
let type_has_meta_key haxe_type key =
match follow haxe_type with
| TInst (klass,_) -> has_meta_key klass.cl_meta key
| TType (type_def,_) -> has_meta_key type_def.t_meta key
| TEnum (enum_def,_) -> has_meta_key enum_def.e_meta key
| _ -> false
;;
(*
let dump_meta meta =
List.iter (fun m -> match m with | (k,_,_) -> print_endline ((fst (MetaInfo.to_string k)) ^ "=" ^ (get_meta_string meta k) ) | _ -> () ) meta;;
*)
let get_class_code class_def key = match class_def.cl_kind with
| KAbstractImpl abstract_def ->
let value = (get_code abstract_def.a_meta key) in
value
| _ -> get_code class_def.cl_meta key
;;
(* 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 =
begin
let output = writer#write in
match class_path with
| (["@verbatim"],file) -> writer#write ("#include <" ^ file ^ ">\n");
| _ ->
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 | TMeta(_,expr) -> is_function_expr expr
| 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
| "::cpp::UInt8" | "::cpp::Int8" | "::cpp::Char"
| "::cpp::UInt16" | "::cpp::Int16"
| "::cpp::UInt32" | "::cpp::Int32"
| "::cpp::UInt64" | "::cpp::Int64"
| "::cpp::Float32" | "::cpp::Float64"
| "int" | "bool" | "double" | "float" -> true
| _ -> false
let rec remove_parens expression =
match expression.eexpr with
| TParenthesis e -> remove_parens e
| TMeta(_,e) -> remove_parens e
| _ -> expression
;;
(*
let rec remove_parens_cast expression =
match expression.eexpr with
| TParenthesis e -> remove_parens_cast e
| TMeta(_,e) -> remove_parens_cast e
| TCast ( e,None) -> remove_parens_cast e
| _ -> expression
;;
*)
let is_interface_type t =
match follow t with
| TInst (klass,params) -> klass.cl_interface
| _ -> false
;;
let is_cpp_function_instance haxe_type =
match follow haxe_type with
| TInst (klass,params) ->
(match klass.cl_path with
| ["cpp"] , "Function" -> true
| _ -> false )
| _ -> false
;;
let is_cpp_function_class haxe_type =
match follow haxe_type with
| TType (klass,params) ->
(match klass.t_path with
| ["cpp"] , "Function" -> true
| _ -> false )
| _ -> false
;;
let is_fromStaticFunction_call func =
match (remove_parens func).eexpr with
| TField (_,FStatic ({cl_path=["cpp"],"Function"},{cf_name="fromStaticFunction"} ) ) -> true
| _ -> false
;;
let is_objc_call field =
match field with
| FStatic(cl,_) | FInstance(cl,_,_) ->
cl.cl_extern && Meta.has Meta.Objc cl.cl_meta
| _ -> false
;;
let is_objc_type t = match follow t with
| TInst(cl,_) -> cl.cl_extern && Meta.has Meta.Objc cl.cl_meta
| _ -> false
;;
let is_addressOf_call func =
match (remove_parens func).eexpr with
| TField (_,FStatic ({cl_path=["cpp"],"Pointer"},{cf_name="addressOf"} ) ) -> true
| _ -> false
;;
let is_lvalue var =
match (remove_parens var).eexpr with
| TLocal _ -> true
| TField (_,FStatic(_,field) ) | TField (_,FInstance(_,_,field) ) -> is_var_field field
| _ -> false
;;
let is_pointer haxe_type includeRaw =
match follow haxe_type with
| TInst (klass,params) ->
(match klass.cl_path with
| ["cpp"] , "Pointer"
| ["cpp"] , "ConstPointer"
| ["cpp"] , "Function" -> true
| ["cpp"] , "RawPointer" when includeRaw -> true
| ["cpp"] , "RawConstPointer" when includeRaw -> true
| _ -> false )
| TType (type_def,params) ->
(match type_def.t_path with
| ["cpp"] , "Pointer"
| ["cpp"] , "ConstPointer"
| ["cpp"] , "Function" -> true
| ["cpp"] , "RawPointer" when includeRaw -> true
| ["cpp"] , "RawConstPointer" when includeRaw -> true
| _ -> false )
| _ -> false
;;
let is_dynamic_type_param class_kind =
match class_kind with
| KTypeParameter _ -> 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 remap =
let type_string = type_string_remap remap in
let join_class_path_remap = if remap then join_class_path_remap else join_class_path in
(match klass.cl_path with
(* Array class *)
| ([],"Array") when is_dynamic_array_param (List.hd params) ->
"cpp::ArrayBase" ^ suffix (* "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) ) ^ " >"
| (["cpp"],"Pointer")
| (["cpp"],"ConstPointer") ->
"::cpp::Pointer< " ^ (String.concat "," (List.map type_string params) ) ^ " >"
| (["cpp"],"RawPointer") ->
" " ^ (String.concat "," (List.map type_string params) ) ^ " * "
| (["cpp"],"RawConstPointer") ->
" const " ^ (String.concat "," (List.map type_string params) ) ^ " * "
| (["cpp"],"Function") ->
"::cpp::Function< " ^ (cpp_function_signature_params params) ^ " >"
| _ when is_dynamic_type_param klass.cl_kind -> "Dynamic"
| ([],"#Int") -> "/* # */int"
| (["haxe";"io"],"Unsigned_char__") -> "unsigned char"
| ([],"Class") -> "hx::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"
| t when type_has_meta_key t Meta.NotNull -> "Dynamic"
| _ -> "/*NULL*/" ^ (type_string t) )
| _ -> assert false);
(* Objective-C class *)
| path when is_objc_type (TInst(klass,[])) ->
let str = join_class_path_remap klass.cl_path "::" in
if suffix = "_obj" then
str
else if klass.cl_interface then
"id <" ^ str ^ ">"
else
str ^ " *"
(* 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 remap =
let type_string = type_string_remap remap in
let join_class_path_remap = if remap then join_class_path_remap else join_class_path in
(match haxe_type with
| TMono r -> (match !r with None -> "Dynamic" ^ suffix | Some t -> type_string_suff suffix t remap)
| 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 (enum,params) -> "::" ^ (join_class_path_remap enum.e_path "::") ^ suffix
| TInst (klass,params) -> (class_string klass suffix params remap)
| 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
| t when type_has_meta_key t Meta.NotNull -> "Dynamic" ^ suffix
| _ -> type_string_suff suffix t remap)
| _ -> 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)
| ["cpp"] , "Pointer"
| ["cpp"] , "ConstPointer" ->
(match params with
| [t] -> "::cpp::Pointer< " ^ (type_string (follow t) ) ^ " >"
| _ -> assert false)
| ["cpp"] , "RawPointer" ->
(match params with
| [t] -> " " ^ (type_string (follow t) ) ^ " *"
| _ -> assert false)
| ["cpp"] , "RawConstPointer" ->
(match params with
| [t] -> "const " ^ (type_string (follow t) ) ^ " *"
| _ -> assert false)
| ["cpp"] , "Function" ->
"::cpp::Function< " ^ (cpp_function_signature_params params ) ^ " >"
| _ -> type_string_suff suffix (apply_params type_def.t_params params type_def.t_type) remap
)
| 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_params))
| EnumStatics e -> type_string_suff suffix (TEnum (e,List.map snd e.e_params))
| _ -> "Dynamic" ^ suffix )
*)
| TDynamic haxe_type -> "Dynamic" ^ suffix
| TLazy func -> type_string_suff suffix ((!func)()) remap
| TAbstract (abs,pl) when abs.a_impl <> None ->
type_string_suff suffix (Abstract.get_underlying_type abs pl) remap
| TAbstract (abs,pl) ->
"::" ^ (join_class_path_remap abs.a_path "::") ^ suffix
)
and type_string_remap remap haxe_type =
type_string_suff "" haxe_type remap
and type_string haxe_type =
type_string_suff "" haxe_type true
and array_element_type haxe_type =
match type_string haxe_type with
| x when cant_be_null haxe_type -> x
| x when is_interface_type (follow haxe_type) -> 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")
| (["cpp"],"RawPointer") |(["cpp"],"ConstRawPointer")
| (["cpp"],"Pointer") |(["cpp"],"ConstPointer")|(["cpp"],"Function") -> false
| _ -> (match klass.cl_kind with KTypeParameter _ -> true | _ -> false)
)
| _ -> false
)
and cpp_function_signature tfun abi =
match follow tfun with
| TFun(args,ret) -> (type_string ret) ^ " " ^ abi ^ "(" ^ (gen_tfun_interface_arg_list args) ^ ")"
| _ -> "void *"
and cpp_function_signature_params params = match params with
| [t; abi] -> (match follow abi with
| TInst (klass,_) -> cpp_function_signature t (get_meta_string klass.cl_meta Meta.Abi)
| _ -> print_endline (type_string abi);
assert false )
| _ ->
print_endline ("Params:" ^ (String.concat "," (List.map type_string params) ));
assert false;
and gen_interface_arg_type_name name opt typ =
let type_str = (type_string typ) in
(* type_str may have already converted Null<X> to Dynamic because of NotNull tag ... *)
(if (opt && (cant_be_null typ) && type_str<>"Dynamic" ) then
"hx::Null< " ^ type_str ^ " > "
else
type_str )
^ " " ^ (keyword_remap name)
and gen_tfun_interface_arg_list args =
String.concat "," (List.map (fun (name,opt,typ) -> gen_interface_arg_type_name name opt typ) args)
and cant_be_null haxe_type =
is_numeric (type_string haxe_type) || (type_has_meta_key haxe_type Meta.NotNull )
;;
let is_object type_string =
not (is_numeric type_string || type_string="::String");
;;
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_or_dyn_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_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;
;;
let is_static_access obj =
match (remove_parens obj).eexpr with
| TTypeExpr _ -> true
| _ -> false
;;
let is_native_with_space func =
match (remove_parens func).eexpr with
| TField(obj,field) when is_static_access obj ->
String.contains (get_field_access_meta field Meta.Native) ' '
| _ -> false
;;
let rec is_cpp_function_member func =
match (remove_parens func).eexpr with
| TField(obj,field) when is_cpp_function_instance obj.etype -> true
| TCall(obj,_) -> is_cpp_function_member obj
| _ -> false
;;
(* Get the type and output it to the stream *)
let gen_type ctx haxe_type =
ctx.ctx_output (type_string 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 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"
| "__GetRealObject"
-> true
| _ -> false;;
let is_extern_class class_def =
class_def.cl_extern || (has_meta_key class_def.cl_meta Meta.Extern) ||
(match class_def.cl_kind with
| KAbstractImpl abstract_def -> (has_meta_key abstract_def.a_meta Meta.Extern)
| _ -> false );
;;
let is_native_gen_class class_def =
(has_meta_key class_def.cl_meta Meta.NativeGen) ||
(match class_def.cl_kind with
| KAbstractImpl abstract_def -> (has_meta_key abstract_def.a_meta Meta.NativeGen)
| _ -> false );
;;
let is_extern_class_instance obj =
match follow obj.etype with
| TInst (klass,params) -> klass.cl_extern
| _ -> false
;;
let is_struct_access t =
match follow t with
| TInst (class_def,_) -> (has_meta_key class_def.cl_meta Meta.StructAccess)
| _ -> 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 arg_type) -> ("hx::Null< " ^ type_str ^ " > ",prefix ^ remap_name)
| Some constant -> (type_str,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 (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) ) );;
let gen_hash32 seed str =
let h = ref (Int32.of_int seed) in
let cycle = Int32.of_int 223 in
for i = 0 to String.length str - 1 do
h := Int32.add (Int32.mul !h cycle) (Int32.of_int (int_of_char (String.unsafe_get str i)));
done;
!h
;;
let gen_hash seed str =
Printf.sprintf "0x%08lx" (gen_hash32 seed str)
;;
let gen_string_hash str =
let h = gen_hash32 0 str in
Printf.sprintf "\"\\x%02lx\",\"\\x%02lx\",\"\\x%02lx\",\"\\x%02lx\""
(Int32.shift_right_logical (Int32.shift_left h 24) 24)
(Int32.shift_right_logical (Int32.shift_left h 16) 24)
(Int32.shift_right_logical (Int32.shift_left h 8) 24)
(Int32.shift_right_logical h 24)
;;
(* 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';