/
SuggestedActionsSource.cs
988 lines (844 loc) · 45.2 KB
/
SuggestedActionsSource.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
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
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.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CodeFixes.Suppression;
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.Shared;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.Editor.Shared.Options;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.Text.Shared.Extensions;
using Microsoft.VisualStudio.Language.Intellisense;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Roslyn.Utilities;
using CodeFixGroupKey = System.Tuple<Microsoft.CodeAnalysis.Diagnostics.DiagnosticData, Microsoft.CodeAnalysis.CodeActions.CodeActionPriority>;
namespace Microsoft.CodeAnalysis.Editor.Implementation.Suggestions
{
internal partial class SuggestedActionsSourceProvider
{
private class SuggestedActionsSource : ForegroundThreadAffinitizedObject, ISuggestedActionsSource2
{
private readonly ISuggestedActionCategoryRegistryService _suggestedActionCategoryRegistry;
// state that will be only reset when source is disposed.
private SuggestedActionsSourceProvider _owner;
private ITextView _textView;
private ITextBuffer _subjectBuffer;
private WorkspaceRegistration _registration;
// mutable state
private Workspace _workspace;
private int _lastSolutionVersionReported;
public event EventHandler<EventArgs> SuggestedActionsChanged;
public SuggestedActionsSource(
IThreadingContext threadingContext,
SuggestedActionsSourceProvider owner,
ITextView textView,
ITextBuffer textBuffer,
ISuggestedActionCategoryRegistryService suggestedActionCategoryRegistry)
: base(threadingContext)
{
_owner = owner;
_textView = textView;
_textView.Closed += OnTextViewClosed;
_subjectBuffer = textBuffer;
_suggestedActionCategoryRegistry = suggestedActionCategoryRegistry;
_registration = Workspace.GetWorkspaceRegistration(textBuffer.AsTextContainer());
_lastSolutionVersionReported = InvalidSolutionVersion;
var updateSource = (IDiagnosticUpdateSource)_owner._diagnosticService;
updateSource.DiagnosticsUpdated += OnDiagnosticsUpdated;
if (_registration.Workspace != null)
{
_workspace = _registration.Workspace;
_workspace.DocumentActiveContextChanged += OnActiveContextChanged;
}
_registration.WorkspaceChanged += OnWorkspaceChanged;
}
public void Dispose()
{
if (_owner != null)
{
var updateSource = (IDiagnosticUpdateSource)_owner._diagnosticService;
updateSource.DiagnosticsUpdated -= OnDiagnosticsUpdated;
}
if (_workspace != null)
{
_workspace.DocumentActiveContextChanged -= OnActiveContextChanged;
}
if (_registration != null)
{
_registration.WorkspaceChanged -= OnWorkspaceChanged;
}
if (_textView != null)
{
_textView.Closed -= OnTextViewClosed;
}
_owner = null;
_workspace = null;
_registration = null;
_textView = null;
_subjectBuffer = null;
}
private bool IsDisposed => _subjectBuffer == null;
public bool TryGetTelemetryId(out Guid telemetryId)
{
telemetryId = default;
var workspace = _workspace;
if (workspace == null || _subjectBuffer == null)
{
return false;
}
var documentId = workspace.GetDocumentIdInCurrentContext(_subjectBuffer.AsTextContainer());
if (documentId == null)
{
return false;
}
var project = workspace.CurrentSolution.GetProject(documentId.ProjectId);
if (project == null)
{
return false;
}
switch (project.Language)
{
case LanguageNames.CSharp:
telemetryId = s_CSharpSourceGuid;
return true;
case LanguageNames.VisualBasic:
telemetryId = s_visualBasicSourceGuid;
return true;
case "Xaml":
telemetryId = s_xamlSourceGuid;
return true;
default:
return false;
}
}
public IEnumerable<SuggestedActionSet> GetSuggestedActions(
ISuggestedActionCategorySet requestedActionCategories,
SnapshotSpan range,
CancellationToken cancellationToken)
{
AssertIsForeground();
if (IsDisposed)
{
return null;
}
using (Logger.LogBlock(FunctionId.SuggestedActions_GetSuggestedActions, cancellationToken))
{
var document = range.Snapshot.GetOpenDocumentInCurrentContextWithChanges();
if (document == null)
{
// this is here to fail test and see why it is failed.
Trace.WriteLine("given range is not current");
return null;
}
var workspace = document.Project.Solution.Workspace;
var supportsFeatureService = workspace.Services.GetService<IDocumentSupportsFeatureService>();
var selectionOpt = TryGetCodeRefactoringSelection(range);
var fixes = GetCodeFixes(supportsFeatureService, requestedActionCategories, workspace, document, range, cancellationToken);
var refactorings = GetRefactorings(supportsFeatureService, requestedActionCategories, workspace, document, selectionOpt, cancellationToken);
// Get the initial set of action sets, with refactorings and fixes appropriately
// ordered against each other.
var result = GetInitiallyOrderedActionSets(selectionOpt, fixes, refactorings);
if (result.IsEmpty)
{
return null;
}
// Now that we have the entire set of action sets, inline, sort and filter
// them appropriately against each other.
var allActionSets = InlineActionSetsIfDesirable(result);
var orderedActionSets = OrderActionSets(allActionSets);
var filteredSets = FilterActionSetsByTitle(orderedActionSets);
return filteredSets;
}
}
private ImmutableArray<SuggestedActionSet> GetInitiallyOrderedActionSets(
TextSpan? selectionOpt, ImmutableArray<SuggestedActionSet> fixes, ImmutableArray<SuggestedActionSet> refactorings)
{
// First, order refactorings based on the order the providers actually gave for their actions.
// This way, a low pri refactoring always shows after a medium pri refactoring, no matter what
// we do below.
refactorings = OrderActionSets(refactorings);
// If there's a selection, it's likely the user is trying to perform some operation
// directly on that operation (like 'extract method'). Prioritize refactorings over
// fixes in that case. Otherwise, it's likely that the user is just on some error
// and wants to fix it (in which case, prioritize fixes).
if (selectionOpt?.Length > 0)
{
// There was a selection. Treat refactorings as more important than
// fixes. Note: we still will sort after this. So any high pri fixes
// will come to the front. Any low-pri refactorings will go to the end.
return refactorings.Concat(fixes);
}
else
{
// No selection. Treat all refactorings as low priority, and place
// after fixes. Even a low pri fixes will be above what was *originally*
// a medium pri refactoring.
refactorings = refactorings.SelectAsArray(r => new SuggestedActionSet(
r.CategoryName, r.Actions, r.Title, SuggestedActionSetPriority.Low, r.ApplicableToSpan));
return fixes.Concat(refactorings);
}
}
private ImmutableArray<SuggestedActionSet> OrderActionSets(
ImmutableArray<SuggestedActionSet> actionSets)
{
var caretPoint = _textView.GetCaretPoint(_subjectBuffer);
return actionSets.OrderByDescending(s => s.Priority)
.ThenBy(s => s, new SuggestedActionSetComparer(caretPoint))
.ToImmutableArray();
}
private ImmutableArray<SuggestedActionSet> FilterActionSetsByTitle(ImmutableArray<SuggestedActionSet> allActionSets)
{
var result = ArrayBuilder<SuggestedActionSet>.GetInstance();
var seenTitles = new HashSet<string>();
foreach (var set in allActionSets)
{
var filteredSet = FilterActionSetByTitle(set, seenTitles);
if (filteredSet != null)
{
result.Add(filteredSet);
}
}
return result.ToImmutableAndFree();
}
private SuggestedActionSet FilterActionSetByTitle(SuggestedActionSet set, HashSet<string> seenTitles)
{
var actions = ArrayBuilder<ISuggestedAction>.GetInstance();
foreach (var action in set.Actions)
{
if (seenTitles.Add(action.DisplayText))
{
actions.Add(action);
}
}
try
{
return actions.Count == 0
? null
: new SuggestedActionSet(set.CategoryName, actions.ToImmutable(), set.Title, set.Priority, set.ApplicableToSpan);
}
finally
{
actions.Free();
}
}
private ImmutableArray<SuggestedActionSet> InlineActionSetsIfDesirable(ImmutableArray<SuggestedActionSet> allActionSets)
{
// If we only have a single set of items, and that set only has three max suggestion
// offered. Then we can consider inlining any nested actions into the top level list.
// (but we only do this if the parent of the nested actions isn't invokable itself).
if (allActionSets.Sum(a => a.Actions.Count()) > 3)
{
return allActionSets;
}
return allActionSets.SelectAsArray(InlineActions);
}
private SuggestedActionSet InlineActions(SuggestedActionSet actionSet)
{
var newActions = ArrayBuilder<ISuggestedAction>.GetInstance();
foreach (var action in actionSet.Actions)
{
var actionWithNestedActions = action as SuggestedActionWithNestedActions;
// Only inline if the underlying code action allows it.
if (actionWithNestedActions?.CodeAction.IsInlinable == true)
{
newActions.AddRange(actionWithNestedActions.NestedActionSet.Actions);
}
else
{
newActions.Add(action);
}
}
return new SuggestedActionSet(
actionSet.CategoryName,
newActions.ToImmutableAndFree(),
actionSet.Title,
actionSet.Priority,
actionSet.ApplicableToSpan);
}
private ImmutableArray<SuggestedActionSet> GetCodeFixes(
IDocumentSupportsFeatureService supportsFeatureService,
ISuggestedActionCategorySet requestedActionCategories,
Workspace workspace,
Document document,
SnapshotSpan range,
CancellationToken cancellationToken)
{
this.AssertIsForeground();
if (_owner._codeFixService != null &&
supportsFeatureService.SupportsCodeFixes(document) &&
requestedActionCategories.Contains(PredefinedSuggestedActionCategoryNames.CodeFix))
{
// We only include suppressions if light bulb is asking for everything.
// If the light bulb is only asking for code fixes, then we don't include suppressions.
var includeSuppressionFixes = requestedActionCategories.Contains(PredefinedSuggestedActionCategoryNames.Any);
var fixes = Task.Run(
() => _owner._codeFixService.GetFixesAsync(
document, range.Span.ToTextSpan(), includeSuppressionFixes, cancellationToken),
cancellationToken).WaitAndGetResult(cancellationToken);
var filteredFixes = FilterOnUIThread(fixes, workspace);
return OrganizeFixes(workspace, filteredFixes, includeSuppressionFixes);
}
return ImmutableArray<SuggestedActionSet>.Empty;
}
private ImmutableArray<CodeFixCollection> FilterOnUIThread(
ImmutableArray<CodeFixCollection> collections, Workspace workspace)
{
this.AssertIsForeground();
return collections.Select(c => FilterOnUIThread(c, workspace)).WhereNotNull().ToImmutableArray();
}
private CodeFixCollection FilterOnUIThread(
CodeFixCollection collection,
Workspace workspace)
{
this.AssertIsForeground();
var applicableFixes = collection.Fixes.WhereAsArray(f => IsApplicable(f.Action, workspace));
return applicableFixes.Length == 0
? null
: applicableFixes.Length == collection.Fixes.Length
? collection
: new CodeFixCollection(
collection.Provider, collection.TextSpan, applicableFixes,
collection.FixAllState, collection.SupportedScopes, collection.FirstDiagnostic);
}
private bool IsApplicable(CodeAction action, Workspace workspace)
{
if (!action.PerformFinalApplicabilityCheck)
{
// If we don't even need to perform the final applicability check,
// then the code action is applicable.
return true;
}
// Otherwise, defer to the action to make the decision.
this.AssertIsForeground();
return action.IsApplicable(workspace);
}
private ImmutableArray<CodeRefactoring> FilterOnUIThread(ImmutableArray<CodeRefactoring> refactorings, Workspace workspace)
{
return refactorings.Select(r => FilterOnUIThread(r, workspace)).WhereNotNull().ToImmutableArray();
}
private CodeRefactoring FilterOnUIThread(CodeRefactoring refactoring, Workspace workspace)
{
var actions = refactoring.Actions.WhereAsArray(a => IsApplicable(a, workspace));
return actions.Length == 0
? null
: actions.Length == refactoring.Actions.Length
? refactoring
: new CodeRefactoring(refactoring.Provider, actions);
}
/// <summary>
/// Arrange fixes into groups based on the issue (diagnostic being fixed) and prioritize these groups.
/// </summary>
private ImmutableArray<SuggestedActionSet> OrganizeFixes(
Workspace workspace, ImmutableArray<CodeFixCollection> fixCollections,
bool includeSuppressionFixes)
{
var map = ImmutableDictionary.CreateBuilder<CodeFixGroupKey, IList<SuggestedAction>>();
var order = ArrayBuilder<CodeFixGroupKey>.GetInstance();
// First group fixes by diagnostic and priority.
GroupFixes(workspace, fixCollections, map, order, includeSuppressionFixes);
// Then prioritize between the groups.
return PrioritizeFixGroups(map.ToImmutable(), order.ToImmutableAndFree());
}
/// <summary>
/// Groups fixes by the diagnostic being addressed by each fix.
/// </summary>
private void GroupFixes(
Workspace workspace,
ImmutableArray<CodeFixCollection> fixCollections,
IDictionary<CodeFixGroupKey, IList<SuggestedAction>> map,
ArrayBuilder<CodeFixGroupKey> order,
bool includeSuppressionFixes)
{
foreach (var fixCollection in fixCollections)
{
ProcessFixCollection(
workspace, map, order, includeSuppressionFixes, fixCollection);
}
}
private void ProcessFixCollection(
Workspace workspace,
IDictionary<CodeFixGroupKey, IList<SuggestedAction>> map,
ArrayBuilder<CodeFixGroupKey> order,
bool includeSuppressionFixes,
CodeFixCollection fixCollection)
{
var fixes = fixCollection.Fixes;
var fixCount = fixes.Length;
SuggestedActionSet getFixAllSuggestedActionSet(CodeAction codeAction) => GetFixAllSuggestedActionSet(
codeAction, fixCount, fixCollection.FixAllState,
fixCollection.SupportedScopes, fixCollection.FirstDiagnostic,
workspace);
var nonSupressionCodeFixes = fixes.WhereAsArray(f => !(f.Action is TopLevelSuppressionCodeAction));
var supressionCodeFixes = fixes.WhereAsArray(f => f.Action is TopLevelSuppressionCodeAction);
AddCodeActions(workspace, map, order, fixCollection,
getFixAllSuggestedActionSet, nonSupressionCodeFixes);
// Add suppression fixes to the end of a given SuggestedActionSet so that they
// always show up last in a group.
if (includeSuppressionFixes)
{
AddCodeActions(workspace, map, order, fixCollection,
getFixAllSuggestedActionSet, supressionCodeFixes);
}
}
private void AddCodeActions(
Workspace workspace, IDictionary<CodeFixGroupKey, IList<SuggestedAction>> map,
ArrayBuilder<CodeFixGroupKey> order, CodeFixCollection fixCollection,
Func<CodeAction, SuggestedActionSet> getFixAllSuggestedActionSet,
ImmutableArray<CodeFix> codeFixes)
{
foreach (var fix in codeFixes)
{
SuggestedAction suggestedAction;
if (fix.Action.NestedCodeActions.Length > 0)
{
var nestedActions = fix.Action.NestedCodeActions.SelectAsArray(
nestedAction => new CodeFixSuggestedAction(
ThreadingContext,
_owner, workspace, _subjectBuffer, fix, fixCollection.Provider,
nestedAction, getFixAllSuggestedActionSet(nestedAction)));
var set = new SuggestedActionSet(categoryName: null,
actions: nestedActions, priority: GetSuggestedActionSetPriority(fix.Action.Priority),
applicableToSpan: fix.PrimaryDiagnostic.Location.SourceSpan.ToSpan());
suggestedAction = new SuggestedActionWithNestedActions(
ThreadingContext,
_owner, workspace, _subjectBuffer,
fixCollection.Provider, fix.Action, set);
}
else
{
suggestedAction = new CodeFixSuggestedAction(
ThreadingContext,
_owner, workspace, _subjectBuffer, fix, fixCollection.Provider,
fix.Action, getFixAllSuggestedActionSet(fix.Action));
}
AddFix(fix, suggestedAction, map, order);
}
}
private static void AddFix(
CodeFix fix, SuggestedAction suggestedAction,
IDictionary<CodeFixGroupKey, IList<SuggestedAction>> map,
ArrayBuilder<CodeFixGroupKey> order)
{
var diag = fix.GetPrimaryDiagnosticData();
var groupKey = new CodeFixGroupKey(diag, fix.Action.Priority);
if (!map.ContainsKey(groupKey))
{
order.Add(groupKey);
map[groupKey] = ImmutableArray.CreateBuilder<SuggestedAction>();
}
map[groupKey].Add(suggestedAction);
}
/// <summary>
/// If the provided fix all context is non-null and the context's code action Id matches the given code action's Id then,
/// returns the set of fix all occurrences actions associated with the code action.
/// </summary>
internal SuggestedActionSet GetFixAllSuggestedActionSet(
CodeAction action,
int actionCount,
FixAllState fixAllState,
ImmutableArray<FixAllScope> supportedScopes,
Diagnostic firstDiagnostic,
Workspace workspace)
{
if (fixAllState == null)
{
return null;
}
if (actionCount > 1 && action.EquivalenceKey == null)
{
return null;
}
var fixAllSuggestedActions = ArrayBuilder<FixAllSuggestedAction>.GetInstance();
foreach (var scope in supportedScopes)
{
var fixAllStateForScope = fixAllState.WithScopeAndEquivalenceKey(scope, action.EquivalenceKey);
var fixAllSuggestedAction = new FixAllSuggestedAction(
ThreadingContext,
_owner, workspace, _subjectBuffer, fixAllStateForScope,
firstDiagnostic, action);
fixAllSuggestedActions.Add(fixAllSuggestedAction);
}
return new SuggestedActionSet(
categoryName: null,
actions: fixAllSuggestedActions.ToImmutableAndFree(),
title: EditorFeaturesResources.Fix_all_occurrences_in);
}
/// <summary>
/// Return prioritized set of fix groups such that fix group for suppression always show up at the bottom of the list.
/// </summary>
/// <remarks>
/// Fix groups are returned in priority order determined based on <see cref="ExtensionOrderAttribute"/>.
/// Priority for all <see cref="SuggestedActionSet"/>s containing fixes is set to <see cref="SuggestedActionSetPriority.Medium"/> by default.
/// The only exception is the case where a <see cref="SuggestedActionSet"/> only contains suppression fixes -
/// the priority of such <see cref="SuggestedActionSet"/>s is set to <see cref="SuggestedActionSetPriority.None"/> so that suppression fixes
/// always show up last after all other fixes (and refactorings) for the selected line of code.
/// </remarks>
private static ImmutableArray<SuggestedActionSet> PrioritizeFixGroups(
ImmutableDictionary<CodeFixGroupKey, IList<SuggestedAction>> map, ImmutableArray<CodeFixGroupKey> order)
{
var sets = ArrayBuilder<SuggestedActionSet>.GetInstance();
foreach (var diag in order)
{
var actions = map[diag];
foreach (var group in actions.GroupBy(a => a.Priority))
{
var priority = GetSuggestedActionSetPriority(group.Key);
// diagnostic from things like build shouldn't reach here since we don't support LB for those diagnostics
Debug.Assert(diag.Item1.HasTextSpan);
var category = GetFixCategory(diag.Item1.Severity);
sets.Add(new SuggestedActionSet(category, group, priority: priority, applicableToSpan: diag.Item1.TextSpan.ToSpan()));
}
}
return sets.ToImmutableAndFree();
}
private static string GetFixCategory(DiagnosticSeverity severity)
{
switch (severity)
{
case DiagnosticSeverity.Hidden:
case DiagnosticSeverity.Info:
case DiagnosticSeverity.Warning:
return PredefinedSuggestedActionCategoryNames.CodeFix;
case DiagnosticSeverity.Error:
return PredefinedSuggestedActionCategoryNames.ErrorFix;
default:
throw ExceptionUtilities.Unreachable;
};
}
private static SuggestedActionSetPriority GetSuggestedActionSetPriority(CodeActionPriority key)
{
switch (key)
{
case CodeActionPriority.None: return SuggestedActionSetPriority.None;
case CodeActionPriority.Low: return SuggestedActionSetPriority.Low;
case CodeActionPriority.Medium: return SuggestedActionSetPriority.Medium;
case CodeActionPriority.High: return SuggestedActionSetPriority.High;
default:
throw new InvalidOperationException();
}
}
private ImmutableArray<SuggestedActionSet> GetRefactorings(
IDocumentSupportsFeatureService supportsFeatureService,
ISuggestedActionCategorySet requestedActionCategories,
Workspace workspace,
Document document,
TextSpan? selectionOpt,
CancellationToken cancellationToken)
{
this.AssertIsForeground();
if (!selectionOpt.HasValue)
{
// this is here to fail test and see why it is failed.
Trace.WriteLine("given range is not current");
return ImmutableArray<SuggestedActionSet>.Empty;
}
var selection = selectionOpt.Value;
if (workspace.Options.GetOption(EditorComponentOnOffOptions.CodeRefactorings) &&
_owner._codeRefactoringService != null &&
supportsFeatureService.SupportsRefactorings(document) &&
requestedActionCategories.Contains(PredefinedSuggestedActionCategoryNames.Refactoring))
{
// It may seem strange that we kick off a task, but then immediately 'Wait' on
// it. However, it's deliberate. We want to make sure that the code runs on
// the background so that no one takes an accidentally dependency on running on
// the UI thread.
var refactorings = Task.Run(
() => _owner._codeRefactoringService.GetRefactoringsAsync(
document, selection, cancellationToken),
cancellationToken).WaitAndGetResult(cancellationToken);
var filteredRefactorings = FilterOnUIThread(refactorings, workspace);
return filteredRefactorings.SelectAsArray(
r => OrganizeRefactorings(workspace, r, selection.ToSpan()));
}
return ImmutableArray<SuggestedActionSet>.Empty;
}
/// <summary>
/// Arrange refactorings into groups.
/// </summary>
/// <remarks>
/// Refactorings are returned in priority order determined based on <see cref="ExtensionOrderAttribute"/>.
/// Priority for all <see cref="SuggestedActionSet"/>s containing refactorings is set to <see cref="SuggestedActionSetPriority.Low"/>
/// and should show up after fixes but before suppression fixes in the light bulb menu.
/// </remarks>
private SuggestedActionSet OrganizeRefactorings(
Workspace workspace, CodeRefactoring refactoring, Span applicableSpan)
{
var refactoringSuggestedActions = ArrayBuilder<SuggestedAction>.GetInstance();
foreach (var action in refactoring.Actions)
{
if (action.NestedCodeActions.Length > 0)
{
var nestedActions = action.NestedCodeActions.SelectAsArray(
na => new CodeRefactoringSuggestedAction(
ThreadingContext,
_owner, workspace, _subjectBuffer, refactoring.Provider, na));
var set = new SuggestedActionSet(categoryName: null,
actions: nestedActions, priority: GetSuggestedActionSetPriority(action.Priority), applicableToSpan: applicableSpan);
refactoringSuggestedActions.Add(new SuggestedActionWithNestedActions(
ThreadingContext,
_owner, workspace, _subjectBuffer,
refactoring.Provider, action, set));
}
else
{
refactoringSuggestedActions.Add(new CodeRefactoringSuggestedAction(
ThreadingContext,
_owner, workspace, _subjectBuffer, refactoring.Provider, action));
}
}
var actions = refactoringSuggestedActions.ToImmutableAndFree();
// An action set gets the the same priority as the highest priority
// action within in.
return new SuggestedActionSet(
PredefinedSuggestedActionCategoryNames.Refactoring,
actions: actions,
priority: GetSuggestedActionSetPriority(actions.Max(a => a.Priority)),
applicableToSpan: applicableSpan);
}
public Task<bool> HasSuggestedActionsAsync(
ISuggestedActionCategorySet requestedActionCategories,
SnapshotSpan range,
CancellationToken cancellationToken)
{
// We implement GetSuggestedActionCategoriesAsync so this should not be called
throw new NotImplementedException($"We implement {nameof(GetSuggestedActionCategoriesAsync)}. This should not be called.");
}
private async Task<TextSpan?> GetSpanAsync(SnapshotSpan range, CancellationToken cancellationToken)
{
// First, ensure that the snapshot we're being asked about is for an actual
// roslyn document. This can fail, for example, in projection scenarios where
// we are called with a range snapshot that refers to the projection buffer
// and not the actual roslyn code that is being projected into it.
var document = range.Snapshot.GetOpenDocumentInCurrentContextWithChanges();
if (document == null)
{
return null;
}
// Also make sure the range is from the same buffer that this source was created for
Contract.ThrowIfFalse(
range.Snapshot.TextBuffer.Equals(_subjectBuffer),
$"Invalid text buffer passed to {nameof(HasSuggestedActionsAsync)}");
// Next, before we do any async work, acquire the user's selection, directly grabbing
// it from the UI thread if htat's what we're on. That way we don't have any reentrancy
// blocking concerns if VS wants to block on this call (for example, if the user
// explicitly invokes the 'show smart tag' command).
//
// This work must happen on the UI thread as it needs to access the _textView's mutable
// state.
//
// Note: we may be called in one of two VS scenarios:
// 1) User has moved caret to a new line. In this case VS will call into us in the
// bg to see if we have any suggested actions for this line. In order to figure
// this out, we need to see what selectoin the user has (for refactorings), which
// necessitates going back to the fg.
//
// 2) User moves to a line and immediately hits ctrl-dot. In this case, on the UI
// thread VS will kick us off and then immediately block to get the results so
// that they can expand the lightbulb. In this case we cannot do BG work first,
// then call back into the UI thread to try to get the user selection. This will
// deadlock as the UI thread is blocked on us.
//
// There are two solution to '2'. Either introduce reentrancy (which we really don't
// like to do), or just ensure that we acquire and get the users selection up front.
// This means that when we're called from the UI therad, we never try to go back to the
// UI thread.
TextSpan? selection = null;
if (IsForeground())
{
selection = TryGetCodeRefactoringSelection(range);
}
else
{
await InvokeBelowInputPriorityAsync(() =>
{
// Make sure we were not disposed between kicking off this work and getting
// to this point.
if (IsDisposed)
{
return;
}
selection = TryGetCodeRefactoringSelection(range);
}, cancellationToken).ConfigureAwait(false);
}
return selection;
}
private async Task<string> GetFixLevelAsync(
SuggestedActionsSourceProvider provider,
Document document,
SnapshotSpan range,
CancellationToken cancellationToken)
{
var workspace = document.Project.Solution.Workspace;
var supportsFeatureService = workspace.Services.GetService<IDocumentSupportsFeatureService>();
if (provider._codeFixService != null &&
supportsFeatureService.SupportsCodeFixes(document))
{
var result = await provider._codeFixService.GetMostSevereFixableDiagnosticAsync(
document, range.Span.ToTextSpan(), cancellationToken).ConfigureAwait(false);
if (result.HasFix)
{
Logger.Log(FunctionId.SuggestedActions_HasSuggestedActionsAsync);
return GetFixCategory(result.Diagnostic.Severity);
}
if (result.PartialResult)
{
// reset solution version number so that we can raise suggested action changed event
Volatile.Write(ref _lastSolutionVersionReported, InvalidSolutionVersion);
return null;
}
}
return null;
}
private async Task<string> TryGetRefactoringSuggestedActionCategoryAsync(
SuggestedActionsSourceProvider provider,
Document document,
TextSpan? selection,
CancellationToken cancellationToken)
{
if (!selection.HasValue)
{
// this is here to fail test and see why it is failed.
Trace.WriteLine("given range is not current");
return null;
}
var workspace = document.Project.Solution.Workspace;
var supportsFeatureService = workspace.Services.GetService<IDocumentSupportsFeatureService>();
if (document.Project.Solution.Options.GetOption(EditorComponentOnOffOptions.CodeRefactorings) &&
provider._codeRefactoringService != null &&
supportsFeatureService.SupportsRefactorings(document))
{
if (await provider._codeRefactoringService.HasRefactoringsAsync(
document, selection.Value, cancellationToken).ConfigureAwait(false))
{
return PredefinedSuggestedActionCategoryNames.Refactoring;
}
}
return null;
}
private TextSpan? TryGetCodeRefactoringSelection(SnapshotSpan range)
{
this.AssertIsForeground();
Debug.Assert(!this.IsDisposed);
var selectedSpans = _textView.Selection.SelectedSpans
.SelectMany(ss => _textView.BufferGraph.MapDownToBuffer(ss, SpanTrackingMode.EdgeExclusive, _subjectBuffer))
.Where(ss => !_textView.IsReadOnlyOnSurfaceBuffer(ss))
.ToList();
// We only support refactorings when there is a single selection in the document.
if (selectedSpans.Count != 1)
{
return null;
}
var translatedSpan = selectedSpans[0].TranslateTo(range.Snapshot, SpanTrackingMode.EdgeInclusive);
// We only support refactorings when selected span intersects with the span that the light bulb is asking for.
if (!translatedSpan.IntersectsWith(range))
{
return null;
}
return translatedSpan.Span.ToTextSpan();
}
private void OnTextViewClosed(object sender, EventArgs e)
{
Dispose();
}
private void OnWorkspaceChanged(object sender, EventArgs e)
{
// REVIEW: this event should give both old and new workspace as argument so that
// one doesn't need to hold onto workspace in field.
// remove existing event registration
if (_workspace != null)
{
_workspace.DocumentActiveContextChanged -= OnActiveContextChanged;
}
// REVIEW: why one need to get new workspace from registration? why not just pass in the new workspace?
// add new event registration
_workspace = _registration.Workspace;
if (_workspace != null)
{
_workspace.DocumentActiveContextChanged += OnActiveContextChanged;
}
}
private void OnActiveContextChanged(object sender, DocumentActiveContextChangedEventArgs e)
{
// REVIEW: it would be nice for changed event to pass in both old and new document.
OnSuggestedActionsChanged(e.Solution.Workspace, e.NewActiveContextDocumentId, e.Solution.WorkspaceVersion);
}
private void OnDiagnosticsUpdated(object sender, DiagnosticsUpdatedArgs e)
{
// document removed case. no reason to raise event
if (e.Solution == null)
{
return;
}
OnSuggestedActionsChanged(e.Workspace, e.DocumentId, e.Solution.WorkspaceVersion);
}
private void OnSuggestedActionsChanged(Workspace currentWorkspace, DocumentId currentDocumentId, int solutionVersion, DiagnosticsUpdatedArgs args = null)
{
// Explicitly hold onto the _subjectBuffer field in a local and use this local in this function to avoid crashes
// if this field happens to be cleared by Dispose() below. This is required since this code path involves code
// that can run on background thread.
var buffer = _subjectBuffer;
if (buffer == null)
{
return;
}
var workspace = buffer.GetWorkspace();
// workspace is not ready, nothing to do.
if (workspace == null || workspace != currentWorkspace)
{
return;
}
if (currentDocumentId != workspace.GetDocumentIdInCurrentContext(buffer.AsTextContainer()) ||
solutionVersion == Volatile.Read(ref _lastSolutionVersionReported))
{
return;
}
this.SuggestedActionsChanged?.Invoke(this, EventArgs.Empty);
Volatile.Write(ref _lastSolutionVersionReported, solutionVersion);
}
public async Task<ISuggestedActionCategorySet> GetSuggestedActionCategoriesAsync(ISuggestedActionCategorySet requestedActionCategories, SnapshotSpan range, CancellationToken cancellationToken)
{
var provider = _owner;
using (var asyncToken = _owner.OperationListener.BeginAsyncOperation(nameof(GetSuggestedActionCategoriesAsync)))
{
var document = range.Snapshot.GetOpenDocumentInCurrentContextWithChanges();
if (document == null)
{
return null;
}
using (var linkedTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken))
{
var linkedToken = linkedTokenSource.Token;
var errorTask = Task.Run(
() => GetFixLevelAsync(provider, document, range, linkedToken), linkedToken);
var selection = await GetSpanAsync(range, linkedToken).ConfigureAwait(false);
Task<string> refactoringTask = Task.FromResult((string)null);
if (selection != null && requestedActionCategories.Contains(PredefinedSuggestedActionCategoryNames.Refactoring))
{
refactoringTask = Task.Run(
() => TryGetRefactoringSuggestedActionCategoryAsync(provider, document, selection, linkedToken), linkedToken);
}
// If we happen to get the result of the error task before the refactoring task,
// and that result is non-null, we can just cancel the refactoring task.
var result = await errorTask.ConfigureAwait(false) ?? await refactoringTask.ConfigureAwait(false);
linkedTokenSource.Cancel();
return result == null
? null
: _suggestedActionCategoryRegistry.CreateSuggestedActionCategorySet(result);
}
}
}
}
}
}