Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add UI for Value Tracking #51974

Merged
8 commits merged into from
Mar 19, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -178,5 +178,10 @@ internal static class PredefinedCommandHandlerNames
/// Command handler name for Edit and Continue file save handler.
/// </summary>
public const string EditAndContinueFileSave = "Edit and Continue Save File Handler";

/// <summary>
/// Command handler name for showing the Value Tracking tool window.
/// </summary>
public const string ShowValueTracking = "Show Value Tracking";
}
}
77 changes: 72 additions & 5 deletions src/EditorFeatures/Core/ValueTracking/ValueTrackedItem.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,86 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Classification;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;

namespace Microsoft.CodeAnalysis.ValueTracking
{
internal class ValueTrackedItem
{
public Location Location { get; }
public ISymbol Symbol { get; }
public ValueTrackedItem? Parent { get; }

public Document Document { get; }
public TextSpan Span { get; }
public ImmutableArray<ClassifiedSpan> ClassifiedSpans { get; }
public SourceText SourceText { get; }
public LineSpan LineSpan { get; }

public ValueTrackedItem(
Location location,
ISymbol symbol)
private ValueTrackedItem(
ISymbol symbol,
SourceText sourceText,
ImmutableArray<ClassifiedSpan> classifiedSpans,
TextSpan textSpan,
Document document,
LineSpan lineSpan,
ValueTrackedItem? parent = null)
{
Location = location;
Symbol = symbol;
Parent = parent;

Span = textSpan;
ClassifiedSpans = classifiedSpans;
SourceText = sourceText;
LineSpan = lineSpan;
Document = document;
}

public static async Task<ValueTrackedItem?> TryCreateAsync(Solution solution, Location location, ISymbol symbol, ValueTrackedItem? parent = null, CancellationToken cancellationToken = default)
{
Contract.ThrowIfNull(location.SourceTree);

var document = solution.GetRequiredDocument(location.SourceTree);
var excerptService = document.Services.GetService<IDocumentExcerptService>();
SourceText? sourceText = null;
ImmutableArray<ClassifiedSpan> classifiedSpans = default;

if (excerptService != null)
{
var result = await excerptService.TryExcerptAsync(document, location.SourceSpan, ExcerptMode.SingleLine, cancellationToken).ConfigureAwait(false);
if (result.HasValue)
{
var value = result.Value;
sourceText = value.Content;
}
}

if (sourceText is null)
{
var documentSpan = await ClassifiedSpansAndHighlightSpanFactory.GetClassifiedDocumentSpanAsync(document, location.SourceSpan, cancellationToken).ConfigureAwait(false);
var classificationResult = await ClassifiedSpansAndHighlightSpanFactory.ClassifyAsync(documentSpan, cancellationToken).ConfigureAwait(false);
classifiedSpans = classificationResult.ClassifiedSpans;
sourceText = await location.SourceTree.GetTextAsync(cancellationToken).ConfigureAwait(false);
}

sourceText.GetLineAndOffset(location.SourceSpan.Start, out var lineStart, out var _);
sourceText.GetLineAndOffset(location.SourceSpan.End, out var lineEnd, out var _);
var lineSpan = LineSpan.FromBounds(lineStart, lineEnd);

return new ValueTrackedItem(
symbol,
sourceText,
classifiedSpans,
location.SourceSpan,
document,
lineSpan,
parent: parent);
}
}
}
19 changes: 13 additions & 6 deletions src/EditorFeatures/Core/ValueTracking/ValueTrackingService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,11 @@ or ILocalSymbol
foreach (var syntaxRef in symbol.DeclaringSyntaxReferences)
{
var location = Location.Create(syntaxRef.SyntaxTree, syntaxRef.Span);
progressCollector.Report(new ValueTrackedItem(location, symbol));
var item = await ValueTrackedItem.TryCreateAsync(solution, location, symbol, parent: null, cancellationToken).ConfigureAwait(false);
if (item is not null)
{
progressCollector.Report(item);
}
}

var findReferenceProgressCollector = new FindReferencesProgress(progressCollector);
Expand All @@ -75,7 +79,7 @@ public Task TrackValueSourceAsync(
ValueTrackingProgressCollector progressCollector,
CancellationToken cancellationToken)
{
throw new NotImplementedException();
return Task.CompletedTask;
}

private class FindReferencesProgress : IStreamingFindReferencesProgress, IStreamingProgressTracker
Expand All @@ -100,14 +104,17 @@ public FindReferencesProgress(ValueTrackingProgressCollector valueTrackingProgre

public ValueTask OnFindInDocumentStartedAsync(Document document) => new();

public ValueTask OnReferenceFoundAsync(ISymbol symbol, ReferenceLocation location)
public async ValueTask OnReferenceFoundAsync(ISymbol symbol, ReferenceLocation location)
{
if (location.IsWrittenTo)
{
_valueTrackingProgressCollector.Report(new ValueTrackedItem(location.Location, symbol));
var solution = location.Document.Project.Solution;
var item = await ValueTrackedItem.TryCreateAsync(solution, location.Location, symbol, parent: null, CancellationToken.None).ConfigureAwait(false);
if (item is not null)
{
_valueTrackingProgressCollector.Report(item);
}
}

return new();
}

public ValueTask OnStartedAsync() => new();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,7 @@ internal static async Task<ISymbol> GetSelectedSymbolAsync(TextSpan textSpan, Do

internal static void ValidateItem(ValueTrackedItem item, int line)
{
var lineSpan = item.Location.GetLineSpan();
Assert.Equal(line, lineSpan.StartLinePosition.Line);
Assert.Equal(line, item.LineSpan.Start);
}
}
}
19 changes: 19 additions & 0 deletions src/VisualStudio/Core/Def/Commands.vsct
Original file line number Diff line number Diff line change
Expand Up @@ -411,6 +411,19 @@
<LocCanonicalName>RemoveUnusedReferences</LocCanonicalName>
</Strings>
</Button>

<Button guid="guidRoslynGrpId" id="cmdidshowValueTracking" priority="0x0203" type="Button">
<Parent guid="guidSHLMainMenu" id="IDG_VS_EDIT_GOTO"/>
<CommandFlag>DynamicVisibility</CommandFlag>
<CommandFlag>DefaultInvisible</CommandFlag>
<CommandFlag>CommandWellOnly</CommandFlag>
<Strings>
<ButtonText>Track Value Source</ButtonText>
<CommandName>ShowValueTrackingCommandName</CommandName>
<CanonicalName>ShowValueTracking</CanonicalName>
<LocCanonicalName>ViewEditorConfigSettings</LocCanonicalName>
</Strings>
</Button>
</Buttons>

<Menus>
Expand Down Expand Up @@ -516,6 +529,10 @@
<CommandPlacement guid="guidRoslynGrpId" id="cmdidRemoveUnusedReferences" priority="0xF200">
<Parent guid="guidSHLMainMenu" id="IDG_VS_CTXT_REFROOT_ADD" />
</CommandPlacement>

<CommandPlacement guid="guidRoslynGrpId" id="cmdidshowValueTracking" priority="0x0203">
<Parent guid="guidSHLMainMenu" id="IDG_VS_CODEWIN_NAVIGATETOLOCATION"/>
</CommandPlacement>
</CommandPlacements>

<KeyBindings>
Expand Down Expand Up @@ -601,6 +618,8 @@
<IDSymbol name="cmdidRunCodeAnalysisForProject" value="0x0201" />

<IDSymbol name="cmdidRemoveUnusedReferences" value="0x202" />

<IDSymbol name="cmdidshowValueTracking" value="0x0203" />
</GuidSymbol>

<GuidSymbol name="guidCSharpInteractiveCommandSet" value="{1492db0a-85a2-4e43-bf0d-ce55b89a8cc6}">
Expand Down
3 changes: 3 additions & 0 deletions src/VisualStudio/Core/Def/Guids.cs
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,9 @@ internal static class Guids
public static readonly Guid RoslynCommandSetId = new(RoslynCommandSetIdString);
public static readonly Guid RoslynGroupId = new(RoslynGroupIdString);

public const string ValueTrackingToolWindowIdString = "60a19d42-2dd7-43f3-be90-c7a9cb7d28f4";
public static readonly Guid ValueTrackingToolWindowId = new(ValueTrackingToolWindowIdString);

// TODO: Remove pending https://github.com/dotnet/roslyn/issues/8927 .
// Interactive guids
public const string InteractiveCommandSetIdString = "00B8868B-F9F5-4970-A048-410B05508506";
Expand Down
1 change: 1 addition & 0 deletions src/VisualStudio/Core/Def/ID.RoslynCommands.cs
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ public static class RoslynCommands

public const int RunCodeAnalysisForProject = 0x0201;
public const int RemoveUnusedReferences = 0x0202;
public const int GoToValueTrackingWindow = 0x0203;
}
}
}
5 changes: 5 additions & 0 deletions src/VisualStudio/Core/Def/Implementation/CommandBindings.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
using Microsoft.CodeAnalysis.Editor.Commanding.Commands;
using Microsoft.VisualStudio.Editor.Commanding;
using Microsoft.VisualStudio.LanguageServices;
using Microsoft.VisualStudio.LanguageServices.ValueTracking;

namespace Microsoft.VisualStudio.Editor.Implementation
{
Expand All @@ -28,5 +29,9 @@ internal sealed class CommandBindings
[Export]
[CommandBinding(Guids.CSharpGroupIdString, ID.CSharpCommands.ContextOrganizeRemoveAndSort, typeof(SortAndRemoveUnnecessaryImportsCommandArgs))]
internal CommandBindingDefinition contextOrganizeRemoveAndSortCommandBinding;

[Export]
[CommandBinding(Guids.RoslynGroupIdString, ID.RoslynCommands.GoToValueTrackingWindow, typeof(ValueTrackingEditorCommandArgs))]
internal CommandBindingDefinition gotoDataFlowToolCommandBinding;
}
}
6 changes: 6 additions & 0 deletions src/VisualStudio/Core/Def/PackageRegistration.pkgdef
Original file line number Diff line number Diff line change
Expand Up @@ -24,3 +24,9 @@
"Value"=dword:00000000
"Title"="Enable experimental C#/VB LSP completion experience"
"PreviewPaneChannels"="IntPreview,int.main"

// The option page configuration is duplicated in RoslynPackage
// [ProvideToolWindow(typeof(ValueTracking.ValueTrackingToolWindow))]
[$RootKey$\ToolWindows\{60a19d42-2dd7-43f3-be90-c7a9cb7d28f4}]
"Name"="Microsoft.VisualStudio.LanguageServices.ValueTracking.ValueTrackingToolWindow"
@="{6cf2e545-6109-4730-8883-cf43d7aec3e1}"
21 changes: 16 additions & 5 deletions src/VisualStudio/Core/Def/RoslynPackage.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,28 +19,23 @@
using Microsoft.CodeAnalysis.Logging;
using Microsoft.CodeAnalysis.Notification;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Remote;
using Microsoft.CodeAnalysis.Telemetry;
using Microsoft.CodeAnalysis.Versions;
using Microsoft.VisualStudio.ComponentModelHost;
using Microsoft.VisualStudio.LanguageServices.ColorSchemes;
using Microsoft.VisualStudio.LanguageServices.Experimentation;
using Microsoft.VisualStudio.LanguageServices.Implementation;
using Microsoft.VisualStudio.LanguageServices.Implementation.DesignerAttribute;
using Microsoft.VisualStudio.LanguageServices.Implementation.Diagnostics;
using Microsoft.VisualStudio.LanguageServices.Implementation.Interactive;
using Microsoft.VisualStudio.LanguageServices.Implementation.LanguageService;
using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem;
using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem.RuleSets;
using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectTelemetry;
using Microsoft.VisualStudio.LanguageServices.Implementation.TableDataSource;
using Microsoft.VisualStudio.LanguageServices.Implementation.TodoComments;
using Microsoft.VisualStudio.LanguageServices.Implementation.UnusedReferences;
using Microsoft.VisualStudio.LanguageServices.Telemetry;
using Microsoft.VisualStudio.PlatformUI;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.Shell.ServiceBroker;
using Microsoft.VisualStudio.TaskStatusCenter;
using Microsoft.VisualStudio.Telemetry;
using Microsoft.VisualStudio.TextManager.Interop;
Expand All @@ -51,6 +46,9 @@
namespace Microsoft.VisualStudio.LanguageServices.Setup
{
[Guid(Guids.RoslynPackageIdString)]

// The option page configuration is duplicated in PackageRegistration.pkgdef
[ProvideToolWindow(typeof(ValueTracking.ValueTrackingToolWindow))]
internal sealed class RoslynPackage : AbstractPackage
{
// The randomly-generated key name is used for serializing the ILSpy decompiler EULA preference to the .SUO
Expand Down Expand Up @@ -188,6 +186,19 @@ protected override async Task LoadComponentsAsync(CancellationToken cancellation
LoadComponentsBackgroundAsync(cancellationToken).Forget();
}

// Overrides for VSSDK003 fix
// See https://github.com/Microsoft/VSSDK-Analyzers/blob/main/doc/VSSDK003.md
public override IVsAsyncToolWindowFactory GetAsyncToolWindowFactory(Guid toolWindowType)
=> toolWindowType == typeof(ValueTracking.ValueTrackingToolWindow).GUID
? this
: base.GetAsyncToolWindowFactory(toolWindowType);

protected override string GetToolWindowTitle(Type toolWindowType, int id)
=> base.GetToolWindowTitle(toolWindowType, id);

protected override Task<object?> InitializeToolWindowAsync(Type toolWindowType, int id, CancellationToken cancellationToken)
=> Task.FromResult((object?)null);

private async Task LoadComponentsBackgroundAsync(CancellationToken cancellationToken)
{
await TaskScheduler.Default;
Expand Down
37 changes: 37 additions & 0 deletions src/VisualStudio/Core/Def/ValueTracking/BindableTextBlock.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using Roslyn.Utilities;

namespace Microsoft.VisualStudio.LanguageServices.ValueTracking
{
internal class BindableTextBlock : TextBlock
{
public IList<Inline> InlineCollection
{
get { return (ObservableCollection<Inline>)GetValue(InlineListProperty); }
set { SetValue(InlineListProperty, value); }
}

public static readonly DependencyProperty InlineListProperty =
DependencyProperty.Register(nameof(InlineCollection), typeof(IList<Inline>), typeof(BindableTextBlock), new UIPropertyMetadata(null, OnPropertyChanged));

private static void OnPropertyChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
var textBlock = (BindableTextBlock)sender;
var newList = (IList<Inline>)e.NewValue;

textBlock.Inlines.Clear();
foreach (var inline in newList)
{
textBlock.Inlines.Add(inline);
}
}
}
}
15 changes: 15 additions & 0 deletions src/VisualStudio/Core/Def/ValueTracking/EmptyTreeViewItem.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
// 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.

namespace Microsoft.VisualStudio.LanguageServices.ValueTracking
{
internal class EmptyTreeViewItem : TreeViewItemBase
{
public static EmptyTreeViewItem Instance { get; } = new();

private EmptyTreeViewItem()
{
}
}
}
43 changes: 43 additions & 0 deletions src/VisualStudio/Core/Def/ValueTracking/TreeViewItemBase.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.CompilerServices;

namespace Microsoft.VisualStudio.LanguageServices.ValueTracking
{
internal class TreeViewItemBase : INotifyPropertyChanged
{
private bool _isExpanded = false;
public bool IsNodeExpanded
{
get => _isExpanded;
set => SetProperty(ref _isExpanded, value);
}

private bool _isSelected = false;
public bool IsNodeSelected
{
get => _isSelected;
set => SetProperty(ref _isSelected, value);
}

public event PropertyChangedEventHandler? PropertyChanged;

protected void SetProperty<T>(ref T field, T value, [CallerMemberName] string name = "")
{
if (EqualityComparer<T>.Default.Equals(field, value))
{
return;
}

field = value;
NotifyPropertyChanged(name);
}

protected void NotifyPropertyChanged(string name)
=> PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}
}
Loading