-
Notifications
You must be signed in to change notification settings - Fork 125
/
opaPrint.ml
1881 lines (1696 loc) · 83.5 KB
/
opaPrint.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 © 2011, 2012 MLstate
This file is part of OPA.
OPA is free software: you can redistribute it and/or modify it under the
terms of the GNU Affero General Public License, version 3, as published by
the Free Software Foundation.
OPA is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for
more details.
You should have received a copy of the GNU Affero General Public License
along with OPA. If not, see <http://www.gnu.org/licenses/>.
*)
(* FIXME: rebel open *)
open SurfaceAst
(* depends *)
module Format = Base.Format
module List = Base.List
(* shorthand *)
module S = SurfaceAst
(* refactoring in progress *)
(* -- *)
type 'ident printer =
<
code : 'dir. ('ident, [< SurfaceAst.all_directives ] as 'dir) SurfaceAst.code LangPrint.pprinter;
code_elt : 'dir. ('ident, [< SurfaceAst.all_directives ] as 'dir) SurfaceAst.code_elt LangPrint.pprinter;
code_elt_node : 'dir. ('ident, [< SurfaceAst.all_directives ] as 'dir) SurfaceAst.code_elt_node LangPrint.pprinter;
expr : 'dir. ('ident, [< SurfaceAst.all_directives ] as 'dir) SurfaceAst.expr LangPrint.pprinter;
ty : 'ident SurfaceAst.ty LangPrint.pprinter;
directive : 'dir. ('ident,[< SurfaceAst.all_directives ] as 'dir) SurfaceAst.directive LangPrint.pprinter;
variant : 'dir. ([< SurfaceAst.all_directives ] as 'dir) LangPrint.pprinter;
typevar : 'ident SurfaceAst.typevar LangPrint.pprinter;
typeident : 'ident SurfaceAst.typeident LangPrint.pprinter;
ident : 'ident LangPrint.pprinter;
keyword : string -> bool
>
module type Familly = sig
val string : string printer
val string_and_pos : string printer
val ident : Ident.t printer
val readable_ident : Ident.t printer
val full_ident : Ident.t printer
end
type 'a pprinter = 'a Format.pprinter
let pp = Format.fprintf
let list = Format.pp_list
let string_complete_match r s =
Str.string_match r s 0 &&
(String.length s == Str.match_end ())
let regular_ident_regexp = Str.regexp "[a-zA-Z_][a-zA-Z0-9_]*" (* same as the parser *)
let regular_typeident_regexp = Str.regexp "[a-zA-Z_][a-zA-Z0-9_.]*"
let keyword = function
| "match" | "with" | "type" | "do" | "if" | "then" | "else" | "as" | "_" | "<-" -> true
| _ -> false
let basic_type = function
| "int" | "string" | "float" -> true
| _ -> false
let operator_regexp = Str.regexp "[-.+\\^*/<>=@|&!$]+"
let unary_minus = "unary_minus"
let unary_minus_float = "unary_minus_float"
let operator_image s =
if s = unary_minus then "-"
else if s = unary_minus_float then "-."
else if s = "$" then "#"
else s
let is_operator s =
if s=unary_minus || s = unary_minus_float then true
else string_complete_match operator_regexp s
let is_ident s =
(string_complete_match regular_ident_regexp) s && not (is_operator s)
let classify_string keyword s =
if keyword s then `backquote
else if is_ident s then `ident
else if is_operator s then `operator
else `backquote
let classify_typeident s =
if keyword s || basic_type s then `backquote
else if is_ident s then `ident
else `backquote
type ident_kind = [
| `ident
| `backquote
| `operator
]
module ExprSugar =
struct
let extract_coercion = function
| (Directive ((`coerce : [< all_directives ]), [e], [ty]), _) -> Some (e,ty)
| _ -> None
let rec sugar_list original_name acc e =
match extract_coercion e with
| Some (((Record ["hd",hd;"tl",tl],_) | (Record ["tl",tl;"hd",hd],_)),
(TypeNamed (Typeident list,_),_)) when original_name list = "list" ->
sugar_list original_name (hd :: acc) tl
| Some ((Record ["nil",_],_),
(TypeNamed (Typeident list,_),_)) when original_name list = "list" ->
`list (List.rev acc, None) (* [1,2] *)
| _ ->
if acc = [] then `no_sugar else `list (List.rev acc, Some e) (* [1,2|e] *)
let sugar_tuple original_name e =
match extract_coercion e with
| Some ((Record l,_), (TypeNamed (Typeident name,_),_)) ->
(try
let n = Scanf.sscanf (original_name name) "tuple_%d" (fun x -> x) in
if n = List.length l && n <> 0 then
let l = List.sort (fun (s1,_) (s2,_) -> String.compare s1 s2) l in
if List.for_alli (fun i (f,_) -> f = "f"^string_of_int (i+1)) l then
`tuple (List.map snd l)
else
`no_sugar
else
`no_sugar
with
| End_of_file
| Scanf.Scan_failure _ -> `no_sugar)
| _ -> `no_sugar
let sugar_if = function
| Match (e1,[
((PatRecord ([("true", _)], `closed), _) | (PatCoerce ((PatRecord ([("true", _)], `closed), _), _), _)), e2 ;
((PatRecord ([("false", _)], `closed), _) | (PatCoerce ((PatRecord ([("false", _)], `closed), _), _), _)), e3 ;
]), _ -> `if_(e1,e2,e3)
| _ -> `no_sugar
let sugar_xhtml original_name e =
match extract_coercion e with
| Some (_, (TypeNamed (Typeident name,_),_)) when original_name name = "xhtml" -> `xhtml e
| _ -> `no_sugar
let sugar_dom_transformation original_name e =
match extract_coercion e with
| Some (_, (TypeNamed (Typeident name,_),_)) when original_name name = "Dom.transformation" -> `action e
| _ -> `no_sugar
let sugar_css_properties original_name e =
match extract_coercion e with
| Some (_, (TypeNamed (Typeident name,_),_)) when original_name name = "Css.properties" -> `css_props e
| _ -> `no_sugar
let rec select e l= match l with
| [] -> `no_sugar
| hd :: tl -> match hd e with
| `no_sugar -> select e tl
| r -> r
let resugarer original_name e =
select e [
sugar_list original_name [];
sugar_tuple original_name;
sugar_if;
sugar_xhtml original_name;
sugar_dom_transformation original_name;
(* sugar_css_properties original_name; *)
]
let handle_coerce_directive print_coerce print_no_coerce typeident_original_name make_expr default = function
| (Directive ((`coerce : [< all_directives ]), [e2], [ty])), _ as e ->
let e3 = match resugarer typeident_original_name e with
| `no_sugar -> make_expr e2
| _ -> default (* coerce will be removed later by resugarer *)
in
print_coerce ty e3
| _ -> print_no_coerce default
end
module PatSugar =
struct
let extract_coercion = function
| (PatCoerce (p,ty),_) -> Some (p,ty)
| _ -> None
let rec sugar_list original_name acc p =
match extract_coercion p with
| Some (((PatRecord (["hd", hd ; "tl", tl], `closed), _) | (PatRecord (["tl", tl ; "hd", hd], `closed), _)),
(TypeNamed (Typeident list,_),_)) when original_name list = "list" ->
sugar_list original_name (hd :: acc) tl
| Some ((PatRecord (["nil", _], `closed), _),
(TypeNamed (Typeident list,_),_)) when original_name list = "list" ->
Some (List.rev acc, None) (* [1,2] *)
| _ ->
if acc = [] then None else Some (List.rev acc, Some p) (* [1,2|e] *)
let sugar_tuple original_name e =
let record_tuple l =
let l = List.sort (fun (s1,_) (s2,_) -> String.compare s1 s2) l in
if List.for_alli (fun i (f,_) -> f = "f"^string_of_int (i+1)) l then
Some (List.map snd l)
else
None
in
match e with
| PatCoerce ((PatRecord (l, `closed), _), (TypeNamed (Typeident name,_),_)),_ ->
(try
let n = Scanf.sscanf (original_name name) "tuple_%d" (fun x -> x) in
if n = List.length l && n <> 0 then
record_tuple l
else
None
with
| End_of_file
| Scanf.Scan_failure _ -> None)
| PatRecord (l, `closed), _ -> record_tuple l
| _ -> None
let resugarer original_name p =
match sugar_list original_name [] p with
| Some (head,rest) -> `list (head,rest)
| None ->
match sugar_tuple original_name p with
| Some l -> `tuple l
| None -> `no_sugar
end
type all_directives = SurfaceAst.all_directives
let userland_visibilities_to_whatever ds =
(ds : QmlAst.userland_visibility_directive list :> [> all_directives] list)
module Sugar = struct
exception Fallback
exception NotARecord
let rec clear_directives e = match fst e with
| Directive(_,[e],_) -> clear_directives e
| _ -> e
let clear_magic e = match fst e with
| Directive(`magic_to_xml,[e],_) -> e
| _ -> e
let clear_coerce e = match fst e with
| Directive(`coerce,[e],_) -> e
| _ -> e
let rec fields_list e = match fst (clear_directives e) with
| Record fields -> fields
| _ -> raise NotARecord
let dot_ f e =
try List.assoc f (fields_list e)
with Not_found -> failwith ("dot on "^f)
let (@) e f = dot_ f e
let is_string e = match fst e with
| Const(CString(_)) -> true
| _ -> false
let string e = match fst e with
| Const(CString(s)) -> s
| _ -> assert false
let is_empty_string e = match fst e with
| Const(CString(s)) -> s=""
| _ -> false
(* record pattern are never closed *)
let iF ?notrecord e l =
try
let fs = (fields_list e) in
try
snd (
Base.List.find (fun (pat,_) ->
List.for_all (fun f -> List.mem_assoc f fs) pat
) l
)
with Not_found -> raise Fallback
with NotARecord when notrecord <> None -> (Option.get notrecord)
let is_nil e = iF e [
["nil"],(fun _ -> true);
[],(fun _ -> false)
] e
let rec list ~map e =
iF e [
["hd";"tl"],(fun e -> (map (e@"hd")) :: (list ~map (e@"tl")));
["nil"] ,(fun _e -> []);
] e
let _1st_char e = FilePos.get_first_char (QmlLoc.pos (snd e))
let cmp_attr (_,_,e1) (_,_,e2) = Pervasives.compare (_1st_char e1) (_1st_char e2)
(* insert an expr into braces *)
let pp_insert_expr ?(sugar=true) ppe f e =
match fst e with
| Directive((`string : [< all_directives]),[_],_) -> pp f "%a" (ppe sugar) e
| _ -> pp f "{%a}" (ppe sugar) e
module String = struct
(* insert an attribute into braces or dquote if needed *)
let rec pp_expr_or_string ?(quote=true) ppe f e =
match fst (clear_directives e) with
| Const(CString(s)) when quote -> pp f "\"%s\"" (QmlPrint.escaped_string s)
| Const(CString(s)) -> pp f "%s" (QmlPrint.escaped_string s)
| Directive(`string,l,_) -> pp_expr ppe f l
| Directive((#all_directives : [< all_directives]) ,_,_)
| _ -> pp_insert_expr ppe f e
and string_elmt ppe f e = pp_expr_or_string ~quote:false ppe f e
and pp_expr ppe f l = pp f "\"%a\"" (Format.pp_list "" (string_elmt ppe)) l
end
module Xhtml = struct
let pp_namespace ppe f ns =
if is_empty_string ns then pp f ""
else pp f "@ namespace=%a" (String.pp_expr_or_string ppe) ns
let str_empty = Const(CString("")),{QmlLoc.pos=FilePos.nopos "tmp";notes=0}
let (++) = List.append
let class_concat e = (* TODO computed string *)
let l = list ~map:(fun x->x) e in
if List.for_all is_string l then (
Const(CString(Base.String.concat " " (List.map string l))),{QmlLoc.pos=FilePos.nopos "tmp";notes=0}
) else e
(* xhtml specific *)
let collect_spec_attr e =
let class_ = e@"class" in
let style = e@"style" in
let class_att v = [str_empty,"class",v] in
let style_att v = [str_empty,"style",v] in
let class_ = try if is_nil class_ then [] else class_att (class_concat class_) with NotARecord -> class_att class_ in
let style = try if is_nil style then [] else style_att style with NotARecord -> style_att style in
let events = list ~map:(fun e->
let event = e@"value" in
str_empty,
"on" ^ (fst (List.hd (fields_list (e@"name")))),
iF event [
["expr"], (fun e -> clear_directives (e@"expr"));
[],(fun e-> e);
] event
) (e@"events") in
let events_options = list ~map:(fun e->
str_empty,
(* hack to fix the "onAction" on options: *)
"options:on"^(fst (List.hd (fields_list (e@"name")))),
e@"value"
) (e@"events_options") in
let href =
let e = e@"href" in
iF e [
["none"], (fun _ -> []);
["untyped"],(fun _ -> [str_empty,"href",e@"untyped"]);
[] ,(fun _ -> [str_empty,"href",e])
] ()
in
List.flatten [class_;style;events;events_options;href]
let collect_args = list ~map:(
fun e -> (e@"namespace"),string (e@"name"),(e@"value")
)
let rec pp_tag ppe f e =
let tag = string (e@"tag") in
let pp_attributes f l =
if l = [] then pp f "" else
pp f "%a" (Format.pp_list "" (pp_attribute ppe)) l
in
let args = collect_args (e@"args") in
let spec_att = e@"specific_attributes" in
let spec_att = iF spec_att [
["none"],(fun _ -> []);
["some"],(fun e -> collect_spec_attr (e@"some"))
] spec_att
in
(* group all attribute and sort by position retrieve original order *)
let attributes = args ++ spec_att in
let attributes = List.sort cmp_attr attributes in
let content = list ~map:(fun x->x) (e@"content") in
(if content = [] then pp f "<%s%a%a/>" else pp f "<%s%a%a>")
tag
(pp_namespace ppe) (e@"namespace")
pp_attributes attributes;
if content <> [] then pp f "%a</%s>"
(Format.pp_list "" (pp_xml ppe)) content
tag
else ()
and pp_attribute ppe f (ns,name,e) =
if is_empty_string ns then
pp f " %s=%a"
name
(String.pp_expr_or_string ppe) e
else
pp f "@%a:%s=%a"
(String.pp_expr_or_string ~quote:true ppe) ns
name
(String.pp_expr_or_string ppe) e
and pp_fragment ?(enclosed=true) ppe f e =
let l = list ~map:(fun x->x) (e@"fragment") in
if l = [] then (
if enclosed then pp f ""
else pp f "<></>"
) else pp f "@[<1><>@,%a</>@]" (Format.pp_list "@," (pp_xml ppe)) l
and pp_text ?(enclosed=true) _ppe f e =
(if enclosed then pp f "%s"
else pp f "<>%s</>") (string (e@"text"))
and pp_xml ?(enclosed=true) (ppe : bool -> ('a,'b) expr pprinter) f e = iF e [
["namespace";"tag";"args";"content";"specific_attributes"] , pp_tag;
["fragment"] , pp_fragment ~enclosed;
["text"] , pp_text ~enclosed;
[] , (fun ppe f e -> ppe false f e)
] ~notrecord:(fun ppe f e -> if enclosed then pp_insert_expr ppe f (clear_coerce (clear_magic e)) else ppe false f (clear_coerce e))
ppe f e
let pp_xml : (bool -> ('ident,[< all_directives ] as 'dir) expr pprinter) -> ('ident,[< all_directives ] as 'dir) expr pprinter
=
fun ppe f e -> pp_xml ~enclosed:false ppe f e
let magie = Obj.magic pp_xml
let pp_xml : 'dir. (bool -> ('ident,[< all_directives ] as 'dir) expr pprinter) -> ('ident,[< all_directives ] as 'dir) expr pprinter
= magie (* Obj.magic pp_xml WTF . *)
end
module Action = struct
let fallback ppe f e _ = ppe false f e
let pp_dst original_name ppe e =
match clear_directives e with
| Apply((Ident(id),_),([_,e],_)),_ -> (
let op = match original_name id with
| "Dom_select_id" -> "#"
| "Dom_select_class" -> "."
| _ -> raise Fallback
in
fun f () -> (
match fst e with
| Directive(`string,l,_) -> pp f "%s{%a}" op (String.pp_expr ppe) l
| _ -> pp f "%s%a" op (String.pp_expr_or_string ~quote:false ppe) e
)
)
| _ -> raise Fallback
let str s f () = pp f "%s" s
let pp_op e =
iF e [
["set"] , str "=";
["prepend"], str "+=";
["append"] , str "=+"
]
let pp_content ppe f e =
let fallback = fallback ppe f e in
iF e [
["content"], (fun ()-> ppe true f (clear_magic (e@"content")));
[], fallback
] ~notrecord:fallback ()
let pp original_name ppe f e =
let fallback = fallback ppe f e in
try
iF e [
["jq";"subject";"verb"], (fun () ->
(* TODO op before start printing *)
let pp_op = pp_op (e@"verb") in
let pp_dst = pp_dst original_name ppe (e@"jq") in
pp f "%a %a %a"
pp_dst ()
pp_op ()
(pp_content ppe) (e@"subject")
);
[], fallback
] ()
with Fallback -> fallback ()
type ('ident,'dir) printer = ('ident -> string) ->
(bool -> ('ident,[< all_directives ] as 'dir) expr pprinter) -> ('ident,[< all_directives ] as 'dir) expr pprinter
let magie = Obj.magic (pp:('ident,'dir) printer)
let pp : 'dir. ('ident,'dir) printer = magie
end
module Css = struct
let pp ppe f e = ppe f e
end
end
module Classic = struct
class virtual ['ident] printer =
object (self)
(* priorities
*
*)
val comma = false
val forall = false
val typesum = false
val arrow = false
val colon = false
val op = false
method under_typesum = {< typesum = true >}
method under_comma = {< comma = true >}
method private under_forall = {< forall = true >}
method private under_arrow = {< arrow = true >}
method under_colon = {< colon = true >}
method private under_op = {< op = true >}
method private reset = {< typesum = false;
comma = false;
forall = false;
arrow = false;
colon = false;
op = false >}
method keyword = function
| "match" | "with" | "type" | "do" | "if" | "then" | "else" | "as" | "_" | "<-" -> true
| _ -> false
method label : 'a. 'a pprinter -> 'a QmlLoc.label pprinter = fun p f v -> p f (fst v)
method private const_expr f = function
| CInt i -> Format.pp_print_string f (Big_int.string_of_big_int i)
| CFloat float -> Format.pp_print_float f float
| CString s -> pp f "\"%s\"" (QmlPrint.escaped_string s)
method private field f s =
Format.pp_print_string f (
match classify_string self#keyword s with
| `ident -> s
| `operator | `backquote -> "`"^s^"`"
)
(*------------------------*)
(*----- type printer -----*)
(*------------------------*)
method ty f ty = self#label self#ty_node f ty
method ty_node f = function
| TypeSumSugar _ as ty when typesum -> pp f "(%a)" self#reset#ty_node ty
| TypeSumSugar _ as ty when forall -> pp f "(%a)" self#reset#ty_node ty
| TypeArrow _ as ty when arrow -> pp f "(%a)" self#reset#ty_node ty
| (TypeSumSugar _ | TypeArrow _ | TypeForall _) as ty when comma -> pp f "(%a)" self#reset#ty_node ty
| TypeConst c -> self#const_ty_node f c
| TypeVar v -> self#typevar f v
| TypeArrow r -> self#arrow_t_node f r
| TypeRecord r -> self#row_t_node f r
| TypeSumSugar l -> self#typesumsugar f l
| TypeNamed t -> self#typeinstancenode f t
| TypeExternal -> Format.pp_print_string f "external"
| TypeForall p -> self#typeforall f p
| TypeModule r -> self#typemodule f r
method private const_ty_node f const =
Format.pp_print_string f (
match const with
| TyInt -> "int"
| TyFloat -> "float"
| TyString -> "string"
)
method private rowvar f _ = Format.pp_print_string f "..."
method private colvar f _ = Format.pp_print_string f "..."
method virtual typeident : 'ident typeident pprinter
method virtual typevar : 'ident typevar pprinter
method virtual typeident_original_name : 'ident -> string
method private row_t f x = self#label self#row_t_node f x
method private row_t_node f (TyRow (nodes, rowo)) =
match nodes, rowo with
| [], None -> Format.pp_print_string f "{}"
| [], Some rowvar -> pp f "{%a}" self#rowvar rowvar
| l, None -> pp f "@[<1>{%a}@]" (list ";@ " self#typerecordbinding) l
| l, Some rowvar -> pp f "@[<1>{%a;@ %a}@]" (list ";@ " self#typerecordbinding) l self#rowvar rowvar
method private typerecordbinding f (s,ty) =
match ty with
| (TypeRecord (TyRow ([],None)),_) -> Format.pp_print_string f s
| _ -> pp f "%a: %a" self#field s self#reset#ty ty
method sum_t f v = self#label self#sum_t_node f v
method private sum_t_node f = function
| SumName typeinstance -> self#typeinstancenode f typeinstance
| SumRecord r -> self#row_t_node f r
| SumVar c -> self#colvar f c
method private arrow_t f v = self#label self#arrow_t_node f v
method private arrow_t_node f (row_t,ty) =
pp f "@[<2>%a ->@ %a@]" self#under_comma#arrow_row_t row_t self#under_arrow#ty ty
method arrow_row_t f v = self#label self#arrow_row_t_node f v
method private arrow_row_t_node f (TyRow (l,row)) =
assert (row = None);
list ",@ " self#arrowbinding f l
method private arrowbinding f (_,ty) = self#ty f ty
method private typeinstance f t = self#label self#typeinstancenode f t
method private typeinstancenode f (ident,params) =
match params with
| [] -> self#typeident f ident
| _ -> pp f "@[@[<2>%a(%a@])@]" self#typeident ident (list ",@ " self#under_comma#ty) params
method private typeforall f (vars,ty) =
pp f "@[<2>forall(@[<h>%a@]) %a@]" (list ",@ " self#typevar) vars self#under_forall#ty ty
method private typesumsugar f l =
pp f "@[<v> %a@]" (list "@ / " self#under_typesum#sum_t) l
method private typemodule f fields =
pp f "@[@{<v2>{{@ %a@ @]}}@]" (list "@ " self#typerecordbinding) fields
(*-------------------------*)
(*---- pattern printer ----*)
(*-------------------------*)
method private is_tilde_field : 'a. ('a -> 'ident option) -> string * 'a -> bool =
(fun getvar (field, pat) ->
match getvar pat with
| Some ident ->
let ident = self#to_protected_ident ident in
String.compare field ident = 0
| None -> false
)
method pat f p =
match PatSugar.resugarer self#typeident_original_name p with
| `list (head,None) -> pp f "@[<2>[%a]@]" (list ",@ " self#pat) head
| `list (head,Some rest) -> pp f "@[<2>[%a@ |@ %a]@]" (list ",@ " self#pat) head self#pat rest
| `tuple pl -> pp f "@[<1>(%a)@]" (list ",@ " self#pat) pl
| `no_sugar -> self#label self#pat_node f p
method pat_node f = function
| PatCoerce _ as p when arrow || comma || colon -> pp f "(%a)" self#reset#pat_node p
| PatRecord (fields, rowvar) -> self#pat_record f fields rowvar
| PatAny -> pp f "_"
| PatConst c -> self#const_expr f c
| PatVar v -> pp f "%a %a" self#pat_directives (userland_visibilities_to_whatever v.directives) self#ident v.ident
| PatCoerce (p,ty) -> pp f "%a : %a" self#under_colon#pat p self#ty ty
| PatAs (p,i) -> pp f "%a %a as %a" self#pat_directives (userland_visibilities_to_whatever i.directives) self#pat p self#ident i.ident
method private pat_record_binding f ((s, p) as pat) =
match p with
| PatCoerce ((PatRecord ([], _), _), (TypeRecord (TyRow ([], None)), _)), _ -> self#field f s
| _ ->
let getvar = function
| S.PatVar v, _ -> Some v.ident
| _ -> None
in
if self#is_tilde_field getvar pat
then
pp f "~%a" self#field s
else
pp f "%a =@ %a" self#field s self#pat p
method private pat_record f fields rowvar =
match fields with
| [] ->
if rowvar = `open_
then
Format.pp_print_string f "{ ... }"
else
Format.pp_print_string f "{}"
| _ ->
let rowvar = if rowvar = `open_ then " ; ..." else "" in
let is_tilde_field field =
let getvar = function
| S.PatVar v, _ -> Some v.S.ident
| _ -> None
in
self#is_tilde_field getvar field
in
if List.for_all is_tilde_field fields
then
let pp_field f (field, _) = self#field f field in
pp f "@[<hv2>~{ %a%s }@]"
(Format.pp_list "@, " pp_field) fields
rowvar
else
pp f "@[<hv2>{ %a%s }@]"
(Format.pp_list " ;@ " self#pat_record_binding) fields
rowvar
(*-------------------------*)
(*----- expr printer ------*)
(*-------------------------*)
method virtual is_operator : 'ident -> bool
method virtual to_protected_ident : 'ident -> string
method virtual to_unprotected_ident : 'ident -> string
method ident f i = Format.pp_print_string f (self#to_protected_ident i)
method private unprotected_ident f i = Format.pp_print_string f (self#to_unprotected_ident i)
method private expr_sugar : 'dir . bool -> ('ident,[< all_directives ] as 'dir) expr pprinter = fun sugar f e ->
if not sugar then self#label self#expr_node f e
else match ExprSugar.resugarer self#typeident_original_name e with
| `list (head,None) -> pp f "@[<2>[%a]@]" (list ",@ " self#expr) head
| `list (head,Some rest) -> pp f "@[<2>[%a@ |@ %a]@]" (list ",@ " self#expr) head self#expr rest
| `tuple el -> pp f "@[<1>(%a)@]" (list ",@ " self#expr) el
| `if_ (e1,e2,e3) -> pp f "@[<2>if %a@;<1 -2>then@ %a@;<1 -2>else@ %a@]" self#expr e1 self#expr e2 self#expr e3
| `xhtml e -> Sugar.Xhtml.pp_xml self#expr_sugar f e
| `action e -> Sugar.Action.pp self#to_unprotected_ident self#expr_sugar f e
| `no_sugar -> self#label self#expr_node f e
method expr : 'dir . ('ident,[< all_directives ] as 'dir) expr pprinter = self#expr_sugar true
method expr_node : 'dir. ('ident,[< all_directives ] as 'dir) expr_node pprinter = fun f -> function
(*| Directive ((`coerce:[< all_directives]),_,_) as e when comma -> pp f "(%a)" self#expr_node e*)
| Lambda _ | Match _ | LetIn _ as e when op -> pp f "(%a)" self#reset#expr_node e
| Lambda _ as e when comma -> pp f "(%a)" self#reset#expr_node e
| Apply ((Ident oper,_LABEL1),([(_,e1);(_,e2)],_LABEL2)) as e when self#is_operator oper ->
if op || colon then pp f "(%a)" self#reset#expr_node e else
pp f "@[<2>%a %s@ %a@]" self#under_op#expr e1 (self#to_unprotected_ident oper) self#under_op#expr e2
| Apply (e,(r,_LABEL)) -> pp f "@[<2>%a(%a)@]" self#apply_expr e (list ",@ " (fun f (_,e) -> self#reset#under_comma#expr f e)) r
| Lambda (r,e) -> pp f "@[<2>%a ->@ %a@]" (list ",@ " (fun f (_,p) -> self#under_comma#pat f p)) r self#expr e
| Const c -> self#const_expr f c
| Ident ident -> self#ident f ident
| LetIn (true,iel,e) ->
pp f "@[<v>@[<2>rec %a@]@ %a@]" (list "@]@ and @[" self#binding) iel self#expr e
| LetIn (false,[bnd],e) ->
pp f "@[<v>@[<2>%a@]@ %a@]" self#binding bnd self#expr e
| LetIn (false,iel,e) ->
pp f "/* encoded let and */@\n@[<v>%a@ %a@]" self#bindings iel self#expr e
| Match (e,pel) ->
pp f "@[<v>match %a with@ " self#reset#expr e;
Format.pp_print_if_newline f ();
Format.pp_print_string f "| ";
pp f "%a@ end@]" (list "@ | " self#rule_) pel
| Record fields -> self#record f fields
| ExtendRecord (r,e) ->
pp f "@[<1>{%a with@ %a}@]" self#expr e (list ";@ " self#record_binding) r
| Dot (e,s) -> pp f "%a.%a" self#apply_expr e self#field s
| Bypass s -> pp f "%%%%%s%%%%" (BslKey.to_string s)
| DBPath (elt,kind,select) -> pp f "%a" (QmlAst.Db.pp_path self#expr) (List.map fst (fst elt), kind, select)
| Directive d -> self#directive f d
method private apply_expr : 'dir. ('ident,[< all_directives ] as 'dir) expr pprinter = fun f -> function
| (Ident _,_)
| (Apply _,_)
| (Directive _ ,_)
| (Dot _, _) as e -> self#expr f e
| e -> pp f "(%a)" self#reset#expr e
method private db_elt : 'dir. ('ident,[< all_directives ] as 'dir) dbelt pprinter = fun f e ->
self#label self#db_elt_node f e
method private db_elt_node : 'dir. ('ident,[< all_directives ] as 'dir) dbelt_node pprinter = fun f l ->
list "" self#db_element f l
method private db_element : 'dir. ('ident,[< all_directives ] as 'dir) preprocessed_db_element pprinter = fun f e ->
self#label self#db_element_node f e
method private db_element_node : 'dir. ('ident,[< all_directives ] as 'dir) preprocessed_db_element_node pprinter = QmlAst.Db.pp_path_elt self#expr
method variant : 'dir. ([< all_directives ] as 'dir) pprinter = fun f -> function
| `magic_to_string -> Format.pp_print_string f "magic_to_string"
| `magic_to_xml -> Format.pp_print_string f "magic_to_xml"
(* computed string *)
| `string -> Format.pp_print_string f "string"
(* internationalization *)
| `i18n -> Format.pp_print_string f "i18n"
| `i18n_lang -> Format.pp_print_string f "i18n_lang"
(* *)
| `fun_action -> Format.pp_print_string f "fun_action"
| `magic_do -> Format.pp_print_string f "magic_do"
| `typeof -> Format.pp_print_string f "typeof"
| `assert_ -> Format.pp_print_string f "assert_"
| `deprecated -> pp f "deprecated"
| `todo -> pp f "todo"
| `server_entry_point -> Format.pp_print_string f "server_entry_point"
| `spawn -> Format.pp_print_string f "spawn"
| `wait -> Format.pp_print_string f "wait"
| `callcc -> Format.pp_print_string f "callcc"
| `atomic -> Format.pp_print_string f "atomic"
| `thread_context -> Format.pp_print_string f "thread_context"
| `with_thread_context -> Format.pp_print_string f "with_thread_context"
| `no_client_calls -> Format.pp_print_string f "no_client_calls"
| `async -> Format.pp_print_string f "async"
| `side_annotation _ -> Format.pp_print_string f "side_annotation"
| `visibility_annotation (`public `sync) -> Format.pp_print_string f "exposed"
| `visibility_annotation (`public `async) -> Format.pp_print_string f "exposed @async"
| `visibility_annotation (`public `funaction) -> Format.pp_print_string f "exposed"
| `visibility_annotation `private_ -> Format.pp_print_string f "protected"
| `static_content (s, eval) -> pp f "static_content[%s][%b]" s eval
| `static_content_directory (s, eval) -> pp f "static_content_directory[%s][%b]" s eval
| `static_resource s -> pp f "static_resource[%s]" s
| `static_resource_directory s -> pp f "static_resource_directory(\"%s\")" s
| `private_ -> Format.pp_print_string f "private"
| `package -> Format.pp_print_string f "package"
| `public -> Format.pp_print_string f "public"
| `unsafe_cast -> Format.pp_print_string f "unsafe_cast"
| `fail -> Format.pp_print_string f "fail"
| `tracker _ -> Format.pp_print_string f "tracker[?]"
| `expand None -> Format.pp_print_string f "expand"
| `expand (Some i) -> pp f "expand[%s]" (Big_int.string_of_big_int i)
| `coerce -> Format.pp_print_string f "coerce"
| `nonexpansive -> Format.pp_print_string f "nonexpansive"
| `opensums -> Format.pp_print_string f "opensums"
| `openrecord -> Format.pp_print_string f "openrecord"
| `module_ -> Format.pp_print_string f "module_"
| `module_field_lifting -> Format.pp_print_string f "module_field_lifting"
| `warncoerce -> Format.pp_print_string f "warncoerce"
| `js_ident -> Format.pp_print_string f "js_ident"
| `open_ -> Format.pp_print_string f "open_"
| `toplevel_open -> Format.pp_print_string f "toplevel_open"
| `toplevel -> Format.pp_print_string f "toplevel"
| `from s -> Format.fprintf f "from(%s)" s
| `local s -> pp f "local[%s]" (Ident.to_string s)
| `doctype (sl, access) ->
pp f "doctype([%a], %a)" (list ",@ " Format.pp_print_string) sl self#variant access
| `parser_ _ -> Format.pp_print_string f "parser_"
| `xml_parser _ -> Format.pp_print_string f "xml_parser"
| `create_lazy_record -> Format.pp_print_string f "create_lazy_record"
| `throw -> Format.pp_print_string f "throw"
| `catch -> Format.pp_print_string f "catch"
| `compiletime s -> Format.fprintf f "compiletime(%S)" s
| `opacapi -> Format.fprintf f "opacapi"
| `stringifier -> Format.fprintf f "stringifier"
| `comparator -> Format.fprintf f "comparator"
| `serializer -> Format.fprintf f "serializer"
| `xmlizer -> Format.fprintf f "xmlizer"
| `sliced_expr -> Format.pp_print_string f "sliced_expr"
| `may_cps -> Format.pp_print_string f "may_cps"
| `llarray -> Format.pp_print_string f "llarray"
| `specialize `strict -> Format.pp_print_string f "specialize_strict"
| `specialize `polymorphic -> Format.pp_print_string f "specialize"
| `recval -> Format.pp_print_string f "recval"
| `sugar _ -> Format.pp_print_string f "sugar"
| `sugar_pat_in _ -> Format.pp_print_string f "sugar_pat_in"
(* TODO add more qml directive type here instead of duplicating with QmlDirectives.to_string above *)
| #QmlAst.closure_instrumentation_directive as d -> Format.pp_print_string f (QmlDirectives.to_string d)
method private string_elmt : 'dir. ('ident,[< all_directives ] as 'dir) expr pprinter = fun f (e,_) ->
match e with
| Const(CString(s)) -> pp f "%s" (QmlPrint.escaped_string s)
| e -> pp f "{%a}" self#expr_node e
method directive : 'dir. ('ident,[< all_directives ] as 'dir) directive pprinter =
fun f (variant, exprs, tys) ->
match variant, exprs, tys with
| `coerce, [e], [ty] ->
if comma || colon then pp f "(%a : %a)" self#reset#under_colon#expr e self#ty ty
else pp f "%a : %a" self#under_colon#expr e self#ty ty
| `module_, [(Record r,_)], _ -> pp f "@[<v>@[<v2>{{@ %a@]@ }}@]" (list ";@ " self#record_binding) r
| `string, l, _ ->
pp f "\"%a\"" (list "" self#string_elmt) l
| #all_directives,[] , [] -> pp f "@[<2>@@%a@]" self#variant variant
| #all_directives,exprs, [] -> pp f "@[<2>@@%a(%a)@]" self#variant variant (list ",@ " self#reset#expr) exprs
| #all_directives,exprs, tys -> pp f "@[<2>@@%a(%a ; %a)@]" self#variant variant (list ",@ " self#reset#expr) exprs (list ",@ " self#ty) tys
method private pat_directive f (v:SurfaceAst.all_directives) = pp f "@[<2>@@%a@]" self#variant v
method private pat_directives f (vs:SurfaceAst.all_directives list) = pp f "%a" (Format.pp_list "@ " self#pat_directive) vs
method private record_binding : 'dir. (string * ('ident, [< all_directives ] as 'dir) expr) pprinter = fun f ((s, e) as expr) ->
match e with
| (Directive ((`coerce : [< all_directives]),[(Record [],_)],[TypeRecord (TyRow ([],None)), _]),_) -> self#field f s
| (Lambda (r,e),_LABEL) -> pp f "@[<2>%a@]" (self#lambda_binding self#field) (s,r,e)
| _ ->
let getvar = function
| S.Ident i, _ -> Some i
| _ -> None
in
if self#is_tilde_field getvar expr
then
pp f "~%a" self#field s
else
pp f "@[<2>%a :@ %a@]" self#field s self#reset#expr e
method private record :
'dir. ((string * ('ident, [< all_directives ] as 'dir) expr) list) pprinter =
fun f l ->
match l with
| [] -> pp f "{}"
| _ ->
let is_tilde_field field =
let getvar = function
| S.Ident i, _ -> Some i
| _ -> None
in
self#is_tilde_field getvar field
in
if List.for_all is_tilde_field l
then
let pp_field f (field, _) = self#field f field in
pp f "@[<hv>~{ %a }@]" (Format.pp_list "@, " pp_field) l
else
pp f "@[<hv>{ %a }@]" (Format.pp_list " ;@ " self#record_binding) l
method private lambda_binding : 'a 'dir. 'a pprinter -> ('a * (string * 'ident pat) list * ('ident, [< all_directives ] as 'dir) expr) pprinter = fun p f (s,r,e) ->
pp f "%a(%a) =@ %a" p s (list ",@ " self#reset#under_comma#pat) (List.map snd r) self#expr e
method private binding : 'dir. ('ident * ('ident, [< all_directives ] as 'dir) expr) pprinter = fun f (i,e) ->
match e with
| (Directive ((`magic_do : [< all_directives ]), [e], _),_) -> pp f "@[<2>do %a@]" self#expr e
| (Lambda (r,e),_LABEL) -> self#lambda_binding self#ident f (i,r,e)
| _ -> pp f "%a =@ %a" self#ident i self#expr e
method bindings : 'dir. ('ident * ('ident, [< all_directives ] as 'dir) expr) list pprinter = fun f iel ->
let il,el = List.split iel in
pp f "@[<2>(%a) =@ (%a)@]" (list ",@ " self#ident) il (list ",@ " self#expr) el
method private rule_ : 'dir. ('ident pat * ('ident, [< all_directives ] as 'dir) expr) pprinter = fun f (p,e) ->
pp f "@[<2>%a ->@ %a@]" self#under_arrow#pat p self#expr e
method private side f = function
| `server -> Format.pp_print_string f "server"
| `client -> Format.pp_print_string f "client"
| `both -> Format.pp_print_string f "both"
| `prefer_server -> Format.pp_print_string f "prefer_server"
| `prefer_client -> Format.pp_print_string f "prefer_client"
| `prefer_both -> Format.pp_print_string f "prefer_both"
| `both_implem -> Format.pp_print_string f "both_implem"
(*-------------------------*)
(*----- decl printer ------*)
(*-------------------------*)
method private path_decl_key f = function
| QmlAst.Db.Decl_fld s -> pp f "/%a" self#field s
| QmlAst.Db.Decl_int -> pp f "@@fixme<db_decl_int>"
| QmlAst.Db.Decl_string -> pp f "@@fixme<db_decl_string>"
| QmlAst.Db.Decl_set [] -> pp f "[_]"
| QmlAst.Db.Decl_set (_ :: _) -> pp f "@@fixme<db_decl_set>"
method private path_decl f l = list "" self#path_decl_key f l
method private db_def : 'dir. (('ident, [< all_directives] as 'dir) expr, 'ident ty) QmlAst.Db.db_def pprinter = fun f -> function
| QmlAst.Db.Db_TypeDecl (path_decl,ty) -> pp f "%a :@ %a" self#path_decl path_decl self#ty ty
| QmlAst.Db.Db_Default (path_decl,e) -> pp f "%a =@ %a" self#path_decl path_decl self#expr e
| QmlAst.Db.Db_Alias (path_decl,path_decl2) -> pp f "%a =@ %a" self#path_decl path_decl self#path_decl path_decl2
| QmlAst.Db.Db_Constraint _ -> pp f "@@fixme<db_constraint>"
| QmlAst.Db.Db_Virtual (p, e) -> pp f "%a := %a" self#path_decl p self#expr e
method code : 'dir. ('ident, [< all_directives ] as 'dir) code pprinter = fun f l ->
list "@\n@\n" self#code_elt f l
method code_elt : 'dir. ('ident, [< all_directives ] as 'dir) code_elt pprinter = fun f c ->
self#label self#code_elt_node f c
method code_elt_node : 'dir. ('ident, [< all_directives ] as 'dir) code_elt_node pprinter = fun f -> function
| Database (ident,[],options) -> pp f "database /* %a */ %s" self#ident ident (QmlAst.Db.options_to_string options)
| Database _ -> pp f "@@fixme<database>"
| NewDbDef db_def -> pp f "@[<2>db %a@]" self#db_def db_def
| NewType typedefs -> (
match typedefs with
| [one] ->
pp f "@[<2>%atype %a@]"
self#typedef_visibility (fst one).SurfaceAst.ty_def_visibility
(self#typedef ~print_visibility: false) one
| _ ->
pp f "@[<v>@[<2>type %a@]@]"
(list "@]@ and @[" (self#typedef ~print_visibility: true)) typedefs
)
| NewVal ([bnd],_) -> pp f "%a" self#pat_binding bnd
| NewVal (pel,_) ->
pp f "%a" self#pat_bindings pel
| Package (`import,s) ->
pp f "import %s" (String.sub s 1 (String.length s - 2))
| Package (`import_plugin, s) ->
pp f "import-plugin %s" (String.sub s 1 (String.length s - 2))
| Package (`declaration,s) ->
pp f "package %s" s
method private pat_binding : 'dir. ('ident pat * ('ident, [< all_directives ] as 'dir) expr) pprinter = fun f (p,e) ->
match p, e with
| (PatVar i,_LABEL1), (Lambda (r,e),_LABEL2) ->
self#lambda_binding self#ident f (i.SurfaceAst.ident,r,e)
| _, (Directive ((`visibility_annotation `public b : [< all_directives ]),[e],_),_) -> (
match b with
| `async -> pp f "@publish_async %a" self#pat_binding (p,e)
| `sync -> pp f "@publish %a" self#pat_binding (p, e)
| `funaction -> assert false
)
| _, (Directive (`side_annotation side,[e],_),_) -> pp f "%a %a" self#side side self#pat_binding (p,e)
| _ -> pp f "%a =@ %a" self#pat p self#expr e
method private pat_bindings : 'dir. ('ident pat * ('ident, [< all_directives ] as 'dir) expr) list pprinter = fun f pel ->
let pl,el = List.split pel in
pp f "@[<2>(%a) =@ (%a)@]" (list ",@ " self#pat) pl (list ",@ " self#expr) el
method private typedef_visibility f = function
| SurfaceAst.TDV_public -> ()
| SurfaceAst.TDV_abstract _ -> pp f "@@abstract@ "
| SurfaceAst.TDV_private _ -> pp f "@@private@ "
method private typedef ~print_visibility f ty_def =
self#label (self#typedef_node ~print_visibility) f ty_def
method private typedef_node ~print_visibility f ty_def =
(* We print the visibility of the definition just before its name only if
requested. In effect, when the definition defines only one type, we
prefer to have the visibility printed first, before the token "type".
So in this case, if the visibility is already printed, no need to print
it again. *)
if print_visibility then
pp f "%a" self#typedef_visibility ty_def.SurfaceAst.ty_def_visibility ;