Skip to content

Commit

Permalink
Re-architect formatting to prepare for cohosting (and for fun!) (#10778)
Browse files Browse the repository at this point in the history
I nerd sniped myself thinking about how to get formatting into
cohosting, given the limitations Alex ran into doing the relayering for
auto insert, and this is the result. I was going to go further and port
the actual formatting endpoint to cohosting, but that would have ran
into the same issue that Alex did with auto insert, so I figured I'd
wait for that to merge, and put this up in the meantime.

This unblocks the formatting, code action and completion end points from
being ported.
Part of #10743
Part of #9519

I **strongly** recommend reviewing commit-at-a-time, as I did this
deliberately in an order, and in order to (hopefully) make reviewing
easier. Though granted, there are a lot of commits.
  • Loading branch information
davidwengier authored Aug 30, 2024
2 parents e1f6fba + ee83a6b commit 21c7674
Show file tree
Hide file tree
Showing 59 changed files with 1,171 additions and 1,458 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -110,15 +110,9 @@ void Method() { }
[Benchmark(Description = "Formatting")]
public async Task RazorCSharpFormattingAsync()
{
var options = new FormattingOptions()
{
TabSize = 4,
InsertSpaces = true
};

var documentContext = new DocumentContext(DocumentUri, DocumentSnapshot, projectContext: null);

var edits = await RazorFormattingService.FormatAsync(documentContext, range: null, options, CancellationToken.None);
var edits = await RazorFormattingService.GetDocumentFormattingEditsAsync(documentContext, htmlEdits: [], range: null, RazorFormattingOptions.Default, CancellationToken.None);

#if DEBUG
// For debugging purposes only.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
using System;
using System.Collections.Frozen;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
Expand Down Expand Up @@ -185,19 +185,21 @@ public void ApplyCapabilities(VSInternalServerCapabilities serverCapabilities, V
}

// For C# we run the edit through our formatting engine
var edits = new[] { delegatedResponse.TextEdit };
Debug.Assert(positionInfo.LanguageKind == RazorLanguageKind.CSharp);

var mappedEdits = delegatedResponse.TextEditFormat == InsertTextFormat.Snippet
? await _razorFormattingService.FormatSnippetAsync(documentContext, positionInfo.LanguageKind, edits, originalRequest.Options, cancellationToken).ConfigureAwait(false)
: await _razorFormattingService.FormatOnTypeAsync(documentContext, positionInfo.LanguageKind, edits, originalRequest.Options, hostDocumentIndex: 0, triggerCharacter: '\0', cancellationToken).ConfigureAwait(false);
if (mappedEdits is not [{ } edit])
var options = RazorFormattingOptions.From(originalRequest.Options, _optionsMonitor.CurrentValue.CodeBlockBraceOnNextLine);

var mappedEdit = delegatedResponse.TextEditFormat == InsertTextFormat.Snippet
? await _razorFormattingService.GetCSharpSnippetFormattingEditAsync(documentContext, [delegatedResponse.TextEdit], options, cancellationToken).ConfigureAwait(false)
: await _razorFormattingService.GetSingleCSharpEditAsync(documentContext, delegatedResponse.TextEdit, options, cancellationToken).ConfigureAwait(false);
if (mappedEdit is null)
{
return null;
}

return new VSInternalDocumentOnAutoInsertResponseItem()
{
TextEdit = edit,
TextEdit = mappedEdit,
TextEditFormat = delegatedResponse.TextEditFormat,
};
}
Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -22,21 +22,6 @@ internal sealed class DefaultCSharpCodeActionResolver(
IClientConnection clientConnection,
IRazorFormattingService razorFormattingService) : CSharpCodeActionResolver(clientConnection)
{
// Usually when we need to format code, we utilize the formatting options provided
// by the platform. However, we aren't provided such options in the case of code actions
// so we use a default (and commonly used) configuration.
private static readonly FormattingOptions s_defaultFormattingOptions = new FormattingOptions()
{
TabSize = 4,
InsertSpaces = true,
OtherOptions = new Dictionary<string, object>
{
{ "trimTrailingWhitespace", true },
{ "insertFinalNewline", true },
{ "trimFinalNewlines", true },
},
};

private readonly IDocumentContextFactory _documentContextFactory = documentContextFactory;
private readonly IRazorFormattingService _razorFormattingService = razorFormattingService;

Expand Down Expand Up @@ -80,11 +65,10 @@ public async override Task<CodeAction> ResolveAsync(

// Remaps the text edits from the generated C# to the razor file,
// as well as applying appropriate formatting.
var formattedEdits = await _razorFormattingService.FormatCodeActionAsync(
var formattedEdit = await _razorFormattingService.GetCSharpCodeActionEditAsync(
documentContext,
RazorLanguageKind.CSharp,
csharpTextEdits,
s_defaultFormattingOptions,
RazorFormattingOptions.Default,
cancellationToken).ConfigureAwait(false);

cancellationToken.ThrowIfCancellationRequested();
Expand All @@ -99,7 +83,7 @@ public async override Task<CodeAction> ResolveAsync(
new TextDocumentEdit()
{
TextDocument = codeDocumentIdentifier,
Edits = formattedEdits,
Edits = formattedEdit is null ? [] : [formattedEdit],
}
}
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
using Microsoft.AspNetCore.Razor.PooledObjects;
using Microsoft.AspNetCore.Razor.Threading;
using Microsoft.CodeAnalysis.ExternalAccess.Razor;
using Microsoft.CodeAnalysis.Razor.Formatting;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.LanguageServer.Protocol;

Expand Down Expand Up @@ -138,7 +139,7 @@ private static ImmutableArray<RazorVSInternalCodeAction> ProcessCodeActionsVSCod
var fqnCodeAction = CreateFQNCodeAction(context, diagnostic, codeAction, fqn);
typeAccessibilityCodeActions.Add(fqnCodeAction);

if (AddUsingsCodeActionProviderHelper.TryCreateAddUsingResolutionParams(fqn, context.Request.TextDocument.Uri, additionalEdit: null, out var @namespace, out var resolutionParams))
if (AddUsingsCodeActionResolver.TryCreateAddUsingResolutionParams(fqn, context.Request.TextDocument.Uri, additionalEdit: null, out var @namespace, out var resolutionParams))
{
var addUsingCodeAction = RazorCodeActionFactory.CreateAddComponentUsing(@namespace, newTagName: null, resolutionParams);
typeAccessibilityCodeActions.Add(addUsingCodeAction);
Expand Down Expand Up @@ -191,7 +192,7 @@ private static ImmutableArray<RazorVSInternalCodeAction> ProcessCodeActionsVS(
// For add using suggestions, the code action title is of the form:
// `using System.Net;`
else if (codeAction.Name is not null && codeAction.Name.Equals(RazorPredefinedCodeFixProviderNames.AddImport, StringComparison.Ordinal) &&
AddUsingsCodeActionProviderHelper.TryExtractNamespace(codeAction.Title, out var @namespace, out var prefix))
AddUsingsHelper.TryExtractNamespace(codeAction.Title, out var @namespace, out var prefix))
{
codeAction.Title = $"{prefix}@using {@namespace}";
typeAccessibilityCodeActions.Add(codeAction.WrapResolvableCodeAction(context, LanguageServerConstants.CodeActions.Default));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ public static async Task RemapAndFixHtmlCodeActionEditAsync(IEditMappingService

foreach (var edit in documentEdits)
{
edit.Edits = HtmlFormatter.FixHtmlTestEdits(htmlSourceText, edit.Edits);
edit.Edits = HtmlFormatter.FixHtmlTextEdits(htmlSourceText, edit.Edits);
}

codeAction.Edit = new WorkspaceEdit
Expand Down
Loading

0 comments on commit 21c7674

Please sign in to comment.