forked from nosami/visualfsharp
/
ChangeToUpcast.fs
55 lines (42 loc) · 2.05 KB
/
ChangeToUpcast.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
// Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information.
namespace Microsoft.VisualStudio.FSharp.Editor
open System.Composition
open System.Threading.Tasks
open Microsoft.CodeAnalysis.Text
open Microsoft.CodeAnalysis.CodeFixes
[<ExportCodeFixProvider(FSharpConstants.FSharpLanguageName, Name = "ChangeToUpcast"); Shared>]
type internal FSharpChangeToUpcastCodeFixProvider() =
inherit CodeFixProvider()
let fixableDiagnosticIds = set ["FS3198"]
override __.FixableDiagnosticIds = Seq.toImmutableArray fixableDiagnosticIds
override this.RegisterCodeFixesAsync context : Task =
asyncMaybe {
let! sourceText = context.Document.GetTextAsync(context.CancellationToken)
let text = sourceText.GetSubText(context.Span).ToString()
// Only works if it's one or the other
let isDowncastOperator = text.Contains(":?>")
let isDowncastKeyword = text.Contains("downcast")
do! Option.guard ((isDowncastOperator || isDowncastKeyword) && not (isDowncastOperator && isDowncastKeyword))
let replacement =
if isDowncastOperator then
text.Replace(":?>", ":>")
else
text.Replace("downcast", "upcast")
let title =
if isDowncastOperator then
SR.UseUpcastOperator()
else
SR.UseUpcastKeyword()
let diagnostics =
context.Diagnostics
|> Seq.filter (fun x -> fixableDiagnosticIds |> Set.contains x.Id)
|> Seq.toImmutableArray
let codeFix =
CodeFixHelpers.createTextChangeCodeFix(
title,
context,
(fun () -> asyncMaybe.Return [| TextChange(context.Span, replacement) |]))
context.RegisterCodeFix(codeFix, diagnostics)
}
|> Async.Ignore
|> RoslynHelpers.StartAsyncUnitAsTask(context.CancellationToken)