From c2894e201ba6287902689c9add80f6d3768640e2 Mon Sep 17 00:00:00 2001 From: David Wengier Date: Fri, 21 Jun 2024 17:13:04 +1000 Subject: [PATCH 01/16] Add a numeric version to document snapshot, and increment it automatically --- .../ProjectSystem/DocumentSnapshot.cs | 2 ++ .../ProjectSystem/DocumentState.cs | 31 ++++++++++++++----- .../ProjectSystem/IDocumentSnapshot.cs | 2 ++ .../ProjectSystem/ImportDocumentSnapshot.cs | 2 ++ .../ProjectSystem/ProjectState.cs | 2 +- .../ProjectSystem/RemoteDocumentSnapshot.cs | 2 ++ 6 files changed, 33 insertions(+), 8 deletions(-) diff --git a/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/ProjectSystem/DocumentSnapshot.cs b/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/ProjectSystem/DocumentSnapshot.cs index e43ca72a06c..fb46ddb484f 100644 --- a/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/ProjectSystem/DocumentSnapshot.cs +++ b/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/ProjectSystem/DocumentSnapshot.cs @@ -17,6 +17,8 @@ internal class DocumentSnapshot : IDocumentSnapshot public IProjectSnapshot Project => ProjectInternal; public bool SupportsOutput => true; + public int Version => State.Version; + public ProjectSnapshot ProjectInternal { get; } public DocumentState State { get; } diff --git a/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/ProjectSystem/DocumentState.cs b/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/ProjectSystem/DocumentState.cs index 859673968b2..64385538afa 100644 --- a/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/ProjectSystem/DocumentState.cs +++ b/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/ProjectSystem/DocumentState.cs @@ -28,9 +28,11 @@ internal partial class DocumentState private Task? _loaderTask; private SourceText? _sourceText; private VersionStamp? _version; + private readonly int _numericVersion; public static DocumentState Create( HostDocument hostDocument, + int numericVersion, Func>? loader) { if (hostDocument is null) @@ -38,7 +40,19 @@ public static DocumentState Create( throw new ArgumentNullException(nameof(hostDocument)); } - return new DocumentState(hostDocument, null, null, loader); + return new DocumentState(hostDocument, null, null, numericVersion, loader); + } + + public static DocumentState Create( + HostDocument hostDocument, + Func>? loader) + { + if (hostDocument is null) + { + throw new ArgumentNullException(nameof(hostDocument)); + } + + return new DocumentState(hostDocument, null, null, 1, loader); } // Internal for testing @@ -46,16 +60,19 @@ internal DocumentState( HostDocument hostDocument, SourceText? text, VersionStamp? version, + int numericVersion, Func>? loader) { HostDocument = hostDocument; _sourceText = text; _version = version; + _numericVersion = numericVersion; _loader = loader ?? EmptyLoader; _lock = new object(); } public HostDocument HostDocument { get; } + public int Version => _numericVersion; public bool IsGeneratedOutputResultAvailable => ComputedState.IsResultAvailable == true; @@ -152,12 +169,12 @@ public bool TryGetTextVersion(out VersionStamp result) public virtual DocumentState WithConfigurationChange() { - var state = new DocumentState(HostDocument, _sourceText, _version, _loader) + var state = new DocumentState(HostDocument, _sourceText, _version, _numericVersion + 1, _loader) { // The source could not have possibly changed. _sourceText = _sourceText, _version = _version, - _loaderTask = _loaderTask + _loaderTask = _loaderTask, }; // Do not cache computed state @@ -167,7 +184,7 @@ public virtual DocumentState WithConfigurationChange() public virtual DocumentState WithImportsChange() { - var state = new DocumentState(HostDocument, _sourceText, _version, _loader) + var state = new DocumentState(HostDocument, _sourceText, _version, _numericVersion + 1, _loader) { // The source could not have possibly changed. _sourceText = _sourceText, @@ -183,7 +200,7 @@ public virtual DocumentState WithImportsChange() public virtual DocumentState WithProjectWorkspaceStateChange() { - var state = new DocumentState(HostDocument, _sourceText, _version, _loader) + var state = new DocumentState(HostDocument, _sourceText, _version, _numericVersion + 1, _loader) { // The source could not have possibly changed. _sourceText = _sourceText, @@ -206,7 +223,7 @@ public virtual DocumentState WithText(SourceText sourceText, VersionStamp versio // Do not cache the computed state - return new DocumentState(HostDocument, sourceText, version, null); + return new DocumentState(HostDocument, sourceText, version, _numericVersion + 1, null); } public virtual DocumentState WithTextLoader(Func> loader) @@ -218,7 +235,7 @@ public virtual DocumentState WithTextLoader(Func> loader) // Do not cache the computed state - return new DocumentState(HostDocument, null, null, loader); + return new DocumentState(HostDocument, null, null, _numericVersion + 1, loader); } // Internal, because we are temporarily sharing code with CohostDocumentSnapshot diff --git a/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/ProjectSystem/IDocumentSnapshot.cs b/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/ProjectSystem/IDocumentSnapshot.cs index c1306beee09..460cfac55d5 100644 --- a/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/ProjectSystem/IDocumentSnapshot.cs +++ b/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/ProjectSystem/IDocumentSnapshot.cs @@ -16,6 +16,8 @@ internal interface IDocumentSnapshot IProjectSnapshot Project { get; } bool SupportsOutput { get; } + int Version { get; } + Task GetTextAsync(); Task GetTextVersionAsync(); Task GetGeneratedOutputAsync(); diff --git a/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/ProjectSystem/ImportDocumentSnapshot.cs b/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/ProjectSystem/ImportDocumentSnapshot.cs index 68f7b345d16..2cc8f3cba02 100644 --- a/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/ProjectSystem/ImportDocumentSnapshot.cs +++ b/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/ProjectSystem/ImportDocumentSnapshot.cs @@ -32,6 +32,8 @@ public ImportDocumentSnapshot(IProjectSnapshot project, RazorProjectItem item) _version = VersionStamp.Default; } + public int Version => 1; + public Task GetGeneratedOutputAsync() => throw new NotSupportedException(); diff --git a/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/ProjectSystem/ProjectState.cs b/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/ProjectSystem/ProjectState.cs index e8db1a11848..b51e3bbd285 100644 --- a/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/ProjectSystem/ProjectState.cs +++ b/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/ProjectSystem/ProjectState.cs @@ -243,7 +243,7 @@ public ProjectState WithAddedHostDocument(HostDocument hostDocument, Func true; + public int Version => throw new NotImplementedException("We don't expect to use this in cohosting because we do not control generated document creation."); + public Task GetTextAsync() => _textDocument.GetTextAsync(); public Task GetTextVersionAsync() => _textDocument.GetTextVersionAsync(); From 546a349bcd0123b94d40020b0392b98bf67e5dc3 Mon Sep 17 00:00:00 2001 From: David Wengier Date: Fri, 21 Jun 2024 17:13:28 +1000 Subject: [PATCH 02/16] Remove document version cache --- .../RazorSemanticTokensBenchmark.cs | 9 - ...zorSemanticTokensRangeEndpointBenchmark.cs | 8 - .../RazorSemanticTokensScrollingBenchmark.cs | 7 - .../DocumentContextFactory.cs | 11 +- .../DocumentVersionCache.DocumentEntry.cs | 17 - .../DocumentVersionCache.TestAccessor.cs | 57 ---- .../DocumentVersionCache.cs | 179 ---------- .../IServiceCollectionExtensions.cs | 3 - .../Formatting/HtmlFormatter.cs | 20 +- .../Formatting/HtmlFormattingPass.cs | 3 +- .../GeneratedDocumentSynchronizer.cs | 12 +- .../IDocumentVersionCache.cs | 16 - .../ProjectSystem/RazorProjectService.cs | 35 -- .../Endpoints/RazorCustomMessageTarget.cs | 16 + ...RazorCustomMessageTarget_SemanticTokens.cs | 6 +- ...rCustomMessageTarget_UpdateCSharpBuffer.cs | 13 +- .../CodeActionEndToEndTest.NetFx.cs | 2 +- .../DocumentContextFactoryTest.cs | 15 +- ...extDocumentUriPresentationEndpointTests.cs | 16 +- .../DocumentVersionCacheTest.cs | 322 ------------------ .../Formatting_NetFx/FormattingTestBase.cs | 5 +- .../TestRazorFormattingService.cs | 8 +- .../GeneratedDocumentSynchronizerTest.cs | 9 +- .../RazorComponentSearchEngineTest.cs | 3 - .../RazorProjectServiceTest.cs | 11 +- .../Refactoring/RenameEndpointTest.cs | 4 +- .../TestRazorProjectService.cs | 2 - .../ProjectSystem/TestDocumentSnapshot.cs | 2 + .../ProjectSystem/ProjectStateTest.cs | 2 +- 29 files changed, 64 insertions(+), 749 deletions(-) delete mode 100644 src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/DocumentVersionCache.DocumentEntry.cs delete mode 100644 src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/DocumentVersionCache.TestAccessor.cs delete mode 100644 src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/DocumentVersionCache.cs delete mode 100644 src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/IDocumentVersionCache.cs delete mode 100644 src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/DocumentVersionCacheTest.cs diff --git a/src/Razor/benchmarks/Microsoft.AspNetCore.Razor.Microbenchmarks/LanguageServer/RazorSemanticTokensBenchmark.cs b/src/Razor/benchmarks/Microsoft.AspNetCore.Razor.Microbenchmarks/LanguageServer/RazorSemanticTokensBenchmark.cs index d7825241214..8afb6f83298 100644 --- a/src/Razor/benchmarks/Microsoft.AspNetCore.Razor.Microbenchmarks/LanguageServer/RazorSemanticTokensBenchmark.cs +++ b/src/Razor/benchmarks/Microsoft.AspNetCore.Razor.Microbenchmarks/LanguageServer/RazorSemanticTokensBenchmark.cs @@ -10,7 +10,6 @@ using System.Threading.Tasks; using BenchmarkDotNet.Attributes; using Microsoft.AspNetCore.Razor.Language; -using Microsoft.AspNetCore.Razor.LanguageServer; using Microsoft.AspNetCore.Razor.LanguageServer.Semantic; using Microsoft.CodeAnalysis.Razor.DocumentMapping; using Microsoft.CodeAnalysis.Razor.Logging; @@ -28,8 +27,6 @@ public class RazorSemanticTokensBenchmark : RazorLanguageServerBenchmarkBase { private IRazorSemanticTokensInfoService RazorSemanticTokenService { get; set; } - private IDocumentVersionCache VersionCache { get; set; } - private Uri DocumentUri => DocumentContext.Uri; private IDocumentSnapshot DocumentSnapshot => DocumentContext.Snapshot; @@ -75,9 +72,6 @@ public async Task InitializeRazorSemanticAsync() public async Task RazorSemanticTokensRangeAsync() { var cancellationToken = CancellationToken.None; - var documentVersion = 1; - - VersionCache.TrackDocumentVersion(DocumentSnapshot, documentVersion); await RazorSemanticTokenService.GetSemanticTokensAsync(DocumentContext, Range.ToLinePositionSpan(), colorBackground: false, Guid.Empty, cancellationToken: cancellationToken).ConfigureAwait(false); } @@ -98,10 +92,7 @@ protected internal override void Builder(IServiceCollection collection) private void EnsureServicesInitialized() { - var capabilitiesService = new BenchmarkClientCapabilitiesService(new VSInternalClientCapabilities { SupportsVisualStudioExtensions = true }); - var legend = new RazorSemanticTokensLegendService(capabilitiesService); RazorSemanticTokenService = RazorLanguageServerHost.GetRequiredService(); - VersionCache = RazorLanguageServerHost.GetRequiredService(); } internal class TestRazorSemanticTokensInfoService : RazorSemanticTokensInfoService diff --git a/src/Razor/benchmarks/Microsoft.AspNetCore.Razor.Microbenchmarks/LanguageServer/RazorSemanticTokensRangeEndpointBenchmark.cs b/src/Razor/benchmarks/Microsoft.AspNetCore.Razor.Microbenchmarks/LanguageServer/RazorSemanticTokensRangeEndpointBenchmark.cs index 8258f197fc8..041413a31b5 100644 --- a/src/Razor/benchmarks/Microsoft.AspNetCore.Razor.Microbenchmarks/LanguageServer/RazorSemanticTokensRangeEndpointBenchmark.cs +++ b/src/Razor/benchmarks/Microsoft.AspNetCore.Razor.Microbenchmarks/LanguageServer/RazorSemanticTokensRangeEndpointBenchmark.cs @@ -32,12 +32,8 @@ public class RazorSemanticTokensRangeEndpointBenchmark : RazorLanguageServerBenc private SemanticTokensRangeEndpoint SemanticTokensRangeEndpoint { get; set; } - private IDocumentVersionCache VersionCache { get; set; } - private Uri DocumentUri => DocumentContext.Uri; - private IDocumentSnapshot DocumentSnapshot => DocumentContext.Snapshot; - private VersionedDocumentContext DocumentContext { get; set; } private Range Range { get; set; } @@ -83,9 +79,6 @@ public async Task InitializeRazorSemanticAsync() start: (0, 0), end: (text.Lines.Count - 1, text.Lines[^1].Span.Length - 1)); - var documentVersion = 1; - VersionCache.TrackDocumentVersion(DocumentSnapshot, documentVersion); - RequestContext = new RazorRequestContext(DocumentContext, RazorLanguageServerHost.GetRequiredService(), "lsp/method", uri: null); var random = new Random(); @@ -133,7 +126,6 @@ protected internal override void Builder(IServiceCollection collection) private void EnsureServicesInitialized() { RazorSemanticTokenService = RazorLanguageServerHost.GetRequiredService(); - VersionCache = RazorLanguageServerHost.GetRequiredService(); } internal class TestCustomizableRazorSemanticTokensInfoService : RazorSemanticTokensInfoService diff --git a/src/Razor/benchmarks/Microsoft.AspNetCore.Razor.Microbenchmarks/LanguageServer/RazorSemanticTokensScrollingBenchmark.cs b/src/Razor/benchmarks/Microsoft.AspNetCore.Razor.Microbenchmarks/LanguageServer/RazorSemanticTokensScrollingBenchmark.cs index 4063270b669..6f5107bb265 100644 --- a/src/Razor/benchmarks/Microsoft.AspNetCore.Razor.Microbenchmarks/LanguageServer/RazorSemanticTokensScrollingBenchmark.cs +++ b/src/Razor/benchmarks/Microsoft.AspNetCore.Razor.Microbenchmarks/LanguageServer/RazorSemanticTokensScrollingBenchmark.cs @@ -8,7 +8,6 @@ using System.Threading; using System.Threading.Tasks; using BenchmarkDotNet.Attributes; -using Microsoft.AspNetCore.Razor.LanguageServer; using Microsoft.CodeAnalysis.Razor.ProjectSystem; using Microsoft.CodeAnalysis.Razor.SemanticTokens; using Microsoft.CodeAnalysis.Text; @@ -23,8 +22,6 @@ public class RazorSemanticTokensScrollingBenchmark : RazorLanguageServerBenchmar { private IRazorSemanticTokensInfoService RazorSemanticTokenService { get; set; } - private IDocumentVersionCache VersionCache { get; set; } - private VersionedDocumentContext DocumentContext { get; set; } private Uri DocumentUri => DocumentContext.Uri; @@ -66,9 +63,6 @@ public async Task InitializeRazorSemanticAsync() public async Task RazorSemanticTokensRangeScrollingAsync() { var cancellationToken = CancellationToken.None; - var documentVersion = 1; - - VersionCache!.TrackDocumentVersion(DocumentSnapshot, documentVersion); var documentLineCount = Range.End.Line; @@ -105,6 +99,5 @@ protected internal override void Builder(IServiceCollection collection) private void EnsureServicesInitialized() { RazorSemanticTokenService = RazorLanguageServerHost.GetRequiredService(); - VersionCache = RazorLanguageServerHost.GetRequiredService(); } } diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/DocumentContextFactory.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/DocumentContextFactory.cs index c752e617e0b..7f46807c2a3 100644 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/DocumentContextFactory.cs +++ b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/DocumentContextFactory.cs @@ -18,12 +18,10 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer; internal sealed class DocumentContextFactory( IProjectSnapshotManager projectManager, - IDocumentVersionCache documentVersionCache, ILoggerFactory loggerFactory) : IDocumentContextFactory { private readonly IProjectSnapshotManager _projectManager = projectManager; - private readonly IDocumentVersionCache _documentVersionCache = documentVersionCache; private readonly ILogger _logger = loggerFactory.GetOrCreateLogger(); public bool TryCreate( @@ -80,13 +78,8 @@ private bool TryGetDocumentAndVersion( return true; } - if (_documentVersionCache.TryGetDocumentVersion(documentSnapshot, out var version)) - { - documentAndVersion = new DocumentSnapshotAndVersion(documentSnapshot, version.Value); - return true; - } - - _logger.LogWarning($"Tried to create context for document {filePath} and project {projectContext?.Id} and a document was found, but version didn't match."); + documentAndVersion = new DocumentSnapshotAndVersion(documentSnapshot, documentSnapshot.Version); + return true; } // This is super rare, if we get here it could mean many things. Some of which: diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/DocumentVersionCache.DocumentEntry.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/DocumentVersionCache.DocumentEntry.cs deleted file mode 100644 index 8c75ad73168..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/DocumentVersionCache.DocumentEntry.cs +++ /dev/null @@ -1,17 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT license. See License.txt in the project root for license information. - -using System; -using Microsoft.CodeAnalysis.Razor.ProjectSystem; - -namespace Microsoft.AspNetCore.Razor.LanguageServer; - -internal sealed partial class DocumentVersionCache -{ - private readonly struct DocumentEntry(IDocumentSnapshot document, int version) - { - public WeakReference Document { get; } = new WeakReference(document); - - public int Version { get; } = version; - } -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/DocumentVersionCache.TestAccessor.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/DocumentVersionCache.TestAccessor.cs deleted file mode 100644 index 8af39581c2a..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/DocumentVersionCache.TestAccessor.cs +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT license. See License.txt in the project root for license information. - -#if !NET -using System.Collections.Generic; -#endif -using System.Collections.Immutable; -using Microsoft.AspNetCore.Razor.PooledObjects; -using Microsoft.CodeAnalysis.Razor.ProjectSystem; - -namespace Microsoft.AspNetCore.Razor.LanguageServer; - -internal sealed partial class DocumentVersionCache -{ - internal TestAccessor GetTestAccessor() => new(this); - - internal class TestAccessor(DocumentVersionCache @this) - { - private readonly DocumentVersionCache _this = @this; - - public record struct DocumentEntry(IDocumentSnapshot? Document, int Version); - - public ImmutableDictionary> GetEntries() - { - using var result = new PooledDictionaryBuilder>(); - using var _ = _this._lock.EnterReadLock(); - - foreach (var (key, entries) in _this._documentLookup_NeedsLock) - { - using var versions = new PooledArrayBuilder(); - - foreach (var entry in entries) - { - var document = entry.Document.TryGetTarget(out var target) - ? target - : null; - - var version = entry.Version; - - versions.Add(new(document, version)); - } - - result.Add(key, versions.ToImmutable()); - } - - return result.ToImmutable(); - } - - public void MarkAsLatestVersion(IDocumentSnapshot document) - { - using (_this._lock.EnterUpgradeableReadLock()) - { - _this.MarkAsLatestVersion(document); - } - } - } -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/DocumentVersionCache.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/DocumentVersionCache.cs deleted file mode 100644 index b92fc2a926e..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/DocumentVersionCache.cs +++ /dev/null @@ -1,179 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT license. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.Diagnostics.CodeAnalysis; -using Microsoft.CodeAnalysis.Razor; -using Microsoft.CodeAnalysis.Razor.ProjectSystem; -using Microsoft.CodeAnalysis.Razor.Workspaces; - -namespace Microsoft.AspNetCore.Razor.LanguageServer; - -internal sealed partial class DocumentVersionCache : IDocumentVersionCache, IRazorStartupService -{ - internal const int MaxDocumentTrackingCount = 20; - - private readonly Dictionary> _documentLookup_NeedsLock = new(FilePathComparer.Instance); - private readonly ReadWriterLocker _lock = new(); - private readonly IProjectSnapshotManager _projectManager; - - public DocumentVersionCache(IProjectSnapshotManager projectManager) - { - _projectManager = projectManager; - _projectManager.Changed += ProjectManager_Changed; - } - - private void ProjectManager_Changed(object? sender, ProjectChangeEventArgs args) - { - // Don't do any work if the solution is closing - if (args.SolutionIsClosing) - { - return; - } - - if (args.Kind == ProjectChangeKind.DocumentChanged) - { - var documentFilePath = args.DocumentFilePath.AssumeNotNull(); - - using (_lock.EnterUpgradeableReadLock()) - { - if (_documentLookup_NeedsLock.ContainsKey(documentFilePath) && - !_projectManager.IsDocumentOpen(documentFilePath)) - { - using (_lock.EnterWriteLock()) - { - // Document closed, evict entry. - _documentLookup_NeedsLock.Remove(documentFilePath); - } - } - } - } - - // Any event that has a project may have changed the state of the documents - // and therefore requires us to mark all existing documents as latest. - if (!_projectManager.TryGetLoadedProject(args.ProjectKey, out var project)) - { - // Project no longer loaded, so there's no work to do. - return; - } - - CaptureProjectDocumentsAsLatest(project); - } - - public void TrackDocumentVersion(IDocumentSnapshot documentSnapshot, int version) - { - if (documentSnapshot is null) - { - throw new ArgumentNullException(nameof(documentSnapshot)); - } - - using (_lock.EnterUpgradeableReadLock()) - { - TrackDocumentVersionCore(documentSnapshot, version); - } - } - - private void TrackDocumentVersionCore(IDocumentSnapshot documentSnapshot, int version) - { - Debug.Assert(_lock.IsUpgradeableReadLockHeld); - - // Need to ensure the write lock covers all uses of documentEntries, not just DocumentLookup - using (_lock.EnterWriteLock()) - { - var key = documentSnapshot.FilePath.AssumeNotNull(); - if (!_documentLookup_NeedsLock.TryGetValue(key, out var documentEntries)) - { - documentEntries = []; - _documentLookup_NeedsLock.Add(key, documentEntries); - } - - if (documentEntries.Count == MaxDocumentTrackingCount) - { - // Clear the oldest document entry - - // With this approach we'll slowly leak memory as new documents are added to the system. We don't clear up - // document file paths where where all of the corresponding entries are expired. - documentEntries.RemoveAt(0); - } - - var entry = new DocumentEntry(documentSnapshot, version); - documentEntries.Add(entry); - } - } - - public int GetLatestDocumentVersion(string filePath) - { - using var _ = _lock.EnterReadLock(); - - if (!_documentLookup_NeedsLock.TryGetValue(filePath, out var documentEntries)) - { - return -1; - } - - return documentEntries[^1].Version; - } - - public bool TryGetDocumentVersion(IDocumentSnapshot documentSnapshot, [NotNullWhen(true)] out int? version) - { - if (documentSnapshot is null) - { - throw new ArgumentNullException(nameof(documentSnapshot)); - } - - using var _ = _lock.EnterReadLock(); - - var filePath = documentSnapshot.FilePath.AssumeNotNull(); - if (!_documentLookup_NeedsLock.TryGetValue(filePath, out var documentEntries)) - { - version = null; - return false; - } - - // We iterate backwards over the entries to prioritize newer entries. - for (var i = documentEntries.Count - 1; i >= 0; i--) - { - if (documentEntries[i].Document.TryGetTarget(out var document) && - document == documentSnapshot) - { - version = documentEntries[i].Version; - return true; - } - } - - version = null; - return false; - } - - private void CaptureProjectDocumentsAsLatest(IProjectSnapshot projectSnapshot) - { - Debug.Assert(!_lock.IsUpgradeableReadLockHeld); - - using var _ = _lock.EnterUpgradeableReadLock(); - - foreach (var documentPath in projectSnapshot.DocumentFilePaths) - { - if (_documentLookup_NeedsLock.ContainsKey(documentPath) && - projectSnapshot.GetDocument(documentPath) is { } document) - { - MarkAsLatestVersion(document); - } - } - } - - private void MarkAsLatestVersion(IDocumentSnapshot document) - { - Debug.Assert(_lock.IsUpgradeableReadLockHeld); - - if (!_documentLookup_NeedsLock.TryGetValue(document.FilePath.AssumeNotNull(), out var documentEntries)) - { - return; - } - - var latestEntry = documentEntries[^1]; - - // Update our internal tracking state to track the changed document as the latest document. - TrackDocumentVersionCore(document, latestEntry.Version); - } -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Extensions/IServiceCollectionExtensions.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Extensions/IServiceCollectionExtensions.cs index 38dfdb87dfb..42a5baee4c9 100644 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Extensions/IServiceCollectionExtensions.cs +++ b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Extensions/IServiceCollectionExtensions.cs @@ -195,9 +195,6 @@ public static void AddDocumentManagementServices(this IServiceCollection service services.AddSingleton(); services.AddSingleton(sp => new Lazy(sp.GetRequiredService)); - services.AddSingleton(); - services.AddSingleton((services) => (IRazorStartupService)services.GetRequiredService()); - services.AddSingleton(); services.AddSingleton(); services.AddSingleton((services) => (RazorProjectService)services.GetRequiredService()); diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Formatting/HtmlFormatter.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Formatting/HtmlFormatter.cs index 288afdeacac..4e990827dea 100644 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Formatting/HtmlFormatter.cs +++ b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Formatting/HtmlFormatter.cs @@ -16,15 +16,11 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.Formatting; internal class HtmlFormatter { - private readonly IDocumentVersionCache _documentVersionCache; private readonly IClientConnection _clientConnection; - public HtmlFormatter( - IClientConnection clientConnection, - IDocumentVersionCache documentVersionCache) + public HtmlFormatter(IClientConnection clientConnection) { _clientConnection = clientConnection; - _documentVersionCache = documentVersionCache; } public async Task FormatAsync( @@ -36,10 +32,7 @@ public async Task FormatAsync( throw new ArgumentNullException(nameof(context)); } - if (!_documentVersionCache.TryGetDocumentVersion(context.OriginalSnapshot, out var documentVersion)) - { - return Array.Empty(); - } + var documentVersion = context.OriginalSnapshot.Version; var @params = new RazorDocumentFormattingParams() { @@ -47,7 +40,7 @@ public async Task FormatAsync( { Uri = context.Uri, }, - HostDocumentVersion = documentVersion.Value, + HostDocumentVersion = documentVersion, Options = context.Options }; @@ -63,10 +56,7 @@ public async Task FormatOnTypeAsync( FormattingContext context, CancellationToken cancellationToken) { - if (!_documentVersionCache.TryGetDocumentVersion(context.OriginalSnapshot, out var documentVersion)) - { - return Array.Empty(); - } + var documentVersion = context.OriginalSnapshot.Version; var @params = new RazorDocumentOnTypeFormattingParams() { @@ -74,7 +64,7 @@ public async Task FormatOnTypeAsync( Character = context.TriggerCharacter.ToString(), TextDocument = new TextDocumentIdentifier { Uri = context.Uri }, Options = context.Options, - HostDocumentVersion = documentVersion.Value, + HostDocumentVersion = documentVersion, }; var result = await _clientConnection.SendRequestAsync( diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Formatting/HtmlFormattingPass.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Formatting/HtmlFormattingPass.cs index f522ea5790c..3e9f87b7ea7 100644 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Formatting/HtmlFormattingPass.cs +++ b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Formatting/HtmlFormattingPass.cs @@ -19,11 +19,10 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.Formatting; internal sealed class HtmlFormattingPass( IDocumentMappingService documentMappingService, IClientConnection clientConnection, - IDocumentVersionCache documentVersionCache, ILoggerFactory loggerFactory) : FormattingPassBase(documentMappingService) { - private readonly HtmlFormatter _htmlFormatter = new HtmlFormatter(clientConnection, documentVersionCache); + private readonly HtmlFormatter _htmlFormatter = new HtmlFormatter(clientConnection); private readonly ILogger _logger = loggerFactory.GetOrCreateLogger(); // We want this to run first because it uses the client HTML formatter. diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/GeneratedDocumentSynchronizer.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/GeneratedDocumentSynchronizer.cs index 2fe06d466d3..b3a01451ce5 100644 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/GeneratedDocumentSynchronizer.cs +++ b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/GeneratedDocumentSynchronizer.cs @@ -9,20 +9,14 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer; internal class GeneratedDocumentSynchronizer( IGeneratedDocumentPublisher publisher, - IDocumentVersionCache documentVersionCache, LanguageServerFeatureOptions languageServerFeatureOptions) : IDocumentProcessedListener { private readonly IGeneratedDocumentPublisher _publisher = publisher; - private readonly IDocumentVersionCache _documentVersionCache = documentVersionCache; private readonly LanguageServerFeatureOptions _languageServerFeatureOptions = languageServerFeatureOptions; public void DocumentProcessed(RazorCodeDocument codeDocument, IDocumentSnapshot document) { - if (!_documentVersionCache.TryGetDocumentVersion(document, out var hostDocumentVersion)) - { - // Could not resolve document version - return; - } + var hostDocumentVersion = document.Version; var filePath = document.FilePath.AssumeNotNull(); @@ -31,11 +25,11 @@ public void DocumentProcessed(RazorCodeDocument codeDocument, IDocumentSnapshot { var htmlText = codeDocument.GetHtmlSourceText(); - _publisher.PublishHtml(document.Project.Key, filePath, htmlText, hostDocumentVersion.Value); + _publisher.PublishHtml(document.Project.Key, filePath, htmlText, hostDocumentVersion); } var csharpText = codeDocument.GetCSharpSourceText(); - _publisher.PublishCSharp(document.Project.Key, filePath, csharpText, hostDocumentVersion.Value); + _publisher.PublishCSharp(document.Project.Key, filePath, csharpText, hostDocumentVersion); } } diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/IDocumentVersionCache.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/IDocumentVersionCache.cs deleted file mode 100644 index 932d55ea68a..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/IDocumentVersionCache.cs +++ /dev/null @@ -1,16 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT license. See License.txt in the project root for license information. - -using System.Diagnostics.CodeAnalysis; -using Microsoft.CodeAnalysis.Razor.ProjectSystem; - -namespace Microsoft.AspNetCore.Razor.LanguageServer; - -internal interface IDocumentVersionCache -{ - bool TryGetDocumentVersion(IDocumentSnapshot documentSnapshot, [NotNullWhen(true)] out int? version); - void TrackDocumentVersion(IDocumentSnapshot documentSnapshot, int version); - - // HACK: This is temporary to allow the cohosting and normal language server to co-exist and share code - int GetLatestDocumentVersion(string filePath); -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/ProjectSystem/RazorProjectService.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/ProjectSystem/RazorProjectService.cs index 74ebb392272..696129efb99 100644 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/ProjectSystem/RazorProjectService.cs +++ b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/ProjectSystem/RazorProjectService.cs @@ -36,7 +36,6 @@ internal partial class RazorProjectService : IRazorProjectService, IRazorProject private readonly IRazorProjectInfoDriver _projectInfoDriver; private readonly IProjectSnapshotManager _projectManager; private readonly RemoteTextLoaderFactory _remoteTextLoaderFactory; - private readonly IDocumentVersionCache _documentVersionCache; private readonly ILogger _logger; private readonly CancellationTokenSource _disposeTokenSource; @@ -45,14 +44,12 @@ internal partial class RazorProjectService : IRazorProjectService, IRazorProject public RazorProjectService( IProjectSnapshotManager projectManager, IRazorProjectInfoDriver projectInfoDriver, - IDocumentVersionCache documentVersionCache, RemoteTextLoaderFactory remoteTextLoaderFactory, ILoggerFactory loggerFactory) { _projectInfoDriver = projectInfoDriver; _projectManager = projectManager; _remoteTextLoaderFactory = remoteTextLoaderFactory; - _documentVersionCache = documentVersionCache; _logger = loggerFactory.GetOrCreateLogger(); // We kick off initialization immediately to ensure that the IRazorProjectService @@ -208,14 +205,6 @@ await _projectManager.UpdateAsync( _logger.LogInformation($"Opening document '{textDocumentPath}' in project '{projectSnapshot.Key}'."); updater.DocumentOpened(projectSnapshot.Key, textDocumentPath, sourceText); }); - - // Use a separate loop, as the above call modified out projects, so we have to make sure we're operating on the latest snapshot - ActOnDocumentInMultipleProjects( - filePath, - (projectSnapshot, textDocumentPath) => - { - TrackDocumentVersion(projectSnapshot, textDocumentPath, version, startGenerating: true); - }); }, cancellationToken) .ConfigureAwait(false); @@ -304,14 +293,6 @@ await _projectManager.UpdateAsync( updater.DocumentChanged(project.Key, textDocumentPath, sourceText); }); - - // Use a separate loop, as the above call modified out projects, so we have to make sure we're operating on the latest snapshot - ActOnDocumentInMultipleProjects( - filePath, - (projectSnapshot, textDocumentPath) => - { - TrackDocumentVersion(projectSnapshot, textDocumentPath, version, startGenerating: false); - }); }, cancellationToken) .ConfigureAwait(false); @@ -672,20 +653,4 @@ private void TryMigrateMiscellaneousDocumentsToProject(ProjectSnapshotManager.Up updater.DocumentAdded(projectSnapshot.Key, newHostDocument, textLoader); } } - - private void TrackDocumentVersion(IProjectSnapshot projectSnapshot, string textDocumentPath, int version, bool startGenerating) - { - if (projectSnapshot.GetDocument(FilePathNormalizer.Normalize(textDocumentPath)) is not { } documentSnapshot) - { - return; - } - - _documentVersionCache.TrackDocumentVersion(documentSnapshot, version); - - if (startGenerating) - { - // Start generating the C# for the document so it can immediately be ready for incoming requests. - documentSnapshot.GetGeneratedOutputAsync().Forget(); - } - } } diff --git a/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/Endpoints/RazorCustomMessageTarget.cs b/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/Endpoints/RazorCustomMessageTarget.cs index 1ae779026f7..c16944aa492 100644 --- a/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/Endpoints/RazorCustomMessageTarget.cs +++ b/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/Endpoints/RazorCustomMessageTarget.cs @@ -136,6 +136,7 @@ private async Task> TrySynchronizeV int requiredHostDocumentVersion, TextDocumentIdentifier hostDocument, CancellationToken cancellationToken, + Range? _ = null, bool rejectOnNewerParallelRequest = true, [CallerMemberName] string? caller = null) where TVirtualDocumentSnapshot : VirtualDocumentSnapshot @@ -200,6 +201,21 @@ private async Task> TrySynchronizeV _logger.LogDebug($"{(result.Synchronized ? "Did" : "Did NOT")} synchronize for {caller}: Version {requiredHostDocumentVersion} for {result.VirtualSnapshot?.Uri}"); } + //if (requiredHostDocumentVersion == 1 && + // result.Synchronized && + // result.VirtualSnapshot is not null && + // range is not null) + //{ + // // If we're at version 1, and we're synced, lets make sure the buffer has enough lines to handle the request + // if (range.Start.Line > result.VirtualSnapshot.Snapshot.LineCount || + // range.End.Line > result.VirtualSnapshot.Snapshot.LineCount) + // { + // Debug.Fail("It worked!"); + // _logger.LogWarning($"Requested line ({range.Start.Line} or {range.End.Line}) is out of bounds for {result.VirtualSnapshot.Uri}. Sync failed."); + // return new SynchronizedResult(false, null); + // } + //} + return result; } diff --git a/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/Endpoints/RazorCustomMessageTarget_SemanticTokens.cs b/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/Endpoints/RazorCustomMessageTarget_SemanticTokens.cs index 1d895280ad4..90656ea4453 100644 --- a/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/Endpoints/RazorCustomMessageTarget_SemanticTokens.cs +++ b/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/Endpoints/RazorCustomMessageTarget_SemanticTokens.cs @@ -3,6 +3,7 @@ using System; using System.Diagnostics; +using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.Razor; @@ -70,7 +71,8 @@ internal partial class RazorCustomMessageTarget var (synchronized, csharpDoc) = await TrySynchronizeVirtualDocumentAsync( (int)semanticTokensParams.RequiredHostDocumentVersion, semanticTokensParams.TextDocument, - cancellationToken); + cancellationToken, + semanticTokensParams.Ranges.FirstOrDefault()); if (csharpDoc is null) { @@ -92,6 +94,8 @@ internal partial class RazorCustomMessageTarget if (csharpDoc.Snapshot.LineCount < lastGeneratedDocumentLine) { + _logger.LogWarning($"Pretending we're not synced because we're asking for line {lastGeneratedDocumentLine} but there are only {csharpDoc.Snapshot.LineCount} lines in the buffer."); + Debug.Fail("Rejecting!"); // We report this as a fail to synchronize, as that's essentially what it is: We were asked for v1, with X lines // and whilst we have v1, we don't have X lines, so we need to wait for a future update to arrive and give us // more content. diff --git a/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/Endpoints/RazorCustomMessageTarget_UpdateCSharpBuffer.cs b/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/Endpoints/RazorCustomMessageTarget_UpdateCSharpBuffer.cs index 9ebc750ea31..e2b6355c927 100644 --- a/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/Endpoints/RazorCustomMessageTarget_UpdateCSharpBuffer.cs +++ b/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/Endpoints/RazorCustomMessageTarget_UpdateCSharpBuffer.cs @@ -78,7 +78,7 @@ request.ProjectKeyId is not null && { if (virtualDocument.ProjectKey.Equals(new ProjectKey(request.ProjectKeyId))) { - _logger.LogDebug($"UpdateCSharpBuffer virtual doc for {request.HostDocumentVersion} of {virtualDocument.Uri}"); + _logger.LogDebug($"UpdateCSharpBuffer virtual doc for {request.HostDocumentVersion} of {virtualDocument.Uri}. Previous lines: {virtualDocument.Snapshot.LineCount}"); _documentManager.UpdateVirtualDocument( hostDocumentUri, @@ -86,6 +86,17 @@ request.ProjectKeyId is not null && request.Changes.Select(change => change.ToVisualStudioTextChange()).ToArray(), request.HostDocumentVersion.Value, state: request.PreviousWasEmpty); + + if (_documentManager.TryGetDocument(hostDocumentUri, out var newDocSnapshot)) + { + var newDoc = newDocSnapshot.VirtualDocuments.Where(e => e.Uri == virtualDocument.Uri).FirstOrDefault(); + + if (newDoc is not null) + { + _logger.LogDebug($"UpdateCSharpBuffer finished updating doc for {request.HostDocumentVersion} of {virtualDocument.Uri}. New lines: {newDoc.Snapshot.LineCount}"); + } + } + return; } } diff --git a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/CodeActions/CodeActionEndToEndTest.NetFx.cs b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/CodeActions/CodeActionEndToEndTest.NetFx.cs index 33b35e3df98..3afd4bc01c2 100644 --- a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/CodeActions/CodeActionEndToEndTest.NetFx.cs +++ b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/CodeActions/CodeActionEndToEndTest.NetFx.cs @@ -1131,7 +1131,7 @@ private async Task ValidateCodeActionAsync( Assert.NotNull(codeActionToRun); - var formattingService = await TestRazorFormattingService.CreateWithFullSupportAsync(LoggerFactory, codeDocument, documentContext.Snapshot, optionsMonitor?.CurrentValue); + var formattingService = await TestRazorFormattingService.CreateWithFullSupportAsync(LoggerFactory, codeDocument, optionsMonitor?.CurrentValue); var changes = await GetEditsAsync( codeActionToRun, requestContext, diff --git a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/DocumentContextFactoryTest.cs b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/DocumentContextFactoryTest.cs index 31394f347d2..295533b052e 100644 --- a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/DocumentContextFactoryTest.cs +++ b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/DocumentContextFactoryTest.cs @@ -21,13 +21,11 @@ public class DocumentContextFactoryTest : LanguageServerTestBase private static readonly string s_baseDirectory = PathUtilities.CreateRootedPath("path", "to"); private readonly TestProjectSnapshotManager _projectManager; - private readonly IDocumentVersionCache _documentVersionCache; public DocumentContextFactoryTest(ITestOutputHelper testOutput) : base(testOutput) { _projectManager = CreateProjectSnapshotManager(); - _documentVersionCache = new DocumentVersionCache(_projectManager); } [Fact] @@ -37,7 +35,7 @@ public void TryCreateAsync_CanNotResolveDocument_ReturnsNull() var filePath = FilePathNormalizer.Normalize(Path.Combine(s_baseDirectory, "file.cshtml")); var uri = new Uri(filePath); - var factory = new DocumentContextFactory(_projectManager, _documentVersionCache, LoggerFactory); + var factory = new DocumentContextFactory(_projectManager, LoggerFactory); // Act Assert.False(factory.TryCreate(uri, out _)); @@ -50,7 +48,7 @@ public void TryCreateForOpenDocumentAsync_CanNotResolveDocument_ReturnsNull() var filePath = FilePathNormalizer.Normalize(Path.Combine(s_baseDirectory, "file.cshtml")); var uri = new Uri(filePath); - var factory = new DocumentContextFactory(_projectManager, _documentVersionCache, LoggerFactory); + var factory = new DocumentContextFactory(_projectManager, LoggerFactory); // Act Assert.False(factory.TryCreateForOpenDocument(uri, out _)); @@ -70,7 +68,7 @@ await _projectManager.UpdateAsync(updater => updater.DocumentAdded(MiscFilesHostProject.Instance.Key, hostDocument, TestMocks.CreateTextLoader(filePath, "")); }); - var factory = new DocumentContextFactory(_projectManager, _documentVersionCache, LoggerFactory); + var factory = new DocumentContextFactory(_projectManager, LoggerFactory); // Act Assert.False(factory.TryCreateForOpenDocument(uri, out _)); @@ -94,7 +92,7 @@ await _projectManager.UpdateAsync(updater => var documentSnapshot = miscFilesProject.GetDocument(filePath); Assert.NotNull(documentSnapshot); - var factory = new DocumentContextFactory(_projectManager, _documentVersionCache, LoggerFactory); + var factory = new DocumentContextFactory(_projectManager, LoggerFactory); // Act Assert.True(factory.TryCreate(uri, out var documentContext)); @@ -113,7 +111,7 @@ public async Task TryCreateAsync_WithProjectContext_Resolves() var projectFilePath = Path.Combine(s_baseDirectory, "project.csproj"); var uri = new Uri(filePath); - var factory = new DocumentContextFactory(_projectManager, _documentVersionCache, LoggerFactory); + var factory = new DocumentContextFactory(_projectManager, LoggerFactory); var hostProject = new HostProject(projectFilePath, intermediateOutputPath, RazorConfiguration.Default, rootNamespace: null); var hostDocument = new HostDocument(filePath, "file.cshtml"); @@ -149,8 +147,7 @@ await _projectManager.UpdateAsync(updater => var documentSnapshot = miscFilesProject.GetDocument(filePath); Assert.NotNull(documentSnapshot); - _documentVersionCache.TrackDocumentVersion(documentSnapshot, version: 1337); - var factory = new DocumentContextFactory(_projectManager, _documentVersionCache, LoggerFactory); + var factory = new DocumentContextFactory(_projectManager, LoggerFactory); // Act Assert.True(factory.TryCreateForOpenDocument(uri, out var documentContext)); diff --git a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/DocumentPresentation/TextDocumentUriPresentationEndpointTests.cs b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/DocumentPresentation/TextDocumentUriPresentationEndpointTests.cs index 318436e546a..100667df822 100644 --- a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/DocumentPresentation/TextDocumentUriPresentationEndpointTests.cs +++ b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/DocumentPresentation/TextDocumentUriPresentationEndpointTests.cs @@ -47,11 +47,9 @@ public async Task Handle_SimpleComponent_ReturnsResult() var razorFilePath = "c:/path/index.razor"; var uri = new Uri(razorFilePath); - var documentVersionCache = new DocumentVersionCache(projectManager); await projectManager.UpdateAsync(updater => updater.DocumentOpened(project.Key, razorFilePath, SourceText.From("
"))); var documentSnapshot = projectManager.GetLoadedProject(project.Key).GetDocument(razorFilePath).AssumeNotNull(); - documentVersionCache.TrackDocumentVersion(documentSnapshot, 1); - var documentContextFactory = new DocumentContextFactory(projectManager, documentVersionCache, LoggerFactory); + var documentContextFactory = new DocumentContextFactory(projectManager, LoggerFactory); Assert.True(documentContextFactory.TryCreateForOpenDocument(uri, null, out var documentContext)); var clientConnection = new Mock(MockBehavior.Strict); @@ -105,11 +103,9 @@ public async Task Handle_SimpleComponentWithChildFile_ReturnsResult() var razorFilePath = "c:/path/index.razor"; var uri = new Uri(razorFilePath); - var documentVersionCache = new DocumentVersionCache(projectManager); await projectManager.UpdateAsync(updater => updater.DocumentOpened(project.Key, razorFilePath, SourceText.From("
"))); var documentSnapshot = projectManager.GetLoadedProject(project.Key).GetDocument(razorFilePath).AssumeNotNull(); - documentVersionCache.TrackDocumentVersion(documentSnapshot, 1); - var documentContextFactory = new DocumentContextFactory(projectManager, documentVersionCache, LoggerFactory); + var documentContextFactory = new DocumentContextFactory(projectManager, LoggerFactory); Assert.True(documentContextFactory.TryCreateForOpenDocument(uri, null, out var documentContext)); var clientConnection = new Mock(MockBehavior.Strict); @@ -174,11 +170,9 @@ public async Task Handle_ComponentWithRequiredAttribute_ReturnsResult() var razorFilePath = "c:/path/index.razor"; var uri = new Uri(razorFilePath); - var documentVersionCache = new DocumentVersionCache(projectManager); await projectManager.UpdateAsync(updater => updater.DocumentOpened(project.Key, razorFilePath, SourceText.From("
"))); var documentSnapshot = projectManager.GetLoadedProject(project.Key).GetDocument(razorFilePath).AssumeNotNull(); - documentVersionCache.TrackDocumentVersion(documentSnapshot, 1); - var documentContextFactory = new DocumentContextFactory(projectManager, documentVersionCache, LoggerFactory); + var documentContextFactory = new DocumentContextFactory(projectManager, LoggerFactory); Assert.True(documentContextFactory.TryCreateForOpenDocument(uri, null, out var documentContext)); var clientConnection = new Mock(MockBehavior.Strict); @@ -382,11 +376,9 @@ public async Task Handle_ComponentWithNestedFiles_ReturnsResult() var razorFilePath = "c:/path/index.razor"; var uri = new Uri(razorFilePath); - var documentVersionCache = new DocumentVersionCache(projectManager); await projectManager.UpdateAsync(updater => updater.DocumentOpened(project.Key, razorFilePath, SourceText.From("
"))); var documentSnapshot = projectManager.GetLoadedProject(project.Key).GetDocument(razorFilePath).AssumeNotNull(); - documentVersionCache.TrackDocumentVersion(documentSnapshot, 1); - var documentContextFactory = new DocumentContextFactory(projectManager, documentVersionCache, LoggerFactory); + var documentContextFactory = new DocumentContextFactory(projectManager, LoggerFactory); Assert.True(documentContextFactory.TryCreateForOpenDocument(uri, null, out var documentContext)); var clientConnection = new Mock(MockBehavior.Strict); diff --git a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/DocumentVersionCacheTest.cs b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/DocumentVersionCacheTest.cs deleted file mode 100644 index acad8a273e2..00000000000 --- a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/DocumentVersionCacheTest.cs +++ /dev/null @@ -1,322 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT license. See License.txt in the project root for license information. - -#if NETFRAMEWORK -using System; -using System.Collections.Generic; -#endif -using System.Threading.Tasks; -using Microsoft.AspNetCore.Razor.Language; -using Microsoft.AspNetCore.Razor.Test.Common.LanguageServer; -using Microsoft.AspNetCore.Razor.Test.Common.ProjectSystem; -using Microsoft.CodeAnalysis; -using Xunit; -using Xunit.Abstractions; - -namespace Microsoft.AspNetCore.Razor.LanguageServer; - -public class DocumentVersionCacheTest(ITestOutputHelper testOutput) : LanguageServerTestBase(testOutput) -{ - [Fact] - public void MarkAsLatestVersion_UntrackedDocument_Noops() - { - // Arrange - var projectManager = CreateProjectSnapshotManager(); - var cache = new DocumentVersionCache(projectManager); - var cacheAccessor = cache.GetTestAccessor(); - var document = TestDocumentSnapshot.Create("C:/file.cshtml"); - cache.TrackDocumentVersion(document, 123); - var untrackedDocument = TestDocumentSnapshot.Create("C:/other.cshtml"); - - // Act - cacheAccessor.MarkAsLatestVersion(untrackedDocument); - - // Assert - Assert.False(cache.TryGetDocumentVersion(untrackedDocument, out var version)); - Assert.Null(version); - } - - [Fact] - public void MarkAsLatestVersion_KnownDocument_TracksNewDocumentAsLatest() - { - // Arrange - var projectManager = CreateProjectSnapshotManager(); - var cache = new DocumentVersionCache(projectManager); - var cacheAccessor = cache.GetTestAccessor(); - var documentInitial = TestDocumentSnapshot.Create("C:/file.cshtml"); - cache.TrackDocumentVersion(documentInitial, 123); - var documentLatest = TestDocumentSnapshot.Create(documentInitial.FilePath); - - // Act - cacheAccessor.MarkAsLatestVersion(documentLatest); - - // Assert - Assert.True(cache.TryGetDocumentVersion(documentLatest, out var version)); - Assert.Equal(123, version); - } - - [Fact] - public async Task ProjectSnapshotManager_Changed_DocumentRemoved_DoesNotEvictDocument() - { - // Arrange - var projectManager = CreateProjectSnapshotManager(); - var cache = new DocumentVersionCache(projectManager); - - var document = TestDocumentSnapshot.Create("C:/file.cshtml"); - Assert.True(document.TryGetText(out var text)); - Assert.True(document.TryGetTextVersion(out var textVersion)); - var textAndVersion = TextAndVersion.Create(text, textVersion); - cache.TrackDocumentVersion(document, 1337); - - await projectManager.UpdateAsync(updater => - { - updater.ProjectAdded(document.ProjectInternal.HostProject); - updater.DocumentAdded(document.ProjectInternal.Key, document.State.HostDocument, TextLoader.From(textAndVersion)); - }); - - // Act - 1 - var result = cache.TryGetDocumentVersion(document, out _); - - // Assert - 1 - Assert.True(result); - - // Act - 2 - await projectManager.UpdateAsync(updater => - updater.DocumentRemoved(document.ProjectInternal.Key, document.State.HostDocument)); - result = cache.TryGetDocumentVersion(document, out _); - - // Assert - 2 - Assert.True(result); - } - - [Fact] - public async Task ProjectSnapshotManager_Changed_OpenDocumentRemoved_DoesNotEvictDocument() - { - // Arrange - var projectManager = CreateProjectSnapshotManager(); - var cache = new DocumentVersionCache(projectManager); - - var document = TestDocumentSnapshot.Create("C:/file.cshtml"); - Assert.True(document.TryGetText(out var text)); - Assert.True(document.TryGetTextVersion(out var textVersion)); - var textAndVersion = TextAndVersion.Create(text, textVersion); - cache.TrackDocumentVersion(document, 1337); - - await projectManager.UpdateAsync(updater => - { - updater.ProjectAdded(document.ProjectInternal.HostProject); - updater.DocumentAdded(document.ProjectInternal.Key, document.State.HostDocument, TextLoader.From(textAndVersion)); - updater.DocumentOpened(document.ProjectInternal.Key, document.FilePath, textAndVersion.Text); - }); - - // Act - 1 - var result = cache.TryGetDocumentVersion(document, out _); - - // Assert - 1 - Assert.True(result); - Assert.True(projectManager.IsDocumentOpen(document.FilePath)); - - // Act - 2 - await projectManager.UpdateAsync(updater => - updater.DocumentRemoved(document.ProjectInternal.Key, document.State.HostDocument)); - result = cache.TryGetDocumentVersion(document, out _); - - // Assert - 2 - Assert.True(result); - } - - [Fact] - public async Task ProjectSnapshotManager_Changed_DocumentClosed_EvictsDocument() - { - // Arrange - var projectManager = CreateProjectSnapshotManager(); - var cache = new DocumentVersionCache(projectManager); - - var document = TestDocumentSnapshot.Create("C:/file.cshtml"); - Assert.True(document.TryGetText(out var text)); - Assert.True(document.TryGetTextVersion(out var textVersion)); - var textAndVersion = TextAndVersion.Create(text, textVersion); - cache.TrackDocumentVersion(document, 1337); - var textLoader = TextLoader.From(textAndVersion); - - await projectManager.UpdateAsync(updater => - { - updater.ProjectAdded(document.ProjectInternal.HostProject); - updater.DocumentAdded(document.ProjectInternal.Key, document.State.HostDocument, textLoader); - }); - - // Act - 1 - var result = cache.TryGetDocumentVersion(document, out _); - - // Assert - 1 - Assert.True(result); - - // Act - 2 - await projectManager.UpdateAsync(updater => - updater.DocumentClosed(document.ProjectInternal.HostProject.Key, document.State.HostDocument.FilePath, textLoader)); - result = cache.TryGetDocumentVersion(document, out var version); - - // Assert - 2 - Assert.False(result); - Assert.Null(version); - } - - [Fact] - public void TrackDocumentVersion_AddsFirstEntry() - { - // Arrange - var projectManager = CreateProjectSnapshotManager(); - var cache = new DocumentVersionCache(projectManager); - var cacheAccessor = cache.GetTestAccessor(); - var document = TestDocumentSnapshot.Create("C:/file.cshtml"); - - // Act - cache.TrackDocumentVersion(document, 1337); - - // Assert - var entries = cacheAccessor.GetEntries(); - var (filePath, entry) = Assert.Single(entries); - Assert.Equal(document.FilePath, filePath); - var (actualDocument, actualVersion) = Assert.Single(entry); - Assert.Same(document, actualDocument); - Assert.Equal(1337, actualVersion); - } - - [Fact] - public void TrackDocumentVersion_EvictsOldEntries() - { - // Arrange - var projectManager = CreateProjectSnapshotManager(); - var cache = new DocumentVersionCache(projectManager); - var cacheAccessor = cache.GetTestAccessor(); - var document = TestDocumentSnapshot.Create("C:/file.cshtml"); - - for (var i = 0; i < DocumentVersionCache.MaxDocumentTrackingCount; i++) - { - cache.TrackDocumentVersion(document, i); - } - - // Act - cache.TrackDocumentVersion(document, 1337); - - // Assert - var (_, entry) = Assert.Single(cacheAccessor.GetEntries()); - Assert.Equal(DocumentVersionCache.MaxDocumentTrackingCount, entry.Length); - Assert.Equal(1337, entry[^1].Version); - } - - [Fact] - public void TryGetDocumentVersion_UntrackedDocumentPath_ReturnsFalse() - { - // Arrange - var projectManager = CreateProjectSnapshotManager(); - var cache = new DocumentVersionCache(projectManager); - var document = TestDocumentSnapshot.Create("C:/file.cshtml"); - - // Act - var result = cache.TryGetDocumentVersion(document, out var version); - - // Assert - Assert.False(result); - Assert.Null(version); - } - - [Fact] - public void TryGetDocumentVersion_EvictedDocument_ReturnsFalse() - { - // Arrange - var projectManager = CreateProjectSnapshotManager(); - var cache = new DocumentVersionCache(projectManager); - var document = TestDocumentSnapshot.Create("C:/file.cshtml"); - var evictedDocument = TestDocumentSnapshot.Create(document.FilePath); - cache.TrackDocumentVersion(document, 1337); - - // Act - var result = cache.TryGetDocumentVersion(evictedDocument, out var version); - - // Assert - Assert.False(result); - Assert.Null(version); - } - - [Fact] - public void TryGetDocumentVersion_KnownDocument_ReturnsTrue() - { - // Arrange - var projectManager = CreateProjectSnapshotManager(); - var cache = new DocumentVersionCache(projectManager); - var document = TestDocumentSnapshot.Create("C:/file.cshtml"); - cache.TrackDocumentVersion(document, 1337); - - // Act - var result = cache.TryGetDocumentVersion(document, out var version); - - // Assert - Assert.True(result); - Assert.Equal(1337, version); - } - - [Fact] - public async Task ProjectSnapshotManager_KnownDocumentAdded_TracksNewDocument() - { - // Arrange - var projectManager = CreateProjectSnapshotManager(); - var cache = new DocumentVersionCache(projectManager); - var cacheAccessor = cache.GetTestAccessor(); - - var project1 = TestProjectSnapshot.Create( - "C:/path/to/project1.csproj", - intermediateOutputPath: "C:/path/to/obj1", - documentFilePaths: [], - RazorConfiguration.Default, - projectWorkspaceState: null); - - var document1 = await projectManager.UpdateAsync(updater => - { - updater.ProjectAdded(project1.HostProject); - return updater.CreateAndAddDocument(project1, @"C:\path\to\file.razor"); - }); - - // Act - cache.TrackDocumentVersion(document1, 1337); - - // Assert - var (filePath, entries) = Assert.Single(cacheAccessor.GetEntries()); - Assert.Equal(document1.FilePath, filePath); - var (actualDocument, actualVersion) = Assert.Single(entries); - Assert.Same(document1, actualDocument); - Assert.Equal(1337, actualVersion); - - // Act II - var project2 = TestProjectSnapshot.Create( - "C:/path/to/project2.csproj", - intermediateOutputPath: "C:/path/to/obj2", - documentFilePaths: [], - RazorConfiguration.Default, - projectWorkspaceState: null); - - var document2 = await projectManager.UpdateAsync(updater => - { - updater.ProjectAdded(project2.HostProject); - updater.CreateAndAddDocument(project2, @"C:\path\to\file.razor"); - - return updater - .GetLoadedProject(project2.Key) - .GetDocument(document1.FilePath); - }); - - // Assert II - (filePath, entries) = Assert.Single(cacheAccessor.GetEntries()); - Assert.Equal(document1.FilePath, filePath); - Assert.Equal(2, entries.Length); - - // Should still be tracking document 1 with no changes - (actualDocument, actualVersion) = entries[0]; - Assert.Same(document1, actualDocument); - Assert.Equal(1337, actualVersion); - - (actualDocument, actualVersion) = entries[1]; - Assert.Same(document2, actualDocument); - Assert.Equal(1337, actualVersion); - } -} diff --git a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/Formatting_NetFx/FormattingTestBase.cs b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/Formatting_NetFx/FormattingTestBase.cs index 112e7ae0016..b785c9fadc0 100644 --- a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/Formatting_NetFx/FormattingTestBase.cs +++ b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/Formatting_NetFx/FormattingTestBase.cs @@ -76,7 +76,7 @@ private async Task RunFormattingTestAsync(string input, string expected, int tab InsertSpaces = insertSpaces, }; - var formattingService = await TestRazorFormattingService.CreateWithFullSupportAsync(LoggerFactory, codeDocument, documentSnapshot, razorLSPOptions); + var formattingService = await TestRazorFormattingService.CreateWithFullSupportAsync(LoggerFactory, codeDocument, razorLSPOptions); var documentContext = new VersionedDocumentContext(uri, documentSnapshot, projectContext: null, version: 1); // Act @@ -120,8 +120,7 @@ private protected async Task RunOnTypeFormattingTestAsync( filePathService, new TestDocumentContextFactory(), LoggerFactory); var languageKind = mappingService.GetLanguageKind(codeDocument, positionAfterTrigger, rightAssociative: false); - var formattingService = await TestRazorFormattingService.CreateWithFullSupportAsync( - LoggerFactory, codeDocument, documentSnapshot, razorLSPOptions); + var formattingService = await TestRazorFormattingService.CreateWithFullSupportAsync(LoggerFactory, codeDocument, razorLSPOptions); var options = new FormattingOptions() { TabSize = tabSize, diff --git a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/Formatting_NetFx/TestRazorFormattingService.cs b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/Formatting_NetFx/TestRazorFormattingService.cs index 12c22645152..4aeed2f02c1 100644 --- a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/Formatting_NetFx/TestRazorFormattingService.cs +++ b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/Formatting_NetFx/TestRazorFormattingService.cs @@ -21,7 +21,6 @@ internal static class TestRazorFormattingService public static async Task CreateWithFullSupportAsync( ILoggerFactory loggerFactory, RazorCodeDocument? codeDocument = null, - IDocumentSnapshot? documentSnapshot = null, RazorLSPOptions? razorLSPOptions = null) { codeDocument ??= TestRazorCodeDocument.CreateEmpty(); @@ -30,11 +29,6 @@ public static async Task CreateWithFullSupportAsync( var mappingService = new LspDocumentMappingService(filePathService, new TestDocumentContextFactory(), loggerFactory); var projectManager = StrictMock.Of(); - var versionCache = new DocumentVersionCache(projectManager); - if (documentSnapshot is not null) - { - versionCache.TrackDocumentVersion(documentSnapshot, version: 1); - } var client = new FormattingLanguageServerClient(loggerFactory); client.AddCodeDocument(codeDocument); @@ -54,7 +48,7 @@ public static async Task CreateWithFullSupportAsync( var passes = new List() { - new HtmlFormattingPass(mappingService, client, versionCache, loggerFactory), + new HtmlFormattingPass(mappingService, client, loggerFactory), new CSharpFormattingPass(mappingService, loggerFactory), new CSharpOnTypeFormattingPass(mappingService, loggerFactory), new RazorFormattingPass(mappingService, optionsMonitor), diff --git a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/GeneratedDocumentSynchronizerTest.cs b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/GeneratedDocumentSynchronizerTest.cs index cd462b579ec..5ae7ee253ca 100644 --- a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/GeneratedDocumentSynchronizerTest.cs +++ b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/GeneratedDocumentSynchronizerTest.cs @@ -3,7 +3,6 @@ using Microsoft.AspNetCore.Razor.Language; using Microsoft.AspNetCore.Razor.ProjectSystem; -using Microsoft.AspNetCore.Razor.Test.Common; using Microsoft.AspNetCore.Razor.Test.Common.LanguageServer; using Microsoft.AspNetCore.Razor.Test.Common.ProjectSystem; using Microsoft.AspNetCore.Razor.Test.Common.Workspaces; @@ -16,7 +15,6 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer; public class GeneratedDocumentSynchronizerTest : LanguageServerTestBase { - private readonly DocumentVersionCache _cache; private readonly GeneratedDocumentSynchronizer _synchronizer; private readonly TestGeneratedDocumentPublisher _publisher; private readonly IDocumentSnapshot _document; @@ -25,10 +23,8 @@ public class GeneratedDocumentSynchronizerTest : LanguageServerTestBase public GeneratedDocumentSynchronizerTest(ITestOutputHelper testOutput) : base(testOutput) { - var projectManager = StrictMock.Of(); - _cache = new DocumentVersionCache(projectManager); _publisher = new TestGeneratedDocumentPublisher(); - _synchronizer = new GeneratedDocumentSynchronizer(_publisher, _cache, TestLanguageServerFeatureOptions.Instance); + _synchronizer = new GeneratedDocumentSynchronizer(_publisher, TestLanguageServerFeatureOptions.Instance); _document = TestDocumentSnapshot.Create("C:/path/to/file.razor"); _codeDocument = CreateCodeDocument("

Hello World

"); } @@ -49,9 +45,6 @@ public void DocumentProcessed_UnknownVersion_Noops() [Fact] public void DocumentProcessed_KnownVersion_Publishes() { - // Arrange - _cache.TrackDocumentVersion(_document, version: 1337); - // Act _synchronizer.DocumentProcessed(_codeDocument, _document); diff --git a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/RazorComponentSearchEngineTest.cs b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/RazorComponentSearchEngineTest.cs index 453c64f7064..3fd1cbf2fb6 100644 --- a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/RazorComponentSearchEngineTest.cs +++ b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/RazorComponentSearchEngineTest.cs @@ -48,8 +48,6 @@ protected override async Task InitializeAsync() { _projectManager = CreateProjectSnapshotManager(); - var documentVersionCache = new DocumentVersionCache(_projectManager); - var remoteTextLoaderFactoryMock = new StrictMock(); remoteTextLoaderFactoryMock .Setup(x => x.Create(It.IsAny())) @@ -65,7 +63,6 @@ protected override async Task InitializeAsync() var projectService = new TestRazorProjectService( remoteTextLoaderFactoryMock.Object, - documentVersionCache, _projectManager, LoggerFactory); diff --git a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/RazorProjectServiceTest.cs b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/RazorProjectServiceTest.cs index 0802a4cf61d..25555ab946a 100644 --- a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/RazorProjectServiceTest.cs +++ b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/RazorProjectServiceTest.cs @@ -32,7 +32,6 @@ public class RazorProjectServiceTest(ITestOutputHelper testOutput) : LanguageSer // Each of these is initialized by InitializeAsync() below. #nullable disable private TestProjectSnapshotManager _projectManager; - private DocumentVersionCache _documentVersionCache; private TestRazorProjectService _projectService; #nullable enable @@ -41,7 +40,6 @@ protected override Task InitializeAsync() var optionsMonitor = TestRazorLSPOptionsMonitor.Create(); var projectEngineFactoryProvider = new LspProjectEngineFactoryProvider(optionsMonitor); _projectManager = CreateProjectSnapshotManager(projectEngineFactoryProvider); - _documentVersionCache = new DocumentVersionCache(_projectManager); var remoteTextLoaderFactoryMock = new StrictMock(); remoteTextLoaderFactoryMock @@ -50,7 +48,6 @@ protected override Task InitializeAsync() _projectService = new TestRazorProjectService( remoteTextLoaderFactoryMock.Object, - _documentVersionCache, _projectManager, LoggerFactory); @@ -850,14 +847,8 @@ public async Task RemoveDocument_RemovesDocumentFromMiscellaneousProject() public async Task RemoveDocument_NoopsIfOwnerProjectDoesNotContainDocument() { // Arrange - const string ProjectFilePath = "C:/path/to/project.csproj"; - const string IntermediateOutputPath = "C:/path/to/obj"; - const string RootNamespace = "TestRootNamespace"; const string DocumentFilePath = "C:/path/to/document.cshtml"; - var ownerProjectKey = await _projectService.AddProjectAsync( - ProjectFilePath, IntermediateOutputPath, RazorConfiguration.Default, RootNamespace, displayName: null, DisposalToken); - using var listener = _projectManager.ListenToNotifications(); // Act @@ -998,7 +989,7 @@ public async Task UpdateDocument_TracksKnownDocumentVersion() listener.AssertNotifications( x => x.DocumentChanged(DocumentFilePath, ownerProject.Key)); - var latestVersion = _documentVersionCache.GetLatestDocumentVersion(DocumentFilePath); + var latestVersion = _projectManager.GetLoadedProject(ownerProjectKey).GetDocument(DocumentFilePath)!.Version;// _documentVersionCache.GetLatestDocumentVersion(DocumentFilePath); Assert.Equal(43, latestVersion); } diff --git a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/Refactoring/RenameEndpointTest.cs b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/Refactoring/RenameEndpointTest.cs index 3aa916de91a..8792aeca17a 100644 --- a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/Refactoring/RenameEndpointTest.cs +++ b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/Refactoring/RenameEndpointTest.cs @@ -625,8 +625,7 @@ public async Task Handle_Rename_SingleServer_DoesNotDelegateForRazor() var projectManager = CreateProjectSnapshotManager(); - var documentVersionCache = new DocumentVersionCache(projectManager); - var documentContextFactory = new DocumentContextFactory(projectManager, documentVersionCache, LoggerFactory); + var documentContextFactory = new DocumentContextFactory(projectManager, LoggerFactory); var remoteTextLoaderFactoryMock = new StrictMock(); remoteTextLoaderFactoryMock @@ -643,7 +642,6 @@ public async Task Handle_Rename_SingleServer_DoesNotDelegateForRazor() var projectService = new TestRazorProjectService( remoteTextLoaderFactoryMock.Object, - documentVersionCache, projectManager, LoggerFactory); diff --git a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/TestRazorProjectService.cs b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/TestRazorProjectService.cs index f0acf1af497..e4f29f50c72 100644 --- a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/TestRazorProjectService.cs +++ b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/TestRazorProjectService.cs @@ -19,13 +19,11 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.ProjectSystem; internal class TestRazorProjectService( RemoteTextLoaderFactory remoteTextLoaderFactory, - IDocumentVersionCache documentVersionCache, IProjectSnapshotManager projectManager, ILoggerFactory loggerFactory) : RazorProjectService( projectManager, CreateProjectInfoDriver(), - documentVersionCache, remoteTextLoaderFactory, loggerFactory) { diff --git a/src/Razor/test/Microsoft.AspNetCore.Razor.Test.Common.Tooling/ProjectSystem/TestDocumentSnapshot.cs b/src/Razor/test/Microsoft.AspNetCore.Razor.Test.Common.Tooling/ProjectSystem/TestDocumentSnapshot.cs index 707786555aa..a419a5bff05 100644 --- a/src/Razor/test/Microsoft.AspNetCore.Razor.Test.Common.Tooling/ProjectSystem/TestDocumentSnapshot.cs +++ b/src/Razor/test/Microsoft.AspNetCore.Razor.Test.Common.Tooling/ProjectSystem/TestDocumentSnapshot.cs @@ -41,6 +41,7 @@ public static TestDocumentSnapshot Create(string filePath, string text, VersionS hostDocument, SourceText.From(text), version, + 1, () => Task.FromResult(TextAndVersion.Create(sourceText, version))); var testDocument = new TestDocumentSnapshot(projectSnapshot, documentState); @@ -64,6 +65,7 @@ internal static TestDocumentSnapshot Create(ProjectSnapshot projectSnapshot, str hostDocument, SourceText.From(text), version, + 1, () => Task.FromResult(TextAndVersion.Create(sourceText, version.Value))); var testDocument = new TestDocumentSnapshot(projectSnapshot, documentState); diff --git a/src/Razor/test/Microsoft.CodeAnalysis.Razor.Workspaces.Test/ProjectSystem/ProjectStateTest.cs b/src/Razor/test/Microsoft.CodeAnalysis.Razor.Workspaces.Test/ProjectSystem/ProjectStateTest.cs index 77fd4a8f7b2..3cc38fe40d3 100644 --- a/src/Razor/test/Microsoft.CodeAnalysis.Razor.Workspaces.Test/ProjectSystem/ProjectStateTest.cs +++ b/src/Razor/test/Microsoft.CodeAnalysis.Razor.Workspaces.Test/ProjectSystem/ProjectStateTest.cs @@ -1026,7 +1026,7 @@ private TestDocumentState( Action? onConfigurationChange, Action? onImportsChange, Action? onProjectWorkspaceStateChange) - : base(hostDocument, text, version, loader) + : base(hostDocument, text, version, 1, loader) { _onTextChange = onTextChange; _onTextLoaderChange = onTextLoaderChange; From 032f7ca74d3d3938665adc69327812682f6bfccc Mon Sep 17 00:00:00 2001 From: David Wengier Date: Mon, 24 Jun 2024 17:20:11 +1000 Subject: [PATCH 03/16] Semantic tokens tweaks fixup semantic tokens tweask --- .../ProvideSemanticTokensRangesParams.cs | 4 +- .../AbstractRazorSemanticTokensInfoService.cs | 2 + .../Endpoints/RazorCustomMessageTarget.cs | 2 +- ...RazorCustomMessageTarget_SemanticTokens.cs | 51 +++++-------------- .../RazorCSharpInterceptionMiddleLayer.cs | 11 ++-- 5 files changed, 22 insertions(+), 48 deletions(-) diff --git a/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Protocol/SemanticTokens/ProvideSemanticTokensRangesParams.cs b/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Protocol/SemanticTokens/ProvideSemanticTokensRangesParams.cs index 73e62bf91db..b1f7082ecbe 100644 --- a/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Protocol/SemanticTokens/ProvideSemanticTokensRangesParams.cs +++ b/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Protocol/SemanticTokens/ProvideSemanticTokensRangesParams.cs @@ -11,7 +11,7 @@ namespace Microsoft.CodeAnalysis.Razor.Workspaces.Protocol.SemanticTokens; internal class ProvideSemanticTokensRangesParams : SemanticTokensParams { [JsonPropertyName("requiredHostDocumentVersion")] - public long RequiredHostDocumentVersion { get; } + public int RequiredHostDocumentVersion { get; } [JsonPropertyName("ranges")] public Range[] Ranges { get; } @@ -19,7 +19,7 @@ internal class ProvideSemanticTokensRangesParams : SemanticTokensParams [JsonPropertyName("correlationId")] public Guid CorrelationId { get; } - public ProvideSemanticTokensRangesParams(TextDocumentIdentifier textDocument, long requiredHostDocumentVersion, Range[] ranges, Guid correlationId) + public ProvideSemanticTokensRangesParams(TextDocumentIdentifier textDocument, int requiredHostDocumentVersion, Range[] ranges, Guid correlationId) { TextDocument = textDocument; RequiredHostDocumentVersion = requiredHostDocumentVersion; diff --git a/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/SemanticTokens/AbstractRazorSemanticTokensInfoService.cs b/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/SemanticTokens/AbstractRazorSemanticTokensInfoService.cs index 712506f4e53..0acf4494658 100644 --- a/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/SemanticTokens/AbstractRazorSemanticTokensInfoService.cs +++ b/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/SemanticTokens/AbstractRazorSemanticTokensInfoService.cs @@ -170,6 +170,8 @@ private static ImmutableArray CombineSemanticRanges(ImmutableArra csharpRanges = [csharpRange]; } + _logger.LogDebug($"Requesting C# semantic tokens for host version {documentContext.Version}, correlation ID {correlationId}, and the server thinks there are {codeDocument.GetCSharpSourceText().Lines.Count} lines of C#"); + var csharpResponse = await _csharpSemanticTokensProvider.GetCSharpSemanticTokensResponseAsync(documentContext, csharpRanges, correlationId, cancellationToken).ConfigureAwait(false); // Indicates an issue with retrieving the C# response (e.g. no response or C# is out of sync with us). diff --git a/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/Endpoints/RazorCustomMessageTarget.cs b/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/Endpoints/RazorCustomMessageTarget.cs index c16944aa492..1c52c7fd813 100644 --- a/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/Endpoints/RazorCustomMessageTarget.cs +++ b/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/Endpoints/RazorCustomMessageTarget.cs @@ -136,7 +136,7 @@ private async Task> TrySynchronizeV int requiredHostDocumentVersion, TextDocumentIdentifier hostDocument, CancellationToken cancellationToken, - Range? _ = null, + LanguageServer.Protocol.Range? _ = null, bool rejectOnNewerParallelRequest = true, [CallerMemberName] string? caller = null) where TVirtualDocumentSnapshot : VirtualDocumentSnapshot diff --git a/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/Endpoints/RazorCustomMessageTarget_SemanticTokens.cs b/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/Endpoints/RazorCustomMessageTarget_SemanticTokens.cs index 90656ea4453..15b5ae81682 100644 --- a/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/Endpoints/RazorCustomMessageTarget_SemanticTokens.cs +++ b/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/Endpoints/RazorCustomMessageTarget_SemanticTokens.cs @@ -6,7 +6,6 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; -using Microsoft.AspNetCore.Razor; using Microsoft.CodeAnalysis.Razor.Logging; using Microsoft.CodeAnalysis.Razor.Protocol; using Microsoft.CodeAnalysis.Razor.Workspaces.Protocol.SemanticTokens; @@ -58,18 +57,10 @@ internal partial class RazorCustomMessageTarget SemanticTokensParams requestParams, CancellationToken cancellationToken) { - if (semanticTokensParams is null) - { - throw new ArgumentNullException(nameof(semanticTokensParams)); - } - - if (semanticTokensParams.Ranges is null) - { - throw new ArgumentNullException(nameof(semanticTokensParams.Ranges)); - } + _logger.LogDebug($"Semantic tokens request for {semanticTokensParams.Ranges.Max(r => r.End.Line)} max line number, host version {semanticTokensParams.RequiredHostDocumentVersion}, correlation ID {semanticTokensParams.CorrelationId}"); var (synchronized, csharpDoc) = await TrySynchronizeVirtualDocumentAsync( - (int)semanticTokensParams.RequiredHostDocumentVersion, + semanticTokensParams.RequiredHostDocumentVersion, semanticTokensParams.TextDocument, cancellationToken, semanticTokensParams.Ranges.FirstOrDefault()); @@ -79,30 +70,6 @@ internal partial class RazorCustomMessageTarget return null; } - if (synchronized && csharpDoc.HostDocumentSyncVersion == 1) - { - // HACK: Workaround for https://github.com/dotnet/razor/issues/9197 to stop Roslyn NFWs - // Sometimes we get asked for semantic tokens on v1, and we have sent a v1 to Roslyn, but its the wrong v1. - // To prevent Roslyn throwing, let's validate the range we're asking about with the generated document they - // would have seen. - var lastGeneratedDocumentLine = requestParams switch - { - SemanticTokensRangeParams range => range.Range.End.Line, - SemanticTokensRangesParams ranges => ranges.Ranges[^1].End.Line, - _ => Assumed.Unreachable() - }; - - if (csharpDoc.Snapshot.LineCount < lastGeneratedDocumentLine) - { - _logger.LogWarning($"Pretending we're not synced because we're asking for line {lastGeneratedDocumentLine} but there are only {csharpDoc.Snapshot.LineCount} lines in the buffer."); - Debug.Fail("Rejecting!"); - // We report this as a fail to synchronize, as that's essentially what it is: We were asked for v1, with X lines - // and whilst we have v1, we don't have X lines, so we need to wait for a future update to arrive and give us - // more content. - return new ProvideSemanticTokensResponse(tokens: null, -1); - } - } - if (!synchronized) { // If we're unable to synchronize we won't produce useful results, but we have to indicate @@ -110,15 +77,19 @@ internal partial class RazorCustomMessageTarget return new ProvideSemanticTokensResponse(tokens: null, hostDocumentSyncVersion: csharpDoc.HostDocumentSyncVersion ?? -1); } - semanticTokensParams.TextDocument.Uri = csharpDoc.Uri; + requestParams.TextDocument.Uri = csharpDoc.Uri; var textBuffer = csharpDoc.Snapshot.TextBuffer; + _logger.LogDebug($"Requesting semantic tokens for {csharpDoc.Uri}, for buffer version {textBuffer.CurrentSnapshot.Version.VersionNumber} and snapshot version {csharpDoc.Snapshot.Version.VersionNumber}, host version {semanticTokensParams.RequiredHostDocumentVersion}, correlation ID {semanticTokensParams.CorrelationId}"); + cancellationToken.ThrowIfCancellationRequested(); var languageServerName = RazorLSPConstants.RazorCSharpLanguageServerName; SemanticTokens? response; using (var disposable = _telemetryReporter.TrackLspRequest(lspMethodName, languageServerName, semanticTokensParams.CorrelationId)) { + try + { var result = await _requestInvoker.ReinvokeRequestOnServerAsync( textBuffer, lspMethodName, @@ -126,7 +97,13 @@ internal partial class RazorCustomMessageTarget requestParams, cancellationToken).ConfigureAwait(false); - response = result?.Response; + response = result?.Response; + } + catch + { + _logger.LogWarning($"Error getting semantic tokens from Roslyn for host version {semanticTokensParams.RequiredHostDocumentVersion}, correlation ID {semanticTokensParams.CorrelationId}"); + throw; + } } if (response?.Data is null) diff --git a/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/RazorCSharpInterceptionMiddleLayer.cs b/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/RazorCSharpInterceptionMiddleLayer.cs index b2f6692ba35..7a7415f1455 100644 --- a/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/RazorCSharpInterceptionMiddleLayer.cs +++ b/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/RazorCSharpInterceptionMiddleLayer.cs @@ -16,15 +16,10 @@ namespace Microsoft.VisualStudio.Razor.LanguageClient; [Export(typeof(IRazorCSharpInterceptionMiddleLayer))] -internal class RazorCSharpInterceptionMiddleLayer : IRazorCSharpInterceptionMiddleLayer +[method: ImportingConstructor] +internal class RazorCSharpInterceptionMiddleLayer(LSPRequestInvoker requestInvoker) : IRazorCSharpInterceptionMiddleLayer { - private readonly LSPRequestInvoker _requestInvoker; - - [ImportingConstructor] - public RazorCSharpInterceptionMiddleLayer(LSPRequestInvoker requestInvoker) - { - _requestInvoker = requestInvoker; - } + private readonly LSPRequestInvoker _requestInvoker = requestInvoker; public bool CanHandle(string methodName) => methodName.Equals(Methods.WorkspaceSemanticTokensRefreshName); From 97be219f90651dfd5ce56ca92e3f01e65c704e38 Mon Sep 17 00:00:00 2001 From: David Wengier Date: Mon, 24 Jun 2024 17:34:53 +1000 Subject: [PATCH 04/16] Fix tests --- .../DocumentContextFactoryTest.cs | 22 +------------------ .../Formatting_NetFx/FormattingTestBase.cs | 3 +++ .../GeneratedDocumentSynchronizerTest.cs | 13 ----------- .../RazorProjectServiceTest.cs | 6 ++--- 4 files changed, 7 insertions(+), 37 deletions(-) diff --git a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/DocumentContextFactoryTest.cs b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/DocumentContextFactoryTest.cs index 295533b052e..61e48cb7880 100644 --- a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/DocumentContextFactoryTest.cs +++ b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/DocumentContextFactoryTest.cs @@ -54,26 +54,6 @@ public void TryCreateForOpenDocumentAsync_CanNotResolveDocument_ReturnsNull() Assert.False(factory.TryCreateForOpenDocument(uri, out _)); } - [Fact] - public async Task TryCreateForOpenDocumentAsync_CanNotResolveVersion_ReturnsNull() - { - // Arrange - var filePath = FilePathNormalizer.Normalize(Path.Combine(s_baseDirectory, "file.cshtml")); - var uri = new Uri(filePath); - - var hostDocument = new HostDocument(filePath, "file.cshtml"); - - await _projectManager.UpdateAsync(updater => - { - updater.DocumentAdded(MiscFilesHostProject.Instance.Key, hostDocument, TestMocks.CreateTextLoader(filePath, "")); - }); - - var factory = new DocumentContextFactory(_projectManager, LoggerFactory); - - // Act - Assert.False(factory.TryCreateForOpenDocument(uri, out _)); - } - [Fact] public async Task TryCreateAsync_ResolvesContent() { @@ -153,7 +133,7 @@ await _projectManager.UpdateAsync(updater => Assert.True(factory.TryCreateForOpenDocument(uri, out var documentContext)); // Assert - Assert.Equal(1337, documentContext.Version); + Assert.Equal(1, documentContext.Version); Assert.Equal(uri, documentContext.Uri); Assert.Same(documentSnapshot, documentContext.Snapshot); } diff --git a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/Formatting_NetFx/FormattingTestBase.cs b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/Formatting_NetFx/FormattingTestBase.cs index b785c9fadc0..a6089dfe1d8 100644 --- a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/Formatting_NetFx/FormattingTestBase.cs +++ b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/Formatting_NetFx/FormattingTestBase.cs @@ -312,6 +312,9 @@ internal static IDocumentSnapshot CreateDocumentSnapshot(string path, ImmutableA documentSnapshot .Setup(d => d.FileKind) .Returns(fileKind); + documentSnapshot + .Setup(d => d.Version) + .Returns(1); documentSnapshot .Setup(d => d.WithText(It.IsAny())) .Returns(text => diff --git a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/GeneratedDocumentSynchronizerTest.cs b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/GeneratedDocumentSynchronizerTest.cs index 5ae7ee253ca..7805abd04b1 100644 --- a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/GeneratedDocumentSynchronizerTest.cs +++ b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/GeneratedDocumentSynchronizerTest.cs @@ -29,19 +29,6 @@ public GeneratedDocumentSynchronizerTest(ITestOutputHelper testOutput) _codeDocument = CreateCodeDocument("

Hello World

"); } - [Fact] - public void DocumentProcessed_UnknownVersion_Noops() - { - // Arrange - - // Act - _synchronizer.DocumentProcessed(_codeDocument, _document); - - // Assert - Assert.False(_publisher.PublishedCSharp); - Assert.False(_publisher.PublishedHtml); - } - [Fact] public void DocumentProcessed_KnownVersion_Publishes() { diff --git a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/RazorProjectServiceTest.cs b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/RazorProjectServiceTest.cs index 25555ab946a..08ca59d78db 100644 --- a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/RazorProjectServiceTest.cs +++ b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/RazorProjectServiceTest.cs @@ -966,7 +966,7 @@ public async Task UpdateDocument_ChangesDocumentInMiscProject() } [Fact] - public async Task UpdateDocument_TracksKnownDocumentVersion() + public async Task UpdateDocument_DocumentVersionUpdated() { // Arrange const string ProjectFilePath = "C:/path/to/project.csproj"; @@ -989,8 +989,8 @@ public async Task UpdateDocument_TracksKnownDocumentVersion() listener.AssertNotifications( x => x.DocumentChanged(DocumentFilePath, ownerProject.Key)); - var latestVersion = _projectManager.GetLoadedProject(ownerProjectKey).GetDocument(DocumentFilePath)!.Version;// _documentVersionCache.GetLatestDocumentVersion(DocumentFilePath); - Assert.Equal(43, latestVersion); + var latestVersion = _projectManager.GetLoadedProject(ownerProjectKey).GetDocument(DocumentFilePath)!.Version; + Assert.Equal(2, latestVersion); } [Fact] From 162c7d55ba4075b4f894d53d3bb8316e5a02c0d2 Mon Sep 17 00:00:00 2001 From: David Wengier Date: Fri, 9 Aug 2024 15:00:59 +1000 Subject: [PATCH 05/16] Remove unused parameter --- .../DocumentDidChangeEndpoint.cs | 2 +- .../DocumentDidOpenEndpoint.cs | 2 +- .../ProjectSystem/IRazorProjectService.cs | 4 +-- .../ProjectSystem/RazorProjectService.cs | 4 +-- .../DocumentDidChangeEndpointTest.cs | 7 ++-- .../DocumentDidOpenEndpointTest.cs | 5 ++- .../RazorComponentSearchEngineTest.cs | 6 ++-- .../RazorProjectServiceTest.cs | 32 +++++++++---------- .../Refactoring/RenameEndpointTest.cs | 18 +++++------ 9 files changed, 39 insertions(+), 41 deletions(-) diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/DocumentSynchronization/DocumentDidChangeEndpoint.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/DocumentSynchronization/DocumentDidChangeEndpoint.cs index afd1da50b3c..73c66dab4b9 100644 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/DocumentSynchronization/DocumentDidChangeEndpoint.cs +++ b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/DocumentSynchronization/DocumentDidChangeEndpoint.cs @@ -60,7 +60,7 @@ public async Task HandleNotificationAsync(DidChangeTextDocumentParams request, R sourceText = ApplyContentChanges(request.ContentChanges, sourceText); await _projectService - .UpdateDocumentAsync(documentContext.FilePath, sourceText, request.TextDocument.Version, cancellationToken) + .UpdateDocumentAsync(documentContext.FilePath, sourceText, cancellationToken) .ConfigureAwait(false); } diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/DocumentSynchronization/DocumentDidOpenEndpoint.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/DocumentSynchronization/DocumentDidOpenEndpoint.cs index 8af40ddf029..cb07a86ef22 100644 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/DocumentSynchronization/DocumentDidOpenEndpoint.cs +++ b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/DocumentSynchronization/DocumentDidOpenEndpoint.cs @@ -23,6 +23,6 @@ public Task HandleNotificationAsync(DidOpenTextDocumentParams request, RazorRequ var sourceText = SourceText.From(request.TextDocument.Text); return _projectService.OpenDocumentAsync( - request.TextDocument.Uri.GetAbsoluteOrUNCPath(), sourceText, request.TextDocument.Version, cancellationToken); + request.TextDocument.Uri.GetAbsoluteOrUNCPath(), sourceText, cancellationToken); } } diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/ProjectSystem/IRazorProjectService.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/ProjectSystem/IRazorProjectService.cs index e83c8c327f1..942c95985bc 100644 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/ProjectSystem/IRazorProjectService.cs +++ b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/ProjectSystem/IRazorProjectService.cs @@ -14,8 +14,8 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.ProjectSystem; internal interface IRazorProjectService { Task AddDocumentToMiscProjectAsync(string filePath, CancellationToken cancellationToken); - Task OpenDocumentAsync(string filePath, SourceText sourceText, int version, CancellationToken cancellationToken); - Task UpdateDocumentAsync(string filePath, SourceText sourceText, int version, CancellationToken cancellationToken); + Task OpenDocumentAsync(string filePath, SourceText sourceText, CancellationToken cancellationToken); + Task UpdateDocumentAsync(string filePath, SourceText sourceText, CancellationToken cancellationToken); Task CloseDocumentAsync(string filePath, CancellationToken cancellationToken); Task RemoveDocumentAsync(string filePath, CancellationToken cancellationToken); diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/ProjectSystem/RazorProjectService.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/ProjectSystem/RazorProjectService.cs index 696129efb99..2704661674e 100644 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/ProjectSystem/RazorProjectService.cs +++ b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/ProjectSystem/RazorProjectService.cs @@ -178,7 +178,7 @@ private void AddDocumentToMiscProjectCore(ProjectSnapshotManager.Updater updater updater.DocumentAdded(miscFilesProject.Key, hostDocument, textLoader); } - public async Task OpenDocumentAsync(string filePath, SourceText sourceText, int version, CancellationToken cancellationToken) + public async Task OpenDocumentAsync(string filePath, SourceText sourceText, CancellationToken cancellationToken) { await WaitForInitializationAsync().ConfigureAwait(false); @@ -278,7 +278,7 @@ await _projectManager.UpdateAsync( .ConfigureAwait(false); } - public async Task UpdateDocumentAsync(string filePath, SourceText sourceText, int version, CancellationToken cancellationToken) + public async Task UpdateDocumentAsync(string filePath, SourceText sourceText, CancellationToken cancellationToken) { await WaitForInitializationAsync().ConfigureAwait(false); diff --git a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/DocumentSynchronization/DocumentDidChangeEndpointTest.cs b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/DocumentSynchronization/DocumentDidChangeEndpointTest.cs index baf947911fb..93e144b75a4 100644 --- a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/DocumentSynchronization/DocumentDidChangeEndpointTest.cs +++ b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/DocumentSynchronization/DocumentDidChangeEndpointTest.cs @@ -33,7 +33,7 @@ public void ApplyContentChanges_SingleChange() }; // Act - var result = endpoint.ApplyContentChanges(new[] { change }, sourceText); + var result = endpoint.ApplyContentChanges([change], sourceText); // Assert Assert.Equal("Hello! World", result.ToString()); @@ -98,13 +98,12 @@ public async Task Handle_DidChangeTextDocument_UpdatesDocument() var documentContext = CreateDocumentContext(documentPath, codeDocument); var projectService = new StrictMock(); projectService - .Setup(service => service.UpdateDocumentAsync(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) + .Setup(service => service.UpdateDocumentAsync(It.IsAny(), It.IsAny(), It.IsAny())) .Returns(Task.CompletedTask) - .Callback((string path, SourceText text, int version, CancellationToken cancellationToken) => + .Callback((string path, SourceText text, CancellationToken cancellationToken) => { Assert.Equal("

", text.ToString()); Assert.Equal(documentPath.OriginalString, path); - Assert.Equal(1337, version); }); var endpoint = new DocumentDidChangeEndpoint(projectService.Object, LoggerFactory); var change = new TextDocumentContentChangeEvent() diff --git a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/DocumentSynchronization/DocumentDidOpenEndpointTest.cs b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/DocumentSynchronization/DocumentDidOpenEndpointTest.cs index 4867629a6f9..a2067331373 100644 --- a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/DocumentSynchronization/DocumentDidOpenEndpointTest.cs +++ b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/DocumentSynchronization/DocumentDidOpenEndpointTest.cs @@ -25,13 +25,12 @@ public async Task Handle_DidOpenTextDocument_AddsDocument() var documentPath = "C:/path/to/document.cshtml"; var projectService = new StrictMock(); projectService - .Setup(service => service.OpenDocumentAsync(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) + .Setup(service => service.OpenDocumentAsync(It.IsAny(), It.IsAny(), It.IsAny())) .Returns(Task.CompletedTask) - .Callback((string path, SourceText text, int version, CancellationToken cancellationToken) => + .Callback((string path, SourceText text, CancellationToken cancellationToken) => { Assert.Equal("hello", text.ToString()); Assert.Equal(documentPath, path); - Assert.Equal(1337, version); }); var endpoint = new DocumentDidOpenEndpoint(projectService.Object); var request = new DidOpenTextDocumentParams() diff --git a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/RazorComponentSearchEngineTest.cs b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/RazorComponentSearchEngineTest.cs index 3fd1cbf2fb6..3f372b9f668 100644 --- a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/RazorComponentSearchEngineTest.cs +++ b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/RazorComponentSearchEngineTest.cs @@ -75,10 +75,10 @@ await projectService.AddProjectAsync( DisposalToken); await projectService.AddDocumentToPotentialProjectsAsync(s_componentFilePath1, DisposalToken); - await projectService.UpdateDocumentAsync(s_componentFilePath1, SourceText.From(""), version: 1, DisposalToken); + await projectService.UpdateDocumentAsync(s_componentFilePath1, SourceText.From(""), DisposalToken); await projectService.AddDocumentToPotentialProjectsAsync(s_componentFilePath2, DisposalToken); - await projectService.UpdateDocumentAsync(s_componentFilePath2, SourceText.From("@namespace Test"), version: 1, DisposalToken); + await projectService.UpdateDocumentAsync(s_componentFilePath2, SourceText.From("@namespace Test"), DisposalToken); await projectService.AddProjectAsync( s_projectFilePath2, @@ -89,7 +89,7 @@ await projectService.AddProjectAsync( DisposalToken); await projectService.AddDocumentToPotentialProjectsAsync(s_componentFilePath3, DisposalToken); - await projectService.UpdateDocumentAsync(s_componentFilePath3, SourceText.From(""), version: 1, DisposalToken); + await projectService.UpdateDocumentAsync(s_componentFilePath3, SourceText.From(""), DisposalToken); } [Fact] diff --git a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/RazorProjectServiceTest.cs b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/RazorProjectServiceTest.cs index 08ca59d78db..ba7e5d7563e 100644 --- a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/RazorProjectServiceTest.cs +++ b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/RazorProjectServiceTest.cs @@ -475,7 +475,7 @@ public async Task CloseDocument_ClosesDocumentInOwnerProject() var ownerProjectKey = await _projectService.AddProjectAsync( ProjectFilePath, IntermediateOutputPath, RazorConfiguration.Default, RootNamespace, displayName: null, DisposalToken); await _projectService.AddDocumentToPotentialProjectsAsync(DocumentFilePath, DisposalToken); - await _projectService.OpenDocumentAsync(DocumentFilePath, s_emptyText, version: 42, DisposalToken); + await _projectService.OpenDocumentAsync(DocumentFilePath, s_emptyText, DisposalToken); var ownerProject = _projectManager.GetLoadedProject(ownerProjectKey); @@ -508,7 +508,7 @@ public async Task CloseDocument_ClosesDocumentInAllOwnerProjects() var ownerProjectKey2 = await _projectService.AddProjectAsync( ProjectFilePath, IntermediateOutputPath2, RazorConfiguration.Default, RootNamespace, displayName: null, DisposalToken); await _projectService.AddDocumentToPotentialProjectsAsync(DocumentFilePath, DisposalToken); - await _projectService.OpenDocumentAsync(DocumentFilePath, s_emptyText, version: 42, DisposalToken); + await _projectService.OpenDocumentAsync(DocumentFilePath, s_emptyText, DisposalToken); var ownerProject1 = _projectManager.GetLoadedProject(ownerProjectKey1); var ownerProject2 = _projectManager.GetLoadedProject(ownerProjectKey2); @@ -535,7 +535,7 @@ public async Task CloseDocument_ClosesDocumentInMiscellaneousProject() const string DocumentFilePath = "document.cshtml"; await _projectService.AddDocumentToPotentialProjectsAsync(DocumentFilePath, DisposalToken); - await _projectService.OpenDocumentAsync(DocumentFilePath, s_emptyText, version: 42, DisposalToken); + await _projectService.OpenDocumentAsync(DocumentFilePath, s_emptyText, DisposalToken); var miscProject = _projectManager.GetMiscellaneousProject(); @@ -573,7 +573,7 @@ public async Task OpenDocument_OpensAlreadyAddedDocumentInOwnerProject() using var listener = _projectManager.ListenToNotifications(); // Act - await _projectService.OpenDocumentAsync(DocumentFilePath, SourceText.From("Hello World"), version: 42, DisposalToken); + await _projectService.OpenDocumentAsync(DocumentFilePath, SourceText.From("Hello World"), DisposalToken); // Assert listener.AssertNotifications( @@ -606,7 +606,7 @@ public async Task OpenDocument_OpensAlreadyAddedDocumentInAllOwnerProjects() using var listener = _projectManager.ListenToNotifications(); // Act - await _projectService.OpenDocumentAsync(DocumentFilePath, SourceText.From("Hello World"), version: 42, DisposalToken); + await _projectService.OpenDocumentAsync(DocumentFilePath, SourceText.From("Hello World"), DisposalToken); // Assert listener.AssertNotifications( @@ -631,7 +631,7 @@ public async Task OpenDocument_OpensAlreadyAddedDocumentInMiscellaneousProject() using var listener = _projectManager.ListenToNotifications(); // Act - await _projectService.OpenDocumentAsync(DocumentFilePath, s_emptyText, version: 42, DisposalToken); + await _projectService.OpenDocumentAsync(DocumentFilePath, s_emptyText, DisposalToken); // Assert listener.AssertNotifications( @@ -657,7 +657,7 @@ public async Task OpenDocument_OpensAndAddsDocumentToMiscellaneousProject() using var listener = _projectManager.ListenToNotifications(); // Act - await _projectService.OpenDocumentAsync(DocumentFilePath, SourceText.From("Hello World"), version: 42, DisposalToken); + await _projectService.OpenDocumentAsync(DocumentFilePath, SourceText.From("Hello World"), DisposalToken); // Assert listener.AssertNotifications( @@ -801,7 +801,7 @@ public async Task RemoveOpenDocument_RemovesDocumentFromOwnerProject_MovesToMisc var ownerProjectKey = await _projectService.AddProjectAsync( ProjectFilePath, IntermediateOutputPath, RazorConfiguration.Default, RootNamespace, displayName: null, DisposalToken); await _projectService.AddDocumentToPotentialProjectsAsync(DocumentFilePath, DisposalToken); - await _projectService.OpenDocumentAsync(DocumentFilePath, s_emptyText, version: 42, DisposalToken); + await _projectService.OpenDocumentAsync(DocumentFilePath, s_emptyText, DisposalToken); var ownerProject = _projectManager.GetLoadedProject(ownerProjectKey); var miscProject = _projectManager.GetMiscellaneousProject(); @@ -887,7 +887,7 @@ public async Task UpdateDocument_ChangesDocumentInOwnerProject() var ownerProjectKey = await _projectService.AddProjectAsync( ProjectFilePath, IntermediateOutputPath, RazorConfiguration.Default, RootNamespace, displayName: null, DisposalToken); await _projectService.AddDocumentToPotentialProjectsAsync(DocumentFilePath, DisposalToken); - await _projectService.OpenDocumentAsync(DocumentFilePath, s_emptyText, version: 42, DisposalToken); + await _projectService.OpenDocumentAsync(DocumentFilePath, s_emptyText, DisposalToken); var ownerProject = _projectManager.GetLoadedProject(ownerProjectKey); @@ -896,7 +896,7 @@ public async Task UpdateDocument_ChangesDocumentInOwnerProject() using var listener = _projectManager.ListenToNotifications(); // Act - await _projectService.UpdateDocumentAsync(DocumentFilePath, s_emptyText.Replace(0, 0, "Hello World"), version: 43, DisposalToken); + await _projectService.UpdateDocumentAsync(DocumentFilePath, s_emptyText.Replace(0, 0, "Hello World"), DisposalToken); // Assert listener.AssertNotifications( @@ -920,7 +920,7 @@ public async Task UpdateDocument_ChangesDocumentInAllOwnerProjects() var ownerProjectKey2 = await _projectService.AddProjectAsync( ProjectFilePath, IntermediateOutputPath2, RazorConfiguration.Default, RootNamespace, displayName: null, DisposalToken); await _projectService.AddDocumentToPotentialProjectsAsync(DocumentFilePath, DisposalToken); - await _projectService.OpenDocumentAsync(DocumentFilePath, s_emptyText, version: 42, DisposalToken); + await _projectService.OpenDocumentAsync(DocumentFilePath, s_emptyText, DisposalToken); var ownerProject1 = _projectManager.GetLoadedProject(ownerProjectKey1); var ownerProject2 = _projectManager.GetLoadedProject(ownerProjectKey2); @@ -930,7 +930,7 @@ public async Task UpdateDocument_ChangesDocumentInAllOwnerProjects() using var listener = _projectManager.ListenToNotifications(); // Act - await _projectService.UpdateDocumentAsync(DocumentFilePath, s_emptyText.Replace(0, 0, "Hello World"), version: 43, DisposalToken); + await _projectService.UpdateDocumentAsync(DocumentFilePath, s_emptyText.Replace(0, 0, "Hello World"), DisposalToken); // Assert listener.AssertNotifications( @@ -947,7 +947,7 @@ public async Task UpdateDocument_ChangesDocumentInMiscProject() const string DocumentFilePath = "document.cshtml"; await _projectService.AddDocumentToPotentialProjectsAsync(DocumentFilePath, DisposalToken); - await _projectService.OpenDocumentAsync(DocumentFilePath, s_emptyText, version: 42, DisposalToken); + await _projectService.OpenDocumentAsync(DocumentFilePath, s_emptyText, DisposalToken); var miscProject = _projectManager.GetMiscellaneousProject(); @@ -956,7 +956,7 @@ public async Task UpdateDocument_ChangesDocumentInMiscProject() using var listener = _projectManager.ListenToNotifications(); // Act - await _projectService.UpdateDocumentAsync(DocumentFilePath, s_emptyText.Replace(0, 0, "Hello World"), version: 43, DisposalToken); + await _projectService.UpdateDocumentAsync(DocumentFilePath, s_emptyText.Replace(0, 0, "Hello World"), DisposalToken); // Assert listener.AssertNotifications( @@ -983,7 +983,7 @@ public async Task UpdateDocument_DocumentVersionUpdated() using var listener = _projectManager.ListenToNotifications(); // Act - await _projectService.UpdateDocumentAsync(DocumentFilePath, s_emptyText.Replace(0, 0, "Hello World"), version: 43, DisposalToken); + await _projectService.UpdateDocumentAsync(DocumentFilePath, s_emptyText.Replace(0, 0, "Hello World"), DisposalToken); // Assert listener.AssertNotifications( @@ -1008,7 +1008,7 @@ await _projectService.AddProjectAsync( // Act await Assert.ThrowsAnyAsync(() => { - return _projectService.UpdateDocumentAsync(DocumentFilePath, s_emptyText.Replace(0, 0, "Hello World"), version: 43, DisposalToken); + return _projectService.UpdateDocumentAsync(DocumentFilePath, s_emptyText.Replace(0, 0, "Hello World"), DisposalToken); }); } diff --git a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/Refactoring/RenameEndpointTest.cs b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/Refactoring/RenameEndpointTest.cs index 8792aeca17a..7f5a35cd276 100644 --- a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/Refactoring/RenameEndpointTest.cs +++ b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/Refactoring/RenameEndpointTest.cs @@ -660,12 +660,12 @@ await projectManager.UpdateAsync(updater => await projectService.AddDocumentToPotentialProjectsAsync(s_componentFilePath1337, DisposalToken); await projectService.AddDocumentToPotentialProjectsAsync(s_indexFilePath1, DisposalToken); - await projectService.UpdateDocumentAsync(s_componentFilePath1, SourceText.From(ComponentText1), version: 42, DisposalToken); - await projectService.UpdateDocumentAsync(s_componentFilePath2, SourceText.From(ComponentText2), version: 42, DisposalToken); - await projectService.UpdateDocumentAsync(s_directoryFilePath1, SourceText.From(DirectoryText1), version: 42, DisposalToken); - await projectService.UpdateDocumentAsync(s_directoryFilePath2, SourceText.From(DirectoryText2), version: 4, DisposalToken); - await projectService.UpdateDocumentAsync(s_componentFilePath1337, SourceText.From(ComponentText1337), version: 42, DisposalToken); - await projectService.UpdateDocumentAsync(s_indexFilePath1, SourceText.From(IndexText1), version: 42, DisposalToken); + await projectService.UpdateDocumentAsync(s_componentFilePath1, SourceText.From(ComponentText1), DisposalToken); + await projectService.UpdateDocumentAsync(s_componentFilePath2, SourceText.From(ComponentText2), DisposalToken); + await projectService.UpdateDocumentAsync(s_directoryFilePath1, SourceText.From(DirectoryText1), DisposalToken); + await projectService.UpdateDocumentAsync(s_directoryFilePath2, SourceText.From(DirectoryText2), DisposalToken); + await projectService.UpdateDocumentAsync(s_componentFilePath1337, SourceText.From(ComponentText1337), DisposalToken); + await projectService.UpdateDocumentAsync(s_indexFilePath1, SourceText.From(IndexText1), DisposalToken); var projectKey2 = await projectService.AddProjectAsync( s_projectFilePath2, s_intermediateOutputPath2, RazorConfiguration.Default, RootNamespace2, displayName: null, DisposalToken); @@ -679,9 +679,9 @@ await projectManager.UpdateAsync(updater => await projectService.AddDocumentToPotentialProjectsAsync(s_componentFilePath4, DisposalToken); await projectService.AddDocumentToPotentialProjectsAsync(s_componentWithParamFilePath, DisposalToken); - await projectService.UpdateDocumentAsync(s_componentFilePath3, SourceText.From(ComponentText3), version: 42, DisposalToken); - await projectService.UpdateDocumentAsync(s_componentFilePath4, SourceText.From(ComponentText4), version: 42, DisposalToken); - await projectService.UpdateDocumentAsync(s_componentWithParamFilePath, SourceText.From(ComponentWithParamText), version: 42, DisposalToken); + await projectService.UpdateDocumentAsync(s_componentFilePath3, SourceText.From(ComponentText3), DisposalToken); + await projectService.UpdateDocumentAsync(s_componentFilePath4, SourceText.From(ComponentText4), DisposalToken); + await projectService.UpdateDocumentAsync(s_componentWithParamFilePath, SourceText.From(ComponentWithParamText), DisposalToken); var searchEngine = new RazorComponentSearchEngine(projectManager, LoggerFactory); options ??= StrictMock.Of(o => From 186a134a3bbe0668043e59b74ef2cfe7d03a9cb7 Mon Sep 17 00:00:00 2001 From: David Wengier Date: Mon, 12 Aug 2024 10:35:32 +1000 Subject: [PATCH 06/16] Remove VersionedDocumentContext and the separate methods to create one --- .../RazorCSharpFormattingBenchmark.cs | 2 +- .../RazorCodeActionsBenchmark.cs | 2 +- .../RazorCompletionBenchmark.cs | 4 +- .../RazorDiagnosticsBenchmark.cs | 8 +-- .../RazorSemanticTokensBenchmark.cs | 7 +-- ...zorSemanticTokensRangeEndpointBenchmark.cs | 7 +-- .../RazorSemanticTokensScrollingBenchmark.cs | 4 +- .../CSharp/DefaultCSharpCodeActionResolver.cs | 6 +- ...mattedRemappingCSharpCodeActionResolver.cs | 6 +- .../CodeActions/CodeActionEndpoint.cs | 6 +- .../Html/DefaultHtmlCodeActionResolver.cs | 4 +- .../Razor/GenerateMethodCodeActionResolver.cs | 6 +- .../ColorPresentationEndpoint.cs | 2 +- .../Completion/CompletionListProvider.cs | 2 +- .../DelegatedCompletionItemResolver.cs | 2 +- .../DelegatedCompletionListProvider.cs | 6 +- .../Completion/RazorCompletionListProvider.cs | 2 +- .../DocumentPullDiagnosticsEndpoint.cs | 4 +- .../DocumentColor/DocumentColorEndpoint.cs | 2 +- .../DocumentContextFactory.cs | 48 +--------------- ...actTextDocumentPresentationEndpointBase.cs | 4 +- .../EndpointContracts/RazorRequestContext.cs | 4 +- .../Folding/FoldingRangeEndpoint.cs | 2 +- .../Formatting/IRazorFormattingService.cs | 2 +- .../Formatting/RazorFormattingService.cs | 4 +- .../Hover/HoverService.cs | 4 +- .../Hover/IHoverService.cs | 4 +- .../InlayHints/IInlayHintService.cs | 2 +- .../InlayHints/InlayHintService.cs | 2 +- .../LspEditMappingService.cs | 14 +---- .../MapCode/MapCodeEndpoint.cs | 8 +-- .../Mapping/RazorLanguageQueryEndpoint.cs | 2 +- .../RazorMapToDocumentRangesEndpoint.cs | 4 +- .../RazorRequestContextFactory.cs | 6 +- .../LSPCSharpSemanticTokensProvider.cs | 4 +- .../SpellCheck/DocumentSpellCheckEndpoint.cs | 4 +- .../WrapWithTag/WrapWithTagEndpoint.cs | 2 +- .../AbstractEditMappingService.cs | 14 ++--- .../ProjectSystem/DocumentContext.cs | 4 ++ .../ProjectSystem/IDocumentContextFactory.cs | 1 - .../IDocumentContextFactoryExtensions.cs | 57 +------------------ .../ProjectSystem/VersionedDocumentContext.cs | 17 ------ .../Rename/IRenameService.cs | 2 +- .../Rename/RenameService.cs | 2 +- .../AbstractRazorSemanticTokensInfoService.cs | 10 ++-- .../ICSharpSemanticTokensProvider.cs | 2 +- .../IRazorSemanticTokenInfoService.cs | 2 +- .../RemoteEditMappingService.cs | 10 +--- .../DocumentContextExtensions.cs | 2 +- .../ProjectSystem/RemoteDocumentContext.cs | 6 +- .../ProjectSystem/RemoteDocumentSnapshot.cs | 2 +- .../RemoteCSharpSemanticTokensProvider.cs | 2 +- .../Endpoints/RazorCustomMessageTarget.cs | 16 ------ ...RazorCustomMessageTarget_SemanticTokens.cs | 15 +++-- .../OnAutoInsertEndpointTest.NetFx.cs | 2 +- .../CodeActionEndToEndTest.NetFx.cs | 6 +- .../Completion/CompletionListProviderTest.cs | 8 +-- ...legatedCompletionItemResolverTest.NetFx.cs | 6 +- .../Delegation/ResponseRewriterTestBase.cs | 2 +- .../RazorCompletionListProviderTest.cs | 16 +++--- .../ValidateBreakpointRangeEndpointTest.cs | 4 +- .../DefinitionEndpointDelegationTest.cs | 2 +- .../DocumentContextFactoryTest.cs | 6 +- .../DocumentHighlightEndpointTest.cs | 2 +- ...extDocumentUriPresentationEndpointTests.cs | 8 +-- .../DocumentSymbolEndpointTest.cs | 2 +- .../FindAllReferencesEndpointTest.cs | 2 +- .../Folding/FoldingEndpointTest.cs | 2 +- .../DocumentOnTypeFormattingEndpointTest.cs | 2 +- .../FormattingLanguageServerTestBase.cs | 2 +- .../Formatting_NetFx/FormattingTestBase.cs | 6 +- .../Hover/HoverServiceTest.cs | 7 ++- .../ImplementationEndpointTest.cs | 2 +- .../InlayHints/InlayHintEndpointTest.cs | 2 +- .../MapCode/MapCodeTest.cs | 4 +- .../Mapping/RazorLanguageQueryEndpointTest.cs | 4 -- .../RazorMapToDocumentRangesEndpointTest.cs | 7 --- .../ProjectContextsEndpointTest.cs | 2 +- .../RenameEndpointDelegationTest.cs | 2 +- .../Refactoring/RenameEndpointTest.cs | 26 ++++----- .../Semantic/SemanticTokensTest.cs | 15 ++--- .../SignatureHelpEndpointTest.cs | 2 +- .../SingleServerDelegatingEndpointTestBase.cs | 2 +- .../LanguageServer/LanguageServerTestBase.cs | 12 ++-- .../LanguageServer/TestDocumentContext.cs | 8 +-- .../TestDocumentContextFactory.cs | 17 +----- .../ProjectSystem/TestDocumentSnapshot.cs | 12 ++-- 87 files changed, 195 insertions(+), 373 deletions(-) delete mode 100644 src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/ProjectSystem/VersionedDocumentContext.cs diff --git a/src/Razor/benchmarks/Microsoft.AspNetCore.Razor.Microbenchmarks/LanguageServer/RazorCSharpFormattingBenchmark.cs b/src/Razor/benchmarks/Microsoft.AspNetCore.Razor.Microbenchmarks/LanguageServer/RazorCSharpFormattingBenchmark.cs index 4cfa36773c0..4de35d8b605 100644 --- a/src/Razor/benchmarks/Microsoft.AspNetCore.Razor.Microbenchmarks/LanguageServer/RazorCSharpFormattingBenchmark.cs +++ b/src/Razor/benchmarks/Microsoft.AspNetCore.Razor.Microbenchmarks/LanguageServer/RazorCSharpFormattingBenchmark.cs @@ -116,7 +116,7 @@ public async Task RazorCSharpFormattingAsync() InsertSpaces = true }; - var documentContext = new VersionedDocumentContext(DocumentUri, DocumentSnapshot, projectContext: null, version: 1); + var documentContext = new DocumentContext(DocumentUri, DocumentSnapshot, projectContext: null); var edits = await RazorFormattingService.FormatAsync(documentContext, range: null, options, CancellationToken.None); diff --git a/src/Razor/benchmarks/Microsoft.AspNetCore.Razor.Microbenchmarks/LanguageServer/RazorCodeActionsBenchmark.cs b/src/Razor/benchmarks/Microsoft.AspNetCore.Razor.Microbenchmarks/LanguageServer/RazorCodeActionsBenchmark.cs index efeead6a96e..d1d21777c6f 100644 --- a/src/Razor/benchmarks/Microsoft.AspNetCore.Razor.Microbenchmarks/LanguageServer/RazorCodeActionsBenchmark.cs +++ b/src/Razor/benchmarks/Microsoft.AspNetCore.Razor.Microbenchmarks/LanguageServer/RazorCodeActionsBenchmark.cs @@ -83,7 +83,7 @@ public async Task SetupAsync() CSharpCodeActionRange = DocumentText.GetZeroWidthRange(csharpCodeActionIndex); HtmlCodeActionRange = DocumentText.GetZeroWidthRange(htmlCodeActionIndex); - var documentContext = new VersionedDocumentContext(DocumentUri, DocumentSnapshot, projectContext: null, 1); + var documentContext = new DocumentContext(DocumentUri, DocumentSnapshot, projectContext: null); var codeDocument = await documentContext.GetCodeDocumentAsync(CancellationToken.None); // Need a root namespace for the Extract to Code Behind light bulb to be happy diff --git a/src/Razor/benchmarks/Microsoft.AspNetCore.Razor.Microbenchmarks/LanguageServer/RazorCompletionBenchmark.cs b/src/Razor/benchmarks/Microsoft.AspNetCore.Razor.Microbenchmarks/LanguageServer/RazorCompletionBenchmark.cs index 0bf6c9fea83..d35a168a36e 100644 --- a/src/Razor/benchmarks/Microsoft.AspNetCore.Razor.Microbenchmarks/LanguageServer/RazorCompletionBenchmark.cs +++ b/src/Razor/benchmarks/Microsoft.AspNetCore.Razor.Microbenchmarks/LanguageServer/RazorCompletionBenchmark.cs @@ -79,7 +79,7 @@ public async Task SetupAsync() RazorPosition = DocumentText.GetPosition(razorCodeActionIndex); - var documentContext = new VersionedDocumentContext(DocumentUri, DocumentSnapshot, projectContext: null, 1); + var documentContext = new DocumentContext(DocumentUri, DocumentSnapshot, projectContext: null); RazorRequestContext = new RazorRequestContext(documentContext, RazorLanguageServerHost.GetRequiredService(), "lsp/method", uri: null); } @@ -146,7 +146,7 @@ public TestDelegatedCompletionListProvider(IEnumerable GetCompletionListAsync(int absoluteIndex, VSInternalCompletionContext completionContext, VersionedDocumentContext documentContext, VSInternalClientCapabilities clientCapabilities, Guid correlationId, CancellationToken cancellationToken) + public override Task GetCompletionListAsync(int absoluteIndex, VSInternalCompletionContext completionContext, DocumentContext documentContext, VSInternalClientCapabilities clientCapabilities, Guid correlationId, CancellationToken cancellationToken) { return Task.FromResult( new VSInternalCompletionList diff --git a/src/Razor/benchmarks/Microsoft.AspNetCore.Razor.Microbenchmarks/LanguageServer/RazorDiagnosticsBenchmark.cs b/src/Razor/benchmarks/Microsoft.AspNetCore.Razor.Microbenchmarks/LanguageServer/RazorDiagnosticsBenchmark.cs index 9e50156d7f5..77c5a38937a 100644 --- a/src/Razor/benchmarks/Microsoft.AspNetCore.Razor.Microbenchmarks/LanguageServer/RazorDiagnosticsBenchmark.cs +++ b/src/Razor/benchmarks/Microsoft.AspNetCore.Razor.Microbenchmarks/LanguageServer/RazorDiagnosticsBenchmark.cs @@ -36,7 +36,7 @@ public class RazorDiagnosticsBenchmark : RazorLanguageServerBenchmarkBase private ImmutableArray SourceMappings { get; set; } private string? GeneratedCode { get; set; } private object? Diagnostics { get; set; } - private VersionedDocumentContext? VersionedDocumentContext { get; set; } + private DocumentContext? DocumentContext { get; set; } private VSInternalDocumentDiagnosticsParams? Request { get; set; } private IEnumerable? Response { get; set; } @@ -74,17 +74,17 @@ public void Setup() RazorCodeDocument = mockRazorCodeDocument.Object; SourceText = RazorCodeDocument.Source.Text; - var documentContext = new Mock( + var documentContext = new Mock( MockBehavior.Strict, new object[] { It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny() }); documentContext .Setup(r => r.GetCodeDocumentAsync(It.IsAny())) .ReturnsAsync(RazorCodeDocument); documentContext.Setup(r => r.Uri).Returns(It.IsAny()); - documentContext.Setup(r => r.Version).Returns(It.IsAny()); + documentContext.Setup(r => r.Snapshot.Version).Returns(It.IsAny()); documentContext.Setup(r => r.GetSourceTextAsync(It.IsAny())).ReturnsAsync(It.IsAny()); RazorRequestContext = new RazorRequestContext(documentContext.Object, null!, "lsp/method", uri: null); - VersionedDocumentContext = documentContext.Object; + DocumentContext = documentContext.Object; var loggerFactory = EmptyLoggerFactory.Instance; var languageServerFeatureOptions = BuildFeatureOptions(); diff --git a/src/Razor/benchmarks/Microsoft.AspNetCore.Razor.Microbenchmarks/LanguageServer/RazorSemanticTokensBenchmark.cs b/src/Razor/benchmarks/Microsoft.AspNetCore.Razor.Microbenchmarks/LanguageServer/RazorSemanticTokensBenchmark.cs index 8afb6f83298..dd76b418ad0 100644 --- a/src/Razor/benchmarks/Microsoft.AspNetCore.Razor.Microbenchmarks/LanguageServer/RazorSemanticTokensBenchmark.cs +++ b/src/Razor/benchmarks/Microsoft.AspNetCore.Razor.Microbenchmarks/LanguageServer/RazorSemanticTokensBenchmark.cs @@ -31,7 +31,7 @@ public class RazorSemanticTokensBenchmark : RazorLanguageServerBenchmarkBase private IDocumentSnapshot DocumentSnapshot => DocumentContext.Snapshot; - private VersionedDocumentContext DocumentContext { get; set; } + private DocumentContext DocumentContext { get; set; } private Range Range { get; set; } @@ -59,8 +59,7 @@ public async Task InitializeRazorSemanticAsync() var documentUri = new Uri(filePath); var documentSnapshot = await GetDocumentSnapshotAsync(ProjectFilePath, filePath, TargetPath); - var version = 1; - DocumentContext = new VersionedDocumentContext(documentUri, documentSnapshot, projectContext: null, version); + DocumentContext = new DocumentContext(documentUri, documentSnapshot, projectContext: null); var text = await DocumentContext.GetSourceTextAsync(CancellationToken.None).ConfigureAwait(false); Range = VsLspFactory.CreateRange( @@ -108,7 +107,7 @@ public TestRazorSemanticTokensInfoService( // We can't get C# responses without significant amounts of extra work, so let's just shim it for now, any non-Null result is fine. protected override Task?> GetCSharpSemanticRangesAsync( - VersionedDocumentContext documentContext, + DocumentContext documentContext, RazorCodeDocument codeDocument, LinePositionSpan razorRange, bool colorBackground, diff --git a/src/Razor/benchmarks/Microsoft.AspNetCore.Razor.Microbenchmarks/LanguageServer/RazorSemanticTokensRangeEndpointBenchmark.cs b/src/Razor/benchmarks/Microsoft.AspNetCore.Razor.Microbenchmarks/LanguageServer/RazorSemanticTokensRangeEndpointBenchmark.cs index 041413a31b5..e4c3e5fffd0 100644 --- a/src/Razor/benchmarks/Microsoft.AspNetCore.Razor.Microbenchmarks/LanguageServer/RazorSemanticTokensRangeEndpointBenchmark.cs +++ b/src/Razor/benchmarks/Microsoft.AspNetCore.Razor.Microbenchmarks/LanguageServer/RazorSemanticTokensRangeEndpointBenchmark.cs @@ -34,7 +34,7 @@ public class RazorSemanticTokensRangeEndpointBenchmark : RazorLanguageServerBenc private Uri DocumentUri => DocumentContext.Uri; - private VersionedDocumentContext DocumentContext { get; set; } + private DocumentContext DocumentContext { get; set; } private Range Range { get; set; } @@ -66,8 +66,7 @@ public async Task InitializeRazorSemanticAsync() var documentUri = new Uri(filePath); var documentSnapshot = await GetDocumentSnapshotAsync(ProjectFilePath, filePath, TargetPath); - var version = 1; - DocumentContext = new VersionedDocumentContext(documentUri, documentSnapshot, projectContext: null, version); + DocumentContext = new DocumentContext(documentUri, documentSnapshot, projectContext: null); var razorOptionsMonitor = RazorLanguageServerHost.GetRequiredService(); var clientCapabilitiesService = new BenchmarkClientCapabilitiesService(new VSInternalClientCapabilities() { SupportsVisualStudioExtensions = true }); @@ -141,7 +140,7 @@ public TestCustomizableRazorSemanticTokensInfoService( // We can't get C# responses without significant amounts of extra work, so let's just shim it for now, any non-Null result is fine. protected override Task?> GetCSharpSemanticRangesAsync( - VersionedDocumentContext documentContext, + DocumentContext documentContext, RazorCodeDocument codeDocument, LinePositionSpan razorSpan, bool colorBackground, diff --git a/src/Razor/benchmarks/Microsoft.AspNetCore.Razor.Microbenchmarks/LanguageServer/RazorSemanticTokensScrollingBenchmark.cs b/src/Razor/benchmarks/Microsoft.AspNetCore.Razor.Microbenchmarks/LanguageServer/RazorSemanticTokensScrollingBenchmark.cs index 6f5107bb265..20bcd3f5505 100644 --- a/src/Razor/benchmarks/Microsoft.AspNetCore.Razor.Microbenchmarks/LanguageServer/RazorSemanticTokensScrollingBenchmark.cs +++ b/src/Razor/benchmarks/Microsoft.AspNetCore.Razor.Microbenchmarks/LanguageServer/RazorSemanticTokensScrollingBenchmark.cs @@ -22,7 +22,7 @@ public class RazorSemanticTokensScrollingBenchmark : RazorLanguageServerBenchmar { private IRazorSemanticTokensInfoService RazorSemanticTokenService { get; set; } - private VersionedDocumentContext DocumentContext { get; set; } + private DocumentContext DocumentContext { get; set; } private Uri DocumentUri => DocumentContext.Uri; @@ -49,7 +49,7 @@ public async Task InitializeRazorSemanticAsync() var documentUri = new Uri(filePath); var documentSnapshot = await GetDocumentSnapshotAsync(ProjectFilePath, filePath, TargetPath); - DocumentContext = new VersionedDocumentContext(documentUri, documentSnapshot, projectContext: null, version: 1); + DocumentContext = new DocumentContext(documentUri, documentSnapshot, projectContext: null); var text = await DocumentSnapshot.GetTextAsync().ConfigureAwait(false); Range = VsLspFactory.CreateRange( diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/CodeActions/CSharp/DefaultCSharpCodeActionResolver.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/CodeActions/CSharp/DefaultCSharpCodeActionResolver.cs index 9e62f694a04..343f7e480cd 100644 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/CodeActions/CSharp/DefaultCSharpCodeActionResolver.cs +++ b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/CodeActions/CSharp/DefaultCSharpCodeActionResolver.cs @@ -46,12 +46,12 @@ public async override Task ResolveAsync( CodeAction codeAction, CancellationToken cancellationToken) { - if (!_documentContextFactory.TryCreateForOpenDocument(csharpParams.RazorFileIdentifier, out var documentContext)) + if (!_documentContextFactory.TryCreate(csharpParams.RazorFileIdentifier, out var documentContext)) { return codeAction; } - var resolvedCodeAction = await ResolveCodeActionWithServerAsync(csharpParams.RazorFileIdentifier, documentContext.Version, RazorLanguageKind.CSharp, codeAction, cancellationToken).ConfigureAwait(false); + var resolvedCodeAction = await ResolveCodeActionWithServerAsync(csharpParams.RazorFileIdentifier, documentContext.Snapshot.Version, RazorLanguageKind.CSharp, codeAction, cancellationToken).ConfigureAwait(false); if (resolvedCodeAction?.Edit?.DocumentChanges is null) { // Unable to resolve code action with server, return original code action @@ -88,7 +88,7 @@ public async override Task ResolveAsync( cancellationToken.ThrowIfCancellationRequested(); - var documentVersion = documentContext.Version; + var documentVersion = documentContext.Snapshot.Version; var codeDocumentIdentifier = new OptionalVersionedTextDocumentIdentifier() { diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/CodeActions/CSharp/UnformattedRemappingCSharpCodeActionResolver.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/CodeActions/CSharp/UnformattedRemappingCSharpCodeActionResolver.cs index 964f576f653..7e0e29d5499 100644 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/CodeActions/CSharp/UnformattedRemappingCSharpCodeActionResolver.cs +++ b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/CodeActions/CSharp/UnformattedRemappingCSharpCodeActionResolver.cs @@ -37,12 +37,12 @@ public async override Task ResolveAsync( { cancellationToken.ThrowIfCancellationRequested(); - if (!_documentContextFactory.TryCreateForOpenDocument(csharpParams.RazorFileIdentifier, out var documentContext)) + if (!_documentContextFactory.TryCreate(csharpParams.RazorFileIdentifier, out var documentContext)) { return codeAction; } - var resolvedCodeAction = await ResolveCodeActionWithServerAsync(csharpParams.RazorFileIdentifier, documentContext.Version, RazorLanguageKind.CSharp, codeAction, cancellationToken).ConfigureAwait(false); + var resolvedCodeAction = await ResolveCodeActionWithServerAsync(csharpParams.RazorFileIdentifier, documentContext.Snapshot.Version, RazorLanguageKind.CSharp, codeAction, cancellationToken).ConfigureAwait(false); if (resolvedCodeAction?.Edit?.DocumentChanges is null) { // Unable to resolve code action with server, return original code action @@ -87,7 +87,7 @@ public async override Task ResolveAsync( var codeDocumentIdentifier = new OptionalVersionedTextDocumentIdentifier() { Uri = csharpParams.RazorFileIdentifier.Uri, - Version = documentContext.Version, + Version = documentContext.Snapshot.Version, }; resolvedCodeAction.Edit = new WorkspaceEdit() { diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/CodeActions/CodeActionEndpoint.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/CodeActions/CodeActionEndpoint.cs index 4a72ea63208..a2d9c0a841c 100644 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/CodeActions/CodeActionEndpoint.cs +++ b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/CodeActions/CodeActionEndpoint.cs @@ -175,7 +175,7 @@ public void ApplyCapabilities(VSInternalServerCapabilities serverCapabilities, V return context; } - private async Task> GetDelegatedCodeActionsAsync(VersionedDocumentContext documentContext, RazorCodeActionContext context, Guid correlationId, CancellationToken cancellationToken) + private async Task> GetDelegatedCodeActionsAsync(DocumentContext documentContext, RazorCodeActionContext context, Guid correlationId, CancellationToken cancellationToken) { var languageKind = _documentMappingService.GetLanguageKind(context.CodeDocument, context.Location.AbsoluteIndex, rightAssociative: false); @@ -256,7 +256,7 @@ private static async Task> FilterCodeA } // Internal for testing - internal async Task GetCodeActionsFromLanguageServerAsync(RazorLanguageKind languageKind, VersionedDocumentContext documentContext, RazorCodeActionContext context, Guid correlationId, CancellationToken cancellationToken) + internal async Task GetCodeActionsFromLanguageServerAsync(RazorLanguageKind languageKind, DocumentContext documentContext, RazorCodeActionContext context, Guid correlationId, CancellationToken cancellationToken) { if (languageKind == RazorLanguageKind.CSharp) { @@ -282,7 +282,7 @@ internal async Task GetCodeActionsFromLanguageServe var delegatedParams = new DelegatedCodeActionParams() { - HostDocumentVersion = documentContext.Version, + HostDocumentVersion = documentContext.Snapshot.Version, CodeActionParams = context.Request, LanguageKind = languageKind, CorrelationId = correlationId diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/CodeActions/Html/DefaultHtmlCodeActionResolver.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/CodeActions/Html/DefaultHtmlCodeActionResolver.cs index e95ca9d060c..4c8fa0a60f3 100644 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/CodeActions/Html/DefaultHtmlCodeActionResolver.cs +++ b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/CodeActions/Html/DefaultHtmlCodeActionResolver.cs @@ -28,12 +28,12 @@ public async override Task ResolveAsync( CodeAction codeAction, CancellationToken cancellationToken) { - if (!_documentContextFactory.TryCreateForOpenDocument(resolveParams.RazorFileIdentifier, out var documentContext)) + if (!_documentContextFactory.TryCreate(resolveParams.RazorFileIdentifier, out var documentContext)) { return codeAction; } - var resolvedCodeAction = await ResolveCodeActionWithServerAsync(resolveParams.RazorFileIdentifier, documentContext.Version, RazorLanguageKind.Html, codeAction, cancellationToken).ConfigureAwait(false); + var resolvedCodeAction = await ResolveCodeActionWithServerAsync(resolveParams.RazorFileIdentifier, documentContext.Snapshot.Version, RazorLanguageKind.Html, codeAction, cancellationToken).ConfigureAwait(false); if (resolvedCodeAction?.Edit?.DocumentChanges is null) { // Unable to resolve code action with server, return original code action diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/CodeActions/Razor/GenerateMethodCodeActionResolver.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/CodeActions/Razor/GenerateMethodCodeActionResolver.cs index 86af5075d71..b990b515e79 100644 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/CodeActions/Razor/GenerateMethodCodeActionResolver.cs +++ b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/CodeActions/Razor/GenerateMethodCodeActionResolver.cs @@ -58,7 +58,7 @@ internal sealed class GenerateMethodCodeActionResolver( return null; } - if (!_documentContextFactory.TryCreateForOpenDocument(actionParams.Uri, out var documentContext)) + if (!_documentContextFactory.TryCreate(actionParams.Uri, out var documentContext)) { return null; } @@ -139,7 +139,7 @@ razorClassName is null || private async Task GenerateMethodInCodeBlockAsync( RazorCodeDocument code, GenerateMethodCodeActionParams actionParams, - VersionedDocumentContext documentContext, + DocumentContext documentContext, string? razorNamespace, string? razorClassName, CancellationToken cancellationToken) @@ -228,7 +228,7 @@ private async Task GenerateMethodInCodeBlockAsync( return new WorkspaceEdit() { DocumentChanges = new[] { razorTextDocEdit } }; } - private static async Task PopulateMethodSignatureAsync(VersionedDocumentContext documentContext, GenerateMethodCodeActionParams actionParams, CancellationToken cancellationToken) + private static async Task PopulateMethodSignatureAsync(DocumentContext documentContext, GenerateMethodCodeActionParams actionParams, CancellationToken cancellationToken) { var templateWithMethodSignature = s_generateMethodTemplate.Replace(MethodName, actionParams.MethodName); diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/ColorPresentation/ColorPresentationEndpoint.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/ColorPresentation/ColorPresentationEndpoint.cs index 6da931e401c..8cd27d497a3 100644 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/ColorPresentation/ColorPresentationEndpoint.cs +++ b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/ColorPresentation/ColorPresentationEndpoint.cs @@ -33,7 +33,7 @@ public async Task HandleRequestAsync(ColorPresentationPa var delegatedRequest = new DelegatedColorPresentationParams { - RequiredHostDocumentVersion = documentContext.Version, + RequiredHostDocumentVersion = documentContext.Snapshot.Version, Color = request.Color, Range = request.Range, TextDocument = request.TextDocument diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Completion/CompletionListProvider.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Completion/CompletionListProvider.cs index f296da09b3d..9caeb7cc5de 100644 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Completion/CompletionListProvider.cs +++ b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Completion/CompletionListProvider.cs @@ -33,7 +33,7 @@ public CompletionListProvider(RazorCompletionListProvider razorCompletionListPro public async Task GetCompletionListAsync( int absoluteIndex, VSInternalCompletionContext completionContext, - VersionedDocumentContext documentContext, + DocumentContext documentContext, VSInternalClientCapabilities clientCapabilities, Guid correlationId, CancellationToken cancellationToken) diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Completion/Delegation/DelegatedCompletionItemResolver.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Completion/Delegation/DelegatedCompletionItemResolver.cs index f977eb4b4ff..3e9464e62f7 100644 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Completion/Delegation/DelegatedCompletionItemResolver.cs +++ b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Completion/Delegation/DelegatedCompletionItemResolver.cs @@ -100,7 +100,7 @@ private async Task PostProcessCompletionItemAsync( } var identifier = context.OriginalRequestParams.Identifier.TextDocumentIdentifier; - if (!_documentContextFactory.TryCreateForOpenDocument(identifier, out var documentContext)) + if (!_documentContextFactory.TryCreate(identifier, out var documentContext)) { return resolvedCompletionItem; } diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Completion/Delegation/DelegatedCompletionListProvider.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Completion/Delegation/DelegatedCompletionListProvider.cs index 2c8e023b46d..fcdc554aa3f 100644 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Completion/Delegation/DelegatedCompletionListProvider.cs +++ b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Completion/Delegation/DelegatedCompletionListProvider.cs @@ -51,7 +51,7 @@ public DelegatedCompletionListProvider( public virtual async Task GetCompletionListAsync( int absoluteIndex, VSInternalCompletionContext completionContext, - VersionedDocumentContext documentContext, + DocumentContext documentContext, VSInternalClientCapabilities clientCapabilities, Guid correlationId, CancellationToken cancellationToken) @@ -119,7 +119,7 @@ public DelegatedCompletionListProvider( return rewrittenResponse; } - private async Task ShouldIncludeSnippetsAsync(VersionedDocumentContext documentContext, int absoluteIndex, CancellationToken cancellationToken) + private async Task ShouldIncludeSnippetsAsync(DocumentContext documentContext, int absoluteIndex, CancellationToken cancellationToken) { var codeDocument = await documentContext.GetCodeDocumentAsync(cancellationToken).ConfigureAwait(false); var tree = codeDocument.GetSyntaxTree(); @@ -182,7 +182,7 @@ private static VSInternalCompletionContext RewriteContext(VSInternalCompletionCo } private async Task TryGetProvisionalCompletionInfoAsync( - VersionedDocumentContext documentContext, + DocumentContext documentContext, VSInternalCompletionContext completionContext, DocumentPositionInfo positionInfo, CancellationToken cancellationToken) diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Completion/RazorCompletionListProvider.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Completion/RazorCompletionListProvider.cs index e73f38dcad8..ea0b2a76a02 100644 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Completion/RazorCompletionListProvider.cs +++ b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Completion/RazorCompletionListProvider.cs @@ -39,7 +39,7 @@ internal class RazorCompletionListProvider( public virtual async Task GetCompletionListAsync( int absoluteIndex, VSInternalCompletionContext completionContext, - VersionedDocumentContext documentContext, + DocumentContext documentContext, VSInternalClientCapabilities clientCapabilities, HashSet? existingCompletions, CancellationToken cancellationToken) diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Diagnostics/DocumentPullDiagnosticsEndpoint.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Diagnostics/DocumentPullDiagnosticsEndpoint.cs index 68d893f9b24..cc175aa49c0 100644 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Diagnostics/DocumentPullDiagnosticsEndpoint.cs +++ b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Diagnostics/DocumentPullDiagnosticsEndpoint.cs @@ -121,7 +121,7 @@ public TextDocumentIdentifier GetTextDocumentIdentifier(VSInternalDocumentDiagno return allDiagnostics.ToArray(); } - private static async Task GetRazorDiagnosticsAsync(VersionedDocumentContext documentContext, CancellationToken cancellationToken) + private static async Task GetRazorDiagnosticsAsync(DocumentContext documentContext, CancellationToken cancellationToken) { var codeDocument = await documentContext.GetCodeDocumentAsync(cancellationToken).ConfigureAwait(false); var sourceText = await documentContext.GetSourceTextAsync(cancellationToken).ConfigureAwait(false); @@ -145,7 +145,7 @@ public TextDocumentIdentifier GetTextDocumentIdentifier(VSInternalDocumentDiagno ]; } - private async Task<(VSInternalDiagnosticReport[]? CSharpDiagnostics, VSInternalDiagnosticReport[]? HtmlDiagnostics)> GetHtmlCSharpDiagnosticsAsync(VersionedDocumentContext documentContext, Guid correlationId, CancellationToken cancellationToken) + private async Task<(VSInternalDiagnosticReport[]? CSharpDiagnostics, VSInternalDiagnosticReport[]? HtmlDiagnostics)> GetHtmlCSharpDiagnosticsAsync(DocumentContext documentContext, Guid correlationId, CancellationToken cancellationToken) { var delegatedParams = new DelegatedDiagnosticParams(documentContext.GetTextDocumentIdentifierAndVersion(), correlationId); var delegatedResponse = await _clientConnection.SendRequestAsync( diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/DocumentColor/DocumentColorEndpoint.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/DocumentColor/DocumentColorEndpoint.cs index f3f870e3470..1275669a97c 100644 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/DocumentColor/DocumentColorEndpoint.cs +++ b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/DocumentColor/DocumentColorEndpoint.cs @@ -38,7 +38,7 @@ public async Task HandleRequestAsync(DocumentColorParams req var delegatedRequest = new DelegatedDocumentColorParams() { - HostDocumentVersion = documentContext.Version, + HostDocumentVersion = documentContext.Snapshot.Version, TextDocument = request.TextDocument }; diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/DocumentContextFactory.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/DocumentContextFactory.cs index 7f46807c2a3..68755ea2ae8 100644 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/DocumentContextFactory.cs +++ b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/DocumentContextFactory.cs @@ -27,19 +27,17 @@ internal sealed class DocumentContextFactory( public bool TryCreate( Uri documentUri, VSProjectContext? projectContext, - bool versioned, [NotNullWhen(true)] out DocumentContext? context) { var filePath = documentUri.GetAbsoluteOrUNCPath(); - if (!TryGetDocumentAndVersion(filePath, projectContext, versioned, out var documentAndVersion)) + if (!TryResolveDocument(filePath, projectContext, out var documentSnapshot)) { // Stale request or misbehaving client, see above comment. context = null; return false; } - var (documentSnapshot, version) = documentAndVersion; if (documentSnapshot is null) { Debug.Fail($"Document snapshot should never be null here for '{filePath}'. This indicates that our acquisition of documents / versions did not behave as expected."); @@ -47,52 +45,10 @@ public bool TryCreate( return false; } - if (versioned) - { - // If we were asked for a versioned document, but have no version info, then we didn't find the document - if (version is null) - { - context = null; - return false; - } - - context = new VersionedDocumentContext(documentUri, documentSnapshot, projectContext, version.Value); - return true; - } - context = new DocumentContext(documentUri, documentSnapshot, projectContext); return true; } - private bool TryGetDocumentAndVersion( - string filePath, - VSProjectContext? projectContext, - bool versioned, - [NotNullWhen(true)] out DocumentSnapshotAndVersion? documentAndVersion) - { - if (TryResolveDocument(filePath, projectContext, out var documentSnapshot)) - { - if (!versioned) - { - documentAndVersion = new DocumentSnapshotAndVersion(documentSnapshot, Version: null); - return true; - } - - documentAndVersion = new DocumentSnapshotAndVersion(documentSnapshot, documentSnapshot.Version); - return true; - } - - // This is super rare, if we get here it could mean many things. Some of which: - // 1. Stale request: - // - Got queued after a "document closed" / "document removed" type action - // - Took too long to run and by the time the request needed the document context the - // version cache has evicted the entry - // 2. Client is misbehaving and sending requests for a document that we've never seen before. - _logger.LogWarning($"Tried to create context for document {filePath} and project {projectContext?.Id} which was not found."); - documentAndVersion = null; - return false; - } - private bool TryResolveDocument( string filePath, VSProjectContext? projectContext, @@ -125,6 +81,4 @@ private bool TryResolveDocument( documentSnapshot = null; return false; } - - private record DocumentSnapshotAndVersion(IDocumentSnapshot Snapshot, int? Version); } diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/DocumentPresentation/AbstractTextDocumentPresentationEndpointBase.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/DocumentPresentation/AbstractTextDocumentPresentationEndpointBase.cs index f0059d00a19..330dd3201d3 100644 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/DocumentPresentation/AbstractTextDocumentPresentationEndpointBase.cs +++ b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/DocumentPresentation/AbstractTextDocumentPresentationEndpointBase.cs @@ -93,7 +93,7 @@ internal abstract class AbstractTextDocumentPresentationEndpointBase( var requestParams = CreateRazorRequestParameters(request); - requestParams.HostDocumentVersion = documentContext.Version; + requestParams.HostDocumentVersion = documentContext.Snapshot.Version; requestParams.Kind = languageKind; // For CSharp we need to map the range to the generated document @@ -115,7 +115,7 @@ internal abstract class AbstractTextDocumentPresentationEndpointBase( // The responses we get back will be for virtual documents, so we have to map them back to the real // document, and in the case of C#, map the returned ranges too - var edit = MapWorkspaceEdit(response, mapRanges: languageKind == RazorLanguageKind.CSharp, codeDocument, documentContext.Version); + var edit = MapWorkspaceEdit(response, mapRanges: languageKind == RazorLanguageKind.CSharp, codeDocument, documentContext.Snapshot.Version); return edit; } diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/EndpointContracts/RazorRequestContext.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/EndpointContracts/RazorRequestContext.cs index a81541b76d2..97819fcb3f0 100644 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/EndpointContracts/RazorRequestContext.cs +++ b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/EndpointContracts/RazorRequestContext.cs @@ -7,9 +7,9 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.EndpointContracts; -internal readonly struct RazorRequestContext(VersionedDocumentContext? documentContext, ILspServices lspServices, string method, Uri? uri) +internal readonly struct RazorRequestContext(DocumentContext? documentContext, ILspServices lspServices, string method, Uri? uri) { - public readonly VersionedDocumentContext? DocumentContext = documentContext; + public readonly DocumentContext? DocumentContext = documentContext; public readonly ILspServices LspServices = lspServices; public readonly string Method = method; public readonly Uri? Uri = uri; diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Folding/FoldingRangeEndpoint.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Folding/FoldingRangeEndpoint.cs index d94e078be6b..f2f71470096 100644 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Folding/FoldingRangeEndpoint.cs +++ b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Folding/FoldingRangeEndpoint.cs @@ -55,7 +55,7 @@ public TextDocumentIdentifier GetTextDocumentIdentifier(FoldingRangeParams reque var requestParams = new RazorFoldingRangeRequestParam { - HostDocumentVersion = documentContext.Version, + HostDocumentVersion = documentContext.Snapshot.Version, TextDocument = @params.TextDocument, }; diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Formatting/IRazorFormattingService.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Formatting/IRazorFormattingService.cs index 9048b915931..55e87401e30 100644 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Formatting/IRazorFormattingService.cs +++ b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Formatting/IRazorFormattingService.cs @@ -12,7 +12,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.Formatting; internal interface IRazorFormattingService { Task FormatAsync( - VersionedDocumentContext documentContext, + DocumentContext documentContext, Range? range, FormattingOptions options, CancellationToken cancellationToken); diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Formatting/RazorFormattingService.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Formatting/RazorFormattingService.cs index 7989815323b..3994238012e 100644 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Formatting/RazorFormattingService.cs +++ b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Formatting/RazorFormattingService.cs @@ -36,7 +36,7 @@ public RazorFormattingService( } public async Task FormatAsync( - VersionedDocumentContext documentContext, + DocumentContext documentContext, Range? range, FormattingOptions options, CancellationToken cancellationToken) @@ -68,7 +68,7 @@ public async Task FormatAsync( var uri = documentContext.Uri; var documentSnapshot = documentContext.Snapshot; - var hostDocumentVersion = documentContext.Version; + var hostDocumentVersion = documentContext.Snapshot.Version; using var context = FormattingContext.Create(uri, documentSnapshot, codeDocument, options, _workspaceFactory); var originalText = context.SourceText; diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Hover/HoverService.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Hover/HoverService.cs index 4fb546a09d6..de1dadb9643 100644 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Hover/HoverService.cs +++ b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Hover/HoverService.cs @@ -35,7 +35,7 @@ internal sealed partial class HoverService( private readonly IDocumentMappingService _documentMappingService = documentMappingService; private readonly IClientCapabilitiesService _clientCapabilitiesService = clientCapabilitiesService; - public async Task GetRazorHoverInfoAsync(VersionedDocumentContext documentContext, DocumentPositionInfo positionInfo, Position position, CancellationToken cancellationToken) + public async Task GetRazorHoverInfoAsync(DocumentContext documentContext, DocumentPositionInfo positionInfo, Position position, CancellationToken cancellationToken) { // HTML can still sometimes be handled by razor. For example hovering over // a component tag like will still be in an html context @@ -57,7 +57,7 @@ internal sealed partial class HoverService( return await GetHoverInfoAsync(documentContext.FilePath, codeDocument, location, _clientCapabilitiesService.ClientCapabilities, cancellationToken).ConfigureAwait(false); } - public async Task TranslateDelegatedResponseAsync(VSInternalHover? response, VersionedDocumentContext documentContext, DocumentPositionInfo positionInfo, CancellationToken cancellationToken) + public async Task TranslateDelegatedResponseAsync(VSInternalHover? response, DocumentContext documentContext, DocumentPositionInfo positionInfo, CancellationToken cancellationToken) { if (response?.Range is null) { diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Hover/IHoverService.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Hover/IHoverService.cs index 5408dd8f17d..b3ef864a76c 100644 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Hover/IHoverService.cs +++ b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Hover/IHoverService.cs @@ -11,6 +11,6 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.Hover; internal interface IHoverService { - Task GetRazorHoverInfoAsync(VersionedDocumentContext versionedDocumentContext, DocumentPositionInfo positionInfo, Position position, CancellationToken cancellationToken); - Task TranslateDelegatedResponseAsync(VSInternalHover? response, VersionedDocumentContext versionedDocumentContext, DocumentPositionInfo positionInfo, CancellationToken cancellationToken); + Task GetRazorHoverInfoAsync(DocumentContext versionedDocumentContext, DocumentPositionInfo positionInfo, Position position, CancellationToken cancellationToken); + Task TranslateDelegatedResponseAsync(VSInternalHover? response, DocumentContext versionedDocumentContext, DocumentPositionInfo positionInfo, CancellationToken cancellationToken); } diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/InlayHints/IInlayHintService.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/InlayHints/IInlayHintService.cs index 54865b68151..fce91249bf1 100644 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/InlayHints/IInlayHintService.cs +++ b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/InlayHints/IInlayHintService.cs @@ -11,7 +11,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.InlayHints; internal interface IInlayHintService { - Task GetInlayHintsAsync(IClientConnection clientConnection, VersionedDocumentContext documentContext, Range range, CancellationToken cancellationToken); + Task GetInlayHintsAsync(IClientConnection clientConnection, DocumentContext documentContext, Range range, CancellationToken cancellationToken); Task ResolveInlayHintAsync(IClientConnection clientConnection, InlayHint inlayHint, CancellationToken cancellationToken); } diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/InlayHints/InlayHintService.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/InlayHints/InlayHintService.cs index 294a6adc827..60b405b5faa 100644 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/InlayHints/InlayHintService.cs +++ b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/InlayHints/InlayHintService.cs @@ -22,7 +22,7 @@ internal sealed class InlayHintService(IDocumentMappingService documentMappingSe { private readonly IDocumentMappingService _documentMappingService = documentMappingService; - public async Task GetInlayHintsAsync(IClientConnection clientConnection, VersionedDocumentContext documentContext, Range range, CancellationToken cancellationToken) + public async Task GetInlayHintsAsync(IClientConnection clientConnection, DocumentContext documentContext, Range range, CancellationToken cancellationToken) { var codeDocument = await documentContext.GetCodeDocumentAsync(cancellationToken).ConfigureAwait(false); var csharpDocument = codeDocument.GetCSharpDocument(); diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/LspEditMappingService.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/LspEditMappingService.cs index e8d9f6c580e..bd88b799311 100644 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/LspEditMappingService.cs +++ b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/LspEditMappingService.cs @@ -22,19 +22,9 @@ internal class LspEditMappingService( { private readonly IDocumentContextFactory _documentContextFactory = documentContextFactory; - protected override bool TryGetVersionedDocumentContext(IDocumentSnapshot contextDocumentSnapshot, Uri razorDocumentUri, VSProjectContext? projectContext, [NotNullWhen(true)] out VersionedDocumentContext? documentContext) + protected override bool TryGetDocumentContext(IDocumentSnapshot contextDocumentSnapshot, Uri razorDocumentUri, VSProjectContext? projectContext, [NotNullWhen(true)] out DocumentContext? documentContext) { - if (!_documentContextFactory.TryCreateForOpenDocument(razorDocumentUri, projectContext, out documentContext)) - { - return false; - } - - return true; - } - - protected override bool TryGetDocumentContext(IDocumentSnapshot contextDocumentSnapshot, Uri razorDocumentUri, [NotNullWhen(true)] out DocumentContext? documentContext) - { - if (!_documentContextFactory.TryCreate(razorDocumentUri, out documentContext)) + if (!_documentContextFactory.TryCreate(razorDocumentUri, projectContext, out documentContext)) { return false; } diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/MapCode/MapCodeEndpoint.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/MapCode/MapCodeEndpoint.cs index e38ace89ca0..4d61c202e32 100644 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/MapCode/MapCodeEndpoint.cs +++ b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/MapCode/MapCodeEndpoint.cs @@ -85,7 +85,7 @@ public void ApplyCapabilities(VSInternalServerCapabilities serverCapabilities, V continue; } - if (!_documentContextFactory.TryCreateForOpenDocument(mapping.TextDocument.Uri, out var documentContext)) + if (!_documentContextFactory.TryCreate(mapping.TextDocument.Uri, out var documentContext)) { continue; } @@ -131,7 +131,7 @@ private async Task TryMapCodeAsync( Location[][] locations, List changes, Guid mapCodeCorrelationId, - VersionedDocumentContext documentContext, + DocumentContext documentContext, CancellationToken cancellationToken) { var syntaxTree = codeToMap.GetSyntaxTree(); @@ -162,7 +162,7 @@ private async Task TryMapCodeAsync( ImmutableArray nodesToMap, Guid mapCodeCorrelationId, List changes, - VersionedDocumentContext documentContext, + DocumentContext documentContext, CancellationToken cancellationToken) { var didCalculateCSharpFocusLocations = false; @@ -357,7 +357,7 @@ private async Task GetCSharpFocusLocationsAsync(Location[][] focus continue; } - if (!_documentContextFactory.TryCreateForOpenDocument(potentialLocation.Uri, out var documentContext)) + if (!_documentContextFactory.TryCreate(potentialLocation.Uri, out var documentContext)) { continue; } diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Mapping/RazorLanguageQueryEndpoint.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Mapping/RazorLanguageQueryEndpoint.cs index 62f55e00a19..7c7bc03cc47 100644 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Mapping/RazorLanguageQueryEndpoint.cs +++ b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Mapping/RazorLanguageQueryEndpoint.cs @@ -39,7 +39,7 @@ public TextDocumentIdentifier GetTextDocumentIdentifier(RazorLanguageQueryParams } var documentSnapshot = documentContext.Snapshot; - var documentVersion = documentContext.Version; + var documentVersion = documentContext.Snapshot.Version; var codeDocument = await documentSnapshot.GetGeneratedOutputAsync().ConfigureAwait(false); var sourceText = await documentSnapshot.GetTextAsync().ConfigureAwait(false); diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Mapping/RazorMapToDocumentRangesEndpoint.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Mapping/RazorMapToDocumentRangesEndpoint.cs index a6e0c6f6a29..1223d0f5c39 100644 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Mapping/RazorMapToDocumentRangesEndpoint.cs +++ b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Mapping/RazorMapToDocumentRangesEndpoint.cs @@ -53,7 +53,7 @@ public Uri GetTextDocumentIdentifier(RazorMapToDocumentRangesParams request) return new RazorMapToDocumentRangesResponse() { Ranges = request.ProjectedRanges, - HostDocumentVersion = documentContext.Version, + HostDocumentVersion = documentContext.Snapshot.Version, }; } @@ -76,7 +76,7 @@ public Uri GetTextDocumentIdentifier(RazorMapToDocumentRangesParams request) return new RazorMapToDocumentRangesResponse() { Ranges = ranges, - HostDocumentVersion = documentContext.Version, + HostDocumentVersion = documentContext.Snapshot.Version, }; } } diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/RazorRequestContextFactory.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/RazorRequestContextFactory.cs index 3383b82b7cb..f89b213204c 100644 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/RazorRequestContextFactory.cs +++ b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/RazorRequestContextFactory.cs @@ -21,7 +21,7 @@ public override Task CreateRequestContextAsync().GetOrCreateLogger(); - VersionedDocumentContext? documentContext = null; + DocumentContext? documentContext = null; var textDocumentHandler = methodHandler as ITextDocumentIdentifierHandler; Uri? uri = null; @@ -35,7 +35,7 @@ public override Task CreateRequestContextAsync uriHandler) { @@ -43,7 +43,7 @@ public override Task CreateRequestContextAsync(); public async Task GetCSharpSemanticTokensResponseAsync( - VersionedDocumentContext documentContext, + DocumentContext documentContext, ImmutableArray csharpSpans, Guid correlationId, CancellationToken cancellationToken) { - var documentVersion = documentContext.Version; + var documentVersion = documentContext.Snapshot.Version; using var _ = ListPool.GetPooledObject(out var csharpRangeList); foreach (var span in csharpSpans) diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/SpellCheck/DocumentSpellCheckEndpoint.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/SpellCheck/DocumentSpellCheckEndpoint.cs index 3d2b69e43a5..625c7a6086b 100644 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/SpellCheck/DocumentSpellCheckEndpoint.cs +++ b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/SpellCheck/DocumentSpellCheckEndpoint.cs @@ -79,7 +79,7 @@ public TextDocumentIdentifier GetTextDocumentIdentifier(VSInternalDocumentSpellC }; } - private static async Task AddRazorSpellCheckRangesAsync(List ranges, VersionedDocumentContext documentContext, CancellationToken cancellationToken) + private static async Task AddRazorSpellCheckRangesAsync(List ranges, DocumentContext documentContext, CancellationToken cancellationToken) { var tree = await documentContext.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); @@ -127,7 +127,7 @@ MarkupMinimizedTagHelperDirectiveAttributeSyntax or } } - private async Task AddCSharpSpellCheckRangesAsync(List ranges, VersionedDocumentContext documentContext, CancellationToken cancellationToken) + private async Task AddCSharpSpellCheckRangesAsync(List ranges, DocumentContext documentContext, CancellationToken cancellationToken) { var delegatedParams = new DelegatedSpellCheckParams(documentContext.GetTextDocumentIdentifierAndVersion()); var delegatedResponse = await _clientConnection.SendRequestAsync( diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/WrapWithTag/WrapWithTagEndpoint.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/WrapWithTag/WrapWithTagEndpoint.cs index 990dbc07a6e..aa168ece625 100644 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/WrapWithTag/WrapWithTagEndpoint.cs +++ b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/WrapWithTag/WrapWithTagEndpoint.cs @@ -104,7 +104,7 @@ public TextDocumentIdentifier GetTextDocumentIdentifier(WrapWithTagParams reques var versioned = new VersionedTextDocumentIdentifier { Uri = request.TextDocument.Uri, - Version = documentContext.Version, + Version = documentContext.Snapshot.Version, }; var parameter = new DelegatedWrapWithTagParams(versioned, request); diff --git a/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/DocumentMapping/AbstractEditMappingService.cs b/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/DocumentMapping/AbstractEditMappingService.cs index f19d04c3500..a06a6ec3d52 100644 --- a/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/DocumentMapping/AbstractEditMappingService.cs +++ b/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/DocumentMapping/AbstractEditMappingService.cs @@ -26,7 +26,7 @@ public async Task RemapWorkspaceEditAsync(IDocumentSnapshot conte if (workspaceEdit.TryGetTextDocumentEdits(out var documentEdits)) { // The LSP spec says, we should prefer `DocumentChanges` property over `Changes` if available. - var remappedEdits = await RemapVersionedDocumentEditsAsync(contextDocumentSnapshot, documentEdits, cancellationToken).ConfigureAwait(false); + var remappedEdits = await RemapTextDocumentEditsAsync(contextDocumentSnapshot, documentEdits, cancellationToken).ConfigureAwait(false); return new WorkspaceEdit() { @@ -62,7 +62,7 @@ private async Task> RemapDocumentEditsAsync(IDocu continue; } - if (!TryGetDocumentContext(contextDocumentSnapshot, uri, out var documentContext)) + if (!TryGetDocumentContext(contextDocumentSnapshot, uri, projectContext: null, out var documentContext)) { continue; } @@ -107,7 +107,7 @@ private TextEdit[] RemapTextEditsCore(Uri generatedDocumentUri, RazorCodeDocumen return remappedEdits.ToArray(); } - private async Task RemapVersionedDocumentEditsAsync(IDocumentSnapshot contextDocumentSnapshot, TextDocumentEdit[] documentEdits, CancellationToken cancellationToken) + private async Task RemapTextDocumentEditsAsync(IDocumentSnapshot contextDocumentSnapshot, TextDocumentEdit[] documentEdits, CancellationToken cancellationToken) { using var remappedDocumentEdits = new PooledArrayBuilder(documentEdits.Length); @@ -125,7 +125,7 @@ private async Task RemapVersionedDocumentEditsAsync(IDocumen var razorDocumentUri = _filePathService.GetRazorDocumentUri(generatedDocumentUri); - if (!TryGetVersionedDocumentContext(contextDocumentSnapshot, razorDocumentUri, entry.TextDocument.GetProjectContext(), out var documentContext)) + if (!TryGetDocumentContext(contextDocumentSnapshot, razorDocumentUri, entry.TextDocument.GetProjectContext(), out var documentContext)) { continue; } @@ -144,7 +144,7 @@ private async Task RemapVersionedDocumentEditsAsync(IDocumen TextDocument = new OptionalVersionedTextDocumentIdentifier() { Uri = razorDocumentUri, - Version = documentContext.Version + Version = documentContext.Snapshot.Version }, Edits = remappedEdits }); @@ -153,7 +153,5 @@ private async Task RemapVersionedDocumentEditsAsync(IDocumen return remappedDocumentEdits.ToArray(); } - protected abstract bool TryGetVersionedDocumentContext(IDocumentSnapshot contextDocumentSnapshot, Uri razorDocumentUri, VSProjectContext? projectContext, [NotNullWhen(true)] out VersionedDocumentContext? documentContext); - - protected abstract bool TryGetDocumentContext(IDocumentSnapshot contextDocumentSnapshot, Uri razorDocumentUri, [NotNullWhen(true)] out DocumentContext? documentContext); + protected abstract bool TryGetDocumentContext(IDocumentSnapshot contextDocumentSnapshot, Uri razorDocumentUri, VSProjectContext? projectContext, [NotNullWhen(true)] out DocumentContext? documentContext); } diff --git a/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/ProjectSystem/DocumentContext.cs b/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/ProjectSystem/DocumentContext.cs index a99c792531f..207357dbbcc 100644 --- a/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/ProjectSystem/DocumentContext.cs +++ b/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/ProjectSystem/DocumentContext.cs @@ -8,6 +8,7 @@ using Microsoft.AspNetCore.Razor; using Microsoft.AspNetCore.Razor.Language; using Microsoft.AspNetCore.Razor.Language.Syntax; +using Microsoft.CodeAnalysis.Razor.Protocol; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.LanguageServer.Protocol; using RazorSyntaxNode = Microsoft.AspNetCore.Razor.Language.Syntax.SyntaxNode; @@ -33,6 +34,9 @@ public TextDocumentIdentifier GetTextDocumentIdentifier() ProjectContext = _projectContext, }; + public TextDocumentIdentifierAndVersion GetTextDocumentIdentifierAndVersion() + => new(GetTextDocumentIdentifier(), Snapshot.Version); + private bool TryGetCodeDocument([NotNullWhen(true)] out RazorCodeDocument? codeDocument) { codeDocument = _codeDocument; diff --git a/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/ProjectSystem/IDocumentContextFactory.cs b/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/ProjectSystem/IDocumentContextFactory.cs index 6eb544326ec..a29c943da58 100644 --- a/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/ProjectSystem/IDocumentContextFactory.cs +++ b/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/ProjectSystem/IDocumentContextFactory.cs @@ -12,6 +12,5 @@ internal interface IDocumentContextFactory bool TryCreate( Uri documentUri, VSProjectContext? projectContext, - bool versioned, [NotNullWhen(true)] out DocumentContext? context); } diff --git a/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/ProjectSystem/IDocumentContextFactoryExtensions.cs b/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/ProjectSystem/IDocumentContextFactoryExtensions.cs index 519212b9df7..4843df493cf 100644 --- a/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/ProjectSystem/IDocumentContextFactoryExtensions.cs +++ b/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/ProjectSystem/IDocumentContextFactoryExtensions.cs @@ -13,64 +13,11 @@ public static bool TryCreate( this IDocumentContextFactory service, TextDocumentIdentifier documentIdentifier, [NotNullWhen(true)] out DocumentContext? context) - => service.TryCreate(documentIdentifier.Uri, documentIdentifier.GetProjectContext(), versioned: false, out context); + => service.TryCreate(documentIdentifier.Uri, documentIdentifier.GetProjectContext(), out context); public static bool TryCreate( this IDocumentContextFactory service, Uri documentUri, [NotNullWhen(true)] out DocumentContext? context) - => service.TryCreate(documentUri, projectContext: null, versioned: false, out context); - - public static bool TryCreate( - this IDocumentContextFactory service, - Uri documentUri, - VSProjectContext? projectContext, - [NotNullWhen(true)] out DocumentContext? context) - => service.TryCreate(documentUri, projectContext, versioned: false, out context); - - public static bool TryCreateForOpenDocument( - this IDocumentContextFactory service, - Uri documentUri, - [NotNullWhen(true)] out VersionedDocumentContext? context) - { - if (service.TryCreate(documentUri, projectContext: null, versioned: true, out var documentContext)) - { - context = (VersionedDocumentContext)documentContext; - return true; - } - - context = null; - return false; - } - - public static bool TryCreateForOpenDocument( - this IDocumentContextFactory service, - TextDocumentIdentifier documentIdentifier, - [NotNullWhen(true)] out VersionedDocumentContext? context) - { - if (service.TryCreate(documentIdentifier.Uri, documentIdentifier.GetProjectContext(), versioned: true, out var documentContext)) - { - context = (VersionedDocumentContext)documentContext; - return true; - } - - context = null; - return false; - } - - public static bool TryCreateForOpenDocument( - this IDocumentContextFactory service, - Uri documentUri, - VSProjectContext? projectContext, - [NotNullWhen(true)] out VersionedDocumentContext? context) - { - if (service.TryCreate(documentUri, projectContext, versioned: true, out var documentContext)) - { - context = (VersionedDocumentContext)documentContext; - return true; - } - - context = null; - return false; - } + => service.TryCreate(documentUri, projectContext: null, out context); } diff --git a/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/ProjectSystem/VersionedDocumentContext.cs b/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/ProjectSystem/VersionedDocumentContext.cs deleted file mode 100644 index 6c4bbcf8ade..00000000000 --- a/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/ProjectSystem/VersionedDocumentContext.cs +++ /dev/null @@ -1,17 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT license. See License.txt in the project root for license information. - -using System; -using Microsoft.CodeAnalysis.Razor.Protocol; -using Microsoft.VisualStudio.LanguageServer.Protocol; - -namespace Microsoft.CodeAnalysis.Razor.ProjectSystem; - -internal class VersionedDocumentContext(Uri uri, IDocumentSnapshot snapshot, VSProjectContext? projectContext, int version) - : DocumentContext(uri, snapshot, projectContext) -{ - public int Version { get; } = version; - - public TextDocumentIdentifierAndVersion GetTextDocumentIdentifierAndVersion() - => new(GetTextDocumentIdentifier(), Version); -} diff --git a/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Rename/IRenameService.cs b/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Rename/IRenameService.cs index 36c271f15d2..6567bf92ba2 100644 --- a/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Rename/IRenameService.cs +++ b/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Rename/IRenameService.cs @@ -11,5 +11,5 @@ namespace Microsoft.CodeAnalysis.Razor.Rename; internal interface IRenameService { - Task TryGetRazorRenameEditsAsync(VersionedDocumentContext documentContext, DocumentPositionInfo positionInfo, string newName, CancellationToken cancellationToken); + Task TryGetRazorRenameEditsAsync(DocumentContext documentContext, DocumentPositionInfo positionInfo, string newName, CancellationToken cancellationToken); } diff --git a/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Rename/RenameService.cs b/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Rename/RenameService.cs index 6563e5bb059..4d74b88fd01 100644 --- a/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Rename/RenameService.cs +++ b/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Rename/RenameService.cs @@ -32,7 +32,7 @@ internal class RenameService( private readonly IProjectCollectionResolver _projectCollectionResolver = projectCollectionResolver; private readonly LanguageServerFeatureOptions _languageServerFeatureOptions = languageServerFeatureOptions; - public async Task TryGetRazorRenameEditsAsync(VersionedDocumentContext documentContext, DocumentPositionInfo positionInfo, string newName, CancellationToken cancellationToken) + public async Task TryGetRazorRenameEditsAsync(DocumentContext documentContext, DocumentPositionInfo positionInfo, string newName, CancellationToken cancellationToken) { // We only support renaming of .razor components, not .cshtml tag helpers if (!FileKinds.IsComponent(documentContext.FileKind)) diff --git a/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/SemanticTokens/AbstractRazorSemanticTokensInfoService.cs b/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/SemanticTokens/AbstractRazorSemanticTokensInfoService.cs index 0acf4494658..fbd237c3710 100644 --- a/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/SemanticTokens/AbstractRazorSemanticTokensInfoService.cs +++ b/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/SemanticTokens/AbstractRazorSemanticTokensInfoService.cs @@ -36,7 +36,7 @@ internal abstract class AbstractRazorSemanticTokensInfoService( private readonly ILogger _logger = logger; public async Task GetSemanticTokensAsync( - VersionedDocumentContext documentContext, + DocumentContext documentContext, LinePositionSpan span, bool colorBackground, Guid correlationId, @@ -58,7 +58,7 @@ internal abstract class AbstractRazorSemanticTokensInfoService( } private async Task GetSemanticTokensAsync( - VersionedDocumentContext documentContext, + DocumentContext documentContext, LinePositionSpan span, Guid correlationId, bool colorBackground, @@ -89,7 +89,7 @@ internal abstract class AbstractRazorSemanticTokensInfoService( // We return null (which to the LSP is a no-op) to prevent flashing of CSharp elements. if (csharpSemanticRangesResult is not { } csharpSemanticRanges) { - _logger.LogDebug($"Couldn't get C# tokens for version {documentContext.Version} of {documentContext.Uri}. Returning null"); + _logger.LogDebug($"Couldn't get C# tokens for version {documentContext.Snapshot.Version} of {documentContext.Uri}. Returning null"); return null; } @@ -134,7 +134,7 @@ private static ImmutableArray CombineSemanticRanges(ImmutableArra // Virtual for benchmarks protected virtual async Task?> GetCSharpSemanticRangesAsync( - VersionedDocumentContext documentContext, + DocumentContext documentContext, RazorCodeDocument codeDocument, LinePositionSpan razorSpan, bool colorBackground, @@ -170,7 +170,7 @@ private static ImmutableArray CombineSemanticRanges(ImmutableArra csharpRanges = [csharpRange]; } - _logger.LogDebug($"Requesting C# semantic tokens for host version {documentContext.Version}, correlation ID {correlationId}, and the server thinks there are {codeDocument.GetCSharpSourceText().Lines.Count} lines of C#"); + _logger.LogDebug($"Requesting C# semantic tokens for host version {documentContext.Snapshot.Version}, correlation ID {correlationId}, and the server thinks there are {codeDocument.GetCSharpSourceText().Lines.Count} lines of C#"); var csharpResponse = await _csharpSemanticTokensProvider.GetCSharpSemanticTokensResponseAsync(documentContext, csharpRanges, correlationId, cancellationToken).ConfigureAwait(false); diff --git a/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/SemanticTokens/ICSharpSemanticTokensProvider.cs b/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/SemanticTokens/ICSharpSemanticTokensProvider.cs index fede98e6331..216f320b74d 100644 --- a/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/SemanticTokens/ICSharpSemanticTokensProvider.cs +++ b/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/SemanticTokens/ICSharpSemanticTokensProvider.cs @@ -13,7 +13,7 @@ namespace Microsoft.CodeAnalysis.Razor.SemanticTokens; internal interface ICSharpSemanticTokensProvider { Task GetCSharpSemanticTokensResponseAsync( - VersionedDocumentContext documentContext, + DocumentContext documentContext, ImmutableArray csharpSpans, Guid correlationId, CancellationToken cancellationToken); diff --git a/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/SemanticTokens/IRazorSemanticTokenInfoService.cs b/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/SemanticTokens/IRazorSemanticTokenInfoService.cs index 26de9805eca..b9240e16426 100644 --- a/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/SemanticTokens/IRazorSemanticTokenInfoService.cs +++ b/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/SemanticTokens/IRazorSemanticTokenInfoService.cs @@ -15,5 +15,5 @@ internal interface IRazorSemanticTokensInfoService /// Gets the int array representing the semantic tokens for the given range. /// /// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#textDocument_semanticTokens for details about the int array - Task GetSemanticTokensAsync(VersionedDocumentContext documentContext, LinePositionSpan range, bool colorBackground, Guid correlationId, CancellationToken cancellationToken); + Task GetSemanticTokensAsync(DocumentContext documentContext, LinePositionSpan range, bool colorBackground, Guid correlationId, CancellationToken cancellationToken); } diff --git a/src/Razor/src/Microsoft.CodeAnalysis.Remote.Razor/DocumentMapping/RemoteEditMappingService.cs b/src/Razor/src/Microsoft.CodeAnalysis.Remote.Razor/DocumentMapping/RemoteEditMappingService.cs index 359c4e90729..7110af27edd 100644 --- a/src/Razor/src/Microsoft.CodeAnalysis.Remote.Razor/DocumentMapping/RemoteEditMappingService.cs +++ b/src/Razor/src/Microsoft.CodeAnalysis.Remote.Razor/DocumentMapping/RemoteEditMappingService.cs @@ -21,7 +21,7 @@ internal sealed class RemoteEditMappingService( { private readonly DocumentSnapshotFactory _documentSnapshotFactory = documentSnapshotFactory; - protected override bool TryGetVersionedDocumentContext(IDocumentSnapshot contextDocumentSnapshot, Uri razorDocumentUri, VSProjectContext? projectContext, [NotNullWhen(true)] out VersionedDocumentContext? documentContext) + protected override bool TryGetDocumentContext(IDocumentSnapshot contextDocumentSnapshot, Uri razorDocumentUri, VSProjectContext? projectContext, [NotNullWhen(true)] out DocumentContext? documentContext) { if (contextDocumentSnapshot is not RemoteDocumentSnapshot originSnapshot) { @@ -40,12 +40,4 @@ protected override bool TryGetVersionedDocumentContext(IDocumentSnapshot context documentContext = new RemoteDocumentContext(razorDocumentUri, razorDocumentSnapshot); return true; } - - protected override bool TryGetDocumentContext(IDocumentSnapshot contextDocumentSnapshot, Uri razorDocumentUri, [NotNullWhen(true)] out DocumentContext? documentContext) - { - // In OOP there is no difference between versioned and unversioned document contexts. - var result = TryGetVersionedDocumentContext(contextDocumentSnapshot, razorDocumentUri, projectContext: null, out var versionedDocumentContext); - documentContext = versionedDocumentContext; - return result; - } } diff --git a/src/Razor/src/Microsoft.CodeAnalysis.Remote.Razor/ProjectSystem/DocumentContextExtensions.cs b/src/Razor/src/Microsoft.CodeAnalysis.Remote.Razor/ProjectSystem/DocumentContextExtensions.cs index bd29cf52ab3..b1213b419f0 100644 --- a/src/Razor/src/Microsoft.CodeAnalysis.Remote.Razor/ProjectSystem/DocumentContextExtensions.cs +++ b/src/Razor/src/Microsoft.CodeAnalysis.Remote.Razor/ProjectSystem/DocumentContextExtensions.cs @@ -15,7 +15,7 @@ namespace Microsoft.CodeAnalysis.Remote.Razor; internal static class DocumentContextExtensions { public static async Task GetGeneratedDocumentAsync( - this VersionedDocumentContext documentContext, + this DocumentContext documentContext, IFilePathService filePathService, CancellationToken cancellationToken) { diff --git a/src/Razor/src/Microsoft.CodeAnalysis.Remote.Razor/ProjectSystem/RemoteDocumentContext.cs b/src/Razor/src/Microsoft.CodeAnalysis.Remote.Razor/ProjectSystem/RemoteDocumentContext.cs index bfd3a34bdff..d96a578fb2a 100644 --- a/src/Razor/src/Microsoft.CodeAnalysis.Remote.Razor/ProjectSystem/RemoteDocumentContext.cs +++ b/src/Razor/src/Microsoft.CodeAnalysis.Remote.Razor/ProjectSystem/RemoteDocumentContext.cs @@ -6,13 +6,13 @@ namespace Microsoft.CodeAnalysis.Remote.Razor.ProjectSystem; -internal class RemoteDocumentContext : VersionedDocumentContext +internal class RemoteDocumentContext : DocumentContext { public TextDocument TextDocument => ((RemoteDocumentSnapshot)Snapshot).TextDocument; public RemoteDocumentContext(Uri uri, RemoteDocumentSnapshot snapshot) - // HACK: Need to revisit version and projectContext here I guess - : base(uri, snapshot, projectContext: null, version: 1) + // HACK: Need to revisit projectContext here I guess + : base(uri, snapshot, projectContext: null) { } } diff --git a/src/Razor/src/Microsoft.CodeAnalysis.Remote.Razor/ProjectSystem/RemoteDocumentSnapshot.cs b/src/Razor/src/Microsoft.CodeAnalysis.Remote.Razor/ProjectSystem/RemoteDocumentSnapshot.cs index 0449adbc393..36efc36202e 100644 --- a/src/Razor/src/Microsoft.CodeAnalysis.Remote.Razor/ProjectSystem/RemoteDocumentSnapshot.cs +++ b/src/Razor/src/Microsoft.CodeAnalysis.Remote.Razor/ProjectSystem/RemoteDocumentSnapshot.cs @@ -34,7 +34,7 @@ internal class RemoteDocumentSnapshot(TextDocument textDocument, RemoteProjectSn public bool SupportsOutput => true; - public int Version => throw new NotImplementedException("We don't expect to use this in cohosting because we do not control generated document creation."); + public int Version => -999; // We don't expect to use this in cohosting, but plenty of existing code logs it's value public Task GetTextAsync() => _textDocument.GetTextAsync(); diff --git a/src/Razor/src/Microsoft.CodeAnalysis.Remote.Razor/SemanticTokens/RemoteCSharpSemanticTokensProvider.cs b/src/Razor/src/Microsoft.CodeAnalysis.Remote.Razor/SemanticTokens/RemoteCSharpSemanticTokensProvider.cs index afd2f6463ab..2823c1a9175 100644 --- a/src/Razor/src/Microsoft.CodeAnalysis.Remote.Razor/SemanticTokens/RemoteCSharpSemanticTokensProvider.cs +++ b/src/Razor/src/Microsoft.CodeAnalysis.Remote.Razor/SemanticTokens/RemoteCSharpSemanticTokensProvider.cs @@ -22,7 +22,7 @@ internal class RemoteCSharpSemanticTokensProvider(IFilePathService filePathServi private readonly IFilePathService _filePathService = filePathService; private readonly ITelemetryReporter _telemetryReporter = telemetryReporter; - public async Task GetCSharpSemanticTokensResponseAsync(VersionedDocumentContext documentContext, ImmutableArray csharpRanges, Guid correlationId, CancellationToken cancellationToken) + public async Task GetCSharpSemanticTokensResponseAsync(DocumentContext documentContext, ImmutableArray csharpRanges, Guid correlationId, CancellationToken cancellationToken) { using var _ = _telemetryReporter.TrackLspRequest(nameof(SemanticTokensRange.GetSemanticTokensAsync), Constants.ExternalAccessServerName, correlationId); diff --git a/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/Endpoints/RazorCustomMessageTarget.cs b/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/Endpoints/RazorCustomMessageTarget.cs index 1c52c7fd813..1ae779026f7 100644 --- a/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/Endpoints/RazorCustomMessageTarget.cs +++ b/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/Endpoints/RazorCustomMessageTarget.cs @@ -136,7 +136,6 @@ private async Task> TrySynchronizeV int requiredHostDocumentVersion, TextDocumentIdentifier hostDocument, CancellationToken cancellationToken, - LanguageServer.Protocol.Range? _ = null, bool rejectOnNewerParallelRequest = true, [CallerMemberName] string? caller = null) where TVirtualDocumentSnapshot : VirtualDocumentSnapshot @@ -201,21 +200,6 @@ private async Task> TrySynchronizeV _logger.LogDebug($"{(result.Synchronized ? "Did" : "Did NOT")} synchronize for {caller}: Version {requiredHostDocumentVersion} for {result.VirtualSnapshot?.Uri}"); } - //if (requiredHostDocumentVersion == 1 && - // result.Synchronized && - // result.VirtualSnapshot is not null && - // range is not null) - //{ - // // If we're at version 1, and we're synced, lets make sure the buffer has enough lines to handle the request - // if (range.Start.Line > result.VirtualSnapshot.Snapshot.LineCount || - // range.End.Line > result.VirtualSnapshot.Snapshot.LineCount) - // { - // Debug.Fail("It worked!"); - // _logger.LogWarning($"Requested line ({range.Start.Line} or {range.End.Line}) is out of bounds for {result.VirtualSnapshot.Uri}. Sync failed."); - // return new SynchronizedResult(false, null); - // } - //} - return result; } diff --git a/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/Endpoints/RazorCustomMessageTarget_SemanticTokens.cs b/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/Endpoints/RazorCustomMessageTarget_SemanticTokens.cs index 15b5ae81682..654bb036108 100644 --- a/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/Endpoints/RazorCustomMessageTarget_SemanticTokens.cs +++ b/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/Endpoints/RazorCustomMessageTarget_SemanticTokens.cs @@ -62,8 +62,7 @@ internal partial class RazorCustomMessageTarget var (synchronized, csharpDoc) = await TrySynchronizeVirtualDocumentAsync( semanticTokensParams.RequiredHostDocumentVersion, semanticTokensParams.TextDocument, - cancellationToken, - semanticTokensParams.Ranges.FirstOrDefault()); + cancellationToken); if (csharpDoc is null) { @@ -90,12 +89,12 @@ internal partial class RazorCustomMessageTarget { try { - var result = await _requestInvoker.ReinvokeRequestOnServerAsync( - textBuffer, - lspMethodName, - languageServerName, - requestParams, - cancellationToken).ConfigureAwait(false); + var result = await _requestInvoker.ReinvokeRequestOnServerAsync( + textBuffer, + lspMethodName, + languageServerName, + requestParams, + cancellationToken).ConfigureAwait(false); response = result?.Response; } diff --git a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/AutoInsert/OnAutoInsertEndpointTest.NetFx.cs b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/AutoInsert/OnAutoInsertEndpointTest.NetFx.cs index 7f7e31e9747..26b5acd8561 100644 --- a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/AutoInsert/OnAutoInsertEndpointTest.NetFx.cs +++ b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/AutoInsert/OnAutoInsertEndpointTest.NetFx.cs @@ -371,7 +371,7 @@ private async Task VerifyCSharpOnAutoInsertAsync(string input, string expected, InsertSpaces = true }, }; - Assert.True(DocumentContextFactory.TryCreateForOpenDocument(@params.TextDocument, out var documentContext)); + Assert.True(DocumentContextFactory.TryCreate(@params.TextDocument, out var documentContext)); var requestContext = CreateRazorRequestContext(documentContext); diff --git a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/CodeActions/CodeActionEndToEndTest.NetFx.cs b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/CodeActions/CodeActionEndToEndTest.NetFx.cs index 3afd4bc01c2..0fa1e83882d 100644 --- a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/CodeActions/CodeActionEndToEndTest.NetFx.cs +++ b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/CodeActions/CodeActionEndToEndTest.NetFx.cs @@ -1240,9 +1240,8 @@ private class GenerateMethodResolverDocumentContextFactory : TestDocumentContext public GenerateMethodResolverDocumentContextFactory (string filePath, RazorCodeDocument codeDocument, - TagHelperDescriptor[]? tagHelpers = null, - int? version = null) - : base(filePath, codeDocument, version) + TagHelperDescriptor[]? tagHelpers = null) + : base(filePath, codeDocument) { _tagHelperDescriptors = CreateTagHelperDescriptors(); if (tagHelpers is not null) @@ -1254,7 +1253,6 @@ public GenerateMethodResolverDocumentContextFactory public override bool TryCreate( Uri documentUri, VSProjectContext? projectContext, - bool versioned, [NotNullWhen(true)] out DocumentContext? context) { if (FilePath is null || CodeDocument is null) diff --git a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/Completion/CompletionListProviderTest.cs b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/Completion/CompletionListProviderTest.cs index e3f63cfb270..e793aa35659 100644 --- a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/Completion/CompletionListProviderTest.cs +++ b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/Completion/CompletionListProviderTest.cs @@ -27,7 +27,7 @@ public class CompletionListProviderTest : LanguageServerTestBase private readonly RazorCompletionListProvider _razorCompletionProvider; private readonly DelegatedCompletionListProvider _delegatedCompletionProvider; private readonly VSInternalCompletionContext _completionContext; - private readonly VersionedDocumentContext _documentContext; + private readonly DocumentContext _documentContext; private readonly VSInternalClientCapabilities _clientCapabilities; public CompletionListProviderTest(ITestOutputHelper testOutput) @@ -38,7 +38,7 @@ public CompletionListProviderTest(ITestOutputHelper testOutput) _razorCompletionProvider = new TestRazorCompletionListProvider(_completionList1, new[] { SharedTriggerCharacter, }, LoggerFactory); _delegatedCompletionProvider = new TestDelegatedCompletionListProvider(_completionList2, new[] { SharedTriggerCharacter, CompletionList2OnlyTriggerCharacter }); _completionContext = new VSInternalCompletionContext(); - _documentContext = TestDocumentContext.From("C:/path/to/file.cshtml", hostDocumentVersion: 0); + _documentContext = TestDocumentContext.From("C:/path/to/file.cshtml"); _clientCapabilities = new VSInternalClientCapabilities(); } @@ -89,7 +89,7 @@ public TestDelegatedCompletionListProvider(VSInternalCompletionList completionLi public override Task GetCompletionListAsync( int absoluteIndex, VSInternalCompletionContext completionContext, - VersionedDocumentContext documentContext, + DocumentContext documentContext, VSInternalClientCapabilities clientCapabilities, Guid correlationId, CancellationToken cancellationToken) @@ -117,7 +117,7 @@ public TestRazorCompletionListProvider( public override Task GetCompletionListAsync( int absoluteIndex, VSInternalCompletionContext completionContext, - VersionedDocumentContext documentContext, + DocumentContext documentContext, VSInternalClientCapabilities clientCapabilities, HashSet existingCompletions, CancellationToken cancellationToken) diff --git a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/Completion/Delegation/DelegatedCompletionItemResolverTest.NetFx.cs b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/Completion/Delegation/DelegatedCompletionItemResolverTest.NetFx.cs index 90b3f93b7db..6df70d43a2c 100644 --- a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/Completion/Delegation/DelegatedCompletionItemResolverTest.NetFx.cs +++ b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/Completion/Delegation/DelegatedCompletionItemResolverTest.NetFx.cs @@ -51,7 +51,7 @@ public DelegatedCompletionItemResolverTest(ITestOutputHelper testOutput) } }; - var documentContext = TestDocumentContext.From("C:/path/to/file.cshtml", hostDocumentVersion: 0); + var documentContext = TestDocumentContext.From("C:/path/to/file.cshtml"); _csharpCompletionParams = new DelegatedCompletionParams( documentContext.GetTextDocumentIdentifierAndVersion(), VsLspFactory.CreatePosition(10, 6), @@ -222,7 +222,7 @@ private async Task ResolveCompletionItemAsync(string c await using var csharpServer = await CreateCSharpServerAsync(codeDocument); var server = TestDelegatedCompletionItemResolverServer.Create(csharpServer, DisposalToken); - var documentContextFactory = new TestDocumentContextFactory("C:/path/to/file.razor", codeDocument, version: 123); + var documentContextFactory = new TestDocumentContextFactory("C:/path/to/file.razor", codeDocument); var resolver = new DelegatedCompletionItemResolver(documentContextFactory, _formattingService.GetValue(), server); var (containingCompletionList, csharpCompletionParams) = await GetCompletionListAndOriginalParamsAsync( cursorPosition, codeDocument, csharpServer); @@ -268,7 +268,7 @@ private async Task CreateCSharpServerAsync(RazorCodeDocumen CSharpTestLspServer csharpServer) { var completionContext = new VSInternalCompletionContext() { TriggerKind = CompletionTriggerKind.Invoked }; - var documentContext = TestDocumentContext.From("C:/path/to/file.razor", codeDocument, hostDocumentVersion: 1337); + var documentContext = TestDocumentContext.From("C:/path/to/file.razor", codeDocument); var provider = TestDelegatedCompletionListProvider.Create(csharpServer, LoggerFactory, DisposalToken); var completionList = await provider.GetCompletionListAsync( diff --git a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/Completion/Delegation/ResponseRewriterTestBase.cs b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/Completion/Delegation/ResponseRewriterTestBase.cs index 66225461c0c..b338d8d03a1 100644 --- a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/Completion/Delegation/ResponseRewriterTestBase.cs +++ b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/Completion/Delegation/ResponseRewriterTestBase.cs @@ -27,7 +27,7 @@ private protected async Task GetRewrittenCompletionLis { var completionContext = new VSInternalCompletionContext(); var codeDocument = CreateCodeDocument(documentContent); - var documentContext = TestDocumentContext.From("C:/path/to/file.cshtml", codeDocument, hostDocumentVersion: 0); + var documentContext = TestDocumentContext.From("C:/path/to/file.cshtml", codeDocument); var provider = TestDelegatedCompletionListProvider.Create(initialCompletionList, LoggerFactory, rewriter ?? Rewriter); var clientCapabilities = new VSInternalClientCapabilities(); var completionList = await provider.GetCompletionListAsync(absoluteIndex, completionContext, documentContext, clientCapabilities, correlationId: Guid.Empty, cancellationToken: DisposalToken); diff --git a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/Completion/RazorCompletionListProviderTest.cs b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/Completion/RazorCompletionListProviderTest.cs index cd809b718d3..1f80264a23c 100644 --- a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/Completion/RazorCompletionListProviderTest.cs +++ b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/Completion/RazorCompletionListProviderTest.cs @@ -364,7 +364,7 @@ public async Task GetCompletionListAsync_ProvidesDirectiveCompletionItems(string var documentPath = "C:/path/to/document.cshtml"; TestFileMarkupParser.GetPosition(documentText, out documentText, out var cursorPosition); var codeDocument = CreateCodeDocument(documentText); - var documentContext = TestDocumentContext.From(documentPath, codeDocument, hostDocumentVersion: 0); + var documentContext = TestDocumentContext.From(documentPath, codeDocument); var provider = new RazorCompletionListProvider(_completionFactsService, _completionListCache, LoggerFactory); // Act @@ -385,7 +385,7 @@ public async Task GetCompletionListAsync_ProvidesDirectiveCompletions_Incomplete // Arrange var documentPath = "C:/path/to/document.cshtml"; var codeDocument = CreateCodeDocument("@"); - var documentContext = TestDocumentContext.From(documentPath, codeDocument, hostDocumentVersion: 0); + var documentContext = TestDocumentContext.From(documentPath, codeDocument); var completionContext = new VSInternalCompletionContext() { TriggerKind = CompletionTriggerKind.TriggerForIncompleteCompletions, @@ -418,7 +418,7 @@ public async Task GetCompletionListAsync_ProvidesInjectOnIncomplete_KeywordIn() var tagHelperContext = TagHelperDocumentContext.Create(prefix: string.Empty, [tagHelper]); var codeDocument = CreateCodeDocument("@in"); codeDocument.SetTagHelperContext(tagHelperContext); - var documentContext = TestDocumentContext.From(documentPath, codeDocument, hostDocumentVersion: 0); + var documentContext = TestDocumentContext.From(documentPath, codeDocument); var provider = new RazorCompletionListProvider(_completionFactsService, _completionListCache, LoggerFactory); var completionContext = new VSInternalCompletionContext() { @@ -447,7 +447,7 @@ public async Task GetCompletionListAsync_DoesNotProvideInjectOnInvoked() var tagHelperContext = TagHelperDocumentContext.Create(prefix: string.Empty, [tagHelper]); var codeDocument = CreateCodeDocument("@inje"); codeDocument.SetTagHelperContext(tagHelperContext); - var documentContext = TestDocumentContext.From(documentPath, codeDocument, hostDocumentVersion: 0); + var documentContext = TestDocumentContext.From(documentPath, codeDocument); var provider = new RazorCompletionListProvider(_completionFactsService, _completionListCache, LoggerFactory); var completionContext = new VSInternalCompletionContext() { @@ -475,7 +475,7 @@ public async Task GetCompletionListAsync_ProvidesInjectOnIncomplete() var tagHelperContext = TagHelperDocumentContext.Create(prefix: string.Empty, [tagHelper]); var codeDocument = CreateCodeDocument("@inje"); codeDocument.SetTagHelperContext(tagHelperContext); - var documentContext = TestDocumentContext.From(documentPath, codeDocument, hostDocumentVersion: 0); + var documentContext = TestDocumentContext.From(documentPath, codeDocument); var provider = new RazorCompletionListProvider(_completionFactsService, _completionListCache, LoggerFactory); var completionContext = new VSInternalCompletionContext() { @@ -505,7 +505,7 @@ public async Task GetCompletionListAsync_ProvidesTagHelperElementCompletionItems var tagHelperContext = TagHelperDocumentContext.Create(prefix: string.Empty, [tagHelper]); var codeDocument = CreateCodeDocument("<"); codeDocument.SetTagHelperContext(tagHelperContext); - var documentContext = TestDocumentContext.From(documentPath, codeDocument, hostDocumentVersion: 0); + var documentContext = TestDocumentContext.From(documentPath, codeDocument); var provider = new RazorCompletionListProvider(_completionFactsService, _completionListCache, LoggerFactory); // Act @@ -535,7 +535,7 @@ public async Task GetCompletionListAsync_ProvidesTagHelperAttributeItems() var tagHelperContext = TagHelperDocumentContext.Create(prefix: string.Empty, [tagHelper]); var codeDocument = CreateCodeDocument("(MockBehavior.Strict); diff --git a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/Definition/DefinitionEndpointDelegationTest.cs b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/Definition/DefinitionEndpointDelegationTest.cs index 2711a8dc359..b844af4ff61 100644 --- a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/Definition/DefinitionEndpointDelegationTest.cs +++ b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/Definition/DefinitionEndpointDelegationTest.cs @@ -240,7 +240,7 @@ await projectManager.UpdateAsync(updater => var searchEngine = new RazorComponentSearchEngine(projectManager, LoggerFactory); var razorUri = new Uri(razorFilePath); - Assert.True(DocumentContextFactory.TryCreateForOpenDocument(razorUri, out var documentContext)); + Assert.True(DocumentContextFactory.TryCreate(razorUri, out var documentContext)); var requestContext = CreateRazorRequestContext(documentContext); var endpoint = new DefinitionEndpoint(searchEngine, DocumentMappingService, LanguageServerFeatureOptions, languageServer, LoggerFactory); diff --git a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/DocumentContextFactoryTest.cs b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/DocumentContextFactoryTest.cs index 61e48cb7880..a202af3d35c 100644 --- a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/DocumentContextFactoryTest.cs +++ b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/DocumentContextFactoryTest.cs @@ -51,7 +51,7 @@ public void TryCreateForOpenDocumentAsync_CanNotResolveDocument_ReturnsNull() var factory = new DocumentContextFactory(_projectManager, LoggerFactory); // Act - Assert.False(factory.TryCreateForOpenDocument(uri, out _)); + Assert.False(factory.TryCreate(uri, out _)); } [Fact] @@ -130,10 +130,10 @@ await _projectManager.UpdateAsync(updater => var factory = new DocumentContextFactory(_projectManager, LoggerFactory); // Act - Assert.True(factory.TryCreateForOpenDocument(uri, out var documentContext)); + Assert.True(factory.TryCreate(uri, out var documentContext)); // Assert - Assert.Equal(1, documentContext.Version); + Assert.Equal(1, documentContext.Snapshot.Version); Assert.Equal(uri, documentContext.Uri); Assert.Same(documentSnapshot, documentContext.Snapshot); } diff --git a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/DocumentHighlighting/DocumentHighlightEndpointTest.cs b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/DocumentHighlighting/DocumentHighlightEndpointTest.cs index 060c282439d..655f2796130 100644 --- a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/DocumentHighlighting/DocumentHighlightEndpointTest.cs +++ b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/DocumentHighlighting/DocumentHighlightEndpointTest.cs @@ -112,7 +112,7 @@ private async Task VerifyHighlightingRangesAsync(string input) await csharpServer.OpenDocumentAsync(csharpDocumentUri, csharpSourceText.ToString()); var razorFilePath = "C:/path/to/file.razor"; - var documentContextFactory = new TestDocumentContextFactory(razorFilePath, codeDocument, version: 1337); + var documentContextFactory = new TestDocumentContextFactory(razorFilePath, codeDocument); var languageServerFeatureOptions = Mock.Of(options => options.SupportsFileManipulation == true && options.SingleServerSupport == true && diff --git a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/DocumentPresentation/TextDocumentUriPresentationEndpointTests.cs b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/DocumentPresentation/TextDocumentUriPresentationEndpointTests.cs index 100667df822..52ee2ceb54a 100644 --- a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/DocumentPresentation/TextDocumentUriPresentationEndpointTests.cs +++ b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/DocumentPresentation/TextDocumentUriPresentationEndpointTests.cs @@ -50,7 +50,7 @@ public async Task Handle_SimpleComponent_ReturnsResult() await projectManager.UpdateAsync(updater => updater.DocumentOpened(project.Key, razorFilePath, SourceText.From("
"))); var documentSnapshot = projectManager.GetLoadedProject(project.Key).GetDocument(razorFilePath).AssumeNotNull(); var documentContextFactory = new DocumentContextFactory(projectManager, LoggerFactory); - Assert.True(documentContextFactory.TryCreateForOpenDocument(uri, null, out var documentContext)); + Assert.True(documentContextFactory.TryCreate(uri, null, out var documentContext)); var clientConnection = new Mock(MockBehavior.Strict); @@ -106,7 +106,7 @@ public async Task Handle_SimpleComponentWithChildFile_ReturnsResult() await projectManager.UpdateAsync(updater => updater.DocumentOpened(project.Key, razorFilePath, SourceText.From("
"))); var documentSnapshot = projectManager.GetLoadedProject(project.Key).GetDocument(razorFilePath).AssumeNotNull(); var documentContextFactory = new DocumentContextFactory(projectManager, LoggerFactory); - Assert.True(documentContextFactory.TryCreateForOpenDocument(uri, null, out var documentContext)); + Assert.True(documentContextFactory.TryCreate(uri, null, out var documentContext)); var clientConnection = new Mock(MockBehavior.Strict); @@ -173,7 +173,7 @@ public async Task Handle_ComponentWithRequiredAttribute_ReturnsResult() await projectManager.UpdateAsync(updater => updater.DocumentOpened(project.Key, razorFilePath, SourceText.From("
"))); var documentSnapshot = projectManager.GetLoadedProject(project.Key).GetDocument(razorFilePath).AssumeNotNull(); var documentContextFactory = new DocumentContextFactory(projectManager, LoggerFactory); - Assert.True(documentContextFactory.TryCreateForOpenDocument(uri, null, out var documentContext)); + Assert.True(documentContextFactory.TryCreate(uri, null, out var documentContext)); var clientConnection = new Mock(MockBehavior.Strict); @@ -379,7 +379,7 @@ public async Task Handle_ComponentWithNestedFiles_ReturnsResult() await projectManager.UpdateAsync(updater => updater.DocumentOpened(project.Key, razorFilePath, SourceText.From("
"))); var documentSnapshot = projectManager.GetLoadedProject(project.Key).GetDocument(razorFilePath).AssumeNotNull(); var documentContextFactory = new DocumentContextFactory(projectManager, LoggerFactory); - Assert.True(documentContextFactory.TryCreateForOpenDocument(uri, null, out var documentContext)); + Assert.True(documentContextFactory.TryCreate(uri, null, out var documentContext)); var clientConnection = new Mock(MockBehavior.Strict); diff --git a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/DocumentSymbols/DocumentSymbolEndpointTest.cs b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/DocumentSymbols/DocumentSymbolEndpointTest.cs index f8cbf5683e3..92907ce1842 100644 --- a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/DocumentSymbols/DocumentSymbolEndpointTest.cs +++ b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/DocumentSymbols/DocumentSymbolEndpointTest.cs @@ -117,7 +117,7 @@ private async Task VerifyDocumentSymbolsAsync(string input, bool hierarchical = } } }; - Assert.True(DocumentContextFactory.TryCreateForOpenDocument(request.TextDocument, out var documentContext)); + Assert.True(DocumentContextFactory.TryCreate(request.TextDocument, out var documentContext)); var requestContext = CreateRazorRequestContext(documentContext); var result = await endpoint.HandleRequestAsync(request, requestContext, DisposalToken); diff --git a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/FindReferences/FindAllReferencesEndpointTest.cs b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/FindReferences/FindAllReferencesEndpointTest.cs index ff0cc641c58..8436afc4d0e 100644 --- a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/FindReferences/FindAllReferencesEndpointTest.cs +++ b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/FindReferences/FindAllReferencesEndpointTest.cs @@ -64,7 +64,7 @@ private async Task VerifyCSharpFindAllReferencesAsyncAsync(string input) }, Position = sourceText.GetPosition(cursorPosition) }; - Assert.True(DocumentContextFactory.TryCreateForOpenDocument(request.TextDocument, out var documentContext)); + Assert.True(DocumentContextFactory.TryCreate(request.TextDocument, out var documentContext)); var requestContext = CreateRazorRequestContext(documentContext); // Act diff --git a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/Folding/FoldingEndpointTest.cs b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/Folding/FoldingEndpointTest.cs index 4bafb189d06..1cff2a0d10f 100644 --- a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/Folding/FoldingEndpointTest.cs +++ b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/Folding/FoldingEndpointTest.cs @@ -222,7 +222,7 @@ private async Task VerifyRazorFoldsAsync(string input, string? filePath = null) } } }; - Assert.True(DocumentContextFactory.TryCreateForOpenDocument(request.TextDocument, out var documentContext)); + Assert.True(DocumentContextFactory.TryCreate(request.TextDocument, out var documentContext)); var requestContext = CreateRazorRequestContext(documentContext); // Act diff --git a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/Formatting_NetFx/DocumentOnTypeFormattingEndpointTest.cs b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/Formatting_NetFx/DocumentOnTypeFormattingEndpointTest.cs index 17177a8e49c..bdcdea1996f 100644 --- a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/Formatting_NetFx/DocumentOnTypeFormattingEndpointTest.cs +++ b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/Formatting_NetFx/DocumentOnTypeFormattingEndpointTest.cs @@ -207,7 +207,7 @@ public async Task Handle_OnTypeFormatting_UnexpectedTriggerCharacter_ReturnsNull Position = VsLspFactory.CreatePosition(2, 11), Options = new FormattingOptions { InsertSpaces = true, TabSize = 4 } }; - Assert.True(documentContextFactory.TryCreateForOpenDocument(uri, out var documentContext)); + Assert.True(documentContextFactory.TryCreate(uri, out var documentContext)); var requestContext = CreateRazorRequestContext(documentContext); // Act diff --git a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/Formatting_NetFx/FormattingLanguageServerTestBase.cs b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/Formatting_NetFx/FormattingLanguageServerTestBase.cs index 25a4ba44e63..cf6fe184229 100644 --- a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/Formatting_NetFx/FormattingLanguageServerTestBase.cs +++ b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/Formatting_NetFx/FormattingLanguageServerTestBase.cs @@ -37,7 +37,7 @@ internal class DummyRazorFormattingService : IRazorFormattingService { public bool Called { get; private set; } - public Task FormatAsync(VersionedDocumentContext documentContext, Range? range, FormattingOptions options, CancellationToken cancellationToken) + public Task FormatAsync(DocumentContext documentContext, Range? range, FormattingOptions options, CancellationToken cancellationToken) { Called = true; return SpecializedTasks.EmptyArray(); diff --git a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/Formatting_NetFx/FormattingTestBase.cs b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/Formatting_NetFx/FormattingTestBase.cs index a6089dfe1d8..c8bab7fac2d 100644 --- a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/Formatting_NetFx/FormattingTestBase.cs +++ b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/Formatting_NetFx/FormattingTestBase.cs @@ -77,7 +77,7 @@ private async Task RunFormattingTestAsync(string input, string expected, int tab }; var formattingService = await TestRazorFormattingService.CreateWithFullSupportAsync(LoggerFactory, codeDocument, razorLSPOptions); - var documentContext = new VersionedDocumentContext(uri, documentSnapshot, projectContext: null, version: 1); + var documentContext = new DocumentContext(uri, documentSnapshot, projectContext: null); // Act var edits = await formattingService.FormatAsync(documentContext, range, options, DisposalToken); @@ -126,7 +126,7 @@ private protected async Task RunOnTypeFormattingTestAsync( TabSize = tabSize, InsertSpaces = insertSpaces, }; - var documentContext = new VersionedDocumentContext(uri, documentSnapshot, projectContext: null, version: 1); + var documentContext = new DocumentContext(uri, documentSnapshot, projectContext: null); // Act var edits = await formattingService.FormatOnTypeAsync(documentContext, languageKind, Array.Empty(), options, hostDocumentIndex: positionAfterTrigger, triggerCharacter: triggerCharacter, DisposalToken); @@ -194,7 +194,7 @@ protected async Task RunCodeActionFormattingTestAsync( TabSize = tabSize, InsertSpaces = insertSpaces, }; - var documentContext = new VersionedDocumentContext(uri, documentSnapshot, projectContext: null, version: 1); + var documentContext = new DocumentContext(uri, documentSnapshot, projectContext: null); // Act var edits = await formattingService.FormatCodeActionAsync(documentContext, languageKind, codeActionEdits, options, DisposalToken); diff --git a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/Hover/HoverServiceTest.cs b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/Hover/HoverServiceTest.cs index d7a1c2bc4a2..411d6405171 100644 --- a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/Hover/HoverServiceTest.cs +++ b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/Hover/HoverServiceTest.cs @@ -871,7 +871,7 @@ private async Task GetResultFromSingleServerEndpointAsync(strin await csharpServer.OpenDocumentAsync(csharpDocumentUri, csharpSourceText.ToString()); var razorFilePath = "C:/path/to/file.razor"; - var documentContextFactory = new TestDocumentContextFactory(razorFilePath, codeDocument, version: 1337); + var documentContextFactory = new TestDocumentContextFactory(razorFilePath, codeDocument); var languageServerFeatureOptions = Mock.Of(options => options.SupportsFileManipulation == true && options.SingleServerSupport == true && @@ -906,7 +906,7 @@ private async Task GetResultFromSingleServerEndpointAsync(strin return await endpoint.HandleRequestAsync(request, requestContext, DisposalToken); } - private VersionedDocumentContext CreateDefaultDocumentContext() + private DocumentContext CreateDefaultDocumentContext() { var txt = """ @addTagHelper *, TestAssembly @@ -927,9 +927,10 @@ public void Increment(){ d.FilePath == path && d.FileKind == FileKinds.Component && d.GetTextAsync() == Task.FromResult(sourceText) && + d.Version == 0 && d.Project == projectSnapshot, MockBehavior.Strict); - var documentContext = new VersionedDocumentContext(new Uri(path), snapshot, projectContext: null, 1337); + var documentContext = new DocumentContext(new Uri(path), snapshot, projectContext: null); return documentContext; } diff --git a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/Implementation/ImplementationEndpointTest.cs b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/Implementation/ImplementationEndpointTest.cs index 0dedf24fcda..6ff8c8f61ac 100644 --- a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/Implementation/ImplementationEndpointTest.cs +++ b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/Implementation/ImplementationEndpointTest.cs @@ -105,7 +105,7 @@ private async Task VerifyCSharpGoToImplementationAsync(string input) }, Position = codeDocument.Source.Text.GetPosition(cursorPosition) }; - Assert.True(DocumentContextFactory.TryCreateForOpenDocument(request.TextDocument, out var documentContext)); + Assert.True(DocumentContextFactory.TryCreate(request.TextDocument, out var documentContext)); var requestContext = CreateRazorRequestContext(documentContext); // Act diff --git a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/InlayHints/InlayHintEndpointTest.cs b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/InlayHints/InlayHintEndpointTest.cs index 49e8758c700..9b964c0898a 100644 --- a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/InlayHints/InlayHintEndpointTest.cs +++ b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/InlayHints/InlayHintEndpointTest.cs @@ -106,7 +106,7 @@ private async Task VerifyInlayHintsAsync(string input, Dictionary sourceMappings) diff --git a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/Mapping/RazorMapToDocumentRangesEndpointTest.cs b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/Mapping/RazorMapToDocumentRangesEndpointTest.cs index 271ebda9975..b70530e5cb0 100644 --- a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/Mapping/RazorMapToDocumentRangesEndpointTest.cs +++ b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/Mapping/RazorMapToDocumentRangesEndpointTest.cs @@ -61,7 +61,6 @@ public async Task Handle_MapToDocumentRanges_CSharp() // Assert Assert.NotNull(response); Assert.Equal(expectedRange, response!.Ranges[0]); - Assert.Equal(1337, response.HostDocumentVersion); } [Fact] @@ -94,7 +93,6 @@ public async Task Handle_MapToDocumentRanges_CSharp_Unmapped() // Assert Assert.NotNull(response); Assert.Equal(VsLspFactory.UndefinedRange, response!.Ranges[0]); - Assert.Equal(1337, response.HostDocumentVersion); } [Fact] @@ -127,7 +125,6 @@ public async Task Handle_MapToDocumentRanges_CSharp_LeadingOverlapsUnmapped() // Assert Assert.NotNull(response); Assert.Equal(VsLspFactory.UndefinedRange, response!.Ranges[0]); - Assert.Equal(1337, response.HostDocumentVersion); } [Fact] @@ -160,7 +157,6 @@ public async Task Handle_MapToDocumentRanges_CSharp_TrailingOverlapsUnmapped() // Assert Assert.NotNull(response); Assert.Equal(VsLspFactory.UndefinedRange, response!.Ranges[0]); - Assert.Equal(1337, response.HostDocumentVersion); } [Fact] @@ -186,7 +182,6 @@ public async Task Handle_MapToDocumentRanges_Html() // Assert Assert.NotNull(response); Assert.Equal(request.ProjectedRanges[0], response!.Ranges[0]); - Assert.Equal(1337, response.HostDocumentVersion); } [Fact] @@ -212,7 +207,6 @@ public async Task Handle_MapToDocumentRanges_Razor() // Assert Assert.NotNull(response); Assert.Equal(request.ProjectedRanges[0], response!.Ranges[0]); - Assert.Equal(1337, response.HostDocumentVersion); } [Fact] @@ -246,7 +240,6 @@ public async Task Handle_MapToDocumentRanges_Unsupported() // Assert Assert.NotNull(response); Assert.Equal(VsLspFactory.UndefinedRange, response!.Ranges[0]); - Assert.Equal(1337, response.HostDocumentVersion); } private static RazorCodeDocument CreateCodeDocumentWithCSharpProjection(string razorSource, string projectedCSharpSource, IEnumerable sourceMappings) diff --git a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/ProjectContexts/ProjectContextsEndpointTest.cs b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/ProjectContexts/ProjectContextsEndpointTest.cs index 8a17f7af7d4..1ebfb541ed6 100644 --- a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/ProjectContexts/ProjectContextsEndpointTest.cs +++ b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/ProjectContexts/ProjectContextsEndpointTest.cs @@ -39,7 +39,7 @@ public async Task GetProjectContexts_ReturnsExpected() } }; - Assert.True(DocumentContextFactory.TryCreateForOpenDocument(request.TextDocument.Uri, out var documentContext)); + Assert.True(DocumentContextFactory.TryCreate(request.TextDocument.Uri, out var documentContext)); var requestContext = CreateRazorRequestContext(documentContext); var results = await endpoint.HandleRequestAsync(request, requestContext, default); diff --git a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/Refactoring/RenameEndpointDelegationTest.cs b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/Refactoring/RenameEndpointDelegationTest.cs index 620a6bba2fe..e96dbb8b141 100644 --- a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/Refactoring/RenameEndpointDelegationTest.cs +++ b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/Refactoring/RenameEndpointDelegationTest.cs @@ -86,7 +86,7 @@ await projectManager.UpdateAsync(updater => Position = codeDocument.Source.Text.GetPosition(cursorPosition), NewName = newName }; - Assert.True(DocumentContextFactory.TryCreateForOpenDocument(request.TextDocument, out var documentContext)); + Assert.True(DocumentContextFactory.TryCreate(request.TextDocument, out var documentContext)); var requestContext = CreateRazorRequestContext(documentContext); // Act diff --git a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/Refactoring/RenameEndpointTest.cs b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/Refactoring/RenameEndpointTest.cs index 7f5a35cd276..c4c98a997d8 100644 --- a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/Refactoring/RenameEndpointTest.cs +++ b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/Refactoring/RenameEndpointTest.cs @@ -122,7 +122,7 @@ public async Task Handle_Rename_FileManipulationNotSupported_ReturnsNull() NewName = "Component5" }; - Assert.True(documentContextFactory.TryCreateForOpenDocument(uri, out var documentContext)); + Assert.True(documentContextFactory.TryCreate(uri, out var documentContext)); var requestContext = CreateRazorRequestContext(documentContext); // Act @@ -145,7 +145,7 @@ public async Task Handle_Rename_WithNamespaceDirective() NewName = "Component5" }; - Assert.True(documentContextFactory.TryCreateForOpenDocument(uri, out var documentContext)); + Assert.True(documentContextFactory.TryCreate(uri, out var documentContext)); var requestContext = CreateRazorRequestContext(documentContext); // Act @@ -186,7 +186,7 @@ public async Task Handle_Rename_OnComponentParameter_ReturnsNull() NewName = "Test2" }; - Assert.True(documentContextFactory.TryCreateForOpenDocument(uri, out var documentContext)); + Assert.True(documentContextFactory.TryCreate(uri, out var documentContext)); var requestContext = CreateRazorRequestContext(documentContext); // Act @@ -209,7 +209,7 @@ public async Task Handle_Rename_OnOpeningBrace_ReturnsNull() NewName = "Test2" }; - Assert.True(documentContextFactory.TryCreateForOpenDocument(uri, out var documentContext)); + Assert.True(documentContextFactory.TryCreate(uri, out var documentContext)); var requestContext = CreateRazorRequestContext(documentContext); // Act @@ -232,7 +232,7 @@ public async Task Handle_Rename_OnComponentNameLeadingEdge_ReturnsResult() NewName = "Test2" }; - Assert.True(documentContextFactory.TryCreateForOpenDocument(uri, out var documentContext)); + Assert.True(documentContextFactory.TryCreate(uri, out var documentContext)); var requestContext = CreateRazorRequestContext(documentContext); // Act @@ -255,7 +255,7 @@ public async Task Handle_Rename_OnComponentName_ReturnsResult() NewName = "Test2" }; - Assert.True(documentContextFactory.TryCreateForOpenDocument(uri, out var documentContext)); + Assert.True(documentContextFactory.TryCreate(uri, out var documentContext)); var requestContext = CreateRazorRequestContext(documentContext); // Act @@ -278,7 +278,7 @@ public async Task Handle_Rename_OnComponentNameTrailingEdge_ReturnsResult() NewName = "Test2" }; - Assert.True(documentContextFactory.TryCreateForOpenDocument(uri, out var documentContext)); + Assert.True(documentContextFactory.TryCreate(uri, out var documentContext)); var requestContext = CreateRazorRequestContext(documentContext); // Act @@ -301,7 +301,7 @@ public async Task Handle_Rename_ComponentInSameFile() NewName = "Component5" }; - Assert.True(documentContextFactory.TryCreateForOpenDocument(uri, out var documentContext)); + Assert.True(documentContextFactory.TryCreate(uri, out var documentContext)); var requestContext = CreateRazorRequestContext(documentContext); // Act @@ -387,7 +387,7 @@ public async Task Handle_Rename_FullyQualifiedAndNot() NewName = "Component5" }; - Assert.True(documentContextFactory.TryCreateForOpenDocument(uri, out var documentContext)); + Assert.True(documentContextFactory.TryCreate(uri, out var documentContext)); var requestContext = CreateRazorRequestContext(documentContext); // Act @@ -433,7 +433,7 @@ public async Task Handle_Rename_MultipleFileUsages() NewName = "Component5" }; - Assert.True(documentContextFactory.TryCreateForOpenDocument(uri, out var documentContext)); + Assert.True(documentContextFactory.TryCreate(uri, out var documentContext)); var requestContext = CreateRazorRequestContext(documentContext); // Act @@ -486,7 +486,7 @@ public async Task Handle_Rename_DifferentDirectories() NewName = "TestComponent" }; - Assert.True(documentContextFactory.TryCreateForOpenDocument(uri, out var documentContext)); + Assert.True(documentContextFactory.TryCreate(uri, out var documentContext)); var requestContext = CreateRazorRequestContext(documentContext); // Act @@ -557,7 +557,7 @@ public async Task Handle_Rename_SingleServer_CallsDelegatedLanguageServer() NewName = "Test2" }; - Assert.True(documentContextFactory.TryCreateForOpenDocument(uri, out var documentContext)); + Assert.True(documentContextFactory.TryCreate(uri, out var documentContext)); var requestContext = CreateRazorRequestContext(documentContext); // Act @@ -597,7 +597,7 @@ public async Task Handle_Rename_SingleServer_DoesNotDelegateForRazor() NewName = "Test2" }; - Assert.True(documentContextFactory.TryCreateForOpenDocument(request.TextDocument.Uri, out var documentContext)); + Assert.True(documentContextFactory.TryCreate(request.TextDocument.Uri, out var documentContext)); var requestContext = CreateRazorRequestContext(documentContext); // Act diff --git a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/Semantic/SemanticTokensTest.cs b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/Semantic/SemanticTokensTest.cs index 0bcf1c28d4e..748262ec53a 100644 --- a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/Semantic/SemanticTokensTest.cs +++ b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/Semantic/SemanticTokensTest.cs @@ -919,7 +919,7 @@ private async Task AssertSemanticTokensAsync( AssertSemanticTokensMatchesBaseline(sourceText, tokens, testName.AssumeNotNull()); } - private static VersionedDocumentContext CreateDocumentContext( + private static DocumentContext CreateDocumentContext( string documentText, bool isRazorFile, ImmutableArray tagHelpers, @@ -942,16 +942,18 @@ private static VersionedDocumentContext CreateDocumentContext( documentSnapshotMock .Setup(x => x.GetTextAsync()) .ReturnsAsync(document.Source.Text); + documentSnapshotMock + .SetupGet(x => x.Version) + .Returns(version); - return new VersionedDocumentContext( + return new DocumentContext( uri: new Uri($@"c:\${GetFileName(isRazorFile)}"), snapshot: documentSnapshotMock.Object, - projectContext: null, - version); + projectContext: null); } private async Task CreateServiceAsync( - VersionedDocumentContext documentSnapshot, + DocumentContext documentSnapshot, ProvideSemanticTokensResponse? csharpTokens, bool withCSharpBackground, bool serverSupportsPreciseRanges, @@ -1198,12 +1200,11 @@ private static string GetFileRepresentationOfTokens(SourceText sourceText, int[] return builder.ToString(); } - private class TestDocumentContextFactory(VersionedDocumentContext? documentContext = null) : IDocumentContextFactory + private class TestDocumentContextFactory(DocumentContext? documentContext = null) : IDocumentContextFactory { public bool TryCreate( Uri documentUri, VSProjectContext? projectContext, - bool versioned, [NotNullWhen(true)] out DocumentContext? context) { context = documentContext; diff --git a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/SignatureHelp/SignatureHelpEndpointTest.cs b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/SignatureHelp/SignatureHelpEndpointTest.cs index b794fc1ece3..646b2085413 100644 --- a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/SignatureHelp/SignatureHelpEndpointTest.cs +++ b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/SignatureHelp/SignatureHelpEndpointTest.cs @@ -113,7 +113,7 @@ private async Task VerifySignatureHelpWithContextAndOptionsAsync(string input, R Context = signatureHelpContext }; - Assert.True(DocumentContextFactory.TryCreateForOpenDocument(request.TextDocument, out var documentContext)); + Assert.True(DocumentContextFactory.TryCreate(request.TextDocument, out var documentContext)); var requestContext = CreateRazorRequestContext(documentContext); diff --git a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/SingleServerDelegatingEndpointTestBase.cs b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/SingleServerDelegatingEndpointTestBase.cs index 4b2e2f3e871..49c4fbb7423 100644 --- a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/SingleServerDelegatingEndpointTestBase.cs +++ b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/SingleServerDelegatingEndpointTestBase.cs @@ -56,7 +56,7 @@ private protected async Task CreateLanguageServerAsync( } } - DocumentContextFactory = new TestDocumentContextFactory(razorFilePath, codeDocument, version: 1337); + DocumentContextFactory = new TestDocumentContextFactory(razorFilePath, codeDocument); LanguageServerFeatureOptions = Mock.Of(options => options.SupportsFileManipulation == true && diff --git a/src/Razor/test/Microsoft.AspNetCore.Razor.Test.Common.Tooling/LanguageServer/LanguageServerTestBase.cs b/src/Razor/test/Microsoft.AspNetCore.Razor.Test.Common.Tooling/LanguageServer/LanguageServerTestBase.cs index e7e0f6e87e2..95ab0722b98 100644 --- a/src/Razor/test/Microsoft.AspNetCore.Razor.Test.Common.Tooling/LanguageServer/LanguageServerTestBase.cs +++ b/src/Razor/test/Microsoft.AspNetCore.Razor.Test.Common.Tooling/LanguageServer/LanguageServerTestBase.cs @@ -58,7 +58,7 @@ private protected TestProjectSnapshotManager CreateProjectSnapshotManager( initializer: static updater => updater.ProjectAdded(MiscFilesHostProject.Instance)); private protected static RazorRequestContext CreateRazorRequestContext( - VersionedDocumentContext? documentContext, + DocumentContext? documentContext, ILspServices? lspServices = null) => new(documentContext, lspServices ?? StrictMock.Of(), "lsp/method", uri: null); @@ -108,9 +108,9 @@ private protected static IDocumentContextFactory CreateDocumentContextFactory(Ur return CreateDocumentContextFactory(documentPath, codeDocument); } - private protected static VersionedDocumentContext CreateDocumentContext(Uri documentPath, RazorCodeDocument codeDocument) + private protected static DocumentContext CreateDocumentContext(Uri documentPath, RazorCodeDocument codeDocument) { - return TestDocumentContext.From(documentPath.GetAbsoluteOrUNCPath(), codeDocument, hostDocumentVersion: 1337); + return TestDocumentContext.From(documentPath.GetAbsoluteOrUNCPath(), codeDocument); } private protected static IDocumentContextFactory CreateDocumentContextFactory( @@ -119,15 +119,15 @@ private protected static IDocumentContextFactory CreateDocumentContextFactory( bool documentFound = true) { var documentContextFactory = documentFound - ? new TestDocumentContextFactory(documentPath.GetAbsoluteOrUNCPath(), codeDocument, version: 1337) + ? new TestDocumentContextFactory(documentPath.GetAbsoluteOrUNCPath(), codeDocument) : new TestDocumentContextFactory(); return documentContextFactory; } - private protected static VersionedDocumentContext CreateDocumentContext(Uri uri, IDocumentSnapshot snapshot) + private protected static DocumentContext CreateDocumentContext(Uri uri, IDocumentSnapshot snapshot) { - return new VersionedDocumentContext(uri, snapshot, projectContext: null, version: 0); + return new DocumentContext(uri, snapshot, projectContext: null); } private protected static RazorLSPOptionsMonitor GetOptionsMonitor(bool enableFormatting = true, bool autoShowCompletion = true, bool autoListParams = true, bool formatOnType = true, bool autoInsertAttributeQuotes = true, bool colorBackground = false, bool codeBlockBraceOnNextLine = false, bool commitElementsWithSpace = true) diff --git a/src/Razor/test/Microsoft.AspNetCore.Razor.Test.Common.Tooling/LanguageServer/TestDocumentContext.cs b/src/Razor/test/Microsoft.AspNetCore.Razor.Test.Common.Tooling/LanguageServer/TestDocumentContext.cs index 27d2273b814..e6e60acffe2 100644 --- a/src/Razor/test/Microsoft.AspNetCore.Razor.Test.Common.Tooling/LanguageServer/TestDocumentContext.cs +++ b/src/Razor/test/Microsoft.AspNetCore.Razor.Test.Common.Tooling/LanguageServer/TestDocumentContext.cs @@ -19,13 +19,13 @@ public static DocumentContext Create(Uri uri, string text) return new DocumentContext(uri, snapshot, projectContext: null); } - public static VersionedDocumentContext From(string filePath, RazorCodeDocument codeDocument, int hostDocumentVersion) + public static DocumentContext From(string filePath, RazorCodeDocument codeDocument, int hostDocumentVersion) { var content = codeDocument.Source.Text.ToString(); - var documentSnapshot = TestDocumentSnapshot.Create(filePath, content); + var documentSnapshot = TestDocumentSnapshot.Create(filePath, content, hostDocumentVersion); documentSnapshot.With(codeDocument); var uri = new Uri(filePath); - return new VersionedDocumentContext(uri, documentSnapshot, projectContext: null, hostDocumentVersion); + return new DocumentContext(uri, documentSnapshot, projectContext: null); } public static DocumentContext From(string filePath, RazorCodeDocument codeDocument) @@ -45,7 +45,7 @@ public static DocumentContext From(string filePath) return From(filePath, codeDocument); } - public static VersionedDocumentContext From(string filePath, int hostDocumentVersion) + public static DocumentContext From(string filePath, int hostDocumentVersion) { var properties = RazorSourceDocumentProperties.Create(filePath, filePath); var sourceDocument = RazorSourceDocument.Create(content: string.Empty, properties); diff --git a/src/Razor/test/Microsoft.AspNetCore.Razor.Test.Common.Tooling/LanguageServer/TestDocumentContextFactory.cs b/src/Razor/test/Microsoft.AspNetCore.Razor.Test.Common.Tooling/LanguageServer/TestDocumentContextFactory.cs index 591df7ed021..7a0aa4ba27d 100644 --- a/src/Razor/test/Microsoft.AspNetCore.Razor.Test.Common.Tooling/LanguageServer/TestDocumentContextFactory.cs +++ b/src/Razor/test/Microsoft.AspNetCore.Razor.Test.Common.Tooling/LanguageServer/TestDocumentContextFactory.cs @@ -13,23 +13,20 @@ internal class TestDocumentContextFactory : IDocumentContextFactory { private protected readonly string? FilePath; private protected readonly RazorCodeDocument? CodeDocument; - private readonly int? _version; public TestDocumentContextFactory() { } - public TestDocumentContextFactory(string filePath, RazorCodeDocument codeDocument, int? version = null) + public TestDocumentContextFactory(string filePath, RazorCodeDocument codeDocument) { FilePath = filePath; CodeDocument = codeDocument; - _version = version; } public virtual bool TryCreate( Uri documentUri, VSProjectContext? projectContext, - bool versioned, [NotNullWhen(true)] out DocumentContext? context) { if (FilePath is null || CodeDocument is null) @@ -38,18 +35,6 @@ public virtual bool TryCreate( return false; } - if (versioned) - { - if (_version is null) - { - context = null; - return false; - } - - context = TestDocumentContext.From(FilePath, CodeDocument, _version.Value); - return true; - } - context = TestDocumentContext.From(FilePath, CodeDocument); return true; } diff --git a/src/Razor/test/Microsoft.AspNetCore.Razor.Test.Common.Tooling/ProjectSystem/TestDocumentSnapshot.cs b/src/Razor/test/Microsoft.AspNetCore.Razor.Test.Common.Tooling/ProjectSystem/TestDocumentSnapshot.cs index a419a5bff05..1f86e7fe5ce 100644 --- a/src/Razor/test/Microsoft.AspNetCore.Razor.Test.Common.Tooling/ProjectSystem/TestDocumentSnapshot.cs +++ b/src/Razor/test/Microsoft.AspNetCore.Razor.Test.Common.Tooling/ProjectSystem/TestDocumentSnapshot.cs @@ -23,13 +23,13 @@ public static TestDocumentSnapshot Create(string filePath) public static TestDocumentSnapshot Create(string filePath, VersionStamp version) => Create(filePath, string.Empty, version); - public static TestDocumentSnapshot Create(string filePath, string text) - => Create(filePath, text, VersionStamp.Default); + public static TestDocumentSnapshot Create(string filePath, string text, int version = 0) + => Create(filePath, text, VersionStamp.Default, numericVersion: version); - public static TestDocumentSnapshot Create(string filePath, string text, VersionStamp version, ProjectWorkspaceState? projectWorkspaceState = null) - => Create(filePath, text, version, TestProjectSnapshot.Create(filePath + ".csproj", projectWorkspaceState)); + public static TestDocumentSnapshot Create(string filePath, string text, VersionStamp version, ProjectWorkspaceState? projectWorkspaceState = null, int numericVersion = 0) + => Create(filePath, text, version, TestProjectSnapshot.Create(filePath + ".csproj", projectWorkspaceState), numericVersion); - public static TestDocumentSnapshot Create(string filePath, string text, VersionStamp version, TestProjectSnapshot projectSnapshot) + public static TestDocumentSnapshot Create(string filePath, string text, VersionStamp version, TestProjectSnapshot projectSnapshot, int numericVersion) { var targetPath = Path.GetDirectoryName(projectSnapshot.FilePath) is string projectDirectory && filePath.StartsWith(projectDirectory) ? filePath[projectDirectory.Length..] @@ -41,7 +41,7 @@ public static TestDocumentSnapshot Create(string filePath, string text, VersionS hostDocument, SourceText.From(text), version, - 1, + numericVersion, () => Task.FromResult(TextAndVersion.Create(sourceText, version))); var testDocument = new TestDocumentSnapshot(projectSnapshot, documentState); From 4fe2eff346d1e0a2b76f2b8dd5ffaf41f8785b7d Mon Sep 17 00:00:00 2001 From: David Wengier Date: Mon, 12 Aug 2024 14:01:06 +1000 Subject: [PATCH 07/16] Expand testing slightly --- ...rTest.cs => ProjectSnapshotManagerTest.cs} | 34 +++++++++++++++++-- 1 file changed, 32 insertions(+), 2 deletions(-) rename src/Razor/test/Microsoft.VisualStudio.LanguageServices.Razor.Test/ProjectSystem/{DefaultProjectSnapshotManagerTest.cs => ProjectSnapshotManagerTest.cs} (96%) diff --git a/src/Razor/test/Microsoft.VisualStudio.LanguageServices.Razor.Test/ProjectSystem/DefaultProjectSnapshotManagerTest.cs b/src/Razor/test/Microsoft.VisualStudio.LanguageServices.Razor.Test/ProjectSystem/ProjectSnapshotManagerTest.cs similarity index 96% rename from src/Razor/test/Microsoft.VisualStudio.LanguageServices.Razor.Test/ProjectSystem/DefaultProjectSnapshotManagerTest.cs rename to src/Razor/test/Microsoft.VisualStudio.LanguageServices.Razor.Test/ProjectSystem/ProjectSnapshotManagerTest.cs index 60c229fa704..62b66ef903e 100644 --- a/src/Razor/test/Microsoft.VisualStudio.LanguageServices.Razor.Test/ProjectSystem/DefaultProjectSnapshotManagerTest.cs +++ b/src/Razor/test/Microsoft.VisualStudio.LanguageServices.Razor.Test/ProjectSystem/ProjectSnapshotManagerTest.cs @@ -22,7 +22,7 @@ namespace Microsoft.VisualStudio.Razor.ProjectSystem; -public class DefaultProjectSnapshotManagerTest : VisualStudioWorkspaceTestBase +public class ProjectSnapshotManagerTest : VisualStudioWorkspaceTestBase { private static readonly HostDocument[] s_documents = [ @@ -52,7 +52,7 @@ public class DefaultProjectSnapshotManagerTest : VisualStudioWorkspaceTestBase private readonly TestProjectSnapshotManager _projectManager; private readonly SourceText _sourceText; - public DefaultProjectSnapshotManagerTest(ITestOutputHelper testOutput) + public ProjectSnapshotManagerTest(ITestOutputHelper testOutput) : base(testOutput) { var someTagHelpers = ImmutableArray.Create( @@ -191,6 +191,8 @@ await _projectManager.UpdateAsync(updater => filePath => filePath == s_documents[0].FilePath); listener.AssertNoNotifications(); + + Assert.Equal(1, project.GetDocument(s_documents[0].FilePath)!.Version); } [UIFact] @@ -469,6 +471,8 @@ await _projectManager.UpdateAsync(updater => Assert.Same(_sourceText, text); Assert.True(_projectManager.IsDocumentOpen(s_documents[0].FilePath)); + + Assert.Equal(2, document.Version); } [UIFact] @@ -505,6 +509,7 @@ await _projectManager.UpdateAsync(updater => var text = await document.GetTextAsync(); Assert.Same(expected, text); Assert.False(_projectManager.IsDocumentOpen(s_documents[0].FilePath)); + Assert.Equal(3, document.Version); } [UIFact] @@ -569,6 +574,7 @@ await _projectManager.UpdateAsync(updater => Assert.NotNull(document); var text = await document.GetTextAsync(); Assert.Same(expected, text); + Assert.Equal(3, document.Version); } [UIFact] @@ -602,6 +608,7 @@ await _projectManager.UpdateAsync(updater => Assert.NotNull(document); var text = await document.GetTextAsync(); Assert.Same(expected, text); + Assert.Equal(3, document.Version); } [UIFact] @@ -749,6 +756,29 @@ await _projectManager.UpdateAsync(updater => listener.AssertNoNotifications(); } + [UIFact] + public async Task ProjectWorkspaceStateChanged_UpdateDocuments() + { + // Arrange + await _projectManager.UpdateAsync(updater => + { + updater.ProjectAdded(s_hostProject); + updater.DocumentAdded(s_hostProject.Key, s_documents[0], null!); + }); + + // Act + await _projectManager.UpdateAsync(updater => + { + updater.ProjectWorkspaceStateChanged(s_hostProject.Key, _projectWorkspaceStateWithTagHelpers); + }); + + // Assert + var document = _projectManager.GetLoadedProject(s_hostProject.Key).GetDocument(s_documents[0].FilePath); + + Assert.NotNull(document); + Assert.Equal(2, document.Version); + } + [UIFact] public async Task ProjectWorkspaceStateChanged_WithHostProject_FirstTime_NotifiesListeners() { From 061347e1adc856f3dc6a6ee357d8546b57154309 Mon Sep 17 00:00:00 2001 From: David Wengier Date: Mon, 12 Aug 2024 14:01:12 +1000 Subject: [PATCH 08/16] Minor logging cleanup --- .../Diagnostics/RazorDiagnosticsPublisher.cs | 6 +---- .../GeneratedDocumentPublisher.cs | 24 +++++-------------- 2 files changed, 7 insertions(+), 23 deletions(-) diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Diagnostics/RazorDiagnosticsPublisher.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Diagnostics/RazorDiagnosticsPublisher.cs index e3f0eb8d901..1f3320294e5 100644 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Diagnostics/RazorDiagnosticsPublisher.cs +++ b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Diagnostics/RazorDiagnosticsPublisher.cs @@ -155,11 +155,7 @@ .. csharpDiagnostics ?? [] PublishDiagnosticsForFilePath(document.FilePath, combinedDiagnostics); - if (_logger.IsEnabled(LogLevel.Trace)) - { - var diagnosticString = string.Join(", ", razorDiagnostics.Select(diagnostic => diagnostic.Id)); - _logger.LogTrace($"Publishing diagnostics for document '{document.FilePath}': {diagnosticString}"); - } + _logger.LogTrace($"Publishing diagnostics for document '{document.FilePath}': {string.Join(", ", razorDiagnostics.Select(diagnostic => diagnostic.Id))}"); async Task GetCSharpDiagnosticsAsync(IDocumentSnapshot document, CancellationToken token) { diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/GeneratedDocumentPublisher.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/GeneratedDocumentPublisher.cs index 4799f85575e..578706da84f 100644 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/GeneratedDocumentPublisher.cs +++ b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/GeneratedDocumentPublisher.cs @@ -79,16 +79,10 @@ public void PublishCSharp(ProjectKey projectKey, string filePath, SourceText sou return; } - if (_logger.IsEnabled(LogLevel.Trace)) - { - var previousDocumentLength = previouslyPublishedData.SourceText.Length; - var currentDocumentLength = sourceText.Length; - var documentLengthDelta = sourceText.Length - previousDocumentLength; - _logger.LogTrace( - $"Updating C# buffer of {filePath} for project {documentKey.ProjectKey} to correspond with host document " + - $"version {hostDocumentVersion}. {previousDocumentLength} -> {currentDocumentLength} = Change delta of " + - $"{documentLengthDelta} via {textChanges.Count} text changes."); - } + _logger.LogTrace( + $"Updating C# buffer of {filePath} for project {documentKey.ProjectKey} to correspond with host document " + + $"version {hostDocumentVersion}. {previouslyPublishedData.SourceText.Length} -> {sourceText.Length} = Change delta of " + + $"{sourceText.Length - previouslyPublishedData.SourceText.Length} via {textChanges.Count} text changes."); _publishedCSharpData[documentKey] = new PublishData(sourceText, hostDocumentVersion); } @@ -124,14 +118,8 @@ public void PublishHtml(ProjectKey projectKey, string filePath, SourceText sourc return; } - if (_logger.IsEnabled(LogLevel.Trace)) - { - var previousDocumentLength = previouslyPublishedData.SourceText.Length; - var currentDocumentLength = sourceText.Length; - var documentLengthDelta = sourceText.Length - previousDocumentLength; - _logger.LogTrace( - $"Updating HTML buffer of {filePath} to correspond with host document version {hostDocumentVersion}. {previousDocumentLength} -> {currentDocumentLength} = Change delta of {documentLengthDelta} via {textChanges.Count} text changes."); - } + _logger.LogTrace( + $"Updating HTML buffer of {filePath} to correspond with host document version {hostDocumentVersion}. {previouslyPublishedData.SourceText.Length} -> {sourceText.Length} = Change delta of {sourceText.Length - previouslyPublishedData.SourceText.Length} via {textChanges.Count} text changes."); _publishedHtmlData[filePath] = new PublishData(sourceText, hostDocumentVersion); } From 6a166dedddbfa49ae81dd5e400ef9c96a2cfea7f Mon Sep 17 00:00:00 2001 From: David Wengier Date: Tue, 13 Aug 2024 09:53:12 +1000 Subject: [PATCH 09/16] Remove unused using --- .../Endpoints/RazorCustomMessageTarget_SemanticTokens.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/Endpoints/RazorCustomMessageTarget_SemanticTokens.cs b/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/Endpoints/RazorCustomMessageTarget_SemanticTokens.cs index 654bb036108..1133cdb6164 100644 --- a/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/Endpoints/RazorCustomMessageTarget_SemanticTokens.cs +++ b/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/Endpoints/RazorCustomMessageTarget_SemanticTokens.cs @@ -1,7 +1,6 @@ // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT license. See License.txt in the project root for license information. -using System; using System.Diagnostics; using System.Linq; using System.Threading; From 374e85cb336aa71ad897507ade183d2d6c96e0cd Mon Sep 17 00:00:00 2001 From: David Wengier Date: Fri, 16 Aug 2024 11:56:48 +1000 Subject: [PATCH 10/16] Don't allow virtual documents to go back in time --- .../GeneratedDocumentPublisher.cs | 20 +++++++++++++++++-- .../Endpoints/RazorCustomMessageTarget.cs | 4 ++-- ...zorCustomMessageTarget_UpdateHtmlBuffer.cs | 4 ++++ 3 files changed, 24 insertions(+), 4 deletions(-) diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/GeneratedDocumentPublisher.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/GeneratedDocumentPublisher.cs index 578706da84f..81a34f72030 100644 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/GeneratedDocumentPublisher.cs +++ b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/GeneratedDocumentPublisher.cs @@ -72,6 +72,14 @@ public void PublishCSharp(ProjectKey projectKey, string filePath, SourceText sou previouslyPublishedData = PublishData.Default; } + if (previouslyPublishedData.HostDocumentVersion > hostDocumentVersion) + { + // We've already published a newer version of this document. No-op. + Debug.Fail("C# document being published that is older than one we've previously published!"); + _logger.LogWarning($"Skipping publish of C# for {filePath} because we've already published version {previouslyPublishedData.HostDocumentVersion}, and this request is for {hostDocumentVersion}."); + return; + } + textChanges = SourceTextDiffer.GetMinimalTextChanges(previouslyPublishedData.SourceText, sourceText); if (textChanges.Count == 0 && hostDocumentVersion == previouslyPublishedData.HostDocumentVersion) { @@ -79,7 +87,7 @@ public void PublishCSharp(ProjectKey projectKey, string filePath, SourceText sou return; } - _logger.LogTrace( + _logger.LogDebug( $"Updating C# buffer of {filePath} for project {documentKey.ProjectKey} to correspond with host document " + $"version {hostDocumentVersion}. {previouslyPublishedData.SourceText.Length} -> {sourceText.Length} = Change delta of " + $"{sourceText.Length - previouslyPublishedData.SourceText.Length} via {textChanges.Count} text changes."); @@ -111,6 +119,14 @@ public void PublishHtml(ProjectKey projectKey, string filePath, SourceText sourc previouslyPublishedData = PublishData.Default; } + if (previouslyPublishedData.HostDocumentVersion > hostDocumentVersion) + { + // We've already published a newer version of this document. No-op. + Debug.Fail("Html document being published that is older than one we've previously published!"); + _logger.LogWarning($"Skipping publish of Html for {filePath} because we've already published version {previouslyPublishedData.HostDocumentVersion}, and this request is for {hostDocumentVersion}."); + return; + } + textChanges = SourceTextDiffer.GetMinimalTextChanges(previouslyPublishedData.SourceText, sourceText); if (textChanges.Count == 0 && hostDocumentVersion == previouslyPublishedData.HostDocumentVersion) { @@ -118,7 +134,7 @@ public void PublishHtml(ProjectKey projectKey, string filePath, SourceText sourc return; } - _logger.LogTrace( + _logger.LogDebug( $"Updating HTML buffer of {filePath} to correspond with host document version {hostDocumentVersion}. {previouslyPublishedData.SourceText.Length} -> {sourceText.Length} = Change delta of {sourceText.Length - previouslyPublishedData.SourceText.Length} via {textChanges.Count} text changes."); _publishedHtmlData[filePath] = new PublishData(sourceText, hostDocumentVersion); diff --git a/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/Endpoints/RazorCustomMessageTarget.cs b/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/Endpoints/RazorCustomMessageTarget.cs index 1ae779026f7..854c9fe04a6 100644 --- a/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/Endpoints/RazorCustomMessageTarget.cs +++ b/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/Endpoints/RazorCustomMessageTarget.cs @@ -146,6 +146,8 @@ private async Task> TrySynchronizeV return await TempForCohost_TrySynchronizeVirtualDocumentAsync(hostDocument, cancellationToken); } + _logger.LogDebug($"Trying to synchronize for {caller} to version {requiredHostDocumentVersion} of {hostDocument.Uri} for {hostDocument.GetProjectContext()?.Id ?? "(no project context)"}"); + // For Html documents we don't do anything fancy, just call the standard service // If we're not generating unique document file names, then we can treat C# documents the same way if (!_languageServerFeatureOptions.IncludeProjectKeyInGeneratedFilePath || @@ -154,8 +156,6 @@ private async Task> TrySynchronizeV return await _documentSynchronizer.TrySynchronizeVirtualDocumentAsync(requiredHostDocumentVersion, hostDocument.Uri, cancellationToken).ConfigureAwait(false); } - _logger.LogDebug($"Trying to synchronize for {caller} to version {requiredHostDocumentVersion} of {hostDocument.Uri} for {hostDocument.GetProjectContext()?.Id ?? "(no project context)"}"); - var virtualDocument = FindVirtualDocument(hostDocument.Uri, hostDocument.GetProjectContext()); if (virtualDocument is { ProjectKey.IsUnknown: true }) diff --git a/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/Endpoints/RazorCustomMessageTarget_UpdateHtmlBuffer.cs b/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/Endpoints/RazorCustomMessageTarget_UpdateHtmlBuffer.cs index 0bf10cdcdb6..b2c366890ff 100644 --- a/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/Endpoints/RazorCustomMessageTarget_UpdateHtmlBuffer.cs +++ b/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/Endpoints/RazorCustomMessageTarget_UpdateHtmlBuffer.cs @@ -5,6 +5,7 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; +using Microsoft.CodeAnalysis.Razor.Logging; using Microsoft.CodeAnalysis.Razor.Protocol; using StreamJsonRpc; @@ -35,6 +36,9 @@ internal void UpdateHtmlBuffer(UpdateBufferRequest request) } var hostDocumentUri = new Uri(request.HostDocumentFilePath); + + _logger.LogDebug($"UpdateHtmlBuffer for {request.HostDocumentVersion} of {hostDocumentUri} in {request.ProjectKeyId}"); + _documentManager.UpdateVirtualDocument( hostDocumentUri, request.Changes.Select(change => change.ToVisualStudioTextChange()).ToArray(), From af13ebdf10eda2a9d7f7b4c0a5522da4bd1bf418 Mon Sep 17 00:00:00 2001 From: David Wengier Date: Mon, 19 Aug 2024 15:19:18 +1000 Subject: [PATCH 11/16] PR feedback - sorta --- .../GeneratedDocumentSynchronizer.cs | 12 ++++- .../GeneratedDocumentSynchronizerTest.cs | 52 +++++++++++++++++-- .../TestLanguageServerFeatureOptions.cs | 5 +- 3 files changed, 62 insertions(+), 7 deletions(-) diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/GeneratedDocumentSynchronizer.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/GeneratedDocumentSynchronizer.cs index b3a01451ce5..d057edfc632 100644 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/GeneratedDocumentSynchronizer.cs +++ b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/GeneratedDocumentSynchronizer.cs @@ -9,17 +9,25 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer; internal class GeneratedDocumentSynchronizer( IGeneratedDocumentPublisher publisher, - LanguageServerFeatureOptions languageServerFeatureOptions) : IDocumentProcessedListener + LanguageServerFeatureOptions languageServerFeatureOptions, + IProjectSnapshotManager projectManager) : IDocumentProcessedListener { private readonly IGeneratedDocumentPublisher _publisher = publisher; private readonly LanguageServerFeatureOptions _languageServerFeatureOptions = languageServerFeatureOptions; + private readonly IProjectSnapshotManager _projectManager = projectManager; public void DocumentProcessed(RazorCodeDocument codeDocument, IDocumentSnapshot document) { var hostDocumentVersion = document.Version; - var filePath = document.FilePath.AssumeNotNull(); + // If the document isn't open, and we're not updating buffers for closed documents, then we don't need to do anything. + if (!_projectManager.IsDocumentOpen(document.FilePath) && + !_languageServerFeatureOptions.UpdateBuffersForClosedDocuments) + { + return; + } + // If cohosting is on, then it is responsible for updating the Html buffer if (!_languageServerFeatureOptions.UseRazorCohostServer) { diff --git a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/GeneratedDocumentSynchronizerTest.cs b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/GeneratedDocumentSynchronizerTest.cs index 7805abd04b1..bba790b36ae 100644 --- a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/GeneratedDocumentSynchronizerTest.cs +++ b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/GeneratedDocumentSynchronizerTest.cs @@ -1,6 +1,7 @@ // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT license. See License.txt in the project root for license information. +using System.Threading.Tasks; using Microsoft.AspNetCore.Razor.Language; using Microsoft.AspNetCore.Razor.ProjectSystem; using Microsoft.AspNetCore.Razor.Test.Common.LanguageServer; @@ -15,8 +16,12 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer; public class GeneratedDocumentSynchronizerTest : LanguageServerTestBase { + private static readonly HostProject s_hostProject = new("/path/to/project.csproj", "/path/to/obj", RazorConfiguration.Default, "TestRootNamespace"); + private static readonly HostDocument s_hostDocument = new("/path/to/file.razor", "file.razor"); + private readonly GeneratedDocumentSynchronizer _synchronizer; private readonly TestGeneratedDocumentPublisher _publisher; + private readonly TestProjectSnapshotManager _projectManager; private readonly IDocumentSnapshot _document; private readonly RazorCodeDocument _codeDocument; @@ -24,14 +29,30 @@ public GeneratedDocumentSynchronizerTest(ITestOutputHelper testOutput) : base(testOutput) { _publisher = new TestGeneratedDocumentPublisher(); - _synchronizer = new GeneratedDocumentSynchronizer(_publisher, TestLanguageServerFeatureOptions.Instance); - _document = TestDocumentSnapshot.Create("C:/path/to/file.razor"); + _projectManager = CreateProjectSnapshotManager(); + _synchronizer = new GeneratedDocumentSynchronizer(_publisher, TestLanguageServerFeatureOptions.Instance, _projectManager); + _document = TestDocumentSnapshot.Create(s_hostDocument.FilePath); _codeDocument = CreateCodeDocument("

Hello World

"); } + protected override async Task InitializeAsync() + { + await _projectManager.UpdateAsync(updater => + { + updater.ProjectAdded(s_hostProject); + updater.DocumentAdded(s_hostProject.Key, s_hostDocument, new EmptyTextLoader(s_hostDocument.FilePath)); + }); + } + [Fact] - public void DocumentProcessed_KnownVersion_Publishes() + public async Task DocumentProcessed_OpenDocument_Publishes() { + // Arrange + await _projectManager.UpdateAsync(updater => + { + updater.DocumentOpened(s_hostProject.Key, s_hostDocument.FilePath, SourceText.From("

Hello World

")); + }); + // Act _synchronizer.DocumentProcessed(_codeDocument, _document); @@ -40,6 +61,31 @@ public void DocumentProcessed_KnownVersion_Publishes() Assert.True(_publisher.PublishedHtml); } + [Fact] + public void DocumentProcessed_CloseDocument_WithOption_Publishes() + { + var options = new TestLanguageServerFeatureOptions(updateBuffersForClosedDocuments: true); + var synchronizer = new GeneratedDocumentSynchronizer(_publisher, options, _projectManager); + + // Act + synchronizer.DocumentProcessed(_codeDocument, _document); + + // Assert + Assert.True(_publisher.PublishedCSharp); + Assert.True(_publisher.PublishedHtml); + } + + [Fact] + public void DocumentProcessed_CloseDocument_DoesntPublish() + { + // Act + _synchronizer.DocumentProcessed(_codeDocument, _document); + + // Assert + Assert.False(_publisher.PublishedCSharp); + Assert.False(_publisher.PublishedHtml); + } + private class TestGeneratedDocumentPublisher : IGeneratedDocumentPublisher { public bool PublishedCSharp { get; private set; } diff --git a/src/Razor/test/Microsoft.AspNetCore.Razor.Test.Common.Tooling/Workspaces/TestLanguageServerFeatureOptions.cs b/src/Razor/test/Microsoft.AspNetCore.Razor.Test.Common.Tooling/Workspaces/TestLanguageServerFeatureOptions.cs index 8d8c9786f81..6e4babb9bc2 100644 --- a/src/Razor/test/Microsoft.AspNetCore.Razor.Test.Common.Tooling/Workspaces/TestLanguageServerFeatureOptions.cs +++ b/src/Razor/test/Microsoft.AspNetCore.Razor.Test.Common.Tooling/Workspaces/TestLanguageServerFeatureOptions.cs @@ -7,7 +7,8 @@ namespace Microsoft.AspNetCore.Razor.Test.Common.Workspaces; internal class TestLanguageServerFeatureOptions( bool includeProjectKeyInGeneratedFilePath = false, - bool forceRuntimeCodeGeneration = false) : LanguageServerFeatureOptions + bool forceRuntimeCodeGeneration = false, + bool updateBuffersForClosedDocuments = false) : LanguageServerFeatureOptions { public static readonly LanguageServerFeatureOptions Instance = new TestLanguageServerFeatureOptions(); @@ -27,7 +28,7 @@ internal class TestLanguageServerFeatureOptions( public override bool UsePreciseSemanticTokenRanges => true; - public override bool UpdateBuffersForClosedDocuments => false; + public override bool UpdateBuffersForClosedDocuments => updateBuffersForClosedDocuments; public override bool IncludeProjectKeyInGeneratedFilePath => includeProjectKeyInGeneratedFilePath; From 80ae134f9f2d0a7218624f85935df17a3f7a213b Mon Sep 17 00:00:00 2001 From: David Wengier Date: Tue, 20 Aug 2024 10:24:35 +1000 Subject: [PATCH 12/16] PR Feedback --- .../ProjectSystem/DocumentState.cs | 38 +++++++++---------- .../ProjectSystem/ProjectState.cs | 6 +-- ...RazorCustomMessageTarget_SemanticTokens.cs | 2 +- ...rCustomMessageTarget_UpdateCSharpBuffer.cs | 21 +++++----- .../ProjectSystem/TestDocumentSnapshot.cs | 18 ++++----- .../ProjectSystem/ProjectStateTest.cs | 10 ++--- 6 files changed, 47 insertions(+), 48 deletions(-) diff --git a/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/ProjectSystem/DocumentState.cs b/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/ProjectSystem/DocumentState.cs index 64385538afa..fded1912608 100644 --- a/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/ProjectSystem/DocumentState.cs +++ b/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/ProjectSystem/DocumentState.cs @@ -27,12 +27,12 @@ internal partial class DocumentState private readonly Func> _loader; private Task? _loaderTask; private SourceText? _sourceText; - private VersionStamp? _version; - private readonly int _numericVersion; + private VersionStamp? _textVersion; + private readonly int _version; public static DocumentState Create( HostDocument hostDocument, - int numericVersion, + int version, Func>? loader) { if (hostDocument is null) @@ -40,7 +40,7 @@ public static DocumentState Create( throw new ArgumentNullException(nameof(hostDocument)); } - return new DocumentState(hostDocument, null, null, numericVersion, loader); + return new DocumentState(hostDocument, null, null, version, loader); } public static DocumentState Create( @@ -52,27 +52,27 @@ public static DocumentState Create( throw new ArgumentNullException(nameof(hostDocument)); } - return new DocumentState(hostDocument, null, null, 1, loader); + return new DocumentState(hostDocument, null, null, version: 1, loader); } // Internal for testing internal DocumentState( HostDocument hostDocument, SourceText? text, - VersionStamp? version, - int numericVersion, + VersionStamp? textVersion, + int version, Func>? loader) { HostDocument = hostDocument; _sourceText = text; + _textVersion = textVersion; _version = version; - _numericVersion = numericVersion; _loader = loader ?? EmptyLoader; _lock = new object(); } public HostDocument HostDocument { get; } - public int Version => _numericVersion; + public int Version => _version; public bool IsGeneratedOutputResultAvailable => ComputedState.IsResultAvailable == true; @@ -149,7 +149,7 @@ public bool TryGetText([NotNullWhen(true)] out SourceText? result) public bool TryGetTextVersion(out VersionStamp result) { - if (_version is { } version) + if (_textVersion is { } version) { result = version; return true; @@ -169,11 +169,11 @@ public bool TryGetTextVersion(out VersionStamp result) public virtual DocumentState WithConfigurationChange() { - var state = new DocumentState(HostDocument, _sourceText, _version, _numericVersion + 1, _loader) + var state = new DocumentState(HostDocument, _sourceText, _textVersion, _version + 1, _loader) { // The source could not have possibly changed. _sourceText = _sourceText, - _version = _version, + _textVersion = _textVersion, _loaderTask = _loaderTask, }; @@ -184,11 +184,11 @@ public virtual DocumentState WithConfigurationChange() public virtual DocumentState WithImportsChange() { - var state = new DocumentState(HostDocument, _sourceText, _version, _numericVersion + 1, _loader) + var state = new DocumentState(HostDocument, _sourceText, _textVersion, _version + 1, _loader) { // The source could not have possibly changed. _sourceText = _sourceText, - _version = _version, + _textVersion = _textVersion, _loaderTask = _loaderTask }; @@ -200,11 +200,11 @@ public virtual DocumentState WithImportsChange() public virtual DocumentState WithProjectWorkspaceStateChange() { - var state = new DocumentState(HostDocument, _sourceText, _version, _numericVersion + 1, _loader) + var state = new DocumentState(HostDocument, _sourceText, _textVersion, _version + 1, _loader) { // The source could not have possibly changed. _sourceText = _sourceText, - _version = _version, + _textVersion = _textVersion, _loaderTask = _loaderTask }; @@ -214,7 +214,7 @@ public virtual DocumentState WithProjectWorkspaceStateChange() return state; } - public virtual DocumentState WithText(SourceText sourceText, VersionStamp version) + public virtual DocumentState WithText(SourceText sourceText, VersionStamp textVersion) { if (sourceText is null) { @@ -223,7 +223,7 @@ public virtual DocumentState WithText(SourceText sourceText, VersionStamp versio // Do not cache the computed state - return new DocumentState(HostDocument, sourceText, version, _numericVersion + 1, null); + return new DocumentState(HostDocument, sourceText, textVersion, _version + 1, null); } public virtual DocumentState WithTextLoader(Func> loader) @@ -235,7 +235,7 @@ public virtual DocumentState WithTextLoader(Func> loader) // Do not cache the computed state - return new DocumentState(HostDocument, null, null, _numericVersion + 1, loader); + return new DocumentState(HostDocument, null, null, _version + 1, loader); } // Internal, because we are temporarily sharing code with CohostDocumentSnapshot diff --git a/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/ProjectSystem/ProjectState.cs b/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/ProjectSystem/ProjectState.cs index b51e3bbd285..dde23d8e562 100644 --- a/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/ProjectSystem/ProjectState.cs +++ b/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/ProjectSystem/ProjectState.cs @@ -243,7 +243,7 @@ public ProjectState WithAddedHostDocument(HostDocument hostDocument, Func r.End.Line)} max line number, host version {semanticTokensParams.RequiredHostDocumentVersion}, correlation ID {semanticTokensParams.CorrelationId}"); + _logger.LogDebug($"Semantic tokens request for {semanticTokensParams.Ranges.Max(static r => r.End.Line)} max line number, host version {semanticTokensParams.RequiredHostDocumentVersion}, correlation ID {semanticTokensParams.CorrelationId}"); var (synchronized, csharpDoc) = await TrySynchronizeVirtualDocumentAsync( semanticTokensParams.RequiredHostDocumentVersion, diff --git a/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/Endpoints/RazorCustomMessageTarget_UpdateCSharpBuffer.cs b/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/Endpoints/RazorCustomMessageTarget_UpdateCSharpBuffer.cs index e2b6355c927..47b797d2ef0 100644 --- a/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/Endpoints/RazorCustomMessageTarget_UpdateCSharpBuffer.cs +++ b/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/Endpoints/RazorCustomMessageTarget_UpdateCSharpBuffer.cs @@ -87,15 +87,7 @@ request.ProjectKeyId is not null && request.HostDocumentVersion.Value, state: request.PreviousWasEmpty); - if (_documentManager.TryGetDocument(hostDocumentUri, out var newDocSnapshot)) - { - var newDoc = newDocSnapshot.VirtualDocuments.Where(e => e.Uri == virtualDocument.Uri).FirstOrDefault(); - - if (newDoc is not null) - { - _logger.LogDebug($"UpdateCSharpBuffer finished updating doc for {request.HostDocumentVersion} of {virtualDocument.Uri}. New lines: {newDoc.Snapshot.LineCount}"); - } - } + _logger.LogDebug($"UpdateCSharpBuffer finished updating doc for {request.HostDocumentVersion} of {virtualDocument.Uri}. New lines: {GetLineCountOfVirtualDocument(hostDocumentUri, virtualDocument)}"); return; } @@ -127,4 +119,15 @@ request.ProjectKeyId is not null && request.HostDocumentVersion.Value, state: request.PreviousWasEmpty); } + + private int GetLineCountOfVirtualDocument(Uri hostDocumentUri, CSharpVirtualDocumentSnapshot virtualDocument) + { + if (_documentManager.TryGetDocument(hostDocumentUri, out var newDocSnapshot) && + newDocSnapshot.VirtualDocuments.FirstOrDefault(e => e.Uri == virtualDocument.Uri) is { } newDoc) + { + return newDoc.Snapshot.LineCount; + } + + return -1; + } } diff --git a/src/Razor/test/Microsoft.AspNetCore.Razor.Test.Common.Tooling/ProjectSystem/TestDocumentSnapshot.cs b/src/Razor/test/Microsoft.AspNetCore.Razor.Test.Common.Tooling/ProjectSystem/TestDocumentSnapshot.cs index 1f86e7fe5ce..65c0670b26c 100644 --- a/src/Razor/test/Microsoft.AspNetCore.Razor.Test.Common.Tooling/ProjectSystem/TestDocumentSnapshot.cs +++ b/src/Razor/test/Microsoft.AspNetCore.Razor.Test.Common.Tooling/ProjectSystem/TestDocumentSnapshot.cs @@ -20,16 +20,16 @@ internal class TestDocumentSnapshot : DocumentSnapshot public static TestDocumentSnapshot Create(string filePath) => Create(filePath, string.Empty); - public static TestDocumentSnapshot Create(string filePath, VersionStamp version) - => Create(filePath, string.Empty, version); + public static TestDocumentSnapshot Create(string filePath, VersionStamp textVersion) + => Create(filePath, string.Empty, textVersion); public static TestDocumentSnapshot Create(string filePath, string text, int version = 0) - => Create(filePath, text, VersionStamp.Default, numericVersion: version); + => Create(filePath, text, VersionStamp.Default, version: version); - public static TestDocumentSnapshot Create(string filePath, string text, VersionStamp version, ProjectWorkspaceState? projectWorkspaceState = null, int numericVersion = 0) - => Create(filePath, text, version, TestProjectSnapshot.Create(filePath + ".csproj", projectWorkspaceState), numericVersion); + public static TestDocumentSnapshot Create(string filePath, string text, VersionStamp textVersion, ProjectWorkspaceState? projectWorkspaceState = null, int version = 0) + => Create(filePath, text, textVersion, TestProjectSnapshot.Create(filePath + ".csproj", projectWorkspaceState), version); - public static TestDocumentSnapshot Create(string filePath, string text, VersionStamp version, TestProjectSnapshot projectSnapshot, int numericVersion) + public static TestDocumentSnapshot Create(string filePath, string text, VersionStamp textVersion, TestProjectSnapshot projectSnapshot, int version) { var targetPath = Path.GetDirectoryName(projectSnapshot.FilePath) is string projectDirectory && filePath.StartsWith(projectDirectory) ? filePath[projectDirectory.Length..] @@ -40,9 +40,9 @@ public static TestDocumentSnapshot Create(string filePath, string text, VersionS var documentState = new DocumentState( hostDocument, SourceText.From(text), + textVersion, version, - numericVersion, - () => Task.FromResult(TextAndVersion.Create(sourceText, version))); + () => Task.FromResult(TextAndVersion.Create(sourceText, textVersion))); var testDocument = new TestDocumentSnapshot(projectSnapshot, documentState); return testDocument; @@ -65,7 +65,7 @@ internal static TestDocumentSnapshot Create(ProjectSnapshot projectSnapshot, str hostDocument, SourceText.From(text), version, - 1, + version: 1, () => Task.FromResult(TextAndVersion.Create(sourceText, version.Value))); var testDocument = new TestDocumentSnapshot(projectSnapshot, documentState); diff --git a/src/Razor/test/Microsoft.CodeAnalysis.Razor.Workspaces.Test/ProjectSystem/ProjectStateTest.cs b/src/Razor/test/Microsoft.CodeAnalysis.Razor.Workspaces.Test/ProjectSystem/ProjectStateTest.cs index 3cc38fe40d3..5f5c1a8e422 100644 --- a/src/Razor/test/Microsoft.CodeAnalysis.Razor.Workspaces.Test/ProjectSystem/ProjectStateTest.cs +++ b/src/Razor/test/Microsoft.CodeAnalysis.Razor.Workspaces.Test/ProjectSystem/ProjectStateTest.cs @@ -1000,8 +1000,6 @@ public static TestDocumentState Create( { return new TestDocumentState( hostDocument, - null, - null, loader, onTextChange, onTextLoaderChange, @@ -1018,15 +1016,13 @@ public static TestDocumentState Create( private TestDocumentState( HostDocument hostDocument, - SourceText? text, - VersionStamp? version, Func>? loader, Action? onTextChange, Action? onTextLoaderChange, Action? onConfigurationChange, Action? onImportsChange, Action? onProjectWorkspaceStateChange) - : base(hostDocument, text, version, 1, loader) + : base(hostDocument, text: null, textVersion: null, version: 1, loader) { _onTextChange = onTextChange; _onTextLoaderChange = onTextLoaderChange; @@ -1035,10 +1031,10 @@ private TestDocumentState( _onProjectWorkspaceStateChange = onProjectWorkspaceStateChange; } - public override DocumentState WithText(SourceText sourceText, VersionStamp version) + public override DocumentState WithText(SourceText sourceText, VersionStamp textVersion) { _onTextChange?.Invoke(); - return base.WithText(sourceText, version); + return base.WithText(sourceText, textVersion); } public override DocumentState WithTextLoader(Func> loader) From caac5992ab36af9d7ee210f3398bbbcff5c966c6 Mon Sep 17 00:00:00 2001 From: David Wengier Date: Tue, 20 Aug 2024 11:14:24 +1000 Subject: [PATCH 13/16] Fix after merge --- .../Refactoring/RenameEndpointTest.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/Refactoring/RenameEndpointTest.cs b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/Refactoring/RenameEndpointTest.cs index b03b5fd25aa..53ebd97eec8 100644 --- a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/Refactoring/RenameEndpointTest.cs +++ b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/Refactoring/RenameEndpointTest.cs @@ -278,7 +278,7 @@ public async Task Handle_Rename_OnComponentEndTag_ReturnsResult() NewName = "Test2" }; - Assert.True(documentContextFactory.TryCreateForOpenDocument(uri, out var documentContext)); + Assert.True(documentContextFactory.TryCreate(uri, out var documentContext)); var requestContext = CreateRazorRequestContext(documentContext); // Act From 3b2ba30db196cd18d18fe7130a8dc66a3e00ac2d Mon Sep 17 00:00:00 2001 From: David Wengier Date: Thu, 22 Aug 2024 22:18:39 +1000 Subject: [PATCH 14/16] We can't tell the client which version we're applying edits for, because only we understand our version numbers --- .../CSharp/DefaultCSharpCodeActionResolver.cs | 5 +---- .../UnformattedRemappingCSharpCodeActionResolver.cs | 1 - .../AbstractTextDocumentPresentationEndpointBase.cs | 1 - .../DocumentMapping/AbstractEditMappingService.cs | 1 - .../LanguageClient/Endpoints/RazorCustomMessageTarget.cs | 4 +++- .../Endpoints/RazorCustomMessageTarget_CodeActions.cs | 9 ++------- .../Html/DefaultHtmlCodeActionProviderTest.cs | 2 -- .../Html/DefaultHtmlCodeActionResolverTest.cs | 2 -- 8 files changed, 6 insertions(+), 19 deletions(-) diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/CodeActions/CSharp/DefaultCSharpCodeActionResolver.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/CodeActions/CSharp/DefaultCSharpCodeActionResolver.cs index 13c1f533431..d6d329ee899 100644 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/CodeActions/CSharp/DefaultCSharpCodeActionResolver.cs +++ b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/CodeActions/CSharp/DefaultCSharpCodeActionResolver.cs @@ -89,12 +89,9 @@ public async override Task ResolveAsync( cancellationToken.ThrowIfCancellationRequested(); - var documentVersion = documentContext.Snapshot.Version; - var codeDocumentIdentifier = new OptionalVersionedTextDocumentIdentifier() { - Uri = csharpParams.RazorFileIdentifier.Uri, - Version = documentVersion, + Uri = csharpParams.RazorFileIdentifier.Uri }; resolvedCodeAction.Edit = new WorkspaceEdit() { diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/CodeActions/CSharp/UnformattedRemappingCSharpCodeActionResolver.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/CodeActions/CSharp/UnformattedRemappingCSharpCodeActionResolver.cs index 7e0e29d5499..170b4cd3417 100644 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/CodeActions/CSharp/UnformattedRemappingCSharpCodeActionResolver.cs +++ b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/CodeActions/CSharp/UnformattedRemappingCSharpCodeActionResolver.cs @@ -87,7 +87,6 @@ public async override Task ResolveAsync( var codeDocumentIdentifier = new OptionalVersionedTextDocumentIdentifier() { Uri = csharpParams.RazorFileIdentifier.Uri, - Version = documentContext.Snapshot.Version, }; resolvedCodeAction.Edit = new WorkspaceEdit() { diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/DocumentPresentation/AbstractTextDocumentPresentationEndpointBase.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/DocumentPresentation/AbstractTextDocumentPresentationEndpointBase.cs index 330dd3201d3..08e735ca3bd 100644 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/DocumentPresentation/AbstractTextDocumentPresentationEndpointBase.cs +++ b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/DocumentPresentation/AbstractTextDocumentPresentationEndpointBase.cs @@ -176,7 +176,6 @@ private TextDocumentEdit[] MapDocumentChanges(TextDocumentEdit[] documentEdits, TextDocument = new OptionalVersionedTextDocumentIdentifier() { Uri = razorDocumentUri, - Version = hostDocumentVersion }, Edits = [.. remappedEdits] }); diff --git a/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/DocumentMapping/AbstractEditMappingService.cs b/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/DocumentMapping/AbstractEditMappingService.cs index a06a6ec3d52..7296deae4ec 100644 --- a/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/DocumentMapping/AbstractEditMappingService.cs +++ b/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/DocumentMapping/AbstractEditMappingService.cs @@ -144,7 +144,6 @@ private async Task RemapTextDocumentEditsAsync(IDocumentSnap TextDocument = new OptionalVersionedTextDocumentIdentifier() { Uri = razorDocumentUri, - Version = documentContext.Snapshot.Version }, Edits = remappedEdits }); diff --git a/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/Endpoints/RazorCustomMessageTarget.cs b/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/Endpoints/RazorCustomMessageTarget.cs index 854c9fe04a6..406fbc3df4e 100644 --- a/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/Endpoints/RazorCustomMessageTarget.cs +++ b/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/Endpoints/RazorCustomMessageTarget.cs @@ -153,7 +153,9 @@ private async Task> TrySynchronizeV if (!_languageServerFeatureOptions.IncludeProjectKeyInGeneratedFilePath || typeof(TVirtualDocumentSnapshot) == typeof(HtmlVirtualDocumentSnapshot)) { - return await _documentSynchronizer.TrySynchronizeVirtualDocumentAsync(requiredHostDocumentVersion, hostDocument.Uri, cancellationToken).ConfigureAwait(false); + var htmlResult = await _documentSynchronizer.TrySynchronizeVirtualDocumentAsync(requiredHostDocumentVersion, hostDocument.Uri, cancellationToken).ConfigureAwait(false); + _logger.LogDebug($"{(htmlResult.Synchronized ? "Did" : "Did NOT")} synchronize for {caller}: Version {requiredHostDocumentVersion} for {htmlResult.VirtualSnapshot?.Uri}"); + return htmlResult; } var virtualDocument = FindVirtualDocument(hostDocument.Uri, hostDocument.GetProjectContext()); diff --git a/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/Endpoints/RazorCustomMessageTarget_CodeActions.cs b/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/Endpoints/RazorCustomMessageTarget_CodeActions.cs index 60384baa0af..e8f5cd0af35 100644 --- a/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/Endpoints/RazorCustomMessageTarget_CodeActions.cs +++ b/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/Endpoints/RazorCustomMessageTarget_CodeActions.cs @@ -21,11 +21,6 @@ internal partial class RazorCustomMessageTarget [JsonRpcMethod(CustomMessageNames.RazorProvideCodeActionsEndpoint, UseSingleObjectParameterDeserialization = true)] public async Task?> ProvideCodeActionsAsync(DelegatedCodeActionParams codeActionParams, CancellationToken cancellationToken) { - if (codeActionParams is null) - { - throw new ArgumentNullException(nameof(codeActionParams)); - } - bool synchronized; VirtualDocumentSnapshot virtualDocumentSnapshot; string languageServerName; @@ -35,7 +30,7 @@ internal partial class RazorCustomMessageTarget codeActionParams.HostDocumentVersion, codeActionParams.CodeActionParams.TextDocument, cancellationToken).ConfigureAwait(false); - languageServerName = RazorLSPConstants.RazorCSharpLanguageServerName; + languageServerName = RazorLSPConstants.HtmlLanguageServerName; } else if (codeActionParams.LanguageKind == RazorLanguageKind.CSharp) { @@ -43,7 +38,7 @@ internal partial class RazorCustomMessageTarget codeActionParams.HostDocumentVersion, codeActionParams.CodeActionParams.TextDocument, cancellationToken).ConfigureAwait(false); - languageServerName = RazorLSPConstants.HtmlLanguageServerName; + languageServerName = RazorLSPConstants.RazorCSharpLanguageServerName; } else { diff --git a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/CodeActions/Html/DefaultHtmlCodeActionProviderTest.cs b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/CodeActions/Html/DefaultHtmlCodeActionProviderTest.cs index bddb160495e..631b6c927e3 100644 --- a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/CodeActions/Html/DefaultHtmlCodeActionProviderTest.cs +++ b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/CodeActions/Html/DefaultHtmlCodeActionProviderTest.cs @@ -84,7 +84,6 @@ public async Task ProvideAsync_RemapsAndFixesEdits() TextDocument = new OptionalVersionedTextDocumentIdentifier { Uri = new Uri(documentPath), - Version = 1 }, Edits = [VsLspFactory.CreateTextEdit(context.SourceText.GetRange(span), "Goo ~~~~~~~~~~~~~~~ Bar")] } @@ -111,7 +110,6 @@ public async Task ProvideAsync_RemapsAndFixesEdits() TextDocument = new OptionalVersionedTextDocumentIdentifier { Uri = new Uri("c:/Test.razor.html"), - Version = 1 }, Edits = [VsLspFactory.CreateTextEdit(position: (0, 0), "Goo")] } diff --git a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/CodeActions/Html/DefaultHtmlCodeActionResolverTest.cs b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/CodeActions/Html/DefaultHtmlCodeActionResolverTest.cs index 480c4c9c633..09cc6992e1b 100644 --- a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/CodeActions/Html/DefaultHtmlCodeActionResolverTest.cs +++ b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/CodeActions/Html/DefaultHtmlCodeActionResolverTest.cs @@ -43,7 +43,6 @@ public async Task ResolveAsync_RemapsAndFixesEdits() TextDocument = new OptionalVersionedTextDocumentIdentifier { Uri = documentUri, - Version = 1 }, Edits = [VsLspFactory.CreateTextEdit(sourceText.GetRange(span), "Goo ~~~~~~~~~~~~~~~ Bar")] } @@ -74,7 +73,6 @@ public async Task ResolveAsync_RemapsAndFixesEdits() TextDocument = new OptionalVersionedTextDocumentIdentifier { Uri = new Uri("c:/Test.razor.html"), - Version = 1 }, Edits = [VsLspFactory.CreateTextEdit(position: (0, 0), "Goo")] } From 4124ce437058b8a8cc0e13d038114682266da860 Mon Sep 17 00:00:00 2001 From: David Wengier Date: Fri, 23 Aug 2024 07:05:50 +1000 Subject: [PATCH 15/16] Remove unused parameter --- .../AbstractTextDocumentPresentationEndpointBase.cs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/DocumentPresentation/AbstractTextDocumentPresentationEndpointBase.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/DocumentPresentation/AbstractTextDocumentPresentationEndpointBase.cs index 08e735ca3bd..f3800209380 100644 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/DocumentPresentation/AbstractTextDocumentPresentationEndpointBase.cs +++ b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/DocumentPresentation/AbstractTextDocumentPresentationEndpointBase.cs @@ -115,7 +115,7 @@ internal abstract class AbstractTextDocumentPresentationEndpointBase( // The responses we get back will be for virtual documents, so we have to map them back to the real // document, and in the case of C#, map the returned ranges too - var edit = MapWorkspaceEdit(response, mapRanges: languageKind == RazorLanguageKind.CSharp, codeDocument, documentContext.Snapshot.Version); + var edit = MapWorkspaceEdit(response, mapRanges: languageKind == RazorLanguageKind.CSharp, codeDocument); return edit; } @@ -149,7 +149,7 @@ private Dictionary MapChanges(Dictionary return remappedChanges; } - private TextDocumentEdit[] MapDocumentChanges(TextDocumentEdit[] documentEdits, bool mapRanges, RazorCodeDocument codeDocument, int hostDocumentVersion) + private TextDocumentEdit[] MapDocumentChanges(TextDocumentEdit[] documentEdits, bool mapRanges, RazorCodeDocument codeDocument) { using var remappedDocumentEdits = new PooledArrayBuilder(documentEdits.Length); foreach (var entry in documentEdits) @@ -206,12 +206,12 @@ private TextEdit[] MapTextEdits(bool mapRanges, RazorCodeDocument codeDocument, return mappedEdits.ToArray(); } - private WorkspaceEdit? MapWorkspaceEdit(WorkspaceEdit workspaceEdit, bool mapRanges, RazorCodeDocument codeDocument, int hostDocumentVersion) + private WorkspaceEdit? MapWorkspaceEdit(WorkspaceEdit workspaceEdit, bool mapRanges, RazorCodeDocument codeDocument) { if (workspaceEdit.TryGetTextDocumentEdits(out var documentEdits)) { // The LSP spec says, we should prefer `DocumentChanges` property over `Changes` if available. - var remappedEdits = MapDocumentChanges(documentEdits, mapRanges, codeDocument, hostDocumentVersion); + var remappedEdits = MapDocumentChanges(documentEdits, mapRanges, codeDocument); return new WorkspaceEdit() { DocumentChanges = remappedEdits From 8cebb29b87e0673e13671ebec1ce57b9c7d07a91 Mon Sep 17 00:00:00 2001 From: David Wengier Date: Tue, 27 Aug 2024 14:00:50 +1000 Subject: [PATCH 16/16] Remove debug.fails --- .../GeneratedDocumentPublisher.cs | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/GeneratedDocumentPublisher.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/GeneratedDocumentPublisher.cs index 81a34f72030..18cbf9b9e65 100644 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/GeneratedDocumentPublisher.cs +++ b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/GeneratedDocumentPublisher.cs @@ -75,7 +75,6 @@ public void PublishCSharp(ProjectKey projectKey, string filePath, SourceText sou if (previouslyPublishedData.HostDocumentVersion > hostDocumentVersion) { // We've already published a newer version of this document. No-op. - Debug.Fail("C# document being published that is older than one we've previously published!"); _logger.LogWarning($"Skipping publish of C# for {filePath} because we've already published version {previouslyPublishedData.HostDocumentVersion}, and this request is for {hostDocumentVersion}."); return; } @@ -122,7 +121,6 @@ public void PublishHtml(ProjectKey projectKey, string filePath, SourceText sourc if (previouslyPublishedData.HostDocumentVersion > hostDocumentVersion) { // We've already published a newer version of this document. No-op. - Debug.Fail("Html document being published that is older than one we've previously published!"); _logger.LogWarning($"Skipping publish of Html for {filePath} because we've already published version {previouslyPublishedData.HostDocumentVersion}, and this request is for {hostDocumentVersion}."); return; }