Skip to content

Commit 26a49b3

Browse files
authored
Reduce the range walked for formatting content validation (#12384)
Previously, this validation pass would walk over the whole content of the original and changed texts. This change modifies it instead to walk over the affected ranges in the original and changed texts based on the given set of changes.
1 parent f535589 commit 26a49b3

File tree

2 files changed

+27
-4
lines changed

2 files changed

+27
-4
lines changed

src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Extensions/SourceTextExtensions.cs

Lines changed: 26 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -60,8 +60,32 @@ public static string GetSubTextString(this SourceText text, TextSpan span)
6060
return new string(charBuffer, 0, span.Length);
6161
}
6262

63-
public static bool NonWhitespaceContentEquals(this SourceText text, SourceText other)
64-
=> NonWhitespaceContentEquals(text, other, 0, text.Length, 0, other.Length);
63+
public static bool NonWhitespaceContentEquals(this SourceText text, ImmutableArray<TextChange> changes)
64+
{
65+
if (changes.IsEmpty)
66+
{
67+
return true;
68+
}
69+
70+
// Determine the affected spans in the original and changed source texts
71+
var firstChangeSpan = changes[0].Span;
72+
var textStart = firstChangeSpan.Start;
73+
var textEnd = firstChangeSpan.End;
74+
75+
for (var i = 1; i < changes.Length; i++)
76+
{
77+
var changeSpan = changes[i].Span;
78+
79+
textStart = Math.Min(textStart, changeSpan.Start);
80+
textEnd = Math.Max(textEnd, changeSpan.End);
81+
}
82+
83+
var changedText = text.WithChanges(changes);
84+
var changedStart = textStart;
85+
var changedEnd = textEnd + (changedText.Length - text.Length);
86+
87+
return text.NonWhitespaceContentEquals(changedText, textStart, textEnd, changedStart, changedEnd);
88+
}
6589

6690
public static bool NonWhitespaceContentEquals(
6791
this SourceText text,

src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Formatting/Passes/FormattingContentValidationPass.cs

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,9 +23,8 @@ internal sealed class FormattingContentValidationPass(ILoggerFactory loggerFacto
2323
public Task<bool> IsValidAsync(FormattingContext context, ImmutableArray<TextChange> changes, CancellationToken cancellationToken)
2424
{
2525
var text = context.SourceText;
26-
var changedText = text.WithChanges(changes);
2726

28-
if (!text.NonWhitespaceContentEquals(changedText))
27+
if (!text.NonWhitespaceContentEquals(changes))
2928
{
3029
// Looks like we removed some non-whitespace content as part of formatting. Oops.
3130
// Discard this formatting result.

0 commit comments

Comments
 (0)