-
Notifications
You must be signed in to change notification settings - Fork 2
/
gencommon.ml
11359 lines (9884 loc) · 412 KB
/
gencommon.ml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
(*
* Copyright (C)2005-2013 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*)
(*
Gen Common API
This module intends to be a common set of utilities common to all targets.
It's intended to provide a set of tools to be able to make targets in Haxe more easily, and to
allow the programmer to have more control of how the target language will handle the program.
For example, as of now, the hxcpp target, while greatly done, relies heavily on cpp's own operator
overloading, and implicit conversions, which make it very hard to deliver a similar solution for languages
that lack these features.
So this little framework is here so you can manipulate the Haxe AST and start bringing the AST closer
to how it's intenteded to be in your host language.
Rules
Design goals
Naming convention
Weaknesses and TODO's
*)
open Unix
open Ast
open Type
open Common
open Option
open Printf
open ExtString
let debug_type_ctor = function
| TMono _ -> "TMono"
| TEnum _ -> "TEnum"
| TInst _ -> "TInst"
| TType _ -> "TType"
| TFun _ -> "TFun"
| TAnon _ -> "TAnon"
| TDynamic _ -> "TDynamic"
| TLazy _ -> "TLazy"
| TAbstract _ -> "TAbstract"
let debug_type = (s_type (print_context()))
let debug_expr = s_expr debug_type
let rec like_float t =
match follow t with
| TAbstract({ a_path = ([], "Float") },[])
| TAbstract({ a_path = ([], "Int") },[]) -> true
| TAbstract({ a_path = (["cs"], "Pointer") },_) -> false
| TAbstract(a, _) -> List.exists (fun t -> like_float t) a.a_from || List.exists (fun t -> like_float t) a.a_to
| _ -> false
let rec like_int t =
match follow t with
| TAbstract({ a_path = ([], "Int") },[]) -> true
| TAbstract({ a_path = (["cs"], "Pointer") },_) -> false
| TAbstract(a, _) -> List.exists (fun t -> like_int t) a.a_from || List.exists (fun t -> like_int t) a.a_to
| _ -> false
let rec like_i64 t =
match follow t with
| TInst({ cl_path = (["cs"], "Int64") },[])
| TAbstract({ a_path = (["cs"], "Int64") },[])
| TInst({ cl_path = (["cs"], "UInt64") },[])
| TInst({ cl_path = (["java"], "Int64") },[])
| TAbstract({ a_path = (["java"], "Int64") },[])
| TInst({ cl_path = (["haxe"], "Int64") },[])
| TAbstract({ a_path = (["haxe"], "Int64") },[]) -> true
| TAbstract(a, _) -> List.exists (fun t -> like_i64 t) a.a_from || List.exists (fun t -> like_i64 t) a.a_to
| _ -> false
let follow_once t =
match t with
| TMono r ->
(match !r with
| Some t -> t
| _ -> t_dynamic (* avoid infinite loop / should be the same in this context *))
| TLazy f ->
!f()
| TType (t,tl) ->
apply_params t.t_params tl t.t_type
| _ -> t
let t_empty = TAnon({ a_fields = PMap.empty; a_status = ref (Closed) })
let tmp_count = ref 0
let reset_temps () = tmp_count := 0
(* the undefined is a special var that works like null, but can have special meaning *)
let v_undefined = alloc_var "__undefined__" t_dynamic
let undefined pos = { eexpr = TLocal(v_undefined); etype = t_dynamic; epos = pos }
module ExprHashtblHelper =
struct
type hash_texpr_t =
{
hepos : pos;
heexpr : int;
hetype : int;
}
let mk_heexpr = function
| TConst _ -> 0 | TLocal _ -> 1 | TArray _ -> 3 | TBinop _ -> 4 | TField _ -> 5 | TTypeExpr _ -> 7 | TParenthesis _ -> 8 | TObjectDecl _ -> 9
| TArrayDecl _ -> 10 | TCall _ -> 11 | TNew _ -> 12 | TUnop _ -> 13 | TFunction _ -> 14 | TVar _ -> 15 | TBlock _ -> 16 | TFor _ -> 17 | TIf _ -> 18 | TWhile _ -> 19
| TSwitch _ -> 20 (* | TPatMatch _ -> 21 *) | TTry _ -> 22 | TReturn _ -> 23 | TBreak -> 24 | TContinue -> 25 | TThrow _ -> 26 | TCast _ -> 27 | TMeta _ -> 28 | TEnumParameter _ -> 29
let mk_heetype = function
| TMono _ -> 0 | TEnum _ -> 1 | TInst _ -> 2 | TType _ -> 3 | TFun _ -> 4
| TAnon _ -> 5 | TDynamic _ -> 6 | TLazy _ -> 7 | TAbstract _ -> 8
let mk_type e =
{
hepos = e.epos;
heexpr = mk_heexpr e.eexpr;
hetype = mk_heetype e.etype;
}
end;;
let path_of_md_def md_def =
match md_def.m_types with
| [TClassDecl c] -> c.cl_path
| _ -> md_def.m_path
open ExprHashtblHelper;;
(* Expression Hashtbl. This shouldn't be kept indefinately as it's not a weak Hashtbl. *)
module ExprHashtbl = Hashtbl.Make(
struct
type t = Type.texpr
let equal = (==)
let hash t = Hashtbl.hash (mk_type t)
end
);;
(* ******************************************* *)
(* Gen Common
This is the key module for generation of Java and C# sources
In order for both modules to share as much code as possible, some
rules were devised:
- every feature has its own submodule, and may contain the following methods:
- configure
sets all the configuration variables for the module to run. If a module has this method,
it *should* be called once before running any filter
- run_filter ->
runs the filter immediately on the context
- add_filter ->
adds the filter to an expr->expr list. Most filter modules will provide this option so the filter
function can only run once.
- most submodules will have side-effects so the order of operations will matter.
When running configure / add_filter this might be taken care of with the rule-based dispatch system working
underneath, but still there might be some incompatibilities. There will be an effort to document it.
The modules can hint on the order by suffixing their functions with _first or _last.
- any of those methods might have different parameters, that configure how the filter will run.
For example, a simple filter that maps switch() expressions to if () .. else if... might receive
a function that filters what content should be mapped
- Other targets can use those filters on their own code. In order to do that,
a simple configuration step is needed: you need to initialize a generator_ctx type with
Gencommon.new_gen (context:Common.context)
with a generator_ctx context you will be able to add filters to your code, and execute them with
Gencommon.run_filters (gen_context:Gencommon.generator_ctx)
After running the filters, you can run your own generator normally.
(* , or you can run
Gencommon.generate_modules (gen_context:Gencommon.generator_ctx) (extension:string) (module_gen:module_type list->bool)
where module_gen will take a whole module (can be *)
*)
(* ******************************************* *)
(* common helpers *)
(* ******************************************* *)
let assertions = false (* when assertions == true, many assertions will be made to guarantee the quality of the data input *)
let debug_mode = ref false
let trace s = if !debug_mode then print_endline s else ()
let timer name = if !debug_mode then Common.timer name else fun () -> ()
let is_string t = match follow t with | TInst({ cl_path = ([], "String") }, []) -> true | _ -> false
(* helper function for creating Anon types of class / enum modules *)
let anon_of_classtype cl =
TAnon {
a_fields = cl.cl_statics;
a_status = ref (Statics cl)
}
let anon_of_enum e =
TAnon {
a_fields = PMap.empty;
a_status = ref (EnumStatics e)
}
let anon_of_abstract a =
TAnon {
a_fields = PMap.empty;
a_status = ref (AbstractStatics a)
}
let anon_of_mt mt = match mt with
| TClassDecl cl -> anon_of_classtype cl
| TEnumDecl e -> anon_of_enum e
| TAbstractDecl a -> anon_of_abstract a
| _ -> assert false
let anon_class t =
match follow t with
| TAnon anon ->
(match !(anon.a_status) with
| Statics (cl) -> Some(TClassDecl(cl))
| EnumStatics (e) -> Some(TEnumDecl(e))
| AbstractStatics (a) -> Some(TAbstractDecl(a))
| _ -> None)
| _ -> None
let path_s path =
match path with | ([], s) -> s | (p, s) -> (String.concat "." (fst path)) ^ "." ^ (snd path)
let rec t_to_md t = match t with
| TInst (cl,_) -> TClassDecl cl
| TEnum (e,_) -> TEnumDecl e
| TType (t,_) -> TTypeDecl t
| TAbstract (a,_) -> TAbstractDecl a
| TAnon anon ->
(match !(anon.a_status) with
| EnumStatics e -> TEnumDecl e
| Statics cl -> TClassDecl cl
| AbstractStatics a -> TAbstractDecl a
| _ -> assert false)
| TLazy f -> t_to_md (!f())
| TMono r -> (match !r with | Some t -> t_to_md t | None -> assert false)
| _ -> assert false
let get_cl mt = match mt with | TClassDecl cl -> cl | _ -> failwith ("Unexpected module type of '" ^ path_s (t_path mt) ^ "'")
let get_abstract mt = match mt with | TAbstractDecl a -> a | _ -> failwith ("Unexpected module type of '" ^ path_s (t_path mt) ^ "'")
let get_tdef mt = match mt with | TTypeDecl t -> t | _ -> assert false
let mk_mt_access mt pos = { eexpr = TTypeExpr(mt); etype = anon_of_mt mt; epos = pos }
let is_void t = match follow t with
| TAbstract ({ a_path = ([], "Void") },[]) ->
true
| _ -> false
let mk_local var pos = { eexpr = TLocal(var); etype = var.v_type; epos = pos }
(* this function is used by CastDetection module *)
let get_fun t =
match follow t with | TFun(r1,r2) -> (r1,r2) | _ -> (trace (s_type (print_context()) (follow t) )); assert false
let mk_cast t e =
{ eexpr = TCast(e, None); etype = t; epos = e.epos }
let mk_classtype_access cl pos =
{ eexpr = TTypeExpr(TClassDecl(cl)); etype = anon_of_classtype cl; epos = pos }
let mk_static_field_access_infer cl field pos params =
try
let cf = (PMap.find field cl.cl_statics) in
{ eexpr = TField(mk_classtype_access cl pos, FStatic(cl, cf)); etype = (if params = [] then cf.cf_type else apply_params cf.cf_params params cf.cf_type); epos = pos }
with | Not_found -> failwith ("Cannot find field " ^ field ^ " in type " ^ (path_s cl.cl_path))
let mk_static_field_access cl field fieldt pos =
{ (mk_static_field_access_infer cl field pos []) with etype = fieldt }
(* stolen from Hugh's sources ;-) *)
(* this used to be a class, but there was something in there that crashed ocaml native compiler in windows *)
module SourceWriter =
struct
type source_writer =
{
sw_buf : Buffer.t;
mutable sw_has_content : bool;
mutable sw_indent : string;
mutable sw_indents : string list;
}
let new_source_writer () =
{
sw_buf = Buffer.create 0;
sw_has_content = false;
sw_indent = "";
sw_indents = [];
}
let add_writer w_write w_read = Buffer.add_buffer w_read.sw_buf w_write.sw_buf
let contents w = Buffer.contents w.sw_buf
let len w = Buffer.length w.sw_buf
let write w x =
(if not w.sw_has_content then begin w.sw_has_content <- true; Buffer.add_string w.sw_buf w.sw_indent; Buffer.add_string w.sw_buf x; end else Buffer.add_string w.sw_buf x);
let len = (String.length x)-1 in
if len >= 0 && String.get x len = '\n' then begin w.sw_has_content <- false end else w.sw_has_content <- true
let push_indent w = w.sw_indents <- "\t"::w.sw_indents; w.sw_indent <- String.concat "" w.sw_indents
let pop_indent w =
match w.sw_indents with
| h::tail -> w.sw_indents <- tail; w.sw_indent <- String.concat "" w.sw_indents
| [] -> w.sw_indent <- "/*?*/"
let newline w = write w "\n"
let begin_block w = (if w.sw_has_content then newline w); write w "{"; push_indent w; newline w
let end_block w = pop_indent w; (if w.sw_has_content then newline w); write w "}"; newline w
let print w =
(if not w.sw_has_content then begin w.sw_has_content <- true; Buffer.add_string w.sw_buf w.sw_indent end);
bprintf w.sw_buf;
end;;
(* rule_dispatcher's priority *)
type priority =
| PFirst
| PLast
| PZero
| PCustom of float
exception DuplicateName of string
exception NoRulesApplied
let indent = ref []
(* the rule dispatcher is the primary way to deal with distributed "plugins" *)
(* we will define rules that will form a distributed / extensible match system *)
class ['tp, 'ret] rule_dispatcher name ignore_not_found =
object(self)
val tbl = Hashtbl.create 16
val mutable keys = []
val names = Hashtbl.create 16
val mutable temp = 0
method add ?(name : string option) (* name helps debugging *) ?(priority : priority = PZero) (rule : 'tp->'ret option) =
let p = match priority with
| PFirst -> infinity
| PLast -> neg_infinity
| PZero -> 0.0
| PCustom i -> i
in
let q = if not( Hashtbl.mem tbl p ) then begin
let q = Stack.create() in
Hashtbl.add tbl p q;
keys <- p :: keys;
keys <- List.sort (fun x y -> - (compare x y)) keys;
q
end else Hashtbl.find tbl p in
let name = match name with
| None -> temp <- temp + 1; "$_" ^ (string_of_int temp)
| Some s -> s
in
(if Hashtbl.mem names name then raise (DuplicateName(name)));
Hashtbl.add names name q;
Stack.push (name, rule) q
method describe =
Hashtbl.iter (fun s _ -> (trace s)) names;
method remove (name : string) =
if Hashtbl.mem names name then begin
let q = Hashtbl.find names name in
let q_temp = Stack.create () in
Stack.iter (function
| (n, _) when n = name -> ()
| _ as r -> Stack.push r q_temp
) q;
Stack.clear q;
Stack.iter (fun r -> Stack.push r q) q_temp;
Hashtbl.remove names name;
true
end else false
method run_f tp = get (self#run tp)
method did_run tp = is_some (self#run tp)
method get_list =
let ret = ref [] in
List.iter (fun key ->
let q = Hashtbl.find tbl key in
Stack.iter (fun (_, rule) -> ret := rule :: !ret) q
) keys;
List.rev !ret
method run_from (priority:float) (tp:'tp) : 'ret option =
let ok = ref ignore_not_found in
let ret = ref None in
indent := "\t" :: !indent;
(try begin
List.iter (fun key ->
if key < priority then begin
let q = Hashtbl.find tbl key in
Stack.iter (fun (n, rule) ->
let t = if !debug_mode then Common.timer ("rule dispatcher rule: " ^ n) else fun () -> () in
let r = rule(tp) in
t();
if is_some r then begin ret := r; raise Exit end
) q
end
) keys
end with Exit -> ok := true);
(match !indent with
| [] -> ()
| h::t -> indent := t);
(if not (!ok) then raise NoRulesApplied);
!ret
method run (tp:'tp) : 'ret option =
self#run_from infinity tp
end;;
(* this is a special case where tp = tret and you stack their output as the next's input *)
class ['tp] rule_map_dispatcher name =
object(self)
inherit ['tp, 'tp] rule_dispatcher name true as super
method run_f tp = get (self#run tp)
method run_from (priority:float) (tp:'tp) : 'ret option =
let cur = ref tp in
(try begin
List.iter (fun key ->
if key < priority then begin
let q = Hashtbl.find tbl key in
Stack.iter (fun (n, rule) ->
trace ("running rule " ^ n);
let t = if !debug_mode then Common.timer ("rule map dispatcher rule: " ^ n) else fun () -> () in
let r = rule(!cur) in
t();
if is_some r then begin cur := get r end
) q
end
) keys
end with Exit -> ());
Some (!cur)
end;;
type generator_ctx =
{
(* these are the basic context fields. If another target is using this context, *)
(* this is all you need to care about *)
mutable gcon : Common.context;
gclasses : gen_classes;
gtools : gen_tools;
(*
configurable function that receives a desired name and makes it "internal", doing the best
to ensure that it will not be called from outside.
To avoid name clashes between internal names, user must specify two strings: a "namespace" and the name itself
*)
mutable gmk_internal_name : string->string->string;
(*
module filters run before module filters and they should generate valid haxe syntax as a result.
Module filters shouldn't go through the expressions as it adds an unnecessary burden to the GC,
and it can all be done in a single step with gexpr_filters and proper priority selection.
As a convention, Module filters should end their name with Modf, so they aren't mistaken with expression filters
*)
gmodule_filters : (module_type) rule_map_dispatcher;
(*
expression filters are the most common filters to be applied.
They should also generate only valid haxe expressions, so e.g. calls to non-existant methods
should be avoided, although there are some ways around them (like gspecial_methods)
*)
gexpr_filters : (texpr) rule_map_dispatcher;
(*
syntax filters are also expression filters but they no longer require
that the resulting expressions be valid haxe expressions.
They then have no guarantee that either the input expressions or the output one follow the same
rules as normal haxe code.
*)
gsyntax_filters : (texpr) rule_map_dispatcher;
(* these are more advanced features, but they would require a rewrite of targets *)
(* they are just helpers to ditribute functions like "follow" or "type to string" *)
(* so adding a module will already take care of correctly following a certain type of *)
(* variable, for example *)
(* follows the type through typedefs, lazy typing, etc. *)
(* it's the place to put specific rules to handle typedefs, like *)
(* other basic types like UInt *)
gfollow : (t, t) rule_dispatcher;
gtypes : (path, module_type) Hashtbl.t;
mutable gtypes_list : module_type list;
mutable gmodules : Type.module_def list;
(* cast detection helpers / settings *)
(* this is a cache for all field access types *)
greal_field_types : (path * string, (tclass_field (* does the cf exist *) * t (*cf's type in relation to current class type params *) * t * tclass (* declared class *) ) option) Hashtbl.t;
(* this function allows any code to handle casts as if it were inside the cast_detect module *)
mutable ghandle_cast : t->t->texpr->texpr;
(* when an unsafe cast is made, we can warn the user *)
mutable gon_unsafe_cast : t->t->pos->unit;
(* does this type needs to be boxed? Normally always false, unless special type handling must be made *)
mutable gneeds_box : t->bool;
(* does this 'special type' needs cast to this other type? *)
(* this is here so we can implement custom behavior for "opaque" typedefs *)
mutable gspecial_needs_cast : t->t->bool;
(* sometimes we may want to support unrelated conversions on cast detection *)
(* for example, haxe.lang.Null<T> -> T on C# *)
(* every time an unrelated conversion is found, each to/from path is searched on this hashtbl *)
(* if found, the function will be executed with from_type, to_type. If returns true, it means that *)
(* it is a supported conversion, and the unsafe cast routine changes to a simple cast *)
gsupported_conversions : (path, t->t->bool) Hashtbl.t;
(* API for filters *)
(* add type can be called at any time, and will add a new module_def that may or may not be filtered *)
(* module_type -> should_filter *)
mutable gadd_type : module_type -> bool -> unit;
(* during expr filters, add_to_module will be available so module_types can be added to current module_def. we must pass the priority argument so the filters can be resumed *)
mutable gadd_to_module : module_type -> float -> unit;
(* during expr filters, shows the current class path *)
mutable gcurrent_path : path;
(* current class *)
mutable gcurrent_class : tclass option;
(* current class field, if any *)
mutable gcurrent_classfield : tclass_field option;
(* events *)
(* is executed once every new classfield *)
mutable gon_classfield_start : (unit -> unit) list;
(* is executed once every new module type *)
mutable gon_new_module_type : (unit -> unit) list;
(* after module filters ended *)
mutable gafter_mod_filters_ended : (unit -> unit) list;
(* after expression filters ended *)
mutable gafter_expr_filters_ended : (unit -> unit) list;
(* after all filters are run *)
mutable gafter_filters_ended : (unit -> unit) list;
mutable gbase_class_fields : (string, tclass_field) PMap.t;
(* real type is the type as it is read by the target. *)
(* This function is here because most targets don't have *)
(* a 1:1 translation between haxe types and its native types *)
(* But types aren't changed to this representation as we might lose *)
(* some valuable type information in the process *)
mutable greal_type : t -> t;
(*
the same as greal_type but for type parameters.
*)
mutable greal_type_param : module_type -> tparams -> tparams;
(*
is the type a value type?
This may be used in some optimizations where reference types and value types
are handled differently. At first the default is very good to use, and if tweaks are needed,
it's best to be done by adding @:struct meta to the value types
*
mutable gis_value_type : t -> bool;*)
(* misc configuration *)
(*
Should the target allow type parameter dynamic conversion,
or should we add a cast to those cases as well?
*)
mutable gallow_tp_dynamic_conversion : bool;
(*
Does the target support type parameter constraints?
If not, they will be ignored when detecting casts
*)
mutable guse_tp_constraints : bool;
(* internal apis *)
(* param_func_call : used by TypeParams and CastDetection *)
mutable gparam_func_call : texpr->texpr->tparams->texpr list->texpr;
(* does it already have a type parameter cast handler? This is used by CastDetect to know if it should handle type parameter casts *)
mutable ghas_tparam_cast_handler : bool;
(* type parameter casts - special cases *)
(* function cast_from, cast_to -> texpr *)
gtparam_cast : (path, (texpr->t->texpr)) Hashtbl.t;
(*
special vars are used for adding special behavior to
*)
gspecial_vars : (string, bool) Hashtbl.t;
}
and gen_classes =
{
cl_reflect : tclass;
cl_type : tclass;
cl_dyn : tclass;
t_iterator : tdef;
mutable nativearray_len : texpr -> pos -> texpr;
mutable nativearray_type : Type.t -> Type.t;
mutable nativearray : Type.t -> Type.t;
}
(* add here all reflection transformation additions *)
and gen_tools =
{
(* (klass : texpr, t : t) : texpr *)
mutable r_create_empty : texpr->t->texpr;
(* Reflect.fields(). The bool is if we are iterating in a read-only manner. If it is read-only we might not need to allocate a new array *)
mutable r_fields : bool->texpr->texpr;
(* (first argument = return type. should be void in most cases) Reflect.setField(obj, field, val) *)
mutable r_set_field : t->texpr->texpr->texpr->texpr;
(* Reflect.field. bool indicates if is safe (no error throwing) or unsafe; t is the expected return type true = safe *)
mutable r_field : bool->t->texpr->texpr->texpr;
(*
these are now the functions that will later be used when creating the reflection classes
*)
(* on the default implementation (at OverloadingCtors), it will be new SomeClass<params>(EmptyInstance) *)
mutable rf_create_empty : tclass->tparams->pos->texpr;
}
let get_type types path =
List.find (fun md -> match md with
| TClassDecl cl when cl.cl_path = path -> true
| TEnumDecl e when e.e_path = path -> true
| TTypeDecl t when t.t_path = path -> true
| TAbstractDecl a when a.a_path = path -> true
| _ -> false
) types
let new_ctx con =
let types = Hashtbl.create (List.length con.types) in
List.iter (fun mt ->
match mt with
| TClassDecl cl -> Hashtbl.add types cl.cl_path mt
| TEnumDecl e -> Hashtbl.add types e.e_path mt
| TTypeDecl t -> Hashtbl.add types t.t_path mt
| TAbstractDecl a -> Hashtbl.add types a.a_path mt
) con.types;
let cl_dyn = match get_type con.types ([], "Dynamic") with
| TClassDecl c -> c
| TAbstractDecl a ->
mk_class a.a_module ([], "Dynamic") a.a_pos
| _ -> assert false
in
let rec gen = {
gcon = con;
gclasses = {
cl_reflect = get_cl (get_type con.types ([], "Reflect"));
cl_type = get_cl (get_type con.types ([], "Type"));
cl_dyn = cl_dyn;
t_iterator = get_tdef (get_type con.types ([], "Iterator"));
nativearray = (fun _ -> assert false);
nativearray_type = (fun _ -> assert false);
nativearray_len = (fun _ -> assert false);
};
gtools = {
r_create_empty = (fun eclass t ->
let fieldcall = mk_static_field_access_infer gen.gclasses.cl_type "createEmptyInstance" eclass.epos [t] in
{ eexpr = TCall(fieldcall, [eclass]); etype = t; epos = eclass.epos }
);
r_fields = (fun is_used_only_by_iteration expr ->
let fieldcall = mk_static_field_access_infer gen.gclasses.cl_reflect "fields" expr.epos [] in
{ eexpr = TCall(fieldcall, [expr]); etype = gen.gcon.basic.tarray gen.gcon.basic.tstring; epos = expr.epos }
);
(* Reflect.setField(obj, field, val). t by now is ignored. FIXME : fix this implementation *)
r_set_field = (fun t obj field v ->
let fieldcall = mk_static_field_access_infer gen.gclasses.cl_reflect "setField" v.epos [] in
{ eexpr = TCall(fieldcall, [obj; field; v]); etype = t_dynamic; epos = v.epos }
);
(* Reflect.field. bool indicates if is safe (no error throwing) or unsafe. true = safe *)
r_field = (fun is_safe t obj field ->
let fieldcall = mk_static_field_access_infer gen.gclasses.cl_reflect "field" obj.epos [] in
(* FIXME: should we see if needs to cast? *)
mk_cast t { eexpr = TCall(fieldcall, [obj; field]); etype = t_dynamic; epos = obj.epos }
);
rf_create_empty = (fun cl p pos ->
gen.gtools.r_create_empty { eexpr = TTypeExpr(TClassDecl cl); epos = pos; etype = t_dynamic } (TInst(cl,p))
); (* TODO: Maybe implement using normal reflection? Type.createEmpty(MyClass) *)
};
gmk_internal_name = (fun ns s -> sprintf "__%s_%s" ns s);
gexpr_filters = new rule_map_dispatcher "gexpr_filters";
gmodule_filters = new rule_map_dispatcher "gmodule_filters";
gsyntax_filters = new rule_map_dispatcher "gsyntax_filters";
gfollow = new rule_dispatcher "gfollow" false;
gtypes = types;
gtypes_list = con.types;
gmodules = con.modules;
greal_field_types = Hashtbl.create 0;
ghandle_cast = (fun to_t from_t e -> mk_cast to_t e);
gon_unsafe_cast = (fun t t2 pos -> (gen.gcon.warning ("Type " ^ (debug_type t2) ^ " is being cast to the unrelated type " ^ (s_type (print_context()) t)) pos));
gneeds_box = (fun t -> false);
gspecial_needs_cast = (fun to_t from_t -> true);
gsupported_conversions = Hashtbl.create 0;
gadd_type = (fun md should_filter ->
if should_filter then begin
gen.gtypes_list <- md :: gen.gtypes_list;
gen.gmodules <- { m_id = alloc_mid(); m_path = (t_path md); m_types = [md]; m_extra = module_extra "" "" 0. MFake } :: gen.gmodules;
Hashtbl.add gen.gtypes (t_path md) md;
end else gen.gafter_filters_ended <- (fun () ->
gen.gtypes_list <- md :: gen.gtypes_list;
gen.gmodules <- { m_id = alloc_mid(); m_path = (t_path md); m_types = [md]; m_extra = module_extra "" "" 0. MFake } :: gen.gmodules;
Hashtbl.add gen.gtypes (t_path md) md;
) :: gen.gafter_filters_ended;
);
gadd_to_module = (fun md pr -> failwith "module added outside expr filters");
gcurrent_path = ([],"");
gcurrent_class = None;
gcurrent_classfield = None;
gon_classfield_start = [];
gon_new_module_type = [];
gafter_mod_filters_ended = [];
gafter_expr_filters_ended = [];
gafter_filters_ended = [];
gbase_class_fields = PMap.empty;
greal_type = (fun t -> t);
greal_type_param = (fun _ t -> t);
gallow_tp_dynamic_conversion = false;
guse_tp_constraints = false;
(* as a default, ignore the params *)
gparam_func_call = (fun ecall efield params elist -> { ecall with eexpr = TCall(efield, elist) });
ghas_tparam_cast_handler = false;
gtparam_cast = Hashtbl.create 0;
gspecial_vars = Hashtbl.create 0;
} in
(*gen.gtools.r_create_empty <-
gen.gtools.r_get_class <-
gen.gtools.r_fields <- *)
gen
let init_ctx gen =
(* ultimately add a follow once handler as the last follow handler *)
let follow_f = gen.gfollow#run in
let follow t =
match t with
| TMono r ->
(match !r with
| Some t -> follow_f t
| _ -> Some t)
| TLazy f ->
follow_f (!f())
| TType (t,tl) ->
follow_f (apply_params t.t_params tl t.t_type)
| _ -> Some t
in
gen.gfollow#add ~name:"final" ~priority:PLast follow
(* run_follow (gen:generator_ctx) (t:t) *)
let run_follow gen = gen.gfollow#run_f
let reorder_modules gen =
let modules = Hashtbl.create 20 in
List.iter (fun md ->
Hashtbl.add modules ( (t_infos md).mt_module ).m_path md
) gen.gtypes_list;
gen.gmodules <- [];
let processed = Hashtbl.create 20 in
Hashtbl.iter (fun md_path md ->
if not (Hashtbl.mem processed md_path) then begin
Hashtbl.add processed md_path true;
gen.gmodules <- { m_id = alloc_mid(); m_path = md_path; m_types = List.rev ( Hashtbl.find_all modules md_path ); m_extra = (t_infos md).mt_module.m_extra } :: gen.gmodules
end
) modules
let run_filters_from gen t filters =
match t with
| TClassDecl c ->
trace (snd c.cl_path);
gen.gcurrent_path <- c.cl_path;
gen.gcurrent_class <- Some(c);
List.iter (fun fn -> fn()) gen.gon_new_module_type;
gen.gcurrent_classfield <- None;
let rec process_field f =
reset_temps();
gen.gcurrent_classfield <- Some(f);
List.iter (fun fn -> fn()) gen.gon_classfield_start;
trace f.cf_name;
(match f.cf_expr with
| None -> ()
| Some e ->
f.cf_expr <- Some (List.fold_left (fun e f -> f e) e filters));
List.iter process_field f.cf_overloads;
in
List.iter process_field c.cl_ordered_fields;
List.iter process_field c.cl_ordered_statics;
(match c.cl_constructor with
| None -> ()
| Some f -> process_field f);
gen.gcurrent_classfield <- None;
(match c.cl_init with
| None -> ()
| Some e ->
c.cl_init <- Some (List.fold_left (fun e f -> f e) e filters));
| TEnumDecl _ -> ()
| TTypeDecl _ -> ()
| TAbstractDecl _ -> ()
let run_filters gen =
let last_error = gen.gcon.error in
let has_errors = ref false in
gen.gcon.error <- (fun msg pos -> has_errors := true; last_error msg pos);
(* first of all, we have to make sure that the filters won't trigger a major Gc collection *)
let t = Common.timer "gencommon_filters" in
(if Common.defined gen.gcon Define.GencommonDebug then debug_mode := true else debug_mode := false);
let run_filters filter =
let rec loop acc mds =
match mds with
| [] -> acc
| md :: tl ->
let filters = [ filter#run_f ] in
let added_types = ref [] in
gen.gadd_to_module <- (fun md_type priority ->
gen.gtypes_list <- md_type :: gen.gtypes_list;
added_types := (md_type, priority) :: !added_types
);
run_filters_from gen md filters;
let added_types = List.map (fun (t,p) ->
run_filters_from gen t [ fun e -> get (filter#run_from p e) ];
if Hashtbl.mem gen.gtypes (t_path t) then begin
let rec loop i =
let p = t_path t in
let new_p = (fst p, snd p ^ "_" ^ (string_of_int i)) in
if Hashtbl.mem gen.gtypes new_p then
loop (i+1)
else
match t with
| TClassDecl cl -> cl.cl_path <- new_p
| TEnumDecl e -> e.e_path <- new_p
| TTypeDecl _ | TAbstractDecl _ -> ()
in
loop 0
end;
Hashtbl.add gen.gtypes (t_path t) t;
t
) !added_types in
loop (added_types @ (md :: acc)) tl
in
List.rev (loop [] gen.gtypes_list)
in
let run_mod_filter filter =
let last_add_to_module = gen.gadd_to_module in
let added_types = ref [] in
gen.gadd_to_module <- (fun md_type priority ->
Hashtbl.add gen.gtypes (t_path md_type) md_type;
added_types := (md_type, priority) :: !added_types
);
let rec loop processed not_processed =
match not_processed with
| hd :: tl ->
(match hd with
| TClassDecl c ->
gen.gcurrent_class <- Some c
| _ ->
gen.gcurrent_class <- None);
let new_hd = filter#run_f hd in
let added_types_new = !added_types in
added_types := [];
let added_types = List.map (fun (t,p) ->
get (filter#run_from p t)
) added_types_new in
loop ( added_types @ (new_hd :: processed) ) tl
| [] ->
processed
in
let filtered = loop [] gen.gtypes_list in
gen.gadd_to_module <- last_add_to_module;
gen.gtypes_list <- List.rev (filtered)
in
run_mod_filter gen.gmodule_filters;
List.iter (fun fn -> fn()) gen.gafter_mod_filters_ended;
let last_add_to_module = gen.gadd_to_module in
gen.gtypes_list <- run_filters gen.gexpr_filters;
gen.gadd_to_module <- last_add_to_module;
List.iter (fun fn -> fn()) gen.gafter_expr_filters_ended;
(* Codegen.post_process gen.gtypes_list [gen.gexpr_filters#run_f]; *)
gen.gtypes_list <- run_filters gen.gsyntax_filters;
List.iter (fun fn -> fn()) gen.gafter_filters_ended;
reorder_modules gen;
t();
if !has_errors then raise (Abort("Compilation aborted with errors",null_pos))
(* ******************************************* *)
(* basic generation module that source code compilation implementations can use *)
(* ******************************************* *)
let write_file gen w source_dir path extension out_files =
let t = timer "write file" in
let s_path = source_dir ^ "/" ^ (snd path) ^ "." ^ (extension) in
(* create the folders if they don't exist *)
mkdir_from_path s_path;
let contents = SourceWriter.contents w in
let should_write = if not (Common.defined gen.gcon Define.ReplaceFiles) && Sys.file_exists s_path then begin
let in_file = open_in s_path in
let old_contents = Std.input_all in_file in
close_in in_file;
contents <> old_contents
end else true in
if should_write then begin
let f = open_out_bin s_path in
output_string f contents;
close_out f
end;
out_files := (unique_full_path s_path) :: !out_files;
t()
let clean_files path excludes verbose =
let rec iter_files pack dir path = try
let file = Unix.readdir dir in
if file <> "." && file <> ".." then begin
let filepath = path ^ "/" ^ file in
if (Unix.stat filepath).st_kind = S_DIR then
let pack = pack @ [file] in
iter_files (pack) (Unix.opendir filepath) filepath;
try Unix.rmdir filepath with Unix.Unix_error (ENOTEMPTY,_,_) -> ();
else if not (String.ends_with filepath ".meta") && not (List.mem (unique_full_path filepath) excludes) then begin
if verbose then print_endline ("Removing " ^ filepath);
Sys.remove filepath