-
-
Notifications
You must be signed in to change notification settings - Fork 193
/
CodePrinter.fs
4761 lines (4126 loc) · 192 KB
/
CodePrinter.fs
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 internal Fantomas.Core.CodePrinter
open System
open System.Text.RegularExpressions
open FSharp.Compiler.Text
open FSharp.Compiler.Syntax
open FSharp.Compiler.SyntaxTrivia
open FSharp.Compiler.Xml
open Fantomas.Core.AstExtensions
open Fantomas.Core.FormatConfig
open Fantomas.Core.SourceParser
open Fantomas.Core.SourceTransformer
open Fantomas.Core.Context
open Fantomas.Core.TriviaTypes
let rec addSpaceBeforeParensInFunCall functionOrMethod arg (ctx: Context) =
match functionOrMethod, arg with
| SynExpr.TypeApp(e, _, _, _, _, _, _), _ -> addSpaceBeforeParensInFunCall e arg ctx
| SynExpr.Paren _, _ -> true
| SynExpr.Const _, _ -> true
| UppercaseSynExpr, ConstUnitExpr -> ctx.Config.SpaceBeforeUppercaseInvocation
| LowercaseSynExpr, ConstUnitExpr -> ctx.Config.SpaceBeforeLowercaseInvocation
| SynExpr.Ident _, SynExpr.Ident _ -> true
| UppercaseSynExpr, Paren _ -> ctx.Config.SpaceBeforeUppercaseInvocation
| LowercaseSynExpr, Paren _ -> ctx.Config.SpaceBeforeLowercaseInvocation
| _ -> true
let addSpaceBeforeParenInPattern (sli: SynLongIdent) (ctx: Context) =
match List.tryLast sli.LongIdent with
| None -> sepSpace ctx
| Some ident when String.IsNullOrWhiteSpace ident.idText -> sepSpace ctx
| Some ident ->
let parameterValue =
if Char.IsUpper ident.idText.[0] then
ctx.Config.SpaceBeforeUppercaseInvocation
else
ctx.Config.SpaceBeforeLowercaseInvocation
onlyIf parameterValue sepSpace ctx
let addSpaceBeforeParensInFunDef (spaceBeforeSetting: bool) (functionOrMethod: SynLongIdent) args =
match functionOrMethod, args with
| SynLongIdent(id = [ newIdent ]), _ when newIdent.idText = "new" -> false
| _, PatParen _ -> spaceBeforeSetting
| _, PatNamed _
| _, SynPat.Wild _ -> true
| SynLongIdent(id = lid), _ ->
match List.tryLast lid with
| None -> false
| Some ident -> not (Char.IsUpper ident.idText.[0])
| _ -> true
let rec genParsedInput ast =
let genParsedInput =
match ast with
| ImplFile im -> genImpFile im
| SigFile si -> genSigFile si
genTriviaFor ParsedInput_ ast.FullRange genParsedInput +> addFinalNewline
/// Respect insert_final_newline setting
and addFinalNewline ctx =
let lastEvent = ctx.WriterEvents.TryHead
match lastEvent with
| Some WriteLineBecauseOfTrivia ->
if ctx.Config.InsertFinalNewline then
ctx
else
// Due to trivia the last event is a newline, if insert_final_newline is false, we need to remove it.
{ ctx with
WriterEvents = ctx.WriterEvents.Tail
WriterModel = { ctx.WriterModel with Lines = List.tail ctx.WriterModel.Lines } }
| _ -> onlyIf ctx.Config.InsertFinalNewline sepNln ctx
(*
See https://github.com/dotnet/fsharp/blob/main/src/Compiler/SyntaxTree/SyntaxTree.fs
hs = hashDirectives : ParsedHashDirective list
mns = modules : SynModuleOrNamespace list
*)
and genImpFile (ParsedImplFileInput(hs, mns, _, _)) =
col sepNln hs genParsedHashDirective
+> (if hs.IsEmpty then sepNone else sepNln)
+> col sepNln mns genModuleOrNamespace
and genSigFile (ParsedSigFileInput(hs, mns, _, _)) =
col sepNone hs genParsedHashDirective
+> (if hs.IsEmpty then sepNone else sepNln)
+> col sepNln mns genSigModuleOrNamespace
and genParsedHashDirective (ParsedHashDirective(h, args, r)) =
let genArg (arg: ParsedHashDirectiveArgument) =
match arg with
| ParsedHashDirectiveArgument.String(value, stringKind, range) ->
genConstString stringKind value
|> genTriviaFor ParsedHashDirectiveArgument_String range
| ParsedHashDirectiveArgument.SourceIdentifier(identifier, _, range) ->
!-identifier |> genTriviaFor ParsedHashDirectiveArgument_String range
!- "#" +> !-h +> sepSpace +> col sepSpace args genArg
|> genTriviaFor ParsedHashDirective_ r
and genModuleOrNamespaceKind (leadingKeyword: SynModuleOrNamespaceLeadingKeyword) (kind: SynModuleOrNamespaceKind) =
match leadingKeyword with
| SynModuleOrNamespaceLeadingKeyword.Namespace range ->
if kind = SynModuleOrNamespaceKind.GlobalNamespace then
genTriviaFor SynModuleOrNamespace_Namespace range !- "namespace" +> !- " global"
else
genTriviaFor SynModuleOrNamespace_Namespace range !- "namespace "
| SynModuleOrNamespaceLeadingKeyword.Module range -> genTriviaFor SynModuleOrNamespace_Module range !- "module "
| SynModuleOrNamespaceLeadingKeyword.None -> sepNone
and genModuleOrNamespace (ModuleOrNamespace(ats, px, leadingKeyword, ao, lids, mds, isRecursive, moduleKind, range)) =
let sepModuleAndFirstDecl =
let firstDecl = List.tryHead mds
match firstDecl with
| None -> sepNone
| Some mdl ->
sepNln
+> sepNlnConsideringTriviaContentBeforeFor (synModuleDeclToFsAstType mdl) mdl.Range
let moduleOrNamespace =
genModuleOrNamespaceKind leadingKeyword moduleKind
+> genAccessOpt ao
+> ifElse isRecursive (!- "rec ") sepNone
+> genLongIdent lids
// Anonymous module do have a single (fixed) ident in the LongIdent
// We don't print the ident but it could have trivia assigned to it.
let genTriviaForAnonModuleIdent =
match lids with
| [ ident ] ->
genTriviaFor Ident_ ident.idRange sepNone
|> genTriviaFor LongIdent_ ident.idRange
| _ -> sepNone
genPreXmlDoc px
+> genAttributes ats
+> ifElse
(moduleKind = SynModuleOrNamespaceKind.AnonModule)
genTriviaForAnonModuleIdent
(moduleOrNamespace +> sepModuleAndFirstDecl)
+> genModuleDeclList mds
|> (match moduleKind with
| SynModuleOrNamespaceKind.AnonModule -> genTriviaFor SynModuleOrNamespace_AnonModule range
| SynModuleOrNamespaceKind.DeclaredNamespace -> genTriviaFor SynModuleOrNamespace_DeclaredNamespace range
| SynModuleOrNamespaceKind.GlobalNamespace -> genTriviaFor SynModuleOrNamespace_GlobalNamespace range
| SynModuleOrNamespaceKind.NamedModule -> genTriviaFor SynModuleOrNamespace_NamedModule range)
and genSigModuleOrNamespace
(SigModuleOrNamespace(ats, px, leadingKeyword, ao, lids, mds, isRecursive, moduleKind, range))
=
let sepModuleAndFirstDecl =
let firstDecl = List.tryHead mds
match firstDecl with
| None -> sepNone
| Some mdl ->
sepNln
+> sepNlnConsideringTriviaContentBeforeFor (synModuleSigDeclToFsAstType mdl) mdl.Range
let moduleOrNamespace =
genModuleOrNamespaceKind leadingKeyword moduleKind
+> genAccessOpt ao
+> ifElse isRecursive (!- "rec ") sepNone
+> genLongIdent lids
genPreXmlDoc px
+> genAttributes ats
+> ifElse (moduleKind = SynModuleOrNamespaceKind.AnonModule) sepNone (moduleOrNamespace +> sepModuleAndFirstDecl)
+> genSigModuleDeclList mds
|> (match moduleKind with
| SynModuleOrNamespaceKind.AnonModule -> genTriviaFor SynModuleOrNamespaceSig_AnonModule range
| SynModuleOrNamespaceKind.DeclaredNamespace -> genTriviaFor SynModuleOrNamespaceSig_DeclaredNamespace range
| SynModuleOrNamespaceKind.GlobalNamespace -> genTriviaFor SynModuleOrNamespaceSig_GlobalNamespace range
| SynModuleOrNamespaceKind.NamedModule -> genTriviaFor SynModuleOrNamespaceSig_NamedModule range)
and genModuleDeclList e =
let rec collectItems
(e: SynModuleDecl list)
(finalContinuation: ColMultilineItem list -> ColMultilineItem list)
: ColMultilineItem list =
match e with
| [] -> finalContinuation []
| OpenL(xs, ys) ->
let expr = col sepNln xs genModuleDecl
let r, triviaType =
List.head xs |> fun mdl -> mdl.Range, synModuleDeclToFsAstType mdl
// SynModuleDecl.Open cannot have attributes
let sepNln = sepNlnConsideringTriviaContentBeforeFor triviaType r
collectItems ys (fun ysItems -> ColMultilineItem(expr, sepNln) :: ysItems |> finalContinuation)
| HashDirectiveL(xs, ys) ->
let expr = col sepNln xs genModuleDecl
let r = List.head xs |> fun mdl -> mdl.Range
// SynModuleDecl.HashDirective cannot have attributes
let sepNln = sepNlnConsideringTriviaContentBeforeFor SynModuleDecl_HashDirective r
collectItems ys (fun ysItems -> ColMultilineItem(expr, sepNln) :: ysItems |> finalContinuation)
| AttributesL(xs, y :: rest) ->
let expr =
col sepNln xs genModuleDecl
+> sepNlnConsideringTriviaContentBeforeFor (synModuleDeclToFsAstType y) y.Range
+> genModuleDecl y
let r = List.head xs |> fun mdl -> mdl.Range
let sepNln = sepNlnConsideringTriviaContentBeforeFor SynModuleDecl_Attributes r
collectItems rest (fun restItems -> ColMultilineItem(expr, sepNln) :: restItems |> finalContinuation)
| m :: rest ->
let sepNln =
sepNlnConsideringTriviaContentBeforeFor (synModuleDeclToFsAstType m) m.Range
let expr = genModuleDecl m
collectItems rest (fun restItems -> ColMultilineItem(expr, sepNln) :: restItems |> finalContinuation)
collectItems e id |> colWithNlnWhenItemIsMultiline
and genSigModuleDeclList (e: SynModuleSigDecl list) =
let rec collectItems
(e: SynModuleSigDecl list)
(finalContinuation: ColMultilineItem list -> ColMultilineItem list)
: ColMultilineItem list =
match e with
| [] -> finalContinuation []
| SigOpenL(xs, ys) ->
let expr = col sepNln xs genSigModuleDecl
let r, triviaType =
List.head xs |> fun mdl -> mdl.Range, synModuleSigDeclToFsAstType mdl
// SynModuleSigDecl.Open cannot have attributes
let sepNln = sepNlnConsideringTriviaContentBeforeFor triviaType r
collectItems ys (fun ysItems -> ColMultilineItem(expr, sepNln) :: ysItems |> finalContinuation)
| SigHashDirectiveL(xs, ys) ->
let expr = col sepNln xs genSigModuleDecl
let r = List.head xs |> fun mdl -> mdl.Range
let sepNln =
sepNlnConsideringTriviaContentBeforeFor SynModuleSigDecl_HashDirective r
collectItems ys (fun ysItems -> ColMultilineItem(expr, sepNln) :: ysItems |> finalContinuation)
| s :: rest ->
let sepNln =
sepNlnConsideringTriviaContentBeforeFor (synModuleSigDeclToFsAstType s) s.Range
let expr = genSigModuleDecl s
collectItems rest (fun restItems -> ColMultilineItem(expr, sepNln) :: restItems |> finalContinuation)
collectItems e id |> colWithNlnWhenItemIsMultiline
and genModuleDecl (node: SynModuleDecl) =
match node with
| Attributes ats ->
fun (ctx: Context) ->
let attributesExpr =
// attributes can have trivia content before or after
// we do extra detection to ensure no additional newline is introduced
// first attribute should not have a newline anyway
List.fold
(fun (prevContentAfterPresent, prevExpr) (a: SynAttributeList) ->
let expr =
ifElse
prevContentAfterPresent
sepNone
(sepNlnConsideringTriviaContentBeforeFor SynModuleDecl_Attributes a.Range)
+> ((col sepNln a.Attributes genAttribute) |> genTriviaFor SynAttributeList_ a.Range)
let hasContentAfter = ctx.HasContentAfter(SynAttributeList_, a.Range)
(hasContentAfter, prevExpr +> expr))
(true, sepNone)
ats
|> snd
attributesExpr ctx
| DeclExpr e -> genExpr e
| Exception ex -> genException ex
| HashDirective p -> genParsedHashDirective p
| Let(ExternBinding eb) -> genExternBinding eb
| Let b -> genSynBinding b
| LetRec bs -> genSynBindings bs false
| ModuleAbbrev(ident, lid) -> !- "module " +> genIdent ident +> sepEq +> sepSpace +> genLongIdent lid
| NamespaceFragment m -> failwithf "NamespaceFragment hasn't been implemented yet: %O" m
| NestedModule(ats, px, moduleKeyword, ao, lid, isRecursive, equalsRange, mds) ->
genPreXmlDoc px
+> genAttributes ats
+> genTriviaForOption SynModuleDecl_NestedModule_Module moduleKeyword (!- "module ")
+> genAccessOpt ao
+> ifElse isRecursive (!- "rec ") sepNone
+> genLongIdent lid
+> genEq SynModuleDecl_NestedModule_Equals equalsRange
+> indent
+> sepNln
+> genModuleDeclList mds
+> unindent
| Open lid -> !- "open " +> genSynLongIdent false lid
| OpenType lid -> !- "open type " +> genSynLongIdent false lid
// There is no nested types and they are recursive if there are more than one definition
| Types ts ->
let items =
List.map
(fun (t: SynTypeDefn) ->
ColMultilineItem(genTypeDefn t, sepNlnConsideringTriviaContentBeforeFor SynTypeDefn_ t.Range))
ts
colWithNlnWhenItemIsMultilineUsingConfig items
| md -> failwithf "Unexpected module declaration: %O" md
|> genTriviaFor (synModuleDeclToFsAstType node) node.Range
and genSigModuleDecl node =
match node with
| SigException ex -> genSigException ex
| SigHashDirective p -> genParsedHashDirective p
| SigVal v -> genVal v None
| SigModuleAbbrev(ident, lid) -> !- "module " +> genIdent ident +> sepEq +> sepSpace +> genLongIdent lid
| SigNamespaceFragment m -> failwithf "NamespaceFragment is not supported yet: %O" m
| SigNestedModule(ats, px, moduleKeyword, ao, lid, equalsRange, mds) ->
genPreXmlDoc px
+> genAttributes ats
+> genTriviaForOption SynModuleSigDecl_NestedModule_Module moduleKeyword !- "module "
+> genAccessOpt ao
+> genLongIdent lid
+> genEq SynModuleSigDecl_NestedModule_Equals equalsRange
+> indent
+> sepNln
+> genSigModuleDeclList mds
+> unindent
| SigOpen lid -> !- "open " +> genSynLongIdent false lid
| SigOpenType sli -> !- "open type " +> genSynLongIdent false sli
| SigTypes ts ->
let items =
List.map
(fun (t: SynTypeDefnSig) ->
let sepNln = sepNlnConsideringTriviaContentBeforeFor SynTypeDefnSig_ t.Range
ColMultilineItem(genSigTypeDefn t, sepNln))
ts
colWithNlnWhenItemIsMultilineUsingConfig items
| md -> failwithf "Unexpected module signature declaration: %O" md
|> genTriviaFor (synModuleSigDeclToFsAstType node) node.Range
and genIdent (ident: Ident) =
let width = ident.idRange.EndColumn - ident.idRange.StartColumn
let genIdent =
if ident.idText.Length + 4 = width then
// add backticks
!- $"``{ident.idText}``"
else
!-ident.idText
genTriviaFor Ident_ ident.idRange genIdent
and genLongIdent (lid: LongIdent) =
col sepDot lid genIdent |> genTriviaFor LongIdent_ (longIdentFullRange lid)
and genSynIdent (addDot: bool) (synIdent: SynIdent) =
let (SynIdent(ident, trivia)) = synIdent
match trivia with
| Some(IdentTrivia.OriginalNotation text) -> !-text
| Some(IdentTrivia.OriginalNotationWithParen(_, text, _)) -> !- $"({text})"
| Some(IdentTrivia.HasParenthesis _) -> !- $"({ident.idText})"
| None -> genIdent ident
|> fun genSy -> genTriviaFor SynIdent_ synIdent.FullRange (onlyIf addDot sepDot +> genSy)
and genSynLongIdent (addLeadingDot: bool) (longIdent: SynLongIdent) =
let lastIndex = longIdent.IdentsWithTrivia.Length - 1
coli sepNone longIdent.IdentsWithTrivia (fun idx si ->
genSynIdent (addLeadingDot || idx > 0) si
+> onlyIf (idx < lastIndex) sepNlnWhenWriteBeforeNewlineNotEmpty)
|> genTriviaFor SynLongIdent_ longIdent.FullRange
and genSynLongIdentMultiline (addLeadingDot: bool) (longIdent: SynLongIdent) =
coli sepNln longIdent.IdentsWithTrivia (fun idx -> genSynIdent (idx > 0 || addLeadingDot))
|> genTriviaFor SynLongIdent_ longIdent.FullRange
// TODO: multiple keyword should be split up!
and genSynLeadingKeyword (lk: SynLeadingKeyword) =
match lk with
| SynLeadingKeyword.Let _ -> genTriviaFor SynLeadingKeyword_Let lk.Range !- "let "
| SynLeadingKeyword.LetRec(_letRange, _recRange) -> !- "let rec " |> genTriviaFor SynLeadingKeyword_LetRec lk.Range
| SynLeadingKeyword.And _ -> genTriviaFor SynLeadingKeyword_And lk.Range !- "and "
| SynLeadingKeyword.Use _ -> genTriviaFor SynLeadingKeyword_Use lk.Range !- "use "
| SynLeadingKeyword.UseRec(_useRange, _recRange) -> genTriviaFor SynLeadingKeyword_UseRec lk.Range !- "use rec "
| SynLeadingKeyword.Extern _ -> genTriviaFor SynLeadingKeyword_Extern lk.Range !- "extern "
| SynLeadingKeyword.Member _ -> genTriviaFor SynLeadingKeyword_Member lk.Range !- "member "
| SynLeadingKeyword.MemberVal(_memberRange, _valRange) ->
genTriviaFor SynLeadingKeyword_MemberVal lk.Range !- "member val "
| SynLeadingKeyword.Override _ -> genTriviaFor SynLeadingKeyword_Override lk.Range !- "override "
| SynLeadingKeyword.OverrideVal(_overrideRange, _valRange) ->
genTriviaFor SynLeadingKeyword_OverrideVal lk.Range !- "override val "
| SynLeadingKeyword.Abstract _ -> genTriviaFor SynLeadingKeyword_Abstract lk.Range !- "abstract "
| SynLeadingKeyword.AbstractMember(_abstractRange, _memberRange) ->
genTriviaFor SynLeadingKeyword_AbstractMember lk.Range !- "abstract member "
| SynLeadingKeyword.StaticMember(_staticRange, _memberRange) ->
genTriviaFor SynLeadingKeyword_StaticMember lk.Range !- "static member "
| SynLeadingKeyword.StaticMemberVal(_staticRange, _memberRange, _valRange) ->
genTriviaFor SynLeadingKeyword_StaticMemberVal lk.Range !- "static member val "
| SynLeadingKeyword.StaticAbstract(_staticRange, _abstractRange) ->
genTriviaFor SynLeadingKeyword_StaticAbstract lk.Range !- "static abstract "
| SynLeadingKeyword.StaticAbstractMember(_staticRange, _abstractMember, _memberRange) ->
genTriviaFor SynLeadingKeyword_StaticAbstractMember lk.Range !- "static abstract member "
| SynLeadingKeyword.StaticVal(_staticRange, _valRange) ->
genTriviaFor SynLeadingKeyword_StaticVal lk.Range !- "static val "
| SynLeadingKeyword.StaticLet(_staticRange, _letRange) ->
genTriviaFor SynLeadingKeyword_StaticLet lk.Range !- "static let "
| SynLeadingKeyword.StaticLetRec(_staticRange, _letRange, _recRange) ->
genTriviaFor SynLeadingKeyword_StaticLetRec lk.Range !- "static let rec "
| SynLeadingKeyword.StaticDo(_staticRange, _doRange) ->
genTriviaFor SynLeadingKeyword_StaticLetRec lk.Range !- "static do "
| SynLeadingKeyword.Default _ -> genTriviaFor SynLeadingKeyword_Default lk.Range !- "default "
| SynLeadingKeyword.DefaultVal(_defaultRange, _valRange) ->
genTriviaFor SynLeadingKeyword_DefaultVal lk.Range !- "default val "
| SynLeadingKeyword.Val _ -> genTriviaFor SynLeadingKeyword_Val lk.Range !- "val "
| SynLeadingKeyword.New _ -> genTriviaFor SynLeadingKeyword_New lk.Range !- "new"
| SynLeadingKeyword.Do _ -> genTriviaFor SynLeadingKeyword_Do lk.Range !- "do "
| SynLeadingKeyword.Synthetic -> sepNone
and genAccess (vis: SynAccess) =
match vis with
| SynAccess.Public r -> genTriviaFor SynAccess_Public r !- "public"
| SynAccess.Internal r -> genTriviaFor SynAccess_Internal r !- "internal"
| SynAccess.Private r -> genTriviaFor SynAccess_Private r !- "private"
and genAccessOpt (ao: SynAccess option) =
optSingle (fun ao -> genAccess ao +> sepSpace) ao
and genAttribute (Attribute(sli, e, target)) =
match e with
// Special treatment for function application on attributes
| ConstUnitExpr -> !- "[<" +> opt sepColon target genIdent +> genSynLongIdent false sli +> !- ">]"
| e ->
let argSpacing = if hasParenthesis e then sepNone else sepSpace
!- "[<"
+> opt sepColon target genIdent
+> genSynLongIdent false sli
+> argSpacing
+> genExpr e
+> !- ">]"
and genAttributesCore (ats: SynAttribute seq) =
let genAttributeExpr (Attribute(sli, e, target) as attr) =
match e with
| ConstUnitExpr -> opt sepColon target genIdent +> genSynLongIdent false sli
| e ->
let argSpacing = if hasParenthesis e then sepNone else sepSpace
opt sepColon target genIdent
+> genSynLongIdent false sli
+> argSpacing
+> genExpr e
|> genTriviaFor SynAttribute_ attr.Range
let shortExpression =
!- "[<" +> atCurrentColumn (col sepSemi ats genAttributeExpr) +> !- ">]"
let longExpression =
!- "[<"
+> atCurrentColumn (col (sepSemi +> sepNln) ats genAttributeExpr)
+> !- ">]"
ifElse (Seq.isEmpty ats) sepNone (expressionFitsOnRestOfLine shortExpression longExpression)
and genOnelinerAttributes ats =
let ats = List.collect (fun (a: SynAttributeList) -> a.Attributes) ats
ifElse (Seq.isEmpty ats) sepNone (genAttributesCore ats +> sepSpace)
/// Try to group attributes if they are on the same line
/// Separate same-line attributes by ';'
/// Each bucket is printed in a different line
and genAttributes (ats: SynAttributes) =
colPost sepNlnUnlessLastEventIsNewline sepNln ats (fun a ->
(genAttributesCore a.Attributes |> genTriviaFor SynAttributeList_ a.Range)
+> sepNlnWhenWriteBeforeNewlineNotEmpty)
and genPreXmlDoc (PreXmlDoc(lines, _)) =
colPost sepNln sepNln lines (sprintf "///%s" >> (!-))
and genExprSepEqPrependType (equalsAstType: FsAstType) (equalsRange: range option) (e: SynExpr) =
match e with
| TypedExpr(Typed, e, t) ->
sepColon
+> genType t
+> genEq equalsAstType equalsRange
+> sepSpaceOrIndentAndNlnIfExpressionExceedsPageWidth (genExpr e)
| _ ->
genEq equalsAstType equalsRange
+> sepSpaceOrIndentAndNlnIfExpressionExceedsPageWidth (genExpr e)
and genTypeSupportMember st =
match st with
| SynType.Var(td, _) -> genTypar td
| TLongIdent sli -> genSynLongIdent false sli
| _ -> !- ""
and genTypeAndParam (typeName: Context -> Context) (tds: SynTyparDecls option) tcs =
let types openSep tds tcs closeSep =
(openSep
+> coli sepComma tds (fun i -> genTyparDecl (i = 0))
+> genSynTypeConstraintList tcs
+> closeSep)
match tds with
| None -> typeName
| Some(PostfixList(gt, tds, tcs, lt, _)) ->
typeName
+> types
(genTriviaFor SynTyparDecls_PostfixList_Greater gt !- "<")
tds
tcs
(genTriviaFor SynTyparDecls_PostfixList_Lesser lt !- ">")
| Some(SynTyparDecls.PostfixList _) -> sepNone // captured above
| Some(SynTyparDecls.PrefixList(tds, _range)) -> types (!- "(") tds [] (!- ")") +> !- " " +> typeName
| Some(SynTyparDecls.SinglePrefix(td, _range)) -> genTyparDecl true td +> sepSpace +> typeName
+> colPre (!- " when ") wordAnd tcs genTypeConstraint
and genTypeParamPostfix tds =
match tds with
| Some(PostfixList(gt, tds, tcs, lt, _range)) ->
(genTriviaFor SynTyparDecls_PostfixList_Greater gt !- "<")
+> coli sepComma tds (fun i -> genTyparDecl (i = 0))
+> genSynTypeConstraintList tcs
+> (genTriviaFor SynTyparDecls_PostfixList_Lesser lt !- ">")
| _ -> sepNone
and genSynTypeConstraintList tcs =
match tcs with
| [] -> sepNone
| _ ->
let short = colPre (sepSpace +> !- "when ") wordAnd tcs genTypeConstraint
let long =
colPre (!- "when ") (sepNln +> wordAndFixed +> sepSpace) tcs genTypeConstraint
autoIndentAndNlnIfExpressionExceedsPageWidth (expressionFitsOnRestOfLine short long)
and genExternBinding (leadingKeyword, ao, attrs, px, pat, rt) =
let rec genTypeForExtern t =
match t with
| TApp(TLongIdent(SynLongIdent([ _ ], [], [ Some(IdentTrivia.OriginalNotation "*") ])), _, [ t ], _, true, range) ->
genType t +> !- "*" |> genTriviaFor SynType_App range
| TApp(TLongIdent(SynLongIdent([ _ ], [], [ Some(IdentTrivia.OriginalNotation "&") ])), _, [ t ], _, true, range) ->
genType t +> !- "&" |> genTriviaFor SynType_App range
| TApp(TArrayInExtern arrayText, None, [ TApp(t, _, _, _, _, _) ], None, true, _) ->
genTypeForExtern t +> !-arrayText
| TArrayInExtern arrayText -> !-arrayText
| _ -> genType t
let rec genPatForExtern pat =
match pat with
| PatAttrib(PatTyped(PatNullary _, t), attrs) -> genOnelinerAttributes attrs +> genTypeForExtern t
| PatAttrib(PatTyped(p, t), attrs) -> genOnelinerAttributes attrs +> genTypeForExtern t +> sepSpace +> genPat p
| PatLongIdent(_, sli, [ PatTuple ps ], _) ->
let short =
genSynLongIdent false sli
+> sepOpenT
+> col sepComma ps genPatForExtern
+> sepCloseT
let long =
genSynLongIdent false sli
+> sepOpenT
+> indentSepNlnUnindent (col (sepComma +> sepNln) ps genPatForExtern)
+> sepNln
+> sepCloseT
expressionFitsOnRestOfLine short long
| _ -> genPat pat
genPreXmlDoc px
+> genAttributes attrs
+> genSynLeadingKeyword leadingKeyword
+> optSingle (fun (a, t) -> genOnelinerAttributes a +> genType t +> sepSpace) rt
+> genAccessOpt ao
+> genPatForExtern pat
+> sepSpace
and genProperty (getOrSetType: FsAstType, getOrSetRange: range, binding: SynBinding) =
let genGetOrSet =
let getOrSetText =
match getOrSetType with
| SynMemberDefn_GetSetMember_Get -> "get"
| SynMemberDefn_GetSetMember_Set -> "set"
| _ -> failwith "expected \"get\" or \"set\""
genTriviaFor getOrSetType getOrSetRange !-getOrSetText +> sepSpace
match binding with
| SynBinding(headPat = PatLongIdent(ao, _, ps, _); expr = e; trivia = { EqualsRange = equalsRange }) ->
let tuplerize ps =
let rec loop acc =
function
| [ p ] -> (List.rev acc, p)
| p1 :: ps -> loop (p1 :: acc) ps
| [] -> invalidArg "p" "Patterns should not be empty"
loop [] ps
match ps with
| [ PatTuple ps ] ->
let ps, p = tuplerize ps
genAccessOpt ao
+> genGetOrSet
+> ifElse
(List.atMostOne ps)
(col sepComma ps genPat +> sepSpace)
(sepOpenT +> col sepComma ps genPat +> sepCloseT +> sepSpace)
+> genPat p
+> genExprSepEqPrependType SynBinding_Equals equalsRange e
| ps ->
genAccessOpt ao
+> genGetOrSet
+> col sepSpace ps genPat
+> genExprSepEqPrependType SynBinding_Equals equalsRange e
| _ -> sepNone
and genMemberBinding b =
match b with
| ExplicitCtor(ats, px, ao, p, equalsRange, e, io) ->
let prefix =
let genPat ctx =
match p with
| PatExplicitCtor(ao, pat) ->
(genAccessOpt ao +> !- "new" +> sepSpaceBeforeClassConstructor +> genPat pat) ctx
| _ -> genPat p ctx
genPreXmlDoc px
+> genAttributes ats
+> genAccessOpt ao
+> genPat
+> optSingle (fun ident -> !- " as " +> genIdent ident) io
match e with
// Handle special "then" block i.e. fake sequential expressions in constructors
| Sequential(e1, e2, false) ->
prefix
+> genEq SynBinding_Equals equalsRange
+> indent
+> sepNln
+> genExpr e1
+> sepNln
+> !- "then "
+> autoIndentAndNlnIfExpressionExceedsPageWidth (genExpr e2)
+> unindent
| e ->
prefix
+> genEq SynBinding_Equals equalsRange
+> sepSpaceOrIndentAndNlnIfExpressionExceedsPageWidth (genExpr e)
| _ -> genSynBinding b
and genVal
(Val(ats, px, leadingKeyword, ao, si, t, _, isInline, isMutable, tds, eo, range))
(optGetSet: string option)
=
let typeName = genTypeAndParam (genSynIdent false si) tds []
let hasGenerics = Option.isSome tds
let lk =
match leadingKeyword with
| SynLeadingKeyword.New _ ->
// new is also the name of the type
sepNone
| _ -> genSynLeadingKeyword leadingKeyword
genPreXmlDoc px
+> genAttributes ats
+> (lk
+> onlyIf isInline (!- "inline ")
+> onlyIf isMutable (!- "mutable ")
+> genAccessOpt ao
+> typeName)
+> ifElse hasGenerics sepColonWithSpacesFixed sepColon
+> genTypeInSignature t
+> optSingle (!-) optGetSet
+> optSingle (fun e -> sepEq +> sepSpace +> genExpr e) eo
|> genTriviaFor SynValSig_ range
and genTypeInSignature (FunType ts) =
match ts with
| [ TWithGlobalConstraints(t, tcs), None ] -> genConstraints t tcs
| ts -> autoIndentAndNlnIfExpressionExceedsPageWidth (genTypeList ts)
and genRecordFieldName (SynExprRecordField((rfn, _), equalsRange, eo, _blockSeparator) as rf) =
opt sepNone eo (fun e ->
let expr = sepSpaceOrIndentAndNlnIfExpressionExceedsPageWidth (genExpr e)
genSynLongIdent false rfn +> genEq SynExprRecordField_Equals equalsRange +> expr)
|> genTriviaFor SynExprRecordField_ rf.FullRange
and genAnonRecordFieldName (AnonRecordFieldName(ident, equalsRange, e, range)) =
let expr = sepSpaceOrIndentAndNlnIfExpressionExceedsPageWidth (genExpr e)
genIdent ident +> genEq SynExpr_AnonRecd_Field_Equals equalsRange +> expr
|> genTriviaFor SynExpr_AnonRecd_Field range
and genTuple es =
let genShortExpr e = addParenForTupleWhen genExpr e
let shortExpression = col sepComma es genShortExpr
let longExpression = genTupleMultiline es
atCurrentColumn (expressionFitsOnRestOfLine shortExpression longExpression)
and genTupleMultiline es =
let containsLambdaOrMatchExpr =
es
|> List.pairwise
|> List.exists (function
| SynExpr.Match _, _
| SynExpr.Lambda _, _
| InfixApp(_, _, _, SynExpr.Lambda _, _), _ -> true
| _ -> false)
let sep =
if containsLambdaOrMatchExpr then
(sepNln +> sepComma)
else
(sepCommaFixed +> sepNln)
let lastIndex = List.length es - 1
let genExpr idx e =
match e with
| SynExpr.IfThenElse _ when (idx < lastIndex) -> autoParenthesisIfExpressionExceedsPageWidth (genExpr e)
| InfixApp(equal, operatorSli, e1, e2, range) when (equal = "=") -> genNamedArgumentExpr operatorSli e1 e2 range
| _ -> genExpr e
coli sep es genExpr
and genNamedArgumentExpr (operatorSli: SynLongIdent) e1 e2 appRange =
let short =
genExpr e1
+> sepSpace
+> genSynLongIdent false operatorSli
+> sepSpace
+> genExpr e2
let long =
genExpr e1
+> sepSpace
+> genSynLongIdent false operatorSli
+> autoIndentAndNlnExpressUnlessStroustrup (fun e -> sepSpace +> genExpr e) e2
expressionFitsOnRestOfLine short long |> genTriviaFor SynExpr_App appRange
and genExpr synExpr ctx =
let expr =
match synExpr with
| LazyExpr(lazyKeyword, e) ->
let isInfixExpr =
match e with
| InfixApp _ -> true
| _ -> false
let genInfixExpr (ctx: Context) =
isShortExpression
ctx.Config.MaxInfixOperatorExpression
// if this fits on the rest of line right after the lazy keyword, it should be wrapped in parenthesis.
(sepOpenT +> genExpr e +> sepCloseT)
// if it is multiline there is no need for parenthesis, because of the indentation
(indent +> sepNln +> genExpr e +> unindent)
ctx
let genNonInfixExpr = autoIndentAndNlnIfExpressionExceedsPageWidth (genExpr e)
genTriviaFor SynExpr_Lazy_Lazy lazyKeyword !- "lazy "
+> ifElse isInfixExpr genInfixExpr genNonInfixExpr
| SingleExpr(kind, e) ->
let mapping =
(match kind with
| YieldFrom _
| Yield _
| Return _
| ReturnFrom _
| Do _
| DoBang _ -> autoIndentAndNlnIfExpressionExceedsPageWidthUnlessStroustrup genExpr e
| _ -> autoIndentAndNlnIfExpressionExceedsPageWidth (genExpr e))
match kind with
| InferredDowncast downcastKeyword ->
genTriviaFor SynExpr_InferredDowncast_Downcast downcastKeyword !- "downcast "
| InferredUpcast upcastKeyword -> genTriviaFor SynExpr_InferredUpcast_Upcast upcastKeyword !- "upcast "
| Assert assertKeyword -> genTriviaFor SynExpr_Assert_Assert assertKeyword !- "assert "
| AddressOfSingle ampersandToken -> genTriviaFor SynExpr_AddressOf_SingleAmpersand ampersandToken !- "&"
| AddressOfDouble ampersandToken -> genTriviaFor SynExpr_AddressOf_DoubleAmpersand ampersandToken !- "&&"
| Yield yieldKeyword -> genTriviaFor SynExpr_YieldOrReturn_Yield yieldKeyword !- "yield "
| Return returnKeyword -> genTriviaFor SynExpr_YieldOrReturn_Return returnKeyword !- "return "
| YieldFrom yieldBangKeyword ->
genTriviaFor SynExpr_YieldOrReturnFrom_YieldBang yieldBangKeyword !- "yield! "
| ReturnFrom returnBangKeyword ->
genTriviaFor SynExpr_YieldOrReturnFrom_ReturnBang returnBangKeyword !- "return! "
| Do doKeyword -> genTriviaFor SynExpr_Do_Do doKeyword !- "do "
| DoBang doBangKeyword -> genTriviaFor SynExpr_DoBang_DoBang doBangKeyword !- "do! "
| Fixed fixedKeyword -> genTriviaFor SynExpr_Fixed_Fixed fixedKeyword !- "fixed "
+> mapping
| ConstExpr(c, r) -> genConst c r
| NullExpr -> !- "null"
// Not sure about the role of e1
| Quote(_, e2, isRaw) ->
let e =
expressionFitsOnRestOfLine (genExpr e2) (indent +> sepNln +> genExpr e2 +> unindent +> sepNln)
ifElse
isRaw
(!- "<@@" +> sepSpace +> e +> sepSpace +> !- "@@>")
(!- "<@" +> sepSpace +> e +> sepSpace +> !- "@>")
| TypedExpr(TypeTest, e, t) -> genExpr e +> !- " :? " +> genType t
| TypedExpr(Downcast, e, t) ->
let shortExpr = genExpr e +> !- " :?> " +> genType t
let longExpr = genExpr e +> sepNln +> !- ":?> " +> genType t
expressionFitsOnRestOfLine shortExpr longExpr
| TypedExpr(Upcast, e, t) ->
let shortExpr = genExpr e +> !- " :> " +> genType t
let longExpr = genExpr e +> sepNln +> !- ":> " +> genType t
expressionFitsOnRestOfLine shortExpr longExpr
| TypedExpr(Typed, (Lambda _ as e), t) -> genExpr e +> sepNln +> sepColon +> genType t
| TypedExpr(Typed, e, t) -> genExpr e +> sepColon +> genType t
| NewTuple(t, px) ->
let sepSpace (ctx: Context) =
match t with
| UppercaseSynType -> onlyIf ctx.Config.SpaceBeforeUppercaseInvocation sepSpace ctx
| LowercaseSynType -> onlyIf ctx.Config.SpaceBeforeLowercaseInvocation sepSpace ctx
let short = !- "new " +> genType t +> sepSpace +> genExpr px
let long =
!- "new "
+> genType t
+> sepSpace
+> genMultilineFunctionApplicationArguments px
expressionFitsOnRestOfLine short long
| SynExpr.New(_, t, e, _) -> !- "new " +> genType t +> sepSpace +> genExpr e
| Tuple(es, _) -> genTuple es
| StructTuple es -> !- "struct " +> sepOpenT +> genTuple es +> sepCloseT
| ArrayOrList(sr, isArray, [], er, _) ->
genArrayOrListOpeningToken isArray true sr
+> genArrayOrListClosingToken isArray true er
| ArrayOrList(openingTokenRange, isArray, xs, closingTokenRange, _) ->
let smallExpression =
genArrayOrListOpeningToken isArray false openingTokenRange
+> col sepSemi xs genExpr
+> genArrayOrListClosingToken isArray false closingTokenRange
let multilineExpression =
ifAlignBrackets
(genMultiLineArrayOrListAlignBrackets isArray xs openingTokenRange closingTokenRange)
(genMultiLineArrayOrList isArray xs openingTokenRange closingTokenRange)
fun ctx ->
if
List.exists isIfThenElseWithYieldReturn xs
|| List.forall isSynExprLambdaOrIfThenElse xs
then
multilineExpression ctx
else
let size = getListOrArrayExprSize ctx ctx.Config.MaxArrayOrListWidth xs
isSmallExpression size smallExpression multilineExpression ctx
| Record(openingBrace, inheritOpt, xs, eo, closingBrace) ->
let smallRecordExpr =
genTriviaFor SynExpr_Record_OpeningBrace openingBrace sepOpenS
+> optSingle
(fun inheritCtor ->
!- "inherit "
+> genInheritConstructor inheritCtor
+> onlyIf (List.isNotEmpty xs) sepSemi)
inheritOpt
+> optSingle (fun e -> genExpr e +> !- " with ") eo
+> col sepSemi xs genRecordFieldName
+> genTriviaFor SynExpr_Record_ClosingBrace closingBrace sepCloseS
let multilineRecordExpr =
ifAlignBrackets
(genMultilineRecordInstanceAlignBrackets openingBrace inheritOpt xs eo closingBrace)
(genMultilineRecordInstance openingBrace inheritOpt xs eo closingBrace)
fun ctx ->
let size = getRecordSize ctx xs
isSmallExpression size smallRecordExpr multilineRecordExpr ctx
| AnonRecord(openingBrace, isStruct, fields, copyInfo, closingBrace) ->
let smallExpression =
onlyIf isStruct !- "struct "
+> genTriviaFor SynExpr_AnonRecd_OpeningBrace openingBrace sepOpenAnonRecd
+> optSingle (fun e -> genExpr e +> !- " with ") copyInfo
+> col sepSemi fields genAnonRecordFieldName
+> genTriviaFor SynExpr_AnonRecd_ClosingBrace closingBrace sepCloseAnonRecd
let longExpression =
ifAlignBrackets
(genMultilineAnonRecordAlignBrackets openingBrace isStruct fields copyInfo closingBrace)
(genMultilineAnonRecord openingBrace isStruct fields copyInfo closingBrace)
fun (ctx: Context) ->
let size = getRecordSize ctx fields
isSmallExpression size smallExpression longExpression ctx
| ObjExpr(t, eio, withKeyword, bd, members, ims) ->
if List.isEmpty bd && List.isEmpty members && List.isEmpty ims then
// Check the role of the second part of eio
let param = opt sepNone (Option.map fst eio) genExpr
// See https://devblogs.microsoft.com/dotnet/announcing-f-5/#default-interface-member-consumption
sepOpenS +> !- "new " +> genType t +> param +> sepCloseS
else
ifAlignBrackets
(genObjExprAlignBrackets t eio withKeyword bd members ims)
(genObjExpr t eio withKeyword bd members ims)
| While(e1, e2) ->
atCurrentColumn (
!- "while "
+> genExpr e1
+> !- " do"
+> indent
+> sepNln
+> genExpr e2
+> unindent
)
| For(ident, equalsRange, e1, e2, e3, isUp) ->
atCurrentColumn (
!- "for "
+> genIdent ident
+> genEq SynExpr_For_Equals equalsRange
+> sepSpace
+> genExpr e1
+> ifElse isUp (!- " to ") (!- " downto ")
+> genExpr e2
+> !- " do"
+> indent
+> sepNln
+> genExpr e3
+> unindent
)
// Handle the form 'for i in e1 -> e2'
| ForEach(p, e1, e2, isArrow) ->
atCurrentColumn (
!- "for "
+> genPat p
+> !- " in "
+> autoIndentAndNlnIfExpressionExceedsPageWidth (genExpr e1)
+> ifElse
isArrow
(sepArrow +> autoIndentAndNlnIfExpressionExceedsPageWidth (genExpr e2))
(!- " do" +> indent +> sepNln +> genExpr e2 +> unindent)
)
| NamedComputationExpr(nameExpr, openingBrace, bodyExpr, closingBrace, computationExprRange) ->
fun ctx ->
let short =
genExpr nameExpr
+> sepSpace
+> (genTriviaFor SynExpr_ComputationExpr_OpeningBrace openingBrace sepOpenS
+> genExpr bodyExpr
+> genTriviaFor SynExpr_ComputationExpr_ClosingBrace closingBrace sepCloseS
|> genTriviaFor SynExpr_ComputationExpr computationExprRange)
let long =
genExpr nameExpr
+> sepSpace
+> (genTriviaFor SynExpr_ComputationExpr_OpeningBrace openingBrace sepOpenS
+> indent
+> sepNln
+> genExpr bodyExpr
+> unindent
+> sepNln
+> genTriviaFor SynExpr_ComputationExpr_ClosingBrace closingBrace sepCloseSFixed
|> genTriviaFor SynExpr_ComputationExpr computationExprRange)
expressionFitsOnRestOfLine short long ctx
| ComputationExpr(openingBrace, e, closingBrace) ->