forked from ocaml-flambda/flambda-backend
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpprintast.ml
2331 lines (2163 loc) · 83 KB
/
pprintast.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
(**************************************************************************)
(* *)
(* OCaml *)
(* *)
(* Thomas Gazagnaire, OCamlPro *)
(* Fabrice Le Fessant, INRIA Saclay *)
(* Hongbo Zhang, University of Pennsylvania *)
(* *)
(* Copyright 2007 Institut National de Recherche en Informatique et *)
(* en Automatique. *)
(* *)
(* All rights reserved. This file is distributed under the terms of *)
(* the GNU Lesser General Public License version 2.1, with the *)
(* special exception on linking described in the file LICENSE. *)
(* *)
(**************************************************************************)
(* Original Code from Ber-metaocaml, modified for 3.12.0 and fixed *)
(* Printing code expressions *)
(* Authors: Ed Pizzi, Fabrice Le Fessant *)
(* Extensive Rewrite: Hongbo Zhang: University of Pennsylvania *)
(* TODO more fine-grained precedence pretty-printing *)
open Asttypes
open Format
open Location
open Longident
open Parsetree
let prefix_symbols = [ '!'; '?'; '~' ]
let infix_symbols = [ '='; '<'; '>'; '@'; '^'; '|'; '&'; '+'; '-'; '*'; '/';
'$'; '%'; '#' ]
(* type fixity = Infix| Prefix *)
let special_infix_strings =
["asr"; "land"; "lor"; "lsl"; "lsr"; "lxor"; "mod"; "or"; ":="; "!="; "::" ]
let letop s =
String.length s > 3
&& s.[0] = 'l'
&& s.[1] = 'e'
&& s.[2] = 't'
&& List.mem s.[3] infix_symbols
let andop s =
String.length s > 3
&& s.[0] = 'a'
&& s.[1] = 'n'
&& s.[2] = 'd'
&& List.mem s.[3] infix_symbols
(* determines if the string is an infix string.
checks backwards, first allowing a renaming postfix ("_102") which
may have resulted from Pexp -> Texp -> Pexp translation, then checking
if all the characters in the beginning of the string are valid infix
characters. *)
let fixity_of_string = function
| "" -> `Normal
| s when List.mem s special_infix_strings -> `Infix s
| s when List.mem s.[0] infix_symbols -> `Infix s
| s when List.mem s.[0] prefix_symbols -> `Prefix s
| s when s.[0] = '.' -> `Mixfix s
| s when letop s -> `Letop s
| s when andop s -> `Andop s
| _ -> `Normal
let view_fixity_of_exp = function
| {pexp_desc = Pexp_ident {txt=Lident l;_}; pexp_attributes = []} ->
fixity_of_string l
| _ -> `Normal
let is_infix = function `Infix _ -> true | _ -> false
let is_mixfix = function `Mixfix _ -> true | _ -> false
let is_kwdop = function `Letop _ | `Andop _ -> true | _ -> false
let first_is c str =
str <> "" && str.[0] = c
let last_is c str =
str <> "" && str.[String.length str - 1] = c
let first_is_in cs str =
str <> "" && List.mem str.[0] cs
(* which identifiers are in fact operators needing parentheses *)
let needs_parens txt =
let fix = fixity_of_string txt in
is_infix fix
|| is_mixfix fix
|| is_kwdop fix
|| first_is_in prefix_symbols txt
(* some infixes need spaces around parens to avoid clashes with comment
syntax *)
let needs_spaces txt =
first_is '*' txt || last_is '*' txt
(* Turn an arbitrary variable name into a valid OCaml identifier by adding \#
in case it is a keyword, or parenthesis when it is an infix or prefix
operator. *)
let ident_of_name ppf txt =
let format : (_, _, _) format =
if Lexer.is_keyword txt then "\\#%s"
else if not (needs_parens txt) then "%s"
else if needs_spaces txt then "(@;%s@;)"
else "(%s)"
in fprintf ppf format txt
let ident_of_name_loc ppf s = ident_of_name ppf s.txt
let protect_longident ppf print_longident longprefix txt =
if not (needs_parens txt) then
fprintf ppf "%a.%a" print_longident longprefix ident_of_name txt
else if needs_spaces txt then
fprintf ppf "%a.(@;%s@;)" print_longident longprefix txt
else
fprintf ppf "%a.(%s)" print_longident longprefix txt
let is_curry_attr attr =
attr.attr_name.txt = Jane_syntax.Arrow_curry.curry_attr_name
let filter_curry_attrs attrs =
List.filter (fun attr -> not (is_curry_attr attr)) attrs
let has_non_curry_attr attrs =
List.exists (fun attr -> not (is_curry_attr attr)) attrs
type space_formatter = (unit, Format.formatter, unit) format
let override = function
| Override -> "!"
| Fresh -> ""
(* variance encoding: need to sync up with the [parser.mly] *)
let type_variance = function
| NoVariance -> ""
| Covariant -> "+"
| Contravariant -> "-"
let type_injectivity = function
| NoInjectivity -> ""
| Injective -> "!"
type construct =
[ `cons of expression list
| `list of expression list
| `nil
| `normal
| `simple of Longident.t
| `tuple
| `btrue
| `bfalse ]
let view_expr x =
match x.pexp_desc with
| Pexp_construct ( {txt= Lident "()"; _},_) -> `tuple
| Pexp_construct ( {txt= Lident "true"; _},_) -> `btrue
| Pexp_construct ( {txt= Lident "false"; _},_) -> `bfalse
| Pexp_construct ( {txt= Lident "[]";_},_) -> `nil
| Pexp_construct ( {txt= Lident"::";_},Some _) ->
let rec loop exp acc = match exp with
| {pexp_desc=Pexp_construct ({txt=Lident "[]";_},_);
pexp_attributes = []} ->
(List.rev acc,true)
| {pexp_desc=
Pexp_construct ({txt=Lident "::";_},
Some ({pexp_desc= Pexp_tuple([None, e1;None, e2]);
pexp_attributes = []}));
pexp_attributes = []}
->
loop e2 (e1::acc)
| e -> (List.rev (e::acc),false) in
let (ls,b) = loop x [] in
if b then
`list ls
else `cons ls
| Pexp_construct (x,None) -> `simple (x.txt)
| _ -> `normal
let is_simple_construct :construct -> bool = function
| `nil | `tuple | `list _ | `simple _ | `btrue | `bfalse -> true
| `cons _ | `normal -> false
let pp = fprintf
type ctxt = {
pipe : bool;
semi : bool;
ifthenelse : bool;
functionrhs : bool;
}
let reset_ctxt = { pipe=false; semi=false; ifthenelse=false; functionrhs=false }
let under_pipe ctxt = { ctxt with pipe=true }
let under_semi ctxt = { ctxt with semi=true }
let under_ifthenelse ctxt = { ctxt with ifthenelse=true }
let under_functionrhs ctxt = { ctxt with functionrhs = true }
(*
let reset_semi ctxt = { ctxt with semi=false }
let reset_ifthenelse ctxt = { ctxt with ifthenelse=false }
let reset_pipe ctxt = { ctxt with pipe=false }
*)
let list : 'a . ?sep:space_formatter -> ?first:space_formatter ->
?last:space_formatter -> (Format.formatter -> 'a -> unit) ->
Format.formatter -> 'a list -> unit
= fun ?sep ?first ?last fu f xs ->
let first = match first with Some x -> x |None -> ("": _ format6)
and last = match last with Some x -> x |None -> ("": _ format6)
and sep = match sep with Some x -> x |None -> ("@ ": _ format6) in
let aux f = function
| [] -> ()
| [x] -> fu f x
| xs ->
let rec loop f = function
| [x] -> fu f x
| x::xs -> fu f x; pp f sep; loop f xs;
| _ -> assert false in begin
pp f first; loop f xs; pp f last;
end in
aux f xs
let option : 'a. ?first:space_formatter -> ?last:space_formatter ->
(Format.formatter -> 'a -> unit) -> Format.formatter -> 'a option -> unit
= fun ?first ?last fu f a ->
let first = match first with Some x -> x | None -> ("": _ format6)
and last = match last with Some x -> x | None -> ("": _ format6) in
match a with
| None -> ()
| Some x -> pp f first; fu f x; pp f last
let paren: 'a . ?first:space_formatter -> ?last:space_formatter ->
bool -> (Format.formatter -> 'a -> unit) -> Format.formatter -> 'a -> unit
= fun ?(first=("": _ format6)) ?(last=("": _ format6)) b fu f x ->
if b then (pp f "("; pp f first; fu f x; pp f last; pp f ")")
else fu f x
let rec longident f = function
| Lident s -> ident_of_name f s
| Ldot(y,s) -> protect_longident f longident y s
| Lapply (y,s) ->
pp f "%a(%a)" longident y longident s
let longident_loc f x = pp f "%a" longident x.txt
let constant f = function
| Pconst_char i ->
pp f "%C" i
| Pconst_string (i, _, None) ->
pp f "%S" i
| Pconst_string (i, _, Some delim) ->
pp f "{%s|%s|%s}" delim i delim
| Pconst_integer (i, None) ->
paren (first_is '-' i) (fun f -> pp f "%s") f i
| Pconst_integer (i, Some m) ->
paren (first_is '-' i) (fun f (i, m) -> pp f "%s%c" i m) f (i,m)
| Pconst_float (i, None) ->
paren (first_is '-' i) (fun f -> pp f "%s") f i
| Pconst_float (i, Some m) ->
paren (first_is '-' i) (fun f (i,m) -> pp f "%s%c" i m) f (i,m)
| Pconst_unboxed_float (x, None) ->
paren (first_is '-' x) (fun f -> pp f "%s") f
(Misc.format_as_unboxed_literal x)
| Pconst_unboxed_float (x, Some suffix)
| Pconst_unboxed_integer (x, suffix) ->
paren (first_is '-' x) (fun f (x, suffix) -> pp f "%s%c" x suffix) f
(Misc.format_as_unboxed_literal x, suffix)
(* trailing space*)
let mutable_flag f = function
| Immutable -> ()
| Mutable -> pp f "mutable@;"
let virtual_flag f = function
| Concrete -> ()
| Virtual -> pp f "virtual@;"
(* trailing space added *)
let rec_flag f rf =
match rf with
| Nonrecursive -> ()
| Recursive -> pp f "rec "
let nonrec_flag f rf =
match rf with
| Nonrecursive -> pp f "nonrec "
| Recursive -> ()
let direction_flag f = function
| Upto -> pp f "to@ "
| Downto -> pp f "downto@ "
let private_flag f = function
| Public -> ()
| Private -> pp f "private@ "
let iter_loc f ctxt {txt; loc = _} = f ctxt txt
let constant_string f s = pp f "%S" s
let tyvar_of_name s =
if String.length s >= 2 && s.[1] = '\'' then
(* without the space, this would be parsed as
a character literal *)
"' " ^ s
else if Lexer.is_keyword s then
"'\\#" ^ s
else if String.equal s "_" then
s
else
"'" ^ s
let tyvar ppf s =
Format.fprintf ppf "%s" (tyvar_of_name s)
let string_loc ppf x = fprintf ppf "%s" x.txt
let string_quot f x = pp f "`%a" ident_of_name x
(* legacy modes and modalities *)
let legacy_mode f { txt = Mode s; _ } =
let s =
match s with
| "local" -> "local_"
| "unique" -> "unique_"
| "once" -> "once_"
| s -> Misc.fatal_errorf "Unrecognized mode %s - should not parse" s
in
pp_print_string f s
let legacy_modes f m =
pp_print_list ~pp_sep:(fun f () -> pp f " ") legacy_mode f m
let optional_legacy_modes f m =
match m with
| [] -> ()
| m ->
legacy_modes f m;
pp_print_space f ()
let legacy_modality f m =
let {txt; _} = (m : modality Location.loc) in
let s =
match txt with
| Modality "global" -> "global_"
| Modality s -> Misc.fatal_errorf "Unrecognized modality %s - should not parse" s
in
pp_print_string f s
let legacy_modalities f m =
pp_print_list ~pp_sep:(fun f () -> pp f " ") legacy_modality f m
let optional_legacy_modalities f m =
match m with
| [] -> ()
| m ->
legacy_modalities f m;
pp_print_space f ()
(* new mode and modality syntax *)
let mode f { txt = Mode s; _ } =
pp_print_string f s
let modes f m =
pp_print_list ~pp_sep:(fun f () -> pp f " ") mode f m
let optional_at_modes f m =
match m with
| [] -> ()
| m -> pp f " %@ %a" modes m
let optional_atat_modes f m =
match m with
| [] -> ()
| m -> pp f " %@%@ %a" modes m
let maybe_type_atat_modes pty ctxt f (c, m) =
pp f "%a%a" (pty ctxt) c optional_atat_modes m
let modality f m =
let {txt = Modality txt; _} = m in
pp_print_string f txt
let modalities f m =
pp_print_list ~pp_sep:(fun f () -> pp f " ") modality f m
let optional_atat_modalities f m =
match m with
| [] -> ()
| m -> pp f " %@%@ %a" modalities m
(* helpers for printing both legacy/new mode syntax *)
let split_out_legacy_modes =
List.partition (fun m ->
let Mode txt = m.txt in
match txt with
| "local" | "unique" | "once" -> true
| _ -> false
)
let maybe_legacy_modes_type_at_modes pty ctxt f (c, m) =
let legacy, m = split_out_legacy_modes m in
pp f "%a%a%a" optional_legacy_modes legacy (pty ctxt) c optional_at_modes m
let split_out_legacy_modalities =
List.partition (fun m ->
let Modality txt = m.txt in
match txt with
| "global" -> true
| _ -> false
)
let modalities_type pty ctxt f pca =
let legacy, m = split_out_legacy_modalities pca.pca_modalities in
pp f "%a%a%a"
optional_legacy_modalities legacy
(pty ctxt) pca.pca_type
optional_atat_modalities m
let include_kind f = function
| Functor -> pp f "@ functor"
| Structure -> ()
(* c ['a,'b] *)
let rec class_params_def ctxt f = function
| [] -> ()
| l ->
pp f "[%a] " (* space *)
(list (type_param ctxt) ~sep:",") l
and type_with_label ctxt f (label, c, mode) =
match label with
| Nolabel ->
maybe_legacy_modes_type_at_modes core_type1 ctxt f (c, mode)
(* otherwise parenthesize *)
| Labelled s ->
pp f "%a:%a" ident_of_name s
(maybe_legacy_modes_type_at_modes core_type1 ctxt) (c, mode)
| Optional s ->
pp f "?%a:%a" ident_of_name s
(maybe_legacy_modes_type_at_modes core_type1 ctxt) (c, mode)
and jkind_annotation ?(nested = false) ctxt f k = match k.pjkind_desc with
| Default -> pp f "_"
| Abbreviation s -> pp f "%s" s
| Mod (t, modes) ->
begin match modes with
| [] -> Misc.fatal_error "malformed jkind annotation"
| _ :: _ ->
Misc.pp_parens_if nested (fun f (t, modes) ->
pp f "%a mod %a"
(jkind_annotation ~nested:true ctxt) t
(pp_print_list ~pp_sep:pp_print_space mode) modes
) f (t, modes)
end
| With (t, ty) ->
Misc.pp_parens_if nested (fun f (t, ty) ->
pp f "%a with %a" (jkind_annotation ~nested:true ctxt) t (core_type ctxt)
ty
) f (t, ty)
| Kind_of ty -> pp f "kind_of_ %a" (core_type ctxt) ty
| Product ts ->
Misc.pp_parens_if nested (fun f ts ->
pp f "%a" (list (jkind_annotation ~nested:true ctxt) ~sep:"@;&@;") ts
) f ts
and tyvar_jkind f (str, jkind) =
match jkind with
| None -> tyvar f str
| Some lay -> pp f "(%a : %a)" tyvar str (jkind_annotation reset_ctxt) lay
and tyvar_loc_jkind f (str, jkind) = tyvar_jkind f (str.txt,jkind)
and tyvar_loc_option_jkind f (str, jkind) =
match jkind with
| None -> tyvar_loc_option f str
| Some jkind ->
pp f "(%a : %a)"
tyvar_loc_option str
(jkind_annotation reset_ctxt) jkind
and name_jkind f (name, jkind) =
match jkind with
| None -> ident_of_name f name
| Some jkind ->
pp f "(%a : %a)"
ident_of_name name
(jkind_annotation reset_ctxt) jkind
and core_type ctxt f x =
let filtered_attrs = filter_curry_attrs x.ptyp_attributes in
if filtered_attrs <> [] then begin
pp f "((%a)%a)" (core_type ctxt) {x with ptyp_attributes=[]}
(attributes ctxt) filtered_attrs
end
else match x.ptyp_desc with
| Ptyp_arrow (l, ct1, ct2, m1, m2) ->
pp f "@[<2>%a@;->@;%a@]" (* FIXME remove parens later *)
(type_with_label ctxt) (l,ct1,m1) (return_type ctxt) (ct2,m2)
| Ptyp_alias (ct, s, j) ->
pp f "@[<2>%a@;as@;%a@]" (core_type1 ctxt) ct
tyvar_loc_option_jkind (s, j)
| Ptyp_poly ([], ct) ->
core_type ctxt f ct
| Ptyp_poly (sl, ct) ->
pp f "@[<2>%a%a@]"
(fun f l -> match l with
| [] -> ()
| _ ->
pp f "%a@;.@;"
(list
tyvar_loc_jkind ~sep:"@;")
l)
sl (core_type ctxt) ct
| _ -> pp f "@[<2>%a@]" (core_type1 ctxt) x
and core_type1 ctxt f x =
if has_non_curry_attr x.ptyp_attributes then core_type ctxt f x
else
match x.ptyp_desc with
| Ptyp_any jkind -> tyvar_loc_option_jkind f (None, jkind)
| Ptyp_var (s, jkind) -> tyvar_jkind f (s, jkind)
| Ptyp_tuple tl ->
pp f "(%a)" (list (labeled_core_type1 ctxt) ~sep:"@;*@;") tl
| Ptyp_unboxed_tuple l ->
core_type1_labeled_tuple ctxt f ~unboxed:true l
| Ptyp_constr (li, l) ->
pp f (* "%a%a@;" *) "%a%a"
(fun f l -> match l with
|[] -> ()
|[x]-> pp f "%a@;" (core_type1 ctxt) x
| _ -> list ~first:"(" ~last:")@;" (core_type ctxt) ~sep:",@;" f l)
l longident_loc li
| Ptyp_variant (l, closed, low) ->
let first_is_inherit = match l with
| {Parsetree.prf_desc = Rinherit _}::_ -> true
| _ -> false in
let type_variant_helper f x =
match x.prf_desc with
| Rtag (l, _, ctl) ->
pp f "@[<2>%a%a@;%a@]" (iter_loc string_quot) l
(fun f l -> match l with
|[] -> ()
| _ -> pp f "@;of@;%a"
(list (core_type ctxt) ~sep:"&") ctl) ctl
(attributes ctxt) x.prf_attributes
| Rinherit ct -> core_type ctxt f ct in
pp f "@[<2>[%a%a]@]"
(fun f l ->
match l, closed with
| [], Closed -> ()
| [], Open -> pp f ">" (* Cf #7200: print [>] correctly *)
| _ ->
pp f "%s@;%a"
(match (closed,low) with
| (Closed,None) -> if first_is_inherit then " |" else ""
| (Closed,Some _) -> "<" (* FIXME desugar the syntax sugar*)
| (Open,_) -> ">")
(list type_variant_helper ~sep:"@;<1 -2>| ") l) l
(fun f low -> match low with
|Some [] |None -> ()
|Some xs ->
pp f ">@ %a"
(list string_quot) xs) low
| Ptyp_object (l, o) ->
let core_field_type f x = match x.pof_desc with
| Otag (l, ct) ->
(* Cf #7200 *)
pp f "@[<hov2>%a: %a@ %a@ @]" ident_of_name l.txt
(core_type ctxt) ct (attributes ctxt) x.pof_attributes
| Oinherit ct ->
pp f "@[<hov2>%a@ @]" (core_type ctxt) ct
in
let field_var f = function
| Asttypes.Closed -> ()
| Asttypes.Open ->
match l with
| [] -> pp f ".."
| _ -> pp f " ;.."
in
pp f "@[<hov2><@ %a%a@ > @]"
(list core_field_type ~sep:";") l
field_var o (* Cf #7200 *)
| Ptyp_class (li, l) -> (*FIXME*)
pp f "@[<hov2>%a@;#%a@]"
(list (core_type ctxt) ~sep:"," ~first:"(" ~last:")") l
longident_loc li
| Ptyp_package (lid, cstrs) ->
let aux f (s, ct) =
pp f "type %a@ =@ %a" longident_loc s (core_type ctxt) ct in
(match cstrs with
|[] -> pp f "@[<hov2>(module@ %a)@]" longident_loc lid
|_ ->
pp f "@[<hov2>(module@ %a@ with@ %a)@]" longident_loc lid
(list aux ~sep:"@ and@ ") cstrs)
| Ptyp_open(li, ct) ->
pp f "@[<hov2>%a.(%a)@]" longident_loc li (core_type ctxt) ct
| Ptyp_extension e -> extension ctxt f e
| (Ptyp_arrow _ | Ptyp_alias _ | Ptyp_poly _) ->
paren true (core_type ctxt) f x
and tyvar_option f = function
| None -> pp f "_"
| Some name -> tyvar f name
and tyvar_loc_option f str = tyvar_option f (Option.map Location.get_txt str)
and core_type1_labeled_tuple ctxt f ~unboxed tl =
pp f "%s(%a)" (if unboxed then "#" else "")
(list (labeled_core_type1 ctxt) ~sep:"@;*@;") tl
and labeled_core_type1 ctxt f (label, ty) =
begin match label with
| None -> ()
| Some s -> pp f "%s:" s
end;
core_type1 ctxt f ty
and return_type ctxt f (x, m) =
if x.ptyp_attributes <> [] then maybe_legacy_modes_type_at_modes core_type1 ctxt f (x, m)
else maybe_legacy_modes_type_at_modes core_type ctxt f (x, m)
(********************pattern********************)
(* be cautious when use [pattern], [pattern1] is preferred *)
and pattern ctxt f x =
match Jane_syntax.Pattern.of_ast x with
| Some (jpat, attrs) -> pattern_jane_syntax ctxt attrs f jpat
| None ->
if x.ppat_attributes <> [] then begin
pp f "((%a)%a)" (pattern ctxt) {x with ppat_attributes=[]}
(attributes ctxt) x.ppat_attributes
end
else match x.ppat_desc with
| Ppat_alias (p, s) ->
pp f "@[<2>%a@;as@;%a@]" (pattern ctxt) p ident_of_name s.txt
| _ -> pattern_or ctxt f x
and pattern_or ctxt f x =
let rec left_associative x acc = match x with
| {ppat_desc=Ppat_or (p1,p2); ppat_attributes = []} ->
left_associative p1 (p2 :: acc)
| x -> x :: acc
in
match left_associative x [] with
| [] -> assert false
| [x] -> pattern1 ctxt f x
| orpats ->
pp f "@[<hov0>%a@]" (list ~sep:"@ | " (pattern1 ctxt)) orpats
and pattern1 ctxt (f:Format.formatter) (x:pattern) : unit =
let rec pattern_list_helper f p = match p with
| {ppat_desc =
Ppat_construct
({ txt = Lident("::") ;_},
Some ([], inner_pat));
ppat_attributes = []} ->
begin match Jane_syntax.Pattern.of_ast inner_pat, inner_pat.ppat_desc with
| None, Ppat_tuple([None, pat1; None, pat2], Closed) ->
pp f "%a::%a" (simple_pattern ctxt) pat1 pattern_list_helper pat2 (*RA*)
| _ -> pattern1 ctxt f p
end
| _ -> pattern1 ctxt f p
in
if x.ppat_attributes <> [] then pattern ctxt f x
else match x.ppat_desc with
| Ppat_variant (l, Some p) ->
pp f "@[<2>`%a@;%a@]" ident_of_name l (simple_pattern ctxt) p
| Ppat_construct (({txt=Lident("()"|"[]"|"true"|"false");_}), _) ->
simple_pattern ctxt f x
| Ppat_construct (({txt;_} as li), po) ->
(* FIXME The third field always false *)
if txt = Lident "::" then
pp f "%a" pattern_list_helper x
else
(match po with
| Some ([], x) ->
pp f "%a@;%a" longident_loc li (simple_pattern ctxt) x
| Some (vl, x) ->
pp f "%a@ (type %a)@;%a" longident_loc li
(list ~sep:"@ " ident_of_name_loc) vl
(simple_pattern ctxt) x
| None -> pp f "%a" longident_loc li)
| _ -> simple_pattern ctxt f x
and labeled_pattern1 ctxt (f:Format.formatter) (label, x) : unit =
let simple_name = match x with
| {ppat_desc = Ppat_var { txt=s; _ }; ppat_attributes = []; _} -> Some s
| _ -> None
in
match label, simple_name with
| None, _ ->
pattern1 ctxt f x
| Some lbl, Some simple_name when String.equal simple_name lbl ->
pp f "~%s" lbl
| Some lbl, _ ->
pp f "~%s:" lbl;
pattern1 ctxt f x
and simple_pattern ctxt (f:Format.formatter) (x:pattern) : unit =
if x.ppat_attributes <> [] then pattern ctxt f x
else match Jane_syntax.Pattern.of_ast x with
| Some (jpat, attrs) -> pattern_jane_syntax ctxt attrs f jpat
| None ->
match x.ppat_desc with
| Ppat_construct (({txt=Lident ("()"|"[]"|"true"|"false" as x);_}), None) ->
pp f "%s" x
| Ppat_any -> pp f "_";
| Ppat_var ({txt = txt;_}) -> ident_of_name f txt
| Ppat_array l ->
pp f "@[<2>[|%a|]@]" (list (pattern1 ctxt) ~sep:";") l
| Ppat_unpack { txt = None } ->
pp f "(module@ _)@ "
| Ppat_unpack { txt = Some s } ->
pp f "(module@ %s)@ " s
| Ppat_type li ->
pp f "#%a" longident_loc li
| Ppat_record (l, closed) ->
let longident_x_pattern f (li, p) =
match (li,p) with
| ({txt=Lident s;_ },
{ppat_desc=Ppat_var {txt;_};
ppat_attributes=[]; _})
when s = txt ->
pp f "@[<2>%a@]" longident_loc li
| _ ->
pp f "@[<2>%a@;=@;%a@]" longident_loc li (pattern1 ctxt) p
in
begin match closed with
| Closed ->
pp f "@[<2>{@;%a@;}@]" (list longident_x_pattern ~sep:";@;") l
| _ ->
pp f "@[<2>{@;%a;_}@]" (list longident_x_pattern ~sep:";@;") l
end
| Ppat_tuple (l, closed) ->
labeled_tuple_pattern ctxt f ~unboxed:false l closed
| Ppat_unboxed_tuple (l, closed) ->
labeled_tuple_pattern ctxt f ~unboxed:true l closed
| Ppat_constant (c) -> pp f "%a" constant c
| Ppat_interval (c1, c2) -> pp f "%a..%a" constant c1 constant c2
| Ppat_variant (l,None) -> pp f "`%a" ident_of_name l
| Ppat_constraint (p, ct, m) ->
let legacy, m = split_out_legacy_modes m in
begin match ct, legacy with
| Some ct, [] | Some ({ ptyp_desc = Ptyp_poly _ } as ct), _ ->
pp f "@[<2>(%a%a@;:@;%a%a)@]"
optional_legacy_modes legacy
(pattern1 ctxt) p
(core_type ctxt) ct
optional_atat_modes m
| Some ct, _ :: _ ->
pp f "@[<2>(%a(%a@;:@;%a%a))@]"
optional_legacy_modes legacy
(pattern1 ctxt) p
(core_type ctxt) ct
optional_atat_modes m
| None, _ ->
pp f "@[<2>(%a%a%a)@]"
optional_legacy_modes legacy
(pattern1 ctxt) p
optional_at_modes m
end
| Ppat_lazy p ->
pp f "@[<2>(lazy@;%a)@]" (simple_pattern ctxt) p
| Ppat_exception p ->
pp f "@[<2>exception@;%a@]" (pattern1 ctxt) p
| Ppat_extension e -> extension ctxt f e
| Ppat_open (lid, p) ->
let with_paren =
match Jane_syntax.Pattern.of_ast p with
| Some (jpat, _attrs) -> begin match jpat with
| Jpat_immutable_array (Iapat_immutable_array _) -> false
end
| None -> match p.ppat_desc with
| Ppat_array _ | Ppat_record _
| Ppat_construct (({txt=Lident ("()"|"[]"|"true"|"false");_}), None) ->
false
| _ -> true in
pp f "@[<2>%a.%a @]" longident_loc lid
(paren with_paren @@ pattern1 ctxt) p
| _ -> paren true (pattern ctxt) f x
and pattern_jane_syntax ctxt attrs f (pat : Jane_syntax.Pattern.t) =
if attrs <> [] then
pp f "((%a)%a)" (pattern_jane_syntax ctxt []) pat
(attributes ctxt) attrs
else
match pat with
| Jpat_immutable_array (Iapat_immutable_array l) ->
pp f "@[<2>[:%a:]@]" (list (pattern1 ctxt) ~sep:";") l
and labeled_tuple_pattern ctxt f ~unboxed l closed =
let closed_flag ppf = function
| Closed -> ()
| Open -> pp ppf ",@;.."
in
pp f "@[<1>%s(%a%a)@]"
(if unboxed then "#" else "")
(list ~sep:",@;" (labeled_pattern1 ctxt)) l
closed_flag closed
and label_exp ctxt f (l,opt,p) =
match l with
| Nolabel ->
(* single case pattern parens needed here *)
pp f "%a" (simple_pattern ctxt) p
| Optional rest ->
begin match p with
| {ppat_desc = Ppat_var {txt;_}; ppat_attributes = []}
when txt = rest ->
(match opt with
| Some o ->
pp f "?(%a=@;%a)" ident_of_name rest (expression ctxt) o
| None -> pp f "?%a" ident_of_name rest)
| _ ->
(match opt with
| Some o ->
(* Remove the legacy modes from the pattern here *)
let legacy, p =
match p.ppat_desc with
| Ppat_constraint (p', cty', m') ->
let legacy, m' = split_out_legacy_modes m' in
let p =
match cty', m' with
| None, [] -> p'
| _ -> { p with ppat_desc = Ppat_constraint (p', cty', m') }
in
legacy, p
| _ -> [], p
in
pp f "?%a:(%a%a=@;%a)"
ident_of_name rest
optional_legacy_modes legacy
(pattern1 ctxt) p
(expression ctxt) o
| None -> pp f "?%a:%a" ident_of_name rest (simple_pattern ctxt) p)
end
| Labelled l -> match p with
| {ppat_desc = Ppat_var {txt;_}; ppat_attributes = []}
when txt = l ->
pp f "~%a" ident_of_name l
| _ -> pp f "~%a:%a" ident_of_name l (simple_pattern ctxt) p
and sugar_expr ctxt f e =
if e.pexp_attributes <> [] then false
else match e.pexp_desc with
| Pexp_apply ({ pexp_desc = Pexp_ident {txt = id; _};
pexp_attributes=[]; _}, args)
when List.for_all (fun (lab, _) -> lab = Nolabel) args -> begin
let print_indexop a path_prefix assign left sep right print_index indices
rem_args =
let print_path ppf = function
| None -> ()
| Some m -> pp ppf ".%a" longident m in
match assign, rem_args with
| false, [] ->
pp f "@[%a%a%s%a%s@]"
(simple_expr ctxt) a print_path path_prefix
left (list ~sep print_index) indices right; true
| true, [v] ->
pp f "@[%a%a%s%a%s@ <-@;<1 2>%a@]"
(simple_expr ctxt) a print_path path_prefix
left (list ~sep print_index) indices right
(simple_expr ctxt) v; true
| _ -> false in
match id, List.map snd args with
| Lident "!", [e] ->
pp f "@[<hov>!%a@]" (simple_expr ctxt) e; true
| Ldot (path, ("get"|"set" as func)), a :: other_args -> begin
let assign = func = "set" in
let print = print_indexop a None assign in
match path, other_args with
| Lident "Array", i :: rest ->
print ".(" "" ")" (expression ctxt) [i] rest
| Lident "String", i :: rest ->
print ".[" "" "]" (expression ctxt) [i] rest
| Ldot (Lident "Bigarray", "Array1"), i1 :: rest ->
print ".{" "," "}" (simple_expr ctxt) [i1] rest
| Ldot (Lident "Bigarray", "Array2"), i1 :: i2 :: rest ->
print ".{" "," "}" (simple_expr ctxt) [i1; i2] rest
| Ldot (Lident "Bigarray", "Array3"), i1 :: i2 :: i3 :: rest ->
print ".{" "," "}" (simple_expr ctxt) [i1; i2; i3] rest
| Ldot (Lident "Bigarray", "Genarray"),
{pexp_desc = Pexp_array indexes; pexp_attributes = []} :: rest ->
print ".{" "," "}" (simple_expr ctxt) indexes rest
| _ -> false
end
| (Lident s | Ldot(_,s)) , a :: i :: rest
when first_is '.' s ->
(* extract operator:
assignment operators end with [right_bracket ^ "<-"],
access operators end with [right_bracket] directly
*)
let multi_indices = String.contains s ';' in
let i =
match i.pexp_desc with
| Pexp_array l when multi_indices -> l
| _ -> [ i ] in
let assign = last_is '-' s in
let kind =
(* extract the right end bracket *)
let n = String.length s in
if assign then s.[n - 3] else s.[n - 1] in
let left, right = match kind with
| ')' -> '(', ")"
| ']' -> '[', "]"
| '}' -> '{', "}"
| _ -> assert false in
let path_prefix = match id with
| Ldot(m,_) -> Some m
| _ -> None in
let left = String.sub s 0 (1+String.index s left) in
print_indexop a path_prefix assign left ";" right
(if multi_indices then expression ctxt else simple_expr ctxt)
i rest
| _ -> false
end
| _ -> false
and expression ctxt f x =
match Jane_syntax.Expression.of_ast x with
| Some (jexpr, attrs) -> jane_syntax_expr ctxt attrs f jexpr
| None ->
if x.pexp_attributes <> [] then
pp f "((%a)@,%a)" (expression ctxt) {x with pexp_attributes=[]}
(attributes ctxt) x.pexp_attributes
else match x.pexp_desc with
| Pexp_function _ | Pexp_match _ | Pexp_try _ | Pexp_sequence _
| Pexp_newtype _
when ctxt.pipe || ctxt.semi ->
paren true (expression reset_ctxt) f x
| Pexp_ifthenelse _ | Pexp_sequence _ when ctxt.ifthenelse ->
paren true (expression reset_ctxt) f x
| Pexp_let _ | Pexp_letmodule _ | Pexp_open _
| Pexp_letexception _ | Pexp_letop _
when ctxt.semi ->
paren true (expression reset_ctxt) f x
| Pexp_newtype (lid, jkind, e) ->
pp f "@[<2>fun@;(type@;%a)@;%a@]"
name_jkind (lid.txt, jkind)
(pp_print_pexp_newtype ctxt "->") e
| Pexp_function (params, constraint_, body) ->
begin match params, constraint_ with
(* Omit [fun] if there are no params. *)
| [], None ->
(* If function cases are a direct body of a function,
the function node should be wrapped in parens so
it doesn't become part of the enclosing function. *)
let should_paren =
match body with
| Pfunction_cases _ -> ctxt.functionrhs
| Pfunction_body _ -> false
in
let ctxt' = if should_paren then reset_ctxt else ctxt in
pp f "@[<2>%a@]" (paren should_paren (function_body ctxt')) body
| [], Some constraint_ ->
pp f "@[<2>(%a@;%a)@]"
(function_body ctxt) body
(function_constraint ctxt) constraint_
| _ :: _, _ ->
pp f "@[<2>fun@;%t@]"
(fun f ->
function_params_then_body
ctxt f params constraint_ body ~delimiter:"->")
end
| Pexp_match (e, l) ->
pp f "@[<hv0>@[<hv0>@[<2>match %a@]@ with@]%a@]"
(expression reset_ctxt) e (case_list ctxt) l
| Pexp_try (e, l) ->
pp f "@[<0>@[<hv2>try@ %a@]@ @[<0>with%a@]@]"
(* "try@;@[<2>%a@]@\nwith@\n%a"*)
(expression reset_ctxt) e (case_list ctxt) l
| Pexp_let (rf, l, e) ->
(* pp f "@[<2>let %a%a in@;<1 -2>%a@]"
(*no indentation here, a new line*) *)
(* rec_flag rf *)
pp f "@[<2>%a in@;<1 -2>%a@]"
(bindings reset_ctxt) (rf,l)
(expression ctxt) e
| Pexp_apply
({ pexp_desc = Pexp_extension({txt = "extension.exclave"}, PStr []) },
[Nolabel, sbody]) ->
pp f "@[<2>exclave_ %a@]" (expression ctxt) sbody
| Pexp_apply (e, l) ->
begin if not (sugar_expr ctxt f x) then
match view_fixity_of_exp e with
| `Infix s ->
begin match l with
| [ (Nolabel, _) as arg1; (Nolabel, _) as arg2 ] ->
(* FIXME associativity label_x_expression_param *)
pp f "@[<2>%a@;%s@;%a@]"
(label_x_expression_param reset_ctxt) arg1 s
(label_x_expression_param ctxt) arg2
| _ ->
pp f "@[<2>%a %a@]"
(simple_expr ctxt) e
(list (label_x_expression_param ctxt)) l
end
| `Prefix s ->
let s =
if List.mem s ["~+";"~-";"~+.";"~-."] &&
(match l with
(* See #7200: avoid turning (~- 1) into (- 1) which is
parsed as an int literal *)
|[(_,{pexp_desc=Pexp_constant _})] -> false