-
-
Notifications
You must be signed in to change notification settings - Fork 193
/
SourceParser.fs
1716 lines (1431 loc) · 53.1 KB
/
SourceParser.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.SourceParser
open System
open System.Diagnostics
open FSharp.Compiler.PrettyNaming
open FSharp.Compiler.Range
open FSharp.Compiler.SyntaxTree
open FSharp.Compiler.XmlDoc
open Fantomas
open Fantomas.Context
open FSharp.Compiler.SourceCodeServices.PrettyNaming
type Composite<'a, 'b> =
| Pair of 'b * 'b
| Single of 'a
#if INTERACTIVE
type Debug = Console
#endif
[<Literal>]
let MaxLength = 512
/// Get source string content based on range value
let lookup (r: range) (c: Context) =
if r.EndLine < c.Positions.Length then
let start =
c.Positions.[r.StartLine - 1] + r.StartColumn
let startLength =
c.Positions.[r.StartLine]
- c.Positions.[r.StartLine - 1]
let finish =
c.Positions.[r.EndLine - 1] + r.EndColumn - 1
let finishLength =
c.Positions.[r.EndLine]
- c.Positions.[r.EndLine - 1]
let content = c.Content
// Any line with more than 512 characters isn't reliable for querying
if start > finish
|| startLength >= MaxLength
|| finishLength >= MaxLength then
Debug.WriteLine("Can't lookup between start = {0} and finish = {1}", start, finish)
None
else
let s = content.[start..finish]
Debug.WriteLine("Content: {0} at start = {1}, finish = {2}", s, start, finish)
if s.Contains("\\\n") then
// Terrible hack to compensate the offset made by F# compiler
let last =
content.[c.Positions.[r.EndLine - 1]..finish]
let offset =
min (last.Length - last.TrimStart(' ').Length) (content.Length - finish - 1)
Debug.WriteLine("Content after patch: {0} with offset = {1}", s, offset)
Some content.[start..finish + offset]
else
Some s
else
None
let (|Ident|) (s: Ident) =
let ident = s.idText
match ident with
| "`global`" -> "global"
| "_" -> "_" // workaround for https://github.com/dotnet/fsharp/issues/7681
| _ -> QuoteIdentifierIfNeeded ident
let (|LongIdent|) (li: LongIdent) =
li
|> Seq.map
(fun x ->
if x.idText = MangledGlobalName then
"global"
else
(|Ident|) x)
|> String.concat "."
|> fun s ->
// Assume that if it starts with base, it's going to be the base keyword
if String.startsWithOrdinal "``base``." s then
String.Join("", "base.", s.[9..])
else
s
let (|LongIdentPieces|_|) =
function
| SynExpr.LongIdent (_, LongIdentWithDots (lids, _), _, _) ->
lids
|> List.map
(fun x ->
if x.idText = MangledGlobalName then
"global"
else
(|Ident|) x)
|> Some
| _ -> None
let inline (|LongIdentWithDots|) (LongIdentWithDots (LongIdent s, _)) = s
type Identifier =
| Id of Ident
| LongId of LongIdent
member x.Text =
match x with
| Id x -> x.idText
| LongId xs ->
xs
|> Seq.map
(fun x ->
if x.idText = MangledGlobalName then
"global"
else
x.idText)
|> String.concat "."
member x.Ranges =
match x with
| Id x -> List.singleton x.idRange
| LongId xs -> List.map (fun (x: Ident) -> x.idRange) xs
/// Different from (|Ident|), this pattern also accepts keywords
let inline (|IdentOrKeyword|) (s: Ident) = Id s
let (|LongIdentOrKeyword|) (li: LongIdent) = LongId li
/// Use infix operators in the short form
let (|OpName|) (x: Identifier) =
let s = x.Text
let s' = DecompileOpName s
if IsActivePatternName s then
sprintf "(%s)" s'
elif IsPrefixOperator s then
if s'.[0] = '~' && s'.Length >= 2 && s'.[1] <> '~' then
s'.[1..]
else
s'
else
match x with
| Id (Ident s)
| LongId (LongIdent s) -> DecompileOpName s
let (|OpNameFullInPattern|) (x: Identifier) =
let r = x.Ranges
let s = x.Text
let s' = DecompileOpName s
(if IsActivePatternName s
|| IsInfixOperator s
|| IsPrefixOperator s
|| IsTernaryOperator s
|| s = "op_Dynamic" then
/// Use two spaces for symmetry
if String.startsWithOrdinal "*" s' && s' <> "*" then
sprintf "( %s )" s'
else
sprintf "(%s)" s'
else
match x with
| Id (Ident s)
| LongId (LongIdent s) -> DecompileOpName s)
|> fun s -> (s, r)
/// Operators in their declaration form
let (|OpNameFull|) (x: Identifier) =
let r = x.Ranges
let s = x.Text
let s' = DecompileOpName s
(if IsActivePatternName s then
s
elif IsInfixOperator s
|| IsPrefixOperator s
|| IsTernaryOperator s
|| s = "op_Dynamic" then
s'
else
match x with
| Id (Ident s)
| LongId (LongIdent s) -> DecompileOpName s)
|> fun s -> (s, r)
// Type params
let inline (|Typar|) (SynTypar.Typar (Ident s, req, _)) =
match req with
| NoStaticReq -> (s, false)
| HeadTypeStaticReq -> (s, true)
let inline (|ValTyparDecls|) (SynValTyparDecls (tds, b, tcs)) = (tds, b, tcs)
// Literals
let rec (|RationalConst|) =
function
| SynRationalConst.Integer i -> string i
| SynRationalConst.Rational (numerator, denominator, _) -> sprintf "(%i/%i)" numerator denominator
| SynRationalConst.Negate (RationalConst s) -> sprintf "- %s" s
let (|Measure|) x =
let rec loop =
function
| SynMeasure.Var (Typar (s, _), _) -> s
| SynMeasure.Anon _ -> "_"
| SynMeasure.One -> "1"
| SynMeasure.Product (m1, m2, _) ->
let s1 = loop m1
let s2 = loop m2
sprintf "%s*%s" s1 s2
| SynMeasure.Divide (m1, m2, _) ->
let s1 = loop m1
let s2 = loop m2
sprintf "%s/%s" s1 s2
| SynMeasure.Power (m, RationalConst n, _) ->
let s = loop m
sprintf "%s^%s" s n
| SynMeasure.Seq (ms, _) -> List.map loop ms |> String.concat " "
| SynMeasure.Named (LongIdent s, _) -> s
sprintf "<%s>" <| loop x
/// Lose information about kinds of literals
let rec (|Const|) c =
match c with
| SynConst.Measure (Const c, Measure m) -> c + m
| SynConst.UserNum (num, ty) -> num + ty
| SynConst.Unit -> "()"
| SynConst.Bool b -> sprintf "%A" b
| SynConst.SByte s -> sprintf "%A" s
| SynConst.Byte b -> sprintf "%A" b
| SynConst.Int16 i -> sprintf "%A" i
| SynConst.UInt16 u -> sprintf "%A" u
| SynConst.Int32 i -> sprintf "%A" i
| SynConst.UInt32 u -> sprintf "%A" u
| SynConst.Int64 i -> sprintf "%A" i
| SynConst.UInt64 u -> sprintf "%A" u
| SynConst.IntPtr i -> sprintf "%in" i
| SynConst.UIntPtr u -> sprintf "%iun" u
| SynConst.Single s -> sprintf "%A" s
| SynConst.Double d -> sprintf "%A" d
| SynConst.Char c -> sprintf "%A" c
| SynConst.Decimal d -> sprintf "%A" d
| SynConst.String (s, _) ->
// Naive check for verbatim strings
if not <| String.IsNullOrEmpty(s)
&& s.Contains("\\")
&& not <| s.Contains(@"\\") then
sprintf "@%A" s
else
sprintf "%A" s
| SynConst.Bytes (bs, _) -> sprintf "%A" bs
// Auto print may cut off the array
| SynConst.UInt16s us -> sprintf "%A" us
let (|String|_|) e =
match e with
| SynExpr.Const (SynConst.String (s, _), _) -> Some s
| _ -> None
let (|MultilineString|_|) e =
match e with
| String (s) when (String.isMultiline s) -> Some e
| _ -> None
let (|Unresolved|) (Const s as c, r) = (c, r, s)
// File level patterns
let (|ImplFile|SigFile|) =
function
| ParsedInput.ImplFile im -> ImplFile im
| ParsedInput.SigFile si -> SigFile si
let (|ParsedImplFileInput|) (ParsedImplFileInput.ParsedImplFileInput (_, _, _, _, hs, mns, _)) = (hs, mns)
let (|ParsedSigFileInput|) (ParsedSigFileInput.ParsedSigFileInput (_, _, _, hs, mns)) = (hs, mns)
let (|ModuleOrNamespace|)
(SynModuleOrNamespace.SynModuleOrNamespace (LongIdent s, isRecursive, isModule, mds, px, ats, ao, _))
=
(ats, px, ao, s, mds, isRecursive, isModule)
let (|SigModuleOrNamespace|)
(SynModuleOrNamespaceSig.SynModuleOrNamespaceSig (LongIdent s, isRecursive, isModule, mds, px, ats, ao, _))
=
(ats, px, ao, s, mds, isRecursive, isModule)
let (|Attribute|) (a: SynAttribute) =
let (LongIdentWithDots s) = a.TypeName
(s, a.ArgExpr, Option.map (fun (i: Ident) -> i.idText) a.Target)
// Access modifiers
let (|Access|) =
function
| SynAccess.Public -> "public"
| SynAccess.Internal -> "internal"
| SynAccess.Private -> "private"
let (|PreXmlDoc|) (px: PreXmlDoc) =
px.ToXmlDoc(false, None).UnprocessedLines
// Module declarations (11 cases)
let (|Open|_|) =
function
| SynModuleDecl.Open (SynOpenDeclTarget.ModuleOrNamespace (LongIdent s, _m), _) -> Some s
| _ -> None
let (|OpenType|_|) =
function
// TODO: are there other SynType causes that need to be handled here?
| SynModuleDecl.Open (SynOpenDeclTarget.Type (SynType.LongIdent (LongIdentWithDots s), _m), _) -> Some s
| _ -> None
let (|ModuleAbbrev|_|) =
function
| SynModuleDecl.ModuleAbbrev (Ident s1, LongIdent s2, _) -> Some(s1, s2)
| _ -> None
let (|HashDirective|_|) =
function
| SynModuleDecl.HashDirective (p, _) -> Some p
| _ -> None
let (|NamespaceFragment|_|) =
function
| SynModuleDecl.NamespaceFragment m -> Some m
| _ -> None
let (|Attributes|_|) =
function
| SynModuleDecl.Attributes (ats, _) -> Some(ats)
| _ -> None
let (|Let|_|) =
function
| SynModuleDecl.Let (false, [ x ], _) -> Some x
| _ -> None
let (|LetRec|_|) =
function
| SynModuleDecl.Let (true, xs, _) -> Some xs
| _ -> None
let (|DoExpr|_|) =
function
| SynModuleDecl.DoExpr (_, x, _) -> Some x
| _ -> None
let (|Types|_|) =
function
| SynModuleDecl.Types (xs, _) -> Some xs
| _ -> None
let (|NestedModule|_|) =
function
| SynModuleDecl.NestedModule (SynComponentInfo.ComponentInfo (ats, _, _, LongIdent s, px, _, ao, _),
isRecursive,
xs,
_,
_) -> Some(ats, px, ao, s, isRecursive, xs)
| _ -> None
let (|Exception|_|) =
function
| SynModuleDecl.Exception (ed, _) -> Some ed
| _ -> None
// Module declaration signatures (9 cases)
let (|SigOpen|_|) =
function
| SynModuleSigDecl.Open (SynOpenDeclTarget.ModuleOrNamespace (LongIdent s, _), _) -> Some s
| _ -> None
let (|SigOpenType|_|) =
function
| SynModuleSigDecl.Open (SynOpenDeclTarget.Type (SynType.LongIdent (LongIdentWithDots s), _), _) -> Some s
| _ -> None
let (|SigModuleAbbrev|_|) =
function
| SynModuleSigDecl.ModuleAbbrev (Ident s1, LongIdent s2, _) -> Some(s1, s2)
| _ -> None
let (|SigHashDirective|_|) =
function
| SynModuleSigDecl.HashDirective (p, _) -> Some p
| _ -> None
let (|SigNamespaceFragment|_|) =
function
| SynModuleSigDecl.NamespaceFragment m -> Some m
| _ -> None
let (|SigVal|_|) =
function
| SynModuleSigDecl.Val (v, _) -> Some v
| _ -> None
let (|SigTypes|_|) =
function
| SynModuleSigDecl.Types (tds, _) -> Some tds
| _ -> None
let (|SigNestedModule|_|) =
function
| SynModuleSigDecl.NestedModule (SynComponentInfo.ComponentInfo (ats, _, _, LongIdent s, px, _, ao, _), _, xs, _) ->
Some(ats, px, ao, s, xs)
| _ -> None
let (|SigException|_|) =
function
| SynModuleSigDecl.Exception (es, _) -> Some es
| _ -> None
// Exception definitions
let (|ExceptionDefRepr|) (SynExceptionDefnRepr.SynExceptionDefnRepr (ats, uc, _, px, ao, _)) = (ats, px, ao, uc)
let (|SigExceptionDefRepr|) (SynExceptionDefnRepr.SynExceptionDefnRepr (ats, uc, _, px, ao, _)) = (ats, px, ao, uc)
let (|ExceptionDef|)
(SynExceptionDefn.SynExceptionDefn (SynExceptionDefnRepr.SynExceptionDefnRepr (ats, uc, _, px, ao, _), ms, _))
=
(ats, px, ao, uc, ms)
let (|SigExceptionDef|)
(SynExceptionSig.SynExceptionSig (SynExceptionDefnRepr.SynExceptionDefnRepr (ats, uc, _, px, ao, _), ms, _))
=
(ats, px, ao, uc, ms)
let (|UnionCase|) (SynUnionCase.UnionCase (ats, Ident s, uct, px, ao, _)) = (ats, px, ao, s, uct)
let (|UnionCaseType|) =
function
| SynUnionCaseType.UnionCaseFields fs -> fs
| SynUnionCaseType.UnionCaseFullType _ -> failwith "UnionCaseFullType should be used internally only."
let (|Field|) (SynField.Field (ats, isStatic, ido, t, isMutable, px, ao, _)) =
(ats, px, ao, isStatic, isMutable, t, Option.map (|Ident|) ido)
let (|EnumCase|) (SynEnumCase.EnumCase (ats, Ident s, c, px, r)) = (ats, px, s, (c, r))
// Member definitions (11 cases)
let (|MDNestedType|_|) =
function
| SynMemberDefn.NestedType (td, ao, _) -> Some(td, ao)
| _ -> None
let (|MDOpen|_|) =
function
| SynMemberDefn.Open (SynOpenDeclTarget.ModuleOrNamespace (LongIdent s, _), _) -> Some s
| _ -> None
let (|MDOpenType|_|) =
function
| SynMemberDefn.Open (SynOpenDeclTarget.Type (SynType.LongIdent (LongIdentWithDots s), _), _) -> Some s
| _ -> None
let (|MDImplicitInherit|_|) =
function
| SynMemberDefn.ImplicitInherit (t, e, ido, _) -> Some(t, e, Option.map (|Ident|) ido)
| _ -> None
let (|MDInherit|_|) =
function
| SynMemberDefn.Inherit (t, ido, _) -> Some(t, Option.map (|Ident|) ido)
| _ -> None
let (|MDValField|_|) =
function
| SynMemberDefn.ValField (f, _) -> Some f
| _ -> None
let (|MDImplicitCtor|_|) =
function
| SynMemberDefn.ImplicitCtor (ao, ats, ps, ido, _docs, _) -> Some(ats, ao, ps, Option.map (|Ident|) ido)
| _ -> None
let (|MDMember|_|) =
function
| SynMemberDefn.Member (b, _) -> Some b
| _ -> None
let (|MDLetBindings|_|) =
function
| SynMemberDefn.LetBindings (es, isStatic, isRec, _) -> Some(isStatic, isRec, es)
| _ -> None
let (|MDAbstractSlot|_|) =
function
| SynMemberDefn.AbstractSlot (ValSpfn (ats, Ident s, tds, t, vi, _, _, px, ao, _, _), mf, _) ->
Some(ats, px, ao, s, t, vi, tds, mf)
| _ -> None
let (|MDInterface|_|) =
function
| SynMemberDefn.Interface (t, mdo, range) -> Some(t, mdo, range)
| _ -> None
let (|MDAutoProperty|_|) =
function
| SynMemberDefn.AutoProperty (ats, isStatic, Ident s, typeOpt, mk, memberKindToMemberFlags, px, ao, e, _, _) ->
Some(ats, px, ao, mk, e, s, isStatic, typeOpt, memberKindToMemberFlags)
| _ -> None
// Interface impl
let (|InterfaceImpl|) (SynInterfaceImpl.InterfaceImpl (t, bs, range)) = (t, bs, range)
// Bindings
let (|PropertyGet|_|) =
function
| MemberKind.PropertyGet -> Some()
| _ -> None
let (|PropertySet|_|) =
function
| MemberKind.PropertySet -> Some()
| _ -> None
let (|PropertyGetSet|_|) =
function
| MemberKind.PropertyGetSet -> Some()
| _ -> None
let (|MFProperty|_|) (mf: MemberFlags) =
match mf.MemberKind with
| MemberKind.PropertyGet
| MemberKind.PropertySet
| MemberKind.PropertyGetSet as mk -> Some mk
| _ -> None
let (|MFMemberFlags|) (mf: MemberFlags) = mf.MemberKind
/// This pattern finds out which keyword to use
let (|MFMember|MFStaticMember|MFConstructor|MFOverride|) (mf: MemberFlags) =
match mf.MemberKind with
| MemberKind.ClassConstructor
| MemberKind.Constructor -> MFConstructor()
| MemberKind.Member
| MemberKind.PropertyGet
| MemberKind.PropertySet
| MemberKind.PropertyGetSet as mk ->
if mf.IsInstance && mf.IsOverrideOrExplicitImpl then
MFOverride mk
elif mf.IsInstance then
MFMember mk
else
MFStaticMember mk
let (|DoBinding|LetBinding|MemberBinding|PropertyBinding|ExplicitCtor|) =
function
| SynBinding.Binding (ao, _, _, _, ats, px, SynValData (Some MFConstructor, _, ido), pat, _, expr, _, _) ->
ExplicitCtor(ats, px, ao, pat, expr, Option.map (|Ident|) ido)
| SynBinding.Binding (ao, _, isInline, _, ats, px, SynValData (Some (MFProperty _ as mf), _, _), pat, _, expr, _, _) ->
PropertyBinding(ats, px, ao, isInline, mf, pat, expr)
| SynBinding.Binding (ao, _, isInline, _, ats, px, SynValData (Some mf, synValInfo, _), pat, _, expr, _, _) ->
MemberBinding(ats, px, ao, isInline, mf, pat, expr, synValInfo)
| SynBinding.Binding (_, DoBinding, _, _, ats, px, _, _, _, expr, _, _) -> DoBinding(ats, px, expr)
| SynBinding.Binding (ao, _, isInline, isMutable, attrs, px, SynValData (_, valInfo, _), pat, _, expr, _, _) ->
LetBinding(attrs, px, ao, isInline, isMutable, pat, expr, valInfo)
// Expressions (55 cases, lacking to handle 11 cases)
let (|TraitCall|_|) =
function
| SynExpr.TraitCall (tps, msg, expr, _) -> Some(tps, msg, expr)
| _ -> None
/// isRaw = true with <@@ and @@>
let (|Quote|_|) =
function
| SynExpr.Quote (e1, isRaw, e2, _, _) -> Some(e1, e2, isRaw)
| _ -> None
let (|Paren|_|) =
function
| SynExpr.Paren (e, lpr, rpr, _) -> Some(lpr, e, rpr)
| _ -> None
type ExprKind =
| InferredDowncast
| InferredUpcast
| Lazy
| Assert
| AddressOfSingle
| AddressOfDouble
| Yield
| Return
| YieldFrom
| ReturnFrom
| Do
| DoBang
override x.ToString() =
match x with
| InferredDowncast -> "downcast "
| InferredUpcast -> "upcast "
| Lazy -> "lazy "
| Assert -> "assert "
| AddressOfSingle -> "&"
| AddressOfDouble -> "&&"
| Yield -> "yield "
| Return -> "return "
| YieldFrom -> "yield! "
| ReturnFrom -> "return! "
| Do -> "do "
| DoBang -> "do! "
let (|SingleExpr|_|) =
function
| SynExpr.InferredDowncast (e, _) -> Some(InferredDowncast, e)
| SynExpr.InferredUpcast (e, _) -> Some(InferredUpcast, e)
| SynExpr.Lazy (e, _) -> Some(Lazy, e)
| SynExpr.Assert (e, _) -> Some(Assert, e)
| SynExpr.AddressOf (true, e, _, _) -> Some(AddressOfSingle, e)
| SynExpr.AddressOf (false, e, _, _) -> Some(AddressOfDouble, e)
| SynExpr.YieldOrReturn ((true, _), e, _) -> Some(Yield, e)
| SynExpr.YieldOrReturn ((false, _), e, _) -> Some(Return, e)
| SynExpr.YieldOrReturnFrom ((true, _), e, _) -> Some(YieldFrom, e)
| SynExpr.YieldOrReturnFrom ((false, _), e, _) -> Some(ReturnFrom, e)
| SynExpr.Do (e, _) -> Some(Do, e)
| SynExpr.DoBang (e, _) -> Some(DoBang, e)
| _ -> None
type TypedExprKind =
| TypeTest
| Downcast
| Upcast
| Typed
let (|TypedExpr|_|) =
function
| SynExpr.TypeTest (e, t, _) -> Some(TypeTest, e, t)
| SynExpr.Downcast (e, t, _) -> Some(Downcast, e, t)
| SynExpr.Upcast (e, t, _) -> Some(Upcast, e, t)
| SynExpr.Typed (e, t, _) -> Some(Typed, e, t)
| _ -> None
let (|While|_|) =
function
| SynExpr.While (_, e1, e2, _) -> Some(e1, e2)
| _ -> None
let (|For|_|) =
function
| SynExpr.For (_, Ident s, e1, isUp, e2, e3, _) -> Some(s, e1, e2, e3, isUp)
| _ -> None
let (|NullExpr|_|) =
function
| SynExpr.Null _ -> Some()
| _ -> None
let (|ConstExpr|_|) =
function
| SynExpr.Const (x, r) -> Some(x, r)
| _ -> None
let (|TypeApp|_|) =
function
| SynExpr.TypeApp (e, _, ts, _, _, _, _) -> Some(e, ts)
| _ -> None
let (|Match|_|) =
function
| SynExpr.Match (_, e, cs, _) -> Some(e, cs)
| _ -> None
let (|MatchBang|_|) =
function
| SynExpr.MatchBang (_, e, cs, _) -> Some(e, cs)
| _ -> None
let (|Sequential|_|) =
function
| SynExpr.Sequential (_, isSeq, e1, e2, _) -> Some(e1, e2, isSeq)
| _ -> None
let rec (|Sequentials|_|) =
function
| Sequential (e, Sequentials es, _) -> Some(e :: es)
| Sequential (e1, e2, _) -> Some [ e1; e2 ]
| _ -> None
let (|SimpleExpr|_|) =
function
| SynExpr.Null _
| SynExpr.Ident _
| SynExpr.LongIdent _
| SynExpr.Const (Const _, _) as e -> Some e
| _ -> None
/// Only recognize numbers; strings are ignored
let rec (|SequentialSimple|_|) =
function
| Sequential (SimpleExpr e, SequentialSimple es, true) -> Some(e :: es)
| Sequential (SimpleExpr e1, SimpleExpr e2, true) -> Some [ e1; e2 ]
| _ -> None
let (|CompExpr|_|) =
function
| SynExpr.CompExpr (isArray, _, expr, _) -> Some(isArray, expr)
| _ -> None
let isCompExpr =
function
| CompExpr _ -> true
| _ -> false
let (|ArrayOrListOfSeqExpr|_|) =
function
| SynExpr.ArrayOrListOfSeqExpr (isArray, expr, _) -> Some(isArray, expr)
| _ -> None
/// This pattern only includes arrays and lists in computation expressions
let (|ArrayOrList|_|) =
function
| ArrayOrListOfSeqExpr (isArray, CompExpr (_, SequentialSimple xs)) -> Some(isArray, xs, true)
| SynExpr.ArrayOrList (isArray, xs, _)
| ArrayOrListOfSeqExpr (isArray, CompExpr (_, Sequentials xs)) -> Some(isArray, xs, false)
| _ -> None
let (|Tuple|_|) =
function
| SynExpr.Tuple (false, exprs, _, tupleRange) -> Some(exprs, Some tupleRange)
| _ -> None
let (|StructTuple|_|) =
function
| SynExpr.Tuple (true, exprs, _, _) -> Some exprs
| _ -> None
let (|IndexedVar|_|) =
function
// We might have to narrow scope of this pattern to avoid incorrect usage
| SynExpr.App (_, _, SynExpr.LongIdent (_, LongIdentWithDots "Microsoft.FSharp.Core.Some", _, _), e, _) ->
Some(Some e)
| SynExpr.LongIdent (_, LongIdentWithDots "Microsoft.FSharp.Core.None", _, _) -> Some None
| _ -> None
let (|Indexer|) =
function
| SynIndexerArg.Two (e1, e1FromEnd, e2, e2FromEnd, _, _) -> Pair((e1, e1FromEnd), (e2, e2FromEnd))
| SynIndexerArg.One (e, fromEnd, _) -> Single(e, fromEnd)
let (|OptVar|_|) =
function
| SynExpr.Ident (IdentOrKeyword (OpNameFull (s, r))) -> Some(s, false, r)
| SynExpr.LongIdent (isOpt, LongIdentWithDots.LongIdentWithDots (LongIdentOrKeyword (OpNameFull (s, r)), _), _, _) ->
Some(s, isOpt, r)
| _ -> None
/// This pattern is escaped by using OpName
let (|Var|_|) =
function
| SynExpr.Ident (IdentOrKeyword (OpName s)) -> Some s
| SynExpr.LongIdent (_, LongIdentWithDots.LongIdentWithDots (LongIdentOrKeyword (OpName s), _), _, _) -> Some s
| _ -> None
// Compiler-generated patterns often have "_arg" prefix
let (|CompilerGeneratedVar|_|) =
function
| SynExpr.Ident (IdentOrKeyword (OpName s)) when String.startsWithOrdinal "_arg" s -> Some s
| SynExpr.LongIdent (_, LongIdentWithDots.LongIdentWithDots (LongIdentOrKeyword (OpName s), _), opt, _) ->
match opt with
| Some _ -> Some s
| None ->
if String.startsWithOrdinal "_arg" s then
Some s
else
None
| _ -> None
/// Get all application params at once
let (|App|_|) e =
let rec loop =
function
// function application is left-recursive
| SynExpr.App (_, _, e, e2, _) ->
let (e1, es) = loop e
(e1, e2 :: es)
| e -> (e, [])
match loop e with
| (_, []) -> None
| (e, es) -> Some(e, List.rev es)
// captures application with single tuple arg
let (|AppTuple|_|) =
function
| App (SynExpr.DotGet _, [ (Paren (_, Tuple _, _)) ]) -> None
| App (e, [ (Paren (lpr, Tuple (args, tupleRange), rpr)) ]) -> Some(e, lpr, args, tupleRange, rpr)
| App (e, [ (Paren (lpr, singleExpr, rpr)) ]) ->
match singleExpr with
| SynExpr.Lambda _
| SynExpr.MatchLambda _ -> None
| _ -> Some(e, lpr, [ singleExpr ], None, rpr)
| _ -> None
let (|NewTuple|_|) =
function
| SynExpr.New (_, t, Paren (lpr, Tuple (args, _), rpr), _) -> Some(t, lpr, args, rpr)
| SynExpr.New (_, t, Paren (lpr, singleExpr, rpr), _) -> Some(t, lpr, [ singleExpr ], rpr)
| SynExpr.New (_, t, ConstExpr (SynConst.Unit, unitRange), _) ->
let lpr =
mkRange "lpr" unitRange.Start unitRange.Start
let rpr =
mkRange "rpr" unitRange.End unitRange.End
Some(t, lpr, [], Some rpr)
| _ -> None
let (|CompApp|_|) =
function
| SynExpr.App (_, _, Var "seq", (SynExpr.App _ as e), _) -> Some("seq", e)
| _ -> None
/// Only process prefix operators here
let (|PrefixApp|_|) =
function
// Var pattern causes a few prefix operators appear as infix operators
| SynExpr.App (_, false, SynExpr.Ident (IdentOrKeyword s), e2, _)
| SynExpr.App (_,
false,
SynExpr.LongIdent (_, LongIdentWithDots.LongIdentWithDots (LongIdentOrKeyword s, _), _, _),
e2,
_) when IsPrefixOperator(DecompileOpName s.Text) -> Some((|OpName|) s, e2)
| _ -> None
let (|InfixApp|_|) synExpr =
match synExpr with
| SynExpr.App (_, true, (Var "::" as e), Tuple ([ e1; e2 ], _), _) -> Some("::", e, e1, e2)
// Range operators need special treatments, so we exclude them here
| SynExpr.App (_, _, SynExpr.App (_, true, (Var s as e), e1, _), e2, _) when s <> ".." -> Some(s, e, e1, e2)
| _ -> None
let (|NewlineInfixApp|_|) =
function
| InfixApp (text, operatorExpr, e1, e2) when (newLineInfixOps.Contains(text)) -> Some(text, operatorExpr, e1, e2)
| _ -> None
let (|NewlineInfixApps|_|) e =
let rec loop synExpr =
match synExpr with
| NewlineInfixApp (s, opE, e, e2) ->
let (e1, es) = loop e
(e1, (s, opE, e2) :: es)
| e -> (e, [])
match loop e with
| (e, es) when (List.length es > 1) -> Some(e, List.rev es)
| _ -> None
let (|SameInfixApps|_|) e =
let rec loop operator synExpr =
match synExpr with
| InfixApp (s, opE, e, e2) when (s = operator) ->
let (e1, es) = loop operator e
(e1, (s, opE, e2) :: es)
| e -> (e, [])
match e with
| InfixApp (operatorText, _, _, _) ->
match loop operatorText e with
| (e, es) when (List.length es > 1) -> Some(e, List.rev es)
| _ -> None
| _ -> None
let (|TernaryApp|_|) =
function
| SynExpr.App (_, _, SynExpr.App (_, _, SynExpr.App (_, true, Var "?<-", e1, _), e2, _), e3, _) -> Some(e1, e2, e3)
| _ -> None
/// Gather all arguments in lambda
let rec (|Lambda|_|) =
function
| SynExpr.Lambda (_, _, pats, Lambda (e, patss), _, _) -> Some(e, pats :: patss)
| SynExpr.Lambda (_, _, pats, e, _, _) -> Some(e, [ pats ])
| _ -> None
let (|MatchLambda|_|) =
function
| SynExpr.MatchLambda (isMember, _, pats, _, _) -> Some(pats, isMember)
| _ -> None
let (|JoinIn|_|) =
function
| SynExpr.JoinIn (e1, _, e2, _) -> Some(e1, e2)
| _ -> None
let (|LetOrUse|_|) =
function
| SynExpr.LetOrUse (isRec, isUse, xs, e, _) -> Some(isRec, isUse, xs, e)
| _ -> None
/// Unfold a list of let bindings
/// Recursive and use properties have to be determined at this point
let rec (|LetOrUses|_|) =
function
| SynExpr.LetOrUse (isRec, isUse, xs, LetOrUses (ys, e), _) ->
let prefix =
if isUse then "use "
elif isRec then "let rec "
else "let "
let xs' =
List.mapi
(fun i x ->
if i = 0 then
(prefix, x)
else
("and ", x))
xs
Some(xs' @ ys, e)
| SynExpr.LetOrUse (isRec, isUse, xs, e, _) ->
let prefix =
if isUse then "use "
elif isRec then "let rec "
else "let "
let xs' =
List.mapi
(fun i x ->
if i = 0 then
(prefix, x)
else
("and ", x))
xs
Some(xs', e)
| _ -> None
type ComputationExpressionStatement =
| LetOrUseStatement of recursive: bool * isUse: bool * SynBinding
| LetOrUseBangStatement of isUse: bool * SynPat * SynExpr * range
| AndBangStatement of SynPat * SynExpr * range
| OtherStatement of SynExpr
let rec collectComputationExpressionStatements e: ComputationExpressionStatement list =
match e with
| SynExpr.LetOrUse (isRecursive, isUse, bindings, body, _) ->
let bindings =
bindings
|> List.map (fun b -> LetOrUseStatement(isRecursive, isUse, b))
let returnExpr =
collectComputationExpressionStatements body
[ yield! bindings; yield! returnExpr ]
| SynExpr.LetOrUseBang (_, isUse, _, pat, expr, andBangs, body, r) ->
let letOrUseBang =
LetOrUseBangStatement(isUse, pat, expr, r)
let andBangs =
andBangs
|> List.map (fun (_, _, _, ap, ae, andRange) -> AndBangStatement(ap, ae, andRange))
let bodyStatements =
collectComputationExpressionStatements body
[ letOrUseBang
yield! andBangs
yield! bodyStatements ]
| SynExpr.Sequential (_, _, e1, e2, _) ->
[ yield! collectComputationExpressionStatements e1
yield! collectComputationExpressionStatements e2 ]
| expr -> [ OtherStatement expr ]
/// Matches if the SynExpr has some or of computation expression member call inside.
let rec (|CompExprBody|_|) expr =
match expr with
| SynExpr.LetOrUse (_, _, _, CompExprBody _, _) -> Some expr
| SynExpr.LetOrUseBang _ -> Some expr
| SynExpr.Sequential (_, _, _, SynExpr.YieldOrReturn _, _) -> Some expr
| SynExpr.Sequential (_, _, _, SynExpr.LetOrUse _, _) -> Some expr
| SynExpr.Sequential (_, _, SynExpr.DoBang _, SynExpr.LetOrUseBang _, _) -> Some expr
| _ -> None
let (|ForEach|_|) =
function
| SynExpr.ForEach (_, SeqExprOnly true, _, pat, e1, SingleExpr (Yield, e2), _) -> Some(pat, e1, e2, true)
| SynExpr.ForEach (_, SeqExprOnly isArrow, _, pat, e1, e2, _) -> Some(pat, e1, e2, isArrow)
| _ -> None
let (|DotIndexedSet|_|) =
function
| SynExpr.DotIndexedSet (e1, es, e2, _, _, _) -> Some(e1, es, e2)