-
Notifications
You must be signed in to change notification settings - Fork 790
/
ServiceAnalysis.fs
1636 lines (1397 loc) · 69.5 KB
/
ServiceAnalysis.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
// Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information.
namespace FSharp.Compiler.EditorServices
open System.Collections.Generic
open System.Runtime.CompilerServices
open Internal.Utilities.Library
open FSharp.Compiler.CodeAnalysis
open FSharp.Compiler.Symbols
open FSharp.Compiler.Syntax
open FSharp.Compiler.Syntax.PrettyNaming
open FSharp.Compiler.Text
open FSharp.Compiler.Text.Range
module UnusedOpens =
let symbolHash =
HashIdentity.FromFunctions (fun (x: FSharpSymbol) -> x.GetEffectivelySameAsHash()) (fun x y -> x.IsEffectivelySameAs(y))
/// Represents one namespace or module opened by an 'open' statement
type OpenedModule(entity: FSharpEntity, isNestedAutoOpen: bool) =
/// Compute an indexed table of the set of symbols revealed by 'open', on-demand
let revealedSymbols: Lazy<HashSet<FSharpSymbol>> =
lazy
let symbols: FSharpSymbol[] =
[|
for ent in entity.NestedEntities do
ent
if ent.IsFSharpRecord then
for rf in ent.FSharpFields do
rf
if ent.IsFSharpUnion && not (ent.HasAttribute<RequireQualifiedAccessAttribute>()) then
for unionCase in ent.UnionCases do
unionCase
if ent.HasAttribute<ExtensionAttribute>() then
for fv in ent.MembersFunctionsAndValues do
// fv.IsExtensionMember is always false for C# extension methods returning by `MembersFunctionsAndValues`,
// so we have to check Extension attribute instead.
// (note: fv.IsExtensionMember has proper value for symbols returning by GetAllUsesOfAllSymbolsInFile though)
if fv.HasAttribute<ExtensionAttribute>() then
fv
for apCase in entity.ActivePatternCases do
apCase
// The IsNamespace and IsFSharpModule cases are handled by looking at DeclaringEntity below
if not entity.IsNamespace && not entity.IsFSharpModule then
for fv in entity.MembersFunctionsAndValues do
fv
|]
HashSet<_>(symbols, symbolHash)
member _.Entity = entity
member _.IsNestedAutoOpen = isNestedAutoOpen
member _.RevealedSymbolsContains(symbol) = revealedSymbols.Force().Contains symbol
type OpenedModuleGroup =
{
OpenedModules: OpenedModule[]
}
static member Create(modul: FSharpEntity) =
let rec getModuleAndItsAutoOpens (isNestedAutoOpen: bool) (modul: FSharpEntity) =
[|
yield OpenedModule(modul, isNestedAutoOpen)
for ent in modul.NestedEntities do
if ent.IsFSharpModule && ent.HasAttribute<AutoOpenAttribute>() then
yield! getModuleAndItsAutoOpens true ent
|]
{
OpenedModules = getModuleAndItsAutoOpens false modul
}
/// Represents a single open statement
type OpenStatement =
{
/// All namespaces, modules and types which this open declaration effectively opens, including the AutoOpen ones
OpenedGroups: OpenedModuleGroup list
/// The range of open statement itself
Range: range
/// The scope on which this open declaration is applied
AppliedScope: range
}
/// Gets the open statements, their scopes and their resolutions
let getOpenStatements (openDeclarations: FSharpOpenDeclaration[]) : OpenStatement[] =
openDeclarations
|> Array.choose (fun openDecl ->
if openDecl.IsOwnNamespace then
None
else
match openDecl.LongId, openDecl.Range with
| firstId :: _, Some range ->
if firstId.idText = MangledGlobalName then
None
else
let openedModulesAndTypes =
List.concat [ openDecl.Modules; openDecl.Types |> List.map (fun ty -> ty.TypeDefinition) ]
Some
{
OpenedGroups = openedModulesAndTypes |> List.map OpenedModuleGroup.Create
Range = range
AppliedScope = openDecl.AppliedScope
}
| _ -> None)
/// Only consider symbol uses which are the first part of a long ident, i.e. with no qualifying identifiers
let filterSymbolUses (getSourceLineStr: int -> string) (symbolUses: seq<FSharpSymbolUse>) =
symbolUses
|> Seq.filter (fun (su: FSharpSymbolUse) ->
match su.Symbol with
| :? FSharpMemberOrFunctionOrValue as fv when fv.IsExtensionMember ->
// Extension members should be taken into account even though they have a prefix (as they do most of the time)
true
| :? FSharpMemberOrFunctionOrValue as fv when not fv.IsModuleValueOrMember ->
// Local values can be ignored
false
| :? FSharpMemberOrFunctionOrValue when su.IsFromDefinition ->
// Value definitions should be ignored
false
| :? FSharpGenericParameter ->
// Generic parameters can be ignored, they never come into scope via 'open'
false
| :? FSharpUnionCase when su.IsFromDefinition -> false
| :? FSharpField as field when field.DeclaringEntity.IsSome && field.DeclaringEntity.Value.IsFSharpRecord ->
// Record fields are used in name resolution
true
| :? FSharpField as field when field.IsUnionCaseField -> false
| _ ->
// For the rest of symbols we pick only those which are the first part of a long ident, because it's they which are
// contained in opened namespaces / modules. For example, we pick `IO` from long ident `IO.File.OpenWrite` because
// it's `open System` which really brings it into scope.
let partialName =
QuickParse.GetPartialLongNameEx(getSourceLineStr su.Range.StartLine, su.Range.EndColumn - 1)
List.isEmpty partialName.QualifyingIdents)
|> Array.ofSeq
/// Split symbol uses into cases that are easy to handle (via DeclaringEntity) and those that don't have a good DeclaringEntity
let splitSymbolUses (symbolUses: FSharpSymbolUse[]) =
symbolUses
|> Array.partition (fun symbolUse ->
let symbol = symbolUse.Symbol
match symbol with
| :? FSharpMemberOrFunctionOrValue as f ->
match f.DeclaringEntity with
| Some ent when ent.IsNamespace || ent.IsFSharpModule -> true
| _ -> false
| _ -> false)
/// Given an 'open' statement, find fresh modules/namespaces referred to by that statement where there is some use of a revealed symbol
/// in the scope of the 'open' is from that module.
///
/// Performance will be roughly NumberOfOpenStatements x NumberOfSymbolUses
let isOpenStatementUsed
(symbolUses2: FSharpSymbolUse[])
(symbolUsesRangesByDeclaringEntity: Dictionary<FSharpEntity, range list>)
(usedModules: Dictionary<FSharpEntity, range list>)
(openStatement: OpenStatement)
=
// Don't re-check modules whose symbols are already known to have been used
let openedGroupsToExamine =
openStatement.OpenedGroups
|> List.choose (fun openedGroup ->
let openedEntitiesToExamine =
openedGroup.OpenedModules
|> Array.filter (fun openedEntity ->
not (
usedModules.BagExistsValueForKey(
openedEntity.Entity,
fun scope -> rangeContainsRange scope openStatement.AppliedScope
)
))
match openedEntitiesToExamine with
| [||] -> None
| _ when openedEntitiesToExamine |> Array.exists (fun x -> not x.IsNestedAutoOpen) ->
Some
{
OpenedModules = openedEntitiesToExamine
}
| _ -> None)
// Find the opened groups that are used by some symbol use
let newlyUsedOpenedGroups =
openedGroupsToExamine
|> List.filter (fun openedGroup ->
openedGroup.OpenedModules
|> Array.exists (fun openedEntity ->
symbolUsesRangesByDeclaringEntity.BagExistsValueForKey(
openedEntity.Entity,
fun symbolUseRange ->
rangeContainsRange openStatement.AppliedScope symbolUseRange
&& Position.posGt symbolUseRange.Start openStatement.Range.End
)
||
symbolUses2
|> Array.exists (fun symbolUse ->
rangeContainsRange openStatement.AppliedScope symbolUse.Range
&& Position.posGt symbolUse.Range.Start openStatement.Range.End
&& openedEntity.RevealedSymbolsContains symbolUse.Symbol)))
// Return them as interim used entities
let newlyOpenedModules =
newlyUsedOpenedGroups
|> List.collect (fun openedGroup -> openedGroup.OpenedModules |> List.ofArray)
for openedModule in newlyOpenedModules do
let scopes =
match usedModules.TryGetValue openedModule.Entity with
| true, scopes -> openStatement.AppliedScope :: scopes
| _ -> [ openStatement.AppliedScope ]
usedModules[openedModule.Entity] <- scopes
not newlyOpenedModules.IsEmpty
/// Incrementally filter out the open statements one by one. Filter those whose contents are referred to somewhere in the symbol uses.
/// Async to allow cancellation.
let rec filterOpenStatementsIncremental
symbolUses2
(symbolUsesRangesByDeclaringEntity: Dictionary<FSharpEntity, range list>)
(openStatements: OpenStatement list)
(usedModules: Dictionary<FSharpEntity, range list>)
acc
=
async {
match openStatements with
| openStatement :: rest ->
if isOpenStatementUsed symbolUses2 symbolUsesRangesByDeclaringEntity usedModules openStatement then
return! filterOpenStatementsIncremental symbolUses2 symbolUsesRangesByDeclaringEntity rest usedModules acc
else
// The open statement has not been used, include it in the results
return!
filterOpenStatementsIncremental
symbolUses2
symbolUsesRangesByDeclaringEntity
rest
usedModules
(openStatement :: acc)
| [] -> return List.rev acc
}
let entityHash =
HashIdentity.FromFunctions (fun (x: FSharpEntity) -> x.GetEffectivelySameAsHash()) (fun x y -> x.IsEffectivelySameAs(y))
/// Filter out the open statements whose contents are referred to somewhere in the symbol uses.
/// Async to allow cancellation.
let filterOpenStatements (symbolUses1: FSharpSymbolUse[], symbolUses2: FSharpSymbolUse[]) openStatements =
async {
// the key is a namespace or module, the value is a list of FSharpSymbolUse range of symbols defined in the
// namespace or module. So, it's just symbol uses ranges grouped by namespace or module where they are _defined_.
let symbolUsesRangesByDeclaringEntity =
Dictionary<FSharpEntity, range list>(entityHash)
for symbolUse in symbolUses1 do
match symbolUse.Symbol with
| :? FSharpMemberOrFunctionOrValue as f ->
match f.DeclaringEntity with
| Some entity when entity.IsNamespace || entity.IsFSharpModule ->
symbolUsesRangesByDeclaringEntity.BagAdd(entity, symbolUse.Range)
| _ -> ()
| _ -> ()
let! results =
filterOpenStatementsIncremental
symbolUses2
symbolUsesRangesByDeclaringEntity
(List.ofArray openStatements)
(Dictionary(entityHash))
[]
return results |> List.map (fun os -> os.Range)
}
/// Get the open statements whose contents are not referred to anywhere in the symbol uses.
/// Async to allow cancellation.
let getUnusedOpens (checkFileResults: FSharpCheckFileResults, getSourceLineStr: int -> string) : Async<range list> =
async {
let! ct = Async.CancellationToken
let symbolUses = checkFileResults.GetAllUsesOfAllSymbolsInFile(ct)
let symbolUses = filterSymbolUses getSourceLineStr symbolUses
let symbolUses = splitSymbolUses symbolUses
let openStatements = getOpenStatements checkFileResults.OpenDeclarations
return! filterOpenStatements symbolUses openStatements
}
module SimplifyNames =
type SimplifiableRange = { Range: range; RelativeName: string }
let getPlidLength (plid: string list) =
(plid |> List.sumBy String.length) + plid.Length
let getSimplifiableNames (checkFileResults: FSharpCheckFileResults, getSourceLineStr: int -> string) =
async {
let result = ResizeArray()
let! ct = Async.CancellationToken
let symbolUses =
checkFileResults.GetAllUsesOfAllSymbolsInFile(ct)
|> Seq.choose (fun symbolUse ->
if symbolUse.IsFromOpenStatement || symbolUse.IsFromDefinition then
None
else
let lineStr = getSourceLineStr symbolUse.Range.StartLine
// for `System.DateTime.Now` it returns ([|"System"; "DateTime"|], "Now")
let partialName =
QuickParse.GetPartialLongNameEx(lineStr, symbolUse.Range.EndColumn - 1)
// `symbolUse.Range.Start` does not point to the start of plid, it points to start of `name`,
// so we have to calculate plid's start ourselves.
let plidStartCol =
symbolUse.Range.EndColumn
- partialName.PartialIdent.Length
- (getPlidLength partialName.QualifyingIdents)
if partialName.PartialIdent = "" || List.isEmpty partialName.QualifyingIdents then
None
else
Some(symbolUse, partialName.QualifyingIdents, plidStartCol, partialName.PartialIdent))
|> Seq.groupBy (fun (symbolUse, _, plidStartCol, _) -> symbolUse.Range.StartLine, plidStartCol)
|> Seq.map (fun (_, xs) -> xs |> Seq.maxBy (fun (symbolUse, _, _, _) -> symbolUse.Range.EndColumn))
for symbolUse, plid, plidStartCol, name in symbolUses do
let posAtStartOfName =
let r = symbolUse.Range
if r.StartLine = r.EndLine then
Position.mkPos r.StartLine (r.EndColumn - name.Length)
else
r.Start
let getNecessaryPlid (plid: string list) : string list =
let rec loop (rest: string list) (current: string list) =
match rest with
| [] -> current
| headIdent :: restPlid ->
let res =
checkFileResults.IsRelativeNameResolvableFromSymbol(posAtStartOfName, current, symbolUse.Symbol)
if res then
current
else
loop restPlid (headIdent :: current)
loop (List.rev plid) []
let necessaryPlid = getNecessaryPlid plid
match necessaryPlid with
| necessaryPlid when necessaryPlid = plid -> ()
| necessaryPlid ->
let r = symbolUse.Range
let necessaryPlidStartCol =
r.EndColumn - name.Length - (getPlidLength necessaryPlid)
let unnecessaryRange =
withStartEnd (Position.mkPos r.StartLine plidStartCol) (Position.mkPos r.EndLine necessaryPlidStartCol) r
let relativeName = (String.concat "." plid) + "." + name
result.Add(
{
Range = unnecessaryRange
RelativeName = relativeName
}
)
return (result :> seq<_>)
}
module UnusedDeclarations =
let isPotentiallyUnusedDeclaration (symbol: FSharpSymbol) : bool =
match symbol with
// Determining that a record, DU or module is used anywhere requires inspecting all their enclosed entities (fields, cases and func / vals)
// for usages, which is too expensive to do. Hence we never gray them out.
| :? FSharpEntity as e when
e.IsFSharpRecord
|| e.IsFSharpUnion
|| e.IsInterface
|| e.IsFSharpModule
|| e.IsClass
|| e.IsNamespace
->
false
// FCS returns inconsistent results for override members; we're skipping these symbols.
| :? FSharpMemberOrFunctionOrValue as f when
f.IsOverrideOrExplicitInterfaceImplementation
|| f.IsBaseValue
|| f.IsConstructor
->
false
// Usage of DU case parameters does not give any meaningful feedback; we never gray them out.
| :? FSharpParameter -> false
| _ -> true
let getUnusedDeclarationRanges (symbolsUses: seq<FSharpSymbolUse>) (isScript: bool) =
let usages =
let usages =
symbolsUses
|> Seq.choose (fun su ->
if not su.IsFromDefinition then
su.Symbol.DeclarationLocation
else
None)
HashSet(usages)
symbolsUses
|> Seq.distinctBy (fun su -> su.Range) // Account for "hidden" uses, like a val in a member val definition. These aren't relevant
|> Seq.choose (fun (su: FSharpSymbolUse) ->
if
su.IsFromDefinition
&& su.Symbol.DeclarationLocation.IsSome
&& (isScript || su.IsPrivateToFile)
&& not (su.Symbol.DisplayName.StartsWith "_")
&& isPotentiallyUnusedDeclaration su.Symbol
then
Some(su, usages.Contains su.Symbol.DeclarationLocation.Value)
else
None)
|> Seq.groupBy (fun (defSu, _) -> defSu.Range)
|> Seq.filter (fun (_, defSus) -> defSus |> Seq.forall (fun (_, isUsed) -> not isUsed))
|> Seq.map (fun (m, _) -> m)
let getUnusedDeclarations (checkFileResults: FSharpCheckFileResults, isScriptFile: bool) =
async {
let! ct = Async.CancellationToken
let allSymbolUsesInFile = checkFileResults.GetAllUsesOfAllSymbolsInFile(ct)
let unusedRanges = getUnusedDeclarationRanges allSymbolUsesInFile isScriptFile
return unusedRanges
}
module UnnecessaryParentheses =
open System
let (|Ident|) (ident: Ident) = ident.idText
/// Represents an expression's precedence, or,
/// for a few few types of expression whose exact
/// kind can be significant, the expression's exact kind.
///
/// Use Precedence.sameKind to determine whether two expressions
/// have the same kind. Use Precedence.compare to compare two
/// expressions' precedence. Avoid using relational operators or the
/// built-in compare function on this type.
type Precedence =
/// yield, yield!, return, return!
| Low
/// <-
| Set
/// :=
| ColonEquals
/// ,
| Comma
/// or, ||
///
/// Refers to the exact operators or and ||.
/// Instances with leading dots or question marks or trailing characters are parsed as Bar instead.
| BarBar
/// &, &&
///
/// Refers to the exact operators & and &&.
/// Instances with leading dots or question marks or trailing characters are parsed as Amp instead.
| AmpAmp
/// :?>
| Downcast
/// :>
| Upcast
/// =…
| Eq
/// |…
| Bar
/// &…
| Amp
/// $…
| Dollar
/// >…
| Greater
/// <…
| Less
/// !=…
| BangEq
/// ^…
| Hat
/// @…
| At
/// ::
| Cons
/// :?
| TypeTest
/// -…
| Sub
/// +…
| Add
/// %…
| Mod
/// /…
| Div
/// *…
| Mul
/// **…
| Exp
/// - x
| UnaryPrefix
/// f x
| Apply
/// -x, !… x, ~~… x
| High
// x.y
| Dot
module Precedence =
/// Returns true only if the two expressions are of the
/// exact same kind. E.g., Add = Add and Sub = Sub,
/// but Add <> Sub, even though their precedence compares equally.
let sameKind prec1 prec2 = prec1 = prec2
/// Compares two expressions' precedence.
let compare prec1 prec2 =
match prec1, prec2 with
| Dot, Dot -> 0
| Dot, _ -> 1
| _, Dot -> -1
| High, High -> 0
| High, _ -> 1
| _, High -> -1
| Apply, Apply -> 0
| Apply, _ -> 1
| _, Apply -> -1
| UnaryPrefix, UnaryPrefix -> 0
| UnaryPrefix, _ -> 1
| _, UnaryPrefix -> -1
| Exp, Exp -> 0
| Exp, _ -> 1
| _, Exp -> -1
| (Mod | Div | Mul), (Mod | Div | Mul) -> 0
| (Mod | Div | Mul), _ -> 1
| _, (Mod | Div | Mul) -> -1
| (Sub | Add), (Sub | Add) -> 0
| (Sub | Add), _ -> 1
| _, (Sub | Add) -> -1
| TypeTest, TypeTest -> 0
| TypeTest, _ -> 1
| _, TypeTest -> -1
| Cons, Cons -> 0
| Cons, _ -> 1
| _, Cons -> -1
| (Hat | At), (Hat | At) -> 0
| (Hat | At), _ -> 1
| _, (Hat | At) -> -1
| (Eq | Bar | Amp | Dollar | Greater | Less | BangEq), (Eq | Bar | Amp | Dollar | Greater | Less | BangEq) -> 0
| (Eq | Bar | Amp | Dollar | Greater | Less | BangEq), _ -> 1
| _, (Eq | Bar | Amp | Dollar | Greater | Less | BangEq) -> -1
| (Downcast | Upcast), (Downcast | Upcast) -> 0
| (Downcast | Upcast), _ -> 1
| _, (Downcast | Upcast) -> -1
| AmpAmp, AmpAmp -> 0
| AmpAmp, _ -> 1
| _, AmpAmp -> -1
| BarBar, BarBar -> 0
| BarBar, _ -> 1
| _, BarBar -> -1
| Comma, Comma -> 0
| Comma, _ -> 1
| _, Comma -> -1
| ColonEquals, ColonEquals -> 0
| ColonEquals, _ -> 1
| _, ColonEquals -> -1
| Set, Set -> 0
| Set, _ -> 1
| _, Set -> -1
| Low, Low -> 0
/// Associativity/association.
type Assoc =
/// Non-associative or no association.
| Non
/// Left-associative or left-hand association.
| Left
/// Right-associative or right-hand association.
| Right
module Assoc =
let ofPrecedence precedence =
match precedence with
| Low -> Non
| Set -> Non
| ColonEquals -> Right
| Comma -> Non
| BarBar -> Left
| AmpAmp -> Left
| Upcast
| Downcast -> Right
| Eq
| Bar
| Amp
| Dollar
| Greater
| Less
| BangEq -> Left
| At
| Hat -> Right
| Cons -> Right
| TypeTest -> Non
| Add
| Sub -> Left
| Mul
| Div
| Mod -> Left
| Exp -> Right
| UnaryPrefix -> Left
| Apply -> Left
| High -> Left
| Dot -> Left
/// Matches if the two expressions or patterns refer to the same object.
[<return: Struct>]
let inline (|Is|_|) (inner1: 'a) (inner2: 'a) =
if obj.ReferenceEquals(inner1, inner2) then
ValueSome Is
else
ValueNone
module SynExpr =
open FSharp.Compiler.SyntaxTrivia
/// See atomicExprAfterType in pars.fsy.
[<return: Struct>]
let (|AtomicExprAfterType|_|) expr =
match expr with
| SynExpr.Paren _
| SynExpr.Quote _
| SynExpr.Const _
| SynExpr.Tuple(isStruct = true)
| SynExpr.Record _
| SynExpr.AnonRecd _
| SynExpr.InterpolatedString _
| SynExpr.Null _
| SynExpr.ArrayOrList(isArray = true)
| SynExpr.ArrayOrListComputed(isArray = true) -> ValueSome AtomicExprAfterType
| _ -> ValueNone
/// Matches if the given expression represents a high-precedence
/// function application, e.g.,
///
/// f x
///
/// (+) x y
[<return: Struct>]
let (|HighPrecedenceApp|_|) expr =
match expr with
| SynExpr.App (isInfix = false; funcExpr = SynExpr.Ident _)
| SynExpr.App (isInfix = false; funcExpr = SynExpr.LongIdent _)
| SynExpr.App (isInfix = false; funcExpr = SynExpr.App(isInfix = false)) -> ValueSome HighPrecedenceApp
| _ -> ValueNone
module FuncExpr =
/// Matches when the given funcExpr is a direct application
/// of a symbolic operator, e.g., -, _not_ (~-).
[<return: Struct>]
let (|SymbolicOperator|_|) funcExpr =
match funcExpr with
| SynExpr.LongIdent(longDotId = SynLongIdent (trivia = trivia)) ->
let rec tryPick =
function
| [] -> ValueNone
| Some (IdentTrivia.OriginalNotation op) :: _ -> ValueSome op
| _ :: rest -> tryPick rest
tryPick trivia
| _ -> ValueNone
/// Matches when the given expression is a prefix operator application, e.g.,
///
/// -x
///
/// ~~~x
[<return: Struct>]
let (|PrefixApp|_|) expr : Precedence voption =
match expr with
| SynExpr.App (isInfix = false; funcExpr = funcExpr & FuncExpr.SymbolicOperator op; argExpr = argExpr) ->
if funcExpr.Range.IsAdjacentTo argExpr.Range then
ValueSome High
else
assert (op.Length > 0)
match op[0] with
| '!'
| '~' -> ValueSome High
| _ -> ValueSome UnaryPrefix
| SynExpr.AddressOf (expr = expr; opRange = opRange) ->
if opRange.IsAdjacentTo expr.Range then
ValueSome High
else
ValueSome UnaryPrefix
| _ -> ValueNone
/// Tries to parse the given original notation as a symbolic infix operator.
[<return: Struct>]
let (|SymbolPrec|_|) (originalNotation: string) =
// Trim any leading dots or question marks from the given symbolic operator.
// Leading dots or question marks have no effect on operator precedence or associativity
// with the exception of &, &&, and ||.
let ignoredLeadingChars = ".?".AsSpan()
let trimmed = originalNotation.AsSpan().TrimStart ignoredLeadingChars
assert (trimmed.Length > 0)
match trimmed[0], originalNotation with
| _, ":=" -> ValueSome ColonEquals
| _, ("||" | "or") -> ValueSome BarBar
| _, ("&" | "&&") -> ValueSome AmpAmp
| '|', _ -> ValueSome Bar
| '&', _ -> ValueSome Amp
| '<', _ -> ValueSome Less
| '>', _ -> ValueSome Greater
| '=', _ -> ValueSome Eq
| '$', _ -> ValueSome Dollar
| '!', _ when trimmed.Length > 1 && trimmed[1] = '=' -> ValueSome BangEq
| '^', _ -> ValueSome Hat
| '@', _ -> ValueSome At
| _, "::" -> ValueSome Cons
| '+', _ -> ValueSome Add
| '-', _ -> ValueSome Sub
| '/', _ -> ValueSome Div
| '%', _ -> ValueSome Mod
| '*', _ when trimmed.Length > 1 && trimmed[1] = '*' -> ValueSome Exp
| '*', _ -> ValueSome Mul
| _ -> ValueNone
/// Any expressions in which the removal of parens would
/// lead to something like the following that would be
/// confused by the parser with a type parameter application:
///
/// x<y>z
///
/// x<y,y>z
[<return: Struct>]
let rec (|ConfusableWithTypeApp|_|) synExpr =
match synExpr with
| SynExpr.Paren(expr = ConfusableWithTypeApp)
| SynExpr.App(funcExpr = ConfusableWithTypeApp)
| SynExpr.App (isInfix = true; funcExpr = FuncExpr.SymbolicOperator (SymbolPrec Greater); argExpr = ConfusableWithTypeApp) ->
ValueSome ConfusableWithTypeApp
| SynExpr.App (isInfix = true; funcExpr = funcExpr & FuncExpr.SymbolicOperator (SymbolPrec Less); argExpr = argExpr) when
argExpr.Range.IsAdjacentTo funcExpr.Range
->
ValueSome ConfusableWithTypeApp
| SynExpr.Tuple (exprs = exprs) ->
let rec anyButLast =
function
| _ :: []
| [] -> ValueNone
| ConfusableWithTypeApp :: _ -> ValueSome ConfusableWithTypeApp
| _ :: tail -> anyButLast tail
anyButLast exprs
| _ -> ValueNone
/// Matches when the expression represents the infix application of a symbolic operator.
///
/// (x λ y) ρ z
///
/// x λ (y ρ z)
[<return: Struct>]
let (|InfixApp|_|) synExpr : struct (Precedence * Assoc) voption =
match synExpr with
| SynExpr.App(funcExpr = SynExpr.App (isInfix = true; funcExpr = FuncExpr.SymbolicOperator (SymbolPrec prec))) ->
ValueSome(prec, Right)
| SynExpr.App (isInfix = true; funcExpr = FuncExpr.SymbolicOperator (SymbolPrec prec)) -> ValueSome(prec, Left)
| SynExpr.Upcast _ -> ValueSome(Upcast, Left)
| SynExpr.Downcast _ -> ValueSome(Downcast, Left)
| SynExpr.TypeTest _ -> ValueSome(TypeTest, Left)
| _ -> ValueNone
/// Returns the given expression's precedence and the side of the inner expression,
/// if applicable.
[<return: Struct>]
let (|OuterBinaryExpr|_|) inner outer : struct (Precedence * Assoc) voption =
match outer with
| SynExpr.YieldOrReturn _
| SynExpr.YieldOrReturnFrom _ -> ValueSome(Low, Right)
| SynExpr.Tuple(exprs = SynExpr.Paren(expr = Is inner) :: _) -> ValueSome(Comma, Left)
| SynExpr.Tuple _ -> ValueSome(Comma, Right)
| InfixApp (Cons, side) -> ValueSome(Cons, side)
| SynExpr.Assert _
| SynExpr.Lazy _
| SynExpr.InferredUpcast _
| SynExpr.InferredDowncast _ -> ValueSome(Apply, Non)
| PrefixApp prec -> ValueSome(prec, Non)
| InfixApp (prec, side) -> ValueSome(prec, side)
| SynExpr.App(argExpr = SynExpr.ComputationExpr _) -> ValueSome(UnaryPrefix, Left)
| SynExpr.App(funcExpr = SynExpr.Paren(expr = SynExpr.App _)) -> ValueSome(Apply, Left)
| SynExpr.App _ -> ValueSome(Apply, Non)
| SynExpr.DotSet(targetExpr = SynExpr.Paren(expr = Is inner)) -> ValueSome(Dot, Left)
| SynExpr.DotSet(rhsExpr = SynExpr.Paren(expr = Is inner)) -> ValueSome(Set, Right)
| SynExpr.DotIndexedSet(objectExpr = SynExpr.Paren(expr = Is inner))
| SynExpr.DotNamedIndexedPropertySet(targetExpr = SynExpr.Paren(expr = Is inner)) -> ValueSome(Dot, Left)
| SynExpr.DotIndexedSet(valueExpr = SynExpr.Paren(expr = Is inner))
| SynExpr.DotNamedIndexedPropertySet(rhsExpr = SynExpr.Paren(expr = Is inner)) -> ValueSome(Set, Right)
| SynExpr.LongIdentSet(expr = SynExpr.Paren(expr = Is inner)) -> ValueSome(Set, Right)
| SynExpr.Set _ -> ValueSome(Set, Non)
| SynExpr.DotGet _ -> ValueSome(Dot, Left)
| SynExpr.DotIndexedGet(objectExpr = SynExpr.Paren(expr = Is inner)) -> ValueSome(Dot, Left)
| _ -> ValueNone
/// Matches a SynExpr.App nested in a sequence of dot-gets.
///
/// x.M.N().O
[<return: Struct>]
let (|NestedApp|_|) expr =
let rec loop =
function
| SynExpr.DotGet (expr = expr)
| SynExpr.DotIndexedGet (objectExpr = expr) -> loop expr
| SynExpr.App _ -> ValueSome NestedApp
| _ -> ValueNone
loop expr
/// Returns the given expression's precedence, if applicable.
[<return: Struct>]
let (|InnerBinaryExpr|_|) expr : Precedence voption =
match expr with
| SynExpr.Tuple(isStruct = false) -> ValueSome Comma
| SynExpr.DotGet(expr = NestedApp)
| SynExpr.DotIndexedGet(objectExpr = NestedApp) -> ValueSome Apply
| SynExpr.DotGet _
| SynExpr.DotIndexedGet _ -> ValueSome Dot
| PrefixApp prec -> ValueSome prec
| InfixApp (prec, _) -> ValueSome prec
| SynExpr.App _
| SynExpr.Assert _
| SynExpr.Lazy _
| SynExpr.For _
| SynExpr.ForEach _
| SynExpr.While _
| SynExpr.Do _
| SynExpr.New _
| SynExpr.InferredUpcast _
| SynExpr.InferredDowncast _ -> ValueSome Apply
| SynExpr.DotIndexedSet _
| SynExpr.DotNamedIndexedPropertySet _
| SynExpr.DotSet _ -> ValueSome Set
| _ -> ValueNone
module Dangling =
/// Returns the first matching nested right-hand target expression, if any.
let private dangling (target: SynExpr -> SynExpr option) =
let (|Target|_|) = target
let (|Last|) = List.last
let rec loop expr =
match expr with
| Target expr -> ValueSome expr
| SynExpr.Tuple (isStruct = false; exprs = Last expr)
| SynExpr.App (argExpr = expr)
| SynExpr.IfThenElse(elseExpr = Some expr)
| SynExpr.IfThenElse (ifExpr = expr)
| SynExpr.Sequential (expr2 = expr)
| SynExpr.YieldOrReturn (expr = expr)
| SynExpr.YieldOrReturnFrom (expr = expr)
| SynExpr.Set (rhsExpr = expr)
| SynExpr.DotSet (rhsExpr = expr)
| SynExpr.DotNamedIndexedPropertySet (rhsExpr = expr)
| SynExpr.DotIndexedSet (valueExpr = expr)
| SynExpr.LongIdentSet (expr = expr)
| SynExpr.LetOrUse (body = expr)
| SynExpr.Lambda (body = expr)
| SynExpr.Match(clauses = Last (SynMatchClause (resultExpr = expr)))
| SynExpr.MatchLambda(matchClauses = Last (SynMatchClause (resultExpr = expr)))
| SynExpr.MatchBang(clauses = Last (SynMatchClause (resultExpr = expr)))
| SynExpr.TryWith(withCases = Last (SynMatchClause (resultExpr = expr)))
| SynExpr.TryFinally (finallyExpr = expr) -> loop expr
| _ -> ValueNone
loop
/// Matches a dangling if-then construct.
[<return: Struct>]
let (|IfThen|_|) =
dangling (function
| SynExpr.IfThenElse _ as expr -> Some expr
| _ -> None)
/// Matches a dangling sequential expression.
[<return: Struct>]
let (|Sequential|_|) =
dangling (function
| SynExpr.Sequential _ as expr -> Some expr
| _ -> None)
/// Matches a dangling try-with or try-finally construct.
[<return: Struct>]
let (|Try|_|) =
dangling (function
| SynExpr.TryWith _
| SynExpr.TryFinally _ as expr -> Some expr
| _ -> None)
/// Matches a dangling match-like construct.
[<return: Struct>]
let (|Match|_|) =
dangling (function
| SynExpr.Match _
| SynExpr.MatchBang _
| SynExpr.MatchLambda _
| SynExpr.TryWith _
| SynExpr.Lambda _ as expr -> Some expr
| _ -> None)
/// Matches a nested dangling construct that could become problematic
/// if the surrounding parens were removed.
[<return: Struct>]
let (|Problematic|_|) =
dangling (function
| SynExpr.Lambda _
| SynExpr.MatchLambda _
| SynExpr.Match _
| SynExpr.MatchBang _
| SynExpr.TryWith _
| SynExpr.TryFinally _
| SynExpr.IfThenElse _
| SynExpr.Sequential _
| SynExpr.LetOrUse _
| SynExpr.Set _
| SynExpr.LongIdentSet _
| SynExpr.DotIndexedSet _
| SynExpr.DotNamedIndexedPropertySet _