forked from janestreet/ocamlformat
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFmt_ast.ml
4739 lines (4566 loc) · 176 KB
/
Fmt_ast.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
(**************************************************************************)
(* *)
(* OCamlFormat *)
(* *)
(* Copyright (c) Facebook, Inc. and its affiliates. *)
(* *)
(* This source code is licensed under the MIT license found in *)
(* the LICENSE file in the root directory of this source tree. *)
(* *)
(**************************************************************************)
(** Format OCaml Ast *)
open Migrate_ast
open Extended_ast
open Asttypes
open Ast
open Fmt
type c =
{ conf: Conf.t
; debug: bool
; source: Source.t
; cmts: Cmts.t
; fmt_code: Conf.t -> Fmt.code_formatter }
module Cmts = struct
include Cmts
let fmt_before c = fmt_before c.cmts c.conf ~fmt_code:c.fmt_code
let fmt_within c = fmt_within c.cmts c.conf ~fmt_code:c.fmt_code
let fmt_after c = fmt_after c.cmts c.conf ~fmt_code:c.fmt_code
let fmt c ?pro ?epi ?eol ?adj loc =
(* remove the before comments from the map first *)
let before = fmt_before c ?pro ?epi ?eol ?adj loc in
(* remove the within comments from the map by accepting the
continuation *)
fun inner ->
(* delay the after comments until the within comments have been
removed *)
let after = fmt_after c ?pro ?epi loc in
let open Fmt in
before $ inner $ after
module Toplevel = struct
let fmt_before c = Toplevel.fmt_before c.cmts c.conf ~fmt_code:c.fmt_code
let fmt_after c = Toplevel.fmt_after c.cmts c.conf ~fmt_code:c.fmt_code
end
end
let cmt_checker {cmts; _} =
{ cmts_before= Cmts.has_before cmts
; cmts_within= Cmts.has_within cmts
; cmts_after= Cmts.has_after cmts }
let break_between c = Ast.break_between c.source (cmt_checker c)
type block =
{ opn: Fmt.t
; pro: Fmt.t option
; psp: Fmt.t
; bdy: Fmt.t
; cls: Fmt.t
; esp: Fmt.t
; epi: Fmt.t option }
let empty =
{ opn= noop
; pro= None
; psp= noop
; bdy= noop
; cls= noop
; esp= noop
; epi= None }
let compose_module {opn; pro; psp; bdy; cls; esp; epi} ~f =
f (fmt_opt pro $ opn $ psp $ bdy $ cls $ esp $ fmt_opt epi)
(* Debug: catch and report failures at nearest enclosing Ast.t *)
let protect =
let first = ref true in
fun c ast pp ->
Fmt.protect pp ~on_error:(fun exc ->
if !first && c.debug then (
let bt = Stdlib.Printexc.get_backtrace () in
Stdlib.Format.eprintf "@\nFAIL@\n%a@\n%s@.%!" Ast.dump ast bt ;
first := false ) ;
raise exc )
let update_config ?quiet c l =
{c with conf= List.fold ~init:c.conf l ~f:(Conf.update ?quiet)}
(* Preserve the position of comments located after the last element of a
list/array (after `;`), otherwise comments are picked up by
`fmt_expression` and printed before `;`. *)
let collection_last_cmt ?pro c (loc : Location.t) locs =
let filter = function Parser.SEMI -> true | _ -> false in
opt (List.last locs) (fun (last : Location.t) ->
match
Source.tokens_between c.source last.loc_end loc.loc_end ~filter
with
| [] -> noop
| (_, semicolon_loc) :: _ ->
Cmts.fmt_after ?pro c last ~filter:(fun Cmt.{loc; _} ->
Location.compare loc semicolon_loc >= 0 ) )
let fmt_elements_collection ?pro ?(first_sep = true) ?(last_sep = true) c
(p : Params.elements_collection) f loc fmt_x xs =
let fmt_one ~first ~last x =
fmt_if_k (not (first && first_sep)) p.sep_before
$ fmt_x x
$ fmt_or_k (last && last_sep) p.sep_after_final p.sep_after_non_final
in
list_fl xs fmt_one $ collection_last_cmt ?pro c loc (List.map ~f xs)
let fmt_expressions c width sub_exp exprs fmt_expr p loc =
match c.conf.fmt_opts.break_collection_expressions.v with
| `Fit_or_vertical ->
fmt_elements_collection c p Exp.location loc fmt_expr exprs
| `Wrap ->
let is_simple x = is_simple c.conf width (sub_exp x) in
let break x1 x2 = not (is_simple x1 && is_simple x2) in
let grps = List.group exprs ~break in
let fmt_grp ~first:first_grp ~last:last_grp exprs =
fmt_elements_collection c ~first_sep:first_grp ~last_sep:last_grp p
Exp.location loc fmt_expr exprs
in
list_fl grps fmt_grp
(** Handle the `break-fun-decl` option *)
let wrap_fun_decl_args c k =
match c.conf.fmt_opts.break_fun_decl.v with
| `Wrap | `Fit_or_vertical -> k
| `Smart -> hvbox 0 k
let box_fun_decl_args c =
match c.conf.fmt_opts.break_fun_decl.v with
| `Fit_or_vertical -> hvbox
| `Wrap | `Smart -> hovbox
(** Handle the `break-fun-sig` option *)
let box_fun_sig_args c =
match c.conf.fmt_opts.break_fun_sig.v with
| _ when c.conf.fmt_opts.ocp_indent_compat.v -> hvbox
| `Fit_or_vertical -> hvbox
| `Wrap | `Smart -> hovbox
let sugar_pmod_functor c ~for_functor_kw pmod =
let source_is_long = Source.is_long_pmod_functor c.source in
Sugar.functor_ c.cmts ~for_functor_kw ~source_is_long pmod
let sugar_pmty_functor c ~for_functor_kw pmty =
let source_is_long = Source.is_long_pmty_functor c.source in
Sugar.functor_type c.cmts ~for_functor_kw ~source_is_long pmty
let closing_paren ?force ?(offset = 0) c =
match c.conf.fmt_opts.indicate_multiline_delimiters.v with
| `No -> str ")"
| `Space -> fits_breaks ")" " )" ?force
| `Closing_on_separate_line -> fits_breaks ")" ")" ~hint:(1000, offset)
let maybe_disabled_k c (loc : Location.t) (l : attributes) f k =
if not c.conf.opr_opts.disable.v then f c
else
let loc = Source.extend_loc_to_include_attributes loc l in
Cmts.drop_inside c.cmts loc ;
let s = Source.string_at c.source loc in
k (Cmts.fmt c loc (str s))
let maybe_disabled c loc l f = maybe_disabled_k c loc l f Fn.id
let update_config_maybe_disabled c loc l f =
let c = update_config c l in
maybe_disabled c loc l f
let update_config_maybe_disabled_block c loc l f =
let fmt bdy = {empty with opn= open_vbox 2; bdy; cls= close_box} in
let c = update_config c l in
maybe_disabled_k c loc l f fmt
let update_items_config c items update_config =
let with_config c i =
let c = update_config c i in
(c, (i, c))
in
let _, items = List.fold_map items ~init:c ~f:with_config in
items
let check_include_functor_attr attrs =
match
List.partition_tf attrs ~f:(fun attr ->
String.equal attr.attr_name.txt "extension.include_functor" )
with
| [], _ -> (attrs, false)
| _ :: _, rest -> (rest, true)
let box_semisemi c ~parent_ctx b k =
let space = Poly.(c.conf.fmt_opts.sequence_style.v = `Separator) in
match parent_ctx with
| _ when not b -> k
| Rep -> k $ fmt_if space " " $ str ";;"
| _ -> hvbox 0 (k $ fmt_or space "@;" "@," $ str ";;")
let fmt_hole () = str "_"
let fmt_item_list c ctx update_config ast fmt_item items =
let items = update_items_config c items update_config in
let break_struct = c.conf.fmt_opts.break_struct.v || is_top ctx in
hvbox 0 @@ list_pn items
@@ fun ~prev (itm, c) ~next ->
let loc = Ast.location (ast itm) in
maybe_disabled c loc [] (fun c -> fmt_item c ctx ~prev ~next itm)
$ opt next (fun (i_n, c_n) ->
fmt_or_k
(break_between c (ast itm, c.conf) (ast i_n, c_n.conf))
(fmt "\n@;<1000 0>")
(fmt_or break_struct "@;<1000 0>" "@ ") )
let fmt_recmodule c ctx items fmt_item ast =
let update_config c i = update_config c (Ast.attributes (ast i)) in
let fmt_item c ctx ~prev ~next:_ i =
fmt_item c ctx ~rec_flag:true ~first:(Option.is_none prev) i
in
fmt_item_list c ctx update_config ast fmt_item items
(* In several places, naked newlines (i.e. not "@\n") are used to avoid
trailing space in open lines. *)
(* In several places, a break such as "@;<1000 0>" is used to force the
enclosing box to break across multiple lines. *)
let rec fmt_longident (li : Longident.t) =
match li with
| Lident id -> str id
| Ldot (li, id) ->
hvbox 0
( fmt_longident li $ fmt "@,."
$ wrap_if (Std_longident.String_id.is_symbol id) "( " " )" (str id)
)
| Lapply (li1, li2) ->
hvbox 2 (fmt_longident li1 $ wrap "@,(" ")" (fmt_longident li2))
let fmt_longident_loc c ?pre {txt; loc} =
Cmts.fmt c loc (opt pre str $ fmt_longident txt)
let str_longident x =
Format_.asprintf "%a" (fun fs x -> eval fs (fmt_longident x)) x
let fmt_str_loc c ?pre {txt; loc} = Cmts.fmt c loc (opt pre str $ str txt)
let fmt_str_loc_opt c ?pre ?(default = "_") {txt; loc} =
Cmts.fmt c loc (opt pre str $ str (Option.value ~default txt))
let variant_var c ({txt= x; loc} : variant_var) =
Cmts.fmt c loc @@ (str "`" $ fmt_str_loc c x)
let fmt_constant c ?epi {pconst_desc; pconst_loc= loc} =
Cmts.fmt c loc
@@
match pconst_desc with
| Pconst_unboxed_integer (sign, lit, suf)
|Pconst_unboxed_float (sign, lit, suf) ->
(match sign with Positive -> noop | Negative -> char '-')
$ char '#' $ str lit $ opt suf char
| Pconst_integer (lit, suf) | Pconst_float (lit, suf) ->
str lit $ opt suf char
| Pconst_char _ -> wrap "'" "'" @@ str (Source.char_literal c.source loc)
| Pconst_string (s, loc', Some delim) ->
Cmts.fmt c loc'
@@ wrap_k (str ("{" ^ delim ^ "|")) (str ("|" ^ delim ^ "}")) (str s)
| Pconst_string (_, loc', None) -> (
let delim = ["@,"; "@;"] in
let contains_pp_commands s =
let is_substring substring = String.is_substring s ~substring in
List.exists delim ~f:is_substring
in
let fmt_string_auto ~break_on_newlines s =
let fmt_words ~epi s =
let words = String.split s ~on:' ' in
let fmt_word ~prev:_ curr ~next =
match next with
| Some "" -> str curr $ str " "
| Some _ ->
str curr $ cbreak ~fits:("", 1, "") ~breaks:(" \\", 0, "")
| None -> str curr
in
hovbox_if (List.length words > 1) 0 (list_pn words fmt_word $ epi)
in
let fmt_line ~epi ~prev:_ curr ~next =
let not_suffix suffix = not (String.is_suffix curr ~suffix) in
let print_ln =
List.for_all delim ~f:not_suffix || not break_on_newlines
in
let fmt_next next =
if String.is_empty next then fmt_if_k print_ln (str "\\n")
else if Char.equal next.[0] ' ' then
fmt_if_k print_ln (str "\\n")
$ cbreak ~fits:("", 0, "") ~breaks:("\\", -1, "\\")
else
fmt_if_k print_ln (str "\\n")
$ cbreak ~fits:("", 0, "") ~breaks:("\\", 0, "")
in
let epi = match next with Some _ -> noop | None -> epi in
fmt_words ~epi curr $ opt next fmt_next
in
let lines = String.split ~on:'\n' s in
let lines =
if break_on_newlines then lines
else
let n_lines = List.length lines in
(* linebreaks are merged with the preceding line when possible
instead of having a blank line in the list *)
List.foldi lines ~init:[] ~f:(fun i acc -> function
| "" when i < n_lines - 1 -> (
match acc with [] -> [""] | h :: t -> (h ^ "\\n") :: t )
| line -> line :: acc )
|> List.rev
in
let epi = str "\"" $ fmt_opt epi in
hvbox 1 (str "\"" $ list_pn lines (fmt_line ~epi))
in
let preserve_or_normalize =
match c.conf.fmt_opts.break_string_literals.v with
| `Never -> `Preserve
| `Auto -> `Normalize
in
let s = Source.string_literal c.source preserve_or_normalize loc in
Cmts.fmt c loc'
@@
match c.conf.fmt_opts.break_string_literals.v with
| `Auto when contains_pp_commands s ->
let break_on_pp_commands in_ pattern =
String.substr_replace_all in_ ~pattern ~with_:(pattern ^ "\n")
in
List.fold_left delim ~init:s ~f:break_on_pp_commands
|> fmt_string_auto ~break_on_newlines:true
| `Auto -> fmt_string_auto ~break_on_newlines:false s
| `Never -> wrap "\"" "\"" (str s) )
let fmt_variance_injectivity c vc = hvbox 0 (list vc "" (fmt_str_loc c))
let fmt_label lbl sep =
match lbl with
| Nolabel -> noop
| Labelled l -> str "~" $ str l $ fmt sep
| Optional l -> str "?" $ str l $ fmt sep
let fmt_direction_flag = function
| Upto -> fmt "@ to "
| Downto -> fmt "@ downto "
let fmt_private ?(pro = fmt "@ ") c loc =
pro $ hvbox 0 @@ Cmts.fmt c loc @@ str "private"
let fmt_virtual ?(pro = fmt "@ ") c loc =
pro $ hvbox 0 @@ Cmts.fmt c loc @@ str "virtual"
let fmt_mutable ?(pro = fmt "@ ") c loc =
pro $ hvbox 0 @@ Cmts.fmt c loc @@ str "mutable"
let fmt_private_flag c = function
| Private loc -> fmt_private c loc
| Public -> noop
let fmt_virtual_flag c = function
| Virtual loc -> fmt_virtual c loc
| Concrete -> noop
let fmt_mutable_flag c = function
| Mutable loc -> fmt_mutable ~pro:noop c loc $ fmt "@ "
| Immutable -> noop
let fmt_mutable_virtual_flag c = function
| {mv_mut= Some m; mv_virt= Some v} when Location.compare_start v m < 1 ->
fmt_virtual c v $ fmt_mutable c m
| {mv_mut; mv_virt} ->
opt mv_mut (fmt_mutable c) $ opt mv_virt (fmt_virtual c)
let fmt_private_virtual_flag c = function
| {pv_priv= Some p; pv_virt= Some v} when Location.compare_start v p < 1 ->
fmt_virtual c v $ fmt_private c p
| {pv_priv; pv_virt} ->
opt pv_priv (fmt_private c) $ opt pv_virt (fmt_virtual c)
let virtual_or_override = function
| Cfk_virtual _ -> noop
| Cfk_concrete (Override, _) -> str "!"
| Cfk_concrete (Fresh, _) -> noop
let fmt_parsed_docstring c ~loc ?pro ~epi str_cmt parsed =
assert (not (String.is_empty str_cmt)) ;
let fmt_parsed parsed =
fmt_if (String.starts_with_whitespace str_cmt) " "
$ Fmt_odoc.fmt ~fmt_code:(c.fmt_code c.conf) parsed
$ fmt_if
(String.length str_cmt > 1 && String.ends_with_whitespace str_cmt)
" "
in
let fmt_raw str_cmt = str str_cmt in
let doc =
match parsed with
| _ when not c.conf.fmt_opts.parse_docstrings.v -> fmt_raw str_cmt
| Ok parsed -> fmt_parsed parsed
| Error msgs ->
if not c.conf.opr_opts.quiet.v then
List.iter msgs ~f:(Docstring.warn Format.err_formatter) ;
fmt_raw str_cmt
in
Cmts.fmt c loc
@@ vbox_if (Option.is_none pro) 0 (fmt_opt pro $ wrap "(**" "*)" doc $ epi)
let docstring_epi ~standalone ~next ~epi ~floating =
let epi = if Option.is_some next then fmt "@\n" else fmt_opt epi in
match next with
| (None | Some (_, false)) when floating && not standalone ->
str "\n" $ epi
| _ -> epi
let fmt_docstring c ?(standalone = false) ?pro ?epi doc =
list_pn (Option.value ~default:[] doc)
(fun ~prev:_ ({txt; loc}, floating) ~next ->
let epi = docstring_epi ~standalone ~next ~epi ~floating in
fmt_parsed_docstring c ~loc ?pro ~epi txt (Docstring.parse ~loc txt) )
let fmt_docstring_around_item' ?(is_val = false) ?(force_before = false)
?(fit = false) c doc1 doc2 =
match (doc1, doc2) with
| Some _, Some _ ->
( fmt_docstring c ~epi:(fmt "@\n") doc1
, fmt_docstring c ~pro:(fmt "@\n") doc2 )
| None, None -> (noop, noop)
| None, Some doc | Some doc, None -> (
let is_tag_only =
List.for_all ~f:(function
| Ok es, _ -> Docstring.is_tag_only es
| _ -> false )
in
let fmt_doc ?epi ?pro doc =
list_pn doc (fun ~prev:_ (parsed, ({txt; loc}, floating)) ~next ->
let next = Option.map next ~f:snd in
let epi = docstring_epi ~standalone:false ~next ~epi ~floating in
fmt_parsed_docstring c ~loc ~epi ?pro txt parsed )
in
let floating_doc, doc =
doc
|> List.map ~f:(fun (({txt; loc}, _) as doc) ->
(Docstring.parse ~loc txt, doc) )
|> List.partition_tf ~f:(fun (_, (_, floating)) -> floating)
in
let placement =
if force_before then `Before
else if
Poly.( = ) c.conf.fmt_opts.doc_comments_tag_only.v `Fit
&& fit && is_tag_only doc
then `Fit
else
let ((`Before | `After) as conf) =
match c.conf.fmt_opts.doc_comments.v with
| `After_when_possible -> `After
| `Before_except_val when is_val -> `After
| `Before_except_val -> `Before
| `Before -> `Before
in
conf
in
let floating_doc = fmt_doc ~epi:(fmt "@\n") floating_doc in
match placement with
| `Before -> (floating_doc $ fmt_doc ~epi:(fmt "@\n") doc, noop)
| `After -> (floating_doc, fmt_doc ~pro:(fmt "@\n") doc)
| `Fit ->
( floating_doc
, fmt_doc ~pro:(break c.conf.fmt_opts.doc_comments_padding.v 0) doc
) )
(** Formats docstrings and decides where to place them Handles the
[doc-comments] and [doc-comment-tag-only] options Returns the tuple
[doc_before, doc_after, attrs] *)
let fmt_docstring_around_item ?is_val ?force_before ?fit c attrs =
let doc1, attrs = doc_atrs attrs in
let doc2, attrs = doc_atrs attrs in
let doc_before, doc_after =
fmt_docstring_around_item' ?is_val ?force_before ?fit c doc1 doc2
in
(doc_before, doc_after, attrs)
let fmt_extension_suffix c ext =
opt ext (fun name -> str "%" $ fmt_str_loc c name)
let is_arrow_or_poly = function
| {ptyp_desc= Ptyp_arrow _ | Ptyp_poly _; _} -> true
| _ -> false
let fmt_assign_arrow c =
match c.conf.fmt_opts.assignment_operator.v with
| `Begin_line -> fmt "@;<1 2><- "
| `End_line -> fmt " <-@;<1 2>"
let arrow_sep c ~parens : Fmt.s =
match c.conf.fmt_opts.break_separators.v with
| `Before -> if parens then "@;<1 1>-> " else "@ -> "
| `After -> " ->@;<1 0>"
let fmt_docstring_padded c doc =
fmt_docstring c ~pro:(break c.conf.fmt_opts.doc_comments_padding.v 0) doc
let sequence_blank_line c (l1 : Location.t) (l2 : Location.t) =
match c.conf.fmt_opts.sequence_blank_line.v with
| `Preserve_one ->
let rec loop prev_pos = function
| cmt :: tl ->
(* Check empty line before each comment *)
Source.empty_line_between c.source prev_pos cmt.Cmt.loc.loc_start
|| loop cmt.Cmt.loc.loc_end tl
| [] ->
(* Check empty line after all comments *)
Source.empty_line_between c.source prev_pos l2.loc_start
in
loop l1.loc_end (Cmts.remaining_before c.cmts l2)
| `Compact -> false
let fmt_quoted_string key ext s = function
| None ->
wrap_k (str (Format_.sprintf "{%s%s|" key ext)) (str "|}") (str s)
| Some delim ->
let ext_and_delim =
if String.is_empty delim then ext
else Format_.sprintf "%s %s" ext delim
in
wrap_k
(str (Format_.sprintf "{%s%s|" key ext_and_delim))
(str (Format_.sprintf "|%s}" delim))
(str s)
let fmt_type_var s =
str "'"
(* [' a'] is a valid type variable, the space is required to not lex as a
char. https://github.com/ocaml/ocaml/pull/2034 *)
$ fmt_if (String.length s > 1 && Char.equal s.[1] '\'') " "
$ str s
let split_global_flags_from_attrs atrs =
match
List.partition_map atrs ~f:(fun a ->
match a.attr_name.txt with
| "extension.global" -> First `Global
| _ -> Second a )
with
| [`Global], atrs -> (true, atrs)
| _ -> (false, atrs)
let is_layout attr =
match attr.attr_name.txt with
| "any" -> true
| "value" -> true
| "void" -> true
| "immediate" -> true
| "immediate64" -> true
| "float64" -> true
| _ -> false
let rec fmt_extension_aux c ctx ~key (ext, pld) =
match (ext.txt, pld, ctx) with
(* Quoted extensions (since ocaml 4.11). *)
| ( ext
, PStr
[ { pstr_desc=
Pstr_eval
( { pexp_desc=
Pexp_constant
{pconst_desc= Pconst_string (str, loc, delim); _}
; pexp_loc
; pexp_loc_stack= _
; pexp_attributes= [] }
, [] )
; pstr_loc } ]
, _ )
when Source.is_quoted_string c.source pstr_loc ->
(* Comments and attributes are not allowed by the parser *)
assert (not (Cmts.has_before c.cmts loc)) ;
assert (not (Cmts.has_after c.cmts loc)) ;
assert (not (Cmts.has_before c.cmts pexp_loc)) ;
assert (not (Cmts.has_after c.cmts pexp_loc)) ;
assert (not (Cmts.has_before c.cmts pstr_loc)) ;
assert (not (Cmts.has_after c.cmts pstr_loc)) ;
hvbox 0 (fmt_quoted_string (Ext.Key.to_string key) ext str delim)
| _, PStr [({pstr_loc; _} as si)], (Pld _ | Str _ | Top)
when Source.extension_using_sugar ~name:ext ~payload:pstr_loc ->
fmt_structure_item c ~last:true ~ext ~semisemi:false (sub_str ~ctx si)
| _, PSig [({psig_loc; _} as si)], (Pld _ | Sig _ | Top)
when Source.extension_using_sugar ~name:ext ~payload:psig_loc ->
fmt_signature_item c ~ext (sub_sig ~ctx si)
| _, PPat (({ppat_loc; _} as pat), _), (Pld _ | Top)
when Source.extension_using_sugar ~name:ext ~payload:ppat_loc ->
fmt_pattern c ~ext (sub_pat ~ctx pat)
| _ ->
wrap "[" "]"
( str (Ext.Key.to_string key)
$ fmt_str_loc c ext
$ fmt_payload c (Pld pld) pld
$ fmt_if (Exposed.Right.payload pld) " " )
and fmt_extension = fmt_extension_aux ~key:Ext.Key.Regular
and fmt_item_extension = fmt_extension_aux ~key:Ext.Key.Item
and fmt_attribute c ~key {attr_name; attr_payload; attr_loc} =
hvbox 0 @@ Cmts.fmt c attr_loc
@@
match (attr_name, attr_payload) with
| ( {txt= ("ocaml.doc" | "ocaml.text") as txt; loc= {loc_ghost= true; _}}
, PStr
[ { pstr_desc=
Pstr_eval
( { pexp_desc=
Pexp_constant
{pconst_desc= Pconst_string (doc, _, None); _}
; pexp_attributes= []
; _ }
, [] )
; _ } ] ) ->
fmt_or (String.equal txt "ocaml.text") "@ " " "
$ wrap "(**" "*)" (str doc)
| name, pld ->
let indent =
match (pld, key) with
| (PStr _ | PSig _), Attr.Key.Floating ->
c.conf.fmt_opts.stritem_extension_indent.v
| _ -> c.conf.fmt_opts.extension_indent.v
in
hvbox indent
(wrap "[" "]"
( str (Attr.Key.to_string key)
$ fmt_str_loc c name
$ fmt_payload c (Pld pld) pld
$ fmt_if (Exposed.Right.payload pld) " " ) )
and fmt_attributes_aux c ?pre ?suf ~key attrs =
let num = List.length attrs in
fmt_if_k (num > 0)
( opt pre (function
(* Breaking before an attribute can confuse ocp-indent that will
produce a suboptimal indentation. *)
| Space when c.conf.fmt_opts.ocp_indent_compat.v -> sp Blank
| pre -> sp pre )
$ hvbox_if (num > 1) 0
(hvbox 0 (list attrs "@ " (fmt_attribute c ~key)) $ opt suf str) )
and fmt_attributes = fmt_attributes_aux ~key:Attr.Key.Regular
and fmt_item_attributes = fmt_attributes_aux ~key:Attr.Key.Item
and fmt_attributes_and_docstrings_aux c ~key attrs =
let standalone, pro, space =
match key with
| Attr.Key.Regular | Attr.Key.Item ->
(false, break c.conf.fmt_opts.doc_comments_padding.v 0, break 1 0)
| Attr.Key.Floating -> (true, noop, noop)
in
let aux = function
| { attr_name=
{txt= "ocaml.doc" | "ocaml.text"; loc= {loc_ghost= true; _}}
; attr_payload=
PStr
[ { pstr_desc=
Pstr_eval
( { pexp_desc=
Pexp_constant
{pconst_desc= Pconst_string (txt, _, None); _}
; pexp_loc= loc
; pexp_attributes= []
; _ }
, [] )
; _ } ]
; _ } ->
fmt_docstring c ~standalone ~pro (Some [({txt; loc}, standalone)])
| attr -> space $ fmt_attribute c ~key attr
in
list attrs "" aux
and fmt_attributes_and_docstrings =
fmt_attributes_and_docstrings_aux ~key:Attr.Key.Regular
and fmt_floating_attributes_and_docstrings =
fmt_attributes_and_docstrings_aux ~key:Attr.Key.Floating
and fmt_payload c ctx pld =
protect c (Pld pld)
@@
match pld with
| PStr mex ->
fmt_if (not (List.is_empty mex)) "@ " $ fmt_structure c ctx mex
| PSig mty ->
fmt ":@ "
(* A trailing space is necessary because [:]] is the immutable array
closing delimiter*)
$ fmt_signature c ctx mty
| PTyp typ -> fmt ":@ " $ fmt_core_type c (sub_typ ~ctx typ)
| PPat (pat, exp) ->
let fmt_when exp =
str " when " $ fmt_expression c (sub_exp ~ctx exp)
in
fmt "?@ " $ fmt_pattern c (sub_pat ~ctx pat) $ opt exp fmt_when
and fmt_record_field c ?typ1 ?typ2 ?rhs lid1 =
let field_space =
match c.conf.fmt_opts.field_space.v with
| `Loose | `Tight_decl -> str " "
| `Tight -> noop
in
let t1 = Option.map typ1 ~f:(fun x -> fmt ": " $ fmt_core_type c x) in
let t2 = Option.map typ2 ~f:(fun x -> fmt ":> " $ fmt_core_type c x) in
let r = Option.map rhs ~f:(fun x -> fmt "=@;<1 2>" $ cbox 0 x) in
let fmt_type_rhs =
match List.filter_opt [t1; t2; r] with
| [] -> noop
| l -> field_space $ list l "@ " Fn.id
in
Cmts.fmt_before c lid1.loc
$ cbox 0
(fmt_longident_loc c lid1 $ Cmts.fmt_after c lid1.loc $ fmt_type_rhs)
and fmt_type_cstr c ?constraint_ctx xtyp =
let colon_before = Poly.(c.conf.fmt_opts.break_colon.v = `Before) in
fmt_or_k colon_before (fits_breaks " " ~hint:(1000, 0) "") (fmt "@;<0 -1>")
$ cbox_if colon_before 0
(fmt_core_type c ~pro:":" ?constraint_ctx ~pro_space:(not colon_before)
~box:(not colon_before) xtyp )
and type_constr_and_body c xbody =
let body = xbody.ast in
let ctx = Exp body in
let fmt_cstr_and_xbody typ exp =
( Some (fmt_type_cstr c ~constraint_ctx:`Fun (sub_typ ~ctx typ))
, sub_exp ~ctx exp )
in
match xbody.ast.pexp_desc with
| Pexp_constraint (exp, typ) ->
Cmts.relocate c.cmts ~src:body.pexp_loc ~before:exp.pexp_loc
~after:exp.pexp_loc ;
fmt_cstr_and_xbody typ exp
| _ -> (None, xbody)
and fmt_arrow_param c ctx
({pap_label= lI; pap_loc= locI; pap_type= tI}, localI) =
let arg_label lbl =
match lbl with
| Nolabel -> if localI then Some (str "local_ ") else None
| Labelled l -> Some (str l $ fmt ":@," $ fmt_if localI "local_ ")
| Optional l ->
Some (str "?" $ str l $ fmt ":@," $ fmt_if localI "local_ ")
in
let xtI = sub_typ ~ctx tI in
let arg =
match arg_label lI with
| None -> fmt_core_type c xtI
| Some f -> hovbox 2 (f $ fmt_core_type c xtI)
in
hvbox 0 (Cmts.fmt_before c locI $ arg)
(* The context of [xtyp] refers to the RHS of the expression (namely
Pexp_constraint) and does not give a relevant information as to whether
[xtyp] should be parenthesized. [constraint_ctx] gives the higher context
of the expression, i.e. if the expression is part of a `fun`
expression. *)
(* CR layouts: Instead of having a [tydecl_param] argument here, the right
thing would be for [xtyp] to provide enough information to determine
whether we are printing a type parameter in a typedecl. But it doesn't,
and that change would be a much bigger diff and make rebasing on upstream
harder in the future. When layouts are upstreamed and upstream ocamlformat
gets support for them, we should remove tydecl_param and go with whatever
their solution is. *)
and fmt_core_type c ?(box = true) ?pro ?(pro_space = true) ?constraint_ctx
?(tydecl_param = false) ({ast= typ; ctx} as xtyp) =
protect c (Typ typ)
@@
let {ptyp_desc; ptyp_attributes; ptyp_loc; _} = typ in
let ptyp_attributes =
List.filter ptyp_attributes ~f:(fun a ->
not (String.equal a.attr_name.txt "extension.curry") )
in
let ptyp_attributes =
List.filter ptyp_attributes ~f:(fun a ->
not (String.equal a.attr_name.txt "extension.global") )
in
update_config_maybe_disabled c ptyp_loc ptyp_attributes
@@ fun c ->
( match pro with
| Some pro -> (
match c.conf.fmt_opts.break_colon.v with
| `Before -> fmt_if pro_space "@;" $ str pro $ str " "
| `After -> fmt_if pro_space " " $ str pro $ fmt "@ " )
| None -> noop )
$
let doc, atrs = doc_atrs ptyp_attributes in
Cmts.fmt c ptyp_loc
@@ (fun k -> k $ fmt_docstring c ~pro:(fmt "@ ") doc)
@@ ( match atrs with
| [] -> Fn.id
| [attr] when is_layout attr ->
Fn.id
(* CR layouts v1.5: layout annotations on type params are printed by
the type parameter printer. Revisit when we have support for
pretty layout annotations in more places. *)
| _ ->
fun k ->
hvbox 0
(Params.parens_if (not tydecl_param) c.conf
(k $ fmt_attributes c ~pre:Cut atrs) ) )
@@
let parens = (not tydecl_param) && parenze_typ xtyp in
hvbox_if box 0
@@ Params.parens_if
(match typ.ptyp_desc with Ptyp_tuple _ -> false | _ -> parens)
c.conf
@@
let in_type_declaration = match ctx with Td _ -> true | _ -> false in
let ctx = Typ typ in
let parenze_constraint_ctx =
match constraint_ctx with
| Some `Fun when not parens -> wrap "(" ")"
| _ -> Fn.id
in
match ptyp_desc with
| Ptyp_alias (typ, str) ->
hvbox 0
(parenze_constraint_ctx
( fmt_core_type c (sub_typ ~ctx typ)
$ fmt "@ as@ "
$ Cmts.fmt c str.loc @@ fmt_type_var str.txt ) )
| Ptyp_any -> str "_"
| Ptyp_arrow (ctl, ct2) ->
Cmts.relocate c.cmts ~src:ptyp_loc
~before:(List.hd_exn ctl).pap_type.ptyp_loc ~after:ct2.ptyp_loc ;
let xt1N, ctx = Sugar.decompose_arrow ctx ctl ct2 in
let indent =
if Poly.(c.conf.fmt_opts.break_separators.v = `Before) then 2 else 0
in
( match pro with
| Some pro when c.conf.fmt_opts.ocp_indent_compat.v ->
fits_breaks ""
(String.make (Int.max 1 (indent - String.length pro)) ' ')
| _ ->
fmt_if_k
Poly.(c.conf.fmt_opts.break_separators.v = `Before)
(fmt_or_k c.conf.fmt_opts.ocp_indent_compat.v (fits_breaks "" "")
(fits_breaks "" " ") ) )
$ parenze_constraint_ctx
(list xt1N (arrow_sep c ~parens) (fmt_arrow_param c ctx))
| Ptyp_constr (lid, []) -> fmt_longident_loc c lid
| Ptyp_constr (lid, [t1]) ->
fmt_core_type c (sub_typ ~ctx t1) $ fmt "@ " $ fmt_longident_loc c lid
| Ptyp_constr (lid, t1N) ->
wrap_fits_breaks c.conf "(" ")"
(list t1N (Params.comma_sep c.conf)
(sub_typ ~ctx >> fmt_core_type c) )
$ fmt "@ " $ fmt_longident_loc c lid
| Ptyp_extension ext ->
hvbox c.conf.fmt_opts.extension_indent.v (fmt_extension c ctx ext)
| Ptyp_package (id, cnstrs) ->
hvbox 2
( hovbox 0 (fmt "module@ " $ fmt_longident_loc c id)
$ fmt_package_type c ctx cnstrs )
| Ptyp_poly ([], _) ->
impossible "produced by the parser, handled elsewhere"
| Ptyp_poly (a1N, t) ->
hovbox_if box 0
( list a1N "@ " (fun {txt; _} -> fmt_type_var txt)
$ fmt ".@ "
$ fmt_core_type c ~box:true (sub_typ ~ctx t) )
| Ptyp_tuple typs ->
hvbox 0
(parenze_constraint_ctx
(wrap_fits_breaks_if ~space:false c.conf parens "(" ")"
(list typs "@ * " (sub_typ ~ctx >> fmt_core_type c)) ) )
| Ptyp_var s -> fmt_type_var s
| Ptyp_variant (rfs, flag, lbls) ->
let row_fields rfs =
match rfs with
| [] -> Cmts.fmt_within c ~pro:noop ptyp_loc
| _ ->
list rfs
( if
in_type_declaration
&& Poly.(c.conf.fmt_opts.type_decl.v = `Sparse)
then "@;<1000 0>| "
else "@ | " )
(fmt_row_field c ctx)
in
let protect_token = Exposed.Right.(list ~elt:row_field) rfs in
let space_around = c.conf.fmt_opts.space_around_variants.v in
let closing =
let empty = List.is_empty rfs in
let force =
match c.conf.fmt_opts.type_decl.v with
| `Sparse -> Option.some_if space_around Break
| `Compact -> None
in
let nspaces = if empty then 0 else 1 in
let space = (protect_token || space_around) && not empty in
fits_breaks
(if space && not empty then " ]" else "]")
~hint:(nspaces, 0) "]" ?force
in
hvbox 0
( match (flag, lbls, rfs) with
| Closed, None, [{prf_desc= Rinherit _; _}] ->
str "[ | " $ row_fields rfs $ closing
| Closed, None, _ ->
let opening = if space_around then "[ " else "[" in
fits_breaks opening "[ " $ row_fields rfs $ closing
| Open, None, _ -> str "[> " $ row_fields rfs $ closing
| Closed, Some [], _ -> str "[< " $ row_fields rfs $ closing
| Closed, Some ls, _ ->
str "[< " $ row_fields rfs $ str " > "
$ list ls "@ " (variant_var c)
$ closing
| Open, Some _, _ -> impossible "not produced by parser" )
| Ptyp_object ([], closed_flag) ->
wrap "<@ " ">"
( match closed_flag with
| OClosed -> Cmts.fmt_within c ~pro:noop ~epi:(str " ") ptyp_loc
| OOpen loc -> Cmts.fmt c loc (str "..") $ fmt "@ " )
| Ptyp_object (fields, closed_flag) ->
let fmt_field {pof_desc; pof_attributes; pof_loc} =
let fmt_field =
match pof_desc with
| Otag (lab_loc, typ) ->
(* label loc * attributes * core_type -> object_field *)
let field_loose =
match c.conf.fmt_opts.field_space.v with
| `Loose | `Tight_decl -> true
| `Tight -> false
in
fmt_str_loc c lab_loc $ fmt_if field_loose " " $ fmt ":@ "
$ fmt_core_type c (sub_typ ~ctx typ)
| Oinherit typ -> fmt_core_type c (sub_typ ~ctx typ)
in
Cmts.fmt c pof_loc
@@ hvbox 4
( hvbox 2 fmt_field
$ fmt_attributes_and_docstrings c pof_attributes )
in
hvbox 0
(wrap "< " " >"
( list fields "@ ; " fmt_field
$
match closed_flag with
| OClosed -> noop
| OOpen loc -> fmt "@ ; " $ Cmts.fmt c loc @@ str ".." ) )
| Ptyp_class (lid, []) -> fmt_longident_loc c ~pre:"#" lid
| Ptyp_class (lid, [t1]) ->
fmt_core_type c (sub_typ ~ctx t1)
$ fmt "@ "
$ fmt_longident_loc c ~pre:"#" lid
| Ptyp_class (lid, t1N) ->
wrap_fits_breaks c.conf "(" ")"
(list t1N (Params.comma_sep c.conf)
(sub_typ ~ctx >> fmt_core_type c) )
$ fmt "@ "
$ fmt_longident_loc c ~pre:"#" lid
| Ptyp_constr_unboxed (lid, []) -> fmt_longident_loc c lid $ char '#'
| Ptyp_constr_unboxed (lid, [t1]) ->
fmt_core_type c (sub_typ ~ctx t1)
$ fmt "@ " $ fmt_longident_loc c lid $ char '#'
| Ptyp_constr_unboxed (lid, t1N) ->
wrap_fits_breaks c.conf "(" ")"
(list t1N (Params.comma_sep c.conf)
(sub_typ ~ctx >> fmt_core_type c) )
$ fmt "@ " $ fmt_longident_loc c lid $ char '#'
and fmt_package_type c ctx cnstrs =
let fmt_cstr ~first ~last:_ (lid, typ) =
fmt_or first "@;<1 0>" "@;<1 1>"
$ hvbox 2
( fmt_or first "with type " "and type "
$ fmt_longident_loc c lid $ fmt " =@ "
$ fmt_core_type c (sub_typ ~ctx typ) )
in
list_fl cnstrs fmt_cstr
and fmt_row_field c ctx {prf_desc; prf_attributes; prf_loc} =
let c = update_config c prf_attributes in
let row =
match prf_desc with
| Rtag (name, const, typs) ->
variant_var c name
$ fmt_if (not (const && List.is_empty typs)) " of@ "
$ fmt_if (const && not (List.is_empty typs)) " & "
$ list typs "@ & " (sub_typ ~ctx >> fmt_core_type c)
| Rinherit typ -> fmt_core_type c (sub_typ ~ctx typ)
in
hvbox 0
( hvbox 0 (Cmts.fmt c prf_loc row)
$ fmt_attributes_and_docstrings c prf_attributes )
and fmt_pattern_attributes c xpat k =