-
Notifications
You must be signed in to change notification settings - Fork 4.1k
/
Copy pathEditSession.cs
1330 lines (1123 loc) · 71.2 KB
/
EditSession.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
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
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
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
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
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
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
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
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
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
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// 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;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Reflection.Metadata.Ecma335;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Contracts.EditAndContinue;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Collections;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.EditAndContinue
{
internal sealed class EditSession
{
internal readonly DebuggingSession DebuggingSession;
internal readonly EditSessionTelemetry Telemetry;
// Maps active statement instructions reported by the debugger to their latest spans that might not yet have been applied
// (remapping not triggered yet). Consumed by the next edit session and updated when changes are committed at the end of the edit session.
//
// Consider a function F containing a call to function G. While G is being executed, F is updated a couple of times (in two edit sessions)
// before the thread returns from G and is remapped to the latest version of F. At the start of the second edit session,
// the active instruction reported by the debugger is still at the original location since function F has not been remapped yet (G has not returned yet).
//
// '>' indicates an active statement instruction for non-leaf frame reported by the debugger.
// v1 - before first edit, G executing
// v2 - after first edit, G still executing
// v3 - after second edit and G returned
//
// F v1: F v2: F v3:
// 0: nop 0: nop 0: nop
// 1> G() 1> nop 1: nop
// 2: nop 2: G() 2: nop
// 3: nop 3: nop 3> G()
//
// When entering a break state we query the debugger for current active statements.
// The returned statements reflect the current state of the threads in the runtime.
// When a change is successfully applied we remember changes in active statement spans.
// These changes are passed to the next edit session.
// We use them to map the spans for active statements returned by the debugger.
//
// In the above case the sequence of events is
// 1st break: get active statements returns (F, v=1, il=1, span1) the active statement is up-to-date
// 1st apply: detected span change for active statement (F, v=1, il=1): span1->span2
// 2nd break: previously updated statements contains (F, v=1, il=1)->span2
// get active statements returns (F, v=1, il=1, span1) which is mapped to (F, v=1, il=1, span2) using previously updated statements
// 2nd apply: detected span change for active statement (F, v=1, il=1): span2->span3
// 3rd break: previously updated statements contains (F, v=1, il=1)->span3
// get active statements returns (F, v=3, il=3, span3) the active statement is up-to-date
//
internal readonly ImmutableDictionary<ManagedMethodId, ImmutableArray<NonRemappableRegion>> NonRemappableRegions;
/// <summary>
/// Gets the capabilities of the runtime with respect to applying code changes.
/// Retrieved lazily from <see cref="DebuggingSession.DebuggerService"/> since they are only needed when changes are detected in the solution.
/// </summary>
internal readonly AsyncLazy<EditAndContinueCapabilities> Capabilities;
/// <summary>
/// Map of base active statements.
/// Calculated lazily based on info retrieved from <see cref="DebuggingSession.DebuggerService"/> since it is only needed when changes are detected in the solution.
/// </summary>
internal readonly AsyncLazy<ActiveStatementsMap> BaseActiveStatements;
/// <summary>
/// Cache of document EnC analyses.
/// </summary>
internal readonly EditAndContinueDocumentAnalysesCache Analyses;
/// <summary>
/// True for Edit and Continue edit sessions - when the application is in break state.
/// False for Hot Reload edit sessions - when the application is running.
/// </summary>
internal readonly bool InBreakState;
/// <summary>
/// A <see cref="DocumentId"/> is added whenever EnC analyzer reports
/// rude edits or module diagnostics. At the end of the session we ask the diagnostic analyzer to reanalyze
/// the documents to clean up the diagnostics.
/// </summary>
private readonly HashSet<DocumentId> _documentsWithReportedDiagnostics = new();
private readonly object _documentsWithReportedDiagnosticsGuard = new();
internal EditSession(
DebuggingSession debuggingSession,
ImmutableDictionary<ManagedMethodId, ImmutableArray<NonRemappableRegion>> nonRemappableRegions,
EditSessionTelemetry telemetry,
AsyncLazy<ActiveStatementsMap>? lazyActiveStatementMap,
bool inBreakState)
{
DebuggingSession = debuggingSession;
NonRemappableRegions = nonRemappableRegions;
Telemetry = telemetry;
InBreakState = inBreakState;
telemetry.SetBreakState(inBreakState);
BaseActiveStatements = lazyActiveStatementMap ?? (inBreakState
? AsyncLazy.Create(GetBaseActiveStatementsAsync)
: new AsyncLazy<ActiveStatementsMap>(ActiveStatementsMap.Empty));
Capabilities = AsyncLazy.Create(GetCapabilitiesAsync);
Analyses = new EditAndContinueDocumentAnalysesCache(BaseActiveStatements, Capabilities);
}
/// <summary>
/// The compiler has various scenarios that will cause it to synthesize things that might not be covered
/// by existing rude edits, but we still need to ensure the runtime supports them before we proceed.
/// </summary>
private async Task<Diagnostic?> GetUnsupportedChangesDiagnosticAsync(EmitDifferenceResult emitResult, CancellationToken cancellationToken)
{
Debug.Assert(emitResult.Success);
Debug.Assert(emitResult.Baseline is not null);
// if there were no changed types then there is nothing to check
if (emitResult.ChangedTypes.Length == 0)
{
return null;
}
var capabilities = await Capabilities.GetValueAsync(cancellationToken).ConfigureAwait(false);
if (!capabilities.HasFlag(EditAndContinueCapabilities.NewTypeDefinition))
{
// If the runtime doesn't support adding new types then we expect every row number for any type that is
// emitted will be less than or equal to the number of rows in the original metadata.
var highestEmittedTypeDefRow = emitResult.ChangedTypes.Max(t => MetadataTokens.GetRowNumber(t));
var highestExistingTypeDefRow = emitResult.Baseline.OriginalMetadata.GetMetadataReader().GetTableRowCount(TableIndex.TypeDef);
if (highestEmittedTypeDefRow > highestExistingTypeDefRow)
{
var descriptor = EditAndContinueDiagnosticDescriptors.GetDescriptor(EditAndContinueErrorCode.AddingTypeRuntimeCapabilityRequired);
return Diagnostic.Create(descriptor, Location.None);
}
}
return null;
}
/// <summary>
/// Errors to be reported when a project is updated but the corresponding module does not support EnC.
/// </summary>
/// <returns><see langword="default"/> if the module is not loaded.</returns>
public async Task<ImmutableArray<Diagnostic>?> GetModuleDiagnosticsAsync(Guid mvid, Project oldProject, Project newProject, ImmutableArray<DocumentAnalysisResults> documentAnalyses, CancellationToken cancellationToken)
{
Contract.ThrowIfTrue(documentAnalyses.IsEmpty);
var availability = await DebuggingSession.DebuggerService.GetAvailabilityAsync(mvid, cancellationToken).ConfigureAwait(false);
if (availability.Status == ManagedHotReloadAvailabilityStatus.ModuleNotLoaded)
{
return null;
}
if (availability.Status == ManagedHotReloadAvailabilityStatus.Available)
{
return ImmutableArray<Diagnostic>.Empty;
}
var descriptor = EditAndContinueDiagnosticDescriptors.GetModuleDiagnosticDescriptor(availability.Status);
var messageArgs = new[] { newProject.Name, availability.LocalizedMessage };
using var _ = ArrayBuilder<Diagnostic>.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.ToImmutable();
}
private static async IAsyncEnumerable<Location> CreateChangedLocationsAsync(Project oldProject, Project newProject, ImmutableArray<DocumentAnalysisResults> documentAnalyses, [EnumeratorCancellation] CancellationToken cancellationToken)
{
var hasRemovedOrAddedDocument = false;
foreach (var documentAnalysis in documentAnalyses)
{
if (!documentAnalysis.HasChanges)
{
continue;
}
var oldDocument = await oldProject.GetDocumentAsync(documentAnalysis.DocumentId, includeSourceGenerated: true, cancellationToken).ConfigureAwait(false);
var newDocument = await newProject.GetDocumentAsync(documentAnalysis.DocumentId, includeSourceGenerated: true, cancellationToken).ConfigureAwait(false);
if (oldDocument == null || newDocument == null)
{
hasRemovedOrAddedDocument = true;
continue;
}
var oldText = await oldDocument.GetValueTextAsync(cancellationToken).ConfigureAwait(false);
var newText = await newDocument.GetValueTextAsync(cancellationToken).ConfigureAwait(false);
var newTree = await newDocument.GetRequiredSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
// document location:
yield return Location.Create(newTree, GetFirstLineDifferenceSpan(oldText, newText));
}
// project location:
if (hasRemovedOrAddedDocument)
{
yield return Location.None;
}
}
private static TextSpan GetFirstLineDifferenceSpan(SourceText oldText, SourceText newText)
{
var oldLineCount = oldText.Lines.Count;
var newLineCount = newText.Lines.Count;
for (var i = 0; i < Math.Min(oldLineCount, newLineCount); i++)
{
var oldLineSpan = oldText.Lines[i].Span;
var newLineSpan = newText.Lines[i].Span;
if (oldLineSpan != newLineSpan || !oldText.GetSubText(oldLineSpan).ContentEquals(newText.GetSubText(newLineSpan)))
{
return newText.Lines[i].Span;
}
}
return (oldLineCount == newLineCount) ? default :
(newLineCount > oldLineCount) ? newText.Lines[oldLineCount].Span :
TextSpan.FromBounds(newText.Lines[newLineCount - 1].End, newText.Lines[newLineCount - 1].EndIncludingLineBreak);
}
private async Task<EditAndContinueCapabilities> GetCapabilitiesAsync(CancellationToken cancellationToken)
{
try
{
var capabilities = await DebuggingSession.DebuggerService.GetCapabilitiesAsync(cancellationToken).ConfigureAwait(false);
return EditAndContinueCapabilitiesParser.Parse(capabilities);
}
catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken))
{
return EditAndContinueCapabilities.Baseline;
}
}
private async Task<ActiveStatementsMap> GetBaseActiveStatementsAsync(CancellationToken cancellationToken)
{
try
{
// Last committed solution reflects the state of the source that is in sync with the binaries that are loaded in the debuggee.
var debugInfos = await DebuggingSession.DebuggerService.GetActiveStatementsAsync(cancellationToken).ConfigureAwait(false);
return ActiveStatementsMap.Create(debugInfos, NonRemappableRegions);
}
catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken))
{
return ActiveStatementsMap.Empty;
}
}
public static async ValueTask<bool> HasChangesAsync(Solution oldSolution, Solution newSolution, string sourceFilePath, CancellationToken cancellationToken)
{
// Note that this path look up does not work for source-generated files:
var newDocumentIds = newSolution.GetDocumentIdsWithFilePath(sourceFilePath);
if (newDocumentIds.IsEmpty)
{
// file does not exist or has been removed:
return !oldSolution.GetDocumentIdsWithFilePath(sourceFilePath).IsEmpty;
}
// it suffices to check the content of one of the document if there are multiple linked ones:
var documentId = newDocumentIds.First();
var oldDocument = oldSolution.GetTextDocument(documentId);
if (oldDocument == null)
{
// file has been added
return true;
}
var newDocument = newSolution.GetRequiredTextDocument(documentId);
return oldDocument != newDocument && !await ContentEqualsAsync(oldDocument, newDocument, cancellationToken).ConfigureAwait(false);
}
public static async ValueTask<bool> HasChangesAsync(Solution oldSolution, Solution newSolution, CancellationToken cancellationToken)
{
if (oldSolution == newSolution)
{
return false;
}
if (oldSolution.ProjectIds.Count != newSolution.ProjectIds.Count)
{
return true;
}
foreach (var newProject in newSolution.Projects)
{
var oldProject = oldSolution.GetProject(newProject.Id);
if (oldProject == null || await HasChangedOrAddedDocumentsAsync(oldProject, newProject, changedOrAddedDocuments: null, cancellationToken).ConfigureAwait(false))
{
return true;
}
}
// The number of projects in both solution is the same and there are no new projects and no changes in existing projects.
// Therefore there are no changes.
return false;
}
private static async ValueTask<bool> ContentEqualsAsync(TextDocument oldDocument, TextDocument newDocument, CancellationToken cancellationToken)
{
// Check if the currently observed document content has changed compared to the base document content.
// This is an important optimization that aims to avoid IO while stepping in sources that have not changed.
//
// We may be comparing out-of-date committed document content but we only make a decision based on that content
// if it matches the current content. If the current content is equal to baseline content that does not match
// the debuggee then the workspace has not observed the change made to the file on disk since baseline was captured
// (there had to be one as the content doesn't match). When we are about to apply changes it is ok to ignore this
// document because the user does not see the change yet in the buffer (if the doc is open) and won't be confused
// if it is not applied yet. The change will be applied later after it's observed by the workspace.
var oldSource = await oldDocument.GetValueTextAsync(cancellationToken).ConfigureAwait(false);
var newSource = await newDocument.GetValueTextAsync(cancellationToken).ConfigureAwait(false);
return oldSource.ContentEquals(newSource);
}
internal static async ValueTask<bool> HasChangedOrAddedDocumentsAsync(Project oldProject, Project newProject, ArrayBuilder<Document>? changedOrAddedDocuments, CancellationToken cancellationToken)
{
if (!newProject.SupportsEditAndContinue())
{
return false;
}
if (oldProject.State == newProject.State)
{
return false;
}
foreach (var documentId in newProject.State.DocumentStates.GetChangedStateIds(oldProject.State.DocumentStates, ignoreUnchangedContent: true))
{
var document = newProject.GetRequiredDocument(documentId);
if (document.State.Attributes.DesignTimeOnly)
{
continue;
}
if (await ContentEqualsAsync(oldProject.GetRequiredDocument(documentId), document, cancellationToken).ConfigureAwait(false))
{
continue;
}
if (changedOrAddedDocuments is null)
{
return true;
}
changedOrAddedDocuments.Add(document);
}
foreach (var documentId in newProject.State.DocumentStates.GetAddedStateIds(oldProject.State.DocumentStates))
{
var document = newProject.GetRequiredDocument(documentId);
if (document.State.Attributes.DesignTimeOnly)
{
continue;
}
if (changedOrAddedDocuments is null)
{
return true;
}
changedOrAddedDocuments.Add(document);
}
// Any changes in non-generated document content might affect source generated documents as well,
// no need to check further in that case.
if (changedOrAddedDocuments is { Count: > 0 })
{
return true;
}
foreach (var documentId in newProject.State.AdditionalDocumentStates.GetChangedStateIds(oldProject.State.AdditionalDocumentStates, ignoreUnchangedContent: true))
{
var document = newProject.GetRequiredAdditionalDocument(documentId);
if (!await ContentEqualsAsync(oldProject.GetRequiredAdditionalDocument(documentId), document, cancellationToken).ConfigureAwait(false))
{
return true;
}
}
foreach (var documentId in newProject.State.AnalyzerConfigDocumentStates.GetChangedStateIds(oldProject.State.AnalyzerConfigDocumentStates, ignoreUnchangedContent: true))
{
var document = newProject.GetRequiredAnalyzerConfigDocument(documentId);
if (!await ContentEqualsAsync(oldProject.GetRequiredAnalyzerConfigDocument(documentId), document, cancellationToken).ConfigureAwait(false))
{
return true;
}
}
// TODO: should handle removed documents above (detect them as edits) https://github.com/dotnet/roslyn/issues/62848
if (newProject.State.DocumentStates.GetRemovedStateIds(oldProject.State.DocumentStates).Any() ||
newProject.State.AdditionalDocumentStates.GetRemovedStateIds(oldProject.State.AdditionalDocumentStates).Any() ||
newProject.State.AdditionalDocumentStates.GetAddedStateIds(oldProject.State.AdditionalDocumentStates).Any() ||
newProject.State.AnalyzerConfigDocumentStates.GetRemovedStateIds(oldProject.State.AnalyzerConfigDocumentStates).Any() ||
newProject.State.AnalyzerConfigDocumentStates.GetAddedStateIds(oldProject.State.AnalyzerConfigDocumentStates).Any())
{
return true;
}
return false;
}
internal static async Task PopulateChangedAndAddedDocumentsAsync(Project oldProject, Project newProject, ArrayBuilder<Document> changedOrAddedDocuments, CancellationToken cancellationToken)
{
changedOrAddedDocuments.Clear();
if (!await HasChangedOrAddedDocumentsAsync(oldProject, newProject, changedOrAddedDocuments, cancellationToken).ConfigureAwait(false))
{
return;
}
cancellationToken.ThrowIfCancellationRequested();
var oldSourceGeneratedDocumentStates = await oldProject.Solution.State.GetSourceGeneratedDocumentStatesAsync(oldProject.State, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
var newSourceGeneratedDocumentStates = await newProject.Solution.State.GetSourceGeneratedDocumentStatesAsync(newProject.State, cancellationToken).ConfigureAwait(false);
foreach (var documentId in newSourceGeneratedDocumentStates.GetChangedStateIds(oldSourceGeneratedDocumentStates, ignoreUnchangedContent: true))
{
var newState = newSourceGeneratedDocumentStates.GetRequiredState(documentId);
if (newState.Attributes.DesignTimeOnly)
{
continue;
}
changedOrAddedDocuments.Add(newProject.GetOrCreateSourceGeneratedDocument(newState));
}
foreach (var documentId in newSourceGeneratedDocumentStates.GetAddedStateIds(oldSourceGeneratedDocumentStates))
{
var newState = newSourceGeneratedDocumentStates.GetRequiredState(documentId);
if (newState.Attributes.DesignTimeOnly)
{
continue;
}
changedOrAddedDocuments.Add(newProject.GetOrCreateSourceGeneratedDocument(newState));
}
}
/// <summary>
/// Enumerates <see cref="DocumentId"/>s of changed (not added or removed) <see cref="Document"/>s (not additional nor analyzer config).
/// </summary>
internal static async IAsyncEnumerable<DocumentId> GetChangedDocumentsAsync(Project oldProject, Project newProject, [EnumeratorCancellation] CancellationToken cancellationToken)
{
Debug.Assert(oldProject.Id == newProject.Id);
if (!newProject.SupportsEditAndContinue() || oldProject.State == newProject.State)
{
yield break;
}
foreach (var documentId in newProject.State.DocumentStates.GetChangedStateIds(oldProject.State.DocumentStates, ignoreUnchangedContent: true))
{
yield return documentId;
}
// Given the following assumptions:
// - source generators are deterministic,
// - metadata references and compilation options have not changed (TODO -- need to check),
// - source documents have not changed,
// - additional documents have not changed,
// - analyzer config documents have not changed,
// the outputs of source generators will not change.
if (!newProject.State.DocumentStates.HasAnyStateChanges(oldProject.State.DocumentStates) &&
!newProject.State.AdditionalDocumentStates.HasAnyStateChanges(oldProject.State.AdditionalDocumentStates) &&
!newProject.State.AnalyzerConfigDocumentStates.HasAnyStateChanges(oldProject.State.AnalyzerConfigDocumentStates))
{
// Based on the above assumption there are no changes in source generated files.
yield break;
}
cancellationToken.ThrowIfCancellationRequested();
var oldSourceGeneratedDocumentStates = await oldProject.Solution.State.GetSourceGeneratedDocumentStatesAsync(oldProject.State, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
var newSourceGeneratedDocumentStates = await newProject.Solution.State.GetSourceGeneratedDocumentStatesAsync(newProject.State, cancellationToken).ConfigureAwait(false);
foreach (var documentId in newSourceGeneratedDocumentStates.GetChangedStateIds(oldSourceGeneratedDocumentStates, ignoreUnchangedContent: true))
{
yield return documentId;
}
}
private async Task<(ImmutableArray<DocumentAnalysisResults> results, ImmutableArray<Diagnostic> diagnostics)> AnalyzeDocumentsAsync(
ArrayBuilder<Document> changedOrAddedDocuments,
ActiveStatementSpanProvider newDocumentActiveStatementSpanProvider,
CancellationToken cancellationToken)
{
using var _1 = ArrayBuilder<Diagnostic>.GetInstance(out var documentDiagnostics);
using var _2 = ArrayBuilder<(Document? oldDocument, Document newDocument)>.GetInstance(out var documents);
foreach (var newDocument in changedOrAddedDocuments)
{
var (oldDocument, oldDocumentState) = await DebuggingSession.LastCommittedSolution.GetDocumentAndStateAsync(newDocument.Id, newDocument, cancellationToken, reloadOutOfSyncDocument: true).ConfigureAwait(false);
switch (oldDocumentState)
{
case CommittedSolution.DocumentState.DesignTimeOnly:
break;
case CommittedSolution.DocumentState.Indeterminate:
case CommittedSolution.DocumentState.OutOfSync:
var descriptor = EditAndContinueDiagnosticDescriptors.GetDescriptor((oldDocumentState == CommittedSolution.DocumentState.Indeterminate) ?
EditAndContinueErrorCode.UnableToReadSourceFileOrPdb : EditAndContinueErrorCode.DocumentIsOutOfSyncWithDebuggee);
documentDiagnostics.Add(Diagnostic.Create(descriptor, Location.Create(newDocument.FilePath!, textSpan: default, lineSpan: default), new[] { newDocument.FilePath }));
break;
case CommittedSolution.DocumentState.MatchesBuildOutput:
// Include the document regardless of whether the module it was built into has been loaded or not.
// If the module has been built it might get loaded later during the debugging session,
// at which point we apply all changes that have been made to the project so far.
documents.Add((oldDocument, newDocument));
break;
default:
throw ExceptionUtilities.UnexpectedValue(oldDocumentState);
}
}
var analyses = await Analyses.GetDocumentAnalysesAsync(DebuggingSession.LastCommittedSolution, documents, newDocumentActiveStatementSpanProvider, cancellationToken).ConfigureAwait(false);
return (analyses, documentDiagnostics.ToImmutable());
}
internal ImmutableArray<DocumentId> GetDocumentsWithReportedDiagnostics()
{
lock (_documentsWithReportedDiagnosticsGuard)
{
return ImmutableArray.CreateRange(_documentsWithReportedDiagnostics);
}
}
internal void TrackDocumentWithReportedDiagnostics(DocumentId documentId)
{
lock (_documentsWithReportedDiagnosticsGuard)
{
_documentsWithReportedDiagnostics.Add(documentId);
}
}
private static ProjectAnalysisSummary GetProjectAnalysisSummary(ImmutableArray<DocumentAnalysisResults> documentAnalyses)
{
var hasChanges = false;
var hasSignificantValidChanges = false;
foreach (var analysis in documentAnalyses)
{
// skip documents that actually were not changed:
if (!analysis.HasChanges)
{
continue;
}
// rude edit detection wasn't completed due to errors that prevent us from analyzing the document:
if (analysis.HasChangesAndSyntaxErrors)
{
return ProjectAnalysisSummary.CompilationErrors;
}
// rude edits detected:
if (!analysis.RudeEditErrors.IsEmpty)
{
return ProjectAnalysisSummary.RudeEdits;
}
hasChanges = true;
hasSignificantValidChanges |= analysis.HasSignificantValidChanges;
}
if (!hasChanges)
{
// we get here if a document is closed and reopen without any actual change:
return ProjectAnalysisSummary.NoChanges;
}
if (!hasSignificantValidChanges)
{
return ProjectAnalysisSummary.ValidInsignificantChanges;
}
return ProjectAnalysisSummary.ValidChanges;
}
internal static async ValueTask<ProjectChanges> GetProjectChangesAsync(
ActiveStatementsMap baseActiveStatements,
Compilation oldCompilation,
Compilation newCompilation,
Project oldProject,
Project newProject,
ImmutableArray<DocumentAnalysisResults> changedDocumentAnalyses,
CancellationToken cancellationToken)
{
try
{
using var _1 = ArrayBuilder<SemanticEditInfo>.GetInstance(out var allEdits);
using var _2 = ArrayBuilder<SequencePointUpdates>.GetInstance(out var allLineEdits);
using var _3 = ArrayBuilder<DocumentActiveStatementChanges>.GetInstance(out var activeStatementsInChangedDocuments);
var analyzer = newProject.Services.GetRequiredService<IEditAndContinueAnalyzer>();
var requiredCapabilities = EditAndContinueCapabilities.None;
foreach (var analysis in changedDocumentAnalyses)
{
if (!analysis.HasSignificantValidChanges)
{
continue;
}
// we shouldn't be asking for deltas in presence of errors:
Contract.ThrowIfTrue(analysis.HasChangesAndErrors);
// Active statements are calculated if document changed and has no syntax errors:
Contract.ThrowIfTrue(analysis.ActiveStatements.IsDefault);
allEdits.AddRange(analysis.SemanticEdits);
allLineEdits.AddRange(analysis.LineEdits);
requiredCapabilities |= analysis.RequiredCapabilities;
if (analysis.ActiveStatements.Length > 0)
{
var oldDocument = await oldProject.GetDocumentAsync(analysis.DocumentId, includeSourceGenerated: true, cancellationToken).ConfigureAwait(false);
var oldActiveStatements = (oldDocument == null) ? ImmutableArray<UnmappedActiveStatement>.Empty :
await baseActiveStatements.GetOldActiveStatementsAsync(analyzer, oldDocument, cancellationToken).ConfigureAwait(false);
activeStatementsInChangedDocuments.Add(new(oldActiveStatements, analysis.ActiveStatements, analysis.ExceptionRegions));
}
}
MergePartialEdits(oldCompilation, newCompilation, allEdits, out var mergedEdits, out var addedSymbols, cancellationToken);
return new ProjectChanges(
mergedEdits,
allLineEdits.ToImmutable(),
addedSymbols,
activeStatementsInChangedDocuments.ToImmutable(),
requiredCapabilities);
}
catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken))
{
throw ExceptionUtilities.Unreachable();
}
}
internal static void MergePartialEdits(
Compilation oldCompilation,
Compilation newCompilation,
IReadOnlyList<SemanticEditInfo> edits,
out ImmutableArray<SemanticEdit> mergedEdits,
out ImmutableHashSet<ISymbol> addedSymbols,
CancellationToken cancellationToken)
{
using var _0 = ArrayBuilder<SemanticEdit>.GetInstance(edits.Count, out var mergedEditsBuilder);
using var _1 = PooledHashSet<ISymbol>.GetInstance(out var addedSymbolsBuilder);
using var _2 = ArrayBuilder<(ISymbol? oldSymbol, ISymbol? newSymbol)>.GetInstance(edits.Count, out var resolvedSymbols);
foreach (var edit in edits)
{
SymbolKeyResolution oldResolution;
if (edit.Kind is SemanticEditKind.Update or SemanticEditKind.Delete)
{
oldResolution = edit.Symbol.Resolve(oldCompilation, ignoreAssemblyKey: true, cancellationToken);
Contract.ThrowIfNull(oldResolution.Symbol);
}
else
{
oldResolution = default;
}
SymbolKeyResolution newResolution;
if (edit.Kind is SemanticEditKind.Update or SemanticEditKind.Insert or SemanticEditKind.Replace)
{
newResolution = edit.Symbol.Resolve(newCompilation, ignoreAssemblyKey: true, cancellationToken);
Contract.ThrowIfNull(newResolution.Symbol);
}
else if (edit.Kind == SemanticEditKind.Delete && edit.DeletedSymbolContainer is not null)
{
// For deletes, we use NewSymbol to reference the containing type of the deleted member
newResolution = edit.DeletedSymbolContainer.Value.Resolve(newCompilation, ignoreAssemblyKey: true, cancellationToken);
Contract.ThrowIfNull(newResolution.Symbol);
}
else
{
newResolution = default;
}
resolvedSymbols.Add((oldResolution.Symbol, newResolution.Symbol));
}
for (var i = 0; i < edits.Count; i++)
{
var edit = edits[i];
if (edit.PartialType == null)
{
var (oldSymbol, newSymbol) = resolvedSymbols[i];
if (edit.Kind == SemanticEditKind.Insert)
{
Contract.ThrowIfNull(newSymbol);
addedSymbolsBuilder.Add(newSymbol);
}
mergedEditsBuilder.Add(new SemanticEdit(
edit.Kind,
oldSymbol: oldSymbol,
newSymbol: newSymbol,
syntaxMap: edit.SyntaxMaps.MatchingNodes,
runtimeRudeEdit: edit.SyntaxMaps.RuntimeRudeEdits));
}
}
// no partial type merging needed:
if (edits.Count == mergedEditsBuilder.Count)
{
mergedEdits = mergedEditsBuilder.ToImmutable();
addedSymbols = addedSymbolsBuilder.ToImmutableHashSet();
return;
}
// Calculate merged syntax map for each partial type symbol:
var symbolKeyComparer = SymbolKey.GetComparer(ignoreCase: false, ignoreAssemblyKeys: true);
var mergedUpdateEditSyntaxMaps = new Dictionary<SymbolKey, (Func<SyntaxNode, SyntaxNode?>? matchingNodes, Func<SyntaxNode, RuntimeRudeEdit?>? runtimeRudeEdits)>(symbolKeyComparer);
var updatesByPartialType = edits
.Where(edit => edit is { PartialType: not null, Kind: SemanticEditKind.Update })
.GroupBy(edit => edit.PartialType!.Value, symbolKeyComparer);
foreach (var partialTypeEdits in updatesByPartialType)
{
Func<SyntaxNode, SyntaxNode?>? mergedMatchingNodes;
Func<SyntaxNode, RuntimeRudeEdit?>? mergedRuntimeRudeEdits;
if (partialTypeEdits.Any(static e => e.SyntaxMaps.HasMap))
{
var newMaps = partialTypeEdits.Where(static edit => edit.SyntaxMaps.HasMap).SelectAsArray(static edit => edit.SyntaxMaps);
mergedMatchingNodes = node => newMaps[newMaps.IndexOf(static (m, node) => m.NewTree == node.SyntaxTree, node)].MatchingNodes!(node);
mergedRuntimeRudeEdits = node => newMaps[newMaps.IndexOf(static (m, node) => m.NewTree == node.SyntaxTree, node)].RuntimeRudeEdits?.Invoke(node);
}
else
{
mergedMatchingNodes = null;
mergedRuntimeRudeEdits = null;
}
mergedUpdateEditSyntaxMaps.Add(partialTypeEdits.Key, (mergedMatchingNodes, mergedRuntimeRudeEdits));
}
// Deduplicate edits based on their target symbol and use merged syntax map calculated above for a given partial type.
using var _3 = PooledHashSet<ISymbol>.GetInstance(out var visitedSymbols);
for (var i = 0; i < edits.Count; i++)
{
var edit = edits[i];
if (edit.PartialType != null)
{
var (oldSymbol, newSymbol) = resolvedSymbols[i];
if (visitedSymbols.Add(newSymbol ?? oldSymbol!))
{
var syntaxMaps = (edit.Kind == SemanticEditKind.Update) ? mergedUpdateEditSyntaxMaps[edit.PartialType.Value] : default;
mergedEditsBuilder.Add(new SemanticEdit(edit.Kind, oldSymbol, newSymbol, syntaxMaps.matchingNodes, syntaxMaps.runtimeRudeEdits));
}
}
}
mergedEdits = mergedEditsBuilder.ToImmutable();
addedSymbols = addedSymbolsBuilder.ToImmutableHashSet();
}
public async ValueTask<SolutionUpdate> EmitSolutionUpdateAsync(Solution solution, ActiveStatementSpanProvider solutionActiveStatementSpanProvider, UpdateId updateId, CancellationToken cancellationToken)
{
var log = EditAndContinueService.Log;
try
{
log.Write("EmitSolutionUpdate {0}.{1}: '{2}'", updateId.SessionId.Ordinal, updateId.Ordinal, solution.FilePath);
using var _1 = ArrayBuilder<ManagedHotReloadUpdate>.GetInstance(out var deltas);
using var _2 = ArrayBuilder<(Guid ModuleId, ImmutableArray<(ManagedModuleMethodId Method, NonRemappableRegion Region)>)>.GetInstance(out var nonRemappableRegions);
using var _3 = ArrayBuilder<ProjectBaseline>.GetInstance(out var newProjectBaselines);
using var _4 = ArrayBuilder<ProjectDiagnostics>.GetInstance(out var diagnostics);
using var _5 = ArrayBuilder<Document>.GetInstance(out var changedOrAddedDocuments);
using var _6 = ArrayBuilder<(DocumentId, ImmutableArray<RudeEditDiagnostic>)>.GetInstance(out var documentsWithRudeEdits);
Diagnostic? syntaxError = null;
var oldSolution = DebuggingSession.LastCommittedSolution;
var isBlocked = false;
var hasEmitErrors = false;
foreach (var newProject in solution.Projects)
{
var oldProject = oldSolution.GetProject(newProject.Id);
if (oldProject == null)
{
log.Write("EnC state of '{0}' queried: project not loaded", newProject.Id);
// 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;
}
await PopulateChangedAndAddedDocumentsAsync(oldProject, newProject, changedOrAddedDocuments, cancellationToken).ConfigureAwait(false);
if (changedOrAddedDocuments.IsEmpty())
{
continue;
}
log.Write("Found {0} potentially changed document(s) in project '{1}'", changedOrAddedDocuments.Count, newProject.Id);
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, ImmutableArray.Create(mvidReadError)));
Telemetry.LogProjectAnalysisSummary(ProjectAnalysisSummary.ValidChanges, newProject.State.ProjectInfo.Attributes.TelemetryId, ImmutableArray.Create(mvidReadError.Descriptor.Id));
isBlocked = true;
continue;
}
if (mvid == Guid.Empty)
{
log.Write("Emitting update of '{0}': project not built", newProject.Id);
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, documentDiagnostics) = await AnalyzeDocumentsAsync(changedOrAddedDocuments, 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));
}
foreach (var changedDocumentAnalysis in changedDocumentAnalyses)
{
if (changedDocumentAnalysis.HasChanges)
{
log.Write("Document changed, added, or deleted: '{0}'", changedDocumentAnalysis.FilePath);
}
Telemetry.LogAnalysisTime(changedDocumentAnalysis.ElapsedTime);
}
var projectSummary = GetProjectAnalysisSummary(changedDocumentAnalyses);
log.Write("Project summary for '{0}': {1}", newProject.Id, projectSummary);
if (projectSummary == ProjectAnalysisSummary.NoChanges)
{
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);
var isModuleEncBlocked = isModuleLoaded && !moduleDiagnostics.IsEmpty;
if (isModuleEncBlocked)
{
diagnostics.Add(new(newProject.Id, moduleDiagnostics));
isBlocked = true;
}
if (projectSummary == ProjectAnalysisSummary.CompilationErrors)
{
// only remember the first syntax error we encounter:
syntaxError ??= changedDocumentAnalyses.FirstOrDefault(a => a.SyntaxError != null)?.SyntaxError;
isBlocked = true;
}
else if (projectSummary == ProjectAnalysisSummary.RudeEdits)
{
foreach (var analysis in changedDocumentAnalyses)
{
if (analysis.RudeEditErrors.Length > 0)
{
documentsWithRudeEdits.Add((analysis.DocumentId, analysis.RudeEditErrors));
Telemetry.LogRudeEditDiagnostics(analysis.RudeEditErrors, newProject.State.Attributes.TelemetryId);
}
}
isBlocked = true;
}
if (isModuleEncBlocked || projectSummary != ProjectAnalysisSummary.ValidChanges)
{
Telemetry.LogProjectAnalysisSummary(projectSummary, newProject.State.ProjectInfo.Attributes.TelemetryId, moduleDiagnostics.NullToEmpty().SelectAsArray(d => d.Descriptor.Id));
await LogDocumentChangesAsync(generation: null, cancellationToken).ConfigureAwait(false);
continue;
}
var oldCompilation = await oldProject.GetCompilationAsync(cancellationToken).ConfigureAwait(false);
Contract.ThrowIfNull(oldCompilation);
if (!DebuggingSession.TryGetOrCreateEmitBaseline(oldProject, oldCompilation, out var createBaselineDiagnostics, out var projectBaseline, out var baselineAccessLock))
{
Debug.Assert(!createBaselineDiagnostics.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, createBaselineDiagnostics));
Telemetry.LogProjectAnalysisSummary(projectSummary, newProject.State.ProjectInfo.Attributes.TelemetryId, createBaselineDiagnostics);
isBlocked = true;
await LogDocumentChangesAsync(generation: null, cancellationToken).ConfigureAwait(false);
continue;
}
await LogDocumentChangesAsync(projectBaseline.Generation + 1, cancellationToken).ConfigureAwait(false);
async ValueTask LogDocumentChangesAsync(int? generation, CancellationToken cancellationToken)
{
var fileLog = log.FileLog;
if (fileLog != null)
{
foreach (var changedDocumentAnalysis in changedDocumentAnalyses)
{
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);
}
}
}
}
log.Write("Emitting update of '{0}'", newProject.Id);
var newCompilation = await newProject.GetCompilationAsync(cancellationToken).ConfigureAwait(false);
Contract.ThrowIfNull(newCompilation);
var oldActiveStatementsMap = await BaseActiveStatements.GetValueAsync(cancellationToken).ConfigureAwait(false);
var projectChanges = await GetProjectChangesAsync(oldActiveStatementsMap, oldCompilation, newCompilation, oldProject, newProject, changedDocumentAnalyses, cancellationToken).ConfigureAwait(false);
using var pdbStream = SerializableBytes.CreateWritableStream();
using var metadataStream = SerializableBytes.CreateWritableStream();
using var ilStream = SerializableBytes.CreateWritableStream();
// project must support compilations since it supports EnC
Contract.ThrowIfNull(newCompilation);
// 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