-
-
Notifications
You must be signed in to change notification settings - Fork 702
Expand file tree
/
Copy pathcppGenClassImplementation.ml
More file actions
1180 lines (982 loc) · 47 KB
/
Copy pathcppGenClassImplementation.ml
File metadata and controls
1180 lines (982 loc) · 47 KB
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
open Ast
open Type
open Globals
open CppStrings
open CppTypeUtils
open CppAst
open CppAstTools
open CppSourceWriter
open CppContext
open CppGen
let write_callable_header callable_name captures func return_type_str prefix output =
let signature = func_to_callable_string "::hx::AutoCallable_obj" func in
Printf.sprintf "struct %s final : public %s {\n" callable_name signature |> output;
(match captures with
| Some obj_name ->
Printf.sprintf "\t::hx::ObjectPtr<%s> __this;\n" obj_name |> output;
Printf.sprintf "\t%s(::hx::ObjectPtr<%s> obj = null()) : __this(obj) {} \n" callable_name obj_name |> output
| None ->
Printf.sprintf "\t%s() {} \n" callable_name |> output);
(* Override __Compare *)
output "\tint __Compare(const ::hx::Object* inRhs) const override {\n";
Printf.sprintf "\t\tauto casted = dynamic_cast<const %s*>(inRhs);\n" callable_name |> output;
output "\t\tif (!casted) { return -1; }\n";
if Option.is_some captures then
output "\t\tif (__this != casted->__this) return 1;\n";
output "\t\treturn 0;\n";
output "\t}\n";
(* Override callableId, Haxe function closures are only compared based on name, not signature *)
output "\tstd::type_index callableId() const override {\n";
Printf.sprintf "\t\treturn std::type_index{ typeid(%s) };\n" callable_name |> output;
output "\t}\n";
Printf.sprintf "\t%s HX_LOCAL_RUN(%s) override {\n" return_type_str (cpp_callable_args func.tcf_args prefix) |> output
let write_callable_trailer captures output =
output "\t}\n";
if Option.is_some captures then begin
output "\tvoid __Mark(hx::MarkContext* __inCtx) override { HX_MARK_MEMBER(__this); }\n";
output "#ifdef HXCPP_VISIT_ALLOCS\n";
output "\tvoid __Visit(hx::VisitContext* __inCtx) override { HX_VISIT_MEMBER(__this); }\n";
output "#endif\n";
end;
output "};\n\n"
let gen_function ctx tcpp_class is_static func =
let output = ctx.ctx_output in
let return_type = cpp_type_of ctx.ctx_common.basic func.tcf_func.tf_type in
let ret, is_void, return_type_str =
match return_type with
| TCppVoid ->
"(void)", true, "void"
| other ->
"return ", false, tcpp_to_string other in
(* The actual function definition *)
output return_type_str;
output (" " ^ tcpp_class.tcl_name ^ "::" ^ func.tcf_name ^ "(");
output (print_arg_list func.tcf_args "__o_");
output ")";
begin match get_meta_string func.tcf_field.cf_meta Meta.Native with
| Some nativeImpl when is_static ->
output " {\n";
output
("\t" ^ ret ^ "::" ^ nativeImpl ^ "("
^ print_arg_list_name func.tcf_args "__o_"
^ ");\n");
output "}\n\n"
| _ ->
ctx.ctx_real_this_ptr <- true;
let code = get_code func.tcf_field.cf_meta Meta.FunctionCode in
let tail_code = get_code func.tcf_field.cf_meta Meta.FunctionTailCode in
with_debug
ctx
func.tcf_field.cf_meta
(gen_cpp_function_body ctx tcpp_class.tcl_class is_static func.tcf_field.cf_name func code tail_code);
end;
output "\n\n";
(* generate dynamic version too ... *)
if (not func.tcf_is_virtual || not func.tcf_is_overriding) && func.tcf_is_reflective then
let callable_name = Printf.sprintf "__%s%s" tcpp_class.tcl_name func.tcf_name in
let signature = func_to_callable_string "::hx::Callable" func in
if is_static then
Printf.sprintf
"%s %s::%s_dyn() { return _hx_alloc%s; }\n\n"
signature
tcpp_class.tcl_name
func.tcf_name
callable_name |> output
else
Printf.sprintf
"%s %s::%s_dyn() { return new %s(this); }\n\n"
signature
tcpp_class.tcl_name
func.tcf_name
callable_name |> output
let gen_function_closures ctx tcpp_class is_static func =
if (not func.tcf_is_virtual || not func.tcf_is_overriding) && func.tcf_is_reflective then
let output = ctx.ctx_output in
let return_type_str = type_to_string ctx.ctx_common.basic func.tcf_func.tf_type in
let return_type = cpp_type_of ctx.ctx_common.basic func.tcf_func.tf_type in
let is_void = return_type = TCppVoid in
let callable_name = Printf.sprintf "__%s%s" tcpp_class.tcl_name func.tcf_name in
let full_name = (tcpp_class.tcl_class.cl_path |> fst |> List.map keyword_remap |> String.concat "::") ^ "::" ^ tcpp_class.tcl_name in
let captures = if is_static then None else Some full_name in
write_callable_header callable_name captures func return_type_str "" output;
let args_pass = func.tcf_args |> List.map fst |> List.map (fun v -> v.tcppv_name) |> String.concat ", " in
let prefix = if is_void then "\t\t" else "\t\treturn " in
if is_static then
Printf.sprintf "%s%s::%s(%s);\n" prefix full_name func.tcf_name args_pass |> output
else
Printf.sprintf "%s__this->%s(%s);\n" prefix func.tcf_name args_pass |> output;
write_callable_trailer captures output;
if is_static then
let signature = func_to_callable_string "::hx::Callable" func in
Printf.sprintf "%s _hx_alloc%s;\n\n" signature callable_name |> output
let gen_static_closure_alloc ctx tcpp_class func =
if (not func.tcf_is_virtual || not func.tcf_is_overriding) && func.tcf_is_reflective then
let output = ctx.ctx_output in
let callable_name = Printf.sprintf "__%s%s" tcpp_class.tcl_name func.tcf_name in
Printf.sprintf "_hx_alloc%s = new (::hx::NewObjectType::NewObjConst) %s();\n\n" callable_name callable_name |> output
let gen_dynamic_function ctx tcpp_class is_static func =
let output = ctx.ctx_output in
let func_name = "__default_" ^ func.tcf_name in
let no_debug = Meta.has Meta.NoDebug func.tcf_field.cf_meta in
let return_type_str = func.tcf_return |> tcpp_to_string in
let captures = Some ((tcpp_class.tcl_class.cl_path |> fst |> List.map keyword_remap |> String.concat "::") ^ "::" ^ tcpp_class.tcl_name) in
write_callable_header func_name captures func return_type_str "__o_" output;
ctx.ctx_real_this_ptr <- false;
gen_cpp_function_body ctx tcpp_class.tcl_class is_static func_name func "" "" no_debug;
write_callable_trailer captures output
let gen_static_variable ctx tcpp_class var =
let output = ctx.ctx_output in
let tcpp_str = var.tcv_type |> tcpp_to_string in
Printf.sprintf "%s %s::%s;\n\n" tcpp_str tcpp_class.tcl_name var.tcv_name |> output
let gen_dynamic_function_init ctx func =
match func.tcf_field.cf_expr with
| Some { eexpr = TFunction function_def } ->
Printf.sprintf "\t%s = new %s;\n\n" func.tcf_name ("__default_" ^ func.tcf_name) |> ctx.ctx_output
| _ ->
()
let gen_boot_field ctx output_cpp tcpp_class =
if has_tcpp_class_flag tcpp_class Boot then (
let gen_var_init ctx class_def var =
match var.tcv_field.cf_expr with
| Some expr ->
let dst = Builder.make_static_field class_def var.tcv_field var.tcv_field.cf_pos in
let op = Builder.binop OpAssign dst expr expr.etype expr.epos in
gen_cpp_init ctx (join_class_path class_def.cl_path ".") "boot" "" op
| _ -> ()
in
output_cpp ("void " ^ tcpp_class.tcl_name ^ "::__boot()\n{\n");
let dot_name = join_class_path tcpp_class.tcl_class.cl_path "." in
(match tcpp_class.tcl_meta with
| Some expr -> gen_cpp_init ctx dot_name "boot" "__mClass->__meta__ = " expr
| None -> ());
(match tcpp_class.tcl_rtti with
| Some expr -> gen_cpp_init ctx dot_name "boot" "__mClass->__rtti__ = " expr
| None -> ());
(* Allocating static function lambdas must be done first *)
(* Init functionality might depend on these being assigned *)
List.iter (gen_static_closure_alloc ctx tcpp_class) tcpp_class.tcl_static_functions;
List.iter (gen_var_init ctx tcpp_class.tcl_class) tcpp_class.tcl_static_variables;
List.iter (gen_dynamic_function_init ctx) tcpp_class.tcl_static_dynamic_functions;
output_cpp "}\n\n")
let gen_init_function ctx output_cpp tcpp_class =
match tcpp_class.tcl_init with
| Some expression ->
output_cpp ("void " ^ tcpp_class.tcl_name ^ "::__init__()");
gen_cpp_init ctx (cpp_class_name tcpp_class.tcl_class) "__init__" "" (mk_block expression);
output_cpp "\n\n"
| None ->
()
let gen_dynamic_function_allocator ctx output_cpp tcpp_class =
match tcpp_class.tcl_dynamic_functions with
| [] -> ()
| functions ->
let mapper func =
Printf.sprintf "\tif (!_hx_obj->%s.mPtr) { _hx_obj->%s = new __default_%s(_hx_obj); }" func.tcf_name func.tcf_name func.tcf_name in
let rec folder acc class_def =
if has_dynamic_member_functions class_def then
let super_name = join_class_path_remap class_def.cl_path "::" ^ "_obj" in
Printf.sprintf "\t%s::__alloc_dynamic_functions(_hx_ctx, _hx_obj);" super_name :: acc
else
match class_def.cl_super with
| Some (super, _) -> folder acc super
| _ -> acc
in
let initial = functions |> List.map mapper in
let allocs = match tcpp_class.tcl_class.cl_super with
| Some (super, _) ->
folder initial super
| _ ->
initial in
let str = allocs |> List.rev |> String.concat "\n" in
Printf.sprintf "void %s::__alloc_dynamic_functions(::hx::Ctx* _hx_ctx, %s* _hx_obj) {\n%s\n}\n" tcpp_class.tcl_name tcpp_class.tcl_name str |> output_cpp
let print_reflective_fields ctx_common class_def variables functions =
let filter_vars var acc =
if var.tcv_is_reflective then
Printf.sprintf "\t%s" (strq ctx_common var.tcv_field.cf_name) :: acc
else
acc in
let filter_funcs func acc =
if func.tcf_is_reflective then
Printf.sprintf "\t%s" (strq ctx_common func.tcf_field.cf_name) :: acc
else
acc in
let calls =
[ "\t::String(null())" ]
|> List.fold_right filter_vars variables
|> List.fold_right filter_funcs functions
in
if List.length calls > 1 then
Some (String.concat ",\n" calls)
else
None
let cpp_interface_impl_name cls =
"_hx_" ^ join_class_path cls.cl_path "_"
let generate_native_class base_ctx tcpp_class =
let class_def = tcpp_class.tcl_class in
let class_path = class_def.cl_path in
let debug = tcpp_class.tcl_debug_level in
let cpp_file = new_placed_cpp_file base_ctx.ctx_common class_path in
let cpp_ctx = file_context base_ctx cpp_file debug false in
let ctx = cpp_ctx in
let output_cpp = cpp_file#write in
let scriptable = has_tcpp_class_flag tcpp_class Scriptable in
cpp_file#write_h "#include <hxcpp.h>\n\n";
let all_referenced =
CppReferences.find_referenced_types ctx (TClassDecl class_def) ctx.ctx_super_deps
ctx.ctx_constructor_deps false false scriptable
in
List.iter (add_include cpp_file) all_referenced;
if scriptable then cpp_file#write_h "#include <hx/Scriptable.h>\n";
cpp_file#write_h "\n";
output_cpp (get_class_code class_def Meta.CppFileCode);
let includes = get_all_meta_string_path class_def.cl_meta Meta.CppInclude in
let printer inc = output_cpp ("#include \"" ^ inc ^ "\"\n") in
List.iter printer includes;
output_cpp "\n";
output_cpp "namespace {\n\n";
List.iter (gen_dynamic_function ctx tcpp_class false) tcpp_class.tcl_dynamic_functions;
List.iter (gen_dynamic_function ctx tcpp_class true) tcpp_class.tcl_static_dynamic_functions;
List.iter (gen_function_closures ctx tcpp_class false) tcpp_class.tcl_functions;
List.iter (gen_function_closures ctx tcpp_class true) tcpp_class.tcl_static_functions;
output_cpp "}\n\n";
begin_namespace output_cpp class_path;
output_cpp (get_class_code class_def Meta.CppNamespaceCode);
gen_init_function ctx output_cpp tcpp_class;
List.iter (gen_function ctx tcpp_class false) tcpp_class.tcl_functions;
List.iter (gen_function ctx tcpp_class true) tcpp_class.tcl_static_functions;
List.iter (gen_static_variable ctx tcpp_class) tcpp_class.tcl_static_variables;
output_cpp "\n";
gen_dynamic_function_allocator ctx output_cpp tcpp_class;
generate_native_constructor ctx output_cpp tcpp_class false;
gen_boot_field ctx output_cpp tcpp_class;
end_namespace output_cpp class_path;
cpp_file#close
let implicit_accessor_arg_count class_def accessor_name base_arity =
let field =
try Some (PMap.find accessor_name class_def.cl_fields)
with Not_found ->
(try Some (PMap.find accessor_name class_def.cl_statics) with Not_found -> None)
in
match field with
| Some cf ->
(match follow cf.cf_type with
| TFun (args, _) -> max 0 (List.length args - base_arity)
| _ -> 0)
| None -> 0
let implicit_getter_args class_def field =
let n = implicit_accessor_arg_count class_def ("get_" ^ field.cf_name) 0 in
String.concat ", " (List.init n (fun _ -> "null()"))
let implicit_setter_args class_def field =
let n = implicit_accessor_arg_count class_def ("set_" ^ field.cf_name) 1 in
String.concat "" (List.init n (fun _ -> ", null()"))
let generate_managed_class base_ctx tcpp_class =
let common_ctx = base_ctx.ctx_common in
let class_def = tcpp_class.tcl_class in
let class_path = class_def.cl_path in
let debug = tcpp_class.tcl_debug_level in
let cpp_file = new_placed_cpp_file base_ctx.ctx_common class_path in
let cpp_ctx = file_context base_ctx cpp_file debug false in
let ctx = cpp_ctx in
let output_cpp = cpp_file#write in
let strq = strq ctx.ctx_common in
let scriptable = has_tcpp_class_flag tcpp_class Scriptable in
let class_super_name =
match class_def.cl_super with
| Some (klass, params) ->
tcpp_to_string_suffix "_obj" (cpp_instance_type ctx.ctx_common.basic klass params CppRetyper.with_stack_value_type)
| _ -> ""
in
cpp_file#write_h "#include <hxcpp.h>\n\n";
let all_referenced =
CppReferences.find_referenced_types ctx (TClassDecl class_def) ctx.ctx_super_deps
ctx.ctx_constructor_deps false false scriptable
in
List.iter (add_include cpp_file) all_referenced;
if scriptable then cpp_file#write_h "#include <hx/Scriptable.h>\n";
cpp_file#write_h "\n";
output_cpp (get_class_code class_def Meta.CppFileCode);
let includes = get_all_meta_string_path class_def.cl_meta Meta.CppInclude in
let printer inc = output_cpp ("#include \"" ^ inc ^ "\"\n") in
List.iter printer includes;
output_cpp "\n";
output_cpp "namespace {\n\n";
List.iter (gen_function_closures ctx tcpp_class false) tcpp_class.tcl_functions;
List.iter (gen_function_closures ctx tcpp_class true) tcpp_class.tcl_static_functions;
List.iter (gen_dynamic_function ctx tcpp_class false) tcpp_class.tcl_dynamic_functions;
List.iter (gen_dynamic_function ctx tcpp_class true) tcpp_class.tcl_static_dynamic_functions;
output_cpp "}\n\n";
begin_namespace output_cpp class_path;
output_cpp "\n";
output_cpp (get_class_code class_def Meta.CppNamespaceCode);
let class_name = tcpp_class.tcl_name in
let cargs = constructor_arg_var_list tcpp_class in
let constructor_var_list = List.map snd cargs in
let constructor_type_args =
cargs
|> List.map (fun (t, a) -> Printf.sprintf "%s %s" t a)
|> String.concat "," in
output_cpp
("void " ^ class_name ^ "::__construct(" ^ constructor_type_args ^ ")");
(match tcpp_class.tcl_constructor with
| Some constructor ->
(* Ensure we reset this real this ptr flag, it may have been set to false in the above gen_dynamic_function *)
ctx.ctx_real_this_ptr <- true;
let cb no_debug =
gen_cpp_function_body ctx class_def false "new" constructor "" ""
no_debug;
output_cpp "\n"
in
with_debug ctx constructor.tcf_field.cf_meta cb
| _ -> output_cpp " { }\n\n");
(* Destructor goes in the cpp file so we can "see" the full definition of the member vars *)
if not (has_class_flag class_def CAbstract) then (
let ptr_name = class_pointer class_def in
let array_arg_list inList =
List.init (List.length inList) (fun idx -> Printf.sprintf "inArgs[%i]" idx) |> String.concat ","
in
Printf.sprintf "::Dynamic %s::__CreateEmpty() { return new %s; }\n\n" class_name class_name |> output_cpp;
Printf.sprintf "void* %s::_hx_vtable = 0;\n\n" class_name |> output_cpp;
Printf.sprintf "::Dynamic %s::__Create(::hx::DynamicArray inArgs)\n" class_name |> output_cpp;
Printf.sprintf "{\n\t%s _hx_result = new %s();\n" ptr_name class_name |> output_cpp;
Printf.sprintf "\t_hx_result->__construct(%s);\n" (array_arg_list constructor_var_list) |> output_cpp;
output_cpp "\treturn _hx_result;\n}\n\n");
output_cpp ("bool " ^ class_name ^ "::_hx_isInstanceOf(int inClassId) {\n");
let rec parent_id_folder acc cur =
match cur.tcl_super with
| Some s -> parent_id_folder (cur.tcl_id :: acc) s
| None -> cur.tcl_id :: acc
in
let implemented_classes =
tcpp_class
|> parent_id_folder [ Int32.of_int 1 ]
|> List.sort compare
in
let txt cId = Printf.sprintf "0x%08lx" cId in
let rec dump_classes indent classes =
match classes with
| [] -> ()
| [ c ] -> output_cpp (indent ^ "return inClassId==(int)" ^ txt c ^ ";\n")
| [ c; c1 ] ->
output_cpp
(indent ^ "return inClassId==(int)" ^ txt c ^ " || inClassId==(int)" ^ txt c1 ^ ";\n")
| _ ->
let len = List.length classes in
let mid = List.nth classes (len / 2) in
let low, high = List.partition (fun e -> e <= mid) classes in
output_cpp (indent ^ "if (inClassId<=(int)" ^ txt mid ^ ") {\n");
dump_classes (indent ^ "\t") low;
output_cpp (indent ^ "} else {\n");
dump_classes (indent ^ "\t") high;
output_cpp (indent ^ "}\n")
in
dump_classes "\t" implemented_classes;
output_cpp "}\n\n";
if List.length tcpp_class.tcl_haxe_interfaces > 0 then (
let cname = cpp_interface_impl_name class_def in
let impl_name = cpp_class_name class_def in
let fold_interface (glued, acc) interface =
let rec gen_interface_funcs interface =
let fold_field (glued, acc) func =
let cast = cpp_tfun_signature false func.iff_args func.iff_return in
let real_name = cpp_member_name_of func.iff_field in
(* C++ can't work out which function it needs to take the addrss of
when the implementation is overloaded - currently the map-set functions.
Change the castKey to force a glue function in this case (could double-cast the pointer, but it is ugly)
*)
let suffix =
match interface.if_class.cl_path with
| (["haxe"], "IMap") when real_name = "set" -> "*"
| _ -> "" in
let cast_key = Printf.sprintf "%s::%s%s" real_name cast suffix in
let implementation_key = Printf.sprintf "%s::%s" real_name (find_class_implementation func tcpp_class) in
if cast_key = implementation_key then
(glued, Printf.sprintf "\t%s&%s::%s" cast impl_name real_name :: acc)
else
let glue = Printf.sprintf "%s_%08lx" func.iff_field.cf_name (gen_hash32 0 cast) in
let glued =
if StringMap.mem cast_key glued then
glued
else
let arg_list = print_retyped_tfun_arg_list true func.iff_args in
let return_type = tcpp_to_string func.iff_return in
let return_str = if return_type = "void" then "" else "return " in
let cpp_code =
Printf.sprintf
"%s %s::%s(%s) { %s%s(%s); }\n"
return_type
class_name
glue
arg_list
return_str
real_name
(print_arg_names func.iff_args) in
StringMap.add cast_key cpp_code glued
in
(glued, Printf.sprintf "\t%s&%s::%s" cast impl_name glue :: acc)
in
let initial =
match interface.if_extends with
| Some super -> gen_interface_funcs super
| _ -> (glued, [])
in
List.fold_left fold_field initial interface.if_functions
in
let interface_name = cpp_interface_impl_name interface.if_class in
let glued, funcs = gen_interface_funcs interface in
let combined = funcs |> List.rev |> String.concat ",\n" in
let call = Printf.sprintf "static %s %s_%s = {\n%s\n};\n" (cpp_class_name interface.if_class) cname interface_name combined in
(glued, call :: acc)
in
let glued, calls =
List.fold_left
fold_interface
(StringMap.empty, [])
tcpp_class.tcl_haxe_interfaces in
calls |> String.concat "\n" |> output_cpp;
glued |> StringMap.bindings |> List.map snd |> String.concat "\n" |> output_cpp;
output_cpp ("void *" ^ class_name ^ "::_hx_getInterface(int inHash) {\n");
output_cpp "\tswitch(inHash) {\n";
let iter interface =
output_cpp ("\t\tcase (int)" ^ interface.if_hash ^ ": return &" ^ cname ^ "_" ^ cpp_interface_impl_name interface.if_class ^ ";\n") in
List.iter
iter
tcpp_class.tcl_haxe_interfaces;
output_cpp "\t}\n";
if class_super_name = "" then (
output_cpp "\t#ifdef HXCPP_SCRIPTABLE\n";
output_cpp "\treturn super::_hx_getInterface(inHash);\n";
output_cpp "\t#else\n";
output_cpp "\treturn 0;\n";
output_cpp "\t#endif\n")
else output_cpp "\treturn super::_hx_getInterface(inHash);\n";
output_cpp "}\n\n");
gen_init_function ctx output_cpp tcpp_class;
List.iter (gen_function ctx tcpp_class false) tcpp_class.tcl_functions;
List.iter (gen_function ctx tcpp_class true) tcpp_class.tcl_static_functions;
List.iter (gen_static_variable ctx tcpp_class) tcpp_class.tcl_static_variables;
output_cpp "\n";
gen_dynamic_function_allocator ctx output_cpp tcpp_class;
let inline_constructor =
can_inline_constructor base_ctx class_def
in
if (not inline_constructor) && not (has_class_flag class_def CAbstract) then
generate_constructor ctx output_cpp tcpp_class false;
(* Initialise non-static variables *)
output_cpp (class_name ^ "::" ^ class_name ^ "()\n{\n");
List.iter
(fun func -> output_cpp ("\t" ^ func.tcf_name ^ " = new __default_" ^ func.tcf_name ^ "(this);\n"))
tcpp_class.tcl_dynamic_functions;
output_cpp "}\n\n";
if tcpp_class.tcl_container = Some Current then (
let rec find_next_super_iteration cls =
match cls.tcl_super with
| Some ({ tcl_container = Some Current } as super) ->
Some (tcpp_to_string_suffix "_obj" (cpp_instance_type ctx.ctx_common.basic super.tcl_class super.tcl_params CppRetyper.with_stack_value_type))
| Some super ->
find_next_super_iteration super
| None ->
None
in
let super_needs_iteration = find_next_super_iteration tcpp_class in
let smart_class_name = snd class_path in
let dump_field_iterator macro var =
Printf.sprintf "\t%s(%s, \"%s\");\n" macro var.tcv_name var.tcv_field.cf_name |> output_cpp
in
(* MARK function - explicitly mark all child pointers *)
output_cpp ("void " ^ class_name ^ "::__Mark(HX_MARK_PARAMS)\n{\n");
output_cpp ("\tHX_MARK_BEGIN_CLASS(" ^ smart_class_name ^ ");\n");
List.iter (dump_field_iterator "HX_MARK_MEMBER_NAME") tcpp_class.tcl_variables;
(match super_needs_iteration with
| None -> ()
| Some super -> output_cpp ("\t" ^ super ^ "::__Mark(HX_MARK_ARG);\n"));
output_cpp "\tHX_MARK_END_CLASS();\n";
output_cpp "}\n\n";
(* Visit function - explicitly visit all child pointers *)
output_cpp ("void " ^ class_name ^ "::__Visit(HX_VISIT_PARAMS)\n{\n");
List.iter (dump_field_iterator "HX_VISIT_MEMBER_NAME") tcpp_class.tcl_variables;
(match super_needs_iteration with
| None -> ()
| Some super -> output_cpp ("\t" ^ super ^ "::__Visit(HX_VISIT_ARG);\n"));
output_cpp "}\n\n");
let dump_quick_field_test fields =
if List.length fields > 0 then (
let len = function _, l, _ -> l in
let sfields = List.sort (fun f1 f2 -> len f1 - len f2) fields in
let len_case = ref (-1) in
output_cpp "\tswitch(inName.length) {\n";
List.iter
(fun (field, l, result) ->
if l <> !len_case then (
if !len_case >= 0 then output_cpp "\t\tbreak;\n";
output_cpp ("\tcase " ^ string_of_int l ^ ":\n");
len_case := l);
output_cpp
("\t\tif (HX_FIELD_EQ(inName,\""
^ StringHelper.s_escape field
^ "\") ) { " ^ result ^ " }\n"))
sfields;
output_cpp "\t}\n")
in
let checkPropCall field =
if
Meta.has Meta.NativeProperty class_def.cl_meta
|| Meta.has Meta.NativeProperty field.cf_meta
|| Gctx.defined common_ctx Define.ForceNativeProperty
then "inCallProp != ::hx::paccNever"
else "inCallProp == ::hx::paccAlways"
in
let get_wrapper field value =
match CppRetyper.cpp_type_of ctx.ctx_common.basic CppRetyper.with_promoted_value_type field.cf_type with
| TCppInst (t, _) as inst when Meta.has Meta.StructAccess t.cl_meta ->
Printf.sprintf "(::cpp::Struct< %s >) %s" (tcpp_to_string inst) value
| TCppStar _ ->
Printf.sprintf "(::cpp::Pointer<void*>) %s" value
| _ ->
value
in
let print_variable var_printer get_printer var acc =
if var.tcv_is_reflective && not (is_abstract_impl class_def) then
let variable = get_wrapper var.tcv_field var.tcv_name in
if var.tcv_has_getter then
let prop_check = checkPropCall var.tcv_field in
let getter = Printf.sprintf "get_%s(%s)" var.tcv_field.cf_name (implicit_getter_args class_def var.tcv_field) |> get_wrapper var.tcv_field in
(var.tcv_field.cf_name, String.length var.tcv_field.cf_name, get_printer prop_check getter variable) :: acc
else
(var.tcv_field.cf_name, String.length var.tcv_field.cf_name, var_printer variable) :: acc
else
acc
in
let print_function printer func acc =
if func.tcf_is_reflective then
let ident = get_wrapper func.tcf_field func.tcf_name |> printer in
let length = String.length func.tcf_field.cf_name in
(func.tcf_field.cf_name, length, ident) :: acc
else
acc
in
let print_property printer var acc =
if var.tcv_has_getter && var.tcv_is_reflective && not (is_abstract_impl class_def) then (
let prop_check = checkPropCall var.tcv_field in
let getter = Printf.sprintf "get_%s(%s)" var.tcv_field.cf_name (implicit_getter_args class_def var.tcv_field) |> get_wrapper var.tcv_field in
(var.tcv_field.cf_name, String.length var.tcv_field.cf_name, printer prop_check getter) :: acc)
else
acc
in
let castable var =
match var.tcv_type with
| TCppInst (t, _) as inst when Meta.has Meta.StructAccess t.cl_meta ->
"cpp::Struct< " ^ tcpp_to_string inst ^ " > "
| TCppStar (t, _) ->
"cpp::Pointer< " ^ tcpp_to_string t ^ " >"
| other ->
tcpp_to_string other
in
if has_tcpp_class_flag tcpp_class MemberGet then (
(* Dynamic "Get" Field function - string version *)
Printf.sprintf "::hx::Val %s::__Field(const ::String &inName,::hx::PropertyAccess inCallProp)\n{\n" class_name |> output_cpp;
let var_printer ident = Printf.sprintf "return ::hx::Val( %s );" ident in
let get_printer check getter ident = Printf.sprintf "return ::hx::Val( %s ? %s : %s );" check getter ident in
let fun_printer ident = Printf.sprintf "return ::hx::Val( %s_dyn() );" ident in
let prop_printer check ident = Printf.sprintf "if (%s) { return ::hx::Val( %s ); }" check ident in
let all_fields = []
|> List.fold_right (print_variable var_printer get_printer) tcpp_class.tcl_variables
|> List.fold_right (print_property prop_printer) tcpp_class.tcl_properties
|> List.fold_right (print_function fun_printer) tcpp_class.tcl_functions in
if List.length all_fields > 0 then (
dump_quick_field_test all_fields;
output_cpp "\treturn super::__Field(inName,inCallProp);\n}\n\n");
);
if has_tcpp_class_flag tcpp_class StaticGet then (
Printf.sprintf "bool %s::__GetStatic(const ::String &inName, ::Dynamic &outValue, ::hx::PropertyAccess inCallProp)\n{\n" class_name |> output_cpp;
let var_printer ident = Printf.sprintf "outValue = %s; return true;" ident in
let get_printer check getter ident = Printf.sprintf "outValue = %s ? %s : %s; return true;" check getter ident in
let fun_printer ident = Printf.sprintf "outValue = %s_dyn(); return true;" ident in
let prop_printer check ident = Printf.sprintf "if (%s) { outValue = %s; return true; }" check ident in
let all_fields = []
|> List.fold_right (print_variable var_printer get_printer) tcpp_class.tcl_static_variables
|> List.fold_right (print_property prop_printer) tcpp_class.tcl_static_properties
|> List.fold_right (print_function fun_printer) tcpp_class.tcl_static_functions in
dump_quick_field_test all_fields;
output_cpp "\treturn false;\n}\n\n");
if has_tcpp_class_flag tcpp_class MemberSet then (
Printf.sprintf "::hx::Val %s::__SetField(const ::String& inName, const ::hx::Val& inValue, ::hx::PropertyAccess inCallProp)\n{\n" class_name |> output_cpp;
let fold_variable var acc =
if var.tcv_is_reflective && not (is_abstract_impl class_def) then
let casted = castable var in
let default = if var.tcv_is_gc_element then
Printf.sprintf "_hx_set_%s(HX_CTX_GET, inValue.Cast< %s >()); return inValue;" var.tcv_name casted
else
Printf.sprintf "%s = inValue.Cast< %s >(); return inValue;" var.tcv_name casted in
match var.tcv_field.cf_kind with
| Var { v_write = AccCall | AccPrivateCall } ->
let prop_call = checkPropCall var.tcv_field in
let setter = Printf.sprintf "set_%s" var.tcv_field.cf_name |> get_wrapper var.tcv_field in
let call = Printf.sprintf "if (%s) { return ::hx::Val( %s(inValue.Cast< %s >()%s) ); } else { %s }" prop_call setter casted (implicit_setter_args class_def var.tcv_field) default in
(var.tcv_field.cf_name, String.length var.tcv_field.cf_name, call) :: acc
| Var { v_write = AccNormal | AccNo | AccNever } ->
(var.tcv_field.cf_name, String.length var.tcv_field.cf_name, default) :: acc
| _ ->
acc
else
acc
in
let fold_property var acc =
if var.tcv_is_reflective && not (is_abstract_impl class_def) then
let casted = castable var in
match var.tcv_field.cf_kind with
| Var { v_write = AccCall | AccPrivateCall } ->
let prop_call = checkPropCall var.tcv_field in
let setter = Printf.sprintf "set_%s" var.tcv_field.cf_name |> get_wrapper var.tcv_field in
let call = Printf.sprintf "if (%s) { return ::hx::Val( %s(inValue.Cast< %s >()%s) ); }" prop_call setter casted (implicit_setter_args class_def var.tcv_field) in
(var.tcv_field.cf_name, String.length var.tcv_field.cf_name, call) :: acc
| _ ->
acc
else
acc
in
let all_fields = []
|> List.fold_right fold_variable tcpp_class.tcl_variables
|> List.fold_right fold_property tcpp_class.tcl_properties in
dump_quick_field_test all_fields;
output_cpp "\treturn super::__SetField(inName,inValue,inCallProp);\n}\n\n");
if has_tcpp_class_flag tcpp_class StaticSet then (
Printf.sprintf "bool %s::__SetStatic(const ::String& inName, ::Dynamic& ioValue, ::hx::PropertyAccess inCallProp)\n{\n" class_name |> output_cpp;
let fold_variable (var:tcpp_class_variable) acc =
if var.tcv_is_reflective && not (is_abstract_impl class_def) then
let casted = castable var in
match var.tcv_field.cf_kind with
| Var { v_write = AccCall | AccPrivateCall } ->
let prop_call = checkPropCall var.tcv_field in
let setter = Printf.sprintf "set_%s" var.tcv_field.cf_name |> get_wrapper var.tcv_field in
let call = Printf.sprintf "if (%s) { ioValue = %s(ioValue.Cast< %s >()%s); } else { %s = ioValue.Cast< %s >(); } return true;" prop_call setter casted (implicit_setter_args class_def var.tcv_field) var.tcv_name casted in
(var.tcv_field.cf_name, String.length var.tcv_field.cf_name, call) :: acc
| Var { v_write = AccNormal | AccNo } ->
(var.tcv_field.cf_name, String.length var.tcv_field.cf_name, Printf.sprintf "%s = ioValue.Cast< %s >(); return true;" var.tcv_name casted) :: acc
| _ ->
acc
else
acc
in
let fold_property var acc =
if var.tcv_is_reflective && not (is_abstract_impl class_def) then
match var.tcv_field.cf_kind with
| Var { v_write = AccCall | AccPrivateCall } ->
let prop_call = checkPropCall var.tcv_field in
let setter = Printf.sprintf "set_%s" var.tcv_field.cf_name |> get_wrapper var.tcv_field in
let casted = castable var in
(var.tcv_field.cf_name, String.length var.tcv_field.cf_name, Printf.sprintf "if (%s) { ioValue = %s(ioValue.Cast< %s >()%s); }" prop_call setter casted (implicit_setter_args class_def var.tcv_field)) :: acc
| _ ->
acc
else
acc
in
let all_fields = []
|> List.fold_right fold_variable tcpp_class.tcl_static_variables
|> List.fold_right fold_property tcpp_class.tcl_static_properties in
dump_quick_field_test all_fields;
output_cpp "\treturn false;\n}\n\n");
(* For getting a list of data members (eg, for serialization) *)
if has_tcpp_class_flag tcpp_class GetFields then (
let append var acc = (strq var.tcv_field.cf_name |> Printf.sprintf "\toutFields->push(%s);") :: acc in
let fields =
[ "\tsuper::__GetFields(outFields);" ]
|> List.fold_right append tcpp_class.tcl_variables
|> List.fold_right append tcpp_class.tcl_properties
|> String.concat "\n" in
Printf.sprintf "void %s::__GetFields(::Array< ::String >& outFields)\n{\n%s\n}\n\n" class_name fields |> output_cpp);
let storage field =
match cpp_type_of ctx.ctx_common.basic field.cf_type with
| TCppScalar "bool" -> "::hx::fsBool"
| TCppScalar "int" -> "::hx::fsInt"
| TCppScalar "Float" -> "::hx::fsFloat"
| TCppString -> "::hx::fsString"
| o when is_object_element o ->
"::hx::fsObject" ^ " /* " ^ tcpp_to_string o ^ " */ "
| u -> "::hx::fsUnknown" ^ " /* " ^ tcpp_to_string u ^ " */ "
in
let dump_member_storage (var:tcpp_class_variable) =
Printf.sprintf
"\t{ %s, (int)offsetof(%s, %s), %s },\n" (storage var.tcv_field) class_name var.tcv_name (strq var.tcv_field.cf_name) |> output_cpp
in
let dump_static_storage (var:tcpp_class_variable) =
Printf.sprintf "\t{ %s, (void*) &%s::%s, %s },\n" (storage var.tcv_field) class_name var.tcv_name (strq var.tcv_field.cf_name) |> output_cpp
in
output_cpp "#ifdef HXCPP_SCRIPTABLE\n";
if List.length tcpp_class.tcl_variables > 0 then (
Printf.sprintf "static ::hx::StorageInfo %s_sMemberStorageInfo[] = {\n" class_name |> output_cpp;
List.iter dump_member_storage tcpp_class.tcl_variables;
output_cpp "\t{ ::hx::fsUnknown, 0, null()}\n};\n")
else
Printf.sprintf "static ::hx::StorageInfo* %s_sMemberStorageInfo = 0;\n" class_name |> output_cpp;
if List.length tcpp_class.tcl_static_variables > 0 then (
Printf.sprintf "static ::hx::StaticInfo %s_sStaticStorageInfo[] = {\n" class_name |> output_cpp;
List.iter dump_static_storage tcpp_class.tcl_static_variables;
output_cpp "\t{ ::hx::fsUnknown, 0, null()}\n};\n")
else
Printf.sprintf "static ::hx::StaticInfo* %s_sStaticStorageInfo = 0;\n" class_name |> output_cpp;
output_cpp "#endif\n\n";
(match print_reflective_fields ctx.ctx_common class_def tcpp_class.tcl_variables tcpp_class.tcl_functions with
| Some str ->
Printf.sprintf "static ::String %s_sMemberFields[] = {\n%s\n};\n\n" class_name str |> output_cpp
| None ->
Printf.sprintf "static ::String* %s_sMemberFields = 0;\n\n" class_name |> output_cpp);
if List.length tcpp_class.tcl_static_variables > 0 then (
let dump_field_iterator macro var =
Printf.sprintf "\t%s(%s::%s, \"%s\");" macro class_name var.tcv_name var.tcv_field.cf_name
in
(* Mark static variables as used *)
let marks =
tcpp_class.tcl_static_variables
|> List.map (dump_field_iterator "HX_MARK_MEMBER_NAME")
|> String.concat "\n" in
Printf.sprintf "static void %s_sMarkStatics(HX_MARK_PARAMS) { \n%s\n };\n\n" class_name marks |> output_cpp;
(* Visit static variables *)
let visits =
tcpp_class.tcl_static_variables
|> List.map (dump_field_iterator "HX_VISIT_MEMBER_NAME")
|> String.concat "\n" in
output_cpp "#ifdef HXCPP_VISIT_ALLOCS\n";
Printf.sprintf "static void %s_sVisitStatics(HX_VISIT_PARAMS) { \n%s\n };\n\n" class_name visits |> output_cpp;
output_cpp "#endif\n\n");
let generate_script_function isStatic field scriptName callName =
let isTemplated = not isStatic in
if isTemplated then output_cpp "\ntemplate<bool _HX_SUPER=false>";
output_cpp
("\nstatic void CPPIA_CALL " ^ scriptName
^ "(::hx::CppiaCtx *ctx) {\n");
let script_return_type = CppCppia.to_script_type field.tcf_return in
(match field.tcf_return with
| TCppVoid ->
()
| TCppMarshalNativeType (native_type, _) ->
Printf.sprintf "ctx->return%s(%s(" (CppCppia.to_script_type_string script_return_type) (TCppMarshalNativeType (native_type, Reference) |> tcpp_to_string) |> output_cpp
| _ ->
Printf.sprintf "ctx->return%s(" (CppCppia.to_script_type_string script_return_type) |> output_cpp);
let dump_call cast =
if isStatic then
Printf.sprintf "%s::%s(" class_name callName |> output_cpp
else
Printf.sprintf "((%s*)ctx->getThis())->%s%s(" class_name cast callName |> output_cpp;
let folder (signature, sep, size) (var, expr) =
let script_type =
match CppCppia.to_script_type var.tcppv_type with
| (CppCppia.ScriptInt | CppCppia.ScriptFloat | CppCppia.ScriptBool) when expr <> None -> CppCppia.ScriptObject
| other -> other
in
Printf.sprintf "%sctx->get%s(%s)" sep (CppCppia.to_script_type_string script_type) size |> output_cpp;
signature ^ CppCppia.to_script_type_signature script_type,
",",
size ^ "+sizeof(" ^ CppCppia.to_script_type_size script_type ^ ")"
in
let signature, _, _ =
List.fold_left folder (CppCppia.to_script_type_signature script_return_type, "", "sizeof(void*)") field.tcf_args
in
output_cpp ")";
signature
in
let signature =
if isTemplated then (
output_cpp " _HX_SUPER ? ";
ignore (dump_call (class_name ^ "::"));
output_cpp " : ";
dump_call "")
else dump_call ""
in
(match field.tcf_return with
| TCppVoid ->
()
| TCppMarshalNativeType (native_type, _) ->
output_cpp "))"
| _ ->
output_cpp ")");
output_cpp ";\n}\n";
signature
in
if scriptable then (
let dump_script_func idx func =
let args = print_arg_list func.tcf_args "" in
let return_type = tcpp_to_string func.tcf_return in
let ret = if return_type = "Void" || return_type = "void" then " " else "return " in
let vtable = Printf.sprintf "__scriptVTable[%i]" (idx + 1) in
Printf.sprintf "\t%s %s(%s) {\n" return_type func.tcf_name args |> output_cpp;
Printf.sprintf ("\tif (%s) {\n") vtable |> output_cpp;
output_cpp "\t\t::hx::CppiaCtx *__ctx = ::hx::CppiaCtx::getCurrent();\n";
output_cpp "\t\t::hx::AutoStack __as(__ctx);\n";
output_cpp ("\t\t__ctx->pushObject( this );\n");
let wrap var =
match var.tcppv_type with
| TCppMarshalNativeType (native_type, _) ->
Printf.sprintf "%s(%s)" (tcpp_to_string (TCppMarshalNativeType (native_type, Reference))) var.tcppv_name
| _ ->
var.tcppv_name
in
func.tcf_args
|> List.map
(fun (var, expr) ->
let script_type =
match CppCppia.to_script_type var.tcppv_type with
| (CppCppia.ScriptInt | CppCppia.ScriptFloat | CppCppia.ScriptBool) when expr <> None -> CppCppia.ScriptObject
| other -> other
in
Printf.sprintf "\t\t__ctx->push%s(%s);" (CppCppia.to_script_type_string script_type) (wrap var))
|> String.concat "\n"
|> output_cpp;
output_cpp "\n";
output_cpp ("\t\t" ^ ret ^ "__ctx->run" ^ (func.tcf_return |> CppCppia.to_script_type |> CppCppia.to_script_type_string) ^ "(" ^ vtable ^ ");\n");