forked from rescript-lang/rescript
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPrinterOcaml.ml
3228 lines (3125 loc) · 94.4 KB
/
PrinterOcaml.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 Printer = struct
type printer = {
src: bytes;
comments: CommentAst.t;
}
(* TODO: should this go inside a ast utility module? *)
let rec collectPatternsFromListConstruct acc pattern =
let open Parsetree in
match pattern.ppat_desc with
| Ppat_construct(
{txt = Longident.Lident "::"},
Some {ppat_desc=Ppat_tuple (pat::rest::[])}
) ->
collectPatternsFromListConstruct (pat::acc) rest
| _ -> List.rev acc, pattern
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;
Doc.rbrace;
]
)
(* This could be done in one pass by collecting locations as we go? *)
let interleaveWhitespace ?(forceBreak=false) (rows: (Location.t * Doc.t) list) =
let rec loop prevLoc acc rows =
match rows with
| [] -> Doc.concat (List.rev acc)
| (loc, doc)::rest ->
if loc.Location.loc_start.pos_lnum - prevLoc.Location.loc_end.pos_lnum > 1 then
loop loc (doc::Doc.line::Doc.line::acc) rest
else
loop loc (doc::Doc.line::acc) rest
in
match rows with
| [] -> Doc.nil
| (firstLoc, firstDoc)::rest ->
(* TODO: perf, reversing the list twice! *)
let forceBreak = forceBreak || (match List.rev rest with
| (lastLoc, _)::_ ->
firstLoc.loc_start.pos_lnum != lastLoc.loc_end.pos_lnum
| _ -> false)
in
Doc.breakableGroup ~forceBreak (
loop firstLoc [firstDoc] rest
)
let printLongident l = match l with
| Longident.Lident lident -> Doc.text lident
| Longident.Ldot (lident, txt) as l ->
let txts = Longident.flatten l in
Doc.join ~sep:Doc.dot (List.map Doc.text txts)
| _ -> failwith "unsupported ident"
(* TODO: better allocation strategy for the buffer *)
let escapeStringContents s =
let len = String.length s in
let b = Buffer.create len in
for i = 0 to len - 1 do
let c = String.get s i in
if c = '\008' then (
Buffer.add_char b '\\';
Buffer.add_char b 'b';
) else if c = '\009' then (
Buffer.add_char b '\\';
Buffer.add_char b 't';
) else if c = '\010' then (
Buffer.add_char b '\\';
Buffer.add_char b 'n';
) else if c = '\013' then (
Buffer.add_char b '\\';
Buffer.add_char b 'r';
) else if c = '\034' then (
Buffer.add_char b '\\';
Buffer.add_char b '"';
) else if c = '\092' then (
Buffer.add_char b '\\';
Buffer.add_char b '\\';
)else (
Buffer.add_char b c;
);
done;
Buffer.contents b
let printConstant c = match c with
| Parsetree.Pconst_integer (s, _) -> Doc.text s
| Pconst_string (s, _) -> Doc.text ("\"" ^ (escapeStringContents s) ^ "\"")
| Pconst_float (s, _) -> Doc.text s
| Pconst_char c -> Doc.text ("'" ^ (Char.escaped c) ^ "'")
let rec printStructure (s : Parsetree.structure) =
interleaveWhitespace (
List.map (fun si -> (si.Parsetree.pstr_loc, printStructureItem si)) s
)
and printStructureItem (si: Parsetree.structure_item) =
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 ~recFlag valueBindings
| Pstr_type(recFlag, typeDeclarations) ->
let recFlag = match recFlag with
| Asttypes.Nonrecursive -> Doc.nil
| Asttypes.Recursive -> Doc.text "rec "
in
printTypeDeclarations ~recFlag typeDeclarations
| Pstr_primitive valueDescription ->
printValueDescription valueDescription
| Pstr_eval (expr, attrs) ->
let needsParens = match expr with
| {pexp_attributes=[({txt="ns.ternary"},_)]; pexp_desc = Pexp_ifthenelse _} -> false
| _ when ParsetreeViewer.hasAttributes expr.pexp_attributes -> true
| _ -> false
in
let exprDoc =
let doc = printExpression expr in
if needsParens then addParens doc else doc
in
Doc.concat [
printAttributes attrs;
exprDoc;
]
| Pstr_attribute attr -> Doc.concat [Doc.text "@"; printAttribute attr]
| Pstr_extension (extension, attrs) -> Doc.concat [
printAttributes attrs;
Doc.concat [Doc.text "%";printExtension extension];
]
| Pstr_include includeDeclaration ->
printIncludeDeclaration includeDeclaration
| Pstr_open openDescription ->
printOpenDescription openDescription
| Pstr_modtype modTypeDecl ->
printModuleTypeDeclaration modTypeDecl
| Pstr_module moduleBinding ->
printModuleBinding ~isRec:false 0 moduleBinding
| Pstr_recmodule moduleBindings ->
Doc.join ~sep:Doc.line (List.mapi (fun i mb ->
printModuleBinding ~isRec:true i mb
) moduleBindings)
| Pstr_exception extensionConstructor ->
printExceptionDef extensionConstructor;
| Pstr_typext typeExtension ->
printTypeExtension typeExtension
| Pstr_class _ | Pstr_class_type _ -> Doc.nil
and printTypeExtension (te : Parsetree.type_extension) =
let prefix = Doc.text "type " in
let name = printLongident te.ptyext_path.txt in
let typeParams = match te.ptyext_params with
| [] -> Doc.nil
| typeParams -> Doc.group (
Doc.concat [
Doc.lessThan;
Doc.indent (
Doc.concat [
Doc.softLine;
Doc.join ~sep:(Doc.concat [Doc.comma; Doc.line]) (
List.map printTypeParam typeParams
)
]
);
Doc.trailingComma;
Doc.softLine;
Doc.greaterThan;
]
)
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
Doc.breakableGroup ~forceBreak (
Doc.indent (
Doc.concat [
Doc.line;
privateFlag;
Doc.join ~sep:Doc.line (
List.mapi printExtensionConstructor ecs
)
]
)
)
in
Doc.group (
Doc.concat [
printAttributes ~loc: te.ptyext_path.loc te.ptyext_attributes;
prefix;
name;
typeParams;
Doc.text " +=";
extensionConstructors;
]
)
and printModuleBinding ~isRec i moduleBinding =
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 modExpr,
Doc.concat [
Doc.text ": ";
printModType modType
]
)
| modExpr ->
(printModExpr modExpr, Doc.nil)
in
Doc.concat [
printAttributes ~loc:moduleBinding.pmb_name.loc moduleBinding.pmb_attributes;
prefix;
Doc.text moduleBinding.pmb_name.Location.txt;
modConstraintDoc;
Doc.text " = ";
modExprDoc;
]
and printModuleTypeDeclaration (modTypeDecl : Parsetree.module_type_declaration) =
Doc.concat [
printAttributes modTypeDecl.pmtd_attributes;
Doc.text "module type ";
Doc.text modTypeDecl.pmtd_name.txt;
(match modTypeDecl.pmtd_type with
| None -> Doc.nil
| Some modType -> Doc.concat [
Doc.text " = ";
printModType modType;
]);
]
and printModType modType =
let modTypeDoc = match modType.pmty_desc with
| Parsetree.Pmty_ident {txt = longident; loc} ->
Doc.concat [
printAttributes ~loc modType.pmty_attributes;
printLongident longident
]
| Pmty_signature signature ->
let signatureDoc = Doc.breakableGroup ~forceBreak:true (
Doc.concat [
Doc.lbrace;
Doc.indent (
Doc.concat [
Doc.line;
printSignature signature;
]
);
Doc.line;
Doc.rbrace;
]
) in
Doc.concat [
printAttributes modType.pmty_attributes;
signatureDoc
]
| Pmty_functor _ ->
let (parameters, returnType) = ParsetreeViewer.functorType modType in
let parametersDoc = match parameters with
| [] -> Doc.nil
| [attrs, {Location.txt = "_"}, Some modType] ->
let attrs = match attrs with
| [] -> Doc.nil
| attrs -> Doc.concat [
Doc.join ~sep:Doc.line (List.map printAttribute attrs);
Doc.line;
] in
Doc.concat [
attrs;
printModType modType
]
| 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 attrs = match attrs with
| [] -> Doc.nil
| attrs -> Doc.concat [
Doc.join ~sep:Doc.line (List.map printAttribute attrs);
Doc.line;
] in
Doc.concat [
attrs;
if lbl.Location.txt = "_" then Doc.nil else Doc.text lbl.txt;
(match modType with
| None -> Doc.nil
| Some modType -> Doc.concat [
if lbl.txt = "_" then Doc.nil else Doc.text ": ";
printModType modType;
]);
]
) params
);
]
);
Doc.trailingComma;
Doc.softLine;
Doc.rparen;
]
)
in
let returnDoc =
let doc = printModType returnType 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 modExpr;
]
| Pmty_extension extension -> printExtension extension
| Pmty_alias {txt = longident} -> Doc.concat [
Doc.text "module ";
printLongident longident;
]
| Pmty_with (modType, withConstraints) ->
let operand =
let doc = printModType modType in
if Parens.modTypeWithOperand modType then addParens doc else doc
in
Doc.group (
Doc.concat [
operand;
Doc.indent (
Doc.concat [
Doc.line;
printWithConstraints withConstraints;
]
)
]
)
in
let attrsAlreadyPrinted = match modType.pmty_desc with
| Pmty_functor _ | Pmty_signature _ | Pmty_ident _ -> true
| _ -> false in
Doc.concat [
if attrsAlreadyPrinted then Doc.nil else printAttributes modType.pmty_attributes;
modTypeDoc;
]
and printWithConstraints withConstraints =
let rows =List.mapi (fun i withConstraint ->
Doc.group (
Doc.concat [
if i == 0 then Doc.text "with " else Doc.text "and ";
printWithConstraint withConstraint;
]
)
) withConstraints
in
Doc.join ~sep:Doc.line rows
and printWithConstraint (withConstraint : Parsetree.with_constraint) =
match withConstraint with
(* with type X.t = ... *)
| Pwith_type ({txt = longident}, typeDeclaration) ->
Doc.group (printTypeDeclaration
~name:(printLongident longident)
~equalSign:"="
~recFlag:Doc.nil
0
typeDeclaration)
(* 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 ({txt = longident}, typeDeclaration) ->
Doc.group(printTypeDeclaration
~name:(printLongident longident)
~equalSign:":="
~recFlag:Doc.nil
0
typeDeclaration)
| 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 signature =
interleaveWhitespace (
List.map (fun si -> (si.Parsetree.psig_loc, printSignatureItem si)) signature
)
and printSignatureItem (si : Parsetree.signature_item) =
match si.psig_desc with
| Parsetree.Psig_value valueDescription ->
printValueDescription valueDescription
| Psig_type (recFlag, typeDeclarations) ->
let recFlag = match recFlag with
| Asttypes.Nonrecursive -> Doc.nil
| Asttypes.Recursive -> Doc.text "rec "
in
printTypeDeclarations ~recFlag typeDeclarations
| Psig_typext typeExtension ->
printTypeExtension typeExtension
| Psig_exception extensionConstructor ->
printExceptionDef extensionConstructor
| Psig_module moduleDeclaration ->
printModuleDeclaration moduleDeclaration
| Psig_recmodule moduleDeclarations ->
printRecModuleDeclarations moduleDeclarations
| Psig_modtype modTypeDecl ->
printModuleTypeDeclaration modTypeDecl
| Psig_open openDescription ->
printOpenDescription openDescription
| Psig_include includeDescription ->
printIncludeDescription includeDescription
| Psig_attribute attr -> Doc.concat [Doc.text "@"; printAttribute attr]
| Psig_extension (extension, attrs) -> Doc.concat [
printAttributes attrs;
Doc.concat [Doc.text "%";printExtension extension];
]
| Psig_class _ | Psig_class_type _ -> Doc.nil
and printRecModuleDeclarations moduleDeclarations =
Doc.group (
Doc.join ~sep:Doc.line (
List.mapi (fun i (md: Parsetree.module_declaration) ->
let body = match md.pmd_type.pmty_desc with
| Parsetree.Pmty_alias {txt = longident } ->
Doc.concat [Doc.text " = "; printLongident longident]
| _ ->
let needsParens = match md.pmd_type.pmty_desc with
| Pmty_with _ -> true
| _ -> false
in
let modTypeDoc =
let doc = printModType md.pmd_type in
if needsParens then addParens doc else doc
in
Doc.concat [Doc.text ": "; modTypeDoc]
in
let prefix = if i < 1 then "module rec " else "and " in
Doc.concat [
printAttributes ~loc:md.pmd_name.loc md.pmd_attributes;
Doc.text prefix;
Doc.text md.pmd_name.txt;
body
]
) moduleDeclarations
)
)
and printModuleDeclaration (md: Parsetree.module_declaration) =
let body = match md.pmd_type.pmty_desc with
| Parsetree.Pmty_alias {txt = longident } ->
Doc.concat [Doc.text " = "; printLongident longident]
| _ -> Doc.concat [Doc.text ": "; printModType md.pmd_type]
in
Doc.concat [
printAttributes ~loc:md.pmd_name.loc md.pmd_attributes;
Doc.text "module ";
Doc.text md.pmd_name.txt;
body
]
and printOpenDescription (openDescription : Parsetree.open_description) =
Doc.concat [
printAttributes openDescription.popen_attributes;
Doc.text "open";
(match openDescription.popen_override with
| Asttypes.Fresh -> Doc.space
| Asttypes.Override -> Doc.text "! ");
printLongident openDescription.popen_lid.txt
]
and printIncludeDescription (includeDescription: Parsetree.include_description) =
Doc.concat [
printAttributes includeDescription.pincl_attributes;
Doc.text "include ";
printModType includeDescription.pincl_mod;
]
and printIncludeDeclaration (includeDeclaration : Parsetree.include_declaration) =
Doc.concat [
printAttributes includeDeclaration.pincl_attributes;
Doc.text "include ";
printModExpr includeDeclaration.pincl_mod;
]
and printValueBindings ~recFlag (vbs: Parsetree.value_binding list) =
let rows = List.mapi (fun i vb ->
let doc = printValueBinding ~recFlag i vb in
(vb.Parsetree.pvb_loc, doc)
) vbs
in
interleaveWhitespace rows
(*
* type value_description = {
* pval_name : string Asttypes.loc;
* pval_type : Parsetree.core_type;
* pval_prim : string list;
* pval_attributes : Parsetree.attributes;
* pval_loc : Location.t;
* }
*)
and printValueDescription valueDescription =
let isExternal =
match valueDescription.pval_prim with | [] -> false | _ -> true
in
Doc.group (
Doc.concat [
Doc.text (if isExternal then "external " else "let ");
Doc.text valueDescription.pval_name.txt;
Doc.text ": ";
printTypExpr valueDescription.pval_type;
if isExternal then
Doc.group (
Doc.concat [
Doc.text " =";
Doc.indent(
Doc.concat [
Doc.line;
Doc.join ~sep:Doc.line (
List.map(fun s -> Doc.concat [
Doc.text "\"";
Doc.text s;
Doc.text "\"";
])
valueDescription.pval_prim
);
]
)
]
)
else Doc.nil
]
)
and printTypeDeclarations ~recFlag typeDeclarations =
let rows = List.mapi (fun i td ->
let doc = printTypeDeclaration
~name:(Doc.text td.Parsetree.ptype_name.txt)
~equalSign:"="
~recFlag
i td
in
(td.Parsetree.ptype_loc, doc)
) typeDeclarations in
interleaveWhitespace rows
(*
* type_declaration = {
* ptype_name: string loc;
* ptype_params: (core_type * variance) list;
* (* ('a1,...'an) t; None represents _*)
* ptype_cstrs: (core_type * core_type * Location.t) list;
* (* ... constraint T1=T1' ... constraint Tn=Tn' *)
* ptype_kind: type_kind;
* ptype_private: private_flag; (* = private ... *)
* ptype_manifest: core_type option; (* = T *)
* ptype_attributes: attributes; (* ... [@@id1] [@@id2] *)
* ptype_loc: Location.t;
* }
*
*
* type t (abstract, no manifest)
* type t = T0 (abstract, manifest=T0)
* type t = C of T | ... (variant, no manifest)
* type t = T0 = C of T | ... (variant, manifest=T0)
* type t = {l: T; ...} (record, no manifest)
* type t = T0 = {l : T; ...} (record, manifest=T0)
* type t = .. (open, no manifest)
*
*
* and type_kind =
* | Ptype_abstract
* | Ptype_variant of constructor_declaration list
* (* Invariant: non-empty list *)
* | Ptype_record of label_declaration list
* (* Invariant: non-empty list *)
* | Ptype_open
*)
and printTypeDeclaration ~name ~equalSign ~recFlag i (td: Parsetree.type_declaration) =
let attrs = printAttributes ~loc:td.ptype_loc td.ptype_attributes in
let prefix = if i > 0 then
Doc.text "and "
else
Doc.concat [Doc.text "type "; recFlag]
in
let typeName = name in
let typeParams = match td.ptype_params with
| [] -> Doc.nil
| typeParams -> Doc.group (
Doc.concat [
Doc.lessThan;
Doc.indent (
Doc.concat [
Doc.softLine;
Doc.join ~sep:(Doc.concat [Doc.comma; Doc.line]) (
List.map printTypeParam typeParams
)
]
);
Doc.trailingComma;
Doc.softLine;
Doc.greaterThan;
]
)
in
let manifestAndKind = match td.ptype_kind with
| Ptype_abstract ->
begin match td.ptype_manifest with
| None -> Doc.nil
| Some(typ) ->
Doc.concat [
Doc.concat [Doc.space; Doc.text equalSign; Doc.space];
printPrivateFlag td.ptype_private;
printTypExpr typ;
]
end
| Ptype_open -> Doc.concat [
Doc.concat [Doc.space; Doc.text equalSign; Doc.space];
printPrivateFlag td.ptype_private;
Doc.text "..";
]
| Ptype_record(lds) ->
let manifest = match td.ptype_manifest with
| None -> Doc.nil
| Some(typ) -> Doc.concat [
Doc.concat [Doc.space; Doc.text equalSign; Doc.space];
printTypExpr typ;
]
in
Doc.concat [
manifest;
Doc.concat [Doc.space; Doc.text equalSign; Doc.space];
printPrivateFlag td.ptype_private;
printRecordDeclaration lds;
]
| Ptype_variant(cds) ->
let manifest = match td.ptype_manifest with
| None -> Doc.nil
| Some(typ) -> Doc.concat [
Doc.concat [Doc.space; Doc.text equalSign; Doc.space];
printTypExpr typ;
]
in
Doc.concat [
manifest;
Doc.concat [Doc.space; Doc.text equalSign];
printConstructorDeclarations ~privateFlag:td.ptype_private cds;
]
in
let constraints = printTypeDefinitionConstraints td.ptype_cstrs in
Doc.group (
Doc.concat [
attrs;
prefix;
typeName;
typeParams;
manifestAndKind;
constraints;
]
)
and printTypeDefinitionConstraints cstrs =
match cstrs with
| [] -> Doc.nil
| cstrs -> Doc.indent (
Doc.group (
Doc.concat [
Doc.line;
Doc.group(
Doc.join ~sep:Doc.line (
List.map printTypeDefinitionConstraint cstrs
)
)
]
)
)
and printTypeDefinitionConstraint ((typ1, typ2, _loc ): Parsetree.core_type * Parsetree.core_type * Location.t) =
Doc.concat [
Doc.text "constraint ";
printTypExpr typ1;
Doc.text " = ";
printTypExpr typ2;
]
and printPrivateFlag (flag : Asttypes.private_flag) = match flag with
| Private -> Doc.text "private "
| Public -> Doc.nil
and printTypeParam (param : (Parsetree.core_type * Asttypes.variance)) =
let (typ, variance) = param in
let printedVariance = match variance with
| Covariant -> Doc.text "+"
| Contravariant -> Doc.text "-"
| Invariant -> Doc.nil
in
Doc.concat [
printedVariance;
printTypExpr typ
]
and printRecordDeclaration (lds: Parsetree.label_declaration list) =
let forceBreak = match (lds, List.rev lds) with
| (first::_, last::_) ->
first.pld_loc.loc_start.pos_lnum < last.pld_loc.loc_end.pos_lnum
| _ -> false
in
Doc.breakableGroup ~forceBreak (
Doc.concat [
Doc.lbrace;
Doc.indent (
Doc.concat [
Doc.softLine;
Doc.join ~sep:(Doc.concat [Doc.comma; Doc.line])
(List.map printLabelDeclaration lds)
]
);
Doc.trailingComma;
Doc.softLine;
Doc.rbrace;
]
)
and printConstructorDeclarations ~privateFlag (cds: Parsetree.constructor_declaration list) =
let forceBreak = match (cds, List.rev cds) with
| (first::_, last::_) ->
first.pcd_loc.loc_start.pos_lnum < last.pcd_loc.loc_end.pos_lnum
| _ -> false
in
let privateFlag = match privateFlag with
| Asttypes.Private -> Doc.concat [
Doc.text "private";
Doc.line;
]
| Public -> Doc.nil
in
Doc.breakableGroup ~forceBreak (
Doc.indent (
Doc.concat [
Doc.line;
privateFlag;
Doc.join ~sep:Doc.line (
List.mapi printConstructorDeclaration cds
)
]
)
)
(*
* {
* pcd_name: string loc;
* pcd_args: constructor_arguments;
* pcd_res: core_type option;
* pcd_loc: Location.t;
* pcd_attributes: attributes; (* C of ... [@id1] [@id2] *)
* }
*)
and printConstructorDeclaration i (cd : Parsetree.constructor_declaration) =
let attrs = printAttributes cd.pcd_attributes in
let bar = if i > 0 then Doc.text "| "
else Doc.ifBreaks (Doc.text "| ") Doc.nil
in
let constrName = Doc.text cd.pcd_name.txt in
let constrArgs = printConstructorArguments cd.pcd_args in
let gadt = match cd.pcd_res with
| None -> Doc.nil
| Some(typ) -> Doc.indent (
Doc.concat [
Doc.text ": ";
printTypExpr typ;
]
)
in
Doc.concat [
bar;
Doc.group (
Doc.concat [
attrs; (* TODO: fix parsing of attributes, so when can print them above the bar? *)
constrName;
constrArgs;
gadt;
]
)
]
and printConstructorArguments (cdArgs : Parsetree.constructor_arguments) =
match cdArgs with
| Pcstr_tuple [] -> Doc.nil
| Pcstr_tuple types -> Doc.group (
Doc.indent (
Doc.concat [
Doc.lparen;
Doc.indent (
Doc.concat [
Doc.softLine;
Doc.join ~sep:(Doc.concat [Doc.comma; Doc.line]) (
List.map printTypExpr types
)
]
);
Doc.trailingComma;
Doc.softLine;
Doc.rparen;
]
)
)
| Pcstr_record lds ->
Doc.indent (
Doc.concat [
Doc.lparen;
(* manually inline the printRecordDeclaration, gives better layout *)
Doc.lbrace;
Doc.indent (
Doc.concat [
Doc.softLine;
Doc.join ~sep:(Doc.concat [Doc.comma; Doc.line])
(List.map printLabelDeclaration lds)
]
);
Doc.trailingComma;
Doc.softLine;
Doc.rbrace;
Doc.rparen;
]
)
and printLabelDeclaration (ld : Parsetree.label_declaration) =
let attrs = printAttributes ~loc:ld.pld_name.loc ld.pld_attributes in
let mutableFlag = match ld.pld_mutable with
| Mutable -> Doc.text "mutable "
| Immutable -> Doc.nil
in
let name = Doc.text ld.pld_name.txt in
Doc.group (
Doc.concat [
attrs;
mutableFlag;
name;
Doc.text ": ";
printTypExpr ld.pld_type;
]
)
and printTypExpr (typExpr : Parsetree.core_type) =
let renderedType = match typExpr.ptyp_desc with
| Ptyp_any -> Doc.text "_"
| Ptyp_var var -> Doc.text ("'" ^ var)
| Ptyp_extension(extension) ->
printExtension extension
| Ptyp_alias(typ, alias) ->
let typ =
(* Technically type t = (string, float) => unit as 'x, doesn't require
* parens around the arrow expression. This is very confusing though.
* Is the "as" part of "unit" or "(string, float) => unit". By printing
* parens we guide the user towards its meaning.*)
let needsParens = match typ.ptyp_desc with
| Ptyp_arrow _ -> true
| _ -> false
in
let doc = printTypExpr typ in
if needsParens then
Doc.concat [Doc.lparen; doc; Doc.rparen]
else
doc
in
Doc.concat [typ; Doc.text " as "; Doc.text ("'" ^ alias)]
| Ptyp_constr({txt = Longident.Ldot(Longident.Lident "Js", "t")}, [typ]) ->
let bsObject = printTypExpr typ in
begin match typExpr.ptyp_attributes with
| [] -> bsObject
| attrs ->
Doc.concat [
Doc.group (
Doc.join ~sep:Doc.line (List.map printAttribute attrs)
);
Doc.space;
printTypExpr typ;
]
end
| Ptyp_constr(longidentLoc, [{ ptyp_desc = Parsetree.Ptyp_tuple tuple }]) ->
let constrName = printLongident longidentLoc.txt in
Doc.group(
Doc.concat([
constrName;
Doc.lessThan;
printTupleType ~inline:true tuple;
Doc.greaterThan;
])
)
| Ptyp_constr(longidentLoc, constrArgs) ->
let constrName = printLongident longidentLoc.txt in
begin match constrArgs with
| [] -> constrName
| [{
Parsetree.ptyp_desc =
Ptyp_constr({txt = Longident.Ldot(Longident.Lident "Js", "t")},
[{ptyp_desc = Ptyp_object (fields, openFlag)}])
}] ->
Doc.concat([
constrName;
Doc.lessThan;
printBsObjectSugar ~inline:true fields openFlag;
Doc.greaterThan;
])
| args -> Doc.group(
Doc.concat([
constrName;
Doc.lessThan;
Doc.indent (
Doc.concat [
Doc.softLine;
Doc.join ~sep:(Doc.concat [Doc.comma; Doc.line]) (
List.map printTypExpr constrArgs
)
]
);
Doc.trailingComma;
Doc.softLine;
Doc.greaterThan;
])
)
end
| Ptyp_arrow _ ->
let (attrsBefore, args, returnType) = ParsetreeViewer.arrowType typExpr in
let returnTypeNeedsParens = match returnType.ptyp_desc with
| Ptyp_alias _ -> true
| _ -> false