From eca584a04560b9002dfd5f68fffe74c1fcf95dfd Mon Sep 17 00:00:00 2001 From: Andrii Chebukin Date: Mon, 14 Sep 2026 16:33:21 +0200 Subject: [PATCH 01/17] Add a refactoring between reference and struct tuples Ctrl+. on a tuple expression, pattern or annotated tuple type converts it to the other kind and follows the value through the solution: annotations of values, parameters, record fields and function results it flows through, tuple patterns taking it apart, and the arguments and values flowing into it. Uses that cannot be followed (fst, snd, generic collections) are left for the compiler to report. CreateWithCodeAndDependency now tells FCS about both files, so the second file can be type-checked. Co-Authored-By: Claude Opus 5 (1M context) --- docs/release-notes/.VisualStudio/18.vNext.md | 1 + .../src/FSharp.Editor/FSharp.Editor.fsproj | 3 + .../src/FSharp.Editor/FSharp.Editor.resx | 9 +- .../FSharp.Editor/Refactor/ConvertTuple.fs | 86 +++ .../FSharp.Editor/Refactor/TupleConversion.fs | 224 +++++++ .../Refactor/TuplePropagation.fs | 593 ++++++++++++++++++ .../FSharp.Editor/xlf/FSharp.Editor.cs.xlf | 15 +- .../FSharp.Editor/xlf/FSharp.Editor.de.xlf | 15 +- .../FSharp.Editor/xlf/FSharp.Editor.es.xlf | 15 +- .../FSharp.Editor/xlf/FSharp.Editor.fr.xlf | 15 +- .../FSharp.Editor/xlf/FSharp.Editor.it.xlf | 15 +- .../FSharp.Editor/xlf/FSharp.Editor.ja.xlf | 15 +- .../FSharp.Editor/xlf/FSharp.Editor.ko.xlf | 15 +- .../FSharp.Editor/xlf/FSharp.Editor.pl.xlf | 15 +- .../FSharp.Editor/xlf/FSharp.Editor.pt-BR.xlf | 15 +- .../FSharp.Editor/xlf/FSharp.Editor.ru.xlf | 15 +- .../FSharp.Editor/xlf/FSharp.Editor.tr.xlf | 15 +- .../xlf/FSharp.Editor.zh-Hans.xlf | 15 +- .../xlf/FSharp.Editor.zh-Hant.xlf | 15 +- .../FSharp.Editor.Tests.fsproj | 1 + .../Refactors/ConvertTupleTests.fs | 310 +++++++++ .../Refactors/RefactorTestFramework.fs | 10 +- 22 files changed, 1349 insertions(+), 83 deletions(-) create mode 100644 vsintegration/src/FSharp.Editor/Refactor/ConvertTuple.fs create mode 100644 vsintegration/src/FSharp.Editor/Refactor/TupleConversion.fs create mode 100644 vsintegration/src/FSharp.Editor/Refactor/TuplePropagation.fs create mode 100644 vsintegration/tests/FSharp.Editor.Tests/Refactors/ConvertTupleTests.fs diff --git a/docs/release-notes/.VisualStudio/18.vNext.md b/docs/release-notes/.VisualStudio/18.vNext.md index 776ec02f5b0..cf222e72dda 100644 --- a/docs/release-notes/.VisualStudio/18.vNext.md +++ b/docs/release-notes/.VisualStudio/18.vNext.md @@ -7,6 +7,7 @@ * Move F# editor and Interactive options to 43 native Unified Settings with independent roaming and a one-time import of existing settings. Preserve the legacy groupings and Interactive setting order, with restart requirements displayed by Unified Settings. Quick Info's preferred description width is a checkbox with a dependent integer control. Remove the eight legacy options pages; the user-wide compiler setting remains external. Typing and deletion completion triggers are independent. ([PR #20877](https://github.com/dotnet/fsharp/pull/20877)) * Added a **Compiler** option in F# Unified Settings, **"Use the .NET SDK F# compiler for builds"**, on by default. Visual Studio uses the .NET SDK F# compiler when the project supplies SDK paths, matching `dotnet build`. Otherwise, it uses the bundled .NET Framework compiler. Turn the option off to use the bundled compiler for all projects. Command-line builds are unaffected. ([Issue #20484](https://github.com/dotnet/fsharp/issues/20484), [PR #20485](https://github.com/dotnet/fsharp/pull/20485)) * F# types, modules, members and values now appear in the GitHub Copilot Chat `#` mention picker, and attach their declaration source as context. ([PR #20409](https://github.com/dotnet/fsharp/pull/20409)) +* Refactoring to convert a tuple between a reference tuple and a struct tuple, following its value through the solution: annotations of values, parameters, record fields and results it flows through, tuple patterns that take it apart, and the arguments and values that flow into it. What cannot be followed (`fst`, `snd`, generic collections) is left for the compiler to report. ### Fixed diff --git a/vsintegration/src/FSharp.Editor/FSharp.Editor.fsproj b/vsintegration/src/FSharp.Editor/FSharp.Editor.fsproj index c0dc0a96846..62d5b851c6a 100644 --- a/vsintegration/src/FSharp.Editor/FSharp.Editor.fsproj +++ b/vsintegration/src/FSharp.Editor/FSharp.Editor.fsproj @@ -109,6 +109,9 @@ + + + diff --git a/vsintegration/src/FSharp.Editor/FSharp.Editor.resx b/vsintegration/src/FSharp.Editor/FSharp.Editor.resx index f9abdee76fd..0351d9fb36a 100644 --- a/vsintegration/src/FSharp.Editor/FSharp.Editor.resx +++ b/vsintegration/src/FSharp.Editor/FSharp.Editor.resx @@ -294,10 +294,11 @@ Returns: - - {0} in {1} -{2} - Tooltip of an F# declaration in the Copilot Chat "#" picker, as Copilot shows a C# one. {0} is the kind of declaration (Class, Method, Field...), {1} the file name, {2} the declaration's name. + + Convert to struct tuple + + + Convert to reference tuple IntelliSense diff --git a/vsintegration/src/FSharp.Editor/Refactor/ConvertTuple.fs b/vsintegration/src/FSharp.Editor/Refactor/ConvertTuple.fs new file mode 100644 index 00000000000..57c69b9a132 --- /dev/null +++ b/vsintegration/src/FSharp.Editor/Refactor/ConvertTuple.fs @@ -0,0 +1,86 @@ +// 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 System.Threading +open System.Threading.Tasks + +open Microsoft.CodeAnalysis +open Microsoft.CodeAnalysis.CodeActions +open Microsoft.CodeAnalysis.CodeRefactorings + +open FSharp.Compiler.Syntax +open FSharp.Compiler.Text + +open CancellableTasks +open TupleConversion + +[] +type internal FSharpConvertTupleRefactoring [] () = + inherit CodeRefactoringProvider() + + static let hasSignatureFile (document: Document) = + let signaturePath = document.FilePath + "i" + + document.Project.Documents + |> Seq.exists (fun d -> String.Equals(d.FilePath, signaturePath, StringComparison.OrdinalIgnoreCase)) + + static let isInQuotation (caretNode: CaretNode) = + let path = + match caretNode with + | CaretNode.Expr(path = path) + | CaretNode.Pat(path = path) + | CaretNode.Type(annotated = Annotated.Pattern(path = path)) + | CaretNode.Type(annotated = Annotated.Expression(path = path)) -> path + | CaretNode.Type _ -> [] + + path + |> List.exists (function + | SyntaxNode.SynExpr(SynExpr.Quote _) -> true + | _ -> false) + + override _.ComputeRefactoringsAsync context = + cancellableTask { + let document = context.Document + + if not (document.IsFSharpSignatureFile || hasSignatureFile document) then + let! cancellationToken = CancellableTask.getCancellationToken () + let! sourceText = document.GetTextAsync cancellationToken + let! parseResults = document.GetFSharpParseResultsAsync(nameof FSharpConvertTupleRefactoring) + + let caret = + let linePosition = sourceText.Lines.GetLinePosition context.Span.Start + Position.mkPos (Line.fromZ linePosition.Line) linePosition.Character + + match tryCaretNode caret parseResults.ParseTree with + | ValueSome caretNode when not (isInQuotation caretNode) -> + let title = + if isStructNode caretNode then + SR.ConvertToReferenceTuple() + else + SR.ConvertToStructTuple() + + let changedSolution = + cancellableTask { + let! converted = TuplePropagation.tryConvert document caretNode (nameof FSharpConvertTupleRefactoring) + + return + match converted with + | ValueSome solution -> solution + | ValueNone -> document.Project.Solution + } + + let action = + CodeAction.Create( + title, + Func>(fun cancellationToken -> + CancellableTask.start cancellationToken changedSolution), + title + ) + + context.RegisterRefactoring action + | _ -> () + } + |> CancellableTask.startAsTask context.CancellationToken diff --git a/vsintegration/src/FSharp.Editor/Refactor/TupleConversion.fs b/vsintegration/src/FSharp.Editor/Refactor/TupleConversion.fs new file mode 100644 index 00000000000..fb3ec7ddc23 --- /dev/null +++ b/vsintegration/src/FSharp.Editor/Refactor/TupleConversion.fs @@ -0,0 +1,224 @@ +// Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information. + +module internal Microsoft.VisualStudio.FSharp.Editor.TupleConversion + +open System + +open Microsoft.CodeAnalysis.Text + +open FSharp.Compiler.Syntax +open FSharp.Compiler.Text + +let spanOf (sourceText: SourceText) (m: range) = + RoslynHelpers.FSharpRangeToTextSpan(sourceText, m) + +let isSame (node: 'T) (other: 'T) = obj.ReferenceEquals(node, other) + +let containsPos (m: range) (position: pos) = + Position.posGeq position m.Start && Position.posGeq m.End position + +let rec stripParenTypes (ty: SynType) = + match ty with + | SynType.Paren(innerType = inner) -> stripParenTypes inner + | _ -> ty + +/// `struct` and the blanks after it, at the start of a struct tuple's range. +let private structKeyword (sourceText: SourceText) (m: range) = + let start = (spanOf sourceText m).Start + let mutable finish = start + "struct".Length + + while finish < sourceText.Length && Char.IsWhiteSpace sourceText[finish] do + finish <- finish + 1 + + TextSpan.FromBounds(start, finish) + +/// The position of the `(` that, with its `)`, encloses only the span and blanks. +let private tryEnclosingParen (sourceText: SourceText) (span: TextSpan) = + let mutable before = span.Start - 1 + + while before >= 0 && Char.IsWhiteSpace sourceText[before] do + before <- before - 1 + + let mutable after = span.End + + while after < sourceText.Length && Char.IsWhiteSpace sourceText[after] do + after <- after + 1 + + if + before >= 0 + && after < sourceText.Length + && sourceText[before] = '(' + && sourceText[after] = ')' + then + ValueSome before + else + ValueNone + +/// Whether the text between start and finish is a whole generic argument: `<` or `,` before it, `>` or `,` after. +let private isGenericArgument (sourceText: SourceText) (start: int) (finish: int) = + let mutable before = start - 1 + + while before >= 0 && Char.IsWhiteSpace sourceText[before] do + before <- before - 1 + + let mutable after = finish + + while after < sourceText.Length && Char.IsWhiteSpace sourceText[after] do + after <- after + 1 + + before >= 0 + && after < sourceText.Length + && (sourceText[before] = '<' || sourceText[before] = ',') + && (sourceText[after] = '>' || sourceText[after] = ',') + +/// Changes giving a tuple type the target kind; a whole annotation also loses the parentheses `struct` needed. +let typeChanges (sourceText: SourceText) (toStruct: bool) (isWholeAnnotation: bool) (tupleType: SynType) = + match tupleType with + | SynType.Tuple(isStruct = isStruct; range = m) when isStruct <> toStruct -> + let span = spanOf sourceText m + + if toStruct then + match tryEnclosingParen sourceText span with + | ValueSome openParen -> [ TextChange(TextSpan(openParen, 0), "struct ") ] + | ValueNone -> + [ + TextChange(TextSpan(span.Start, 0), "struct (") + TextChange(TextSpan(span.End, 0), ")") + ] + else + let keyword = structKeyword sourceText m + + if isWholeAnnotation || isGenericArgument sourceText keyword.Start span.End then + [ + TextChange(TextSpan(keyword.Start, keyword.Length + 1), "") + TextChange(TextSpan(span.End - 1, 1), "") + ] + else + [ TextChange(keyword, "") ] + | _ -> [] + +/// Whether the tuple is the argument list of a method, constructor or union case call rather than a tuple value. +let isArgumentList (tuple: SynExpr) (path: SyntaxVisitorPath) = + match path with + | SyntaxNode.SynExpr(SynExpr.Paren(expr = inner) as paren) :: SyntaxNode.SynExpr(SynExpr.App(flag = ExprAtomicFlag.Atomic; argExpr = arg) | SynExpr.New( + expr = arg)) :: _ -> isSame inner tuple && isSame arg paren + | _ -> false + +/// Changes giving a tuple expression the target kind; ValueNone when it is not a tuple or cannot change in place. +let tryExprChanges (sourceText: SourceText) (toStruct: bool) (tuple: SynExpr) (path: SyntaxVisitorPath) = + match tuple with + | SynExpr.Tuple(isStruct = isStruct) when isStruct = toStruct -> ValueSome [] + | SynExpr.Tuple(range = m) when not toStruct -> ValueSome [ TextChange(structKeyword sourceText m, "") ] + | SynExpr.Tuple(range = m) -> + match path with + | SyntaxNode.SynExpr(SynExpr.Paren(expr = inner; range = parenRange)) :: _ when isSame inner tuple -> + ValueSome [ TextChange(TextSpan((spanOf sourceText parenRange).Start, 0), "struct ") ] + | _ when m.StartLine = m.EndLine -> + let span = spanOf sourceText m + + ValueSome + [ + TextChange(TextSpan(span.Start, 0), "struct (") + TextChange(TextSpan(span.End, 0), ")") + ] + | _ -> ValueNone + | _ -> ValueNone + +/// Changes giving a tuple pattern the target kind; ValueNone when it is not a tuple or cannot change in place. +let tryPatChanges (sourceText: SourceText) (toStruct: bool) (tuple: SynPat) (path: SyntaxVisitorPath) = + match tuple with + | SynPat.Tuple(isStruct = isStruct) when isStruct = toStruct -> ValueSome [] + | SynPat.Tuple(range = m) when not toStruct -> ValueSome [ TextChange(structKeyword sourceText m, "") ] + | SynPat.Tuple(range = m) -> + match path with + | SyntaxNode.SynPat(SynPat.Paren(pat = inner; range = parenRange)) :: _ when isSame inner tuple -> + ValueSome [ TextChange(TextSpan((spanOf sourceText parenRange).Start, 0), "struct ") ] + | _ when m.StartLine = m.EndLine -> + let span = spanOf sourceText m + + ValueSome + [ + TextChange(TextSpan(span.Start, 0), "struct (") + TextChange(TextSpan(span.End, 0), ")") + ] + | _ -> ValueNone + | _ -> ValueNone + +/// The innermost tuple type within the type that contains the position. +let rec tryTupleTypeAt (position: pos) (ty: SynType) = + if not (containsPos ty.Range position) then + ValueNone + else + let inner = + match ty with + | SynType.Paren(innerType = inner) + | SynType.Array(elementType = inner) + | SynType.WithGlobalConstraints(typeName = inner) -> tryTupleTypeAt position inner + | SynType.App(typeName = typeName; typeArgs = typeArgs) + | SynType.LongIdentApp(typeName = typeName; typeArgs = typeArgs) -> + typeName :: typeArgs |> Seq.tryPickV (tryTupleTypeAt position) + | SynType.Fun(argType = argType; returnType = returnType) -> [ argType; returnType ] |> Seq.tryPickV (tryTupleTypeAt position) + | SynType.Tuple(path = segments) -> + segments + |> Seq.tryPickV (function + | SynTupleTypeSegment.Type element -> tryTupleTypeAt position element + | _ -> ValueNone) + | _ -> ValueNone + + match inner, ty with + | ValueSome _, _ -> inner + | ValueNone, SynType.Tuple _ -> ValueSome ty + | ValueNone, _ -> ValueNone + +/// What a tuple type under the caret annotates. +[] +type Annotated = + | Pattern of pat: SynPat * path: SyntaxVisitorPath + | Expression of expr: SynExpr * path: SyntaxVisitorPath + | Return of binding: SynBinding + | Field of field: SynField + +[] +type CaretNode = + | Expr of tuple: SynExpr * path: SyntaxVisitorPath + | Pat of tuple: SynPat * path: SyntaxVisitorPath + | Type of tuple: SynType * annotated: Annotated * isWholeAnnotation: bool + +let isStructNode (node: CaretNode) = + match node with + | CaretNode.Expr(tuple = SynExpr.Tuple(isStruct = isStruct)) + | CaretNode.Pat(tuple = SynPat.Tuple(isStruct = isStruct)) + | CaretNode.Type(tuple = SynType.Tuple(isStruct = isStruct)) -> isStruct + | _ -> false + +/// The innermost tuple expression, pattern or annotated tuple type under the caret. +let tryCaretNode (caret: pos) (parseTree: ParsedInput) = + let annotationAt (annotation: SynType) (annotated: Annotated) = + tryTupleTypeAt caret annotation + |> ValueOption.map (fun tuple -> CaretNode.Type(tuple, annotated, isSame (stripParenTypes annotation) tuple)) + + (ValueNone, parseTree) + ||> ParsedInput.fold (fun found path node -> + match node with + | SyntaxNode.SynExpr(SynExpr.Tuple(range = m) as tuple) when containsPos m caret && not (isArgumentList tuple path) -> + ValueSome(CaretNode.Expr(tuple, path)) + | SyntaxNode.SynPat(SynPat.Tuple(range = m) as tuple) when containsPos m caret -> ValueSome(CaretNode.Pat(tuple, path)) + | SyntaxNode.SynPat(SynPat.Typed(targetType = annotation) as pat) when containsPos annotation.Range caret -> + annotationAt annotation (Annotated.Pattern(pat, path)) + |> ValueOption.orElse found + | SyntaxNode.SynExpr(SynExpr.Typed(targetType = annotation) as expr) when containsPos annotation.Range caret -> + annotationAt annotation (Annotated.Expression(expr, path)) + |> ValueOption.orElse found + | SyntaxNode.SynBinding(SynBinding(returnInfo = Some(SynBindingReturnInfo(typeName = annotation))) as binding) when + containsPos annotation.Range caret + -> + annotationAt annotation (Annotated.Return binding) |> ValueOption.orElse found + | SyntaxNode.SynTypeDefn(SynTypeDefn( + typeRepr = SynTypeDefnRepr.Simple(SynTypeDefnSimpleRepr.Record(recordFieldsAndSpreads = fields), _))) -> + fields + |> Seq.tryPickV (function + | SynFieldOrSpread.Field(SynField(fieldType = annotation) as field) when containsPos annotation.Range caret -> + annotationAt annotation (Annotated.Field field) + | _ -> ValueNone) + |> ValueOption.orElse found + | _ -> found) diff --git a/vsintegration/src/FSharp.Editor/Refactor/TuplePropagation.fs b/vsintegration/src/FSharp.Editor/Refactor/TuplePropagation.fs new file mode 100644 index 00000000000..d816c0ffc3d --- /dev/null +++ b/vsintegration/src/FSharp.Editor/Refactor/TuplePropagation.fs @@ -0,0 +1,593 @@ +// Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information. + +module internal Microsoft.VisualStudio.FSharp.Editor.TuplePropagation + +open System +open System.Collections.Generic + +open Microsoft.CodeAnalysis +open Microsoft.CodeAnalysis.Text + +open FSharp.Compiler.CodeAnalysis +open FSharp.Compiler.Symbols +open FSharp.Compiler.Syntax +open FSharp.Compiler.Text + +open CancellableTasks +open TupleConversion + +[] +type private Source = + { + Document: Document + Text: SourceText + Tree: ParsedInput + Check: FSharpCheckFileResults + } + +/// A place whose tuple type changes kind, and so passes the change on to what flows in and out of it. +[] +type private Slot = + /// A value, a parameter's value or a record field. + | Symbol of symbolUse: FSharpSymbolUse * source: Source + /// The result of a function or a method. + | Result of functionUse: FSharpSymbolUse * source: Source + /// A parameter, by its curried argument and, when that argument is a tuple of parameters, its position in it. + | Parameter of functionUse: FSharpSymbolUse * source: Source * group: int * index: int voption + +let private containsRange (outer: range) (inner: range) = + Position.posGeq inner.Start outer.Start && Position.posGeq outer.End inner.End + +let private symbolUseAt (source: Source) (ident: Ident) = + let line = source.Text.Lines[Line.toZ ident.idRange.EndLine].ToString() + source.Check.GetSymbolUseAtLocation(ident.idRange.EndLine, ident.idRange.EndColumn, line, [ ident.idText ]) + +let rec private tryPatternIdent (pat: SynPat) = + match pat with + | SynPat.Named(ident = SynIdent(ident, _)) + | SynPat.OptionalVal(ident, _) -> ValueSome ident + | SynPat.Paren(pat = inner) + | SynPat.Typed(pat = inner) + | SynPat.Attrib(pat = inner) -> tryPatternIdent inner + | _ -> ValueNone + +let rec private stripParenPats (pat: SynPat) = + match pat with + | SynPat.Paren(pat = inner) -> stripParenPats inner + | _ -> pat + +/// The name of the function applied by the expression, and how many arguments are applied before it. +let rec private tryCallee (expr: SynExpr) (applied: int) = + match expr with + | SynExpr.App(isInfix = false; funcExpr = funcExpr) -> tryCallee funcExpr (applied + 1) + | SynExpr.TypeApp(expr = inner) -> tryCallee inner applied + | SynExpr.Ident ident -> ValueSome(struct (ident, applied)) + | SynExpr.LongIdent(longDotId = SynLongIdent(id = ids)) + | SynExpr.DotGet(longDotId = SynLongIdent(id = ids)) -> + match List.tryLast ids with + | Some ident -> ValueSome(struct (ident, applied)) + | None -> ValueNone + | _ -> ValueNone + +/// The application of a function reference to all of its curried argument groups. +let rec private tryApplication (node: SynExpr) (path: SyntaxVisitorPath) (remaining: int) = + if remaining = 0 then + ValueSome(struct (node, path)) + else + match path with + | SyntaxNode.SynExpr(SynExpr.TypeApp(expr = inner) as typeApp) :: rest when isSame inner node -> + tryApplication typeApp rest remaining + | SyntaxNode.SynExpr(SynExpr.App(isInfix = false; funcExpr = funcExpr) as app) :: rest when isSame funcExpr node -> + tryApplication app rest (remaining - 1) + | _ -> ValueNone + +/// The argument a function reference is applied to in the given curried group. +let rec private tryArgument (node: SynExpr) (path: SyntaxVisitorPath) (group: int) = + match path with + | SyntaxNode.SynExpr(SynExpr.TypeApp(expr = inner) as typeApp) :: rest when isSame inner node -> tryArgument typeApp rest group + | SyntaxNode.SynExpr(SynExpr.App(isInfix = false; funcExpr = funcExpr; argExpr = argument) as app) :: rest when isSame funcExpr node -> + if group = 0 then + ValueSome(struct (argument, SyntaxNode.SynExpr app :: rest)) + else + tryArgument app rest (group - 1) + | _ -> ValueNone + +/// The function and the position of the parameter a pattern in a binding's head declares. +let rec private tryParameterPosition (pat: SynPat) (path: SyntaxVisitorPath) = + match path with + | SyntaxNode.SynPat(SynPat.LongIdent(longDotId = SynLongIdent(id = ids); argPats = SynArgPats.Pats args)) :: SyntaxNode.SynBinding _ :: _ -> + let found = + args + |> List.indexed + |> List.tryFind (fun (_, arg) -> containsRange arg.Range pat.Range) + + match found, List.tryLast ids with + | Some(group, arg), Some name -> + let index = + match stripParenPats arg with + | SynPat.Tuple(elementPats = elements) -> + match + elements + |> List.tryFindIndex (fun element -> containsRange element.Range pat.Range) + with + | Some index -> ValueSome index + | None -> ValueNone + | _ -> ValueNone + + ValueSome(struct (name, group, index)) + | _ -> ValueNone + | _ :: rest -> tryParameterPosition pat rest + | [] -> ValueNone + +/// The expression a tuple pattern takes apart: the right-hand side of its binding or the matched expression. +let rec private tryMatchedExpression (pat: SynPat) (path: SyntaxVisitorPath) = + match path with + | SyntaxNode.SynPat(SynPat.Paren _ as paren) :: rest -> tryMatchedExpression paren rest + | SyntaxNode.SynBinding(SynBinding(headPat = headPat; expr = body)) :: _ when isSame headPat pat -> ValueSome(struct (body, path)) + | SyntaxNode.SynMatchClause(SynMatchClause(pat = clausePat)) :: SyntaxNode.SynExpr(SynExpr.Match(expr = scrutinee) as matchExpr) :: rest when + isSame clausePat pat + -> + ValueSome(struct (scrutinee, SyntaxNode.SynExpr matchExpr :: rest)) + | _ -> ValueNone + +/// The expression node a symbol use stands for: an identifier, or the last part of a dotted name. +let private tryUseNode (tree: ParsedInput) (useRange: range) = + let isUse (ident: Ident) = + Position.posEq ident.idRange.Start useRange.Start + && Position.posEq ident.idRange.End useRange.End + + (useRange.Start, tree) + ||> ParsedInput.tryPickLast (fun path node -> + match node with + | SyntaxNode.SynExpr(SynExpr.Ident ident as expr) when isUse ident -> Some(expr, path) + | SyntaxNode.SynExpr(SynExpr.LongIdent(longDotId = SynLongIdent(id = ids)) as expr) + | SyntaxNode.SynExpr(SynExpr.DotGet(longDotId = SynLongIdent(id = ids)) as expr) when + // A dotted use can cover the whole name, `r.Field`, not only its last part. + List.tryLast ids + |> Option.exists (fun ident -> Position.posEq ident.idRange.End useRange.End) + -> + Some(expr, path) + | _ -> None) + +/// The value given to a record field whose name is at the use, in a record construction or copy-and-update. +let private tryRecordFieldValue (tree: ParsedInput) (useRange: range) = + (useRange.Start, tree) + ||> ParsedInput.tryPickLast (fun path node -> + match node with + | SyntaxNode.SynExpr(SynExpr.Record(recordFields = fields) as record) -> + fields + |> List.tryPick (function + | SynExprRecordFieldOrSpread.Field(field = SynExprRecordField(fieldName = (SynLongIdent(id = ids), _); expr = Some value)) when + List.tryLast ids + |> Option.exists (fun ident -> Position.posEq ident.idRange.Start useRange.Start) + -> + Some(value, SyntaxNode.SynExpr record :: path) + | _ -> None) + | _ -> None) + +/// The pattern declaring a parameter of the function declared at the range: its whole curried argument, or one +/// element of an argument that is a tuple of parameters. +let private tryParameterPattern (tree: ParsedInput) (declaration: range) (group: int) (index: int voption) = + (ValueNone, tree) + ||> ParsedInput.fold (fun found _ node -> + match found, node with + | ValueNone, + SyntaxNode.SynBinding(SynBinding(headPat = SynPat.LongIdent(longDotId = SynLongIdent(id = ids); argPats = SynArgPats.Pats args))) when + group < args.Length + && List.tryLast ids + |> Option.exists (fun ident -> Position.posEq ident.idRange.Start declaration.Start) + -> + match stripParenPats (List.item group args), index with + | SynPat.Tuple(elementPats = elements), ValueSome index when index < elements.Length -> + ValueSome(stripParenPats (List.item index elements)) + | SynPat.Tuple _, _ + | _, ValueSome _ -> ValueNone + | parameter, ValueNone -> ValueSome parameter + | _ -> found) + +let private annotationChanges (sourceText: SourceText) (toStruct: bool) (annotation: SynType) = + match stripParenTypes annotation with + | SynType.Tuple _ as tuple -> typeChanges sourceText toStruct true tuple + | _ -> [] + +type private Engine(solution: Solution, toStruct: bool, userOpName: string) = + let sources = Dictionary() + let changes = Dictionary>() + let visited = HashSet(StringComparer.Ordinal) + let pending = Queue() + let mutable failed = false + + let isDeclaration (useRange: range) (declaration: range) = + String.Equals(useRange.FileName, declaration.FileName, StringComparison.OrdinalIgnoreCase) + && Position.posEq useRange.Start declaration.Start + + let tryDeclarationDocument (symbol: FSharpSymbol) = + match symbol.DeclarationLocation with + | Some declaration -> + solution.TryGetDocumentFromPath declaration.FileName + |> ValueOption.map (fun document -> struct (declaration, document)) + | None -> ValueNone + + let keyOf (kind: string) (symbol: FSharpSymbol) = + symbol.DeclarationLocation + |> Option.map (fun m -> $"{kind}|{m.FileName}|{m.StartLine}|{m.StartColumn}") + + member _.Load(document: Document) = + cancellableTask { + match sources.TryGetValue document.Id with + | true, source -> return source + | _ -> + let! cancellationToken = CancellableTask.getCancellationToken () + let! text = document.GetTextAsync cancellationToken + let! parseResults, checkResults = document.GetFSharpParseAndCheckResultsAsync userOpName + + let source = + { + Document = document + Text = text + Tree = parseResults.ParseTree + Check = checkResults + } + + sources[document.Id] <- source + return source + } + + member _.Add (source: Source) (newChanges: TextChange list) = + let documentChanges = + match changes.TryGetValue source.Document.Id with + | true, documentChanges -> documentChanges + | _ -> + let documentChanges = ResizeArray() + changes[source.Document.Id] <- documentChanges + documentChanges + + for change in newChanges do + let isKnown = + documentChanges + |> Seq.exists (fun known -> + known.Span = change.Span + && String.Equals(known.NewText, change.NewText, StringComparison.Ordinal)) + + if not isKnown then + documentChanges.Add change + + member this.AddOrFail (source: Source) (result: TextChange list voption) = + match result with + | ValueSome newChanges -> this.Add source newChanges + | ValueNone -> failed <- true + + member _.Enqueue (key: string option) (slot: Slot) = + match key with + | Some key when visited.Add key -> pending.Enqueue slot + | _ -> () + + member this.EnqueueSymbol (source: Source) (ident: Ident) = + match symbolUseAt source ident with + | Some symbolUse when (tryDeclarationDocument symbolUse.Symbol).IsSome -> + let isValue = + match symbolUse.Symbol with + | :? FSharpField -> true + | :? FSharpMemberOrFunctionOrValue as mfv -> not mfv.IsFunction && not mfv.IsMember + | _ -> false + + if isValue then + this.Enqueue (keyOf "S" symbolUse.Symbol) (Slot.Symbol(symbolUse, source)) + | _ -> () + + member this.EnqueueResult (source: Source) (name: Ident) = + match symbolUseAt source name with + | Some functionUse when (tryDeclarationDocument functionUse.Symbol).IsSome -> + match functionUse.Symbol with + | :? FSharpMemberOrFunctionOrValue as mfv when mfv.IsFunction || mfv.IsMember -> + this.Enqueue (keyOf "R" functionUse.Symbol) (Slot.Result(functionUse, source)) + | _ -> () + | _ -> () + + member this.EnqueueParameter (source: Source) (functionName: Ident) (group: int) (index: int voption) = + match symbolUseAt source functionName with + | Some functionUse when (tryDeclarationDocument functionUse.Symbol).IsSome -> + match functionUse.Symbol with + | :? FSharpMemberOrFunctionOrValue as mfv when mfv.IsFunction || mfv.IsMember -> + let position = + match index with + | ValueSome index -> $"{group}|{index}" + | ValueNone -> $"{group}" + + this.Enqueue + (keyOf "P" functionUse.Symbol |> Option.map (fun key -> $"{key}|{position}")) + (Slot.Parameter(functionUse, source, group, index)) + | _ -> () + | _ -> () + + /// A value of the changing kind flows into a pattern. + member this.IntoPattern (source: Source) (pat: SynPat) (path: SyntaxVisitorPath) = + match pat with + | SynPat.Paren(pat = inner) -> this.IntoPattern source inner (SyntaxNode.SynPat pat :: path) + | SynPat.Typed(pat = inner; targetType = annotation) -> + this.Add source (annotationChanges source.Text toStruct annotation) + this.IntoPattern source inner (SyntaxNode.SynPat pat :: path) + | SynPat.Named(ident = SynIdent(ident, _)) + | SynPat.LongIdent(longDotId = SynLongIdent(id = [ ident ]); argPats = SynArgPats.Pats []) -> this.EnqueueSymbol source ident + | SynPat.Tuple _ -> this.AddOrFail source (tryPatChanges source.Text toStruct pat path) + | _ -> () + + /// The value of the node now has the changing kind: pass that on to where it goes. + member this.FlowOut (source: Source) (node: SynExpr) (path: SyntaxVisitorPath) = + match path with + | SyntaxNode.SynExpr(SynExpr.Paren(expr = inner) as paren) :: rest when isSame inner node -> this.FlowOut source paren rest + | SyntaxNode.SynExpr(SynExpr.Typed(expr = inner; targetType = annotation) as typed) :: rest when isSame inner node -> + this.Add source (annotationChanges source.Text toStruct annotation) + this.FlowOut source typed rest + | SyntaxNode.SynBinding(SynBinding(headPat = headPat; expr = body)) :: _ when isSame body node -> + match headPat with + | SynPat.LongIdent(longDotId = SynLongIdent(id = ids); argPats = SynArgPats.Pats(_ :: _)) -> + match List.tryLast ids with + | Some name -> this.EnqueueResult source name + | None -> () + | _ -> this.IntoPattern source headPat path + | SyntaxNode.SynExpr(SynExpr.Sequential(expr2 = last) as container) :: rest when isSame last node -> + this.FlowOut source container rest + | SyntaxNode.SynExpr(SynExpr.LetOrUse letOrUse as container) :: rest when isSame letOrUse.Body node -> + this.FlowOut source container rest + | SyntaxNode.SynExpr(SynExpr.IfThenElse(thenExpr = thenExpr; elseExpr = Some elseExpr) as container) :: rest when + isSame thenExpr node || isSame elseExpr node + -> + this.Retarget source container rest + this.FlowOut source container rest + | SyntaxNode.SynMatchClause(SynMatchClause(resultExpr = result)) :: SyntaxNode.SynExpr(SynExpr.Match _ as container) :: rest when + isSame result node + -> + this.Retarget source container rest + this.FlowOut source container rest + | SyntaxNode.SynExpr(SynExpr.App(isInfix = false; funcExpr = funcExpr; argExpr = argument)) :: _ when isSame argument node -> + match tryCallee funcExpr 0 with + | ValueSome(struct (name, group)) -> this.EnqueueParameter source name group ValueNone + | ValueNone -> () + | SyntaxNode.SynExpr(SynExpr.Tuple(exprs = exprs)) :: SyntaxNode.SynExpr(SynExpr.Paren _ as paren) :: SyntaxNode.SynExpr(SynExpr.App( + isInfix = false; funcExpr = funcExpr; argExpr = argument)) :: _ when isSame argument paren -> + match tryCallee funcExpr 0, List.tryFindIndex (isSame node) exprs with + | ValueSome(struct (name, group)), Some index -> this.EnqueueParameter source name group (ValueSome index) + | _ -> () + | SyntaxNode.SynExpr(SynExpr.Record(recordFields = fields)) :: _ -> + for field in fields do + match field with + | SynExprRecordFieldOrSpread.Field(field = SynExprRecordField(fieldName = (SynLongIdent(id = ids), _); expr = Some value)) when + isSame value node + -> + match List.tryLast ids with + | Some name -> this.EnqueueSymbol source name + | None -> () + | _ -> () + | SyntaxNode.SynExpr(SynExpr.Match(expr = scrutinee; clauses = clauses) as matchExpr) :: rest when isSame scrutinee node -> + for SynMatchClause(pat = pat) as clause in clauses do + match stripParenPats pat with + | SynPat.Tuple _ as tuple -> + let tuplePath = + match pat with + | SynPat.Paren _ -> [ SyntaxNode.SynPat pat ] + | _ -> [ SyntaxNode.SynMatchClause clause; SyntaxNode.SynExpr matchExpr ] @ rest + + this.AddOrFail source (tryPatChanges source.Text toStruct tuple tuplePath) + | _ -> () + | _ -> () + + /// The expression must now produce the changing kind: change what it is built from. + member this.Retarget (source: Source) (expr: SynExpr) (path: SyntaxVisitorPath) = + let childPath = SyntaxNode.SynExpr expr :: path + + match expr with + | SynExpr.Paren(expr = inner) -> this.Retarget source inner childPath + | SynExpr.Typed(expr = inner; targetType = annotation) -> + this.Add source (annotationChanges source.Text toStruct annotation) + this.Retarget source inner childPath + | SynExpr.Tuple _ when not (isArgumentList expr path) -> this.AddOrFail source (tryExprChanges source.Text toStruct expr path) + | SynExpr.Ident ident -> this.EnqueueSymbol source ident + | SynExpr.LongIdent(longDotId = SynLongIdent(id = ids)) + | SynExpr.DotGet(longDotId = SynLongIdent(id = ids)) -> + match List.tryLast ids with + | Some ident -> this.EnqueueSymbol source ident + | None -> () + | SynExpr.App(isInfix = false) -> + match tryCallee expr 0 with + | ValueSome(struct (name, _)) -> this.EnqueueResult source name + | ValueNone -> () + | SynExpr.IfThenElse(thenExpr = thenExpr; elseExpr = Some elseExpr) -> + this.Retarget source thenExpr childPath + this.Retarget source elseExpr childPath + | SynExpr.Match(clauses = clauses) -> + for SynMatchClause(resultExpr = result) as clause in clauses do + this.Retarget source result (SyntaxNode.SynMatchClause clause :: childPath) + | SynExpr.Sequential(expr2 = last) -> this.Retarget source last childPath + | SynExpr.LetOrUse letOrUse -> this.Retarget source letOrUse.Body childPath + | _ -> () + + /// Changes the declaration of a value, a parameter or a record field. + member this.Define (source: Source) (declaration: range) = + let isDeclared (ident: Ident) = + Position.posEq ident.idRange.Start declaration.Start + + ((), source.Tree) + ||> ParsedInput.fold (fun () path node -> + match node with + | SyntaxNode.SynBinding(SynBinding(headPat = SynPat.Named(ident = SynIdent(ident, _)); expr = body)) when isDeclared ident -> + this.Retarget source body (node :: path) + | SyntaxNode.SynPat(SynPat.Typed(pat = inner; targetType = annotation)) when + tryPatternIdent inner |> ValueOption.exists isDeclared + -> + this.Add source (annotationChanges source.Text toStruct annotation) + | SyntaxNode.SynTypeDefn(SynTypeDefn( + typeRepr = SynTypeDefnRepr.Simple(SynTypeDefnSimpleRepr.Record(recordFieldsAndSpreads = fields), _))) -> + for field in fields do + match field with + | SynFieldOrSpread.Field(SynField(idOpt = Some ident; fieldType = annotation)) when isDeclared ident -> + this.Add source (annotationChanges source.Text toStruct annotation) + | _ -> () + | _ -> ()) + + /// Changes the declared or inferred result of a function. + member this.DefineResult (source: Source) (declaration: range) = + ((), source.Tree) + ||> ParsedInput.fold (fun () path node -> + match node with + | SyntaxNode.SynBinding(SynBinding(headPat = SynPat.LongIdent(longDotId = SynLongIdent(id = ids)); expr = body)) when + List.tryLast ids + |> Option.exists (fun ident -> Position.posEq ident.idRange.Start declaration.Start) + -> + this.Retarget source body (node :: path) + | _ -> ()) + + member this.ProcessSymbol (symbolUse: FSharpSymbolUse) (source: Source) = + cancellableTask { + match tryDeclarationDocument symbolUse.Symbol with + | ValueSome(struct (declaration, document)) -> + let! definition = this.Load document + this.Define definition declaration + let! uses = SymbolHelpers.getSymbolUses symbolUse source.Document source.Check + + for useDocument, useRange in uses do + if not (isDeclaration useRange declaration) then + let! useSource = this.Load useDocument + + match tryRecordFieldValue useSource.Tree useRange with + | Some(value, path) -> this.Retarget useSource value path + | None -> + match tryUseNode useSource.Tree useRange with + | Some(node, path) -> this.FlowOut useSource node path + | None -> () + | ValueNone -> () + } + + member this.ProcessResult (functionUse: FSharpSymbolUse) (source: Source) = + cancellableTask { + match tryDeclarationDocument functionUse.Symbol, functionUse.Symbol with + | ValueSome(struct (declaration, document)), (:? FSharpMemberOrFunctionOrValue as mfv) -> + let! definition = this.Load document + this.DefineResult definition declaration + let groups = max 1 mfv.CurriedParameterGroups.Count + let! uses = SymbolHelpers.getSymbolUses functionUse source.Document source.Check + + for useDocument, useRange in uses do + if not (isDeclaration useRange declaration) then + let! useSource = this.Load useDocument + + match tryUseNode useSource.Tree useRange with + | Some(node, path) -> + match tryApplication node path groups with + | ValueSome(struct (application, rest)) -> this.FlowOut useSource application rest + | ValueNone -> () + | None -> () + | _ -> () + } + + member this.ProcessParameter (functionUse: FSharpSymbolUse) (source: Source) (group: int) (index: int voption) = + cancellableTask { + match tryDeclarationDocument functionUse.Symbol with + | ValueSome(struct (declaration, document)) -> + let! definition = this.Load document + + match tryParameterPattern definition.Tree declaration group index with + | ValueSome parameter -> + match parameter with + | SynPat.Typed(targetType = annotation) -> this.Add definition (annotationChanges definition.Text toStruct annotation) + | _ -> () + + match tryPatternIdent parameter with + | ValueSome ident -> this.EnqueueSymbol definition ident + | ValueNone -> () + + let! uses = SymbolHelpers.getSymbolUses functionUse source.Document source.Check + + for useDocument, useRange in uses do + if not (isDeclaration useRange declaration) then + let! useSource = this.Load useDocument + + match tryUseNode useSource.Tree useRange with + | Some(node, path) -> + match tryArgument node path group, index with + | ValueSome(struct (SynExpr.Paren(expr = SynExpr.Tuple(exprs = exprs) as tuple) as argument, argumentPath)), + ValueSome index when index < exprs.Length -> + this.Retarget + useSource + (List.item index exprs) + (SyntaxNode.SynExpr tuple :: SyntaxNode.SynExpr argument :: argumentPath) + | ValueSome(struct (argument, argumentPath)), ValueNone -> this.Retarget useSource argument argumentPath + | _ -> () + | None -> () + | ValueNone -> () + | ValueNone -> () + } + + member this.Seed (source: Source) (caretNode: CaretNode) = + match caretNode with + | CaretNode.Expr(tuple, path) -> + this.AddOrFail source (tryExprChanges source.Text toStruct tuple path) + this.FlowOut source tuple path + | CaretNode.Pat(tuple, path) -> + this.AddOrFail source (tryPatChanges source.Text toStruct tuple path) + + match tryMatchedExpression tuple path with + | ValueSome(struct (matched, matchedPath)) -> this.Retarget source matched matchedPath + | ValueNone -> () + | CaretNode.Type(tuple, annotated, isWholeAnnotation) -> + this.Add source (typeChanges source.Text toStruct isWholeAnnotation tuple) + + if isWholeAnnotation then + match annotated with + | Annotated.Pattern(SynPat.Typed(pat = inner) as pat, path) -> + match tryPatternIdent inner with + | ValueSome ident -> this.EnqueueSymbol source ident + | ValueNone -> () + + match tryParameterPosition pat path with + | ValueSome(struct (name, group, index)) -> this.EnqueueParameter source name group index + | ValueNone -> () + | Annotated.Pattern _ -> () + | Annotated.Expression(expr, path) -> + this.Retarget source expr path + this.FlowOut source expr path + | Annotated.Return(SynBinding( + headPat = SynPat.LongIdent(longDotId = SynLongIdent(id = ids); argPats = SynArgPats.Pats(_ :: _)))) -> + match List.tryLast ids with + | Some name -> this.EnqueueResult source name + | None -> () + | Annotated.Return(SynBinding(headPat = headPat)) -> + match tryPatternIdent headPat with + | ValueSome ident -> this.EnqueueSymbol source ident + | ValueNone -> () + | Annotated.Field(SynField(idOpt = Some ident)) -> this.EnqueueSymbol source ident + | Annotated.Field _ -> () + + /// The solution with every change of the chain, or ValueNone when a part cannot change or changes collide. + member this.Run(document: Document, caretNode: CaretNode) = + cancellableTask { + let! source = this.Load document + this.Seed source caretNode + + while pending.Count > 0 && not failed do + match pending.Dequeue() with + | Slot.Symbol(symbolUse, slotSource) -> do! this.ProcessSymbol symbolUse slotSource + | Slot.Result(functionUse, slotSource) -> do! this.ProcessResult functionUse slotSource + | Slot.Parameter(functionUse, slotSource, group, index) -> do! this.ProcessParameter functionUse slotSource group index + + let mutable result = ValueSome solution + + for KeyValue(documentId, documentChanges) in changes do + let ordered = documentChanges |> Seq.sortBy _.Span.Start |> Seq.toArray + + let collides = + ordered + |> Array.pairwise + |> Array.exists (fun (first, second) -> first.Span.End > second.Span.Start) + + match result with + | ValueSome current when not collides && not failed -> + result <- ValueSome(current.WithDocumentText(documentId, sources[documentId].Text.WithChanges ordered)) + | _ -> result <- ValueNone + + return if failed then ValueNone else result + } + +/// Changes the tuple under the caret to the other kind, together with everything its value flows through. +let tryConvert (document: Document) (caretNode: CaretNode) (userOpName: string) = + Engine(document.Project.Solution, not (isStructNode caretNode), userOpName).Run(document, caretNode) diff --git a/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.cs.xlf b/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.cs.xlf index 3298f878a8c..71fadd5b7b3 100644 --- a/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.cs.xlf +++ b/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.cs.xlf @@ -57,6 +57,11 @@ Pro kontrolu nerovnosti použijte <>. + + Convert to reference tuple + Convert to reference tuple + + Use '=' for equality check Pro kontrolu rovnosti použijte =. @@ -67,12 +72,10 @@ Použít místo negace odčítání - - {0} in {1} -{2} - {0} in {1} -{2} - Tooltip of an F# declaration in the Copilot Chat "#" picker, as Copilot shows a C# one. {0} is the kind of declaration (Class, Method, Field...), {1} the file name, {2} the declaration's name. + + Convert to struct tuple + Convert to struct tuple + F# Disposable Values (locals) diff --git a/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.de.xlf b/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.de.xlf index 0e7bf530579..4d1d3deb0f0 100644 --- a/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.de.xlf +++ b/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.de.xlf @@ -57,6 +57,11 @@ "<>" für die Überprüfung auf Ungleichheit verwenden + + Convert to reference tuple + Convert to reference tuple + + Use '=' for equality check "=" für Gleichheitsüberprüfung verwenden @@ -67,12 +72,10 @@ Subtraktion anstelle von Negation verwenden - - {0} in {1} -{2} - {0} in {1} -{2} - Tooltip of an F# declaration in the Copilot Chat "#" picker, as Copilot shows a C# one. {0} is the kind of declaration (Class, Method, Field...), {1} the file name, {2} the declaration's name. + + Convert to struct tuple + Convert to struct tuple + F# Disposable Values (locals) diff --git a/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.es.xlf b/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.es.xlf index fb6a11748e7..796253dad8a 100644 --- a/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.es.xlf +++ b/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.es.xlf @@ -57,6 +57,11 @@ Usar "<>" para la comprobación de desigualdad + + Convert to reference tuple + Convert to reference tuple + + Use '=' for equality check Usar "=" para la comprobación de igualdad @@ -67,12 +72,10 @@ Usar la resta en lugar de la negación - - {0} in {1} -{2} - {0} in {1} -{2} - Tooltip of an F# declaration in the Copilot Chat "#" picker, as Copilot shows a C# one. {0} is the kind of declaration (Class, Method, Field...), {1} the file name, {2} the declaration's name. + + Convert to struct tuple + Convert to struct tuple + F# Disposable Values (locals) diff --git a/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.fr.xlf b/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.fr.xlf index b5c2cd85b3b..807ff12ba4a 100644 --- a/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.fr.xlf +++ b/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.fr.xlf @@ -57,6 +57,11 @@ Utiliser '<>' pour vérifier l'inégalité + + Convert to reference tuple + Convert to reference tuple + + Use '=' for equality check Utiliser '=' pour vérifier l'égalité @@ -67,12 +72,10 @@ Utiliser la soustraction à la place de la négation - - {0} in {1} -{2} - {0} in {1} -{2} - Tooltip of an F# declaration in the Copilot Chat "#" picker, as Copilot shows a C# one. {0} is the kind of declaration (Class, Method, Field...), {1} the file name, {2} the declaration's name. + + Convert to struct tuple + Convert to struct tuple + F# Disposable Values (locals) diff --git a/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.it.xlf b/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.it.xlf index ad663d26a2b..d8cde89d11e 100644 --- a/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.it.xlf +++ b/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.it.xlf @@ -57,6 +57,11 @@ Usare '<>' per il controllo di disuguaglianza + + Convert to reference tuple + Convert to reference tuple + + Use '=' for equality check Usare '=' per il controllo di uguaglianza @@ -67,12 +72,10 @@ Usare la sottrazione invece della negazione - - {0} in {1} -{2} - {0} in {1} -{2} - Tooltip of an F# declaration in the Copilot Chat "#" picker, as Copilot shows a C# one. {0} is the kind of declaration (Class, Method, Field...), {1} the file name, {2} the declaration's name. + + Convert to struct tuple + Convert to struct tuple + F# Disposable Values (locals) diff --git a/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.ja.xlf b/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.ja.xlf index 0f5652f2543..5de2425a497 100644 --- a/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.ja.xlf +++ b/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.ja.xlf @@ -57,6 +57,11 @@ 非等値のチェックには '<>' を使用します + + Convert to reference tuple + Convert to reference tuple + + Use '=' for equality check 等値性のチェックには '=' を使用します @@ -67,12 +72,10 @@ 否定の代わりに減算を使用する - - {0} in {1} -{2} - {0} in {1} -{2} - Tooltip of an F# declaration in the Copilot Chat "#" picker, as Copilot shows a C# one. {0} is the kind of declaration (Class, Method, Field...), {1} the file name, {2} the declaration's name. + + Convert to struct tuple + Convert to struct tuple + F# Disposable Values (locals) diff --git a/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.ko.xlf b/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.ko.xlf index 5da9ba3d1b7..8890edf3d98 100644 --- a/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.ko.xlf +++ b/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.ko.xlf @@ -57,6 +57,11 @@ 같지 않음 검사에 '<>' 사용 + + Convert to reference tuple + Convert to reference tuple + + Use '=' for equality check 같음 검사에 '=' 사용 @@ -67,12 +72,10 @@ 부정 대신 빼기 사용 - - {0} in {1} -{2} - {0} in {1} -{2} - Tooltip of an F# declaration in the Copilot Chat "#" picker, as Copilot shows a C# one. {0} is the kind of declaration (Class, Method, Field...), {1} the file name, {2} the declaration's name. + + Convert to struct tuple + Convert to struct tuple + F# Disposable Values (locals) diff --git a/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.pl.xlf b/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.pl.xlf index 20ad3e7a963..3ef8558c940 100644 --- a/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.pl.xlf +++ b/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.pl.xlf @@ -57,6 +57,11 @@ Użyj operatora „<>” do sprawdzenia nierówności + + Convert to reference tuple + Convert to reference tuple + + Use '=' for equality check Użyj znaku „=” w celu sprawdzenia równości @@ -67,12 +72,10 @@ Użyj odejmowania zamiast negacji - - {0} in {1} -{2} - {0} in {1} -{2} - Tooltip of an F# declaration in the Copilot Chat "#" picker, as Copilot shows a C# one. {0} is the kind of declaration (Class, Method, Field...), {1} the file name, {2} the declaration's name. + + Convert to struct tuple + Convert to struct tuple + F# Disposable Values (locals) diff --git a/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.pt-BR.xlf b/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.pt-BR.xlf index f6a9da54b62..3f990a69eea 100644 --- a/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.pt-BR.xlf +++ b/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.pt-BR.xlf @@ -57,6 +57,11 @@ Usar '<>' para a verificação de desigualdade + + Convert to reference tuple + Convert to reference tuple + + Use '=' for equality check Usar '=' para verificação de igualdade @@ -67,12 +72,10 @@ Use a subtração em vez da negação - - {0} in {1} -{2} - {0} in {1} -{2} - Tooltip of an F# declaration in the Copilot Chat "#" picker, as Copilot shows a C# one. {0} is the kind of declaration (Class, Method, Field...), {1} the file name, {2} the declaration's name. + + Convert to struct tuple + Convert to struct tuple + F# Disposable Values (locals) diff --git a/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.ru.xlf b/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.ru.xlf index 87ba8ce08f3..51ac3a60609 100644 --- a/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.ru.xlf +++ b/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.ru.xlf @@ -57,6 +57,11 @@ Используйте "<>" для проверки на неравенство + + Convert to reference tuple + Convert to reference tuple + + Use '=' for equality check Используйте "=" для проверки равенства @@ -67,12 +72,10 @@ Используйте вычитание вместо отрицания. - - {0} in {1} -{2} - {0} in {1} -{2} - Tooltip of an F# declaration in the Copilot Chat "#" picker, as Copilot shows a C# one. {0} is the kind of declaration (Class, Method, Field...), {1} the file name, {2} the declaration's name. + + Convert to struct tuple + Convert to struct tuple + F# Disposable Values (locals) diff --git a/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.tr.xlf b/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.tr.xlf index 7f1fcbfd6bb..6a6cf150b90 100644 --- a/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.tr.xlf +++ b/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.tr.xlf @@ -57,6 +57,11 @@ Eşitsizlik denetimi için '<>' kullanın + + Convert to reference tuple + Convert to reference tuple + + Use '=' for equality check Eşitlik denetimi için '=' kullan @@ -67,12 +72,10 @@ Negatif yapma yerine çıkarmayı kullanın - - {0} in {1} -{2} - {0} in {1} -{2} - Tooltip of an F# declaration in the Copilot Chat "#" picker, as Copilot shows a C# one. {0} is the kind of declaration (Class, Method, Field...), {1} the file name, {2} the declaration's name. + + Convert to struct tuple + Convert to struct tuple + F# Disposable Values (locals) diff --git a/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.zh-Hans.xlf b/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.zh-Hans.xlf index 28c85e2800b..0630be81c1b 100644 --- a/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.zh-Hans.xlf +++ b/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.zh-Hans.xlf @@ -57,6 +57,11 @@ 使用 "<>" 进行不相等检查 + + Convert to reference tuple + Convert to reference tuple + + Use '=' for equality check 使用 "=" 进行同等性检查 @@ -67,12 +72,10 @@ 使用减法代替求反 - - {0} in {1} -{2} - {0} in {1} -{2} - Tooltip of an F# declaration in the Copilot Chat "#" picker, as Copilot shows a C# one. {0} is the kind of declaration (Class, Method, Field...), {1} the file name, {2} the declaration's name. + + Convert to struct tuple + Convert to struct tuple + F# Disposable Values (locals) diff --git a/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.zh-Hant.xlf b/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.zh-Hant.xlf index 06562e95b93..c7d4413b70d 100644 --- a/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.zh-Hant.xlf +++ b/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.zh-Hant.xlf @@ -57,6 +57,11 @@ 使用 '<>' 進行不等式檢查 + + Convert to reference tuple + Convert to reference tuple + + Use '=' for equality check 使用 '=' 檢查是否相等 @@ -67,12 +72,10 @@ 使用減號代替否定 - - {0} in {1} -{2} - {0} in {1} -{2} - Tooltip of an F# declaration in the Copilot Chat "#" picker, as Copilot shows a C# one. {0} is the kind of declaration (Class, Method, Field...), {1} the file name, {2} the declaration's name. + + Convert to struct tuple + Convert to struct tuple + F# Disposable Values (locals) diff --git a/vsintegration/tests/FSharp.Editor.Tests/FSharp.Editor.Tests.fsproj b/vsintegration/tests/FSharp.Editor.Tests/FSharp.Editor.Tests.fsproj index 73ee106e8a7..9d7bfd7618c 100644 --- a/vsintegration/tests/FSharp.Editor.Tests/FSharp.Editor.Tests.fsproj +++ b/vsintegration/tests/FSharp.Editor.Tests/FSharp.Editor.Tests.fsproj @@ -80,6 +80,7 @@ + diff --git a/vsintegration/tests/FSharp.Editor.Tests/Refactors/ConvertTupleTests.fs b/vsintegration/tests/FSharp.Editor.Tests/Refactors/ConvertTupleTests.fs new file mode 100644 index 00000000000..adcacd08618 --- /dev/null +++ b/vsintegration/tests/FSharp.Editor.Tests/Refactors/ConvertTupleTests.fs @@ -0,0 +1,310 @@ +module FSharp.Editor.Tests.Refactors.ConvertTupleTests + +open System + +open Microsoft.CodeAnalysis +open Microsoft.VisualStudio.FSharp.Editor +open Microsoft.VisualStudio.FSharp.Editor.CancellableTasks + +open Xunit + +open FSharp.Compiler.Diagnostics + +open FSharp.Editor.Tests.Refactors.RefactorTestFramework + +let private caretAt (code: string) (marker: string) = + code.IndexOf(marker, StringComparison.Ordinal) + +let private textOf (document: Document) = + (document.GetTextAsync() |> GetTaskResult).ToString() + +let private errorsOf (document: Document) = + let _, checkResults = + document.GetFSharpParseAndCheckResultsAsync "test" + |> CancellableTask.runSynchronouslyWithoutCancellation + + checkResults.Diagnostics + |> Array.filter (fun diagnostic -> diagnostic.Severity = FSharpDiagnosticSeverity.Error) + +let private refactorIn (context: TestContext) (code: string) (marker: string) = + tryRefactor code (caretAt code marker) context (new FSharpConvertTupleRefactoring()) + +let private refactored (code: string) (marker: string) = + use context = TestContext.CreateWithCode code + let document = refactorIn context code marker + Assert.Empty(errorsOf document) + textOf document + +let private actionsAt (code: string) (marker: string) = + use context = TestContext.CreateWithCode code + tryGetRefactoringActions code (caretAt code marker) context (new FSharpConvertTupleRefactoring()) + +[] +[] +[ = [] +""", + "int * int", + """ +module M + +let pairs: list = [] +""")>] +let ``Tuple that flows nowhere else converts on its own`` (before: string, marker: string, after: string) = + Assert.Equal(after, refactored before marker) + Assert.Equal(before, refactored after marker) + +[] +let ``Value, its tuple patterns and the annotations it flows into convert together`` () = + let reference = + """ +module M + +let pair = (1, 2) +let (a, b) = pair +let copy: int * int = pair +""" + + let structs = + """ +module M + +let pair = struct (1, 2) +let struct (a, b) = pair +let copy: struct (int * int) = pair +""" + + Assert.Equal(structs, refactored reference "1, 2") + Assert.Equal(reference, refactored structs "1, 2") + +[] +let ``Parameter annotation converts its arguments and the patterns on it`` () = + let reference = + """ +module M + +let sum (p: int * int) = + let (a, b) = p + a + b + +let pair = (3, 4) +let total = sum pair + sum (1, 2) +""" + + let structs = + """ +module M + +let sum (p: struct (int * int)) = + let struct (a, b) = p + a + b + +let pair = struct (3, 4) +let total = sum pair + sum struct (1, 2) +""" + + Assert.Equal(structs, refactored reference "int * int") + Assert.Equal(reference, refactored structs "int * int") + +[] +[] +[] +let ``Parameter converts the matching argument of every call`` (reference: string, structs: string) = + Assert.Equal(structs, refactored reference "int * int") + Assert.Equal(reference, refactored structs "int * int") + +[] +let ``Value declared in another file converts there`` () = + let definition = + """ +module A + +let pair = (1, 2) +""" + + let code = + """ +module B + +let (a, b) = A.pair +""" + + use context = TestContext.CreateWithCodeAndDependency code definition + let document = refactorIn context code "a, b" + + Assert.Empty(errorsOf document) + + Assert.Equal( + """ +module B + +let struct (a, b) = A.pair +""", + textOf document + ) + + Assert.Equal( + """ +module A + +let pair = struct (1, 2) +""", + (context.Solution.Projects |> Seq.head).Documents |> Seq.head |> textOf + ) + +[] +let ``Use that cannot be followed is left for the compiler to report`` () = + let code = + """ +module M + +let pair = (1, 2) +let first = fst pair +""" + + use context = TestContext.CreateWithCode code + let document = refactorIn context code "1, 2" + + Assert.Equal( + """ +module M + +let pair = struct (1, 2) +let first = fst pair +""", + textOf document + ) + + Assert.Equal(5, (errorsOf document |> Array.exactlyOne).StartLine) + +[] +let ``Return type converts the result and the patterns taking it apart`` () = + let reference = + """ +module M + +let origin () : int * int = (0, 0) +let (x, y) = origin () +""" + + let structs = + """ +module M + +let origin () : struct (int * int) = struct (0, 0) +let struct (x, y) = origin () +""" + + Assert.Equal(structs, refactored reference "int * int") + Assert.Equal(reference, refactored structs "int * int") + +[] +let ``Record field converts its values and the patterns on it`` () = + let reference = + """ +module M + +type Line = { Start: int * int; Finish: int * int } + +let line = { Start = (0, 0); Finish = (1, 1) } +let (sx, sy) = line.Start +""" + + let structs = + """ +module M + +type Line = { Start: struct (int * int); Finish: int * int } + +let line = { Start = struct (0, 0); Finish = (1, 1) } +let struct (sx, sy) = line.Start +""" + + Assert.Equal(structs, refactored reference "int * int; Finish") + Assert.Equal(reference, refactored structs "int * int); Finish") + +[] +let ``Title names the target kind`` () = + let reference = + """ +module M + +let pair = (1, 2) +""" + + let structs = + """ +module M + +let pair = struct (1, 2) +""" + + Assert.Equal("Convert to struct tuple", (actionsAt reference "1, 2" |> Seq.exactlyOne).Title) + Assert.Equal("Convert to reference tuple", (actionsAt structs "1, 2" |> Seq.exactlyOne).Title) + +[] +[] +[] +[ +""", + "1, 2")>] +let ``No action`` (code: string, marker: string) = Assert.Empty(actionsAt code marker) diff --git a/vsintegration/tests/FSharp.Editor.Tests/Refactors/RefactorTestFramework.fs b/vsintegration/tests/FSharp.Editor.Tests/Refactors/RefactorTestFramework.fs index 849da8c84ec..88800677c38 100644 --- a/vsintegration/tests/FSharp.Editor.Tests/Refactors/RefactorTestFramework.fs +++ b/vsintegration/tests/FSharp.Editor.Tests/Refactors/RefactorTestFramework.fs @@ -8,6 +8,8 @@ open Microsoft.CodeAnalysis open Microsoft.CodeAnalysis.Text open Microsoft.VisualStudio.FSharp.Editor.CancellableTasks +open FSharp.Compiler.CodeAnalysis + open FSharp.Editor.Tests.Helpers open Microsoft.CodeAnalysis.CodeRefactorings open Microsoft.CodeAnalysis.CodeActions @@ -31,7 +33,13 @@ type TestContext(Solution: Solution) = new TestContext(solution) static member CreateWithCodeAndDependency (code: string) (codeForPreviousFile: string) = - let mutable solution = RoslynTestHelpers.CreateSolution(codeForPreviousFile) + let options = + { RoslynTestHelpers.DefaultProjectOptions with + SourceFiles = [| "C:\\test.fs"; "C:\\test2.fs" |] + } + + let mutable solution = + RoslynTestHelpers.CreateSolution(codeForPreviousFile, options) let firstProject = solution.Projects.First() solution <- solution.AddDocument(DocumentId.CreateNewId(firstProject.Id), "test2.fs", code, filePath = "C:\\test2.fs") From c4880aaaf40b8afe8072b26650ded7b802f467fe Mon Sep 17 00:00:00 2001 From: Andrii Chebukin Date: Mon, 14 Sep 2026 17:01:36 +0200 Subject: [PATCH 02/17] Build the two-file refactoring test project as a synthetic project Adding the second document to a single-file solution left Find All References unable to see either file, so a chain through a function's call sites stopped at the first file. The synthetic project gives both files to the checker the way AddReturnTypeTests and FindReferencesTests set up theirs. Co-Authored-By: Claude Opus 5 (1M context) --- .../Refactors/RefactorTestFramework.fs | 22 ++++++++++--------- 1 file changed, 12 insertions(+), 10 deletions(-) diff --git a/vsintegration/tests/FSharp.Editor.Tests/Refactors/RefactorTestFramework.fs b/vsintegration/tests/FSharp.Editor.Tests/Refactors/RefactorTestFramework.fs index 88800677c38..c5f2602b108 100644 --- a/vsintegration/tests/FSharp.Editor.Tests/Refactors/RefactorTestFramework.fs +++ b/vsintegration/tests/FSharp.Editor.Tests/Refactors/RefactorTestFramework.fs @@ -8,7 +8,7 @@ open Microsoft.CodeAnalysis open Microsoft.CodeAnalysis.Text open Microsoft.VisualStudio.FSharp.Editor.CancellableTasks -open FSharp.Compiler.CodeAnalysis +open FSharp.Test.ProjectGeneration open FSharp.Editor.Tests.Helpers open Microsoft.CodeAnalysis.CodeRefactorings @@ -33,17 +33,19 @@ type TestContext(Solution: Solution) = new TestContext(solution) static member CreateWithCodeAndDependency (code: string) (codeForPreviousFile: string) = - let options = - { RoslynTestHelpers.DefaultProjectOptions with - SourceFiles = [| "C:\\test.fs"; "C:\\test2.fs" |] + let project = + { SyntheticProject.Create( + { sourceFile "First" [] with + Source = codeForPreviousFile + }, + { sourceFile "Second" [ "First" ] with + Source = code + } + ) with + AutoAddModules = false } - let mutable solution = - RoslynTestHelpers.CreateSolution(codeForPreviousFile, options) - - let firstProject = solution.Projects.First() - solution <- solution.AddDocument(DocumentId.CreateNewId(firstProject.Id), "test2.fs", code, filePath = "C:\\test2.fs") - + let solution, _ = RoslynTestHelpers.CreateSolution project new TestContext(solution) let tryRefactor (code: string) (cursorPosition) (context: TestContext) (refactorProvider: 'T :> CodeRefactoringProvider) = From c80c1e56c670017686395683763de51df0a665ac Mon Sep 17 00:00:00 2001 From: Andrii Chebukin Date: Mon, 14 Sep 2026 17:09:15 +0200 Subject: [PATCH 03/17] Check the two-file tuple result as a new project The synthetic project's checker reads the other file from disk, so checking the refactored document saw the old definition; a struct tuple pattern happens to accept a reference tuple, which hid that. Co-Authored-By: Claude Opus 5 (1M context) --- .../Refactors/ConvertTupleTests.fs | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/vsintegration/tests/FSharp.Editor.Tests/Refactors/ConvertTupleTests.fs b/vsintegration/tests/FSharp.Editor.Tests/Refactors/ConvertTupleTests.fs index adcacd08618..e8c89da12f5 100644 --- a/vsintegration/tests/FSharp.Editor.Tests/Refactors/ConvertTupleTests.fs +++ b/vsintegration/tests/FSharp.Editor.Tests/Refactors/ConvertTupleTests.fs @@ -178,8 +178,6 @@ let (a, b) = A.pair use context = TestContext.CreateWithCodeAndDependency code definition let document = refactorIn context code "a, b" - Assert.Empty(errorsOf document) - Assert.Equal( """ module B @@ -198,6 +196,15 @@ let pair = struct (1, 2) (context.Solution.Projects |> Seq.head).Documents |> Seq.head |> textOf ) + // The checker reads the other file of a synthetic project from disk, so the result is checked as a new project. + let definitionAfter = + (context.Solution.Projects |> Seq.head).Documents |> Seq.head |> textOf + + use checkContext = + TestContext.CreateWithCodeAndDependency (textOf document) definitionAfter + + Assert.Empty((checkContext.Solution.Projects |> Seq.head).Documents |> Seq.last |> errorsOf) + [] let ``Use that cannot be followed is left for the compiler to report`` () = let code = From a7518470a9cd8d82419b9d9db4e07be6e2908dab Mon Sep 17 00:00:00 2001 From: Andrii Chebukin Date: Mon, 14 Sep 2026 19:59:10 +0200 Subject: [PATCH 04/17] Leave a method's parameter list alone and convert curried tuple arguments with their calls The only argument of a member or constructor is its parameter list, not a tuple, so it is no longer offered. A tuple that is a whole curried argument of a function or member now converts the matching argument at every call, and `struct` no longer runs into a name the parenthesis follows (`f(a, b)`). Co-Authored-By: Claude Opus 5 (1M context) --- .../FSharp.Editor/Refactor/TupleConversion.fs | 28 ++++++- .../Refactor/TuplePropagation.fs | 50 +++++++++--- .../Refactors/ConvertTupleTests.fs | 80 +++++++++++++++++++ 3 files changed, 143 insertions(+), 15 deletions(-) diff --git a/vsintegration/src/FSharp.Editor/Refactor/TupleConversion.fs b/vsintegration/src/FSharp.Editor/Refactor/TupleConversion.fs index fb3ec7ddc23..979b730a7b6 100644 --- a/vsintegration/src/FSharp.Editor/Refactor/TupleConversion.fs +++ b/vsintegration/src/FSharp.Editor/Refactor/TupleConversion.fs @@ -54,6 +54,12 @@ let private tryEnclosingParen (sourceText: SourceText) (span: TextSpan) = else ValueNone +/// `struct ` to insert in front of the `(` at the position, after a space when it would run into a name: `f(a, b)`. +let private structAt (sourceText: SourceText) (position: int) = + match if position > 0 then sourceText[position - 1] else ' ' with + | c when Char.IsLetterOrDigit c || c = '_' || c = '\'' || c = '`' || c = ')' || c = ']' -> " struct " + | _ -> "struct " + /// Whether the text between start and finish is a whole generic argument: `<` or `,` before it, `>` or `,` after. let private isGenericArgument (sourceText: SourceText) (start: int) (finish: int) = let mutable before = start - 1 @@ -104,6 +110,19 @@ let isArgumentList (tuple: SynExpr) (path: SyntaxVisitorPath) = expr = arg)) :: _ -> isSame inner tuple && isSame arg paren | _ -> false +/// Whether the tuple pattern is the parameter list of a member or constructor: its only argument, parenthesized or +/// (a struct tuple) not. +let isParameterList (tuple: SynPat) (path: SyntaxVisitorPath) = + let struct (argument, headPath) = + match path with + | SyntaxNode.SynPat(SynPat.Paren(pat = inner) as paren) :: rest when isSame inner tuple -> struct (paren, rest) + | _ -> struct (tuple, path) + + match headPath with + | SyntaxNode.SynPat(SynPat.LongIdent(argPats = SynArgPats.Pats [ only ])) :: SyntaxNode.SynBinding(SynBinding( + valData = SynValData(memberFlags = Some _))) :: _ -> isSame only argument + | _ -> false + /// Changes giving a tuple expression the target kind; ValueNone when it is not a tuple or cannot change in place. let tryExprChanges (sourceText: SourceText) (toStruct: bool) (tuple: SynExpr) (path: SyntaxVisitorPath) = match tuple with @@ -112,7 +131,8 @@ let tryExprChanges (sourceText: SourceText) (toStruct: bool) (tuple: SynExpr) (p | SynExpr.Tuple(range = m) -> match path with | SyntaxNode.SynExpr(SynExpr.Paren(expr = inner; range = parenRange)) :: _ when isSame inner tuple -> - ValueSome [ TextChange(TextSpan((spanOf sourceText parenRange).Start, 0), "struct ") ] + let start = (spanOf sourceText parenRange).Start + ValueSome [ TextChange(TextSpan(start, 0), structAt sourceText start) ] | _ when m.StartLine = m.EndLine -> let span = spanOf sourceText m @@ -132,7 +152,8 @@ let tryPatChanges (sourceText: SourceText) (toStruct: bool) (tuple: SynPat) (pat | SynPat.Tuple(range = m) -> match path with | SyntaxNode.SynPat(SynPat.Paren(pat = inner; range = parenRange)) :: _ when isSame inner tuple -> - ValueSome [ TextChange(TextSpan((spanOf sourceText parenRange).Start, 0), "struct ") ] + let start = (spanOf sourceText parenRange).Start + ValueSome [ TextChange(TextSpan(start, 0), structAt sourceText start) ] | _ when m.StartLine = m.EndLine -> let span = spanOf sourceText m @@ -202,7 +223,8 @@ let tryCaretNode (caret: pos) (parseTree: ParsedInput) = match node with | SyntaxNode.SynExpr(SynExpr.Tuple(range = m) as tuple) when containsPos m caret && not (isArgumentList tuple path) -> ValueSome(CaretNode.Expr(tuple, path)) - | SyntaxNode.SynPat(SynPat.Tuple(range = m) as tuple) when containsPos m caret -> ValueSome(CaretNode.Pat(tuple, path)) + | SyntaxNode.SynPat(SynPat.Tuple(range = m) as tuple) when containsPos m caret && not (isParameterList tuple path) -> + ValueSome(CaretNode.Pat(tuple, path)) | SyntaxNode.SynPat(SynPat.Typed(targetType = annotation) as pat) when containsPos annotation.Range caret -> annotationAt annotation (Annotated.Pattern(pat, path)) |> ValueOption.orElse found diff --git a/vsintegration/src/FSharp.Editor/Refactor/TuplePropagation.fs b/vsintegration/src/FSharp.Editor/Refactor/TuplePropagation.fs index d816c0ffc3d..4e87537351b 100644 --- a/vsintegration/src/FSharp.Editor/Refactor/TuplePropagation.fs +++ b/vsintegration/src/FSharp.Editor/Refactor/TuplePropagation.fs @@ -130,6 +130,20 @@ let rec private tryMatchedExpression (pat: SynPat) (path: SyntaxVisitorPath) = ValueSome(struct (scrutinee, SyntaxNode.SynExpr matchExpr :: rest)) | _ -> ValueNone +/// The function and the curried group of which the pattern is the whole argument, parenthesized or (a struct tuple) not. +let private tryWholeArgument (pat: SynPat) (path: SyntaxVisitorPath) = + let struct (argument, headPath) = + match path with + | SyntaxNode.SynPat(SynPat.Paren(pat = inner) as paren) :: rest when isSame inner pat -> struct (paren, rest) + | _ -> struct (pat, path) + + match headPath with + | SyntaxNode.SynPat(SynPat.LongIdent(longDotId = SynLongIdent(id = ids); argPats = SynArgPats.Pats args)) :: SyntaxNode.SynBinding _ :: _ -> + match List.tryFindIndex (isSame argument) args, List.tryLast ids with + | Some group, Some name -> ValueSome(struct (name, group)) + | _ -> ValueNone + | _ -> ValueNone + /// The expression node a symbol use stands for: an identifier, or the last part of a dotted name. let private tryUseNode (tree: ParsedInput) (useRange: range) = let isUse (ident: Ident) = @@ -168,21 +182,30 @@ let private tryRecordFieldValue (tree: ParsedInput) (useRange: range) = /// The pattern declaring a parameter of the function declared at the range: its whole curried argument, or one /// element of an argument that is a tuple of parameters. let private tryParameterPattern (tree: ParsedInput) (declaration: range) (group: int) (index: int voption) = + let pathTo (pat: SynPat) (parentPath: SyntaxVisitorPath) = + match pat with + | SynPat.Paren _ -> SyntaxNode.SynPat pat :: parentPath + | _ -> parentPath + (ValueNone, tree) - ||> ParsedInput.fold (fun found _ node -> + ||> ParsedInput.fold (fun found path node -> match found, node with | ValueNone, - SyntaxNode.SynBinding(SynBinding(headPat = SynPat.LongIdent(longDotId = SynLongIdent(id = ids); argPats = SynArgPats.Pats args))) when + SyntaxNode.SynBinding(SynBinding( + headPat = SynPat.LongIdent(longDotId = SynLongIdent(id = ids); argPats = SynArgPats.Pats args) as headPat)) when group < args.Length && List.tryLast ids |> Option.exists (fun ident -> Position.posEq ident.idRange.Start declaration.Start) -> - match stripParenPats (List.item group args), index with - | SynPat.Tuple(elementPats = elements), ValueSome index when index < elements.Length -> - ValueSome(stripParenPats (List.item index elements)) - | SynPat.Tuple _, _ + let argument = List.item group args + let argumentPath = pathTo argument (SyntaxNode.SynPat headPat :: node :: path) + + match stripParenPats argument, index with + | SynPat.Tuple(elementPats = elements) as tuple, ValueSome index when index < elements.Length -> + let element = List.item index elements + ValueSome(struct (stripParenPats element, pathTo element (SyntaxNode.SynPat tuple :: argumentPath))) | _, ValueSome _ -> ValueNone - | parameter, ValueNone -> ValueSome parameter + | parameter, ValueNone -> ValueSome(struct (parameter, argumentPath)) | _ -> found) let private annotationChanges (sourceText: SourceText) (toStruct: bool) (annotation: SynType) = @@ -309,7 +332,7 @@ type private Engine(solution: Solution, toStruct: bool, userOpName: string) = this.IntoPattern source inner (SyntaxNode.SynPat pat :: path) | SynPat.Named(ident = SynIdent(ident, _)) | SynPat.LongIdent(longDotId = SynLongIdent(id = [ ident ]); argPats = SynArgPats.Pats []) -> this.EnqueueSymbol source ident - | SynPat.Tuple _ -> this.AddOrFail source (tryPatChanges source.Text toStruct pat path) + | SynPat.Tuple _ when not (isParameterList pat path) -> this.AddOrFail source (tryPatChanges source.Text toStruct pat path) | _ -> () /// The value of the node now has the changing kind: pass that on to where it goes. @@ -487,9 +510,11 @@ type private Engine(solution: Solution, toStruct: bool, userOpName: string) = let! definition = this.Load document match tryParameterPattern definition.Tree declaration group index with - | ValueSome parameter -> + | ValueSome(struct (SynPat.Tuple _ as parameter, parameterPath)) when isParameterList parameter parameterPath -> () + | ValueSome(struct (parameter, parameterPath)) -> match parameter with | SynPat.Typed(targetType = annotation) -> this.Add definition (annotationChanges definition.Text toStruct annotation) + | SynPat.Tuple _ -> this.AddOrFail definition (tryPatChanges definition.Text toStruct parameter parameterPath) | _ -> () match tryPatternIdent parameter with @@ -526,9 +551,10 @@ type private Engine(solution: Solution, toStruct: bool, userOpName: string) = | CaretNode.Pat(tuple, path) -> this.AddOrFail source (tryPatChanges source.Text toStruct tuple path) - match tryMatchedExpression tuple path with - | ValueSome(struct (matched, matchedPath)) -> this.Retarget source matched matchedPath - | ValueNone -> () + match tryMatchedExpression tuple path, tryWholeArgument tuple path with + | ValueSome(struct (matched, matchedPath)), _ -> this.Retarget source matched matchedPath + | ValueNone, ValueSome(struct (name, group)) -> this.EnqueueParameter source name group ValueNone + | ValueNone, ValueNone -> () | CaretNode.Type(tuple, annotated, isWholeAnnotation) -> this.Add source (typeChanges source.Text toStruct isWholeAnnotation tuple) diff --git a/vsintegration/tests/FSharp.Editor.Tests/Refactors/ConvertTupleTests.fs b/vsintegration/tests/FSharp.Editor.Tests/Refactors/ConvertTupleTests.fs index e8c89da12f5..e5b20a66fba 100644 --- a/vsintegration/tests/FSharp.Editor.Tests/Refactors/ConvertTupleTests.fs +++ b/vsintegration/tests/FSharp.Editor.Tests/Refactors/ConvertTupleTests.fs @@ -159,6 +159,65 @@ let ``Parameter converts the matching argument of every call`` (reference: strin Assert.Equal(structs, refactored reference "int * int") Assert.Equal(reference, refactored structs "int * int") +[] +[] +[] +let ``Tuple argument of a curried function or member converts with its calls`` (reference: string, marker: string, structs: string) = + Assert.Equal(structs, refactored reference marker) + Assert.Equal(reference, refactored structs marker) + +[] +let ``Struct keyword is separated from a name the parenthesis follows`` () = + let code = + """ +module M + +let add(a, b) c = a + b + c + +let total = add (1, 2) 3 +""" + + Assert.Equal( + """ +module M + +let add struct (a, b) c = a + b + c + +let total = add struct (1, 2) 3 +""", + refactored code "a, b" + ) + [] let ``Value declared in another file converts there`` () = let definition = @@ -314,4 +373,25 @@ module M let quoted = <@ (1, 2) @> """, "1, 2")>] +[] +[] +[] let ``No action`` (code: string, marker: string) = Assert.Empty(actionsAt code marker) From f47024887c6668ef41855df7ad75494ebaa0aaeb Mon Sep 17 00:00:00 2001 From: Andrii Chebukin Date: Mon, 14 Sep 2026 21:36:25 +0200 Subject: [PATCH 05/17] Link the release note to the pull request and move it to a random line of its section Co-Authored-By: Claude Opus 5 (1M context) --- docs/release-notes/.VisualStudio/18.vNext.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/release-notes/.VisualStudio/18.vNext.md b/docs/release-notes/.VisualStudio/18.vNext.md index cf222e72dda..1af65e6ddab 100644 --- a/docs/release-notes/.VisualStudio/18.vNext.md +++ b/docs/release-notes/.VisualStudio/18.vNext.md @@ -3,6 +3,7 @@ * Suggest active-pattern cases from unopened modules and offer valid Add Open and qualification edits. ([PR #20719](https://github.com/dotnet/fsharp/pull/20719)) * Add maintainer-requested F# Apex Visual Studio integration tests on DartLab-1ES CloudTest, using PR pipeline definitions pinned to an explicitly requested commit SHA. ([PR #20625](https://github.com/dotnet/fsharp/pull/20625)) * Code-fixes for FS3888 (compiler-semantic attribute on the `.fs` but not the `.fsi`): copy the attribute into the `.fsi`, or remove it from the `.fs`. ([Issue #19560](https://github.com/dotnet/fsharp/issues/19560), [PR #19880](https://github.com/dotnet/fsharp/pull/19880)) +* Refactoring to convert a tuple between a reference tuple and a struct tuple, following its value through the solution: annotations of values, parameters, record fields and results it flows through, tuple patterns that take it apart, and the arguments and values that flow into it. What cannot be followed (`fst`, `snd`, generic collections) is left for the compiler to report. ([PR #20548](https://github.com/dotnet/fsharp/pull/20548)) * Expand `` in IDE tooltips, completion, and signature help, inheriting XML documentation from base classes, interfaces, overridden members, and constructors. ([Issue #19175](https://github.com/dotnet/fsharp/issues/19175), [PR #19188](https://github.com/dotnet/fsharp/pull/19188)) * Move F# editor and Interactive options to 43 native Unified Settings with independent roaming and a one-time import of existing settings. Preserve the legacy groupings and Interactive setting order, with restart requirements displayed by Unified Settings. Quick Info's preferred description width is a checkbox with a dependent integer control. Remove the eight legacy options pages; the user-wide compiler setting remains external. Typing and deletion completion triggers are independent. ([PR #20877](https://github.com/dotnet/fsharp/pull/20877)) * Added a **Compiler** option in F# Unified Settings, **"Use the .NET SDK F# compiler for builds"**, on by default. Visual Studio uses the .NET SDK F# compiler when the project supplies SDK paths, matching `dotnet build`. Otherwise, it uses the bundled .NET Framework compiler. Turn the option off to use the bundled compiler for all projects. Command-line builds are unaffected. ([Issue #20484](https://github.com/dotnet/fsharp/issues/20484), [PR #20485](https://github.com/dotnet/fsharp/pull/20485)) From 89ac5aed5b1c62b2dbcdd5b4ea6e1ea6e5b08a44 Mon Sep 17 00:00:00 2001 From: XperiAndri Date: Tue, 29 Sep 2026 19:17:18 +0200 Subject: [PATCH 06/17] Tell argument lists by the called symbol and follow values through try and match aliases A parenthesized tuple applied to a method, a constructor or a union case of several fields is an argument list however the call is spaced. Results flow through try/finally and try/with, a match clause that names the value passes it on, and removing `struct` from a type keeps a comment before its parenthesis. `struct` is kept apart from a name ending in any identifier character the lexer accepts, combining marks included. Co-Authored-By: Claude Opus 5.5 --- .../FSharp.Editor/Refactor/ConvertTuple.fs | 12 +- .../FSharp.Editor/Refactor/TupleConversion.fs | 150 ++++++++++++++++-- .../Refactor/TuplePropagation.fs | 31 ++-- .../Refactors/ConvertTupleTests.fs | 115 ++++++++++++++ 4 files changed, 285 insertions(+), 23 deletions(-) diff --git a/vsintegration/src/FSharp.Editor/Refactor/ConvertTuple.fs b/vsintegration/src/FSharp.Editor/Refactor/ConvertTuple.fs index 57c69b9a132..3f8c11f4339 100644 --- a/vsintegration/src/FSharp.Editor/Refactor/ConvertTuple.fs +++ b/vsintegration/src/FSharp.Editor/Refactor/ConvertTuple.fs @@ -54,7 +54,17 @@ type internal FSharpConvertTupleRefactoring [] () = let linePosition = sourceText.Lines.GetLinePosition context.Span.Start Position.mkPos (Line.fromZ linePosition.Line) linePosition.Character - match tryCaretNode caret parseResults.ParseTree with + // Telling an argument list from a tuple value takes resolving the call; skip that when no tuple is near. + let! found = + match tryCaretNode (fun _ -> false) caret parseResults.ParseTree with + | ValueNone -> CancellableTask.singleton ValueNone + | ValueSome _ -> + cancellableTask { + let! _, checkResults = document.GetFSharpParseAndCheckResultsAsync(nameof FSharpConvertTupleRefactoring) + return tryCaretNode (callsMethod sourceText checkResults) caret parseResults.ParseTree + } + + match found with | ValueSome caretNode when not (isInQuotation caretNode) -> let title = if isStructNode caretNode then diff --git a/vsintegration/src/FSharp.Editor/Refactor/TupleConversion.fs b/vsintegration/src/FSharp.Editor/Refactor/TupleConversion.fs index 979b730a7b6..c23a55dd49d 100644 --- a/vsintegration/src/FSharp.Editor/Refactor/TupleConversion.fs +++ b/vsintegration/src/FSharp.Editor/Refactor/TupleConversion.fs @@ -3,9 +3,12 @@ module internal Microsoft.VisualStudio.FSharp.Editor.TupleConversion open System +open System.Globalization open Microsoft.CodeAnalysis.Text +open FSharp.Compiler.CodeAnalysis +open FSharp.Compiler.Symbols open FSharp.Compiler.Syntax open FSharp.Compiler.Text @@ -32,6 +35,89 @@ let private structKeyword (sourceText: SourceText) (m: range) = TextSpan.FromBounds(start, finish) +/// The position of the first character from the position on that is not a blank or in a comment. +let rec private skipTrivia (sourceText: SourceText) (position: int) = + let at offset = + if position + offset < sourceText.Length then + sourceText[position + offset] + else + '\000' + + if position >= sourceText.Length then + position + elif Char.IsWhiteSpace(at 0) then + skipTrivia sourceText (position + 1) + elif at 0 = '/' && at 1 = '/' then + let line = sourceText.Lines.GetLineFromPosition position + skipTrivia sourceText line.EndIncludingLineBreak + elif at 0 = '(' && at 1 = '*' && at 2 <> ')' then + let mutable depth = 1 + let mutable current = position + 2 + + while depth > 0 && current < sourceText.Length do + if + sourceText[current] = '(' + && current + 1 < sourceText.Length + && sourceText[current + 1] = '*' + then + depth <- depth + 1 + current <- current + 2 + elif + sourceText[current] = '*' + && current + 1 < sourceText.Length + && sourceText[current + 1] = ')' + then + depth <- depth - 1 + current <- current + 2 + else + current <- current + 1 + + skipTrivia sourceText current + else + position + +/// Whether the character before the position ends an identifier, by the lexer's rule for identifier characters. +let isIdentifierCharBefore (sourceText: SourceText) (position: int) = + if position <= 0 then + false + else + let last = sourceText[position - 1] + + let category = + if + Char.IsLowSurrogate last + && position >= 2 + && Char.IsHighSurrogate sourceText[position - 2] + then + CharUnicodeInfo.GetUnicodeCategory(String([| sourceText[position - 2]; last |]), 0) + else + CharUnicodeInfo.GetUnicodeCategory last + + match category with + | UnicodeCategory.UppercaseLetter + | UnicodeCategory.LowercaseLetter + | UnicodeCategory.TitlecaseLetter + | UnicodeCategory.ModifierLetter + | UnicodeCategory.OtherLetter + | UnicodeCategory.LetterNumber + | UnicodeCategory.DecimalDigitNumber + | UnicodeCategory.ConnectorPunctuation + | UnicodeCategory.NonSpacingMark + | UnicodeCategory.SpacingCombiningMark + | UnicodeCategory.Format -> true + | _ -> last = '\'' + +/// Whether text inserted at the position would run into the name or closing bracket before it: `f(a, b)`. +let needsSpaceBefore (sourceText: SourceText) (position: int) = + isIdentifierCharBefore sourceText position + || position > 0 + && match sourceText[position - 1] with + | '`' + | ')' + | ']' + | '}' -> true + | _ -> false + /// The position of the `(` that, with its `)`, encloses only the span and blanks. let private tryEnclosingParen (sourceText: SourceText) (span: TextSpan) = let mutable before = span.Start - 1 @@ -56,9 +142,10 @@ let private tryEnclosingParen (sourceText: SourceText) (span: TextSpan) = /// `struct ` to insert in front of the `(` at the position, after a space when it would run into a name: `f(a, b)`. let private structAt (sourceText: SourceText) (position: int) = - match if position > 0 then sourceText[position - 1] else ' ' with - | c when Char.IsLetterOrDigit c || c = '_' || c = '\'' || c = '`' || c = ')' || c = ']' -> " struct " - | _ -> "struct " + if needsSpaceBefore sourceText position then + " struct " + else + "struct " /// Whether the text between start and finish is a whole generic argument: `<` or `,` before it, `>` or `,` after. let private isGenericArgument (sourceText: SourceText) (start: int) (finish: int) = @@ -93,21 +180,62 @@ let typeChanges (sourceText: SourceText) (toStruct: bool) (isWholeAnnotation: bo ] else let keyword = structKeyword sourceText m + let openParen = skipTrivia sourceText keyword.End - if isWholeAnnotation || isGenericArgument sourceText keyword.Start span.End then + if + (isWholeAnnotation || isGenericArgument sourceText keyword.Start span.End) + && openParen < span.End + && sourceText[openParen] = '(' + then [ - TextChange(TextSpan(keyword.Start, keyword.Length + 1), "") + TextChange(keyword, "") + TextChange(TextSpan(openParen, 1), "") TextChange(TextSpan(span.End - 1, 1), "") ] else [ TextChange(keyword, "") ] | _ -> [] -/// Whether the tuple is the argument list of a method, constructor or union case call rather than a tuple value. -let isArgumentList (tuple: SynExpr) (path: SyntaxVisitorPath) = +/// Whether the applied expression names a method or constructor that takes one argument list, or a union case of +/// several fields: its parenthesized argument is an argument list. A name that does not resolve counts as one. +let callsMethod (sourceText: SourceText) (checkResults: FSharpCheckFileResults) (funcExpr: SynExpr) = + let rec tryName (expr: SynExpr) = + match expr with + | SynExpr.Ident ident -> ValueSome ident + | SynExpr.LongIdent(longDotId = SynLongIdent(id = ids)) + | SynExpr.DotGet(longDotId = SynLongIdent(id = ids)) -> + match List.tryLast ids with + | Some ident -> ValueSome ident + | None -> ValueNone + | SynExpr.TypeApp(expr = inner) -> tryName inner + | _ -> ValueNone + + match tryName funcExpr with + | ValueNone -> false + | ValueSome ident -> + let line = sourceText.Lines[Line.toZ ident.idRange.EndLine].ToString() + + match checkResults.GetSymbolUseAtLocation(ident.idRange.EndLine, ident.idRange.EndColumn, line, [ ident.idText ]) with + | Some symbolUse -> + match symbolUse.Symbol with + | :? FSharpMemberOrFunctionOrValue as mfv -> + mfv.IsMember + && not mfv.IsProperty + && not mfv.IsEvent + && mfv.CurriedParameterGroups.Count <= 1 + | :? FSharpUnionCase as unionCase -> unionCase.Fields.Count > 1 + | :? FSharpEntity -> true + | _ -> false + | None -> true + +/// Whether the tuple is the argument list of a method, constructor or union case call rather than a tuple value, +/// however the call is spaced: `M(a, b)` and `M (a, b)` alike. +let isArgumentList (callsMethod: SynExpr -> bool) (tuple: SynExpr) (path: SyntaxVisitorPath) = match path with - | SyntaxNode.SynExpr(SynExpr.Paren(expr = inner) as paren) :: SyntaxNode.SynExpr(SynExpr.App(flag = ExprAtomicFlag.Atomic; argExpr = arg) | SynExpr.New( - expr = arg)) :: _ -> isSame inner tuple && isSame arg paren + | SyntaxNode.SynExpr(SynExpr.Paren(expr = inner) as paren) :: SyntaxNode.SynExpr(SynExpr.New(expr = arg)) :: _ -> + isSame inner tuple && isSame arg paren + | SyntaxNode.SynExpr(SynExpr.Paren(expr = inner) as paren) :: SyntaxNode.SynExpr(SynExpr.App( + isInfix = false; funcExpr = funcExpr; argExpr = arg)) :: _ when isSame inner tuple && isSame arg paren -> callsMethod funcExpr | _ -> false /// Whether the tuple pattern is the parameter list of a member or constructor: its only argument, parenthesized or @@ -213,7 +341,7 @@ let isStructNode (node: CaretNode) = | _ -> false /// The innermost tuple expression, pattern or annotated tuple type under the caret. -let tryCaretNode (caret: pos) (parseTree: ParsedInput) = +let tryCaretNode (callsMethod: SynExpr -> bool) (caret: pos) (parseTree: ParsedInput) = let annotationAt (annotation: SynType) (annotated: Annotated) = tryTupleTypeAt caret annotation |> ValueOption.map (fun tuple -> CaretNode.Type(tuple, annotated, isSame (stripParenTypes annotation) tuple)) @@ -221,7 +349,7 @@ let tryCaretNode (caret: pos) (parseTree: ParsedInput) = (ValueNone, parseTree) ||> ParsedInput.fold (fun found path node -> match node with - | SyntaxNode.SynExpr(SynExpr.Tuple(range = m) as tuple) when containsPos m caret && not (isArgumentList tuple path) -> + | SyntaxNode.SynExpr(SynExpr.Tuple(range = m) as tuple) when containsPos m caret && not (isArgumentList callsMethod tuple path) -> ValueSome(CaretNode.Expr(tuple, path)) | SyntaxNode.SynPat(SynPat.Tuple(range = m) as tuple) when containsPos m caret && not (isParameterList tuple path) -> ValueSome(CaretNode.Pat(tuple, path)) diff --git a/vsintegration/src/FSharp.Editor/Refactor/TuplePropagation.fs b/vsintegration/src/FSharp.Editor/Refactor/TuplePropagation.fs index 4e87537351b..ce2d9e6cdcc 100644 --- a/vsintegration/src/FSharp.Editor/Refactor/TuplePropagation.fs +++ b/vsintegration/src/FSharp.Editor/Refactor/TuplePropagation.fs @@ -358,7 +358,12 @@ type private Engine(solution: Solution, toStruct: bool, userOpName: string) = -> this.Retarget source container rest this.FlowOut source container rest - | SyntaxNode.SynMatchClause(SynMatchClause(resultExpr = result)) :: SyntaxNode.SynExpr(SynExpr.Match _ as container) :: rest when + | SyntaxNode.SynExpr(SynExpr.TryFinally(tryExpr = body) as container) :: rest when isSame body node -> + this.FlowOut source container rest + | SyntaxNode.SynExpr(SynExpr.TryWith(tryExpr = body) as container) :: rest when isSame body node -> + this.Retarget source container rest + this.FlowOut source container rest + | SyntaxNode.SynMatchClause(SynMatchClause(resultExpr = result)) :: SyntaxNode.SynExpr(SynExpr.Match _ | SynExpr.TryWith _ as container) :: rest when isSame result node -> this.Retarget source container rest @@ -384,15 +389,7 @@ type private Engine(solution: Solution, toStruct: bool, userOpName: string) = | _ -> () | SyntaxNode.SynExpr(SynExpr.Match(expr = scrutinee; clauses = clauses) as matchExpr) :: rest when isSame scrutinee node -> for SynMatchClause(pat = pat) as clause in clauses do - match stripParenPats pat with - | SynPat.Tuple _ as tuple -> - let tuplePath = - match pat with - | SynPat.Paren _ -> [ SyntaxNode.SynPat pat ] - | _ -> [ SyntaxNode.SynMatchClause clause; SyntaxNode.SynExpr matchExpr ] @ rest - - this.AddOrFail source (tryPatChanges source.Text toStruct tuple tuplePath) - | _ -> () + this.IntoPattern source pat (SyntaxNode.SynMatchClause clause :: SyntaxNode.SynExpr matchExpr :: rest) | _ -> () /// The expression must now produce the changing kind: change what it is built from. @@ -404,7 +401,8 @@ type private Engine(solution: Solution, toStruct: bool, userOpName: string) = | SynExpr.Typed(expr = inner; targetType = annotation) -> this.Add source (annotationChanges source.Text toStruct annotation) this.Retarget source inner childPath - | SynExpr.Tuple _ when not (isArgumentList expr path) -> this.AddOrFail source (tryExprChanges source.Text toStruct expr path) + | SynExpr.Tuple _ when not (isArgumentList (callsMethod source.Text source.Check) expr path) -> + this.AddOrFail source (tryExprChanges source.Text toStruct expr path) | SynExpr.Ident ident -> this.EnqueueSymbol source ident | SynExpr.LongIdent(longDotId = SynLongIdent(id = ids)) | SynExpr.DotGet(longDotId = SynLongIdent(id = ids)) -> @@ -421,6 +419,12 @@ type private Engine(solution: Solution, toStruct: bool, userOpName: string) = | SynExpr.Match(clauses = clauses) -> for SynMatchClause(resultExpr = result) as clause in clauses do this.Retarget source result (SyntaxNode.SynMatchClause clause :: childPath) + | SynExpr.TryFinally(tryExpr = body) -> this.Retarget source body childPath + | SynExpr.TryWith(tryExpr = body; withCases = handlers) -> + this.Retarget source body childPath + + for SynMatchClause(resultExpr = result) as handler in handlers do + this.Retarget source result (SyntaxNode.SynMatchClause handler :: childPath) | SynExpr.Sequential(expr2 = last) -> this.Retarget source last childPath | SynExpr.LetOrUse letOrUse -> this.Retarget source letOrUse.Body childPath | _ -> () @@ -435,6 +439,11 @@ type private Engine(solution: Solution, toStruct: bool, userOpName: string) = match node with | SyntaxNode.SynBinding(SynBinding(headPat = SynPat.Named(ident = SynIdent(ident, _)); expr = body)) when isDeclared ident -> this.Retarget source body (node :: path) + | SyntaxNode.SynExpr(SynExpr.Match(expr = scrutinee; clauses = clauses)) when + clauses + |> List.exists (fun (SynMatchClause(pat = pat)) -> tryPatternIdent pat |> ValueOption.exists isDeclared) + -> + this.Retarget source scrutinee (node :: path) | SyntaxNode.SynPat(SynPat.Typed(pat = inner; targetType = annotation)) when tryPatternIdent inner |> ValueOption.exists isDeclared -> diff --git a/vsintegration/tests/FSharp.Editor.Tests/Refactors/ConvertTupleTests.fs b/vsintegration/tests/FSharp.Editor.Tests/Refactors/ConvertTupleTests.fs index e5b20a66fba..d228de62ec5 100644 --- a/vsintegration/tests/FSharp.Editor.Tests/Refactors/ConvertTupleTests.fs +++ b/vsintegration/tests/FSharp.Editor.Tests/Refactors/ConvertTupleTests.fs @@ -358,6 +358,106 @@ let pair = struct (1, 2) [] +[ (0, 0) + +let (x, y) = make () +""", + """ +module M + +let make () = + try struct (1, 2) + with _ -> struct (0, 0) + +let struct (x, y) = make () +""")>] +let ``Result flowing out of try converts every branch of it`` (reference: string, structs: string) = + Assert.Equal(structs, refactored reference "x, y") + Assert.Equal(reference, refactored structs "x, y") + +[] +[ p +let (a, b) = copy +""", + """ +module M + +let pair = struct (1, 2) +let copy = match pair with | p -> p +let struct (a, b) = copy +""")>] +[] +let ``Value converts through the names it is bound to again`` (reference: string, structs: string) = + Assert.Equal(structs, refactored reference "1, 2") + Assert.Equal(reference, refactored structs "1, 2") + Assert.Equal(structs, refactored reference "a, b") + Assert.Equal(reference, refactored structs "a, b") + +[] +let ``Comment between struct and its parenthesis is kept`` () = + let code = + """ +module M + +type R = { Pair: struct (* note *) (int * int) } +""" + + Assert.Equal( + """ +module M + +type R = { Pair: (* note *) int * int } +""", + refactored code "int * int" + ) + +[] +let ``Struct keyword is separated from a name ending in a combining mark`` () = + let code = "\nmodule M\n\nlet f\u0301(a,b) = a+b\nlet x = f\u0301 (1,2)\n" + + Assert.Equal("\nmodule M\n\nlet f\u0301 struct (a,b) = a+b\nlet x = f\u0301 struct (1,2)\n", refactored code "a,b") + +[] +[] @@ -370,6 +470,21 @@ let biggest = System.Math.Max(1, 2) [] +[] +[ """, "1, 2")>] From 9620d95529904a06cd3137f86ce231bec266e743 Mon Sep 17 00:00:00 2001 From: XperiAndri Date: Sun, 11 Oct 2026 09:41:11 +0200 Subject: [PATCH 07/17] Follow tuples through lambdas, function aliases, named arguments and annotated patterns The conversion now also follows a tuple through - a function in parentheses, `(sum) (1, 2)`; - a name bound to a lambda, its parameters and its result; - a function alias and a partial application, `let alias = make`; - a named argument, `M(p = pair)`; - an annotated tuple pattern, `((a, b): int * int)`, from the pattern, the annotation or the value; - a value whose binding head is in parentheses, `let (pair: int * int) = (1, 2)`. It is no longer offered where the result cannot compile or nothing would change: - on the annotation of a member's only argument, which is its parameter list; - on the argument of a union case whose only field is declared a tuple; - on the argument of a method in parentheses, `(c.Add) (1, 2)`; - on a tuple over several lines without parentheses, which cannot change in place. `struct` is kept apart from type arguments the parenthesis follows: `f struct (1, 2)`. Co-Authored-By: Claude Opus 5.5 --- .../FSharp.Editor/Refactor/ConvertTuple.fs | 2 +- .../FSharp.Editor/Refactor/TupleConversion.fs | 62 ++- .../Refactor/TuplePropagation.fs | 359 +++++++++++++++--- .../Refactors/ConvertTupleTests.fs | 323 +++++++++++++++- 4 files changed, 658 insertions(+), 88 deletions(-) diff --git a/vsintegration/src/FSharp.Editor/Refactor/ConvertTuple.fs b/vsintegration/src/FSharp.Editor/Refactor/ConvertTuple.fs index 3f8c11f4339..7ddaadc13e4 100644 --- a/vsintegration/src/FSharp.Editor/Refactor/ConvertTuple.fs +++ b/vsintegration/src/FSharp.Editor/Refactor/ConvertTuple.fs @@ -65,7 +65,7 @@ type internal FSharpConvertTupleRefactoring [] () = } match found with - | ValueSome caretNode when not (isInQuotation caretNode) -> + | ValueSome caretNode when not (isInQuotation caretNode) && canChange sourceText caretNode -> let title = if isStructNode caretNode then SR.ConvertToReferenceTuple() diff --git a/vsintegration/src/FSharp.Editor/Refactor/TupleConversion.fs b/vsintegration/src/FSharp.Editor/Refactor/TupleConversion.fs index c23a55dd49d..392923c8020 100644 --- a/vsintegration/src/FSharp.Editor/Refactor/TupleConversion.fs +++ b/vsintegration/src/FSharp.Editor/Refactor/TupleConversion.fs @@ -107,7 +107,8 @@ let isIdentifierCharBefore (sourceText: SourceText) (position: int) = | UnicodeCategory.Format -> true | _ -> last = '\'' -/// Whether text inserted at the position would run into the name or closing bracket before it: `f(a, b)`. +/// Whether text inserted at the position would run into the name, closing bracket or type arguments before it: +/// `f(a, b)`, `f(a, b)`. let needsSpaceBefore (sourceText: SourceText) (position: int) = isIdentifierCharBefore sourceText position || position > 0 @@ -115,7 +116,8 @@ let needsSpaceBefore (sourceText: SourceText) (position: int) = | '`' | ')' | ']' - | '}' -> true + | '}' + | '>' -> true | _ -> false /// The position of the `(` that, with its `)`, encloses only the span and blanks. @@ -196,8 +198,9 @@ let typeChanges (sourceText: SourceText) (toStruct: bool) (isWholeAnnotation: bo [ TextChange(keyword, "") ] | _ -> [] -/// Whether the applied expression names a method or constructor that takes one argument list, or a union case of -/// several fields: its parenthesized argument is an argument list. A name that does not resolve counts as one. +/// Whether the applied expression names a method or constructor that takes one argument list, a union case of +/// several fields, or a union case whose only field is declared a tuple: its parenthesized argument is an argument +/// list, or a tuple of the kind the field declares. A name that does not resolve counts as one. let callsMethod (sourceText: SourceText) (checkResults: FSharpCheckFileResults) (funcExpr: SynExpr) = let rec tryName (expr: SynExpr) = match expr with @@ -207,7 +210,8 @@ let callsMethod (sourceText: SourceText) (checkResults: FSharpCheckFileResults) match List.tryLast ids with | Some ident -> ValueSome ident | None -> ValueNone - | SynExpr.TypeApp(expr = inner) -> tryName inner + | SynExpr.TypeApp(expr = inner) + | SynExpr.Paren(expr = inner) -> tryName inner | _ -> ValueNone match tryName funcExpr with @@ -223,7 +227,9 @@ let callsMethod (sourceText: SourceText) (checkResults: FSharpCheckFileResults) && not mfv.IsProperty && not mfv.IsEvent && mfv.CurriedParameterGroups.Count <= 1 - | :? FSharpUnionCase as unionCase -> unionCase.Fields.Count > 1 + | :? FSharpUnionCase as unionCase -> + unionCase.Fields.Count > 1 + || unionCase.Fields |> Seq.exists _.FieldType.IsTupleType | :? FSharpEntity -> true | _ -> false | None -> true @@ -238,13 +244,13 @@ let isArgumentList (callsMethod: SynExpr -> bool) (tuple: SynExpr) (path: Syntax isInfix = false; funcExpr = funcExpr; argExpr = arg)) :: _ when isSame inner tuple && isSame arg paren -> callsMethod funcExpr | _ -> false -/// Whether the tuple pattern is the parameter list of a member or constructor: its only argument, parenthesized or +/// Whether the pattern is the parameter list of a member or constructor: its only argument, parenthesized or /// (a struct tuple) not. -let isParameterList (tuple: SynPat) (path: SyntaxVisitorPath) = +let isParameterList (pat: SynPat) (path: SyntaxVisitorPath) = let struct (argument, headPath) = match path with - | SyntaxNode.SynPat(SynPat.Paren(pat = inner) as paren) :: rest when isSame inner tuple -> struct (paren, rest) - | _ -> struct (tuple, path) + | SyntaxNode.SynPat(SynPat.Paren(pat = inner) as paren) :: rest when isSame inner pat -> struct (paren, rest) + | _ -> struct (pat, path) match headPath with | SyntaxNode.SynPat(SynPat.LongIdent(argPats = SynArgPats.Pats [ only ])) :: SyntaxNode.SynBinding(SynBinding( @@ -340,6 +346,27 @@ let isStructNode (node: CaretNode) = | CaretNode.Type(tuple = SynType.Tuple(isStruct = isStruct)) -> isStruct | _ -> false +/// Whether the path shows a lambda parameter a second time. For a parameter that is not a plain name the parser puts +/// a match in the lambda's body, and the traversal walks that too; there the pattern has lost the parentheses and +/// the annotation around it. +let private isLambdaParameterAgain (pat: SynPat) (path: SyntaxVisitorPath) = + let rec lambdaArgs (path: SyntaxVisitorPath) = + match path with + | SyntaxNode.SynMatchClause _ :: SyntaxNode.SynExpr(SynExpr.Match _) :: rest -> lambdaArgs rest + | SyntaxNode.SynExpr(SynExpr.Lambda(parsedData = Some(args, _))) :: _ -> args + | _ -> [] + + let rec abovePatterns (path: SyntaxVisitorPath) = + match path with + | SyntaxNode.SynPat _ :: rest -> abovePatterns rest + | _ -> path + + match abovePatterns path with + | SyntaxNode.SynMatchClause _ :: _ as clausePath -> + lambdaArgs clausePath + |> List.exists (fun arg -> Range.rangeContainsRange arg.Range pat.Range) + | _ -> false + /// The innermost tuple expression, pattern or annotated tuple type under the caret. let tryCaretNode (callsMethod: SynExpr -> bool) (caret: pos) (parseTree: ParsedInput) = let annotationAt (annotation: SynType) (annotated: Annotated) = @@ -351,11 +378,13 @@ let tryCaretNode (callsMethod: SynExpr -> bool) (caret: pos) (parseTree: ParsedI match node with | SyntaxNode.SynExpr(SynExpr.Tuple(range = m) as tuple) when containsPos m caret && not (isArgumentList callsMethod tuple path) -> ValueSome(CaretNode.Expr(tuple, path)) + | SyntaxNode.SynPat pat when containsPos pat.Range caret && isLambdaParameterAgain pat path -> found | SyntaxNode.SynPat(SynPat.Tuple(range = m) as tuple) when containsPos m caret && not (isParameterList tuple path) -> ValueSome(CaretNode.Pat(tuple, path)) | SyntaxNode.SynPat(SynPat.Typed(targetType = annotation) as pat) when containsPos annotation.Range caret -> - annotationAt annotation (Annotated.Pattern(pat, path)) - |> ValueOption.orElse found + match annotationAt annotation (Annotated.Pattern(pat, path)) with + | ValueSome(CaretNode.Type(isWholeAnnotation = true)) when isParameterList pat path -> found + | node -> node |> ValueOption.orElse found | SyntaxNode.SynExpr(SynExpr.Typed(targetType = annotation) as expr) when containsPos annotation.Range caret -> annotationAt annotation (Annotated.Expression(expr, path)) |> ValueOption.orElse found @@ -372,3 +401,12 @@ let tryCaretNode (callsMethod: SynExpr -> bool) (caret: pos) (parseTree: ParsedI | _ -> ValueNone) |> ValueOption.orElse found | _ -> found) + +/// Whether the tuple under the caret can change in place, which a tuple over several lines without parentheses cannot. +let canChange (sourceText: SourceText) (node: CaretNode) = + let toStruct = not (isStructNode node) + + match node with + | CaretNode.Expr(tuple, path) -> (tryExprChanges sourceText toStruct tuple path).IsSome + | CaretNode.Pat(tuple, path) -> (tryPatChanges sourceText toStruct tuple path).IsSome + | CaretNode.Type _ -> true diff --git a/vsintegration/src/FSharp.Editor/Refactor/TuplePropagation.fs b/vsintegration/src/FSharp.Editor/Refactor/TuplePropagation.fs index ce2d9e6cdcc..322ddb905fe 100644 --- a/vsintegration/src/FSharp.Editor/Refactor/TuplePropagation.fs +++ b/vsintegration/src/FSharp.Editor/Refactor/TuplePropagation.fs @@ -56,11 +56,24 @@ let rec private stripParenPats (pat: SynPat) = | SynPat.Paren(pat = inner) -> stripParenPats inner | _ -> pat -/// The name of the function applied by the expression, and how many arguments are applied before it. +/// `name = value`, the form of a named argument. +[] +let private (|NameEqualsValue|_|) (expr: SynExpr) = + match expr with + | SynExpr.App( + isInfix = false + funcExpr = SynExpr.App( + isInfix = true; funcExpr = SynExpr.LongIdent(longDotId = SynLongIdent(id = [ operator ])); argExpr = SynExpr.Ident name) + argExpr = value) when String.Equals(operator.idText, "op_Equality", StringComparison.Ordinal) -> ValueSome(struct (name, value)) + | _ -> ValueNone + +/// The name of the function applied by the expression, in parentheses or not, and how many arguments are applied +/// before it. let rec private tryCallee (expr: SynExpr) (applied: int) = match expr with | SynExpr.App(isInfix = false; funcExpr = funcExpr) -> tryCallee funcExpr (applied + 1) - | SynExpr.TypeApp(expr = inner) -> tryCallee inner applied + | SynExpr.TypeApp(expr = inner) + | SynExpr.Paren(expr = inner) -> tryCallee inner applied | SynExpr.Ident ident -> ValueSome(struct (ident, applied)) | SynExpr.LongIdent(longDotId = SynLongIdent(id = ids)) | SynExpr.DotGet(longDotId = SynLongIdent(id = ids)) -> @@ -69,14 +82,21 @@ let rec private tryCallee (expr: SynExpr) (applied: int) = | None -> ValueNone | _ -> ValueNone +/// The function reference a binding's body is, with the arguments applied to it: `let alias = f` and +/// `let partial = f x` forward to `f`. +let rec private tryForwarded (body: SynExpr) = + match body with + | SynExpr.Typed(expr = inner) -> tryForwarded inner + | _ -> tryCallee body 0 + /// The application of a function reference to all of its curried argument groups. let rec private tryApplication (node: SynExpr) (path: SyntaxVisitorPath) (remaining: int) = if remaining = 0 then ValueSome(struct (node, path)) else match path with - | SyntaxNode.SynExpr(SynExpr.TypeApp(expr = inner) as typeApp) :: rest when isSame inner node -> - tryApplication typeApp rest remaining + | SyntaxNode.SynExpr(SynExpr.TypeApp(expr = inner) | SynExpr.Paren(expr = inner) as wrapper) :: rest when isSame inner node -> + tryApplication wrapper rest remaining | SyntaxNode.SynExpr(SynExpr.App(isInfix = false; funcExpr = funcExpr) as app) :: rest when isSame funcExpr node -> tryApplication app rest (remaining - 1) | _ -> ValueNone @@ -84,7 +104,8 @@ let rec private tryApplication (node: SynExpr) (path: SyntaxVisitorPath) (remain /// The argument a function reference is applied to in the given curried group. let rec private tryArgument (node: SynExpr) (path: SyntaxVisitorPath) (group: int) = match path with - | SyntaxNode.SynExpr(SynExpr.TypeApp(expr = inner) as typeApp) :: rest when isSame inner node -> tryArgument typeApp rest group + | SyntaxNode.SynExpr(SynExpr.TypeApp(expr = inner) | SynExpr.Paren(expr = inner) as wrapper) :: rest when isSame inner node -> + tryArgument wrapper rest group | SyntaxNode.SynExpr(SynExpr.App(isInfix = false; funcExpr = funcExpr; argExpr = argument) as app) :: rest when isSame funcExpr node -> if group = 0 then ValueSome(struct (argument, SyntaxNode.SynExpr app :: rest)) @@ -92,17 +113,45 @@ let rec private tryArgument (node: SynExpr) (path: SyntaxVisitorPath) (group: in tryArgument app rest (group - 1) | _ -> ValueNone -/// The function and the position of the parameter a pattern in a binding's head declares. -let rec private tryParameterPosition (pat: SynPat) (path: SyntaxVisitorPath) = +/// The name a function reference is bound to without being applied to all of its arguments, and how many it is +/// applied to: `let alias = f` and `let partial = f x`. +let rec private tryForwardingBinding (node: SynExpr) (path: SyntaxVisitorPath) (applied: int) = match path with - | SyntaxNode.SynPat(SynPat.LongIdent(longDotId = SynLongIdent(id = ids); argPats = SynArgPats.Pats args)) :: SyntaxNode.SynBinding _ :: _ -> - let found = - args - |> List.indexed - |> List.tryFind (fun (_, arg) -> containsRange arg.Range pat.Range) + | SyntaxNode.SynExpr(SynExpr.TypeApp(expr = inner) | SynExpr.Paren(expr = inner) | SynExpr.Typed(expr = inner) as wrapper) :: rest when + isSame inner node + -> + tryForwardingBinding wrapper rest applied + | SyntaxNode.SynExpr(SynExpr.App(isInfix = false; funcExpr = funcExpr) as app) :: rest when isSame funcExpr node -> + tryForwardingBinding app rest (applied + 1) + | SyntaxNode.SynBinding(SynBinding(headPat = headPat; expr = body)) :: _ when isSame body node -> + tryPatternIdent headPat |> ValueOption.map (fun name -> struct (name, applied)) + | _ -> ValueNone - match found, List.tryLast ids with - | Some(group, arg), Some name -> +/// The lambda an expression is, through parentheses and a type annotation: its parameter patterns, its body and the +/// path to them. +let rec private tryLambda (expr: SynExpr) (path: SyntaxVisitorPath) = + match expr with + | SynExpr.Paren(expr = inner) + | SynExpr.Typed(expr = inner) -> tryLambda inner (SyntaxNode.SynExpr expr :: path) + | SynExpr.Lambda(parsedData = Some(args, body)) -> ValueSome(struct (args, body, SyntaxNode.SynExpr expr :: path)) + | _ -> ValueNone + +/// The name a lambda is bound to, through parentheses and a type annotation: `let f = fun x -> x`. +let rec private tryLambdaOwner (lambda: SynExpr) (path: SyntaxVisitorPath) = + match path with + | SyntaxNode.SynExpr(SynExpr.Paren(expr = inner) | SynExpr.Typed(expr = inner) as wrapper) :: rest when isSame inner lambda -> + tryLambdaOwner wrapper rest + | SyntaxNode.SynBinding(SynBinding(headPat = headPat; expr = body)) :: _ when isSame body lambda -> tryPatternIdent headPat + | _ -> ValueNone + +/// The function and the position of the parameter a pattern in a binding's head, or among the parameters of the +/// lambda a name is bound to, declares. +let rec private tryParameterPosition (pat: SynPat) (path: SyntaxVisitorPath) = + let positionIn (args: SynPat list) (name: Ident) = + args + |> List.indexed + |> List.tryFindV (fun (_, arg) -> containsRange arg.Range pat.Range) + |> ValueOption.map (fun (group, arg) -> let index = match stripParenPats arg with | SynPat.Tuple(elementPats = elements) -> @@ -114,15 +163,25 @@ let rec private tryParameterPosition (pat: SynPat) (path: SyntaxVisitorPath) = | None -> ValueNone | _ -> ValueNone - ValueSome(struct (name, group, index)) - | _ -> ValueNone + struct (name, group, index)) + + match path with + | SyntaxNode.SynPat(SynPat.LongIdent(longDotId = SynLongIdent(id = ids); argPats = SynArgPats.Pats args)) :: SyntaxNode.SynBinding _ :: _ -> + match List.tryLast ids with + | Some name -> positionIn args name + | None -> ValueNone + | SyntaxNode.SynExpr(SynExpr.Lambda(parsedData = Some(args, _)) as lambda) :: rest -> + match tryLambdaOwner lambda rest with + | ValueSome name -> positionIn args name + | ValueNone -> ValueNone | _ :: rest -> tryParameterPosition pat rest | [] -> ValueNone -/// The expression a tuple pattern takes apart: the right-hand side of its binding or the matched expression. +/// The expression a tuple pattern takes apart, through parentheses and a type annotation: the right-hand side of its +/// binding or the matched expression. let rec private tryMatchedExpression (pat: SynPat) (path: SyntaxVisitorPath) = match path with - | SyntaxNode.SynPat(SynPat.Paren _ as paren) :: rest -> tryMatchedExpression paren rest + | SyntaxNode.SynPat(SynPat.Paren _ | SynPat.Typed _ as wrapper) :: rest -> tryMatchedExpression wrapper rest | SyntaxNode.SynBinding(SynBinding(headPat = headPat; expr = body)) :: _ when isSame headPat pat -> ValueSome(struct (body, path)) | SyntaxNode.SynMatchClause(SynMatchClause(pat = clausePat)) :: SyntaxNode.SynExpr(SynExpr.Match(expr = scrutinee) as matchExpr) :: rest when isSame clausePat pat @@ -130,18 +189,34 @@ let rec private tryMatchedExpression (pat: SynPat) (path: SyntaxVisitorPath) = ValueSome(struct (scrutinee, SyntaxNode.SynExpr matchExpr :: rest)) | _ -> ValueNone -/// The function and the curried group of which the pattern is the whole argument, parenthesized or (a struct tuple) not. +/// The type annotations on a pattern, through the parentheses around it: `((a, b): int * int)`. +let rec private annotationsOn (pat: SynPat) (path: SyntaxVisitorPath) = + match path with + | SyntaxNode.SynPat(SynPat.Paren(pat = inner) as paren) :: rest when isSame inner pat -> annotationsOn paren rest + | SyntaxNode.SynPat(SynPat.Typed(pat = inner; targetType = annotation) as typed) :: rest when isSame inner pat -> + annotation :: annotationsOn typed rest + | _ -> [] + +/// The function and the curried group of which the pattern is the whole argument, through parentheses and a type +/// annotation or (a struct tuple) with neither. The function can be a name bound to a lambda. let private tryWholeArgument (pat: SynPat) (path: SyntaxVisitorPath) = - let struct (argument, headPath) = + let rec outermost (pat: SynPat) (path: SyntaxVisitorPath) = match path with - | SyntaxNode.SynPat(SynPat.Paren(pat = inner) as paren) :: rest when isSame inner pat -> struct (paren, rest) + | SyntaxNode.SynPat(SynPat.Paren(pat = inner) | SynPat.Typed(pat = inner) as wrapper) :: rest when isSame inner pat -> + outermost wrapper rest | _ -> struct (pat, path) + let struct (argument, headPath) = outermost pat path + match headPath with | SyntaxNode.SynPat(SynPat.LongIdent(longDotId = SynLongIdent(id = ids); argPats = SynArgPats.Pats args)) :: SyntaxNode.SynBinding _ :: _ -> match List.tryFindIndex (isSame argument) args, List.tryLast ids with | Some group, Some name -> ValueSome(struct (name, group)) | _ -> ValueNone + | SyntaxNode.SynExpr(SynExpr.Lambda(parsedData = Some(args, _)) as lambda) :: rest -> + match List.tryFindIndex (isSame argument) args, tryLambdaOwner lambda rest with + | Some group, ValueSome name -> ValueSome(struct (name, group)) + | _ -> ValueNone | _ -> ValueNone /// The expression node a symbol use stands for: an identifier, or the last part of a dotted name. @@ -179,26 +254,32 @@ let private tryRecordFieldValue (tree: ParsedInput) (useRange: range) = | _ -> None) | _ -> None) -/// The pattern declaring a parameter of the function declared at the range: its whole curried argument, or one -/// element of an argument that is a tuple of parameters. +/// The body of the binding that gives the name declared at the range its value, `let name = body`, and the path to it. +let private tryNamedBinding (tree: ParsedInput) (declaration: range) = + (ValueNone, tree) + ||> ParsedInput.fold (fun found path node -> + match found, node with + | ValueNone, SyntaxNode.SynBinding(SynBinding(headPat = headPat; expr = body)) when + tryPatternIdent headPat + |> ValueOption.exists (fun ident -> Position.posEq ident.idRange.Start declaration.Start) + -> + ValueSome(struct (body, node :: path)) + | _ -> found) + +/// The pattern declaring a parameter of the function declared at the range, a function or a name bound to a lambda: +/// its whole curried argument, or one element of an argument that is a tuple of parameters. let private tryParameterPattern (tree: ParsedInput) (declaration: range) (group: int) (index: int voption) = let pathTo (pat: SynPat) (parentPath: SyntaxVisitorPath) = match pat with | SynPat.Paren _ -> SyntaxNode.SynPat pat :: parentPath | _ -> parentPath - (ValueNone, tree) - ||> ParsedInput.fold (fun found path node -> - match found, node with - | ValueNone, - SyntaxNode.SynBinding(SynBinding( - headPat = SynPat.LongIdent(longDotId = SynLongIdent(id = ids); argPats = SynArgPats.Pats args) as headPat)) when - group < args.Length - && List.tryLast ids - |> Option.exists (fun ident -> Position.posEq ident.idRange.Start declaration.Start) - -> + let parameterIn (args: SynPat list) (argsPath: SyntaxVisitorPath) = + if group >= args.Length then + ValueNone + else let argument = List.item group args - let argumentPath = pathTo argument (SyntaxNode.SynPat headPat :: node :: path) + let argumentPath = pathTo argument argsPath match stripParenPats argument, index with | SynPat.Tuple(elementPats = elements) as tuple, ValueSome index when index < elements.Length -> @@ -206,13 +287,88 @@ let private tryParameterPattern (tree: ParsedInput) (declaration: range) (group: ValueSome(struct (stripParenPats element, pathTo element (SyntaxNode.SynPat tuple :: argumentPath))) | _, ValueSome _ -> ValueNone | parameter, ValueNone -> ValueSome(struct (parameter, argumentPath)) + + (ValueNone, tree) + ||> ParsedInput.fold (fun found path node -> + match found, node with + | ValueNone, + SyntaxNode.SynBinding(SynBinding( + headPat = SynPat.LongIdent(longDotId = SynLongIdent(id = ids); argPats = SynArgPats.Pats args) as headPat)) when + List.tryLast ids + |> Option.exists (fun ident -> Position.posEq ident.idRange.Start declaration.Start) + -> + parameterIn args (SyntaxNode.SynPat headPat :: node :: path) | _ -> found) + |> ValueOption.orElseWith (fun () -> + tryNamedBinding tree declaration + |> ValueOption.bind (fun struct (body, bodyPath) -> tryLambda body bodyPath) + |> ValueOption.bind (fun struct (args, _, argsPath) -> parameterIn args argsPath)) let private annotationChanges (sourceText: SourceText) (toStruct: bool) (annotation: SynType) = match stripParenTypes annotation with | SynType.Tuple _ as tuple -> typeChanges sourceText toStruct true tuple | _ -> [] +let private hasName (name: string) (parameter: FSharpParameter) = + match parameter.Name with + | Some parameterName -> String.Equals(parameterName, name, StringComparison.Ordinal) + | None -> false + +/// The name an argument can give for the parameter of a method at the position. +let private tryParameterName (symbol: FSharpSymbol) (group: int) (index: int voption) = + match symbol with + | :? FSharpMemberOrFunctionOrValue as mfv when mfv.IsMember && group < mfv.CurriedParameterGroups.Count -> + let parameters = mfv.CurriedParameterGroups[group] + + match index with + | ValueSome index when index < parameters.Count -> parameters[index].Name + | ValueNone when parameters.Count = 1 -> parameters[0].Name + | _ -> None + | _ -> None + +/// The value an argument gives a parameter: the part of an argument list given for it by name, else the one at its +/// position, or the whole argument when the parameter is not one of a tuple of parameters. +let private tryArgumentValue (parameterName: string option) (index: int voption) (argument: SynExpr) (argumentPath: SyntaxVisitorPath) = + let struct (elements, elementsPath) = + match argument with + | SynExpr.Paren(expr = SynExpr.Tuple(exprs = exprs) as tuple) -> + struct (exprs, SyntaxNode.SynExpr tuple :: SyntaxNode.SynExpr argument :: argumentPath) + | SynExpr.Paren(expr = inner) -> struct ([ inner ], SyntaxNode.SynExpr argument :: argumentPath) + | _ -> struct ([], argumentPath) + + let named = + match parameterName with + | Some parameterName -> + elements + |> Seq.tryPickV (fun element -> + match element with + | NameEqualsValue(struct (name, value)) when String.Equals(name.idText, parameterName, StringComparison.Ordinal) -> + ValueSome(struct (value, SyntaxNode.SynExpr element :: elementsPath)) + | _ -> ValueNone) + | None -> ValueNone + + match named, index, argument with + | ValueSome _, _, _ -> named + | ValueNone, ValueSome index, SynExpr.Paren(expr = SynExpr.Tuple(exprs = exprs)) when index < exprs.Length -> + ValueSome(struct (List.item index exprs, elementsPath)) + | ValueNone, ValueSome _, _ -> ValueNone + | ValueNone, ValueNone, _ -> ValueSome(struct (argument, argumentPath)) + +/// How many curried arguments a function takes: its parameter groups or, for a function value, the arrows of its type. +let private groupCount (mfv: FSharpMemberOrFunctionOrValue) = + let rec arrows (ty: FSharpType) = + if ty.IsFunctionType then + 1 + arrows ty.GenericArguments[1] + else + 0 + + if mfv.CurriedParameterGroups.Count > 0 then + mfv.CurriedParameterGroups.Count + else + match mfv.FullTypeSafe with + | Some ty -> max 1 (arrows ty) + | None -> 1 + type private Engine(solution: Solution, toStruct: bool, userOpName: string) = let sources = Dictionary() let changes = Dictionary>() @@ -323,6 +479,35 @@ type private Engine(solution: Solution, toStruct: bool, userOpName: string) = | _ -> () | _ -> () + /// Enqueues the parameter of a method that an argument names: `M(name = value)`. + member this.EnqueueNamedParameter (source: Source) (methodName: Ident) (group: int) (parameterName: Ident) = + match symbolUseAt source methodName with + | Some methodUse -> + match methodUse.Symbol with + | :? FSharpMemberOrFunctionOrValue as mfv when mfv.IsMember && group < mfv.CurriedParameterGroups.Count -> + let parameters = mfv.CurriedParameterGroups[group] + + match parameters |> Seq.tryFindIndexV (hasName parameterName.idText) with + | ValueSome _ when parameters.Count = 1 -> this.EnqueueParameter source methodName group ValueNone + | ValueSome index -> this.EnqueueParameter source methodName group (ValueSome index) + | ValueNone -> () + | _ -> () + | None -> () + + /// The function a binding's body forwards to, with the arguments the body applies to it: a function reference + /// applied to fewer arguments than the function takes. + member _.TryForwarded (source: Source) (body: SynExpr) = + match tryForwarded body with + | ValueSome(struct (callee, applied)) -> + match symbolUseAt source callee with + | Some calleeUse -> + match calleeUse.Symbol with + | :? FSharpMemberOrFunctionOrValue as mfv when (mfv.IsFunction || mfv.IsMember) && applied < groupCount mfv -> + ValueSome(struct (callee, applied)) + | _ -> ValueNone + | None -> ValueNone + | ValueNone -> ValueNone + /// A value of the changing kind flows into a pattern. member this.IntoPattern (source: Source) (pat: SynPat) (path: SyntaxVisitorPath) = match pat with @@ -368,6 +553,20 @@ type private Engine(solution: Solution, toStruct: bool, userOpName: string) = -> this.Retarget source container rest this.FlowOut source container rest + | SyntaxNode.SynExpr(SynExpr.Lambda(parsedData = Some(_, body)) as lambda) :: rest when isSame body node -> + match tryLambdaOwner lambda rest with + | ValueSome name -> this.EnqueueResult source name + | ValueNone -> () + | SyntaxNode.SynExpr(NameEqualsValue(struct (parameterName, value))) :: rest when isSame value node -> + match rest with + | SyntaxNode.SynExpr(SynExpr.Tuple _) :: SyntaxNode.SynExpr(SynExpr.Paren _ as paren) :: SyntaxNode.SynExpr(SynExpr.App( + isInfix = false; funcExpr = funcExpr; argExpr = argument)) :: _ + | SyntaxNode.SynExpr(SynExpr.Paren _ as paren) :: SyntaxNode.SynExpr(SynExpr.App( + isInfix = false; funcExpr = funcExpr; argExpr = argument)) :: _ when isSame argument paren -> + match tryCallee funcExpr 0 with + | ValueSome(struct (methodName, group)) -> this.EnqueueNamedParameter source methodName group parameterName + | ValueNone -> () + | _ -> () | SyntaxNode.SynExpr(SynExpr.App(isInfix = false; funcExpr = funcExpr; argExpr = argument)) :: _ when isSame argument node -> match tryCallee funcExpr 0 with | ValueSome(struct (name, group)) -> this.EnqueueParameter source name group ValueNone @@ -437,7 +636,9 @@ type private Engine(solution: Solution, toStruct: bool, userOpName: string) = ((), source.Tree) ||> ParsedInput.fold (fun () path node -> match node with - | SyntaxNode.SynBinding(SynBinding(headPat = SynPat.Named(ident = SynIdent(ident, _)); expr = body)) when isDeclared ident -> + | SyntaxNode.SynBinding(SynBinding(headPat = headPat; expr = body)) when + tryPatternIdent headPat |> ValueOption.exists isDeclared + -> this.Retarget source body (node :: path) | SyntaxNode.SynExpr(SynExpr.Match(expr = scrutinee; clauses = clauses)) when clauses @@ -457,7 +658,8 @@ type private Engine(solution: Solution, toStruct: bool, userOpName: string) = | _ -> () | _ -> ()) - /// Changes the declared or inferred result of a function. + /// Changes the declared or inferred result of a function, of a name bound to a lambda, or of the function a name + /// forwards to. member this.DefineResult (source: Source) (declaration: range) = ((), source.Tree) ||> ParsedInput.fold (fun () path node -> @@ -469,6 +671,16 @@ type private Engine(solution: Solution, toStruct: bool, userOpName: string) = this.Retarget source body (node :: path) | _ -> ()) + match tryNamedBinding source.Tree declaration with + | ValueSome(struct (body, bodyPath)) -> + match tryLambda body bodyPath with + | ValueSome(struct (_, result, resultPath)) -> this.Retarget source result resultPath + | ValueNone -> + match this.TryForwarded source body with + | ValueSome(struct (callee, _)) -> this.EnqueueResult source callee + | ValueNone -> () + | ValueNone -> () + member this.ProcessSymbol (symbolUse: FSharpSymbolUse) (source: Source) = cancellableTask { match tryDeclarationDocument symbolUse.Symbol with @@ -496,7 +708,7 @@ type private Engine(solution: Solution, toStruct: bool, userOpName: string) = | ValueSome(struct (declaration, document)), (:? FSharpMemberOrFunctionOrValue as mfv) -> let! definition = this.Load document this.DefineResult definition declaration - let groups = max 1 mfv.CurriedParameterGroups.Count + let groups = groupCount mfv let! uses = SymbolHelpers.getSymbolUses functionUse source.Document source.Check for useDocument, useRange in uses do @@ -507,7 +719,10 @@ type private Engine(solution: Solution, toStruct: bool, userOpName: string) = | Some(node, path) -> match tryApplication node path groups with | ValueSome(struct (application, rest)) -> this.FlowOut useSource application rest - | ValueNone -> () + | ValueNone -> + match tryForwardingBinding node path 0 with + | ValueSome(struct (name, applied)) when applied < groups -> this.EnqueueResult useSource name + | _ -> () | None -> () | _ -> () } @@ -518,18 +733,32 @@ type private Engine(solution: Solution, toStruct: bool, userOpName: string) = | ValueSome(struct (declaration, document)) -> let! definition = this.Load document - match tryParameterPattern definition.Tree declaration group index with - | ValueSome(struct (SynPat.Tuple _ as parameter, parameterPath)) when isParameterList parameter parameterPath -> () - | ValueSome(struct (parameter, parameterPath)) -> - match parameter with - | SynPat.Typed(targetType = annotation) -> this.Add definition (annotationChanges definition.Text toStruct annotation) - | SynPat.Tuple _ -> this.AddOrFail definition (tryPatChanges definition.Text toStruct parameter parameterPath) - | _ -> () - - match tryPatternIdent parameter with - | ValueSome ident -> this.EnqueueSymbol definition ident - | ValueNone -> () - + let isFound = + match tryParameterPattern definition.Tree declaration group index with + | ValueSome(struct (SynPat.Tuple _ as parameter, parameterPath)) when isParameterList parameter parameterPath -> false + | ValueSome(struct (parameter, parameterPath)) -> + match parameter with + | SynPat.Typed _ -> this.IntoPattern definition parameter parameterPath + | SynPat.Tuple _ -> this.AddOrFail definition (tryPatChanges definition.Text toStruct parameter parameterPath) + | _ -> () + + match tryPatternIdent parameter with + | ValueSome ident -> this.EnqueueSymbol definition ident + | ValueNone -> () + + true + | ValueNone -> + match tryNamedBinding definition.Tree declaration with + | ValueSome(struct (body, _)) -> + match this.TryForwarded definition body with + | ValueSome(struct (callee, applied)) -> + this.EnqueueParameter definition callee (group + applied) index + true + | ValueNone -> false + | ValueNone -> false + + if isFound then + let parameterName = tryParameterName functionUse.Symbol group index let! uses = SymbolHelpers.getSymbolUses functionUse source.Document source.Check for useDocument, useRange in uses do @@ -538,17 +767,17 @@ type private Engine(solution: Solution, toStruct: bool, userOpName: string) = match tryUseNode useSource.Tree useRange with | Some(node, path) -> - match tryArgument node path group, index with - | ValueSome(struct (SynExpr.Paren(expr = SynExpr.Tuple(exprs = exprs) as tuple) as argument, argumentPath)), - ValueSome index when index < exprs.Length -> - this.Retarget - useSource - (List.item index exprs) - (SyntaxNode.SynExpr tuple :: SyntaxNode.SynExpr argument :: argumentPath) - | ValueSome(struct (argument, argumentPath)), ValueNone -> this.Retarget useSource argument argumentPath - | _ -> () + match tryArgument node path group with + | ValueSome(struct (argument, argumentPath)) -> + match tryArgumentValue parameterName index argument argumentPath with + | ValueSome(struct (value, valuePath)) -> this.Retarget useSource value valuePath + | ValueNone -> () + | ValueNone -> + match tryForwardingBinding node path 0 with + | ValueSome(struct (name, applied)) when applied <= group -> + this.EnqueueParameter useSource name (group - applied) index + | _ -> () | None -> () - | ValueNone -> () | ValueNone -> () } @@ -560,6 +789,9 @@ type private Engine(solution: Solution, toStruct: bool, userOpName: string) = | CaretNode.Pat(tuple, path) -> this.AddOrFail source (tryPatChanges source.Text toStruct tuple path) + for annotation in annotationsOn tuple path do + this.Add source (annotationChanges source.Text toStruct annotation) + match tryMatchedExpression tuple path, tryWholeArgument tuple path with | ValueSome(struct (matched, matchedPath)), _ -> this.Retarget source matched matchedPath | ValueNone, ValueSome(struct (name, group)) -> this.EnqueueParameter source name group ValueNone @@ -572,7 +804,12 @@ type private Engine(solution: Solution, toStruct: bool, userOpName: string) = | Annotated.Pattern(SynPat.Typed(pat = inner) as pat, path) -> match tryPatternIdent inner with | ValueSome ident -> this.EnqueueSymbol source ident - | ValueNone -> () + | ValueNone -> + this.IntoPattern source inner (SyntaxNode.SynPat pat :: path) + + match tryMatchedExpression pat path with + | ValueSome(struct (matched, matchedPath)) -> this.Retarget source matched matchedPath + | ValueNone -> () match tryParameterPosition pat path with | ValueSome(struct (name, group, index)) -> this.EnqueueParameter source name group index diff --git a/vsintegration/tests/FSharp.Editor.Tests/Refactors/ConvertTupleTests.fs b/vsintegration/tests/FSharp.Editor.Tests/Refactors/ConvertTupleTests.fs index d228de62ec5..aced945fd2c 100644 --- a/vsintegration/tests/FSharp.Editor.Tests/Refactors/ConvertTupleTests.fs +++ b/vsintegration/tests/FSharp.Editor.Tests/Refactors/ConvertTupleTests.fs @@ -62,6 +62,17 @@ module M let pairs: list = [] """)>] +[] let ``Tuple that flows nowhere else converts on its own`` (before: string, marker: string, after: string) = Assert.Equal(after, refactored before marker) Assert.Equal(before, refactored after marker) @@ -196,27 +207,35 @@ let ``Tuple argument of a curried function or member converts with its calls`` ( Assert.Equal(structs, refactored reference marker) Assert.Equal(reference, refactored structs marker) -[] -let ``Struct keyword is separated from a name the parenthesis follows`` () = - let code = - """ +[] +[] +[(1, 2) """, - refactored code "a, b" - ) + "1, 2", + """ +module M + +let nothing = ignore<_> struct (1, 2) +""")>] +let ``Struct keyword is separated from a name or type arguments the parenthesis follows`` (code: string, marker: string, after: string) = + Assert.Equal(after, refactored code marker) [] let ``Value declared in another file converts there`` () = @@ -289,8 +308,11 @@ let first = fst pair Assert.Equal(5, (errorsOf document |> Array.exactlyOne).StartLine) -[] -let ``Return type converts the result and the patterns taking it apart`` () = +[] +[] +[] +[] +let ``Return type converts the result and the patterns taking it apart`` (marker: string) = let reference = """ module M @@ -307,8 +329,8 @@ let origin () : struct (int * int) = struct (0, 0) let struct (x, y) = origin () """ - Assert.Equal(structs, refactored reference "int * int") - Assert.Equal(reference, refactored structs "int * int") + Assert.Equal(structs, refactored reference marker) + Assert.Equal(reference, refactored structs marker) [] let ``Record field converts its values and the patterns on it`` () = @@ -430,6 +452,240 @@ let ``Value converts through the names it is bound to again`` (reference: string Assert.Equal(structs, refactored reference "a, b") Assert.Equal(reference, refactored structs "a, b") +[] +[] +[] +let ``Annotated value in parentheses converts with its initializer`` (marker: string) = + let reference = + """ +module M + +let (pair: int * int) = (1, 2) +let (a, b) = pair +""" + + let structs = + """ +module M + +let (pair: struct (int * int)) = struct (1, 2) +let struct (a, b) = pair +""" + + Assert.Equal(structs, refactored reference marker) + Assert.Equal(reference, refactored structs marker) + +[] +[] +[ a + b +""", + """ +module M + +let pair = struct (1, 2) +let total = match pair with | (struct (a, b): struct (int * int)) -> a + b +""")>] +[] +[ a + b + +let total = sum (1, 2) +""", + """ +module M + +let sum = fun (struct (a, b): struct (int * int)) -> a + b + +let total = sum struct (1, 2) +""")>] +let ``Annotated tuple pattern converts with its annotation and the value it takes apart`` (reference: string, structs: string) = + for marker in [ "a, b"; "int * int"; "1, 2" ] do + Assert.Equal(structs, refactored reference marker) + Assert.Equal(reference, refactored structs marker) + +[] +[] +[] +[ a + b +let value = sum (1, 2) +""", + """ +module M + +let sum = fun struct (a, b) -> a + b +let value = sum struct (1, 2) +""")>] +[ (1, 2) +let (a, b) = make () +""", + """ +module M + +let make = fun () -> struct (1, 2) +let struct (a, b) = make () +""")>] +[] +[] +let ``Function in parentheses, bound as a lambda, aliased or partly applied converts with its calls`` (reference: string, structs: string) = + for marker in [ "1, 2"; "a, b" ] do + Assert.Equal(structs, refactored reference marker) + Assert.Equal(reference, refactored structs marker) + +[] +[] +[] +[] +let ``Named argument converts with the parameter it names`` (reference: string, structs: string, markers: string) = + for marker in markers.Split '|' do + Assert.Equal(structs, refactored reference marker) + Assert.Equal(reference, refactored structs marker) + [] let ``Comment between struct and its parenthesis is kept`` () = let code = @@ -509,4 +765,43 @@ type Point(x: int, y: int) = new(x: int, y: int, z: int) = Point(x + z, y) """, "z: int")>] +[] +[] +[] +[] +[] let ``No action`` (code: string, marker: string) = Assert.Empty(actionsAt code marker) From 8c36108935b068a21b304f7949d4ae41a07636e8 Mon Sep 17 00:00:00 2001 From: XperiAndri Date: Thu, 15 Oct 2026 02:56:38 +0100 Subject: [PATCH 08/17] Compact the tuple refactoring sources Delete the comments the code says by itself and name what they described, share the edit code of tuple expressions and patterns, share the use scan of the propagation engine and keep every function at three nested levels or fewer. Co-Authored-By: Claude Sonnet 5.5 --- .../FSharp.Editor/Refactor/ConvertTuple.fs | 10 +- .../FSharp.Editor/Refactor/TupleConversion.fs | 343 +++++----- .../Refactor/TuplePropagation.fs | 638 ++++++++---------- 3 files changed, 447 insertions(+), 544 deletions(-) diff --git a/vsintegration/src/FSharp.Editor/Refactor/ConvertTuple.fs b/vsintegration/src/FSharp.Editor/Refactor/ConvertTuple.fs index 7ddaadc13e4..1ab0d597b07 100644 --- a/vsintegration/src/FSharp.Editor/Refactor/ConvertTuple.fs +++ b/vsintegration/src/FSharp.Editor/Refactor/ConvertTuple.fs @@ -54,15 +54,17 @@ type internal FSharpConvertTupleRefactoring [] () = let linePosition = sourceText.Lines.GetLinePosition context.Span.Start Position.mkPos (Line.fromZ linePosition.Line) linePosition.Character - // Telling an argument list from a tuple value takes resolving the call; skip that when no tuple is near. + let hasTupleCandidate = + (tryCaretNode (fun _ -> false) caret parseResults.ParseTree).IsSome + let! found = - match tryCaretNode (fun _ -> false) caret parseResults.ParseTree with - | ValueNone -> CancellableTask.singleton ValueNone - | ValueSome _ -> + if hasTupleCandidate then cancellableTask { let! _, checkResults = document.GetFSharpParseAndCheckResultsAsync(nameof FSharpConvertTupleRefactoring) return tryCaretNode (callsMethod sourceText checkResults) caret parseResults.ParseTree } + else + CancellableTask.singleton ValueNone match found with | ValueSome caretNode when not (isInQuotation caretNode) && canChange sourceText caretNode -> diff --git a/vsintegration/src/FSharp.Editor/Refactor/TupleConversion.fs b/vsintegration/src/FSharp.Editor/Refactor/TupleConversion.fs index 392923c8020..b2af4a7a191 100644 --- a/vsintegration/src/FSharp.Editor/Refactor/TupleConversion.fs +++ b/vsintegration/src/FSharp.Editor/Refactor/TupleConversion.fs @@ -17,15 +17,17 @@ let spanOf (sourceText: SourceText) (m: range) = let isSame (node: 'T) (other: 'T) = obj.ReferenceEquals(node, other) -let containsPos (m: range) (position: pos) = - Position.posGeq position m.Start && Position.posGeq m.End position - let rec stripParenTypes (ty: SynType) = match ty with | SynType.Paren(innerType = inner) -> stripParenTypes inner | _ -> ty -/// `struct` and the blanks after it, at the start of a struct tuple's range. +let private charAt (sourceText: SourceText) (position: int) = + if position >= 0 && position < sourceText.Length then + sourceText[position] + else + '\000' + let private structKeyword (sourceText: SourceText) (m: range) = let start = (spanOf sourceText m).Start let mutable finish = start + "struct".Length @@ -35,13 +37,24 @@ let private structKeyword (sourceText: SourceText) (m: range) = TextSpan.FromBounds(start, finish) -/// The position of the first character from the position on that is not a blank or in a comment. +let private endOfBlockComment (sourceText: SourceText) (start: int) = + let mutable depth = 1 + let mutable current = start + 2 + + while depth > 0 && current < sourceText.Length do + match charAt sourceText current, charAt sourceText (current + 1) with + | '(', '*' -> + depth <- depth + 1 + current <- current + 2 + | '*', ')' -> + depth <- depth - 1 + current <- current + 2 + | _ -> current <- current + 1 + + current + let rec private skipTrivia (sourceText: SourceText) (position: int) = - let at offset = - if position + offset < sourceText.Length then - sourceText[position + offset] - else - '\000' + let at offset = charAt sourceText (position + offset) if position >= sourceText.Length then position @@ -51,32 +64,10 @@ let rec private skipTrivia (sourceText: SourceText) (position: int) = let line = sourceText.Lines.GetLineFromPosition position skipTrivia sourceText line.EndIncludingLineBreak elif at 0 = '(' && at 1 = '*' && at 2 <> ')' then - let mutable depth = 1 - let mutable current = position + 2 - - while depth > 0 && current < sourceText.Length do - if - sourceText[current] = '(' - && current + 1 < sourceText.Length - && sourceText[current + 1] = '*' - then - depth <- depth + 1 - current <- current + 2 - elif - sourceText[current] = '*' - && current + 1 < sourceText.Length - && sourceText[current + 1] = ')' - then - depth <- depth - 1 - current <- current + 2 - else - current <- current + 1 - - skipTrivia sourceText current + skipTrivia sourceText (endOfBlockComment sourceText position) else position -/// Whether the character before the position ends an identifier, by the lexer's rule for identifier characters. let isIdentifierCharBefore (sourceText: SourceText) (position: int) = if position <= 0 then false @@ -107,135 +98,128 @@ let isIdentifierCharBefore (sourceText: SourceText) (position: int) = | UnicodeCategory.Format -> true | _ -> last = '\'' -/// Whether text inserted at the position would run into the name, closing bracket or type arguments before it: -/// `f(a, b)`, `f(a, b)`. let needsSpaceBefore (sourceText: SourceText) (position: int) = isIdentifierCharBefore sourceText position - || position > 0 - && match sourceText[position - 1] with - | '`' - | ')' - | ']' - | '}' - | '>' -> true - | _ -> false - -/// The position of the `(` that, with its `)`, encloses only the span and blanks. -let private tryEnclosingParen (sourceText: SourceText) (span: TextSpan) = - let mutable before = span.Start - 1 + || match charAt sourceText (position - 1) with + | '`' + | ')' + | ']' + | '}' + | '>' -> true + | _ -> false - while before >= 0 && Char.IsWhiteSpace sourceText[before] do - before <- before - 1 - - let mutable after = span.End - - while after < sourceText.Length && Char.IsWhiteSpace sourceText[after] do - after <- after + 1 - - if - before >= 0 - && after < sourceText.Length - && sourceText[before] = '(' - && sourceText[after] = ')' - then - ValueSome before - else - ValueNone - -/// `struct ` to insert in front of the `(` at the position, after a space when it would run into a name: `f(a, b)`. let private structAt (sourceText: SourceText) (position: int) = if needsSpaceBefore sourceText position then " struct " else "struct " -/// Whether the text between start and finish is a whole generic argument: `<` or `,` before it, `>` or `,` after. -let private isGenericArgument (sourceText: SourceText) (start: int) (finish: int) = - let mutable before = start - 1 +let private nonBlankAround (sourceText: SourceText) (span: TextSpan) = + let mutable before = span.Start - 1 while before >= 0 && Char.IsWhiteSpace sourceText[before] do before <- before - 1 - let mutable after = finish + let mutable after = span.End while after < sourceText.Length && Char.IsWhiteSpace sourceText[after] do after <- after + 1 - before >= 0 - && after < sourceText.Length - && (sourceText[before] = '<' || sourceText[before] = ',') - && (sourceText[after] = '>' || sourceText[after] = ',') + struct (before, after) + +let private tryEnclosingParen (sourceText: SourceText) (span: TextSpan) = + let struct (before, after) = nonBlankAround sourceText span + + if charAt sourceText before = '(' && charAt sourceText after = ')' then + ValueSome before + else + ValueNone + +let private isGenericArgument (sourceText: SourceText) (span: TextSpan) = + let struct (before, after) = nonBlankAround sourceText span + + (charAt sourceText before = '<' || charAt sourceText before = ',') + && (charAt sourceText after = '>' || charAt sourceText after = ',') + +let private insertStructParens (span: TextSpan) = + [ + TextChange(TextSpan(span.Start, 0), "struct (") + TextChange(TextSpan(span.End, 0), ")") + ] + +let private addStructChanges (sourceText: SourceText) (m: range) = + let span = spanOf sourceText m + + match tryEnclosingParen sourceText span with + | ValueSome openParen -> [ TextChange(TextSpan(openParen, 0), "struct ") ] + | ValueNone -> insertStructParens span + +let private dropStructChanges (sourceText: SourceText) (isWholeAnnotation: bool) (m: range) = + let span = spanOf sourceText m + let keyword = structKeyword sourceText m + let openParen = skipTrivia sourceText keyword.End + + let hasRedundantParens = + (isWholeAnnotation + || isGenericArgument sourceText (TextSpan.FromBounds(keyword.Start, span.End))) + && openParen < span.End + && sourceText[openParen] = '(' + + if hasRedundantParens then + [ + TextChange(keyword, "") + TextChange(TextSpan(openParen, 1), "") + TextChange(TextSpan(span.End - 1, 1), "") + ] + else + [ TextChange(keyword, "") ] -/// Changes giving a tuple type the target kind; a whole annotation also loses the parentheses `struct` needed. let typeChanges (sourceText: SourceText) (toStruct: bool) (isWholeAnnotation: bool) (tupleType: SynType) = match tupleType with | SynType.Tuple(isStruct = isStruct; range = m) when isStruct <> toStruct -> - let span = spanOf sourceText m - if toStruct then - match tryEnclosingParen sourceText span with - | ValueSome openParen -> [ TextChange(TextSpan(openParen, 0), "struct ") ] - | ValueNone -> - [ - TextChange(TextSpan(span.Start, 0), "struct (") - TextChange(TextSpan(span.End, 0), ")") - ] + addStructChanges sourceText m else - let keyword = structKeyword sourceText m - let openParen = skipTrivia sourceText keyword.End - - if - (isWholeAnnotation || isGenericArgument sourceText keyword.Start span.End) - && openParen < span.End - && sourceText[openParen] = '(' - then - [ - TextChange(keyword, "") - TextChange(TextSpan(openParen, 1), "") - TextChange(TextSpan(span.End - 1, 1), "") - ] - else - [ TextChange(keyword, "") ] + dropStructChanges sourceText isWholeAnnotation m | _ -> [] -/// Whether the applied expression names a method or constructor that takes one argument list, a union case of -/// several fields, or a union case whose only field is declared a tuple: its parenthesized argument is an argument -/// list, or a tuple of the kind the field declares. A name that does not resolve counts as one. +let rec tryCallee (expr: SynExpr) (applied: int) = + match expr with + | SynExpr.App(isInfix = false; funcExpr = funcExpr) -> tryCallee funcExpr (applied + 1) + | SynExpr.TypeApp(expr = inner) + | SynExpr.Paren(expr = inner) -> tryCallee inner applied + | SynExpr.Ident ident -> ValueSome(struct (ident, applied)) + | SynExpr.LongIdent(longDotId = SynLongIdent(id = ids)) + | SynExpr.DotGet(longDotId = SynLongIdent(id = ids)) -> + match List.tryLast ids with + | Some ident -> ValueSome(struct (ident, applied)) + | None -> ValueNone + | _ -> ValueNone + +let symbolUseAtIdent (sourceText: SourceText) (checkResults: FSharpCheckFileResults) (ident: Ident) = + let line = sourceText.Lines[Line.toZ ident.idRange.EndLine].ToString() + checkResults.GetSymbolUseAtLocation(ident.idRange.EndLine, ident.idRange.EndColumn, line, [ ident.idText ]) + +let private takesArgumentList (symbol: FSharpSymbol) = + match symbol with + | :? FSharpMemberOrFunctionOrValue as mfv -> + mfv.IsMember + && not mfv.IsProperty + && not mfv.IsEvent + && mfv.CurriedParameterGroups.Count <= 1 + | :? FSharpUnionCase as unionCase -> + unionCase.Fields.Count > 1 + || unionCase.Fields |> Seq.exists _.FieldType.IsTupleType + | :? FSharpEntity -> true + | _ -> false + let callsMethod (sourceText: SourceText) (checkResults: FSharpCheckFileResults) (funcExpr: SynExpr) = - let rec tryName (expr: SynExpr) = - match expr with - | SynExpr.Ident ident -> ValueSome ident - | SynExpr.LongIdent(longDotId = SynLongIdent(id = ids)) - | SynExpr.DotGet(longDotId = SynLongIdent(id = ids)) -> - match List.tryLast ids with - | Some ident -> ValueSome ident - | None -> ValueNone - | SynExpr.TypeApp(expr = inner) - | SynExpr.Paren(expr = inner) -> tryName inner - | _ -> ValueNone - - match tryName funcExpr with - | ValueNone -> false - | ValueSome ident -> - let line = sourceText.Lines[Line.toZ ident.idRange.EndLine].ToString() - - match checkResults.GetSymbolUseAtLocation(ident.idRange.EndLine, ident.idRange.EndColumn, line, [ ident.idText ]) with - | Some symbolUse -> - match symbolUse.Symbol with - | :? FSharpMemberOrFunctionOrValue as mfv -> - mfv.IsMember - && not mfv.IsProperty - && not mfv.IsEvent - && mfv.CurriedParameterGroups.Count <= 1 - | :? FSharpUnionCase as unionCase -> - unionCase.Fields.Count > 1 - || unionCase.Fields |> Seq.exists _.FieldType.IsTupleType - | :? FSharpEntity -> true - | _ -> false - | None -> true - -/// Whether the tuple is the argument list of a method, constructor or union case call rather than a tuple value, -/// however the call is spaced: `M(a, b)` and `M (a, b)` alike. + match tryCallee funcExpr 0 with + | ValueSome(struct (ident, 0)) -> + symbolUseAtIdent sourceText checkResults ident + |> Option.forall (fun symbolUse -> takesArgumentList symbolUse.Symbol) + | _ -> false + let isArgumentList (callsMethod: SynExpr -> bool) (tuple: SynExpr) (path: SyntaxVisitorPath) = match path with | SyntaxNode.SynExpr(SynExpr.Paren(expr = inner) as paren) :: SyntaxNode.SynExpr(SynExpr.New(expr = arg)) :: _ -> @@ -244,8 +228,6 @@ let isArgumentList (callsMethod: SynExpr -> bool) (tuple: SynExpr) (path: Syntax isInfix = false; funcExpr = funcExpr; argExpr = arg)) :: _ when isSame inner tuple && isSame arg paren -> callsMethod funcExpr | _ -> false -/// Whether the pattern is the parameter list of a member or constructor: its only argument, parenthesized or -/// (a struct tuple) not. let isParameterList (pat: SynPat) (path: SyntaxVisitorPath) = let struct (argument, headPath) = match path with @@ -257,51 +239,39 @@ let isParameterList (pat: SynPat) (path: SyntaxVisitorPath) = valData = SynValData(memberFlags = Some _))) :: _ -> isSame only argument | _ -> false -/// Changes giving a tuple expression the target kind; ValueNone when it is not a tuple or cannot change in place. -let tryExprChanges (sourceText: SourceText) (toStruct: bool) (tuple: SynExpr) (path: SyntaxVisitorPath) = - match tuple with - | SynExpr.Tuple(isStruct = isStruct) when isStruct = toStruct -> ValueSome [] - | SynExpr.Tuple(range = m) when not toStruct -> ValueSome [ TextChange(structKeyword sourceText m, "") ] - | SynExpr.Tuple(range = m) -> - match path with - | SyntaxNode.SynExpr(SynExpr.Paren(expr = inner; range = parenRange)) :: _ when isSame inner tuple -> +let private tupleChanges (sourceText: SourceText) (toStruct: bool) (isStruct: bool) (m: range) (enclosingParen: range voption) = + if isStruct = toStruct then + ValueSome [] + elif not toStruct then + ValueSome [ TextChange(structKeyword sourceText m, "") ] + else + match enclosingParen with + | ValueSome parenRange -> let start = (spanOf sourceText parenRange).Start ValueSome [ TextChange(TextSpan(start, 0), structAt sourceText start) ] - | _ when m.StartLine = m.EndLine -> - let span = spanOf sourceText m - - ValueSome - [ - TextChange(TextSpan(span.Start, 0), "struct (") - TextChange(TextSpan(span.End, 0), ")") - ] - | _ -> ValueNone + | ValueNone when m.StartLine = m.EndLine -> ValueSome(insertStructParens (spanOf sourceText m)) + | ValueNone -> ValueNone + +let tryExprChanges (sourceText: SourceText) (toStruct: bool) (tuple: SynExpr) (path: SyntaxVisitorPath) = + match tuple, path with + | SynExpr.Tuple(isStruct = isStruct; range = m), SyntaxNode.SynExpr(SynExpr.Paren(expr = inner; range = parenRange)) :: _ when + isSame inner tuple + -> + tupleChanges sourceText toStruct isStruct m (ValueSome parenRange) + | SynExpr.Tuple(isStruct = isStruct; range = m), _ -> tupleChanges sourceText toStruct isStruct m ValueNone | _ -> ValueNone -/// Changes giving a tuple pattern the target kind; ValueNone when it is not a tuple or cannot change in place. let tryPatChanges (sourceText: SourceText) (toStruct: bool) (tuple: SynPat) (path: SyntaxVisitorPath) = - match tuple with - | SynPat.Tuple(isStruct = isStruct) when isStruct = toStruct -> ValueSome [] - | SynPat.Tuple(range = m) when not toStruct -> ValueSome [ TextChange(structKeyword sourceText m, "") ] - | SynPat.Tuple(range = m) -> - match path with - | SyntaxNode.SynPat(SynPat.Paren(pat = inner; range = parenRange)) :: _ when isSame inner tuple -> - let start = (spanOf sourceText parenRange).Start - ValueSome [ TextChange(TextSpan(start, 0), structAt sourceText start) ] - | _ when m.StartLine = m.EndLine -> - let span = spanOf sourceText m - - ValueSome - [ - TextChange(TextSpan(span.Start, 0), "struct (") - TextChange(TextSpan(span.End, 0), ")") - ] - | _ -> ValueNone + match tuple, path with + | SynPat.Tuple(isStruct = isStruct; range = m), SyntaxNode.SynPat(SynPat.Paren(pat = inner; range = parenRange)) :: _ when + isSame inner tuple + -> + tupleChanges sourceText toStruct isStruct m (ValueSome parenRange) + | SynPat.Tuple(isStruct = isStruct; range = m), _ -> tupleChanges sourceText toStruct isStruct m ValueNone | _ -> ValueNone -/// The innermost tuple type within the type that contains the position. let rec tryTupleTypeAt (position: pos) (ty: SynType) = - if not (containsPos ty.Range position) then + if not (Range.rangeContainsPos ty.Range position) then ValueNone else let inner = @@ -325,7 +295,6 @@ let rec tryTupleTypeAt (position: pos) (ty: SynType) = | ValueNone, SynType.Tuple _ -> ValueSome ty | ValueNone, _ -> ValueNone -/// What a tuple type under the caret annotates. [] type Annotated = | Pattern of pat: SynPat * path: SyntaxVisitorPath @@ -346,9 +315,7 @@ let isStructNode (node: CaretNode) = | CaretNode.Type(tuple = SynType.Tuple(isStruct = isStruct)) -> isStruct | _ -> false -/// Whether the path shows a lambda parameter a second time. For a parameter that is not a plain name the parser puts -/// a match in the lambda's body, and the traversal walks that too; there the pattern has lost the parentheses and -/// the annotation around it. +// A lambda parameter that is not a plain name is matched again in the body, without its parentheses and annotation. let private isLambdaParameterAgain (pat: SynPat) (path: SyntaxVisitorPath) = let rec lambdaArgs (path: SyntaxVisitorPath) = match path with @@ -367,7 +334,6 @@ let private isLambdaParameterAgain (pat: SynPat) (path: SyntaxVisitorPath) = |> List.exists (fun arg -> Range.rangeContainsRange arg.Range pat.Range) | _ -> false -/// The innermost tuple expression, pattern or annotated tuple type under the caret. let tryCaretNode (callsMethod: SynExpr -> bool) (caret: pos) (parseTree: ParsedInput) = let annotationAt (annotation: SynType) (annotated: Annotated) = tryTupleTypeAt caret annotation @@ -376,33 +342,34 @@ let tryCaretNode (callsMethod: SynExpr -> bool) (caret: pos) (parseTree: ParsedI (ValueNone, parseTree) ||> ParsedInput.fold (fun found path node -> match node with - | SyntaxNode.SynExpr(SynExpr.Tuple(range = m) as tuple) when containsPos m caret && not (isArgumentList callsMethod tuple path) -> + | SyntaxNode.SynExpr(SynExpr.Tuple(range = m) as tuple) when + Range.rangeContainsPos m caret && not (isArgumentList callsMethod tuple path) + -> ValueSome(CaretNode.Expr(tuple, path)) - | SyntaxNode.SynPat pat when containsPos pat.Range caret && isLambdaParameterAgain pat path -> found - | SyntaxNode.SynPat(SynPat.Tuple(range = m) as tuple) when containsPos m caret && not (isParameterList tuple path) -> + | SyntaxNode.SynPat pat when Range.rangeContainsPos pat.Range caret && isLambdaParameterAgain pat path -> found + | SyntaxNode.SynPat(SynPat.Tuple(range = m) as tuple) when Range.rangeContainsPos m caret && not (isParameterList tuple path) -> ValueSome(CaretNode.Pat(tuple, path)) - | SyntaxNode.SynPat(SynPat.Typed(targetType = annotation) as pat) when containsPos annotation.Range caret -> + | SyntaxNode.SynPat(SynPat.Typed(targetType = annotation) as pat) when Range.rangeContainsPos annotation.Range caret -> match annotationAt annotation (Annotated.Pattern(pat, path)) with | ValueSome(CaretNode.Type(isWholeAnnotation = true)) when isParameterList pat path -> found | node -> node |> ValueOption.orElse found - | SyntaxNode.SynExpr(SynExpr.Typed(targetType = annotation) as expr) when containsPos annotation.Range caret -> + | SyntaxNode.SynExpr(SynExpr.Typed(targetType = annotation) as expr) when Range.rangeContainsPos annotation.Range caret -> annotationAt annotation (Annotated.Expression(expr, path)) |> ValueOption.orElse found | SyntaxNode.SynBinding(SynBinding(returnInfo = Some(SynBindingReturnInfo(typeName = annotation))) as binding) when - containsPos annotation.Range caret + Range.rangeContainsPos annotation.Range caret -> annotationAt annotation (Annotated.Return binding) |> ValueOption.orElse found | SyntaxNode.SynTypeDefn(SynTypeDefn( typeRepr = SynTypeDefnRepr.Simple(SynTypeDefnSimpleRepr.Record(recordFieldsAndSpreads = fields), _))) -> fields |> Seq.tryPickV (function - | SynFieldOrSpread.Field(SynField(fieldType = annotation) as field) when containsPos annotation.Range caret -> + | SynFieldOrSpread.Field(SynField(fieldType = annotation) as field) when Range.rangeContainsPos annotation.Range caret -> annotationAt annotation (Annotated.Field field) | _ -> ValueNone) |> ValueOption.orElse found | _ -> found) -/// Whether the tuple under the caret can change in place, which a tuple over several lines without parentheses cannot. let canChange (sourceText: SourceText) (node: CaretNode) = let toStruct = not (isStructNode node) diff --git a/vsintegration/src/FSharp.Editor/Refactor/TuplePropagation.fs b/vsintegration/src/FSharp.Editor/Refactor/TuplePropagation.fs index 322ddb905fe..1b4864f8b9d 100644 --- a/vsintegration/src/FSharp.Editor/Refactor/TuplePropagation.fs +++ b/vsintegration/src/FSharp.Editor/Refactor/TuplePropagation.fs @@ -25,22 +25,20 @@ type private Source = Check: FSharpCheckFileResults } -/// A place whose tuple type changes kind, and so passes the change on to what flows in and out of it. [] type private Slot = - /// A value, a parameter's value or a record field. - | Symbol of symbolUse: FSharpSymbolUse * source: Source - /// The result of a function or a method. + | Value of symbolUse: FSharpSymbolUse * source: Source | Result of functionUse: FSharpSymbolUse * source: Source - /// A parameter, by its curried argument and, when that argument is a tuple of parameters, its position in it. | Parameter of functionUse: FSharpSymbolUse * source: Source * group: int * index: int voption -let private containsRange (outer: range) (inner: range) = - Position.posGeq inner.Start outer.Start && Position.posGeq outer.End inner.End - let private symbolUseAt (source: Source) (ident: Ident) = - let line = source.Text.Lines[Line.toZ ident.idRange.EndLine].ToString() - source.Check.GetSymbolUseAtLocation(ident.idRange.EndLine, ident.idRange.EndColumn, line, [ ident.idText ]) + symbolUseAtIdent source.Text source.Check ident + +let private startsAt (position: pos) (ident: Ident) = + Position.posEq ident.idRange.Start position + +let private endsAt (position: pos) (ident: Ident) = + Position.posEq ident.idRange.End position let rec private tryPatternIdent (pat: SynPat) = match pat with @@ -56,7 +54,6 @@ let rec private stripParenPats (pat: SynPat) = | SynPat.Paren(pat = inner) -> stripParenPats inner | _ -> pat -/// `name = value`, the form of a named argument. [] let private (|NameEqualsValue|_|) (expr: SynExpr) = match expr with @@ -67,54 +64,42 @@ let private (|NameEqualsValue|_|) (expr: SynExpr) = argExpr = value) when String.Equals(operator.idText, "op_Equality", StringComparison.Ordinal) -> ValueSome(struct (name, value)) | _ -> ValueNone -/// The name of the function applied by the expression, in parentheses or not, and how many arguments are applied -/// before it. -let rec private tryCallee (expr: SynExpr) (applied: int) = - match expr with - | SynExpr.App(isInfix = false; funcExpr = funcExpr) -> tryCallee funcExpr (applied + 1) - | SynExpr.TypeApp(expr = inner) - | SynExpr.Paren(expr = inner) -> tryCallee inner applied - | SynExpr.Ident ident -> ValueSome(struct (ident, applied)) - | SynExpr.LongIdent(longDotId = SynLongIdent(id = ids)) - | SynExpr.DotGet(longDotId = SynLongIdent(id = ids)) -> +[] +let private (|FunctionHead|_|) (pat: SynPat) = + match pat with + | SynPat.LongIdent(longDotId = SynLongIdent(id = ids); argPats = SynArgPats.Pats(_ :: _)) -> match List.tryLast ids with - | Some ident -> ValueSome(struct (ident, applied)) + | Some name -> ValueSome name | None -> ValueNone | _ -> ValueNone -/// The function reference a binding's body is, with the arguments applied to it: `let alias = f` and -/// `let partial = f x` forward to `f`. -let rec private tryForwarded (body: SynExpr) = +let rec private tryForwardedFunction (body: SynExpr) = match body with - | SynExpr.Typed(expr = inner) -> tryForwarded inner + | SynExpr.Typed(expr = inner) -> tryForwardedFunction inner | _ -> tryCallee body 0 -/// The application of a function reference to all of its curried argument groups. -let rec private tryApplication (node: SynExpr) (path: SyntaxVisitorPath) (remaining: int) = +let rec private tryFullApplication (node: SynExpr) (path: SyntaxVisitorPath) (remaining: int) = if remaining = 0 then ValueSome(struct (node, path)) else match path with | SyntaxNode.SynExpr(SynExpr.TypeApp(expr = inner) | SynExpr.Paren(expr = inner) as wrapper) :: rest when isSame inner node -> - tryApplication wrapper rest remaining + tryFullApplication wrapper rest remaining | SyntaxNode.SynExpr(SynExpr.App(isInfix = false; funcExpr = funcExpr) as app) :: rest when isSame funcExpr node -> - tryApplication app rest (remaining - 1) + tryFullApplication app rest (remaining - 1) | _ -> ValueNone -/// The argument a function reference is applied to in the given curried group. -let rec private tryArgument (node: SynExpr) (path: SyntaxVisitorPath) (group: int) = +let rec private tryArgumentInGroup (node: SynExpr) (path: SyntaxVisitorPath) (group: int) = match path with | SyntaxNode.SynExpr(SynExpr.TypeApp(expr = inner) | SynExpr.Paren(expr = inner) as wrapper) :: rest when isSame inner node -> - tryArgument wrapper rest group + tryArgumentInGroup wrapper rest group | SyntaxNode.SynExpr(SynExpr.App(isInfix = false; funcExpr = funcExpr; argExpr = argument) as app) :: rest when isSame funcExpr node -> if group = 0 then ValueSome(struct (argument, SyntaxNode.SynExpr app :: rest)) else - tryArgument app rest (group - 1) + tryArgumentInGroup app rest (group - 1) | _ -> ValueNone -/// The name a function reference is bound to without being applied to all of its arguments, and how many it is -/// applied to: `let alias = f` and `let partial = f x`. let rec private tryForwardingBinding (node: SynExpr) (path: SyntaxVisitorPath) (applied: int) = match path with | SyntaxNode.SynExpr(SynExpr.TypeApp(expr = inner) | SynExpr.Paren(expr = inner) | SynExpr.Typed(expr = inner) as wrapper) :: rest when @@ -127,8 +112,6 @@ let rec private tryForwardingBinding (node: SynExpr) (path: SyntaxVisitorPath) ( tryPatternIdent headPat |> ValueOption.map (fun name -> struct (name, applied)) | _ -> ValueNone -/// The lambda an expression is, through parentheses and a type annotation: its parameter patterns, its body and the -/// path to them. let rec private tryLambda (expr: SynExpr) (path: SyntaxVisitorPath) = match expr with | SynExpr.Paren(expr = inner) @@ -136,7 +119,6 @@ let rec private tryLambda (expr: SynExpr) (path: SyntaxVisitorPath) = | SynExpr.Lambda(parsedData = Some(args, body)) -> ValueSome(struct (args, body, SyntaxNode.SynExpr expr :: path)) | _ -> ValueNone -/// The name a lambda is bound to, through parentheses and a type annotation: `let f = fun x -> x`. let rec private tryLambdaOwner (lambda: SynExpr) (path: SyntaxVisitorPath) = match path with | SyntaxNode.SynExpr(SynExpr.Paren(expr = inner) | SynExpr.Typed(expr = inner) as wrapper) :: rest when isSame inner lambda -> @@ -144,26 +126,20 @@ let rec private tryLambdaOwner (lambda: SynExpr) (path: SyntaxVisitorPath) = | SyntaxNode.SynBinding(SynBinding(headPat = headPat; expr = body)) :: _ when isSame body lambda -> tryPatternIdent headPat | _ -> ValueNone -/// The function and the position of the parameter a pattern in a binding's head, or among the parameters of the -/// lambda a name is bound to, declares. let rec private tryParameterPosition (pat: SynPat) (path: SyntaxVisitorPath) = + let containsPat (outer: SynPat) = + Range.rangeContainsRange outer.Range pat.Range + + let tupleElementIndex (arg: SynPat) = + match stripParenPats arg with + | SynPat.Tuple(elementPats = elements) -> elements |> Seq.tryFindIndexV containsPat + | _ -> ValueNone + let positionIn (args: SynPat list) (name: Ident) = args |> List.indexed - |> List.tryFindV (fun (_, arg) -> containsRange arg.Range pat.Range) - |> ValueOption.map (fun (group, arg) -> - let index = - match stripParenPats arg with - | SynPat.Tuple(elementPats = elements) -> - match - elements - |> List.tryFindIndex (fun element -> containsRange element.Range pat.Range) - with - | Some index -> ValueSome index - | None -> ValueNone - | _ -> ValueNone - - struct (name, group, index)) + |> List.tryFindV (fun (_, arg) -> containsPat arg) + |> ValueOption.map (fun (group, arg) -> struct (name, group, tupleElementIndex arg)) match path with | SyntaxNode.SynPat(SynPat.LongIdent(longDotId = SynLongIdent(id = ids); argPats = SynArgPats.Pats args)) :: SyntaxNode.SynBinding _ :: _ -> @@ -177,8 +153,6 @@ let rec private tryParameterPosition (pat: SynPat) (path: SyntaxVisitorPath) = | _ :: rest -> tryParameterPosition pat rest | [] -> ValueNone -/// The expression a tuple pattern takes apart, through parentheses and a type annotation: the right-hand side of its -/// binding or the matched expression. let rec private tryMatchedExpression (pat: SynPat) (path: SyntaxVisitorPath) = match path with | SyntaxNode.SynPat(SynPat.Paren _ | SynPat.Typed _ as wrapper) :: rest -> tryMatchedExpression wrapper rest @@ -189,7 +163,6 @@ let rec private tryMatchedExpression (pat: SynPat) (path: SyntaxVisitorPath) = ValueSome(struct (scrutinee, SyntaxNode.SynExpr matchExpr :: rest)) | _ -> ValueNone -/// The type annotations on a pattern, through the parentheses around it: `((a, b): int * int)`. let rec private annotationsOn (pat: SynPat) (path: SyntaxVisitorPath) = match path with | SyntaxNode.SynPat(SynPat.Paren(pat = inner) as paren) :: rest when isSame inner pat -> annotationsOn paren rest @@ -197,8 +170,6 @@ let rec private annotationsOn (pat: SynPat) (path: SyntaxVisitorPath) = annotation :: annotationsOn typed rest | _ -> [] -/// The function and the curried group of which the pattern is the whole argument, through parentheses and a type -/// annotation or (a struct tuple) with neither. The function can be a name bound to a lambda. let private tryWholeArgument (pat: SynPat) (path: SyntaxVisitorPath) = let rec outermost (pat: SynPat) (path: SyntaxVisitorPath) = match path with @@ -219,55 +190,47 @@ let private tryWholeArgument (pat: SynPat) (path: SyntaxVisitorPath) = | _ -> ValueNone | _ -> ValueNone -/// The expression node a symbol use stands for: an identifier, or the last part of a dotted name. let private tryUseNode (tree: ParsedInput) (useRange: range) = let isUse (ident: Ident) = - Position.posEq ident.idRange.Start useRange.Start - && Position.posEq ident.idRange.End useRange.End + startsAt useRange.Start ident && endsAt useRange.End ident + + let endsWithUse (ids: Ident list) = + List.tryLast ids |> Option.exists (endsAt useRange.End) (useRange.Start, tree) ||> ParsedInput.tryPickLast (fun path node -> match node with | SyntaxNode.SynExpr(SynExpr.Ident ident as expr) when isUse ident -> Some(expr, path) | SyntaxNode.SynExpr(SynExpr.LongIdent(longDotId = SynLongIdent(id = ids)) as expr) - | SyntaxNode.SynExpr(SynExpr.DotGet(longDotId = SynLongIdent(id = ids)) as expr) when - // A dotted use can cover the whole name, `r.Field`, not only its last part. - List.tryLast ids - |> Option.exists (fun ident -> Position.posEq ident.idRange.End useRange.End) - -> - Some(expr, path) + | SyntaxNode.SynExpr(SynExpr.DotGet(longDotId = SynLongIdent(id = ids)) as expr) when endsWithUse ids -> Some(expr, path) | _ -> None) -/// The value given to a record field whose name is at the use, in a record construction or copy-and-update. let private tryRecordFieldValue (tree: ParsedInput) (useRange: range) = + let tryFieldValue (path: SyntaxVisitorPath) (record: SynExpr) (fields: SynExprRecordFieldOrSpread list) = + fields + |> List.tryPick (function + | SynExprRecordFieldOrSpread.Field(field = SynExprRecordField(fieldName = (SynLongIdent(id = ids), _); expr = Some value)) when + List.tryLast ids |> Option.exists (startsAt useRange.Start) + -> + Some(value, SyntaxNode.SynExpr record :: path) + | _ -> None) + (useRange.Start, tree) ||> ParsedInput.tryPickLast (fun path node -> match node with - | SyntaxNode.SynExpr(SynExpr.Record(recordFields = fields) as record) -> - fields - |> List.tryPick (function - | SynExprRecordFieldOrSpread.Field(field = SynExprRecordField(fieldName = (SynLongIdent(id = ids), _); expr = Some value)) when - List.tryLast ids - |> Option.exists (fun ident -> Position.posEq ident.idRange.Start useRange.Start) - -> - Some(value, SyntaxNode.SynExpr record :: path) - | _ -> None) + | SyntaxNode.SynExpr(SynExpr.Record(recordFields = fields) as record) -> tryFieldValue path record fields | _ -> None) -/// The body of the binding that gives the name declared at the range its value, `let name = body`, and the path to it. let private tryNamedBinding (tree: ParsedInput) (declaration: range) = (ValueNone, tree) ||> ParsedInput.fold (fun found path node -> match found, node with | ValueNone, SyntaxNode.SynBinding(SynBinding(headPat = headPat; expr = body)) when - tryPatternIdent headPat - |> ValueOption.exists (fun ident -> Position.posEq ident.idRange.Start declaration.Start) + tryPatternIdent headPat |> ValueOption.exists (startsAt declaration.Start) -> ValueSome(struct (body, node :: path)) | _ -> found) -/// The pattern declaring a parameter of the function declared at the range, a function or a name bound to a lambda: -/// its whole curried argument, or one element of an argument that is a tuple of parameters. let private tryParameterPattern (tree: ParsedInput) (declaration: range) (group: int) (index: int voption) = let pathTo (pat: SynPat) (parentPath: SyntaxVisitorPath) = match pat with @@ -294,8 +257,7 @@ let private tryParameterPattern (tree: ParsedInput) (declaration: range) (group: | ValueNone, SyntaxNode.SynBinding(SynBinding( headPat = SynPat.LongIdent(longDotId = SynLongIdent(id = ids); argPats = SynArgPats.Pats args) as headPat)) when - List.tryLast ids - |> Option.exists (fun ident -> Position.posEq ident.idRange.Start declaration.Start) + List.tryLast ids |> Option.exists (startsAt declaration.Start) -> parameterIn args (SyntaxNode.SynPat headPat :: node :: path) | _ -> found) @@ -305,16 +267,12 @@ let private tryParameterPattern (tree: ParsedInput) (declaration: range) (group: |> ValueOption.bind (fun struct (args, _, argsPath) -> parameterIn args argsPath)) let private annotationChanges (sourceText: SourceText) (toStruct: bool) (annotation: SynType) = - match stripParenTypes annotation with - | SynType.Tuple _ as tuple -> typeChanges sourceText toStruct true tuple - | _ -> [] + typeChanges sourceText toStruct true (stripParenTypes annotation) let private hasName (name: string) (parameter: FSharpParameter) = - match parameter.Name with - | Some parameterName -> String.Equals(parameterName, name, StringComparison.Ordinal) - | None -> false + parameter.Name + |> Option.exists (fun parameterName -> String.Equals(parameterName, name, StringComparison.Ordinal)) -/// The name an argument can give for the parameter of a method at the position. let private tryParameterName (symbol: FSharpSymbol) (group: int) (index: int voption) = match symbol with | :? FSharpMemberOrFunctionOrValue as mfv when mfv.IsMember && group < mfv.CurriedParameterGroups.Count -> @@ -326,8 +284,6 @@ let private tryParameterName (symbol: FSharpSymbol) (group: int) (index: int vop | _ -> None | _ -> None -/// The value an argument gives a parameter: the part of an argument list given for it by name, else the one at its -/// position, or the whole argument when the parameter is not one of a tuple of parameters. let private tryArgumentValue (parameterName: string option) (index: int voption) (argument: SynExpr) (argumentPath: SyntaxVisitorPath) = let struct (elements, elementsPath) = match argument with @@ -354,7 +310,6 @@ let private tryArgumentValue (parameterName: string option) (index: int voption) | ValueNone, ValueSome _, _ -> ValueNone | ValueNone, ValueNone, _ -> ValueSome(struct (argument, argumentPath)) -/// How many curried arguments a function takes: its parameter groups or, for a function value, the arrows of its type. let private groupCount (mfv: FSharpMemberOrFunctionOrValue) = let rec arrows (ty: FSharpType) = if ty.IsFunctionType then @@ -369,6 +324,20 @@ let private groupCount (mfv: FSharpMemberOrFunctionOrValue) = | Some ty -> max 1 (arrows ty) | None -> 1 +let private isValueSymbol (symbol: FSharpSymbol) = + match symbol with + | :? FSharpField -> true + | :? FSharpMemberOrFunctionOrValue as mfv -> not mfv.IsFunction && not mfv.IsMember + | _ -> false + +let private tryPartiallyAppliedFunction (source: Source) (body: SynExpr) = + let isPartiallyApplied struct (callee: Ident, applied: int) = + match symbolUseAt source callee |> Option.map _.Symbol with + | Some(:? FSharpMemberOrFunctionOrValue as mfv) -> (mfv.IsFunction || mfv.IsMember) && applied < groupCount mfv + | _ -> false + + tryForwardedFunction body |> ValueOption.filter isPartiallyApplied + type private Engine(solution: Solution, toStruct: bool, userOpName: string) = let sources = Dictionary() let changes = Dictionary>() @@ -391,6 +360,14 @@ type private Engine(solution: Solution, toStruct: bool, userOpName: string) = symbol.DeclarationLocation |> Option.map (fun m -> $"{kind}|{m.FileName}|{m.StartLine}|{m.StartColumn}") + let tryFunctionUse (source: Source) (name: Ident) = + match symbolUseAt source name with + | Some functionUse when (tryDeclarationDocument functionUse.Symbol).IsSome -> + match functionUse.Symbol with + | :? FSharpMemberOrFunctionOrValue as mfv when mfv.IsFunction || mfv.IsMember -> ValueSome functionUse + | _ -> ValueNone + | _ -> ValueNone + member _.Load(document: Document) = cancellableTask { match sources.TryGetValue document.Id with @@ -436,103 +413,72 @@ type private Engine(solution: Solution, toStruct: bool, userOpName: string) = | ValueSome newChanges -> this.Add source newChanges | ValueNone -> failed <- true + member this.AddAnnotation (source: Source) (annotation: SynType) = + this.Add source (annotationChanges source.Text toStruct annotation) + member _.Enqueue (key: string option) (slot: Slot) = match key with | Some key when visited.Add key -> pending.Enqueue slot | _ -> () - member this.EnqueueSymbol (source: Source) (ident: Ident) = + member this.EnqueueValue (source: Source) (ident: Ident) = match symbolUseAt source ident with - | Some symbolUse when (tryDeclarationDocument symbolUse.Symbol).IsSome -> - let isValue = - match symbolUse.Symbol with - | :? FSharpField -> true - | :? FSharpMemberOrFunctionOrValue as mfv -> not mfv.IsFunction && not mfv.IsMember - | _ -> false - - if isValue then - this.Enqueue (keyOf "S" symbolUse.Symbol) (Slot.Symbol(symbolUse, source)) + | Some symbolUse when + (tryDeclarationDocument symbolUse.Symbol).IsSome + && isValueSymbol symbolUse.Symbol + -> + this.Enqueue (keyOf "S" symbolUse.Symbol) (Slot.Value(symbolUse, source)) | _ -> () member this.EnqueueResult (source: Source) (name: Ident) = - match symbolUseAt source name with - | Some functionUse when (tryDeclarationDocument functionUse.Symbol).IsSome -> - match functionUse.Symbol with - | :? FSharpMemberOrFunctionOrValue as mfv when mfv.IsFunction || mfv.IsMember -> - this.Enqueue (keyOf "R" functionUse.Symbol) (Slot.Result(functionUse, source)) - | _ -> () - | _ -> () + match tryFunctionUse source name with + | ValueSome functionUse -> this.Enqueue (keyOf "R" functionUse.Symbol) (Slot.Result(functionUse, source)) + | ValueNone -> () member this.EnqueueParameter (source: Source) (functionName: Ident) (group: int) (index: int voption) = - match symbolUseAt source functionName with - | Some functionUse when (tryDeclarationDocument functionUse.Symbol).IsSome -> - match functionUse.Symbol with - | :? FSharpMemberOrFunctionOrValue as mfv when mfv.IsFunction || mfv.IsMember -> - let position = - match index with - | ValueSome index -> $"{group}|{index}" - | ValueNone -> $"{group}" - - this.Enqueue - (keyOf "P" functionUse.Symbol |> Option.map (fun key -> $"{key}|{position}")) - (Slot.Parameter(functionUse, source, group, index)) - | _ -> () - | _ -> () + match tryFunctionUse source functionName with + | ValueSome functionUse -> + let position = + match index with + | ValueSome index -> $"{group}|{index}" + | ValueNone -> $"{group}" + + this.Enqueue + (keyOf "P" functionUse.Symbol |> Option.map (fun key -> $"{key}|{position}")) + (Slot.Parameter(functionUse, source, group, index)) + | ValueNone -> () - /// Enqueues the parameter of a method that an argument names: `M(name = value)`. member this.EnqueueNamedParameter (source: Source) (methodName: Ident) (group: int) (parameterName: Ident) = - match symbolUseAt source methodName with - | Some methodUse -> - match methodUse.Symbol with - | :? FSharpMemberOrFunctionOrValue as mfv when mfv.IsMember && group < mfv.CurriedParameterGroups.Count -> - let parameters = mfv.CurriedParameterGroups[group] - - match parameters |> Seq.tryFindIndexV (hasName parameterName.idText) with - | ValueSome _ when parameters.Count = 1 -> this.EnqueueParameter source methodName group ValueNone - | ValueSome index -> this.EnqueueParameter source methodName group (ValueSome index) - | ValueNone -> () - | _ -> () - | None -> () + match symbolUseAt source methodName |> Option.map _.Symbol with + | Some(:? FSharpMemberOrFunctionOrValue as mfv) when mfv.IsMember && group < mfv.CurriedParameterGroups.Count -> + let parameters = mfv.CurriedParameterGroups[group] - /// The function a binding's body forwards to, with the arguments the body applies to it: a function reference - /// applied to fewer arguments than the function takes. - member _.TryForwarded (source: Source) (body: SynExpr) = - match tryForwarded body with - | ValueSome(struct (callee, applied)) -> - match symbolUseAt source callee with - | Some calleeUse -> - match calleeUse.Symbol with - | :? FSharpMemberOrFunctionOrValue as mfv when (mfv.IsFunction || mfv.IsMember) && applied < groupCount mfv -> - ValueSome(struct (callee, applied)) - | _ -> ValueNone - | None -> ValueNone - | ValueNone -> ValueNone + match parameters |> Seq.tryFindIndexV (hasName parameterName.idText) with + | ValueSome _ when parameters.Count = 1 -> this.EnqueueParameter source methodName group ValueNone + | ValueSome index -> this.EnqueueParameter source methodName group (ValueSome index) + | ValueNone -> () + | _ -> () - /// A value of the changing kind flows into a pattern. member this.IntoPattern (source: Source) (pat: SynPat) (path: SyntaxVisitorPath) = match pat with | SynPat.Paren(pat = inner) -> this.IntoPattern source inner (SyntaxNode.SynPat pat :: path) | SynPat.Typed(pat = inner; targetType = annotation) -> - this.Add source (annotationChanges source.Text toStruct annotation) + this.AddAnnotation source annotation this.IntoPattern source inner (SyntaxNode.SynPat pat :: path) | SynPat.Named(ident = SynIdent(ident, _)) - | SynPat.LongIdent(longDotId = SynLongIdent(id = [ ident ]); argPats = SynArgPats.Pats []) -> this.EnqueueSymbol source ident + | SynPat.LongIdent(longDotId = SynLongIdent(id = [ ident ]); argPats = SynArgPats.Pats []) -> this.EnqueueValue source ident | SynPat.Tuple _ when not (isParameterList pat path) -> this.AddOrFail source (tryPatChanges source.Text toStruct pat path) | _ -> () - /// The value of the node now has the changing kind: pass that on to where it goes. member this.FlowOut (source: Source) (node: SynExpr) (path: SyntaxVisitorPath) = match path with | SyntaxNode.SynExpr(SynExpr.Paren(expr = inner) as paren) :: rest when isSame inner node -> this.FlowOut source paren rest | SyntaxNode.SynExpr(SynExpr.Typed(expr = inner; targetType = annotation) as typed) :: rest when isSame inner node -> - this.Add source (annotationChanges source.Text toStruct annotation) + this.AddAnnotation source annotation this.FlowOut source typed rest | SyntaxNode.SynBinding(SynBinding(headPat = headPat; expr = body)) :: _ when isSame body node -> match headPat with - | SynPat.LongIdent(longDotId = SynLongIdent(id = ids); argPats = SynArgPats.Pats(_ :: _)) -> - match List.tryLast ids with - | Some name -> this.EnqueueResult source name - | None -> () + | FunctionHead name -> this.EnqueueResult source name | _ -> this.IntoPattern source headPat path | SyntaxNode.SynExpr(SynExpr.Sequential(expr2 = last) as container) :: rest when isSame last node -> this.FlowOut source container rest @@ -541,167 +487,165 @@ type private Engine(solution: Solution, toStruct: bool, userOpName: string) = | SyntaxNode.SynExpr(SynExpr.IfThenElse(thenExpr = thenExpr; elseExpr = Some elseExpr) as container) :: rest when isSame thenExpr node || isSame elseExpr node -> - this.Retarget source container rest - this.FlowOut source container rest + this.FlowOutOfBranch source container rest | SyntaxNode.SynExpr(SynExpr.TryFinally(tryExpr = body) as container) :: rest when isSame body node -> this.FlowOut source container rest | SyntaxNode.SynExpr(SynExpr.TryWith(tryExpr = body) as container) :: rest when isSame body node -> - this.Retarget source container rest - this.FlowOut source container rest + this.FlowOutOfBranch source container rest | SyntaxNode.SynMatchClause(SynMatchClause(resultExpr = result)) :: SyntaxNode.SynExpr(SynExpr.Match _ | SynExpr.TryWith _ as container) :: rest when isSame result node -> - this.Retarget source container rest - this.FlowOut source container rest + this.FlowOutOfBranch source container rest | SyntaxNode.SynExpr(SynExpr.Lambda(parsedData = Some(_, body)) as lambda) :: rest when isSame body node -> - match tryLambdaOwner lambda rest with - | ValueSome name -> this.EnqueueResult source name - | ValueNone -> () + tryLambdaOwner lambda rest |> ValueOption.iter (this.EnqueueResult source) | SyntaxNode.SynExpr(NameEqualsValue(struct (parameterName, value))) :: rest when isSame value node -> - match rest with - | SyntaxNode.SynExpr(SynExpr.Tuple _) :: SyntaxNode.SynExpr(SynExpr.Paren _ as paren) :: SyntaxNode.SynExpr(SynExpr.App( - isInfix = false; funcExpr = funcExpr; argExpr = argument)) :: _ - | SyntaxNode.SynExpr(SynExpr.Paren _ as paren) :: SyntaxNode.SynExpr(SynExpr.App( - isInfix = false; funcExpr = funcExpr; argExpr = argument)) :: _ when isSame argument paren -> - match tryCallee funcExpr 0 with - | ValueSome(struct (methodName, group)) -> this.EnqueueNamedParameter source methodName group parameterName - | ValueNone -> () - | _ -> () + this.FlowOutOfNamedArgument source parameterName rest | SyntaxNode.SynExpr(SynExpr.App(isInfix = false; funcExpr = funcExpr; argExpr = argument)) :: _ when isSame argument node -> - match tryCallee funcExpr 0 with - | ValueSome(struct (name, group)) -> this.EnqueueParameter source name group ValueNone - | ValueNone -> () + tryCallee funcExpr 0 + |> ValueOption.iter (fun struct (name, group) -> this.EnqueueParameter source name group ValueNone) | SyntaxNode.SynExpr(SynExpr.Tuple(exprs = exprs)) :: SyntaxNode.SynExpr(SynExpr.Paren _ as paren) :: SyntaxNode.SynExpr(SynExpr.App( isInfix = false; funcExpr = funcExpr; argExpr = argument)) :: _ when isSame argument paren -> match tryCallee funcExpr 0, List.tryFindIndex (isSame node) exprs with | ValueSome(struct (name, group)), Some index -> this.EnqueueParameter source name group (ValueSome index) | _ -> () - | SyntaxNode.SynExpr(SynExpr.Record(recordFields = fields)) :: _ -> - for field in fields do - match field with - | SynExprRecordFieldOrSpread.Field(field = SynExprRecordField(fieldName = (SynLongIdent(id = ids), _); expr = Some value)) when - isSame value node - -> - match List.tryLast ids with - | Some name -> this.EnqueueSymbol source name - | None -> () - | _ -> () + | SyntaxNode.SynExpr(SynExpr.Record(recordFields = fields)) :: _ -> this.FlowOutOfRecordField source node fields | SyntaxNode.SynExpr(SynExpr.Match(expr = scrutinee; clauses = clauses) as matchExpr) :: rest when isSame scrutinee node -> for SynMatchClause(pat = pat) as clause in clauses do this.IntoPattern source pat (SyntaxNode.SynMatchClause clause :: SyntaxNode.SynExpr matchExpr :: rest) | _ -> () - /// The expression must now produce the changing kind: change what it is built from. + member this.FlowOutOfBranch (source: Source) (container: SynExpr) (path: SyntaxVisitorPath) = + this.Retarget source container path + this.FlowOut source container path + + member this.FlowOutOfNamedArgument (source: Source) (parameterName: Ident) (path: SyntaxVisitorPath) = + match path with + | SyntaxNode.SynExpr(SynExpr.Tuple _) :: SyntaxNode.SynExpr(SynExpr.Paren _ as paren) :: SyntaxNode.SynExpr(SynExpr.App( + isInfix = false; funcExpr = funcExpr; argExpr = argument)) :: _ + | SyntaxNode.SynExpr(SynExpr.Paren _ as paren) :: SyntaxNode.SynExpr(SynExpr.App( + isInfix = false; funcExpr = funcExpr; argExpr = argument)) :: _ when isSame argument paren -> + tryCallee funcExpr 0 + |> ValueOption.iter (fun struct (methodName, group) -> this.EnqueueNamedParameter source methodName group parameterName) + | _ -> () + + member this.FlowOutOfRecordField (source: Source) (node: SynExpr) (fields: SynExprRecordFieldOrSpread list) = + for field in fields do + match field with + | SynExprRecordFieldOrSpread.Field(field = SynExprRecordField(fieldName = (SynLongIdent(id = ids), _); expr = Some value)) when + isSame value node + -> + List.tryLast ids |> Option.iter (this.EnqueueValue source) + | _ -> () + member this.Retarget (source: Source) (expr: SynExpr) (path: SyntaxVisitorPath) = let childPath = SyntaxNode.SynExpr expr :: path match expr with | SynExpr.Paren(expr = inner) -> this.Retarget source inner childPath | SynExpr.Typed(expr = inner; targetType = annotation) -> - this.Add source (annotationChanges source.Text toStruct annotation) + this.AddAnnotation source annotation this.Retarget source inner childPath | SynExpr.Tuple _ when not (isArgumentList (callsMethod source.Text source.Check) expr path) -> this.AddOrFail source (tryExprChanges source.Text toStruct expr path) - | SynExpr.Ident ident -> this.EnqueueSymbol source ident + | SynExpr.Ident ident -> this.EnqueueValue source ident | SynExpr.LongIdent(longDotId = SynLongIdent(id = ids)) - | SynExpr.DotGet(longDotId = SynLongIdent(id = ids)) -> - match List.tryLast ids with - | Some ident -> this.EnqueueSymbol source ident - | None -> () + | SynExpr.DotGet(longDotId = SynLongIdent(id = ids)) -> List.tryLast ids |> Option.iter (this.EnqueueValue source) | SynExpr.App(isInfix = false) -> - match tryCallee expr 0 with - | ValueSome(struct (name, _)) -> this.EnqueueResult source name - | ValueNone -> () + tryCallee expr 0 + |> ValueOption.iter (fun struct (name, _) -> this.EnqueueResult source name) | SynExpr.IfThenElse(thenExpr = thenExpr; elseExpr = Some elseExpr) -> this.Retarget source thenExpr childPath this.Retarget source elseExpr childPath - | SynExpr.Match(clauses = clauses) -> - for SynMatchClause(resultExpr = result) as clause in clauses do - this.Retarget source result (SyntaxNode.SynMatchClause clause :: childPath) + | SynExpr.Match(clauses = clauses) -> this.RetargetResults source clauses childPath | SynExpr.TryFinally(tryExpr = body) -> this.Retarget source body childPath | SynExpr.TryWith(tryExpr = body; withCases = handlers) -> this.Retarget source body childPath - - for SynMatchClause(resultExpr = result) as handler in handlers do - this.Retarget source result (SyntaxNode.SynMatchClause handler :: childPath) + this.RetargetResults source handlers childPath | SynExpr.Sequential(expr2 = last) -> this.Retarget source last childPath | SynExpr.LetOrUse letOrUse -> this.Retarget source letOrUse.Body childPath | _ -> () - /// Changes the declaration of a value, a parameter or a record field. + member this.RetargetValue (source: Source) (struct (value, path): struct (SynExpr * SyntaxVisitorPath)) = + this.Retarget source value path + + member this.RetargetResults (source: Source) (clauses: SynMatchClause list) (path: SyntaxVisitorPath) = + for SynMatchClause(resultExpr = result) as clause in clauses do + this.Retarget source result (SyntaxNode.SynMatchClause clause :: path) + member this.Define (source: Source) (declaration: range) = - let isDeclared (ident: Ident) = - Position.posEq ident.idRange.Start declaration.Start + let isDeclared = startsAt declaration.Start ((), source.Tree) - ||> ParsedInput.fold (fun () path node -> - match node with - | SyntaxNode.SynBinding(SynBinding(headPat = headPat; expr = body)) when - tryPatternIdent headPat |> ValueOption.exists isDeclared - -> - this.Retarget source body (node :: path) - | SyntaxNode.SynExpr(SynExpr.Match(expr = scrutinee; clauses = clauses)) when - clauses - |> List.exists (fun (SynMatchClause(pat = pat)) -> tryPatternIdent pat |> ValueOption.exists isDeclared) - -> - this.Retarget source scrutinee (node :: path) - | SyntaxNode.SynPat(SynPat.Typed(pat = inner; targetType = annotation)) when - tryPatternIdent inner |> ValueOption.exists isDeclared - -> - this.Add source (annotationChanges source.Text toStruct annotation) - | SyntaxNode.SynTypeDefn(SynTypeDefn( - typeRepr = SynTypeDefnRepr.Simple(SynTypeDefnSimpleRepr.Record(recordFieldsAndSpreads = fields), _))) -> - for field in fields do - match field with - | SynFieldOrSpread.Field(SynField(idOpt = Some ident; fieldType = annotation)) when isDeclared ident -> - this.Add source (annotationChanges source.Text toStruct annotation) - | _ -> () - | _ -> ()) + ||> ParsedInput.fold (fun () path node -> this.DefineAt source isDeclared path node) + + member this.DefineAt (source: Source) (isDeclared: Ident -> bool) (path: SyntaxVisitorPath) (node: SyntaxNode) = + match node with + | SyntaxNode.SynBinding(SynBinding(headPat = headPat; expr = body)) when tryPatternIdent headPat |> ValueOption.exists isDeclared -> + this.Retarget source body (node :: path) + | SyntaxNode.SynExpr(SynExpr.Match(expr = scrutinee; clauses = clauses)) when + clauses + |> List.exists (fun (SynMatchClause(pat = pat)) -> tryPatternIdent pat |> ValueOption.exists isDeclared) + -> + this.Retarget source scrutinee (node :: path) + | SyntaxNode.SynPat(SynPat.Typed(pat = inner; targetType = annotation)) when tryPatternIdent inner |> ValueOption.exists isDeclared -> + this.AddAnnotation source annotation + | SyntaxNode.SynTypeDefn(SynTypeDefn( + typeRepr = SynTypeDefnRepr.Simple(SynTypeDefnSimpleRepr.Record(recordFieldsAndSpreads = fields), _))) -> + for field in fields do + match field with + | SynFieldOrSpread.Field(SynField(idOpt = Some ident; fieldType = annotation)) when isDeclared ident -> + this.AddAnnotation source annotation + | _ -> () + | _ -> () - /// Changes the declared or inferred result of a function, of a name bound to a lambda, or of the function a name - /// forwards to. member this.DefineResult (source: Source) (declaration: range) = ((), source.Tree) ||> ParsedInput.fold (fun () path node -> match node with | SyntaxNode.SynBinding(SynBinding(headPat = SynPat.LongIdent(longDotId = SynLongIdent(id = ids)); expr = body)) when - List.tryLast ids - |> Option.exists (fun ident -> Position.posEq ident.idRange.Start declaration.Start) + List.tryLast ids |> Option.exists (startsAt declaration.Start) -> this.Retarget source body (node :: path) | _ -> ()) match tryNamedBinding source.Tree declaration with - | ValueSome(struct (body, bodyPath)) -> - match tryLambda body bodyPath with - | ValueSome(struct (_, result, resultPath)) -> this.Retarget source result resultPath - | ValueNone -> - match this.TryForwarded source body with - | ValueSome(struct (callee, _)) -> this.EnqueueResult source callee - | ValueNone -> () + | ValueSome(struct (body, bodyPath)) -> this.DefineNamedResult source body bodyPath | ValueNone -> () - member this.ProcessSymbol (symbolUse: FSharpSymbolUse) (source: Source) = + member this.DefineNamedResult (source: Source) (body: SynExpr) (bodyPath: SyntaxVisitorPath) = + match tryLambda body bodyPath with + | ValueSome(struct (_, result, resultPath)) -> this.Retarget source result resultPath + | ValueNone -> + tryPartiallyAppliedFunction source body + |> ValueOption.iter (fun struct (callee, _) -> this.EnqueueResult source callee) + + member this.ForEachUse (symbolUse: FSharpSymbolUse) (source: Source) (declaration: range) (visit: Source -> range -> unit) = + cancellableTask { + let! uses = SymbolHelpers.getSymbolUses symbolUse source.Document source.Check + + for useDocument, useRange in uses do + if not (isDeclaration useRange declaration) then + let! useSource = this.Load useDocument + visit useSource useRange + } + + member this.ProcessValue (symbolUse: FSharpSymbolUse) (source: Source) = cancellableTask { match tryDeclarationDocument symbolUse.Symbol with | ValueSome(struct (declaration, document)) -> let! definition = this.Load document this.Define definition declaration - let! uses = SymbolHelpers.getSymbolUses symbolUse source.Document source.Check - - for useDocument, useRange in uses do - if not (isDeclaration useRange declaration) then - let! useSource = this.Load useDocument - - match tryRecordFieldValue useSource.Tree useRange with - | Some(value, path) -> this.Retarget useSource value path - | None -> - match tryUseNode useSource.Tree useRange with - | Some(node, path) -> this.FlowOut useSource node path - | None -> () + do! this.ForEachUse symbolUse source declaration this.FlowOutOfValueUse | ValueNone -> () } + member this.FlowOutOfValueUse (useSource: Source) (useRange: range) = + match tryRecordFieldValue useSource.Tree useRange with + | Some(value, path) -> this.Retarget useSource value path + | None -> + tryUseNode useSource.Tree useRange + |> Option.iter (fun (node, path) -> this.FlowOut useSource node path) + member this.ProcessResult (functionUse: FSharpSymbolUse) (source: Source) = cancellableTask { match tryDeclarationDocument functionUse.Symbol, functionUse.Symbol with @@ -709,78 +653,76 @@ type private Engine(solution: Solution, toStruct: bool, userOpName: string) = let! definition = this.Load document this.DefineResult definition declaration let groups = groupCount mfv - let! uses = SymbolHelpers.getSymbolUses functionUse source.Document source.Check - - for useDocument, useRange in uses do - if not (isDeclaration useRange declaration) then - let! useSource = this.Load useDocument - - match tryUseNode useSource.Tree useRange with - | Some(node, path) -> - match tryApplication node path groups with - | ValueSome(struct (application, rest)) -> this.FlowOut useSource application rest - | ValueNone -> - match tryForwardingBinding node path 0 with - | ValueSome(struct (name, applied)) when applied < groups -> this.EnqueueResult useSource name - | _ -> () - | None -> () + do! this.ForEachUse functionUse source declaration (this.FlowOutOfResultUse groups) | _ -> () } + member this.FlowOutOfResultUse (groups: int) (useSource: Source) (useRange: range) = + match tryUseNode useSource.Tree useRange with + | Some(node, path) -> + match tryFullApplication node path groups with + | ValueSome(struct (application, rest)) -> this.FlowOut useSource application rest + | ValueNone -> + match tryForwardingBinding node path 0 with + | ValueSome(struct (name, applied)) when applied < groups -> this.EnqueueResult useSource name + | _ -> () + | None -> () + member this.ProcessParameter (functionUse: FSharpSymbolUse) (source: Source) (group: int) (index: int voption) = cancellableTask { match tryDeclarationDocument functionUse.Symbol with | ValueSome(struct (declaration, document)) -> let! definition = this.Load document - let isFound = - match tryParameterPattern definition.Tree declaration group index with - | ValueSome(struct (SynPat.Tuple _ as parameter, parameterPath)) when isParameterList parameter parameterPath -> false - | ValueSome(struct (parameter, parameterPath)) -> - match parameter with - | SynPat.Typed _ -> this.IntoPattern definition parameter parameterPath - | SynPat.Tuple _ -> this.AddOrFail definition (tryPatChanges definition.Text toStruct parameter parameterPath) - | _ -> () - - match tryPatternIdent parameter with - | ValueSome ident -> this.EnqueueSymbol definition ident - | ValueNone -> () - - true - | ValueNone -> - match tryNamedBinding definition.Tree declaration with - | ValueSome(struct (body, _)) -> - match this.TryForwarded definition body with - | ValueSome(struct (callee, applied)) -> - this.EnqueueParameter definition callee (group + applied) index - true - | ValueNone -> false - | ValueNone -> false - - if isFound then + if this.DefineParameter definition declaration group index then let parameterName = tryParameterName functionUse.Symbol group index - let! uses = SymbolHelpers.getSymbolUses functionUse source.Document source.Check - - for useDocument, useRange in uses do - if not (isDeclaration useRange declaration) then - let! useSource = this.Load useDocument - - match tryUseNode useSource.Tree useRange with - | Some(node, path) -> - match tryArgument node path group with - | ValueSome(struct (argument, argumentPath)) -> - match tryArgumentValue parameterName index argument argumentPath with - | ValueSome(struct (value, valuePath)) -> this.Retarget useSource value valuePath - | ValueNone -> () - | ValueNone -> - match tryForwardingBinding node path 0 with - | ValueSome(struct (name, applied)) when applied <= group -> - this.EnqueueParameter useSource name (group - applied) index - | _ -> () - | None -> () + do! this.ForEachUse functionUse source declaration (this.FlowOutOfParameterUse parameterName group index) | ValueNone -> () } + member this.DefineParameter (definition: Source) (declaration: range) (group: int) (index: int voption) = + match tryParameterPattern definition.Tree declaration group index with + | ValueSome(struct (SynPat.Tuple _ as parameter, parameterPath)) when isParameterList parameter parameterPath -> false + | ValueSome(struct (parameter, parameterPath)) -> + match parameter with + | SynPat.Typed _ -> this.IntoPattern definition parameter parameterPath + | SynPat.Tuple _ -> this.AddOrFail definition (tryPatChanges definition.Text toStruct parameter parameterPath) + | _ -> () + + tryPatternIdent parameter |> ValueOption.iter (this.EnqueueValue definition) + true + | ValueNone -> this.ForwardParameter definition declaration group index + + member this.ForwardParameter (definition: Source) (declaration: range) (group: int) (index: int voption) = + let forwarded = + tryNamedBinding definition.Tree declaration + |> ValueOption.bind (fun struct (body, _) -> tryPartiallyAppliedFunction definition body) + + match forwarded with + | ValueSome(struct (callee, applied)) -> + this.EnqueueParameter definition callee (group + applied) index + true + | ValueNone -> false + + member this.FlowOutOfParameterUse + (parameterName: string option) + (group: int) + (index: int voption) + (useSource: Source) + (useRange: range) + = + match tryUseNode useSource.Tree useRange with + | Some(node, path) -> + match tryArgumentInGroup node path group with + | ValueSome(struct (argument, argumentPath)) -> + tryArgumentValue parameterName index argument argumentPath + |> ValueOption.iter (this.RetargetValue useSource) + | ValueNone -> + match tryForwardingBinding node path 0 with + | ValueSome(struct (name, applied)) when applied <= group -> this.EnqueueParameter useSource name (group - applied) index + | _ -> () + | None -> () + member this.Seed (source: Source) (caretNode: CaretNode) = match caretNode with | CaretNode.Expr(tuple, path) -> @@ -790,7 +732,7 @@ type private Engine(solution: Solution, toStruct: bool, userOpName: string) = this.AddOrFail source (tryPatChanges source.Text toStruct tuple path) for annotation in annotationsOn tuple path do - this.Add source (annotationChanges source.Text toStruct annotation) + this.AddAnnotation source annotation match tryMatchedExpression tuple path, tryWholeArgument tuple path with | ValueSome(struct (matched, matchedPath)), _ -> this.Retarget source matched matchedPath @@ -800,37 +742,30 @@ type private Engine(solution: Solution, toStruct: bool, userOpName: string) = this.Add source (typeChanges source.Text toStruct isWholeAnnotation tuple) if isWholeAnnotation then - match annotated with - | Annotated.Pattern(SynPat.Typed(pat = inner) as pat, path) -> - match tryPatternIdent inner with - | ValueSome ident -> this.EnqueueSymbol source ident - | ValueNone -> - this.IntoPattern source inner (SyntaxNode.SynPat pat :: path) - - match tryMatchedExpression pat path with - | ValueSome(struct (matched, matchedPath)) -> this.Retarget source matched matchedPath - | ValueNone -> () - - match tryParameterPosition pat path with - | ValueSome(struct (name, group, index)) -> this.EnqueueParameter source name group index - | ValueNone -> () - | Annotated.Pattern _ -> () - | Annotated.Expression(expr, path) -> - this.Retarget source expr path - this.FlowOut source expr path - | Annotated.Return(SynBinding( - headPat = SynPat.LongIdent(longDotId = SynLongIdent(id = ids); argPats = SynArgPats.Pats(_ :: _)))) -> - match List.tryLast ids with - | Some name -> this.EnqueueResult source name - | None -> () - | Annotated.Return(SynBinding(headPat = headPat)) -> - match tryPatternIdent headPat with - | ValueSome ident -> this.EnqueueSymbol source ident - | ValueNone -> () - | Annotated.Field(SynField(idOpt = Some ident)) -> this.EnqueueSymbol source ident - | Annotated.Field _ -> () - - /// The solution with every change of the chain, or ValueNone when a part cannot change or changes collide. + this.SeedAnnotated source annotated + + member this.SeedAnnotated (source: Source) (annotated: Annotated) = + match annotated with + | Annotated.Pattern(SynPat.Typed(pat = inner) as pat, path) -> this.SeedTypedPattern source pat inner path + | Annotated.Pattern _ -> () + | Annotated.Expression(expr, path) -> + this.Retarget source expr path + this.FlowOut source expr path + | Annotated.Return(SynBinding(headPat = FunctionHead name)) -> this.EnqueueResult source name + | Annotated.Return(SynBinding(headPat = headPat)) -> tryPatternIdent headPat |> ValueOption.iter (this.EnqueueValue source) + | Annotated.Field(SynField(idOpt = Some ident)) -> this.EnqueueValue source ident + | Annotated.Field _ -> () + + member this.SeedTypedPattern (source: Source) (pat: SynPat) (inner: SynPat) (path: SyntaxVisitorPath) = + match tryPatternIdent inner with + | ValueSome ident -> this.EnqueueValue source ident + | ValueNone -> + this.IntoPattern source inner (SyntaxNode.SynPat pat :: path) + tryMatchedExpression pat path |> ValueOption.iter (this.RetargetValue source) + + tryParameterPosition pat path + |> ValueOption.iter (fun struct (name, group, index) -> this.EnqueueParameter source name group index) + member this.Run(document: Document, caretNode: CaretNode) = cancellableTask { let! source = this.Load document @@ -838,7 +773,7 @@ type private Engine(solution: Solution, toStruct: bool, userOpName: string) = while pending.Count > 0 && not failed do match pending.Dequeue() with - | Slot.Symbol(symbolUse, slotSource) -> do! this.ProcessSymbol symbolUse slotSource + | Slot.Value(symbolUse, slotSource) -> do! this.ProcessValue symbolUse slotSource | Slot.Result(functionUse, slotSource) -> do! this.ProcessResult functionUse slotSource | Slot.Parameter(functionUse, slotSource, group, index) -> do! this.ProcessParameter functionUse slotSource group index @@ -860,6 +795,5 @@ type private Engine(solution: Solution, toStruct: bool, userOpName: string) = return if failed then ValueNone else result } -/// Changes the tuple under the caret to the other kind, together with everything its value flows through. let tryConvert (document: Document) (caretNode: CaretNode) (userOpName: string) = Engine(document.Project.Solution, not (isStructNode caretNode), userOpName).Run(document, caretNode) From 7c9a82d1e63e7b2d84b7a76dfe05d23cf91f3f65 Mon Sep 17 00:00:00 2001 From: XperiAndri Date: Thu, 15 Oct 2026 02:56:45 +0100 Subject: [PATCH 09/17] Share the cross-file refactoring test setup Move the test helpers into RefactorTestFramework, let them add the module M wrapper and run the two-file refactoring with its re-check as a new project, and assert both directions of a conversion in one helper. Co-Authored-By: Claude Sonnet 5.5 --- .../Refactors/ConvertTupleTests.fs | 270 ++---------------- .../Refactors/RefactorTestFramework.fs | 58 ++++ 2 files changed, 89 insertions(+), 239 deletions(-) diff --git a/vsintegration/tests/FSharp.Editor.Tests/Refactors/ConvertTupleTests.fs b/vsintegration/tests/FSharp.Editor.Tests/Refactors/ConvertTupleTests.fs index aced945fd2c..b29662444c2 100644 --- a/vsintegration/tests/FSharp.Editor.Tests/Refactors/ConvertTupleTests.fs +++ b/vsintegration/tests/FSharp.Editor.Tests/Refactors/ConvertTupleTests.fs @@ -1,88 +1,51 @@ module FSharp.Editor.Tests.Refactors.ConvertTupleTests -open System - -open Microsoft.CodeAnalysis open Microsoft.VisualStudio.FSharp.Editor -open Microsoft.VisualStudio.FSharp.Editor.CancellableTasks open Xunit -open FSharp.Compiler.Diagnostics - open FSharp.Editor.Tests.Refactors.RefactorTestFramework -let private caretAt (code: string) (marker: string) = - code.IndexOf(marker, StringComparison.Ordinal) - -let private textOf (document: Document) = - (document.GetTextAsync() |> GetTaskResult).ToString() - -let private errorsOf (document: Document) = - let _, checkResults = - document.GetFSharpParseAndCheckResultsAsync "test" - |> CancellableTask.runSynchronouslyWithoutCancellation +let private refactored (body: string) (marker: string) = + refactoredBy (new FSharpConvertTupleRefactoring()) body marker - checkResults.Diagnostics - |> Array.filter (fun diagnostic -> diagnostic.Severity = FSharpDiagnosticSeverity.Error) - -let private refactorIn (context: TestContext) (code: string) (marker: string) = - tryRefactor code (caretAt code marker) context (new FSharpConvertTupleRefactoring()) - -let private refactored (code: string) (marker: string) = - use context = TestContext.CreateWithCode code - let document = refactorIn context code marker - Assert.Empty(errorsOf document) - textOf document +let private actionsAt (body: string) (marker: string) = + actionsBy (new FSharpConvertTupleRefactoring()) body marker -let private actionsAt (code: string) (marker: string) = - use context = TestContext.CreateWithCode code - tryGetRefactoringActions code (caretAt code marker) context (new FSharpConvertTupleRefactoring()) +let private convertsBothWays (markers: string seq) (reference: string) (structs: string) = + for marker in markers do + Assert.Equal(structs, refactored reference marker) + Assert.Equal(reference, refactored structs marker) [] [] [ = [] """, "int * int", """ -module M - let pairs: list = [] """)>] [] let ``Tuple that flows nowhere else converts on its own`` (before: string, marker: string, after: string) = - Assert.Equal(after, refactored before marker) - Assert.Equal(before, refactored after marker) + convertsBothWays [ marker ] before after [] let ``Value, its tuple patterns and the annotations it flows into convert together`` () = let reference = """ -module M - let pair = (1, 2) let (a, b) = pair let copy: int * int = pair @@ -90,22 +53,17 @@ let copy: int * int = pair let structs = """ -module M - let pair = struct (1, 2) let struct (a, b) = pair let copy: struct (int * int) = pair """ - Assert.Equal(structs, refactored reference "1, 2") - Assert.Equal(reference, refactored structs "1, 2") + convertsBothWays [ "1, 2" ] reference structs [] let ``Parameter annotation converts its arguments and the patterns on it`` () = let reference = """ -module M - let sum (p: int * int) = let (a, b) = p a + b @@ -116,8 +74,6 @@ let total = sum pair + sum (1, 2) let structs = """ -module M - let sum (p: struct (int * int)) = let struct (a, b) = p a + b @@ -126,13 +82,10 @@ let pair = struct (3, 4) let total = sum pair + sum struct (1, 2) """ - Assert.Equal(structs, refactored reference "int * int") - Assert.Equal(reference, refactored structs "int * int") + convertsBothWays [ "int * int" ] reference structs [] [] [] let ``Parameter converts the matching argument of every call`` (reference: string, structs: string) = - Assert.Equal(structs, refactored reference "int * int") - Assert.Equal(reference, refactored structs "int * int") + convertsBothWays [ "int * int" ] reference structs [] [] [] let ``Tuple argument of a curried function or member converts with its calls`` (reference: string, marker: string, structs: string) = - Assert.Equal(structs, refactored reference marker) - Assert.Equal(reference, refactored structs marker) + convertsBothWays [ marker ] reference structs [] [] [(1, 2) """, "1, 2", """ -module M - let nothing = ignore<_> struct (1, 2) """)>] let ``Struct keyword is separated from a name or type arguments the parenthesis follows`` (code: string, marker: string, after: string) = @@ -253,8 +182,8 @@ module B let (a, b) = A.pair """ - use context = TestContext.CreateWithCodeAndDependency code definition - let document = refactorIn context code "a, b" + let struct (codeAfter, definitionAfter) = + refactoredAcrossFiles (new FSharpConvertTupleRefactoring()) definition code "a, b" Assert.Equal( """ @@ -262,7 +191,7 @@ module B let struct (a, b) = A.pair """, - textOf document + codeAfter ) Assert.Equal( @@ -271,35 +200,24 @@ module A let pair = struct (1, 2) """, - (context.Solution.Projects |> Seq.head).Documents |> Seq.head |> textOf + definitionAfter ) - // The checker reads the other file of a synthetic project from disk, so the result is checked as a new project. - let definitionAfter = - (context.Solution.Projects |> Seq.head).Documents |> Seq.head |> textOf - - use checkContext = - TestContext.CreateWithCodeAndDependency (textOf document) definitionAfter - - Assert.Empty((checkContext.Solution.Projects |> Seq.head).Documents |> Seq.last |> errorsOf) - [] let ``Use that cannot be followed is left for the compiler to report`` () = let code = - """ -module M - + inModuleM + """ let pair = (1, 2) let first = fst pair """ use context = TestContext.CreateWithCode code - let document = refactorIn context code "1, 2" + let document = refactorAt (new FSharpConvertTupleRefactoring()) context code "1, 2" Assert.Equal( - """ -module M - + inModuleM + """ let pair = struct (1, 2) let first = fst pair """, @@ -315,29 +233,22 @@ let first = fst pair let ``Return type converts the result and the patterns taking it apart`` (marker: string) = let reference = """ -module M - let origin () : int * int = (0, 0) let (x, y) = origin () """ let structs = """ -module M - let origin () : struct (int * int) = struct (0, 0) let struct (x, y) = origin () """ - Assert.Equal(structs, refactored reference marker) - Assert.Equal(reference, refactored structs marker) + convertsBothWays [ marker ] reference structs [] let ``Record field converts its values and the patterns on it`` () = let reference = """ -module M - type Line = { Start: int * int; Finish: int * int } let line = { Start = (0, 0); Finish = (1, 1) } @@ -346,8 +257,6 @@ let (sx, sy) = line.Start let structs = """ -module M - type Line = { Start: struct (int * int); Finish: int * int } let line = { Start = struct (0, 0); Finish = (1, 1) } @@ -361,15 +270,11 @@ let struct (sx, sy) = line.Start let ``Title names the target kind`` () = let reference = """ -module M - let pair = (1, 2) """ let structs = """ -module M - let pair = struct (1, 2) """ @@ -378,8 +283,6 @@ let pair = struct (1, 2) [] [] [ (0, 0) @@ -405,8 +304,6 @@ let make () = let (x, y) = make () """, """ -module M - let make () = try struct (1, 2) with _ -> struct (0, 0) @@ -414,43 +311,31 @@ let make () = let struct (x, y) = make () """)>] let ``Result flowing out of try converts every branch of it`` (reference: string, structs: string) = - Assert.Equal(structs, refactored reference "x, y") - Assert.Equal(reference, refactored structs "x, y") + convertsBothWays [ "x, y" ] reference structs [] [ p let (a, b) = copy """, """ -module M - let pair = struct (1, 2) let copy = match pair with | p -> p let struct (a, b) = copy """)>] [] let ``Value converts through the names it is bound to again`` (reference: string, structs: string) = - Assert.Equal(structs, refactored reference "1, 2") - Assert.Equal(reference, refactored structs "1, 2") - Assert.Equal(structs, refactored reference "a, b") - Assert.Equal(reference, refactored structs "a, b") + convertsBothWays [ "1, 2"; "a, b" ] reference structs [] [] @@ -458,165 +343,114 @@ let ``Value converts through the names it is bound to again`` (reference: string let ``Annotated value in parentheses converts with its initializer`` (marker: string) = let reference = """ -module M - let (pair: int * int) = (1, 2) let (a, b) = pair """ let structs = """ -module M - let (pair: struct (int * int)) = struct (1, 2) let struct (a, b) = pair """ - Assert.Equal(structs, refactored reference marker) - Assert.Equal(reference, refactored structs marker) + convertsBothWays [ marker ] reference structs [] [] [ a + b """, """ -module M - let pair = struct (1, 2) let total = match pair with | (struct (a, b): struct (int * int)) -> a + b """)>] [] [ a + b let total = sum (1, 2) """, """ -module M - let sum = fun (struct (a, b): struct (int * int)) -> a + b let total = sum struct (1, 2) """)>] let ``Annotated tuple pattern converts with its annotation and the value it takes apart`` (reference: string, structs: string) = - for marker in [ "a, b"; "int * int"; "1, 2" ] do - Assert.Equal(structs, refactored reference marker) - Assert.Equal(reference, refactored structs marker) + convertsBothWays [ "a, b"; "int * int"; "1, 2" ] reference structs [] [] [] [ a + b let value = sum (1, 2) """, """ -module M - let sum = fun struct (a, b) -> a + b let value = sum struct (1, 2) """)>] [ (1, 2) let (a, b) = make () """, """ -module M - let make = fun () -> struct (1, 2) let struct (a, b) = make () """)>] [] [] let ``Function in parentheses, bound as a lambda, aliased or partly applied converts with its calls`` (reference: string, structs: string) = - for marker in [ "1, 2"; "a, b" ] do - Assert.Equal(structs, refactored reference marker) - Assert.Equal(reference, refactored structs marker) + convertsBothWays [ "1, 2"; "a, b" ] reference structs [] [] [] [] let ``Named argument converts with the parameter it names`` (reference: string, structs: string, markers: string) = - for marker in markers.Split '|' do - Assert.Equal(structs, refactored reference marker) - Assert.Equal(reference, refactored structs marker) + convertsBothWays (markers.Split '|') reference structs [] let ``Comment between struct and its parenthesis is kept`` () = let code = """ -module M - type R = { Pair: struct (* note *) (int * int) } """ Assert.Equal( """ -module M - type R = { Pair: (* note *) int * int } """, refactored code "int * int" @@ -706,32 +524,24 @@ type R = { Pair: (* note *) int * int } [] let ``Struct keyword is separated from a name ending in a combining mark`` () = - let code = "\nmodule M\n\nlet f\u0301(a,b) = a+b\nlet x = f\u0301 (1,2)\n" + let code = "\nlet f\u0301(a,b) = a+b\nlet x = f\u0301 (1,2)\n" - Assert.Equal("\nmodule M\n\nlet f\u0301 struct (a,b) = a+b\nlet x = f\u0301 struct (1,2)\n", refactored code "a,b") + Assert.Equal("\nlet f\u0301 struct (a,b) = a+b\nlet x = f\u0301 struct (1,2)\n", refactored code "a,b") [] [] [] [] [] [ """, "1, 2")>] [] [] [] [] [] [] [] [ CancellableTask.startWithoutCancellation |> fun task -> task.Result + +let caretAt (code: string) (marker: string) = + code.IndexOf(marker, StringComparison.Ordinal) + +let textOf (document: Document) = + (document.GetTextAsync() |> GetTaskResult).ToString() + +let errorsOf (document: Document) = + let _, checkResults = + document.GetFSharpParseAndCheckResultsAsync "test" + |> CancellableTask.runSynchronouslyWithoutCancellation + + checkResults.Diagnostics + |> Array.filter (fun diagnostic -> diagnostic.Severity = FSharpDiagnosticSeverity.Error) + +let private moduleHeader (body: string) = + let lineBreak = body[.. body.IndexOf('\n')] + lineBreak + "module M" + lineBreak + +let inModuleM (body: string) = moduleHeader body + body + +let refactorAt (provider: 'T :> CodeRefactoringProvider) (context: TestContext) (code: string) (marker: string) = + tryRefactor code (caretAt code marker) context provider + +let refactoredBy (provider: 'T :> CodeRefactoringProvider) (body: string) (marker: string) = + let code = inModuleM body + use context = TestContext.CreateWithCode code + let document = refactorAt provider context code marker + Assert.Empty(errorsOf document) + + let header = moduleHeader body + let text = textOf document + Assert.StartsWith(header, text, StringComparison.Ordinal) + text.Substring header.Length + +let actionsBy (provider: 'T :> CodeRefactoringProvider) (body: string) (marker: string) = + let code = inModuleM body + use context = TestContext.CreateWithCode code + tryGetRefactoringActions code (caretAt code marker) context provider + +// The checker reads the other file of a synthetic project from disk, so the result is checked as a new project. +let refactoredAcrossFiles (provider: 'T :> CodeRefactoringProvider) (dependency: string) (code: string) (marker: string) = + use context = TestContext.CreateWithCodeAndDependency code dependency + let document = refactorAt provider context code marker + + let dependencyAfter = + (context.Solution.Projects |> Seq.head).Documents |> Seq.head |> textOf + + use checkContext = + TestContext.CreateWithCodeAndDependency (textOf document) dependencyAfter + + Assert.Empty((checkContext.Solution.Projects |> Seq.head).Documents |> Seq.last |> errorsOf) + + struct (textOf document, dependencyAfter) From 5260227e3fc16bf831e6877d71e11571a2a7cbb1 Mon Sep 17 00:00:00 2001 From: XperiAndri Date: Fri, 30 Oct 2026 00:54:20 +0100 Subject: [PATCH 10/17] Bring the rebased branch to what it had before the rebase Replaying the branch onto main left some files short of the branch's own content; this restores it. Co-Authored-By: Claude Sonnet 5.5 --- docs/release-notes/.VisualStudio/18.vNext.md | 1 - vsintegration/src/FSharp.Editor/FSharp.Editor.resx | 5 +++++ vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.cs.xlf | 7 +++++++ vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.de.xlf | 7 +++++++ vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.es.xlf | 7 +++++++ vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.fr.xlf | 7 +++++++ vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.it.xlf | 7 +++++++ vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.ja.xlf | 7 +++++++ vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.ko.xlf | 7 +++++++ vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.pl.xlf | 7 +++++++ .../src/FSharp.Editor/xlf/FSharp.Editor.pt-BR.xlf | 7 +++++++ vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.ru.xlf | 7 +++++++ vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.tr.xlf | 7 +++++++ .../src/FSharp.Editor/xlf/FSharp.Editor.zh-Hans.xlf | 7 +++++++ .../src/FSharp.Editor/xlf/FSharp.Editor.zh-Hant.xlf | 7 +++++++ 15 files changed, 96 insertions(+), 1 deletion(-) diff --git a/docs/release-notes/.VisualStudio/18.vNext.md b/docs/release-notes/.VisualStudio/18.vNext.md index 1af65e6ddab..ef63f52f6c0 100644 --- a/docs/release-notes/.VisualStudio/18.vNext.md +++ b/docs/release-notes/.VisualStudio/18.vNext.md @@ -8,7 +8,6 @@ * Move F# editor and Interactive options to 43 native Unified Settings with independent roaming and a one-time import of existing settings. Preserve the legacy groupings and Interactive setting order, with restart requirements displayed by Unified Settings. Quick Info's preferred description width is a checkbox with a dependent integer control. Remove the eight legacy options pages; the user-wide compiler setting remains external. Typing and deletion completion triggers are independent. ([PR #20877](https://github.com/dotnet/fsharp/pull/20877)) * Added a **Compiler** option in F# Unified Settings, **"Use the .NET SDK F# compiler for builds"**, on by default. Visual Studio uses the .NET SDK F# compiler when the project supplies SDK paths, matching `dotnet build`. Otherwise, it uses the bundled .NET Framework compiler. Turn the option off to use the bundled compiler for all projects. Command-line builds are unaffected. ([Issue #20484](https://github.com/dotnet/fsharp/issues/20484), [PR #20485](https://github.com/dotnet/fsharp/pull/20485)) * F# types, modules, members and values now appear in the GitHub Copilot Chat `#` mention picker, and attach their declaration source as context. ([PR #20409](https://github.com/dotnet/fsharp/pull/20409)) -* Refactoring to convert a tuple between a reference tuple and a struct tuple, following its value through the solution: annotations of values, parameters, record fields and results it flows through, tuple patterns that take it apart, and the arguments and values that flow into it. What cannot be followed (`fst`, `snd`, generic collections) is left for the compiler to report. ### Fixed diff --git a/vsintegration/src/FSharp.Editor/FSharp.Editor.resx b/vsintegration/src/FSharp.Editor/FSharp.Editor.resx index 0351d9fb36a..9895c8141d8 100644 --- a/vsintegration/src/FSharp.Editor/FSharp.Editor.resx +++ b/vsintegration/src/FSharp.Editor/FSharp.Editor.resx @@ -294,6 +294,11 @@ Returns: + + {0} in {1} +{2} + Tooltip of an F# declaration in the Copilot Chat "#" picker, as Copilot shows a C# one. {0} is the kind of declaration (Class, Method, Field...), {1} the file name, {2} the declaration's name. + Convert to struct tuple diff --git a/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.cs.xlf b/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.cs.xlf index 71fadd5b7b3..a83fb9d2ebb 100644 --- a/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.cs.xlf +++ b/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.cs.xlf @@ -72,6 +72,13 @@ Použít místo negace odčítání + + {0} in {1} +{2} + {0} in {1} +{2} + Tooltip of an F# declaration in the Copilot Chat "#" picker, as Copilot shows a C# one. {0} is the kind of declaration (Class, Method, Field...), {1} the file name, {2} the declaration's name. + Convert to struct tuple Convert to struct tuple diff --git a/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.de.xlf b/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.de.xlf index 4d1d3deb0f0..0016a080fd2 100644 --- a/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.de.xlf +++ b/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.de.xlf @@ -72,6 +72,13 @@ Subtraktion anstelle von Negation verwenden + + {0} in {1} +{2} + {0} in {1} +{2} + Tooltip of an F# declaration in the Copilot Chat "#" picker, as Copilot shows a C# one. {0} is the kind of declaration (Class, Method, Field...), {1} the file name, {2} the declaration's name. + Convert to struct tuple Convert to struct tuple diff --git a/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.es.xlf b/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.es.xlf index 796253dad8a..9e83d397f24 100644 --- a/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.es.xlf +++ b/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.es.xlf @@ -72,6 +72,13 @@ Usar la resta en lugar de la negación + + {0} in {1} +{2} + {0} in {1} +{2} + Tooltip of an F# declaration in the Copilot Chat "#" picker, as Copilot shows a C# one. {0} is the kind of declaration (Class, Method, Field...), {1} the file name, {2} the declaration's name. + Convert to struct tuple Convert to struct tuple diff --git a/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.fr.xlf b/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.fr.xlf index 807ff12ba4a..17a5b29806f 100644 --- a/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.fr.xlf +++ b/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.fr.xlf @@ -72,6 +72,13 @@ Utiliser la soustraction à la place de la négation + + {0} in {1} +{2} + {0} in {1} +{2} + Tooltip of an F# declaration in the Copilot Chat "#" picker, as Copilot shows a C# one. {0} is the kind of declaration (Class, Method, Field...), {1} the file name, {2} the declaration's name. + Convert to struct tuple Convert to struct tuple diff --git a/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.it.xlf b/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.it.xlf index d8cde89d11e..791c6d39fc2 100644 --- a/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.it.xlf +++ b/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.it.xlf @@ -72,6 +72,13 @@ Usare la sottrazione invece della negazione + + {0} in {1} +{2} + {0} in {1} +{2} + Tooltip of an F# declaration in the Copilot Chat "#" picker, as Copilot shows a C# one. {0} is the kind of declaration (Class, Method, Field...), {1} the file name, {2} the declaration's name. + Convert to struct tuple Convert to struct tuple diff --git a/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.ja.xlf b/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.ja.xlf index 5de2425a497..e004b3ef500 100644 --- a/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.ja.xlf +++ b/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.ja.xlf @@ -72,6 +72,13 @@ 否定の代わりに減算を使用する + + {0} in {1} +{2} + {0} in {1} +{2} + Tooltip of an F# declaration in the Copilot Chat "#" picker, as Copilot shows a C# one. {0} is the kind of declaration (Class, Method, Field...), {1} the file name, {2} the declaration's name. + Convert to struct tuple Convert to struct tuple diff --git a/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.ko.xlf b/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.ko.xlf index 8890edf3d98..4c0926e740e 100644 --- a/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.ko.xlf +++ b/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.ko.xlf @@ -72,6 +72,13 @@ 부정 대신 빼기 사용 + + {0} in {1} +{2} + {0} in {1} +{2} + Tooltip of an F# declaration in the Copilot Chat "#" picker, as Copilot shows a C# one. {0} is the kind of declaration (Class, Method, Field...), {1} the file name, {2} the declaration's name. + Convert to struct tuple Convert to struct tuple diff --git a/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.pl.xlf b/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.pl.xlf index 3ef8558c940..21474c0f861 100644 --- a/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.pl.xlf +++ b/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.pl.xlf @@ -72,6 +72,13 @@ Użyj odejmowania zamiast negacji + + {0} in {1} +{2} + {0} in {1} +{2} + Tooltip of an F# declaration in the Copilot Chat "#" picker, as Copilot shows a C# one. {0} is the kind of declaration (Class, Method, Field...), {1} the file name, {2} the declaration's name. + Convert to struct tuple Convert to struct tuple diff --git a/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.pt-BR.xlf b/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.pt-BR.xlf index 3f990a69eea..6bba340724e 100644 --- a/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.pt-BR.xlf +++ b/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.pt-BR.xlf @@ -72,6 +72,13 @@ Use a subtração em vez da negação + + {0} in {1} +{2} + {0} in {1} +{2} + Tooltip of an F# declaration in the Copilot Chat "#" picker, as Copilot shows a C# one. {0} is the kind of declaration (Class, Method, Field...), {1} the file name, {2} the declaration's name. + Convert to struct tuple Convert to struct tuple diff --git a/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.ru.xlf b/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.ru.xlf index 51ac3a60609..02d11f34e46 100644 --- a/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.ru.xlf +++ b/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.ru.xlf @@ -72,6 +72,13 @@ Используйте вычитание вместо отрицания. + + {0} in {1} +{2} + {0} in {1} +{2} + Tooltip of an F# declaration in the Copilot Chat "#" picker, as Copilot shows a C# one. {0} is the kind of declaration (Class, Method, Field...), {1} the file name, {2} the declaration's name. + Convert to struct tuple Convert to struct tuple diff --git a/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.tr.xlf b/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.tr.xlf index 6a6cf150b90..48ad6fa4e71 100644 --- a/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.tr.xlf +++ b/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.tr.xlf @@ -72,6 +72,13 @@ Negatif yapma yerine çıkarmayı kullanın + + {0} in {1} +{2} + {0} in {1} +{2} + Tooltip of an F# declaration in the Copilot Chat "#" picker, as Copilot shows a C# one. {0} is the kind of declaration (Class, Method, Field...), {1} the file name, {2} the declaration's name. + Convert to struct tuple Convert to struct tuple diff --git a/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.zh-Hans.xlf b/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.zh-Hans.xlf index 0630be81c1b..f9261b59be1 100644 --- a/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.zh-Hans.xlf +++ b/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.zh-Hans.xlf @@ -72,6 +72,13 @@ 使用减法代替求反 + + {0} in {1} +{2} + {0} in {1} +{2} + Tooltip of an F# declaration in the Copilot Chat "#" picker, as Copilot shows a C# one. {0} is the kind of declaration (Class, Method, Field...), {1} the file name, {2} the declaration's name. + Convert to struct tuple Convert to struct tuple diff --git a/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.zh-Hant.xlf b/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.zh-Hant.xlf index c7d4413b70d..3e6c14e883f 100644 --- a/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.zh-Hant.xlf +++ b/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.zh-Hant.xlf @@ -72,6 +72,13 @@ 使用減號代替否定 + + {0} in {1} +{2} + {0} in {1} +{2} + Tooltip of an F# declaration in the Copilot Chat "#" picker, as Copilot shows a C# one. {0} is the kind of declaration (Class, Method, Field...), {1} the file name, {2} the declaration's name. + Convert to struct tuple Convert to struct tuple From b77aaa7fd23df18784dc89313539103483918d2d Mon Sep 17 00:00:00 2001 From: XperiAndri Date: Sun, 8 Nov 2026 03:36:30 +0100 Subject: [PATCH 11/17] Convert both sides of an as pattern with the tuple it takes apart A value bound by `(a, b) as alias` reaches the tuple pattern and the alias alike: the conversion now follows the value into both sides of the as pattern, from the value, from either side, and through a parameter, so neither side keeps the old tuple kind (FS0001). Co-Authored-By: Claude Sonnet 5.5 --- .../Refactor/TuplePropagation.fs | 20 +++++++++++--- .../Refactors/ConvertTupleTests.fs | 26 +++++++++++++++++++ 2 files changed, 43 insertions(+), 3 deletions(-) diff --git a/vsintegration/src/FSharp.Editor/Refactor/TuplePropagation.fs b/vsintegration/src/FSharp.Editor/Refactor/TuplePropagation.fs index 1b4864f8b9d..d313682c58b 100644 --- a/vsintegration/src/FSharp.Editor/Refactor/TuplePropagation.fs +++ b/vsintegration/src/FSharp.Editor/Refactor/TuplePropagation.fs @@ -155,7 +155,7 @@ let rec private tryParameterPosition (pat: SynPat) (path: SyntaxVisitorPath) = let rec private tryMatchedExpression (pat: SynPat) (path: SyntaxVisitorPath) = match path with - | SyntaxNode.SynPat(SynPat.Paren _ | SynPat.Typed _ as wrapper) :: rest -> tryMatchedExpression wrapper rest + | SyntaxNode.SynPat(SynPat.Paren _ | SynPat.Typed _ | SynPat.As _ as wrapper) :: rest -> tryMatchedExpression wrapper rest | SyntaxNode.SynBinding(SynBinding(headPat = headPat; expr = body)) :: _ when isSame headPat pat -> ValueSome(struct (body, path)) | SyntaxNode.SynMatchClause(SynMatchClause(pat = clausePat)) :: SyntaxNode.SynExpr(SynExpr.Match(expr = scrutinee) as matchExpr) :: rest when isSame clausePat pat @@ -175,6 +175,7 @@ let private tryWholeArgument (pat: SynPat) (path: SyntaxVisitorPath) = match path with | SyntaxNode.SynPat(SynPat.Paren(pat = inner) | SynPat.Typed(pat = inner) as wrapper) :: rest when isSame inner pat -> outermost wrapper rest + | SyntaxNode.SynPat(SynPat.As _ as wrapper) :: rest -> outermost wrapper rest | _ -> struct (pat, path) let struct (argument, headPath) = outermost pat path @@ -468,6 +469,9 @@ type private Engine(solution: Solution, toStruct: bool, userOpName: string) = | SynPat.Named(ident = SynIdent(ident, _)) | SynPat.LongIdent(longDotId = SynLongIdent(id = [ ident ]); argPats = SynArgPats.Pats []) -> this.EnqueueValue source ident | SynPat.Tuple _ when not (isParameterList pat path) -> this.AddOrFail source (tryPatChanges source.Text toStruct pat path) + | SynPat.As(lhsPat = lhs; rhsPat = rhs) -> + this.IntoPattern source lhs (SyntaxNode.SynPat pat :: path) + this.IntoPattern source rhs (SyntaxNode.SynPat pat :: path) | _ -> () member this.FlowOut (source: Source) (node: SynExpr) (path: SyntaxVisitorPath) = @@ -568,6 +572,10 @@ type private Engine(solution: Solution, toStruct: bool, userOpName: string) = member this.RetargetValue (source: Source) (struct (value, path): struct (SynExpr * SyntaxVisitorPath)) = this.Retarget source value path + member this.FromMatched (source: Source) (struct (matched, matchedPath): struct (SynExpr * SyntaxVisitorPath)) = + this.Retarget source matched matchedPath + this.FlowOut source matched matchedPath + member this.RetargetResults (source: Source) (clauses: SynMatchClause list) (path: SyntaxVisitorPath) = for SynMatchClause(resultExpr = result) as clause in clauses do this.Retarget source result (SyntaxNode.SynMatchClause clause :: path) @@ -587,6 +595,11 @@ type private Engine(solution: Solution, toStruct: bool, userOpName: string) = |> List.exists (fun (SynMatchClause(pat = pat)) -> tryPatternIdent pat |> ValueOption.exists isDeclared) -> this.Retarget source scrutinee (node :: path) + | SyntaxNode.SynPat(SynPat.As(lhsPat = lhs; rhsPat = rhs) as pat) when + tryPatternIdent lhs |> ValueOption.exists isDeclared + || tryPatternIdent rhs |> ValueOption.exists isDeclared + -> + tryMatchedExpression pat path |> ValueOption.iter (this.FromMatched source) | SyntaxNode.SynPat(SynPat.Typed(pat = inner; targetType = annotation)) when tryPatternIdent inner |> ValueOption.exists isDeclared -> this.AddAnnotation source annotation | SyntaxNode.SynTypeDefn(SynTypeDefn( @@ -685,7 +698,8 @@ type private Engine(solution: Solution, toStruct: bool, userOpName: string) = | ValueSome(struct (SynPat.Tuple _ as parameter, parameterPath)) when isParameterList parameter parameterPath -> false | ValueSome(struct (parameter, parameterPath)) -> match parameter with - | SynPat.Typed _ -> this.IntoPattern definition parameter parameterPath + | SynPat.Typed _ + | SynPat.As _ -> this.IntoPattern definition parameter parameterPath | SynPat.Tuple _ -> this.AddOrFail definition (tryPatChanges definition.Text toStruct parameter parameterPath) | _ -> () @@ -735,7 +749,7 @@ type private Engine(solution: Solution, toStruct: bool, userOpName: string) = this.AddAnnotation source annotation match tryMatchedExpression tuple path, tryWholeArgument tuple path with - | ValueSome(struct (matched, matchedPath)), _ -> this.Retarget source matched matchedPath + | ValueSome matched, _ -> this.FromMatched source matched | ValueNone, ValueSome(struct (name, group)) -> this.EnqueueParameter source name group ValueNone | ValueNone, ValueNone -> () | CaretNode.Type(tuple, annotated, isWholeAnnotation) -> diff --git a/vsintegration/tests/FSharp.Editor.Tests/Refactors/ConvertTupleTests.fs b/vsintegration/tests/FSharp.Editor.Tests/Refactors/ConvertTupleTests.fs index b29662444c2..89387206ead 100644 --- a/vsintegration/tests/FSharp.Editor.Tests/Refactors/ConvertTupleTests.fs +++ b/vsintegration/tests/FSharp.Editor.Tests/Refactors/ConvertTupleTests.fs @@ -334,6 +334,32 @@ let pair = struct (1, 2) let alias = pair let struct (a, b) = alias """)>] +[] +[] +[] let ``Value converts through the names it is bound to again`` (reference: string, structs: string) = convertsBothWays [ "1, 2"; "a, b" ] reference structs From 4d1d452db49460bc630fd1f4ddadad02bb4a1a82 Mon Sep 17 00:00:00 2001 From: XperiAndri Date: Sun, 8 Nov 2026 03:42:08 +0100 Subject: [PATCH 12/17] Withhold the tuple conversion when the value passes a tuple abbreviation An annotation such as `Pair` for `type Pair = int * int` is a contract the conversion cannot rewrite, and converting around it gave FS0001. The checker resolves the annotation; when it abbreviates a tuple the conversion fails. The conversion now runs before the action is offered, so a failed conversion offers no action instead of one that changes nothing. Co-Authored-By: Claude Sonnet 5.5 --- .../FSharp.Editor/Refactor/ConvertTuple.fs | 34 +++++++------------ .../Refactor/TuplePropagation.fs | 16 ++++++++- .../Refactors/ConvertTupleTests.fs | 12 +++++++ 3 files changed, 39 insertions(+), 23 deletions(-) diff --git a/vsintegration/src/FSharp.Editor/Refactor/ConvertTuple.fs b/vsintegration/src/FSharp.Editor/Refactor/ConvertTuple.fs index 1ab0d597b07..a3d41e25bb0 100644 --- a/vsintegration/src/FSharp.Editor/Refactor/ConvertTuple.fs +++ b/vsintegration/src/FSharp.Editor/Refactor/ConvertTuple.fs @@ -68,31 +68,21 @@ type internal FSharpConvertTupleRefactoring [] () = match found with | ValueSome caretNode when not (isInQuotation caretNode) && canChange sourceText caretNode -> - let title = - if isStructNode caretNode then - SR.ConvertToReferenceTuple() - else - SR.ConvertToStructTuple() + let! converted = TuplePropagation.tryConvert document caretNode (nameof FSharpConvertTupleRefactoring) - let changedSolution = - cancellableTask { - let! converted = TuplePropagation.tryConvert document caretNode (nameof FSharpConvertTupleRefactoring) - - return - match converted with - | ValueSome solution -> solution - | ValueNone -> document.Project.Solution - } + match converted with + | ValueSome solution -> + let title = + if isStructNode caretNode then + SR.ConvertToReferenceTuple() + else + SR.ConvertToStructTuple() - let action = - CodeAction.Create( - title, - Func>(fun cancellationToken -> - CancellableTask.start cancellationToken changedSolution), - title - ) + let action = + CodeAction.Create(title, Func>(fun _ -> Task.FromResult solution), title) - context.RegisterRefactoring action + context.RegisterRefactoring action + | ValueNone -> () | _ -> () } |> CancellableTask.startAsTask context.CancellationToken diff --git a/vsintegration/src/FSharp.Editor/Refactor/TuplePropagation.fs b/vsintegration/src/FSharp.Editor/Refactor/TuplePropagation.fs index d313682c58b..1ff8bd07557 100644 --- a/vsintegration/src/FSharp.Editor/Refactor/TuplePropagation.fs +++ b/vsintegration/src/FSharp.Editor/Refactor/TuplePropagation.fs @@ -270,6 +270,17 @@ let private tryParameterPattern (tree: ParsedInput) (declaration: range) (group: let private annotationChanges (sourceText: SourceText) (toStruct: bool) (annotation: SynType) = typeChanges sourceText toStruct true (stripParenTypes annotation) +let rec private isTupleAbbreviation (source: Source) (annotation: SynType) = + match stripParenTypes annotation with + | SynType.App(typeName = typeName) -> isTupleAbbreviation source typeName + | SynType.LongIdent(SynLongIdent(id = ids)) -> + match List.tryLast ids |> Option.bind (symbolUseAt source) |> Option.map _.Symbol with + | Some(:? FSharpEntity as entity) -> + entity.IsFSharpAbbreviation + && entity.AbbreviatedType.StripAbbreviations().IsTupleType + | _ -> false + | _ -> false + let private hasName (name: string) (parameter: FSharpParameter) = parameter.Name |> Option.exists (fun parameterName -> String.Equals(parameterName, name, StringComparison.Ordinal)) @@ -415,7 +426,10 @@ type private Engine(solution: Solution, toStruct: bool, userOpName: string) = | ValueNone -> failed <- true member this.AddAnnotation (source: Source) (annotation: SynType) = - this.Add source (annotationChanges source.Text toStruct annotation) + if isTupleAbbreviation source annotation then + failed <- true + else + this.Add source (annotationChanges source.Text toStruct annotation) member _.Enqueue (key: string option) (slot: Slot) = match key with diff --git a/vsintegration/tests/FSharp.Editor.Tests/Refactors/ConvertTupleTests.fs b/vsintegration/tests/FSharp.Editor.Tests/Refactors/ConvertTupleTests.fs index 89387206ead..263a09519ae 100644 --- a/vsintegration/tests/FSharp.Editor.Tests/Refactors/ConvertTupleTests.fs +++ b/vsintegration/tests/FSharp.Editor.Tests/Refactors/ConvertTupleTests.fs @@ -622,4 +622,16 @@ let pair = 2 """, "1,")>] +[] +[] let ``No action`` (code: string, marker: string) = Assert.Empty(actionsAt code marker) From 2fef53cc5a4b0af5eaf48db400649e342432fd44 Mon Sep 17 00:00:00 2001 From: Andrii Chebukin Date: Mon, 14 Sep 2026 17:09:57 +0200 Subject: [PATCH 13/17] Add a refactoring between reference and struct anonymous records The tuple and anonymous record conversions now share one engine. The branch carried copies of the commits of the tuple branch and of several commits of main, so its history is rebuilt as this one commit on top of the tuple branch. It holds the refactoring, the shared engine with the review fixes, and the compaction made since they were first written. --- docs/release-notes/.VisualStudio/18.vNext.md | 1 + .../src/FSharp.Editor/FSharp.Editor.fsproj | 5 +- .../src/FSharp.Editor/FSharp.Editor.resx | 6 + .../Refactor/AnonymousRecordConversion.fs | 50 +++ .../Refactor/ConvertAnonymousRecord.fs | 22 + .../FSharp.Editor/Refactor/ConvertTuple.fs | 78 +--- .../Refactor/StructConversion.fs | 265 +++++++++++ ...plePropagation.fs => StructPropagation.fs} | 160 +++++-- .../FSharp.Editor/Refactor/TupleConversion.fs | 298 ++----------- .../FSharp.Editor/xlf/FSharp.Editor.cs.xlf | 10 + .../FSharp.Editor/xlf/FSharp.Editor.de.xlf | 10 + .../FSharp.Editor/xlf/FSharp.Editor.es.xlf | 10 + .../FSharp.Editor/xlf/FSharp.Editor.fr.xlf | 10 + .../FSharp.Editor/xlf/FSharp.Editor.it.xlf | 10 + .../FSharp.Editor/xlf/FSharp.Editor.ja.xlf | 10 + .../FSharp.Editor/xlf/FSharp.Editor.ko.xlf | 10 + .../FSharp.Editor/xlf/FSharp.Editor.pl.xlf | 10 + .../FSharp.Editor/xlf/FSharp.Editor.pt-BR.xlf | 10 + .../FSharp.Editor/xlf/FSharp.Editor.ru.xlf | 10 + .../FSharp.Editor/xlf/FSharp.Editor.tr.xlf | 10 + .../xlf/FSharp.Editor.zh-Hans.xlf | 10 + .../xlf/FSharp.Editor.zh-Hant.xlf | 10 + .../FSharp.Editor.Tests.fsproj | 1 + .../Refactors/ConvertAnonymousRecordTests.fs | 421 ++++++++++++++++++ .../Refactors/ConvertTupleTests.fs | 26 +- .../Refactors/RefactorTestFramework.fs | 5 + 26 files changed, 1095 insertions(+), 373 deletions(-) create mode 100644 vsintegration/src/FSharp.Editor/Refactor/AnonymousRecordConversion.fs create mode 100644 vsintegration/src/FSharp.Editor/Refactor/ConvertAnonymousRecord.fs create mode 100644 vsintegration/src/FSharp.Editor/Refactor/StructConversion.fs rename vsintegration/src/FSharp.Editor/Refactor/{TuplePropagation.fs => StructPropagation.fs} (86%) create mode 100644 vsintegration/tests/FSharp.Editor.Tests/Refactors/ConvertAnonymousRecordTests.fs diff --git a/docs/release-notes/.VisualStudio/18.vNext.md b/docs/release-notes/.VisualStudio/18.vNext.md index ef63f52f6c0..8f863bbcfb9 100644 --- a/docs/release-notes/.VisualStudio/18.vNext.md +++ b/docs/release-notes/.VisualStudio/18.vNext.md @@ -2,6 +2,7 @@ * Suggest active-pattern cases from unopened modules and offer valid Add Open and qualification edits. ([PR #20719](https://github.com/dotnet/fsharp/pull/20719)) * Add maintainer-requested F# Apex Visual Studio integration tests on DartLab-1ES CloudTest, using PR pipeline definitions pinned to an explicitly requested commit SHA. ([PR #20625](https://github.com/dotnet/fsharp/pull/20625)) +* Refactoring to convert an anonymous record between `{| … |}` and `struct {| … |}`, following its value through the solution the same way. A copy-and-update `{| r with … |}` has its own form and converts independently of `r`. ([PR #20549](https://github.com/dotnet/fsharp/pull/20549)) * Code-fixes for FS3888 (compiler-semantic attribute on the `.fs` but not the `.fsi`): copy the attribute into the `.fsi`, or remove it from the `.fs`. ([Issue #19560](https://github.com/dotnet/fsharp/issues/19560), [PR #19880](https://github.com/dotnet/fsharp/pull/19880)) * Refactoring to convert a tuple between a reference tuple and a struct tuple, following its value through the solution: annotations of values, parameters, record fields and results it flows through, tuple patterns that take it apart, and the arguments and values that flow into it. What cannot be followed (`fst`, `snd`, generic collections) is left for the compiler to report. ([PR #20548](https://github.com/dotnet/fsharp/pull/20548)) * Expand `` in IDE tooltips, completion, and signature help, inheriting XML documentation from base classes, interfaces, overridden members, and constructors. ([Issue #19175](https://github.com/dotnet/fsharp/issues/19175), [PR #19188](https://github.com/dotnet/fsharp/pull/19188)) diff --git a/vsintegration/src/FSharp.Editor/FSharp.Editor.fsproj b/vsintegration/src/FSharp.Editor/FSharp.Editor.fsproj index 62d5b851c6a..3ea87442556 100644 --- a/vsintegration/src/FSharp.Editor/FSharp.Editor.fsproj +++ b/vsintegration/src/FSharp.Editor/FSharp.Editor.fsproj @@ -109,9 +109,12 @@ + - + + + diff --git a/vsintegration/src/FSharp.Editor/FSharp.Editor.resx b/vsintegration/src/FSharp.Editor/FSharp.Editor.resx index 9895c8141d8..d8f5d72b8c0 100644 --- a/vsintegration/src/FSharp.Editor/FSharp.Editor.resx +++ b/vsintegration/src/FSharp.Editor/FSharp.Editor.resx @@ -305,6 +305,12 @@ Convert to reference tuple + + Convert to struct anonymous record + + + Convert to reference anonymous record + IntelliSense diff --git a/vsintegration/src/FSharp.Editor/Refactor/AnonymousRecordConversion.fs b/vsintegration/src/FSharp.Editor/Refactor/AnonymousRecordConversion.fs new file mode 100644 index 00000000000..5e6012b0c8e --- /dev/null +++ b/vsintegration/src/FSharp.Editor/Refactor/AnonymousRecordConversion.fs @@ -0,0 +1,50 @@ +// Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information. + +module internal Microsoft.VisualStudio.FSharp.Editor.AnonymousRecordConversion + +open Microsoft.CodeAnalysis.Text + +open FSharp.Compiler.Syntax +open FSharp.Compiler.Text + +open StructConversion + +let private keywordChanges (sourceText: SourceText) (toStruct: bool) (isStruct: bool) (m: range) = + match isStruct, toStruct with + | true, true + | false, false -> [] + | false, true -> + let start = (spanOf sourceText m).Start + [ TextChange(TextSpan(start, 0), structAt sourceText start) ] + | true, false -> [ TextChange(structKeyword sourceText m, "") ] + +let kind: StructKind = + { + IsExpr = + fun _ expr _ -> + match expr with + | SynExpr.AnonRecd _ -> true + | _ -> false + IsPat = fun _ _ -> false + IsParameterList = fun _ _ -> false + IsType = + function + | SynType.AnonRecd _ -> true + | _ -> false + IsStruct = + function + | CaretNode.Expr(node = SynExpr.AnonRecd(isStruct = isStruct)) + | CaretNode.Type(node = SynType.AnonRecd(isStruct = isStruct)) -> isStruct + | _ -> false + ExprChanges = + fun sourceText toStruct expr _ -> + match expr with + | SynExpr.AnonRecd(isStruct = isStruct; range = m) -> ValueSome(keywordChanges sourceText toStruct isStruct m) + | _ -> ValueNone + PatChanges = fun _ _ _ _ -> ValueNone + TypeChanges = + fun sourceText toStruct _ ty -> + match ty with + | SynType.AnonRecd(isStruct = isStruct; range = m) -> keywordChanges sourceText toStruct isStruct m + | _ -> [] + } diff --git a/vsintegration/src/FSharp.Editor/Refactor/ConvertAnonymousRecord.fs b/vsintegration/src/FSharp.Editor/Refactor/ConvertAnonymousRecord.fs new file mode 100644 index 00000000000..aa4ded9061a --- /dev/null +++ b/vsintegration/src/FSharp.Editor/Refactor/ConvertAnonymousRecord.fs @@ -0,0 +1,22 @@ +// 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.CodeRefactorings + +open CancellableTasks + +[] +type internal FSharpConvertAnonymousRecordRefactoring [] () = + inherit CodeRefactoringProvider() + + override _.ComputeRefactoringsAsync context = + StructPropagation.registerConversion + context + AnonymousRecordConversion.kind + SR.ConvertToStructAnonymousRecord + SR.ConvertToReferenceAnonymousRecord + (nameof FSharpConvertAnonymousRecordRefactoring) + |> CancellableTask.startAsTask context.CancellationToken diff --git a/vsintegration/src/FSharp.Editor/Refactor/ConvertTuple.fs b/vsintegration/src/FSharp.Editor/Refactor/ConvertTuple.fs index a3d41e25bb0..ddb820c25e3 100644 --- a/vsintegration/src/FSharp.Editor/Refactor/ConvertTuple.fs +++ b/vsintegration/src/FSharp.Editor/Refactor/ConvertTuple.fs @@ -2,87 +2,21 @@ namespace Microsoft.VisualStudio.FSharp.Editor -open System open System.Composition -open System.Threading -open System.Threading.Tasks -open Microsoft.CodeAnalysis -open Microsoft.CodeAnalysis.CodeActions open Microsoft.CodeAnalysis.CodeRefactorings -open FSharp.Compiler.Syntax -open FSharp.Compiler.Text - open CancellableTasks -open TupleConversion [] type internal FSharpConvertTupleRefactoring [] () = inherit CodeRefactoringProvider() - static let hasSignatureFile (document: Document) = - let signaturePath = document.FilePath + "i" - - document.Project.Documents - |> Seq.exists (fun d -> String.Equals(d.FilePath, signaturePath, StringComparison.OrdinalIgnoreCase)) - - static let isInQuotation (caretNode: CaretNode) = - let path = - match caretNode with - | CaretNode.Expr(path = path) - | CaretNode.Pat(path = path) - | CaretNode.Type(annotated = Annotated.Pattern(path = path)) - | CaretNode.Type(annotated = Annotated.Expression(path = path)) -> path - | CaretNode.Type _ -> [] - - path - |> List.exists (function - | SyntaxNode.SynExpr(SynExpr.Quote _) -> true - | _ -> false) - override _.ComputeRefactoringsAsync context = - cancellableTask { - let document = context.Document - - if not (document.IsFSharpSignatureFile || hasSignatureFile document) then - let! cancellationToken = CancellableTask.getCancellationToken () - let! sourceText = document.GetTextAsync cancellationToken - let! parseResults = document.GetFSharpParseResultsAsync(nameof FSharpConvertTupleRefactoring) - - let caret = - let linePosition = sourceText.Lines.GetLinePosition context.Span.Start - Position.mkPos (Line.fromZ linePosition.Line) linePosition.Character - - let hasTupleCandidate = - (tryCaretNode (fun _ -> false) caret parseResults.ParseTree).IsSome - - let! found = - if hasTupleCandidate then - cancellableTask { - let! _, checkResults = document.GetFSharpParseAndCheckResultsAsync(nameof FSharpConvertTupleRefactoring) - return tryCaretNode (callsMethod sourceText checkResults) caret parseResults.ParseTree - } - else - CancellableTask.singleton ValueNone - - match found with - | ValueSome caretNode when not (isInQuotation caretNode) && canChange sourceText caretNode -> - let! converted = TuplePropagation.tryConvert document caretNode (nameof FSharpConvertTupleRefactoring) - - match converted with - | ValueSome solution -> - let title = - if isStructNode caretNode then - SR.ConvertToReferenceTuple() - else - SR.ConvertToStructTuple() - - let action = - CodeAction.Create(title, Func>(fun _ -> Task.FromResult solution), title) - - context.RegisterRefactoring action - | ValueNone -> () - | _ -> () - } + StructPropagation.registerConversion + context + TupleConversion.kind + SR.ConvertToStructTuple + SR.ConvertToReferenceTuple + (nameof FSharpConvertTupleRefactoring) |> CancellableTask.startAsTask context.CancellationToken diff --git a/vsintegration/src/FSharp.Editor/Refactor/StructConversion.fs b/vsintegration/src/FSharp.Editor/Refactor/StructConversion.fs new file mode 100644 index 00000000000..71de660fd12 --- /dev/null +++ b/vsintegration/src/FSharp.Editor/Refactor/StructConversion.fs @@ -0,0 +1,265 @@ +// Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information. + +module internal Microsoft.VisualStudio.FSharp.Editor.StructConversion + +open System +open System.Globalization + +open Microsoft.CodeAnalysis.Text + +open FSharp.Compiler.CodeAnalysis +open FSharp.Compiler.Symbols +open FSharp.Compiler.Syntax +open FSharp.Compiler.Text + +let spanOf (sourceText: SourceText) (m: range) = + RoslynHelpers.FSharpRangeToTextSpan(sourceText, m) + +let isSame (node: 'T) (other: 'T) = obj.ReferenceEquals(node, other) + +let rec stripParenTypes (ty: SynType) = + match ty with + | SynType.Paren(innerType = inner) -> stripParenTypes inner + | _ -> ty + +let charAt (sourceText: SourceText) (position: int) = + if position >= 0 && position < sourceText.Length then + sourceText[position] + else + '\000' + +let structKeyword (sourceText: SourceText) (m: range) = + let start = (spanOf sourceText m).Start + let mutable finish = start + "struct".Length + + while finish < sourceText.Length && Char.IsWhiteSpace sourceText[finish] do + finish <- finish + 1 + + TextSpan.FromBounds(start, finish) + +let private endOfBlockComment (sourceText: SourceText) (start: int) = + let mutable depth = 1 + let mutable current = start + 2 + + while depth > 0 && current < sourceText.Length do + match charAt sourceText current, charAt sourceText (current + 1) with + | '(', '*' -> + depth <- depth + 1 + current <- current + 2 + | '*', ')' -> + depth <- depth - 1 + current <- current + 2 + | _ -> current <- current + 1 + + current + +let rec skipTrivia (sourceText: SourceText) (position: int) = + let at offset = charAt sourceText (position + offset) + + if position >= sourceText.Length then + position + elif Char.IsWhiteSpace(at 0) then + skipTrivia sourceText (position + 1) + elif at 0 = '/' && at 1 = '/' then + let line = sourceText.Lines.GetLineFromPosition position + skipTrivia sourceText line.EndIncludingLineBreak + elif at 0 = '(' && at 1 = '*' && at 2 <> ')' then + skipTrivia sourceText (endOfBlockComment sourceText position) + else + position + +let isIdentifierCharBefore (sourceText: SourceText) (position: int) = + if position <= 0 then + false + else + let last = sourceText[position - 1] + + let category = + if + Char.IsLowSurrogate last + && position >= 2 + && Char.IsHighSurrogate sourceText[position - 2] + then + CharUnicodeInfo.GetUnicodeCategory(String([| sourceText[position - 2]; last |]), 0) + else + CharUnicodeInfo.GetUnicodeCategory last + + match category with + | UnicodeCategory.UppercaseLetter + | UnicodeCategory.LowercaseLetter + | UnicodeCategory.TitlecaseLetter + | UnicodeCategory.ModifierLetter + | UnicodeCategory.OtherLetter + | UnicodeCategory.LetterNumber + | UnicodeCategory.DecimalDigitNumber + | UnicodeCategory.ConnectorPunctuation + | UnicodeCategory.NonSpacingMark + | UnicodeCategory.SpacingCombiningMark + | UnicodeCategory.Format -> true + | _ -> last = '\'' + +let needsSpaceBefore (sourceText: SourceText) (position: int) = + isIdentifierCharBefore sourceText position + || match charAt sourceText (position - 1) with + | '`' + | ')' + | ']' + | '}' + | '>' -> true + | _ -> false + +let structAt (sourceText: SourceText) (position: int) = + if needsSpaceBefore sourceText position then + " struct " + else + "struct " + +let rec tryCallee (expr: SynExpr) (applied: int) = + match expr with + | SynExpr.App(isInfix = false; funcExpr = funcExpr) -> tryCallee funcExpr (applied + 1) + | SynExpr.TypeApp(expr = inner) + | SynExpr.Paren(expr = inner) -> tryCallee inner applied + | SynExpr.Ident ident -> ValueSome(struct (ident, applied)) + | SynExpr.LongIdent(longDotId = SynLongIdent(id = ids)) + | SynExpr.DotGet(longDotId = SynLongIdent(id = ids)) -> + match List.tryLast ids with + | Some ident -> ValueSome(struct (ident, applied)) + | None -> ValueNone + | _ -> ValueNone + +let symbolUseAtIdent (sourceText: SourceText) (checkResults: FSharpCheckFileResults) (ident: Ident) = + let line = sourceText.Lines[Line.toZ ident.idRange.EndLine].ToString() + checkResults.GetSymbolUseAtLocation(ident.idRange.EndLine, ident.idRange.EndColumn, line, [ ident.idText ]) + +let private takesArgumentList (symbol: FSharpSymbol) = + match symbol with + | :? FSharpMemberOrFunctionOrValue as mfv -> + mfv.IsMember + && not mfv.IsProperty + && not mfv.IsEvent + && mfv.CurriedParameterGroups.Count <= 1 + | :? FSharpUnionCase as unionCase -> + unionCase.Fields.Count > 1 + || unionCase.Fields |> Seq.exists _.FieldType.IsTupleType + | :? FSharpEntity -> true + | _ -> false + +let callsMethod (sourceText: SourceText) (checkResults: FSharpCheckFileResults) (funcExpr: SynExpr) = + match tryCallee funcExpr 0 with + | ValueSome(struct (ident, 0)) -> + symbolUseAtIdent sourceText checkResults ident + |> Option.forall (fun symbolUse -> takesArgumentList symbolUse.Symbol) + | _ -> false + +[] +type Annotated = + | Pattern of pat: SynPat * path: SyntaxVisitorPath + | Expression of expr: SynExpr * path: SyntaxVisitorPath + | Return of binding: SynBinding + | Field of field: SynField + +[] +type CaretNode = + | Expr of node: SynExpr * path: SyntaxVisitorPath + | Pat of node: SynPat * path: SyntaxVisitorPath + | Type of node: SynType * annotated: Annotated * isWholeAnnotation: bool + +[] +type StructKind = + { + IsExpr: (SynExpr -> bool) -> SynExpr -> SyntaxVisitorPath -> bool + IsPat: SynPat -> SyntaxVisitorPath -> bool + // `M(p: int * int)` is still called as `M(1, 2)`: an annotation on a member's parameter list converts nothing else. + IsParameterList: SynPat -> SyntaxVisitorPath -> bool + IsType: SynType -> bool + IsStruct: CaretNode -> bool + ExprChanges: SourceText -> bool -> SynExpr -> SyntaxVisitorPath -> TextChange list voption + PatChanges: SourceText -> bool -> SynPat -> SyntaxVisitorPath -> TextChange list voption + TypeChanges: SourceText -> bool -> bool -> SynType -> TextChange list + } + +let rec private tryTypeAt (kind: StructKind) (position: pos) (ty: SynType) = + if not (Range.rangeContainsPos ty.Range position) then + ValueNone + else + let inner = + match ty with + | SynType.Paren(innerType = inner) + | SynType.Array(elementType = inner) + | SynType.WithGlobalConstraints(typeName = inner) -> tryTypeAt kind position inner + | SynType.App(typeName = typeName; typeArgs = typeArgs) + | SynType.LongIdentApp(typeName = typeName; typeArgs = typeArgs) -> + typeName :: typeArgs |> Seq.tryPickV (tryTypeAt kind position) + | SynType.Fun(argType = argType; returnType = returnType) -> [ argType; returnType ] |> Seq.tryPickV (tryTypeAt kind position) + | SynType.Tuple(path = segments) -> + segments + |> Seq.tryPickV (function + | SynTupleTypeSegment.Type element -> tryTypeAt kind position element + | _ -> ValueNone) + | SynType.AnonRecd(fields = fields) -> fields |> Seq.tryPickV (fun (_, fieldType) -> tryTypeAt kind position fieldType) + | _ -> ValueNone + + match inner with + | ValueSome _ -> inner + | ValueNone when kind.IsType ty -> ValueSome ty + | ValueNone -> ValueNone + +// A lambda parameter that is not a plain name is matched again in the body, without its parentheses and annotation. +let private isLambdaParameterAgain (pat: SynPat) (path: SyntaxVisitorPath) = + let rec lambdaArgs (path: SyntaxVisitorPath) = + match path with + | SyntaxNode.SynMatchClause _ :: SyntaxNode.SynExpr(SynExpr.Match _) :: rest -> lambdaArgs rest + | SyntaxNode.SynExpr(SynExpr.Lambda(parsedData = Some(args, _))) :: _ -> args + | _ -> [] + + let rec abovePatterns (path: SyntaxVisitorPath) = + match path with + | SyntaxNode.SynPat _ :: rest -> abovePatterns rest + | _ -> path + + match abovePatterns path with + | SyntaxNode.SynMatchClause _ :: _ as clausePath -> + lambdaArgs clausePath + |> List.exists (fun arg -> Range.rangeContainsRange arg.Range pat.Range) + | _ -> false + +let tryCaretNode (kind: StructKind) (callsMethod: SynExpr -> bool) (caret: pos) (parseTree: ParsedInput) = + let annotationAt (annotation: SynType) (annotated: Annotated) = + tryTypeAt kind caret annotation + |> ValueOption.map (fun node -> CaretNode.Type(node, annotated, isSame (stripParenTypes annotation) node)) + + (ValueNone, parseTree) + ||> ParsedInput.fold (fun found path node -> + match node with + | SyntaxNode.SynExpr expr when Range.rangeContainsPos expr.Range caret && kind.IsExpr callsMethod expr path -> + ValueSome(CaretNode.Expr(expr, path)) + | SyntaxNode.SynPat pat when Range.rangeContainsPos pat.Range caret && isLambdaParameterAgain pat path -> found + | SyntaxNode.SynPat pat when Range.rangeContainsPos pat.Range caret && kind.IsPat pat path -> ValueSome(CaretNode.Pat(pat, path)) + | SyntaxNode.SynPat(SynPat.Typed(targetType = annotation) as pat) when Range.rangeContainsPos annotation.Range caret -> + match annotationAt annotation (Annotated.Pattern(pat, path)) with + | ValueSome(CaretNode.Type(isWholeAnnotation = true)) when kind.IsParameterList pat path -> found + | node -> node |> ValueOption.orElse found + | SyntaxNode.SynExpr(SynExpr.Typed(targetType = annotation) as expr) when Range.rangeContainsPos annotation.Range caret -> + annotationAt annotation (Annotated.Expression(expr, path)) + |> ValueOption.orElse found + | SyntaxNode.SynBinding(SynBinding(returnInfo = Some(SynBindingReturnInfo(typeName = annotation))) as binding) when + Range.rangeContainsPos annotation.Range caret + -> + annotationAt annotation (Annotated.Return binding) |> ValueOption.orElse found + | SyntaxNode.SynTypeDefn(SynTypeDefn( + typeRepr = SynTypeDefnRepr.Simple(SynTypeDefnSimpleRepr.Record(recordFieldsAndSpreads = fields), _))) -> + fields + |> Seq.tryPickV (function + | SynFieldOrSpread.Field(SynField(fieldType = annotation) as field) when Range.rangeContainsPos annotation.Range caret -> + annotationAt annotation (Annotated.Field field) + | _ -> ValueNone) + |> ValueOption.orElse found + | _ -> found) + +let canChange (kind: StructKind) (sourceText: SourceText) (caretNode: CaretNode) = + let toStruct = not (kind.IsStruct caretNode) + + match caretNode with + | CaretNode.Expr(node, path) -> (kind.ExprChanges sourceText toStruct node path).IsSome + | CaretNode.Pat(node, path) -> (kind.PatChanges sourceText toStruct node path).IsSome + | CaretNode.Type _ -> true diff --git a/vsintegration/src/FSharp.Editor/Refactor/TuplePropagation.fs b/vsintegration/src/FSharp.Editor/Refactor/StructPropagation.fs similarity index 86% rename from vsintegration/src/FSharp.Editor/Refactor/TuplePropagation.fs rename to vsintegration/src/FSharp.Editor/Refactor/StructPropagation.fs index 1ff8bd07557..7de6461d173 100644 --- a/vsintegration/src/FSharp.Editor/Refactor/TuplePropagation.fs +++ b/vsintegration/src/FSharp.Editor/Refactor/StructPropagation.fs @@ -1,11 +1,15 @@ // Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information. -module internal Microsoft.VisualStudio.FSharp.Editor.TuplePropagation +module internal Microsoft.VisualStudio.FSharp.Editor.StructPropagation open System open System.Collections.Generic +open System.Threading +open System.Threading.Tasks open Microsoft.CodeAnalysis +open Microsoft.CodeAnalysis.CodeActions +open Microsoft.CodeAnalysis.CodeRefactorings open Microsoft.CodeAnalysis.Text open FSharp.Compiler.CodeAnalysis @@ -14,7 +18,7 @@ open FSharp.Compiler.Syntax open FSharp.Compiler.Text open CancellableTasks -open TupleConversion +open StructConversion [] type private Source = @@ -40,6 +44,17 @@ let private startsAt (position: pos) (ident: Ident) = let private endsAt (position: pos) (ident: Ident) = Position.posEq ident.idRange.End position +let private isGenericParameter (mfv: FSharpMemberOrFunctionOrValue) (group: int) (index: int voption) = + if group >= mfv.CurriedParameterGroups.Count then + false + else + let parameters = mfv.CurriedParameterGroups[group] + + match index with + | ValueSome index when index < parameters.Count -> parameters[index].Type.IsGenericParameter + | ValueSome _ -> false + | ValueNone -> parameters.Count = 1 && parameters[0].Type.IsGenericParameter + let rec private tryPatternIdent (pat: SynPat) = match pat with | SynPat.Named(ident = SynIdent(ident, _)) @@ -267,17 +282,14 @@ let private tryParameterPattern (tree: ParsedInput) (declaration: range) (group: |> ValueOption.bind (fun struct (body, bodyPath) -> tryLambda body bodyPath) |> ValueOption.bind (fun struct (args, _, argsPath) -> parameterIn args argsPath)) -let private annotationChanges (sourceText: SourceText) (toStruct: bool) (annotation: SynType) = - typeChanges sourceText toStruct true (stripParenTypes annotation) - -let rec private isTupleAbbreviation (source: Source) (annotation: SynType) = +let rec private isStructCandidateAbbreviation (source: Source) (annotation: SynType) = match stripParenTypes annotation with - | SynType.App(typeName = typeName) -> isTupleAbbreviation source typeName + | SynType.App(typeName = typeName) -> isStructCandidateAbbreviation source typeName | SynType.LongIdent(SynLongIdent(id = ids)) -> match List.tryLast ids |> Option.bind (symbolUseAt source) |> Option.map _.Symbol with - | Some(:? FSharpEntity as entity) -> - entity.IsFSharpAbbreviation - && entity.AbbreviatedType.StripAbbreviations().IsTupleType + | Some(:? FSharpEntity as entity) when entity.IsFSharpAbbreviation -> + let abbreviated = entity.AbbreviatedType.StripAbbreviations() + abbreviated.IsTupleType || abbreviated.IsAnonRecordType | _ -> false | _ -> false @@ -338,8 +350,11 @@ let private groupCount (mfv: FSharpMemberOrFunctionOrValue) = let private isValueSymbol (symbol: FSharpSymbol) = match symbol with - | :? FSharpField -> true - | :? FSharpMemberOrFunctionOrValue as mfv -> not mfv.IsFunction && not mfv.IsMember + | :? FSharpField as field -> not field.FieldType.IsGenericParameter + | :? FSharpMemberOrFunctionOrValue as mfv -> + not mfv.IsFunction + && not mfv.IsMember + && not (mfv.FullTypeSafe |> Option.exists _.IsGenericParameter) | _ -> false let private tryPartiallyAppliedFunction (source: Source) (body: SynExpr) = @@ -350,13 +365,16 @@ let private tryPartiallyAppliedFunction (source: Source) (body: SynExpr) = tryForwardedFunction body |> ValueOption.filter isPartiallyApplied -type private Engine(solution: Solution, toStruct: bool, userOpName: string) = +type private Engine(solution: Solution, kind: StructKind, toStruct: bool, userOpName: string) = let sources = Dictionary() let changes = Dictionary>() let visited = HashSet(StringComparer.Ordinal) let pending = Queue() let mutable failed = false + let annotationChanges (sourceText: SourceText) (annotation: SynType) = + kind.TypeChanges sourceText toStruct true (stripParenTypes annotation) + let isDeclaration (useRange: range) (declaration: range) = String.Equals(useRange.FileName, declaration.FileName, StringComparison.OrdinalIgnoreCase) && Position.posEq useRange.Start declaration.Start @@ -368,15 +386,15 @@ type private Engine(solution: Solution, toStruct: bool, userOpName: string) = |> ValueOption.map (fun document -> struct (declaration, document)) | None -> ValueNone - let keyOf (kind: string) (symbol: FSharpSymbol) = + let keyOf (slotKind: string) (symbol: FSharpSymbol) = symbol.DeclarationLocation - |> Option.map (fun m -> $"{kind}|{m.FileName}|{m.StartLine}|{m.StartColumn}") + |> Option.map (fun m -> $"{slotKind}|{m.FileName}|{m.StartLine}|{m.StartColumn}") let tryFunctionUse (source: Source) (name: Ident) = match symbolUseAt source name with | Some functionUse when (tryDeclarationDocument functionUse.Symbol).IsSome -> match functionUse.Symbol with - | :? FSharpMemberOrFunctionOrValue as mfv when mfv.IsFunction || mfv.IsMember -> ValueSome functionUse + | :? FSharpMemberOrFunctionOrValue as mfv when mfv.IsFunction || mfv.IsMember -> ValueSome(struct (functionUse, mfv)) | _ -> ValueNone | _ -> ValueNone @@ -426,10 +444,10 @@ type private Engine(solution: Solution, toStruct: bool, userOpName: string) = | ValueNone -> failed <- true member this.AddAnnotation (source: Source) (annotation: SynType) = - if isTupleAbbreviation source annotation then + if isStructCandidateAbbreviation source annotation then failed <- true else - this.Add source (annotationChanges source.Text toStruct annotation) + this.Add source (annotationChanges source.Text annotation) member _.Enqueue (key: string option) (slot: Slot) = match key with @@ -447,12 +465,13 @@ type private Engine(solution: Solution, toStruct: bool, userOpName: string) = member this.EnqueueResult (source: Source) (name: Ident) = match tryFunctionUse source name with - | ValueSome functionUse -> this.Enqueue (keyOf "R" functionUse.Symbol) (Slot.Result(functionUse, source)) - | ValueNone -> () + | ValueSome(struct (functionUse, mfv)) when not mfv.ReturnParameter.Type.IsGenericParameter -> + this.Enqueue (keyOf "R" functionUse.Symbol) (Slot.Result(functionUse, source)) + | _ -> () member this.EnqueueParameter (source: Source) (functionName: Ident) (group: int) (index: int voption) = match tryFunctionUse source functionName with - | ValueSome functionUse -> + | ValueSome(struct (functionUse, mfv)) when not (isGenericParameter mfv group index) -> let position = match index with | ValueSome index -> $"{group}|{index}" @@ -461,7 +480,7 @@ type private Engine(solution: Solution, toStruct: bool, userOpName: string) = this.Enqueue (keyOf "P" functionUse.Symbol |> Option.map (fun key -> $"{key}|{position}")) (Slot.Parameter(functionUse, source, group, index)) - | ValueNone -> () + | _ -> () member this.EnqueueNamedParameter (source: Source) (methodName: Ident) (group: int) (parameterName: Ident) = match symbolUseAt source methodName |> Option.map _.Symbol with @@ -482,7 +501,7 @@ type private Engine(solution: Solution, toStruct: bool, userOpName: string) = this.IntoPattern source inner (SyntaxNode.SynPat pat :: path) | SynPat.Named(ident = SynIdent(ident, _)) | SynPat.LongIdent(longDotId = SynLongIdent(id = [ ident ]); argPats = SynArgPats.Pats []) -> this.EnqueueValue source ident - | SynPat.Tuple _ when not (isParameterList pat path) -> this.AddOrFail source (tryPatChanges source.Text toStruct pat path) + | _ when kind.IsPat pat path -> this.AddOrFail source (kind.PatChanges source.Text toStruct pat path) | SynPat.As(lhsPat = lhs; rhsPat = rhs) -> this.IntoPattern source lhs (SyntaxNode.SynPat pat :: path) this.IntoPattern source rhs (SyntaxNode.SynPat pat :: path) @@ -563,8 +582,8 @@ type private Engine(solution: Solution, toStruct: bool, userOpName: string) = | SynExpr.Typed(expr = inner; targetType = annotation) -> this.AddAnnotation source annotation this.Retarget source inner childPath - | SynExpr.Tuple _ when not (isArgumentList (callsMethod source.Text source.Check) expr path) -> - this.AddOrFail source (tryExprChanges source.Text toStruct expr path) + | _ when kind.IsExpr (callsMethod source.Text source.Check) expr path -> + this.AddOrFail source (kind.ExprChanges source.Text toStruct expr path) | SynExpr.Ident ident -> this.EnqueueValue source ident | SynExpr.LongIdent(longDotId = SynLongIdent(id = ids)) | SynExpr.DotGet(longDotId = SynLongIdent(id = ids)) -> List.tryLast ids |> Option.iter (this.EnqueueValue source) @@ -709,12 +728,13 @@ type private Engine(solution: Solution, toStruct: bool, userOpName: string) = member this.DefineParameter (definition: Source) (declaration: range) (group: int) (index: int voption) = match tryParameterPattern definition.Tree declaration group index with - | ValueSome(struct (SynPat.Tuple _ as parameter, parameterPath)) when isParameterList parameter parameterPath -> false + | ValueSome(struct (SynPat.Tuple _ as parameter, parameterPath)) when not (kind.IsPat parameter parameterPath) -> false | ValueSome(struct (parameter, parameterPath)) -> match parameter with | SynPat.Typed _ | SynPat.As _ -> this.IntoPattern definition parameter parameterPath - | SynPat.Tuple _ -> this.AddOrFail definition (tryPatChanges definition.Text toStruct parameter parameterPath) + | _ when kind.IsPat parameter parameterPath -> + this.AddOrFail definition (kind.PatChanges definition.Text toStruct parameter parameterPath) | _ -> () tryPatternIdent parameter |> ValueOption.iter (this.EnqueueValue definition) @@ -753,21 +773,21 @@ type private Engine(solution: Solution, toStruct: bool, userOpName: string) = member this.Seed (source: Source) (caretNode: CaretNode) = match caretNode with - | CaretNode.Expr(tuple, path) -> - this.AddOrFail source (tryExprChanges source.Text toStruct tuple path) - this.FlowOut source tuple path - | CaretNode.Pat(tuple, path) -> - this.AddOrFail source (tryPatChanges source.Text toStruct tuple path) + | CaretNode.Expr(node, path) -> + this.AddOrFail source (kind.ExprChanges source.Text toStruct node path) + this.FlowOut source node path + | CaretNode.Pat(node, path) -> + this.AddOrFail source (kind.PatChanges source.Text toStruct node path) - for annotation in annotationsOn tuple path do + for annotation in annotationsOn node path do this.AddAnnotation source annotation - match tryMatchedExpression tuple path, tryWholeArgument tuple path with + match tryMatchedExpression node path, tryWholeArgument node path with | ValueSome matched, _ -> this.FromMatched source matched | ValueNone, ValueSome(struct (name, group)) -> this.EnqueueParameter source name group ValueNone | ValueNone, ValueNone -> () - | CaretNode.Type(tuple, annotated, isWholeAnnotation) -> - this.Add source (typeChanges source.Text toStruct isWholeAnnotation tuple) + | CaretNode.Type(node, annotated, isWholeAnnotation) -> + this.Add source (kind.TypeChanges source.Text toStruct isWholeAnnotation node) if isWholeAnnotation then this.SeedAnnotated source annotated @@ -823,5 +843,69 @@ type private Engine(solution: Solution, toStruct: bool, userOpName: string) = return if failed then ValueNone else result } -let tryConvert (document: Document) (caretNode: CaretNode) (userOpName: string) = - Engine(document.Project.Solution, not (isStructNode caretNode), userOpName).Run(document, caretNode) +let private hasSignatureFile (document: Document) = + let signaturePath = document.FilePath + "i" + + document.Project.Documents + |> Seq.exists (fun d -> String.Equals(d.FilePath, signaturePath, StringComparison.OrdinalIgnoreCase)) + +let private isInQuotation (caretNode: CaretNode) = + let path = + match caretNode with + | CaretNode.Expr(path = path) + | CaretNode.Pat(path = path) + | CaretNode.Type(annotated = Annotated.Pattern(path = path)) + | CaretNode.Type(annotated = Annotated.Expression(path = path)) -> path + | CaretNode.Type _ -> [] + + path + |> List.exists (function + | SyntaxNode.SynExpr(SynExpr.Quote _) -> true + | _ -> false) + +let private conversionAction (title: string) (solution: Solution) = + CodeAction.Create(title, Func>(fun _ -> Task.FromResult solution), title) + +let registerConversion + (context: CodeRefactoringContext) + (kind: StructKind) + (toStructTitle: unit -> string) + (toReferenceTitle: unit -> string) + (userOpName: string) + = + cancellableTask { + let document = context.Document + + if not (document.IsFSharpSignatureFile || hasSignatureFile document) then + let! cancellationToken = CancellableTask.getCancellationToken () + let! sourceText = document.GetTextAsync cancellationToken + let! parseResults = document.GetFSharpParseResultsAsync userOpName + + let caret = + let linePosition = sourceText.Lines.GetLinePosition context.Span.Start + Position.mkPos (Line.fromZ linePosition.Line) linePosition.Character + + let hasCandidate = + (tryCaretNode kind (fun _ -> false) caret parseResults.ParseTree).IsSome + + let! found = + if hasCandidate then + cancellableTask { + let! _, checkResults = document.GetFSharpParseAndCheckResultsAsync userOpName + return tryCaretNode kind (callsMethod sourceText checkResults) caret parseResults.ParseTree + } + else + CancellableTask.singleton ValueNone + + match found with + | ValueSome caretNode when not (isInQuotation caretNode) && canChange kind sourceText caretNode -> + let isStruct = kind.IsStruct caretNode + let! converted = Engine(document.Project.Solution, kind, not isStruct, userOpName).Run(document, caretNode) + + match converted with + | ValueSome solution -> + let title = if isStruct then toReferenceTitle () else toStructTitle () + context.RegisterRefactoring(conversionAction title solution) + | ValueNone -> () + | _ -> () + } diff --git a/vsintegration/src/FSharp.Editor/Refactor/TupleConversion.fs b/vsintegration/src/FSharp.Editor/Refactor/TupleConversion.fs index b2af4a7a191..882ea3dde6a 100644 --- a/vsintegration/src/FSharp.Editor/Refactor/TupleConversion.fs +++ b/vsintegration/src/FSharp.Editor/Refactor/TupleConversion.fs @@ -3,116 +3,13 @@ module internal Microsoft.VisualStudio.FSharp.Editor.TupleConversion open System -open System.Globalization open Microsoft.CodeAnalysis.Text -open FSharp.Compiler.CodeAnalysis -open FSharp.Compiler.Symbols open FSharp.Compiler.Syntax open FSharp.Compiler.Text -let spanOf (sourceText: SourceText) (m: range) = - RoslynHelpers.FSharpRangeToTextSpan(sourceText, m) - -let isSame (node: 'T) (other: 'T) = obj.ReferenceEquals(node, other) - -let rec stripParenTypes (ty: SynType) = - match ty with - | SynType.Paren(innerType = inner) -> stripParenTypes inner - | _ -> ty - -let private charAt (sourceText: SourceText) (position: int) = - if position >= 0 && position < sourceText.Length then - sourceText[position] - else - '\000' - -let private structKeyword (sourceText: SourceText) (m: range) = - let start = (spanOf sourceText m).Start - let mutable finish = start + "struct".Length - - while finish < sourceText.Length && Char.IsWhiteSpace sourceText[finish] do - finish <- finish + 1 - - TextSpan.FromBounds(start, finish) - -let private endOfBlockComment (sourceText: SourceText) (start: int) = - let mutable depth = 1 - let mutable current = start + 2 - - while depth > 0 && current < sourceText.Length do - match charAt sourceText current, charAt sourceText (current + 1) with - | '(', '*' -> - depth <- depth + 1 - current <- current + 2 - | '*', ')' -> - depth <- depth - 1 - current <- current + 2 - | _ -> current <- current + 1 - - current - -let rec private skipTrivia (sourceText: SourceText) (position: int) = - let at offset = charAt sourceText (position + offset) - - if position >= sourceText.Length then - position - elif Char.IsWhiteSpace(at 0) then - skipTrivia sourceText (position + 1) - elif at 0 = '/' && at 1 = '/' then - let line = sourceText.Lines.GetLineFromPosition position - skipTrivia sourceText line.EndIncludingLineBreak - elif at 0 = '(' && at 1 = '*' && at 2 <> ')' then - skipTrivia sourceText (endOfBlockComment sourceText position) - else - position - -let isIdentifierCharBefore (sourceText: SourceText) (position: int) = - if position <= 0 then - false - else - let last = sourceText[position - 1] - - let category = - if - Char.IsLowSurrogate last - && position >= 2 - && Char.IsHighSurrogate sourceText[position - 2] - then - CharUnicodeInfo.GetUnicodeCategory(String([| sourceText[position - 2]; last |]), 0) - else - CharUnicodeInfo.GetUnicodeCategory last - - match category with - | UnicodeCategory.UppercaseLetter - | UnicodeCategory.LowercaseLetter - | UnicodeCategory.TitlecaseLetter - | UnicodeCategory.ModifierLetter - | UnicodeCategory.OtherLetter - | UnicodeCategory.LetterNumber - | UnicodeCategory.DecimalDigitNumber - | UnicodeCategory.ConnectorPunctuation - | UnicodeCategory.NonSpacingMark - | UnicodeCategory.SpacingCombiningMark - | UnicodeCategory.Format -> true - | _ -> last = '\'' - -let needsSpaceBefore (sourceText: SourceText) (position: int) = - isIdentifierCharBefore sourceText position - || match charAt sourceText (position - 1) with - | '`' - | ')' - | ']' - | '}' - | '>' -> true - | _ -> false - -let private structAt (sourceText: SourceText) (position: int) = - if needsSpaceBefore sourceText position then - " struct " - else - "struct " +open StructConversion let private nonBlankAround (sourceText: SourceText) (span: TextSpan) = let mutable before = span.Start - 1 @@ -174,7 +71,7 @@ let private dropStructChanges (sourceText: SourceText) (isWholeAnnotation: bool) else [ TextChange(keyword, "") ] -let typeChanges (sourceText: SourceText) (toStruct: bool) (isWholeAnnotation: bool) (tupleType: SynType) = +let private typeChanges (sourceText: SourceText) (toStruct: bool) (isWholeAnnotation: bool) (tupleType: SynType) = match tupleType with | SynType.Tuple(isStruct = isStruct; range = m) when isStruct <> toStruct -> if toStruct then @@ -183,44 +80,7 @@ let typeChanges (sourceText: SourceText) (toStruct: bool) (isWholeAnnotation: bo dropStructChanges sourceText isWholeAnnotation m | _ -> [] -let rec tryCallee (expr: SynExpr) (applied: int) = - match expr with - | SynExpr.App(isInfix = false; funcExpr = funcExpr) -> tryCallee funcExpr (applied + 1) - | SynExpr.TypeApp(expr = inner) - | SynExpr.Paren(expr = inner) -> tryCallee inner applied - | SynExpr.Ident ident -> ValueSome(struct (ident, applied)) - | SynExpr.LongIdent(longDotId = SynLongIdent(id = ids)) - | SynExpr.DotGet(longDotId = SynLongIdent(id = ids)) -> - match List.tryLast ids with - | Some ident -> ValueSome(struct (ident, applied)) - | None -> ValueNone - | _ -> ValueNone - -let symbolUseAtIdent (sourceText: SourceText) (checkResults: FSharpCheckFileResults) (ident: Ident) = - let line = sourceText.Lines[Line.toZ ident.idRange.EndLine].ToString() - checkResults.GetSymbolUseAtLocation(ident.idRange.EndLine, ident.idRange.EndColumn, line, [ ident.idText ]) - -let private takesArgumentList (symbol: FSharpSymbol) = - match symbol with - | :? FSharpMemberOrFunctionOrValue as mfv -> - mfv.IsMember - && not mfv.IsProperty - && not mfv.IsEvent - && mfv.CurriedParameterGroups.Count <= 1 - | :? FSharpUnionCase as unionCase -> - unionCase.Fields.Count > 1 - || unionCase.Fields |> Seq.exists _.FieldType.IsTupleType - | :? FSharpEntity -> true - | _ -> false - -let callsMethod (sourceText: SourceText) (checkResults: FSharpCheckFileResults) (funcExpr: SynExpr) = - match tryCallee funcExpr 0 with - | ValueSome(struct (ident, 0)) -> - symbolUseAtIdent sourceText checkResults ident - |> Option.forall (fun symbolUse -> takesArgumentList symbolUse.Symbol) - | _ -> false - -let isArgumentList (callsMethod: SynExpr -> bool) (tuple: SynExpr) (path: SyntaxVisitorPath) = +let private isArgumentList (callsMethod: SynExpr -> bool) (tuple: SynExpr) (path: SyntaxVisitorPath) = match path with | SyntaxNode.SynExpr(SynExpr.Paren(expr = inner) as paren) :: SyntaxNode.SynExpr(SynExpr.New(expr = arg)) :: _ -> isSame inner tuple && isSame arg paren @@ -228,17 +88,6 @@ let isArgumentList (callsMethod: SynExpr -> bool) (tuple: SynExpr) (path: Syntax isInfix = false; funcExpr = funcExpr; argExpr = arg)) :: _ when isSame inner tuple && isSame arg paren -> callsMethod funcExpr | _ -> false -let isParameterList (pat: SynPat) (path: SyntaxVisitorPath) = - let struct (argument, headPath) = - match path with - | SyntaxNode.SynPat(SynPat.Paren(pat = inner) as paren) :: rest when isSame inner pat -> struct (paren, rest) - | _ -> struct (pat, path) - - match headPath with - | SyntaxNode.SynPat(SynPat.LongIdent(argPats = SynArgPats.Pats [ only ])) :: SyntaxNode.SynBinding(SynBinding( - valData = SynValData(memberFlags = Some _))) :: _ -> isSame only argument - | _ -> false - let private tupleChanges (sourceText: SourceText) (toStruct: bool) (isStruct: bool) (m: range) (enclosingParen: range voption) = if isStruct = toStruct then ValueSome [] @@ -252,7 +101,7 @@ let private tupleChanges (sourceText: SourceText) (toStruct: bool) (isStruct: bo | ValueNone when m.StartLine = m.EndLine -> ValueSome(insertStructParens (spanOf sourceText m)) | ValueNone -> ValueNone -let tryExprChanges (sourceText: SourceText) (toStruct: bool) (tuple: SynExpr) (path: SyntaxVisitorPath) = +let private tryExprChanges (sourceText: SourceText) (toStruct: bool) (tuple: SynExpr) (path: SyntaxVisitorPath) = match tuple, path with | SynExpr.Tuple(isStruct = isStruct; range = m), SyntaxNode.SynExpr(SynExpr.Paren(expr = inner; range = parenRange)) :: _ when isSame inner tuple @@ -261,7 +110,7 @@ let tryExprChanges (sourceText: SourceText) (toStruct: bool) (tuple: SynExpr) (p | SynExpr.Tuple(isStruct = isStruct; range = m), _ -> tupleChanges sourceText toStruct isStruct m ValueNone | _ -> ValueNone -let tryPatChanges (sourceText: SourceText) (toStruct: bool) (tuple: SynPat) (path: SyntaxVisitorPath) = +let private tryPatChanges (sourceText: SourceText) (toStruct: bool) (tuple: SynPat) (path: SyntaxVisitorPath) = match tuple, path with | SynPat.Tuple(isStruct = isStruct; range = m), SyntaxNode.SynPat(SynPat.Paren(pat = inner; range = parenRange)) :: _ when isSame inner tuple @@ -270,110 +119,41 @@ let tryPatChanges (sourceText: SourceText) (toStruct: bool) (tuple: SynPat) (pat | SynPat.Tuple(isStruct = isStruct; range = m), _ -> tupleChanges sourceText toStruct isStruct m ValueNone | _ -> ValueNone -let rec tryTupleTypeAt (position: pos) (ty: SynType) = - if not (Range.rangeContainsPos ty.Range position) then - ValueNone - else - let inner = - match ty with - | SynType.Paren(innerType = inner) - | SynType.Array(elementType = inner) - | SynType.WithGlobalConstraints(typeName = inner) -> tryTupleTypeAt position inner - | SynType.App(typeName = typeName; typeArgs = typeArgs) - | SynType.LongIdentApp(typeName = typeName; typeArgs = typeArgs) -> - typeName :: typeArgs |> Seq.tryPickV (tryTupleTypeAt position) - | SynType.Fun(argType = argType; returnType = returnType) -> [ argType; returnType ] |> Seq.tryPickV (tryTupleTypeAt position) - | SynType.Tuple(path = segments) -> - segments - |> Seq.tryPickV (function - | SynTupleTypeSegment.Type element -> tryTupleTypeAt position element - | _ -> ValueNone) - | _ -> ValueNone - - match inner, ty with - | ValueSome _, _ -> inner - | ValueNone, SynType.Tuple _ -> ValueSome ty - | ValueNone, _ -> ValueNone - -[] -type Annotated = - | Pattern of pat: SynPat * path: SyntaxVisitorPath - | Expression of expr: SynExpr * path: SyntaxVisitorPath - | Return of binding: SynBinding - | Field of field: SynField - -[] -type CaretNode = - | Expr of tuple: SynExpr * path: SyntaxVisitorPath - | Pat of tuple: SynPat * path: SyntaxVisitorPath - | Type of tuple: SynType * annotated: Annotated * isWholeAnnotation: bool - -let isStructNode (node: CaretNode) = - match node with - | CaretNode.Expr(tuple = SynExpr.Tuple(isStruct = isStruct)) - | CaretNode.Pat(tuple = SynPat.Tuple(isStruct = isStruct)) - | CaretNode.Type(tuple = SynType.Tuple(isStruct = isStruct)) -> isStruct - | _ -> false - -// A lambda parameter that is not a plain name is matched again in the body, without its parentheses and annotation. -let private isLambdaParameterAgain (pat: SynPat) (path: SyntaxVisitorPath) = - let rec lambdaArgs (path: SyntaxVisitorPath) = - match path with - | SyntaxNode.SynMatchClause _ :: SyntaxNode.SynExpr(SynExpr.Match _) :: rest -> lambdaArgs rest - | SyntaxNode.SynExpr(SynExpr.Lambda(parsedData = Some(args, _))) :: _ -> args - | _ -> [] - - let rec abovePatterns (path: SyntaxVisitorPath) = +let private isParameterList (pat: SynPat) (path: SyntaxVisitorPath) = + let struct (argument, headPath) = match path with - | SyntaxNode.SynPat _ :: rest -> abovePatterns rest - | _ -> path + | SyntaxNode.SynPat(SynPat.Paren(pat = inner) as paren) :: rest when isSame inner pat -> struct (paren, rest) + | _ -> struct (pat, path) - match abovePatterns path with - | SyntaxNode.SynMatchClause _ :: _ as clausePath -> - lambdaArgs clausePath - |> List.exists (fun arg -> Range.rangeContainsRange arg.Range pat.Range) + match headPath with + | SyntaxNode.SynPat(SynPat.LongIdent(argPats = SynArgPats.Pats [ only ])) :: SyntaxNode.SynBinding(SynBinding( + valData = SynValData(memberFlags = Some _))) :: _ -> isSame only argument | _ -> false -let tryCaretNode (callsMethod: SynExpr -> bool) (caret: pos) (parseTree: ParsedInput) = - let annotationAt (annotation: SynType) (annotated: Annotated) = - tryTupleTypeAt caret annotation - |> ValueOption.map (fun tuple -> CaretNode.Type(tuple, annotated, isSame (stripParenTypes annotation) tuple)) - - (ValueNone, parseTree) - ||> ParsedInput.fold (fun found path node -> - match node with - | SyntaxNode.SynExpr(SynExpr.Tuple(range = m) as tuple) when - Range.rangeContainsPos m caret && not (isArgumentList callsMethod tuple path) - -> - ValueSome(CaretNode.Expr(tuple, path)) - | SyntaxNode.SynPat pat when Range.rangeContainsPos pat.Range caret && isLambdaParameterAgain pat path -> found - | SyntaxNode.SynPat(SynPat.Tuple(range = m) as tuple) when Range.rangeContainsPos m caret && not (isParameterList tuple path) -> - ValueSome(CaretNode.Pat(tuple, path)) - | SyntaxNode.SynPat(SynPat.Typed(targetType = annotation) as pat) when Range.rangeContainsPos annotation.Range caret -> - match annotationAt annotation (Annotated.Pattern(pat, path)) with - | ValueSome(CaretNode.Type(isWholeAnnotation = true)) when isParameterList pat path -> found - | node -> node |> ValueOption.orElse found - | SyntaxNode.SynExpr(SynExpr.Typed(targetType = annotation) as expr) when Range.rangeContainsPos annotation.Range caret -> - annotationAt annotation (Annotated.Expression(expr, path)) - |> ValueOption.orElse found - | SyntaxNode.SynBinding(SynBinding(returnInfo = Some(SynBindingReturnInfo(typeName = annotation))) as binding) when - Range.rangeContainsPos annotation.Range caret - -> - annotationAt annotation (Annotated.Return binding) |> ValueOption.orElse found - | SyntaxNode.SynTypeDefn(SynTypeDefn( - typeRepr = SynTypeDefnRepr.Simple(SynTypeDefnSimpleRepr.Record(recordFieldsAndSpreads = fields), _))) -> - fields - |> Seq.tryPickV (function - | SynFieldOrSpread.Field(SynField(fieldType = annotation) as field) when Range.rangeContainsPos annotation.Range caret -> - annotationAt annotation (Annotated.Field field) - | _ -> ValueNone) - |> ValueOption.orElse found - | _ -> found) - -let canChange (sourceText: SourceText) (node: CaretNode) = - let toStruct = not (isStructNode node) - - match node with - | CaretNode.Expr(tuple, path) -> (tryExprChanges sourceText toStruct tuple path).IsSome - | CaretNode.Pat(tuple, path) -> (tryPatChanges sourceText toStruct tuple path).IsSome - | CaretNode.Type _ -> true +let kind: StructKind = + { + IsExpr = + fun callsMethod expr path -> + match expr with + | SynExpr.Tuple _ -> not (isArgumentList callsMethod expr path) + | _ -> false + IsPat = + fun pat path -> + match pat with + | SynPat.Tuple _ -> not (isParameterList pat path) + | _ -> false + IsParameterList = isParameterList + IsType = + function + | SynType.Tuple _ -> true + | _ -> false + IsStruct = + function + | CaretNode.Expr(node = SynExpr.Tuple(isStruct = isStruct)) + | CaretNode.Pat(node = SynPat.Tuple(isStruct = isStruct)) + | CaretNode.Type(node = SynType.Tuple(isStruct = isStruct)) -> isStruct + | _ -> false + ExprChanges = tryExprChanges + PatChanges = tryPatChanges + TypeChanges = typeChanges + } diff --git a/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.cs.xlf b/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.cs.xlf index a83fb9d2ebb..3764e6148b7 100644 --- a/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.cs.xlf +++ b/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.cs.xlf @@ -84,6 +84,16 @@ Convert to struct tuple + + Convert to reference anonymous record + Convert to reference anonymous record + + + + Convert to struct anonymous record + Convert to struct anonymous record + + F# Disposable Values (locals) Uvolnitelné hodnoty jazyka F# (místní) diff --git a/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.de.xlf b/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.de.xlf index 0016a080fd2..2085c8de660 100644 --- a/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.de.xlf +++ b/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.de.xlf @@ -84,6 +84,16 @@ Convert to struct tuple + + Convert to reference anonymous record + Convert to reference anonymous record + + + + Convert to struct anonymous record + Convert to struct anonymous record + + F# Disposable Values (locals) Disposable-Werte in F# (lokal) diff --git a/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.es.xlf b/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.es.xlf index 9e83d397f24..43803a148a4 100644 --- a/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.es.xlf +++ b/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.es.xlf @@ -84,6 +84,16 @@ Convert to struct tuple + + Convert to reference anonymous record + Convert to reference anonymous record + + + + Convert to struct anonymous record + Convert to struct anonymous record + + F# Disposable Values (locals) Valores de F# descartables (locales) diff --git a/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.fr.xlf b/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.fr.xlf index 17a5b29806f..6ffe74e08fe 100644 --- a/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.fr.xlf +++ b/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.fr.xlf @@ -84,6 +84,16 @@ Convert to struct tuple + + Convert to reference anonymous record + Convert to reference anonymous record + + + + Convert to struct anonymous record + Convert to struct anonymous record + + F# Disposable Values (locals) Valeurs F# pouvant être supprimées (variables locales) diff --git a/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.it.xlf b/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.it.xlf index 791c6d39fc2..2d3e8da9203 100644 --- a/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.it.xlf +++ b/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.it.xlf @@ -84,6 +84,16 @@ Convert to struct tuple + + Convert to reference anonymous record + Convert to reference anonymous record + + + + Convert to struct anonymous record + Convert to struct anonymous record + + F# Disposable Values (locals) Valori eliminabili F# (variabili locali) diff --git a/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.ja.xlf b/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.ja.xlf index e004b3ef500..b15717ff7f4 100644 --- a/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.ja.xlf +++ b/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.ja.xlf @@ -84,6 +84,16 @@ Convert to struct tuple + + Convert to reference anonymous record + Convert to reference anonymous record + + + + Convert to struct anonymous record + Convert to struct anonymous record + + F# Disposable Values (locals) F# の破棄可能な値 (ローカル) diff --git a/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.ko.xlf b/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.ko.xlf index 4c0926e740e..4ab7de0b8c0 100644 --- a/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.ko.xlf +++ b/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.ko.xlf @@ -84,6 +84,16 @@ Convert to struct tuple + + Convert to reference anonymous record + Convert to reference anonymous record + + + + Convert to struct anonymous record + Convert to struct anonymous record + + F# Disposable Values (locals) F# 삭제 가능한 값(로컬) diff --git a/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.pl.xlf b/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.pl.xlf index 21474c0f861..20c27478257 100644 --- a/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.pl.xlf +++ b/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.pl.xlf @@ -84,6 +84,16 @@ Convert to struct tuple + + Convert to reference anonymous record + Convert to reference anonymous record + + + + Convert to struct anonymous record + Convert to struct anonymous record + + F# Disposable Values (locals) Wartości możliwe do likwidacji języka F# (lokalne) diff --git a/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.pt-BR.xlf b/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.pt-BR.xlf index 6bba340724e..c5b62af5420 100644 --- a/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.pt-BR.xlf +++ b/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.pt-BR.xlf @@ -84,6 +84,16 @@ Convert to struct tuple + + Convert to reference anonymous record + Convert to reference anonymous record + + + + Convert to struct anonymous record + Convert to struct anonymous record + + F# Disposable Values (locals) Valores F# Descartáveis (locais) diff --git a/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.ru.xlf b/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.ru.xlf index 02d11f34e46..e900c41beb2 100644 --- a/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.ru.xlf +++ b/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.ru.xlf @@ -84,6 +84,16 @@ Convert to struct tuple + + Convert to reference anonymous record + Convert to reference anonymous record + + + + Convert to struct anonymous record + Convert to struct anonymous record + + F# Disposable Values (locals) Освобождаемые значения F# (локальные) diff --git a/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.tr.xlf b/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.tr.xlf index 48ad6fa4e71..86d3f57e544 100644 --- a/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.tr.xlf +++ b/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.tr.xlf @@ -84,6 +84,16 @@ Convert to struct tuple + + Convert to reference anonymous record + Convert to reference anonymous record + + + + Convert to struct anonymous record + Convert to struct anonymous record + + F# Disposable Values (locals) F# Atılabilir Değerleri (yereller) diff --git a/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.zh-Hans.xlf b/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.zh-Hans.xlf index f9261b59be1..417c9ef4a6c 100644 --- a/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.zh-Hans.xlf +++ b/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.zh-Hans.xlf @@ -84,6 +84,16 @@ Convert to struct tuple + + Convert to reference anonymous record + Convert to reference anonymous record + + + + Convert to struct anonymous record + Convert to struct anonymous record + + F# Disposable Values (locals) F# 可释放值(局部值) diff --git a/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.zh-Hant.xlf b/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.zh-Hant.xlf index 3e6c14e883f..cc3fb80ca47 100644 --- a/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.zh-Hant.xlf +++ b/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.zh-Hant.xlf @@ -84,6 +84,16 @@ Convert to struct tuple + + Convert to reference anonymous record + Convert to reference anonymous record + + + + Convert to struct anonymous record + Convert to struct anonymous record + + F# Disposable Values (locals) F# 可處置的值 (區域) diff --git a/vsintegration/tests/FSharp.Editor.Tests/FSharp.Editor.Tests.fsproj b/vsintegration/tests/FSharp.Editor.Tests/FSharp.Editor.Tests.fsproj index 9d7bfd7618c..2e1a5ecdd20 100644 --- a/vsintegration/tests/FSharp.Editor.Tests/FSharp.Editor.Tests.fsproj +++ b/vsintegration/tests/FSharp.Editor.Tests/FSharp.Editor.Tests.fsproj @@ -81,6 +81,7 @@ + diff --git a/vsintegration/tests/FSharp.Editor.Tests/Refactors/ConvertAnonymousRecordTests.fs b/vsintegration/tests/FSharp.Editor.Tests/Refactors/ConvertAnonymousRecordTests.fs new file mode 100644 index 00000000000..51d31d4ac5a --- /dev/null +++ b/vsintegration/tests/FSharp.Editor.Tests/Refactors/ConvertAnonymousRecordTests.fs @@ -0,0 +1,421 @@ +module FSharp.Editor.Tests.Refactors.ConvertAnonymousRecordTests + +open Microsoft.VisualStudio.FSharp.Editor + +open Xunit + +open FSharp.Editor.Tests.Refactors.RefactorTestFramework + +let private refactored (body: string) (marker: string) = + refactoredBy (new FSharpConvertAnonymousRecordRefactoring()) body marker + +let private actionsAt (body: string) (marker: string) = + actionsBy (new FSharpConvertAnonymousRecordRefactoring()) body marker + +let private convertsBothWays (markers: string seq) (reference: string) (structs: string) = + convertsBothWaysBy (new FSharpConvertAnonymousRecordRefactoring()) markers reference structs + +[] +[] +[ = [] +""", + "A: int", + """ +let items: list = [] +""")>] +[] +let ``Anonymous record that flows nowhere else converts on its own`` (reference: string, marker: string, structs: string) = + convertsBothWays [ marker ] reference structs + +[] +let ``Value and the annotations it flows into convert together`` () = + let reference = + """ +let person = {| Name = "Ada"; Age = 36 |} +let copy: {| Name: string; Age: int |} = person +let age = person.Age +""" + + let structs = + """ +let person = struct {| Name = "Ada"; Age = 36 |} +let copy: struct {| Name: string; Age: int |} = person +let age = person.Age +""" + + convertsBothWays [ "Ada" ] reference structs + +[] +let ``Parameter annotation converts its arguments`` () = + let reference = + """ +let greet (p: {| Name: string |}) = "Hi " + p.Name + +let ada = {| Name = "Ada" |} +let greetings = [ greet ada; greet {| Name = "Bob" |} ] +""" + + let structs = + """ +let greet (p: struct {| Name: string |}) = "Hi " + p.Name + +let ada = struct {| Name = "Ada" |} +let greetings = [ greet ada; greet struct {| Name = "Bob" |} ] +""" + + convertsBothWays [ "Name: string" ] reference structs + +[] +let ``Return type converts the result and the values it is bound to`` () = + let reference = + """ +let origin () : {| X: int; Y: int |} = {| X = 0; Y = 0 |} +let start: {| X: int; Y: int |} = origin () +""" + + let structs = + """ +let origin () : struct {| X: int; Y: int |} = struct {| X = 0; Y = 0 |} +let start: struct {| X: int; Y: int |} = origin () +""" + + convertsBothWays [ "X: int" ] reference structs + +[] +let ``Record field converts its values and the annotations reading it`` () = + let reference = + """ +type Person = { Info: {| Age: int |}; Tags: {| Count: int |} } + +let person = { Info = {| Age = 30 |}; Tags = {| Count = 0 |} } +let info: {| Age: int |} = person.Info +""" + + let structs = + """ +type Person = { Info: struct {| Age: int |}; Tags: {| Count: int |} } + +let person = { Info = struct {| Age = 30 |}; Tags = {| Count = 0 |} } +let info: struct {| Age: int |} = person.Info +""" + + convertsBothWays [ "Age: int" ] reference structs + +[] +[] +[] +let ``Copy-and-update converts independently of its source`` (reference: string, marker: string, structs: string) = + convertsBothWays [ marker ] reference structs + +[] +let ``Value declared in another file converts there`` () = + let definition = + """ +module A + +let person = {| Name = "Ada" |} +""" + + let code = + """ +module B + +let name (p: {| Name: string |}) = p.Name +let text = name A.person +""" + + let struct (codeAfter, definitionAfter) = + refactoredAcrossFiles (new FSharpConvertAnonymousRecordRefactoring()) definition code "Name: string" + + Assert.Equal( + """ +module B + +let name (p: struct {| Name: string |}) = p.Name +let text = name A.person +""", + codeAfter + ) + + Assert.Equal( + """ +module A + +let person = struct {| Name = "Ada" |} +""", + definitionAfter + ) + +[] +let ``Title names the target kind`` () = + let reference = + """ +let point = {| X = 1 |} +""" + + let structs = + """ +let point = struct {| X = 1 |} +""" + + Assert.Equal("Convert to struct anonymous record", (actionsAt reference "X = 1" |> Seq.exactlyOne).Title) + Assert.Equal("Convert to reference anonymous record", (actionsAt structs "X = 1" |> Seq.exactlyOne).Title) + +[] +[] +[ {| A = 0 |} + +let copy: {| A: int |} = make () +""", + """ +let make () = + try struct {| A = 1 |} + with _ -> struct {| A = 0 |} + +let copy: struct {| A: int |} = make () +""")>] +let ``Result flowing out of try converts every branch of it`` (reference: string, structs: string) = + convertsBothWays [ "A: int" ] reference structs + +[] +[ p +let typed: {| A: int |} = copy +""", + """ +let person = struct {| A = 1 |} +let copy = match person with | p -> p +let typed: struct {| A: int |} = copy +""")>] +[] +[] +let ``Value converts through the names it is bound to again`` (reference: string, structs: string) = + convertsBothWays [ "A = 1"; "A: int" ] reference structs + +[] +[] +[] +[ p.Size +let total = size {| Size = 1 |} +""", + """ +let size = fun (p: struct {| Size: int |}) -> p.Size +let total = size struct {| Size = 1 |} +""")>] +[ {| Size = 1 |} +let copy: {| Size: int |} = make () +""", + """ +let make = fun () -> struct {| Size = 1 |} +let copy: struct {| Size: int |} = make () +""")>] +[] +[] +let ``Function in parentheses, bound as a lambda, aliased or partly applied converts with its calls`` (reference: string, structs: string) = + convertsBothWays [ "Size = 1"; "Size: int" ] reference structs + +[] +[] +[] +[] +let ``Member parameter converts with the arguments given for it by position or by name`` (reference: string, structs: string) = + convertsBothWays [ "Size = 1"; "Size: int" ] reference structs + +[] +let ``Generic parameter stops the conversion`` () = + let reference = + """ +let identity<'T> (x: 'T) = x +let a = identity {| A = 1 |} +let b = identity<{| B: int |}> {| B = 2 |} +""" + + let structs = + """ +let identity<'T> (x: 'T) = x +let a = identity struct {| A = 1 |} +let b = identity<{| B: int |}> {| B = 2 |} +""" + + convertsBothWays [ "A = 1" ] reference structs + +[] +let ``Generic field does not stop the conversion`` () = + let reference = + """ +let make value = {| Value = value |} +let a: {| Value: int |} = make 1 +let b: {| Value: string |} = make "s" +""" + + let structs = + """ +let make value = struct {| Value = value |} +let a: struct {| Value: int |} = make 1 +let b: struct {| Value: string |} = make "s" +""" + + convertsBothWays [ "Value = value"; "Value: int" ] reference structs + +[] +[{| A = 1 |}\n", "\nlet x = id<_> struct {| A = 1 |}\n")>] +[] +[] +let ``Struct keyword is separated from a name or type arguments the record follows`` (before: string, after: string) = + Assert.Equal(after, refactored before "A = 1") + +[] +[] +[] +[ +""", + "A = 1")>] +let ``No action`` (code: string, marker: string) = Assert.Empty(actionsAt code marker) diff --git a/vsintegration/tests/FSharp.Editor.Tests/Refactors/ConvertTupleTests.fs b/vsintegration/tests/FSharp.Editor.Tests/Refactors/ConvertTupleTests.fs index 263a09519ae..ad37b8777bd 100644 --- a/vsintegration/tests/FSharp.Editor.Tests/Refactors/ConvertTupleTests.fs +++ b/vsintegration/tests/FSharp.Editor.Tests/Refactors/ConvertTupleTests.fs @@ -13,9 +13,7 @@ let private actionsAt (body: string) (marker: string) = actionsBy (new FSharpConvertTupleRefactoring()) body marker let private convertsBothWays (markers: string seq) (reference: string) (structs: string) = - for marker in markers do - Assert.Equal(structs, refactored reference marker) - Assert.Equal(reference, refactored structs marker) + convertsBothWaysBy (new FSharpConvertTupleRefactoring()) markers reference structs [] [] +[] +[] +let ``Tuple of generic elements converts with the function it goes through`` (reference: string, useMarker: string, structs: string) = + convertsBothWays [ "a, b"; useMarker ] reference structs + [] let ``Comment between struct and its parenthesis is kept`` () = let code = diff --git a/vsintegration/tests/FSharp.Editor.Tests/Refactors/RefactorTestFramework.fs b/vsintegration/tests/FSharp.Editor.Tests/Refactors/RefactorTestFramework.fs index dd4ea3bcf99..9e646e49556 100644 --- a/vsintegration/tests/FSharp.Editor.Tests/Refactors/RefactorTestFramework.fs +++ b/vsintegration/tests/FSharp.Editor.Tests/Refactors/RefactorTestFramework.fs @@ -136,6 +136,11 @@ let refactoredBy (provider: 'T :> CodeRefactoringProvider) (body: string) (marke Assert.StartsWith(header, text, StringComparison.Ordinal) text.Substring header.Length +let convertsBothWaysBy (provider: 'T :> CodeRefactoringProvider) (markers: string seq) (reference: string) (structs: string) = + for marker in markers do + Assert.Equal(structs, refactoredBy provider reference marker) + Assert.Equal(reference, refactoredBy provider structs marker) + let actionsBy (provider: 'T :> CodeRefactoringProvider) (body: string) (marker: string) = let code = inModuleM body use context = TestContext.CreateWithCode code From 4cff45e662e647b6c55a22d49eb85b9141708105 Mon Sep 17 00:00:00 2001 From: XperiAndri Date: Sun, 8 Nov 2026 03:48:55 +0100 Subject: [PATCH 14/17] Cover as patterns and abbreviations in the anonymous record conversion The shared engine converts a record bound through `as` on both sides and withholds the conversion when the record passes an annotation that abbreviates an anonymous record, as it does for tuples. Co-Authored-By: Claude Sonnet 5.5 --- .../Refactors/ConvertAnonymousRecordTests.fs | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/vsintegration/tests/FSharp.Editor.Tests/Refactors/ConvertAnonymousRecordTests.fs b/vsintegration/tests/FSharp.Editor.Tests/Refactors/ConvertAnonymousRecordTests.fs index 51d31d4ac5a..a7b58a137d1 100644 --- a/vsintegration/tests/FSharp.Editor.Tests/Refactors/ConvertAnonymousRecordTests.fs +++ b/vsintegration/tests/FSharp.Editor.Tests/Refactors/ConvertAnonymousRecordTests.fs @@ -259,6 +259,14 @@ let typed: {| A: int |} = person let (person: struct {| A: int |}) = struct {| A = 1 |} let typed: struct {| A: int |} = person """)>] +[] let ``Value converts through the names it is bound to again`` (reference: string, structs: string) = convertsBothWays [ "A = 1"; "A: int" ] reference structs @@ -416,6 +424,11 @@ let point = { X = 1 } "X = 1")>] [ +""", + "A = 1")>] +[] let ``No action`` (code: string, marker: string) = Assert.Empty(actionsAt code marker) From ec9448b6f6976e35d652d97827d737e05980d3bf Mon Sep 17 00:00:00 2001 From: XperiAndri Date: Sun, 8 Nov 2026 03:53:40 +0100 Subject: [PATCH 15/17] Stop at a generic parameter reached through a function alias `let alias = identity` has no parameter list of its own, so the generic boundary missed its `'T` parameter and converting one call of the alias converted every other, unrelated call (FS0001). The parameter type now comes from the alias's function type when it has no parameter list. Co-Authored-By: Claude Sonnet 5.5 --- .../Refactor/StructPropagation.fs | 21 ++++++++++++-- .../Refactors/ConvertAnonymousRecordTests.fs | 28 ++++++++++++------- 2 files changed, 36 insertions(+), 13 deletions(-) diff --git a/vsintegration/src/FSharp.Editor/Refactor/StructPropagation.fs b/vsintegration/src/FSharp.Editor/Refactor/StructPropagation.fs index 7de6461d173..e828b2ffe1e 100644 --- a/vsintegration/src/FSharp.Editor/Refactor/StructPropagation.fs +++ b/vsintegration/src/FSharp.Editor/Refactor/StructPropagation.fs @@ -44,16 +44,31 @@ let private startsAt (position: pos) (ident: Ident) = let private endsAt (position: pos) (ident: Ident) = Position.posEq ident.idRange.End position -let private isGenericParameter (mfv: FSharpMemberOrFunctionOrValue) (group: int) (index: int voption) = - if group >= mfv.CurriedParameterGroups.Count then - false +let rec private skipArrows (groups: int) (ty: FSharpType) = + if groups > 0 && ty.IsFunctionType then + skipArrows (groups - 1) ty.GenericArguments[1] else + ty + +let private isGenericParameter (mfv: FSharpMemberOrFunctionOrValue) (group: int) (index: int voption) = + if group < mfv.CurriedParameterGroups.Count then let parameters = mfv.CurriedParameterGroups[group] match index with | ValueSome index when index < parameters.Count -> parameters[index].Type.IsGenericParameter | ValueSome _ -> false | ValueNone -> parameters.Count = 1 && parameters[0].Type.IsGenericParameter + else + match mfv.FullTypeSafe |> Option.map (skipArrows group) with + | Some ty when ty.IsFunctionType -> + let domain = ty.GenericArguments[0] + + match index with + | ValueSome index when domain.IsTupleType && index < domain.GenericArguments.Count -> + domain.GenericArguments[index].IsGenericParameter + | ValueSome _ -> false + | ValueNone -> domain.IsGenericParameter + | _ -> false let rec private tryPatternIdent (pat: SynPat) = match pat with diff --git a/vsintegration/tests/FSharp.Editor.Tests/Refactors/ConvertAnonymousRecordTests.fs b/vsintegration/tests/FSharp.Editor.Tests/Refactors/ConvertAnonymousRecordTests.fs index a7b58a137d1..085b8724cb1 100644 --- a/vsintegration/tests/FSharp.Editor.Tests/Refactors/ConvertAnonymousRecordTests.fs +++ b/vsintegration/tests/FSharp.Editor.Tests/Refactors/ConvertAnonymousRecordTests.fs @@ -368,22 +368,30 @@ let total = C().Grow(p = struct {| Size = 1 |}, by = 1) let ``Member parameter converts with the arguments given for it by position or by name`` (reference: string, structs: string) = convertsBothWays [ "Size = 1"; "Size: int" ] reference structs -[] -let ``Generic parameter stops the conversion`` () = - let reference = - """ +[] +[ (x: 'T) = x let a = identity {| A = 1 |} let b = identity<{| B: int |}> {| B = 2 |} -""" - - let structs = - """ +""", + """ let identity<'T> (x: 'T) = x let a = identity struct {| A = 1 |} let b = identity<{| B: int |}> {| B = 2 |} -""" - +""")>] +[ (x: 'T) = x +let alias = identity +let a = alias {| A = 1 |} +let b: {| B: int |} = alias {| B = 2 |} +""", + """ +let identity<'T> (x: 'T) = x +let alias = identity +let a = alias struct {| A = 1 |} +let b: {| B: int |} = alias {| B = 2 |} +""")>] +let ``Generic parameter stops the conversion`` (reference: string, structs: string) = convertsBothWays [ "A = 1" ] reference structs [] From 7ea81c952687d73f82badea98d1b4d615cc98eb6 Mon Sep 17 00:00:00 2001 From: XperiAndri Date: Sun, 8 Nov 2026 03:58:02 +0100 Subject: [PATCH 16/17] Follow the value assigned to a mutable through the assignment In `p <- q` the value of `q` flows into `p`. Converting either side missed the assignment and left the other with the old kind (FS0001): the conversion now follows the assignment from the variable to the assigned value and back. Co-Authored-By: Claude Sonnet 5.5 --- .../FSharp.Editor/Refactor/StructPropagation.fs | 17 ++++++++++++++++- .../Refactors/ConvertAnonymousRecordTests.fs | 10 ++++++++++ .../Refactors/ConvertTupleTests.fs | 12 ++++++++++++ 3 files changed, 38 insertions(+), 1 deletion(-) diff --git a/vsintegration/src/FSharp.Editor/Refactor/StructPropagation.fs b/vsintegration/src/FSharp.Editor/Refactor/StructPropagation.fs index e828b2ffe1e..7a52e901318 100644 --- a/vsintegration/src/FSharp.Editor/Refactor/StructPropagation.fs +++ b/vsintegration/src/FSharp.Editor/Refactor/StructPropagation.fs @@ -252,6 +252,16 @@ let private tryRecordFieldValue (tree: ParsedInput) (useRange: range) = | SyntaxNode.SynExpr(SynExpr.Record(recordFields = fields) as record) -> tryFieldValue path record fields | _ -> None) +let private tryAssignedValue (tree: ParsedInput) (useRange: range) = + (useRange.Start, tree) + ||> ParsedInput.tryPickLast (fun path node -> + match node with + | SyntaxNode.SynExpr(SynExpr.LongIdentSet(longDotId = SynLongIdent(id = ids); expr = value) as assignment) when + List.tryLast ids |> Option.exists (endsAt useRange.End) + -> + Some(value, SyntaxNode.SynExpr assignment :: path) + | _ -> None) + let private tryNamedBinding (tree: ParsedInput) (declaration: range) = (ValueNone, tree) ||> ParsedInput.fold (fun found path node -> @@ -561,6 +571,8 @@ type private Engine(solution: Solution, kind: StructKind, toStruct: bool, userOp | ValueSome(struct (name, group)), Some index -> this.EnqueueParameter source name group (ValueSome index) | _ -> () | SyntaxNode.SynExpr(SynExpr.Record(recordFields = fields)) :: _ -> this.FlowOutOfRecordField source node fields + | SyntaxNode.SynExpr(SynExpr.LongIdentSet(longDotId = SynLongIdent(id = ids); expr = value)) :: _ when isSame value node -> + List.tryLast ids |> Option.iter (this.EnqueueValue source) | SyntaxNode.SynExpr(SynExpr.Match(expr = scrutinee; clauses = clauses) as matchExpr) :: rest when isSame scrutinee node -> for SynMatchClause(pat = pat) as clause in clauses do this.IntoPattern source pat (SyntaxNode.SynMatchClause clause :: SyntaxNode.SynExpr matchExpr :: rest) @@ -701,7 +713,10 @@ type private Engine(solution: Solution, kind: StructKind, toStruct: bool, userOp } member this.FlowOutOfValueUse (useSource: Source) (useRange: range) = - match tryRecordFieldValue useSource.Tree useRange with + match + tryRecordFieldValue useSource.Tree useRange + |> Option.orElseWith (fun () -> tryAssignedValue useSource.Tree useRange) + with | Some(value, path) -> this.Retarget useSource value path | None -> tryUseNode useSource.Tree useRange diff --git a/vsintegration/tests/FSharp.Editor.Tests/Refactors/ConvertAnonymousRecordTests.fs b/vsintegration/tests/FSharp.Editor.Tests/Refactors/ConvertAnonymousRecordTests.fs index 085b8724cb1..b12f3e34d4a 100644 --- a/vsintegration/tests/FSharp.Editor.Tests/Refactors/ConvertAnonymousRecordTests.fs +++ b/vsintegration/tests/FSharp.Editor.Tests/Refactors/ConvertAnonymousRecordTests.fs @@ -267,6 +267,16 @@ let typed: {| A: int |} = alias let ((person: struct {| A: int |}) as alias) = struct {| A = 1 |} let typed: struct {| A: int |} = alias """)>] +[] let ``Value converts through the names it is bound to again`` (reference: string, structs: string) = convertsBothWays [ "A = 1"; "A: int" ] reference structs diff --git a/vsintegration/tests/FSharp.Editor.Tests/Refactors/ConvertTupleTests.fs b/vsintegration/tests/FSharp.Editor.Tests/Refactors/ConvertTupleTests.fs index ad37b8777bd..32afe5fb4d8 100644 --- a/vsintegration/tests/FSharp.Editor.Tests/Refactors/ConvertTupleTests.fs +++ b/vsintegration/tests/FSharp.Editor.Tests/Refactors/ConvertTupleTests.fs @@ -351,6 +351,18 @@ let (struct (c, d) as alias) = struct (1, 2) let struct (a, b) = alias """)>] [] +[ Date: Sun, 8 Nov 2026 04:01:49 +0100 Subject: [PATCH 17/17] Cover a multiline tuple reached from a parameter annotation Converting `p: int * int` reaches an unparenthesized tuple over several lines that cannot be rewritten in place. The action used to be offered and then change nothing; since the conversion runs before the action is offered, no action is offered. Co-Authored-By: Claude Sonnet 5.5 --- .../FSharp.Editor.Tests/Refactors/ConvertTupleTests.fs | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/vsintegration/tests/FSharp.Editor.Tests/Refactors/ConvertTupleTests.fs b/vsintegration/tests/FSharp.Editor.Tests/Refactors/ConvertTupleTests.fs index 32afe5fb4d8..d577cbe26e1 100644 --- a/vsintegration/tests/FSharp.Editor.Tests/Refactors/ConvertTupleTests.fs +++ b/vsintegration/tests/FSharp.Editor.Tests/Refactors/ConvertTupleTests.fs @@ -655,6 +655,14 @@ let pair = """, "1,")>] [] +[