/
Workspace.cs
2195 lines (1880 loc) · 103 KB
/
Workspace.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.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Options.EditorConfig;
using Microsoft.CodeAnalysis.Remote;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis
{
/// <summary>
/// A workspace provides access to a active set of source code projects and documents and their
/// associated syntax trees, compilations and semantic models. A workspace has a current solution
/// that is an immutable snapshot of the projects and documents. This property may change over time
/// as the workspace is updated either from live interactions in the environment or via call to the
/// workspace's <see cref="TryApplyChanges(Solution)"/> method.
/// </summary>
public abstract partial class Workspace : IDisposable
{
private readonly string? _workspaceKind;
private readonly HostWorkspaceServices _services;
private readonly BranchId _primaryBranchId;
private readonly IOptionService _optionService;
// forces serialization of mutation calls from host (OnXXX methods). Must take this lock before taking stateLock.
private readonly SemaphoreSlim _serializationLock = new(initialCount: 1);
// this lock guards all the mutable fields (do not share lock with derived classes)
private readonly NonReentrantLock _stateLock = new(useThisInstanceForSynchronization: true);
// Current solution.
private Solution _latestSolution;
private readonly TaskQueue _taskQueue;
// test hooks.
internal static bool TestHookStandaloneProjectsDoNotHoldReferences = false;
internal bool TestHookPartialSolutionsDisabled { get; set; }
/// <summary>
/// Determines whether changes made to unchangeable documents will be silently ignored or cause exceptions to be thrown
/// when they are applied to workspace via <see cref="TryApplyChanges(Solution, IProgressTracker)"/>.
/// A document is unchangeable if <see cref="IDocumentOperationService.CanApplyChange"/> is false.
/// </summary>
internal virtual bool IgnoreUnchangeableDocumentsWhenApplyingChanges { get; } = false;
private Action<string>? _testMessageLogger;
/// <summary>
/// Constructs a new workspace instance.
/// </summary>
/// <param name="host">The <see cref="HostServices"/> this workspace uses</param>
/// <param name="workspaceKind">A string that can be used to identify the kind of workspace. Usually this matches the name of the class.</param>
protected Workspace(HostServices host, string? workspaceKind)
{
_primaryBranchId = BranchId.GetNextId();
_workspaceKind = workspaceKind;
_services = host.CreateWorkspaceServices(this);
_optionService = _services.GetRequiredService<IOptionService>();
_optionService.RegisterWorkspace(this);
// queue used for sending events
var schedulerProvider = _services.GetRequiredService<ITaskSchedulerProvider>();
var listenerProvider = _services.GetRequiredService<IWorkspaceAsynchronousOperationListenerProvider>();
_taskQueue = new TaskQueue(listenerProvider.GetListener(), schedulerProvider.CurrentContextScheduler);
// initialize with empty solution
var info = SolutionInfo.Create(SolutionId.CreateNewId(), VersionStamp.Create());
var emptyOptions = new SerializableOptionSet(languages: ImmutableHashSet<string>.Empty, _optionService,
serializableOptions: ImmutableHashSet<IOption>.Empty, values: ImmutableDictionary<OptionKey, object?>.Empty,
changedOptionKeysSerializable: ImmutableHashSet<OptionKey>.Empty);
_latestSolution = CreateSolution(info, emptyOptions, analyzerReferences: SpecializedCollections.EmptyReadOnlyList<AnalyzerReference>());
_optionService.RegisterDocumentOptionsProvider(EditorConfigDocumentOptionsProviderFactory.Create());
}
internal void LogTestMessage(string message)
=> _testMessageLogger?.Invoke(message);
/// <summary>
/// Sets an internal logger that will receive some messages.
/// </summary>
/// <param name="writeLineMessageLogger">An action called to write a single line to the log.</param>
internal void SetTestLogger(Action<string>? writeLineMessageLogger)
=> _testMessageLogger = writeLineMessageLogger;
/// <summary>
/// Services provider by the host for implementing workspace features.
/// </summary>
public HostWorkspaceServices Services => _services;
/// <summary>
/// primary branch id that current solution has
/// </summary>
internal BranchId PrimaryBranchId => _primaryBranchId;
/// <summary>
/// Override this property if the workspace supports partial semantics for documents.
/// </summary>
protected internal virtual bool PartialSemanticsEnabled => false;
/// <summary>
/// The kind of the workspace.
/// This is generally <see cref="WorkspaceKind.Host"/> if originating from the host environment, but may be
/// any other name used for a specific kind of workspace.
/// </summary>
// TODO (https://github.com/dotnet/roslyn/issues/37110): decide if Kind should be non-null
public string? Kind => _workspaceKind;
/// <summary>
/// Create a new empty solution instance associated with this workspace.
/// </summary>
protected internal Solution CreateSolution(SolutionInfo solutionInfo)
{
var options = _optionService.GetSerializableOptionsSnapshot(solutionInfo.GetRemoteSupportedProjectLanguages());
return CreateSolution(solutionInfo, options, solutionInfo.AnalyzerReferences);
}
/// <summary>
/// Create a new empty solution instance associated with this workspace, and with the given options.
/// </summary>
private Solution CreateSolution(SolutionInfo solutionInfo, SerializableOptionSet options, IReadOnlyList<AnalyzerReference> analyzerReferences)
=> new(this, solutionInfo.Attributes, options, analyzerReferences);
/// <summary>
/// Create a new empty solution instance associated with this workspace.
/// </summary>
protected internal Solution CreateSolution(SolutionId id)
=> CreateSolution(SolutionInfo.Create(id, VersionStamp.Create()));
/// <summary>
/// The current solution.
///
/// The solution is an immutable model of the current set of projects and source documents.
/// It provides access to source text, syntax trees and semantics.
///
/// This property may change as the workspace reacts to changes in the environment or
/// after <see cref="TryApplyChanges(Solution)"/> is called.
/// </summary>
public Solution CurrentSolution
{
get
{
return Volatile.Read(ref _latestSolution);
}
}
/// <summary>
/// Sets the <see cref="CurrentSolution"/> of this workspace. This method does not raise a <see cref="WorkspaceChanged"/> event.
/// </summary>
/// <remarks>
/// This method does not guarantee that linked files will have the same contents. Callers
/// should enforce that policy before passing in the new solution.
/// </remarks>
protected Solution SetCurrentSolution(Solution solution)
{
if (solution is null)
{
throw new ArgumentNullException(nameof(solution));
}
var currentSolution = Volatile.Read(ref _latestSolution);
if (solution == currentSolution)
{
// No change
return solution;
}
while (true)
{
var newSolution = solution.WithNewWorkspace(this, currentSolution.WorkspaceVersion + 1);
var oldSolution = Interlocked.CompareExchange(ref _latestSolution, newSolution, currentSolution);
if (oldSolution == currentSolution)
{
return newSolution;
}
currentSolution = oldSolution;
}
}
/// <summary>
/// Applies specified transformation to <see cref="CurrentSolution"/>, updates <see cref="CurrentSolution"/> to the new value and raises a workspace change event of the specified kind.
/// </summary>
/// <param name="transformation">Solution transformation.</param>
/// <param name="kind">The kind of workspace change event to raise.</param>
/// <param name="projectId">The id of the project updated by <paramref name="transformation"/> to be passed to the workspace change event.</param>
/// <param name="documentId">The id of the document updated by <paramref name="transformation"/> to be passed to the workspace change event.</param>
/// <returns>True if <see cref="CurrentSolution"/> was set to the transformed solution, false if the transformation did not change the solution.</returns>
internal bool SetCurrentSolution(Func<Solution, Solution> transformation, WorkspaceChangeKind kind, ProjectId? projectId = null, DocumentId? documentId = null)
{
Contract.ThrowIfNull(transformation);
var currentSolution = Volatile.Read(ref _latestSolution);
while (true)
{
var transformedSolution = transformation(currentSolution);
if (transformedSolution == currentSolution)
{
return false;
}
var newSolution = transformedSolution.WithNewWorkspace(this, currentSolution.WorkspaceVersion + 1);
Solution oldSolution;
using (_serializationLock.DisposableWait())
{
oldSolution = Interlocked.CompareExchange(ref _latestSolution, newSolution, currentSolution);
if (oldSolution == currentSolution)
{
// Queue the event but don't execute its handlers on this thread.
// Doing so under the serialization lock guarantees the same ordering of the events
// as the order of the changes made to the solution.
RaiseWorkspaceChangedEventAsync(kind, oldSolution, newSolution, projectId, documentId);
return true;
}
}
currentSolution = oldSolution;
}
}
/// <summary>
/// Gets or sets the set of all global options and <see cref="Solution.Options"/>.
/// Setter also force updates the <see cref="CurrentSolution"/> to have the updated <see cref="Solution.Options"/>.
/// </summary>
public OptionSet Options
{
get
{
return this.CurrentSolution.Options;
}
[Obsolete(@"Workspace options should be set by invoking 'workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(newOptionSet))'")]
set
{
SetOptions(value);
}
}
/// <summary>
/// Sets global options and <see cref="Options"/> to have the new options.
/// NOTE: This method also updates <see cref="CurrentSolution"/> to a new solution instance with updated <see cref="Solution.Options"/>.
/// </summary>
internal void SetOptions(OptionSet options)
=> _optionService.SetOptions(options);
internal void UpdateCurrentSolutionOnOptionsChanged()
{
var newOptions = _optionService.GetSerializableOptionsSnapshot(this.CurrentSolution.State.GetRemoteSupportedProjectLanguages());
this.SetCurrentSolution(this.CurrentSolution.WithOptions(newOptions));
}
/// <summary>
/// Executes an action as a background task, as part of a sequential queue of tasks.
/// </summary>
[SuppressMessage("Style", "VSTHRD200:Use \"Async\" suffix for async methods", Justification = "This is a Task wrapper, not an asynchronous method.")]
protected internal Task ScheduleTask(Action action, string? taskName = "Workspace.Task")
=> _taskQueue.ScheduleTask(taskName ?? "Workspace.Task", action, CancellationToken.None);
/// <summary>
/// Execute a function as a background task, as part of a sequential queue of tasks.
/// </summary>
[SuppressMessage("Style", "VSTHRD200:Use \"Async\" suffix for async methods", Justification = "This is a Task wrapper, not an asynchronous method.")]
protected internal Task<T> ScheduleTask<T>(Func<T> func, string? taskName = "Workspace.Task")
=> _taskQueue.ScheduleTask(taskName ?? "Workspace.Task", func, CancellationToken.None);
/// <summary>
/// Override this method to act immediately when the text of a document has changed, as opposed
/// to waiting for the corresponding workspace changed event to fire asynchronously.
/// </summary>
protected virtual void OnDocumentTextChanged(Document document)
{
}
/// <summary>
/// Override this method to act immediately when a document is closing, as opposed
/// to waiting for the corresponding workspace changed event to fire asynchronously.
/// </summary>
protected virtual void OnDocumentClosing(DocumentId documentId)
{
}
/// <summary>
/// Clears all solution data and empties the current solution.
/// </summary>
protected void ClearSolution()
{
using (_serializationLock.DisposableWait())
{
var oldSolution = this.CurrentSolution;
this.ClearSolutionData();
this.RaiseWorkspaceChangedEventAsync(WorkspaceChangeKind.SolutionCleared, oldSolution, this.CurrentSolution);
}
}
/// <summary>
/// This method is called when a solution is cleared.
///
/// Override this method if you want to do additional work when a solution is cleared.
/// Call the base method at the end of your method.
/// </summary>
protected virtual void ClearSolutionData()
{
// clear any open documents
this.ClearOpenDocuments();
this.SetCurrentSolution(this.CreateSolution(this.CurrentSolution.Id));
}
/// <summary>
/// This method is called when an individual project is removed.
///
/// Override this method if you want to do additional work when a project is removed.
/// Call the base method at the end of your method.
/// </summary>
protected virtual void ClearProjectData(ProjectId projectId)
=> this.ClearOpenDocuments(projectId);
/// <summary>
/// This method is called to clear an individual document is removed.
///
/// Override this method if you want to do additional work when a document is removed.
/// Call the base method at the end of your method.
/// </summary>
protected internal virtual void ClearDocumentData(DocumentId documentId)
=> this.ClearOpenDocument(documentId);
/// <summary>
/// Disposes this workspace. The workspace can longer be used after it is disposed.
/// </summary>
public void Dispose()
=> this.Dispose(finalize: false);
/// <summary>
/// Call this method when the workspace is disposed.
///
/// Override this method to do additional work when the workspace is disposed.
/// Call this method at the end of your method.
/// </summary>
protected virtual void Dispose(bool finalize)
{
if (!finalize)
{
this.ClearSolutionData();
this.Services.GetService<IWorkspaceEventListenerService>()?.Stop();
}
(_optionService as IWorkspaceOptionService)?.OnWorkspaceDisposed(this);
_optionService.UnregisterWorkspace(this);
// Directly dispose IRemoteHostClientProvider if necessary. This is a test hook to ensure RemoteWorkspace
// gets disposed in unit tests as soon as TestWorkspace gets disposed. This would be superseded by direct
// support for IDisposable in https://github.com/dotnet/roslyn/pull/47951.
if (Services.GetService<IRemoteHostClientProvider>() is IDisposable disposableService)
{
disposableService.Dispose();
}
}
#region Host API
/// <summary>
/// Call this method to respond to a solution being opened in the host environment.
/// </summary>
protected internal void OnSolutionAdded(SolutionInfo solutionInfo)
{
using (_serializationLock.DisposableWait())
{
var oldSolution = this.CurrentSolution;
var solutionId = solutionInfo.Id;
CheckSolutionIsEmpty();
this.SetCurrentSolution(this.CreateSolution(solutionInfo));
solutionInfo.Projects.Do(p => OnProjectAdded_NoLock(p, silent: true));
var newSolution = this.CurrentSolution;
this.RaiseWorkspaceChangedEventAsync(WorkspaceChangeKind.SolutionAdded, oldSolution, newSolution);
}
}
/// <summary>
/// Call this method to respond to a solution being reloaded in the host environment.
/// </summary>
protected internal void OnSolutionReloaded(SolutionInfo reloadedSolutionInfo)
{
using (_serializationLock.DisposableWait())
{
var oldSolution = this.CurrentSolution;
var newSolution = this.SetCurrentSolution(this.CreateSolution(reloadedSolutionInfo));
reloadedSolutionInfo.Projects.Do(pi => OnProjectAdded_NoLock(pi, silent: true));
newSolution = this.AdjustReloadedSolution(oldSolution, this.CurrentSolution);
newSolution = this.SetCurrentSolution(newSolution);
this.RaiseWorkspaceChangedEventAsync(WorkspaceChangeKind.SolutionReloaded, oldSolution, newSolution);
}
}
/// <summary>
/// This method is called when the solution is removed from the workspace.
///
/// Override this method if you want to do additional work when the solution is removed.
/// Call the base method at the end of your method.
/// Call this method to respond to a solution being removed/cleared/closed in the host environment.
/// </summary>
protected internal void OnSolutionRemoved()
{
using (_serializationLock.DisposableWait())
{
var oldSolution = this.CurrentSolution;
this.ClearSolutionData();
// reset to new empty solution
this.SetCurrentSolution(this.CreateSolution(SolutionId.CreateNewId()));
this.RaiseWorkspaceChangedEventAsync(WorkspaceChangeKind.SolutionRemoved, oldSolution, this.CurrentSolution);
}
}
/// <summary>
/// Call this method to respond to a project being added/opened in the host environment.
/// </summary>
protected internal void OnProjectAdded(ProjectInfo projectInfo)
=> this.OnProjectAdded(projectInfo, silent: false);
private void OnProjectAdded(ProjectInfo projectInfo, bool silent)
{
using (_serializationLock.DisposableWait())
{
this.OnProjectAdded_NoLock(projectInfo, silent);
}
}
private void OnProjectAdded_NoLock(ProjectInfo projectInfo, bool silent)
{
var projectId = projectInfo.Id;
CheckProjectIsNotInCurrentSolution(projectId);
var oldSolution = this.CurrentSolution;
var newSolution = this.SetCurrentSolution(oldSolution.AddProject(projectInfo));
if (!silent)
{
this.RaiseWorkspaceChangedEventAsync(WorkspaceChangeKind.ProjectAdded, oldSolution, newSolution, projectId);
}
}
/// <summary>
/// Call this method to respond to a project being reloaded in the host environment.
/// </summary>
protected internal virtual void OnProjectReloaded(ProjectInfo reloadedProjectInfo)
{
using (_serializationLock.DisposableWait())
{
var projectId = reloadedProjectInfo.Id;
CheckProjectIsInCurrentSolution(projectId);
var oldSolution = this.CurrentSolution;
var newSolution = oldSolution.RemoveProject(projectId).AddProject(reloadedProjectInfo);
newSolution = this.AdjustReloadedProject(oldSolution.GetRequiredProject(projectId), newSolution.GetRequiredProject(projectId)).Solution;
newSolution = this.SetCurrentSolution(newSolution);
this.RaiseWorkspaceChangedEventAsync(WorkspaceChangeKind.ProjectReloaded, oldSolution, newSolution, projectId);
}
}
/// <summary>
/// Call this method to respond to a project being removed from the host environment.
/// </summary>
protected internal virtual void OnProjectRemoved(ProjectId projectId)
{
using (_serializationLock.DisposableWait())
{
CheckProjectIsInCurrentSolution(projectId);
this.CheckProjectCanBeRemoved(projectId);
var oldSolution = this.CurrentSolution;
this.ClearProjectData(projectId);
var newSolution = this.SetCurrentSolution(oldSolution.RemoveProject(projectId));
this.RaiseWorkspaceChangedEventAsync(WorkspaceChangeKind.ProjectRemoved, oldSolution, newSolution, projectId);
}
}
/// <summary>
/// Currently projects can always be removed, but this method still exists because it's protected and we don't
/// want to break people who may have derived from <see cref="Workspace"/> and either called it, or overridden it.
/// </summary>
protected virtual void CheckProjectCanBeRemoved(ProjectId projectId)
{
}
/// <summary>
/// Call this method when a project's assembly name is changed in the host environment.
/// </summary>
protected internal void OnAssemblyNameChanged(ProjectId projectId, string assemblyName)
=> SetCurrentSolution(oldSolution => oldSolution.WithProjectAssemblyName(projectId, assemblyName), WorkspaceChangeKind.ProjectChanged, projectId);
/// <summary>
/// Call this method when a project's output file path is changed in the host environment.
/// </summary>
protected internal void OnOutputFilePathChanged(ProjectId projectId, string? outputFilePath)
=> SetCurrentSolution(oldSolution => oldSolution.WithProjectOutputFilePath(projectId, outputFilePath), WorkspaceChangeKind.ProjectChanged, projectId);
/// <summary>
/// Call this method when a project's output ref file path is changed in the host environment.
/// </summary>
protected internal void OnOutputRefFilePathChanged(ProjectId projectId, string? outputFilePath)
=> SetCurrentSolution(oldSolution => oldSolution.WithProjectOutputRefFilePath(projectId, outputFilePath), WorkspaceChangeKind.ProjectChanged, projectId);
/// <summary>
/// Call this method when a project's name is changed in the host environment.
/// </summary>
// TODO (https://github.com/dotnet/roslyn/issues/37124): decide if we want to allow "name" to be nullable.
// As of this writing you can pass null, but rather than updating the project to null it seems it does nothing.
// I'm leaving this marked as "non-null" so as not to say we actually support that behavior. The underlying
// requirement is ProjectInfo.ProjectAttributes holds a non-null name, so you can't get a null into this even if you tried.
protected internal void OnProjectNameChanged(ProjectId projectId, string name, string? filePath)
=> SetCurrentSolution(oldSolution => oldSolution.WithProjectName(projectId, name).WithProjectFilePath(projectId, filePath), WorkspaceChangeKind.ProjectChanged, projectId);
/// <summary>
/// Call this method when a project's default namespace is changed in the host environment.
/// </summary>
internal void OnDefaultNamespaceChanged(ProjectId projectId, string? defaultNamespace)
=> SetCurrentSolution(oldSolution => oldSolution.WithProjectDefaultNamespace(projectId, defaultNamespace), WorkspaceChangeKind.ProjectChanged, projectId);
/// <summary>
/// Call this method when a project's compilation options are changed in the host environment.
/// </summary>
protected internal void OnCompilationOptionsChanged(ProjectId projectId, CompilationOptions options)
=> SetCurrentSolution(oldSolution => oldSolution.WithProjectCompilationOptions(projectId, options), WorkspaceChangeKind.ProjectChanged, projectId);
/// <summary>
/// Call this method when a project's parse options are changed in the host environment.
/// </summary>
protected internal void OnParseOptionsChanged(ProjectId projectId, ParseOptions options)
=> SetCurrentSolution(oldSolution => oldSolution.WithProjectParseOptions(projectId, options), WorkspaceChangeKind.ProjectChanged, projectId);
/// <summary>
/// Call this method when a project reference is added to a project in the host environment.
/// </summary>
protected internal void OnProjectReferenceAdded(ProjectId projectId, ProjectReference projectReference)
{
SetCurrentSolution(oldSolution =>
{
CheckProjectIsInCurrentSolution(projectReference.ProjectId);
CheckProjectDoesNotHaveProjectReference(projectId, projectReference);
// Can only add this P2P reference if it would not cause a circularity.
CheckProjectDoesNotHaveTransitiveProjectReference(projectId, projectReference.ProjectId);
return oldSolution.AddProjectReference(projectId, projectReference);
}, WorkspaceChangeKind.ProjectChanged, projectId);
}
/// <summary>
/// Call this method when a project reference is removed from a project in the host environment.
/// </summary>
protected internal void OnProjectReferenceRemoved(ProjectId projectId, ProjectReference projectReference)
{
SetCurrentSolution(oldSolution =>
{
CheckProjectIsInCurrentSolution(projectReference.ProjectId);
CheckProjectHasProjectReference(projectId, projectReference);
return oldSolution.RemoveProjectReference(projectId, projectReference);
}, WorkspaceChangeKind.ProjectChanged, projectId);
}
/// <summary>
/// Call this method when a metadata reference is added to a project in the host environment.
/// </summary>
protected internal void OnMetadataReferenceAdded(ProjectId projectId, MetadataReference metadataReference)
{
SetCurrentSolution(oldSolution =>
{
CheckProjectDoesNotHaveMetadataReference(projectId, metadataReference);
return oldSolution.AddMetadataReference(projectId, metadataReference);
}, WorkspaceChangeKind.ProjectChanged, projectId);
}
/// <summary>
/// Call this method when a metadata reference is removed from a project in the host environment.
/// </summary>
protected internal void OnMetadataReferenceRemoved(ProjectId projectId, MetadataReference metadataReference)
{
SetCurrentSolution(oldSolution =>
{
CheckProjectHasMetadataReference(projectId, metadataReference);
return oldSolution.RemoveMetadataReference(projectId, metadataReference);
}, WorkspaceChangeKind.ProjectChanged, projectId);
}
/// <summary>
/// Call this method when an analyzer reference is added to a project in the host environment.
/// </summary>
protected internal void OnAnalyzerReferenceAdded(ProjectId projectId, AnalyzerReference analyzerReference)
{
SetCurrentSolution(oldSolution =>
{
CheckProjectDoesNotHaveAnalyzerReference(projectId, analyzerReference);
return oldSolution.AddAnalyzerReference(projectId, analyzerReference);
}, WorkspaceChangeKind.ProjectChanged, projectId);
}
/// <summary>
/// Call this method when an analyzer reference is removed from a project in the host environment.
/// </summary>
protected internal void OnAnalyzerReferenceRemoved(ProjectId projectId, AnalyzerReference analyzerReference)
{
SetCurrentSolution(oldSolution =>
{
CheckProjectHasAnalyzerReference(projectId, analyzerReference);
return oldSolution.RemoveAnalyzerReference(projectId, analyzerReference);
}, WorkspaceChangeKind.ProjectChanged, projectId);
}
/// <summary>
/// Call this method when an analyzer reference is added to a project in the host environment.
/// </summary>
internal void OnSolutionAnalyzerReferenceAdded(AnalyzerReference analyzerReference)
{
SetCurrentSolution(oldSolution =>
{
CheckSolutionDoesNotHaveAnalyzerReference(oldSolution, analyzerReference);
return oldSolution.AddAnalyzerReference(analyzerReference);
}, WorkspaceChangeKind.SolutionChanged);
}
/// <summary>
/// Call this method when an analyzer reference is removed from a project in the host environment.
/// </summary>
internal void OnSolutionAnalyzerReferenceRemoved(AnalyzerReference analyzerReference)
{
SetCurrentSolution(oldSolution =>
{
CheckSolutionHasAnalyzerReference(oldSolution, analyzerReference);
return oldSolution.RemoveAnalyzerReference(analyzerReference);
}, WorkspaceChangeKind.SolutionChanged);
}
/// <summary>
/// Call this method when status of project has changed to incomplete.
/// See <see cref="ProjectInfo.HasAllInformation"/> for more information.
/// </summary>
// TODO: make it public
internal void OnHasAllInformationChanged(ProjectId projectId, bool hasAllInformation)
=> SetCurrentSolution(oldSolution => oldSolution.WithHasAllInformation(projectId, hasAllInformation), WorkspaceChangeKind.ProjectChanged, projectId);
/// <summary>
/// Call this method when a project's RunAnalyzers property is changed in the host environment.
/// </summary>
internal void OnRunAnalyzersChanged(ProjectId projectId, bool runAnalyzers)
=> SetCurrentSolution(oldSolution => oldSolution.WithRunAnalyzers(projectId, runAnalyzers), WorkspaceChangeKind.ProjectChanged, projectId);
/// <summary>
/// Call this method when a document is added to a project in the host environment.
/// </summary>
protected internal void OnDocumentAdded(DocumentInfo documentInfo)
{
using (_serializationLock.DisposableWait())
{
var documentId = documentInfo.Id;
var oldSolution = this.CurrentSolution;
var newSolution = this.SetCurrentSolution(oldSolution.AddDocument(documentInfo));
this.RaiseWorkspaceChangedEventAsync(WorkspaceChangeKind.DocumentAdded, oldSolution, newSolution, documentId: documentId);
}
}
/// <summary>
/// Call this method when multiple document are added to one or more projects in the host environment.
/// </summary>
protected internal void OnDocumentsAdded(ImmutableArray<DocumentInfo> documentInfos)
{
using (_serializationLock.DisposableWait())
{
var oldSolution = this.CurrentSolution;
var newSolution = this.SetCurrentSolution(oldSolution.AddDocuments(documentInfos));
// Raise ProjectChanged as the event type here. DocumentAdded is presumed by many callers to have a
// DocumentId associated with it, and we don't want to be raising multiple events.
this.RaiseWorkspaceChangedEventAsync(WorkspaceChangeKind.ProjectChanged, oldSolution, newSolution);
}
}
/// <summary>
/// Call this method when a document is reloaded in the host environment.
/// </summary>
protected internal void OnDocumentReloaded(DocumentInfo newDocumentInfo)
{
using (_serializationLock.DisposableWait())
{
var documentId = newDocumentInfo.Id;
var oldSolution = this.CurrentSolution;
var newSolution = this.SetCurrentSolution(oldSolution.RemoveDocument(documentId).AddDocument(newDocumentInfo));
this.RaiseWorkspaceChangedEventAsync(WorkspaceChangeKind.DocumentReloaded, oldSolution, newSolution, documentId: documentId);
}
}
/// <summary>
/// Call this method when a document is removed from a project in the host environment.
/// </summary>
protected internal void OnDocumentRemoved(DocumentId documentId)
{
using (_serializationLock.DisposableWait())
{
CheckDocumentIsInCurrentSolution(documentId);
this.CheckDocumentCanBeRemoved(documentId);
var oldSolution = this.CurrentSolution;
this.ClearDocumentData(documentId);
var newSolution = this.SetCurrentSolution(oldSolution.RemoveDocument(documentId));
this.RaiseWorkspaceChangedEventAsync(WorkspaceChangeKind.DocumentRemoved, oldSolution, newSolution, documentId: documentId);
}
}
protected virtual void CheckDocumentCanBeRemoved(DocumentId documentId)
{
}
/// <summary>
/// Call this method when the text of a document is changed on disk.
/// </summary>
protected internal void OnDocumentTextLoaderChanged(DocumentId documentId, TextLoader loader)
{
using (_serializationLock.DisposableWait())
{
CheckDocumentIsInCurrentSolution(documentId);
var oldSolution = this.CurrentSolution;
var newSolution = oldSolution.WithDocumentTextLoader(documentId, loader, PreservationMode.PreserveValue);
newSolution = this.SetCurrentSolution(newSolution);
var newDocument = newSolution.GetDocument(documentId)!;
this.OnDocumentTextChanged(newDocument);
this.RaiseWorkspaceChangedEventAsync(WorkspaceChangeKind.DocumentChanged, oldSolution, newSolution, documentId: documentId);
}
}
/// <summary>
/// Call this method when the text of a additional document is changed on disk.
/// </summary>
protected internal void OnAdditionalDocumentTextLoaderChanged(DocumentId documentId, TextLoader loader)
{
using (_serializationLock.DisposableWait())
{
CheckAdditionalDocumentIsInCurrentSolution(documentId);
var oldSolution = this.CurrentSolution;
var newSolution = oldSolution.WithAdditionalDocumentTextLoader(documentId, loader, PreservationMode.PreserveValue);
newSolution = this.SetCurrentSolution(newSolution);
this.RaiseWorkspaceChangedEventAsync(WorkspaceChangeKind.AdditionalDocumentChanged, oldSolution, newSolution, documentId: documentId);
}
}
/// <summary>
/// Call this method when the text of a analyzer config document is changed on disk.
/// </summary>
protected internal void OnAnalyzerConfigDocumentTextLoaderChanged(DocumentId documentId, TextLoader loader)
{
using (_serializationLock.DisposableWait())
{
CheckAnalyzerConfigDocumentIsInCurrentSolution(documentId);
var oldSolution = this.CurrentSolution;
var newSolution = oldSolution.WithAnalyzerConfigDocumentTextLoader(documentId, loader, PreservationMode.PreserveValue);
newSolution = this.SetCurrentSolution(newSolution);
this.RaiseWorkspaceChangedEventAsync(WorkspaceChangeKind.AnalyzerConfigDocumentChanged, oldSolution, newSolution, documentId: documentId);
}
}
/// <summary>
/// Call this method when the document info changes, such as the name, folders or file path.
/// </summary>
protected internal void OnDocumentInfoChanged(DocumentId documentId, DocumentInfo newInfo)
{
using (_serializationLock.DisposableWait())
{
CheckDocumentIsInCurrentSolution(documentId);
var oldSolution = this.CurrentSolution;
var newSolution = oldSolution;
var oldAttributes = oldSolution.GetDocument(documentId)!.State.Attributes;
if (oldAttributes.Name != newInfo.Name)
{
newSolution = newSolution.WithDocumentName(documentId, newInfo.Name);
}
if (oldAttributes.Folders != newInfo.Folders)
{
newSolution = newSolution.WithDocumentFolders(documentId, newInfo.Folders);
}
if (oldAttributes.FilePath != newInfo.FilePath)
{
// TODO (https://github.com/dotnet/roslyn/issues/37125): Solution.WithDocumentFilePath will throw if
// filePath is null, but it's odd because we *do* support null file paths. The suppression here is to silence it
// but should be removed when the bug is fixed.
newSolution = newSolution.WithDocumentFilePath(documentId, newInfo.FilePath!);
}
if (oldAttributes.SourceCodeKind != newInfo.SourceCodeKind)
{
newSolution = newSolution.WithDocumentSourceCodeKind(documentId, newInfo.SourceCodeKind);
}
if (newSolution != oldSolution)
{
SetCurrentSolution(newSolution);
this.RaiseWorkspaceChangedEventAsync(WorkspaceChangeKind.DocumentInfoChanged, oldSolution, newSolution, documentId: documentId);
}
}
}
/// <summary>
/// Call this method when the text of a document is updated in the host environment.
/// </summary>
protected internal void OnDocumentTextChanged(DocumentId documentId, SourceText newText, PreservationMode mode)
{
OnAnyDocumentTextChanged(
documentId,
newText,
mode,
CheckDocumentIsInCurrentSolution,
(solution, docId) => solution.GetRelatedDocumentIds(docId),
(solution, docId, text, preservationMode) => solution.WithDocumentText(docId, text, preservationMode),
WorkspaceChangeKind.DocumentChanged,
isCodeDocument: true);
}
/// <summary>
/// Call this method when the text of an additional document is updated in the host environment.
/// </summary>
protected internal void OnAdditionalDocumentTextChanged(DocumentId documentId, SourceText newText, PreservationMode mode)
{
OnAnyDocumentTextChanged(
documentId,
newText,
mode,
CheckAdditionalDocumentIsInCurrentSolution,
(solution, docId) => ImmutableArray.Create(docId), // We do not support the concept of linked additional documents
(solution, docId, text, preservationMode) => solution.WithAdditionalDocumentText(docId, text, preservationMode),
WorkspaceChangeKind.AdditionalDocumentChanged,
isCodeDocument: false);
}
/// <summary>
/// Call this method when the text of an analyzer config document is updated in the host environment.
/// </summary>
protected internal void OnAnalyzerConfigDocumentTextChanged(DocumentId documentId, SourceText newText, PreservationMode mode)
{
OnAnyDocumentTextChanged(
documentId,
newText,
mode,
CheckAnalyzerConfigDocumentIsInCurrentSolution,
(solution, docId) => ImmutableArray.Create(docId), // We do not support the concept of linked additional documents
(solution, docId, text, preservationMode) => solution.WithAnalyzerConfigDocumentText(docId, text, preservationMode),
WorkspaceChangeKind.AnalyzerConfigDocumentChanged,
isCodeDocument: false);
}
/// <summary>
/// When a <see cref="Document"/>s text is changed, we need to make sure all of the linked
/// files also have their content updated in the new solution before applying it to the
/// workspace to avoid the workspace having solutions with linked files where the contents
/// do not match.
/// </summary>
private void OnAnyDocumentTextChanged(
DocumentId documentId,
SourceText newText,
PreservationMode mode,
Action<DocumentId> checkIsInCurrentSolution,
Func<Solution, DocumentId, ImmutableArray<DocumentId>> getRelatedDocuments,
Func<Solution, DocumentId, SourceText, PreservationMode, Solution> updateSolutionWithText,
WorkspaceChangeKind changeKind,
bool isCodeDocument)
{
using (_serializationLock.DisposableWait())
{
checkIsInCurrentSolution(documentId);
var originalSolution = CurrentSolution;
var updatedSolution = CurrentSolution;
var previousSolution = updatedSolution;
var linkedDocuments = getRelatedDocuments(updatedSolution, documentId);
var updatedDocumentIds = new List<DocumentId>();
foreach (var linkedDocument in linkedDocuments)
{
previousSolution = updatedSolution;
updatedSolution = updateSolutionWithText(updatedSolution, linkedDocument, newText, mode);
if (previousSolution != updatedSolution)
{
updatedDocumentIds.Add(linkedDocument);
}
}
// In the case of linked files, we may have already updated all of the linked
// documents during an earlier call to this method. We may have no work to do here.
if (updatedDocumentIds.Count > 0)
{
var newSolution = SetCurrentSolution(updatedSolution);
// Prior to the unification of the callers of this method, the
// OnAdditionalDocumentTextChanged method did not fire any sort of synchronous
// update notification event, so we preserve that behavior here.
if (isCodeDocument)
{
foreach (var updatedDocumentId in updatedDocumentIds)
{
var newDocument = newSolution.GetDocument(updatedDocumentId);
Contract.ThrowIfNull(newDocument);
OnDocumentTextChanged(newDocument);
}
}
foreach (var updatedDocumentInfo in updatedDocumentIds)
{
RaiseWorkspaceChangedEventAsync(
changeKind,
originalSolution,
newSolution,
documentId: updatedDocumentInfo);
}
}
}
}
/// <summary>
/// Call this method when the SourceCodeKind of a document changes in the host environment.
/// </summary>
protected internal void OnDocumentSourceCodeKindChanged(DocumentId documentId, SourceCodeKind sourceCodeKind)
{
using (_serializationLock.DisposableWait())
{
CheckDocumentIsInCurrentSolution(documentId);
var oldSolution = this.CurrentSolution;
var newSolution = this.SetCurrentSolution(oldSolution.WithDocumentSourceCodeKind(documentId, sourceCodeKind));
var newDocument = newSolution.GetDocument(documentId)!;
this.OnDocumentTextChanged(newDocument);
this.RaiseWorkspaceChangedEventAsync(WorkspaceChangeKind.DocumentChanged, oldSolution, newSolution, documentId: documentId);
}
}
/// <summary>