Skip to content

Add ConvertToF#LambdaSyntax code fixer #10637

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Dec 9, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions src/fsharp/service/ServiceUntypedParse.fs
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,30 @@ type FSharpParseFileResults(errors: FSharpErrorInfo[], input: ParsedInput option
member scope.ParseHadErrors = parseHadErrors

member scope.ParseTree = input

member scope.TryRangeOfParenEnclosingOpEqualsGreaterUsage opGreaterEqualPos =
let (|Ident|_|) ofName =
function | SynExpr.Ident ident when ident.idText = ofName -> Some ()
| _ -> None
let (|InfixAppOfOpEqualsGreater|_|) =
function | SynExpr.App(ExprAtomicFlag.NonAtomic, false, SynExpr.App(ExprAtomicFlag.NonAtomic, true, Ident "op_EqualsGreater", actualParamListExpr, _), actualLambdaBodyExpr, _) ->
Some (actualParamListExpr, actualLambdaBodyExpr)
| _ -> None

match scope.ParseTree with
| Some parseTree ->
AstTraversal.Traverse(opGreaterEqualPos, parseTree, { new AstTraversal.AstVisitorBase<_>() with
member _.VisitExpr(_, _, defaultTraverse, expr) =
match expr with
| SynExpr.Paren((InfixAppOfOpEqualsGreater(lambdaArgs, lambdaBody) as app), _, _, _) ->
Some (app.Range, lambdaArgs.Range, lambdaBody.Range)
| _ -> defaultTraverse expr
member _.VisitBinding(defaultTraverse, binding) =
match binding with
| SynBinding.Binding (_, SynBindingKind.NormalBinding, _, _, _, _, _, _, _, (InfixAppOfOpEqualsGreater(lambdaArgs, lambdaBody) as app), _, _) ->
Some(app.Range, lambdaArgs.Range, lambdaBody.Range)
| _ -> defaultTraverse binding })
| None -> None

member scope.TryRangeOfExprInYieldOrReturn pos =
match scope.ParseTree with
Expand Down
3 changes: 3 additions & 0 deletions src/fsharp/service/ServiceUntypedParse.fsi
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,9 @@ type public FSharpParseFileResults =
/// The syntax tree resulting from the parse
member ParseTree : ParsedInput option

/// Attempts to find the range of an attempted lambda expression or pattern, the argument range, and the expr range when writing a C#-style "lambda" (which is actually an operator application)
member TryRangeOfParenEnclosingOpEqualsGreaterUsage: opGreaterEqualPos: pos -> Option<range * range * range>

/// Attempts to find the range of an expression `expr` contained in a `yield expr` or `return expr` expression (and bang-variants).
member TryRangeOfExprInYieldOrReturn: pos: pos -> Option<range>

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22755,6 +22755,7 @@ FSharp.Compiler.SourceCodeServices.FSharpParseFileResults: FSharp.Compiler.Sourc
FSharp.Compiler.SourceCodeServices.FSharpParseFileResults: Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Range+range] TryRangeOfRefCellDereferenceContainingPos(pos)
FSharp.Compiler.SourceCodeServices.FSharpParseFileResults: Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Range+range] TryRangeOfRecordExpressionContainingPos(pos)
FSharp.Compiler.SourceCodeServices.FSharpParseFileResults: Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Range+range] TryRangeOfExprInYieldOrReturn(pos)
FSharp.Compiler.SourceCodeServices.FSharpParseFileResults: Microsoft.FSharp.Core.FSharpOption`1[System.Tuple`3[FSharp.Compiler.Range+range,FSharp.Compiler.Range+range,FSharp.Compiler.Range+range]] TryRangeOfParenEnclosingOpEqualsGreaterUsage(pos)
FSharp.Compiler.SourceCodeServices.FSharpParseFileResults: Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.Range+range] ValidateBreakpointLocation(pos)
FSharp.Compiler.SourceCodeServices.FSharpParseFileResults: Microsoft.FSharp.Core.FSharpOption`1[FSharp.Compiler.SourceCodeServices.FSharpNoteworthyParamInfoLocations] FindNoteworthyParamInfoLocations(pos)
FSharp.Compiler.SourceCodeServices.FSharpParseFileResults: Boolean IsPositionContainedInACurriedParameter(pos)
Expand Down
56 changes: 55 additions & 1 deletion tests/service/ServiceUntypedParseTests.fs
Original file line number Diff line number Diff line change
Expand Up @@ -407,4 +407,58 @@ let f x =
|> tups
|> shouldEqual ((3, 11), (3, 12))
| None ->
Assert.Fail("Expected to get a range back, but got none.")
Assert.Fail("Expected to get a range back, but got none.")

[<Test>]
let ``TryRangeOfParenEnclosingOpEqualsGreaterUsage - not correct operator``() =
let source = """
let x = y |> y + 1
"""
let parseFileResults, _ = getParseAndCheckResults source
let res = parseFileResults.TryRangeOfParenEnclosingOpEqualsGreaterUsage (mkPos 2 8)
Assert.True(res.IsNone, "Expected not to find any ranges.")

[<Test>]
let ``TryRangeOfParenEnclosingOpEqualsGreaterUsage - error arg pos``() =
let source = """
let x = y => y + 1
"""
let parseFileResults, _ = getParseAndCheckResults source
let res = parseFileResults.TryRangeOfParenEnclosingOpEqualsGreaterUsage (mkPos 2 8)
match res with
| Some (overallRange, argRange, exprRange) ->
[overallRange; argRange; exprRange]
|> List.map tups
|> shouldEqual [((2, 8), (2, 18)); ((2, 8), (2, 9)); ((2, 13), (2, 18))]
| None ->
Assert.Fail("Expected to get a range back, but got none.")

[<Test>]
let ``TryRangeOfParenEnclosingOpEqualsGreaterUsage - error expr pos``() =
let source = """
let x = y => y + 1
"""
let parseFileResults, _ = getParseAndCheckResults source
let res = parseFileResults.TryRangeOfParenEnclosingOpEqualsGreaterUsage (mkPos 2 13)
match res with
| Some (overallRange, argRange, exprRange) ->
[overallRange; argRange; exprRange]
|> List.map tups
|> shouldEqual [((2, 8), (2, 18)); ((2, 8), (2, 9)); ((2, 13), (2, 18))]
| None ->
Assert.Fail("Expected to get a range back, but got none.")

[<Test>]
let ``TryRangeOfParenEnclosingOpEqualsGreaterUsage - parenthesized lambda``() =
let source = """
[1..10] |> List.map (x => x + 1)
"""
let parseFileResults, _ = getParseAndCheckResults source
let res = parseFileResults.TryRangeOfParenEnclosingOpEqualsGreaterUsage (mkPos 2 21)
match res with
| Some (overallRange, argRange, exprRange) ->
[overallRange; argRange; exprRange]
|> List.map tups
|> shouldEqual [((2, 21), (2, 31)); ((2, 21), (2, 22)); ((2, 26), (2, 31))]
| None ->
Assert.Fail("Expected to get a range back, but got none.")
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
// 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 Microsoft.CodeAnalysis.Text
open Microsoft.CodeAnalysis.CodeFixes

[<ExportCodeFixProvider(FSharpConstants.FSharpLanguageName, Name = "ConvertCSharpLambdaToFSharpLambda"); Shared>]
type internal FSharpConvertCSharpLambdaToFSharpLambdaCodeFixProvider
[<ImportingConstructor>]
(
checkerProvider: FSharpCheckerProvider,
projectInfoManager: FSharpProjectOptionsManager
) =
inherit CodeFixProvider()

static let userOpName = "ConvertCSharpLambdaToFSharpLambda"
let fixableDiagnosticIds = set ["FS0039"; "FS0043"]

override _.FixableDiagnosticIds = Seq.toImmutableArray fixableDiagnosticIds

override _.RegisterCodeFixesAsync context =
asyncMaybe {
let! sourceText = context.Document.GetTextAsync(context.CancellationToken)
let! parsingOptions, _ = projectInfoManager.TryGetOptionsForEditingDocumentOrProject(context.Document, context.CancellationToken, userOpName)
let! parseResults = checkerProvider.Checker.ParseFile(context.Document.FilePath, sourceText.ToFSharpSourceText(), parsingOptions, userOpName) |> liftAsync

let errorRange = RoslynHelpers.TextSpanToFSharpRange(context.Document.FilePath, context.Span, sourceText)

let! fullParenRange, lambdaArgRange, lambdaBodyRange = parseResults.TryRangeOfParenEnclosingOpEqualsGreaterUsage errorRange.Start

let! fullParenSpan = RoslynHelpers.TryFSharpRangeToTextSpan(sourceText, fullParenRange)
let! lambdaArgSpan = RoslynHelpers.TryFSharpRangeToTextSpan(sourceText, lambdaArgRange)
let! lambdaBodySpan = RoslynHelpers.TryFSharpRangeToTextSpan(sourceText, lambdaBodyRange)

let replacement =
let argText = sourceText.GetSubText(lambdaArgSpan).ToString()
let bodyText = sourceText.GetSubText(lambdaBodySpan).ToString()
TextChange(fullParenSpan, "fun " + argText + " -> " + bodyText)

let diagnostics =
context.Diagnostics
|> Seq.filter (fun x -> fixableDiagnosticIds |> Set.contains x.Id)
|> Seq.toImmutableArray

let title = SR.UseFSharpLambda()

let codeFix =
CodeFixHelpers.createTextChangeCodeFix(
title,
context,
(fun () -> asyncMaybe.Return [| replacement |]))

context.RegisterCodeFix(codeFix, diagnostics)
}
|> Async.Ignore
|> RoslynHelpers.StartAsyncUnitAsTask(context.CancellationToken)
1 change: 1 addition & 0 deletions vsintegration/src/FSharp.Editor/FSharp.Editor.fsproj
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,7 @@
<Compile Include="Commands\FsiCommandService.fs" />
<Compile Include="Commands\XmlDocCommandService.fs" />
<Compile Include="CodeFix\CodeFixHelpers.fs" />
<Compile Include="CodeFix\ConvertCSharpLambdaToFSharpLambda.fs" />
<Compile Include="CodeFix\RemoveReturnOrYield.fs" />
<Compile Include="CodeFix\ConvertToAnonymousRecord.fs" />
<Compile Include="CodeFix\UseMutationWhenValueIsMutable.fs" />
Expand Down
3 changes: 3 additions & 0 deletions vsintegration/src/FSharp.Editor/FSharp.Editor.resx
Original file line number Diff line number Diff line change
Expand Up @@ -261,4 +261,7 @@
<data name="UseMutationWhenValueIsMutable" xml:space="preserve">
<value>Use '&lt;-' to mutate value</value>
</data>
<data name="UseFSharpLambda" xml:space="preserve">
<value>Use F# lambda syntax</value>
</data>
</root>
5 changes: 5 additions & 0 deletions vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.cs.xlf
Original file line number Diff line number Diff line change
Expand Up @@ -217,6 +217,11 @@
<target state="translated">Formátování</target>
<note />
</trans-unit>
<trans-unit id="UseFSharpLambda">
<source>Use F# lambda syntax</source>
<target state="new">Use F# lambda syntax</target>
<note />
</trans-unit>
<trans-unit id="UseMutationWhenValueIsMutable">
<source>Use '&lt;-' to mutate value</source>
<target state="new">Use '&lt;-' to mutate value</target>
Expand Down
5 changes: 5 additions & 0 deletions vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.de.xlf
Original file line number Diff line number Diff line change
Expand Up @@ -217,6 +217,11 @@
<target state="translated">Formatierung</target>
<note />
</trans-unit>
<trans-unit id="UseFSharpLambda">
<source>Use F# lambda syntax</source>
<target state="new">Use F# lambda syntax</target>
<note />
</trans-unit>
<trans-unit id="UseMutationWhenValueIsMutable">
<source>Use '&lt;-' to mutate value</source>
<target state="new">Use '&lt;-' to mutate value</target>
Expand Down
5 changes: 5 additions & 0 deletions vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.es.xlf
Original file line number Diff line number Diff line change
Expand Up @@ -217,6 +217,11 @@
<target state="translated">Formato</target>
<note />
</trans-unit>
<trans-unit id="UseFSharpLambda">
<source>Use F# lambda syntax</source>
<target state="new">Use F# lambda syntax</target>
<note />
</trans-unit>
<trans-unit id="UseMutationWhenValueIsMutable">
<source>Use '&lt;-' to mutate value</source>
<target state="new">Use '&lt;-' to mutate value</target>
Expand Down
5 changes: 5 additions & 0 deletions vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.fr.xlf
Original file line number Diff line number Diff line change
Expand Up @@ -217,6 +217,11 @@
<target state="translated">Mise en forme</target>
<note />
</trans-unit>
<trans-unit id="UseFSharpLambda">
<source>Use F# lambda syntax</source>
<target state="new">Use F# lambda syntax</target>
<note />
</trans-unit>
<trans-unit id="UseMutationWhenValueIsMutable">
<source>Use '&lt;-' to mutate value</source>
<target state="new">Use '&lt;-' to mutate value</target>
Expand Down
5 changes: 5 additions & 0 deletions vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.it.xlf
Original file line number Diff line number Diff line change
Expand Up @@ -217,6 +217,11 @@
<target state="translated">Formattazione</target>
<note />
</trans-unit>
<trans-unit id="UseFSharpLambda">
<source>Use F# lambda syntax</source>
<target state="new">Use F# lambda syntax</target>
<note />
</trans-unit>
<trans-unit id="UseMutationWhenValueIsMutable">
<source>Use '&lt;-' to mutate value</source>
<target state="new">Use '&lt;-' to mutate value</target>
Expand Down
5 changes: 5 additions & 0 deletions vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.ja.xlf
Original file line number Diff line number Diff line change
Expand Up @@ -217,6 +217,11 @@
<target state="translated">書式設定</target>
<note />
</trans-unit>
<trans-unit id="UseFSharpLambda">
<source>Use F# lambda syntax</source>
<target state="new">Use F# lambda syntax</target>
<note />
</trans-unit>
<trans-unit id="UseMutationWhenValueIsMutable">
<source>Use '&lt;-' to mutate value</source>
<target state="new">Use '&lt;-' to mutate value</target>
Expand Down
5 changes: 5 additions & 0 deletions vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.ko.xlf
Original file line number Diff line number Diff line change
Expand Up @@ -217,6 +217,11 @@
<target state="translated">서식</target>
<note />
</trans-unit>
<trans-unit id="UseFSharpLambda">
<source>Use F# lambda syntax</source>
<target state="new">Use F# lambda syntax</target>
<note />
</trans-unit>
<trans-unit id="UseMutationWhenValueIsMutable">
<source>Use '&lt;-' to mutate value</source>
<target state="new">Use '&lt;-' to mutate value</target>
Expand Down
5 changes: 5 additions & 0 deletions vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.pl.xlf
Original file line number Diff line number Diff line change
Expand Up @@ -217,6 +217,11 @@
<target state="translated">Formatowanie</target>
<note />
</trans-unit>
<trans-unit id="UseFSharpLambda">
<source>Use F# lambda syntax</source>
<target state="new">Use F# lambda syntax</target>
<note />
</trans-unit>
<trans-unit id="UseMutationWhenValueIsMutable">
<source>Use '&lt;-' to mutate value</source>
<target state="new">Use '&lt;-' to mutate value</target>
Expand Down
5 changes: 5 additions & 0 deletions vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.pt-BR.xlf
Original file line number Diff line number Diff line change
Expand Up @@ -217,6 +217,11 @@
<target state="translated">Formatação</target>
<note />
</trans-unit>
<trans-unit id="UseFSharpLambda">
<source>Use F# lambda syntax</source>
<target state="new">Use F# lambda syntax</target>
<note />
</trans-unit>
<trans-unit id="UseMutationWhenValueIsMutable">
<source>Use '&lt;-' to mutate value</source>
<target state="new">Use '&lt;-' to mutate value</target>
Expand Down
5 changes: 5 additions & 0 deletions vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.ru.xlf
Original file line number Diff line number Diff line change
Expand Up @@ -217,6 +217,11 @@
<target state="translated">Форматирование</target>
<note />
</trans-unit>
<trans-unit id="UseFSharpLambda">
<source>Use F# lambda syntax</source>
<target state="new">Use F# lambda syntax</target>
<note />
</trans-unit>
<trans-unit id="UseMutationWhenValueIsMutable">
<source>Use '&lt;-' to mutate value</source>
<target state="new">Use '&lt;-' to mutate value</target>
Expand Down
5 changes: 5 additions & 0 deletions vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.tr.xlf
Original file line number Diff line number Diff line change
Expand Up @@ -217,6 +217,11 @@
<target state="translated">Biçimlendirme</target>
<note />
</trans-unit>
<trans-unit id="UseFSharpLambda">
<source>Use F# lambda syntax</source>
<target state="new">Use F# lambda syntax</target>
<note />
</trans-unit>
<trans-unit id="UseMutationWhenValueIsMutable">
<source>Use '&lt;-' to mutate value</source>
<target state="new">Use '&lt;-' to mutate value</target>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -217,6 +217,11 @@
<target state="translated">正在格式化</target>
<note />
</trans-unit>
<trans-unit id="UseFSharpLambda">
<source>Use F# lambda syntax</source>
<target state="new">Use F# lambda syntax</target>
<note />
</trans-unit>
<trans-unit id="UseMutationWhenValueIsMutable">
<source>Use '&lt;-' to mutate value</source>
<target state="new">Use '&lt;-' to mutate value</target>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -217,6 +217,11 @@
<target state="translated">格式化</target>
<note />
</trans-unit>
<trans-unit id="UseFSharpLambda">
<source>Use F# lambda syntax</source>
<target state="new">Use F# lambda syntax</target>
<note />
</trans-unit>
<trans-unit id="UseMutationWhenValueIsMutable">
<source>Use '&lt;-' to mutate value</source>
<target state="new">Use '&lt;-' to mutate value</target>
Expand Down