Skip to content

Commit 77bccb8

Browse files
xperiandriclaude
andcommitted
Fix the five review findings on the snippet catalog and indentation
A RequireQualifiedAccess union rejects a bare case pattern (`A`, not `U.A`) - the generated pattern binds a fresh variable instead of testing the case, so it takes the first arm regardless of the actual value. matchRulesFor now qualifies with the entity's DisplayName when the union carries the attribute, the same way it already does for enums. ClassName() used the navigation item's LogicalName, which is qualified by every enclosing module ("Outer.C") - it does not resolve from a constructor sitting inside C's own scope. Strips to the name after the last '.'. GenerateMatchCases() resolved the lexer symbol nearest the field's end position, which is whatever identifier happens to sit there - for `f x`, that is `x`, not the call `f x`. Reads the type the checker captured for the field's whole span instead (TryGetCapturedType), so it matches the expression's own result type regardless of its shape. Surround With reindented every non-first selected line uniformly, including a line that is itself inside a multi-line string continued from an earlier selected line - inserting indentation there changes the string's value, not just its position. classifyLines now threads the lexer's color state across the span and classifies such a line as InsideString, left untouched like a blank line. lock.snippet closed the lambda on the same line as $selected$$end$, so a selection whose last line ends in a trailing // comment swallowed the closing paren into the comment, leaving the call unclosed. Moved onto its own line, matching how the other wrapping snippets already close. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
1 parent 547d18b commit 77bccb8

5 files changed

Lines changed: 135 additions & 64 deletions

File tree

‎vsintegration/Vsix/VisualFSharpFull/snippets/1033/FSharp/lock.snippet‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,8 @@
2020
</Literal>
2121
</Declarations>
2222
<Code Language="FSharp"><![CDATA[lock $lockObject$ (fun () ->
23-
$selected$$end$)]]></Code>
23+
$selected$$end$
24+
)]]></Code>
2425
</Snippet>
2526
</CodeSnippet>
2627
</CodeSnippets>

‎vsintegration/src/FSharp.Editor/Snippets/SnippetExpansionClient.fs‎

Lines changed: 52 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,8 @@ open Microsoft.VisualStudio.Text
1717
open Microsoft.VisualStudio.Text.Editor
1818
open Microsoft.VisualStudio.TextManager.Interop
1919

20+
open FSharp.Compiler.Tokenization
21+
2022
open MSXML
2123

2224
[<AutoOpen>]
@@ -44,10 +46,53 @@ module internal SnippetExpansionHelpers =
4446
String('\t', width / tabSize) + String(' ', width % tabSize)
4547

4648
/// Whether the line starts a directive wrapper, asking the snapshot for the one character that
47-
/// settles it before copying the line out to compare prefixes.
48-
let startsRootLevelDirective (line: ITextSnapshotLine) indent =
49+
/// settles it before falling back to comparing the already-fetched text against known prefixes.
50+
let startsRootLevelDirective (line: ITextSnapshotLine) indent (text: string) =
4951
line.Snapshot[line.Start.Position + indent] = '#'
50-
&& SnippetIndentation.isRootLevelDirective (line.GetText())
52+
&& SnippetIndentation.isRootLevelDirective text
53+
54+
/// Scans one line's text from `lexState`, threading the state a later line needs to know whether
55+
/// it opens inside an unfinished string.
56+
let rec private lexStateAfter (tokenizer: FSharpLineTokenizer) lexState =
57+
match tokenizer.ScanToken lexState with
58+
| None, atEndOfLine -> atEndOfLine
59+
| Some _, afterToken -> lexStateAfter tokenizer afterToken
60+
61+
/// The kind and indentation of every line `FormatSpan` was given, threading the lexer state
62+
/// across them so a `SelectedRest` line that opens inside a string - continuing one that started
63+
/// on an earlier selected line - is left alone rather than reindented into the string's value.
64+
let classifyLines (snapshot: ITextSnapshot) (span: VsTextSpan) selectedLines =
65+
let sourceTokenizer = FSharpSourceTokenizer([], None, None)
66+
let lastLine = min span.iEndLine (snapshot.LineCount - 1)
67+
let mutable lexState = FSharpTokenizerLexState.Initial
68+
69+
[
70+
for lineNumber in span.iStartLine .. lastLine ->
71+
let line = snapshot.GetLineFromLineNumber lineNumber
72+
let indent = leadingWhitespaceOf line
73+
let text = line.GetText()
74+
let enteringLexState = lexState
75+
76+
lexState <- lexStateAfter (sourceTokenizer.CreateLineTokenizer text) lexState
77+
78+
let kind =
79+
if indent = line.Length then
80+
SnippetIndentation.Blank
81+
elif SnippetIndentation.isInsideString (FSharpLineTokenizer.ColorStateOfLexState enteringLexState) then
82+
SnippetIndentation.InsideString
83+
elif startsRootLevelDirective line indent text then
84+
SnippetIndentation.RootLevelDirective
85+
else
86+
match selectedLines with
87+
| ValueSome(first, _) when lineNumber = first -> SnippetIndentation.SelectedFirst
88+
| ValueSome(first, last) when lineNumber > first && lineNumber <= last -> SnippetIndentation.SelectedRest
89+
| _ -> SnippetIndentation.Template
90+
91+
{
92+
SnippetIndentation.Kind = kind
93+
SnippetIndentation.Indent = indent
94+
}
95+
]
5196

5297
/// Where `$selected$` sits in a snippet's `<Code>`: which of its lines holds the field, and the
5398
/// column the template indents it to. That is the one nesting level a wrapper contributes, and the
@@ -307,7 +352,9 @@ type internal FSharpSnippetExpansionClient
307352
///
308353
/// - a root-level directive (`#if`, `#endif`) belongs at column 0 whatever it wraps;
309354
/// - text the engine substituted into `$selected$` already carries the indentation it had in
310-
/// the buffer, and needs only the nesting the template adds around the field;
355+
/// the buffer, and needs only the nesting the template adds around the field - except a
356+
/// line that opens inside a string continued from an earlier one, whose whitespace is the
357+
/// string's own value and is left untouched;
311358
/// - every other line is the snippet's own, and takes the column of the code it wraps -
312359
/// the caret's for Insert Snippet, the selection's for Surround With.
313360
member _.FormatSpan(_buffer, ts: VsTextSpan[]) =
@@ -329,31 +376,7 @@ type internal FSharpSnippetExpansionClient
329376
| ValueSome s -> SnippetIndentation.AroundSelection(s.Column, s.FieldIndent)
330377
| ValueNone -> SnippetIndentation.AtCaret span.iStartIndex
331378

332-
let lastLine = min span.iEndLine (snapshot.LineCount - 1)
333-
334-
let lines =
335-
[
336-
for lineNumber in span.iStartLine .. lastLine ->
337-
let line = snapshot.GetLineFromLineNumber lineNumber
338-
let indent = leadingWhitespaceOf line
339-
340-
let kind =
341-
if indent = line.Length then
342-
SnippetIndentation.Blank
343-
elif startsRootLevelDirective line indent then
344-
SnippetIndentation.RootLevelDirective
345-
else
346-
match selectedLines with
347-
| ValueSome(first, _) when lineNumber = first -> SnippetIndentation.SelectedFirst
348-
| ValueSome(first, last) when lineNumber > first && lineNumber <= last ->
349-
SnippetIndentation.SelectedRest
350-
| _ -> SnippetIndentation.Template
351-
352-
{
353-
SnippetIndentation.Kind = kind
354-
SnippetIndentation.Indent = indent
355-
}
356-
]
379+
let lines = classifyLines snapshot span selectedLines
357380

358381
use edit = subjectBuffer.CreateEdit()
359382

‎vsintegration/src/FSharp.Editor/Snippets/SnippetFunctions.fs‎

Lines changed: 38 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -111,7 +111,13 @@ module internal SnippetFunctionHelpers =
111111
| _ -> ValueSome declaration)
112112
ValueNone
113113

114-
return innermost |> ValueOption.map _.LogicalName
114+
// `LogicalName` is qualified by every enclosing module (`Outer.C`), which does not
115+
// resolve from a constructor sitting inside `C`'s own scope.
116+
return
117+
innermost
118+
|> ValueOption.map (fun declaration ->
119+
let name = declaration.LogicalName
120+
name.Substring(name.LastIndexOf('.') + 1))
115121
}
116122

117123
/// The type an expression evaluates to: for a call, what is left once its arguments are applied.
@@ -125,12 +131,20 @@ module internal SnippetFunctionHelpers =
125131
/// so no intermediate collection of rules is ever built.
126132
let private matchRulesFor (entity: FSharpEntity) =
127133
if entity.IsFSharpUnion then
134+
// A `[<RequireQualifiedAccess>]` union rejects a bare case pattern (`A`, not `U.A`) -
135+
// that reads as binding a fresh variable named `A`, not testing the case.
136+
let qualifier =
137+
if entity.HasAttribute<RequireQualifiedAccessAttribute>() then
138+
$"%s{entity.DisplayName}."
139+
else
140+
""
141+
128142
entity.UnionCases
129143
|> Seq.map (fun case ->
130144
if case.HasFields then
131-
$"| %s{case.Name} _ -> ()"
145+
$"| %s{qualifier}%s{case.Name} _ -> ()"
132146
else
133-
$"| %s{case.Name} -> ()")
147+
$"| %s{qualifier}%s{case.Name} -> ()")
134148
elif entity.IsEnum then
135149
seq {
136150
for field in entity.FSharpFields do
@@ -143,40 +157,33 @@ module internal SnippetFunctionHelpers =
143157
else
144158
Seq.empty
145159

146-
let private matchRulesForUse (symbolUse: FSharpSymbolUse) =
147-
match symbolUse.Symbol with
148-
| :? FSharpMemberOrFunctionOrValue as value ->
149-
let resultType = resultTypeOf value.FullType
150-
151-
if resultType.HasTypeDefinition then
152-
matchRulesFor resultType.TypeDefinition
153-
else
154-
Seq.empty
155-
| _ -> Seq.empty
156-
157-
/// The match rules covering the union or enum at `position`, or ValueNone for anything else.
158-
let tryGetMatchRules (document: Document) position =
160+
/// The match rules covering the union or enum `$expression$` evaluates to, or ValueNone for
161+
/// anything else. Reads the type the checker captured for the field's own span rather than the
162+
/// symbol nearest the caret: that resolves to whatever token sits there, which is the wrong type
163+
/// the moment `$expression$` is itself a call - `f x` would resolve the type of `x`, not of `f x`.
164+
let tryGetMatchRules (document: Document) (span: VsTextSpan) =
159165
cancellableTask {
160-
let! lexerSymbol = document.TryFindFSharpLexerSymbolAsync(position, SymbolLookupKind.Greedy, false, false, userOpName)
161166
let! _, checkResults = document.GetFSharpParseAndCheckResultsAsync userOpName
162167
let! ct = CancellableTask.getCancellationToken ()
163168
let! sourceText = document.GetTextAsync ct
164169

165-
let line = sourceText.Lines.GetLineFromPosition position
170+
let range =
171+
Range.mkRange
172+
document.FilePath
173+
(Position.mkPos (span.iStartLine + 1) span.iStartIndex)
174+
(Position.mkPos (span.iEndLine + 1) span.iEndIndex)
175+
176+
let position = sourceText.Lines[span.iEndLine].Start + span.iEndIndex
166177

167178
let rules =
168-
lexerSymbol
169-
|> ValueOption.ofOption
170-
|> ValueOption.bind (fun symbol ->
171-
checkResults.GetSymbolUseAtLocation(
172-
line.LineNumber + 1,
173-
symbol.Ident.idRange.EndColumn,
174-
line.ToString(),
175-
symbol.FullIsland
176-
)
177-
|> ValueOption.ofOption)
178-
|> ValueOption.map matchRulesForUse
179-
|> ValueOption.defaultValue Seq.empty
179+
checkResults.TryGetCapturedType range
180+
|> Option.map resultTypeOf
181+
|> Option.bind (fun resultType ->
182+
if resultType.HasTypeDefinition then
183+
Some(matchRulesFor resultType.TypeDefinition)
184+
else
185+
None)
186+
|> Option.defaultValue Seq.empty
180187

181188
return
182189
match String.Join(sourceText.LineBreakAt position, rules) with
@@ -263,9 +270,7 @@ type internal SnippetFunctionGenerateMatchCases(getSession, subjectBuffer: IText
263270
override this.TryGetValue() =
264271
match tryGetDocument subjectBuffer, matchedField |> ValueOption.bind (tryGetFieldSpan this.Session) with
265272
| ValueSome document, ValueSome span ->
266-
let position = positionOf subjectBuffer.CurrentSnapshot span.iEndLine span.iEndIndex
267-
268273
// Resolving the user's expression needs a check of the text they just typed, so there is
269274
// no cached answer to fall back on - only the literal's declared default.
270-
runSynchronously document.Project.FSharpTimeUntilStaleCompletion (tryGetMatchRules document position)
275+
runSynchronously document.Project.FSharpTimeUntilStaleCompletion (tryGetMatchRules document span)
271276
| _ -> ValueNone

‎vsintegration/src/FSharp.Editor/Snippets/SnippetIndentation.fs‎

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@ namespace Microsoft.VisualStudio.FSharp.Editor
44

55
open System
66

7+
open FSharp.Compiler.Tokenization
8+
79
/// Where the lines of an inserted snippet belong, as arithmetic over columns.
810
///
911
/// The expansion engine inserts a snippet verbatim: the opening line lands at the insertion column
@@ -25,6 +27,9 @@ module internal SnippetIndentation =
2527
| SelectedFirst
2628
/// A later line of that text. It starts its own buffer line at its original column.
2729
| SelectedRest
30+
/// A later line of that text which begins inside a string literal continued from an earlier
31+
/// selected line - its whitespace is part of the string's value, not its layout.
32+
| InsideString
2833
/// Whitespace only; left alone so the snippet does not leave trailing spaces behind.
2934
| Blank
3035

@@ -51,12 +56,21 @@ module internal SnippetIndentation =
5156
rootLevelDirectives
5257
|> Array.exists (fun directive -> text.StartsWith(directive, StringComparison.Ordinal))
5358

59+
/// Whether a line beginning in this lexer color state is a continuation of a string literal.
60+
let isInsideString (colorState: FSharpTokenizerColorState) =
61+
match colorState with
62+
| FSharpTokenizerColorState.String
63+
| FSharpTokenizerColorState.VerbatimString
64+
| FSharpTokenizerColorState.TripleQuoteString -> true
65+
| _ -> false
66+
5467
/// How far each line has to move. Positive inserts, negative removes, zero leaves it alone.
5568
let deltas placement (lines: Line list) =
5669
lines
5770
|> List.mapi (fun index line ->
5871
match line.Kind, placement with
59-
| Blank, _ -> 0
72+
| Blank, _
73+
| InsideString, _ -> 0
6074
| RootLevelDirective, _ -> -line.Indent
6175
| Template, AtCaret column -> if index = 0 then 0 else column
6276
| Template, AroundSelection(column, _) -> column

‎vsintegration/tests/FSharp.Editor.Tests/Snippets/SnippetIndentationTests.fs‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@ namespace FSharp.Editor.Tests
44

55
open Xunit
66

7+
open FSharp.Compiler.Tokenization
8+
79
open Microsoft.VisualStudio.FSharp.Editor.SnippetIndentation
810

911
/// Every case here is a real insertion that came out wrong at some point, recorded as the columns the
@@ -33,6 +35,9 @@ module SnippetIndentationTests =
3335
let private selectedRest indent =
3436
{ Kind = SelectedRest; Indent = indent }
3537

38+
let private insideString indent =
39+
{ Kind = InsideString; Indent = indent }
40+
3641
[<Fact>]
3742
let ``Surround With for over two lines nests both under the loop`` () =
3843
// fields = [
@@ -99,3 +104,26 @@ module SnippetIndentationTests =
99104
let lines = [ template 0; selectedFirst 16; selectedRest 16 ]
100105

101106
Assert.Equal<int list>([ 12; 16; 20 ], columnsAfter (AroundSelection(12, 4)) lines)
107+
108+
[<Fact>]
109+
let ``A line inside a string carried over from the selection is left alone`` () =
110+
// captured <- """a <- selectedFirst, untouched regardless of placement
111+
// b""" <- selectedRest, but "b\"\"\"" is the string's own content
112+
let lines = [ template 0; selectedFirst 0; insideString 0 ]
113+
114+
Assert.Equal<int list>([ 20; 0; 0 ], columnsAfter (AroundSelection(20, 4)) lines)
115+
116+
[<Theory>]
117+
[<InlineData(FSharpTokenizerColorState.String)>]
118+
[<InlineData(FSharpTokenizerColorState.VerbatimString)>]
119+
[<InlineData(FSharpTokenizerColorState.TripleQuoteString)>]
120+
let ``A string color state is recognized as a string continuation`` (state: FSharpTokenizerColorState) =
121+
Assert.True(isInsideString state)
122+
123+
[<Theory>]
124+
[<InlineData(FSharpTokenizerColorState.Token)>]
125+
[<InlineData(FSharpTokenizerColorState.Comment)>]
126+
[<InlineData(FSharpTokenizerColorState.SingleLineComment)>]
127+
[<InlineData(FSharpTokenizerColorState.IfDefSkip)>]
128+
[<InlineData(FSharpTokenizerColorState.InitialState)>]
129+
let ``A non-string color state is not`` (state: FSharpTokenizerColorState) = Assert.False(isInsideString state)

0 commit comments

Comments
 (0)