-
Notifications
You must be signed in to change notification settings - Fork 2
/
parser.ml
3158 lines (2946 loc) · 97.5 KB
/
parser.ml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
(*
* Copyright (C)2005-2013 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*)
open Ast
type error_msg =
| Unexpected of token
| Duplicate_default
| Missing_semicolon
| Unclosed_macro
| Unimplemented
| Missing_type
| Custom of string
exception Error of error_msg * pos
exception TypePath of string list * (string * bool) option * bool (* in import *)
exception Display of expr
exception ContinueClassField of expr * token
exception BreakBlock
let error_msg = function
| Unexpected t -> "Unexpected "^(s_token t)
| Duplicate_default -> "Duplicate default"
| Missing_semicolon -> "Missing ;"
| Unclosed_macro -> "Unclosed macro"
| Unimplemented -> "Not implemented for current platform"
| Missing_type -> "Missing type declaration"
| Custom s -> s
let error m p = raise (Error (m,p))
let display_error : (error_msg -> pos -> unit) ref = ref (fun _ _ -> assert false)
let quoted_ident_prefix = "@$__hx__"
let quote_ident s =
quoted_ident_prefix ^ s
let unquote_ident f =
let pf = quoted_ident_prefix in
let pflen = String.length pf in
let is_quoted = String.length f >= pflen && String.sub f 0 pflen = pf in
let s = if is_quoted then String.sub f pflen (String.length f - pflen) else f in
let is_valid = not is_quoted || try
for i = 0 to String.length s - 1 do
match String.unsafe_get s i with
| 'a'..'z' | 'A'..'Z' | '_' -> ()
| '0'..'9' when i > 0 -> ()
| _ -> raise Exit
done;
if Hashtbl.mem Lexer.keywords s then raise Exit;
true
with Exit ->
false
in
s,is_quoted,is_valid
let cache = ref (DynArray.create())
let last_doc = ref None
let use_doc = ref false
let use_parser_resume = ref true
let resume_display = ref null_pos
let in_macro = ref false
let last_token s =
let n = Stream.count s in
DynArray.get (!cache) (if n = 0 then 0 else n - 1)
let serror() = raise (Stream.Error "")
let do_resume() = !resume_display <> null_pos
let display e = raise (Display e)
let type_path sl in_import = match sl with
| n :: l when n.[0] >= 'A' && n.[0] <= 'Z' -> raise (TypePath (List.rev l,Some (n,false),in_import));
| _ -> raise (TypePath (List.rev sl,None,in_import))
let is_resuming p =
let p2 = !resume_display in
p.pmax = p2.pmin && !use_parser_resume && Common.unique_full_path p.pfile = p2.pfile
let set_resume p =
resume_display := { p with pfile = Common.unique_full_path p.pfile }
let is_dollar_ident e = match fst e with
| EConst (Ident n) when n.[0] = '$' ->
true
| _ ->
false
let precedence op =
let left = true and right = false in
match op with
| OpMod -> 0, left
| OpMult | OpDiv -> 1, left
| OpAdd | OpSub -> 2, left
| OpShl | OpShr | OpUShr -> 3, left
| OpOr | OpAnd | OpXor -> 4, left
| OpEq | OpNotEq | OpGt | OpLt | OpGte | OpLte -> 5, left
| OpInterval -> 6, left
| OpBoolAnd -> 7, left
| OpBoolOr -> 8, left
| OpArrow -> 9, right
| OpAssign | OpAssignOp _ -> 10, right
let is_not_assign = function
| OpAssign | OpAssignOp _ -> false
| _ -> true
let swap op1 op2 =
let p1, left1 = precedence op1 in
let p2, _ = precedence op2 in
left1 && p1 <= p2
let rec make_binop op e ((v,p2) as e2) =
match v with
| EBinop (_op,_e,_e2) when swap op _op ->
let _e = make_binop op e _e in
EBinop (_op,_e,_e2) , punion (pos _e) (pos _e2)
| ETernary (e1,e2,e3) when is_not_assign op ->
let e = make_binop op e e1 in
ETernary (e,e2,e3) , punion (pos e) (pos e3)
| _ ->
EBinop (op,e,e2) , punion (pos e) (pos e2)
let rec make_unop op ((v,p2) as e) p1 =
match v with
| EBinop (bop,e,e2) -> EBinop (bop, make_unop op e p1 , e2) , (punion p1 p2)
| ETernary (e1,e2,e3) -> ETernary (make_unop op e1 p1 , e2, e3), punion p1 p2
| _ ->
EUnop (op,Prefix,e), punion p1 p2
let rec make_meta name params ((v,p2) as e) p1 =
match v with
| EBinop (bop,e,e2) -> EBinop (bop, make_meta name params e p1 , e2) , (punion p1 p2)
| ETernary (e1,e2,e3) -> ETernary (make_meta name params e1 p1 , e2, e3), punion p1 p2
| _ ->
EMeta((name,params,p1),e),punion p1 p2
(* vv extended syntax vv *)
let use_extended_syntax = ref false
let out_of_order_exprs:expr list ref = ref []
let out_of_order_cfs:class_field list ref = ref []
let for_ctx = ref []
let push_for_ctx a = for_ctx := a :: !for_ctx
let pop_for_ctx() = match !for_ctx with
| [] -> ()
| x::xs -> for_ctx := xs
let peek_for_ctx() = match !for_ctx with
| [] -> None
| x::xs -> x
let warning : (string -> pos -> unit) ref = ref (fun _ _ -> assert false)
(* for debugging purpose *)
let dump_n_token n s =
if !use_extended_syntax then
let p = ref null_pos in
match Stream.npeek n s with
| [] -> ()
| x::xs ->
let m=List.map(fun (t,p2) -> p:=punion !p p2; ("< " ^ (s_token t) ^ " >")) (x::xs) in
!warning (String.concat " " m) !p
let var_id = ref 0
let mk_fresh_name ?(sfx="") pfx =
let i = !var_id in
var_id := i + 1;
pfx ^ (string_of_int i) ^ sfx
let struct_var_name_prefix = "__st"
let struct_global_var_marker = "$st$"
let flags_stack = ref []
let current_flag = ref 0
let noDbldotFlag = 1
let parseOptTypeFlag = 2
let fieldsDeclarationFlag = 4
let ccDefinedFlag = 8
let hasLocalAccessFlag = 16
let initInCCFlag = 32
let discardPossibleClassFieldMemberFlag = 64
let s_flag f =
let is f v = (f land v)<>0 in
let cl f v = f land (lnot v) in
let rec loop acc f =
if is f noDbldotFlag then loop ("noDbldotFlag"::acc) (cl f noDbldotFlag)
else if is f parseOptTypeFlag then loop ("parseOptTypeFlag"::acc) (cl f parseOptTypeFlag)
else if is f fieldsDeclarationFlag then loop ("fieldsDeclarationFlag"::acc) (cl f fieldsDeclarationFlag)
else if is f ccDefinedFlag then loop ("ccDefinedFlag"::acc) (cl f ccDefinedFlag)
else if is f hasLocalAccessFlag then loop ("hasLocalAccessFlag"::acc) (cl f hasLocalAccessFlag)
else if is f initInCCFlag then loop ("initInCCFlag"::acc) (cl f initInCCFlag)
else if is f discardPossibleClassFieldMemberFlag then loop ("discardPossibleClassFieldMemberFlag"::acc) (cl f discardPossibleClassFieldMemberFlag)
else acc
in
let acc = loop [] f in
String.concat "|" acc
let get_flag() = !current_flag
let is_flag_set f = (!current_flag land f)<>0
let set_flag f = current_flag := !current_flag lor f
let clear_flag f = current_flag := !current_flag land (lnot f)
let push_flag f = set_flag f; flags_stack := !current_flag::!flags_stack
let push_not_flag f = clear_flag f; flags_stack := !current_flag::!flags_stack
let pop_flag() =
let f = match !flags_stack with
| [] -> 0
| x::xs -> flags_stack := xs; x
in
current_flag := f;
f
type destructure_name = string * pos
type destructure_elm = {
mutable name: string * string;
mutable globals_def: (destructure_name * destructure_name * expr) list;
mutable globals: (destructure_name * destructure_name) list;
mutable locals: (destructure_name * destructure_name) list;
mutable protected: bool;
mutable structures: destructure_elm list;
}
let mk_structure_elm n = {name=n; globals_def=[]; globals=[]; locals=[]; structures=[]; protected=false;}
let mk_ident n p = (EConst(Ident n), p)
let mk_string n p = (EConst(String n), p)
type cc_arg_mode =
| Read
| Write
type scope_def_from =
| SDFClass of string
| SDFFunction of string
| SDFOther
type field_type =
| NormalField
| LocalField
| PrivateField
let s_from = function
| SDFClass s -> "class "^s
| SDFFunction s -> "function "^s
| SDFOther -> "other"
type 'a def_value = {ht:(string , 'a) Hashtbl.t; parent:'a def_node; from:scope_def_from;mutable exprs:expr list}
and 'a def_node = Nil | DefValue of 'a def_value
type cc_arg = {
mutable arg: access list * pos * (string * bool * complex_type option * expr option);
is_mutable : bool;
mutable mode : field_type;
mutable use_cnt: int;
mutable meta: metadata;
}
type cc_field_def = {
ccfd_access: access list;
ccfd_meta: metadata;
ccfd_mutable: bool;
}
type cc_param = {
cc_open_par : pos;
cc_close_par : pos;
cc_params : type_param list;
cc_args : cc_arg list;
cc_access : access list;
}
type cc_info = {
mutable cc_param : cc_param option;
mutable cc_super_args : pos * expr list option;
}
let cc_arg_defs:'a def_value list ref = ref []
let cl_sym_defs:'a def_value list ref = ref []
let mk_def_value p f = {ht=Hashtbl.create 0; parent=p; from=f; exprs=[];}
let get_def_parent = function
| [] -> Nil
| x::xs -> DefValue x
let leave_scope s = if !use_extended_syntax then
match !s with
| [] -> ()
| x::xs -> s:=xs
let push s e = s:=e::!s
let enter_scope s f = if !use_extended_syntax then
push s (mk_def_value (get_def_parent !s) f)
let is_cc_scope = function
| {parent=Nil;from=_ as f; _} ->
(match f with
| SDFClass _ -> true
| _ -> false)
| _ -> false
let find_in_scope ?(deep=true) s n =
if !use_extended_syntax then
if not deep then
match !s with
| [] -> None
| x::xs ->
try Some(Hashtbl.find x.ht n)
with Not_found -> None
else
let rec loop = function
| [] -> None
| x::xs ->
try Some(Hashtbl.find x.ht n)
with Not_found -> loop xs
in loop !s
else None
let get_scope_for ?(deep=true) s n =
if !use_extended_syntax then
if not deep then
match !s with
| [] -> None
| x::xs ->
try
Hashtbl.find x.ht n;
Some(x)
with Not_found -> None
else
let rec loop = function
| [] -> None
| x::xs ->
try
Hashtbl.find x.ht n;
Some(x)
with Not_found -> loop xs
in loop !s
else None
let mk_this p = mk_ident "this" p
let mk_this_assign fn pfn =
let e_this = mk_this pfn in
let e_this = (EField (e_this, fn) , pfn) in
make_binop OpAssign e_this (mk_ident fn pfn)
let mk_call fn fa pfn = ECall (mk_ident fn pfn, fa), pfn
let mk_int i p = EConst (Int i), p
let parse_cc_opt_access = parser
| [< '(Kwd Private, _) >] -> [APrivate]
| [< '(Kwd Public, _) >] -> [APublic]
| [< >] -> [APublic]
let parse_cc_param_opt_access = parser
| [< '(Kwd Private, _) >] -> [APrivate]
| [< '(Kwd Public, _) >] -> [APublic]
| [< >] -> [APublic]
let parse_cc_param_opt_modifier = parser
| [< '(Kwd Var, _) >] -> NormalField, true
| [< '(Kwd KConst, _) >] -> NormalField, false
| [< '(Kwd Val, _) >] -> NormalField, false
| [< >] -> LocalField, false
let get_opt_name = function
| None -> "", null_pos
| Some(n, p) -> n, p
let mk_local_private v =
if v.mode=LocalField then begin
v.mode <- PrivateField;
let al, p, r = v.arg in
let al = List.filter(fun a -> a<>APublic && a<>APrivate) al in
let l = List.length al in
(*print_string ("mk private:"^(string_of_int l)^"\n");*)
v.meta <- (Meta.Private, [], p) :: v.meta;
v.arg <- (APrivate::al), p, r
end
let add_cl_sym_def ?(new_scope:scope_def_from option=None) ?(field_def:cc_field_def option=None) s p =
if !use_extended_syntax && not !in_macro then
let shadowing v pos opt_adder =
let tp = match v.arg with
| _,p,_ -> p
in
let printer file line = Printf.sprintf "%d:" line in
let tp = Lexer.get_error_pos printer tp in
if (v.use_cnt=0 && v.mode=LocalField) then begin
!warning (s ^ " is shadowing constructor parameter declared at " ^ tp) pos;
match opt_adder with
| Some(adder) -> adder()
| _ -> ()
end else begin
mk_local_private v;
error (Custom (s ^ " is overriding constructor parameter declared at " ^ tp)) pos
end
in
match field_def with
| None ->
let scope = cl_sym_defs in
let _ = match !scope with
| [] -> ()
| x::xs when s<>"" ->
(*println("try to add '"^s^" into "^(s_from x.from));*)
let add() = Hashtbl.add x.ht s p; in
if is_cc_scope x then begin
(*println("add_cl_sym_def:"^s);*)
let cf = find_in_scope cc_arg_defs s ~deep:false in
match cf with
| Some v ->
if not (v.mode=LocalField) then
let tp = match v.arg with
| _,p,_ -> p
in
let printer file line = Printf.sprintf "%d:" line in
let tp = Lexer.get_error_pos printer tp in
error (Custom ("can't redeclared constructor parameter " ^ s ^ " declared at " ^ tp)) p
else
shadowing v p (Some add)
| None -> add()
end else
let cf = find_in_scope cc_arg_defs s ~deep:false in
(match cf with
| Some v ->
let tp = match v.arg with
| _,p,_ -> p
in
let printer file line = Printf.sprintf "%d:" line in
let tp = Lexer.get_error_pos printer tp in
!warning (s ^ " is shadowing constructor parameter declared at " ^ tp) p;
add()
| None -> add())
| _ -> ()
in
(match new_scope with
| Some f -> enter_scope scope f
| _ -> ())
| Some {ccfd_access=_ as al; ccfd_mutable=_ as im; ccfd_meta=_ as meta} ->
let cf = find_in_scope cc_arg_defs s ~deep:false in
let add v = match !cc_arg_defs with x::xs -> (*println("adding in class field '"^s^" into "^(s_from x.from));*) Hashtbl.add x.ht s v | _ -> () in
(match cf with
| Some v ->
mk_local_private v;
shadowing v p None
| None -> add {arg=al, p ,(s, false, None, None);is_mutable=im;mode=NormalField;use_cnt=0;meta=meta;})
let exists_in_scope ?(deep=true) s n =
if (!use_extended_syntax) then
if not deep then
match !s with
| [] -> false
| x::xs -> Hashtbl.mem x.ht n
else
let rec loop = function
| [] -> false
| x::xs ->
if Hashtbl.mem x.ht n then true
else loop xs
in loop !s
else false
let use_def ?(check_scope=true) has_local_access s =
if (!use_extended_syntax && not !in_macro) then
let sv = if check_scope then find_in_scope cl_sym_defs s else None in
let cv = find_in_scope cc_arg_defs ~deep:false s in
(*print_string (s ^ " : " ^ (string_of_bool check_scope) ^ " , " ^ (string_of_bool has_local_access) ^ "\n");*)
let incr = match cv with
| Some cf ->
set_flag initInCCFlag;
(*print_string ("find in cc arg " ^ s ^ "[" ^ (s_flag !current_flag) ^ "\n");*)
if not has_local_access then begin
mk_local_private cf;
cf.use_cnt <- cf.use_cnt + 1;
end
| _ -> ()
in
match sv with
| None -> incr
| Some _ -> set_flag initInCCFlag
let use_cc_arg s m =
if (!use_extended_syntax && not !in_macro) then
match !cc_arg_defs with
| [] -> ()
| x::xs ->
try
let cf = Hashtbl.find x.ht s in
let v = get_scope_for cl_sym_defs s
in match v with
| None -> ()
| Some(v) when is_cc_scope v ->
(match m with
| Read -> cf.use_cnt <- cf.use_cnt + 1
| Write ->
if (cf.is_mutable) then
cf.use_cnt <- cf.use_cnt + 1
else
match cf.arg with
| _, p , (n, _, _, _) -> error (Custom ("can't write into immutable argument " ^ n)) p)
| _ -> ()
with Not_found -> ()
let mk_type pack name params sub =
{
tpackage = List.rev pack;
tname = name;
tparams = params;
tsub = sub;
}
let mk_type_inf pack =
mk_type pack "Dynamic" ([TPType(CTPath {tpackage=[];tname="_";tparams=[];tsub=None;})]) None
let mk_cc_fields fields =
let mk_field = function
| {arg=ac, p, (n, _, t, e); is_mutable=_ as im; meta=_ as m; _} ->
let t =
if t=None then Some(CTPath (mk_type_inf []))
else t
in
let k =
if (im) then FVar(t, e)
else FProp("default", "never", t, e)
in
{
cff_name = n;
cff_doc = None;
cff_meta = [(Meta.AllowWrite , [mk_ident "new" p], p)] @ m;
cff_access = ac;
cff_pos = p;
cff_kind = k;
}
in
List.map mk_field fields
let mk_cc_init cc p1 p2 =
let filter_field = function
| {mode=_ as m; _} -> m<>LocalField
in
let fields =
match cc with
| {cc_param=Some {cc_args=_ as ca; _}; _} -> ca
| _ -> []
in
let fields = List.filter filter_field fields in
let sp, cc_super_args, callsuper = match cc.cc_super_args with
| p, None -> p, [], false
| p, Some xs -> p, xs, true
in
let super_idents = List.filter(function | EConst(Ident _), _ -> true | _ -> false) cc_super_args in
(match cc.cc_param with
| None ->
(match super_idents with
| [] -> ()
| (EConst(Ident n), p1)::xs -> error (Custom ("undefined parameter " ^ n) ) p1
| _ -> ())
| Some(cp) ->
let exists_ident n = function
| {arg=(_, _ , (n1, _, _, _)); _} when (n1=n) -> true
| _ -> false
in
let check_ident = function
| EConst(Ident n), p1 when n<>"null"-> if (not (List.exists (exists_ident n) cp.cc_args)) then error (Custom ("undefined parameter " ^ n) ) p1
| _ -> ()
in
List.iter check_ident super_idents
);
let super =
if not callsuper then []
else let super = mk_call "super" cc_super_args sp in [super]
in
let mk_assign = function
| {arg=(_, p, (n, _, _, _)); _} -> mk_this_assign n p
in
let assigns = match cc.cc_param with
| None -> []
| Some(cp) -> (List.map mk_assign fields)
in
let code =
match !cc_arg_defs with
| x::_ ->
(*println("fields.len:"^string_of_int(List.length x.exprs));*)
let rec loop acc fields = match fields with
| [] -> acc
| y::ys ->
let i = List.length ys in
(*let call = mk_call ("if" ^ (string_of_int i)) [] null_pos in
loop (y::call::acc) ys *)
loop (y::acc) ys
in
let exprs = x.exprs in
x.exprs <- [];
loop [] exprs
| _ -> []
in
let init = super @ List.rev_append assigns code
in
let fields = mk_cc_fields fields in
let mk_new ac cp args p1 p2 =
let f =
{
f_params = cp;
f_args = args;
f_type = None;
f_expr = Some(EBlock init, p2);
}
in
{
cff_name = "new";
cff_doc = None;
cff_meta = [];
cff_access = ac;
cff_pos = punion p1 p2;
cff_kind = FFun f;
}
in
match cc.cc_param with
| None -> if (init == []) then fields else fields @ [mk_new [APublic] [] [] p1 p2]
| Some(cp) ->
let mk_arg = function
| {arg=(_, _, a); _} -> a
in
let args = List.map mk_arg cp.cc_args in
List.rev_append fields [mk_new cp.cc_access cp.cc_params args cp.cc_open_par cp.cc_close_par]
let add_cc_to_fields cc p1 p2 fl =
if (!use_extended_syntax) then
(mk_cc_init cc p1 p2) @ fl
else fl
(* ^^ extended syntax ^^ *)
let reify in_macro =
let cur_pos = ref None in
let mk_enum ename n vl p =
let constr = (EConst (Ident n),p) in
match vl with
| [] -> constr
| _ -> (ECall (constr,vl),p)
in
let to_const c p =
let cst n v = mk_enum "Constant" n [EConst (String v),p] p in
match c with
| Int i -> cst "CInt" i
| String s -> cst "CString" s
| Float s -> cst "CFloat" s
| Ident s -> cst "CIdent" s
| Regexp (r,o) -> mk_enum "Constant" "CRegexp" [(EConst (String r),p);(EConst (String o),p)] p
in
let rec to_binop o p =
let op n = mk_enum "Binop" n [] p in
match o with
| OpAdd -> op "OpAdd"
| OpMult -> op "OpMult"
| OpDiv -> op "OpDiv"
| OpSub -> op "OpSub"
| OpAssign -> op "OpAssign"
| OpEq -> op "OpEq"
| OpNotEq -> op "OpNotEq"
| OpGt -> op "OpGt"
| OpGte -> op "OpGte"
| OpLt -> op "OpLt"
| OpLte -> op "OpLte"
| OpAnd -> op "OpAnd"
| OpOr -> op "OpOr"
| OpXor -> op "OpXor"
| OpBoolAnd -> op "OpBoolAnd"
| OpBoolOr -> op "OpBoolOr"
| OpShl -> op "OpShl"
| OpShr -> op "OpShr"
| OpUShr -> op "OpUShr"
| OpMod -> op "OpMod"
| OpAssignOp o -> mk_enum "Binop" "OpAssignOp" [to_binop o p] p
| OpInterval -> op "OpInterval"
| OpArrow -> op "OpArrow"
in
let to_string s p =
let len = String.length s in
if len > 1 && s.[0] = '$' then
(EConst (Ident (String.sub s 1 (len - 1))),p)
else
(EConst (String s),p)
in
let to_array f a p =
(EArrayDecl (List.map (fun s -> f s p) a),p)
in
let to_null p =
(EConst (Ident "null"),p)
in
let to_opt f v p =
match v with
| None -> to_null p
| Some v -> f v p
in
let to_bool o p =
(EConst (Ident (if o then "true" else "false")),p)
in
let to_obj fields p =
(EObjectDecl fields,p)
in
let rec to_tparam t p =
let n, v = (match t with
| TPType t -> "TPType", to_ctype t p
| TPExpr e -> "TPExpr", to_expr e p
) in
mk_enum "TypeParam" n [v] p
and to_tpath t p =
let len = String.length t.tname in
if t.tpackage = [] && len > 1 && t.tname.[0] = '$' then
(EConst (Ident (String.sub t.tname 1 (len - 1))),p)
else begin
let fields = [
("pack", to_array to_string t.tpackage p);
("name", to_string t.tname p);
("params", to_array to_tparam t.tparams p);
] in
to_obj (match t.tsub with None -> fields | Some s -> fields @ ["sub",to_string s p]) p
end
and to_ctype t p =
let ct n vl = mk_enum "ComplexType" n vl p in
match t with
| CTPath { tpackage = []; tparams = []; tsub = None; tname = n } when n.[0] = '$' ->
to_string n p
| CTPath t -> ct "TPath" [to_tpath t p]
| CTFunction (args,ret) -> ct "TFunction" [to_array to_ctype args p; to_ctype ret p]
| CTAnonymous fields -> ct "TAnonymous" [to_array to_cfield fields p]
| CTParent t -> ct "TParent" [to_ctype t p]
| CTExtend (tl,fields) -> ct "TExtend" [to_array to_tpath tl p; to_array to_cfield fields p]
| CTOptional t -> ct "TOptional" [to_ctype t p]
and to_fun f p =
let farg (n,o,t,e) p =
let fields = [
"name", to_string n p;
"opt", to_bool o p;
"type", to_opt to_ctype t p;
] in
to_obj (match e with None -> fields | Some e -> fields @ ["value",to_expr e p]) p
in
let rec fparam t p =
let fields = [
"name", to_string t.tp_name p;
"constraints", to_array to_ctype t.tp_constraints p;
"params", to_array fparam t.tp_params p;
] in
to_obj fields p
in
let fields = [
("args",to_array farg f.f_args p);
("ret",to_opt to_ctype f.f_type p);
("expr",to_opt to_expr f.f_expr p);
("params",to_array fparam f.f_params p);
] in
to_obj fields p
and to_cfield f p =
let p = f.cff_pos in
let to_access a p =
let n = (match a with
| APublic -> "APublic"
| APrivate -> "APrivate"
| AStatic -> "AStatic"
| AOverride -> "AOverride"
| ADynamic -> "ADynamic"
| AInline -> "AInline"
| AMacro -> "AMacro"
) in
mk_enum "Access" n [] p
in
let to_kind k =
let n, vl = (match k with
| FVar (ct,e) -> "FVar", [to_opt to_ctype ct p;to_opt to_expr e p]
| FFun f -> "FFun", [to_fun f p]
| FProp (get,set,t,e) -> "FProp", [to_string get p; to_string set p; to_opt to_ctype t p; to_opt to_expr e p]
) in
mk_enum "FieldType" n vl p
in
let fields = [
Some ("name", to_string f.cff_name p);
(match f.cff_doc with None -> None | Some s -> Some ("doc", to_string s p));
(match f.cff_access with [] -> None | l -> Some ("access", to_array to_access l p));
Some ("kind", to_kind f.cff_kind);
Some ("pos", to_pos f.cff_pos);
(match f.cff_meta with [] -> None | l -> Some ("meta", to_meta f.cff_meta p));
] in
let fields = List.rev (List.fold_left (fun acc v -> match v with None -> acc | Some e -> e :: acc) [] fields) in
to_obj fields p
and to_meta m p =
to_array (fun (m,el,p) _ ->
let fields = [
"name", to_string (fst (Common.MetaInfo.to_string m)) p;
"params", to_expr_array el p;
"pos", to_pos p;
] in
to_obj fields p
) m p
and to_pos p =
match !cur_pos with
| Some p ->
p
| None ->
let file = (EConst (String p.pfile),p) in
let pmin = (EConst (Int (string_of_int p.pmin)),p) in
let pmax = (EConst (Int (string_of_int p.pmax)),p) in
if in_macro then
(EUntyped (ECall ((EConst (Ident "__dollar__mk_pos"),p),[file;pmin;pmax]),p),p)
else
to_obj [("file",file);("min",pmin);("max",pmax)] p
and to_expr_array a p = match a with
| [EMeta ((Meta.Dollar "a",[],_),e1),_] -> (match fst e1 with EArrayDecl el -> to_expr_array el p | _ -> e1)
| _ -> to_array to_expr a p
and to_expr e _ =
let p = snd e in
let expr n vl =
let e = mk_enum "ExprDef" n vl p in
to_obj [("expr",e);("pos",to_pos p)] p
in
let loop e = to_expr e (snd e) in
match fst e with
| EConst (Ident n) when n.[0] = '$' && String.length n > 1 ->
to_string n p
| EConst c ->
expr "EConst" [to_const c p]
| EArray (e1,e2) ->
expr "EArray" [loop e1;loop e2]
| EBinop (op,e1,e2) ->
expr "EBinop" [to_binop op p; loop e1; loop e2]
| EField (e,s) ->
expr "EField" [loop e; to_string s p]
| EParenthesis e ->
expr "EParenthesis" [loop e]
| EObjectDecl fl ->
expr "EObjectDecl" [to_array (fun (f,e) -> to_obj [("field",to_string f p);("expr",loop e)]) fl p]
| EArrayDecl el ->
expr "EArrayDecl" [to_expr_array el p]
| ECall (e,el) ->
expr "ECall" [loop e;to_expr_array el p]
| ENew (t,el) ->
expr "ENew" [to_tpath t p;to_expr_array el p]
| EUnop (op,flag,e) ->
let op = mk_enum "Unop" (match op with
| Increment -> "OpIncrement"
| Decrement -> "OpDecrement"
| Not -> "OpNot"
| Neg -> "OpNeg"
| NegBits -> "OpNegBits"
) [] p in
expr "EUnop" [op;to_bool (flag = Postfix) p;loop e]
| EVars vl ->
expr "EVars" [to_array (fun (v,t,e,m) p ->
let fields = [
"name", to_string v p;
"type", to_opt to_ctype t p;
"expr", to_opt to_expr e p;
] in
to_obj fields p
) vl p]
| EFunction (name,f) ->
let name = match name with
| None ->
to_null p
| Some name ->
if ExtString.String.starts_with name "inline_$" then begin
let real_name = (String.sub name 7 (String.length name - 7)) in
let e_name = to_string real_name p in
let e_inline = to_string "inline_" p in
let e_add = (EBinop(OpAdd,e_inline,e_name),p) in
e_add
end else
to_string name p
in
expr "EFunction" [name; to_fun f p]
| EBlock el ->
expr "EBlock" [to_expr_array el p]
| EFor (e1,e2) ->
expr "EFor" [loop e1;loop e2]
| EIn (e1,e2) ->
expr "EIn" [loop e1;loop e2]
| EIf (e1,e2,eelse) ->
expr "EIf" [loop e1;loop e2;to_opt to_expr eelse p]
| EWhile (e1,e2,flag) ->
expr "EWhile" [loop e1;loop e2;to_bool (flag = NormalWhile) p]
| ESwitch (e1,cases,def) ->
let scase (el,eg,e) p =
to_obj [("values",to_expr_array el p);"guard",to_opt to_expr eg p;"expr",to_opt to_expr e p] p
in
expr "ESwitch" [loop e1;to_array scase cases p;to_opt (to_opt to_expr) def p]
| ETry (e1,catches) ->
let scatch (n,t,e) p =
to_obj [("name",to_string n p);("type",to_ctype t p);("expr",loop e)] p
in
expr "ETry" [loop e1;to_array scatch catches p]
| EReturn eo ->
expr "EReturn" [to_opt to_expr eo p]
| EBreak ->
expr "EBreak" []
| EContinue ->
expr "EContinue" []
| EUntyped e ->
expr "EUntyped" [loop e]
| EThrow e ->
expr "EThrow" [loop e]
| ECast (e,ct) ->
expr "ECast" [loop e; to_opt to_ctype ct p]
| EDisplay (e,flag) ->
expr "EDisplay" [loop e; to_bool flag p]
| EDisplayNew t ->
expr "EDisplayNew" [to_tpath t p]
| ETernary (e1,e2,e3) ->
expr "ETernary" [loop e1;loop e2;loop e3]
| ECheckType (e1,ct) ->
expr "ECheckType" [loop e1; to_ctype ct p]
| EMeta ((m,ml,p),e1) ->
match m, ml with
| Meta.Dollar ("" | "e"), _ ->
e1
| Meta.Dollar "a", _ ->
expr "EArrayDecl" (match fst e1 with EArrayDecl el -> [to_expr_array el p] | _ -> [e1])
| Meta.Dollar "b", _ ->
expr "EBlock" [e1]
(* TODO: can $v and $i be implemented better? *)
| Meta.Dollar "v", _ ->
begin match fst e1 with
| EParenthesis (ECheckType (e2, CTPath{tname="String";tpackage=[]}),_) -> expr "EConst" [mk_enum "Constant" "CString" [e2] (pos e2)]
| EParenthesis (ECheckType (e2, CTPath{tname="Int";tpackage=[]}),_) -> expr "EConst" [mk_enum "Constant" "CInt" [e2] (pos e2)]
| EParenthesis (ECheckType (e2, CTPath{tname="Float";tpackage=[]}),_) -> expr "EConst" [mk_enum "Constant" "CFloat" [e2] (pos e2)]
| _ -> (ECall ((EField ((EField ((EField ((EConst (Ident "haxe"),p),"macro"),p),"Context"),p),"makeExpr"),p),[e; to_pos (pos e)]),p)
end
| Meta.Dollar "i", _ ->
expr "EConst" [mk_enum "Constant" "CIdent" [e1] (pos e1)]
| Meta.Dollar "p", _ ->
(ECall ((EField ((EField ((EField ((EConst (Ident "haxe"),p),"macro"),p),"MacroStringTools"),p),"toFieldExpr"),p),[e]),p)
| Meta.Custom ":pos", [pexpr] ->
let old = !cur_pos in
cur_pos := Some pexpr;
let e = loop e1 in
cur_pos := old;
e
| _ ->
expr "EMeta" [to_obj [("name",to_string (fst (Common.MetaInfo.to_string m)) p);("params",to_expr_array ml p);("pos",to_pos p)] p;loop e1]
and to_tparam_decl p t =
to_obj [
"name", to_string t.tp_name p;
"params", (EArrayDecl (List.map (to_tparam_decl p) t.tp_params),p);
"constraints", (EArrayDecl (List.map (fun t -> to_ctype t p) t.tp_constraints),p)
] p
and to_type_def (t,p) =
match t with
| EClass d ->
let ext = ref None and impl = ref [] and interf = ref false in
List.iter (function
| HExtern | HPrivate -> ()
| HInterface -> interf := true;
| HExtends t -> ext := Some (to_tpath t p)
| HImplements i -> impl := (to_tpath i p) :: !impl
) d.d_flags;
to_obj [
"pack", (EArrayDecl [],p);
"name", to_string d.d_name p;
"pos", to_pos p;
"meta", to_meta d.d_meta p;
"params", (EArrayDecl (List.map (to_tparam_decl p) d.d_params),p);
"isExtern", to_bool (List.mem HExtern d.d_flags) p;
"kind", mk_enum "TypeDefKind" "TDClass" [(match !ext with None -> (EConst (Ident "null"),p) | Some t -> t);(EArrayDecl (List.rev !impl),p);to_bool !interf p] p;