-
Notifications
You must be signed in to change notification settings - Fork 196
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Always use designtime document for formatting with FUSE #10640
Merged
ryzngard
merged 7 commits into
dotnet:main
from
ryzngard:formatting_always_uses_designtime
Jul 22, 2024
Merged
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
4f89cb3
Move flag passing
ryzngard fd2de6a
Check feature flag and force design time if it's on
ryzngard 19f6059
Add some tests
ryzngard 1a00a68
Use the same code document everywhere
ryzngard 9e0c256
Fix cohosting
ryzngard 7effa35
Update src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/ProjectS…
ryzngard 0880f25
Update src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/…
ryzngard File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
252 changes: 252 additions & 0 deletions
252
...crosoft.CodeAnalysis.Razor.Workspaces/ProjectSystem/DocumentState.ComputedStateTracker.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,252 @@ | ||
// 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.CodeAnalysis; | ||
using System.Threading; | ||
using System.Threading.Tasks; | ||
using Microsoft.AspNetCore.Razor.Language; | ||
|
||
namespace Microsoft.CodeAnalysis.Razor.ProjectSystem; | ||
|
||
internal partial class DocumentState | ||
{ | ||
private class ComputedStateTracker | ||
ryzngard marked this conversation as resolved.
Show resolved
Hide resolved
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. All of this green made me remember how much I hate how confusing |
||
{ | ||
private readonly object _lock; | ||
|
||
private ComputedStateTracker? _older; | ||
|
||
// We utilize a WeakReference here to avoid bloating committed memory. If pieces request document output inbetween GC collections | ||
// then we will provide the weak referenced task; otherwise we require any state requests to be re-computed. | ||
private WeakReference<Task<(RazorCodeDocument, VersionStamp)>>? _taskUnsafeReference; | ||
|
||
private ComputedOutput? _computedOutput; | ||
|
||
public ComputedStateTracker(DocumentState state, ComputedStateTracker? older = null) | ||
{ | ||
_lock = state._lock; | ||
_older = older; | ||
} | ||
|
||
public bool IsResultAvailable | ||
{ | ||
get | ||
{ | ||
if (_computedOutput?.TryGetCachedOutput(out _, out _) == true) | ||
{ | ||
return true; | ||
} | ||
|
||
if (_taskUnsafeReference is null) | ||
{ | ||
return false; | ||
} | ||
|
||
if (_taskUnsafeReference.TryGetTarget(out var taskUnsafe)) | ||
{ | ||
return taskUnsafe.IsCompleted; | ||
} | ||
|
||
return false; | ||
} | ||
} | ||
|
||
public async Task<(RazorCodeDocument, VersionStamp)> GetGeneratedOutputAndVersionAsync(ProjectSnapshot project, IDocumentSnapshot document) | ||
{ | ||
if (_computedOutput?.TryGetCachedOutput(out var cachedCodeDocument, out var cachedInputVersion) == true) | ||
{ | ||
return (cachedCodeDocument, cachedInputVersion); | ||
} | ||
|
||
var (codeDocument, inputVersion) = await GetMemoizedGeneratedOutputAndVersionAsync(project, document).ConfigureAwait(false); | ||
|
||
_computedOutput = new ComputedOutput(codeDocument, inputVersion); | ||
return (codeDocument, inputVersion); | ||
} | ||
|
||
private Task<(RazorCodeDocument, VersionStamp)> GetMemoizedGeneratedOutputAndVersionAsync(ProjectSnapshot project, IDocumentSnapshot document) | ||
{ | ||
if (project is null) | ||
{ | ||
throw new ArgumentNullException(nameof(project)); | ||
} | ||
|
||
if (document is null) | ||
{ | ||
throw new ArgumentNullException(nameof(document)); | ||
} | ||
|
||
if (_taskUnsafeReference is null || | ||
!_taskUnsafeReference.TryGetTarget(out var taskUnsafe)) | ||
{ | ||
TaskCompletionSource<(RazorCodeDocument, VersionStamp)>? tcs = null; | ||
|
||
lock (_lock) | ||
{ | ||
if (_taskUnsafeReference is null || | ||
!_taskUnsafeReference.TryGetTarget(out taskUnsafe)) | ||
{ | ||
// So this is a bit confusing. Instead of directly calling the Razor parser inside of this lock we create an indirect TaskCompletionSource | ||
// to represent when it completes. The reason behind this is that there are several scenarios in which the Razor parser will run synchronously | ||
// (mostly all in VS) resulting in this lock being held for significantly longer than expected. To avoid threads queuing up repeatedly on the | ||
// above lock and blocking we can allow those threads to await asynchronously for the completion of the original parse. | ||
|
||
tcs = new(TaskCreationOptions.RunContinuationsAsynchronously); | ||
taskUnsafe = tcs.Task; | ||
_taskUnsafeReference = new WeakReference<Task<(RazorCodeDocument, VersionStamp)>>(taskUnsafe); | ||
} | ||
} | ||
|
||
if (tcs is null) | ||
{ | ||
// There's no task completion source created meaning a value was retrieved from cache, just return it. | ||
return taskUnsafe; | ||
} | ||
|
||
// Typically in VS scenarios this will run synchronously because all resources are readily available. | ||
var outputTask = ComputeGeneratedOutputAndVersionAsync(project, document); | ||
if (outputTask.IsCompleted) | ||
{ | ||
// Compiling ran synchronously, lets just immediately propagate to the TCS | ||
PropagateToTaskCompletionSource(outputTask, tcs); | ||
} | ||
else | ||
{ | ||
// Task didn't run synchronously (most likely outside of VS), lets allocate a bit more but utilize ContinueWith | ||
// to properly connect the output task and TCS | ||
_ = outputTask.ContinueWith( | ||
static (task, state) => | ||
{ | ||
Assumes.NotNull(state); | ||
var tcs = (TaskCompletionSource<(RazorCodeDocument, VersionStamp)>)state; | ||
|
||
PropagateToTaskCompletionSource(task, tcs); | ||
}, | ||
tcs, | ||
CancellationToken.None, | ||
TaskContinuationOptions.ExecuteSynchronously, | ||
TaskScheduler.Default); | ||
} | ||
} | ||
|
||
return taskUnsafe; | ||
|
||
static void PropagateToTaskCompletionSource( | ||
Task<(RazorCodeDocument, VersionStamp)> targetTask, | ||
TaskCompletionSource<(RazorCodeDocument, VersionStamp)> tcs) | ||
{ | ||
if (targetTask.Status == TaskStatus.RanToCompletion) | ||
{ | ||
#pragma warning disable VSTHRD103 // Call async methods when in an async method | ||
tcs.SetResult(targetTask.Result); | ||
#pragma warning restore VSTHRD103 // Call async methods when in an async method | ||
} | ||
else if (targetTask.Status == TaskStatus.Canceled) | ||
{ | ||
tcs.SetCanceled(); | ||
} | ||
else if (targetTask.Status == TaskStatus.Faulted) | ||
{ | ||
// Faulted tasks area always aggregate exceptions so we need to extract the "true" exception if it's available: | ||
Assumes.NotNull(targetTask.Exception); | ||
var exception = targetTask.Exception.InnerException ?? targetTask.Exception; | ||
tcs.SetException(exception); | ||
} | ||
} | ||
} | ||
|
||
private async Task<(RazorCodeDocument, VersionStamp)> ComputeGeneratedOutputAndVersionAsync(ProjectSnapshot project, IDocumentSnapshot document) | ||
{ | ||
// We only need to produce the generated code if any of our inputs is newer than the | ||
// previously cached output. | ||
// | ||
// First find the versions that are the inputs: | ||
// - The project + computed state | ||
// - The imports | ||
// - This document | ||
// | ||
// All of these things are cached, so no work is wasted if we do need to generate the code. | ||
var configurationVersion = project.State.ConfigurationVersion; | ||
var projectWorkspaceStateVersion = project.State.ProjectWorkspaceStateVersion; | ||
var documentCollectionVersion = project.State.DocumentCollectionVersion; | ||
var imports = await GetImportsAsync(document, project.GetProjectEngine()).ConfigureAwait(false); | ||
var documentVersion = await document.GetTextVersionAsync().ConfigureAwait(false); | ||
|
||
// OK now that have the previous output and all of the versions, we can see if anything | ||
// has changed that would require regenerating the code. | ||
var inputVersion = documentVersion; | ||
if (inputVersion.GetNewerVersion(configurationVersion) == configurationVersion) | ||
{ | ||
inputVersion = configurationVersion; | ||
} | ||
|
||
if (inputVersion.GetNewerVersion(projectWorkspaceStateVersion) == projectWorkspaceStateVersion) | ||
{ | ||
inputVersion = projectWorkspaceStateVersion; | ||
} | ||
|
||
if (inputVersion.GetNewerVersion(documentCollectionVersion) == documentCollectionVersion) | ||
{ | ||
inputVersion = documentCollectionVersion; | ||
} | ||
|
||
foreach (var import in imports) | ||
{ | ||
var importVersion = import.Version; | ||
if (inputVersion.GetNewerVersion(importVersion) == importVersion) | ||
{ | ||
inputVersion = importVersion; | ||
} | ||
} | ||
|
||
if (_older?._taskUnsafeReference != null && | ||
_older._taskUnsafeReference.TryGetTarget(out var taskUnsafe)) | ||
{ | ||
var (olderOutput, olderInputVersion) = await taskUnsafe.ConfigureAwait(false); | ||
if (inputVersion.GetNewerVersion(olderInputVersion) == olderInputVersion) | ||
{ | ||
// Nothing has changed, we can use the cached result. | ||
lock (_lock) | ||
{ | ||
_taskUnsafeReference = _older._taskUnsafeReference; | ||
_older = null; | ||
return (olderOutput, olderInputVersion); | ||
} | ||
} | ||
} | ||
|
||
var tagHelpers = await project.GetTagHelpersAsync(CancellationToken.None).ConfigureAwait(false); | ||
var forceRuntimeCodeGeneration = project.Configuration.LanguageServerFlags?.ForceRuntimeCodeGeneration ?? false; | ||
var codeDocument = await GenerateCodeDocumentAsync(tagHelpers, project.GetProjectEngine(), document, imports, forceRuntimeCodeGeneration).ConfigureAwait(false); | ||
return (codeDocument, inputVersion); | ||
} | ||
|
||
private class ComputedOutput | ||
{ | ||
private readonly VersionStamp _inputVersion; | ||
private readonly WeakReference<RazorCodeDocument> _codeDocumentReference; | ||
|
||
public ComputedOutput(RazorCodeDocument codeDocument, VersionStamp inputVersion) | ||
{ | ||
_codeDocumentReference = new WeakReference<RazorCodeDocument>(codeDocument); | ||
_inputVersion = inputVersion; | ||
} | ||
|
||
public bool TryGetCachedOutput([NotNullWhen(true)] out RazorCodeDocument? codeDocument, out VersionStamp inputVersion) | ||
{ | ||
// The goal here is to capture a weak reference to the code document so if there's ever a sub-system that's still utilizing it | ||
// our computed output maintains its cache. | ||
|
||
if (_codeDocumentReference.TryGetTarget(out codeDocument)) | ||
{ | ||
inputVersion = _inputVersion; | ||
return true; | ||
} | ||
|
||
inputVersion = default; | ||
return false; | ||
} | ||
} | ||
} | ||
} |
12 changes: 12 additions & 0 deletions
12
...zor/src/Microsoft.CodeAnalysis.Razor.Workspaces/ProjectSystem/DocumentState.ImportItem.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,12 @@ | ||
// Copyright (c) .NET Foundation. All rights reserved. | ||
// Licensed under the MIT license. See License.txt in the project root for license information. | ||
|
||
namespace Microsoft.CodeAnalysis.Razor.ProjectSystem; | ||
|
||
internal partial class DocumentState | ||
{ | ||
internal record struct ImportItem(string? FilePath, VersionStamp Version, IDocumentSnapshot Document) | ||
{ | ||
public readonly string? FileKind => Document.FileKind; | ||
} | ||
} |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Should this take a
CancellationToken
and pass it toGetDesignTimeDocumentAsync(...)
and then intoproject.GetTagHelpersAsync(...)
?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
A lot of the stack this depends on doesn't currently take cancellation tokens. I think they should so I'll file a tech debt issue.