This repository has been archived by the owner on Jun 15, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 38
/
res_printer.ml
5677 lines (5540 loc) · 185 KB
/
res_printer.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
module Doc = Res_doc
module CommentTable = Res_comments_table
module Comment = Res_comment
module Token = Res_token
module Parens = Res_parens
module ParsetreeViewer = Res_parsetree_viewer
type callbackStyle =
(* regular arrow function, example: `let f = x => x + 1` *)
| NoCallback
(* `Thing.map(foo, (arg1, arg2) => MyModuleBlah.toList(argument))` *)
| FitsOnOneLine
(* Thing.map(longArgumet, veryLooooongArgument, (arg1, arg2) =>
* MyModuleBlah.toList(argument)
* )
*)
| ArgumentsFitOnOneLine
(* Since compiler version 8.3, the bs. prefix is no longer needed *)
(* Synced from
https://github.com/rescript-lang/rescript-compiler/blob/29174de1a5fde3b16cf05d10f5ac109cfac5c4ca/jscomp/frontend/ast_external_process.ml#L291-L367 *)
let convertBsExternalAttribute = function
| "bs.as" -> "as"
| "bs.deriving" -> "deriving"
| "bs.get" -> "get"
| "bs.get_index" -> "get_index"
| "bs.ignore" -> "ignore"
| "bs.inline" -> "inline"
| "bs.int" -> "int"
| "bs.meth" -> "meth"
| "bs.module" -> "module"
| "bs.new" -> "new"
| "bs.obj" -> "obj"
| "bs.optional" -> "optional"
| "bs.return" -> "return"
| "bs.send" -> "send"
| "bs.scope" -> "scope"
| "bs.set" -> "set"
| "bs.set_index" -> "set_index"
| "bs.splice" | "bs.variadic" -> "variadic"
| "bs.string" -> "string"
| "bs.this" -> "this"
| "bs.uncurry" -> "uncurry"
| "bs.unwrap" -> "unwrap"
| "bs.val" -> "val"
(* bs.send.pipe shouldn't be transformed *)
| txt -> txt
(* These haven't been needed for a long time now *)
(* Synced from
https://github.com/rescript-lang/rescript-compiler/blob/29174de1a5fde3b16cf05d10f5ac109cfac5c4ca/jscomp/frontend/ast_exp_extension.ml *)
let convertBsExtension = function
| "bs.debugger" -> "debugger"
| "bs.external" -> "raw"
(* We should never see this one since we use the sugared object form, but still *)
| "bs.obj" -> "obj"
| "bs.raw" -> "raw"
| "bs.re" -> "re"
(* TODO: what about bs.time and bs.node? *)
| txt -> txt
let addParens doc =
Doc.group
(Doc.concat
[
Doc.lparen;
Doc.indent (Doc.concat [Doc.softLine; doc]);
Doc.softLine;
Doc.rparen;
])
let addBraces doc =
Doc.group
(Doc.concat
[
Doc.lbrace;
Doc.indent (Doc.concat [Doc.softLine; doc]);
Doc.softLine;
Doc.rbrace;
])
let addAsync doc = Doc.concat [Doc.text "async "; doc]
let getFirstLeadingComment tbl loc =
match Hashtbl.find tbl.CommentTable.leading loc with
| comment :: _ -> Some comment
| [] -> None
| exception Not_found -> None
(* Checks if `loc` has a leading line comment, i.e. `// comment above`*)
let hasLeadingLineComment tbl loc =
match getFirstLeadingComment tbl loc with
| Some comment -> Comment.isSingleLineComment comment
| None -> false
let hasCommentBelow tbl loc =
match Hashtbl.find tbl.CommentTable.trailing loc with
| comment :: _ ->
let commentLoc = Comment.loc comment in
commentLoc.Location.loc_start.pos_lnum > loc.Location.loc_end.pos_lnum
| [] -> false
| exception Not_found -> false
let hasNestedJsxOrMoreThanOneChild expr =
let rec loop inRecursion expr =
match expr.Parsetree.pexp_desc with
| Pexp_construct
({txt = Longident.Lident "::"}, Some {pexp_desc = Pexp_tuple [hd; tail]})
->
if inRecursion || ParsetreeViewer.isJsxExpression hd then true
else loop true tail
| _ -> false
in
loop false expr
let hasCommentsInside tbl loc =
match Hashtbl.find_opt tbl.CommentTable.inside loc with
| None -> false
| _ -> true
let hasTrailingComments tbl loc =
match Hashtbl.find_opt tbl.CommentTable.trailing loc with
| None -> false
| _ -> true
let printMultilineCommentContent txt =
(* Turns
* |* first line
* * second line
* * third line *|
* Into
* |* first line
* * second line
* * third line *|
*
* What makes a comment suitable for this kind of indentation?
* -> multiple lines + every line starts with a star
*)
let rec indentStars lines acc =
match lines with
| [] -> Doc.nil
| [lastLine] ->
let line = String.trim lastLine in
let doc = Doc.text (" " ^ line) in
let trailingSpace = if line = "" then Doc.nil else Doc.space in
List.rev (trailingSpace :: doc :: acc) |> Doc.concat
| line :: lines ->
let line = String.trim line in
if line != "" && String.unsafe_get line 0 == '*' then
let doc = Doc.text (" " ^ line) in
indentStars lines (Doc.hardLine :: doc :: acc)
else
let trailingSpace =
let len = String.length txt in
if len > 0 && String.unsafe_get txt (len - 1) = ' ' then Doc.space
else Doc.nil
in
let content = Comment.trimSpaces txt in
Doc.concat [Doc.text content; trailingSpace]
in
let lines = String.split_on_char '\n' txt in
match lines with
| [] -> Doc.text "/* */"
| [line] ->
Doc.concat
[Doc.text "/* "; Doc.text (Comment.trimSpaces line); Doc.text " */"]
| first :: rest ->
let firstLine = Comment.trimSpaces first in
Doc.concat
[
Doc.text "/*";
(match firstLine with
| "" | "*" -> Doc.nil
| _ -> Doc.space);
indentStars rest [Doc.hardLine; Doc.text firstLine];
Doc.text "*/";
]
let printTrailingComment (prevLoc : Location.t) (nodeLoc : Location.t) comment =
let singleLine = Comment.isSingleLineComment comment in
let content =
let txt = Comment.txt comment in
if singleLine then Doc.text ("//" ^ txt)
else printMultilineCommentContent txt
in
let diff =
let cmtStart = (Comment.loc comment).loc_start in
cmtStart.pos_lnum - prevLoc.loc_end.pos_lnum
in
let isBelow =
(Comment.loc comment).loc_start.pos_lnum > nodeLoc.loc_end.pos_lnum
in
if diff > 0 || isBelow then
Doc.concat
[
Doc.breakParent;
Doc.lineSuffix
(Doc.concat
[
Doc.hardLine;
(if diff > 1 then Doc.hardLine else Doc.nil);
content;
]);
]
else if not singleLine then Doc.concat [Doc.space; content]
else Doc.lineSuffix (Doc.concat [Doc.space; content])
let printLeadingComment ?nextComment comment =
let singleLine = Comment.isSingleLineComment comment in
let content =
let txt = Comment.txt comment in
if singleLine then Doc.text ("//" ^ txt)
else printMultilineCommentContent txt
in
let separator =
Doc.concat
[
(if singleLine then Doc.concat [Doc.hardLine; Doc.breakParent]
else Doc.nil);
(match nextComment with
| Some next ->
let nextLoc = Comment.loc next in
let currLoc = Comment.loc comment in
let diff =
nextLoc.Location.loc_start.pos_lnum
- currLoc.Location.loc_end.pos_lnum
in
let nextSingleLine = Comment.isSingleLineComment next in
if singleLine && nextSingleLine then
if diff > 1 then Doc.hardLine else Doc.nil
else if singleLine && not nextSingleLine then
if diff > 1 then Doc.hardLine else Doc.nil
else if diff > 1 then Doc.concat [Doc.hardLine; Doc.hardLine]
else if diff == 1 then Doc.hardLine
else Doc.space
| None -> Doc.nil);
]
in
Doc.concat [content; separator]
(* This function is used for printing comments inside an empty block *)
let printCommentsInside cmtTbl loc =
let printComment comment =
let singleLine = Comment.isSingleLineComment comment in
let txt = Comment.txt comment in
if singleLine then Doc.text ("//" ^ txt)
else printMultilineCommentContent txt
in
let forceBreak =
loc.Location.loc_start.pos_lnum <> loc.Location.loc_end.pos_lnum
in
let rec loop acc comments =
match comments with
| [] -> Doc.nil
| [comment] ->
let cmtDoc = printComment comment in
let cmtsDoc = Doc.concat (Doc.softLine :: List.rev (cmtDoc :: acc)) in
let doc =
Doc.breakableGroup ~forceBreak
(Doc.concat [Doc.ifBreaks (Doc.indent cmtsDoc) cmtsDoc; Doc.softLine])
in
doc
| comment :: rest ->
let cmtDoc = Doc.concat [printComment comment; Doc.line] in
loop (cmtDoc :: acc) rest
in
match Hashtbl.find cmtTbl.CommentTable.inside loc with
| exception Not_found -> Doc.nil
| comments ->
Hashtbl.remove cmtTbl.inside loc;
loop [] comments
(* This function is used for printing comments inside an empty file *)
let printCommentsInsideFile cmtTbl =
let rec loop acc comments =
match comments with
| [] -> Doc.nil
| [comment] ->
let cmtDoc = printLeadingComment comment in
let doc =
Doc.group (Doc.concat [Doc.concat (List.rev (cmtDoc :: acc))])
in
doc
| comment :: (nextComment :: _comments as rest) ->
let cmtDoc = printLeadingComment ~nextComment comment in
loop (cmtDoc :: acc) rest
in
match Hashtbl.find cmtTbl.CommentTable.inside Location.none with
| exception Not_found -> Doc.nil
| comments ->
Hashtbl.remove cmtTbl.inside Location.none;
Doc.group (loop [] comments)
let printLeadingComments node tbl loc =
let rec loop acc comments =
match comments with
| [] -> node
| [comment] ->
let cmtDoc = printLeadingComment comment in
let diff =
loc.Location.loc_start.pos_lnum
- (Comment.loc comment).Location.loc_end.pos_lnum
in
let separator =
if Comment.isSingleLineComment comment then
if diff > 1 then Doc.hardLine else Doc.nil
else if diff == 0 then Doc.space
else if diff > 1 then Doc.concat [Doc.hardLine; Doc.hardLine]
else Doc.hardLine
in
let doc =
Doc.group
(Doc.concat [Doc.concat (List.rev (cmtDoc :: acc)); separator; node])
in
doc
| comment :: (nextComment :: _comments as rest) ->
let cmtDoc = printLeadingComment ~nextComment comment in
loop (cmtDoc :: acc) rest
in
match Hashtbl.find tbl loc with
| exception Not_found -> node
| comments ->
(* Remove comments from tbl: Some ast nodes have the same location.
* We only want to print comments once *)
Hashtbl.remove tbl loc;
loop [] comments
let printTrailingComments node tbl loc =
let rec loop prev acc comments =
match comments with
| [] -> Doc.concat (List.rev acc)
| comment :: comments ->
let cmtDoc = printTrailingComment prev loc comment in
loop (Comment.loc comment) (cmtDoc :: acc) comments
in
match Hashtbl.find tbl loc with
| exception Not_found -> node
| [] -> node
| _first :: _ as comments ->
(* Remove comments from tbl: Some ast nodes have the same location.
* We only want to print comments once *)
Hashtbl.remove tbl loc;
let cmtsDoc = loop loc [] comments in
Doc.concat [node; cmtsDoc]
let printComments doc (tbl : CommentTable.t) loc =
let docWithLeadingComments = printLeadingComments doc tbl.leading loc in
printTrailingComments docWithLeadingComments tbl.trailing loc
let printList ~getLoc ~nodes ~print ?(forceBreak = false) t =
let rec loop (prevLoc : Location.t) acc nodes =
match nodes with
| [] -> (prevLoc, Doc.concat (List.rev acc))
| node :: nodes ->
let loc = getLoc node in
let startPos =
match getFirstLeadingComment t loc with
| None -> loc.loc_start
| Some comment -> (Comment.loc comment).loc_start
in
let sep =
if startPos.pos_lnum - prevLoc.loc_end.pos_lnum > 1 then
Doc.concat [Doc.hardLine; Doc.hardLine]
else Doc.hardLine
in
let doc = printComments (print node t) t loc in
loop loc (doc :: sep :: acc) nodes
in
match nodes with
| [] -> Doc.nil
| node :: nodes ->
let firstLoc = getLoc node in
let doc = printComments (print node t) t firstLoc in
let lastLoc, docs = loop firstLoc [doc] nodes in
let forceBreak =
forceBreak || firstLoc.loc_start.pos_lnum != lastLoc.loc_end.pos_lnum
in
Doc.breakableGroup ~forceBreak docs
let printListi ~getLoc ~nodes ~print ?(forceBreak = false) t =
let rec loop i (prevLoc : Location.t) acc nodes =
match nodes with
| [] -> (prevLoc, Doc.concat (List.rev acc))
| node :: nodes ->
let loc = getLoc node in
let startPos =
match getFirstLeadingComment t loc with
| None -> loc.loc_start
| Some comment -> (Comment.loc comment).loc_start
in
let sep =
if startPos.pos_lnum - prevLoc.loc_end.pos_lnum > 1 then
Doc.concat [Doc.hardLine; Doc.hardLine]
else Doc.line
in
let doc = printComments (print node t i) t loc in
loop (i + 1) loc (doc :: sep :: acc) nodes
in
match nodes with
| [] -> Doc.nil
| node :: nodes ->
let firstLoc = getLoc node in
let doc = printComments (print node t 0) t firstLoc in
let lastLoc, docs = loop 1 firstLoc [doc] nodes in
let forceBreak =
forceBreak || firstLoc.loc_start.pos_lnum != lastLoc.loc_end.pos_lnum
in
Doc.breakableGroup ~forceBreak docs
let rec printLongidentAux accu = function
| Longident.Lident s -> Doc.text s :: accu
| Ldot (lid, s) -> printLongidentAux (Doc.text s :: accu) lid
| Lapply (lid1, lid2) ->
let d1 = Doc.join ~sep:Doc.dot (printLongidentAux [] lid1) in
let d2 = Doc.join ~sep:Doc.dot (printLongidentAux [] lid2) in
Doc.concat [d1; Doc.lparen; d2; Doc.rparen] :: accu
let printLongident = function
| Longident.Lident txt -> Doc.text txt
| lid -> Doc.join ~sep:Doc.dot (printLongidentAux [] lid)
type identifierStyle = ExoticIdent | NormalIdent
let classifyIdentContent ?(allowUident = false) txt =
if Token.isKeywordTxt txt then ExoticIdent
else
let len = String.length txt in
let rec loop i =
if i == len then NormalIdent
else if i == 0 then
match String.unsafe_get txt i with
| 'A' .. 'Z' when allowUident -> loop (i + 1)
| 'a' .. 'z' | '_' -> loop (i + 1)
| _ -> ExoticIdent
else
match String.unsafe_get txt i with
| 'A' .. 'Z' | 'a' .. 'z' | '0' .. '9' | '\'' | '_' -> loop (i + 1)
| _ -> ExoticIdent
in
loop 0
let printIdentLike ?allowUident txt =
match classifyIdentContent ?allowUident txt with
| ExoticIdent -> Doc.concat [Doc.text "\\\""; Doc.text txt; Doc.text "\""]
| NormalIdent -> Doc.text txt
let rec unsafe_for_all_range s ~start ~finish p =
start > finish
|| p (String.unsafe_get s start)
&& unsafe_for_all_range s ~start:(start + 1) ~finish p
let for_all_from s start p =
let len = String.length s in
unsafe_for_all_range s ~start ~finish:(len - 1) p
(* See https://github.com/rescript-lang/rescript-compiler/blob/726cfa534314b586e5b5734471bc2023ad99ebd9/jscomp/ext/ext_string.ml#L510 *)
let isValidNumericPolyvarNumber (x : string) =
let len = String.length x in
len > 0
&&
let a = Char.code (String.unsafe_get x 0) in
a <= 57
&&
if len > 1 then
a > 48
&& for_all_from x 1 (function
| '0' .. '9' -> true
| _ -> false)
else a >= 48
(* Exotic identifiers in poly-vars have a "lighter" syntax: #"ease-in" *)
let printPolyVarIdent txt =
(* numeric poly-vars don't need quotes: #644 *)
if isValidNumericPolyvarNumber txt then Doc.text txt
else
match classifyIdentContent ~allowUident:true txt with
| ExoticIdent -> Doc.concat [Doc.text "\""; Doc.text txt; Doc.text "\""]
| NormalIdent -> (
match txt with
| "" -> Doc.concat [Doc.text "\""; Doc.text txt; Doc.text "\""]
| _ -> Doc.text txt)
let printLident l =
let flatLidOpt lid =
let rec flat accu = function
| Longident.Lident s -> Some (s :: accu)
| Ldot (lid, s) -> flat (s :: accu) lid
| Lapply (_, _) -> None
in
flat [] lid
in
match l with
| Longident.Lident txt -> printIdentLike txt
| Longident.Ldot (path, txt) ->
let doc =
match flatLidOpt path with
| Some txts ->
Doc.concat
[
Doc.join ~sep:Doc.dot (List.map Doc.text txts);
Doc.dot;
printIdentLike txt;
]
| None -> Doc.text "printLident: Longident.Lapply is not supported"
in
doc
| Lapply (_, _) -> Doc.text "printLident: Longident.Lapply is not supported"
let printLongidentLocation l cmtTbl =
let doc = printLongident l.Location.txt in
printComments doc cmtTbl l.loc
(* Module.SubModule.x *)
let printLidentPath path cmtTbl =
let doc = printLident path.Location.txt in
printComments doc cmtTbl path.loc
(* Module.SubModule.x or Module.SubModule.X *)
let printIdentPath path cmtTbl =
let doc = printLident path.Location.txt in
printComments doc cmtTbl path.loc
let printStringLoc sloc cmtTbl =
let doc = printIdentLike sloc.Location.txt in
printComments doc cmtTbl sloc.loc
let printStringContents txt =
let lines = String.split_on_char '\n' txt in
Doc.join ~sep:Doc.literalLine (List.map Doc.text lines)
let printConstant ?(templateLiteral = false) c =
match c with
| Parsetree.Pconst_integer (s, suffix) -> (
match suffix with
| Some c -> Doc.text (s ^ Char.escaped c)
| None -> Doc.text s)
| Pconst_string (txt, None) ->
Doc.concat [Doc.text "\""; printStringContents txt; Doc.text "\""]
| Pconst_string (txt, Some prefix) ->
if prefix = "INTERNAL_RES_CHAR_CONTENTS" then
Doc.concat [Doc.text "'"; Doc.text txt; Doc.text "'"]
else
let lquote, rquote =
if templateLiteral then ("`", "`") else ("\"", "\"")
in
Doc.concat
[
(if prefix = "js" then Doc.nil else Doc.text prefix);
Doc.text lquote;
printStringContents txt;
Doc.text rquote;
]
| Pconst_float (s, _) -> Doc.text s
| Pconst_char c ->
let str =
match Char.unsafe_chr c with
| '\'' -> "\\'"
| '\\' -> "\\\\"
| '\n' -> "\\n"
| '\t' -> "\\t"
| '\r' -> "\\r"
| '\b' -> "\\b"
| ' ' .. '~' as c ->
let s = (Bytes.create [@doesNotRaise]) 1 in
Bytes.unsafe_set s 0 c;
Bytes.unsafe_to_string s
| _ -> Res_utf8.encodeCodePoint c
in
Doc.text ("'" ^ str ^ "'")
let printOptionalLabel attrs =
if Res_parsetree_viewer.hasOptionalAttribute attrs then Doc.text "?"
else Doc.nil
let customLayoutThreshold = 2
let rec printStructure ~customLayout (s : Parsetree.structure) t =
match s with
| [] -> printCommentsInsideFile t
| structure ->
printList
~getLoc:(fun s -> s.Parsetree.pstr_loc)
~nodes:structure
~print:(printStructureItem ~customLayout)
t
and printStructureItem ~customLayout (si : Parsetree.structure_item) cmtTbl =
match si.pstr_desc with
| Pstr_value (rec_flag, valueBindings) ->
let recFlag =
match rec_flag with
| Asttypes.Nonrecursive -> Doc.nil
| Asttypes.Recursive -> Doc.text "rec "
in
printValueBindings ~customLayout ~recFlag valueBindings cmtTbl
| Pstr_type (recFlag, typeDeclarations) ->
let recFlag =
match recFlag with
| Asttypes.Nonrecursive -> Doc.nil
| Asttypes.Recursive -> Doc.text "rec "
in
printTypeDeclarations ~customLayout ~recFlag typeDeclarations cmtTbl
| Pstr_primitive valueDescription ->
printValueDescription ~customLayout valueDescription cmtTbl
| Pstr_eval (expr, attrs) ->
let exprDoc =
let doc = printExpressionWithComments ~customLayout expr cmtTbl in
match Parens.structureExpr expr with
| Parens.Parenthesized -> addParens doc
| Braced braces -> printBraces doc expr braces
| Nothing -> doc
in
Doc.concat [printAttributes ~customLayout attrs cmtTbl; exprDoc]
| Pstr_attribute attr ->
fst (printAttribute ~customLayout ~standalone:true attr cmtTbl)
| Pstr_extension (extension, attrs) ->
Doc.concat
[
printAttributes ~customLayout attrs cmtTbl;
Doc.concat
[printExtension ~customLayout ~atModuleLvl:true extension cmtTbl];
]
| Pstr_include includeDeclaration ->
printIncludeDeclaration ~customLayout includeDeclaration cmtTbl
| Pstr_open openDescription ->
printOpenDescription ~customLayout openDescription cmtTbl
| Pstr_modtype modTypeDecl ->
printModuleTypeDeclaration ~customLayout modTypeDecl cmtTbl
| Pstr_module moduleBinding ->
printModuleBinding ~customLayout ~isRec:false moduleBinding cmtTbl 0
| Pstr_recmodule moduleBindings ->
printListi
~getLoc:(fun mb -> mb.Parsetree.pmb_loc)
~nodes:moduleBindings
~print:(printModuleBinding ~customLayout ~isRec:true)
cmtTbl
| Pstr_exception extensionConstructor ->
printExceptionDef ~customLayout extensionConstructor cmtTbl
| Pstr_typext typeExtension ->
printTypeExtension ~customLayout typeExtension cmtTbl
| Pstr_class _ | Pstr_class_type _ -> Doc.nil
and printTypeExtension ~customLayout (te : Parsetree.type_extension) cmtTbl =
let prefix = Doc.text "type " in
let name = printLidentPath te.ptyext_path cmtTbl in
let typeParams = printTypeParams ~customLayout te.ptyext_params cmtTbl in
let extensionConstructors =
let ecs = te.ptyext_constructors in
let forceBreak =
match (ecs, List.rev ecs) with
| first :: _, last :: _ ->
first.pext_loc.loc_start.pos_lnum > te.ptyext_path.loc.loc_end.pos_lnum
|| first.pext_loc.loc_start.pos_lnum < last.pext_loc.loc_end.pos_lnum
| _ -> false
in
let privateFlag =
match te.ptyext_private with
| Asttypes.Private -> Doc.concat [Doc.text "private"; Doc.line]
| Public -> Doc.nil
in
let rows =
printListi
~getLoc:(fun n -> n.Parsetree.pext_loc)
~print:(printExtensionConstructor ~customLayout)
~nodes:ecs ~forceBreak cmtTbl
in
Doc.breakableGroup ~forceBreak
(Doc.indent
(Doc.concat
[
Doc.line;
privateFlag;
rows;
(* Doc.join ~sep:Doc.line ( *)
(* List.mapi printExtensionConstructor ecs *)
(* ) *)
]))
in
Doc.group
(Doc.concat
[
printAttributes ~customLayout ~loc:te.ptyext_path.loc
te.ptyext_attributes cmtTbl;
prefix;
name;
typeParams;
Doc.text " +=";
extensionConstructors;
])
and printModuleBinding ~customLayout ~isRec moduleBinding cmtTbl i =
let prefix =
if i = 0 then
Doc.concat
[Doc.text "module "; (if isRec then Doc.text "rec " else Doc.nil)]
else Doc.text "and "
in
let modExprDoc, modConstraintDoc =
match moduleBinding.pmb_expr with
| {pmod_desc = Pmod_constraint (modExpr, modType)} ->
( printModExpr ~customLayout modExpr cmtTbl,
Doc.concat [Doc.text ": "; printModType ~customLayout modType cmtTbl] )
| modExpr -> (printModExpr ~customLayout modExpr cmtTbl, Doc.nil)
in
let modName =
let doc = Doc.text moduleBinding.pmb_name.Location.txt in
printComments doc cmtTbl moduleBinding.pmb_name.loc
in
let doc =
Doc.concat
[
printAttributes ~customLayout ~loc:moduleBinding.pmb_name.loc
moduleBinding.pmb_attributes cmtTbl;
prefix;
modName;
modConstraintDoc;
Doc.text " = ";
modExprDoc;
]
in
printComments doc cmtTbl moduleBinding.pmb_loc
and printModuleTypeDeclaration ~customLayout
(modTypeDecl : Parsetree.module_type_declaration) cmtTbl =
let modName =
let doc = Doc.text modTypeDecl.pmtd_name.txt in
printComments doc cmtTbl modTypeDecl.pmtd_name.loc
in
Doc.concat
[
printAttributes ~customLayout modTypeDecl.pmtd_attributes cmtTbl;
Doc.text "module type ";
modName;
(match modTypeDecl.pmtd_type with
| None -> Doc.nil
| Some modType ->
Doc.concat [Doc.text " = "; printModType ~customLayout modType cmtTbl]);
]
and printModType ~customLayout modType cmtTbl =
let modTypeDoc =
match modType.pmty_desc with
| Parsetree.Pmty_ident longident ->
Doc.concat
[
printAttributes ~customLayout ~loc:longident.loc
modType.pmty_attributes cmtTbl;
printLongidentLocation longident cmtTbl;
]
| Pmty_signature [] ->
if hasCommentsInside cmtTbl modType.pmty_loc then
let doc = printCommentsInside cmtTbl modType.pmty_loc in
Doc.concat [Doc.lbrace; doc; Doc.rbrace]
else
let shouldBreak =
modType.pmty_loc.loc_start.pos_lnum
< modType.pmty_loc.loc_end.pos_lnum
in
Doc.breakableGroup ~forceBreak:shouldBreak
(Doc.concat [Doc.lbrace; Doc.softLine; Doc.softLine; Doc.rbrace])
| Pmty_signature signature ->
let signatureDoc =
Doc.breakableGroup ~forceBreak:true
(Doc.concat
[
Doc.lbrace;
Doc.indent
(Doc.concat
[Doc.line; printSignature ~customLayout signature cmtTbl]);
Doc.line;
Doc.rbrace;
])
in
Doc.concat
[
printAttributes ~customLayout modType.pmty_attributes cmtTbl;
signatureDoc;
]
| Pmty_functor _ ->
let parameters, returnType = ParsetreeViewer.functorType modType in
let parametersDoc =
match parameters with
| [] -> Doc.nil
| [(attrs, {Location.txt = "_"; loc}, Some modType)] ->
let cmtLoc =
{loc with loc_end = modType.Parsetree.pmty_loc.loc_end}
in
let attrs = printAttributes ~customLayout attrs cmtTbl in
let doc =
Doc.concat [attrs; printModType ~customLayout modType cmtTbl]
in
printComments doc cmtTbl cmtLoc
| params ->
Doc.group
(Doc.concat
[
Doc.lparen;
Doc.indent
(Doc.concat
[
Doc.softLine;
Doc.join
~sep:(Doc.concat [Doc.comma; Doc.line])
(List.map
(fun (attrs, lbl, modType) ->
let cmtLoc =
match modType with
| None -> lbl.Asttypes.loc
| Some modType ->
{
lbl.Asttypes.loc with
loc_end =
modType.Parsetree.pmty_loc.loc_end;
}
in
let attrs =
printAttributes ~customLayout attrs cmtTbl
in
let lblDoc =
if lbl.Location.txt = "_" || lbl.txt = "*" then
Doc.nil
else
let doc = Doc.text lbl.txt in
printComments doc cmtTbl lbl.loc
in
let doc =
Doc.concat
[
attrs;
lblDoc;
(match modType with
| None -> Doc.nil
| Some modType ->
Doc.concat
[
(if lbl.txt = "_" then Doc.nil
else Doc.text ": ");
printModType ~customLayout modType
cmtTbl;
]);
]
in
printComments doc cmtTbl cmtLoc)
params);
]);
Doc.trailingComma;
Doc.softLine;
Doc.rparen;
])
in
let returnDoc =
let doc = printModType ~customLayout returnType cmtTbl in
if Parens.modTypeFunctorReturn returnType then addParens doc else doc
in
Doc.group
(Doc.concat
[
parametersDoc;
Doc.group (Doc.concat [Doc.text " =>"; Doc.line; returnDoc]);
])
| Pmty_typeof modExpr ->
Doc.concat
[Doc.text "module type of "; printModExpr ~customLayout modExpr cmtTbl]
| Pmty_extension extension ->
printExtension ~customLayout ~atModuleLvl:false extension cmtTbl
| Pmty_alias longident ->
Doc.concat [Doc.text "module "; printLongidentLocation longident cmtTbl]
| Pmty_with (modType, withConstraints) ->
let operand =
let doc = printModType ~customLayout modType cmtTbl in
if Parens.modTypeWithOperand modType then addParens doc else doc
in
Doc.group
(Doc.concat
[
operand;
Doc.indent
(Doc.concat
[
Doc.line;
printWithConstraints ~customLayout withConstraints cmtTbl;
]);
])
in
let attrsAlreadyPrinted =
match modType.pmty_desc with
| Pmty_functor _ | Pmty_signature _ | Pmty_ident _ -> true
| _ -> false
in
let doc =
Doc.concat
[
(if attrsAlreadyPrinted then Doc.nil
else printAttributes ~customLayout modType.pmty_attributes cmtTbl);
modTypeDoc;
]
in
printComments doc cmtTbl modType.pmty_loc
and printWithConstraints ~customLayout withConstraints cmtTbl =
let rows =
List.mapi
(fun i withConstraint ->
Doc.group
(Doc.concat
[
(if i == 0 then Doc.text "with " else Doc.text "and ");
printWithConstraint ~customLayout withConstraint cmtTbl;
]))
withConstraints
in
Doc.join ~sep:Doc.line rows
and printWithConstraint ~customLayout
(withConstraint : Parsetree.with_constraint) cmtTbl =
match withConstraint with
(* with type X.t = ... *)
| Pwith_type (longident, typeDeclaration) ->
Doc.group
(printTypeDeclaration ~customLayout
~name:(printLidentPath longident cmtTbl)
~equalSign:"=" ~recFlag:Doc.nil 0 typeDeclaration CommentTable.empty)
(* with module X.Y = Z *)
| Pwith_module ({txt = longident1}, {txt = longident2}) ->
Doc.concat
[
Doc.text "module ";
printLongident longident1;
Doc.text " =";
Doc.indent (Doc.concat [Doc.line; printLongident longident2]);
]
(* with type X.t := ..., same format as [Pwith_type] *)
| Pwith_typesubst (longident, typeDeclaration) ->
Doc.group
(printTypeDeclaration ~customLayout
~name:(printLidentPath longident cmtTbl)
~equalSign:":=" ~recFlag:Doc.nil 0 typeDeclaration CommentTable.empty)
| Pwith_modsubst ({txt = longident1}, {txt = longident2}) ->
Doc.concat
[
Doc.text "module ";
printLongident longident1;
Doc.text " :=";
Doc.indent (Doc.concat [Doc.line; printLongident longident2]);
]
and printSignature ~customLayout signature cmtTbl =
match signature with
| [] -> printCommentsInsideFile cmtTbl
| signature ->
printList
~getLoc:(fun s -> s.Parsetree.psig_loc)
~nodes:signature
~print:(printSignatureItem ~customLayout)
cmtTbl
and printSignatureItem ~customLayout (si : Parsetree.signature_item) cmtTbl =
match si.psig_desc with
| Parsetree.Psig_value valueDescription ->
printValueDescription ~customLayout valueDescription cmtTbl
| Psig_type (recFlag, typeDeclarations) ->
let recFlag =
match recFlag with
| Asttypes.Nonrecursive -> Doc.nil
| Asttypes.Recursive -> Doc.text "rec "
in
printTypeDeclarations ~customLayout ~recFlag typeDeclarations cmtTbl
| Psig_typext typeExtension ->
printTypeExtension ~customLayout typeExtension cmtTbl
| Psig_exception extensionConstructor ->
printExceptionDef ~customLayout extensionConstructor cmtTbl
| Psig_module moduleDeclaration ->
printModuleDeclaration ~customLayout moduleDeclaration cmtTbl
| Psig_recmodule moduleDeclarations ->
printRecModuleDeclarations ~customLayout moduleDeclarations cmtTbl
| Psig_modtype modTypeDecl ->
printModuleTypeDeclaration ~customLayout modTypeDecl cmtTbl
| Psig_open openDescription ->
printOpenDescription ~customLayout openDescription cmtTbl
| Psig_include includeDescription ->
printIncludeDescription ~customLayout includeDescription cmtTbl
| Psig_attribute attr ->
fst (printAttribute ~customLayout ~standalone:true attr cmtTbl)
| Psig_extension (extension, attrs) ->
Doc.concat
[
printAttributes ~customLayout attrs cmtTbl;
Doc.concat
[printExtension ~customLayout ~atModuleLvl:true extension cmtTbl];
]
| Psig_class _ | Psig_class_type _ -> Doc.nil
and printRecModuleDeclarations ~customLayout moduleDeclarations cmtTbl =
printListi
~getLoc:(fun n -> n.Parsetree.pmd_loc)
~nodes:moduleDeclarations
~print:(printRecModuleDeclaration ~customLayout)
cmtTbl
and printRecModuleDeclaration ~customLayout md cmtTbl i =