EditAndContinueWorkspaceService.cs 29.7 KB
Newer Older
1 2
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

3 4
#nullable enable

5 6 7 8 9 10 11 12 13 14
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.ErrorReporting;
15
using Microsoft.CodeAnalysis.Host;
16 17 18
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.PooledObjects;
19
using Microsoft.CodeAnalysis.Shared;
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;

namespace Microsoft.CodeAnalysis.EditAndContinue
{
    /// <summary>
    /// Implements core of Edit and Continue orchestration: management of edit sessions and connecting EnC related services.
    /// </summary>
    internal sealed class EditAndContinueWorkspaceService : IEditAndContinueWorkspaceService
    {
        internal static readonly TraceLog Log = new TraceLog(2048, "EnC");

        private readonly Workspace _workspace;
        private readonly IActiveStatementTrackingService _trackingService;
        private readonly IActiveStatementProvider _activeStatementProvider;
        private readonly IDiagnosticAnalyzerService _diagnosticService;
        private readonly IDebuggeeModuleMetadataProvider _debugeeModuleMetadataProvider;
        private readonly EditAndContinueDiagnosticUpdateSource _emitDiagnosticsUpdateSource;
        private readonly EditSessionTelemetry _editSessionTelemetry;
        private readonly DebuggingSessionTelemetry _debuggingSessionTelemetry;
        private readonly ICompilationOutputsProviderService _compilationOutputsProvider;
        private readonly Action<DebuggingSessionTelemetry.Data> _reportTelemetry;

        /// <summary>
        /// A document id is added whenever a diagnostic is reported while in run mode.
        /// These diagnostics are cleared as soon as we enter break mode or the debugging session terminates.
        /// </summary>
        private readonly HashSet<DocumentId> _documentsWithReportedDiagnosticsDuringRunMode;
        private readonly object _documentsWithReportedDiagnosticsDuringRunModeGuard = new object();

50 51 52
        private DebuggingSession? _debuggingSession;
        private EditSession? _editSession;
        private PendingSolutionUpdate? _pendingUpdate;
53 54 55 56 57 58 59 60 61

        internal EditAndContinueWorkspaceService(
            Workspace workspace,
            IActiveStatementTrackingService activeStatementTrackingService,
            ICompilationOutputsProviderService compilationOutputsProvider,
            IDiagnosticAnalyzerService diagnosticService,
            EditAndContinueDiagnosticUpdateSource diagnosticUpdateSource,
            IActiveStatementProvider activeStatementProvider,
            IDebuggeeModuleMetadataProvider debugeeModuleMetadataProvider,
62
            Action<DebuggingSessionTelemetry.Data>? reportTelemetry = null)
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
        {
            _workspace = workspace;
            _diagnosticService = diagnosticService;
            _emitDiagnosticsUpdateSource = diagnosticUpdateSource;
            _activeStatementProvider = activeStatementProvider;
            _debugeeModuleMetadataProvider = debugeeModuleMetadataProvider;
            _trackingService = activeStatementTrackingService;
            _debuggingSessionTelemetry = new DebuggingSessionTelemetry();
            _editSessionTelemetry = new EditSessionTelemetry();
            _documentsWithReportedDiagnosticsDuringRunMode = new HashSet<DocumentId>();
            _compilationOutputsProvider = compilationOutputsProvider;
            _reportTelemetry = reportTelemetry ?? ReportTelemetry;
        }

        // test only:
78
        internal DebuggingSession? Test_GetDebuggingSession() => _debuggingSession;
79 80
        internal EditSession? Test_GetEditSession() => _editSession;
        internal PendingSolutionUpdate? Test_GetPendingSolutionUpdate() => _pendingUpdate;
81 82 83 84

        public bool IsDebuggingSessionInProgress
            => _debuggingSession != null;

85 86 87 88 89 90 91 92 93 94
        public void OnSourceFileUpdated(DocumentId documentId)
        {
            var debuggingSession = _debuggingSession;
            if (debuggingSession != null)
            {
                // fire and forget
                _ = Task.Run(() => debuggingSession.LastCommittedSolution.OnSourceFileUpdatedAsync(documentId, debuggingSession.CancellationToken));
            }
        }

95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
        /// <summary>
        /// Invoked whenever a module instance is loaded to a process being debugged.
        /// </summary>
        public void OnManagedModuleInstanceLoaded(Guid mvid)
            => _editSession?.ModuleInstanceLoadedOrUnloaded(mvid);

        /// <summary>
        /// Invoked whenever a module instance is unloaded from a process being debugged.
        /// </summary>
        public void OnManagedModuleInstanceUnloaded(Guid mvid)
            => _editSession?.ModuleInstanceLoadedOrUnloaded(mvid);

        public void StartDebuggingSession()
        {
            var previousSession = Interlocked.CompareExchange(ref _debuggingSession, new DebuggingSession(_workspace, _debugeeModuleMetadataProvider, _activeStatementProvider, _compilationOutputsProvider), null);
            Contract.ThrowIfFalse(previousSession == null, "New debugging session can't be started until the existing one has ended.");
        }

        public void StartEditSession()
        {
            var debuggingSession = _debuggingSession;
            Contract.ThrowIfNull(debuggingSession, "Edit session can only be started during debugging session");

            var newSession = new EditSession(debuggingSession, _editSessionTelemetry);

            var previousSession = Interlocked.CompareExchange(ref _editSession, newSession, null);
            Contract.ThrowIfFalse(previousSession == null, "New edit session can't be started until the existing one has ended.");

            _trackingService.StartTracking(newSession);

            // clear diagnostics reported during run mode:
            ClearReportedRunModeDiagnostics();
        }

        public void EndEditSession()
        {
            // first, publish null session:
            var session = Interlocked.Exchange(ref _editSession, null);
            Contract.ThrowIfNull(session, "Edit session has not started.");

            // then cancel all ongoing work bound to the session:
            session.Cancel();

            // then clear all reported rude edits:
            _diagnosticService.Reanalyze(_workspace, documentIds: session.GetDocumentsWithReportedDiagnostics());

            _trackingService.EndTracking();

            _debuggingSessionTelemetry.LogEditSession(_editSessionTelemetry.GetDataAndClear());

            session.Dispose();
        }

        public void EndDebuggingSession()
        {
            var debuggingSession = Interlocked.Exchange(ref _debuggingSession, null);
            Contract.ThrowIfNull(debuggingSession, "Debugging session has not started.");

153 154 155
            // cancel all ongoing work bound to the session:
            debuggingSession.Cancel();

156 157 158 159 160 161 162 163 164 165 166
            _reportTelemetry(_debuggingSessionTelemetry.GetDataAndClear());

            // clear emit/apply diagnostics reported previously:
            _emitDiagnosticsUpdateSource.ClearDiagnostics();

            // clear diagnostics reported during run mode:
            ClearReportedRunModeDiagnostics();

            debuggingSession.Dispose();
        }

167 168 169 170 171 172
        internal static bool SupportsEditAndContinue(Project project)
            => project.LanguageServices.GetService<IEditAndContinueAnalyzer>() != null;

        internal static bool IsDesignTimeOnlyDocument(Document document)
            => document.Services.GetService<DocumentPropertiesService>()?.DesignTimeOnly == true;

173 174 175 176 177 178 179 180 181 182
        public async Task<ImmutableArray<Diagnostic>> GetDocumentDiagnosticsAsync(Document document, CancellationToken cancellationToken)
        {
            try
            {
                var debuggingSession = _debuggingSession;
                if (debuggingSession == null)
                {
                    return ImmutableArray<Diagnostic>.Empty;
                }

183
                // Not a C# or VB project.
184
                var project = document.Project;
185 186 187 188 189 190 191
                if (!SupportsEditAndContinue(project))
                {
                    return ImmutableArray<Diagnostic>.Empty;
                }

                // Document does not compile to the assembly (e.g. cshtml files, .g.cs files generated for completion only)
                if (IsDesignTimeOnlyDocument(document) || !document.SupportsSyntaxTree)
192 193 194 195 196 197 198 199 200 201 202 203 204 205
                {
                    return ImmutableArray<Diagnostic>.Empty;
                }

                // Do not analyze documents (and report diagnostics) of projects that have not been built.
                // Allow user to make any changes in these documents, they won't be applied within the current debugging session.
                // Do not report the file read error - it might be an intermittent issue. The error will be reported when the 
                // change is attempted to be applied.
                var (mvid, _) = await debuggingSession.GetProjectModuleIdAsync(project.Id, cancellationToken).ConfigureAwait(false);
                if (mvid == Guid.Empty)
                {
                    return ImmutableArray<Diagnostic>.Empty;
                }

206 207
                var (oldDocument, oldDocumentState) = await debuggingSession.LastCommittedSolution.GetDocumentAndStateAsync(document.Id, cancellationToken).ConfigureAwait(false);
                if (oldDocumentState == CommittedSolution.DocumentState.OutOfSync ||
208
                    oldDocumentState == CommittedSolution.DocumentState.Indeterminate ||
209 210 211 212 213 214 215 216 217
                    oldDocumentState == CommittedSolution.DocumentState.DesignTimeOnly)
                {
                    // Do not report diagnostics for existing out-of-sync documents or design-time-only documents.
                    return ImmutableArray<Diagnostic>.Empty;
                }

                // The document has not changed while the application is running since the last changes were committed:
                var editSession = _editSession;

218 219
                if (editSession == null)
                {
220 221 222 223 224
                    if (document == oldDocument)
                    {
                        return ImmutableArray<Diagnostic>.Empty;
                    }

225 226
                    // Any changes made in loaded, built projects outside of edit session are rude edits (the application is running):
                    var newSyntaxTree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
227 228 229 230
                    Contract.ThrowIfNull(newSyntaxTree);

                    var changedSpans = await GetChangedSpansAsync(oldDocument, newSyntaxTree, cancellationToken).ConfigureAwait(false);
                    return GetRunModeDocumentDiagnostics(document, newSyntaxTree, changedSpans);
231 232
                }

233
                var analysis = await editSession.GetDocumentAnalysis(oldDocument, document).GetValueAsync(cancellationToken).ConfigureAwait(false);
234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249
                if (analysis.HasChanges)
                {
                    // Once we detected a change in a document let the debugger know that the corresponding loaded module
                    // is about to be updated, so that it can start initializing it for EnC update, reducing the amount of time applying
                    // the change blocks the UI when the user "continues".
                    debuggingSession.PrepareModuleForUpdate(mvid);

                    // Check if EnC is allowed for all loaded modules corresponding to the project.
                    var moduleDiagnostics = editSession.GetModuleDiagnostics(mvid, project.Name);

                    if (!moduleDiagnostics.IsEmpty)
                    {
                        // track the document, so that we can refresh or clean diagnostics at the end of edit session:
                        editSession.TrackDocumentWithReportedDiagnostics(document.Id);

                        var newSyntaxTree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
250 251 252
                        Contract.ThrowIfNull(newSyntaxTree);

                        var changedSpans = await GetChangedSpansAsync(oldDocument, newSyntaxTree, cancellationToken).ConfigureAwait(false);
253 254

                        var diagnosticsBuilder = ArrayBuilder<Diagnostic>.GetInstance();
255
                        foreach (var span in changedSpans)
256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287
                        {
                            var location = Location.Create(newSyntaxTree, span);

                            foreach (var diagnostic in moduleDiagnostics)
                            {
                                diagnosticsBuilder.Add(diagnostic.ToDiagnostic(location));
                            }
                        }

                        return diagnosticsBuilder.ToImmutableAndFree();
                    }
                }

                if (analysis.RudeEditErrors.IsEmpty)
                {
                    return ImmutableArray<Diagnostic>.Empty;
                }

                editSession.Telemetry.LogRudeEditDiagnostics(analysis.RudeEditErrors);

                // track the document, so that we can refresh or clean diagnostics at the end of edit session:
                editSession.TrackDocumentWithReportedDiagnostics(document.Id);

                var tree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
                return analysis.RudeEditErrors.SelectAsArray((e, t) => e.ToDiagnostic(t), tree);
            }
            catch (Exception e) when (FatalError.ReportWithoutCrashUnlessCanceled(e))
            {
                return ImmutableArray<Diagnostic>.Empty;
            }
        }

288
        private static async Task<IEnumerable<TextSpan>> GetChangedSpansAsync(Document? oldDocument, SyntaxTree newSyntaxTree, CancellationToken cancellationToken)
289
        {
290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308
            if (oldDocument != null)
            {
                var oldSyntaxTree = await oldDocument.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
                Contract.ThrowIfNull(oldSyntaxTree);

                return GetSpansInNewDocument(await GetDocumentTextChangesAsync(oldSyntaxTree, newSyntaxTree, cancellationToken).ConfigureAwait(false));
            }

            var newRoot = await newSyntaxTree.GetRootAsync(cancellationToken).ConfigureAwait(false);
            return SpecializedCollections.SingletonEnumerable(newRoot.FullSpan);
        }

        private ImmutableArray<Diagnostic> GetRunModeDocumentDiagnostics(Document newDocument, SyntaxTree newSyntaxTree, IEnumerable<TextSpan> changedSpans)
        {
            if (!changedSpans.Any())
            {
                return ImmutableArray<Diagnostic>.Empty;
            }

309 310 311 312 313 314 315
            lock (_documentsWithReportedDiagnosticsDuringRunModeGuard)
            {
                _documentsWithReportedDiagnosticsDuringRunMode.Add(newDocument.Id);
            }

            var descriptor = EditAndContinueDiagnosticDescriptors.GetDescriptor(EditAndContinueErrorCode.ChangesNotAppliedWhileRunning);
            var args = new[] { newDocument.Project.Name };
316
            return changedSpans.SelectAsArray(span => Diagnostic.Create(descriptor, Location.Create(newSyntaxTree, span), args));
317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399
        }

        // internal for testing
        internal static async Task<IList<TextChange>> GetDocumentTextChangesAsync(SyntaxTree oldSyntaxTree, SyntaxTree newSyntaxTree, CancellationToken cancellationToken)
        {
            var list = newSyntaxTree.GetChanges(oldSyntaxTree);
            if (list.Count != 0)
            {
                return list;
            }

            var oldText = await oldSyntaxTree.GetTextAsync(cancellationToken).ConfigureAwait(false);
            var newText = await newSyntaxTree.GetTextAsync(cancellationToken).ConfigureAwait(false);
            if (oldText.ContentEquals(newText))
            {
                return Array.Empty<TextChange>();
            }

            var roList = newText.GetTextChanges(oldText);
            if (roList.Count != 0)
            {
                return roList.ToArray();
            }

            return Array.Empty<TextChange>();
        }

        // internal for testing
        internal static IEnumerable<TextSpan> GetSpansInNewDocument(IEnumerable<TextChange> changes)
        {
            int oldPosition = 0;
            int newPosition = 0;
            foreach (var change in changes)
            {
                if (change.Span.Start < oldPosition)
                {
                    Debug.Fail("Text changes not ordered");
                    yield break;
                }

                if (change.Span.Length == 0 && change.NewText.Length == 0)
                {
                    continue;
                }

                // skip unchanged text:
                newPosition += change.Span.Start - oldPosition;

                yield return new TextSpan(newPosition, change.NewText.Length);

                // apply change:
                oldPosition = change.Span.End;
                newPosition += change.NewText.Length;
            }
        }

        private void ClearReportedRunModeDiagnostics()
        {
            // clear diagnostics reported during run mode:
            ImmutableArray<DocumentId> documentsToReanalyze;
            lock (_documentsWithReportedDiagnosticsDuringRunModeGuard)
            {
                documentsToReanalyze = _documentsWithReportedDiagnosticsDuringRunMode.ToImmutableArray();
                _documentsWithReportedDiagnosticsDuringRunMode.Clear();
            }

            // clear all reported run mode diagnostics:
            _diagnosticService.Reanalyze(_workspace, documentIds: documentsToReanalyze);
        }

        /// <summary>
        /// Determine whether the updates made to projects containing the specified file (or all projects that are built, 
        /// if <paramref name="sourceFilePath"/> is null) are ready to be applied and the debugger should attempt to apply
        /// them on "continue".
        /// </summary>
        /// <returns>
        /// Returns <see cref="SolutionUpdateStatus.Blocked"/> if there are rude edits or other errors 
        /// that block the application of the updates. Might return <see cref="SolutionUpdateStatus.Ready"/> even if there are 
        /// errors in the code that will block the application of the updates. E.g. emit diagnostics can't be determined until 
        /// emit is actually performed. Therefore, this method only serves as an optimization to avoid unnecessary emit attempts,
        /// but does not provide a definitive answer. Only <see cref="EmitSolutionUpdateAsync"/> can definitively determine whether
        /// the update is valid or not.
        /// </returns>
400
        public Task<bool> HasChangesAsync(string? sourceFilePath, CancellationToken cancellationToken)
401 402 403 404 405 406 407
        {
            // GetStatusAsync is called outside of edit session when the debugger is determining 
            // whether a source file checksum matches the one in PDB.
            // The debugger expects no changes in this case.
            var editSession = _editSession;
            if (editSession == null)
            {
408
                return Task.FromResult(false);
409 410
            }

411
            return editSession.HasChangesAsync(_workspace.CurrentSolution, sourceFilePath, cancellationToken);
412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431
        }

        public async Task<(SolutionUpdateStatus Summary, ImmutableArray<Deltas> Deltas)> EmitSolutionUpdateAsync(CancellationToken cancellationToken)
        {
            var editSession = _editSession;
            if (editSession == null)
            {
                return (SolutionUpdateStatus.None, ImmutableArray<Deltas>.Empty);
            }

            var solution = _workspace.CurrentSolution;

            var solutionUpdate = await editSession.EmitSolutionUpdateAsync(solution, cancellationToken).ConfigureAwait(false);

            if (solutionUpdate.Summary == SolutionUpdateStatus.Ready)
            {
                var previousPendingUpdate = Interlocked.Exchange(ref _pendingUpdate, new PendingSolutionUpdate(
                    solution,
                    solutionUpdate.EmitBaselines,
                    solutionUpdate.Deltas,
432
                    solutionUpdate.ModuleReaders));
433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498

                // commit/discard was not called:
                Contract.ThrowIfFalse(previousPendingUpdate == null);
            }

            // clear emit/apply diagnostics reported previously:
            _emitDiagnosticsUpdateSource.ClearDiagnostics();

            // report emit/apply diagnostics:
            foreach (var (projectId, diagnostics) in solutionUpdate.Diagnostics)
            {
                _emitDiagnosticsUpdateSource.ReportDiagnostics(solution, projectId, diagnostics);
            }

            // Note that we may return empty deltas if all updates have been deferred.
            // The debugger will still call commit or discard on the update batch.
            return (solutionUpdate.Summary, solutionUpdate.Deltas);
        }

        public void CommitSolutionUpdate()
        {
            var editSession = _editSession;

            Contract.ThrowIfNull(editSession);

            var pendingUpdate = Interlocked.Exchange(ref _pendingUpdate, null);
            Contract.ThrowIfNull(pendingUpdate);

            editSession.DebuggingSession.CommitSolutionUpdate(pendingUpdate);
            editSession.ChangesApplied();
        }

        public void DiscardSolutionUpdate()
        {
            Contract.ThrowIfNull(_editSession);

            var pendingUpdate = Interlocked.Exchange(ref _pendingUpdate, null);
            Contract.ThrowIfNull(pendingUpdate);

            foreach (var moduleReader in pendingUpdate.ModuleReaders)
            {
                moduleReader.Dispose();
            }
        }

        public async Task<LinePositionSpan?> GetCurrentActiveStatementPositionAsync(ActiveInstructionId instructionId, CancellationToken cancellationToken)
        {
            try
            {
                // It is allowed to call this method before entering or after exiting break mode. In fact, the VS debugger does so. 
                // We return null since there the concept of active statement only makes sense during break mode.
                var editSession = _editSession;
                if (editSession == null)
                {
                    return null;
                }

                // TODO: Avoid enumerating active statements for unchanged documents.
                // We would need to add a document path parameter to be able to find the document we need to check for changes.
                // https://github.com/dotnet/roslyn/issues/24324
                var baseActiveStatements = await editSession.BaseActiveStatements.GetValueAsync(cancellationToken).ConfigureAwait(false);
                if (!baseActiveStatements.InstructionMap.TryGetValue(instructionId, out var baseActiveStatement))
                {
                    return null;
                }

499 500 501 502 503 504 505
                var (oldPrimaryDocument, _) = await editSession.DebuggingSession.LastCommittedSolution.GetDocumentAndStateAsync(baseActiveStatement.PrimaryDocumentId, cancellationToken).ConfigureAwait(false);
                if (oldPrimaryDocument == null)
                {
                    // Can't determine position of an active statement if the document is out-of-sync with loaded module debug information.
                    return null;
                }

506
                var primaryDocument = _workspace.CurrentSolution.GetDocument(baseActiveStatement.PrimaryDocumentId);
507 508 509 510 511 512
                if (primaryDocument == null)
                {
                    // The document has been deleted.
                    return null;
                }

513
                var documentAnalysis = await editSession.GetDocumentAnalysis(oldPrimaryDocument, primaryDocument).GetValueAsync(cancellationToken).ConfigureAwait(false);
514 515 516 517 518 519 520 521 522 523 524 525 526 527 528
                var currentActiveStatements = documentAnalysis.ActiveStatements;
                if (currentActiveStatements.IsDefault)
                {
                    // The document has syntax errors.
                    return null;
                }

                return currentActiveStatements[baseActiveStatement.PrimaryDocumentOrdinal].Span;
            }
            catch (Exception e) when (FatalError.ReportWithoutCrashUnlessCanceled(e))
            {
                return null;
            }
        }

529 530 531 532 533 534 535 536 537
        /// <summary>
        /// Called by the debugger to determine whether an active statement is in an exception region,
        /// so it can determine whether the active statement can be remapped. This only happens when the EnC is about to apply changes.
        /// If the debugger determines we can remap active statements, the application of changes proceeds.
        /// </summary>
        /// <returns>
        /// True if the instruction is located within an exception region, false if it is not, null if the instruction isn't an active statement 
        /// or the exception regions can't be determined.
        /// </returns>
538 539 540 541 542 543 544 545 546 547
        public async Task<bool?> IsActiveStatementInExceptionRegionAsync(ActiveInstructionId instructionId, CancellationToken cancellationToken)
        {
            try
            {
                var editSession = _editSession;
                if (editSession == null)
                {
                    return null;
                }

548 549 550 551
                // This method is only called when the EnC is about to apply changes, at which point all active statements and 
                // their exception regions will be needed. Hence it's not neccessary to scope this query down to just the instruction
                // the debugger is interested at this point while not calculating the others.

552 553 554 555 556 557
                var baseActiveStatements = await editSession.BaseActiveStatements.GetValueAsync(cancellationToken).ConfigureAwait(false);
                if (!baseActiveStatements.InstructionMap.TryGetValue(instructionId, out var baseActiveStatement))
                {
                    return null;
                }

558 559 560 561
                var baseExceptionRegions = (await editSession.GetBaseActiveExceptionRegionsAsync(cancellationToken).ConfigureAwait(false))[baseActiveStatement.Ordinal];

                // If the document is out-of-sync the exception regions can't be determined.
                return baseExceptionRegions.Spans.IsDefault ? (bool?)null : baseExceptionRegions.IsActiveStatementCovered;
562 563 564 565 566 567 568 569 570 571 572 573 574
            }
            catch (Exception e) when (FatalError.ReportWithoutCrashUnlessCanceled(e))
            {
                return null;
            }
        }

        public void ReportApplyChangesException(string message)
        {
            var descriptor = EditAndContinueDiagnosticDescriptors.GetDescriptor(EditAndContinueErrorCode.CannotApplyChangesUnexpectedError);

            _emitDiagnosticsUpdateSource.ReportDiagnostics(
                _workspace.CurrentSolution,
575
                projectId: null,
576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643
                new[] { Diagnostic.Create(descriptor, Location.None, new[] { message }) });
        }

        private static void ReportTelemetry(DebuggingSessionTelemetry.Data data)
        {
            // report telemetry (fire and forget):
            _ = Task.Run(() => LogDebuggingSessionTelemetry(data, Logger.Log, LogAggregator.GetNextId));
        }

        // internal for testing
        internal static void LogDebuggingSessionTelemetry(DebuggingSessionTelemetry.Data debugSessionData, Action<FunctionId, LogMessage> log, Func<int> getNextId)
        {
            const string SessionId = nameof(SessionId);
            const string EditSessionId = nameof(EditSessionId);

            var debugSessionId = getNextId();

            log(FunctionId.Debugging_EncSession, KeyValueLogMessage.Create(map =>
            {
                map[SessionId] = debugSessionId;
                map["SessionCount"] = debugSessionData.EditSessionData.Length;
                map["EmptySessionCount"] = debugSessionData.EmptyEditSessionCount;
            }));

            foreach (var editSessionData in debugSessionData.EditSessionData)
            {
                var editSessionId = getNextId();

                log(FunctionId.Debugging_EncSession_EditSession, KeyValueLogMessage.Create(map =>
                {
                    map[SessionId] = debugSessionId;
                    map[EditSessionId] = editSessionId;

                    map["HadCompilationErrors"] = editSessionData.HadCompilationErrors;
                    map["HadRudeEdits"] = editSessionData.HadRudeEdits;
                    map["HadValidChanges"] = editSessionData.HadValidChanges;
                    map["HadValidInsignificantChanges"] = editSessionData.HadValidInsignificantChanges;

                    map["RudeEditsCount"] = editSessionData.RudeEdits.Length;
                    map["EmitDeltaErrorIdCount"] = editSessionData.EmitErrorIds.Length;
                }));

                foreach (var errorId in editSessionData.EmitErrorIds)
                {
                    log(FunctionId.Debugging_EncSession_EditSession_EmitDeltaErrorId, KeyValueLogMessage.Create(map =>
                    {
                        map[SessionId] = debugSessionId;
                        map[EditSessionId] = editSessionId;
                        map["ErrorId"] = errorId;
                    }));
                }

                foreach (var (editKind, syntaxKind) in editSessionData.RudeEdits)
                {
                    log(FunctionId.Debugging_EncSession_EditSession_RudeEdit, KeyValueLogMessage.Create(map =>
                    {
                        map[SessionId] = debugSessionId;
                        map[EditSessionId] = editSessionId;

                        map["RudeEditKind"] = editKind;
                        map["RudeEditSyntaxKind"] = syntaxKind;
                        map["RudeEditBlocking"] = editSessionData.HadRudeEdits;
                    }));
                }
            }
        }
    }
}