-
-
Notifications
You must be signed in to change notification settings - Fork 193
/
CodePrinter.fs
5769 lines (5093 loc) · 223 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.CodePrinter
open System
open System.Text.RegularExpressions
open FSharp.Compiler.Text
open FSharp.Compiler.Syntax
open FSharp.Compiler.Xml
open Fantomas
open Fantomas.FormatConfig
open Fantomas.SourceParser
open Fantomas.SourceTransformer
open Fantomas.Context
open Fantomas.TriviaTypes
open Fantomas.TriviaContext
open Fantomas.AstExtensions
/// This type consists of contextual information which is important for formatting
/// Please avoid using this record as it can be the cause of unexpected behavior when used incorrectly
type ASTContext =
{ /// Current node is a subnode deep down in an interface
InterfaceRange: Range option
/// This pattern matters for formatting extern declarations
IsCStylePattern: bool
/// Range operators are naked in 'for..in..do' constructs
IsNakedRange: bool
/// A field is rendered as union field or not
IsUnionField: bool
/// First type param might need extra spaces to avoid parsing errors on `<^`, `<'`, etc.
IsFirstTypeParam: bool
/// Inside a SynPat of MatchClause
IsInsideMatchClausePattern: bool }
static member Default =
{ InterfaceRange = None
IsCStylePattern = false
IsNakedRange = false
IsUnionField = false
IsFirstTypeParam = false
IsInsideMatchClausePattern = false }
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 addSpaceBeforeParensInFunDef (spaceBeforeSetting: bool) (functionOrMethod: string) args =
let isLastPartUppercase =
let parts = functionOrMethod.Split '.'
Char.IsUpper parts.[parts.Length - 1].[0]
match functionOrMethod, args with
| "new", _ -> false
| _, PatParen _ -> spaceBeforeSetting
| _, PatNamed _
| _, SynPat.Wild _ -> true
| _: string, _ -> not isLastPartUppercase
| _ -> true
let rec genParsedInput astContext ast =
match ast with
| ImplFile im -> genImpFile astContext im
| SigFile si -> genSigFile astContext si
+> 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/fsharp/FSharp.Compiler.Service/blob/master/src/fsharp/ast.fs#L1518
hs = hashDirectives : ParsedHashDirective list
mns = modules : SynModuleOrNamespace list
*)
and genImpFile astContext (ParsedImplFileInput (hs, mns)) =
col sepNone hs genParsedHashDirective
+> (if hs.IsEmpty then sepNone else sepNln)
+> col sepNln mns (genModuleOrNamespace astContext)
and genSigFile astContext (ParsedSigFileInput (hs, mns)) =
col sepNone hs genParsedHashDirective
+> (if hs.IsEmpty then sepNone else sepNln)
+> col sepNln mns (genSigModuleOrNamespace astContext)
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 (kind: SynModuleOrNamespaceKind) =
match kind with
| SynModuleOrNamespaceKind.DeclaredNamespace -> !- "namespace "
| SynModuleOrNamespaceKind.NamedModule -> !- "module "
| SynModuleOrNamespaceKind.GlobalNamespace -> !- "namespace global"
| SynModuleOrNamespaceKind.AnonModule -> sepNone
and genModuleOrNamespace astContext (ModuleOrNamespace (ats, px, ao, lids, mds, isRecursive, moduleKind)) =
let sepModuleAndFirstDecl =
let firstDecl = List.tryHead mds
match firstDecl with
| None -> sepNone
| Some mdl ->
sepNln
+> sepNlnConsideringTriviaContentBeforeForMainNode (synModuleDeclToFsAstType mdl) mdl.Range
let lidsFullRange =
match lids with
| [] -> range.Zero
| (_, r) :: _ -> Range.unionRanges r (List.last lids |> snd)
let moduleOrNamespace =
genModuleOrNamespaceKind moduleKind
+> opt sepSpace ao genAccess
+> ifElse isRecursive (!- "rec ") sepNone
+> col (!- ".") lids (fun (lid, r) -> genTriviaFor Ident_ r (!-lid))
|> genTriviaFor LongIdent_ lidsFullRange
// 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
| [ (_, r) ] -> genTriviaFor Ident_ r sepNone
| _ -> sepNone
|> genTriviaFor LongIdent_ lidsFullRange
genPreXmlDoc px
+> genAttributes astContext ats
+> ifElse (moduleKind = SynModuleOrNamespaceKind.AnonModule) genTriviaForAnonModuleIdent moduleOrNamespace
+> sepModuleAndFirstDecl
+> genModuleDeclList astContext mds
and genSigModuleOrNamespace astContext (SigModuleOrNamespace (ats, px, ao, lids, mds, isRecursive, moduleKind)) =
let sepModuleAndFirstDecl =
let firstDecl = List.tryHead mds
match firstDecl with
| None -> sepNone
| Some mdl ->
match mdl with
| SynModuleSigDecl.Types _ ->
sepNlnConsideringTriviaContentBeforeForMainNode SynModuleSigDecl_Types mdl.Range
| SynModuleSigDecl.Val _ -> sepNlnConsideringTriviaContentBeforeForMainNode SynValSig_ mdl.Range
| _ -> sepNone
+> sepNln
let lidsFullRange =
match lids with
| [] -> range.Zero
| (_, r) :: _ -> Range.unionRanges r (List.last lids |> snd)
let moduleOrNamespace =
genModuleOrNamespaceKind moduleKind
+> opt sepSpace ao genAccess
+> ifElse isRecursive (!- "rec ") sepNone
+> col (!- ".") lids (fun (lid, r) -> genTriviaFor Ident_ r (!-lid))
|> genTriviaFor LongIdent_ lidsFullRange
genPreXmlDoc px
+> genAttributes astContext ats
+> ifElse (moduleKind = SynModuleOrNamespaceKind.AnonModule) sepNone moduleOrNamespace
+> sepModuleAndFirstDecl
+> genSigModuleDeclList astContext mds
and genModuleDeclList astContext 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 astContext)
let r = List.head xs |> fun mdl -> mdl.Range
// SynModuleDecl.Open cannot have attributes
let sepNln = sepNlnConsideringTriviaContentBeforeForMainNode SynModuleDecl_Open r
collectItems ys (fun ysItems ->
ColMultilineItem(expr, sepNln) :: ysItems
|> finalContinuation)
| HashDirectiveL (xs, ys) ->
let expr = col sepNln xs (genModuleDecl astContext)
let r = List.head xs |> fun mdl -> mdl.Range
// SynModuleDecl.HashDirective cannot have attributes
let sepNln =
sepNlnConsideringTriviaContentBeforeForMainNode SynModuleDecl_HashDirective r
collectItems ys (fun ysItems ->
ColMultilineItem(expr, sepNln) :: ysItems
|> finalContinuation)
| AttributesL (xs, y :: rest) ->
let expr =
col sepNln xs (genModuleDecl astContext)
+> sepNlnConsideringTriviaContentBeforeForMainNode (synModuleDeclToFsAstType y) y.Range
+> genModuleDecl astContext y
let r = List.head xs |> fun mdl -> mdl.Range
let sepNln =
sepNlnConsideringTriviaContentBeforeForMainNode SynModuleDecl_Attributes r
collectItems rest (fun restItems ->
ColMultilineItem(expr, sepNln) :: restItems
|> finalContinuation)
| m :: rest ->
let sepNln =
sepNlnConsideringTriviaContentBeforeForMainNode (synModuleDeclToFsAstType m) m.Range
let expr = genModuleDecl astContext m
collectItems rest (fun restItems ->
ColMultilineItem(expr, sepNln) :: restItems
|> finalContinuation)
collectItems e id |> colWithNlnWhenItemIsMultiline
and genSigModuleDeclList astContext (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 astContext)
let r = List.head xs |> fun mdl -> mdl.Range
// SynModuleSigDecl.Open cannot have attributes
let sepNln = sepNlnConsideringTriviaContentBeforeForMainNode SynModuleSigDecl_Open r
collectItems ys (fun ysItems ->
ColMultilineItem(expr, sepNln) :: ysItems
|> finalContinuation)
| s :: rest ->
let sepNln =
sepNlnConsideringTriviaContentBeforeForMainNode (synModuleSigDeclToFsAstType s) s.FullRange
let expr = genSigModuleDecl astContext s
collectItems rest (fun restItems ->
ColMultilineItem(expr, sepNln) :: restItems
|> finalContinuation)
collectItems e id |> colWithNlnWhenItemIsMultiline
and genModuleDecl astContext (node: SynModuleDecl) =
match node with
| Attributes ats ->
fun ctx ->
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
(sepNlnConsideringTriviaContentBeforeForMainNode SynModuleDecl_Attributes a.Range)
+> ((col sepNln a.Attributes (genAttribute astContext))
|> genTriviaFor SynAttributeList_ a.Range)
let hasContentAfter =
TriviaHelpers.``has content after after that matches``
(fun tn -> RangeHelpers.rangeEq tn.Range a.Range)
(function
| Newline
| Comment (LineCommentOnSingleLine _)
| Directive _ -> true
| _ -> false)
(Map.tryFindOrEmptyList SynAttributeList_ ctx.TriviaMainNodes)
(hasContentAfter, prevExpr +> expr))
(true, sepNone)
ats
|> snd
attributesExpr ctx
| DoExpr e -> genExprKeepIndentInBranch astContext e
| Exception ex -> genException astContext ex
| HashDirective p -> genParsedHashDirective p
| Extern (ats, px, ao, t, s, ps) ->
genPreXmlDoc px +> genAttributes astContext ats
-- "extern "
+> genType { astContext with IsCStylePattern = true } false t
+> sepSpace
+> opt sepSpace ao genAccess
-- s
+> sepOpenT
+> col sepComma ps (genPat { astContext with IsCStylePattern = true })
+> sepCloseT
// Add a new line after module-level let bindings
| Let b -> genLetBinding astContext "let " b
| LetRec (b :: bs) ->
let sepBAndBs =
match List.tryHead bs with
| Some b' ->
let r = b'.RangeOfBindingWithRhs
sepNln
+> sepNlnConsideringTriviaContentBeforeForMainNode (synBindingToFsAstType b) r
| None -> id
genLetBinding astContext "let rec " b
+> sepBAndBs
+> colEx
(fun (b': SynBinding) ->
let r = b'.RangeOfBindingWithRhs
sepNln
+> sepNlnConsideringTriviaContentBeforeForMainNode (synBindingToFsAstType b) r)
bs
(fun andBinding ->
enterNodeFor (synBindingToFsAstType b) andBinding.RangeOfBindingWithRhs
+> genLetBinding astContext "and " andBinding)
| ModuleAbbrev (s1, s2) -> !- "module " -- s1 +> sepEq +> sepSpace -- s2
| NamespaceFragment m -> failwithf "NamespaceFragment hasn't been implemented yet: %O" m
| NestedModule (ats, px, ao, s, isRecursive, mds) ->
genPreXmlDoc px
+> genAttributes astContext ats
+> genAfterAttributesBefore
SynModuleDecl_NestedModule_AfterAttributesBeforeModuleName
node.AfterAttributesBeforeNestedModuleName
+> (!- "module ")
+> opt sepSpace ao genAccess
+> ifElse isRecursive (!- "rec ") sepNone
-- s
+> sepEq
+> indent
+> sepNln
+> genModuleDeclList astContext mds
+> unindent
| Open s -> !-(sprintf "open %s" s)
| OpenType s -> !-(sprintf "open type %s" s)
// There is no nested types and they are recursive if there are more than one definition
| Types (t :: ts) ->
let items =
ColMultilineItem(genTypeDefn astContext true t, sepNone)
:: (List.map
(fun t ->
ColMultilineItem(
genTypeDefn astContext false t,
sepNlnConsideringTriviaContentBeforeForMainNode SynTypeDefn_ t.Range
))
ts)
colWithNlnWhenItemIsMultilineUsingConfig items
| md -> failwithf "Unexpected module declaration: %O" md
|> genTriviaFor (synModuleDeclToFsAstType node) node.Range
and genSigModuleDecl astContext node =
match node with
| SigException ex -> genSigException astContext ex
| SigHashDirective p -> genParsedHashDirective p
| SigVal v -> genVal astContext v
| SigModuleAbbrev (s1, s2) -> !- "module " -- s1 +> sepEq +> sepSpace -- s2
| SigNamespaceFragment m -> failwithf "NamespaceFragment is not supported yet: %O" m
| SigNestedModule (ats, px, ao, s, mds) ->
genPreXmlDoc px
+> genAttributes astContext ats
+> genAfterAttributesBefore
SynModuleSigDecl_NestedModule_AfterAttributesBeforeModuleName
node.AfterAttributesBeforeNestedModuleName
-- "module "
+> opt sepSpace ao genAccess
-- s
+> sepEq
+> indent
+> sepNln
+> genSigModuleDeclList astContext mds
+> unindent
| SigOpen s -> !-(sprintf "open %s" s)
| SigOpenType s -> !-(sprintf "open type %s" s)
| SigTypes (t :: ts) ->
let items =
ColMultilineItem(genSigTypeDefn astContext true t, sepNone)
:: (List.map
(fun (t: SynTypeDefnSig) ->
let sepNln = sepNlnConsideringTriviaContentBeforeForMainNode SynTypeDefnSig_ t.Range
ColMultilineItem(genSigTypeDefn astContext false t, sepNln))
ts)
colWithNlnWhenItemIsMultilineUsingConfig items
| md -> failwithf "Unexpected module signature declaration: %O" md
|> (match node with
| SynModuleSigDecl.Types _ -> genTriviaFor SynModuleSigDecl_Types node.Range
| SynModuleSigDecl.NestedModule _ -> genTriviaFor SynModuleSigDecl_NestedModule node.Range
| SynModuleSigDecl.Open (SynOpenDeclTarget.ModuleOrNamespace _, _) ->
genTriviaFor SynModuleSigDecl_Open node.Range
| SynModuleSigDecl.Open (SynOpenDeclTarget.Type _, _) -> genTriviaFor SynModuleSigDecl_OpenType node.Range
| SynModuleSigDecl.Exception _ -> genTriviaFor SynModuleSigDecl_Exception node.FullRange
| _ -> id)
and genAccess (Access s) = !-s
and genAttribute astContext (Attribute (s, e, target)) =
match e with
// Special treatment for function application on attributes
| ConstUnitExpr -> !- "[<" +> opt sepColon target (!-) -- s -- ">]"
| e ->
let argSpacing =
if hasParenthesis e then
id
else
sepSpace
!- "[<" +> opt sepColon target (!-) -- s
+> argSpacing
+> genExpr astContext e
-- ">]"
and genAttributesCore astContext (ats: SynAttribute seq) =
let genAttributeExpr astContext (Attribute (s, e, target) as attr) =
match e with
| ConstUnitExpr -> opt sepColon target (!-) -- s
| e ->
let argSpacing =
if hasParenthesis e then
id
else
sepSpace
opt sepColon target (!-) -- s
+> argSpacing
+> genExpr astContext e
|> genTriviaFor SynAttribute_ attr.Range
let shortExpression =
!- "[<"
+> atCurrentColumn (col sepSemi ats (genAttributeExpr astContext))
-- ">]"
let longExpression =
!- "[<"
+> atCurrentColumn (col (sepSemi +> sepNln) ats (genAttributeExpr astContext))
-- ">]"
ifElse (Seq.isEmpty ats) sepNone (expressionFitsOnRestOfLine shortExpression longExpression)
and genOnelinerAttributes astContext ats =
let ats = List.collect (fun (a: SynAttributeList) -> a.Attributes) ats
ifElse (Seq.isEmpty ats) sepNone (genAttributesCore astContext 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 astContext (ats: SynAttributes) =
ats
|> List.fold
(fun acc a (ctx: Context) ->
let dontAddNewline =
TriviaHelpers.``has content after that ends with``
(fun t -> RangeHelpers.rangeEq t.Range a.Range)
(function
| Directive _
| Newline
| Comment (LineCommentOnSingleLine _) -> true
| _ -> false)
(Map.tryFindOrEmptyList SynAttributeList_ ctx.TriviaMainNodes)
let chain =
acc
+> (genAttributesCore astContext a.Attributes
|> genTriviaFor SynAttributeList_ a.Range)
+> ifElse dontAddNewline sepNone sepNln
chain ctx)
sepNone
and genPreXmlDoc (PreXmlDoc lines) ctx =
if ctx.Config.StrictMode then
colPost sepNln sepNln lines (sprintf "///%s" >> (!-)) ctx
else
ctx
and genExprSepEqPrependType (astContext: ASTContext) (e: SynExpr) =
match e with
| TypedExpr (Typed, e, t) ->
sepColon
+> genType astContext false t
+> sepEq
+> sepSpaceOrIndentAndNlnIfExpressionExceedsPageWidth (genExpr astContext e)
| _ ->
sepEq
+> sepSpaceOrIndentAndNlnIfExpressionExceedsPageWidth (genExpr astContext e)
and genTyparList astContext tps =
ifElse
(List.atMostOne tps)
(col wordOr tps (genTypar astContext))
(sepOpenT
+> col wordOr tps (genTypar astContext)
+> sepCloseT)
and genTypeAndParam astContext typeName (tds: SynTyparDecls option) tcs =
let types openSep tds tcs closeSep =
(!-openSep
+> coli sepComma tds (fun i -> genTyparDecl { astContext with IsFirstTypeParam = i = 0 })
+> colPre (!- " when ") wordAnd tcs (genTypeConstraint astContext)
-- closeSep)
match tds with
| None -> !-typeName
| Some (SynTyparDecls.PostfixList (tds, tcs, _range)) -> !-typeName +> types "<" tds tcs ">"
| Some (SynTyparDecls.PrefixList (tds, _range)) -> types "(" tds [] ")" -- " " -- typeName
| Some (SynTyparDecls.SinglePrefix (td, _range)) ->
genTyparDecl { astContext with IsFirstTypeParam = true } td
+> sepSpace
-- typeName
+> colPre (!- " when ") wordAnd tcs (genTypeConstraint astContext)
and genTypeParamPostfix astContext tds =
match tds with
| Some (SynTyparDecls.PostfixList (tds, tcs, _range)) ->
(!- "<"
+> coli sepComma tds (fun i -> genTyparDecl { astContext with IsFirstTypeParam = i = 0 })
+> colPre (!- " when ") wordAnd tcs (genTypeConstraint astContext)
-- ">")
| _ -> sepNone
and genLetBinding astContext pref b =
let genPref = !-pref
let isRecursiveLetOrUseFunction = (pref = "and ")
match b with
| LetBinding (ats, px, ao, isInline, isMutable, p, e, valInfo) ->
match e, p with
| TypedExpr (Typed, e, t), PatLongIdent (ao, s, ps, tpso) when (List.isNotEmpty ps) ->
genSynBindingFunctionWithReturnType
astContext
false
isRecursiveLetOrUseFunction
px
ats
b.AfterAttributesBeforeHeadPattern
genPref
ao
isInline
isMutable
s
p.Range
ps
tpso
t
valInfo
e
| e, PatLongIdent (ao, s, ps, tpso) when (List.isNotEmpty ps) ->
genSynBindingFunction
astContext
false
isRecursiveLetOrUseFunction
px
ats
b.AfterAttributesBeforeHeadPattern
genPref
ao
isInline
isMutable
s
p.Range
ps
tpso
e
| TypedExpr (Typed, e, t), pat ->
genSynBindingValue
astContext
isRecursiveLetOrUseFunction
px
ats
b.AfterAttributesBeforeHeadPattern
genPref
ao
isInline
isMutable
pat
(Some t)
e
| _, PatTuple _ ->
genLetBindingDestructedTuple astContext isRecursiveLetOrUseFunction px ats pref ao isInline isMutable p e
| _, pat ->
genSynBindingValue
astContext
isRecursiveLetOrUseFunction
px
ats
b.AfterAttributesBeforeHeadPattern
genPref
ao
isInline
isMutable
pat
None
e
| _ -> sepNone
| DoBinding (ats, px, e) ->
let prefix =
if pref.Contains("let") then
pref.Replace("let", "do")
else
"do "
genPreXmlDoc px +> genAttributes astContext ats
-- prefix
+> autoIndentAndNlnIfExpressionExceedsPageWidth (genExpr astContext e)
| b -> failwithf "%O isn't a let binding" b
+> leaveNodeFor (synBindingToFsAstType b) b.RangeOfBindingWithRhs
and genProperty astContext prefix ao propertyKind ps e =
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
!-prefix +> opt sepSpace ao genAccess
-- propertyKind
+> ifElse
(List.atMostOne ps)
(col sepComma ps (genPat astContext) +> sepSpace)
(sepOpenT
+> col sepComma ps (genPat astContext)
+> sepCloseT
+> sepSpace)
+> genPat astContext p
+> genExprSepEqPrependType astContext e
| ps ->
!-prefix +> opt sepSpace ao genAccess
-- propertyKind
+> col sepSpace ps (genPat astContext)
+> genExprSepEqPrependType astContext e
and genPropertyWithGetSet astContext (b1, b2) rangeOfMember =
match b1, b2 with
| PropertyBinding (ats, px, ao, isInline, mf1, PatLongIdent (ao1, s1, ps1, _), e1, _),
PropertyBinding (_, _, _, _, _, PatLongIdent (ao2, _, ps2, _), e2, _) ->
let prefix =
genPreXmlDoc px
+> genAttributes astContext ats
+> genMemberFlags astContext mf1
+> ifElse isInline (!- "inline ") sepNone
+> opt sepSpace ao genAccess
assert (ps1 |> Seq.map fst |> Seq.forall Option.isNone)
assert (ps2 |> Seq.map fst |> Seq.forall Option.isNone)
let ps1 = List.map snd ps1
let ps2 = List.map snd ps2
prefix
+> !-s1
+> indent
+> sepNln
+> optSingle (fun rom -> enterNodeTokenByName rom WITH) rangeOfMember
+> genProperty astContext "with " ao1 "get " ps1 e1
+> sepNln
+> genProperty astContext "and " ao2 "set " ps2 e2
+> unindent
| _ -> sepNone
and genMemberBindingList astContext node =
let rec collectItems
(node: SynBinding list)
(finalContinuation: ColMultilineItem list -> ColMultilineItem list)
: ColMultilineItem list =
match node with
| [] -> finalContinuation []
| mb :: rest ->
let expr = genMemberBinding astContext mb
let r = mb.RangeOfBindingWithRhs
let sepNln =
sepNlnConsideringTriviaContentBeforeForMainNode (synBindingToFsAstType mb) r
collectItems rest (fun restItems ->
ColMultilineItem(expr, sepNln) :: restItems
|> finalContinuation)
collectItems node id
|> colWithNlnWhenItemIsMultiline
and genMemberBinding astContext b =
match b with
| PropertyBinding (ats, px, ao, isInline, mf, p, e, synValInfo) ->
let prefix =
genPreXmlDoc px
+> genAttributes astContext ats
+> genMemberFlags astContext mf
+> ifElse isInline (!- "inline ") sepNone
+> opt sepSpace ao genAccess
let propertyKind =
match mf with
| MFProperty PropertyGet -> "get "
| MFProperty PropertySet -> "set "
| mf -> failwithf "Unexpected member flags: %O" mf
match p with
| PatLongIdent (ao, s, ps, _) ->
assert (ps |> Seq.map fst |> Seq.forall Option.isNone)
match ao, propertyKind, ps with
| None, "get ", [ _, PatParen (_, PatUnitConst, _) ] ->
// Provide short-hand notation `x.Member = ...` for `x.Member with get()` getters
let pat =
match p with
| SynPat.LongIdent (lid, extraId, typarDecls, _, accessibility, range) ->
SynPat.LongIdent(lid, extraId, typarDecls, SynArgPats.Pats([]), accessibility, range)
| _ -> p
let prefix =
(onlyIfNot mf.IsInstance (!- "static ")
+> !- "member ")
genMemberBindingImpl astContext prefix b ats px ao isInline pat e synValInfo
| _ ->
let ps = List.map snd ps
prefix -- s
+> indent
+> sepNln
+> genProperty astContext "with " ao propertyKind ps e
+> unindent
| p -> failwithf "Unexpected pattern: %O" p
| MemberBinding (ats, px, ao, isInline, mf, p, e, synValInfo) ->
let prefix = genMemberFlagsForMemberBinding astContext mf b.RangeOfBindingWithRhs
genMemberBindingImpl astContext prefix b ats px ao isInline p e synValInfo
| ExplicitCtor (ats, px, ao, p, e, so) ->
let prefix =
let genPat ctx =
match p with
| PatExplicitCtor (ao, pat) ->
(opt sepSpace ao genAccess
+> !- "new"
+> sepSpaceBeforeClassConstructor
+> genPat astContext pat)
ctx
| _ -> genPat astContext p ctx
genPreXmlDoc px
+> genAttributes astContext ats
+> opt sepSpace ao genAccess
+> genPat
+> opt sepNone so (sprintf " as %s" >> (!-))
match e with
// Handle special "then" block i.e. fake sequential expressions in constructors
| Sequential (e1, e2, false) ->
prefix
+> sepEq
+> indent
+> sepNln
+> genExpr astContext e1
++ "then "
+> autoIndentAndNlnIfExpressionExceedsPageWidth (genExpr astContext e2)
+> unindent
| e ->
prefix
+> sepEq
+> sepSpaceOrIndentAndNlnIfExpressionExceedsPageWidth (genExpr astContext e)
| b -> failwithf "%O isn't a member binding" b
|> genTriviaFor (synBindingToFsAstType b) b.RangeOfBindingWithRhs
and genMemberBindingImpl
(astContext: ASTContext)
(prefix: Context -> Context)
(b: SynBinding)
(ats: SynAttributes)
(px: PreXmlDoc)
(ao: SynAccess option)
(isInline: bool)
(p: SynPat)
(e: SynExpr)
(synValInfo: SynValInfo)
=
match e, p with
| TypedExpr (Typed, e, t), PatLongIdent (ao, s, ps, tpso) when (List.isNotEmpty ps) ->
genSynBindingFunctionWithReturnType
astContext
true
false
px
ats
b.AfterAttributesBeforeHeadPattern
prefix
ao
isInline
false
s
p.Range
ps
tpso
t
synValInfo
e
| e, PatLongIdent (ao, s, ps, tpso) when (List.isNotEmpty ps) ->
genSynBindingFunction
astContext
true
false
px
ats
b.AfterAttributesBeforeHeadPattern
prefix
ao
isInline
false
s
p.Range
ps
tpso
e
| TypedExpr (Typed, e, t), pat ->
genSynBindingValue
astContext
false
px
ats
b.AfterAttributesBeforeHeadPattern
prefix
ao
isInline
false
pat
(Some t)
e
| _, pat ->
genSynBindingValue
astContext
false
px
ats
b.AfterAttributesBeforeHeadPattern
prefix
ao
isInline
false
pat
None
e
and genMemberFlags astContext (mf: SynMemberFlags) =
match mf with
| MFMember _ -> !- "member "
| MFStaticMember _ -> !- "static member "
| MFConstructor _ -> sepNone
| MFOverride _ -> ifElse astContext.InterfaceRange.IsSome (!- "member ") (!- "override ")
and genMemberFlagsForMemberBinding astContext (mf: SynMemberFlags) (rangeOfBindingAndRhs: Range) =
fun ctx ->
// TODO: fix https://github.com/dotnet/fsharp/issues/11508 and get rid of this mess
let keywordFromTrivia =
[ yield! (Map.tryFindOrEmptyList SynMemberDefn_Member ctx.TriviaMainNodes)
yield! (Map.tryFindOrEmptyList SynMemberSig_Member ctx.TriviaMainNodes)
yield! (Map.tryFindOrEmptyList MEMBER ctx.TriviaTokenNodes) ]
|> List.tryFind (fun { Type = t; Range = r } ->
match t with
| MainNode SynMemberDefn_Member
| MainNode SynMemberSig_Member -> // trying to get AST trivia
RangeHelpers.``range contains`` r rangeOfBindingAndRhs
| Token (MEMBER, _) -> // trying to get token trivia
r.StartLine = rangeOfBindingAndRhs.StartLine
// In case the member has attributes
|| RangeHelpers.``range contains`` rangeOfBindingAndRhs r
| _ -> false)
|> Option.bind (fun tn ->
tn.ContentItself
|> Option.bind (fun tc ->
match tc with
| Keyword { Content = "override" | "default" | "member" | "abstract" | "abstract member" as kw } ->
Some(!-(kw + " "))
| _ -> None))
match mf with
| MFStaticMember _
| MFConstructor _ -> genMemberFlags astContext mf
| MFMember _ ->
keywordFromTrivia
|> Option.defaultValue (genMemberFlags astContext mf)
| MFOverride _ ->
keywordFromTrivia
|> Option.defaultValue (!- "override ")
<| ctx
and genVal astContext (Val (ats, px, ao, s, identRange, t, vi, isInline, isMutable, tds, eo, range)) =
let typeName = genTypeAndParam astContext s tds []
let (FunType namedArgs) = (t, vi)
let hasGenerics = Option.isSome tds
genPreXmlDoc px
+> genAttributes astContext ats
+> (!- "val "
+> onlyIf isInline (!- "inline ")
+> onlyIf isMutable (!- "mutable ")
+> opt sepSpace ao genAccess
+> typeName
|> genTriviaFor Ident_ identRange)
+> ifElse hasGenerics sepColonWithSpacesFixed sepColon
+> ifElse
(List.isNotEmpty namedArgs)
(autoIndentAndNlnIfExpressionExceedsPageWidth (genTypeList astContext namedArgs))
(genConstraints astContext t vi)
+> optSingle (fun e -> sepEq +> sepSpace +> genExpr astContext e) eo
|> genTriviaFor SynValSig_ range
and genRecordFieldName astContext (RecordFieldName (s, eo) as node) =
let rfn, _, _ = node
let range = (fst rfn).Range
opt sepNone eo (fun e ->
let expr = sepSpaceOrIndentAndNlnIfExpressionExceedsPageWidth (genExpr astContext e)
!-s +> sepEq +> expr)
|> genTriviaFor RecordField_ range
and genAnonRecordFieldName astContext (AnonRecordFieldName (s, e)) =
let expr = sepSpaceOrIndentAndNlnIfExpressionExceedsPageWidth (genExpr astContext e)
!-s +> sepEq +> expr
and genTuple astContext es =
let genShortExpr astContext e =
addParenForTupleWhen (genExpr astContext) e
let shortExpression = col sepComma es (genShortExpr astContext)
let longExpression =
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
(sepComma +> sepNln)
let lastIndex = List.length es - 1
let genExpr astContext idx e =
match e with
| SynExpr.IfThenElse _ when (idx < lastIndex) ->
autoParenthesisIfExpressionExceedsPageWidth (genExpr astContext e)