Repository navigation
Add a refactoring between fun x -> x.Prop and _.Prop
#20535
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
base: main
Are you sure you want to change the base?
Changes from all commits
2d659ca
9647915
adbc192
458eb68
8eae96c
82a217b
fe9cbc3
b527d97
67cb84d
81f238d
6594e89
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,39 @@ | ||
| module FSharp.Compiler.Service.Tests.SyntaxTreeOpsTests | ||
|
|
||
| open FSharp.Compiler.Service.Tests.Common | ||
| open FSharp.Compiler.Syntax | ||
| open FSharp.Compiler.SyntaxTreeOps | ||
| open Xunit | ||
|
|
||
| let private exprOf source = | ||
| match getParseResults source with | ||
| | ParsedInput.ImplFile(ParsedImplFileInput(contents = [ SynModuleOrNamespace(decls = [ SynModuleDecl.Expr(expr = expr) ]) ])) -> expr | ||
| | tree -> failwith $"Expected a single expression, got %A{tree}" | ||
|
|
||
| [<Theory>] | ||
| [<InlineData("x.P")>] | ||
| [<InlineData("x.A.B")>] | ||
| [<InlineData("x.M(y)")>] | ||
| [<InlineData("x.Xs[0]")>] | ||
| [<InlineData("x.Xs.[0]")>] | ||
| [<InlineData("x.M<int>()")>] | ||
| [<InlineData("x.M().P")>] | ||
| let ``tryPopUnaryArg splits the root off a chain that pushUnaryArg restores`` (source: string) = | ||
| let body = exprOf source | ||
|
|
||
| match tryPopUnaryArg body with | ||
| | ValueSome(struct (root, popped)) -> | ||
| Assert.Equal("x", root.idText) | ||
| Assert.Equal($"%A{body}", $"%A{pushUnaryArg popped root}") | ||
| | ValueNone -> Assert.Fail $"Expected {source} to have a root" | ||
|
|
||
| [<Theory>] | ||
| [<InlineData("f x.P")>] | ||
| [<InlineData("x.M y")>] | ||
| [<InlineData("x.P + 1")>] | ||
| [<InlineData("x")>] | ||
| [<InlineData("x[0]")>] | ||
| [<InlineData("(x.P)")>] | ||
| [<InlineData("x.")>] | ||
| let ``tryPopUnaryArg rejects what _. cannot express`` (source: string) = | ||
| Assert.True((tryPopUnaryArg (exprOf source)).IsNone) |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,208 @@ | ||
| // Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information. | ||
|
|
||
| namespace Microsoft.VisualStudio.FSharp.Editor | ||
|
|
||
| open System | ||
| open System.Composition | ||
|
|
||
| open Microsoft.CodeAnalysis.CodeActions | ||
| open Microsoft.CodeAnalysis.CodeRefactorings | ||
| open Microsoft.CodeAnalysis.Text | ||
| open Microsoft.VisualStudio.FSharp.Editor.Telemetry | ||
|
|
||
| open FSharp.Compiler.Syntax | ||
| open FSharp.Compiler.SyntaxTreeOps | ||
| open FSharp.Compiler.SyntaxTrivia | ||
| open FSharp.Compiler.Text | ||
|
|
||
| open CancellableTasks | ||
|
|
||
| [<RequireQualifiedAccess>] | ||
| module private DotLambdaConversion = | ||
|
|
||
| [<NoComparison; NoEquality>] | ||
| type Conversion = | ||
| { | ||
| Title: string | ||
| Direction: string | ||
| Change: TextChange | ||
| } | ||
|
|
||
| let hasName (name: string) (ident: Ident) = | ||
| String.Equals(ident.idText, name, StringComparison.Ordinal) | ||
|
|
||
| let identifiersIn (body: SynExpr) = | ||
| ([], [ SyntaxNode.SynExpr body ]) | ||
| ||> SyntaxNodes.fold (fun identifiers _ node -> | ||
| match node with | ||
| | SyntaxNode.SynExpr(SynExpr.Ident ident) | ||
| | SyntaxNode.SynExpr(SynExpr.LongIdent(longDotId = SynLongIdent(id = ident :: _))) | ||
| | SyntaxNode.SynExpr(SynExpr.LongIdentSet(longDotId = SynLongIdent(id = ident :: _))) | ||
| | SyntaxNode.SynExpr(SynExpr.NamedIndexedPropertySet(longDotId = SynLongIdent(id = ident :: _))) | ||
| | SyntaxNode.SynPat(SynPat.Named(ident = SynIdent(ident, _))) -> ident :: identifiers | ||
| | _ -> identifiers) | ||
|
|
||
| let parameterNameFor (body: SynExpr) = | ||
| let used = identifiersIn body | ||
|
|
||
| Seq.initInfinite (fun i -> if i = 0 then "x" else $"x{i}") | ||
| |> Seq.find (fun name -> not (List.exists (hasName name) used)) | ||
|
|
||
| let canBeCapturedByGeneratedArgument (ident: Ident) = | ||
| let prefix = "_arg" | ||
| let name = ident.idText | ||
|
|
||
| let rec isDigitsFrom i = | ||
| i = name.Length || (Char.IsDigit name[i] && isDigitsFrom (i + 1)) | ||
|
|
||
| name.Length > prefix.Length | ||
| && name.StartsWith(prefix, StringComparison.Ordinal) | ||
| && isDigitsFrom prefix.Length | ||
|
|
||
| let hasCommentIn (comments: CommentTrivia list) (m: range) = | ||
| comments | ||
| |> List.exists (fun (CommentTrivia.LineComment comment | CommentTrivia.BlockComment comment) -> Range.rangeContainsRange m comment) | ||
|
|
||
| let rec lastOffsideSensitiveLine (expr: SynExpr) = | ||
| match expr with | ||
| | SynExpr.App(flag = ExprAtomicFlag.Atomic; funcExpr = func) -> lastOffsideSensitiveLine func | ||
| | SynExpr.DotGet(longDotId = longDotId) -> longDotId.Range.EndLine | ||
| | SynExpr.DotIndexedGet(dotRange = dot) -> dot.EndLine | ||
| | _ -> expr.Range.EndLine | ||
|
|
||
| let isInQuotation (path: SyntaxVisitorPath) = | ||
| path | ||
| |> List.exists (function | ||
| | SyntaxNode.SynExpr(SynExpr.Quote _) -> true | ||
| | _ -> false) | ||
|
|
||
| let rec isAppliedDirectly (expr: SynExpr) (path: SyntaxVisitorPath) = | ||
| match path with | ||
| | SyntaxNode.SynExpr(SynExpr.Paren _ as paren) :: outer -> isAppliedDirectly paren outer | ||
| | SyntaxNode.SynExpr(SynExpr.App(funcExpr = func)) :: _ -> obj.ReferenceEquals(func, expr) | ||
| | _ -> false | ||
|
|
||
| let isBlankBetween (sourceText: SourceText) start finish = | ||
| start <= finish | ||
| && String.IsNullOrWhiteSpace(sourceText.ToString(TextSpan.FromBounds(start, finish))) | ||
|
|
||
| [<return: Struct>] | ||
| let (|SoleParenthesizedLambdaArgument|_|) (sourceText: SourceText) (lambda: SynExpr) (lambdaSpan: TextSpan) (path: SyntaxVisitorPath) = | ||
| match path with | ||
| | SyntaxNode.SynExpr(SynExpr.Paren(expr = inner; leftParenRange = leftParen; rightParenRange = Some rightParen; range = parenRange) as paren) :: SyntaxNode.SynExpr(SynExpr.App( | ||
| flag = ExprAtomicFlag.NonAtomic; isInfix = false; argExpr = arg)) :: _ when | ||
| obj.ReferenceEquals(inner, lambda) | ||
| && obj.ReferenceEquals(arg, paren) | ||
| && isBlankBetween sourceText (RoslynHelpers.FSharpRangeToTextSpan(sourceText, leftParen)).End lambdaSpan.Start | ||
| && isBlankBetween sourceText lambdaSpan.End (RoslynHelpers.FSharpRangeToTextSpan(sourceText, rightParen)).Start | ||
| -> | ||
| ValueSome(RoslynHelpers.FSharpRangeToTextSpan(sourceText, parenRange)) | ||
| | _ -> ValueNone | ||
|
|
||
| let toShorthand (sourceText: SourceText) (path: SyntaxVisitorPath) (lambda: SynExpr) (root: Ident) = | ||
| let lambdaSpan = RoslynHelpers.FSharpRangeToTextSpan(sourceText, lambda.Range) | ||
| let rootEnd = RoslynHelpers.FSharpRangeToTextSpan(sourceText, root.idRange).End | ||
|
|
||
| match path with | ||
| | SoleParenthesizedLambdaArgument sourceText lambda lambdaSpan parenSpan -> | ||
| let chain = sourceText.ToString(TextSpan.FromBounds(rootEnd, lambdaSpan.End)) | ||
| TextChange(parenSpan, $"_{chain}") | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🤖🕵️ [P2] Valid multiline lambda becomes invalid shorthand (FS0010/FS3118). Reproduced with the HEAD editor helper and compiler; preserve continuation indentation relative to the receiver, or suppress this forward conversion. let lengths = [" a "] |> List.map (fun s ->
s.Trim()
.Length)
// Rewritten to:
let lengths = [" a "] |> List.map _.Trim()
.Length // FS0010, FS3118
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Fixed in 6df973f: lambda to shorthand is not offered when the member chain continues on a later line than the one it starts on, as in this example. Arguments that span lines still convert. New |
||
| | _ -> TextChange(TextSpan.FromBounds(lambdaSpan.Start, rootEnd), "_") | ||
|
abonie marked this conversation as resolved.
Resolved
|
||
|
|
||
| let toLambda (sourceText: SourceText) (path: SyntaxVisitorPath) (body: SynExpr) (range: range) (trivia: SynExprDotLambdaTrivia) = | ||
| let name = parameterNameFor body | ||
| let lambda = $"fun {name} -> {name}" | ||
|
|
||
| let underscore = | ||
| RoslynHelpers.FSharpRangeToTextSpan(sourceText, trivia.UnderscoreRange) | ||
|
|
||
| match path with | ||
| | SyntaxNode.SynExpr(SynExpr.Paren _) :: _ | ||
| | SyntaxNode.SynBinding _ :: _ -> TextChange(underscore, lambda) | ||
| | _ -> | ||
| let span = RoslynHelpers.FSharpRangeToTextSpan(sourceText, range) | ||
| let chain = sourceText.ToString(TextSpan.FromBounds(underscore.End, span.End)) | ||
| TextChange(span, $"({lambda}{chain})") | ||
|
|
||
|
abonie marked this conversation as resolved.
Resolved
|
||
| let tryFind (sourceText: SourceText) (position: pos) (parseTree: ParsedInput) = | ||
| let comments = | ||
| match parseTree with | ||
| | ParsedInput.ImplFile file -> file.Trivia.CodeComments | ||
| | ParsedInput.SigFile file -> file.Trivia.CodeComments | ||
|
|
||
| (position, parseTree) | ||
| ||> ParsedInput.tryPickLast (fun path node -> | ||
| match node with | ||
| | SyntaxNode.SynExpr(SynExpr.Lambda( | ||
| fromMethod = false | ||
| parsedData = Some([ SynPat.Named(ident = SynIdent(parameter, _); isThisVal = false; accessibility = None) ], body)) as lambda) when | ||
| not (isInQuotation path) && not (isAppliedDirectly lambda path) | ||
| -> | ||
| let identifiers = identifiersIn body | ||
|
|
||
| match tryPopUnaryArg body with | ||
| | ValueSome(struct (root, _)) when | ||
| hasName parameter.idText root | ||
| && (identifiers |> List.filter (hasName parameter.idText) |> List.length) = 1 | ||
| && not (List.exists canBeCapturedByGeneratedArgument identifiers) | ||
| && not (hasCommentIn comments (Range.withEnd root.idRange.End lambda.Range)) | ||
| && lastOffsideSensitiveLine body = root.idRange.StartLine | ||
| -> | ||
|
abonie marked this conversation as resolved.
Resolved
|
||
| Some | ||
| { | ||
| Title = SR.ConvertToShorthandLambda() | ||
| Direction = "shorthand" | ||
| Change = toShorthand sourceText path lambda root | ||
|
abonie marked this conversation as resolved.
Resolved
|
||
| } | ||
| | _ -> None | ||
|
|
||
| | SyntaxNode.SynExpr(SynExpr.DotLambda(expr = body; range = range; trivia = trivia)) when | ||
| not body.IsArbExprAndThusAlreadyReportedError | ||
|
abonie marked this conversation as resolved.
Resolved
|
||
| && not (isInQuotation path) | ||
| && lastOffsideSensitiveLine body = range.StartLine | ||
| -> | ||
| Some | ||
| { | ||
| Title = SR.ConvertToFunLambda() | ||
| Direction = "lambda" | ||
| Change = toLambda sourceText path body range trivia | ||
| } | ||
|
|
||
| | _ -> None) | ||
|
|
||
| [<ExportCodeRefactoringProvider(FSharpConstants.FSharpLanguageName, Name = "ConvertDotLambda"); Shared>] | ||
| type internal FSharpConvertDotLambdaRefactoring [<ImportingConstructor>] () = | ||
| inherit CodeRefactoringProvider() | ||
|
|
||
| override _.ComputeRefactoringsAsync context = | ||
| cancellableTask { | ||
| let document = context.Document | ||
|
|
||
| if not document.IsFSharpSignatureFile then | ||
| let! cancellationToken = CancellableTask.getCancellationToken () | ||
| let! sourceText = document.GetTextAsync cancellationToken | ||
|
|
||
| let! parseResults = document.GetFSharpParseResultsAsync(nameof FSharpConvertDotLambdaRefactoring) | ||
|
|
||
| let caret = sourceText.Lines.GetLinePosition context.Span.Start | ||
| let position = Position.fromZ caret.Line caret.Character | ||
|
|
||
| match DotLambdaConversion.tryFind sourceText position parseResults.ParseTree with | ||
| | Some conversion -> | ||
| let changedDocument = | ||
| cancellableTask { | ||
| TelemetryReporter.ReportSingleEvent( | ||
| TelemetryEvents.RefactoringActivated, | ||
| [| | ||
| "name", box (nameof FSharpConvertDotLambdaRefactoring) | ||
| "direction", box conversion.Direction | ||
| |] | ||
| ) | ||
|
|
||
| return document.WithText(sourceText.WithChanges conversion.Change) | ||
| } | ||
|
|
||
| context.RegisterRefactoring(CodeAction.Create(conversion.Title, changedDocument, conversion.Title)) | ||
| | None -> () | ||
| } | ||
| |> CancellableTask.startAsTask context.CancellationToken | ||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🤖🕵️ [P2] Silent capture across conditional-compilation configurations: converting lambda to shorthand with
ALTundefined changes[0]to[-1]whenALTis later enabled. Both versions compile; include inactive names in the capture checks or withhold the conversion.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🤖🕵️ Same for
_.X→ lambda: the generatedxcaptures the outerxin the inactive branch.With
ALT:[-1]→[0].