From 87d6c9955d4c6f71a2745317f5d5b20a62874407 Mon Sep 17 00:00:00 2001 From: tmat Date: Fri, 23 May 2025 09:06:57 -0700 Subject: [PATCH 1/2] Simplify diagnostic tracking --- .../EditAndContinueLanguageService.cs | 28 +- .../EditAndContinueLanguageServiceTests.cs | 67 +- .../EditAndContinue/DebuggingSession.cs | 26 +- .../EditAndContinue/DocumentWithRudeEdits.cs | 13 - .../EditAndContinueDiagnosticDescriptors.cs | 88 ++- .../Portable/EditAndContinue/EditSession.cs | 601 +++++++++--------- .../EditAndContinue/EditSessionTelemetry.cs | 17 +- .../EmitSolutionUpdateResults.cs | 122 ++-- .../IEditAndContinueSessionTracker.cs | 4 +- .../Remote/RemoteDebuggingSessionProxy.cs | 2 - .../EditAndContinue/RudeEditDiagnostic.cs | 24 - .../Portable/EditAndContinue/RudeEditKind.cs | 3 + .../EditAndContinue/SolutionUpdate.cs | 22 +- .../EditAndContinue/Utilities/Extensions.cs | 15 +- .../Watch/Api/WatchHotReloadService.cs | 8 +- .../EditAndContinueWorkspaceServiceTests.cs | 142 +++-- .../EmitSolutionUpdateResultsTests.cs | 5 +- .../RemoteEditAndContinueServiceTests.cs | 1 - .../EditAndContinueWorkspaceTestBase.cs | 6 + .../ManagedHotReloadLanguageService.cs | 1 - .../RemoteEditAndContinueService.cs | 1 - .../Core/Utilities/PooledBuilderExtensions.cs | 4 +- 22 files changed, 628 insertions(+), 572 deletions(-) delete mode 100644 src/Features/Core/Portable/EditAndContinue/DocumentWithRudeEdits.cs diff --git a/src/EditorFeatures/Core/EditAndContinue/EditAndContinueLanguageService.cs b/src/EditorFeatures/Core/EditAndContinue/EditAndContinueLanguageService.cs index 4e8dc859383f2..8ba83cfca7f08 100644 --- a/src/EditorFeatures/Core/EditAndContinue/EditAndContinueLanguageService.cs +++ b/src/EditorFeatures/Core/EditAndContinue/EditAndContinueLanguageService.cs @@ -398,26 +398,26 @@ public async ValueTask GetUpdatesAsync(ImmutableArray? deletedDocumentRudeEdits = null; - foreach (var rudeEdit in result.RudeEdits) + ArrayBuilder? applyChangesDiagnostics = null; + foreach (var diagnostic in result.Diagnostics) { - if (await solution.GetDocumentAsync(rudeEdit.DocumentId, includeSourceGenerated: true, cancellationToken).ConfigureAwait(false) == null) + // Report warnings and errors that are not reported when analyzing documents or are reported for deleted documents. + + if (diagnostic.Severity is not (DiagnosticSeverity.Error or DiagnosticSeverity.Warning)) { - deletedDocumentRudeEdits ??= ArrayBuilder.GetInstance(); - deletedDocumentRudeEdits.Add(rudeEdit); + continue; } - } - if (deletedDocumentRudeEdits != null) - { - deletedDocumentRudeEdits.AddRange(result.Diagnostics); - UpdateApplyChangesDiagnostics(deletedDocumentRudeEdits.ToImmutableAndFree()); - } - else - { - UpdateApplyChangesDiagnostics(result.Diagnostics); + if ((!EditAndContinueDiagnosticDescriptors.IsRudeEdit(diagnostic.Id)) || + await solution.GetDocumentAsync(diagnostic.DocumentId, includeSourceGenerated: true, cancellationToken).ConfigureAwait(false) == null) + { + applyChangesDiagnostics ??= ArrayBuilder.GetInstance(); + applyChangesDiagnostics.Add(diagnostic); + } } + UpdateApplyChangesDiagnostics(applyChangesDiagnostics.ToImmutableOrEmptyAndFree()); + return new ManagedHotReloadUpdates( result.ModuleUpdates.Updates.FromContract(), result.GetAllDiagnostics().FromContract(), diff --git a/src/EditorFeatures/Test/EditAndContinue/EditAndContinueLanguageServiceTests.cs b/src/EditorFeatures/Test/EditAndContinue/EditAndContinueLanguageServiceTests.cs index cd9743e109eca..5f0c1571e4343 100644 --- a/src/EditorFeatures/Test/EditAndContinue/EditAndContinueLanguageServiceTests.cs +++ b/src/EditorFeatures/Test/EditAndContinue/EditAndContinueLanguageServiceTests.cs @@ -118,7 +118,7 @@ public async Task Test(bool commitChanges) await localWorkspace.ChangeSolutionAsync(localWorkspace.CurrentSolution .AddTestProject("proj", out var projectId) - .AddTestDocument("test.cs", "class C { }", out var documentId).Project.Solution); + .AddTestDocument("class C { }", "test.cs", out var documentId).Project.Solution); var solution = localWorkspace.CurrentSolution; var project = solution.GetRequiredProject(projectId); @@ -156,15 +156,30 @@ await localWorkspace.ChangeSolutionAsync(localWorkspace.CurrentSolution // EmitSolutionUpdate - var diagnosticDescriptor1 = EditAndContinueDiagnosticDescriptors.GetDescriptor(EditAndContinueErrorCode.ErrorReadingFile); + var errorReadingFileDescriptor = EditAndContinueDiagnosticDescriptors.GetDescriptor(EditAndContinueErrorCode.ErrorReadingFile); + var moduleErrorDescriptor = EditAndContinueDiagnosticDescriptors.GetModuleDiagnosticDescriptor(Contracts.EditAndContinue.ManagedHotReloadAvailabilityStatus.Optimized); + var syntaxErrorDescriptor = new DiagnosticDescriptor("CS0001", "Syntax error", "Syntax error", "Compiler", DiagnosticSeverity.Error, isEnabledByDefault: true); + var compilerHiddenDescriptor = new DiagnosticDescriptor("CS0002", "Hidden", "Emit Hidden", "Compiler", DiagnosticSeverity.Hidden, isEnabledByDefault: true); + var compilerInfoDescriptor = new DiagnosticDescriptor("CS0003", "Info", "Emit Info", "Compiler", DiagnosticSeverity.Info, isEnabledByDefault: true); + var compilerWarningDescriptor = new DiagnosticDescriptor("CS0004", "Emit Warning", "Emit Warning", "Compiler", DiagnosticSeverity.Warning, isEnabledByDefault: true); + var compilerErrorDescriptor = new DiagnosticDescriptor("CS0005", "Emit Error", "Emit Error", "Compiler", DiagnosticSeverity.Error, isEnabledByDefault: true); mockEncService.EmitSolutionUpdateImpl = (solution, _, _) => { var syntaxTree = solution.GetRequiredDocument(documentId).GetSyntaxTreeSynchronously(CancellationToken.None)!; - var documentDiagnostic = CodeAnalysis.Diagnostic.Create(diagnosticDescriptor1, Location.Create(syntaxTree, TextSpan.FromBounds(1, 2)), ["doc", "error 1"]); - var projectDiagnostic = CodeAnalysis.Diagnostic.Create(diagnosticDescriptor1, Location.None, ["proj", "error 2"]); - var syntaxError = CodeAnalysis.Diagnostic.Create(diagnosticDescriptor1, Location.Create(syntaxTree, TextSpan.FromBounds(1, 2)), ["doc", "syntax error 3"]); + var documentDiagnostic = CodeAnalysis.Diagnostic.Create(errorReadingFileDescriptor, Location.Create(syntaxTree, TextSpan.FromBounds(1, 2)), ["doc", "error 1"]); + var projectDiagnostic = CodeAnalysis.Diagnostic.Create(errorReadingFileDescriptor, Location.None, ["proj", "error 2"]); + var moduleError = CodeAnalysis.Diagnostic.Create(moduleErrorDescriptor, Location.None, ["proj", "module error"]); + var syntaxError = CodeAnalysis.Diagnostic.Create(syntaxErrorDescriptor, Location.Create(syntaxTree, TextSpan.FromBounds(1, 2))); + var compilerDocHidden = CodeAnalysis.Diagnostic.Create(compilerHiddenDescriptor, Location.Create(syntaxTree, TextSpan.FromBounds(1, 2))); + var compilerDocInfo = CodeAnalysis.Diagnostic.Create(compilerInfoDescriptor, Location.Create(syntaxTree, TextSpan.FromBounds(1, 2))); + var compilerDocWarning = CodeAnalysis.Diagnostic.Create(compilerWarningDescriptor, Location.Create(syntaxTree, TextSpan.FromBounds(1, 2))); + var compilerDocError = CodeAnalysis.Diagnostic.Create(compilerErrorDescriptor, Location.Create(syntaxTree, TextSpan.FromBounds(1, 2))); + var compilerProjectHidden = CodeAnalysis.Diagnostic.Create(compilerHiddenDescriptor, Location.None); + var compilerProjectInfo = CodeAnalysis.Diagnostic.Create(compilerInfoDescriptor, Location.None); + var compilerProjectWarning = CodeAnalysis.Diagnostic.Create(compilerWarningDescriptor, Location.None); + var compilerProjectError = CodeAnalysis.Diagnostic.Create(compilerErrorDescriptor, Location.None); var rudeEditDiagnostic = new RudeEditDiagnostic(RudeEditKind.Delete, TextSpan.FromBounds(2, 3), arguments: ["x"]).ToDiagnostic(syntaxTree); var deletedDocumentRudeEdit = new RudeEditDiagnostic(RudeEditKind.Delete, TextSpan.FromBounds(2, 3), arguments: [""]).ToDiagnostic(tree: null); @@ -172,8 +187,26 @@ await localWorkspace.ChangeSolutionAsync(localWorkspace.CurrentSolution { Solution = solution, ModuleUpdates = new ModuleUpdates(ModuleUpdateStatus.Ready, []), - Diagnostics = [new ProjectDiagnostics(project.Id, [documentDiagnostic, projectDiagnostic])], - RudeEdits = [new ProjectDiagnostics(project.Id, [rudeEditDiagnostic, deletedDocumentRudeEdit])], + Diagnostics = + [ + new ProjectDiagnostics( + project.Id, + [ + documentDiagnostic, + projectDiagnostic, + moduleError, + rudeEditDiagnostic, + deletedDocumentRudeEdit, + compilerDocError, + compilerDocWarning, + compilerDocHidden, + compilerDocInfo, + compilerProjectError, + compilerProjectWarning, + compilerProjectHidden, + compilerProjectInfo, + ]) + ], SyntaxError = syntaxError, ProjectsToRebuild = [project.Id], ProjectsToRestart = ImmutableDictionary>.Empty.Add(project.Id, []) @@ -186,18 +219,28 @@ await localWorkspace.ChangeSolutionAsync(localWorkspace.CurrentSolution AssertEx.Equal( [ - $"Error ENC0033: {project.FilePath}(0, 0, 0, 0): {string.Format(FeaturesResources.Deleting_0_requires_restarting_the_application, "")}", $"Error ENC1001: {document.FilePath}(0, 1, 0, 2): {string.Format(FeaturesResources.ErrorReadingFile, "doc", "error 1")}", - $"Error ENC1001: {project.FilePath}(0, 0, 0, 0): {string.Format(FeaturesResources.ErrorReadingFile, "proj", "error 2")}" + $"Error ENC1001: {project.FilePath}(0, 0, 0, 0): {string.Format(FeaturesResources.ErrorReadingFile, "proj", "error 2")}", + $"Error ENC2012: {project.FilePath}(0, 0, 0, 0): {string.Format(FeaturesResources.EditAndContinueDisallowedByProject, "proj", "module error")}", + $"Error ENC0033: {project.FilePath}(0, 0, 0, 0): {string.Format(FeaturesResources.Deleting_0_requires_restarting_the_application, "")}", + $"Error CS0005: {document.FilePath}(0, 1, 0, 2): Emit Error", + $"Warning CS0004: {document.FilePath}(0, 1, 0, 2): Emit Warning", + $"Error CS0005: {project.FilePath}(0, 0, 0, 0): Emit Error", + $"Warning CS0004: {project.FilePath}(0, 0, 0, 0): Emit Warning", ], sessionState.ApplyChangesDiagnostics.Select(Inspect)); AssertEx.Equal( [ - $"Error ENC1001: {document.FilePath}(0, 1, 0, 2): {string.Format(FeaturesResources.ErrorReadingFile, "doc", "error 1")}", - $"Error ENC1001: {project.FilePath}(0, 0, 0, 0): {string.Format(FeaturesResources.ErrorReadingFile, "proj", "error 2")}", - $"Error ENC1001: {document.FilePath}(0, 1, 0, 2): {string.Format(FeaturesResources.ErrorReadingFile, "doc", "syntax error 3")}", + $"RestartRequired ENC1001: {document.FilePath}(0, 1, 0, 2): {string.Format(FeaturesResources.ErrorReadingFile, "doc", "error 1")}", + $"RestartRequired ENC1001: {project.FilePath}(0, 0, 0, 0): {string.Format(FeaturesResources.ErrorReadingFile, "proj", "error 2")}", + $"RestartRequired ENC2012: {project.FilePath}(0, 0, 0, 0): {string.Format(FeaturesResources.EditAndContinueDisallowedByProject, "proj", "module error")}", $"RestartRequired ENC0033: {document.FilePath}(0, 2, 0, 3): {string.Format(FeaturesResources.Deleting_0_requires_restarting_the_application, "x")}", $"RestartRequired ENC0033: {project.FilePath}(0, 0, 0, 0): {string.Format(FeaturesResources.Deleting_0_requires_restarting_the_application, "")}", + $"Error CS0005: {document.FilePath}(0, 1, 0, 2): Emit Error", + $"Warning CS0004: {document.FilePath}(0, 1, 0, 2): Emit Warning", + $"Error CS0005: {project.FilePath}(0, 0, 0, 0): Emit Error", + $"Warning CS0004: {project.FilePath}(0, 0, 0, 0): Emit Warning", + $"Error CS0001: {document.FilePath}(0, 1, 0, 2): Syntax error", ], updates.Diagnostics.Select(Inspect)); Assert.True(sessionState.IsSessionActive); diff --git a/src/Features/Core/Portable/EditAndContinue/DebuggingSession.cs b/src/Features/Core/Portable/EditAndContinue/DebuggingSession.cs index c1b4eabc70ff4..a264ea3ae34fa 100644 --- a/src/Features/Core/Portable/EditAndContinue/DebuggingSession.cs +++ b/src/Features/Core/Portable/EditAndContinue/DebuggingSession.cs @@ -309,7 +309,7 @@ internal ImmutableList GetOrCreateEmitBaselines( Guid moduleId, Project baselineProject, Compilation baselineCompilation, - out ImmutableArray errors, + ArrayBuilder diagnostics, out ReaderWriterLockSlim baselineAccessLock) { baselineAccessLock = _baselineAccessLock; @@ -319,17 +319,16 @@ internal ImmutableList GetOrCreateEmitBaselines( { if (TryGetBaselinesContainingModuleVersion(moduleId, out existingBaselines)) { - errors = []; return existingBaselines; } } var outputs = GetCompilationOutputs(baselineProject); - if (!TryCreateInitialBaseline(baselineCompilation, outputs, baselineProject.Id, out errors, out var initialBaseline, out var debugInfoReaderProvider, out var metadataReaderProvider)) + if (!TryCreateInitialBaseline(baselineCompilation, outputs, baselineProject.Id, diagnostics, out var initialBaseline, out var debugInfoReaderProvider, out var metadataReaderProvider)) { // Unable to read the DLL/PDB at this point (it might be open by another process). // Don't cache the failure so that the user can attempt to apply changes again. - return existingBaselines ?? []; + return []; } lock (_projectEmitBaselinesGuard) @@ -359,7 +358,7 @@ private unsafe bool TryCreateInitialBaseline( Compilation compilation, CompilationOutputs compilationOutputs, ProjectId projectId, - out ImmutableArray errors, + ArrayBuilder diagnostics, [NotNullWhen(true)] out EmitBaseline? baseline, [NotNullWhen(true)] out DebugInformationReaderProvider? debugInfoReaderProvider, [NotNullWhen(true)] out MetadataReaderProvider? metadataReaderProvider) @@ -370,7 +369,6 @@ private unsafe bool TryCreateInitialBaseline( // Alternatively, we could drop the data once we are done with emitting the delta and re-emit the baseline again // when we need it next time and the module is loaded. - errors = []; baseline = null; debugInfoReaderProvider = null; metadataReaderProvider = null; @@ -413,7 +411,7 @@ private unsafe bool TryCreateInitialBaseline( SessionLog.Write($"Failed to create baseline for '{projectId.DebugName}': {e.Message}", LogMessageSeverity.Error); var descriptor = EditAndContinueDiagnosticDescriptors.GetDescriptor(EditAndContinueErrorCode.ErrorReadingFile); - errors = [Diagnostic.Create(descriptor, Location.None, [fileBeingRead, e.Message])]; + diagnostics.Add(Diagnostic.Create(descriptor, Location.None, [fileBeingRead, e.Message])); } finally { @@ -552,21 +550,10 @@ public async ValueTask EmitSolutionUpdateAsync( break; } - using var _ = ArrayBuilder.GetInstance(out var rudeEditDiagnostics); - foreach (var (projectId, documentsWithRudeEdits) in solutionUpdate.DocumentsWithRudeEdits.GroupBy(static e => e.Id.ProjectId).OrderBy(static id => id)) - { - foreach (var documentWithRudeEdits in documentsWithRudeEdits) - { - var document = await solution.GetDocumentAsync(documentWithRudeEdits.Id, includeSourceGenerated: true, cancellationToken).ConfigureAwait(false); - var tree = (document != null) ? await document.GetRequiredSyntaxTreeAsync(cancellationToken).ConfigureAwait(false) : null; - rudeEditDiagnostics.Add(new(projectId, documentWithRudeEdits.RudeEdits.SelectAsArray(static (rudeEdit, tree) => rudeEdit.ToDiagnostic(tree), tree))); - } - } - EmitSolutionUpdateResults.GetProjectsToRebuildAndRestart( solution, solutionUpdate.ModuleUpdates, - rudeEditDiagnostics, + solutionUpdate.Diagnostics, runningProjects, out var projectsToRestart, out var projectsToRebuild); @@ -578,7 +565,6 @@ public async ValueTask EmitSolutionUpdateAsync( Solution = solution, ModuleUpdates = solutionUpdate.ModuleUpdates, Diagnostics = solutionUpdate.Diagnostics, - RudeEdits = rudeEditDiagnostics.ToImmutable(), SyntaxError = solutionUpdate.SyntaxError, ProjectsToRestart = projectsToRestart, ProjectsToRebuild = projectsToRebuild diff --git a/src/Features/Core/Portable/EditAndContinue/DocumentWithRudeEdits.cs b/src/Features/Core/Portable/EditAndContinue/DocumentWithRudeEdits.cs deleted file mode 100644 index 5759ea8026e56..0000000000000 --- a/src/Features/Core/Portable/EditAndContinue/DocumentWithRudeEdits.cs +++ /dev/null @@ -1,13 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Collections.Immutable; - -namespace Microsoft.CodeAnalysis.EditAndContinue; - -internal readonly struct DocumentWithRudeEdits(DocumentId id, ImmutableArray rudeEdits) -{ - public DocumentId Id { get; } = id; - public ImmutableArray RudeEdits { get; } = rudeEdits; -} diff --git a/src/Features/Core/Portable/EditAndContinue/EditAndContinueDiagnosticDescriptors.cs b/src/Features/Core/Portable/EditAndContinue/EditAndContinueDiagnosticDescriptors.cs index 65a6f9c4410dd..646d2e7cd5673 100644 --- a/src/Features/Core/Portable/EditAndContinue/EditAndContinueDiagnosticDescriptors.cs +++ b/src/Features/Core/Portable/EditAndContinue/EditAndContinueDiagnosticDescriptors.cs @@ -2,9 +2,9 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable disable - using System; +using System.Linq; +using System.Diagnostics; using System.Collections.Generic; using System.Collections.Immutable; using Microsoft.CodeAnalysis.Contracts.EditAndContinue; @@ -14,18 +14,24 @@ namespace Microsoft.CodeAnalysis.EditAndContinue; internal static class EditAndContinueDiagnosticDescriptors { - private const int GeneralDiagnosticBaseId = 1000; - private const int ModuleDiagnosticBaseId = 2000; - private static readonly int s_diagnosticBaseIndex; + private const string EncDiagnosticIdPrefix = "ENC"; + private const string RudeEditDiagnosticIdPrefix = EncDiagnosticIdPrefix + "0"; + private const string GeneralDiagnosticIdPrefix = EncDiagnosticIdPrefix + "1"; + private const string ModuleDiagnosticIdPrefix = EncDiagnosticIdPrefix + "2"; + + private static readonly int s_generalDiagnosticBaseIndex; private static readonly LocalizableResourceString s_rudeEditLocString; private static readonly LocalizableResourceString s_encLocString; private static readonly LocalizableResourceString s_encDisallowedByProjectLocString; private static readonly ImmutableArray s_descriptors; + private static readonly ImmutableHashSet s_noEffectDiagnosticIds; + + private static readonly string s_documentReadErrorId = GetDiagnosticId(EditAndContinueErrorCode.UnableToReadSourceFileOrPdb); // descriptors for diagnostics reported by the debugger: - private static Dictionary s_lazyModuleDiagnosticDescriptors; + private static Dictionary? s_lazyModuleDiagnosticDescriptors; private static readonly object s_moduleDiagnosticDescriptorsGuard; static EditAndContinueDiagnosticDescriptors() @@ -37,29 +43,40 @@ static EditAndContinueDiagnosticDescriptors() s_encDisallowedByProjectLocString = new LocalizableResourceString(nameof(FeaturesResources.EditAndContinueDisallowedByProject), FeaturesResources.ResourceManager, typeof(FeaturesResources)); var builder = ImmutableArray.CreateBuilder(); + var noEffectDiagnosticIds = ImmutableHashSet.CreateBuilder(); - void add(int index, int id, string resourceName, LocalizableResourceString title, DiagnosticSeverity severity) + void Add(int index, string prefix, int code, string resourceName, LocalizableResourceString title, DiagnosticSeverity severity, bool isNoEffect) { + // no-effect diagnostics should be warnings: + Debug.Assert(!isNoEffect || severity == DiagnosticSeverity.Warning); + if (index >= builder.Count) { builder.Count = index + 1; } + var id = GetDiagnosticId(prefix, code); + builder[index] = new DiagnosticDescriptor( - GetDiagnosticId(id), + id, title, messageFormat: new LocalizableResourceString(resourceName, FeaturesResources.ResourceManager, typeof(FeaturesResources)), DiagnosticCategory.EditAndContinue, severity, isEnabledByDefault: true, customTags: DiagnosticCustomTags.EditAndContinue); + + if (isNoEffect) + { + noEffectDiagnosticIds.Add(id); + } } - void AddRudeEdit(RudeEditKind kind, string resourceName, DiagnosticSeverity severity = DiagnosticSeverity.Error) - => add(GetDescriptorIndex(kind), (int)kind, resourceName, s_rudeEditLocString, severity); + void AddRudeEdit(RudeEditKind kind, string resourceName, DiagnosticSeverity severity = DiagnosticSeverity.Error, bool noEffect = false) + => Add(GetDescriptorIndex(kind), RudeEditDiagnosticIdPrefix, (int)kind, resourceName, s_rudeEditLocString, severity, noEffect); - void AddGeneralDiagnostic(EditAndContinueErrorCode code, string resourceName, DiagnosticSeverity severity = DiagnosticSeverity.Error) - => add(GetDescriptorIndex(code), GeneralDiagnosticBaseId + (int)code, resourceName, s_encLocString, severity); + void AddGeneralDiagnostic(EditAndContinueErrorCode code, string resourceName, DiagnosticSeverity severity = DiagnosticSeverity.Error, bool noEffect = false) + => Add(GetDescriptorIndex(code), GeneralDiagnosticIdPrefix, (int)code, resourceName, s_encLocString, severity, noEffect); // // rude edits @@ -148,7 +165,7 @@ void AddGeneralDiagnostic(EditAndContinueErrorCode code, string resourceName, Di AddRudeEdit(RudeEditKind.NotCapturingPrimaryConstructorParameter, nameof(FeaturesResources.Ceasing_to_capture_primary_constructor_parameter_0_of_1_requires_restarting_the_application)); AddRudeEdit(RudeEditKind.ChangingAttribute, nameof(FeaturesResources.Changing_attribute_0_requires_restarting_the_application)); AddRudeEdit(RudeEditKind.ChangingNameOrSignatureOfActiveMember, nameof(FeaturesResources.Changing_name_or_signature_of_0_that_contains_an_active_statement_requires_restarting_the_application)); - AddRudeEdit(RudeEditKind.UpdateMightNotHaveAnyEffect, nameof(FeaturesResources.Changing_0_might_not_have_any_effect_until_the_application_is_restarted), DiagnosticSeverity.Warning); + AddRudeEdit(RudeEditKind.UpdateMightNotHaveAnyEffect, nameof(FeaturesResources.Changing_0_might_not_have_any_effect_until_the_application_is_restarted), DiagnosticSeverity.Warning, noEffect: true); AddRudeEdit(RudeEditKind.TypeUpdateAroundActiveStatement, nameof(FeaturesResources.Updating_a_0_around_an_active_statement_requires_restarting_the_application)); AddRudeEdit(RudeEditKind.InsertOrMoveComInterfaceMember, nameof(FeaturesResources.Adding_or_moving_0_of_a_COM_interface_requires_restarting_the_application)); @@ -162,7 +179,7 @@ void AddGeneralDiagnostic(EditAndContinueErrorCode code, string resourceName, Di // other Roslyn reported diagnostics: // - s_diagnosticBaseIndex = builder.Count; + s_generalDiagnosticBaseIndex = builder.Count; AddGeneralDiagnostic(EditAndContinueErrorCode.ErrorReadingFile, nameof(FeaturesResources.ErrorReadingFile)); AddGeneralDiagnostic(EditAndContinueErrorCode.CannotApplyChangesUnexpectedError, nameof(FeaturesResources.CannotApplyChangesUnexpectedError)); @@ -170,9 +187,10 @@ void AddGeneralDiagnostic(EditAndContinueErrorCode code, string resourceName, Di AddGeneralDiagnostic(EditAndContinueErrorCode.DocumentIsOutOfSyncWithDebuggee, nameof(FeaturesResources.DocumentIsOutOfSyncWithDebuggee), DiagnosticSeverity.Warning); AddGeneralDiagnostic(EditAndContinueErrorCode.UnableToReadSourceFileOrPdb, nameof(FeaturesResources.UnableToReadSourceFileOrPdb)); AddGeneralDiagnostic(EditAndContinueErrorCode.AddingTypeRuntimeCapabilityRequired, nameof(FeaturesResources.ChangesRequiredSynthesizedType)); - AddGeneralDiagnostic(EditAndContinueErrorCode.UpdatingDocumentInStaleProject, nameof(FeaturesResources.Changing_source_file_0_in_a_stale_project_has_no_effect_until_the_project_is_rebuit), DiagnosticSeverity.Warning); + AddGeneralDiagnostic(EditAndContinueErrorCode.UpdatingDocumentInStaleProject, nameof(FeaturesResources.Changing_source_file_0_in_a_stale_project_has_no_effect_until_the_project_is_rebuit), DiagnosticSeverity.Warning, noEffect: true); s_descriptors = builder.ToImmutable(); + s_noEffectDiagnosticIds = noEffectDiagnosticIds.ToImmutable(); } internal static ImmutableArray GetDescriptors() @@ -193,7 +211,7 @@ internal static DiagnosticDescriptor GetModuleDiagnosticDescriptor(ManagedHotRel if (!s_lazyModuleDiagnosticDescriptors.TryGetValue(status, out var descriptor)) { s_lazyModuleDiagnosticDescriptors.Add(status, descriptor = new DiagnosticDescriptor( - $"ENC{ModuleDiagnosticBaseId + (int)status:D4}", + GetDiagnosticId(status), s_encLocString, s_encDisallowedByProjectLocString, DiagnosticCategory.EditAndContinue, @@ -206,15 +224,45 @@ internal static DiagnosticDescriptor GetModuleDiagnosticDescriptor(ManagedHotRel } } + private static string GetDiagnosticId(string prefix, int code) + => $"{prefix}{code:D3}"; + + private static string GetDiagnosticId(EditAndContinueErrorCode code) + => GetDiagnosticId(GeneralDiagnosticIdPrefix, (int)code); + + private static string GetDiagnosticId(ManagedHotReloadAvailabilityStatus status) + => GetDiagnosticId(ModuleDiagnosticIdPrefix, (int)status); + private static int GetDescriptorIndex(RudeEditKind kind) => (int)kind; private static int GetDescriptorIndex(EditAndContinueErrorCode errorCode) - => s_diagnosticBaseIndex + (int)errorCode; + => s_generalDiagnosticBaseIndex + (int)errorCode; + + public static bool IsEncDiagnostic(string diagnosticId) + => diagnosticId.Length > EncDiagnosticIdPrefix.Length && diagnosticId.StartsWith(EncDiagnosticIdPrefix, StringComparison.Ordinal) && diagnosticId[EncDiagnosticIdPrefix.Length] is >= '0' and <= '9'; - private static string GetDiagnosticId(int id) - => $"ENC{id:D4}"; + public static bool IsRudeEdit(string diagnosticId) + => diagnosticId.StartsWith(RudeEditDiagnosticIdPrefix, StringComparison.Ordinal); public static RudeEditKind GetRudeEditKind(string diagnosticId) - => diagnosticId.StartsWith("ENC", StringComparison.Ordinal) && int.TryParse(diagnosticId[3..], out var id) ? (RudeEditKind)id : RudeEditKind.None; + => IsRudeEdit(diagnosticId) && int.TryParse(diagnosticId[RudeEditDiagnosticIdPrefix.Length..], out var id) ? (RudeEditKind)id : RudeEditKind.None; + + public static bool IsDocumentReadError(this Diagnostic diagnostic) + => diagnostic.Id == s_documentReadErrorId; + + public static bool IsNoEffectDiagnostic(this Diagnostic diagnostic) + => s_noEffectDiagnosticIds.Contains(diagnostic.Id); + + public static bool IsEncDiagnostic(this Diagnostic diagnostic) + => IsEncDiagnostic(diagnostic.Id); + + public static DiagnosticSeverity GetSeverity(this RudeEditKind kind) + => GetDescriptor(kind).DefaultSeverity; + + public static bool IsBlocking(this RudeEditKind kind) + => kind.GetSeverity() == DiagnosticSeverity.Error; + + public static bool HasBlockingRudeEdits(this ImmutableArray diagnostics) + => diagnostics.Any(static e => e.Kind.IsBlocking()); } diff --git a/src/Features/Core/Portable/EditAndContinue/EditSession.cs b/src/Features/Core/Portable/EditAndContinue/EditSession.cs index 383ffa69bd5ff..3570ebf2ecdf3 100644 --- a/src/Features/Core/Portable/EditAndContinue/EditSession.cs +++ b/src/Features/Core/Portable/EditAndContinue/EditSession.cs @@ -151,33 +151,26 @@ public TraceLog Log /// /// Errors to be reported when a project is updated but the corresponding module does not support EnC. /// - /// if the module is not loaded. - public async Task?> GetModuleDiagnosticsAsync(Guid mvid, Project oldProject, Project newProject, ImmutableArray documentAnalyses, CancellationToken cancellationToken) + /// Non-null diagnostic id if the module blocks EnC operation. + public async Task ReportModuleDiagnosticsAsync(Guid mvid, Project oldProject, Project newProject, ImmutableArray documentAnalyses, ArrayBuilder diagnostics, CancellationToken cancellationToken) { Contract.ThrowIfTrue(documentAnalyses.IsEmpty); var availability = await DebuggingSession.DebuggerService.GetAvailabilityAsync(mvid, cancellationToken).ConfigureAwait(false); - if (availability.Status == ManagedHotReloadAvailabilityStatus.ModuleNotLoaded) + if (availability.Status is ManagedHotReloadAvailabilityStatus.ModuleNotLoaded or ManagedHotReloadAvailabilityStatus.Available) { return null; } - if (availability.Status == ManagedHotReloadAvailabilityStatus.Available) - { - return ImmutableArray.Empty; - } - var descriptor = EditAndContinueDiagnosticDescriptors.GetModuleDiagnosticDescriptor(availability.Status); var messageArgs = new[] { newProject.Name, availability.LocalizedMessage }; - using var _ = ArrayBuilder.GetInstance(out var diagnostics); - await foreach (var location in CreateChangedLocationsAsync(oldProject, newProject, documentAnalyses, cancellationToken).ConfigureAwait(false)) { diagnostics.Add(Diagnostic.Create(descriptor, location, messageArgs)); } - return diagnostics.ToImmutableAndClear(); + return descriptor.Id; } private static async IAsyncEnumerable CreateChangedLocationsAsync(Project oldProject, Project newProject, ImmutableArray documentAnalyses, [EnumeratorCancellation] CancellationToken cancellationToken) @@ -441,7 +434,7 @@ internal static async ValueTask HasDocumentDifferencesAsync(Project oldPro return false; } - internal static async Task GetDocumentDifferencesAsync(TraceLog log, Project oldProject, Project newProject, ProjectDocumentDifferences documentDifferences, ArrayBuilder diagnostics, CancellationToken cancellationToken) + internal static async Task GetDocumentDifferencesAsync(TraceLog log, Project oldProject, Project newProject, ProjectDocumentDifferences documentDifferences, ArrayBuilder diagnostics, CancellationToken cancellationToken) { documentDifferences.Clear(); @@ -490,23 +483,18 @@ internal static async Task GetDocumentDifferencesAsync(TraceLog log, Project old } } - private static async ValueTask> GetSourceGeneratedDocumentStatesAsync(TraceLog log, Project project, ArrayBuilder? diagnostics, CancellationToken cancellationToken) + private static async ValueTask> GetSourceGeneratedDocumentStatesAsync(TraceLog log, Project project, ArrayBuilder? diagnostics, CancellationToken cancellationToken) { var generatorDiagnostics = await project.Solution.CompilationState.GetSourceGeneratorDiagnosticsAsync(project.State, cancellationToken).ConfigureAwait(false); - if (generatorDiagnostics is not []) - { - diagnostics?.Add(new ProjectDiagnostics(project.Id, generatorDiagnostics)); - } + diagnostics?.AddRange(generatorDiagnostics); - foreach (var generatorDiagnostic in generatorDiagnostics) + if (diagnostics == null) { - log.Write($"Source generator failed: {generatorDiagnostic}", generatorDiagnostic.Severity switch + foreach (var generatorDiagnostic in generatorDiagnostics) { - DiagnosticSeverity.Warning => LogMessageSeverity.Warning, - DiagnosticSeverity.Error => LogMessageSeverity.Error, - _ => LogMessageSeverity.Info - }); + log.Write($"Source generator failed: {generatorDiagnostic}", LogMessageSeverity.Info); + } } return await project.Solution.CompilationState.GetSourceGeneratedDocumentStatesAsync(project.State, cancellationToken).ConfigureAwait(false); @@ -557,13 +545,13 @@ internal static async IAsyncEnumerable GetChangedDocumentsAsync(Trac } } - private async Task<(ImmutableArray results, ImmutableArray diagnostics, bool hasOutOfSyncDocument)> AnalyzeDocumentsAsync( + private async Task<(ImmutableArray results, bool hasOutOfSyncDocument)> AnalyzeDocumentsAsync( Solution newSolution, ProjectDocumentDifferences documentDifferences, ActiveStatementSpanProvider newDocumentActiveStatementSpanProvider, + ArrayBuilder diagnostics, CancellationToken cancellationToken) { - using var _1 = ArrayBuilder.GetInstance(out var documentDiagnostics); using var _2 = ArrayBuilder<(Document? oldDocument, Document? newDocument)>.GetInstance(out var documents); var hasOutOfSyncDocument = false; @@ -577,7 +565,7 @@ internal static async IAsyncEnumerable GetChangedDocumentsAsync(Trac case CommittedSolution.DocumentState.Indeterminate: var descriptor = EditAndContinueDiagnosticDescriptors.GetDescriptor(EditAndContinueErrorCode.UnableToReadSourceFileOrPdb); - documentDiagnostics.Add(Diagnostic.Create(descriptor, Location.Create(newDocument.FilePath!, textSpan: default, lineSpan: default), [newDocument.FilePath])); + diagnostics.Add(Diagnostic.Create(descriptor, Location.Create(newDocument.FilePath!, textSpan: default, lineSpan: default), [newDocument.FilePath])); break; case CommittedSolution.DocumentState.OutOfSync: @@ -609,7 +597,7 @@ internal static async IAsyncEnumerable GetChangedDocumentsAsync(Trac ? [] : await Analyses.GetDocumentAnalysesAsync(DebuggingSession.LastCommittedSolution, newSolution, documents, newDocumentActiveStatementSpanProvider, cancellationToken).ConfigureAwait(false); - return (analyses, documentDiagnostics.ToImmutable(), hasOutOfSyncDocument); + return (analyses, hasOutOfSyncDocument); } private static ProjectAnalysisSummary GetProjectAnalysisSummary(ImmutableArray documentAnalyses) @@ -847,6 +835,8 @@ internal static void MergePartialEdits( public async ValueTask EmitSolutionUpdateAsync(Solution solution, ActiveStatementSpanProvider solutionActiveStatementSpanProvider, UpdateId updateId, CancellationToken cancellationToken) { + var projectDiagnostics = ArrayBuilder.GetInstance(); + try { Log.Write($"Found {updateId.SessionId} potentially changed document(s) in project {updateId.Ordinal} '{solution.FilePath}'"); @@ -854,9 +844,8 @@ public async ValueTask EmitSolutionUpdateAsync(Solution solution using var _1 = ArrayBuilder.GetInstance(out var deltas); using var _2 = ArrayBuilder<(Guid ModuleId, ImmutableArray<(ManagedModuleMethodId Method, NonRemappableRegion Region)>)>.GetInstance(out var nonRemappableRegions); using var _3 = ArrayBuilder.GetInstance(out var newProjectBaselines); - using var _4 = ArrayBuilder.GetInstance(out var diagnostics); - using var _5 = ArrayBuilder.GetInstance(out var documentsWithRudeEdits); - using var _6 = ArrayBuilder.GetInstance(out var projectsToStale); + using var _4 = ArrayBuilder.GetInstance(out var projectsToStale); + using var _5 = PooledDictionary>.GetInstance(out var diagnosticBuilders); using var documentDifferences = new ProjectDocumentDifferences(); // After all projects have been analyzed "true" value indicates changed document that is only included in stale projects. @@ -888,341 +877,347 @@ void UpdateChangedDocumentsStaleness(bool isStale) var blockUpdates = false; var hasEmitErrors = false; - var hadDocumentReadError = false; foreach (var newProject in solution.Projects) { - if (!newProject.SupportsEditAndContinue(Log)) + try { - continue; - } + if (!newProject.SupportsEditAndContinue(Log)) + { + continue; + } - var oldProject = oldSolution.GetProject(newProject.Id); - if (oldProject == null) - { - Log.Write($"EnC state of {newProject.GetLogDisplay()} queried: project not loaded"); + var oldProject = oldSolution.GetProject(newProject.Id); + if (oldProject == null) + { + Log.Write($"EnC state of {newProject.GetLogDisplay()} queried: project not loaded"); + + // TODO (https://github.com/dotnet/roslyn/issues/1204): + // + // When debugging session is started some projects might not have been loaded to the workspace yet (may be explicitly unloaded by the user). + // We capture the base solution. Edits in files that are in projects that haven't been loaded won't be applied + // and will result in source mismatch when the user steps into them. + // + // We can allow project to be added by including all its documents here. + // When we analyze these documents later on we'll check if they match the PDB. + // If so we can add them to the committed solution and detect further changes. + // It might be more efficient though to track added projects separately. + + continue; + } - // TODO (https://github.com/dotnet/roslyn/issues/1204): - // - // When debugging session is started some projects might not have been loaded to the workspace yet (may be explicitly unloaded by the user). - // We capture the base solution. Edits in files that are in projects that haven't been loaded won't be applied - // and will result in source mismatch when the user steps into them. - // - // We can allow project to be added by including all its documents here. - // When we analyze these documents later on we'll check if they match the PDB. - // If so we can add them to the committed solution and detect further changes. - // It might be more efficient though to track added projects separately. + projectDiagnostics = ArrayBuilder.GetInstance(); - continue; - } + await GetDocumentDifferencesAsync(Log, oldProject, newProject, documentDifferences, projectDiagnostics, cancellationToken).ConfigureAwait(false); + if (documentDifferences.IsEmpty) + { + continue; + } - await GetDocumentDifferencesAsync(Log, oldProject, newProject, documentDifferences, diagnostics, cancellationToken).ConfigureAwait(false); - if (documentDifferences.IsEmpty) - { - continue; - } + Log.Write($"Found {documentDifferences.ChangedOrAdded.Count} potentially changed and {documentDifferences.Deleted.Count} deleted document(s) in project {newProject.GetLogDisplay()}"); - Log.Write($"Found {documentDifferences.ChangedOrAdded.Count} potentially changed and {documentDifferences.Deleted.Count} deleted document(s) in project {newProject.GetLogDisplay()}"); + var isStaleProject = oldSolution.IsStaleProject(newProject.Id); - var isStaleProject = oldSolution.IsStaleProject(newProject.Id); + // We don't consider document changes in stale projects until they are rebuilt (removed from stale set). + if (isStaleProject) + { + Log.Write($"EnC state of {newProject.GetLogDisplay()} queried: project is stale"); + UpdateChangedDocumentsStaleness(isStale: true); + continue; + } - // We don't consider document changes in stale projects until they are rebuilt (removed from stale set). - if (isStaleProject) - { - Log.Write($"EnC state of {newProject.GetLogDisplay()} queried: project is stale"); - UpdateChangedDocumentsStaleness(isStale: true); - continue; - } + var (mvid, mvidReadError) = await DebuggingSession.GetProjectModuleIdAsync(newProject, cancellationToken).ConfigureAwait(false); + if (mvidReadError != null) + { + // The error hasn't been reported by GetDocumentDiagnosticsAsync since it might have been intermittent. + // The MVID is required for emit so we consider the error permanent and report it here. + // Bail before analyzing documents as the analysis needs to read the PDB which will likely fail if we can't even read the MVID. + projectDiagnostics.Add(mvidReadError); - var (mvid, mvidReadError) = await DebuggingSession.GetProjectModuleIdAsync(newProject, cancellationToken).ConfigureAwait(false); - if (mvidReadError != null) - { - // The error hasn't been reported by GetDocumentDiagnosticsAsync since it might have been intermittent. - // The MVID is required for emit so we consider the error permanent and report it here. - // Bail before analyzing documents as the analysis needs to read the PDB which will likely fail if we can't even read the MVID. - diagnostics.Add(new(newProject.Id, [mvidReadError])); + Telemetry.LogProjectAnalysisSummary(ProjectAnalysisSummary.ValidChanges, newProject.State.ProjectInfo.Attributes.TelemetryId, projectDiagnostics); + blockUpdates = true; + continue; + } - Telemetry.LogProjectAnalysisSummary(ProjectAnalysisSummary.ValidChanges, newProject.State.ProjectInfo.Attributes.TelemetryId, ImmutableArray.Create(mvidReadError.Descriptor.Id)); - blockUpdates = true; - continue; - } + if (mvid == Guid.Empty) + { + Log.Write($"Changes not applied to {newProject.Name} '{newProject.FilePath}': project not built"); + UpdateChangedDocumentsStaleness(isStale: true); + continue; + } - if (mvid == Guid.Empty) - { - Log.Write($"Changes not applied to {newProject.Name} '{newProject.FilePath}': project not built"); - UpdateChangedDocumentsStaleness(isStale: true); - continue; - } + // Ensure that all changed documents are in-sync. Once a document is in-sync it can't get out-of-sync. + // Therefore, results of further computations based on base snapshots of changed documents can't be invalidated by + // incoming events updating the content of out-of-sync documents. + // + // If in past we concluded that a document is out-of-sync, attempt to check one more time before we block apply. + // The source file content might have been updated since the last time we checked. + // + // TODO (investigate): https://github.com/dotnet/roslyn/issues/38866 + // It is possible that the result of Rude Edit semantic analysis of an unchanged document will change if there + // another document is updated. If we encounter a significant case of this we should consider caching such a result per project, + // rather then per document. Also, we might be observing an older semantics if the document that is causing the change is out-of-sync -- + // e.g. the binary was built with an overload C.M(object), but a generator updated class C to also contain C.M(string), + // which change we have not observed yet. Then call-sites of C.M in a changed document observed by the analysis will be seen as C.M(object) + // instead of the true C.M(string). + + var (changedDocumentAnalyses, hasOutOfSyncChangedDocument) = + await AnalyzeDocumentsAsync(solution, documentDifferences, solutionActiveStatementSpanProvider, projectDiagnostics, cancellationToken).ConfigureAwait(false); - // Ensure that all changed documents are in-sync. Once a document is in-sync it can't get out-of-sync. - // Therefore, results of further computations based on base snapshots of changed documents can't be invalidated by - // incoming events updating the content of out-of-sync documents. - // - // If in past we concluded that a document is out-of-sync, attempt to check one more time before we block apply. - // The source file content might have been updated since the last time we checked. - // - // TODO (investigate): https://github.com/dotnet/roslyn/issues/38866 - // It is possible that the result of Rude Edit semantic analysis of an unchanged document will change if there - // another document is updated. If we encounter a significant case of this we should consider caching such a result per project, - // rather then per document. Also, we might be observing an older semantics if the document that is causing the change is out-of-sync -- - // e.g. the binary was built with an overload C.M(object), but a generator updated class C to also contain C.M(string), - // which change we have not observed yet. Then call-sites of C.M in a changed document observed by the analysis will be seen as C.M(object) - // instead of the true C.M(string). - - var (changedDocumentAnalyses, documentDiagnostics, hasOutOfSyncChangedDocument) = - await AnalyzeDocumentsAsync(solution, documentDifferences, solutionActiveStatementSpanProvider, cancellationToken).ConfigureAwait(false); - - if (documentDiagnostics.Any()) - { // The diagnostic hasn't been reported by GetDocumentDiagnosticsAsync since out-of-sync documents are likely to be synchronized // before the changes are attempted to be applied. If we still have any out-of-sync documents we report warnings and ignore changes in them. // If in future the file is updated so that its content matches the PDB checksum, the document transitions to a matching state, // and we consider any further changes to it for application. - diagnostics.Add(new(newProject.Id, documentDiagnostics)); - - if (documentDiagnostics.Any(d => d.Severity == DiagnosticSeverity.Error)) + if (projectDiagnostics.Any(static d => d.IsDocumentReadError())) { - blockUpdates = hadDocumentReadError = true; + blockUpdates = true; } - } - if (hasOutOfSyncChangedDocument) - { - // The project is considered stale as long as it has at least one document that is out-of-sync. - // Treat the project the same as if it hasn't been built. We won't produce delta for it until it gets rebuilt. - Log.Write($"Changes not applied to {newProject.Name} '{newProject.FilePath}': binaries not up-to-date"); + if (hasOutOfSyncChangedDocument) + { + // The project is considered stale as long as it has at least one document that is out-of-sync. + // Treat the project the same as if it hasn't been built. We won't produce delta for it until it gets rebuilt. + Log.Write($"Changes not applied to {newProject.Name} '{newProject.FilePath}': binaries not up-to-date"); - projectsToStale.Add(newProject.Id); - UpdateChangedDocumentsStaleness(isStale: true); + projectsToStale.Add(newProject.Id); + UpdateChangedDocumentsStaleness(isStale: true); - continue; - } + continue; + } - UpdateChangedDocumentsStaleness(isStale: false); + UpdateChangedDocumentsStaleness(isStale: false); - foreach (var changedDocumentAnalysis in changedDocumentAnalyses) - { - if (changedDocumentAnalysis.SyntaxError != null) + foreach (var changedDocumentAnalysis in changedDocumentAnalyses) { - // only remember the first syntax error we encounter: - syntaxError ??= changedDocumentAnalysis.SyntaxError; + if (changedDocumentAnalysis.SyntaxError != null) + { + // only remember the first syntax error we encounter: + syntaxError ??= changedDocumentAnalysis.SyntaxError; - Log.Write($"Changed document '{changedDocumentAnalysis.FilePath}' has syntax error: {changedDocumentAnalysis.SyntaxError}"); - } - else if (changedDocumentAnalysis.HasChanges) - { - Log.Write($"Document changed, added, or deleted: '{changedDocumentAnalysis.FilePath}'"); - } + Log.Write($"Changed document '{changedDocumentAnalysis.FilePath}' has syntax error: {changedDocumentAnalysis.SyntaxError}"); + } + else if (changedDocumentAnalysis.HasChanges) + { + Log.Write($"Document changed, added, or deleted: '{changedDocumentAnalysis.FilePath}'"); + } - Telemetry.LogAnalysisTime(changedDocumentAnalysis.ElapsedTime); - } + Telemetry.LogAnalysisTime(changedDocumentAnalysis.ElapsedTime); + } - var projectSummary = GetProjectAnalysisSummary(changedDocumentAnalyses); - Log.Write($"Project summary for {newProject.Name} '{newProject.FilePath}': {projectSummary}"); + var projectSummary = GetProjectAnalysisSummary(changedDocumentAnalyses); + Log.Write($"Project summary for {newProject.Name} '{newProject.FilePath}': {projectSummary}"); - if (projectSummary is ProjectAnalysisSummary.NoChanges or ProjectAnalysisSummary.ValidInsignificantChanges) - { - continue; - } - - // The capability of a module to apply edits may change during edit session if the user attaches debugger to - // an additional process that doesn't support EnC (or detaches from such process). Before we apply edits - // we need to check with the debugger. - var (moduleDiagnostics, isModuleLoaded) = await GetModuleDiagnosticsAsync(mvid, oldProject, newProject, changedDocumentAnalyses, cancellationToken).ConfigureAwait(false); + if (projectSummary is ProjectAnalysisSummary.NoChanges or ProjectAnalysisSummary.ValidInsignificantChanges) + { + continue; + } - var isModuleEncBlocked = isModuleLoaded && !moduleDiagnostics.IsEmpty; - if (isModuleEncBlocked) - { - diagnostics.Add(new(newProject.Id, moduleDiagnostics)); - blockUpdates = true; - } + // The capability of a module to apply edits may change during edit session if the user attaches debugger to + // an additional process that doesn't support EnC (or detaches from such process). Before we apply edits + // we need to check with the debugger. + var moduleBlockingDiagnosticId = await ReportModuleDiagnosticsAsync(mvid, oldProject, newProject, changedDocumentAnalyses, projectDiagnostics, cancellationToken).ConfigureAwait(false); + var isModuleEncBlocked = moduleBlockingDiagnosticId != null; - if (projectSummary is ProjectAnalysisSummary.SyntaxErrors or ProjectAnalysisSummary.RudeEdits) - { - blockUpdates = true; - } + if (isModuleEncBlocked) + { + blockUpdates = true; + } - // Report rude edit diagnostics - these can be blocking (errors) or non-blocking (warnings): - foreach (var analysis in changedDocumentAnalyses) - { - if (!analysis.RudeEdits.IsEmpty) + if (projectSummary is ProjectAnalysisSummary.SyntaxErrors or ProjectAnalysisSummary.RudeEdits) { - documentsWithRudeEdits.Add(new(analysis.DocumentId, analysis.RudeEdits)); - Telemetry.LogRudeEditDiagnostics(analysis.RudeEdits, newProject.State.Attributes.TelemetryId); + blockUpdates = true; } - } - if (isModuleEncBlocked || projectSummary != ProjectAnalysisSummary.ValidChanges) - { - Telemetry.LogProjectAnalysisSummary(projectSummary, newProject.State.ProjectInfo.Attributes.TelemetryId, moduleDiagnostics.NullToEmpty().SelectAsArray(d => d.Descriptor.Id)); + // Report rude edit diagnostics - these can be blocking (errors) or non-blocking (warnings): + foreach (var analysis in changedDocumentAnalyses) + { + if (!analysis.RudeEdits.IsEmpty) + { + var document = await solution.GetDocumentAsync(analysis.DocumentId, includeSourceGenerated: true, cancellationToken).ConfigureAwait(false); + var tree = (document != null) ? await document.GetRequiredSyntaxTreeAsync(cancellationToken).ConfigureAwait(false) : null; - await LogDocumentChangesAsync(generation: null, cancellationToken).ConfigureAwait(false); - continue; - } + foreach (var rudeEdit in analysis.RudeEdits) + { + projectDiagnostics.Add(rudeEdit.ToDiagnostic(tree)); + } - var oldCompilation = await oldProject.GetCompilationAsync(cancellationToken).ConfigureAwait(false); - Contract.ThrowIfNull(oldCompilation); + Telemetry.LogRudeEditDiagnostics(analysis.RudeEdits, newProject.State.Attributes.TelemetryId); + } + } - var projectBaselines = DebuggingSession.GetOrCreateEmitBaselines(mvid, oldProject, oldCompilation, out var createBaselineErrors, out var baselineAccessLock); - if (!createBaselineErrors.IsEmpty) - { - // Report diagnosics even when the module is never going to be loaded (e.g. in multi-targeting scenario, where only one framework being debugged). - // This is consistent with reporting compilation errors - the IDE reports them for all TFMs regardless of what framework the app is running on. - diagnostics.Add(new(newProject.Id, createBaselineErrors)); - Telemetry.LogProjectAnalysisSummary(projectSummary, newProject.State.ProjectInfo.Attributes.TelemetryId, createBaselineErrors); + if (isModuleEncBlocked || projectSummary != ProjectAnalysisSummary.ValidChanges) + { + Telemetry.LogProjectAnalysisSummary(projectSummary, newProject.State.ProjectInfo.Attributes.TelemetryId, projectDiagnostics); - blockUpdates = true; - await LogDocumentChangesAsync(generation: null, cancellationToken).ConfigureAwait(false); - continue; - } + await LogDocumentChangesAsync(generation: null, cancellationToken).ConfigureAwait(false); + continue; + } - Contract.ThrowIfTrue(projectBaselines.IsEmpty); + var oldCompilation = await oldProject.GetCompilationAsync(cancellationToken).ConfigureAwait(false); + Contract.ThrowIfNull(oldCompilation); - Log.Write($"Emitting update of {newProject.Name} '{newProject.FilePath}': project not built"); + var projectBaselines = DebuggingSession.GetOrCreateEmitBaselines(mvid, oldProject, oldCompilation, projectDiagnostics, out var baselineAccessLock); + if (projectBaselines.IsEmpty) + { + // Report diagnosics even when the module is never going to be loaded (e.g. in multi-targeting scenario, where only one framework being debugged). + // This is consistent with reporting compilation errors - the IDE reports them for all TFMs regardless of what framework the app is running on. + Telemetry.LogProjectAnalysisSummary(projectSummary, newProject.State.ProjectInfo.Attributes.TelemetryId, projectDiagnostics); - var newCompilation = await newProject.GetCompilationAsync(cancellationToken).ConfigureAwait(false); + blockUpdates = true; + await LogDocumentChangesAsync(generation: null, cancellationToken).ConfigureAwait(false); + continue; + } - // project must support compilations since it supports EnC - Contract.ThrowIfNull(newCompilation); + Log.Write($"Emitting update of {newProject.Name} '{newProject.FilePath}': project not built"); - var oldActiveStatementsMap = await BaseActiveStatements.GetValueAsync(cancellationToken).ConfigureAwait(false); - var projectChanges = await GetProjectChangesAsync(oldActiveStatementsMap, oldCompilation, newCompilation, oldProject, newProject, changedDocumentAnalyses, cancellationToken).ConfigureAwait(false); + var newCompilation = await newProject.GetCompilationAsync(cancellationToken).ConfigureAwait(false); - // The compiler only uses this predicate to determine if CS7101: "Member 'X' added during the current debug session - // can only be accessed from within its declaring assembly 'Lib'" should be reported. - // Prior to .NET 8 Preview 4 the runtime failed to apply such edits. - // This was fixed in Preview 4 along with support for generics. If we see a generic capability we can disable reporting - // this compiler error. Otherwise, we leave the check as is in order to detect at least some runtime failures on .NET Framework. - // Note that the analysis in the compiler detecting the circumstances under which the runtime fails - // to apply the change has both false positives (flagged generic updates that shouldn't be flagged) and negatives - // (didn't flag cases like https://github.com/dotnet/roslyn/issues/68293). - var capabilities = await Capabilities.GetValueAsync(cancellationToken).ConfigureAwait(false); - var requiredCapabilities = projectChanges.RequiredCapabilities.ToStringArray(); + // project must support compilations since it supports EnC + Contract.ThrowIfNull(newCompilation); - var isAddedSymbolPredicate = capabilities.HasFlag(EditAndContinueCapabilities.GenericAddMethodToExistingType) ? - static _ => false : (Func)projectChanges.AddedSymbols.Contains; + var oldActiveStatementsMap = await BaseActiveStatements.GetValueAsync(cancellationToken).ConfigureAwait(false); + var projectChanges = await GetProjectChangesAsync(oldActiveStatementsMap, oldCompilation, newCompilation, oldProject, newProject, changedDocumentAnalyses, cancellationToken).ConfigureAwait(false); - var emitDiagnostics = ImmutableArray.Empty; + // The compiler only uses this predicate to determine if CS7101: "Member 'X' added during the current debug session + // can only be accessed from within its declaring assembly 'Lib'" should be reported. + // Prior to .NET 8 Preview 4 the runtime failed to apply such edits. + // This was fixed in Preview 4 along with support for generics. If we see a generic capability we can disable reporting + // this compiler error. Otherwise, we leave the check as is in order to detect at least some runtime failures on .NET Framework. + // Note that the analysis in the compiler detecting the circumstances under which the runtime fails + // to apply the change has both false positives (flagged generic updates that shouldn't be flagged) and negatives + // (didn't flag cases like https://github.com/dotnet/roslyn/issues/68293). + var capabilities = await Capabilities.GetValueAsync(cancellationToken).ConfigureAwait(false); + var requiredCapabilities = projectChanges.RequiredCapabilities.ToStringArray(); - foreach (var projectBaseline in projectBaselines) - { - await LogDocumentChangesAsync(projectBaseline.Generation + 1, cancellationToken).ConfigureAwait(false); + var isAddedSymbolPredicate = capabilities.HasFlag(EditAndContinueCapabilities.GenericAddMethodToExistingType) ? + static _ => false : (Func)projectChanges.AddedSymbols.Contains; - using var pdbStream = SerializableBytes.CreateWritableStream(); - using var metadataStream = SerializableBytes.CreateWritableStream(); - using var ilStream = SerializableBytes.CreateWritableStream(); + foreach (var projectBaseline in projectBaselines) + { + await LogDocumentChangesAsync(projectBaseline.Generation + 1, cancellationToken).ConfigureAwait(false); - EmitDifferenceResult emitResult; + using var pdbStream = SerializableBytes.CreateWritableStream(); + using var metadataStream = SerializableBytes.CreateWritableStream(); + using var ilStream = SerializableBytes.CreateWritableStream(); - // The lock protects underlying baseline readers from being disposed while emitting delta. - // If the lock is disposed at this point the session has been incorrectly disposed while operations on it are in progress. - using (baselineAccessLock.DisposableRead()) - { - DebuggingSession.ThrowIfDisposed(); + EmitDifferenceResult emitResult; - var emitDifferenceTimer = SharedStopwatch.StartNew(); + // The lock protects underlying baseline readers from being disposed while emitting delta. + // If the lock is disposed at this point the session has been incorrectly disposed while operations on it are in progress. + using (baselineAccessLock.DisposableRead()) + { + DebuggingSession.ThrowIfDisposed(); - emitResult = newCompilation.EmitDifference( - projectBaseline.EmitBaseline, - projectChanges.SemanticEdits, - isAddedSymbolPredicate, - metadataStream, - ilStream, - pdbStream, - new EmitDifferenceOptions() { EmitFieldRva = capabilities.HasFlag(EditAndContinueCapabilities.AddFieldRva) }, - cancellationToken); + var emitDifferenceTimer = SharedStopwatch.StartNew(); - Telemetry.LogEmitDifferenceTime(emitDifferenceTimer.Elapsed); - } + emitResult = newCompilation.EmitDifference( + projectBaseline.EmitBaseline, + projectChanges.SemanticEdits, + isAddedSymbolPredicate, + metadataStream, + ilStream, + pdbStream, + new EmitDifferenceOptions() { EmitFieldRva = capabilities.HasFlag(EditAndContinueCapabilities.AddFieldRva) }, + cancellationToken); - // TODO: https://github.com/dotnet/roslyn/issues/36061 - // We should only report diagnostics from emit phase. - // Syntax and semantic diagnostics are already reported by the diagnostic analyzer. - // Currently we do not have means to distinguish between diagnostics reported from compilation and emit phases. - // Querying diagnostics of the entire compilation or just the updated files migth be slow. - // In fact, it is desirable to allow emitting deltas for symbols affected by the change while allowing untouched - // method bodies to have errors. - if (!emitResult.Diagnostics.IsEmpty) - { - diagnostics.Add(new(newProject.Id, emitResult.Diagnostics)); - } + Telemetry.LogEmitDifferenceTime(emitDifferenceTimer.Elapsed); + } - if (!emitResult.Success) - { - // error - blockUpdates = hasEmitErrors = true; - emitDiagnostics = emitResult.Diagnostics; - break; - } + // TODO: https://github.com/dotnet/roslyn/issues/36061 + // We should only report diagnostics from emit phase. + // Syntax and semantic diagnostics are already reported by the diagnostic analyzer. + // Currently we do not have means to distinguish between diagnostics reported from compilation and emit phases. + // Querying diagnostics of the entire compilation or just the updated files migth be slow. + // In fact, it is desirable to allow emitting deltas for symbols affected by the change while allowing untouched + // method bodies to have errors. + if (!emitResult.Diagnostics.IsEmpty) + { + projectDiagnostics.AddRange(emitResult.Diagnostics); + } - Contract.ThrowIfNull(emitResult.Baseline); + if (!emitResult.Success) + { + // error + blockUpdates = hasEmitErrors = true; + break; + } - var unsupportedChangesDiagnostic = await GetUnsupportedChangesDiagnosticAsync(emitResult, cancellationToken).ConfigureAwait(false); - if (unsupportedChangesDiagnostic is not null) - { - emitDiagnostics = [unsupportedChangesDiagnostic]; - diagnostics.Add(new(newProject.Id, emitDiagnostics)); - blockUpdates = true; - break; - } + Contract.ThrowIfNull(emitResult.Baseline); - var updatedMethodTokens = emitResult.UpdatedMethods.SelectAsArray(h => MetadataTokens.GetToken(h)); - var changedTypeTokens = emitResult.ChangedTypes.SelectAsArray(h => MetadataTokens.GetToken(h)); - - // Determine all active statements whose span changed and exception region span deltas. - GetActiveStatementAndExceptionRegionSpans( - projectBaseline.ModuleId, - oldActiveStatementsMap, - updatedMethodTokens, - NonRemappableRegions, - projectChanges.ActiveStatementChanges, - out var activeStatementsInUpdatedMethods, - out var moduleNonRemappableRegions, - out var exceptionRegionUpdates); - - var delta = new ManagedHotReloadUpdate( - projectBaseline.ModuleId, - newCompilation.AssemblyName ?? newProject.Name, // used for display in debugger diagnostics - newProject.Id, - ilStream.ToImmutableArray(), - metadataStream.ToImmutableArray(), - pdbStream.ToImmutableArray(), - changedTypeTokens, - requiredCapabilities, - updatedMethodTokens, - projectChanges.LineChanges, - activeStatementsInUpdatedMethods, - exceptionRegionUpdates); - - deltas.Add(delta); - - nonRemappableRegions.Add((mvid, moduleNonRemappableRegions)); - newProjectBaselines.Add(new ProjectBaseline(mvid, projectBaseline.ProjectId, emitResult.Baseline, projectBaseline.Generation + 1)); - - var fileLog = Log.FileLog; - if (fileLog != null) - { - await LogDeltaFilesAsync(fileLog, delta, projectBaseline.Generation, oldProject, newProject, cancellationToken).ConfigureAwait(false); + var unsupportedChangesDiagnostic = await GetUnsupportedChangesDiagnosticAsync(emitResult, cancellationToken).ConfigureAwait(false); + if (unsupportedChangesDiagnostic is not null) + { + projectDiagnostics.Add(unsupportedChangesDiagnostic); + blockUpdates = true; + break; + } + + var updatedMethodTokens = emitResult.UpdatedMethods.SelectAsArray(h => MetadataTokens.GetToken(h)); + var changedTypeTokens = emitResult.ChangedTypes.SelectAsArray(h => MetadataTokens.GetToken(h)); + + // Determine all active statements whose span changed and exception region span deltas. + GetActiveStatementAndExceptionRegionSpans( + projectBaseline.ModuleId, + oldActiveStatementsMap, + updatedMethodTokens, + NonRemappableRegions, + projectChanges.ActiveStatementChanges, + out var activeStatementsInUpdatedMethods, + out var moduleNonRemappableRegions, + out var exceptionRegionUpdates); + + var delta = new ManagedHotReloadUpdate( + projectBaseline.ModuleId, + newCompilation.AssemblyName ?? newProject.Name, // used for display in debugger diagnostics + newProject.Id, + ilStream.ToImmutableArray(), + metadataStream.ToImmutableArray(), + pdbStream.ToImmutableArray(), + changedTypeTokens, + requiredCapabilities, + updatedMethodTokens, + projectChanges.LineChanges, + activeStatementsInUpdatedMethods, + exceptionRegionUpdates); + + deltas.Add(delta); + + nonRemappableRegions.Add((mvid, moduleNonRemappableRegions)); + newProjectBaselines.Add(new ProjectBaseline(mvid, projectBaseline.ProjectId, emitResult.Baseline, projectBaseline.Generation + 1)); + + var fileLog = Log.FileLog; + if (fileLog != null) + { + await LogDeltaFilesAsync(fileLog, delta, projectBaseline.Generation, oldProject, newProject, cancellationToken).ConfigureAwait(false); + } } - } - Telemetry.LogProjectAnalysisSummary(projectSummary, newProject.State.ProjectInfo.Attributes.TelemetryId, emitDiagnostics); + Telemetry.LogProjectAnalysisSummary(projectSummary, newProject.State.ProjectInfo.Attributes.TelemetryId, projectDiagnostics); - async ValueTask LogDocumentChangesAsync(int? generation, CancellationToken cancellationToken) - { - var fileLog = Log.FileLog; - if (fileLog != null) + async ValueTask LogDocumentChangesAsync(int? generation, CancellationToken cancellationToken) { - foreach (var changedDocumentAnalysis in changedDocumentAnalyses) + var fileLog = Log.FileLog; + if (fileLog != null) { - if (changedDocumentAnalysis.HasChanges) + foreach (var changedDocumentAnalysis in changedDocumentAnalyses) { - var oldDocument = await oldProject.GetDocumentAsync(changedDocumentAnalysis.DocumentId, includeSourceGenerated: true, cancellationToken).ConfigureAwait(false); - var newDocument = await newProject.GetDocumentAsync(changedDocumentAnalysis.DocumentId, includeSourceGenerated: true, cancellationToken).ConfigureAwait(false); - await fileLog.WriteDocumentChangeAsync(oldDocument, newDocument, updateId, generation, cancellationToken).ConfigureAwait(false); + if (changedDocumentAnalysis.HasChanges) + { + var oldDocument = await oldProject.GetDocumentAsync(changedDocumentAnalysis.DocumentId, includeSourceGenerated: true, cancellationToken).ConfigureAwait(false); + var newDocument = await newProject.GetDocumentAsync(changedDocumentAnalysis.DocumentId, includeSourceGenerated: true, cancellationToken).ConfigureAwait(false); + await fileLog.WriteDocumentChangeAsync(oldDocument, newDocument, updateId, generation, cancellationToken).ConfigureAwait(false); + } } } } } + finally + { + if (!projectDiagnostics.IsEmpty) + { + diagnosticBuilders.Add(newProject.Id, projectDiagnostics); + projectDiagnostics = ArrayBuilder.GetInstance(); + } + } } // Report stale document updates. @@ -1236,7 +1231,7 @@ async ValueTask LogDocumentChangesAsync(int? generation, CancellationToken cance { var descriptor = EditAndContinueDiagnosticDescriptors.GetDescriptor(EditAndContinueErrorCode.UpdatingDocumentInStaleProject); var diagnostic = Diagnostic.Create(descriptor, Location.Create(documentPath, textSpan: default, lineSpan: default), [documentPath]); - diagnostics.Add(new ProjectDiagnostics(documentId.ProjectId, [diagnostic])); + diagnosticBuilders.MultiAdd(documentId.ProjectId, diagnostic); } } } @@ -1247,12 +1242,13 @@ async ValueTask LogDocumentChangesAsync(int? generation, CancellationToken cance Telemetry.LogRuntimeCapabilities(await Capabilities.GetValueAsync(cancellationToken).ConfigureAwait(false)); } + var diagnostics = diagnosticBuilders.SelectAsArray(entry => new ProjectDiagnostics(entry.Key, entry.Value.ToImmutableAndFree())); + var update = blockUpdates ? SolutionUpdate.Empty( - diagnostics.ToImmutable(), - documentsWithRudeEdits.ToImmutable(), + diagnostics, syntaxError, - syntaxError != null || hasEmitErrors || hadDocumentReadError ? ModuleUpdateStatus.Blocked : ModuleUpdateStatus.RestartRequired) + syntaxError != null || hasEmitErrors ? ModuleUpdateStatus.Blocked : ModuleUpdateStatus.RestartRequired) : new SolutionUpdate( new ModuleUpdates( (deltas.Count > 0) ? ModuleUpdateStatus.Ready : ModuleUpdateStatus.None, @@ -1260,8 +1256,7 @@ async ValueTask LogDocumentChangesAsync(int? generation, CancellationToken cance projectsToStale.ToImmutable(), nonRemappableRegions.ToImmutable(), newProjectBaselines.ToImmutable(), - diagnostics.ToImmutable(), - documentsWithRudeEdits.ToImmutable(), + diagnostics, syntaxError); return update; @@ -1270,6 +1265,10 @@ async ValueTask LogDocumentChangesAsync(int? generation, CancellationToken cance { throw ExceptionUtilities.Unreachable(); } + finally + { + projectDiagnostics.Free(); + } bool LogException(Exception e) { diff --git a/src/Features/Core/Portable/EditAndContinue/EditSessionTelemetry.cs b/src/Features/Core/Portable/EditAndContinue/EditSessionTelemetry.cs index d2ead3388ee92..ac85a90fbf59a 100644 --- a/src/Features/Core/Portable/EditAndContinue/EditSessionTelemetry.cs +++ b/src/Features/Core/Portable/EditAndContinue/EditSessionTelemetry.cs @@ -84,11 +84,19 @@ public void LogEmitDifferenceTime(TimeSpan span) public void LogAnalysisTime(TimeSpan span) => _analysisTime += span; - public void LogProjectAnalysisSummary(ProjectAnalysisSummary summary, Guid projectTelemetryId, ImmutableArray errorsIds) + public void LogProjectAnalysisSummary(ProjectAnalysisSummary summary, Guid projectTelemetryId, IEnumerable diagnostics) { lock (_guard) { - _emitErrorIds.AddRange(errorsIds); + var hasError = false; + foreach (var diagnostic in diagnostics) + { + if (!diagnostic.IsEncDiagnostic() && diagnostic.Severity == DiagnosticSeverity.Error) + { + _emitErrorIds.Add(diagnostic.Id); + hasError = true; + } + } switch (summary) { @@ -106,7 +114,7 @@ public void LogProjectAnalysisSummary(ProjectAnalysisSummary summary, Guid proje case ProjectAnalysisSummary.ValidChanges: _hadValidChanges = true; - if (errorsIds.IsEmpty && _projectsWithValidDelta.Count < MaxReportedProjectIds) + if (!hasError && _projectsWithValidDelta.Count < MaxReportedProjectIds) { _projectsWithValidDelta.Add(projectTelemetryId); } @@ -123,9 +131,6 @@ public void LogProjectAnalysisSummary(ProjectAnalysisSummary summary, Guid proje } } - public void LogProjectAnalysisSummary(ProjectAnalysisSummary summary, Guid projectTelemetryId, ImmutableArray emitDiagnostics) - => LogProjectAnalysisSummary(summary, projectTelemetryId, emitDiagnostics.SelectAsArray(d => d.Severity == DiagnosticSeverity.Error, d => d.Id)); - public void LogRudeEditDiagnostics(ImmutableArray diagnostics, Guid projectTelemetryId) { lock (_guard) diff --git a/src/Features/Core/Portable/EditAndContinue/EmitSolutionUpdateResults.cs b/src/Features/Core/Portable/EditAndContinue/EmitSolutionUpdateResults.cs index 5478af5286b7b..d14fc1fa0f274 100644 --- a/src/Features/Core/Portable/EditAndContinue/EmitSolutionUpdateResults.cs +++ b/src/Features/Core/Portable/EditAndContinue/EmitSolutionUpdateResults.cs @@ -26,9 +26,6 @@ internal readonly struct Data [DataMember] public required ImmutableArray Diagnostics { get; init; } - [DataMember] - public required ImmutableArray RudeEdits { get; init; } - [DataMember] public required DiagnosticData? SyntaxError { get; init; } @@ -42,14 +39,20 @@ internal ImmutableArray GetAllDiagnostics() { using var _ = ArrayBuilder.GetInstance(out var builder); - // Add semantic and lowering diagnostics reported during delta emit: - foreach (var diagnostic in Diagnostics) { - builder.Add(diagnostic.ToHotReloadDiagnostic(ModuleUpdates.Status, isRudeEdit: false)); - } + var severity = diagnostic.Severity switch + { + DiagnosticSeverity.Error => EditAndContinueDiagnosticDescriptors.IsEncDiagnostic(diagnostic.Id) ? ManagedHotReloadDiagnosticSeverity.RestartRequired : ManagedHotReloadDiagnosticSeverity.Error, + DiagnosticSeverity.Warning => ManagedHotReloadDiagnosticSeverity.Warning, + _ => default + }; - // Add syntax error: + if (severity != default) + { + builder.Add(diagnostic.ToHotReloadDiagnostic(severity)); + } + } if (SyntaxError != null) { @@ -66,13 +69,6 @@ internal ImmutableArray GetAllDiagnostics() fileSpan.Span.ToSourceSpan())); } - // Report all rude edits. - - foreach (var data in RudeEdits) - { - builder.Add(data.ToHotReloadDiagnostic(ModuleUpdates.Status, isRudeEdit: true)); - } - return builder.ToImmutableAndClear(); } } @@ -82,7 +78,6 @@ internal ImmutableArray GetAllDiagnostics() Solution = null, ModuleUpdates = new ModuleUpdates(ModuleUpdateStatus.None, []), Diagnostics = [], - RudeEdits = [], SyntaxError = null, ProjectsToRestart = ImmutableDictionary>.Empty, ProjectsToRebuild = [], @@ -100,12 +95,11 @@ internal ImmutableArray GetAllDiagnostics() public required ModuleUpdates ModuleUpdates { get; init; } /// - /// Reported diagnostics, other than rude edits, per project. - /// May contain multiple entries for the same project. + /// Reported diagnostics per project. + /// At most one set of diagnostics per project. /// public required ImmutableArray Diagnostics { get; init; } - public required ImmutableArray RudeEdits { get; init; } public required Diagnostic? SyntaxError { get; init; } /// @@ -126,7 +120,6 @@ public Data Dehydrate() { ModuleUpdates = ModuleUpdates, Diagnostics = [], - RudeEdits = [], SyntaxError = null, ProjectsToRestart = ImmutableDictionary>.Empty, ProjectsToRebuild = [], @@ -135,7 +128,6 @@ public Data Dehydrate() { ModuleUpdates = ModuleUpdates, Diagnostics = Diagnostics.ToDiagnosticData(Solution), - RudeEdits = RudeEdits.ToDiagnosticData(Solution), SyntaxError = GetSyntaxErrorData(), ProjectsToRestart = ProjectsToRestart, ProjectsToRebuild = ProjectsToRebuild, @@ -168,17 +160,17 @@ public Data Dehydrate() internal static void GetProjectsToRebuildAndRestart( Solution solution, ModuleUpdates moduleUpdates, - ArrayBuilder rudeEdits, + ImmutableArray diagnostics, ImmutableDictionary runningProjects, out ImmutableDictionary> projectsToRestart, out ImmutableArray projectsToRebuild) { - Debug.Assert(!rudeEdits.HasDuplicates(d => d.ProjectId)); - Debug.Assert(rudeEdits.Select(re => re.ProjectId).IsSorted()); + Debug.Assert(!diagnostics.HasDuplicates(d => d.ProjectId)); + Debug.Assert(diagnostics.Select(re => re.ProjectId).IsSorted()); - // Projects with blocking rude edits should not have updates: - Debug.Assert(rudeEdits - .Where(r => r.Diagnostics.HasBlockingRudeEdits()) + // Projects with errors (including blocking rude edits) should not have updates: + Debug.Assert(diagnostics + .Where(r => r.Diagnostics.Any(static d => d.Severity == DiagnosticSeverity.Error)) .Select(r => r.ProjectId) .Intersect(moduleUpdates.Updates.Select(u => u.ProjectId)) .IsEmpty()); @@ -207,12 +199,9 @@ internal static void GetProjectsToRebuildAndRestart( using var _4 = ArrayBuilder<(ProjectId projectWithRudeEdits, ImmutableArray impactedRunningProjects)>.GetInstance(out var impactedRunningProjectMap); using var _5 = ArrayBuilder.GetInstance(out var impactedRunningProjects); - for (var i = 0; i < rudeEdits.Count; i++) + foreach (var (projectId, projectDiagnostics) in diagnostics) { - var (projectId, projectDiagnostics) = rudeEdits[i]; - - var hasBlocking = projectDiagnostics.HasBlockingRudeEdits(); - var hasNoEffect = projectDiagnostics.HasNoEffectRudeEdits(); + ClassifyRudeEdits(projectDiagnostics, out var hasBlocking, out var hasNoEffect); if (!hasBlocking && !hasNoEffect) { continue; @@ -356,47 +345,82 @@ void AddImpactedRunningProjects(ArrayBuilder impactedProjects, Projec } } + private static void ClassifyRudeEdits(ImmutableArray diagnostics, out bool blocking, out bool noEffect) + { + noEffect = false; + blocking = false; + + foreach (var diagnostic in diagnostics) + { + noEffect |= diagnostic.IsNoEffectDiagnostic(); + blocking |= diagnostic.IsEncDiagnostic() && diagnostic.Severity == DiagnosticSeverity.Error; + + if (noEffect && blocking) + { + return; + } + } + } + public ImmutableArray GetAllDiagnostics() { - using var _ = ArrayBuilder.GetInstance(out var diagnostics); + using var _ = ArrayBuilder.GetInstance(out var result); - // add semantic and lowering diagnostics reported during delta emit: foreach (var (_, projectEmitDiagnostics) in Diagnostics) { - diagnostics.AddRange(projectEmitDiagnostics); + result.AddRange(projectEmitDiagnostics); } - // add syntax error: if (SyntaxError != null) { - diagnostics.Add(SyntaxError); + result.Add(SyntaxError); } - // add rude edits: - foreach (var (_, projectEmitDiagnostics) in RudeEdits) + return result.ToImmutableAndClear(); + } + + /// + /// Returns all diagnostics that can be addressed by rebuilding/restarting the project. + /// + public ImmutableArray<(ProjectId projectId, ImmutableArray diagnostics)> GetTransientDiagnostics() + { + using var _ = ArrayBuilder<(ProjectId projectId, ImmutableArray diagnostics)>.GetInstance(out var result); + + foreach (var (projectId, diagnostics) in Diagnostics) { - diagnostics.AddRange(projectEmitDiagnostics); + var transientDiagnostics = diagnostics.WhereAsArray(static d => d.IsEncDiagnostic()); + if (transientDiagnostics.Length > 0) + { + result.Add((projectId, transientDiagnostics)); + } } - return diagnostics.ToImmutableAndClear(); + return result.ToImmutable(); } - public ImmutableArray GetAllCompilationDiagnostics() + /// + /// Returns all diagnostics that can't be addressed by rebuilding/restarting the project. + /// + public ImmutableArray GetPersistentDiagnostics() { - using var _ = ArrayBuilder.GetInstance(out var diagnostics); + using var _ = ArrayBuilder.GetInstance(out var result); - // add semantic and lowering diagnostics reported during delta emit: - foreach (var (_, projectEmitDiagnostics) in Diagnostics) + foreach (var (_, diagnostics) in Diagnostics) { - diagnostics.AddRange(projectEmitDiagnostics); + foreach (var diagnostic in diagnostics) + { + if (!diagnostic.IsEncDiagnostic()) + { + result.AddRange(diagnostics); + } + } } - // add syntax error: if (SyntaxError != null) { - diagnostics.Add(SyntaxError); + result.Add(SyntaxError); } - return diagnostics.ToImmutableAndClear(); + return result.ToImmutableAndClear(); } } diff --git a/src/Features/Core/Portable/EditAndContinue/IEditAndContinueSessionTracker.cs b/src/Features/Core/Portable/EditAndContinue/IEditAndContinueSessionTracker.cs index 25086909a4bd9..922e0095c446a 100644 --- a/src/Features/Core/Portable/EditAndContinue/IEditAndContinueSessionTracker.cs +++ b/src/Features/Core/Portable/EditAndContinue/IEditAndContinueSessionTracker.cs @@ -19,9 +19,9 @@ internal interface IEditAndContinueSessionTracker /// /// Diagnostics reported by the last call. - /// Includes emit errors and issues reported by the debugger when applying changes. + /// Includes emit errors, project level errors, project level rude edits and issues reported by the debugger when applying changes. /// Does not include rude edits reported for added or changed documents, which are reported by , - /// Incldues rude edits reported for deleted documents. + /// Includes rude edits reported for deleted documents. /// ImmutableArray ApplyChangesDiagnostics { get; } } diff --git a/src/Features/Core/Portable/EditAndContinue/Remote/RemoteDebuggingSessionProxy.cs b/src/Features/Core/Portable/EditAndContinue/Remote/RemoteDebuggingSessionProxy.cs index 6ec4de320e5e9..4e45681a6d66a 100644 --- a/src/Features/Core/Portable/EditAndContinue/Remote/RemoteDebuggingSessionProxy.cs +++ b/src/Features/Core/Portable/EditAndContinue/Remote/RemoteDebuggingSessionProxy.cs @@ -78,7 +78,6 @@ await client.TryInvokeAsync( { ModuleUpdates = new ModuleUpdates(ModuleUpdateStatus.RestartRequired, []), Diagnostics = [], - RudeEdits = [], SyntaxError = null, ProjectsToRebuild = [], ProjectsToRestart = ImmutableDictionary>.Empty, @@ -90,7 +89,6 @@ await client.TryInvokeAsync( { ModuleUpdates = new ModuleUpdates(ModuleUpdateStatus.RestartRequired, []), Diagnostics = GetInternalErrorDiagnosticData(e.Message), - RudeEdits = [], SyntaxError = null, ProjectsToRebuild = [], ProjectsToRestart = ImmutableDictionary>.Empty, diff --git a/src/Features/Core/Portable/EditAndContinue/RudeEditDiagnostic.cs b/src/Features/Core/Portable/EditAndContinue/RudeEditDiagnostic.cs index d422e1f99f7a7..34e38bee9de28 100644 --- a/src/Features/Core/Portable/EditAndContinue/RudeEditDiagnostic.cs +++ b/src/Features/Core/Portable/EditAndContinue/RudeEditDiagnostic.cs @@ -47,27 +47,3 @@ internal Diagnostic ToDiagnostic(SyntaxTree? tree) return Diagnostic.Create(descriptor, tree?.GetLocation(Span) ?? Location.None, Arguments); } } - -internal static class RudeEditExtensions -{ - internal static DiagnosticSeverity GetSeverity(this RudeEditKind kind) - => EditAndContinueDiagnosticDescriptors.GetDescriptor(kind).DefaultSeverity; - - internal static bool IsBlocking(this RudeEditKind kind) - => kind.GetSeverity() == DiagnosticSeverity.Error; - - internal static bool IsBlockingRudeEdit(this Diagnostic diagnostic) - => diagnostic.Descriptor.DefaultSeverity == DiagnosticSeverity.Error; - - internal static bool IsNoEffectRudeEdit(this Diagnostic diagnostic) - => EditAndContinueDiagnosticDescriptors.GetRudeEditKind(diagnostic.Id) == RudeEditKind.UpdateMightNotHaveAnyEffect; - - public static bool HasBlockingRudeEdits(this ImmutableArray diagnostics) - => diagnostics.Any(IsBlockingRudeEdit); - - public static bool HasNoEffectRudeEdits(this ImmutableArray diagnostics) - => diagnostics.Any(IsNoEffectRudeEdit); - - public static bool HasBlockingRudeEdits(this ImmutableArray diagnostics) - => diagnostics.Any(static e => e.Kind.IsBlocking()); -} diff --git a/src/Features/Core/Portable/EditAndContinue/RudeEditKind.cs b/src/Features/Core/Portable/EditAndContinue/RudeEditKind.cs index a8d9fcbeda3b2..f7dcd29eb4d39 100644 --- a/src/Features/Core/Portable/EditAndContinue/RudeEditKind.cs +++ b/src/Features/Core/Portable/EditAndContinue/RudeEditKind.cs @@ -7,6 +7,9 @@ namespace Microsoft.CodeAnalysis.EditAndContinue; // TELEMETRY: DO NOT MODIFY ANY ENUM VALUES OF THIS ENUM. // IT WILL BREAK OUR SQM VARIABLE MAPPINGS. +/// +/// Diagnostics reported by . +/// internal enum RudeEditKind : ushort { None = 0, diff --git a/src/Features/Core/Portable/EditAndContinue/SolutionUpdate.cs b/src/Features/Core/Portable/EditAndContinue/SolutionUpdate.cs index 331e59b4682b7..a7b12bed2896a 100644 --- a/src/Features/Core/Portable/EditAndContinue/SolutionUpdate.cs +++ b/src/Features/Core/Portable/EditAndContinue/SolutionUpdate.cs @@ -15,20 +15,19 @@ internal readonly struct SolutionUpdate( ImmutableArray<(Guid ModuleId, ImmutableArray<(ManagedModuleMethodId Method, NonRemappableRegion Region)>)> nonRemappableRegions, ImmutableArray projectBaselines, ImmutableArray diagnostics, - ImmutableArray documentsWithRudeEdits, Diagnostic? syntaxError) { public readonly ModuleUpdates ModuleUpdates = moduleUpdates; public readonly ImmutableArray ProjectsToStale = projectsToStale; public readonly ImmutableArray<(Guid ModuleId, ImmutableArray<(ManagedModuleMethodId Method, NonRemappableRegion Region)>)> NonRemappableRegions = nonRemappableRegions; public readonly ImmutableArray ProjectBaselines = projectBaselines; + + // Diagnostics for projects, unique entries per project. public readonly ImmutableArray Diagnostics = diagnostics; - public readonly ImmutableArray DocumentsWithRudeEdits = documentsWithRudeEdits; public readonly Diagnostic? SyntaxError = syntaxError; public static SolutionUpdate Empty( ImmutableArray diagnostics, - ImmutableArray documentsWithRudeEdits, Diagnostic? syntaxError, ModuleUpdateStatus status) => new( @@ -37,7 +36,6 @@ public static SolutionUpdate Empty( nonRemappableRegions: [], projectBaselines: [], diagnostics, - documentsWithRudeEdits, syntaxError); internal void Log(TraceLog log, UpdateId updateId) @@ -56,18 +54,12 @@ internal void Log(TraceLog log, UpdateId updateId) { foreach (var diagnostic in projectDiagnostics.Diagnostics) { - if (diagnostic.Severity == DiagnosticSeverity.Error) + log.Write($"[{projectDiagnostics.ProjectId.DebugName}]: {diagnostic}", diagnostic.Severity switch { - log.Write($"Project {projectDiagnostics.ProjectId.DebugName} update error: {diagnostic}", LogMessageSeverity.Error); - } - } - } - - foreach (var documentWithRudeEdits in DocumentsWithRudeEdits) - { - foreach (var rudeEdit in documentWithRudeEdits.RudeEdits) - { - log.Write($"Document {documentWithRudeEdits.Id.DebugName} rude edit: {rudeEdit.Kind} {rudeEdit.SyntaxKind}", LogMessageSeverity.Error); + DiagnosticSeverity.Warning => LogMessageSeverity.Warning, + DiagnosticSeverity.Error => LogMessageSeverity.Error, + _ => LogMessageSeverity.Info + }); } } } diff --git a/src/Features/Core/Portable/EditAndContinue/Utilities/Extensions.cs b/src/Features/Core/Portable/EditAndContinue/Utilities/Extensions.cs index 2efe0c1e1def4..5df8e5934181a 100644 --- a/src/Features/Core/Portable/EditAndContinue/Utilities/Extensions.cs +++ b/src/Features/Core/Portable/EditAndContinue/Utilities/Extensions.cs @@ -126,25 +126,14 @@ private static bool IsRazorDesignTimeOnlyDocument(string filePath) => filePath.EndsWith(".razor.g.cs", StringComparison.OrdinalIgnoreCase) || filePath.EndsWith(".cshtml.g.cs", StringComparison.OrdinalIgnoreCase); - public static ManagedHotReloadDiagnostic ToHotReloadDiagnostic(this DiagnosticData data, ModuleUpdateStatus updateStatus, bool isRudeEdit) + public static ManagedHotReloadDiagnostic ToHotReloadDiagnostic(this DiagnosticData data, ManagedHotReloadDiagnosticSeverity severity) { var fileSpan = data.DataLocation.MappedFileSpan; return new( data.Id, data.Message ?? FeaturesResources.Unknown_error_occurred, - isRudeEdit - ? data.DefaultSeverity switch - { - DiagnosticSeverity.Error => ManagedHotReloadDiagnosticSeverity.RestartRequired, - DiagnosticSeverity.Warning => ManagedHotReloadDiagnosticSeverity.Warning, - _ => throw ExceptionUtilities.UnexpectedValue(data.DefaultSeverity) - } - : updateStatus == ModuleUpdateStatus.RestartRequired - ? ManagedHotReloadDiagnosticSeverity.RestartRequired - : (data.Severity == DiagnosticSeverity.Error) - ? ManagedHotReloadDiagnosticSeverity.Error - : ManagedHotReloadDiagnosticSeverity.Warning, + severity, fileSpan.Path ?? "", fileSpan.Span.ToSourceSpan()); } diff --git a/src/Features/Core/Portable/ExternalAccess/Watch/Api/WatchHotReloadService.cs b/src/Features/Core/Portable/ExternalAccess/Watch/Api/WatchHotReloadService.cs index 330331bf71a6b..e3062e52d657e 100644 --- a/src/Features/Core/Portable/ExternalAccess/Watch/Api/WatchHotReloadService.cs +++ b/src/Features/Core/Portable/ExternalAccess/Watch/Api/WatchHotReloadService.cs @@ -143,6 +143,7 @@ public readonly struct Updates2 public readonly Status Status { get; init; } /// + /// Returns all diagnostics that can't be addressed by rebuilding/restarting the project. /// Syntactic, semantic and emit diagnostics. /// /// @@ -151,7 +152,8 @@ public readonly struct Updates2 public required ImmutableArray CompilationDiagnostics { get; init; } /// - /// Rude edits per project. + /// Transient diagnostics (rude edits) per project. + /// All diagnostics that can be addressed by rebuilding/restarting the project. /// public required ImmutableArray<(ProjectId project, ImmutableArray diagnostics)> RudeEdits { get; init; } @@ -315,8 +317,8 @@ public async Task GetUpdatesAsync(Solution solution, ImmutableDictiona ModuleUpdateStatus.Blocked => Status.Blocked, _ => throw ExceptionUtilities.UnexpectedValue(results.ModuleUpdates.Status) }, - CompilationDiagnostics = results.GetAllCompilationDiagnostics(), - RudeEdits = results.RudeEdits.SelectAsArray(static re => (re.ProjectId, re.Diagnostics)), + CompilationDiagnostics = results.GetPersistentDiagnostics(), + RudeEdits = results.GetTransientDiagnostics(), ProjectUpdates = results.ModuleUpdates.Updates.SelectAsArray(static update => new Update( update.Module, update.ProjectId, diff --git a/src/Features/Test/EditAndContinue/EditAndContinueWorkspaceServiceTests.cs b/src/Features/Test/EditAndContinue/EditAndContinueWorkspaceServiceTests.cs index 1d1bf2eaacfca..75393597dae57 100644 --- a/src/Features/Test/EditAndContinue/EditAndContinueWorkspaceServiceTests.cs +++ b/src/Features/Test/EditAndContinue/EditAndContinueWorkspaceServiceTests.cs @@ -596,14 +596,14 @@ public async Task ErrorReadingPdbFile() var document2 = solution.GetDocument(document1.Id); // error not reported here since it might be intermittent and will be reported if the issue persist when applying the update: - var diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); - Assert.Empty(diagnostics); + var docDiagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); + Assert.Empty(docDiagnostics); // an error occurred so we need to call update to determine whether we have changes to apply or not: - var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); - Assert.Equal(ModuleUpdateStatus.Blocked, updates.Status); + var (updates, diagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); + Assert.Equal(ModuleUpdateStatus.RestartRequired, updates.Status); Assert.Empty(updates.Updates); - AssertEx.Equal([$"{project.FilePath}: (0,0)-(0,0): Error ENC1006: {string.Format(FeaturesResources.UnableToReadSourceFileOrPdb, sourceFile.Path)}"], InspectDiagnostics(emitDiagnostics)); + AssertEx.Equal([$"{project.FilePath}: (0,0)-(0,0): Error ENC1006: {string.Format(FeaturesResources.UnableToReadSourceFileOrPdb, sourceFile.Path)}"], InspectDiagnostics(diagnostics)); EndDebuggingSession(debuggingSession); @@ -642,22 +642,24 @@ public async Task ErrorReadingSourceFile() using var fileLock = File.Open(sourceFile.Path, FileMode.Open, FileAccess.Read, FileShare.None); // error not reported here since it might be intermittent and will be reported if the issue persist when applying the update: - var diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); - Assert.Empty(diagnostics); + var docDiagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); + Assert.Empty(docDiagnostics); // an error occurred so we need to call update to determine whether we have changes to apply or not: - var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); - Assert.Equal(ModuleUpdateStatus.Blocked, updates.Status); + var (updates, diagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); + Assert.Equal(ModuleUpdateStatus.RestartRequired, updates.Status); Assert.Empty(updates.Updates); - AssertEx.Equal([$"{document1.Project.FilePath}: (0,0)-(0,0): Error ENC1006: {string.Format(FeaturesResources.UnableToReadSourceFileOrPdb, sourceFile.Path)}"], InspectDiagnostics(emitDiagnostics)); + AssertEx.Equal( + [$"{document1.Project.FilePath}: (0,0)-(0,0): Error ENC1006: {string.Format(FeaturesResources.UnableToReadSourceFileOrPdb, sourceFile.Path)}"], + InspectDiagnostics(diagnostics)); fileLock.Dispose(); // try apply changes again: - (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); + (updates, diagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ModuleUpdateStatus.Ready, updates.Status); Assert.NotEmpty(updates.Updates); - Assert.Empty(emitDiagnostics); + Assert.Empty(diagnostics); debuggingSession.DiscardSolutionUpdate(); EndDebuggingSession(debuggingSession); @@ -1048,15 +1050,15 @@ public async Task RudeEdits(bool breakMode) solution = solution.WithDocumentText(document1.Id, CreateText(source2)); var document2 = solution.GetDocument(document1.Id); - var diagnostics1 = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); - AssertEx.Equal(["ENC0110: " + string.Format(FeaturesResources.Changing_the_signature_of_0_requires_restarting_the_application_because_it_is_not_supported_by_the_runtime, FeaturesResources.method)], - diagnostics1.Select(d => $"{d.Id}: {d.GetMessage()}")); + var docDiagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); + AssertEx.Equal(["ENC0110: Error: " + string.Format(FeaturesResources.Changing_the_signature_of_0_requires_restarting_the_application_because_it_is_not_supported_by_the_runtime, FeaturesResources.method)], + InspectDiagnostics(docDiagnostics)); // validate solution update status and emit: - var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); + var (updates, diagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ModuleUpdateStatus.RestartRequired, updates.Status); Assert.Empty(updates.Updates); - Assert.Empty(emitDiagnostics); + AssertEx.SequenceEqual(["ENC0110"], InspectDiagnosticIds(diagnostics)); if (breakMode) { @@ -1189,14 +1191,14 @@ class C { int Y => 2; } var generatedDocument = (await solution.Projects.Single().GetSourceGeneratedDocumentsAsync()).Single(); - var diagnostics1 = await service.GetDocumentDiagnosticsAsync(generatedDocument, s_noActiveSpans, CancellationToken.None); - AssertEx.Equal(["ENC0110: " + string.Format(FeaturesResources.Changing_the_signature_of_0_requires_restarting_the_application_because_it_is_not_supported_by_the_runtime, FeaturesResources.method)], - diagnostics1.Select(d => $"{d.Id}: {d.GetMessage()}")); + var docDiagnostics = await service.GetDocumentDiagnosticsAsync(generatedDocument, s_noActiveSpans, CancellationToken.None); + AssertEx.Equal(["ENC0110: Error: " + string.Format(FeaturesResources.Changing_the_signature_of_0_requires_restarting_the_application_because_it_is_not_supported_by_the_runtime, FeaturesResources.method)], + InspectDiagnostics(docDiagnostics)); - var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); + var (updates, diagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ModuleUpdateStatus.RestartRequired, updates.Status); Assert.Empty(updates.Updates); - Assert.Empty(emitDiagnostics); + AssertEx.Equal(["ENC0110"], InspectDiagnosticIds(diagnostics)); EndDebuggingSession(debuggingSession); } @@ -1240,11 +1242,11 @@ public async Task RudeEdits_DocumentOutOfSync(bool breakMode) var document2 = solution.GetDocument(documentId); // no Rude Edits, since the document is out-of-sync - var diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); - Assert.Empty(diagnostics); + var docDiagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); + Assert.Empty(docDiagnostics); // the document is out-of-sync, so no rude edits reported: - var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); + var (updates, diagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ModuleUpdateStatus.None, updates.Status); Assert.Empty(updates.Updates); @@ -1255,30 +1257,30 @@ public async Task RudeEdits_DocumentOutOfSync(bool breakMode) // We don't check if the content on disk has been updated to match either. // Document state can only be reset via UpdateBaselines. sourceFile.WriteAllText(source0, Encoding.UTF8); - diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); - Assert.Empty(diagnostics); + docDiagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); + Assert.Empty(docDiagnostics); // rebuild triggers reload of out-of-sync file content: moduleId = EmitAndLoadLibraryToDebuggee(projectId, source0, sourceFilePath: sourceFile.Path); debuggingSession.UpdateBaselines(solution.WithDocumentText(documentId, CreateText(source0)), [projectId]); - (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); + (updates, diagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ModuleUpdateStatus.RestartRequired, updates.Status); Assert.Empty(updates.Updates); - Assert.Empty(emitDiagnostics); + AssertEx.SequenceEqual(["ENC0110"], InspectDiagnosticIds(diagnostics)); // now we see the rude edit: - diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); + docDiagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Equal( [ - "ENC0110: " + string.Format(FeaturesResources.Changing_the_signature_of_0_requires_restarting_the_application_because_it_is_not_supported_by_the_runtime, FeaturesResources.method) + "ENC0110: Error: " + string.Format(FeaturesResources.Changing_the_signature_of_0_requires_restarting_the_application_because_it_is_not_supported_by_the_runtime, FeaturesResources.method) ], - diagnostics.Select(d => $"{d.Id}: {d.GetMessage()}")); + InspectDiagnostics(docDiagnostics)); - (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); + (updates, diagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ModuleUpdateStatus.RestartRequired, updates.Status); Assert.Empty(updates.Updates); - Assert.Empty(emitDiagnostics); + AssertEx.SequenceEqual(["ENC0110"], InspectDiagnosticIds(diagnostics)); if (breakMode) { @@ -1341,16 +1343,16 @@ public async Task RudeEdits_DocumentWithoutSequencePoints() var document2 = solution.Projects.Single().Documents.Single(); // Rude Edits reported: - var diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); + var docDiagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Equal( - ["ENC0023: " + string.Format(FeaturesResources.Adding_an_abstract_0_or_overriding_an_inherited_0_requires_restarting_the_application, FeaturesResources.method)], - diagnostics.Select(d => $"{d.Id}: {d.GetMessage()}")); + ["ENC0023: Error: " + string.Format(FeaturesResources.Adding_an_abstract_0_or_overriding_an_inherited_0_requires_restarting_the_application, FeaturesResources.method)], + InspectDiagnostics(docDiagnostics)); // validate solution update status and emit: - var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); + var (updates, diagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ModuleUpdateStatus.RestartRequired, updates.Status); Assert.Empty(updates.Updates); - Assert.Empty(emitDiagnostics); + AssertEx.SequenceEqual(["ENC0023"], InspectDiagnosticIds(diagnostics)); EndDebuggingSession(debuggingSession); } @@ -1384,29 +1386,29 @@ public async Task RudeEdits_DelayLoadedModule() var document2 = solution.Projects.Single().Documents.Single(); // Rude Edits reported: - var diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); + var docDiagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Equal( - ["ENC0110: " + string.Format(FeaturesResources.Changing_the_signature_of_0_requires_restarting_the_application_because_it_is_not_supported_by_the_runtime, FeaturesResources.method)], - diagnostics.Select(d => $"{d.Id}: {d.GetMessage()}")); + ["ENC0110: Error: " + string.Format(FeaturesResources.Changing_the_signature_of_0_requires_restarting_the_application_because_it_is_not_supported_by_the_runtime, FeaturesResources.method)], + InspectDiagnostics(docDiagnostics)); - var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); + var (updates, diagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ModuleUpdateStatus.RestartRequired, updates.Status); Assert.Empty(updates.Updates); - Assert.Empty(emitDiagnostics); + AssertEx.SequenceEqual(["ENC0110"], InspectDiagnosticIds(diagnostics)); // load library to the debuggee: LoadLibraryToDebuggee(moduleId); // Rude Edits still reported: - diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); + docDiagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Equal( - ["ENC0110: " + string.Format(FeaturesResources.Changing_the_signature_of_0_requires_restarting_the_application_because_it_is_not_supported_by_the_runtime, FeaturesResources.method)], - diagnostics.Select(d => $"{d.Id}: {d.GetMessage()}")); + ["ENC0110: Error: " + string.Format(FeaturesResources.Changing_the_signature_of_0_requires_restarting_the_application_because_it_is_not_supported_by_the_runtime, FeaturesResources.method)], + InspectDiagnostics(docDiagnostics)); - (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); + (updates, diagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ModuleUpdateStatus.RestartRequired, updates.Status); Assert.Empty(updates.Updates); - Assert.Empty(emitDiagnostics); + AssertEx.SequenceEqual(["ENC0110"], InspectDiagnosticIds(diagnostics)); EndDebuggingSession(debuggingSession); } @@ -1466,8 +1468,8 @@ public async Task RudeEdits_UpdateBaseline(bool validChangeBeforeRudeEdit) // Rude Edits reported: var diagnostics = await service.GetDocumentDiagnosticsAsync(solution.GetRequiredDocument(documentId), s_noActiveSpans, CancellationToken.None); AssertEx.Equal( - ["ENC0023: " + string.Format(FeaturesResources.Adding_an_abstract_0_or_overriding_an_inherited_0_requires_restarting_the_application, FeaturesResources.method)], - diagnostics.Select(d => $"{d.Id}: {d.GetMessage()}")); + ["ENC0023: Error: " + string.Format(FeaturesResources.Adding_an_abstract_0_or_overriding_an_inherited_0_requires_restarting_the_application, FeaturesResources.method)], + InspectDiagnostics(diagnostics)); // validate solution update status and emit: result = await debuggingSession.EmitSolutionUpdateAsync(solution, runningProjects, s_noActiveSpans, CancellationToken.None); @@ -1766,7 +1768,7 @@ public async Task HasChanges_Documents(TextDocumentKind documentKind) AssertEx.Equal([generatedDocumentId], await EditSession.GetChangedDocumentsAsync(log, oldSolution.GetProject(projectId), solution.GetProject(projectId), CancellationToken.None).ToImmutableArrayAsync(CancellationToken.None)); - var diagnostics = new ArrayBuilder(); + var diagnostics = new ArrayBuilder(); await EditSession.GetDocumentDifferencesAsync(log, oldSolution.GetProject(projectId), solution.GetProject(projectId), documentDifferences, diagnostics, CancellationToken.None); Assert.Empty(diagnostics); Assert.Empty(documentDifferences.Deleted); @@ -1932,9 +1934,9 @@ public async Task HasChanges_SourceGeneratorFailure() // No changed source documents since the generator failed: AssertEx.Empty(await EditSession.GetChangedDocumentsAsync(log, oldProject, project, CancellationToken.None).ToImmutableArrayAsync(CancellationToken.None)); - var diagnostics = new ArrayBuilder(); + var diagnostics = new ArrayBuilder(); await EditSession.GetDocumentDifferencesAsync(log, oldProject, project, documentDiffences, diagnostics, CancellationToken.None); - Assert.Contains("System.InvalidOperationException: Source generator failed", diagnostics.Single().Diagnostics.Single().GetMessage()); + Assert.Contains("System.InvalidOperationException: Source generator failed", diagnostics.Single().GetMessage()); AssertEx.Empty(documentDiffences.ChangedOrAdded); AssertEx.Equal(["generated.cs"], documentDiffences.Deleted.Select(d => d.Name)); @@ -2926,14 +2928,14 @@ void F() {} .WithDocumentText(documentBId, CreateText(sourceB2)); // Rude Edit reported: - var diagnostics = await service.GetDocumentDiagnosticsAsync(solution.GetRequiredDocument(documentBId), s_noActiveSpans, CancellationToken.None); + var docDiagnostics = await service.GetDocumentDiagnosticsAsync(solution.GetRequiredDocument(documentBId), s_noActiveSpans, CancellationToken.None); AssertEx.Equal( - ["ENC0023: " + string.Format(FeaturesResources.Adding_an_abstract_0_or_overriding_an_inherited_0_requires_restarting_the_application, FeaturesResources.method)], - diagnostics.Select(d => $"{d.Id}: {d.GetMessage()}")); + ["ENC0023: Error: " + string.Format(FeaturesResources.Adding_an_abstract_0_or_overriding_an_inherited_0_requires_restarting_the_application, FeaturesResources.method)], + InspectDiagnostics(docDiagnostics)); // validate solution update status and emit: - var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); - Assert.Empty(emitDiagnostics); + var (updates, diagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); + AssertEx.SequenceEqual(["ENC0023"], InspectDiagnosticIds(diagnostics)); Assert.Equal(ModuleUpdateStatus.RestartRequired, updates.Status); // TODO: https://github.com/dotnet/roslyn/issues/78244 @@ -3018,7 +3020,7 @@ static B() var diagnostics = await service.GetDocumentDiagnosticsAsync(solution.GetRequiredDocument(documentBId), s_noActiveSpans, CancellationToken.None); AssertEx.Equal( ["ENC0118: Warning: " + string.Format(FeaturesResources.Changing_0_might_not_have_any_effect_until_the_application_is_restarted, FeaturesResources.static_constructor)], - diagnostics.Select(d => $"{d.Id}: {d.Severity}: {d.GetMessage()}")); + InspectDiagnostics(diagnostics)); // TODO: Set RestartWhenChangesHaveNoEffect=true and AllowPartialUpdate=true // https://github.com/dotnet/roslyn/issues/78244 @@ -3032,7 +3034,7 @@ static B() AssertEx.SetEqual([], result.ProjectsToRestart.Select(p => p.Key.DebugName)); var updates = result.ModuleUpdates; - Assert.Empty(result.Diagnostics); + AssertEx.SequenceEqual(["ENC0118"], InspectDiagnosticIds(result.Diagnostics.ToDiagnosticData(solution))); Assert.Equal(ModuleUpdateStatus.Ready, updates.Status); // check emitted delta: @@ -4371,12 +4373,12 @@ int F() solution = solution.WithDocumentText(document.Id, CreateText(source2)); document = solution.GetDocument(document.Id); - var diagnostics = await service.GetDocumentDiagnosticsAsync(document, s_noActiveSpans, CancellationToken.None); - AssertEx.Equal(["ENC0063: " + string.Format(FeaturesResources.Updating_a_0_around_an_active_statement_requires_restarting_the_application, CSharpFeaturesResources.catch_clause)], - diagnostics.Select(d => $"{d.Id}: {d.GetMessage()}")); + var docDiagnostics = await service.GetDocumentDiagnosticsAsync(document, s_noActiveSpans, CancellationToken.None); + AssertEx.Equal(["ENC0063: Error: " + string.Format(FeaturesResources.Updating_a_0_around_an_active_statement_requires_restarting_the_application, CSharpFeaturesResources.catch_clause)], + InspectDiagnostics(docDiagnostics)); - var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); - Assert.Empty(emitDiagnostics); + var (updates, diagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); + AssertEx.SequenceEqual(["ENC0063"], InspectDiagnosticIds(diagnostics)); Assert.Equal(ModuleUpdateStatus.RestartRequired, updates.Status); // undo the change @@ -4388,12 +4390,12 @@ int F() // change the source (now a valid edit since there is no active statement) solution = solution.WithDocumentText(document.Id, CreateText(source2)); - diagnostics = await service.GetDocumentDiagnosticsAsync(document, s_noActiveSpans, CancellationToken.None); - Assert.Empty(diagnostics); + docDiagnostics = await service.GetDocumentDiagnosticsAsync(document, s_noActiveSpans, CancellationToken.None); + Assert.Empty(docDiagnostics); // validate solution update status and emit (Hot Reload change): - (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); - Assert.Empty(emitDiagnostics); + (updates, diagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); + Assert.Empty(diagnostics); Assert.Equal(ModuleUpdateStatus.Ready, updates.Status); debuggingSession.DiscardSolutionUpdate(); diff --git a/src/Features/Test/EditAndContinue/EmitSolutionUpdateResultsTests.cs b/src/Features/Test/EditAndContinue/EmitSolutionUpdateResultsTests.cs index db72d32fd5a77..0c805de7d8ed7 100644 --- a/src/Features/Test/EditAndContinue/EmitSolutionUpdateResultsTests.cs +++ b/src/Features/Test/EditAndContinue/EmitSolutionUpdateResultsTests.cs @@ -49,7 +49,7 @@ private static ManagedHotReloadUpdate CreateMockUpdate(ProjectId projectId) private static ModuleUpdates CreateValidUpdates(params IEnumerable projectIds) => new(ModuleUpdateStatus.Blocked, [.. projectIds.Select(CreateMockUpdate)]); - private static ArrayBuilder CreateProjectRudeEdits(IEnumerable blocking, IEnumerable noEffect) + private static ImmutableArray CreateProjectRudeEdits(IEnumerable blocking, IEnumerable noEffect) => [.. blocking.Select(id => (id, kind: RudeEditKind.InternalError)).Concat(noEffect.Select(id => (id, kind: RudeEditKind.UpdateMightNotHaveAnyEffect))) .GroupBy(e => e.id) .OrderBy(g => g.Key) @@ -139,8 +139,7 @@ public async Task GetHotReloadDiagnostics() var data = new EmitSolutionUpdateResults.Data() { - Diagnostics = diagnostics, - RudeEdits = rudeEdits, + Diagnostics = [.. diagnostics, .. rudeEdits], SyntaxError = syntaxError, ModuleUpdates = new ModuleUpdates(ModuleUpdateStatus.Blocked, Updates: []), ProjectsToRebuild = [], diff --git a/src/Features/Test/EditAndContinue/RemoteEditAndContinueServiceTests.cs b/src/Features/Test/EditAndContinue/RemoteEditAndContinueServiceTests.cs index 8c84333be83a5..a2c51883bcb7d 100644 --- a/src/Features/Test/EditAndContinue/RemoteEditAndContinueServiceTests.cs +++ b/src/Features/Test/EditAndContinue/RemoteEditAndContinueServiceTests.cs @@ -213,7 +213,6 @@ await localWorkspace.ChangeSolutionAsync(localWorkspace.CurrentSolution Solution = solution, ModuleUpdates = updates, Diagnostics = diagnostics, - RudeEdits = [], SyntaxError = syntaxError, ProjectsToRebuild = [project.Id], ProjectsToRestart = ImmutableDictionary>.Empty.Add(project.Id, []), diff --git a/src/Features/TestUtilities/EditAndContinue/EditAndContinueWorkspaceTestBase.cs b/src/Features/TestUtilities/EditAndContinue/EditAndContinueWorkspaceTestBase.cs index 8f62eed06aed2..f1a4b059d5582 100644 --- a/src/Features/TestUtilities/EditAndContinue/EditAndContinueWorkspaceTestBase.cs +++ b/src/Features/TestUtilities/EditAndContinue/EditAndContinueWorkspaceTestBase.cs @@ -234,6 +234,12 @@ internal static IEnumerable InspectDiagnostics(ImmutableArray $"{(string.IsNullOrWhiteSpace(diagnostic.DataLocation.MappedFileSpan.Path) ? diagnostic.ProjectId.ToString() : diagnostic.DataLocation.MappedFileSpan.ToString())}: {diagnostic.Severity} {diagnostic.Id}: {diagnostic.Message}"; + internal static IEnumerable InspectDiagnostics(ImmutableArray actual) + => actual.Select(d => $"{d.Id}: {d.Severity}: {d.GetMessage()}"); + + internal static IEnumerable InspectDiagnosticIds(ImmutableArray actual) + => actual.Select(d => d.Id); + internal static Guid ReadModuleVersionId(Stream stream) { using var peReader = new PEReader(stream); diff --git a/src/Workspaces/Remote/Core/EditAndContinue/ManagedHotReloadLanguageService.cs b/src/Workspaces/Remote/Core/EditAndContinue/ManagedHotReloadLanguageService.cs index 57b6da1ce129a..e99e2980972f1 100644 --- a/src/Workspaces/Remote/Core/EditAndContinue/ManagedHotReloadLanguageService.cs +++ b/src/Workspaces/Remote/Core/EditAndContinue/ManagedHotReloadLanguageService.cs @@ -312,7 +312,6 @@ public async ValueTask GetUpdatesAsync(ImmutableArray> GetDocumentDiagnosticsAsync(Che { ModuleUpdates = new ModuleUpdates(ModuleUpdateStatus.Blocked, []), Diagnostics = GetUnexpectedUpdateError(solution.GetProject(runningProjects.FirstOrDefault().Key) ?? solution.Projects.First(), e.Message), - RudeEdits = [], SyntaxError = null, ProjectsToRebuild = [], ProjectsToRestart = ImmutableDictionary>.Empty, diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/PooledBuilderExtensions.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/PooledBuilderExtensions.cs index be373a34a7009..16acaab1b5384 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/PooledBuilderExtensions.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/PooledBuilderExtensions.cs @@ -93,10 +93,10 @@ public static ImmutableArray ToFlattenedImmutableArrayAndFree(this ArrayBu } } - public static bool HasDuplicates(this ArrayBuilder builder) + public static bool HasDuplicates(this IReadOnlyList builder) => builder.HasDuplicates(static x => x); - public static bool HasDuplicates(this ArrayBuilder builder, Func selector) + public static bool HasDuplicates(this IReadOnlyList builder, Func selector) { switch (builder.Count) { From 6d7591ed43e0f7772eda58452341cba7e1c8916c Mon Sep 17 00:00:00 2001 From: tmat Date: Tue, 27 May 2025 17:46:43 -0700 Subject: [PATCH 2/2] Fixes --- .../EditAndContinue/DebuggingSessionTelemetry.cs | 2 +- .../EditAndContinueDiagnosticDescriptors.cs | 3 +++ .../Portable/EditAndContinue/EditSessionTelemetry.cs | 2 +- .../EditAndContinueWorkspaceServiceTests.cs | 12 ++++++------ .../EmitSolutionUpdateResultsTests.cs | 2 +- 5 files changed, 12 insertions(+), 9 deletions(-) diff --git a/src/Features/Core/Portable/EditAndContinue/DebuggingSessionTelemetry.cs b/src/Features/Core/Portable/EditAndContinue/DebuggingSessionTelemetry.cs index 255cb5b4d1728..30ea313eb36ed 100644 --- a/src/Features/Core/Portable/EditAndContinue/DebuggingSessionTelemetry.cs +++ b/src/Features/Core/Portable/EditAndContinue/DebuggingSessionTelemetry.cs @@ -106,7 +106,7 @@ public static void Log(Data data, Action log, Func map["RudeEditsCount"] = editSessionData.RudeEdits.Length; - // Number of emit errors. + // Number of emit errors. These are any errors only produced during emitting deltas and do not include document analysis errors. map["EmitDeltaErrorIdCount"] = editSessionData.EmitErrorIds.Length; // False for Hot Reload session, true or missing for EnC session (missing in older data that did not have this property). diff --git a/src/Features/Core/Portable/EditAndContinue/EditAndContinueDiagnosticDescriptors.cs b/src/Features/Core/Portable/EditAndContinue/EditAndContinueDiagnosticDescriptors.cs index 646d2e7cd5673..4e11ff963f950 100644 --- a/src/Features/Core/Portable/EditAndContinue/EditAndContinueDiagnosticDescriptors.cs +++ b/src/Features/Core/Portable/EditAndContinue/EditAndContinueDiagnosticDescriptors.cs @@ -257,6 +257,9 @@ public static bool IsNoEffectDiagnostic(this Diagnostic diagnostic) public static bool IsEncDiagnostic(this Diagnostic diagnostic) => IsEncDiagnostic(diagnostic.Id); + public static bool IsRudeEdit(this Diagnostic diagnostic) + => IsRudeEdit(diagnostic.Id); + public static DiagnosticSeverity GetSeverity(this RudeEditKind kind) => GetDescriptor(kind).DefaultSeverity; diff --git a/src/Features/Core/Portable/EditAndContinue/EditSessionTelemetry.cs b/src/Features/Core/Portable/EditAndContinue/EditSessionTelemetry.cs index ac85a90fbf59a..33aad51f75d98 100644 --- a/src/Features/Core/Portable/EditAndContinue/EditSessionTelemetry.cs +++ b/src/Features/Core/Portable/EditAndContinue/EditSessionTelemetry.cs @@ -91,7 +91,7 @@ public void LogProjectAnalysisSummary(ProjectAnalysisSummary summary, Guid proje var hasError = false; foreach (var diagnostic in diagnostics) { - if (!diagnostic.IsEncDiagnostic() && diagnostic.Severity == DiagnosticSeverity.Error) + if (diagnostic.Severity == DiagnosticSeverity.Error && !diagnostic.IsRudeEdit()) { _emitErrorIds.Add(diagnostic.Id); hasError = true; diff --git a/src/Features/Test/EditAndContinue/EditAndContinueWorkspaceServiceTests.cs b/src/Features/Test/EditAndContinue/EditAndContinueWorkspaceServiceTests.cs index 75393597dae57..9d304a5d535a0 100644 --- a/src/Features/Test/EditAndContinue/EditAndContinueWorkspaceServiceTests.cs +++ b/src/Features/Test/EditAndContinue/EditAndContinueWorkspaceServiceTests.cs @@ -518,20 +518,20 @@ public async Task ErrorReadingModuleFile(bool breakMode) var document2 = solution.GetDocument(document1.Id); // error not reported here since it might be intermittent and will be reported if the issue persist when applying the update: - var diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); - Assert.Empty(diagnostics); + var docDiagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); + Assert.Empty(docDiagnostics); - var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); + var (updates, diagnostics1) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ModuleUpdateStatus.RestartRequired, updates.Status); Assert.Empty(updates.Updates); - AssertEx.Equal([$"{document1.Project.FilePath}: (0,0)-(0,0): Error ENC1001: {string.Format(FeaturesResources.ErrorReadingFile, moduleFile.Path, expectedErrorMessage)}"], InspectDiagnostics(emitDiagnostics)); + AssertEx.Equal([$"{document1.Project.FilePath}: (0,0)-(0,0): Error ENC1001: {string.Format(FeaturesResources.ErrorReadingFile, moduleFile.Path, expectedErrorMessage)}"], InspectDiagnostics(diagnostics1)); // correct the error: EmitLibrary(projectId, source2); - var (updates2, emitDiagnostics2) = await EmitSolutionUpdateAsync(debuggingSession, solution); + var (updates2, diagnostics2) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ModuleUpdateStatus.Ready, updates2.Status); - Assert.Empty(emitDiagnostics2); + Assert.Empty(diagnostics2); CommitSolutionUpdate(debuggingSession); diff --git a/src/Features/Test/EditAndContinue/EmitSolutionUpdateResultsTests.cs b/src/Features/Test/EditAndContinue/EmitSolutionUpdateResultsTests.cs index 0c805de7d8ed7..7db22a62b4a0c 100644 --- a/src/Features/Test/EditAndContinue/EmitSolutionUpdateResultsTests.cs +++ b/src/Features/Test/EditAndContinue/EmitSolutionUpdateResultsTests.cs @@ -148,7 +148,7 @@ public async Task GetHotReloadDiagnostics() var actual = data.GetAllDiagnostics(); - AssertEx.Equal( + AssertEx.SetEqual( [ $@"Warning CS0001: {razorPath1} (10,10)-(10,15): warning", $@"Error CS0012: {razorPath2} (10,10)-(10,15): error",