|
| 1 | +// Copyright (c) .NET Foundation. All rights reserved. |
| 2 | +// Licensed under the MIT license. See License.txt in the project root for license information. |
| 3 | + |
| 4 | +using System; |
| 5 | +using System.Collections.Generic; |
| 6 | +using System.Diagnostics; |
| 7 | +using System.Threading; |
| 8 | +using System.Threading.Tasks; |
| 9 | +using Microsoft.AspNetCore.Razor.Language; |
| 10 | +using Microsoft.AspNetCore.Razor.Language.Syntax; |
| 11 | +using Microsoft.AspNetCore.Razor.LanguageServer.Common; |
| 12 | +using Microsoft.AspNetCore.Razor.LanguageServer.EndpointContracts; |
| 13 | +using Microsoft.AspNetCore.Razor.LanguageServer.Extensions; |
| 14 | +using Microsoft.AspNetCore.Razor.LanguageServer.Protocol; |
| 15 | +using Microsoft.AspNetCore.Razor.PooledObjects; |
| 16 | +using Microsoft.CodeAnalysis.Razor.Workspaces; |
| 17 | +using Microsoft.CommonLanguageServerProtocol.Framework; |
| 18 | +using Microsoft.VisualStudio.LanguageServer.Protocol; |
| 19 | + |
| 20 | +namespace Microsoft.AspNetCore.Razor.LanguageServer.SpellCheck; |
| 21 | + |
| 22 | +[LanguageServerEndpoint(VSInternalMethods.TextDocumentSpellCheckableRangesName)] |
| 23 | +internal sealed class DocumentSpellCheckEndpoint : IRazorRequestHandler<VSInternalDocumentSpellCheckableParams, VSInternalSpellCheckableRangeReport[]>, IRegistrationExtension |
| 24 | +{ |
| 25 | + private readonly IRazorDocumentMappingService _documentMappingService; |
| 26 | + private readonly LanguageServerFeatureOptions _languageServerFeatureOptions; |
| 27 | + private readonly ClientNotifierServiceBase _languageServer; |
| 28 | + |
| 29 | + public DocumentSpellCheckEndpoint( |
| 30 | + IRazorDocumentMappingService documentMappingService, |
| 31 | + LanguageServerFeatureOptions languageServerFeatureOptions, |
| 32 | + ClientNotifierServiceBase languageServer) |
| 33 | + { |
| 34 | + _documentMappingService = documentMappingService ?? throw new ArgumentNullException(nameof(documentMappingService)); |
| 35 | + _languageServerFeatureOptions = languageServerFeatureOptions ?? throw new ArgumentNullException(nameof(languageServerFeatureOptions)); |
| 36 | + _languageServer = languageServer ?? throw new ArgumentNullException(nameof(languageServer)); |
| 37 | + } |
| 38 | + |
| 39 | + public bool MutatesSolutionState => false; |
| 40 | + |
| 41 | + public RegistrationExtensionResult GetRegistration(VSInternalClientCapabilities clientCapabilities) |
| 42 | + { |
| 43 | + const string ServerCapability = "_vs_spellCheckingProvider"; |
| 44 | + |
| 45 | + return new RegistrationExtensionResult(ServerCapability, true); |
| 46 | + } |
| 47 | + |
| 48 | + public TextDocumentIdentifier GetTextDocumentIdentifier(VSInternalDocumentSpellCheckableParams request) |
| 49 | + { |
| 50 | + if (request.TextDocument is null) |
| 51 | + { |
| 52 | + throw new ArgumentNullException(nameof(request.TextDocument)); |
| 53 | + } |
| 54 | + |
| 55 | + return request.TextDocument; |
| 56 | + } |
| 57 | + |
| 58 | + public async Task<VSInternalSpellCheckableRangeReport[]> HandleRequestAsync(VSInternalDocumentSpellCheckableParams request, RazorRequestContext requestContext, CancellationToken cancellationToken) |
| 59 | + { |
| 60 | + var documentContext = requestContext.GetRequiredDocumentContext(); |
| 61 | + |
| 62 | + using var _ = ListPool<SpellCheckRange>.GetPooledObject(out var ranges); |
| 63 | + |
| 64 | + await AddRazorSpellCheckRangesAsync(ranges, documentContext, cancellationToken).ConfigureAwait(false); |
| 65 | + |
| 66 | + if (_languageServerFeatureOptions.SingleServerSupport) |
| 67 | + { |
| 68 | + await AddCSharpSpellCheckRangesAsync(ranges, documentContext, cancellationToken).ConfigureAwait(false); |
| 69 | + } |
| 70 | + |
| 71 | + return new[] |
| 72 | + { |
| 73 | + new VSInternalSpellCheckableRangeReport |
| 74 | + { |
| 75 | + Ranges = ConvertSpellCheckRangesToIntTriples(ranges), |
| 76 | + ResultId = Guid.NewGuid().ToString() |
| 77 | + } |
| 78 | + }; |
| 79 | + } |
| 80 | + |
| 81 | + private static async Task AddRazorSpellCheckRangesAsync(List<SpellCheckRange> ranges, VersionedDocumentContext documentContext, CancellationToken cancellationToken) |
| 82 | + { |
| 83 | + var tree = await documentContext.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); |
| 84 | + |
| 85 | + // We don't want to report spelling errors in script or style tags, so we avoid descending into them at all, which |
| 86 | + // means we don't need complicated logic, and it performs a bit better. We assume any C# in them will still be reported |
| 87 | + // by Roslyn. |
| 88 | + // In an ideal world we wouldn't need this logic at all, as we would defer to the Html LSP server to provide spell checking |
| 89 | + // but it doesn't currently support it. When that support is added, we can remove all of this but the RazorCommentBlockSyntax |
| 90 | + // handling. |
| 91 | + foreach (var node in tree.Root.DescendantNodes(n => n is not MarkupElementSyntax { StartTag.Name.Content: "script" or "style" })) |
| 92 | + { |
| 93 | + if (node is RazorCommentBlockSyntax commentBlockSyntax) |
| 94 | + { |
| 95 | + ranges.Add(new((int)VSInternalSpellCheckableRangeKind.Comment, commentBlockSyntax.Comment.SpanStart, commentBlockSyntax.Comment.Span.Length)); |
| 96 | + } |
| 97 | + else if (node is MarkupTextLiteralSyntax textLiteralSyntax) |
| 98 | + { |
| 99 | + // Attribute names are text literals, but we don't want to spell check them because either C# will, |
| 100 | + // whether they're component attributes based on property names, or they come from tag helper attribute |
| 101 | + // parameters as strings, or they're Html attributes which are not necessarily expected to be real words. |
| 102 | + if (node.Parent is MarkupTagHelperAttributeSyntax or MarkupAttributeBlockSyntax) |
| 103 | + { |
| 104 | + continue; |
| 105 | + } |
| 106 | + |
| 107 | + // Text literals appear everywhere in Razor to hold newlines and indentation, so its worth saving the tokens |
| 108 | + if (textLiteralSyntax.ContainsOnlyWhitespace()) |
| 109 | + { |
| 110 | + continue; |
| 111 | + } |
| 112 | + |
| 113 | + ranges.Add(new((int)VSInternalSpellCheckableRangeKind.String, textLiteralSyntax.SpanStart, textLiteralSyntax.Span.Length)); |
| 114 | + } |
| 115 | + } |
| 116 | + } |
| 117 | + |
| 118 | + private async Task AddCSharpSpellCheckRangesAsync(List<SpellCheckRange> ranges, VersionedDocumentContext documentContext, CancellationToken cancellationToken) |
| 119 | + { |
| 120 | + var delegatedParams = new DelegatedSpellCheckParams(documentContext.Identifier); |
| 121 | + var delegatedResponse = await _languageServer.SendRequestAsync<DelegatedSpellCheckParams, VSInternalSpellCheckableRangeReport[]?>( |
| 122 | + RazorLanguageServerCustomMessageTargets.RazorSpellCheckEndpoint, |
| 123 | + delegatedParams, |
| 124 | + cancellationToken).ConfigureAwait(false); |
| 125 | + |
| 126 | + if (delegatedResponse is null) |
| 127 | + { |
| 128 | + return; |
| 129 | + } |
| 130 | + |
| 131 | + var codeDocument = await documentContext.GetCodeDocumentAsync(cancellationToken).ConfigureAwait(false); |
| 132 | + var csharpDocument = codeDocument.GetCSharpDocument(); |
| 133 | + |
| 134 | + foreach (var report in delegatedResponse) |
| 135 | + { |
| 136 | + if (report.Ranges is not { } csharpRanges) |
| 137 | + { |
| 138 | + continue; |
| 139 | + } |
| 140 | + |
| 141 | + // Since we get C# tokens that have relative starts, we need to convert them back to absolute indexes |
| 142 | + // so we can sort them with the Razor tokens later |
| 143 | + var absoluteCSharpStartIndex = 0; |
| 144 | + for (var i = 0; i < csharpRanges.Length; i += 3) |
| 145 | + { |
| 146 | + var kind = csharpRanges[i]; |
| 147 | + var start = csharpRanges[i + 1]; |
| 148 | + var length = csharpRanges[i + 2]; |
| 149 | + |
| 150 | + absoluteCSharpStartIndex += start; |
| 151 | + |
| 152 | + // We need to map the start index to produce results, and we validate that we can map the end index so we don't have |
| 153 | + // squiggles that go from C# into Razor/Html. |
| 154 | + if (_documentMappingService.TryMapToHostDocumentPosition(csharpDocument, absoluteCSharpStartIndex, out var _1, out var hostDocumentIndex) && |
| 155 | + _documentMappingService.TryMapToHostDocumentPosition(csharpDocument, absoluteCSharpStartIndex + length, out var _2, out var _3)) |
| 156 | + { |
| 157 | + ranges.Add(new(kind, hostDocumentIndex, length)); |
| 158 | + } |
| 159 | + |
| 160 | + absoluteCSharpStartIndex += length; |
| 161 | + } |
| 162 | + } |
| 163 | + } |
| 164 | + |
| 165 | + private static int[] ConvertSpellCheckRangesToIntTriples(List<SpellCheckRange> ranges) |
| 166 | + { |
| 167 | + // Important to sort first, or the client will just ignore anything we say |
| 168 | + ranges.Sort(AbsoluteStartIndexComparer.Instance); |
| 169 | + |
| 170 | + using var _ = ListPool<int>.GetPooledObject(out var data); |
| 171 | + data.SetCapacityIfLarger(ranges.Count * 3); |
| 172 | + |
| 173 | + var lastAbsoluteEndIndex = 0; |
| 174 | + foreach (var range in ranges) |
| 175 | + { |
| 176 | + if (range.Length == 0) |
| 177 | + { |
| 178 | + continue; |
| 179 | + } |
| 180 | + |
| 181 | + data.Add(range.Kind); |
| 182 | + data.Add(range.AbsoluteStartIndex - lastAbsoluteEndIndex); |
| 183 | + data.Add(range.Length); |
| 184 | + |
| 185 | + lastAbsoluteEndIndex = range.AbsoluteStartIndex + range.Length; |
| 186 | + } |
| 187 | + |
| 188 | + return data.ToArray(); |
| 189 | + } |
| 190 | + |
| 191 | + private sealed record SpellCheckRange(int Kind, int AbsoluteStartIndex, int Length); |
| 192 | + |
| 193 | + private sealed class AbsoluteStartIndexComparer : IComparer<SpellCheckRange> |
| 194 | + { |
| 195 | + public static readonly AbsoluteStartIndexComparer Instance = new(); |
| 196 | + |
| 197 | + public int Compare(SpellCheckRange? x, SpellCheckRange? y) |
| 198 | + { |
| 199 | + if (x is null || y is null) |
| 200 | + { |
| 201 | + Debug.Fail("There shouldn't be a null in the list of spell check ranges."); |
| 202 | + |
| 203 | + return 0; |
| 204 | + } |
| 205 | + |
| 206 | + return x.AbsoluteStartIndex.CompareTo(y.AbsoluteStartIndex); |
| 207 | + } |
| 208 | + } |
| 209 | +} |
0 commit comments