-
-
Notifications
You must be signed in to change notification settings - Fork 193
/
ASTTransformer.fs
3569 lines (3135 loc) · 145 KB
/
ASTTransformer.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 rec Fantomas.Core.ASTTransformer
open System.Collections.Generic
open System.Text.RegularExpressions
open Fantomas.FCS.Text
open Fantomas.FCS.Text.Range
open Fantomas.FCS.Syntax
open Fantomas.FCS.SyntaxTrivia
open Fantomas.FCS.Xml
open Fantomas.Core.ISourceTextExtensions
open Fantomas.Core.RangePatterns
open Fantomas.Core.SyntaxOak
open Microsoft.FSharp.Core
type CreationAide =
{ SourceText: ISourceText option }
member x.TextFromSource fallback range =
match x.SourceText with
| None -> fallback ()
| Some sourceText -> sourceText.GetContentAt range
let stn text range = SingleTextNode(text, range)
let mkIdent (ident: Ident) =
let width = ident.idRange.EndColumn - ident.idRange.StartColumn
let text =
if ident.idText.Length + 4 = width then
// add backticks
$"``{ident.idText}``"
else
ident.idText
stn text ident.idRange
let mkSynIdent (SynIdent(ident, trivia)) =
match trivia with
| None -> mkIdent ident
| Some(IdentTrivia.OriginalNotation text) -> stn text ident.idRange
| Some(IdentTrivia.OriginalNotationWithParen(_, text, _)) -> stn $"({text})" ident.idRange
| Some(IdentTrivia.HasParenthesis _) -> stn $"({ident.idText})" ident.idRange
let mkSynLongIdent (sli: SynLongIdent) =
match sli.IdentsWithTrivia with
| [] -> IdentListNode.Empty
| [ single ] -> IdentListNode([ IdentifierOrDot.Ident(mkSynIdent single) ], sli.Range)
| head :: tail ->
assert (tail.Length = sli.Dots.Length)
let rest =
(sli.Dots, tail)
||> List.zip
|> List.collect (fun (dot, ident) ->
[ IdentifierOrDot.KnownDot(stn "." dot)
IdentifierOrDot.Ident(mkSynIdent ident) ])
IdentListNode(IdentifierOrDot.Ident(mkSynIdent head) :: rest, sli.Range)
let mkLongIdent (longIdent: LongIdent) : IdentListNode =
match longIdent with
| [] -> IdentListNode.Empty
| [ single ] -> IdentListNode([ IdentifierOrDot.Ident(mkIdent single) ], single.idRange)
| head :: tail ->
let rest =
tail
|> List.collect (fun ident -> [ IdentifierOrDot.UnknownDot; IdentifierOrDot.Ident(mkIdent ident) ])
let range =
longIdent |> List.map (fun ident -> ident.idRange) |> List.reduce unionRanges
IdentListNode(IdentifierOrDot.Ident(stn head.idText head.idRange) :: rest, range)
let mkSynAccess (vis: SynAccess option) =
match vis with
| None -> None
| Some(SynAccess.Internal range) -> Some(stn "internal" range)
| Some(SynAccess.Private range) -> Some(stn "private" range)
| Some(SynAccess.Public range) -> Some(stn "public" range)
let parseExpressionInSynBinding returnInfo expr =
match returnInfo, expr with
| Some(SynBindingReturnInfo(typeName = t1)), SynExpr.Typed(e, t2, _) when RangeHelpers.rangeEq t1.Range t2.Range ->
e
| _ -> expr
let mkConstString (creationAide: CreationAide) (stringKind: SynStringKind) (value: string) (range: range) =
let escaped = Regex.Replace(value, "\"{1}", "\\\"")
let fallback () =
match stringKind with
| SynStringKind.Regular -> sprintf "\"%s\"" escaped
| SynStringKind.Verbatim -> sprintf "@\"%s\"" escaped
| SynStringKind.TripleQuote -> sprintf "\"\"\"%s\"\"\"" escaped
stn (creationAide.TextFromSource fallback range) range
let mkParsedHashDirective (creationAide: CreationAide) (ParsedHashDirective(ident, args, range)) =
let args =
args
|> List.map (function
| ParsedHashDirectiveArgument.String(value, stringKind, range) ->
mkConstString creationAide stringKind value range
| ParsedHashDirectiveArgument.SourceIdentifier(identifier, _, range) -> stn identifier range)
ParsedHashDirectiveNode(ident, args, range)
let mkConstant (creationAide: CreationAide) c r : Constant =
let orElse fallback =
stn (creationAide.TextFromSource (fun () -> fallback) r) r |> Constant.FromText
match c with
| SynConst.Unit -> mkUnit r |> Constant.Unit
| SynConst.Bool b -> stn (if b then "true" else "false") r |> Constant.FromText
| SynConst.Byte v -> orElse $"%A{v}"
| SynConst.SByte v -> orElse $"%A{v}"
| SynConst.Int16 v -> orElse $"%A{v}"
| SynConst.Int32 v -> orElse $"%A{v}"
| SynConst.Int64 v -> orElse $"%A{v}"
| SynConst.UInt16 v -> orElse $"%A{v}"
| SynConst.UInt16s v -> orElse $"%A{v}"
| SynConst.UInt32 v -> orElse $"%A{v}"
| SynConst.UInt64 v -> orElse $"%A{v}"
| SynConst.Double v -> orElse $"%A{v}"
| SynConst.Single v -> orElse $"%A{v}"
| SynConst.Decimal v -> orElse $"%A{v}"
| SynConst.IntPtr v -> orElse $"%A{v}"
| SynConst.UIntPtr v -> orElse $"%A{v}"
| SynConst.UserNum(v, s) ->
let fallback () = $"%s{v}%s{s}"
stn (creationAide.TextFromSource fallback r) r |> Constant.FromText
| SynConst.String(value, stringKind, r) -> mkConstString creationAide stringKind value r |> Constant.FromText
| SynConst.Char c ->
let escapedChar =
match c with
| '\r' -> @"'\r'"
| '\n' -> @"'\n'"
| '\t' -> @"'\t'"
| '\\' -> @"'\\'"
| '\b' -> @"'\b'"
| '\f' -> @"'\f'"
| _ -> c.ToString()
orElse escapedChar
| SynConst.Bytes(bytes, _, r) ->
let fallback () =
let content =
System.String(Array.map (fun (byte: byte) -> System.Convert.ToChar(byte)) bytes)
$"\"{content}\"B"
stn (creationAide.TextFromSource fallback r) r |> Constant.FromText
| SynConst.Measure(c, numberRange, measure, trivia) ->
let uOfMRange =
mkRange trivia.LessRange.FileName trivia.LessRange.Start trivia.GreaterRange.End
let unitOfMeasure =
UnitOfMeasureNode(
stn "<" trivia.LessRange,
mkMeasure creationAide measure,
stn ">" trivia.GreaterRange,
uOfMRange
)
ConstantMeasureNode(mkConstant creationAide c numberRange, unitOfMeasure, r)
|> Constant.Measure
| SynConst.SourceIdentifier(c, _, r) -> stn c r |> Constant.FromText
let mkMeasure (creationAide: CreationAide) (measure: SynMeasure) : Measure =
match measure with
| SynMeasure.Var(typar, _) -> mkSynTypar typar |> Measure.Single
| SynMeasure.Anon m -> stn "_" m |> Measure.Single
| SynMeasure.One m -> stn "1" m |> Measure.Single
| SynMeasure.Product(m1, mAsterisk, m2, m) ->
MeasureOperatorNode(mkMeasure creationAide m1, stn "*" mAsterisk, mkMeasure creationAide m2, m)
|> Measure.Operator
| SynMeasure.Divide(m1, mSlash, m2, m) ->
let lhs = m1 |> Option.map (mkMeasure creationAide)
MeasureDivideNode(lhs, stn "/" mSlash, mkMeasure creationAide m2, m)
|> Measure.Divide
| SynMeasure.Power(ms, mCaret, rat, m) ->
MeasurePowerNode(mkMeasure creationAide ms, stn "^" mCaret, mkSynRationalConst creationAide rat, m)
|> Measure.Power
| SynMeasure.Named(lid, _) -> mkLongIdent lid |> Measure.Multiple
| SynMeasure.Paren(measure, StartEndRange 1 (mOpen, m, mClose)) ->
MeasureParenNode(stn "(" mOpen, mkMeasure creationAide measure, stn ")" mClose, m)
|> Measure.Paren
| SynMeasure.Seq(ms, m) -> MeasureSequenceNode(List.map (mkMeasure creationAide) ms, m) |> Measure.Seq
let mkAttribute (creationAide: CreationAide) (a: SynAttribute) =
let expr =
match a.ArgExpr with
| UnitExpr _ -> None
| e -> mkExpr creationAide e |> Some
AttributeNode(mkSynLongIdent a.TypeName, expr, Option.map mkIdent a.Target, a.Range)
let mkAttributeList (creationAide: CreationAide) (al: SynAttributeList) : AttributeListNode =
let attributes = List.map (mkAttribute creationAide) al.Attributes
let opening, closing =
match al.Range with
| StartEndRange 2 (s, _, e) -> stn "[<" s, stn ">]" e
AttributeListNode(opening, attributes, closing, al.Range)
let mkAttributes (creationAide: CreationAide) (al: SynAttributeList list) : MultipleAttributeListNode option =
match al with
| [] -> None
| _ ->
let attributeLists = List.map (mkAttributeList creationAide) al
let range = attributeLists |> List.map (fun al -> al.Range) |> combineRanges
Some(MultipleAttributeListNode(attributeLists, range))
let (|Sequentials|_|) e =
let rec visit (e: SynExpr) (finalContinuation: SynExpr list -> SynExpr list) : SynExpr list =
match e with
| SynExpr.Sequential(_, _, e1, e2, _) -> visit e2 (fun xs -> e1 :: xs |> finalContinuation)
| e -> finalContinuation [ e ]
match e with
| SynExpr.Sequential(_, _, e1, e2, _) ->
let xs = visit e2 id
Some(e1 :: xs)
| _ -> None
let mkOpenAndCloseForArrayOrList isArray range =
if isArray then
let (StartEndRange 2 (mO, _, mC)) = range
stn "[|" mO, stn "|]" mC
else
let (StartEndRange 1 (mO, _, mC)) = range
stn "[" mO, stn "]" mC
let mkInheritConstructor (creationAide: CreationAide) (t: SynType) (e: SynExpr) (mInherit: range) (m: range) =
let inheritNode = stn "inherit" mInherit
let m = unionRanges mInherit m
match e with
| SynExpr.Const(constant = SynConst.Unit; range = StartEndRange 1 (mOpen, unitRange, mClose)) ->
// The unit expression could have been added artificially.
if unitRange.StartColumn + 2 = unitRange.EndColumn then
InheritConstructorUnitNode(inheritNode, mkType creationAide t, stn "(" mOpen, stn ")" mClose, m)
|> InheritConstructor.Unit
else
InheritConstructorTypeOnlyNode(inheritNode, mkType creationAide t, m)
|> InheritConstructor.TypeOnly
| SynExpr.Paren _ as px ->
InheritConstructorParenNode(inheritNode, mkType creationAide t, mkExpr creationAide px, m)
|> InheritConstructor.Paren
| _ ->
InheritConstructorOtherNode(inheritNode, mkType creationAide t, mkExpr creationAide e, m)
|> InheritConstructor.Other
let mkTuple (creationAide: CreationAide) (exprs: SynExpr list) (commas: range list) (m: range) =
match exprs with
| [] -> failwith "SynExpr.Tuple with no elements"
| head :: tail ->
let rest =
assert (tail.Length = commas.Length)
List.zip commas tail
|> List.collect (fun (c, e) -> [ yield Choice2Of2(stn "," c); yield Choice1Of2(mkExpr creationAide e) ])
ExprTupleNode([ yield Choice1Of2(mkExpr creationAide head); yield! rest ], m)
/// Unfold a list of let bindings
/// Recursive and use properties have to be determined at this point
let rec (|LetOrUses|_|) =
function
| SynExpr.LetOrUse(_, _, xs, LetOrUses(ys, e), _, trivia) ->
let xs' = List.mapWithLast (fun b -> b, None) (fun b -> b, trivia.InKeyword) xs
Some(xs' @ ys, e)
| SynExpr.LetOrUse(_, _, xs, e, _, trivia) ->
let xs' = List.mapWithLast (fun b -> b, None) (fun b -> b, trivia.InKeyword) xs
Some(xs', e)
| _ -> None
let rec collectComputationExpressionStatements
(creationAide: CreationAide)
(e: SynExpr)
(finalContinuation: ComputationExpressionStatement list -> ComputationExpressionStatement list)
: ComputationExpressionStatement list =
match e with
| LetOrUses(bindings, body) ->
let bindings =
bindings
|> List.map (fun (b, inNode) ->
let b: BindingNode = mkBinding creationAide b
let inNode, m =
match inNode with
| None -> None, b.Range
| Some mIn -> Some(stn "in" mIn), unionRanges b.Range mIn
ExprLetOrUseNode(b, inNode, m)
|> ComputationExpressionStatement.LetOrUseStatement)
collectComputationExpressionStatements creationAide body (fun bodyStatements ->
[ yield! bindings; yield! bodyStatements ] |> finalContinuation)
| SynExpr.LetOrUseBang(_,
isUse,
_,
pat,
expr,
andBangs,
body,
StartRange 4 (mLeading, _m),
{ EqualsRange = Some mEq }) ->
let letOrUseBang =
ExprLetOrUseBangNode(
stn (if isUse then "use!" else "let!") mLeading,
mkPat creationAide pat,
stn "=" mEq,
mkExpr creationAide expr,
unionRanges mLeading expr.Range
)
|> ComputationExpressionStatement.LetOrUseBangStatement
let andBangs =
andBangs
|> List.map (fun (SynExprAndBang(_, _, _, ap, ae, StartRange 4 (mAnd, m), trivia)) ->
ExprAndBang(
stn "and!" mAnd,
mkPat creationAide ap,
stn "=" trivia.EqualsRange,
mkExpr creationAide ae,
m
)
|> ComputationExpressionStatement.AndBangStatement)
collectComputationExpressionStatements creationAide body (fun bodyStatements ->
[ letOrUseBang; yield! andBangs; yield! bodyStatements ] |> finalContinuation)
| SynExpr.Sequential(_, _, e1, e2, _) ->
let continuations
: ((ComputationExpressionStatement list -> ComputationExpressionStatement list)
-> ComputationExpressionStatement list) list =
[ collectComputationExpressionStatements creationAide e1
collectComputationExpressionStatements creationAide e2 ]
let finalContinuation (nodes: ComputationExpressionStatement list list) : ComputationExpressionStatement list =
List.collect id nodes |> finalContinuation
Continuation.sequence continuations finalContinuation
| expr -> finalContinuation [ ComputationExpressionStatement.OtherStatement(mkExpr creationAide expr) ]
/// Process compiler-generated matches in an appropriate way
let rec private skipGeneratedLambdas expr =
match expr with
| SynExpr.Lambda(inLambdaSeq = true; body = bodyExpr) -> skipGeneratedLambdas bodyExpr
| _ -> expr
and skipGeneratedMatch expr =
match expr with
| SynExpr.Match(_, _, [ SynMatchClause.SynMatchClause(resultExpr = innerExpr) as clause ], matchRange, _) when
matchRange.Start = clause.Range.Start
->
skipGeneratedMatch innerExpr
| _ -> expr
let inline private getLambdaBodyExpr expr =
let skippedLambdas = skipGeneratedLambdas expr
skipGeneratedMatch skippedLambdas
let mkLambda creationAide pats mArrow body (StartRange 3 (mFun, m)) : ExprLambdaNode =
let body = getLambdaBodyExpr body
ExprLambdaNode(stn "fun" mFun, List.map (mkPat creationAide) pats, stn "->" mArrow, mkExpr creationAide body, m)
let mkSynMatchClause creationAide (SynMatchClause(p, eo, e, range, _, trivia)) : MatchClauseNode =
let fullRange =
match trivia.BarRange with
| None -> range
| Some barRange -> unionRanges barRange range
MatchClauseNode(
Option.map (stn "|") trivia.BarRange,
mkPat creationAide p,
Option.map (mkExpr creationAide) eo,
stn "->" trivia.ArrowRange.Value,
mkExpr creationAide e,
fullRange
)
let (|ColonColonInfixApp|_|) =
function
| SynExpr.App(
isInfix = true
funcExpr = SynExpr.LongIdent(
longDotId = SynLongIdent([ operatorIdent ], [], [ Some(IdentTrivia.OriginalNotation "::") ]))
argExpr = SynExpr.Tuple(exprs = [ e1; e2 ])) -> Some(e1, stn "::" operatorIdent.idRange, e2)
| _ -> None
let (|InfixApp|_|) synExpr =
match synExpr with
| ColonColonInfixApp(lhs, operator, rhs) -> Some(lhs, operator, rhs)
| SynExpr.App(
funcExpr = SynExpr.App(
isInfix = true
funcExpr = SynExpr.LongIdent(
longDotId = SynLongIdent([ operatorIdent ], [], [ Some(IdentTrivia.OriginalNotation operator) ]))
argExpr = e1)
argExpr = e2) -> Some(e1, stn operator operatorIdent.idRange, e2)
| _ -> None
let (|IndexWithoutDot|_|) expr =
match expr with
| SynExpr.App(ExprAtomicFlag.Atomic, false, identifierExpr, SynExpr.ArrayOrListComputed(false, indexExpr, _), _) ->
Some(identifierExpr, indexExpr)
| SynExpr.App(ExprAtomicFlag.NonAtomic,
false,
identifierExpr,
(SynExpr.ArrayOrListComputed(isArray = false; expr = indexExpr) as argExpr),
_) when (RangeHelpers.isAdjacentTo identifierExpr.Range argExpr.Range) ->
Some(identifierExpr, indexExpr)
| _ -> None
let (|MultipleConsInfixApps|_|) expr =
let rec visit expr (headAndLastOperator: (SynExpr * SingleTextNode) option) (xs: Queue<SingleTextNode * SynExpr>) =
match expr with
| ColonColonInfixApp(lhs, operator, rhs) ->
match headAndLastOperator with
| None -> visit rhs (Some(lhs, operator)) xs
| Some(head, lastOperator) ->
xs.Enqueue(lastOperator, lhs)
visit rhs (Some(head, operator)) xs
| e ->
match headAndLastOperator with
| None -> e, xs
| Some(head, lastOperator) ->
xs.Enqueue(lastOperator, e)
head, xs
match expr with
| ColonColonInfixApp _ ->
let head, xs = visit expr None (Queue())
if xs.Count < 2 then None else Some(head, Seq.toList xs)
| _ -> None
let rightOperators = set [| "@"; "**"; "^"; ":=" |]
let (|SameInfixApps|_|) expr =
let rec visitLeft sameOperator expr continuation =
match expr with
| InfixApp(lhs, operator, rhs) when operator.Text = sameOperator ->
visitLeft sameOperator lhs (fun (head, xs: Queue<SingleTextNode * SynExpr>) ->
xs.Enqueue(operator, rhs)
continuation (head, xs))
| e -> continuation (e, Queue())
let rec visitRight
(sameOperator: string)
(expr: SynExpr)
(headAndLastOperator: (SynExpr * SingleTextNode) option)
(xs: Queue<SingleTextNode * SynExpr>)
: SynExpr * Queue<SingleTextNode * SynExpr> =
match expr with
| SynExpr.App(ExprAtomicFlag.NonAtomic,
false,
SynExpr.App(
isInfix = true
funcExpr = SynExpr.LongIdent(
longDotId = SynLongIdent(
id = [ operatorIdent ]; trivia = [ Some(IdentTrivia.OriginalNotation lhsOperator) ]))
argExpr = leftExpr),
rhs,
_) when (lhsOperator = sameOperator) ->
let operator = stn lhsOperator operatorIdent.idRange
match headAndLastOperator with
| None ->
// Start of the infix chain, the leftExpr is the utmost left
visitRight sameOperator rhs (Some(leftExpr, operator)) xs
| Some(head, lastOperator) ->
// Continue collecting
xs.Enqueue(lastOperator, leftExpr)
visitRight sameOperator rhs (Some(head, operator)) xs
| e ->
match headAndLastOperator with
| None -> e, xs
| Some(head, lastOperator) ->
xs.Enqueue(lastOperator, e)
head, xs
match expr with
| InfixApp(_, operator, _) ->
let isRight =
Set.exists (fun (rOp: string) -> operator.Text.StartsWith(rOp)) rightOperators
let head, xs =
if isRight then
visitRight operator.Text expr None (Queue())
else
visitLeft operator.Text expr id
if xs.Count < 2 then None else Some(head, Seq.toList xs)
| _ -> None
let newLineInfixOps = set [ "|>"; "||>"; "|||>"; ">>"; ">>=" ]
let (|NewlineInfixApps|_|) expr =
let rec visit expr continuation =
match expr with
| InfixApp(lhs, operator, rhs) when newLineInfixOps.Contains operator.Text ->
visit lhs (fun (head, xs: Queue<SingleTextNode * SynExpr>) ->
xs.Enqueue(operator, rhs)
continuation (head, xs))
| e -> continuation (e, Queue())
match expr with
| InfixApp _ ->
let head, xs = visit expr id
if xs.Count < 2 then None else Some(head, Seq.toList xs)
| _ -> None
let rec (|ElIf|_|) =
function
| SynExpr.IfThenElse(e1,
e2,
Some(ElIf((elifNode: Choice<SingleTextNode, range * range>, eshE1, eshThenKw, eshE2) :: es,
elseInfo)),
_,
_,
_,
trivia) ->
let ifNode =
stn (if trivia.IsElif then "elif" else "if") trivia.IfKeyword |> Choice1Of2
let elifNode =
match trivia.ElseKeyword with
| None -> elifNode
| Some mElse ->
match elifNode with
| Choice1Of2 ifNode -> Choice2Of2(mElse, ifNode.Range)
| Choice2Of2 _ -> failwith "Cannot merge a second else keyword into existing else if"
Some(
(ifNode, e1, stn "then" trivia.ThenKeyword, e2)
:: (elifNode, eshE1, eshThenKw, eshE2)
:: es,
elseInfo
)
| SynExpr.IfThenElse(e1, e2, e3, _, _, _, trivia) ->
let elseInfo =
match trivia.ElseKeyword, e3 with
| Some elseKw, Some elseExpr -> Some(stn "else" elseKw, elseExpr)
| _ -> None
let ifNode =
stn (if trivia.IsElif then "elif" else "if") trivia.IfKeyword |> Choice1Of2
Some([ (ifNode, e1, stn "then" trivia.ThenKeyword, e2) ], elseInfo)
| _ -> None
let (|ConstNumberExpr|_|) =
function
| SynExpr.Const(SynConst.Double v, m) -> Some(string v, m)
| SynExpr.Const(SynConst.Decimal v, m) -> Some(string v, m)
| SynExpr.Const(SynConst.Single v, m) -> Some(string v, m)
| SynExpr.Const(SynConst.Int16 v, m) -> Some(string v, m)
| SynExpr.Const(SynConst.Int32 v, m) -> Some(string v, m)
| SynExpr.Const(SynConst.Int64 v, m) -> Some(string v, m)
| _ -> None
let (|App|_|) e =
let rec visit expr continuation =
match expr with
| SynExpr.App(funcExpr = funcExpr; argExpr = argExpr) ->
visit funcExpr (fun (head, xs: Queue<SynExpr>) ->
xs.Enqueue(argExpr)
continuation (head, xs))
| e -> continuation (e, Queue())
let head, xs = visit e id
if xs.Count = 0 then None else Some(head, Seq.toList xs)
let (|ParenLambda|_|) e =
match e with
| ParenExpr(lpr, SynExpr.Lambda(_, _, _, _, Some(pats, body), mLambda, { ArrowRange = Some mArrow }), rpr, _) ->
Some(lpr, pats, mArrow, body, mLambda, rpr)
| _ -> None
let (|ParenMatchLambda|_|) e =
match e with
| ParenExpr(lpr, SynExpr.MatchLambda(_, mFunction, clauses, _, mMatchLambda), rpr, _) ->
Some(lpr, mFunction, clauses, mMatchLambda, rpr)
| _ -> None
let mkMatchLambda creationAide mFunction cs m =
ExprMatchLambdaNode(stn "function" mFunction, List.map (mkSynMatchClause creationAide) cs, m)
[<RequireQualifiedAccess>]
type LinkExpr =
| Identifier of
// Could be SynExpr.LongIdent or SynExpr.TypeApp(LongIdent)
SynExpr
| Dot of range
| Expr of SynExpr
| AppParenLambda of functionName: SynExpr * parenLambda: SynExpr
| AppParen of functionName: SynExpr * lpr: range * e: SynExpr * rpr: range * pr: range
| AppUnit of functionName: SynExpr * unit: range
| IndexExpr of indexExpr: SynExpr
let mkLinksFromSynLongIdent (sli: SynLongIdent) : LinkExpr list =
let idents =
List.map (mkLongIdentExprFromSynIdent >> LinkExpr.Identifier) sli.IdentsWithTrivia
let dots = List.map LinkExpr.Dot sli.Dots
[ yield! idents; yield! dots ]
|> List.sortBy (function
| LinkExpr.Identifier identifierExpr -> identifierExpr.Range.StartLine, identifierExpr.Range.StartColumn
| LinkExpr.Dot m -> m.StartLine, m.StartColumn
| LinkExpr.Expr _
| LinkExpr.AppParenLambda _
| LinkExpr.AppParen _
| LinkExpr.AppUnit _
| LinkExpr.IndexExpr _ -> -1, -1)
let (|UnitExpr|_|) e =
match e with
| SynExpr.Const(constant = SynConst.Unit) -> Some e.Range
| _ -> None
let (|ParenExpr|_|) e =
match e with
| SynExpr.Paren(e, lpr, Some rpr, pr) -> Some(lpr, e, rpr, pr)
| _ -> None
let mkLongIdentExprFromSynIdent (SynIdent(ident, identTrivia)) =
SynExpr.LongIdent(false, SynLongIdent([ ident ], [], [ identTrivia ]), None, ident.idRange)
let mkLinksFromFunctionName (mkLinkFromExpr: SynExpr -> LinkExpr) (functionName: SynExpr) : LinkExpr list =
match functionName with
| SynExpr.TypeApp(SynExpr.LongIdent(longDotId = sli),
lessRange,
typeArgs,
commaRanges,
Some greaterRange,
typeArgsRange,
_) ->
match sli.IdentsWithTrivia with
| []
| [ _ ] -> [ mkLinkFromExpr functionName ]
| synIdents ->
let leftLinks = mkLinksFromSynLongIdent sli
let lastSynIdent = List.last synIdents
let m =
let (SynIdent(ident, _)) = lastSynIdent
unionRanges ident.idRange greaterRange
let typeAppExpr =
SynExpr.TypeApp(
mkLongIdentExprFromSynIdent lastSynIdent,
lessRange,
typeArgs,
commaRanges,
Some greaterRange,
typeArgsRange,
m
)
[ yield! List.cutOffLast leftLinks; yield mkLinkFromExpr typeAppExpr ]
| SynExpr.LongIdent(longDotId = sli) ->
match sli.IdentsWithTrivia with
| []
| [ _ ] -> [ mkLinkFromExpr functionName ]
| synIdents ->
let leftLinks = mkLinksFromSynLongIdent sli
let lastSynIdent = List.last synIdents
[ yield! List.cutOffLast leftLinks
yield (mkLongIdentExprFromSynIdent lastSynIdent |> mkLinkFromExpr) ]
| e -> [ mkLinkFromExpr e ]
let (|ChainExpr|_|) (e: SynExpr) : LinkExpr list option =
let rec visit (e: SynExpr) (continuation: LinkExpr list -> LinkExpr list) =
match e with
| SynExpr.App(
isInfix = false
funcExpr = SynExpr.TypeApp(SynExpr.DotGet _ as funcExpr,
lessRange,
typeArgs,
commaRanges,
Some greaterRange,
typeArgsRange,
_)
argExpr = ParenExpr _ | UnitExpr _ as argExpr) ->
visit funcExpr (fun leftLinks ->
let lastLink =
match List.tryLast leftLinks with
| Some(LinkExpr.Identifier identifierExpr) ->
let typeApp =
SynExpr.TypeApp(
identifierExpr,
lessRange,
typeArgs,
commaRanges,
Some greaterRange,
typeArgsRange,
unionRanges identifierExpr.Range greaterRange
)
match argExpr with
| UnitExpr mUnit -> [ LinkExpr.AppUnit(typeApp, mUnit) ]
| ParenExpr(lpr, innerExpr, rpr, pr) -> [ LinkExpr.AppParen(typeApp, lpr, innerExpr, rpr, pr) ]
| _ -> []
| _ -> []
let leftLinks = List.cutOffLast leftLinks
continuation [ yield! leftLinks; yield! lastLink ])
| SynExpr.TypeApp(SynExpr.DotGet _ as dotGet,
lessRange,
typeArgs,
commaRanges,
Some greaterRange,
typeArgsRange,
_) ->
visit dotGet (fun leftLinks ->
let lastLink =
match List.tryLast leftLinks with
| Some(LinkExpr.Identifier property) ->
[ SynExpr.TypeApp(
property,
lessRange,
typeArgs,
commaRanges,
Some greaterRange,
typeArgsRange,
unionRanges property.Range greaterRange
)
|> LinkExpr.Identifier ]
| _ -> []
let leftLinks = List.cutOffLast leftLinks
continuation [ yield! leftLinks; yield! lastLink ])
// Transform `x().y[0]` into `x()` , `dot`, `y[0]`
| IndexWithoutDot(SynExpr.DotGet(expr, mDot, sli, _), indexExpr) ->
visit expr (fun leftLinks ->
let middleLinks, lastExpr =
match List.tryLast sli.IdentsWithTrivia with
| None -> [], indexExpr
| Some lastMiddleLink ->
let middleLinks = mkLinksFromSynLongIdent sli |> List.cutOffLast
let indexWithDotExpr =
let identifierExpr = mkLongIdentExprFromSynIdent lastMiddleLink
// Create an adjacent range for the `[`,`]` in the index expression.
let adjacentRange =
mkRange
indexExpr.Range.FileName
(Position.mkPos
identifierExpr.Range.StartLine
(identifierExpr.Range.StartColumn + 1))
(Position.mkPos indexExpr.Range.EndLine (indexExpr.Range.EndColumn - 1))
SynExpr.App(
ExprAtomicFlag.Atomic,
false,
identifierExpr,
SynExpr.ArrayOrListComputed(false, indexExpr, adjacentRange),
unionRanges identifierExpr.Range indexExpr.Range
)
middleLinks, indexWithDotExpr
continuation
[ yield! leftLinks
yield LinkExpr.Dot mDot
yield! middleLinks
yield LinkExpr.Expr lastExpr ])
| SynExpr.App(isInfix = false; funcExpr = SynExpr.DotGet _ as funcExpr; argExpr = argExpr) ->
visit funcExpr (fun leftLinks ->
match List.tryLast leftLinks with
| Some(LinkExpr.Identifier(identifierExpr)) ->
match argExpr with
| UnitExpr mUnit ->
let leftLinks = List.cutOffLast leftLinks
// Compose a function application by taking the last identifier of the SynExpr.DotGet
// and the following argument expression.
// Example: X().Y() -> Take `Y` as function name and `()` as argument.
let rightLink = LinkExpr.AppUnit(identifierExpr, mUnit)
continuation [ yield! leftLinks; yield rightLink ]
| ParenExpr(lpr, e, rpr, pr) ->
let leftLinks = List.cutOffLast leftLinks
// Example: A().B(fun b -> b)
let rightLink = LinkExpr.AppParen(identifierExpr, lpr, e, rpr, pr)
continuation [ yield! leftLinks; yield rightLink ]
| _ -> visit argExpr (fun rightLinks -> continuation [ yield! leftLinks; yield! rightLinks ])
| _ -> visit argExpr (fun rightLinks -> continuation [ yield! leftLinks; yield! rightLinks ]))
| SynExpr.DotGet(expr, rangeOfDot, longDotId, _) ->
visit expr (fun links ->
continuation
[ yield! links
yield LinkExpr.Dot rangeOfDot
yield! mkLinksFromSynLongIdent longDotId ])
| SynExpr.App(isInfix = false; funcExpr = funcExpr; argExpr = UnitExpr mUnit) ->
mkLinksFromFunctionName (fun e -> LinkExpr.AppUnit(e, mUnit)) funcExpr
|> continuation
| SynExpr.App(isInfix = false; funcExpr = funcExpr; argExpr = ParenExpr(lpr, e, rpr, pr)) ->
mkLinksFromFunctionName (fun f -> LinkExpr.AppParen(f, lpr, e, rpr, pr)) funcExpr
|> continuation
| SynExpr.App(ExprAtomicFlag.Atomic,
false,
(SynExpr.LongIdent _ as funcExpr),
(SynExpr.ArrayOrList _ as argExpr),
_) ->
visit funcExpr (fun leftLinks ->
let app =
match List.tryLast leftLinks with
| Some(LinkExpr.Identifier identifier) ->
[ SynExpr.App(
ExprAtomicFlag.Atomic,
false,
identifier,
argExpr,
unionRanges identifier.Range argExpr.Range
)
|> LinkExpr.Expr ]
| _ -> []
let leftLinks = List.cutOffLast leftLinks
continuation [ yield! leftLinks; yield! app ])
| SynExpr.TypeApp _ as typeApp -> mkLinksFromFunctionName LinkExpr.Identifier typeApp |> continuation
| SynExpr.LongIdent(longDotId = sli) -> continuation (mkLinksFromSynLongIdent sli)
| SynExpr.Ident _ -> continuation [ LinkExpr.Identifier e ]
| SynExpr.DotIndexedGet(objectExpr, indexArgs, dotRange, _) ->
visit objectExpr (fun leftLinks ->
continuation
[ yield! leftLinks
yield LinkExpr.Dot dotRange
yield LinkExpr.IndexExpr indexArgs ])
| other -> continuation [ LinkExpr.Expr other ]
match e with
// An identifier only application with a parenthesis lambda expression.
// ex: `List.map (fun n -> n)` or `MailboxProcessor<string>.Start (fun n -> n)
// Because the identifier is not complex we don't consider it a chain.
| SynExpr.App(
isInfix = false
funcExpr = SynExpr.LongIdent _ | SynExpr.Ident _ | SynExpr.DotGet(expr = SynExpr.TypeApp(expr = SynExpr.Ident _))
argExpr = ParenExpr(_, SynExpr.Lambda _, _, _)) -> None
| SynExpr.App(
isInfix = false
funcExpr = SynExpr.DotGet _ | SynExpr.TypeApp(expr = SynExpr.DotGet _)
argExpr = UnitExpr _ | ParenExpr _)
| SynExpr.DotGet _
| SynExpr.TypeApp(expr = SynExpr.DotGet _)
| SynExpr.DotIndexedGet(objectExpr = SynExpr.App(funcExpr = SynExpr.DotGet _) | SynExpr.DotGet _) ->
Some(visit e id)
| _ -> None
let (|AppSingleParenArg|_|) =
function
| App(SynExpr.DotGet _, [ (SynExpr.Paren(expr = SynExpr.Tuple _)) ]) -> None
| App(e, [ SynExpr.Paren(expr = singleExpr) as px ]) ->
match singleExpr with
| SynExpr.Lambda _
| SynExpr.MatchLambda _ -> None
| _ -> Some(e, px)
| _ -> None
let mkParenExpr creationAide lpr e rpr m =
ExprParenNode(stn "(" lpr, mkExpr creationAide e, stn ")" rpr, m)
let mkExpr (creationAide: CreationAide) (e: SynExpr) : Expr =
let exprRange = e.Range
match e with
| SynExpr.Lazy(e, StartRange 4 (lazyKeyword, _range)) ->
ExprLazyNode(stn "lazy" lazyKeyword, mkExpr creationAide e, exprRange)
|> Expr.Lazy
| SynExpr.InferredDowncast(e, StartRange 8 (downcastKeyword, _range)) ->
ExprSingleNode(stn "downcast" downcastKeyword, true, false, mkExpr creationAide e, exprRange)
|> Expr.Single
| SynExpr.InferredUpcast(e, StartRange 6 (upcastKeyword, _range)) ->
ExprSingleNode(stn "upcast" upcastKeyword, true, false, mkExpr creationAide e, exprRange)
|> Expr.Single
| SynExpr.Assert(e, StartRange 6 (assertKeyword, _range)) ->
ExprSingleNode(stn "assert" assertKeyword, true, false, mkExpr creationAide e, exprRange)
|> Expr.Single
| SynExpr.AddressOf(true, e, _, StartRange 1 (ampersandToken, _range)) ->
ExprSingleNode(stn "&" ampersandToken, false, false, mkExpr creationAide e, exprRange)
|> Expr.Single
| SynExpr.AddressOf(false, e, _, StartRange 2 (ampersandToken, _range)) ->
ExprSingleNode(stn "&&" ampersandToken, false, false, mkExpr creationAide e, exprRange)
|> Expr.Single
| SynExpr.YieldOrReturn((true, _), e, StartRange 5 (yieldKeyword, _range)) ->
ExprSingleNode(stn "yield" yieldKeyword, true, true, mkExpr creationAide e, exprRange)
|> Expr.Single
| SynExpr.YieldOrReturn((false, _), e, StartRange 6 (returnKeyword, _range)) ->
ExprSingleNode(stn "return" returnKeyword, true, true, mkExpr creationAide e, exprRange)
|> Expr.Single
| SynExpr.YieldOrReturnFrom((true, _), e, StartRange 6 (yieldBangKeyword, _range)) ->
ExprSingleNode(stn "yield!" yieldBangKeyword, true, true, mkExpr creationAide e, exprRange)
|> Expr.Single
| SynExpr.YieldOrReturnFrom((false, _), e, StartRange 7 (returnBangKeyword, _range)) ->
ExprSingleNode(stn "return!" returnBangKeyword, true, true, mkExpr creationAide e, exprRange)
|> Expr.Single
| SynExpr.Do(e, StartRange 2 (doKeyword, _range)) ->
ExprSingleNode(stn "do" doKeyword, true, true, mkExpr creationAide e, exprRange)
|> Expr.Single
| SynExpr.DoBang(e, StartRange 3 (doBangKeyword, _range)) ->
ExprSingleNode(stn "do!" doBangKeyword, true, true, mkExpr creationAide e, exprRange)
|> Expr.Single
| SynExpr.Fixed(e, StartRange 5 (fixedKeyword, _range)) ->
ExprSingleNode(stn "fixed" fixedKeyword, true, false, mkExpr creationAide e, exprRange)
|> Expr.Single
| SynExpr.Const(c, r) -> mkConstant creationAide c r |> Expr.Constant
| SynExpr.Null _ -> stn "null" exprRange |> Expr.Null
| SynExpr.Quote(_, isRaw, e, _, range) -> mkExprQuote creationAide isRaw e range |> Expr.Quote
| SynExpr.TypeTest(e, t, _) ->
ExprTypedNode(mkExpr creationAide e, ":?", mkType creationAide t, exprRange)
|> Expr.Typed
| SynExpr.Downcast(e, t, _) ->
ExprTypedNode(mkExpr creationAide e, ":?>", mkType creationAide t, exprRange)
|> Expr.Typed
| SynExpr.Upcast(e, t, _) ->
ExprTypedNode(mkExpr creationAide e, ":>", mkType creationAide t, exprRange)
|> Expr.Typed
| SynExpr.Typed(e, t, _) ->
ExprTypedNode(mkExpr creationAide e, ":", mkType creationAide t, exprRange)
|> Expr.Typed
| SynExpr.New(_, t, e, StartRange 3 (newRange, _)) ->
ExprNewNode(stn "new" newRange, mkType creationAide t, mkExpr creationAide e, exprRange)
|> Expr.New
| SynExpr.Tuple(false, exprs, commas, _) -> mkTuple creationAide exprs commas exprRange |> Expr.Tuple
| SynExpr.Tuple(true, exprs, commas, StartRange 6 (mStruct, _) & EndRange 1 (mClosing, _)) ->
let mTuple =
match List.tryHead exprs, List.tryLast exprs with
| Some e1, Some e2 -> unionRanges e1.Range e2.Range
| _ -> failwith "SynExpr.Tuple with no elements"
ExprStructTupleNode(stn "struct" mStruct, mkTuple creationAide exprs commas mTuple, stn ")" mClosing, exprRange)
|> Expr.StructTuple
| SynExpr.ArrayOrListComputed(isArray, Sequentials xs, range)
| SynExpr.ArrayOrList(isArray, xs, range) ->
let o, c = mkOpenAndCloseForArrayOrList isArray range
ExprArrayOrListNode(o, List.map (mkExpr creationAide) xs, c, exprRange)
|> Expr.ArrayOrList
| SynExpr.ArrayOrListComputed(isArray, singleExpr, range) ->
let o, c = mkOpenAndCloseForArrayOrList isArray range
ExprArrayOrListNode(o, [ mkExpr creationAide singleExpr ], c, exprRange)
|> Expr.ArrayOrList
| SynExpr.Record(baseInfo, copyInfo, recordFields, StartEndRange 1 (mOpen, _, mClose)) ->
let fieldNodes =
recordFields
|> List.choose (function
| SynExprRecordField((fieldName, _), Some mEq, Some expr, _) ->
let m = unionRanges fieldName.Range expr.Range
Some(RecordFieldNode(mkSynLongIdent fieldName, stn "=" mEq, mkExpr creationAide expr, m))
| _ -> None)
match baseInfo, copyInfo with
| Some _, Some _ -> failwith "Unexpected that both baseInfo and copyInfo are present in SynExpr.Record"
| Some(t, e, m, _, mInherit), None ->
let inheritCtor = mkInheritConstructor creationAide t e mInherit m
ExprInheritRecordNode(stn "{" mOpen, inheritCtor, fieldNodes, stn "}" mClose, exprRange)
|> Expr.InheritRecord
| None, Some(copyExpr, _) ->
let copyExpr = mkExpr creationAide copyExpr
ExprRecordNode(stn "{" mOpen, Some copyExpr, fieldNodes, stn "}" mClose, exprRange)
|> Expr.Record
| None, None ->
ExprRecordNode(stn "{" mOpen, None, fieldNodes, stn "}" mClose, exprRange)
|> Expr.Record
| SynExpr.AnonRecd(true,
copyInfo,
recordFields,
(StartRange 6 (mStruct, _) & EndRange 2 (mClose, _)),
{ OpeningBraceRange = mOpen }) ->
let fields =
recordFields
|> List.choose (function
| sli, Some mEq, e ->